@lunora/cli
Version:
The Lunora CLI: init, dev, deploy, codegen, migrate, seed, doctor, insights, logs, registry, and the rest of the project commands
16 lines (14 loc) • 16.5 kB
JavaScript
import{V as ne}from"./cli.mjs";import{d as oe}from"../packem_shared/command-BpMv2n0o.mjs";import{EXIT_CODE as g}from"../packem_shared/EXIT_CODE-DQVhSE-1.mjs";import{existsSync as f,readFileSync as P,statSync as L,watch as le}from"node:fs";import{homedir as C}from"node:os";import{findWranglerFile as ce}from"@lunora/config/cloudflare";import{join as i,relative as ae}from"@visulima/path";import{stringify as se}from"smol-toml";import{h as ie,u as de,i as ue,r as me}from"../packem_shared/mcp-config-file-GR1Y_CVw.mjs";import{detectPackageManager as fe,execArgsFor as pe}from"@lunora/config/cli";import{resolve as $,join as ge,dirname as N}from"node:path";import{readLiveDevServerState as S,DEV_STATE_DIR as he}from"@lunora/config";import{resolveAdminToken as ve}from"@lunora/config/studio-host";import{connectLocalStdio as ye,connectFunctionStdio as we}from"@lunora/mcp";import{i as be}from"../packem_shared/path-containment-CgxYZggb.mjs";const v=e=>({args:[...e.args],command:e.command,...e.env===void 0?{}:{env:e.env}}),j=e=>e.transport==="http"?{type:"http",url:e.url}:v(e),Se=e=>e.transport==="http"?{httpUrl:e.url}:v(e),ke=e=>e.transport==="http"?{serverUrl:e.url}:v(e),Ee=e=>({args:["-y","mcp-remote",e],command:"npx"}),$e=e=>e.transport==="http"?Ee(e.url):v(e),je=e=>e.transport==="http"?{url:e.url}:v(e),Oe=e=>e.transport==="http"?{enabled:!0,type:"remote",url:e.url}:{command:[e.command,...e.args],enabled:!0,type:"local",...e.env===void 0?{}:{environment:e.env}},Ce=e=>e.transport==="http"?{disabled:!1,type:"streamableHttp",url:e.url}:{disabled:!1,...v(e)},_e=({home:e,platform:t})=>{if(t==="darwin")return{global:i(e,"Library","Application Support","Claude","claude_desktop_config.json")};if(t==="win32"){const r=process.env.APPDATA;return r===void 0||r===""?{}:{global:i(r,"Claude","claude_desktop_config.json")}}return t==="linux"?{global:i(e,".config","Claude","claude_desktop_config.json")}:{}},Me=(e,t)=>se({mcp_servers:{[e]:t.transport==="http"?{url:t.url}:{args:[...t.args],command:t.command,...t.env===void 0?{}:{env:t.env}}}}),y=[{buildEntry:j,paths:({projectRoot:e})=>({project:i(e,".mcp.json")}),format:"json",id:"claude-code",key:"mcpServers",label:"Claude Code"},{buildEntry:j,paths:({home:e,projectRoot:t})=>({global:i(e,".cursor","mcp.json"),project:i(t,".cursor","mcp.json")}),format:"json",id:"cursor",key:"mcpServers",label:"Cursor"},{buildEntry:j,paths:({projectRoot:e})=>({project:i(e,".vscode","mcp.json")}),format:"json",id:"vscode",key:"servers",label:"VS Code (GitHub Copilot)"},{buildEntry:Se,paths:({home:e,projectRoot:t})=>({global:i(e,".gemini","settings.json"),project:i(t,".gemini","settings.json")}),format:"json",id:"gemini",key:"mcpServers",label:"Gemini CLI"},{buildEntry:$e,paths:_e,format:"json",id:"claude-desktop",key:"mcpServers",label:"Claude Desktop"},{buildEntry:ke,paths:({home:e})=>({global:i(e,".codeium","windsurf","mcp_config.json")}),format:"json",id:"windsurf",key:"mcpServers",label:"Windsurf"},{buildEntry:Oe,paths:({home:e,projectRoot:t})=>({global:i(e,".config","opencode","opencode.json"),project:i(t,"opencode.json")}),format:"json",id:"opencode",key:"mcp",label:"OpenCode"},{buildEntry:Ce,paths:({home:e})=>({global:i(e,".cline","mcp.json")}),format:"json",id:"cline",key:"mcpServers",label:"Cline"},{buildEntry:je,paths:({home:e})=>({global:i(e,".config","zed","settings.json")}),format:"json",id:"zed",key:"context_servers",label:"Zed"},{paths:({home:e,projectRoot:t})=>({global:i(e,".codex","config.toml"),project:i(t,".codex","config.toml")}),format:"manual",id:"codex",label:"Codex CLI",renderSnippet:Me}],I=y.map(e=>e.id),Ue=e=>y.find(t=>t.id===e.toLowerCase()),xe=["global","project"],h=(e,t)=>{const r=ae(t,e);return r.length>0&&!r.startsWith("..")?r:e},Le=(e,t)=>{const r=e.paths(t);return xe.flatMap(n=>{const o=r[n];return o===void 0?[]:[{client:e,path:o,scope:n}]})},Ne=(e,t,r,n)=>{const o=e.paths(t),l=r==="global"?"project":"global",c=o[r]??(n?void 0:o[l]);if(c!==void 0)return{client:e,path:c,scope:o[r]===void 0?l:r}},Ae=e=>y.filter(t=>Object.values(t.paths(e)).some(r=>f(r))),R=(e,t,r,n)=>{if(e.length===0)return t();const o=[];for(const l of e){const c=Ue(l);if(c===void 0){r.error(`mcp ${n}: unknown client "${l}". Known clients: ${I.join(", ")}.`);return}o.push(c)}return o},De=e=>e.client.format==="json",Te="https://lunora.sh/mcp",H="lunora-docs",W="lunora",Fe=e=>f(i(e,"lunora"))&&ce(e)!==void 0,Pe=e=>{const{args:t,command:r}=pe(e,"lunora",["mcp","serve"]);return{args:t,command:r,transport:"stdio"}},Ie=e=>({transport:"http",url:e}),Re=e=>({home:e.home,platform:e.platform,projectRoot:e.cwd}),G=(e,t,r)=>Ne(e,Re(r),r.scope??t.preferredScope,r.scope!==void 0||!t.allowScopeFallback),He=(e,t,r)=>{const n=G(e,t,r);if(n===void 0){r.logger.warn(`${e.label}: has no ${r.scope??t.preferredScope}-scoped config — skipped "${t.name}".`);return}const{path:o}=n,l=e.buildEntry(t.spec);if(r.print===!0){const u=h(o,r.cwd);return r.force!==!0&&ie({key:e.key,name:t.name,path:o})?(r.logger.info(`${e.label}: "${t.name}" already configured in ${u} — a real install would skip it (re-run with --force to replace).`),{action:"printed",path:o}):(r.logger.info(`${e.label} → ${u}
${JSON.stringify({[e.key]:{[t.name]:l}},void 0,4)}`),{action:"printed",path:o})}const c=de({entry:l,force:r.force===!0,key:e.key,name:t.name,path:o}),s=h(o,r.cwd);return c.action==="invalid"?r.logger.error(`${e.label}: ${s} is not valid JSON (${c.error??"unknown error"}) — left untouched.`):c.action==="skipped"?r.logger.info(`${e.label}: "${t.name}" already configured in ${s} — re-run with --force to replace it.`):r.logger.success(`${e.label}: ${c.action==="created"?"created":"updated"} ${s} with "${t.name}".`),{action:c.action,path:o}},We=(e,t,r)=>{const n=G(e,t,r)?.path;if(n===void 0){r.logger.warn(`${e.label}: no known config location on ${r.platform} — skipped.`);return}return r.logger.info(`${e.label}: add this to ${h(n,r.cwd)}
${e.renderSnippet(t.name,t.spec)}`),{action:"printed",path:n}},Ge=e=>{const t=[];return e.localOnly!==!0&&t.push({allowScopeFallback:!0,name:H,preferredScope:"global",spec:Ie(e.docsUrl??Te)}),e.docsOnly!==!0&&Fe(e.cwd)&&t.push({allowScopeFallback:!1,name:W,preferredScope:"project",spec:Pe(fe(e.cwd))}),t},Je=e=>{const t=e.home??C(),r=e.platform??process.platform;e.logger.info("Supported MCP clients:");for(const n of y){const o=n.paths({home:t,platform:r,projectRoot:e.cwd}),l=c=>{const s=o[c];return s===void 0?"—":h(s,e.cwd)};e.logger.info(` ${n.id.padEnd(15)} ${n.label.padEnd(24)} project: ${l("project").padEnd(30)} global: ${l("global")}`)}return{code:0,written:[]}},Ve=e=>e.docsOnly===!0&&e.localOnly===!0?"`--docs-only` and `--local-only` are mutually exclusive — pass at most one.":"`--local-only` was set but this directory is not a Lunora project (no `lunora/` directory and wrangler config).",ze=(e,t,r)=>{const n=[];for(const o of e)for(const l of t){const c=o.format==="json"?He(o,l,r):We(o,l,r);c!==void 0&&n.push({action:c.action,client:o.id,path:c.path,server:l.name})}return n},Ke=e=>{const t=e.home??C(),r=e.platform??process.platform,n=R(e.clients,()=>Ae({home:t,platform:r,projectRoot:e.cwd}),e.logger,"install");if(n===void 0)return{code:g.USAGE,written:[]};if(n.length===0)return e.logger.error(`mcp install: no MCP client config found — name one explicitly, e.g. \`lunora mcp install claude-code\`. Known clients: ${I.join(", ")}.`),{code:g.NOT_FOUND,written:[]};e.clients.length===0&&e.logger.info(`Detected ${String(n.length)} configured client(s): ${n.map(c=>c.label).join(", ")}.`);const o=Ge(e);if(o.length===0)return e.logger.error(`mcp install: nothing to install — ${Ve(e)}`),{code:g.USAGE,written:[]};const l=ze(n,o,{...e,home:t,platform:r});return l.some(c=>c.action==="created"||c.action==="updated")&&e.logger.info("Restart your editor (or reload its MCP servers) to pick up the change."),{code:l.some(c=>c.action==="invalid")?1:0,written:l}},J=100,V=1e3,A=e=>({content:[{text:JSON.stringify(e,void 0,2),type:"text"}]}),qe=e=>({content:[{text:e,type:"text"}]}),Be=e=>{const t=typeof e=="string"?Number(e):e;return typeof t!="number"||!Number.isFinite(t)?J:Math.min(V,Math.max(1,Math.floor(t)))},D=(e,t)=>{if(t===void 0)return;const r=$(e,he);return be(r,$(e,t))?$(e,t):void 0},Xe=(e,t)=>{const r=P(e,"utf8").split(`
`);return r.at(-1)===""&&r.pop(),r.slice(-t).join(`
`)},Ze=e=>[{definition:{annotations:{destructiveHint:!1,idempotentHint:!0,openWorldHint:!1,readOnlyHint:!0,title:"Check the local dev server"},description:"Report whether a `lunora dev` server is running for this project, and its URL, studio URL, mode and uptime. Call this first when a query or mutation tool fails to connect.",inputSchema:{properties:{},type:"object"},name:"lunora_dev_status"},handle:async()=>{const t=S(e);return A(t===void 0?{hint:"Start it with `lunora dev` in the project directory.",running:!1}:{background:t.background===!0,logFile:D(e,t.logFile),mode:t.mode,pid:t.pid,running:!0,startedAt:t.startedAt,studioUrl:t.studioUrl,url:t.url})}},{definition:{annotations:{destructiveHint:!1,idempotentHint:!0,openWorldHint:!1,readOnlyHint:!0,title:"Read the local dev server log"},description:"Return the tail of the running dev server's captured log — worker output, request errors, and stack traces. Only available when the server was started in the background (`lunora dev --background`); a foreground server prints to its own terminal.",inputSchema:{properties:{lines:{description:`How many trailing lines to return (default ${String(J)}, max ${String(V)})`,type:"number"}},type:"object"},name:"lunora_dev_logs"},handle:async t=>{const r=S(e);if(r===void 0)return{content:[{text:"no dev server is running — start one with `lunora dev`",type:"text"}],isError:!0};const n=D(e,r.logFile);if(n===void 0||!f(n))return{content:[{text:"this dev server is not capturing its output to a file (it runs in the foreground) — restart it with `lunora dev --background` to make its logs readable here",type:"text"}],isError:!0};const o=Be(t.lines),l=Xe(n,o);return qe(l.length===0?"(the dev server log is empty)":l)}}],O={methods:[],openrpc:"1.3.2"},Qe=e=>e instanceof Error&&e.code==="ENOENT",Ye=new Set(["127.0.0.1","::1","localhost"]),z=e=>{try{const{hostname:t}=new URL(e);return Ye.has(t.startsWith("[")?t.slice(1,-1):t)}catch{return!1}},T=e=>{const t=e.url??S(e.cwd)?.url;if(t===void 0||t.length===0)return;if(e.token!==void 0&&e.token.length>0)return{token:e.token,url:t};if(!z(t))return{url:t};const r=ve(e.cwd);return r===void 0||r.length===0?{url:t}:{token:r,url:t}},K=async e=>{await new Promise(t=>{const r=()=>{t()};e.onclose=r,process.stdin.once("close",r),process.stdin.once("end",r)})},et=e=>{if(e===void 0)return"lunora mcp serve: ready (documentation tools). No dev server running yet — start `lunora dev` and the deployment tools start working, no restart needed.\n";if(e.token!==void 0)return`lunora mcp serve: ready — deployment at ${e.url}
`;const r=!z(e.url)?"the project's admin token was NOT sent to this non-local url; pass --token to authenticate deliberately":"no LUNORA_ADMIN_TOKEN in the environment or .dev.vars; the deployment tools will be refused until one is set";return`lunora mcp serve: ready — deployment at ${e.url} (${r})
`},q=e=>{process.stderr.write(e)},tt=async(e,t)=>{const r=e.writeError??q,n=ge(e.cwd,"lunora","_generated","openrpc.json"),o=()=>e.url??S(e.cwd)?.url;let l,c;const s=a=>{r(`lunora mcp serve --functions: kept the last tool list — the rewritten document did not load: ${String(a)}
`)};let u={mtimeMs:-1,spec:O};const w=()=>{let a;try{a=L(n).mtimeMs,c=void 0}catch(d){if(Qe(d))u.spec!==O&&(u={mtimeMs:-1,spec:O});else{const m=d.code??String(d);c!==m&&(c=m,s(d))}return u.spec}if(a!==u.mtimeMs)try{u={mtimeMs:a,spec:JSON.parse(P(n,"utf8"))}}catch(d){l!==a&&(l=a,s(d))}return u.spec};let b;try{b=await t({allowWrites:e.allowWrites===!0,onReloadError:s,openRpcSpec:w,url:o,version:e.version,...e.token===void 0||e.token.length===0?{}:{token:e.token}})}catch(a){const d=a instanceof Error?a.message:String(a);return r(`lunora mcp serve --functions: failed to start — ${d}
`),{code:1,deployment:void 0}}const B=e.token===void 0||e.token.length===0,k=o(),X=k===void 0||k.length===0?"no deployment yet (start `lunora dev` or pass --url; calls fail until one runs)":k,Z=f(n)?"":" (no openrpc.json yet: run `lunora codegen --api-spec openrpc`; the functions appear once it exists)";r(`lunora mcp serve --functions: ready — ${X}${B?" (no --token: only public functions answer, and writes are refused)":""}${Z}
`);const E=N(n),_=a=>{r(`lunora mcp serve --functions: the tool list will not be announced on a change — ${String(a)}
`)},Q=()=>{if(f(E))return E;const a=N(E);return f(a)?a:e.cwd};let M=f(n);const Y=a=>{try{const{dev:d,ino:m}=L(a);return`${String(d)}:${String(m)}`}catch{return""}};let p;const U=()=>{const a=Q(),d=Y(a);if(!(p?.directory===a&&(d===""||p.identity===d))){p?.watcher.close(),p=void 0;try{const m=le(a,(it,ee)=>{const x=f(n),te=ee==="openrpc.json"||x!==M;M=x,U(),te&&b.sendToolListChanged?.().catch(re=>{r(`lunora mcp serve --functions: could not announce the tool list change — ${String(re)}
`)})});m.on("error",_),p={directory:a,identity:d,watcher:m}}catch(m){_(m)}}};U();try{await K(b)}finally{p?.watcher.close();try{await b.close?.()}catch(a){r(`lunora mcp serve --functions: could not close the server — ${String(a)}
`)}}return{code:0,deployment:void 0}},rt=async(e,t=ye,r=we)=>{if(e.functions===!0)return tt(e,r);const n=e.writeError??q;let o;try{o=await t({allowWrites:e.allowWrites===!0,deployment:()=>T(e),docs:e.noDocs===!0?!1:{...e.docsUrl===void 0?{}:{baseUrl:e.docsUrl}},extraTools:Ze(e.cwd),version:e.version})}catch(c){const s=c instanceof Error?c.message:String(c);return n(`lunora mcp serve: failed to start — ${s}
`),{code:1,deployment:void 0}}const l=T(e);return n(et(l)),await K(o),{code:0,deployment:l}},nt=e=>{const t=[];return e.localOnly!==!0&&t.push(H),e.docsOnly!==!0&&t.push(W),t},ot=(e,t,r,n)=>{const o=me({key:e.key,name:t,path:r}),l=h(r,n.cwd);return o.action==="removed"?n.logger.success(`${e.label}: removed "${t}" from ${l}.`):o.action==="invalid"&&n.logger.error(`${e.label}: ${l} is not valid JSON (${o.error??"unknown error"}) — left untouched.`),{action:o.action,path:r}},lt=(e,t,r,n)=>{const o=ue({key:e.key,name:t,path:r}),l=h(r,n.cwd);return o==="invalid"?(n.logger.error(`${e.label}: ${l} is not valid JSON — a real run would report it and exit non-zero.`),{action:"invalid",path:r}):o==="absent"?{action:"absent",path:r}:(n.logger.info(`${e.label}: would remove "${t}" from ${l}.`),{action:"removed",path:r})},ct=(e,t,r)=>e.flatMap(n=>Le(n,t)).filter(De).filter(n=>r===void 0||n.scope===r),at=e=>{const t=e.home??C(),r=e.platform??process.platform,n=R(e.clients,()=>y,e.logger,"uninstall");if(n===void 0)return{code:g.USAGE,removed:[]};const o=nt(e);if(o.length===0)return e.logger.error("mcp uninstall: nothing to remove — `--docs-only` and `--local-only` are mutually exclusive, pass at most one."),{code:g.USAGE,removed:[]};const l=[],c={home:t,platform:r,projectRoot:e.cwd};for(const s of ct(n,c,e.scope))for(const u of o){const w=e.print===!0?lt(s.client,u,s.path,e):ot(s.client,u,s.path,e);w.action!=="absent"&&l.push({...w,client:s.client.id,server:u})}return l.length===0?e.logger.info("Nothing to remove — no Lunora MCP servers were configured in the clients checked."):e.print===!0&&e.logger.info("Nothing was changed — re-run without --print to remove these."),{code:l.some(s=>s.action==="invalid")?1:0,removed:l}},F=e=>e.global===!0?"global":e.project===!0?"project":void 0,st=async(e,t)=>{const{code:r}=await rt({allowWrites:t.allowWrites===!0,cwd:e,functions:t.functions===!0,noDocs:t.docs===!1,version:ne,...t.docsUrl===void 0?{}:{docsUrl:t.docsUrl},...t.token===void 0?{}:{token:t.token},...t.url===void 0?{}:{url:t.url}});return{code:r}},jt=oe(async({argument:e,cwd:t,logger:r,options:n})=>{const[o,...l]=e;if(o==="serve")return st(t,n);if(o==="uninstall"){const c=F(n),{code:s}=at({clients:l,cwd:t,docsOnly:n.docsOnly===!0,localOnly:n.localOnly===!0,logger:r,print:n.print===!0,...c===void 0?{}:{scope:c}});return{code:s}}if(o==="install"){if(n.list===!0)return Je({cwd:t,logger:r});const c=F(n),{code:s}=Ke({clients:l,cwd:t,docsOnly:n.docsOnly===!0,force:n.force===!0,localOnly:n.localOnly===!0,logger:r,print:n.print===!0,...c===void 0?{}:{scope:c},...n.docsUrl===void 0?{}:{docsUrl:n.docsUrl}});return{code:s}}return r.error("mcp: unknown subcommand. Usage: lunora mcp <install|uninstall|serve>"),{code:g.USAGE}});export{jt as execute};