@syntrologie/runtime-sdk 2.4.0 → 2.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-VQHPYHLL.js → chunk-QGWATS3Z.js} +7 -5
- package/dist/chunk-QGWATS3Z.js.map +7 -0
- package/dist/hooks/useShadowCanvasConfig.d.ts +3 -1
- package/dist/index.js +1 -1
- package/dist/react.js +1 -1
- package/dist/smart-canvas.esm.js +3 -3
- package/dist/smart-canvas.esm.js.map +3 -3
- package/dist/smart-canvas.js +7 -5
- package/dist/smart-canvas.js.map +2 -2
- package/dist/smart-canvas.min.js +3 -3
- package/dist/smart-canvas.min.js.map +3 -3
- package/dist/version.d.ts +1 -1
- package/package.json +7 -7
- package/dist/chunk-VQHPYHLL.js.map +0 -7
package/dist/smart-canvas.min.js
CHANGED
|
@@ -110,7 +110,7 @@ Error generating stack: `+i.message+`
|
|
|
110
110
|
s.textContent = '.${e} { ${n} }';
|
|
111
111
|
document.head.appendChild(s);
|
|
112
112
|
document.documentElement.className += ' ${e}';
|
|
113
|
-
})();`}function ef(t,e,n="first-match"){for(let i of e){let r=t.getFeatureValue?.(i,null);if(!r||typeof r!="object")continue;let a=r,o=a.tiles&&a.tiles.length>0,s=a.actions&&a.actions.length>0;if(o||s)return{tiles:a.tiles??[],actions:a.actions??[],fetchedAt:a.fetchedAt??new Date().toISOString(),...a.schemaVersion&&{schemaVersion:a.schemaVersion},...a.configVersion&&{configVersion:a.configVersion},...a.canvasTitle&&{canvasTitle:a.canvasTitle},...a.theme&&{theme:a.theme},...a.launcher&&{launcher:a.launcher}}}return null}var Qm=!1;function DE(){if(typeof window>"u")return!1;try{return new URLSearchParams(window.location.search).get("syntro_debug")==="true"}catch{return!1}}function Jm(t){if(DE()){Qm=!0;return}Qm=t??!1}function sN(){return DE()?!0:Qm}function G(t,e,n){sN()&&(n!==void 0?console.log(`[${t}]`,e,n):console.log(`[${t}]`,e))}function cn(t,e,n){n!==void 0?console.warn(`[${t}]`,e,n):console.warn(`[${t}]`,e)}function tf(t,e,n){n!==void 0?console.error(`[${t}]`,e,n):console.error(`[${t}]`,e)}var nf="2.4.
|
|
113
|
+
})();`}function ef(t,e,n="first-match"){for(let i of e){let r=t.getFeatureValue?.(i,null);if(!r||typeof r!="object")continue;let a=r,o=a.tiles&&a.tiles.length>0,s=a.actions&&a.actions.length>0;if(o||s)return{tiles:a.tiles??[],actions:a.actions??[],fetchedAt:a.fetchedAt??new Date().toISOString(),...a.schemaVersion&&{schemaVersion:a.schemaVersion},...a.configVersion&&{configVersion:a.configVersion},...a.canvasTitle&&{canvasTitle:a.canvasTitle},...a.theme&&{theme:a.theme},...a.launcher&&{launcher:a.launcher}}}return null}var Qm=!1;function DE(){if(typeof window>"u")return!1;try{return new URLSearchParams(window.location.search).get("syntro_debug")==="true"}catch{return!1}}function Jm(t){if(DE()){Qm=!0;return}Qm=t??!1}function sN(){return DE()?!0:Qm}function G(t,e,n){sN()&&(n!==void 0?console.log(`[${t}]`,e,n):console.log(`[${t}]`,e))}function cn(t,e,n){n!==void 0?console.warn(`[${t}]`,e,n):console.warn(`[${t}]`,e)}function tf(t,e,n){n!==void 0?console.error(`[${t}]`,e,n):console.error(`[${t}]`,e)}var nf="2.4.1";var Bi="2.0";var lN=["api.syntrologie.com","cdn.syntrologie.com","localhost","127.0.0.1"];function cN(t){try{let e=new URL(t),n=/^(localhost|127\.0\.0\.1)$/.test(e.hostname);return e.protocol!=="https:"&&!n?(console.warn("[SmartCanvas] Config URI must use HTTPS:",t),!1):lN.some(r=>e.hostname===r)?!0:(console.warn("[SmartCanvas] Config URI host not in allowlist:",e.hostname),!1)}catch{return console.warn("[SmartCanvas] Invalid config URI:",t),!1}}function uN(t){if(typeof window>"u")return!1;try{return new URL(t).origin===window.location.origin}catch{return!1}}var LE="syntro_config_cache",dN=1440*60*1e3;function HE(){try{return typeof localStorage<"u"&&localStorage!==null}catch{return!1}}function fN(t,e){if(HE())try{let n={config:t,timestamp:Date.now(),sdkVersion:e};localStorage.setItem(LE,JSON.stringify(n))}catch{}}function pN(t){if(!HE())return null;try{let e=localStorage.getItem(LE);if(!e)return null;let n=JSON.parse(e);return!n.config||typeof n.timestamp!="number"||!n.sdkVersion||n.sdkVersion!==t||Date.now()-n.timestamp>dN?null:n.config}catch{return null}}var rf=({configUri:t,experiments:e,featureKey:n="smart-canvas-config-uri"})=>{if(t)return t;let i=e?.getFeatureValue?.(n,null);if(i)return i};function hN(t,e,n){if(e){let i=t.getFeatureValue?.(e,null);if(i&&typeof i=="object"){let r=i.variant_flags;if(r&&r.length>0)return r}}if(n&&t.getAllFeatures){let i=t.getAllFeatures();return Object.keys(i).filter(r=>r.startsWith(n))}return[]}var Oa=({configUri:t,experiments:e,featureKey:n,credentials:i,configFeatureKey:r="smart-canvas-config",manifestKey:a,variantFlagPrefix:o,sdkVersion:s})=>async()=>{if(e&&r){let u=e.getFeatureValue?.(r,null);if(u&&typeof u=="object")return G("SmartCanvas Config","Resolved config directly from feature flag",u),u}if(e&&(a||o)){let u=hN(e,a,o);if(u.length>0){let f=ef(e,u);if(f)return G("SmartCanvas Config","Resolved config from variant flags",f),f}}let l=rf({configUri:t,experiments:e,featureKey:n});if(!l)return G("SmartCanvas Config","No config available \u2014 returning empty config"),{tiles:[],actions:[],fetchedAt:new Date().toISOString()};if(!cN(l))throw new Error(`SmartCanvas: config URI not allowed: ${l}`);let c=i??(uN(l)?"include":"omit");try{let u=await fetch(l,{credentials:c,headers:{"X-SDK-Version":nf,"X-SDK-Schema-Version":Bi}});if(!u.ok)throw new Error(`SmartCanvas: failed to fetch config (${u.status})`);let f=await u.json();return G("SmartCanvas Config","Fetched config from URI",f),s&&fN(f,s),f}catch(u){if(s){let f=pN(s);if(f)return G("SmartCanvas Config","Serving config from offline cache"),f}throw u}};var gN=["cdn.syntrologie.com","api.syntrologie.com","dev-api.syntrologie.com","localhost","127.0.0.1",".syntrologie.com"];function IE(t){if(typeof window>"u")return null;let n=new URLSearchParams(window.location.search).get(t);if(!n)return null;try{let i=n.replace(/-/g,"+").replace(/_/g,"/");return JSON.parse(atob(i))}catch(i){return cn("Syntro Runtime",`Failed to decode ${t}:`,i),null}}var is,rs;function Lr(){if(is==null){let t=typeof window<"u"?window.__SYNTRO_EDITOR_PARAMS__:null;if(t?.token)is={token:t.token,api_base:t.apiBase||""},console.log(`[DIAG] getEditorSource: from __SYNTRO_EDITOR_PARAMS__ (token=${is.token.slice(0,15)}...)`);else{let e=IE("editor_source");e&&(is=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 is??null}function Ma(){if(rs==null){let t=typeof window<"u"?window.__SYNTRO_EDITOR_PARAMS__:null;if(t?.mode)rs={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=${rs.mode})`);else{let e=IE("editor_conf");e&&(rs=e),console.log(`[DIAG] getEditorConf: from URL param \u2192 ${e?`mode=${e.mode}`:"NULL"}`)}}return rs??null}function mN(t){G("Syntro Runtime","Validating editor URL:",t);try{if(t.startsWith("/"))return G("Syntro Runtime","\u2713 Relative URL allowed (same-origin):",t),!0;let e=new URL(t),n=/^(localhost|127\.0\.0\.1)$/.test(e.hostname);return e.protocol!=="https:"&&!n?(cn("Syntro Runtime","\u274C Editor URL must use HTTPS:",t),!1):gN.some(r=>r.startsWith(".")?e.hostname.endsWith(r)||e.hostname===r.slice(1):e.hostname===r)?(G("Syntro Runtime","\u2713 Editor URL validated"),!0):(cn("Syntro Runtime","\u274C Editor URL host not in allowlist:",e.hostname),!1)}catch(e){return cn("Syntro Runtime",`\u274C Invalid editor URL: ${t}`,e),!1}}var zE=()=>{let t=Ma();return!Lr()?.token||!t?null:t.mode==="editor"||t.mode==="audit"||t.mode==="review"?t.mode:null};function vN(){return Lr()?.token??null}function yN(){return Lr()?.api_base??null}var ec=null,BE=async t=>{if(G("Syntro Runtime","====== LOAD EDITOR SDK ======"),typeof window>"u"){G("Syntro Runtime","Not in browser - skipping editor SDK load");return}if(window.SyntroEditor){G("Syntro Runtime","Editor SDK already loaded (window.SyntroEditor exists)");return}if(ec)return G("Syntro Runtime","Editor SDK load already in progress, waiting..."),ec;let e=typeof t=="string"?{editorUrl:t}:t??{};if(e.editorUrl==="skip"){G("Syntro Runtime",'editorUrl="skip" \u2014 deferring to caller'),G("Syntro Runtime","================================");return}let n=yN(),r=(n?`${n}/api/editor/sdk/editor-sdk.js`:null)||e.editorUrl;if(!r){cn("Syntro Runtime","\u274C No editor SDK URL available (no api_base, no editorUrl option)"),G("Syntro Runtime","================================");return}let a=vN();if(!a){cn("Syntro Runtime","\u274C No token found in editor_source."),G("Syntro Runtime","================================");return}let o=`${r}?token=${encodeURIComponent(a)}`;if(G("Syntro Runtime","Editor URL:",o),G("Syntro Runtime","Options:",{hasIntegrity:!!e.integrity,hasEditorUrl:!!r,hasApiBase:!!n,tokenPrefix:`${a.slice(0,10)}...`}),!mN(r)){console.error("[Syntro Runtime] \u274C BLOCKED: Editor from untrusted URL:",r),G("Syntro Runtime","================================");return}return G("Syntro Runtime","\u2713 URL validated, injecting script tag..."),ec=new Promise((s,l)=>{let c=document.createElement("script");c.src=o,c.async=!0,e.integrity&&(c.integrity=e.integrity,c.crossOrigin="anonymous",G("Syntro Runtime","SRI integrity check enabled")),c.onload=()=>{G("Syntro Runtime","\u2713 Editor SDK script loaded successfully"),G("Syntro Runtime","================================"),s()},c.onerror=u=>{console.error("[Syntro Runtime] \u274C Failed to load Editor SDK:",u),console.error("[Syntro Runtime] URL attempted:",o),G("Syntro Runtime","================================"),ec=null,l(u)},document.head.appendChild(c),G("Syntro Runtime","Script tag appended to <head>")}),ec};function as(t,e){for(let n of t){let i=n.props;if(!i)continue;let r=i.scope;if(!r?.events)continue;let a=i.actions;if(!a)continue;let o=new Set;for(let u of a)if(u.showWhen?.type==="rules")for(let f of u.showWhen.rules)for(let h of f.conditions)h.type==="event_count"&&h.key&&o.add(h.key);if(o.size===0)continue;let{events:s,urlContains:l,props:c}=r;for(let u of o)e.register(u,f=>{if(!s.includes(f.name)||l&&!String(f.props?.pathname??"").includes(l))return!1;if(c){for(let[h,g]of Object.entries(c))if(f.props?.[h]!==g)return!1}return!0})}}var ii=null;function FE(t){ii&&ii!==t?t.appendChild(ii):ii=t;let e=t.getRootNode();e instanceof ShadowRoot&&bN(e)}function UE(){return ii||(ii=document.createElement("div"),ii.id="syntro-overlays",Object.assign(ii.style,{position:"fixed",inset:"0",zIndex:"2147483647",pointerEvents:"none"}),document.body.appendChild(ii)),ii}var $E=!1;function bN(t){if($E)return;let e=`
|
|
114
114
|
:host {
|
|
115
115
|
--syntro-surface: #0f1318;
|
|
116
116
|
--syntro-fg: #cbd0d7;
|
|
@@ -426,7 +426,7 @@ Error generating stack: `+i.message+`
|
|
|
426
426
|
.syntro-badge-ping { animation: syntro-badge-ping 1.5s cubic-bezier(0,0,0.2,1) infinite; }
|
|
427
427
|
.syntro-badge-glow { animation: syntro-badge-glow 2s ease-in-out infinite; }
|
|
428
428
|
.syntro-badge-bounce { animation: syntro-badge-bounce 2s ease-in-out infinite; }
|
|
429
|
-
`;function UN(t){if(t.querySelector(`#${XE}`))return;let e=document.createElement("style");e.id=XE,e.textContent=FN,t.appendChild(e)}var VN={position:"right",baseWidth:"clamp(320px, 16.666vw, 420px)",expandedWidth:"40vw",zIndex:2147483600,backdropBlur:"18px",mode:"dark",colorPrimary:ne[3],colorBackground:E[1],colorText:dt.primary,colorTextSecondary:dt.secondary,borderRadius:"12px",glassBackground:oe(E[1],.6),glassBlur:"blur(24px)",glassSaturate:"saturate(1.2)"};function ov({isOpen:t,onToggle:e,telemetry:n,launcherLabel:i="Adaptives",launcherAnimate:r=!1,launcherAnimationStyle:a="pulse",notificationCount:o,footerSlot:s,tiles:l,isLoading:c,error:u,canvasTitle:f,displayMode:h="standard",theme:g}){let[_,b]=(0,qt.useState)(!1),[w,d]=(0,qt.useState)(null),p=(0,qt.useRef)(null),m=ri(),{shadowRoot:v,portalRoot:S}=tc(),{notifications:T,dismiss:A}=ff(m?.events??null,l);hf(m,l,m?.apps);let k=(0,qt.useCallback)(L=>{m&&m.events.publish(ye.NOTIFICATION_CLICKED,{notificationId:L.id,tileId:L.tileId,itemId:L.itemId}),t||e(),m&&L.tileId&&m.events.publish(ye.NOTIFICATION_DEEP_LINK,{tileId:L.tileId,itemId:L.itemId}),A(L.id)},[m,t,e,A]),C={...VN,...g};(0,qt.useEffect)(()=>{t&&l.forEach(L=>{if(n?.trackRectangleViewed(L.id,"overlay"),m){let de=os.tileViewed(L.id,"overlay");m.events.publish(de.name,de.props,de.source)}})},[n,m,t,l]),(0,qt.useEffect)(()=>{b(!0),UN(v)},[v]);let x=(0,qt.useCallback)(()=>{let L=!t;if(L?n?.trackCanvasOpened("overlay"):n?.trackCanvasClosed("overlay"),m){let de=L?os.canvasOpened("overlay"):os.canvasClosed("overlay");m.events.publish(de.name,de.props,de.source)}e()},[t,n,m,e]),M=(0,qt.useCallback)(L=>{let de=L.currentTarget.getBoundingClientRect();p.current={startX:L.clientX,startY:L.clientY,startElX:de.left,startElY:de.top,dragged:!1},L.currentTarget.setPointerCapture(L.pointerId)},[]),z=(0,qt.useCallback)(L=>{let de=p.current;if(!de)return;let fn=L.clientX-de.startX,We=L.clientY-de.startY;(Math.abs(fn)>5||Math.abs(We)>5)&&(de.dragged=!0),de.dragged&&d({x:de.startElX+fn,y:de.startElY+We})},[]),U=(0,qt.useCallback)(L=>{let de=p.current;p.current=null,de&&!de.dragged&&x()},[x]),P=h==="focused",Z=C.position==="right",X={display:"flex",flexDirection:"column",width:P?C.expandedWidth:C.baseWidth,minWidth:"320px",height:"100%",maxHeight:"100%",pointerEvents:"auto",opacity:t?1:0,transition:t?"transform 340ms cubic-bezier(0.16, 1, 0.3, 1), opacity 280ms ease-out":"transform 280ms cubic-bezier(0.4, 0, 0.2, 1), opacity 200ms ease-in",color:C.colorText||dt.primary,background:P?C.glassBackground??oe(E[1],.6):"transparent",backdropFilter:P?`${C.glassBlur??"blur(24px)"} ${C.glassSaturate??"saturate(1.2)"}`:"blur(6px)",WebkitBackdropFilter:P?`${C.glassBlur??"blur(24px)"} ${C.glassSaturate??"saturate(1.2)"}`:"blur(6px)",...P?{}:{maskImage:Z?"linear-gradient(to right, transparent, black 6%)":"linear-gradient(to left, transparent, black 6%)",WebkitMaskImage:Z?"linear-gradient(to right, transparent, black 6%)":"linear-gradient(to left, transparent, black 6%)"},border:"none",borderRadius:"0",boxShadow:"none",transform:t?"translateX(0)":Z?"translateX(120%)":"translateX(-120%)"},W={position:"absolute",inset:0,display:"flex",flexDirection:Z?"row-reverse":"row",alignItems:"stretch",pointerEvents:"none",padding:"0"},D=(0,pe.jsx)("div",{"data-shadow-canvas-id":"overlay-root",style:{position:"fixed",inset:0,pointerEvents:t?"auto":"none",zIndex:C.zIndex},children:(0,pe.jsxs)("div",{style:W,children:[(0,pe.jsxs)("div",{"data-shadow-canvas-id":"overlay-container",style:X,children:[P&&f&&(0,pe.jsx)("header",{style:{color:"white",padding:"1.5rem 1.5rem 0"},children:(0,pe.jsx)("p",{style:{margin:0,fontSize:"0.7rem",textTransform:"uppercase",letterSpacing:"0.5em",color:dt.tertiary},children:f})}),(0,pe.jsx)("div",{style:{flex:1,overflowY:"auto",padding:P?"0":"1rem"},children:c?(0,pe.jsx)("div",{style:{color:dt.primary,padding:P?"1rem":"0"},children:"Loading..."}):u?(0,pe.jsxs)("div",{style:{color:Be[8],padding:P?"1rem":"0"},children:["Failed to load: ",u]}):P?l.length>0?(0,pe.jsx)(ls,{config:l[0],surface:"overlay",telemetry:n,style:{width:"100%",height:"100%"}}):null:(0,pe.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem",width:"100%"},children:l.map(L=>(0,pe.jsx)(ls,{config:L,surface:"overlay",telemetry:n,style:{width:"100%"}},L.id))})}),s]}),(0,pe.jsx)("div",{onClick:x,style:{flex:"1 1 auto",pointerEvents:t?"auto":"none",cursor:"default"}})]})});return _?(0,pe.jsxs)(pe.Fragment,{children:[(0,av.createPortal)((0,pe.jsxs)("div",{"data-shadow-canvas-id":"overlay-launcher",style:{position:"fixed",inset:0,pointerEvents:"none",zIndex:C.zIndex+47},children:[(0,pe.jsx)(sf,{notifications:T,onDismiss:A,onClickNotification:k,position:C.position}),(0,pe.jsxs)("button",{type:"button","aria-label":"Toggle shadow canvas",className:r&&!t?"syntro-launcher-animate":void 0,style:{position:"fixed",...w?{top:w.y,left:w.x}:{bottom:"2.5rem",right:Z?"2.5rem":void 0,left:Z?void 0:"2.5rem"},pointerEvents:"auto",display:"flex",alignItems:"center",justifyContent:"center",width:"56px",height:"56px",borderRadius:"9999px",color:Gl.primary.icon,boxShadow:`0 8px 32px ${oe(E[0],.6)}`,transition:p.current?"none":"transform 0.2s ease, opacity 0.3s ease, background-color 0.2s ease",outline:"none",padding:0,border:"none",backgroundColor:Gl.primary.backgroundDefault,cursor:p.current?.dragged?"grabbing":"pointer",touchAction:"none"},onPointerDown:M,onPointerMove:z,onPointerUp:U,onMouseEnter:L=>{p.current?.dragged||(L.currentTarget.style.backgroundColor=Gl.primary.backgroundHover)},onMouseLeave:L=>{p.current?.dragged||(L.currentTarget.style.backgroundColor=Gl.primary.backgroundDefault)},children:[(0,pe.jsx)("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false",style:{transition:"transform 200ms ease"},children:t?(0,pe.jsxs)(pe.Fragment,{children:[(0,pe.jsx)("path",{d:"M18 6L6 18"}),(0,pe.jsx)("path",{d:"M6 6l12 12"})]}):(0,pe.jsxs)(pe.Fragment,{children:[(0,pe.jsx)("path",{d:"M12 3l1.912 5.813a2 2 0 0 0 1.275 1.275L21 12l-5.813 1.912a2 2 0 0 0-1.275 1.275L12 21l-1.912-5.813a2 2 0 0 0-1.275-1.275L3 12l5.813-1.912a2 2 0 0 0 1.275-1.275L12 3Z"}),(0,pe.jsx)("path",{d:"M5 3v4"}),(0,pe.jsx)("path",{d:"M3 5h4"}),(0,pe.jsx)("path",{d:"M19 17v4"}),(0,pe.jsx)("path",{d:"M17 19h4"})]})}),!t&&T.length>0&&(0,pe.jsxs)("div",{style:{position:"absolute",top:-2,right:-2,pointerEvents:"none"},children:[(0,pe.jsx)("span",{className:"syntro-badge-ping",style:{position:"absolute",inset:0,borderRadius:"9999px",background:oe(ne[4],.4)}}),(0,pe.jsx)("span",{className:"syntro-badge-glow",style:{position:"absolute",inset:-4,borderRadius:"9999px"}}),(0,pe.jsx)("span",{className:"syntro-badge-bounce",style:{position:"relative",display:"flex",alignItems:"center",justifyContent:"center",width:20,height:20,borderRadius:"9999px",background:ne[4],color:Ze.white,fontSize:11,fontWeight:700},children:T.length>99?"99+":T.length})]})]})]}),S),t?(0,av.createPortal)(D,S):null]}):null}var Hr=ee(nt(),1);var jN=t=>[...t].sort((e,n)=>(n.priority??0)-(e.priority??0));function sv({fetcher:t,pollIntervalMs:e=3e4,experiments:n,runtime:i}){let[r,a]=(0,Hr.useState)({tiles:[],actions:[],isLoading:!0}),o=(0,Hr.useCallback)(async()=>{try{a(c=>({...c,isLoading:!0,error:void 0}));let s=await t();G("SmartCanvas Config","Raw config response",s);let l=s.tiles||[];i?(l=await i.filterTiles(l),n&&(l=l.filter(c=>n.shouldRenderRectangle(c)))):n&&(l=l.filter(c=>n.shouldRenderRectangle(c))),G("SmartCanvas Config",`Tile count after filtering: ${l.length}`),a({tiles:jN(l),actions:s.actions||[],isLoading:!1,fetchedAt:s.fetchedAt,canvasTitle:s.canvasTitle,configVersion:s.configVersion,theme:s.theme,launcher:s.launcher})}catch(s){let l=s instanceof Error?s.message:"Unknown error";console.error("[SmartCanvas Config] Failed to fetch/filter config:",l,s),a(c=>({...c,isLoading:!1,error:l}))}},[n,t,i]);return(0,Hr.useEffect)(()=>{if(o(),!e)return;let s=setInterval(o,e);return()=>clearInterval(s)},[o,e]),(0,Hr.useMemo)(()=>r,[r])}var rc=ee(qe(),1);function lv({controller:t,fetcher:e,configUri:n,configUriFeatureKey:i="smart-canvas-config-uri",configFeatureKey:r="smart-canvas-config",fetchCredentials:a="include",pollIntervalMs:o,experiments:s,telemetry:l,runtime:c,overlayFetcher:u,overlayConfigUri:f,overlayConfigFeatureKey:h="smart-canvas-overlay-uri",overlayFetchCredentials:g="include",footerSlot:_,launcherLabel:b,canvasHost:w,theme:d,initialBatchHandle:p}){return c?(0,rc.jsx)(gf,{runtime:c,children:(0,rc.jsx)(QE,{controller:t,fetcher:e,configUri:n,configUriFeatureKey:i,configFeatureKey:r,fetchCredentials:a,pollIntervalMs:o,experiments:s,telemetry:l,runtime:c,overlayFetcher:u,overlayConfigUri:f,overlayConfigFeatureKey:h,overlayFetchCredentials:g,footerSlot:_,launcherLabel:b,canvasHost:w,theme:d,initialBatchHandle:p})}):(0,rc.jsx)(QE,{controller:t,fetcher:e,configUri:n,configUriFeatureKey:i,configFeatureKey:r,fetchCredentials:a,pollIntervalMs:o,experiments:s,telemetry:l,overlayFetcher:u,overlayConfigUri:f,overlayConfigFeatureKey:h,overlayFetchCredentials:g,footerSlot:_,launcherLabel:b,canvasHost:w,theme:d,initialBatchHandle:p})}function QE({controller:t,fetcher:e,configUri:n,configUriFeatureKey:i="smart-canvas-config-uri",configFeatureKey:r="smart-canvas-config",fetchCredentials:a="include",pollIntervalMs:o,experiments:s,telemetry:l,runtime:c,overlayFetcher:u,overlayConfigUri:f,overlayConfigFeatureKey:h="smart-canvas-overlay-uri",overlayFetchCredentials:g="include",footerSlot:_,launcherLabel:b,canvasHost:w,theme:d,initialBatchHandle:p}){let[m,v]=(0,Nt.useState)(t.getState().open),S=mf(),[T,A]=(0,Nt.useState)(()=>typeof window<"u"?window.location.pathname:"/"),k=S?.url?new URL(S.url).pathname:T;(0,Nt.useEffect)(()=>{if(c||typeof window>"u")return;let Z=()=>A(window.location.pathname);window.addEventListener("popstate",Z);let X=history.pushState,W=history.replaceState;return history.pushState=function(...D){X.apply(this,D),queueMicrotask(Z)},history.replaceState=function(...D){W.apply(this,D),queueMicrotask(Z)},()=>{window.removeEventListener("popstate",Z),history.pushState=X,history.replaceState=W}},[c]);let C=(0,Nt.useMemo)(()=>e||Oa({configUri:n,experiments:s,featureKey:i,configFeatureKey:r,credentials:a}),[e,n,s,i,r,a]),x=sv({fetcher:C,pollIntervalMs:o,experiments:s,runtime:c}),M=x.tiles.length>0&&!x.error;(0,Nt.useEffect)(()=>t.subscribe(Z=>v(Z.open)),[t]),(0,Nt.useEffect)(()=>{!x.isLoading&&!M&&t.getState().open&&t.setOpen(!1)},[t,M,x.isLoading]);let z=(0,Nt.useRef)(p??null),U=(0,Nt.useRef)(!!p);(0,Nt.useEffect)(()=>{if(!c?.actions)return;if(U.current){x.actions.length>0&&(U.current=!1);return}let Z=!1;return(async()=>{if(z.current){console.log("[SmartCanvasApp] Reverting previous action batch before re-apply");try{await z.current.revertAll()}catch(W){console.error("[SmartCanvasApp] Failed to revert actions:",W)}z.current=null}if(!Z&&x.actions.length>0){console.log(`[SmartCanvasApp] Applying ${x.actions.length} action(s):`,x.actions.map((W,D)=>`[${D}] ${W.kind}${W.anchorId?` anchor="${W.anchorId}"`:""}${W.label?` "${W.label}"`:""}`).join(", "));try{let W=await c.actions.applyBatch(x.actions);Z?await W.revertAll():(z.current=W,console.log("[SmartCanvasApp] Action batch applied successfully"))}catch(W){Z||console.error("[SmartCanvasApp] Failed to apply actions:",W,`
|
|
429
|
+
`;function UN(t){if(t.querySelector(`#${XE}`))return;let e=document.createElement("style");e.id=XE,e.textContent=FN,t.appendChild(e)}var VN={position:"right",baseWidth:"clamp(320px, 16.666vw, 420px)",expandedWidth:"40vw",zIndex:2147483600,backdropBlur:"18px",mode:"dark",colorPrimary:ne[3],colorBackground:E[1],colorText:dt.primary,colorTextSecondary:dt.secondary,borderRadius:"12px",glassBackground:oe(E[1],.6),glassBlur:"blur(24px)",glassSaturate:"saturate(1.2)"};function ov({isOpen:t,onToggle:e,telemetry:n,launcherLabel:i="Adaptives",launcherAnimate:r=!1,launcherAnimationStyle:a="pulse",notificationCount:o,footerSlot:s,tiles:l,isLoading:c,error:u,canvasTitle:f,displayMode:h="standard",theme:g}){let[_,b]=(0,qt.useState)(!1),[w,d]=(0,qt.useState)(null),p=(0,qt.useRef)(null),m=ri(),{shadowRoot:v,portalRoot:S}=tc(),{notifications:T,dismiss:A}=ff(m?.events??null,l);hf(m,l,m?.apps);let k=(0,qt.useCallback)(L=>{m&&m.events.publish(ye.NOTIFICATION_CLICKED,{notificationId:L.id,tileId:L.tileId,itemId:L.itemId}),t||e(),m&&L.tileId&&m.events.publish(ye.NOTIFICATION_DEEP_LINK,{tileId:L.tileId,itemId:L.itemId}),A(L.id)},[m,t,e,A]),C={...VN,...g};(0,qt.useEffect)(()=>{t&&l.forEach(L=>{if(n?.trackRectangleViewed(L.id,"overlay"),m){let de=os.tileViewed(L.id,"overlay");m.events.publish(de.name,de.props,de.source)}})},[n,m,t,l]),(0,qt.useEffect)(()=>{b(!0),UN(v)},[v]);let x=(0,qt.useCallback)(()=>{let L=!t;if(L?n?.trackCanvasOpened("overlay"):n?.trackCanvasClosed("overlay"),m){let de=L?os.canvasOpened("overlay"):os.canvasClosed("overlay");m.events.publish(de.name,de.props,de.source)}e()},[t,n,m,e]),M=(0,qt.useCallback)(L=>{let de=L.currentTarget.getBoundingClientRect();p.current={startX:L.clientX,startY:L.clientY,startElX:de.left,startElY:de.top,dragged:!1},L.currentTarget.setPointerCapture(L.pointerId)},[]),z=(0,qt.useCallback)(L=>{let de=p.current;if(!de)return;let fn=L.clientX-de.startX,We=L.clientY-de.startY;(Math.abs(fn)>5||Math.abs(We)>5)&&(de.dragged=!0),de.dragged&&d({x:de.startElX+fn,y:de.startElY+We})},[]),U=(0,qt.useCallback)(L=>{let de=p.current;p.current=null,de&&!de.dragged&&x()},[x]),P=h==="focused",Z=C.position==="right",X={display:"flex",flexDirection:"column",width:P?C.expandedWidth:C.baseWidth,minWidth:"320px",height:"100%",maxHeight:"100%",pointerEvents:"auto",opacity:t?1:0,transition:t?"transform 340ms cubic-bezier(0.16, 1, 0.3, 1), opacity 280ms ease-out":"transform 280ms cubic-bezier(0.4, 0, 0.2, 1), opacity 200ms ease-in",color:C.colorText||dt.primary,background:P?C.glassBackground??oe(E[1],.6):"transparent",backdropFilter:P?`${C.glassBlur??"blur(24px)"} ${C.glassSaturate??"saturate(1.2)"}`:"blur(6px)",WebkitBackdropFilter:P?`${C.glassBlur??"blur(24px)"} ${C.glassSaturate??"saturate(1.2)"}`:"blur(6px)",...P?{}:{maskImage:Z?"linear-gradient(to right, transparent, black 6%)":"linear-gradient(to left, transparent, black 6%)",WebkitMaskImage:Z?"linear-gradient(to right, transparent, black 6%)":"linear-gradient(to left, transparent, black 6%)"},border:"none",borderRadius:"0",boxShadow:"none",transform:t?"translateX(0)":Z?"translateX(120%)":"translateX(-120%)"},W={position:"absolute",inset:0,display:"flex",flexDirection:Z?"row-reverse":"row",alignItems:"stretch",pointerEvents:"none",padding:"0"},D=(0,pe.jsx)("div",{"data-shadow-canvas-id":"overlay-root",style:{position:"fixed",inset:0,pointerEvents:t?"auto":"none",zIndex:C.zIndex},children:(0,pe.jsxs)("div",{style:W,children:[(0,pe.jsxs)("div",{"data-shadow-canvas-id":"overlay-container",style:X,children:[P&&f&&(0,pe.jsx)("header",{style:{color:"white",padding:"1.5rem 1.5rem 0"},children:(0,pe.jsx)("p",{style:{margin:0,fontSize:"0.7rem",textTransform:"uppercase",letterSpacing:"0.5em",color:dt.tertiary},children:f})}),(0,pe.jsx)("div",{style:{flex:1,overflowY:"auto",padding:P?"0":"1rem"},children:c?(0,pe.jsx)("div",{style:{color:dt.primary,padding:P?"1rem":"0"},children:"Loading..."}):u?(0,pe.jsxs)("div",{style:{color:Be[8],padding:P?"1rem":"0"},children:["Failed to load: ",u]}):P?l.length>0?(0,pe.jsx)(ls,{config:l[0],surface:"overlay",telemetry:n,style:{width:"100%",height:"100%"}}):null:(0,pe.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:"0.75rem",width:"100%"},children:l.map(L=>(0,pe.jsx)(ls,{config:L,surface:"overlay",telemetry:n,style:{width:"100%"}},L.id))})}),s]}),(0,pe.jsx)("div",{onClick:x,style:{flex:"1 1 auto",pointerEvents:t?"auto":"none",cursor:"default"}})]})});return _?(0,pe.jsxs)(pe.Fragment,{children:[(0,av.createPortal)((0,pe.jsxs)("div",{"data-shadow-canvas-id":"overlay-launcher",style:{position:"fixed",inset:0,pointerEvents:"none",zIndex:C.zIndex+47},children:[(0,pe.jsx)(sf,{notifications:T,onDismiss:A,onClickNotification:k,position:C.position}),(0,pe.jsxs)("button",{type:"button","aria-label":"Toggle shadow canvas",className:r&&!t?"syntro-launcher-animate":void 0,style:{position:"fixed",...w?{top:w.y,left:w.x}:{bottom:"2.5rem",right:Z?"2.5rem":void 0,left:Z?void 0:"2.5rem"},pointerEvents:"auto",display:"flex",alignItems:"center",justifyContent:"center",width:"56px",height:"56px",borderRadius:"9999px",color:Gl.primary.icon,boxShadow:`0 8px 32px ${oe(E[0],.6)}`,transition:p.current?"none":"transform 0.2s ease, opacity 0.3s ease, background-color 0.2s ease",outline:"none",padding:0,border:"none",backgroundColor:Gl.primary.backgroundDefault,cursor:p.current?.dragged?"grabbing":"pointer",touchAction:"none"},onPointerDown:M,onPointerMove:z,onPointerUp:U,onMouseEnter:L=>{p.current?.dragged||(L.currentTarget.style.backgroundColor=Gl.primary.backgroundHover)},onMouseLeave:L=>{p.current?.dragged||(L.currentTarget.style.backgroundColor=Gl.primary.backgroundDefault)},children:[(0,pe.jsx)("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false",style:{transition:"transform 200ms ease"},children:t?(0,pe.jsxs)(pe.Fragment,{children:[(0,pe.jsx)("path",{d:"M18 6L6 18"}),(0,pe.jsx)("path",{d:"M6 6l12 12"})]}):(0,pe.jsxs)(pe.Fragment,{children:[(0,pe.jsx)("path",{d:"M12 3l1.912 5.813a2 2 0 0 0 1.275 1.275L21 12l-5.813 1.912a2 2 0 0 0-1.275 1.275L12 21l-1.912-5.813a2 2 0 0 0-1.275-1.275L3 12l5.813-1.912a2 2 0 0 0 1.275-1.275L12 3Z"}),(0,pe.jsx)("path",{d:"M5 3v4"}),(0,pe.jsx)("path",{d:"M3 5h4"}),(0,pe.jsx)("path",{d:"M19 17v4"}),(0,pe.jsx)("path",{d:"M17 19h4"})]})}),!t&&T.length>0&&(0,pe.jsxs)("div",{style:{position:"absolute",top:-2,right:-2,pointerEvents:"none"},children:[(0,pe.jsx)("span",{className:"syntro-badge-ping",style:{position:"absolute",inset:0,borderRadius:"9999px",background:oe(ne[4],.4)}}),(0,pe.jsx)("span",{className:"syntro-badge-glow",style:{position:"absolute",inset:-4,borderRadius:"9999px"}}),(0,pe.jsx)("span",{className:"syntro-badge-bounce",style:{position:"relative",display:"flex",alignItems:"center",justifyContent:"center",width:20,height:20,borderRadius:"9999px",background:ne[4],color:Ze.white,fontSize:11,fontWeight:700},children:T.length>99?"99+":T.length})]})]})]}),S),t?(0,av.createPortal)(D,S):null]}):null}var Hr=ee(nt(),1);var jN=t=>[...t].sort((e,n)=>(n.priority??0)-(e.priority??0));function sv({fetcher:t,pollIntervalMs:e=3e4,experiments:n,runtime:i,pathname:r}){let[a,o]=(0,Hr.useState)({tiles:[],actions:[],isLoading:!0}),s=(0,Hr.useCallback)(async()=>{try{o(u=>({...u,isLoading:!0,error:void 0}));let l=await t();G("SmartCanvas Config","Raw config response",l);let c=l.tiles||[];i?(c=await i.filterTiles(c),n&&(c=c.filter(u=>n.shouldRenderRectangle(u)))):n&&(c=c.filter(u=>n.shouldRenderRectangle(u))),G("SmartCanvas Config",`Tile count after filtering: ${c.length}`),o({tiles:jN(c),actions:l.actions||[],isLoading:!1,fetchedAt:l.fetchedAt,canvasTitle:l.canvasTitle,configVersion:l.configVersion,theme:l.theme,launcher:l.launcher})}catch(l){let c=l instanceof Error?l.message:"Unknown error";console.error("[SmartCanvas Config] Failed to fetch/filter config:",c,l),o(u=>({...u,isLoading:!1,error:c}))}},[n,t,i]);return(0,Hr.useEffect)(()=>{if(s(),!e)return;let l=setInterval(s,e);return()=>clearInterval(l)},[s,e,r]),(0,Hr.useMemo)(()=>a,[a])}var rc=ee(qe(),1);function lv({controller:t,fetcher:e,configUri:n,configUriFeatureKey:i="smart-canvas-config-uri",configFeatureKey:r="smart-canvas-config",fetchCredentials:a="include",pollIntervalMs:o,experiments:s,telemetry:l,runtime:c,overlayFetcher:u,overlayConfigUri:f,overlayConfigFeatureKey:h="smart-canvas-overlay-uri",overlayFetchCredentials:g="include",footerSlot:_,launcherLabel:b,canvasHost:w,theme:d,initialBatchHandle:p}){return c?(0,rc.jsx)(gf,{runtime:c,children:(0,rc.jsx)(QE,{controller:t,fetcher:e,configUri:n,configUriFeatureKey:i,configFeatureKey:r,fetchCredentials:a,pollIntervalMs:o,experiments:s,telemetry:l,runtime:c,overlayFetcher:u,overlayConfigUri:f,overlayConfigFeatureKey:h,overlayFetchCredentials:g,footerSlot:_,launcherLabel:b,canvasHost:w,theme:d,initialBatchHandle:p})}):(0,rc.jsx)(QE,{controller:t,fetcher:e,configUri:n,configUriFeatureKey:i,configFeatureKey:r,fetchCredentials:a,pollIntervalMs:o,experiments:s,telemetry:l,overlayFetcher:u,overlayConfigUri:f,overlayConfigFeatureKey:h,overlayFetchCredentials:g,footerSlot:_,launcherLabel:b,canvasHost:w,theme:d,initialBatchHandle:p})}function QE({controller:t,fetcher:e,configUri:n,configUriFeatureKey:i="smart-canvas-config-uri",configFeatureKey:r="smart-canvas-config",fetchCredentials:a="include",pollIntervalMs:o,experiments:s,telemetry:l,runtime:c,overlayFetcher:u,overlayConfigUri:f,overlayConfigFeatureKey:h="smart-canvas-overlay-uri",overlayFetchCredentials:g="include",footerSlot:_,launcherLabel:b,canvasHost:w,theme:d,initialBatchHandle:p}){let[m,v]=(0,Nt.useState)(t.getState().open),S=mf(),[T,A]=(0,Nt.useState)(()=>typeof window<"u"?window.location.pathname:"/"),k=S?.url?new URL(S.url).pathname:T;(0,Nt.useEffect)(()=>{if(c||typeof window>"u")return;let Z=()=>A(window.location.pathname);window.addEventListener("popstate",Z);let X=history.pushState,W=history.replaceState;return history.pushState=function(...D){X.apply(this,D),queueMicrotask(Z)},history.replaceState=function(...D){W.apply(this,D),queueMicrotask(Z)},()=>{window.removeEventListener("popstate",Z),history.pushState=X,history.replaceState=W}},[c]);let C=(0,Nt.useMemo)(()=>e||Oa({configUri:n,experiments:s,featureKey:i,configFeatureKey:r,credentials:a}),[e,n,s,i,r,a]),x=sv({fetcher:C,pollIntervalMs:o,experiments:s,runtime:c,pathname:k}),M=x.tiles.length>0&&!x.error;(0,Nt.useEffect)(()=>t.subscribe(Z=>v(Z.open)),[t]),(0,Nt.useEffect)(()=>{!x.isLoading&&!M&&t.getState().open&&t.setOpen(!1)},[t,M,x.isLoading]);let z=(0,Nt.useRef)(p??null),U=(0,Nt.useRef)(!!p);(0,Nt.useEffect)(()=>{if(!c?.actions)return;if(U.current){x.actions.length>0&&(U.current=!1);return}let Z=!1;return(async()=>{if(z.current){console.log("[SmartCanvasApp] Reverting previous action batch before re-apply");try{await z.current.revertAll()}catch(W){console.error("[SmartCanvasApp] Failed to revert actions:",W)}z.current=null}if(!Z&&x.actions.length>0){console.log(`[SmartCanvasApp] Applying ${x.actions.length} action(s):`,x.actions.map((W,D)=>`[${D}] ${W.kind}${W.anchorId?` anchor="${W.anchorId}"`:""}${W.label?` "${W.label}"`:""}`).join(", "));try{let W=await c.actions.applyBatch(x.actions);Z?await W.revertAll():(z.current=W,console.log("[SmartCanvasApp] Action batch applied successfully"))}catch(W){Z||console.error("[SmartCanvasApp] Failed to apply actions:",W,`
|
|
430
430
|
Actions that failed:`,JSON.stringify(x.actions,null,2))}}})(),()=>{Z=!0,z.current&&(console.log("[SmartCanvasApp] Cleanup: reverting action batch (actions changed or unmount)"),z.current.revertAll().catch(W=>{console.error("[SmartCanvasApp] Failed to revert actions on cleanup:",W)}),z.current=null)}},[c,x.actions]),(0,Nt.useEffect)(()=>{if(c)return c.events.subscribe({names:["canvas.requestOpen"]},()=>t.setOpen(!0))},[c,t]);let P=(0,Nt.useMemo)(()=>{let Z=x.theme;return Z?{...Z,...d}:d},[x.theme,d]);return!x.isLoading&&!M?null:(0,rc.jsx)(ov,{tiles:x.tiles,isLoading:x.isLoading,error:x.error,canvasTitle:x.canvasTitle,telemetry:l,launcherLabel:b??x.launcher?.label,launcherAnimate:x.launcher?.animate,launcherAnimationStyle:x.launcher?.animationStyle,notificationCount:x.launcher?.notificationCount??x.tiles.length,footerSlot:_,isOpen:m,onToggle:()=>t.toggle(),displayMode:x.displayMode,theme:P})}var cv=ee(qe(),1),JE="smart-canvas",eC=`
|
|
431
431
|
:host {
|
|
432
432
|
font: inherit;
|
|
@@ -446,7 +446,7 @@ Actions that failed:`,JSON.stringify(x.actions,null,2))}}})(),()=>{Z=!0,z.curren
|
|
|
446
446
|
`).replace(/\r/g,`
|
|
447
447
|
`)).length,r=0;r<i;r++){var o=t.charCodeAt(r),s=null;o<128?n++:s=o>127&&o<2048?String.fromCharCode(o>>6|192,63&o|128):String.fromCharCode(o>>12|224,o>>6&63|128,63&o|128),Qi(s)||(n>e&&(a+=t.substring(e,n)),a+=s,e=n=r+1)}return n>e&&(a+=t.substring(e,t.length)),a},T3=!!Kv||!!Wv,zA="text/plain",vp=function(t,e,n){var i;n===void 0&&(n=!0);var[r,a]=t.split("?"),o=j({},e),s=(i=a?.split("&").map((c=>{var u,[f,h]=c.split("="),g=n&&(u=o[f])!==null&&u!==void 0?u:h;return delete o[f],f+"="+g})))!==null&&i!==void 0?i:[],l=qL(o);return l&&s.push(l),r+"?"+s.join("&")},Rc=(t,e)=>JSON.stringify(t,((n,i)=>typeof i=="bigint"?i.toString():i),e),qv=t=>{var{data:e,compression:n}=t;if(e){if(n===Xi.GZipJS){var i=C3((function(l,c){var u=l.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(l);for(var f=new Ln(l.length+(l.length>>>1)),h=0,g=function(d){f[h++]=d},_=0;_<u;++_){if(h+5>f.length){var b=new Ln(h+8+(u-_<<1));b.set(f),f=b}var w=l.charCodeAt(_);w<128||c?g(w):w<2048?(g(192|w>>>6),g(128|63&w)):w>55295&&w<57344?(g(240|(w=65536+(1047552&w)|1023&l.charCodeAt(++_))>>>18),g(128|w>>>12&63),g(128|w>>>6&63),g(128|63&w)):(g(224|w>>>12),g(128|w>>>6&63),g(128|63&w))}return KT(f,0,h)})(Rc(e)),{mtime:0}),r=new Blob([i],{type:zA});return{contentType:zA,body:r,estimatedSize:r.size}}if(n===Xi.Base64){var a=(function(l){var c,u,f,h,g,_="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",b=0,w=0,d="",p=[];if(!l)return l;l=A3(l);do c=(g=l.charCodeAt(b++)<<16|l.charCodeAt(b++)<<8|l.charCodeAt(b++))>>18&63,u=g>>12&63,f=g>>6&63,h=63&g,p[w++]=_.charAt(c)+_.charAt(u)+_.charAt(f)+_.charAt(h);while(b<l.length);switch(d=p.join(""),l.length%3){case 1:d=d.slice(0,-2)+"==";break;case 2:d=d.slice(0,-1)+"="}return d})(Rc(e)),o=(l=>"data="+encodeURIComponent(typeof l=="string"?l:Rc(l)))(a);return{contentType:"application/x-www-form-urlencoded",body:o,estimatedSize:new Blob([o]).size}}var s=Rc(e);return{contentType:"application/json",body:s,estimatedSize:new Blob([s]).size}}},ep=[];Wv&&ep.push({transport:"fetch",method:t=>{var e,n,{contentType:i,body:r,estimatedSize:a}=(e=qv(t))!==null&&e!==void 0?e:{},o=new Headers;Re(t.headers,(function(u,f){o.append(f,u)})),i&&o.append("Content-Type",i);var s=t.url,l=null;if(iA){var c=new iA;l={signal:c.signal,timeout:setTimeout((()=>c.abort()),t.timeout)}}Wv(s,j({method:t?.method||"GET",headers:o,keepalive:t.method==="POST"&&(a||0)<52428.8,body:r,signal:(n=l)==null?void 0:n.signal},t.fetchOptions)).then((u=>u.text().then((f=>{var h={statusCode:u.status,text:f};if(u.status===200)try{h.json=JSON.parse(f)}catch(g){$.error(g)}t.callback==null||t.callback(h)})))).catch((u=>{$.error(u),t.callback==null||t.callback({statusCode:0,text:u})})).finally((()=>l?clearTimeout(l.timeout):null))}}),Kv&&ep.push({transport:"XHR",method:t=>{var e,n=new Kv;n.open(t.method||"GET",t.url,!0);var{contentType:i,body:r}=(e=qv(t))!==null&&e!==void 0?e:{};Re(t.headers,(function(a,o){n.setRequestHeader(o,a)})),i&&n.setRequestHeader("Content-Type",i),t.timeout&&(n.timeout=t.timeout),t.disableXHRCredentials||(n.withCredentials=!0),n.onreadystatechange=()=>{if(n.readyState===4){var a={statusCode:n.status,text:n.responseText};if(n.status===200)try{a.json=JSON.parse(n.responseText)}catch{}t.callback==null||t.callback(a)}},n.send(r)}}),dn!=null&&dn.sendBeacon&&ep.push({transport:"sendBeacon",method:t=>{var e=vp(t.url,{beacon:"1"});try{var n,{contentType:i,body:r}=(n=qv(t))!==null&&n!==void 0?n:{},a=typeof r=="string"?new Blob([r],{type:i}):r;dn.sendBeacon(e,a)}catch{}}});var yp=function(t,e){if(!(function(n){try{new RegExp(n)}catch{return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function BA(t,e,n){return Rc({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:n})}var XT={exact:(t,e)=>e.some((n=>t.some((i=>n===i)))),is_not:(t,e)=>e.every((n=>t.every((i=>n!==i)))),regex:(t,e)=>e.some((n=>t.some((i=>yp(n,i))))),not_regex:(t,e)=>e.every((n=>t.every((i=>!yp(n,i))))),icontains:(t,e)=>e.map(Qf).some((n=>t.map(Qf).some((i=>n.includes(i))))),not_icontains:(t,e)=>e.map(Qf).every((n=>t.map(Qf).every((i=>!n.includes(i)))))},Qf=t=>t.toLowerCase();function QT(t,e){return!t||Object.entries(t).every((n=>{var[i,r]=n,a=e?.[i];if(I(a)||Qi(a))return!1;var o=[String(a)],s=XT[r.operator];return!!s&&s(r.values,o)}))}var Pv=st("[Error tracking]"),Fy=class{constructor(e){var n,i;this.Jt=[],this.Kt=new ty([new iy,new uy,new ay,new ry,new ly,new sy,new oy,new cy],AL("web:javascript",xL,CL)),this._instance=e,this.Jt=(n=(i=this._instance.persistence)==null?void 0:i.get_property(fy))!==null&&n!==void 0?n:[]}onRemoteConfig(e){var n,i,r,a=(n=(i=e.errorTracking)==null?void 0:i.suppressionRules)!==null&&n!==void 0?n:[],o=(r=e.errorTracking)==null?void 0:r.captureExtensionExceptions;this.Jt=a,this._instance.persistence&&this._instance.persistence.register({[fy]:this.Jt,[hA]:o})}get Yt(){var e,n=!!this._instance.get_property(hA),i=this._instance.config.error_tracking.captureExtensionExceptions;return(e=i??n)!==null&&e!==void 0&&e}buildProperties(e,n){return this.Kt.buildFromUnknown(e,{syntheticException:n?.syntheticException,mechanism:{handled:n?.handled}})}sendExceptionEvent(e){var n=e.$exception_list;if(this.Xt(n)){if(this.Qt(n))return void Pv.info("Skipping exception capture because a suppression rule matched");if(!this.Yt&&this.Zt(n))return void Pv.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.ti(n))return void Pv.info("Skipping exception capture because it was thrown by the PostHog SDK")}return this._instance.capture("$exception",e,{_noTruncate:!0,_batchKey:"exceptionEvent"})}Qt(e){if(e.length===0)return!1;var n=e.reduce(((i,r)=>{var{type:a,value:o}=r;return ot(a)&&a.length>0&&i.$exception_types.push(a),ot(o)&&o.length>0&&i.$exception_values.push(o),i}),{$exception_types:[],$exception_values:[]});return this.Jt.some((i=>{var r=i.values.map((a=>{var o,s=XT[a.operator],l=Ae(a.value)?a.value:[a.value],c=(o=n[a.key])!==null&&o!==void 0?o:[];return l.length>0&&s(l,c)}));return i.type==="OR"?r.some(Boolean):r.every(Boolean)}))}Zt(e){return e.flatMap((n=>{var i,r;return(i=(r=n.stacktrace)==null?void 0:r.frames)!==null&&i!==void 0?i:[]})).some((n=>n.filename&&n.filename.startsWith("chrome-extension://")))}ti(e){if(e.length>0){var n,i,r,a,o=(n=(i=e[0].stacktrace)==null?void 0:i.frames)!==null&&n!==void 0?n:[],s=o[o.length-1];return(r=s==null||(a=s.filename)==null?void 0:a.includes("posthog.com/static"))!==null&&r!==void 0&&r}return!1}Xt(e){return!Ee(e)&&Ae(e)}},Zn=st("[FeatureFlags]"),_c=st("[FeatureFlags]",{debugEnabled:!0}),Gv="$active_feature_flags",Cs="$override_feature_flags",$A="$feature_flag_payloads",Sc="$override_feature_flag_payloads",FA="$feature_flag_request_id",UA="$feature_flag_evaluated_at",VA=t=>{var e={};for(var[n,i]of Jf(t||{}))i&&(e[n]=i);return e},k3=t=>{var e=t.flags;return e?(t.featureFlags=Object.fromEntries(Object.keys(e).map((n=>{var i;return[n,(i=e[n].variant)!==null&&i!==void 0?i:e[n].enabled]}))),t.featureFlagPayloads=Object.fromEntries(Object.keys(e).filter((n=>e[n].enabled)).filter((n=>{var i;return(i=e[n].metadata)==null?void 0:i.payload})).map((n=>{var i;return[n,(i=e[n].metadata)==null?void 0:i.payload]})))):Zn.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),t},R3=(function(t){return t.FeatureFlags="feature_flags",t.Recordings="recordings",t})({}),Uy=class{constructor(e){this.ii=!1,this.ei=!1,this.ri=!1,this.si=!1,this.ni=!1,this.oi=!1,this.ai=!1,this._instance=e,this.featureFlagEventHandlers=[]}li(){var e=this._instance.config.evaluation_environments;return e!=null&&e.length?e.filter((n=>{var i=n&&typeof n=="string"&&n.trim().length>0;return i||Zn.error("Invalid evaluation environment found:",n,"Expected non-empty string"),i})):[]}ui(){return this.li().length>0}flags(){if(this._instance.config.__preview_remote_config)this.oi=!0;else{var e=!this.hi&&(this._instance.config.advanced_disable_feature_flags||this._instance.config.advanced_disable_feature_flags_on_first_load);this.vi({disableFlags:e})}}get hasLoadedFlags(){return this.ei}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var e=this._instance.get_property(py),n=this._instance.get_property(Cs),i=this._instance.get_property(Sc);if(!i&&!n)return e||{};var r=Ye({},e||{}),a=[...new Set([...Object.keys(i||{}),...Object.keys(n||{})])];for(var o of a){var s,l,c=r[o],u=n?.[o],f=I(u)?(s=c?.enabled)!==null&&s!==void 0&&s:!!u,h=I(u)?c.variant:typeof u=="string"?u:void 0,g=i?.[o],_=j({},c,{enabled:f,variant:f?h??c?.variant:void 0});f!==c?.enabled&&(_.original_enabled=c?.enabled),h!==c?.variant&&(_.original_variant=c?.variant),g&&(_.metadata=j({},c?.metadata,{payload:g,original_payload:c==null||(l=c.metadata)==null?void 0:l.payload})),r[o]=_}return this.ii||(Zn.warn(" Overriding feature flag details!",{flagDetails:e,overriddenPayloads:i,finalDetails:r}),this.ii=!0),r}getFlagVariants(){var e=this._instance.get_property(Rs),n=this._instance.get_property(Cs);if(!n)return e||{};for(var i=Ye({},e),r=Object.keys(n),a=0;a<r.length;a++)i[r[a]]=n[r[a]];return this.ii||(Zn.warn(" Overriding feature flags!",{enabledFlags:e,overriddenFlags:n,finalFlags:i}),this.ii=!0),i}getFlagPayloads(){var e=this._instance.get_property($A),n=this._instance.get_property(Sc);if(!n)return e||{};for(var i=Ye({},e||{}),r=Object.keys(n),a=0;a<r.length;a++)i[r[a]]=n[r[a]];return this.ii||(Zn.warn(" Overriding feature flag payloads!",{flagPayloads:e,overriddenPayloads:n,finalPayloads:i}),this.ii=!0),i}reloadFeatureFlags(){this.si||this._instance.config.advanced_disable_feature_flags||this.hi||(this.hi=setTimeout((()=>{this.vi()}),5))}di(){clearTimeout(this.hi),this.hi=void 0}ensureFlagsLoaded(){this.ei||this.ri||this.hi||this.reloadFeatureFlags()}setAnonymousDistinctId(e){this.$anon_distinct_id=e}setReloadingPaused(e){this.si=e}vi(e){var n;if(this.di(),!this._instance.O())if(this.ri)this.ni=!0;else{var i={token:this._instance.config.token,distinct_id:this._instance.get_distinct_id(),groups:this._instance.getGroups(),$anon_distinct_id:this.$anon_distinct_id,person_properties:j({},((n=this._instance.persistence)==null?void 0:n.get_initial_props())||{},this._instance.get_property(Tc)||{}),group_properties:this._instance.get_property(Ja)};(e!=null&&e.disableFlags||this._instance.config.advanced_disable_feature_flags)&&(i.disable_flags=!0),this.ui()&&(i.evaluation_environments=this.li());var r=this._instance.config.__preview_remote_config,a=r?"/flags/?v=2":"/flags/?v=2&config=true",o=this._instance.config.advanced_only_evaluate_survey_feature_flags?"&only_evaluate_survey_feature_flags=true":"",s=this._instance.requestRouter.endpointFor("flags",a+o);r&&(i.timezone=GT()),this.ri=!0,this._instance.ci({method:"POST",url:s,data:i,compression:this._instance.config.disable_compression?void 0:Xi.Base64,timeout:this._instance.config.feature_flag_request_timeout_ms,callback:l=>{var c,u,f=!0;if(l.statusCode===200&&(this.ni||(this.$anon_distinct_id=void 0),f=!1),this.ri=!1,this.oi||(this.oi=!0,this._instance.fi((u=l.json)!==null&&u!==void 0?u:{})),!i.disable_flags||this.ni)if(this.ai=!f,l.json&&(c=l.json.quotaLimited)!=null&&c.includes(R3.FeatureFlags))Zn.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more.");else{var h;i.disable_flags||this.receivedFeatureFlags((h=l.json)!==null&&h!==void 0?h:{},f),this.ni&&(this.ni=!1,this.vi())}}})}}getFeatureFlag(e,n){if(n===void 0&&(n={}),this.ei||this.getFlags()&&this.getFlags().length>0){var i=this.getFlagVariants()[e],r=""+i,a=this._instance.get_property(FA)||void 0,o=this._instance.get_property(UA)||void 0,s=this._instance.get_property(ap)||{};if((n.send_event||!("send_event"in n))&&(!(e in s)||!s[e].includes(r))){var l,c,u,f,h,g,_,b,w;Ae(s[e])?s[e].push(r):s[e]=[r],(l=this._instance.persistence)==null||l.register({[ap]:s});var d=this.getFeatureFlagDetails(e),p={$feature_flag:e,$feature_flag_response:i,$feature_flag_payload:this.getFeatureFlagPayload(e)||null,$feature_flag_request_id:a,$feature_flag_evaluated_at:o,$feature_flag_bootstrapped_response:((c=this._instance.config.bootstrap)==null||(c=c.featureFlags)==null?void 0:c[e])||null,$feature_flag_bootstrapped_payload:((u=this._instance.config.bootstrap)==null||(u=u.featureFlagPayloads)==null?void 0:u[e])||null,$used_bootstrap_value:!this.ai};I(d==null||(f=d.metadata)==null?void 0:f.version)||(p.$feature_flag_version=d.metadata.version);var m,v=(h=d==null||(g=d.reason)==null?void 0:g.description)!==null&&h!==void 0?h:d==null||(_=d.reason)==null?void 0:_.code;v&&(p.$feature_flag_reason=v),d!=null&&(b=d.metadata)!=null&&b.id&&(p.$feature_flag_id=d.metadata.id),I(d?.original_variant)&&I(d?.original_enabled)||(p.$feature_flag_original_response=I(d.original_variant)?d.original_enabled:d.original_variant),d!=null&&(w=d.metadata)!=null&&w.original_payload&&(p.$feature_flag_original_payload=d==null||(m=d.metadata)==null?void 0:m.original_payload),this._instance.capture("$feature_flag_called",p)}return i}Zn.warn('getFeatureFlag for key "'+e+`" failed. Feature flags didn't load in time.`)}getFeatureFlagDetails(e){return this.getFlagsWithDetails()[e]}getFeatureFlagPayload(e){return this.getFlagPayloads()[e]}getRemoteConfigPayload(e,n){var i=this._instance.config.token,r={distinct_id:this._instance.get_distinct_id(),token:i};this.ui()&&(r.evaluation_environments=this.li()),this._instance.ci({method:"POST",url:this._instance.requestRouter.endpointFor("flags","/flags/?v=2&config=true"),data:r,compression:this._instance.config.disable_compression?void 0:Xi.Base64,timeout:this._instance.config.feature_flag_request_timeout_ms,callback:a=>{var o,s=(o=a.json)==null?void 0:o.featureFlagPayloads;n(s?.[e]||void 0)}})}isFeatureEnabled(e,n){if(n===void 0&&(n={}),this.ei||this.getFlags()&&this.getFlags().length>0){var i=this.getFeatureFlag(e,n);return I(i)?void 0:!!i}Zn.warn('isFeatureEnabled for key "'+e+`" failed. Feature flags didn't load in time.`)}addFeatureFlagsHandler(e){this.featureFlagEventHandlers.push(e)}removeFeatureFlagsHandler(e){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((n=>n!==e))}receivedFeatureFlags(e,n){if(this._instance.persistence){this.ei=!0;var i=this.getFlagVariants(),r=this.getFlagPayloads(),a=this.getFlagsWithDetails();(function(o,s,l,c,u){l===void 0&&(l={}),c===void 0&&(c={}),u===void 0&&(u={});var f=k3(o),h=f.flags,g=f.featureFlags,_=f.featureFlagPayloads;if(g){var b=o.requestId,w=o.evaluatedAt;if(Ae(g)){Zn.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var d={};if(g)for(var p=0;p<g.length;p++)d[g[p]]=!0;s&&s.register({[Gv]:g,[Rs]:d})}else{var m=g,v=_,S=h;o.errorsWhileComputingFlags&&(m=j({},l,m),v=j({},c,v),S=j({},u,S)),s&&s.register(j({[Gv]:Object.keys(VA(m)),[Rs]:m||{},[$A]:v||{},[py]:S||{}},b?{[FA]:b}:{},w?{[UA]:w}:{}))}}})(e,this._instance.persistence,i,r,a),this.pi(n)}}override(e,n){n===void 0&&(n=!1),Zn.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:e,suppressWarning:n})}overrideFeatureFlags(e){if(!this._instance.__loaded||!this._instance.persistence)return Zn.uninitializedWarning("posthog.featureFlags.overrideFeatureFlags");if(e===!1)return this._instance.persistence.unregister(Cs),this._instance.persistence.unregister(Sc),this.pi(),_c.info("All overrides cleared");if(e&&typeof e=="object"&&("flags"in e||"payloads"in e)){var n,i=e;if(this.ii=!!((n=i.suppressWarning)!==null&&n!==void 0&&n),"flags"in i){if(i.flags===!1)this._instance.persistence.unregister(Cs),_c.info("Flag overrides cleared");else if(i.flags){if(Ae(i.flags)){for(var r={},a=0;a<i.flags.length;a++)r[i.flags[a]]=!0;this._instance.persistence.register({[Cs]:r})}else this._instance.persistence.register({[Cs]:i.flags});_c.info("Flag overrides set",{flags:i.flags})}}return"payloads"in i&&(i.payloads===!1?(this._instance.persistence.unregister(Sc),_c.info("Payload overrides cleared")):i.payloads&&(this._instance.persistence.register({[Sc]:i.payloads}),_c.info("Payload overrides set",{payloads:i.payloads}))),void this.pi()}this.pi()}onFeatureFlags(e){if(this.addFeatureFlagsHandler(e),this.ei){var{flags:n,flagVariants:i}=this.gi();e(n,i)}return()=>this.removeFeatureFlagsHandler(e)}updateEarlyAccessFeatureEnrollment(e,n,i){var r,a=(this._instance.get_property(Ac)||[]).find((c=>c.flagKey===e)),o={["$feature_enrollment/"+e]:n},s={$feature_flag:e,$feature_enrollment:n,$set:o};a&&(s.$early_access_feature_name=a.name),i&&(s.$feature_enrollment_stage=i),this._instance.capture("$feature_enrollment_update",s),this.setPersonPropertiesForFlags(o,!1);var l=j({},this.getFlagVariants(),{[e]:n});(r=this._instance.persistence)==null||r.register({[Gv]:Object.keys(VA(l)),[Rs]:l}),this.pi()}getEarlyAccessFeatures(e,n,i){n===void 0&&(n=!1);var r=this._instance.get_property(Ac),a=i?"&"+i.map((o=>"stage="+o)).join("&"):"";if(r&&!n)return e(r);this._instance.ci({url:this._instance.requestRouter.endpointFor("api","/api/early_access_features/?token="+this._instance.config.token+a),method:"GET",callback:o=>{var s,l;if(o.json){var c=o.json.earlyAccessFeatures;return(s=this._instance.persistence)==null||s.unregister(Ac),(l=this._instance.persistence)==null||l.register({[Ac]:c}),e(c)}}})}gi(){var e=this.getFlags(),n=this.getFlagVariants();return{flags:e.filter((i=>n[i])),flagVariants:Object.keys(n).filter((i=>n[i])).reduce(((i,r)=>(i[r]=n[r],i)),{})}}pi(e){var{flags:n,flagVariants:i}=this.gi();this.featureFlagEventHandlers.forEach((r=>r(n,i,{errorsLoading:e})))}setPersonPropertiesForFlags(e,n){n===void 0&&(n=!0);var i=this._instance.get_property(Tc)||{};this._instance.register({[Tc]:j({},i,e)}),n&&this._instance.reloadFeatureFlags()}resetPersonPropertiesForFlags(){this._instance.unregister(Tc)}setGroupPropertiesForFlags(e,n){n===void 0&&(n=!0);var i=this._instance.get_property(Ja)||{};Object.keys(i).length!==0&&Object.keys(i).forEach((r=>{i[r]=j({},i[r],e[r]),delete e[r]})),this._instance.register({[Ja]:j({},i,e)}),n&&this._instance.reloadFeatureFlags()}resetGroupPropertiesForFlags(e){if(e){var n=this._instance.get_property(Ja)||{};this._instance.register({[Ja]:j({},n,{[e]:{}})})}else this._instance.unregister(Ja)}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}},O3=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],Nc=class{constructor(e,n){this.F=e,this.props={},this.mi=!1,this.yi=(i=>{var r="";return i.token&&(r=i.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),i.persistence_name?"ph_"+i.persistence_name:"ph_"+r+"_posthog"})(e),this.Y=this.bi(e),this.load(),e.debug&&$.info("Persistence loaded",e.persistence,j({},this.props)),this.update_config(e,e,n),this.save()}isDisabled(){return!!this.wi}bi(e){O3.indexOf(e.persistence.toLowerCase())===-1&&($.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var n=e.persistence.toLowerCase();return n==="localstorage"&&Ue.H()?Ue:n==="localstorage+cookie"&&Yf.H()?Yf:n==="sessionstorage"&&St.H()?St:n==="memory"?QL:n==="cookie"?di:Yf.H()?Yf:di}properties(){var e={};return Re(this.props,(function(n,i){if(i===Rs&&ft(n))for(var r=Object.keys(n),a=0;a<r.length;a++)e["$feature/"+r[a]]=n[r[a]];else s=i,l=!1,(Qi(o=LL)?l:nA&&o.indexOf===nA?o.indexOf(s)!=-1:(Re(o,(function(c){if(l||(l=c===s))return ip})),l))||(e[i]=n);var o,s,l})),e}load(){if(!this.wi){var e=this.Y.W(this.yi);e&&(this.props=Ye({},e))}}save(){this.wi||this.Y.G(this.yi,this.props,this.xi,this.Si,this.Ei,this.F.debug)}remove(){this.Y.V(this.yi,!1),this.Y.V(this.yi,!0)}clear(){this.remove(),this.props={}}register_once(e,n,i){if(ft(e)){I(n)&&(n="None"),this.xi=I(i)?this.$i:i;var r=!1;if(Re(e,((a,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==n||(this.props[o]=a,r=!0)})),r)return this.save(),!0}return!1}register(e,n){if(ft(e)){this.xi=I(n)?this.$i:n;var i=!1;if(Re(e,((r,a)=>{e.hasOwnProperty(a)&&this.props[a]!==r&&(this.props[a]=r,i=!0)})),i)return this.save(),!0}return!1}unregister(e){e in this.props&&(delete this.props[e],this.save())}update_campaign_params(){if(!this.mi){var e=FT(this.F.custom_campaign_params,this.F.mask_personal_data_properties,this.F.custom_personal_data_properties);ks(ab(e))||this.register(e),this.mi=!0}}update_search_keyword(){var e;this.register((e=B?.referrer)?VT(e):{})}update_referrer_info(){var e;this.register_once({$referrer:jT(),$referring_domain:B!=null&&B.referrer&&((e=up(B.referrer))==null?void 0:e.host)||"$direct"},void 0)}set_initial_person_info(){this.props[vy]||this.props[yy]||this.register_once({[op]:qT(this.F.mask_personal_data_properties,this.F.custom_personal_data_properties)},void 0)}get_initial_props(){var e={};Re([yy,vy],(o=>{var s=this.props[o];s&&Re(s,(function(l,c){e["$initial_"+Xv(c)]=l}))}));var n,i,r=this.props[op];if(r){var a=(n=PT(r),i={},Re(n,(function(o,s){i["$initial_"+Xv(s)]=o})),i);Ye(e,a)}return e}safe_merge(e){return Re(this.props,(function(n,i){i in e||(e[i]=n)})),e}update_config(e,n,i){if(this.$i=this.xi=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!i),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie),e.persistence!==n.persistence){var r=this.bi(e),a=this.props;this.clear(),this.Y=r,this.props=a,this.save()}}set_disabled(e){this.wi=e,this.wi?this.remove():this.save()}set_cross_subdomain(e){e!==this.Si&&(this.Si=e,this.remove(),this.save())}set_secure(e){e!==this.Ei&&(this.Ei=e,this.remove(),this.save())}set_event_timer(e,n){var i=this.props[Cc]||{};i[e]=n,this.props[Cc]=i,this.save()}remove_event_timer(e){var n=(this.props[Cc]||{})[e];return I(n)||(delete this.props[Cc][e],this.save()),n}get_property(e){return this.props[e]}set_property(e,n){this.props[e]=n,this.save()}},xc=(function(t){return t.Activation="events",t.Cancellation="cancelEvents",t})({}),NB=(function(t){return t.Button="button",t.Tab="tab",t.Selector="selector",t})({}),DB=(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})({}),LB=(function(t){return t.Top="top",t.Left="left",t.Right="right",t.Bottom="bottom",t})({}),Zv=(function(t){return t.Popover="popover",t.API="api",t.Widget="widget",t.ExternalSurvey="external_survey",t})({}),HB=(function(t){return t.Open="open",t.MultipleChoice="multiple_choice",t.SingleChoice="single_choice",t.Rating="rating",t.Link="link",t})({}),IB=(function(t){return t.NextQuestion="next_question",t.End="end",t.ResponseBased="response_based",t.SpecificQuestion="specific_question",t})({}),zB=(function(t){return t.Once="once",t.Recurring="recurring",t.Always="always",t})({}),tp=(function(t){return t.SHOWN="survey shown",t.DISMISSED="survey dismissed",t.SENT="survey sent",t})({}),jA=(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})({}),JT=(function(t){return t.Popover="popover",t.Inline="inline",t})({}),$c=class{constructor(){this.ki={},this.ki={}}on(e,n){return this.ki[e]||(this.ki[e]=[]),this.ki[e].push(n),()=>{this.ki[e]=this.ki[e].filter((i=>i!==n))}}emit(e,n){for(var i of this.ki[e]||[])i(n);for(var r of this.ki["*"]||[])r(e,n)}};function As(t,e,n){if(Ee(t))return!1;switch(n){case"exact":return t===e;case"contains":var i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(i,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}var Vy=class{constructor(e){this.Pi=new $c,this.Ti=(n,i)=>this.Ri(n,i)&&this.Ii(n,i)&&this.Fi(n,i)&&this.Ci(n,i),this.Ri=(n,i)=>i==null||!i.event||n?.event===i?.event,this._instance=e,this.Mi=new Set,this.Oi=new Set}init(){var e;if(!I((e=this._instance)==null?void 0:e.Ai)){var n;(n=this._instance)==null||n.Ai(((i,r)=>{this.on(i,r)}))}}register(e){var n,i;if(!I((n=this._instance)==null?void 0:n.Ai)&&(e.forEach((o=>{var s,l;(s=this.Oi)==null||s.add(o),(l=o.steps)==null||l.forEach((c=>{var u;(u=this.Mi)==null||u.add(c?.event||"")}))})),(i=this._instance)!=null&&i.autocapture)){var r,a=new Set;e.forEach((o=>{var s;(s=o.steps)==null||s.forEach((l=>{l!=null&&l.selector&&a.add(l?.selector)}))})),(r=this._instance)==null||r.autocapture.setElementSelectors(a)}}on(e,n){var i;n!=null&&e.length!=0&&(this.Mi.has(e)||this.Mi.has(n?.event))&&this.Oi&&((i=this.Oi)==null?void 0:i.size)>0&&this.Oi.forEach((r=>{this.Di(n,r)&&this.Pi.emit("actionCaptured",r.name)}))}ji(e){this.onAction("actionCaptured",(n=>e(n)))}Di(e,n){if(n?.steps==null)return!1;for(var i of n.steps)if(this.Ti(e,i))return!0;return!1}onAction(e,n){return this.Pi.on(e,n)}Ii(e,n){if(n!=null&&n.url){var i,r=e==null||(i=e.properties)==null?void 0:i.$current_url;if(!r||typeof r!="string"||!As(r,n.url,n.url_matching||"contains"))return!1}return!0}Fi(e,n){return!!this.Li(e,n)&&!!this.Ni(e,n)&&!!this.Ui(e,n)}Li(e,n){var i;if(n==null||!n.href)return!0;var r=this.zi(e);if(r.length>0)return r.some((s=>As(s.href,n.href,n.href_matching||"exact")));var a,o=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!o&&As((a=o.match(/(?::|")href="(.*?)"/))?a[1]:"",n.href,n.href_matching||"exact")}Ni(e,n){var i;if(n==null||!n.text)return!0;var r=this.zi(e);if(r.length>0)return r.some((c=>As(c.text,n.text,n.text_matching||"exact")||As(c.$el_text,n.text,n.text_matching||"exact")));var a,o,s,l=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";return!!l&&(a=(function(c){for(var u,f=[],h=/(?::|")text="(.*?)"/g;!Ee(u=h.exec(c));)f.includes(u[1])||f.push(u[1]);return f})(l),o=n.text,s=n.text_matching||"exact",a.some((c=>As(c,o,s))))}Ui(e,n){var i,r;if(n==null||!n.selector)return!0;var a=e==null||(i=e.properties)==null?void 0:i.$element_selectors;if(a!=null&&a.includes(n.selector))return!0;var o=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";if(n.selector_regex&&o)try{return new RegExp(n.selector_regex).test(o)}catch{return!1}return!1}zi(e){var n;return(e==null||(n=e.properties)==null?void 0:n.$elements)==null?[]:e?.properties.$elements}Ci(e,n){return n==null||!n.properties||n.properties.length===0||QT(n.properties.reduce(((i,r)=>{var a=Ae(r.value)?r.value.map(String):r.value!=null?[String(r.value)]:[];return i[r.key]={values:a,operator:r.operator||"exact"},i}),{}),e?.properties)}},Se=st("[Surveys]"),jy="seenSurvey_",M3=(t,e)=>{var n="$survey_"+e+"/"+t.id;return t.current_iteration&&t.current_iteration>0&&(n="$survey_"+e+"/"+t.id+"/"+t.current_iteration),n},qA=t=>{var e=""+jy+t.id;return t.current_iteration&&t.current_iteration>0&&(e=""+jy+t.id+"_"+t.current_iteration),e},N3=[Zv.Popover,Zv.Widget,Zv.API],D3={ignoreConditions:!1,ignoreDelay:!1,displayType:JT.Popover},qy=class{constructor(e){this._instance=e,this.Hi=new Map,this.Bi=new Map,this.qi=new Map}Wi(e,n){return!!e&&QT(e.propertyFilters,n?.properties)}Gi(e,n){var i=new Map;return e.forEach((r=>{var a;(a=r.conditions)==null||(a=a[n])==null||(a=a.values)==null||a.forEach((o=>{if(o!=null&&o.name){var s=i.get(o.name)||[];s.push(r.id),i.set(o.name,s)}}))})),i}Vi(e,n,i){var r,a=(i===xc.Activation?this.Hi:this.Bi).get(e),o=[];return(r=this._instance)==null||r.getSurveys((s=>{o=s.filter((l=>a?.includes(l.id)))})),o.filter((s=>{var l,c=(l=s.conditions)==null||(l=l[i])==null||(l=l.values)==null?void 0:l.find((u=>u.name===e));return this.Wi(c,n)}))}register(e){var n;I((n=this._instance)==null?void 0:n.Ai)||(this.Ji(e),this.Ki(e))}Ki(e){var n=e.filter((i=>{var r,a;return((r=i.conditions)==null?void 0:r.actions)&&((a=i.conditions)==null||(a=a.actions)==null||(a=a.values)==null?void 0:a.length)>0}));n.length!==0&&(this.Yi==null&&(this.Yi=new Vy(this._instance),this.Yi.init(),this.Yi.ji((i=>{this.onAction(i)}))),n.forEach((i=>{var r,a,o,s,l;i.conditions&&(r=i.conditions)!=null&&r.actions&&(a=i.conditions)!=null&&(a=a.actions)!=null&&a.values&&((o=i.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((s=this.Yi)==null||s.register(i.conditions.actions.values),(l=i.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((c=>{if(c&&c.name){var u=this.qi.get(c.name);u&&u.push(i.id),this.qi.set(c.name,u||[i.id])}})))})))}Ji(e){var n,i=e.filter((a=>{var o,s;return((o=a.conditions)==null?void 0:o.events)&&((s=a.conditions)==null||(s=s.events)==null||(s=s.values)==null?void 0:s.length)>0})),r=e.filter((a=>{var o,s;return((o=a.conditions)==null?void 0:o.cancelEvents)&&((s=a.conditions)==null||(s=s.cancelEvents)==null||(s=s.values)==null?void 0:s.length)>0}));(i.length!==0||r.length!==0)&&((n=this._instance)==null||n.Ai(((a,o)=>{this.onEvent(a,o)})),this.Hi=this.Gi(e,xc.Activation),this.Bi=this.Gi(e,xc.Cancellation))}onEvent(e,n){var i,r=((i=this._instance)==null||(i=i.persistence)==null?void 0:i.props[Zf])||[];if(tp.SHOWN===e&&n&&r.length>0){var a;Se.info("survey event matched, removing survey from activated surveys",{event:e,eventPayload:n,existingActivatedSurveys:r});var o=n==null||(a=n.properties)==null?void 0:a.$survey_id;if(o){var s=r.indexOf(o);s>=0&&(r.splice(s,1),this.Xi(r))}}else{if(this.Bi.has(e)){var l=this.Vi(e,n,xc.Cancellation);l.length>0&&(Se.info("cancel event matched, cancelling surveys",{event:e,surveysToCancel:l.map((u=>u.id))}),l.forEach((u=>{var f,h=r.indexOf(u.id);h>=0&&r.splice(h,1),(f=this._instance)==null||f.cancelPendingSurvey(u.id)})),this.Xi(r))}if(this.Hi.has(e)){Se.info("survey event name matched",{event:e,eventPayload:n,surveys:this.Hi.get(e)});var c=this.Vi(e,n,xc.Activation);this.Xi(r.concat(c.map((u=>u.id))||[]))}}}onAction(e){var n,i=((n=this._instance)==null||(n=n.persistence)==null?void 0:n.props[Zf])||[];this.qi.has(e)&&this.Xi(i.concat(this.qi.get(e)||[]))}Xi(e){var n;Se.info("updating activated surveys",{activatedSurveys:e}),(n=this._instance)==null||(n=n.persistence)==null||n.register({[Zf]:[...new Set(e)]})}getSurveys(){var e,n=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[Zf];return n||[]}getEventToSurveys(){return this.Hi}Qi(){return this.Yi}},Py=class{constructor(e){this.Zi=void 0,this._surveyManager=null,this.te=!1,this.ie=!1,this.ee=[],this._instance=e,this._surveyEventReceiver=null}onRemoteConfig(e){if(!this._instance.config.disable_surveys){var n=e.surveys;if(Ee(n))return Se.warn("Flags not loaded yet. Not loading surveys.");var i=Ae(n);this.Zi=i?n.length>0:n,Se.info("flags response received, isSurveysEnabled: "+this.Zi),this.loadIfEnabled()}}reset(){localStorage.removeItem("lastSeenSurveyDate");for(var e=[],n=0;n<localStorage.length;n++){var i=localStorage.key(n);(i!=null&&i.startsWith(jy)||i!=null&&i.startsWith("inProgressSurvey_"))&&e.push(i)}e.forEach((r=>localStorage.removeItem(r)))}loadIfEnabled(){if(!this._surveyManager)if(this.ie)Se.info("Already initializing surveys, skipping...");else if(this._instance.config.disable_surveys)Se.info("Disabled. Not loading surveys.");else if(this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())Se.info("Not loading surveys in cookieless mode without consent.");else{var e=J?.__PosthogExtensions__;if(e){if(!I(this.Zi)||this._instance.config.advanced_enable_surveys){var n=this.Zi||this._instance.config.advanced_enable_surveys;this.ie=!0;try{var i=e.generateSurveys;if(i)return void this.re(i,n);var r=e.loadExternalDependency;if(!r)return void this.se("PostHog loadExternalDependency extension not found.");r(this._instance,"surveys",(a=>{a||!e.generateSurveys?this.se("Could not load surveys script",a):this.re(e.generateSurveys,n)}))}catch(a){throw this.se("Error initializing surveys",a),a}finally{this.ie=!1}}}else Se.error("PostHog Extensions not found.")}}re(e,n){this._surveyManager=e(this._instance,n),this._surveyEventReceiver=new qy(this._instance),Se.info("Surveys loaded successfully"),this.ne({isLoaded:!0})}se(e,n){Se.error(e,n),this.ne({isLoaded:!1,error:e})}onSurveysLoaded(e){return this.ee.push(e),this._surveyManager&&this.ne({isLoaded:!0}),()=>{this.ee=this.ee.filter((n=>n!==e))}}getSurveys(e,n){if(n===void 0&&(n=!1),this._instance.config.disable_surveys)return Se.info("Disabled. Not loading surveys."),e([]);var i=this._instance.get_property(hy);if(i&&!n)return e(i,{isLoaded:!0});if(this.te)return e([],{isLoaded:!1,error:"Surveys are already being loaded"});try{this.te=!0,this._instance.ci({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this._instance.config.token),method:"GET",timeout:this._instance.config.surveys_request_timeout_ms,callback:r=>{var a;this.te=!1;var o=r.statusCode;if(o!==200||!r.json){var s="Surveys API could not be loaded, status: "+o;return Se.error(s),e([],{isLoaded:!1,error:s})}var l,c=r.json.surveys||[],u=c.filter((f=>(function(h){return!(!h.start_date||h.end_date)})(f)&&((function(h){var g;return!((g=h.conditions)==null||(g=g.events)==null||(g=g.values)==null||!g.length)})(f)||(function(h){var g;return!((g=h.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(f))));return u.length>0&&((l=this._surveyEventReceiver)==null||l.register(u)),(a=this._instance.persistence)==null||a.register({[hy]:c}),e(c,{isLoaded:!0})}})}catch(r){throw this.te=!1,r}}ne(e){for(var n of this.ee)try{if(!e.isLoaded)return n([],e);this.getSurveys(n)}catch(i){Se.error("Error in survey callback",i)}}getActiveMatchingSurveys(e,n){if(n===void 0&&(n=!1),!Ee(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(e,n);Se.warn("init was not called")}oe(e){var n=null;return this.getSurveys((i=>{var r;n=(r=i.find((a=>a.id===e)))!==null&&r!==void 0?r:null})),n}ae(e){if(Ee(this._surveyManager))return{eligible:!1,reason:"SDK is not enabled or survey functionality is not yet loaded"};var n=typeof e=="string"?this.oe(e):e;return n?this._surveyManager.checkSurveyEligibility(n):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(e){if(Ee(this._surveyManager))return Se.warn("init was not called"),{visible:!1,disabledReason:"SDK is not enabled or survey functionality is not yet loaded"};var n=this.ae(e);return{visible:n.eligible,disabledReason:n.reason}}canRenderSurveyAsync(e,n){return Ee(this._surveyManager)?(Se.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:"SDK is not enabled or survey functionality is not yet loaded"})):new Promise((i=>{this.getSurveys((r=>{var a,o=(a=r.find((l=>l.id===e)))!==null&&a!==void 0?a:null;if(o){var s=this.ae(o);i({visible:s.eligible,disabledReason:s.reason})}else i({visible:!1,disabledReason:"Survey not found"})}),n)}))}renderSurvey(e,n){var i;if(Ee(this._surveyManager))Se.warn("init was not called");else{var r=typeof e=="string"?this.oe(e):e;if(r!=null&&r.id)if(N3.includes(r.type)){var a=B?.querySelector(n);if(a)return(i=r.appearance)!=null&&i.surveyPopupDelaySeconds?(Se.info("Rendering survey "+r.id+" with delay of "+r.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var o,s;Se.info("Rendering survey "+r.id+" with delay of "+((o=r.appearance)==null?void 0:o.surveyPopupDelaySeconds)+" seconds"),(s=this._surveyManager)==null||s.renderSurvey(r,a),Se.info("Survey "+r.id+" rendered")}),1e3*r.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(r,a);Se.warn("Survey element not found")}else Se.warn("Surveys of type "+r.type+" cannot be rendered in the app");else Se.warn("Survey not found")}}displaySurvey(e,n){var i;if(Ee(this._surveyManager))Se.warn("init was not called");else{var r=this.oe(e);if(r){var a=r;if((i=r.appearance)!=null&&i.surveyPopupDelaySeconds&&n.ignoreDelay&&(a=j({},r,{appearance:j({},r.appearance,{surveyPopupDelaySeconds:0})})),n.ignoreConditions===!1){var o=this.canRenderSurvey(r);if(!o.visible)return void Se.warn("Survey is not eligible to be displayed: ",o.disabledReason)}n.displayType!==JT.Inline?this._surveyManager.handlePopoverSurvey(a):this.renderSurvey(a,n.selector)}else Se.warn("Survey not found")}}cancelPendingSurvey(e){Ee(this._surveyManager)?Se.warn("init was not called"):this._surveyManager.cancelSurvey(e)}},PA=st("[RateLimiter]"),Gy=class{constructor(e){var n,i;this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=r=>{var a=r.text;if(a&&a.length)try{(JSON.parse(a).quota_limited||[]).forEach((o=>{PA.info((o||"events")+" is quota limited."),this.serverLimits[o]=new Date().getTime()+6e4}))}catch(o){return void PA.warn('could not rate limit - continuing. Error: "'+o?.message+'"',{text:a})}},this.instance=e,this.captureEventsPerSecond=((n=e.config.rate_limiting)==null?void 0:n.events_per_second)||10,this.captureEventsBurstLimit=Math.max(((i=e.config.rate_limiting)==null?void 0:i.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond),this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}clientRateLimitContext(e){var n,i,r;e===void 0&&(e=!1);var a=new Date().getTime(),o=(n=(i=this.instance.persistence)==null?void 0:i.get_property(my))!==null&&n!==void 0?n:{tokens:this.captureEventsBurstLimit,last:a};o.tokens+=(a-o.last)/1e3*this.captureEventsPerSecond,o.last=a,o.tokens>this.captureEventsBurstLimit&&(o.tokens=this.captureEventsBurstLimit);var s=o.tokens<1;return s||e||(o.tokens=Math.max(0,o.tokens-1)),!s||this.lastEventRateLimited||e||this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited. Config is set to "+this.captureEventsPerSecond+" events per second and "+this.captureEventsBurstLimit+" events burst limit."},{skip_client_rate_limiting:!0}),this.lastEventRateLimited=s,(r=this.instance.persistence)==null||r.set_property(my,o),{isRateLimited:s,remainingTokens:o.tokens}}isServerRateLimited(e){var n=this.serverLimits[e||"events"]||!1;return n!==!1&&new Date().getTime()<n}},Qa=st("[RemoteConfig]"),Zy=class{constructor(e){this._instance=e}get remoteConfig(){var e;return(e=J._POSTHOG_REMOTE_CONFIG)==null||(e=e[this._instance.config.token])==null?void 0:e.config}le(e){var n,i;(n=J.__PosthogExtensions__)!=null&&n.loadExternalDependency?(i=J.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,"remote-config",(()=>e(this.remoteConfig))):(Qa.error("PostHog Extensions not found. Cannot load remote config."),e())}ue(e){this._instance.ci({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:n=>{e(n.json)}})}load(){try{if(this.remoteConfig)return Qa.info("Using preloaded remote config",this.remoteConfig),void this.fi(this.remoteConfig);if(this._instance.O())return void Qa.warn("Remote config is disabled. Falling back to local config.");this.le((e=>{if(!e)return Qa.info("No config found after loading remote JS config. Falling back to JSON."),void this.ue((n=>{this.fi(n)}));this.fi(e)}))}catch(e){Qa.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()):Qa.info("__preview_remote_config is disabled. Logging config instead",e):Qa.error("Failed to fetch remote config from PostHog.")}},Yy=3e3,Wy=class{constructor(e,n){this.he=!0,this.ve=[],this.de=ci(n?.flush_interval_ms||Yy,250,5e3,$.createLogger("flush interval"),Yy),this.ce=e}enqueue(e){this.ve.push(e),this.fe||this.pe()}unload(){this.ge();var e=this.ve.length>0?this._e():{},n=Object.values(e);[...n.filter((i=>i.url.indexOf("/e")===0)),...n.filter((i=>i.url.indexOf("/e")!==0))].map((i=>{this.ce(j({},i,{transport:"sendBeacon"}))}))}enable(){this.he=!1,this.pe()}pe(){var e=this;this.he||(this.fe=setTimeout((()=>{if(this.ge(),this.ve.length>0){var n=this._e(),i=function(){var a=n[r],o=new Date().getTime();a.data&&Ae(a.data)&&Re(a.data,(s=>{s.offset=Math.abs(s.timestamp-o),delete s.timestamp})),e.ce(a)};for(var r in n)i()}}),this.de))}ge(){clearTimeout(this.fe),this.fe=void 0}_e(){var e={};return Re(this.ve,(n=>{var i,r=n,a=(r?r.batchKey:null)||r.url;I(e[a])&&(e[a]=j({},r,{data:[]})),(i=e[a].data)==null||i.push(r.data)})),this.ve=[],e}},L3=["retriesPerformedSoFar"],Ky=class{constructor(e){this.me=!1,this.ye=3e3,this.ve=[],this._instance=e,this.ve=[],this.be=!0,!I(R)&&"onLine"in R.navigator&&(this.be=R.navigator.onLine,this.we=()=>{this.be=!0,this.Dt()},this.xe=()=>{this.be=!1},tt(R,"online",this.we),tt(R,"offline",this.xe))}get length(){return this.ve.length}retriableRequest(e){var{retriesPerformedSoFar:n}=e,i=XA(e,L3);fi(n)&&n>0&&(i.url=vp(i.url,{retry_count:n})),this._instance.ci(j({},i,{callback:r=>{r.statusCode!==200&&(r.statusCode<400||r.statusCode>=500)&&(n??0)<10?this.Se(j({retriesPerformedSoFar:n},i)):i.callback==null||i.callback(r)}}))}Se(e){var n=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=n+1;var i=(function(o){var s=3e3*Math.pow(2,o),l=s/2,c=Math.min(18e5,s),u=(Math.random()-.5)*(c-l);return Math.ceil(c+u)})(n),r=Date.now()+i;this.ve.push({retryAt:r,requestOptions:e});var a="Enqueued failed request for retry in "+i;navigator.onLine||(a+=" (Browser is offline)"),$.warn(a),this.me||(this.me=!0,this.Ee())}Ee(){if(this.$e&&clearTimeout(this.$e),this.ve.length===0)return this.me=!1,void(this.$e=void 0);this.$e=setTimeout((()=>{this.be&&this.ve.length>0&&this.Dt(),this.Ee()}),this.ye)}Dt(){var e=Date.now(),n=[],i=this.ve.filter((a=>a.retryAt<e||(n.push(a),!1)));if(this.ve=n,i.length>0)for(var{requestOptions:r}of i)this.retriableRequest(r)}unload(){for(var{requestOptions:e}of(this.$e&&(clearTimeout(this.$e),this.$e=void 0),this.me=!1,I(R)||(this.we&&(R.removeEventListener("online",this.we),this.we=void 0),this.xe&&(R.removeEventListener("offline",this.xe),this.xe=void 0)),this.ve))try{this._instance.ci(j({},e,{transport:"sendBeacon"}))}catch(n){$.error(n)}this.ve=[]}},Xy=class{constructor(e){this.ke=()=>{var n,i,r,a;this.Pe||(this.Pe={});var o=this.scrollElement(),s=this.scrollY(),l=o?Math.max(0,o.scrollHeight-o.clientHeight):0,c=s+(o?.clientHeight||0),u=o?.scrollHeight||0;this.Pe.lastScrollY=Math.ceil(s),this.Pe.maxScrollY=Math.max(s,(n=this.Pe.maxScrollY)!==null&&n!==void 0?n:0),this.Pe.maxScrollHeight=Math.max(l,(i=this.Pe.maxScrollHeight)!==null&&i!==void 0?i:0),this.Pe.lastContentY=c,this.Pe.maxContentY=Math.max(c,(r=this.Pe.maxContentY)!==null&&r!==void 0?r:0),this.Pe.maxContentHeight=Math.max(u,(a=this.Pe.maxContentHeight)!==null&&a!==void 0?a:0)},this._instance=e}getContext(){return this.Pe}resetContext(){var e=this.Pe;return setTimeout(this.ke,0),e}startMeasuringScrollPosition(){tt(R,"scroll",this.ke,{capture:!0}),tt(R,"scrollend",this.ke,{capture:!0}),tt(R,"resize",this.ke)}scrollElement(){if(!this._instance.config.scroll_root_selector)return R?.document.documentElement;var e=Ae(this._instance.config.scroll_root_selector)?this._instance.config.scroll_root_selector:[this._instance.config.scroll_root_selector];for(var n of e){var i=R?.document.querySelector(n);if(i)return i}}scrollY(){if(this._instance.config.scroll_root_selector){var e=this.scrollElement();return e&&e.scrollTop||0}return R&&(R.scrollY||R.pageYOffset||R.document.documentElement.scrollTop)||0}scrollX(){if(this._instance.config.scroll_root_selector){var e=this.scrollElement();return e&&e.scrollLeft||0}return R&&(R.scrollX||R.pageXOffset||R.document.documentElement.scrollLeft)||0}},H3=t=>qT(t?.config.mask_personal_data_properties,t?.config.custom_personal_data_properties),bp=class{constructor(e,n,i,r){this.Te=a=>{var o=this.Re();if(!o||o.sessionId!==a){var s={sessionId:a,props:this.Ie(this._instance)};this.Fe.register({[gy]:s})}},this._instance=e,this.Ce=n,this.Fe=i,this.Ie=r||H3,this.Ce.onSessionId(this.Te)}Re(){return this.Fe.props[gy]}getSetOnceProps(){var e,n=(e=this.Re())==null?void 0:e.props;return n?"r"in n?PT(n):{$referring_domain:n.referringDomain,$pathname:n.initialPathName,utm_source:n.utm_source,utm_campaign:n.utm_campaign,utm_medium:n.utm_medium,utm_content:n.utm_content,utm_term:n.utm_term}:{}}getSessionProps(){var e={};return Re(ab(this.getSetOnceProps()),((n,i)=>{i==="$current_url"&&(i="url"),e["$session_entry_"+Xv(i)]=n})),e}},Yv=st("[SessionId]"),_p=class{on(e,n){return this.Me.on(e,n)}constructor(e,n,i){var r;if(this.Oe=[],this.Ae=void 0,this.Me=new $c,this.De=(u,f)=>Math.abs(u-f)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode==="always")throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.F=e.config,this.Fe=e.persistence,this.je=void 0,this.Le=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.Ne=n||Xr,this.Ue=i||Xr;var a=this.F.persistence_name||this.F.token,o=this.F.session_idle_timeout_seconds||1800;if(this._sessionTimeoutMs=1e3*ci(o,60,36e3,Yv.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.ze(),this.He="ph_"+a+"_window_id",this.Be="ph_"+a+"_primary_window_exists",this.qe()){var s=St.W(this.He),l=St.W(this.Be);s&&!l?this.je=s:St.V(this.He),St.G(this.Be,!0)}if((r=this.F.bootstrap)!=null&&r.sessionID)try{var c=(u=>{var f=u.replace(/-/g,"");if(f.length!==32)throw new Error("Not a valid UUID");if(f[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(f.substring(0,12),16)})(this.F.bootstrap.sessionID);this.We(this.F.bootstrap.sessionID,new Date().getTime(),c)}catch(u){Yv.error("Invalid sessionID in bootstrap",u)}this.Ge()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return I(this.Oe)&&(this.Oe=[]),this.Oe.push(e),this.Le&&e(this.Le,this.je),()=>{this.Oe=this.Oe.filter((n=>n!==e))}}qe(){return this.F.persistence!=="memory"&&!this.Fe.wi&&St.H()}Ve(e){e!==this.je&&(this.je=e,this.qe()&&St.G(this.He,e))}Je(){return this.je?this.je:this.qe()?St.W(this.He):null}We(e,n,i){e===this.Le&&n===this._sessionActivityTimestamp&&i===this._sessionStartTimestamp||(this._sessionStartTimestamp=i,this._sessionActivityTimestamp=n,this.Le=e,this.Fe.register({[rp]:[n,e,i]}))}Ke(){var e=this.Fe.props[rp];return Ae(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.We(null,null,null)}destroy(){clearTimeout(this.Ye),this.Ye=void 0,this.Ae&&R&&(R.removeEventListener("beforeunload",this.Ae,{capture:!1}),this.Ae=void 0),this.Oe=[]}Ge(){this.Ae=()=>{this.qe()&&St.V(this.Be)},tt(R,"beforeunload",this.Ae,{capture:!1})}checkAndGetSessionAndWindowId(e,n){if(e===void 0&&(e=!1),n===void 0&&(n=null),this.F.cookieless_mode==="always")throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var i=n||new Date().getTime(),[r,a,o]=this.Ke(),s=this.Je(),l=fi(o)&&o>0&&Math.abs(i-o)>864e5,c=!1,u=!a,f=!u&&!e&&this.De(i,r);u||f||l?(a=this.Ne(),s=this.Ue(),Yv.info("new session ID generated",{sessionId:a,windowId:s,changeReason:{noSessionId:u,activityTimeout:f,sessionPastMaximumLength:l}}),o=i,c=!0):s||(s=this.Ue(),c=!0);var h=r===0||!e||l?i:r,g=o===0?new Date().getTime():o;return this.Ve(s),this.We(a,h,g),e||this.ze(),c&&this.Oe.forEach((_=>_(a,s,c?{noSessionId:u,activityTimeout:f,sessionPastMaximumLength:l}:void 0))),{sessionId:a,windowId:s,sessionStartTimestamp:g,changeReason:c?{noSessionId:u,activityTimeout:f,sessionPastMaximumLength:l}:void 0,lastActivityTimestamp:r}}ze(){clearTimeout(this.Ye),this.Ye=setTimeout((()=>{var[e]=this.Ke();if(this.De(new Date().getTime(),e)){var n=this.Le;this.resetSessionId(),this.Me.emit("forcedIdleReset",{idleSessionId:n})}}),1.1*this.sessionTimeoutMs)}},I3=["$set_once","$set"],Wr=st("[SiteApps]"),Qy=class{constructor(e){this._instance=e,this.Xe=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}Qe(e,n){if(n){var i=this.globalsForEvent(n);this.Xe.push(i),this.Xe.length>1e3&&(this.Xe=this.Xe.slice(10))}}get siteAppLoaders(){var e;return(e=J._POSTHOG_REMOTE_CONFIG)==null||(e=e[this._instance.config.token])==null?void 0:e.siteApps}init(){if(this.isEnabled){var e=this._instance.Ai(this.Qe.bind(this));this.Ze=()=>{e(),this.Xe=[],this.Ze=void 0}}}globalsForEvent(e){var n,i,r,a,o,s,l;if(!e)throw new Error("Event payload is required");var c={},u=this._instance.get_property("$groups")||[],f=this._instance.get_property("$stored_group_properties")||{};for(var[h,g]of Object.entries(f))c[h]={id:u[h],type:h,properties:g};var{$set_once:_,$set:b}=e;return{event:j({},XA(e,I3),{properties:j({},e.properties,b?{$set:j({},(n=(i=e.properties)==null?void 0:i.$set)!==null&&n!==void 0?n:{},b)}:{},_?{$set_once:j({},(r=(a=e.properties)==null?void 0:a.$set_once)!==null&&r!==void 0?r:{},_)}:{}),elements_chain:(o=(s=e.properties)==null?void 0:s.$elements_chain)!==null&&o!==void 0?o:"",distinct_id:(l=e.properties)==null?void 0:l.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:c}}setupSiteApp(e){var n=this.apps[e.id],i=()=>{var s;!n.errored&&this.Xe.length&&(Wr.info("Processing "+this.Xe.length+" events for site app with id "+e.id),this.Xe.forEach((l=>n.processEvent==null?void 0:n.processEvent(l))),n.processedBuffer=!0),Object.values(this.apps).every((l=>l.processedBuffer||l.errored))&&((s=this.Ze)==null||s.call(this))},r=!1,a=s=>{n.errored=!s,n.loaded=!0,Wr.info("Site app with id "+e.id+" "+(s?"loaded":"errored")),r&&i()};try{var{processEvent:o}=e.init({posthog:this._instance,callback:s=>{a(s)}});o&&(n.processEvent=o),r=!0}catch(s){Wr.error("Error while initializing PostHog app with config id "+e.id,s),a(!1)}if(r&&n.loaded)try{i()}catch(s){Wr.error("Error while processing buffered events PostHog app with config id "+e.id,s),n.errored=!0}}tr(){var e=this.siteAppLoaders||[];for(var n of e)this.apps[n.id]={id:n.id,loaded:!1,errored:!1,processedBuffer:!1};for(var i of e)this.setupSiteApp(i)}ir(e){if(Object.keys(this.apps).length!==0){var n=this.globalsForEvent(e);for(var i of Object.values(this.apps))try{i.processEvent==null||i.processEvent(n)}catch(r){Wr.error("Error while processing event "+e.event+" for site app "+i.id,r)}}}onRemoteConfig(e){var n,i,r,a=this;if((n=this.siteAppLoaders)!=null&&n.length)return this.isEnabled?(this.tr(),void this._instance.on("eventCaptured",(c=>this.ir(c)))):void Wr.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((i=this.Ze)==null||i.call(this),(r=e.siteApps)!=null&&r.length)if(this.isEnabled){var o=function(c){var u;J["__$$ph_site_app_"+c]=a._instance,(u=J.__PosthogExtensions__)==null||u.loadSiteApp==null||u.loadSiteApp(a._instance,l,(f=>{if(f)return Wr.error("Error while initializing PostHog app with config id "+c,f)}))};for(var{id:s,url:l}of e.siteApps)o(s)}else Wr.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}},ek=function(t,e){if(!t)return!1;var n=t.userAgent;if(n&&oA(n,e))return!0;try{var i=t?.userAgentData;if(i!=null&&i.brands&&i.brands.some((r=>oA(r?.brand,e))))return!0}catch{}return!!t.webdriver},Oc=(function(t){return t.US="us",t.EU="eu",t.CUSTOM="custom",t})({}),GA="i.posthog.com",Jy=class{constructor(e){this.er={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return e==="https://app.posthog.com"?"https://us.i.posthog.com":e}get flagsApiHost(){var e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e,n=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return n||(n=this.apiHost.replace("."+GA,".posthog.com")),n==="https://app.posthog.com"?"https://us.posthog.com":n}get region(){return this.er[this.apiHost]||(/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this.er[this.apiHost]=Oc.US:/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this.er[this.apiHost]=Oc.EU:this.er[this.apiHost]=Oc.CUSTOM),this.er[this.apiHost]}endpointFor(e,n){if(n===void 0&&(n=""),n&&(n=n[0]==="/"?n:"/"+n),e==="ui")return this.uiHost+n;if(e==="flags")return this.flagsApiHost+n;if(this.region===Oc.CUSTOM)return this.apiHost+n;var i=GA+n;switch(e){case"assets":return"https://"+this.region+"-assets."+i;case"api":return"https://"+this.region+"."+i}}},z3={icontains:(t,e)=>!!R&&e.href.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>!!R&&e.href.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>!!R&&yp(e.href,t),not_regex:(t,e)=>!!R&&!yp(e.href,t),exact:(t,e)=>e.href===t,is_not:(t,e)=>e.href!==t},eb=class t{constructor(e){var n=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(i){i===void 0&&(i=!1),n.getWebExperiments((r=>{t.rr("retrieved web experiments from the server"),n.sr=new Map,r.forEach((a=>{if(a.feature_flag_key){var o;n.sr&&(t.rr("setting flag key ",a.feature_flag_key," to web experiment ",a),(o=n.sr)==null||o.set(a.feature_flag_key,a));var s=n._instance.getFeatureFlag(a.feature_flag_key);ot(s)&&a.variants[s]&&n.nr(a.name,s,a.variants[s].transforms)}else if(a.variants)for(var l in a.variants){var c=a.variants[l];t.ar(c)&&n.nr(a.name,l,c.transforms)}}))}),i)},this._instance=e,this._instance.onFeatureFlags((i=>{this.onFeatureFlags(i)}))}onFeatureFlags(e){if(this._is_bot())t.rr("Refusing to render web experiment since the viewer is a likely bot");else if(!this._instance.config.disable_web_experiments){if(Ee(this.sr))return this.sr=new Map,this.loadIfEnabled(),void this.previewWebExperiment();t.rr("applying feature flags",e),e.forEach((n=>{var i;if(this.sr&&(i=this.sr)!=null&&i.has(n)){var r,a=this._instance.getFeatureFlag(n),o=(r=this.sr)==null?void 0:r.get(n);a&&o!=null&&o.variants[a]&&this.nr(o.name,a,o.variants[a].transforms)}}))}}previewWebExperiment(){var e=t.getWindowLocation();if(e!=null&&e.search){var n=dp(e?.search,"__experiment_id"),i=dp(e?.search,"__experiment_variant");n&&i&&(t.rr("previewing web experiments "+n+" && "+i),this.getWebExperiments((r=>{this.lr(parseInt(n),i,r)}),!1,!0))}}loadIfEnabled(){this._instance.config.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,n,i){if(this._instance.config.disable_web_experiments&&!i)return e([]);var r=this._instance.get_property("$web_experiments");if(r&&!n)return e(r);this._instance.ci({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this._instance.config.token),method:"GET",callback:a=>{if(a.statusCode!==200||!a.json)return e([]);var o=a.json.experiments||[];return e(o)}})}lr(e,n,i){var r=i.filter((a=>a.id===e));r&&r.length>0&&(t.rr("Previewing web experiment ["+r[0].name+"] with variant ["+n+"]"),this.nr(r[0].name,n,r[0].variants[n].transforms))}static ar(e){return!Ee(e.conditions)&&t.ur(e)&&t.hr(e)}static ur(e){var n;if(Ee(e.conditions)||Ee((n=e.conditions)==null?void 0:n.url))return!0;var i,r,a,o=t.getWindowLocation();return!!o&&((i=e.conditions)==null||!i.url||z3[(r=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&r!==void 0?r:"icontains"](e.conditions.url,o))}static getWindowLocation(){return R?.location}static hr(e){var n;if(Ee(e.conditions)||Ee((n=e.conditions)==null?void 0:n.utm))return!0;var i=FT();if(i.utm_source){var r,a,o,s,l,c,u,f,h=(r=e.conditions)==null||(r=r.utm)==null||!r.utm_campaign||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_campaign)==i.utm_campaign,g=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((s=e.conditions)==null||(s=s.utm)==null?void 0:s.utm_source)==i.utm_source,_=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((c=e.conditions)==null||(c=c.utm)==null?void 0:c.utm_medium)==i.utm_medium,b=(u=e.conditions)==null||(u=u.utm)==null||!u.utm_term||((f=e.conditions)==null||(f=f.utm)==null?void 0:f.utm_term)==i.utm_term;return h&&_&&b&&g}return!1}static rr(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];$.info("[WebExperiments] "+e,i)}nr(e,n,i){this._is_bot()?t.rr("Refusing to render web experiment since the viewer is a likely bot"):n!=="control"?i.forEach((r=>{if(r.selector){var a;t.rr("applying transform of variant "+n+" for experiment "+e+" ",r);var o=(a=document)==null?void 0:a.querySelectorAll(r.selector);o?.forEach((s=>{var l=s;r.html&&(l.innerHTML=r.html),r.css&&l.setAttribute("style",r.css)}))}})):t.rr("Control variants leave the page unmodified.")}_is_bot(){return dn&&this._instance?ek(dn,this._instance.config.custom_blocked_useragents):void 0}},B3=st("[PostHog ExternalIntegrations]"),$3={intercom:"intercom-integration",crispChat:"crisp-chat-integration"},tb=class{constructor(e){this._instance=e}it(e,n){var i;(i=J.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,e,(r=>{if(r)return B3.error("failed to load script",r);n()}))}startIfEnabledOrStop(){var e=this,n=function(o){var s,l,c;!r||(s=J.__PosthogExtensions__)!=null&&(s=s.integrations)!=null&&s[o]||e.it($3[o],(()=>{var u;(u=J.__PosthogExtensions__)==null||(u=u.integrations)==null||(u=u[o])==null||u.start(e._instance)})),!r&&(l=J.__PosthogExtensions__)!=null&&(l=l.integrations)!=null&&l[o]&&((c=J.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[o])==null||c.stop())};for(var[i,r]of Object.entries((a=this._instance.config.integrations)!==null&&a!==void 0?a:{})){var a;n(i)}}},nb="[SessionRecording]",wc=st(nb),Sp=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 wc.error("started without valid sessionManager"),new Error(nb+" started without valid sessionManager. This is a bug.");if(this._instance.config.cookieless_mode==="always")throw new Error(nb+' cannot be used with cookieless_mode="always"')}get cr(){var e,n=!((e=this._instance.get_property(Iv))==null||!e.enabled),i=!this._instance.config.disable_session_recording,r=this._instance.config.disable_session_recording||this._instance.consent.isOptedOut();return R&&n&&i&&!r}startIfEnabledOrStop(e){var n;if(!this.cr||(n=this.vr)==null||!n.isStarted){var i=!I(Object.assign)&&!I(Array.from);this.cr&&i?(this.gr(e),wc.info("starting")):this.stopRecording()}}gr(e){var n,i,r;this.cr&&(J!=null&&(n=J.__PosthogExtensions__)!=null&&(n=n.rrweb)!=null&&n.record&&(i=J.__PosthogExtensions__)!=null&&i.initSessionRecording?this._r(e):(r=J.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,this.mr,(a=>{if(a)return wc.error("could not load recorder",a);this._r(e)})))}stopRecording(){var e,n;(e=this.pr)==null||e.call(this),this.pr=void 0,(n=this.vr)==null||n.stop()}yr(){var e;(e=this._instance.persistence)==null||e.unregister(sT)}br(e){if(this._instance.persistence){var n,i,r=this._instance.persistence,a=()=>{var o=e.sessionRecording===!1?void 0:e.sessionRecording,s=o?.sampleRate,l=Ee(s)?null:parseFloat(s);Ee(l)&&this.yr();var c=o?.minimumDurationMilliseconds;r.register({[Iv]:j({enabled:!!o},o,{networkPayloadCapture:j({capturePerformance:e.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:l,minimumDurationMilliseconds:I(c)?null:c,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers})})};a(),(n=this.pr)==null||n.call(this),this.pr=(i=this._instance.sessionManager)==null?void 0:i.onSessionId(a)}}onRemoteConfig(e){"sessionRecording"in e?e.sessionRecording!==!1?(this.br(e),this.dr=!0,this.startIfEnabledOrStop()):this.dr=!0:wc.info("skipping remote config with no sessionRecording",e)}log(e,n){var i;n===void 0&&(n="log"),(i=this.vr)!=null&&i.log?this.vr.log(e,n):wc.warn("log called before recorder was ready")}get mr(){var e,n,i=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.get_property(Iv);return(i==null||(n=i.scriptConfig)==null?void 0:n.script)||"lazy-recorder"}_r(e){var n,i;if((n=J.__PosthogExtensions__)==null||!n.initSessionRecording)throw Error("Called on script loaded before session recording is available");this.vr||(this.vr=(i=J.__PosthogExtensions__)==null?void 0:i.initSessionRecording(this._instance),this.vr._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),this.vr.start(e)}onRRwebEmit(e){var n;(n=this.vr)==null||n.onRRwebEmit==null||n.onRRwebEmit(e)}overrideLinkedFlag(){var e,n;this.vr||(n=this._instance.persistence)==null||n.register({$replay_override_linked_flag:!0}),(e=this.vr)==null||e.overrideLinkedFlag()}overrideSampling(){var e,n;this.vr||(n=this._instance.persistence)==null||n.register({$replay_override_sampling:!0}),(e=this.vr)==null||e.overrideSampling()}overrideTrigger(e){var n,i;this.vr||(i=this._instance.persistence)==null||i.register({[e==="url"?"$replay_override_url_trigger":"$replay_override_event_trigger"]:!0}),(n=this.vr)==null||n.overrideTrigger(e)}get sdkDebugProperties(){var e;return((e=this.vr)==null?void 0:e.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(e,n){var i;return!((i=this.vr)==null||!i.tryAddCustomEvent(e,n))}},Dc={},ib=()=>{},Ts="posthog",tk=!T3&&Zt?.indexOf("MSIE")===-1&&Zt?.indexOf("Mozilla")===-1,ZA=t=>{var e;return j({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,token:"",autocapture:!0,cross_subdomain_cookie:DL(B?.location),persistence:"localStorage+cookie",persistence_name:"",loaded:ib,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:Yt&&ot(Yt?.search)&&Yt.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_external_dependency_loading:!1,enable_recording_console_log:void 0,secure_cookie:(R==null||(e=R.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error:n=>{var i="Bad HTTP status: "+n.statusCode+" "+n.text;$.error(i)},get_device_id:n=>n,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:"identified_only",before_send:void 0,request_queue_config:{flush_interval_ms:Yy},error_tracking:{},_onCapture:ib,__preview_eager_load_replay:!1},(n=>({rageclick:!(n&&n>="2025-11-30")||{content_ignorelist:!0},capture_pageview:!(n&&n>="2025-05-24")||"history_change",session_recording:n&&n>="2025-11-30"?{strictMinimumDuration:!0}:{}}))(t))},YA=t=>{var e={};I(t.process_person)||(e.person_profiles=t.process_person),I(t.xhr_headers)||(e.request_headers=t.xhr_headers),I(t.cookie_name)||(e.persistence_name=t.cookie_name),I(t.disable_cookie)||(e.disable_persistence=t.disable_cookie),I(t.store_google)||(e.save_campaign_params=t.store_google),I(t.verbose)||(e.debug=t.verbose);var n=Ye({},e,t);return Ae(t.property_blacklist)&&(I(t.property_denylist)?n.property_denylist=t.property_blacklist:Ae(t.property_denylist)?n.property_denylist=[...t.property_blacklist,...t.property_denylist]:$.error("Invalid value for property_denylist config: "+t.property_denylist)),n},rb=class{constructor(){this.__forceAllowLocalhost=!1}get wr(){return this.__forceAllowLocalhost}set wr(e){$.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}},xp=class t{get decideEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){this.webPerformance=new rb,this.Sr=!1,this.version=Yi.LIB_VERSION,this.Er=new $c,this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=ZA(),this.SentryIntegration=Ty,this.sentryIntegration=e=>(function(n,i){var r=wT(n,i);return{name:xT,processEvent:a=>r(a)}})(this,e),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.$r=!1,this.kr=null,this.Pr=null,this.Tr=null,this.featureFlags=new Uy(this),this.toolbar=new ky(this),this.scrollManager=new Xy(this),this.pageViewManager=new Hy(this),this.surveys=new Py(this),this.experiments=new eb(this),this.exceptions=new Fy(this),this.rateLimiter=new Gy(this),this.requestRouter=new Jy(this),this.consent=new Ey(this),this.externalIntegrations=new tb(this),this.people={set:(e,n,i)=>{var r=ot(e)?{[e]:n}:e;this.setPersonProperties(r),i?.({})},set_once:(e,n,i)=>{var r=ot(e)?{[e]:n}:e;this.setPersonProperties(void 0,r),i?.({})}},this.on("eventCaptured",(e=>$.info('send "'+e?.event+'"',e)))}init(e,n,i){if(i&&i!==Ts){var r,a=(r=Dc[i])!==null&&r!==void 0?r:new t;return a._init(e,n,i),Dc[i]=a,Dc[Ts][i]=a,a}return this._init(e,n,i)}_init(e,n,i){var r;if(n===void 0&&(n={}),I(e)||Qv(e))return $.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config={},n.debug=this.Rr(n.debug),this.Ir=n,this.Fr=[],n.person_profiles&&(this.Pr=n.person_profiles),this.set_config(Ye({},ZA(n.defaults),YA(n),{name:i,token:e})),this.config.on_xhr_error&&$.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=n.disable_compression?void 0:Xi.GZipJS;var a=this.Cr();this.persistence=new Nc(this.config,a),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Nc(j({},this.config,{persistence:"sessionStorage"}),a);var o=j({},this.persistence.props),s=j({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.Mr=new Wy((p=>this.Or(p)),this.config.request_queue_config),this.Ar=new Ky(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 _p(this),this.sessionPropsManager=new bp(this,this.sessionManager,this.persistence)),this.config.__preview_deferred_init_extensions?($.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.Dr(l)}),0)):($.info("Initializing extensions synchronously"),this.Dr(l)),Yi.DEBUG=Yi.DEBUG||this.config.debug,Yi.DEBUG&&$.info("Starting in debug mode",{this:this,config:n,thisC:j({},this.config),p:o,s}),((r=n.bootstrap)==null?void 0:r.distinctID)!==void 0){var c,u,f=this.config.get_device_id(Xr()),h=(c=n.bootstrap)!=null&&c.isIdentifiedID?f:n.bootstrap.distinctID;this.persistence.set_property(Wi,(u=n.bootstrap)!=null&&u.isIdentifiedID?"identified":"anonymous"),this.register({distinct_id:n.bootstrap.distinctID,$device_id:h})}if(this.jr()){var g,_,b=Object.keys(((g=n.bootstrap)==null?void 0:g.featureFlags)||{}).filter((p=>{var m;return!((m=n.bootstrap)==null||(m=m.featureFlags)==null||!m[p])})).reduce(((p,m)=>{var v;return p[m]=((v=n.bootstrap)==null||(v=v.featureFlags)==null?void 0:v[m])||!1,p}),{}),w=Object.keys(((_=n.bootstrap)==null?void 0:_.featureFlagPayloads)||{}).filter((p=>b[p])).reduce(((p,m)=>{var v,S;return(v=n.bootstrap)!=null&&(v=v.featureFlagPayloads)!=null&&v[m]&&(p[m]=(S=n.bootstrap)==null||(S=S.featureFlagPayloads)==null?void 0:S[m]),p}),{});this.featureFlags.receivedFeatureFlags({featureFlags:b,featureFlagPayloads:w})}if(l)this.register_once({distinct_id:gc,$device_id:null},"");else if(!this.get_distinct_id()){var d=this.config.get_device_id(Xr());this.register_once({distinct_id:d,$device_id:d},""),this.persistence.set_property(Wi,"anonymous")}return tt(R,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),this.toolbar.maybeLoadToolbar(),n.segment?t3(this,(()=>this.Lr())):this.Lr(),Qr(this.config._onCapture)&&this.config._onCapture!==ib&&($.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(p=>this.config._onCapture(p.event,p)))),this.config.ip&&$.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this}Dr(e){var n=performance.now();this.historyAutocapture=new Ay(this),this.historyAutocapture.startIfEnabled();var i=[];i.push((()=>{new Ry(this).startIfEnabledOrStop()})),i.push((()=>{var r;this.siteApps=new Qy(this),(r=this.siteApps)==null||r.init()})),e||i.push((()=>{this.sessionRecording=new Sp(this),this.sessionRecording.startIfEnabledOrStop()})),this.config.disable_scroll_properties||i.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),i.push((()=>{this.autocapture=new _y(this),this.autocapture.startIfEnabled()})),i.push((()=>{this.surveys.loadIfEnabled()})),i.push((()=>{this.heatmaps=new Ly(this),this.heatmaps.startIfEnabled()})),i.push((()=>{this.webVitalsAutocapture=new Dy(this)})),i.push((()=>{this.exceptionObserver=new Cy(this),this.exceptionObserver.startIfEnabled()})),i.push((()=>{this.deadClicksAutocapture=new pp(this,e3),this.deadClicksAutocapture.startIfEnabled()})),i.push((()=>{if(this.Nr){var r=this.Nr;this.Nr=void 0,this.fi(r)}})),this.Ur(i,n)}Ur(e,n){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-n>=30&&e.length>0)return void setTimeout((()=>{this.Ur(e,n)}),0);var i=e.shift();if(i)try{i()}catch(a){$.error("Error initializing extension:",a)}}var r=Math.round(performance.now()-n);this.register_for_session({$sdk_debug_extensions_init_method:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",$sdk_debug_extensions_init_time_ms:r}),this.config.__preview_deferred_init_extensions&&$.info("PostHog extensions initialized ("+r+"ms)")}fi(e){var n,i,r,a,o,s,l,c;if(!B||!B.body)return $.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.fi(e)}),500);this.config.__preview_deferred_init_extensions&&(this.Nr=e),this.compression=void 0,e.supportedCompression&&!this.config.disable_compression&&(this.compression=ue(e.supportedCompression,Xi.GZipJS)?Xi.GZipJS:ue(e.supportedCompression,Xi.Base64)?Xi.Base64:void 0),(n=e.analytics)!=null&&n.endpoint&&(this.analyticsDefaultEndpoint=e.analytics.endpoint),this.set_config({person_profiles:this.Pr?this.Pr:"identified_only"}),(i=this.siteApps)==null||i.onRemoteConfig(e),(r=this.sessionRecording)==null||r.onRemoteConfig(e),(a=this.autocapture)==null||a.onRemoteConfig(e),(o=this.heatmaps)==null||o.onRemoteConfig(e),this.surveys.onRemoteConfig(e),(s=this.webVitalsAutocapture)==null||s.onRemoteConfig(e),(l=this.exceptionObserver)==null||l.onRemoteConfig(e),this.exceptions.onRemoteConfig(e),(c=this.deadClicksAutocapture)==null||c.onRemoteConfig(e)}Lr(){try{this.config.loaded(this)}catch(e){$.critical("`loaded` function failed",e)}this.zr(),this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.config.cookieless_mode==="always")&&this.Hr()}),1),new Zy(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()&&ea(this.__request_queue,(e=>this.Or(e))),this.__request_queue=[],this.zr()}_handle_unload(){var e,n;this.config.request_batching?(this.Br()&&this.capture("$pageleave"),(e=this.Mr)==null||e.unload(),(n=this.Ar)==null||n.unload()):this.Br()&&this.capture("$pageleave",null,{transport:"sendBeacon"})}ci(e){this.__loaded&&(tk?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)||(e.transport=e.transport||this.config.api_transport,e.url=vp(e.url,{ip:this.config.ip?1:0}),e.headers=j({},this.config.request_headers),e.compression=e.compression==="best-available"?this.compression:e.compression,e.disableXHRCredentials=this.config.__preview_disable_xhr_credentials,this.config.__preview_disable_beacon&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(n=>{var i,r,a,o=j({},n);o.timeout=o.timeout||6e4,o.url=vp(o.url,{_:new Date().getTime().toString(),ver:Yi.LIB_VERSION,compression:o.compression});var s=(i=o.transport)!==null&&i!==void 0?i:"fetch",l=ep.filter((u=>!o.disableTransport||!u.transport||!o.disableTransport.includes(u.transport))),c=(r=(a=rT(l,(u=>u.transport===s)))==null?void 0:a.method)!==null&&r!==void 0?r:l[0].method;if(!c)throw new Error("No available transport method");c(o)})(j({},e,{callback:n=>{var i,r;this.rateLimiter.checkForLimiting(n),n.statusCode>=400&&((i=(r=this.config).on_request_error)==null||i.call(r,n)),e.callback==null||e.callback(n)}}))))}Or(e){this.Ar?this.Ar.retriableRequest(e):this.ci(e)}_execute_array(e){var n,i=[],r=[],a=[];ea(e,(s=>{s&&(n=s[0],Ae(n)?a.push(s):Qr(s)?s.call(this):Ae(s)&&n==="alias"?i.push(s):Ae(s)&&n.indexOf("capture")!==-1&&Qr(this[n])?a.push(s):r.push(s))}));var o=function(s,l){ea(s,(function(c){if(Ae(c[0])){var u=l;Re(c,(function(f){u=u[f[0]].apply(u,f.slice(1))}))}else this[c[0]].apply(this,c.slice(1))}),l)};o(i,this),o(r,this),o(a,this)}jr(){var e,n;return((e=this.config.bootstrap)==null?void 0:e.featureFlags)&&Object.keys((n=this.config.bootstrap)==null?void 0:n.featureFlags).length>0||!1}push(e){this._execute_array([e])}capture(e,n,i){var r;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.Mr){if(this.is_capturing())if(!I(e)&&ot(e)){var a=!this.config.opt_out_useragent_filter&&this._is_bot();if(!(a&&!this.config.__preview_capture_bot_pageviews)){var o=i!=null&&i.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(o==null||!o.isRateLimited){n!=null&&n.$current_url&&!ot(n?.$current_url)&&($.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),n==null||delete n.$current_url),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var s=new Date,l=i?.timestamp||s,c=Xr(),u={uuid:c,event:e,properties:this.calculateEventProperties(e,n||{},l,c)};e==="$pageview"&&this.config.__preview_capture_bot_pageviews&&a&&(u.event="$bot_pageview",u.properties.$browser_type="bot"),o&&(u.properties.$lib_rate_limit_remaining_tokens=o.remainingTokens),i?.$set&&(u.$set=i?.$set);var f,h=this.qr(i?.$set_once);if(h&&(u.$set_once=h),(u=ML(u,i!=null&&i._noTruncate?null:this.config.properties_string_max_length)).timestamp=l,I(i?.timestamp)||(u.properties.$event_time_override_provided=!0,u.properties.$event_time_override_system_time=s),e===tp.DISMISSED||e===tp.SENT){var g=n?.[jA.SURVEY_ID],_=n?.[jA.SURVEY_ITERATION];f={id:g,current_iteration:_},localStorage.getItem(qA(f))||localStorage.setItem(qA(f),"true"),u.$set=j({},u.$set,{[M3({id:g,current_iteration:_},e===tp.SENT?"responded":"dismissed")]:!0})}var b=j({},u.properties.$set,u.$set);if(ks(b)||this.setPersonPropertiesForFlags(b),!Ee(this.config.before_send)){var w=this.Wr(u);if(!w)return;u=w}this.Er.emit("eventCaptured",u);var d={method:"POST",url:(r=i?._url)!==null&&r!==void 0?r:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),data:u,compression:"best-available",batchKey:i?._batchKey};return!this.config.request_batching||i&&(i==null||!i._batchKey)||i!=null&&i.send_instantly?this.Or(d):this.Mr.enqueue(d),u}$.critical("This capture call is ignored due to client rate limiting.")}}else $.error("No event name provided to posthog.capture")}else $.uninitializedWarning("posthog.capture")}Ai(e){return this.on("eventCaptured",(n=>e(n.event,n)))}calculateEventProperties(e,n,i,r,a){if(i=i||new Date,!this.persistence||!this.sessionPersistence)return n;var o=a?void 0:this.persistence.remove_event_timer(e),s=j({},n);if(s.token=this.config.token,s.$config_defaults=this.config.defaults,(this.config.cookieless_mode=="always"||this.config.cookieless_mode=="on_reject"&&this.consent.isExplicitlyOptedOut())&&(s.$cookieless_mode=!0),e==="$snapshot"){var l=j({},this.persistence.properties(),this.sessionPersistence.properties());return s.distinct_id=l.distinct_id,(!ot(s.distinct_id)&&!fi(s.distinct_id)||Qv(s.distinct_id))&&$.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),s}var c,u=v3(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties);if(this.sessionManager){var{sessionId:f,windowId:h}=this.sessionManager.checkAndGetSessionAndWindowId(a,i.getTime());s.$session_id=f,s.$window_id=h}this.sessionPropsManager&&Ye(s,this.sessionPropsManager.getSessionProps());try{var g;this.sessionRecording&&Ye(s,this.sessionRecording.sdkDebugProperties),s.$sdk_debug_retry_queue_size=(g=this.Ar)==null?void 0:g.length}catch(d){s.$sdk_debug_error_capturing_properties=String(d)}if(this.requestRouter.region===Oc.CUSTOM&&(s.$lib_custom_api_host=this.config.api_host),c=e!=="$pageview"||a?e!=="$pageleave"||a?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(i):this.pageViewManager.doPageView(i,r),s=Ye(s,c),e==="$pageview"&&B&&(s.title=B.title),!I(o)){var _=i.getTime()-o;s.$duration=parseFloat((_/1e3).toFixed(3))}Zt&&this.config.opt_out_useragent_filter&&(s.$browser_type=this._is_bot()?"bot":"browser"),(s=Ye({},u,this.persistence.properties(),this.sessionPersistence.properties(),s)).$is_identified=this._isIdentified(),Ae(this.config.property_denylist)?Re(this.config.property_denylist,(function(d){delete s[d]})):$.error("Invalid value for property_denylist config: "+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var b=this.config.sanitize_properties;b&&($.error("sanitize_properties is deprecated. Use before_send instead"),s=b(s,e));var w=this.Gr();return s.$process_person_profile=w,w&&!a&&this.Vr("_calculate_event_properties"),s}qr(e){var n;if(!this.persistence||!this.Gr()||this.Sr)return e;var i=this.persistence.get_initial_props(),r=(n=this.sessionPropsManager)==null?void 0:n.getSetOnceProps(),a=Ye({},i,r||{},e||{}),o=this.config.sanitize_properties;return o&&($.error("sanitize_properties is deprecated. Use before_send instead"),a=o(a,"$set_once")),this.Sr=!0,ks(a)?void 0:a}register(e,n){var i;(i=this.persistence)==null||i.register(e,n)}register_once(e,n,i){var r;(r=this.persistence)==null||r.register_once(e,n,i)}register_for_session(e){var n;(n=this.sessionPersistence)==null||n.register(e)}unregister(e){var n;(n=this.persistence)==null||n.unregister(e)}unregister_for_session(e){var n;(n=this.sessionPersistence)==null||n.unregister(e)}Jr(e,n){this.register({[e]:n})}getFeatureFlag(e,n){return this.featureFlags.getFeatureFlag(e,n)}getFeatureFlagPayload(e){var n=this.featureFlags.getFeatureFlagPayload(e);try{return JSON.parse(n)}catch{return n}}isFeatureEnabled(e,n){return this.featureFlags.isFeatureEnabled(e,n)}reloadFeatureFlags(){this.featureFlags.reloadFeatureFlags()}updateEarlyAccessFeatureEnrollment(e,n,i){this.featureFlags.updateEarlyAccessFeatureEnrollment(e,n,i)}getEarlyAccessFeatures(e,n,i){return n===void 0&&(n=!1),this.featureFlags.getEarlyAccessFeatures(e,n,i)}on(e,n){return this.Er.on(e,n)}onFeatureFlags(e){return this.featureFlags.onFeatureFlags(e)}onSurveysLoaded(e){return this.surveys.onSurveysLoaded(e)}onSessionId(e){var n,i;return(n=(i=this.sessionManager)==null?void 0:i.onSessionId(e))!==null&&n!==void 0?n:()=>{}}getSurveys(e,n){n===void 0&&(n=!1),this.surveys.getSurveys(e,n)}getActiveMatchingSurveys(e,n){n===void 0&&(n=!1),this.surveys.getActiveMatchingSurveys(e,n)}renderSurvey(e,n){this.surveys.renderSurvey(e,n)}displaySurvey(e,n){n===void 0&&(n=D3),this.surveys.displaySurvey(e,n)}cancelPendingSurvey(e){this.surveys.cancelPendingSurvey(e)}canRenderSurvey(e){return this.surveys.canRenderSurvey(e)}canRenderSurveyAsync(e,n){return n===void 0&&(n=!1),this.surveys.canRenderSurveyAsync(e,n)}identify(e,n,i){if(!this.__loaded||!this.persistence)return $.uninitializedWarning("posthog.identify");if(fi(e)&&(e=e.toString(),$.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),e)if(["distinct_id","distinctid"].includes(e.toLowerCase()))$.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.');else if(e!==gc){if(this.Vr("posthog.identify")){var r=this.get_distinct_id();if(this.register({$user_id:e}),!this.get_property("$device_id")){var a=r;this.register_once({$had_persisted_distinct_id:!0,$device_id:a},"")}e!==r&&e!==this.get_property(Ec)&&(this.unregister(Ec),this.register({distinct_id:e}));var o=(this.persistence.get_property(Wi)||"anonymous")==="anonymous";e!==r&&o?(this.persistence.set_property(Wi,"identified"),this.setPersonPropertiesForFlags(j({},i||{},n||{}),!1),this.capture("$identify",{distinct_id:e,$anon_distinct_id:r},{$set:n||{},$set_once:i||{}}),this.Tr=BA(e,n,i),this.featureFlags.setAnonymousDistinctId(r)):(n||i)&&this.setPersonProperties(n,i),e!==r&&(this.reloadFeatureFlags(),this.unregister(ap))}}else $.critical('The string "'+gc+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.');else $.error("Unique user id has not been set in posthog.identify")}setPersonProperties(e,n){if((e||n)&&this.Vr("posthog.setPersonProperties")){var i=BA(this.get_distinct_id(),e,n);this.Tr!==i?(this.setPersonPropertiesForFlags(j({},n||{},e||{})),this.capture("$set",{$set:e||{},$set_once:n||{}}),this.Tr=i):$.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}group(e,n,i){if(e&&n){if(this.Vr("posthog.group")){var r=this.getGroups();r[e]!==n&&this.resetGroupPropertiesForFlags(e),this.register({$groups:j({},r,{[e]:n})}),i&&(this.capture("$groupidentify",{$group_type:e,$group_key:n,$group_set:i}),this.setGroupPropertiesForFlags({[e]:i})),r[e]===n||i||this.reloadFeatureFlags()}}else $.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,n){n===void 0&&(n=!0),this.featureFlags.setPersonPropertiesForFlags(e,n)}resetPersonPropertiesForFlags(){this.featureFlags.resetPersonPropertiesForFlags()}setGroupPropertiesForFlags(e,n){n===void 0&&(n=!0),this.Vr("posthog.setGroupPropertiesForFlags")&&this.featureFlags.setGroupPropertiesForFlags(e,n)}resetGroupPropertiesForFlags(e){this.featureFlags.resetGroupPropertiesForFlags(e)}reset(e){var n,i,r,a;if($.info("reset"),!this.__loaded)return $.uninitializedWarning("posthog.reset");var o=this.get_property("$device_id");if(this.consent.reset(),(n=this.persistence)==null||n.clear(),(i=this.sessionPersistence)==null||i.clear(),this.surveys.reset(),this.featureFlags.reset(),(r=this.persistence)==null||r.set_property(Wi,"anonymous"),(a=this.sessionManager)==null||a.resetSessionId(),this.Tr=null,this.config.cookieless_mode==="always")this.register_once({distinct_id:gc,$device_id:null},"");else{var s=this.config.get_device_id(Xr());this.register_once({distinct_id:s,$device_id:e?s:o},"")}this.register({$last_posthog_reset:new Date().toISOString()},1)}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,n;return(e=(n=this.sessionManager)==null?void 0:n.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var{sessionId:n,sessionStartTimestamp:i}=this.sessionManager.checkAndGetSessionAndWindowId(!0),r=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+n);if(e!=null&&e.withTimestamp&&i){var a,o=(a=e.timestampLookBack)!==null&&a!==void 0?a:10;if(!i)return r;r+="?t="+Math.max(Math.floor((new Date().getTime()-i)/1e3)-o,0)}return r}alias(e,n){return e===this.get_property(aT)?($.critical("Attempting to create alias for existing People user - aborting."),-2):this.Vr("posthog.alias")?(I(n)&&(n=this.get_distinct_id()),e!==n?(this.Jr(Ec,e),this.capture("$create_alias",{alias:e,distinct_id:n})):($.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var n=j({},this.config);if(ft(e)){var i,r,a,o,s;Ye(this.config,YA(e));var l=this.Cr();(i=this.persistence)==null||i.update_config(this.config,n,l),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Nc(j({},this.config,{persistence:"sessionStorage"}),l);var c=this.Rr(this.config.debug);Jr(c)&&(this.config.debug=c),Jr(this.config.debug)&&(this.config.debug?(Yi.DEBUG=!0,Ue.H()&&Ue.G("ph_debug","true"),$.info("set_config",{config:e,oldConfig:n,newConfig:j({},this.config)})):(Yi.DEBUG=!1,Ue.H()&&Ue.V("ph_debug"))),(r=this.sessionRecording)==null||r.startIfEnabledOrStop(),(a=this.autocapture)==null||a.startIfEnabled(),(o=this.heatmaps)==null||o.startIfEnabled(),this.surveys.loadIfEnabled(),this.Kr(),(s=this.externalIntegrations)==null||s.startIfEnabledOrStop()}}startSessionRecording(e){var n=e===!0,i={sampling:n||!(e==null||!e.sampling),linked_flag:n||!(e==null||!e.linked_flag),url_trigger:n||!(e==null||!e.url_trigger),event_trigger:n||!(e==null||!e.event_trigger)};if(Object.values(i).some(Boolean)){var r,a,o,s,l;(r=this.sessionManager)==null||r.checkAndGetSessionAndWindowId(),i.sampling&&((a=this.sessionRecording)==null||a.overrideSampling()),i.linked_flag&&((o=this.sessionRecording)==null||o.overrideLinkedFlag()),i.url_trigger&&((s=this.sessionRecording)==null||s.overrideTrigger("url")),i.event_trigger&&((l=this.sessionRecording)==null||l.overrideTrigger("event"))}this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!((e=this.sessionRecording)==null||!e.started)}captureException(e,n){var i=new Error("PostHog syntheticException"),r=this.exceptions.buildProperties(e,{handled:!0,syntheticException:i});return this.exceptions.sendExceptionEvent(j({},r,n))}loadToolbar(e){return this.toolbar.loadToolbar(e)}get_property(e){var n;return(n=this.persistence)==null?void 0:n.props[e]}getSessionProperty(e){var n;return(n=this.sessionPersistence)==null?void 0:n.props[e]}toString(){var e,n=(e=this.config.name)!==null&&e!==void 0?e:Ts;return n!==Ts&&(n=Ts+"."+n),n}_isIdentified(){var e,n;return((e=this.persistence)==null?void 0:e.get_property(Wi))==="identified"||((n=this.sessionPersistence)==null?void 0:n.get_property(Wi))==="identified"}Gr(){var e,n;return!(this.config.person_profiles==="never"||this.config.person_profiles==="identified_only"&&!this._isIdentified()&&ks(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[Ec])&&((n=this.persistence)==null||(n=n.props)==null||!n[sp]))}Br(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.Gr()||this.Vr("posthog.createPersonProfile")&&this.setPersonProperties({},{})}Vr(e){return this.config.person_profiles==="never"?($.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Jr(sp,!0),!0)}Cr(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut(),n=this.config.opt_out_persistence_by_default||this.config.cookieless_mode==="on_reject";return this.config.disable_persistence||e&&!!n}Kr(){var e,n,i,r,a=this.Cr();return((e=this.persistence)==null?void 0:e.wi)!==a&&((i=this.persistence)==null||i.set_disabled(a)),((n=this.sessionPersistence)==null?void 0:n.wi)!==a&&((r=this.sessionPersistence)==null||r.set_disabled(a)),a}opt_in_capturing(e){var n;if(this.config.cookieless_mode!=="always"){var i,r;this.config.cookieless_mode==="on_reject"&&this.consent.isExplicitlyOptedOut()&&(this.reset(!0),(i=this.sessionManager)==null||i.destroy(),this.sessionManager=new _p(this),this.persistence&&(this.sessionPropsManager=new bp(this,this.sessionManager,this.persistence)),this.sessionRecording=new Sp(this),this.sessionRecording.startIfEnabledOrStop()),this.consent.optInOut(!0),this.Kr(),this.zr(),(n=this.sessionRecording)==null||n.startIfEnabledOrStop(),this.config.cookieless_mode=="on_reject"&&this.surveys.loadIfEnabled(),(I(e?.captureEventName)||e!=null&&e.captureEventName)&&this.capture((r=e?.captureEventName)!==null&&r!==void 0?r:"$opt_in",e?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hr()}else $.warn('Consent opt in/out is not valid with cookieless_mode="always" and will be ignored')}opt_out_capturing(){var e,n;this.config.cookieless_mode!=="always"?(this.config.cookieless_mode==="on_reject"&&this.consent.isOptedIn()&&this.reset(!0),this.consent.optInOut(!1),this.Kr(),this.config.cookieless_mode==="on_reject"&&(this.register({distinct_id:gc,$device_id:null}),(e=this.sessionManager)==null||e.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,(n=this.sessionRecording)==null||n.stopRecording(),this.sessionRecording=void 0,this.Hr())):$.warn('Consent opt in/out is not valid with cookieless_mode="always" and will be ignored')}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===Ki.GRANTED?"granted":e===Ki.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 dn?ek(dn,this.config.custom_blocked_useragents):void 0}Hr(){B&&(B.visibilityState==="visible"?this.$r||(this.$r=!0,this.capture("$pageview",{title:B.title},{send_instantly:!0}),this.kr&&(B.removeEventListener("visibilitychange",this.kr),this.kr=null)):this.kr||(this.kr=this.Hr.bind(this),tt(B,"visibilitychange",this.kr)))}debug(e){e===!1?(R?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(R?.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}O(){var e,n,i,r,a,o,s,l=this.Ir||{};return"advanced_disable_flags"in l?!!l.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?($.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(i="advanced_disable_decide",r=!1,a=$,o=(n="advanced_disable_flags")in(e=l)&&!I(e[n]),s=i in e&&!I(e[i]),o?e[n]:s?(a&&a.warn("Config field '"+i+"' is deprecated. Please use '"+n+"' instead. The old field will be removed in a future major version."),e[i]):r)}Wr(e){if(Ee(this.config.before_send))return e;var n=Ae(this.config.before_send)?this.config.before_send:[this.config.before_send],i=e;for(var r of n){if(i=r(i),Ee(i)){var a="Event '"+e.event+"' was rejected in beforeSend function";return hL(e.event)?$.warn(a+". This can cause unexpected behavior."):$.info(a),null}i.properties&&!ks(i.properties)||$.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}return i}getPageViewId(){var e;return(e=this.pageViewManager.Vt)==null?void 0:e.pageViewId}captureTraceFeedback(e,n){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:n})}captureTraceMetric(e,n,i){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:n,$ai_metric_value:String(i)})}Rr(e){var n=Jr(e)&&!e,i=Ue.H()&&Ue.q("ph_debug")==="true";return!n&&(!!i||e)}};(function(t,e){for(var n=0;n<e.length;n++)t.prototype[e[n]]=OL(t.prototype[e[n]])})(xp,["identify"]);var WA,nk=(WA=Dc[Ts]=new xp,(function(){function t(){t.done||(t.done=!0,tk=!1,Re(Dc,(function(e){e._dom_loaded()})))}B!=null&&B.addEventListener?B.readyState==="complete"?t():tt(B,"DOMContentLoaded",t,{capture:!1}):R&&$.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),WA);var gb=class{constructor(e={}){this.options=e;V(this,"client");V(this,"featureFlagsCallback");V(this,"captureCallback");V(this,"consentUnsub");if(this.client=e.client,this.featureFlagsCallback=e.onFeatureFlagsLoaded,this.captureCallback=e.onCapture,!this.client&&e.consent&&e.requireExplicitConsent&&typeof window<"u"&&e.apiKey){let n=e.consent;n.getStatus()==="granted"&&this.initPostHog(),this.consentUnsub=n.subscribe(r=>{r==="granted"?this.client?this.client.opt_in_capturing():this.initPostHog():r==="denied"&&this.client&&this.client.opt_out_capturing()});return}!this.client&&typeof window<"u"&&e.apiKey&&this.initPostHog()}initPostHog(){let e=this.options;if(!e.apiKey)return;let n=e.enableFeatureFlags??!0,i=`syntro_${e.apiKey.slice(-6)||"sdk"}`;this.client=nk.init(e.apiKey,{api_host:e.apiHost??"https://telemetry.syntrologie.com",advanced_disable_feature_flags:!n,advanced_disable_feature_flags_on_first_load:!n,autocapture:e.autocapture??!0,capture_pageview:e.capturePageview??!0,capture_pageleave:e.capturePageleave??!0,disable_session_recording:!(e.sessionRecording??!0),opt_out_useragent_filter:!0,session_recording:{recordCrossDomainIFrames:!0},capture_performance:!0,enable_recording_console_log:!0,loaded:r=>{if(n&&this.featureFlagsCallback){r.onFeatureFlags(()=>{let o=this.getAllFeatureFlags();o&&this.featureFlagsCallback&&this.featureFlagsCallback(o)});let a=this.getAllFeatureFlags();a&&Object.keys(a).length>0&&this.featureFlagsCallback(a)}this.captureCallback&&r.on("eventCaptured",a=>{let o=typeof a=="string"?a:a?.event,s=typeof a=="string"?void 0:a?.properties;typeof o=="string"&&this.captureCallback?.(o,s)})}},i)}getAllFeatureFlags(){return this.client?.featureFlags?.getFlagVariants?.()}getSegmentFlags(){let e=this.getAllFeatureFlags();if(!e)return{};let n={};for(let[i,r]of Object.entries(e))i.startsWith("in_segment_")&&(n[i]=r===!0);return n}identify(e,n){this.client?.identify(e,n)}alias(e,n){this.client?.alias(e,n)}track(e,n){this.client?.capture(e,n)}trackCanvasOpened(e){this.track("shadow_canvas_opened",{surface:e})}trackCanvasClosed(e){this.track("shadow_canvas_closed",{surface:e})}trackRectangleViewed(e,n){this.track("shadow_canvas_rectangle_viewed",{rectangleId:e,surface:n})}trackAction(e,n,i){this.track("shadow_canvas_action",{action:e,rectangleId:n,surface:i})}register(e){this.client?.register?.(e)}getSessionId(){return this.client?.get_session_id?.()}startSessionRecording(){this.client?.startSessionRecording?.()}trackExperiment(e,n,i){let r=`$experiment_${e}`;this.register({[r]:i??`variation_${n}`,[`${r}_id`]:n}),this.track("$experiment_started",{$experiment_key:e,$experiment_variation_id:n,$experiment_variation_name:i??`variation_${n}`})}setPersonProperties(e){this.client?.capture("$set",{$set:e})}setPersonPropertiesOnce(e){this.client?.capture("$set",{$set_once:e})}getDistinctId(){return this.client?.get_distinct_id?.()}};function Ap(t={}){return new gb(t)}var mb=async(t,e)=>{let n=[];if(e.applyAction)for(let i of t.actions){let r=await e.applyAction(i);n.push(r)}return{cleanup:async()=>{for(let i=n.length-1;i>=0;i--)try{await n[i].revert()}catch{}}}},vb=async(t,e)=>{let n=[];if(e.applyAction){let i=t.actions.map(r=>e.applyAction(r));if(t.waitFor==="any"){let r=await Promise.race(i);n.push(r);let a=await Promise.allSettled(i);for(let o of a)o.status==="fulfilled"&&o.value!==r&&n.push(o.value)}else{let r=await Promise.all(i);n.push(...r)}}return{cleanup:async()=>{for(let i of n)try{await i.revert()}catch{}}}},yb=async(t,e)=>{let n,i,r=!1,a={cleanup:()=>{r=!0,i&&clearTimeout(i),n&&n()}};return t.event&&e.subscribeEvent?await new Promise(o=>{n=e.subscribeEvent(t.event,()=>{r||o()}),t.durationMs!==void 0&&(i=setTimeout(()=>{r||o()},t.durationMs))}):t.durationMs!==void 0&&await new Promise(o=>{i=setTimeout(()=>{r||o()},t.durationMs)}),a};var _b="syntro_active_tour",Tp=new Map;function F3(t){try{let e=localStorage.getItem(_b);if(!e)return null;let n=JSON.parse(e);return n.tourId!==t?null:n}catch{return null}}function bb(t){try{localStorage.setItem(_b,JSON.stringify(t))}catch{}}function U3(){try{localStorage.removeItem(_b)}catch{}}function jc(){return window.location.pathname}function V3(t){if(!t.route)return!0;let e=jc();return t.route.includes("*")?new RegExp(`^${t.route.replace(/\*/g,".*")}$`).test(e):e===t.route}var Sb=async(t,e)=>{let{tourId:n,steps:i,startStep:r,autoStart:a=!0}=t;if(i.length===0)throw new Error(`Tour "${n}" has no steps`);if(Tp.has(n))return{cleanup:async()=>{let m=Tp.get(n);m&&await m.cleanup()}};if(!e.applyAction)throw new Error("Tour executor requires applyAction in context");let o=F3(n),s=!!o;if(!s&&!a)return{cleanup:()=>{}};o||(o={tourId:n,currentStepId:r||i[0].id,startedAt:Date.now()},bb(o));let l=i.findIndex(m=>m.id===o.currentStepId);if(l===-1){let m=r||i[0].id;l=i.findIndex(v=>v.id===m),l===-1&&(l=0),o.currentStepId=i[l].id,bb(o)}let c=i[l];if(!V3(c))return e.publishEvent("tour.waiting_for_route",{tourId:n,stepId:c.id,expectedRoute:c.route,currentRoute:jc()}),{cleanup:()=>{}};let u=!1,f=null,h=null,g=null,_=async()=>{h&&(h(),h=null),f?.isApplied()&&(await f.revert(),f=null)},b=async m=>{if(u)return;if(await _(),m==="end"){U3(),e.publishEvent("tour.completed",{tourId:n,totalSteps:i.length}),u=!0;return}let v=i.find(S=>S.id===m);if(!v){console.error(`[Tour] Step "${m}" not found`);return}if(o.currentStepId=m,bb(o),e.publishEvent("tour.step_changed",{tourId:n,previousStepId:c.id,nextStepId:m}),v.route&&v.route!==jc()){e.publishEvent("tour.awaiting_navigation",{tourId:n,stepId:m,targetRoute:v.route});return}await w(v)},w=async m=>{if(!u){e.publishEvent("tour.step_started",{tourId:n,stepId:m.id,stepIndex:i.findIndex(v=>v.id===m.id),totalSteps:i.length});try{f=await e.applyAction(m.action)}catch(v){console.error(`[Tour] Failed to execute step "${m.id}":`,v),e.publishEvent("tour.step_failed",{tourId:n,stepId:m.id,error:String(v)});return}if(m.onAction&&e.subscribeEvent){h=e.subscribeEvent("action.modal_cta_clicked",T=>{let A=T?.actionId;if(A&&m.onAction){let k=m.onAction[A];k&&b(k)}});let v=e.subscribeEvent("action.tooltip_cta_clicked",T=>{let A=T?.actionId;if(A&&m.onAction){let k=m.onAction[A];k&&b(k)}}),S=h;h=()=>{S(),v()}}}};g=(()=>{let m=jc(),v=()=>{let A=jc();A!==m&&(m=A,e.publishEvent("tour.route_changed",{tourId:n,newRoute:A}))};if(e.subscribeNavigation)return e.subscribeNavigation(()=>v());window.addEventListener("popstate",v);let S=history.pushState.bind(history),T=history.replaceState.bind(history);return history.pushState=(...A)=>{S(...A),queueMicrotask(v)},history.replaceState=(...A)=>{T(...A),queueMicrotask(v)},()=>{window.removeEventListener("popstate",v),history.pushState=S,history.replaceState=T}})(),s?e.publishEvent("tour.resumed",{tourId:n,stepId:o.currentStepId}):e.publishEvent("tour.started",{tourId:n,totalSteps:i.length,startStepId:o.currentStepId}),await w(c);let p=async()=>{u=!0,Tp.delete(n),await _(),g&&g(),e.publishEvent("tour.paused",{tourId:n,stepId:o.currentStepId})};return Tp.set(n,{cleanup:p}),{cleanup:p}};var qc=class{constructor(){V(this,"executors",new Map);for(let{kind:e,executor:n}of $m)this.registerCore(e,n);for(let{kind:e,executor:n}of Pm)this.registerCore(e,n);this.registerCore("core:mountWidget",async()=>{throw new Error("core:mountWidget must be handled by ActionEngine")}),this.registerCore("core:sequence",mb),this.registerCore("core:parallel",vb),this.registerCore("core:wait",yb),this.registerCore("core:tour",Sb)}registerCore(e,n,i){this.executors.set(e,{kind:e,executor:n,schema:i,source:"core",isBuiltIn:!0})}register(e,n,i,r="custom",a=!1){if(this.executors.has(e)){if(this.executors.get(e).isBuiltIn)return;console.warn(`[ExecutorRegistry] Overriding executor for kind: ${e} (source: ${r})`)}console.log(`[ExecutorRegistry] Registered executor: ${e} (source: ${r})`),this.executors.set(e,{kind:e,executor:n,schema:i,source:r,isBuiltIn:a})}unregister(e){let n=this.executors.get(e);return n?n.isBuiltIn?(console.warn(`[ExecutorRegistry] Cannot unregister built-in executor: ${e}`),!1):(this.executors.delete(e),!0):!1}unregisterBySource(e){for(let[n,i]of this.executors.entries())i.source===e&&this.executors.delete(n)}get(e){return this.executors.get(e)?.executor}getRegistration(e){return this.executors.get(e)}has(e){return this.executors.has(e)}validate(e){let n=[];if(!e||typeof e!="object")return n.push({code:"INVALID_ACTION",message:"Action must be an object"}),{valid:!1,errors:n,warnings:[]};let{kind:i}=e;if(!i||typeof i!="string")return n.push({code:"MISSING_KIND",message:"Action must have a 'kind' property"}),{valid:!1,errors:n,warnings:[]};let r=this.executors.get(i);if(!r)return n.push({code:"UNKNOWN_KIND",message:`Unknown action kind: ${i}`,field:"kind"}),{valid:!1,errors:n,warnings:[]};if(r.schema){let a=r.schema.safeParse(e);if(!a.success){for(let o of a.error.issues)n.push({code:"SCHEMA_VALIDATION_ERROR",message:o.message,field:o.path.join(".")});return{valid:!1,errors:n,warnings:[]}}}return{valid:!0,errors:[],warnings:[]}}list(){return Array.from(this.executors.keys())}listRegistrations(){return Array.from(this.executors.values())}getBuiltInKinds(){return Array.from(this.executors.entries()).filter(([,e])=>e.isBuiltIn).map(([e])=>e)}getCustomKinds(){return Array.from(this.executors.entries()).filter(([,e])=>!e.isBuiltIn).map(([e])=>e)}},pi=new qc;function ik(t){return pi.get(t)}function kp(t){return pi.has(t)}var j3=new Set(["onclick","onerror","onload","onmouseover","onfocus","onblur","onchange","onsubmit","onkeydown","onkeyup","onkeypress"]),rk=5e4,ak=50;function Ji(t){let e=[],n=[];if(!t||typeof t!="object")return e.push({code:"INVALID_ACTION",message:"Action must be an object"}),{valid:!1,errors:e,warnings:n};let{kind:i}=t;if(!i||typeof i!="string")return e.push({code:"MISSING_KIND",message:"Action must have a 'kind' property"}),{valid:!1,errors:e,warnings:n};if(!kp(i)&&i!=="core:mountWidget"){let r=pi.list();return console.error(`[ActionValidation] Unknown action kind: "${i}". Registered kinds (${r.length}): [${r.join(", ")}]. This usually means the app that provides "${i}" hasn't been activated yet, or the executor was never registered in ExecutorRegistry.`),e.push({code:"UNKNOWN_KIND",message:`Unknown action kind: ${i}`,field:"kind"}),{valid:!1,errors:e,warnings:n}}switch(i){case"overlays:highlight":case"overlays:pulse":case"navigation:scrollTo":na(t,e,n);break;case"overlays:badge":na(t,e,n),q3(t,e,n);break;case"overlays:tooltip":na(t,e,n),P3(t,e,n);break;case"overlays:modal":n5(t,e,n);break;case"content:insertHtml":na(t,e,n),G3(t,e,n);break;case"content:setText":na(t,e,n),Z3(t,e,n);break;case"content:setAttr":na(t,e,n),Y3(t,e,n);break;case"content:addClass":case"content:removeClass":na(t,e,n),W3(t,e,n);break;case"content:setStyle":na(t,e,n),K3(t,e,n);break;case"core:mountWidget":X3(t,e,n);break;case"core:wait":Q3(t,e,n);break;case"core:sequence":J3(t,e,n);break;case"core:parallel":e5(t,e,n);break;case"core:tour":i5(t,e,n);break;case"navigation:navigate":t5(t,e,n);break}return{valid:e.length===0,errors:e,warnings:n}}function na(t,e,n){!t.anchorId||typeof t.anchorId!="string"?e.push({code:"MISSING_ANCHOR_ID",message:"Action requires an 'anchorId' property",field:"anchorId"}):t.anchorId.length>200&&n.push({code:"LONG_ANCHOR_ID",message:"Anchor ID is unusually long",suggestion:"Consider using a shorter, more descriptive ID"})}function q3(t,e,n){!t.content||typeof t.content!="string"?e.push({code:"MISSING_CONTENT",message:"Badge action requires 'content' property",field:"content"}):t.content.length>100&&n.push({code:"LONG_BADGE_CONTENT",message:"Badge content is quite long",suggestion:"Keep badge content short (under 100 characters)"})}function P3(t,e,n){if(!t.content||typeof t.content!="object"){e.push({code:"MISSING_CONTENT",message:"Tooltip action requires 'content' object",field:"content"});return}(!t.content.body||typeof t.content.body!="string")&&e.push({code:"MISSING_BODY",message:"Tooltip content requires 'body' property",field:"content.body"})}function G3(t,e,n){!t.html||typeof t.html!="string"?e.push({code:"MISSING_HTML",message:"insertHtml action requires 'html' property",field:"html"}):t.html.length>rk&&e.push({code:"HTML_TOO_LONG",message:`HTML content exceeds maximum length of ${rk}`,field:"html"});let i=["before","after","prepend","append","replace"];(!t.position||!i.includes(t.position))&&e.push({code:"INVALID_POSITION",message:`Position must be one of: ${i.join(", ")}`,field:"position"})}function Z3(t,e,n){(t.text===void 0||t.text===null)&&e.push({code:"MISSING_TEXT",message:"setText action requires 'text' property",field:"text"})}function Y3(t,e,n){!t.attr||typeof t.attr!="string"?e.push({code:"MISSING_ATTR",message:"setAttr action requires 'attr' property",field:"attr"}):(j3.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 W3(t,e,n){!t.className||typeof t.className!="string"?e.push({code:"MISSING_CLASS_NAME",message:"Class action requires 'className' property",field:"className"}):/^[a-zA-Z_-][a-zA-Z0-9_-]*$/.test(t.className)||n.push({code:"INVALID_CLASS_NAME",message:"Class name contains unusual characters",suggestion:"Use alphanumeric characters, hyphens, and underscores"})}function K3(t,e,n){if(!t.styles||typeof t.styles!="object")e.push({code:"MISSING_STYLES",message:"setStyle action requires 'styles' object",field:"styles"});else{let i=Object.keys(t.styles).length;i>ak&&e.push({code:"TOO_MANY_STYLES",message:`Too many styles (${i}). Maximum is ${ak}`,field:"styles"});for(let[r,a]of Object.entries(t.styles))typeof a=="string"&&a.includes("expression(")&&e.push({code:"DANGEROUS_STYLE",message:`Style expressions are not allowed: ${r}`,field:`styles.${r}`})}}function X3(t,e,n){(!t.slot||typeof t.slot!="string")&&e.push({code:"MISSING_SLOT",message:"mountWidget action requires 'slot' property",field:"slot"}),!t.widget||typeof t.widget!="object"?e.push({code:"MISSING_WIDGET",message:"mountWidget action requires 'widget' object",field:"widget"}):(!t.widget.widgetId||typeof t.widget.widgetId!="string")&&e.push({code:"MISSING_WIDGET_ID",message:"Widget must have a 'widgetId' property",field:"widget.widgetId"})}function Q3(t,e,n){t.durationMs===void 0&&!t.event&&e.push({code:"MISSING_WAIT_CONFIG",message:"wait action requires either 'durationMs' or 'event' property"}),t.durationMs!==void 0&&t.durationMs<0&&e.push({code:"INVALID_DURATION",message:"durationMs must be a positive number",field:"durationMs"}),t.event!==void 0&&typeof t.event!="string"&&e.push({code:"INVALID_EVENT",message:"event must be a string",field:"event"})}function J3(t,e,n){if(!t.actions||!Array.isArray(t.actions)){e.push({code:"MISSING_ACTIONS",message:"sequence action requires 'actions' array",field:"actions"});return}t.actions.length===0&&n.push({code:"EMPTY_SEQUENCE",message:"sequence has no actions",suggestion:"Add at least one action to the sequence"});for(let i=0;i<t.actions.length;i++){let r=Ji(t.actions[i]);for(let a of r.errors)e.push({...a,field:`actions[${i}]${a.field?`.${a.field}`:""}`});for(let a of r.warnings)n.push(a)}}function e5(t,e,n){if(!t.actions||!Array.isArray(t.actions)){e.push({code:"MISSING_ACTIONS",message:"parallel action requires 'actions' array",field:"actions"});return}t.actions.length===0&&n.push({code:"EMPTY_PARALLEL",message:"parallel has no actions",suggestion:"Add at least one action to the parallel group"}),t.waitFor&&!["all","any"].includes(t.waitFor)&&e.push({code:"INVALID_WAIT_FOR",message:"waitFor must be 'all' or 'any'",field:"waitFor"});for(let i=0;i<t.actions.length;i++){let r=Ji(t.actions[i]);for(let a of r.errors)e.push({...a,field:`actions[${i}]${a.field?`.${a.field}`:""}`});for(let a of r.warnings)n.push(a)}}function t5(t,e,n){if(!t.url||typeof t.url!="string")e.push({code:"MISSING_URL",message:"navigate action requires 'url' property",field:"url"});else{let i=t.url.trim().toLowerCase();i.startsWith("javascript:")&&e.push({code:"DANGEROUS_URL",message:"javascript: URLs are not allowed",field:"url"}),i.startsWith("data:")&&n.push({code:"DATA_URL",message:"data: URLs may have limited support",suggestion:"Consider using a regular URL instead"})}}function n5(t,e,n){if(!t.content||typeof t.content!="object"){e.push({code:"MISSING_CONTENT",message:"Modal action requires 'content' object",field:"content"});return}if((!t.content.body||typeof t.content.body!="string")&&e.push({code:"MISSING_BODY",message:"Modal content requires 'body' property",field:"content.body"}),t.size&&!["sm","md","lg"].includes(t.size)&&e.push({code:"INVALID_SIZE",message:"Modal size must be 'sm', 'md', or 'lg'",field:"size"}),t.ctaButtons)if(!Array.isArray(t.ctaButtons))e.push({code:"INVALID_CTA_BUTTONS",message:"ctaButtons must be an array",field:"ctaButtons"});else for(let i=0;i<t.ctaButtons.length;i++){let r=t.ctaButtons[i];(!r.label||typeof r.label!="string")&&e.push({code:"MISSING_BUTTON_LABEL",message:`CTA button at index ${i} requires 'label' property`,field:`ctaButtons[${i}].label`}),(!r.actionId||typeof r.actionId!="string")&&e.push({code:"MISSING_BUTTON_ACTION_ID",message:`CTA button at index ${i} requires 'actionId' property`,field:`ctaButtons[${i}].actionId`})}}function i5(t,e,n){if((!t.tourId||typeof t.tourId!="string")&&e.push({code:"MISSING_TOUR_ID",message:"Tour action requires 'tourId' property",field:"tourId"}),!t.steps||!Array.isArray(t.steps)){e.push({code:"MISSING_STEPS",message:"Tour action requires 'steps' array",field:"steps"});return}t.steps.length===0&&e.push({code:"EMPTY_STEPS",message:"Tour must have at least one step",field:"steps"});let i=new Set;for(let r=0;r<t.steps.length;r++){let a=t.steps[r];if(!a.id||typeof a.id!="string"?e.push({code:"MISSING_STEP_ID",message:`Step at index ${r} requires 'id' property`,field:`steps[${r}].id`}):(i.has(a.id)&&e.push({code:"DUPLICATE_STEP_ID",message:`Duplicate step ID: ${a.id}`,field:`steps[${r}].id`}),i.add(a.id)),!a.action)e.push({code:"MISSING_STEP_ACTION",message:`Step at index ${r} requires 'action' property`,field:`steps[${r}].action`});else{let o=Ji(a.action);for(let s of o.errors)e.push({...s,field:`steps[${r}].action${s.field?`.${s.field}`:""}`});for(let s of o.warnings)n.push(s)}if(a.onAction)for(let[o,s]of Object.entries(a.onAction))s!=="end"&&!t.steps.some(l=>l.id===s)&&n.push({code:"UNKNOWN_TARGET_STEP",message:`Step "${a.id}" references unknown target step: ${s}`,suggestion:`Make sure step "${s}" exists in the tour`})}}function Rp(t){let e=[],n=[];if(!Array.isArray(t))return console.error("[ActionValidation] validateActions called with non-array:",typeof t),e.push({code:"INVALID_ACTIONS",message:"Actions must be an array"}),{valid:!1,errors:e,warnings:n};for(let i=0;i<t.length;i++){let r=Ji(t[i]);if(!r.valid){let a=t[i];console.error(`[ActionValidation] Action [${i}] failed validation:`,`kind="${a?.kind??"undefined"}"`,r.errors.map(o=>`${o.code}: ${o.message}`).join("; "),a)}for(let a of r.errors)e.push({...a,field:a.field?`[${i}].${a.field}`:`[${i}]`});for(let a of r.warnings)n.push({...a,suggestion:a.suggestion?`Action ${i}: ${a.suggestion}`:void 0})}return e.length>0&&console.error(`[ActionValidation] Batch validation failed: ${e.length} error(s) in ${t.length} action(s).`,e.map(i=>`${i.field??"?"}: ${i.message}`).join(" | ")),{valid:e.length===0,errors:e,warnings:n}}var r5=0;function Op(t){let{overlayRoot:e,eventBus:n,surfaces:i,anchorResolver:r,adaptiveId:a,executorRegistry:o=pi,subscribeNavigation:s}=t,l=new Map;function c(){return`action-${++r5}`}function u(p,m){n&&n.publish(p,m)}function f(){return{overlayRoot:e,resolveAnchor:r,generateId:c,publishEvent:u,adaptiveId:a,applyAction:g,subscribeEvent:n?(p,m)=>n.subscribe({names:[p]},v=>m(v.props)):void 0,subscribeNavigation:s}}async function h(p,m){if(!i)throw new Error("Surfaces provider required for core:mountWidget actions");let v=i.mount(p.slot,{type:"widget",widgetId:p.widget.widgetId,config:p.widget.props},{priority:p.widget.priority});return m.publishEvent("action.applied",{id:m.generateId(),kind:"core:mountWidget",slot:p.slot,widgetId:p.widget.widgetId}),{cleanup:()=>{v.unmount()},updateFn:S=>{if("widget"in S&&S.widget){let T=S.widget;T.props&&v.update({type:"widget",widgetId:p.widget.widgetId,config:T.props})}}}}async function g(p){let m=Ji(p);if(!m.valid){let C=m.errors.map(x=>x.message).join("; ");throw console.error(`[ActionEngine] Validation failed for action kind="${p?.kind}":`,C,p),new Error(`Action validation failed: ${C}`)}let v=c(),S=f(),T;if(p.kind==="core:mountWidget")T=await h(p,S);else{let C=o.get(p.kind);if(!C){let x="list"in o?o.list():"(list unavailable)";throw console.error(`[ActionEngine] No executor for kind="${p.kind}".`,`Registered: [${x}]`),new Error(`No executor for action kind: ${p.kind}`)}T=await C(p,S)}let A={id:v,action:p,adaptiveId:a,appliedTs:Date.now(),state:"applied",cleanup:T.cleanup,updateFn:T.updateFn};return l.set(v,A),u("action.applied",{id:v,kind:p.kind,anchorId:"anchorId"in p?p.anchorId:void 0}),{id:v,action:p,async revert(){let C=l.get(v);if(!(!C||C.state!=="applied"))try{await C.cleanup(),C.state="reverted",u("action.reverted",{id:v,kind:p.kind})}catch(x){throw C.state="failed",u("action.failed",{id:v,kind:p.kind,error:String(x)}),x}finally{l.delete(v)}},isApplied(){return l.get(v)?.state==="applied"},async update(C){let x=l.get(v);if(!x||x.state!=="applied")throw new Error("Cannot update action that is not applied");if(x.updateFn)await x.updateFn(C);else throw new Error(`Action kind ${p.kind} does not support updates`)},getState(){return l.get(v)?.state??"reverted"}}}async function _(p){console.log(`[ActionEngine] applyBatch: ${p.length} action(s)`,p.map(k=>k.kind).join(", "));let m=Rp(p);if(!m.valid){let k=m.errors.map(C=>C.message).join("; ");throw console.error(`[ActionEngine] Batch validation FAILED for ${p.length} action(s):`,k,`
|
|
448
448
|
Actions:`,p.map((C,x)=>` [${x}] ${C.kind} ${C.anchorId?`anchor="${C.anchorId}"`:""} ${C.label?`label="${C.label}"`:""}`).join(`
|
|
449
|
-
`)),new Error(`Batch validation failed: ${k}`)}let v=c(),S=[],T=[];try{for(let k of p){let C=await g(k);S.push(C),T.push(C)}}catch(k){console.error(`[ActionEngine] Batch apply FAILED at action ${T.length+1}/${p.length}.`,`Successfully applied: ${T.length}. Rolling back...`,k);for(let C of T)try{await C.revert()}catch{}throw k}return{id:v,handles:S,async revertAll(){for(let k=S.length-1;k>=0;k--)try{await S[k].revert()}catch(C){console.error(`[ActionEngine] Error reverting action ${S[k].id}:`,C)}},isApplied(){return S.every(k=>k.isApplied())}}}function b(p){return Ji(p)}function w(){return Array.from(l.values()).map(p=>({id:p.id,action:p.action,adaptiveId:p.adaptiveId,appliedTs:p.appliedTs,state:p.state}))}function d(){for(let p of l.values())if(p.state==="applied")try{p.cleanup()}catch(m){console.error("[ActionEngine] Error during cleanup:",m)}l.clear()}return{apply:g,applyBatch:_,validate:b,getActive:w,destroy:d}}var ok=y.object({type:y.literal("page_url"),url:y.string()}),sk=y.object({type:y.literal("route"),routeId:y.string()}),lk=y.object({type:y.literal("anchor_visible"),anchorId:y.string(),state:y.enum(["visible","present","absent"])}),ck=y.object({type:y.literal("event_occurred"),eventName:y.string(),withinMs:y.number().optional()}),uk=y.object({type:y.literal("state_equals"),key:y.string(),value:y.unknown()}),dk=y.object({type:y.literal("viewport"),minWidth:y.number().optional(),maxWidth:y.number().optional(),minHeight:y.number().optional(),maxHeight:y.number().optional()}),fk=y.object({type:y.literal("session_metric"),key:y.string(),operator:y.enum(["gte","lte","eq","gt","lt"]),threshold:y.number()}),pk=y.object({type:y.literal("dismissed"),key:y.string(),inverted:y.boolean().optional()}),hk=y.object({type:y.literal("cooldown_active"),key:y.string(),inverted:y.boolean().optional()}),gk=y.object({type:y.literal("frequency_limit"),key:y.string(),limit:y.number(),inverted:y.boolean().optional()}),mk=y.object({type:y.literal("event_count"),key:y.string(),operator:y.enum(["gte","lte","eq","gt","lt"]),count:y.number().int().min(0),withinMs:y.number().positive().optional()}),Mp=y.discriminatedUnion("type",[ok,sk,lk,ck,uk,dk,fk,pk,hk,gk,mk]),xb=y.object({conditions:y.array(Mp),value:y.unknown()}),wb=y.object({type:y.literal("rules"),rules:y.array(xb),default:y.unknown()}),Eb=y.object({type:y.literal("score"),field:y.string(),threshold:y.number(),above:y.unknown(),below:y.unknown()}),Cb=y.object({type:y.literal("model"),modelId:y.string(),inputs:y.array(y.string()),outputMapping:y.record(y.string(),y.unknown()),default:y.unknown()}),Ab=y.object({type:y.literal("external"),endpoint:y.string(),method:y.enum(["GET","POST"]).optional(),default:y.unknown(),timeoutMs:y.number().optional()}),Tb=y.discriminatedUnion("type",[wb,Eb,Cb,Ab]),kb=y.object({include:y.array(y.string()).optional(),exclude:y.array(y.string()).optional()}),Pc=y.object({routes:kb,strategy:Tb.optional()});function a5(t){return Mp.safeParse(t)}function o5(t){return Tb.safeParse(t)}function s5(t){return Pc.safeParse(t)}var l5=[{defName:"activationConfig",schema:Pc},{defName:"routeFilter",schema:kb},{defName:"ruleStrategy",schema:wb},{defName:"scoreStrategy",schema:Eb},{defName:"modelStrategy",schema:Cb},{defName:"externalStrategy",schema:Ab},{defName:"rule",schema:xb},{defName:"condition",schema:Mp}];var pt={activation:Pc.optional()},Rb=y.object({color:y.string().optional(),scrimOpacity:y.number().min(0).max(1).optional(),paddingPx:y.number().optional(),radiusPx:y.number().optional()}).strict(),Ob=y.enum(["top-left","top-right","bottom-left","bottom-right"]),Mb=y.enum(["top","top-start","top-end","bottom","bottom-start","bottom-end","left","left-start","left-end","right","right-start","right-end"]),Dp=y.object({label:y.string(),actionId:y.string(),primary:y.boolean().optional()}).strict(),Nb=y.object({title:y.string().optional(),body:y.string(),ctaButtons:y.array(Dp).optional()}).strict(),Db=y.object({title:y.string().optional(),body:y.string()}).strict(),Lb=y.enum(["before","after","prepend","append","replace"]),Hb=y.enum(["immediate","hover","click"]),Ib=y.object({widgetId:y.string(),props:y.record(y.unknown()).optional(),priority:y.number().optional()}).strict(),zb=y.object({id:y.string(),action:y.any(),route:y.string().optional(),onAction:y.record(y.string()).optional()}).strict(),Bb=y.enum(["auto","smooth","instant"]),Np=y.enum(["start","center","end","nearest"]),$b=y.object({kind:y.literal("content:setText"),anchorId:y.string(),text:y.string(),label:y.string().optional()}).extend(pt).strict(),Fb=y.object({kind:y.literal("content:setAttr"),anchorId:y.string(),attr:y.string(),value:y.string(),label:y.string().optional()}).extend(pt).strict(),Ub=y.object({kind:y.literal("content:addClass"),anchorId:y.string(),className:y.string(),label:y.string().optional()}).extend(pt).strict(),Vb=y.object({kind:y.literal("content:removeClass"),anchorId:y.string(),className:y.string(),label:y.string().optional()}).extend(pt).strict(),jb=y.object({kind:y.literal("content:setStyle"),anchorId:y.string(),styles:y.record(y.string()),label:y.string().optional()}).extend(pt).strict(),qb=y.object({kind:y.literal("content:insertHtml"),anchorId:y.string(),html:y.string(),position:Lb,label:y.string().optional()}).extend(pt).strict(),Pb=y.object({kind:y.literal("overlays:highlight"),anchorId:y.string(),style:Rb.optional(),duration:y.number().optional(),label:y.string().optional()}).extend(pt).strict(),Gb=y.object({kind:y.literal("overlays:pulse"),anchorId:y.string(),duration:y.number().optional(),label:y.string().optional()}).extend(pt).strict(),Zb=y.object({kind:y.literal("overlays:badge"),anchorId:y.string(),content:y.string(),position:Ob.optional(),label:y.string().optional()}).extend(pt).strict(),Yb=y.object({kind:y.literal("overlays:tooltip"),anchorId:y.string(),content:Nb,trigger:Hb.optional(),placement:Mb.optional(),waitFor:y.string().optional(),label:y.string().optional()}).extend(pt).strict(),Wb=y.object({kind:y.literal("overlays:modal"),content:Db,size:y.enum(["sm","md","lg"]).optional(),blocking:y.boolean().optional(),scrim:y.object({opacity:y.number().min(0).max(1).optional()}).strict().optional(),dismiss:y.object({onEsc:y.boolean().optional(),closeButton:y.boolean().optional(),timeoutMs:y.number().min(0).optional()}).strict().optional(),ctaButtons:y.array(Dp).optional(),waitFor:y.string().optional(),label:y.string().optional()}).extend(pt).strict(),Kb=y.object({kind:y.literal("navigation:scrollTo"),anchorId:y.string(),behavior:Bb.optional(),block:Np.optional(),inline:Np.optional(),label:y.string().optional()}).extend(pt).strict(),Xb=y.object({kind:y.literal("navigation:navigate"),url:y.string(),target:y.enum(["_self","_blank"]).optional(),label:y.string().optional()}).extend(pt).strict(),Qb=y.object({kind:y.literal("core:mountWidget"),slot:y.string(),widget:Ib,label:y.string().optional()}).extend(pt).strict(),Jb=y.object({kind:y.literal("core:wait"),durationMs:y.number().min(0).optional(),event:y.string().optional(),label:y.string().optional()}).extend(pt).strict(),e_=y.object({kind:y.literal("core:sequence"),actions:y.array(y.any()),label:y.string().optional()}).extend(pt).strict(),t_=y.object({kind:y.literal("core:parallel"),actions:y.array(y.any()),waitFor:y.enum(["all","any"]).optional(),label:y.string().optional()}).extend(pt).strict(),n_=y.object({kind:y.literal("core:tour"),tourId:y.string(),steps:y.array(zb).min(1),startStep:y.string().optional(),autoStart:y.boolean().optional(),label:y.string().optional()}).extend(pt).strict(),vk=[{defName:"setText",schema:$b},{defName:"setAttr",schema:Fb},{defName:"addClass",schema:Ub},{defName:"removeClass",schema:Vb},{defName:"setStyle",schema:jb},{defName:"insertHtml",schema:qb},{defName:"highlight",schema:Pb},{defName:"pulse",schema:Gb},{defName:"badge",schema:Zb},{defName:"tooltip",schema:Yb},{defName:"modal",schema:Wb},{defName:"scrollTo",schema:Kb},{defName:"navigate",schema:Xb},{defName:"mountWidget",schema:Qb},{defName:"wait",schema:Jb},{defName:"sequence",schema:e_},{defName:"parallel",schema:t_},{defName:"tour",schema:n_}];function c5(){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 i_(t,e){if(!e)return;let n;try{n=new URL(t).pathname}catch{n=t}if(e.exclude){for(let i of e.exclude)if(yk(n,i))return}if(e.include){for(let i of e.include)if(yk(n,i))return i;return}return n}function yk(t,e){let n=t.replace(/\/$/,"")||"/",i=e.replace(/\/$/,"")||"/";if(n===i)return!0;let r=i.replace(/:[^/]+/g,"[^/]+").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(n)}var Gc=class{constructor(e={}){V(this,"context");V(this,"previousContext");V(this,"listeners",new Set);V(this,"telemetry");V(this,"routes");V(this,"navigation");V(this,"cleanupFns",[]);if(this.telemetry=e.telemetry,this.routes=e.routes,this.navigation=e.navigation,this.context=c5(),this.previousContext={...this.context},e.telemetry?.getSessionId){let n=e.telemetry.getSessionId();n&&(this.context.session.sessionId=n)}e.initialPageHistory&&(this.context.session.pageHistory=e.initialPageHistory),this.context.page.routeId=i_(this.context.page.url,this.routes),this.addPageToHistory(this.context.page.url),typeof window<"u"&&this.setupBrowserListeners()}get(){return{...this.context}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}setRoutes(e){this.routes=e;let n=i_(this.context.page.url,this.routes);n!==this.context.page.routeId&&this.updateContext({page:{...this.context.page,routeId:n}})}setAnchors(e){this.updateContext({anchors:e})}setSessionId(e){e!==this.context.session.sessionId&&this.updateContext({session:{...this.context.session,sessionId:e}})}destroy(){for(let e of this.cleanupFns)e();this.cleanupFns=[],this.listeners.clear()}setupBrowserListeners(){let e,n=()=>{clearTimeout(e),e=setTimeout(()=>{this.updateViewport()},100)};if(window.addEventListener("resize",n),this.cleanupFns.push(()=>window.removeEventListener("resize",n)),this.navigation){let i=this.navigation.subscribe(()=>this.updatePage());this.cleanupFns.push(i)}else{let i=()=>{this.updatePage()};window.addEventListener("popstate",i),this.cleanupFns.push(()=>window.removeEventListener("popstate",i));let r=history.pushState.bind(history),a=history.replaceState.bind(history);history.pushState=(...o)=>{r(...o),queueMicrotask(()=>this.updatePage())},history.replaceState=(...o)=>{a(...o),queueMicrotask(()=>this.updatePage())},this.cleanupFns.push(()=>{history.pushState=r,history.replaceState=a})}}updateViewport(){let e={width:window.innerWidth,height:window.innerHeight};(e.width!==this.context.viewport.width||e.height!==this.context.viewport.height)&&this.updateContext({viewport:e})}updatePage(){let e=window.location.href,{title:n}=document,i=i_(e,this.routes),r={url:e,title:n,routeId:i};(r.url!==this.context.page.url||r.title!==this.context.page.title||r.routeId!==this.context.page.routeId)&&(r.url!==this.context.page.url&&this.addPageToHistory(r.url),this.updateContext({page:r}))}addPageToHistory(e){let n={url:e,ts:Date.now()},i=[...this.context.session.pageHistory||[],n];i.length>50&&i.shift(),this.context.session.pageHistory=i}updateContext(e){this.previousContext={...this.context},this.context={...this.context,...e},this.notifyListeners()}notifyListeners(){for(let e of this.listeners)try{e(this.context,this.previousContext)}catch(n){console.error("[ContextManager] Listener error:",n)}}};function Lp(t={}){return new Gc(t)}var bk=y.object({url:y.string(),routeId:y.string().optional(),title:y.string().optional(),locale:y.string().optional()}),_k=y.object({url:y.string(),ts:y.number()}),Sk=y.object({sessionId:y.string(),startTs:y.number(),pageHistory:y.array(_k).optional()}),xk=y.object({width:y.number(),height:y.number()}),wk=y.object({x:y.number(),y:y.number(),w:y.number(),h:y.number()}),Ek=y.object({anchorId:y.string(),present:y.boolean(),visible:y.boolean().optional(),boundingBox:wk.optional()}),Ck=y.record(y.string(),y.union([y.number(),y.string(),y.boolean(),y.undefined()])),Ak=y.object({page:bk,session:Sk,viewport:xk,anchors:y.array(Ek).optional(),augmented:Ck.optional()});function u5(t){return Ak.safeParse(t)}function r_(t,e){let{context:n,state:i,events:r}=e;switch(t.type){case"page_url":{let{url:a}=t,o=n.page.url,s=a.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*");return new RegExp(`^${s}$`).test(o)}case"route":return n.page.routeId===t.routeId;case"anchor_visible":{let a=n.anchors?.find(o=>o.anchorId===t.anchorId);switch(t.state){case"visible":return a?.visible===!0;case"present":return a?.present===!0;case"absent":return!a?.present;default:return!1}}case"event_occurred":{if(!r)return!1;let a=t.withinMs??6e4;return r.hasRecentEvent(t.eventName,a)}case"state_equals":return!1;case"viewport":{let{width:a,height:o}=n.viewport;return!(t.minWidth!==void 0&&a<t.minWidth||t.maxWidth!==void 0&&a>t.maxWidth||t.minHeight!==void 0&&o<t.minHeight||t.maxHeight!==void 0&&o>t.maxHeight)}case"session_metric":{if(!i)return!1;let a=i.getSessionMetric(t.key),{operator:o,threshold:s}=t;switch(o){case"gte":return a>=s;case"lte":return a<=s;case"eq":return a===s;case"gt":return a>s;case"lt":return a<s;default:return!1}}case"dismissed":{if(!i)return t.inverted??!1;let a=i.isDismissed(t.key);return t.inverted?!a:a}case"cooldown_active":{if(!i)return t.inverted??!1;let a=i.isCooldownActive(t.key);return t.inverted?!a:a}case"frequency_limit":{if(!i)return t.inverted??!1;let o=i.getFrequencyCount(t.key)>=t.limit;return t.inverted?!o:o}case"event_count":{if(!e.accumulator)return!1;let a=t,o=e.accumulator.getCount(a.key,a.withinMs);switch(a.operator){case"gte":return o>=a.count;case"lte":return o<=a.count;case"eq":return o===a.count;case"gt":return o>a.count;case"lt":return o<a.count;default:return!1}}default:return console.warn("[RuleStrategy] Unknown condition type:",t.type),!1}}function a_(t,e){let n=[];for(let i of t.conditions){let r=r_(i,e);if(n.push({condition:i,result:r}),!r)return{matched:!1,conditionResults:n}}return{matched:!0,conditionResults:n}}function Zc(t,e){for(let n=0;n<t.rules.length;n++){let i=t.rules[n],{matched:r,conditionResults:a}=a_(i,e);if(r)return{value:i.value,isFallback:!1,matchInfo:{strategyType:"rules",matchedRuleIndex:n,evaluatedConditions:a}}}return{value:t.default,isFallback:!0,matchInfo:{strategyType:"rules"}}}function Yc(t,e){let{context:n}=e,i=n.augmented?.[t.field];return i===void 0||typeof i!="number"?{value:t.below,isFallback:!0,matchInfo:{strategyType:"score"}}:{value:i>=t.threshold?t.above:t.below,isFallback:!1,matchInfo:{strategyType:"score"}}}function Tk(t,e){let{state:n,events:i,sessionMetrics:r,accumulator:a}=e;return{context:t,state:n?{isDismissed:o=>n.dismissals.isDismissed(o),isCooldownActive:o=>n.cooldowns.isActive(o),getFrequencyCount:o=>n.frequency.count(o),getSessionMetric:o=>r?.get(o)??0}:void 0,events:i?{hasRecentEvent:(o,s)=>i.hasRecentEvent(o,s)}:void 0,accumulator:a?{getCount:(o,s)=>a.getCount(o,s)}:void 0}}async function o_(t,e,n={}){let i=Tk(e,n);switch(t.type){case"rules":return Zc(t,i);case"score":return Yc(t,i);case"model":return{value:t.default,isFallback:!0,matchInfo:{strategyType:"model"}};case"external":return{value:t.default,isFallback:!0,matchInfo:{strategyType:"external"}};default:return console.warn("[DecisionEngine] Unknown strategy type:",t.type),{value:void 0,isFallback:!0,matchInfo:{strategyType:t.type}}}}function s_(t,e,n={}){let i=Tk(e,n);switch(t.type){case"rules":return Zc(t,i);case"score":return Yc(t,i);case"model":case"external":return{value:t.default,isFallback:!0,matchInfo:{strategyType:t.type}};default:return{value:void 0,isFallback:!0,matchInfo:{strategyType:t.type}}}}function Hp(t){return{evaluate:(e,n)=>o_(e,n,t),evaluateSync:(e,n)=>s_(e,n,t)}}function Ip(t){let{eventBus:e,stateStore:n}=t,i=new Map,r=new Set,a=null,o=n.ns("accumulator");function s(c){let u=!1;for(let f of i.values()){if(!f.predicate(c))continue;let h=o.get(f.stateKey)||{count:0};h.count++,f.needsTimestamps&&(h.timestamps||(h.timestamps=[]),h.timestamps.push(c.ts),h.timestamps.length>200&&(h.timestamps=h.timestamps.slice(-200))),o.set(f.stateKey,h),u=!0}if(u)for(let f of r)try{f()}catch(h){console.error("[EventAccumulator] Subscriber error:",h)}}function l(){a||i.size===0||(a=e.subscribe(s))}return{register(c,u,f=!1){let h=`ev:${c}`,g=i.get(h);if(g){f&&!g.needsTimestamps&&(g.needsTimestamps=!0);return}i.set(h,{stateKey:h,needsTimestamps:f,predicate:u}),l()},getCount(c,u){let f=`ev:${c}`,h=o.get(f);if(!h)return 0;if(u===void 0||!h.timestamps)return h.count;let g=Date.now()-u;return h.timestamps.filter(_=>_>=g).length},subscribe(c){return r.add(c),()=>{r.delete(c)}},destroy(){a&&(a(),a=null),i.clear(),r.clear()}}}function l_(t,e){return e?!(e.names&&e.names.length>0&&!e.names.includes(t.name)||e.patterns&&e.patterns.length>0&&!e.patterns.some(i=>{try{return new RegExp(i).test(t.name)}catch{return!1}})||e.sources&&e.sources.length>0&&!e.sources.includes(t.source)):!0}var Wc=class{constructor(e={}){V(this,"subscriptions",new Set);V(this,"history",[]);V(this,"maxHistorySize");this.maxHistorySize=e.maxHistorySize??100}subscribe(e,n){let i,r;typeof e=="function"?(i=void 0,r=e):(i=e,r=n);let a={filter:i,callback:r};return this.subscriptions.add(a),()=>{this.subscriptions.delete(a)}}publish(e,n,i="canvas"){let r={ts:Date.now(),name:e,source:i,props:n,schemaVersion:Na};this.publishEvent(r)}publishEvent(e){this.history.push(e),this.history.length>this.maxHistorySize&&this.history.shift();for(let n of this.subscriptions)if(l_(e,n.filter))try{n.callback(e)}catch(i){console.error("[EventBus] Subscriber error:",i)}}getRecent(e,n){let i=this.history;return e&&(i=i.filter(r=>l_(r,e))),n&&n>0&&(i=i.slice(-n)),i}hasRecentEvent(e,n,i){let r=Date.now()-n;return this.history.some(a=>a.name===e&&a.ts>=r&&(i===void 0||a.source===i))}countRecentEvents(e,n){let i=this.history.filter(r=>l_(r,e));if(n!==void 0){let r=Date.now()-n;i=i.filter(a=>a.ts>=r)}return i.length}clearHistory(){this.history=[]}getSubscriberCount(){return this.subscriptions.size}};function zs(t={}){return new Wc(t)}var kk={$autocapture:"ui.click",$click:ye.UI_CLICK,$scroll:ye.UI_SCROLL,$input:ye.UI_INPUT,$change:ye.UI_CHANGE,$submit:ye.UI_SUBMIT,$pageview:ye.NAV_PAGE_VIEW,$pageleave:ye.NAV_PAGE_LEAVE,$session_start:"session.start",$identify:"user.identify"};function d5(t){let e=t.event;if(typeof e!="string")return"posthog.unknown";if(kk[e])return kk[e];if(e==="$autocapture"){let n=t.properties?.$tag_name,i=t.properties?.$event_type;return i==="submit"?ye.UI_SUBMIT:i==="change"?ye.UI_CHANGE:n==="input"||n==="textarea"?ye.UI_INPUT:ye.UI_CLICK}return e.startsWith("$")?e.replace("$","posthog."):`posthog.${e}`}function f5(t){let e={},n=t.properties||{},i=n.$elements;return n.$tag_name?e.tagName=n.$tag_name:i?.[0]?.tag_name&&(e.tagName=i[0].tag_name),n.$el_text&&(e.elementText=n.$el_text),i&&(e.elements=i),n.$current_url&&(e.url=n.$current_url),n.$pathname&&(e.pathname=n.$pathname),n.$host&&(e.host=n.$host),n.$viewport_width&&(e.viewportWidth=n.$viewport_width),n.$viewport_height&&(e.viewportHeight=n.$viewport_height),n.$session_id&&(e.sessionId=n.$session_id),n.$scroll_depth&&(e.scrollDepth=n.$scroll_depth),n.$scroll_percentage&&(e.scrollPercentage=n.$scroll_percentage),e.originalEvent=t.event,e}function c_(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:d5(t),source:"posthog",props:f5(t),schemaVersion:Na}}function u_(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 zp(t){return(e,n)=>{if(typeof e!="string")return;let i={event:e,properties:n,timestamp:Date.now()};if(u_(i)){let r=c_(i);t(r)}}}var d_=y.enum(["posthog","canvas","derived"]),Rk=y.object({ts:y.number(),name:y.string(),source:d_,props:y.record(y.string(),y.unknown()).optional(),schemaVersion:y.string()}),Ok=y.object({names:y.array(y.string()).optional(),patterns:y.array(y.string()).optional(),sources:y.array(d_).optional()});function p5(t){return Rk.safeParse(t)}function h5(t){return Ok.safeParse(t)}var Bs=class{constructor(){V(this,"listeners",new Set);V(this,"capturedPushState");V(this,"capturedReplaceState");V(this,"wasNative");V(this,"destroyed",!1);V(this,"onPopState",()=>{this.notify(window.location.href,"popstate")});this.wasNative=this.isNativeFunction(history.pushState),this.capturedPushState=history.pushState,this.capturedReplaceState=history.replaceState,history.pushState=(...e)=>{this.capturedPushState.call(history,...e),queueMicrotask(()=>this.notify(window.location.href,"pushState"))},history.replaceState=(...e)=>{this.capturedReplaceState.call(history,...e),queueMicrotask(()=>this.notify(window.location.href,"replaceState"))},window.addEventListener("popstate",this.onPopState)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}diagnose(){return{isNative:this.wasNative,subscriberCount:this.listeners.size}}destroy(){this.destroyed||(this.destroyed=!0,history.pushState=this.capturedPushState,history.replaceState=this.capturedReplaceState,window.removeEventListener("popstate",this.onPopState),this.listeners.clear())}notify(e,n){if(!this.destroyed)for(let i of this.listeners)try{i(e,n)}catch{}}isNativeFunction(e){try{return Function.prototype.toString.call(e).includes("[native code]")}catch{return!1}}};var f_="cooldown:";function Mk(t){return{set(e,n){let i=f_+e,r=Date.now()+n;t.set(i,r)},isActive(e){return this.remaining(e)>0},remaining(e){let n=f_+e,i=t.get(n);if(i===void 0)return 0;let r=i-Date.now();return r<=0?(t.remove(n),0):r},clear(e){let n=f_+e;t.remove(n)}}}var Kc="dismissed:";function Nk(t,e){return{mark(n,i=!1){let r=Kc+n;(i?e:t).set(r,!0)},isDismissed(n){let i=Kc+n;return t.has(i)||e.has(i)},clear(n){let i=Kc+n;t.remove(i),e.remove(i)},clearAll(){for(let n of t.keys())n.startsWith(Kc)&&t.remove(n);for(let n of e.keys())n.startsWith(Kc)&&e.remove(n)}}}var p_="freq:";function Dk(t){function e(n){let i=p_+n,r=t.get(i);if(r){if(r.resetAt&&Date.now()>=r.resetAt){t.remove(i);return}return r}}return{increment(n,i){let r=p_+n,a=e(n),o=(a?.count??0)+1,s={count:o,resetAt:a?.resetAt??(i?Date.now()+i:void 0)};return t.set(r,s),o},count(n){return e(n)?.count??0},reset(n){let i=p_+n;t.remove(i)},hasReachedLimit(n,i){return this.count(n)>=i}}}var g5="syntro";function h_(t,e){let n=`${e}:`;return{get(i){if(t)try{let r=t.getItem(n+i);if(!r)return;let a=JSON.parse(r);if(a.expiresAt&&Date.now()>=a.expiresAt){t.removeItem(n+i);return}return a.value}catch{return}},set(i,r,a){if(t)try{let o={value:r,expiresAt:a?Date.now()+a:void 0};t.setItem(n+i,JSON.stringify(o))}catch(o){console.warn("[StateStore] Failed to save:",o)}},remove(i){t&&t.removeItem(n+i)},has(i){return t?this.get(i)!==void 0:!1},keys(){if(!t)return[];let i=[];for(let r=0;r<t.length;r++){let a=t.key(r);a?.startsWith(n)&&i.push(a.slice(n.length))}return i},clear(){if(!t)return;let i=this.keys();for(let r of i)t.removeItem(n+r)}}}function g_(t){let e=new Map,n=`${t}:`;return{get(i){let r=e.get(n+i);if(r){if(r.expiresAt&&Date.now()>=r.expiresAt){e.delete(n+i);return}return r.value}},set(i,r,a){e.set(n+i,{value:r,expiresAt:a?Date.now()+a:void 0})},remove(i){e.delete(n+i)},has(i){return this.get(i)!==void 0},keys(){let i=[];for(let r of e.keys())r.startsWith(n)&&i.push(r.slice(n.length));return i},clear(){for(let i of e.keys())i.startsWith(n)&&e.delete(i)}}}var Xc=class{constructor(e={}){V(this,"session");V(this,"user");V(this,"dismissals");V(this,"cooldowns");V(this,"frequency");V(this,"namespace");V(this,"namespacedStorages",new Map);this.namespace=e.namespace??g5,typeof window<"u"?(this.session=h_(typeof sessionStorage<"u"?sessionStorage:void 0,this.namespace),this.user=h_(typeof localStorage<"u"?localStorage:void 0,this.namespace)):(this.session=g_(this.namespace),this.user=g_(this.namespace)),this.dismissals=Nk(this.session,this.user),this.cooldowns=Mk(this.user),this.frequency=Dk(this.session)}ns(e){let n=`${this.namespace}:${e}`;if(!this.namespacedStorages.has(n)){let i=typeof window<"u"&&typeof sessionStorage<"u"?h_(sessionStorage,n):g_(n);this.namespacedStorages.set(n,i)}return this.namespacedStorages.get(n)}};function Bp(t={}){return new Xc(t)}function $s(t){return t.startsWith("inline:")?"inline":t.startsWith("adjacent:")?"adjacent":"static"}function Qc(t){return t.startsWith("inline:")?t.slice(7):t.startsWith("adjacent:")?t.slice(9):null}var m_={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"}},Fs={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:[]},Lk={duration:200,easing:"cubic-bezier(0.16, 1, 0.3, 1)",fill:"forwards"};function $p(t,e,n){let i=m_[e];Object.assign(t.style,i),n&&(n.maxWidth&&(t.style.maxWidth=n.maxWidth),n.maxHeight&&(t.style.maxHeight=n.maxHeight),n.minWidth&&(t.style.minWidth=n.minWidth),n.minHeight&&(t.style.minHeight=n.minHeight))}function Fp(t,e,n){let i=n.placement==="auto"?"bottom":n.placement,r=[Vd(n.offset?{mainAxis:n.offset.y,crossAxis:n.offset.x}:8)];return n.flip!==!1&&r.push(qd()),n.shift!==!1&&r.push(jd({padding:8})),t.style.position="absolute",t.style.zIndex="2147483646",Ud(e,t,async()=>{let{x:o,y:s,strategy:l}=await Pd(e,t,{placement:i,middleware:r});Object.assign(t.style,{position:l,left:`${o}px`,top:`${s}px`})})}function Up(t,e,n="append"){return t.style.position="relative",t.style.display="inline-block",n==="prepend"?e.insertBefore(t,e.firstChild):e.appendChild(t),()=>{t.remove()}}function Vp(t,e){return e==="none"||Fs[e].length===0?null:t.animate(Fs[e],Lk)}function jp(t,e){if(e==="none"||Fs[e].length===0)return Promise.resolve();let n=[...Fs[e]].reverse(),i=t.animate(n,Lk);return new Promise(r=>{i.onfinish=()=>r(),i.oncancel=()=>r()})}function qp(t,e){let n=document.createElement("div");return n.setAttribute("data-syntro-surface",t),n.setAttribute("data-syntro-mount-id",e),n.className="syntro-surface",Object.assign(n.style,{pointerEvents:"auto",boxSizing:"border-box",overflow:"auto"}),n}function Pp(t){switch($s(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 Hk(t){if(typeof window.Sanitizer=="function")try{let l=new window.Sanitizer({}).sanitizeToFragment(t),c=document.createElement("div");return c.append(l),c.innerHTML}catch{}let n=document.createElement("template");n.innerHTML=t;let i=n.content,r=document.createTreeWalker(i,NodeFilter.SHOW_ELEMENT,null),a=new Set(["b","strong","i","em","u","span","div","p","br","ul","ol","li","code","pre","small","sup","sub","a","button"]),o=[];for(;r.nextNode();){let s=r.currentNode,l=s.tagName.toLowerCase();if(!a.has(l)){o.push(s);continue}for(let c of Array.from(s.attributes)){let u=c.name.toLowerCase(),f=c.value.trim().toLowerCase(),h=u.startsWith("on"),g=(u==="href"||u==="src")&&f.startsWith("javascript:");(h||g)&&s.removeAttribute(c.name)}}for(let s of o){for(;s.firstChild;)s.parentNode?.insertBefore(s.firstChild,s);s.remove()}return n.innerHTML=(i.firstChild,n.innerHTML)}var m5=0;function Gp(t){let{overlayRoot:e,eventBus:n,anchorResolver:i,defaultAnimation:r="fade",widgetRegistry:a}=t,o=new Map,s=new Map,l=new Map;function c(){return`mount-${++m5}`}function u(v,S){n&&n.publish(v,S)}function f(v){let S=l.get(v);if(S){let T=w(v);for(let A of S)try{A(T)}catch(k){console.error("[Surfaces] State callback error:",k)}}}let h=new Map;function g(v,S,T){switch(S.type){case"html":v.innerHTML=Hk(S.content);return;case"widget":{if(a?.has(S.widgetId)){let A=a.mount(S.widgetId,v,S.config);return T&&h.set(T,A),()=>{A.unmount(),T&&h.delete(T)}}console.warn(`[Surfaces] Widget not found: ${S.widgetId}`),v.innerHTML=`<div data-widget-id="${S.widgetId}" data-widget-missing="true">Widget: ${S.widgetId}</div>`;return}case"custom":return S.mount(v);case"react":v.innerHTML="<div data-react-component>React Component</div>";return;default:console.warn("[Surfaces] Unknown content type");return}}function _(v,S,T){let A=c(),k=$s(v),C=T?.priority??0,x=T?.animation??r,M=T?.exclusive??!0,z=o.get(v);if(z&&M){if(z.options.priority>C)throw new Error(`Slot ${v} is occupied by higher priority content (${z.options.priority} > ${C})`);b(z)}let U=qp(v,A);U.style.zIndex=String(Pp(v));let P;if(k==="static")$p(U,v,T?.constraints),e.appendChild(U);else if(k==="inline"){let D=Qc(v);if(!D)throw new Error(`Invalid inline slot: ${v}`);if(!i)throw new Error("Anchor resolver required for inline slots");let L=i(D);if(!L)throw new Error(`Anchor not found for inline slot: ${D}`);P=Up(U,L)}else if(k==="adjacent"){let D=Qc(v);if(!D)throw new Error(`Invalid adjacent slot: ${v}`);if(!i)throw new Error("Anchor resolver required for adjacent slots");let L=i(D);if(!L)throw new Error(`Anchor not found for adjacent slot: ${D}`);e.appendChild(U),P=Fp(U,L,T?.position??{placement:"bottom"})}let Z=g(U,S,A);Vp(U,x);let X={id:A,slot:v,content:S,options:{priority:C,exclusive:M,animation:x,position:T?.position??{placement:"auto"},constraints:T?.constraints??{},adaptiveId:T?.adaptiveId,autoUnmountOnRouteChange:T?.autoUnmountOnRouteChange??!0},container:U,cleanup:()=>{P?.(),Z?.()},mountedAt:Date.now()};return o.set(v,X),s.set(v,(s.get(v)??0)+1),u("surface.mounted",{slot:v,id:A,adaptiveId:T?.adaptiveId}),f(v),{id:A,update(D){let L=o.get(v);if(!L||L.id!==A)throw new Error("Mount no longer active");let de=h.get(A);if(de){if(D.type==="widget"){de.update(D.config),L.content=D;return}de.unmount(),h.delete(A)}L.container.innerHTML="";let fn=g(L.container,D,A);if(L.content=D,fn){let We=L.cleanup;L.cleanup=()=>{We?.(),fn()}}},setOptions(D){let L=o.get(v);if(!L||L.id!==A)throw new Error("Mount no longer active");D.priority!==void 0&&(L.options.priority=D.priority),D.animation!==void 0&&(L.options.animation=D.animation),D.constraints&&k==="static"&&(D.constraints.maxWidth&&(L.container.style.maxWidth=D.constraints.maxWidth),D.constraints.maxHeight&&(L.container.style.maxHeight=D.constraints.maxHeight),D.constraints.minWidth&&(L.container.style.minWidth=D.constraints.minWidth),D.constraints.minHeight&&(L.container.style.minHeight=D.constraints.minHeight)),f(v)},async unmount(){let D=o.get(v);!D||D.id!==A||await b(D)},isMounted(){return o.get(v)?.id===A},getContainer(){let D=o.get(v);return D?.id===A?D.container:null}}}async function b(v){await jp(v.container,v.options.animation),v.cleanup?.(),v.container.remove(),o.delete(v.slot),u("surface.unmounted",{slot:v.slot,id:v.id}),f(v.slot)}function w(v){let S=o.get(v);return{slot:v,occupied:!!S,currentPriority:S?.options.priority,currentAdaptiveId:S?.options.adaptiveId,mountCount:s.get(v)??0,currentMountId:S?.id}}function d(v,S){let T=l.get(v);return T||(T=new Set,l.set(v,T)),T.add(S),()=>{T?.delete(S),T?.size===0&&l.delete(v)}}function p(v,S){let T=o.get(v);return T?S!==void 0?S>=T.options.priority:!1:!0}function m(){for(let v of o.values())try{v.cleanup?.(),v.container.remove()}catch(S){console.error("[Surfaces] Error during cleanup:",S)}o.clear(),l.clear()}return{mount:_,getState:w,onStateChange:d,canMount:p,destroy:m}}var Jc=class{constructor(){V(this,"widgets",new Map);V(this,"mountedWidgets",new Map);V(this,"mountIdCounter",0);V(this,"runtimeRef");V(this,"listeners",new Set)}bindRuntime(e){this.runtimeRef=e}register(e,n,i="custom",r){if(this.widgets.has(e)){if(this.widgets.get(e).source==="built-in")throw new Error(`Cannot override built-in widget: ${e}`);console.warn(`[WidgetRegistry] Overriding widget: ${e}`)}this.widgets.set(e,{id:e,widget:n,source:i,metadata:r}),this.notify({type:"registered",widgetId:e})}unregister(e){let n=this.widgets.get(e);return n?n.source==="built-in"?(console.warn(`[WidgetRegistry] Cannot unregister built-in widget: ${e}`),!1):(this.widgets.delete(e),this.notify({type:"unregistered",widgetId:e}),!0):!1}unregisterBySource(e){for(let[n,i]of this.widgets.entries())i.source===e&&this.widgets.delete(n)}get(e){return this.widgets.get(e)?.widget}getRegistration(e){return this.widgets.get(e)}has(e){return this.widgets.has(e)}mount(e,n,i){let r=this.widgets.get(e);if(!r)throw new Error(`Widget not found: ${e}`);let a=`widget-mount-${++this.mountIdCounter}`;n.setAttribute("data-widget-mount-id",a),n.setAttribute("data-widget-id",e);let o={...i,runtime:this.runtimeRef},s=r.widget.mount(n,o);return this.mountedWidgets.set(a,{cleanup:s??void 0,container:n}),{widgetId:e,container:n,unmount:()=>{let c=this.mountedWidgets.get(a);c&&(c.cleanup?.(),this.mountedWidgets.delete(a),n.removeAttribute("data-widget-mount-id"),n.removeAttribute("data-widget-id"),n.innerHTML="")},update:c=>{if(r.widget.update)r.widget.update(n,c);else{let u=this.mountedWidgets.get(a);if(u){u.cleanup?.(),n.innerHTML="";let f={...c,runtime:this.runtimeRef},h=r.widget.mount(n,f);u.cleanup=h??void 0}}}}}list(){return Array.from(this.widgets.keys())}listRegistrations(){return Array.from(this.widgets.values())}getBySource(e){return Array.from(this.widgets.values()).filter(n=>n.source===e)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){for(let n of this.listeners)try{n(e)}catch(i){console.error("[WidgetRegistry] Listener error:",i)}}destroy(){for(let[e,n]of this.mountedWidgets.entries())n.cleanup?.(),n.container.innerHTML="";this.mountedWidgets.clear()}},Zp=new Jc;var v_="2.0.0";function v5(t,e){if(!e)return!0;let n;try{n=new URL(t).pathname}catch{n=t}let i=n.replace(/\/$/,"")||"/";if(e.exclude){for(let r of e.exclude)if(Ik(i,r))return!1}if(e.include&&e.include.length>0){for(let r of e.include)if(Ik(i,r))return!0;return!1}return!0}function Ik(t,e){let n=e.replace(/\/$/,"")||"/";if(t===n)return!0;let i=n.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/:[^/]+/g,"[^/]+");return new RegExp(`^${i}$`).test(t)}function y5(t){try{return document.querySelector(t)}catch{return null}}function Yp(t={}){let{telemetry:e,sessionMetrics:n,routes:i,mode:r="production",namespace:a}=t,o=t.widgets??Zp,s=t.executors??pi,l=t.apps??ts,c=new Bs,u=Lp({telemetry:e,routes:i,navigation:c}),f=t.events??zs(),h=Bp({namespace:a}),g=Ip({eventBus:f,stateStore:h}),_=Hp({state:h,events:f,sessionMetrics:n,accumulator:g}),b=UE(),w=v=>y5(v),d=Gp({overlayRoot:b,eventBus:f,anchorResolver:w,widgetRegistry:o}),p=Op({overlayRoot:b,eventBus:f,surfaces:d,anchorResolver:w,executorRegistry:s,subscribeNavigation:v=>c.subscribe(v)}),m={telemetry:e,context:u,events:f,state:h,sessionMetrics:n,actions:p,surfaces:d,widgets:o,executors:s,apps:l,accumulator:g,navigation:c,version:v_,mode:r,async evaluate(v){return _.evaluate(v,u.get())},evaluateSync(v){return _.evaluateSync(v,u.get())},async filterTiles(v){let S=u.get().page.url,T=[];for(let A of v){let k=A.activation;if(!k){T.push(A);continue}if(!v5(S,k.routes))continue;if(!k.strategy){T.push(A);continue}(await this.evaluate(k.strategy)).value&&T.push(A)}return T},setRoutes(v){u.setRoutes(v)},destroy(){l.unbind().catch(v=>{console.error("[Runtime] Error unbinding apps registry:",v)}),g.destroy(),c.destroy(),u.destroy(),p.destroy(),d.destroy()}};return l.bind(m),o.bindRuntime(m),m}var zk=y.object({value:y.unknown(),expiresAt:y.number().optional()}),Bk=y.object({count:y.number(),resetAt:y.number().optional()});function b5(t){return zk.safeParse(t)}function _5(t){return Bk.safeParse(t)}var $k={growthbook:t=>If({...t,autoInit:!0})};function Fk(t,e){let n=$k[t];if(!n)throw new Error(`Unknown experiment provider: ${t}. Supported: ${Object.keys($k).join(", ")}`);return n(e)}var S5=["cdn.syntrologie.com","localhost","127.0.0.1"];function x5(t){try{let e=new URL(t),n=/^(localhost|127\.0\.0\.1)$/.test(e.hostname);return e.protocol!=="https:"&&!n?(console.warn("[SmartCanvas] CDN URL must use HTTPS:",t),!1):S5.some(r=>e.hostname===r)?!0:(console.warn("[SmartCanvas] CDN host not in allowlist:",e.hostname),!1)}catch{return console.warn("[SmartCanvas] Invalid CDN URL:",t),!1}}var y_=class{constructor(e){V(this,"name","cdn");V(this,"url");V(this,"integrity");if(this.url=`${e.baseUrl}/${e.configId}.json`,this.integrity=e.integrity,!x5(this.url))throw new Error(`[SmartCanvas] CDN URL not allowed: ${this.url}`)}async fetch(){let e=performance.now(),n=await fetch(this.url,{credentials:"omit",cache:"default"});if(!n.ok)throw new Error(`[SmartCanvas] Failed to fetch config from CDN (${n.status})`);let i=await n.text();if(this.integrity){let l=await w5(i),c=this.integrity.replace("sha384-","");if(l!==c)throw new Error(`[SmartCanvas] Config integrity check failed. Expected ${c}, got ${l}`)}let r=JSON.parse(i),a=performance.now()-e,o=n.headers.get("cache-control"),s=n.headers.get("age");return{config:r,meta:{source:"cdn",fetchTimeMs:a,cached:o?.includes("public")??!1,cacheAge:s?parseInt(s,10):void 0}}}};async function w5(t){let n=new TextEncoder().encode(t),i=await crypto.subtle.digest("SHA-384",n),r=new Uint8Array(i);return btoa(String.fromCharCode(...r))}function Uk(t){return new y_(t)}var E5="syntro_exp",C5="syntro_var",b_=class{constructor(e){V(this,"name","experiments");V(this,"client");V(this,"featureKey");V(this,"manifestKey");V(this,"variantFlagPrefix");this.client=e.client,this.featureKey=e.featureKey??"smart-canvas-config",this.manifestKey=e.manifestKey,this.variantFlagPrefix=e.variantFlagPrefix}async fetch(){let e=performance.now();if(typeof window<"u"){let r=new URLSearchParams(window.location.search),a=r.get(E5),o=r.get(C5);if(a&&o!==null&&this.client.setForcedVariations){let s=parseInt(o,10);Number.isNaN(s)||(console.log(`[SmartCanvas] Preview mode: forcing "${a}" to variation ${s}`),this.client.setForcedVariations({[a]:s}))}}if(this.manifestKey||this.variantFlagPrefix){let r=this.fetchMultiFlag();if(r){let a=performance.now()-e;return{config:r,meta:{source:"experiments",fetchTimeMs:a,cached:!0}}}}let n=this.client.getFeatureValue?.(this.featureKey,null);if(!n||typeof n!="object")throw new Error(`[SmartCanvas] Feature "${this.featureKey}" not found or invalid. Ensure the feature is configured in your experiment platform.`);let i=performance.now()-e;return{config:n,meta:{source:"experiments",fetchTimeMs:i,cached:!0}}}fetchMultiFlag(){let e=this.getVariantFlagKeys();return!e||e.length===0?null:ef(this.client,e)}getVariantFlagKeys(){if(this.manifestKey){let e=this.client.getFeatureValue?.(this.manifestKey,null);if(e&&typeof e=="object"){let n=e.variant_flags;if(n&&n.length>0)return n}}if(this.variantFlagPrefix&&this.client.getAllFeatures){let e=this.client.getAllFeatures();return Object.keys(e).filter(n=>n.startsWith(this.variantFlagPrefix))}return[]}};function Vk(t){return new b_(t)}var A5="https://cdn.syntrologie.com/configs",jk={cdn:t=>{if(!t.configId)throw new Error("CDN fetcher requires 'configId' option");return Uk({baseUrl:t.baseUrl??A5,configId:t.configId,integrity:t.integrity})},experiments:t=>{if(!t.featureKey)throw new Error("Experiments fetcher requires 'featureKey' option");return Vk({featureKey:t.featureKey})}};function qk(t,e={}){let n=jk[t];if(!n)throw new Error(`Unknown config fetcher type: ${t}. Supported: ${Object.keys(jk).join(", ")}`);return n(e)}var Pk={posthog:t=>Ap(t),noop:()=>Pf()};function Gk(t,e){let n=Pk[t];if(!n)throw new Error(`Unknown telemetry provider: ${t}. Supported: ${Object.keys(Pk).join(", ")}`);return n(e)}var __="syn_";function eu(t){if(!t.startsWith(__))throw new Error("Invalid Syntro token: must start with 'syn_'");let n=t.slice(__.length).replace(/-/g,"+").replace(/_/g,"/"),i=atob(n),r=JSON.parse(i);if(r.v!==1)throw new Error(`Unsupported token version: ${r.v}`);return r}function Wp(t){let e=JSON.stringify(t),n=btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");return __+n}function er(t){if(typeof process<"u"&&process.env)return process.env[t];try{let e=(0,eval)("import.meta");if(e?.env)return e.env[t]}catch{}}function T5(){if(typeof window>"u")return G("Syntro Bootstrap","isEditorMode: not in browser"),!1;let t=Ma(),n=!!(Lr()?.token&&t?.mode==="editor");return G("Syntro Bootstrap","isEditorMode:",n),n}function k5(){if(typeof window>"u")return G("Syntro Bootstrap","isAuditMode: not in browser"),!1;let t=Ma(),n=!!(Lr()?.token&&t?.mode==="audit");return G("Syntro Bootstrap","isAuditMode:",n),n}function R5(){if(typeof window>"u")return G("Syntro Bootstrap","isReviewMode: not in browser"),!1;let t=Ma(),n=!!(Lr()?.token&&t?.mode==="review");return G("Syntro Bootstrap","isReviewMode:",n),n}var Zk="syntro_segment_attributes";function O5(){if(typeof window>"u")return{};try{let t=localStorage.getItem(Zk);if(t){let e=JSON.parse(t);return G("Syntro Bootstrap","Loaded cached segment attributes:",e),e}}catch(t){cn("Syntro Bootstrap","Failed to load cached segment attributes:",t)}return{}}function M5(t){if(!(typeof window>"u"))try{localStorage.setItem(Zk,JSON.stringify(t)),G("Syntro Bootstrap","Cached segment attributes:",t)}catch(e){cn("Syntro Bootstrap","Failed to cache segment attributes:",e)}}function N5(t){if(!t)return{};let e={};for(let[n,i]of Object.entries(t))n.startsWith("in_segment_")&&(e[n]=i===!0);return e}async function D5(t){Jm(),G("Syntro Bootstrap","====== INIT ======"),G("Syntro Bootstrap","Options:",{hasToken:!!t.token,tokenPrefix:`${t.token?.slice(0,15)}...`,hasCanvasOptions:!!t.canvas});let e=T5(),n=k5(),i=R5(),r=e?"editor":n?"audit":i?"review":null;if(console.log(`[DIAG] Mode detection: editor=${e}, audit=${n}, review=${i}, sdkMode=${r}`),console.log("[DIAG] editorSource:",Lr()),console.log("[DIAG] editorConf:",Ma()),G("Syntro Bootstrap","SDK mode:",r??"normal"),!r&&typeof window<"u"){let x=!!window.__SYNTRO_EDITOR_PARAMS__,M=!!window.__SYNTRO_AUDIT_LEGEND__,z=!!window.__SYNTRO_REVIEW_DATA__;if(x||M||z){let U=[x&&"__SYNTRO_EDITOR_PARAMS__",M&&"__SYNTRO_AUDIT_LEGEND__",z&&"__SYNTRO_REVIEW_DATA__"].filter(Boolean);console.warn(`[Syntro Bootstrap] \u26A0 Mode detection returned null but mode-specific globals found: ${U.join(", ")}. This suggests URL params were lost (redirect?) but the service worker injected mode data. Check if replaceState failed or if page JS changed the URL before init().`)}}console.log(`[DIAG] Token resolution: options.token=${t.token?t.token.slice(0,15)+"...":"null"}`);let a=t.token;if(!a&&r){let M=Ma()?.syntro_token;M?.startsWith("syn_")&&(a=M,G("Syntro Bootstrap",`\u2713 Using syntro_token from editor_conf (${r} mode)`))}let o;if(a)if(a.startsWith("syn_"))G("Syntro Bootstrap","Token starts with syn_, decoding..."),o=eu(a),Jm(o.d);else if(r)G("Syntro Bootstrap",`\u2713 Non-syn_ token allowed (${r} mode)`);else throw tf("Syntro Bootstrap","\u274C Token does not start with syn_ and NOT in editor/audit/review mode!"),tf("Syntro Bootstrap","Token received:",a),new Error("Invalid Syntro token: must start with 'syn_'");else if(r)G("Syntro Bootstrap",`\u2713 No token, but ${r} mode - proceeding`);else throw tf("Syntro Bootstrap","\u274C No token provided and NOT in editor/audit/review mode!"),new Error("Syntro token is required (unless in editor, audit, or review mode)");let s=er("NEXT_PUBLIC_SYNTRO_EXPERIMENT_HOST")||er("VITE_SYNTRO_EXPERIMENT_HOST")||o?.eh,l=er("NEXT_PUBLIC_SYNTRO_TELEMETRY_HOST")||er("VITE_SYNTRO_TELEMETRY_HOST")||o?.th,c=er("NEXT_PUBLIC_SYNTRO_EDITOR_URL")||er("VITE_SYNTRO_EDITOR_URL")||t.canvas?.editorUrl,u=O5();G("Syntro Bootstrap","Phase 1: Using cached segment attributes:",u);let f,h=zs();console.log("[Syntro Bootstrap] EventBus created");let g=zp(x=>{h.publishEvent(x)}),_=x=>{G("Syntro Bootstrap","Phase 2: PostHog feature flags loaded");let M=N5(x);if(G("Syntro Bootstrap","Segment flags from PostHog:",M),M5(M),f){let U={...w?.getAll?.()??{},...M};G("Syntro Bootstrap","Updating GrowthBook with attributes:",U),f.setAttributes?.(U)}},b;if(o?.t){let x=o.t==="noop"?"noop":"posthog";b=Gk(x,{apiKey:o.t,apiHost:l,enableFeatureFlags:!0,onFeatureFlagsLoaded:_,onCapture:g}),console.log(`[Syntro Bootstrap] Telemetry client created (${x}) with EventBus wiring`)}let w;o?.e&&(f=Fk("growthbook",{clientKey:o.e,apiHost:s,attributes:u,onExperimentViewed:b?.trackExperiment?(x,M,z)=>{b.trackExperiment(x,M,z)}:void 0})),t.enableSessionMetrics&&(w=zf({experiments:f,onMetricChange:(x,M)=>{G("Syntro Bootstrap",`Session metric changed: ${x} = ${M}`)}}),G("Syntro Bootstrap","SessionMetricTracker created"));let d="production";e?d="editor":n?d="audit":er("NODE_ENV")==="development"&&(d="development");let p=Yp({telemetry:b,sessionMetrics:w,mode:d,events:h});G("Syntro Bootstrap","Runtime created:",{version:p.version,mode:p.mode,hasContext:!!p.context,hasEvents:!!p.events,hasState:!!p.state}),G("Syntro Bootstrap","Core app executors already registered");let m=t.cdnBase||er("NEXT_PUBLIC_SYNTRO_CDN_BASE")||er("VITE_SYNTRO_CDN_BASE")||"https://cdn.syntrologie.com",v=Kd({cdnBase:m,registry:p.apps,onLoadStart:x=>{G("Syntro Bootstrap",`Loading app from CDN: ${x}`)},onLoadEnd:(x,M,z)=>{M?G("Syntro Bootstrap",`App loaded successfully: ${x}`):cn("Syntro Bootstrap",`Failed to load app: ${x}`,z)}});typeof window<"u"&&(window.SynOS={...window.SynOS,appRegistry:p.apps,runtime:p,version:p.version},G("Syntro Bootstrap","Global SynOS object exposed"));let S=p.apps.list?.()??[];console.log(`[DIAG] Activation loop: ${S.length} apps in registry:`,S.map(x=>`${x.manifest.id}(${x.state})`).join(", "));for(let x of S)if(x.state==="registered")try{await p.apps.activate(x.manifest.id),console.log(`[DIAG] Activated: ${x.manifest.id} \u2192 widgets: [${p.widgets.list().join(", ")}]`)}catch(M){console.error(`[DIAG] FAILED to activate: ${x.manifest.id}`,M),cn("Syntro Bootstrap",`Failed to auto-activate built-in app: ${x.manifest.id}`,M)}if(console.log(`[DIAG] Activation complete. Total widgets: [${p.widgets.list().join(", ")}]`),f?.refreshFeatures)try{await f.refreshFeatures(),G("Syntro Bootstrap","GrowthBook features loaded")}catch(x){cn("Syntro Bootstrap","Failed to load GrowthBook features:",x)}let T;if(t.fetcher)T=t.fetcher;else if(o?.f){let x=qk(o.f,o.o??{});T=async()=>{let M=await x.fetch();return{...M.config,tiles:M.config.tiles??[]}}}else f&&(T=Oa({experiments:f}));let A=new Set,k=T?async()=>{let x=await T();console.log("[Syntro Bootstrap] Config fetched:",`tiles=${x.tiles?.length??0},`,`actions=${x.actions?.length??0},`,`theme=${x.theme?.name??"none"}`),x.actions?.length>0&&console.log("[Syntro Bootstrap] Actions in config:",x.actions.map((U,P)=>`[${P}] ${U.kind}${U.anchorId?` anchor="${U.anchorId}"`:""}${U.label?` "${U.label}"`:""}`).join(", "));let M=x,z=v.getRequiredApps(M);return z.length>0?console.log("[Syntro Bootstrap] Required external apps:",z.join(", ")):G("Syntro Bootstrap","No external apps required (all executors are built-in)"),z.length>0&&await v.loadAppsForConfig(M).then(async P=>{let Z=P.filter(D=>D.success),X=P.filter(D=>!D.success);Z.length>0&&console.log(`[Syntro Bootstrap] Apps loaded from CDN: ${Z.map(D=>D.appId).join(", ")}`);let W=X.filter(D=>!A.has(D.appId));W.length>0&&(console.error("[Syntro Bootstrap] Apps FAILED to load from CDN:",W.map(D=>`${D.appId} (${D.error})`).join(", ")),W.forEach(D=>A.add(D.appId)));for(let D of z)if(p.apps.has(D))try{await p.apps.activate(D),console.log(`[Syntro Bootstrap] App activated: ${D}`)}catch(L){console.error(`[Syntro Bootstrap] Failed to activate app: ${D}`,L)}else console.error(`[Syntro Bootstrap] App "${D}" required by config but NOT registered.`,`Available apps: [${Array.from(p.apps.list?.()??[]).join(", ")}]`)}),x}:void 0;return{canvas:await yf({...t.canvas,fetcher:k,integrations:{experiments:f,telemetry:b},editorUrl:c,runtime:p}),runtime:p,experiments:f,telemetry:b,sessionMetrics:w,appLoader:v}}var S_={init:D5,encodeToken:Wp,decodeToken:eu};typeof window<"u"&&(window.Syntro=S_);var x_="2026-02-26T20:06:39.444Z (ba85f6525)";if(typeof window<"u"){console.log(`[Syntro Runtime] Build: ${x_}`);let t=window.SynOS,e=t?.appRegistry||ts;window.SynOS={...t,appRegistry:e,_runtimeBuild:x_,React:Yk.default,ReactDOM:{...L5,createPortal:Kp.createPortal,flushSync:Kp.flushSync}},RE(e)}return aR(H5);})();
|
|
449
|
+
`)),new Error(`Batch validation failed: ${k}`)}let v=c(),S=[],T=[];try{for(let k of p){let C=await g(k);S.push(C),T.push(C)}}catch(k){console.error(`[ActionEngine] Batch apply FAILED at action ${T.length+1}/${p.length}.`,`Successfully applied: ${T.length}. Rolling back...`,k);for(let C of T)try{await C.revert()}catch{}throw k}return{id:v,handles:S,async revertAll(){for(let k=S.length-1;k>=0;k--)try{await S[k].revert()}catch(C){console.error(`[ActionEngine] Error reverting action ${S[k].id}:`,C)}},isApplied(){return S.every(k=>k.isApplied())}}}function b(p){return Ji(p)}function w(){return Array.from(l.values()).map(p=>({id:p.id,action:p.action,adaptiveId:p.adaptiveId,appliedTs:p.appliedTs,state:p.state}))}function d(){for(let p of l.values())if(p.state==="applied")try{p.cleanup()}catch(m){console.error("[ActionEngine] Error during cleanup:",m)}l.clear()}return{apply:g,applyBatch:_,validate:b,getActive:w,destroy:d}}var ok=y.object({type:y.literal("page_url"),url:y.string()}),sk=y.object({type:y.literal("route"),routeId:y.string()}),lk=y.object({type:y.literal("anchor_visible"),anchorId:y.string(),state:y.enum(["visible","present","absent"])}),ck=y.object({type:y.literal("event_occurred"),eventName:y.string(),withinMs:y.number().optional()}),uk=y.object({type:y.literal("state_equals"),key:y.string(),value:y.unknown()}),dk=y.object({type:y.literal("viewport"),minWidth:y.number().optional(),maxWidth:y.number().optional(),minHeight:y.number().optional(),maxHeight:y.number().optional()}),fk=y.object({type:y.literal("session_metric"),key:y.string(),operator:y.enum(["gte","lte","eq","gt","lt"]),threshold:y.number()}),pk=y.object({type:y.literal("dismissed"),key:y.string(),inverted:y.boolean().optional()}),hk=y.object({type:y.literal("cooldown_active"),key:y.string(),inverted:y.boolean().optional()}),gk=y.object({type:y.literal("frequency_limit"),key:y.string(),limit:y.number(),inverted:y.boolean().optional()}),mk=y.object({type:y.literal("event_count"),key:y.string(),operator:y.enum(["gte","lte","eq","gt","lt"]),count:y.number().int().min(0),withinMs:y.number().positive().optional()}),Mp=y.discriminatedUnion("type",[ok,sk,lk,ck,uk,dk,fk,pk,hk,gk,mk]),xb=y.object({conditions:y.array(Mp),value:y.unknown()}),wb=y.object({type:y.literal("rules"),rules:y.array(xb),default:y.unknown()}),Eb=y.object({type:y.literal("score"),field:y.string(),threshold:y.number(),above:y.unknown(),below:y.unknown()}),Cb=y.object({type:y.literal("model"),modelId:y.string(),inputs:y.array(y.string()),outputMapping:y.record(y.string(),y.unknown()),default:y.unknown()}),Ab=y.object({type:y.literal("external"),endpoint:y.string(),method:y.enum(["GET","POST"]).optional(),default:y.unknown(),timeoutMs:y.number().optional()}),Tb=y.discriminatedUnion("type",[wb,Eb,Cb,Ab]),kb=y.object({include:y.array(y.string()).optional(),exclude:y.array(y.string()).optional()}),Pc=y.object({routes:kb,strategy:Tb.optional()});function a5(t){return Mp.safeParse(t)}function o5(t){return Tb.safeParse(t)}function s5(t){return Pc.safeParse(t)}var l5=[{defName:"activationConfig",schema:Pc},{defName:"routeFilter",schema:kb},{defName:"ruleStrategy",schema:wb},{defName:"scoreStrategy",schema:Eb},{defName:"modelStrategy",schema:Cb},{defName:"externalStrategy",schema:Ab},{defName:"rule",schema:xb},{defName:"condition",schema:Mp}];var pt={activation:Pc.optional()},Rb=y.object({color:y.string().optional(),scrimOpacity:y.number().min(0).max(1).optional(),paddingPx:y.number().optional(),radiusPx:y.number().optional()}).strict(),Ob=y.enum(["top-left","top-right","bottom-left","bottom-right"]),Mb=y.enum(["top","top-start","top-end","bottom","bottom-start","bottom-end","left","left-start","left-end","right","right-start","right-end"]),Dp=y.object({label:y.string(),actionId:y.string(),primary:y.boolean().optional()}).strict(),Nb=y.object({title:y.string().optional(),body:y.string(),ctaButtons:y.array(Dp).optional()}).strict(),Db=y.object({title:y.string().optional(),body:y.string()}).strict(),Lb=y.enum(["before","after","prepend","append","replace"]),Hb=y.enum(["immediate","hover","click"]),Ib=y.object({widgetId:y.string(),props:y.record(y.unknown()).optional(),priority:y.number().optional()}).strict(),zb=y.object({id:y.string(),action:y.any(),route:y.string().optional(),onAction:y.record(y.string()).optional()}).strict(),Bb=y.enum(["auto","smooth","instant"]),Np=y.enum(["start","center","end","nearest"]),$b=y.object({kind:y.literal("content:setText"),anchorId:y.string(),text:y.string(),label:y.string().optional()}).extend(pt).strict(),Fb=y.object({kind:y.literal("content:setAttr"),anchorId:y.string(),attr:y.string(),value:y.string(),label:y.string().optional()}).extend(pt).strict(),Ub=y.object({kind:y.literal("content:addClass"),anchorId:y.string(),className:y.string(),label:y.string().optional()}).extend(pt).strict(),Vb=y.object({kind:y.literal("content:removeClass"),anchorId:y.string(),className:y.string(),label:y.string().optional()}).extend(pt).strict(),jb=y.object({kind:y.literal("content:setStyle"),anchorId:y.string(),styles:y.record(y.string()),label:y.string().optional()}).extend(pt).strict(),qb=y.object({kind:y.literal("content:insertHtml"),anchorId:y.string(),html:y.string(),position:Lb,label:y.string().optional()}).extend(pt).strict(),Pb=y.object({kind:y.literal("overlays:highlight"),anchorId:y.string(),style:Rb.optional(),duration:y.number().optional(),label:y.string().optional()}).extend(pt).strict(),Gb=y.object({kind:y.literal("overlays:pulse"),anchorId:y.string(),duration:y.number().optional(),label:y.string().optional()}).extend(pt).strict(),Zb=y.object({kind:y.literal("overlays:badge"),anchorId:y.string(),content:y.string(),position:Ob.optional(),label:y.string().optional()}).extend(pt).strict(),Yb=y.object({kind:y.literal("overlays:tooltip"),anchorId:y.string(),content:Nb,trigger:Hb.optional(),placement:Mb.optional(),waitFor:y.string().optional(),label:y.string().optional()}).extend(pt).strict(),Wb=y.object({kind:y.literal("overlays:modal"),content:Db,size:y.enum(["sm","md","lg"]).optional(),blocking:y.boolean().optional(),scrim:y.object({opacity:y.number().min(0).max(1).optional()}).strict().optional(),dismiss:y.object({onEsc:y.boolean().optional(),closeButton:y.boolean().optional(),timeoutMs:y.number().min(0).optional()}).strict().optional(),ctaButtons:y.array(Dp).optional(),waitFor:y.string().optional(),label:y.string().optional()}).extend(pt).strict(),Kb=y.object({kind:y.literal("navigation:scrollTo"),anchorId:y.string(),behavior:Bb.optional(),block:Np.optional(),inline:Np.optional(),label:y.string().optional()}).extend(pt).strict(),Xb=y.object({kind:y.literal("navigation:navigate"),url:y.string(),target:y.enum(["_self","_blank"]).optional(),label:y.string().optional()}).extend(pt).strict(),Qb=y.object({kind:y.literal("core:mountWidget"),slot:y.string(),widget:Ib,label:y.string().optional()}).extend(pt).strict(),Jb=y.object({kind:y.literal("core:wait"),durationMs:y.number().min(0).optional(),event:y.string().optional(),label:y.string().optional()}).extend(pt).strict(),e_=y.object({kind:y.literal("core:sequence"),actions:y.array(y.any()),label:y.string().optional()}).extend(pt).strict(),t_=y.object({kind:y.literal("core:parallel"),actions:y.array(y.any()),waitFor:y.enum(["all","any"]).optional(),label:y.string().optional()}).extend(pt).strict(),n_=y.object({kind:y.literal("core:tour"),tourId:y.string(),steps:y.array(zb).min(1),startStep:y.string().optional(),autoStart:y.boolean().optional(),label:y.string().optional()}).extend(pt).strict(),vk=[{defName:"setText",schema:$b},{defName:"setAttr",schema:Fb},{defName:"addClass",schema:Ub},{defName:"removeClass",schema:Vb},{defName:"setStyle",schema:jb},{defName:"insertHtml",schema:qb},{defName:"highlight",schema:Pb},{defName:"pulse",schema:Gb},{defName:"badge",schema:Zb},{defName:"tooltip",schema:Yb},{defName:"modal",schema:Wb},{defName:"scrollTo",schema:Kb},{defName:"navigate",schema:Xb},{defName:"mountWidget",schema:Qb},{defName:"wait",schema:Jb},{defName:"sequence",schema:e_},{defName:"parallel",schema:t_},{defName:"tour",schema:n_}];function c5(){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 i_(t,e){if(!e)return;let n;try{n=new URL(t).pathname}catch{n=t}if(e.exclude){for(let i of e.exclude)if(yk(n,i))return}if(e.include){for(let i of e.include)if(yk(n,i))return i;return}return n}function yk(t,e){let n=t.replace(/\/$/,"")||"/",i=e.replace(/\/$/,"")||"/";if(n===i)return!0;let r=i.replace(/:[^/]+/g,"[^/]+").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(n)}var Gc=class{constructor(e={}){V(this,"context");V(this,"previousContext");V(this,"listeners",new Set);V(this,"telemetry");V(this,"routes");V(this,"navigation");V(this,"cleanupFns",[]);if(this.telemetry=e.telemetry,this.routes=e.routes,this.navigation=e.navigation,this.context=c5(),this.previousContext={...this.context},e.telemetry?.getSessionId){let n=e.telemetry.getSessionId();n&&(this.context.session.sessionId=n)}e.initialPageHistory&&(this.context.session.pageHistory=e.initialPageHistory),this.context.page.routeId=i_(this.context.page.url,this.routes),this.addPageToHistory(this.context.page.url),typeof window<"u"&&this.setupBrowserListeners()}get(){return{...this.context}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}setRoutes(e){this.routes=e;let n=i_(this.context.page.url,this.routes);n!==this.context.page.routeId&&this.updateContext({page:{...this.context.page,routeId:n}})}setAnchors(e){this.updateContext({anchors:e})}setSessionId(e){e!==this.context.session.sessionId&&this.updateContext({session:{...this.context.session,sessionId:e}})}destroy(){for(let e of this.cleanupFns)e();this.cleanupFns=[],this.listeners.clear()}setupBrowserListeners(){let e,n=()=>{clearTimeout(e),e=setTimeout(()=>{this.updateViewport()},100)};if(window.addEventListener("resize",n),this.cleanupFns.push(()=>window.removeEventListener("resize",n)),this.navigation){let i=this.navigation.subscribe(()=>this.updatePage());this.cleanupFns.push(i)}else{let i=()=>{this.updatePage()};window.addEventListener("popstate",i),this.cleanupFns.push(()=>window.removeEventListener("popstate",i));let r=history.pushState.bind(history),a=history.replaceState.bind(history);history.pushState=(...o)=>{r(...o),queueMicrotask(()=>this.updatePage())},history.replaceState=(...o)=>{a(...o),queueMicrotask(()=>this.updatePage())},this.cleanupFns.push(()=>{history.pushState=r,history.replaceState=a})}}updateViewport(){let e={width:window.innerWidth,height:window.innerHeight};(e.width!==this.context.viewport.width||e.height!==this.context.viewport.height)&&this.updateContext({viewport:e})}updatePage(){let e=window.location.href,{title:n}=document,i=i_(e,this.routes),r={url:e,title:n,routeId:i};(r.url!==this.context.page.url||r.title!==this.context.page.title||r.routeId!==this.context.page.routeId)&&(r.url!==this.context.page.url&&this.addPageToHistory(r.url),this.updateContext({page:r}))}addPageToHistory(e){let n={url:e,ts:Date.now()},i=[...this.context.session.pageHistory||[],n];i.length>50&&i.shift(),this.context.session.pageHistory=i}updateContext(e){this.previousContext={...this.context},this.context={...this.context,...e},this.notifyListeners()}notifyListeners(){for(let e of this.listeners)try{e(this.context,this.previousContext)}catch(n){console.error("[ContextManager] Listener error:",n)}}};function Lp(t={}){return new Gc(t)}var bk=y.object({url:y.string(),routeId:y.string().optional(),title:y.string().optional(),locale:y.string().optional()}),_k=y.object({url:y.string(),ts:y.number()}),Sk=y.object({sessionId:y.string(),startTs:y.number(),pageHistory:y.array(_k).optional()}),xk=y.object({width:y.number(),height:y.number()}),wk=y.object({x:y.number(),y:y.number(),w:y.number(),h:y.number()}),Ek=y.object({anchorId:y.string(),present:y.boolean(),visible:y.boolean().optional(),boundingBox:wk.optional()}),Ck=y.record(y.string(),y.union([y.number(),y.string(),y.boolean(),y.undefined()])),Ak=y.object({page:bk,session:Sk,viewport:xk,anchors:y.array(Ek).optional(),augmented:Ck.optional()});function u5(t){return Ak.safeParse(t)}function r_(t,e){let{context:n,state:i,events:r}=e;switch(t.type){case"page_url":{let{url:a}=t,o=n.page.url,s=a.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*");return new RegExp(`^${s}$`).test(o)}case"route":return n.page.routeId===t.routeId;case"anchor_visible":{let a=n.anchors?.find(o=>o.anchorId===t.anchorId);switch(t.state){case"visible":return a?.visible===!0;case"present":return a?.present===!0;case"absent":return!a?.present;default:return!1}}case"event_occurred":{if(!r)return!1;let a=t.withinMs??6e4;return r.hasRecentEvent(t.eventName,a)}case"state_equals":return!1;case"viewport":{let{width:a,height:o}=n.viewport;return!(t.minWidth!==void 0&&a<t.minWidth||t.maxWidth!==void 0&&a>t.maxWidth||t.minHeight!==void 0&&o<t.minHeight||t.maxHeight!==void 0&&o>t.maxHeight)}case"session_metric":{if(!i)return!1;let a=i.getSessionMetric(t.key),{operator:o,threshold:s}=t;switch(o){case"gte":return a>=s;case"lte":return a<=s;case"eq":return a===s;case"gt":return a>s;case"lt":return a<s;default:return!1}}case"dismissed":{if(!i)return t.inverted??!1;let a=i.isDismissed(t.key);return t.inverted?!a:a}case"cooldown_active":{if(!i)return t.inverted??!1;let a=i.isCooldownActive(t.key);return t.inverted?!a:a}case"frequency_limit":{if(!i)return t.inverted??!1;let o=i.getFrequencyCount(t.key)>=t.limit;return t.inverted?!o:o}case"event_count":{if(!e.accumulator)return!1;let a=t,o=e.accumulator.getCount(a.key,a.withinMs);switch(a.operator){case"gte":return o>=a.count;case"lte":return o<=a.count;case"eq":return o===a.count;case"gt":return o>a.count;case"lt":return o<a.count;default:return!1}}default:return console.warn("[RuleStrategy] Unknown condition type:",t.type),!1}}function a_(t,e){let n=[];for(let i of t.conditions){let r=r_(i,e);if(n.push({condition:i,result:r}),!r)return{matched:!1,conditionResults:n}}return{matched:!0,conditionResults:n}}function Zc(t,e){for(let n=0;n<t.rules.length;n++){let i=t.rules[n],{matched:r,conditionResults:a}=a_(i,e);if(r)return{value:i.value,isFallback:!1,matchInfo:{strategyType:"rules",matchedRuleIndex:n,evaluatedConditions:a}}}return{value:t.default,isFallback:!0,matchInfo:{strategyType:"rules"}}}function Yc(t,e){let{context:n}=e,i=n.augmented?.[t.field];return i===void 0||typeof i!="number"?{value:t.below,isFallback:!0,matchInfo:{strategyType:"score"}}:{value:i>=t.threshold?t.above:t.below,isFallback:!1,matchInfo:{strategyType:"score"}}}function Tk(t,e){let{state:n,events:i,sessionMetrics:r,accumulator:a}=e;return{context:t,state:n?{isDismissed:o=>n.dismissals.isDismissed(o),isCooldownActive:o=>n.cooldowns.isActive(o),getFrequencyCount:o=>n.frequency.count(o),getSessionMetric:o=>r?.get(o)??0}:void 0,events:i?{hasRecentEvent:(o,s)=>i.hasRecentEvent(o,s)}:void 0,accumulator:a?{getCount:(o,s)=>a.getCount(o,s)}:void 0}}async function o_(t,e,n={}){let i=Tk(e,n);switch(t.type){case"rules":return Zc(t,i);case"score":return Yc(t,i);case"model":return{value:t.default,isFallback:!0,matchInfo:{strategyType:"model"}};case"external":return{value:t.default,isFallback:!0,matchInfo:{strategyType:"external"}};default:return console.warn("[DecisionEngine] Unknown strategy type:",t.type),{value:void 0,isFallback:!0,matchInfo:{strategyType:t.type}}}}function s_(t,e,n={}){let i=Tk(e,n);switch(t.type){case"rules":return Zc(t,i);case"score":return Yc(t,i);case"model":case"external":return{value:t.default,isFallback:!0,matchInfo:{strategyType:t.type}};default:return{value:void 0,isFallback:!0,matchInfo:{strategyType:t.type}}}}function Hp(t){return{evaluate:(e,n)=>o_(e,n,t),evaluateSync:(e,n)=>s_(e,n,t)}}function Ip(t){let{eventBus:e,stateStore:n}=t,i=new Map,r=new Set,a=null,o=n.ns("accumulator");function s(c){let u=!1;for(let f of i.values()){if(!f.predicate(c))continue;let h=o.get(f.stateKey)||{count:0};h.count++,f.needsTimestamps&&(h.timestamps||(h.timestamps=[]),h.timestamps.push(c.ts),h.timestamps.length>200&&(h.timestamps=h.timestamps.slice(-200))),o.set(f.stateKey,h),u=!0}if(u)for(let f of r)try{f()}catch(h){console.error("[EventAccumulator] Subscriber error:",h)}}function l(){a||i.size===0||(a=e.subscribe(s))}return{register(c,u,f=!1){let h=`ev:${c}`,g=i.get(h);if(g){f&&!g.needsTimestamps&&(g.needsTimestamps=!0);return}i.set(h,{stateKey:h,needsTimestamps:f,predicate:u}),l()},getCount(c,u){let f=`ev:${c}`,h=o.get(f);if(!h)return 0;if(u===void 0||!h.timestamps)return h.count;let g=Date.now()-u;return h.timestamps.filter(_=>_>=g).length},subscribe(c){return r.add(c),()=>{r.delete(c)}},destroy(){a&&(a(),a=null),i.clear(),r.clear()}}}function l_(t,e){return e?!(e.names&&e.names.length>0&&!e.names.includes(t.name)||e.patterns&&e.patterns.length>0&&!e.patterns.some(i=>{try{return new RegExp(i).test(t.name)}catch{return!1}})||e.sources&&e.sources.length>0&&!e.sources.includes(t.source)):!0}var Wc=class{constructor(e={}){V(this,"subscriptions",new Set);V(this,"history",[]);V(this,"maxHistorySize");this.maxHistorySize=e.maxHistorySize??100}subscribe(e,n){let i,r;typeof e=="function"?(i=void 0,r=e):(i=e,r=n);let a={filter:i,callback:r};return this.subscriptions.add(a),()=>{this.subscriptions.delete(a)}}publish(e,n,i="canvas"){let r={ts:Date.now(),name:e,source:i,props:n,schemaVersion:Na};this.publishEvent(r)}publishEvent(e){this.history.push(e),this.history.length>this.maxHistorySize&&this.history.shift();for(let n of this.subscriptions)if(l_(e,n.filter))try{n.callback(e)}catch(i){console.error("[EventBus] Subscriber error:",i)}}getRecent(e,n){let i=this.history;return e&&(i=i.filter(r=>l_(r,e))),n&&n>0&&(i=i.slice(-n)),i}hasRecentEvent(e,n,i){let r=Date.now()-n;return this.history.some(a=>a.name===e&&a.ts>=r&&(i===void 0||a.source===i))}countRecentEvents(e,n){let i=this.history.filter(r=>l_(r,e));if(n!==void 0){let r=Date.now()-n;i=i.filter(a=>a.ts>=r)}return i.length}clearHistory(){this.history=[]}getSubscriberCount(){return this.subscriptions.size}};function zs(t={}){return new Wc(t)}var kk={$autocapture:"ui.click",$click:ye.UI_CLICK,$scroll:ye.UI_SCROLL,$input:ye.UI_INPUT,$change:ye.UI_CHANGE,$submit:ye.UI_SUBMIT,$pageview:ye.NAV_PAGE_VIEW,$pageleave:ye.NAV_PAGE_LEAVE,$session_start:"session.start",$identify:"user.identify"};function d5(t){let e=t.event;if(typeof e!="string")return"posthog.unknown";if(kk[e])return kk[e];if(e==="$autocapture"){let n=t.properties?.$tag_name,i=t.properties?.$event_type;return i==="submit"?ye.UI_SUBMIT:i==="change"?ye.UI_CHANGE:n==="input"||n==="textarea"?ye.UI_INPUT:ye.UI_CLICK}return e.startsWith("$")?e.replace("$","posthog."):`posthog.${e}`}function f5(t){let e={},n=t.properties||{},i=n.$elements;return n.$tag_name?e.tagName=n.$tag_name:i?.[0]?.tag_name&&(e.tagName=i[0].tag_name),n.$el_text&&(e.elementText=n.$el_text),i&&(e.elements=i),n.$current_url&&(e.url=n.$current_url),n.$pathname&&(e.pathname=n.$pathname),n.$host&&(e.host=n.$host),n.$viewport_width&&(e.viewportWidth=n.$viewport_width),n.$viewport_height&&(e.viewportHeight=n.$viewport_height),n.$session_id&&(e.sessionId=n.$session_id),n.$scroll_depth&&(e.scrollDepth=n.$scroll_depth),n.$scroll_percentage&&(e.scrollPercentage=n.$scroll_percentage),e.originalEvent=t.event,e}function c_(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:d5(t),source:"posthog",props:f5(t),schemaVersion:Na}}function u_(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 zp(t){return(e,n)=>{if(typeof e!="string")return;let i={event:e,properties:n,timestamp:Date.now()};if(u_(i)){let r=c_(i);t(r)}}}var d_=y.enum(["posthog","canvas","derived"]),Rk=y.object({ts:y.number(),name:y.string(),source:d_,props:y.record(y.string(),y.unknown()).optional(),schemaVersion:y.string()}),Ok=y.object({names:y.array(y.string()).optional(),patterns:y.array(y.string()).optional(),sources:y.array(d_).optional()});function p5(t){return Rk.safeParse(t)}function h5(t){return Ok.safeParse(t)}var Bs=class{constructor(){V(this,"listeners",new Set);V(this,"capturedPushState");V(this,"capturedReplaceState");V(this,"wasNative");V(this,"destroyed",!1);V(this,"onPopState",()=>{this.notify(window.location.href,"popstate")});this.wasNative=this.isNativeFunction(history.pushState),this.capturedPushState=history.pushState,this.capturedReplaceState=history.replaceState,history.pushState=(...e)=>{this.capturedPushState.call(history,...e),queueMicrotask(()=>this.notify(window.location.href,"pushState"))},history.replaceState=(...e)=>{this.capturedReplaceState.call(history,...e),queueMicrotask(()=>this.notify(window.location.href,"replaceState"))},window.addEventListener("popstate",this.onPopState)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}diagnose(){return{isNative:this.wasNative,subscriberCount:this.listeners.size}}destroy(){this.destroyed||(this.destroyed=!0,history.pushState=this.capturedPushState,history.replaceState=this.capturedReplaceState,window.removeEventListener("popstate",this.onPopState),this.listeners.clear())}notify(e,n){if(!this.destroyed)for(let i of this.listeners)try{i(e,n)}catch{}}isNativeFunction(e){try{return Function.prototype.toString.call(e).includes("[native code]")}catch{return!1}}};var f_="cooldown:";function Mk(t){return{set(e,n){let i=f_+e,r=Date.now()+n;t.set(i,r)},isActive(e){return this.remaining(e)>0},remaining(e){let n=f_+e,i=t.get(n);if(i===void 0)return 0;let r=i-Date.now();return r<=0?(t.remove(n),0):r},clear(e){let n=f_+e;t.remove(n)}}}var Kc="dismissed:";function Nk(t,e){return{mark(n,i=!1){let r=Kc+n;(i?e:t).set(r,!0)},isDismissed(n){let i=Kc+n;return t.has(i)||e.has(i)},clear(n){let i=Kc+n;t.remove(i),e.remove(i)},clearAll(){for(let n of t.keys())n.startsWith(Kc)&&t.remove(n);for(let n of e.keys())n.startsWith(Kc)&&e.remove(n)}}}var p_="freq:";function Dk(t){function e(n){let i=p_+n,r=t.get(i);if(r){if(r.resetAt&&Date.now()>=r.resetAt){t.remove(i);return}return r}}return{increment(n,i){let r=p_+n,a=e(n),o=(a?.count??0)+1,s={count:o,resetAt:a?.resetAt??(i?Date.now()+i:void 0)};return t.set(r,s),o},count(n){return e(n)?.count??0},reset(n){let i=p_+n;t.remove(i)},hasReachedLimit(n,i){return this.count(n)>=i}}}var g5="syntro";function h_(t,e){let n=`${e}:`;return{get(i){if(t)try{let r=t.getItem(n+i);if(!r)return;let a=JSON.parse(r);if(a.expiresAt&&Date.now()>=a.expiresAt){t.removeItem(n+i);return}return a.value}catch{return}},set(i,r,a){if(t)try{let o={value:r,expiresAt:a?Date.now()+a:void 0};t.setItem(n+i,JSON.stringify(o))}catch(o){console.warn("[StateStore] Failed to save:",o)}},remove(i){t&&t.removeItem(n+i)},has(i){return t?this.get(i)!==void 0:!1},keys(){if(!t)return[];let i=[];for(let r=0;r<t.length;r++){let a=t.key(r);a?.startsWith(n)&&i.push(a.slice(n.length))}return i},clear(){if(!t)return;let i=this.keys();for(let r of i)t.removeItem(n+r)}}}function g_(t){let e=new Map,n=`${t}:`;return{get(i){let r=e.get(n+i);if(r){if(r.expiresAt&&Date.now()>=r.expiresAt){e.delete(n+i);return}return r.value}},set(i,r,a){e.set(n+i,{value:r,expiresAt:a?Date.now()+a:void 0})},remove(i){e.delete(n+i)},has(i){return this.get(i)!==void 0},keys(){let i=[];for(let r of e.keys())r.startsWith(n)&&i.push(r.slice(n.length));return i},clear(){for(let i of e.keys())i.startsWith(n)&&e.delete(i)}}}var Xc=class{constructor(e={}){V(this,"session");V(this,"user");V(this,"dismissals");V(this,"cooldowns");V(this,"frequency");V(this,"namespace");V(this,"namespacedStorages",new Map);this.namespace=e.namespace??g5,typeof window<"u"?(this.session=h_(typeof sessionStorage<"u"?sessionStorage:void 0,this.namespace),this.user=h_(typeof localStorage<"u"?localStorage:void 0,this.namespace)):(this.session=g_(this.namespace),this.user=g_(this.namespace)),this.dismissals=Nk(this.session,this.user),this.cooldowns=Mk(this.user),this.frequency=Dk(this.session)}ns(e){let n=`${this.namespace}:${e}`;if(!this.namespacedStorages.has(n)){let i=typeof window<"u"&&typeof sessionStorage<"u"?h_(sessionStorage,n):g_(n);this.namespacedStorages.set(n,i)}return this.namespacedStorages.get(n)}};function Bp(t={}){return new Xc(t)}function $s(t){return t.startsWith("inline:")?"inline":t.startsWith("adjacent:")?"adjacent":"static"}function Qc(t){return t.startsWith("inline:")?t.slice(7):t.startsWith("adjacent:")?t.slice(9):null}var m_={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"}},Fs={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:[]},Lk={duration:200,easing:"cubic-bezier(0.16, 1, 0.3, 1)",fill:"forwards"};function $p(t,e,n){let i=m_[e];Object.assign(t.style,i),n&&(n.maxWidth&&(t.style.maxWidth=n.maxWidth),n.maxHeight&&(t.style.maxHeight=n.maxHeight),n.minWidth&&(t.style.minWidth=n.minWidth),n.minHeight&&(t.style.minHeight=n.minHeight))}function Fp(t,e,n){let i=n.placement==="auto"?"bottom":n.placement,r=[Vd(n.offset?{mainAxis:n.offset.y,crossAxis:n.offset.x}:8)];return n.flip!==!1&&r.push(qd()),n.shift!==!1&&r.push(jd({padding:8})),t.style.position="absolute",t.style.zIndex="2147483646",Ud(e,t,async()=>{let{x:o,y:s,strategy:l}=await Pd(e,t,{placement:i,middleware:r});Object.assign(t.style,{position:l,left:`${o}px`,top:`${s}px`})})}function Up(t,e,n="append"){return t.style.position="relative",t.style.display="inline-block",n==="prepend"?e.insertBefore(t,e.firstChild):e.appendChild(t),()=>{t.remove()}}function Vp(t,e){return e==="none"||Fs[e].length===0?null:t.animate(Fs[e],Lk)}function jp(t,e){if(e==="none"||Fs[e].length===0)return Promise.resolve();let n=[...Fs[e]].reverse(),i=t.animate(n,Lk);return new Promise(r=>{i.onfinish=()=>r(),i.oncancel=()=>r()})}function qp(t,e){let n=document.createElement("div");return n.setAttribute("data-syntro-surface",t),n.setAttribute("data-syntro-mount-id",e),n.className="syntro-surface",Object.assign(n.style,{pointerEvents:"auto",boxSizing:"border-box",overflow:"auto"}),n}function Pp(t){switch($s(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 Hk(t){if(typeof window.Sanitizer=="function")try{let l=new window.Sanitizer({}).sanitizeToFragment(t),c=document.createElement("div");return c.append(l),c.innerHTML}catch{}let n=document.createElement("template");n.innerHTML=t;let i=n.content,r=document.createTreeWalker(i,NodeFilter.SHOW_ELEMENT,null),a=new Set(["b","strong","i","em","u","span","div","p","br","ul","ol","li","code","pre","small","sup","sub","a","button"]),o=[];for(;r.nextNode();){let s=r.currentNode,l=s.tagName.toLowerCase();if(!a.has(l)){o.push(s);continue}for(let c of Array.from(s.attributes)){let u=c.name.toLowerCase(),f=c.value.trim().toLowerCase(),h=u.startsWith("on"),g=(u==="href"||u==="src")&&f.startsWith("javascript:");(h||g)&&s.removeAttribute(c.name)}}for(let s of o){for(;s.firstChild;)s.parentNode?.insertBefore(s.firstChild,s);s.remove()}return n.innerHTML=(i.firstChild,n.innerHTML)}var m5=0;function Gp(t){let{overlayRoot:e,eventBus:n,anchorResolver:i,defaultAnimation:r="fade",widgetRegistry:a}=t,o=new Map,s=new Map,l=new Map;function c(){return`mount-${++m5}`}function u(v,S){n&&n.publish(v,S)}function f(v){let S=l.get(v);if(S){let T=w(v);for(let A of S)try{A(T)}catch(k){console.error("[Surfaces] State callback error:",k)}}}let h=new Map;function g(v,S,T){switch(S.type){case"html":v.innerHTML=Hk(S.content);return;case"widget":{if(a?.has(S.widgetId)){let A=a.mount(S.widgetId,v,S.config);return T&&h.set(T,A),()=>{A.unmount(),T&&h.delete(T)}}console.warn(`[Surfaces] Widget not found: ${S.widgetId}`),v.innerHTML=`<div data-widget-id="${S.widgetId}" data-widget-missing="true">Widget: ${S.widgetId}</div>`;return}case"custom":return S.mount(v);case"react":v.innerHTML="<div data-react-component>React Component</div>";return;default:console.warn("[Surfaces] Unknown content type");return}}function _(v,S,T){let A=c(),k=$s(v),C=T?.priority??0,x=T?.animation??r,M=T?.exclusive??!0,z=o.get(v);if(z&&M){if(z.options.priority>C)throw new Error(`Slot ${v} is occupied by higher priority content (${z.options.priority} > ${C})`);b(z)}let U=qp(v,A);U.style.zIndex=String(Pp(v));let P;if(k==="static")$p(U,v,T?.constraints),e.appendChild(U);else if(k==="inline"){let D=Qc(v);if(!D)throw new Error(`Invalid inline slot: ${v}`);if(!i)throw new Error("Anchor resolver required for inline slots");let L=i(D);if(!L)throw new Error(`Anchor not found for inline slot: ${D}`);P=Up(U,L)}else if(k==="adjacent"){let D=Qc(v);if(!D)throw new Error(`Invalid adjacent slot: ${v}`);if(!i)throw new Error("Anchor resolver required for adjacent slots");let L=i(D);if(!L)throw new Error(`Anchor not found for adjacent slot: ${D}`);e.appendChild(U),P=Fp(U,L,T?.position??{placement:"bottom"})}let Z=g(U,S,A);Vp(U,x);let X={id:A,slot:v,content:S,options:{priority:C,exclusive:M,animation:x,position:T?.position??{placement:"auto"},constraints:T?.constraints??{},adaptiveId:T?.adaptiveId,autoUnmountOnRouteChange:T?.autoUnmountOnRouteChange??!0},container:U,cleanup:()=>{P?.(),Z?.()},mountedAt:Date.now()};return o.set(v,X),s.set(v,(s.get(v)??0)+1),u("surface.mounted",{slot:v,id:A,adaptiveId:T?.adaptiveId}),f(v),{id:A,update(D){let L=o.get(v);if(!L||L.id!==A)throw new Error("Mount no longer active");let de=h.get(A);if(de){if(D.type==="widget"){de.update(D.config),L.content=D;return}de.unmount(),h.delete(A)}L.container.innerHTML="";let fn=g(L.container,D,A);if(L.content=D,fn){let We=L.cleanup;L.cleanup=()=>{We?.(),fn()}}},setOptions(D){let L=o.get(v);if(!L||L.id!==A)throw new Error("Mount no longer active");D.priority!==void 0&&(L.options.priority=D.priority),D.animation!==void 0&&(L.options.animation=D.animation),D.constraints&&k==="static"&&(D.constraints.maxWidth&&(L.container.style.maxWidth=D.constraints.maxWidth),D.constraints.maxHeight&&(L.container.style.maxHeight=D.constraints.maxHeight),D.constraints.minWidth&&(L.container.style.minWidth=D.constraints.minWidth),D.constraints.minHeight&&(L.container.style.minHeight=D.constraints.minHeight)),f(v)},async unmount(){let D=o.get(v);!D||D.id!==A||await b(D)},isMounted(){return o.get(v)?.id===A},getContainer(){let D=o.get(v);return D?.id===A?D.container:null}}}async function b(v){await jp(v.container,v.options.animation),v.cleanup?.(),v.container.remove(),o.delete(v.slot),u("surface.unmounted",{slot:v.slot,id:v.id}),f(v.slot)}function w(v){let S=o.get(v);return{slot:v,occupied:!!S,currentPriority:S?.options.priority,currentAdaptiveId:S?.options.adaptiveId,mountCount:s.get(v)??0,currentMountId:S?.id}}function d(v,S){let T=l.get(v);return T||(T=new Set,l.set(v,T)),T.add(S),()=>{T?.delete(S),T?.size===0&&l.delete(v)}}function p(v,S){let T=o.get(v);return T?S!==void 0?S>=T.options.priority:!1:!0}function m(){for(let v of o.values())try{v.cleanup?.(),v.container.remove()}catch(S){console.error("[Surfaces] Error during cleanup:",S)}o.clear(),l.clear()}return{mount:_,getState:w,onStateChange:d,canMount:p,destroy:m}}var Jc=class{constructor(){V(this,"widgets",new Map);V(this,"mountedWidgets",new Map);V(this,"mountIdCounter",0);V(this,"runtimeRef");V(this,"listeners",new Set)}bindRuntime(e){this.runtimeRef=e}register(e,n,i="custom",r){if(this.widgets.has(e)){if(this.widgets.get(e).source==="built-in")throw new Error(`Cannot override built-in widget: ${e}`);console.warn(`[WidgetRegistry] Overriding widget: ${e}`)}this.widgets.set(e,{id:e,widget:n,source:i,metadata:r}),this.notify({type:"registered",widgetId:e})}unregister(e){let n=this.widgets.get(e);return n?n.source==="built-in"?(console.warn(`[WidgetRegistry] Cannot unregister built-in widget: ${e}`),!1):(this.widgets.delete(e),this.notify({type:"unregistered",widgetId:e}),!0):!1}unregisterBySource(e){for(let[n,i]of this.widgets.entries())i.source===e&&this.widgets.delete(n)}get(e){return this.widgets.get(e)?.widget}getRegistration(e){return this.widgets.get(e)}has(e){return this.widgets.has(e)}mount(e,n,i){let r=this.widgets.get(e);if(!r)throw new Error(`Widget not found: ${e}`);let a=`widget-mount-${++this.mountIdCounter}`;n.setAttribute("data-widget-mount-id",a),n.setAttribute("data-widget-id",e);let o={...i,runtime:this.runtimeRef},s=r.widget.mount(n,o);return this.mountedWidgets.set(a,{cleanup:s??void 0,container:n}),{widgetId:e,container:n,unmount:()=>{let c=this.mountedWidgets.get(a);c&&(c.cleanup?.(),this.mountedWidgets.delete(a),n.removeAttribute("data-widget-mount-id"),n.removeAttribute("data-widget-id"),n.innerHTML="")},update:c=>{if(r.widget.update)r.widget.update(n,c);else{let u=this.mountedWidgets.get(a);if(u){u.cleanup?.(),n.innerHTML="";let f={...c,runtime:this.runtimeRef},h=r.widget.mount(n,f);u.cleanup=h??void 0}}}}}list(){return Array.from(this.widgets.keys())}listRegistrations(){return Array.from(this.widgets.values())}getBySource(e){return Array.from(this.widgets.values()).filter(n=>n.source===e)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){for(let n of this.listeners)try{n(e)}catch(i){console.error("[WidgetRegistry] Listener error:",i)}}destroy(){for(let[e,n]of this.mountedWidgets.entries())n.cleanup?.(),n.container.innerHTML="";this.mountedWidgets.clear()}},Zp=new Jc;var v_="2.0.0";function v5(t,e){if(!e)return!0;let n;try{n=new URL(t).pathname}catch{n=t}let i=n.replace(/\/$/,"")||"/";if(e.exclude){for(let r of e.exclude)if(Ik(i,r))return!1}if(e.include&&e.include.length>0){for(let r of e.include)if(Ik(i,r))return!0;return!1}return!0}function Ik(t,e){let n=e.replace(/\/$/,"")||"/";if(t===n)return!0;let i=n.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/:[^/]+/g,"[^/]+");return new RegExp(`^${i}$`).test(t)}function y5(t){try{return document.querySelector(t)}catch{return null}}function Yp(t={}){let{telemetry:e,sessionMetrics:n,routes:i,mode:r="production",namespace:a}=t,o=t.widgets??Zp,s=t.executors??pi,l=t.apps??ts,c=new Bs,u=Lp({telemetry:e,routes:i,navigation:c}),f=t.events??zs(),h=Bp({namespace:a}),g=Ip({eventBus:f,stateStore:h}),_=Hp({state:h,events:f,sessionMetrics:n,accumulator:g}),b=UE(),w=v=>y5(v),d=Gp({overlayRoot:b,eventBus:f,anchorResolver:w,widgetRegistry:o}),p=Op({overlayRoot:b,eventBus:f,surfaces:d,anchorResolver:w,executorRegistry:s,subscribeNavigation:v=>c.subscribe(v)}),m={telemetry:e,context:u,events:f,state:h,sessionMetrics:n,actions:p,surfaces:d,widgets:o,executors:s,apps:l,accumulator:g,navigation:c,version:v_,mode:r,async evaluate(v){return _.evaluate(v,u.get())},evaluateSync(v){return _.evaluateSync(v,u.get())},async filterTiles(v){let S=u.get().page.url,T=[];for(let A of v){let k=A.activation;if(!k){T.push(A);continue}if(!v5(S,k.routes))continue;if(!k.strategy){T.push(A);continue}(await this.evaluate(k.strategy)).value&&T.push(A)}return T},setRoutes(v){u.setRoutes(v)},destroy(){l.unbind().catch(v=>{console.error("[Runtime] Error unbinding apps registry:",v)}),g.destroy(),c.destroy(),u.destroy(),p.destroy(),d.destroy()}};return l.bind(m),o.bindRuntime(m),m}var zk=y.object({value:y.unknown(),expiresAt:y.number().optional()}),Bk=y.object({count:y.number(),resetAt:y.number().optional()});function b5(t){return zk.safeParse(t)}function _5(t){return Bk.safeParse(t)}var $k={growthbook:t=>If({...t,autoInit:!0})};function Fk(t,e){let n=$k[t];if(!n)throw new Error(`Unknown experiment provider: ${t}. Supported: ${Object.keys($k).join(", ")}`);return n(e)}var S5=["cdn.syntrologie.com","localhost","127.0.0.1"];function x5(t){try{let e=new URL(t),n=/^(localhost|127\.0\.0\.1)$/.test(e.hostname);return e.protocol!=="https:"&&!n?(console.warn("[SmartCanvas] CDN URL must use HTTPS:",t),!1):S5.some(r=>e.hostname===r)?!0:(console.warn("[SmartCanvas] CDN host not in allowlist:",e.hostname),!1)}catch{return console.warn("[SmartCanvas] Invalid CDN URL:",t),!1}}var y_=class{constructor(e){V(this,"name","cdn");V(this,"url");V(this,"integrity");if(this.url=`${e.baseUrl}/${e.configId}.json`,this.integrity=e.integrity,!x5(this.url))throw new Error(`[SmartCanvas] CDN URL not allowed: ${this.url}`)}async fetch(){let e=performance.now(),n=await fetch(this.url,{credentials:"omit",cache:"default"});if(!n.ok)throw new Error(`[SmartCanvas] Failed to fetch config from CDN (${n.status})`);let i=await n.text();if(this.integrity){let l=await w5(i),c=this.integrity.replace("sha384-","");if(l!==c)throw new Error(`[SmartCanvas] Config integrity check failed. Expected ${c}, got ${l}`)}let r=JSON.parse(i),a=performance.now()-e,o=n.headers.get("cache-control"),s=n.headers.get("age");return{config:r,meta:{source:"cdn",fetchTimeMs:a,cached:o?.includes("public")??!1,cacheAge:s?parseInt(s,10):void 0}}}};async function w5(t){let n=new TextEncoder().encode(t),i=await crypto.subtle.digest("SHA-384",n),r=new Uint8Array(i);return btoa(String.fromCharCode(...r))}function Uk(t){return new y_(t)}var E5="syntro_exp",C5="syntro_var",b_=class{constructor(e){V(this,"name","experiments");V(this,"client");V(this,"featureKey");V(this,"manifestKey");V(this,"variantFlagPrefix");this.client=e.client,this.featureKey=e.featureKey??"smart-canvas-config",this.manifestKey=e.manifestKey,this.variantFlagPrefix=e.variantFlagPrefix}async fetch(){let e=performance.now();if(typeof window<"u"){let r=new URLSearchParams(window.location.search),a=r.get(E5),o=r.get(C5);if(a&&o!==null&&this.client.setForcedVariations){let s=parseInt(o,10);Number.isNaN(s)||(console.log(`[SmartCanvas] Preview mode: forcing "${a}" to variation ${s}`),this.client.setForcedVariations({[a]:s}))}}if(this.manifestKey||this.variantFlagPrefix){let r=this.fetchMultiFlag();if(r){let a=performance.now()-e;return{config:r,meta:{source:"experiments",fetchTimeMs:a,cached:!0}}}}let n=this.client.getFeatureValue?.(this.featureKey,null);if(!n||typeof n!="object")throw new Error(`[SmartCanvas] Feature "${this.featureKey}" not found or invalid. Ensure the feature is configured in your experiment platform.`);let i=performance.now()-e;return{config:n,meta:{source:"experiments",fetchTimeMs:i,cached:!0}}}fetchMultiFlag(){let e=this.getVariantFlagKeys();return!e||e.length===0?null:ef(this.client,e)}getVariantFlagKeys(){if(this.manifestKey){let e=this.client.getFeatureValue?.(this.manifestKey,null);if(e&&typeof e=="object"){let n=e.variant_flags;if(n&&n.length>0)return n}}if(this.variantFlagPrefix&&this.client.getAllFeatures){let e=this.client.getAllFeatures();return Object.keys(e).filter(n=>n.startsWith(this.variantFlagPrefix))}return[]}};function Vk(t){return new b_(t)}var A5="https://cdn.syntrologie.com/configs",jk={cdn:t=>{if(!t.configId)throw new Error("CDN fetcher requires 'configId' option");return Uk({baseUrl:t.baseUrl??A5,configId:t.configId,integrity:t.integrity})},experiments:t=>{if(!t.featureKey)throw new Error("Experiments fetcher requires 'featureKey' option");return Vk({featureKey:t.featureKey})}};function qk(t,e={}){let n=jk[t];if(!n)throw new Error(`Unknown config fetcher type: ${t}. Supported: ${Object.keys(jk).join(", ")}`);return n(e)}var Pk={posthog:t=>Ap(t),noop:()=>Pf()};function Gk(t,e){let n=Pk[t];if(!n)throw new Error(`Unknown telemetry provider: ${t}. Supported: ${Object.keys(Pk).join(", ")}`);return n(e)}var __="syn_";function eu(t){if(!t.startsWith(__))throw new Error("Invalid Syntro token: must start with 'syn_'");let n=t.slice(__.length).replace(/-/g,"+").replace(/_/g,"/"),i=atob(n),r=JSON.parse(i);if(r.v!==1)throw new Error(`Unsupported token version: ${r.v}`);return r}function Wp(t){let e=JSON.stringify(t),n=btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");return __+n}function er(t){if(typeof process<"u"&&process.env)return process.env[t];try{let e=(0,eval)("import.meta");if(e?.env)return e.env[t]}catch{}}function T5(){if(typeof window>"u")return G("Syntro Bootstrap","isEditorMode: not in browser"),!1;let t=Ma(),n=!!(Lr()?.token&&t?.mode==="editor");return G("Syntro Bootstrap","isEditorMode:",n),n}function k5(){if(typeof window>"u")return G("Syntro Bootstrap","isAuditMode: not in browser"),!1;let t=Ma(),n=!!(Lr()?.token&&t?.mode==="audit");return G("Syntro Bootstrap","isAuditMode:",n),n}function R5(){if(typeof window>"u")return G("Syntro Bootstrap","isReviewMode: not in browser"),!1;let t=Ma(),n=!!(Lr()?.token&&t?.mode==="review");return G("Syntro Bootstrap","isReviewMode:",n),n}var Zk="syntro_segment_attributes";function O5(){if(typeof window>"u")return{};try{let t=localStorage.getItem(Zk);if(t){let e=JSON.parse(t);return G("Syntro Bootstrap","Loaded cached segment attributes:",e),e}}catch(t){cn("Syntro Bootstrap","Failed to load cached segment attributes:",t)}return{}}function M5(t){if(!(typeof window>"u"))try{localStorage.setItem(Zk,JSON.stringify(t)),G("Syntro Bootstrap","Cached segment attributes:",t)}catch(e){cn("Syntro Bootstrap","Failed to cache segment attributes:",e)}}function N5(t){if(!t)return{};let e={};for(let[n,i]of Object.entries(t))n.startsWith("in_segment_")&&(e[n]=i===!0);return e}async function D5(t){Jm(),G("Syntro Bootstrap","====== INIT ======"),G("Syntro Bootstrap","Options:",{hasToken:!!t.token,tokenPrefix:`${t.token?.slice(0,15)}...`,hasCanvasOptions:!!t.canvas});let e=T5(),n=k5(),i=R5(),r=e?"editor":n?"audit":i?"review":null;if(console.log(`[DIAG] Mode detection: editor=${e}, audit=${n}, review=${i}, sdkMode=${r}`),console.log("[DIAG] editorSource:",Lr()),console.log("[DIAG] editorConf:",Ma()),G("Syntro Bootstrap","SDK mode:",r??"normal"),!r&&typeof window<"u"){let x=!!window.__SYNTRO_EDITOR_PARAMS__,M=!!window.__SYNTRO_AUDIT_LEGEND__,z=!!window.__SYNTRO_REVIEW_DATA__;if(x||M||z){let U=[x&&"__SYNTRO_EDITOR_PARAMS__",M&&"__SYNTRO_AUDIT_LEGEND__",z&&"__SYNTRO_REVIEW_DATA__"].filter(Boolean);console.warn(`[Syntro Bootstrap] \u26A0 Mode detection returned null but mode-specific globals found: ${U.join(", ")}. This suggests URL params were lost (redirect?) but the service worker injected mode data. Check if replaceState failed or if page JS changed the URL before init().`)}}console.log(`[DIAG] Token resolution: options.token=${t.token?t.token.slice(0,15)+"...":"null"}`);let a=t.token;if(!a&&r){let M=Ma()?.syntro_token;M?.startsWith("syn_")&&(a=M,G("Syntro Bootstrap",`\u2713 Using syntro_token from editor_conf (${r} mode)`))}let o;if(a)if(a.startsWith("syn_"))G("Syntro Bootstrap","Token starts with syn_, decoding..."),o=eu(a),Jm(o.d);else if(r)G("Syntro Bootstrap",`\u2713 Non-syn_ token allowed (${r} mode)`);else throw tf("Syntro Bootstrap","\u274C Token does not start with syn_ and NOT in editor/audit/review mode!"),tf("Syntro Bootstrap","Token received:",a),new Error("Invalid Syntro token: must start with 'syn_'");else if(r)G("Syntro Bootstrap",`\u2713 No token, but ${r} mode - proceeding`);else throw tf("Syntro Bootstrap","\u274C No token provided and NOT in editor/audit/review mode!"),new Error("Syntro token is required (unless in editor, audit, or review mode)");let s=er("NEXT_PUBLIC_SYNTRO_EXPERIMENT_HOST")||er("VITE_SYNTRO_EXPERIMENT_HOST")||o?.eh,l=er("NEXT_PUBLIC_SYNTRO_TELEMETRY_HOST")||er("VITE_SYNTRO_TELEMETRY_HOST")||o?.th,c=er("NEXT_PUBLIC_SYNTRO_EDITOR_URL")||er("VITE_SYNTRO_EDITOR_URL")||t.canvas?.editorUrl,u=O5();G("Syntro Bootstrap","Phase 1: Using cached segment attributes:",u);let f,h=zs();console.log("[Syntro Bootstrap] EventBus created");let g=zp(x=>{h.publishEvent(x)}),_=x=>{G("Syntro Bootstrap","Phase 2: PostHog feature flags loaded");let M=N5(x);if(G("Syntro Bootstrap","Segment flags from PostHog:",M),M5(M),f){let U={...w?.getAll?.()??{},...M};G("Syntro Bootstrap","Updating GrowthBook with attributes:",U),f.setAttributes?.(U)}},b;if(o?.t){let x=o.t==="noop"?"noop":"posthog";b=Gk(x,{apiKey:o.t,apiHost:l,enableFeatureFlags:!0,onFeatureFlagsLoaded:_,onCapture:g}),console.log(`[Syntro Bootstrap] Telemetry client created (${x}) with EventBus wiring`)}let w;o?.e&&(f=Fk("growthbook",{clientKey:o.e,apiHost:s,attributes:u,onExperimentViewed:b?.trackExperiment?(x,M,z)=>{b.trackExperiment(x,M,z)}:void 0})),t.enableSessionMetrics&&(w=zf({experiments:f,onMetricChange:(x,M)=>{G("Syntro Bootstrap",`Session metric changed: ${x} = ${M}`)}}),G("Syntro Bootstrap","SessionMetricTracker created"));let d="production";e?d="editor":n?d="audit":er("NODE_ENV")==="development"&&(d="development");let p=Yp({telemetry:b,sessionMetrics:w,mode:d,events:h});G("Syntro Bootstrap","Runtime created:",{version:p.version,mode:p.mode,hasContext:!!p.context,hasEvents:!!p.events,hasState:!!p.state}),G("Syntro Bootstrap","Core app executors already registered");let m=t.cdnBase||er("NEXT_PUBLIC_SYNTRO_CDN_BASE")||er("VITE_SYNTRO_CDN_BASE")||"https://cdn.syntrologie.com",v=Kd({cdnBase:m,registry:p.apps,onLoadStart:x=>{G("Syntro Bootstrap",`Loading app from CDN: ${x}`)},onLoadEnd:(x,M,z)=>{M?G("Syntro Bootstrap",`App loaded successfully: ${x}`):cn("Syntro Bootstrap",`Failed to load app: ${x}`,z)}});typeof window<"u"&&(window.SynOS={...window.SynOS,appRegistry:p.apps,runtime:p,version:p.version},G("Syntro Bootstrap","Global SynOS object exposed"));let S=p.apps.list?.()??[];console.log(`[DIAG] Activation loop: ${S.length} apps in registry:`,S.map(x=>`${x.manifest.id}(${x.state})`).join(", "));for(let x of S)if(x.state==="registered")try{await p.apps.activate(x.manifest.id),console.log(`[DIAG] Activated: ${x.manifest.id} \u2192 widgets: [${p.widgets.list().join(", ")}]`)}catch(M){console.error(`[DIAG] FAILED to activate: ${x.manifest.id}`,M),cn("Syntro Bootstrap",`Failed to auto-activate built-in app: ${x.manifest.id}`,M)}if(console.log(`[DIAG] Activation complete. Total widgets: [${p.widgets.list().join(", ")}]`),f?.refreshFeatures)try{await f.refreshFeatures(),G("Syntro Bootstrap","GrowthBook features loaded")}catch(x){cn("Syntro Bootstrap","Failed to load GrowthBook features:",x)}let T;if(t.fetcher)T=t.fetcher;else if(o?.f){let x=qk(o.f,o.o??{});T=async()=>{let M=await x.fetch();return{...M.config,tiles:M.config.tiles??[]}}}else f&&(T=Oa({experiments:f}));let A=new Set,k=T?async()=>{let x=await T();console.log("[Syntro Bootstrap] Config fetched:",`tiles=${x.tiles?.length??0},`,`actions=${x.actions?.length??0},`,`theme=${x.theme?.name??"none"}`),x.actions?.length>0&&console.log("[Syntro Bootstrap] Actions in config:",x.actions.map((U,P)=>`[${P}] ${U.kind}${U.anchorId?` anchor="${U.anchorId}"`:""}${U.label?` "${U.label}"`:""}`).join(", "));let M=x,z=v.getRequiredApps(M);return z.length>0?console.log("[Syntro Bootstrap] Required external apps:",z.join(", ")):G("Syntro Bootstrap","No external apps required (all executors are built-in)"),z.length>0&&await v.loadAppsForConfig(M).then(async P=>{let Z=P.filter(D=>D.success),X=P.filter(D=>!D.success);Z.length>0&&console.log(`[Syntro Bootstrap] Apps loaded from CDN: ${Z.map(D=>D.appId).join(", ")}`);let W=X.filter(D=>!A.has(D.appId));W.length>0&&(console.error("[Syntro Bootstrap] Apps FAILED to load from CDN:",W.map(D=>`${D.appId} (${D.error})`).join(", ")),W.forEach(D=>A.add(D.appId)));for(let D of z)if(p.apps.has(D))try{await p.apps.activate(D),console.log(`[Syntro Bootstrap] App activated: ${D}`)}catch(L){console.error(`[Syntro Bootstrap] Failed to activate app: ${D}`,L)}else console.error(`[Syntro Bootstrap] App "${D}" required by config but NOT registered.`,`Available apps: [${Array.from(p.apps.list?.()??[]).join(", ")}]`)}),x}:void 0;return{canvas:await yf({...t.canvas,fetcher:k,integrations:{experiments:f,telemetry:b},editorUrl:c,runtime:p}),runtime:p,experiments:f,telemetry:b,sessionMetrics:w,appLoader:v}}var S_={init:D5,encodeToken:Wp,decodeToken:eu};typeof window<"u"&&(window.Syntro=S_);var x_="2026-02-26T22:38:37.348Z (38fdc4fa1)";if(typeof window<"u"){console.log(`[Syntro Runtime] Build: ${x_}`);let t=window.SynOS,e=t?.appRegistry||ts;window.SynOS={...t,appRegistry:e,_runtimeBuild:x_,React:Yk.default,ReactDOM:{...L5,createPortal:Kp.createPortal,flushSync:Kp.flushSync}},RE(e)}return aR(H5);})();
|
|
450
450
|
/*! Bundled license information:
|
|
451
451
|
|
|
452
452
|
react/cjs/react.production.js:
|