@zenovay/cli 1.0.1 → 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.
- package/dist/{ai-DDefS75j.js → ai-B1ZHq3uM.js} +1 -1
- package/dist/{analytical-screen-B4xo6sII.js → analytical-screen-BvQa8oH6.js} +1 -1
- package/dist/analytics-S6AFt20R.js +1 -0
- package/dist/bin.js +8 -6
- package/dist/{companies-BFUFJkEM.js → companies-Cpb3yv2Q.js} +1 -1
- package/dist/{csv-emit-CmlDBfbA.js → csv-emit-B-5km-O-.js} +1 -1
- package/dist/{deploys-DLvmc21H.js → deploys-DZ0IR9Re.js} +1 -1
- package/dist/{devices-BMdSSO0o.js → devices-C_NjBY89.js} +1 -1
- package/dist/{doctor-BI6TF72T.js → doctor-BsEuqZTb.js} +1 -1
- package/dist/{errors-DTs33lNs.js → errors-DPRcy7WT.js} +1 -1
- package/dist/{export-BAFQahzg.js → export-DhSRfpg_.js} +1 -1
- package/dist/{funnel-CnkLL8HX.js → funnel-Cb4-3RJB.js} +1 -1
- package/dist/{geo-B9TL_gUX.js → geo-ReUNKl3F.js} +1 -1
- package/dist/{health-C6ZK4ZDk.js → health-DTR77eQW.js} +1 -1
- package/dist/{heatmaps-BLVXNROm.js → heatmaps-B-As729q.js} +1 -1
- package/dist/init-4u9IQ8h_.js +105 -0
- package/dist/{init-DJbtwhvX.js → init-kKTNK6nn.js} +1 -1
- package/dist/{insights-J4kYprJu.js → insights-BiqMftak.js} +1 -1
- package/dist/{journeys-BRqDOAqs.js → journeys-CogDUObU.js} +1 -1
- package/dist/{live-DJsNJ-fo.js → live-BNX4HBCf.js} +1 -1
- package/dist/{analytics-ZCtpMy4v.js → overview-CmTIumZy.js} +2 -2
- package/dist/overview-L8jqiSuU.js +1 -0
- package/dist/{pages-DXd2DGo6.js → pages-BYVz90uO.js} +1 -1
- package/dist/{projects-CTXvqzN8.js → projects-BdRZaLg8.js} +1 -1
- package/dist/{retention-DWQML_Jo.js → retention-DQHXVSG0.js} +1 -1
- package/dist/{revenue-Dm4wls0K.js → revenue-CitFZ4DN.js} +1 -1
- package/dist/{self-test-CEclBRpu.js → self-test-BcCqMRQ9.js} +1 -1
- package/dist/{sessions-KmEQ4zZp.js → sessions-dPZ32wpz.js} +1 -1
- package/dist/{sources-CJQtexqb.js → sources-lvpcvTTz.js} +1 -1
- package/dist/{stats-ctt0SOlE.js → stats-EeSDu70A.js} +1 -1
- package/dist/{uptime-Dgi5KItw.js → uptime-BA8vRzJQ.js} +1 -1
- package/dist/{visitors-CbU2tXXG.js → visitors-mjvSIKkI.js} +1 -1
- package/dist/{vitals-3NBHzH_m.js → vitals-D3sMQksQ.js} +1 -1
- package/dist/{webhooks-forward-CCd-RyJc.js → webhooks-forward-B8nnKB4f.js} +1 -1
- package/dist/wizard-bin.js +1 -1
- package/package.json +1 -1
- package/dist/init-CczZwsQf.js +0 -105
- package/dist/watch-GUa_JTOS.js +0 -1
- /package/dist/{annotation-aMzsv1oV.js → annotation-CZ2bEuyD.js} +0 -0
- /package/dist/{api-keys-x_GGL61a.js → api-keys-CLol-4YC.js} +0 -0
- /package/dist/{audit-VHsZwYPM.js → audit-CFlSb0g5.js} +0 -0
- /package/dist/{commands-BE8-kQ9U.js → commands-DVRYYbbn.js} +0 -0
- /package/dist/{completions-suqE20Pu.js → completions-XLznfo7H.js} +0 -0
- /package/dist/{csv-emit-C-9o-imN.js → csv-emit-BiRGo6SK.js} +0 -0
- /package/dist/{domains-CNv8-i1K.js → domains-ByXV1O4R.js} +0 -0
- /package/dist/{events-tail-CzYtpjey.js → events-tail-DEdVkmT0.js} +0 -0
- /package/dist/{examples-DikBW-H2.js → examples-CsQBLv9W.js} +0 -0
- /package/dist/{globe-CnpFQ9iU.js → globe-DwaTDQns.js} +0 -0
- /package/dist/{goals-DQqxuANi.js → goals-Ds0QZ4H6.js} +0 -0
- /package/dist/{health-Cg5Vtq-A.js → health-D6w7hF5q.js} +0 -0
- /package/dist/{home-CcQ7J4RY.js → home-DGYBSPWi.js} +0 -0
- /package/dist/{integrations-C3z-N73K.js → integrations-CCvt4xb_.js} +0 -0
- /package/dist/{logout-u6BpGCg6.js → logout-BoUfEnN9.js} +0 -0
- /package/dist/{notes-sFga-5H5.js → notes-BrY4efpr.js} +0 -0
- /package/dist/{plans-BhicnNJA.js → plans-DT8hilXl.js} +0 -0
- /package/dist/{profile-DsSj1vSw.js → profile-CDY3kFEq.js} +0 -0
- /package/dist/{query-Ds3hjKZ8.js → query-DLC0vi-K.js} +0 -0
- /package/dist/{range-tabs-BbJdVWNV.js → range-tabs-CH2cEXOf.js} +0 -0
- /package/dist/{settings-1kdqZcWp.js → settings-DO8UOasX.js} +0 -0
- /package/dist/{share-BsCpBNTV.js → share-BkvKZuPo.js} +0 -0
- /package/dist/{site-switcher-B2L1-Pjd.js → site-switcher-BAoYWp18.js} +0 -0
- /package/dist/{status-agent-CMpp3zEX.js → status-agent-BLIJc81G.js} +0 -0
- /package/dist/{team-CyzZCg--.js → team-Bw6dcpI2.js} +0 -0
- /package/dist/{teams-DnOLx5tK.js → teams-cwzXaqBH.js} +0 -0
- /package/dist/{telemetry-C-0DECLq.js → telemetry-CgyMy4hV.js} +0 -0
- /package/dist/{themes-6H0KlK3b.js → themes-BC8U4Od4.js} +0 -0
- /package/dist/{tour-fOYY-mK0.js → tour-ChHRo89U.js} +0 -0
- /package/dist/{ui-C5Te-OTJ.js → ui-BTnLAro-.js} +0 -0
- /package/dist/{update-C72vyFU1.js → update-DkMxLJbM.js} +0 -0
- /package/dist/{usage-BOlapdBM.js → usage-CkyXScnm.js} +0 -0
- /package/dist/{use-DBiMOOkB.js → use-BW8rVPgW.js} +0 -0
- /package/dist/{webhooks-CrE9paQf.js → webhooks-D1PNfhgJ.js} +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import{mocha as e}from"./theme-Brz9wK0w.js";import{spawn as t}from"node:child_process";import n from"chalk";const r=3e4,i=4,a=1e3;function o(e,t){let n=e.requires;if(!n)return null;if(n.auth!==!1&&!t.authenticated)return`not authenticated`;if(n.tier&&t.currentTier){let e={free:0,pro:1,scale:2,enterprise:3},r=e[t.currentTier]??0,i=e[n.tier]??99}return n.multipleTeams&&!t.hasMultipleTeams?`requires 2+ teams`:n.freeTeam&&!t.hasFreeTeam?`requires a Free-tier team`:null}function s(e,n,r,i){return new Promise(a=>{let o=/\.[mc]?js$/.test(e),s=o?`node`:e,c=o?[e,...n]:n,l=t(s,c,{env:{...process.env,ZENOVAY_NO_UPDATE_CHECK:`1`,...i},stdio:[`ignore`,`pipe`,`pipe`]}),u=``,d=``,f=!1,p=setTimeout(()=>{f=!0;try{l.kill(`SIGKILL`)}catch{}},r);l.stdout?.on(`data`,e=>{u+=e.toString(`utf8`),u.length>1048576&&(u=u.slice(0,1048576))}),l.stderr?.on(`data`,e=>{d+=e.toString(`utf8`),d.length>1048576&&(d=d.slice(0,1048576))}),l.on(`error`,e=>{clearTimeout(p),a({stdout:u,stderr:d+`\n[spawn error: ${e.message}]`,exitCode:-1,timedOut:f})}),l.on(`close`,e=>{clearTimeout(p),a({stdout:u,stderr:d,exitCode:e??0,timedOut:f})})})}async function c(e,t){let n=Date.now(),i=o(e,t.env);if(i)return{name:e.name,category:e.category,status:`skip`,durationMs:0,reason:i};if(e.inProcess)try{let t=await e.inProcess(),r=Date.now()-n;return t.ok?{name:e.name,category:e.category,status:`pass`,durationMs:r,...t.detail?{detail:t.detail}:{}}:{name:e.name,category:e.category,status:`fail`,durationMs:r,reason:t.reason}}catch(t){return{name:e.name,category:e.category,status:`fail`,durationMs:Date.now()-n,reason:t.message}}let c=e.name===`stack-leak.bad-net`?{ZENOVAY_API_BASE:`http://127.0.0.1:1`}:void 0,l=t.timeoutMs??r,u=await s(t.binPath,e.command,l,c),d=Date.now()-n;if(u.timedOut)return{name:e.name,category:e.category,status:`fail`,durationMs:d,reason:`timeout (${Math.round(l/1e3)}s)`,...t.verbose?{rawStdout:u.stdout.slice(0,a),rawStderr:u.stderr.slice(0,a)}:{}};let f;try{f=e.assert(u.stdout,u.stderr,u.exitCode)}catch(n){return{name:e.name,category:e.category,status:`fail`,durationMs:d,reason:`assert threw: ${n.message}`,...t.verbose?{rawStdout:u.stdout.slice(0,a),rawStderr:u.stderr.slice(0,a)}:{}}}return f.ok?{name:e.name,category:e.category,status:`pass`,durationMs:d,...f.detail?{detail:f.detail}:{},...t.verbose?{rawStdout:u.stdout.slice(0,a),rawStderr:u.stderr.slice(0,a)}:{}}:{name:e.name,category:e.category,status:`fail`,durationMs:d,reason:f.reason,...t.verbose?{rawStdout:u.stdout.slice(0,a),rawStderr:u.stderr.slice(0,a)}:{}}}async function l(e,t){let n=Date.now(),r=Math.max(1,t.parallel??i),a=Array(e.length).fill(void 0),o=[];for(let n=0;n<e.length;n++){let r=e[n];r&&(t.quick&&!r.quick||o.push(n))}let s=0,l=[],u=async()=>{for(;;){let n=s;if(s+=1,n>=o.length)return;let r=o[n];if(r===void 0)return;let i=e[r];if(!i)continue;let l=await c(i,t);a[r]=l,t.onResult?.(l)}};for(let e=0;e<r;e++)l.push(u());await Promise.all(l);let d=[];for(let e of a)e&&d.push(e);let f=d.filter(e=>e.status===`pass`).length,p=d.filter(e=>e.status===`fail`).length,m=d.filter(e=>e.status===`skip`).length;return{results:d,total:d.length,pass:f,fail:p,skip:m,durationMs:Date.now()-n}}async function u(e){let t={currentTier:null,hasMultipleTeams:!1,hasFreeTeam:!1,authenticated:!1};try{let{readToken:n}=await import(`./token-store-QTNSg4TT.js`),{readConfig:r}=await import(`./config-B72_Kfe0.js`),{ApiV2Client:i}=await import(`./api-v2-Co0dWAP5.js`),a=await n({strict:!1}).catch(()=>null);if(!a)return t;t.authenticated=!0;let o=await r(),s=new i({config:o,cliVersion:e,token:a}),c=await s.me();if(c.team?.plan){let e=c.team.plan.toLowerCase();(e===`free`||e===`pro`||e===`scale`||e===`enterprise`)&&(t.currentTier=e)}c.teams&&c.teams.length>=2&&(t.hasMultipleTeams=!0),(c.teams&&c.teams.some(e=>e.plan?.toLowerCase()===`free`)||t.currentTier===`free`)&&(t.hasFreeTeam=!0)}catch{}return t}function d(e){let t=e.trim();if(!t)return{ok:!1,reason:`empty stdout`};try{return{ok:!0,value:JSON.parse(t)}}catch{let e=t.split(`
|
|
2
2
|
`).filter(e=>e.trim().startsWith(`{`)||e.trim().startsWith(`[`)).pop();if(e)try{return{ok:!0,value:JSON.parse(e)}}catch{}return{ok:!1,reason:`stdout not JSON (got ${t.length} bytes)`}}}function f(e,t,n){if(n!==0)return{ok:!1,reason:`exit ${n}`};let r=d(e);return r.ok?{ok:!0}:{ok:!1,reason:r.reason}}function p(e,t,n){if(n!==0){let r=[e,t];for(let e of r)if(e.includes(`tier_insufficient`))return{ok:!0,detail:{gated:!0}};return{ok:!1,reason:`exit ${n} — ${(t||e).slice(0,80)}`}}let r=d(e);return r.ok?{ok:!0}:{ok:!1,reason:r.reason}}function m(e){if(typeof e!=`object`||!e)return!1;let t=e;if(Array.isArray(t.items)||Array.isArray(t.rows)||Array.isArray(t.data))return!0;if(typeof t.data==`object`&&t.data!==null){let e=t.data;if(Array.isArray(e.items)||Array.isArray(e.rows))return!0}return!1}const h=[{name:`analytics`,category:`ANALYTICS`,command:[`analytics`,`--json`],assert:(e,t,n)=>{let r=f(e,t,n);if(!r.ok)return r;let i=d(e);if(!i.ok)return{ok:!1,reason:i.reason};let a=i.value,o=a.visitors??a.data?.visitors,s=a.pageviews??a.data?.pageviews;return{ok:!0,detail:{visitors:o??null,pageviews:s??null}}},quick:!0},{name:`overview`,category:`ANALYTICS`,command:[`overview`,`--json`],assert:f},{name:`pages`,category:`ANALYTICS`,command:[`pages`,`--json`],assert:(e,t,n)=>{let r=f(e,t,n);if(!r.ok)return r;let i=d(e);if(!i.ok)return{ok:!1,reason:i.reason};let a=i.value,o=a.items??a.data?.items;return{ok:!0,detail:{rows:o?.length??0}}},quick:!0},{name:`sources`,category:`ANALYTICS`,command:[`sources`,`--json`],assert:f,quick:!0},{name:`devices`,category:`ANALYTICS`,command:[`devices`,`--json`],assert:f},{name:`geo`,category:`ANALYTICS`,command:[`geo`,`--json`],assert:f},{name:`live`,category:`ANALYTICS`,command:[`live`,`--json`],assert:(e,t,n)=>{let r=f(e,t,n);if(!r.ok)return r;let i=d(e);if(i.ok&&typeof i.value==`object`&&i.value!==null){let e=i.value,t=e.bounceRate??e.data?.bounceRate;if(typeof t==`number`&&(t<0||t>1))return{ok:!1,reason:`bounceRate semantics violated (got ${t}, expected 0..1)`}}return{ok:!0}}},{name:`revenue`,category:`ANALYTICS`,command:[`revenue`,`--json`],assert:f},{name:`funnels`,category:`ANALYTICS`,command:[`funnels`,`--json`],assert:p,requires:{tier:`pro`}},{name:`home`,category:`ANALYTICS`,command:[`home`,`--json`],assert:f},{name:`usage`,category:`ANALYTICS`,command:[`usage`,`--json`],assert:f,quick:!0},{name:`stats`,category:`ANALYTICS`,command:[`stats`,`--json`],assert:f},{name:`retention`,category:`BEHAVIOR`,command:[`retention`,`--json`],assert:p,requires:{tier:`pro`}},{name:`uptime`,category:`BEHAVIOR`,command:[`uptime`,`--json`],assert:p,requires:{tier:`pro`}},{name:`sessions`,category:`BEHAVIOR`,command:[`sessions`,`--json`],assert:p,requires:{tier:`pro`}},{name:`heatmaps`,category:`BEHAVIOR`,command:[`heatmaps`,`--json`],assert:p,requires:{tier:`pro`}},{name:`journeys`,category:`BEHAVIOR`,command:[`journeys`,`--json`],assert:p,requires:{tier:`pro`}},{name:`insights`,category:`INTELLIGENCE`,command:[`insights`,`--json`],assert:p,requires:{tier:`pro`}},{name:`domains list`,category:`MANAGE`,command:[`domains`,`list`,`--json`],assert:(e,t,n)=>{let r=f(e,t,n);if(!r.ok)return r;let i=d(e);return!i.ok||!m(i.value)?{ok:!1,reason:`expected list shape ({items|rows|data})`}:{ok:!0}},quick:!0},{name:`api-keys list`,category:`MANAGE`,command:[`api-keys`,`list`,`--json`],assert:(e,t,n)=>{let r=f(e,t,n);if(!r.ok)return r;let i=d(e);return!i.ok||!m(i.value)?{ok:!1,reason:`expected list shape`}:{ok:!0}}},{name:`team list`,category:`MANAGE`,command:[`team`,`list`,`--json`],assert:p,requires:{tier:`pro`}},{name:`webhooks list`,category:`MANAGE`,command:[`webhooks`,`list`,`--json`],assert:f},{name:`profile show`,category:`ACCOUNT`,command:[`profile`,`show`,`--json`],assert:f,quick:!0},{name:`plans info`,category:`ACCOUNT`,command:[`plans`,`info`,`--json`],assert:f},{name:`settings get`,category:`ACCOUNT`,command:[`settings`,`get`,`--json`],assert:f},{name:`integrations list`,category:`ACCOUNT`,command:[`integrations`,`list`,`--json`],assert:f},{name:`goals list`,category:`ACCOUNT`,command:[`goals`,`list`,`--json`],assert:p,requires:{tier:`pro`}},{name:`notes list`,category:`ACCOUNT`,command:[`notes`,`list`,`--json`],assert:f},{name:`audit list`,category:`ACCOUNT`,command:[`audit`,`list`,`--json`],assert:p,requires:{tier:`pro`}},{name:`share url`,category:`ACCOUNT`,command:[`share`,`url`,`--json`],assert:(e,t,n)=>n!==0&&n!==1&&n!==2?{ok:!1,reason:`unexpected exit ${n}`}:{ok:!0}},{name:`teams list`,category:`ACCOUNT`,command:[`teams`,`list`,`--json`],assert:f},{name:`health`,category:`OPERATIONS`,command:[`health`,`--json`],assert:(e,t,n)=>{let r=d(e);return r.ok?{ok:!0}:{ok:!1,reason:r.reason}},quick:!0},{name:`commands`,category:`OPERATIONS`,command:[`commands`,`--json`],assert:(e,t,n)=>{let r=f(e,t,n);if(!r.ok)return r;let i=d(e);if(!i.ok)return{ok:!1,reason:i.reason};let a=i.value,o=a.commands;return!Array.isArray(o)||o.length===0?{ok:!1,reason:`commands tree empty`}:{ok:!0,detail:{commands:o.length}}}},{name:`themes`,category:`OPERATIONS`,command:[`themes`,`--json`],assert:f},{name:`projects`,category:`OPERATIONS`,command:[`projects`,`--json`],assert:f},{name:`idor.cross-team`,category:`SECURITY`,command:[`domains`,`list`,`--site-id`,`00000000-0000-0000-0000-000000000001`,`--json`],assert:(e,t,n)=>{let r=e+t;return/forbidden|not_found|tier_insufficient|auth_required|auth_invalid/.test(r)?{ok:!0,detail:{rejected:!0}}:r.includes(`"items"`)||r.includes(`"rows"`)?{ok:!1,reason:`expected forbidden/not_found, got data`}:{ok:!0,detail:{rejected:`empty`}}},requires:{multipleTeams:!0},dev:!0},{name:`idor.bad-uuid`,category:`SECURITY`,command:[`analytics`,`--site-id`,`00000000-0000-0000-0000-000000000000`,`--json`],assert:(e,t,n)=>{let r=e+t;return/not_found|forbidden|auth_/.test(r)?{ok:!0,detail:{rejected:!0}}:/error|invalid|"code":/i.test(r)?{ok:!0,detail:{rejected:`error-shaped`}}:{ok:!1,reason:`silent zeros — expected not_found`}},quick:!0,dev:!0},{name:`tier-gate.retention`,category:`SECURITY`,command:[`retention`,`--json`],assert:(e,t,n)=>{let r=e+t;return r.includes(`tier_insufficient`)?{ok:!0,detail:{gated:`tier_insufficient`}}:/upgrade_required|tier_required/.test(r)?{ok:!0,detail:{gated:`legacy-or-transitional`}}:/"code":\s*"forbidden"/.test(r)&&/tier|upgrade|plan/i.test(r)?{ok:!0,detail:{gated:`forbidden+tier-message`}}:n===0&&!/"type"\s*:\s*"error"/.test(r)?{ok:!0,detail:{gated:`pass-through (Pro+ access)`}}:{ok:!1,reason:`gate did not behave as expected (no tier envelope and no clean pass-through)`}},dev:!0},{name:`stack-leak.bad-net`,category:`SECURITY`,command:[`analytics`,`--json`],assert:(e,t,n)=>{let r=e+t;return/\/Users\//.test(r)||/node:internal\//.test(r)?{ok:!1,reason:`stack trace leaked filesystem path`}:{ok:!0}},quick:!0},{name:`token-perms`,category:`SECURITY`,command:[],assert:()=>({ok:!1,reason:`should run in-process`}),inProcess:async()=>{let{stat:e}=await import(`node:fs/promises`),t=await import(`node:path`),n=process.env.HOME??process.env.USERPROFILE??``,r=process.env.XDG_CONFIG_HOME??t.join(n,`.config`),i=process.platform===`win32`?t.join(process.env.APPDATA??t.join(n,`AppData`,`Roaming`),`zenovay`,`auth.json`):t.join(r,`zenovay`,`auth.json`);try{let t=await e(i);if(process.platform===`win32`)return{ok:!0,detail:{mode:`win32-skip`}};let n=t.mode&511;return n===384?{ok:!0,detail:{mode:`0600`}}:{ok:!1,reason:`auth.json mode ${n.toString(8)} != 0600`}}catch(e){let t=e.code;return t===`ENOENT`?{ok:!0,detail:{mode:`no-auth-file`}}:{ok:!1,reason:e.message}}},quick:!0},{name:`secret-scrub`,category:`SECURITY`,command:[],assert:()=>({ok:!1,reason:`should run in-process`}),inProcess:async()=>{let{SECRET_PATTERNS:e,scrubSecrets:t}=await import(`./secrets-c-NB_plk.js`),n=[{name:`openai-proj`,sample:`sk-proj-abcdefghijklmnopqrstuvwxyz0123456789`},{name:`anthropic`,sample:`sk-ant-abcdefghijklmnopqrstuvwxyz0123456789`},{name:`openai-sk`,sample:`sk-abcdefghijklmnopqrstuvwxyz0123`},{name:`github-pat-new`,sample:`github_pat_`+`a`.repeat(82)},{name:`github-pat`,sample:`ghp_`+`a`.repeat(36)},{name:`github-oauth`,sample:`gho_`+`a`.repeat(36)},{name:`aws-access-key`,sample:`AKIAABCDEFGHIJKLMNOP`},{name:`stripe-live`,sample:`sk_live_`+`a`.repeat(28)},{name:`stripe-test`,sample:`pk_test_`+`a`.repeat(28)},{name:`stripe-restricted`,sample:`rk_live_`+`a`.repeat(28)},{name:`stripe-webhook`,sample:`whsec_`+`a`.repeat(28)},{name:`slack-bot`,sample:`xoxb-1234567890-abcdef`},{name:`google-api`,sample:`AIza`+`a`.repeat(35)},{name:`jwt`,sample:`eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTYifQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c`},{name:`private-key-rsa`,sample:`-----BEGIN RSA PRIVATE KEY-----`},{name:`private-key-pkcs8`,sample:`-----BEGIN PRIVATE KEY-----`},{name:`supabase-jwt`,sample:`eyJhbGciOi`+`a`.repeat(40)},{name:`resend-api`,sample:`re_`+`a`.repeat(20)},{name:`gitlab-pat`,sample:`glpat-`+`a`.repeat(20)},{name:`shopify`,sample:`shpat_`+`a`.repeat(32)},{name:`service-role-key`,sample:`service_role: "`+`a`.repeat(40)+`"`}],r=n.map(e=>`${e.name}=${e.sample}`).join(`
|
|
3
3
|
`),i=t(r),a=n.filter(e=>i.includes(`[REDACTED:${e.name}]`)).length,o=e.length,s=Math.max(18,o-4);return a>=s?{ok:!0,detail:{matched:a,total:o}}:{ok:!1,reason:`${a}/${o} patterns redacted (need >= ${s})`}},quick:!0},{name:`help-line-count`,category:`DISCOVERABILITY`,command:[`--help`],assert:(e,t,n)=>{let r=e.split(`
|
|
4
|
-
`).length;return r<90?{ok:!0,detail:{lines:r}}:{ok:!1,reason:`${r} lines (target < 90)`}},dev:!0},{name:`help-no-wave-markers`,category:`DISCOVERABILITY`,command:[`--help`],assert:(e,t,n)=>{let r=/\b(?:Wave\s*\d|W\d|V2\.1)\b/i,i=e.match(r);return i?{ok:!1,reason:`found marker: ${i[0]}`}:{ok:!0}},dev:!0},{name:`help-has-groups`,category:`DISCOVERABILITY`,command:[`--help`],assert:(e,t,n)=>{let r=[`ANALYTICS`,`BEHAVIOR`,`MANAGE`,`ACCOUNT`,`OPERATIONS`],i=r.filter(t=>!e.includes(t));return i.length===0?{ok:!0,detail:{found:r}}:{ok:!1,reason:`missing groups: ${i.join(`, `)}`}},dev:!0},{name:`examples-coverage`,category:`DISCOVERABILITY`,command:[],assert:()=>({ok:!1,reason:`should run in-process`}),inProcess:async()=>{let{EXAMPLES:e}=await import(`./examples-
|
|
4
|
+
`).length;return r<90?{ok:!0,detail:{lines:r}}:{ok:!1,reason:`${r} lines (target < 90)`}},dev:!0},{name:`help-no-wave-markers`,category:`DISCOVERABILITY`,command:[`--help`],assert:(e,t,n)=>{let r=/\b(?:Wave\s*\d|W\d|V2\.1)\b/i,i=e.match(r);return i?{ok:!1,reason:`found marker: ${i[0]}`}:{ok:!0}},dev:!0},{name:`help-has-groups`,category:`DISCOVERABILITY`,command:[`--help`],assert:(e,t,n)=>{let r=[`ANALYTICS`,`BEHAVIOR`,`MANAGE`,`ACCOUNT`,`OPERATIONS`],i=r.filter(t=>!e.includes(t));return i.length===0?{ok:!0,detail:{found:r}}:{ok:!1,reason:`missing groups: ${i.join(`, `)}`}},dev:!0},{name:`examples-coverage`,category:`DISCOVERABILITY`,command:[],assert:()=>({ok:!1,reason:`should run in-process`}),inProcess:async()=>{let{EXAMPLES:e}=await import(`./examples-CsQBLv9W.js`),t=Object.keys(e).length;return t>=25?{ok:!0,detail:{commands:t}}:{ok:!1,reason:`${t} commands have examples (need >= 25)`}},dev:!0},{name:`envelope-shape`,category:`DISCOVERABILITY`,command:[`commands`,`--json`],assert:(e,t,n)=>{if(n!==0)return{ok:!1,reason:`exit ${n}`};let r=d(e);if(!r.ok)return{ok:!1,reason:r.reason};let i=r.value,a=typeof i.version==`string`&&Array.isArray(i.commands);return a?{ok:!0,detail:{commands:i.commands.length}}:{ok:!1,reason:`commands payload missing version+commands`}},dev:!0}],g=h.length,_={accent:n.hex(e.accent),success:n.hex(e.success),error:n.hex(e.error),muted:n.hex(e.muted)};async function v(e){let t=(process.execPath||``).split(`/`).pop()||``,n=/^node(\.exe)?$/i.test(t),r=n?process.argv[1]??process.execPath:process.execPath,i=!!e.full||process.env.ZENOVAY_SELF_TEST_FULL===`1`,a=h.filter(e=>i||!e.dev);e.quick&&(a=a.filter(e=>e.quick));let o=await u(e.cliVersion);return e.json?y({...e,binPath:r,env:o,catalog:a}):S({...e,binPath:r,env:o,catalog:a})}async function y(e){let t=await l(e.catalog,{binPath:e.binPath,quick:e.quick??!1,verbose:e.verbose??!1,parallel:e.parallel,env:e.env,onResult:e=>{let t={type:`self-test.result`,name:e.name,category:e.category,status:e.status,durationMs:e.durationMs,...e.detail?{detail:e.detail}:{},...e.reason?{reason:e.reason}:{},...e.rawStdout?{rawStdout:e.rawStdout}:{},...e.rawStderr?{rawStderr:e.rawStderr}:{}};process.stdout.write(`${JSON.stringify(t)}\n`)}});return process.stdout.write(`${JSON.stringify({type:`self-test.summary`,total:t.total,pass:t.pass,fail:t.fail,skip:t.skip,durationMs:t.durationMs,cliVersion:e.cliVersion,env:e.env})}\n`),t.fail>0?1:0}const b=26,x=8;async function S(e){w(e.cliVersion,e.quick??!1,e.catalog.length);let t=new Map,n=0,r=null,i=new Map;for(let t of e.catalog)i.set(t.category,(i.get(t.category)??0)+1);let a=await l(e.catalog,{binPath:e.binPath,quick:e.quick??!1,verbose:e.verbose??!1,parallel:e.parallel,env:e.env,onResult:a=>{for(t.set(a.name,a);n<e.catalog.length;){let a=e.catalog[n];if(!a)break;let o=t.get(a.name);if(!o)break;r!==a.category&&(T(a.category,i.get(a.category)??0),r=a.category),E(a,o),t.delete(a.name),n+=1}}});return D(a),a.fail>0?1:0}function C(){return Math.max(60,process.stdout.columns??80)}function w(e,t,n){let r=Math.min(120,C()),i=r-2,a=`ZENOVAY · v${e}`,o=`self-test · ${t?`quick`:`full`} · ${n} test${n===1?``:`s`}`,s=`╭─ `+a+` `+`─`.repeat(Math.max(0,i-a.length-4))+`╮`,c=`│ `+o+` `.repeat(Math.max(0,i-o.length-2))+`│`,l=`╰`+`─`.repeat(i)+`╯`;process.stdout.write(_.accent(s)+`
|
|
5
5
|
`),process.stdout.write(_.accent(c)+`
|
|
6
6
|
`),process.stdout.write(_.accent(l)+`
|
|
7
7
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readConfig as e}from"./config-JVhBplSX.js";import"./api-CdcB84ie.js";import{readToken as t}from"./token-store-BvSCse1t.js";import{ApiV2Client as n}from"./api-v2-D0mvt__4.js";import{requireTier as r}from"./tier-DDIroQbc.js";import"./formatter-C4YSOKuq.js";import{emit$1 as i,isHeadless as a}from"./emit-D4YlMlzk.js";import{openInBrowser as o}from"./open-url-BtI5aLgL.js";import"./theme-Brz9wK0w.js";import{Banner as s,Panel as c,useTheme as l}from"./panel-CTtQ2ue6.js";import"./prompt-BXvg2B4R.js";import{Keybar as u}from"./keybar-DO5OoZy9.js";import{resolveSiteId as d}from"./resolve-site-BTVBMF1C.js";import{DataTable as f}from"./data-table-BhKjjiOS.js";import{EmptyState as p}from"./empty-state-D-krMX62.js";import{deepLinkFor as m}from"./keybar-deep-link-B4VJn2ko.js";import{useFullscreen as h}from"./use-fullscreen-ucSyZkjO.js";import{useSiteSwitcher as g}from"./site-switcher-
|
|
1
|
+
import{readConfig as e}from"./config-JVhBplSX.js";import"./api-CdcB84ie.js";import{readToken as t}from"./token-store-BvSCse1t.js";import{ApiV2Client as n}from"./api-v2-D0mvt__4.js";import{requireTier as r}from"./tier-DDIroQbc.js";import"./formatter-C4YSOKuq.js";import{emit$1 as i,isHeadless as a}from"./emit-D4YlMlzk.js";import{openInBrowser as o}from"./open-url-BtI5aLgL.js";import"./theme-Brz9wK0w.js";import{Banner as s,Panel as c,useTheme as l}from"./panel-CTtQ2ue6.js";import"./prompt-BXvg2B4R.js";import{Keybar as u}from"./keybar-DO5OoZy9.js";import{resolveSiteId as d}from"./resolve-site-BTVBMF1C.js";import{DataTable as f}from"./data-table-BhKjjiOS.js";import{EmptyState as p}from"./empty-state-D-krMX62.js";import{deepLinkFor as m}from"./keybar-deep-link-B4VJn2ko.js";import{useFullscreen as h}from"./use-fullscreen-ucSyZkjO.js";import{useSiteSwitcher as g}from"./site-switcher-BAoYWp18.js";import{Box as _,Text as v,render as y,useApp as b,useInput as x}from"ink";import S,{useEffect as C,useState as w}from"react";import T from"ink-spinner";function E(e){if(!e||e<=0)return`—`;let t=Math.floor(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60);return`${n}m ${(t%60).toString().padStart(2,`0`)}s`}function D(e){if(!e)return`—`;let t=Date.parse(e);if(Number.isNaN(t))return`—`;let n=Math.max(0,Math.floor((Date.now()-t)/1e3));return n<60?`${n}s`:n<3600?`${Math.floor(n/60)}m`:n<86400?`${Math.floor(n/3600)}h`:`${Math.floor(n/86400)}d`}async function O(o){let s=await e(),c=await t({strict:!1});if(!c)return process.stderr.write("Not logged in — run `zenovay login` first.\n"),2;let l=new n({config:s,cliVersion:o.cliVersion,token:c});try{await r(l,`pro`)}catch(e){return process.stderr.write(`${e.message}\n`),2}let u,f;try{({siteId:u,site:f}=await d(l,{explicit:o.siteId,headless:!!o.json,cliVersion:o.cliVersion}))}catch(e){return process.stderr.write(`${e.message}\n`),2}let p=f?.url?f.url.replace(/^https?:\/\//,``).replace(/\/$/,``):f?.name??u;if(a(o)){let e=await l.getSessions(u);return i({type:`sessions.snapshot`,data:e}),0}return new Promise(e=>{let{unmount:t}=y(S.createElement(k,{api:l,siteId:u,siteLabel:p,cliVersion:o.cliVersion,onExit:n=>{t(),e(n)}}))})}const k=({api:e,siteId:t,siteLabel:n,cliVersion:r,onExit:i})=>{h();let{exit:a}=b(),{theme:d}=l(),[y,O]=w(null),[k,A]=w(!0),[j,M]=w(null),[N,P]=w(t),[F,I]=w(n),L=g(e,N,e=>{P(e.id),I(e.url.replace(/^https?:\/\//,``).replace(/\/$/,``)),O(null)});if(x((e,t)=>{if(L.open){(t.escape||e===`s`)&&L.close();return}if(e===`o`||e===`O`){o(m(`sessions`,{siteId:N}));return}if(e===`s`){L.toggle();return}e===`q`&&(a(),i(0))}),C(()=>{let t=!1;return(async()=>{try{let n=await e.getSessions(N);t||(O(n),A(!1))}catch(e){t||(M(e.message),A(!1))}})(),()=>{t=!0}},[e,N]),k)return S.createElement(_,{flexDirection:`column`},S.createElement(s,{version:r,subtitle:`sessions · ${F}`}),S.createElement(c,{title:`Loading`,state:`busy`},S.createElement(_,null,S.createElement(v,{color:d.accent},S.createElement(T,{type:`dots`})),S.createElement(v,null,` Fetching sessions…`))));if(j)return S.createElement(_,{flexDirection:`column`},S.createElement(s,{version:r,subtitle:`sessions · ${F}`}),S.createElement(p,{reason:`error`,headline:`Failed to load`,hint:j}),L.overlay,S.createElement(u,{items:[{key:`s`,label:`site`},{key:`o`,label:`open in browser`},{key:`q`,label:`quit`}]}));if(!y||y.length===0)return S.createElement(_,{flexDirection:`column`},S.createElement(s,{version:r,subtitle:`sessions · ${F}`}),S.createElement(p,{reason:`no-data`,headline:`No replays yet`,hint:`Enable session replay in your site settings, press [s] to switch site, then revisit your site to capture one.`}),L.overlay,S.createElement(u,{items:[{key:`s`,label:`site`},{key:`o`,label:`open in browser`},{key:`q`,label:`quit`}]}));let R=[{key:`id`,label:`session id`,width:24},{key:`visitor`,label:`visitor`,width:18},{key:`duration`,label:`duration`,align:`right`,width:9,format:e=>E(e)},{key:`startedAt`,label:`when`,align:`right`,width:6,format:e=>D(String(e))},{key:`pageCount`,label:`events`,align:`right`,width:7},{key:`deviceType`,label:`device`,width:8,format:e=>String(e??`—`)}],z=process.stdout.rows??40,B=Math.max(4,z-15),V=y.slice(0,B),H=y.length-V.length;return S.createElement(_,{flexDirection:`column`},S.createElement(s,{version:r,subtitle:`sessions · ${F}`}),S.createElement(c,{title:`Recent sessions (${y.length})`},S.createElement(f,{columns:R,data:V,zebra:!0}),H>0?S.createElement(v,{color:d.dim},` +${H} more · run with --json for all`):null),S.createElement(_,{marginTop:1},S.createElement(v,{color:d.dim},`Open any session for replay at https://app.zenovay.com/replay`)),L.overlay,S.createElement(u,{items:[{key:`s`,label:`site`},{key:`o`,label:`open in browser`},{key:`q`,label:`quit`}],active:`o`}))};export{O as sessionsCommand};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{readConfig as e}from"./config-JVhBplSX.js";import"./api-CdcB84ie.js";import{readToken as t}from"./token-store-BvSCse1t.js";import"./error-codes-ByhvHx2M.js";import"./telemetry-BV-xvfdt.js";import{ApiV2Client as n}from"./api-v2-D0mvt__4.js";import{formatTabular as r,selectFormat as i}from"./formatter-C4YSOKuq.js";import{openInBrowser as a}from"./open-url-BtI5aLgL.js";import"./client-ntsEXSVC.js";import"./theme-Brz9wK0w.js";import{useTheme as o}from"./panel-CTtQ2ue6.js";import"./prompt-BXvg2B4R.js";import"./keybar-DO5OoZy9.js";import"./chat-panel-D9IjovCR.js";import{resolveSiteId as s}from"./resolve-site-BTVBMF1C.js";import{DataTable as c}from"./data-table-BhKjjiOS.js";import{EmptyState as l}from"./empty-state-D-krMX62.js";import"./grid-CMwhs-Ms.js";import{Bar as u}from"./bar-NfgovYHe.js";import{deepLinkFor as d}from"./keybar-deep-link-B4VJn2ko.js";import"./use-fullscreen-ucSyZkjO.js";import"./range-tabs-
|
|
1
|
+
import{readConfig as e}from"./config-JVhBplSX.js";import"./api-CdcB84ie.js";import{readToken as t}from"./token-store-BvSCse1t.js";import"./error-codes-ByhvHx2M.js";import"./telemetry-BV-xvfdt.js";import{ApiV2Client as n}from"./api-v2-D0mvt__4.js";import{formatTabular as r,selectFormat as i}from"./formatter-C4YSOKuq.js";import{openInBrowser as a}from"./open-url-BtI5aLgL.js";import"./client-ntsEXSVC.js";import"./theme-Brz9wK0w.js";import{useTheme as o}from"./panel-CTtQ2ue6.js";import"./prompt-BXvg2B4R.js";import"./keybar-DO5OoZy9.js";import"./chat-panel-D9IjovCR.js";import{resolveSiteId as s}from"./resolve-site-BTVBMF1C.js";import{DataTable as c}from"./data-table-BhKjjiOS.js";import{EmptyState as l}from"./empty-state-D-krMX62.js";import"./grid-CMwhs-Ms.js";import{Bar as u}from"./bar-NfgovYHe.js";import{deepLinkFor as d}from"./keybar-deep-link-B4VJn2ko.js";import"./use-fullscreen-ucSyZkjO.js";import"./range-tabs-CH2cEXOf.js";import{runAnalyticalScreen as f}from"./analytical-screen-BvQa8oH6.js";import{Box as p,Text as m}from"ink";import h from"react";function g(e){return e==null?{glyph:`·`,tone:`neutral`}:e>.5?{glyph:`▲`,tone:`up`}:e<-.5?{glyph:`▼`,tone:`down`}:{glyph:`→`,tone:`neutral`}}function _({data:e}){let{theme:t}=o();return h.createElement(m,null,h.createElement(m,{bold:!0},e.totalVisitors.toLocaleString()),` `,h.createElement(m,{color:t.muted},`visitors · `,e.sources.length,` sources`))}function v({data:e}){let{theme:t}=o();if(e.sources.length===0)return h.createElement(l,{reason:`no-data`,headline:`No source data yet`,hint:`Visit your site so referrers can be attributed, or widen the window with the number keys.`});let n={up:t.success,down:t.accent2,neutral:t.muted},r=e.totalVisitors||1,i=[...e.sources].sort((e,t)=>t.visitors-e.visitors).slice(0,12);return h.createElement(p,{flexDirection:`column`},i.map((e,i)=>{let a=e.visitors/r*100,o=g(e.delta);return h.createElement(p,{key:`${e.source}-${i}`,flexDirection:`row`},h.createElement(p,{width:20,marginRight:1,flexShrink:0},h.createElement(m,{wrap:`truncate`},e.source)),h.createElement(p,{flexShrink:0},h.createElement(u,{value:e.visitors,max:r,width:30,showPercent:!1,track:!0})),h.createElement(p,{width:7,marginLeft:1,flexShrink:0,justifyContent:`flex-end`},h.createElement(m,{color:t.fg},e.visitors.toLocaleString())),h.createElement(p,{width:8,marginLeft:1,flexShrink:0,justifyContent:`flex-end`},h.createElement(m,{color:t.muted},a.toFixed(1),`%`)),h.createElement(p,{width:2,marginLeft:1,flexShrink:0},h.createElement(m,{color:n[o.tone]},o.glyph)))}))}function y({data:e,columns:t}){return e.sources.length===0?h.createElement(l,{reason:`no-data`,headline:`No source data yet`,hint:`Visit your site so referrers can be attributed, or widen the window with [1-4].`}):h.createElement(c,{data:e.sources.slice(0,20),columns:t,headerStyle:`accent`})}async function b(o){let c=await e(),l=await t({strict:!1}),u=new n({config:c,cliVersion:o.cliVersion,token:l}),p,m;try{({siteId:p,site:m}=await s(u,{explicit:o.siteId,headless:!!(o.json||o.csv||o.tsv||o.ndjson),cliVersion:o.cliVersion}))}catch(e){return process.stderr.write(`${e.message}\n`),2}let g=i(o),b=o.period??`30d`,x=[{key:`source`,label:`source`,width:22},{key:`channel`,label:`channel`,width:10,format:e=>String(e??`—`)},{key:`visitors`,label:`visitors`,width:8,align:`right`},{key:`delta`,label:`Δ`,width:6,align:`right`,format:e=>typeof e==`number`?`${e>0?`+`:``}${(e*100).toFixed(1)}%`:`—`}];return f({cliVersion:o.cliVersion,title:`sources · ${m?.url?m.url.replace(/^https?:\/\//,``).replace(/\/$/,``):m?.name??p}`,commandName:`sources`,authToken:l?.accessToken??null,refreshIntervalMs:6e4,ranges:{windows:[`7d`,`30d`,`90d`]},fetcher:(e,t)=>u.getSources(p,t&&t!==`24h`?t:b,o.compare,e),format:g,ai:{api:u,siteId:p,siteLabel:m?.url?m.url.replace(/^https?:\/\//,``).replace(/\/$/,``):m?.name??p},keybindings:{o:{label:`open in browser`,handler:()=>{a(d(`sources`,{siteId:p}))}}},headlessEmit:(e,t)=>{if(t===`json`||t===`ndjson`){process.stdout.write(JSON.stringify(e,null,t===`json`?2:0)),t===`ndjson`&&process.stdout.write(`
|
|
2
2
|
`);return}process.stdout.write(r(e.sources,[`source`,`channel`,`visitors`,`conversions`,`revenue`,`delta`],t))},panels:[{id:`summary`,title:`Total`,render:e=>h.createElement(_,{data:e})},{id:`channels`,title:`By channel`,render:e=>h.createElement(v,{data:e})},{id:`table`,title:`Detail`,render:e=>h.createElement(y,{data:e,columns:x})}]})}export{b as sourcesCommand};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{readConfig as e}from"./config-JVhBplSX.js";import"./api-CdcB84ie.js";import{readToken as t}from"./token-store-BvSCse1t.js";import"./error-codes-ByhvHx2M.js";import"./telemetry-BV-xvfdt.js";import{ApiV2Client as n}from"./api-v2-D0mvt__4.js";import{formatTabular as r,selectFormat as i}from"./formatter-C4YSOKuq.js";import"./client-ntsEXSVC.js";import"./theme-Brz9wK0w.js";import{useTheme as a}from"./panel-CTtQ2ue6.js";import"./prompt-BXvg2B4R.js";import"./keybar-DO5OoZy9.js";import"./chat-panel-D9IjovCR.js";import{resolveSiteId as o}from"./resolve-site-BTVBMF1C.js";import{DataTable as s}from"./data-table-BhKjjiOS.js";import{EmptyState as c}from"./empty-state-D-krMX62.js";import"./grid-CMwhs-Ms.js";import"./use-fullscreen-ucSyZkjO.js";import"./range-tabs-
|
|
1
|
+
import{readConfig as e}from"./config-JVhBplSX.js";import"./api-CdcB84ie.js";import{readToken as t}from"./token-store-BvSCse1t.js";import"./error-codes-ByhvHx2M.js";import"./telemetry-BV-xvfdt.js";import{ApiV2Client as n}from"./api-v2-D0mvt__4.js";import{formatTabular as r,selectFormat as i}from"./formatter-C4YSOKuq.js";import"./client-ntsEXSVC.js";import"./theme-Brz9wK0w.js";import{useTheme as a}from"./panel-CTtQ2ue6.js";import"./prompt-BXvg2B4R.js";import"./keybar-DO5OoZy9.js";import"./chat-panel-D9IjovCR.js";import{resolveSiteId as o}from"./resolve-site-BTVBMF1C.js";import{DataTable as s}from"./data-table-BhKjjiOS.js";import{EmptyState as c}from"./empty-state-D-krMX62.js";import"./grid-CMwhs-Ms.js";import"./use-fullscreen-ucSyZkjO.js";import"./range-tabs-CH2cEXOf.js";import{runAnalyticalScreen as l}from"./analytical-screen-BvQa8oH6.js";import{Box as u,Text as d}from"ink";import f from"react";function p(e){return`${(e*100).toFixed(1)}%`}function m(e){return e<60?`${Math.round(e)}s`:e<3600?`${Math.floor(e/60)}m ${Math.round(e%60)}s`:`${Math.floor(e/3600)}h ${Math.floor(e%3600/60)}m`}const h=({data:e})=>{let{theme:t}=a();return f.createElement(u,{flexDirection:`column`},f.createElement(d,null,f.createElement(d,{bold:!0},e.visitors.toLocaleString()),f.createElement(d,{color:t.muted},` visitors `),f.createElement(d,{bold:!0},e.pageviews.toLocaleString()),f.createElement(d,{color:t.muted},` pageviews `),f.createElement(d,{bold:!0},e.sessions.toLocaleString()),f.createElement(d,{color:t.muted},` sessions`)),f.createElement(d,{color:t.muted},`bounce `,p(e.bounceRate),` · avg session `,m(e.avgSessionSec)))};async function g(a){let u=await e(),d=await t({strict:!1}),g=new n({config:u,cliVersion:a.cliVersion,token:d}),_,v;try{({siteId:_,site:v}=await o(g,{explicit:a.siteId,headless:!!(a.json||a.csv||a.tsv||a.ndjson),cliVersion:a.cliVersion}))}catch(e){return process.stderr.write(`${e.message}\n`),2}let y=i(a),b=a.range??`24h`,x=[{key:`url`,label:`page`,width:40,format:e=>String(e??`—`)},{key:`views`,label:`views`,width:8,align:`right`}],S=[{key:`country`,label:`country`,width:8},{key:`visitors`,label:`visitors`,width:8,align:`right`}];return l({cliVersion:a.cliVersion,title:`stats · ${v?.url?v.url.replace(/^https?:\/\//,``).replace(/\/$/,``):v?.name??_}`,commandName:`stats`,ranges:{windows:[`24h`,`7d`,`30d`]},ai:{api:g,siteId:_,siteLabel:v?.url?v.url.replace(/^https?:\/\//,``).replace(/\/$/,``):v?.name??_},authToken:d?.accessToken??null,refreshIntervalMs:a.watch?6e4:0,fetcher:(e,t)=>g.getStats(_,t??b,e),format:y,headlessEmit:(e,t)=>{if(t===`json`||t===`ndjson`){process.stdout.write(JSON.stringify(e,null,t===`json`?2:0)),t===`ndjson`&&process.stdout.write(`
|
|
2
2
|
`);return}process.stdout.write(r([{range:b,visitors:e.visitors,pageviews:e.pageviews,sessions:e.sessions,bounceRate:p(e.bounceRate),avgSession:m(e.avgSessionSec)}],[`range`,`visitors`,`pageviews`,`sessions`,`bounceRate`,`avgSession`],t))},panels:[{id:`summary`,title:`Summary`,render:e=>f.createElement(h,{data:e})},{id:`pages`,title:`Top pages`,render:e=>e.topPages.length===0?f.createElement(c,{reason:`no-data`,headline:`No pages yet`,hint:`No page views in the ${b} window.`}):f.createElement(s,{data:e.topPages.slice(0,10),columns:x,headerStyle:`accent`})},{id:`countries`,title:`Top countries`,render:e=>e.topCountries.length===0?f.createElement(c,{reason:`no-data`,headline:`No country data yet`,hint:`No located visitors in the ${b} window.`}):f.createElement(s,{data:e.topCountries.slice(0,10),columns:S,headerStyle:`accent`})}]})}export{g as statsCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readConfig as e}from"./config-JVhBplSX.js";import"./api-CdcB84ie.js";import{readToken as t}from"./token-store-BvSCse1t.js";import{ApiV2Client as n}from"./api-v2-D0mvt__4.js";import{requireTier as r}from"./tier-DDIroQbc.js";import"./formatter-C4YSOKuq.js";import{emit$1 as i,isHeadless as a}from"./emit-D4YlMlzk.js";import{openInBrowser as o}from"./open-url-BtI5aLgL.js";import"./theme-Brz9wK0w.js";import{Banner as s,Panel as c,useTheme as l}from"./panel-CTtQ2ue6.js";import"./prompt-BXvg2B4R.js";import{Keybar as u}from"./keybar-DO5OoZy9.js";import{resolveSiteId as d}from"./resolve-site-BTVBMF1C.js";import{stripUrlPrefix as f}from"./fmt-xxIPQJX-.js";import{DataTable as p}from"./data-table-BhKjjiOS.js";import{EmptyState as m}from"./empty-state-D-krMX62.js";import{deepLinkFor as h}from"./keybar-deep-link-B4VJn2ko.js";import{useFullscreen as g}from"./use-fullscreen-ucSyZkjO.js";import{useSiteSwitcher as _}from"./site-switcher-
|
|
1
|
+
import{readConfig as e}from"./config-JVhBplSX.js";import"./api-CdcB84ie.js";import{readToken as t}from"./token-store-BvSCse1t.js";import{ApiV2Client as n}from"./api-v2-D0mvt__4.js";import{requireTier as r}from"./tier-DDIroQbc.js";import"./formatter-C4YSOKuq.js";import{emit$1 as i,isHeadless as a}from"./emit-D4YlMlzk.js";import{openInBrowser as o}from"./open-url-BtI5aLgL.js";import"./theme-Brz9wK0w.js";import{Banner as s,Panel as c,useTheme as l}from"./panel-CTtQ2ue6.js";import"./prompt-BXvg2B4R.js";import{Keybar as u}from"./keybar-DO5OoZy9.js";import{resolveSiteId as d}from"./resolve-site-BTVBMF1C.js";import{stripUrlPrefix as f}from"./fmt-xxIPQJX-.js";import{DataTable as p}from"./data-table-BhKjjiOS.js";import{EmptyState as m}from"./empty-state-D-krMX62.js";import{deepLinkFor as h}from"./keybar-deep-link-B4VJn2ko.js";import{useFullscreen as g}from"./use-fullscreen-ucSyZkjO.js";import{useSiteSwitcher as _}from"./site-switcher-BAoYWp18.js";import{Box as v,Text as y,render as b,useApp as x,useInput as S}from"ink";import C,{useEffect as w,useState as T}from"react";import E from"ink-spinner";function D(e){return e===`up`?`● up`:e===`down`?`● down`:`○ unknown`}function O(e){if(!e)return`—`;let t=Date.parse(e);if(Number.isNaN(t))return`—`;let n=Math.round((t-Date.now())/(1e3*60*60*24));return`${n}d`}function k(e,t){let n=Math.max(0,Math.round((t-e)/1e3));if(n<5)return`just now`;if(n<60)return`${n}s ago`;let r=Math.floor(n/60);return r<60?`${r}m ago`:`${Math.floor(r/60)}h ago`}async function A(o){let s=await e(),c=await t({strict:!1});if(!c)return process.stderr.write("Not logged in — run `zenovay login` first.\n"),2;let l=new n({config:s,cliVersion:o.cliVersion,token:c});try{await r(l,`pro`)}catch(e){return process.stderr.write(`${e.message}\n`),2}let u,f;try{({siteId:u,site:f}=await d(l,{explicit:o.siteId,headless:!!o.json,cliVersion:o.cliVersion}))}catch(e){return process.stderr.write(`${e.message}\n`),2}let p=f?.url?f.url.replace(/^https?:\/\//,``).replace(/\/$/,``):f?.name??u;if(a(o)){let e=await l.getUptime(u);return i({type:`uptime.snapshot`,data:e}),0}return new Promise(e=>{let{unmount:t}=b(C.createElement(j,{api:l,siteId:u,siteLabel:p,cliVersion:o.cliVersion,onExit:n=>{t(),e(n)}}))})}const j=({api:e,siteId:t,siteLabel:n,cliVersion:r,onExit:i})=>{g();let{exit:a}=x(),{theme:d}=l(),[b,A]=T(null),[j,M]=T(!0),[N,P]=T(null),[ee,F]=T(0),[I,L]=T(!1),[R,z]=T(null),[B,V]=T(()=>Date.now()),[H,U]=T(t),[W,G]=T(n),K=_(e,H,e=>{U(e.id),G(e.url.replace(/^https?:\/\//,``).replace(/\/$/,``)),A(null)}),q=[{key:`r`,label:`refresh`},{key:`s`,label:`site`},{key:`o`,label:`browser`},{key:`q`,label:`quit`}];if(S((e,t)=>{if(K.open){(t.escape||e===`s`)&&K.close();return}if(e===`r`||e===`R`){F(e=>e+1);return}if(e===`s`){K.toggle();return}if(e===`o`||e===`O`){o(h(`uptime`,{siteId:H}));return}e===`q`&&(a(),i(0))}),w(()=>{let e=setInterval(()=>V(Date.now()),5e3),t=setInterval(()=>F(e=>e+1),3e4);return()=>{clearInterval(e),clearInterval(t)}},[]),w(()=>{let t=!1;return b===null?M(!0):L(!0),(async()=>{try{let n=await e.getUptime(H);if(t)return;A(n.monitors),M(!1),L(!1),z(Date.now())}catch(e){t||(P(e.message),M(!1),L(!1))}})(),()=>{t=!0}},[e,H,ee]),j)return C.createElement(v,{flexDirection:`column`},C.createElement(s,{version:r,subtitle:`uptime · ${W}`,live:!1}),C.createElement(c,{title:`Loading`,state:`busy`},C.createElement(v,null,C.createElement(y,{color:d.accent},C.createElement(E,{type:`dots`})),C.createElement(y,null,` Fetching monitors…`))));if(N)return C.createElement(v,{flexDirection:`column`},C.createElement(s,{version:r,subtitle:`uptime · ${W}`,live:!1}),C.createElement(m,{reason:`error`,headline:`Couldn't load monitors`,hint:N}),C.createElement(u,{items:q,active:`r`}));if(!b||b.length===0)return C.createElement(v,{flexDirection:`column`},C.createElement(s,{version:r,subtitle:`uptime · ${W}`,live:!1}),C.createElement(m,{reason:`no-data`,headline:`No monitors configured`,hint:`Add an uptime monitor at app.zenovay.com/uptime, press [s] to switch site, then re-run.`}),K.overlay,C.createElement(u,{items:q,active:`r`}));let J=[{key:`url`,label:`monitor`,width:36,format:e=>f(String(e??``))},{key:`status`,label:`status`,width:11,format:e=>D(String(e))},{key:`p95ms`,label:`p95 ms`,align:`right`,width:8,format:e=>typeof e==`number`?String(e):`—`},{key:`sslExpiry`,label:`ssl exp`,align:`right`,width:8,format:e=>O(e)}],Y=process.stdout.rows??40,X=Math.max(4,Y-16),Z=b.slice(0,X),Q=b.length-Z.length,$=b.filter(e=>e.status===`down`).length,te=b.filter(e=>e.status===`up`).length;return C.createElement(v,{flexDirection:`column`},C.createElement(s,{version:r,subtitle:`uptime · ${W}`,live:!0}),C.createElement(v,{marginTop:1,flexDirection:`row`},C.createElement(y,{color:d.success},te,` up`),C.createElement(y,{color:d.dim},` · `),C.createElement(y,{color:$>0?d.error:d.dim},$,` down`)),C.createElement(v,{marginTop:1},C.createElement(c,{title:`Monitors (${b.length})`},C.createElement(p,{columns:J,data:Z,zebra:!0}),Q>0?C.createElement(y,{color:d.dim},` +${Q} more · run with --json for all`):null)),C.createElement(v,{marginTop:1},C.createElement(y,{color:d.dim},I?`↻ refreshing…`:R===null?``:`↻ updated ${k(R,B)} · [r] refresh`)),K.overlay,C.createElement(u,{items:q,active:`r`}))};export{A as uptimeCommand};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{readConfig as e}from"./config-JVhBplSX.js";import"./api-CdcB84ie.js";import{readToken as t}from"./token-store-BvSCse1t.js";import"./error-codes-ByhvHx2M.js";import"./telemetry-BV-xvfdt.js";import{ApiV2Client as n}from"./api-v2-D0mvt__4.js";import{formatTabular as r,selectFormat as i}from"./formatter-C4YSOKuq.js";import{openInBrowser as a}from"./open-url-BtI5aLgL.js";import"./client-ntsEXSVC.js";import"./theme-Brz9wK0w.js";import{useTheme as o}from"./panel-CTtQ2ue6.js";import"./prompt-BXvg2B4R.js";import"./keybar-DO5OoZy9.js";import{brailleSpark as s,spark as c}from"./sparkline-CpoBjjlc.js";import"./chat-panel-D9IjovCR.js";import{resolveSiteId as l}from"./resolve-site-BTVBMF1C.js";import{DataTable as u}from"./data-table-BhKjjiOS.js";import{EmptyState as d}from"./empty-state-D-krMX62.js";import"./grid-CMwhs-Ms.js";import{deepLinkFor as f}from"./keybar-deep-link-B4VJn2ko.js";import"./use-fullscreen-ucSyZkjO.js";import"./range-tabs-
|
|
1
|
+
import{readConfig as e}from"./config-JVhBplSX.js";import"./api-CdcB84ie.js";import{readToken as t}from"./token-store-BvSCse1t.js";import"./error-codes-ByhvHx2M.js";import"./telemetry-BV-xvfdt.js";import{ApiV2Client as n}from"./api-v2-D0mvt__4.js";import{formatTabular as r,selectFormat as i}from"./formatter-C4YSOKuq.js";import{openInBrowser as a}from"./open-url-BtI5aLgL.js";import"./client-ntsEXSVC.js";import"./theme-Brz9wK0w.js";import{useTheme as o}from"./panel-CTtQ2ue6.js";import"./prompt-BXvg2B4R.js";import"./keybar-DO5OoZy9.js";import{brailleSpark as s,spark as c}from"./sparkline-CpoBjjlc.js";import"./chat-panel-D9IjovCR.js";import{resolveSiteId as l}from"./resolve-site-BTVBMF1C.js";import{DataTable as u}from"./data-table-BhKjjiOS.js";import{EmptyState as d}from"./empty-state-D-krMX62.js";import"./grid-CMwhs-Ms.js";import{deepLinkFor as f}from"./keybar-deep-link-B4VJn2ko.js";import"./use-fullscreen-ucSyZkjO.js";import"./range-tabs-CH2cEXOf.js";import{runAnalyticalScreen as p}from"./analytical-screen-BvQa8oH6.js";import{Box as m,Text as h}from"ink";import g from"react";function _(e){let t=Math.max(0,Math.floor((Date.now()-new Date(e).getTime())/1e3));return t<60?`${t}s`:t<3600?`${Math.floor(t/60)}m`:t<86400?`${Math.floor(t/3600)}h`:`${Math.floor(t/86400)}d`}function v(e){let t=e,n=t.events??t.timeseries;return Array.isArray(n)&&n.length>0?c(n,8):`▁▁▁▁▁▁▁▁`}function y(e){let t=e;if(typeof t.sessionDurationSec==`number`)return t.sessionDurationSec;if(typeof t.sessionDurationMs==`number`)return Math.floor(t.sessionDurationMs/1e3);if(typeof t.durationMs==`number`)return Math.floor(t.durationMs/1e3);if(typeof t.duration==`number`)return Math.floor(t.duration/1e3);let n=Date.parse(e.startedAt);return Number.isNaN(n)?0:Math.max(0,Math.floor((Date.now()-n)/1e3))}async function b(o){let s=await e(),c=await t({strict:!1}),u=new n({config:s,cliVersion:o.cliVersion,token:c}),d,m;try{({siteId:d,site:m}=await l(u,{explicit:o.siteId,headless:!!(o.json||o.csv||o.tsv||o.ndjson),cliVersion:o.cliVersion}))}catch(e){return process.stderr.write(`${e.message}\n`),2}let h=m?.url?m.url.replace(/^https?:\/\//,``).replace(/\/$/,``):m?.name??d,b=i(o),C=o.limit??50,w=typeof o.minDuration==`number`&&o.minDuration>0?o.minDuration:0,T=e=>w<=0?e:e.filter(e=>y(e)>=w),E=6e4,D=e=>{let t=Date.parse(e.startedAt);return Number.isFinite(t)&&Date.now()-t<E},O=[{key:`startedAt`,label:``,width:5,format:(e,t)=>D(t)?`● new`:``},{key:`startedAt`,label:`when`,width:6,format:e=>_(String(e))},{key:`country`,label:`country`,width:7,format:e=>String(e??`—`)},{key:`city`,label:`city`,width:14,format:e=>String(e??`—`)},{key:`device`,label:`device`,width:7,format:e=>String(e??`—`)},{key:`page`,label:`page`,width:26,format:e=>String(e??`—`)},{key:`id`,label:`24h`,width:8,format:(e,t)=>v(t)}];return p({cliVersion:o.cliVersion,title:`visitors · ${h}`,commandName:`visitors`,ai:{api:u,siteId:d,siteLabel:h},authToken:c?.accessToken??null,refreshIntervalMs:1e4,fetcher:e=>u.getVisitors(d,{limit:C},e),format:b,keybindings:{o:{label:`open in browser`,handler:()=>{a(f(`visitors`,{siteId:d}))}}},headlessEmit:(e,t)=>{let n={...e,visitors:T(e.visitors)};if(t===`json`||t===`ndjson`){process.stdout.write(JSON.stringify(n,null,t===`json`?2:0)),t===`ndjson`&&process.stdout.write(`
|
|
2
2
|
`);return}let i=[`startedAt`,`country`,`city`,`device`,`page`];process.stdout.write(r(n.visitors,i,t))},panels:[{id:`live`,title:`Now`,render:e=>g.createElement(x,{visitors:T(e.visitors)})},{id:`visitors`,title:`Active sessions`,render:e=>g.createElement(S,{visitors:T(e.visitors),limit:C,columns:O})}]})}const x=({visitors:e})=>{let{theme:t}=o(),n=[...e].sort((e,t)=>Date.parse(t.startedAt)-Date.parse(e.startedAt)),r=n[0],i=Array(24*6).fill(0),a=Date.now();for(let t of e){let e=a-new Date(t.startedAt).getTime(),n=Math.floor(e/(10*60*1e3));n>=0&&n<i.length&&(i[i.length-1-n]+=1)}return g.createElement(m,{flexDirection:`column`},g.createElement(h,{bold:!0},e.length,` live`),g.createElement(h,{color:t.muted},s(i,40)),r?g.createElement(h,{color:t.muted},`top: `,r.city??r.country??`—`,` · `,r.page??`—`):null)},S=({visitors:e,limit:t,columns:n})=>{let r=[...e].sort((e,t)=>Date.parse(t.startedAt)-Date.parse(e.startedAt)).slice(0,t);return r.length===0?g.createElement(d,{reason:`no-data`,headline:`No active sessions yet`,hint:`Visitors appear here as they browse — this view polls every 10s.`}):g.createElement(u,{columns:n,data:r,headerStyle:`accent`})};export{b as visitorsCommand};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{readConfig as e}from"./config-JVhBplSX.js";import"./api-CdcB84ie.js";import{readToken as t}from"./token-store-BvSCse1t.js";import"./error-codes-ByhvHx2M.js";import"./telemetry-BV-xvfdt.js";import{ApiV2Client as n}from"./api-v2-D0mvt__4.js";import{formatTabular as r,selectFormat as i}from"./formatter-C4YSOKuq.js";import{openInBrowser as a}from"./open-url-BtI5aLgL.js";import"./client-ntsEXSVC.js";import"./theme-Brz9wK0w.js";import{useTheme as o}from"./panel-CTtQ2ue6.js";import"./prompt-BXvg2B4R.js";import"./keybar-DO5OoZy9.js";import"./chat-panel-D9IjovCR.js";import{resolveSiteId as s}from"./resolve-site-BTVBMF1C.js";import{DataTable as c}from"./data-table-BhKjjiOS.js";import{EmptyState as l}from"./empty-state-D-krMX62.js";import"./grid-CMwhs-Ms.js";import{deepLinkFor as u}from"./keybar-deep-link-B4VJn2ko.js";import"./use-fullscreen-ucSyZkjO.js";import"./range-tabs-
|
|
1
|
+
import{readConfig as e}from"./config-JVhBplSX.js";import"./api-CdcB84ie.js";import{readToken as t}from"./token-store-BvSCse1t.js";import"./error-codes-ByhvHx2M.js";import"./telemetry-BV-xvfdt.js";import{ApiV2Client as n}from"./api-v2-D0mvt__4.js";import{formatTabular as r,selectFormat as i}from"./formatter-C4YSOKuq.js";import{openInBrowser as a}from"./open-url-BtI5aLgL.js";import"./client-ntsEXSVC.js";import"./theme-Brz9wK0w.js";import{useTheme as o}from"./panel-CTtQ2ue6.js";import"./prompt-BXvg2B4R.js";import"./keybar-DO5OoZy9.js";import"./chat-panel-D9IjovCR.js";import{resolveSiteId as s}from"./resolve-site-BTVBMF1C.js";import{DataTable as c}from"./data-table-BhKjjiOS.js";import{EmptyState as l}from"./empty-state-D-krMX62.js";import"./grid-CMwhs-Ms.js";import{deepLinkFor as u}from"./keybar-deep-link-B4VJn2ko.js";import"./use-fullscreen-ucSyZkjO.js";import"./range-tabs-CH2cEXOf.js";import{runAnalyticalScreen as d}from"./analytical-screen-BvQa8oH6.js";import{Box as f,Text as p}from"ink";import m from"react";const h={lcp:{good:2500,poor:4e3},inp:{good:200,poor:500},cls:{good:.1,poor:.25},ttfb:{good:800,poor:1800},fcp:{good:1800,poor:3e3}};function g(e,t){let n=h[e];return t<=n.good?{label:`good`,tone:`good`}:t<=n.poor?{label:`needs`,tone:`needs`}:{label:`poor`,tone:`poor`}}function _(e,t){return e===`cls`?t.toFixed(3):t<1e3?`${Math.round(t)}ms`:`${(t/1e3).toFixed(2)}s`}function v({data:e}){let{theme:t}=o(),n={good:t.success,needs:t.warn,poor:t.error},r=t=>{let n=0,r=0;for(let i of e.vitals){let e=i[t]?.p75;typeof e==`number`&&(n+=e*i.samples,r+=i.samples)}return r>0?n/r:0},i=[`lcp`,`inp`,`cls`,`ttfb`,`fcp`];return m.createElement(f,{flexDirection:`column`},i.map(e=>{let t=r(e),i=g(e,t);return m.createElement(p,{key:e},m.createElement(p,{color:n[i.tone]},`● `),m.createElement(p,{bold:!0},e.toUpperCase().padEnd(5)),` `,m.createElement(p,null,_(e,t).padStart(8)),` `,m.createElement(p,{color:n[i.tone]},i.label))}))}function y({data:e,columns:t}){return e.vitals.length===0?m.createElement(l,{reason:`no-data`,headline:`No vitals data yet`,hint:`Core Web Vitals appear once real visitors load instrumented pages.`}):m.createElement(c,{data:e.vitals.slice(0,15),columns:t,headerStyle:`accent`})}async function b(o){let c=await e(),l=await t({strict:!1}),f=new n({config:c,cliVersion:o.cliVersion,token:l}),p,h;try{({siteId:p,site:h}=await s(f,{explicit:o.siteId,headless:!!(o.json||o.csv||o.tsv||o.ndjson),cliVersion:o.cliVersion}))}catch(e){return process.stderr.write(`${e.message}\n`),2}let g=i(o),b=[{key:`url`,label:`url`,width:32},{key:`device`,label:`device`,width:7,format:e=>String(e??`—`)},{key:`lcp`,label:`LCP p75`,width:9,align:`right`,format:e=>e&&typeof e==`object`&&`p75`in e?_(`lcp`,e.p75):`—`},{key:`inp`,label:`INP p75`,width:9,align:`right`,format:e=>e&&typeof e==`object`&&`p75`in e?_(`inp`,e.p75):`—`},{key:`cls`,label:`CLS p75`,width:9,align:`right`,format:e=>e&&typeof e==`object`&&`p75`in e?_(`cls`,e.p75):`—`},{key:`samples`,label:`n`,width:6,align:`right`}];return d({cliVersion:o.cliVersion,title:`vitals · ${h?.url?h.url.replace(/^https?:\/\//,``).replace(/\/$/,``):h?.name??p}`,commandName:`vitals`,ai:{api:f,siteId:p,siteLabel:h?.url?h.url.replace(/^https?:\/\//,``).replace(/\/$/,``):h?.name??p},authToken:l?.accessToken??null,refreshIntervalMs:o.watch?5*6e4:0,ranges:!0,fetcher:(e,t)=>f.getVitals(p,{url:o.url,device:o.device,window:t??o.window},e),format:g,keybindings:{o:{label:`open in browser`,handler:()=>{a(u(`vitals`,{siteId:p}))}}},headlessEmit:(e,t)=>{if(t===`json`||t===`ndjson`){process.stdout.write(JSON.stringify(e,null,t===`json`?2:0)),t===`ndjson`&&process.stdout.write(`
|
|
2
2
|
`);return}process.stdout.write(r(e.vitals,[`url`,`device`,`samples`],t))},panels:[{id:`summary`,title:`Site-wide p75`,render:e=>m.createElement(v,{data:e})},{id:`pages`,title:`Per-page`,render:e=>m.createElement(y,{data:e,columns:b})}]})}export{b as vitalsCommand};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{readConfig as e}from"./config-JVhBplSX.js";import"./api-CdcB84ie.js";import{readToken as t}from"./token-store-BvSCse1t.js";import{ApiV2Client as n}from"./api-v2-D0mvt__4.js";import"./theme-Brz9wK0w.js";import{Banner as r,Panel as i,useTheme as a}from"./panel-CTtQ2ue6.js";import"./progress-row-Afnt5Ng8.js";import"./prompt-BXvg2B4R.js";import{Keybar as o}from"./keybar-DO5OoZy9.js";import"./sparkline-CpoBjjlc.js";import{resolveSiteId as s}from"./resolve-site-BTVBMF1C.js";import"./data-table-BhKjjiOS.js";import"./bar-NfgovYHe.js";import"./ui-
|
|
1
|
+
import{readConfig as e}from"./config-JVhBplSX.js";import"./api-CdcB84ie.js";import{readToken as t}from"./token-store-BvSCse1t.js";import{ApiV2Client as n}from"./api-v2-D0mvt__4.js";import"./theme-Brz9wK0w.js";import{Banner as r,Panel as i,useTheme as a}from"./panel-CTtQ2ue6.js";import"./progress-row-Afnt5Ng8.js";import"./prompt-BXvg2B4R.js";import{Keybar as o}from"./keybar-DO5OoZy9.js";import"./sparkline-CpoBjjlc.js";import{resolveSiteId as s}from"./resolve-site-BTVBMF1C.js";import"./data-table-BhKjjiOS.js";import"./bar-NfgovYHe.js";import"./ui-BTnLAro-.js";import{Box as c,Text as l,render as u,useApp as d,useInput as f}from"ink";import p,{useEffect as m,useState as h}from"react";function g(e,t){let n=Math.max(0,Math.round((t-e)/1e3));if(n<5)return`just now`;if(n<60)return`${n}s ago`;let r=Math.floor(n/60);return r<60?`${r}m ago`:`${Math.floor(r/60)}h ago`}async function _(e,t){let n=new TextEncoder,r=await crypto.subtle.importKey(`raw`,n.encode(e),{name:`HMAC`,hash:`SHA-256`},!1,[`sign`]),i=await crypto.subtle.sign(`HMAC`,r,n.encode(t));return Array.from(new Uint8Array(i),e=>e.toString(16).padStart(2,`0`)).join(``)}function v({label:e,value:t,valueColor:n}){let{theme:r}=a();return p.createElement(c,{flexDirection:`row`},p.createElement(c,{width:14},p.createElement(l,{color:r.dim},e.toUpperCase())),p.createElement(c,{flexGrow:1},p.createElement(l,{color:n??r.fg,wrap:`truncate`},t)))}function y({stats:e,target:t}){let{theme:n}=a();return p.createElement(i,{title:`webhooks forward`,state:e.connected?`ok`:`busy`},p.createElement(v,{label:`public url`,value:e.publicUrl,valueColor:n.accent}),p.createElement(v,{label:`forwarding to`,value:t}),p.createElement(c,{flexDirection:`row`,marginTop:1},e.connected?p.createElement(l,{color:n.success},`● connected`):p.createElement(l,{color:n.warn},`○ connecting…`),p.createElement(l,{color:n.muted},` · `,e.total,` requests · `),p.createElement(l,{color:n.success},e.ok,` ok`),p.createElement(l,{color:n.muted},` · `),p.createElement(l,{color:e.err>0?n.error:n.muted},e.err,` err`),e.lastStatus===null?null:p.createElement(l,{color:n.muted},` · last HTTP `,e.lastStatus)),e.lastError?p.createElement(c,{flexDirection:`row`},p.createElement(l,{color:n.error,wrap:`truncate`},`last error: `,e.lastError)):null)}async function b(i){let v=await e(),b=await t({strict:!1});if(!b?.accessToken)return process.stderr.write("Not authenticated. Run `zenovay login` first.\n"),2;if(!i.to)return process.stderr.write(`Missing --to <url> (e.g. --to localhost:3000/webhook).
|
|
2
2
|
`),2;let x=i.to.match(/^https?:\/\//)?i.to:`http://${i.to}`,S=new n({config:v,cliVersion:i.cliVersion,token:b}),C,w;try{({siteId:C,site:w}=await s(S,{explicit:i.siteId,headless:!1,cliVersion:i.cliVersion}))}catch(e){return process.stderr.write(`${e.message}\n`),2}let T=w?.url?w.url.replace(/^https?:\/\//,``).replace(/\/$/,``):w?.name??C,E;try{E=await S.createTunnel(C,i.to)}catch(e){return process.stderr.write(`Failed to register tunnel: ${e.message}\n`),1}let D=i.sign?i.secret??E.tunnelKey:null,O=()=>{let{theme:e}=a(),{exit:t}=d(),[n,s]=h({total:0,ok:0,err:0,lastStatus:null,lastError:null,lastForwardedAt:null,publicUrl:E.publicUrl,wsUrl:E.wsUrl,connected:!1}),[u,v]=h(()=>Date.now());m(()=>{let e=setInterval(()=>v(Date.now()),5e3);return()=>clearInterval(e)},[]),f((e,n)=>{(e===`q`||n.escape)&&t()}),m(()=>{let e=new AbortController,t=async e=>{try{let t={...e.headers};delete t.host,delete t[`content-length`],D&&(t[`X-Zenovay-Signature`]=`sha256=${await _(D,e.body)}`);let n=await fetch(x,{method:e.method,headers:t,body:e.method===`GET`||e.method===`HEAD`?void 0:e.body}),r=await n.text(),i={};return n.headers.forEach((e,t)=>{i[t]=e}),s(e=>({...e,total:e.total+1,ok:e.ok+(n.ok?1:0),err:e.err+(n.ok?0:1),lastStatus:n.status,lastError:n.ok?null:`HTTP ${n.status}`,lastForwardedAt:Date.now()})),{status:n.status,headers:i,body:r}}catch(e){let t=e instanceof Error?e.message:String(e);return s(e=>({...e,total:e.total+1,err:e.err+1,lastError:t,lastForwardedAt:Date.now()})),{status:502,body:JSON.stringify({error:`cli_local_failed`,detail:t})}}};return(async()=>{let n=S.tunnelClient(E.wsUrl);s(e=>({...e,connected:!0}));try{await n.start(t,e.signal)}catch(e){s(t=>({...t,connected:!1,lastError:e.message}))}})(),()=>{e.abort()}},[]);let b=n.lastForwardedAt===null?n.connected?`↻ live · waiting for first webhook`:`↻ connecting…`:`↻ last forward ${g(n.lastForwardedAt,u)}`;return p.createElement(c,{flexDirection:`column`},p.createElement(r,{version:i.cliVersion,subtitle:`webhooks forward · ${T} · ${n.connected?`live`:`connecting`}`,live:n.connected}),p.createElement(y,{stats:n,target:`${x}${i.sign?` · HMAC-signed`:``}`}),p.createElement(c,{marginTop:1},p.createElement(l,{color:e.dim},b)),p.createElement(o,{items:[{key:`q`,label:`quit`},{key:`esc`,label:`quit`}]}))},{waitUntilExit:k}=u(p.createElement(O,null));return await k(),0}export{b as webhooksForwardCommand};
|
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-CczZwsQf.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 M,useState as N}from"react";import{globby as P}from"globby";import F from"ink-spinner";import{applyPatch as ne}from"diff";const I=[`@zenovay/tracker`,`@zenovay/next`,`@zenovay/nuxt`,`@zenovay/svelte`,`@zenovay/astro`,`@zenovay/remix`,`@zenovay/node`],re=[`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,L=/data-zenovay-site\s*[=:]\s*["'`]([^"'`]+)["'`]/i,R=/\binit\s*\(\s*['"`](ZV_[A-Za-z0-9]+)['"`]/g,z=[{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 B(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 I)if(e in i){n.zenovayInstalled=!0,n.packageMarker=e;break}}catch{}for(let t of re)try{await x.access(b.join(e,t)),n.zenovayInstalled=!0,n.configFile=t;break}catch{}let r=await P([`**/*.{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(L),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)){R.lastIndex=0;let e;for(;(e=R.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 z)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=se(n,t),n}function se(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 B(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 P(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=ne(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 P([`**/*.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 P([`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]=N(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(F,{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)}}));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{watchCommand:t}=await import(`./watch-GUa_JTOS.js`);return t({cliVersion:e.cliVersion,siteId:i})}if(t===`events`){let{eventsTailCommand:t}=await import(`./events-tail-CzYtpjey.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(),B(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]=N(`intro`),[l,d]=N(null),[h,g]=N([]),[_,y]=N(null),[b,x]=N(null),[S,C]=N(null),[w,T]=N([]),[ee,O]=N(void 0),[k,P]=N(null),[ne,I]=N(null),[re,ie]=N(0),[ae,oe]=N(!1),[L,R]=N(null),z=M(null),se=M(!1);return j(()=>(process.stdout.isTTY&&process.stdout.write(`\x1B[?1049h\x1B[H`),()=>{z.current?.abort(),process.stdout.isTTY&&process.stdout.write(`\x1B[?1049l`)}),[]),j(()=>{se.current||(se.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(),B(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:O,setSandboxStats:P,setVerifyResult:I,setPendingApproval:R,registerBridge:e=>{z.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:O,setSandboxStats:P,setVerifyResult:I,setPendingApproval:R,registerBridge:e=>{z.current=e}});return}c(`site-picker`)}catch(e){C(e.message),c(`error`)}})())},[]),j(()=>{s===`error`&&(z.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(F,{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(F,{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:O,setSandboxStats:P,setVerifyResult:I,setPendingApproval:R,registerBridge:e=>{z.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&&z.current?.resolve(L.id,e)}}),s===`install-complete`&&l&&b&&A.createElement(En,{adapter:l,site:b,stats:k,verify:ne,onCommit:()=>c(`commit-prompt`),onSkipCommit:()=>c(`deploy-prompt`)}),s===`commit-prompt`&&b&&A.createElement(Dn,{cwd:t.cwd,onDone:e=>{e.committed&&O(`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:re,onTick:e=>ie(e),onArrived:()=>{oe(!0),c(`success`)},onTimeout:()=>c(`success`)}),s===`success`&&l&&b&&A.createElement(Tn,{adapter:l,site:b,stats:k,arrived:ae,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 B(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 B(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 watch` works directly"))):A.createElement(E,{marginTop:1},A.createElement(D,{color:o.muted},`From your shell: `),A.createElement(D,{color:o.fg},l,` watch`),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]=N(`committing`),[o,s]=N(`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(F,{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]=N(`preflight`),[d,f]=N(``),[h,g]=N([]),_=M(!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(F,{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(F,{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};
|
package/dist/watch-GUa_JTOS.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{readConfig as e}from"./config-JVhBplSX.js";import"./api-CdcB84ie.js";import{readToken as t}from"./token-store-BvSCse1t.js";import{ApiV2Client as n}from"./api-v2-D0mvt__4.js";import"./formatter-C4YSOKuq.js";import{emit$1 as r,isHeadless as i}from"./emit-D4YlMlzk.js";import{openInBrowser as a}from"./open-url-BtI5aLgL.js";import{parseSseStream as o}from"./client-ntsEXSVC.js";import"./theme-Brz9wK0w.js";import{Banner as s,Panel as c,useTheme as l}from"./panel-CTtQ2ue6.js";import"./prompt-BXvg2B4R.js";import{Keybar as u}from"./keybar-DO5OoZy9.js";import{spark as d}from"./sparkline-CpoBjjlc.js";import{resolveSiteId as f}from"./resolve-site-BTVBMF1C.js";import{stripUrlPrefix as p}from"./fmt-xxIPQJX-.js";import{EmptyState as m}from"./empty-state-D-krMX62.js";import{tileWidths as h}from"./grid-CMwhs-Ms.js";import{deepLinkFor as g}from"./keybar-deep-link-B4VJn2ko.js";import{useFullscreen as _}from"./use-fullscreen-ucSyZkjO.js";import{z as v}from"zod";import{Box as y,Text as b,render as x,useApp as ee,useInput as te}from"ink";import S,{useEffect as C,useState as w}from"react";import ne from"ink-spinner";import T from"ink-text-input";const E=Math.PI*2;function D(e){let t=e,n=Math.PI*Math.sin(e);for(let e=0;e<6;e++){let e=2*t+Math.sin(2*t)-n,r=2+2*Math.cos(2*t);if(r===0)break;t-=e/r}return t}function O(e,t){if(e<-90||e>90||t<-180||t>180)return null;let n=e*Math.PI/180,r=t*Math.PI/180,i=D(n),a=r*Math.cos(i)/Math.PI,o=Math.sin(i);return{x:a,y:o}}function k(e){if(e)return!0;let t=process.env;if(t.NO_COLOR||t.ZENOVAY_GLOBE===`ascii`)return!0;let n=(t.LANG||t.LC_ALL||t.LC_CTYPE||``).toLowerCase();return!!(n&&!n.includes(`utf`))}function A(e,t){let n=e*2,r=t*4;return{dw:n,dh:r,bits:new Uint8Array(n*r)}}function j(e,t,n){t<0||t>=e.dw||n<0||n>=e.dh||(e.bits[n*e.dw+t]=1)}function M(e){let t=e.dw/2,n=e.dh/2,r=e.dw/2-1,i=e.dh/2-1,a=Math.max(e.dw,e.dh)*2;for(let o=0;o<a;o++){let s=o/a*E,c=Math.round(t+r*Math.cos(s)),l=Math.round(n+i*Math.sin(s));j(e,c,l)}}function N(e){let t=Math.floor(e.dh/2);for(let n=0;n<e.dw;n+=4)j(e,n,t)}function P(e,t){let n=e.dw/2,r=e.dh/2,i=e.dw/2-1,a=e.dh/2-1;for(let o of t){let t=O(o.lat,o.lng);if(!t)continue;let s=Math.round(n+t.x*i),c=Math.round(r-t.y*a);j(e,s,c),j(e,s+1,c),j(e,s,c+1),j(e,s+1,c+1)}}const F=[[0,0],[0,1],[0,2],[1,0],[1,1],[1,2],[0,3],[1,3]];function I(e,t,n){let r=0;for(let i=0;i<F.length;i++){let[a,o]=F[i],s=t*2+a,c=n*4+o;e.bits[c*e.dw+s]&&(r|=1<<i)}return r===0?` `:String.fromCodePoint(10240+r)}function L(e,t,n){let r=0;for(let i=0;i<4;i++)for(let a=0;a<2;a++){let o=t*2+a,s=n*4+i;e.bits[s*e.dw+o]&&r++}return r===0?` `:r<=2?`.`:r<=4?`:`:r<=6?`*`:`#`}function re({data:e,width:t=80,height:n=20,asciiOnly:r}){let{theme:i}=l(),a=k(r),o=A(t,n);M(o),N(o),P(o,e);let s=[];for(let e=0;e<n;e++){let n=``;for(let r=0;r<t;r++)n+=a?L(o,r,e):I(o,r,e);s.push(n)}return S.createElement(y,{flexDirection:`column`},s.map((e,t)=>S.createElement(b,{key:t,color:i.accent},e)),S.createElement(b,{color:i.muted},e.length,` live · `,a?`ascii mode`:`braille mode`))}function ie(e,t){let n=Math.max(0,Math.round((t-e)/1e3));if(n<5)return`just now`;if(n<60)return`${n}s ago`;let r=Math.floor(n/60);return r<60?`${r}m ago`:`${Math.floor(r/60)}h ago`}const ae=v.object({siteId:v.string().optional(),window:v.string().optional(),totalVisitors:v.number().optional(),visitors:v.object({count:v.number().optional(),series:v.array(v.number()).optional()}).optional(),topPages:v.array(v.object({path:v.string(),views:v.number().optional(),count:v.number().optional()})).optional(),sources:v.array(v.object({source:v.string(),visitors:v.number()})).optional()}).passthrough();async function R(a){let o=await e(),s=await t({strict:!1});if(!s)return process.stderr.write("Not logged in — run `zenovay login` first.\n"),2;let c=new n({config:o,cliVersion:a.cliVersion,token:s}),l;try{({siteId:l}=await f(c,{explicit:a.siteId,headless:!!a.json,cliVersion:a.cliVersion}))}catch(e){return process.stderr.write(`${e.message}\n`),2}if(i(a)){let e=await c.getDashboardSnapshot(l);return r({type:`watch.tick`,snapshot:e}),0}return new Promise(e=>{let{unmount:t}=x(S.createElement(z,{api:c,siteId:l,intervalMs:a.intervalMs??15e3,cliVersion:a.cliVersion,onExit:n=>{t(),e(n)}}))})}const z=({api:e,siteId:t,intervalMs:n,cliVersion:r,onExit:i})=>{_();let{theme:d}=l(),{exit:f}=ee(),[p,v]=w(null),[x,T]=w(null),[E,D]=w(null),[O,k]=w([]),[A,j]=w(!0),[M,N]=w(null),[P,F]=w(1),[I,L]=w(!1),[R,z]=w(!1),[B,W]=w(null),[ue,de]=w(()=>Date.now());te((e,n)=>{if(e===`o`||e===`O`){a(g(`watch`,{siteId:t}));return}if(e===`q`){f(),i(0);return}if(e===`?`||e===`/`){z(e=>!e);return}if(e===`g`){L(e=>!e);return}if(n.tab){F(e=>{let t=n.shift?(e+4)%6+1:e%6+1;return t});return}(e===`1`||e===`2`||e===`3`||e===`4`||e===`5`||e===`6`)&&F(Number(e))});let[fe,G]=w(!1);if(C(()=>{let r=!1,i=async()=>{try{let n=await e.getDashboardSnapshot(t);if(r)return;let i=ae.safeParse(n);if(!i.success){G(!0),j(!1);return}G(!1);let a=i.data,o={visitors:a.visitors??(typeof a.totalVisitors==`number`?{count:a.totalVisitors}:void 0),topPages:a.topPages?.map(e=>({path:e.path,views:e.views??e.count??0})),sources:a.sources};v(o),e.getVitals(t).then(e=>{r||T(e)},()=>{}),e.getGoals(t).then(e=>{r||D(e)},()=>{}),j(!1),N(null),W(Date.now())}catch(e){r||N(e.message)}};i();let a=setInterval(i,n);return()=>{r=!0,clearInterval(a)}},[e,t,n]),C(()=>{if(R)return;let e=setInterval(()=>de(Date.now()),5e3);return()=>clearInterval(e)},[R]),C(()=>{let n=new AbortController;return(async()=>{try{let r=await e.openEventsStream(t,n.signal);for await(let e of o(r))e.type===`error`&&k(t=>[...t,`[ERR ${e.code}] ${e.message}`].slice(-10))}catch{}})(),()=>n.abort()},[e,t]),A)return S.createElement(y,{flexDirection:`column`},S.createElement(s,{version:r,subtitle:`watch · ${t}`,live:!1}),S.createElement(c,{title:`Loading`,state:`busy`},S.createElement(y,null,S.createElement(b,{color:d.accent},S.createElement(ne,{type:`dots`})),S.createElement(b,null,` Fetching snapshot…`))));if(M&&!p)return S.createElement(y,{flexDirection:`column`},S.createElement(s,{version:r,subtitle:`watch · ${t}`,live:!1}),S.createElement(m,{reason:`error`,headline:`Failed to load`,hint:M}));if(fe&&!p)return S.createElement(y,{flexDirection:`column`},S.createElement(s,{version:r,subtitle:`watch · ${t}`,live:!1}),S.createElement(m,{reason:`error`,headline:`Couldn't load dashboard`,hint:"The server returned an unexpected shape. Try `zenovay update` to refresh the CLI."}));let K=process.stdout.columns??80,q=2,J=h(K,3,q),[Y,X,Z]=[J[0]??20,J[1]??20,J[2]??20],Q=process.stdout.rows??40,pe=Math.max(4,Q-16),$=Math.max(2,Math.min(8,Math.floor(pe/2))),me=[],he=(p?.visitors?.count??0)>0||(p?.topPages?.length??0)>0||(p?.sources?.length??0)>0;return S.createElement(y,{flexDirection:`column`},S.createElement(s,{version:r,subtitle:`watch · ${t}${I?` · globe`:``}`,live:he}),S.createElement(y,{flexDirection:`row`,width:K},S.createElement(y,{flexDirection:`column`,flexShrink:0,width:Y,marginRight:q},I?S.createElement(c,{title:`Live globe`,focused:P===1,width:Y},S.createElement(re,{data:me,width:Math.max(8,Y-4),height:Math.max(8,Math.min(12,$*2))})):S.createElement(se,{snapshot:p,focused:P===1,width:Y}),S.createElement(V,{events:O,focused:P===4,width:Y,rows:$})),S.createElement(y,{flexDirection:`column`,flexShrink:0,width:X,marginRight:q},S.createElement(ce,{snapshot:p,focused:P===2,width:X,rows:$}),S.createElement(H,{vitals:x,focused:P===5,width:X})),S.createElement(y,{flexDirection:`column`,flexShrink:0,width:Z},S.createElement(le,{snapshot:p,focused:P===3,width:Z,rows:$}),S.createElement(U,{goals:E,focused:P===6,width:Z,rows:$}))),R?S.createElement(oe,{api:e,siteId:t,width:K}):null,S.createElement(y,{marginTop:1},S.createElement(b,{color:d.dim},B===null?``:`↻ updated ${ie(B,ue)}`,` · watch is deprecated — use `,S.createElement(b,{color:d.accent},`zenovay overview`))),S.createElement(u,{items:[{key:`tab`,label:`next`},{key:`1-6`,label:`jump`},{key:`g`,label:I?`panels`:`globe`},{key:`?/`,label:R?`close chat`:`ai chat`},{key:`o`,label:`browser`},{key:`q`,label:`quit`}]}))},oe=({api:e,siteId:t,width:n})=>{let{theme:r}=l(),[i,a]=w(``),[s,u]=w([]),[d,f]=w(!1),[p,m]=w(``),[h,g]=w(null),_=async n=>{let r=n.trim();if(!r||d)return;g(null),a(``);let i=[...s,{role:`user`,content:r}];u(i),f(!0),m(``);try{let n=i.map(e=>({role:e.role,content:e.content})),r=await e.openAiStream(`chat`,{messages:n,siteId:t},void 0),a=``;for await(let e of o(r))if(e.type===`delta`)a+=e.content,m(a);else if(e.type===`error`)g(`${e.code}: ${e.message}`);else if(e.type===`done`)break;u([...i,{role:`assistant`,content:a}]),m(``)}catch(e){g(e instanceof Error?e.message:`chat failed`)}finally{f(!1)}};return S.createElement(y,{marginTop:1},S.createElement(c,{title:`AI chat (esc / ?/ to close)`,focused:!0,width:n},S.createElement(y,{flexDirection:`column`},s.slice(-6).map((e,t)=>S.createElement(y,{key:t,flexDirection:`column`,marginBottom:1},S.createElement(b,{color:e.role===`user`?r.accent:r.info,bold:!0},e.role===`user`?`you`:`zenovay`),S.createElement(b,null,e.content))),d&&p?S.createElement(y,{flexDirection:`column`,marginBottom:1},S.createElement(b,{color:r.info,bold:!0},`zenovay`),S.createElement(b,null,p)):null,h?S.createElement(b,{color:r.error},`✗ `,h):null,S.createElement(y,null,S.createElement(b,{color:r.accent},d?`⠋ `:`▸ `),S.createElement(T,{value:i,onChange:a,onSubmit:_,placeholder:d?`streaming…`:`ask anything about your analytics`})))))},B=({label:e,value:t})=>{let{theme:n}=l();return S.createElement(y,{flexDirection:`row`},S.createElement(y,{flexGrow:1,flexShrink:1,marginRight:1},S.createElement(b,{wrap:`truncate`},e)),S.createElement(y,{width:t.length,flexShrink:0},S.createElement(b,{color:n.fg},t)))},se=({snapshot:e,focused:t,width:n})=>{let{theme:r}=l(),i=e?.visitors?.count??0,a=e?.visitors?.series??[];return S.createElement(c,{title:`Visitors`,focused:t,width:n},S.createElement(b,{color:r.typography.headline.color,bold:r.typography.headline.bold},i.toLocaleString()),a.length>0?S.createElement(b,{color:r.accent},d(a,Math.max(8,n-6))):S.createElement(b,{color:r.dim},`no data yet`))},ce=({snapshot:e,focused:t,width:n,rows:r=5})=>{let i=e?.topPages??[],a=i.slice(0,r),o=i.length-a.length;return S.createElement(c,{title:`Top pages`,focused:t,width:n},i.length===0?S.createElement(m,{reason:`no-data`,headline:`No pages yet`}):S.createElement(S.Fragment,null,a.map(e=>S.createElement(B,{key:e.path,label:p(e.path),value:(e.views??0).toLocaleString()})),o>0?S.createElement(W,{count:o}):null))},le=({snapshot:e,focused:t,width:n,rows:r=5})=>{let i=e?.sources??[],a=i.slice(0,r),o=i.length-a.length;return S.createElement(c,{title:`Sources`,focused:t,width:n},i.length===0?S.createElement(m,{reason:`no-data`,headline:`No sources yet`}):S.createElement(S.Fragment,null,a.map(e=>S.createElement(B,{key:e.source,label:e.source,value:e.visitors.toLocaleString()})),o>0?S.createElement(W,{count:o}):null))},V=({events:e,focused:t,width:n,rows:r=5})=>{let{theme:i}=l(),a=e.slice(-r);return S.createElement(c,{title:`Errors`,focused:t,width:n},e.length===0?S.createElement(b,{color:i.dim},`no errors — stream healthy`):a.map((e,t)=>S.createElement(b,{key:t,wrap:`truncate`},e)))},H=({vitals:e,focused:t,width:n})=>{let{theme:r}=l(),i=(e,t,n)=>S.createElement(y,{key:e,flexDirection:`row`},S.createElement(y,{width:6},S.createElement(b,{color:r.dim},e)),S.createElement(y,{flexGrow:1,justifyContent:`flex-end`},S.createElement(b,{color:r.fg},typeof t==`number`?`${t.toFixed(0)}${n}`:`—`)));return S.createElement(c,{title:`Vitals`,focused:t,width:n},i(`LCP`,e?.lcpP75,`ms`),i(`INP`,e?.inpP75,`ms`),i(`CLS`,e?.clsP75?e.clsP75*1e3:void 0,`/1k`),i(`TTFB`,e?.ttfbP75,`ms`),i(`FCP`,e?.fcpP75,`ms`))},U=({goals:e,focused:t,width:n,rows:r=5})=>{let i=e?.goals??[],a=i.slice(0,r),o=i.length-a.length;return S.createElement(c,{title:`Goals`,focused:t,width:n},i.length===0?S.createElement(m,{reason:`no-data`,headline:`No goals yet`}):S.createElement(S.Fragment,null,a.map(e=>S.createElement(B,{key:e.name,label:e.name,value:e.completions.toLocaleString()})),o>0?S.createElement(W,{count:o}):null))},W=({count:e})=>{let{theme:t}=l();return S.createElement(b,{color:t.dim},` +${e} more`)};export{R as watchCommand};
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|