@lunora/cli 1.0.0-alpha.159 → 1.0.0-alpha.160

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,99 @@
1
- import{i as L}from"../packem_shared/cli-DiEQDidI.mjs";import{i as J}from"../packem_shared/command-0l-ZPhIX.mjs";import{existsSync as p,readFileSync as h,mkdirSync as P,realpathSync as W,statSync as D,writeFileSync as T,chmodSync as z,renameSync as H,unlinkSync as I}from"node:fs";import{homedir as $}from"node:os";import{findWranglerFile as K}from"@lunora/config/cloudflare";import{join as s,dirname as q,relative as G}from"@visulima/path";import{l as V,M as Z}from"../packem_shared/detect-package-manager-DXDstphE.mjs";import{stringify as B}from"smol-toml";import{parse as Q,modify as X,applyEdits as Y}from"jsonc-parser";import{readLiveDevServerState as y}from"@lunora/config";import{resolveAdminToken as oo}from"@lunora/config/studio-host";import{connectLocalStdio as to}from"@lunora/mcp";const u=o=>({args:[...o.args],command:o.command,...o.env===void 0?{}:{env:o.env}}),v=o=>o.transport==="http"?{type:"http",url:o.url}:u(o),eo=o=>o.transport==="http"?{httpUrl:o.url}:u(o),ro=o=>o.transport==="http"?{serverUrl:o.url}:u(o),no=o=>({args:["-y","mcp-remote",o],command:"npx"}),ao=o=>o.transport==="http"?no(o.url):u(o),io=o=>o.transport==="http"?{url:o.url}:u(o),lo=o=>o.transport==="http"?{enabled:!0,type:"remote",url:o.url}:{command:[o.command,...o.args],enabled:!0,type:"local",...o.env===void 0?{}:{environment:o.env}},so=o=>o.transport==="http"?{disabled:!1,type:"streamableHttp",url:o.url}:{disabled:!1,...u(o)},co=({home:o,platform:t})=>{if(t==="darwin")return{global:s(o,"Library","Application Support","Claude","claude_desktop_config.json")};if(t==="win32"){const e=process.env.APPDATA;return e===void 0||e===""?{}:{global:s(e,"Claude","claude_desktop_config.json")}}return t==="linux"?{global:s(o,".config","Claude","claude_desktop_config.json")}:{}},po=(o,t)=>B({mcp_servers:{[o]:t.transport==="http"?{url:t.url}:{args:[...t.args],command:t.command,...t.env===void 0?{}:{env:t.env}}}}),g=[{buildEntry:v,paths:({projectRoot:o})=>({project:s(o,".mcp.json")}),format:"json",id:"claude-code",key:"mcpServers",label:"Claude Code"},{buildEntry:v,paths:({home:o,projectRoot:t})=>({global:s(o,".cursor","mcp.json"),project:s(t,".cursor","mcp.json")}),format:"json",id:"cursor",key:"mcpServers",label:"Cursor"},{buildEntry:v,paths:({projectRoot:o})=>({project:s(o,".vscode","mcp.json")}),format:"json",id:"vscode",key:"servers",label:"VS Code (GitHub Copilot)"},{buildEntry:eo,paths:({home:o,projectRoot:t})=>({global:s(o,".gemini","settings.json"),project:s(t,".gemini","settings.json")}),format:"json",id:"gemini",key:"mcpServers",label:"Gemini CLI"},{buildEntry:ao,paths:co,format:"json",id:"claude-desktop",key:"mcpServers",label:"Claude Desktop"},{buildEntry:ro,paths:({home:o})=>({global:s(o,".codeium","windsurf","mcp_config.json")}),format:"json",id:"windsurf",key:"mcpServers",label:"Windsurf"},{buildEntry:lo,paths:({home:o,projectRoot:t})=>({global:s(o,".config","opencode","opencode.json"),project:s(t,"opencode.json")}),format:"json",id:"opencode",key:"mcp",label:"OpenCode"},{buildEntry:so,paths:({home:o})=>({global:s(o,".cline","mcp.json")}),format:"json",id:"cline",key:"mcpServers",label:"Cline"},{buildEntry:io,paths:({home:o})=>({global:s(o,".config","zed","settings.json")}),format:"json",id:"zed",key:"context_servers",label:"Zed"},{paths:({home:o,projectRoot:t})=>({global:s(o,".codex","config.toml"),project:s(t,".codex","config.toml")}),format:"manual",id:"codex",label:"Codex CLI",renderSnippet:po}],O=g.map(o=>o.id),uo=o=>g.find(t=>t.id===o.toLowerCase()),x=(o,t)=>{let e=o,r;try{e=W(o),r=D(e).mode}catch{}const a=`${e}.lunora-${Math.random().toString(36).slice(2,10)}.tmp`;try{T(a,t,"utf8"),r!==void 0&&z(a,r),H(a,e)}catch(n){try{I(a)}catch{}throw n}},mo={formattingOptions:{insertSpaces:!0,tabSize:4}},b=o=>{const t=[],e=Q(o,t,{allowTrailingComma:!0});return{errors:t,value:e}},f=o=>typeof o=="object"&&o!==null&&!Array.isArray(o),w=(o,t,e)=>{if(!f(o))return;const r=o[t];return f(r)?r[e]:void 0},C=o=>{if(!p(o.path))return"absent";let t;try{t=h(o.path,"utf8")}catch{return"invalid"}if(t.trim().length===0)return"absent";const{errors:e,value:r}=b(t);return e.length>0||!f(r)?"invalid":w(r,o.key,o.name)===void 0?"absent":"present"},fo=o=>C(o)==="present",E=(o,t,e,r,a)=>{try{const n=X(o,[e,r],a,mo);n.length>0&&x(t,Y(o,n));return}catch(n){return n instanceof Error?n.message:String(n)}},go=o=>{const{entry:t,force:e=!1,key:r,name:a,path:n}=o,i=p(n)?h(n,"utf8"):"";if(i.trim().length===0)return P(q(n),{recursive:!0}),x(n,`${JSON.stringify({[r]:{[a]:t}},void 0,4)}
2
- `),{action:"created",path:n};const{errors:l,value:c}=b(i);if(l.length>0)return{action:"invalid",error:`parse error at offset ${String(l[0]?.offset??0)}`,path:n};if(!f(c))return{action:"invalid",error:"the file's root is not a JSON object",path:n};const m=c[r];if(m!==void 0&&!f(m))return{action:"invalid",error:`"${r}" is not an object`,path:n};if(w(c,r,a)!==void 0&&!e)return{action:"skipped",path:n};const j=E(i,n,r,a,t);return j===void 0?{action:"updated",path:n}:{action:"invalid",error:j,path:n}},ho=o=>{const{key:t,name:e,path:r}=o;if(!p(r))return{action:"absent",path:r};let a;try{a=h(r,"utf8")}catch(c){return{action:"invalid",error:c instanceof Error?c.message:String(c),path:r}}const{errors:n,value:i}=b(a);if(n.length>0)return{action:"invalid",error:`parse error at offset ${String(n[0]?.offset??0)}`,path:r};if(w(i,t,e)===void 0)return{action:"absent",path:r};const l=E(a,r,t,e,void 0);return l===void 0?{action:"removed",path:r}:{action:"invalid",error:l,path:r}},vo=["global","project"],d=(o,t)=>{const e=G(t,o);return e.length>0&&!e.startsWith("..")?e:o},yo=(o,t)=>{const e=o.paths(t);return vo.flatMap(r=>{const a=e[r];return a===void 0?[]:[{client:o,path:a,scope:r}]})},$o=(o,t,e,r)=>{const a=o.paths(t),n=e==="global"?"project":"global",i=a[e]??(r?void 0:a[n]);if(i!==void 0)return{client:o,path:i,scope:a[e]===void 0?n:e}},bo=o=>g.filter(t=>Object.values(t.paths(o)).some(e=>p(e))),R=(o,t,e,r)=>{if(o.length===0)return t();const a=[];for(const n of o){const i=uo(n);if(i===void 0){e.error(`mcp ${r}: unknown client "${n}". Known clients: ${O.join(", ")}.`);return}a.push(i)}return a},wo=o=>o.client.format==="json",jo="https://lunora.sh/mcp",U="lunora-docs",N="lunora",ko=o=>p(s(o,"lunora"))&&K(o)!==void 0,So=o=>{const{args:t,command:e}=Z(o,"lunora",["mcp","serve"]);return{args:t,command:e,transport:"stdio"}},Oo=o=>({transport:"http",url:o}),xo=o=>({home:o.home,platform:o.platform,projectRoot:o.cwd}),_=(o,t,e)=>$o(o,xo(e),e.scope??t.preferredScope,e.scope!==void 0||!t.allowScopeFallback),Co=(o,t,e)=>{const r=_(o,t,e);if(r===void 0){e.logger.warn(`${o.label}: has no ${e.scope??t.preferredScope}-scoped config — skipped "${t.name}".`);return}const{path:a}=r,n=o.buildEntry(t.spec);if(e.print===!0){const c=d(a,e.cwd);return e.force!==!0&&fo({key:o.key,name:t.name,path:a})?(e.logger.info(`${o.label}: "${t.name}" already configured in ${c} — a real install would skip it (re-run with --force to replace).`),{action:"printed",path:a}):(e.logger.info(`${o.label} → ${c}
3
- ${JSON.stringify({[o.key]:{[t.name]:n}},void 0,4)}`),{action:"printed",path:a})}const i=go({entry:n,force:e.force===!0,key:o.key,name:t.name,path:a}),l=d(a,e.cwd);return i.action==="invalid"?e.logger.error(`${o.label}: ${l} is not valid JSON (${i.error??"unknown error"}) — left untouched.`):i.action==="skipped"?e.logger.info(`${o.label}: "${t.name}" already configured in ${l} — re-run with --force to replace it.`):e.logger.success(`${o.label}: ${i.action==="created"?"created":"updated"} ${l} with "${t.name}".`),{action:i.action,path:a}},Eo=(o,t,e)=>{const r=_(o,t,e)?.path;if(r===void 0){e.logger.warn(`${o.label}: no known config location on ${e.platform} — skipped.`);return}return e.logger.info(`${o.label}: add this to ${d(r,e.cwd)}
4
-
5
- ${o.renderSnippet(t.name,t.spec)}`),{action:"printed",path:r}},Ro=o=>{const t=[];return o.localOnly!==!0&&t.push({allowScopeFallback:!0,name:U,preferredScope:"global",spec:Oo(o.docsUrl??jo)}),o.docsOnly!==!0&&ko(o.cwd)&&t.push({allowScopeFallback:!1,name:N,preferredScope:"project",spec:So(V(o.cwd))}),t},Uo=o=>{const t=o.home??$(),e=o.platform??process.platform;o.logger.info("Supported MCP clients:");for(const r of g){const a=r.paths({home:t,platform:e,projectRoot:o.cwd}),n=i=>{const l=a[i];return l===void 0?"":d(l,o.cwd)};o.logger.info(` ${r.id.padEnd(15)} ${r.label.padEnd(24)} project: ${n("project").padEnd(30)} global: ${n("global")}`)}return{code:0,written:[]}},No=o=>o.docsOnly===!0&&o.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).",_o=(o,t,e)=>{const r=[];for(const a of o)for(const n of t){const i=a.format==="json"?Co(a,n,e):Eo(a,n,e);i!==void 0&&r.push({action:i.action,client:a.id,path:i.path,server:n.name})}return r},Mo=o=>{const t=o.home??$(),e=o.platform??process.platform,r=R(o.clients,()=>bo({home:t,platform:e,projectRoot:o.cwd}),o.logger,"install");if(r===void 0)return{code:1,written:[]};if(r.length===0)return o.logger.error(`mcp install: no MCP client config found — name one explicitly, e.g. \`lunora mcp install claude-code\`. Known clients: ${O.join(", ")}.`),{code:1,written:[]};o.clients.length===0&&o.logger.info(`Detected ${String(r.length)} configured client(s): ${r.map(i=>i.label).join(", ")}.`);const a=Ro(o);if(a.length===0)return o.logger.error(`mcp install: nothing to install${No(o)}`),{code:1,written:[]};const n=_o(r,a,{...o,home:t,platform:e});return n.some(i=>i.action==="created"||i.action==="updated")&&o.logger.info("Restart your editor (or reload its MCP servers) to pick up the change."),{code:n.some(i=>i.action==="invalid")?1:0,written:n}},M=100,A=1e3,Ao=o=>({content:[{text:JSON.stringify(o,void 0,2),type:"text"}]}),Fo=o=>({content:[{text:o,type:"text"}]}),Lo=o=>{const t=typeof o=="string"?Number(o):o;return typeof t!="number"||!Number.isFinite(t)?M:Math.min(A,Math.max(1,Math.floor(t)))},Jo=(o,t)=>{const e=h(o,"utf8").split(`
6
- `);return e.at(-1)===""&&e.pop(),e.slice(-t).join(`
7
- `)},Po=o=>[{definition:{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=y(o);return Ao(t===void 0?{hint:"Start it with `lunora dev` in the project directory.",running:!1}:{background:t.background===!0,logFile:t.logFile,mode:t.mode,pid:t.pid,running:!0,startedAt:t.startedAt,studioUrl:t.studioUrl,url:t.url})}},{definition:{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(M)}, max ${String(A)})`,type:"number"}},type:"object"},name:"lunora_dev_logs"},handle:async t=>{const e=y(o);if(e===void 0)return{content:[{text:"no dev server is running — start one with `lunora dev`",type:"text"}],isError:!0};if(e.logFile===void 0||!p(e.logFile))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 r=Lo(t.lines),a=Jo(e.logFile,r);return Fo(a.length===0?"(the dev server log is empty)":a)}}],Wo=new Set(["127.0.0.1","::1","localhost"]),F=o=>{try{const{hostname:t}=new URL(o);return Wo.has(t.startsWith("[")?t.slice(1,-1):t)}catch{return!1}},k=o=>{const t=o.url??y(o.cwd)?.url;if(t===void 0||t.length===0)return;if(o.token!==void 0&&o.token.length>0)return{token:o.token,url:t};if(o.url!==void 0&&!F(o.url))return{url:t};const e=oo(o.cwd);return e===void 0||e.length===0?{url:t}:{token:e,url:t}},Do=async o=>{await new Promise(t=>{const e=()=>{t()};o.onclose=e,process.stdin.once("close",e),process.stdin.once("end",e)})},To=(o,t)=>{if(o===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(o.token!==void 0)return`lunora mcp serve: ready — deployment at ${o.url}
8
- `;const e=t.url!==void 0&&!F(t.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 ${o.url} (${e})
9
- `},zo=async(o,t=to)=>{const e=o.writeError??(n=>{process.stderr.write(n)});let r;try{r=await t({allowWrites:o.allowWrites===!0,deployment:()=>k(o),docs:o.noDocs===!0?!1:{...o.docsUrl===void 0?{}:{baseUrl:o.docsUrl}},extraTools:Po(o.cwd),version:o.version})}catch(n){const i=n instanceof Error?n.message:String(n);return e(`lunora mcp serve: failed to start — ${i}
10
- `),{code:1,deployment:void 0}}const a=k(o);return e(To(a,o)),await Do(r),{code:0,deployment:a}},Ho=o=>{const t=[];return o.localOnly!==!0&&t.push(U),o.docsOnly!==!0&&t.push(N),t},Io=(o,t,e,r)=>{const a=ho({key:o.key,name:t,path:e}),n=d(e,r.cwd);return a.action==="removed"?r.logger.success(`${o.label}: removed "${t}" from ${n}.`):a.action==="invalid"&&r.logger.error(`${o.label}: ${n} is not valid JSON (${a.error??"unknown error"}) — left untouched.`),{action:a.action,path:e}},Ko=(o,t,e,r)=>{const a=C({key:o.key,name:t,path:e}),n=d(e,r.cwd);return a==="invalid"?(r.logger.error(`${o.label}: ${n} is not valid JSON — a real run would report it and exit non-zero.`),{action:"invalid",path:e}):a==="absent"?{action:"absent",path:e}:(r.logger.info(`${o.label}: would remove "${t}" from ${n}.`),{action:"removed",path:e})},qo=(o,t,e)=>o.flatMap(r=>yo(r,t)).filter(wo).filter(r=>e===void 0||r.scope===e),Go=o=>{const t=o.home??$(),e=o.platform??process.platform,r=R(o.clients,()=>g,o.logger,"uninstall");if(r===void 0)return{code:1,removed:[]};const a=Ho(o);if(a.length===0)return o.logger.error("mcp uninstall: nothing to remove — `--docs-only` and `--local-only` are mutually exclusive, pass at most one."),{code:1,removed:[]};const n=[],i={home:t,platform:e,projectRoot:o.cwd};for(const l of qo(r,i,o.scope))for(const c of a){const m=o.print===!0?Ko(l.client,c,l.path,o):Io(l.client,c,l.path,o);m.action!=="absent"&&n.push({...m,client:l.client.id,server:c})}return n.length===0?o.logger.info("Nothing to remove — no Lunora MCP servers were configured in the clients checked."):o.print===!0&&o.logger.info("Nothing was changed — re-run without --print to remove these."),{code:n.some(l=>l.action==="invalid")?1:0,removed:n}},S=o=>o.global===!0?"global":o.project===!0?"project":void 0,Vo=async(o,t)=>{const{code:e}=await zo({allowWrites:t.allowWrites===!0,cwd:o,noDocs:t.docs===!1,version:L,...t.docsUrl===void 0?{}:{docsUrl:t.docsUrl},...t.token===void 0?{}:{token:t.token},...t.url===void 0?{}:{url:t.url}});return{code:e}},lt=J(async({argument:o,cwd:t,logger:e,options:r})=>{const[a,...n]=o;if(a==="serve")return Vo(t,r);if(a==="uninstall"){const i=S(r),{code:l}=Go({clients:n,cwd:t,docsOnly:r.docsOnly===!0,localOnly:r.localOnly===!0,logger:e,print:r.print===!0,...i===void 0?{}:{scope:i}});return{code:l}}if(a==="install"){if(r.list===!0)return Uo({cwd:t,logger:e});const i=S(r),{code:l}=Mo({clients:n,cwd:t,docsOnly:r.docsOnly===!0,force:r.force===!0,localOnly:r.localOnly===!0,logger:e,print:r.print===!0,...i===void 0?{}:{scope:i},...r.docsUrl===void 0?{}:{docsUrl:r.docsUrl}});return{code:l}}return e.error("mcp: unknown subcommand. Usage: lunora mcp <install|uninstall|serve>"),{code:1}});export{lt as execute};
1
+ import{existsSync as T,readFileSync as O}from"node:fs";import{writeFile as x,mkdir as D}from"node:fs/promises";import{join as v}from"@visulima/path";import{i as B}from"../packem_shared/command-0l-ZPhIX.mjs";import{createRequire as q}from"node:module";import{LunoraError as w}from"@lunora/errors";import{P as U,l as F}from"../packem_shared/detect-package-manager-DXDstphE.mjs";import{parseSchema as Y,applyAdditiveEdit as j}from"@lunora/config";const H=/^\//,J=(e,n)=>{try{const{args:t,command:a}=U(F(e),[n],{dev:!0});return`${a} ${t.join(" ")}`}catch{return`<your-package-manager> add -D ${n}`}},R=(e,n,t)=>{const a=q(v(t,"noop.cjs"));try{a.resolve(e)}catch{throw new w("INTERNAL",`\`lunora introspect\` needs the \`${n}\` driver to read this database, and it isn't installed.
2
+
3
+ Install it in your project:
4
+
5
+ ${J(t,n)}`)}return a(e)},P=e=>{const n=e.slice(0,Math.max(0,e.indexOf(":"))).toLowerCase();if(n==="postgres"||n==="postgresql")return"postgres";if(n==="mysql"||n==="mariadb")return"mysql";throw new w("INTERNAL",`Unrecognised database URL scheme \`${n}\`. Expected a \`postgres://\`, \`postgresql://\`, \`mysql://\`, or \`mariadb://\` connection string.`)},W=e=>{try{const n=new URL(e).pathname.replace(H,"");return n===""?void 0:decodeURIComponent(n)}catch{return}},K=async(e,n,t,a=process.cwd())=>{if(n==="postgres"){const o=R("pg","pg",a).Client,c=new o({connectionString:e});return await c.connect(),{close:async()=>{await c.end()},execute:async(m,d)=>(await c.query(m,[...d])).rows,schema:t??"public"}}const s=R("mysql2/promise","mysql2",a).createConnection,r=await s(e),i=t??W(e);if(i===void 0)throw new w("INTERNAL","A MySQL connection string must name a database (`mysql://host/<database>`), or pass `--schema`.");return{close:async()=>{await r.end()},execute:async(o,c)=>{const[m]=await r.execute(o,[...c]);return Array.isArray(m)?m:[]},schema:i}},h=new Set(["_creationTime","_id"]),Q={bigint:"v.bigint()",bigserial:"v.bigint()",bit:"v.string()",bool:"v.boolean()",boolean:"v.boolean()",box:"v.string()",bpchar:"v.string()",bytea:"v.bytes()",char:"v.string()",character:"v.string()","character varying":"v.string()",cidr:"v.string()",circle:"v.string()",citext:"v.string()",date:"v.date()","double precision":"v.number()",float4:"v.number()",float8:"v.number()",inet:"v.string()",int:"v.number()",int2:"v.number()",int4:"v.number()",int8:"v.bigint()",integer:"v.number()",interval:"v.string()",json:"v.any()",jsonb:"v.any()",line:"v.string()",lseg:"v.string()",macaddr:"v.string()",money:"v.number()",name:"v.string()",numeric:"v.number()",path:"v.string()",point:"v.string()",polygon:"v.string()",real:"v.number()",serial:"v.number()",smallint:"v.number()",smallserial:"v.number()",text:"v.string()",time:"v.string()","time with time zone":"v.string()","time without time zone":"v.string()",timestamp:"v.timestamp()","timestamp with time zone":"v.timestamp()","timestamp without time zone":"v.timestamp()",timestamptz:"v.timestamp()",tsquery:"v.string()",tsvector:"v.string()",uuid:"v.string()",varbit:"v.string()",varchar:"v.string()",xml:"v.string()"},G={bigint:"v.bigint()",binary:"v.bytes()",bit:"v.number()",blob:"v.bytes()",char:"v.string()",date:"v.date()",datetime:"v.timestamp()",decimal:"v.number()",double:"v.number()",enum:"v.string()",float:"v.number()",int:"v.number()",integer:"v.number()",json:"v.any()",longblob:"v.bytes()",longtext:"v.string()",mediumblob:"v.bytes()",mediumint:"v.number()",mediumtext:"v.string()",numeric:"v.number()",set:"v.string()",smallint:"v.number()",text:"v.string()",time:"v.string()",timestamp:"v.timestamp()",tinyblob:"v.bytes()",tinyint:"v.number()",tinytext:"v.string()",varbinary:"v.bytes()",varchar:"v.string()",year:"v.number()"},N=(e,n)=>{const t=(n==="postgres"?Q:G)[e.dataType],a=e.references===void 0?t:`v.id(${JSON.stringify(e.references.table)})`;let s=a??"v.any()";for(let r=0;r<e.arrayDepth;r+=1)s=`v.array(${s})`;return e.nullable&&(s=`v.optional(${s})`),{expression:s,known:a!==void 0}},M=/^[A-Z_$][\w$]*$/i,z=/[^\dA-Z]+(.)?/gi,X=/^\d+/,Z=/[^\w-]/g,V=/[\u003C\u003E\u002F\u2028\u2029]/g,ee={"/":String.raw`\u002F`,"\u2028":String.raw`\u2028`,"\u2029":String.raw`\u2029`,"<":String.raw`\u003C`,">":String.raw`\u003E`},b=e=>JSON.stringify(e).replaceAll(V,n=>ee[n]??n),$=e=>M.test(e)?e:b(e),te=e=>M.test(e)?`.${e}`:`[${b(e)}]`,I=e=>e.replaceAll("*/",String.raw`*\/`),ne=e=>{const n=e.replaceAll(Z,"_");return n===""?"table":n},ae=e=>{const n=e.replaceAll(z,(t,a)=>a?.toUpperCase()??"").replace(X,"");return n===""?"table":`${n.charAt(0).toLowerCase()}${n.slice(1)}`},C=e=>e.columns.filter(n=>!h.has(n.name)),re=e=>{const n=new Set(e.primaryKey);for(const t of e.indexes)for(const a of t.columns)n.add(a);for(const t of e.columns)t.references!==void 0&&n.add(t.name);return[...n].filter(t=>!h.has(t))},k=(e,n,t,a)=>e.references===void 0||n.has(e.references.table)?e:(a.push(`${t}.${e.name}: references \`${e.references.table}\`, which isn't in the generated schema emitted as a plain column instead of \`v.id(...)\`.`),{arrayDepth:e.arrayDepth,dataType:e.dataType,name:e.name,nullable:e.nullable}),se=(e,n,t,a)=>{const s=[];for(const i of e.columns){if(h.has(i.name)){a.push(`${e.name}.${i.name}: skipped \`${i.name}\` is a Lunora system column. Rename it in the source database or map it by hand.`);continue}const o=k(i,t,e.name,a),{expression:c,known:m}=N(o,n);!m&&o.references===void 0&&(a.push(`${e.name}.${i.name}: no mapping for SQL type \`${i.dataType}\` — emitted as \`v.any()\`.`),s.push(` // TODO: \`${I(i.dataType)}\` has no direct validator; narrow this.`)),s.push(` ${$(i.name)}: ${c},`)}const r=[' .global({ backend: "hyperdrive" })'];if(e.primaryKey.length>0&&e.primaryKey.every(i=>!h.has(i))){const i=e.primaryKey.map(o=>b(o)).join(", ");r.push(` .index(${b(`by_${e.primaryKey.join("_")}`)}, [${i}], { unique: true })`)}for(const i of e.indexes){const o=i.columns.filter(d=>!h.has(d));if(o.length===0)continue;const c=o.map(d=>b(d)).join(", "),m=i.unique?", { unique: true }":"";r.push(` .index(${b(i.name)}, [${c}]${m})`)}return` ${$(e.name)}: defineTable({
6
+ ${s.join(`
7
+ `)}
8
+ })
9
+ ${r.join(`
10
+ `)},`},ie=(e,n,t)=>{const a=new Set(e.tables.map(r=>r.name)),s=e.tables.map(r=>se(r,e.dialect,a,t)).join(`
11
+ `);return`/**
12
+ * Generated by \`lunora introspect\` from an existing ${e.dialect==="postgres"?"Postgres":"MySQL"} database.
13
+ *
14
+ * This file is a STARTING POINT, not a build artifact — it is written once and is
15
+ * yours to edit. Review it before shipping: column types are mapped
16
+ * conservatively, and every table is \`.global({ backend: "hyperdrive" })\` because
17
+ * its rows live in the external database. Re-running \`lunora introspect\` will not
18
+ * overwrite it unless you pass \`--force\`.
19
+ */
20
+ import { defineSchema, defineTable, v } from "${n.serverImport}";
21
+
22
+ export default defineSchema({
23
+ ${s}
24
+ });
25
+ `},oe=(e,n,t,a=new Set([e.name]),s=[])=>{const r=ae(e.name),i=re(e),o=new Map(C(e).map(l=>[l.name,l])),c=i.map(l=>{const g=o.get(l);if(g===void 0)return;const p=k({...g,nullable:!1},a,e.name,[]),{expression:E,known:A}=N(p,n);return!A&&p.references===void 0&&s.push(`${e.name}.${l}: filter falls back to \`v.any()\` (no mapping for SQL type \`${g.dataType}\`).`),` ${$(l)}: ${E},`}).filter(l=>l!==void 0),m=[b("_creationTime"),...i.map(l=>b(l))].join(", "),d=`ctx.db${te(e.name)}`;return`/**
26
+ * Generated by \`lunora introspect\` for the \`${I(e.name)}\` table — a
27
+ * starting point you own and edit.
28
+ *
29
+ * Both procedures are RPC-only. Add \`.expose({ rest: true })\` once you've decided
30
+ * this data should be public, and gate them with your auth/RLS middleware first —
31
+ * \`introspect\` cannot know who is allowed to read this table.
32
+ */
33
+ import { defineListArgs, v } from "${t.serverImport}";
34
+
35
+ import type { Doc } from "./_generated/dataModel";
36
+ import { c } from "./_generated/server";
37
+
38
+ const ${r}List = defineListArgs<Doc<${b(e.name)}>>()({
39
+ // Only index-backed columns are published as filterable, so a caller cannot
40
+ // reach a column you did not choose to expose. Note that \`contains\` and the
41
+ // negative operators still scan — narrow this list, and review it, before
42
+ // adding \`.expose({ rest: true })\`.
43
+ filter: {
44
+ ${c.join(`
45
+ `)}
46
+ },
47
+ orderBy: [${m}],
48
+ });
49
+
50
+ export const list = c.query.input(${r}List.args).query(({ args, ctx }) => ${d}.findMany(${r}List.toQueryArgs(args)));
51
+
52
+ export const get = c.query.input({ id: v.id(${b(e.name)}) }).query(({ args, ctx }) => ${d}.get(args.id));
53
+ `},ce=(e,n)=>{const t=[],a=new Set(e.tables.map(r=>r.name)),s=[{contents:ie(e,n,t),path:"schema.ts"}];if(n.procedures){const r=new Map([["schema","the generated schema module"]]);for(const i of e.tables){if(C(i).length===0){t.push(`${i.name}: no usable columns — procedure module skipped.`);continue}const o=ne(i.name);o!==i.name&&t.push(`${i.name}: written as \`${o}.ts\` — the table name isn't usable as a filename.`);const c=r.get(o);if(c!==void 0){t.push(`${i.name}: procedure module skipped — its filename \`${o}.ts\` collides with table \`${c}\`.`);continue}r.set(o,i.name),s.push({contents:oe(i,e.dialect,n,a,t),path:`${o}.ts`})}}return{files:s,warnings:t}},_=/^[A-Z_$][\w$]*$/i,me=e=>e.startsWith("v.optional(")&&e.endsWith(")")?e.slice(11,-1):e,le=(e,n,t)=>{const a=[],s=new Set(n?.columns.map(r=>r.name));for(const r of e.columns){if(h.has(r.name)||s.has(r.name))continue;if(!_.test(r.name)){t.warnings.push(`${e.name}.${r.name}: skipped — column names must be bare identifiers to merge.`);continue}const i=r.references!==void 0&&!t.present.has(r.references.table),{expression:o}=N(i?{...r,references:void 0}:r,t.dialect);a.push({column:r.name,kind:"addOptionalColumn",table:e.name,validator:me(o)}),!r.nullable&&n!==void 0&&t.warnings.push(`${e.name}.${r.name}: added as \`v.optional(...)\` — a required column on an existing table needs a backfill migration.`)}return a},ue=(e,n,t)=>{const a=[],s=new Set(n?.indexes.map(r=>r.name));for(const r of e.indexes){const i=r.columns.filter(o=>!h.has(o));if(!(s.has(r.name)||i.length===0)){if(!_.test(r.name)||!i.every(o=>_.test(o))){t.push(`${e.name}: index \`${r.name}\` skipped — index and column names must be bare identifiers to merge.`);continue}a.push({fields:i,kind:"addIndex",name:r.name,table:e.name,...r.unique?{unique:!0}:{}})}}return a},de=(e,n,t)=>{const a=[],s=[],r=new Map(n.map(o=>[o.name,o])),i=new Set([...r.keys(),...e.tables.map(o=>o.name)]);for(const o of e.tables){if(!_.test(o.name)){s.push(`${o.name}: skipped — merging into an existing schema needs a table name that is a bare identifier.`);continue}const c=r.get(o.name);c===void 0&&a.push({global:{backend:"hyperdrive"},kind:"addTable",table:o.name}),a.push(...le(o,c,{dialect:t,present:i,warnings:s}),...ue(o,c,s))}return{edits:a,warnings:s}},pe=(e,n,t)=>{const a=Y(e);if(!a.ok)return{applied:0,warnings:[`lunora/schema.ts could not be parsed (${a.reason}) — leave it alone and merge by hand, or pass --force.`]};const s=de(n,a.tables,t),r=[...s.warnings];let i=e,o=0;for(const c of s.edits){const m=j(i,c);m.ok?(i=m.text,o+=1):r.push(`${c.table}: skipped one edit (${m.reason}).`)}return{applied:o,warnings:r,...o===0?{}:{text:i}}},u=(e,n)=>{const t=e[n]??e[n.toLowerCase()]??e[n.toUpperCase()];return typeof t=="string"?t:typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"?String(t):""},ge=`
54
+ SELECT c.table_name, c.column_name, c.is_nullable, c.data_type, c.udt_name
55
+ FROM information_schema.columns c
56
+ JOIN information_schema.tables t
57
+ ON t.table_schema = c.table_schema AND t.table_name = c.table_name
58
+ WHERE c.table_schema = $1 AND t.table_type = 'BASE TABLE'
59
+ ORDER BY c.table_name, c.ordinal_position`,be=`
60
+ SELECT tc.table_name, kcu.column_name
61
+ FROM information_schema.table_constraints tc
62
+ JOIN information_schema.key_column_usage kcu
63
+ ON kcu.constraint_name = tc.constraint_name AND kcu.table_schema = tc.table_schema
64
+ WHERE tc.table_schema = $1 AND tc.constraint_type = 'PRIMARY KEY'
65
+ ORDER BY tc.table_name, kcu.ordinal_position`,fe=`
66
+ SELECT tc.table_name, kcu.column_name, ccu.table_name AS foreign_table, ccu.column_name AS foreign_column
67
+ FROM information_schema.table_constraints tc
68
+ JOIN information_schema.key_column_usage kcu
69
+ ON kcu.constraint_name = tc.constraint_name AND kcu.table_schema = tc.table_schema
70
+ JOIN information_schema.constraint_column_usage ccu
71
+ ON ccu.constraint_name = tc.constraint_name AND ccu.table_schema = tc.table_schema
72
+ WHERE tc.table_schema = $1 AND tc.constraint_type = 'FOREIGN KEY'`,he=`
73
+ SELECT t.relname AS table_name, i.relname AS index_name, ix.indisunique AS is_unique, a.attname AS column_name
74
+ FROM pg_class t
75
+ JOIN pg_index ix ON t.oid = ix.indrelid
76
+ JOIN pg_class i ON i.oid = ix.indexrelid
77
+ JOIN pg_namespace n ON n.oid = t.relnamespace
78
+ CROSS JOIN LATERAL unnest(ix.indkey) WITH ORDINALITY AS k(attnum, ord)
79
+ JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum
80
+ WHERE n.nspname = $1 AND t.relkind = 'r' AND NOT ix.indisprimary
81
+ ORDER BY t.relname, i.relname, k.ord`,ve=`
82
+ SELECT c.TABLE_NAME, c.COLUMN_NAME, c.IS_NULLABLE, c.DATA_TYPE
83
+ FROM information_schema.COLUMNS c
84
+ JOIN information_schema.TABLES t
85
+ ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME
86
+ WHERE c.TABLE_SCHEMA = ? AND t.TABLE_TYPE = 'BASE TABLE'
87
+ ORDER BY c.TABLE_NAME, c.ORDINAL_POSITION`,ye=`
88
+ SELECT TABLE_NAME, COLUMN_NAME
89
+ FROM information_schema.KEY_COLUMN_USAGE
90
+ WHERE TABLE_SCHEMA = ? AND CONSTRAINT_NAME = 'PRIMARY'
91
+ ORDER BY TABLE_NAME, ORDINAL_POSITION`,_e=`
92
+ SELECT TABLE_NAME, COLUMN_NAME, REFERENCED_TABLE_NAME AS foreign_table, REFERENCED_COLUMN_NAME AS foreign_column
93
+ FROM information_schema.KEY_COLUMN_USAGE
94
+ WHERE TABLE_SCHEMA = ? AND REFERENCED_TABLE_NAME IS NOT NULL`,Ee=`
95
+ SELECT TABLE_NAME, INDEX_NAME AS index_name, NON_UNIQUE, COLUMN_NAME
96
+ FROM information_schema.STATISTICS
97
+ WHERE TABLE_SCHEMA = ? AND INDEX_NAME <> 'PRIMARY'
98
+ ORDER BY TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX`,y=e=>{const n=new Map;for(const t of e){const a=u(t,"table_name"),s=n.get(a);s===void 0?n.set(a,[t]):s.push(t)}return n},Ae=(e,n)=>{const t=u(e,"data_type").toLowerCase();if(n!=="postgres")return{arrayDepth:0,dataType:t};const a=u(e,"udt_name").toLowerCase();return t==="array"&&a.startsWith("_")?{arrayDepth:1,dataType:a.slice(1)}:{arrayDepth:0,dataType:a===""?t:a}},$e=(e,n)=>{const t=new Map;for(const a of e){const s=u(a,"index_name"),r=n==="postgres"?u(a,"is_unique")==="true":u(a,"NON_UNIQUE")==="0",i=t.get(s);i===void 0?t.set(s,{columns:[u(a,"column_name")],unique:r}):i.columns.push(u(a,"column_name"))}return[...t.entries()].map(([a,s])=>({columns:s.columns,name:a,unique:s.unique}))},we=async(e,n,t)=>{const a=n==="postgres",[s,r,i,o]=await Promise.all([e(a?ge:ve,[t]),e(a?be:ye,[t]),e(a?fe:_e,[t]),e(a?he:Ee,[t])]),c=y(r),m=y(i),d=y(o),l=[];for(const[g,p]of y(s)){const E=new Map((m.get(g)??[]).map(f=>[u(f,"column_name"),{column:u(f,"foreign_column"),table:u(f,"foreign_table")}])),A=p.map(f=>{const S=u(f,"column_name"),L=E.get(S);return{...Ae(f,n),name:S,nullable:u(f,"is_nullable").toUpperCase()==="YES",...L===void 0?{}:{references:L}}});l.push({columns:A,indexes:$e(d.get(g)??[],n),name:g,primaryKey:(c.get(g)??[]).map(f=>u(f,"column_name"))})}return l.sort((g,p)=>g.name.localeCompare(p.name)),{dialect:n,tables:l}},Ne=e=>{try{const n=JSON.parse(O(v(e,"package.json"),"utf8"));return n.dependencies?.lunorash===void 0&&n.devDependencies?.lunorash===void 0?"@lunora/server":"lunorash/server"}catch{return"@lunora/server"}},Se=async(e,n,t)=>{const a=v(n,e.path);return T(a)&&t.force!==!0?(t.logger.warn(`skipped lunora/${e.path} — it already exists (pass --force to overwrite)`),!1):t.dryRun===!0?(t.logger.info(`would write lunora/${e.path} (${String(e.contents.split(`
99
+ `).length)} lines)`),!1):(await D(n,{recursive:!0}),await x(a,e.contents,"utf8"),t.logger.info(`wrote lunora/${e.path}`),!0)},Le=(e,n)=>{const t=n.tables;if(t===void 0||t.length===0)return e.tables;for(const a of t)e.tables.some(s=>s.name===a)||n.logger.warn(`--tables: no table named "${a}" exists in this schema — skipped.`);return e.tables.filter(a=>t.includes(a.name))},Re=async(e,n,t,a)=>{const s=pe(O(e,"utf8"),n,t);for(const r of s.warnings)a.logger.warn(r);return s.text===void 0?(a.logger.info("lunora/schema.ts is already up to date with the database."),!1):a.dryRun===!0?(a.logger.info(`would merge ${String(s.applied)} addition(s) into lunora/schema.ts`),!1):(await x(e,s.text,"utf8"),a.logger.info(`merged ${String(s.applied)} addition(s) into lunora/schema.ts`),!0)},Te=async e=>{const n=e.cwd??process.cwd();if(e.connection===void 0&&(e.url===void 0||e.url===""))return e.logger.error("`lunora introspect` needs a database URL: pass --url, or set DATABASE_URL."),{code:1,written:[]};const t=e.connection===void 0?P(e.url):e.dialect??"postgres",a=e.connection??await K(e.url,t,e.schema,n);let s;try{s=await we(a.execute,t,a.schema)}finally{e.connection===void 0&&await a.close()}const r=Le(s,e);if(r.length===0)return e.logger.error("no tables found to introspect — check --schema and --tables."),{code:1,written:[]};const{files:i,warnings:o}=ce({...s,tables:r},{procedures:e.procedures!==!1,serverImport:Ne(n)}),c=v(n,"lunora"),m=[],d=v(c,"schema.ts"),l=T(d)&&e.force!==!0,g=l?i.filter(p=>p.path!=="schema.ts"):i;l&&await Re(d,{tables:r},t,e)&&m.push("schema.ts");for(const p of g)await Se(p,c,e)&&m.push(p.path);for(const p of o)e.logger.warn(p);return e.logger.info(`introspected ${String(r.length)} table(s) from ${t}. Review the generated files before running \`lunora dev\`.`),{code:0,written:m}},qe=B(async({cwd:e,logger:n,options:t})=>({code:(await Te({cwd:e,dryRun:t.dryRun===!0,force:t.force===!0,logger:n,procedures:t.procedures!==!1,schema:t.schema,tables:t.tables===void 0?void 0:t.tables.split(",").map(a=>a.trim()),url:t.url??process.env.DATABASE_URL})).code}));export{qe as execute,Ne as resolveServerImport,Te as runIntrospectCommand};
@@ -0,0 +1,10 @@
1
+ import{i as L}from"../packem_shared/cli-Cu92injU.mjs";import{i as J}from"../packem_shared/command-0l-ZPhIX.mjs";import{existsSync as p,readFileSync as h,mkdirSync as P,realpathSync as W,statSync as D,writeFileSync as T,chmodSync as z,renameSync as H,unlinkSync as I}from"node:fs";import{homedir as $}from"node:os";import{findWranglerFile as K}from"@lunora/config/cloudflare";import{join as s,dirname as q,relative as G}from"@visulima/path";import{l as V,M as Z}from"../packem_shared/detect-package-manager-DXDstphE.mjs";import{stringify as B}from"smol-toml";import{parse as Q,modify as X,applyEdits as Y}from"jsonc-parser";import{readLiveDevServerState as y}from"@lunora/config";import{resolveAdminToken as oo}from"@lunora/config/studio-host";import{connectLocalStdio as to}from"@lunora/mcp";const u=o=>({args:[...o.args],command:o.command,...o.env===void 0?{}:{env:o.env}}),v=o=>o.transport==="http"?{type:"http",url:o.url}:u(o),eo=o=>o.transport==="http"?{httpUrl:o.url}:u(o),ro=o=>o.transport==="http"?{serverUrl:o.url}:u(o),no=o=>({args:["-y","mcp-remote",o],command:"npx"}),ao=o=>o.transport==="http"?no(o.url):u(o),io=o=>o.transport==="http"?{url:o.url}:u(o),lo=o=>o.transport==="http"?{enabled:!0,type:"remote",url:o.url}:{command:[o.command,...o.args],enabled:!0,type:"local",...o.env===void 0?{}:{environment:o.env}},so=o=>o.transport==="http"?{disabled:!1,type:"streamableHttp",url:o.url}:{disabled:!1,...u(o)},co=({home:o,platform:t})=>{if(t==="darwin")return{global:s(o,"Library","Application Support","Claude","claude_desktop_config.json")};if(t==="win32"){const e=process.env.APPDATA;return e===void 0||e===""?{}:{global:s(e,"Claude","claude_desktop_config.json")}}return t==="linux"?{global:s(o,".config","Claude","claude_desktop_config.json")}:{}},po=(o,t)=>B({mcp_servers:{[o]:t.transport==="http"?{url:t.url}:{args:[...t.args],command:t.command,...t.env===void 0?{}:{env:t.env}}}}),g=[{buildEntry:v,paths:({projectRoot:o})=>({project:s(o,".mcp.json")}),format:"json",id:"claude-code",key:"mcpServers",label:"Claude Code"},{buildEntry:v,paths:({home:o,projectRoot:t})=>({global:s(o,".cursor","mcp.json"),project:s(t,".cursor","mcp.json")}),format:"json",id:"cursor",key:"mcpServers",label:"Cursor"},{buildEntry:v,paths:({projectRoot:o})=>({project:s(o,".vscode","mcp.json")}),format:"json",id:"vscode",key:"servers",label:"VS Code (GitHub Copilot)"},{buildEntry:eo,paths:({home:o,projectRoot:t})=>({global:s(o,".gemini","settings.json"),project:s(t,".gemini","settings.json")}),format:"json",id:"gemini",key:"mcpServers",label:"Gemini CLI"},{buildEntry:ao,paths:co,format:"json",id:"claude-desktop",key:"mcpServers",label:"Claude Desktop"},{buildEntry:ro,paths:({home:o})=>({global:s(o,".codeium","windsurf","mcp_config.json")}),format:"json",id:"windsurf",key:"mcpServers",label:"Windsurf"},{buildEntry:lo,paths:({home:o,projectRoot:t})=>({global:s(o,".config","opencode","opencode.json"),project:s(t,"opencode.json")}),format:"json",id:"opencode",key:"mcp",label:"OpenCode"},{buildEntry:so,paths:({home:o})=>({global:s(o,".cline","mcp.json")}),format:"json",id:"cline",key:"mcpServers",label:"Cline"},{buildEntry:io,paths:({home:o})=>({global:s(o,".config","zed","settings.json")}),format:"json",id:"zed",key:"context_servers",label:"Zed"},{paths:({home:o,projectRoot:t})=>({global:s(o,".codex","config.toml"),project:s(t,".codex","config.toml")}),format:"manual",id:"codex",label:"Codex CLI",renderSnippet:po}],O=g.map(o=>o.id),uo=o=>g.find(t=>t.id===o.toLowerCase()),x=(o,t)=>{let e=o,r;try{e=W(o),r=D(e).mode}catch{}const a=`${e}.lunora-${Math.random().toString(36).slice(2,10)}.tmp`;try{T(a,t,"utf8"),r!==void 0&&z(a,r),H(a,e)}catch(n){try{I(a)}catch{}throw n}},mo={formattingOptions:{insertSpaces:!0,tabSize:4}},b=o=>{const t=[],e=Q(o,t,{allowTrailingComma:!0});return{errors:t,value:e}},f=o=>typeof o=="object"&&o!==null&&!Array.isArray(o),w=(o,t,e)=>{if(!f(o))return;const r=o[t];return f(r)?r[e]:void 0},C=o=>{if(!p(o.path))return"absent";let t;try{t=h(o.path,"utf8")}catch{return"invalid"}if(t.trim().length===0)return"absent";const{errors:e,value:r}=b(t);return e.length>0||!f(r)?"invalid":w(r,o.key,o.name)===void 0?"absent":"present"},fo=o=>C(o)==="present",E=(o,t,e,r,a)=>{try{const n=X(o,[e,r],a,mo);n.length>0&&x(t,Y(o,n));return}catch(n){return n instanceof Error?n.message:String(n)}},go=o=>{const{entry:t,force:e=!1,key:r,name:a,path:n}=o,i=p(n)?h(n,"utf8"):"";if(i.trim().length===0)return P(q(n),{recursive:!0}),x(n,`${JSON.stringify({[r]:{[a]:t}},void 0,4)}
2
+ `),{action:"created",path:n};const{errors:l,value:c}=b(i);if(l.length>0)return{action:"invalid",error:`parse error at offset ${String(l[0]?.offset??0)}`,path:n};if(!f(c))return{action:"invalid",error:"the file's root is not a JSON object",path:n};const m=c[r];if(m!==void 0&&!f(m))return{action:"invalid",error:`"${r}" is not an object`,path:n};if(w(c,r,a)!==void 0&&!e)return{action:"skipped",path:n};const j=E(i,n,r,a,t);return j===void 0?{action:"updated",path:n}:{action:"invalid",error:j,path:n}},ho=o=>{const{key:t,name:e,path:r}=o;if(!p(r))return{action:"absent",path:r};let a;try{a=h(r,"utf8")}catch(c){return{action:"invalid",error:c instanceof Error?c.message:String(c),path:r}}const{errors:n,value:i}=b(a);if(n.length>0)return{action:"invalid",error:`parse error at offset ${String(n[0]?.offset??0)}`,path:r};if(w(i,t,e)===void 0)return{action:"absent",path:r};const l=E(a,r,t,e,void 0);return l===void 0?{action:"removed",path:r}:{action:"invalid",error:l,path:r}},vo=["global","project"],d=(o,t)=>{const e=G(t,o);return e.length>0&&!e.startsWith("..")?e:o},yo=(o,t)=>{const e=o.paths(t);return vo.flatMap(r=>{const a=e[r];return a===void 0?[]:[{client:o,path:a,scope:r}]})},$o=(o,t,e,r)=>{const a=o.paths(t),n=e==="global"?"project":"global",i=a[e]??(r?void 0:a[n]);if(i!==void 0)return{client:o,path:i,scope:a[e]===void 0?n:e}},bo=o=>g.filter(t=>Object.values(t.paths(o)).some(e=>p(e))),R=(o,t,e,r)=>{if(o.length===0)return t();const a=[];for(const n of o){const i=uo(n);if(i===void 0){e.error(`mcp ${r}: unknown client "${n}". Known clients: ${O.join(", ")}.`);return}a.push(i)}return a},wo=o=>o.client.format==="json",jo="https://lunora.sh/mcp",U="lunora-docs",N="lunora",ko=o=>p(s(o,"lunora"))&&K(o)!==void 0,So=o=>{const{args:t,command:e}=Z(o,"lunora",["mcp","serve"]);return{args:t,command:e,transport:"stdio"}},Oo=o=>({transport:"http",url:o}),xo=o=>({home:o.home,platform:o.platform,projectRoot:o.cwd}),_=(o,t,e)=>$o(o,xo(e),e.scope??t.preferredScope,e.scope!==void 0||!t.allowScopeFallback),Co=(o,t,e)=>{const r=_(o,t,e);if(r===void 0){e.logger.warn(`${o.label}: has no ${e.scope??t.preferredScope}-scoped config — skipped "${t.name}".`);return}const{path:a}=r,n=o.buildEntry(t.spec);if(e.print===!0){const c=d(a,e.cwd);return e.force!==!0&&fo({key:o.key,name:t.name,path:a})?(e.logger.info(`${o.label}: "${t.name}" already configured in ${c} — a real install would skip it (re-run with --force to replace).`),{action:"printed",path:a}):(e.logger.info(`${o.label} → ${c}
3
+ ${JSON.stringify({[o.key]:{[t.name]:n}},void 0,4)}`),{action:"printed",path:a})}const i=go({entry:n,force:e.force===!0,key:o.key,name:t.name,path:a}),l=d(a,e.cwd);return i.action==="invalid"?e.logger.error(`${o.label}: ${l} is not valid JSON (${i.error??"unknown error"}) — left untouched.`):i.action==="skipped"?e.logger.info(`${o.label}: "${t.name}" already configured in ${l} — re-run with --force to replace it.`):e.logger.success(`${o.label}: ${i.action==="created"?"created":"updated"} ${l} with "${t.name}".`),{action:i.action,path:a}},Eo=(o,t,e)=>{const r=_(o,t,e)?.path;if(r===void 0){e.logger.warn(`${o.label}: no known config location on ${e.platform} — skipped.`);return}return e.logger.info(`${o.label}: add this to ${d(r,e.cwd)}
4
+
5
+ ${o.renderSnippet(t.name,t.spec)}`),{action:"printed",path:r}},Ro=o=>{const t=[];return o.localOnly!==!0&&t.push({allowScopeFallback:!0,name:U,preferredScope:"global",spec:Oo(o.docsUrl??jo)}),o.docsOnly!==!0&&ko(o.cwd)&&t.push({allowScopeFallback:!1,name:N,preferredScope:"project",spec:So(V(o.cwd))}),t},Uo=o=>{const t=o.home??$(),e=o.platform??process.platform;o.logger.info("Supported MCP clients:");for(const r of g){const a=r.paths({home:t,platform:e,projectRoot:o.cwd}),n=i=>{const l=a[i];return l===void 0?"—":d(l,o.cwd)};o.logger.info(` ${r.id.padEnd(15)} ${r.label.padEnd(24)} project: ${n("project").padEnd(30)} global: ${n("global")}`)}return{code:0,written:[]}},No=o=>o.docsOnly===!0&&o.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).",_o=(o,t,e)=>{const r=[];for(const a of o)for(const n of t){const i=a.format==="json"?Co(a,n,e):Eo(a,n,e);i!==void 0&&r.push({action:i.action,client:a.id,path:i.path,server:n.name})}return r},Mo=o=>{const t=o.home??$(),e=o.platform??process.platform,r=R(o.clients,()=>bo({home:t,platform:e,projectRoot:o.cwd}),o.logger,"install");if(r===void 0)return{code:1,written:[]};if(r.length===0)return o.logger.error(`mcp install: no MCP client config found — name one explicitly, e.g. \`lunora mcp install claude-code\`. Known clients: ${O.join(", ")}.`),{code:1,written:[]};o.clients.length===0&&o.logger.info(`Detected ${String(r.length)} configured client(s): ${r.map(i=>i.label).join(", ")}.`);const a=Ro(o);if(a.length===0)return o.logger.error(`mcp install: nothing to install — ${No(o)}`),{code:1,written:[]};const n=_o(r,a,{...o,home:t,platform:e});return n.some(i=>i.action==="created"||i.action==="updated")&&o.logger.info("Restart your editor (or reload its MCP servers) to pick up the change."),{code:n.some(i=>i.action==="invalid")?1:0,written:n}},M=100,A=1e3,Ao=o=>({content:[{text:JSON.stringify(o,void 0,2),type:"text"}]}),Fo=o=>({content:[{text:o,type:"text"}]}),Lo=o=>{const t=typeof o=="string"?Number(o):o;return typeof t!="number"||!Number.isFinite(t)?M:Math.min(A,Math.max(1,Math.floor(t)))},Jo=(o,t)=>{const e=h(o,"utf8").split(`
6
+ `);return e.at(-1)===""&&e.pop(),e.slice(-t).join(`
7
+ `)},Po=o=>[{definition:{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=y(o);return Ao(t===void 0?{hint:"Start it with `lunora dev` in the project directory.",running:!1}:{background:t.background===!0,logFile:t.logFile,mode:t.mode,pid:t.pid,running:!0,startedAt:t.startedAt,studioUrl:t.studioUrl,url:t.url})}},{definition:{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(M)}, max ${String(A)})`,type:"number"}},type:"object"},name:"lunora_dev_logs"},handle:async t=>{const e=y(o);if(e===void 0)return{content:[{text:"no dev server is running — start one with `lunora dev`",type:"text"}],isError:!0};if(e.logFile===void 0||!p(e.logFile))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 r=Lo(t.lines),a=Jo(e.logFile,r);return Fo(a.length===0?"(the dev server log is empty)":a)}}],Wo=new Set(["127.0.0.1","::1","localhost"]),F=o=>{try{const{hostname:t}=new URL(o);return Wo.has(t.startsWith("[")?t.slice(1,-1):t)}catch{return!1}},k=o=>{const t=o.url??y(o.cwd)?.url;if(t===void 0||t.length===0)return;if(o.token!==void 0&&o.token.length>0)return{token:o.token,url:t};if(o.url!==void 0&&!F(o.url))return{url:t};const e=oo(o.cwd);return e===void 0||e.length===0?{url:t}:{token:e,url:t}},Do=async o=>{await new Promise(t=>{const e=()=>{t()};o.onclose=e,process.stdin.once("close",e),process.stdin.once("end",e)})},To=(o,t)=>{if(o===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(o.token!==void 0)return`lunora mcp serve: ready — deployment at ${o.url}
8
+ `;const e=t.url!==void 0&&!F(t.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 ${o.url} (${e})
9
+ `},zo=async(o,t=to)=>{const e=o.writeError??(n=>{process.stderr.write(n)});let r;try{r=await t({allowWrites:o.allowWrites===!0,deployment:()=>k(o),docs:o.noDocs===!0?!1:{...o.docsUrl===void 0?{}:{baseUrl:o.docsUrl}},extraTools:Po(o.cwd),version:o.version})}catch(n){const i=n instanceof Error?n.message:String(n);return e(`lunora mcp serve: failed to start — ${i}
10
+ `),{code:1,deployment:void 0}}const a=k(o);return e(To(a,o)),await Do(r),{code:0,deployment:a}},Ho=o=>{const t=[];return o.localOnly!==!0&&t.push(U),o.docsOnly!==!0&&t.push(N),t},Io=(o,t,e,r)=>{const a=ho({key:o.key,name:t,path:e}),n=d(e,r.cwd);return a.action==="removed"?r.logger.success(`${o.label}: removed "${t}" from ${n}.`):a.action==="invalid"&&r.logger.error(`${o.label}: ${n} is not valid JSON (${a.error??"unknown error"}) — left untouched.`),{action:a.action,path:e}},Ko=(o,t,e,r)=>{const a=C({key:o.key,name:t,path:e}),n=d(e,r.cwd);return a==="invalid"?(r.logger.error(`${o.label}: ${n} is not valid JSON — a real run would report it and exit non-zero.`),{action:"invalid",path:e}):a==="absent"?{action:"absent",path:e}:(r.logger.info(`${o.label}: would remove "${t}" from ${n}.`),{action:"removed",path:e})},qo=(o,t,e)=>o.flatMap(r=>yo(r,t)).filter(wo).filter(r=>e===void 0||r.scope===e),Go=o=>{const t=o.home??$(),e=o.platform??process.platform,r=R(o.clients,()=>g,o.logger,"uninstall");if(r===void 0)return{code:1,removed:[]};const a=Ho(o);if(a.length===0)return o.logger.error("mcp uninstall: nothing to remove — `--docs-only` and `--local-only` are mutually exclusive, pass at most one."),{code:1,removed:[]};const n=[],i={home:t,platform:e,projectRoot:o.cwd};for(const l of qo(r,i,o.scope))for(const c of a){const m=o.print===!0?Ko(l.client,c,l.path,o):Io(l.client,c,l.path,o);m.action!=="absent"&&n.push({...m,client:l.client.id,server:c})}return n.length===0?o.logger.info("Nothing to remove — no Lunora MCP servers were configured in the clients checked."):o.print===!0&&o.logger.info("Nothing was changed — re-run without --print to remove these."),{code:n.some(l=>l.action==="invalid")?1:0,removed:n}},S=o=>o.global===!0?"global":o.project===!0?"project":void 0,Vo=async(o,t)=>{const{code:e}=await zo({allowWrites:t.allowWrites===!0,cwd:o,noDocs:t.docs===!1,version:L,...t.docsUrl===void 0?{}:{docsUrl:t.docsUrl},...t.token===void 0?{}:{token:t.token},...t.url===void 0?{}:{url:t.url}});return{code:e}},lt=J(async({argument:o,cwd:t,logger:e,options:r})=>{const[a,...n]=o;if(a==="serve")return Vo(t,r);if(a==="uninstall"){const i=S(r),{code:l}=Go({clients:n,cwd:t,docsOnly:r.docsOnly===!0,localOnly:r.localOnly===!0,logger:e,print:r.print===!0,...i===void 0?{}:{scope:i}});return{code:l}}if(a==="install"){if(r.list===!0)return Uo({cwd:t,logger:e});const i=S(r),{code:l}=Mo({clients:n,cwd:t,docsOnly:r.docsOnly===!0,force:r.force===!0,localOnly:r.localOnly===!0,logger:e,print:r.print===!0,...i===void 0?{}:{scope:i},...r.docsUrl===void 0?{}:{docsUrl:r.docsUrl}});return{code:l}}return e.error("mcp: unknown subcommand. Usage: lunora mcp <install|uninstall|serve>"),{code:1}});export{lt as execute};
@@ -1,4 +1,4 @@
1
- import{existsSync as h,mkdirSync as L,writeFileSync as g,readFileSync as b,readdirSync as re,rmSync as _,mkdtempSync as oe,lstatSync as Te,cpSync as J,renameSync as je}from"node:fs";import{tmpdir as ie}from"node:os";import{detectFramework as Oe,isInteractive as v,LUNA_ART as Be,LUNA_NAME as Ee,LUNA_SIGNOFF as Pe,paintAnswer as De,BADGES as m,detectLintTools as Ve,applyLintIgnores as ze}from"@lunora/config";import{walkSync as Ue}from"@visulima/fs";import{join as p,dirname as S,basename as A,resolve as se,relative as He}from"@visulima/path";import{downloadTemplate as ne}from"giget";import{modify as qe,applyEdits as We}from"jsonc-parser";import{join as D,dirname as Fe}from"node:path";import{p as le,M as Ke,l as V,g as Je,P as Ge,k as Qe}from"../packem_shared/detect-package-manager-DXDstphE.mjs";import{i as Ye}from"../packem_shared/command-0l-ZPhIX.mjs";import Xe from"magic-string";import{Project as Ze,SyntaxKind as f}from"ts-morph";import{P as z}from"../packem_shared/prompt-cancelled-C8Sj7OqI.mjs";import{P as ce,g as de,b as et,L as pe,I as tt}from"../packem_shared/commands-CG9qEtqR.mjs";import{defaultSpawner as ue}from"../packem_shared/createRecordingSpawner-SKs4R1fc.mjs";import{_ as at,R as rt,D as ot,B as he,M as it,o as me,F as ge,v as U,V as st,H as nt,q as ve,C as fe,J as lt}from"../packem_shared/tui-prompts-BU3irGxV.mjs";import{l as we,u as ct,p as dt,b as pt,a as ut,q as ht,h as mt,f as ye,t as be,n as gt,j as vt}from"../packem_shared/lint-ignore-report-CKDXv9MQ.mjs";import{logStep as G}from"../packem_shared/createLogger-BoSxdb2T.mjs";import ft from"node:dns/promises";const H={bun:{githubCacheKey:void 0,githubSetupStep:` - uses: oven-sh/setup-bun@v2
1
+ import{existsSync as h,mkdirSync as L,writeFileSync as g,readFileSync as b,readdirSync as re,rmSync as R,mkdtempSync as oe,lstatSync as Te,cpSync as J,renameSync as je}from"node:fs";import{tmpdir as ie}from"node:os";import{detectFramework as Oe,isInteractive as v,LUNA_ART as Be,LUNA_NAME as Pe,LUNA_SIGNOFF as Ee,paintAnswer as De,BADGES as m,detectLintTools as Ve,applyLintIgnores as ze}from"@lunora/config";import{walkSync as Ue}from"@visulima/fs";import{join as p,dirname as S,basename as A,resolve as se,relative as He}from"@visulima/path";import{downloadTemplate as ne}from"giget";import{modify as qe,applyEdits as We}from"jsonc-parser";import{join as D,dirname as Fe}from"node:path";import{p as le,M as Ke,l as V,g as Je,P as Ge,k as Qe}from"../packem_shared/detect-package-manager-DXDstphE.mjs";import{i as Ye}from"../packem_shared/command-0l-ZPhIX.mjs";import Xe from"magic-string";import{Project as Ze,SyntaxKind as f}from"ts-morph";import{P as z}from"../packem_shared/prompt-cancelled-C8Sj7OqI.mjs";import{P as ce,g as de,b as et,O as pe}from"../packem_shared/resolve-BZp6jitE.mjs";import{defaultSpawner as ue}from"../packem_shared/createRecordingSpawner-SKs4R1fc.mjs";import{_ as tt,R as at,D as rt,B as he,M as ot,o as me,F as ge,v as U,V as it,H as st,q as ve,C as fe,J as nt}from"../packem_shared/tui-prompts-BU3irGxV.mjs";import{l as we,u as lt,p as ct,b as dt,a as pt,q as ut,h as ht,f as ye,t as be,n as mt,j as gt}from"../packem_shared/lint-ignore-report-BR2og7ff.mjs";import{logStep as G}from"../packem_shared/createLogger-BoSxdb2T.mjs";import vt from"node:dns/promises";import{I as ft}from"../packem_shared/commands-BJueH6Qo.mjs";const H={bun:{githubCacheKey:void 0,githubSetupStep:` - uses: oven-sh/setup-bun@v2
2
2
  `,gitlabImage:"oven/bun:1",gitlabProvisionScript:[],installCmd:"bun install --frozen-lockfile",lockfile:"bun.lockb"},npm:{githubCacheKey:"npm",githubSetupStep:"",gitlabImage:"node:22",gitlabProvisionScript:[],installCmd:"npm ci",lockfile:"package-lock.json"},pnpm:{githubCacheKey:"pnpm",githubSetupStep:` - uses: pnpm/action-setup@v4
3
3
  `,gitlabImage:"node:22",gitlabProvisionScript:["corepack enable"],installCmd:"pnpm install --frozen-lockfile",lockfile:"pnpm-lock.yaml"},yarn:{githubCacheKey:"yarn",githubSetupStep:"",gitlabImage:"node:22",gitlabProvisionScript:["corepack enable"],installCmd:"yarn install --frozen-lockfile",lockfile:"yarn.lock"}},$=(e,t)=>{const a=Ke(e,"lunora",t);return[a.command,...a.args].join(" ")},Q=e=>` - uses: actions/checkout@v4
4
4
  ${e.githubSetupStep} - uses: actions/setup-node@v4
@@ -82,16 +82,16 @@ preview:
82
82
  - if: $CI_PIPELINE_SOURCE == "merge_request_event"
83
83
  script:
84
84
  - ${$(e,["deploy","--preview"])}
85
- `},xe={github:{file:D(".github","workflows","deploy.yml"),secretsHint:"repository secrets (Settings → Secrets and variables → Actions)"},gitlab:{file:".gitlab-ci.yml",secretsHint:"masked CI/CD variables (Settings → CI/CD → Variables)"}},bt=(e,t)=>e==="github"?wt(t):yt(t),xt=e=>e==="github"||e==="gitlab",kt=(e,t,a,r={})=>{const o=D(e,xe[t].file);return h(o)&&r.overwrite!==!0?{path:o,skipped:!0,written:!1}:(L(Fe(o),{recursive:!0}),g(o,bt(t,a),"utf8"),{path:o,skipped:!1,written:!0})},$t=(e,t,a,r,o={})=>{const i=xe[t];try{const s=kt(e,t,a,o);if(s.skipped)r.info(`--ci ${t}: ${i.file} already exists — left unchanged (re-run with overwrite to replace).`);else{const n=le(a),l=[n.command,...n.args].join(" "),{installCmd:d,lockfile:u}=H[a];r.success(`--ci ${t}: wrote ${i.file}`),r.info(`--ci ${t}: set CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID as ${i.secretsHint} to enable deploys.`),r.info(`--ci ${t}: run \`${l}\` and commit ${u} before pushing — the pipeline runs \`${d}\`.`)}return s}catch(s){const n=s instanceof Error?s.message:String(s);return r.warn(`--ci ${t}: could not write ${i.file} (${n})`),{path:D(e,i.file),skipped:!1,written:!1}}},Ct={astro:"@lunora/react",none:"@lunora/react",nuxt:"@lunora/vue","react-router":"@lunora/react","solid-start":"@lunora/solid",sveltekit:"@lunora/svelte","tanstack-start":"@lunora/react","tanstack-start-solid":"@lunora/solid"},Mt=e=>{const t=Oe(e);return{...t,adapter:Ct[t.framework]}},I="lunora()",Y='import { lunora } from "@lunora/vite";',Lt=/\blunora\s*\(/u,St='"@lunora/vite"',At="'@lunora/vite'",Nt=e=>{for(const t of e.getStatements()){if(t.getKind()!==f.ExportAssignment)continue;const a=t.asKindOrThrow(f.ExportAssignment).getExpression();if(a.getKind()!==f.CallExpression)continue;const r=a.asKindOrThrow(f.CallExpression);if(r.getExpression().getText()!=="defineConfig")continue;const o=r.getArguments()[0];if(o?.getKind()===f.ObjectLiteralExpression)return o.asKindOrThrow(f.ObjectLiteralExpression)}},It=e=>{for(const t of e.getStatements()){if(t.getKind()!==f.ExportAssignment)continue;const a=t.asKindOrThrow(f.ExportAssignment).getExpression();if(a.getKind()===f.ObjectLiteralExpression)return a.asKindOrThrow(f.ObjectLiteralExpression)}},_t=e=>new Ze({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}).createSourceFile("vite.config.ts",e,{overwrite:!0}),Rt=(e,t)=>{const a=t.getImportDeclarations().at(-1)?.getEnd()??0;a===0?e.prepend(`${Y}
85
+ `},xe={github:{file:D(".github","workflows","deploy.yml"),secretsHint:"repository secrets (Settings → Secrets and variables → Actions)"},gitlab:{file:".gitlab-ci.yml",secretsHint:"masked CI/CD variables (Settings → CI/CD → Variables)"}},bt=(e,t)=>e==="github"?wt(t):yt(t),xt=e=>e==="github"||e==="gitlab",kt=(e,t,a,r={})=>{const o=D(e,xe[t].file);return h(o)&&r.overwrite!==!0?{path:o,skipped:!0,written:!1}:(L(Fe(o),{recursive:!0}),g(o,bt(t,a),"utf8"),{path:o,skipped:!1,written:!0})},$t=(e,t,a,r,o={})=>{const i=xe[t];try{const s=kt(e,t,a,o);if(s.skipped)r.info(`--ci ${t}: ${i.file} already exists — left unchanged (re-run with overwrite to replace).`);else{const n=le(a),l=[n.command,...n.args].join(" "),{installCmd:d,lockfile:u}=H[a];r.success(`--ci ${t}: wrote ${i.file}`),r.info(`--ci ${t}: set CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID as ${i.secretsHint} to enable deploys.`),r.info(`--ci ${t}: run \`${l}\` and commit ${u} before pushing — the pipeline runs \`${d}\`.`)}return s}catch(s){const n=s instanceof Error?s.message:String(s);return r.warn(`--ci ${t}: could not write ${i.file} (${n})`),{path:D(e,i.file),skipped:!1,written:!1}}},Ct={astro:"@lunora/react",none:"@lunora/react",nuxt:"@lunora/vue","react-router":"@lunora/react","solid-start":"@lunora/solid",sveltekit:"@lunora/svelte","tanstack-start":"@lunora/react","tanstack-start-solid":"@lunora/solid",vinext:"@lunora/react"},Mt=e=>{const t=Oe(e);return{...t,adapter:Ct[t.framework]}},I="lunora()",Y='import { lunora } from "@lunora/vite";',Lt=/\blunora\s*\(/u,St='"@lunora/vite"',At="'@lunora/vite'",Nt=e=>{for(const t of e.getStatements()){if(t.getKind()!==f.ExportAssignment)continue;const a=t.asKindOrThrow(f.ExportAssignment).getExpression();if(a.getKind()!==f.CallExpression)continue;const r=a.asKindOrThrow(f.CallExpression);if(r.getExpression().getText()!=="defineConfig")continue;const o=r.getArguments()[0];if(o?.getKind()===f.ObjectLiteralExpression)return o.asKindOrThrow(f.ObjectLiteralExpression)}},It=e=>{for(const t of e.getStatements()){if(t.getKind()!==f.ExportAssignment)continue;const a=t.asKindOrThrow(f.ExportAssignment).getExpression();if(a.getKind()===f.ObjectLiteralExpression)return a.asKindOrThrow(f.ObjectLiteralExpression)}},Rt=e=>new Ze({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}).createSourceFile("vite.config.ts",e,{overwrite:!0}),_t=(e,t)=>{const a=t.getImportDeclarations().at(-1)?.getEnd()??0;a===0?e.prepend(`${Y}
86
86
  `):e.appendLeft(a,`
87
87
  ${Y}`)},Tt=(e,t)=>{const a=t.getProperty("plugins");if(a===void 0){const i=t.getProperties(),s=t.getStart()+1;if(i.length===0)e.appendLeft(s,` plugins: [${I}] `);else{const n=i[0];n!==void 0&&e.appendLeft(n.getStart(),`plugins: [${I}],
88
- `)}return}const r=a.getDescendantsOfKind(f.ArrayLiteralExpression)[0];if(r===void 0)return;const o=r.getElements();if(o.length===0)e.appendLeft(r.getStart()+1,I);else{const i=o[0];i!==void 0&&e.appendLeft(i.getStart(),`${I}, `)}},ke=e=>{if(Lt.test(e))return{changed:!1,code:e,reason:"lunora plugin already present"};const t=_t(e),a=Nt(t)??It(t);if(a===void 0)return{changed:!1,code:e,reason:"could not locate a Vite config plugins array to patch"};const r=new Xe(e);return!e.includes(St)&&!e.includes(At)&&Rt(r,t),Tt(r,a),{changed:!0,code:r.toString()}},jt=/enotfound|eai_again|econnrefused|etimedout|network|fetch failed|getaddrinfo/u,Ot=/404|not found|could not find|no such/u,Bt=(e,t)=>{const a=e instanceof Error?e.message:String(e),r=a.toLowerCase(),o=`failed to download template "${t.templateType}" from ${t.remote}: ${a}`;return Ot.test(r)?{hints:[`Check the template name "${t.templateType}" and the ref "${t.ref}".`,"List/inspect available templates, or target a branch/tag with `--ref <branch>`."],message:`template "${t.templateType}" not found at ${t.remote}: ${a}`}:jt.test(r)?{hints:["You appear to be offline or unable to reach GitHub.","To scaffold without a network, point at a local template root: `lunora init --from <dir>`."],message:o}:{hints:["If this is a network/offline issue, scaffold from a local root with `lunora init --from <dir>`."],message:o}},R=async(e,t,a)=>{if(v()){await rt(m[e],t,a);return}if(process.stdout.write(`
88
+ `)}return}const r=a.getDescendantsOfKind(f.ArrayLiteralExpression)[0];if(r===void 0)return;const o=r.getElements();if(o.length===0)e.appendLeft(r.getStart()+1,I);else{const i=o[0];i!==void 0&&e.appendLeft(i.getStart(),`${I}, `)}},ke=e=>{if(Lt.test(e))return{changed:!1,code:e,reason:"lunora plugin already present"};const t=Rt(e),a=Nt(t)??It(t);if(a===void 0)return{changed:!1,code:e,reason:"could not locate a Vite config plugins array to patch"};const r=new Xe(e);return!e.includes(St)&&!e.includes(At)&&_t(r,t),Tt(r,a),{changed:!0,code:r.toString()}},jt=/enotfound|eai_again|econnrefused|etimedout|network|fetch failed|getaddrinfo/u,Ot=/404|not found|could not find|no such/u,Bt=(e,t)=>{const a=e instanceof Error?e.message:String(e),r=a.toLowerCase(),o=`failed to download template "${t.templateType}" from ${t.remote}: ${a}`;return Ot.test(r)?{hints:[`Check the template name "${t.templateType}" and the ref "${t.ref}".`,"List/inspect available templates, or target a branch/tag with `--ref <branch>`."],message:`template "${t.templateType}" not found at ${t.remote}: ${a}`}:jt.test(r)?{hints:["You appear to be offline or unable to reach GitHub.","To scaffold without a network, point at a local template root: `lunora init --from <dir>`."],message:o}:{hints:["If this is a network/offline issue, scaffold from a local root with `lunora init --from <dir>`."],message:o}},_=async(e,t,a)=>{if(v()){await at(m[e],t,a);return}if(process.stdout.write(`
89
89
  `),a===void 0||a===""){G(e,t);return}const r=a.split(`
90
90
  `).map(o=>De(o)).join(`
91
91
  `);G(e,`${t}
92
- ${r}`)},Et=async e=>{if(v()){await at();return}e.info(`
92
+ ${r}`)},Pt=async e=>{if(v()){await tt();return}e.info(`
93
93
  ${Be}
94
- ${Ee}: ${Pe}`)},$e=[{description:"LLMs via Workers AI (summarize, generate, stream)",label:"AI",value:"ai"},{description:"Sign-up / sign-in (asks which provider)",label:"Authentication",value:"auth"},{description:"Copy-in auth screens for your framework (sign in/up, reset, 2FA)",label:"Auth UI",value:"auth-ui"},{description:"Snapshot + restore your Durable Object data",label:"Backups",value:"backup"},{description:"Headless browser screenshots + PDFs",label:"Browser rendering",value:"browser"},{description:"Zero Trust identity via Cloudflare Access",label:"Cloudflare Access",value:"cloudflare-access"},{description:"Scheduled jobs via Cron Triggers (@lunora/scheduler)",label:"Cron jobs",value:"crons"},{description:"Cloudflare Email Workers + a dev mail catcher",label:"Transactional email",value:"email"},{description:"OpenFeature feature flags (ctx.flags)",label:"Feature flags",value:"flags"},{description:"External Postgres/MySQL via Hyperdrive",label:"Hyperdrive",value:"hyperdrive"},{description:"Stripe-first payments (checkout, subscription, webhooks)",label:"Payments",value:"payment"},{description:"Live presence / who's-online over hibernated WebSockets",label:"Presence",value:"presence"},{description:"Async message queues (push/pull consumers)",label:"Queues",value:"queue"},{description:"Typed R2 buckets + signed URLs (@lunora/storage)",label:"File storage",value:"storage"},{description:"Durable long-running workflows (step.do, sleep, branch)",label:"Workflows",value:"workflow"}],X=$e.map(e=>e.value),Pt=e=>e==="email"?we:e,Dt=(e,t)=>{const a=[];for(const r of e.split(",").map(o=>o.trim()).filter(Boolean))X.includes(r)?a.includes(r)||a.push(r):t(`init: unknown --add feature "${r}" — expected ${X.join(" | ")}; skipping.`);return a},Vt=async e=>{const t=await mt(e.select),a=await ye(e.text,e.projectName);return{label:"auth",names:[t],transformManifest:r=>be(r,a)}},zt=async e=>{const t=await e.text(pt,{placeholder:"you@yourdomain.com"}),a=ut(t,r=>{e.logger.warn(r)});return{label:"email",names:[we],transformManifest:a===void 0?void 0:r=>ht(r,a)}},Ut=async(e,t)=>{const a=e.resolveAuthUiItem?.()??"auth-ui-react";if(t)return{label:"auth-ui",names:[a]};const r=await ye(e.text,e.projectName);return{label:"auth-ui",names:[a],transformManifest:o=>be(o,r)}},Ht=async e=>{const t=await ct(e.text,e.projectName);return{label:"storage",names:["storage"],transformManifest:a=>dt(a,t)}},qt={auth:Vt,"auth-ui":async(e,t)=>Ut(e,t.includes("auth")),email:zt,storage:Ht},Z=async e=>{if(e.preselected!==void 0&&e.preselected.length>0){await e.applyAll(e.preselected.map(r=>{const o=r==="auth-ui"?e.resolveAuthUiItem?.()??"auth-ui-react":Pt(r);return{label:r,names:[o]}}));return}if(!e.interactive){e.logger.info("tip: add features later with `lunora add <ai|auth|backup|browser|cloudflare-access|crons|email|flags|hyperdrive|payment|presence|queue|storage|workflow>`.");return}const t=await e.multiSelect("Which features do you want to add?",$e,{defaults:[]});if(t.length===0)return;const a=[];for(const r of t){const o=qt[r];a.push(o?await o(e,t):{label:r,names:[r]})}await e.applyAll(a)},Wt=[{description:"Adds an ignores entry to eslint.config.js",label:"ESLint",value:"eslint"},{description:"Writes .prettierignore",label:"Prettier",value:"prettier"},{description:"Adds negated patterns to biome.json",label:"Biome",value:"biome"},{description:"Writes ignorePatterns to .oxlintrc.json",label:"oxlint (oxc)",value:"oxlint"}],Ft="Which linter/formatter do you use? We'll tell it to skip Lunora's generated files.",Kt=async e=>{const t=e.interactive?await e.multiSelect(Ft,Wt,{defaults:e.detected}):[...e.detected];if(t.length===0)return[];const a=e.apply(t);return gt(a,e.logger),a},N="M 259.500 10.552 C 220.080 15.859, 182.424 32.566, 152.500 58.025 C 110.179 94.031, 85.380 137.183, 77.518 188.500 C 75.410 202.255, 74.569 225.677, 75.796 236.466 C 76.757 244.917, 76.683 245.692, 74.518 249.966 C 63.118 272.466, 53.141 303.876, 51.382 322.799 L 50.718 329.943 71.960 320.471 C 83.643 315.262, 93.326 311, 93.478 311 C 93.630 311, 96.547 316.063, 99.959 322.250 C 103.371 328.438, 107.249 334.850, 108.577 336.500 L 110.990 339.500 110.981 336 C 110.977 334.075, 111.499 324.991, 112.143 315.813 L 113.312 299.127 121.406 293.336 C 132.495 285.403, 149.593 271.554, 161 261.268 C 171.556 251.748, 189.116 235, 188.540 235 C 188.337 235, 183.069 238.648, 176.835 243.106 C 142.318 267.789, 68.537 314, 63.646 314 C 61.843 314, 72.791 281.179, 80.905 262.259 C 92.233 235.845, 107.473 212.389, 132.106 183.453 L 138.451 176 148.268 176 C 176.192 176, 197.512 187.154, 212.868 209.797 C 216.470 215.108, 217.035 216.595, 216.477 219.297 C 211.386 243.968, 202.359 274.496, 193.797 296 C 183.898 320.861, 167.147 352.101, 152.395 373.215 L 147.004 380.930 152.891 385.830 C 161.400 392.911, 165.563 396, 166.594 395.998 C 167.092 395.998, 168.772 391.641, 170.327 386.317 C 176.279 365.934, 188.422 338.749, 200.942 317.778 C 223.060 280.731, 256.432 244.369, 294.500 215.836 C 309.956 204.252, 313.937 201.603, 314.719 202.385 C 315.116 202.783, 315.449 213.096, 315.460 225.304 C 315.474 241.855, 315.021 250.405, 313.680 258.924 C 307.009 301.272, 291.175 336.677, 263.112 372 C 255.259 381.883, 227.182 410.673, 218.516 417.727 L 213.532 421.783 223.439 424.880 C 281.705 443.093, 349.165 436.018, 398.616 406.508 C 446.728 377.797, 483.322 331.466, 497.366 281.481 C 503.381 260.075, 504.480 250.741, 504.491 221 C 504.501 191.997, 503.598 184.047, 497.987 163.732 C 484.768 115.871, 452.505 72.708, 407.718 42.964 C 381.051 25.254, 352.818 14.828, 319.695 10.460 C 305.932 8.645, 273.298 8.695, 259.500 10.552",M=`/* The welcome page is a full-bleed starter — reset the browser's default
94
+ ${Pe}: ${Ee}`)},$e=[{description:"LLMs via Workers AI (summarize, generate, stream)",label:"AI",value:"ai"},{description:"Sign-up / sign-in (asks which provider)",label:"Authentication",value:"auth"},{description:"Copy-in auth screens for your framework (sign in/up, reset, 2FA)",label:"Auth UI",value:"auth-ui"},{description:"Snapshot + restore your Durable Object data",label:"Backups",value:"backup"},{description:"Headless browser screenshots + PDFs",label:"Browser rendering",value:"browser"},{description:"Zero Trust identity via Cloudflare Access",label:"Cloudflare Access",value:"cloudflare-access"},{description:"Scheduled jobs via Cron Triggers (@lunora/scheduler)",label:"Cron jobs",value:"crons"},{description:"Cloudflare Email Workers + a dev mail catcher",label:"Transactional email",value:"email"},{description:"OpenFeature feature flags (ctx.flags)",label:"Feature flags",value:"flags"},{description:"External Postgres/MySQL via Hyperdrive",label:"Hyperdrive",value:"hyperdrive"},{description:"Stripe-first payments (checkout, subscription, webhooks)",label:"Payments",value:"payment"},{description:"Live presence / who's-online over hibernated WebSockets",label:"Presence",value:"presence"},{description:"Async message queues (push/pull consumers)",label:"Queues",value:"queue"},{description:"Typed R2 buckets + signed URLs (@lunora/storage)",label:"File storage",value:"storage"},{description:"Durable long-running workflows (step.do, sleep, branch)",label:"Workflows",value:"workflow"}],X=$e.map(e=>e.value),Et=e=>e==="email"?we:e,Dt=(e,t)=>{const a=[];for(const r of e.split(",").map(o=>o.trim()).filter(Boolean))X.includes(r)?a.includes(r)||a.push(r):t(`init: unknown --add feature "${r}" — expected ${X.join(" | ")}; skipping.`);return a},Vt=async e=>{const t=await ht(e.select),a=await ye(e.text,e.projectName);return{label:"auth",names:[t],transformManifest:r=>be(r,a)}},zt=async e=>{const t=await e.text(dt,{placeholder:"you@yourdomain.com"}),a=pt(t,r=>{e.logger.warn(r)});return{label:"email",names:[we],transformManifest:a===void 0?void 0:r=>ut(r,a)}},Ut=async(e,t)=>{const a=e.resolveAuthUiItem?.()??"auth-ui-react";if(t)return{label:"auth-ui",names:[a]};const r=await ye(e.text,e.projectName);return{label:"auth-ui",names:[a],transformManifest:o=>be(o,r)}},Ht=async e=>{const t=await lt(e.text,e.projectName);return{label:"storage",names:["storage"],transformManifest:a=>ct(a,t)}},qt={auth:Vt,"auth-ui":async(e,t)=>Ut(e,t.includes("auth")),email:zt,storage:Ht},Z=async e=>{if(e.preselected!==void 0&&e.preselected.length>0){await e.applyAll(e.preselected.map(r=>{const o=r==="auth-ui"?e.resolveAuthUiItem?.()??"auth-ui-react":Et(r);return{label:r,names:[o]}}));return}if(!e.interactive){e.logger.info("tip: add features later with `lunora add <ai|auth|backup|browser|cloudflare-access|crons|email|flags|hyperdrive|payment|presence|queue|storage|workflow>`.");return}const t=await e.multiSelect("Which features do you want to add?",$e,{defaults:[]});if(t.length===0)return;const a=[];for(const r of t){const o=qt[r];a.push(o?await o(e,t):{label:r,names:[r]})}await e.applyAll(a)},Wt=[{description:"Adds an ignores entry to eslint.config.js",label:"ESLint",value:"eslint"},{description:"Writes .prettierignore",label:"Prettier",value:"prettier"},{description:"Adds negated patterns to biome.json",label:"Biome",value:"biome"},{description:"Writes ignorePatterns to .oxlintrc.json",label:"oxlint (oxc)",value:"oxlint"}],Ft="Which linter/formatter do you use? We'll tell it to skip Lunora's generated files.",Kt=async e=>{const t=e.interactive?await e.multiSelect(Ft,Wt,{defaults:e.detected}):[...e.detected];if(t.length===0)return[];const a=e.apply(t);return mt(a,e.logger),a},N="M 259.500 10.552 C 220.080 15.859, 182.424 32.566, 152.500 58.025 C 110.179 94.031, 85.380 137.183, 77.518 188.500 C 75.410 202.255, 74.569 225.677, 75.796 236.466 C 76.757 244.917, 76.683 245.692, 74.518 249.966 C 63.118 272.466, 53.141 303.876, 51.382 322.799 L 50.718 329.943 71.960 320.471 C 83.643 315.262, 93.326 311, 93.478 311 C 93.630 311, 96.547 316.063, 99.959 322.250 C 103.371 328.438, 107.249 334.850, 108.577 336.500 L 110.990 339.500 110.981 336 C 110.977 334.075, 111.499 324.991, 112.143 315.813 L 113.312 299.127 121.406 293.336 C 132.495 285.403, 149.593 271.554, 161 261.268 C 171.556 251.748, 189.116 235, 188.540 235 C 188.337 235, 183.069 238.648, 176.835 243.106 C 142.318 267.789, 68.537 314, 63.646 314 C 61.843 314, 72.791 281.179, 80.905 262.259 C 92.233 235.845, 107.473 212.389, 132.106 183.453 L 138.451 176 148.268 176 C 176.192 176, 197.512 187.154, 212.868 209.797 C 216.470 215.108, 217.035 216.595, 216.477 219.297 C 211.386 243.968, 202.359 274.496, 193.797 296 C 183.898 320.861, 167.147 352.101, 152.395 373.215 L 147.004 380.930 152.891 385.830 C 161.400 392.911, 165.563 396, 166.594 395.998 C 167.092 395.998, 168.772 391.641, 170.327 386.317 C 176.279 365.934, 188.422 338.749, 200.942 317.778 C 223.060 280.731, 256.432 244.369, 294.500 215.836 C 309.956 204.252, 313.937 201.603, 314.719 202.385 C 315.116 202.783, 315.449 213.096, 315.460 225.304 C 315.474 241.855, 315.021 250.405, 313.680 258.924 C 307.009 301.272, 291.175 336.677, 263.112 372 C 255.259 381.883, 227.182 410.673, 218.516 417.727 L 213.532 421.783 223.439 424.880 C 281.705 443.093, 349.165 436.018, 398.616 406.508 C 446.728 377.797, 483.322 331.466, 497.366 281.481 C 503.381 260.075, 504.480 250.741, 504.491 221 C 504.501 191.997, 503.598 184.047, 497.987 163.732 C 484.768 115.871, 452.505 72.708, 407.718 42.964 C 381.051 25.254, 352.818 14.828, 319.695 10.460 C 305.932 8.645, 273.298 8.695, 259.500 10.552",M=`/* The welcome page is a full-bleed starter — reset the browser's default
95
95
  body margin/padding so it sits flush; everything else is scoped under
96
96
  .lunora-welcome (collision-safe). */
97
97
  body {
@@ -1194,7 +1194,7 @@ export default app;
1194
1194
  ${o.join(`
1195
1195
  `)}
1196
1196
  `,"utf8")},O=e=>e==="lunorash"||e.startsWith("@lunora/"),ma=(e,t,a,r)=>O(e)?r.get(e)??a:t,k=(e,t,a)=>({...e,[t]:a}),ee=(e,t,a)=>Object.fromEntries(Object.entries(e).map(([r,o])=>[r,ma(r,o,t,a)])),ga=async(e,t,a,r)=>{const o=p(e,"package.json"),i=JSON.parse(b(o,"utf8"));let s=k(i.dependencies??{},"lunorash",r);s=k(s,"@lunora/ratelimit",r),a.adapter.startsWith("@lunora/")&&(s=k(s,a.adapter,r));for(const[u,c]of Object.entries(a.extraDependencies??{}))s=k(s,u,c);let n=k(i.devDependencies??{},"@lunora/vite",r);n=k(n,"@lunora/studio",r);for(const[u,c]of Object.entries(pa))n=k(n,u,c);const l=[...Object.keys(s),...Object.keys(n)].filter(u=>O(u)),d=await ce(l,r);i.name=t,i.imports={...i.imports,"#lunora/*":"./lunora/*"},i.dependencies=ee(s,r,d),i.devDependencies=ee(n,r,d),i.scripts={...i.scripts,codegen:"lunora codegen",deploy:"vite build && lunora deploy"},g(o,`${JSON.stringify(i,void 0,4)}
1197
- `,"utf8")},va=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],Ce=e=>va.map(t=>p(e,t)).find(t=>h(t)),fa=(e,t)=>{const a=Ce(e);if(a===void 0){t.warn("overlay: no vite.config found in the create-vite base — add `lunora()` to your Vite plugins manually.");return}const r=ke(b(a,"utf8"));r.changed&&g(a,r.code,"utf8")},wa=async e=>{const{adapter:t,distTag:a,logger:r,name:o,target:i}=e,s=[];x(i,p("lunora","ratelimit","schema.ts"),oa,s),x(i,p("lunora","schema.ts"),ia,s),x(i,p("lunora","messages.ts"),sa,s),x(i,p("src","server.ts"),na,s),x(i,"wrangler.jsonc",la.replaceAll("__NAME__",o),s),x(i,".env.example",da,s);for(const n of t.files)x(i,n.path,n.contents,s);return fa(i,r),await ga(i,o,t,a),ha(i),s},ya=["lunar","silver","silent","waning","waxing","crescent","cosmic","stellar","orbital","gibbous","twilight","midnight","shimmering","drifting","weightless"],ba=["moon","tide","crater","comet","eclipse","halo","orbit","nebula","voyager","lander","rover","beacon","harbor","meadow","fox"],te=e=>e[Math.floor(Math.random()*e.length)],xa=()=>`${te(ya)}-${te(ba)}`,ka=async()=>ft.lookup("github.com").then(()=>!0,()=>!1),$a=/^(?:gh|github):([^/]+)\/([^#/]+)(?:\/[^#]*)?(?:#(.+))?$/,Me=e=>{const t=$a.exec(e);if(t===null)return;const[,a,r,o]=t;if(!(a===void 0||r===void 0))return{owner:a,ref:o??"HEAD",repo:r}},Ca=async e=>{const t=Me(e);if(t===void 0)return;const a=`https://codeload.github.com/${t.owner}/${t.repo}/tar.gz/${t.ref}`;try{const r=await fetch(a,{method:"HEAD"});return r.status===404?!1:r.ok?!0:void 0}catch{return}},Le=async e=>e.isLocal||!(e.source===void 0||Me(e.source)!==void 0)?!0:await ka()?e.source!==void 0&&await Ca(e.source)===!1?(e.logger.error(`template source not found: ${e.source} — double-check --ref / --source, or browse the templates at https://lunora.sh/docs.`),!1):!0:(e.logger.error("you appear to be offline — connect to the internet and try again, or scaffold from a local template with `--from <dir>`."),!1),y={extras:"Let's finish setting up your app.",framework:"Which framework should we launch?",git:"Initialize a new git repository? (optional)",install:"Install dependencies now?",name:"Where should we land your project?",nextHeader:"Liftoff confirmed — explore your project!",packageManager:"Which package manager?"},Ma=new Set([".gitignore",".html",".js",".json",".jsonc",".md",".mjs",".ts",".tsx"]),La=`import { defineConfig } from "vite";
1197
+ `,"utf8")},va=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],Ce=e=>va.map(t=>p(e,t)).find(t=>h(t)),fa=(e,t)=>{const a=Ce(e);if(a===void 0){t.warn("overlay: no vite.config found in the create-vite base — add `lunora()` to your Vite plugins manually.");return}const r=ke(b(a,"utf8"));r.changed&&g(a,r.code,"utf8")},wa=async e=>{const{adapter:t,distTag:a,logger:r,name:o,target:i}=e,s=[];x(i,p("lunora","ratelimit","schema.ts"),oa,s),x(i,p("lunora","schema.ts"),ia,s),x(i,p("lunora","messages.ts"),sa,s),x(i,p("src","server.ts"),na,s),x(i,"wrangler.jsonc",la.replaceAll("__NAME__",o),s),x(i,".env.example",da,s);for(const n of t.files)x(i,n.path,n.contents,s);return fa(i,r),await ga(i,o,t,a),ha(i),s},ya=["lunar","silver","silent","waning","waxing","crescent","cosmic","stellar","orbital","gibbous","twilight","midnight","shimmering","drifting","weightless"],ba=["moon","tide","crater","comet","eclipse","halo","orbit","nebula","voyager","lander","rover","beacon","harbor","meadow","fox"],te=e=>e[Math.floor(Math.random()*e.length)],xa=()=>`${te(ya)}-${te(ba)}`,ka=async()=>vt.lookup("github.com").then(()=>!0,()=>!1),$a=/^(?:gh|github):([^/]+)\/([^#/]+)(?:\/[^#]*)?(?:#(.+))?$/,Me=e=>{const t=$a.exec(e);if(t===null)return;const[,a,r,o]=t;if(!(a===void 0||r===void 0))return{owner:a,ref:o??"HEAD",repo:r}},Ca=async e=>{const t=Me(e);if(t===void 0)return;const a=`https://codeload.github.com/${t.owner}/${t.repo}/tar.gz/${t.ref}`;try{const r=await fetch(a,{method:"HEAD"});return r.status===404?!1:r.ok?!0:void 0}catch{return}},Le=async e=>e.isLocal||!(e.source===void 0||Me(e.source)!==void 0)?!0:await ka()?e.source!==void 0&&await Ca(e.source)===!1?(e.logger.error(`template source not found: ${e.source} — double-check --ref / --source, or browse the templates at https://lunora.sh/docs.`),!1):!0:(e.logger.error("you appear to be offline — connect to the internet and try again, or scaffold from a local template with `--from <dir>`."),!1),y={extras:"Let's finish setting up your app.",framework:"Which framework should we launch?",git:"Initialize a new git repository? (optional)",install:"Install dependencies now?",name:"Where should we land your project?",nextHeader:"Liftoff confirmed — explore your project!",packageManager:"Which package manager?"},Ma=new Set([".gitignore",".html",".js",".json",".jsonc",".md",".mjs",".ts",".tsx"]),La=`import { defineConfig } from "vite";
1198
1198
  import { lunora } from "@lunora/vite";
1199
1199
 
1200
1200
  export default defineConfig({ plugins: [lunora()] });
@@ -1221,8 +1221,8 @@ export const send = mutation
1221
1221
  .mutation(async ({ args }) => {
1222
1222
  return { channelId: args.channelId, text: args.text };
1223
1223
  });
1224
- `,Na="gh:anolilab/lunora/templates",Ia=e=>{const t=e.lastIndexOf(".");return t===-1?!1:Ma.has(e.slice(t))},_a=(e,t)=>e.replaceAll("{{name}}",t),Ra=async(e,t)=>{const a=new Set;for(const r of e)if(A(r)==="package.json")try{const o=JSON.parse(b(r,"utf8"));for(const i of["dependencies","devDependencies"])for(const s of Object.keys(o[i]??{}))O(s)&&a.add(s)}catch{}return ce(a,t)},Ta=(e,t,a)=>{let r;try{r=JSON.parse(e)}catch{return e}let o=e;for(const i of["dependencies","devDependencies"])for(const s of Object.keys(r[i]??{})){if(!O(s))continue;const n=a.get(s)??t,l=qe(o,[i,s],n,{formattingOptions:{insertSpaces:!0,tabSize:4}});o=We(o,l)}return o},ja=["@parcel/watcher","esbuild","lmdb","msgpackr-extract","rs-module-lexer","sharp","unrs-resolver","vue-demi","workerd"],Oa=["cpu-features","protobufjs","ssh2"],Se="pnpm-workspace.yaml",Ba=()=>["# pnpm reads its settings from here (the package.json `pnpm` field is no longer read).","# Pre-approve the toolchain's native build scripts so `pnpm install` runs them","# without the interactive `pnpm approve-builds` step; deny the optional native","# builds a scaffold doesn't need (so no C/C++ toolchain is required).","allowBuilds:",...ja.map(e=>` '${e}': true`),...Oa.map(e=>` '${e}': false`),""].join(`
1225
- `),W=e=>{const t=[];for(const a of Ue(e,{includeDirs:!1,includeFiles:!0}))Te(a.path).isSymbolicLink()||t.push(a.path);return t},Ae=async(e,t,a)=>{const r=W(e),o=[],i=pe(),s=await Ra(r,i);for(const n of r){const l=He(e,n),d=p(t,l);L(S(d),{recursive:!0});const u=b(n);let c=Ia(n)?_a(u.toString("utf8"),a):void 0;c!==void 0&&A(n)==="package.json"&&(c=Ta(c,i,s)),c===void 0?g(d,u):g(d,c,"utf8"),o.push(d)}return o},E=(e,t,a)=>t!==void 0&&t.length>0?t:`${Na}/${e}#${de(a)}`,Ea=e=>e.includes("..")?!1:e.startsWith("gh:")||e.startsWith("github:")||e.startsWith("https://"),C=(e,t)=>{e.info(`[dry-run] would ${t}`)},F=(e,t,a)=>{v()&&process.stdout.write(`
1226
- `),e.success(`scaffolded ${String(t.length)} files into ${a}`)},Pa=(e,t)=>{const{args:a,command:r}=Ge(e,t);return`${r} ${a.join(" ")}`},Ne=(e,t)=>{let a=se(e);for(;;){if(t(a))return!0;const r=S(a);if(r===a)return!1;a=r}},Da=e=>{if(h(p(e,Se)))return!0;const t=p(e,"package.json");if(!h(t))return!1;try{return JSON.parse(b(t,"utf8")).workspaces!==void 0}catch{return!1}},Ie=e=>Ne(e,Da),Va=e=>Ne(e,t=>h(p(t,".git"))),za=async(e,t)=>{if(e.yes===!0||!v()||Va(S(t)))return;if(!await me(y.git,{badge:m.git,defaultYes:!1})){await ge("Sounds good! You can always run git init manually.");return}if(e.dryRun===!0){C(e.logger,"initialize a git repository");return}const a=e.spawner??ue;(await st("Initializing a git repository…",()=>a({args:["init"],command:"git",cwd:t}))).code===0?await R("git","Initialized an empty git repository."):e.logger.warn("`git init` failed — initialize it yourself later with `git init`.")},Ua=async(e,t,a,r)=>{const o=[{code:`cd ./${e}`,lead:"Enter your project directory using"}];t===void 0&&o.push({code:`${a} install`,lead:"Install dependencies with",tail:r?" from the workspace root":void 0}),o.push({code:Qe(a,"dev"),lead:"Run",tail:" to start the dev server."},{code:"lunora add",lead:"Add features like auth or storage using"});const i=[{code:"https://lunora.sh/docs",lead:"Read the docs at"},{code:"https://lunora.sh/chat",lead:"Stuck? Join the chat at"}];if(v()){await nt(m.next,y.nextHeader,o,i);return}const s=o.map(n=>`${n.lead} ${n.code}${n.tail??""}`);s.push("",...i.map(n=>`${n.lead} ${n.code}${n.tail??""}`)),await R("next",y.nextHeader,s.join(`
1227
- `))},Ha=e=>e.yes!==!0&&(e.installPrompt!==void 0||v()),qa=async(e,t)=>{if(!Ha(e)||Ie(S(t)))return;const a=Je(e.packageManagerProbe),[r]=a;if(r===void 0)return;if(!await(e.installPrompt?.confirmInstall??(async()=>me(y.install,{badge:m.deps,defaultYes:!0})))()){await ge("No problem! Remember to install dependencies after setup.");return}let o=r;if(a.length>1&&(o=e.installPrompt?await e.installPrompt.selectManager(a):await U(y.packageManager,a.map(d=>({label:d,value:d})),{badge:m.deps,default:r})??r),e.dryRun===!0){C(e.logger,`install dependencies with ${o}`);return}if(o==="pnpm"){const d=p(t,Se);h(d)||g(d,Ba(),"utf8")}const i=e.spawner??ue,{args:s,command:n}=le(o);await R("deps",`Installing dependencies with ${o}…`);const l=await i({args:s,command:n,cwd:t});if(l.code!==0){e.logger.warn(`\`${n} install\` exited with code ${String(l.code)} — run it yourself in ${A(t)}/.`);return}return await R("deps",`Dependencies installed with ${o}.`),o},Wa=async(e,t,a,r,o)=>{const i=p(e,t);if(!h(i))return o.error(`template not found in local source: ${i}`),{code:1,files:[],target:a};const s=await Ae(i,a,r);return F(o,s,a),{code:0,files:s,target:a}},Fa=async e=>{const{logger:t,name:a,ref:r,source:o,target:i,templateType:s}=e,n=oe(p(ie(),"lunora-init-fetch-")),l=p(n,"template");try{const d=o!==void 0&&o.length>0?r:await et(r,t),u=E(s,o,d);let c,w=[];await ve([{label:`${s} template fetched`,run:async()=>{c=await ne(u,{cwd:n,dir:l,force:!0,install:!1,silent:!0})}},{label:`files copied into ${a}/`,run:async()=>{w=await Ae(l,i,a)}}],{end:"Project initialized!",start:"Project initializing…"});const K=W(l);return v()&&process.stdout.write(`
1228
- `),t.info(c?.commit?`template: ${c.source} @ ${c.commit} (${String(K.length)} files)`:`template: ${c?.source??u} (${String(K.length)} files)`),F(t,w,i),{code:0,files:w,target:i}}catch(d){if(d instanceof z)throw d;const{hints:u,message:c}=Bt(d,{ref:de(r),remote:E(s,o,r),templateType:s});t.error(c);for(const w of u)t.warn(w);return{code:1,files:[],target:i}}finally{_(n,{force:!0,recursive:!0})}},Ka=e=>{for(const t of["_gitignore","_npmrc","_gitattributes"]){const a=p(e,t);h(a)&&je(a,p(e,`.${t.slice(1)}`))}},Ja=async e=>{const{framework:t,logger:a,name:r,overlayBaseFrom:o,target:i}=e,s=j[t],n=oe(p(ie(),"lunora-vite-base-"));try{let l;if(o!==void 0&&(l=p(o,`template-${s.createViteTemplate}`),!h(l)))return a.error(`create-vite base not found on disk: ${l}`),{code:1,files:[],target:i};const d=async()=>{if(l!==void 0){J(l,i,{recursive:!0});return}const c=p(n,"base"),w=`github:vitejs/vite/packages/create-vite/template-${s.createViteTemplate}#main`;await ne(w,{cwd:n,dir:c,force:!0,install:!1,silent:!0}),Ka(c),J(c,i,{recursive:!0})};let u=[];return await ve([{label:`create-vite (${s.label}) base ready`,run:d},{label:`Lunora overlay applied (${s.label})`,run:async()=>{u=await wa({adapter:s,distTag:pe(),logger:a,name:r,target:i})}}],{end:"Project initialized!",start:"Project initializing…"}),F(a,u,i),{code:0,files:[...W(i)],target:i}}catch(l){if(l instanceof z)throw l;const d=l instanceof Error?l.message:String(l);return a.error(`failed to scaffold the ${s.label} base: ${d}`),{code:1,files:[],target:i}}finally{_(n,{force:!0,recursive:!0})}},P=(e,t,a,r,o)=>(o.error(`init --in-place: could not ${e} ${t}: ${a instanceof Error?a.message:String(a)}`),{code:1,files:[],target:r}),Ga=(e,t)=>{const a=p(e,"vite.config.ts");try{g(a,La,"utf8")}catch(r){return P("write",a,r,e,t)}return t.success(`created ${a} with lunora() plugin`),{code:0,files:[a],target:e}},Qa=(e,t,a)=>{let r;try{r=b(e,"utf8")}catch(i){return P("read",e,i,t,a)}const o=ke(r);if(!o.changed)return a.info(`${e}: ${o.reason??"no changes needed"}`),{code:0,files:[],target:t};try{g(e,o.code,"utf8")}catch(i){return P("write",e,i,t,a)}return a.success(`patched ${e} — added lunora() plugin`),{code:0,files:[e],target:t}},Ya=(e,t)=>{const a=p(e,"lunora"),r=p(a,"schema.ts");if(h(r))return t.info(`lunora/ already present — left ${r} untouched`),[];const o=[];try{L(a,{recursive:!0}),g(r,Sa,"utf8"),o.push(r);const i=p(a,"messages.ts");h(i)||(g(i,Aa,"utf8"),o.push(i)),t.success(`scaffolded lunora/ (${String(o.length)} file(s))`)}catch(i){const s=i instanceof Error?i.message:String(i);t.error(`init --here: could not scaffold lunora/: ${s}`)}return o},Xa=(e,t,a)=>{const{adapter:r,class:o,framework:i}=e;a.info(""),a.info(`detected framework: ${i} (class ${o})`),a.info("next steps:"),a.info(` 1. install the adapter: ${Pa(t,[r,"@lunora/client","@lunora/runtime","@lunora/server"])}`),a.info(" 2. run codegen: lunora codegen"),o==="A"?(a.info(" 3. compose one worker: wrap your worker entry with"),a.info(" createWorker({ httpRouter: <your framework SSR handler>, shardDO: ShardDO, ... })"),a.info(` 4. add the provider: mount the ${r} provider in your root layout/route`),a.info(" 5. make a loader live: preloadQuery() in a loader, usePreloadedQuery() in the component"),a.info(" see https://lunora.sh/docs/frameworks/reactive-loaders")):o==="B"?(a.info(" 3. inject Lunora: mount Lunora realtime under /_lunora/* in your server hook"),a.info(` (${i} owns its Cloudflare adapter — Lunora composes into its server entry)`),a.info(` 4. add the provider: mount the ${r} provider in your root layout`),a.info(" 5. read the guide: https://lunora.sh/docs/frameworks/deploy")):(a.info(" 3. add the provider: wrap your app with the LunoraProvider from @lunora/react"),a.info(" 4. read the guide: https://lunora.sh/docs/frameworks/bring-your-framework")),a.info("")},Za=(e,t,a)=>{const r=Ce(e);return r===void 0?t==="sveltekit"||t==="nuxt"||t==="astro"?(a.info(`no Vite config found — ${t} wires Lunora through its server entry (see next steps)`),{code:0,files:[],target:e}):Ga(e,a):Qa(r,e,a)},er=(e,t)=>{const a=Mt(e),r=Za(e,a.framework,t);if(r.code!==0)return r;const o=Ya(e,t);return Xa(a,V(e),t),{code:0,files:[...r.files,...o],target:e}},tr=e=>e.yes!==!0&&(e.prompt!==void 0||(e.interactive??v())),ae=async(e,t,a)=>{a.dryRun!==!0&&await Kt({apply:r=>ze(e,r),detected:Ve(e),interactive:t,logger:a.logger,multiSelect:a.lintPrompt??((r,o,i)=>fe(r,o,{...i,badge:m.add}))})},ar=async(e,t)=>{const a=tr(e),r=e.add===void 0?[]:Dt(e.add,i=>{e.logger.warn(i)}),o={applyAll:async i=>{if(i.length===0)return!0;if(e.dryRun===!0)return C(e.logger,`add ${i.map(c=>c.label).join(", ")}`),!0;const s=[],n=v()?{error:c=>{s.push({level:"error",message:c})},info:()=>{},success:()=>{},warn:c=>{s.push({level:"warn",message:c})}}:e.logger,l=i.map(c=>({running:`adding ${c.label}…`,task:()=>tt({allowUnsafeSource:e.allowUnsafeSource,cwd:t,from:e.registryFrom,logger:n,names:[...c.names],ref:e.ref,source:e.registrySource,transformManifest:c.transformManifest,yes:!0})})),d=`added ${i.map(c=>c.label).join(", ")}`,u=await lt(m.add,l,d);for(const{level:c,message:w}of s)e.logger[c](w);return u.every(c=>c.code===0)},interactive:a,logger:e.logger,multiSelect:e.prompt?.multiSelect??((i,s,n)=>fe(i,s,{...n,badge:m.add})),preselected:r.length>0?r:void 0,projectName:A(t),resolveAuthUiItem:()=>{try{const i=JSON.parse(b(p(t,"package.json"),"utf8"));return vt({...i.dependencies,...i.devDependencies})??"auth-ui-react"}catch{return"auth-ui-react"}},select:e.prompt?.select??((i,s,n)=>U(i,s,{...n,badge:m.add})),text:e.prompt?.text??((i,s)=>he(i,{...s,badge:m.add}))};if(r.length>0){await Z(o),await ae(t,a,e);return}v()&&await it(y.extras),await Z(o),await ae(t,a,e)},B="react",_e=[{description:"React SPA — official create-vite base + the Lunora layer (the default)",label:"React",value:"react"},{description:"Vue SPA — create-vite base + Lunora",label:"Vue",value:"vue"},{description:"Solid SPA — create-vite base + Lunora",label:"Solid",value:"solid"},{description:"Svelte SPA — create-vite base + Lunora",label:"Svelte",value:"svelte"},{description:"Next.js (App Router) — OpenNext on Cloudflare + a standalone Lunora worker",label:"Next.js",value:"next"},{description:"TanStack Start (React) — SSR with live-loader routes",label:"TanStack Start · React",value:"tanstack-start-react"},{description:"TanStack Start (Solid)",label:"TanStack Start · Solid",value:"tanstack-start-solid"},{description:"React Router (v7, framework mode) — SSR composed into the Lunora worker",label:"React Router",value:"react-router"},{description:"Astro + a standalone Lunora worker",label:"Astro",value:"astro"},{description:"AnalogJS (Angular) — single-worker, Lunora mounted in Nitro",label:"Analog",value:"analog"},{description:"Nuxt (Vue) — single-worker, Lunora mounted in Nitro",label:"Nuxt",value:"nuxt"},{description:"SvelteKit + a standalone Lunora worker",label:"SvelteKit",value:"sveltekit"},{description:"React Native (Expo) — an iOS/Android/web app + a Lunora worker backend",label:"React Native · Expo",value:"expo"},{description:"Worker only — no frontend",label:"Standalone",value:"standalone"}],rr=Object.keys(j).join("|"),Re=_e.filter(e=>!q(e.value)).map(e=>e.value),or=Re.join("|"),ir=e=>q(e)?{framework:e,kind:"overlay"}:{kind:"template",templateType:e},sr=async e=>e.vite!==void 0?{framework:e.vite,kind:"overlay"}:e.templateType!==void 0?{kind:"template",templateType:e.templateType}:!v()||e.yes===!0?{framework:B,kind:"overlay"}:ir(await U(y.framework,_e,{badge:m.tmpl,default:B})??B),nr=e=>{if(v()||e.yes===!0)return;const t=[];if(e.name===void 0&&t.push("a project name (`lunora init <name>`)"),e.templateType===void 0&&e.vite===void 0&&t.push(`a framework — \`--vite <${rr}>\` for an SPA, or \`-t <${or}>\` for a bespoke template`),t.length!==0)return`lunora init can't prompt in a non-interactive terminal — provide ${t.join(" and ")}, or pass --yes to accept the defaults.`},lr=async(e,t,a,r)=>q(t)?await Le({isLocal:e.overlayBaseFrom!==void 0,logger:e.logger})?(L(r,{recursive:!0}),Ja({framework:t,logger:e.logger,name:a,overlayBaseFrom:e.overlayBaseFrom,target:r})):{code:1,files:[],target:r}:(e.logger.error(`init: unknown framework "${t}". Supported overlays: ${Object.keys(j).join(", ")}.`),{code:1,files:[],target:r}),cr=async(e,t,a,r)=>e.from!==void 0?await Wa(e.from,t,r,a,e.logger):e.source!==void 0&&e.source.length>0&&!e.allowUnsafeSource&&!Ea(e.source)?(e.logger.error(`init: refusing --source ${e.source} — only gh:, github:, or https:// sources are allowed (and may not contain ".."). Re-run with --allow-unsafe-source if you really want this.`),{code:1,files:[],target:r}):await Le({isLocal:!1,logger:e.logger,source:E(t,e.source,e.ref)})?Fa({logger:e.logger,name:a,ref:e.ref,source:e.source,target:r,templateType:t}):{code:1,files:[],target:r},dr=async(e,t,a)=>{await ot("realtime backend on Cloudflare Workers + Durable Objects");const r=nr(e);if(r!==void 0)return e.logger.error(r),{code:1,files:[],target:""};const o=xa(),i=e.name??await he(y.name,{badge:m.dir,default:o,placeholder:o}),s=await sr(e),n=i.trim();if(n.length===0)return e.logger.error("init: refusing an empty project name — pass a directory name (e.g. `lunora init my-app`)."),{code:1,files:[],target:""};if(n.includes("/")||n.includes("\\")||n===".."||n===".")return e.logger.error(`init: refusing project name "${n}" — must not contain path separators or be "." / "..".`),{code:1,files:[],target:""};const l=se(t,n),d=h(l);if(d&&re(l).length>0)return e.logger.error(`target directory not empty: ${l}`),{code:1,files:[],target:l};if(e.dryRun===!0){const u=s.kind==="overlay"?`the ${s.framework} create-vite overlay`:`the ${s.templateType} template`;return C(e.logger,`scaffold ${u} into ${l}`),{code:0,files:[],target:l}}return a(l,d),s.kind==="overlay"?lr(e,s.framework,n,l):cr(e,s.templateType,n,l)},pr=(e,t)=>{const{target:a,targetPreExisted:r}=e;if(!(a===void 0||!h(a))){if(r===!0)for(const o of re(a))_(p(a,o),{force:!0,recursive:!0});else _(a,{force:!0,recursive:!0});t.info(`removed the partially-created project at ${a}`)}},ur=async(e,t,a)=>e.inPlace!==!0?dr(e,t,a):e.dryRun===!0?(C(e.logger,`configure Lunora into ${t}`),{code:0,files:[],target:t}):er(t,e.logger),hr=async(e,t,a)=>{await ar(e,t.target);const r=e.inPlace===!0?void 0:await qa(e,t.target);if(e.inPlace!==!0){await za(e,t.target);const o=r??V(t.target);await Ua(A(t.target),r,o,Ie(a)),await Et(e.logger)}},mr=(e,t,a)=>{if(t.code!==0||e.ci===void 0)return;if(e.dryRun===!0){C(e.logger,`scaffold a ${e.ci} CI deploy pipeline`);return}const r=e.inPlace===!0?a:t.target;try{const o=V(r);$t(r,e.ci,o,e.logger)}catch{e.logger.warn(`--ci ${e.ci}: could not detect a package manager for this project — skipped the CI pipeline.`)}},gr=async e=>{const t=e.cwd??process.cwd(),a={};let r;try{r=await ur(e,t,(o,i)=>{a.target=o,a.targetPreExisted=i}),r.code===0&&r.target!==""&&(a.target=void 0,await hr(e,r,t))}catch(o){if(o instanceof z)return pr(a,e.logger),process.stdout.write("\n ✖ Setup cancelled — run `lunora init` again whenever you're ready. 🌙\n"),{code:130,files:[],target:""};throw o}return mr(e,r,t),r},vr=e=>typeof e=="string"&&Re.includes(e),fr=(e,t)=>{if(e!==void 0){if(xt(e))return e;t.warn(`init: unknown --ci "${e}" — expected github | gitlab; skipping CI scaffold.`)}},Er=Ye(({argument:e,cwd:t,logger:a,options:r})=>{const o=r.template!==void 0&&vr(r.template)?r.template:void 0;return gr({add:r.add,allowUnsafeSource:r.allowUnsafeSource===!0,cwd:t,ci:fr(r.ci,a),dryRun:r.dryRun===!0,from:r.from,inPlace:r.here===!0,interactive:r.interactive===!0?!0:void 0,logger:a,name:e[0],ref:r.ref,source:r.source,templateType:o,vite:r.vite,yes:r.yes===!0})});export{Er as execute,vr as isTemplate,E as resolveTemplateSource,gr as runInitCommand};
1224
+ `,Na="gh:anolilab/lunora/templates",Ia=e=>{const t=e.lastIndexOf(".");return t===-1?!1:Ma.has(e.slice(t))},Ra=(e,t)=>e.replaceAll("{{name}}",t),_a=async(e,t)=>{const a=new Set;for(const r of e)if(A(r)==="package.json")try{const o=JSON.parse(b(r,"utf8"));for(const i of["dependencies","devDependencies"])for(const s of Object.keys(o[i]??{}))O(s)&&a.add(s)}catch{}return ce(a,t)},Ta=(e,t,a)=>{let r;try{r=JSON.parse(e)}catch{return e}let o=e;for(const i of["dependencies","devDependencies"])for(const s of Object.keys(r[i]??{})){if(!O(s))continue;const n=a.get(s)??t,l=qe(o,[i,s],n,{formattingOptions:{insertSpaces:!0,tabSize:4}});o=We(o,l)}return o},ja=["@parcel/watcher","esbuild","lmdb","msgpackr-extract","rs-module-lexer","sharp","unrs-resolver","vue-demi","workerd"],Oa=["cpu-features","protobufjs","ssh2"],Se="pnpm-workspace.yaml",Ba=()=>["# pnpm reads its settings from here (the package.json `pnpm` field is no longer read).","# Pre-approve the toolchain's native build scripts so `pnpm install` runs them","# without the interactive `pnpm approve-builds` step; deny the optional native","# builds a scaffold doesn't need (so no C/C++ toolchain is required).","allowBuilds:",...ja.map(e=>` '${e}': true`),...Oa.map(e=>` '${e}': false`),""].join(`
1225
+ `),W=e=>{const t=[];for(const a of Ue(e,{includeDirs:!1,includeFiles:!0}))Te(a.path).isSymbolicLink()||t.push(a.path);return t},Ae=async(e,t,a)=>{const r=W(e),o=[],i=pe(),s=await _a(r,i);for(const n of r){const l=He(e,n),d=p(t,l);L(S(d),{recursive:!0});const u=b(n);let c=Ia(n)?Ra(u.toString("utf8"),a):void 0;c!==void 0&&A(n)==="package.json"&&(c=Ta(c,i,s)),c===void 0?g(d,u):g(d,c,"utf8"),o.push(d)}return o},P=(e,t,a)=>t!==void 0&&t.length>0?t:`${Na}/${e}#${de(a)}`,Pa=e=>e.includes("..")?!1:e.startsWith("gh:")||e.startsWith("github:")||e.startsWith("https://"),C=(e,t)=>{e.info(`[dry-run] would ${t}`)},F=(e,t,a)=>{v()&&process.stdout.write(`
1226
+ `),e.success(`scaffolded ${String(t.length)} files into ${a}`)},Ea=(e,t)=>{const{args:a,command:r}=Ge(e,t);return`${r} ${a.join(" ")}`},Ne=(e,t)=>{let a=se(e);for(;;){if(t(a))return!0;const r=S(a);if(r===a)return!1;a=r}},Da=e=>{if(h(p(e,Se)))return!0;const t=p(e,"package.json");if(!h(t))return!1;try{return JSON.parse(b(t,"utf8")).workspaces!==void 0}catch{return!1}},Ie=e=>Ne(e,Da),Va=e=>Ne(e,t=>h(p(t,".git"))),za=async(e,t)=>{if(e.yes===!0||!v()||Va(S(t)))return;if(!await me(y.git,{badge:m.git,defaultYes:!1})){await ge("Sounds good! You can always run git init manually.");return}if(e.dryRun===!0){C(e.logger,"initialize a git repository");return}const a=e.spawner??ue;(await it("Initializing a git repository…",()=>a({args:["init"],command:"git",cwd:t}))).code===0?await _("git","Initialized an empty git repository."):e.logger.warn("`git init` failed — initialize it yourself later with `git init`.")},Ua=async(e,t,a,r)=>{const o=[{code:`cd ./${e}`,lead:"Enter your project directory using"}];t===void 0&&o.push({code:`${a} install`,lead:"Install dependencies with",tail:r?" from the workspace root":void 0}),o.push({code:Qe(a,"dev"),lead:"Run",tail:" to start the dev server."},{code:"lunora add",lead:"Add features like auth or storage using"});const i=[{code:"https://lunora.sh/docs",lead:"Read the docs at"},{code:"https://lunora.sh/chat",lead:"Stuck? Join the chat at"}];if(v()){await st(m.next,y.nextHeader,o,i);return}const s=o.map(n=>`${n.lead} ${n.code}${n.tail??""}`);s.push("",...i.map(n=>`${n.lead} ${n.code}${n.tail??""}`)),await _("next",y.nextHeader,s.join(`
1227
+ `))},Ha=e=>e.yes!==!0&&(e.installPrompt!==void 0||v()),qa=async(e,t)=>{if(!Ha(e)||Ie(S(t)))return;const a=Je(e.packageManagerProbe),[r]=a;if(r===void 0)return;if(!await(e.installPrompt?.confirmInstall??(async()=>me(y.install,{badge:m.deps,defaultYes:!0})))()){await ge("No problem! Remember to install dependencies after setup.");return}let o=r;if(a.length>1&&(o=e.installPrompt?await e.installPrompt.selectManager(a):await U(y.packageManager,a.map(d=>({label:d,value:d})),{badge:m.deps,default:r})??r),e.dryRun===!0){C(e.logger,`install dependencies with ${o}`);return}if(o==="pnpm"){const d=p(t,Se);h(d)||g(d,Ba(),"utf8")}const i=e.spawner??ue,{args:s,command:n}=le(o);await _("deps",`Installing dependencies with ${o}…`);const l=await i({args:s,command:n,cwd:t});if(l.code!==0){e.logger.warn(`\`${n} install\` exited with code ${String(l.code)} — run it yourself in ${A(t)}/.`);return}return await _("deps",`Dependencies installed with ${o}.`),o},Wa=async(e,t,a,r,o)=>{const i=p(e,t);if(!h(i))return o.error(`template not found in local source: ${i}`),{code:1,files:[],target:a};const s=await Ae(i,a,r);return F(o,s,a),{code:0,files:s,target:a}},Fa=async e=>{const{logger:t,name:a,ref:r,source:o,target:i,templateType:s}=e,n=oe(p(ie(),"lunora-init-fetch-")),l=p(n,"template");try{const d=o!==void 0&&o.length>0?r:await et(r,t),u=P(s,o,d);let c,w=[];await ve([{label:`${s} template fetched`,run:async()=>{c=await ne(u,{cwd:n,dir:l,force:!0,install:!1,silent:!0})}},{label:`files copied into ${a}/`,run:async()=>{w=await Ae(l,i,a)}}],{end:"Project initialized!",start:"Project initializing…"});const K=W(l);return v()&&process.stdout.write(`
1228
+ `),t.info(c?.commit?`template: ${c.source} @ ${c.commit} (${String(K.length)} files)`:`template: ${c?.source??u} (${String(K.length)} files)`),F(t,w,i),{code:0,files:w,target:i}}catch(d){if(d instanceof z)throw d;const{hints:u,message:c}=Bt(d,{ref:de(r),remote:P(s,o,r),templateType:s});t.error(c);for(const w of u)t.warn(w);return{code:1,files:[],target:i}}finally{R(n,{force:!0,recursive:!0})}},Ka=e=>{for(const t of["_gitignore","_npmrc","_gitattributes"]){const a=p(e,t);h(a)&&je(a,p(e,`.${t.slice(1)}`))}},Ja=async e=>{const{framework:t,logger:a,name:r,overlayBaseFrom:o,target:i}=e,s=j[t],n=oe(p(ie(),"lunora-vite-base-"));try{let l;if(o!==void 0&&(l=p(o,`template-${s.createViteTemplate}`),!h(l)))return a.error(`create-vite base not found on disk: ${l}`),{code:1,files:[],target:i};const d=async()=>{if(l!==void 0){J(l,i,{recursive:!0});return}const c=p(n,"base"),w=`github:vitejs/vite/packages/create-vite/template-${s.createViteTemplate}#main`;await ne(w,{cwd:n,dir:c,force:!0,install:!1,silent:!0}),Ka(c),J(c,i,{recursive:!0})};let u=[];return await ve([{label:`create-vite (${s.label}) base ready`,run:d},{label:`Lunora overlay applied (${s.label})`,run:async()=>{u=await wa({adapter:s,distTag:pe(),logger:a,name:r,target:i})}}],{end:"Project initialized!",start:"Project initializing…"}),F(a,u,i),{code:0,files:[...W(i)],target:i}}catch(l){if(l instanceof z)throw l;const d=l instanceof Error?l.message:String(l);return a.error(`failed to scaffold the ${s.label} base: ${d}`),{code:1,files:[],target:i}}finally{R(n,{force:!0,recursive:!0})}},E=(e,t,a,r,o)=>(o.error(`init --in-place: could not ${e} ${t}: ${a instanceof Error?a.message:String(a)}`),{code:1,files:[],target:r}),Ga=(e,t)=>{const a=p(e,"vite.config.ts");try{g(a,La,"utf8")}catch(r){return E("write",a,r,e,t)}return t.success(`created ${a} with lunora() plugin`),{code:0,files:[a],target:e}},Qa=(e,t,a)=>{let r;try{r=b(e,"utf8")}catch(i){return E("read",e,i,t,a)}const o=ke(r);if(!o.changed)return a.info(`${e}: ${o.reason??"no changes needed"}`),{code:0,files:[],target:t};try{g(e,o.code,"utf8")}catch(i){return E("write",e,i,t,a)}return a.success(`patched ${e} — added lunora() plugin`),{code:0,files:[e],target:t}},Ya=(e,t)=>{const a=p(e,"lunora"),r=p(a,"schema.ts");if(h(r))return t.info(`lunora/ already present — left ${r} untouched`),[];const o=[];try{L(a,{recursive:!0}),g(r,Sa,"utf8"),o.push(r);const i=p(a,"messages.ts");h(i)||(g(i,Aa,"utf8"),o.push(i)),t.success(`scaffolded lunora/ (${String(o.length)} file(s))`)}catch(i){const s=i instanceof Error?i.message:String(i);t.error(`init --here: could not scaffold lunora/: ${s}`)}return o},Xa=(e,t,a)=>{const{adapter:r,class:o,framework:i}=e;a.info(""),a.info(`detected framework: ${i} (class ${o})`),a.info("next steps:"),a.info(` 1. install the adapter: ${Ea(t,[r,"@lunora/client","@lunora/runtime","@lunora/server"])}`),a.info(" 2. run codegen: lunora codegen"),o==="A"?(a.info(" 3. compose one worker: wrap your worker entry with"),a.info(" createWorker({ httpRouter: <your framework SSR handler>, shardDO: ShardDO, ... })"),a.info(` 4. add the provider: mount the ${r} provider in your root layout/route`),a.info(" 5. make a loader live: preloadQuery() in a loader, usePreloadedQuery() in the component"),a.info(" see https://lunora.sh/docs/frameworks/reactive-loaders")):o==="B"?(a.info(" 3. inject Lunora: mount Lunora realtime under /_lunora/* in your server hook"),a.info(` (${i} owns its Cloudflare adapter — Lunora composes into its server entry)`),a.info(` 4. add the provider: mount the ${r} provider in your root layout`),a.info(" 5. read the guide: https://lunora.sh/docs/frameworks/deploy")):(a.info(" 3. add the provider: wrap your app with the LunoraProvider from @lunora/react"),a.info(" 4. read the guide: https://lunora.sh/docs/frameworks/bring-your-framework")),a.info("")},Za=(e,t,a)=>{const r=Ce(e);return r===void 0?t==="sveltekit"||t==="nuxt"||t==="astro"?(a.info(`no Vite config found — ${t} wires Lunora through its server entry (see next steps)`),{code:0,files:[],target:e}):Ga(e,a):Qa(r,e,a)},er=(e,t)=>{const a=Mt(e),r=Za(e,a.framework,t);if(r.code!==0)return r;const o=Ya(e,t);return Xa(a,V(e),t),{code:0,files:[...r.files,...o],target:e}},tr=e=>e.yes!==!0&&(e.prompt!==void 0||(e.interactive??v())),ae=async(e,t,a)=>{a.dryRun!==!0&&await Kt({apply:r=>ze(e,r),detected:Ve(e),interactive:t,logger:a.logger,multiSelect:a.lintPrompt??((r,o,i)=>fe(r,o,{...i,badge:m.add}))})},ar=async(e,t)=>{const a=tr(e),r=e.add===void 0?[]:Dt(e.add,i=>{e.logger.warn(i)}),o={applyAll:async i=>{if(i.length===0)return!0;if(e.dryRun===!0)return C(e.logger,`add ${i.map(c=>c.label).join(", ")}`),!0;const s=[],n=v()?{error:c=>{s.push({level:"error",message:c})},info:()=>{},success:()=>{},warn:c=>{s.push({level:"warn",message:c})}}:e.logger,l=i.map(c=>({running:`adding ${c.label}…`,task:()=>ft({allowUnsafeSource:e.allowUnsafeSource,cwd:t,from:e.registryFrom,logger:n,names:[...c.names],ref:e.ref,source:e.registrySource,transformManifest:c.transformManifest,yes:!0})})),d=`added ${i.map(c=>c.label).join(", ")}`,u=await nt(m.add,l,d);for(const{level:c,message:w}of s)e.logger[c](w);return u.every(c=>c.code===0)},interactive:a,logger:e.logger,multiSelect:e.prompt?.multiSelect??((i,s,n)=>fe(i,s,{...n,badge:m.add})),preselected:r.length>0?r:void 0,projectName:A(t),resolveAuthUiItem:()=>{try{const i=JSON.parse(b(p(t,"package.json"),"utf8"));return gt({...i.dependencies,...i.devDependencies})??"auth-ui-react"}catch{return"auth-ui-react"}},select:e.prompt?.select??((i,s,n)=>U(i,s,{...n,badge:m.add})),text:e.prompt?.text??((i,s)=>he(i,{...s,badge:m.add}))};if(r.length>0){await Z(o),await ae(t,a,e);return}v()&&await ot(y.extras),await Z(o),await ae(t,a,e)},B="react",Re=[{description:"React SPA — official create-vite base + the Lunora layer (the default)",label:"React",value:"react"},{description:"Vue SPA — create-vite base + Lunora",label:"Vue",value:"vue"},{description:"Solid SPA — create-vite base + Lunora",label:"Solid",value:"solid"},{description:"Svelte SPA — create-vite base + Lunora",label:"Svelte",value:"svelte"},{description:"Next.js (App Router) — OpenNext on Cloudflare + a standalone Lunora worker",label:"Next.js",value:"next"},{description:"TanStack Start (React) — SSR with live-loader routes",label:"TanStack Start · React",value:"tanstack-start-react"},{description:"TanStack Start (Solid)",label:"TanStack Start · Solid",value:"tanstack-start-solid"},{description:"Next.js App Router on Vite (vinext) — composed into the Lunora worker (experimental)",label:"vinext · App Router",value:"vinext"},{description:"Next.js Pages Router on Vite (vinext) — composed into one worker (experimental)",label:"vinext · Pages Router",value:"vinext-pages"},{description:"React Router (v7, framework mode) — SSR composed into the Lunora worker",label:"React Router",value:"react-router"},{description:"Astro + a standalone Lunora worker",label:"Astro",value:"astro"},{description:"AnalogJS (Angular) — single-worker, Lunora mounted in Nitro",label:"Analog",value:"analog"},{description:"Nuxt (Vue) — single-worker, Lunora mounted in Nitro",label:"Nuxt",value:"nuxt"},{description:"SvelteKit + a standalone Lunora worker",label:"SvelteKit",value:"sveltekit"},{description:"React Native (Expo) — an iOS/Android/web app + a Lunora worker backend",label:"React Native · Expo",value:"expo"},{description:"Worker only — no frontend",label:"Standalone",value:"standalone"}],rr=Object.keys(j).join("|"),_e=Re.filter(e=>!q(e.value)).map(e=>e.value),or=_e.join("|"),ir=e=>q(e)?{framework:e,kind:"overlay"}:{kind:"template",templateType:e},sr=async e=>e.vite!==void 0?{framework:e.vite,kind:"overlay"}:e.templateType!==void 0?{kind:"template",templateType:e.templateType}:!v()||e.yes===!0?{framework:B,kind:"overlay"}:ir(await U(y.framework,Re,{badge:m.tmpl,default:B})??B),nr=e=>{if(v()||e.yes===!0)return;const t=[];if(e.name===void 0&&t.push("a project name (`lunora init <name>`)"),e.templateType===void 0&&e.vite===void 0&&t.push(`a framework — \`--vite <${rr}>\` for an SPA, or \`-t <${or}>\` for a bespoke template`),t.length!==0)return`lunora init can't prompt in a non-interactive terminal — provide ${t.join(" and ")}, or pass --yes to accept the defaults.`},lr=async(e,t,a,r)=>q(t)?await Le({isLocal:e.overlayBaseFrom!==void 0,logger:e.logger})?(L(r,{recursive:!0}),Ja({framework:t,logger:e.logger,name:a,overlayBaseFrom:e.overlayBaseFrom,target:r})):{code:1,files:[],target:r}:(e.logger.error(`init: unknown framework "${t}". Supported overlays: ${Object.keys(j).join(", ")}.`),{code:1,files:[],target:r}),cr=async(e,t,a,r)=>e.from!==void 0?await Wa(e.from,t,r,a,e.logger):e.source!==void 0&&e.source.length>0&&!e.allowUnsafeSource&&!Pa(e.source)?(e.logger.error(`init: refusing --source ${e.source} — only gh:, github:, or https:// sources are allowed (and may not contain ".."). Re-run with --allow-unsafe-source if you really want this.`),{code:1,files:[],target:r}):await Le({isLocal:!1,logger:e.logger,source:P(t,e.source,e.ref)})?Fa({logger:e.logger,name:a,ref:e.ref,source:e.source,target:r,templateType:t}):{code:1,files:[],target:r},dr=async(e,t,a)=>{await rt("realtime backend on Cloudflare Workers + Durable Objects");const r=nr(e);if(r!==void 0)return e.logger.error(r),{code:1,files:[],target:""};const o=xa(),i=e.name??await he(y.name,{badge:m.dir,default:o,placeholder:o}),s=await sr(e),n=i.trim();if(n.length===0)return e.logger.error("init: refusing an empty project name — pass a directory name (e.g. `lunora init my-app`)."),{code:1,files:[],target:""};if(n.includes("/")||n.includes("\\")||n===".."||n===".")return e.logger.error(`init: refusing project name "${n}" — must not contain path separators or be "." / "..".`),{code:1,files:[],target:""};const l=se(t,n),d=h(l);if(d&&re(l).length>0)return e.logger.error(`target directory not empty: ${l}`),{code:1,files:[],target:l};if(e.dryRun===!0){const u=s.kind==="overlay"?`the ${s.framework} create-vite overlay`:`the ${s.templateType} template`;return C(e.logger,`scaffold ${u} into ${l}`),{code:0,files:[],target:l}}return a(l,d),s.kind==="overlay"?lr(e,s.framework,n,l):cr(e,s.templateType,n,l)},pr=(e,t)=>{const{target:a,targetPreExisted:r}=e;if(!(a===void 0||!h(a))){if(r===!0)for(const o of re(a))R(p(a,o),{force:!0,recursive:!0});else R(a,{force:!0,recursive:!0});t.info(`removed the partially-created project at ${a}`)}},ur=async(e,t,a)=>e.inPlace!==!0?dr(e,t,a):e.dryRun===!0?(C(e.logger,`configure Lunora into ${t}`),{code:0,files:[],target:t}):er(t,e.logger),hr=async(e,t,a)=>{await ar(e,t.target);const r=e.inPlace===!0?void 0:await qa(e,t.target);if(e.inPlace!==!0){await za(e,t.target);const o=r??V(t.target);await Ua(A(t.target),r,o,Ie(a)),await Pt(e.logger)}},mr=(e,t,a)=>{if(t.code!==0||e.ci===void 0)return;if(e.dryRun===!0){C(e.logger,`scaffold a ${e.ci} CI deploy pipeline`);return}const r=e.inPlace===!0?a:t.target;try{const o=V(r);$t(r,e.ci,o,e.logger)}catch{e.logger.warn(`--ci ${e.ci}: could not detect a package manager for this project — skipped the CI pipeline.`)}},gr=async e=>{const t=e.cwd??process.cwd(),a={};let r;try{r=await ur(e,t,(o,i)=>{a.target=o,a.targetPreExisted=i}),r.code===0&&r.target!==""&&(a.target=void 0,await hr(e,r,t))}catch(o){if(o instanceof z)return pr(a,e.logger),process.stdout.write("\n ✖ Setup cancelled — run `lunora init` again whenever you're ready. 🌙\n"),{code:130,files:[],target:""};throw o}return mr(e,r,t),r},vr=e=>typeof e=="string"&&_e.includes(e),fr=(e,t)=>{if(e!==void 0){if(xt(e))return e;t.warn(`init: unknown --ci "${e}" — expected github | gitlab; skipping CI scaffold.`)}},Er=Ye(({argument:e,cwd:t,logger:a,options:r})=>{const o=r.template!==void 0&&vr(r.template)?r.template:void 0;return gr({add:r.add,allowUnsafeSource:r.allowUnsafeSource===!0,cwd:t,ci:fr(r.ci,a),dryRun:r.dryRun===!0,from:r.from,inPlace:r.here===!0,interactive:r.interactive===!0?!0:void 0,logger:a,name:e[0],ref:r.ref,source:r.source,templateType:o,vite:r.vite,yes:r.yes===!0})});export{Er as execute,vr as isTemplate,P as resolveTemplateSource,gr as runInitCommand};
@@ -1 +1 @@
1
- import"node:fs";import"node:path";import"node:url";import"@lunora/errors";import"@visulima/cerebro";import"@visulima/cerebro/command/completion";import"@visulima/cerebro/command/version";import{d as S,t as A,i as C,f as D}from"./cli-DiEQDidI.mjs";import"./detect-package-manager-DXDstphE.mjs";import"./createLogger-BoSxdb2T.mjs";export{S as COMMANDS,A as REGISTERED_COMMAND_NAMES,C as VERSION,D as runCli};
1
+ import"node:fs";import"node:path";import"node:url";import"@lunora/errors";import"@visulima/cerebro";import"@visulima/cerebro/command/completion";import"@visulima/cerebro/command/version";import{p as S,a as A,i as C,u as D}from"./cli-Cu92injU.mjs";import"./detect-package-manager-DXDstphE.mjs";import"./createLogger-BoSxdb2T.mjs";export{S as COMMANDS,A as REGISTERED_COMMAND_NAMES,C as VERSION,D as runCli};