@zenovay/cli 1.0.23 → 1.0.24

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 (69) hide show
  1. package/dist/{agency-CXn6ghSg.js → agency-BNaZxwuI.js} +1 -1
  2. package/dist/{ai-BhP4sLv5.js → ai-TOnnAM-e.js} +1 -1
  3. package/dist/{alerts-DQhW7iBJ.js → alerts-pzUmtvMF.js} +1 -1
  4. package/dist/{analytical-screen-CwzTTWSN.js → analytical-screen-Z8oykSBJ.js} +1 -1
  5. package/dist/{analytics-B6LX4KtS.js → analytics-DnICaaM-.js} +2 -2
  6. package/dist/{annotation-BFjhrp0W.js → annotation-DSdNqyEC.js} +1 -1
  7. package/dist/{api-BjI2Fkpj.js → api-CBukwv2I.js} +1 -1
  8. package/dist/{api-keys-CcYmhFAn.js → api-keys-BrHTpsbc.js} +1 -1
  9. package/dist/{api-v2-C08aT2tD.js → api-v2--DPtrRGv.js} +1 -1
  10. package/dist/api-v2-sUR_nVdV.js +1 -0
  11. package/dist/{audit-ByQTzk4F.js → audit-CIg-teMg.js} +1 -1
  12. package/dist/bin.js +7 -7
  13. package/dist/{companies-DoWVWT3n.js → companies-DH1MOieW.js} +1 -1
  14. package/dist/{completions-BQZk2_z8.js → completions-DNEK2qom.js} +1 -1
  15. package/dist/{deploys-fslHuzcI.js → deploys-D261j_D-.js} +1 -1
  16. package/dist/{devices-DBlXlKpl.js → devices-BG4tGm29.js} +1 -1
  17. package/dist/{doctor-CUcGEDQ3.js → doctor-WAEVPtnG.js} +1 -1
  18. package/dist/{domains-C8k_-uxF.js → domains-DfLjgM3t.js} +1 -1
  19. package/dist/{error-codes-B34VS5kE.js → error-codes-Bw13FZCw.js} +1 -1
  20. package/dist/{error-codes-DBKSLU_H.js → error-codes-DZnI2JsI.js} +1 -1
  21. package/dist/{errors-D0ZAKyyp.js → errors-CTVbJ5V0.js} +1 -1
  22. package/dist/{events-tail-ChBWUY2U.js → events-tail-B0RxKP3U.js} +1 -1
  23. package/dist/{export-BNTMuFkm.js → export-CFfTX4on.js} +1 -1
  24. package/dist/{funnel-DUADVc08.js → funnel-DsMn91zW.js} +1 -1
  25. package/dist/{geo-BPJo25Kz.js → geo-BXurbfTm.js} +1 -1
  26. package/dist/{globe-BihtdD3C.js → globe-ka4CYfJg.js} +1 -1
  27. package/dist/{goals-DOrNec3J.js → goals-D3oPsLrm.js} +1 -1
  28. package/dist/{health-1qT1VvMd.js → health-BVyYaTGB.js} +1 -1
  29. package/dist/{health--A4ohPuM.js → health-DJweY04d.js} +1 -1
  30. package/dist/{heatmaps-B57AUVWd.js → heatmaps-BzMMPGn_.js} +1 -1
  31. package/dist/{home-cBUICiVc.js → home-BFzJXK-U.js} +1 -1
  32. package/dist/{init-DEjXba3A.js → init-4tQns4Ed.js} +1 -1
  33. package/dist/init-CvOszx8_.js +335 -0
  34. package/dist/{insights-1_6dityO.js → insights-DetIAtXK.js} +1 -1
  35. package/dist/{integrations-DnGjzmxX.js → integrations-BqwI6VNk.js} +1 -1
  36. package/dist/{journeys-cWX23e27.js → journeys-CI7lh9Bo.js} +1 -1
  37. package/dist/{live-CztLfKw_.js → live-DltW8mP8.js} +1 -1
  38. package/dist/login-BD9Q3e7S.js +1 -0
  39. package/dist/{login-B0HQYYBk.js → login-vzW-8q0w.js} +1 -1
  40. package/dist/{logout-D_z-o7Df.js → logout-CQUoX-t4.js} +1 -1
  41. package/dist/{notes-GM2yOOui.js → notes-zgu5aUgZ.js} +1 -1
  42. package/dist/{pages-C2cFd2kA.js → pages-CeZztbJL.js} +1 -1
  43. package/dist/{plans-CWVJxcHz.js → plans-C_j2XLQ4.js} +1 -1
  44. package/dist/{profile-Uqw7PTNA.js → profile-C-CyW8Bx.js} +1 -1
  45. package/dist/{projects-Bf_yPgg2.js → projects-7ifzwrtn.js} +1 -1
  46. package/dist/{query-BRI6jsCB.js → query-C3e5w05g.js} +1 -1
  47. package/dist/{retention-DiJO8tEO.js → retention-ByySsFfr.js} +1 -1
  48. package/dist/{revenue-BknSw-ON.js → revenue-CBgvMcDZ.js} +1 -1
  49. package/dist/{self-test-ZJq1IFy0.js → self-test-RTam3wnZ.js} +1 -1
  50. package/dist/{sessions-TMh968Eh.js → sessions-9dtqST89.js} +1 -1
  51. package/dist/{settings-BNtoRxL2.js → settings-BPBWCOOH.js} +1 -1
  52. package/dist/{share-BkAcPmBB.js → share-COuGNR8Q.js} +1 -1
  53. package/dist/{sources-Cc8KehCL.js → sources-DiH5acUP.js} +1 -1
  54. package/dist/{stats-CyQ30WQQ.js → stats-h_juyrDM.js} +1 -1
  55. package/dist/{status-agent-CCtrc_xJ.js → status-agent-Daz4qPSV.js} +1 -1
  56. package/dist/{team-BxIB_sx7.js → team-CtHhMm_t.js} +1 -1
  57. package/dist/{teams-C17B3ARm.js → teams-6x1xB5VJ.js} +1 -1
  58. package/dist/{uptime-Bi495745.js → uptime-42ArloS6.js} +1 -1
  59. package/dist/{usage-ET7C0T4C.js → usage-DeNyFk5w.js} +1 -1
  60. package/dist/{use-B9zOU23-.js → use-CuQ2Z9Aw.js} +1 -1
  61. package/dist/{visitors-BVZI0rsU.js → visitors-DMSB-LQP.js} +1 -1
  62. package/dist/{vitals-scWZhFJZ.js → vitals-Q7_u9sxq.js} +1 -1
  63. package/dist/{webhooks-6Gab0Im6.js → webhooks-B1eqAQXM.js} +1 -1
  64. package/dist/{webhooks-forward-CaSdkBXY.js → webhooks-forward-DfNBzOJ7.js} +1 -1
  65. package/dist/wizard-bin.js +1 -1
  66. package/package.json +1 -1
  67. package/dist/api-v2-D4BD6BTF.js +0 -1
  68. package/dist/init-fhEg3cPZ.js +0 -335
  69. package/dist/login-BJ5CNvdO.js +0 -1
@@ -1,2 +1,2 @@
1
- import{readConfig as e}from"./config-JVhBplSX.js";import"./api-BjI2Fkpj.js";import{readToken as t}from"./token-store-CuZEiQNg.js";import{ApiV2Client as n}from"./api-v2-C08aT2tD.js";import"./theme-DSRmbn9T.js";import{Banner as r,Panel as i,useTheme as a}from"./panel-DbiZwGB3.js";import"./progress-row-BSv_Zm8f.js";import"./prompt-Dae2nnYJ.js";import{Keybar as o}from"./keybar-BY1csJGI.js";import"./sparkline-B7VaYaxH.js";import{resolveSiteId as s}from"./resolve-site-D8PIddP1.js";import"./data-table-Bd1OPNrr.js";import"./bar-DjNjvYQO.js";import"./ui-aT7D3OhH.js";import{Box as c,Text as l,render as u,useApp as d,useInput as f}from"ink";import p,{useEffect as m,useState as h}from"react";function g(e,t){let n=Math.max(0,Math.round((t-e)/1e3));if(n<5)return`just now`;if(n<60)return`${n}s ago`;let r=Math.floor(n/60);return r<60?`${r}m ago`:`${Math.floor(r/60)}h ago`}async function _(e,t){let n=new TextEncoder,r=await crypto.subtle.importKey(`raw`,n.encode(e),{name:`HMAC`,hash:`SHA-256`},!1,[`sign`]),i=await crypto.subtle.sign(`HMAC`,r,n.encode(t));return Array.from(new Uint8Array(i),e=>e.toString(16).padStart(2,`0`)).join(``)}function v({label:e,value:t,valueColor:n}){let{theme:r}=a();return p.createElement(c,{flexDirection:`row`},p.createElement(c,{width:14},p.createElement(l,{color:r.dim},e.toUpperCase())),p.createElement(c,{flexGrow:1},p.createElement(l,{color:n??r.fg,wrap:`truncate`},t)))}function y({stats:e,target:t}){let{theme:n}=a();return p.createElement(i,{title:`webhooks forward`,state:e.connected?`ok`:`busy`},p.createElement(v,{label:`public url`,value:e.publicUrl,valueColor:n.accent}),p.createElement(v,{label:`forwarding to`,value:t}),p.createElement(c,{flexDirection:`row`,marginTop:1},e.connected?p.createElement(l,{color:n.success},`● connected`):p.createElement(l,{color:n.warn},`○ connecting…`),p.createElement(l,{color:n.muted},` · `,e.total,` requests · `),p.createElement(l,{color:n.success},e.ok,` ok`),p.createElement(l,{color:n.muted},` · `),p.createElement(l,{color:e.err>0?n.error:n.muted},e.err,` err`),e.lastStatus===null?null:p.createElement(l,{color:n.muted},` · last HTTP `,e.lastStatus)),e.lastError?p.createElement(c,{flexDirection:`row`},p.createElement(l,{color:n.error,wrap:`truncate`},`last error: `,e.lastError)):null)}async function b(i){let v=await e(),b=await t({strict:!1});if(!b?.accessToken)return process.stderr.write("Not authenticated. Run `zenovay login` first.\n"),2;if(!i.to)return process.stderr.write(`Missing --to <url> (e.g. --to localhost:3000/webhook).
1
+ import{readConfig as e}from"./config-JVhBplSX.js";import"./api-CBukwv2I.js";import{readToken as t}from"./token-store-CuZEiQNg.js";import{ApiV2Client as n}from"./api-v2--DPtrRGv.js";import"./theme-DSRmbn9T.js";import{Banner as r,Panel as i,useTheme as a}from"./panel-DbiZwGB3.js";import"./progress-row-BSv_Zm8f.js";import"./prompt-Dae2nnYJ.js";import{Keybar as o}from"./keybar-BY1csJGI.js";import"./sparkline-B7VaYaxH.js";import{resolveSiteId as s}from"./resolve-site-D8PIddP1.js";import"./data-table-Bd1OPNrr.js";import"./bar-DjNjvYQO.js";import"./ui-aT7D3OhH.js";import{Box as c,Text as l,render as u,useApp as d,useInput as f}from"ink";import p,{useEffect as m,useState as h}from"react";function g(e,t){let n=Math.max(0,Math.round((t-e)/1e3));if(n<5)return`just now`;if(n<60)return`${n}s ago`;let r=Math.floor(n/60);return r<60?`${r}m ago`:`${Math.floor(r/60)}h ago`}async function _(e,t){let n=new TextEncoder,r=await crypto.subtle.importKey(`raw`,n.encode(e),{name:`HMAC`,hash:`SHA-256`},!1,[`sign`]),i=await crypto.subtle.sign(`HMAC`,r,n.encode(t));return Array.from(new Uint8Array(i),e=>e.toString(16).padStart(2,`0`)).join(``)}function v({label:e,value:t,valueColor:n}){let{theme:r}=a();return p.createElement(c,{flexDirection:`row`},p.createElement(c,{width:14},p.createElement(l,{color:r.dim},e.toUpperCase())),p.createElement(c,{flexGrow:1},p.createElement(l,{color:n??r.fg,wrap:`truncate`},t)))}function y({stats:e,target:t}){let{theme:n}=a();return p.createElement(i,{title:`webhooks forward`,state:e.connected?`ok`:`busy`},p.createElement(v,{label:`public url`,value:e.publicUrl,valueColor:n.accent}),p.createElement(v,{label:`forwarding to`,value:t}),p.createElement(c,{flexDirection:`row`,marginTop:1},e.connected?p.createElement(l,{color:n.success},`● connected`):p.createElement(l,{color:n.warn},`○ connecting…`),p.createElement(l,{color:n.muted},` · `,e.total,` requests · `),p.createElement(l,{color:n.success},e.ok,` ok`),p.createElement(l,{color:n.muted},` · `),p.createElement(l,{color:e.err>0?n.error:n.muted},e.err,` err`),e.lastStatus===null?null:p.createElement(l,{color:n.muted},` · last HTTP `,e.lastStatus)),e.lastError?p.createElement(c,{flexDirection:`row`},p.createElement(l,{color:n.error,wrap:`truncate`},`last error: `,e.lastError)):null)}async function b(i){let v=await e(),b=await t({strict:!1});if(!b?.accessToken)return process.stderr.write("Not authenticated. Run `zenovay login` first.\n"),2;if(!i.to)return process.stderr.write(`Missing --to <url> (e.g. --to localhost:3000/webhook).
2
2
  `),2;let x=i.to.match(/^https?:\/\//)?i.to:`http://${i.to}`,S=new n({config:v,cliVersion:i.cliVersion,token:b}),C,w;try{({siteId:C,site:w}=await s(S,{explicit:i.siteId,headless:!1,cliVersion:i.cliVersion}))}catch(e){return process.stderr.write(`${e.message}\n`),2}let T=w?.url?w.url.replace(/^https?:\/\//,``).replace(/\/$/,``):w?.name??C,E;try{E=await S.createTunnel(C,i.to)}catch(e){return process.stderr.write(`Failed to register tunnel: ${e.message}\n`),1}let D=i.sign?i.secret??E.tunnelKey:null,O=()=>{let{theme:e}=a(),{exit:t}=d(),[n,s]=h({total:0,ok:0,err:0,lastStatus:null,lastError:null,lastForwardedAt:null,publicUrl:E.publicUrl,wsUrl:E.wsUrl,connected:!1}),[u,v]=h(()=>Date.now());m(()=>{let e=setInterval(()=>v(Date.now()),5e3);return()=>clearInterval(e)},[]),f((e,n)=>{(e===`q`||n.escape)&&t()}),m(()=>{let e=new AbortController,t=async e=>{try{let t={...e.headers};delete t.host,delete t[`content-length`],D&&(t[`X-Zenovay-Signature`]=`sha256=${await _(D,e.body)}`);let n=await fetch(x,{method:e.method,headers:t,body:e.method===`GET`||e.method===`HEAD`?void 0:e.body}),r=await n.text(),i={};return n.headers.forEach((e,t)=>{i[t]=e}),s(e=>({...e,total:e.total+1,ok:e.ok+(n.ok?1:0),err:e.err+(n.ok?0:1),lastStatus:n.status,lastError:n.ok?null:`HTTP ${n.status}`,lastForwardedAt:Date.now()})),{status:n.status,headers:i,body:r}}catch(e){let t=e instanceof Error?e.message:String(e);return s(e=>({...e,total:e.total+1,err:e.err+1,lastError:t,lastForwardedAt:Date.now()})),{status:502,body:JSON.stringify({error:`cli_local_failed`,detail:t})}}};return(async()=>{let n=S.tunnelClient(E.wsUrl);s(e=>({...e,connected:!0}));try{await n.start(t,e.signal)}catch(e){s(t=>({...t,connected:!1,lastError:e.message}))}})(),()=>{e.abort()}},[]);let b=n.lastForwardedAt===null?n.connected?`↻ live · waiting for first webhook`:`↻ connecting…`:`↻ last forward ${g(n.lastForwardedAt,u)}`;return p.createElement(c,{flexDirection:`column`},p.createElement(r,{version:i.cliVersion,subtitle:`webhooks forward · ${T} · ${n.connected?`live`:`connecting`}`,live:n.connected}),p.createElement(y,{stats:n,target:`${x}${i.sign?` · HMAC-signed`:``}`}),p.createElement(c,{marginTop:1},p.createElement(l,{color:e.dim},b)),p.createElement(o,{items:[{key:`q`,label:`quit`},{key:`esc`,label:`quit`}]}))},{waitUntilExit:k}=u(p.createElement(O,null));return await k(),0}export{b as webhooksForwardCommand};
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import(`./init-DEjXba3A.js`).then(async({initCommand:e})=>{let{readFileSync:t}=await import(`node:fs`),n=await import(`node:path`),{fileURLToPath:r}=await import(`node:url`),i=n.dirname(r(import.meta.url)),a=JSON.parse(t(n.join(i,`..`,`package.json`),`utf8`)),o=process.argv.slice(2),s=o.includes(`--json`),c=o.includes(`--yes`),l=o.includes(`--skip-mcp`),u=o.includes(`--skip-verify`),d=await e({cliVersion:a.version,cwd:process.cwd(),json:s,yes:c,skipMcp:l,skipVerify:u});process.exit(d)});
2
+ import(`./init-4tQns4Ed.js`).then(async({initCommand:e})=>{let{readFileSync:t}=await import(`node:fs`),n=await import(`node:path`),{fileURLToPath:r}=await import(`node:url`),i=n.dirname(r(import.meta.url)),a=JSON.parse(t(n.join(i,`..`,`package.json`),`utf8`)),o=process.argv.slice(2),s=o.includes(`--json`),c=o.includes(`--yes`),l=o.includes(`--skip-mcp`),u=o.includes(`--skip-verify`),d=await e({cliVersion:a.version,cwd:process.cwd(),json:s,yes:c,skipMcp:l,skipVerify:u});process.exit(d)});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zenovay/cli",
3
- "version": "1.0.23",
3
+ "version": "1.0.24",
4
4
  "description": "Zenovay CLI — AI install wizard + full terminal analytics dashboard",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1 +0,0 @@
1
- import"./config-JVhBplSX.js";import{ApiError as e}from"./api-BjI2Fkpj.js";import"./token-store-CuZEiQNg.js";import{ApiV2Client as t}from"./api-v2-C08aT2tD.js";export{t as ApiV2Client};
@@ -1,335 +0,0 @@
1
- import{readConfig as e,updateConfig as t}from"./config-JVhBplSX.js";import{ApiClient as n,dashboardUrlForSite as r}from"./api-BjI2Fkpj.js";import{readToken as i}from"./token-store-CuZEiQNg.js";import{diagnoseInstall as a}from"./detect-installed-DpSaAeH-.js";import{emit$1 as o,isHeadless as s}from"./emit-5vELQfsB.js";import{openInBrowser as c}from"./open-url-IjqD5f_n.js";import{scrubSecrets as l}from"./secrets-zGZxXoM0.js";import{parseSseStream as u}from"./client-DNMRt-Hq.js";import{swapToFirstPartySnippet as d}from"./snippet-CwowVrmh.js";import{loginCommand as f,maybeInstallCompletions as p}from"./login-B0HQYYBk.js";import{Banner as m,Panel as h,useTheme as g}from"./panel-DbiZwGB3.js";import{DiffView as _,ProgressRow as v}from"./progress-row-BSv_Zm8f.js";import{Select as y}from"./prompt-Dae2nnYJ.js";import{Keybar as b}from"./keybar-BY1csJGI.js";import{spark as x}from"./sparkline-B7VaYaxH.js";import{execFile as S}from"node:child_process";import C from"node:path";import{promises as w}from"node:fs";import{z as T}from"zod";import E from"node:os";import D from"node:crypto";import{ulid as O}from"ulid";import{Box as k,Text as A,render as ee,useApp as te,useInput as j}from"ink";import M from"node:fs/promises";import N,{useEffect as P,useRef as F,useState as I}from"react";import{globby as ne}from"globby";import L from"ink-spinner";import{applyPatch as re}from"diff";import{promisify as ie}from"node:util";const ae=[/^(src\/)?app\/(.*\/)?layout\.(tsx|ts|jsx|js)$/,/^(src\/)?app\/root\.(tsx|ts|jsx|js)$/,/^(src\/)?pages\/(_app|_document)\.(tsx|ts|jsx|js)$/,/^src\/layouts\/.*\.(astro|svelte|vue)$/,/^src\/pages\/index\.astro$/,/^(src\/)?components\/.*\.(astro|svelte|vue|tsx|jsx|ts|js)$/,/^src\/routes\/\+layout\.(svelte|ts|js)$/,/^src\/routes\/root\..*$/,/^src\/(root|entry-server|entry-client)\.(tsx|ts|jsx|js)$/,/^src\/main\.(tsx|ts|jsx|js)$/,/^src\/App\.(tsx|ts|jsx|js|svelte|vue)$/,/^gatsby-(ssr|browser|config)\.(js|ts|mjs)$/,/^(next|nuxt|vite|astro|remix|svelte|tailwind|postcss)\.config\.(ts|mts|cts|js|mjs|cjs)$/,/^plugins\/.*\.(ts|js)$/,/^index\.html?$/,/^src\/index\.html?$/],oe=[/(^|\/)\.env($|\.(?!example$)[^/]+$)/,/(^|\/)\.git(\/|$)/,/(^|\/)node_modules\//,/(^|\/)\.ssh\//,/(^|\/)\.aws\//,/\.pem$/,/\.key$/,/(^|\/)id_rsa($|\.)/,/(^|\/)\.npmrc$/,/(^|\/)credentials(\.|$)/],R=256*1024,se=20,z=20,ce=20;var B=class extends Error{constructor(e,t){super(t),this.code=e,this.name=`SandboxError`}};const le=/<script[^>]*src\s*=\s*["'](?:https:\/\/(?:api|cdn)\.zenovay\.com\/[^"']+|[^"']*\/_z\/script\.js[^"']*)["'][^>]*>\s*<\/script>/i,ue=[{name:`PostHog`,re:/posthog\.com\b|posthog-js|window\.posthog/i},{name:`Plausible`,re:/plausible\.io\/js|window\.plausible/i},{name:`Google Analytics`,re:/googletagmanager\.com\/gtag\/js|google-analytics\.com\/analytics\.js|window\.gtag\b/i},{name:`Mixpanel`,re:/cdn\.mxpnl\.com|mixpanel-browser/i},{name:`Segment`,re:/cdn\.segment\.com\/analytics\.js|window\.analytics\b/i},{name:`Hotjar`,re:/static\.hotjar\.com|\(h,o,t,j,a,r\)/i},{name:`Amplitude`,re:/cdn\.amplitude\.com|amplitude\.getInstance/i},{name:`Heap`,re:/cdn\.heapanalytics\.com/i},{name:`FullStory`,re:/fullstory\.com\/s\/fs\.js|window\.FS\.identify/i}];var V=class{sessionId;cwd;cwdReal;undoRoot;readCount=0;writeCount=0;roundCount=0;writtenPathsSet=new Set;prunedOnce=!1;journaledPaths=new Map;constructor(e){this.sessionId=e.sessionId??O(),this.cwd=e.cwd,this.cwdReal=w.realpath(e.cwd),this.undoRoot=e.undoRoot??C.join(E.homedir(),`.zenovay`,`undo`)}incrementRound(){if(this.roundCount++,this.roundCount>ce)throw new B(`round-cap`,`Tool-call recursion cap (${ce}) exceeded.`)}stats(){return{sessionId:this.sessionId,reads:this.readCount,writes:this.writeCount,rounds:this.roundCount,writtenPaths:[...this.writtenPathsSet]}}async resolveForRead(e){return this.resolveSafe(e,`read`)}async resolveForWrite(e){return this.resolveSafe(e,`write`)}async journalTrustedWrite(e){if(typeof e!=`string`||e.length===0||e.includes(`\0`))throw new B(`escape`,`Journal path must be a non-empty string without null bytes.`);let t=await this.cwdReal,n=C.resolve(t,e),r=[],i=n,a=null;for(;a===null;)try{let e=await w.realpath(i);a=C.join(e,...r.reverse())}catch(t){if(t.code!==`ENOENT`)throw new B(`escape`,`realpath failed: ${t.message}`);try{let t=await w.lstat(i);if(t.isSymbolicLink())throw new B(`escape`,`Unresolved symlink in journal path: ${e}`)}catch(e){if(e instanceof B)throw e;if(e.code!==`ENOENT`)throw new B(`escape`,`lstat failed: ${e.message}`)}let n=C.dirname(i);if(n===i)throw new B(`escape`,`Could not resolve journal path: ${e}`);r.push(C.basename(i)),i=n}if(!this.isWithin(a,t))throw new B(`escape`,`Path escapes cwd: ${e}`);await this.journalBackup(a)}async resolveSafe(e,t){if(typeof e!=`string`||e.length===0)throw new B(`escape`,`Path must be a non-empty string.`);if(e.includes(`\0`))throw new B(`escape`,`Null byte in path.`);if(/^\\\\[?.]\\/.test(e)||/^\\\\[A-Za-z0-9]/.test(e))throw new B(`escape`,`Windows special path prefix: ${e}`);if(/%/.test(e))try{let t=decodeURIComponent(e);if(/%[0-9A-Fa-f]{2}/.test(t))throw new B(`escape`,`Double-encoded path: ${e}`);e=t}catch(t){throw t instanceof B?t:new B(`escape`,`Malformed percent-encoding: ${e}`)}if(e.includes(`\0`))throw new B(`escape`,`Null byte in decoded path.`);if(e.includes(`\\`))throw new B(`escape`,`Backslash in path (Windows-style separator not accepted): ${e}`);let n=await this.cwdReal,r=C.isAbsolute(e)?e:C.join(n,e),i=C.normalize(r),a=i;try{a=await w.realpath(i)}catch(e){if(e.code!==`ENOENT`)throw new B(`escape`,`realpath failed: ${e.message}`);let t=C.dirname(i);try{let e=await w.realpath(t);a=C.join(e,C.basename(i))}catch{}}if(!this.isWithin(a,n))throw new B(`escape`,`Path escapes cwd: ${e}`);let o=C.relative(n,a),s=o.toLowerCase();for(let e of oe)if(e.test(o)||e.test(s)){if(t===`read`&&/(^|\/)node_modules\//i.test(o))continue;throw new B(`blocklisted`,`Path is on the hard blocklist: ${o}`)}if(t===`write`){let e=ae.some(e=>e.test(o));if(!e&&!/^\.env(\.local)?$/.test(o)&&!/^\.claude\//.test(o)&&!/^\.cursor\//.test(o))throw new B(`not-allowlisted`,`Write path not on allowlist: ${o}`)}return a}isWithin(e,t){let n=C.relative(t,e);return!n.startsWith(`..`)&&!C.isAbsolute(n)}async safeRead(e){if(this.readCount>=se)throw new B(`read-cap`,`Read cap (${se}) reached.`);let t=await this.resolveForRead(e),n=await w.stat(t);if(n.size>R)throw new B(`too-large`,`File exceeds ${R}B: ${e} (${n.size}B)`);let r=await w.readFile(t),i=r.subarray(0,Math.min(r.length,8192));if(i.includes(0))throw new B(`binary-rejected`,`Binary content in ${e}.`);return this.readCount++,r.toString(`utf8`)}async safeWrite(e,t){if(this.writeCount>=z)throw new B(`write-cap`,`Write cap (${z}) reached.`);if(t.length>R)throw new B(`too-large`,`Write exceeds ${R}B: ${e}`);let n=await this.resolveForWrite(e),r=await w.readFile(n,`utf8`).catch(e=>{if(e.code===`ENOENT`)return null;throw e});if(r!==null){if(le.test(r)&&!le.test(t))throw new B(`destructive-tracker-removal`,`Refusing to write ${e}: existing Zenovay tracker tag would be removed. If you want to change the data-id, use patch_file to swap the attribute value instead of overwriting the file.`);for(let{name:n,re:i}of ue)if(i.test(r)&&!i.test(t))throw new B(`destructive-competitor-removal`,`Refusing to write ${e}: existing ${n} tracker would be removed. Zenovay installs alongside competitors — never replace them.`)}let i=await this.journalBackup(n);await w.mkdir(C.dirname(n),{recursive:!0}),await w.writeFile(n,t,`utf8`),this.writeCount++;let a=await this.cwdReal;return this.writtenPathsSet.add(C.relative(a,n)),{backupPath:i}}async journalBackup(e){if(this.journaledPaths.has(e))return this.journaledPaths.get(e)??null;let t=await w.readFile(e).catch(e=>{if(e.code===`ENOENT`)return null;throw e}),n=C.join(this.undoRoot,this.sessionId);await w.mkdir(n,{recursive:!0,mode:448}),this.prunedOnce||(this.prunedOnce=!0,me(this.undoRoot,this.sessionId));let r=D.createHash(`sha256`).update(e).digest(`hex`).slice(0,16),i=C.join(n,`${r}.bak`),a=C.join(n,`manifest.jsonl`);t!==null&&await w.writeFile(i,t,{mode:384});let o=t===null?null:i,s=JSON.stringify({abs:e,backupPath:o,ts:Date.now()});return await w.appendFile(a,s+`
2
- `,{mode:384}),this.journaledPaths.set(e,o),o}static wrapForModel(e,t){let n=D.createHash(`sha256`).update(t).digest(`hex`).slice(0,16),r=t.replaceAll(`&`,`&amp;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`);return`<FILE path="${e}" sha256="${n}">\n${r}\n</FILE>`}static scrubSecrets(e){return l(e)}};const de=20;function H(e,t){let n=C.relative(t,e);return n===``||!n.startsWith(`..`)&&!C.isAbsolute(n)}function fe(e){if(!/^[A-Za-z0-9_-]+$/.test(e))throw new B(`escape`,`Invalid undo session id.`)}async function U(e,t){fe(e);let n=await w.realpath(t),r=await w.realpath(C.join(n,e));if(!H(r,n))throw new B(`escape`,`Undo session escapes the undo root.`);let i=await w.realpath(C.join(r,`manifest.jsonl`));if(!H(i,r))throw new B(`escape`,`Undo manifest escapes its session directory.`);let a=await w.readFile(i,`utf8`),o=a.split(`
3
- `).filter(e=>e.trim().length>0).map(e=>{let t=JSON.parse(e);if(typeof t.abs!=`string`||!C.isAbsolute(t.abs)||t.backupPath!==null&&typeof t.backupPath!=`string`)throw new B(`escape`,`Undo manifest contains an invalid path entry.`);return{abs:C.resolve(t.abs),backupPath:t.backupPath}});return{entries:o,sessionDir:r}}async function W(e,t){let n=e,r=[];for(;;)try{let i=await w.realpath(n),a=C.join(i,...r.reverse());if(!H(a,t))throw new B(`escape`,`Undo target escapes the current project: ${e}`);return a}catch(t){if(t instanceof B||t.code!==`ENOENT`)throw t;let i=C.dirname(n);if(i===n)throw new B(`escape`,`Could not resolve undo target: ${e}`);r.push(C.basename(n)),n=i}}async function pe(e,t,n){let r=n?.undoRoot??C.join(E.homedir(),`.zenovay`,`undo`),i=await w.realpath(t),{entries:a}=await U(e,r);return a.length>0&&a.every(e=>H(e.abs,i))}async function me(e,t,n=de){try{let r=await w.readdir(e,{withFileTypes:!0}),i=r.filter(e=>e.isDirectory()).map(e=>e.name);if(i.length<=n)return 0;let a=await Promise.all(i.map(async t=>{let n=await w.stat(C.join(e,t)).catch(()=>null);return{name:t,mtime:n?n.mtimeMs:0}}));a.sort((e,t)=>t.mtime-e.mtime);let o=a.slice(n).filter(e=>e.name!==t);return await Promise.all(o.map(t=>w.rm(C.join(e,t.name),{recursive:!0,force:!0}).catch(()=>{}))),o.length}catch{return 0}}async function he(e,t){let n=t?.undoRoot??C.join(E.homedir(),`.zenovay`,`undo`),r,i;try{({entries:r,sessionDir:i}=await U(e,n))}catch(e){if(e.code===`ENOENT`)return{restored:0};throw e}let a=t?.cwd?await w.realpath(t.cwd):null,o=new Set,s=0;for(let e of r.reverse()){if(o.has(e.abs))continue;o.add(e.abs);let t=a?await W(e.abs,a):e.abs;if(e.backupPath===null)await w.unlink(t).catch(()=>void 0),s++;else{let n=await w.realpath(e.backupPath);if(!H(n,i))throw new B(`escape`,`Undo backup escapes its session directory.`);let r=await w.readFile(n);await w.writeFile(t,r),s++}}return{restored:s}}async function G(e){let t=await e.readFile(`package.json`),n=!1;if(t)try{let e=JSON.parse(t);n=!!(e.dependencies?.[`@angular/core`]??e.devDependencies?.[`@angular/core`])}catch{}let r=await e.exists(`angular.json`)||await e.exists(`.angular-cli.json`);if(n||r){let t=await e.exists(`src/index.html`)?`src/index.html`:`index.html`;return{matched:!0,confidence:.9,reason:`Detected Angular via ${n?"`@angular/core`":"`angular.json`"} (shell: ${t}).`}}return{matched:!1,confidence:0,reason:`No Angular dependency or angular.json found.`}}function ge(e){let t=e.trackingCode??e.siteId??``,n=e.targetPath||`src/index.html`,r=`<script defer\n data-id="${t}"\n src="https://api.zenovay.com/z.js">\n</script>`;return[{targetPath:n,anchorKind:`head-tag`,code:r,description:`Inject the Zenovay tracker inside <head> of the Angular index.html shell.`}]}const _e={id:`angular`,displayName:`Angular`,detect:G,files:[{path:`src/index.html`,kind:`mutate`,required:!0}],envVarName:`NG_ZENOVAY_SITE`,buildSnippets:ge},ve=[`astro.config.ts`,`astro.config.mjs`,`astro.config.js`];async function ye(e){for(let t of ve)if(await e.exists(t))return{matched:!0,confidence:.95,reason:`Detected Astro via \`${t}\`.`};let t=await e.readFile(`package.json`);if(t)try{let e=JSON.parse(t);if(e.dependencies?.astro??e.devDependencies?.astro)return{matched:!0,confidence:.8,reason:"Detected Astro via `astro` dependency."}}catch{}return{matched:!1,confidence:0,reason:"No astro.config.* or `astro` dependency found."}}function be(e){let t=e.trackingCode??e.siteId??``,n=`<script defer data-id="${t}" src="https://api.zenovay.com/z.js" is:inline></script>`;return[{targetPath:`src/layouts/Layout.astro`,anchorKind:`head-tag`,code:n,description:`Inject the Zenovay tracker inside <head> of the primary layout.`},{targetPath:`src/layouts/BaseHead.astro`,anchorKind:`head-tag`,code:n,description:"Fallback target when the project uses a dedicated `BaseHead.astro`."},{targetPath:`src/pages/index.astro`,anchorKind:`head-tag`,code:n,description:"Fallback for layout-less projects (e.g. the official `create-astro --template minimal` starter keeps the document <head> inline in src/pages/index.astro)."}]}const K={id:`astro`,displayName:`Astro`,detect:ye,files:[{path:`src/layouts/Layout.astro`,kind:`mutate`,required:!1},{path:`src/layouts/BaseHead.astro`,kind:`mutate`,required:!1},{path:`.env`,kind:`create`,required:!0}],envVarName:`PUBLIC_ZENOVAY_SITE`,buildSnippets:be};async function xe(e){let t=await e.readFile(`package.json`);if(t)try{let e=JSON.parse(t);if(e.dependencies?.gatsby??e.devDependencies?.gatsby)return!0}catch{}return await e.exists(`gatsby-config.js`)||await e.exists(`gatsby-config.ts`)}async function Se(e){return await xe(e)?{matched:!0,confidence:.95,reason:"Detected Gatsby via `gatsby` dependency / `gatsby-config`."}:{matched:!1,confidence:0,reason:`No Gatsby dependency or config found.`}}function q(e){let t=e.trackingCode??e.siteId??``,n=`const React = require('react');
4
-
5
- exports.onRenderBody = ({ setHeadComponents }) => {
6
- setHeadComponents([
7
- React.createElement('script', {
8
- key: 'zenovay-tracker',
9
- defer: true,
10
- 'data-id': '${t}',
11
- src: 'https://api.zenovay.com/z.js',
12
- }),
13
- ]);
14
- };
15
- `;return[{targetPath:`gatsby-ssr.js`,anchorKind:`replace-file`,code:n,description:`Add the Zenovay tracker via Gatsby SSR onRenderBody → setHeadComponents.`}]}const Ce={id:`gatsby`,displayName:`Gatsby`,detect:Se,files:[{path:`gatsby-ssr.js`,kind:`create`,required:!0}],envVarName:`GATSBY_ZENOVAY_SITE`,buildSnippets:q},we=[`app/layout.tsx`,`app/layout.ts`,`app/layout.jsx`,`app/layout.js`,`src/app/layout.tsx`,`src/app/layout.ts`,`src/app/layout.jsx`,`src/app/layout.js`];async function Te(e){for(let t of we)if(await e.exists(t))return t;return null}async function Ee(e){let t=await e.readFile(`package.json`);if(!t)return!1;try{let e=JSON.parse(t);return!!(e.dependencies?.next??e.devDependencies?.next)}catch{return!1}}async function De(e){let t=await Ee(e),n=await e.exists(`app`)||await e.exists(`src/app`),r=await Te(e);return t?n?r?{matched:!0,confidence:.95,reason:`Detected Next.js App Router via \`next\` dep + \`${r}\`.`}:{matched:!1,confidence:.4,reason:"Found `app/` but no root layout file (layout.tsx/ts/jsx/js)."}:{matched:!1,confidence:0,reason:"No `app/` directory found — not an App Router project."}:{matched:!1,confidence:0,reason:"package.json does not list `next` as a dependency."}}function Oe(e,t=`script`){let n=e.targetPath||`app/layout.tsx`,r=e.trackingCode??e.siteId??``;return t===`npm`?Ae(n,r):ke(n,r)}function ke(e,t){return[{targetPath:e,anchorKind:`after-imports`,code:`import Script from 'next/script';`,description:`Import next/script to inject the Zenovay tracker.`},{targetPath:e,anchorKind:`wrap-children`,code:`<Script
16
- defer
17
- data-id="${t}"
18
- src="https://api.zenovay.com/z.js"
19
- strategy="afterInteractive"
20
- />
21
- {children}`,description:`Add the Zenovay tracker <Script> next to children in the root layout.`}]}function Ae(e,t){return[{targetPath:`components/zenovay-bootstrap.tsx`,anchorKind:`replace-file`,code:`'use client';
22
-
23
- import { useEffect } from 'react';
24
- import { init } from '@zenovay/tracker';
25
-
26
- /**
27
- * Mounts the Zenovay tracker exactly once on the client. Equivalent to the
28
- * canonical <script src="https://api.zenovay.com/z.js"> tag — init() injects
29
- * the same loader internally.
30
- */
31
- export function ZenovayBootstrap() {
32
- useEffect(() => {
33
- init(${JSON.stringify(t)});
34
- }, []);
35
- return null;
36
- }
37
- `,description:`Create a client-component bootstrap that calls init() from @zenovay/tracker.`},{targetPath:e,anchorKind:`after-imports`,code:`import { ZenovayBootstrap } from '@/components/zenovay-bootstrap';`,description:`Import the Zenovay tracker bootstrap into the root layout.`},{targetPath:e,anchorKind:`wrap-children`,code:`<ZenovayBootstrap />
38
- {children}`,description:`Render the Zenovay tracker bootstrap alongside children in the root layout.`}]}const je={id:`next-app-router`,displayName:`Next.js (App Router)`,detect:De,files:[{path:`app/layout.tsx`,kind:`mutate`,required:!0}],envVarName:`NEXT_PUBLIC_ZENOVAY_SITE`,packageDeps:[`@zenovay/tracker`],supportsNpmMode:!0,buildSnippets:Oe},Me=[`pages/_app.tsx`,`pages/_app.ts`,`pages/_app.jsx`,`pages/_app.js`,`src/pages/_app.tsx`,`src/pages/_app.ts`,`src/pages/_app.jsx`,`src/pages/_app.js`];async function Ne(e){for(let t of Me)if(await e.exists(t))return t;return null}async function Pe(e){let t=await e.readFile(`package.json`);if(!t)return!1;try{let e=JSON.parse(t);return!!(e.dependencies?.next??e.devDependencies?.next)}catch{return!1}}async function Fe(e){let t=await Pe(e);if(!t)return{matched:!1,confidence:0,reason:"package.json does not list `next` as a dependency."};let n=await Ne(e);if(n)return{matched:!0,confidence:.9,reason:`Detected Next.js Pages Router via \`${n}\`.`};let r=await e.exists(`app`),i=await e.glob(`pages/**/*.{tsx,ts,jsx,js}`);return i.length>0&&!r?{matched:!0,confidence:.7,reason:"Found `pages/` directory with route files but no `_app` — will create one."}:{matched:!1,confidence:.2,reason:`Next.js detected, but no pages-router entry point found.`}}function Ie(e){let t=`pages/_app.tsx`,n=e.trackingCode??e.siteId??``,r=`import type { AppProps } from 'next/app';
39
- import Script from 'next/script';
40
-
41
- export default function App({ Component, pageProps }: AppProps) {
42
- return (
43
- <>
44
- <Script
45
- defer
46
- data-id="${n}"
47
- src="https://api.zenovay.com/z.js"
48
- strategy="afterInteractive"
49
- />
50
- <Component {...pageProps} />
51
- </>
52
- );
53
- }
54
- `;return[{targetPath:t,anchorKind:`after-imports`,code:`import Script from 'next/script';`,description:"Import next/script in `_app`."},{targetPath:t,anchorKind:`wrap-children`,code:`<><Script defer data-id="${n}" src="https://api.zenovay.com/z.js" strategy="afterInteractive" /><Component {...pageProps} /></>`,description:`Render the Zenovay tracker alongside the page component.`},{targetPath:t,anchorKind:`replace-file`,code:r,description:"Full replacement when `_app` does not exist yet."}]}const Le={id:`next-pages-router`,displayName:`Next.js (Pages Router)`,detect:Fe,files:[{path:`pages/_app.tsx`,kind:`mutate`,required:!0}],envVarName:`NEXT_PUBLIC_ZENOVAY_SITE`,buildSnippets:Ie},Re=T.object({modules:T.array(T.string()).optional(),runtimeConfig:T.object({public:T.record(T.string(),T.unknown()).optional()}).optional()}).passthrough();async function ze(e){let t=await e.readFile(`package.json`);if(!t)return{matched:!1,confidence:0,reason:`No package.json found.`};try{let e=JSON.parse(t),n=!!(e.dependencies?.nuxt??e.devDependencies?.nuxt??e.dependencies?.nuxt3??e.devDependencies?.nuxt3);if(n)return{matched:!0,confidence:.95,reason:"Detected Nuxt via `nuxt` / `nuxt3` dependency."}}catch{}let n=await e.exists(`nuxt.config.ts`)||await e.exists(`nuxt.config.js`)||await e.exists(`nuxt.config.mjs`);return n?{matched:!0,confidence:.6,reason:"Found `nuxt.config.*` but no explicit dependency listing."}:{matched:!1,confidence:0,reason:`No Nuxt dependency or config detected.`}}function Be(e){let t=e.trackingCode??e.siteId??``,n=` app: {
55
- head: {
56
- script: [
57
- {
58
- defer: true,
59
- src: 'https://api.zenovay.com/z.js',
60
- 'data-id': '${t}',
61
- },
62
- ],
63
- },
64
- },`;return[{targetPath:`nuxt.config.ts`,anchorKind:`head-tag`,code:n,description:"Add the Zenovay tracker to Nuxt's `app.head.script` so every page loads it."}]}const Ve={id:`nuxt`,displayName:`Nuxt`,detect:ze,files:[{path:`nuxt.config.ts`,kind:`mutate`,required:!0}],envVarName:`NUXT_PUBLIC_ZENOVAY_SITE`,buildSnippets:Be},He=[`index.html`,`public/index.html`,`dist/index.html`];async function Ue(e){for(let t of He)if(await e.exists(t))return{matched:!0,confidence:.5,reason:`Detected plain HTML project via \`${t}\`.`};let t=await e.glob(`**/*.html`);return t.length>0?{matched:!0,confidence:.3,reason:`Found ${t.length} HTML file(s); plain-HTML adapter is usable as fallback.`}:{matched:!1,confidence:0,reason:`No HTML files found in the project.`}}function We(e){let t=e.trackingCode??e.siteId??``,n=`<script defer\n data-id="${t}"\n src="https://api.zenovay.com/z.js">\n</script>`;return[{targetPath:`index.html`,anchorKind:`head-tag`,code:n,description:`Inject the Zenovay tracker inside <head>. Repeat for every HTML file that contains a <head>.`}]}const Ge={id:`plain-html`,displayName:`Plain HTML`,detect:Ue,files:[{path:`index.html`,kind:`mutate`,required:!0}],envVarName:`PUBLIC_ZENOVAY_SITE`,buildSnippets:We};async function Ke(e){let t=await e.readFile(`package.json`);if(!t)return{matched:!1,confidence:0,reason:`No package.json.`};try{let e=JSON.parse(t),n={...e.dependencies??{},...e.devDependencies??{}};if(n[`@builder.io/qwik-city`]??n[`@builder.io/qwik`])return{matched:!0,confidence:.92,reason:"Detected Qwik via `@builder.io/qwik(-city)`."}}catch{}return{matched:!1,confidence:0,reason:`No Qwik dependency found.`}}function qe(e){let t=e.trackingCode??e.siteId??``,n=e.targetPath||`src/root.tsx`,r=`<script
65
- defer
66
- data-id="${t}"
67
- src="https://api.zenovay.com/z.js"
68
- />`;return[{targetPath:n,anchorKind:`head-tag`,code:r,description:`Add the Zenovay tracker into the <head> of the Qwik root document.`}]}const Je={id:`qwik`,displayName:`Qwik`,detect:Ke,files:[{path:`src/root.tsx`,kind:`mutate`,required:!0}],envVarName:`PUBLIC_ZENOVAY_SITE`,buildSnippets:qe};async function Ye(e){let t=await e.readFile(`package.json`);if(t)try{let e=JSON.parse(t),n={...e.dependencies??{},...e.devDependencies??{}},r=Object.keys(n).some(e=>e.startsWith(`@remix-run/`));if(r)return{matched:!0,confidence:.95,reason:"Detected Remix via `@remix-run/*` dependencies."}}catch{}return await e.exists(`remix.config.js`)||await e.exists(`remix.config.ts`)?{matched:!0,confidence:.8,reason:"Detected Remix via `remix.config.*`."}:{matched:!1,confidence:0,reason:`No Remix dependency or config detected.`}}function Xe(e){let t=e.trackingCode??e.siteId??``;return[{targetPath:`app/root.tsx`,anchorKind:`head-tag`,code:`<script defer data-id="${t}" src="https://api.zenovay.com/z.js"></script>`,description:`Inline the Zenovay tracker <script> inside the document <head>.`}]}const Ze={id:`remix`,displayName:`Remix`,detect:Ye,files:[{path:`app/root.tsx`,kind:`mutate`,required:!0}],envVarName:`PUBLIC_ZENOVAY_SITE`,buildSnippets:Xe};async function Qe(e){let t=await e.readFile(`package.json`);if(!t)return{matched:!1,confidence:0,reason:`No package.json.`};try{let e=JSON.parse(t),n={...e.dependencies??{},...e.devDependencies??{}};if(n[`@solidjs/start`]??n[`solid-start`])return{matched:!0,confidence:.92,reason:"Detected SolidStart via `@solidjs/start` / `solid-start`."}}catch{}return{matched:!1,confidence:0,reason:`No SolidStart dependency found.`}}function $e(e){let t=e.trackingCode??e.siteId??``,n=e.targetPath||`src/entry-server.tsx`,r=`<script
69
- defer
70
- data-id="${t}"
71
- src="https://api.zenovay.com/z.js"
72
- />`;return[{targetPath:n,anchorKind:`head-tag`,code:r,description:`Add the Zenovay tracker into the document <head> rendered by SolidStart entry-server.`}]}const et={id:`solid-start`,displayName:`SolidStart`,detect:Qe,files:[{path:`src/entry-server.tsx`,kind:`mutate`,required:!0}],envVarName:`VITE_ZENOVAY_SITE`,buildSnippets:$e};async function tt(e){let t=await e.readFile(`package.json`);if(!t)return{matched:!1,confidence:0,reason:`No package.json found.`};try{let e=JSON.parse(t),n=!!(e.dependencies?.[`@sveltejs/kit`]??e.devDependencies?.[`@sveltejs/kit`]);return n?{matched:!0,confidence:.95,reason:"Detected SvelteKit via `@sveltejs/kit` dependency."}:{matched:!1,confidence:0,reason:"`@sveltejs/kit` not in dependencies."}}catch{return{matched:!1,confidence:0,reason:`package.json is not valid JSON.`}}}function nt(e){let t=e.trackingCode??e.siteId??``,n=`<svelte:head>
73
- <script defer data-id="${t}" src="https://api.zenovay.com/z.js"></script>
74
- </svelte:head>
75
-
76
- <slot />
77
- `;return[{targetPath:`src/routes/+layout.svelte`,anchorKind:`replace-file`,code:n,description:`Root layout that loads the Zenovay tracker in every route via <svelte:head>.`}]}const rt={id:`sveltekit`,displayName:`SvelteKit`,detect:tt,files:[{path:`src/routes/+layout.svelte`,kind:`mutate`,required:!0}],envVarName:`PUBLIC_ZENOVAY_SITE`,buildSnippets:nt},it=[`next`,`nuxt`,`nuxt3`,`@sveltejs/kit`,`astro`,`@remix-run/react`,`@builder.io/qwik-city`,`@builder.io/qwik`,`@solidjs/start`,`solid-start`,`@angular/core`,`gatsby`],at=[`index.html`,`public/index.html`];async function ot(e){let t=await e.readFile(`package.json`);if(!t)return{};try{let e=JSON.parse(t);return{...e.dependencies??{},...e.devDependencies??{}}}catch{return{}}}async function st(e){for(let t of at)if(await e.exists(t))return t;return null}async function ct(e){let t=await ot(e);if(it.some(e=>t[e]))return{matched:!1,confidence:0,reason:`A Vite-based meta-framework (Next/Nuxt/SvelteKit/Astro/Remix/Qwik/Solid/Angular) owns this project.`};let n=!!t.vite,r=await st(e);return n&&r?{matched:!0,confidence:.85,reason:`Detected a Vite app via \`vite\` dependency + \`${r}\`.`}:n?{matched:!0,confidence:.55,reason:"Detected `vite` but no index.html — the agent will locate the SPA entry."}:{matched:!1,confidence:0,reason:"No `vite` dependency found."}}function lt(e){let t=e.trackingCode??e.siteId??``,n=e.targetPath||`index.html`,r=`<script defer\n data-id="${t}"\n src="https://api.zenovay.com/z.js">\n</script>`;return[{targetPath:n,anchorKind:`head-tag`,code:r,description:`Inject the Zenovay tracker inside <head> of the Vite entry HTML.`}]}const ut={id:`vite`,displayName:`Vite`,detect:ct,files:[{path:`index.html`,kind:`mutate`,required:!0}],envVarName:`VITE_ZENOVAY_SITE`,buildSnippets:lt},dt=[je,Le,Ve,rt,K,Ze,Ce,_e,et,Je,ut,Ge];async function ft(e){let t=[];for(let n of dt){let r=await n.detect(e);t.push({adapter:n,result:r})}let n=[...t].sort((e,t)=>t.result.confidence-e.result.confidence),r=n[0],i=r&&r.result.matched?r.adapter:null;return{adapter:i,ranked:n}}function pt(e){let t=t=>C.resolve(e,t);return{cwd:e,async readFile(e){try{return await w.readFile(t(e),`utf8`)}catch(e){let t=e.code;if(t===`ENOENT`||t===`EISDIR`)return null;throw e}},async exists(e){try{return await w.access(t(e)),!0}catch{return!1}},async glob(t){return ne(t,{cwd:e,dot:!1,gitignore:!0,onlyFiles:!0,followSymbolicLinks:!1})}}}async function mt(e,t){let n=pt(e),{adapter:r,ranked:i}=await ft(n),a=i[0];return r&&a&&a.result.confidence>=.7?r:t?t.pickInteractively(i):r}function ht(e){let t=/[\s"'#=]/.test(e)||e===``,n=t?`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`:e;return n}function gt(e,t){return`${e}=${ht(t)}`}async function J(e,t,n={}){let r=n.filename??`.env.local`,i=C.resolve(e,r),a=``,o=!0;try{a=await w.readFile(i,`utf8`)}catch(e){if(e.code===`ENOENT`)o=!1;else throw e}let s=[],c=[],l=[],u=[],d=a;for(let[e,n]of Object.entries(t)){let t=RegExp(`^(\\s*)(export\\s+)?(${e})(\\s*=\\s*)(.*)$`,`gm`),r=!1,i=!1;if(d=d.replace(t,(t,a,o,s,c,l)=>{r=!0;let u=ht(n),d=l.trim();return d===u||!/ZENOVAY/i.test(e)?t:(i=!0,`${a}${o??``}${s}${c}${u}`)}),r){i?c.push(e):l.push(e);continue}u.push(gt(e,n)),s.push(e)}if(s.length===0&&c.length===0)return{file:r,created:!1,existing:o,addedKeys:s,updatedKeys:c,skippedKeys:l};let f=`# Added by Zenovay CLI`,p;if(o&&u.length>0){let e=d.length>0&&!d.endsWith(`
78
- `);p=d+(e?`
79
- `:``)+`
80
- `+f+`
81
- `+u.join(`
82
- `)+`
83
- `}else p=o?d:f+`
84
- `+u.join(`
85
- `)+`
86
- `;if(await n.beforeWrite?.(i),o)await w.writeFile(i,p,`utf8`);else{let e=await w.open(i,`w`,384);try{await e.writeFile(p,`utf8`)}finally{await e.close()}}return{file:r,created:!o,existing:o,addedKeys:s,updatedKeys:c,skippedKeys:l}}const _t=`https://api.zenovay.com/mcp`,vt=T.object({url:T.string().url(),headers:T.record(T.string(),T.string()).optional()}).passthrough(),yt=T.object({mcpServers:T.record(T.string(),vt).optional()}).passthrough();function bt(e){return e.HOME??e.USERPROFILE??E.homedir()}function xt(e){return e.APPDATA??null}function St(e,t){let n=bt(t),r=xt(t),i=[];return i.push({id:`claude-code`,displayName:`Claude Code`,configPath:C.join(n,`.claude.json`),serversKey:`mcpServers`,includeType:!0}),i.push({id:`cursor`,displayName:`Cursor`,configPath:C.join(n,`.cursor`,`mcp.json`),serversKey:`mcpServers`,includeType:!1}),e===`win32`&&r&&i.push({id:`cursor`,displayName:`Cursor (AppData)`,configPath:C.join(r,`Cursor`,`User`,`globalStorage`,`cursor.mcp`,`mcp.json`),serversKey:`mcpServers`,includeType:!1}),e===`darwin`?i.push({id:`claude-desktop`,displayName:`Claude Desktop`,configPath:C.join(n,`Library`,`Application Support`,`Claude`,`claude_desktop_config.json`),serversKey:`mcpServers`,includeType:!0}):e===`win32`&&r?i.push({id:`claude-desktop`,displayName:`Claude Desktop`,configPath:C.join(r,`Claude`,`claude_desktop_config.json`),serversKey:`mcpServers`,includeType:!0}):i.push({id:`claude-desktop`,displayName:`Claude Desktop`,configPath:C.join(n,`.config`,`Claude`,`claude_desktop_config.json`),serversKey:`mcpServers`,includeType:!0}),i.push({id:`vscode`,displayName:`VS Code`,configPath:C.join(n,`.vscode`,`mcp.json`),serversKey:`servers`,includeType:!0}),i}async function Ct(e){try{return await w.access(e),!0}catch{return!1}}async function wt(e){try{let t=await w.readFile(e,`utf8`);if(t.trim().length===0)return{};let n=JSON.parse(t),r=yt.safeParse(n);return r.success?r.data:n&&typeof n==`object`?n:{}}catch{return{}}}function Tt(e){return e?{type:`http`,url:_t}:{url:_t}}function Et(e){return!e||typeof e!=`object`?!1:Object.values(e).some(e=>e&&typeof e==`object`&&e.url===_t)}async function Y(e){let t=e.env??process.env,n=e.platform??process.platform,r=new Set(e.skip??[]),i=[],a=[],o=[],s=new Set;for(let e of St(n,t)){if(r.has(e.id)){a.push(e.displayName);continue}if(s.has(e.configPath))continue;s.add(e.configPath);try{let t=await Ct(e.configPath);if(!t){a.push(e.displayName);continue}let n=await wt(e.configPath),r=n[e.serversKey];if(Et(r)){i.push(e.displayName);continue}let o=`${e.configPath}.bak`;await w.copyFile(e.configPath,o);let s=r&&typeof r==`object`?r:{},c={...n,[e.serversKey]:{...s,zenovay:Tt(e.includeType)}};await w.mkdir(C.dirname(e.configPath),{recursive:!0}),await w.writeFile(e.configPath,JSON.stringify(c,null,2)+`
87
- `,`utf8`),await w.chmod(e.configPath,384).catch(()=>void 0),i.push(e.displayName)}catch(t){o.push({client:e.displayName,message:t instanceof Error?t.message:String(t)})}}return{installed:i,skipped:a,errors:o}}async function Dt(e,t,n){let r=n.timeoutMs??18e4,i=n.pollIntervalMs??2e3,a=n.now??(()=>Date.now()),o=n.sleep??(e=>new Promise(t=>setTimeout(t,e))),s=a(),c=s+r;for(n.onTick?.(0);;){let l=await n.api.getFirstEvent({siteId:e,since:t});if(l.received)return{received:!0,event:l.event};let u=a()-s;if(u>=r)return{received:!1};let d=c-a(),f=Math.min(i,Math.max(0,d));if(f<=0)return{received:!1};await o(f),n.onTick?.(a()-s)}}const Ot=T.object({path:T.string().min(1)}),kt=T.object({path:T.string().min(1),content:T.string(),reason:T.string().min(1)}),At=T.object({path:T.string().min(1),patch:T.string().min(1),reason:T.string().min(1)}),jt=T.object({}),Mt=T.object({question:T.string().min(1),choices:T.array(T.string()).optional()});async function Nt(e,t){let n=Ot.safeParse(t);if(!n.success)return{ok:!1,content:null,error:`invalid_args`};try{let t=await e.safeRead(n.data.path),r=V.scrubSecrets(t),i=24e3,a=r.length>i?`${r.slice(0,i)}\n\n[... truncated: file is ${r.length} chars; showing the first ${i}]`:r;return{ok:!0,content:V.wrapForModel(n.data.path,a)}}catch(e){return{ok:!1,content:null,error:e.message}}}async function Pt(e,t,n){let r=kt.safeParse(t);if(!r.success)return{ok:!1,content:null,error:`invalid_args`};let{path:i,content:a,reason:o}=r.data,s=``;try{s=await e.safeRead(i)}catch{s=``}let c=await n.approve({path:i,oldContent:s,newContent:a,reason:o});if(c===`n`)return{ok:!1,content:null,error:`skipped_by_user`};if(c===`e`)return{ok:!1,content:null,error:`deferred_to_user_edit`};try{let{backupPath:t}=await e.safeWrite(i,a);return{ok:!0,content:{path:i,backupPath:t}}}catch(e){return{ok:!1,content:null,error:e.message}}}async function Ft(e,t,n){let r=At.safeParse(t);if(!r.success)return{ok:!1,content:null,error:`invalid_args`};let{path:i,patch:a,reason:o}=r.data;if(/^\*\*\*\s+Begin Patch/m.test(a)||/^\*\*\*\s+Update File:/m.test(a))return{ok:!1,content:null,error:'unsupported_patch_format: This tool only accepts STANDARD unified diff with `--- a/...`, `+++ b/...`, and `@@ -N,M +N,M @@` headers. The "*** Begin Patch / *** Update File:" V4A format is NOT supported. Please call write_file with the full new file content instead.'};let s;try{s=await e.safeRead(i)}catch(e){return{ok:!1,content:null,error:e.message}}let c;try{c=re(s,a)}catch(e){return{ok:!1,content:null,error:`patch_failed: ${e.message}. Please call write_file with the full new file content instead — write_file is more reliable than patch_file for this use case.`}}return c===!1||typeof c!=`string`?{ok:!1,content:null,error:`patch_did_not_apply_cleanly. The patch context may not match the file. Please call write_file with the full new file content instead.`}:Pt(e,{path:i,content:c,reason:o},n)}async function It(e){try{let t=pt(e),{adapter:n,ranked:r}=await ft(t);return{ok:!0,content:{matched:n!==null,adapter:n?.id,displayName:n?.displayName,ranked:r.map(e=>({id:e.adapter.id,confidence:e.result.confidence,reason:e.result.reason}))}}}catch(e){return{ok:!1,content:null,error:e.message}}}async function Lt(e,t){let n=Mt.safeParse(t);if(!n.success)return{ok:!1,content:null,error:`invalid_args`};try{let t=await e.ask(n.data);return{ok:!0,content:{answer:t}}}catch(e){return{ok:!1,content:null,error:e.message}}}const Rt=3;function zt(e,t,n){if(n)return e.delete(t),null;let r=(e.get(t)??0)+1;return e.set(t,r),r>=Rt?`STOP retrying ${t}: it failed ${r} times. Do NOT call write_file/patch_file on ${t} again — edit a different entry file, or if the tracker is already present, stop and return.`:null}async function Bt(e){let{api:t,sandbox:n,approval:r,prompter:i,handlers:a}=e,o=[...e.initialMessages],s=``,c=0,l=new Map;for(;c<ce;){n.incrementRound(),c++;let d=new AbortController,f=9e4,p=()=>{let e=setTimeout(()=>d.abort(),f);return e.unref?.(),e},m=p(),h=()=>{clearTimeout(m),m=p()},g;try{g=await t.openAiStream(`install`,{messages:o,cwd_fingerprint:n.sessionId,diagnosis:e.diagnosis,targetTrackingCode:e.targetTrackingCode},d.signal)}catch(e){throw clearTimeout(m),e}let _=[],v=``;for await(let e of u(g))switch(h(),e.type){case`delta`:v+=e.content,a?.onDelta?.(e.content);break;case`tool_start`:a?.onToolStart?.({id:e.id,name:e.name});break;case`tool_call`:{clearTimeout(m);let t=await Vt(e.name,e.arguments,{sandbox:n,cwd:n.cwd,approval:r,prompter:i});h();let o=(e.name===`write_file`||e.name===`patch_file`)&&typeof e.arguments.path==`string`?e.arguments.path:null;if(o){let e=zt(l,o,t.ok!==!1);e&&(t={...t,error:`${t.error??`write_failed`} — ${e}`})}_.push({id:e.id,name:e.name,arguments:e.arguments,result:t}),a?.onToolResult?.({id:e.id,name:e.name,result:t});break}case`usage`:a?.onUsage?.(e);break;case`error`:throw clearTimeout(m),a?.onError?.(e),Error(`[${e.code}] ${e.message}`);case`done`:break}if(clearTimeout(m),v&&(s+=v),_.length===0){v&&o.push({role:`assistant`,content:v});break}o.push({role:`assistant`,content:v,toolCalls:_.map(e=>({id:e.id,type:`function`,function:{name:e.name,arguments:JSON.stringify(e.arguments)}}))});for(let e of _)o.push({role:`tool`,toolCallId:e.id,toolName:e.name,content:JSON.stringify(e.result)})}return{finalText:s,rounds:c}}async function Vt(e,t,n){try{switch(e){case`read_file`:return await Nt(n.sandbox,t);case`write_file`:return await Pt(n.sandbox,t,n.approval);case`patch_file`:return await Ft(n.sandbox,t,n.approval);case`detect_framework`:return await It(n.cwd);case`ask_user`:return await Lt(n.prompter,t);default:return{ok:!1,content:null,error:`unknown_tool:${e}`}}}catch(e){return{ok:!1,content:null,error:`tool_threw: ${e.message}`}}}const Ht="What to do: re-run with `--review` to approve each write, or install manually (see https://docs.zenovay.com/en/integrations/cli).";function Ut(e,t,n,r){if(e.writes===0){let t=r?`Agent error: ${r.message}`:`Agent returned without writing any files (${e.reads} reads, ${e.rounds} rounds). The model may have refused or the AI Gateway may be misconfigured.`;return{ok:!1,error:`${t}\n${Ht} Nothing was changed in your project.`}}if(!t.includes(n)){let r=e.writtenPaths.join(`, `)||`(none)`,i=t.length?` (found other code(s): ${t.join(`, `)})`:``;return{ok:!1,error:`Agent wrote to: [${r}] but no Zenovay tracker <script> with your code (${n}) is present in any source file${i} — the tracker is NOT installed. The model likely wrote the code into .env only, or edited the wrong file.\n${Ht} Review/undo what was written under ~/.zenovay/undo/.`}}return{ok:!0}}const Wt=e=>`<script defer\n data-id="${e}"\n src="https://api.zenovay.com/z.js">\n</script>`;async function Gt(e){let t={installed:[],skipped:[],errors:[]};if(!X(e.trackingCode))return t.errors.push({file:`(input)`,error:`Unexpected tracking-code format: "${e.trackingCode}". Expected letters, digits, "_" or "-".`}),t;let n=await ne(`**/*.html`,{cwd:e.cwd,gitignore:!0,expandDirectories:!1,absolute:!1,ignore:[`node_modules/**`,`.git/**`,`dist/**`,`.next/**`,`.nuxt/**`,`build/**`,`.output/**`]});if(n.length===0)return t;let r=Wt(e.trackingCode),i=RegExp(`data-id\\s*=\\s*["']${Kt(e.trackingCode)}["']`);for(let a of n){let n=C.join(e.cwd,a),o;try{o=await w.readFile(n,`utf8`)}catch(e){t.errors.push({file:a,error:e.message});continue}if(le.test(o)&&i.test(o)){t.skipped.push({file:a,reason:`already installed with correct tracking code`});continue}let s;if(le.test(o))s=o.replace(/(<script[^>]*src\s*=\s*["']https:\/\/(?:api|cdn)\.zenovay\.com\/[^"']+["'][^>]*>)/i,t=>t.replace(/data-id\s*=\s*["']ZV_\w+["']/i,`data-id="${e.trackingCode}"`)),s===o&&(s=o.replace(/<script(\s)/i,`<script$1data-id="${e.trackingCode}"$1`));else if(e.updateOnly){t.skipped.push({file:a,reason:`updateOnly=true and no Zenovay tag present`});continue}else if(/<\/head>/i.test(o)){if(s=o.replace(/(\n[\t ]*)?<\/head>/i,(e,t)=>{let n=t??`
88
- `,i=r.replace(/\n/g,`${n}`);return`${n}${i}${n}</head>`}),s===o){t.skipped.push({file:a,reason:`</head> regex did not match unexpectedly`});continue}}else{t.skipped.push({file:a,reason:`no <head>...</head> in file (fragment or non-page)`});continue}let c=null;for(let{name:e,re:t}of ue)if(t.test(o)&&!t.test(s)){c=e;break}if(c){t.errors.push({file:a,error:`would remove ${c} tracker — refusing to write`});continue}try{await e.beforeWrite?.(n),await w.writeFile(n,s,`utf8`),t.installed.push(a)}catch(e){t.errors.push({file:a,error:e.message})}}return t}function Kt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function X(e){return typeof e==`string`&&e.length>0&&e.length<=64&&/^[A-Za-z0-9_-]+$/.test(e)}function qt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}const Jt=/<[Ss]cript\b[^>]*\bsrc\s*=\s*["'`][^"'`]*(?:api\.zenovay\.com\/z\.js|\/(?:api\/)?_z\/script\.js)[^"'`]*["'`][^>]*>/;function Yt(e){return Jt.test(e)}function Xt(e){return/api\.zenovay\.com\/z\.js/i.test(e)||/\/(?:api\/)?_z\/script\.js/i.test(e)}function Zt(e,t){let n=qt(t),r=e.match(new RegExp(Jt.source,`gi`))||[];return r.length===0?!1:r.every(e=>{let t=/\/(?:api\/)?_z\/script\.js/i.test(e);return t?RegExp(`[?&]id=${n}(?:["'\`&\\s/]|$)`).test(e):RegExp(`\\bdata-id\\s*=\\s*["'\`]${n}["'\`]`).test(e)})}function Qt(e,t){return e.replace(/<[Ss]cript\b[^>]*>/g,e=>{let n=/\bsrc\s*=\s*["'`][^"'`]*api\.zenovay\.com\/z\.js/.test(e),r=/\bsrc\s*=\s*["'`][^"'`]*\/(?:api\/)?_z\/script\.js/.test(e);if(!n&&!r)return e;let i=e.replace(/(\bdata-id\s*=\s*["'`])[^"'`]*(["'`])/i,`$1${t}$2`);return r&&(i=i.replace(/([?&]id=)[^&"'`\s]*/i,`$1${encodeURIComponent(t)}`)),i})}const $t=`https://api.zenovay.com/z.js`;function en(e){if(/from\s+['"]next\/script['"]/.test(e))return e;let t=e.split(`
89
- `),n=-1;for(let e=0;e<t.length;e++)/^\s*import\s/.test(t[e])&&(n=e);let r=`import Script from 'next/script';`;if(n>=0)t.splice(n+1,0,r);else{let e=/^\s*['"]use client['"];?\s*$/.test(t[0]??``);t.splice(e?1:0,0,r)}return t.join(`
90
- `)}function tn(e,t){let n=/([ \t]*)<\/body>/,r=e.match(n);if(!r)return null;let i=r[1]??``,a=`${i} <Script defer data-id="${t}" src="${$t}" strategy="afterInteractive" />`;return e.replace(n,`${a}\n${i}</body>`)}async function nn(e){let{cwd:t,trackingCode:n}=e,r={installed:[],skipped:[],errors:[],fellThrough:!1};if(!X(n))return r.errors.push({file:`(input)`,error:`unexpected tracking-code format: "${n}"`}),r;let i;try{i=await ne([`app/**/layout.{tsx,ts,jsx,js}`,`src/app/**/layout.{tsx,ts,jsx,js}`],{cwd:t,gitignore:!1,ignore:[`**/node_modules/**`]})}catch(e){return r.errors.push({file:`app/**/layout`,error:e.message}),r.fellThrough=!0,r}if(i.length===0)return r.fellThrough=!0,r;let a=[];for(let e of i)try{let n=await M.readFile(C.join(t,e),`utf8`);/<body[\s/>]/.test(n)&&a.push({rel:e,src:n,depth:e.split(`/`).length})}catch{}if(a.length===0)return r.fellThrough=!0,r;a.sort((e,t)=>e.depth-t.depth);let o=a[0];if(Zt(o.src,n))return r.skipped.push({file:o.rel,reason:`already installed with correct tracking code`}),r;if(Jt.test(o.src)){let i=Qt(o.src,n);if(i!==o.src){try{let n=C.join(t,o.rel);await e.beforeWrite?.(n),await M.writeFile(n,i),r.installed.push(o.rel)}catch(e){r.errors.push({file:o.rel,error:e.message}),r.fellThrough=!0}return r}return r.fellThrough=!0,r}if(Xt(o.src))return r.fellThrough=!0,r;let s=en(o.src),c=tn(s,n);if(!c)return r.fellThrough=!0,r;try{let n=C.join(t,o.rel);await e.beforeWrite?.(n),await M.writeFile(n,c),r.installed.push(o.rel)}catch(e){r.errors.push({file:o.rel,error:e.message}),r.fellThrough=!0}return r}const rn=`api.zenovay.com/z.js`;async function Z(e){try{return await w.readFile(e,`utf8`)}catch{return null}}function an(e,t){let n=e.toLowerCase().lastIndexOf(`</head>`);if(n===-1)return null;let r=e.lastIndexOf(`
91
- `,n-1)+1,i=(e.slice(r,n).match(/^[ \t]*/)??[``])[0],a=`${i}${t}\n`;return e.slice(0,r)+a+e.slice(r)}async function on(e,t,n,r,i,a=0,o=new Set){if(a>4)return null;let s=C.dirname(e),c=/import\s+[^;]*?from\s*['"`](\.[^'"`]+\.(?:astro|tsx|jsx|vue|svelte))['"`]/g,l=[],u;for(;(u=c.exec(t))!==null;){let e=C.resolve(s,u[1]);if(o.has(e))continue;o.add(e);let t=await Z(e);if(t===null)continue;if(Yt(t)){if(Zt(t,r))return e;let n=Qt(t,r);return n!==t&&(await i?.(e),await w.writeFile(e,n,`utf8`)),e}if(Xt(t))return e;let a=an(t,n);if(a!==null)return await i?.(e),await w.writeFile(e,a,`utf8`),e;l.push({abs:e,content:t})}for(let e of l){let t=await on(e.abs,e.content,n,r,i,a+1,o);if(t)return t}return null}async function sn(e){if(!X(e.trackingCode))return{installed:[],skipped:[],errors:[{file:`(input)`,error:`unexpected tracking-code format: "${e.trackingCode}"`}],fellThrough:!1};if(e.adapter.id===`nuxt`)return ln(e);if(e.adapter.id===`sveltekit`)return un(e);let{cwd:t,trackingCode:n,siteId:r,adapter:i}=e,a={installed:[],skipped:[],errors:[],fellThrough:!1},o;try{o=i.buildSnippets({trackingCode:n,siteId:r??``},`script`)}catch{return a.fellThrough=!0,a}if(!o||o.length===0)return a.fellThrough=!0,a;let s=new Set(o.map(e=>e.anchorKind));if(s.size===1&&s.has(`head-tag`)){let r=!1;for(let i of o){let o=C.join(t,i.targetPath),s=await Z(o);if(s===null){a.skipped.push({file:i.targetPath,reason:`target file not present`});continue}if(Zt(s,n)){a.skipped.push({file:i.targetPath,reason:`already installed with correct tracking code`}),r=!0;break}if(Yt(s)){let t=Qt(s,n);if(t!==s)try{await e.beforeWrite?.(o),await w.writeFile(o,t,`utf8`),a.installed.push(i.targetPath),r=!0;break}catch(e){a.errors.push({file:i.targetPath,error:e.message});continue}return a.fellThrough=!0,a}if(Xt(s)){a.skipped.push({file:i.targetPath,reason:`tracker present in an unparseable form (not double-inserting)`}),r=!0;break}let c=an(s,i.code);if(c===null){let c=await on(o,s,i.code,n,e.beforeWrite);if(c){a.installed.push(C.relative(t,c)),r=!0;break}a.skipped.push({file:i.targetPath,reason:`no </head> anchor (inline or in an imported head component)`});continue}try{await e.beforeWrite?.(o),await w.writeFile(o,c,`utf8`),a.installed.push(i.targetPath),r=!0;break}catch(e){a.errors.push({file:i.targetPath,error:e.message})}}return!r&&a.installed.length===0&&a.errors.length===0&&(a.fellThrough=!0),a}if(s.size===1&&s.has(`replace-file`)&&o.length===1){let r=o[0];if(!r)return a.fellThrough=!0,a;let s=i.files.find(e=>e.path===r.targetPath),c=C.join(t,r.targetPath),l=await Z(c);if(l!==null)return l.includes(rn)&&l.includes(n)?(a.skipped.push({file:r.targetPath,reason:`already installed with correct tracking code`}),a):(a.fellThrough=!0,a);if(s?.kind===`create`){try{await e.beforeWrite?.(c),await w.mkdir(C.dirname(c),{recursive:!0}),await w.writeFile(c,r.code,`utf8`),a.installed.push(r.targetPath)}catch(e){a.errors.push({file:r.targetPath,error:e.message}),a.fellThrough=a.installed.length===0}return a}return a.fellThrough=!0,a}return a.fellThrough=!0,a}function cn(){return{installed:[],skipped:[],errors:[],fellThrough:!1}}async function ln(e){let t=cn(),n=[`nuxt.config.ts`,`nuxt.config.mjs`,`nuxt.config.js`],r=null,i=null,a=null;for(let t of n){let n=C.join(e.cwd,t),o=await Z(n);if(o!==null){r=t,i=n,a=o;break}}if(a===null||i===null||r===null)return t.skipped.push({file:`nuxt.config.ts`,reason:`nuxt.config not found`}),t.fellThrough=!0,t;if(a.includes(rn))return a.includes(e.trackingCode)?(t.skipped.push({file:r,reason:`already installed with correct tracking code`}),t):(t.fellThrough=!0,t);if(/\bapp\s*:/.test(a))return t.fellThrough=!0,t;let o=a.match(/defineNuxtConfig\s*\(\s*\{/);if(!o||o.index===void 0)return t.fellThrough=!0,t;let s=e.adapter.buildSnippets({trackingCode:e.trackingCode,siteId:e.siteId??``},`script`)[0]?.code;if(!s)return t.fellThrough=!0,t;let c=o.index+o[0].length,l=`${a.slice(0,c)}\n${s}${a.slice(c)}`;try{await e.beforeWrite?.(i),await w.writeFile(i,l,`utf8`),t.installed.push(r)}catch(e){t.errors.push({file:r,error:e.message}),t.fellThrough=!0}return t}async function un(e){let t=cn(),n=`src/routes/+layout.svelte`,r=C.join(e.cwd,n),i=await Z(r),a=`<svelte:head>\n <script defer data-id="${e.trackingCode}" src="https://api.zenovay.com/z.js"></script>\n</svelte:head>\n`;if(i!==null){if(Zt(i,e.trackingCode))return t.skipped.push({file:n,reason:`already installed with correct tracking code`}),t;if(Yt(i)){let a=Qt(i,e.trackingCode);if(a!==i){try{await e.beforeWrite?.(r),await w.writeFile(r,a,`utf8`),t.installed.push(n)}catch(e){t.errors.push({file:n,error:e.message}),t.fellThrough=!0}return t}return t.fellThrough=!0,t}if(Xt(i))return t.fellThrough=!0,t;let o=i.indexOf(`</svelte:head>`),s=o>=0?i.slice(0,o)+` <script defer data-id="${e.trackingCode}" src="https://api.zenovay.com/z.js"></script>\n`+i.slice(o):`${a}\n${i}`;try{await e.beforeWrite?.(r),await w.writeFile(r,s,`utf8`),t.installed.push(n)}catch(e){t.errors.push({file:n,error:e.message}),t.fellThrough=!0}return t}let o=e.adapter.buildSnippets({trackingCode:e.trackingCode,siteId:e.siteId??``},`script`)[0]?.code;if(!o)return t.fellThrough=!0,t;try{await e.beforeWrite?.(r),await w.mkdir(C.dirname(r),{recursive:!0}),await w.writeFile(r,o,`utf8`),t.installed.push(n)}catch(e){t.errors.push({file:n,error:e.message}),t.fellThrough=!0}return t}async function dn(e,t){try{return await w.access(C.join(e,t)),!0}catch{return!1}}async function fn(e,t){try{let n=await w.stat(C.join(e,t));return n.isDirectory()}catch{return!1}}async function pn(e,t){try{return await w.readFile(C.join(e,t),`utf8`)}catch{return null}}const mn=[`next.config.js`,`next.config.mjs`,`next.config.cjs`,`next.config.ts`];async function hn(e){let t=[],n=await pn(e,`wrangler.toml`),r=n!==null&&/^\s*pages_build_output_dir\s*=/m.test(n),i=await fn(e,`functions`),a=await fn(e,`.cloudflare`);if(r&&t.push(`wrangler.toml has pages_build_output_dir`),i&&t.push(`functions/ directory present`),a&&t.push(`.cloudflare/ directory present`),r||a)return{host:`cloudflare-pages`,signals:t};let o=await dn(e,`vercel.json`),s=await fn(e,`.vercel`);if(o&&t.push(`vercel.json present`),s&&t.push(`.vercel/ directory present`),o||s)return{host:`vercel`,signals:t};let c=await dn(e,`netlify.toml`),l=await dn(e,C.join(`public`,`_redirects`)),u=await dn(e,`_redirects`);if(c&&t.push(`netlify.toml present`),l&&t.push(`public/_redirects present`),u&&t.push(`_redirects present`),c||l||u)return{host:`netlify`,signals:t};let d=null;for(let t of mn)if(await dn(e,t)){d=t;break}return d?(t.push(`${d} present (no Vercel/Netlify/CF-Pages signal)`),{host:`nextjs-server`,signals:t}):(t.push(`no deployment-host signals found`),{host:`unknown`,signals:t})}function gn(e){if(!e)return;let t=e.trim().toLowerCase();if(t===`cloudflare-pages`||t===`cloudflare`||t===`cf-pages`||t===`pages`)return`cloudflare-pages`;if(t===`vercel`)return`vercel`;if(t===`netlify`)return`netlify`;if(t===`nextjs`||t===`next`||t===`nextjs-server`)return`nextjs-server`}const _n=`https://api.zenovay.com`;function vn(e){return`// Auto-generated by @zenovay/cli — first-party tracking proxy. Do not edit.
92
- /**
93
- * First-Party Proxy for Zenovay Tracking.
94
- *
95
- * This Cloudflare Pages Function proxies tracking requests from your site to
96
- * ${e}/fp/* — making tracking requests "first-party" to bypass browser
97
- * tracking protection (Firefox ETP, Edge Tracking Prevention, Safari ITP, Brave).
98
- *
99
- * Routes (this function lives at functions/api/_z/[[path]].ts → /api/_z/*):
100
- * - GET /api/_z/script.js → ${e}/fp/script.js
101
- * - GET /api/_z/load → ${e}/fp/load
102
- * - POST /api/_z/e/:trackingCode → ${e}/fp/e/:trackingCode
103
- * - POST /api/_z/events → ${e}/fp/events
104
- * - GET /api/_z/settings/:trackingCode → ${e}/fp/settings/:trackingCode
105
- */
106
-
107
- interface Env {
108
- NEXT_PUBLIC_API_URL?: string
109
- }
110
-
111
- interface EventContext {
112
- request: Request
113
- params: { path?: string[] }
114
- env: Env
115
- }
116
-
117
- /**
118
- * Handle all HTTP methods (GET, POST, OPTIONS).
119
- */
120
- export async function onRequest(context: EventContext): Promise<Response> {
121
- const { request, params, env } = context
122
-
123
- // Build the path from the catch-all parameter.
124
- const pathSegments = params.path || []
125
- const path = pathSegments.join('/')
126
-
127
- // API base URL — defaults to the value baked in at generation time, but an
128
- // env var override (NEXT_PUBLIC_API_URL) still wins if present.
129
- const apiBase = env.NEXT_PUBLIC_API_URL || '${e}'
130
-
131
- // Build target URL — proxy to /fp/* endpoints.
132
- const targetUrl = \`\${apiBase}/fp/\${path}\${new URL(request.url).search}\`
133
-
134
- // Handle OPTIONS (CORS preflight).
135
- if (request.method === 'OPTIONS') {
136
- return new Response(null, {
137
- status: 204,
138
- headers: {
139
- 'Access-Control-Allow-Origin': '*',
140
- 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
141
- 'Access-Control-Allow-Headers': 'Content-Type, X-Zenovay-Tracking-Code',
142
- 'Access-Control-Max-Age': '86400',
143
- },
144
- })
145
- }
146
-
147
- try {
148
- // Get the real client IP from Cloudflare headers.
149
- const clientIP =
150
- request.headers.get('CF-Connecting-IP') ||
151
- request.headers.get('X-Forwarded-For')?.split(',')[0]?.trim() ||
152
- request.headers.get('X-Real-IP') ||
153
- ''
154
-
155
- // Clone the original headers.
156
- const proxyHeaders = new Headers(request.headers)
157
-
158
- // Add/set proxy identification headers.
159
- proxyHeaders.set('X-Zenovay-Proxy', 'first-party')
160
- proxyHeaders.set('X-Zenovay-Real-IP', clientIP)
161
-
162
- // Forward the visitor's real CF geo data as custom headers before deleting
163
- // the originals. When this Worker proxies to ${e}, Cloudflare
164
- // overwrites CF-* headers with the Worker datacenter's info — these custom
165
- // headers preserve the visitor's real geo.
166
- const cfCountry = request.headers.get('CF-IPCountry')
167
- const cfCity = request.headers.get('CF-IPCity')
168
- const cfRegion = request.headers.get('CF-Region')
169
- const cfLatitude = request.headers.get('CF-IPLatitude')
170
- const cfLongitude = request.headers.get('CF-IPLongitude')
171
- const cfTimezone = request.headers.get('CF-Timezone')
172
- if (cfCountry) proxyHeaders.set('X-Zenovay-CF-Country', cfCountry)
173
- if (cfCity) proxyHeaders.set('X-Zenovay-CF-City', cfCity)
174
- if (cfRegion) proxyHeaders.set('X-Zenovay-CF-Region', cfRegion)
175
- if (cfLatitude) proxyHeaders.set('X-Zenovay-CF-Latitude', cfLatitude)
176
- if (cfLongitude) proxyHeaders.set('X-Zenovay-CF-Longitude', cfLongitude)
177
- if (cfTimezone) proxyHeaders.set('X-Zenovay-CF-Timezone', cfTimezone)
178
-
179
- // Remove headers that shouldn't be forwarded.
180
- proxyHeaders.delete('Host')
181
- proxyHeaders.delete('CF-Connecting-IP')
182
- proxyHeaders.delete('CF-RAY')
183
- proxyHeaders.delete('CF-Visitor')
184
- proxyHeaders.delete('CF-IPCountry')
185
- proxyHeaders.delete('CF-Worker')
186
-
187
- // Prepare request options. redirect:'manual' so the proxy never follows an
188
- // upstream redirect to an unexpected origin (defense-in-depth).
189
- const requestInit: RequestInit = {
190
- method: request.method,
191
- headers: proxyHeaders,
192
- redirect: 'manual',
193
- }
194
-
195
- // Forward the body for POST/PUT/PATCH requests.
196
- if (request.method === 'POST' || request.method === 'PUT' || request.method === 'PATCH') {
197
- requestInit.body = await request.arrayBuffer()
198
- }
199
-
200
- // Forward the request to the API with a 5s timeout — tracking is
201
- // fire-and-forget, so a slow/hung upstream must never block the visitor's
202
- // page. On timeout we return a fast 204 (see the catch below).
203
- const ctl = new AbortController()
204
- const timer = setTimeout(() => ctl.abort(), 5000)
205
- let response: Response
206
- try {
207
- response = await fetch(targetUrl, {
208
- ...requestInit,
209
- signal: ctl.signal,
210
- cf: {
211
- // Bypass cache for scripts to ensure fresh versions.
212
- cacheTtl: path.endsWith('.js') || path.includes('script') ? 0 : 60,
213
- cacheEverything: false,
214
- },
215
- } as RequestInit)
216
- } finally {
217
- clearTimeout(timer)
218
- }
219
-
220
- // Clone response headers.
221
- const responseHeaders = new Headers(response.headers)
222
-
223
- // Add proxy identification.
224
- responseHeaders.set('X-Zenovay-Proxied', 'true')
225
-
226
- // For scripts, ensure the proper content type and no caching.
227
- if (path.endsWith('.js') || path.includes('script') || path.includes('load')) {
228
- responseHeaders.set('Content-Type', 'application/javascript; charset=utf-8')
229
-
230
- // Don't cache scripts so the latest API config (apiUrl, trackingCode) is
231
- // always served.
232
- responseHeaders.set('Cache-Control', 'no-cache, no-store, must-revalidate')
233
- }
234
-
235
- // CORS headers for the proxied response.
236
- responseHeaders.set('Access-Control-Allow-Origin', '*')
237
- responseHeaders.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
238
- responseHeaders.set('Access-Control-Allow-Headers', 'Content-Type, X-Zenovay-Tracking-Code')
239
-
240
- // Return the proxied response.
241
- return new Response(response.body, {
242
- status: response.status,
243
- statusText: response.statusText,
244
- headers: responseHeaders,
245
- })
246
- } catch (error) {
247
- // Timeout/abort → fail fast + silent (204) so tracking never blocks the page.
248
- if (error instanceof Error && error.name === 'AbortError') {
249
- return new Response(null, {
250
- status: 204,
251
- headers: { 'Access-Control-Allow-Origin': '*' },
252
- })
253
- }
254
- console.error('[Zenovay First-Party Proxy] Error:', error)
255
-
256
- return new Response(
257
- JSON.stringify({
258
- error: 'Proxy error',
259
- message: error instanceof Error ? error.message : 'Unknown error',
260
- }),
261
- {
262
- status: 502,
263
- headers: {
264
- 'Content-Type': 'application/json',
265
- 'Access-Control-Allow-Origin': '*',
266
- },
267
- }
268
- )
269
- }
270
- }
271
-
272
- /**
273
- * Handle GET requests specifically.
274
- */
275
- export async function onRequestGet(context: EventContext): Promise<Response> {
276
- return onRequest(context)
277
- }
278
-
279
- /**
280
- * Handle POST requests specifically.
281
- */
282
- export async function onRequestPost(context: EventContext): Promise<Response> {
283
- return onRequest(context)
284
- }
285
-
286
- /**
287
- * Handle OPTIONS requests specifically (CORS preflight).
288
- */
289
- export async function onRequestOptions(_context: EventContext): Promise<Response> {
290
- return new Response(null, {
291
- status: 204,
292
- headers: {
293
- 'Access-Control-Allow-Origin': '*',
294
- 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
295
- 'Access-Control-Allow-Headers': 'Content-Type, X-Zenovay-Tracking-Code',
296
- 'Access-Control-Max-Age': '86400',
297
- },
298
- })
299
- }
300
- `}async function yn(e,t){let n=(t.apiBase||_n).replace(/\/+$/,``),r=C.join(e,`functions`,`api`,`_z`),i=C.join(r,`[[path]].ts`);try{let e=await w.readFile(i,`utf8`),t=e.includes(`${n}/fp/`)||e.includes(`'${n}'`)&&e.includes(`/fp/`),r=e.includes(`X-Zenovay-Proxied`);return{file:i,action:t&&r?`exists`:`manual`}}catch{}return await t.beforeWrite?.(i),await w.mkdir(r,{recursive:!0}),await w.writeFile(i,vn(n),`utf8`),{file:i,action:`created`}}const bn=`https://api.zenovay.com`,xn=[`next.config.js`,`next.config.mjs`,`next.config.cjs`,`next.config.ts`];function Sn(e){return` // Zenovay first-party proxy — forwards /api/_z/* to the tracking API
301
- {
302
- source: '/api/_z/:path*',
303
- destination: '${e}/fp/:path*',
304
- },`}function Cn(e){return`/** @type {import('next').NextConfig} */
305
- const nextConfig = {
306
- async rewrites() {
307
- return [
308
- ${Sn(e)}
309
- ];
310
- },
311
- };
312
-
313
- export default nextConfig;
314
- `}async function wn(e,t={}){let n=t.apiBase??bn,r=null;for(let t of xn){let n=C.join(e,t);try{await M.access(n),r=n;break}catch{}}if(!r){let r=C.join(e,`next.config.mjs`);return await t.beforeWrite?.(r),await M.writeFile(r,Cn(n),`utf8`),{file:r,action:`created`}}let i=await M.readFile(r,`utf8`),a=i.includes(`source: '/api/_z/:path*'`)||i.includes(`source: "/api/_z/:path*"`),o=i.includes(`destination: '${n}/fp/:path*'`)||i.includes(`destination: "${n}/fp/:path*"`);if(a&&o)return{file:r,action:`exists`};if(i.includes(`/api/_z/:path*`)||i.includes(`/_z/:path*`)||/\brewrites\s*(?::|=|\()/.test(i)||/\bredirects\s*\(/.test(i))return{file:r,action:`manual`};let s=[...i.matchAll(/(?:module\.exports\s*=\s*|export\s+default\s+|const\s+\w+\s*(?::\s*[^={\n]{1,80})?=\s*)\{/g)],c=s.length===1?s[0]:null;if(!c||c.index===void 0)return{file:r,action:`manual`};let l=c.index+c[0].length-1,u=i.slice(0,l+1),d=i.slice(l+1),f=`
315
- async rewrites() {
316
- return [
317
- ${Sn(n)}
318
- ];
319
- },`,p=`${u}${f}${d}`;return await t.beforeWrite?.(r),await M.writeFile(r,p,`utf8`),{file:r,action:`updated`}}const Tn=`https://api.zenovay.com`;async function En(e,t={}){let n=t.apiBase??Tn,r=C.join(e,`vercel.json`),i={source:`/api/_z/(.*)`,destination:`${n}/fp/$1`},a=null;try{a=await M.readFile(r,`utf8`)}catch{a=null}if(a===null){let e={rewrites:[i]};return await t.beforeWrite?.(r),await M.writeFile(r,`${JSON.stringify(e,null,2)}\n`,`utf8`),{file:r,action:`created`}}let o;try{o=JSON.parse(a)}catch{throw Error(`Cannot parse existing vercel.json at ${r}: invalid JSON`)}if(typeof o!=`object`||!o||Array.isArray(o))throw Error(`Cannot merge into vercel.json at ${r}: top-level value is not a JSON object`);let s=Array.isArray(o.rewrites)?o.rewrites:[],c=s.some(e=>e?.source===i.source&&e?.destination===i.destination);if(c)return{file:r,action:`exists`};if(s.some(e=>typeof e?.source==`string`&&e.source.startsWith(`/api/_z`)))throw Error(`Existing /api/_z rewrite in ${r} does not point to ${i.destination}`);return o.rewrites=[...s,i],await t.beforeWrite?.(r),await M.writeFile(r,`${JSON.stringify(o,null,2)}\n`,`utf8`),{file:r,action:`updated`}}const Dn=`https://api.zenovay.com`;async function On(e){let t=C.join(e,`_redirects`),n=C.join(e,`public`,`_redirects`);for(let e of[t,n])try{return await M.access(e),e}catch{}try{let t=await M.stat(C.join(e,`public`));if(t.isDirectory())return n}catch{}return t}async function kn(e,t={}){let n=t.apiBase??Dn,r=await On(e),i=`/api/_z/* ${n}/fp/:splat 200`,a=null;try{a=await M.readFile(r,`utf8`)}catch{a=null}if(a===null)return await t.beforeWrite?.(r),await M.mkdir(C.dirname(r),{recursive:!0}),await M.writeFile(r,`# Zenovay first-party proxy — forwards /api/_z/* to the tracking API\n${i}\n`,`utf8`),{file:r,action:`created`};let o=a.split(/\r?\n/).map(e=>e.trim()).filter(e=>e.length>0&&!e.startsWith(`#`)),s=i.split(/\s+/).join(` `),c=o.some(e=>e.split(/\s+/).join(` `)===s);if(c)return{file:r,action:`exists`};if(o.some(e=>e.startsWith(`/api/_z/`)))throw Error(`Existing /api/_z redirect in ${r} does not match the Zenovay proxy target`);let l=`# Zenovay first-party proxy — forwards /api/_z/* to the tracking API`,u=a.split(/\r?\n/),d=u.findIndex(e=>{let t=e.trim();return t.length===0||t.startsWith(`#`)?!1:t.split(/\s+/)[0]===`/*`}),f;if(d>=0)u.splice(d,0,l,i),f=u.join(`
320
- `),f.endsWith(`
321
- `)||(f+=`
322
- `);else{let e=a.length>0&&!a.endsWith(`
323
- `)?`
324
- `:``;f=`${a}${e}${l}\n${i}\n`}return await t.beforeWrite?.(r),await M.writeFile(r,f,`utf8`),{file:r,action:`updated`}}const An="Your tracker is already live and working — it counts visitors in Chrome, Firefox and most browsers, no further setup required. First-party tracking is OPTIONAL and adds the rest: Safari, Brave, and browsers with strict tracking prevention block analytics loaded from another company's domain, so to capture those visitors too you serve Zenovay from your OWN domain. That last step is wired at your hosting provider — enable it any time with `zenovay init --host cloudflare-pages` (or `vercel` / `netlify` / `nextjs`).";async function jn(e,t){let{trackingCode:n,apiBase:r,forceHost:i,beforeWrite:a}=t,o=`unknown`,s=null,c=`skipped`,l=null,u=!1,f=new Set;try{switch(o=i&&i!==`unknown`?i:(await hn(e)).host,o){case`cloudflare-pages`:{let t=await yn(e,{apiBase:r,beforeWrite:a});s=t.file,c=t.action,(t.action===`created`||t.action===`updated`)&&f.add(C.relative(e,t.file));break}case`nextjs-server`:{let t=await wn(e,{apiBase:r,beforeWrite:a});s=t.file,c=t.action,(t.action===`created`||t.action===`updated`)&&f.add(C.relative(e,t.file)),t.action===`manual`&&(l=`Your tracker is live. To also count Safari/Brave visitors, add this rewrite to ${t.file} yourself (its shape couldn't be edited automatically): { source: '/api/_z/:path*', destination: 'https://api.zenovay.com/fp/:path*' }.`);break}case`vercel`:{let t=await En(e,{apiBase:r,beforeWrite:a});s=t.file,c=t.action,(t.action===`created`||t.action===`updated`)&&f.add(C.relative(e,t.file));break}case`netlify`:{let t=await kn(e,{apiBase:r,beforeWrite:a});s=t.file,c=t.action,(t.action===`created`||t.action===`updated`)&&f.add(C.relative(e,t.file));break}case`unknown`:default:c=`skipped`,l=An;break}c===`manual`&&!l&&(l=`An existing proxy configuration could not be verified safely, so Zenovay kept the standard tracker active. Review the /api/_z rule before enabling first-party tracking.`)}catch(e){s=null,c=`skipped`,l=`${An} (auto-setup hit an error: ${e.message.slice(0,120)})`}let p=s!==null&&c!==`manual`&&c!==`skipped`;if(p)try{let t=await d(e,{trackingCode:n,beforeWrite:a});u=t.swapped;for(let e of t.files)f.add(e)}catch{u=!1}return{host:o,proxyFile:s,proxyAction:c,snippetSwapped:u,manual:l,changedFiles:[...f]}}const Mn=`\x1B]8;;`,Nn=`\x07`;function Pn(){return process.env.FORCE_HYPERLINK?!0:!(process.env.NO_COLOR||!process.stdout.isTTY||process.env.CI||(process.env.TERM??``)===`dumb`)}function Fn({url:e,label:t,color:n,arrow:r=!0}){let{theme:i}=g(),a=n??i.fg,o=(t??e)+(r?` ↗`:``);return Pn()?N.createElement(A,{color:a,underline:!0},Mn,e,Nn,o,Mn,Nn):t&&t!==e?N.createElement(A,{color:a},N.createElement(A,{underline:!0},t),N.createElement(A,{color:i.dim},` (`,e,`)`)):N.createElement(A,{color:a,underline:!0},e)}function Q({label:e,value:t,labelWidth:n=12}){let{theme:r}=g();return N.createElement(k,{flexDirection:`row`},N.createElement(k,{width:n,flexShrink:0},N.createElement(A,{color:r.dim},e.toUpperCase())),typeof t==`string`?N.createElement(A,{color:r.fg},t):t)}function In(e){return e.review&&process.stdout.isTTY?`interactive`:`auto`}function Ln(e){let t=null,n=null,r=!1,i=!1,a=0,o=new Set,s=()=>{for(let e of o)e(t)};return{async approve(o){if(i)return`n`;if(e.mode===`auto`||r)return`y`;let c=String(++a);return new Promise(e=>{t={id:c,...o},n=t=>{t===`a`&&(r=!0),e(t)},s()})},subscribe(e){return o.add(e),()=>{o.delete(e)}},current(){return t},resolve(e,r){if(!t||t.id!==e||!n)return;let i=n;t=null,n=null,s(),i(r)},abort(){if(i=!0,n){let e=n;t=null,n=null,s(),e(`n`)}}}}function Rn(){let e=[12,15,18,22,28,35,41,50,58,64,72,78],t=x(e,24);return[` ↑`,` ${t}`,` └────────────────────────`,` May Jun Jul Aug Sep`]}function zn(){return[` Landing page ████████████████████ 100%`,` ↓ -28%`,` Pricing ██████████████░░░░░░ 72%`,` ↓ -50%`,` Checkout ███████░░░░░░░░░░░░░ 36%`,` ↓ -64%`,` Purchased ███░░░░░░░░░░░░░░░░░ 13%`]}function Bn(){return[` ▇▇▇▇▇▇▇▇▇▎ 89 Sarah K. /pricing 🇺🇸`,` ▇▇▇▇▇▇░░░░ 61 anon /docs 🇩🇪`,` ▇▇▇░░░░░░░ 34 anon /changelog 🇯🇵`]}function Vn(){return[` LCP ● 2.1s good ████████████░░░░░░`,` INP ● 89ms good ██████████████████`,` CLS ⚠ 0.14 needs ████████████░░░░░░`,` TTFB ● 380ms good ███████████████░░░`]}const Hn=[{title:`Welcome`,body:[`The wizard is an agent — it handles the entire`,`Zenovay setup process on your behalf.`,``,`Reading your project, deciding where the tracker`,`belongs, and writing the snippet for you.`]},{title:`Events`,body:[`Events are the foundation of Zenovay analytics.`,``,`Every pageview, click, and custom action is an`,`event. Group them into Goals to track conversions.`]},{title:`Trends`,body:[`Use trends to measure growth.`,``,`See how visitors, signups, and revenue have`,`changed over the last week, month, or quarter.`],visual:Rn},{title:`Funnels`,body:[`Funnels reveal where users drop off.`,``,`Define the steps you care about — landing,`,`pricing, checkout, purchase — and Zenovay shows`,`the per-step conversion rate.`],visual:zn},{title:`Live visitors`,body:[`Watch every visitor in real time, ranked by an`,`AI score that highlights high-intent traffic.`,``,"Use `zenovay visitors --live` after install."],visual:Bn},{title:`Core Web Vitals`,body:[`LCP, INP, CLS — Google's page-experience metrics,`,`collected automatically once the tracker is in.`,``,"Use `zenovay vitals` to see them per page + device."],visual:Vn},{title:`MCP integration`,body:[`Your CLI session can install Zenovay's MCP server`,`into Cursor / Claude Desktop / VS Code.`,``,`Then ask your AI: "what were my top pages today?"`,`and it queries Zenovay directly.`]},{title:`AI insights`,body:[`Zenovay watches your data and surfaces anomalies`,`automatically — traffic spikes, error bursts,`,`revenue drops — without you needing to ask.`,``,"Run `zenovay ai` after install to chat with them."]},{title:`Privacy-first`,body:[`No cookies required. No third-party trackers.`,`Cookieless mode is one toggle in your dashboard.`,``,`GDPR, CCPA, and PECR-compliant out of the box.`]}],Un=11e3,Wn=9,Gn=({width:e,height:t})=>{let{theme:n}=g(),[r,i]=I(0);P(()=>{if(Hn.length<=1)return;let e=setInterval(()=>{i(e=>(e+1)%Hn.length)},Un);return()=>clearInterval(e)},[]);let a=Hn[r],o=a.visual?a.visual():[];return N.createElement(k,{flexDirection:`column`,width:e,height:t,paddingX:2,paddingY:1},N.createElement(k,{marginBottom:1},N.createElement(A,{color:n.typography.label.color,dimColor:n.typography.label.dim},`LEARN`)),N.createElement(k,{flexDirection:`column`,minHeight:Wn,key:r},N.createElement(k,{marginBottom:1},N.createElement(A,{bold:!0,color:n.fg,wrap:`truncate`},a.title)),a.body.map((e,t)=>N.createElement(A,{key:t,color:n.muted,wrap:`truncate`},e||` `)),o.length>0&&N.createElement(k,{flexDirection:`column`,marginTop:1},o.map((e,t)=>N.createElement(A,{key:t,color:n.accent},e)))),N.createElement(k,{flexGrow:1}),N.createElement(k,{marginTop:1},N.createElement(A,null,Hn.map((e,t)=>N.createElement(A,{key:t,color:t===r?n.muted:n.dim},t===r?`─`:`·`)))))},Kn={pending:`·`,active:`⠋`,done:`✓`,error:`✗`};function qn(e,t){switch(e){case`pending`:return t.dim;case`active`:return t.accent;case`done`:return t.success;case`error`:return t.error}}const Jn=({tasks:e,width:t,height:n,liveLine:r})=>{let{theme:i}=g();return N.createElement(k,{flexDirection:`column`,width:t,height:n,paddingX:2,paddingY:1},N.createElement(k,{marginBottom:1},N.createElement(A,{color:i.typography.label.color,dimColor:i.typography.label.dim},`TASKS`)),e.map(e=>N.createElement(k,{key:e.id,flexDirection:`column`},N.createElement(k,{flexDirection:`row`},e.status===`active`?N.createElement(A,{color:i.accent},N.createElement(L,{type:`dots`})):N.createElement(A,{color:qn(e.status,i)},Kn[e.status]),N.createElement(A,null,` `),N.createElement(A,{color:e.status===`pending`?i.muted:i.fg,wrap:`truncate`},e.label)),e.detail&&N.createElement(k,{paddingLeft:2},N.createElement(A,{color:i.dim,wrap:`truncate`},e.detail)))),N.createElement(k,{flexGrow:1}),r&&N.createElement(k,{flexDirection:`row`,marginTop:1},N.createElement(A,{color:i.accent},`◆ `),N.createElement(A,{color:i.fg,wrap:`truncate`},r)))};function Yn(e){return e.toLowerCase().replace(/[^a-z0-9]/g,``)}function Xn(e,t){if(e.length===0)return null;if(e.length===1)return e[0]??null;if(!t)return null;let n=Yn(t);if(!n)return null;let r=e.find(e=>Yn(e.name)===n);if(r)return r;let i=e.find(e=>{let t=new URL(e.url).hostname;return Yn(t.split(`.`)[0]??``)===n});if(i)return i;if(n.length<4)return null;let a=e.filter(e=>{let t=Yn(e.name),r=Yn(new URL(e.url).hostname);return t.includes(n)||r.includes(n)||n.includes(t)||n.includes(r)});return a.length===1?a[0]??null:null}const Zn=ie(S),Qn=2e4;async function $(e,t){let n=await Zn(`git`,t,{cwd:e,timeout:Qn,maxBuffer:4e6,env:{...process.env,GIT_TERMINAL_PROMPT:`0`}});return{stdout:n.stdout,stderr:n.stderr}}function $n(e){let t=e.split(`\0`).filter(Boolean),n=[];for(let e=0;e<t.length;e++){let r=t[e];if(r.length<4)continue;let i=r.slice(0,2);n.push(r.slice(3)),/[RC]/.test(i)&&t[e+1]&&n.push(t[++e])}return[...new Set(n)]}async function er(e){let{stdout:t}=await $(e,[`status`,`--porcelain=v1`,`-z`,`--untracked-files=all`]);return $n(t)}async function tr(e){try{let{stdout:t}=await $(e,[`rev-parse`,`--show-toplevel`]),n=C.resolve(t.trim());return{isRepository:!0,root:n,dirtyPaths:await er(n)}}catch{return{isRepository:!1,root:null,dirtyPaths:[]}}}async function nr(e,t,n){let r=await w.realpath(e).catch(()=>C.resolve(e)),i=C.resolve(r,n),a=await w.realpath(i).catch(()=>i),o=C.relative(t,a);return!o||o.startsWith(`..`)||C.isAbsolute(o)?null:o.split(C.sep).join(`/`)}function rr(e){return/(^|\/)\.env(?:$|\.(?!example(?:$|\.)))/i.test(e)}async function ir(e){let{cwd:t,baseline:n}=e;if(!n.isRepository||!n.root)return{committed:!1,pushed:!1,reason:`not-repository`,message:`Not a git repository — skipped automatic commit.`};if(n.dirtyPaths.length>0)return{committed:!1,pushed:!1,reason:`dirty-baseline`,message:`The repository already had uncommitted work, so Zenovay left git untouched. Commit the tracker through your normal workflow.`};let r=await Promise.all(e.changedPaths.map(e=>nr(t,n.root,e))),i=[...new Set(r.filter(e=>!!e))];if(i.length===0)return{committed:!1,pushed:!1,reason:`no-journaled-changes`,message:`No Zenovay-written files were recorded — git was left untouched.`};let a=i.filter(e=>!rr(e)),o=i.filter(rr),s=await er(n.root),c=new Set(i),l=s.filter(e=>!c.has(e));if(l.length>0)return{committed:!1,pushed:!1,reason:`unexpected-changes`,message:`New non-Zenovay changes appeared during setup (${l.join(`, `)}), so git was left untouched.`,unstagedPaths:s};if(a.length===0)return{committed:!1,pushed:!1,reason:`no-staged-changes`,message:`Only local environment files changed; Zenovay intentionally did not commit them.`,unstagedPaths:o};let{stdout:u}=await $(n.root,[`symbolic-ref`,`--quiet`,`--short`,`HEAD`]),d=u.trim();e.onDetail?.(`Staging ${a.length} Zenovay file(s)…`),await $(n.root,[`add`,`--`,...a]);try{return await $(n.root,[`diff`,`--cached`,`--quiet`]),{committed:!1,pushed:!1,reason:`no-staged-changes`,message:`The recorded Zenovay files were already up to date.`,unstagedPaths:o}}catch{}e.onPhase?.(`committing`),e.onDetail?.(`Creating a tracker-only commit…`),await $(n.root,[`commit`,`-m`,`chore(zenovay): install tracking script via @zenovay/cli`]);let{stdout:f}=await $(n.root,[`rev-parse`,`--short`,`HEAD`]),p=f.trim();e.onPhase?.(`pushing`),e.onDetail?.(`Pushing ${p} to origin/${d}…`);try{await $(n.root,[`push`,`origin`,d])}catch(e){let t=e instanceof Error?e.message.split(`
325
- `)[0]:`unknown git error`;return{committed:!0,pushed:!1,shortSha:p,branch:d,reason:`push-failed`,pushError:t,message:`Commit ${p} was created locally, but it was not pushed. Run: git push origin ${d}`,unstagedPaths:o}}return e.onPhase?.(`done`),{committed:!0,pushed:!0,shortSha:p,branch:d,message:`Pushed ${p} to origin/${d}.`,unstagedPaths:o}}const ar=/<script\b[^>]*\bsrc\s*=\s*["'][^"']*(?:(?:api|cdn)\.zenovay\.com\/|\/(?:api\/)?_z\/script\.js)[^"']*["'][^>]*>/gi,or=/\bsrc\s*=\s*["']([^"']+)["']/i,sr=/data-id\s*=\s*["'](ZV_[A-Za-z0-9_-]+)["']/i,cr=/[?&]id=(ZV_[A-Za-z0-9_-]+)/i;function lr(e){return e.match(sr)?.[1]??e.match(cr)?.[1]??null}function ur(e){return/\/(?:api\/)?_z\/script\.js/i.test(e)}async function dr(e,t,n=fetch){try{let r=await n(e,{headers:{"User-Agent":`zenovay-cli/preflight`},signal:AbortSignal.timeout(8e3),redirect:`follow`});if(!r.ok)return{state:`tracker-missing`,httpStatus:r.status};let i=await r.text(),a=i.match(ar)??[];if(a.length===0)return{state:`tracker-missing`};let o=[...new Set(a.map(lr).filter(e=>!!e))],s=a.find(e=>lr(e)===t);if(!s)return{state:`tracker-wrong-id`,foundCodes:o};if(!ur(s))return{state:`tracker-correct`};let c=s.match(or)?.[1]?.replace(/&amp;/gi,`&`);if(!c)return{state:`proxy-broken`,scriptUrl:e,detail:`The first-party tracker tag has no readable script URL.`};let l=new URL(c,r.url||e).toString(),u;try{u=await n(l,{headers:{"User-Agent":`zenovay-cli/preflight`},signal:AbortSignal.timeout(8e3),redirect:`follow`})}catch(e){return{state:`proxy-broken`,scriptUrl:l,detail:`The first-party script could not be reached: ${e instanceof Error?e.message:`network error`}`}}if(!u.ok)return{state:`proxy-broken`,scriptUrl:l,httpStatus:u.status,detail:`The first-party script returned HTTP ${u.status}.`};let d=u.headers.get(`content-type`)??``;if(!/(?:java|ecma)script/i.test(d))return{state:`proxy-broken`,scriptUrl:l,detail:`The first-party route returned ${d||`an unknown content type`} instead of JavaScript.`};if(u.headers.get(`x-zenovay-proxied`)?.toLowerCase()!==`true`)return{state:`proxy-broken`,scriptUrl:l,detail:`The route did not identify itself as a Zenovay first-party proxy.`};let f=await u.text();return f.includes(t)?{state:`tracker-correct`}:{state:`proxy-broken`,scriptUrl:l,detail:`The proxy script was served with a different tracking code.`}}catch(e){return{state:`tracker-missing`,networkError:e instanceof Error?e.message:`network error`}}}async function fr(e){if(e.undo)return pr(e);if(s(e))return mr(e);let t=`quit`,n=null,r=null,i=Promise.resolve(),a=await new Promise(a=>{let{unmount:o,waitUntilExit:s}=ee(N.createElement(hr,{opts:e,onExit:(e,i,s,c)=>{t=i??`quit`,n=s??null,r=c??null,o(),a(e)}}),{exitOnCtrlC:!0});i=s(),i.then(()=>a(130),()=>a(1))});if(await i.catch(()=>{}),a===0&&r)return await c(r),0;let o=a===0&&t!==`quit`&&!!n;if(a===0&&!o&&await p().catch(()=>void 0),a!==0||t===`quit`||!n)return a;let l=n.id,u=t===`watch`?[`overview`,`--site-id`,l]:[`events`,`tail`,`--site-id`,l],{spawnSync:d}=await import(`node:child_process`),{realpathSync:f}=await import(`node:fs`),{buildPostInstallReexec:m}=await import(`./ensure-latest-BfsWmA1w.js`),{cmd:h,args:g}=m({execPath:process.execPath,argv1:process.argv[1]??``,sub:u,resolveSymlink:f});await new Promise(e=>setImmediate(e));let _=d(h,g,{stdio:`inherit`});if(_.error){let e=t===`watch`?`overview`:`events tail`;return process.stderr.write(`Run \`zenovay ${e} --site-id ${l}\` to continue.\n`),0}return _.status??0}async function pr(e){let t=C.join(E.homedir(),`.zenovay`,`undo`),n;try{let e=await w.readdir(t,{withFileTypes:!0}),r=e.filter(e=>e.isDirectory()).map(e=>e.name),i=await Promise.all(r.map(async e=>({name:e,mtime:await w.stat(C.join(t,e)).then(e=>e.mtimeMs,()=>0)})));n=i.sort((e,t)=>t.mtime-e.mtime).map(e=>e.name)}catch{n=[]}if(n.length===0)return s(e)?(o({type:`info`,message:`Nothing to undo — no init session has modified project files on this machine.`}),o({type:`done`,command:`init`,exitCode:0})):process.stdout.write(`Nothing to undo — no init session has modified project files on this machine.
326
- `),0;let r;for(let t of n)if(await pe(t,e.cwd).catch(()=>!1)){r=t;break}if(!r){let t=`Nothing to undo — no init session belongs to this project.`;return s(e)?(o({type:`info`,message:t}),o({type:`done`,command:`init`,exitCode:0})):process.stdout.write(`${t}\n`),0}try{let{restored:t}=await he(r,{cwd:e.cwd}),n=t>0?`Reverted ${t} file(s) from the last install (session ${r}).`:`Nothing to revert in the last session (${r}).`;return s(e)?(o({type:`info`,message:n}),o({type:`done`,command:`init`,exitCode:0})):process.stdout.write(`${n}\n`),0}catch(n){let i=`Undo failed: ${n.message}. The backups are under ${C.join(t,r)} if you need to restore by hand.`;return s(e)?(o({type:`error`,code:`undo_failed`,message:i}),o({type:`done`,command:`init`,exitCode:1})):process.stderr.write(`${i}\n`),1}}async function mr(t){let r=await import(`./telemetry-DIAzAYko.js`).catch(()=>null);r?.emit(`install.start`,{properties:{mode:`headless`}});try{let s=await e(),c=await mt(t.cwd);if(!c)return o({type:`error`,code:`no_framework`,message:`Could not detect framework (headless mode has no picker).`}),r?.emit(`install.error`,{error_code:`no_framework`,properties:{mode:`headless`}}),2;o({type:`framework.detected`,framework:c.id,confidence:1}),r?.emit(`install.framework_detected`,{properties:{framework:c.id}});let l=await i({strict:!1});if(!l&&!process.env.ZENOVAY_API_TOKEN)return o({type:`error`,code:`not_logged_in`,message:"Run `zenovay login` first (or set ZENOVAY_API_TOKEN)."}),2;let u=new n({config:s,cliVersion:t.cliVersion,token:l}),[d,f]=await Promise.all([u.getSites(),a(t.cwd,``).catch(()=>null)]),p;if(t.siteId){if(p=d.find(e=>e.id===t.siteId),!p)return o({type:`error`,code:`site_not_found`,message:`Site ${t.siteId} not found.`}),2}else if(f?.foundTrackingCodes.length){for(let e of f.foundTrackingCodes){let t=d.find(t=>t.trackingCode===e);if(t){p=t;break}}!p&&d.length===1&&(p=d[0])}else p=d.length===1?d[0]:void 0;if(!p)return o({type:`error`,code:d.length===0?`no_site`:`site_required`,message:d.length===0?`No sites exist; create one at app.zenovay.com or re-run interactively.`:`More than one site exists and none matches this project. Pass --site-id <ID> so Zenovay cannot install the wrong tracker.`}),2;let m=p.trackingCode??p.id;if(f&&(f.recommendation===`no-op`||f.foundTrackingCodes.includes(m)))return o({type:`info`,message:`Zenovay already installed correctly for ${p.name} (${m})`}),o({type:`done`,command:`init`,exitCode:0}),0;o({type:`info`,message:`Using site ${p.id} (${p.name}) trackingCode=${p.trackingCode??p.id}`});let h=p.trackingCode??p.id;if(!X(h))return o({type:`error`,code:`invalid_tracking_code`,message:`tracking code "${h}" has an unexpected format; aborting to avoid broken markup`}),1;let g=new V({cwd:t.cwd}),_=e=>g.journalTrustedWrite(e);if(c.id===`plain-html`){let e=await Gt({cwd:t.cwd,trackingCode:h,updateOnly:f?.recommendation===`update-tracking-code`,beforeWrite:_});if(e.installed.length===0&&e.skipped.length===0)return o({type:`error`,code:`install_failed`,message:`No .html files with a <head> block found to inject the tracker into (errors: ${e.errors.length}).`}),r?.emit(`install.error`,{error_code:`install_failed`,properties:{mode:`headless`,framework:c.id}}),o({type:`done`,command:`init`,exitCode:1}),1;o({type:`info`,message:`tracker injected into ${e.installed.length} file(s); ${e.skipped.length} already current; ${e.errors.length} error(s)`})}else if(c.id===`next-app-router`){let e=await nn({cwd:t.cwd,trackingCode:h,beforeWrite:_});if(e.fellThrough||e.errors.length>0)return o({type:`error`,code:`headless_framework_unsupported`,message:"This Next.js project has a structure the headless installer can't edit safely (no standard document-shell layout found). Run `zenovay init` interactively — the wizard places the tracker in the correct file. Nothing was modified."}),r?.emit(`install.error`,{error_code:`headless_framework_unsupported`,properties:{mode:`headless`,framework:c.id}}),o({type:`done`,command:`init`,exitCode:1}),1;o({type:`info`,message:`tracker inserted: ${e.installed[0]??`already installed — nothing to change`}`})}else{let e=await sn({cwd:t.cwd,trackingCode:h,siteId:p.id,adapter:c,beforeWrite:_}),n=e.skipped.some(e=>/already installed|tracker present/i.test(e.reason));if(e.fellThrough||e.errors.length>0||e.installed.length===0&&!n)return o({type:`error`,code:`headless_framework_unsupported`,message:`${c.displayName}'s tracker insert isn't a mechanical edit the headless mode can apply safely for this project shape. Run \`zenovay init\` interactively — the wizard uses a deterministic fast path and falls back to the AI installer only where judgement is needed. Nothing was modified.`}),r?.emit(`install.error`,{error_code:`headless_framework_unsupported`,properties:{mode:`headless`,framework:c.id}}),o({type:`done`,command:`init`,exitCode:1}),1;o({type:`info`,message:`tracker inserted: ${e.installed[0]??`already installed — nothing to change`}`})}let v=await J(t.cwd,{[c.envVarName]:h},{beforeWrite:_});if(v.addedKeys.length>0&&o({type:`info`,message:`env vars added: ${v.addedKeys.join(`,`)}`}),t.firstParty!==!1){let e=await jn(t.cwd,{trackingCode:h,forceHost:gn(t.host),beforeWrite:_});e.proxyFile&&e.proxyAction!==`manual`&&e.proxyAction!==`skipped`?o({type:`info`,message:`first-party tracking enabled — analytics now load from your own domain (${_r(t.cwd,e.proxyFile)}), so visitors on Safari/Brave and other strict-privacy browsers are counted too`}):e.manual&&o({type:`info`,message:e.manual})}else o({type:`info`,message:"first-party tracking skipped (--no-first-party) — enable it later with `zenovay init --host <cloudflare-pages|vercel|netlify|nextjs>`"});return o({type:`done`,command:`init`,exitCode:0}),r?.emit(`install.success`,{properties:{framework:c.id,mode:`headless`,env_keys_added:v.addedKeys.length}}),0}catch(e){return o({type:`error`,code:`init_failed`,message:e.message}),r?.emit(`install.error`,{error_code:`init_failed`,properties:{mode:`headless`,error:(e.message??`unknown`).slice(0,128)}}),1}}const hr=({opts:t,onExit:r})=>{let{exit:o}=te(),{theme:s}=g(),[c,l]=I(`intro`),[u,d]=I(null),[p,_]=I([]),[v,y]=I(null),[x,S]=I(null),[C,w]=I(null),[T,E]=I([]),[D,O]=I(void 0),[ee,M]=I(null),[ne,re]=I(null),[ie,ae]=I(null),[oe,R]=I(0),[se,z]=I(`skipped`),[ce,B]=I(null),[le,ue]=I(null),[V,de]=I(null),H=F(new Set),fe=F(!1),U=F(null),W=F(!0),pe=N.useCallback(e=>{for(let t of e)t&&H.current.add(t)},[]),[me,he]=I(null),G=F(null),ge=F(!1),[_e,ve]=I(!1),[ye,be]=I(void 0),K=F(null),xe=N.useCallback(e=>new Promise(t=>{K.current=t,be(e),ve(!0)}),[]),Se=N.useCallback(e=>{ve(!1);let t=K.current;K.current=null,t?.(e)},[]),q=N.useCallback((e,t,n,i)=>{W.current&&(W.current=!1,o(),r(e,t,n,i))},[o,r]);j((e,t)=>{let n=e.toLowerCase()===`q`||t.escape;n&&(c===`error`?q(1):c===`create-site`&&q(0))}),P(()=>{let e=process.env.TERM_PROGRAM===`vscode`,t=!!process.stdout.isTTY&&!e;return t&&process.stdout.write(`\x1B[?1049h\x1B[H`),()=>{W.current=!1,G.current?.abort(),K.current?.(null),K.current=null,t&&process.stdout.write(`\x1B[?1049l`)}},[]),P(()=>{ge.current||(ge.current=!0,(async()=>{try{ue(await tr(t.cwd));let r=!!process.stdout.isTTY&&!t.yes&&!t.json;r&&await new Promise(e=>setTimeout(e,1400)),l(`detecting`);let o=await mt(t.cwd);if(!o){w(`Could not detect your framework. Supported: Next.js, Nuxt, SvelteKit, Astro, Remix, plain HTML.`),l(`error`);return}d(o);let s=await i({strict:!1});!process.env.ZENOVAY_API_TOKEN&&!s&&(l(`login`),await f({cliVersion:t.cliVersion,offerCompletions:!1})),l(`loading-sites`);let c=await e(),u=await i({strict:!1}),p=new n({config:c,cliVersion:t.cliVersion,token:u}),[m,h]=await Promise.all([p.getSites(),a(t.cwd,``).catch(()=>null)]),g=await Rr(t.cwd);if(_(m),y(g),m.length===0){l(`create-site`);return}if(t.siteId){let e=m.find(e=>e.id===t.siteId);if(!e){w(`Site ${t.siteId} not found in your account.`),l(`error`);return}let n=e.trackingCode??e.id;if(h?.foundTrackingCodes.includes(n)){S(e),l(`already-installed`);return}S(e),xr(e,o,t,{setPhase:l,setErrorMsg:w,setTasks:E,setLiveLine:O,setSandboxStats:M,setVerifyResult:re,setFirstParty:ae,setPendingApproval:he,askHostChoice:xe,recordChangedPaths:pe,registerBridge:e=>{G.current=e}});return}if(h?.foundTrackingCodes.length)for(let e of h.foundTrackingCodes){let t=m.find(t=>t.trackingCode===e);if(t){S(t),l(`already-installed`);return}}let v=Xn(m,g);if(t.yes&&v){S(v),xr(v,o,t,{setPhase:l,setErrorMsg:w,setTasks:E,setLiveLine:O,setSandboxStats:M,setVerifyResult:re,setFirstParty:ae,setPendingApproval:he,askHostChoice:xe,recordChangedPaths:pe,registerBridge:e=>{G.current=e}});return}l(`site-picker`)}catch(e){w(e.message),l(`error`)}})())},[]),P(()=>{c===`error`&&(G.current?.abort(),setTimeout(()=>q(1),8e3))},[c]);let Ce=async()=>{if(!fe.current){if(fe.current=!0,z(`verified`),!x){l(`success`);return}try{let r=await e();if(!W.current)return;let a=await i({strict:!1});if(!W.current)return;let o=new n({config:r,cliVersion:t.cliVersion,token:a}),s=await o.getSetupDestination(x.id);if(!W.current)return;if(B(s),s.kind===`account_onboarding`||s.kind===`site_onboarding`){q(0,`quit`,x,s.url);return}}catch{}W.current&&l(`success`)}};return N.createElement(k,{flexDirection:`column`},N.createElement(m,{version:t.cliVersion,subtitle:`AI install wizard`}),c===`intro`&&N.createElement(Sr,null),c===`detecting`&&N.createElement(h,{title:`Scanning`,state:`busy`},N.createElement(k,null,N.createElement(A,{color:s.accent},N.createElement(L,{type:`dots`})),N.createElement(A,null,` Detecting framework…`))),c===`login`&&N.createElement(h,{title:`Authenticating`,state:`busy`},N.createElement(A,null,`Opening browser for login… (paste ZENOVAY_API_TOKEN env var to skip)`)),c===`loading-sites`&&N.createElement(h,{title:`Loading your sites`,state:`busy`},N.createElement(k,null,N.createElement(A,{color:s.accent},N.createElement(L,{type:`dots`})),N.createElement(A,null,` Fetching your Zenovay sites…`))),c===`already-installed`&&x&&N.createElement(Tr,{site:x,onContinueSetup:()=>{if(t.skipVerify){z(`skipped`),l(`success`);return}U.current=Date.now(),R(0),l(`visit-prompt`)},onReinstall:()=>{l(`site-picker`)},onExit:()=>q(0,`quit`,x)}),c===`site-picker`&&u&&N.createElement(Er,{sites:p,preselectHint:v,onPick:e=>{if(e===`create-new`){l(`create-site`);return}S(e),xr(e,u,t,{setPhase:l,setErrorMsg:w,setTasks:E,setLiveLine:O,setSandboxStats:M,setVerifyResult:re,setFirstParty:ae,setPendingApproval:he,askHostChoice:xe,recordChangedPaths:pe,registerBridge:e=>{G.current=e}})}}),c===`create-site`&&N.createElement(h,{title:`Add a site first`,state:`warn`},N.createElement(A,{color:s.warn},`You don't have a Zenovay site yet. Create one at https://app.zenovay.com/websites (takes ~30 seconds), then re-run `,N.createElement(A,{color:s.accent},`zenovay init`),` here.`),N.createElement(k,{marginTop:1},N.createElement(A,{color:s.muted},`Press `),N.createElement(A,{color:s.accent},`q`),N.createElement(A,{color:s.muted},` to exit.`))),c===`agent`&&u&&x&&N.createElement(wr,{adapter:u,site:x,tasks:T,liveLine:D,pendingApproval:me,onApprove:e=>{me&&G.current?.resolve(me.id,e)},pendingHostChoice:_e,hostChoiceNote:ye,onHostChoice:Se}),c===`install-complete`&&u&&x&&N.createElement(Ar,{cwd:t.cwd,adapter:u,site:x,stats:ee,verify:ne,firstParty:ie,onCommit:()=>l(`commit-prompt`),onSkipCommit:()=>l(`deploy-prompt`),onQuit:()=>q(0,`quit`,x)}),c===`commit-prompt`&&x&&N.createElement(Mr,{cwd:t.cwd,baseline:le??{isRepository:!1,root:null,dirtyPaths:[]},changedPaths:[...H.current],onDone:e=>{de(e.message),e.pushed&&O(`Pushed ${e.shortSha} to ${e.branch}`),l(`deploy-prompt`)},onError:e=>{w(e),l(`error`)}}),c===`deploy-prompt`&&x&&N.createElement(Nr,{site:x,notice:V,onDeployed:()=>{t.skipVerify?(z(`skipped`),l(`success`)):(U.current=Date.now(),l(`visit-prompt`))},onSkip:()=>{z(`skipped`),l(`success`)},onQuit:()=>q(0,`quit`,x)}),c===`visit-prompt`&&x&&N.createElement(Pr,{site:x,onContinue:()=>l(`verify`),onQuit:()=>q(0,`quit`,x)}),c===`verify`&&x&&N.createElement(Fr,{site:x,since:U.current??Date.now(),elapsed:oe,onTick:e=>R(e),onArrived:()=>{Ce()},onTimeout:()=>{z(`unverified`),l(`success`)},onSkip:()=>{z(`skipped`),l(`success`)},onQuit:()=>q(0,`quit`,x)}),c===`success`&&u&&x&&N.createElement(kr,{adapter:u,site:x,stats:ee,outcome:se,dashboardUrl:ce?.kind===`dashboard`?ce.url:void 0,firstParty:ie,onPick:e=>q(0,e,x)}),c===`error`&&N.createElement(h,{title:`Install failed`,state:`err`},N.createElement(A,{color:s.error},C??`Unknown error`)),N.createElement(b,{items:c===`already-installed`?[{key:`enter`,label:`verify and continue`},{key:`r`,label:`reinstall or change site`},{key:`q`,label:`quit`},{key:`ctrl-c`,label:`abort`}]:[{key:`q`,label:`quit`},{key:`ctrl-c`,label:`abort`}]}))};async function gr(e,t,n,r){if(e.firstParty===!1){n.setFirstParty?.({host:`unknown`,proxyFile:null,proxyAction:`skipped`,snippetSwapped:!1,manual:"First-party tracking skipped (--no-first-party). Safari/Brave and other strict-privacy setups block third-party analytics — add all-browser coverage any time with `zenovay init --host <cloudflare-pages|vercel|netlify|nextjs>`.",changedFiles:[]});return}if(!n.setFirstParty)return;n.setTasks(e=>e.some(e=>e.id===`first-party`)?e.map(e=>e.id===`first-party`?{...e,status:`active`}:e):[...e,{id:`first-party`,label:`Set up first-party tracking (all browsers)`,status:`active`}]),n.setLiveLine(`Setting up first-party tracking (all browsers)…`);let i=gn(e.host),a=null;try{if(a=await jn(e.cwd,{trackingCode:t,forceHost:i,beforeWrite:r}),n.setFirstParty(a),n.recordChangedPaths?.(a.changedFiles),a.host===`unknown`&&!i&&n.askHostChoice){n.setLiveLine(`Where do you deploy this site? (enables all-browser tracking)`);let i=e.host?`Unrecognized --host "${e.host}" — pick your host below.`:void 0,o=await n.askHostChoice(i);o&&(n.setLiveLine(`Setting up first-party tracking…`),a=await jn(e.cwd,{trackingCode:t,forceHost:o,beforeWrite:r}),n.setFirstParty(a),n.recordChangedPaths?.(a.changedFiles))}}catch{a={host:`unknown`,proxyFile:null,proxyAction:`skipped`,snippetSwapped:!1,manual:"First-party setup hit an error — your standard tracker is active; add all-browser coverage later with `zenovay init --host <cloudflare-pages|vercel|netlify|nextjs>`.",changedFiles:[]},n.setFirstParty(a)}let o=vr(a,e.cwd);n.setTasks(e=>e.map(e=>e.id===`first-party`?{...e,status:`done`,detail:o}:e)),n.setLiveLine(void 0)}function _r(e,t){let n=C.resolve(e),r=C.isAbsolute(t)?C.normalize(t):C.resolve(n,t),i=C.relative(n,r);return i&&i!==`..`&&!i.startsWith(`..${C.sep}`)&&!C.isAbsolute(i)?i:C.basename(t)}function vr(e,t){return e?e.proxyFile&&e.proxyAction!==`manual`&&e.proxyAction!==`skipped`?`now loads from your domain (${_r(t,e.proxyFile)})`:e.manual?`standard tracking active — see note below for all-browser coverage`:`standard tracking active`:`standard tracking active`}function yr(e){return e&&e.installed.length>0?e.installed.join(`, `):e&&e.errors.length>0?`failed: ${e.errors[0]?.message??`unknown error`}`:`none detected`}async function br(e,t,n){n.setLiveLine(`Verifying the tracker is in your source…`);try{let r=await a(e,t),i=r.recommendation===`no-op`&&r.foundTrackingCodes.includes(t);n.setVerifyResult?.({ok:i,detail:i?`Tracker confirmed in your source files`:`Couldn't auto-confirm the tracker (diagnosis: ${r.recommendation}) — please double-check`})}catch{n.setVerifyResult?.({ok:!1,detail:`Verification check could not run`})}n.setLiveLine(void 0)}async function xr(r,o,s,c){try{c.setPhase(`agent`);let l=await e(),u=await i({strict:!1}),d=new n({config:l,cliVersion:s.cliVersion,token:u}),f=new V({cwd:s.cwd}),p=e=>f.journalTrustedWrite(e),m=r.trackingCode??r.id;if(!X(m)){c.setErrorMsg(`The resolved tracking code "${m}" has an unexpected format (expected letters, digits, "_" or "-"). Aborting to avoid writing broken markup — re-check the site in your dashboard.`),c.setPhase(`error`);return}await t({defaultSiteId:r.id,defaultSiteName:r.name}).catch(()=>void 0);let h=await a(s.cwd,m);if(h.recommendation===`no-op`){c.setTasks(e=>e.map(e=>e.id===`detect`||e.id===`read`||e.id===`write`?{...e,status:`done`,detail:`already installed correctly`}:e)),c.setLiveLine(h.summary),c.setSandboxStats?.({reads:0,writes:0,rounds:0}),!s.skipMcp&&u&&await Y({accessToken:u.accessToken}).catch(()=>void 0),c.setVerifyResult?.({ok:!0,detail:`Already installed correctly`}),await gr(s,m,c,p),c.setPhase(`install-complete`);return}if(h.competitors.length>0&&c.setLiveLine(`Detected ${h.competitors.map(e=>e.name).join(`, `)} — will install Zenovay alongside (won't touch their tags).`),o.id===`next-app-router`){c.setTasks([{id:`detect`,label:`Detect framework`,status:`done`,detail:`Next.js (App Router)`},{id:`read`,label:`Find the document shell layout`,status:`active`},{id:`write`,label:`Insert tracker <Script>`,status:`pending`},{id:`env`,label:`Write env vars (.env.local)`,status:`pending`},{id:`mcp`,label:`Install MCP clients (Claude Code/Cursor/VS Code)`,status:`pending`},{id:`verify`,label:`Verify the tracker in your source`,status:`pending`}]),c.setLiveLine(`Next.js — locating the document shell layout…`);let e=await nn({cwd:s.cwd,trackingCode:m,beforeWrite:p});if(c.recordChangedPaths?.(e.installed),!e.fellThrough&&e.errors.length===0){let t=e.installed[0]??`already installed`;c.setTasks(e=>e.map(e=>e.id===`read`||e.id===`write`?{...e,status:`done`,detail:t}:e));let n=await J(s.cwd,{[o.envVarName]:m},{beforeWrite:p});if((n.addedKeys.length>0||n.updatedKeys.length>0)&&c.recordChangedPaths?.([n.file]),c.setTasks(e=>e.map(e=>e.id===`env`?{...e,status:`done`,detail:`${n.addedKeys.length} key(s) added`}:e)),!s.skipMcp&&u){let e=await Y({accessToken:u.accessToken}).catch(e=>({installed:[],skipped:[],errors:[{client:`mcp`,message:e.message}]}));c.setTasks(t=>t.map(t=>t.id===`mcp`?{...t,status:`done`,detail:yr(e)}:t))}else c.setTasks(e=>e.map(e=>e.id===`mcp`?{...e,status:`done`,detail:`skipped`}:e));await br(s.cwd,m,c),c.setTasks(e=>e.map(e=>e.id===`verify`?{...e,status:`done`}:e)),c.setSandboxStats?.({reads:1,writes:e.installed.length,rounds:0}),await gr(s,m,c,p),c.setPhase(`install-complete`);return}c.setLiveLine(`Custom Next.js structure — handing off to the AI agent…`)}let g=o.id===`plain-html`;if(g){c.setTasks([{id:`detect`,label:`Detect framework`,status:`done`,detail:`Plain HTML`},{id:`read`,label:`Scan .html pages`,status:`active`},{id:`write`,label:`Insert tracker <script>`,status:`pending`},{id:`env`,label:`Write env vars`,status:`pending`},{id:`mcp`,label:`Install MCP clients (Claude Code/Cursor/VS Code)`,status:`pending`},{id:`verify`,label:`Verify the tracker in your source`,status:`pending`}]),c.setLiveLine(`Plain HTML — using fast install path (no AI needed)…`);let e=await Gt({cwd:s.cwd,trackingCode:m,updateOnly:h.recommendation===`update-tracking-code`,beforeWrite:p});if(c.recordChangedPaths?.(e.installed),e.installed.length===0&&e.errors.length===0&&e.skipped.length===0)throw Error(`No .html files with a <head>...</head> block were found to inject the tracker into.`);if(e.installed.length===0&&e.errors.length>0)throw Error(`Programmatic install failed for all ${e.errors.length} file(s). First error: ${e.errors[0].file}: ${e.errors[0].error}`);c.setTasks(t=>t.map(t=>t.id===`read`||t.id===`write`?{...t,status:`done`,detail:`${e.installed.length} file(s)`}:t)),c.setLiveLine(`Tracker added to ${e.installed.length} file(s). Skipped ${e.skipped.length}, errored ${e.errors.length}.`);let t=await J(s.cwd,{[o.envVarName]:m},{beforeWrite:p});if((t.addedKeys.length>0||t.updatedKeys.length>0)&&c.recordChangedPaths?.([t.file]),c.setTasks(e=>e.map(e=>e.id===`env`?{...e,status:`done`,detail:`${t.addedKeys.length} key(s) added`}:e)),!s.skipMcp&&u){let e=await Y({accessToken:u.accessToken}).catch(e=>({installed:[],skipped:[],errors:[{client:`mcp`,message:e.message}]}));c.setTasks(t=>t.map(t=>t.id===`mcp`?{...t,status:`done`,detail:yr(e)}:t))}else c.setTasks(e=>e.map(e=>e.id===`mcp`?{...e,status:`done`,detail:`skipped`}:e));await br(s.cwd,m,c),c.setSandboxStats?.({reads:e.installed.length,writes:e.installed.length,rounds:0}),await gr(s,m,c,p),c.setPhase(`install-complete`);return}{let e=await sn({cwd:s.cwd,trackingCode:m,siteId:r.id,adapter:o,beforeWrite:p});c.recordChangedPaths?.(e.installed);let t=e.skipped.some(e=>/already installed|tracker present/i.test(e.reason));if(!e.fellThrough&&e.errors.length===0&&(e.installed.length>0||t)){c.setTasks([{id:`detect`,label:`Detect framework`,status:`done`,detail:o.displayName},{id:`write`,label:`Insert tracker snippet`,status:`done`,detail:e.installed[0]??`already installed`},{id:`env`,label:`Write env vars (.env.local)`,status:`active`},{id:`mcp`,label:`Install MCP clients (Claude Code/Cursor/VS Code)`,status:`pending`},{id:`verify`,label:`Verify the tracker in your source`,status:`pending`}]),c.setLiveLine(`${o.displayName} — using fast install path (no AI needed)…`);let t=await J(s.cwd,{[o.envVarName]:m},{beforeWrite:p});if((t.addedKeys.length>0||t.updatedKeys.length>0)&&c.recordChangedPaths?.([t.file]),c.setTasks(e=>e.map(e=>e.id===`env`?{...e,status:`done`,detail:`${t.addedKeys.length} key(s) added`}:e)),!s.skipMcp&&u){let e=await Y({accessToken:u.accessToken}).catch(e=>({installed:[],skipped:[],errors:[{client:`mcp`,message:e.message}]}));c.setTasks(t=>t.map(t=>t.id===`mcp`?{...t,status:`done`,detail:yr(e)}:t))}else c.setTasks(e=>e.map(e=>e.id===`mcp`?{...e,status:`done`,detail:`skipped`}:e));await br(s.cwd,m,c),c.setTasks(e=>e.map(e=>e.id===`verify`?{...e,status:`done`}:e)),c.setSandboxStats?.({reads:1,writes:e.installed.length,rounds:0}),await gr(s,m,c,p),c.setPhase(`install-complete`);return}c.setLiveLine(`${o.displayName} needs a closer look — using the AI installer (a bit slower than the fast path)…`)}let _=o.buildSnippets({trackingCode:m,siteId:r.id}),v=`Install Zenovay tracking into this ${o.displayName} project.\nSite: ${r.name} (trackingCode: ${m}).\n1. Call detect_framework to confirm the framework.\n2. Read the entry file(s) for this framework:\n`+o.files.map(e=>` - ${e.path}`).join(`
327
- `)+`
328
- 3. Insert the tracker using the snippet below.
329
- 4. Confirm the change with a diff before writing.
330
-
331
- Snippet reference (anchored by anchorKind — adapt to the actual file):
332
- `+_.map(e=>` ${e.anchorKind} @ ${e.targetPath}:\n ${e.code.replace(/\n/g,`
333
- `)}`).join(`
334
-
335
- `);c.setTasks([{id:`detect`,label:`Detect framework`,status:`active`},{id:`read`,label:`Read project entry files`,status:`pending`},{id:`write`,label:`Insert tracker snippet`,status:`pending`},{id:`env`,label:`Write env vars (.env.local)`,status:`pending`},{id:`mcp`,label:`Install MCP clients (Claude Code/Cursor/VS Code)`,status:`pending`},{id:`verify`,label:`Wait for first event`,status:`pending`}]);let y=(e,t,n)=>{c.setTasks(r=>r.map(r=>r.id===e?{...r,status:t,detail:n??r.detail}:r))},b=Ln({mode:In(s)});c.registerBridge(b);let x=b.subscribe(e=>c.setPendingApproval(e)),S=null,C=``,w=0;try{await Bt({api:d,sandbox:f,approval:b,prompter:{async ask({question:e}){return e}},handlers:{onToolStart:({name:e})=>{e===`detect_framework`?(y(`detect`,`active`),c.setLiveLine(`Inspecting package.json + config files…`)):e===`read_file`?(y(`detect`,`done`),y(`read`,`active`)):(e===`write_file`||e===`patch_file`)&&(y(`read`,`done`),y(`write`,`active`))},onToolResult:({name:e,result:t})=>{let n=t?.ok!==!1,r=t?.content??{};e===`detect_framework`&&n&&(y(`detect`,`done`,o.displayName),c.setLiveLine(`Detected ${o.displayName}`)),e===`read_file`&&n&&r.path&&c.setLiveLine(`Read ${r.path}`),(e===`write_file`||e===`patch_file`)&&n&&r.path&&(y(`read`,`done`),y(`write`,`done`,`wrote ${r.path}`),c.setLiveLine(`Wrote ${r.path}`))},onDelta:e=>{C=(C+e).slice(-600);let t=Date.now();if(t-w<280)return;w=t;let n=C.replace(/\s+/g,` `).trim().slice(-80);n.length>4&&c.setLiveLine(n)}},initialMessages:[{role:`user`,content:v}],diagnosis:h,targetTrackingCode:m})}catch(e){S=e}finally{x(),c.setPendingApproval(null)}let T=f.stats();c.recordChangedPaths?.(T.writtenPaths);let E=T.writes>0?await a(s.cwd,m).catch(()=>null):null,D=Ut(T,E?.foundTrackingCodes??[],m,S);if(!D.ok)throw Error(D.error);y(`write`,`done`),y(`env`,`active`),c.setLiveLine(`Adding env var to .env.local`);let O=await J(s.cwd,{[o.envVarName]:m},{beforeWrite:p});if((O.addedKeys.length>0||O.updatedKeys.length>0)&&c.recordChangedPaths?.([O.file]),y(`env`,`done`,`${O.addedKeys.length} key(s) added`),!s.skipMcp&&u){y(`mcp`,`active`),c.setLiveLine(`Detecting Cursor / Claude Desktop / VS Code…`);let e=await Y({accessToken:u.accessToken}).catch(e=>({installed:[],skipped:[],errors:[{client:`mcp`,message:e.message}]}));y(`mcp`,`done`,yr(e))}else y(`mcp`,`done`,`skipped`);c.setTasks(e=>e.map(e=>e.id===`detect`||e.id===`read`||e.id===`write`?{...e,status:e.status===`pending`?`done`:e.status}:e)),await br(s.cwd,m,c),c.setSandboxStats?.(T),await gr(s,m,c,p),c.setPhase(`install-complete`)}catch(e){c.setErrorMsg(e.message),c.setPhase(`error`)}}const Sr=()=>{let{theme:e}=g();return N.createElement(h,{title:`Zenovay wants to set up your project`,state:`idle`},N.createElement(A,null,`We'll use AI to analyze your codebase and add the Zenovay tracker.`),N.createElement(A,{color:e.muted},`.env* contents stay on your machine. Only framework metadata reaches api.zenovay.com.`))},Cr=({siteName:e,note:t,onChoose:n})=>{let{theme:r}=g(),i=[{label:`Cloudflare Pages`,value:`cloudflare-pages`,description:`writes functions/api/_z/[[path]].ts`},{label:`Vercel`,value:`vercel`,description:`adds a vercel.json rewrite`},{label:`Netlify`,value:`netlify`,description:`adds a _redirects rule`},{label:`Next.js (self-hosted)`,value:`nextjs-server`,description:`adds a next.config rewrite`},{label:`Skip — standard tracking only`,value:`skip`,description:`already works in Chrome, Firefox and most browsers`}];return N.createElement(k,{flexDirection:`column`,paddingX:2,paddingTop:1},N.createElement(A,{bold:!0},`Count visitors in every browser?`),t?N.createElement(A,{color:r.warn},t):null,N.createElement(A,{color:r.muted},`Your tracker already works. Safari, Edge and Brave block analytics loaded from another domain — serving Zenovay from your own domain fixes that. Where is `,e,` deployed?`),N.createElement(k,{marginTop:1},N.createElement(y,{items:i,onSelect:e=>n(e===`skip`?null:e)})))},wr=({adapter:e,site:t,tasks:n,liveLine:r,pendingApproval:i,onApprove:a,pendingHostChoice:o,hostChoiceNote:s,onHostChoice:c})=>{let{theme:l}=g(),u=process.stdout.columns??100,d=(process.stdout.rows??30)-8,f=Math.floor(u/2)-1,p=Math.max(14,d);return N.createElement(k,{flexDirection:`column`},N.createElement(k,{flexDirection:`row`,minHeight:p,borderStyle:`round`,borderColor:l.border},N.createElement(k,{width:f,flexDirection:`column`},N.createElement(Gn,{width:f,height:p})),N.createElement(k,{width:1,flexDirection:`column`},N.createElement(A,{color:l.border},`│`)),N.createElement(k,{width:f,flexDirection:`column`},i?N.createElement(k,{flexDirection:`column`,paddingX:2,paddingTop:1},N.createElement(A,{color:l.warn},`The agent wants to write `,i.path),i.reason?N.createElement(A,{color:l.muted},i.reason):null,N.createElement(_,{key:i.id,filePath:i.path,oldContent:i.oldContent,newContent:i.newContent,onApprove:a})):o&&c?N.createElement(Cr,{siteName:t.name,note:s,onChoose:c}):N.createElement(N.Fragment,null,N.createElement(k,{paddingX:2,paddingTop:1},N.createElement(v,{done:n.filter(e=>e.status===`done`).length,total:n.length,label:n.find(e=>e.status===`active`)?.label})),N.createElement(Jn,{tasks:n,liveLine:r,width:f,height:p})))),N.createElement(k,{marginTop:1},N.createElement(A,{color:l.muted},`Site: `,t.name,` · code: `,t.trackingCode??t.id,` · Framework: `,e.displayName)))},Tr=({site:e,onContinueSetup:t,onReinstall:n,onExit:r})=>{let{theme:i}=g();j((e,i)=>{let a=e.toLowerCase();if(a===`q`||i.escape){r();return}if(a===`r`){n();return}if(a===`c`||i.return){t();return}});let a=e.url.replace(/^https?:\/\//,``).replace(/\/$/,``);return N.createElement(h,{title:`Already installed`,state:`ok`},N.createElement(k,{flexDirection:`column`,gap:1},N.createElement(k,{flexDirection:`row`,gap:1},N.createElement(A,{color:i.success},`✓`),N.createElement(A,{bold:!0},e.name),N.createElement(A,{color:i.muted},`(`,a,`)`)),N.createElement(A,{color:i.muted},`Zenovay is installed in this project. Verify the live site to continue setup.`),e.trackingCode?N.createElement(A,{color:i.dim},`tracking code: `,e.trackingCode):null,N.createElement(k,{marginTop:1,flexDirection:`column`},N.createElement(A,null,N.createElement(A,{color:i.accent},`[Enter]`),` Verify the live site and continue setup`),N.createElement(A,null,N.createElement(A,{color:i.accent},`[R]`),` Reinstall or choose a different site`))))},Er=({sites:e,preselectHint:t,onPick:n})=>{let r=Xn(e,t),i=e.filter(e=>e.id!==r?.id),a=r?[r,...i]:i,o=[...a.map(e=>({label:Lr(e,e.id===r?.id),value:e,description:e.trackingCode?`trackingCode: ${e.trackingCode}`:void 0})),{label:`+ Create new site on app.zenovay.com`,value:`create-new`,description:`Open the dashboard to add a new website`}];return N.createElement(h,{title:t?`Pick a site (best match: ${t})`:`Pick a site`,state:`idle`},N.createElement(y,{items:o,onSelect:n}))};function Dr(){let e=process.argv[1]??``;return e.includes(`/_npx/`)||e.includes(`\\_npx\\`)||process.env.npm_execpath?.includes(`npx`)?`npx`:`global`}const Or=({k:e,primary:t})=>{let{theme:n}=g();return N.createElement(A,null,N.createElement(A,{color:n.muted},`[`),N.createElement(A,{bold:!0,color:t?n.accent:n.fg},e),N.createElement(A,{color:n.muted},`] `))},kr=({adapter:e,site:t,stats:n,outcome:i,dashboardUrl:a,firstParty:o,onPick:s})=>{let{theme:l}=g(),u=Dr(),d=u===`npx`?`npx @zenovay/cli`:`zenovay`,f=a??r(t),p=i===`verified`,m=p?`You’re live on Zenovay`:i===`unverified`?`Tracker installed — not yet verified`:`Tracker installed — verification skipped`,_=p?`✓ First event received from ${t.name}`:i===`unverified`?`Installation finished, but no new event was confirmed.`:`Installation finished without checking for a new event.`,v=n&&n.rounds>0?`${n.writes} file(s) · ${n.rounds} agent round(s)`:n&&n.writes>0?`${n.writes} file(s) · programmatic (no AI calls)`:null;return j((e,t)=>{let n=e.toLowerCase();n===`o`?c(f):n===`q`||t.escape||n===`s`?s(`quit`):p&&(n===`w`||t.return)?s(`watch`):p&&n===`e`?s(`events`):!p&&t.return&&s(`quit`)},{isActive:!0}),N.createElement(h,{title:m,state:p?`ok`:`warn`},N.createElement(A,{bold:!0,color:p?l.success:l.warn},_),N.createElement(A,{color:l.accent},`─`.repeat(18)),N.createElement(k,{marginTop:1,flexDirection:`column`},N.createElement(Q,{label:`Framework`,value:e.displayName}),N.createElement(Q,{label:`Site`,value:N.createElement(Fn,{url:t.url,label:t.name})}),t.trackingCode?N.createElement(Q,{label:`Tracker`,value:N.createElement(A,{color:l.muted},t.trackingCode)}):N.createElement(Q,{label:`Tracker`,value:N.createElement(A,{color:l.warn},t.id,` (using site ID — verify in dashboard)`)}),v?N.createElement(Q,{label:`Changes`,value:N.createElement(A,{color:l.muted},v)}):null,p?null:N.createElement(Q,{label:`Verification`,value:N.createElement(A,{color:l.warn},i===`unverified`?`No event confirmed`:`Skipped`)}),N.createElement(Q,{label:`Dashboard`,value:N.createElement(Fn,{url:f})})),o&&o.proxyFile&&o.proxyAction!==`manual`&&o.proxyAction!==`skipped`?N.createElement(k,{marginTop:1},N.createElement(A,{color:l.success},`✓ `),N.createElement(A,{color:l.muted},`Analytics now load from your own domain — after you deploy, Safari, Edge and Brave visitors are counted too.`)):o?.manual?N.createElement(k,{marginTop:1,flexDirection:`column`},N.createElement(A,{color:l.muted},`Counting visitors in every browser (optional):`),N.createElement(A,{color:l.muted},` `,o.manual)):null,N.createElement(k,{marginTop:1,flexDirection:`column`},N.createElement(A,{color:l.dim},`Next steps`),p?N.createElement(k,{marginTop:1},N.createElement(A,null,` `),N.createElement(Or,{k:`W`,primary:!0}),N.createElement(A,null,`Watch live in this terminal `),N.createElement(A,{color:l.muted},`— visitors, pages, sources, vitals`)):null,N.createElement(k,null,N.createElement(A,null,` `),N.createElement(Or,{k:`O`}),N.createElement(A,null,`Open the dashboard in your browser`)),p?N.createElement(k,null,N.createElement(A,null,` `),N.createElement(Or,{k:`E`}),N.createElement(A,null,`Stream events as they fire `),N.createElement(A,{color:l.muted},`— page views, custom events, live`)):null,N.createElement(k,null,N.createElement(A,null,` `),N.createElement(Or,{k:`S`}),N.createElement(A,null,`Exit to shell`))),u===`npx`?N.createElement(k,{marginTop:1,flexDirection:`column`,borderStyle:`single`,borderColor:l.warn,paddingX:1},N.createElement(A,{color:l.warn,bold:!0},`Heads up — you ran via npx`),N.createElement(A,{color:l.muted},"The `zenovay` command isn’t on your PATH yet. After you exit, run:"),N.createElement(k,{marginTop:1},N.createElement(A,{color:l.fg},` npm i -g @zenovay/cli `),N.createElement(A,{color:l.muted},"→ then `zenovay overview` works directly"))):N.createElement(k,{marginTop:1},N.createElement(A,{color:l.muted},`From your shell: `),N.createElement(A,{color:l.fg},d,` overview`),N.createElement(A,{color:l.muted},` · `),N.createElement(A,{color:l.fg},d,` --help`)))},Ar=({cwd:e,adapter:t,site:n,stats:r,verify:i,firstParty:a,onCommit:o,onSkipCommit:s,onQuit:c})=>{let{theme:l}=g();return Ir((e,t)=>{e===`q`||e===`Q`||t.escape?c():e===`y`||e===`Y`||t.return?o():(e===`n`||e===`N`||e===`s`||e===`S`)&&s()}),N.createElement(h,{title:`Tracker installed`,state:i&&!i.ok?`warn`:`ok`},i?N.createElement(A,null,N.createElement(A,{color:i.ok?l.success:l.warn},i.ok?`✔ Verified — `:`⚠ `),i.detail):N.createElement(A,null,N.createElement(A,{color:l.success},`✔ `),`The Zenovay tracker is in your project.`),N.createElement(k,{marginTop:1},N.createElement(A,{color:l.muted},`Framework: `),N.createElement(A,null,t.displayName)),N.createElement(k,null,N.createElement(A,{color:l.muted},`Site: `),N.createElement(A,null,n.name,` (`,n.url,`)`)),r&&N.createElement(k,null,N.createElement(A,{color:l.muted},`Modified: `),N.createElement(A,null,r.writes,` file(s)`)),N.createElement(jr,{cwd:e,firstParty:a}),N.createElement(k,{marginTop:1},N.createElement(A,null,`Commit + push these changes to git? `),N.createElement(A,{color:l.accent},`[Y/n]`)))},jr=({cwd:e,firstParty:t})=>{let{theme:n}=g();if(!t)return null;let r=t.proxyFile&&t.proxyAction!==`manual`&&t.proxyAction!==`skipped`?t.proxyFile:null;return r?N.createElement(k,{marginTop:1,flexDirection:`column`},N.createElement(k,null,N.createElement(A,{color:n.success},`✔ `),N.createElement(A,null,`Analytics now load from your own domain `),N.createElement(A,{color:n.muted},`(`,_r(e,r),`)`)),N.createElement(A,{color:n.muted},`After you deploy, Safari, Edge and Brave visitors are counted too.`)):t.manual?N.createElement(k,{marginTop:1,flexDirection:`column`},N.createElement(k,null,N.createElement(A,{color:n.muted},`Counting visitors in every browser (optional):`)),N.createElement(A,{color:n.muted},t.manual)):null},Mr=({cwd:e,baseline:t,changedPaths:n,onDone:r,onError:i})=>{let{theme:a}=g(),[o,s]=I(`committing`),[c,l]=I(`Checking the Zenovay file journal…`),u=F(!1);return P(()=>{u.current||(u.current=!0,(async()=>{try{let i=await ir({cwd:e,baseline:t,changedPaths:n,onDetail:e=>l(e),onPhase:e=>s(e)});s(`done`),l(i.message),setTimeout(()=>r(i),800)}catch(e){i(e.message)}})())},[t,n,e,r,i]),N.createElement(h,{title:`Committing to git`,state:`busy`},N.createElement(k,null,o===`done`?N.createElement(A,{color:a.success},`✓`):N.createElement(A,{color:a.accent},N.createElement(L,{type:`dots`})),N.createElement(A,null,` `,o===`pushing`?`Pushing to origin…`:o===`done`?`Git step finished`:`Committing…`)),N.createElement(k,{marginTop:1},N.createElement(A,{color:a.muted},c)))},Nr=({site:e,notice:t,onDeployed:n,onSkip:r,onQuit:i})=>{let{theme:a}=g();return Ir((e,t)=>{e===`q`||e===`Q`||t.escape?i():e===`y`||e===`Y`||t.return||e===`d`||e===`D`?n():(e===`n`||e===`N`||e===`s`||e===`S`)&&r()}),N.createElement(h,{title:`Ready to deploy?`,state:`idle`},N.createElement(A,null,`The tracker is installed locally. To capture events you need it on the live site:`),N.createElement(A,null,` `),N.createElement(k,null,N.createElement(A,{color:a.muted},` → `),N.createElement(Fn,{url:e.url})),N.createElement(A,null,` `),N.createElement(A,{color:a.muted},`Push the change through your normal deploy pipeline (Vercel auto-deploy, CI/CD, etc.).`),t?N.createElement(k,{marginTop:1},N.createElement(A,{color:a.warn},t)):null,N.createElement(k,{marginTop:1},N.createElement(A,null,`Once it’s deployed, press `),N.createElement(A,{color:a.accent},`[Y]`),N.createElement(A,null,` to verify the tracker is firing. `),N.createElement(A,{color:a.muted},`[s] skip verification`)))},Pr=({site:e,onContinue:t,onQuit:n})=>{let{theme:r}=g();return Ir((e,r)=>{e===`q`||e===`Q`||r.escape?n():t()}),N.createElement(h,{title:`Visit your site`,state:`idle`},N.createElement(A,null,`To send a test event, open any page on your site:`),N.createElement(A,null,` `),N.createElement(k,null,N.createElement(A,{color:r.muted},` → `),N.createElement(Fn,{url:e.url})),N.createElement(A,null,` `),N.createElement(A,{color:r.muted},`The tracker fires automatically on page load. We’ll verify the next event arrives.`),N.createElement(k,{marginTop:1},N.createElement(A,null,`Press `),N.createElement(A,{color:r.accent},`[any key]`),N.createElement(A,null,` when you’ve visited the page.`)))},Fr=({site:t,since:r,elapsed:a,onTick:o,onArrived:s,onTimeout:c,onSkip:l,onQuit:u})=>{let{theme:d}=g(),[f,p]=I(`preflight`),[m,_]=I(``),[v,y]=I([]),b=F(!1),x=t.trackingCode??t.id,S=async()=>{p(`preflight`),_(`Fetching ${t.url}…`);let e=await dr(t.url,x);if(b.current)return;if(e.state===`tracker-correct`){p(`polling`),_(`Tracker detected on live site — waiting for first hit…`),C();return}if(e.state===`tracker-wrong-id`){p(`wrong-id-on-live`),y(e.foundCodes),_(`Live site has Zenovay but with id(s): ${e.foundCodes.join(`, `)}`);return}if(e.state===`proxy-broken`){p(`proxy-broken`),_(`${e.detail} Route: ${e.scriptUrl}`);return}p(`awaiting-deploy`);let n=e.networkError?/enotfound|getaddrinfo|dns/i.test(e.networkError)?` (DNS lookup failed — check the site URL is correct + deployed)`:/timeout|etimedout|abort|econnrefused|network/i.test(e.networkError)?` (check your internet connection, then retry with [r])`:``:``;_(e.networkError?`Couldn’t reach ${t.url}: ${e.networkError}${n}`:e.httpStatus?`${t.url} returned HTTP ${e.httpStatus}`:`No Zenovay tracker found on ${t.url}.`)},C=async()=>{try{let a=await e(),c=await i({strict:!1}),l=new n({config:a,cliVersion:`0`,token:c}),u=await Dt(t.id,r,{api:l,timeoutMs:6e4,pollIntervalMs:2500,onTick:e=>{b.current||o(e)}});if(b.current)return;u.received?(p(`success`),s()):p(`timeout`)}catch{b.current||p(`timeout`)}};P(()=>(b.current=!1,S(),()=>{b.current=!0}),[]),j((e,t)=>{if(e===`q`||e===`Q`||t.escape){u();return}if(e===`s`||e===`S`){f===`timeout`?c():f!==`success`&&l();return}(f===`awaiting-deploy`||f===`wrong-id-on-live`||f===`proxy-broken`||f===`timeout`)&&(e===`r`||e===`R`)&&S()},{isActive:!0});let w=Math.floor(a/1e3);return f===`preflight`?N.createElement(h,{title:`Verifying`,state:`busy`},N.createElement(k,null,N.createElement(A,{color:d.accent},N.createElement(L,{type:`dots`})),N.createElement(A,null,` Checking your live site for the tracker…`)),N.createElement(k,{marginTop:1},N.createElement(A,{color:d.muted},m))):f===`awaiting-deploy`?N.createElement(h,{title:`Tracker not yet on your live site`,state:`warn`},N.createElement(A,{color:d.warn},m),N.createElement(k,{marginTop:1,flexDirection:`column`},N.createElement(A,null,`The tracker is in your local repo but hasn’t been deployed yet.`),N.createElement(A,{color:d.muted},`Push your changes and wait for your deploy to finish (Vercel / Cloudflare Pages / CI), then retry.`)),N.createElement(k,{marginTop:1},N.createElement(A,null,`Press `),N.createElement(A,{color:d.accent},`[r]`),N.createElement(A,null,` to re-check, `),N.createElement(A,{color:d.accent},`[s]`),N.createElement(A,null,` to skip verification.`))):f===`wrong-id-on-live`?N.createElement(h,{title:`Live site has a different tracking code`,state:`warn`},N.createElement(A,{color:d.warn},`Expected: `,N.createElement(A,{color:d.accent},x),` `,`Found on live: `,N.createElement(A,{color:d.accent},v.join(`, `))),N.createElement(k,{marginTop:1,flexDirection:`column`},N.createElement(A,null,`Your local install uses a different ID than what’s on `,t.url,`.`),N.createElement(A,{color:d.muted},`Deploy the new local version, then retry — or skip if the existing ID is intentional.`)),N.createElement(k,{marginTop:1},N.createElement(A,null,`Press `),N.createElement(A,{color:d.accent},`[r]`),N.createElement(A,null,` to re-check, `),N.createElement(A,{color:d.accent},`[s]`),N.createElement(A,null,` to skip.`))):f===`proxy-broken`?N.createElement(h,{title:`First-party proxy is not working`,state:`warn`},N.createElement(A,{color:d.warn},m),N.createElement(k,{marginTop:1,flexDirection:`column`},N.createElement(A,null,`The tracker tag is deployed, but its same-origin script route did not return the Zenovay JavaScript.`),N.createElement(A,{color:d.muted},`Check the host rewrite or function route, deploy the fix, then retry.`)),N.createElement(k,{marginTop:1},N.createElement(A,null,`Press `),N.createElement(A,{color:d.accent},`[r]`),N.createElement(A,null,` to re-check, `),N.createElement(A,{color:d.accent},`[s]`),N.createElement(A,null,` to skip.`))):f===`timeout`?N.createElement(h,{title:`No event arrived in 1 minute`,state:`warn`},N.createElement(A,{color:d.warn},`The tracker is on your live site but no hits reached api.zenovay.com.`),N.createElement(k,{marginTop:1},N.createElement(A,{color:d.muted},`Try opening `,t.url,` in a fresh browser tab (no ad-blocker), then retry.`)),N.createElement(k,{marginTop:1},N.createElement(A,null,`Press `),N.createElement(A,{color:d.accent},`[r]`),N.createElement(A,null,` to re-check, `),N.createElement(A,{color:d.accent},`[s]`),N.createElement(A,null,` to finish without verification.`))):f===`success`?N.createElement(h,{title:`First event received`,state:`busy`},N.createElement(k,null,N.createElement(A,{color:d.success},`✓`),N.createElement(A,null,` Resolving your next setup step…`))):N.createElement(h,{title:`Waiting for first event`,state:`busy`},N.createElement(k,null,N.createElement(A,{color:d.accent},N.createElement(L,{type:`dots`})),N.createElement(A,null,` Polling api.zenovay.com for the first hit on `),N.createElement(A,{color:d.accent},t.url),N.createElement(A,null,` (`,w,`s elapsed)`)),N.createElement(k,{marginTop:1},N.createElement(A,{color:d.muted},`Reload the page if nothing arrives within ~30 seconds.`)))};function Ir(e){j((t,n)=>{e(t,{return:n.return,escape:n.escape})},{isActive:!0})}function Lr(e,t){let n=`${e.name}`.padEnd(30,` `).slice(0,30),r=e.url.replace(/^https?:\/\//,``).padEnd(28,` `).slice(0,28),i=t?` ← best match`:``;return`${n} ${r}${i}`}async function Rr(e){try{let t=await w.readFile(C.join(e,`package.json`),`utf8`),n=JSON.parse(t);if(n.name)return String(n.name).replace(/^@[^/]+\//,``)}catch{}try{let t=await w.readFile(C.join(e,`.git`,`config`),`utf8`),n=t.match(/url\s*=\s*.*[/:]([^/]+?)(?:\.git)?\s*$/m);if(n&&n[1])return n[1]}catch{}return C.basename(e)}export{Tr as AlreadyInstalledPanel,Cr as HostChoicePanel,fr as initCommand};