@zenovay/cli 1.0.27 → 1.0.31
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{ai-CDJBrlIj.js → ai-EujeaV4L.js} +1 -1
- package/dist/bin.js +10 -10
- package/dist/{ensure-latest-BfsWmA1w.js → ensure-latest-3A_-Fnvl.js} +1 -1
- package/dist/ensure-latest-DAiAIi4p.js +5 -0
- package/dist/{init-o7NcLZpL.js → init-BO0YSf9G.js} +18 -18
- package/dist/{init-Bw55rcHV.js → init-ZniT6LxK.js} +1 -1
- package/dist/{update-CXMG8g-D.js → update-CmdUMkfW.js} +1 -1
- package/dist/wizard-bin.js +1 -1
- package/package.json +2 -2
- package/dist/ensure-latest-CEFXfYj4.js +0 -5
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{readConfig as e}from"./config-JVhBplSX.js";import"./api-CBukwv2I.js";import{readToken as t}from"./token-store-CuZEiQNg.js";import{emit as n}from"./telemetry-BgkzI2cW.js";import{ApiV2Client as r}from"./api-v2--DPtrRGv.js";import{detectInstalled as i}from"./detect-installed-DpSaAeH-.js";import"./formatter-PBF-wEt1.js";import{emit$1 as a,isHeadless as o}from"./emit-5vELQfsB.js";import"./open-url-IjqD5f_n.js";import"./secrets-zGZxXoM0.js";import{initCommand as s}from"./init-
|
|
1
|
+
import{readConfig as e}from"./config-JVhBplSX.js";import"./api-CBukwv2I.js";import{readToken as t}from"./token-store-CuZEiQNg.js";import{emit as n}from"./telemetry-BgkzI2cW.js";import{ApiV2Client as r}from"./api-v2--DPtrRGv.js";import{detectInstalled as i}from"./detect-installed-DpSaAeH-.js";import"./formatter-PBF-wEt1.js";import{emit$1 as a,isHeadless as o}from"./emit-5vELQfsB.js";import"./open-url-IjqD5f_n.js";import"./secrets-zGZxXoM0.js";import{initCommand as s}from"./init-BO0YSf9G.js";import{parseSseStream as c}from"./client-DNMRt-Hq.js";import"./snippet-CwowVrmh.js";import"./login-vzW-8q0w.js";import"./theme-DSRmbn9T.js";import{Banner as l,Panel as u,useTheme as d}from"./panel-DbiZwGB3.js";import"./progress-row-BSv_Zm8f.js";import{Select as f}from"./prompt-Dae2nnYJ.js";import"./keybar-BY1csJGI.js";import"./sparkline-B7VaYaxH.js";import{ChatPanel as p}from"./chat-panel-DKVM8gnJ.js";import{resolveSiteId as m}from"./resolve-site-D8PIddP1.js";import{Box as h,Static as g,Text as _,render as v,useApp as y,useInput as ee}from"ink";import b,{useEffect as x,useRef as S,useState as C}from"react";import w from"ink-spinner";import T from"ink-text-input";const E=30,D=9e4;function O(e){return e.replace(/_/g,` `)}function k(e){if(!e)return``;let t=Object.entries(e).map(([e,t])=>`${e}: ${JSON.stringify(t)}`).join(`, `);return t.length>80?t.slice(0,77)+`…`:t}function A(e,t,n){if(t<=0)return{body:``,clipped:0};let r=e.split(`
|
|
2
2
|
`),i=[];for(let e of r)if(e.length<=n||n<=0)i.push(e);else for(let t=0;t<e.length;t+=n)i.push(e.slice(t,t+n));if(i.length<=t)return{body:e,clipped:0};let a=i.slice(i.length-t);return{body:a.join(`
|
|
3
3
|
`),clipped:i.length-t}}const j=({cliVersion:e,api:t,siteId:r,siteLabel:i,initialAllowAll:a=!1,onClose:o})=>{let{theme:s}=d(),{exit:f}=y(),[p,m]=C([]),[v,j]=C(``),[M,N]=C(!1),[P,F]=C(``),[I,L]=C([]),[R,z]=C(null),[B,V]=C(a),[H,U]=C(!1),[W,G]=C(0),K=S(``),q=S(null),J=S(Date.now());x(()=>{if(!M)return;let e=setInterval(()=>{K.current!==P&&F(K.current)},Math.floor(1e3/E));return()=>clearInterval(e)},[M,P]),x(()=>(n(`mcp.open`,{properties:{has_site:!!r}}),()=>{n(`mcp.close`,{duration_ms:Date.now()-J.current})}),[r]),ee((e,t)=>{if(t.escape||t.ctrl&&e===`c`){q.current?.abort(),o();return}if(e===`a`||e===`A`){V(!0),H&&U(!1);return}if(e===`x`||e===`X`){q.current?.abort(),z(`Cancelled.`),U(!1),N(!1);return}if((t.return||e===`y`||e===`Y`)&&H){U(!1);return}if((e===`n`||e===`N`)&&H){q.current?.abort(),z(`Cancelled by user.`),U(!1),N(!1);return}});let Y=async e=>{let i=e.trim();if(!i||M||H)return;j(``),z(null),m(e=>[...e,{role:`user`,content:i}]),K.current=``,F(``),L([]),G(0),N(!0),q.current=new AbortController;let a=setTimeout(()=>{q.current?.abort(),z(`Request timed out after ${D/1e3}s`)},D);try{let e=p.map(e=>({role:e.role,content:e.content}));e.push({role:`user`,content:i});let a=await t.openAiStream(`mcp`,{messages:e,siteId:r},q.current.signal);if(!a.ok){z(`MCP request failed (${a.status})`);return}let o=0,s=new Map;for await(let e of c(a))if(e.type===`delta`)K.current+=e.content;else if(e.type===`tool_call`)s.set(e.id,e.arguments),o+=1,G(o),n(`mcp.tool_call`,{properties:{tool_name:e.name}}),L(t=>[...t,{id:e.id,name:e.name,argsPreview:k(e.arguments),status:`running`}]);else if(e.type===`tool_start`){let t=s.get(e.id);L(r=>r.some(t=>t.id===e.id)?r:(o+=1,G(o),n(`mcp.tool_call`,{properties:{tool_name:e.name}}),[...r,{id:e.id,name:e.name,argsPreview:k(t),status:`running`}]))}else if(e.type===`tool_result`)L(t=>t.map(t=>t.id===e.id?{...t,status:e.error?`error`:`done`,result:e.summary,error:e.error,name:e.name??t.name}:t));else if(e.type===`done`){let e=K.current;m(t=>[...t,{role:`assistant`,content:e||``}]),o>0&&!B&&U(!0);break}else if(e.type===`error`){z(e.message);break}}catch(e){e.name!==`AbortError`&&z(e.message??`unknown error`)}finally{clearTimeout(a),K.current=``,F(``),N(!1),q.current=null}},X=[`mcp`,i].filter(Boolean).join(` · `),Z=process.stdout.rows??40,Q=Math.max(4,Z-16),te=Math.max(20,(process.stdout.columns??80)-4),$=A(P,Q,te);return b.createElement(h,{flexDirection:`column`},b.createElement(l,{version:e,subtitle:X}),p.length===0&&!M?b.createElement(h,{marginTop:1,marginLeft:2,flexDirection:`column`},b.createElement(_,{color:s.muted},`Describe what you want to create or change. Examples:`),b.createElement(h,{marginTop:0,flexDirection:`column`},b.createElement(_,{color:s.dim},` · "Create a goal for newsletter signups"`),b.createElement(_,{color:s.dim},` · "Add a funnel: landing page → signup → dashboard"`),b.createElement(_,{color:s.dim},` · "Annotate today with our product launch"`),b.createElement(_,{color:s.dim},` · "Set up uptime monitoring for /api/health"`)),b.createElement(h,{marginTop:1},b.createElement(_,{color:s.dim},`MCP actions execute server-side. `),b.createElement(_,{color:s.warn},`Review each turn before continuing.`)),b.createElement(h,{marginTop:0,flexDirection:`row`},b.createElement(_,{color:s.accent},`[a]`),b.createElement(_,{color:s.dim},` allow-all · `),b.createElement(_,{color:s.accent},`[Esc]`),b.createElement(_,{color:s.dim},` close`))):null,b.createElement(g,{items:p},(e,t)=>b.createElement(h,{key:t,marginTop:1},b.createElement(u,{title:e.role===`user`?`you`:`Zenovay MCP`,pillColor:e.role===`user`?s.accent:s.info,state:`idle`},b.createElement(_,{color:s.fg,wrap:`wrap`},e.content)))),M?b.createElement(h,{flexDirection:`column`},I.length>0?b.createElement(h,{marginTop:1},b.createElement(u,{title:`Actions${B?` (allow-all)`:``}`,state:I.some(e=>e.status===`running`)?`busy`:`ok`},I.map(e=>b.createElement(h,{key:e.id,flexDirection:`column`,marginBottom:0},b.createElement(h,{flexDirection:`row`},b.createElement(_,{color:e.status===`error`?s.error:e.status===`done`?s.success:s.accent},e.status===`done`?`✓ `:e.status===`error`?`✗ `:`⋯ `),b.createElement(_,{color:s.fg,bold:!0},O(e.name))),e.argsPreview?b.createElement(h,{marginLeft:2},b.createElement(_,{color:s.dim},e.argsPreview)):null,e.status===`done`&&e.result?b.createElement(h,{marginLeft:2},b.createElement(_,{color:s.dim},`→ `,e.result.slice(0,80))):null,e.status===`error`&&e.error?b.createElement(h,{marginLeft:2},b.createElement(_,{color:s.error},`✗ `,e.error.slice(0,80))):null)))):null,P.length>0?b.createElement(h,{marginTop:1},b.createElement(u,{title:`Zenovay MCP`,pillColor:s.info,state:`busy`},$.clipped>0?b.createElement(_,{color:s.dim},` …${$.clipped} earlier line${$.clipped===1?``:`s`} above`):null,b.createElement(_,{color:s.fg,wrap:`wrap`},$.body))):I.every(e=>e.status!==`running`)||I.length===0?b.createElement(h,{marginTop:1,marginLeft:2,flexDirection:`row`},b.createElement(_,{color:s.accent},b.createElement(w,{type:`dots`})),b.createElement(_,{color:s.muted},` Planning actions…`)):null):null,H&&!M?b.createElement(h,{marginTop:1},b.createElement(u,{title:`Continue?`,state:`warn`,pillColor:s.warn},b.createElement(_,{color:s.muted},W,` action`,W===1?``:`s`,` executed this turn. Send another message?`),b.createElement(h,{marginTop:1,flexDirection:`row`},b.createElement(_,{color:s.success},`[Enter / y] `),b.createElement(_,{color:s.dim},`continue `),b.createElement(_,{color:s.error},`[n] `),b.createElement(_,{color:s.dim},`cancel `),b.createElement(_,{color:s.accent},`[a] `),b.createElement(_,{color:s.dim},`allow-all this session `),b.createElement(_,{color:s.warn},`[x] `),b.createElement(_,{color:s.dim},`abort`)))):null,R?b.createElement(h,{marginTop:1,marginLeft:2},b.createElement(_,{color:s.error},`✗ `,R)):null,b.createElement(h,{marginTop:1,marginLeft:2,flexDirection:`column`},b.createElement(h,{flexDirection:`row`},b.createElement(_,{color:M||H?s.dim:s.accent},M?`⋯ `:H?`? `:`> `),b.createElement(T,{value:v,onChange:j,onSubmit:e=>void Y(e),placeholder:M?`executing…`:H?`press Enter to continue, n to cancel…`:`describe what to create or change…`})),b.createElement(h,{marginTop:1,flexDirection:`row`},b.createElement(_,{color:s.dim},`[Enter] send [a] allow-all [x] abort [Esc] close`),B?b.createElement(_,{color:s.success},` ● allow-all`):null)))};async function M(e){if((o(e)||!process.stdin.isTTY)&&e.mode!==`install`)return a({type:`error`,code:`interactive_only`,message:`zenovay ai is interactive; run without --json in a TTY`}),2;let t=await i(e.cwd),n;if(e.mode)n=e.mode;else if(!t.installed)n=`install`;else if(o(e))return a({type:`error`,code:`no_mode`,message:`Headless mode requires --mode chat|mcp|install`}),2;else n=await N(t,e.cliVersion);return n===`install`?s({cliVersion:e.cliVersion,cwd:e.cwd,json:e.json}):n===`chat`?P(e):F(e)}async function N(e,t){return new Promise(n=>{let r=[{label:`Chat with your analytics`,value:`chat`,description:`Ask natural-language questions about your data`},{label:`Manage via MCP`,value:`mcp`,description:`Create goals, funnels, sites, etc. in plain English`},{label:`Re-run install / repair`,value:`install`,description:`Run the install wizard again`}],i=e.packageMarker?`detected · ${e.packageMarker}`:`detected`,{unmount:a}=v(b.createElement(h,{flexDirection:`column`},b.createElement(l,{version:t,subtitle:`ai · ${i}`,live:!1}),b.createElement(h,{marginTop:1},b.createElement(u,{title:`Zenovay AI assistant`,state:`idle`},b.createElement(_,null,`What do you want to do?`))),b.createElement(h,{marginTop:1},b.createElement(f,{items:r,onSelect:e=>{a(),n(e)}}))))})}async function P(n){let i=await e(),a=await t({strict:!1});if(!a)return process.stderr.write("Not logged in — run `zenovay login` first.\n"),2;let o=i.defaultSiteId,s=i.defaultSiteName,c=new r({config:i,cliVersion:n.cliVersion,token:a});return new Promise(e=>{let{unmount:t}=v(b.createElement(p,{cliVersion:n.cliVersion,api:c,dashboardContext:{commandName:`ai chat`,siteId:o,siteLabel:s,metricsSnapshot:null},onClose:()=>{t(),e(0)}}))})}async function F(n){let i=await e(),a=await t({strict:!1});if(!a)return process.stderr.write("Not logged in — run `zenovay login` first.\n"),2;let o=new r({config:i,cliVersion:n.cliVersion,token:a}),s,c;try{let e=await m(o,{explicit:void 0,headless:!1,cliVersion:n.cliVersion});s=e.siteId,c=e.site?.url?e.site.url.replace(/^https?:\/\//,``).replace(/\/$/,``):e.site?.name??s}catch{}return new Promise(e=>{let{unmount:t}=v(b.createElement(j,{cliVersion:n.cliVersion,api:o,siteId:s,siteLabel:c,onClose:()=>{t(),e(0)}}))})}export{M as aiCommand};
|
package/dist/bin.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{configDir as e}from"./config-JVhBplSX.js";import"./check-D9G0N7NB.js";import{ensureLatest as
|
|
2
|
+
import{configDir as e}from"./config-JVhBplSX.js";import"./check-D9G0N7NB.js";import{cleanupStaleUpdateBackups as t,ensureLatest as n}from"./ensure-latest-DAiAIi4p.js";import"./api-CBukwv2I.js";import"./token-store-CuZEiQNg.js";import{normalizeError as r}from"./error-codes-DZnI2JsI.js";import{EXAMPLES as i}from"./examples-wBHwEUt8.js";import{emit as a,flush as o,initTelemetry as s}from"./telemetry-BgkzI2cW.js";import{cac as c}from"cac";import{fork as l}from"node:child_process";import u from"node:path";import{fileURLToPath as d}from"node:url";import{readFileSync as f}from"node:fs";function p(e=process.execPath){return!/(?:^|\/)(?:node|nodejs|bun|deno)(?:\.exe)?$/i.test(e.replace(/\\/g,`/`))}function m(e=process.execPath,t=process.argv){return p(e)?e:t[1]??e}var h=`@zenovay/cli`,g=`1.0.31`,_=`Zenovay CLI — AI install wizard + full terminal analytics dashboard`,v=`module`,y={zenovay:`dist/bin.js`,zv:`dist/bin.js`},b=[`dist/**/*.js`,`dist/**/*.cjs`,`dist/**/*.mjs`,`dist/**/*.d.ts`,`README.md`,`LICENSE`],x={dev:`tsx src/bin.ts`,build:`tsdown`,"build:binaries":`tsx scripts/build-binaries.ts`,typecheck:`tsc --noEmit`,lint:`eslint 'src/**/*.{ts,tsx}'`,test:`vitest run`,"test:watch":`vitest`,"test:all":`vitest run tests/unit tests/integration tests/security`,"test:release":`vitest run tests/e2e tests/update --testTimeout=600000`,"test:smoke":`vitest run tests/smoke --testTimeout=60000`,"test:update-golden":`UPDATE_GOLDEN=1 vitest run tests/e2e`,"render:globe":`tsx scripts/render-globe.ts`,smoke:`bash scripts/smoke-test.sh`},S={cac:`^6.7.14`,chalk:`^5.4.1`,diff:`^8.0.3`,globby:`^14.1.0`,ink:`^5.1.0`,"ink-gradient":`^3.0.0`,"ink-select-input":`^6.0.0`,"ink-spinner":`^5.0.0`,"ink-text-input":`^6.0.0`,open:`^10.1.0`,react:`^18.3.1`,semver:`^7.6.3`,"string-width":`^7.2.0`,ulid:`^2.3.0`,ws:`^8.18.0`,zod:`^3.23.8`},C={"@aws-sdk/client-s3":`^3.1036.0`,"@types/node":`^22.10.0`,"@types/react":`^18.3.12`,"@types/semver":`^7.5.8`,"@typescript-eslint/parser":`^8.61.0`,"@vitest/coverage-v8":`^2.1.8`,"csv-parse":`^6.2.1`,eslint:`^9.16.0`,"ink-testing-library":`^4.0.0`,"react-devtools-core":`^4.19.1`,tsdown:`^0.9.0`,tsx:`^4.19.2`,typescript:`^5.7.2`,vitest:`^2.1.8`},w={node:`>=20.0.0`},T=`pnpm@9.15.9`,E={overrides:{"ws@>=8.0.0 <8.21.0":`>=8.21.0`}},D=`Zenovay <cli@zenovay.com>`,O=`SEE LICENSE IN LICENSE`,k=`https://cli.zenovay.com`,A={type:`git`,url:`git+https://github.com/zenovay/cli-zenovay.git`},j={url:`https://cli.zenovay.com/feedback`},M=[`zenovay`,`analytics`,`cli`,`tui`,`ai-agent`,`install-wizard`],N={name:h,version:g,description:_,type:v,bin:y,files:b,scripts:x,dependencies:S,devDependencies:C,engines:w,packageManager:T,pnpm:E,author:D,license:O,homepage:k,repository:A,bugs:j,keywords:M};const P=u.dirname(d(import.meta.url)),F=N.version,I=m();function L(){return p()}function R(){if(process.env.ZENOVAY_BACKGROUND_UPDATE===`1`&&!(process.env.ZENOVAY_NO_UPDATE_CHECK===`1`||process.env.CI===`true`))try{let e=u.join(P,`lib`,`update`,`worker.js`),t=l(e,[],{detached:!0,stdio:`ignore`,env:{...process.env,ZENOVAY_UPDATE_WORKER_FORK:`1`}});t.unref()}catch{}}const z=c(`zenovay`);z.version(F);const B=[`ANALYTICS`,`BEHAVIOR`,`INTELLIGENCE`,`OPERATIONS`,`MANAGE`,`ACCOUNT`];function V(e){let t=/\[([A-Z]+)\]/.exec(e),n=t?B.indexOf(t[1]??``):-1;return n===-1?B.length:n}z.help(e=>{let t=e.filter(e=>{let t=e.title??``;return!/for more info/i.test(t)}),n=t.find(e=>e.title===`Options`);n&&typeof n.body==`string`&&(n.body=n.body.split(`
|
|
3
3
|
`).map(e=>e.includes(`--no-first-party`)?e.replace(/\s+\(default: true\)\s*$/,``):e).join(`
|
|
4
4
|
`));let r=t.find(e=>e.title===`Commands`);r&&typeof r.body==`string`&&(r.body=r.body.split(`
|
|
5
|
-
`).map((e,t)=>({line:e,i:t,rank:
|
|
6
|
-
`));let i=
|
|
5
|
+
`).map((e,t)=>({line:e,i:t,rank:V(e)})).sort((e,t)=>e.rank-t.rank||e.i-t.i).map(e=>e.line).join(`
|
|
6
|
+
`));let i=z.matchedCommand;return i?.description&&t.splice(1,0,{body:` ${i.description}`}),t.push({body:"Run `zenovay <command> --help` for command-specific options and examples."}),t}),z.option(`-q, --quiet`,`Suppress spinners + interactive UI; implies --json`),z.option(`--team <id>`,"Team override for this command — id only (use `zenovay teams switch <name>` for name lookup)"),(process.argv.includes(`-q`)||process.argv.includes(`--quiet`))&&(process.env.ZENOVAY_FORMAT=`json`,process.argv.includes(`--json`)||process.argv.push(`--json`));let H;for(let e=0;e<process.argv.length;e++){let t=process.argv[e];if(!t)continue;if(t===`--team`){H=process.argv[e+1];break}let n=/^--team=(.+)$/.exec(t);if(n){H=n[1];break}}if(H&&(process.env.ZENOVAY_TEAM_ID=H),!process.env.ZENOVAY_TEAM_ID)try{let t=u.join(e(),`config.json`),n=f(t,`utf8`),r=JSON.parse(n);r.currentTeamId&&(process.env.ZENOVAY_TEAM_ID=r.currentTeamId)}catch{}z.command(`init`,`[OPERATIONS] AI install wizard — add Zenovay tracking to your codebase`).option(`--json`,`Emit NDJSON events to stdout`).option(`--yes`,`Auto-approve all diffs (for CI)`).option(`--review`,`Review each file write before it is applied`).option(`--skip-mcp`,`Skip MCP client install`).option(`--skip-verify`,`Skip first-event verification`).option(`--undo`,`Revert the file writes from the most recent init session`).option(`--no-first-party`,`Skip the same-origin /api/_z/* proxy setup (first-party tracking)`).option(`--host <host>`,`Deploy host for first-party tracking when it can't be auto-detected: cloudflare-pages | vercel | netlify | nextjs`).option(`--site-id <id>`,`Install for a specific site id (skips the picker)`).action(async e=>{let{initCommand:t}=await import(`./init-ZniT6LxK.js`),n=await t({cliVersion:F,cwd:process.cwd(),json:e.json,yes:e.yes,review:e.review,skipMcp:e.skipMcp,skipVerify:e.skipVerify,undo:e.undo,firstParty:e.firstParty,host:e.host,siteId:e.siteId});process.exitCode=n}),z.command(`login`,`[OPERATIONS] Authenticate via OAuth device flow`).option(`--json`,`Emit NDJSON events`).option(`--no-browser`,`Skip opening the browser automatically`).action(async e=>{let{loginCommand:t}=await import(`./login-BD9Q3e7S.js`),n=await t({cliVersion:F,json:e.json,openBrowser:e.browser!==!1,onCode:e=>{process.stdout.write(`\n Open this URL to authorize the CLI:\n ${e.verificationUriComplete??e.verificationUri}\n Or enter code: ${e.userCode}\n\n`)}});!e.json&&n.email?process.stdout.write(`\n ✔ Logged in as ${n.email}\n Try \`zenovay overview\` to see your dashboard, or \`zenovay --help\` for the full command list.\n\n`):e.json||process.stdout.write(`
|
|
7
7
|
✔ Logged in.
|
|
8
8
|
|
|
9
|
-
`)}),
|
|
10
|
-
`:`\n✗ Unknown analytics sub-command: '${e}'\n Valid: live | funnels | goals | insights | profiles | companies. Run \`zenovay analytics --help\`\n`),process.exit(2)}}),
|
|
11
|
-
`:`\n✗ Unknown events action: '${e??`(none)`}'\n Usage: zenovay events tail. Run \`zenovay events tail --help\`\n`),process.exit(2));let{eventsTailCommand:n}=await import(`./events-tail-B0RxKP3U.js`),r=await n({cliVersion:M,siteId:t.siteId,json:t.json,filter:t.filter,forwardTo:t.forwardTo,replay24h:t.replay24h,setForwardSecret:t.setForwardSecret});process.exitCode=r}),F.command(`health`,`[OPERATIONS] Run self-diagnostic checks`).option(`--json`,``).action(async e=>{let{healthCommand:t}=await import(`./health-DJweY04d.js`),n=await t({cliVersion:M,binaryPath:N,json:e.json});process.exitCode=n}),F.command(`annotation [action]`,`[OPERATIONS] annotation create [--type --message --occurred-at] (deploy / release / campaign / incident / custom)`).option(`--type <type>`,`One of: deploy, release, campaign, incident, custom`,{default:`custom`}).option(`--message <message>`,`Short description (1–500 chars)`,{default:``}).option(`--occurred-at <iso>`,`ISO 8601 timestamp (default: now)`).option(`--site-id <id>`,`Site ID`).option(`--json`,``).action(async(e,t)=>{let n=e??`create`;if(n!==`create`){process.stderr.write(`Unknown annotation action: ${n}. Try: zenovay annotation create --type=deploy --message="..."\n`),process.exitCode=2;return}let{annotationCreateCommand:r}=await import(`./annotation-DSdNqyEC.js`),i=await r({cliVersion:M,type:t.type,message:t.message,occurredAt:t.occurredAt,siteId:t.siteId,json:t.json});process.exitCode=i}),F.command(`doctor`,`[OPERATIONS] AI-assisted self-healing`).option(`--json`,``).action(async e=>{let{doctorCommand:t}=await import(`./doctor-WAEVPtnG.js`),n=await t({cliVersion:M,binaryPath:N,json:e.json});process.exitCode=n}),F.command(`stats`,`[ANALYTICS] One-shot dashboard summary (scriptable by default)`).option(`--site-id <id>`,`Site ID`).option(`--range <range>`,`Time range: 24h | 7d | 30d`,{default:`24h`}).option(`--watch`,`Auto-refresh every 60s`).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async e=>{let{statsCommand:t}=await import(`./stats-h_juyrDM.js`),n=await t({cliVersion:M,siteId:e.siteId,range:e.range,watch:e.watch,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),F.command(`sources`,`[ANALYTICS] Traffic source breakdown with delta arrows`).option(`--site-id <id>`,`Site ID`).option(`--range, --period <p>`,`Time range: 7d | 30d | 90d | 1y (--period is a legacy alias)`,{default:`30d`}).option(`--compare <c>`,`Comparison window (use "prev" for period-over-period)`).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async e=>{let{sourcesCommand:t}=await import(`./sources-DICOhsY7.js`),n=await t({cliVersion:M,siteId:e.siteId,period:e.period,compare:e.compare,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),F.command(`vitals`,`[BEHAVIOR] Core Web Vitals dashboard (LCP / INP / CLS / TTFB / FCP) (Pro+)`).option(`--site-id <id>`,`Site ID`).option(`--url <path>`,`Filter to a single URL`).option(`--device <type>`,`Filter by device: mobile | desktop`).option(`--range, --window <w>`,`Time range: 24h | 7d | 30d | 90d (--window is a legacy alias)`,{default:`7d`}).option(`--watch`,`Auto-refresh every 5 minutes`).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async e=>{let{vitalsCommand:t}=await import(`./vitals-CC9vlIZJ.js`),n=await t({cliVersion:M,siteId:e.siteId,url:e.url,device:e.device,window:e.window,watch:e.watch,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),F.command(`revenue`,`[ANALYTICS] MRR / ARR / transaction series`).option(`--site-id <id>`,`Site ID`).option(`--range <r>`,`Time range: 24h | 7d | 30d | 1y`,{default:`30d`}).option(`--watch`,`Auto-refresh every 5 minutes`).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async e=>{let{revenueCommand:t}=await import(`./revenue-CsHAZxDg.js`),n=await t({cliVersion:M,siteId:e.siteId,range:e.range,watch:e.watch,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),F.command(`funnels`,`[BEHAVIOR] List available funnels (Pro+)`).option(`--site-id <id>`,`Site ID`).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async e=>{let{funnelCommand:t}=await import(`./funnel-D33I_HwQ.js`),n=await t({cliVersion:M,siteId:e.siteId,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),F.command(`themes`,`[OPERATIONS] List available themes with colored swatches`).option(`--validate <path>`,`Validate a custom theme JSON file`).option(`--json`,`Emit themes JSON to stdout`).action(async e=>{let{themesCommand:t}=await import(`./themes-BBtRXVPz.js`),n=await t({cliVersion:M,validate:e.validate,json:e.json});process.exitCode=n}),F.command(`completions [shell] [valuesType]`,`[OPERATIONS] Emit shell-completion script (bash | zsh | fish | nushell | pwsh)`).option(`--list`,`List supported shells`).action(async(e,t,n)=>{let{completionsCommand:r}=await import(`./completions-DNEK2qom.js`),i=await r({shell:e,valuesType:t,list:n.list});process.exitCode=i}),F.command(`query [sql]`,`[INTELLIGENCE] Restricted SQL REPL over the analytics schema (Scale+)`).option(`--site-id <id>`,`Site ID`).option(`--max-rows <n>`,`Cap result row count`,{default:1e3}).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async(e,t)=>{let{queryCommand:n}=await import(`./query-C3e5w05g.js`),r=await n({cliVersion:M,siteId:t.siteId,sql:e,maxRows:typeof t.maxRows==`string`?Number(t.maxRows):t.maxRows,json:t.json,csv:t.csv,tsv:t.tsv,ndjson:t.ndjson});process.exitCode=r}),F.command(`companies`,`[INTELLIGENCE] B2B identification feed (Scale+)`).option(`--site-id <id>`,`Site ID`).option(`--range, --window <w>`,`Time range: 24h | 7d | 30d | 90d (--window is a legacy alias)`,{default:`24h`}).option(`--limit <n>`,`Max rows`,{default:100}).option(`--new-only`,`Show only newly identified companies (first-seen in last hour)`).option(`--watch`,`Auto-refresh every 30s`).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async e=>{let{companiesCommand:t}=await import(`./companies-DS2pEJXX.js`),n=await t({cliVersion:M,siteId:e.siteId,window:e.window,limit:typeof e.limit==`string`?Number(e.limit):e.limit,newOnly:e.newOnly,watch:e.watch,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),F.command(`projects`,`[OPERATIONS] List your tracked projects`).option(`--site-id <id>`,`Site ID`).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async e=>{let{projectsCommand:t}=await import(`./projects-7ifzwrtn.js`),n=await t({cliVersion:M,siteId:e.siteId,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),F.command(`deploys`,`[OPERATIONS] Recent deploy markers overlaid on charts`).option(`--site-id <id>`,`Site ID`).option(`--branch <name>`,`Filter to a single branch (e.g. main, develop)`).option(`--since <iso>`,`Only commits after this ISO timestamp`).option(`--limit <n>`,`Max rows`,{default:50}).option(`--connect`,`Print the GitHub-integration deep link in app.zenovay.com`).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async e=>{let{deploysCommand:t}=await import(`./deploys-D261j_D-.js`),n=await t({cliVersion:M,siteId:e.siteId,branch:e.branch,since:e.since,limit:typeof e.limit==`string`?Number(e.limit):e.limit,connect:e.connect,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),F.command(`errors`,`[BEHAVIOR] Recent JS / HTTP error snapshot`).alias(`error`).option(`--site-id <id>`,`Site ID`).option(`--range, --window <w>`,`Time range: 24h | 7d | 30d | 90d (--window is a legacy alias)`,{default:`24h`}).option(`--limit <n>`,`Max errors to fetch`,{default:100}).option(`--search <q>`,`Filter by class or message substring`).option(`--watch`,`Auto-refresh every 30s`).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async e=>{let{errorsCommand:t}=await import(`./errors-DdUD9FzI.js`),n=await t({cliVersion:M,siteId:e.siteId,window:e.window,limit:typeof e.limit==`string`?Number(e.limit):e.limit,search:e.search,watch:e.watch,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),F.command(`funnel <id>`,`[BEHAVIOR] Funnel drop-off chart for a specific funnel (Pro+)`).option(`--site-id <id>`,`Site ID`).option(`--range, --window <w>`,`Time range: 7d | 30d (--window is a legacy alias)`,{default:`30d`}).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async(e,t)=>{let{funnelCommand:n}=await import(`./funnel-D33I_HwQ.js`),r=await n({cliVersion:M,siteId:t.siteId,funnelId:e,window:t.window,json:t.json,csv:t.csv,tsv:t.tsv,ndjson:t.ndjson});process.exitCode=r}),F.command(`api-keys [action] [id]`,`[MANAGE] api-keys list | create [--name --scope] | delete <id>`).option(`--name <n>`,`Human-readable label (create)`).option(`--scope <scope>`,`read | write (create)`,{default:`read`}).option(`--yes`,`Skip confirmation (delete)`).option(`--json`,``).action(async(e,t,n)=>{let{apiKeysCommand:r}=await import(`./api-keys-BrHTpsbc.js`),i=e??`list`;process.exitCode=await r({cliVersion:M,action:i,id:t,name:n.name,scope:n.scope===`write`?`write`:`read`,yes:n.yes,json:n.json})}),F.command(`domains [action] [arg]`,`[MANAGE] domains list | add <url> [--name] | delete <id>`).option(`--name <n>`,`Friendly project name (add; default: domain itself)`).option(`--yes`,`Skip confirmation (delete)`).option(`--json`,``).action(async(e,t,n)=>{let{domainsCommand:r}=await import(`./domains-B-1JuH-0.js`),i=e??`list`;process.exitCode=await r({cliVersion:M,action:i,url:i===`add`?t:void 0,id:i===`delete`?t:void 0,name:n.name,yes:n.yes,json:n.json})}),F.command(`team [action] [arg] [arg2]`,`[MANAGE] team list | invite <email> [--role] | remove <userId> | role <userId> <admin|member> (Pro+)`).option(`--role <role>`,`admin | member (invite)`,{default:`member`}).option(`--yes`,`Skip confirmation (remove)`).option(`--json`,``).action(async(e,t,n,r)=>{let{teamCommand:i}=await import(`./team-CtHhMm_t.js`),a=e??`list`,o;a===`role`?o=n===`admin`?`admin`:`member`:a===`invite`&&(o=r.role===`admin`?`admin`:`member`),process.exitCode=await i({cliVersion:M,action:a,email:a===`invite`?t:void 0,userId:a===`remove`||a===`role`?t:void 0,role:o,yes:r.yes,json:r.json})}),F.command(`profile [action]`,`[ACCOUNT] profile show | edit [--name --notifications]`).option(`--name <n>`,`New display name (edit)`).option(`--notifications <pref>`,`email | none (edit)`).option(`--json`,``).action(async(e,t)=>{let n=e??`show`,r=t.notifications===`email`||t.notifications===`none`?t.notifications:void 0,{profileCommand:i}=await import(`./profile-C-CyW8Bx.js`);process.exitCode=await i({cliVersion:M,action:n,name:t.name,notifications:r,json:t.json})}),F.command(`plans [action] [arg] [arg2]`,`[ACCOUNT] plans info | upgrade <pro|scale> | cancel --yes | payment update`).option(`--yes`,"Required for `cancel`").option(`--json`,``).action(async(e,t,n,r)=>{let i=e??`info`,{plansCommand:a}=await import(`./plans-C_j2XLQ4.js`),o;if(i===`upgrade`&&t){let e=String(t).toLowerCase();(e===`pro`||e===`scale`||e===`enterprise`)&&(o=e)}let s=i===`payment`&&t===`update`||i===`payment`?`update`:void 0;process.exitCode=await a({cliVersion:M,action:i,targetPlan:o,paymentAction:s,yes:r.yes,json:r.json})}),F.command(`billing [action]`,"[ACCOUNT] Alias for `plans info`").option(`--json`,``).action(async(e,t)=>{let{plansCommand:n}=await import(`./plans-C_j2XLQ4.js`);process.exitCode=await n({cliVersion:M,action:`info`,json:t.json})}),F.command(`settings [action] [key] [value]`,`[ACCOUNT] settings get [key] | set <key> <value>`).option(`--json`,``).action(async(e,t,n,r)=>{let i=e??`get`,{settingsCommand:a}=await import(`./settings-BPBWCOOH.js`);process.exitCode=await a({cliVersion:M,action:i,key:t||void 0,value:n||void 0,json:r.json})}),F.command(`integrations [action] [name]`,`[ACCOUNT] integrations list | connect <gsc|github> | disconnect <gsc|github>`).option(`--yes`,`Skip confirmation (disconnect)`).option(`--json`,``).action(async(e,t,n)=>{let r=e??`list`,i=t===`gsc`||t===`github`?t:void 0,{integrationsCommand:a}=await import(`./integrations-BqwI6VNk.js`);process.exitCode=await a({cliVersion:M,action:r,name:i,yes:n.yes,json:n.json})}),F.command(`goals [action] [id]`,`[ACCOUNT] goals list | create [--name --type --target] | delete <id> (Pro+)`).option(`--name <n>`,`Goal name (create)`).option(`--type <t>`,`pageview | event (create)`).option(`--target <v>`,`URL pattern or event name (create)`).option(`--yes`,`Skip confirmation (delete)`).option(`--json`,``).action(async(e,t,n)=>{let r=e??`list`,i=n.type===`event`||n.type===`pageview`?n.type:void 0,{goalsCommand:a}=await import(`./goals-D3oPsLrm.js`);process.exitCode=await a({cliVersion:M,action:r,id:t,name:n.name,type:i,target:n.target,yes:n.yes,json:n.json})}),F.command(`notes [action] [id]`,`[ACCOUNT] notes list | create [--content --site-id] | delete <id>`).option(`--content <text>`,`Note body (create)`).option(`--site-id <id>`,`Attach to a specific site (create; defaults to current)`).option(`--yes`,`Skip confirmation (delete)`).option(`--json`,``).action(async(e,t,n)=>{let r=e??`list`,{notesCommand:i}=await import(`./notes-zgu5aUgZ.js`);process.exitCode=await i({cliVersion:M,action:r,id:t,content:n.content,siteId:n.siteId,yes:n.yes,json:n.json})}),F.command(`agency [action] [arg] [arg2]`,`[ACCOUNT] agency clients list | clients add [--email --name] | clients remove <id> | report send <clientId> (Scale+)`).option(`--email <e>`,`Client contact email (clients add)`).option(`--name <n>`,`Client name (clients add)`).option(`--yes`,`Skip confirmation (clients remove)`).option(`--json`,``).action(async(e,t,n,r)=>{let{agencyCommand:i}=await import(`./agency-BNaZxwuI.js`),a=`clients-list`,o;e===`clients`?t===`add`?a=`clients-add`:t===`remove`?(a=`clients-remove`,o=n):a=`clients-list`:e===`report`&&t===`send`&&(a=`report-send`,o=n),process.exitCode=await i({cliVersion:M,action:a,id:o,email:r.email,name:r.name,yes:r.yes,json:r.json})}),F.command(`use [site]`,`[OPERATIONS] Set / show / reset your default site (used when --site-id is omitted)`).option(`--reset`,`Clear the stored default site`).option(`--show`,`Print the current default and exit`).option(`--json`,`Emit JSON`).action(async(e,t)=>{let{useCommand:n}=await import(`./use-CuQ2Z9Aw.js`),r=await n({cliVersion:M,match:e,reset:t.reset,show:t.show,json:t.json});process.exitCode=r}),F.command(`update`,`[OPERATIONS] Manually install the latest version`).option(`--check`,`Don't install — just print latest`).option(`--force-downgrade`,`Allow downgrading to an older version`).option(`--no-update-check`,`Disable auto-update for this invocation`).option(`--json`,``).action(async e=>{let{updateCommand:t}=await import(`./update-CXMG8g-D.js`);await t({cliVersion:M,binaryPath:N,check:e.check,forceDowngrade:e.forceDowngrade,json:e.json})}),F.command(`usage`,`[ACCOUNT] Current month events vs plan limits + headcounts`).option(`--json`,``).action(async e=>{let{usageCommand:t}=await import(`./usage-DeNyFk5w.js`);process.exitCode=await t({cliVersion:M,json:e.json})}),F.command(`globe`,`[ANALYTICS] Live 3D globe — visitors plotted on a Braille sphere`).option(`--site-id <id>`,`Site ID`).option(`--browser`,`Open the dashboard's Mapbox globe in your browser instead of the terminal version`).option(`--json`,``).action(async e=>{let{globeCommand:t}=await import(`./globe-Cp0sY704.js`);process.exitCode=await t({cliVersion:M,siteId:e.siteId,browser:e.browser,json:e.json})}),F.command(`webhooks [action] [arg]`,`[MANAGE] webhooks list | add <url> [--events] | delete <id> | rotate <id> | test <id> | forward [--to]`).option(`--events <list>`,`Comma-separated event types (add)`).option(`--yes`,`Skip confirmation (delete/rotate)`).option(`--to <url>`,`forward: local URL to POST events to (e.g. localhost:3000/webhook)`).option(`--site-id <id>`,`forward: Site ID`).option(`--sign`,`forward: HMAC-sign each forwarded request with X-Zenovay-Signature`).option(`--secret <hex>`,`forward: HMAC secret (auto-derived from tunnel key if --sign without --secret)`).option(`--max-retries <n>`,`forward: per-request retry count`,{default:3}).option(`--json`,``).action(async(e,t,n)=>{let r=e??`list`;if(r===`forward`){let{webhooksForwardCommand:e}=await import(`./webhooks-forward-DfNBzOJ7.js`);process.exitCode=await e({cliVersion:M,to:n.to,siteId:n.siteId,sign:n.sign,secret:n.secret,maxRetries:typeof n.maxRetries==`string`?Number(n.maxRetries):n.maxRetries});return}let{webhooksCommand:i}=await import(`./webhooks-B1eqAQXM.js`);process.exitCode=await i({cliVersion:M,action:r,url:r===`add`?t:void 0,id:r===`delete`||r===`rotate`||r===`test`?t:void 0,events:n.events,yes:n.yes,json:n.json})}),F.command(`audit [action]`,`[ACCOUNT] audit list [--since --action --actor] | export [--format --out] (Pro+)`).option(`--range, --since <window>`,`Time range like 24h, 7d, 30d (list; --since is a legacy alias)`,{default:`7d`}).option(`--action <pattern>`,`Filter by action string (list)`).option(`--actor <userId>`,`Filter by actor user ID (list)`).option(`--format <fmt>`,`ndjson | csv | json (export)`,{default:`ndjson`}).option(`--out <file>`,`Output file path (export). Defaults to stdout`).option(`--json`,``).action(async(e,t)=>{let n=e??`list`,r=t.format??`ndjson`,{auditCommand:i}=await import(`./audit-CIg-teMg.js`);process.exitCode=await i({cliVersion:M,action:n,since:t.since,filterAction:t.action,actor:t.actor,format:r,out:t.out,json:t.json})}),F.command(`share [action]`,`[ACCOUNT] share enable | disable | url — public dashboard share for the current site`).option(`--site-id <id>`,`Site ID (defaults to your current default site)`).option(`--yes`,`Skip confirmation (disable)`).option(`--json`,``).action(async(e,t)=>{let n=e??`url`,{shareCommand:r}=await import(`./share-COuGNR8Q.js`);process.exitCode=await r({cliVersion:M,action:n,siteId:t.siteId,yes:t.yes,json:t.json})}),F.command(`commands`,`[OPERATIONS] Emit the machine-readable command tree (for AI agents and shell-completion regen)`).option(`--json`,``).action(async e=>{let{commandsCommand:t}=await import(`./commands-CGCCx0-s.js`);process.exitCode=await t({cliVersion:M,json:e.json})}),F.command(`teams [action] [arg]`,`[ACCOUNT] teams list | switch <name-or-id> | current | reset`).option(`--json`,``).action(async(e,t,n)=>{let r=e??`list`,{teamsCommand:i}=await import(`./teams-6x1xB5VJ.js`);process.exitCode=await i({cliVersion:M,action:r,match:r===`switch`?t:void 0,json:n.json})}),F.command(`self-test`,`[OPERATIONS] Functional smoke check across every read endpoint and your local install`).option(`--quick`,`Run a 10-test subset (faster)`).option(`--full`,`Include active security probes + CLI meta-tests (dev/CI use)`).option(`--verbose`,`Include full stdout/stderr per test`).option(`--parallel <n>`,`Concurrent subprocesses (default 4)`,{default:4}).option(`--json`,`Emit NDJSON one line per test result + final summary`).action(async e=>{let{selfTestCommand:t}=await import(`./self-test-RTam3wnZ.js`);process.exitCode=await t({cliVersion:M,full:!!e.full,quick:!!e.quick,verbose:!!e.verbose,parallel:Number(e.parallel)||4,json:!!e.json})}),F.command(`tour`,`[OPERATIONS] Interactive 8-step walkthrough of the CLI`).option(`--non-interactive`,`Print all 8 steps as a flat document (no prompts)`).action(async e=>{let{tourCommand:t}=await import(`./tour-CE8jtA2L.js`);process.exitCode=await t({cliVersion:M,nonInteractive:!!(e[`non-interactive`]||e.nonInteractive)})}),F.command(`alerts [action] [id]`,`[MANAGE] alerts list | create [--metric --op --threshold --window] | delete <id> (Pro+)`).option(`--site-id <id>`,`Site ID (defaults to your current default site)`).option(`--metric <name>`,`Metric to watch (visitors|pageviews|bounce_rate|errors|lcp|inp|cls|uptime|revenue)`).option(`--op <gt|lt>`,`Comparison operator`).option(`--threshold <num>`,`Numeric threshold`).option(`--window <e.g. 1h>`,`Rolling window (5m|1h|24h|7d)`).option(`--name <label>`,`Optional friendly label for the alert`).option(`--channel <chan>`,`Notification channel: in_app | email | webhook (default in_app)`).option(`--email <addr>`,`Notification email (required when --channel email)`).option(`--yes`,`Skip confirmation prompt on delete`).option(`--json`,``).action(async(e,t,n)=>{let r=e??`list`,i=new Set([`list`,`create`,`delete`]);i.has(r)||(process.stderr.write(n.json?JSON.stringify({type:`error`,code:`validation_failed`,message:`Unknown alerts action: ${e}`,hint:`Run zenovay alerts --help`})+`
|
|
12
|
-
`:`\n✗ Unknown action: '${e}'\n Valid: list | create | delete. Run \`zenovay alerts --help\`\n`),process.exit(2));let{alertsCommand:a}=await import(`./alerts-pzUmtvMF.js`);process.exitCode=await a({cliVersion:
|
|
13
|
-
`:`\n✗ Unknown export type: '${e}'\n Valid: analytics | sessions | heatmaps. Run \`zenovay export --help\`\n`),process.exit(2));let r=t.format??`csv`,{exportCommand:i}=await import(`./export-CFfTX4on.js`);process.exitCode=await i({type:e,cliVersion:
|
|
9
|
+
`)}),z.command(`logout`,`[OPERATIONS] Revoke current session and delete local auth`).option(`--json`,``).action(async e=>{let{logoutCommand:t}=await import(`./logout-CQUoX-t4.js`);await t({cliVersion:F,json:e.json})}),z.command(`ai`,`[INTELLIGENCE] 3-mode AI assistant (install / chat / mcp)`).option(`--mode <mode>`,`install | chat | mcp`).option(`--json`,``).action(async e=>{let{aiCommand:t}=await import(`./ai-EujeaV4L.js`),n=await t({cliVersion:F,cwd:process.cwd(),mode:e.mode,json:e.json});process.exitCode=n}),z.command(`watch`,"[ANALYTICS] Alias for `analytics` (dashboard summary)").option(`--site-id <id>`,`Site ID`).option(`--interval <ms>`,`Poll interval ms (legacy; ignored by analytics)`,{default:15e3}).option(`--json`,``).option(`--csv`,`Emit top-pages as CSV`).option(`--tsv`,`Emit top-pages as TSV`).option(`--ndjson`,`Emit top-pages as NDJSON (one row per line)`).action(async e=>{let{analyticsCommand:t}=await import(`./analytics-COca9Xif.js`),n=await t({cliVersion:F,siteId:e.siteId,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),z.command(`analytics [sub]`,`[ANALYTICS] Landing dashboard — visitors, pageviews, bounce, top pages. Subs: live | funnels | goals | insights | profiles | companies`).option(`--site-id <id>`,`Site ID`).option(`--json`,``).option(`--csv`,`Emit top-pages as CSV`).option(`--tsv`,`Emit top-pages as TSV`).option(`--ndjson`,`Emit top-pages as NDJSON (one row per line)`).action(async(e,t)=>{switch(e){case void 0:{let{analyticsCommand:e}=await import(`./analytics-COca9Xif.js`);process.exitCode=await e({cliVersion:F,siteId:t.siteId,json:t.json,csv:t.csv,tsv:t.tsv,ndjson:t.ndjson});return}case`live`:{let{liveCommand:e}=await import(`./live-CcaTO8Jp.js`);process.exitCode=await e({cliVersion:F,siteId:t.siteId,json:t.json});return}case`funnels`:{let{funnelCommand:e}=await import(`./funnel-D33I_HwQ.js`);process.exitCode=await e({cliVersion:F,siteId:t.siteId,json:t.json,csv:t.csv,tsv:t.tsv,ndjson:t.ndjson});return}case`goals`:{let{goalsCommand:e}=await import(`./goals-D3oPsLrm.js`);process.exitCode=await e({cliVersion:F,action:`list`,json:t.json});return}case`insights`:{let{insightsCommand:e}=await import(`./insights-CccdyWT_.js`);process.exitCode=await e({cliVersion:F,siteId:t.siteId,json:t.json});return}case`profiles`:{let{visitorsCommand:e}=await import(`./visitors-BbwAaAwO.js`);process.exitCode=await e({cliVersion:F,siteId:t.siteId,json:t.json});return}case`companies`:{let{companiesCommand:e}=await import(`./companies-DS2pEJXX.js`);process.exitCode=await e({cliVersion:F,siteId:t.siteId,json:t.json});return}default:process.stderr.write(t.json?JSON.stringify({type:`error`,code:`validation_failed`,message:`Unknown analytics sub-command: ${e}`,hint:`Valid: live | funnels | goals | insights | profiles | companies`})+`
|
|
10
|
+
`:`\n✗ Unknown analytics sub-command: '${e}'\n Valid: live | funnels | goals | insights | profiles | companies. Run \`zenovay analytics --help\`\n`),process.exit(2)}}),z.command(`overview`,"[ANALYTICS] Alias for `analytics`").option(`--site-id <id>`,`Site ID`).option(`--json`,``).option(`--csv`,`Emit top-pages as CSV`).option(`--tsv`,`Emit top-pages as TSV`).option(`--ndjson`,`Emit top-pages as NDJSON (one row per line)`).action(async e=>{let{analyticsCommand:t}=await import(`./analytics-COca9Xif.js`),n=await t({cliVersion:F,siteId:e.siteId,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),z.command(`home`,`[ACCOUNT] Top-level summary — sites + this-week deltas`).option(`--json`,``).action(async e=>{let{homeCommand:t}=await import(`./home-B_rPBhQA.js`);process.exitCode=await t({cliVersion:F,json:e.json})}),z.command(`live`,`[ANALYTICS] Real-time visitors + globe + recent events (2s polling)`).option(`--site-id <id>`,`Site ID`).option(`--json`,``).action(async e=>{let{liveCommand:t}=await import(`./live-CcaTO8Jp.js`),n=await t({cliVersion:F,siteId:e.siteId,json:e.json});process.exitCode=n}),z.command(`pages`,`[ANALYTICS] Top pages by views — last 24h`).option(`--site-id <id>`,`Site ID`).option(`--json`,``).option(`--csv`,`Emit pages as CSV`).option(`--tsv`,`Emit pages as TSV`).option(`--ndjson`,`Emit pages as NDJSON (one row per line)`).action(async e=>{let{pagesCommand:t}=await import(`./pages-Cz1Eh2e_.js`),n=await t({cliVersion:F,siteId:e.siteId,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),z.command(`devices`,`[ANALYTICS] Device / browser / OS breakdown — last 24h`).option(`--site-id <id>`,`Site ID`).option(`--json`,``).option(`--csv`,`Emit devices as CSV`).option(`--tsv`,`Emit devices as TSV`).option(`--ndjson`,`Emit devices as NDJSON (one row per line)`).action(async e=>{let{devicesCommand:t}=await import(`./devices-DlMziDZv.js`),n=await t({cliVersion:F,siteId:e.siteId,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),z.command(`geo`,`[ANALYTICS] Countries + cities + globe — last 24h`).option(`--site-id <id>`,`Site ID`).option(`--json`,``).option(`--csv`,`Emit countries as CSV`).option(`--tsv`,`Emit countries as TSV`).option(`--ndjson`,`Emit countries as NDJSON (one row per line)`).action(async e=>{let{geoCommand:t}=await import(`./geo-B7RMf9rK.js`),n=await t({cliVersion:F,siteId:e.siteId,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),z.command(`retention`,`[BEHAVIOR] Cohort retention heatmap — D1 / D7 / D30 (Pro+)`).option(`--site-id <id>`,`Site ID`).option(`--json`,``).action(async e=>{let{retentionCommand:t}=await import(`./retention-BfEYEGIw.js`),n=await t({cliVersion:F,siteId:e.siteId,json:e.json});process.exitCode=n}),z.command(`uptime`,`[BEHAVIOR] Uptime monitors with status + p95 (Pro+)`).option(`--site-id <id>`,`Site ID`).option(`--json`,``).action(async e=>{let{uptimeCommand:t}=await import(`./uptime-CG4AjtHP.js`),n=await t({cliVersion:F,siteId:e.siteId,json:e.json});process.exitCode=n}),z.command(`sessions`,`[BEHAVIOR] Recent session-replay list (Pro+)`).option(`--site-id <id>`,`Site ID`).option(`--json`,``).action(async e=>{let{sessionsCommand:t}=await import(`./sessions-iWcA6sGf.js`),n=await t({cliVersion:F,siteId:e.siteId,json:e.json});process.exitCode=n}),z.command(`heatmaps`,`[BEHAVIOR] Recent heatmap captures (Pro+)`).option(`--site-id <id>`,`Site ID`).option(`--json`,``).action(async e=>{let{heatmapsCommand:t}=await import(`./heatmaps-_qAowqwu.js`),n=await t({cliVersion:F,siteId:e.siteId,json:e.json});process.exitCode=n}),z.command(`journeys`,`[BEHAVIOR] Page-to-page transition flow (Pro+)`).option(`--site-id <id>`,`Site ID`).option(`--json`,``).action(async e=>{let{journeysCommand:t}=await import(`./journeys-DPMLvZT1.js`),n=await t({cliVersion:F,siteId:e.siteId,json:e.json});process.exitCode=n}),z.command(`insights`,`[INTELLIGENCE] AI-generated anomaly / trend / recommendation cards (Pro+)`).option(`--site-id <id>`,`Site ID`).option(`--json`,``).action(async e=>{let{insightsCommand:t}=await import(`./insights-CccdyWT_.js`),n=await t({cliVersion:F,siteId:e.siteId,json:e.json});process.exitCode=n}),z.command(`events [action]`,`[OPERATIONS] events tail [--filter --forward-to --replay-24h] — stream live events`).option(`--site-id <id>`,`Site ID`,{default:``}).option(`--filter <expr>`,`Filter expression (e.g. 'type=pageview AND country=US')`).option(`--forward-to <url>`,`POST each event to a webhook with HMAC-SHA256 signature`).option(`--replay-24h`,`Replay the last 24h before going live`).option(`--set-forward-secret <hex>`,`Persist the HMAC secret used by --forward-to`).option(`--json`,``).action(async(e,t)=>{e!==`tail`&&(process.stderr.write(t.json?JSON.stringify({type:`error`,code:`validation_failed`,message:`Unknown events action: ${e??`(none)`}`,hint:`Usage: zenovay events tail`})+`
|
|
11
|
+
`:`\n✗ Unknown events action: '${e??`(none)`}'\n Usage: zenovay events tail. Run \`zenovay events tail --help\`\n`),process.exit(2));let{eventsTailCommand:n}=await import(`./events-tail-B0RxKP3U.js`),r=await n({cliVersion:F,siteId:t.siteId,json:t.json,filter:t.filter,forwardTo:t.forwardTo,replay24h:t.replay24h,setForwardSecret:t.setForwardSecret});process.exitCode=r}),z.command(`health`,`[OPERATIONS] Run self-diagnostic checks`).option(`--json`,``).action(async e=>{let{healthCommand:t}=await import(`./health-DJweY04d.js`),n=await t({cliVersion:F,binaryPath:I,json:e.json});process.exitCode=n}),z.command(`annotation [action]`,`[OPERATIONS] annotation create [--type --message --occurred-at] (deploy / release / campaign / incident / custom)`).option(`--type <type>`,`One of: deploy, release, campaign, incident, custom`,{default:`custom`}).option(`--message <message>`,`Short description (1–500 chars)`,{default:``}).option(`--occurred-at <iso>`,`ISO 8601 timestamp (default: now)`).option(`--site-id <id>`,`Site ID`).option(`--json`,``).action(async(e,t)=>{let n=e??`create`;if(n!==`create`){process.stderr.write(`Unknown annotation action: ${n}. Try: zenovay annotation create --type=deploy --message="..."\n`),process.exitCode=2;return}let{annotationCreateCommand:r}=await import(`./annotation-DSdNqyEC.js`),i=await r({cliVersion:F,type:t.type,message:t.message,occurredAt:t.occurredAt,siteId:t.siteId,json:t.json});process.exitCode=i}),z.command(`doctor`,`[OPERATIONS] AI-assisted self-healing`).option(`--json`,``).action(async e=>{let{doctorCommand:t}=await import(`./doctor-WAEVPtnG.js`),n=await t({cliVersion:F,binaryPath:I,json:e.json});process.exitCode=n}),z.command(`stats`,`[ANALYTICS] One-shot dashboard summary (scriptable by default)`).option(`--site-id <id>`,`Site ID`).option(`--range <range>`,`Time range: 24h | 7d | 30d`,{default:`24h`}).option(`--watch`,`Auto-refresh every 60s`).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async e=>{let{statsCommand:t}=await import(`./stats-h_juyrDM.js`),n=await t({cliVersion:F,siteId:e.siteId,range:e.range,watch:e.watch,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),z.command(`sources`,`[ANALYTICS] Traffic source breakdown with delta arrows`).option(`--site-id <id>`,`Site ID`).option(`--range, --period <p>`,`Time range: 7d | 30d | 90d | 1y (--period is a legacy alias)`,{default:`30d`}).option(`--compare <c>`,`Comparison window (use "prev" for period-over-period)`).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async e=>{let{sourcesCommand:t}=await import(`./sources-DICOhsY7.js`),n=await t({cliVersion:F,siteId:e.siteId,period:e.period,compare:e.compare,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),z.command(`vitals`,`[BEHAVIOR] Core Web Vitals dashboard (LCP / INP / CLS / TTFB / FCP) (Pro+)`).option(`--site-id <id>`,`Site ID`).option(`--url <path>`,`Filter to a single URL`).option(`--device <type>`,`Filter by device: mobile | desktop`).option(`--range, --window <w>`,`Time range: 24h | 7d | 30d | 90d (--window is a legacy alias)`,{default:`7d`}).option(`--watch`,`Auto-refresh every 5 minutes`).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async e=>{let{vitalsCommand:t}=await import(`./vitals-CC9vlIZJ.js`),n=await t({cliVersion:F,siteId:e.siteId,url:e.url,device:e.device,window:e.window,watch:e.watch,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),z.command(`revenue`,`[ANALYTICS] MRR / ARR / transaction series`).option(`--site-id <id>`,`Site ID`).option(`--range <r>`,`Time range: 24h | 7d | 30d | 1y`,{default:`30d`}).option(`--watch`,`Auto-refresh every 5 minutes`).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async e=>{let{revenueCommand:t}=await import(`./revenue-CsHAZxDg.js`),n=await t({cliVersion:F,siteId:e.siteId,range:e.range,watch:e.watch,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),z.command(`funnels`,`[BEHAVIOR] List available funnels (Pro+)`).option(`--site-id <id>`,`Site ID`).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async e=>{let{funnelCommand:t}=await import(`./funnel-D33I_HwQ.js`),n=await t({cliVersion:F,siteId:e.siteId,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),z.command(`themes`,`[OPERATIONS] List available themes with colored swatches`).option(`--validate <path>`,`Validate a custom theme JSON file`).option(`--json`,`Emit themes JSON to stdout`).action(async e=>{let{themesCommand:t}=await import(`./themes-BBtRXVPz.js`),n=await t({cliVersion:F,validate:e.validate,json:e.json});process.exitCode=n}),z.command(`completions [shell] [valuesType]`,`[OPERATIONS] Emit shell-completion script (bash | zsh | fish | nushell | pwsh)`).option(`--list`,`List supported shells`).action(async(e,t,n)=>{let{completionsCommand:r}=await import(`./completions-DNEK2qom.js`),i=await r({shell:e,valuesType:t,list:n.list});process.exitCode=i}),z.command(`query [sql]`,`[INTELLIGENCE] Restricted SQL REPL over the analytics schema (Scale+)`).option(`--site-id <id>`,`Site ID`).option(`--max-rows <n>`,`Cap result row count`,{default:1e3}).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async(e,t)=>{let{queryCommand:n}=await import(`./query-C3e5w05g.js`),r=await n({cliVersion:F,siteId:t.siteId,sql:e,maxRows:typeof t.maxRows==`string`?Number(t.maxRows):t.maxRows,json:t.json,csv:t.csv,tsv:t.tsv,ndjson:t.ndjson});process.exitCode=r}),z.command(`companies`,`[INTELLIGENCE] B2B identification feed (Scale+)`).option(`--site-id <id>`,`Site ID`).option(`--range, --window <w>`,`Time range: 24h | 7d | 30d | 90d (--window is a legacy alias)`,{default:`24h`}).option(`--limit <n>`,`Max rows`,{default:100}).option(`--new-only`,`Show only newly identified companies (first-seen in last hour)`).option(`--watch`,`Auto-refresh every 30s`).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async e=>{let{companiesCommand:t}=await import(`./companies-DS2pEJXX.js`),n=await t({cliVersion:F,siteId:e.siteId,window:e.window,limit:typeof e.limit==`string`?Number(e.limit):e.limit,newOnly:e.newOnly,watch:e.watch,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),z.command(`projects`,`[OPERATIONS] List your tracked projects`).option(`--site-id <id>`,`Site ID`).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async e=>{let{projectsCommand:t}=await import(`./projects-7ifzwrtn.js`),n=await t({cliVersion:F,siteId:e.siteId,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),z.command(`deploys`,`[OPERATIONS] Recent deploy markers overlaid on charts`).option(`--site-id <id>`,`Site ID`).option(`--branch <name>`,`Filter to a single branch (e.g. main, develop)`).option(`--since <iso>`,`Only commits after this ISO timestamp`).option(`--limit <n>`,`Max rows`,{default:50}).option(`--connect`,`Print the GitHub-integration deep link in app.zenovay.com`).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async e=>{let{deploysCommand:t}=await import(`./deploys-D261j_D-.js`),n=await t({cliVersion:F,siteId:e.siteId,branch:e.branch,since:e.since,limit:typeof e.limit==`string`?Number(e.limit):e.limit,connect:e.connect,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),z.command(`errors`,`[BEHAVIOR] Recent JS / HTTP error snapshot`).alias(`error`).option(`--site-id <id>`,`Site ID`).option(`--range, --window <w>`,`Time range: 24h | 7d | 30d | 90d (--window is a legacy alias)`,{default:`24h`}).option(`--limit <n>`,`Max errors to fetch`,{default:100}).option(`--search <q>`,`Filter by class or message substring`).option(`--watch`,`Auto-refresh every 30s`).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async e=>{let{errorsCommand:t}=await import(`./errors-DdUD9FzI.js`),n=await t({cliVersion:F,siteId:e.siteId,window:e.window,limit:typeof e.limit==`string`?Number(e.limit):e.limit,search:e.search,watch:e.watch,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),z.command(`funnel <id>`,`[BEHAVIOR] Funnel drop-off chart for a specific funnel (Pro+)`).option(`--site-id <id>`,`Site ID`).option(`--range, --window <w>`,`Time range: 7d | 30d (--window is a legacy alias)`,{default:`30d`}).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async(e,t)=>{let{funnelCommand:n}=await import(`./funnel-D33I_HwQ.js`),r=await n({cliVersion:F,siteId:t.siteId,funnelId:e,window:t.window,json:t.json,csv:t.csv,tsv:t.tsv,ndjson:t.ndjson});process.exitCode=r}),z.command(`api-keys [action] [id]`,`[MANAGE] api-keys list | create [--name --scope] | delete <id>`).option(`--name <n>`,`Human-readable label (create)`).option(`--scope <scope>`,`read | write (create)`,{default:`read`}).option(`--yes`,`Skip confirmation (delete)`).option(`--json`,``).action(async(e,t,n)=>{let{apiKeysCommand:r}=await import(`./api-keys-BrHTpsbc.js`),i=e??`list`;process.exitCode=await r({cliVersion:F,action:i,id:t,name:n.name,scope:n.scope===`write`?`write`:`read`,yes:n.yes,json:n.json})}),z.command(`domains [action] [arg]`,`[MANAGE] domains list | add <url> [--name] | delete <id>`).option(`--name <n>`,`Friendly project name (add; default: domain itself)`).option(`--yes`,`Skip confirmation (delete)`).option(`--json`,``).action(async(e,t,n)=>{let{domainsCommand:r}=await import(`./domains-B-1JuH-0.js`),i=e??`list`;process.exitCode=await r({cliVersion:F,action:i,url:i===`add`?t:void 0,id:i===`delete`?t:void 0,name:n.name,yes:n.yes,json:n.json})}),z.command(`team [action] [arg] [arg2]`,`[MANAGE] team list | invite <email> [--role] | remove <userId> | role <userId> <admin|member> (Pro+)`).option(`--role <role>`,`admin | member (invite)`,{default:`member`}).option(`--yes`,`Skip confirmation (remove)`).option(`--json`,``).action(async(e,t,n,r)=>{let{teamCommand:i}=await import(`./team-CtHhMm_t.js`),a=e??`list`,o;a===`role`?o=n===`admin`?`admin`:`member`:a===`invite`&&(o=r.role===`admin`?`admin`:`member`),process.exitCode=await i({cliVersion:F,action:a,email:a===`invite`?t:void 0,userId:a===`remove`||a===`role`?t:void 0,role:o,yes:r.yes,json:r.json})}),z.command(`profile [action]`,`[ACCOUNT] profile show | edit [--name --notifications]`).option(`--name <n>`,`New display name (edit)`).option(`--notifications <pref>`,`email | none (edit)`).option(`--json`,``).action(async(e,t)=>{let n=e??`show`,r=t.notifications===`email`||t.notifications===`none`?t.notifications:void 0,{profileCommand:i}=await import(`./profile-C-CyW8Bx.js`);process.exitCode=await i({cliVersion:F,action:n,name:t.name,notifications:r,json:t.json})}),z.command(`plans [action] [arg] [arg2]`,`[ACCOUNT] plans info | upgrade <pro|scale> | cancel --yes | payment update`).option(`--yes`,"Required for `cancel`").option(`--json`,``).action(async(e,t,n,r)=>{let i=e??`info`,{plansCommand:a}=await import(`./plans-C_j2XLQ4.js`),o;if(i===`upgrade`&&t){let e=String(t).toLowerCase();(e===`pro`||e===`scale`||e===`enterprise`)&&(o=e)}let s=i===`payment`&&t===`update`||i===`payment`?`update`:void 0;process.exitCode=await a({cliVersion:F,action:i,targetPlan:o,paymentAction:s,yes:r.yes,json:r.json})}),z.command(`billing [action]`,"[ACCOUNT] Alias for `plans info`").option(`--json`,``).action(async(e,t)=>{let{plansCommand:n}=await import(`./plans-C_j2XLQ4.js`);process.exitCode=await n({cliVersion:F,action:`info`,json:t.json})}),z.command(`settings [action] [key] [value]`,`[ACCOUNT] settings get [key] | set <key> <value>`).option(`--json`,``).action(async(e,t,n,r)=>{let i=e??`get`,{settingsCommand:a}=await import(`./settings-BPBWCOOH.js`);process.exitCode=await a({cliVersion:F,action:i,key:t||void 0,value:n||void 0,json:r.json})}),z.command(`integrations [action] [name]`,`[ACCOUNT] integrations list | connect <gsc|github> | disconnect <gsc|github>`).option(`--yes`,`Skip confirmation (disconnect)`).option(`--json`,``).action(async(e,t,n)=>{let r=e??`list`,i=t===`gsc`||t===`github`?t:void 0,{integrationsCommand:a}=await import(`./integrations-BqwI6VNk.js`);process.exitCode=await a({cliVersion:F,action:r,name:i,yes:n.yes,json:n.json})}),z.command(`goals [action] [id]`,`[ACCOUNT] goals list | create [--name --type --target] | delete <id> (Pro+)`).option(`--name <n>`,`Goal name (create)`).option(`--type <t>`,`pageview | event (create)`).option(`--target <v>`,`URL pattern or event name (create)`).option(`--yes`,`Skip confirmation (delete)`).option(`--json`,``).action(async(e,t,n)=>{let r=e??`list`,i=n.type===`event`||n.type===`pageview`?n.type:void 0,{goalsCommand:a}=await import(`./goals-D3oPsLrm.js`);process.exitCode=await a({cliVersion:F,action:r,id:t,name:n.name,type:i,target:n.target,yes:n.yes,json:n.json})}),z.command(`notes [action] [id]`,`[ACCOUNT] notes list | create [--content --site-id] | delete <id>`).option(`--content <text>`,`Note body (create)`).option(`--site-id <id>`,`Attach to a specific site (create; defaults to current)`).option(`--yes`,`Skip confirmation (delete)`).option(`--json`,``).action(async(e,t,n)=>{let r=e??`list`,{notesCommand:i}=await import(`./notes-zgu5aUgZ.js`);process.exitCode=await i({cliVersion:F,action:r,id:t,content:n.content,siteId:n.siteId,yes:n.yes,json:n.json})}),z.command(`agency [action] [arg] [arg2]`,`[ACCOUNT] agency clients list | clients add [--email --name] | clients remove <id> | report send <clientId> (Scale+)`).option(`--email <e>`,`Client contact email (clients add)`).option(`--name <n>`,`Client name (clients add)`).option(`--yes`,`Skip confirmation (clients remove)`).option(`--json`,``).action(async(e,t,n,r)=>{let{agencyCommand:i}=await import(`./agency-BNaZxwuI.js`),a=`clients-list`,o;e===`clients`?t===`add`?a=`clients-add`:t===`remove`?(a=`clients-remove`,o=n):a=`clients-list`:e===`report`&&t===`send`&&(a=`report-send`,o=n),process.exitCode=await i({cliVersion:F,action:a,id:o,email:r.email,name:r.name,yes:r.yes,json:r.json})}),z.command(`use [site]`,`[OPERATIONS] Set / show / reset your default site (used when --site-id is omitted)`).option(`--reset`,`Clear the stored default site`).option(`--show`,`Print the current default and exit`).option(`--json`,`Emit JSON`).action(async(e,t)=>{let{useCommand:n}=await import(`./use-CuQ2Z9Aw.js`),r=await n({cliVersion:F,match:e,reset:t.reset,show:t.show,json:t.json});process.exitCode=r}),z.command(`update`,`[OPERATIONS] Manually install the latest version`).option(`--check`,`Don't install — just print latest`).option(`--force-downgrade`,`Allow downgrading to an older version`).option(`--no-update-check`,`Disable auto-update for this invocation`).option(`--json`,``).action(async e=>{let{updateCommand:t}=await import(`./update-CmdUMkfW.js`);await t({cliVersion:F,binaryPath:I,check:e.check,forceDowngrade:e.forceDowngrade,json:e.json})}),z.command(`usage`,`[ACCOUNT] Current month events vs plan limits + headcounts`).option(`--json`,``).action(async e=>{let{usageCommand:t}=await import(`./usage-DeNyFk5w.js`);process.exitCode=await t({cliVersion:F,json:e.json})}),z.command(`globe`,`[ANALYTICS] Live 3D globe — visitors plotted on a Braille sphere`).option(`--site-id <id>`,`Site ID`).option(`--browser`,`Open the dashboard's Mapbox globe in your browser instead of the terminal version`).option(`--json`,``).action(async e=>{let{globeCommand:t}=await import(`./globe-Cp0sY704.js`);process.exitCode=await t({cliVersion:F,siteId:e.siteId,browser:e.browser,json:e.json})}),z.command(`webhooks [action] [arg]`,`[MANAGE] webhooks list | add <url> [--events] | delete <id> | rotate <id> | test <id> | forward [--to]`).option(`--events <list>`,`Comma-separated event types (add)`).option(`--yes`,`Skip confirmation (delete/rotate)`).option(`--to <url>`,`forward: local URL to POST events to (e.g. localhost:3000/webhook)`).option(`--site-id <id>`,`forward: Site ID`).option(`--sign`,`forward: HMAC-sign each forwarded request with X-Zenovay-Signature`).option(`--secret <hex>`,`forward: HMAC secret (auto-derived from tunnel key if --sign without --secret)`).option(`--max-retries <n>`,`forward: per-request retry count`,{default:3}).option(`--json`,``).action(async(e,t,n)=>{let r=e??`list`;if(r===`forward`){let{webhooksForwardCommand:e}=await import(`./webhooks-forward-DfNBzOJ7.js`);process.exitCode=await e({cliVersion:F,to:n.to,siteId:n.siteId,sign:n.sign,secret:n.secret,maxRetries:typeof n.maxRetries==`string`?Number(n.maxRetries):n.maxRetries});return}let{webhooksCommand:i}=await import(`./webhooks-B1eqAQXM.js`);process.exitCode=await i({cliVersion:F,action:r,url:r===`add`?t:void 0,id:r===`delete`||r===`rotate`||r===`test`?t:void 0,events:n.events,yes:n.yes,json:n.json})}),z.command(`audit [action]`,`[ACCOUNT] audit list [--since --action --actor] | export [--format --out] (Pro+)`).option(`--range, --since <window>`,`Time range like 24h, 7d, 30d (list; --since is a legacy alias)`,{default:`7d`}).option(`--action <pattern>`,`Filter by action string (list)`).option(`--actor <userId>`,`Filter by actor user ID (list)`).option(`--format <fmt>`,`ndjson | csv | json (export)`,{default:`ndjson`}).option(`--out <file>`,`Output file path (export). Defaults to stdout`).option(`--json`,``).action(async(e,t)=>{let n=e??`list`,r=t.format??`ndjson`,{auditCommand:i}=await import(`./audit-CIg-teMg.js`);process.exitCode=await i({cliVersion:F,action:n,since:t.since,filterAction:t.action,actor:t.actor,format:r,out:t.out,json:t.json})}),z.command(`share [action]`,`[ACCOUNT] share enable | disable | url — public dashboard share for the current site`).option(`--site-id <id>`,`Site ID (defaults to your current default site)`).option(`--yes`,`Skip confirmation (disable)`).option(`--json`,``).action(async(e,t)=>{let n=e??`url`,{shareCommand:r}=await import(`./share-COuGNR8Q.js`);process.exitCode=await r({cliVersion:F,action:n,siteId:t.siteId,yes:t.yes,json:t.json})}),z.command(`commands`,`[OPERATIONS] Emit the machine-readable command tree (for AI agents and shell-completion regen)`).option(`--json`,``).action(async e=>{let{commandsCommand:t}=await import(`./commands-CGCCx0-s.js`);process.exitCode=await t({cliVersion:F,json:e.json})}),z.command(`teams [action] [arg]`,`[ACCOUNT] teams list | switch <name-or-id> | current | reset`).option(`--json`,``).action(async(e,t,n)=>{let r=e??`list`,{teamsCommand:i}=await import(`./teams-6x1xB5VJ.js`);process.exitCode=await i({cliVersion:F,action:r,match:r===`switch`?t:void 0,json:n.json})}),z.command(`self-test`,`[OPERATIONS] Functional smoke check across every read endpoint and your local install`).option(`--quick`,`Run a 10-test subset (faster)`).option(`--full`,`Include active security probes + CLI meta-tests (dev/CI use)`).option(`--verbose`,`Include full stdout/stderr per test`).option(`--parallel <n>`,`Concurrent subprocesses (default 4)`,{default:4}).option(`--json`,`Emit NDJSON one line per test result + final summary`).action(async e=>{let{selfTestCommand:t}=await import(`./self-test-RTam3wnZ.js`);process.exitCode=await t({cliVersion:F,full:!!e.full,quick:!!e.quick,verbose:!!e.verbose,parallel:Number(e.parallel)||4,json:!!e.json})}),z.command(`tour`,`[OPERATIONS] Interactive 8-step walkthrough of the CLI`).option(`--non-interactive`,`Print all 8 steps as a flat document (no prompts)`).action(async e=>{let{tourCommand:t}=await import(`./tour-CE8jtA2L.js`);process.exitCode=await t({cliVersion:F,nonInteractive:!!(e[`non-interactive`]||e.nonInteractive)})}),z.command(`alerts [action] [id]`,`[MANAGE] alerts list | create [--metric --op --threshold --window] | delete <id> (Pro+)`).option(`--site-id <id>`,`Site ID (defaults to your current default site)`).option(`--metric <name>`,`Metric to watch (visitors|pageviews|bounce_rate|errors|lcp|inp|cls|uptime|revenue)`).option(`--op <gt|lt>`,`Comparison operator`).option(`--threshold <num>`,`Numeric threshold`).option(`--window <e.g. 1h>`,`Rolling window (5m|1h|24h|7d)`).option(`--name <label>`,`Optional friendly label for the alert`).option(`--channel <chan>`,`Notification channel: in_app | email | webhook (default in_app)`).option(`--email <addr>`,`Notification email (required when --channel email)`).option(`--yes`,`Skip confirmation prompt on delete`).option(`--json`,``).action(async(e,t,n)=>{let r=e??`list`,i=new Set([`list`,`create`,`delete`]);i.has(r)||(process.stderr.write(n.json?JSON.stringify({type:`error`,code:`validation_failed`,message:`Unknown alerts action: ${e}`,hint:`Run zenovay alerts --help`})+`
|
|
12
|
+
`:`\n✗ Unknown action: '${e}'\n Valid: list | create | delete. Run \`zenovay alerts --help\`\n`),process.exit(2));let{alertsCommand:a}=await import(`./alerts-pzUmtvMF.js`);process.exitCode=await a({cliVersion:F,action:r,siteId:n[`site-id`]??n.siteId,metric:n.metric,op:n.op,threshold:n.threshold,window:n.window,name:n.name,channel:n.channel,email:n.email,id:t,yes:!!n.yes,json:!!n.json})}),z.command(`export <type>`,`[OPERATIONS] Export data: analytics | sessions (Pro+) | heatmaps (Pro+)`).option(`--site-id <id>`,`Site ID (defaults to your current default site)`).option(`--range <range>`,`Time range: 7d | 30d | 90d`,{default:`30d`}).option(`--format <fmt>`,`Output format: csv | json`,{default:`csv`}).option(`--out <file>`,`Write to file instead of stdout`).option(`--json`,``).action(async(e,t)=>{let n=new Set([`analytics`,`sessions`,`heatmaps`]);n.has(e)||(process.stderr.write(t.json?JSON.stringify({type:`error`,code:`validation_failed`,message:`Unknown export type: ${e}`,hint:`Valid: analytics | sessions | heatmaps`})+`
|
|
13
|
+
`:`\n✗ Unknown export type: '${e}'\n Valid: analytics | sessions | heatmaps. Run \`zenovay export --help\`\n`),process.exit(2));let r=t.format??`csv`,{exportCommand:i}=await import(`./export-CFfTX4on.js`);process.exitCode=await i({type:e,cliVersion:F,siteId:t[`site-id`]||t.siteId,range:t.range,format:r,out:t.out,json:!!t.json})}),z.command(`visitors`,`[ANALYTICS] Live visitor table with sortable rows`).option(`--site-id <id>`,`Site ID`).option(`--min-duration <seconds>`,`Filter to sessions ≥ N seconds`,{default:0}).option(`--json`,``).option(`--csv`,`Emit visitors as CSV`).option(`--tsv`,`Emit visitors as TSV`).option(`--ndjson`,`Emit visitors as NDJSON (one row per line)`).action(async e=>{let{visitorsCommand:t}=await import(`./visitors-BbwAaAwO.js`);process.exitCode=await t({cliVersion:F,siteId:e.siteId,minDuration:Number(e[`min-duration`]||e.minDuration)||0,json:!!e.json,csv:!!e.csv,tsv:!!e.tsv,ndjson:!!e.ndjson})}),z.command(`status`,"[OPERATIONS] Alias of `health` — self-diagnostic checks").option(`--json`,``).action(async e=>{let{healthCommand:t}=await import(`./health-DJweY04d.js`);process.exitCode=await t({cliVersion:F,binaryPath:I,json:!!e.json})}),z.command(`telemetry [action]`,`[OPERATIONS] Manage anonymous CLI telemetry (on / off / status)`).option(`--json`,``).action(async(e,t)=>{let{telemetryCommand:n}=await import(`./telemetry-CyIcWTLw.js`);process.exitCode=await n({cliVersion:F,action:e,json:!!t.json})}),z.command(`status-agent`,`[OPERATIONS] Background daemon → tmux status bar + threshold alerts`).option(`--daemonize`,`Fork detached child + write PID file`).option(`--child`,`Internal flag — actual polling loop (used by --daemonize)`).option(`--stop`,`Stop the running daemon (read PID file → SIGTERM)`).option(`--install-tmux`,`Print the tmux conf snippet`).option(`--install-systemd`,`Print a systemd user-unit template`).option(`--install-launchd`,`Print a macOS launchd plist template`).option(`--notify-on <rules>`,`Comma-separated threshold rules, e.g. "error_rate>5,revenue_drop>20"`).option(`--site-id <id>`,`Site to poll (defaults to your saved default site)`).option(`--interval-ms <ms>`,`Poll interval ms (default 60000)`,{type:[Number]}).option(`--save-config`,`Persist --notify-on + --interval-ms to ~/.config/zenovay/config.json`).option(`--show-config`,`Print the persisted statusAgent config + exit`).action(async e=>{let{statusAgentCommand:t}=await import(`./status-agent-Daz4qPSV.js`);process.exitCode=await t({cliVersion:F,daemonize:!!e.daemonize,child:!!e.child,stop:!!e.stop,installTmux:!!e.installTmux,installSystemd:!!e.installSystemd,installLaunchd:!!e.installLaunchd,saveConfig:!!e.saveConfig,showConfig:!!e.showConfig,notifyOn:e.notifyOn,siteId:e.siteId,intervalMs:Array.isArray(e.intervalMs)?e.intervalMs[0]:e.intervalMs})});const U={events:`events tail`};for(let e of z.commands){let t=U[e.name]??e.name,n=i[t];if(n)for(let t of n)e.example(t)}z.parse(process.argv,{run:!1}),(async()=>{L()&&await t(I),await n({binaryPath:I,currentVersion:F,argv:process.argv}),R();let i,c;try{let t=u.join(e(),`config.json`),n=f(t,`utf8`);i=JSON.parse(n).apiBase}catch{}try{let t=u.join(e(),`auth.json`),n=f(t,`utf8`);c=JSON.parse(n).accessToken}catch{}await s({cliVersion:F,apiBase:i,token:c}).catch(()=>void 0);let l=Date.now(),d=(()=>{let e=z.matchedCommand;return e?.name})();a(`cli.startup`,{command:d});try{let e=z.matchedCommand,t=process.argv.slice(2).filter(e=>!e.startsWith(`-`)),n=process.argv.includes(`--help`)||process.argv.includes(`-h`),r=process.argv.includes(`--version`)||process.argv.includes(`-v`);if(!e&&t.length>0&&!n&&(process.stderr.write(`Unknown command: \`${t.join(` `)}\`\nRun \`zenovay --help\` to see all commands.\n`),a(`cli.exit`,{command:d,exit_code:2,duration_ms:Date.now()-l,error_code:`unknown_command`}),await o().catch(()=>void 0),process.exit(2)),!e&&t.length===0&&!n&&!r){z.outputHelp(),a(`cli.exit`,{command:`help`,exit_code:0,duration_ms:Date.now()-l}),await o().catch(()=>void 0);return}let i=e?.name,s=new Set([`login`,`logout`,`init`,`ai`,`completions`,`themes`,`update`,`health`,`status`,`doctor`,`telemetry`,`tour`,`commands`]),c=process.env.ZENOVAY_API_TOKEN?.trim();if(i&&!s.has(i)&&!c){let{readToken:e}=await import(`./token-store-UmKB69od.js`),t=await e({strict:!1}).catch(()=>null);if(!t){let e=process.env.ZENOVAY_FORMAT===`json`||process.argv.includes(`--json`)||process.argv.includes(`-q`)||process.argv.includes(`--quiet`);e?process.stderr.write(JSON.stringify({type:`error`,code:`not_authenticated`,message:`Not logged in. Run: zenovay login`})+`
|
|
14
14
|
`):process.stderr.write(`
|
|
15
15
|
✗ You are not logged in.
|
|
16
16
|
Run \`zenovay login\` to authenticate, then retry.
|
|
17
|
-
`),process.exitCode=2,
|
|
18
|
-
`):(process.stderr.write(`\n✗ ${t.message}\n`),t.hint&&process.stderr.write(` ${t.hint}\n`));let
|
|
17
|
+
`),process.exitCode=2,a(`cli.exit`,{command:d,exit_code:2,duration_ms:Date.now()-l,error_code:`not_authenticated`}),await o().catch(()=>void 0);return}}await z.runMatchedCommand(),a(`cli.exit`,{command:d,exit_code:typeof process.exitCode==`number`?process.exitCode:0,duration_ms:Date.now()-l}),await o().catch(()=>void 0)}catch(e){let t=r(e),n=process.env.ZENOVAY_FORMAT===`json`||process.argv.includes(`--json`)||process.argv.includes(`-q`)||process.argv.includes(`--quiet`);n?process.stderr.write(JSON.stringify(t)+`
|
|
18
|
+
`):(process.stderr.write(`\n✗ ${t.message}\n`),t.hint&&process.stderr.write(` ${t.hint}\n`));let i=t.code===`validation_failed`||t.code===`auth_required`?2:1;a(`command.error`,{command:d,error_code:t.code??`unknown_error`,duration_ms:Date.now()-l}),a(`cli.exit`,{command:d,exit_code:i,duration_ms:Date.now()-l}),await o().catch(()=>void 0),process.exit(i)}})();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./config-JVhBplSX.js";import"./check-D9G0N7NB.js";import{buildPostInstallReexec as e,detectInstallMethod as t,ensureLatest as n,reExec as r,runNpmGlobalInstall as i}from"./ensure-latest-
|
|
1
|
+
import"./config-JVhBplSX.js";import"./check-D9G0N7NB.js";import{buildPostInstallReexec as e,detectInstallMethod as t,ensureLatest as n,reExec as r,runNpmGlobalInstall as i}from"./ensure-latest-DAiAIi4p.js";export{e as buildPostInstallReexec};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{configDir as e,readConfig as t}from"./config-JVhBplSX.js";import{classifyBump as n,manifestSchema as r,platformKey as i}from"./check-D9G0N7NB.js";import{spawn as a}from"node:child_process";import o from"node:path";import{promises as s,realpathSync as c}from"node:fs";import l from"semver";import{z as u}from"zod";import d from"node:crypto";const f=`i0FuwuAJT+tSZFfjMwpJenQQ6omSFeJMjUOYDdV1uh4=`;async function p(e,t=process.platform){if(t!==`win32`)return;let n=o.dirname(e),r=`${o.basename(e)}.old-`,i;try{i=await s.readdir(n)}catch{return}await Promise.all(i.filter(e=>e.startsWith(r)&&/^\d+$/.test(e.slice(r.length))).map(e=>s.unlink(o.join(n,e)).catch(()=>void 0)))}async function m(e){let{manifest:t,currentVersion:r,forceDowngrade:a}=e,o=n(r,t.latest);if(o===`none`)return{updated:!1,from:r,to:t.latest,reason:`already-latest`};if(o===`downgrade`&&!a)return{updated:!1,from:r,to:t.latest,reason:`downgrade-blocked`};t.minSupported&&l.lt(r,t.minSupported);let c=i(),u=t.platforms[c];if(!u)throw Error(`No release binary for platform ${c}`);let d=await h(u,e.binaryPath,e.fetchImpl,e.signal);try{return await g(d,u.sha256),await v(u,t.latest,c),await y(d,e.binaryPath),{updated:!0,from:r,to:t.latest}}catch(e){throw await s.unlink(d).catch(()=>void 0),e}}async function h(e,t,n=fetch,r){if(!/^https:\/\//i.test(e.url))throw Error(`Refusing non-HTTPS download URL: ${e.url}`);let i=await n(e.url,{signal:r});if(!i.ok)throw Error(`Download failed: ${i.status}`);let a=Buffer.from(await i.arrayBuffer()),o=`${t}.new-${d.randomBytes(6).toString(`hex`)}`;return await s.writeFile(o,a,{mode:493}),o}async function g(e,t){let n=await s.readFile(e),r=d.createHash(`sha256`).update(n).digest(`hex`);if(r.toLowerCase()!==t.toLowerCase())throw Error(`Checksum mismatch: expected ${t}, got ${r}. Update REFUSED.`)}function _(e,t,n){return Buffer.from(`${e}|${t}|${n}`)}async function v(e,t,n){let r=Buffer.from(f,`base64`);if(r.length!==32)throw Error(`Invalid release public key — update REFUSED.`);let i=_(e.sha256,t,n),a=Buffer.from(e.sig,`base64`),o=d.createPublicKey({key:Buffer.concat([Buffer.from(`302a300506032b6570032100`,`hex`),r]),format:`der`,type:`spki`}),s=d.verify(null,i,o,a);if(!s)throw Error(`Signature verification FAILED. Update REFUSED.`)}async function y(e,t){let n=`${t}.old-${Date.now()}`;try{await s.rename(t,n)}catch(e){if(e.code!==`ENOENT`)throw e}try{try{await s.rename(e,t)}catch(n){if(n.code!==`EXDEV`)throw n;await s.copyFile(e,t),await s.unlink(e).catch(()=>void 0)}process.platform!==`win32`&&await s.chmod(t,493),await s.unlink(n).catch(()=>void 0)}catch(e){try{await s.rename(n,t)}catch{}throw e}}const b=2e3,x=3e4,S=5e3,C=5e3,w=36e5,T=new Set([`update`,`health`,`doctor`,`--version`,`-v`]),E=u.object({checkedAt:u.number(),latest:u.string(),platforms:u.record(u.string(),u.unknown()).optional(),binaryDeferredFor:u.string().optional()});function D(){return o.join(e(),`update-cache.json`)}async function O(){try{let e=await s.readFile(D(),`utf8`),t=E.safeParse(JSON.parse(e));return t.success?t.data:null}catch{return null}}async function k(t){try{await s.mkdir(e(),{recursive:!0,mode:448}),await s.writeFile(D(),JSON.stringify(t),{mode:384})}catch{}}const A=u.object({latest:u.string(),minSupported:u.string().optional(),platforms:u.record(u.string(),u.unknown()).optional(),downloads:u.record(u.string(),u.unknown()).optional()});async function j(e){if(M(e.argv))return;let t=null,n=await O();if(n&&Date.now()-n.checkedAt<w)t={latest:n.latest,platforms:n.platforms??{}};else{try{t=await N()}catch(e){V(`update check failed: ${e.message}`);return}t&&await k({checkedAt:Date.now(),latest:t.latest,platforms:t.platforms})}if(!t||!l.valid(e.currentVersion)||!l.valid(t.latest)||l.eq(e.currentVersion,t.latest)||l.lt(t.latest,e.currentVersion))return;let r=l.diff(e.currentVersion,t.latest);if(!r)return;let i=P();if(r===`patch`||r===`prepatch`){let n=await I(t,e,i);if(n&&i===`npm-global`)return;n&&await B(e.argv);return}if(r===`minor`||r===`preminor`||r===`major`||r===`premajor`||r===`prerelease`){let n=await z(t.latest);if(!n){process.stderr.write(`Continuing with ${e.currentVersion}.\n`);return}let r=await I(t,e,i);if(r&&i===`npm-global`)return;r&&await B(e.argv);return}}function M(e){if(process.env.ZENOVAY_NO_UPDATE_CHECK===`1`||process.env.CI===`true`||e.includes(`--no-update-check`))return!0;let t=e[2];return!!(t&&T.has(t))}async function N(){let e=P();if(e===`npm-global`||e===`npm-local`||e===`unknown`)try{let e=await fetch(`https://registry.npmjs.org/@zenovay/cli/latest`,{signal:AbortSignal.timeout(b),headers:{Accept:`application/json`}});if(!e.ok)return null;let t=await e.json();return t.version?{latest:t.version,platforms:{}}:null}catch{return null}let n=await t(),i=`https://zenovay-cli-distribution.zenovay.workers.dev`,a=n.cliBase===i?[n.cliBase]:[n.cliBase,i];for(let e of a)try{let t=await fetch(`${e}/version`,{signal:AbortSignal.timeout(b)});if(!t.ok)continue;let n=await t.json(),i=r.safeParse(n);if(i.success)return i.data;let a=A.safeParse(n);if(a.success)return{latest:a.data.latest,minSupported:a.data.minSupported,platforms:{}}}catch{}return null}function P(){let e=process.argv[1]??``;if(!e)return`unknown`;let t=e;try{t=c(e)}catch{}let n=t.replace(/\\/g,`/`);return n.includes(`/_npx/`)?`npm-local`:n.includes(`/node_modules/@zenovay/cli/`)?`npm-global`:n.includes(`/node_modules/.bin/zenovay`)?`npm-local`:n.includes(`/node_modules/`)?`unknown`:`binary`}function F(e){let t=e.execPath.replace(/\\/g,`/`),n=/(?:^|\/)(?:node|nodejs|bun|deno)(?:\.exe)?$/i.test(t);if(!n)return{cmd:e.execPath,args:e.sub};let r=e.argv1;if(e.resolveSymlink)try{r=e.resolveSymlink(e.argv1)}catch{}return{cmd:e.execPath,args:[r,...e.sub]}}async function I(e,n,r){if(r===`npm-local`)return process.stderr.write(`Update available — \`npm i -g @zenovay/cli@${e.latest}\` to upgrade.\n`),!1;if(r===`unknown`)return V(`unknown install method; skipping auto-update (latest ${e.latest})`),!1;if(r===`npm-global`){if(process.env.ZENOVAY_NO_AUTO_UPDATE===`1`||process.env.ZENOVAY_AUTO_UPDATE===`0`)return process.stderr.write(`Update available (${e.latest}). Auto-update disabled — run \`npm i -g @zenovay/cli@${e.latest}\` to upgrade.\n`),!1;if(process.stdin.isTTY&&process.stderr.isTTY){let t=await L(e.latest);if(!t)return process.stderr.write(`Skipped. Run \`npm i -g @zenovay/cli@${e.latest}\` to upgrade later.\n`),!1}return await R(e.latest)}let i=`${process.platform}-${process.arch}`,a=e.platforms??{};if(!a[i])return process.stderr.write(`\nUpdate ${e.latest} is published to npm (no native binary for ${i} in this release).\nUpgrade with one of:\n npm i -g @zenovay/cli@${e.latest}\n curl -fsSL https://cli.zenovay.com/install.sh | sh\n\n`),!1;let o=await O();if(o?.binaryDeferredFor===e.latest)return!1;let s=new AbortController,c=setTimeout(()=>s.abort(),S);try{let r=await t(),i=await m({currentVersion:n.currentVersion,cliBase:r.cliBase,binaryPath:n.binaryPath,manifest:e,signal:s.signal});return i.updated?!0:(V(`update skipped: ${i.reason??`unknown`}`),!1)}catch(t){return s.signal.aborted?(process.stderr.write(`Update ${e.latest} is ready but needs longer than the quick auto-update window — run \`zenovay update\` to install it now.\n`),await k({checkedAt:o?.checkedAt??Date.now(),latest:e.latest,platforms:o?.platforms??e.platforms,binaryDeferredFor:e.latest}).catch(()=>void 0),!1):(V(`update failed: ${t.message}`),!1)}finally{clearTimeout(c)}}function L(e){return new Promise(t=>{process.stderr.write(`Update @zenovay/cli to ${e} via \`npm i -g\`? [Y/n] (auto-yes 5s) `);let n=!1,r=e=>{if(n)return;let r=e.toString(`utf8`).trim().toLowerCase();n=!0,i(),process.stderr.write(`
|
|
2
|
+
`),t(r!==`n`&&r!==`no`)},i=()=>{clearTimeout(a),process.stdin.off(`data`,r);try{process.stdin.pause()}catch{}},a=setTimeout(()=>{n||(n=!0,i(),process.stderr.write(`
|
|
3
|
+
`),t(!0))},C);try{process.stdin.resume(),process.stdin.on(`data`,r)}catch{i(),t(!0)}})}function R(e){return new Promise(t=>{process.stderr.write(` Updating @zenovay/cli to ${e}...\n`);let n=process.platform===`win32`,r=n?`npm.cmd`:`npm`,i=[`install`,`-g`,`@zenovay/cli@${e}`],o={stdio:[`ignore`,`ignore`,`pipe`],shell:n},s=``,c=!1,l;try{l=a(r,i,o)}catch(n){process.stderr.write(`\n Couldn't launch npm automatically: ${n.message}\n Update manually: npm i -g @zenovay/cli@${e}\n`),t(!1);return}let u=setTimeout(()=>{if(!c){c=!0;try{l.kill(`SIGKILL`)}catch{}V(`npm install timed out after ${x/1e3}s; continuing with current version`),t(!1)}},x);l.stderr?.on(`data`,e=>{s+=e.toString(`utf8`)}),l.on(`error`,e=>{c||(c=!0,clearTimeout(u),V(`npm install error: ${e.message}`),t(!1))}),l.on(`exit`,n=>{if(!c){if(c=!0,clearTimeout(u),n===0){process.stdin.isTTY&&process.stderr.isTTY&&(process.stderr.write(` ✔ Updated to ${e}. Re-run your command to use the new version.\n`),process.exit(0)),process.stderr.write(` ✔ Updated to ${e} — the new version applies on your next run.\n`),t(!1);return}/EACCES|permission denied/i.test(s)?process.stderr.write(`Auto-update needs sudo for the global npm prefix. Run: sudo npm i -g @zenovay/cli@${e}\n`):V(`npm install exited ${n}; continuing with current version`),t(!1)}})})}function z(e){return new Promise(t=>{if(!process.stdin.isTTY||!process.stderr.isTTY){t(!0);return}process.stderr.write(`New version ${e} available. Update? [Y/n] (auto-yes 5s) `);let n=!1,r=e=>{if(n)return;let r=e.toString(`utf8`).trim().toLowerCase();n=!0,i(),process.stderr.write(`
|
|
4
|
+
`),t(r===``||r===`y`||r===`yes`)},i=()=>{clearTimeout(a),process.stdin.off(`data`,r);try{process.stdin.pause()}catch{}},a=setTimeout(()=>{n||(n=!0,i(),process.stderr.write(`
|
|
5
|
+
`),t(!0))},C);try{process.stdin.resume(),process.stdin.on(`data`,r)}catch{i(),t(!0)}})}function B(e){return new Promise(t=>{try{let{cmd:n,args:r}=F({execPath:process.execPath,argv1:e[1]??``,sub:e.slice(2),resolveSymlink:e=>c(e)}),i=a(n,r,{stdio:`inherit`});i.on(`exit`,e=>{process.exit(typeof e==`number`?e:0)}),i.on(`error`,()=>{t(!1)})}catch{t(!1)}})}function V(e){if(process.env.ZENOVAY_DEBUG_UPDATE===`1`)try{process.stderr.write(`zenovay: ${e}\n`)}catch{}}export{m as applyManifest,F as buildPostInstallReexec,p as cleanupStaleUpdateBackups,P as detectInstallMethod,j as ensureLatest,B as reExec,R as runNpmGlobalInstall};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import{readConfig as e,updateConfig as t}from"./config-JVhBplSX.js";import{ApiClient as n,completionUrlForVerifiedSetup as r,dashboardUrlForSite as i}from"./api-CBukwv2I.js";import{readToken as a}from"./token-store-CuZEiQNg.js";import{diagnoseInstall as o}from"./detect-installed-DpSaAeH-.js";import{emit$1 as s,isHeadless as c}from"./emit-5vELQfsB.js";import{openInBrowser as l}from"./open-url-IjqD5f_n.js";import{scrubSecrets as u}from"./secrets-zGZxXoM0.js";import{parseSseStream as d}from"./client-DNMRt-Hq.js";import{swapToFirstPartySnippet as f}from"./snippet-CwowVrmh.js";import{loginCommand as p,maybeInstallCompletions as m}from"./login-vzW-8q0w.js";import{Banner as h,Panel as g,useTheme as _}from"./panel-DbiZwGB3.js";import{DiffView as v,ProgressRow as y}from"./progress-row-BSv_Zm8f.js";import{Select as b}from"./prompt-Dae2nnYJ.js";import{Keybar as ee}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 te,useApp as ne,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 re}from"globby";import L from"ink-spinner";import{applyPatch as ie}from"diff";import{promisify as ae}from"node:util";const oe=[/^(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?$/],se=[/(^|\/)\.env($|\.(?!example$)[^/]+$)/,/(^|\/)\.git(\/|$)/,/(^|\/)node_modules\//,/(^|\/)\.ssh\//,/(^|\/)\.aws\//,/\.pem$/,/\.key$/,/(^|\/)id_rsa($|\.)/,/(^|\/)\.npmrc$/,/(^|\/)credentials(\.|$)/],R=256*1024,ce=20,z=20,B=20;var V=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 de=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>B)throw new V(`round-cap`,`Tool-call recursion cap (${B}) 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 V(`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 V(`escape`,`realpath failed: ${t.message}`);try{let t=await w.lstat(i);if(t.isSymbolicLink())throw new V(`escape`,`Unresolved symlink in journal path: ${e}`)}catch(e){if(e instanceof V)throw e;if(e.code!==`ENOENT`)throw new V(`escape`,`lstat failed: ${e.message}`)}let n=C.dirname(i);if(n===i)throw new V(`escape`,`Could not resolve journal path: ${e}`);r.push(C.basename(i)),i=n}if(!this.isWithin(a,t))throw new V(`escape`,`Path escapes cwd: ${e}`);await this.journalBackup(a)}async resolveSafe(e,t){if(typeof e!=`string`||e.length===0)throw new V(`escape`,`Path must be a non-empty string.`);if(e.includes(`\0`))throw new V(`escape`,`Null byte in path.`);if(/^\\\\[?.]\\/.test(e)||/^\\\\[A-Za-z0-9]/.test(e))throw new V(`escape`,`Windows special path prefix: ${e}`);if(/%/.test(e))try{let t=decodeURIComponent(e);if(/%[0-9A-Fa-f]{2}/.test(t))throw new V(`escape`,`Double-encoded path: ${e}`);e=t}catch(t){throw t instanceof V?t:new V(`escape`,`Malformed percent-encoding: ${e}`)}if(e.includes(`\0`))throw new V(`escape`,`Null byte in decoded path.`);if(e.includes(`\\`))throw new V(`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 V(`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 V(`escape`,`Path escapes cwd: ${e}`);let o=C.relative(n,a),s=o.toLowerCase();for(let e of se)if(e.test(o)||e.test(s)){if(t===`read`&&/(^|\/)node_modules\//i.test(o))continue;throw new V(`blocklisted`,`Path is on the hard blocklist: ${o}`)}if(t===`write`){let e=oe.some(e=>e.test(o));if(!e&&!/^\.env(\.local)?$/.test(o)&&!/^\.claude\//.test(o)&&!/^\.cursor\//.test(o))throw new V(`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>=ce)throw new V(`read-cap`,`Read cap (${ce}) reached.`);let t=await this.resolveForRead(e),n=await w.stat(t);if(n.size>R)throw new V(`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 V(`binary-rejected`,`Binary content in ${e}.`);return this.readCount++,r.toString(`utf8`)}async safeWrite(e,t){if(this.writeCount>=z)throw new V(`write-cap`,`Write cap (${z}) reached.`);if(t.length>R)throw new V(`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 V(`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 V(`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,U(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
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(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`);return`<FILE path="${e}" sha256="${n}">\n${r}\n</FILE>`}static scrubSecrets(e){return u(e)}};const fe=20;function H(e,t){let n=C.relative(t,e);return n===``||!n.startsWith(`..`)&&!C.isAbsolute(n)}function pe(e){if(!/^[A-Za-z0-9_-]+$/.test(e))throw new V(`escape`,`Invalid undo session id.`)}async function me(e,t){pe(e);let n=await w.realpath(t),r=await w.realpath(C.join(n,e));if(!H(r,n))throw new V(`escape`,`Undo session escapes the undo root.`);let i=await w.realpath(C.join(r,`manifest.jsonl`));if(!H(i,r))throw new V(`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 V(`escape`,`Undo manifest contains an invalid path entry.`);return{abs:C.resolve(t.abs),backupPath:t.backupPath}});return{entries:o,sessionDir:r}}async function he(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 V(`escape`,`Undo target escapes the current project: ${e}`);return a}catch(t){if(t instanceof V||t.code!==`ENOENT`)throw t;let i=C.dirname(n);if(i===n)throw new V(`escape`,`Could not resolve undo target: ${e}`);r.push(C.basename(n)),n=i}}async function ge(e,t,n){let r=n?.undoRoot??C.join(E.homedir(),`.zenovay`,`undo`),i=await w.realpath(t),{entries:a}=await me(e,r);return a.length>0&&a.every(e=>H(e.abs,i))}async function U(e,t,n=fe){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 _e(e,t){let n=t?.undoRoot??C.join(E.homedir(),`.zenovay`,`undo`),r,i;try{({entries:r,sessionDir:i}=await me(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 he(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 V(`escape`,`Undo backup escapes its session directory.`);let r=await w.readFile(n);await w.writeFile(t,r),s++}}return{restored:s}}async function ve(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 ye(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 W={id:`angular`,displayName:`Angular`,detect:ve,files:[{path:`src/index.html`,kind:`mutate`,required:!0}],envVarName:`NG_ZENOVAY_SITE`,buildSnippets:ye},be=[`astro.config.ts`,`astro.config.mjs`,`astro.config.js`];async function xe(e){for(let t of be)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 Se(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 Ce={id:`astro`,displayName:`Astro`,detect:xe,files:[{path:`src/layouts/Layout.astro`,kind:`mutate`,required:!1},{path:`src/layouts/BaseHead.astro`,kind:`mutate`,required:!1}
|
|
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 V(`escape`,`Undo manifest contains an invalid path entry.`);return{abs:C.resolve(t.abs),backupPath:t.backupPath}});return{entries:o,sessionDir:r}}async function he(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 V(`escape`,`Undo target escapes the current project: ${e}`);return a}catch(t){if(t instanceof V||t.code!==`ENOENT`)throw t;let i=C.dirname(n);if(i===n)throw new V(`escape`,`Could not resolve undo target: ${e}`);r.push(C.basename(n)),n=i}}async function ge(e,t,n){let r=n?.undoRoot??C.join(E.homedir(),`.zenovay`,`undo`),i=await w.realpath(t),{entries:a}=await me(e,r);return a.length>0&&a.every(e=>H(e.abs,i))}async function U(e,t,n=fe){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 _e(e,t){let n=t?.undoRoot??C.join(E.homedir(),`.zenovay`,`undo`),r,i;try{({entries:r,sessionDir:i}=await me(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 he(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 V(`escape`,`Undo backup escapes its session directory.`);let r=await w.readFile(n);await w.writeFile(t,r),s++}}return{restored:s}}async function ve(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 ye(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 W={id:`angular`,displayName:`Angular`,detect:ve,files:[{path:`src/index.html`,kind:`mutate`,required:!0}],envVarName:`NG_ZENOVAY_SITE`,buildSnippets:ye},be=[`astro.config.ts`,`astro.config.mjs`,`astro.config.js`];async function xe(e){for(let t of be)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 Se(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 Ce={id:`astro`,displayName:`Astro`,detect:xe,files:[{path:`src/layouts/Layout.astro`,kind:`mutate`,required:!1},{path:`src/layouts/BaseHead.astro`,kind:`mutate`,required:!1}],buildSnippets:Se};async function we(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 G(e){return await we(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 Te(e){let t=e.trackingCode??e.siteId??``,n=`const React = require('react');
|
|
4
4
|
|
|
5
5
|
exports.onRenderBody = ({ setHeadComponents }) => {
|
|
6
6
|
setHeadComponents([
|
|
@@ -74,7 +74,7 @@ export default function App({ Component, pageProps }: AppProps) {
|
|
|
74
74
|
</svelte:head>
|
|
75
75
|
|
|
76
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 at={id:`sveltekit`,displayName:`SvelteKit`,detect:rt,files:[{path:`src/routes/+layout.svelte`,kind:`mutate`,required:!0}],envVarName:`PUBLIC_ZENOVAY_SITE`,buildSnippets:it},ot=[`next`,`nuxt`,`nuxt3`,`@sveltejs/kit`,`astro`,`@remix-run/react`,`@builder.io/qwik-city`,`@builder.io/qwik`,`@solidjs/start`,`solid-start`,`@angular/core`,`gatsby`],st=[`index.html`,`public/index.html`];async function ct(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 lt(e){for(let t of st)if(await e.exists(t))return t;return null}async function ut(e){let t=await ct(e);if(ot.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 lt(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 dt(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 ft={id:`vite`,displayName:`Vite`,detect:ut,files:[{path:`index.html`,kind:`mutate`,required:!0}],envVarName:`VITE_ZENOVAY_SITE`,buildSnippets:dt},pt=[Ne,ze,Ue,at,Ce,$e,Ee,W,nt,Xe,ft,qe];async function mt(e){let t=[];for(let n of pt){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 ht(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 re(t,{cwd:e,dot:!1,gitignore:!0,onlyFiles:!0,followSymbolicLinks:!1})}}}async function gt(e,t){let n=ht(e),{adapter:r,ranked:i}=await mt(n),a=i[0];return r&&a&&a.result.confidence>=.7?r:t?t.pickInteractively(i):r}function _t(e){let t=/[\s"'#=]/.test(e)||e===``,n=t?`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`:e;return n}function
|
|
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 at={id:`sveltekit`,displayName:`SvelteKit`,detect:rt,files:[{path:`src/routes/+layout.svelte`,kind:`mutate`,required:!0}],envVarName:`PUBLIC_ZENOVAY_SITE`,buildSnippets:it},ot=[`next`,`nuxt`,`nuxt3`,`@sveltejs/kit`,`astro`,`@remix-run/react`,`@builder.io/qwik-city`,`@builder.io/qwik`,`@solidjs/start`,`solid-start`,`@angular/core`,`gatsby`],st=[`index.html`,`public/index.html`];async function ct(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 lt(e){for(let t of st)if(await e.exists(t))return t;return null}async function ut(e){let t=await ct(e);if(ot.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 lt(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 dt(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 ft={id:`vite`,displayName:`Vite`,detect:ut,files:[{path:`index.html`,kind:`mutate`,required:!0}],envVarName:`VITE_ZENOVAY_SITE`,buildSnippets:dt},pt=[Ne,ze,Ue,at,Ce,$e,Ee,W,nt,Xe,ft,qe];async function mt(e){let t=[];for(let n of pt){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 ht(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 re(t,{cwd:e,dot:!1,gitignore:!0,onlyFiles:!0,followSymbolicLinks:!1})}}}async function gt(e,t){let n=ht(e),{adapter:r,ranked:i}=await mt(n),a=i[0];return r&&a&&a.result.confidence>=.7?r:t?t.pickInteractively(i):r}async function _t(e,t,n,r={}){return t.envVarName?bt(e,{[t.envVarName]:n},r):{file:r.filename??`.env.local`,created:!1,existing:!1,addedKeys:[],updatedKeys:[],skippedKeys:[]}}function vt(e){let t=/[\s"'#=]/.test(e)||e===``,n=t?`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`:e;return n}function yt(e,t){return`${e}=${vt(t)}`}async function bt(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=vt(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(yt(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
78
|
`);p=d+(e?`
|
|
79
79
|
`:``)+`
|
|
80
80
|
`+f+`
|
|
@@ -83,13 +83,13 @@ export default function App({ Component, pageProps }: AppProps) {
|
|
|
83
83
|
`}else p=o?d:f+`
|
|
84
84
|
`+u.join(`
|
|
85
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
|
|
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
|
|
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
|
|
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 xt=`https://api.zenovay.com/mcp`,St=T.object({url:T.string().url(),headers:T.record(T.string(),T.string()).optional()}).passthrough(),Ct=T.object({mcpServers:T.record(T.string(),St).optional()}).passthrough();function wt(e){return e.HOME??e.USERPROFILE??E.homedir()}function Tt(e){return e.APPDATA??null}function Et(e,t){let n=wt(t),r=Tt(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 Dt(e){try{return await w.access(e),!0}catch{return!1}}async function Ot(e){try{let t=await w.readFile(e,`utf8`);if(t.trim().length===0)return{};let n=JSON.parse(t),r=Ct.safeParse(n);return r.success?r.data:n&&typeof n==`object`?n:{}}catch{return{}}}function kt(e){return e?{type:`http`,url:xt}:{url:xt}}function At(e){return!e||typeof e!=`object`?!1:Object.values(e).some(e=>e&&typeof e==`object`&&e.url===xt)}async function q(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 Et(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 Dt(e.configPath);if(!t){a.push(e.displayName);continue}let n=await Ot(e.configPath),r=n[e.serversKey];if(At(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:kt(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 jt(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 Mt=T.object({path:T.string().min(1)}),Nt=T.object({path:T.string().min(1),content:T.string(),reason:T.string().min(1)}),Pt=T.object({path:T.string().min(1),patch:T.string().min(1),reason:T.string().min(1)}),Ft=T.object({}),It=T.object({question:T.string().min(1),choices:T.array(T.string()).optional()});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.safeRead(n.data.path),r=de.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:de.wrapForModel(n.data.path,a)}}catch(e){return{ok:!1,content:null,error:e.message}}}async function Rt(e,t,n){let r=Nt.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 zt(e,t,n){let r=Pt.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=ie(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.`}:Rt(e,{path:i,content:c,reason:o},n)}async function Bt(e){try{let t=ht(e),{adapter:n,ranked:r}=await mt(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 Vt(e,t){let n=It.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 Ht=3;function Ut(e,t,n){if(n)return e.delete(t),null;let r=(e.get(t)??0)+1;return e.set(t,r),r>=Ht?`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 Wt(e){let{api:t,sandbox:n,approval:r,prompter:i,handlers:a}=e,o=[...e.initialMessages],s=``,c=0,l=new Map;for(;c<B;){n.incrementRound(),c++;let u=new AbortController,f=9e4,p=()=>{let e=setTimeout(()=>u.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},u.signal)}catch(e){throw clearTimeout(m),e}let _=[],v=``;for await(let e of d(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 Gt(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=Ut(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 Gt(e,t,n){try{switch(e){case`read_file`:return await Lt(n.sandbox,t);case`write_file`:return await Rt(n.sandbox,t,n.approval);case`patch_file`:return await zt(n.sandbox,t,n.approval);case`detect_framework`:return await Bt(n.cwd);case`ask_user`:return await Vt(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 Kt="What to do: re-run with `--review` to approve each write, or install manually (see https://docs.zenovay.com/en/integrations/cli).";function qt(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${Kt} 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${Kt} Review/undo what was written under ~/.zenovay/undo/.`}}return{ok:!0}}const Jt=e=>`<script defer\n data-id="${e}"\n src="https://api.zenovay.com/z.js">\n</script>`;async function Yt(e){let t={installed:[],skipped:[],errors:[]};if(!J(e.trackingCode))return t.errors.push({file:`(input)`,error:`Unexpected tracking-code format: "${e.trackingCode}". Expected letters, digits, "_" or "-".`}),t;let n=await re(`**/*.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=Jt(e.trackingCode),i=RegExp(`data-id\\s*=\\s*["']${Xt(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 Xt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function J(e){return typeof e==`string`&&e.length>0&&e.length<=64&&/^[A-Za-z0-9_-]+$/.test(e)}function Zt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}const Qt=/<[Ss]cript\b[^>]*\bsrc\s*=\s*["'`][^"'`]*(?:api\.zenovay\.com\/z\.js|\/(?:api\/)?_z\/script\.js)[^"'`]*["'`][^>]*>/;function $t(e){return Qt.test(e)}function en(e){return/api\.zenovay\.com\/z\.js/i.test(e)||/\/(?:api\/)?_z\/script\.js/i.test(e)}function tn(e,t){let n=Zt(t),r=e.match(new RegExp(Qt.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 nn(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 rn=`https://api.zenovay.com/z.js`;function an(e){if(/from\s+['"]next\/script['"]/.test(e))return e;let t=e.split(`
|
|
89
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
|
|
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
|
|
92
|
-
// @zenovay/cli-proxy-version: ${
|
|
90
|
+
`)}function on(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="${rn}" strategy="afterInteractive" />`;return e.replace(n,`${a}\n${i}</body>`)}async function sn(e){let{cwd:t,trackingCode:n}=e,r={installed:[],skipped:[],errors:[],fellThrough:!1};if(!J(n))return r.errors.push({file:`(input)`,error:`unexpected tracking-code format: "${n}"`}),r;let i;try{i=await re([`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(tn(o.src,n))return r.skipped.push({file:o.rel,reason:`already installed with correct tracking code`}),r;if(Qt.test(o.src)){let i=nn(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(en(o.src))return r.fellThrough=!0,r;let s=an(o.src),c=on(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 cn=`api.zenovay.com/z.js`;async function Y(e){try{return await w.readFile(e,`utf8`)}catch{return null}}function ln(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 un(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 Y(e);if(t===null)continue;if($t(t)){if(tn(t,r))return e;let n=nn(t,r);return n!==t&&(await i?.(e),await w.writeFile(e,n,`utf8`)),e}if(en(t))return e;let a=ln(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 un(e.abs,e.content,n,r,i,a+1,o);if(t)return t}return null}async function dn(e){if(!J(e.trackingCode))return{installed:[],skipped:[],errors:[{file:`(input)`,error:`unexpected tracking-code format: "${e.trackingCode}"`}],fellThrough:!1};if(e.adapter.id===`nuxt`)return pn(e);if(e.adapter.id===`sveltekit`)return mn(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 Y(o);if(s===null){a.skipped.push({file:i.targetPath,reason:`target file not present`});continue}if(tn(s,n)){a.skipped.push({file:i.targetPath,reason:`already installed with correct tracking code`}),r=!0;break}if($t(s)){let t=nn(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(en(s)){a.skipped.push({file:i.targetPath,reason:`tracker present in an unparseable form (not double-inserting)`}),r=!0;break}let c=ln(s,i.code);if(c===null){let c=await un(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 Y(c);if(l!==null)return l.includes(cn)&&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 fn(){return{installed:[],skipped:[],errors:[],fellThrough:!1}}async function pn(e){let t=fn(),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 Y(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(cn))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 mn(e){let t=fn(),n=`src/routes/+layout.svelte`,r=C.join(e.cwd,n),i=await Y(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(tn(i,e.trackingCode))return t.skipped.push({file:n,reason:`already installed with correct tracking code`}),t;if($t(i)){let a=nn(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(en(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 X(e,t){try{return await w.access(C.join(e,t)),!0}catch{return!1}}async function hn(e,t){try{let n=await w.stat(C.join(e,t));return n.isDirectory()}catch{return!1}}async function gn(e,t){try{return await w.readFile(C.join(e,t),`utf8`)}catch{return null}}const _n=[`next.config.js`,`next.config.mjs`,`next.config.cjs`,`next.config.ts`];async function vn(e){let t=[],n=await gn(e,`wrangler.toml`),r=n!==null&&/^\s*pages_build_output_dir\s*=/m.test(n),i=await hn(e,`functions`),a=await hn(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 X(e,`vercel.json`),s=await hn(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 X(e,`netlify.toml`),l=await X(e,C.join(`public`,`_redirects`)),u=await X(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 _n)if(await X(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 yn(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 bn=`https://api.zenovay.com`,xn=`// Auto-generated by @zenovay/cli — first-party tracking proxy. Do not edit.`,Sn=2;function Cn(e){return`${xn}
|
|
92
|
+
// @zenovay/cli-proxy-version: ${Sn}
|
|
93
93
|
/**
|
|
94
94
|
* First-Party Proxy for Zenovay Tracking.
|
|
95
95
|
*
|
|
@@ -319,33 +319,33 @@ export async function onRequestOptions(_context: EventContext): Promise<Response
|
|
|
319
319
|
},
|
|
320
320
|
})
|
|
321
321
|
}
|
|
322
|
-
`}function
|
|
322
|
+
`}function wn(e,t){if(!e.startsWith(`${xn}\n`))return!1;let n=[`export async function onRequest(context: EventContext): Promise<Response>`,"const targetUrl = `${apiBase}/fp/${path}${new URL(request.url).search}`",`const apiBase = env.NEXT_PUBLIC_API_URL || '${t}'`,`responseHeaders.set('X-Zenovay-Proxied', 'true')`,`export async function onRequestOptions`];return n.every(t=>e.includes(t))}async function Tn(e,t){let n=(t.apiBase||bn).replace(/\/+$/,``),r=C.join(e,`functions`,`api`,`_z`),i=C.join(r,`[[path]].ts`),a=Cn(n);try{let e=await w.readFile(i,`utf8`);return e===a?{file:i,action:`exists`}:wn(e,n)?(await t.beforeWrite?.(i),await w.writeFile(i,a,`utf8`),{file:i,action:`updated`}):{file:i,action:`manual`}}catch(e){if(e.code!==`ENOENT`)throw e}return await t.beforeWrite?.(i),await w.mkdir(r,{recursive:!0}),await w.writeFile(i,a,`utf8`),{file:i,action:`created`}}const En=`https://api.zenovay.com`,Dn=[`next.config.js`,`next.config.mjs`,`next.config.cjs`,`next.config.ts`];function On(e){return` // Zenovay first-party proxy — forwards /api/_z/* to the tracking API
|
|
323
323
|
{
|
|
324
324
|
source: '/api/_z/:path*',
|
|
325
325
|
destination: '${e}/fp/:path*',
|
|
326
|
-
},`}function
|
|
326
|
+
},`}function kn(e){return`/** @type {import('next').NextConfig} */
|
|
327
327
|
const nextConfig = {
|
|
328
328
|
async rewrites() {
|
|
329
329
|
return [
|
|
330
|
-
${
|
|
330
|
+
${On(e)}
|
|
331
331
|
];
|
|
332
332
|
},
|
|
333
333
|
};
|
|
334
334
|
|
|
335
335
|
export default nextConfig;
|
|
336
|
-
`}async function
|
|
336
|
+
`}async function An(e,t={}){let n=t.apiBase??En,r=null;for(let t of Dn){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,kn(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=`
|
|
337
337
|
async rewrites() {
|
|
338
338
|
return [
|
|
339
|
-
${
|
|
339
|
+
${On(n)}
|
|
340
340
|
];
|
|
341
|
-
},`,p=`${u}${f}${d}`;return await t.beforeWrite?.(r),await M.writeFile(r,p,`utf8`),{file:r,action:`updated`}}const
|
|
341
|
+
},`,p=`${u}${f}${d}`;return await t.beforeWrite?.(r),await M.writeFile(r,p,`utf8`),{file:r,action:`updated`}}const jn=`https://api.zenovay.com`;async function Mn(e,t={}){let n=t.apiBase??jn,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 Nn=`https://api.zenovay.com`;async function Pn(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 Fn(e,t={}){let n=t.apiBase??Nn,r=await Pn(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(`
|
|
342
342
|
`),f.endsWith(`
|
|
343
343
|
`)||(f+=`
|
|
344
344
|
`);else{let e=a.length>0&&!a.endsWith(`
|
|
345
345
|
`)?`
|
|
346
|
-
`:``;f=`${a}${e}${l}\n${i}\n`}return await t.beforeWrite?.(r),await M.writeFile(r,f,`utf8`),{file:r,action:`updated`}}const Fn="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 In(e,t){let{trackingCode:n,apiBase:r,forceHost:i,beforeWrite:a}=t,o=`unknown`,s=null,c=`skipped`,l=null,u=!1,d=new Set;try{switch(o=i&&i!==`unknown`?i:(await _n(e)).host,o){case`cloudflare-pages`:{let t=await wn(e,{apiBase:r,beforeWrite:a});s=t.file,c=t.action,(t.action===`created`||t.action===`updated`)&&d.add(C.relative(e,t.file));break}case`nextjs-server`:{let t=await kn(e,{apiBase:r,beforeWrite:a});s=t.file,c=t.action,(t.action===`created`||t.action===`updated`)&&d.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 jn(e,{apiBase:r,beforeWrite:a});s=t.file,c=t.action,(t.action===`created`||t.action===`updated`)&&d.add(C.relative(e,t.file));break}case`netlify`:{let t=await Pn(e,{apiBase:r,beforeWrite:a});s=t.file,c=t.action,(t.action===`created`||t.action===`updated`)&&d.add(C.relative(e,t.file));break}case`unknown`:default:c=`skipped`,l=Fn;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=`${Fn} (auto-setup hit an error: ${e.message.slice(0,120)})`}let p=s!==null&&c!==`manual`&&c!==`skipped`;if(p)try{let t=await f(e,{trackingCode:n,beforeWrite:a});u=t.swapped;for(let e of t.files)d.add(e)}catch{u=!1}return{host:o,proxyFile:s,proxyAction:c,snippetSwapped:u,manual:l,changedFiles:[...d]}}const Ln=`\x1B]8;;`,Rn=`\x07`;function zn(){return process.env.FORCE_HYPERLINK?!0:!(process.env.NO_COLOR||!process.stdout.isTTY||process.env.CI||(process.env.TERM??``)===`dumb`)}function Bn({url:e,label:t,color:n,arrow:r=!0}){let{theme:i}=_(),a=n??i.fg,o=(t??e)+(r?` ↗`:``);return zn()?N.createElement(A,{color:a,underline:!0},Ln,e,Rn,o,Ln,Rn):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 Z({label:e,value:t,labelWidth:n=12}){let{theme:r}=_();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 Vn(e){return e.review&&process.stdout.isTTY?`interactive`:`auto`}function Hn(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 Un(){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 Wn(){return[` Landing page ████████████████████ 100%`,` ↓ -28%`,` Pricing ██████████████░░░░░░ 72%`,` ↓ -50%`,` Checkout ███████░░░░░░░░░░░░░ 36%`,` ↓ -64%`,` Purchased ███░░░░░░░░░░░░░░░░░ 13%`]}function Gn(){return[` ▇▇▇▇▇▇▇▇▇▎ 89 Sarah K. /pricing 🇺🇸`,` ▇▇▇▇▇▇░░░░ 61 anon /docs 🇩🇪`,` ▇▇▇░░░░░░░ 34 anon /changelog 🇯🇵`]}function Kn(){return[` LCP ● 2.1s good ████████████░░░░░░`,` INP ● 89ms good ██████████████████`,` CLS ⚠ 0.14 needs ████████████░░░░░░`,` TTFB ● 380ms good ███████████████░░░`]}const qn=[{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:Un},{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:Wn},{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:Gn},{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:Kn},{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.`]}],Jn=11e3,Yn=9,Xn=({width:e,height:t})=>{let{theme:n}=_(),[r,i]=I(0);P(()=>{if(qn.length<=1)return;let e=setInterval(()=>{i(e=>(e+1)%qn.length)},Jn);return()=>clearInterval(e)},[]);let a=qn[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:Yn,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,qn.map((e,t)=>N.createElement(A,{key:t,color:t===r?n.muted:n.dim},t===r?`─`:`·`)))))},Zn={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 $n=({tasks:e,width:t,height:n,liveLine:r})=>{let{theme:i}=_();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)},Zn[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 Q(e){return e.toLowerCase().replace(/[^a-z0-9]/g,``)}function er(e,t){if(e.length===0)return null;if(e.length===1)return e[0]??null;if(!t)return null;let n=Q(t);if(!n)return null;let r=e.find(e=>Q(e.name)===n);if(r)return r;let i=e.find(e=>{let t=new URL(e.url).hostname;return Q(t.split(`.`)[0]??``)===n});if(i)return i;if(n.length<4)return null;let a=e.filter(e=>{let t=Q(e.name),r=Q(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 tr=ae(S),nr=2e4;async function $(e,t){let n=await tr(`git`,t,{cwd:e,timeout:nr,maxBuffer:4e6,env:{...process.env,GIT_TERMINAL_PROMPT:`0`}});return{stdout:n.stdout,stderr:n.stderr}}function rr(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 ir(e){let{stdout:t}=await $(e,[`status`,`--porcelain=v1`,`-z`,`--untracked-files=all`]);return rr(t)}async function ar(e){try{let{stdout:t}=await $(e,[`rev-parse`,`--show-toplevel`]),n=C.resolve(t.trim());return{isRepository:!0,root:n,dirtyPaths:await ir(n)}}catch{return{isRepository:!1,root:null,dirtyPaths:[]}}}async function or(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 sr(e){return/(^|\/)\.env(?:$|\.(?!example(?:$|\.)))/i.test(e)}async function cr(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=>or(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=>!sr(e)),o=i.filter(sr),s=await ir(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(`
|
|
347
|
-
`)[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
|
|
348
|
-
`),0;let r;for(let t of n)if(await ge(t,e.cwd).catch(()=>!1)){r=t;break}if(!r){let t=`Nothing to undo — no init session belongs to this project.`;return c(e)?(s({type:`info`,message:t}),s({type:`done`,command:`init`,exitCode:0})):process.stdout.write(`${t}\n`),0}try{let{restored:t}=await _e(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 c(e)?(s({type:`info`,message:n}),s({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 c(e)?(s({type:`error`,code:`undo_failed`,message:i}),s({type:`done`,command:`init`,exitCode:1})):process.stderr.write(`${i}\n`),1}}async function yr(t){let r=await import(`./telemetry-DIAzAYko.js`).catch(()=>null);r?.emit(`install.start`,{properties:{mode:`headless`}});try{let i=await e(),c=await gt(t.cwd);if(!c)return s({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;s({type:`framework.detected`,framework:c.id,confidence:1}),r?.emit(`install.framework_detected`,{properties:{framework:c.id}});let l=await a({strict:!1});if(!l&&!process.env.ZENOVAY_API_TOKEN)return s({type:`error`,code:`not_logged_in`,message:"Run `zenovay login` first (or set ZENOVAY_API_TOKEN)."}),2;let u=new n({config:i,cliVersion:t.cliVersion,token:l}),[d,f]=await Promise.all([u.getSites(),o(t.cwd,``).catch(()=>null)]),p;if(t.siteId){if(p=d.find(e=>e.id===t.siteId),!p)return s({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 s({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 s({type:`info`,message:`Zenovay already installed correctly for ${p.name} (${m})`}),s({type:`done`,command:`init`,exitCode:0}),0;s({type:`info`,message:`Using site ${p.id} (${p.name}) trackingCode=${p.trackingCode??p.id}`});let h=p.trackingCode??p.id;if(!J(h))return s({type:`error`,code:`invalid_tracking_code`,message:`tracking code "${h}" has an unexpected format; aborting to avoid broken markup`}),1;let g=new de({cwd:t.cwd}),_=e=>g.journalTrustedWrite(e);if(c.id===`plain-html`){let e=await Jt({cwd:t.cwd,trackingCode:h,updateOnly:f?.recommendation===`update-tracking-code`,beforeWrite:_});if(e.installed.length===0&&e.skipped.length===0)return s({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}}),s({type:`done`,command:`init`,exitCode:1}),1;s({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 on({cwd:t.cwd,trackingCode:h,beforeWrite:_});if(e.fellThrough||e.errors.length>0)return s({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}}),s({type:`done`,command:`init`,exitCode:1}),1;s({type:`info`,message:`tracker inserted: ${e.installed[0]??`already installed — nothing to change`}`})}else{let e=await un({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 s({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}}),s({type:`done`,command:`init`,exitCode:1}),1;s({type:`info`,message:`tracker inserted: ${e.installed[0]??`already installed — nothing to change`}`})}let v=await yt(t.cwd,{[c.envVarName]:h},{beforeWrite:_});if(v.addedKeys.length>0&&s({type:`info`,message:`env vars added: ${v.addedKeys.join(`,`)}`}),t.firstParty!==!1){let e=await In(t.cwd,{trackingCode:h,forceHost:vn(t.host),beforeWrite:_});e.proxyFile&&e.proxyAction!==`manual`&&e.proxyAction!==`skipped`?s({type:`info`,message:`first-party tracking enabled — analytics now load from your own domain (${wr(t.cwd,e.proxyFile)}), so visitors on Safari/Brave and other strict-privacy browsers are counted too`}):e.manual&&s({type:`info`,message:e.manual})}else s({type:`info`,message:"first-party tracking skipped (--no-first-party) — enable it later with `zenovay init --host <cloudflare-pages|vercel|netlify|nextjs>`"});return s({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 s({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 br=({opts:t,onExit:i})=>{let{exit:s}=ne(),{theme:c}=_(),[l,u]=I(`intro`),[d,f]=I(null),[m,v]=I([]),[y,b]=I(null),[x,S]=I(null),[C,w]=I(null),[T,E]=I([]),[D,O]=I(void 0),[te,M]=I(null),[re,ie]=I(null),[ae,oe]=I(null),[se,R]=I(0),[ce,z]=I(`skipped`),[B,V]=I(null),[le,ue]=I(null),[de,fe]=I(null),H=F(new Set),[pe,me]=I(0),he=F(!1),ge=F(null),U=F(!0),_e=N.useCallback(e=>{let t=H.current.size;for(let t of e)t&&H.current.add(t);H.current.size!==t&&me(H.current.size)},[]),[ve,ye]=I(null),W=F(null),be=F(!1),[xe,Se]=I(!1),[Ce,we]=I(void 0),G=F(null),Te=N.useCallback(e=>new Promise(t=>{G.current=t,we(e),Se(!0)}),[]),Ee=N.useCallback(e=>{Se(!1);let t=G.current;G.current=null,t?.(e)},[]),K=N.useCallback((e,t,n,r)=>{U.current&&(U.current=!1,s(),i(e,t,n,r))},[s,i]);j((e,t)=>{let n=e.toLowerCase()===`q`||t.escape;n&&(l===`error`?K(1):l===`create-site`&&K(0))}),P(()=>{let e=process.env.TERM_PROGRAM===`vscode`,t=!!process.stdout.isTTY&&!e;return t&&process.stdout.write(`\x1B[?1049h\x1B[H`),()=>{U.current=!1,W.current?.abort(),G.current?.(null),G.current=null,t&&process.stdout.write(`\x1B[?1049l`)}},[]),P(()=>{be.current||(be.current=!0,(async()=>{try{ue(await ar(t.cwd));let r=!!process.stdout.isTTY&&!t.yes&&!t.json;r&&await new Promise(e=>setTimeout(e,1400)),u(`detecting`);let i=await gt(t.cwd);if(!i){w(`Could not detect your framework. Supported: Next.js, Nuxt, SvelteKit, Astro, Remix, plain HTML.`),u(`error`);return}f(i);let s=await a({strict:!1});!process.env.ZENOVAY_API_TOKEN&&!s&&(u(`login`),await p({cliVersion:t.cliVersion,offerCompletions:!1})),u(`loading-sites`);let c=await e(),l=await a({strict:!1}),d=new n({config:c,cliVersion:t.cliVersion,token:l}),[m,h]=await Promise.all([d.getSites(),o(t.cwd,``).catch(()=>null)]),g=await Gr(t.cwd);if(v(m),b(g),m.length===0){u(`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.`),u(`error`);return}let n=e.trackingCode??e.id;if(h?.foundTrackingCodes.includes(n)){S(e),u(`already-installed`);return}S(e),Or(e,i,t,{setPhase:u,setErrorMsg:w,setTasks:E,setLiveLine:O,setSandboxStats:M,setVerifyResult:ie,setFirstParty:oe,setPendingApproval:ye,askHostChoice:Te,recordChangedPaths:_e,registerBridge:e=>{W.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),u(`already-installed`);return}}let _=er(m,g);if(t.yes&&_){S(_),Or(_,i,t,{setPhase:u,setErrorMsg:w,setTasks:E,setLiveLine:O,setSandboxStats:M,setVerifyResult:ie,setFirstParty:oe,setPendingApproval:ye,askHostChoice:Te,recordChangedPaths:_e,registerBridge:e=>{W.current=e}});return}u(`site-picker`)}catch(e){w(e.message),u(`error`)}})())},[]),P(()=>{l===`error`&&(W.current?.abort(),setTimeout(()=>K(1),8e3))},[l]);let De=async()=>{if(!he.current){if(he.current=!0,z(`verified`),!x){u(`success`);return}try{let i=await e();if(!U.current)return;let o=await a({strict:!1});if(!U.current)return;let s=new n({config:i,cliVersion:t.cliVersion,token:o}),c=await s.getSetupDestination(x.id);if(!U.current)return;V(c);let l=r(x.id,c);if(l){K(0,`quit`,x,l);return}}catch{U.current&&K(0,`quit`,x,r(x.id,null));return}U.current&&u(`success`)}};return N.createElement(k,{flexDirection:`column`},N.createElement(h,{version:t.cliVersion,subtitle:`AI install wizard`}),l===`intro`&&N.createElement(kr,null),l===`detecting`&&N.createElement(g,{title:`Scanning`,state:`busy`},N.createElement(k,null,N.createElement(A,{color:c.accent},N.createElement(L,{type:`dots`})),N.createElement(A,null,` Detecting framework…`))),l===`login`&&N.createElement(g,{title:`Authenticating`,state:`busy`},N.createElement(A,null,`Opening browser for login… (paste ZENOVAY_API_TOKEN env var to skip)`)),l===`loading-sites`&&N.createElement(g,{title:`Loading your sites`,state:`busy`},N.createElement(k,null,N.createElement(A,{color:c.accent},N.createElement(L,{type:`dots`})),N.createElement(A,null,` Fetching your Zenovay sites…`))),l===`already-installed`&&x&&N.createElement(Mr,{site:x,onContinueSetup:()=>{if(t.skipVerify){z(`skipped`),u(`success`);return}ge.current=Date.now(),R(0),u(`visit-prompt`)},onReinstall:()=>{u(`site-picker`)},onExit:()=>K(0,`quit`,x)}),l===`site-picker`&&d&&N.createElement(Nr,{sites:m,preselectHint:y,onPick:e=>{if(e===`create-new`){u(`create-site`);return}S(e),Or(e,d,t,{setPhase:u,setErrorMsg:w,setTasks:E,setLiveLine:O,setSandboxStats:M,setVerifyResult:ie,setFirstParty:oe,setPendingApproval:ye,askHostChoice:Te,recordChangedPaths:_e,registerBridge:e=>{W.current=e}})}}),l===`create-site`&&N.createElement(g,{title:`Add a site first`,state:`warn`},N.createElement(A,{color:c.warn},`You don't have a Zenovay site yet. Create one at `,gr,`(takes ~30 seconds), then re-run `,N.createElement(A,{color:c.accent},`zenovay init`),` here.`),N.createElement(k,{marginTop:1},N.createElement(A,{color:c.muted},`Press `),N.createElement(A,{color:c.accent},`q`),N.createElement(A,{color:c.muted},` to exit.`))),l===`agent`&&d&&x&&N.createElement(jr,{adapter:d,site:x,tasks:T,liveLine:D,pendingApproval:ve,onApprove:e=>{ve&&W.current?.resolve(ve.id,e)},pendingHostChoice:xe,hostChoiceNote:Ce,onHostChoice:Ee}),l===`install-complete`&&d&&x&&N.createElement(Lr,{cwd:t.cwd,adapter:d,site:x,stats:te,modifiedFileCount:pe,verify:re,firstParty:ae,onCommit:()=>u(`commit-prompt`),onSkipCommit:()=>u(`deploy-prompt`),onQuit:()=>K(0,`quit`,x)}),l===`commit-prompt`&&x&&N.createElement(zr,{cwd:t.cwd,baseline:le??{isRepository:!1,root:null,dirtyPaths:[]},changedPaths:[...H.current],onDone:e=>{fe(e.message),e.pushed&&O(`Pushed ${e.shortSha} to ${e.branch}`),u(`deploy-prompt`)},onError:e=>{w(e),u(`error`)}}),l===`deploy-prompt`&&x&&N.createElement(Br,{site:x,notice:de,onDeployed:()=>{t.skipVerify?(z(`skipped`),u(`success`)):(ge.current=Date.now(),u(`visit-prompt`))},onSkip:()=>{z(`skipped`),u(`success`)},onQuit:()=>K(0,`quit`,x)}),l===`visit-prompt`&&x&&N.createElement(Vr,{site:x,onContinue:()=>u(`verify`),onQuit:()=>K(0,`quit`,x)}),l===`verify`&&x&&N.createElement(Hr,{site:x,since:ge.current??Date.now(),elapsed:se,onTick:e=>R(e),onArrived:()=>{De()},onTimeout:()=>{z(`unverified`),u(`success`)},onSkip:()=>{z(`skipped`),u(`success`)},onQuit:()=>K(0,`quit`,x)}),l===`success`&&d&&x&&N.createElement(Ir,{adapter:d,site:x,stats:te,modifiedFileCount:pe,outcome:ce,dashboardUrl:B?.kind===`dashboard`?B.url:void 0,firstParty:ae,onPick:e=>K(0,e,x)}),l===`error`&&N.createElement(g,{title:`Install failed`,state:`err`},N.createElement(A,{color:c.error},C??`Unknown error`)),N.createElement(ee,{items:l===`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 xr(e,t,n,r){if(e.firstParty===!1){let e={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 n.setFirstParty?.(e),e}if(!n.setFirstParty)return null;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=vn(e.host),a=null;try{if(a=await In(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 In(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=Tr(a,e.cwd);return n.setTasks(e=>e.map(e=>e.id===`first-party`?{...e,status:`done`,detail:o}:e)),n.setLiveLine(void 0),a}function Sr(e){return!e||e.changedFiles.length===0?`Already installed correctly`:e.proxyAction===`updated`?`Tracker already present; first-party proxy upgraded`:e.proxyAction===`created`?`Tracker already present; first-party proxy added`:`Tracker already present; first-party tracking updated`}function Cr(e){return`${e} ${e===1?`file`:`files`}`}function wr(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 Tr(e,t){return e?e.proxyFile&&e.proxyAction!==`manual`&&e.proxyAction!==`skipped`?`now loads from your domain (${wr(t,e.proxyFile)})`:e.manual?`standard tracking active — see note below for all-browser coverage`:`standard tracking active`:`standard tracking active`}function Er(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 Dr(e,t,n){n.setLiveLine(`Verifying the tracker is in your source…`);try{let r=await o(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 Or(r,i,s,c){try{c.setPhase(`agent`);let l=await e(),u=await a({strict:!1}),d=new n({config:l,cliVersion:s.cliVersion,token:u}),f=new de({cwd:s.cwd}),p=e=>f.journalTrustedWrite(e),m=r.trackingCode??r.id;if(!J(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 o(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 q({accessToken:u.accessToken}).catch(()=>void 0);let e=await xr(s,m,c,p);c.setVerifyResult?.({ok:!0,detail:Sr(e)}),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).`),i.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 on({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 yt(s.cwd,{[i.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 q({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:Er(e)}:t))}else c.setTasks(e=>e.map(e=>e.id===`mcp`?{...e,status:`done`,detail:`skipped`}:e));await Dr(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 xr(s,m,c,p),c.setPhase(`install-complete`);return}c.setLiveLine(`Custom Next.js structure — handing off to the AI agent…`)}let g=i.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 Jt({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 yt(s.cwd,{[i.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 q({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:Er(e)}:t))}else c.setTasks(e=>e.map(e=>e.id===`mcp`?{...e,status:`done`,detail:`skipped`}:e));await Dr(s.cwd,m,c),c.setSandboxStats?.({reads:e.installed.length,writes:e.installed.length,rounds:0}),await xr(s,m,c,p),c.setPhase(`install-complete`);return}{let e=await un({cwd:s.cwd,trackingCode:m,siteId:r.id,adapter:i,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:i.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(`${i.displayName} — using fast install path (no AI needed)…`);let t=await yt(s.cwd,{[i.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 q({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:Er(e)}:t))}else c.setTasks(e=>e.map(e=>e.id===`mcp`?{...e,status:`done`,detail:`skipped`}:e));await Dr(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 xr(s,m,c,p),c.setPhase(`install-complete`);return}c.setLiveLine(`${i.displayName} needs a closer look — using the AI installer (a bit slower than the fast path)…`)}let _=i.buildSnippets({trackingCode:m,siteId:r.id}),v=`Install Zenovay tracking into this ${i.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`+i.files.map(e=>` - ${e.path}`).join(`
|
|
346
|
+
`:``;f=`${a}${e}${l}\n${i}\n`}return await t.beforeWrite?.(r),await M.writeFile(r,f,`utf8`),{file:r,action:`updated`}}const In="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 Ln(e,t){let{trackingCode:n,apiBase:r,forceHost:i,beforeWrite:a}=t,o=`unknown`,s=null,c=`skipped`,l=null,u=!1,d=new Set;try{switch(o=i&&i!==`unknown`?i:(await vn(e)).host,o){case`cloudflare-pages`:{let t=await Tn(e,{apiBase:r,beforeWrite:a});s=t.file,c=t.action,(t.action===`created`||t.action===`updated`)&&d.add(C.relative(e,t.file));break}case`nextjs-server`:{let t=await An(e,{apiBase:r,beforeWrite:a});s=t.file,c=t.action,(t.action===`created`||t.action===`updated`)&&d.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 Mn(e,{apiBase:r,beforeWrite:a});s=t.file,c=t.action,(t.action===`created`||t.action===`updated`)&&d.add(C.relative(e,t.file));break}case`netlify`:{let t=await Fn(e,{apiBase:r,beforeWrite:a});s=t.file,c=t.action,(t.action===`created`||t.action===`updated`)&&d.add(C.relative(e,t.file));break}case`unknown`:default:c=`skipped`,l=In;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=`${In} (auto-setup hit an error: ${e.message.slice(0,120)})`}let p=s!==null&&c!==`manual`&&c!==`skipped`;if(p)try{let t=await f(e,{trackingCode:n,beforeWrite:a});u=t.swapped;for(let e of t.files)d.add(e)}catch{u=!1}return{host:o,proxyFile:s,proxyAction:c,snippetSwapped:u,manual:l,changedFiles:[...d]}}const Rn=`\x1B]8;;`,zn=`\x07`;function Bn(){return process.env.FORCE_HYPERLINK?!0:!(process.env.NO_COLOR||!process.stdout.isTTY||process.env.CI||(process.env.TERM??``)===`dumb`)}function Vn({url:e,label:t,color:n,arrow:r=!0}){let{theme:i}=_(),a=n??i.fg,o=(t??e)+(r?` ↗`:``);return Bn()?N.createElement(A,{color:a,underline:!0},Rn,e,zn,o,Rn,zn):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 Z({label:e,value:t,labelWidth:n=12}){let{theme:r}=_();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 Hn(e){return e.review&&process.stdout.isTTY?`interactive`:`auto`}function Un(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 Wn(){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 Gn(){return[` Landing page ████████████████████ 100%`,` ↓ -28%`,` Pricing ██████████████░░░░░░ 72%`,` ↓ -50%`,` Checkout ███████░░░░░░░░░░░░░ 36%`,` ↓ -64%`,` Purchased ███░░░░░░░░░░░░░░░░░ 13%`]}function Kn(){return[` ▇▇▇▇▇▇▇▇▇▎ 89 Sarah K. /pricing 🇺🇸`,` ▇▇▇▇▇▇░░░░ 61 anon /docs 🇩🇪`,` ▇▇▇░░░░░░░ 34 anon /changelog 🇯🇵`]}function qn(){return[` LCP ● 2.1s good ████████████░░░░░░`,` INP ● 89ms good ██████████████████`,` CLS ⚠ 0.14 needs ████████████░░░░░░`,` TTFB ● 380ms good ███████████████░░░`]}const Jn=[{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:Wn},{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:Gn},{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:Kn},{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:qn},{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.`]}],Yn=11e3,Xn=9,Zn=({width:e,height:t})=>{let{theme:n}=_(),[r,i]=I(0);P(()=>{if(Jn.length<=1)return;let e=setInterval(()=>{i(e=>(e+1)%Jn.length)},Yn);return()=>clearInterval(e)},[]);let a=Jn[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:Xn,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,Jn.map((e,t)=>N.createElement(A,{key:t,color:t===r?n.muted:n.dim},t===r?`─`:`·`)))))},Qn={pending:`·`,active:`⠋`,done:`✓`,error:`✗`};function $n(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 er=({tasks:e,width:t,height:n,liveLine:r})=>{let{theme:i}=_();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:$n(e.status,i)},Qn[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 Q(e){return e.toLowerCase().replace(/[^a-z0-9]/g,``)}function tr(e,t){if(e.length===0)return null;if(e.length===1)return e[0]??null;if(!t)return null;let n=Q(t);if(!n)return null;let r=e.find(e=>Q(e.name)===n);if(r)return r;let i=e.find(e=>{let t=new URL(e.url).hostname;return Q(t.split(`.`)[0]??``)===n});if(i)return i;if(n.length<4)return null;let a=e.filter(e=>{let t=Q(e.name),r=Q(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 nr=ae(S),rr=2e4;async function $(e,t){let n=await nr(`git`,t,{cwd:e,timeout:rr,maxBuffer:4e6,env:{...process.env,GIT_TERMINAL_PROMPT:`0`}});return{stdout:n.stdout,stderr:n.stderr}}function ir(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 ar(e){let{stdout:t}=await $(e,[`status`,`--porcelain=v1`,`-z`,`--untracked-files=all`]);return ir(t)}async function or(e){try{let{stdout:t}=await $(e,[`rev-parse`,`--show-toplevel`]),n=C.resolve(t.trim());return{isRepository:!0,root:n,dirtyPaths:await ar(n)}}catch{return{isRepository:!1,root:null,dirtyPaths:[]}}}async function sr(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 cr(e){return/(^|\/)\.env(?:$|\.(?!example(?:$|\.)))/i.test(e)}async function lr(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=>sr(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=>!cr(e)),o=i.filter(cr),s=await ar(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(`
|
|
347
|
+
`)[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 ur=/<script\b[^>]*\bsrc\s*=\s*["'][^"']*(?:(?:api|cdn)\.zenovay\.com\/|\/(?:api\/)?_z\/script\.js)[^"']*["'][^>]*>/gi,dr=/\bsrc\s*=\s*["']([^"']+)["']/i,fr=/data-id\s*=\s*["'](ZV_[A-Za-z0-9_-]+)["']/i,pr=/[?&]id=(ZV_[A-Za-z0-9_-]+)/i;function mr(e){return e.match(fr)?.[1]??e.match(pr)?.[1]??null}function hr(e){return/\/(?:api\/)?_z\/script\.js/i.test(e)}async function gr(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(ur)??[];if(a.length===0)return{state:`tracker-missing`};let o=[...new Set(a.map(mr).filter(e=>!!e))],s=a.find(e=>mr(e)===t);if(!s)return{state:`tracker-wrong-id`,foundCodes:o};if(!hr(s))return{state:`tracker-correct`};let c=s.match(dr)?.[1]?.replace(/&/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`}}}const _r=`https://app.zenovay.com/domains/add`;async function vr(e){if(e.undo)return yr(e);if(c(e))return br(e);let t=`quit`,n=null,r=null,i=Promise.resolve(),a=await new Promise(a=>{let{unmount:o,waitUntilExit:s}=te(N.createElement(xr,{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 l(r),0;let o=a===0&&t!==`quit`&&!!n;if(a===0&&!o&&await m().catch(()=>void 0),a!==0||t===`quit`||!n)return a;let s=n.id,u=t===`watch`?[`overview`,`--site-id`,s]:[`events`,`tail`,`--site-id`,s],{spawnSync:d}=await import(`node:child_process`),{realpathSync:f}=await import(`node:fs`),{buildPostInstallReexec:p}=await import(`./ensure-latest-3A_-Fnvl.js`),{cmd:h,args:g}=p({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 ${s}\` to continue.\n`),0}return _.status??0}async function yr(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 c(e)?(s({type:`info`,message:`Nothing to undo — no init session has modified project files on this machine.`}),s({type:`done`,command:`init`,exitCode:0})):process.stdout.write(`Nothing to undo — no init session has modified project files on this machine.
|
|
348
|
+
`),0;let r;for(let t of n)if(await ge(t,e.cwd).catch(()=>!1)){r=t;break}if(!r){let t=`Nothing to undo — no init session belongs to this project.`;return c(e)?(s({type:`info`,message:t}),s({type:`done`,command:`init`,exitCode:0})):process.stdout.write(`${t}\n`),0}try{let{restored:t}=await _e(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 c(e)?(s({type:`info`,message:n}),s({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 c(e)?(s({type:`error`,code:`undo_failed`,message:i}),s({type:`done`,command:`init`,exitCode:1})):process.stderr.write(`${i}\n`),1}}async function br(t){let r=await import(`./telemetry-DIAzAYko.js`).catch(()=>null);r?.emit(`install.start`,{properties:{mode:`headless`}});try{let i=await e(),c=await gt(t.cwd);if(!c)return s({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;s({type:`framework.detected`,framework:c.id,confidence:1}),r?.emit(`install.framework_detected`,{properties:{framework:c.id}});let l=await a({strict:!1});if(!l&&!process.env.ZENOVAY_API_TOKEN)return s({type:`error`,code:`not_logged_in`,message:"Run `zenovay login` first (or set ZENOVAY_API_TOKEN)."}),2;let u=new n({config:i,cliVersion:t.cliVersion,token:l}),[d,f]=await Promise.all([u.getSites(),o(t.cwd,``).catch(()=>null)]),p;if(t.siteId){if(p=d.find(e=>e.id===t.siteId),!p)return s({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 s({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 s({type:`info`,message:`Zenovay already installed correctly for ${p.name} (${m})`}),s({type:`done`,command:`init`,exitCode:0}),0;s({type:`info`,message:`Using site ${p.id} (${p.name}) trackingCode=${p.trackingCode??p.id}`});let h=p.trackingCode??p.id;if(!J(h))return s({type:`error`,code:`invalid_tracking_code`,message:`tracking code "${h}" has an unexpected format; aborting to avoid broken markup`}),1;let g=new de({cwd:t.cwd}),_=e=>g.journalTrustedWrite(e);if(c.id===`plain-html`){let e=await Yt({cwd:t.cwd,trackingCode:h,updateOnly:f?.recommendation===`update-tracking-code`,beforeWrite:_});if(e.installed.length===0&&e.skipped.length===0)return s({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}}),s({type:`done`,command:`init`,exitCode:1}),1;s({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 sn({cwd:t.cwd,trackingCode:h,beforeWrite:_});if(e.fellThrough||e.errors.length>0)return s({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}}),s({type:`done`,command:`init`,exitCode:1}),1;s({type:`info`,message:`tracker inserted: ${e.installed[0]??`already installed — nothing to change`}`})}else{let e=await dn({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 s({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}}),s({type:`done`,command:`init`,exitCode:1}),1;s({type:`info`,message:`tracker inserted: ${e.installed[0]??`already installed — nothing to change`}`})}let v=await _t(t.cwd,c,h,{beforeWrite:_});if(v.addedKeys.length>0&&s({type:`info`,message:`env vars added: ${v.addedKeys.join(`,`)}`}),t.firstParty!==!1){let e=await Ln(t.cwd,{trackingCode:h,forceHost:yn(t.host),beforeWrite:_});e.proxyFile&&e.proxyAction!==`manual`&&e.proxyAction!==`skipped`?s({type:`info`,message:`first-party tracking enabled — analytics now load from your own domain (${Tr(t.cwd,e.proxyFile)}), so visitors on Safari/Brave and other strict-privacy browsers are counted too`}):e.manual&&s({type:`info`,message:e.manual})}else s({type:`info`,message:"first-party tracking skipped (--no-first-party) — enable it later with `zenovay init --host <cloudflare-pages|vercel|netlify|nextjs>`"});return s({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 s({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 xr=({opts:t,onExit:i})=>{let{exit:s}=ne(),{theme:c}=_(),[l,u]=I(`intro`),[d,f]=I(null),[m,v]=I([]),[y,b]=I(null),[x,S]=I(null),[C,w]=I(null),[T,E]=I([]),[D,O]=I(void 0),[te,M]=I(null),[re,ie]=I(null),[ae,oe]=I(null),[se,R]=I(0),[ce,z]=I(`skipped`),[B,V]=I(null),[le,ue]=I(null),[de,fe]=I(null),H=F(new Set),[pe,me]=I(0),he=F(!1),ge=F(null),U=F(!0),_e=N.useCallback(e=>{let t=H.current.size;for(let t of e)t&&H.current.add(t);H.current.size!==t&&me(H.current.size)},[]),[ve,ye]=I(null),W=F(null),be=F(!1),[xe,Se]=I(!1),[Ce,we]=I(void 0),G=F(null),Te=N.useCallback(e=>new Promise(t=>{G.current=t,we(e),Se(!0)}),[]),Ee=N.useCallback(e=>{Se(!1);let t=G.current;G.current=null,t?.(e)},[]),K=N.useCallback((e,t,n,r)=>{U.current&&(U.current=!1,s(),i(e,t,n,r))},[s,i]);j((e,t)=>{let n=e.toLowerCase()===`q`||t.escape;n&&(l===`error`?K(1):l===`create-site`&&K(0))}),P(()=>{let e=process.env.TERM_PROGRAM===`vscode`,t=!!process.stdout.isTTY&&!e;return t&&process.stdout.write(`\x1B[?1049h\x1B[H`),()=>{U.current=!1,W.current?.abort(),G.current?.(null),G.current=null,t&&process.stdout.write(`\x1B[?1049l`)}},[]),P(()=>{be.current||(be.current=!0,(async()=>{try{ue(await or(t.cwd));let r=!!process.stdout.isTTY&&!t.yes&&!t.json;r&&await new Promise(e=>setTimeout(e,1400)),u(`detecting`);let i=await gt(t.cwd);if(!i){w(`Could not detect your framework. Supported: Next.js, Nuxt, SvelteKit, Astro, Remix, plain HTML.`),u(`error`);return}f(i);let s=await a({strict:!1});!process.env.ZENOVAY_API_TOKEN&&!s&&(u(`login`),await p({cliVersion:t.cliVersion,offerCompletions:!1})),u(`loading-sites`);let c=await e(),l=await a({strict:!1}),d=new n({config:c,cliVersion:t.cliVersion,token:l}),[m,h]=await Promise.all([d.getSites(),o(t.cwd,``).catch(()=>null)]),g=await Kr(t.cwd);if(v(m),b(g),m.length===0){u(`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.`),u(`error`);return}let n=e.trackingCode??e.id;if(h?.foundTrackingCodes.includes(n)){S(e),u(`already-installed`);return}S(e),kr(e,i,t,{setPhase:u,setErrorMsg:w,setTasks:E,setLiveLine:O,setSandboxStats:M,setVerifyResult:ie,setFirstParty:oe,setPendingApproval:ye,askHostChoice:Te,recordChangedPaths:_e,registerBridge:e=>{W.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),u(`already-installed`);return}}let _=tr(m,g);if(t.yes&&_){S(_),kr(_,i,t,{setPhase:u,setErrorMsg:w,setTasks:E,setLiveLine:O,setSandboxStats:M,setVerifyResult:ie,setFirstParty:oe,setPendingApproval:ye,askHostChoice:Te,recordChangedPaths:_e,registerBridge:e=>{W.current=e}});return}u(`site-picker`)}catch(e){w(e.message),u(`error`)}})())},[]),P(()=>{l===`error`&&(W.current?.abort(),setTimeout(()=>K(1),8e3))},[l]);let De=async()=>{if(!he.current){if(he.current=!0,z(`verified`),!x){u(`success`);return}try{let i=await e();if(!U.current)return;let o=await a({strict:!1});if(!U.current)return;let s=new n({config:i,cliVersion:t.cliVersion,token:o}),c=await s.getSetupDestination(x.id);if(!U.current)return;V(c);let l=r(x.id,c);if(l){K(0,`quit`,x,l);return}}catch{U.current&&K(0,`quit`,x,r(x.id,null));return}U.current&&u(`success`)}};return N.createElement(k,{flexDirection:`column`},N.createElement(h,{version:t.cliVersion,subtitle:`AI install wizard`}),l===`intro`&&N.createElement(Ar,null),l===`detecting`&&N.createElement(g,{title:`Scanning`,state:`busy`},N.createElement(k,null,N.createElement(A,{color:c.accent},N.createElement(L,{type:`dots`})),N.createElement(A,null,` Detecting framework…`))),l===`login`&&N.createElement(g,{title:`Authenticating`,state:`busy`},N.createElement(A,null,`Opening browser for login… (paste ZENOVAY_API_TOKEN env var to skip)`)),l===`loading-sites`&&N.createElement(g,{title:`Loading your sites`,state:`busy`},N.createElement(k,null,N.createElement(A,{color:c.accent},N.createElement(L,{type:`dots`})),N.createElement(A,null,` Fetching your Zenovay sites…`))),l===`already-installed`&&x&&N.createElement(Nr,{site:x,onContinueSetup:()=>{if(t.skipVerify){z(`skipped`),u(`success`);return}ge.current=Date.now(),R(0),u(`visit-prompt`)},onReinstall:()=>{u(`site-picker`)},onExit:()=>K(0,`quit`,x)}),l===`site-picker`&&d&&N.createElement(Pr,{sites:m,preselectHint:y,onPick:e=>{if(e===`create-new`){u(`create-site`);return}S(e),kr(e,d,t,{setPhase:u,setErrorMsg:w,setTasks:E,setLiveLine:O,setSandboxStats:M,setVerifyResult:ie,setFirstParty:oe,setPendingApproval:ye,askHostChoice:Te,recordChangedPaths:_e,registerBridge:e=>{W.current=e}})}}),l===`create-site`&&N.createElement(g,{title:`Add a site first`,state:`warn`},N.createElement(A,{color:c.warn},`You don't have a Zenovay site yet. Create one at `,_r,`(takes ~30 seconds), then re-run `,N.createElement(A,{color:c.accent},`zenovay init`),` here.`),N.createElement(k,{marginTop:1},N.createElement(A,{color:c.muted},`Press `),N.createElement(A,{color:c.accent},`q`),N.createElement(A,{color:c.muted},` to exit.`))),l===`agent`&&d&&x&&N.createElement(Mr,{adapter:d,site:x,tasks:T,liveLine:D,pendingApproval:ve,onApprove:e=>{ve&&W.current?.resolve(ve.id,e)},pendingHostChoice:xe,hostChoiceNote:Ce,onHostChoice:Ee}),l===`install-complete`&&d&&x&&N.createElement(Rr,{cwd:t.cwd,adapter:d,site:x,stats:te,modifiedFileCount:pe,verify:re,firstParty:ae,onCommit:()=>u(`commit-prompt`),onSkipCommit:()=>u(`deploy-prompt`),onQuit:()=>K(0,`quit`,x)}),l===`commit-prompt`&&x&&N.createElement(Br,{cwd:t.cwd,baseline:le??{isRepository:!1,root:null,dirtyPaths:[]},changedPaths:[...H.current],onDone:e=>{fe(e.message),e.pushed&&O(`Pushed ${e.shortSha} to ${e.branch}`),u(`deploy-prompt`)},onError:e=>{w(e),u(`error`)}}),l===`deploy-prompt`&&x&&N.createElement(Vr,{site:x,notice:de,onDeployed:()=>{t.skipVerify?(z(`skipped`),u(`success`)):(ge.current=Date.now(),u(`visit-prompt`))},onSkip:()=>{z(`skipped`),u(`success`)},onQuit:()=>K(0,`quit`,x)}),l===`visit-prompt`&&x&&N.createElement(Hr,{site:x,onContinue:()=>u(`verify`),onQuit:()=>K(0,`quit`,x)}),l===`verify`&&x&&N.createElement(Ur,{site:x,since:ge.current??Date.now(),elapsed:se,onTick:e=>R(e),onArrived:()=>{De()},onTimeout:()=>{z(`unverified`),u(`success`)},onSkip:()=>{z(`skipped`),u(`success`)},onQuit:()=>K(0,`quit`,x)}),l===`success`&&d&&x&&N.createElement(Lr,{adapter:d,site:x,stats:te,modifiedFileCount:pe,outcome:ce,dashboardUrl:B?.kind===`dashboard`?B.url:void 0,firstParty:ae,onPick:e=>K(0,e,x)}),l===`error`&&N.createElement(g,{title:`Install failed`,state:`err`},N.createElement(A,{color:c.error},C??`Unknown error`)),N.createElement(ee,{items:l===`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 Sr(e,t,n,r){if(e.firstParty===!1){let e={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 n.setFirstParty?.(e),e}if(!n.setFirstParty)return null;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=yn(e.host),a=null;try{if(a=await Ln(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 Ln(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=Er(a,e.cwd);return n.setTasks(e=>e.map(e=>e.id===`first-party`?{...e,status:`done`,detail:o}:e)),n.setLiveLine(void 0),a}function Cr(e){return!e||e.changedFiles.length===0?`Already installed correctly`:e.proxyAction===`updated`?`Tracker already present; first-party proxy upgraded`:e.proxyAction===`created`?`Tracker already present; first-party proxy added`:`Tracker already present; first-party tracking updated`}function wr(e){return`${e} ${e===1?`file`:`files`}`}function Tr(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 Er(e,t){return e?e.proxyFile&&e.proxyAction!==`manual`&&e.proxyAction!==`skipped`?`now loads from your domain (${Tr(t,e.proxyFile)})`:e.manual?`standard tracking active — see note below for all-browser coverage`:`standard tracking active`:`standard tracking active`}function Dr(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 Or(e,t,n){n.setLiveLine(`Verifying the tracker is in your source…`);try{let r=await o(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 kr(r,i,s,c){try{c.setPhase(`agent`);let l=await e(),u=await a({strict:!1}),d=new n({config:l,cliVersion:s.cliVersion,token:u}),f=new de({cwd:s.cwd}),p=e=>f.journalTrustedWrite(e),m=r.trackingCode??r.id;if(!J(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 o(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 q({accessToken:u.accessToken}).catch(()=>void 0);let e=await Sr(s,m,c,p);c.setVerifyResult?.({ok:!0,detail:Cr(e)}),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).`),i.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 sn({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 _t(s.cwd,i,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 q({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:Dr(e)}:t))}else c.setTasks(e=>e.map(e=>e.id===`mcp`?{...e,status:`done`,detail:`skipped`}:e));await Or(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 Sr(s,m,c,p),c.setPhase(`install-complete`);return}c.setLiveLine(`Custom Next.js structure — handing off to the AI agent…`)}let g=i.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 Yt({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 _t(s.cwd,i,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 q({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:Dr(e)}:t))}else c.setTasks(e=>e.map(e=>e.id===`mcp`?{...e,status:`done`,detail:`skipped`}:e));await Or(s.cwd,m,c),c.setSandboxStats?.({reads:e.installed.length,writes:e.installed.length,rounds:0}),await Sr(s,m,c,p),c.setPhase(`install-complete`);return}{let e=await dn({cwd:s.cwd,trackingCode:m,siteId:r.id,adapter:i,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:i.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(`${i.displayName} — using fast install path (no AI needed)…`);let t=await _t(s.cwd,i,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 q({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:Dr(e)}:t))}else c.setTasks(e=>e.map(e=>e.id===`mcp`?{...e,status:`done`,detail:`skipped`}:e));await Or(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 Sr(s,m,c,p),c.setPhase(`install-complete`);return}c.setLiveLine(`${i.displayName} needs a closer look — using the AI installer (a bit slower than the fast path)…`)}let _=i.buildSnippets({trackingCode:m,siteId:r.id}),v=`Install Zenovay tracking into this ${i.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`+i.files.map(e=>` - ${e.path}`).join(`
|
|
349
349
|
`)+`
|
|
350
350
|
3. Insert the tracker using the snippet below.
|
|
351
351
|
4. Confirm the change with a diff before writing.
|
|
@@ -354,4 +354,4 @@ Snippet reference (anchored by anchorKind — adapt to the actual file):
|
|
|
354
354
|
`+_.map(e=>` ${e.anchorKind} @ ${e.targetPath}:\n ${e.code.replace(/\n/g,`
|
|
355
355
|
`)}`).join(`
|
|
356
356
|
|
|
357
|
-
`);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=Hn({mode:Vn(s)});c.registerBridge(b);let ee=b.subscribe(e=>c.setPendingApproval(e)),x=null,S=``,C=0;try{await Ut({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`,i.displayName),c.setLiveLine(`Detected ${i.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=>{S=(S+e).slice(-600);let t=Date.now();if(t-C<280)return;C=t;let n=S.replace(/\s+/g,` `).trim().slice(-80);n.length>4&&c.setLiveLine(n)}},initialMessages:[{role:`user`,content:v}],diagnosis:h,targetTrackingCode:m})}catch(e){x=e}finally{ee(),c.setPendingApproval(null)}let w=f.stats();c.recordChangedPaths?.(w.writtenPaths);let T=w.writes>0?await o(s.cwd,m).catch(()=>null):null,E=Kt(w,T?.foundTrackingCodes??[],m,x);if(!E.ok)throw Error(E.error);y(`write`,`done`),y(`env`,`active`),c.setLiveLine(`Adding env var to .env.local`);let D=await yt(s.cwd,{[i.envVarName]:m},{beforeWrite:p});if((D.addedKeys.length>0||D.updatedKeys.length>0)&&c.recordChangedPaths?.([D.file]),y(`env`,`done`,`${D.addedKeys.length} key(s) added`),!s.skipMcp&&u){y(`mcp`,`active`),c.setLiveLine(`Detecting Cursor / Claude Desktop / VS Code…`);let e=await q({accessToken:u.accessToken}).catch(e=>({installed:[],skipped:[],errors:[{client:`mcp`,message:e.message}]}));y(`mcp`,`done`,Er(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 Dr(s.cwd,m,c),c.setSandboxStats?.(w),await xr(s,m,c,p),c.setPhase(`install-complete`)}catch(e){c.setErrorMsg(e.message),c.setPhase(`error`)}}const kr=()=>{let{theme:e}=_();return N.createElement(g,{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.`))},Ar=({siteName:e,note:t,onChoose:n})=>{let{theme:r}=_(),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(b,{items:i,onSelect:e=>n(e===`skip`?null:e)})))},jr=({adapter:e,site:t,tasks:n,liveLine:r,pendingApproval:i,onApprove:a,pendingHostChoice:o,hostChoiceNote:s,onHostChoice:c})=>{let{theme:l}=_(),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(Xn,{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(v,{key:i.id,filePath:i.path,oldContent:i.oldContent,newContent:i.newContent,onApprove:a})):o&&c?N.createElement(Ar,{siteName:t.name,note:s,onChoose:c}):N.createElement(N.Fragment,null,N.createElement(k,{paddingX:2,paddingTop:1},N.createElement(y,{done:n.filter(e=>e.status===`done`).length,total:n.length,label:n.find(e=>e.status===`active`)?.label})),N.createElement($n,{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)))},Mr=({site:e,onContinueSetup:t,onReinstall:n,onExit:r})=>{let{theme:i}=_();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(g,{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`))))},Nr=({sites:e,preselectHint:t,onPick:n})=>{let r=er(e,t),i=e.filter(e=>e.id!==r?.id),a=r?[r,...i]:i,o=[...a.map(e=>({label:Wr(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(g,{title:t?`Pick a site (best match: ${t})`:`Pick a site`,state:`idle`},N.createElement(b,{items:o,onSelect:n}))};function Pr(){let e=process.argv[1]??``;return e.includes(`/_npx/`)||e.includes(`\\_npx\\`)||process.env.npm_execpath?.includes(`npx`)?`npx`:`global`}const Fr=({k:e,primary:t})=>{let{theme:n}=_();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},`] `))},Ir=({adapter:e,site:t,stats:n,modifiedFileCount:r,outcome:a,dashboardUrl:o,firstParty:s,onPick:c})=>{let{theme:u}=_(),d=Pr(),f=d===`npx`?`npx @zenovay/cli`:`zenovay`,p=o??i(t),m=a===`verified`,h=m?`You’re live on Zenovay`:a===`unverified`?`Tracker installed — not yet verified`:`Tracker installed — verification skipped`,v=m?`✓ First event received from ${t.name}`:a===`unverified`?`Installation finished, but no new event was confirmed.`:`Installation finished without checking for a new event.`,y=n&&n.rounds>0?`${Cr(r)} · ${n.rounds} agent round(s)`:r>0?`${Cr(r)} · programmatic (no AI calls)`:null;return j((e,t)=>{let n=e.toLowerCase();n===`o`?l(p):n===`q`||t.escape||n===`s`?c(`quit`):m&&(n===`w`||t.return)?c(`watch`):m&&n===`e`?c(`events`):!m&&t.return&&c(`quit`)},{isActive:!0}),N.createElement(g,{title:h,state:m?`ok`:`warn`},N.createElement(A,{bold:!0,color:m?u.success:u.warn},v),N.createElement(A,{color:u.accent},`─`.repeat(18)),N.createElement(k,{marginTop:1,flexDirection:`column`},N.createElement(Z,{label:`Framework`,value:e.displayName}),N.createElement(Z,{label:`Site`,value:N.createElement(Bn,{url:t.url,label:t.name})}),t.trackingCode?N.createElement(Z,{label:`Tracker`,value:N.createElement(A,{color:u.muted},t.trackingCode)}):N.createElement(Z,{label:`Tracker`,value:N.createElement(A,{color:u.warn},t.id,` (using site ID — verify in dashboard)`)}),y?N.createElement(Z,{label:`Changes`,value:N.createElement(A,{color:u.muted},y)}):null,m?null:N.createElement(Z,{label:`Verification`,value:N.createElement(A,{color:u.warn},a===`unverified`?`No event confirmed`:`Skipped`)}),N.createElement(Z,{label:`Dashboard`,value:N.createElement(Bn,{url:p})})),s&&s.proxyFile&&s.proxyAction!==`manual`&&s.proxyAction!==`skipped`?N.createElement(k,{marginTop:1},N.createElement(A,{color:u.success},`✓ `),N.createElement(A,{color:u.muted},`Analytics now load from your own domain — after you deploy, Safari, Edge and Brave visitors are counted too.`)):s?.manual?N.createElement(k,{marginTop:1,flexDirection:`column`},N.createElement(A,{color:u.muted},`Counting visitors in every browser (optional):`),N.createElement(A,{color:u.muted},` `,s.manual)):null,N.createElement(k,{marginTop:1,flexDirection:`column`},N.createElement(A,{color:u.dim},`Next steps`),m?N.createElement(k,{marginTop:1},N.createElement(A,null,` `),N.createElement(Fr,{k:`W`,primary:!0}),N.createElement(A,null,`Watch live in this terminal `),N.createElement(A,{color:u.muted},`— visitors, pages, sources, vitals`)):null,N.createElement(k,null,N.createElement(A,null,` `),N.createElement(Fr,{k:`O`}),N.createElement(A,null,`Open the dashboard in your browser`)),m?N.createElement(k,null,N.createElement(A,null,` `),N.createElement(Fr,{k:`E`}),N.createElement(A,null,`Stream events as they fire `),N.createElement(A,{color:u.muted},`— page views, custom events, live`)):null,N.createElement(k,null,N.createElement(A,null,` `),N.createElement(Fr,{k:`S`}),N.createElement(A,null,`Exit to shell`))),d===`npx`?N.createElement(k,{marginTop:1,flexDirection:`column`,borderStyle:`single`,borderColor:u.warn,paddingX:1},N.createElement(A,{color:u.warn,bold:!0},`Heads up — you ran via npx`),N.createElement(A,{color:u.muted},"The `zenovay` command isn’t on your PATH yet. After you exit, run:"),N.createElement(k,{marginTop:1},N.createElement(A,{color:u.fg},` npm i -g @zenovay/cli `),N.createElement(A,{color:u.muted},"→ then `zenovay overview` works directly"))):N.createElement(k,{marginTop:1},N.createElement(A,{color:u.muted},`From your shell: `),N.createElement(A,{color:u.fg},f,` overview`),N.createElement(A,{color:u.muted},` · `),N.createElement(A,{color:u.fg},f,` --help`)))},Lr=({cwd:e,adapter:t,site:n,stats:r,modifiedFileCount:i,verify:a,firstParty:o,onCommit:s,onSkipCommit:c,onQuit:l})=>{let{theme:u}=_();return Ur((e,t)=>{e===`q`||e===`Q`||t.escape?l():e===`y`||e===`Y`||t.return?s():(e===`n`||e===`N`||e===`s`||e===`S`)&&c()}),N.createElement(g,{title:`Tracker installed`,state:a&&!a.ok?`warn`:`ok`},a?N.createElement(A,null,N.createElement(A,{color:a.ok?u.success:u.warn},a.ok?`✔ Verified — `:`⚠ `),a.detail):N.createElement(A,null,N.createElement(A,{color:u.success},`✔ `),`The Zenovay tracker is in your project.`),N.createElement(k,{marginTop:1},N.createElement(A,{color:u.muted},`Framework: `),N.createElement(A,null,t.displayName)),N.createElement(k,null,N.createElement(A,{color:u.muted},`Site: `),N.createElement(A,null,n.name,` (`,n.url,`)`)),r&&N.createElement(k,null,N.createElement(A,{color:u.muted},`Modified: `),N.createElement(A,null,Cr(i))),N.createElement(Rr,{cwd:e,firstParty:o}),N.createElement(k,{marginTop:1},N.createElement(A,null,`Commit + push these changes to git? `),N.createElement(A,{color:u.accent},`[Y/n]`)))},Rr=({cwd:e,firstParty:t})=>{let{theme:n}=_();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},`(`,wr(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},zr=({cwd:e,baseline:t,changedPaths:n,onDone:r,onError:i})=>{let{theme:a}=_(),[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 cr({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(g,{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)))},Br=({site:e,notice:t,onDeployed:n,onSkip:r,onQuit:i})=>{let{theme:a}=_();return Ur((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(g,{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(Bn,{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`)))},Vr=({site:e,onContinue:t,onQuit:n})=>{let{theme:r}=_();return Ur((e,r)=>{e===`q`||e===`Q`||r.escape?n():t()}),N.createElement(g,{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(Bn,{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.`)))},Hr=({site:t,since:r,elapsed:i,onTick:o,onArrived:s,onTimeout:c,onSkip:l,onQuit:u})=>{let{theme:d}=_(),[f,p]=I(`preflight`),[m,h]=I(``),[v,y]=I([]),b=F(!1),ee=t.trackingCode??t.id,x=async()=>{p(`preflight`),h(`Fetching ${t.url}…`);let e=await hr(t.url,ee);if(b.current)return;if(e.state===`tracker-correct`){p(`polling`),h(`Tracker detected on live site — waiting for first hit…`),S();return}if(e.state===`tracker-wrong-id`){p(`wrong-id-on-live`),y(e.foundCodes),h(`Live site has Zenovay but with id(s): ${e.foundCodes.join(`, `)}`);return}if(e.state===`proxy-broken`){p(`proxy-broken`),h(`${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])`:``:``;h(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}.`)},S=async()=>{try{let i=await e(),c=await a({strict:!1}),l=new n({config:i,cliVersion:`0`,token:c}),u=await At(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,x(),()=>{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`)&&x()},{isActive:!0});let C=Math.floor(i/1e3);return f===`preflight`?N.createElement(g,{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(g,{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(g,{title:`Live site has a different tracking code`,state:`warn`},N.createElement(A,{color:d.warn},`Expected: `,N.createElement(A,{color:d.accent},ee),` `,`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(g,{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(g,{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(g,{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(g,{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,` (`,C,`s elapsed)`)),N.createElement(k,{marginTop:1},N.createElement(A,{color:d.muted},`Reload the page if nothing arrives within ~30 seconds.`)))};function Ur(e){j((t,n)=>{e(t,{return:n.return,escape:n.escape})},{isActive:!0})}function Wr(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 Gr(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{gr as ADD_SITE_URL,Mr as AlreadyInstalledPanel,Ar as HostChoicePanel,Lr as InstallCompletePanel,Cr as formatFileCount,_r as initCommand,Sr as noOpInstallVerificationDetail};
|
|
357
|
+
`);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=Un({mode:Hn(s)});c.registerBridge(b);let ee=b.subscribe(e=>c.setPendingApproval(e)),x=null,S=``,C=0;try{await Wt({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`,i.displayName),c.setLiveLine(`Detected ${i.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=>{S=(S+e).slice(-600);let t=Date.now();if(t-C<280)return;C=t;let n=S.replace(/\s+/g,` `).trim().slice(-80);n.length>4&&c.setLiveLine(n)}},initialMessages:[{role:`user`,content:v}],diagnosis:h,targetTrackingCode:m})}catch(e){x=e}finally{ee(),c.setPendingApproval(null)}let w=f.stats();c.recordChangedPaths?.(w.writtenPaths);let T=w.writes>0?await o(s.cwd,m).catch(()=>null):null,E=qt(w,T?.foundTrackingCodes??[],m,x);if(!E.ok)throw Error(E.error);y(`write`,`done`),y(`env`,`active`),c.setLiveLine(`Adding env var to .env.local`);let D=await _t(s.cwd,i,m,{beforeWrite:p});if((D.addedKeys.length>0||D.updatedKeys.length>0)&&c.recordChangedPaths?.([D.file]),y(`env`,`done`,`${D.addedKeys.length} key(s) added`),!s.skipMcp&&u){y(`mcp`,`active`),c.setLiveLine(`Detecting Cursor / Claude Desktop / VS Code…`);let e=await q({accessToken:u.accessToken}).catch(e=>({installed:[],skipped:[],errors:[{client:`mcp`,message:e.message}]}));y(`mcp`,`done`,Dr(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 Or(s.cwd,m,c),c.setSandboxStats?.(w),await Sr(s,m,c,p),c.setPhase(`install-complete`)}catch(e){c.setErrorMsg(e.message),c.setPhase(`error`)}}const Ar=()=>{let{theme:e}=_();return N.createElement(g,{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.`))},jr=({siteName:e,note:t,onChoose:n})=>{let{theme:r}=_(),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(b,{items:i,onSelect:e=>n(e===`skip`?null:e)})))},Mr=({adapter:e,site:t,tasks:n,liveLine:r,pendingApproval:i,onApprove:a,pendingHostChoice:o,hostChoiceNote:s,onHostChoice:c})=>{let{theme:l}=_(),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(Zn,{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(v,{key:i.id,filePath:i.path,oldContent:i.oldContent,newContent:i.newContent,onApprove:a})):o&&c?N.createElement(jr,{siteName:t.name,note:s,onChoose:c}):N.createElement(N.Fragment,null,N.createElement(k,{paddingX:2,paddingTop:1},N.createElement(y,{done:n.filter(e=>e.status===`done`).length,total:n.length,label:n.find(e=>e.status===`active`)?.label})),N.createElement(er,{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)))},Nr=({site:e,onContinueSetup:t,onReinstall:n,onExit:r})=>{let{theme:i}=_();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(g,{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`))))},Pr=({sites:e,preselectHint:t,onPick:n})=>{let r=tr(e,t),i=e.filter(e=>e.id!==r?.id),a=r?[r,...i]:i,o=[...a.map(e=>({label:Gr(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(g,{title:t?`Pick a site (best match: ${t})`:`Pick a site`,state:`idle`},N.createElement(b,{items:o,onSelect:n}))};function Fr(){let e=process.argv[1]??``;return e.includes(`/_npx/`)||e.includes(`\\_npx\\`)||process.env.npm_execpath?.includes(`npx`)?`npx`:`global`}const Ir=({k:e,primary:t})=>{let{theme:n}=_();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},`] `))},Lr=({adapter:e,site:t,stats:n,modifiedFileCount:r,outcome:a,dashboardUrl:o,firstParty:s,onPick:c})=>{let{theme:u}=_(),d=Fr(),f=d===`npx`?`npx @zenovay/cli`:`zenovay`,p=o??i(t),m=a===`verified`,h=m?`You’re live on Zenovay`:a===`unverified`?`Tracker installed — not yet verified`:`Tracker installed — verification skipped`,v=m?`✓ First event received from ${t.name}`:a===`unverified`?`Installation finished, but no new event was confirmed.`:`Installation finished without checking for a new event.`,y=n&&n.rounds>0?`${wr(r)} · ${n.rounds} agent round(s)`:r>0?`${wr(r)} · programmatic (no AI calls)`:null;return j((e,t)=>{let n=e.toLowerCase();n===`o`?l(p):n===`q`||t.escape||n===`s`?c(`quit`):m&&(n===`w`||t.return)?c(`watch`):m&&n===`e`?c(`events`):!m&&t.return&&c(`quit`)},{isActive:!0}),N.createElement(g,{title:h,state:m?`ok`:`warn`},N.createElement(A,{bold:!0,color:m?u.success:u.warn},v),N.createElement(A,{color:u.accent},`─`.repeat(18)),N.createElement(k,{marginTop:1,flexDirection:`column`},N.createElement(Z,{label:`Framework`,value:e.displayName}),N.createElement(Z,{label:`Site`,value:N.createElement(Vn,{url:t.url,label:t.name})}),t.trackingCode?N.createElement(Z,{label:`Tracker`,value:N.createElement(A,{color:u.muted},t.trackingCode)}):N.createElement(Z,{label:`Tracker`,value:N.createElement(A,{color:u.warn},t.id,` (using site ID — verify in dashboard)`)}),y?N.createElement(Z,{label:`Changes`,value:N.createElement(A,{color:u.muted},y)}):null,m?null:N.createElement(Z,{label:`Verification`,value:N.createElement(A,{color:u.warn},a===`unverified`?`No event confirmed`:`Skipped`)}),N.createElement(Z,{label:`Dashboard`,value:N.createElement(Vn,{url:p})})),s&&s.proxyFile&&s.proxyAction!==`manual`&&s.proxyAction!==`skipped`?N.createElement(k,{marginTop:1},N.createElement(A,{color:u.success},`✓ `),N.createElement(A,{color:u.muted},`Analytics now load from your own domain — after you deploy, Safari, Edge and Brave visitors are counted too.`)):s?.manual?N.createElement(k,{marginTop:1,flexDirection:`column`},N.createElement(A,{color:u.muted},`Counting visitors in every browser (optional):`),N.createElement(A,{color:u.muted},` `,s.manual)):null,N.createElement(k,{marginTop:1,flexDirection:`column`},N.createElement(A,{color:u.dim},`Next steps`),m?N.createElement(k,{marginTop:1},N.createElement(A,null,` `),N.createElement(Ir,{k:`W`,primary:!0}),N.createElement(A,null,`Watch live in this terminal `),N.createElement(A,{color:u.muted},`— visitors, pages, sources, vitals`)):null,N.createElement(k,null,N.createElement(A,null,` `),N.createElement(Ir,{k:`O`}),N.createElement(A,null,`Open the dashboard in your browser`)),m?N.createElement(k,null,N.createElement(A,null,` `),N.createElement(Ir,{k:`E`}),N.createElement(A,null,`Stream events as they fire `),N.createElement(A,{color:u.muted},`— page views, custom events, live`)):null,N.createElement(k,null,N.createElement(A,null,` `),N.createElement(Ir,{k:`S`}),N.createElement(A,null,`Exit to shell`))),d===`npx`?N.createElement(k,{marginTop:1,flexDirection:`column`,borderStyle:`single`,borderColor:u.warn,paddingX:1},N.createElement(A,{color:u.warn,bold:!0},`Heads up — you ran via npx`),N.createElement(A,{color:u.muted},"The `zenovay` command isn’t on your PATH yet. After you exit, run:"),N.createElement(k,{marginTop:1},N.createElement(A,{color:u.fg},` npm i -g @zenovay/cli `),N.createElement(A,{color:u.muted},"→ then `zenovay overview` works directly"))):N.createElement(k,{marginTop:1},N.createElement(A,{color:u.muted},`From your shell: `),N.createElement(A,{color:u.fg},f,` overview`),N.createElement(A,{color:u.muted},` · `),N.createElement(A,{color:u.fg},f,` --help`)))},Rr=({cwd:e,adapter:t,site:n,stats:r,modifiedFileCount:i,verify:a,firstParty:o,onCommit:s,onSkipCommit:c,onQuit:l})=>{let{theme:u}=_();return Wr((e,t)=>{e===`q`||e===`Q`||t.escape?l():e===`y`||e===`Y`||t.return?s():(e===`n`||e===`N`||e===`s`||e===`S`)&&c()}),N.createElement(g,{title:`Tracker installed`,state:a&&!a.ok?`warn`:`ok`},a?N.createElement(A,null,N.createElement(A,{color:a.ok?u.success:u.warn},a.ok?`✔ Verified — `:`⚠ `),a.detail):N.createElement(A,null,N.createElement(A,{color:u.success},`✔ `),`The Zenovay tracker is in your project.`),N.createElement(k,{marginTop:1},N.createElement(A,{color:u.muted},`Framework: `),N.createElement(A,null,t.displayName)),N.createElement(k,null,N.createElement(A,{color:u.muted},`Site: `),N.createElement(A,null,n.name,` (`,n.url,`)`)),r&&N.createElement(k,null,N.createElement(A,{color:u.muted},`Modified: `),N.createElement(A,null,wr(i))),N.createElement(zr,{cwd:e,firstParty:o}),N.createElement(k,{marginTop:1},N.createElement(A,null,`Commit + push these changes to git? `),N.createElement(A,{color:u.accent},`[Y/n]`)))},zr=({cwd:e,firstParty:t})=>{let{theme:n}=_();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},`(`,Tr(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},Br=({cwd:e,baseline:t,changedPaths:n,onDone:r,onError:i})=>{let{theme:a}=_(),[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 lr({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(g,{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)))},Vr=({site:e,notice:t,onDeployed:n,onSkip:r,onQuit:i})=>{let{theme:a}=_();return Wr((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(g,{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(Vn,{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`)))},Hr=({site:e,onContinue:t,onQuit:n})=>{let{theme:r}=_();return Wr((e,r)=>{e===`q`||e===`Q`||r.escape?n():t()}),N.createElement(g,{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(Vn,{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.`)))},Ur=({site:t,since:r,elapsed:i,onTick:o,onArrived:s,onTimeout:c,onSkip:l,onQuit:u})=>{let{theme:d}=_(),[f,p]=I(`preflight`),[m,h]=I(``),[v,y]=I([]),b=F(!1),ee=t.trackingCode??t.id,x=async()=>{p(`preflight`),h(`Fetching ${t.url}…`);let e=await gr(t.url,ee);if(b.current)return;if(e.state===`tracker-correct`){p(`polling`),h(`Tracker detected on live site — waiting for first hit…`),S();return}if(e.state===`tracker-wrong-id`){p(`wrong-id-on-live`),y(e.foundCodes),h(`Live site has Zenovay but with id(s): ${e.foundCodes.join(`, `)}`);return}if(e.state===`proxy-broken`){p(`proxy-broken`),h(`${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])`:``:``;h(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}.`)},S=async()=>{try{let i=await e(),c=await a({strict:!1}),l=new n({config:i,cliVersion:`0`,token:c}),u=await jt(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,x(),()=>{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`)&&x()},{isActive:!0});let C=Math.floor(i/1e3);return f===`preflight`?N.createElement(g,{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(g,{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(g,{title:`Live site has a different tracking code`,state:`warn`},N.createElement(A,{color:d.warn},`Expected: `,N.createElement(A,{color:d.accent},ee),` `,`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(g,{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(g,{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(g,{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(g,{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,` (`,C,`s elapsed)`)),N.createElement(k,{marginTop:1},N.createElement(A,{color:d.muted},`Reload the page if nothing arrives within ~30 seconds.`)))};function Wr(e){j((t,n)=>{e(t,{return:n.return,escape:n.escape})},{isActive:!0})}function Gr(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 Kr(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{_r as ADD_SITE_URL,Nr as AlreadyInstalledPanel,jr as HostChoicePanel,Rr as InstallCompletePanel,wr as formatFileCount,vr as initCommand,Cr as noOpInstallVerificationDetail};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./config-JVhBplSX.js";import"./api-CBukwv2I.js";import"./token-store-CuZEiQNg.js";import"./detect-installed-DpSaAeH-.js";import"./formatter-PBF-wEt1.js";import"./emit-5vELQfsB.js";import"./open-url-IjqD5f_n.js";import"./secrets-zGZxXoM0.js";import{ADD_SITE_URL as e,AlreadyInstalledPanel as t,HostChoicePanel as n,InstallCompletePanel as r,formatFileCount as i,initCommand as a,noOpInstallVerificationDetail as o}from"./init-
|
|
1
|
+
import"./config-JVhBplSX.js";import"./api-CBukwv2I.js";import"./token-store-CuZEiQNg.js";import"./detect-installed-DpSaAeH-.js";import"./formatter-PBF-wEt1.js";import"./emit-5vELQfsB.js";import"./open-url-IjqD5f_n.js";import"./secrets-zGZxXoM0.js";import{ADD_SITE_URL as e,AlreadyInstalledPanel as t,HostChoicePanel as n,InstallCompletePanel as r,formatFileCount as i,initCommand as a,noOpInstallVerificationDetail as o}from"./init-BO0YSf9G.js";import"./client-DNMRt-Hq.js";import"./snippet-CwowVrmh.js";import"./login-vzW-8q0w.js";import"./theme-DSRmbn9T.js";import"./panel-DbiZwGB3.js";import"./progress-row-BSv_Zm8f.js";import"./prompt-Dae2nnYJ.js";import"./keybar-BY1csJGI.js";import"./sparkline-B7VaYaxH.js";export{a as initCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readConfig as e}from"./config-JVhBplSX.js";import{classifyBump as t,fetchManifest as n}from"./check-D9G0N7NB.js";import{applyManifest as r,detectInstallMethod as i,runNpmGlobalInstall as a}from"./ensure-latest-
|
|
1
|
+
import{readConfig as e}from"./config-JVhBplSX.js";import{classifyBump as t,fetchManifest as n}from"./check-D9G0N7NB.js";import{applyManifest as r,detectInstallMethod as i,runNpmGlobalInstall as a}from"./ensure-latest-DAiAIi4p.js";import"./formatter-PBF-wEt1.js";import{emit$1 as o,isHeadless as s}from"./emit-5vELQfsB.js";const c=`https://zenovay-cli-distribution.zenovay.workers.dev`,l=2e3;async function u(e,t){if(e===`npm-global`||e===`npm-local`||e===`unknown`){let e;try{e=await fetch(`https://registry.npmjs.org/@zenovay/cli/latest`,{signal:AbortSignal.timeout(l),headers:{Accept:`application/json`}})}catch(e){throw Error(`Could not reach the npm registry (${e.message}). Try: npm i -g @zenovay/cli@latest`)}if(!e.ok)throw Error(`npm registry lookup failed (${e.status}). Try: npm i -g @zenovay/cli@latest`);let t=await e.json();if(!t.version)throw Error(`npm registry returned no version`);return{latest:t.version,platforms:{}}}let r=t===c?[t]:[t,c],i=null;for(let e of r)try{return await n({cliBase:e,signal:AbortSignal.timeout(l)})}catch(e){i=e}throw Error(`Could not reach the update server (${i?.message??`unknown error`}). Update via npm instead: npm i -g @zenovay/cli@latest`)}async function d(n){let c=await e(),l=i(),d=await u(l,c.cliBase),f=t(n.cliVersion,d.latest);if(n.check)return s({json:n.json})?o({type:`info`,message:`latest=${d.latest} current=${n.cliVersion} bump=${f}`}):process.stdout.write(`Current: ${n.cliVersion}\nLatest: ${d.latest}\nBump: ${f}\n`),{updated:!1,from:n.cliVersion,to:d.latest};if(f===`none`)return s({json:n.json})||process.stdout.write(`Already on latest (${n.cliVersion}).\n`),{updated:!1,from:n.cliVersion,to:d.latest};if(f===`downgrade`&&!n.forceDowngrade)throw Error(`Refused to downgrade ${n.cliVersion} → ${d.latest}. Pass --force-downgrade if you really want this.`);if(l===`npm-global`){s({json:n.json})||process.stdout.write(`Updating via npm to @zenovay/cli@${d.latest}…\n`);let e=await a(d.latest);return{updated:e,from:n.cliVersion,to:d.latest}}if(l===`npm-local`){let e=`Update your project dependency: npm i @zenovay/cli@${d.latest}`;return s({json:n.json})?o({type:`info`,message:e}):process.stdout.write(`${e}\n`),{updated:!1,from:n.cliVersion,to:d.latest}}try{let e=await r({currentVersion:n.cliVersion,cliBase:c.cliBase,binaryPath:n.binaryPath,forceDowngrade:n.forceDowngrade,manifest:d});return s({json:n.json})?e.updated&&o({type:`update.applied`,from:e.from,to:e.to}):e.updated?process.stdout.write(`Updated ${e.from} → ${e.to}\n`):process.stdout.write(`Not updated (${e.reason??`unknown`}).\n`),e}catch(e){if(/No release binary/i.test(e.message)){let e=`No prebuilt binary for your platform on this release yet. Update via npm instead:\n npm i -g @zenovay/cli@${d.latest}`;return s({json:n.json})?o({type:`info`,message:e}):process.stdout.write(`${e}\n`),{updated:!1,from:n.cliVersion,to:d.latest}}throw e}}export{d as updateCommand};
|
package/dist/wizard-bin.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import(`./init-
|
|
2
|
+
import(`./init-ZniT6LxK.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.
|
|
3
|
+
"version": "1.0.31",
|
|
4
4
|
"description": "Zenovay CLI — AI install wizard + full terminal analytics dashboard",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -78,7 +78,7 @@
|
|
|
78
78
|
"homepage": "https://cli.zenovay.com",
|
|
79
79
|
"repository": {
|
|
80
80
|
"type": "git",
|
|
81
|
-
"url": "https://github.com/zenovay/cli-zenovay.git"
|
|
81
|
+
"url": "git+https://github.com/zenovay/cli-zenovay.git"
|
|
82
82
|
},
|
|
83
83
|
"bugs": {
|
|
84
84
|
"url": "https://cli.zenovay.com/feedback"
|
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import{configDir as e,readConfig as t}from"./config-JVhBplSX.js";import{classifyBump as n,manifestSchema as r,platformKey as i}from"./check-D9G0N7NB.js";import{spawn as a}from"node:child_process";import o from"node:path";import{promises as s,realpathSync as c}from"node:fs";import l from"semver";import{z as u}from"zod";import d from"node:crypto";const f=`i0FuwuAJT+tSZFfjMwpJenQQ6omSFeJMjUOYDdV1uh4=`;async function p(e){let{manifest:t,currentVersion:r,forceDowngrade:a}=e,o=n(r,t.latest);if(o===`none`)return{updated:!1,from:r,to:t.latest,reason:`already-latest`};if(o===`downgrade`&&!a)return{updated:!1,from:r,to:t.latest,reason:`downgrade-blocked`};t.minSupported&&l.lt(r,t.minSupported);let c=i(),u=t.platforms[c];if(!u)throw Error(`No release binary for platform ${c}`);let d=await m(u,e.binaryPath,e.fetchImpl,e.signal);try{return await h(d,u.sha256),await g(u,t.latest,c),await _(d,e.binaryPath),{updated:!0,from:r,to:t.latest}}catch(e){throw await s.unlink(d).catch(()=>void 0),e}}async function m(e,t,n=fetch,r){if(!/^https:\/\//i.test(e.url))throw Error(`Refusing non-HTTPS download URL: ${e.url}`);let i=await n(e.url,{signal:r});if(!i.ok)throw Error(`Download failed: ${i.status}`);let a=Buffer.from(await i.arrayBuffer()),o=`${t}.new-${d.randomBytes(6).toString(`hex`)}`;return await s.writeFile(o,a,{mode:493}),o}async function h(e,t){let n=await s.readFile(e),r=d.createHash(`sha256`).update(n).digest(`hex`);if(r.toLowerCase()!==t.toLowerCase())throw Error(`Checksum mismatch: expected ${t}, got ${r}. Update REFUSED.`)}async function g(e,t,n){let r=Buffer.from(f,`base64`);if(r.length!==32)throw Error(`Invalid release public key — update REFUSED.`);let i=Buffer.from(`${e.sha256}|${t}|${n}`),a=Buffer.from(e.sig,`base64`),o=d.createPublicKey({key:Buffer.concat([Buffer.from(`302a300506032b6570032100`,`hex`),r]),format:`der`,type:`spki`}),s=d.verify(null,i,o,a);if(!s)throw Error(`Signature verification FAILED. Update REFUSED.`)}async function _(e,t){let n=`${t}.old-${Date.now()}`;try{await s.rename(t,n)}catch(e){if(e.code!==`ENOENT`)throw e}try{try{await s.rename(e,t)}catch(n){if(n.code!==`EXDEV`)throw n;await s.copyFile(e,t),await s.unlink(e).catch(()=>void 0)}process.platform!==`win32`&&await s.chmod(t,493),await s.unlink(n).catch(()=>void 0)}catch(e){try{await s.rename(n,t)}catch{}throw e}}const v=2e3,y=3e4,b=5e3,x=5e3,S=36e5,C=new Set([`update`,`health`,`doctor`,`--version`,`-v`]),w=u.object({checkedAt:u.number(),latest:u.string(),platforms:u.record(u.string(),u.unknown()).optional(),binaryDeferredFor:u.string().optional()});function T(){return o.join(e(),`update-cache.json`)}async function E(){try{let e=await s.readFile(T(),`utf8`),t=w.safeParse(JSON.parse(e));return t.success?t.data:null}catch{return null}}async function D(t){try{await s.mkdir(e(),{recursive:!0,mode:448}),await s.writeFile(T(),JSON.stringify(t),{mode:384})}catch{}}const O=u.object({latest:u.string(),minSupported:u.string().optional(),platforms:u.record(u.string(),u.unknown()).optional(),downloads:u.record(u.string(),u.unknown()).optional()});async function k(e){if(A(e.argv))return;let t=null,n=await E();if(n&&Date.now()-n.checkedAt<S)t={latest:n.latest,platforms:n.platforms??{}};else{try{t=await j()}catch(e){z(`update check failed: ${e.message}`);return}t&&await D({checkedAt:Date.now(),latest:t.latest,platforms:t.platforms})}if(!t||!l.valid(e.currentVersion)||!l.valid(t.latest)||l.eq(e.currentVersion,t.latest)||l.lt(t.latest,e.currentVersion))return;let r=l.diff(e.currentVersion,t.latest);if(!r)return;let i=M();if(r===`patch`||r===`prepatch`){let n=await P(t,e,i);if(n&&i===`npm-global`)return;n&&await R(e.argv);return}if(r===`minor`||r===`preminor`||r===`major`||r===`premajor`||r===`prerelease`){let n=await L(t.latest);if(!n){process.stderr.write(`Continuing with ${e.currentVersion}.\n`);return}let r=await P(t,e,i);if(r&&i===`npm-global`)return;r&&await R(e.argv);return}}function A(e){if(process.env.ZENOVAY_NO_UPDATE_CHECK===`1`||process.env.CI===`true`||e.includes(`--no-update-check`))return!0;let t=e[2];return!!(t&&C.has(t))}async function j(){let e=M();if(e===`npm-global`||e===`npm-local`||e===`unknown`)try{let e=await fetch(`https://registry.npmjs.org/@zenovay/cli/latest`,{signal:AbortSignal.timeout(v),headers:{Accept:`application/json`}});if(!e.ok)return null;let t=await e.json();return t.version?{latest:t.version,platforms:{}}:null}catch{return null}let n=await t(),i=`https://zenovay-cli-distribution.zenovay.workers.dev`,a=n.cliBase===i?[n.cliBase]:[n.cliBase,i];for(let e of a)try{let t=await fetch(`${e}/version`,{signal:AbortSignal.timeout(v)});if(!t.ok)continue;let n=await t.json(),i=r.safeParse(n);if(i.success)return i.data;let a=O.safeParse(n);if(a.success)return{latest:a.data.latest,minSupported:a.data.minSupported,platforms:{}}}catch{}return null}function M(){let e=process.argv[1]??``;if(!e)return`unknown`;let t=e;try{t=c(e)}catch{}let n=t.replace(/\\/g,`/`);return n.includes(`/_npx/`)?`npm-local`:n.includes(`/node_modules/@zenovay/cli/`)?`npm-global`:n.includes(`/node_modules/.bin/zenovay`)?`npm-local`:n.includes(`/node_modules/`)?`unknown`:`binary`}function N(e){let t=e.execPath.replace(/\\/g,`/`),n=/(?:^|\/)(?:node|nodejs|bun|deno)(?:\.exe)?$/i.test(t);if(!n)return{cmd:e.execPath,args:e.sub};let r=e.argv1;if(e.resolveSymlink)try{r=e.resolveSymlink(e.argv1)}catch{}return{cmd:e.execPath,args:[r,...e.sub]}}async function P(e,n,r){if(r===`npm-local`)return process.stderr.write(`Update available — \`npm i -g @zenovay/cli@${e.latest}\` to upgrade.\n`),!1;if(r===`unknown`)return z(`unknown install method; skipping auto-update (latest ${e.latest})`),!1;if(r===`npm-global`){if(process.env.ZENOVAY_NO_AUTO_UPDATE===`1`||process.env.ZENOVAY_AUTO_UPDATE===`0`)return process.stderr.write(`Update available (${e.latest}). Auto-update disabled — run \`npm i -g @zenovay/cli@${e.latest}\` to upgrade.\n`),!1;if(process.stdin.isTTY&&process.stderr.isTTY){let t=await F(e.latest);if(!t)return process.stderr.write(`Skipped. Run \`npm i -g @zenovay/cli@${e.latest}\` to upgrade later.\n`),!1}return await I(e.latest)}let i=`${process.platform}-${process.arch}`,a=e.platforms??{};if(!a[i])return process.stderr.write(`\nUpdate ${e.latest} is published to npm (no native binary for ${i} in this release).\nUpgrade with one of:\n npm i -g @zenovay/cli@${e.latest}\n curl -fsSL https://cli.zenovay.com/install.sh | sh\n\n`),!1;let o=await E();if(o?.binaryDeferredFor===e.latest)return!1;let s=new AbortController,c=setTimeout(()=>s.abort(),b);try{let r=await t(),i=await p({currentVersion:n.currentVersion,cliBase:r.cliBase,binaryPath:n.binaryPath,manifest:e,signal:s.signal});return i.updated?!0:(z(`update skipped: ${i.reason??`unknown`}`),!1)}catch(t){return s.signal.aborted?(process.stderr.write(`Update ${e.latest} is ready but needs longer than the quick auto-update window — run \`zenovay update\` to install it now.\n`),await D({checkedAt:o?.checkedAt??Date.now(),latest:e.latest,platforms:o?.platforms??e.platforms,binaryDeferredFor:e.latest}).catch(()=>void 0),!1):(z(`update failed: ${t.message}`),!1)}finally{clearTimeout(c)}}function F(e){return new Promise(t=>{process.stderr.write(`Update @zenovay/cli to ${e} via \`npm i -g\`? [Y/n] (auto-yes 5s) `);let n=!1,r=e=>{if(n)return;let r=e.toString(`utf8`).trim().toLowerCase();n=!0,i(),process.stderr.write(`
|
|
2
|
-
`),t(r!==`n`&&r!==`no`)},i=()=>{clearTimeout(a),process.stdin.off(`data`,r);try{process.stdin.pause()}catch{}},a=setTimeout(()=>{n||(n=!0,i(),process.stderr.write(`
|
|
3
|
-
`),t(!0))},x);try{process.stdin.resume(),process.stdin.on(`data`,r)}catch{i(),t(!0)}})}function I(e){return new Promise(t=>{process.stderr.write(` Updating @zenovay/cli to ${e}...\n`);let n=process.platform===`win32`,r=n?`npm.cmd`:`npm`,i=[`install`,`-g`,`@zenovay/cli@${e}`],o={stdio:[`ignore`,`ignore`,`pipe`],shell:n},s=``,c=!1,l;try{l=a(r,i,o)}catch(n){process.stderr.write(`\n Couldn't launch npm automatically: ${n.message}\n Update manually: npm i -g @zenovay/cli@${e}\n`),t(!1);return}let u=setTimeout(()=>{if(!c){c=!0;try{l.kill(`SIGKILL`)}catch{}z(`npm install timed out after ${y/1e3}s; continuing with current version`),t(!1)}},y);l.stderr?.on(`data`,e=>{s+=e.toString(`utf8`)}),l.on(`error`,e=>{c||(c=!0,clearTimeout(u),z(`npm install error: ${e.message}`),t(!1))}),l.on(`exit`,n=>{if(!c){if(c=!0,clearTimeout(u),n===0){process.stdin.isTTY&&process.stderr.isTTY&&(process.stderr.write(` ✔ Updated to ${e}. Re-run your command to use the new version.\n`),process.exit(0)),process.stderr.write(` ✔ Updated to ${e} — the new version applies on your next run.\n`),t(!1);return}/EACCES|permission denied/i.test(s)?process.stderr.write(`Auto-update needs sudo for the global npm prefix. Run: sudo npm i -g @zenovay/cli@${e}\n`):z(`npm install exited ${n}; continuing with current version`),t(!1)}})})}function L(e){return new Promise(t=>{if(!process.stdin.isTTY||!process.stderr.isTTY){t(!0);return}process.stderr.write(`New version ${e} available. Update? [Y/n] (auto-yes 5s) `);let n=!1,r=e=>{if(n)return;let r=e.toString(`utf8`).trim().toLowerCase();n=!0,i(),process.stderr.write(`
|
|
4
|
-
`),t(r===``||r===`y`||r===`yes`)},i=()=>{clearTimeout(a),process.stdin.off(`data`,r);try{process.stdin.pause()}catch{}},a=setTimeout(()=>{n||(n=!0,i(),process.stderr.write(`
|
|
5
|
-
`),t(!0))},x);try{process.stdin.resume(),process.stdin.on(`data`,r)}catch{i(),t(!0)}})}function R(e){return new Promise(t=>{try{let{cmd:n,args:r}=N({execPath:process.execPath,argv1:e[1]??``,sub:e.slice(2),resolveSymlink:e=>c(e)}),i=a(n,r,{stdio:`inherit`});i.on(`exit`,e=>{process.exit(typeof e==`number`?e:0)}),i.on(`error`,()=>{t(!1)})}catch{t(!1)}})}function z(e){if(process.env.ZENOVAY_DEBUG_UPDATE===`1`)try{process.stderr.write(`zenovay: ${e}\n`)}catch{}}export{p as applyManifest,N as buildPostInstallReexec,M as detectInstallMethod,k as ensureLatest,R as reExec,I as runNpmGlobalInstall};
|