@zenovay/cli 1.0.2 → 1.0.3
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.
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{readConfig as e}from"./config-JVhBplSX.js";import"./api-CdcB84ie.js";import{readToken as t}from"./token-store-BvSCse1t.js";import{emit as n}from"./telemetry-BV-xvfdt.js";import{ApiV2Client as r}from"./api-v2-D0mvt__4.js";import{detectInstalled as i,initCommand as a}from"./init-
|
|
1
|
+
import{readConfig as e}from"./config-JVhBplSX.js";import"./api-CdcB84ie.js";import{readToken as t}from"./token-store-BvSCse1t.js";import{emit as n}from"./telemetry-BV-xvfdt.js";import{ApiV2Client as r}from"./api-v2-D0mvt__4.js";import{detectInstalled as i,initCommand as a}from"./init-4u9IQ8h_.js";import"./formatter-C4YSOKuq.js";import{emit$1 as o,isHeadless as s}from"./emit-D4YlMlzk.js";import"./open-url-BtI5aLgL.js";import"./secrets-ApB7yh2A.js";import{parseSseStream as c}from"./client-ntsEXSVC.js";import"./login-DU1fY88U.js";import"./theme-Brz9wK0w.js";import{Banner as l,Panel as u,useTheme as d}from"./panel-CTtQ2ue6.js";import"./progress-row-Afnt5Ng8.js";import{Select as f}from"./prompt-BXvg2B4R.js";import"./keybar-DO5OoZy9.js";import"./sparkline-CpoBjjlc.js";import{ChatPanel as p}from"./chat-panel-D9IjovCR.js";import{resolveSiteId as m}from"./resolve-site-BTVBMF1C.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((s(e)||!process.stdin.isTTY)&&e.mode!==`install`)return o({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(s(e))return o({type:`error`,code:`no_mode`,message:`Headless mode requires --mode chat|mcp|install`}),2;else n=await N(t,e.cliVersion);return n===`install`?a({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,12 +1,14 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{configDir as e,readConfig as t}from"./config-JVhBplSX.js";import{manifestSchema as n}from"./check-D9G0N7NB.js";import{applyManifest as r}from"./apply-oUMOH7u2.js";import"./api-CdcB84ie.js";import"./token-store-BvSCse1t.js";import{normalizeError as i}from"./error-codes-ByhvHx2M.js";import{emit as a,flush as o,initTelemetry as s}from"./telemetry-BV-xvfdt.js";import{cac as c}from"cac";import{fork as l,spawn as u}from"node:child_process";import d from"node:path";import{fileURLToPath as ee}from"node:url";import{promises as f,readFileSync as p}from"node:fs";import
|
|
2
|
+
import{configDir as e,readConfig as t}from"./config-JVhBplSX.js";import{manifestSchema as n}from"./check-D9G0N7NB.js";import{applyManifest as r}from"./apply-oUMOH7u2.js";import"./api-CdcB84ie.js";import"./token-store-BvSCse1t.js";import{normalizeError as i}from"./error-codes-ByhvHx2M.js";import{emit as a,flush as o,initTelemetry as s}from"./telemetry-BV-xvfdt.js";import{cac as c}from"cac";import{fork as l,spawn as u}from"node:child_process";import d from"node:path";import{fileURLToPath as ee}from"node:url";import{promises as f,readFileSync as p}from"node:fs";import m from"semver";import{z as h}from"zod";const g=2e3,_=3e4,v=5e3,y=5e3,b=36e5,x=new Set([`update`,`health`,`doctor`,`--version`,`-v`]),S=h.object({checkedAt:h.number(),latest:h.string()});function C(){return d.join(e(),`update-cache.json`)}async function te(){try{let e=await f.readFile(C(),`utf8`),t=S.safeParse(JSON.parse(e));return t.success?t.data:null}catch{return null}}async function ne(t){try{await f.mkdir(e(),{recursive:!0,mode:448}),await f.writeFile(C(),JSON.stringify(t),{mode:384})}catch{}}const re=h.object({latest:h.string(),minSupported:h.string().optional(),platforms:h.record(h.string(),h.unknown()).optional(),downloads:h.record(h.string(),h.unknown()).optional()});async function w(e){if(T(e.argv))return;let t=null,n=await te();if(n&&Date.now()-n.checkedAt<b)t={latest:n.latest,platforms:{}};else{try{t=await E()}catch(e){N(`update check failed: ${e.message}`);return}t&&await ne({checkedAt:Date.now(),latest:t.latest})}if(!t||!m.valid(e.currentVersion)||!m.valid(t.latest)||m.eq(e.currentVersion,t.latest)||m.lt(t.latest,e.currentVersion))return;let r=m.diff(e.currentVersion,t.latest);if(!r)return;let i=D();if(r===`patch`||r===`prepatch`){let n=await O(t,e,i);if(n&&i===`npm-global`)return;n&&M(e.argv);return}if(r===`minor`||r===`preminor`||r===`major`||r===`premajor`||r===`prerelease`){let n=await j(t.latest);if(!n){process.stderr.write(`Continuing with ${e.currentVersion}.\n`);return}let r=await O(t,e,i);if(r&&i===`npm-global`)return;r&&M(e.argv);return}}function T(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&&x.has(t))}async function E(){let e=D();if(e===`npm-global`||e===`npm-local`||e===`unknown`)try{let e=await fetch(`https://registry.npmjs.org/@zenovay/cli/latest`,{signal:AbortSignal.timeout(g),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 r=await t(),i=`https://zenovay-cli-distribution.zenovay.workers.dev`,a=r.cliBase===i?[r.cliBase]:[r.cliBase,i];for(let e of a)try{let t=await fetch(`${e}/version`,{signal:AbortSignal.timeout(g)});if(!t.ok)continue;let r=await t.json(),i=n.safeParse(r);if(i.success)return i.data;let a=re.safeParse(r);if(a.success)return{latest:a.data.latest,minSupported:a.data.minSupported,platforms:{}}}catch{}return null}function D(){let e=process.argv[1]??``;if(!e)return`unknown`;let t=e.replace(/\\/g,`/`);return t.includes(`/_npx/`)?`npm-local`:t.includes(`/node_modules/@zenovay/cli/`)?`npm-global`:t.includes(`/node_modules/.bin/zenovay`)?`npm-local`:t.includes(`/node_modules/`)?`unknown`:`binary`}async function O(e,n,i){if(i===`npm-local`)return process.stderr.write(`Update available — \`npm i -g @zenovay/cli@${e.latest}\` to upgrade.\n`),!1;if(i===`unknown`)return N(`unknown install method; skipping auto-update (latest ${e.latest})`),!1;if(i===`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 k(e.latest);if(!t)return process.stderr.write(`Skipped. Run \`npm i -g @zenovay/cli@${e.latest}\` to upgrade later.\n`),!1}return await A(e.latest)}let a=`${process.platform}-${process.arch}`,o=e.platforms??{};if(!o[a])return process.stderr.write(`\nUpdate ${e.latest} is published to npm (no native binary for ${a} 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;try{let i=await t(),a=await Promise.race([r({currentVersion:n.currentVersion,cliBase:i.cliBase,binaryPath:n.binaryPath,manifest:e}),new Promise((e,t)=>setTimeout(()=>t(Error(`patch install timeout`)),v))]);return a.updated?!0:(N(`update skipped: ${a.reason??`unknown`}`),!1)}catch(e){return N(`update failed: ${e.message}`),!1}}function k(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(`
|
|
3
|
+
`),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(`
|
|
4
|
+
`),t(!0))},y);try{process.stdin.resume(),process.stdin.on(`data`,r)}catch{i(),t(!0)}})}function A(e){return new Promise(t=>{process.stderr.write(` Updating @zenovay/cli to ${e}...\n`);let n=process.platform===`win32`?`npm.cmd`:`npm`,r=[`install`,`-g`,`@zenovay/cli@${e}`],i={stdio:[`ignore`,`ignore`,`pipe`]},a=``,o=!1,s=u(n,r,i),c=setTimeout(()=>{if(!o){o=!0;try{s.kill(`SIGKILL`)}catch{}N(`npm install timed out after ${_/1e3}s; continuing with current version`),t(!1)}},_);s.stderr?.on(`data`,e=>{a+=e.toString(`utf8`)}),s.on(`error`,e=>{o||(o=!0,clearTimeout(c),N(`npm install error: ${e.message}`),t(!1))}),s.on(`exit`,n=>{o||(o=!0,clearTimeout(c),n===0&&(process.stderr.write(` ✔ Updated to ${e}. Re-run your command to use the new version.\n`),process.exit(0)),/EACCES|permission denied/i.test(a)?process.stderr.write(`Auto-update needs sudo for the global npm prefix. Run: sudo npm i -g @zenovay/cli@${e}\n`):N(`npm install exited ${n}; continuing with current version`),t(!1))})})}function j(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(`
|
|
3
5
|
`),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(`
|
|
4
|
-
`),t(!0))},
|
|
6
|
+
`),t(!0))},y);try{process.stdin.resume(),process.stdin.on(`data`,r)}catch{i(),t(!0)}})}function M(e){try{let t=e.slice(1),n=u(process.execPath,t,{stdio:`inherit`});n.on(`exit`,e=>{process.exit(typeof e==`number`?e:0)}),n.on(`error`,()=>{})}catch{}}function N(e){if(process.env.ZENOVAY_DEBUG_UPDATE===`1`)try{process.stderr.write(`zenovay: ${e}\n`)}catch{}}var P=`@zenovay/cli`,F=`1.0.3`,I=`Zenovay CLI — AI install wizard + full terminal analytics dashboard`,L=`module`,R={zenovay:`dist/bin.js`,zv:`dist/bin.js`},z=[`dist/**/*.js`,`dist/**/*.cjs`,`dist/**/*.mjs`,`dist/**/*.d.ts`,`README.md`,`LICENSE`],ie={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`},B={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`,zod:`^3.23.8`},V={"@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`},H={node:`>=20.0.0`},U=`pnpm@9.15.9`,W={overrides:{"ws@>=8.0.0 <8.21.0":`>=8.21.0`}},G=`Zenovay <cli@zenovay.com>`,K=`SEE LICENSE IN LICENSE`,q=`https://cli.zenovay.com`,J={type:`git`,url:`https://github.com/zenovay/cli-zenovay.git`},Y={url:`https://cli.zenovay.com/feedback`},ae=[`zenovay`,`analytics`,`cli`,`tui`,`ai-agent`,`install-wizard`],oe={name:P,version:F,description:I,type:L,bin:R,files:z,scripts:ie,dependencies:B,devDependencies:V,engines:H,packageManager:U,pnpm:W,author:G,license:K,homepage:q,repository:J,bugs:Y,keywords:ae};const se=d.dirname(ee(import.meta.url)),X=oe.version,Z=process.argv[0]??`zenovay`;function ce(){if(process.env.ZENOVAY_BACKGROUND_UPDATE===`1`&&!(process.env.ZENOVAY_NO_UPDATE_CHECK===`1`||process.env.CI===`true`))try{let e=d.join(se,`lib`,`update`,`worker.js`),t=l(e,[],{detached:!0,stdio:`ignore`,env:{...process.env,ZENOVAY_UPDATE_WORKER_FORK:`1`}});t.unref()}catch{}}const Q=c(`zenovay`);Q.version(X),Q.help(e=>{let t=e.filter(e=>{let t=e.title??``;return!/for more info/i.test(t)});return t.push({body:"Run `zenovay <command> --help` for command-specific options and examples."}),t}),Q.option(`-q, --quiet`,`Suppress spinners + interactive UI; implies --json`),Q.option(`--team <name-or-id>`,"Team override for this command (alternative to `zenovay teams switch`)"),(process.argv.includes(`-q`)||process.argv.includes(`--quiet`))&&(process.env.ZENOVAY_FORMAT=`json`,process.argv.includes(`--json`)||process.argv.push(`--json`));const $=process.argv.findIndex(e=>e===`--team`);if($!==-1&&process.argv[$+1]&&(process.env.ZENOVAY_TEAM_ID=process.argv[$+1]),!process.env.ZENOVAY_TEAM_ID)try{let e=process.env.HOME??process.env.USERPROFILE??``,t=d.join(e,`.config`,`zenovay`,`config.json`),n=p(t,`utf8`),r=JSON.parse(n);r.currentTeamId&&(process.env.ZENOVAY_TEAM_ID=r.currentTeamId)}catch{}Q.command(`init`,`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(`--site-id <id>`,`Install for a specific site id (skips the picker)`).action(async e=>{let{initCommand:t}=await import(`./init-kKTNK6nn.js`),n=await t({cliVersion:X,cwd:process.cwd(),json:e.json,yes:e.yes,review:e.review,skipMcp:e.skipMcp,skipVerify:e.skipVerify,siteId:e.siteId});process.exitCode=n}),Q.command(`login`,`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-CDAP0iKS.js`),n=await t({cliVersion:X,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(`
|
|
5
7
|
✔ Logged in.
|
|
6
8
|
|
|
7
|
-
`)}),Q.command(`logout`,`Revoke current session and delete local auth`).option(`--json`,``).action(async e=>{let{logoutCommand:t}=await import(`./logout-BoUfEnN9.js`);await t({cliVersion:X,json:e.json})}),Q.command(`ai`,`3-mode AI assistant (install / chat / mcp)`).option(`--mode <mode>`,`install | chat | mcp`).option(`--json`,``).action(async e=>{let{aiCommand:t}=await import(`./ai-
|
|
9
|
+
`)}),Q.command(`logout`,`Revoke current session and delete local auth`).option(`--json`,``).action(async e=>{let{logoutCommand:t}=await import(`./logout-BoUfEnN9.js`);await t({cliVersion:X,json:e.json})}),Q.command(`ai`,`3-mode AI assistant (install / chat / mcp)`).option(`--mode <mode>`,`install | chat | mcp`).option(`--json`,``).action(async e=>{let{aiCommand:t}=await import(`./ai-B1ZHq3uM.js`),n=await t({cliVersion:X,cwd:process.cwd(),mode:e.mode,json:e.json});process.exitCode=n}),Q.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-S6AFt20R.js`),n=await t({cliVersion:X,siteId:e.siteId,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),Q.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-S6AFt20R.js`);process.exitCode=await e({cliVersion:X,siteId:t.siteId,json:t.json,csv:t.csv,tsv:t.tsv,ndjson:t.ndjson});return}case`live`:{let{liveCommand:e}=await import(`./live-BNX4HBCf.js`);process.exitCode=await e({cliVersion:X,siteId:t.siteId,json:t.json});return}case`funnels`:{let{funnelCommand:e}=await import(`./funnel-Cb4-3RJB.js`);process.exitCode=await e({cliVersion:X,siteId:t.siteId,json:t.json,csv:t.csv,tsv:t.tsv,ndjson:t.ndjson});return}case`goals`:{let{goalsCommand:e}=await import(`./goals-Ds0QZ4H6.js`);process.exitCode=await e({cliVersion:X,action:`list`,json:t.json});return}case`insights`:{let{insightsCommand:e}=await import(`./insights-BiqMftak.js`);process.exitCode=await e({cliVersion:X,siteId:t.siteId,json:t.json});return}case`profiles`:{let{visitorsCommand:e}=await import(`./visitors-mjvSIKkI.js`);process.exitCode=await e({cliVersion:X,siteId:t.siteId,json:t.json});return}case`companies`:{let{companiesCommand:e}=await import(`./companies-Cpb3yv2Q.js`);process.exitCode=await e({cliVersion:X,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`})+`
|
|
8
10
|
`:`\n✗ Unknown analytics sub-command: '${e}'\n Valid: live | funnels | goals | insights | profiles | companies. Run \`zenovay analytics --help\`\n`),process.exit(2)}}),Q.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-S6AFt20R.js`),n=await t({cliVersion:X,siteId:e.siteId,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),Q.command(`home`,`[ACCOUNT] Top-level summary — sites + this-week deltas`).option(`--json`,``).action(async e=>{let{homeCommand:t}=await import(`./home-DGYBSPWi.js`);process.exitCode=await t({cliVersion:X,json:e.json})}),Q.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-BNX4HBCf.js`),n=await t({cliVersion:X,siteId:e.siteId,json:e.json});process.exitCode=n}),Q.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-BYVz90uO.js`),n=await t({cliVersion:X,siteId:e.siteId,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),Q.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-C_NjBY89.js`),n=await t({cliVersion:X,siteId:e.siteId,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),Q.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-ReUNKl3F.js`),n=await t({cliVersion:X,siteId:e.siteId,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),Q.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-DQHXVSG0.js`),n=await t({cliVersion:X,siteId:e.siteId,json:e.json});process.exitCode=n}),Q.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-BA8vRzJQ.js`),n=await t({cliVersion:X,siteId:e.siteId,json:e.json});process.exitCode=n}),Q.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-dPZ32wpz.js`),n=await t({cliVersion:X,siteId:e.siteId,json:e.json});process.exitCode=n}),Q.command(`heatmaps`,`[BEHAVIOR] Recent heatmap captures (Pro+)`).option(`--site-id <id>`,`Site ID`).option(`--json`,``).action(async e=>{let{heatmapsCommand:t}=await import(`./heatmaps-B-As729q.js`),n=await t({cliVersion:X,siteId:e.siteId,json:e.json});process.exitCode=n}),Q.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-CogDUObU.js`),n=await t({cliVersion:X,siteId:e.siteId,json:e.json});process.exitCode=n}),Q.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-BiqMftak.js`),n=await t({cliVersion:X,siteId:e.siteId,json:e.json});process.exitCode=n}),Q.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`})+`
|
|
9
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-DEdVkmT0.js`),r=await n({cliVersion:X,siteId:t.siteId,json:t.json,filter:t.filter,forwardTo:t.forwardTo,replay24h:t.replay24h,setForwardSecret:t.setForwardSecret});process.exitCode=r}),Q.command(`health`,`Run self-diagnostic checks`).option(`--json`,``).action(async e=>{let{healthCommand:t}=await import(`./health-DTR77eQW.js`),n=await t({cliVersion:X,binaryPath:Z,json:e.json});process.exitCode=n}),Q.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-CZ2bEuyD.js`),i=await r({cliVersion:X,type:t.type,message:t.message,occurredAt:t.occurredAt,siteId:t.siteId,json:t.json});process.exitCode=i}),Q.command(`doctor`,`AI-assisted self-healing`).option(`--json`,``).action(async e=>{let{doctorCommand:t}=await import(`./doctor-BsEuqZTb.js`),n=await t({cliVersion:X,binaryPath:Z,json:e.json});process.exitCode=n}),Q.command(`stats`,`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-EeSDu70A.js`),n=await t({cliVersion:X,siteId:e.siteId,range:e.range,watch:e.watch,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),Q.command(`sources`,`Traffic source breakdown with delta arrows`).option(`--site-id <id>`,`Site ID`).option(`--period <p>`,`Period: 7d | 30d | 90d | 1y`,{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-lvpcvTTz.js`),n=await t({cliVersion:X,siteId:e.siteId,period:e.period,compare:e.compare,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),Q.command(`vitals`,`Core Web Vitals dashboard (LCP / INP / CLS / TTFB / FCP)`).option(`--site-id <id>`,`Site ID`).option(`--url <path>`,`Filter to a single URL`).option(`--device <type>`,`Filter by device: mobile | desktop`).option(`--window <w>`,`Time window: 24h | 7d | 30d | 90d`,{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-D3sMQksQ.js`),n=await t({cliVersion:X,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}),Q.command(`revenue`,`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-CitFZ4DN.js`),n=await t({cliVersion:X,siteId:e.siteId,range:e.range,watch:e.watch,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),Q.command(`funnels`,`List available funnels`).option(`--site-id <id>`,`Site ID`).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async e=>{let{funnelCommand:t}=await import(`./funnel-Cb4-3RJB.js`),n=await t({cliVersion:X,siteId:e.siteId,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),Q.command(`themes`,`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-BC8U4Od4.js`),n=await t({cliVersion:X,validate:e.validate,json:e.json});process.exitCode=n}),Q.command(`completions [shell] [valuesType]`,`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-XLznfo7H.js`),i=await r({shell:e,valuesType:t,list:n.list});process.exitCode=i}),Q.command(`query [sql]`,`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-DLC0vi-K.js`),r=await n({cliVersion:X,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}),Q.command(`companies`,`B2B identification feed (Scale+)`).option(`--site-id <id>`,`Site ID`).option(`--window <w>`,`Time window: 24h | 7d | 30d | 90d`,{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-Cpb3yv2Q.js`),n=await t({cliVersion:X,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}),Q.command(`projects`,`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-BdRZaLg8.js`),n=await t({cliVersion:X,siteId:e.siteId,json:e.json,csv:e.csv,tsv:e.tsv,ndjson:e.ndjson});process.exitCode=n}),Q.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-DZ0IR9Re.js`),n=await t({cliVersion:X,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}),Q.command(`errors`,`[BEHAVIOR] Recent JS / HTTP error snapshot`).alias(`error`).option(`--site-id <id>`,`Site ID`).option(`--window <w>`,`Time window: 24h | 7d | 30d | 90d`,{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-DPRcy7WT.js`),n=await t({cliVersion:X,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}),Q.command(`funnel <id>`,`Funnel drop-off chart for a specific funnel`).option(`--site-id <id>`,`Site ID`).option(`--window <w>`,`Time window: 7d | 30d`,{default:`30d`}).option(`--json`,``).option(`--csv`,``).option(`--tsv`,``).option(`--ndjson`,``).action(async(e,t)=>{let{funnelCommand:n}=await import(`./funnel-Cb4-3RJB.js`),r=await n({cliVersion:X,siteId:t.siteId,funnelId:e,window:t.window,json:t.json,csv:t.csv,tsv:t.tsv,ndjson:t.ndjson});process.exitCode=r}),Q.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-CLol-4YC.js`),i=e??`list`;process.exitCode=await r({cliVersion:X,action:i,id:t,name:n.name,scope:n.scope===`write`?`write`:`read`,yes:n.yes,json:n.json})}),Q.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-ByXV1O4R.js`),i=e??`list`;process.exitCode=await r({cliVersion:X,action:i,url:i===`add`?t:void 0,id:i===`delete`?t:void 0,name:n.name,yes:n.yes,json:n.json})}),Q.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-Bw6dcpI2.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:X,action:a,email:a===`invite`?t:void 0,userId:a===`remove`||a===`role`?t:void 0,role:o,yes:r.yes,json:r.json})}),Q.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-CDY3kFEq.js`);process.exitCode=await i({cliVersion:X,action:n,name:t.name,notifications:r,json:t.json})}),Q.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-DT8hilXl.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:X,action:i,targetPlan:o,paymentAction:s,yes:r.yes,json:r.json})}),Q.command(`billing [action]`,"[ACCOUNT] Alias for `plans info`").option(`--json`,``).action(async(e,t)=>{let{plansCommand:n}=await import(`./plans-DT8hilXl.js`);process.exitCode=await n({cliVersion:X,action:`info`,json:t.json})}),Q.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-DO8UOasX.js`);process.exitCode=await a({cliVersion:X,action:i,key:t||void 0,value:n||void 0,json:r.json})}),Q.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-CCvt4xb_.js`);process.exitCode=await a({cliVersion:X,action:r,name:i,yes:n.yes,json:n.json})}),Q.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-Ds0QZ4H6.js`);process.exitCode=await a({cliVersion:X,action:r,id:t,name:n.name,type:i,target:n.target,yes:n.yes,json:n.json})}),Q.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-BrY4efpr.js`);process.exitCode=await i({cliVersion:X,action:r,id:t,content:n.content,siteId:n.siteId,yes:n.yes,json:n.json})}),Q.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-cNkRWBOo.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:X,action:a,id:o,email:r.email,name:r.name,yes:r.yes,json:r.json})}),Q.command(`use [site]`,`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-BW8rVPgW.js`),r=await n({cliVersion:X,match:e,reset:t.reset,show:t.show,json:t.json});process.exitCode=r}),Q.command(`update`,`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-DkMxLJbM.js`);await t({cliVersion:X,binaryPath:Z,check:e.check,forceDowngrade:e.forceDowngrade,json:e.json})}),Q.command(`usage`,`[ACCOUNT] Current month events vs plan limits + headcounts`).option(`--json`,``).action(async e=>{let{usageCommand:t}=await import(`./usage-CkyXScnm.js`);process.exitCode=await t({cliVersion:X,json:e.json})}),Q.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-DwaTDQns.js`);process.exitCode=await t({cliVersion:X,siteId:e.siteId,browser:e.browser,json:e.json})}),Q.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-B8nnKB4f.js`);process.exitCode=await e({cliVersion:X,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-D1PNfhgJ.js`);process.exitCode=await i({cliVersion:X,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})}),Q.command(`audit [action]`,`[ACCOUNT] audit list [--since --action --actor] | export [--format --out] (Pro+)`).option(`--since <window>`,`Window like 24h, 7d, 30d (list)`,{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-CFlSb0g5.js`);process.exitCode=await i({cliVersion:X,action:n,since:t.since,filterAction:t.action,actor:t.actor,format:r,out:t.out,json:t.json})}),Q.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-BkvKZuPo.js`);process.exitCode=await r({cliVersion:X,action:n,siteId:t.siteId,yes:t.yes,json:t.json})}),Q.command(`commands`,`Emit the machine-readable command tree (for AI agents and shell-completion regen)`).option(`--json`,``).action(async e=>{let{commandsCommand:t}=await import(`./commands-DVRYYbbn.js`);process.exitCode=await t({cliVersion:X,json:e.json})}),Q.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-cwzXaqBH.js`);process.exitCode=await i({cliVersion:X,action:r,match:r===`switch`?t:void 0,json:n.json})}),Q.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-BcCqMRQ9.js`);process.exitCode=await t({cliVersion:X,full:!!e.full,quick:!!e.quick,verbose:!!e.verbose,parallel:Number(e.parallel)||4,json:!!e.json})}),Q.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-ChHRo89U.js`);process.exitCode=await t({cliVersion:X,nonInteractive:!!(e[`non-interactive`]||e.nonInteractive)})}),Q.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`})+`
|
|
10
12
|
`:`\n✗ Unknown action: '${e}'\n Valid: list | create | delete. Run \`zenovay alerts --help\`\n`),process.exit(2));let{alertsCommand:a}=await import(`./alerts-BQ0EMdBT.js`);process.exitCode=await a({cliVersion:X,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})}),Q.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`})+`
|
|
11
|
-
`:`\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-DhSRfpg_.js`);process.exitCode=await i({type:e,cliVersion:X,siteId:t[`site-id`]||t.siteId,range:t.range,format:r,out:t.out,json:!!t.json})}),Q.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-mjvSIKkI.js`);process.exitCode=await t({cliVersion:X,siteId:e.siteId,minDuration:Number(e[`min-duration`]||e.minDuration)||0,json:!!e.json,csv:!!e.csv,tsv:!!e.tsv,ndjson:!!e.ndjson})}),Q.command(`status`,"[OPERATIONS] Alias of `health` — self-diagnostic checks").option(`--json`,``).action(async e=>{let{healthCommand:t}=await import(`./health-DTR77eQW.js`);process.exitCode=await t({cliVersion:X,binaryPath:Z,json:!!e.json})}),Q.command(`telemetry [action]`,`[OPERATIONS] Manage anonymous CLI telemetry (on / off / status)`).option(`--json`,``).action(async(e,t)=>{let{telemetryCommand:n}=await import(`./telemetry-CgyMy4hV.js`);process.exitCode=await n({cliVersion:X,action:e,json:!!t.json})}),Q.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-BLIJc81G.js`);process.exitCode=await t({cliVersion:X,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})}),Q.parse(process.argv,{run:!1}),(async()=>{await
|
|
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-DhSRfpg_.js`);process.exitCode=await i({type:e,cliVersion:X,siteId:t[`site-id`]||t.siteId,range:t.range,format:r,out:t.out,json:!!t.json})}),Q.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-mjvSIKkI.js`);process.exitCode=await t({cliVersion:X,siteId:e.siteId,minDuration:Number(e[`min-duration`]||e.minDuration)||0,json:!!e.json,csv:!!e.csv,tsv:!!e.tsv,ndjson:!!e.ndjson})}),Q.command(`status`,"[OPERATIONS] Alias of `health` — self-diagnostic checks").option(`--json`,``).action(async e=>{let{healthCommand:t}=await import(`./health-DTR77eQW.js`);process.exitCode=await t({cliVersion:X,binaryPath:Z,json:!!e.json})}),Q.command(`telemetry [action]`,`[OPERATIONS] Manage anonymous CLI telemetry (on / off / status)`).option(`--json`,``).action(async(e,t)=>{let{telemetryCommand:n}=await import(`./telemetry-CgyMy4hV.js`);process.exitCode=await n({cliVersion:X,action:e,json:!!t.json})}),Q.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-BLIJc81G.js`);process.exitCode=await t({cliVersion:X,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})}),Q.parse(process.argv,{run:!1}),(async()=>{await w({binaryPath:Z,currentVersion:X,argv:process.argv}),ce();let e,t;try{let t=process.env.HOME??process.env.USERPROFILE??``,n=d.join(t,`.config`,`zenovay`,`config.json`),r=p(n,`utf8`);e=JSON.parse(r).apiBase}catch{}try{let e=process.env.HOME??process.env.USERPROFILE??``,n=d.join(e,`.config`,`zenovay`,`auth.json`),r=p(n,`utf8`);t=JSON.parse(r).accessToken}catch{}await s({cliVersion:X,apiBase:e,token:t}).catch(()=>void 0);let n=Date.now(),r=(()=>{let e=Q.matchedCommand;return e?.name})();a(`cli.startup`,{command:r});try{let e=Q.matchedCommand,t=process.argv.slice(2).filter(e=>!e.startsWith(`-`)),i=process.argv.includes(`--help`)||process.argv.includes(`-h`);if(!e&&t.length>0&&!i&&(process.stderr.write(`Unknown command: \`${t.join(` `)}\`\nRun \`zenovay --help\` to see all commands.\n`),a(`cli.exit`,{command:r,exit_code:2,duration_ms:Date.now()-n,error_code:`unknown_command`}),await o().catch(()=>void 0),process.exit(2)),!e&&t.length===0&&!i){Q.outputHelp(),a(`cli.exit`,{command:`help`,exit_code:0,duration_ms:Date.now()-n}),await o().catch(()=>void 0);return}await Q.runMatchedCommand(),a(`cli.exit`,{command:r,exit_code:typeof process.exitCode==`number`?process.exitCode:0,duration_ms:Date.now()-n}),await o().catch(()=>void 0)}catch(e){let t=i(e),s=process.env.ZENOVAY_FORMAT===`json`||process.argv.includes(`--json`)||process.argv.includes(`-q`)||process.argv.includes(`--quiet`);s?process.stderr.write(JSON.stringify(t)+`
|
|
12
14
|
`):(process.stderr.write(`\n✗ ${t.message}\n`),t.hint&&process.stderr.write(` ${t.hint}\n`)),a(`command.error`,{command:r,error_code:t.code??`unknown_error`,duration_ms:Date.now()-n}),a(`cli.exit`,{command:r,exit_code:1,duration_ms:Date.now()-n}),await o().catch(()=>void 0),process.exit(1)}})();
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import{readConfig as e,updateConfig as t}from"./config-JVhBplSX.js";import{ApiClient as n,dashboardUrlForSite as r}from"./api-CdcB84ie.js";import{readToken as i}from"./token-store-BvSCse1t.js";import{emit$1 as a,isHeadless as o}from"./emit-D4YlMlzk.js";import{openInBrowser as s}from"./open-url-BtI5aLgL.js";import{scrubSecrets as c}from"./secrets-ApB7yh2A.js";import{parseSseStream as l}from"./client-ntsEXSVC.js";import{loginCommand as u,maybeInstallCompletions as d}from"./login-DU1fY88U.js";import{Banner as f,Panel as p,useTheme as m}from"./panel-CTtQ2ue6.js";import{DiffView as h,ProgressRow as g}from"./progress-row-Afnt5Ng8.js";import{Select as _}from"./prompt-BXvg2B4R.js";import{Keybar as v}from"./keybar-DO5OoZy9.js";import{spark as y}from"./sparkline-CpoBjjlc.js";import b from"node:path";import{promises as x}from"node:fs";import{z as S}from"zod";import C from"node:os";import w from"node:crypto";import{ulid as T}from"ulid";import{Box as E,Text as D,render as ee,useApp as te,useInput as O}from"ink";import k from"node:fs/promises";import A,{useEffect as j,useRef as ne,useState as M}from"react";import{globby as N}from"globby";import P from"ink-spinner";import{applyPatch as F}from"diff";const re=[`@zenovay/tracker`,`@zenovay/next`,`@zenovay/nuxt`,`@zenovay/svelte`,`@zenovay/astro`,`@zenovay/remix`,`@zenovay/node`],I=[`zenovay.config.ts`,`zenovay.config.js`,`zenovay.config.mjs`,`zenovay.config.json`],ie=/<[Ss]cript\b[^>]*\bsrc\s*=\s*["'`]https:\/\/(?:api|cdn)\.zenovay\.com\/[^"'`]+["'`][^>]*>/gi,ae=/["'`]https:\/\/(?:api|cdn)\.zenovay\.com\/[^"'`]*z\.js[^"'`]*["'`]/gi,oe=/["']?data-?[Ii]d["']?\s*[=:]\s*["'`](ZV_[A-Za-z0-9]+)["'`]/i,se=/data-zenovay-site\s*[=:]\s*["'`]([^"'`]+)["'`]/i,L=/\binit\s*\(\s*['"`](ZV_[A-Za-z0-9]+)['"`]/g,R=[{name:`PostHog`,patterns:[/posthog\.com\b/i,/posthog-js/,/window\.posthog/]},{name:`Plausible`,patterns:[/plausible\.io\/js/i,/window\.plausible/]},{name:`Google Analytics`,patterns:[/googletagmanager\.com\/gtag\/js/i,/www\.google-analytics\.com\/analytics\.js/i,/window\.gtag\b/]},{name:`Mixpanel`,patterns:[/cdn\.mxpnl\.com/i,/mixpanel-browser/]},{name:`Segment`,patterns:[/cdn\.segment\.com\/analytics\.js/i,/window\.analytics\b/]},{name:`Hotjar`,patterns:[/static\.hotjar\.com/i,/\(h,o,t,j,a,r\)/i]},{name:`Amplitude`,patterns:[/cdn\.amplitude\.com/i,/amplitude\.getInstance/]},{name:`Heap`,patterns:[/cdn\.heapanalytics\.com/i]},{name:`FullStory`,patterns:[/fullstory\.com\/s\/fs\.js/i,/window\.FS\.identify/]}];async function z(e,t){let n={zenovayInstalled:!1,correctTrackingCode:!1,foundTrackingCodes:[],zenovayFiles:[],competitors:[],summary:``,recommendation:`fresh-install`};try{let t=await x.readFile(b.join(e,`package.json`),`utf8`),r=JSON.parse(t),i={...r.dependencies,...r.devDependencies};for(let e of re)if(e in i){n.zenovayInstalled=!0,n.packageMarker=e;break}}catch{}for(let t of I)try{await x.access(b.join(e,t)),n.zenovayInstalled=!0,n.configFile=t;break}catch{}let r=await N([`**/*.{html,htm,tsx,jsx,vue,svelte,astro,ts,js,mjs}`,`!node_modules/**`,`!.git/**`,`!dist/**`,`!.next/**`,`!.nuxt/**`,`!build/**`,`!.output/**`],{cwd:e,gitignore:!0,deep:4,absolute:!0}).catch(()=>[]),i=new Map,a=new Set;for(let t of r.slice(0,300)){let r;try{r=await x.readFile(t,`utf8`)}catch{continue}let o=b.relative(e,t);ie.lastIndex=0,ae.lastIndex=0;let s=r.match(ie),c=r.match(ae),l=(s?.length??0)+(c?.length??0);if(l>0){n.zenovayInstalled=!0;let e=(s?.[0]??c?.[0]??``).slice(0,200),t=r.match(oe)??r.match(se),i=t?.[1]??null;i&&a.add(i),n.zenovayFiles.push({file:o,currentTrackingCode:i,scriptTagCount:l,matchSample:e})}if(l===0&&/\.[jt]sx?$/.test(t)){L.lastIndex=0;let e;for(;(e=L.exec(r))!==null;){let t=e[1];a.add(t),n.zenovayInstalled=!0,n.zenovayFiles.push({file:o,currentTrackingCode:t,scriptTagCount:0,matchSample:e[0].slice(0,80)})}}for(let e of R)if(e.patterns.some(e=>e.test(r))){let t=i.get(e.name)??new Set;t.add(o),i.set(e.name,t)}}if(n.foundTrackingCodes=Array.from(a),n.competitors=Array.from(i.entries()).map(([e,t])=>({name:e,files:Array.from(t).slice(0,5)})),n.zenovayInstalled)if(n.foundTrackingCodes.length>0){let e=n.foundTrackingCodes.every(e=>e===t);n.correctTrackingCode=e,n.recommendation=e?`no-op`:`update-tracking-code`}else n.correctTrackingCode=!1,n.recommendation=`no-op`;else n.competitors.length>0?n.recommendation=`fresh-install-alongside-competitor`:n.recommendation=`fresh-install`;return n.summary=B(n,t),n}function B(e,t){let n=[];return e.zenovayInstalled?e.foundTrackingCodes.length===0?n.push(`Zenovay package or config detected but no <script> tag found.`):e.correctTrackingCode?n.push(`Zenovay tracker present in ${e.zenovayFiles.length} file(s) with correct ID ${t}.`):n.push(`Zenovay tracker present in ${e.zenovayFiles.length} file(s), but with mismatching ID(s): ${e.foundTrackingCodes.join(`, `)} (target: ${t}).`):n.push(`No Zenovay tracker found.`),e.competitors.length>0&&n.push(`Competitor tracker(s) present (DO NOT modify): ${e.competitors.map(e=>e.name).join(`, `)}.`),n.join(` `)}async function ce(e){let t=await z(e,``);return{installed:t.zenovayInstalled,reasons:t.summary?[t.summary]:[],packageMarker:t.packageMarker,configFile:t.configFile,scriptFile:t.zenovayFiles[0]?.file}}const le=[/^package\.json$/,/^package-lock\.json$/,/^pnpm-lock\.yaml$/,/^yarn\.lock$/,/^bun\.lock$/,/^tsconfig.*\.json$/,/^(next|nuxt|vite|astro|remix|svelte|tailwind|postcss)\.config\.(ts|mts|cts|js|mjs|cjs)$/,/^app\/.*\.(tsx|ts|jsx|js|svelte|astro|vue)$/,/^pages\/.*\.(tsx|ts|jsx|js)$/,/^src\/app\/.*\.(tsx|ts|jsx|js)$/,/^src\/pages\/.*\.(tsx|ts|jsx|js)$/,/^src\/components\/.*\.(astro|svelte|vue|tsx|ts|jsx|js)$/,/^src\/(root|app|entry-server|entry-client)\.(tsx|ts|jsx|js)$/,/^gatsby-(ssr|browser|config)\.(js|ts|mjs)$/,/\.html?$/,/^src\/main\.(tsx|ts|jsx|js)$/,/^src\/App\.(tsx|ts|jsx|js|svelte|vue)$/,/^src\/routes\/\+layout\.(svelte|ts|js)$/,/^src\/routes\/root\..*$/,/^src\/layouts\/.*\.(astro|svelte|vue)$/,/^\.env\.example$/,/^README\.md$/,/^\.gitignore$/,/^nuxt\.config\.(ts|js|mjs)$/,/^plugins\/.*\.(ts|js)$/],ue=[/(^|\/)\.env($|\.(?!example$)[^/]+$)/,/(^|\/)\.git(\/|$)/,/(^|\/)node_modules\//,/(^|\/)\.ssh\//,/(^|\/)\.aws\//,/\.pem$/,/\.key$/,/(^|\/)id_rsa($|\.)/,/(^|\/)\.npmrc$/,/(^|\/)credentials(\.|$)/],V=256*1024,de=20,fe=20,pe=12;var H=class extends Error{constructor(e,t){super(t),this.code=e,this.name=`SandboxError`}};const U=/<script[^>]*src\s*=\s*["']https:\/\/(?:api|cdn)\.zenovay\.com\/[^"']+["'][^>]*>\s*<\/script>/i,me=[{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 he=class{sessionId;cwd;cwdReal;undoRoot;readCount=0;writeCount=0;roundCount=0;writtenPathsSet=new Set;constructor(e){this.sessionId=e.sessionId??T(),this.cwd=e.cwd,this.cwdReal=x.realpath(e.cwd),this.undoRoot=e.undoRoot??b.join(C.homedir(),`.zenovay`,`undo`)}incrementRound(){if(this.roundCount++,this.roundCount>pe)throw new H(`round-cap`,`Tool-call recursion cap (${pe}) 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 resolveSafe(e,t){if(typeof e!=`string`||e.length===0)throw new H(`escape`,`Path must be a non-empty string.`);if(e.includes(`\0`))throw new H(`escape`,`Null byte in path.`);if(/^\\\\[?.]\\/.test(e)||/^\\\\[A-Za-z0-9]/.test(e))throw new H(`escape`,`Windows special path prefix: ${e}`);if(/%/.test(e))try{let t=decodeURIComponent(e);if(/%[0-9A-Fa-f]{2}/.test(t))throw new H(`escape`,`Double-encoded path: ${e}`);e=t}catch(t){throw t instanceof H?t:new H(`escape`,`Malformed percent-encoding: ${e}`)}if(e.includes(`\0`))throw new H(`escape`,`Null byte in decoded path.`);if(e.includes(`\\`))throw new H(`escape`,`Backslash in path (Windows-style separator not accepted): ${e}`);let n=await this.cwdReal,r=b.isAbsolute(e)?e:b.join(n,e),i=b.normalize(r),a=i;try{a=await x.realpath(i)}catch(e){if(e.code!==`ENOENT`)throw new H(`escape`,`realpath failed: ${e.message}`);let t=b.dirname(i);try{let e=await x.realpath(t);a=b.join(e,b.basename(i))}catch{}}if(!this.isWithin(a,n))throw new H(`escape`,`Path escapes cwd: ${e}`);let o=b.relative(n,a),s=o.toLowerCase();for(let e of ue)if(e.test(o)||e.test(s)){if(t===`read`&&/(^|\/)node_modules\//i.test(o))continue;throw new H(`blocklisted`,`Path is on the hard blocklist: ${o}`)}if(t===`write`){let e=le.some(e=>e.test(o));if(!e&&!/^\.env(\.local)?$/.test(o)&&!/^\.claude\//.test(o)&&!/^\.cursor\//.test(o))throw new H(`not-allowlisted`,`Write path not on allowlist: ${o}`)}return a}isWithin(e,t){let n=b.relative(t,e);return!n.startsWith(`..`)&&!b.isAbsolute(n)}async safeRead(e){if(this.readCount>=de)throw new H(`read-cap`,`Read cap (${de}) reached.`);let t=await this.resolveForRead(e),n=await x.stat(t);if(n.size>V)throw new H(`too-large`,`File exceeds ${V}B: ${e} (${n.size}B)`);let r=await x.readFile(t),i=r.subarray(0,Math.min(r.length,8192));if(i.includes(0))throw new H(`binary-rejected`,`Binary content in ${e}.`);return this.readCount++,r.toString(`utf8`)}async safeWrite(e,t){if(this.writeCount>=fe)throw new H(`write-cap`,`Write cap (${fe}) reached.`);if(t.length>V)throw new H(`too-large`,`Write exceeds ${V}B: ${e}`);let n=await this.resolveForWrite(e),r=await x.readFile(n,`utf8`).catch(e=>{if(e.code===`ENOENT`)return null;throw e});if(r!==null){if(U.test(r)&&!U.test(t))throw new H(`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 me)if(i.test(r)&&!i.test(t))throw new H(`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 x.mkdir(b.dirname(n),{recursive:!0}),await x.writeFile(n,t,`utf8`),this.writeCount++;let a=await this.cwdReal;return this.writtenPathsSet.add(b.relative(a,n)),{backupPath:i}}async journalBackup(e){let t=await x.readFile(e).catch(e=>{if(e.code===`ENOENT`)return null;throw e}),n=b.join(this.undoRoot,this.sessionId);await x.mkdir(n,{recursive:!0,mode:448});let r=w.createHash(`sha256`).update(e).digest(`hex`).slice(0,16),i=b.join(n,`${r}.bak`),a=b.join(n,`manifest.jsonl`);t&&await x.writeFile(i,t,{mode:384});let o=JSON.stringify({abs:e,backupPath:t?i:null,ts:Date.now()});return await x.appendFile(a,o+`
|
|
2
|
+
`,{mode:384}),t?i:null}static wrapForModel(e,t){let n=w.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 c(e)}};async function ge(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 _e(e){let t=e.trackingCode??e.siteId??``,n=e.targetPath||`src/index.html`,r=`<script defer\n data-id="${t}"\n data-allow-localhost="true"\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 ve={id:`angular`,displayName:`Angular`,detect:ge,files:[{path:`src/index.html`,kind:`mutate`,required:!0}],envVarName:`NG_ZENOVAY_SITE`,buildSnippets:_e},ye=[`astro.config.ts`,`astro.config.mjs`,`astro.config.js`];async function be(e){for(let t of ye)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 xe(e){let t=e.trackingCode??e.siteId??``,n=`<script defer data-id="${t}" data-allow-localhost="true" 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`."}]}const Se={id:`astro`,displayName:`Astro`,detect:be,files:[{path:`src/layouts/Layout.astro`,kind:`mutate`,required:!1},{path:`src/layouts/BaseHead.astro`,kind:`mutate`,required:!1},{path:`.env`,kind:`create`,required:!0}],envVarName:`PUBLIC_ZENOVAY_SITE`,buildSnippets:xe};async function Ce(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 we(e){return await Ce(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');
|
|
3
|
+
|
|
4
|
+
exports.onRenderBody = ({ setHeadComponents }) => {
|
|
5
|
+
setHeadComponents([
|
|
6
|
+
React.createElement('script', {
|
|
7
|
+
key: 'zenovay-tracker',
|
|
8
|
+
defer: true,
|
|
9
|
+
'data-id': '${t}',
|
|
10
|
+
'data-allow-localhost': 'true',
|
|
11
|
+
src: 'https://api.zenovay.com/z.js',
|
|
12
|
+
}),
|
|
13
|
+
]);
|
|
14
|
+
};
|
|
15
|
+
`;return[{targetPath:`gatsby-ssr.js`,anchorKind:`replace-file`,code:n,description:`Add the Zenovay tracker via Gatsby SSR onRenderBody → setHeadComponents.`}]}const Ee={id:`gatsby`,displayName:`Gatsby`,detect:we,files:[{path:`gatsby-ssr.js`,kind:`create`,required:!0}],envVarName:`GATSBY_ZENOVAY_SITE`,buildSnippets:Te},De=[`app/layout.tsx`,`app/layout.ts`,`app/layout.jsx`,`app/layout.js`,`src/app/layout.tsx`,`src/app/layout.ts`,`src/app/layout.jsx`,`src/app/layout.js`];async function Oe(e){for(let t of De)if(await e.exists(t))return t;return null}async function ke(e){let t=await e.readFile(`package.json`);if(!t)return!1;try{let e=JSON.parse(t);return!!(e.dependencies?.next??e.devDependencies?.next)}catch{return!1}}async function Ae(e){let t=await ke(e),n=await e.exists(`app`)||await e.exists(`src/app`),r=await Oe(e);return t?n?r?{matched:!0,confidence:.95,reason:`Detected Next.js App Router via \`next\` dep + \`${r}\`.`}:{matched:!1,confidence:.4,reason:"Found `app/` but no root layout file (layout.tsx/ts/jsx/js)."}:{matched:!1,confidence:0,reason:"No `app/` directory found — not an App Router project."}:{matched:!1,confidence:0,reason:"package.json does not list `next` as a dependency."}}function je(e,t=`script`){let n=e.targetPath||`app/layout.tsx`,r=e.trackingCode??e.siteId??``;return t===`npm`?Ne(n,r):Me(n,r)}function Me(e,t){return[{targetPath:e,anchorKind:`after-imports`,code:`import Script from 'next/script';`,description:`Import next/script to inject the Zenovay tracker.`},{targetPath:e,anchorKind:`wrap-children`,code:`<Script
|
|
16
|
+
defer
|
|
17
|
+
data-id="${t}"
|
|
18
|
+
data-allow-localhost="true"
|
|
19
|
+
src="https://api.zenovay.com/z.js"
|
|
20
|
+
strategy="afterInteractive"
|
|
21
|
+
/>
|
|
22
|
+
{children}`,description:`Add the Zenovay tracker <Script> next to children in the root layout.`}]}function Ne(e,t){return[{targetPath:`components/zenovay-bootstrap.tsx`,anchorKind:`replace-file`,code:`'use client';
|
|
23
|
+
|
|
24
|
+
import { useEffect } from 'react';
|
|
25
|
+
import { init } from '@zenovay/tracker';
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Mounts the Zenovay tracker exactly once on the client. Equivalent to the
|
|
29
|
+
* canonical <script src="https://api.zenovay.com/z.js"> tag — init() injects
|
|
30
|
+
* the same loader internally.
|
|
31
|
+
*/
|
|
32
|
+
export function ZenovayBootstrap() {
|
|
33
|
+
useEffect(() => {
|
|
34
|
+
init('${t}', { allowLocalhost: true });
|
|
35
|
+
}, []);
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
`,description:`Create a client-component bootstrap that calls init() from @zenovay/tracker.`},{targetPath:e,anchorKind:`after-imports`,code:`import { ZenovayBootstrap } from '@/components/zenovay-bootstrap';`,description:`Import the Zenovay tracker bootstrap into the root layout.`},{targetPath:e,anchorKind:`wrap-children`,code:`<ZenovayBootstrap />
|
|
39
|
+
{children}`,description:`Render the Zenovay tracker bootstrap alongside children in the root layout.`}]}const Pe={id:`next-app-router`,displayName:`Next.js (App Router)`,detect:Ae,files:[{path:`app/layout.tsx`,kind:`mutate`,required:!0}],envVarName:`NEXT_PUBLIC_ZENOVAY_SITE`,packageDeps:[`@zenovay/tracker`],supportsNpmMode:!0,buildSnippets:je},Fe=[`pages/_app.tsx`,`pages/_app.ts`,`pages/_app.jsx`,`pages/_app.js`,`src/pages/_app.tsx`,`src/pages/_app.ts`,`src/pages/_app.jsx`,`src/pages/_app.js`];async function Ie(e){for(let t of Fe)if(await e.exists(t))return t;return null}async function Le(e){let t=await e.readFile(`package.json`);if(!t)return!1;try{let e=JSON.parse(t);return!!(e.dependencies?.next??e.devDependencies?.next)}catch{return!1}}async function Re(e){let t=await Le(e);if(!t)return{matched:!1,confidence:0,reason:"package.json does not list `next` as a dependency."};let n=await Ie(e);if(n)return{matched:!0,confidence:.9,reason:`Detected Next.js Pages Router via \`${n}\`.`};let r=await e.exists(`app`),i=await e.glob(`pages/**/*.{tsx,ts,jsx,js}`);return i.length>0&&!r?{matched:!0,confidence:.7,reason:"Found `pages/` directory with route files but no `_app` — will create one."}:{matched:!1,confidence:.2,reason:`Next.js detected, but no pages-router entry point found.`}}function ze(e){let t=`pages/_app.tsx`,n=e.trackingCode??e.siteId??``,r=`import type { AppProps } from 'next/app';
|
|
40
|
+
import Script from 'next/script';
|
|
41
|
+
|
|
42
|
+
export default function App({ Component, pageProps }: AppProps) {
|
|
43
|
+
return (
|
|
44
|
+
<>
|
|
45
|
+
<Script
|
|
46
|
+
defer
|
|
47
|
+
data-id="${n}"
|
|
48
|
+
data-allow-localhost="true"
|
|
49
|
+
src="https://api.zenovay.com/z.js"
|
|
50
|
+
strategy="afterInteractive"
|
|
51
|
+
/>
|
|
52
|
+
<Component {...pageProps} />
|
|
53
|
+
</>
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
`;return[{targetPath:t,anchorKind:`after-imports`,code:`import Script from 'next/script';`,description:"Import next/script in `_app`."},{targetPath:t,anchorKind:`wrap-children`,code:`<><Script defer data-id="${n}" data-allow-localhost="true" src="https://api.zenovay.com/z.js" strategy="afterInteractive" /><Component {...pageProps} /></>`,description:`Render the Zenovay tracker alongside the page component.`},{targetPath:t,anchorKind:`replace-file`,code:r,description:"Full replacement when `_app` does not exist yet."}]}const Be={id:`next-pages-router`,displayName:`Next.js (Pages Router)`,detect:Re,files:[{path:`pages/_app.tsx`,kind:`mutate`,required:!0}],envVarName:`NEXT_PUBLIC_ZENOVAY_SITE`,buildSnippets:ze},Ve=S.object({modules:S.array(S.string()).optional(),runtimeConfig:S.object({public:S.record(S.string(),S.unknown()).optional()}).optional()}).passthrough();async function He(e){let t=await e.readFile(`package.json`);if(!t)return{matched:!1,confidence:0,reason:`No package.json found.`};try{let e=JSON.parse(t),n=!!(e.dependencies?.nuxt??e.devDependencies?.nuxt??e.dependencies?.nuxt3??e.devDependencies?.nuxt3);if(n)return{matched:!0,confidence:.95,reason:"Detected Nuxt via `nuxt` / `nuxt3` dependency."}}catch{}let n=await e.exists(`nuxt.config.ts`)||await e.exists(`nuxt.config.js`)||await e.exists(`nuxt.config.mjs`);return n?{matched:!0,confidence:.6,reason:"Found `nuxt.config.*` but no explicit dependency listing."}:{matched:!1,confidence:0,reason:`No Nuxt dependency or config detected.`}}function Ue(e){let t=e.trackingCode??e.siteId??``,n=` app: {
|
|
57
|
+
head: {
|
|
58
|
+
script: [
|
|
59
|
+
{
|
|
60
|
+
defer: true,
|
|
61
|
+
src: 'https://api.zenovay.com/z.js',
|
|
62
|
+
'data-id': '${t}',
|
|
63
|
+
'data-allow-localhost': 'true',
|
|
64
|
+
},
|
|
65
|
+
],
|
|
66
|
+
},
|
|
67
|
+
},`;return[{targetPath:`nuxt.config.ts`,anchorKind:`head-tag`,code:n,description:"Add the Zenovay tracker to Nuxt's `app.head.script` so every page loads it."}]}const We={id:`nuxt`,displayName:`Nuxt`,detect:He,files:[{path:`nuxt.config.ts`,kind:`mutate`,required:!0}],envVarName:`NUXT_PUBLIC_ZENOVAY_SITE`,buildSnippets:Ue},Ge=[`index.html`,`public/index.html`,`dist/index.html`];async function Ke(e){for(let t of Ge)if(await e.exists(t))return{matched:!0,confidence:.5,reason:`Detected plain HTML project via \`${t}\`.`};let t=await e.glob(`**/*.html`);return t.length>0?{matched:!0,confidence:.3,reason:`Found ${t.length} HTML file(s); plain-HTML adapter is usable as fallback.`}:{matched:!1,confidence:0,reason:`No HTML files found in the project.`}}function qe(e){let t=e.siteId??``,n=`<script defer\n data-id="${t}"\n data-allow-localhost="true"\n src="https://api.zenovay.com/z.js">\n</script>`;return[{targetPath:`index.html`,anchorKind:`head-tag`,code:n,description:`Inject the Zenovay tracker inside <head>. Repeat for every HTML file that contains a <head>.`}]}const Je={id:`plain-html`,displayName:`Plain HTML`,detect:Ke,files:[{path:`index.html`,kind:`mutate`,required:!0}],envVarName:`PUBLIC_ZENOVAY_SITE`,buildSnippets:qe};async function Ye(e){let t=await e.readFile(`package.json`);if(!t)return{matched:!1,confidence:0,reason:`No package.json.`};try{let e=JSON.parse(t),n={...e.dependencies??{},...e.devDependencies??{}};if(n[`@builder.io/qwik-city`]??n[`@builder.io/qwik`])return{matched:!0,confidence:.92,reason:"Detected Qwik via `@builder.io/qwik(-city)`."}}catch{}return{matched:!1,confidence:0,reason:`No Qwik dependency found.`}}function Xe(e){let t=e.trackingCode??e.siteId??``,n=e.targetPath||`src/root.tsx`,r=`<script
|
|
68
|
+
defer
|
|
69
|
+
data-id="${t}"
|
|
70
|
+
data-allow-localhost="true"
|
|
71
|
+
src="https://api.zenovay.com/z.js"
|
|
72
|
+
/>`;return[{targetPath:n,anchorKind:`head-tag`,code:r,description:`Add the Zenovay tracker into the <head> of the Qwik root document.`}]}const Ze={id:`qwik`,displayName:`Qwik`,detect:Ye,files:[{path:`src/root.tsx`,kind:`mutate`,required:!0}],envVarName:`PUBLIC_ZENOVAY_SITE`,buildSnippets:Xe};async function Qe(e){let t=await e.readFile(`package.json`);if(t)try{let e=JSON.parse(t),n={...e.dependencies??{},...e.devDependencies??{}},r=Object.keys(n).some(e=>e.startsWith(`@remix-run/`));if(r)return{matched:!0,confidence:.95,reason:"Detected Remix via `@remix-run/*` dependencies."}}catch{}return await e.exists(`remix.config.js`)||await e.exists(`remix.config.ts`)?{matched:!0,confidence:.8,reason:"Detected Remix via `remix.config.*`."}:{matched:!1,confidence:0,reason:`No Remix dependency or config detected.`}}function $e(e){let t=e.trackingCode??e.siteId??``;return[{targetPath:`app/root.tsx`,anchorKind:`head-tag`,code:`<script defer data-id="${t}" data-allow-localhost="true" src="https://api.zenovay.com/z.js"></script>`,description:`Inline the Zenovay tracker <script> inside the document <head>.`}]}const et={id:`remix`,displayName:`Remix`,detect:Qe,files:[{path:`app/root.tsx`,kind:`mutate`,required:!0}],envVarName:`PUBLIC_ZENOVAY_SITE`,buildSnippets:$e};async function tt(e){let t=await e.readFile(`package.json`);if(!t)return{matched:!1,confidence:0,reason:`No package.json.`};try{let e=JSON.parse(t),n={...e.dependencies??{},...e.devDependencies??{}};if(n[`@solidjs/start`]??n[`solid-start`])return{matched:!0,confidence:.92,reason:"Detected SolidStart via `@solidjs/start` / `solid-start`."}}catch{}return{matched:!1,confidence:0,reason:`No SolidStart dependency found.`}}function nt(e){let t=e.trackingCode??e.siteId??``,n=e.targetPath||`src/entry-server.tsx`,r=`<script
|
|
73
|
+
defer
|
|
74
|
+
data-id="${t}"
|
|
75
|
+
data-allow-localhost="true"
|
|
76
|
+
src="https://api.zenovay.com/z.js"
|
|
77
|
+
/>`;return[{targetPath:n,anchorKind:`head-tag`,code:r,description:`Add the Zenovay tracker into the document <head> rendered by SolidStart entry-server.`}]}const rt={id:`solid-start`,displayName:`SolidStart`,detect:tt,files:[{path:`src/entry-server.tsx`,kind:`mutate`,required:!0}],envVarName:`VITE_ZENOVAY_SITE`,buildSnippets:nt};async function it(e){let t=await e.readFile(`package.json`);if(!t)return{matched:!1,confidence:0,reason:`No package.json found.`};try{let e=JSON.parse(t),n=!!(e.dependencies?.[`@sveltejs/kit`]??e.devDependencies?.[`@sveltejs/kit`]);return n?{matched:!0,confidence:.95,reason:"Detected SvelteKit via `@sveltejs/kit` dependency."}:{matched:!1,confidence:0,reason:"`@sveltejs/kit` not in dependencies."}}catch{return{matched:!1,confidence:0,reason:`package.json is not valid JSON.`}}}function at(e){let t=e.trackingCode??e.siteId??``,n=`<svelte:head>
|
|
78
|
+
<script defer data-id="${t}" data-allow-localhost="true" src="https://api.zenovay.com/z.js"></script>
|
|
79
|
+
</svelte:head>
|
|
80
|
+
|
|
81
|
+
<slot />
|
|
82
|
+
`;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 ot={id:`sveltekit`,displayName:`SvelteKit`,detect:it,files:[{path:`src/routes/+layout.svelte`,kind:`mutate`,required:!0}],envVarName:`PUBLIC_ZENOVAY_SITE`,buildSnippets:at},st=[`next`,`nuxt`,`nuxt3`,`@sveltejs/kit`,`astro`,`@remix-run/react`,`@builder.io/qwik-city`,`@builder.io/qwik`,`@solidjs/start`,`solid-start`,`@angular/core`,`gatsby`],ct=[`index.html`,`public/index.html`];async function lt(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 ut(e){for(let t of ct)if(await e.exists(t))return t;return null}async function dt(e){let t=await lt(e);if(st.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 ut(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 ft(e){let t=e.trackingCode??e.siteId??``,n=e.targetPath||`index.html`,r=`<script defer\n data-id="${t}"\n data-allow-localhost="true"\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 pt={id:`vite`,displayName:`Vite`,detect:dt,files:[{path:`index.html`,kind:`mutate`,required:!0}],envVarName:`VITE_ZENOVAY_SITE`,buildSnippets:ft},mt=[Pe,Be,We,ot,Se,et,Ee,ve,rt,Ze,pt,Je];async function ht(e){let t=[];for(let n of mt){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 gt(e){let t=t=>b.resolve(e,t);return{cwd:e,async readFile(e){try{return await x.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 x.access(t(e)),!0}catch{return!1}},async glob(t){return N(t,{cwd:e,dot:!1,gitignore:!0,onlyFiles:!0,followSymbolicLinks:!1})}}}async function _t(e,t){let n=gt(e),{adapter:r,ranked:i}=await ht(n),a=i[0];return r&&a&&a.result.confidence>=.7?r:t?t.pickInteractively(i):r}function vt(e,t){let n=/[\s"'#=]/.test(t)||t===``,r=n?`"${t.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`:t;return`${e}=${r}`}function yt(e){let t=new Set;for(let n of e.split(/\r?\n/)){let e=n.trim();if(!e||e.startsWith(`#`))continue;let r=e.indexOf(`=`);if(r<=0)continue;let i=e.slice(0,r).trim();/^[A-Za-z_][A-Za-z0-9_]*$/.test(i)&&t.add(i)}return t}async function W(e,t,n={}){let r=n.filename??`.env.local`,i=b.resolve(e,r),a=``,o=!0;try{a=await x.readFile(i,`utf8`)}catch(e){if(e.code===`ENOENT`)o=!1;else throw e}let s=o?yt(a):new Set,c=[],l=[],u=[];for(let[e,n]of Object.entries(t)){if(s.has(e)){l.push(e);continue}u.push(vt(e,n)),c.push(e)}if(c.length===0)return{created:!1,existing:o,addedKeys:c,skippedKeys:l};let d=`# Added by Zenovay CLI`,f;if(o){let e=a.length>0&&!a.endsWith(`
|
|
83
|
+
`);f=a+(e?`
|
|
84
|
+
`:``)+`
|
|
85
|
+
`+d+`
|
|
86
|
+
`+u.join(`
|
|
87
|
+
`)+`
|
|
88
|
+
`}else f=d+`
|
|
89
|
+
`+u.join(`
|
|
90
|
+
`)+`
|
|
91
|
+
`;if(o)await x.writeFile(i,f,`utf8`);else{let e=await x.open(i,`w`,384);try{await e.writeFile(f,`utf8`)}finally{await e.close()}}return{created:!o,existing:o,addedKeys:c,skippedKeys:l}}const bt=`https://api.zenovay.com/mcp`,xt=S.object({url:S.string().url(),headers:S.record(S.string(),S.string()).optional()}),St=S.object({mcpServers:S.record(S.string(),xt).optional()}).passthrough();function Ct(e){return e.HOME??e.USERPROFILE??C.homedir()}function wt(e){return e.APPDATA??null}function Tt(e,t){let n=Ct(t),r=wt(t),i=[];return i.push({id:`cursor`,displayName:`Cursor`,configPath:b.join(n,`.cursor`,`mcp.json`)}),e===`win32`&&r&&i.push({id:`cursor`,displayName:`Cursor (AppData)`,configPath:b.join(r,`Cursor`,`User`,`globalStorage`,`cursor.mcp`,`mcp.json`)}),e===`darwin`?i.push({id:`claude-desktop`,displayName:`Claude Desktop`,configPath:b.join(n,`Library`,`Application Support`,`Claude`,`claude_desktop_config.json`)}):e===`win32`&&r?i.push({id:`claude-desktop`,displayName:`Claude Desktop`,configPath:b.join(r,`Claude`,`claude_desktop_config.json`)}):i.push({id:`claude-desktop`,displayName:`Claude Desktop`,configPath:b.join(n,`.config`,`Claude`,`claude_desktop_config.json`)}),i.push({id:`vscode`,displayName:`VS Code`,configPath:b.join(n,`.vscode`,`mcp.json`)}),i}async function Et(e){try{return await x.access(e),!0}catch{return!1}}async function Dt(e){try{let t=await x.readFile(e,`utf8`);if(t.trim().length===0)return{};let n=JSON.parse(t),r=St.safeParse(n);return r.success?r.data:n&&typeof n==`object`?n:{}}catch{return{}}}function Ot(){return{url:bt}}async function G(e){let t=e.env??process.env,n=e.platform??process.platform,r=new Set(e.skip??[]),i=[],a=[],o=[],s=new Set,c=Ot();for(let e of Tt(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 Et(e.configPath);if(!t){a.push(e.displayName);continue}let n=await Dt(e.configPath),r=`${e.configPath}.bak`;await x.copyFile(e.configPath,r);let o={...n,mcpServers:{...n.mcpServers??{},zenovay:c}};await x.mkdir(b.dirname(e.configPath),{recursive:!0}),await x.writeFile(e.configPath,JSON.stringify(o,null,2)+`
|
|
92
|
+
`,`utf8`),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 kt(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 At=S.object({path:S.string().min(1)}),jt=S.object({path:S.string().min(1),content:S.string(),reason:S.string().min(1)}),Mt=S.object({path:S.string().min(1),patch:S.string().min(1),reason:S.string().min(1)}),Nt=S.object({}),Pt=S.object({question:S.string().min(1),choices:S.array(S.string()).optional()});async function Ft(e,t){let n=At.safeParse(t);if(!n.success)return{ok:!1,content:null,error:`invalid_args`};try{let t=await e.safeRead(n.data.path),r=he.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:he.wrapForModel(n.data.path,a)}}catch(e){return{ok:!1,content:null,error:e.message}}}async function It(e,t,n){let r=jt.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 Lt(e,t,n){let r=Mt.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=F(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.`}:It(e,{path:i,content:c,reason:o},n)}async function Rt(e){try{let t=gt(e),{adapter:n,ranked:r}=await ht(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 zt(e,t){let n=Pt.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}}}async function Bt(e){let{api:t,sandbox:n,approval:r,prompter:i,handlers:a}=e,o=[...e.initialMessages],s=``,c=0;for(;c<pe;){n.incrementRound(),c++;let u=await t.openAiStream(`install`,{messages:o,cwd_fingerprint:n.sessionId,diagnosis:e.diagnosis,targetTrackingCode:e.targetTrackingCode}),d=[],f=``;for await(let e of l(u))switch(e.type){case`delta`:f+=e.content,a?.onDelta?.(e.content);break;case`tool_start`:a?.onToolStart?.({id:e.id,name:e.name});break;case`tool_call`:{let t=await Vt(e.name,e.arguments,{sandbox:n,cwd:n.cwd,approval:r,prompter:i});d.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 a?.onError?.(e),Error(`[${e.code}] ${e.message}`);case`done`:break}if(f&&(s+=f),d.length===0){f&&o.push({role:`assistant`,content:f});break}o.push({role:`assistant`,content:f,toolCalls:d.map(e=>({id:e.id,type:`function`,function:{name:e.name,arguments:JSON.stringify(e.arguments)}}))});for(let e of d)o.push({role:`tool`,toolCallId:e.id,toolName:e.name,content:JSON.stringify(e.result)})}return{finalText:s,rounds:c}}async function Vt(e,t,n){try{switch(e){case`read_file`:return await Ft(n.sandbox,t);case`write_file`:return await It(n.sandbox,t,n.approval);case`patch_file`:return await Lt(n.sandbox,t,n.approval);case`detect_framework`:return await Rt(n.cwd);case`ask_user`:return await zt(n.prompter,t);default:return{ok:!1,content:null,error:`unknown_tool:${e}`}}}catch(e){return{ok:!1,content:null,error:`tool_threw: ${e.message}`}}}const Ht=e=>`<script defer\n data-id="${e}"\n data-allow-localhost="true"\n src="https://api.zenovay.com/z.js">\n</script>`;async function Ut(e){let t={installed:[],skipped:[],errors:[]},n=await N([`**/*.html`,`!node_modules/**`,`!.git/**`,`!dist/**`,`!.next/**`,`!.nuxt/**`,`!build/**`,`!.output/**`],{cwd:e.cwd,gitignore:!0,absolute:!1});if(n.length===0)return t;let r=Ht(e.trackingCode),i=RegExp(`data-id\\s*=\\s*["']${Wt(e.trackingCode)}["']`);for(let a of n){let n=b.join(e.cwd,a),o;try{o=await x.readFile(n,`utf8`)}catch(e){t.errors.push({file:a,error:e.message});continue}if(U.test(o)&&i.test(o)){t.skipped.push({file:a,reason:`already installed with correct tracking code`});continue}let s;if(U.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??`
|
|
93
|
+
`,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 me)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 x.writeFile(n,s,`utf8`),t.installed.push(a)}catch(e){t.errors.push({file:a,error:e.message})}}return t}function Wt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}const Gt=`https://api.zenovay.com/z.js`;function Kt(e,t){return e.includes(Gt)&&e.includes(t)}function qt(e){if(/from\s+['"]next\/script['"]/.test(e))return e;let t=e.split(`
|
|
94
|
+
`),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(`
|
|
95
|
+
`)}function Jt(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}" data-allow-localhost="true" src="${Gt}" strategy="afterInteractive" />`;return e.replace(n,`${a}\n${i}</body>`)}async function Yt(e){let{cwd:t,trackingCode:n}=e,r={installed:[],skipped:[],errors:[],fellThrough:!1},i;try{i=await N([`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 k.readFile(b.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(Kt(o.src,n))return r.skipped.push({file:o.rel,reason:`already installed with correct tracking code`}),r;let s=qt(o.src),c=Jt(s,n);if(!c)return r.fellThrough=!0,r;try{await k.writeFile(b.join(t,o.rel),c),r.installed.push(o.rel)}catch(e){r.errors.push({file:o.rel,error:e.message}),r.fellThrough=!0}return r}const K=`api.zenovay.com/z.js`;async function q(e){try{return await x.readFile(e,`utf8`)}catch{return null}}function Xt(e,t){let n=e.toLowerCase().lastIndexOf(`</head>`);if(n===-1)return null;let r=e.lastIndexOf(`
|
|
96
|
+
`,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 Zt(e){if(e.adapter.id===`nuxt`)return $t(e);if(e.adapter.id===`sveltekit`)return en(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 e=!1;for(let n of o){let r=b.join(t,n.targetPath),i=await q(r);if(i===null){a.skipped.push({file:n.targetPath,reason:`target file not present`});continue}if(i.includes(K)){a.skipped.push({file:n.targetPath,reason:`tracker already present`}),e=!0;break}let o=Xt(i,n.code);if(o===null){a.skipped.push({file:n.targetPath,reason:`no </head> anchor in target`});continue}try{await x.writeFile(r,o,`utf8`),a.installed.push(n.targetPath),e=!0;break}catch(e){a.errors.push({file:n.targetPath,error:e.message})}}return!e&&a.installed.length===0&&a.errors.length===0&&(a.fellThrough=!0),a}if(s.size===1&&s.has(`replace-file`)&&o.length===1){let e=o[0];if(!e)return a.fellThrough=!0,a;let n=i.files.find(t=>t.path===e.targetPath),r=b.join(t,e.targetPath),s=await q(r);if(s!==null)return s.includes(K)?(a.skipped.push({file:e.targetPath,reason:`tracker already present`}),a):(a.fellThrough=!0,a);if(n?.kind===`create`){try{await x.mkdir(b.dirname(r),{recursive:!0}),await x.writeFile(r,e.code,`utf8`),a.installed.push(e.targetPath)}catch(t){a.errors.push({file:e.targetPath,error:t.message}),a.fellThrough=a.installed.length===0}return a}return a.fellThrough=!0,a}return a.fellThrough=!0,a}function Qt(){return{installed:[],skipped:[],errors:[],fellThrough:!1}}async function $t(e){let t=Qt(),n=[`nuxt.config.ts`,`nuxt.config.mjs`,`nuxt.config.js`],r=null,i=null,a=null;for(let t of n){let n=b.join(e.cwd,t),o=await q(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(K))return t.skipped.push({file:r,reason:`tracker already present`}),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 x.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 en(e){let t=Qt(),n=`src/routes/+layout.svelte`,r=b.join(e.cwd,n),i=await q(r),a=`<svelte:head>\n <script defer data-id="${e.trackingCode}" data-allow-localhost="true" src="https://api.zenovay.com/z.js"></script>\n</svelte:head>\n`;if(i!==null){if(i.includes(K))return t.skipped.push({file:n,reason:`tracker already present`}),t;try{await x.writeFile(r,`${a}\n${i}`,`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 x.mkdir(b.dirname(r),{recursive:!0}),await x.writeFile(r,o,`utf8`),t.installed.push(n)}catch(e){t.errors.push({file:n,error:e.message}),t.fellThrough=!0}return t}const tn=`\x1B]8;;`,nn=`\x07`;function rn(){return process.env.FORCE_HYPERLINK?!0:!(process.env.NO_COLOR||!process.stdout.isTTY||process.env.CI||(process.env.TERM??``)===`dumb`)}function J({url:e,label:t,color:n,arrow:r=!0}){let{theme:i}=m(),a=n??i.fg,o=(t??e)+(r?` ↗`:``);return rn()?A.createElement(D,{color:a,underline:!0},tn,e,nn,o,tn,nn):t&&t!==e?A.createElement(D,{color:a},A.createElement(D,{underline:!0},t),A.createElement(D,{color:i.dim},` (`,e,`)`)):A.createElement(D,{color:a,underline:!0},e)}function Y({label:e,value:t,labelWidth:n=12}){let{theme:r}=m();return A.createElement(E,{flexDirection:`row`},A.createElement(E,{width:n,flexShrink:0},A.createElement(D,{color:r.dim},e.toUpperCase())),typeof t==`string`?A.createElement(D,{color:r.fg},t):t)}function an(e){return e.review&&process.stdout.isTTY?`interactive`:`auto`}function on(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 sn(){let e=[12,15,18,22,28,35,41,50,58,64,72,78],t=y(e,24);return[` ↑`,` ${t}`,` └────────────────────────`,` May Jun Jul Aug Sep`]}function cn(){return[` Landing page ████████████████████ 100%`,` ↓ -28%`,` Pricing ██████████████░░░░░░ 72%`,` ↓ -50%`,` Checkout ███████░░░░░░░░░░░░░ 36%`,` ↓ -64%`,` Purchased ███░░░░░░░░░░░░░░░░░ 13%`]}function ln(){return[` ▇▇▇▇▇▇▇▇▇▎ 89 Sarah K. /pricing 🇺🇸`,` ▇▇▇▇▇▇░░░░ 61 anon /docs 🇩🇪`,` ▇▇▇░░░░░░░ 34 anon /changelog 🇯🇵`]}function un(){return[` LCP ● 2.1s good ████████████░░░░░░`,` INP ● 89ms good ██████████████████`,` CLS ⚠ 0.14 needs ████████████░░░░░░`,` TTFB ● 380ms good ███████████████░░░`]}const X=[{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:sn},{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:cn},{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:ln},{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:un},{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.`]}],dn=11e3,fn=9,pn=({width:e,height:t})=>{let{theme:n}=m(),[r,i]=M(0);j(()=>{if(X.length<=1)return;let e=setInterval(()=>{i(e=>(e+1)%X.length)},dn);return()=>clearInterval(e)},[]);let a=X[r],o=a.visual?a.visual():[];return A.createElement(E,{flexDirection:`column`,width:e,height:t,paddingX:2,paddingY:1},A.createElement(E,{marginBottom:1},A.createElement(D,{color:n.typography.label.color,dimColor:n.typography.label.dim},`LEARN`)),A.createElement(E,{flexDirection:`column`,minHeight:fn,key:r},A.createElement(E,{marginBottom:1},A.createElement(D,{bold:!0,color:n.fg,wrap:`truncate`},a.title)),a.body.map((e,t)=>A.createElement(D,{key:t,color:n.muted,wrap:`truncate`},e||` `)),o.length>0&&A.createElement(E,{flexDirection:`column`,marginTop:1},o.map((e,t)=>A.createElement(D,{key:t,color:n.accent},e)))),A.createElement(E,{flexGrow:1}),A.createElement(E,{marginTop:1},A.createElement(D,null,X.map((e,t)=>A.createElement(D,{key:t,color:t===r?n.muted:n.dim},t===r?`─`:`·`)))))},mn={pending:`·`,active:`⠋`,done:`✓`,error:`✗`};function hn(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 gn=({tasks:e,width:t,height:n,liveLine:r})=>{let{theme:i}=m();return A.createElement(E,{flexDirection:`column`,width:t,height:n,paddingX:2,paddingY:1},A.createElement(E,{marginBottom:1},A.createElement(D,{color:i.typography.label.color,dimColor:i.typography.label.dim},`TASKS`)),e.map(e=>A.createElement(E,{key:e.id,flexDirection:`column`},A.createElement(E,{flexDirection:`row`},e.status===`active`?A.createElement(D,{color:i.accent},A.createElement(P,{type:`dots`})):A.createElement(D,{color:hn(e.status,i)},mn[e.status]),A.createElement(D,null,` `),A.createElement(D,{color:e.status===`pending`?i.muted:i.fg,wrap:`truncate`},e.label)),e.detail&&A.createElement(E,{paddingLeft:2},A.createElement(D,{color:i.dim,wrap:`truncate`},e.detail)))),A.createElement(E,{flexGrow:1}),r&&A.createElement(E,{flexDirection:`row`,marginTop:1},A.createElement(D,{color:i.accent},`◆ `),A.createElement(D,{color:i.fg,wrap:`truncate`},r)))};async function _n(e){if(o(e))return vn(e);let t=`quit`,n=null,r=await new Promise(r=>{let{unmount:i,waitUntilExit:a}=ee(A.createElement(yn,{opts:e,onExit:(e,a,o)=>{t=a??`quit`,n=o??null,i(),r(e)}}),{exitOnCtrlC:!0});a().catch(()=>r(1))});if(r===0&&await d().catch(()=>void 0),r!==0||t===`quit`||!n)return r;let i=n.id;if(t===`watch`){let{overviewCommand:t}=await import(`./overview-L8jqiSuU.js`);return t({cliVersion:e.cliVersion,siteId:i})}if(t===`events`){let{eventsTailCommand:t}=await import(`./events-tail-DEdVkmT0.js`);return t({cliVersion:e.cliVersion,siteId:i})}return 0}async function vn(t){let r=await import(`./telemetry-Bbh6Vtst.js`).catch(()=>null);r?.emit(`install.start`,{properties:{mode:`headless`}});try{let o=await e(),s=await _t(t.cwd);if(!s)return a({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;a({type:`framework.detected`,framework:s.id,confidence:1}),r?.emit(`install.framework_detected`,{properties:{framework:s.id}});let c=await i({strict:!1});if(!c&&!process.env.ZENOVAY_API_TOKEN)return a({type:`error`,code:`not_logged_in`,message:"Run `zenovay login` first (or set ZENOVAY_API_TOKEN)."}),2;let l=new n({config:o,cliVersion:t.cliVersion,token:c}),[u,d]=await Promise.all([l.getSites(),z(t.cwd,``).catch(()=>null)]),f;if(t.siteId){if(f=u.find(e=>e.id===t.siteId),!f)return a({type:`error`,code:`site_not_found`,message:`Site ${t.siteId} not found.`}),2}else if(d?.foundTrackingCodes.length){for(let e of d.foundTrackingCodes){let t=u.find(t=>t.trackingCode===e);if(t){f=t;break}}f||=u[0]}else f=u[0];if(!f)return a({type:`error`,code:`no_site`,message:`No sites exist; create one at app.zenovay.com or re-run interactively.`}),2;let p=f.trackingCode??f.id;if(d&&(d.recommendation===`no-op`||d.foundTrackingCodes.includes(p)))return a({type:`info`,message:`Zenovay already installed correctly for ${f.name} (${p})`}),a({type:`done`,command:`init`,exitCode:0}),0;a({type:`info`,message:`Using site ${f.id} (${f.name}) trackingCode=${f.trackingCode??f.id}`});let m=f.trackingCode??f.id,h=await W(t.cwd,{[s.envVarName]:m});if(a({type:`info`,message:`env vars added: ${h.addedKeys.join(`,`)}`}),s.id===`plain-html`){let e=await Ut({cwd:t.cwd,trackingCode:m,updateOnly:d?.recommendation===`update-tracking-code`});if(e.installed.length===0&&e.skipped.length===0)return a({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:s.id}}),1;a({type:`info`,message:`tracker injected into ${e.installed.length} file(s); ${e.skipped.length} already current; ${e.errors.length} error(s)`})}else return a({type:`error`,code:`headless_framework_unsupported`,message:`Headless install can only auto-inject the tracker for plain-HTML projects. For ${s.displayName}, run \`zenovay init\` interactively — the AI wizard places the <Script> in the correct entry file. (The env var ${h.addedKeys.join(`, `)||s.envVarName} was written.)`}),r?.emit(`install.error`,{error_code:`headless_framework_unsupported`,properties:{mode:`headless`,framework:s.id}}),1;return a({type:`done`,command:`init`,exitCode:0}),r?.emit(`install.success`,{properties:{framework:s.id,mode:`headless`,env_keys_added:h.addedKeys.length}}),0}catch(e){return a({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 yn=({opts:t,onExit:r})=>{let{exit:a}=te(),{theme:o}=m(),[s,c]=M(`intro`),[l,d]=M(null),[h,g]=M([]),[_,y]=M(null),[b,x]=M(null),[S,C]=M(null),[w,T]=M([]),[ee,k]=M(void 0),[N,F]=M(null),[re,I]=M(null),[ie,ae]=M(0),[oe,se]=M(!1),[L,R]=M(null),B=ne(null),ce=ne(!1);return O((e,t)=>{s===`error`&&(e.toLowerCase()===`q`||t.escape)&&(a(),r(1))}),j(()=>(process.stdout.isTTY&&process.stdout.write(`\x1B[?1049h\x1B[H`),()=>{B.current?.abort(),process.stdout.isTTY&&process.stdout.write(`\x1B[?1049l`)}),[]),j(()=>{ce.current||(ce.current=!0,(async()=>{try{c(`detecting`);let r=await _t(t.cwd);if(!r){C(`Could not detect your framework. Supported: Next.js, Nuxt, SvelteKit, Astro, Remix, plain HTML.`),c(`error`);return}d(r);let a=await i({strict:!1});!process.env.ZENOVAY_API_TOKEN&&!a&&(c(`login`),await u({cliVersion:t.cliVersion,offerCompletions:!1})),c(`loading-sites`);let o=await e(),s=await i({strict:!1}),l=new n({config:o,cliVersion:t.cliVersion,token:s}),[f,p]=await Promise.all([l.getSites(),z(t.cwd,``).catch(()=>null)]),m=await In(t.cwd);if(g(f),y(m),f.length===0){c(`create-site`);return}if(p?.foundTrackingCodes.length)for(let e of p.foundTrackingCodes){let t=f.find(t=>t.trackingCode===e);if(t){x(t),c(`already-installed`);return}}if(t.siteId){let e=f.find(e=>e.id===t.siteId);if(!e){C(`Site ${t.siteId} not found in your account.`),c(`error`);return}x(e),bn(e,r,t,{setPhase:c,setErrorMsg:C,setTasks:T,setLiveLine:k,setSandboxStats:F,setVerifyResult:I,setPendingApproval:R,registerBridge:e=>{B.current=e}});return}let h=Ln(f,m);if(t.yes&&h){x(h),bn(h,r,t,{setPhase:c,setErrorMsg:C,setTasks:T,setLiveLine:k,setSandboxStats:F,setVerifyResult:I,setPendingApproval:R,registerBridge:e=>{B.current=e}});return}c(`site-picker`)}catch(e){C(e.message),c(`error`)}})())},[]),j(()=>{s===`error`&&(B.current?.abort(),setTimeout(()=>{a(),r(1)},8e3))},[s]),A.createElement(E,{flexDirection:`column`},A.createElement(f,{version:t.cliVersion,subtitle:`AI install wizard`}),s===`intro`&&A.createElement(xn,null),s===`detecting`&&A.createElement(p,{title:`Scanning`,state:`busy`},A.createElement(E,null,A.createElement(D,{color:o.accent},A.createElement(P,{type:`dots`})),A.createElement(D,null,` Detecting framework…`))),s===`login`&&A.createElement(p,{title:`Authenticating`,state:`busy`},A.createElement(D,null,`Opening browser for login… (paste ZENOVAY_API_TOKEN env var to skip)`)),s===`loading-sites`&&A.createElement(p,{title:`Loading your sites`,state:`busy`},A.createElement(E,null,A.createElement(D,{color:o.accent},A.createElement(P,{type:`dots`})),A.createElement(D,null,` Fetching your Zenovay sites…`))),s===`already-installed`&&b&&A.createElement(Cn,{site:b,onContinue:()=>{c(`site-picker`)},onExit:()=>{a(),r(0,`quit`,b)}}),s===`site-picker`&&l&&A.createElement(wn,{sites:h,preselectHint:_,onPick:e=>{if(e===`create-new`){c(`create-site`);return}x(e),bn(e,l,t,{setPhase:c,setErrorMsg:C,setTasks:T,setLiveLine:k,setSandboxStats:F,setVerifyResult:I,setPendingApproval:R,registerBridge:e=>{B.current=e}})}}),s===`create-site`&&A.createElement(p,{title:`Create a new site`,state:`warn`},A.createElement(D,{color:o.warn},"No site picked (or none exist yet). Visit https://app.zenovay.com/websites to create one, then re-run `zenovay init`."),A.createElement(D,{color:o.muted},`(Inline site creation from the CLI is scheduled for V1.1 — it requires a plan-limit check.)`)),s===`agent`&&l&&b&&A.createElement(Sn,{adapter:l,site:b,tasks:w,liveLine:ee,pendingApproval:L,onApprove:e=>{L&&B.current?.resolve(L.id,e)}}),s===`install-complete`&&l&&b&&A.createElement(Dn,{adapter:l,site:b,stats:N,verify:re,onCommit:()=>c(`commit-prompt`),onSkipCommit:()=>c(`deploy-prompt`)}),s===`commit-prompt`&&b&&A.createElement(On,{cwd:t.cwd,onDone:e=>{e.committed&&k(`Pushed ${e.shortSha} to ${e.branch}`),c(`deploy-prompt`)},onError:e=>{C(e),c(`error`)}}),s===`deploy-prompt`&&b&&A.createElement(kn,{site:b,onDeployed:()=>c(`visit-prompt`),onSkip:()=>c(`verify`)}),s===`visit-prompt`&&b&&A.createElement(An,{site:b,onContinue:()=>c(`verify`)}),s===`verify`&&b&&A.createElement(Mn,{site:b,elapsed:ie,onTick:e=>ae(e),onArrived:()=>{se(!0),c(`success`)},onTimeout:()=>c(`success`)}),s===`success`&&l&&b&&A.createElement(En,{adapter:l,site:b,stats:N,arrived:oe,onPick:e=>{a(),r(0,e,b)}}),s===`error`&&A.createElement(p,{title:`Install failed`,state:`err`},A.createElement(D,{color:o.error},S??`Unknown error`)),A.createElement(v,{items:s===`already-installed`?[{key:`q`,label:`quit`},{key:`r`,label:`re-run wizard`},{key:`ctrl-c`,label:`abort`}]:[{key:`q`,label:`quit`},{key:`ctrl-c`,label:`abort`}]}))};async function Z(e,t,n){n.setLiveLine(`Verifying the tracker is in your source…`);try{let r=await z(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 bn(r,a,o,s){try{s.setPhase(`agent`);let c=await e(),l=await i({strict:!1}),u=new n({config:c,cliVersion:o.cliVersion,token:l}),d=new he({cwd:o.cwd}),f=r.trackingCode??r.id;await t({defaultSiteId:r.id,defaultSiteName:r.name}).catch(()=>void 0);let p=await z(o.cwd,f);if(p.recommendation===`no-op`){s.setTasks(e=>e.map(e=>e.id===`detect`||e.id===`read`||e.id===`write`?{...e,status:`done`,detail:`already installed correctly`}:e)),s.setLiveLine(p.summary),s.setSandboxStats?.({reads:0,writes:0,rounds:0}),!o.skipMcp&&l&&await G({accessToken:l.accessToken}).catch(()=>void 0),s.setVerifyResult?.({ok:!0,detail:`Already installed correctly`}),s.setPhase(`install-complete`);return}if(p.competitors.length>0&&s.setLiveLine(`Detected ${p.competitors.map(e=>e.name).join(`, `)} — will install Zenovay alongside (won't touch their tags).`),a.id===`next-app-router`){s.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 (Cursor/Claude/VS Code)`,status:`pending`},{id:`verify`,label:`Verify the tracker in your source`,status:`pending`}]),s.setLiveLine(`Next.js — locating the document shell layout…`);let e=await Yt({cwd:o.cwd,trackingCode:f});if(!e.fellThrough&&e.errors.length===0){let t=e.installed[0]??`already installed`;s.setTasks(e=>e.map(e=>e.id===`read`||e.id===`write`?{...e,status:`done`,detail:t}:e));let n=await W(o.cwd,{[a.envVarName]:f});if(s.setTasks(e=>e.map(e=>e.id===`env`?{...e,status:`done`,detail:`${n.addedKeys.length} key(s) added`}:e)),!o.skipMcp&&l){let e=await G({accessToken:l.accessToken}).catch(()=>null);s.setTasks(t=>t.map(t=>t.id===`mcp`?{...t,status:`done`,detail:e&&e.installed.length>0?e.installed.join(`, `):`none detected`}:t))}else s.setTasks(e=>e.map(e=>e.id===`mcp`?{...e,status:`done`,detail:`skipped`}:e));await Z(o.cwd,f,s),s.setTasks(e=>e.map(e=>e.id===`verify`?{...e,status:`done`}:e)),s.setSandboxStats?.({reads:1,writes:e.installed.length,rounds:0}),s.setPhase(`install-complete`);return}s.setLiveLine(`Custom Next.js structure — handing off to the AI agent…`)}let m=a.id===`plain-html`;if(m){s.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 (Cursor/Claude/VS Code)`,status:`pending`},{id:`verify`,label:`Verify the tracker in your source`,status:`pending`}]),s.setLiveLine(`Plain HTML — using fast install path (no AI needed)…`);let e=await Ut({cwd:o.cwd,trackingCode:f,updateOnly:p.recommendation===`update-tracking-code`});if(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}`);s.setTasks(t=>t.map(t=>t.id===`read`||t.id===`write`?{...t,status:`done`,detail:`${e.installed.length} file(s)`}:t)),s.setLiveLine(`Tracker added to ${e.installed.length} file(s). Skipped ${e.skipped.length}, errored ${e.errors.length}.`);let t=await W(o.cwd,{[a.envVarName]:f});if(s.setTasks(e=>e.map(e=>e.id===`env`?{...e,status:`done`,detail:`${t.addedKeys.length} key(s) added`}:e)),!o.skipMcp&&l){let e=await G({accessToken:l.accessToken}).catch(()=>null);s.setTasks(t=>t.map(t=>t.id===`mcp`?{...t,status:`done`,detail:e&&e.installed.length>0?e.installed.join(`, `):`none detected`}:t))}else s.setTasks(e=>e.map(e=>e.id===`mcp`?{...e,status:`done`,detail:`skipped`}:e));await Z(o.cwd,f,s),s.setSandboxStats?.({reads:e.installed.length,writes:e.installed.length,rounds:0}),s.setPhase(`install-complete`);return}{let e=await Zt({cwd:o.cwd,trackingCode:f,siteId:r.id,adapter:a}),t=e.skipped.some(e=>/already present/.test(e.reason));if(!e.fellThrough&&e.errors.length===0&&(e.installed.length>0||t)){s.setTasks([{id:`detect`,label:`Detect framework`,status:`done`,detail:a.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 (Cursor/Claude/VS Code)`,status:`pending`},{id:`verify`,label:`Verify the tracker in your source`,status:`pending`}]),s.setLiveLine(`${a.displayName} — using fast install path (no AI needed)…`);let t=await W(o.cwd,{[a.envVarName]:f});if(s.setTasks(e=>e.map(e=>e.id===`env`?{...e,status:`done`,detail:`${t.addedKeys.length} key(s) added`}:e)),!o.skipMcp&&l){let e=await G({accessToken:l.accessToken}).catch(()=>null);s.setTasks(t=>t.map(t=>t.id===`mcp`?{...t,status:`done`,detail:e&&e.installed.length>0?e.installed.join(`, `):`none detected`}:t))}else s.setTasks(e=>e.map(e=>e.id===`mcp`?{...e,status:`done`,detail:`skipped`}:e));await Z(o.cwd,f,s),s.setTasks(e=>e.map(e=>e.id===`verify`?{...e,status:`done`}:e)),s.setSandboxStats?.({reads:1,writes:e.installed.length,rounds:0}),s.setPhase(`install-complete`);return}s.setLiveLine(`${a.displayName} — handing off to the AI agent…`)}let h=a.buildSnippets({trackingCode:f,siteId:r.id}),g=`Install Zenovay tracking into this ${a.displayName} project.\nSite: ${r.name} (trackingCode: ${f}).\n1. Call detect_framework to confirm the framework.\n2. Read the entry file(s) for this framework:\n`+a.files.map(e=>` - ${e.path}`).join(`
|
|
97
|
+
`)+`
|
|
98
|
+
3. Insert the tracker using the snippet below.
|
|
99
|
+
4. Confirm the change with a diff before writing.
|
|
100
|
+
|
|
101
|
+
Snippet reference (anchored by anchorKind — adapt to the actual file):
|
|
102
|
+
`+h.map(e=>` ${e.anchorKind} @ ${e.targetPath}:\n ${e.code.replace(/\n/g,`
|
|
103
|
+
`)}`).join(`
|
|
104
|
+
|
|
105
|
+
`);s.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 (Cursor/Claude/VS Code)`,status:`pending`},{id:`verify`,label:`Wait for first event`,status:`pending`}]);let _=(e,t,n)=>{s.setTasks(r=>r.map(r=>r.id===e?{...r,status:t,detail:n??r.detail}:r))},v=on({mode:an(o)});s.registerBridge(v);let y=v.subscribe(e=>s.setPendingApproval(e)),b=null;try{await Bt({api:u,sandbox:d,approval:v,prompter:{async ask({question:e}){return e}},handlers:{onToolStart:({name:e})=>{e===`detect_framework`?(_(`detect`,`active`),s.setLiveLine(`Inspecting package.json + config files…`)):e===`read_file`?(_(`detect`,`done`),_(`read`,`active`)):(e===`write_file`||e===`patch_file`)&&(_(`read`,`done`),_(`write`,`active`))},onToolResult:({name:e,result:t})=>{let n=t?.ok!==!1,r=t?.content??{};e===`detect_framework`&&n&&(_(`detect`,`done`,a.displayName),s.setLiveLine(`Detected ${a.displayName}`)),e===`read_file`&&n&&r.path&&s.setLiveLine(`Read ${r.path}`),(e===`write_file`||e===`patch_file`)&&n&&r.path&&(_(`read`,`done`),_(`write`,`done`,`wrote ${r.path}`),s.setLiveLine(`Wrote ${r.path}`))},onDelta:e=>{let t=e.replace(/\s+/g,` `).trim();t.length>4&&s.setLiveLine(t.slice(0,80))}},initialMessages:[{role:`user`,content:g}],diagnosis:p,targetTrackingCode:f})}catch(e){b=e}finally{y(),s.setPendingApproval(null)}let x=d.stats();if(x.writes===0){let e=b?`Agent error: ${b.message}`:`Agent returned without writing any files (${x.reads} reads, ${x.rounds} rounds). The model may have refused or the AI Gateway may be misconfigured. Check api.zenovay.com logs.`;throw Error(e)}let S=a.files.map(e=>e.path),C=x.writtenPaths.some(e=>S.some(t=>e===t||e.endsWith(`/${t}`)));if(!C)throw Error(`Agent wrote to: [${x.writtenPaths.join(`, `)}] but never modified the framework's tracker target file(s): [${S.join(`, `)}]. The tracker is NOT installed. The model likely put the trackingCode into .env.local instead of into the HTML/JSX entry file.`);_(`write`,`done`),_(`env`,`active`),s.setLiveLine(`Adding env var to .env.local`);let w=await W(o.cwd,{[a.envVarName]:f});if(_(`env`,`done`,`${w.addedKeys.length} key(s) added`),!o.skipMcp&&l){_(`mcp`,`active`),s.setLiveLine(`Detecting Cursor / Claude Desktop / VS Code…`);let e=await G({accessToken:l.accessToken}).catch(()=>null);e&&e.installed.length>0?_(`mcp`,`done`,e.installed.join(`, `)):_(`mcp`,`done`,`none detected`)}else _(`mcp`,`done`,`skipped`);s.setTasks(e=>e.map(e=>e.id===`detect`||e.id===`read`||e.id===`write`?{...e,status:e.status===`pending`?`done`:e.status}:e)),await Z(o.cwd,f,s),s.setSandboxStats?.(x),s.setPhase(`install-complete`)}catch(e){s.setErrorMsg(e.message),s.setPhase(`error`)}}const xn=()=>{let{theme:e}=m();return A.createElement(p,{title:`Zenovay wants to set up your project`,state:`idle`},A.createElement(D,null,`We'll use AI to analyze your codebase and add the Zenovay tracker.`),A.createElement(D,{color:e.muted},`.env* contents stay on your machine. Only framework metadata reaches api.zenovay.com.`))},Sn=({adapter:e,site:t,tasks:n,liveLine:r,pendingApproval:i,onApprove:a})=>{let{theme:o}=m(),s=process.stdout.columns??100,c=(process.stdout.rows??30)-8,l=Math.floor(s/2)-1,u=Math.max(14,c);return A.createElement(E,{flexDirection:`column`},A.createElement(E,{flexDirection:`row`,minHeight:u,borderStyle:`round`,borderColor:o.border},A.createElement(E,{width:l,flexDirection:`column`},A.createElement(pn,{width:l,height:u})),A.createElement(E,{width:1,flexDirection:`column`},A.createElement(D,{color:o.border},`│`)),A.createElement(E,{width:l,flexDirection:`column`},i?A.createElement(E,{flexDirection:`column`,paddingX:2,paddingTop:1},A.createElement(D,{color:o.warn},`The agent wants to write `,i.path),i.reason?A.createElement(D,{color:o.muted},i.reason):null,A.createElement(h,{key:i.id,filePath:i.path,oldContent:i.oldContent,newContent:i.newContent,onApprove:a})):A.createElement(A.Fragment,null,A.createElement(E,{paddingX:2,paddingTop:1},A.createElement(g,{done:n.filter(e=>e.status===`done`).length,total:n.length,label:n.find(e=>e.status===`active`)?.label})),A.createElement(gn,{tasks:n,liveLine:r,width:l,height:u})))),A.createElement(E,{marginTop:1},A.createElement(D,{color:o.muted},`Site: `,t.name,` · code: `,t.trackingCode??t.id,` · Framework: `,e.displayName)))},Cn=({site:e,onContinue:t,onExit:n})=>{let{theme:r}=m();O((e,r)=>{if(e===`q`||r.escape){n();return}if(e===`r`||e===`R`){t();return}});let i=e.url.replace(/^https?:\/\//,``).replace(/\/$/,``);return A.createElement(p,{title:`Already installed`,state:`ok`},A.createElement(E,{flexDirection:`column`,gap:1},A.createElement(E,{flexDirection:`row`,gap:1},A.createElement(D,{color:r.success},`✓`),A.createElement(D,{bold:!0},e.name),A.createElement(D,{color:r.muted},`(`,i,`)`)),A.createElement(D,{color:r.muted},`Zenovay is already tracking this project. No changes needed.`),e.trackingCode?A.createElement(D,{color:r.dim},`tracking code: `,e.trackingCode):null))},wn=({sites:e,preselectHint:t,onPick:n})=>{let r=Ln(e,t),i=e.filter(e=>e.id!==r?.id),a=r?[r,...i]:i,o=[...a.map(e=>({label:Fn(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 A.createElement(p,{title:t?`Pick a site (best match: ${t})`:`Pick a site`,state:`idle`},A.createElement(_,{items:o,onSelect:n}))};function Tn(){let e=process.argv[1]??``;return e.includes(`/_npx/`)||e.includes(`\\_npx\\`)||process.env.npm_execpath?.includes(`npx`)?`npx`:`global`}const Q=({k:e,primary:t})=>{let{theme:n}=m();return A.createElement(D,null,A.createElement(D,{color:n.muted},`[`),A.createElement(D,{bold:!0,color:t?n.accent:n.fg},e),A.createElement(D,{color:n.muted},`] `))},En=({adapter:e,site:t,stats:n,arrived:i,onPick:a})=>{let{theme:o}=m(),c=Tn(),l=c===`npx`?`npx @zenovay/cli`:`zenovay`,u=r(t),d=n&&n.rounds>0?`${n.writes} file(s) · ${n.rounds} agent round(s)`:n&&n.writes>0?`${n.writes} file(s) · programmatic (no AI calls)`:null;return O((e,t)=>{let n=e.toLowerCase();n===`w`||t.return?a(`watch`):n===`o`?s(u).catch(()=>void 0):n===`e`?a(`events`):(n===`s`||n===`q`||t.escape)&&a(`quit`)},{isActive:!0}),A.createElement(p,{title:`You're live on Zenovay`,state:`ok`},A.createElement(D,{bold:!0,color:o.success},i?`✓ First event received from ${t.name}`:`✓ Installed successfully`),A.createElement(D,{color:o.accent},`─`.repeat(18)),A.createElement(E,{marginTop:1,flexDirection:`column`},A.createElement(Y,{label:`Framework`,value:e.displayName}),A.createElement(Y,{label:`Site`,value:A.createElement(J,{url:t.url,label:t.name})}),t.trackingCode?A.createElement(Y,{label:`Tracker`,value:A.createElement(D,{color:o.muted},t.trackingCode)}):null,d?A.createElement(Y,{label:`Changes`,value:A.createElement(D,{color:o.muted},d)}):null,A.createElement(Y,{label:`Dashboard`,value:A.createElement(J,{url:u})})),A.createElement(E,{marginTop:1,flexDirection:`column`},A.createElement(D,{color:o.dim},`WHAT'S NEXT`),A.createElement(E,{marginTop:1},A.createElement(D,null,` `),A.createElement(Q,{k:`W`,primary:!0}),A.createElement(D,null,`Watch live in this terminal `),A.createElement(D,{color:o.muted},`— visitors, pages, sources, vitals`)),A.createElement(E,null,A.createElement(D,null,` `),A.createElement(Q,{k:`O`}),A.createElement(D,null,`Open the dashboard in your browser`)),A.createElement(E,null,A.createElement(D,null,` `),A.createElement(Q,{k:`E`}),A.createElement(D,null,`Stream events as they fire `),A.createElement(D,{color:o.muted},`— page views, custom events, live`)),A.createElement(E,null,A.createElement(D,null,` `),A.createElement(Q,{k:`S`}),A.createElement(D,null,`Exit to shell`))),c===`npx`?A.createElement(E,{marginTop:1,flexDirection:`column`,borderStyle:`single`,borderColor:o.warn,paddingX:1},A.createElement(D,{color:o.warn,bold:!0},`Heads up — you ran via npx`),A.createElement(D,{color:o.muted},"The `zenovay` command isn't on your PATH yet. After you exit, run:"),A.createElement(E,{marginTop:1},A.createElement(D,{color:o.fg},` npm i -g @zenovay/cli `),A.createElement(D,{color:o.muted},"→ then `zenovay overview` works directly"))):A.createElement(E,{marginTop:1},A.createElement(D,{color:o.muted},`From your shell: `),A.createElement(D,{color:o.fg},l,` overview`),A.createElement(D,{color:o.muted},` · `),A.createElement(D,{color:o.fg},l,` --help`)))},Dn=({adapter:e,site:t,stats:n,verify:r,onCommit:i,onSkipCommit:a})=>{let{theme:o}=m();return Nn(e=>{e===`y`||e===`Y`||e===`\r`?i():(e===`n`||e===`N`||e===`s`||e===`S`)&&a()}),A.createElement(p,{title:`Tracker installed`,state:r&&!r.ok?`warn`:`ok`},r?A.createElement(D,null,A.createElement(D,{color:r.ok?o.success:o.warn},r.ok?`✔ Verified — `:`⚠ `),r.detail):A.createElement(D,null,A.createElement(D,{color:o.success},`✔ `),`The Zenovay tracker is in your project.`),A.createElement(E,{marginTop:1},A.createElement(D,{color:o.muted},`Framework: `),A.createElement(D,null,e.displayName)),A.createElement(E,null,A.createElement(D,{color:o.muted},`Site: `),A.createElement(D,null,t.name,` (`,t.url,`)`)),n&&A.createElement(E,null,A.createElement(D,{color:o.muted},`Modified: `),A.createElement(D,null,n.writes,` file(s)`)),A.createElement(E,{marginTop:1},A.createElement(D,null,`Commit + push these changes to git? `),A.createElement(D,{color:o.accent},`[Y/n]`)))},On=({cwd:e,onDone:t,onError:n})=>{let{theme:r}=m(),[i,a]=M(`committing`),[o,s]=M(`Staging changes…`);return j(()=>{(async()=>{try{let n=await Pn(e,e=>s(e),e=>a(e));n.committed?s(`Pushed ${n.shortSha} to origin/${n.branch}`):s(`No changes to commit (already up-to-date).`),setTimeout(()=>t(n),800)}catch(e){n(e.message)}})()},[]),A.createElement(p,{title:`Committing to git`,state:`busy`},A.createElement(E,null,A.createElement(D,{color:r.accent},A.createElement(P,{type:`dots`})),A.createElement(D,null,` `,i===`pushing`?`Pushing to origin`:`Committing`,`…`)),A.createElement(E,{marginTop:1},A.createElement(D,{color:r.muted},o)))},kn=({site:e,onDeployed:t,onSkip:n})=>{let{theme:r}=m();return Nn(e=>{e===`y`||e===`Y`||e===`\r`||e===`d`||e===`D`?t():(e===`n`||e===`N`||e===`s`||e===`S`)&&n()}),A.createElement(p,{title:`Ready to deploy?`,state:`idle`},A.createElement(D,null,`The tracker is installed locally. To capture events you need it on the live site:`),A.createElement(D,null,` `),A.createElement(E,null,A.createElement(D,{color:r.muted},` → `),A.createElement(J,{url:e.url})),A.createElement(D,null,` `),A.createElement(D,{color:r.muted},`Push the change through your normal deploy pipeline (Vercel auto-deploy, CI/CD, etc.).`),A.createElement(E,{marginTop:1},A.createElement(D,null,`Once it's deployed, press `),A.createElement(D,{color:r.accent},`[Y]`),A.createElement(D,null,` to verify the tracker is firing. `),A.createElement(D,{color:r.muted},`[s] skip verification`)))},An=({site:e,onContinue:t})=>{let{theme:n}=m();return Nn(()=>t()),A.createElement(p,{title:`Visit your site`,state:`idle`},A.createElement(D,null,`To send a test event, open any page on your site:`),A.createElement(D,null,` `),A.createElement(E,null,A.createElement(D,{color:n.muted},` → `),A.createElement(J,{url:e.url})),A.createElement(D,null,` `),A.createElement(D,{color:n.muted},`The tracker fires automatically on page load. We'll verify the next event arrives.`),A.createElement(E,{marginTop:1},A.createElement(D,null,`Press `),A.createElement(D,{color:n.accent},`[any key]`),A.createElement(D,null,` when you've visited the page.`)))};async function jn(e,t){try{let n=await fetch(e,{headers:{"User-Agent":`zenovay-cli/preflight`},signal:AbortSignal.timeout(8e3),redirect:`follow`});if(!n.ok)return{state:`tracker-missing`,httpStatus:n.status};let r=await n.text(),i=/<script[^>]*src\s*=\s*["']https:\/\/(?:api|cdn)\.zenovay\.com\/[^"']+["'][^>]*>\s*<\/script>/gi,a=/data-id\s*=\s*["'](ZV_[A-Za-z0-9]+)["']/i,o=r.match(i)??[];if(o.length===0)return{state:`tracker-missing`};let s=Array.from(new Set(o.map(e=>e.match(a)?.[1]).filter(e=>!!e)));return s.includes(t)?{state:`tracker-correct`}:{state:`tracker-wrong-id`,foundCodes:s}}catch(e){return{state:`tracker-missing`,networkError:e.message}}}const Mn=({site:t,elapsed:r,onTick:a,onArrived:o,onTimeout:s})=>{let{theme:c}=m(),[l,u]=M(`preflight`),[d,f]=M(``),[h,g]=M([]),_=ne(!1),v=t.trackingCode??t.id,y=async()=>{u(`preflight`),f(`Fetching ${t.url}…`);let e=await jn(t.url,v);if(!_.current){if(e.state===`tracker-correct`){u(`polling`),f(`Tracker detected on live site — waiting for first hit…`),b();return}if(e.state===`tracker-wrong-id`){u(`wrong-id-on-live`),g(e.foundCodes),f(`Live site has Zenovay but with id(s): ${e.foundCodes.join(`, `)}`);return}u(`awaiting-deploy`),f(e.networkError?`Couldn't reach ${t.url}: ${e.networkError}`:e.httpStatus?`${t.url} returned HTTP ${e.httpStatus}`:`No Zenovay tracker found on ${t.url}.`)}},b=async()=>{let r=Date.now()-10*60*1e3;try{let s=await e(),c=await i({strict:!1}),l=new n({config:s,cliVersion:`0`,token:c}),d=await kt(t.id,r,{api:l,timeoutMs:6e4,pollIntervalMs:2500,onTick:e=>{_.current||a(e)}});if(_.current)return;d.received?(u(`success`),o()):u(`timeout`)}catch{_.current||u(`timeout`)}};j(()=>(_.current=!1,y(),()=>{_.current=!0}),[]),O(e=>{(l===`awaiting-deploy`||l===`wrong-id-on-live`||l===`timeout`)&&(e===`r`||e===`R`?y():(e===`s`||e===`S`)&&s())},{isActive:!0});let x=Math.floor(r/1e3);return l===`preflight`?A.createElement(p,{title:`Verifying`,state:`busy`},A.createElement(E,null,A.createElement(D,{color:c.accent},A.createElement(P,{type:`dots`})),A.createElement(D,null,` Checking your live site for the tracker…`)),A.createElement(E,{marginTop:1},A.createElement(D,{color:c.muted},d))):l===`awaiting-deploy`?A.createElement(p,{title:`Tracker not yet on your live site`,state:`warn`},A.createElement(D,{color:c.warn},d),A.createElement(E,{marginTop:1,flexDirection:`column`},A.createElement(D,null,`The tracker is in your local repo but hasn't been deployed yet.`),A.createElement(D,{color:c.muted},`Push your changes and wait for your deploy to finish (Vercel / Cloudflare Pages / CI), then retry.`)),A.createElement(E,{marginTop:1},A.createElement(D,null,`Press `),A.createElement(D,{color:c.accent},`[r]`),A.createElement(D,null,` to re-check, `),A.createElement(D,{color:c.accent},`[s]`),A.createElement(D,null,` to skip verification.`))):l===`wrong-id-on-live`?A.createElement(p,{title:`Live site has a different tracking code`,state:`warn`},A.createElement(D,{color:c.warn},`Expected: `,A.createElement(D,{color:c.accent},v),` `,`Found on live: `,A.createElement(D,{color:c.accent},h.join(`, `))),A.createElement(E,{marginTop:1,flexDirection:`column`},A.createElement(D,null,`Your local install uses a different ID than what's on `,t.url,`.`),A.createElement(D,{color:c.muted},`Deploy the new local version, then retry — or skip if the existing ID is intentional.`)),A.createElement(E,{marginTop:1},A.createElement(D,null,`Press `),A.createElement(D,{color:c.accent},`[r]`),A.createElement(D,null,` to re-check, `),A.createElement(D,{color:c.accent},`[s]`),A.createElement(D,null,` to skip.`))):l===`timeout`?A.createElement(p,{title:`No event arrived in 3 minutes`,state:`warn`},A.createElement(D,{color:c.warn},`The tracker is on your live site but no hits reached api.zenovay.com.`),A.createElement(E,{marginTop:1},A.createElement(D,{color:c.muted},`Try opening `,t.url,` in a fresh browser tab (no ad-blocker), then retry.`)),A.createElement(E,{marginTop:1},A.createElement(D,null,`Press `),A.createElement(D,{color:c.accent},`[r]`),A.createElement(D,null,` to re-check, `),A.createElement(D,{color:c.accent},`[s]`),A.createElement(D,null,` to finish without verification.`))):A.createElement(p,{title:`Waiting for first event`,state:`busy`},A.createElement(E,null,A.createElement(D,{color:c.accent},A.createElement(P,{type:`dots`})),A.createElement(D,null,` Polling api.zenovay.com for the first hit on `),A.createElement(D,{color:c.accent},t.url),A.createElement(D,null,` (`,x,`s elapsed)`)),A.createElement(E,{marginTop:1},A.createElement(D,{color:c.muted},`Reload the page if nothing arrives within ~30 seconds.`)))};function Nn(e){O((t,n)=>{e(t,{return:n.return,escape:n.escape})},{isActive:!0})}async function Pn(e,t,n){let{execFile:r}=await import(`node:child_process`),{promisify:i}=await import(`node:util`),a=i(r),o=async(t,n)=>{let{stdout:r}=await a(t,n,{cwd:e,maxBuffer:4e6});return r.trim()};try{await o(`git`,[`rev-parse`,`--is-inside-work-tree`])}catch{return t(`Not a git repository — skipped.`),{committed:!1}}let s=await o(`git`,[`status`,`--porcelain`]);if(!s)return{committed:!1};t(`Staging tracker changes…`),await o(`git`,[`add`,`-A`]),t(`Creating commit…`),await o(`git`,[`commit`,`-m`,`chore(zenovay): install tracking script via @zenovay/cli`]);let c=await o(`git`,[`rev-parse`,`--short`,`HEAD`]),l=await o(`git`,[`rev-parse`,`--abbrev-ref`,`HEAD`]);n(`pushing`),t(`Pushing to origin/${l}…`);try{await o(`git`,[`push`,`origin`,l])}catch(e){return t(`Commit ${c} created locally; push failed (${e.message.slice(0,80)}). Push manually with: git push origin ${l}`),{committed:!0,shortSha:c,branch:l}}return n(`done`),{committed:!0,shortSha:c,branch:l}}function Fn(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 In(e){try{let t=await x.readFile(b.join(e,`package.json`),`utf8`),n=JSON.parse(t);if(n.name)return String(n.name).replace(/^@[^/]+\//,``)}catch{}try{let t=await x.readFile(b.join(e,`.git`,`config`),`utf8`),n=t.match(/url\s*=\s*.*[/:]([^/]+?)(?:\.git)?\s*$/m);if(n&&n[1])return n[1]}catch{}return b.basename(e)}function Ln(e,t){if(!t||e.length===0)return e[0]??null;let n=$(t),r=e.find(e=>$(e.name)===n);if(r)return r;let i=e.find(e=>{let t=e.url.replace(/^https?:\/\//,``).replace(/\/.*$/,``),[r]=t.split(`.`);return $(r??``)===n});if(i)return i;let a=e.find(e=>{let t=$(e.name),r=$(e.url);return t.includes(n)||r.includes(n)||n.includes(t)||n.includes(r)});return a??e[0]??null}function $(e){return e.toLowerCase().replace(/[^a-z0-9]/g,``)}export{ce as detectInstalled,_n as initCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./config-JVhBplSX.js";import"./api-CdcB84ie.js";import"./token-store-BvSCse1t.js";import{initCommand as e}from"./init-
|
|
1
|
+
import"./config-JVhBplSX.js";import"./api-CdcB84ie.js";import"./token-store-BvSCse1t.js";import{initCommand as e}from"./init-4u9IQ8h_.js";import"./formatter-C4YSOKuq.js";import"./emit-D4YlMlzk.js";import"./open-url-BtI5aLgL.js";import"./secrets-ApB7yh2A.js";import"./client-ntsEXSVC.js";import"./login-DU1fY88U.js";import"./theme-Brz9wK0w.js";import"./panel-CTtQ2ue6.js";import"./progress-row-Afnt5Ng8.js";import"./prompt-BXvg2B4R.js";import"./keybar-DO5OoZy9.js";import"./sparkline-CpoBjjlc.js";export{e as initCommand};
|
package/dist/wizard-bin.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import(`./init-
|
|
2
|
+
import(`./init-kKTNK6nn.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
package/dist/init-igNlvq0N.js
DELETED
|
@@ -1,105 +0,0 @@
|
|
|
1
|
-
import{readConfig as e,updateConfig as t}from"./config-JVhBplSX.js";import{ApiClient as n,dashboardUrlForSite as r}from"./api-CdcB84ie.js";import{readToken as i}from"./token-store-BvSCse1t.js";import{emit$1 as a,isHeadless as o}from"./emit-D4YlMlzk.js";import{openInBrowser as s}from"./open-url-BtI5aLgL.js";import{scrubSecrets as c}from"./secrets-ApB7yh2A.js";import{parseSseStream as l}from"./client-ntsEXSVC.js";import{loginCommand as u,maybeInstallCompletions as d}from"./login-DU1fY88U.js";import{Banner as f,Panel as p,useTheme as m}from"./panel-CTtQ2ue6.js";import{DiffView as h,ProgressRow as g}from"./progress-row-Afnt5Ng8.js";import{Select as _}from"./prompt-BXvg2B4R.js";import{Keybar as v}from"./keybar-DO5OoZy9.js";import{spark as y}from"./sparkline-CpoBjjlc.js";import b from"node:path";import{promises as x}from"node:fs";import{z as S}from"zod";import C from"node:os";import w from"node:crypto";import{ulid as T}from"ulid";import{Box as E,Text as D,render as ee,useApp as te,useInput as O}from"ink";import k from"node:fs/promises";import A,{useEffect as j,useRef as ne,useState as M}from"react";import{globby as N}from"globby";import P from"ink-spinner";import{applyPatch as F}from"diff";const re=[`@zenovay/tracker`,`@zenovay/next`,`@zenovay/nuxt`,`@zenovay/svelte`,`@zenovay/astro`,`@zenovay/remix`,`@zenovay/node`],I=[`zenovay.config.ts`,`zenovay.config.js`,`zenovay.config.mjs`,`zenovay.config.json`],ie=/<[Ss]cript\b[^>]*\bsrc\s*=\s*["'`]https:\/\/(?:api|cdn)\.zenovay\.com\/[^"'`]+["'`][^>]*>/gi,ae=/["'`]https:\/\/(?:api|cdn)\.zenovay\.com\/[^"'`]*z\.js[^"'`]*["'`]/gi,oe=/["']?data-?[Ii]d["']?\s*[=:]\s*["'`](ZV_[A-Za-z0-9]+)["'`]/i,se=/data-zenovay-site\s*[=:]\s*["'`]([^"'`]+)["'`]/i,L=/\binit\s*\(\s*['"`](ZV_[A-Za-z0-9]+)['"`]/g,R=[{name:`PostHog`,patterns:[/posthog\.com\b/i,/posthog-js/,/window\.posthog/]},{name:`Plausible`,patterns:[/plausible\.io\/js/i,/window\.plausible/]},{name:`Google Analytics`,patterns:[/googletagmanager\.com\/gtag\/js/i,/www\.google-analytics\.com\/analytics\.js/i,/window\.gtag\b/]},{name:`Mixpanel`,patterns:[/cdn\.mxpnl\.com/i,/mixpanel-browser/]},{name:`Segment`,patterns:[/cdn\.segment\.com\/analytics\.js/i,/window\.analytics\b/]},{name:`Hotjar`,patterns:[/static\.hotjar\.com/i,/\(h,o,t,j,a,r\)/i]},{name:`Amplitude`,patterns:[/cdn\.amplitude\.com/i,/amplitude\.getInstance/]},{name:`Heap`,patterns:[/cdn\.heapanalytics\.com/i]},{name:`FullStory`,patterns:[/fullstory\.com\/s\/fs\.js/i,/window\.FS\.identify/]}];async function z(e,t){let n={zenovayInstalled:!1,correctTrackingCode:!1,foundTrackingCodes:[],zenovayFiles:[],competitors:[],summary:``,recommendation:`fresh-install`};try{let t=await x.readFile(b.join(e,`package.json`),`utf8`),r=JSON.parse(t),i={...r.dependencies,...r.devDependencies};for(let e of re)if(e in i){n.zenovayInstalled=!0,n.packageMarker=e;break}}catch{}for(let t of I)try{await x.access(b.join(e,t)),n.zenovayInstalled=!0,n.configFile=t;break}catch{}let r=await N([`**/*.{html,htm,tsx,jsx,vue,svelte,astro,ts,js,mjs}`,`!node_modules/**`,`!.git/**`,`!dist/**`,`!.next/**`,`!.nuxt/**`,`!build/**`,`!.output/**`],{cwd:e,gitignore:!0,deep:4,absolute:!0}).catch(()=>[]),i=new Map,a=new Set;for(let t of r.slice(0,300)){let r;try{r=await x.readFile(t,`utf8`)}catch{continue}let o=b.relative(e,t);ie.lastIndex=0,ae.lastIndex=0;let s=r.match(ie),c=r.match(ae),l=(s?.length??0)+(c?.length??0);if(l>0){n.zenovayInstalled=!0;let e=(s?.[0]??c?.[0]??``).slice(0,200),t=r.match(oe)??r.match(se),i=t?.[1]??null;i&&a.add(i),n.zenovayFiles.push({file:o,currentTrackingCode:i,scriptTagCount:l,matchSample:e})}if(l===0&&/\.[jt]sx?$/.test(t)){L.lastIndex=0;let e;for(;(e=L.exec(r))!==null;){let t=e[1];a.add(t),n.zenovayInstalled=!0,n.zenovayFiles.push({file:o,currentTrackingCode:t,scriptTagCount:0,matchSample:e[0].slice(0,80)})}}for(let e of R)if(e.patterns.some(e=>e.test(r))){let t=i.get(e.name)??new Set;t.add(o),i.set(e.name,t)}}if(n.foundTrackingCodes=Array.from(a),n.competitors=Array.from(i.entries()).map(([e,t])=>({name:e,files:Array.from(t).slice(0,5)})),n.zenovayInstalled)if(n.foundTrackingCodes.length>0){let e=n.foundTrackingCodes.every(e=>e===t);n.correctTrackingCode=e,n.recommendation=e?`no-op`:`update-tracking-code`}else n.correctTrackingCode=!1,n.recommendation=`no-op`;else n.competitors.length>0?n.recommendation=`fresh-install-alongside-competitor`:n.recommendation=`fresh-install`;return n.summary=B(n,t),n}function B(e,t){let n=[];return e.zenovayInstalled?e.foundTrackingCodes.length===0?n.push(`Zenovay package or config detected but no <script> tag found.`):e.correctTrackingCode?n.push(`Zenovay tracker present in ${e.zenovayFiles.length} file(s) with correct ID ${t}.`):n.push(`Zenovay tracker present in ${e.zenovayFiles.length} file(s), but with mismatching ID(s): ${e.foundTrackingCodes.join(`, `)} (target: ${t}).`):n.push(`No Zenovay tracker found.`),e.competitors.length>0&&n.push(`Competitor tracker(s) present (DO NOT modify): ${e.competitors.map(e=>e.name).join(`, `)}.`),n.join(` `)}async function ce(e){let t=await z(e,``);return{installed:t.zenovayInstalled,reasons:t.summary?[t.summary]:[],packageMarker:t.packageMarker,configFile:t.configFile,scriptFile:t.zenovayFiles[0]?.file}}const le=[/^package\.json$/,/^package-lock\.json$/,/^pnpm-lock\.yaml$/,/^yarn\.lock$/,/^bun\.lock$/,/^tsconfig.*\.json$/,/^(next|nuxt|vite|astro|remix|svelte|tailwind|postcss)\.config\.(ts|mts|cts|js|mjs|cjs)$/,/^app\/.*\.(tsx|ts|jsx|js|svelte|astro|vue)$/,/^pages\/.*\.(tsx|ts|jsx|js)$/,/^src\/app\/.*\.(tsx|ts|jsx|js)$/,/^src\/pages\/.*\.(tsx|ts|jsx|js)$/,/^src\/components\/.*\.(astro|svelte|vue|tsx|ts|jsx|js)$/,/^src\/(root|app|entry-server|entry-client)\.(tsx|ts|jsx|js)$/,/^gatsby-(ssr|browser|config)\.(js|ts|mjs)$/,/\.html?$/,/^src\/main\.(tsx|ts|jsx|js)$/,/^src\/App\.(tsx|ts|jsx|js|svelte|vue)$/,/^src\/routes\/\+layout\.(svelte|ts|js)$/,/^src\/routes\/root\..*$/,/^src\/layouts\/.*\.(astro|svelte|vue)$/,/^\.env\.example$/,/^README\.md$/,/^\.gitignore$/,/^nuxt\.config\.(ts|js|mjs)$/,/^plugins\/.*\.(ts|js)$/],ue=[/(^|\/)\.env($|\.(?!example$)[^/]+$)/,/(^|\/)\.git(\/|$)/,/(^|\/)node_modules\//,/(^|\/)\.ssh\//,/(^|\/)\.aws\//,/\.pem$/,/\.key$/,/(^|\/)id_rsa($|\.)/,/(^|\/)\.npmrc$/,/(^|\/)credentials(\.|$)/],V=256*1024,de=50,fe=20,pe=40;var H=class extends Error{constructor(e,t){super(t),this.code=e,this.name=`SandboxError`}};const U=/<script[^>]*src\s*=\s*["']https:\/\/(?:api|cdn)\.zenovay\.com\/[^"']+["'][^>]*>\s*<\/script>/i,me=[{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 he=class{sessionId;cwd;cwdReal;undoRoot;readCount=0;writeCount=0;roundCount=0;writtenPathsSet=new Set;constructor(e){this.sessionId=e.sessionId??T(),this.cwd=e.cwd,this.cwdReal=x.realpath(e.cwd),this.undoRoot=e.undoRoot??b.join(C.homedir(),`.zenovay`,`undo`)}incrementRound(){if(this.roundCount++,this.roundCount>pe)throw new H(`round-cap`,`Tool-call recursion cap (${pe}) 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 resolveSafe(e,t){if(typeof e!=`string`||e.length===0)throw new H(`escape`,`Path must be a non-empty string.`);if(e.includes(`\0`))throw new H(`escape`,`Null byte in path.`);if(/^\\\\[?.]\\/.test(e)||/^\\\\[A-Za-z0-9]/.test(e))throw new H(`escape`,`Windows special path prefix: ${e}`);if(/%/.test(e))try{let t=decodeURIComponent(e);if(/%[0-9A-Fa-f]{2}/.test(t))throw new H(`escape`,`Double-encoded path: ${e}`);e=t}catch(t){throw t instanceof H?t:new H(`escape`,`Malformed percent-encoding: ${e}`)}if(e.includes(`\0`))throw new H(`escape`,`Null byte in decoded path.`);if(e.includes(`\\`))throw new H(`escape`,`Backslash in path (Windows-style separator not accepted): ${e}`);let n=await this.cwdReal,r=b.isAbsolute(e)?e:b.join(n,e),i=b.normalize(r),a=i;try{a=await x.realpath(i)}catch(e){if(e.code!==`ENOENT`)throw new H(`escape`,`realpath failed: ${e.message}`);let t=b.dirname(i);try{let e=await x.realpath(t);a=b.join(e,b.basename(i))}catch{}}if(!this.isWithin(a,n))throw new H(`escape`,`Path escapes cwd: ${e}`);let o=b.relative(n,a),s=o.toLowerCase();for(let e of ue)if(e.test(o)||e.test(s)){if(t===`read`&&/(^|\/)node_modules\//i.test(o))continue;throw new H(`blocklisted`,`Path is on the hard blocklist: ${o}`)}if(t===`write`){let e=le.some(e=>e.test(o));if(!e&&!/^\.env(\.local)?$/.test(o)&&!/^\.claude\//.test(o)&&!/^\.cursor\//.test(o))throw new H(`not-allowlisted`,`Write path not on allowlist: ${o}`)}return a}isWithin(e,t){let n=b.relative(t,e);return!n.startsWith(`..`)&&!b.isAbsolute(n)}async safeRead(e){if(this.readCount>=de)throw new H(`read-cap`,`Read cap (${de}) reached.`);let t=await this.resolveForRead(e),n=await x.stat(t);if(n.size>V)throw new H(`too-large`,`File exceeds ${V}B: ${e} (${n.size}B)`);let r=await x.readFile(t),i=r.subarray(0,Math.min(r.length,8192));if(i.includes(0))throw new H(`binary-rejected`,`Binary content in ${e}.`);return this.readCount++,r.toString(`utf8`)}async safeWrite(e,t){if(this.writeCount>=fe)throw new H(`write-cap`,`Write cap (${fe}) reached.`);if(t.length>V)throw new H(`too-large`,`Write exceeds ${V}B: ${e}`);let n=await this.resolveForWrite(e),r=await x.readFile(n,`utf8`).catch(e=>{if(e.code===`ENOENT`)return null;throw e});if(r!==null){if(U.test(r)&&!U.test(t))throw new H(`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 me)if(i.test(r)&&!i.test(t))throw new H(`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 x.mkdir(b.dirname(n),{recursive:!0}),await x.writeFile(n,t,`utf8`),this.writeCount++;let a=await this.cwdReal;return this.writtenPathsSet.add(b.relative(a,n)),{backupPath:i}}async journalBackup(e){let t=await x.readFile(e).catch(e=>{if(e.code===`ENOENT`)return null;throw e}),n=b.join(this.undoRoot,this.sessionId);await x.mkdir(n,{recursive:!0,mode:448});let r=w.createHash(`sha256`).update(e).digest(`hex`).slice(0,16),i=b.join(n,`${r}.bak`),a=b.join(n,`manifest.jsonl`);t&&await x.writeFile(i,t,{mode:384});let o=JSON.stringify({abs:e,backupPath:t?i:null,ts:Date.now()});return await x.appendFile(a,o+`
|
|
2
|
-
`,{mode:384}),t?i:null}static wrapForModel(e,t){let n=w.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 c(e)}};async function ge(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 _e(e){let t=e.trackingCode??e.siteId??``,n=e.targetPath||`src/index.html`,r=`<script defer\n data-id="${t}"\n data-allow-localhost="true"\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 ve={id:`angular`,displayName:`Angular`,detect:ge,files:[{path:`src/index.html`,kind:`mutate`,required:!0}],envVarName:`NG_ZENOVAY_SITE`,buildSnippets:_e},ye=[`astro.config.ts`,`astro.config.mjs`,`astro.config.js`];async function be(e){for(let t of ye)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 xe(e){let t=e.trackingCode??e.siteId??``,n=`<script defer data-id="${t}" data-allow-localhost="true" 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`."}]}const Se={id:`astro`,displayName:`Astro`,detect:be,files:[{path:`src/layouts/Layout.astro`,kind:`mutate`,required:!1},{path:`src/layouts/BaseHead.astro`,kind:`mutate`,required:!1},{path:`.env`,kind:`create`,required:!0}],envVarName:`PUBLIC_ZENOVAY_SITE`,buildSnippets:xe};async function Ce(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 we(e){return await Ce(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');
|
|
3
|
-
|
|
4
|
-
exports.onRenderBody = ({ setHeadComponents }) => {
|
|
5
|
-
setHeadComponents([
|
|
6
|
-
React.createElement('script', {
|
|
7
|
-
key: 'zenovay-tracker',
|
|
8
|
-
defer: true,
|
|
9
|
-
'data-id': '${t}',
|
|
10
|
-
'data-allow-localhost': 'true',
|
|
11
|
-
src: 'https://api.zenovay.com/z.js',
|
|
12
|
-
}),
|
|
13
|
-
]);
|
|
14
|
-
};
|
|
15
|
-
`;return[{targetPath:`gatsby-ssr.js`,anchorKind:`replace-file`,code:n,description:`Add the Zenovay tracker via Gatsby SSR onRenderBody → setHeadComponents.`}]}const Ee={id:`gatsby`,displayName:`Gatsby`,detect:we,files:[{path:`gatsby-ssr.js`,kind:`create`,required:!0}],envVarName:`GATSBY_ZENOVAY_SITE`,buildSnippets:Te},De=[`app/layout.tsx`,`app/layout.ts`,`app/layout.jsx`,`app/layout.js`,`src/app/layout.tsx`,`src/app/layout.ts`,`src/app/layout.jsx`,`src/app/layout.js`];async function Oe(e){for(let t of De)if(await e.exists(t))return t;return null}async function ke(e){let t=await e.readFile(`package.json`);if(!t)return!1;try{let e=JSON.parse(t);return!!(e.dependencies?.next??e.devDependencies?.next)}catch{return!1}}async function Ae(e){let t=await ke(e),n=await e.exists(`app`)||await e.exists(`src/app`),r=await Oe(e);return t?n?r?{matched:!0,confidence:.95,reason:`Detected Next.js App Router via \`next\` dep + \`${r}\`.`}:{matched:!1,confidence:.4,reason:"Found `app/` but no root layout file (layout.tsx/ts/jsx/js)."}:{matched:!1,confidence:0,reason:"No `app/` directory found — not an App Router project."}:{matched:!1,confidence:0,reason:"package.json does not list `next` as a dependency."}}function je(e,t=`script`){let n=e.targetPath||`app/layout.tsx`,r=e.trackingCode??e.siteId??``;return t===`npm`?Ne(n,r):Me(n,r)}function Me(e,t){return[{targetPath:e,anchorKind:`after-imports`,code:`import Script from 'next/script';`,description:`Import next/script to inject the Zenovay tracker.`},{targetPath:e,anchorKind:`wrap-children`,code:`<Script
|
|
16
|
-
defer
|
|
17
|
-
data-id="${t}"
|
|
18
|
-
data-allow-localhost="true"
|
|
19
|
-
src="https://api.zenovay.com/z.js"
|
|
20
|
-
strategy="afterInteractive"
|
|
21
|
-
/>
|
|
22
|
-
{children}`,description:`Add the Zenovay tracker <Script> next to children in the root layout.`}]}function Ne(e,t){return[{targetPath:`components/zenovay-bootstrap.tsx`,anchorKind:`replace-file`,code:`'use client';
|
|
23
|
-
|
|
24
|
-
import { useEffect } from 'react';
|
|
25
|
-
import { init } from '@zenovay/tracker';
|
|
26
|
-
|
|
27
|
-
/**
|
|
28
|
-
* Mounts the Zenovay tracker exactly once on the client. Equivalent to the
|
|
29
|
-
* canonical <script src="https://api.zenovay.com/z.js"> tag — init() injects
|
|
30
|
-
* the same loader internally.
|
|
31
|
-
*/
|
|
32
|
-
export function ZenovayBootstrap() {
|
|
33
|
-
useEffect(() => {
|
|
34
|
-
init('${t}', { allowLocalhost: true });
|
|
35
|
-
}, []);
|
|
36
|
-
return null;
|
|
37
|
-
}
|
|
38
|
-
`,description:`Create a client-component bootstrap that calls init() from @zenovay/tracker.`},{targetPath:e,anchorKind:`after-imports`,code:`import { ZenovayBootstrap } from '@/components/zenovay-bootstrap';`,description:`Import the Zenovay tracker bootstrap into the root layout.`},{targetPath:e,anchorKind:`wrap-children`,code:`<ZenovayBootstrap />
|
|
39
|
-
{children}`,description:`Render the Zenovay tracker bootstrap alongside children in the root layout.`}]}const Pe={id:`next-app-router`,displayName:`Next.js (App Router)`,detect:Ae,files:[{path:`app/layout.tsx`,kind:`mutate`,required:!0}],envVarName:`NEXT_PUBLIC_ZENOVAY_SITE`,packageDeps:[`@zenovay/tracker`],supportsNpmMode:!0,buildSnippets:je},Fe=[`pages/_app.tsx`,`pages/_app.ts`,`pages/_app.jsx`,`pages/_app.js`,`src/pages/_app.tsx`,`src/pages/_app.ts`,`src/pages/_app.jsx`,`src/pages/_app.js`];async function Ie(e){for(let t of Fe)if(await e.exists(t))return t;return null}async function Le(e){let t=await e.readFile(`package.json`);if(!t)return!1;try{let e=JSON.parse(t);return!!(e.dependencies?.next??e.devDependencies?.next)}catch{return!1}}async function Re(e){let t=await Le(e);if(!t)return{matched:!1,confidence:0,reason:"package.json does not list `next` as a dependency."};let n=await Ie(e);if(n)return{matched:!0,confidence:.9,reason:`Detected Next.js Pages Router via \`${n}\`.`};let r=await e.exists(`app`),i=await e.glob(`pages/**/*.{tsx,ts,jsx,js}`);return i.length>0&&!r?{matched:!0,confidence:.7,reason:"Found `pages/` directory with route files but no `_app` — will create one."}:{matched:!1,confidence:.2,reason:`Next.js detected, but no pages-router entry point found.`}}function ze(e){let t=`pages/_app.tsx`,n=e.trackingCode??e.siteId??``,r=`import type { AppProps } from 'next/app';
|
|
40
|
-
import Script from 'next/script';
|
|
41
|
-
|
|
42
|
-
export default function App({ Component, pageProps }: AppProps) {
|
|
43
|
-
return (
|
|
44
|
-
<>
|
|
45
|
-
<Script
|
|
46
|
-
defer
|
|
47
|
-
data-id="${n}"
|
|
48
|
-
data-allow-localhost="true"
|
|
49
|
-
src="https://api.zenovay.com/z.js"
|
|
50
|
-
strategy="afterInteractive"
|
|
51
|
-
/>
|
|
52
|
-
<Component {...pageProps} />
|
|
53
|
-
</>
|
|
54
|
-
);
|
|
55
|
-
}
|
|
56
|
-
`;return[{targetPath:t,anchorKind:`after-imports`,code:`import Script from 'next/script';`,description:"Import next/script in `_app`."},{targetPath:t,anchorKind:`wrap-children`,code:`<><Script defer data-id="${n}" data-allow-localhost="true" src="https://api.zenovay.com/z.js" strategy="afterInteractive" /><Component {...pageProps} /></>`,description:`Render the Zenovay tracker alongside the page component.`},{targetPath:t,anchorKind:`replace-file`,code:r,description:"Full replacement when `_app` does not exist yet."}]}const Be={id:`next-pages-router`,displayName:`Next.js (Pages Router)`,detect:Re,files:[{path:`pages/_app.tsx`,kind:`mutate`,required:!0}],envVarName:`NEXT_PUBLIC_ZENOVAY_SITE`,buildSnippets:ze},Ve=S.object({modules:S.array(S.string()).optional(),runtimeConfig:S.object({public:S.record(S.string(),S.unknown()).optional()}).optional()}).passthrough();async function He(e){let t=await e.readFile(`package.json`);if(!t)return{matched:!1,confidence:0,reason:`No package.json found.`};try{let e=JSON.parse(t),n=!!(e.dependencies?.nuxt??e.devDependencies?.nuxt??e.dependencies?.nuxt3??e.devDependencies?.nuxt3);if(n)return{matched:!0,confidence:.95,reason:"Detected Nuxt via `nuxt` / `nuxt3` dependency."}}catch{}let n=await e.exists(`nuxt.config.ts`)||await e.exists(`nuxt.config.js`)||await e.exists(`nuxt.config.mjs`);return n?{matched:!0,confidence:.6,reason:"Found `nuxt.config.*` but no explicit dependency listing."}:{matched:!1,confidence:0,reason:`No Nuxt dependency or config detected.`}}function Ue(e){let t=e.trackingCode??e.siteId??``,n=` app: {
|
|
57
|
-
head: {
|
|
58
|
-
script: [
|
|
59
|
-
{
|
|
60
|
-
defer: true,
|
|
61
|
-
src: 'https://api.zenovay.com/z.js',
|
|
62
|
-
'data-id': '${t}',
|
|
63
|
-
'data-allow-localhost': 'true',
|
|
64
|
-
},
|
|
65
|
-
],
|
|
66
|
-
},
|
|
67
|
-
},`;return[{targetPath:`nuxt.config.ts`,anchorKind:`head-tag`,code:n,description:"Add the Zenovay tracker to Nuxt's `app.head.script` so every page loads it."}]}const We={id:`nuxt`,displayName:`Nuxt`,detect:He,files:[{path:`nuxt.config.ts`,kind:`mutate`,required:!0}],envVarName:`NUXT_PUBLIC_ZENOVAY_SITE`,buildSnippets:Ue},Ge=[`index.html`,`public/index.html`,`dist/index.html`];async function Ke(e){for(let t of Ge)if(await e.exists(t))return{matched:!0,confidence:.5,reason:`Detected plain HTML project via \`${t}\`.`};let t=await e.glob(`**/*.html`);return t.length>0?{matched:!0,confidence:.3,reason:`Found ${t.length} HTML file(s); plain-HTML adapter is usable as fallback.`}:{matched:!1,confidence:0,reason:`No HTML files found in the project.`}}function qe(e){let t=e.siteId??``,n=`<script defer\n data-id="${t}"\n data-allow-localhost="true"\n src="https://api.zenovay.com/z.js">\n</script>`;return[{targetPath:`index.html`,anchorKind:`head-tag`,code:n,description:`Inject the Zenovay tracker inside <head>. Repeat for every HTML file that contains a <head>.`}]}const Je={id:`plain-html`,displayName:`Plain HTML`,detect:Ke,files:[{path:`index.html`,kind:`mutate`,required:!0}],envVarName:`PUBLIC_ZENOVAY_SITE`,buildSnippets:qe};async function Ye(e){let t=await e.readFile(`package.json`);if(!t)return{matched:!1,confidence:0,reason:`No package.json.`};try{let e=JSON.parse(t),n={...e.dependencies??{},...e.devDependencies??{}};if(n[`@builder.io/qwik-city`]??n[`@builder.io/qwik`])return{matched:!0,confidence:.92,reason:"Detected Qwik via `@builder.io/qwik(-city)`."}}catch{}return{matched:!1,confidence:0,reason:`No Qwik dependency found.`}}function Xe(e){let t=e.trackingCode??e.siteId??``,n=e.targetPath||`src/root.tsx`,r=`<script
|
|
68
|
-
defer
|
|
69
|
-
data-id="${t}"
|
|
70
|
-
data-allow-localhost="true"
|
|
71
|
-
src="https://api.zenovay.com/z.js"
|
|
72
|
-
/>`;return[{targetPath:n,anchorKind:`head-tag`,code:r,description:`Add the Zenovay tracker into the <head> of the Qwik root document.`}]}const Ze={id:`qwik`,displayName:`Qwik`,detect:Ye,files:[{path:`src/root.tsx`,kind:`mutate`,required:!0}],envVarName:`PUBLIC_ZENOVAY_SITE`,buildSnippets:Xe};async function Qe(e){let t=await e.readFile(`package.json`);if(t)try{let e=JSON.parse(t),n={...e.dependencies??{},...e.devDependencies??{}},r=Object.keys(n).some(e=>e.startsWith(`@remix-run/`));if(r)return{matched:!0,confidence:.95,reason:"Detected Remix via `@remix-run/*` dependencies."}}catch{}return await e.exists(`remix.config.js`)||await e.exists(`remix.config.ts`)?{matched:!0,confidence:.8,reason:"Detected Remix via `remix.config.*`."}:{matched:!1,confidence:0,reason:`No Remix dependency or config detected.`}}function $e(e){let t=e.trackingCode??e.siteId??``;return[{targetPath:`app/root.tsx`,anchorKind:`head-tag`,code:`<script defer data-id="${t}" data-allow-localhost="true" src="https://api.zenovay.com/z.js"></script>`,description:`Inline the Zenovay tracker <script> inside the document <head>.`}]}const et={id:`remix`,displayName:`Remix`,detect:Qe,files:[{path:`app/root.tsx`,kind:`mutate`,required:!0}],envVarName:`PUBLIC_ZENOVAY_SITE`,buildSnippets:$e};async function tt(e){let t=await e.readFile(`package.json`);if(!t)return{matched:!1,confidence:0,reason:`No package.json.`};try{let e=JSON.parse(t),n={...e.dependencies??{},...e.devDependencies??{}};if(n[`@solidjs/start`]??n[`solid-start`])return{matched:!0,confidence:.92,reason:"Detected SolidStart via `@solidjs/start` / `solid-start`."}}catch{}return{matched:!1,confidence:0,reason:`No SolidStart dependency found.`}}function nt(e){let t=e.trackingCode??e.siteId??``,n=e.targetPath||`src/entry-server.tsx`,r=`<script
|
|
73
|
-
defer
|
|
74
|
-
data-id="${t}"
|
|
75
|
-
data-allow-localhost="true"
|
|
76
|
-
src="https://api.zenovay.com/z.js"
|
|
77
|
-
/>`;return[{targetPath:n,anchorKind:`head-tag`,code:r,description:`Add the Zenovay tracker into the document <head> rendered by SolidStart entry-server.`}]}const rt={id:`solid-start`,displayName:`SolidStart`,detect:tt,files:[{path:`src/entry-server.tsx`,kind:`mutate`,required:!0}],envVarName:`VITE_ZENOVAY_SITE`,buildSnippets:nt};async function it(e){let t=await e.readFile(`package.json`);if(!t)return{matched:!1,confidence:0,reason:`No package.json found.`};try{let e=JSON.parse(t),n=!!(e.dependencies?.[`@sveltejs/kit`]??e.devDependencies?.[`@sveltejs/kit`]);return n?{matched:!0,confidence:.95,reason:"Detected SvelteKit via `@sveltejs/kit` dependency."}:{matched:!1,confidence:0,reason:"`@sveltejs/kit` not in dependencies."}}catch{return{matched:!1,confidence:0,reason:`package.json is not valid JSON.`}}}function at(e){let t=e.trackingCode??e.siteId??``,n=`<svelte:head>
|
|
78
|
-
<script defer data-id="${t}" data-allow-localhost="true" src="https://api.zenovay.com/z.js"></script>
|
|
79
|
-
</svelte:head>
|
|
80
|
-
|
|
81
|
-
<slot />
|
|
82
|
-
`;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 ot={id:`sveltekit`,displayName:`SvelteKit`,detect:it,files:[{path:`src/routes/+layout.svelte`,kind:`mutate`,required:!0}],envVarName:`PUBLIC_ZENOVAY_SITE`,buildSnippets:at},st=[`next`,`nuxt`,`nuxt3`,`@sveltejs/kit`,`astro`,`@remix-run/react`,`@builder.io/qwik-city`,`@builder.io/qwik`,`@solidjs/start`,`solid-start`,`@angular/core`,`gatsby`],ct=[`index.html`,`public/index.html`];async function lt(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 ut(e){for(let t of ct)if(await e.exists(t))return t;return null}async function dt(e){let t=await lt(e);if(st.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 ut(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 ft(e){let t=e.trackingCode??e.siteId??``,n=e.targetPath||`index.html`,r=`<script defer\n data-id="${t}"\n data-allow-localhost="true"\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 pt={id:`vite`,displayName:`Vite`,detect:dt,files:[{path:`index.html`,kind:`mutate`,required:!0}],envVarName:`VITE_ZENOVAY_SITE`,buildSnippets:ft},mt=[Pe,Be,We,ot,Se,et,Ee,ve,rt,Ze,pt,Je];async function ht(e){let t=[];for(let n of mt){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 gt(e){let t=t=>b.resolve(e,t);return{cwd:e,async readFile(e){try{return await x.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 x.access(t(e)),!0}catch{return!1}},async glob(t){return N(t,{cwd:e,dot:!1,gitignore:!0,onlyFiles:!0,followSymbolicLinks:!1})}}}async function _t(e,t){let n=gt(e),{adapter:r,ranked:i}=await ht(n),a=i[0];return r&&a&&a.result.confidence>=.7?r:t?t.pickInteractively(i):r}function vt(e,t){let n=/[\s"'#=]/.test(t)||t===``,r=n?`"${t.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`:t;return`${e}=${r}`}function yt(e){let t=new Set;for(let n of e.split(/\r?\n/)){let e=n.trim();if(!e||e.startsWith(`#`))continue;let r=e.indexOf(`=`);if(r<=0)continue;let i=e.slice(0,r).trim();/^[A-Za-z_][A-Za-z0-9_]*$/.test(i)&&t.add(i)}return t}async function W(e,t,n={}){let r=n.filename??`.env.local`,i=b.resolve(e,r),a=``,o=!0;try{a=await x.readFile(i,`utf8`)}catch(e){if(e.code===`ENOENT`)o=!1;else throw e}let s=o?yt(a):new Set,c=[],l=[],u=[];for(let[e,n]of Object.entries(t)){if(s.has(e)){l.push(e);continue}u.push(vt(e,n)),c.push(e)}if(c.length===0)return{created:!1,existing:o,addedKeys:c,skippedKeys:l};let d=`# Added by Zenovay CLI`,f;if(o){let e=a.length>0&&!a.endsWith(`
|
|
83
|
-
`);f=a+(e?`
|
|
84
|
-
`:``)+`
|
|
85
|
-
`+d+`
|
|
86
|
-
`+u.join(`
|
|
87
|
-
`)+`
|
|
88
|
-
`}else f=d+`
|
|
89
|
-
`+u.join(`
|
|
90
|
-
`)+`
|
|
91
|
-
`;if(o)await x.writeFile(i,f,`utf8`);else{let e=await x.open(i,`w`,384);try{await e.writeFile(f,`utf8`)}finally{await e.close()}}return{created:!o,existing:o,addedKeys:c,skippedKeys:l}}const bt=`https://api.zenovay.com/mcp`,xt=S.object({url:S.string().url(),headers:S.record(S.string(),S.string()).optional()}),St=S.object({mcpServers:S.record(S.string(),xt).optional()}).passthrough();function Ct(e){return e.HOME??e.USERPROFILE??C.homedir()}function wt(e){return e.APPDATA??null}function Tt(e,t){let n=Ct(t),r=wt(t),i=[];return i.push({id:`cursor`,displayName:`Cursor`,configPath:b.join(n,`.cursor`,`mcp.json`)}),e===`win32`&&r&&i.push({id:`cursor`,displayName:`Cursor (AppData)`,configPath:b.join(r,`Cursor`,`User`,`globalStorage`,`cursor.mcp`,`mcp.json`)}),e===`darwin`?i.push({id:`claude-desktop`,displayName:`Claude Desktop`,configPath:b.join(n,`Library`,`Application Support`,`Claude`,`claude_desktop_config.json`)}):e===`win32`&&r?i.push({id:`claude-desktop`,displayName:`Claude Desktop`,configPath:b.join(r,`Claude`,`claude_desktop_config.json`)}):i.push({id:`claude-desktop`,displayName:`Claude Desktop`,configPath:b.join(n,`.config`,`Claude`,`claude_desktop_config.json`)}),i.push({id:`vscode`,displayName:`VS Code`,configPath:b.join(n,`.vscode`,`mcp.json`)}),i}async function Et(e){try{return await x.access(e),!0}catch{return!1}}async function Dt(e){try{let t=await x.readFile(e,`utf8`);if(t.trim().length===0)return{};let n=JSON.parse(t),r=St.safeParse(n);return r.success?r.data:n&&typeof n==`object`?n:{}}catch{return{}}}function Ot(){return{url:bt}}async function G(e){let t=e.env??process.env,n=e.platform??process.platform,r=new Set(e.skip??[]),i=[],a=[],o=[],s=new Set,c=Ot();for(let e of Tt(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 Et(e.configPath);if(!t){a.push(e.displayName);continue}let n=await Dt(e.configPath),r=`${e.configPath}.bak`;await x.copyFile(e.configPath,r);let o={...n,mcpServers:{...n.mcpServers??{},zenovay:c}};await x.mkdir(b.dirname(e.configPath),{recursive:!0}),await x.writeFile(e.configPath,JSON.stringify(o,null,2)+`
|
|
92
|
-
`,`utf8`),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 kt(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 At=S.object({path:S.string().min(1)}),jt=S.object({path:S.string().min(1),content:S.string(),reason:S.string().min(1)}),Mt=S.object({path:S.string().min(1),patch:S.string().min(1),reason:S.string().min(1)}),Nt=S.object({}),Pt=S.object({question:S.string().min(1),choices:S.array(S.string()).optional()});async function Ft(e,t){let n=At.safeParse(t);if(!n.success)return{ok:!1,content:null,error:`invalid_args`};try{let t=await e.safeRead(n.data.path),r=he.scrubSecrets(t);return{ok:!0,content:he.wrapForModel(n.data.path,r)}}catch(e){return{ok:!1,content:null,error:e.message}}}async function It(e,t,n){let r=jt.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 Lt(e,t,n){let r=Mt.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=F(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.`}:It(e,{path:i,content:c,reason:o},n)}async function Rt(e){try{let t=gt(e),{adapter:n,ranked:r}=await ht(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 zt(e,t){let n=Pt.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}}}async function Bt(e){let{api:t,sandbox:n,approval:r,prompter:i,handlers:a}=e,o=[...e.initialMessages],s=``,c=0;for(;c<pe;){n.incrementRound(),c++;let u=await t.openAiStream(`install`,{messages:o,cwd_fingerprint:n.sessionId,diagnosis:e.diagnosis,targetTrackingCode:e.targetTrackingCode}),d=[],f=``;for await(let e of l(u))switch(e.type){case`delta`:f+=e.content,a?.onDelta?.(e.content);break;case`tool_start`:a?.onToolStart?.({id:e.id,name:e.name});break;case`tool_call`:{let t=await Vt(e.name,e.arguments,{sandbox:n,cwd:n.cwd,approval:r,prompter:i});d.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 a?.onError?.(e),Error(`[${e.code}] ${e.message}`);case`done`:break}if(f&&(s+=f),d.length===0){f&&o.push({role:`assistant`,content:f});break}o.push({role:`assistant`,content:f,toolCalls:d.map(e=>({id:e.id,type:`function`,function:{name:e.name,arguments:JSON.stringify(e.arguments)}}))});for(let e of d)o.push({role:`tool`,toolCallId:e.id,toolName:e.name,content:JSON.stringify(e.result)})}return{finalText:s,rounds:c}}async function Vt(e,t,n){try{switch(e){case`read_file`:return await Ft(n.sandbox,t);case`write_file`:return await It(n.sandbox,t,n.approval);case`patch_file`:return await Lt(n.sandbox,t,n.approval);case`detect_framework`:return await Rt(n.cwd);case`ask_user`:return await zt(n.prompter,t);default:return{ok:!1,content:null,error:`unknown_tool:${e}`}}}catch(e){return{ok:!1,content:null,error:`tool_threw: ${e.message}`}}}const Ht=e=>`<script defer\n data-id="${e}"\n data-allow-localhost="true"\n src="https://api.zenovay.com/z.js">\n</script>`;async function Ut(e){let t={installed:[],skipped:[],errors:[]},n=await N([`**/*.html`,`!node_modules/**`,`!.git/**`,`!dist/**`,`!.next/**`,`!.nuxt/**`,`!build/**`,`!.output/**`],{cwd:e.cwd,gitignore:!0,absolute:!1});if(n.length===0)return t;let r=Ht(e.trackingCode),i=RegExp(`data-id\\s*=\\s*["']${Wt(e.trackingCode)}["']`);for(let a of n){let n=b.join(e.cwd,a),o;try{o=await x.readFile(n,`utf8`)}catch(e){t.errors.push({file:a,error:e.message});continue}if(U.test(o)&&i.test(o)){t.skipped.push({file:a,reason:`already installed with correct tracking code`});continue}let s;if(U.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??`
|
|
93
|
-
`,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 me)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 x.writeFile(n,s,`utf8`),t.installed.push(a)}catch(e){t.errors.push({file:a,error:e.message})}}return t}function Wt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}const Gt=`https://api.zenovay.com/z.js`;function Kt(e,t){return e.includes(Gt)&&e.includes(t)}function qt(e){if(/from\s+['"]next\/script['"]/.test(e))return e;let t=e.split(`
|
|
94
|
-
`),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(`
|
|
95
|
-
`)}function Jt(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}" data-allow-localhost="true" src="${Gt}" strategy="afterInteractive" />`;return e.replace(n,`${a}\n${i}</body>`)}async function Yt(e){let{cwd:t,trackingCode:n}=e,r={installed:[],skipped:[],errors:[],fellThrough:!1},i;try{i=await N([`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 k.readFile(b.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(Kt(o.src,n))return r.skipped.push({file:o.rel,reason:`already installed with correct tracking code`}),r;let s=qt(o.src),c=Jt(s,n);if(!c)return r.fellThrough=!0,r;try{await k.writeFile(b.join(t,o.rel),c),r.installed.push(o.rel)}catch(e){r.errors.push({file:o.rel,error:e.message}),r.fellThrough=!0}return r}const K=`api.zenovay.com/z.js`;async function q(e){try{return await x.readFile(e,`utf8`)}catch{return null}}function Xt(e,t){let n=e.toLowerCase().lastIndexOf(`</head>`);if(n===-1)return null;let r=e.lastIndexOf(`
|
|
96
|
-
`,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 Zt(e){if(e.adapter.id===`nuxt`)return $t(e);if(e.adapter.id===`sveltekit`)return en(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 e=!1;for(let n of o){let r=b.join(t,n.targetPath),i=await q(r);if(i===null){a.skipped.push({file:n.targetPath,reason:`target file not present`});continue}if(i.includes(K)){a.skipped.push({file:n.targetPath,reason:`tracker already present`}),e=!0;break}let o=Xt(i,n.code);if(o===null){a.skipped.push({file:n.targetPath,reason:`no </head> anchor in target`});continue}try{await x.writeFile(r,o,`utf8`),a.installed.push(n.targetPath),e=!0;break}catch(e){a.errors.push({file:n.targetPath,error:e.message})}}return!e&&a.installed.length===0&&a.errors.length===0&&(a.fellThrough=!0),a}if(s.size===1&&s.has(`replace-file`)&&o.length===1){let e=o[0];if(!e)return a.fellThrough=!0,a;let n=i.files.find(t=>t.path===e.targetPath),r=b.join(t,e.targetPath),s=await q(r);if(s!==null)return s.includes(K)?(a.skipped.push({file:e.targetPath,reason:`tracker already present`}),a):(a.fellThrough=!0,a);if(n?.kind===`create`){try{await x.mkdir(b.dirname(r),{recursive:!0}),await x.writeFile(r,e.code,`utf8`),a.installed.push(e.targetPath)}catch(t){a.errors.push({file:e.targetPath,error:t.message}),a.fellThrough=a.installed.length===0}return a}return a.fellThrough=!0,a}return a.fellThrough=!0,a}function Qt(){return{installed:[],skipped:[],errors:[],fellThrough:!1}}async function $t(e){let t=Qt(),n=[`nuxt.config.ts`,`nuxt.config.mjs`,`nuxt.config.js`],r=null,i=null,a=null;for(let t of n){let n=b.join(e.cwd,t),o=await q(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(K))return t.skipped.push({file:r,reason:`tracker already present`}),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 x.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 en(e){let t=Qt(),n=`src/routes/+layout.svelte`,r=b.join(e.cwd,n),i=await q(r),a=`<svelte:head>\n <script defer data-id="${e.trackingCode}" data-allow-localhost="true" src="https://api.zenovay.com/z.js"></script>\n</svelte:head>\n`;if(i!==null){if(i.includes(K))return t.skipped.push({file:n,reason:`tracker already present`}),t;try{await x.writeFile(r,`${a}\n${i}`,`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 x.mkdir(b.dirname(r),{recursive:!0}),await x.writeFile(r,o,`utf8`),t.installed.push(n)}catch(e){t.errors.push({file:n,error:e.message}),t.fellThrough=!0}return t}const tn=`\x1B]8;;`,nn=`\x07`;function rn(){return process.env.FORCE_HYPERLINK?!0:!(process.env.NO_COLOR||!process.stdout.isTTY||process.env.CI||(process.env.TERM??``)===`dumb`)}function J({url:e,label:t,color:n,arrow:r=!0}){let{theme:i}=m(),a=n??i.fg,o=(t??e)+(r?` ↗`:``);return rn()?A.createElement(D,{color:a,underline:!0},tn,e,nn,o,tn,nn):t&&t!==e?A.createElement(D,{color:a},A.createElement(D,{underline:!0},t),A.createElement(D,{color:i.dim},` (`,e,`)`)):A.createElement(D,{color:a,underline:!0},e)}function Y({label:e,value:t,labelWidth:n=12}){let{theme:r}=m();return A.createElement(E,{flexDirection:`row`},A.createElement(E,{width:n,flexShrink:0},A.createElement(D,{color:r.dim},e.toUpperCase())),typeof t==`string`?A.createElement(D,{color:r.fg},t):t)}function an(e){return e.yes||!process.stdout.isTTY?`auto`:`interactive`}function on(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 sn(){let e=[12,15,18,22,28,35,41,50,58,64,72,78],t=y(e,24);return[` ↑`,` ${t}`,` └────────────────────────`,` May Jun Jul Aug Sep`]}function cn(){return[` Landing page ████████████████████ 100%`,` ↓ -28%`,` Pricing ██████████████░░░░░░ 72%`,` ↓ -50%`,` Checkout ███████░░░░░░░░░░░░░ 36%`,` ↓ -64%`,` Purchased ███░░░░░░░░░░░░░░░░░ 13%`]}function ln(){return[` ▇▇▇▇▇▇▇▇▇▎ 89 Sarah K. /pricing 🇺🇸`,` ▇▇▇▇▇▇░░░░ 61 anon /docs 🇩🇪`,` ▇▇▇░░░░░░░ 34 anon /changelog 🇯🇵`]}function un(){return[` LCP ● 2.1s good ████████████░░░░░░`,` INP ● 89ms good ██████████████████`,` CLS ⚠ 0.14 needs ████████████░░░░░░`,` TTFB ● 380ms good ███████████████░░░`]}const X=[{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:sn},{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:cn},{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:ln},{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:un},{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.`]}],dn=8e3,fn=({width:e,height:t})=>{let{theme:n}=m(),[r,i]=M(0);j(()=>{if(X.length<=1)return;let e=setInterval(()=>{i(e=>(e+1)%X.length)},dn);return()=>clearInterval(e)},[]);let a=X[r],o=a.visual?a.visual():[];return A.createElement(E,{flexDirection:`column`,width:e,height:t,paddingX:2,paddingY:1},A.createElement(E,{marginBottom:1},A.createElement(D,{color:n.typography.label.color,dimColor:n.typography.label.dim},`LEARN`)),A.createElement(E,{marginBottom:1},A.createElement(D,{bold:!0,color:n.fg,wrap:`truncate`},a.title)),a.body.map((e,t)=>A.createElement(D,{key:t,color:n.muted,wrap:`truncate`},e||` `)),o.length>0&&A.createElement(E,{flexDirection:`column`,marginTop:1},o.map((e,t)=>A.createElement(D,{key:t,color:n.accent},e))),A.createElement(E,{flexGrow:1}),A.createElement(E,{flexDirection:`row`,marginTop:1},A.createElement(D,null,X.map((e,t)=>A.createElement(D,{key:t,color:t===r?n.accent:n.dim},t===r?`●`:`·`,t<X.length-1?` `:``))),A.createElement(D,{color:n.dim},` · `,r+1,` / `,X.length)))},pn={pending:`·`,active:`⠋`,done:`✓`,error:`✗`};function mn(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 hn=({tasks:e,width:t,height:n,liveLine:r})=>{let{theme:i}=m(),a=e.filter(e=>e.status===`done`).length;return A.createElement(E,{flexDirection:`column`,width:t,height:n,paddingX:2,paddingY:1},A.createElement(E,{marginBottom:1},A.createElement(D,{color:i.typography.label.color,dimColor:i.typography.label.dim},`TASKS`)),e.map(e=>A.createElement(E,{key:e.id,flexDirection:`column`},A.createElement(E,{flexDirection:`row`},e.status===`active`?A.createElement(D,{color:i.accent},A.createElement(P,{type:`dots`})):A.createElement(D,{color:mn(e.status,i)},pn[e.status]),A.createElement(D,null,` `),A.createElement(D,{color:e.status===`pending`?i.muted:i.fg,wrap:`truncate`},e.label)),e.detail&&A.createElement(E,{paddingLeft:2},A.createElement(D,{color:i.dim,wrap:`truncate`},e.detail)))),A.createElement(E,{flexGrow:1}),r&&A.createElement(E,{flexDirection:`row`,marginTop:1},A.createElement(D,{color:i.accent},`◆ `),A.createElement(D,{color:i.fg,wrap:`truncate`},r)),A.createElement(E,{marginTop:1},A.createElement(D,{color:i.dim},a,` / `,e.length)))};async function gn(e){if(o(e))return _n(e);let t=`quit`,n=null,r=await new Promise(r=>{let{unmount:i,waitUntilExit:a}=ee(A.createElement(vn,{opts:e,onExit:(e,a,o)=>{t=a??`quit`,n=o??null,i(),r(e)}}),{exitOnCtrlC:!0});a().catch(()=>r(1))});if(r===0&&await d().catch(()=>void 0),r!==0||t===`quit`||!n)return r;let i=n.id;if(t===`watch`){let{overviewCommand:t}=await import(`./overview-L8jqiSuU.js`);return t({cliVersion:e.cliVersion,siteId:i})}if(t===`events`){let{eventsTailCommand:t}=await import(`./events-tail-DEdVkmT0.js`);return t({cliVersion:e.cliVersion,siteId:i})}return 0}async function _n(t){let r=await import(`./telemetry-Bbh6Vtst.js`).catch(()=>null);r?.emit(`install.start`,{properties:{mode:`headless`}});try{let o=await e(),s=await _t(t.cwd);if(!s)return a({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;a({type:`framework.detected`,framework:s.id,confidence:1}),r?.emit(`install.framework_detected`,{properties:{framework:s.id}});let c=await i({strict:!1});if(!c&&!process.env.ZENOVAY_API_TOKEN)return a({type:`error`,code:`not_logged_in`,message:"Run `zenovay login` first (or set ZENOVAY_API_TOKEN)."}),2;let l=new n({config:o,cliVersion:t.cliVersion,token:c}),[u,d]=await Promise.all([l.getSites(),z(t.cwd,``).catch(()=>null)]),f;if(t.siteId){if(f=u.find(e=>e.id===t.siteId),!f)return a({type:`error`,code:`site_not_found`,message:`Site ${t.siteId} not found.`}),2}else if(d?.foundTrackingCodes.length){for(let e of d.foundTrackingCodes){let t=u.find(t=>t.trackingCode===e);if(t){f=t;break}}f||=u[0]}else f=u[0];if(!f)return a({type:`error`,code:`no_site`,message:`No sites exist; create one at app.zenovay.com or re-run interactively.`}),2;let p=f.trackingCode??f.id;if(d&&(d.recommendation===`no-op`||d.foundTrackingCodes.includes(p)))return a({type:`info`,message:`Zenovay already installed correctly for ${f.name} (${p})`}),a({type:`done`,command:`init`,exitCode:0}),0;a({type:`info`,message:`Using site ${f.id} (${f.name}) trackingCode=${f.trackingCode??f.id}`});let m=f.trackingCode??f.id,h=await W(t.cwd,{[s.envVarName]:m});if(a({type:`info`,message:`env vars added: ${h.addedKeys.join(`,`)}`}),s.id===`plain-html`){let e=await Ut({cwd:t.cwd,trackingCode:m,updateOnly:d?.recommendation===`update-tracking-code`});if(e.installed.length===0&&e.skipped.length===0)return a({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:s.id}}),1;a({type:`info`,message:`tracker injected into ${e.installed.length} file(s); ${e.skipped.length} already current; ${e.errors.length} error(s)`})}else return a({type:`error`,code:`headless_framework_unsupported`,message:`Headless install can only auto-inject the tracker for plain-HTML projects. For ${s.displayName}, run \`zenovay init\` interactively — the AI wizard places the <Script> in the correct entry file. (The env var ${h.addedKeys.join(`, `)||s.envVarName} was written.)`}),r?.emit(`install.error`,{error_code:`headless_framework_unsupported`,properties:{mode:`headless`,framework:s.id}}),1;return a({type:`done`,command:`init`,exitCode:0}),r?.emit(`install.success`,{properties:{framework:s.id,mode:`headless`,env_keys_added:h.addedKeys.length}}),0}catch(e){return a({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 vn=({opts:t,onExit:r})=>{let{exit:a}=te(),{theme:o}=m(),[s,c]=M(`intro`),[l,d]=M(null),[h,g]=M([]),[_,y]=M(null),[b,x]=M(null),[S,C]=M(null),[w,T]=M([]),[ee,k]=M(void 0),[N,F]=M(null),[re,I]=M(null),[ie,ae]=M(0),[oe,se]=M(!1),[L,R]=M(null),B=ne(null),ce=ne(!1);return O((e,t)=>{s===`error`&&(e.toLowerCase()===`q`||t.escape)&&(a(),r(1))}),j(()=>(process.stdout.isTTY&&process.stdout.write(`\x1B[?1049h\x1B[H`),()=>{B.current?.abort(),process.stdout.isTTY&&process.stdout.write(`\x1B[?1049l`)}),[]),j(()=>{ce.current||(ce.current=!0,(async()=>{try{c(`detecting`);let r=await _t(t.cwd);if(!r){C(`Could not detect your framework. Supported: Next.js, Nuxt, SvelteKit, Astro, Remix, plain HTML.`),c(`error`);return}d(r);let a=await i({strict:!1});!process.env.ZENOVAY_API_TOKEN&&!a&&(c(`login`),await u({cliVersion:t.cliVersion,offerCompletions:!1})),c(`loading-sites`);let o=await e(),s=await i({strict:!1}),l=new n({config:o,cliVersion:t.cliVersion,token:s}),[f,p]=await Promise.all([l.getSites(),z(t.cwd,``).catch(()=>null)]),m=await Fn(t.cwd);if(g(f),y(m),f.length===0){c(`create-site`);return}if(p?.foundTrackingCodes.length)for(let e of p.foundTrackingCodes){let t=f.find(t=>t.trackingCode===e);if(t){x(t),c(`already-installed`);return}}if(t.siteId){let e=f.find(e=>e.id===t.siteId);if(!e){C(`Site ${t.siteId} not found in your account.`),c(`error`);return}x(e),yn(e,r,t,{setPhase:c,setErrorMsg:C,setTasks:T,setLiveLine:k,setSandboxStats:F,setVerifyResult:I,setPendingApproval:R,registerBridge:e=>{B.current=e}});return}let h=In(f,m);if(t.yes&&h){x(h),yn(h,r,t,{setPhase:c,setErrorMsg:C,setTasks:T,setLiveLine:k,setSandboxStats:F,setVerifyResult:I,setPendingApproval:R,registerBridge:e=>{B.current=e}});return}c(`site-picker`)}catch(e){C(e.message),c(`error`)}})())},[]),j(()=>{s===`error`&&(B.current?.abort(),setTimeout(()=>{a(),r(1)},8e3))},[s]),A.createElement(E,{flexDirection:`column`},A.createElement(f,{version:t.cliVersion,subtitle:`AI install wizard`}),s===`intro`&&A.createElement(bn,null),s===`detecting`&&A.createElement(p,{title:`Scanning`,state:`busy`},A.createElement(E,null,A.createElement(D,{color:o.accent},A.createElement(P,{type:`dots`})),A.createElement(D,null,` Detecting framework…`))),s===`login`&&A.createElement(p,{title:`Authenticating`,state:`busy`},A.createElement(D,null,`Opening browser for login… (paste ZENOVAY_API_TOKEN env var to skip)`)),s===`loading-sites`&&A.createElement(p,{title:`Loading your sites`,state:`busy`},A.createElement(E,null,A.createElement(D,{color:o.accent},A.createElement(P,{type:`dots`})),A.createElement(D,null,` Fetching your Zenovay sites…`))),s===`already-installed`&&b&&A.createElement(Sn,{site:b,onContinue:()=>{c(`site-picker`)},onExit:()=>{a(),r(0,`quit`,b)}}),s===`site-picker`&&l&&A.createElement(Cn,{sites:h,preselectHint:_,onPick:e=>{if(e===`create-new`){c(`create-site`);return}x(e),yn(e,l,t,{setPhase:c,setErrorMsg:C,setTasks:T,setLiveLine:k,setSandboxStats:F,setVerifyResult:I,setPendingApproval:R,registerBridge:e=>{B.current=e}})}}),s===`create-site`&&A.createElement(p,{title:`Create a new site`,state:`warn`},A.createElement(D,{color:o.warn},"No site picked (or none exist yet). Visit https://app.zenovay.com/websites to create one, then re-run `zenovay init`."),A.createElement(D,{color:o.muted},`(Inline site creation from the CLI is scheduled for V1.1 — it requires a plan-limit check.)`)),s===`agent`&&l&&b&&A.createElement(xn,{adapter:l,site:b,tasks:w,liveLine:ee,pendingApproval:L,onApprove:e=>{L&&B.current?.resolve(L.id,e)}}),s===`install-complete`&&l&&b&&A.createElement(En,{adapter:l,site:b,stats:N,verify:re,onCommit:()=>c(`commit-prompt`),onSkipCommit:()=>c(`deploy-prompt`)}),s===`commit-prompt`&&b&&A.createElement(Dn,{cwd:t.cwd,onDone:e=>{e.committed&&k(`Pushed ${e.shortSha} to ${e.branch}`),c(`deploy-prompt`)},onError:e=>{C(e),c(`error`)}}),s===`deploy-prompt`&&b&&A.createElement(On,{site:b,onDeployed:()=>c(`visit-prompt`),onSkip:()=>c(`verify`)}),s===`visit-prompt`&&b&&A.createElement(kn,{site:b,onContinue:()=>c(`verify`)}),s===`verify`&&b&&A.createElement(jn,{site:b,elapsed:ie,onTick:e=>ae(e),onArrived:()=>{se(!0),c(`success`)},onTimeout:()=>c(`success`)}),s===`success`&&l&&b&&A.createElement(Tn,{adapter:l,site:b,stats:N,arrived:oe,onPick:e=>{a(),r(0,e,b)}}),s===`error`&&A.createElement(p,{title:`Install failed`,state:`err`},A.createElement(D,{color:o.error},S??`Unknown error`)),A.createElement(v,{items:s===`already-installed`?[{key:`q`,label:`quit`},{key:`r`,label:`re-run wizard`},{key:`ctrl-c`,label:`abort`}]:[{key:`q`,label:`quit`},{key:`ctrl-c`,label:`abort`}]}))};async function Z(e,t,n){n.setLiveLine(`Verifying the tracker is in your source…`);try{let r=await z(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 yn(r,a,o,s){try{s.setPhase(`agent`);let c=await e(),l=await i({strict:!1}),u=new n({config:c,cliVersion:o.cliVersion,token:l}),d=new he({cwd:o.cwd}),f=r.trackingCode??r.id;await t({defaultSiteId:r.id,defaultSiteName:r.name}).catch(()=>void 0);let p=await z(o.cwd,f);if(p.recommendation===`no-op`){s.setTasks(e=>e.map(e=>e.id===`detect`||e.id===`read`||e.id===`write`?{...e,status:`done`,detail:`already installed correctly`}:e)),s.setLiveLine(p.summary),s.setSandboxStats?.({reads:0,writes:0,rounds:0}),!o.skipMcp&&l&&await G({accessToken:l.accessToken}).catch(()=>void 0),s.setVerifyResult?.({ok:!0,detail:`Already installed correctly`}),s.setPhase(`install-complete`);return}if(p.competitors.length>0&&s.setLiveLine(`Detected ${p.competitors.map(e=>e.name).join(`, `)} — will install Zenovay alongside (won't touch their tags).`),a.id===`next-app-router`){s.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 (Cursor/Claude/VS Code)`,status:`pending`},{id:`verify`,label:`Verify the tracker in your source`,status:`pending`}]),s.setLiveLine(`Next.js — locating the document shell layout…`);let e=await Yt({cwd:o.cwd,trackingCode:f});if(!e.fellThrough&&e.errors.length===0){let t=e.installed[0]??`already installed`;s.setTasks(e=>e.map(e=>e.id===`read`||e.id===`write`?{...e,status:`done`,detail:t}:e));let n=await W(o.cwd,{[a.envVarName]:f});if(s.setTasks(e=>e.map(e=>e.id===`env`?{...e,status:`done`,detail:`${n.addedKeys.length} key(s) added`}:e)),!o.skipMcp&&l){let e=await G({accessToken:l.accessToken}).catch(()=>null);s.setTasks(t=>t.map(t=>t.id===`mcp`?{...t,status:`done`,detail:e&&e.installed.length>0?e.installed.join(`, `):`none detected`}:t))}else s.setTasks(e=>e.map(e=>e.id===`mcp`?{...e,status:`done`,detail:`skipped`}:e));await Z(o.cwd,f,s),s.setTasks(e=>e.map(e=>e.id===`verify`?{...e,status:`done`}:e)),s.setSandboxStats?.({reads:1,writes:e.installed.length,rounds:0}),s.setPhase(`install-complete`);return}s.setLiveLine(`Custom Next.js structure — handing off to the AI agent…`)}let m=a.id===`plain-html`;if(m){s.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 (Cursor/Claude/VS Code)`,status:`pending`},{id:`verify`,label:`Verify the tracker in your source`,status:`pending`}]),s.setLiveLine(`Plain HTML — using fast install path (no AI needed)…`);let e=await Ut({cwd:o.cwd,trackingCode:f,updateOnly:p.recommendation===`update-tracking-code`});if(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}`);s.setTasks(t=>t.map(t=>t.id===`read`||t.id===`write`?{...t,status:`done`,detail:`${e.installed.length} file(s)`}:t)),s.setLiveLine(`Tracker added to ${e.installed.length} file(s). Skipped ${e.skipped.length}, errored ${e.errors.length}.`);let t=await W(o.cwd,{[a.envVarName]:f});if(s.setTasks(e=>e.map(e=>e.id===`env`?{...e,status:`done`,detail:`${t.addedKeys.length} key(s) added`}:e)),!o.skipMcp&&l){let e=await G({accessToken:l.accessToken}).catch(()=>null);s.setTasks(t=>t.map(t=>t.id===`mcp`?{...t,status:`done`,detail:e&&e.installed.length>0?e.installed.join(`, `):`none detected`}:t))}else s.setTasks(e=>e.map(e=>e.id===`mcp`?{...e,status:`done`,detail:`skipped`}:e));await Z(o.cwd,f,s),s.setSandboxStats?.({reads:e.installed.length,writes:e.installed.length,rounds:0}),s.setPhase(`install-complete`);return}{let e=await Zt({cwd:o.cwd,trackingCode:f,siteId:r.id,adapter:a}),t=e.skipped.some(e=>/already present/.test(e.reason));if(!e.fellThrough&&e.errors.length===0&&(e.installed.length>0||t)){s.setTasks([{id:`detect`,label:`Detect framework`,status:`done`,detail:a.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 (Cursor/Claude/VS Code)`,status:`pending`},{id:`verify`,label:`Verify the tracker in your source`,status:`pending`}]),s.setLiveLine(`${a.displayName} — using fast install path (no AI needed)…`);let t=await W(o.cwd,{[a.envVarName]:f});if(s.setTasks(e=>e.map(e=>e.id===`env`?{...e,status:`done`,detail:`${t.addedKeys.length} key(s) added`}:e)),!o.skipMcp&&l){let e=await G({accessToken:l.accessToken}).catch(()=>null);s.setTasks(t=>t.map(t=>t.id===`mcp`?{...t,status:`done`,detail:e&&e.installed.length>0?e.installed.join(`, `):`none detected`}:t))}else s.setTasks(e=>e.map(e=>e.id===`mcp`?{...e,status:`done`,detail:`skipped`}:e));await Z(o.cwd,f,s),s.setTasks(e=>e.map(e=>e.id===`verify`?{...e,status:`done`}:e)),s.setSandboxStats?.({reads:1,writes:e.installed.length,rounds:0}),s.setPhase(`install-complete`);return}s.setLiveLine(`${a.displayName} — handing off to the AI agent…`)}let h=a.buildSnippets({trackingCode:f,siteId:r.id}),g=`Install Zenovay tracking into this ${a.displayName} project.\nSite: ${r.name} (trackingCode: ${f}).\n1. Call detect_framework to confirm the framework.\n2. Read the entry file(s) for this framework:\n`+a.files.map(e=>` - ${e.path}`).join(`
|
|
97
|
-
`)+`
|
|
98
|
-
3. Insert the tracker using the snippet below.
|
|
99
|
-
4. Confirm the change with a diff before writing.
|
|
100
|
-
|
|
101
|
-
Snippet reference (anchored by anchorKind — adapt to the actual file):
|
|
102
|
-
`+h.map(e=>` ${e.anchorKind} @ ${e.targetPath}:\n ${e.code.replace(/\n/g,`
|
|
103
|
-
`)}`).join(`
|
|
104
|
-
|
|
105
|
-
`);s.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 (Cursor/Claude/VS Code)`,status:`pending`},{id:`verify`,label:`Wait for first event`,status:`pending`}]);let _=(e,t,n)=>{s.setTasks(r=>r.map(r=>r.id===e?{...r,status:t,detail:n??r.detail}:r))},v=on({mode:an(o)});s.registerBridge(v);let y=v.subscribe(e=>s.setPendingApproval(e)),b=null;try{await Bt({api:u,sandbox:d,approval:v,prompter:{async ask({question:e}){return e}},handlers:{onToolStart:({name:e})=>{e===`detect_framework`?(_(`detect`,`active`),s.setLiveLine(`Inspecting package.json + config files…`)):e===`read_file`?(_(`detect`,`done`),_(`read`,`active`)):(e===`write_file`||e===`patch_file`)&&(_(`read`,`done`),_(`write`,`active`))},onToolResult:({name:e,result:t})=>{let n=t?.ok!==!1,r=t?.content??{};e===`detect_framework`&&n&&(_(`detect`,`done`,a.displayName),s.setLiveLine(`Detected ${a.displayName}`)),e===`read_file`&&n&&r.path&&s.setLiveLine(`Read ${r.path}`),(e===`write_file`||e===`patch_file`)&&n&&r.path&&s.setLiveLine(`Wrote ${r.path}`)},onDelta:e=>{let t=e.replace(/\s+/g,` `).trim();t.length>4&&s.setLiveLine(t.slice(0,80))}},initialMessages:[{role:`user`,content:g}],diagnosis:p,targetTrackingCode:f})}catch(e){b=e}finally{y(),s.setPendingApproval(null)}let x=d.stats();if(x.writes===0){let e=b?`Agent error: ${b.message}`:`Agent returned without writing any files (${x.reads} reads, ${x.rounds} rounds). The model may have refused or the AI Gateway may be misconfigured. Check api.zenovay.com logs.`;throw Error(e)}let S=a.files.map(e=>e.path),C=x.writtenPaths.some(e=>S.some(t=>e===t||e.endsWith(`/${t}`)));if(!C)throw Error(`Agent wrote to: [${x.writtenPaths.join(`, `)}] but never modified the framework's tracker target file(s): [${S.join(`, `)}]. The tracker is NOT installed. The model likely put the trackingCode into .env.local instead of into the HTML/JSX entry file.`);_(`write`,`done`),_(`env`,`active`),s.setLiveLine(`Adding env var to .env.local`);let w=await W(o.cwd,{[a.envVarName]:f});if(_(`env`,`done`,`${w.addedKeys.length} key(s) added`),!o.skipMcp&&l){_(`mcp`,`active`),s.setLiveLine(`Detecting Cursor / Claude Desktop / VS Code…`);let e=await G({accessToken:l.accessToken}).catch(()=>null);e&&e.installed.length>0?_(`mcp`,`done`,e.installed.join(`, `)):_(`mcp`,`done`,`none detected`)}else _(`mcp`,`done`,`skipped`);s.setTasks(e=>e.map(e=>e.id===`detect`||e.id===`read`||e.id===`write`?{...e,status:e.status===`pending`?`done`:e.status}:e)),await Z(o.cwd,f,s),s.setSandboxStats?.(x),s.setPhase(`install-complete`)}catch(e){s.setErrorMsg(e.message),s.setPhase(`error`)}}const bn=()=>{let{theme:e}=m();return A.createElement(p,{title:`Zenovay wants to set up your project`,state:`idle`},A.createElement(D,null,`We'll use AI to analyze your codebase and add the Zenovay tracker.`),A.createElement(D,{color:e.muted},`.env* contents stay on your machine. Only framework metadata reaches api.zenovay.com.`))},xn=({adapter:e,site:t,tasks:n,liveLine:r,pendingApproval:i,onApprove:a})=>{let{theme:o}=m(),s=process.stdout.columns??100,c=(process.stdout.rows??30)-8,l=Math.floor(s/2)-1,u=Math.max(14,c);return A.createElement(E,{flexDirection:`column`},A.createElement(E,{flexDirection:`row`,minHeight:u,borderStyle:`round`,borderColor:o.border},A.createElement(E,{width:l,flexDirection:`column`},A.createElement(fn,{width:l,height:u})),A.createElement(E,{width:1,flexDirection:`column`},A.createElement(D,{color:o.border},`│`)),A.createElement(E,{width:l,flexDirection:`column`},i?A.createElement(E,{flexDirection:`column`,paddingX:2,paddingTop:1},A.createElement(D,{color:o.warn},`The agent wants to write `,i.path),i.reason?A.createElement(D,{color:o.muted},i.reason):null,A.createElement(h,{key:i.id,filePath:i.path,oldContent:i.oldContent,newContent:i.newContent,onApprove:a})):A.createElement(A.Fragment,null,A.createElement(E,{paddingX:2,paddingTop:1},A.createElement(g,{done:n.filter(e=>e.status===`done`).length,total:n.length,label:n.find(e=>e.status===`active`)?.label})),A.createElement(hn,{tasks:n,liveLine:r,width:l,height:u})))),A.createElement(E,{marginTop:1},A.createElement(D,{color:o.muted},`Site: `,t.name,` · code: `,t.trackingCode??t.id,` · Framework: `,e.displayName)))},Sn=({site:e,onContinue:t,onExit:n})=>{let{theme:r}=m();O((e,r)=>{if(e===`q`||r.escape){n();return}if(e===`r`||e===`R`){t();return}});let i=e.url.replace(/^https?:\/\//,``).replace(/\/$/,``);return A.createElement(p,{title:`Already installed`,state:`ok`},A.createElement(E,{flexDirection:`column`,gap:1},A.createElement(E,{flexDirection:`row`,gap:1},A.createElement(D,{color:r.success},`✓`),A.createElement(D,{bold:!0},e.name),A.createElement(D,{color:r.muted},`(`,i,`)`)),A.createElement(D,{color:r.muted},`Zenovay is already tracking this project. No changes needed.`),e.trackingCode?A.createElement(D,{color:r.dim},`tracking code: `,e.trackingCode):null))},Cn=({sites:e,preselectHint:t,onPick:n})=>{let r=In(e,t),i=e.filter(e=>e.id!==r?.id),a=r?[r,...i]:i,o=[...a.map(e=>({label:Pn(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 A.createElement(p,{title:t?`Pick a site (best match: ${t})`:`Pick a site`,state:`idle`},A.createElement(_,{items:o,onSelect:n}))};function wn(){let e=process.argv[1]??``;return e.includes(`/_npx/`)||e.includes(`\\_npx\\`)||process.env.npm_execpath?.includes(`npx`)?`npx`:`global`}const Q=({k:e,primary:t})=>{let{theme:n}=m();return A.createElement(D,null,A.createElement(D,{color:n.muted},`[`),A.createElement(D,{bold:!0,color:t?n.accent:n.fg},e),A.createElement(D,{color:n.muted},`] `))},Tn=({adapter:e,site:t,stats:n,arrived:i,onPick:a})=>{let{theme:o}=m(),c=wn(),l=c===`npx`?`npx @zenovay/cli`:`zenovay`,u=r(t),d=n&&n.rounds>0?`${n.writes} file(s) · ${n.rounds} agent round(s)`:n&&n.writes>0?`${n.writes} file(s) · programmatic (no AI calls)`:null;return O((e,t)=>{let n=e.toLowerCase();n===`w`||t.return?a(`watch`):n===`o`?s(u).catch(()=>void 0):n===`e`?a(`events`):(n===`s`||n===`q`||t.escape)&&a(`quit`)},{isActive:!0}),A.createElement(p,{title:`You're live on Zenovay`,state:`ok`},A.createElement(D,{bold:!0,color:o.success},i?`✓ First event received from ${t.name}`:`✓ Installed successfully`),A.createElement(D,{color:o.accent},`─`.repeat(18)),A.createElement(E,{marginTop:1,flexDirection:`column`},A.createElement(Y,{label:`Framework`,value:e.displayName}),A.createElement(Y,{label:`Site`,value:A.createElement(J,{url:t.url,label:t.name})}),t.trackingCode?A.createElement(Y,{label:`Tracker`,value:A.createElement(D,{color:o.muted},t.trackingCode)}):null,d?A.createElement(Y,{label:`Changes`,value:A.createElement(D,{color:o.muted},d)}):null,A.createElement(Y,{label:`Dashboard`,value:A.createElement(J,{url:u})})),A.createElement(E,{marginTop:1,flexDirection:`column`},A.createElement(D,{color:o.dim},`WHAT'S NEXT`),A.createElement(E,{marginTop:1},A.createElement(D,null,` `),A.createElement(Q,{k:`W`,primary:!0}),A.createElement(D,null,`Watch live in this terminal `),A.createElement(D,{color:o.muted},`— visitors, pages, sources, vitals`)),A.createElement(E,null,A.createElement(D,null,` `),A.createElement(Q,{k:`O`}),A.createElement(D,null,`Open the dashboard in your browser`)),A.createElement(E,null,A.createElement(D,null,` `),A.createElement(Q,{k:`E`}),A.createElement(D,null,`Stream events as they fire `),A.createElement(D,{color:o.muted},`— page views, custom events, live`)),A.createElement(E,null,A.createElement(D,null,` `),A.createElement(Q,{k:`S`}),A.createElement(D,null,`Exit to shell`))),c===`npx`?A.createElement(E,{marginTop:1,flexDirection:`column`,borderStyle:`single`,borderColor:o.warn,paddingX:1},A.createElement(D,{color:o.warn,bold:!0},`Heads up — you ran via npx`),A.createElement(D,{color:o.muted},"The `zenovay` command isn't on your PATH yet. After you exit, run:"),A.createElement(E,{marginTop:1},A.createElement(D,{color:o.fg},` npm i -g @zenovay/cli `),A.createElement(D,{color:o.muted},"→ then `zenovay overview` works directly"))):A.createElement(E,{marginTop:1},A.createElement(D,{color:o.muted},`From your shell: `),A.createElement(D,{color:o.fg},l,` overview`),A.createElement(D,{color:o.muted},` · `),A.createElement(D,{color:o.fg},l,` --help`)))},En=({adapter:e,site:t,stats:n,verify:r,onCommit:i,onSkipCommit:a})=>{let{theme:o}=m();return Mn(e=>{e===`y`||e===`Y`||e===`\r`?i():(e===`n`||e===`N`||e===`s`||e===`S`)&&a()}),A.createElement(p,{title:`Tracker installed`,state:r&&!r.ok?`warn`:`ok`},r?A.createElement(D,null,A.createElement(D,{color:r.ok?o.success:o.warn},r.ok?`✔ Verified — `:`⚠ `),r.detail):A.createElement(D,null,A.createElement(D,{color:o.success},`✔ `),`The Zenovay tracker is in your project.`),A.createElement(E,{marginTop:1},A.createElement(D,{color:o.muted},`Framework: `),A.createElement(D,null,e.displayName)),A.createElement(E,null,A.createElement(D,{color:o.muted},`Site: `),A.createElement(D,null,t.name,` (`,t.url,`)`)),n&&A.createElement(E,null,A.createElement(D,{color:o.muted},`Modified: `),A.createElement(D,null,n.writes,` file(s)`)),A.createElement(E,{marginTop:1},A.createElement(D,null,`Commit + push these changes to git? `),A.createElement(D,{color:o.accent},`[Y/n]`)))},Dn=({cwd:e,onDone:t,onError:n})=>{let{theme:r}=m(),[i,a]=M(`committing`),[o,s]=M(`Staging changes…`);return j(()=>{(async()=>{try{let n=await Nn(e,e=>s(e),e=>a(e));n.committed?s(`Pushed ${n.shortSha} to origin/${n.branch}`):s(`No changes to commit (already up-to-date).`),setTimeout(()=>t(n),800)}catch(e){n(e.message)}})()},[]),A.createElement(p,{title:`Committing to git`,state:`busy`},A.createElement(E,null,A.createElement(D,{color:r.accent},A.createElement(P,{type:`dots`})),A.createElement(D,null,` `,i===`pushing`?`Pushing to origin`:`Committing`,`…`)),A.createElement(E,{marginTop:1},A.createElement(D,{color:r.muted},o)))},On=({site:e,onDeployed:t,onSkip:n})=>{let{theme:r}=m();return Mn(e=>{e===`y`||e===`Y`||e===`\r`||e===`d`||e===`D`?t():(e===`n`||e===`N`||e===`s`||e===`S`)&&n()}),A.createElement(p,{title:`Ready to deploy?`,state:`idle`},A.createElement(D,null,`The tracker is installed locally. To capture events you need it on the live site:`),A.createElement(D,null,` `),A.createElement(E,null,A.createElement(D,{color:r.muted},` → `),A.createElement(J,{url:e.url})),A.createElement(D,null,` `),A.createElement(D,{color:r.muted},`Push the change through your normal deploy pipeline (Vercel auto-deploy, CI/CD, etc.).`),A.createElement(E,{marginTop:1},A.createElement(D,null,`Once it's deployed, press `),A.createElement(D,{color:r.accent},`[Y]`),A.createElement(D,null,` to verify the tracker is firing. `),A.createElement(D,{color:r.muted},`[s] skip verification`)))},kn=({site:e,onContinue:t})=>{let{theme:n}=m();return Mn(()=>t()),A.createElement(p,{title:`Visit your site`,state:`idle`},A.createElement(D,null,`To send a test event, open any page on your site:`),A.createElement(D,null,` `),A.createElement(E,null,A.createElement(D,{color:n.muted},` → `),A.createElement(J,{url:e.url})),A.createElement(D,null,` `),A.createElement(D,{color:n.muted},`The tracker fires automatically on page load. We'll verify the next event arrives.`),A.createElement(E,{marginTop:1},A.createElement(D,null,`Press `),A.createElement(D,{color:n.accent},`[any key]`),A.createElement(D,null,` when you've visited the page.`)))};async function An(e,t){try{let n=await fetch(e,{headers:{"User-Agent":`zenovay-cli/preflight`},signal:AbortSignal.timeout(8e3),redirect:`follow`});if(!n.ok)return{state:`tracker-missing`,httpStatus:n.status};let r=await n.text(),i=/<script[^>]*src\s*=\s*["']https:\/\/(?:api|cdn)\.zenovay\.com\/[^"']+["'][^>]*>\s*<\/script>/gi,a=/data-id\s*=\s*["'](ZV_[A-Za-z0-9]+)["']/i,o=r.match(i)??[];if(o.length===0)return{state:`tracker-missing`};let s=Array.from(new Set(o.map(e=>e.match(a)?.[1]).filter(e=>!!e)));return s.includes(t)?{state:`tracker-correct`}:{state:`tracker-wrong-id`,foundCodes:s}}catch(e){return{state:`tracker-missing`,networkError:e.message}}}const jn=({site:t,elapsed:r,onTick:a,onArrived:o,onTimeout:s})=>{let{theme:c}=m(),[l,u]=M(`preflight`),[d,f]=M(``),[h,g]=M([]),_=ne(!1),v=t.trackingCode??t.id,y=async()=>{u(`preflight`),f(`Fetching ${t.url}…`);let e=await An(t.url,v);if(!_.current){if(e.state===`tracker-correct`){u(`polling`),f(`Tracker detected on live site — waiting for first hit…`),b();return}if(e.state===`tracker-wrong-id`){u(`wrong-id-on-live`),g(e.foundCodes),f(`Live site has Zenovay but with id(s): ${e.foundCodes.join(`, `)}`);return}u(`awaiting-deploy`),f(e.networkError?`Couldn't reach ${t.url}: ${e.networkError}`:e.httpStatus?`${t.url} returned HTTP ${e.httpStatus}`:`No Zenovay tracker found on ${t.url}.`)}},b=async()=>{let r=Date.now()-10*60*1e3;try{let s=await e(),c=await i({strict:!1}),l=new n({config:s,cliVersion:`0`,token:c}),d=await kt(t.id,r,{api:l,timeoutMs:6e4,pollIntervalMs:2500,onTick:e=>{_.current||a(e)}});if(_.current)return;d.received?(u(`success`),o()):u(`timeout`)}catch{_.current||u(`timeout`)}};j(()=>(_.current=!1,y(),()=>{_.current=!0}),[]),O(e=>{(l===`awaiting-deploy`||l===`wrong-id-on-live`||l===`timeout`)&&(e===`r`||e===`R`?y():(e===`s`||e===`S`)&&s())},{isActive:!0});let x=Math.floor(r/1e3);return l===`preflight`?A.createElement(p,{title:`Verifying`,state:`busy`},A.createElement(E,null,A.createElement(D,{color:c.accent},A.createElement(P,{type:`dots`})),A.createElement(D,null,` Checking your live site for the tracker…`)),A.createElement(E,{marginTop:1},A.createElement(D,{color:c.muted},d))):l===`awaiting-deploy`?A.createElement(p,{title:`Tracker not yet on your live site`,state:`warn`},A.createElement(D,{color:c.warn},d),A.createElement(E,{marginTop:1,flexDirection:`column`},A.createElement(D,null,`The tracker is in your local repo but hasn't been deployed yet.`),A.createElement(D,{color:c.muted},`Push your changes and wait for your deploy to finish (Vercel / Cloudflare Pages / CI), then retry.`)),A.createElement(E,{marginTop:1},A.createElement(D,null,`Press `),A.createElement(D,{color:c.accent},`[r]`),A.createElement(D,null,` to re-check, `),A.createElement(D,{color:c.accent},`[s]`),A.createElement(D,null,` to skip verification.`))):l===`wrong-id-on-live`?A.createElement(p,{title:`Live site has a different tracking code`,state:`warn`},A.createElement(D,{color:c.warn},`Expected: `,A.createElement(D,{color:c.accent},v),` `,`Found on live: `,A.createElement(D,{color:c.accent},h.join(`, `))),A.createElement(E,{marginTop:1,flexDirection:`column`},A.createElement(D,null,`Your local install uses a different ID than what's on `,t.url,`.`),A.createElement(D,{color:c.muted},`Deploy the new local version, then retry — or skip if the existing ID is intentional.`)),A.createElement(E,{marginTop:1},A.createElement(D,null,`Press `),A.createElement(D,{color:c.accent},`[r]`),A.createElement(D,null,` to re-check, `),A.createElement(D,{color:c.accent},`[s]`),A.createElement(D,null,` to skip.`))):l===`timeout`?A.createElement(p,{title:`No event arrived in 3 minutes`,state:`warn`},A.createElement(D,{color:c.warn},`The tracker is on your live site but no hits reached api.zenovay.com.`),A.createElement(E,{marginTop:1},A.createElement(D,{color:c.muted},`Try opening `,t.url,` in a fresh browser tab (no ad-blocker), then retry.`)),A.createElement(E,{marginTop:1},A.createElement(D,null,`Press `),A.createElement(D,{color:c.accent},`[r]`),A.createElement(D,null,` to re-check, `),A.createElement(D,{color:c.accent},`[s]`),A.createElement(D,null,` to finish without verification.`))):A.createElement(p,{title:`Waiting for first event`,state:`busy`},A.createElement(E,null,A.createElement(D,{color:c.accent},A.createElement(P,{type:`dots`})),A.createElement(D,null,` Polling api.zenovay.com for the first hit on `),A.createElement(D,{color:c.accent},t.url),A.createElement(D,null,` (`,x,`s elapsed)`)),A.createElement(E,{marginTop:1},A.createElement(D,{color:c.muted},`Reload the page if nothing arrives within ~30 seconds.`)))};function Mn(e){O((t,n)=>{e(t,{return:n.return,escape:n.escape})},{isActive:!0})}async function Nn(e,t,n){let{execFile:r}=await import(`node:child_process`),{promisify:i}=await import(`node:util`),a=i(r),o=async(t,n)=>{let{stdout:r}=await a(t,n,{cwd:e,maxBuffer:4e6});return r.trim()};try{await o(`git`,[`rev-parse`,`--is-inside-work-tree`])}catch{return t(`Not a git repository — skipped.`),{committed:!1}}let s=await o(`git`,[`status`,`--porcelain`]);if(!s)return{committed:!1};t(`Staging tracker changes…`),await o(`git`,[`add`,`-A`]),t(`Creating commit…`),await o(`git`,[`commit`,`-m`,`chore(zenovay): install tracking script via @zenovay/cli`]);let c=await o(`git`,[`rev-parse`,`--short`,`HEAD`]),l=await o(`git`,[`rev-parse`,`--abbrev-ref`,`HEAD`]);n(`pushing`),t(`Pushing to origin/${l}…`);try{await o(`git`,[`push`,`origin`,l])}catch(e){return t(`Commit ${c} created locally; push failed (${e.message.slice(0,80)}). Push manually with: git push origin ${l}`),{committed:!0,shortSha:c,branch:l}}return n(`done`),{committed:!0,shortSha:c,branch:l}}function Pn(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 Fn(e){try{let t=await x.readFile(b.join(e,`package.json`),`utf8`),n=JSON.parse(t);if(n.name)return String(n.name).replace(/^@[^/]+\//,``)}catch{}try{let t=await x.readFile(b.join(e,`.git`,`config`),`utf8`),n=t.match(/url\s*=\s*.*[/:]([^/]+?)(?:\.git)?\s*$/m);if(n&&n[1])return n[1]}catch{}return b.basename(e)}function In(e,t){if(!t||e.length===0)return e[0]??null;let n=$(t),r=e.find(e=>$(e.name)===n);if(r)return r;let i=e.find(e=>{let t=e.url.replace(/^https?:\/\//,``).replace(/\/.*$/,``),[r]=t.split(`.`);return $(r??``)===n});if(i)return i;let a=e.find(e=>{let t=$(e.name),r=$(e.url);return t.includes(n)||r.includes(n)||n.includes(t)||n.includes(r)});return a??e[0]??null}function $(e){return e.toLowerCase().replace(/[^a-z0-9]/g,``)}export{ce as detectInstalled,gn as initCommand};
|