@canonry/canonry 5.30.2 → 5.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (20) hide show
  1. package/assets/assets/{AuditHistoryPanel-8GPJdEWL.js → AuditHistoryPanel-DW2aeqJP.js} +1 -1
  2. package/assets/assets/{BacklinksPage-8-KPXFtA.js → BacklinksPage-DroPpjd3.js} +1 -1
  3. package/assets/assets/{HistoryPage-CKgF71m5.js → HistoryPage-2o6p-ZDF.js} +1 -1
  4. package/assets/assets/{MeasurementPropertyPage-nfGYHl6C.js → MeasurementPropertyPage-VTGLyVuD.js} +1 -1
  5. package/assets/assets/{ProjectPage-BPtdO-Gp.js → ProjectPage-CXV64SBB.js} +1 -1
  6. package/assets/assets/{RunRow-C3CRRfb4.js → RunRow-CIhSIAoR.js} +1 -1
  7. package/assets/assets/{RunsPage-BvCCjtqM.js → RunsPage-lO9xMTSl.js} +1 -1
  8. package/assets/assets/{SettingsPage-B1QuP6Cv.js → SettingsPage-CBwns7cb.js} +1 -1
  9. package/assets/assets/{SiteHealthSection-DgM3aTd-.js → SiteHealthSection-C372wrfT.js} +3 -3
  10. package/assets/assets/{TrafficPage-DEUDhBXG.js → TrafficPage-DGyS-IjJ.js} +1 -1
  11. package/assets/assets/{TrafficSourceDetailPage-gpgLsGA1.js → TrafficSourceDetailPage-BBaz_ivE.js} +1 -1
  12. package/assets/assets/{extract-error-message-CH4G5kw6.js → extract-error-message-QcHrDOjc.js} +1 -1
  13. package/assets/assets/{index-B2qeAPfR.js → index-CbnQjcJj.js} +3 -3
  14. package/assets/assets/{react-sigma_core.esm.min-CG4hSMQ3.js → react-sigma_core.esm.min-D9tjGma4.js} +1 -1
  15. package/assets/assets/{v2-overview-adapter-QNwqt0UG.js → v2-overview-adapter-CLlJkExr.js} +1 -1
  16. package/assets/index.html +1 -1
  17. package/dist/{chunk-7YRGVXR5.js → chunk-6UO23AKO.js} +147 -64
  18. package/dist/cli.js +1 -1
  19. package/dist/index.js +1 -1
  20. package/package.json +12 -13
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./SiteHealthSection-DgM3aTd-.js","./vendor-tanstack-ZXXkndVj.js","./vendor-lucide-N6vOpZmh.js","./ChartPrimitives-B5okB5g-.js","./vendor-recharts-llkUFBGR.js","./ProjectPage-BPtdO-Gp.js","./RunRow-C3CRRfb4.js","./extract-error-message-CH4G5kw6.js","./v2-overview-adapter-QNwqt0UG.js","./vendor-markdown-B4giJcws.js","./AuditHistoryPanel-8GPJdEWL.js","./vendor-radix-twS1M3FF.js","./vendor-yaml-GWJz5H2G.js","./RunsPage-BvCCjtqM.js","./HistoryPage-CKgF71m5.js","./SettingsPage-B1QuP6Cv.js","./BacklinksPage-8-KPXFtA.js","./TrafficPage-DEUDhBXG.js","./TrafficSourceDetailPage-gpgLsGA1.js","./MeasurementPropertyPage-nfGYHl6C.js"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./SiteHealthSection-C372wrfT.js","./vendor-tanstack-ZXXkndVj.js","./vendor-lucide-N6vOpZmh.js","./ChartPrimitives-B5okB5g-.js","./vendor-recharts-llkUFBGR.js","./ProjectPage-CXV64SBB.js","./RunRow-CIhSIAoR.js","./extract-error-message-QcHrDOjc.js","./v2-overview-adapter-CLlJkExr.js","./vendor-markdown-B4giJcws.js","./AuditHistoryPanel-DW2aeqJP.js","./vendor-radix-twS1M3FF.js","./vendor-yaml-GWJz5H2G.js","./RunsPage-lO9xMTSl.js","./HistoryPage-2o6p-ZDF.js","./SettingsPage-CBwns7cb.js","./BacklinksPage-DroPpjd3.js","./TrafficPage-DGyS-IjJ.js","./TrafficSourceDetailPage-BBaz_ivE.js","./MeasurementPropertyPage-VTGLyVuD.js"])))=>i.map(i=>d[i]);
2
2
  import{c as GN,d as KN,r as C,j as l,Q as HN,M as QN,q as ye,e as Nc,L as We,a as FN,t as wr,u as yt,f as ZN,h as Jn,k as Ns,l as Pk,m as YN,n as qk,O as Tf,o as Ga,p as XN,s as qt,v as Mk,x as _s,y as JN,z as WN,A as e5}from"./vendor-tanstack-ZXXkndVj.js";import{S as t5,O as kg,P as Bk,C as Sg,a as Lk,T as jg,D as Vk,R as $k}from"./vendor-radix-twS1M3FF.js";import{c as Uk}from"./vendor-recharts-llkUFBGR.js";import{A as yc,X as $r,S as Ag,a as Gk,G as Kk,C as Jd,L as Rr,R as ed,M as n5,b as a5,P as Ef,H as Hk,c as i5,d as s5,e as Wd,f as Cg,T as Qk,W as o5,g as Ng,h as r5,i as l5,j as c5,k as u5,l as d5,m as m5,n as p5,B as h5,F as f5,o as g5,p as y5,q as b5,r as v5,s as Fk,t as Zk,u as Rf,v as Yk,w as x5,x as Xk,E as w5}from"./vendor-lucide-N6vOpZmh.js";import{M as k5,r as S5}from"./vendor-markdown-B4giJcws.js";import{p as j5}from"./vendor-yaml-GWJz5H2G.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const u of document.querySelectorAll('link[rel="modulepreload"]'))r(u);new MutationObserver(u=>{for(const h of u)if(h.type==="childList")for(const f of h.addedNodes)f.tagName==="LINK"&&f.rel==="modulepreload"&&r(f)}).observe(document,{childList:!0,subtree:!0});function i(u){const h={};return u.integrity&&(h.integrity=u.integrity),u.referrerPolicy&&(h.referrerPolicy=u.referrerPolicy),u.crossOrigin==="use-credentials"?h.credentials="include":u.crossOrigin==="anonymous"?h.credentials="omit":h.credentials="same-origin",h}function r(u){if(u.ep)return;u.ep=!0;const h=i(u);fetch(u.href,h)}})();var $h={exports:{}},tc={},Uh={exports:{}},Gh={};var Fv;function A5(){return Fv||(Fv=1,(function(e){function n(O,ne){var ge=O.length;O.push(ne);e:for(;0<ge;){var Se=ge-1>>>1,ae=O[Se];if(0<u(ae,ne))O[Se]=ne,O[ge]=ae,ge=Se;else break e}}function i(O){return O.length===0?null:O[0]}function r(O){if(O.length===0)return null;var ne=O[0],ge=O.pop();if(ge!==ne){O[0]=ge;e:for(var Se=0,ae=O.length,_e=ae>>>1;Se<_e;){var Be=2*(Se+1)-1,ve=O[Be],le=Be+1,ce=O[le];if(0>u(ve,ge))le<ae&&0>u(ce,ve)?(O[Se]=ce,O[le]=ge,Se=le):(O[Se]=ve,O[Be]=ge,Se=Be);else if(le<ae&&0>u(ce,ge))O[Se]=ce,O[le]=ge,Se=le;else break e}}return ne}function u(O,ne){var ge=O.sortIndex-ne.sortIndex;return ge!==0?ge:O.id-ne.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var h=performance;e.unstable_now=function(){return h.now()}}else{var f=Date,b=f.now();e.unstable_now=function(){return f.now()-b}}var v=[],w=[],k=1,j=null,T=3,N=!1,P=!1,E=!1,q=!1,H=typeof setTimeout=="function"?setTimeout:null,X=typeof clearTimeout=="function"?clearTimeout:null,L=typeof setImmediate<"u"?setImmediate:null;function Z(O){for(var ne=i(w);ne!==null;){if(ne.callback===null)r(w);else if(ne.startTime<=O)r(w),ne.sortIndex=ne.expirationTime,n(v,ne);else break;ne=i(w)}}function Y(O){if(E=!1,Z(O),!P)if(i(v)!==null)P=!0,ee||(ee=!0,Ue());else{var ne=i(w);ne!==null&&$e(Y,ne.startTime-O)}}var ee=!1,B=-1,K=5,we=-1;function Xe(){return q?!0:!(e.unstable_now()-we<K)}function nt(){if(q=!1,ee){var O=e.unstable_now();we=O;var ne=!0;try{e:{P=!1,E&&(E=!1,X(B),B=-1),N=!0;var ge=T;try{t:{for(Z(O),j=i(v);j!==null&&!(j.expirationTime>O&&Xe());){var Se=j.callback;if(typeof Se=="function"){j.callback=null,T=j.priorityLevel;var ae=Se(j.expirationTime<=O);if(O=e.unstable_now(),typeof ae=="function"){j.callback=ae,Z(O),ne=!0;break t}j===i(v)&&r(v),Z(O)}else r(v);j=i(v)}if(j!==null)ne=!0;else{var _e=i(w);_e!==null&&$e(Y,_e.startTime-O),ne=!1}}break e}finally{j=null,T=ge,N=!1}ne=void 0}}finally{ne?Ue():ee=!1}}}var Ue;if(typeof L=="function")Ue=function(){L(nt)};else if(typeof MessageChannel<"u"){var Pe=new MessageChannel,ke=Pe.port2;Pe.port1.onmessage=nt,Ue=function(){ke.postMessage(null)}}else Ue=function(){H(nt,0)};function $e(O,ne){B=H(function(){O(e.unstable_now())},ne)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(O){O.callback=null},e.unstable_forceFrameRate=function(O){0>O||125<O?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):K=0<O?Math.floor(1e3/O):5},e.unstable_getCurrentPriorityLevel=function(){return T},e.unstable_next=function(O){switch(T){case 1:case 2:case 3:var ne=3;break;default:ne=T}var ge=T;T=ne;try{return O()}finally{T=ge}},e.unstable_requestPaint=function(){q=!0},e.unstable_runWithPriority=function(O,ne){switch(O){case 1:case 2:case 3:case 4:case 5:break;default:O=3}var ge=T;T=O;try{return ne()}finally{T=ge}},e.unstable_scheduleCallback=function(O,ne,ge){var Se=e.unstable_now();switch(typeof ge=="object"&&ge!==null?(ge=ge.delay,ge=typeof ge=="number"&&0<ge?Se+ge:Se):ge=Se,O){case 1:var ae=-1;break;case 2:ae=250;break;case 5:ae=1073741823;break;case 4:ae=1e4;break;default:ae=5e3}return ae=ge+ae,O={id:k++,callback:ne,priorityLevel:O,startTime:ge,expirationTime:ae,sortIndex:-1},ge>Se?(O.sortIndex=ge,n(w,O),i(v)===null&&O===i(w)&&(E?(X(B),B=-1):E=!0,$e(Y,ge-Se))):(O.sortIndex=ae,n(v,O),P||N||(P=!0,ee||(ee=!0,Ue()))),O},e.unstable_shouldYield=Xe,e.unstable_wrapCallback=function(O){var ne=T;return function(){var ge=T;T=ne;try{return O.apply(this,arguments)}finally{T=ge}}}})(Gh)),Gh}var Zv;function C5(){return Zv||(Zv=1,Uh.exports=A5()),Uh.exports}var Yv;function N5(){if(Yv)return tc;Yv=1;var e=C5(),n=GN(),i=KN();function r(t){var a="https://react.dev/errors/"+t;if(1<arguments.length){a+="?args[]="+encodeURIComponent(arguments[1]);for(var s=2;s<arguments.length;s++)a+="&args[]="+encodeURIComponent(arguments[s])}return"Minified React error #"+t+"; visit "+a+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function u(t){return!(!t||t.nodeType!==1&&t.nodeType!==9&&t.nodeType!==11)}function h(t){var a=t,s=t;if(t.alternate)for(;a.return;)a=a.return;else{t=a;do a=t,(a.flags&4098)!==0&&(s=a.return),t=a.return;while(t)}return a.tag===3?s:null}function f(t){if(t.tag===13){var a=t.memoizedState;if(a===null&&(t=t.alternate,t!==null&&(a=t.memoizedState)),a!==null)return a.dehydrated}return null}function b(t){if(t.tag===31){var a=t.memoizedState;if(a===null&&(t=t.alternate,t!==null&&(a=t.memoizedState)),a!==null)return a.dehydrated}return null}function v(t){if(h(t)!==t)throw Error(r(188))}function w(t){var a=t.alternate;if(!a){if(a=h(t),a===null)throw Error(r(188));return a!==t?null:t}for(var s=t,c=a;;){var p=s.return;if(p===null)break;var g=p.alternate;if(g===null){if(c=p.return,c!==null){s=c;continue}break}if(p.child===g.child){for(g=p.child;g;){if(g===s)return v(p),t;if(g===c)return v(p),a;g=g.sibling}throw Error(r(188))}if(s.return!==c.return)s=p,c=g;else{for(var x=!1,A=p.child;A;){if(A===s){x=!0,s=p,c=g;break}if(A===c){x=!0,c=p,s=g;break}A=A.sibling}if(!x){for(A=g.child;A;){if(A===s){x=!0,s=g,c=p;break}if(A===c){x=!0,c=g,s=p;break}A=A.sibling}if(!x)throw Error(r(189))}}if(s.alternate!==c)throw Error(r(190))}if(s.tag!==3)throw Error(r(188));return s.stateNode.current===s?t:a}function k(t){var a=t.tag;if(a===5||a===26||a===27||a===6)return t;for(t=t.child;t!==null;){if(a=k(t),a!==null)return a;t=t.sibling}return null}var j=Object.assign,T=Symbol.for("react.element"),N=Symbol.for("react.transitional.element"),P=Symbol.for("react.portal"),E=Symbol.for("react.fragment"),q=Symbol.for("react.strict_mode"),H=Symbol.for("react.profiler"),X=Symbol.for("react.consumer"),L=Symbol.for("react.context"),Z=Symbol.for("react.forward_ref"),Y=Symbol.for("react.suspense"),ee=Symbol.for("react.suspense_list"),B=Symbol.for("react.memo"),K=Symbol.for("react.lazy"),we=Symbol.for("react.activity"),Xe=Symbol.for("react.memo_cache_sentinel"),nt=Symbol.iterator;function Ue(t){return t===null||typeof t!="object"?null:(t=nt&&t[nt]||t["@@iterator"],typeof t=="function"?t:null)}var Pe=Symbol.for("react.client.reference");function ke(t){if(t==null)return null;if(typeof t=="function")return t.$$typeof===Pe?null:t.displayName||t.name||null;if(typeof t=="string")return t;switch(t){case E:return"Fragment";case H:return"Profiler";case q:return"StrictMode";case Y:return"Suspense";case ee:return"SuspenseList";case we:return"Activity"}if(typeof t=="object")switch(t.$$typeof){case P:return"Portal";case L:return t.displayName||"Context";case X:return(t._context.displayName||"Context")+".Consumer";case Z:var a=t.render;return t=t.displayName,t||(t=a.displayName||a.name||"",t=t!==""?"ForwardRef("+t+")":"ForwardRef"),t;case B:return a=t.displayName||null,a!==null?a:ke(t.type)||"Memo";case K:a=t._payload,t=t._init;try{return ke(t(a))}catch{}}return null}var $e=Array.isArray,O=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,ne=i.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,ge={pending:!1,data:null,method:null,action:null},Se=[],ae=-1;function _e(t){return{current:t}}function Be(t){0>ae||(t.current=Se[ae],Se[ae]=null,ae--)}function ve(t,a){ae++,Se[ae]=t.current,t.current=a}var le=_e(null),ce=_e(null),Q=_e(null),me=_e(null);function De(t,a){switch(ve(Q,a),ve(ce,t),ve(le,null),a.nodeType){case 9:case 11:t=(t=a.documentElement)&&(t=t.namespaceURI)?yv(t):0;break;default:if(t=a.tagName,a=a.namespaceURI)a=yv(a),t=bv(a,t);else switch(t){case"svg":t=1;break;case"math":t=2;break;default:t=0}}Be(le),ve(le,t)}function je(){Be(le),Be(ce),Be(Q)}function it(t){t.memoizedState!==null&&ve(me,t);var a=le.current,s=bv(a,t.type);a!==s&&(ve(ce,t),ve(le,s))}function Ge(t){ce.current===t&&(Be(le),Be(ce)),me.current===t&&(Be(me),Xl._currentValue=ge)}var jt,He;function re(t){if(jt===void 0)try{throw Error()}catch(s){var a=s.stack.trim().match(/\n( *(at )?)/);jt=a&&a[1]||"",He=-1<s.stack.indexOf(`
3
3
  at`)?" (<anonymous>)":-1<s.stack.indexOf("@")?"@unknown:0:0":""}return`
4
4
  `+jt+t+He}var lt=!1;function Gt(t,a){if(!t||lt)return"";lt=!0;var s=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var c={DetermineComponentFrameRoot:function(){try{if(a){var se=function(){throw Error()};if(Object.defineProperty(se.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(se,[])}catch(F){var G=F}Reflect.construct(t,[],se)}else{try{se.call()}catch(F){G=F}t.call(se.prototype)}}else{try{throw Error()}catch(F){G=F}(se=t())&&typeof se.catch=="function"&&se.catch(function(){})}}catch(F){if(F&&G&&typeof F.stack=="string")return[F.stack,G.stack]}return[null,null]}};c.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var p=Object.getOwnPropertyDescriptor(c.DetermineComponentFrameRoot,"name");p&&p.configurable&&Object.defineProperty(c.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var g=c.DetermineComponentFrameRoot(),x=g[0],A=g[1];if(x&&A){var D=x.split(`
@@ -60,7 +60,7 @@ ${JSON.stringify(r.raw,null,2)}`):n.push(u)}return n.length>0?n.join(`
60
60
  `);for(;Z!==-1;){const Y=q.slice(0,Z);q=q.slice(Z+2);for(const ee of Y.split(`
61
61
  `)){if(!ee.startsWith("data:"))continue;const B=ee.slice(5).trim();if(!B)continue;let K;try{K=JSON.parse(B)}catch{continue}K.type==="stream_close"&&(N=!0),k(K)}Z=q.indexOf(`
62
62
 
63
- `)}}if(w?.aborted)throw new DOMException("Turn stopped","AbortError");if(!N)throw new Error("Connection ended before Aero finished. Review the partial answer before retrying.")}finally{w?.removeEventListener("abort",H);try{P.releaseLock()}catch{}}}function Ad(e){return!e||e.role!=="assistant"?"":e.content.filter(n=>n.type==="text").map(n=>n.text).join("")}const gg=[{id:"status",label:"Status",prompt:"Give me a quick status: the latest sweep, which engines answered, and anything that needs attention."},{id:"changes",label:"What changed",prompt:"Compare the latest complete sweep with the one before it. Lead with mentions, then citations. Keep branded and non-brand queries separate if the project splits them, and say which changes are bigger than normal run-to-run noise."},{id:"gaps",label:"Biggest gaps",prompt:"Which tracked queries does no engine mention us on, and who gets named instead? Group them by topic or market."},{id:"insights",label:"Top insights",prompt:"Walk me through the 3 most severe active insights and what to do about each."}],lY="https://canonry.ai",cY="This demo plays sample answers only. Pick a starting point, or type / to choose one.",uY="Stopped. The sample answer so far is kept.";function yk(e){return{queryKey:["aero-preview",e],queryFn:()=>sY(e),staleTime:1/0,gcTime:1/0}}const bk=[{command:"/status",label:"Status",prompt:"Give me a quick status: the latest sweep, which engines answered, and anything that needs attention."},{command:"/changes",label:"What changed",prompt:"Compare the latest complete sweep with the one before it. Lead with mentions, then citations. Keep branded and non-brand queries separate if the project splits them, and say which changes are bigger than normal run-to-run noise."},{command:"/gaps",label:"Biggest gaps",prompt:"Which tracked queries does no engine mention us on, and who gets named instead? Group them by topic or market."},{command:"/insights",label:"Top insights",prompt:"Walk me through the 3 most severe active insights and what to do about each."},{command:"/last-run",label:"Last run",prompt:"Summarize the latest run for this project: which engines answered, what moved in mentions and citations, and anything that failed."},{command:"/run-sweep",label:"Run sweep now",prompt:"Run a new answer-visibility sweep for this project now and tell me when it lands."},{command:"/queries",label:"Queries",prompt:"List the tracked queries for this project and flag any that are obvious duplicates or underperformers."},{command:"/competitors",label:"Competitors",prompt:"Which competitors do engines name most often on queries where we are not named, and on which engines?"},{command:"/new",label:"New conversation (save current)",action:"new"}],fd=e=>`canonry:aero:provider:${e}`,dY=e=>`canonry:aero:scope:${e}`;function vk(e){if(typeof window>"u")return null;try{return window.localStorage.getItem(e)}catch{return null}}function mY(e,n){if(!(typeof window>"u"))try{window.localStorage.setItem(e,n)}catch{}}function xk(e){if(!(typeof window>"u"))try{window.localStorage.removeItem(e)}catch{}}function pY({projectName:e,context:n,preview:i=W0()}){const r=fo(),{canWrite:u,account:h}=pa(),f=Jn(),b=h?.role==="viewer",[v,w]=C.useState(!1),[k,j]=C.useState(!1),[T,N]=C.useState([]),[P,E]=C.useState(void 0),q=C.useRef(!1),[H,X]=C.useState(!1),[L,Z]=C.useState(!1),[Y,ee]=C.useState(null),[B,K]=C.useState(!1),[we,Xe]=C.useState(!1),[nt,Ue]=C.useState(null),Pe=C.useRef(!1),[ke,$e]=C.useState(""),[O,ne]=C.useState(!1),[ge,Se]=C.useState([]),[ae,_e]=C.useState(""),[Be,ve]=C.useState(null),[le,ce]=C.useState(null),[Q,me]=C.useState(null),De=C.useRef(!0),[je,it]=C.useState(()=>vk(fd(e))??null),Ge=r||b||i?null:je,[jt]=C.useState(()=>vk(dY(e))==="all"?"all":"read-only"),He=r||b||i?"read-only":jt,re=C.useRef(null),lt=C.useRef(null),Gt=C.useRef(null),ea=C.useRef(null),{ref:ci}=$Z([T,ae,ge]),Le=C.useRef(null);C.useLayoutEffect(()=>{const oe=Le.current;if(!oe)return;oe.style.height="auto";const Ie=k?gY:fY;oe.scrollHeight>0&&(oe.style.height=`${Math.min(oe.scrollHeight,Ie)}px`)},[ke,k,v]);const[ct,Kt]=C.useState(0),Ht=C.useMemo(()=>{const oe=ke.trimStart();if(!oe.startsWith("/"))return[];if(/\s/.test(oe))return[];const Ie=oe.toLowerCase();return bk.filter(Ye=>(!(r||b)||Ye.command!=="/run-sweep")&&(!b||Ye.action!=="new")&&(!i||gg.some(Qt=>Qt.prompt===Ye.prompt))&&(Ye.command.startsWith(Ie)||Ye.label.toLowerCase().includes(Ie.slice(1))))},[ke,r,b,i]);C.useEffect(()=>{Kt(oe=>Ht.length===0?0:Math.min(oe,Ht.length-1))},[Ht.length]);const Rn=yt({...NQ({client:J,path:{name:e}}),enabled:!b&&!i,staleTime:6e4}),Lt=C.useMemo(()=>{const oe=Rn.data?.providers??[];if(Ge){const Ye=oe.find(Qt=>Qt.id===Ge&&Qt.configured);if(Ye)return Ye}const Ie=Rn.data?.defaultProvider;return Ie?oe.find(Ye=>Ye.id===Ie)??null:null},[Ge,Rn.data]),ui=b||i||Lt!==null;yt({...yk(e),enabled:i&&v}),C.useEffect(()=>{if(!Rn.data||!Ge)return;Rn.data.providers.find(Ie=>Ie.id===Ge&&Ie.configured)||(it(null),xk(fd(e)))},[Rn.data,Ge,e]);const Ps=C.useCallback(oe=>{it(oe),oe?mY(fd(e),oe):xk(fd(e))},[e]);C.useEffect(()=>{if(!v)return;const oe=Ie=>{Ie.key==="Escape"&&(L?Z(!1):k?j(!1):w(!1))};return window.addEventListener("keydown",oe),()=>window.removeEventListener("keydown",oe)},[v,k,L]),C.useEffect(()=>{if(!v||!ui||i)return;let oe=!1;ve(null);const Ie=()=>{oe||O||Pe.current||Cf(e).then(st=>{oe||Pe.current||(Xe(st.isStreaming??!1),E(st.conversationId??null),!oe&&!st.isStreaming&&(lt.current===null||st.updatedAt&&st.updatedAt!==lt.current.previous)&&(N(st.messages),re.current=st.updatedAt,lt.current=null))}).catch(st=>{oe||ve(zi(st))})};Ie();const Qt=window.setInterval(Ie,15e3);return()=>{oe=!0,window.clearInterval(Qt)}},[v,e,O,ui,B,i]),C.useEffect(()=>(De.current=!0,()=>{De.current=!1,ea.current?.abort()}),[e]);async function Un(oe,Ie=n){const Ye=oe.trim();if(!Ye||L||O||B||Pe.current||we||!ui)return;if(i){await di(Ye);return}if(r&&/^\/run-sweep(?:\s|$)/i.test(Ye)){ve(hg);return}ve(null),ce(null),me({prompt:Ye,context:Ie}),$e(""),ne(!0),_e(""),Gt.current=null,Se([]),lt.current={previous:re.current};const Qt={role:"user",content:Ye,timestamp:Date.now(),aeroContext:Ie};N(et=>[...et,Qt]);const st=new AbortController;ea.current=st;try{await rY({project:e,prompt:Ye,conversationId:P,provider:Ge??void 0,scope:He,context:Ie,signal:st.signal,onEvent:qs});const et=await Cf(e);De.current&&!et.isStreaming&&(E(et.conversationId??null),N(et.messages),re.current=et.updatedAt,lt.current=null)}catch(et){if(!De.current)return;b&&(lt.current=null);const Jt=Gt.current;Jt&&Ad(Jt).trim()&&N(Za=>[...Za,Jt]),st.signal.aborted?ce("Stopped. Partial response preserved. An action already dispatched may still finish."):ve(zi(et))}finally{De.current&&(ne(!1),_e(""),Se(et=>et.map(Jt=>Jt.endedAt===void 0?{...Jt,interrupted:!0}:Jt))),ea.current=null}}async function di(oe){const Ie=bk.find(st=>st.command===oe.toLowerCase())?.prompt??oe,Ye=gg.find(st=>st.prompt===Ie)?.id;if(!Ye){ve(null),me(null),ce(cY);return}ve(null),ce(null),me({prompt:Ie}),$e(""),ne(!0),_e(""),Gt.current=null,Se([]),N(st=>[...st,{role:"user",content:Ie,timestamp:Date.now()}]);const Qt=new AbortController;ea.current=Qt;try{const st=await f.ensureQueryData(yk(e));if(Qt.signal.aborted)throw new DOMException("Preview stopped","AbortError");const et=st.starters.find(Jt=>Jt.id===Ye);if(!et)throw new Error("This demo has no sample answer for that starting point.");await aY({starter:et,signal:Qt.signal,onEvent:qs,reducedMotion:WZ()})}catch(st){if(!De.current)return;const et=Gt.current;et&&Ad(et).trim()&&N(Jt=>[...Jt,et]),Qt.signal.aborted?ce(uY):ve(zi(st))}finally{De.current&&(ne(!1),_e(""),Se(st=>st.map(et=>et.endedAt===void 0?{...et,interrupted:!0}:et))),ea.current=null}}function qs(oe){if(De.current)switch(oe.type){case"message_update":oe.message.role==="assistant"&&(Gt.current=oe.message),_e(Ad(oe.message));break;case"message_end":if(oe.message.role!=="user"){const Ie=oe.message;N(Ye=>[...Ye,Ie])}oe.message.role==="assistant"&&(Gt.current=null,_e(""),oe.message.errorMessage&&ve(oe.message.errorMessage));break;case"aero_turn_status":oe.status?.reason==="tool-limit"?ce("Tool-call limit reached. Partial response preserved."):oe.status?.reason==="time-limit"?ce("Time limit reached. Partial response preserved."):oe.status?.reason==="completed"&&me(null);break;case"tool_execution_start":Se(Ie=>[...Ie,{id:oe.toolCallId,name:oe.toolName,label:oe.label,args:oe.args,startedAt:Date.now()}]);break;case"tool_execution_end":Se(Ie=>Ie.map(Ye=>Ye.id===oe.toolCallId?{...Ye,endedAt:Date.now(),isError:oe.isError,result:oe.result}:Ye));break;case"error":ve(oe.message);break}}async function Vi(oe,Ie=!1){if(!(O||we||Pe.current)){Pe.current=!0,K(!0),ve(null);try{await oe();const Ye=await Cf(e);if(!De.current)return;lt.current=null,re.current=Ye.updatedAt,E(Ye.conversationId??null),N(Ye.messages),Se([]),_e(""),ce(null),me(null),Ue(null),Z(Ie),ee(Ie?await Gw(e):null),Le.current?.focus()}catch(Ye){De.current&&ve(zi(Ye))}finally{Pe.current=!1,De.current&&K(!1)}}}async function $i(){if(i){if(O)return;N([]),Se([]),_e(""),ve(null),ce(null),me(null),Le.current?.focus();return}await Vi(()=>b?oY(e):aK(e,crypto.randomUUID()))}async function Ms(oe=!1){if(!(Pe.current||q.current)){q.current=!0,X(!0),Z(!0),ve(null);try{const Ie=await Gw(e,{offset:oe?Y?.nextOffset??0:0});De.current&&ee(Ye=>oe&&Ye?{...Ie,conversations:[...Ye.conversations,...Ie.conversations]}:Ie)}catch(Ie){De.current&&ve(zi(Ie))}finally{q.current=!1,De.current&&X(!1)}}}const fn=T.length===0,At=!(b||i);if(At&&Rn.isPending)return null;if(At&&Rn.isError)return l.jsx("div",{className:"pointer-events-none fixed inset-x-0 bottom-0 z-40 flex justify-center p-3",children:l.jsxs("div",{role:"status",className:"flex w-full max-w-3xl flex-wrap items-center gap-x-2 gap-y-1 rounded-lg border border-base bg-bg/95 px-4 py-2 text-sm shadow-lg",children:[l.jsx(ed,{className:"h-4 w-4 text-muted","aria-hidden":"true"}),l.jsx("span",{className:"font-medium text-strong",children:"Aero could not check provider availability."}),l.jsx(ue,{variant:"outline",size:"sm",className:"pointer-events-auto ml-auto",onClick:()=>{Rn.refetch()},children:"Try again"})]})});const gn=Lt&&!Lt.configured?Lt:null;if(At&&(!Lt||gn))return l.jsx("div",{className:"pointer-events-none fixed inset-x-0 bottom-0 z-40 flex justify-center p-3",children:l.jsxs("div",{role:"status",className:"flex w-full max-w-3xl flex-wrap items-center gap-x-2 gap-y-1 rounded-lg border border-base bg-bg/95 px-4 py-2 text-sm shadow-lg",children:[l.jsx(ed,{className:"h-4 w-4 text-muted","aria-hidden":"true"}),l.jsxs("span",{className:"flex items-center gap-1.5 font-medium text-strong",children:[gn?`Aero is set to ${gn.label.replace(/\s+\(.+\)$/,"")}, which has no API key.`:"Aero needs an answer-engine provider.",l.jsx(Ua,{text:gn?`Set ${CC(gn.id)} on the server, or providers.${gn.id}.apiKey in its config.yaml.`:"Aero is the built-in AEO analyst. It reads your Canonry data with you once a provider is connected."})]}),gn?null:u?l.jsx(ue,{asChild:!0,variant:"outline",size:"sm",className:"pointer-events-auto ml-auto",children:l.jsx(We,{to:"/settings",children:"Open Settings"})}):l.jsx("span",{className:"ml-auto text-secondary",children:"Ask an administrator to configure one."})]})});const Sn=v&&k?"pointer-events-auto fixed inset-0 z-40 flex items-stretch justify-center bg-bg/70 p-4 sm:p-8 backdrop-blur-sm":"pointer-events-none fixed inset-x-0 bottom-0 z-40 flex justify-center p-3",Bs=k?"pointer-events-auto flex h-full w-full max-w-5xl flex-col overflow-hidden rounded-2xl border border-mono-800/80 bg-bg/95 shadow-2xl":"pointer-events-auto w-full max-w-3xl",fa=k?"flex-1 overflow-y-auto px-6 py-5 text-sm text-strong":"max-h-[40vh] min-h-[120px] overflow-y-auto px-4 py-3 text-sm text-strong";return l.jsx("div",{className:Sn,onClick:oe=>{k&&oe.target===oe.currentTarget&&j(!1)},children:l.jsx("div",{className:Bs,children:v?l.jsxs("div",{"data-aero-panel":!0,className:k?"flex h-full flex-col":"flex flex-col overflow-hidden rounded-2xl border border-mono-800/80 bg-bg/95 shadow-xl backdrop-blur",children:[l.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-mono-800/70 px-4 py-2.5",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(ed,{className:"h-4 w-4 text-positive-400","aria-hidden":"true"}),l.jsx("span",{className:"text-sm font-medium text-heading",children:"Aero"}),l.jsx("span",{className:"text-[10px] uppercase tracking-wider text-muted",children:O||we?"working…":e})]}),l.jsxs("div",{className:"flex items-center gap-1",children:[!r&&!b&&!i&&l.jsx(hY,{providers:Rn.data?.providers??[],active:Lt,override:Ge,onPick:Ps,disabled:O}),l.jsx("button",{type:"button",onClick:()=>j(oe=>!oe),className:"rounded-md p-1.5 text-muted transition hover:bg-surface-inset hover:text-strong","aria-label":k?"Collapse":"Expand",title:k?"Collapse":"Expand",children:k?l.jsx(n5,{className:"h-3.5 w-3.5","aria-hidden":"true"}):l.jsx(a5,{className:"h-3.5 w-3.5","aria-hidden":"true"})}),l.jsx("button",{type:"button",onClick:()=>{j(!1),w(!1)},className:"rounded-md p-1.5 text-muted transition hover:bg-surface-inset hover:text-strong","aria-label":"Close Aero",children:l.jsx($r,{className:"h-4 w-4","aria-hidden":"true"})})]})]}),l.jsxs("div",{className:"flex flex-wrap items-center gap-2 border-b border-subtle px-4 py-2",children:[l.jsxs(ue,{variant:"outline",size:"sm",disabled:O||we||B,onClick:pn($i),title:b||i?"Clear this conversation and start fresh.":"Save this conversation and start fresh. Shared project notes are kept.",children:[l.jsx(Ef,{className:"h-3.5 w-3.5","aria-hidden":"true"})," New conversation"]}),!b&&!i&&l.jsxs(ue,{variant:"ghost",size:"sm","aria-expanded":L,"aria-controls":"aero-history",disabled:B,onClick:()=>{L?Z(!1):Ms()},children:[l.jsx(Hk,{className:"h-3.5 w-3.5","aria-hidden":"true"})," History"]})]}),L?l.jsxs("div",{id:"aero-history",className:fa,"aria-label":"Conversation history",children:[l.jsxs("h3",{className:"mb-2 text-sm font-medium text-heading",children:["Conversations in ",e]}),Y?Y.conversations.length===0?l.jsx("p",{className:"text-sm text-secondary",children:"No saved conversations yet. Your conversations will appear here."}):l.jsx("ul",{className:"divide-y divide-default",children:Y.conversations.map(oe=>l.jsxs("li",{className:"py-2",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsxs("button",{className:"min-w-0 flex-1 rounded-md px-2 py-1 text-left hover:bg-surface-hover focus-visible:ring-2 focus-visible:ring-positive-500",disabled:O||we||B,onClick:()=>{oe.active?Z(!1):Vi(()=>iK(e,oe.id))},children:[l.jsx("span",{className:"block truncate text-sm text-heading",children:oe.title}),l.jsxs("span",{className:"text-xs text-secondary",children:[oe.active?"Current · ":"",new Date(oe.updatedAt).toLocaleString()]})]}),l.jsx(ue,{variant:"ghost",size:"sm",disabled:O||we||B,"aria-label":`Delete conversation: ${oe.title}`,onClick:()=>Ue(oe.id),children:"Delete"})]}),nt===oe.id&&l.jsxs("div",{role:"group","aria-label":"Confirm conversation deletion",className:"mt-2 rounded-md border border-default p-3 text-sm text-secondary",children:[l.jsx("p",{children:"Delete this conversation permanently? Shared project notes will be kept."}),l.jsxs("div",{className:"mt-2 flex gap-2",children:[l.jsx(ue,{variant:"destructive",size:"sm",disabled:B,onClick:()=>{Vi(async()=>{await sK(e,oe.id)},!0)},children:"Delete conversation"}),l.jsx(ue,{variant:"ghost",size:"sm",disabled:B,onClick:()=>Ue(null),children:"Cancel"})]})]})]},oe.id))}):l.jsx("p",{className:"text-sm text-secondary",children:H?"Loading history…":"History could not be loaded. Close and reopen History to retry."}),Y?.nextOffset!=null&&l.jsx(ue,{variant:"ghost",size:"sm",disabled:H,onClick:()=>{Ms(!0)},children:H?"Loading…":"Load more"})]}):l.jsxs("div",{ref:ci,className:fa,children:[fn&&!O&&l.jsxs("div",{className:"flex flex-col gap-3 py-2",children:[l.jsx("p",{className:"text-sm text-secondary",children:i?l.jsxs(l.Fragment,{children:["See how Aero answers about ",l.jsx("span",{className:"text-strong",children:e}),". Choose a starting point."]}):l.jsxs(l.Fragment,{children:["Ask about ",l.jsx("span",{className:"text-strong",children:e})," or choose a starting point."]})}),l.jsx(wk,{onPick:oe=>{Un(oe)}})]}),xY(T,e,Ge,He,ge,O,!b&&!i),O&&ae&&l.jsxs("div",{className:"mt-3",children:[l.jsx("div",{className:"mb-0.5 text-[10px] uppercase tracking-wider text-positive-400",children:"Aero"}),l.jsx(NC,{content:ae})]}),O&&!ae&&ge.every(oe=>oe.endedAt!==void 0)&&l.jsx(AY,{}),i&&!fn&&!O&&l.jsxs("div",{className:"mt-4 flex flex-col gap-2 border-t border-subtle pt-3",children:[l.jsx("p",{className:"text-xs text-secondary",children:"Try another starting point."}),l.jsx(wk,{onPick:oe=>{Un(oe)}})]})]}),(Be||le)&&l.jsxs("div",{role:Be?"alert":"status",className:"mx-3 my-2 flex flex-wrap items-center gap-2 rounded-md border border-base bg-surface px-3 py-2 text-sm text-secondary",children:[l.jsx("span",{className:"flex-1",children:Be??le}),Q&&!O&&l.jsx(ue,{variant:"outline",size:"sm",onClick:()=>{He==="all"?($e(Q.prompt),Le.current?.focus()):Un(Q.prompt,Q.context)},children:He==="all"?"Review prompt":"Retry"})]}),i&&l.jsxs("p",{className:"border-t border-subtle px-4 py-2 text-xs text-secondary",children:["Sample answers on demo data."," ",l.jsxs("a",{href:lY,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-0.5 text-positive-400 underline decoration-positive-700 hover:decoration-positive-400",children:["Aero answers from your own Canonry data.",l.jsx(Gk,{className:"h-3 w-3","aria-hidden":"true"}),l.jsx("span",{className:"sr-only",children:" (opens in a new tab)"})]})]}),l.jsxs("div",{className:"relative",children:[!L&&Ht.length>0&&l.jsx(bY,{title:i?"Starting points":"Commands",matches:Ht,selectedIndex:ct,onHover:Kt,onPick:oe=>{$e(""),Le.current?.focus(),oe.action==="new"?$i():Un(oe.prompt)}}),l.jsxs("form",{className:"flex items-end gap-2 border-t border-mono-800/70 bg-bg/80 px-3 py-2.5",onSubmit:oe=>{if(oe.preventDefault(),Ht.length>0){const Ie=Ht[ct];$e(""),Ie.action==="new"?$i():Un(Ie.prompt);return}Un(ke)},children:[l.jsx("textarea",{ref:Le,value:ke,onChange:oe=>$e(oe.target.value),onKeyDown:oe=>{if(Ht.length>0){if(oe.key==="ArrowDown"){oe.preventDefault(),Kt(Ie=>(Ie+1)%Ht.length);return}if(oe.key==="ArrowUp"){oe.preventDefault(),Kt(Ie=>(Ie-1+Ht.length)%Ht.length);return}if(oe.key==="Tab"){oe.preventDefault();const Ie=Ht[ct];$e(`${Ie.command} `);return}if(oe.key==="Escape"){oe.preventDefault(),$e("");return}}if(oe.key==="Enter"&&!oe.shiftKey)if(oe.preventDefault(),Ht.length>0){const Ie=Ht[ct];$e(""),Ie.action==="new"?$i():Un(Ie.prompt)}else Un(ke)},disabled:L||B,placeholder:L?"Open a conversation to continue…":i?"Type / for a starting point":"Ask Aero, or / for commands…","aria-label":"Message Aero",rows:k?3:1,className:"flex-1 resize-none overflow-y-auto bg-transparent text-sm text-heading placeholder:text-mono-600 focus:outline-none disabled:opacity-60"}),O?l.jsxs(ue,{type:"button",variant:"outline",size:"sm",onClick:()=>ea.current?.abort(),"aria-label":"Stop Aero",children:[l.jsx(i5,{className:"h-3.5 w-3.5","aria-hidden":"true"})," Stop"]}):l.jsx(ue,{type:"submit",size:"sm",disabled:!ke.trim()||L||B||we,"aria-label":"Send",children:l.jsx(s5,{className:"h-4 w-4","aria-hidden":"true"})})]})]})]}):l.jsx("button",{type:"button",onClick:()=>w(!0),className:"flex w-full items-center justify-between rounded-lg border border-mono-800/80 bg-bg/95 px-4 py-2 text-left text-sm text-secondary shadow-lg transition hover:border-strong hover:bg-bg-elevated/90 hover:text-strong",children:l.jsxs("span",{className:"flex items-center gap-2",children:[l.jsx(ed,{className:"h-4 w-4 text-positive-400","aria-hidden":"true"}),"Ask Aero about ",e,"…"]})})})})}function hY({providers:e,active:n,override:i,onPick:r,disabled:u}){const[h,f]=C.useState(!1),b=C.useRef(null);if(C.useEffect(()=>{if(!h)return;const w=j=>{b.current?.contains(j.target)||f(!1)},k=j=>{j.key==="Escape"&&f(!1)};return window.addEventListener("mousedown",w),window.addEventListener("keydown",k),()=>{window.removeEventListener("mousedown",w),window.removeEventListener("keydown",k)}},[h]),e.length===0)return null;const v=n?.label.replace(/\s+\(.+\)$/,"")??"No provider";return l.jsxs("div",{ref:b,className:"relative",children:[l.jsxs("button",{type:"button",onClick:()=>f(w=>!w),disabled:u,className:"flex items-center gap-1 rounded-md px-2 py-1 text-sm text-secondary transition hover:bg-surface-inset hover:text-strong disabled:opacity-50","aria-label":"Switch agent model","aria-haspopup":"listbox","aria-expanded":h,title:n?`${n.label} · ${n.defaultModel}`:"Pick a provider",children:[l.jsx("span",{className:"font-medium text-strong",children:v}),l.jsx(Jd,{className:"h-3 w-3","aria-hidden":"true"})]}),h&&l.jsxs("div",{role:"listbox",className:"absolute right-0 top-full z-50 mt-1 w-64 overflow-hidden rounded-lg border border-base bg-bg shadow-xl",children:[l.jsx("div",{className:"border-b border-default px-3 py-2 text-sm font-medium text-secondary",children:"Answer engine"}),l.jsx("ul",{className:"max-h-72 overflow-y-auto py-1",children:e.map(w=>{const k=n?.id===w.id,j=i===w.id;return l.jsx("li",{children:l.jsxs("button",{type:"button",role:"option","aria-selected":k,disabled:!w.configured,onClick:()=>{w.configured&&(r(j?null:w.id),f(!1))},className:"flex w-full items-center gap-2 px-3 py-2.5 text-left text-sm transition enabled:hover:bg-bg-elevated disabled:cursor-not-allowed disabled:opacity-60",title:w.configured?w.defaultModel:`Add ${CC(w.id)} in Settings or your environment`,children:[l.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center",children:k?l.jsx(Wd,{className:"h-3 w-3 text-positive-400","aria-hidden":"true"}):null}),l.jsx("span",{className:"min-w-0 flex-1 truncate font-medium text-heading",children:w.label.replace(/\s+\(.+\)$/,"")}),j&&l.jsx("span",{className:"rounded-md border border-positive-800/60 bg-positive-950/60 px-2 py-0.5 text-[11px] text-positive",children:"Selected"}),!w.configured&&l.jsx("span",{className:"rounded-md border border-base px-2 py-0.5 text-[11px] text-secondary",children:"Needs setup"})]})},w.id)})}),i&&l.jsx("button",{type:"button",onClick:()=>{r(null),f(!1)},className:"w-full border-t border-default px-3 py-2 text-left text-[11px] text-secondary transition hover:bg-bg-elevated hover:text-heading",children:"Reset to default"})]})]})}const fY=144,gY=288,Nf=288,yY=8;function bY({title:e,matches:n,selectedIndex:i,onHover:r,onPick:u}){const h=C.useRef(null),f=C.useRef(null),b=C.useRef(null),[v,w]=C.useState(Nf);return C.useLayoutEffect(()=>{const k=h.current,j=k?.closest("[data-aero-panel]"),T=k?.parentElement;if(!k||!j||!T)return;const N=T.getBoundingClientRect().top-j.getBoundingClientRect().top-yY*2-(f.current?.getBoundingClientRect().height??0);w(N>0?Math.min(Nf,Math.floor(N)):Nf)},[n.length]),C.useEffect(()=>{b.current?.querySelector('[aria-selected="true"]')?.scrollIntoView?.({block:"nearest"})},[i]),l.jsxs("div",{ref:h,className:"absolute inset-x-3 bottom-full mb-2 overflow-hidden rounded-lg border border-base bg-bg/98 shadow-2xl",children:[l.jsx("div",{ref:f,className:"border-b border-default px-3 py-1.5 text-[10px] uppercase tracking-wider text-muted",children:e}),l.jsx("ul",{ref:b,role:"listbox",className:"overflow-y-auto py-1",style:{maxHeight:v},children:n.map((k,j)=>{const T=j===i;return l.jsx("li",{children:l.jsxs("button",{type:"button",role:"option","aria-selected":T,onMouseEnter:()=>r(j),onClick:()=>u(k),className:`flex w-full items-center gap-3 px-3 py-2 text-left text-sm transition ${T?"bg-bg-elevated text-heading":"text-neutral hover:bg-bg-elevated/60"}`,children:[l.jsx("span",{className:"font-medium",children:k.label}),l.jsx("span",{className:"ml-auto font-mono text-[11px] text-secondary",children:k.command})]})},k.command)})})]})}function wk({onPick:e}){return l.jsx("div",{className:"flex flex-wrap gap-1.5",children:gg.map(n=>l.jsx("button",{type:"button",onClick:()=>e(n.prompt),className:"rounded-md border border-base bg-bg-elevated/70 px-3 py-1.5 text-sm text-neutral transition hover:border-strong hover:bg-mono-800/70 hover:text-heading",children:n.label},n.label))})}function CC(e){switch(e){case"claude":return"ANTHROPIC_API_KEY";case"openai":return"OPENAI_API_KEY";case"gemini":return"GOOGLE_API_KEY";case"zai":return"ZAI_API_KEY";case"deepinfra":return"DEEPINFRA_TOKEN"}}function vY(e,n){const i=e.timestamp??0;return`${e.role}:${i}:${n}`}function xY(e,n,i,r,u,h,f=!0){const b=[];for(let v=0;v<e.length;v++){const w=e[v],k=vY(w,v);if(w.role==="user"){const j=typeof w.content=="string"?w.content:JSON.stringify(w.content);if(j.startsWith("[system]"))continue;b.push(l.jsx(wY,{text:j,projectName:n,providerOverride:i,scope:r,context:w.aeroContext,cliCopy:f},k));continue}if(w.role==="assistant"){const j=new Map;let T=v+1;for(;T<e.length&&e[T].role==="toolResult";){const E=e[T];j.set(E.toolCallId,E),T++}const N=SY(w,j).map(E=>{const q=u.find(X=>X.id===E.id),H={...E,...q};return{...H,interrupted:H.endedAt===void 0&&(!h||H.interrupted)}}),P=Ad(w);b.push(l.jsxs(C.Fragment,{children:[P.trim()&&l.jsxs("div",{className:"mt-3",children:[l.jsx("div",{className:"mb-0.5 text-[10px] uppercase tracking-wider text-positive-400",children:"Aero"}),l.jsx(NC,{content:P})]}),N.length>0&&l.jsx("div",{className:"mt-3 space-y-1.5",children:N.map(E=>l.jsx(jY,{trail:E},E.id))})]},k)),v=T-1;continue}}return b}function wY({text:e,projectName:n,providerOverride:i,scope:r,context:u,cliCopy:h=!0}){const[f,b]=C.useState(!1),v=C.useMemo(()=>kY(n,e,i,r,u),[n,e,i,r,u]);async function w(){try{await navigator.clipboard.writeText(v),b(!0),window.setTimeout(()=>b(!1),1500)}catch{}}return l.jsxs("div",{className:"group relative mt-3 rounded-md bg-bg-elevated/60 px-3 py-2 text-strong",children:[l.jsxs("div",{className:"flex items-center justify-between gap-2",children:[l.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted",children:"You"}),h&&l.jsx("button",{type:"button",onClick:pn(w),className:"inline-flex items-center gap-1 rounded border border-mono-800/70 bg-bg/60 px-1.5 py-0.5 text-[10px] text-secondary opacity-0 transition hover:border-strong hover:text-heading group-hover:opacity-100 focus:opacity-100","aria-label":"Copy as CLI command",title:v,children:f?l.jsxs(l.Fragment,{children:[l.jsx(Wd,{className:"h-2.5 w-2.5 text-positive-400","aria-hidden":"true"}),"Copied"]}):l.jsxs(l.Fragment,{children:[l.jsx(Cg,{className:"h-2.5 w-2.5","aria-hidden":"true"}),"Copy as CLI"]})})]}),l.jsx("div",{className:"whitespace-pre-wrap",children:e})]})}function kY(e,n,i,r,u){const h=["canonry","agent","ask",vf(e),vf(n)];return i&&h.push("--provider",i),r==="read-only"&&h.push("--scope","read-only"),u&&h.push("--context",vf(JSON.stringify(u))),h.join(" ")}function SY(e,n){const i=[];for(const r of e.content){if(r.type!=="toolCall")continue;const u=r,h=n.get(u.id);i.push({id:u.id,name:u.name,args:u.arguments,label:h?.aeroToolLabel,durationMs:h?.aeroDurationMs,endedAt:h?.timestamp,isError:h?.isError,result:h?.content})}return i}function jY({trail:e}){const[n,i]=C.useState(!1),r=e.endedAt===void 0&&!e.interrupted,u=!r&&e.isError===!0,h=e.durationMs??(e.endedAt!=null&&e.startedAt!=null?e.endedAt-e.startedAt:null),f=h==null||h<0?null:h<1e3?`${h}ms`:`${(h/1e3).toFixed(1)}s`,b=u?"border-negative-800/50":r?"border-positive-800/50":"border-mono-800/70",v=u?"bg-negative-950/20":r?"bg-positive-950/20":"bg-surface-hover";return l.jsxs("div",{className:`rounded-md border ${b} ${v}`,children:[l.jsxs("button",{type:"button",onClick:()=>i(w=>!w),className:"flex w-full items-center gap-2 px-2.5 py-1.5 text-left","aria-expanded":n,children:[l.jsx("span",{className:"flex h-3.5 w-3.5 shrink-0 items-center justify-center",children:r?l.jsx(Rr,{className:"h-3 w-3 animate-spin text-positive-400","aria-hidden":"true"}):u?l.jsx(Qk,{className:"h-3 w-3 text-negative-400","aria-hidden":"true"}):l.jsx(o5,{className:"h-3 w-3 text-muted","aria-hidden":"true"})}),l.jsx("span",{className:"text-sm font-medium text-heading",children:e.label??e.name.replace(/^(?:canonry|aero)_/,"").replace(/_/g," ")}),l.jsxs("span",{className:"ml-auto flex items-center gap-2 text-[10px] text-muted",children:[r?l.jsx("span",{className:"text-positive-400",children:"running…"}):l.jsxs(l.Fragment,{children:[l.jsx("span",{children:e.interrupted?"interrupted":u?"failed":"done"}),f&&l.jsx("span",{children:f})]}),l.jsx(Ng,{className:`h-3 w-3 transition-transform ${n?"rotate-90":""}`,"aria-hidden":"true"})]})]}),n&&l.jsxs("div",{className:"border-t border-default px-2.5 py-2 text-[11px] text-secondary",children:[l.jsx("div",{className:"mb-2 text-xs text-secondary",children:e.name}),l.jsx("div",{className:"mb-1 text-xs text-secondary",children:"Inputs"}),l.jsx("pre",{className:"mb-2 overflow-x-auto whitespace-pre-wrap break-all text-xs text-neutral",children:kk(e.args)}),!r&&e.result!==void 0&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"mb-1 text-[9px] uppercase tracking-wider text-faint",children:u?"Error":"Result"}),l.jsx("pre",{className:"overflow-x-auto whitespace-pre-wrap break-all text-xs text-neutral",children:kk(e.result)})]})]})]})}function kk(e){try{const n=typeof e=="string"?e:JSON.stringify(e,null,2);return n.length>2e3?`${n.slice(0,2e3)}
63
+ `)}}if(w?.aborted)throw new DOMException("Turn stopped","AbortError");if(!N)throw new Error("Connection ended before Aero finished. Review the partial answer before retrying.")}finally{w?.removeEventListener("abort",H);try{P.releaseLock()}catch{}}}function Ad(e){return!e||e.role!=="assistant"?"":e.content.filter(n=>n.type==="text").map(n=>n.text).join("")}const gg=[{id:"status",label:"Status",prompt:"Give me a quick status: the latest sweep, which engines answered, and anything that needs attention."},{id:"changes",label:"What changed",prompt:"Compare the latest complete sweep with the one before it. Lead with mentions, then citations. Keep branded and non-brand queries separate if the project splits them, and say which changes are bigger than normal run-to-run noise."},{id:"gaps",label:"Biggest gaps",prompt:"Which tracked queries does no engine mention us on, and who gets named instead? Group them by topic or market."},{id:"insights",label:"Top insights",prompt:"Walk me through the 3 most severe active insights and what to do about each."}],lY="https://canonry.ai",cY="This demo plays sample answers only. Pick a starting point, or type / to choose one.",uY="Stopped. The sample answer so far is kept.";function yk(e){return{queryKey:["aero-preview",e],queryFn:()=>sY(e),staleTime:1/0,gcTime:1/0}}const bk=[{command:"/status",label:"Status",prompt:"Give me a quick status: the latest sweep, which engines answered, and anything that needs attention."},{command:"/changes",label:"What changed",prompt:"Compare the latest complete sweep with the one before it. Lead with mentions, then citations. Keep branded and non-brand queries separate if the project splits them, and say which changes are bigger than normal run-to-run noise."},{command:"/gaps",label:"Biggest gaps",prompt:"Which tracked queries does no engine mention us on, and who gets named instead? Group them by topic or market."},{command:"/insights",label:"Top insights",prompt:"Walk me through the 3 most severe active insights and what to do about each."},{command:"/last-run",label:"Last run",prompt:"Summarize the latest run for this project: which engines answered, what moved in mentions and citations, and anything that failed."},{command:"/run-sweep",label:"Run sweep now",prompt:"Run a new answer-visibility sweep for this project now and tell me when it lands."},{command:"/queries",label:"Queries",prompt:"List the tracked queries for this project and flag any that are obvious duplicates or underperformers."},{command:"/competitors",label:"Competitors",prompt:"Which competitors do engines name most often on queries where we are not named, and on which engines?"},{command:"/new",label:"New conversation (save current)",action:"new"}],fd=e=>`canonry:aero:provider:${e}`,dY=e=>`canonry:aero:scope:${e}`;function vk(e){if(typeof window>"u")return null;try{return window.localStorage.getItem(e)}catch{return null}}function mY(e,n){if(!(typeof window>"u"))try{window.localStorage.setItem(e,n)}catch{}}function xk(e){if(!(typeof window>"u"))try{window.localStorage.removeItem(e)}catch{}}function pY({projectName:e,context:n,preview:i=W0()}){const r=fo(),{canWrite:u,account:h}=pa(),f=Jn(),b=h?.role==="viewer",[v,w]=C.useState(!1),[k,j]=C.useState(!1),[T,N]=C.useState([]),[P,E]=C.useState(void 0),q=C.useRef(!1),[H,X]=C.useState(!1),[L,Z]=C.useState(!1),[Y,ee]=C.useState(null),[B,K]=C.useState(!1),[we,Xe]=C.useState(!1),[nt,Ue]=C.useState(null),Pe=C.useRef(!1),[ke,$e]=C.useState(""),[O,ne]=C.useState(!1),[ge,Se]=C.useState([]),[ae,_e]=C.useState(""),[Be,ve]=C.useState(null),[le,ce]=C.useState(null),[Q,me]=C.useState(null),De=C.useRef(!0),[je,it]=C.useState(()=>vk(fd(e))??null),Ge=r||b||i?null:je,[jt]=C.useState(()=>vk(dY(e))==="all"?"all":"read-only"),He=r||b||i?"read-only":jt,re=C.useRef(null),lt=C.useRef(null),Gt=C.useRef(null),ea=C.useRef(null),{ref:ci}=$Z([T,ae,ge]),Le=C.useRef(null);C.useLayoutEffect(()=>{const oe=Le.current;if(!oe)return;oe.style.height="auto";const Ie=k?gY:fY;oe.scrollHeight>0&&(oe.style.height=`${Math.min(oe.scrollHeight,Ie)}px`)},[ke,k,v]);const[ct,Kt]=C.useState(0),Ht=C.useMemo(()=>{const oe=ke.trimStart();if(!oe.startsWith("/"))return[];if(/\s/.test(oe))return[];const Ie=oe.toLowerCase();return bk.filter(Ye=>(!(r||b)||Ye.command!=="/run-sweep")&&(!b||Ye.action!=="new")&&(!i||gg.some(Qt=>Qt.prompt===Ye.prompt))&&(Ye.command.startsWith(Ie)||Ye.label.toLowerCase().includes(Ie.slice(1))))},[ke,r,b,i]);C.useEffect(()=>{Kt(oe=>Ht.length===0?0:Math.min(oe,Ht.length-1))},[Ht.length]);const Rn=yt({...NQ({client:J,path:{name:e}}),enabled:!b&&!i,staleTime:6e4}),Lt=C.useMemo(()=>{const oe=Rn.data?.providers??[];if(Ge){const Ye=oe.find(Qt=>Qt.id===Ge&&Qt.configured);if(Ye)return Ye}const Ie=Rn.data?.defaultProvider;return Ie?oe.find(Ye=>Ye.id===Ie)??null:null},[Ge,Rn.data]),ui=b||i||Lt!==null;yt({...yk(e),enabled:i&&v}),C.useEffect(()=>{if(!Rn.data||!Ge)return;Rn.data.providers.find(Ie=>Ie.id===Ge&&Ie.configured)||(it(null),xk(fd(e)))},[Rn.data,Ge,e]);const Ps=C.useCallback(oe=>{it(oe),oe?mY(fd(e),oe):xk(fd(e))},[e]);C.useEffect(()=>{if(!v)return;const oe=Ie=>{Ie.key==="Escape"&&(L?Z(!1):k?j(!1):w(!1))};return window.addEventListener("keydown",oe),()=>window.removeEventListener("keydown",oe)},[v,k,L]),C.useEffect(()=>{if(!v||!ui||i)return;let oe=!1;ve(null);const Ie=()=>{oe||O||Pe.current||Cf(e).then(st=>{oe||Pe.current||(Xe(st.isStreaming??!1),E(st.conversationId??null),!oe&&!st.isStreaming&&(lt.current===null||st.updatedAt&&st.updatedAt!==lt.current.previous)&&(N(st.messages),re.current=st.updatedAt,lt.current=null))}).catch(st=>{oe||ve(zi(st))})};Ie();const Qt=window.setInterval(Ie,15e3);return()=>{oe=!0,window.clearInterval(Qt)}},[v,e,O,ui,B,i]),C.useEffect(()=>(De.current=!0,()=>{De.current=!1,ea.current?.abort()}),[e]);async function Un(oe,Ie=n){const Ye=oe.trim();if(!Ye||L||O||B||Pe.current||we||!ui)return;if(i){await di(Ye);return}if(r&&/^\/run-sweep(?:\s|$)/i.test(Ye)){ve(hg);return}ve(null),ce(null),me({prompt:Ye,context:Ie}),$e(""),ne(!0),_e(""),Gt.current=null,Se([]),lt.current={previous:re.current};const Qt={role:"user",content:Ye,timestamp:Date.now(),aeroContext:Ie};N(et=>[...et,Qt]);const st=new AbortController;ea.current=st;try{await rY({project:e,prompt:Ye,conversationId:P,provider:Ge??void 0,scope:He,context:Ie,signal:st.signal,onEvent:qs});const et=await Cf(e);De.current&&!et.isStreaming&&(E(et.conversationId??null),N(et.messages),re.current=et.updatedAt,lt.current=null)}catch(et){if(!De.current)return;b&&(lt.current=null);const Jt=Gt.current;Jt&&Ad(Jt).trim()&&N(Za=>[...Za,Jt]),st.signal.aborted?ce("Stopped. Partial response preserved. An action already dispatched may still finish."):ve(zi(et))}finally{De.current&&(ne(!1),_e(""),Se(et=>et.map(Jt=>Jt.endedAt===void 0?{...Jt,interrupted:!0}:Jt))),ea.current=null}}async function di(oe){const Ie=bk.find(st=>st.command===oe.toLowerCase())?.prompt??oe,Ye=gg.find(st=>st.prompt===Ie)?.id;if(!Ye){ve(null),me(null),ce(cY);return}ve(null),ce(null),me({prompt:Ie}),$e(""),ne(!0),_e(""),Gt.current=null,Se([]),N(st=>[...st,{role:"user",content:Ie,timestamp:Date.now()}]);const Qt=new AbortController;ea.current=Qt;try{const st=await f.ensureQueryData(yk(e));if(Qt.signal.aborted)throw new DOMException("Preview stopped","AbortError");const et=st.starters.find(Jt=>Jt.id===Ye);if(!et)throw new Error("This demo has no sample answer for that starting point.");await aY({starter:et,signal:Qt.signal,onEvent:qs,reducedMotion:WZ()})}catch(st){if(!De.current)return;const et=Gt.current;et&&Ad(et).trim()&&N(Jt=>[...Jt,et]),Qt.signal.aborted?ce(uY):ve(zi(st))}finally{De.current&&(ne(!1),_e(""),Se(st=>st.map(et=>et.endedAt===void 0?{...et,interrupted:!0}:et))),ea.current=null}}function qs(oe){if(De.current)switch(oe.type){case"message_update":oe.message.role==="assistant"&&(Gt.current=oe.message),_e(Ad(oe.message));break;case"message_end":if(oe.message.role!=="user"){const Ie=oe.message;N(Ye=>[...Ye,Ie])}oe.message.role==="assistant"&&(Gt.current=null,_e(""),oe.message.errorMessage&&ve(oe.message.errorMessage));break;case"aero_turn_status":oe.status?.reason==="tool-limit"?ce("Tool-call limit reached. Partial response preserved."):oe.status?.reason==="time-limit"?ce("Time limit reached. Partial response preserved."):oe.status?.reason==="completed"&&me(null);break;case"tool_execution_start":Se(Ie=>[...Ie,{id:oe.toolCallId,name:oe.toolName,label:oe.label,args:oe.args,startedAt:Date.now()}]);break;case"tool_execution_end":Se(Ie=>Ie.map(Ye=>Ye.id===oe.toolCallId?{...Ye,endedAt:Date.now(),isError:oe.isError,result:oe.result}:Ye));break;case"error":ve(oe.message);break}}async function Vi(oe,Ie=!1){if(!(O||we||Pe.current)){Pe.current=!0,K(!0),ve(null);try{await oe();const Ye=await Cf(e);if(!De.current)return;lt.current=null,re.current=Ye.updatedAt,E(Ye.conversationId??null),N(Ye.messages),Se([]),_e(""),ce(null),me(null),Ue(null),Z(Ie),ee(Ie?await Gw(e):null),Le.current?.focus()}catch(Ye){De.current&&ve(zi(Ye))}finally{Pe.current=!1,De.current&&K(!1)}}}async function $i(){if(i){if(O)return;N([]),Se([]),_e(""),ve(null),ce(null),me(null),Le.current?.focus();return}await Vi(()=>b?oY(e):aK(e,crypto.randomUUID()))}async function Ms(oe=!1){if(!(Pe.current||q.current)){q.current=!0,X(!0),Z(!0),ve(null);try{const Ie=await Gw(e,{offset:oe?Y?.nextOffset??0:0});De.current&&ee(Ye=>oe&&Ye?{...Ie,conversations:[...Ye.conversations,...Ie.conversations]}:Ie)}catch(Ie){De.current&&ve(zi(Ie))}finally{q.current=!1,De.current&&X(!1)}}}const fn=T.length===0,At=!(b||i);if(At&&Rn.isPending)return null;if(At&&Rn.isError)return l.jsx("div",{className:"pointer-events-none fixed inset-x-0 bottom-0 z-40 flex justify-center p-3",children:l.jsxs("div",{role:"status",className:"flex w-full max-w-3xl flex-wrap items-center gap-x-2 gap-y-1 rounded-lg border border-base bg-bg/95 px-4 py-2 text-sm shadow-lg",children:[l.jsx(ed,{className:"h-4 w-4 text-muted","aria-hidden":"true"}),l.jsx("span",{className:"font-medium text-strong",children:"Aero could not check provider availability."}),l.jsx(ue,{variant:"outline",size:"sm",className:"pointer-events-auto ml-auto",onClick:()=>{Rn.refetch()},children:"Try again"})]})});const gn=Lt&&!Lt.configured?Lt:null;if(At&&(!Lt||gn))return l.jsx("div",{className:"pointer-events-none fixed inset-x-0 bottom-0 z-40 flex justify-center p-3",children:l.jsxs("div",{role:"status",className:"flex w-full max-w-3xl flex-wrap items-center gap-x-2 gap-y-1 rounded-lg border border-base bg-bg/95 px-4 py-2 text-sm shadow-lg",children:[l.jsx(ed,{className:"h-4 w-4 text-muted","aria-hidden":"true"}),l.jsxs("span",{className:"flex items-center gap-1.5 font-medium text-strong",children:[gn?`Aero is set to ${gn.label.replace(/\s+\(.+\)$/,"")}, which has no API key.`:"Aero needs an answer-engine provider.",l.jsx(Ua,{text:gn?`Set ${CC(gn.id)} on the server, or providers.${gn.id}.apiKey in its config.yaml.`:"Aero is the built-in AEO analyst. It reads your Canonry data with you once a provider is connected."})]}),gn?null:u?l.jsx(ue,{asChild:!0,variant:"outline",size:"sm",className:"pointer-events-auto ml-auto",children:l.jsx(We,{to:"/settings",children:"Open Settings"})}):l.jsx("span",{className:"ml-auto text-secondary",children:"Ask an administrator to configure one."})]})});const Sn=v&&k?"pointer-events-auto fixed inset-0 z-40 flex items-stretch justify-center bg-bg/70 p-4 sm:p-8 backdrop-blur-sm":"pointer-events-none fixed inset-x-0 bottom-0 z-40 flex justify-center p-3",Bs=k?"pointer-events-auto flex h-full w-full max-w-5xl flex-col overflow-hidden rounded-2xl border border-mono-800/80 bg-bg/95 shadow-2xl":"pointer-events-auto w-full max-w-3xl",fa=k?"flex-1 overflow-y-auto px-6 py-5 text-sm text-strong":"max-h-[40vh] min-h-[120px] overflow-y-auto px-4 py-3 text-sm text-strong";return l.jsx("div",{className:Sn,onClick:oe=>{k&&oe.target===oe.currentTarget&&j(!1)},children:l.jsx("div",{className:Bs,children:v?l.jsxs("div",{"data-aero-panel":!0,className:k?"flex h-full flex-col":"flex flex-col overflow-hidden rounded-2xl border border-mono-800/80 bg-bg/95 shadow-xl backdrop-blur",children:[l.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-mono-800/70 px-4 py-2.5",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(ed,{className:"h-4 w-4 text-positive-400","aria-hidden":"true"}),l.jsx("span",{className:"text-sm font-medium text-heading",children:"Aero"}),l.jsx("span",{className:"text-[10px] uppercase tracking-wider text-muted",children:O||we?"working…":e})]}),l.jsxs("div",{className:"flex items-center gap-1",children:[!r&&!b&&!i&&l.jsx(hY,{providers:Rn.data?.providers??[],active:Lt,override:Ge,onPick:Ps,disabled:O}),l.jsx("button",{type:"button",onClick:()=>j(oe=>!oe),className:"rounded-md p-1.5 text-muted transition hover:bg-surface-inset hover:text-strong","aria-label":k?"Collapse":"Expand",title:k?"Collapse":"Expand",children:k?l.jsx(n5,{className:"h-3.5 w-3.5","aria-hidden":"true"}):l.jsx(a5,{className:"h-3.5 w-3.5","aria-hidden":"true"})}),l.jsx("button",{type:"button",onClick:()=>{j(!1),w(!1)},className:"rounded-md p-1.5 text-muted transition hover:bg-surface-inset hover:text-strong","aria-label":"Close Aero",children:l.jsx($r,{className:"h-4 w-4","aria-hidden":"true"})})]})]}),l.jsxs("div",{className:"flex flex-wrap items-center gap-2 border-b border-subtle px-4 py-2",children:[l.jsxs(ue,{variant:"outline",size:"sm",disabled:O||we||B,onClick:pn($i),title:b||i?"Clear this conversation and start fresh.":"Save this conversation and start fresh. Shared project notes are kept.",children:[l.jsx(Ef,{className:"h-3.5 w-3.5","aria-hidden":"true"})," New conversation"]}),!b&&!i&&l.jsxs(ue,{variant:"ghost",size:"sm","aria-expanded":L,"aria-controls":"aero-history",disabled:B,onClick:()=>{L?Z(!1):Ms()},children:[l.jsx(Hk,{className:"h-3.5 w-3.5","aria-hidden":"true"})," History"]})]}),L?l.jsxs("div",{id:"aero-history",className:fa,"aria-label":"Conversation history",children:[l.jsxs("h3",{className:"mb-2 text-sm font-medium text-heading",children:["Conversations in ",e]}),Y?Y.conversations.length===0?l.jsx("p",{className:"text-sm text-secondary",children:"No saved conversations yet. Your conversations will appear here."}):l.jsx("ul",{className:"divide-y divide-default",children:Y.conversations.map(oe=>l.jsxs("li",{className:"py-2",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsxs("button",{className:"min-w-0 flex-1 rounded-md px-2 py-1 text-left hover:bg-surface-hover focus-visible:ring-2 focus-visible:ring-positive-500",disabled:O||we||B,onClick:()=>{oe.active?Z(!1):Vi(()=>iK(e,oe.id))},children:[l.jsx("span",{className:"block truncate text-sm text-heading",children:oe.title}),l.jsxs("span",{className:"text-xs text-secondary",children:[oe.active?"Current · ":"",new Date(oe.updatedAt).toLocaleString()]})]}),l.jsx(ue,{variant:"ghost",size:"sm",disabled:O||we||B,"aria-label":`Delete conversation: ${oe.title}`,onClick:()=>Ue(oe.id),children:"Delete"})]}),nt===oe.id&&l.jsxs("div",{role:"group","aria-label":"Confirm conversation deletion",className:"mt-2 rounded-md border border-default p-3 text-sm text-secondary",children:[l.jsx("p",{children:"Delete this conversation permanently? Shared project notes will be kept."}),l.jsxs("div",{className:"mt-2 flex gap-2",children:[l.jsx(ue,{variant:"destructive",size:"sm",disabled:B,onClick:()=>{Vi(async()=>{await sK(e,oe.id)},!0)},children:"Delete conversation"}),l.jsx(ue,{variant:"ghost",size:"sm",disabled:B,onClick:()=>Ue(null),children:"Cancel"})]})]})]},oe.id))}):l.jsx("p",{className:"text-sm text-secondary",children:H?"Loading history…":"History could not be loaded. Close and reopen History to retry."}),Y?.nextOffset!=null&&l.jsx(ue,{variant:"ghost",size:"sm",disabled:H,onClick:()=>{Ms(!0)},children:H?"Loading…":"Load more"})]}):l.jsxs("div",{ref:ci,className:fa,children:[fn&&!O&&l.jsxs("div",{className:"flex flex-col gap-3 py-2",children:[l.jsx("p",{className:"text-sm text-secondary",children:i?l.jsxs(l.Fragment,{children:["See how Aero answers about ",l.jsx("span",{className:"text-strong",children:e}),". Choose a starting point."]}):l.jsxs(l.Fragment,{children:["Ask about ",l.jsx("span",{className:"text-strong",children:e})," or choose a starting point."]})}),l.jsx(wk,{onPick:oe=>{Un(oe)}})]}),xY(T,e,Ge,He,ge,O,!b&&!i),O&&ae&&l.jsxs("div",{className:"mt-3",children:[l.jsx("div",{className:"mb-0.5 text-[10px] uppercase tracking-wider text-positive-400",children:"Aero"}),l.jsx(NC,{content:ae})]}),O&&!ae&&ge.every(oe=>oe.endedAt!==void 0)&&l.jsx(AY,{}),i&&!fn&&!O&&l.jsxs("div",{className:"mt-4 flex flex-col gap-2 border-t border-subtle pt-3",children:[l.jsx("p",{className:"text-xs text-secondary",children:"Try another starting point."}),l.jsx(wk,{onPick:oe=>{Un(oe)}})]})]}),(Be||le)&&l.jsxs("div",{role:Be?"alert":"status",className:"mx-3 my-2 flex flex-wrap items-center gap-2 rounded-md border border-base bg-surface px-3 py-2 text-sm text-secondary",children:[l.jsx("span",{className:"flex-1",children:Be??le}),Q&&!O&&l.jsx(ue,{variant:"outline",size:"sm",onClick:()=>{He==="all"?($e(Q.prompt),Le.current?.focus()):Un(Q.prompt,Q.context)},children:He==="all"?"Review prompt":"Retry"})]}),i&&l.jsxs("p",{className:"border-t border-subtle px-4 py-2 text-xs text-secondary",children:["Sample answers on demo data."," ",l.jsxs("a",{href:lY,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-0.5 text-positive-400 underline decoration-positive-700 hover:decoration-positive-400",children:["Aero answers from your own Canonry data.",l.jsx(Gk,{className:"h-3 w-3","aria-hidden":"true"}),l.jsx("span",{className:"sr-only",children:" (opens in a new tab)"})]})]}),l.jsxs("div",{className:"relative",children:[!L&&Ht.length>0&&l.jsx(bY,{title:i?"Starting points":"Commands",matches:Ht,selectedIndex:ct,onHover:Kt,onPick:oe=>{$e(""),Le.current?.focus(),oe.action==="new"?$i():Un(oe.prompt)}}),l.jsxs("form",{className:"flex items-end gap-2 border-t border-mono-800/70 bg-bg/80 px-3 py-2.5",onSubmit:oe=>{if(oe.preventDefault(),Ht.length>0){const Ie=Ht[ct];$e(""),Ie.action==="new"?$i():Un(Ie.prompt);return}Un(ke)},children:[l.jsx("textarea",{ref:Le,value:ke,onChange:oe=>$e(oe.target.value),onKeyDown:oe=>{if(Ht.length>0){if(oe.key==="ArrowDown"){oe.preventDefault(),Kt(Ie=>(Ie+1)%Ht.length);return}if(oe.key==="ArrowUp"){oe.preventDefault(),Kt(Ie=>(Ie-1+Ht.length)%Ht.length);return}if(oe.key==="Tab"){oe.preventDefault();const Ie=Ht[ct];$e(`${Ie.command} `);return}if(oe.key==="Escape"){oe.preventDefault(),$e("");return}}if(oe.key==="Enter"&&!oe.shiftKey)if(oe.preventDefault(),Ht.length>0){const Ie=Ht[ct];$e(""),Ie.action==="new"?$i():Un(Ie.prompt)}else Un(ke)},disabled:L||B,placeholder:L?"Open a conversation to continue…":i?"Type / for a starting point":"Ask Aero, or / for commands…","aria-label":"Message Aero",rows:k?3:1,className:"flex-1 resize-none overflow-y-auto bg-transparent text-sm text-heading placeholder:text-mono-600 focus:outline-none disabled:opacity-60"}),O?l.jsxs(ue,{type:"button",variant:"outline",size:"sm",onClick:()=>ea.current?.abort(),"aria-label":"Stop Aero",children:[l.jsx(i5,{className:"h-3.5 w-3.5","aria-hidden":"true"})," Stop"]}):l.jsx(ue,{type:"submit",size:"sm",disabled:!ke.trim()||L||B||we,"aria-label":"Send",children:l.jsx(s5,{className:"h-4 w-4","aria-hidden":"true"})})]})]})]}):l.jsx("button",{type:"button",onClick:()=>w(!0),className:"flex w-full items-center justify-between rounded-lg border border-mono-800/80 bg-bg/95 px-4 py-2 text-left text-sm text-secondary shadow-lg transition hover:border-strong hover:bg-bg-elevated/90 hover:text-strong",children:l.jsxs("span",{className:"flex items-center gap-2",children:[l.jsx(ed,{className:"h-4 w-4 text-positive-400","aria-hidden":"true"}),"Ask Aero about ",e,"…"]})})})})}function hY({providers:e,active:n,override:i,onPick:r,disabled:u}){const[h,f]=C.useState(!1),b=C.useRef(null);if(C.useEffect(()=>{if(!h)return;const w=j=>{b.current?.contains(j.target)||f(!1)},k=j=>{j.key==="Escape"&&f(!1)};return window.addEventListener("mousedown",w),window.addEventListener("keydown",k),()=>{window.removeEventListener("mousedown",w),window.removeEventListener("keydown",k)}},[h]),e.length===0)return null;const v=n?.label.replace(/\s+\(.+\)$/,"")??"No provider";return l.jsxs("div",{ref:b,className:"relative",children:[l.jsxs("button",{type:"button",onClick:()=>f(w=>!w),disabled:u,className:"flex items-center gap-1 rounded-md px-2 py-1 text-sm text-secondary transition hover:bg-surface-inset hover:text-strong disabled:opacity-50","aria-label":"Switch agent model","aria-haspopup":"listbox","aria-expanded":h,title:n?`${n.label} · ${n.defaultModel}`:"Pick a provider",children:[l.jsx("span",{className:"font-medium text-strong",children:v}),l.jsx(Jd,{className:"h-3 w-3","aria-hidden":"true"})]}),h&&l.jsxs("div",{role:"listbox",className:"absolute right-0 top-full z-50 mt-1 w-64 overflow-hidden rounded-lg border border-base bg-bg shadow-xl",children:[l.jsx("div",{className:"border-b border-default px-3 py-2 text-sm font-medium text-secondary",children:"Answer engine"}),l.jsx("ul",{className:"max-h-72 overflow-y-auto py-1",children:e.map(w=>{const k=n?.id===w.id,j=i===w.id;return l.jsx("li",{children:l.jsxs("button",{type:"button",role:"option","aria-selected":k,disabled:!w.configured,onClick:()=>{w.configured&&(r(j?null:w.id),f(!1))},className:"flex w-full items-center gap-2 px-3 py-2.5 text-left text-sm transition enabled:hover:bg-bg-elevated disabled:cursor-not-allowed disabled:opacity-60",title:w.configured?w.defaultModel:`Add ${CC(w.id)} in Settings or your environment`,children:[l.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center",children:k?l.jsx(Wd,{className:"h-3 w-3 text-positive-400","aria-hidden":"true"}):null}),l.jsx("span",{className:"min-w-0 flex-1 truncate font-medium text-heading",children:w.label.replace(/\s+\(.+\)$/,"")}),j&&l.jsx("span",{className:"rounded-md border border-positive-800/60 bg-positive-950/60 px-2 py-0.5 text-[11px] text-positive",children:"Selected"}),!w.configured&&l.jsx("span",{className:"rounded-md border border-base px-2 py-0.5 text-[11px] text-secondary",children:"Needs setup"})]})},w.id)})}),i&&l.jsx("button",{type:"button",onClick:()=>{r(null),f(!1)},className:"w-full border-t border-default px-3 py-2 text-left text-[11px] text-secondary transition hover:bg-bg-elevated hover:text-heading",children:"Reset to default"})]})]})}const fY=144,gY=288,Nf=288,yY=8;function bY({title:e,matches:n,selectedIndex:i,onHover:r,onPick:u}){const h=C.useRef(null),f=C.useRef(null),b=C.useRef(null),[v,w]=C.useState(Nf);return C.useLayoutEffect(()=>{const k=h.current,j=k?.closest("[data-aero-panel]"),T=k?.parentElement;if(!k||!j||!T)return;const N=T.getBoundingClientRect().top-j.getBoundingClientRect().top-yY*2-(f.current?.getBoundingClientRect().height??0);w(N>0?Math.min(Nf,Math.floor(N)):Nf)},[n.length]),C.useEffect(()=>{b.current?.querySelector('[aria-selected="true"]')?.scrollIntoView?.({block:"nearest"})},[i]),l.jsxs("div",{ref:h,className:"absolute inset-x-3 bottom-full mb-2 overflow-hidden rounded-lg border border-base bg-bg/98 shadow-2xl",children:[l.jsx("div",{ref:f,className:"border-b border-default px-3 py-1.5 text-[10px] uppercase tracking-wider text-muted",children:e}),l.jsx("ul",{ref:b,role:"listbox",className:"overflow-y-auto py-1",style:{maxHeight:v},children:n.map((k,j)=>{const T=j===i;return l.jsx("li",{children:l.jsxs("button",{type:"button",role:"option","aria-selected":T,onMouseEnter:()=>r(j),onClick:()=>u(k),className:`flex w-full items-center gap-3 px-3 py-2 text-left text-sm transition ${T?"bg-bg-elevated text-heading":"text-neutral hover:bg-bg-elevated/60"}`,children:[l.jsx("span",{className:"font-medium",children:k.label}),l.jsx("span",{className:"ml-auto font-mono text-[11px] text-secondary",children:k.command})]})},k.command)})})]})}function wk({onPick:e}){return l.jsx("div",{className:"flex flex-wrap gap-1.5",children:gg.map(n=>l.jsx("button",{type:"button",onClick:()=>e(n.prompt),className:"rounded-md border border-base bg-bg-elevated/70 px-3 py-1.5 text-sm text-neutral transition hover:border-strong hover:bg-mono-800/70 hover:text-heading",children:n.label},n.label))})}function CC(e){switch(e){case"claude":return"ANTHROPIC_API_KEY";case"openai":return"OPENAI_API_KEY";case"gemini":return"GEMINI_API_KEY";case"zai":return"ZAI_API_KEY";case"deepinfra":return"DEEPINFRA_TOKEN"}}function vY(e,n){const i=e.timestamp??0;return`${e.role}:${i}:${n}`}function xY(e,n,i,r,u,h,f=!0){const b=[];for(let v=0;v<e.length;v++){const w=e[v],k=vY(w,v);if(w.role==="user"){const j=typeof w.content=="string"?w.content:JSON.stringify(w.content);if(j.startsWith("[system]"))continue;b.push(l.jsx(wY,{text:j,projectName:n,providerOverride:i,scope:r,context:w.aeroContext,cliCopy:f},k));continue}if(w.role==="assistant"){const j=new Map;let T=v+1;for(;T<e.length&&e[T].role==="toolResult";){const E=e[T];j.set(E.toolCallId,E),T++}const N=SY(w,j).map(E=>{const q=u.find(X=>X.id===E.id),H={...E,...q};return{...H,interrupted:H.endedAt===void 0&&(!h||H.interrupted)}}),P=Ad(w);b.push(l.jsxs(C.Fragment,{children:[P.trim()&&l.jsxs("div",{className:"mt-3",children:[l.jsx("div",{className:"mb-0.5 text-[10px] uppercase tracking-wider text-positive-400",children:"Aero"}),l.jsx(NC,{content:P})]}),N.length>0&&l.jsx("div",{className:"mt-3 space-y-1.5",children:N.map(E=>l.jsx(jY,{trail:E},E.id))})]},k)),v=T-1;continue}}return b}function wY({text:e,projectName:n,providerOverride:i,scope:r,context:u,cliCopy:h=!0}){const[f,b]=C.useState(!1),v=C.useMemo(()=>kY(n,e,i,r,u),[n,e,i,r,u]);async function w(){try{await navigator.clipboard.writeText(v),b(!0),window.setTimeout(()=>b(!1),1500)}catch{}}return l.jsxs("div",{className:"group relative mt-3 rounded-md bg-bg-elevated/60 px-3 py-2 text-strong",children:[l.jsxs("div",{className:"flex items-center justify-between gap-2",children:[l.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted",children:"You"}),h&&l.jsx("button",{type:"button",onClick:pn(w),className:"inline-flex items-center gap-1 rounded border border-mono-800/70 bg-bg/60 px-1.5 py-0.5 text-[10px] text-secondary opacity-0 transition hover:border-strong hover:text-heading group-hover:opacity-100 focus:opacity-100","aria-label":"Copy as CLI command",title:v,children:f?l.jsxs(l.Fragment,{children:[l.jsx(Wd,{className:"h-2.5 w-2.5 text-positive-400","aria-hidden":"true"}),"Copied"]}):l.jsxs(l.Fragment,{children:[l.jsx(Cg,{className:"h-2.5 w-2.5","aria-hidden":"true"}),"Copy as CLI"]})})]}),l.jsx("div",{className:"whitespace-pre-wrap",children:e})]})}function kY(e,n,i,r,u){const h=["canonry","agent","ask",vf(e),vf(n)];return i&&h.push("--provider",i),r==="read-only"&&h.push("--scope","read-only"),u&&h.push("--context",vf(JSON.stringify(u))),h.join(" ")}function SY(e,n){const i=[];for(const r of e.content){if(r.type!=="toolCall")continue;const u=r,h=n.get(u.id);i.push({id:u.id,name:u.name,args:u.arguments,label:h?.aeroToolLabel,durationMs:h?.aeroDurationMs,endedAt:h?.timestamp,isError:h?.isError,result:h?.content})}return i}function jY({trail:e}){const[n,i]=C.useState(!1),r=e.endedAt===void 0&&!e.interrupted,u=!r&&e.isError===!0,h=e.durationMs??(e.endedAt!=null&&e.startedAt!=null?e.endedAt-e.startedAt:null),f=h==null||h<0?null:h<1e3?`${h}ms`:`${(h/1e3).toFixed(1)}s`,b=u?"border-negative-800/50":r?"border-positive-800/50":"border-mono-800/70",v=u?"bg-negative-950/20":r?"bg-positive-950/20":"bg-surface-hover";return l.jsxs("div",{className:`rounded-md border ${b} ${v}`,children:[l.jsxs("button",{type:"button",onClick:()=>i(w=>!w),className:"flex w-full items-center gap-2 px-2.5 py-1.5 text-left","aria-expanded":n,children:[l.jsx("span",{className:"flex h-3.5 w-3.5 shrink-0 items-center justify-center",children:r?l.jsx(Rr,{className:"h-3 w-3 animate-spin text-positive-400","aria-hidden":"true"}):u?l.jsx(Qk,{className:"h-3 w-3 text-negative-400","aria-hidden":"true"}):l.jsx(o5,{className:"h-3 w-3 text-muted","aria-hidden":"true"})}),l.jsx("span",{className:"text-sm font-medium text-heading",children:e.label??e.name.replace(/^(?:canonry|aero)_/,"").replace(/_/g," ")}),l.jsxs("span",{className:"ml-auto flex items-center gap-2 text-[10px] text-muted",children:[r?l.jsx("span",{className:"text-positive-400",children:"running…"}):l.jsxs(l.Fragment,{children:[l.jsx("span",{children:e.interrupted?"interrupted":u?"failed":"done"}),f&&l.jsx("span",{children:f})]}),l.jsx(Ng,{className:`h-3 w-3 transition-transform ${n?"rotate-90":""}`,"aria-hidden":"true"})]})]}),n&&l.jsxs("div",{className:"border-t border-default px-2.5 py-2 text-[11px] text-secondary",children:[l.jsx("div",{className:"mb-2 text-xs text-secondary",children:e.name}),l.jsx("div",{className:"mb-1 text-xs text-secondary",children:"Inputs"}),l.jsx("pre",{className:"mb-2 overflow-x-auto whitespace-pre-wrap break-all text-xs text-neutral",children:kk(e.args)}),!r&&e.result!==void 0&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"mb-1 text-[9px] uppercase tracking-wider text-faint",children:u?"Error":"Result"}),l.jsx("pre",{className:"overflow-x-auto whitespace-pre-wrap break-all text-xs text-neutral",children:kk(e.result)})]})]})]})}function kk(e){try{const n=typeof e=="string"?e:JSON.stringify(e,null,2);return n.length>2e3?`${n.slice(0,2e3)}
64
64
  … (${n.length-2e3} more chars)`:n}catch{return String(e)}}function NC({content:e}){return l.jsx("div",{className:"text-heading",children:l.jsx(k5,{remarkPlugins:[S5],components:{h1:n=>l.jsx("h1",{...n,className:"mt-3 mb-2 text-base font-semibold text-primary"}),h2:n=>l.jsx("h2",{...n,className:"mt-3 mb-2 text-sm font-semibold text-primary"}),h3:n=>l.jsx("h3",{...n,className:"mt-3 mb-1.5 text-sm font-semibold text-heading"}),h4:n=>l.jsx("h4",{...n,className:"mt-2 mb-1 text-xs font-semibold uppercase tracking-wide text-neutral"}),p:n=>l.jsx("p",{...n,className:"mb-2 leading-relaxed"}),ul:n=>l.jsx("ul",{...n,className:"mb-2 ml-4 list-disc space-y-1"}),ol:n=>l.jsx("ol",{...n,className:"mb-2 ml-4 list-decimal space-y-1"}),li:n=>l.jsx("li",{...n,className:"marker:text-mono-600"}),strong:n=>l.jsx("strong",{...n,className:"font-semibold text-primary"}),em:n=>l.jsx("em",{...n,className:"text-strong"}),code:({children:n,...i})=>l.jsx("code",{...i,className:"rounded bg-mono-800/70 px-1 py-0.5 font-mono text-[12px] text-positive-200",children:n}),pre:n=>l.jsx("pre",{...n,className:"mb-2 overflow-x-auto rounded-md border border-base bg-bg-elevated/70 p-3 font-mono text-xs text-strong"}),a:n=>l.jsx("a",{...n,className:"text-positive-400 underline decoration-positive-700 hover:decoration-positive-400",target:"_blank",rel:"noopener noreferrer"}),table:n=>l.jsx("div",{className:"mb-2 overflow-x-auto",children:l.jsx("table",{...n,className:"w-full border-collapse text-xs"})}),thead:n=>l.jsx("thead",{...n,className:"border-b border-base"}),th:n=>l.jsx("th",{...n,className:"px-2 py-1 text-left font-semibold text-neutral"}),tr:n=>l.jsx("tr",{...n,className:"border-b border-mono-900"}),td:n=>l.jsx("td",{...n,className:"px-2 py-1 text-strong"}),blockquote:n=>l.jsx("blockquote",{...n,className:"mb-2 border-l-2 border-strong pl-3 italic text-secondary"}),hr:()=>l.jsx("hr",{className:"my-3 border-base"})},children:e})})}function AY(){return l.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[l.jsx("div",{className:"text-[10px] uppercase tracking-wider text-positive-400",children:"Aero"}),l.jsxs("div",{className:"flex items-center gap-1","aria-label":"Aero is thinking",children:[l.jsx("span",{className:"aero-dot h-1.5 w-1.5 rounded-full bg-positive-400/80"}),l.jsx("span",{className:"aero-dot aero-dot-2 h-1.5 w-1.5 rounded-full bg-positive-400/60"}),l.jsx("span",{className:"aero-dot aero-dot-3 h-1.5 w-1.5 rounded-full bg-positive-400/40"})]})]})}function _C({isAdmin:e,account:n}){return e||n?.role==="viewer"&&SG()}function CY(){const{isAdmin:e,account:n}=pa(),i=qk(),r=/^\/projects\/([^/]+)/.exec(i.pathname),u=r?decodeURIComponent(r[1]):null,h=yt({...Do({client:J}),enabled:u!==null,staleTime:6e4}),f=VZ(i.pathname,i.search),b=h.data??[],v=b.find(T=>T.id===u)??b.find(T=>T.name===u),w=TK(v?.name??u??"",f),k=W0(),j=k||_C({isAdmin:e,account:n});return!u||!j||!v?null:l.jsx(pY,{projectName:v.name,context:w,preview:k},v.name)}const yg={project:"getApiV1ProjectsByName",google:"getApiV1ProjectsByNameGoogle",gsc:"getApiV1ProjectsByNameGoogleGsc",bing:"getApiV1ProjectsByNameBing",ga:"getApiV1ProjectsByNameGa",gbp:"getApiV1ProjectsByNameGbp",ads:"getApiV1ProjectsByNameAds",googleAds:"getApiV1ProjectsByNameGoogleAds",gtm:"getApiV1ProjectsByNameGtm",conversionTracking:"getApiV1ProjectsByNameConversionTracking",traffic:"getApiV1ProjectsByNameTraffic",discovery:"getApiV1ProjectsByNameDiscover",researchRuns:"getApiV1ProjectsByNameResearchRuns",visibilityReport:"getApiV1ProjectsByNameVisibilityReport",queryTracking:"getApiV1ProjectsByNameQueryTracking",technicalAeo:"getApiV1ProjectsByNameTechnicalAeo",runs:"getApiV1ProjectsByNameRuns"};function On(e,n){const i=yg[n];return e.invalidateQueries({predicate:r=>{const u=r.queryKey[0];return typeof u?._id=="string"&&u._id.startsWith(i)}})}function Gie(e,n){return e.invalidateQueries({predicate:i=>{const r=i.queryKey[0];return r?.path?.name!==n||typeof r._id!="string"?!1:r._id.startsWith("getApiV1ProjectsByNameMeasurement")||r._id===yg.queryTracking||r._id===yg.visibilityReport||r._id==="getApiV1ProjectsByNameQueries"||r._id==="getApiV1ProjectsByName"}})}function Cc(e,n,i){switch(e.invalidateQueries({queryKey:s1({client:J})}),e.invalidateQueries({queryKey:As({client:J})}),On(e,"runs"),n){case ze["answer-visibility"]:pg(e,i,"none"),On(e,"visibilityReport"),On(e,"queryTracking");return;case ze["backlink-extract"]:return;case ze["site-audit"]:On(e,"technicalAeo");return;case ze["gsc-sync"]:case ze["inspect-sitemap"]:On(e,"gsc");return;case ze["ga-sync"]:On(e,"ga");return;case ze["traffic-sync"]:On(e,"ga"),On(e,"traffic");return;case ze["bing-inspect"]:case ze["bing-inspect-sitemap"]:On(e,"bing");return;case ze["aeo-discover-seed"]:case ze["aeo-discover-probe"]:pg(e,i);return;case ze["gbp-sync"]:On(e,"gbp");return;case ze["ads-sync"]:On(e,"ads");return;case ze["google-ads-sync"]:On(e,"googleAds"),On(e,"conversionTracking");return;case ze["gtm-sync"]:On(e,"gtm"),On(e,"conversionTracking");return;default:return n}}const Sk=[{label:"GitHub",href:"https://github.com/Canonry/canonry",Icon:Kk},{label:"Docs",href:"https://github.com/Canonry/canonry/tree/main/docs",Icon:h5},{label:"Changelog",href:"https://github.com/Canonry/canonry/releases",Icon:f5}],jk=e=>({label:e,state:"checking",detail:"Checking service health"}),NY={apiStatus:jk("API"),workerStatus:jk("Worker")};function _Y(e){return e==="completed"?"positive":e==="partial"?"caution":"negative"}function TY(e){const n=pc(e.kind);return e.status==="completed"?`${n} completed`:e.status==="partial"?`${n} completed with partial results`:e.status==="cancelled"?`${n} cancelled`:`${n} failed`}function EY(e,n){return e.error?`${n}: ${u0(e.error)}`:e.location?`${n} · ${e.location}`:n}function Ak(e,n,i){if(n)return n;const r=i.find(u=>u.id===e);return r?.displayName||r?.name||e}function RY(e,n){return[e.completed>0?`${e.completed} completed`:null,e.partial>0?`${e.partial} partial`:null,e.failed>0?`${e.failed} failed`:null,e.cancelled>0?`${e.cancelled} cancelled`:null,n>0?`${n} skipped at queue time`:null].filter(Boolean).join(", ")}function DY(e){return e.failed>0||e.cancelled>0?"negative":e.partial>0?"caution":"positive"}function zY(){const e=Jn(),n=C.useSyncExternalStore(nC,Bi,Bi),i=Object.keys(n.runs).length>0||Object.keys(n.batches).length>0,r=yt({..._m({client:J}),enabled:i,staleTime:Lr,refetchInterval:3e3}),u=yt({...Do({client:J}),enabled:i}),h=C.useRef({}),f=C.useCallback(()=>{r.refetch()},[r.refetch]);return C.useEffect(()=>{i&&f()},[i,f]),C.useEffect(()=>{if(!i||typeof window>"u")return;const b=()=>{document.visibilityState==="visible"&&f()};return window.addEventListener("focus",f),document.addEventListener("visibilitychange",b),()=>{window.removeEventListener("focus",f),document.removeEventListener("visibilitychange",b)}},[i,f]),C.useEffect(()=>{const b=r.data??[],v=u.data??[],w=Object.fromEntries(b.map(j=>[j.id,j])),k=Object.fromEntries(b.map(j=>[j.id,j.status]));for(const j of Object.values(n.runs)){const T=w[j.runId];if(!T||!MQ(T.status)||(h.current[T.id]??j.lastAnnouncedStatus)===T.status)continue;const P=v.find(q=>q.id===T.projectId);if(P&&Cc(e,T.kind,P.name),j.sourceAction==="run-all"){wf(T.id);continue}const E=Ak(T.projectId,j.projectLabel,v);wn({title:TY(T),detail:EY(T,E),tone:_Y(T.status),dedupeKey:`run:${T.id}`,dedupeMode:"replace",cta:{label:"View run",intent:"open-run-drawer",runId:T.id}}),wf(T.id)}if(r.data!==void 0){const j=new Set(b.map(N=>N.id)),T=LQ(Object.values(n.runs),j,Date.now(),BQ);for(const N of T){const P=v.find(E=>E.id===N.projectId);P&&Cc(e,N.kind,P.name),N.sourceAction!=="run-all"&&wn({title:`${pc(N.kind)} status unavailable`,detail:Ak(N.projectId,N.projectLabel,v),tone:"neutral",dedupeKey:`run-stale:${N.runId}`,dedupeMode:"replace"}),wf(N.runId)}}for(const j of Object.values(n.batches)){const T=VQ(j.runIds,w);T.finished&&(wn({title:"Run-all batch finished",detail:RY(T,j.skippedCount),tone:DY(T),dedupeKey:`batch:${j.batchId}`,dedupeMode:"replace",cta:{label:"View runs",intent:"go-to-runs"}}),qQ(j.batchId))}h.current=k},[u.data,r.data,n,e]),null}function IY(){const{account:e,isAdmin:n}=pa(),i=Uc(),r=C.useMemo(()=>qA(),[]),u=C.useMemo(wG,[]),h=C.useMemo(kG,[]),f=W0()||h&&_C({isAdmin:n,account:e}),b=C.useMemo(jG,[]),v=qk(),{dashboard:w,isLoading:k,refetch:j}=zm(void 0,{includeSettings:!r,includeOverviews:!1,pauseProjectPolling:v.pathname==="/setup"}),P=d1(!i,i?.health).data??i?.health??NY,{runId:E,evidenceId:q,closeDrawer:H}=m1(),[X,L]=C.useState(!1),[Z,Y]=C.useState(()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("canonry:sidebarHidden")==="true"}catch{return!1}}),[ee,B]=C.useState(()=>{if(typeof window>"u")return null;try{return window.localStorage.getItem("canonry:dismissedUpdateVersion")}catch{return null}}),[K]=C.useState(()=>typeof window>"u"?null:new URLSearchParams(window.location.search).get("force-update")),we=K?{current:P.apiStatus.version??"0.0.0",latest:K,url:"https://www.npmjs.com/package/@canonry/canonry",upgradeCommand:"npm install -g @canonry/canonry"}:P.apiStatus.updateAvailable,Xe=b&&we&&we.latest!==ee,nt=()=>{if(we){try{window.localStorage.setItem("canonry:dismissedUpdateVersion",we.latest)}catch{}B(we.latest)}},Ue=()=>{const re=!Z;try{re?window.localStorage.setItem("canonry:sidebarHidden","true"):window.localStorage.removeItem("canonry:sidebarHidden")}catch{}Y(re)},Pe=NZ(E),ke=Pe.data??null,$e=Pe.isLoading;C.useEffect(()=>{ke&&ke.status!=="running"&&ke.status!=="queued"&&j()},[ke?.status,j]),C.useEffect(()=>{L(!1)},[v.pathname]),C.useEffect(()=>{if(typeof window>"u"||!E&&!q)return;const re=lt=>{lt.key==="Escape"&&H()};return window.addEventListener("keydown",re),()=>{window.removeEventListener("keydown",re)}},[E,q,H]);const O=w??i?.dashboard??null,ne=v.pathname==="/setup",ge=ne&&O!==null&&O.portfolioOverview.projects.length===0,Se=ne&&(v.search.onboarding==="site-health"||v.search.onboarding==="first-run"||v.search.onboarding==="complete"),[ae,_e]=C.useState(ge);C.useEffect(()=>{ne?ge&&_e(!0):_e(!1)},[ge,ne]);const ve=ne&&(Se||ge||ae||ne&&O===null),le=ve?"app-shell-focus":Z?"app-shell-sidebar-hidden":"",ce=E?(O?JF(O,E):void 0)??(ke?Dm(ke,O?.projects.find(re=>re.project.id===ke.projectId)?.project.displayName??O?.projects.find(re=>re.project.id===ke.projectId)?.project.name??"Unknown project"):void 0):void 0,Q=C.useMemo(()=>HF(v.pathname,O),[v.pathname,O]),{commandCenter:me,evidenceLoading:De,evidenceError:je,isError:it,refetch:Ge}=jZ(q?Q:null,{evidence:!0}),jt=C.useMemo(()=>{if(q)return eZ(me,O,q)},[q,me,O]),He=(()=>{const re=v.pathname;if(re==="/")return"Portfolio";if(re==="/projects")return"Projects";if(re==="/runs")return"Runs";if(re==="/history")return"History";if(re==="/settings")return"Settings";if(re==="/setup")return"Setup";if(re==="/backlinks")return"Backlink data";if(re==="/traffic"||re.startsWith("/traffic/"))return"Traffic sources";if(re.startsWith("/projects/")){const lt=O?.projects.find(Gt=>Gt.project.name===Q);return lt?.project.displayName||lt?.project.name||Q||"Projects"}return"Not found"})();if(r){const re=!r.views||r.views.includes(PK(v.pathname));return l.jsxs("div",{className:"app-shell app-shell-embed","data-theme":VK(r.theme),style:$K(r.theme),children:[l.jsx("a",{className:"skip-link",href:"#content",children:"Skip to content"}),l.jsx("main",{id:"content",className:"page-shell",children:re?l.jsx(Tf,{}):l.jsx("div",{className:"embed-view-unavailable",role:"status",children:"This view is not available in embed mode."})})]})}return l.jsxs(l.Fragment,{children:[l.jsx("a",{className:"skip-link",href:"#content",children:"Skip to content"}),l.jsx(IZ,{}),l.jsxs("div",{className:`app-shell ${le}${Er()?" app-shell-demo":""}`,children:[!ve&&!Z&&l.jsxs("aside",{id:"desktop-sidebar",className:"sidebar","aria-label":"Primary navigation",children:[l.jsx("div",{className:"sidebar-brand",children:l.jsx(ok,{version:P.apiStatus.version,updateAvailable:Xe?we:null,onDismissUpdate:nt})}),l.jsxs("nav",{className:"sidebar-nav",children:[l.jsxs(We,{to:"/",className:"sidebar-link",activeProps:{className:"sidebar-link sidebar-link-active"},activeOptions:{exact:!0},children:[l.jsx(r5,{className:"sidebar-icon"}),l.jsx("span",{children:"Portfolio"})]}),l.jsxs(We,{to:"/projects",className:"sidebar-link",activeProps:{className:"sidebar-link sidebar-link-active"},activeOptions:{exact:!1},children:[l.jsx(l5,{className:"sidebar-icon"}),l.jsx("span",{children:"Projects"})]}),l.jsxs(We,{to:"/runs",className:"sidebar-link",activeProps:{className:"sidebar-link sidebar-link-active"},activeOptions:{exact:!0},children:[l.jsx(c5,{className:"sidebar-icon"}),l.jsx("span",{children:"Runs"})]}),l.jsxs(We,{to:"/history",className:"sidebar-link",activeProps:{className:"sidebar-link sidebar-link-active"},activeOptions:{exact:!0},children:[l.jsx(Hk,{className:"sidebar-icon"}),l.jsx("span",{children:"History"})]}),l.jsxs(We,{to:"/traffic",className:"sidebar-link",activeProps:{className:"sidebar-link sidebar-link-active"},activeOptions:{exact:!1},children:[l.jsx(u5,{className:"sidebar-icon"}),l.jsx("span",{children:"Traffic sources"})]}),!Er()&&l.jsxs(We,{to:"/backlinks",className:"sidebar-link",activeProps:{className:"sidebar-link sidebar-link-active"},activeOptions:{exact:!0},children:[l.jsx(d5,{className:"sidebar-icon"}),l.jsx("span",{children:"Backlink data"})]}),n&&l.jsxs(We,{to:"/settings",className:"sidebar-link",activeProps:{className:"sidebar-link sidebar-link-active"},activeOptions:{exact:!0},children:[l.jsx(m5,{className:"sidebar-icon"}),l.jsx("span",{children:"Settings"})]}),k?l.jsxs(l.Fragment,{children:[l.jsx("p",{className:"sidebar-section-title",children:"Tracked projects"}),[1,2,3].map(re=>l.jsxs("div",{className:"sidebar-skeleton-item",children:[l.jsx("span",{className:"skeleton-circle size-2"}),l.jsx("span",{className:"skeleton-text flex-1",style:{width:`${50+re*15}%`}})]},re))]}):O&&O.projects.length>0?l.jsxs(l.Fragment,{children:[l.jsx("p",{className:"sidebar-section-title",children:"Tracked projects"}),O.projects.map(re=>{const lt=re.visibilitySummary.tone;return l.jsxs(We,{to:"/projects/$projectName",params:{projectName:re.project.name},className:"sidebar-project",activeProps:{className:"sidebar-project sidebar-project-active"},children:[l.jsx("span",{className:`sidebar-dot sidebar-dot-${lt}`}),l.jsx("span",{children:re.project.displayName||re.project.name})]},re.project.id)})]}):k?null:l.jsxs(l.Fragment,{children:[l.jsx("p",{className:"sidebar-section-title",children:"Resources"}),n&&l.jsxs(We,{to:"/setup",className:"sidebar-link",activeProps:{className:"sidebar-link sidebar-link-active"},activeOptions:{exact:!0},children:[l.jsx(p5,{className:"sidebar-icon"}),l.jsx("span",{children:"Setup"})]})]})]}),e&&l.jsxs("div",{className:"sidebar-account",children:[l.jsxs("div",{className:"sidebar-account-identity",children:[l.jsx("span",{className:"sidebar-account-name",children:e.name}),e.role==="viewer"?l.jsx("span",{className:"sidebar-account-role",children:Bw()}):null]}),l.jsx(ue,{type:"button",variant:"ghost",size:"sm",onClick:pn(async()=>{await Uw(),window.location.reload()}),children:"Sign out"})]}),u?l.jsx("div",{className:"sidebar-footer",children:Sk.map(({label:re,href:lt,Icon:Gt})=>l.jsx("a",{className:"sidebar-footer-icon",href:lt,target:"_blank",rel:"noopener noreferrer",title:re,"aria-label":re,children:l.jsx(Gt,{className:"size-4"})},lt))}):null]}),l.jsxs("div",{className:"main-area",children:[l.jsxs("header",{className:"topbar",children:[l.jsxs("div",{className:"topbar-left",children:[!ve&&l.jsx(ue,{className:"sidebar-privacy-toggle",variant:"ghost",size:"icon",type:"button","aria-label":Z?"Show sidebar":"Hide sidebar","aria-controls":Z?void 0:"desktop-sidebar","aria-expanded":!Z,title:Z?"Show sidebar":"Hide sidebar",onClick:Ue,children:Z?l.jsx(g5,{className:"size-4"}):l.jsx(y5,{className:"size-4"})}),l.jsx("div",{className:"topbar-brand-mobile",children:l.jsx(ok,{compact:!0})}),l.jsxs("nav",{className:"breadcrumb","aria-label":"Breadcrumb",children:[l.jsx(We,{to:"/",children:"Home"}),l.jsx(Ng,{className:"breadcrumb-sep size-3"}),l.jsx("span",{className:"breadcrumb-current",children:He})]})]}),l.jsxs("div",{className:"topbar-actions",children:[l.jsx(OZ,{}),l.jsxs("div",{className:"health-pill-row",children:[l.jsxs("span",{className:`health-pill health-pill-${P.apiStatus.state}`,title:Vr(P.apiStatus),children:["API ",P.apiStatus.state==="ok"?"ok":P.apiStatus.state]}),l.jsx("span",{className:`health-pill health-pill-${P.workerStatus.state}`,title:Vr(P.workerStatus),children:`Worker ${P.workerStatus.state==="ok"?"ok":P.workerStatus.state}`})]}),ve?null:l.jsxs(ue,{className:"nav-toggle",variant:"secondary",size:"icon",type:"button","aria-expanded":X,"aria-controls":"mobile-nav",onClick:()=>L(re=>!re),children:[l.jsx(b5,{className:"size-4"}),l.jsx("span",{className:"sr-only",children:"Open navigation"})]})]})]}),ve?null:l.jsxs("div",{id:"mobile-nav",className:`mobile-nav ${X?"mobile-nav-open":""}`,children:[l.jsxs(ue,{className:"mobile-nav-close",variant:"ghost",size:"icon",type:"button",onClick:()=>L(!1),children:[l.jsx($r,{className:"size-5"}),l.jsx("span",{className:"sr-only",children:"Close navigation"})]}),l.jsx(We,{to:"/",className:"mobile-nav-link",activeProps:{className:"mobile-nav-link mobile-nav-link-active"},activeOptions:{exact:!0},children:"Portfolio"}),l.jsx(We,{to:"/projects",className:"mobile-nav-link",activeProps:{className:"mobile-nav-link mobile-nav-link-active"},activeOptions:{exact:!1},children:"Projects"}),l.jsx(We,{to:"/runs",className:"mobile-nav-link",activeProps:{className:"mobile-nav-link mobile-nav-link-active"},activeOptions:{exact:!0},children:"Runs"}),l.jsx(We,{to:"/history",className:"mobile-nav-link",activeProps:{className:"mobile-nav-link mobile-nav-link-active"},activeOptions:{exact:!0},children:"History"}),l.jsx(We,{to:"/traffic",className:"mobile-nav-link",activeProps:{className:"mobile-nav-link mobile-nav-link-active"},activeOptions:{exact:!1},children:"Traffic sources"}),!Er()&&l.jsx(We,{to:"/backlinks",className:"mobile-nav-link",activeProps:{className:"mobile-nav-link mobile-nav-link-active"},activeOptions:{exact:!0},children:"Backlink data"}),n&&l.jsx(We,{to:"/settings",className:"mobile-nav-link",activeProps:{className:"mobile-nav-link mobile-nav-link-active"},activeOptions:{exact:!0},children:"Settings"}),O&&O.projects.length>0?l.jsxs("div",{className:"mobile-nav-section",children:[l.jsx("p",{className:"mobile-nav-section-title",children:"Tracked projects"}),O.projects.map(re=>l.jsx(We,{to:"/projects/$projectName",params:{projectName:re.project.name},className:"mobile-nav-link",children:re.project.name},re.project.id))]}):null,e&&l.jsxs("div",{className:"mobile-nav-section",children:[l.jsx("p",{className:"mobile-nav-section-title",children:"Signed in"}),l.jsxs("div",{className:"sidebar-account",children:[l.jsxs("div",{className:"sidebar-account-identity",children:[l.jsx("span",{className:"sidebar-account-name",children:e.name}),e.role==="viewer"?l.jsx("span",{className:"sidebar-account-role",children:Bw()}):null]}),l.jsx(ue,{type:"button",variant:"ghost",size:"sm","data-testid":"mobile-sign-out",onClick:pn(async()=>{await Uw(),window.location.reload()}),children:"Sign out"})]})]})]}),l.jsx("main",{id:"content",className:`page-shell ${f&&Q?"pb-20":""}`.trim(),children:k&&!i?l.jsxs("div",{className:"page-skeleton",children:[l.jsxs("div",{className:"page-skeleton-header",children:[l.jsx("div",{className:"skeleton-text h-6 w-40"}),l.jsx("div",{className:"skeleton-text-sm w-72"})]}),l.jsx("div",{className:"page-skeleton-grid",children:[1,2,3].map(re=>l.jsxs("div",{className:"page-skeleton-card",children:[l.jsx("div",{className:"skeleton-text w-24"}),l.jsx("div",{className:"skeleton-text w-full"}),l.jsx("div",{className:"skeleton-text-sm w-3/4"})]},re))}),l.jsx("div",{className:"page-skeleton-grid",style:{gridTemplateColumns:"1fr 1fr"},children:[1,2].map(re=>l.jsxs("div",{className:"page-skeleton-card",children:[l.jsx("div",{className:"skeleton-text w-20"}),l.jsx("div",{className:"space-y-2",children:[1,2,3].map(lt=>l.jsx("div",{className:"skeleton-text-sm w-full"},lt))})]},re))})]}):l.jsx(Tf,{})}),l.jsxs("footer",{className:"footer",children:[l.jsxs("span",{className:"footer-brand",children:[l.jsx("span",{children:l.jsx("a",{href:"https://canonry.ai",children:"Canonry"})}),P.apiStatus.version&&P.apiStatus.version!=="unknown"?l.jsxs("span",{className:"footer-version",children:["v",P.apiStatus.version]}):null]}),u?l.jsx("div",{className:"footer-links",children:Sk.map(({label:re,href:lt,Icon:Gt})=>l.jsx("a",{href:lt,target:"_blank",rel:"noopener noreferrer",title:re,"aria-label":re,className:"footer-icon",children:l.jsx(Gt,{className:"size-3.5"})},lt))}):null]})]}),E&&!ce&&$e?l.jsx(hd,{open:!0,title:"Loading run details",subtitle:"Fetching the durable run record",onClose:H,children:l.jsx("p",{className:"text-sm text-muted",role:"status",children:"Loading run details…"})}):null,E&&!ce&&Pe.isError?l.jsx(hd,{open:!0,title:"Run unavailable",subtitle:"The run could not be loaded",onClose:H,children:l.jsx("p",{className:"text-sm text-negative",children:Pe.error instanceof Error?Pe.error.message:"Run details are unavailable."})}):null,ce?l.jsxs(hd,{open:!0,title:ce.summary,subtitle:`${ce.projectName} · ${ce.kindLabel}`,onClose:H,children:[l.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1 text-sm",children:[l.jsx(u1,{status:ce.status}),l.jsx("span",{className:"text-secondary",children:ce.startedAt}),l.jsx("span",{className:"text-muted",children:ce.duration}),l.jsx("span",{className:"text-faint",children:ce.triggerLabel})]}),ce.status==="failed"&&ce.statusDetail&&l.jsx("p",{className:"mt-2 text-sm text-negative",children:ce.statusDetail}),l.jsxs("div",{className:"mt-4",children:[l.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-2",children:"Activity Log"}),$e?l.jsx("p",{className:"text-sm text-muted",children:"Loading run details..."}):ke?.snapshots&&ke.snapshots.length>0?l.jsxs("div",{className:"space-y-2",children:[ke.snapshots.map(re=>l.jsxs("div",{className:"rounded-lg border border-default bg-surface p-3",children:[l.jsxs("div",{className:"flex items-center justify-between gap-2 mb-1",children:[l.jsx("p",{className:"text-sm font-medium text-strong truncate",children:re.query??"Unknown query"}),l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx(IF,{provider:re.provider}),l.jsx(bC,{variant:re.citationState===Pd.cited?"success":"neutral",children:re.citationState})]})]}),re.model&&l.jsx("p",{className:"text-[11px] text-muted font-mono",children:re.model}),re.citedDomains.length>0&&l.jsxs("p",{className:"text-xs text-muted mt-1",children:[l.jsx("span",{className:"text-secondary",children:"Sources:"})," ",re.citedDomains.join(", ")]}),re.citedCompetitorDomains.length>0&&l.jsxs("p",{className:"text-xs text-negative-400/80 mt-0.5",children:["Competitor cited: ",re.citedCompetitorDomains.join(", ")]}),re.mentionedCompetitorDomains.length>0&&l.jsxs("p",{className:"text-xs text-negative-400/80 mt-0.5",children:["Competitor mentioned: ",re.mentionedCompetitorDomains.join(", ")]}),re.groundingSources&&re.groundingSources.length>0&&l.jsxs("details",{className:"mt-2",children:[l.jsxs("summary",{className:"text-xs text-muted cursor-pointer hover:text-secondary",children:[re.groundingSources.length," grounding source",re.groundingSources.length!==1?"s":""]}),l.jsx("ul",{className:"mt-2 space-y-3",children:re.groundingSources.map((lt,Gt)=>l.jsx("li",{className:"min-w-0",children:l.jsx(mg,{url:lt.uri,title:lt.title})},Gt))})]}),re.answerText&&l.jsxs("details",{className:"mt-1",children:[l.jsx("summary",{className:"text-xs text-muted cursor-pointer hover:text-secondary",children:"Answer preview"}),l.jsx("p",{className:"mt-1 text-xs text-secondary leading-relaxed whitespace-pre-wrap",children:re.answerText})]})]},re.id)),ke.status==="running"&&l.jsxs("div",{className:"flex items-center gap-2 p-3 text-sm text-muted",children:[l.jsx("span",{className:"inline-block h-2 w-2 rounded-full bg-caution-500 animate-pulse"}),"Running remaining queries..."]})]}):ke&&ke.status==="running"?l.jsxs("div",{className:"flex items-center gap-2 p-3 text-sm text-muted",children:[l.jsx("span",{className:"inline-block h-2 w-2 rounded-full bg-caution-500 animate-pulse"}),"Waiting for first query result..."]}):ke&&ke.status==="queued"?l.jsxs("div",{className:"flex items-center gap-2 p-3 text-sm text-muted",children:[l.jsx("span",{className:"inline-block h-2 w-2 rounded-full bg-mono-500 animate-pulse"}),"Run queued, waiting for execution slot..."]}):ke&&ke.error?l.jsxs("div",{className:"rounded-lg border border-negative-800/40 bg-negative-950/20 p-3",children:[l.jsx("p",{className:"text-sm font-medium text-negative mb-2",children:"Run failed"}),l.jsx("pre",{className:"max-h-48 overflow-y-auto whitespace-pre-wrap break-words font-mono text-xs leading-5 text-negative",children:DK(ke.error)})]}):l.jsx("p",{className:"text-sm text-muted",children:"No snapshot data available."})]})]}):null,q&&!jt?l.jsx(hd,{open:!0,title:De?"Loading answer":"Answer unavailable",subtitle:"Query evidence",onClose:H,children:De?l.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading answer…"}):l.jsxs(l.Fragment,{children:[l.jsx("p",{role:"alert",className:"text-sm text-secondary",children:je||it?"Could not load this answer.":"This answer is not in the available query evidence."}),l.jsx(ue,{type:"button",variant:"outline",onClick:()=>{Ge()},children:"Retry"})]})}):null,jt?l.jsx(UF,{evidence:jt.evidence,project:jt.project,onClose:H}):null,l.jsx(zY,{}),l.jsx(EZ,{}),f?l.jsx(CY,{}):null]})]})}class OY extends C.Component{state={error:null};static getDerivedStateFromError(n){return{error:n}}componentDidCatch(n,i){console.error("[ErrorBoundary]",n,i.componentStack)}handleReset=()=>{this.setState({error:null})};render(){return this.state.error?l.jsx("div",{className:"page-container",children:l.jsxs("div",{className:"flex flex-col items-center justify-center gap-4 py-20 text-center",children:[l.jsx("div",{className:"rounded-full bg-negative-950/40 p-3",children:l.jsx(Qk,{className:"size-6 text-negative-400"})}),l.jsx("h2",{className:"text-lg font-semibold text-heading",children:"Something went wrong"}),l.jsx("p",{className:"text-sm text-secondary max-w-md",children:this.state.error.message||"An unexpected error occurred while rendering this page."}),l.jsxs("div",{className:"flex gap-3 mt-2",children:[l.jsxs(ue,{variant:"secondary",size:"sm",onClick:this.handleReset,children:[l.jsx(v5,{className:"size-3.5 mr-1.5"}),"Try again"]}),l.jsx(ue,{variant:"secondary",size:"sm",onClick:()=>{const n=window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,"")??"";window.location.href=n||"/"},children:"Go home"})]})]})}):this.props.children}}const _a=C.forwardRef(({className:e,...n},i)=>l.jsx("div",{ref:i,className:Ia("rounded-xl border border-base bg-bg/75 shadow-[0_0_0_1px_var(--color-shadow-hairline)]",e),...n}));_a.displayName="Card";const Nr=C.forwardRef(({className:e,...n},i)=>l.jsx("div",{ref:i,className:Ia("flex flex-col gap-1.5 p-5",e),...n}));Nr.displayName="CardHeader";const TC=C.forwardRef(({className:e,...n},i)=>l.jsx("h3",{ref:i,className:Ia("font-medium tracking-tight text-primary",e),...n}));TC.displayName="CardTitle";const Fd=C.forwardRef(({className:e,...n},i)=>l.jsx("p",{ref:i,className:Ia("text-sm text-muted",e),...n}));Fd.displayName="CardDescription";const go=C.forwardRef(({className:e,...n},i)=>l.jsx("div",{ref:i,className:Ia("p-5 pt-0",e),...n}));go.displayName="CardContent";function bg({disabled:e,title:n,...i}){const{canWrite:r}=pa();return r?l.jsx(ue,{disabled:e,title:n,...i}):l.jsx(ue,{...i,disabled:!0,title:QA})}function h1({title:e,children:n}){const{isAdmin:i}=pa();return i?l.jsx(l.Fragment,{children:n}):l.jsxs(_a,{className:"surface-card mx-auto mt-8 max-w-lg",children:[l.jsxs(Nr,{children:[l.jsxs(TC,{children:[e," is for administrators"]}),l.jsx(Fd,{children:"Your account has view-only access. You can read everything this install has measured; changing how it is set up needs an administrator account."})]}),l.jsx(go,{children:l.jsx("p",{className:"supporting-copy",children:"If you need to make a change here, ask an administrator on this install."})})]})}function Kie(e,n,i){return{mode:n,scope:e.measurementScope,scopeKey:e.measurementScopeKey,marketKey:e.marketKey,queryClass:e.queryClass==="non-brand"?"non-brand":"branded",provider:e.provider,model:e.model,location:e.location,runId:e.measurementRunId,revision:e.revision,evaluationDefinitionId:i}}function Hie(e,n,i){const r=[...new Set(n.filter(u=>!i||u.provider===i).map(u=>u.sourceRunId).filter(u=>!!u))].sort();return{...e,mode:"simple",scope:"project",scopeKey:void 0,marketKey:void 0,provider:i||void 0,model:void 0,revision:void 0,runId:r.length===1?r[0]:void 0,runIds:r.length>1?r:void 0}}function hc(e,n,i,r){return["sentiment",e,n,i??null,r??null]}const EC=5e3,PY=new Set(["pending","running","waiting-to-retry"]);function Ck(e){return PY.has(e.state)}function qY(e){const n=e?.coverage.counts;return!!(n&&n.pending+n.running+n["waiting-to-retry"]>0)}function MY(e,n){return qY(e)||n?EC:!1}function BY(e,n,i=!0){const r=yt({queryKey:hc(e,"settings"),queryFn:()=>Sd(e),retry:!1,staleTime:0,refetchOnWindowFocus:"always"}),u=yt({queryKey:hc(e,"jobs"),queryFn:()=>dK(e),enabled:!!r.data?.actions.configure,retry:!1,refetchOnWindowFocus:"always",refetchInterval:w=>w.state.data?.jobs.some(Ck)?EC:!1}),h=!!u.data?.jobs.some(Ck),f=w=>{const k={...n,queryClass:w};return{queryKey:hc(e,"summary",k),queryFn:()=>oK(e,k),enabled:i&&!!(r.data?.enabled&&r.data.installEnabled),retry:!1,staleTime:0,refetchOnWindowFocus:"always",refetchInterval:j=>MY(j.state.data,h)}},b=yt(f("branded")),v=yt(f("non-brand"));return{settings:r,branded:b,nonBrand:v,jobs:u}}const Cs={branded:"Branded","non-brand":"Non-brand"},fc={states:{disabled:"Sentiment is disabled.","not-measured":"No sentiment assessments yet.",processing:"Sentiment classification is in progress.",canceled:"Sentiment work was canceled.",partial:"Sentiment results are partial.",failed:"Sentiment classification failed.",complete:"Sentiment classification is complete.",unsupported:"Sentiment is unavailable for this selection."},noJudgments:"No evaluative answers were classified.",favorable:"Favorable answers divided by favorable, mixed, and unfavorable judgments. Factual, unmentioned, unsupported, and unclassified answers are not judgments. Branded and non-brand queries are measured separately."};function el(e){return e.replaceAll("-"," ").replace(/^./,n=>n.toUpperCase())}const vg=["branded","non-brand"];function qm(e){return e.interval?`${Xt(e.interval.low,bt.fraction)} to ${Xt(e.interval.high,bt.fraction)}`:null}function LY({value:e,label:n}){const i=qm(e.score);return l.jsxs("div",{role:"group","aria-label":`${n} favorable share`,children:[l.jsx("span",{className:"font-mono text-lg text-primary",children:e.score.favorableDisplay}),l.jsxs("span",{className:"ml-2 text-sm text-secondary",children:[e.coverage.judged," judged"]}),e.provisional&&l.jsx("span",{className:"ml-2 text-sm text-secondary",children:"Provisional"}),i&&l.jsxs("span",{className:"block text-sm text-secondary",children:["95% interval ",i]})]})}function RC(e){return!!e?.configured&&!MA()}function VY({queryClass:e,headline:n,primary:i}){const r=qm(n.score),u=n.score.interval?`${Xt(n.score.interval.low,bt.fraction)}–${Xt(n.score.interval.high,bt.fraction)}`:null;return l.jsxs("div",{role:"group","aria-label":`${Cs[e]} favorable share`,...i?{"data-sentiment-primary":""}:{},children:[l.jsxs("p",{className:"flex items-baseline justify-between gap-1",children:[l.jsx("span",{className:"text-[12px] text-secondary",children:Cs[e]}),l.jsxs("span",{className:`whitespace-nowrap font-mono ${i?"text-base font-semibold text-heading":"text-[13px] text-primary"}`,children:[n.score.favorableDisplay,n.provisional&&l.jsx("span",{role:"img","aria-label":"Provisional",className:"ml-0.5 text-caution",children:"*"})]})]}),l.jsxs("p",{className:"truncate text-[11px] leading-4 text-faint",title:`${n.coverage.judged} judged${r?`, 95% interval ${r}`:""}`,children:[n.coverage.judged," judged",u&&l.jsxs(l.Fragment,{children:[" · ",l.jsx("span",{className:"sr-only",children:"95% interval "}),u]})]})]})}function $Y({value:e}){if(!RC(e))return null;const n={branded:e.branded,"non-brand":e.nonBrand},i=[fc.favorable,...vg.map(r=>{const u=n[r],h=qm(u.score);return`${Cs[r]}: ${u.score.favorableDisplay}, ${u.coverage.judged} of ${u.coverage.selected} judged${h?`, 95% interval ${h}`:""}. ${u.provisional?"Provisional. ":""}${fc.states[u.state]}${u.reason?` ${u.reason}`:""}`})].join(" ");return l.jsx("div",{className:"project-row-stat","data-sentiment-score":!0,children:l.jsxs("div",{className:"grid gap-y-1",children:[l.jsxs("div",{className:"flex items-center",children:[l.jsx("p",{className:"metric-inline-label",children:"Favorable"}),l.jsx("span",{className:"relative z-10",children:l.jsx(Ua,{text:i,placement:"bottom"})})]}),vg.map((r,u)=>l.jsx(VY,{queryClass:r,headline:n[r],primary:u===0},r))]})})}const Io=C.createContext(null);function Qie(){return C.useContext(Io)?.configured??!1}function Fie({projectName:e,selection:n,runOptions:i=[],waitForResolvedRun:r=!1,evidenceReady:u=!0,hasSourceEvidence:h=!0,children:f}){return l.jsx(UY,{projectName:e,selection:n,runOptions:i,waitForResolvedRun:r,evidenceReady:u,hasSourceEvidence:h,children:f})}function UY({projectName:e,selection:n,runOptions:i,waitForResolvedRun:r,evidenceReady:u,hasSourceEvidence:h,children:f}){const b=JSON.stringify([e,n]),[v,w]=C.useState(null),k=C.useCallback(Pe=>w(ke=>ke?.key===b&&ke?.runId===Pe?.runId&&ke?.revision===Pe?.revision?ke:Pe?{...Pe,key:b}:null),[b]),j=u&&(!r||v?.key===b),T=r&&j&&v?{...n,runId:v.runId,revision:v.revision}:n,N=JSON.stringify([e,T]),{settings:P,branded:E,nonBrand:q,jobs:H}=BY(e,T,j&&h),[X,L]=C.useState(!1),[Z,Y]=C.useState(null),ee=C.useRef(null);C.useEffect(()=>{L(!1),Y(null)},[N]);const B=j&&!!(P.data?.enabled&&P.data.installEnabled),we=(n.queryClass==="non-brand"?q.data:E.data)?.selection,Xe={...T,...we?{...we,runId:we.runId??void 0,runIds:we.runId?void 0:we.runIds,revision:we.revision??void 0,evaluationDefinitionId:we.evaluationDefinitionId??void 0}:{}},nt=Xe.runId&&!i.some(Pe=>Pe.id===Xe.runId)?[{id:Xe.runId,label:"Displayed sweep"},...i]:i,Ue=Pe=>{Pe.preventDefault(),ee.current?.focus()};return l.jsxs(Io.Provider,{value:{projectName:e,selection:T,resolveSource:k,settings:P,summaries:{branded:E,"non-brand":q},configured:B,hasSourceEvidence:h,openManage:Pe=>{ee.current=Pe,L(!0)},openEvidence:(Pe,ke,$e)=>{ee.current=$e,Y({selection:Pe,label:ke})}},children:[f,l.jsx(ug,{open:X&&!!P.data?.actions.configure,onOpenChange:L,children:l.jsxs(Kd,{onCloseAutoFocus:Ue,className:"overflow-y-auto",children:[l.jsxs(dg,{children:[l.jsx(Hd,{children:"Manage sentiment"}),l.jsx(Qd,{children:"Classify saved answers and review the cost before submitting a backfill."})]}),P.data?.actions.configure&&l.jsx(eX,{projectName:e,settings:P.data,selection:Xe,runOptions:nt},JSON.stringify([P.data.evaluationDefinitionId,P.data.enabled,P.data.enablementEpoch])),H.data&&l.jsx(ZY,{projectName:e,jobs:H.data.jobs})]})}),l.jsx(ug,{open:Z!==null,onOpenChange:Pe=>{Pe||Y(null)},children:l.jsxs(Kd,{onCloseAutoFocus:Ue,className:"overflow-y-auto",children:[l.jsxs(dg,{children:[l.jsxs(Hd,{children:["Sentiment evidence",Z?`: ${Z.label}`:""]}),l.jsx(Qd,{children:"Stored judgments and exact quotations for the selected query and scope."})]}),Z&&l.jsx(HY,{projectName:e,selection:Z.selection},JSON.stringify(Z.selection))]})})]})}function Zie(e,n){const i=C.useContext(Io)?.resolveSource;C.useEffect(()=>{i?.(e?{runId:e,revision:n??void 0}:null)},[i,e,n])}function Yie(){const e=C.useContext(Io);return e?.settings.data?.actions.configure?l.jsx(bg,{type:"button",variant:"outline",size:"sm",onClick:n=>e.openManage(n.currentTarget),children:e.settings.data.enabled?"Manage sentiment":"Enable sentiment"}):null}function Xie({queryClass:e="all"}){const n=C.useContext(Io);if(!n?.configured||e==="unknown"||e==="unclassified")return null;const i=e==="all"?vg:[e];return l.jsx("div",{className:"mb-4 flex flex-wrap items-start gap-x-8 gap-y-3","aria-label":"Favorable answer scores",children:i.map(r=>{const u=n.summaries[r];return l.jsxs("div",{children:[l.jsxs("div",{className:"mb-1 flex items-center gap-2",children:[l.jsxs("span",{className:"text-sm text-secondary",children:["Favorable · ",Cs[r]]}),l.jsx(Ua,{text:fc.favorable})]}),n.hasSourceEvidence?u.data?l.jsxs(l.Fragment,{children:[l.jsx(LY,{value:u.data,label:Cs[r]}),l.jsxs("details",{className:"mt-1 text-sm text-secondary",children:[l.jsx("summary",{className:"cursor-pointer",children:"Coverage and method"}),l.jsxs("p",{children:[u.data.coverage.judged," judged of ",u.data.coverage.selected," selected assessments; ",u.data.coverage.distinctSourceAnswers," distinct source answers."]}),l.jsxs("p",{children:[u.data.coverage.eligibleAssessments," eligible; ",u.data.coverage.unadmittedAssessments," awaiting admission."]}),l.jsx("p",{children:u.data.state==="complete"&&u.data.coverage.judged===0?fc.noJudgments:fc.states[u.data.state]}),u.data.reason&&l.jsx("p",{children:u.data.reason}),Object.entries(u.data.coverage.counts).filter(([h,f])=>f>0&&!["favorable","mixed","unfavorable"].includes(h)).map(([h,f])=>l.jsxs("p",{children:[el(h),": ",f]},h)),l.jsx("p",{children:n.settings.data?.disclosure}),l.jsxs("p",{children:["95% Wilson interval: ",qm(u.data.score)??"Unavailable"]}),l.jsx("p",{children:u.data.score.limitation})]})]}):u.isError?l.jsxs("p",{role:"alert",className:"text-sm text-secondary",children:["Favorable score unavailable. ",l.jsx(ue,{variant:"ghost",onClick:()=>{u.refetch()},children:"Retry score"})]}):l.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading favorable score…"}):l.jsx("p",{className:"text-sm text-secondary",children:"Unavailable"})]},r)})})}function Jie({queryId:e,sourceSnapshotIds:n=[],queryClass:i,location:r,showLabel:u=!1}){const h=C.useContext(Io);if(!h?.configured)return null;const f=i?h.summaries[i]:void 0,b=h.hasSourceEvidence?f?.data:void 0,v=b?.queries.filter(T=>T.queryClass===i&&(e?T.queryId===e:n.length>0)&&n.every(N=>T.sourceSnapshotIds.includes(N)))??[],w=v.length===1?v[0]:void 0,k=r===void 0?w:w?.locations.find(T=>T.location===r);if(!w||!k)return l.jsx("span",{className:"text-sm text-secondary",children:h.hasSourceEvidence&&f?.isPending&&(e||n.length)?"Loading…":"Unavailable"});const j={...h.selection,...b.selection,runId:b.selection.runId??void 0,runIds:b.selection.runId?void 0:b.selection.runIds,revision:b.selection.revision??void 0,evaluationDefinitionId:b.selection.evaluationDefinitionId??void 0,queryClass:w.queryClass,queryId:w.queryId,executionNodeKey:w.executionNodeKey??void 0,...r===void 0?{}:{location:r??"none"}};return l.jsxs(ue,{type:"button",variant:"ghost",className:"h-auto min-h-11 flex-col items-start gap-0 px-1","aria-label":`View ${Cs[w.queryClass]} sentiment evidence for ${w.queryText}`,onKeyDown:T=>T.stopPropagation(),onClick:T=>{T.stopPropagation(),h.openEvidence(j,w.queryText,T.currentTarget)},children:[u&&l.jsx("span",{className:"text-sm font-normal text-secondary",children:"Favorable"}),l.jsx("span",{className:"font-mono text-primary",children:k.score.favorableDisplay}),l.jsxs("span",{className:"text-sm font-normal text-secondary",children:[k.coverage.judged," judged"]}),k.provisional&&l.jsx("span",{className:"text-xs font-normal text-caution",children:"Provisional"})]})}function GY(e){return e.outcome==="subject-not-mentioned"?"Not mentioned":e.outcome==="running"?"Classifying":e.outcome==="waiting-to-retry"?"Retrying":e.outcome?el(e.outcome):e.state==="not-measured"?"Not classified":e.state==="processing"?"Classifying":e.state==="failed"?"Failed":e.state==="canceled"?"Canceled":"Unavailable"}function Wie({queryId:e,sourceSnapshotIds:n,queryClass:i,provider:r,model:u,location:h,showSubjects:f=!1,showLabel:b=!1}){const v=C.useContext(Io);if(!v?.configured)return null;const w=i?v.summaries[i]:void 0,k=v.hasSourceEvidence?w?.data:void 0,j=k?.queries.filter(P=>P.queryClass===i&&(!e||P.queryId===e)&&n.length>0&&n.every(E=>P.sourceSnapshotIds.includes(E)))??[],T=j.length===1?j[0]:void 0,N=T?.assessments?.filter(P=>n.includes(P.sourceSnapshotId)&&P.provider===r&&P.location===h&&(u===void 0||P.servedModel===u))??[];return l.jsxs("div",{role:"group",className:"text-sm text-secondary","aria-label":`${r||"Saved answer"} sentiment`,children:[b&&l.jsx("span",{className:"block text-sm text-secondary",children:"Sentiment"}),N.length?N.map(P=>{const E=GY(P),q=P.outcome==="favorable"?"positive":P.outcome==="unfavorable"?"negative":P.outcome==="mixed"?"caution":"neutral",H=l.jsxs(l.Fragment,{children:[f&&l.jsxs("span",{children:[P.subjectLabel," · "]}),l.jsx(bn,{tone:q,className:"max-w-full shrink-0 rounded-none border-0 bg-transparent p-0 text-sm font-normal tracking-normal [overflow-wrap:normal]",children:E})]}),X={...v.selection,...k.selection,runId:k.selection.runId??void 0,runIds:k.selection.runId?void 0:k.selection.runIds,revision:k.selection.revision??void 0,evaluationDefinitionId:k.selection.evaluationDefinitionId??void 0,queryClass:T.queryClass,queryId:T.queryId,executionNodeKey:T.executionNodeKey??void 0,assessmentId:P.assessmentId??void 0};return l.jsxs("div",{className:"flex items-center gap-1",children:[P.assessmentId?l.jsx(ue,{type:"button",variant:"ghost",className:"h-auto min-h-11 flex-wrap justify-start whitespace-normal px-1 text-left text-sm","aria-label":`View ${P.provider} sentiment evidence for ${P.subjectLabel}: ${E}`,onKeyDown:L=>L.stopPropagation(),onClick:L=>{L.stopPropagation(),v.openEvidence(X,`${T.queryText} · ${P.provider} · ${P.subjectLabel}`,L.currentTarget)},children:H}):l.jsx("span",{children:H}),P.reason&&l.jsx(Ua,{text:P.reason})]},JSON.stringify([P.sourceSnapshotId,P.subjectId,P.assessmentId]))}):l.jsx("span",{children:v.hasSourceEvidence&&w?.isPending&&n.length?"Loading…":"Unavailable"})]})}function KY({item:e}){return l.jsxs("article",{className:"space-y-4 border-b border-default py-5 text-sm text-secondary",children:[l.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[l.jsx("strong",{className:"text-primary",children:e.subject.displayName}),l.jsx(bn,{tone:"neutral",children:el(e.outcome)}),l.jsx("span",{children:Cs[e.context.queryClass]}),l.jsx("span",{children:e.context.provider}),l.jsx("span",{children:e.context.servedModel??"Source model unavailable"}),l.jsx("span",{children:e.context.location??"No location"})]}),e.reason&&l.jsx("p",{children:e.reason}),l.jsxs("section",{children:[l.jsx("h3",{className:"mb-2 text-heading",children:"Conclusion evidence"}),e.conclusion.length?e.conclusion.map(n=>l.jsx("blockquote",{className:"mb-2 border-l border-strong pl-3 text-primary",children:n.text},`${n.id}:${n.start}`)):l.jsx("p",{children:"No valid conclusion evidence is available."})]}),l.jsxs("section",{children:[l.jsx("h3",{className:"mb-2 text-heading",children:"Complaint evidence"}),e.complaint?.length?e.complaint.map(n=>l.jsx("blockquote",{className:"mb-2 border-l border-strong pl-3 text-primary",children:n.text},`${n.id}:${n.start}`)):l.jsx("p",{children:"No complaint was identified."})]}),l.jsxs("details",{children:[l.jsx("summary",{className:"cursor-pointer",children:"Original source answer"}),l.jsx("p",{className:"mt-2 whitespace-pre-wrap break-words text-primary",children:e.sourceText})]}),l.jsxs("details",{children:[l.jsx("summary",{className:"cursor-pointer",children:"Assessment provenance"}),l.jsxs("dl",{className:"mt-3 space-y-2 break-all",children:[l.jsx("dt",{children:"Query"}),l.jsx("dd",{children:e.context.queryText}),l.jsx("dt",{children:"Subject"}),l.jsxs("dd",{children:[e.subject.displayName," (",e.subject.id,")"]}),l.jsx("dt",{children:"Run"}),l.jsx("dd",{children:e.runId}),l.jsx("dt",{children:"Revision"}),l.jsx("dd",{children:e.context.revision??"Unavailable"}),l.jsx("dt",{children:"Evaluator"}),l.jsx("dd",{children:e.returnedModel??"Unavailable"}),l.jsx("dt",{children:"Evaluation definition"}),l.jsx("dd",{children:e.evaluationDefinitionId}),l.jsx("dt",{children:"Source snapshot"}),l.jsx("dd",{children:e.sourceSnapshotId}),l.jsx("dt",{children:"Source hash"}),l.jsx("dd",{children:e.sourceTextHash}),e.context.usageEdges.map((n,i)=>l.jsxs("div",{children:[l.jsx("dt",{children:"Assignment"}),l.jsxs("dd",{children:["Target ",n.targetId,"; Property ",n.propertyId??"None","; market ",n.marketId??"None","; ",n.queryClass]})]},i))]})]})]})}function HY({projectName:e,selection:n}){const[i,r]=C.useState(),u=yt({queryKey:hc(e,"evidence",n,i),queryFn:()=>lK(e,n,i),retry:!1});return u.isPending?l.jsx("p",{role:"status",className:"mt-4 text-sm text-secondary",children:"Loading sentiment evidence…"}):u.isError?l.jsxs("p",{role:"alert",className:"mt-4 text-sm text-secondary",children:["Could not load sentiment evidence. ",l.jsx(ue,{variant:"outline",onClick:()=>{u.refetch()},children:"Retry evidence"})]}):l.jsxs(l.Fragment,{children:[u.data.items.length?u.data.items.map(h=>l.jsx(KY,{item:h},h.assessmentId)):l.jsx("p",{className:"mt-4 text-sm text-secondary",children:"No stored sentiment evidence for this query and scope."}),l.jsxs("div",{className:"mt-3 flex gap-2",children:[i&&l.jsx(ue,{variant:"outline",onClick:()=>r(void 0),children:"First evidence page"}),u.data.nextCursor&&l.jsx(ue,{variant:"outline",onClick:()=>r(u.data.nextCursor??void 0),children:"Next evidence page"})]})]})}function QY({projectName:e,jobId:n}){const[i,r]=C.useState(),u=yt({queryKey:hc(e,`job:${n}`,void 0,i),queryFn:()=>mK(e,n,i),retry:!1});return u.isPending?l.jsx("p",{role:"status",children:"Loading attempts…"}):u.isError?l.jsxs("p",{role:"alert",children:["Could not load attempts. ",l.jsx(ue,{variant:"outline",onClick:()=>{u.refetch()},children:"Retry attempts"})]}):l.jsxs(l.Fragment,{children:[u.data.attempts.map(h=>l.jsxs("p",{children:[h.errorCode??"Request complete","; ",h.usage.kind==="unknown"?"Usage unknown":`${h.usage.inputTokens??"Unknown"} input tokens (${h.usage.kind})`]},h.id)),l.jsxs("div",{className:"mt-2 flex gap-2",children:[i&&l.jsx(ue,{variant:"outline",onClick:()=>r(void 0),children:"Newest attempts"}),u.data.nextAttemptCursor&&l.jsx(ue,{variant:"outline",onClick:()=>r(u.data.nextAttemptCursor??void 0),children:"Older attempts"})]})]})}function FY({projectName:e,job:n}){const[i,r]=C.useState(!1);return l.jsxs("details",{onToggle:u=>r(u.currentTarget.open),children:[l.jsx("summary",{children:"Job details"}),n.cancellationReason&&l.jsx("p",{children:n.cancellationReason}),Object.entries(n.counts).filter(([,u])=>u>0).map(([u,h])=>l.jsxs("p",{children:[el(u),": ",h]},u)),l.jsxs("p",{children:["Attempts: ",n.attemptCount]}),i&&n.attemptCount>0&&l.jsx(QY,{projectName:e,jobId:n.id})]})}function ZY({projectName:e,jobs:n}){return l.jsxs("details",{className:"mt-6 text-sm text-secondary",children:[l.jsx("summary",{className:"cursor-pointer",children:"Recent sentiment jobs"}),n.length===0?l.jsx("p",{className:"mt-2",children:"No sentiment jobs have been submitted."}):l.jsx("div",{className:"data-table-wrapper mt-3",children:l.jsxs("table",{className:"data-table","aria-label":"Sentiment jobs",children:[l.jsx("thead",{children:l.jsxs("tr",{children:[l.jsx("th",{children:"Submitted"}),l.jsx("th",{children:"State"}),l.jsx("th",{children:"Selected"}),l.jsx("th",{children:"Details"})]})}),l.jsx("tbody",{children:n.map(i=>l.jsxs("tr",{children:[l.jsx("td",{children:IK(i.createdAt)}),l.jsx("td",{children:el(i.state)}),l.jsx("td",{children:i.selected}),l.jsx("td",{children:l.jsx(FY,{projectName:e,job:i})})]},i.id))})]})})]})}const YY={probe:"Probe sweeps","unsupported-run-kind":"Not an answer sweep","failed-run":"Failed sweep","incomplete-run":"Incomplete sweep","legacy-missing-provenance":"Saved without its frozen query and subject record","legacy-missing-language":"Saved before the answer language was recorded","excluded-branded":"Branded answers (backfill that class separately)","excluded-non-brand":"Non-brand answers (backfill that class separately)"};function XY(e){return YY[e]??el(e)}function DC(e){return[e.provider&&`engine ${e.provider}`,e.model&&`model ${e.model}`,e.location&&(e.location==="none"?"no location":`location ${e.location}`),e.scope!=="project"&&e.scopeKey&&`${e.scope} ${e.scopeKey}`,e.marketKey&&`market ${e.marketKey}`,e.queryId&&`query ${e.queryId}`,e.revision!==void 0&&`revision ${e.revision}`].filter(n=>!!n)}function JY(e){const n=DC(e);return[`${Cs[e.queryClass]} queries`,...n.length?n:["whole sweep"]].join(" · ")}function WY(e,n,i,r){return r?{...e,queryClass:i,queryId:void 0,runIds:void 0,runId:n}:{mode:"auto",scope:"project",queryClass:i,runId:n}}function eX({projectName:e,settings:n,selection:i,runOptions:r}){const u=Jn(),[h,f]=C.useState(n.enabled),[b,v]=C.useState(i.runId??""),[w,k]=C.useState(i.queryClass),[j,T]=C.useState(!1),[N,P]=C.useState(null),E=C.useRef(null),q=DC({...i,queryId:void 0}),H=()=>u.invalidateQueries({queryKey:["sentiment",e]}),X=()=>{P(null),E.current=null},L=Ga({mutationFn:async()=>{if(!(await Sd(e)).actions.configure)throw new Error("Administrator permission is required to configure sentiment.");return rK(e,{enabled:h})},onSuccess:async()=>{X(),await H(),await u.invalidateQueries({queryKey:["project-overview-slim"]})},onError:H}),Z=Ga({mutationFn:async()=>{if(!(await Sd(e)).actions.backfill)throw new Error("Administrator permission is required to backfill sentiment.");return cK(e,WY(i,b,w,j&&q.length>0))},onSuccess:B=>{P(B),E.current=crypto.randomUUID()},onError:H}),Y=Ga({mutationFn:async()=>{if(!N?.previewToken||!E.current)throw new Error("Create and review a backfill preview first.");if(!(await Sd(e)).actions.backfill)throw new Error("Administrator permission is required to backfill sentiment.");return uK(e,N.previewToken,E.current)},onSuccess:async()=>{X(),await H()},onError:H}),ee=L.isPending||Z.isPending||Y.isPending;return l.jsxs("div",{className:"mt-5 space-y-5 text-sm text-secondary",children:[l.jsx("p",{children:n.disclosure}),!n.ready&&l.jsx("p",{children:n.readinessReasons.join("; ")||"An operator must configure sentiment on this installation."}),l.jsxs("form",{className:"space-y-3",onSubmit:B=>{B.preventDefault(),L.mutate()},children:[l.jsxs("label",{className:"flex items-center gap-2",children:[l.jsx("input",{type:"checkbox",checked:h,disabled:ee,onChange:B=>{f(B.target.checked),X()}}),"Enable project sentiment"]}),l.jsx("p",{children:"Enabling applies to future completed sweeps. Past sweeps require an explicit backfill."}),l.jsx(bg,{type:"submit",disabled:ee,children:L.isPending?"Saving…":"Save sentiment settings"}),L.isError&&l.jsx("p",{role:"alert",children:zi(L.error)}),L.isSuccess&&l.jsx("p",{role:"status",children:"Sentiment settings saved."})]}),n.actions.backfill&&l.jsxs("section",{className:"space-y-3",children:[l.jsx("h3",{children:"Backfill a saved sweep"}),l.jsxs("label",{className:"block",children:["Saved sweep",l.jsxs("select",{className:"mt-1 block w-full rounded-md border border-default bg-bg p-2 text-primary",value:b,disabled:ee,onChange:B=>{v(B.target.value),X()},children:[l.jsx("option",{value:"",children:"Select a saved sweep"}),r.map(B=>l.jsx("option",{value:B.id,children:B.label},B.id))]})]}),l.jsxs("label",{className:"block",children:["Query class",l.jsxs("select",{className:"mt-1 block w-full rounded-md border border-default bg-bg p-2 text-primary",value:w,disabled:ee,onChange:B=>{k(B.target.value),X()},children:[l.jsx("option",{value:"non-brand",children:"Non-brand"}),l.jsx("option",{value:"branded",children:"Branded"})]})]}),l.jsx("p",{children:"The backfill covers every engine, location and query of the chosen sweep for this query class."}),q.length>0&&l.jsxs("label",{className:"flex items-start gap-2",children:[l.jsx("input",{type:"checkbox",className:"mt-1",checked:j,disabled:ee,onChange:B=>{T(B.target.checked),X()}}),l.jsxs("span",{children:["Limit to the current view",l.jsx("span",{className:"block",children:q.join(" · ")})]})]}),l.jsx(ue,{variant:"outline",disabled:ee||!b||!n.enabled||!n.ready,onClick:()=>{X(),Z.mutate()},children:Z.isPending?"Preparing preview…":"Preview sentiment backfill"}),Z.isError&&l.jsx("p",{role:"alert",children:zi(Z.error)}),N&&l.jsxs("div",{className:"space-y-3",children:[l.jsxs("dl",{className:"grid grid-cols-[1fr_auto] gap-2",children:[l.jsx("dt",{children:"Selection"}),l.jsx("dd",{className:"text-right",children:JY(N.selection)}),l.jsx("dt",{children:"Eligible assessments"}),l.jsx("dd",{children:N.eligibleAssessments}),l.jsx("dt",{children:"Already classified"}),l.jsx("dd",{children:N.alreadyClassified}),l.jsx("dt",{children:"Estimated input tokens"}),l.jsx("dd",{children:N.estimatedInputTokens}),l.jsx("dt",{children:"Estimated cost (USD)"}),l.jsx("dd",{children:N.estimatedCostUsd??"Unavailable"})]}),l.jsx(Ua,{text:N.estimateMethod}),N.eligibleAssessments===0&&l.jsx("p",{children:"No saved answers in this selection can be classified."}),N.skipped.length>0&&l.jsxs("div",{children:[l.jsx("p",{children:"Not included:"}),l.jsx("ul",{"aria-label":"Skipped assessments",className:"list-disc pl-5",children:N.skipped.map(B=>l.jsxs("li",{children:[XY(B.reason),": ",B.count]},`${B.runId}:${B.reason}`))})]}),l.jsx(bg,{disabled:ee||!N.previewToken||N.eligibleAssessments===0,onClick:()=>Y.mutate(),children:Y.isPending?"Submitting…":"Confirm sentiment backfill"})]}),Y.isError&&l.jsxs("p",{role:"alert",children:[zi(Y.error)," Retry uses the same request key."]}),Y.isSuccess&&l.jsx("p",{role:"status",children:"Backfill submitted. Progress is available in Recent jobs."})]})]})}const tX=20,nX=6;function aX({points:e,tone:n}){const i=C.useId();if(e.length===0)return null;const r=42,u=132,h=5,f=u-h*2,b=r-h*2,v=b-nX,w=q=>h+q/Math.max(e.length-1,1)*f,k=tG(e),j=Math.min(...e),T=Math.max(...e),N=Math.max(T-j,tX),P=(T+j)/2-N/2,E=e.map((q,H)=>({x:w(H),y:h+(1-(q-P)/N)*v}));return l.jsxs("svg",{className:`sparkline sparkline-${n}${k?" sparkline-provisional":""}`,viewBox:`0 0 ${u} ${r}`,"aria-hidden":"true",children:[l.jsx("defs",{children:l.jsx("clipPath",{id:i,children:l.jsx("rect",{x:h,y:h,width:f,height:b,rx:"8"})})}),l.jsx("line",{className:"sparkline-guide",x1:h,x2:u-h,y1:r-h,y2:r-h}),E.length===1?l.jsx("circle",{className:"sparkline-point",cx:E[0].x,cy:E[0].y,r:"3"}):l.jsx("polyline",{clipPath:`url(#${i})`,points:E.map(q=>`${q.x},${q.y}`).join(" "),vectorEffect:"non-scaling-stroke"})]})}function iX({project:e}){return l.jsxs("div",{className:`project-row relative${RC(e.sentiment)?" project-row-with-sentiment":""}`,children:[l.jsx("div",{className:"project-row-chart",children:l.jsx(aX,{points:e.trend,tone:WA(e.lastRun.status)})}),l.jsxs("div",{className:"project-row-primary",children:[l.jsxs(We,{to:"/projects/$projectName",params:{projectName:e.project.name},className:"after:absolute after:inset-0 after:rounded-xl focus-visible:outline-none focus-visible:after:ring-2 focus-visible:after:ring-mono-400",children:[l.jsx("p",{className:"project-name",children:e.project.name}),l.jsx("p",{className:"project-domain",children:e.project.canonicalDomain})]}),l.jsx("p",{className:"project-insight",children:e.insight})]}),l.jsx("div",{className:"project-row-stat",children:l.jsxs("div",{className:"metric-inline-block",children:[l.jsx("p",{className:"metric-inline-label",children:"Mentioned"}),l.jsx("p",{className:`metric-inline-value ${e.mentionTone==="caution"?"text-caution-400":""}`,children:e.hasMeasurement===!1?"Not measured":Xt(e.mentionScore,bt.percent)}),l.jsx("p",{className:`metric-inline-caption${e.providerCoverage?" text-caution":""}`,title:e.providerCoverage,children:e.providerCoverage?l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"sr-only",children:"Partial sweep: "}),e.providerCoverage]}):e.mentionDelta})]})}),l.jsx("div",{className:"project-row-stat",children:l.jsxs("div",{className:"metric-inline-block",children:[l.jsxs("p",{className:"metric-inline-label",children:[l.jsx("span",{"aria-hidden":"true",children:"Pressure"}),l.jsx("span",{className:"sr-only",children:"Competitor pressure"})]}),l.jsx("p",{className:"metric-inline-value",children:e.hasMeasurement===!1?"Not measured":e.competitorPressureLabel}),l.jsx("p",{className:"metric-inline-caption","aria-hidden":"true"})]})}),l.jsx($Y,{value:e.sentiment}),l.jsx("span",{className:"project-row-link",children:l.jsx(Ng,{className:"h-4 w-4 text-muted"})})]})}function sX(){const{isAdmin:e}=pa(),n=Uc(),{dashboard:i,isLoading:r,isError:u,refetch:h}=zm(),f=i??n?.dashboard,v=d1(!n,n?.health),{openRun:w}=m1();if(u&&!f)return l.jsxs("div",{className:"page-container",children:[l.jsx("div",{className:"page-header",children:l.jsxs("div",{className:"page-header-left",children:[l.jsx("h1",{className:"page-title",children:"Portfolio unavailable"}),l.jsx("p",{className:"page-subtitle",children:"Canonry could not load the project list."})]})}),l.jsxs("div",{className:"max-w-xl rounded-lg border border-negative bg-negative-soft p-4",role:"alert",children:[l.jsx("p",{className:"text-sm font-medium text-heading",children:"Your projects have not been changed."}),l.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Check the connection or sign in again, then retry."}),l.jsx(ue,{type:"button",variant:"secondary",className:"mt-4",onClick:()=>{h()},children:"Retry loading portfolio"})]})]});if(!f||r)return l.jsxs("div",{className:"page-skeleton",children:[l.jsxs("div",{className:"page-skeleton-header",children:[l.jsx("div",{className:"skeleton-text h-6 w-32"}),l.jsx("div",{className:"skeleton-text-sm w-64"})]}),l.jsx("div",{className:"space-y-3",children:[1,2,3].map(E=>l.jsxs("div",{className:"rounded-xl border border-default bg-surface p-4 flex items-center gap-4",children:[l.jsxs("div",{className:"flex-1 space-y-2",children:[l.jsx("div",{className:"skeleton-text w-36"}),l.jsx("div",{className:"skeleton-text-sm w-48"})]}),l.jsx("div",{className:"skeleton-text w-16"}),l.jsx("div",{className:"skeleton-text w-16"}),l.jsx("div",{className:"skeleton h-8 w-20 rounded"})]},E))})]});const k=f.portfolioOverview,j=k.projects.length>0&&k.projects.every(E=>E.hasMeasurement===!1),T=k.attentionItems.map(E=>j&&E.id==="attention_stable"?{...E,tone:"neutral",title:"Awaiting first measurement",detail:"Visibility results will appear after the first sweep."}:E),N=v.data??n?.health??{apiStatus:{label:"API",state:"checking",detail:"Checking service health"},workerStatus:{label:"Worker",state:"checking",detail:"Checking service health"}},P=TQ(k.systemHealth.filter(E=>e||E.id==="api"||E.id==="worker"),N,f.settings);return l.jsxs("div",{className:"page-container",children:[l.jsx("div",{className:"page-header",children:l.jsxs("div",{className:"page-header-left",children:[l.jsx("h1",{className:"page-title",children:"Portfolio"}),l.jsx("p",{className:"page-subtitle",children:"Visibility across all projects."})]})}),k.projects.length>0?l.jsx("div",{className:"project-list project-list-scrollable",children:k.projects.map(E=>l.jsx(iX,{project:E},E.project.id))}):l.jsxs(_a,{className:"surface-card empty-card",children:[l.jsx("h3",{children:k.emptyState?.title??"No projects yet"}),l.jsx("p",{className:"supporting-copy",children:k.emptyState?.detail}),l.jsx(ue,{size:"sm",asChild:!0,children:l.jsx(We,{to:k.emptyState?.ctaHref==="/setup"||!k.emptyState?.ctaHref?"/setup":"/",children:k.emptyState?.ctaLabel??"Launch setup"})})]}),l.jsxs("div",{className:"overview-secondary-grid",children:[T.length>0&&l.jsxs("section",{className:"overview-secondary-section",children:[l.jsx("div",{className:"section-head section-head-inline",children:l.jsxs("div",{children:[l.jsx("p",{className:"eyebrow eyebrow-soft",children:"Needs attention"}),l.jsx("h2",{className:"section-title-sm",children:"What changed"})]})}),l.jsx("div",{className:"attention-list attention-list-scrollable",children:T.map(E=>E.href?l.jsxs(We,{to:E.href,className:`attention-item attention-item-${E.tone}`,children:[l.jsxs("div",{children:[l.jsx("p",{className:"attention-title",children:E.title}),l.jsx("p",{className:"attention-detail",children:E.detail})]}),E.actionLabel&&l.jsx("span",{className:"attention-action",children:E.actionLabel})]},E.id):l.jsxs("div",{className:`attention-item attention-item-static attention-item-${E.tone}`,children:[l.jsxs("div",{children:[l.jsx("p",{className:"attention-title",children:E.title}),l.jsx("p",{className:"attention-detail",children:E.detail})]}),E.actionLabel&&l.jsx("span",{className:"attention-action",children:E.actionLabel})]},E.id))})]}),l.jsxs("section",{className:"overview-secondary-section",children:[l.jsx("div",{className:"section-head section-head-inline",children:l.jsxs("div",{children:[l.jsx("p",{className:"eyebrow eyebrow-soft",children:"Recent runs"}),l.jsx("h2",{className:"section-title-sm",children:"Activity"})]})}),l.jsx("div",{className:"compact-stack compact-stack-scrollable",children:k.recentRuns.length>0?k.recentRuns.map(E=>l.jsxs("button",{className:"compact-run",type:"button",onClick:()=>w(E.id),children:[l.jsxs("div",{children:[l.jsx("p",{className:"compact-run-title",children:E.projectName}),l.jsx("p",{className:"compact-run-detail",children:E.summary})]}),l.jsx(u1,{status:E.status})]},E.id)):l.jsx("p",{className:"supporting-copy",children:"Run history appears here after the first launch."})})]})]}),l.jsxs("section",{className:"page-section",children:[l.jsx("div",{className:"section-head section-head-inline",children:l.jsxs("div",{children:[l.jsx("p",{className:"eyebrow eyebrow-soft",children:"System health"}),l.jsx("h2",{className:"section-title-sm",children:"Infrastructure"})]})}),l.jsx("div",{className:"divide-y divide-default border-y border-default",children:P.map(E=>{const q=E.id==="api"?N.apiStatus:E.id==="worker"?N.workerStatus:void 0,H=q?q.state==="ok"?void 0:Vr(q):E.tone==="positive"?void 0:E.meta;return l.jsxs("div",{className:"flex items-start justify-between gap-4 py-3",children:[l.jsxs("div",{children:[l.jsx("p",{className:"text-sm font-medium text-heading",children:E.label}),H&&l.jsx("p",{className:"mt-1 text-sm text-secondary",children:H})]}),l.jsx(bn,{tone:E.tone,title:q?Vr(q):E.meta,children:E.detail})]},E.id)})})]})]})}const oX='a, button, input, select, textarea, label, [role="button"], [role="link"], [role="checkbox"], [role="menuitem"]';function rX(e){if(e.defaultPrevented||e.button!==0||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return!1;const n=e.target;if(n&&typeof n.closest=="function"&&n.closest(oX))return!1;const i=typeof window<"u"?window.getSelection():null;return!(i&&!i.isCollapsed&&i.toString().trim()!=="")}function lX({onApplied:e}){const{canWrite:n}=pa(),[i,r]=C.useState(""),[u,h]=C.useState(!1),[f,b]=C.useState([]),[v,w]=C.useState([]);if(MA()||!n)return null;const k=async()=>{if(!i.trim())return;h(!0),b([]),w([]);const j=j5(i),T=[],N=[];for(let P=0;P<j.length;P++){const E=j[P];if(E.errors.length>0){T.push(`Document ${P+1}: ${E.errors[0]?.message}`);continue}const q=E.toJSON();if(!(!q||typeof q!="object"))try{const H=await YG(q);N.push(`Applied "${H.displayName||H.name}" (revision ${H.configRevision})`)}catch(H){T.push(`Document ${P+1}: ${zi(H)}`)}}b(N),w(T),h(!1),N.length>0&&(wn({title:"YAML applied",detail:`Applied ${N.length} document${N.length===1?"":"s"} successfully.`,tone:T.length>0?"caution":"positive",dedupeKey:"yaml:apply",dedupeMode:"replace"}),e())};return l.jsxs("section",{className:"mt-8",children:[l.jsx("div",{className:"page-section-divider"}),l.jsx("div",{className:"section-head mt-6",children:l.jsxs("div",{children:[l.jsx("p",{className:"eyebrow eyebrow-soft",children:"Config as code"}),l.jsx("h2",{className:"text-sm font-medium text-strong",children:"Apply YAML"})]})}),l.jsxs("p",{className:"text-muted text-sm mb-3",children:["Paste a ",l.jsx("code",{className:"text-secondary",children:"canonry.yaml"})," config (multi-document YAML with ",l.jsx("code",{className:"text-secondary",children:"---"})," separators supported)."]}),l.jsx("textarea",{className:"setup-input w-full font-mono text-xs",rows:10,placeholder:`apiVersion: canonry/v1
65
65
  kind: Project
66
66
  metadata:
@@ -83,4 +83,4 @@ spec:
83
83
  `);Rn(Fe),$i(!0)}}catch(U){al(U instanceof Error?U.message:"Failed to generate queries"),X({flowVersion:ft,onboardingSessionId:q,event:"onboarding.blocked",step:"queries",action:"generate_queries",reasonCode:gc(U,"unknown")},"onboarding.blocked:queries:generate")}finally{tl(!1)}}},pl=async()=>{if(!He)return;const U=hi;if(U.length!==0){Ya(!0),rl(null);try{await $G(He,U),Qi(!0),await r(),X({flowVersion:ft,onboardingSessionId:q,event:"onboarding.step_completed",step:"competitors",method:"manual",countBucket:oi(U.length)},"onboarding.step_completed:competitors"),ne(4)}catch(Fe){rl(Fe instanceof Error?Fe.message:"Failed to save competitors"),X({flowVersion:ft,onboardingSessionId:q,event:"onboarding.blocked",step:"competitors",action:"save",reasonCode:"unknown"},"onboarding.blocked:competitors:save")}finally{Ya(!1)}}},hl=async()=>{const U=Zi.trim();if(U){Lo(!0),Vo(null);try{await UA("gemini",{apiKey:U}),wn({title:"Gemini configured",detail:"Provider is ready — continuing setup.",tone:"positive",dedupeKey:"setup:gemini:configured",dedupeMode:"drop"}),Qc(""),await r(),Ls(v.providerStatuses.find(Fe=>Fe.name.toLowerCase()==="gemini")?.name??"gemini"),X({flowVersion:ft,onboardingSessionId:q,event:"onboarding.step_completed",step:"system",method:"inline"},"onboarding.step_completed:system")}catch(Fe){Vo(Fe instanceof Error?Fe.message:"Failed to save Gemini key"),X({flowVersion:ft,onboardingSessionId:q,event:"onboarding.blocked",step:"system",action:"configure_provider",reasonCode:"provider_save_failed"},"onboarding.blocked:system:provider_save_failed")}finally{Lo(!1)}}},fi=async()=>{if(!fo()){if(!He||Wa){zn(Wa??"Complete setup before launching the first sweep.");const U=ba??(He?ya===0?"no_queries":"run_rejected":"unknown");fa||X({flowVersion:ft,onboardingSessionId:q,event:"run.requested",origin:"dashboard_setup",result:"rejected",providerCountBucket:oi(Jt),queryCountBucket:oi(ya),reasonCode:U});return}Us(!0),zn(null);try{const U=await dl.mutateAsync({projectName:He,projectLabel:ve||_e||He,sourceAction:"setup-launch"});$m(U.id),Vm(!0),IC(He,U.id),ul.current=U.id,fa||X({flowVersion:ft,onboardingSessionId:q,event:"run.requested",origin:"dashboard_setup",result:"queued",providerCountBucket:oi(Jt),queryCountBucket:oi(ya)}),await r()}catch(U){zn(U instanceof Error?U.message:"Failed to queue the visibility sweep. Retry when the instance is ready."),fa||X({flowVersion:ft,onboardingSessionId:q,event:"run.requested",origin:"dashboard_setup",result:"rejected",providerCountBucket:oi(Jt),queryCountBucket:oi(ya),reasonCode:gc(U,"run_rejected")})}finally{Us(!1)}}},qn=()=>ne(U=>N?2:Math.max(0,U-1)),Go=(U,Fe,gi)=>{X({flowVersion:ft,onboardingSessionId:q,event:"onboarding.step_completed",step:U,method:"existing",...gi===void 0?{}:{countBucket:oi(gi)}},`onboarding.step_completed:${U}`),ne(Fe)},fl=()=>{if(X({flowVersion:ft,onboardingSessionId:q,event:"onboarding.step_completed",step:"queries",method:"skipped",countBucket:"0"},"onboarding.step_completed:queries"),N){Kt();return}ne(3)},Fc=()=>{X({flowVersion:ft,onboardingSessionId:q,event:"onboarding.step_completed",step:"competitors",method:"skipped",countBucket:"0"},"onboarding.step_completed:competitors"),ne(4)},Gs=N?"section":_a,va=et!==!0||st===!0?l.jsx(ue,{type:"button",variant:"ghost",size:"sm",className:"min-h-11",onClick:()=>{r(),Bs&&Qt.refetch()},children:"Check again"}):null,gl=(et===!1||ga)&&!!ta,Ks=N&&(O===2||O===4)?w?l.jsxs("section",{"aria-labelledby":"setup-provider-heading",className:"space-y-3 border-b border-default pb-6 mb-6",children:[l.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[l.jsx("h2",{id:"setup-provider-heading",className:"text-lg font-semibold text-heading",children:et===!1?"Connect a provider":"Answer engine provider"}),l.jsx(bn,{tone:et===!0?"positive":"neutral",children:et===!0?"Configured":et===!1?"Not connected":"Checking"})]}),l.jsx("p",{className:"max-w-prose text-sm text-secondary",children:et===!0?At.length>0?`${At.map(U=>U.displayName??U.name).join(", ")} available for this project. Research and sweeps use your provider account.`:"ChatGPT in Chrome is configured for sweeps. Query Research needs an API provider.":et===!1?"An answer engine is required for visibility sweeps. You can save queries now and connect later.":"Checking available providers. You can choose queries while this finishes."}),et===!1||ga?ta?l.jsx("div",{children:l.jsx(TX,{compact:!0,leadingField:l.jsxs("div",{className:"min-w-0 space-y-1.5",children:[l.jsx("label",{className:"block text-sm font-medium text-secondary",htmlFor:"setup-provider",children:"Provider to connect"}),l.jsx("select",{ref:Kc,id:"setup-provider",className:"setup-input",value:ta.name,onChange:U=>{U.target.value!==ta.name&&(qo.current=document.activeElement===U.currentTarget,sl(U.target.value))},children:Bo.map(U=>l.jsx("option",{value:U.name,children:U.displayName??U.name},U.name))})]}),secondaryActions:va,providerName:ta.name,keyUrl:ta.keyUrl,modelHint:ta.modelHint,onSaved:()=>{sn(!1),r()}},ta.name)}):l.jsx("p",{className:"max-w-prose text-sm text-secondary",children:fn.length>0?`This project's provider selection is ${fn.join(", ")}. Configure an allowed provider in Settings, or change the selection in project Settings.`:"Provider configuration is unavailable here. Open Settings to connect an answer engine, then check again."}):null,l.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[et===!0&&!ga&&ta?l.jsx(ue,{type:"button",variant:"outline",size:"sm",onClick:()=>sn(!0),children:"Configure a provider"}):null,!ta||st===!0?l.jsx(ue,{type:"button",variant:"outline",size:"sm",asChild:!0,children:l.jsx(We,{to:"/settings",target:"_blank",rel:"noopener noreferrer",children:"Open provider settings"})}):null,gl?null:va]})]}):l.jsxs("section",{"aria-labelledby":"setup-provider-heading",className:"space-y-2 border-b border-default pb-6 mb-6",children:[l.jsx("h2",{id:"setup-provider-heading",className:"text-lg font-semibold text-heading",children:"Answer engine provider"}),l.jsx("p",{className:"max-w-prose text-sm text-secondary",children:"Provider settings are managed by an administrator."}),Ye?l.jsx("p",{role:"alert",className:"text-sm text-negative",children:"Provider readiness could not be checked. Try again."}):l.jsx("p",{className:"max-w-prose text-sm text-secondary",role:"status",children:et===!0?"An answer engine is available for this project.":et===!1?"Ask an administrator to connect an answer engine for this project. You can save queries now.":"Checking provider readiness. You can save queries now."}),l.jsx(ue,{type:"button",variant:"ghost",size:"sm",className:"min-h-11",disabled:oe.isFetching,onClick:()=>{oe.refetch()},children:Ye?"Retry provider check":"Check again"})]}):null,ei=(()=>{switch(O){case 0:return l.jsxs(_a,{className:"surface-card step-card",children:[l.jsx("div",{className:"section-head",children:l.jsxs("div",{children:[l.jsx("p",{className:"eyebrow eyebrow-soft",children:"Step 1 of 5"}),l.jsx("h2",{children:"System check"})]})}),l.jsx("p",{className:"supporting-copy",children:"Checking that your Canonry instance is configured and reachable."}),l.jsx("div",{className:"compact-stack",children:T.healthChecks.map(U=>l.jsxs("div",{className:"health-check-row",children:[l.jsxs("div",{children:[l.jsx("p",{className:"run-row-title",children:U.label}),l.jsx("p",{className:"supporting-copy",children:U.detail}),U.id==="provider"&&U.state!=="ready"&&l.jsxs("div",{className:"mt-3 rounded-md border border-default bg-bg-elevated/40 p-3 space-y-2",children:[l.jsxs("p",{className:"text-xs text-secondary",children:["Paste a Gemini key to enable visibility checks (free at"," ",l.jsx("a",{href:"https://aistudio.google.com/apikey",target:"_blank",rel:"noreferrer",className:"text-positive-400 hover:text-positive underline underline-offset-2",children:"aistudio.google.com"}),")."]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("input",{type:"password",value:Zi,onChange:Fe=>Qc(Fe.target.value),placeholder:"AI... (paste here)",className:"flex-1 rounded-md border border-base bg-bg px-2.5 py-1.5 text-sm text-heading placeholder:text-faint focus:border-mono-600 focus:outline-none font-mono",disabled:In}),l.jsx(ue,{type:"button",size:"sm",disabled:In||!Zi.trim(),onClick:pn(hl),children:In?"Saving...":"Save"})]}),ml&&l.jsxs("div",{role:"alert",className:"space-y-1 text-xs text-negative",children:[l.jsx("p",{children:ml}),l.jsx("p",{children:"Check that the key is complete, then retry Save."})]}),l.jsxs("p",{className:"text-sm text-secondary",children:["Connect more answer engines later in"," ",l.jsx(We,{to:"/settings",className:"text-link hover:underline",children:"Settings"}),"."]})]})]}),l.jsx(bn,{tone:U.state==="ready"?"positive":"caution",title:U.id==="api"?Vr(j.apiStatus):U.id==="worker"?Vr(j.workerStatus):U.detail,children:U.state==="ready"?"Ready":"Attention"})]},U.id))}),l.jsxs("div",{className:"setup-nav",children:[T.launchState.blockedReason?l.jsx("p",{role:"status",className:"supporting-copy text-negative",children:T.launchState.blockedReason}):l.jsx("span",{}),l.jsx(ue,{type:"button",disabled:!T.launchState.enabled,title:T.launchState.blockedReason,onClick:()=>{X({flowVersion:ft,onboardingSessionId:q,event:"onboarding.step_completed",step:"system",method:"automatic"},"onboarding.step_completed:system"),ne($e)},children:"Continue"})]})]});case 1:return l.jsxs(_a,{className:"surface-card step-card",children:[l.jsxs("div",{className:"section-head",children:[l.jsxs("div",{children:[l.jsx("p",{className:"eyebrow eyebrow-soft",children:"Step 2 of 5"}),l.jsx("h2",{children:"Create project"})]}),He?l.jsx(bn,{tone:"positive",children:"Created"}):null]}),He?l.jsxs("div",{className:"compact-stack",children:[l.jsxs("p",{className:"text-neutral",children:["Project ",l.jsx("span",{className:"text-heading font-medium",children:He})," created successfully."]}),l.jsxs("div",{className:"setup-nav",children:[l.jsx(ue,{type:"button",variant:"outline",onClick:qn,children:"Back"}),l.jsx(ue,{type:"button",onClick:()=>Go("project",2),children:"Continue"})]})]}):l.jsxs("div",{className:"compact-stack",children:[l.jsxs("div",{className:"setup-field",children:[l.jsx("label",{className:"setup-label",htmlFor:"project-name",children:"Project name"}),l.jsx("input",{id:"project-name",className:"setup-input",type:"text",placeholder:"my-website",value:_e,onChange:U=>Be(U.target.value)}),Gn&&Gn!==_e?l.jsxs("p",{className:"supporting-copy",children:["Slug: ",Gn]}):null]}),l.jsxs("div",{className:"setup-field",children:[l.jsx("label",{className:"setup-label",htmlFor:"display-name",children:"Display name (optional)"}),l.jsx("input",{id:"display-name",className:"setup-input",type:"text",placeholder:"My Website",value:ve,onChange:U=>le(U.target.value)})]}),l.jsxs("div",{className:"setup-field",children:[l.jsx("label",{className:"setup-label",htmlFor:"domain",children:"Canonical domain"}),l.jsx("input",{id:"domain",className:"setup-input",type:"text",placeholder:"example.com",value:ce,onChange:U=>Q(U.target.value)})]}),l.jsxs("div",{className:"setup-field-row",children:[l.jsxs("div",{className:"setup-field",children:[l.jsx("label",{className:"setup-label",htmlFor:"country",children:"Country"}),l.jsx("input",{id:"country",className:"setup-input",type:"text",placeholder:"US",maxLength:2,value:me,onChange:U=>De(U.target.value.toUpperCase())})]}),l.jsxs("div",{className:"setup-field",children:[l.jsx("label",{className:"setup-label",htmlFor:"language",children:"Language"}),l.jsx("input",{id:"language",className:"setup-input",type:"text",placeholder:"en",maxLength:5,value:je,onChange:U=>it(U.target.value.toLowerCase())})]})]}),l.jsxs("label",{className:"flex items-start gap-3 rounded-md border border-default bg-surface p-3 cursor-pointer hover:border-strong",children:[l.jsx("input",{type:"checkbox",className:"mt-0.5 h-4 w-4 rounded border-strong bg-bg",checked:Ge,onChange:U=>jt(U.target.checked)}),l.jsxs("span",{className:"flex-1",children:[l.jsx("span",{className:"block text-sm text-heading",children:"Auto-extract backlinks"}),l.jsxs("span",{className:"block text-xs text-muted mt-0.5",children:["When a new Common Crawl release syncs, automatically extract backlinks for this project."," ",l.jsx(We,{to:"/backlinks",className:"text-positive-400 hover:text-positive underline underline-offset-2",children:"Manage backlinks"})]})]})]}),lt?l.jsx("p",{className:"text-negative-400 text-sm",children:lt}):null,l.jsxs("div",{className:"setup-nav",children:[l.jsx(ue,{type:"button",variant:"outline",onClick:qn,children:"Back"}),l.jsx(ue,{type:"button",disabled:!Gn||!ce||ea,onClick:pn(Gm),children:ea?"Creating...":"Create project"})]})]})]});case 2:return l.jsxs(Gs,{className:N?"visibility-setup-section step-card":"surface-card step-card","aria-labelledby":"setup-queries-heading",children:[l.jsxs("div",{className:"section-head",children:[l.jsxs("div",{children:[l.jsx("p",{className:"eyebrow eyebrow-soft",children:N?"Step 1 of 2":"Step 3 of 5"}),l.jsx("h2",{id:"setup-queries-heading",children:"Add queries"})]}),ae?l.jsx(bn,{tone:"neutral",children:"Loading"}):B.isError?l.jsx(bn,{tone:"negative",children:"Load failed"}):Lt?l.jsxs(bn,{tone:"positive",children:[na.length," saved"]}):l.jsxs(bn,{tone:"neutral",children:[na.length," quer",na.length!==1?"ies":"y"]})]}),l.jsx("p",{className:"supporting-copy",children:"Add the queries your customers use, one per line. You can refine your list later."}),l.jsxs("div",{className:"space-y-2 border-b border-default pb-4",children:[l.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[l.jsxs("div",{className:"min-w-0 space-y-1",children:[l.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Research queries with your agent"}),l.jsx("p",{className:"max-w-prose text-sm text-secondary",children:"Ask your agent to compare answers and available sources with Canonry Research, then recommend queries. Research does not change your tracked queries."})]}),l.jsx(ue,{type:"button",variant:"outline",size:"sm",className:"min-h-11 shrink-0 self-start",onClick:pn(ol),children:Dn?"Research prompt copied":"Copy research prompt"})]}),l.jsxs("details",{open:Mo||void 0,className:"text-sm text-secondary",children:[l.jsx("summary",{className:"min-h-11 cursor-pointer py-3 text-link",children:"View agent prompt"}),l.jsx("textarea",{"aria-label":"Agent query research prompt",readOnly:!0,className:"setup-textarea mt-2 w-full",rows:8,value:Gi})]}),Mo?l.jsx("p",{role:"alert",className:"text-sm text-negative",children:"Could not copy. Select and copy the prompt above."}):null]}),ae?l.jsx("div",{className:"rounded-md border border-default bg-bg-elevated/40 p-4 text-sm text-secondary",role:"status",children:"Loading saved queries…"}):B.isError?l.jsxs("div",{className:"compact-stack",children:[l.jsx("div",{role:"alert",className:"rounded-md border border-negative bg-negative-soft p-3 text-sm text-negative",children:"Saved queries could not be loaded. Retry before changing the query basket."}),l.jsxs("div",{className:"setup-nav",children:[l.jsx(ue,{type:"button",variant:"outline",onClick:N?Le:qn,children:"Back"}),l.jsx(ue,{type:"button",onClick:()=>{B.refetch()},children:"Retry loading queries"})]})]}):Lt?l.jsxs("div",{className:"compact-stack",children:[l.jsx("ul",{className:"detail-list",children:na.map(U=>l.jsx("li",{children:U},U))}),l.jsxs("div",{className:"setup-nav",children:[l.jsx(ue,{type:"button",variant:"outline",onClick:N?Le:qn,children:"Back"}),l.jsx(ue,{type:"button",variant:"outline",onClick:()=>ui(!1),children:"Edit queries"}),l.jsx(ue,{type:"button",onClick:()=>Go("queries",N?4:3,na.length),children:"Continue"})]})]}):l.jsxs("div",{className:"compact-stack",children:[At.length>0?l.jsxs("div",{className:"compact-stack",children:[l.jsxs("div",{className:"flex items-center gap-2 text-muted text-xs uppercase tracking-wide",children:[l.jsx("span",{className:"flex-1 border-t border-base"}),"auto-generate",l.jsx("span",{className:"flex-1 border-t border-base"})]}),l.jsxs("div",{className:"flex items-end gap-2",children:[l.jsxs("div",{className:"setup-field flex-1",children:[l.jsx("label",{className:"setup-label",htmlFor:"gen-provider",children:"Provider"}),l.jsx("select",{id:"gen-provider",className:"setup-input",value:Za,onChange:U=>Ls(U.target.value),children:At.map(U=>l.jsxs("option",{value:U.name,children:[U.displayName??U.name,U.model?` (${U.model})`:""]},U.name))})]}),l.jsxs("div",{className:"setup-field",children:[l.jsx("label",{className:"setup-label",htmlFor:"gen-count",children:"Count"}),l.jsx("select",{id:"gen-count",className:"setup-input",value:Po,onChange:U=>Vs(Number(U.target.value)),children:[3,5,10,15,20].map(U=>l.jsx("option",{value:U,children:U},U))})]}),l.jsx(ue,{type:"button",variant:"outline",disabled:Gc||!Za,onClick:pn(Pa),children:Gc?"Analyzing site...":"Generate"})]}),nl?l.jsx("p",{className:"text-negative-400 text-sm",children:nl}):null]}):null,N?null:l.jsxs("div",{className:"flex items-center gap-2 text-muted text-xs uppercase tracking-wide",children:[l.jsx("span",{className:"flex-1 border-t border-base"}),"or type manually",l.jsx("span",{className:"flex-1 border-t border-base"})]}),l.jsxs("div",{className:"setup-field",children:[l.jsx("label",{className:"setup-label",htmlFor:"queries",children:"Queries (one per line)"}),l.jsx("textarea",{id:"queries",className:"setup-textarea",rows:6,placeholder:`emergency dentist brooklyn
84
84
  best invisalign downtown brooklyn
85
85
  pediatric dentist brooklyn heights`,value:Ht,onChange:U=>Rn(U.target.value)})]}),Ps?l.jsx("p",{className:"text-negative-400 text-sm",children:Ps}):null,l.jsxs("div",{className:"setup-nav",children:[l.jsx(ue,{type:"button",variant:"outline",onClick:N?Le:qn,children:"Back"}),l.jsx(ue,{type:"button",variant:"ghost",onClick:fl,children:N?"Finish without AI Visibility":"Skip for now"}),l.jsx(ue,{type:"button",disabled:na.length===0||di,onClick:pn(Uo),children:di?"Saving...":`Save ${na.length} quer${na.length!==1?"ies":"y"}`})]})]})]});case 3:return l.jsxs(_a,{className:"surface-card step-card",children:[l.jsxs("div",{className:"section-head",children:[l.jsxs("div",{children:[l.jsx("p",{className:"eyebrow eyebrow-soft",children:"Step 4 of 5"}),l.jsx("h2",{children:"Add competitors"})]}),Hi?l.jsx(bn,{tone:"positive",children:"Saved"}):null]}),l.jsx("p",{className:"supporting-copy",children:"Domains that compete for the same queries. One per line."}),Hi?l.jsxs("div",{className:"compact-stack",children:[l.jsx("ul",{className:"detail-list",children:hi.map(U=>l.jsx("li",{children:U},U))}),l.jsxs("div",{className:"setup-nav",children:[l.jsx(ue,{type:"button",variant:"outline",onClick:qn,children:"Back"}),l.jsx(ue,{type:"button",onClick:()=>Go("competitors",4,hi.length),children:"Continue"})]})]}):l.jsxs("div",{className:"compact-stack",children:[l.jsxs("div",{className:"setup-field",children:[l.jsx("label",{className:"setup-label",htmlFor:"competitors",children:"Competitor domains (one per line)"}),l.jsx("textarea",{id:"competitors",className:"setup-textarea",rows:4,placeholder:`competitor1.com
86
- competitor2.com`,value:mi,onChange:U=>Ki(U.target.value)})]}),Wt?l.jsx("p",{className:"text-negative-400 text-sm",children:Wt}):null,l.jsxs("div",{className:"setup-nav",children:[l.jsx(ue,{type:"button",variant:"outline",onClick:qn,children:"Back"}),l.jsxs("div",{className:"flex gap-2",children:[l.jsx(ue,{type:"button",variant:"outline",onClick:Fc,children:"Skip"}),l.jsx(ue,{type:"button",disabled:hi.length===0||ll,onClick:pn(pl),children:ll?"Saving...":`Save ${hi.length} competitor${hi.length!==1?"s":""}`})]})]})]})]});case 4:{const U=Ja.data,Fe=U?.status??(Fi===nt?.id?nt.status:void 0),gi=Fe==="completed"||Fe==="partial"||Fe==="failed"||Fe==="cancelled",qa=U?.snapshots??[],Ko=qa.filter(Ma=>Ma.citationState==="cited").length,Zc=qa.filter(Ma=>Ma.answerMentioned===!0).length,An=new Set(qa.map(Ma=>Ma.query).filter(Ma=>!!Ma)).size,ti=Fe?Tk(Fe,qa.length):!1,Hs=Ue&&!Xa,Qs=jn??(U?.error?RK(U.error):Fe==="cancelled"?"The sweep was cancelled before it produced a baseline.":(Fe==="completed"||Fe==="partial")&&qa.length===0?"The sweep finished without producing any snapshots.":nt?.statusDetail||"The sweep did not produce a baseline.");let Fs=null;return Hs||ti?Fs=l.jsx(bn,{tone:"positive",children:"Complete"}):jn&&!Xa?Fs=l.jsx(bn,{tone:"negative",children:"Failed"}):gi?Fs=l.jsx(bn,{tone:"negative",children:Fe==="cancelled"?"Cancelled":"Failed"}):Xa&&(Fs=l.jsx(bn,{tone:"caution",children:"Running"})),l.jsxs(_a,{className:"surface-card step-card",children:[l.jsxs("div",{className:"section-head",children:[l.jsxs("div",{children:[l.jsx("p",{className:"eyebrow eyebrow-soft",children:N?"Step 2 of 2":"Step 5 of 5"}),l.jsx("h2",{children:fo()?"AI Visibility":"Launch first run"})]}),Fs]}),Hs?l.jsxs("div",{className:"compact-stack",children:[l.jsxs("p",{className:"text-secondary",children:["Setup is complete. ",l.jsx("span",{className:"text-strong font-medium",children:He})," already has a successful answer-visibility baseline."]}),l.jsxs("div",{className:"setup-nav",children:[l.jsx("span",{}),l.jsx(ue,{type:"button",onClick:()=>ct(),children:f?"Finish setup":"Open project dashboard →"})]})]}):!Xa&&fo()?l.jsxs("div",{className:"compact-stack",children:[He?l.jsx(QZ,{projectName:He}):l.jsx("p",{className:"text-sm text-secondary",children:hg}),jn&&l.jsx("p",{role:"alert",className:"text-sm text-negative",children:jn}),l.jsxs("div",{className:"setup-nav",children:[l.jsx("span",{}),l.jsx(ue,{type:"button",onClick:Le,children:"Open project dashboard →"})]})]}):Xa?gi?ti?l.jsxs("div",{className:"compact-stack",children:[l.jsxs("p",{className:"text-neutral",children:["Sweep complete. Your first answer-visibility snapshot for"," ",l.jsx("span",{className:"text-heading font-medium",children:He}),":"]}),l.jsxs("div",{className:"grid grid-cols-3 gap-2 mt-1",children:[l.jsxs("div",{className:"rounded-md border border-default bg-surface p-3",children:[l.jsx("p",{className:"text-xs font-medium text-secondary",children:"Mentioned"}),l.jsxs("p",{className:"text-2xl font-bold tabular-nums text-primary mt-1",children:[Zc,l.jsxs("span",{className:"text-faint text-lg",children:[" / ",An]})]}),l.jsx("p",{className:"mt-0.5 text-sm text-secondary",children:"queries naming your brand"})]}),l.jsxs("div",{className:"rounded-md border border-default bg-surface p-3",children:[l.jsx("p",{className:"text-xs font-medium text-secondary",children:"Cited"}),l.jsxs("p",{className:"text-2xl font-bold tabular-nums text-primary mt-1",children:[Ko,l.jsxs("span",{className:"text-faint text-lg",children:[" / ",An]})]}),l.jsx("p",{className:"mt-0.5 text-sm text-secondary",children:"queries citing your site"})]}),l.jsxs("div",{className:"rounded-md border border-default bg-surface p-3",children:[l.jsx("p",{className:"text-xs font-medium text-secondary",children:"Results"}),l.jsx("p",{className:"text-2xl font-bold tabular-nums text-primary mt-1",children:qa.length}),l.jsx("p",{className:"mt-0.5 text-sm text-secondary",children:"completed engine checks"})]})]}),!b&&He?l.jsx(_X,{projectName:He}):null,l.jsxs("div",{className:"setup-nav",children:[l.jsx("span",{}),l.jsx(ue,{type:"button",onClick:()=>ct(),children:f?"Finish setup":"Open project dashboard →"})]})]}):l.jsxs("div",{className:"compact-stack",children:[l.jsxs("div",{role:"alert",className:"rounded-md border border-negative bg-negative-soft p-3 text-sm text-negative",children:[l.jsx("p",{children:Qs}),l.jsx("p",{className:"mt-1 text-xs text-secondary",children:fo()?hg:w?"Fix provider or query configuration if needed, then retry without leaving setup.":"Ask an administrator to review the provider and query configuration."})]}),l.jsxs("div",{className:"setup-nav",children:[w&&!fo()?l.jsx(ue,{type:"button",variant:"outline",asChild:!0,children:l.jsx(We,{to:"/settings",children:"Configure providers"})}):l.jsx("span",{}),fo()||!w?l.jsx(ue,{type:"button",onClick:Le,children:"Open project dashboard →"}):l.jsx(ue,{type:"button",disabled:pi||!!Wa,onClick:pn(fi),children:pi?"Retrying...":"Retry visibility sweep"})]})]}):l.jsxs("div",{className:"compact-stack",children:[l.jsx("p",{className:"text-neutral",children:"Sweep running. This usually takes 30 to 60 seconds."}),l.jsx("div",{className:"rounded-md border border-default bg-surface p-3 text-xs text-muted",children:l.jsxs("p",{children:["Status: ",l.jsx("span",{className:"text-neutral",children:Fe??"queued"})]})}),Ja.isError&&l.jsxs("div",{role:"alert",className:"rounded-md border border-negative bg-negative-soft p-3 text-sm text-negative",children:[l.jsx("p",{children:Ja.error instanceof Error?Ja.error.message:"Could not refresh the sweep status."}),l.jsx(ue,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>{Ja.refetch()},children:"Retry status check"})]}),l.jsxs("div",{className:"setup-nav",children:[l.jsx("span",{}),l.jsx(ue,{type:"button",variant:"outline",onClick:f?()=>ct():Le,children:f?"Finish setup":"Watch on project page"})]})]}):l.jsxs("div",{className:"compact-stack",children:[l.jsxs("p",{className:"supporting-copy",children:["Your queries are saved. Run a first sweep to get a baseline for"," ",l.jsx("span",{className:"text-heading font-medium",children:He}),", or finish and run it later from the project. A sweep calls the answer engines, so it costs provider usage."]}),(Wa||jn)&&l.jsxs("div",{role:"alert",className:"rounded-md border border-negative bg-negative-soft p-3 text-sm text-negative",children:[l.jsx("p",{children:jn??Wa}),l.jsx("p",{className:"mt-1 text-xs text-secondary",children:"Resolve the blocker above, then retry the sweep here."})]}),l.jsxs("div",{className:"setup-nav",children:[l.jsx(ue,{type:"button",variant:"outline",onClick:qn,children:"Back"}),l.jsx(ue,{type:"button",variant:"ghost",onClick:Kt,children:"Finish without running"}),ba==="no_provider"&&!N?l.jsx(ue,{type:"button",asChild:!0,children:l.jsx(We,{to:"/settings",children:"Configure a provider"})}):l.jsx(ue,{type:"button",disabled:pi||!!Wa,title:Wa,onClick:pn(fi),children:pi?"Launching...":jn?"Retry visibility sweep":"Launch visibility sweep"})]})]})]})}default:return null}})();return l.jsxs("div",{className:N?"page-container visibility-setup":"page-container",children:[f?l.jsx(jo,{current:"visibility"}):null,l.jsxs("div",{className:"page-header",children:[l.jsxs("div",{className:"page-header-left",children:[l.jsx("h1",{ref:u?h:void 0,tabIndex:u?-1:void 0,className:"page-title",children:u?"Set up AI Visibility":"Setup"}),l.jsx("p",{className:"page-subtitle",children:u?"Connect an answer engine, then choose queries for your first sweep.":"Create a project and run its first visibility check."})]}),f?l.jsx("div",{className:"page-header-right",children:l.jsx(ue,{type:"button",variant:"outline",className:"min-h-11",onClick:Kt,children:"Skip AI Visibility"})}):null]}),f?null:l.jsx(IX,{current:N?O===4?1:0:O,labels:N?DX:RX}),l.jsxs("section",{className:"setup-wizard",children:[Ks,ei]})]})}const _f="canonry mcp install --client claude-code",qX="https://github.com/Canonry/canonry/blob/main/docs/mcp.md";function MX(){const e=C.useRef(g1()).current,n=C.useRef(new Set),i=C.useCallback((r,u)=>{n.current.has(r)||(n.current.add(r),n1({...u,flowVersion:ft,onboardingSessionId:e,surface:"platform",eventId:y1()}))},[e]);return C.useEffect(()=>{i("started",{event:"onboarding.started",step:"finish",resumed:!1})},[i]),C.useCallback(r=>{i(`action:${r}`,{event:"onboarding.step_completed",step:"finish",method:"manual",nextAction:r})},[i])}const Bm=C.createContext(()=>{});function BX({projectName:e,skippedVisibility:n=!1}){const i=yt({...mQ({client:J,path:{name:e}}),retry:!1}),r=i.data?.hasData?i.data:null,u=MX(),h=Dk(e,ze["site-audit"]),f=Dk(e,ze["answer-visibility"]),b={...h?{site:h,fixes:h}:{},...LX(f,n)};return l.jsx(Bm.Provider,{value:u,children:l.jsxs("div",{className:"page-container max-w-6xl py-8 md:py-10",children:[l.jsx(jo,{current:"done",outcomes:b}),l.jsxs("header",{className:"relative mx-auto mt-12 max-w-2xl text-center md:mt-16",children:[l.jsx(VX,{}),l.jsx("p",{className:"onb-reveal mt-6 text-sm font-medium text-positive",style:Ta(250),children:"Setup complete"}),l.jsx("h1",{className:"onb-reveal mt-2 text-5xl font-semibold tracking-tight text-heading md:text-6xl",style:Ta(350),children:"You’re set."}),l.jsxs("p",{className:"onb-reveal mx-auto mt-4 max-w-xl text-lg text-secondary",style:Ta(450),children:["Canonry is tracking ",l.jsx("span",{className:"font-medium text-heading",children:e}),". Here’s how to get the most out of it from here."]})]}),l.jsxs("div",{className:"mt-14 grid gap-4 md:grid-cols-6",children:[l.jsx(gd,{className:"md:col-span-4 md:row-span-2",delayMs:600,labelledBy:"onb-agent-heading",children:l.jsx(GX,{projectName:e})}),l.jsx(gd,{className:"md:col-span-2 md:row-span-2",delayMs:700,labelledBy:"onb-data-heading",children:l.jsx(QX,{projectName:e})}),l.jsx(gd,{className:"md:col-span-3",delayMs:800,labelledBy:"onb-schedule-heading",children:l.jsx(YX,{projectName:e})}),l.jsx(gd,{className:"md:col-span-3",delayMs:900,labelledBy:"onb-alerts-heading",children:l.jsx(XX,{projectName:e,score:r?.aggregateScore??null})})]}),l.jsxs("div",{className:"onb-reveal mt-12 flex flex-col items-center gap-3 sm:flex-row sm:justify-center",style:Ta(1e3),children:[l.jsx(ue,{asChild:!0,className:"h-11 rounded-full px-6 text-base md:h-11",children:l.jsxs(We,{to:"/projects/$projectName",params:{projectName:e},replace:!0,onClick:()=>u("open_project"),children:["Open ",e,l.jsx(yc,{className:"size-4","aria-hidden":"true"})]})}),l.jsx(ue,{asChild:!0,variant:"ghost",className:"h-11 rounded-full px-5 md:h-11",children:l.jsx(We,{to:"/projects/$projectName/technical-aeo",params:{projectName:e},replace:!0,onClick:()=>u("review_page_health"),children:"Review page health"})})]})]})})}function Dk(e,n){const i=yt({...XA({client:J,path:{name:e},query:{kind:n,limit:20}}),retry:!1,refetchInterval:r=>zk(r.state.status==="success"?{isSuccess:!0,data:r.state.data}:{isSuccess:!1})==="pending"?5e3:!1});return zk(i)}function LX(e,n){return e===void 0?{}:n?{visibility:"skipped"}:{visibility:e}}function zk(e){if(!e.isSuccess||!e.data)return"unknown";const n=e.data.filter(i=>i.trigger!==ks.probe);if(!n.some(i=>i.status===nn.completed||i.status===nn.partial))return n.some(i=>i.status===nn.queued||i.status===nn.running)?"pending":n.length>0?"incomplete":"skipped"}function Ta(e){return{"--onb-delay":`${e}ms`}}function VX(){return l.jsx("div",{className:"onb-check relative mx-auto size-20","aria-hidden":"true",children:l.jsxs("svg",{viewBox:"0 0 80 80",className:"relative size-20",children:[l.jsx("circle",{className:"onb-check-ring",cx:"40",cy:"40",r:"36",fill:"none",strokeWidth:"3",pathLength:"1"}),l.jsx("path",{className:"onb-check-mark",d:"M25 41 L35 51 L56 30",fill:"none",strokeWidth:"4",strokeLinecap:"round",strokeLinejoin:"round",pathLength:"1"})]})})}function gd({className:e="",delayMs:n,labelledBy:i,children:r}){return l.jsx("section",{"aria-labelledby":i,className:`onb-reveal onb-tile flex flex-col overflow-hidden rounded-2xl border border-default bg-surface p-6 md:p-7 ${e}`,style:Ta(n),children:r})}function Lm({id:e,eyebrow:n,title:i,children:r}){return l.jsxs("div",{children:[l.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted",children:n}),l.jsx("h2",{id:e,className:"mt-1.5 text-2xl font-semibold tracking-tight text-heading",children:i}),l.jsx("p",{className:"mt-2 text-sm text-secondary",children:r})]})}const yd=[{id:"diagnose",label:"Diagnose",prompt:"Why did we lose citations this week?",calls:["canonry_insights_list","canonry_competitor_landscape"],reply:"Two engines started citing a competitor’s comparison page instead of yours. Want me to draft one that answers the same query?"},{id:"fix",label:"Fix",prompt:"Fix the weakest pages on the site.",calls:["canonry_technical_aeo_pages","canonry_site_health_page_audit"],reply:"The lowest-scoring pages are missing structured data and answer-first intros. I’ve written the changes for you to review."},{id:"automate",label:"Automate",prompt:"Re-check everything every Monday and tell me in Slack.",calls:["canonry_schedule_set","canonry_agent_webhook_attach"],reply:"Done. A sweep runs every Monday, and I’ll post what changed to Slack."}],$X=9e3;function UX(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function GX({projectName:e}){const n=C.useContext(Bm),[i,r]=C.useState(0),[u,h]=C.useState(!1),[f,b]=C.useState(!1);C.useEffect(()=>{if(u||UX())return;const k=window.setTimeout(()=>r(j=>(j+1)%yd.length),$X);return()=>window.clearTimeout(k)},[i,u]);const v=async()=>{try{await navigator.clipboard.writeText(_f),n("copy_agent_command"),b(!0),window.setTimeout(()=>b(!1),1800)}catch{wn({tone:"negative",title:"Could not copy the command",detail:`Run ${_f} in your terminal.`})}},w=yd[i]??yd[0];return l.jsxs(l.Fragment,{children:[l.jsxs(Lm,{id:"onb-agent-heading",eyebrow:"Your agent",title:"Let your agent run it.",children:["Your agent can do everything in Canonry: diagnose a drop, fix pages, run sweeps and scans, and write the client report. Use Claude Code, Codex, Cursor, or Aero, the analyst built into"," ",l.jsx("span",{className:"text-heading",children:e})," that reviews every sweep on its own."]}),l.jsxs("div",{className:"mt-6 flex flex-1 flex-col rounded-xl border border-default bg-bg",onMouseEnter:()=>h(!0),onMouseLeave:()=>h(!1),onFocus:()=>h(!0),children:[l.jsxs("div",{className:"flex items-center gap-1 border-b border-default px-3 py-2",role:"tablist","aria-label":"Example agent sessions",children:[yd.map((k,j)=>l.jsx("button",{type:"button",role:"tab","aria-selected":j===i,onClick:()=>{r(j),h(!0)},className:`rounded-md px-2.5 py-1 text-xs font-medium transition-colors ${j===i?"bg-surface-inset text-heading":"text-muted hover:text-secondary"}`,children:k.label},k.id)),l.jsx("span",{className:"ml-auto text-xs text-faint",children:"Example"})]}),l.jsxs("div",{role:"tabpanel","aria-label":`${w.label} example`,className:"flex-1 p-4 font-mono text-[13px] leading-relaxed",children:[l.jsxs("p",{className:"onb-type text-heading",style:Ta(150),children:[l.jsx("span",{className:"text-muted",children:"> "}),w.prompt]}),w.calls.map((k,j)=>l.jsxs("p",{className:"onb-line mt-1 text-muted first:mt-3",style:Ta(1300+j*450),children:[l.jsx("span",{className:"text-positive",children:"●"})," ",k]},k)),l.jsx("p",{className:"onb-line mt-3 text-secondary",style:Ta(1500+w.calls.length*450),children:w.reply}),l.jsx("span",{className:"onb-caret mt-2 inline-block h-4 w-2 bg-current align-middle text-secondary",style:Ta(1900+w.calls.length*450),"aria-hidden":"true"})]},w.id)]}),l.jsxs("div",{className:"mt-4 flex flex-wrap items-center gap-2",children:[l.jsx("code",{className:"min-w-0 flex-1 truncate rounded-lg border border-default bg-surface-inset px-3 py-2 font-mono text-[13px] text-heading",children:_f}),l.jsxs(ue,{type:"button",variant:"secondary",size:"sm",className:"h-9 md:h-9",onClick:()=>{v()},children:[f?l.jsx(Wd,{className:"size-4","aria-hidden":"true"}):l.jsx(Cg,{className:"size-4","aria-hidden":"true"}),f?"Copied":"Copy"]}),l.jsx("a",{href:qX,target:"_blank",rel:"noreferrer",className:"text-sm font-medium text-link underline-offset-4 hover:underline",children:"Other clients"})]})]})}const KX=[{icon:Ag,label:"Search Console",action:"connect_search_console",to:"/projects/$projectName/search-console"},{icon:Fk,label:"Google Analytics",action:"connect_analytics",to:"/projects/$projectName/activity"},{icon:Yk,label:"Business Profile",action:"connect_business_profile",to:"/projects/$projectName/local"}],HX=["GPTBot","ClaudeBot","PerplexityBot"];function QX({projectName:e}){const n=C.useContext(Bm);return l.jsxs(l.Fragment,{children:[l.jsx(Lm,{id:"onb-data-heading",eyebrow:"Server-side traffic",title:"See the AI bots.",children:"AI crawlers and answer-engine fetches never run JavaScript, so Google Analytics never sees them. Canonry reads them straight from your server."}),l.jsx(FX,{}),l.jsxs(We,{to:"/traffic",onClick:()=>n("connect_server_traffic"),"aria-label":"Connect server-side traffic",className:"group flex items-center gap-3 rounded-xl border border-strong bg-surface-inset px-4 py-3 text-sm font-medium text-heading transition-colors hover:bg-surface-inset-hover",children:[l.jsx(Xk,{className:"size-4 text-positive","aria-hidden":"true"}),l.jsxs("span",{className:"flex-1",children:["Connect your server",l.jsx("span",{className:"block text-xs font-normal text-secondary",children:"Cloudflare, Vercel, WordPress, or Cloud Run"})]}),l.jsx(yc,{className:"size-4 text-link transition-transform group-hover:translate-x-0.5","aria-hidden":"true"})]}),l.jsx("p",{className:"mt-5 text-xs font-medium uppercase tracking-wide text-muted",children:"Also connect"}),l.jsx("ul",{className:"mt-1 divide-y divide-default",children:KX.map(({icon:i,label:r,action:u,to:h})=>l.jsx("li",{children:l.jsxs(We,{to:h,params:{projectName:e},"aria-label":`Connect ${r}`,onClick:()=>n(u),className:"group flex items-center gap-3 py-2.5 text-sm text-heading",children:[l.jsx(i,{className:"size-4 text-muted","aria-hidden":"true"}),l.jsx("span",{className:"flex-1",children:r}),l.jsx(yc,{className:"size-3.5 text-link transition-transform group-hover:translate-x-0.5","aria-hidden":"true"})]})},r))})]})}function FX(){const e=[22,70,118];return l.jsxs("div",{className:"relative my-6 h-36","aria-hidden":"true",children:[l.jsx("svg",{viewBox:"0 0 200 140",preserveAspectRatio:"none",className:"absolute inset-0 size-full",children:e.map((n,i)=>l.jsx("path",{className:"onb-flow",style:Ta(i*400),d:`M20 ${n} C 100 ${n}, 118 70, 170 70`,fill:"none",strokeWidth:"1.5"},n))}),HX.map((n,i)=>l.jsx("span",{className:"onb-bot absolute left-0 -translate-y-1/2 rounded-md border border-default bg-bg-elevated px-2 py-1 font-mono text-[11px] text-secondary",style:{top:`${(e[i]??70)/140*100}%`,...Ta(i*600)},children:n},n)),l.jsx("span",{className:"onb-hub absolute right-0 top-1/2 flex size-11 -translate-y-1/2 items-center justify-center rounded-2xl bg-accent text-on-inverse",children:l.jsx(Xk,{className:"size-5"})})]})}const ZX=["M","T","W","T","F","S","S"];function YX({projectName:e}){return l.jsxs(l.Fragment,{children:[l.jsx(Lm,{id:"onb-schedule-heading",eyebrow:"Scheduled sweeps",title:"Runs on its own.",children:"Re-measure every week without lifting a finger, so a drop shows up before a customer notices."}),l.jsx("ol",{className:"mt-6 grid grid-cols-7 gap-2","aria-hidden":"true",children:ZX.map((n,i)=>l.jsxs("li",{className:"flex flex-col items-center gap-2",children:[l.jsx("span",{className:"onb-day size-3 rounded-full bg-surface-inset",style:Ta(i*500)}),l.jsx("span",{className:"text-xs text-muted",children:n})]},i))}),l.jsx(MC,{projectName:e,to:"/projects/$projectName/settings",icon:Zk,label:"Set a schedule",action:"set_schedule"})]})}function XX({projectName:e,score:n}){return l.jsxs(l.Fragment,{children:[l.jsx(Lm,{id:"onb-alerts-heading",eyebrow:"Notifications",title:"Hear about changes.",children:"Get a webhook in Slack or anywhere else when a sweep finishes or a score moves."}),l.jsxs("div",{className:"relative mt-6 flex h-14 items-center","aria-hidden":"true",children:[l.jsx("span",{className:"onb-bell flex size-10 items-center justify-center rounded-full border border-default bg-bg-elevated",children:l.jsx(Rf,{className:"size-4 text-secondary"})}),l.jsxs("span",{className:"onb-toast ml-3 flex items-center gap-2 rounded-xl border border-default bg-bg-elevated px-3 py-2 text-sm shadow-[0_8px_24px_var(--color-shadow-panel)]",children:[l.jsx("span",{className:"size-2 rounded-full bg-positive-400"}),l.jsx("span",{className:"text-heading",children:e}),l.jsx("span",{className:"text-secondary",children:n===null?"sweep finished":`page health ${n}`})]})]}),l.jsx(MC,{projectName:e,to:"/projects/$projectName/settings",icon:Rf,label:"Add a notification",action:"add_notification"})]})}function MC({projectName:e,to:n,icon:i,label:r,action:u}){const h=C.useContext(Bm);return l.jsxs(We,{to:n,params:{projectName:e},onClick:()=>h(u),className:"group mt-6 inline-flex items-center gap-2 self-start text-sm font-medium text-link",children:[l.jsx(i,{className:"size-4","aria-hidden":"true"}),r,l.jsx(yc,{className:"size-3.5 transition-transform group-hover:translate-x-0.5","aria-hidden":"true"})]})}const JX=C.lazy(async()=>({default:(await Li(()=>import("./SiteHealthSection-DgM3aTd-.js").then(n=>n.d),__vite__mapDeps([0,1,2,3,4]),import.meta.url)).SiteHealthSection})),WX=`Public pages only, crawled from this computer and stored locally. The first scan reads up to ${n3} pages, then stops.`,eJ=1800,tJ="https://github.com/Canonry/canonry#or-use-any-shell-capable-coding-agent",nJ="Help me set up Canonry for my public site.\n\nUse the official Canonry docs:\n- Agent quickstart: https://github.com/Canonry/canonry#or-use-any-shell-capable-coding-agent\n- CLI reference: https://github.com/Canonry/canonry/blob/main/skills/canonry/references/canonry-cli.md\n- Plugin setup: https://github.com/Canonry/canonry/blob/main/docs/plugins.md\n- MCP setup: https://github.com/Canonry/canonry/blob/main/docs/mcp.md\n\nPick one path and stay on it. Use connected Canonry tools (plugin or MCP) only if you have them and I have not pointed you at a specific install. A connected tool runs in its own process and never sees `CANONRY_CONFIG_DIR`, `CANONRY_PORT`, or anything else you export in a shell, so it always acts on my default install. If I named a config directory, a port, or a sandbox, that is the shell path: use `cnry` and tell me which path you chose. Never mix the two in one run, and never create a duplicate project. The `cnry` and `canonry` commands are interchangeable.\n\n1. Ask for my public domain, country, and language. Do not create or scan anything yet. Country and language are only applied when a project is created, so if you reuse an existing project, report its country and language instead of changing them.\n2. Shell path only: confirm `cnry` is on PATH, then run `cnry --version`. If Canonry is missing, propose `npm install -g @canonry/canonry` and wait for approval. Then run `cnry doctor --format json`, which is the command that says whether config, database, and server are in place. `cnry --version` does not read config and succeeds on a completely unconfigured install, so it cannot answer this. If config is missing, run `cnry bootstrap` yourself: it is not interactive, takes about a second, and is safe to rerun. Do not hand it to me and wait. The interactive command is `cnry init`, which is optional provider and OAuth setup that Page Health does not need. Bootstrap prints an API key, so do not repeat its output back to me, and never ask me to paste passwords, API keys, OAuth credentials, or command output.\n3. Confirm the API is reachable. `cnry doctor --format json` reports it, and any project read exits non-zero with `CONNECTION_ERROR` when it is not. If it is unreachable, propose `cnry start` and wait for approval. Use `cnry start`, which is the background daemon, and not `cnry serve`, which runs in the foreground and will block you until I stop it, even though some error messages suggest it. Stop anything you started with `cnry stop`.\n4. List projects with the connected project tool or `cnry project list --format json`, and reuse one whose domain matches. Confirm the proposed name is not already assigned to a different domain. To find out whether a project has already been scanned, run `cnry technical-aeo score <project> --format json` with no `--run-id`, which reports the latest run. Read the `hasData` field, not the score: this command exits 0 and reports `aggregateScore: 0` for a project that has never been scanned, so reading the score alone would have you tell me my site scored zero. If `hasData` is true and `runStatus` is `completed` or `partial`, read that scan instead of starting a new one. If no project matches, show the exact create operation and wait for approval.\n5. Propose a bounded Site Health scan: `--max-pages 100` for a first look, plus whether dead-link checking is on (it is off unless you pass `--check-dead-links`). Show the connected operation or the exact `cnry technical-aeo run <project> --max-pages 100 --wait --format json` command with the project name filled in, and wait for separate approval before scanning. `--wait` polls for up to 15 minutes and returns only the run id and status. If the status it returns is still `queued` or `running`, the scan has not finished: do not rerun it or report results, poll `cnry technical-aeo progress <project> --run-id <run-id> --format json` until it is terminal. If `--wait` outruns your own tool timeout first, recover the run id with `cnry technical-aeo score <project> --format json` and poll the same way.\n6. When the run is `completed` or `partial`, read `cnry technical-aeo crawl <project> --run-id <run-id> --format json` first. It is the only one of these commands that carries `termination` and `complete`; the score and pages commands do not. Then read `cnry technical-aeo score <project> --run-id <run-id> --format json` and `cnry technical-aeo pages <project> --run-id <run-id> --sort score-asc --limit 10 --format jsonl`. Tell me the termination reason in plain words and whether the scan covered the whole site or stopped at a page, link, depth, or time limit. A `partial` run scored the pages it reached and not my site, so never present it as a full-site result. If it stopped early, the fix depends on the reason, so say which: a page or depth limit needs a larger budget, a time limit needs a smaller scan (a lower `--max-pages` or `--max-depth`). If the run failed or was cancelled, inspect the run error and stop.\n7. Summarize only completed evidence, then propose AI Visibility setup. Ask before you add queries, connect providers, start a provider-backed or quota-consuming run, edit files, or publish.";function aJ(e,n){return e==="legacy"?"legacy":e==="platform"?"platform":n.state==="success"?n.projectCount===0?"platform":"legacy":n.state==="error"?"retry":"loading"}const iJ="2000-01-01T00:00:00.000Z",sJ=5e3;function oJ(e,n){const i=new Set,r=new Map;for(const f of n)f.trigger!==ks.probe&&(r.has(f.projectId)||r.set(f.projectId,f.id),(f.status===nn.completed||f.status===nn.partial)&&i.add(f.projectId));const h=(e.every(f=>f.createdAt)?[...e].sort((f,b)=>(f.createdAt??"").localeCompare(b.createdAt??"")||f.name.localeCompare(b.name)):e).find(f=>!i.has(f.id));return h?{projectName:h.name,runId:r.get(h.id)}:null}const BC=[{value:"US",label:"United States"},{value:"CA",label:"Canada"},{value:"GB",label:"United Kingdom"},{value:"AU",label:"Australia"},{value:"NZ",label:"New Zealand"},{value:"IE",label:"Ireland"},{value:"DE",label:"Germany"},{value:"FR",label:"France"},{value:"ES",label:"Spain"},{value:"IT",label:"Italy"},{value:"NL",label:"Netherlands"},{value:"BR",label:"Brazil"},{value:"MX",label:"Mexico"},{value:"IN",label:"India"},{value:"SG",label:"Singapore"},{value:"JP",label:"Japan"}],LC=[{value:"en",label:"English"},{value:"es",label:"Spanish"},{value:"fr",label:"French"},{value:"de",label:"German"},{value:"it",label:"Italian"},{value:"pt",label:"Portuguese"},{value:"nl",label:"Dutch"},{value:"ja",label:"Japanese"}];function rJ(e,n){try{const i=new Intl.DisplayNames(["en"],{type:"region"}),r=new Intl.DisplayNames(["en"],{type:"language"}),u=e.length===2?i.of(e.toUpperCase()):void 0,h=n?r.of(n.toLowerCase()):void 0;return`${u??(e||"Country")} · ${h??(n||"Language")}`}catch{return`${e||"Country"} · ${n||"Language"}`}}function lJ(e,n){const i=e.trim().toUpperCase(),r=n.trim().toLowerCase();return{countryValid:BC.some(u=>u.value===i),languageValid:LC.some(u=>u.value===r)}}function cJ(e){const n=e.replace(/^\[|\]$/g,"");return/^(?:\d{1,3}\.){3}\d{1,3}$/.test(n)||n.includes(":")}function uJ(e){const n=e.trim();if(!n)return null;const i=/^[a-z][a-z\d+.-]*:\/\//i.test(n)?n:`https://${n}`;let r;try{r=new URL(i)}catch{return null}if(r.protocol!=="http:"&&r.protocol!=="https:")return null;const u=r.hostname.toLowerCase().replace(/^www\./,"");if(!u||u==="localhost"||cJ(u)||!u.includes("."))return null;const h=u.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return h?{canonicalDomain:u,projectName:h,displayName:u}:null}async function dJ(e,n=eJ){let i;const r=new Promise(h=>{i=setTimeout(()=>h({state:"timed-out"}),n)}),u=await Promise.race([e.then(h=>({state:"queued",run:h})),r]);return i&&clearTimeout(i),u}function mJ(e,n){e.catch(()=>{wn({title:"Site Health scan did not start",detail:"The project is safe. Choose Run scan in Site Health to retry.",tone:"negative",dedupeKey:`site-health-dispatch:${n}`})})}function VC(e){const n=C.useRef(g1()).current,i=C.useRef(new Set),r=C.useCallback((u,h)=>{if(h){if(i.current.has(h))return;i.current.add(h)}n1({...u,surface:e,eventId:y1()})},[e]);return{onboardingSessionId:n,emit:r}}function Ik(e,n){return e instanceof xn&&e.statusCode===409?"A project with this name already exists. Change the project name, or open the existing project.":e instanceof Error&&e.message?e.message:n}function wg(){return l.jsxs("div",{className:"page-container max-w-3xl","aria-busy":"true","aria-live":"polite",children:[l.jsx("div",{className:"page-header",children:l.jsxs("div",{className:"page-header-left",children:[l.jsx("h1",{className:"page-title",children:"Preparing setup"}),l.jsx("p",{className:"page-subtitle",children:"Checking the projects already on this install."})]})}),l.jsxs("div",{className:"flex items-center gap-3 rounded-lg border border-default bg-surface p-4 text-sm text-secondary",role:"status",children:[l.jsx(Rr,{className:"size-4 motion-safe:animate-spin","aria-hidden":"true"}),"Loading projects…"]})]})}function pJ({onRetry:e}){return l.jsxs("div",{className:"page-container max-w-3xl",children:[l.jsx("div",{className:"page-header",children:l.jsxs("div",{className:"page-header-left",children:[l.jsx("h1",{className:"page-title",children:"Can’t load projects"}),l.jsx("p",{className:"page-subtitle",children:"Canonry could not confirm whether this install already has a project."})]})}),l.jsxs("div",{className:"rounded-lg border border-negative bg-negative-soft p-4",role:"alert",tabIndex:-1,children:[l.jsx("p",{className:"text-sm font-medium text-heading",children:"Setup is paused to protect existing projects."}),l.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Check the connection or sign in again, then retry."}),l.jsx(ue,{type:"button",className:"mt-4",variant:"secondary",onClick:e,children:"Retry project check"})]})]})}function hJ({projectName:e,initialRunId:n}){return l.jsx(h1,{title:"Site Health setup",children:l.jsx(fJ,{projectName:e,initialRunId:n})})}function fJ({projectName:e,initialRunId:n}){const i=Ns(),r=yt({...Do({client:J}),enabled:!!e,retry:!1,refetchOnMount:"always"}),{onboardingSessionId:u,emit:h}=VC("site_health"),[f]=C.useState(()=>yX(n));C.useEffect(()=>{f&&bX()},[f]),C.useEffect(()=>{e&&h({flowVersion:ft,onboardingSessionId:u,event:"onboarding.started",step:"run",resumed:!!n&&!f},"onboarding.started")},[h,f,n,u,e]),C.useEffect(()=>{!e||!n||OC(e)?.runId!==n&&IC(e,n)},[n,e]);const v=yt({...o1({client:J,path:{id:n??""}}),enabled:!!n,refetchInterval:({state:N})=>{const P=N.data?.status;return P==="completed"||P==="partial"||P==="failed"||P==="cancelled"?!1:2e3},refetchIntervalInBackground:!0}).data?.status;if(C.useEffect(()=>{if(!e||!n||!v)return;if(v==="completed"||v==="partial"){h({flowVersion:ft,onboardingSessionId:u,event:"onboarding.step_completed",step:"run",method:"automatic"},"onboarding.step_completed:run"),Yd(n);return}if(v!=="failed"&&v!=="cancelled")return;const N=v==="cancelled"?"run_cancelled":"run_failed";h({flowVersion:ft,onboardingSessionId:u,event:"onboarding.blocked",step:"run",action:"retry_run",reasonCode:N},`onboarding.blocked:run:${N}`),Yd(n)},[h,n,u,e,v]),!e)return l.jsxs("div",{className:"page-container max-w-3xl",children:[l.jsx("div",{className:"page-header",children:l.jsxs("div",{className:"page-header-left",children:[l.jsx("h1",{className:"page-title",children:"Project not found"}),l.jsx("p",{className:"page-subtitle",children:"This setup link does not identify a project."})]})}),l.jsx(ue,{type:"button",variant:"secondary",onClick:()=>{i({to:"/projects"})},children:"View projects"})]});if(r.isPending)return l.jsxs("div",{className:"page-container max-w-3xl","aria-busy":"true","aria-live":"polite",children:[l.jsx(jo,{current:"site"}),l.jsxs("div",{className:"mt-8 flex items-center gap-3 text-sm text-secondary",role:"status",children:[l.jsx(Rr,{className:"size-4 motion-safe:animate-spin","aria-hidden":"true"}),"Loading Site Health setup…"]})]});if(r.isError)return l.jsxs("div",{className:"page-container max-w-3xl",children:[l.jsx("div",{className:"page-header",children:l.jsxs("div",{className:"page-header-left",children:[l.jsx("h1",{className:"page-title",children:"Can’t resume setup"}),l.jsx("p",{className:"page-subtitle",children:"Canonry could not load the project for this Site Health scan."})]})}),l.jsxs("div",{className:"rounded-lg border border-negative bg-negative-soft p-4",role:"alert",children:[l.jsx("p",{className:"text-sm text-secondary",children:"Check the connection or sign in again, then retry."}),l.jsx(ue,{type:"button",className:"mt-4",variant:"secondary",onClick:()=>{r.refetch()},children:"Retry project check"})]})]});const w=r.data.find(N=>N.name===e);if(!w)return l.jsxs("div",{className:"page-container max-w-3xl",children:[l.jsx("div",{className:"page-header",children:l.jsxs("div",{className:"page-header-left",children:[l.jsx("h1",{className:"page-title",children:"Project not found"}),l.jsxs("p",{className:"page-subtitle",children:["Canonry could not find ",e,". It will not open a different project."]})]})}),l.jsx(ue,{type:"button",variant:"secondary",onClick:()=>{i({to:"/projects"})},children:"View projects"})]});const k=()=>{i({to:"/setup",search:{onboarding:"site-health",setupProject:w.name},replace:!0})},j=()=>{i({to:"/setup",search:{experience:"legacy",onboarding:"site-health",setupProject:w.name},replace:!0})},T=()=>{h({flowVersion:ft,onboardingSessionId:u,event:"onboarding.step_completed",step:"run",method:"skipped"},"onboarding.step_completed:run"),i({to:"/setup",search:{onboarding:"complete",setupProject:w.name,skipped:"visibility"},replace:!0})};return l.jsxs("div",{className:"page-container max-w-7xl py-8 md:py-10",children:[l.jsx("h1",{className:"sr-only",children:"Set up Canonry"}),l.jsx(C.Suspense,{fallback:l.jsxs("div",{className:"space-y-5",children:[l.jsx(jo,{current:"site"}),l.jsxs("div",{className:"flex min-h-72 items-center justify-center gap-3 text-sm text-secondary",role:"status",children:[l.jsx(Rr,{className:"size-4 motion-safe:animate-spin","aria-hidden":"true"}),"Loading Site Health…"]})]}),children:l.jsx(JX,{projectName:w.name,projectId:w.id,initialRunId:n,onReleaseInitialRun:k,showOnboardingActions:!0,onContinueOnboarding:j,onSkipOnboarding:T})})]})}function gJ(){const e=Pk({from:"/setup"}),n=e.onboarding==="site-health"&&!e.setupProject,i=e.onboarding==="site-health"&&e.experience!=="legacy",r=bG(),u=e.experience==="legacy"?"legacy":e.experience==="platform"?"platform":r,[h,f]=C.useState(!1),[b,v]=C.useState(void 0),w=yt({...Do({client:J}),enabled:u==="auto",retry:!1,refetchOnMount:"always"}),k=yt({..._m({client:J,query:{kind:ze["site-audit"],since:iJ,limit:sJ}}),enabled:u==="auto",retry:!1,refetchOnMount:"always"}),j=u==="auto"&&w.isSuccess&&w.isFetchedAfterMount&&w.data.length===0;C.useEffect(()=>{j&&f(!0)},[j]);const T=u!=="auto"?{state:"idle"}:w.isSuccess&&w.isFetchedAfterMount?{state:"success",projectCount:w.data.length}:w.isError?{state:"error"}:{state:"loading"},N=u==="legacy"?"legacy":h||j?"platform":aJ(u,T);if(e.onboarding==="complete"&&e.setupProject)return l.jsx(BX,{projectName:e.setupProject,skippedVisibility:e.skipped==="visibility"});if(n||i)return l.jsx(hJ,{projectName:e.setupProject,initialRunId:e.siteHealthRunId});const P=u==="auto"&&N==="legacy"&&!e.setupProject&&w.isSuccess;if(P&&b===void 0)return k.isError?v(null):k.isSuccess&&k.isFetchedAfterMount&&v(oJ(w.data,k.data)),l.jsx(wg,{});const E=P?b:null;return E?l.jsx(yJ,{projectName:E.projectName,runId:E.runId}):N==="legacy"?l.jsx(OX,{visibilityProjectName:e.setupProject,siteHealthOnboarding:e.onboarding==="site-health",onboardingFinish:e.onboarding==="site-health"||e.onboarding==="first-run"}):N==="loading"?l.jsx(wg,{}):N==="retry"?l.jsx(pJ,{onRetry:()=>{w.refetch()}}):l.jsx(bJ,{onActivationStarted:()=>f(!0),skipSiteScan:e.siteScan==="skip"})}function yJ({projectName:e,runId:n}){const i=Ns();return C.useEffect(()=>{i({to:"/setup",search:{onboarding:"site-health",setupProject:e,...n?{siteHealthRunId:n}:{}},replace:!0})},[i,e,n]),l.jsx(wg,{})}function bJ({onActivationStarted:e,skipSiteScan:n}){return l.jsx(h1,{title:"Site Health setup",children:l.jsx(vJ,{onActivationStarted:e,skipSiteScan:n})})}function vJ({onActivationStarted:e,skipSiteScan:n}){const i=Ns(),r=Jn(),u=AX(),h=yt({...gH({client:J}),retry:!1}),f=Ga(yH()),[b,v]=C.useState(""),[w,k]=C.useState(""),[j,T]=C.useState(""),[N,P]=C.useState("US"),[E,q]=C.useState("en"),[H,X]=C.useState(!1),[L,Z]=C.useState("idle"),[Y,ee]=C.useState(null),[B,K]=C.useState(null),[we,Xe]=C.useState(!1),[nt,Ue]=C.useState(null),[Pe,ke]=C.useState(!1),$e=h.isError?void 0:h.data,O=typeof $e?.enabled=="boolean"?$e.enabled:null,ne=f.isPending?f.variables.body.enabled:O,[ge,Se]=C.useState(null),ae=C.useRef(null),{onboardingSessionId:_e,emit:Be}=VC("platform");C.useEffect(()=>{Be({flowVersion:ft,onboardingSessionId:_e,event:"onboarding.started",step:"project",resumed:!1},"onboarding.started")},[Be,_e]);const ve=uJ(b),le=w||ve?.projectName||"",ce=j||ve?.displayName||"",Q=L==="creating"||L==="dispatching",me=B??nt,De=rJ(N,E),{countryValid:je,languageValid:it}=lJ(N,E),Ge=je&&it;C.useEffect(()=>{me&&ae.current?.focus()},[me]);const jt=(Le,ct)=>i({to:"/setup",search:{...ct?{siteHealthRunId:ct}:{},onboarding:"site-health",setupProject:Le.name},replace:!0}),He=async Le=>{Z("dispatching"),Ue(null);try{const ct=u.mutateAsync({projectName:Le.name,projectId:Le.id,projectLabel:Le.displayName||Le.name,suppressErrorToast:!0,body:{checkDeadLinks:!0,maxPages:n3}}),Kt=await dJ(ct);if(Kt.state==="queued"){Be({flowVersion:ft,onboardingSessionId:_e,event:"run.requested",origin:"dashboard_setup",result:"queued",kind:"site_health",providerCountBucket:"0",queryCountBucket:"0"}),gX(Kt.run.runId),await jt(Le,Kt.run.runId);return}ct.then(()=>{Be({flowVersion:ft,onboardingSessionId:_e,event:"run.requested",origin:"dashboard_setup",result:"queued",kind:"site_health",providerCountBucket:"0",queryCountBucket:"0"})},Ht=>{Be({flowVersion:ft,onboardingSessionId:_e,event:"run.requested",origin:"dashboard_setup",result:"rejected",kind:"site_health",providerCountBucket:"0",queryCountBucket:"0",reasonCode:gc(Ht,"run_rejected")})}),mJ(ct,Le.id),await jt(Le)}catch(ct){Z("recovery"),Ue(Ik(ct,"The project was created, but the Site Health scan could not be started."));const Kt=gc(ct,"run_rejected");Be({flowVersion:ft,onboardingSessionId:_e,event:"run.requested",origin:"dashboard_setup",result:"rejected",kind:"site_health",providerCountBucket:"0",queryCountBucket:"0",reasonCode:Kt}),Be({flowVersion:ft,onboardingSessionId:_e,event:"onboarding.blocked",step:"run",action:"retry_run",reasonCode:Kt},`onboarding.blocked:run:${Kt}`)}},re=async Le=>{if(Le.preventDefault(),!(!ve||!n&&!H||!Ge||Q)){Z("creating"),K(null),Xe(!1),Ue(null);try{const ct=await MG({name:le,displayName:ce,canonicalDomain:ve.canonicalDomain,country:N,language:E});if(e(),ee(ct),Be({flowVersion:ft,onboardingSessionId:_e,event:"onboarding.step_completed",step:"project",method:"manual"},"onboarding.step_completed:project"),await r.invalidateQueries({queryKey:As({client:J})}),n){await i({to:"/setup",search:{experience:"legacy",onboarding:"first-run",setupProject:ct.name},replace:!0});return}await He(ct)}catch(ct){Z("idle");const Kt=ct instanceof xn&&ct.statusCode===409;Xe(Kt),K(Ik(ct,"Could not create the project. Try again.")),Be({flowVersion:ft,onboardingSessionId:_e,event:"onboarding.blocked",step:"project",action:"save",reasonCode:gc(ct,"project_create_failed")},"onboarding.blocked:project"),Kt&&(e(),r.invalidateQueries({queryKey:As({client:J})}))}}},lt=()=>{Y&&!Q&&He(Y)},Gt=()=>{Q||i({to:"/projects"})},ea=async()=>{try{await navigator.clipboard.writeText(nJ),ke(!0)}catch{wn({tone:"negative",title:"Could not copy setup request",detail:"Open the agent quickstart to continue with the CLI instead."})}},ci=async Le=>{Se(null);try{const ct=await f.mutateAsync({client:J,body:{enabled:Le}});r.setQueryData(JA({client:J}),ct),ct.enabled!==Le&&Se(`The server kept telemetry ${ct.enabled?"on":"off"}. Check its telemetry settings.`)}catch{Se("Could not update telemetry. Try again.")}};return Y&&L==="recovery"?l.jsxs("div",{className:"page-container max-w-3xl",children:[l.jsx(jo,{current:"site"}),l.jsx("div",{className:"page-header mt-8",children:l.jsxs("div",{className:"page-header-left",children:[l.jsx("h1",{className:"page-title",children:"Project created"}),l.jsxs("p",{className:"page-subtitle",children:[Y.displayName||Y.name," is ready. The Site Health scan needs another try."]})]})}),l.jsxs("div",{ref:ae,className:"rounded-lg border border-negative bg-negative-soft p-4",role:"alert",tabIndex:-1,children:[l.jsx("p",{className:"text-sm font-medium text-heading",children:nt}),l.jsx("p",{className:"mt-1 text-sm text-secondary",children:"You can retry the scan or continue setup and retry from Site Health."}),l.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[l.jsx(ue,{type:"button",onClick:lt,children:"Retry Site Health scan"}),l.jsx(ue,{type:"button",variant:"secondary",onClick:()=>{jt(Y)},children:"Continue setup"})]})]})]}):l.jsxs("div",{className:"page-container max-w-xl py-8 md:py-12",children:[n?null:l.jsx(jo,{current:"site"}),l.jsxs("header",{className:`mb-8 ${n?"":"mt-8"}`,children:[l.jsx("h1",{id:"site-map-setup-title",className:"text-2xl font-semibold tracking-[-0.025em] text-heading",children:n?"Create a project":"Scan your site"}),l.jsx("p",{className:"mt-2 max-w-lg text-sm leading-6 text-secondary",children:n?"Add a public domain, then choose the queries you want to track. No site scan will run.":"Enter your public website to see its pages, structure, internal links, and technical SEO scores."})]}),l.jsxs("form",{"aria-labelledby":"site-map-setup-title",className:"space-y-6",onSubmit:pn(re),noValidate:!0,children:[l.jsxs("div",{className:"grid gap-2",children:[l.jsx("label",{className:"text-sm font-medium text-heading",htmlFor:"launchpad-domain",children:"Website URL"}),l.jsx("input",{id:"launchpad-domain",className:"h-11 w-full rounded-md border border-strong bg-bg-elevated/50 px-3 text-base text-heading outline-none transition placeholder:text-muted focus:border-mono-500 focus:ring-1 focus:ring-mono-500",type:"text",inputMode:"url",autoComplete:"url",autoCapitalize:"none",spellCheck:!1,required:!0,"aria-invalid":!!(b&&!ve),"aria-describedby":b&&!ve?"launchpad-domain-hint launchpad-domain-error":"launchpad-domain-hint",placeholder:"https://example.com",value:b,onChange:Le=>{v(Le.target.value),K(null),Xe(!1)}}),l.jsx("p",{id:"launchpad-domain-hint",className:"text-sm text-secondary",children:n?l.jsxs(l.Fragment,{children:["A public domain is still required."," ",l.jsx(We,{to:"/setup",search:{experience:"platform"},className:"font-medium text-link underline-offset-4 hover:underline",children:"Map with Site Health instead"})]}):l.jsxs(l.Fragment,{children:["Only public pages are scanned."," ",l.jsx(We,{to:"/setup",search:{experience:"platform",onboarding:"first-run",siteScan:"skip"},className:"font-medium text-link underline-offset-4 hover:underline",children:"Set up without a site scan"})]})}),b&&!ve?l.jsx("p",{id:"launchpad-domain-error",className:"text-sm text-negative",role:"alert",children:"Enter a public domain, such as example.com."}):null]}),l.jsxs("details",{className:"group border-y border-default",children:[l.jsxs("summary",{className:"flex min-h-11 cursor-pointer list-none items-center justify-between gap-4 py-3 text-sm [&::-webkit-details-marker]:hidden",children:[l.jsx("span",{className:"font-medium text-heading",children:"Project name and locale"}),l.jsxs("span",{className:"flex items-center gap-2 text-secondary",children:[De,l.jsx(Jd,{className:"size-4 transition-transform group-open:rotate-180 motion-reduce:transition-none","aria-hidden":"true"})]})]}),l.jsxs("div",{className:"space-y-5 border-t border-default py-4",children:[ve?l.jsxs("div",{children:[l.jsx("p",{className:"mb-3 text-sm font-medium text-heading",children:"Project"}),l.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[l.jsxs("div",{className:"grid gap-2",children:[l.jsx("label",{className:"text-sm text-secondary",htmlFor:"launchpad-project-name",children:"Project name"}),l.jsx("input",{id:"launchpad-project-name",className:"setup-input h-10",type:"text",value:le,onChange:Le=>k(Le.target.value)})]}),l.jsxs("div",{className:"grid gap-2",children:[l.jsx("label",{className:"text-sm text-secondary",htmlFor:"launchpad-display-name",children:"Display name"}),l.jsx("input",{id:"launchpad-display-name",className:"setup-input h-10",type:"text",value:ce,onChange:Le=>T(Le.target.value)})]})]})]}):null,l.jsxs("div",{children:[l.jsx("p",{className:"mb-3 text-sm font-medium text-heading",children:"Locale"}),l.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[l.jsxs("div",{className:"grid gap-2",children:[l.jsx("label",{className:"text-sm text-secondary",htmlFor:"launchpad-country",children:"Country"}),l.jsx("select",{id:"launchpad-country",className:"setup-input h-10",value:N,onChange:Le=>P(Le.target.value),children:BC.map(Le=>l.jsx("option",{value:Le.value,children:Le.label},Le.value))})]}),l.jsxs("div",{className:"grid gap-2",children:[l.jsx("label",{className:"text-sm text-secondary",htmlFor:"launchpad-language",children:"Language"}),l.jsx("select",{id:"launchpad-language",className:"setup-input h-10",value:E,onChange:Le=>q(Le.target.value),children:LC.map(Le=>l.jsx("option",{value:Le.value,children:Le.label},Le.value))})]})]})]})]})]}),n?null:l.jsxs("label",{className:"flex min-h-11 cursor-pointer items-start gap-3 py-2",children:[l.jsx("input",{className:"mt-0.5 size-4 shrink-0 rounded border-strong bg-bg",type:"checkbox",checked:H,onChange:Le=>X(Le.target.checked),"aria-label":"Allow Canonry to scan this public site."}),l.jsxs("span",{className:"flex items-center gap-1.5",children:[l.jsx("span",{className:"text-sm leading-5 text-heading",children:"Allow Canonry to scan this public site."}),l.jsx(Ua,{text:WX})]})]}),me?l.jsxs("div",{ref:ae,className:"rounded-md border border-negative bg-negative-soft p-3",role:"alert",tabIndex:-1,children:[l.jsx("p",{className:"text-sm font-medium text-heading",children:me}),we?l.jsx(ue,{type:"button",variant:"secondary",size:"sm",className:"mt-3",onClick:Gt,children:"View projects"}):null]}):null,l.jsxs("div",{className:"grid gap-2",children:[l.jsx(ue,{className:"h-11 w-full",type:"submit",disabled:!ve||!n&&!H||!Ge||Q,children:L==="creating"||L==="dispatching"?l.jsxs(l.Fragment,{children:[l.jsx(Rr,{className:"size-4 motion-safe:animate-spin","aria-hidden":"true"})," ",n?"Creating project…":"Mapping site…"]}):n?"Create project":"Scan site"}),L==="dispatching"?l.jsx("span",{className:"text-center text-sm text-secondary",role:"status",children:"Opening Site Health when the scan is ready."}):null]})]}),l.jsxs("section",{className:"mt-8 border-t border-default pt-6","aria-labelledby":"agent-setup-title",children:[l.jsx("p",{id:"agent-setup-title",className:"text-sm font-medium text-heading",children:"Use your agent instead"}),l.jsx("p",{className:"mt-1 text-sm leading-5 text-secondary",children:"Copy a complete CLI setup request into any agent."}),l.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-1",children:[l.jsxs(ue,{type:"button",variant:"ghost",size:"sm",className:"-ml-3",onClick:pn(ea),children:[Pe?l.jsx(Wd,{className:"size-3.5","aria-hidden":"true"}):l.jsx(Cg,{className:"size-3.5","aria-hidden":"true"}),l.jsx("span",{"aria-live":"polite",children:Pe?"Copied setup request":"Copy setup request"})]}),l.jsx(ue,{asChild:!0,variant:"ghost",size:"sm",children:l.jsxs("a",{href:tJ,target:"_blank",rel:"noopener noreferrer",children:["Agent quickstart",l.jsx(w5,{className:"size-3.5","aria-hidden":"true"}),l.jsx("span",{className:"sr-only",children:" (opens in a new tab)"})]})})]})]}),O!==null?l.jsxs("section",{className:"mt-6 border-t border-default pt-5","aria-labelledby":"telemetry-title",children:[l.jsxs("label",{className:`flex min-h-11 items-start gap-3 py-2 ${f.isPending?"cursor-wait":"cursor-pointer"}`,children:[l.jsx("input",{className:"mt-0.5 size-4 shrink-0 rounded border-strong bg-bg accent-accent focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-mono-500 disabled:cursor-wait",type:"checkbox",checked:ne??!1,disabled:f.isPending,onChange:Le=>{ci(Le.target.checked)},"aria-describedby":"telemetry-detail"}),l.jsxs("span",{className:"grid gap-0.5",children:[l.jsx("span",{id:"telemetry-title",className:"text-sm leading-5 text-heading",children:"Share anonymous product telemetry"}),l.jsx("span",{id:"telemetry-detail",className:"max-w-[70ch] text-sm leading-5 text-secondary",children:"Helps prioritize improvements. Canonry does not send raw domains, URLs, queries, answer content, or credentials."})]})]}),f.isPending?l.jsx("p",{className:"mt-1 text-sm text-secondary",role:"status",children:"Saving preference…"}):null,ge?l.jsx("p",{className:"mt-1 text-sm text-negative",role:"alert",children:ge}):null]}):null]})}function xJ(){return l.jsx("div",{className:"page-container",children:l.jsx("section",{className:"page-section",children:l.jsxs(_a,{className:"surface-card empty-card",children:[l.jsx("h1",{children:"Route not found"}),l.jsx("p",{children:"The current path does not map to a dashboard view."}),l.jsx(ue,{asChild:!0,children:l.jsx(We,{to:"/",children:"Return to overview"})})]})})})}const ha=_s(()=>Li(()=>import("./ProjectPage-BPtdO-Gp.js"),__vite__mapDeps([5,1,2,6,0,3,4,7,8,9,10,11,12]),import.meta.url),"ProjectPage"),wJ=_s(()=>Li(()=>import("./RunsPage-BvCCjtqM.js"),__vite__mapDeps([13,1,6,11,4,2,9,12]),import.meta.url),"RunsPage"),kJ=_s(()=>Li(()=>import("./HistoryPage-CKgF71m5.js"),__vite__mapDeps([14,1,10,11,4,2,9,12]),import.meta.url),"HistoryPage"),SJ=_s(()=>Li(()=>import("./SettingsPage-B1QuP6Cv.js"),__vite__mapDeps([15,1,11,4,2,9,12]),import.meta.url),"SettingsPage"),jJ=_s(()=>Li(()=>import("./BacklinksPage-8-KPXFtA.js"),__vite__mapDeps([16,1,2,11,4,9,12]),import.meta.url),"BacklinksPage"),AJ=_s(()=>Li(()=>import("./TrafficPage-DEUDhBXG.js"),__vite__mapDeps([17,1,7,2,11,4,9,12]),import.meta.url),"TrafficPage"),CJ=_s(()=>Li(()=>import("./TrafficSourceDetailPage-gpgLsGA1.js"),__vite__mapDeps([18,1,7,3,4,2,11,9,12]),import.meta.url),"TrafficSourceDetailPage"),NJ=_s(()=>Li(()=>import("./MeasurementPropertyPage-nfGYHl6C.js"),__vite__mapDeps([19,1,3,4,8,9,2,11,12]),import.meta.url),"MeasurementPropertyPage");function _J(){return l.jsx(OY,{children:l.jsx(_K,{children:l.jsx(IY,{})})})}const Vn=XN()({component:_J,validateSearch:e=>({manageQueries:e.manageQueries===!0||e.manageQueries==="true"?!0:void 0,runId:typeof e.runId=="string"?e.runId:void 0,siteHealthRunId:typeof e.siteHealthRunId=="string"?e.siteHealthRunId:void 0,evidenceId:typeof e.evidenceId=="string"?e.evidenceId:void 0,runStatus:typeof e.runStatus=="string"?e.runStatus:void 0,runKind:typeof e.runKind=="string"?e.runKind:void 0,runProject:typeof e.runProject=="string"?e.runProject:void 0,runWindow:typeof e.runWindow=="string"?e.runWindow:void 0,runQuery:typeof e.runQuery=="string"?e.runQuery:void 0,onboarding:e.onboarding==="site-health"||e.onboarding==="first-run"||e.onboarding==="complete"?e.onboarding:void 0,experience:e.experience==="legacy"||e.experience==="platform"?e.experience:void 0,siteScan:e.siteScan==="skip"?"skip":void 0,skipped:e.skipped==="visibility"?"visibility":void 0,setupProject:typeof e.setupProject=="string"?e.setupProject:void 0,scope:typeof e.scope=="string"?e.scope:void 0,class:typeof e.class=="string"?e.class:void 0,...Object.fromEntries(["queryWorkspace","researchMode","trackingQueryId","measurementScope","measurementScopeKey","measurementMarketKey","queryClass","measurementProvider","measurementModel","measurementLocation","measurementFrom","measurementTo","measurementRevision","measurementRunId","measurementQueryKey","measurementAnswer"].map(n=>[n,typeof e[n]=="string"?e[n]:void 0]))})}),TJ=qt({getParentRoute:()=>Vn,path:"/",component:sX,beforeLoad:async({context:e})=>{let n=e.queryClient.getQueryData(As({client:J}));if(n===void 0)try{n=await e.queryClient.ensureQueryData(Do({client:J}))}catch{return}if(n.length===0)throw Mk({to:"/setup"})}}),EJ=qt({getParentRoute:()=>Vn,path:"/projects",component:cX}),RJ=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,$n=qt({getParentRoute:()=>Vn,path:"/projects/$projectName",component:()=>l.jsx(Tf,{}),beforeLoad:async({context:e,params:n,location:i})=>{const r=n.projectName;if(!RJ.test(r))return;let u=e.queryClient.getQueryData(As({client:J}));if(!u)try{u=await e.queryClient.ensureQueryData(Do({client:J}))}catch{return}const h=u.find(f=>f.id===r);if(h)throw Mk({to:i.pathname.replace(`/projects/${r}`,`/projects/${encodeURIComponent(h.name)}`),replace:!0})}}),DJ=qt({getParentRoute:()=>$n,path:"/",component:()=>l.jsx(ha,{tab:"overview"})}),zJ=qt({getParentRoute:()=>$n,path:"/portfolio",component:()=>l.jsx(ha,{tab:"portfolio"})}),IJ=qt({getParentRoute:()=>$n,path:"/search-console",component:()=>l.jsx(ha,{tab:"search-console"})}),OJ=qt({getParentRoute:()=>$n,path:"/conversions",component:()=>l.jsx(ha,{tab:"conversions"})}),PJ=qt({getParentRoute:()=>$n,path:"/local",component:()=>l.jsx(ha,{tab:"local"})}),qJ=qt({getParentRoute:()=>$n,path:"/discovery",component:()=>l.jsx(ha,{tab:"discovery"})}),MJ=qt({getParentRoute:()=>$n,path:"/queries",component:()=>l.jsx(ha,{tab:"queries"})}),BJ=qt({getParentRoute:()=>$n,path:"/properties/$targetKey",component:()=>l.jsx(NJ,{})}),LJ=qt({getParentRoute:()=>$n,path:"/report",component:()=>l.jsx(ha,{tab:"report"})}),VJ=qt({getParentRoute:()=>$n,path:"/activity",component:()=>l.jsx(ha,{tab:"activity"})}),$J=qt({getParentRoute:()=>$n,path:"/backlinks",component:()=>l.jsx(ha,{tab:"backlinks"})}),UJ=qt({getParentRoute:()=>$n,path:"/technical-aeo",component:()=>l.jsx(ha,{tab:"technical-aeo"})}),GJ=qt({getParentRoute:()=>$n,path:"/history",component:()=>l.jsx(ha,{tab:"history"})}),KJ=qt({getParentRoute:()=>$n,path:"/settings",component:()=>l.jsx(ha,{tab:"settings"})}),HJ=qt({getParentRoute:()=>Vn,path:"/runs",component:wJ}),QJ=qt({getParentRoute:()=>Vn,path:"/history",component:kJ}),FJ=qt({getParentRoute:()=>Vn,path:"/settings",component:SJ,beforeLoad:({context:e})=>{}}),ZJ=qt({getParentRoute:()=>Vn,path:"/setup",component:gJ}),YJ=qt({getParentRoute:()=>Vn,path:"/backlinks",component:jJ}),XJ=qt({getParentRoute:()=>Vn,path:"/traffic",component:AJ}),JJ=qt({getParentRoute:()=>Vn,path:"/traffic/$projectName/$sourceId",component:CJ}),WJ=qt({getParentRoute:()=>Vn,path:"*",component:xJ}),eW=Vn.addChildren([TJ,EJ,$n.addChildren([DJ,zJ,IJ,OJ,PJ,qJ,MJ,BJ,LJ,VJ,$J,UJ,GJ,KJ]),HJ,QJ,FJ,ZJ,YJ,XJ,JJ,WJ]);function tW(){return typeof window<"u"&&window.__CANONRY_CONFIG__?.basePath?window.__CANONRY_CONFIG__.basePath:"/"}const Ok=tW(),nW=Ok==="/"?"":Ok.replace(/\/$/,"");function aW(e,n){return JN({routeTree:eW,basepath:nW||"/",context:{queryClient:e},...n?.initialEntries})}const iW=6e4;function sW(){const e=C.useRef(OG()).current,[n,i]=C.useState(e?"ready":"checking"),[r,u]=C.useState(null),[h,f]=C.useState(null),[b,v]=C.useState(e),[w,k]=C.useState(!1),[j,T]=C.useState(""),[N,P]=C.useState(""),[E,q]=C.useState(""),[H,X]=C.useState(!1),[L,Z]=C.useState("password"),[Y,ee]=C.useState(null),[B,K]=C.useState(!1),[we,Xe]=C.useState(!1),nt=C.useRef(null),Ue=C.useRef(null),Pe=C.useRef(null),ke=()=>{const Q=r?`${r.name}:${r.role}`:e?"api-key:explicit":h?`api-key:${h.id}`:"no-accounts";if(!nt.current||Pe.current!==Q){Ue.current?.clear();const me=AK();Ue.current=me,nt.current=aW(me),Pe.current=Q}return{queryClient:Ue.current,router:nt.current}},$e=Q=>Q.authRequired?(k(!0),u(Q.user),f(null),v(!1),i(Q.user?"ready":"account-login"),!0):!1;C.useEffect(()=>{let Q=!1;const me=async(De,je=!1)=>{try{const it=await xf();if(Q)return;f(it),v(!1),i("ready")}catch(it){if(Q)return;if(je&&it instanceof xn&&it.statusCode===401)return QG().then(()=>{Q||(ee(null),f(null),v(!1),Xe(!0),i("login"))}).catch(Ge=>{Q||(ee(Ge instanceof Error?Ge.message:"Could not clear the invalid session"),i(De))});ee(it instanceof Error?it.message:"Could not verify API key access"),i(De)}};return e?(me("api-key-error"),()=>{Q=!0}):(Promise.allSettled([$w(),Vw()]).then(([De,je])=>{if(Q||De.status==="fulfilled"&&$e(De.value))return;if(je.status==="rejected"){const Ge=je.reason;ee(Ge instanceof Error?Ge.message:"Failed to reach the Canonry API"),i("login");return}const it=je.value;it.authenticated?(v(!0),me("api-key-error",!0)):(f(null),v(!1),i(it.setupRequired?"setup":"login"))}),()=>{Q=!0})},[]),C.useEffect(()=>{if(n!=="ready"||e)return;const Q=setInterval(()=>{if(w){$w().then(me=>{me.authRequired&&!me.user&&(Xe(!0),u(null),f(null),i("account-login"))}).catch(()=>{});return}Vw().then(me=>{me.authenticated||(Xe(!0),f(null),i(me.setupRequired?"setup":"login"))}).catch(()=>{})},iW);return Lw(()=>{Xe(!0),u(null),f(null),v(!1),i(w?"account-login":"login")}),()=>{clearInterval(Q),Lw(null)}},[n,w,e]);const O=async Q=>{if(Q.preventDefault(),!N.trim()||N.trim().length<8){ee("Password must be at least 8 characters");return}if(N!==E){ee("Passwords do not match");return}K(!0),ee(null);try{if(!(await GG(N.trim())).authenticated){ee("Setup failed");return}P(""),q(""),X(!1),Xe(!1),f(null),v(!0),i("checking");try{const De=await xf();f(De),v(!1),i("ready")}catch(De){ee(De instanceof Error?De.message:"Could not verify API key access"),i("api-key-error")}}catch(me){ee(me instanceof xn||me instanceof Error?me.message:"Setup failed")}finally{K(!1)}},ne=Q=>{P(Q),ee(null)},ge=Q=>{q(Q),ee(null)},Se=async Q=>{if(Q.preventDefault(),!!N.trim()){K(!0),ee(null);try{if(!(L==="api-key"?await HG(N.trim()):await KG(N.trim())).authenticated){ee(L==="api-key"?"Invalid API key":"Incorrect password");return}const De=await xf();f(De),v(!1),P(""),X(!1),Xe(!1),i("ready")}catch(me){ee(me instanceof xn||me instanceof Error?me.message:"Authentication failed")}finally{K(!1)}}},ae=Q=>{Z(Q),P(""),X(!1),ee(null)},_e=async Q=>{if(Q.preventDefault(),!(!j.trim()||!N)){K(!0),ee(null);try{const me=await FG(j.trim(),N);if(!me.user){ee("Incorrect name or password.");return}P(""),Xe(!1),u(me.user),f(null),v(!1),i("ready")}catch(me){ee(me instanceof xn?me.message:"Incorrect name or password.")}finally{K(!1)}}};if(n==="ready"){const{queryClient:Q,router:me}=ke();return l.jsx(fK,{account:r,apiKey:h,apiKeyPending:b,children:l.jsx(WN,{client:Q,children:l.jsx(e5,{router:me})})})}const Be=N.trim(),ve=N.length>0&&Be.length<8,le=E.length>0&&N!==E,ce=Be.length>=8&&N===E;return l.jsx("div",{className:"min-h-screen bg-bg px-4 py-8",children:l.jsxs("div",{className:"mx-auto flex min-h-[calc(100vh-4rem)] max-w-md flex-col items-center justify-center gap-5",children:[l.jsxs("div",{"data-testid":"auth-brand",className:"flex items-center gap-2.5",children:[l.jsx("img",{className:"size-7",src:"./favicon.svg",alt:"","aria-hidden":"true"}),l.jsx("span",{className:"text-lg font-semibold tracking-tight text-heading",children:"Canonry"})]}),l.jsx(_a,{className:"surface-card w-full",children:n==="checking"?l.jsx(go,{className:"py-8",children:l.jsx("p",{className:"supporting-copy text-center",children:"Connecting to Canonry…"})}):n==="api-key-error"?l.jsxs(l.Fragment,{children:[l.jsxs(Nr,{children:[l.jsx("p",{className:"eyebrow eyebrow-soft",children:"Dashboard access"}),l.jsx("h1",{className:"font-medium tracking-tight text-primary",children:"Could not verify API key access"})]}),l.jsxs(go,{className:"space-y-4",children:[l.jsx("p",{className:"supporting-copy",children:Y??"Canonry could not verify this session’s access, so the dashboard stayed locked."}),l.jsx(ue,{type:"button",className:"w-full",onClick:()=>{window.location.reload()},children:"Try again"})]})]}):n==="account-login"?l.jsxs(l.Fragment,{children:[l.jsxs(Nr,{children:[l.jsx("p",{className:"eyebrow eyebrow-soft",children:"Dashboard access"}),l.jsx("h1",{className:"font-medium tracking-tight text-primary",children:"Sign in to Canonry"})]}),l.jsxs(go,{children:[we?l.jsx("p",{className:"mb-4 rounded-md border border-caution bg-caution-soft px-3 py-2 text-sm text-caution",children:"You were signed out — please sign in again."}):null,l.jsxs("form",{className:"space-y-4",onSubmit:pn(_e),children:[l.jsxs("label",{className:"block space-y-1.5",htmlFor:"account-name",children:[l.jsx("span",{className:"text-xs font-medium text-secondary",children:"Name"}),l.jsx("input",{autoFocus:!0,id:"account-name",className:"w-full rounded-md border border-base bg-bg px-3 py-2 text-sm text-heading outline-none transition focus:border-mono-600",type:"text",name:"username",autoComplete:"username",value:j,onChange:Q=>{T(Q.target.value),ee(null)},"aria-invalid":!!Y,"aria-describedby":Y?"account-login-error":void 0})]}),l.jsxs("label",{className:"block space-y-1.5",htmlFor:"account-password",children:[l.jsx("span",{className:"text-xs font-medium text-secondary",children:"Password"}),l.jsx("input",{id:"account-password",className:"w-full rounded-md border border-base bg-bg px-3 py-2 text-sm text-heading outline-none transition focus:border-mono-600",type:"password",name:"password",autoComplete:"current-password",value:N,onChange:Q=>ne(Q.target.value),"aria-invalid":!!Y,"aria-describedby":Y?"account-login-error":void 0})]}),Y?l.jsx("p",{id:"account-login-error",role:"alert",className:"text-sm text-negative-400",children:Y}):null,l.jsx(ue,{type:"submit",disabled:B||!j.trim()||!N,children:B?"Signing in…":"Sign in"})]})]})]}):n==="setup"?l.jsxs(l.Fragment,{children:[l.jsxs(Nr,{children:[l.jsx("p",{className:"eyebrow eyebrow-soft",children:"First-time setup"}),l.jsx("h1",{className:"font-medium tracking-tight text-primary",children:"Create a dashboard password"}),l.jsx(Fd,{children:"This password protects the dashboard on this computer."})]}),l.jsx(go,{children:l.jsxs("form",{className:"space-y-4",onSubmit:pn(O),children:[l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("label",{className:"block text-xs font-medium text-secondary",htmlFor:"dashboard-password-new",children:"Password"}),l.jsx("input",{autoFocus:!0,id:"dashboard-password-new",className:"w-full rounded-md border border-base bg-bg px-3 py-2 text-sm text-heading outline-none transition focus:border-mono-600",type:H?"text":"password",name:"new-password",autoComplete:"new-password",minLength:8,required:!0,value:N,onChange:Q=>ne(Q.target.value),"aria-invalid":ve,"aria-describedby":"dashboard-password-new-help"}),l.jsx("span",{id:"dashboard-password-new-help","aria-live":"polite",className:ve?"block text-sm text-negative-400":"block text-sm text-secondary",children:ve?"Enter at least 8 characters.":"Use at least 8 characters."})]}),l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("label",{className:"block text-xs font-medium text-secondary",htmlFor:"dashboard-password-confirm",children:"Confirm password"}),l.jsx("input",{id:"dashboard-password-confirm",className:"w-full rounded-md border border-base bg-bg px-3 py-2 text-sm text-heading outline-none transition focus:border-mono-600",type:H?"text":"password",name:"confirm-password",autoComplete:"new-password",minLength:8,required:!0,value:E,onChange:Q=>ge(Q.target.value),"aria-invalid":le,"aria-describedby":"dashboard-password-confirm-help"}),l.jsx("span",{id:"dashboard-password-confirm-help","aria-live":"polite",className:le?"block text-sm text-negative-400":"block text-sm text-secondary",children:le?"Passwords do not match.":"Enter the same password again."})]}),l.jsxs("label",{className:"flex min-h-10 cursor-pointer items-center gap-2 text-sm text-secondary",htmlFor:"dashboard-password-show",children:[l.jsx("input",{id:"dashboard-password-show",type:"checkbox",checked:H,onChange:Q=>X(Q.target.checked)}),"Show passwords"]}),Y?l.jsx("p",{id:"dashboard-password-setup-error",role:"alert",className:"text-sm text-negative-400",children:Y}):null,l.jsx(ue,{type:"submit",disabled:B||!ce,children:B?"Creating password…":"Create password and continue"})]})})]}):l.jsxs(l.Fragment,{children:[l.jsxs(Nr,{children:[l.jsx("p",{className:"eyebrow eyebrow-soft",children:"Dashboard access"}),l.jsx("h1",{className:"font-medium tracking-tight text-primary",children:"Sign in to Canonry"}),l.jsx(Fd,{children:L==="api-key"?"Enter an API key from this Canonry install. This opens the dashboard with that key’s access and does not change the password.":"Enter your dashboard password to continue."})]}),l.jsxs(go,{children:[we?l.jsx("p",{className:"mb-4 rounded-md border border-caution bg-caution-soft px-3 py-2 text-sm text-caution",children:"Your session expired — please sign in again."}):null,l.jsxs("form",{className:"space-y-4",onSubmit:pn(Se),children:[l.jsxs("label",{className:"block space-y-1.5",htmlFor:"dashboard-password-current",children:[l.jsx("span",{className:"text-xs font-medium text-secondary",children:L==="api-key"?"Canonry API key":"Password"}),l.jsx("input",{autoFocus:!0,id:"dashboard-password-current",className:"w-full rounded-md border border-base bg-bg px-3 py-2 text-sm text-heading outline-none transition focus:border-mono-600",type:H?"text":"password",name:L==="api-key"?"apiKey":"password",autoComplete:L==="api-key"?"off":"current-password",spellCheck:!1,required:!0,value:N,onChange:Q=>ne(Q.target.value),"aria-invalid":!!Y,"aria-describedby":Y?"dashboard-password-login-error":void 0})]}),l.jsxs("label",{className:"flex min-h-10 cursor-pointer items-center gap-2 text-sm text-secondary",htmlFor:"dashboard-login-password-show",children:[l.jsx("input",{id:"dashboard-login-password-show",type:"checkbox",checked:H,onChange:Q=>X(Q.target.checked)}),L==="api-key"?"Show API key":"Show password"]}),Y?l.jsx("p",{id:"dashboard-password-login-error",role:"alert",className:"text-sm text-negative-400",children:Y}):null,l.jsx(ue,{type:"submit",disabled:B||!N.trim(),children:B?"Signing in…":"Open dashboard"}),l.jsx(ue,{type:"button",variant:"ghost",onClick:()=>ae(L==="api-key"?"password":"api-key"),children:L==="api-key"?"Use dashboard password instead":"Forgot password? Use API key"})]})]})]})})]})})}const $C=document.getElementById("root");if(!$C)throw new Error("Expected #root element for web app bootstrap.");T5.createRoot($C).render(l.jsx(C.StrictMode,{children:l.jsx(sW,{})}));export{Fae as $,xne as A,ue as B,Pd as C,vne as D,pa as E,EK as F,tse as G,nse as H,Ua as I,BF as J,IK as K,VW as L,Mie as M,$ne as N,Kne as O,Ute as P,Lne as Q,bt as R,Xie as S,bn as T,$ae as U,Kae as V,Gae as W,Jte as X,Xte as Y,lne as Z,wn as _,qie as a,cae as a$,Zae as a0,ane as a1,Yae as a2,ine as a3,ene as a4,nne as a5,Hae as a6,Qae as a7,Uae as a8,Wte as a9,ag as aA,Mne as aB,jd as aC,yie as aD,zi as aE,hg as aF,fo as aG,IF as aH,kK as aI,aae as aJ,LZ as aK,tne as aL,QW as aM,wj as aN,VP as aO,Zie as aP,Yie as aQ,LW as aR,Rte as aS,GI as aT,En as aU,mg as aV,BW as aW,dee as aX,MW as aY,GK as aZ,mH as a_,Xae as aa,iie as ab,eie as ac,nie as ad,tie as ae,aie as af,Cne as ag,r1 as ah,ze as ai,Wae as aj,nC as ak,Bi as al,Jae as am,bg as an,x9 as ao,w9 as ap,qW as aq,PW as ar,Tne as as,One as at,Pne as au,xn as av,qne as aw,Ite as ax,RK as ay,MQ as az,aee as b,bW as b$,hae as b0,uae as b1,Cee as b2,_ee as b3,K$ as b4,Tee as b5,tH as b6,lae as b7,Q$ as b8,eg as b9,kae as bA,Eae as bB,jae as bC,Iae as bD,Aae as bE,Oae as bF,_ae as bG,qae as bH,Lae as bI,xX as bJ,Cae as bK,pe as bL,DW as bM,RW as bN,EW as bO,TW as bP,CW as bQ,AW as bR,_W as bS,NW as bT,jW as bU,SW as bV,gW as bW,yW as bX,kW as bY,wW as bZ,xW as b_,Nee as ba,CG as bb,dae as bc,rae as bd,aH as be,mae as bf,Gie as bg,pae as bh,kie as bi,Sie as bj,sne as bk,s1 as bl,gie as bm,XA as bn,vae as bo,wae as bp,Tae as bq,Bae as br,Mae as bs,Nae as bt,Pae as bu,Vae as bv,Sae as bw,Rae as bx,Dae as by,zae as bz,gB as c,UW as c$,vW as c0,fW as c1,hW as c2,pW as c3,mW as c4,e6 as c5,uee as c6,pee as c7,ree as c8,hee as c9,Tte as cA,kee as cB,xee as cC,Oee as cD,tG as cE,Cte as cF,Nte as cG,Ate as cH,jte as cI,mte as cJ,dte as cK,cte as cL,ute as cM,wee as cN,rte as cO,ote as cP,Zee as cQ,Yee as cR,bee as cS,See as cT,Xee as cU,hte as cV,$W as cW,kte as cX,Ste as cY,bte as cZ,xte as c_,mee as ca,lee as cb,cee as cc,yee as cd,ise as ce,fie as cf,ng as cg,fee as ch,Ree as ci,Dee as cj,xo as ck,Eee as cl,gee as cm,gne as cn,Dt as co,m$ as cp,ate as cq,Ete as cr,Jee as cs,Wee as ct,ete as cu,tte as cv,nte as cw,oV as cx,see as cy,Ow as cz,Qie as d,Hd as d$,wte as d0,vte as d1,iee as d2,ite as d3,Uee as d4,Gee as d5,Kee as d6,Hee as d7,Qee as d8,Fee as d9,$ee as dA,Vte as dB,Lte as dC,Bte as dD,yne as dE,fH as dF,xae as dG,Fne as dH,HW as dI,Fw as dJ,Kte as dK,Hte as dL,Hne as dM,Qne as dN,Qte as dO,Fte as dP,Yte as dQ,Zte as dR,Uc as dS,Do as dT,qA as dU,Xne as dV,Yne as dW,jZ as dX,ug as dY,Kd as dZ,dg as d_,oG as da,_te as db,oee as dc,zW as dd,rV as de,qee as df,pte as dg,OW as dh,vee as di,zee as dj,Pee as dk,Iee as dl,GW as dm,fte as dn,gte as dp,yte as dq,Bee as dr,TA as ds,Mee as dt,Lee as du,KW as dv,Vee as dw,ste as dx,IW as dy,lte as dz,Jie as e,Gte as e$,Qd as e0,BZ as e1,FK as e2,yo as e3,Xd as e4,vH as e5,EX as e6,ase as e7,$ie as e8,qZ as e9,As as eA,UK as eB,QK as eC,$te as eD,sie as eE,JG as eF,pne as eG,rie as eH,lie as eI,cie as eJ,oie as eK,Une as eL,cne as eM,une as eN,dne as eO,hne as eP,mne as eQ,Lr as eR,_m as eS,ese as eT,Dm as eU,u1 as eV,yae as eW,bae as eX,EG as eY,Dte as eZ,zte as e_,Vie as ea,jX as eb,fae as ec,Jne as ed,Lie as ee,nae as ef,Wne as eg,gae as eh,Bie as ei,eae as ej,nn as ek,Iie as el,HZ as em,qG as en,qK as eo,QZ as ep,Uie as eq,Kie as er,Hie as es,Fie as et,ks as eu,Ote as ev,LG as ew,Pte as ex,qte as ey,Mte as ez,Xt as f,Rie as f$,one as f0,rne as f1,h1 as f2,zm as f3,d1 as f4,TX as f5,fne as f6,Vr as f7,Yw as f8,Nne as f9,sae as fA,YW as fB,Li as fC,Ia as fD,ZW as fE,AG as fF,mQ as fG,Aie as fH,jie as fI,AX as fJ,_ie as fK,UZ as fL,nee as fM,XW as fN,Oie as fO,Pie as fP,Cie as fQ,Nie as fR,FW as fS,Eie as fT,zie as fU,Tie as fV,Die as fW,jo as fX,n3 as fY,JW as fZ,tee as f_,Ene as fa,Dne as fb,zne as fc,_ne as fd,Rne as fe,Ine as ff,vf as fg,Ane as fh,xie as fi,rX as fj,Aee as fk,G0 as fl,Zne as fm,bie as fn,wie as fo,jne as fp,jee as fq,kne as fr,Sne as fs,wne as ft,vie as fu,Vne as fv,nI as fw,iae as fx,tae as fy,oae as fz,Wie as g,KM as g0,eee as g1,WW as g2,rk as h,r2 as i,Bne as j,uie as k,mie as l,_a as m,Ln as n,J as o,MA as p,Er as q,On as r,Gne as s,zK as t,m1 as u,pn as v,die as w,hie as x,pie as y,bne as z};
86
+ competitor2.com`,value:mi,onChange:U=>Ki(U.target.value)})]}),Wt?l.jsx("p",{className:"text-negative-400 text-sm",children:Wt}):null,l.jsxs("div",{className:"setup-nav",children:[l.jsx(ue,{type:"button",variant:"outline",onClick:qn,children:"Back"}),l.jsxs("div",{className:"flex gap-2",children:[l.jsx(ue,{type:"button",variant:"outline",onClick:Fc,children:"Skip"}),l.jsx(ue,{type:"button",disabled:hi.length===0||ll,onClick:pn(pl),children:ll?"Saving...":`Save ${hi.length} competitor${hi.length!==1?"s":""}`})]})]})]})]});case 4:{const U=Ja.data,Fe=U?.status??(Fi===nt?.id?nt.status:void 0),gi=Fe==="completed"||Fe==="partial"||Fe==="failed"||Fe==="cancelled",qa=U?.snapshots??[],Ko=qa.filter(Ma=>Ma.citationState==="cited").length,Zc=qa.filter(Ma=>Ma.answerMentioned===!0).length,An=new Set(qa.map(Ma=>Ma.query).filter(Ma=>!!Ma)).size,ti=Fe?Tk(Fe,qa.length):!1,Hs=Ue&&!Xa,Qs=jn??(U?.error?RK(U.error):Fe==="cancelled"?"The sweep was cancelled before it produced a baseline.":(Fe==="completed"||Fe==="partial")&&qa.length===0?"The sweep finished without producing any snapshots.":nt?.statusDetail||"The sweep did not produce a baseline.");let Fs=null;return Hs||ti?Fs=l.jsx(bn,{tone:"positive",children:"Complete"}):jn&&!Xa?Fs=l.jsx(bn,{tone:"negative",children:"Failed"}):gi?Fs=l.jsx(bn,{tone:"negative",children:Fe==="cancelled"?"Cancelled":"Failed"}):Xa&&(Fs=l.jsx(bn,{tone:"caution",children:"Running"})),l.jsxs(_a,{className:"surface-card step-card",children:[l.jsxs("div",{className:"section-head",children:[l.jsxs("div",{children:[l.jsx("p",{className:"eyebrow eyebrow-soft",children:N?"Step 2 of 2":"Step 5 of 5"}),l.jsx("h2",{children:fo()?"AI Visibility":"Launch first run"})]}),Fs]}),Hs?l.jsxs("div",{className:"compact-stack",children:[l.jsxs("p",{className:"text-secondary",children:["Setup is complete. ",l.jsx("span",{className:"text-strong font-medium",children:He})," already has a successful answer-visibility baseline."]}),l.jsxs("div",{className:"setup-nav",children:[l.jsx("span",{}),l.jsx(ue,{type:"button",onClick:()=>ct(),children:f?"Finish setup":"Open project dashboard →"})]})]}):!Xa&&fo()?l.jsxs("div",{className:"compact-stack",children:[He?l.jsx(QZ,{projectName:He}):l.jsx("p",{className:"text-sm text-secondary",children:hg}),jn&&l.jsx("p",{role:"alert",className:"text-sm text-negative",children:jn}),l.jsxs("div",{className:"setup-nav",children:[l.jsx("span",{}),l.jsx(ue,{type:"button",onClick:Le,children:"Open project dashboard →"})]})]}):Xa?gi?ti?l.jsxs("div",{className:"compact-stack",children:[l.jsxs("p",{className:"text-neutral",children:["Sweep complete. Your first answer-visibility snapshot for"," ",l.jsx("span",{className:"text-heading font-medium",children:He}),":"]}),l.jsxs("div",{className:"grid grid-cols-3 gap-2 mt-1",children:[l.jsxs("div",{className:"rounded-md border border-default bg-surface p-3",children:[l.jsx("p",{className:"text-xs font-medium text-secondary",children:"Mentioned"}),l.jsxs("p",{className:"text-2xl font-bold tabular-nums text-primary mt-1",children:[Zc,l.jsxs("span",{className:"text-faint text-lg",children:[" / ",An]})]}),l.jsx("p",{className:"mt-0.5 text-sm text-secondary",children:"queries naming your brand"})]}),l.jsxs("div",{className:"rounded-md border border-default bg-surface p-3",children:[l.jsx("p",{className:"text-xs font-medium text-secondary",children:"Cited"}),l.jsxs("p",{className:"text-2xl font-bold tabular-nums text-primary mt-1",children:[Ko,l.jsxs("span",{className:"text-faint text-lg",children:[" / ",An]})]}),l.jsx("p",{className:"mt-0.5 text-sm text-secondary",children:"queries citing your site"})]}),l.jsxs("div",{className:"rounded-md border border-default bg-surface p-3",children:[l.jsx("p",{className:"text-xs font-medium text-secondary",children:"Results"}),l.jsx("p",{className:"text-2xl font-bold tabular-nums text-primary mt-1",children:qa.length}),l.jsx("p",{className:"mt-0.5 text-sm text-secondary",children:"completed engine checks"})]})]}),!b&&He?l.jsx(_X,{projectName:He}):null,l.jsxs("div",{className:"setup-nav",children:[l.jsx("span",{}),l.jsx(ue,{type:"button",onClick:()=>ct(),children:f?"Finish setup":"Open project dashboard →"})]})]}):l.jsxs("div",{className:"compact-stack",children:[l.jsxs("div",{role:"alert",className:"rounded-md border border-negative bg-negative-soft p-3 text-sm text-negative",children:[l.jsx("p",{children:Qs}),l.jsx("p",{className:"mt-1 text-xs text-secondary",children:fo()?hg:w?"Fix provider or query configuration if needed, then retry without leaving setup.":"Ask an administrator to review the provider and query configuration."})]}),l.jsxs("div",{className:"setup-nav",children:[w&&!fo()?l.jsx(ue,{type:"button",variant:"outline",asChild:!0,children:l.jsx(We,{to:"/settings",children:"Configure providers"})}):l.jsx("span",{}),fo()||!w?l.jsx(ue,{type:"button",onClick:Le,children:"Open project dashboard →"}):l.jsx(ue,{type:"button",disabled:pi||!!Wa,onClick:pn(fi),children:pi?"Retrying...":"Retry visibility sweep"})]})]}):l.jsxs("div",{className:"compact-stack",children:[l.jsx("p",{className:"text-neutral",children:"Sweep running. This usually takes 30 to 60 seconds."}),l.jsx("div",{className:"rounded-md border border-default bg-surface p-3 text-xs text-muted",children:l.jsxs("p",{children:["Status: ",l.jsx("span",{className:"text-neutral",children:Fe??"queued"})]})}),Ja.isError&&l.jsxs("div",{role:"alert",className:"rounded-md border border-negative bg-negative-soft p-3 text-sm text-negative",children:[l.jsx("p",{children:Ja.error instanceof Error?Ja.error.message:"Could not refresh the sweep status."}),l.jsx(ue,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>{Ja.refetch()},children:"Retry status check"})]}),l.jsxs("div",{className:"setup-nav",children:[l.jsx("span",{}),l.jsx(ue,{type:"button",variant:"outline",onClick:f?()=>ct():Le,children:f?"Finish setup":"Watch on project page"})]})]}):l.jsxs("div",{className:"compact-stack",children:[l.jsxs("p",{className:"supporting-copy",children:["Your queries are saved. Run a first sweep to get a baseline for"," ",l.jsx("span",{className:"text-heading font-medium",children:He}),", or finish and run it later from the project. A sweep calls the answer engines, so it costs provider usage."]}),(Wa||jn)&&l.jsxs("div",{role:"alert",className:"rounded-md border border-negative bg-negative-soft p-3 text-sm text-negative",children:[l.jsx("p",{children:jn??Wa}),l.jsx("p",{className:"mt-1 text-xs text-secondary",children:"Resolve the blocker above, then retry the sweep here."})]}),l.jsxs("div",{className:"setup-nav",children:[l.jsx(ue,{type:"button",variant:"outline",onClick:qn,children:"Back"}),l.jsx(ue,{type:"button",variant:"ghost",onClick:Kt,children:"Finish without running"}),ba==="no_provider"&&!N?l.jsx(ue,{type:"button",asChild:!0,children:l.jsx(We,{to:"/settings",children:"Configure a provider"})}):l.jsx(ue,{type:"button",disabled:pi||!!Wa,title:Wa,onClick:pn(fi),children:pi?"Launching...":jn?"Retry visibility sweep":"Launch visibility sweep"})]})]})]})}default:return null}})();return l.jsxs("div",{className:N?"page-container visibility-setup":"page-container",children:[f?l.jsx(jo,{current:"visibility"}):null,l.jsxs("div",{className:"page-header",children:[l.jsxs("div",{className:"page-header-left",children:[l.jsx("h1",{ref:u?h:void 0,tabIndex:u?-1:void 0,className:"page-title",children:u?"Set up AI Visibility":"Setup"}),l.jsx("p",{className:"page-subtitle",children:u?"Connect an answer engine, then choose queries for your first sweep.":"Create a project and run its first visibility check."})]}),f?l.jsx("div",{className:"page-header-right",children:l.jsx(ue,{type:"button",variant:"outline",className:"min-h-11",onClick:Kt,children:"Skip AI Visibility"})}):null]}),f?null:l.jsx(IX,{current:N?O===4?1:0:O,labels:N?DX:RX}),l.jsxs("section",{className:"setup-wizard",children:[Ks,ei]})]})}const _f="canonry mcp install --client claude-code",qX="https://github.com/Canonry/canonry/blob/main/docs/mcp.md";function MX(){const e=C.useRef(g1()).current,n=C.useRef(new Set),i=C.useCallback((r,u)=>{n.current.has(r)||(n.current.add(r),n1({...u,flowVersion:ft,onboardingSessionId:e,surface:"platform",eventId:y1()}))},[e]);return C.useEffect(()=>{i("started",{event:"onboarding.started",step:"finish",resumed:!1})},[i]),C.useCallback(r=>{i(`action:${r}`,{event:"onboarding.step_completed",step:"finish",method:"manual",nextAction:r})},[i])}const Bm=C.createContext(()=>{});function BX({projectName:e,skippedVisibility:n=!1}){const i=yt({...mQ({client:J,path:{name:e}}),retry:!1}),r=i.data?.hasData?i.data:null,u=MX(),h=Dk(e,ze["site-audit"]),f=Dk(e,ze["answer-visibility"]),b={...h?{site:h,fixes:h}:{},...LX(f,n)};return l.jsx(Bm.Provider,{value:u,children:l.jsxs("div",{className:"page-container max-w-6xl py-8 md:py-10",children:[l.jsx(jo,{current:"done",outcomes:b}),l.jsxs("header",{className:"relative mx-auto mt-12 max-w-2xl text-center md:mt-16",children:[l.jsx(VX,{}),l.jsx("p",{className:"onb-reveal mt-6 text-sm font-medium text-positive",style:Ta(250),children:"Setup complete"}),l.jsx("h1",{className:"onb-reveal mt-2 text-5xl font-semibold tracking-tight text-heading md:text-6xl",style:Ta(350),children:"You’re set."}),l.jsxs("p",{className:"onb-reveal mx-auto mt-4 max-w-xl text-lg text-secondary",style:Ta(450),children:["Canonry is tracking ",l.jsx("span",{className:"font-medium text-heading",children:e}),". Here’s how to get the most out of it from here."]})]}),l.jsxs("div",{className:"mt-14 grid gap-4 md:grid-cols-6",children:[l.jsx(gd,{className:"md:col-span-4 md:row-span-2",delayMs:600,labelledBy:"onb-agent-heading",children:l.jsx(GX,{projectName:e})}),l.jsx(gd,{className:"md:col-span-2 md:row-span-2",delayMs:700,labelledBy:"onb-data-heading",children:l.jsx(QX,{projectName:e})}),l.jsx(gd,{className:"md:col-span-3",delayMs:800,labelledBy:"onb-schedule-heading",children:l.jsx(YX,{projectName:e})}),l.jsx(gd,{className:"md:col-span-3",delayMs:900,labelledBy:"onb-alerts-heading",children:l.jsx(XX,{projectName:e,score:r?.aggregateScore??null})})]}),l.jsxs("div",{className:"onb-reveal mt-12 flex flex-col items-center gap-3 sm:flex-row sm:justify-center",style:Ta(1e3),children:[l.jsx(ue,{asChild:!0,className:"h-11 rounded-full px-6 text-base md:h-11",children:l.jsxs(We,{to:"/projects/$projectName",params:{projectName:e},replace:!0,onClick:()=>u("open_project"),children:["Open ",e,l.jsx(yc,{className:"size-4","aria-hidden":"true"})]})}),l.jsx(ue,{asChild:!0,variant:"ghost",className:"h-11 rounded-full px-5 md:h-11",children:l.jsx(We,{to:"/projects/$projectName/technical-aeo",params:{projectName:e},replace:!0,onClick:()=>u("review_page_health"),children:"Review page health"})})]})]})})}function Dk(e,n){const i=yt({...XA({client:J,path:{name:e},query:{kind:n,limit:20}}),retry:!1,refetchInterval:r=>zk(r.state.status==="success"?{isSuccess:!0,data:r.state.data}:{isSuccess:!1})==="pending"?5e3:!1});return zk(i)}function LX(e,n){return e===void 0?{}:n?{visibility:"skipped"}:{visibility:e}}function zk(e){if(!e.isSuccess||!e.data)return"unknown";const n=e.data.filter(i=>i.trigger!==ks.probe);if(!n.some(i=>i.status===nn.completed||i.status===nn.partial))return n.some(i=>i.status===nn.queued||i.status===nn.running)?"pending":n.length>0?"incomplete":"skipped"}function Ta(e){return{"--onb-delay":`${e}ms`}}function VX(){return l.jsx("div",{className:"onb-check relative mx-auto size-20","aria-hidden":"true",children:l.jsxs("svg",{viewBox:"0 0 80 80",className:"relative size-20",children:[l.jsx("circle",{className:"onb-check-ring",cx:"40",cy:"40",r:"36",fill:"none",strokeWidth:"3",pathLength:"1"}),l.jsx("path",{className:"onb-check-mark",d:"M25 41 L35 51 L56 30",fill:"none",strokeWidth:"4",strokeLinecap:"round",strokeLinejoin:"round",pathLength:"1"})]})})}function gd({className:e="",delayMs:n,labelledBy:i,children:r}){return l.jsx("section",{"aria-labelledby":i,className:`onb-reveal onb-tile flex flex-col overflow-hidden rounded-2xl border border-default bg-surface p-6 md:p-7 ${e}`,style:Ta(n),children:r})}function Lm({id:e,eyebrow:n,title:i,children:r}){return l.jsxs("div",{children:[l.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted",children:n}),l.jsx("h2",{id:e,className:"mt-1.5 text-2xl font-semibold tracking-tight text-heading",children:i}),l.jsx("p",{className:"mt-2 text-sm text-secondary",children:r})]})}const yd=[{id:"diagnose",label:"Diagnose",prompt:"Why did we lose citations this week?",calls:["canonry_insights_list","canonry_competitor_landscape"],reply:"Two engines started citing a competitor’s comparison page instead of yours. Want me to draft one that answers the same query?"},{id:"fix",label:"Fix",prompt:"Fix the weakest pages on the site.",calls:["canonry_technical_aeo_pages","canonry_site_health_page_audit"],reply:"The lowest-scoring pages are missing structured data and answer-first intros. I’ve written the changes for you to review."},{id:"automate",label:"Automate",prompt:"Re-check everything every Monday and tell me in Slack.",calls:["canonry_schedule_set","canonry_agent_webhook_attach"],reply:"Done. A sweep runs every Monday, and I’ll post what changed to Slack."}],$X=9e3;function UX(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function GX({projectName:e}){const n=C.useContext(Bm),[i,r]=C.useState(0),[u,h]=C.useState(!1),[f,b]=C.useState(!1);C.useEffect(()=>{if(u||UX())return;const k=window.setTimeout(()=>r(j=>(j+1)%yd.length),$X);return()=>window.clearTimeout(k)},[i,u]);const v=async()=>{try{await navigator.clipboard.writeText(_f),n("copy_agent_command"),b(!0),window.setTimeout(()=>b(!1),1800)}catch{wn({tone:"negative",title:"Could not copy the command",detail:`Run ${_f} in your terminal.`})}},w=yd[i]??yd[0];return l.jsxs(l.Fragment,{children:[l.jsxs(Lm,{id:"onb-agent-heading",eyebrow:"Your agent",title:"Let your agent run it.",children:["Your agent can do everything in Canonry: diagnose a drop, fix pages, run sweeps and scans, and write the client report. Use Claude Code, Codex, Cursor, or Aero, the analyst built into"," ",l.jsx("span",{className:"text-heading",children:e})," that reviews every sweep on its own."]}),l.jsxs("div",{className:"mt-6 flex flex-1 flex-col rounded-xl border border-default bg-bg",onMouseEnter:()=>h(!0),onMouseLeave:()=>h(!1),onFocus:()=>h(!0),children:[l.jsxs("div",{className:"flex items-center gap-1 border-b border-default px-3 py-2",role:"tablist","aria-label":"Example agent sessions",children:[yd.map((k,j)=>l.jsx("button",{type:"button",role:"tab","aria-selected":j===i,onClick:()=>{r(j),h(!0)},className:`rounded-md px-2.5 py-1 text-xs font-medium transition-colors ${j===i?"bg-surface-inset text-heading":"text-muted hover:text-secondary"}`,children:k.label},k.id)),l.jsx("span",{className:"ml-auto text-xs text-faint",children:"Example"})]}),l.jsxs("div",{role:"tabpanel","aria-label":`${w.label} example`,className:"flex-1 p-4 font-mono text-[13px] leading-relaxed",children:[l.jsxs("p",{className:"onb-type text-heading",style:Ta(150),children:[l.jsx("span",{className:"text-muted",children:"> "}),w.prompt]}),w.calls.map((k,j)=>l.jsxs("p",{className:"onb-line mt-1 text-muted first:mt-3",style:Ta(1300+j*450),children:[l.jsx("span",{className:"text-positive",children:"●"})," ",k]},k)),l.jsx("p",{className:"onb-line mt-3 text-secondary",style:Ta(1500+w.calls.length*450),children:w.reply}),l.jsx("span",{className:"onb-caret mt-2 inline-block h-4 w-2 bg-current align-middle text-secondary",style:Ta(1900+w.calls.length*450),"aria-hidden":"true"})]},w.id)]}),l.jsxs("div",{className:"mt-4 flex flex-wrap items-center gap-2",children:[l.jsx("code",{className:"min-w-0 flex-1 truncate rounded-lg border border-default bg-surface-inset px-3 py-2 font-mono text-[13px] text-heading",children:_f}),l.jsxs(ue,{type:"button",variant:"secondary",size:"sm",className:"h-9 md:h-9",onClick:()=>{v()},children:[f?l.jsx(Wd,{className:"size-4","aria-hidden":"true"}):l.jsx(Cg,{className:"size-4","aria-hidden":"true"}),f?"Copied":"Copy"]}),l.jsx("a",{href:qX,target:"_blank",rel:"noreferrer",className:"text-sm font-medium text-link underline-offset-4 hover:underline",children:"Other clients"})]})]})}const KX=[{icon:Ag,label:"Search Console",action:"connect_search_console",to:"/projects/$projectName/search-console"},{icon:Fk,label:"Google Analytics",action:"connect_analytics",to:"/projects/$projectName/activity"},{icon:Yk,label:"Business Profile",action:"connect_business_profile",to:"/projects/$projectName/local"}],HX=["GPTBot","ClaudeBot","PerplexityBot"];function QX({projectName:e}){const n=C.useContext(Bm);return l.jsxs(l.Fragment,{children:[l.jsx(Lm,{id:"onb-data-heading",eyebrow:"Server-side traffic",title:"See the AI bots.",children:"AI crawlers and answer-engine fetches never run JavaScript, so Google Analytics never sees them. Canonry reads them straight from your server."}),l.jsx(FX,{}),l.jsxs(We,{to:"/traffic",onClick:()=>n("connect_server_traffic"),"aria-label":"Connect server-side traffic",className:"group flex items-center gap-3 rounded-xl border border-strong bg-surface-inset px-4 py-3 text-sm font-medium text-heading transition-colors hover:bg-surface-inset-hover",children:[l.jsx(Xk,{className:"size-4 text-positive","aria-hidden":"true"}),l.jsxs("span",{className:"flex-1",children:["Connect your server",l.jsx("span",{className:"block text-xs font-normal text-secondary",children:"Cloudflare, Vercel, WordPress, or Cloud Run"})]}),l.jsx(yc,{className:"size-4 text-link transition-transform group-hover:translate-x-0.5","aria-hidden":"true"})]}),l.jsx("p",{className:"mt-5 text-xs font-medium uppercase tracking-wide text-muted",children:"Also connect"}),l.jsx("ul",{className:"mt-1 divide-y divide-default",children:KX.map(({icon:i,label:r,action:u,to:h})=>l.jsx("li",{children:l.jsxs(We,{to:h,params:{projectName:e},"aria-label":`Connect ${r}`,onClick:()=>n(u),className:"group flex items-center gap-3 py-2.5 text-sm text-heading",children:[l.jsx(i,{className:"size-4 text-muted","aria-hidden":"true"}),l.jsx("span",{className:"flex-1",children:r}),l.jsx(yc,{className:"size-3.5 text-link transition-transform group-hover:translate-x-0.5","aria-hidden":"true"})]})},r))})]})}function FX(){const e=[22,70,118];return l.jsxs("div",{className:"relative my-6 h-36","aria-hidden":"true",children:[l.jsx("svg",{viewBox:"0 0 200 140",preserveAspectRatio:"none",className:"absolute inset-0 size-full",children:e.map((n,i)=>l.jsx("path",{className:"onb-flow",style:Ta(i*400),d:`M20 ${n} C 100 ${n}, 118 70, 170 70`,fill:"none",strokeWidth:"1.5"},n))}),HX.map((n,i)=>l.jsx("span",{className:"onb-bot absolute left-0 -translate-y-1/2 rounded-md border border-default bg-bg-elevated px-2 py-1 font-mono text-[11px] text-secondary",style:{top:`${(e[i]??70)/140*100}%`,...Ta(i*600)},children:n},n)),l.jsx("span",{className:"onb-hub absolute right-0 top-1/2 flex size-11 -translate-y-1/2 items-center justify-center rounded-2xl bg-accent text-on-inverse",children:l.jsx(Xk,{className:"size-5"})})]})}const ZX=["M","T","W","T","F","S","S"];function YX({projectName:e}){return l.jsxs(l.Fragment,{children:[l.jsx(Lm,{id:"onb-schedule-heading",eyebrow:"Scheduled sweeps",title:"Runs on its own.",children:"Re-measure every week without lifting a finger, so a drop shows up before a customer notices."}),l.jsx("ol",{className:"mt-6 grid grid-cols-7 gap-2","aria-hidden":"true",children:ZX.map((n,i)=>l.jsxs("li",{className:"flex flex-col items-center gap-2",children:[l.jsx("span",{className:"onb-day size-3 rounded-full bg-surface-inset",style:Ta(i*500)}),l.jsx("span",{className:"text-xs text-muted",children:n})]},i))}),l.jsx(MC,{projectName:e,to:"/projects/$projectName/settings",icon:Zk,label:"Set a schedule",action:"set_schedule"})]})}function XX({projectName:e,score:n}){return l.jsxs(l.Fragment,{children:[l.jsx(Lm,{id:"onb-alerts-heading",eyebrow:"Notifications",title:"Hear about changes.",children:"Get a webhook in Slack or anywhere else when a sweep finishes or a score moves."}),l.jsxs("div",{className:"relative mt-6 flex h-14 items-center","aria-hidden":"true",children:[l.jsx("span",{className:"onb-bell flex size-10 items-center justify-center rounded-full border border-default bg-bg-elevated",children:l.jsx(Rf,{className:"size-4 text-secondary"})}),l.jsxs("span",{className:"onb-toast ml-3 flex items-center gap-2 rounded-xl border border-default bg-bg-elevated px-3 py-2 text-sm shadow-[0_8px_24px_var(--color-shadow-panel)]",children:[l.jsx("span",{className:"size-2 rounded-full bg-positive-400"}),l.jsx("span",{className:"text-heading",children:e}),l.jsx("span",{className:"text-secondary",children:n===null?"sweep finished":`page health ${n}`})]})]}),l.jsx(MC,{projectName:e,to:"/projects/$projectName/settings",icon:Rf,label:"Add a notification",action:"add_notification"})]})}function MC({projectName:e,to:n,icon:i,label:r,action:u}){const h=C.useContext(Bm);return l.jsxs(We,{to:n,params:{projectName:e},onClick:()=>h(u),className:"group mt-6 inline-flex items-center gap-2 self-start text-sm font-medium text-link",children:[l.jsx(i,{className:"size-4","aria-hidden":"true"}),r,l.jsx(yc,{className:"size-3.5 transition-transform group-hover:translate-x-0.5","aria-hidden":"true"})]})}const JX=C.lazy(async()=>({default:(await Li(()=>import("./SiteHealthSection-C372wrfT.js").then(n=>n.d),__vite__mapDeps([0,1,2,3,4]),import.meta.url)).SiteHealthSection})),WX=`Public pages only, crawled from this computer and stored locally. The first scan reads up to ${n3} pages, then stops.`,eJ=1800,tJ="https://github.com/Canonry/canonry#or-use-any-shell-capable-coding-agent",nJ="Help me set up Canonry for my public site.\n\nUse the official Canonry docs:\n- Agent quickstart: https://github.com/Canonry/canonry#or-use-any-shell-capable-coding-agent\n- CLI reference: https://github.com/Canonry/canonry/blob/main/skills/canonry/references/canonry-cli.md\n- Plugin setup: https://github.com/Canonry/canonry/blob/main/docs/plugins.md\n- MCP setup: https://github.com/Canonry/canonry/blob/main/docs/mcp.md\n\nPick one path and stay on it. Use connected Canonry tools (plugin or MCP) only if you have them and I have not pointed you at a specific install. A connected tool runs in its own process and never sees `CANONRY_CONFIG_DIR`, `CANONRY_PORT`, or anything else you export in a shell, so it always acts on my default install. If I named a config directory, a port, or a sandbox, that is the shell path: use `cnry` and tell me which path you chose. Never mix the two in one run, and never create a duplicate project. The `cnry` and `canonry` commands are interchangeable.\n\n1. Ask for my public domain, country, and language. Do not create or scan anything yet. Country and language are only applied when a project is created, so if you reuse an existing project, report its country and language instead of changing them.\n2. Shell path only: confirm `cnry` is on PATH, then run `cnry --version`. If Canonry is missing, propose `npm install -g @canonry/canonry` and wait for approval. Then run `cnry doctor --format json`, which is the command that says whether config, database, and server are in place. `cnry --version` does not read config and succeeds on a completely unconfigured install, so it cannot answer this. If config is missing, run `cnry bootstrap` yourself: it is not interactive, takes about a second, and is safe to rerun. Do not hand it to me and wait. The interactive command is `cnry init`, which is optional provider and OAuth setup that Page Health does not need. Bootstrap prints an API key, so do not repeat its output back to me, and never ask me to paste passwords, API keys, OAuth credentials, or command output.\n3. Confirm the API is reachable. `cnry doctor --format json` reports it, and any project read exits non-zero with `CONNECTION_ERROR` when it is not. If it is unreachable, propose `cnry start` and wait for approval. Use `cnry start`, which is the background daemon, and not `cnry serve`, which runs in the foreground and will block you until I stop it, even though some error messages suggest it. Stop anything you started with `cnry stop`.\n4. List projects with the connected project tool or `cnry project list --format json`, and reuse one whose domain matches. Confirm the proposed name is not already assigned to a different domain. To find out whether a project has already been scanned, run `cnry technical-aeo score <project> --format json` with no `--run-id`, which reports the latest run. Read the `hasData` field, not the score: this command exits 0 and reports `aggregateScore: 0` for a project that has never been scanned, so reading the score alone would have you tell me my site scored zero. If `hasData` is true and `runStatus` is `completed` or `partial`, read that scan instead of starting a new one. If no project matches, show the exact create operation and wait for approval.\n5. Propose a bounded Site Health scan: `--max-pages 100` for a first look, plus whether dead-link checking is on (it is off unless you pass `--check-dead-links`). Show the connected operation or the exact `cnry technical-aeo run <project> --max-pages 100 --wait --format json` command with the project name filled in, and wait for separate approval before scanning. `--wait` polls for up to 15 minutes and returns only the run id and status. If the status it returns is still `queued` or `running`, the scan has not finished: do not rerun it or report results, poll `cnry technical-aeo progress <project> --run-id <run-id> --format json` until it is terminal. If `--wait` outruns your own tool timeout first, recover the run id with `cnry technical-aeo score <project> --format json` and poll the same way.\n6. When the run is `completed` or `partial`, read `cnry technical-aeo crawl <project> --run-id <run-id> --format json` first. It is the only one of these commands that carries `termination` and `complete`; the score and pages commands do not. Then read `cnry technical-aeo score <project> --run-id <run-id> --format json` and `cnry technical-aeo pages <project> --run-id <run-id> --sort score-asc --limit 10 --format jsonl`. Tell me the termination reason in plain words and whether the scan covered the whole site or stopped at a page, link, depth, or time limit. A `partial` run scored the pages it reached and not my site, so never present it as a full-site result. If it stopped early, the fix depends on the reason, so say which: a page or depth limit needs a larger budget, a time limit needs a smaller scan (a lower `--max-pages` or `--max-depth`). If the run failed or was cancelled, inspect the run error and stop.\n7. Summarize only completed evidence, then propose AI Visibility setup. Ask before you add queries, connect providers, start a provider-backed or quota-consuming run, edit files, or publish.";function aJ(e,n){return e==="legacy"?"legacy":e==="platform"?"platform":n.state==="success"?n.projectCount===0?"platform":"legacy":n.state==="error"?"retry":"loading"}const iJ="2000-01-01T00:00:00.000Z",sJ=5e3;function oJ(e,n){const i=new Set,r=new Map;for(const f of n)f.trigger!==ks.probe&&(r.has(f.projectId)||r.set(f.projectId,f.id),(f.status===nn.completed||f.status===nn.partial)&&i.add(f.projectId));const h=(e.every(f=>f.createdAt)?[...e].sort((f,b)=>(f.createdAt??"").localeCompare(b.createdAt??"")||f.name.localeCompare(b.name)):e).find(f=>!i.has(f.id));return h?{projectName:h.name,runId:r.get(h.id)}:null}const BC=[{value:"US",label:"United States"},{value:"CA",label:"Canada"},{value:"GB",label:"United Kingdom"},{value:"AU",label:"Australia"},{value:"NZ",label:"New Zealand"},{value:"IE",label:"Ireland"},{value:"DE",label:"Germany"},{value:"FR",label:"France"},{value:"ES",label:"Spain"},{value:"IT",label:"Italy"},{value:"NL",label:"Netherlands"},{value:"BR",label:"Brazil"},{value:"MX",label:"Mexico"},{value:"IN",label:"India"},{value:"SG",label:"Singapore"},{value:"JP",label:"Japan"}],LC=[{value:"en",label:"English"},{value:"es",label:"Spanish"},{value:"fr",label:"French"},{value:"de",label:"German"},{value:"it",label:"Italian"},{value:"pt",label:"Portuguese"},{value:"nl",label:"Dutch"},{value:"ja",label:"Japanese"}];function rJ(e,n){try{const i=new Intl.DisplayNames(["en"],{type:"region"}),r=new Intl.DisplayNames(["en"],{type:"language"}),u=e.length===2?i.of(e.toUpperCase()):void 0,h=n?r.of(n.toLowerCase()):void 0;return`${u??(e||"Country")} · ${h??(n||"Language")}`}catch{return`${e||"Country"} · ${n||"Language"}`}}function lJ(e,n){const i=e.trim().toUpperCase(),r=n.trim().toLowerCase();return{countryValid:BC.some(u=>u.value===i),languageValid:LC.some(u=>u.value===r)}}function cJ(e){const n=e.replace(/^\[|\]$/g,"");return/^(?:\d{1,3}\.){3}\d{1,3}$/.test(n)||n.includes(":")}function uJ(e){const n=e.trim();if(!n)return null;const i=/^[a-z][a-z\d+.-]*:\/\//i.test(n)?n:`https://${n}`;let r;try{r=new URL(i)}catch{return null}if(r.protocol!=="http:"&&r.protocol!=="https:")return null;const u=r.hostname.toLowerCase().replace(/^www\./,"");if(!u||u==="localhost"||cJ(u)||!u.includes("."))return null;const h=u.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return h?{canonicalDomain:u,projectName:h,displayName:u}:null}async function dJ(e,n=eJ){let i;const r=new Promise(h=>{i=setTimeout(()=>h({state:"timed-out"}),n)}),u=await Promise.race([e.then(h=>({state:"queued",run:h})),r]);return i&&clearTimeout(i),u}function mJ(e,n){e.catch(()=>{wn({title:"Site Health scan did not start",detail:"The project is safe. Choose Run scan in Site Health to retry.",tone:"negative",dedupeKey:`site-health-dispatch:${n}`})})}function VC(e){const n=C.useRef(g1()).current,i=C.useRef(new Set),r=C.useCallback((u,h)=>{if(h){if(i.current.has(h))return;i.current.add(h)}n1({...u,surface:e,eventId:y1()})},[e]);return{onboardingSessionId:n,emit:r}}function Ik(e,n){return e instanceof xn&&e.statusCode===409?"A project with this name already exists. Change the project name, or open the existing project.":e instanceof Error&&e.message?e.message:n}function wg(){return l.jsxs("div",{className:"page-container max-w-3xl","aria-busy":"true","aria-live":"polite",children:[l.jsx("div",{className:"page-header",children:l.jsxs("div",{className:"page-header-left",children:[l.jsx("h1",{className:"page-title",children:"Preparing setup"}),l.jsx("p",{className:"page-subtitle",children:"Checking the projects already on this install."})]})}),l.jsxs("div",{className:"flex items-center gap-3 rounded-lg border border-default bg-surface p-4 text-sm text-secondary",role:"status",children:[l.jsx(Rr,{className:"size-4 motion-safe:animate-spin","aria-hidden":"true"}),"Loading projects…"]})]})}function pJ({onRetry:e}){return l.jsxs("div",{className:"page-container max-w-3xl",children:[l.jsx("div",{className:"page-header",children:l.jsxs("div",{className:"page-header-left",children:[l.jsx("h1",{className:"page-title",children:"Can’t load projects"}),l.jsx("p",{className:"page-subtitle",children:"Canonry could not confirm whether this install already has a project."})]})}),l.jsxs("div",{className:"rounded-lg border border-negative bg-negative-soft p-4",role:"alert",tabIndex:-1,children:[l.jsx("p",{className:"text-sm font-medium text-heading",children:"Setup is paused to protect existing projects."}),l.jsx("p",{className:"mt-1 text-sm text-secondary",children:"Check the connection or sign in again, then retry."}),l.jsx(ue,{type:"button",className:"mt-4",variant:"secondary",onClick:e,children:"Retry project check"})]})]})}function hJ({projectName:e,initialRunId:n}){return l.jsx(h1,{title:"Site Health setup",children:l.jsx(fJ,{projectName:e,initialRunId:n})})}function fJ({projectName:e,initialRunId:n}){const i=Ns(),r=yt({...Do({client:J}),enabled:!!e,retry:!1,refetchOnMount:"always"}),{onboardingSessionId:u,emit:h}=VC("site_health"),[f]=C.useState(()=>yX(n));C.useEffect(()=>{f&&bX()},[f]),C.useEffect(()=>{e&&h({flowVersion:ft,onboardingSessionId:u,event:"onboarding.started",step:"run",resumed:!!n&&!f},"onboarding.started")},[h,f,n,u,e]),C.useEffect(()=>{!e||!n||OC(e)?.runId!==n&&IC(e,n)},[n,e]);const v=yt({...o1({client:J,path:{id:n??""}}),enabled:!!n,refetchInterval:({state:N})=>{const P=N.data?.status;return P==="completed"||P==="partial"||P==="failed"||P==="cancelled"?!1:2e3},refetchIntervalInBackground:!0}).data?.status;if(C.useEffect(()=>{if(!e||!n||!v)return;if(v==="completed"||v==="partial"){h({flowVersion:ft,onboardingSessionId:u,event:"onboarding.step_completed",step:"run",method:"automatic"},"onboarding.step_completed:run"),Yd(n);return}if(v!=="failed"&&v!=="cancelled")return;const N=v==="cancelled"?"run_cancelled":"run_failed";h({flowVersion:ft,onboardingSessionId:u,event:"onboarding.blocked",step:"run",action:"retry_run",reasonCode:N},`onboarding.blocked:run:${N}`),Yd(n)},[h,n,u,e,v]),!e)return l.jsxs("div",{className:"page-container max-w-3xl",children:[l.jsx("div",{className:"page-header",children:l.jsxs("div",{className:"page-header-left",children:[l.jsx("h1",{className:"page-title",children:"Project not found"}),l.jsx("p",{className:"page-subtitle",children:"This setup link does not identify a project."})]})}),l.jsx(ue,{type:"button",variant:"secondary",onClick:()=>{i({to:"/projects"})},children:"View projects"})]});if(r.isPending)return l.jsxs("div",{className:"page-container max-w-3xl","aria-busy":"true","aria-live":"polite",children:[l.jsx(jo,{current:"site"}),l.jsxs("div",{className:"mt-8 flex items-center gap-3 text-sm text-secondary",role:"status",children:[l.jsx(Rr,{className:"size-4 motion-safe:animate-spin","aria-hidden":"true"}),"Loading Site Health setup…"]})]});if(r.isError)return l.jsxs("div",{className:"page-container max-w-3xl",children:[l.jsx("div",{className:"page-header",children:l.jsxs("div",{className:"page-header-left",children:[l.jsx("h1",{className:"page-title",children:"Can’t resume setup"}),l.jsx("p",{className:"page-subtitle",children:"Canonry could not load the project for this Site Health scan."})]})}),l.jsxs("div",{className:"rounded-lg border border-negative bg-negative-soft p-4",role:"alert",children:[l.jsx("p",{className:"text-sm text-secondary",children:"Check the connection or sign in again, then retry."}),l.jsx(ue,{type:"button",className:"mt-4",variant:"secondary",onClick:()=>{r.refetch()},children:"Retry project check"})]})]});const w=r.data.find(N=>N.name===e);if(!w)return l.jsxs("div",{className:"page-container max-w-3xl",children:[l.jsx("div",{className:"page-header",children:l.jsxs("div",{className:"page-header-left",children:[l.jsx("h1",{className:"page-title",children:"Project not found"}),l.jsxs("p",{className:"page-subtitle",children:["Canonry could not find ",e,". It will not open a different project."]})]})}),l.jsx(ue,{type:"button",variant:"secondary",onClick:()=>{i({to:"/projects"})},children:"View projects"})]});const k=()=>{i({to:"/setup",search:{onboarding:"site-health",setupProject:w.name},replace:!0})},j=()=>{i({to:"/setup",search:{experience:"legacy",onboarding:"site-health",setupProject:w.name},replace:!0})},T=()=>{h({flowVersion:ft,onboardingSessionId:u,event:"onboarding.step_completed",step:"run",method:"skipped"},"onboarding.step_completed:run"),i({to:"/setup",search:{onboarding:"complete",setupProject:w.name,skipped:"visibility"},replace:!0})};return l.jsxs("div",{className:"page-container max-w-7xl py-8 md:py-10",children:[l.jsx("h1",{className:"sr-only",children:"Set up Canonry"}),l.jsx(C.Suspense,{fallback:l.jsxs("div",{className:"space-y-5",children:[l.jsx(jo,{current:"site"}),l.jsxs("div",{className:"flex min-h-72 items-center justify-center gap-3 text-sm text-secondary",role:"status",children:[l.jsx(Rr,{className:"size-4 motion-safe:animate-spin","aria-hidden":"true"}),"Loading Site Health…"]})]}),children:l.jsx(JX,{projectName:w.name,projectId:w.id,initialRunId:n,onReleaseInitialRun:k,showOnboardingActions:!0,onContinueOnboarding:j,onSkipOnboarding:T})})]})}function gJ(){const e=Pk({from:"/setup"}),n=e.onboarding==="site-health"&&!e.setupProject,i=e.onboarding==="site-health"&&e.experience!=="legacy",r=bG(),u=e.experience==="legacy"?"legacy":e.experience==="platform"?"platform":r,[h,f]=C.useState(!1),[b,v]=C.useState(void 0),w=yt({...Do({client:J}),enabled:u==="auto",retry:!1,refetchOnMount:"always"}),k=yt({..._m({client:J,query:{kind:ze["site-audit"],since:iJ,limit:sJ}}),enabled:u==="auto",retry:!1,refetchOnMount:"always"}),j=u==="auto"&&w.isSuccess&&w.isFetchedAfterMount&&w.data.length===0;C.useEffect(()=>{j&&f(!0)},[j]);const T=u!=="auto"?{state:"idle"}:w.isSuccess&&w.isFetchedAfterMount?{state:"success",projectCount:w.data.length}:w.isError?{state:"error"}:{state:"loading"},N=u==="legacy"?"legacy":h||j?"platform":aJ(u,T);if(e.onboarding==="complete"&&e.setupProject)return l.jsx(BX,{projectName:e.setupProject,skippedVisibility:e.skipped==="visibility"});if(n||i)return l.jsx(hJ,{projectName:e.setupProject,initialRunId:e.siteHealthRunId});const P=u==="auto"&&N==="legacy"&&!e.setupProject&&w.isSuccess;if(P&&b===void 0)return k.isError?v(null):k.isSuccess&&k.isFetchedAfterMount&&v(oJ(w.data,k.data)),l.jsx(wg,{});const E=P?b:null;return E?l.jsx(yJ,{projectName:E.projectName,runId:E.runId}):N==="legacy"?l.jsx(OX,{visibilityProjectName:e.setupProject,siteHealthOnboarding:e.onboarding==="site-health",onboardingFinish:e.onboarding==="site-health"||e.onboarding==="first-run"}):N==="loading"?l.jsx(wg,{}):N==="retry"?l.jsx(pJ,{onRetry:()=>{w.refetch()}}):l.jsx(bJ,{onActivationStarted:()=>f(!0),skipSiteScan:e.siteScan==="skip"})}function yJ({projectName:e,runId:n}){const i=Ns();return C.useEffect(()=>{i({to:"/setup",search:{onboarding:"site-health",setupProject:e,...n?{siteHealthRunId:n}:{}},replace:!0})},[i,e,n]),l.jsx(wg,{})}function bJ({onActivationStarted:e,skipSiteScan:n}){return l.jsx(h1,{title:"Site Health setup",children:l.jsx(vJ,{onActivationStarted:e,skipSiteScan:n})})}function vJ({onActivationStarted:e,skipSiteScan:n}){const i=Ns(),r=Jn(),u=AX(),h=yt({...gH({client:J}),retry:!1}),f=Ga(yH()),[b,v]=C.useState(""),[w,k]=C.useState(""),[j,T]=C.useState(""),[N,P]=C.useState("US"),[E,q]=C.useState("en"),[H,X]=C.useState(!1),[L,Z]=C.useState("idle"),[Y,ee]=C.useState(null),[B,K]=C.useState(null),[we,Xe]=C.useState(!1),[nt,Ue]=C.useState(null),[Pe,ke]=C.useState(!1),$e=h.isError?void 0:h.data,O=typeof $e?.enabled=="boolean"?$e.enabled:null,ne=f.isPending?f.variables.body.enabled:O,[ge,Se]=C.useState(null),ae=C.useRef(null),{onboardingSessionId:_e,emit:Be}=VC("platform");C.useEffect(()=>{Be({flowVersion:ft,onboardingSessionId:_e,event:"onboarding.started",step:"project",resumed:!1},"onboarding.started")},[Be,_e]);const ve=uJ(b),le=w||ve?.projectName||"",ce=j||ve?.displayName||"",Q=L==="creating"||L==="dispatching",me=B??nt,De=rJ(N,E),{countryValid:je,languageValid:it}=lJ(N,E),Ge=je&&it;C.useEffect(()=>{me&&ae.current?.focus()},[me]);const jt=(Le,ct)=>i({to:"/setup",search:{...ct?{siteHealthRunId:ct}:{},onboarding:"site-health",setupProject:Le.name},replace:!0}),He=async Le=>{Z("dispatching"),Ue(null);try{const ct=u.mutateAsync({projectName:Le.name,projectId:Le.id,projectLabel:Le.displayName||Le.name,suppressErrorToast:!0,body:{checkDeadLinks:!0,maxPages:n3}}),Kt=await dJ(ct);if(Kt.state==="queued"){Be({flowVersion:ft,onboardingSessionId:_e,event:"run.requested",origin:"dashboard_setup",result:"queued",kind:"site_health",providerCountBucket:"0",queryCountBucket:"0"}),gX(Kt.run.runId),await jt(Le,Kt.run.runId);return}ct.then(()=>{Be({flowVersion:ft,onboardingSessionId:_e,event:"run.requested",origin:"dashboard_setup",result:"queued",kind:"site_health",providerCountBucket:"0",queryCountBucket:"0"})},Ht=>{Be({flowVersion:ft,onboardingSessionId:_e,event:"run.requested",origin:"dashboard_setup",result:"rejected",kind:"site_health",providerCountBucket:"0",queryCountBucket:"0",reasonCode:gc(Ht,"run_rejected")})}),mJ(ct,Le.id),await jt(Le)}catch(ct){Z("recovery"),Ue(Ik(ct,"The project was created, but the Site Health scan could not be started."));const Kt=gc(ct,"run_rejected");Be({flowVersion:ft,onboardingSessionId:_e,event:"run.requested",origin:"dashboard_setup",result:"rejected",kind:"site_health",providerCountBucket:"0",queryCountBucket:"0",reasonCode:Kt}),Be({flowVersion:ft,onboardingSessionId:_e,event:"onboarding.blocked",step:"run",action:"retry_run",reasonCode:Kt},`onboarding.blocked:run:${Kt}`)}},re=async Le=>{if(Le.preventDefault(),!(!ve||!n&&!H||!Ge||Q)){Z("creating"),K(null),Xe(!1),Ue(null);try{const ct=await MG({name:le,displayName:ce,canonicalDomain:ve.canonicalDomain,country:N,language:E});if(e(),ee(ct),Be({flowVersion:ft,onboardingSessionId:_e,event:"onboarding.step_completed",step:"project",method:"manual"},"onboarding.step_completed:project"),await r.invalidateQueries({queryKey:As({client:J})}),n){await i({to:"/setup",search:{experience:"legacy",onboarding:"first-run",setupProject:ct.name},replace:!0});return}await He(ct)}catch(ct){Z("idle");const Kt=ct instanceof xn&&ct.statusCode===409;Xe(Kt),K(Ik(ct,"Could not create the project. Try again.")),Be({flowVersion:ft,onboardingSessionId:_e,event:"onboarding.blocked",step:"project",action:"save",reasonCode:gc(ct,"project_create_failed")},"onboarding.blocked:project"),Kt&&(e(),r.invalidateQueries({queryKey:As({client:J})}))}}},lt=()=>{Y&&!Q&&He(Y)},Gt=()=>{Q||i({to:"/projects"})},ea=async()=>{try{await navigator.clipboard.writeText(nJ),ke(!0)}catch{wn({tone:"negative",title:"Could not copy setup request",detail:"Open the agent quickstart to continue with the CLI instead."})}},ci=async Le=>{Se(null);try{const ct=await f.mutateAsync({client:J,body:{enabled:Le}});r.setQueryData(JA({client:J}),ct),ct.enabled!==Le&&Se(`The server kept telemetry ${ct.enabled?"on":"off"}. Check its telemetry settings.`)}catch{Se("Could not update telemetry. Try again.")}};return Y&&L==="recovery"?l.jsxs("div",{className:"page-container max-w-3xl",children:[l.jsx(jo,{current:"site"}),l.jsx("div",{className:"page-header mt-8",children:l.jsxs("div",{className:"page-header-left",children:[l.jsx("h1",{className:"page-title",children:"Project created"}),l.jsxs("p",{className:"page-subtitle",children:[Y.displayName||Y.name," is ready. The Site Health scan needs another try."]})]})}),l.jsxs("div",{ref:ae,className:"rounded-lg border border-negative bg-negative-soft p-4",role:"alert",tabIndex:-1,children:[l.jsx("p",{className:"text-sm font-medium text-heading",children:nt}),l.jsx("p",{className:"mt-1 text-sm text-secondary",children:"You can retry the scan or continue setup and retry from Site Health."}),l.jsxs("div",{className:"mt-4 flex flex-wrap gap-3",children:[l.jsx(ue,{type:"button",onClick:lt,children:"Retry Site Health scan"}),l.jsx(ue,{type:"button",variant:"secondary",onClick:()=>{jt(Y)},children:"Continue setup"})]})]})]}):l.jsxs("div",{className:"page-container max-w-xl py-8 md:py-12",children:[n?null:l.jsx(jo,{current:"site"}),l.jsxs("header",{className:`mb-8 ${n?"":"mt-8"}`,children:[l.jsx("h1",{id:"site-map-setup-title",className:"text-2xl font-semibold tracking-[-0.025em] text-heading",children:n?"Create a project":"Scan your site"}),l.jsx("p",{className:"mt-2 max-w-lg text-sm leading-6 text-secondary",children:n?"Add a public domain, then choose the queries you want to track. No site scan will run.":"Enter your public website to see its pages, structure, internal links, and technical SEO scores."})]}),l.jsxs("form",{"aria-labelledby":"site-map-setup-title",className:"space-y-6",onSubmit:pn(re),noValidate:!0,children:[l.jsxs("div",{className:"grid gap-2",children:[l.jsx("label",{className:"text-sm font-medium text-heading",htmlFor:"launchpad-domain",children:"Website URL"}),l.jsx("input",{id:"launchpad-domain",className:"h-11 w-full rounded-md border border-strong bg-bg-elevated/50 px-3 text-base text-heading outline-none transition placeholder:text-muted focus:border-mono-500 focus:ring-1 focus:ring-mono-500",type:"text",inputMode:"url",autoComplete:"url",autoCapitalize:"none",spellCheck:!1,required:!0,"aria-invalid":!!(b&&!ve),"aria-describedby":b&&!ve?"launchpad-domain-hint launchpad-domain-error":"launchpad-domain-hint",placeholder:"https://example.com",value:b,onChange:Le=>{v(Le.target.value),K(null),Xe(!1)}}),l.jsx("p",{id:"launchpad-domain-hint",className:"text-sm text-secondary",children:n?l.jsxs(l.Fragment,{children:["A public domain is still required."," ",l.jsx(We,{to:"/setup",search:{experience:"platform"},className:"font-medium text-link underline-offset-4 hover:underline",children:"Map with Site Health instead"})]}):l.jsxs(l.Fragment,{children:["Only public pages are scanned."," ",l.jsx(We,{to:"/setup",search:{experience:"platform",onboarding:"first-run",siteScan:"skip"},className:"font-medium text-link underline-offset-4 hover:underline",children:"Set up without a site scan"})]})}),b&&!ve?l.jsx("p",{id:"launchpad-domain-error",className:"text-sm text-negative",role:"alert",children:"Enter a public domain, such as example.com."}):null]}),l.jsxs("details",{className:"group border-y border-default",children:[l.jsxs("summary",{className:"flex min-h-11 cursor-pointer list-none items-center justify-between gap-4 py-3 text-sm [&::-webkit-details-marker]:hidden",children:[l.jsx("span",{className:"font-medium text-heading",children:"Project name and locale"}),l.jsxs("span",{className:"flex items-center gap-2 text-secondary",children:[De,l.jsx(Jd,{className:"size-4 transition-transform group-open:rotate-180 motion-reduce:transition-none","aria-hidden":"true"})]})]}),l.jsxs("div",{className:"space-y-5 border-t border-default py-4",children:[ve?l.jsxs("div",{children:[l.jsx("p",{className:"mb-3 text-sm font-medium text-heading",children:"Project"}),l.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[l.jsxs("div",{className:"grid gap-2",children:[l.jsx("label",{className:"text-sm text-secondary",htmlFor:"launchpad-project-name",children:"Project name"}),l.jsx("input",{id:"launchpad-project-name",className:"setup-input h-10",type:"text",value:le,onChange:Le=>k(Le.target.value)})]}),l.jsxs("div",{className:"grid gap-2",children:[l.jsx("label",{className:"text-sm text-secondary",htmlFor:"launchpad-display-name",children:"Display name"}),l.jsx("input",{id:"launchpad-display-name",className:"setup-input h-10",type:"text",value:ce,onChange:Le=>T(Le.target.value)})]})]})]}):null,l.jsxs("div",{children:[l.jsx("p",{className:"mb-3 text-sm font-medium text-heading",children:"Locale"}),l.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[l.jsxs("div",{className:"grid gap-2",children:[l.jsx("label",{className:"text-sm text-secondary",htmlFor:"launchpad-country",children:"Country"}),l.jsx("select",{id:"launchpad-country",className:"setup-input h-10",value:N,onChange:Le=>P(Le.target.value),children:BC.map(Le=>l.jsx("option",{value:Le.value,children:Le.label},Le.value))})]}),l.jsxs("div",{className:"grid gap-2",children:[l.jsx("label",{className:"text-sm text-secondary",htmlFor:"launchpad-language",children:"Language"}),l.jsx("select",{id:"launchpad-language",className:"setup-input h-10",value:E,onChange:Le=>q(Le.target.value),children:LC.map(Le=>l.jsx("option",{value:Le.value,children:Le.label},Le.value))})]})]})]})]})]}),n?null:l.jsxs("label",{className:"flex min-h-11 cursor-pointer items-start gap-3 py-2",children:[l.jsx("input",{className:"mt-0.5 size-4 shrink-0 rounded border-strong bg-bg",type:"checkbox",checked:H,onChange:Le=>X(Le.target.checked),"aria-label":"Allow Canonry to scan this public site."}),l.jsxs("span",{className:"flex items-center gap-1.5",children:[l.jsx("span",{className:"text-sm leading-5 text-heading",children:"Allow Canonry to scan this public site."}),l.jsx(Ua,{text:WX})]})]}),me?l.jsxs("div",{ref:ae,className:"rounded-md border border-negative bg-negative-soft p-3",role:"alert",tabIndex:-1,children:[l.jsx("p",{className:"text-sm font-medium text-heading",children:me}),we?l.jsx(ue,{type:"button",variant:"secondary",size:"sm",className:"mt-3",onClick:Gt,children:"View projects"}):null]}):null,l.jsxs("div",{className:"grid gap-2",children:[l.jsx(ue,{className:"h-11 w-full",type:"submit",disabled:!ve||!n&&!H||!Ge||Q,children:L==="creating"||L==="dispatching"?l.jsxs(l.Fragment,{children:[l.jsx(Rr,{className:"size-4 motion-safe:animate-spin","aria-hidden":"true"})," ",n?"Creating project…":"Mapping site…"]}):n?"Create project":"Scan site"}),L==="dispatching"?l.jsx("span",{className:"text-center text-sm text-secondary",role:"status",children:"Opening Site Health when the scan is ready."}):null]})]}),l.jsxs("section",{className:"mt-8 border-t border-default pt-6","aria-labelledby":"agent-setup-title",children:[l.jsx("p",{id:"agent-setup-title",className:"text-sm font-medium text-heading",children:"Use your agent instead"}),l.jsx("p",{className:"mt-1 text-sm leading-5 text-secondary",children:"Copy a complete CLI setup request into any agent."}),l.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-1",children:[l.jsxs(ue,{type:"button",variant:"ghost",size:"sm",className:"-ml-3",onClick:pn(ea),children:[Pe?l.jsx(Wd,{className:"size-3.5","aria-hidden":"true"}):l.jsx(Cg,{className:"size-3.5","aria-hidden":"true"}),l.jsx("span",{"aria-live":"polite",children:Pe?"Copied setup request":"Copy setup request"})]}),l.jsx(ue,{asChild:!0,variant:"ghost",size:"sm",children:l.jsxs("a",{href:tJ,target:"_blank",rel:"noopener noreferrer",children:["Agent quickstart",l.jsx(w5,{className:"size-3.5","aria-hidden":"true"}),l.jsx("span",{className:"sr-only",children:" (opens in a new tab)"})]})})]})]}),O!==null?l.jsxs("section",{className:"mt-6 border-t border-default pt-5","aria-labelledby":"telemetry-title",children:[l.jsxs("label",{className:`flex min-h-11 items-start gap-3 py-2 ${f.isPending?"cursor-wait":"cursor-pointer"}`,children:[l.jsx("input",{className:"mt-0.5 size-4 shrink-0 rounded border-strong bg-bg accent-accent focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-mono-500 disabled:cursor-wait",type:"checkbox",checked:ne??!1,disabled:f.isPending,onChange:Le=>{ci(Le.target.checked)},"aria-describedby":"telemetry-detail"}),l.jsxs("span",{className:"grid gap-0.5",children:[l.jsx("span",{id:"telemetry-title",className:"text-sm leading-5 text-heading",children:"Share anonymous product telemetry"}),l.jsx("span",{id:"telemetry-detail",className:"max-w-[70ch] text-sm leading-5 text-secondary",children:"Helps prioritize improvements. Canonry does not send raw domains, URLs, queries, answer content, or credentials."})]})]}),f.isPending?l.jsx("p",{className:"mt-1 text-sm text-secondary",role:"status",children:"Saving preference…"}):null,ge?l.jsx("p",{className:"mt-1 text-sm text-negative",role:"alert",children:ge}):null]}):null]})}function xJ(){return l.jsx("div",{className:"page-container",children:l.jsx("section",{className:"page-section",children:l.jsxs(_a,{className:"surface-card empty-card",children:[l.jsx("h1",{children:"Route not found"}),l.jsx("p",{children:"The current path does not map to a dashboard view."}),l.jsx(ue,{asChild:!0,children:l.jsx(We,{to:"/",children:"Return to overview"})})]})})})}const ha=_s(()=>Li(()=>import("./ProjectPage-CXV64SBB.js"),__vite__mapDeps([5,1,2,6,0,3,4,7,8,9,10,11,12]),import.meta.url),"ProjectPage"),wJ=_s(()=>Li(()=>import("./RunsPage-lO9xMTSl.js"),__vite__mapDeps([13,1,6,11,4,2,9,12]),import.meta.url),"RunsPage"),kJ=_s(()=>Li(()=>import("./HistoryPage-2o6p-ZDF.js"),__vite__mapDeps([14,1,10,11,4,2,9,12]),import.meta.url),"HistoryPage"),SJ=_s(()=>Li(()=>import("./SettingsPage-CBwns7cb.js"),__vite__mapDeps([15,1,11,4,2,9,12]),import.meta.url),"SettingsPage"),jJ=_s(()=>Li(()=>import("./BacklinksPage-DroPpjd3.js"),__vite__mapDeps([16,1,2,11,4,9,12]),import.meta.url),"BacklinksPage"),AJ=_s(()=>Li(()=>import("./TrafficPage-DGyS-IjJ.js"),__vite__mapDeps([17,1,7,2,11,4,9,12]),import.meta.url),"TrafficPage"),CJ=_s(()=>Li(()=>import("./TrafficSourceDetailPage-BBaz_ivE.js"),__vite__mapDeps([18,1,7,3,4,2,11,9,12]),import.meta.url),"TrafficSourceDetailPage"),NJ=_s(()=>Li(()=>import("./MeasurementPropertyPage-VTGLyVuD.js"),__vite__mapDeps([19,1,3,4,8,9,2,11,12]),import.meta.url),"MeasurementPropertyPage");function _J(){return l.jsx(OY,{children:l.jsx(_K,{children:l.jsx(IY,{})})})}const Vn=XN()({component:_J,validateSearch:e=>({manageQueries:e.manageQueries===!0||e.manageQueries==="true"?!0:void 0,runId:typeof e.runId=="string"?e.runId:void 0,siteHealthRunId:typeof e.siteHealthRunId=="string"?e.siteHealthRunId:void 0,evidenceId:typeof e.evidenceId=="string"?e.evidenceId:void 0,runStatus:typeof e.runStatus=="string"?e.runStatus:void 0,runKind:typeof e.runKind=="string"?e.runKind:void 0,runProject:typeof e.runProject=="string"?e.runProject:void 0,runWindow:typeof e.runWindow=="string"?e.runWindow:void 0,runQuery:typeof e.runQuery=="string"?e.runQuery:void 0,onboarding:e.onboarding==="site-health"||e.onboarding==="first-run"||e.onboarding==="complete"?e.onboarding:void 0,experience:e.experience==="legacy"||e.experience==="platform"?e.experience:void 0,siteScan:e.siteScan==="skip"?"skip":void 0,skipped:e.skipped==="visibility"?"visibility":void 0,setupProject:typeof e.setupProject=="string"?e.setupProject:void 0,scope:typeof e.scope=="string"?e.scope:void 0,class:typeof e.class=="string"?e.class:void 0,...Object.fromEntries(["queryWorkspace","researchMode","trackingQueryId","measurementScope","measurementScopeKey","measurementMarketKey","queryClass","measurementProvider","measurementModel","measurementLocation","measurementFrom","measurementTo","measurementRevision","measurementRunId","measurementQueryKey","measurementAnswer"].map(n=>[n,typeof e[n]=="string"?e[n]:void 0]))})}),TJ=qt({getParentRoute:()=>Vn,path:"/",component:sX,beforeLoad:async({context:e})=>{let n=e.queryClient.getQueryData(As({client:J}));if(n===void 0)try{n=await e.queryClient.ensureQueryData(Do({client:J}))}catch{return}if(n.length===0)throw Mk({to:"/setup"})}}),EJ=qt({getParentRoute:()=>Vn,path:"/projects",component:cX}),RJ=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,$n=qt({getParentRoute:()=>Vn,path:"/projects/$projectName",component:()=>l.jsx(Tf,{}),beforeLoad:async({context:e,params:n,location:i})=>{const r=n.projectName;if(!RJ.test(r))return;let u=e.queryClient.getQueryData(As({client:J}));if(!u)try{u=await e.queryClient.ensureQueryData(Do({client:J}))}catch{return}const h=u.find(f=>f.id===r);if(h)throw Mk({to:i.pathname.replace(`/projects/${r}`,`/projects/${encodeURIComponent(h.name)}`),replace:!0})}}),DJ=qt({getParentRoute:()=>$n,path:"/",component:()=>l.jsx(ha,{tab:"overview"})}),zJ=qt({getParentRoute:()=>$n,path:"/portfolio",component:()=>l.jsx(ha,{tab:"portfolio"})}),IJ=qt({getParentRoute:()=>$n,path:"/search-console",component:()=>l.jsx(ha,{tab:"search-console"})}),OJ=qt({getParentRoute:()=>$n,path:"/conversions",component:()=>l.jsx(ha,{tab:"conversions"})}),PJ=qt({getParentRoute:()=>$n,path:"/local",component:()=>l.jsx(ha,{tab:"local"})}),qJ=qt({getParentRoute:()=>$n,path:"/discovery",component:()=>l.jsx(ha,{tab:"discovery"})}),MJ=qt({getParentRoute:()=>$n,path:"/queries",component:()=>l.jsx(ha,{tab:"queries"})}),BJ=qt({getParentRoute:()=>$n,path:"/properties/$targetKey",component:()=>l.jsx(NJ,{})}),LJ=qt({getParentRoute:()=>$n,path:"/report",component:()=>l.jsx(ha,{tab:"report"})}),VJ=qt({getParentRoute:()=>$n,path:"/activity",component:()=>l.jsx(ha,{tab:"activity"})}),$J=qt({getParentRoute:()=>$n,path:"/backlinks",component:()=>l.jsx(ha,{tab:"backlinks"})}),UJ=qt({getParentRoute:()=>$n,path:"/technical-aeo",component:()=>l.jsx(ha,{tab:"technical-aeo"})}),GJ=qt({getParentRoute:()=>$n,path:"/history",component:()=>l.jsx(ha,{tab:"history"})}),KJ=qt({getParentRoute:()=>$n,path:"/settings",component:()=>l.jsx(ha,{tab:"settings"})}),HJ=qt({getParentRoute:()=>Vn,path:"/runs",component:wJ}),QJ=qt({getParentRoute:()=>Vn,path:"/history",component:kJ}),FJ=qt({getParentRoute:()=>Vn,path:"/settings",component:SJ,beforeLoad:({context:e})=>{}}),ZJ=qt({getParentRoute:()=>Vn,path:"/setup",component:gJ}),YJ=qt({getParentRoute:()=>Vn,path:"/backlinks",component:jJ}),XJ=qt({getParentRoute:()=>Vn,path:"/traffic",component:AJ}),JJ=qt({getParentRoute:()=>Vn,path:"/traffic/$projectName/$sourceId",component:CJ}),WJ=qt({getParentRoute:()=>Vn,path:"*",component:xJ}),eW=Vn.addChildren([TJ,EJ,$n.addChildren([DJ,zJ,IJ,OJ,PJ,qJ,MJ,BJ,LJ,VJ,$J,UJ,GJ,KJ]),HJ,QJ,FJ,ZJ,YJ,XJ,JJ,WJ]);function tW(){return typeof window<"u"&&window.__CANONRY_CONFIG__?.basePath?window.__CANONRY_CONFIG__.basePath:"/"}const Ok=tW(),nW=Ok==="/"?"":Ok.replace(/\/$/,"");function aW(e,n){return JN({routeTree:eW,basepath:nW||"/",context:{queryClient:e},...n?.initialEntries})}const iW=6e4;function sW(){const e=C.useRef(OG()).current,[n,i]=C.useState(e?"ready":"checking"),[r,u]=C.useState(null),[h,f]=C.useState(null),[b,v]=C.useState(e),[w,k]=C.useState(!1),[j,T]=C.useState(""),[N,P]=C.useState(""),[E,q]=C.useState(""),[H,X]=C.useState(!1),[L,Z]=C.useState("password"),[Y,ee]=C.useState(null),[B,K]=C.useState(!1),[we,Xe]=C.useState(!1),nt=C.useRef(null),Ue=C.useRef(null),Pe=C.useRef(null),ke=()=>{const Q=r?`${r.name}:${r.role}`:e?"api-key:explicit":h?`api-key:${h.id}`:"no-accounts";if(!nt.current||Pe.current!==Q){Ue.current?.clear();const me=AK();Ue.current=me,nt.current=aW(me),Pe.current=Q}return{queryClient:Ue.current,router:nt.current}},$e=Q=>Q.authRequired?(k(!0),u(Q.user),f(null),v(!1),i(Q.user?"ready":"account-login"),!0):!1;C.useEffect(()=>{let Q=!1;const me=async(De,je=!1)=>{try{const it=await xf();if(Q)return;f(it),v(!1),i("ready")}catch(it){if(Q)return;if(je&&it instanceof xn&&it.statusCode===401)return QG().then(()=>{Q||(ee(null),f(null),v(!1),Xe(!0),i("login"))}).catch(Ge=>{Q||(ee(Ge instanceof Error?Ge.message:"Could not clear the invalid session"),i(De))});ee(it instanceof Error?it.message:"Could not verify API key access"),i(De)}};return e?(me("api-key-error"),()=>{Q=!0}):(Promise.allSettled([$w(),Vw()]).then(([De,je])=>{if(Q||De.status==="fulfilled"&&$e(De.value))return;if(je.status==="rejected"){const Ge=je.reason;ee(Ge instanceof Error?Ge.message:"Failed to reach the Canonry API"),i("login");return}const it=je.value;it.authenticated?(v(!0),me("api-key-error",!0)):(f(null),v(!1),i(it.setupRequired?"setup":"login"))}),()=>{Q=!0})},[]),C.useEffect(()=>{if(n!=="ready"||e)return;const Q=setInterval(()=>{if(w){$w().then(me=>{me.authRequired&&!me.user&&(Xe(!0),u(null),f(null),i("account-login"))}).catch(()=>{});return}Vw().then(me=>{me.authenticated||(Xe(!0),f(null),i(me.setupRequired?"setup":"login"))}).catch(()=>{})},iW);return Lw(()=>{Xe(!0),u(null),f(null),v(!1),i(w?"account-login":"login")}),()=>{clearInterval(Q),Lw(null)}},[n,w,e]);const O=async Q=>{if(Q.preventDefault(),!N.trim()||N.trim().length<8){ee("Password must be at least 8 characters");return}if(N!==E){ee("Passwords do not match");return}K(!0),ee(null);try{if(!(await GG(N.trim())).authenticated){ee("Setup failed");return}P(""),q(""),X(!1),Xe(!1),f(null),v(!0),i("checking");try{const De=await xf();f(De),v(!1),i("ready")}catch(De){ee(De instanceof Error?De.message:"Could not verify API key access"),i("api-key-error")}}catch(me){ee(me instanceof xn||me instanceof Error?me.message:"Setup failed")}finally{K(!1)}},ne=Q=>{P(Q),ee(null)},ge=Q=>{q(Q),ee(null)},Se=async Q=>{if(Q.preventDefault(),!!N.trim()){K(!0),ee(null);try{if(!(L==="api-key"?await HG(N.trim()):await KG(N.trim())).authenticated){ee(L==="api-key"?"Invalid API key":"Incorrect password");return}const De=await xf();f(De),v(!1),P(""),X(!1),Xe(!1),i("ready")}catch(me){ee(me instanceof xn||me instanceof Error?me.message:"Authentication failed")}finally{K(!1)}}},ae=Q=>{Z(Q),P(""),X(!1),ee(null)},_e=async Q=>{if(Q.preventDefault(),!(!j.trim()||!N)){K(!0),ee(null);try{const me=await FG(j.trim(),N);if(!me.user){ee("Incorrect name or password.");return}P(""),Xe(!1),u(me.user),f(null),v(!1),i("ready")}catch(me){ee(me instanceof xn?me.message:"Incorrect name or password.")}finally{K(!1)}}};if(n==="ready"){const{queryClient:Q,router:me}=ke();return l.jsx(fK,{account:r,apiKey:h,apiKeyPending:b,children:l.jsx(WN,{client:Q,children:l.jsx(e5,{router:me})})})}const Be=N.trim(),ve=N.length>0&&Be.length<8,le=E.length>0&&N!==E,ce=Be.length>=8&&N===E;return l.jsx("div",{className:"min-h-screen bg-bg px-4 py-8",children:l.jsxs("div",{className:"mx-auto flex min-h-[calc(100vh-4rem)] max-w-md flex-col items-center justify-center gap-5",children:[l.jsxs("div",{"data-testid":"auth-brand",className:"flex items-center gap-2.5",children:[l.jsx("img",{className:"size-7",src:"./favicon.svg",alt:"","aria-hidden":"true"}),l.jsx("span",{className:"text-lg font-semibold tracking-tight text-heading",children:"Canonry"})]}),l.jsx(_a,{className:"surface-card w-full",children:n==="checking"?l.jsx(go,{className:"py-8",children:l.jsx("p",{className:"supporting-copy text-center",children:"Connecting to Canonry…"})}):n==="api-key-error"?l.jsxs(l.Fragment,{children:[l.jsxs(Nr,{children:[l.jsx("p",{className:"eyebrow eyebrow-soft",children:"Dashboard access"}),l.jsx("h1",{className:"font-medium tracking-tight text-primary",children:"Could not verify API key access"})]}),l.jsxs(go,{className:"space-y-4",children:[l.jsx("p",{className:"supporting-copy",children:Y??"Canonry could not verify this session’s access, so the dashboard stayed locked."}),l.jsx(ue,{type:"button",className:"w-full",onClick:()=>{window.location.reload()},children:"Try again"})]})]}):n==="account-login"?l.jsxs(l.Fragment,{children:[l.jsxs(Nr,{children:[l.jsx("p",{className:"eyebrow eyebrow-soft",children:"Dashboard access"}),l.jsx("h1",{className:"font-medium tracking-tight text-primary",children:"Sign in to Canonry"})]}),l.jsxs(go,{children:[we?l.jsx("p",{className:"mb-4 rounded-md border border-caution bg-caution-soft px-3 py-2 text-sm text-caution",children:"You were signed out — please sign in again."}):null,l.jsxs("form",{className:"space-y-4",onSubmit:pn(_e),children:[l.jsxs("label",{className:"block space-y-1.5",htmlFor:"account-name",children:[l.jsx("span",{className:"text-xs font-medium text-secondary",children:"Name"}),l.jsx("input",{autoFocus:!0,id:"account-name",className:"w-full rounded-md border border-base bg-bg px-3 py-2 text-sm text-heading outline-none transition focus:border-mono-600",type:"text",name:"username",autoComplete:"username",value:j,onChange:Q=>{T(Q.target.value),ee(null)},"aria-invalid":!!Y,"aria-describedby":Y?"account-login-error":void 0})]}),l.jsxs("label",{className:"block space-y-1.5",htmlFor:"account-password",children:[l.jsx("span",{className:"text-xs font-medium text-secondary",children:"Password"}),l.jsx("input",{id:"account-password",className:"w-full rounded-md border border-base bg-bg px-3 py-2 text-sm text-heading outline-none transition focus:border-mono-600",type:"password",name:"password",autoComplete:"current-password",value:N,onChange:Q=>ne(Q.target.value),"aria-invalid":!!Y,"aria-describedby":Y?"account-login-error":void 0})]}),Y?l.jsx("p",{id:"account-login-error",role:"alert",className:"text-sm text-negative-400",children:Y}):null,l.jsx(ue,{type:"submit",disabled:B||!j.trim()||!N,children:B?"Signing in…":"Sign in"})]})]})]}):n==="setup"?l.jsxs(l.Fragment,{children:[l.jsxs(Nr,{children:[l.jsx("p",{className:"eyebrow eyebrow-soft",children:"First-time setup"}),l.jsx("h1",{className:"font-medium tracking-tight text-primary",children:"Create a dashboard password"}),l.jsx(Fd,{children:"This password protects the dashboard on this computer."})]}),l.jsx(go,{children:l.jsxs("form",{className:"space-y-4",onSubmit:pn(O),children:[l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("label",{className:"block text-xs font-medium text-secondary",htmlFor:"dashboard-password-new",children:"Password"}),l.jsx("input",{autoFocus:!0,id:"dashboard-password-new",className:"w-full rounded-md border border-base bg-bg px-3 py-2 text-sm text-heading outline-none transition focus:border-mono-600",type:H?"text":"password",name:"new-password",autoComplete:"new-password",minLength:8,required:!0,value:N,onChange:Q=>ne(Q.target.value),"aria-invalid":ve,"aria-describedby":"dashboard-password-new-help"}),l.jsx("span",{id:"dashboard-password-new-help","aria-live":"polite",className:ve?"block text-sm text-negative-400":"block text-sm text-secondary",children:ve?"Enter at least 8 characters.":"Use at least 8 characters."})]}),l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("label",{className:"block text-xs font-medium text-secondary",htmlFor:"dashboard-password-confirm",children:"Confirm password"}),l.jsx("input",{id:"dashboard-password-confirm",className:"w-full rounded-md border border-base bg-bg px-3 py-2 text-sm text-heading outline-none transition focus:border-mono-600",type:H?"text":"password",name:"confirm-password",autoComplete:"new-password",minLength:8,required:!0,value:E,onChange:Q=>ge(Q.target.value),"aria-invalid":le,"aria-describedby":"dashboard-password-confirm-help"}),l.jsx("span",{id:"dashboard-password-confirm-help","aria-live":"polite",className:le?"block text-sm text-negative-400":"block text-sm text-secondary",children:le?"Passwords do not match.":"Enter the same password again."})]}),l.jsxs("label",{className:"flex min-h-10 cursor-pointer items-center gap-2 text-sm text-secondary",htmlFor:"dashboard-password-show",children:[l.jsx("input",{id:"dashboard-password-show",type:"checkbox",checked:H,onChange:Q=>X(Q.target.checked)}),"Show passwords"]}),Y?l.jsx("p",{id:"dashboard-password-setup-error",role:"alert",className:"text-sm text-negative-400",children:Y}):null,l.jsx(ue,{type:"submit",disabled:B||!ce,children:B?"Creating password…":"Create password and continue"})]})})]}):l.jsxs(l.Fragment,{children:[l.jsxs(Nr,{children:[l.jsx("p",{className:"eyebrow eyebrow-soft",children:"Dashboard access"}),l.jsx("h1",{className:"font-medium tracking-tight text-primary",children:"Sign in to Canonry"}),l.jsx(Fd,{children:L==="api-key"?"Enter an API key from this Canonry install. This opens the dashboard with that key’s access and does not change the password.":"Enter your dashboard password to continue."})]}),l.jsxs(go,{children:[we?l.jsx("p",{className:"mb-4 rounded-md border border-caution bg-caution-soft px-3 py-2 text-sm text-caution",children:"Your session expired — please sign in again."}):null,l.jsxs("form",{className:"space-y-4",onSubmit:pn(Se),children:[l.jsxs("label",{className:"block space-y-1.5",htmlFor:"dashboard-password-current",children:[l.jsx("span",{className:"text-xs font-medium text-secondary",children:L==="api-key"?"Canonry API key":"Password"}),l.jsx("input",{autoFocus:!0,id:"dashboard-password-current",className:"w-full rounded-md border border-base bg-bg px-3 py-2 text-sm text-heading outline-none transition focus:border-mono-600",type:H?"text":"password",name:L==="api-key"?"apiKey":"password",autoComplete:L==="api-key"?"off":"current-password",spellCheck:!1,required:!0,value:N,onChange:Q=>ne(Q.target.value),"aria-invalid":!!Y,"aria-describedby":Y?"dashboard-password-login-error":void 0})]}),l.jsxs("label",{className:"flex min-h-10 cursor-pointer items-center gap-2 text-sm text-secondary",htmlFor:"dashboard-login-password-show",children:[l.jsx("input",{id:"dashboard-login-password-show",type:"checkbox",checked:H,onChange:Q=>X(Q.target.checked)}),L==="api-key"?"Show API key":"Show password"]}),Y?l.jsx("p",{id:"dashboard-password-login-error",role:"alert",className:"text-sm text-negative-400",children:Y}):null,l.jsx(ue,{type:"submit",disabled:B||!N.trim(),children:B?"Signing in…":"Open dashboard"}),l.jsx(ue,{type:"button",variant:"ghost",onClick:()=>ae(L==="api-key"?"password":"api-key"),children:L==="api-key"?"Use dashboard password instead":"Forgot password? Use API key"})]})]})]})})]})})}const $C=document.getElementById("root");if(!$C)throw new Error("Expected #root element for web app bootstrap.");T5.createRoot($C).render(l.jsx(C.StrictMode,{children:l.jsx(sW,{})}));export{Fae as $,xne as A,ue as B,Pd as C,vne as D,pa as E,EK as F,tse as G,nse as H,Ua as I,BF as J,IK as K,VW as L,Mie as M,$ne as N,Kne as O,Ute as P,Lne as Q,bt as R,Xie as S,bn as T,$ae as U,Kae as V,Gae as W,Jte as X,Xte as Y,lne as Z,wn as _,qie as a,cae as a$,Zae as a0,ane as a1,Yae as a2,ine as a3,ene as a4,nne as a5,Hae as a6,Qae as a7,Uae as a8,Wte as a9,ag as aA,Mne as aB,jd as aC,yie as aD,zi as aE,hg as aF,fo as aG,IF as aH,kK as aI,aae as aJ,LZ as aK,tne as aL,QW as aM,wj as aN,VP as aO,Zie as aP,Yie as aQ,LW as aR,Rte as aS,GI as aT,En as aU,mg as aV,BW as aW,dee as aX,MW as aY,GK as aZ,mH as a_,Xae as aa,iie as ab,eie as ac,nie as ad,tie as ae,aie as af,Cne as ag,r1 as ah,ze as ai,Wae as aj,nC as ak,Bi as al,Jae as am,bg as an,x9 as ao,w9 as ap,qW as aq,PW as ar,Tne as as,One as at,Pne as au,xn as av,qne as aw,Ite as ax,RK as ay,MQ as az,aee as b,bW as b$,hae as b0,uae as b1,Cee as b2,_ee as b3,K$ as b4,Tee as b5,tH as b6,lae as b7,Q$ as b8,eg as b9,kae as bA,Eae as bB,jae as bC,Iae as bD,Aae as bE,Oae as bF,_ae as bG,qae as bH,Lae as bI,xX as bJ,Cae as bK,pe as bL,DW as bM,RW as bN,EW as bO,TW as bP,CW as bQ,AW as bR,_W as bS,NW as bT,jW as bU,SW as bV,gW as bW,yW as bX,kW as bY,wW as bZ,xW as b_,Nee as ba,CG as bb,dae as bc,rae as bd,aH as be,mae as bf,Gie as bg,pae as bh,kie as bi,Sie as bj,sne as bk,s1 as bl,gie as bm,XA as bn,vae as bo,wae as bp,Tae as bq,Bae as br,Mae as bs,Nae as bt,Pae as bu,Vae as bv,Sae as bw,Rae as bx,Dae as by,zae as bz,gB as c,UW as c$,vW as c0,fW as c1,hW as c2,pW as c3,mW as c4,e6 as c5,uee as c6,pee as c7,ree as c8,hee as c9,Tte as cA,kee as cB,xee as cC,Oee as cD,tG as cE,Cte as cF,Nte as cG,Ate as cH,jte as cI,mte as cJ,dte as cK,cte as cL,ute as cM,wee as cN,rte as cO,ote as cP,Zee as cQ,Yee as cR,bee as cS,See as cT,Xee as cU,hte as cV,$W as cW,kte as cX,Ste as cY,bte as cZ,xte as c_,mee as ca,lee as cb,cee as cc,yee as cd,ise as ce,fie as cf,ng as cg,fee as ch,Ree as ci,Dee as cj,xo as ck,Eee as cl,gee as cm,gne as cn,Dt as co,m$ as cp,ate as cq,Ete as cr,Jee as cs,Wee as ct,ete as cu,tte as cv,nte as cw,oV as cx,see as cy,Ow as cz,Qie as d,Hd as d$,wte as d0,vte as d1,iee as d2,ite as d3,Uee as d4,Gee as d5,Kee as d6,Hee as d7,Qee as d8,Fee as d9,$ee as dA,Vte as dB,Lte as dC,Bte as dD,yne as dE,fH as dF,xae as dG,Fne as dH,HW as dI,Fw as dJ,Kte as dK,Hte as dL,Hne as dM,Qne as dN,Qte as dO,Fte as dP,Yte as dQ,Zte as dR,Uc as dS,Do as dT,qA as dU,Xne as dV,Yne as dW,jZ as dX,ug as dY,Kd as dZ,dg as d_,oG as da,_te as db,oee as dc,zW as dd,rV as de,qee as df,pte as dg,OW as dh,vee as di,zee as dj,Pee as dk,Iee as dl,GW as dm,fte as dn,gte as dp,yte as dq,Bee as dr,TA as ds,Mee as dt,Lee as du,KW as dv,Vee as dw,ste as dx,IW as dy,lte as dz,Jie as e,Gte as e$,Qd as e0,BZ as e1,FK as e2,yo as e3,Xd as e4,vH as e5,EX as e6,ase as e7,$ie as e8,qZ as e9,As as eA,UK as eB,QK as eC,$te as eD,sie as eE,JG as eF,pne as eG,rie as eH,lie as eI,cie as eJ,oie as eK,Une as eL,cne as eM,une as eN,dne as eO,hne as eP,mne as eQ,Lr as eR,_m as eS,ese as eT,Dm as eU,u1 as eV,yae as eW,bae as eX,EG as eY,Dte as eZ,zte as e_,Vie as ea,jX as eb,fae as ec,Jne as ed,Lie as ee,nae as ef,Wne as eg,gae as eh,Bie as ei,eae as ej,nn as ek,Iie as el,HZ as em,qG as en,qK as eo,QZ as ep,Uie as eq,Kie as er,Hie as es,Fie as et,ks as eu,Ote as ev,LG as ew,Pte as ex,qte as ey,Mte as ez,Xt as f,Rie as f$,one as f0,rne as f1,h1 as f2,zm as f3,d1 as f4,TX as f5,fne as f6,Vr as f7,Yw as f8,Nne as f9,sae as fA,YW as fB,Li as fC,Ia as fD,ZW as fE,AG as fF,mQ as fG,Aie as fH,jie as fI,AX as fJ,_ie as fK,UZ as fL,nee as fM,XW as fN,Oie as fO,Pie as fP,Cie as fQ,Nie as fR,FW as fS,Eie as fT,zie as fU,Tie as fV,Die as fW,jo as fX,n3 as fY,JW as fZ,tee as f_,Ene as fa,Dne as fb,zne as fc,_ne as fd,Rne as fe,Ine as ff,vf as fg,Ane as fh,xie as fi,rX as fj,Aee as fk,G0 as fl,Zne as fm,bie as fn,wie as fo,jne as fp,jee as fq,kne as fr,Sne as fs,wne as ft,vie as fu,Vne as fv,nI as fw,iae as fx,tae as fy,oae as fz,Wie as g,KM as g0,eee as g1,WW as g2,rk as h,r2 as i,Bne as j,uie as k,mie as l,_a as m,Ln as n,J as o,MA as p,Er as q,On as r,Gne as s,zK as t,m1 as u,pn as v,die as w,hie as x,pie as y,bne as z};