@lunora/cli 1.0.0-alpha.124 → 1.0.0-alpha.125
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.mjs +1 -1
- package/dist/index.d.mts +6 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.mjs +1 -1
- package/dist/packem_chunks/handler10.mjs +1 -1
- package/dist/packem_chunks/handler11.mjs +1 -1
- package/dist/packem_chunks/handler13.mjs +2 -2
- package/dist/packem_chunks/handler18.mjs +2 -2
- package/dist/packem_chunks/handler23.mjs +1 -1
- package/dist/packem_chunks/handler3.mjs +2 -2
- package/dist/packem_chunks/runMigrateGenerateCommand.mjs +3 -3
- package/dist/packem_chunks/runRpcCommand.mjs +1 -1
- package/dist/packem_shared/{COMMANDS-DY2j27E4.mjs → COMMANDS-DmB3_936.mjs} +3 -3
- package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-C5vGgrhK.mjs +8 -0
- package/dist/packem_shared/admin-token-DV5A9T5b.mjs +1 -0
- package/dist/packem_shared/admin-url-Ca-KI3d_.mjs +1 -0
- package/package.json +6 -6
- package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-DL87PIEl.mjs +0 -8
- package/dist/packem_shared/admin-url-DfVehV3e.mjs +0 -1
package/dist/bin.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{runCli as s}from"./packem_shared/COMMANDS-
|
|
2
|
+
import{runCli as s}from"./packem_shared/COMMANDS-DmB3_936.mjs";try{const r=await s();process.exit(r)}catch(r){process.stderr.write(`${r instanceof Error?r.message:String(r)}
|
|
3
3
|
`),process.exit(1)}
|
package/dist/index.d.mts
CHANGED
|
@@ -255,11 +255,17 @@ type FetchLike = (input: string, init?: {
|
|
|
255
255
|
}>;
|
|
256
256
|
interface RunCommandOptions {
|
|
257
257
|
args?: string;
|
|
258
|
+
/** Forge this user id for the call (dispatches through the admin-gated `runAs` op). */
|
|
259
|
+
as?: string;
|
|
260
|
+
/** JSON-encoded extra identity claims to accompany {@link RunCommandOptions.as}. */
|
|
261
|
+
claims?: string;
|
|
258
262
|
cwd?: string;
|
|
259
263
|
fetchImpl?: FetchLike;
|
|
260
264
|
functionPath: string;
|
|
261
265
|
logger: Logger;
|
|
262
266
|
shard?: string;
|
|
267
|
+
/** Admin bearer for the `runAs` dispatch; resolved from the environment / `.dev.vars` when absent. */
|
|
268
|
+
token?: string;
|
|
263
269
|
url?: string;
|
|
264
270
|
}
|
|
265
271
|
interface RunCommandResult {
|
package/dist/index.d.ts
CHANGED
|
@@ -255,11 +255,17 @@ type FetchLike = (input: string, init?: {
|
|
|
255
255
|
}>;
|
|
256
256
|
interface RunCommandOptions {
|
|
257
257
|
args?: string;
|
|
258
|
+
/** Forge this user id for the call (dispatches through the admin-gated `runAs` op). */
|
|
259
|
+
as?: string;
|
|
260
|
+
/** JSON-encoded extra identity claims to accompany {@link RunCommandOptions.as}. */
|
|
261
|
+
claims?: string;
|
|
258
262
|
cwd?: string;
|
|
259
263
|
fetchImpl?: FetchLike;
|
|
260
264
|
functionPath: string;
|
|
261
265
|
logger: Logger;
|
|
262
266
|
shard?: string;
|
|
267
|
+
/** Admin bearer for the `runAs` dispatch; resolved from the environment / `.dev.vars` when absent. */
|
|
268
|
+
token?: string;
|
|
263
269
|
url?: string;
|
|
264
270
|
}
|
|
265
271
|
interface RunCommandResult {
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{COMMANDS as o,VERSION as n,runCli as a}from"./packem_shared/COMMANDS-
|
|
1
|
+
import{COMMANDS as o,VERSION as n,runCli as a}from"./packem_shared/COMMANDS-DmB3_936.mjs";import{runCodegenCommand as t}from"./packem_chunks/runCodegenCommand.mjs";import{DEFAULT_IMPORT_BATCH_SIZE as p,runExportCommand as f,runImportCommand as x}from"./packem_shared/DEFAULT_IMPORT_BATCH_SIZE-C5vGgrhK.mjs";import{runDeployCommand as C}from"./packem_chunks/runDeployCommand.mjs";import{planDevCommand as u,runDevCommand as s}from"./packem_chunks/planDevCommand.mjs";import{runInitCommand as g}from"./packem_chunks/runInitCommand.mjs";import{runMigrateGenerateCommand as T}from"./packem_chunks/runMigrateGenerateCommand.mjs";import{runResetCommand as E}from"./packem_chunks/runResetCommand.mjs";import{runRpcCommand as A}from"./packem_chunks/runRpcCommand.mjs";import{insertSchemaExtension as c}from"./packem_shared/insertSchemaExtension-DZReBZ4_.mjs";import{createLogger as _,pail as h}from"./packem_shared/createLogger--C3x1FNE.mjs";import{diffSnapshots as L,renderAddColumn as O,renderCreateIndex as b,renderCreateTable as w,renderDropIndex as B,renderDropTable as F,renderMigrationFile as P,validatorKindToSqlType as U}from"./packem_shared/diffSnapshots-9bDd9nOK.mjs";import{default as q}from"./packem_shared/schemaIrToSnapshot-Clwd2A8e.mjs";import{createRecordingSpawner as N,defaultSpawner as Q}from"./packem_shared/createRecordingSpawner-ByIqBepG.mjs";import{default as j}from"./packem_shared/parseManifest-x3WsxKHz.mjs";import{REQUIRED_COMPATIBILITY_DATE as H,REQUIRED_FLAG as K,validateWranglerProject as Y,validateWranglerConfig as Z}from"@lunora/config";import{buildRegistryIndex as J}from"./packem_shared/buildRegistryIndex-DwySASBu.mjs";import{M as $,q as rr,k as er}from"./packem_shared/commands-B1SpMXov.mjs";export{o as COMMANDS,p as DEFAULT_IMPORT_BATCH_SIZE,H as REQUIRED_COMPATIBILITY_DATE,K as REQUIRED_FLAG,n as VERSION,J as buildRegistryIndex,_ as createLogger,N as createRecordingSpawner,Q as defaultSpawner,L as diffSnapshots,c as insertSchemaExtension,h as pail,j as parseManifest,u as planDevCommand,O as renderAddColumn,b as renderCreateIndex,w as renderCreateTable,B as renderDropIndex,F as renderDropTable,P as renderMigrationFile,$ as runAddCommand,rr as runBuildIndexCommand,a as runCli,t as runCodegenCommand,C as runDeployCommand,s as runDevCommand,f as runExportCommand,x as runImportCommand,g as runInitCommand,T as runMigrateGenerateCommand,er as runRegistryViewCommand,E as runResetCommand,A as runRpcCommand,q as schemaIrToSnapshot,Y as validateWrangler,Z as validateWranglerConfig,U as validatorKindToSqlType};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as p}from"../packem_shared/command-Bjv4VmYA.mjs";import{s as u}from"../packem_shared/resolve-target-vxaXHmvg.mjs";import{runExportCommand as m}from"../packem_shared/DEFAULT_IMPORT_BATCH_SIZE-
|
|
1
|
+
import{i as p}from"../packem_shared/command-Bjv4VmYA.mjs";import{s as u}from"../packem_shared/resolve-target-vxaXHmvg.mjs";import{runExportCommand as m}from"../packem_shared/DEFAULT_IMPORT_BATCH_SIZE-C5vGgrhK.mjs";const s=p(({argument:r,cwd:t,logger:e,options:o})=>m({cwd:t,logger:e,out:r[0]??o.out,prod:o.prod===!0,tables:o.tables,token:o.token,url:u({cwd:t,prod:o.prod===!0,url:o.url})}));export{s as execute};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as m}from"../packem_shared/command-Bjv4VmYA.mjs";import{s as p}from"../packem_shared/resolve-target-vxaXHmvg.mjs";import{runImportCommand as i}from"../packem_shared/DEFAULT_IMPORT_BATCH_SIZE-
|
|
1
|
+
import{i as m}from"../packem_shared/command-Bjv4VmYA.mjs";import{s as p}from"../packem_shared/resolve-target-vxaXHmvg.mjs";import{runImportCommand as i}from"../packem_shared/DEFAULT_IMPORT_BATCH_SIZE-C5vGgrhK.mjs";const d=m(({argument:a,cwd:o,logger:r,options:e})=>{const t=a[0];return t?i({batchSize:e.batchSize,cwd:o,file:t,logger:r,prod:e.prod===!0,table:e.table,token:e.token,url:p({cwd:o,prod:e.prod===!0,url:e.url}),yes:e.yes===!0}):(r.error("import requires a file. Usage: lunora import <path> [--table <name>]"),{code:1})});export{d as execute};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`)},
|
|
1
|
+
import{u as m}from"../packem_shared/admin-url-Ca-KI3d_.mjs";import{i as $}from"../packem_shared/command-Bjv4VmYA.mjs";import{s as S}from"../packem_shared/resolve-target-vxaXHmvg.mjs";const M="__lunora_admin__:getFunctionStats",y=10,v=/\/$/u,u=(o,e)=>({calls:o.calls,conflicts:o.conflicts??0,errors:o.errors,lastErrorMessage:o.lastErrorMessage,maxDurationMs:o.maxDurationMs,meanDurationMs:o.calls===0?0:o.totalDurationMs/o.calls,path:o.path,rate:e}),w=(o,e)=>{const t=o.filter(r=>(r.conflicts??0)>0).map(r=>u(r,r.calls===0?0:(r.conflicts??0)/r.calls)).toSorted((r,s)=>s.rate-r.rate||s.conflicts-r.conflicts).slice(0,e),i=o.filter(r=>r.errors>0).map(r=>u(r,r.calls===0?0:r.errors/r.calls)).toSorted((r,s)=>s.rate-r.rate||s.errors-r.errors).slice(0,e),n=o.map(r=>u(r,0)).toSorted((r,s)=>s.maxDurationMs-r.maxDurationMs).slice(0,e);return{errorHotspots:i,latencyOutliers:n,totalFunctions:o.length,writeContention:t}},p=o=>`${(o*100).toFixed(1)}%`,f=o=>o<1e3?`${Math.round(o).toString()}ms`:`${(o/1e3).toFixed(2)}s`,d=(o,e,t,i)=>[o,...e.length===0?[` ${t}`]:e.map(n=>` ${i(n)}`)],O=o=>{const e=t=>t.lastErrorMessage?` — ${t.lastErrorMessage}`:"";return[`Insights over ${o.totalFunctions.toString()} function${o.totalFunctions===1?"":"s"}`,"",...d("Write-conflict hot-spots (OCC contention — candidates for sharding):",o.writeContention,"none — no write conflicts observed",t=>`${t.path} ${t.conflicts.toString()}/${t.calls.toString()} calls (${p(t.rate)})`),"",...d("Error hot-spots:",o.errorHotspots,"none — no errors observed",t=>`${t.path} ${t.errors.toString()}/${t.calls.toString()} calls (${p(t.rate)})${e(t)}`),"",...d("Latency outliers (slowest single call):",o.latencyOutliers,"none — no functions have run",t=>`${t.path} max ${f(t.maxDurationMs)}, mean ${f(t.meanDurationMs)} over ${t.calls.toString()} calls`)].join(`
|
|
2
|
+
`)},N=o=>o===void 0||!Number.isFinite(o)||o<=0?y:Math.floor(o),x=async o=>{if(o.prod&&o.url===void 0)return o.logger.error("--prod requires an explicit --url (refusing to report from the implicit localhost worker)"),{code:1};const e=o.token??process.env.LUNORA_ADMIN_TOKEN;if(!e)return o.logger.error("admin token required — pass --token or set LUNORA_ADMIN_TOKEN"),{code:1};const t=m(o.url,o.logger,o.cwd);if(t===void 0)return{code:1};const i=`${t.replace(v,"")}/_lunora/rpc`,n=globalThis.fetch;if(typeof n!="function")throw new TypeError("no fetch implementation available — pass fetchImpl or run on Node >= 18");const r={args:{},functionPath:M};o.shard!==void 0&&(r.shardKey=o.shard),o.logger.info(`POST ${i} -> insights`);const s=await n(i,{body:JSON.stringify(r),headers:{authorization:`Bearer ${e}`,"content-type":"application/json"},method:"POST"}),a=await s.text();if(!s.ok)return o.logger.error(`insights failed: HTTP ${String(s.status)}: ${a}`),{code:1};let l;try{l=JSON.parse(a)}catch{return o.logger.error(`insights failed: worker returned non-JSON: ${a}`),{code:1}}const h=l.result??l,{functions:g}=h;if(!Array.isArray(g))return o.logger.error("insights failed: response carried no `functions` array"),{code:1};const c=w(g,N(o.limit));return o.logger.info(o.json?JSON.stringify(c,void 0,2):O(c)),{code:0,report:c}},k=$(({cwd:o,logger:e,options:t})=>{const i=t.limit===void 0?void 0:Number.parseInt(t.limit,10);return x({cwd:o,json:t.json,limit:i,logger:e,prod:t.prod,shard:t.shard,token:t.token,url:S({cwd:o,prod:t.prod===!0,url:t.url})})});export{w as buildInsightsReport,k as execute,O as formatInsightsReport,x as runInsightsCommand};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{existsSync as y}from"node:fs";import{mkdtemp as S,writeFile as v,rm as
|
|
1
|
+
import{existsSync as y}from"node:fs";import{mkdtemp as S,writeFile as v,rm as $}from"node:fs/promises";import{tmpdir as j}from"node:os";import{discoverSchema as k,schemaFromIr as C}from"@lunora/codegen";import{seedPlan as R}from"@lunora/seed";import{join as m}from"@visulima/path";import{Project as x}from"ts-morph";import{i as z}from"../packem_shared/command-Bjv4VmYA.mjs";import{s as A}from"../packem_shared/resolve-target-vxaXHmvg.mjs";import{i as F}from"../packem_shared/tui-prompts-CCt3jm1k.mjs";import{runImportCommand as I}from"../packem_shared/DEFAULT_IMPORT_BATCH_SIZE-C5vGgrhK.mjs";import{runResetCommand as T}from"./runResetCommand.mjs";const p=r=>{if(r===void 0)return!0;try{const{hostname:e}=new URL(r);return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||e==="::1"}catch{return!1}},U=(r,e)=>typeof e=="bigint"?Number(e):e instanceof ArrayBuffer?[...new Uint8Array(e)]:e,c=r=>({code:r,conflicts:0,generated:0,inserted:0,ndjson:""}),N=(r,e)=>{if(!y(e))return r.logger.error(`schema not found: ${e} — run \`vis generate lunora-table --name=<name>\` to create one`),c(1);if(r.reset===!0&&(r.prod===!0||!p(r.url)))return r.logger.error("--reset only clears local .wrangler/state and cannot be combined with --prod or a remote --url"),c(1)},P=async(r,e,t,o)=>{const l=await S(m(j(),"lunora-seed-")),a=m(l,"rows.ndjson");await v(a,r,"utf8");try{const n=await I({batchSize:o.batchSize,cwd:t,fetchImpl:o.fetchImpl,file:a,logger:o.logger,prod:o.prod,token:o.token,url:o.url}),d=n.body?.conflicts??0;return d>0&&o.logger.warn(`${String(d)} row(s) skipped — their _id already exists. Seeding is deterministic; re-run with --reset to wipe local state first, or a different --seed for fresh ids.`),{code:n.code,conflicts:d,generated:e,inserted:n.inserted,ndjson:r}}finally{await $(l,{force:!0,recursive:!0}).catch(()=>{})}},_=(r,e)=>{if(r.table===void 0||e.tables.some(o=>o.name===r.table))return;const t=e.tables.map(o=>o.name).join(", ");return r.logger.error(`unknown table "${r.table}" — schema defines: ${t||"(no tables)"}`),c(1)},B=async(r,e)=>{if(!(!(r.prod===!0||!p(r.url))||r.yes===!0)){if(!process.stdin.isTTY&&r.confirm===void 0)return r.logger.error("seed: refusing to insert into a non-local target without confirmation — re-run with --yes"),c(1);if(!await(r.confirm??F)(`This will insert ${String(e)} generated row(s) into ${r.url??"the production worker"}. Continue?`))return r.logger.info("seed: aborted"),c(1)}},H=async r=>{const e=r.cwd??process.cwd(),t=m(e,"lunora","schema.ts"),o=N(r,t);if(o!==void 0)return o;const l=new x({skipAddingFilesFromTsConfig:!0}),a=k(l,t),n=_(r,a);if(n!==void 0)return n;const d=C(a),g=R(d,{defaultCount:r.count??10,now:r.now,only:r.table===void 0?void 0:[r.table],seed:r.seed??0}),u=[];for(const{rows:f,table:h}of g)for(const b of f)u.push(JSON.stringify({doc:b,table:h},U));const i=u.length>0?`${u.join(`
|
|
2
2
|
`)}
|
|
3
|
-
`:"",s=u.length;if(r.dryRun===!0)return i.length>0&&process.stdout.write(i),r.logger.info(`generated ${String(s)} row(s) across ${String(g.length)} table(s) — dry run, nothing inserted`),{code:0,conflicts:0,generated:s,inserted:0,ndjson:i};if(r.reset===!0){const f=await T({cwd:e,logger:r.logger,yes:!0});if(f.code!==0)return{code:f.code,conflicts:0,generated:s,inserted:0,ndjson:i}}if(s===0)return r.logger.warn("no rows generated — nothing to insert"),{code:0,conflicts:0,generated:0,inserted:0,ndjson:i};const
|
|
3
|
+
`:"",s=u.length;if(r.dryRun===!0)return i.length>0&&process.stdout.write(i),r.logger.info(`generated ${String(s)} row(s) across ${String(g.length)} table(s) — dry run, nothing inserted`),{code:0,conflicts:0,generated:s,inserted:0,ndjson:i};if(r.reset===!0){const f=await T({cwd:e,logger:r.logger,yes:!0});if(f.code!==0)return{code:f.code,conflicts:0,generated:s,inserted:0,ndjson:i}}if(s===0)return r.logger.warn("no rows generated — nothing to insert"),{code:0,conflicts:0,generated:0,inserted:0,ndjson:i};const w=await B(r,s);return w!==void 0?w:P(i,s,e,r)},W=z(async({cwd:r,logger:e,options:t})=>({code:(await H({batchSize:t.batchSize,count:t.count,cwd:r,dryRun:t.dryRun===!0,logger:e,prod:t.prod===!0,reset:t.reset===!0,now:t.now,seed:t.seed,table:t.table,token:t.token,url:A({cwd:r,prod:t.prod===!0,url:t.url}),yes:t.yes===!0})).code}));export{W as execute,H as runSeedCommand};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{VERSION as J}from"../packem_shared/COMMANDS-
|
|
1
|
+
import{VERSION as J}from"../packem_shared/COMMANDS-DmB3_936.mjs";import{i as W}from"../packem_shared/command-Bjv4VmYA.mjs";import{existsSync as u,readFileSync as y,realpathSync as D,statSync as T,writeFileSync as z,chmodSync as I,renameSync as H,unlinkSync as K,mkdirSync as q}from"node:fs";import{homedir as w}from"node:os";import{findWranglerFile as G,readLiveDevServerState as b}from"@lunora/config";import{join as s,dirname as V,relative as Z}from"@visulima/path";import{P as B,M as Q}from"../packem_shared/detect-package-manager-B2eIuAiP.mjs";import{stringify as X}from"smol-toml";import{modify as x,applyEdits as E,parse as Y}from"jsonc-parser";import{resolveAdminToken as oo}from"@lunora/config/studio-host";import{connectLocalStdio as to}from"@lunora/mcp";const m=o=>({args:[...o.args],command:o.command,...o.env===void 0?{}:{env:o.env}}),$=o=>o.transport==="http"?{type:"http",url:o.url}:m(o),eo=o=>o.transport==="http"?{httpUrl:o.url}:m(o),ro=o=>o.transport==="http"?{serverUrl:o.url}:m(o),no=o=>({args:["-y","mcp-remote",o],command:"npx"}),ao=o=>o.transport==="http"?no(o.url):m(o),io=o=>o.transport==="http"?{url:o.url}:m(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,...m(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)=>X({mcp_servers:{[o]:t.transport==="http"?{url:t.url}:{args:[...t.args],command:t.command,...t.env===void 0?{}:{env:t.env}}}}),h=[{buildEntry:$,paths:({projectRoot:o})=>({project:s(o,".mcp.json")}),format:"json",id:"claude-code",key:"mcpServers",label:"Claude Code"},{buildEntry:$,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:$,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}],C=h.map(o=>o.id),uo=o=>h.find(t=>t.id===o.toLowerCase()),v=(o,t)=>{let e=o,r;try{e=D(o),r=T(e).mode}catch{}const n=`${e}.lunora-${Math.random().toString(36).slice(2,10)}.tmp`;try{z(n,t,"utf8"),r!==void 0&&I(n,r),H(n,e)}catch(a){try{K(n)}catch{}throw a}},R={formattingOptions:{insertSpaces:!0,tabSize:4}},k=o=>{const t=[],e=Y(o,t,{allowTrailingComma:!0});return{errors:t,value:e}},g=o=>typeof o=="object"&&o!==null&&!Array.isArray(o),j=(o,t,e)=>{if(!g(o))return;const r=o[t];return g(r)?r[e]:void 0},N=o=>{if(!u(o.path))return"absent";let t;try{t=y(o.path,"utf8")}catch{return"invalid"}if(t.trim().length===0)return"absent";const{errors:e,value:r}=k(t);return e.length>0||!g(r)?"invalid":j(r,o.key,o.name)===void 0?"absent":"present"},mo=o=>N(o)==="present",fo=o=>{const{entry:t,force:e=!1,key:r,name:n,path:a}=o;if(!u(a))return q(V(a),{recursive:!0}),v(a,`${JSON.stringify({[r]:{[n]:t}},void 0,4)}
|
|
2
2
|
`),{action:"created",path:a};const i=y(a,"utf8");if(i.trim().length===0)return v(a,`${JSON.stringify({[r]:{[n]:t}},void 0,4)}
|
|
3
3
|
`),{action:"created",path:a};const{errors:l,value:c}=k(i);if(l.length>0)return{action:"invalid",error:`parse error at offset ${String(l[0]?.offset??0)}`,path:a};if(!g(c))return{action:"invalid",error:"the file's root is not a JSON object",path:a};const f=c[r];if(f!==void 0&&!g(f))return{action:"invalid",error:`"${r}" is not an object`,path:a};if(j(c,r,n)!==void 0&&!e)return{action:"skipped",path:a};try{const d=x(i,[r,n],t,R);d.length>0&&v(a,E(i,d))}catch(d){return{action:"invalid",error:d instanceof Error?d.message:String(d),path:a}}return{action:"updated",path:a}},go=o=>{const{key:t,name:e,path:r}=o;if(!u(r))return{action:"absent",path:r};let n;try{n=y(r,"utf8")}catch(l){return{action:"invalid",error:l instanceof Error?l.message:String(l),path:r}}const{errors:a,value:i}=k(n);if(a.length>0)return{action:"invalid",error:`parse error at offset ${String(a[0]?.offset??0)}`,path:r};if(j(i,t,e)===void 0)return{action:"absent",path:r};try{const l=x(n,[t,e],void 0,R);l.length>0&&v(r,E(n,l))}catch(l){return{action:"invalid",error:l instanceof Error?l.message:String(l),path:r}}return{action:"removed",path:r}},ho=["global","project"],p=(o,t)=>{const e=Z(t,o);return e.length>0&&!e.startsWith("..")?e:o},vo=(o,t)=>{const e=o.paths(t);return ho.flatMap(r=>{const n=e[r];return n===void 0?[]:[{client:o,path:n,scope:r}]})},yo=(o,t,e,r)=>{const n=o.paths(t),a=e==="global"?"project":"global",i=n[e]??(r?void 0:n[a]);if(i!==void 0)return{client:o,path:i,scope:n[e]===void 0?a:e}},$o=o=>h.filter(t=>Object.values(t.paths(o)).some(e=>u(e))),U=(o,t,e,r)=>{if(o.length===0)return t();const n=[];for(const a of o){const i=uo(a);if(i===void 0){e.error(`mcp ${r}: unknown client "${a}". Known clients: ${C.join(", ")}.`);return}n.push(i)}return n},bo=o=>o.client.format==="json",wo="https://lunora.sh/mcp",_="lunora-docs",M="lunora",ko=o=>u(s(o,"lunora"))&&G(o)!==void 0,jo=o=>{const{args:t,command:e}=Q(o,"lunora",["mcp","serve"]);return{args:t,command:e,transport:"stdio"}},So=o=>({transport:"http",url:o}),Oo=o=>({home:o.home,platform:o.platform,projectRoot:o.cwd}),A=(o,t,e)=>yo(o,Oo(e),e.scope??t.preferredScope,e.scope!==void 0||!t.allowScopeFallback),xo=(o,t,e)=>{const r=A(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:n}=r,a=o.buildEntry(t.spec);if(e.print===!0){const c=p(n,e.cwd);return e.force!==!0&&mo({key:o.key,name:t.name,path:n})?(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:n}):(e.logger.info(`${o.label} → ${c}
|
|
4
4
|
${JSON.stringify({[o.key]:{[t.name]:a}},void 0,4)}`),{action:"printed",path:n})}const i=fo({entry:a,force:e.force===!0,key:o.key,name:t.name,path:n}),l=p(n,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:n}},Eo=(o,t,e)=>{const r=A(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 ${p(r,e.cwd)}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{existsSync as
|
|
2
|
-
`,"utf8")},I=async(t,o)=>{await m(o,{recursive:!0});const
|
|
1
|
+
import{existsSync as l}from"node:fs";import{mkdir as m,readFile as f,writeFile as g}from"node:fs/promises";import{join as s}from"node:path";import{LunoraError as k}from"@lunora/errors";import{u as w}from"../packem_shared/admin-url-Ca-KI3d_.mjs";import{i as b}from"../packem_shared/command-Bjv4VmYA.mjs";import{s as y}from"../packem_shared/resolve-target-vxaXHmvg.mjs";import{runExportCommand as h,runImportCommand as $}from"../packem_shared/DEFAULT_IMPORT_BATCH_SIZE-C5vGgrhK.mjs";const v=".lunora-backups",p="manifest.json",S="/_lunora/admin/pitr",N="__lunora_admin__:getPitrBookmark",_="__lunora_admin__:pitrRestore",O=t=>typeof t=="object"&&t!==null&&typeof t.id=="string"&&typeof t.file=="string",u=async t=>{const o=s(t,p);if(!l(o))return[];let r;try{r=JSON.parse(await f(o,"utf8"))}catch(e){const a=e instanceof Error?e.message:String(e);throw new k("INTERNAL",`backup: ${o} exists but is not valid JSON (${a}) — refusing to overwrite it; fix or remove it manually`,{cause:e})}if(!Array.isArray(r))throw new TypeError(`backup: ${o} exists but is not a JSON array — refusing to overwrite it; fix or remove it manually`);return r.filter(O)},x=async(t,o)=>{await g(s(t,p),`${JSON.stringify(o,void 0,2)}
|
|
2
|
+
`,"utf8")},I=async(t,o)=>{await m(o,{recursive:!0});const r=(t.now??(()=>new Date))().toISOString(),e=`lunora-backup-${r.replaceAll(/[.:]/gu,"-")}.ndjson`,a=await h({cwd:t.cwd,fetchImpl:t.fetchImpl,logger:t.logger,out:s(o,e),prod:t.prod,tables:t.tables,token:t.token,url:t.url});if(a.code!==0)return{code:a.code};const i={bytes:a.bytes,createdAt:r,file:e,id:r,rows:a.rows,tables:t.tables},n=await u(o);return n.push(i),await x(o,n),t.logger.success(`backup created: ${e} (${a.rows.toString()} rows, ${a.bytes.toString()} bytes)`),{code:0,entry:i}},A=async(t,o)=>{const r=await u(o);if(r.length===0)return t.logger.info(`no backups found in ${o}`),{code:0};for(const e of r)t.logger.info(`${e.id} ${e.rows.toString()} rows ${e.bytes.toString()} bytes ${e.file}`);return{code:0}},E=async(t,o)=>{const{target:r}=t;if(r===void 0||r.length===0)return t.logger.error("restore requires a backup id or file path. Usage: lunora backup restore <id|file>"),{code:1};const e=(await u(o)).find(i=>i.id===r),a=e?s(o,e.file):r;return l(a)?{code:(await $({cwd:t.cwd,fetchImpl:t.fetchImpl,file:a,logger:t.logger,prod:t.prod,token:t.token,url:t.url,yes:t.yes})).code}:(t.logger.error(`backup not found: ${r}`),{code:1})},T=t=>{const o=t.token??process.env.LUNORA_ADMIN_TOKEN;if(!o){t.logger.error("admin token required — pass --token or set LUNORA_ADMIN_TOKEN");return}if(t.prod&&t.url===void 0){t.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)");return}if(t.restore===!0&&t.at===void 0&&t.bookmark===void 0){t.logger.error("pitr --restore requires --at <time> or --bookmark <bookmark>");return}if(t.restore===!0&&t.prod===!0&&t.yes!==!0){t.logger.error("pitr --restore --prod restores production data in place. Re-run with --yes to confirm.");return}const r=w(t.url,t.logger,t.cwd);if(r===void 0)return;const e=t.pitrFetch??globalThis.fetch;if(typeof e!="function")throw new TypeError("no fetch implementation available — pass pitrFetch or run on Node >= 18");return{fetchImpl:e,requestUrl:`${r}${S}`,token:o}},q=(t,o)=>{const r={};return t.at!==void 0&&(r.time=t.at),o&&t.bookmark!==void 0&&(r.bookmark=t.bookmark),o&&t.restart===!0&&(r.restart=!0),r},J=async t=>{const o=T(t);if(o===void 0)return{code:1};const r=t.restore===!0,e=r?_:N,a=q(t,r),i=r?"restore":"bookmark";t.logger.info(`POST ${o.requestUrl} -> pitr ${i}${t.shard===void 0?"":` (shard "${t.shard}")`}`);const n=await o.fetchImpl(o.requestUrl,{body:JSON.stringify({args:a,functionPath:e,shardKey:t.shard}),headers:{authorization:`Bearer ${o.token}`,"content-type":"application/json"},method:"POST"}),d=await n.text();let c;try{c=JSON.parse(d)}catch{c=d}return t.logger.info(JSON.stringify(c,void 0,2)),{code:n.ok?0:1}},U=async t=>{const o=t.cwd??process.cwd(),r=s(o,t.dir??v);try{return t.subcommand==="create"?await I(t,r):t.subcommand==="list"?await A(t,r):t.subcommand==="pitr"?await J(t):await E(t,r)}catch(e){return t.logger.error(e instanceof Error?e.message:String(e)),{code:1}}},R=t=>t==="create"||t==="list"||t==="pitr"||t==="restore",M=b(({argument:t,cwd:o,logger:r,options:e})=>{const a=t[0];return R(a)?U({at:e.at,bookmark:e.bookmark,cwd:o,dir:e.dir,logger:r,prod:e.prod===!0,restart:e.restart===!0,restore:e.restore===!0,shard:e.shard,subcommand:a,tables:e.tables,target:t[1],token:e.token,url:y({cwd:o,prod:e.prod===!0,url:e.url}),yes:e.yes===!0}):(r.error(`backup: unknown subcommand "${a??""}" — expected create | list | restore | pitr`),{code:1})});export{M as execute,U as runBackupCommand};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{existsSync as m,mkdirSync as S,writeFileSync as h,mkdtempSync as C,rmSync as I,readFileSync as k}from"node:fs";import{tmpdir as A}from"node:os";import{discoverSchema as T,discoverMigrations as N}from"@lunora/codegen";import{isInteractive as M,promptSelect as z,promptText as E}from"@lunora/config";import{LunoraError as
|
|
2
|
-
`,"utf8"),r.logger.success(`wrote ${g}`),l.unsupported.length>0&&r.logger.warn(`${String(l.unsupported.length)} unsupported diff(s) — see the comment block in ${
|
|
1
|
+
import{existsSync as m,mkdirSync as S,writeFileSync as h,mkdtempSync as C,rmSync as I,readFileSync as k}from"node:fs";import{tmpdir as A}from"node:os";import{discoverSchema as T,discoverMigrations as N}from"@lunora/codegen";import{isInteractive as M,promptSelect as z,promptText as E}from"@lunora/config";import{LunoraError as $}from"@lunora/errors";import{join as c}from"@visulima/path";import{Project as w}from"ts-morph";import{u as F}from"../packem_shared/admin-url-Ca-KI3d_.mjs";import{i as O}from"../packem_shared/command-Bjv4VmYA.mjs";import{diffSnapshots as R,renderMigrationFile as q}from"../packem_shared/diffSnapshots-9bDd9nOK.mjs";import{s as D}from"../packem_shared/resolve-target-vxaXHmvg.mjs";import L from"../packem_shared/schemaIrToSnapshot-Clwd2A8e.mjs";import{runExportCommand as j,runImportCommand as B}from"../packem_shared/DEFAULT_IMPORT_BATCH_SIZE-C5vGgrhK.mjs";const H=".snapshot.json",x=/[^\da-z]+/gu,U=(r,e)=>{let o=0,t=r.length;for(;o<t&&r[o]===e;)o+=1;for(;t>o&&r[t-1]===e;)t-=1;return r.slice(o,t)},J=r=>{const e=U(r.toLowerCase().replaceAll(x,"_"),"_");return e===""?"auto":e},P=r=>{const e=(o,t=2)=>o.toString().padStart(t,"0");return`${String(r.getUTCFullYear())}${e(r.getUTCMonth()+1)}${e(r.getUTCDate())}${e(r.getUTCHours())}${e(r.getUTCMinutes())}${e(r.getUTCSeconds())}`},Z=r=>{if(m(r))try{const e=k(r,"utf8"),o=JSON.parse(e);if(o.version!==1)throw new $("INTERNAL",`unsupported snapshot version: ${o.version}`);return o}catch(e){const o=e instanceof Error?e.message:String(e);throw new $("INTERNAL",`failed to read ${r}: ${o}`,{cause:e})}},K=r=>{const e=r.cwd??process.cwd(),o=c(e,"lunora","schema.ts");if(!m(o))return r.logger.error(`schema not found: ${o} — run \`vis generate lunora-table --name=<name>\` to create one`),{code:1,empty:!0,migrationFile:""};const t=new w({skipAddingFilesFromTsConfig:!0}),n=T(t,o),a=L(n),i=c(e,"lunora","migrations"),s=c(i,H);let d;try{d=Z(s)}catch(p){return r.logger.error(p instanceof Error?p.message:String(p)),{code:1,empty:!0,migrationFile:""}}const l=R(d,a);if(l.empty)return r.logger.info("no schema changes detected — snapshot is already up to date"),{code:0,empty:!0,migrationFile:""};const u=(r.now??(()=>new Date))(),b=J(r.name??"auto"),y=`${P(u)}_${b}.sql`,g=c(i,y);S(i,{recursive:!0});const _=q(b,l,u.toISOString());return h(g,_,"utf8"),h(s,`${JSON.stringify(a,void 0,4)}
|
|
2
|
+
`,"utf8"),r.logger.success(`wrote ${g}`),l.unsupported.length>0&&r.logger.warn(`${String(l.unsupported.length)} unsupported diff(s) — see the comment block in ${y} and write the SQL manually`),{code:0,empty:!1,migrationFile:g}},Q="migrations.ts",v=/^[A-Za-z_]\w*$/u,V=new Set(["await","break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","false","finally","for","function","if","implements","import","in","instanceof","interface","let","new","null","package","private","protected","public","return","static","super","switch","this","throw","true","try","typeof","var","void","while","with","yield"]),f='import { defineMigration } from "@lunora/server";',W="__lunora_admin__:runMigration",Y="__lunora_admin__:migrationStatus",G="/_lunora/migrate",X=r=>U(r.trim().toLowerCase().replaceAll(x,"-"),"-"),rr=r=>r.split("-").filter(e=>e.length>0).map((e,o)=>o===0?e:e.charAt(0).toUpperCase()+e.slice(1)).join(""),er=r=>{const e=c(r,"lunora","schema.ts");if(!m(e))return[];try{const o=new w({skipAddingFilesFromTsConfig:!0});return T(o,e).tables.map(t=>t.name)}catch{return[]}},tr=async r=>r.length>0?z("Which table does this migration iterate?",r.map(e=>({label:e,value:e}))):E("Target table for the migration: "),or=async(r,e)=>{if(e.table!==void 0)return e.table;const o=e.promptTable??(M()?tr:void 0);if(o===void 0){e.logger.error("migrate create requires a target table when not running interactively — re-run with --table <table>");return}const t=(await o(er(r)))?.trim();if(t===void 0||t===""){e.logger.error("no table selected — re-run with --table <table>");return}return t},nr=async r=>{const e=r.cwd??process.cwd(),o=X(r.name);if(o==="")return r.logger.error(`invalid migration name: "${r.name}" — must contain at least one alphanumeric character`),{code:1,file:""};const t=rr(o);if(!v.test(t)||V.has(t))return r.logger.error(`invalid migration name: "${r.name}" derives the export \`${t}\`, which is not a valid identifier — pick a name that starts with a letter and isn't a reserved word`),{code:1,file:""};const n=await or(e,r);if(n===void 0)return{code:1,file:""};if(!v.test(n))return r.logger.error(`invalid table: "${n}" — must be a valid identifier ([A-Za-z_][A-Za-z0-9_]*)`),{code:1,file:""};const a=c(e,"lunora"),i=c(a,Q);let s=m(i)?k(i,"utf8"):"";if(s.includes(`id: "${o}"`)||new RegExp(String.raw`\bexport const ${t}\b`,"u").test(s))return r.logger.error(`a migration with id "${o}" (export \`${t}\`) already exists in ${i}`),{code:1,file:""};s.trim()===""?s=`${f}
|
|
3
3
|
`:s.includes(f)||(s=`${f}
|
|
4
4
|
${s}`);const d=`export const ${t} = defineMigration({
|
|
5
5
|
id: "${o}",
|
|
@@ -8,4 +8,4 @@ ${s}`);const d=`export const ${t} = defineMigration({
|
|
|
8
8
|
});`;return S(a,{recursive:!0}),h(i,`${s.trimEnd()}
|
|
9
9
|
|
|
10
10
|
${d}
|
|
11
|
-
`,"utf8"),r.logger.success(`scaffolded migration "${o}" in ${i}`),{code:0,file:i}},ir=(r,e)=>{const o=new w({skipAddingFilesFromTsConfig:!0});return N(o,c(r,"lunora")).find(t=>t.id===e)?.table},ar=(r,e)=>{let o;try{o=ir(r,e.id)}catch(t){e.logger.error(t instanceof Error?t.message:String(t));return}if(o===void 0){e.logger.error(`migration "${e.id}" not found under lunora/ — declare it with defineMigration({ id: "${e.id}", ... })`);return}if(o===""){e.logger.error(`migration "${e.id}" must declare \`table\` as a static string literal`);return}return o},sr=r=>{const e=r.cwd??process.cwd();if(r.prod&&r.url===void 0){r.logger.error("--prod requires an explicit --url (refusing to migrate the implicit localhost worker)");return}if(r.prod&&(r.subcommand==="up"||r.subcommand==="down")&&!r.yes){r.logger.error(`migrate ${r.subcommand} --prod runs the migration against production. Re-run with --yes to confirm.`);return}const o=r.token??process.env.LUNORA_ADMIN_TOKEN;if(!o){r.logger.error("admin token required — pass --token or set LUNORA_ADMIN_TOKEN");return}const t=ar(e,r);if(t===void 0)return;const n=F(r.url,r.logger);if(n===void 0)return;const a=r.fetchImpl??globalThis.fetch;if(typeof a!="function")throw new TypeError("no fetch implementation available — pass fetchImpl or run on Node >= 18");return{fetchImpl:a,requestUrl:`${n}${G}`,table:t,token:o}},cr=r=>{const e={id:r.id};return r.subcommand==="status"||(e.direction=r.subcommand,r.dryRun&&(e.dryRun=!0),r.batchSize!==void 0&&(e.batchSize=r.batchSize),r.maxBatches!==void 0&&(e.maxBatches=r.maxBatches)),e},dr=async r=>{const e=sr(r);if(e===void 0)return{body:void 0,code:1,requestUrl:""};const{fetchImpl:o,requestUrl:t,table:n,token:a}=e,i=r.subcommand==="status"?Y:W,s=cr(r);r.logger.info(`POST ${t} -> ${r.subcommand} ${r.id} (table "${n}")`);const d=await o(t,{body:JSON.stringify({args:s,functionPath:i,table:n}),headers:{authorization:`Bearer ${a}`,"content-type":"application/json"},method:"POST"}),l=await d.text();let u;try{u=JSON.parse(l)}catch{u=l}return r.logger.info(JSON.stringify(u,void 0,2)),{body:u,code:d.ok?0:1,requestUrl:t}},lr=async r=>{const{logger:e}=r,o=r.fromUrl??r.toUrl,t=r.toUrl??r.fromUrl;if(o!==void 0&&o===t)return e.error("source and target are the same deployment — pass distinct --from-url and --to-url so the D1 export and Hyperdrive import don't run against one database"),{code:1};const n=r.out===void 0?C(c(A(),"lunora-d1ps-")):void 0,a=r.out??c(n,"dump.ndjson");try{e.info(`Exporting .global() data from the D1 source (${o??"http://localhost:8787"}) …`);const i=await j({fetchImpl:r.fetchImpl,logger:e,out:a,prod:r.prod,tables:r.tables,token:r.fromToken,url:o});if(i.code!==0)return{code:i.code};e.info(`Exported ${String(i.rows)} row(s) (${String(i.bytes)} bytes).`),e.info(`Importing into the Hyperdrive target (${t??"http://localhost:8787"}) …`);const s=await B({batchSize:r.batchSize,fetchImpl:r.fetchImpl,file:a,logger:e,prod:r.prod,token:r.toToken,url:t});return s.code!==0?{code:s.code}:(s.inserted===i.rows?e.info(`✓ Migrated ${String(i.rows)} row(s) — counts match. Verify your app reads from Hyperdrive, then decommission the D1 binding.`):e.warn(`Imported ${String(s.inserted)} of ${String(i.rows)} exported row(s) — the remainder likely already existed in the target (see conflicts above). Re-run after resolving, or inspect the dump with --out.`),{code:0})}finally{n!==void 0&&I(n,{force:!0,recursive:!0})}},Tr=O(({argument:r,cwd:e,logger:o,options:t})=>{const n=r[0];if(n==="generate")return K({cwd:e,logger:o,name:r[1]??t.name});if(n==="d1-to-hyperdrive")return lr({batchSize:t.batchSize,fromToken:t.fromToken??t.token,fromUrl:t.fromUrl??t.url,logger:o,out:t.out,prod:t.prod===!0,tables:t.tables,toToken:t.toToken??t.token,toUrl:t.toUrl??t.url});if(n==="create"){const a=r[1]??t.name;return a?nr({cwd:e,logger:o,name:a,table:t.table}):(o.error("migrate create requires a name. Usage: lunora migrate create <name> [--table <table>]"),{code:1})}if(n==="up"||n==="down"||n==="status"){const a=r[1]??t.name;return a?dr({batchSize:t.batchSize,cwd:e,dryRun:t.dryRun===!0,id:a,logger:o,maxBatches:t.steps,prod:t.prod===!0,subcommand:n,token:t.token,url:D({cwd:e,prod:t.prod===!0,url:t.url}),yes:t.yes===!0}):(o.error(`migrate ${n} requires a migration id. Usage: lunora migrate ${n} <id>`),{code:1})}return o.error(`unknown migrate subcommand: "${n??""}" — expected generate | create | up | down | status`),{code:1}});export{Tr as execute,nr as runMigrateCreateCommand,dr as runMigrateDataCommand,K as runMigrateGenerateCommand,lr as runMigrateToHyperdriveCommand};
|
|
11
|
+
`,"utf8"),r.logger.success(`scaffolded migration "${o}" in ${i}`),{code:0,file:i}},ir=(r,e)=>{const o=new w({skipAddingFilesFromTsConfig:!0});return N(o,c(r,"lunora")).find(t=>t.id===e)?.table},ar=(r,e)=>{let o;try{o=ir(r,e.id)}catch(t){e.logger.error(t instanceof Error?t.message:String(t));return}if(o===void 0){e.logger.error(`migration "${e.id}" not found under lunora/ — declare it with defineMigration({ id: "${e.id}", ... })`);return}if(o===""){e.logger.error(`migration "${e.id}" must declare \`table\` as a static string literal`);return}return o},sr=r=>{const e=r.cwd??process.cwd();if(r.prod&&r.url===void 0){r.logger.error("--prod requires an explicit --url (refusing to migrate the implicit localhost worker)");return}if(r.prod&&(r.subcommand==="up"||r.subcommand==="down")&&!r.yes){r.logger.error(`migrate ${r.subcommand} --prod runs the migration against production. Re-run with --yes to confirm.`);return}const o=r.token??process.env.LUNORA_ADMIN_TOKEN;if(!o){r.logger.error("admin token required — pass --token or set LUNORA_ADMIN_TOKEN");return}const t=ar(e,r);if(t===void 0)return;const n=F(r.url,r.logger,r.cwd);if(n===void 0)return;const a=r.fetchImpl??globalThis.fetch;if(typeof a!="function")throw new TypeError("no fetch implementation available — pass fetchImpl or run on Node >= 18");return{fetchImpl:a,requestUrl:`${n}${G}`,table:t,token:o}},cr=r=>{const e={id:r.id};return r.subcommand==="status"||(e.direction=r.subcommand,r.dryRun&&(e.dryRun=!0),r.batchSize!==void 0&&(e.batchSize=r.batchSize),r.maxBatches!==void 0&&(e.maxBatches=r.maxBatches)),e},dr=async r=>{const e=sr(r);if(e===void 0)return{body:void 0,code:1,requestUrl:""};const{fetchImpl:o,requestUrl:t,table:n,token:a}=e,i=r.subcommand==="status"?Y:W,s=cr(r);r.logger.info(`POST ${t} -> ${r.subcommand} ${r.id} (table "${n}")`);const d=await o(t,{body:JSON.stringify({args:s,functionPath:i,table:n}),headers:{authorization:`Bearer ${a}`,"content-type":"application/json"},method:"POST"}),l=await d.text();let u;try{u=JSON.parse(l)}catch{u=l}return r.logger.info(JSON.stringify(u,void 0,2)),{body:u,code:d.ok?0:1,requestUrl:t}},lr=async r=>{const{logger:e}=r,o=r.fromUrl??r.toUrl,t=r.toUrl??r.fromUrl;if(o!==void 0&&o===t)return e.error("source and target are the same deployment — pass distinct --from-url and --to-url so the D1 export and Hyperdrive import don't run against one database"),{code:1};const n=r.out===void 0?C(c(A(),"lunora-d1ps-")):void 0,a=r.out??c(n,"dump.ndjson");try{e.info(`Exporting .global() data from the D1 source (${o??"http://localhost:8787"}) …`);const i=await j({fetchImpl:r.fetchImpl,logger:e,out:a,prod:r.prod,tables:r.tables,token:r.fromToken,url:o});if(i.code!==0)return{code:i.code};e.info(`Exported ${String(i.rows)} row(s) (${String(i.bytes)} bytes).`),e.info(`Importing into the Hyperdrive target (${t??"http://localhost:8787"}) …`);const s=await B({batchSize:r.batchSize,fetchImpl:r.fetchImpl,file:a,logger:e,prod:r.prod,token:r.toToken,url:t});return s.code!==0?{code:s.code}:(s.inserted===i.rows?e.info(`✓ Migrated ${String(i.rows)} row(s) — counts match. Verify your app reads from Hyperdrive, then decommission the D1 binding.`):e.warn(`Imported ${String(s.inserted)} of ${String(i.rows)} exported row(s) — the remainder likely already existed in the target (see conflicts above). Re-run after resolving, or inspect the dump with --out.`),{code:0})}finally{n!==void 0&&I(n,{force:!0,recursive:!0})}},Tr=O(({argument:r,cwd:e,logger:o,options:t})=>{const n=r[0];if(n==="generate")return K({cwd:e,logger:o,name:r[1]??t.name});if(n==="d1-to-hyperdrive")return lr({batchSize:t.batchSize,fromToken:t.fromToken??t.token,fromUrl:t.fromUrl??t.url,logger:o,out:t.out,prod:t.prod===!0,tables:t.tables,toToken:t.toToken??t.token,toUrl:t.toUrl??t.url});if(n==="create"){const a=r[1]??t.name;return a?nr({cwd:e,logger:o,name:a,table:t.table}):(o.error("migrate create requires a name. Usage: lunora migrate create <name> [--table <table>]"),{code:1})}if(n==="up"||n==="down"||n==="status"){const a=r[1]??t.name;return a?dr({batchSize:t.batchSize,cwd:e,dryRun:t.dryRun===!0,id:a,logger:o,maxBatches:t.steps,prod:t.prod===!0,subcommand:n,token:t.token,url:D({cwd:e,prod:t.prod===!0,url:t.url}),yes:t.yes===!0}):(o.error(`migrate ${n} requires a migration id. Usage: lunora migrate ${n} <id>`),{code:1})}return o.error(`unknown migrate subcommand: "${n??""}" — expected generate | create | up | down | status`),{code:1}});export{Tr as execute,nr as runMigrateCreateCommand,dr as runMigrateDataCommand,K as runMigrateGenerateCommand,lr as runMigrateToHyperdriveCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as
|
|
1
|
+
import{LunoraError as v}from"@lunora/errors";import{l as w,v as _}from"../packem_shared/admin-token-DV5A9T5b.mjs";import{u as N,s as $}from"../packem_shared/admin-url-Ca-KI3d_.mjs";import{i as b}from"../packem_shared/command-Bjv4VmYA.mjs";import{t as P}from"../packem_shared/resolve-target-vxaXHmvg.mjs";const f=(r,e="--args")=>{if(r===void 0||r.length===0)return{};try{return JSON.parse(r)}catch(o){const t=o instanceof Error?o.message:String(o);throw new v("INTERNAL",`failed to parse ${e} as JSON: ${t}`,{cause:o})}},S=/\/$/u,O="__lunora_admin__:runAs",k="__lunora_admin__:",A=(r,e)=>{const o=e.body?.error?.code;e.runAs||e.status!==403||o!=="FORBIDDEN_SHARD"||r.info("this app authorizes per shard, so an anonymous call is denied — retry with --as <userId> to run as an authenticated user")},E=({args:r,claims:e,options:o,runAs:t})=>{const a=t?{args:{args:r,functionPath:o.functionPath,identity:e,userId:o.as},functionPath:O}:{args:r,functionPath:o.functionPath};return o.shard!==void 0&&(a.shardKey=o.shard),a},I=({cwd:r,logger:e,needsBearer:o,url:t})=>o?N(t,e,r):(P({cwd:r,url:t})??$(r)).replace(S,""),T=async r=>{const e=r.cwd??process.cwd(),o=r.as!==void 0&&r.as!=="",t=o||r.functionPath.startsWith(k),a=I({cwd:e,logger:r.logger,needsBearer:t,url:r.url});if(a===void 0)return{body:void 0,code:1,requestUrl:r.url??""};const s=`${a}/_lunora/rpc`,u=r.fetchImpl??globalThis.fetch;if(typeof u!="function")throw new TypeError("no fetch implementation available — pass --fetch via dependency injection or run on Node >= 18");let l,g;try{l=f(r.args),g=r.claims===void 0?void 0:f(r.claims,"--claims")}catch(d){return r.logger.error(d instanceof Error?d.message:String(d)),{body:void 0,code:1,requestUrl:s}}const{source:m,token:n}=t?w({cwd:e,token:r.token,url:a}):{};if(t&&n===void 0)return r.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{body:void 0,code:1,requestUrl:s};n!==void 0&&r.logger.debug?.(`admin bearer from ${_(m)}`);const p={"content-type":"application/json",...n===void 0?{}:{authorization:`Bearer ${n}`}},y=E({args:l,claims:g,options:r,runAs:o});r.logger.info(`POST ${s} -> ${r.functionPath}${o?` (as ${r.as??""})`:""}`);const c=await u(s,{body:JSON.stringify(y),headers:p,method:"POST"}),h=await c.text();let i;try{i=JSON.parse(h)}catch{i=h}return r.logger.info(JSON.stringify(i,void 0,2)),A(r.logger,{body:i,runAs:o,status:c.status}),{body:i,code:c.ok?0:1,requestUrl:s}},D=b(({argument:r,cwd:e,logger:o,options:t})=>{const a=r[0];return a?T({args:t.args,as:t.as,claims:t.claims,cwd:e,functionPath:a,logger:o,shard:t.shard,token:t.token,url:t.url}):(o.error("missing function path. Usage: lunora run <functionPath> [--args <json>]"),{code:1})});export{D as execute,T as runRpcCommand};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{mkdirSync as x,readFileSync as f,lstatSync as O,writeFileSync as N}from"node:fs";import{join as d,dirname as g}from"node:path";import{fileURLToPath as R}from"node:url";import{resolveHint as B,isLunoraError as v,flattenHint as A,findSolutionByMessage as L}from"@lunora/errors";import{createCerebro as D}from"@visulima/cerebro";import C from"@visulima/cerebro/command/completion";import E from"@visulima/cerebro/command/version";import{p as s}from"./api-spec-BENwiyUa.mjs";import{createLogger as b}from"./createLogger--C3x1FNE.mjs";import{VisulimaError as j,renderError as I}from"@visulima/error";import{homedir as P}from"node:os";const T={argument:{description:"Feature or registry item: ai | auth | email | storage | crons | presence | queue | workflow | flags | backup | …",name:"feature",type:String},description:"Add a feature or registry item (ai, auth, email, storage, crons, …) to the current Lunora project",examples:[["lunora add auth","Add authentication (asks which provider)"],["lunora add auth --provider clerk","Add Clerk auth without prompting"],["lunora add auth-ui","Add copy-in auth screens for your framework (auto-detected)"],["lunora add email","Add transactional email (Cloudflare Email Workers + dev mail catcher)"],["lunora add storage","Add the R2 storage registry item (asks for the bucket name)"],["lunora add storage --bucket my-app-uploads","Add storage with a bucket name, no prompt"],["lunora add crons","Add the scheduled-jobs registry item"],["lunora add storage --ref alpha","Add an item from the alpha branch's registry"]],group:"Project",loader:()=>import("../packem_chunks/handler.mjs").then(e=>({default:e.execute})),name:"add",options:[{description:"auth: provider to use without prompting (auth | clerk | auth0)",name:"provider",type:String},{description:"auth: D1 database name to use without prompting (lowercase alphanumeric + hyphens)",name:"db",type:String},{description:"storage: R2 bucket name to use without prompting (lowercase alphanumeric + hyphens)",name:"bucket",type:String},{description:"email: verified destination address to use without prompting",name:"mail-to",type:String},{description:"Skip prompts (auth provider, DB name, bucket name, mail destination) and use the defaults",name:"yes",type:Boolean},{description:"Local registry root (offline; expects <name>/ subdirs)",name:"from",type:String},{description:"Override the remote registry source base (e.g. gh:owner/repo/registry)",name:"source",type:String},{description:"Fetch items from a git ref (branch, tag, or commit), e.g. --ref alpha. Overrides the version-derived default",name:"ref",type:String},{description:"Permit --source values outside gh:/github:/https://",name:"allow-unsafe-source",type:Boolean},{description:"Output format: pretty (default) or json",name:"format",type:String}]},_={description:"Run wrangler dry-run and report bundle size, top modules, and _generated files",examples:[["lunora analyze","Report the worker bundle size + heaviest modules"]],group:"Deploy",loader:()=>import("../packem_chunks/handler2.mjs").then(e=>({default:e.execute})),name:"analyze",options:[{description:"Emit a JSON report instead of human text",name:"json",type:Boolean}]},$={argument:{description:"create | list | restore <id|file> | pitr",name:"subcommand",type:String},description:"Managed snapshot backups (create | list | restore) plus native point-in-time recovery (pitr)",examples:[["lunora backup create","Snapshot every table to a backup file"],["lunora backup list","List recorded snapshots"],["lunora backup restore <id>","Restore a snapshot by id"],["lunora backup pitr --at 2026-06-01T00:00:00Z","Point-in-time recovery (≤30 days)"]],group:"Data",loader:()=>import("../packem_chunks/handler3.mjs").then(e=>({default:e.execute})),name:"backup",options:[{description:"Backup directory (default .lunora-backups)",name:"dir",type:String},{description:"Comma-separated table allowlist (create)",name:"tables",type:String},{description:"pitr: time to read/restore to (ISO or epoch-ms, ≤30 days)",name:"at",type:String},{description:"pitr --restore: explicit bookmark to restore to (wins over --at)",name:"bookmark",type:String},{description:"pitr: perform a restore instead of just reading the bookmark",name:"restore",type:Boolean},{description:"pitr --restore: restart the shard now so recovery applies immediately",name:"restart",type:Boolean},{description:"pitr: target shard key (default: root shard)",name:"shard",type:String},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Confirm a production pitr --restore (required with --prod)",name:"yes",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String}]},U={description:"Codegen + validate + bundle the Worker to disk without deploying",examples:[["lunora build","Bundle to .lunora/build without deploying"],["lunora build --out-dir dist-worker","Bundle to a custom directory"]],group:"Deploy",loader:()=>import("../packem_chunks/handler4.mjs").then(e=>({default:e.execute})),name:"build",options:[{description:`Which API spec(s) to emit: ${s} (default openapi)`,name:"api-spec",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Directory to write the bundled Worker to (default .lunora/build)",name:"out-dir",type:String}]},M={description:"Run codegen for lunora/ functions and schema",examples:[["lunora codegen","Generate lunora/_generated/ from your schema + functions"]],group:"Develop",loader:()=>import("../packem_chunks/runCodegenCommand.mjs").then(e=>({default:e.execute})),name:"codegen",options:[{description:`Which API spec(s) to emit: ${s} (default openapi)`,name:"api-spec",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String}]},W={argument:{description:"<build|push|images|list|info|delete> [args…]",name:"args",type:String},description:"Build/push container images and manage container instances (wraps wrangler containers)",examples:[["lunora containers build ./containers/transcoder --tag transcoder:v1","Build a container image with the local Docker engine"],["lunora containers build ./containers/transcoder --tag transcoder:v1 --push","Build and push to the Cloudflare Registry in one step"],["lunora containers push transcoder:v1","Push a locally-tagged image to the Cloudflare Registry"],["lunora containers images list","List images in your Cloudflare Registry"],["lunora containers images delete transcoder:v1","Delete an image to free registry storage"]],group:"Deploy",loader:()=>import("../packem_chunks/handler5.mjs").then(e=>({default:e.execute})),name:"containers",options:[{description:"build: push the image to the Cloudflare Registry after building",name:"push",type:Boolean},{description:"build: name:tag for the image (forwarded to wrangler --tag)",name:"tag",type:String},{description:"Cloudflare environment name",name:"env",type:String}]},J={description:"Codegen, validate wrangler, then wrangler deploy",examples:[["lunora deploy","Deploy to Cloudflare"],["lunora deploy --env production","Deploy to a named environment"],["lunora deploy --dry-run","Validate + bundle without publishing"],["lunora deploy --migrate","Deploy, then run pending data migrations"]],group:"Deploy",loader:()=>import("../packem_chunks/runDeployCommand.mjs").then(e=>({default:e.execute})),name:"deploy",options:[{description:"Override the schema-drift gate (deploy even with breaking schema drift and no migration)",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${s} (default openapi)`,name:"api-spec",type:String},{description:"Validate, bundle, and run pre-deploy gates without publishing (wrangler deploy --dry-run)",name:"dry-run",type:Boolean},{description:"Cloudflare environment name",name:"env",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"After a successful deploy, run pending data migrations against the live worker",name:"migrate",type:Boolean},{description:"Skip codegen + the schema-drift gate (assumes `lunora build`/`prepare` already ran in this CI run). Wrangler still bundles the worker.",name:"prebuilt",type:Boolean},{description:"Admin bearer token for --migrate (falls back to LUNORA_ADMIN_TOKEN)",name:"migrate-token",type:String},{description:"Worker URL for --migrate (REQUIRED with --migrate; the deploy target URL is not captured automatically)",name:"migrate-url",type:String},{description:"Confirm running the production data migration triggered by --migrate (required with --migrate)",name:"migrate-yes",type:Boolean},{description:"Upload a preview version (wrangler versions upload) instead of going live — prints a preview URL; doesn't shift production traffic",name:"preview",type:Boolean},{description:"Deploy to a temporary Cloudflare account when unauthenticated (wrangler deploy --temporary; live ~60min, then claim or it's deleted). Wrangler errors if you're already authenticated.",name:"temporary",type:Boolean},{description:"Re-bless the committed schema baseline (lunora/.lunora-schema.json) with the current shape",name:"update-schema-baseline",type:Boolean}]},K={argument:{description:"list | inspect <version-id> | rollback [version-id] | promote <version-id>",name:"subcommand",type:String},description:"List deployments and roll back / promote / inspect Worker versions",examples:[["lunora deployments list","Show the 10 most recent deployments"],["lunora deployments inspect <version-id>","View a specific Worker version"],["lunora deployments rollback --yes","Roll back to the previous version"],["lunora deployments promote <version-id> --yes","Send 100% of traffic to a version"]],group:"Deploy",loader:()=>import("../packem_chunks/handler6.mjs").then(e=>({default:e.execute})),name:"deployments",options:[{description:"Cloudflare environment name",name:"env",type:String},{description:"Display `list` output as JSON",name:"json",type:Boolean},{description:"Reason/description recorded with a rollback or promote",name:"message",type:String},{description:"Confirm a rollback or promote (required — these change live traffic)",name:"yes",type:Boolean}]},q={argument:{description:"Optional subcommand: stop (shut the running dev server down) | status (report it) | logs (print its captured output)",name:"args",type:String},description:"Run the dev stack: wrangler worker + studio + codegen watch",examples:[["lunora dev","Run the worker + studio + codegen watch"],["lunora dev --background","Run detached: blocks until ready, prints URL + PID, then returns"],["lunora dev stop","Stop the background/tracked dev server (idempotent)"],["lunora dev status","Report the running dev server (URL, PID, uptime)"],["lunora dev logs","Print the captured dev-server log (background runs)"],["lunora dev --json","Machine-readable JSON log lines (also LUNORA_LOG_JSON=1)"],["lunora dev --no-studio","Skip the embedded studio server"],["lunora dev --worker-port 8080","Use a custom wrangler dev port"],["lunora dev --remote","Proxy D1/KV/R2 to the deployed worker (also LUNORA_REMOTE=1)"]],group:"Develop",loader:()=>import("../packem_chunks/planDevCommand.mjs").then(e=>({default:e.execute})),name:"dev",options:[{description:`Which API spec(s) codegen emits: ${s} (default openapi)`,name:"api-spec",type:String},{description:"Studio server port (default 6173)",name:"port",type:Number},{description:"wrangler dev port (default 8787)",name:"worker-port",type:Number},{description:"Run the dev server as a managed background process (auto-enabled when an AI agent is detected; LUNORA_AGENT_MODE=0 disables)",name:"background",type:Boolean},{description:"Emit machine-readable JSON log lines (also LUNORA_LOG_JSON=1; auto-enabled for AI agents)",name:"json",type:Boolean},{description:"How many trailing lines `lunora dev logs` prints (default 100, 0 = all)",name:"lines",type:Number},{description:"Don't start the embedded studio server",name:"no-studio",type:Boolean},{description:"Don't watch + regenerate codegen",name:"no-codegen",type:Boolean},{description:"Proxy D1/KV/R2 bindings to the deployed worker (or set LUNORA_REMOTE=1)",name:"remote",type:Boolean}]},F={argument:{description:"Optional path under the docs site (e.g. addons/studio)",name:"section",type:String},description:"Open the Lunora docs in your browser (optional [section] path)",examples:[["lunora docs","Open the Lunora docs"],["lunora docs addons/studio","Open a specific docs section"]],group:"Project",loader:()=>import("../packem_chunks/handler7.mjs").then(e=>({default:e.execute})),name:"docs"},H={description:"Preflight the current Lunora project (wrangler bindings, placeholders, dev secrets)",examples:[["lunora doctor","Run the project preflight checks"]],group:"Project",loader:()=>import("../packem_chunks/handler8.mjs").then(e=>({default:e.execute})),name:"doctor",options:[]},V={argument:{description:"list | get <KEY> | set <KEY> <VALUE> | unset <KEY> | generate [KEY] | push | diff | doctor",name:"subcommand",type:String},description:"Manage .dev.vars and sync secrets via wrangler (list | get | set | unset | generate | push | diff | doctor)",examples:[["lunora env list","List .dev.vars keys"],["lunora env set API_KEY secret","Set a local variable"],["lunora env generate","Generate strong values for the project's secrets (print KEY=value)"],["lunora env generate AUTH_SECRET --set","Generate one secret and write it to .dev.vars"],["lunora env push --yes","Upload secrets to Cloudflare"],["lunora env diff","Compare local .dev.vars keys against Cloudflare"]],group:"Data",loader:()=>import("../packem_chunks/handler9.mjs").then(e=>({default:e.execute})),name:"env",options:[{description:"Target production for `push` (passes --env production to wrangler)",name:"prod",type:Boolean},{description:"For `generate` — write the generated secrets into .dev.vars instead of printing them",name:"set",type:Boolean},{description:"Push secrets to a temporary-account deployment when unauthenticated (wrangler secret put --temporary). Errors if you're already authenticated.",name:"temporary",type:Boolean},{description:"Required for `push` — confirms uploading secrets to Cloudflare",name:"yes",type:Boolean}]},G={argument:{description:"Optional path (alias for --out)",name:"path",type:String},description:"Stream NDJSON of every shard-local + global table from the worker",examples:[["lunora export --out backup.ndjson","Dump every table to an NDJSON file"],["lunora export --tables messages,users","Export only specific tables"]],group:"Data",loader:()=>import("../packem_chunks/handler10.mjs").then(e=>({default:e.execute})),name:"export",options:[{description:"Output file path (`-` for stdout, default)",name:"out",type:String},{description:"Comma-separated table allowlist",name:"tables",type:String},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String}]},Y={argument:{description:"Source NDJSON file",name:"file",type:String},description:"Bulk-insert rows from an NDJSON file via the worker's admin endpoint",examples:[["lunora import backup.ndjson","Bulk-insert rows from an NDJSON file"]],group:"Data",loader:()=>import("../packem_chunks/handler11.mjs").then(e=>({default:e.execute})),name:"import",options:[{description:"Wrap each bare doc as `{table:<name>,doc:...}`",name:"table",type:String},{description:"Rows per HTTP request (default 500)",name:"batch-size",type:Number},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Confirm bulk-writing production (required with --prod)",name:"yes",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String}]},z={description:"Print resolved project config: @lunora/* versions, wrangler summary, schema overview",examples:[["lunora info","Print resolved project config"],["lunora info --json","Emit a JSON snapshot"]],group:"Project",loader:()=>import("../packem_chunks/handler12.mjs").then(e=>({default:e.execute})),name:"info",options:[{description:"Emit a JSON snapshot instead of human text",name:"json",type:Boolean}]},Q={argument:{description:"Project name",name:"name",type:String},description:"Scaffold a new Lunora project",examples:[["lunora init my-app","Scaffold with the default (vite) template"],["lunora init my-app -t next","Scaffold a Next.js app"],["lunora init my-app -t tanstack-start-react","Scaffold a TanStack Start (React) app"],["lunora init my-app -t tanstack-start-solid","Scaffold a TanStack Start (Solid) app"],["lunora init my-app --ref alpha","Scaffold from the alpha branch's templates"],["lunora init --here","Add Lunora to the current project"],["lunora init my-app --ci github","Scaffold + add a GitHub Actions deploy pipeline"],["lunora init my-app --ci gitlab","Scaffold + add a GitLab CI deploy pipeline"]],group:"Project",loader:()=>import("../packem_chunks/runInitCommand.mjs").then(e=>({default:e.execute})),name:"init",options:[{alias:"t",description:"Bespoke template (standalone | astro | next | nuxt | sveltekit | tanstack-start-react | tanstack-start-solid). For an SPA use --vite react|vue|solid|svelte.",name:"template",type:String},{description:"Scaffold via the create-vite overlay for a framework (react | vue | solid | svelte | vanilla) — official create-vite base + Lunora layer",name:"vite",type:String},{description:"Local templates root to copy from (offline-friendly; expects <type>/ subdirs)",name:"from",type:String},{description:"Override the remote template source (e.g. gh:owner/repo/sub#ref)",name:"source",type:String},{description:"Fetch templates from a git ref (branch, tag, or commit), e.g. --ref alpha. Overrides the version-derived default",name:"ref",type:String},{description:"Permit --source values outside gh:/github:/https:// (e.g. local file://)",name:"allow-unsafe-source",type:Boolean},{description:"Add Lunora to the current project: detect the framework, patch the config, scaffold lunora/, print per-framework wiring steps",name:"here",type:Boolean},{alias:"i",description:"After scaffolding, offer to add auth + email (defaults on when stdin is a TTY)",name:"interactive",type:Boolean},{alias:"y",description:"Skip the auth/email offer; scaffold only",name:"yes",type:Boolean},{description:"Also scaffold a CI deploy pipeline: github (.github/workflows/deploy.yml) or gitlab (.gitlab-ci.yml)",name:"ci",type:String},{description:"Add features non-interactively after scaffolding (comma-separated): ai | auth | backup | browser | cloudflare-access | crons | email | flags | hyperdrive | payment | presence | queue | storage | workflow",name:"add",type:String},{description:"Walk through every step (prompts + output) without writing files, installing, or running git",name:"dry-run",type:Boolean}]},X={description:"Report write-conflict hot-spots, error rates, and latency outliers from a running Worker",examples:[["lunora insights","Report against the local dev worker"],["lunora insights --shard channel:demo","Scope the report to one shard"],["lunora insights --json","Emit the raw report as JSON"],["lunora insights --prod --url https://app.example.com --token $LUNORA_ADMIN_TOKEN","Report against production"]],group:"Develop",loader:()=>import("../packem_chunks/handler13.mjs").then(e=>({default:e.execute})),name:"insights",options:[{description:"Explicit shard key (defaults to the root shard)",name:"shard",type:String},{description:"Max rows per section (default 10)",name:"limit",type:String},{description:"Emit a JSON report instead of human text",name:"json",type:Boolean},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (or LUNORA_ADMIN_TOKEN)",name:"token",type:String}]},Z={description:"Scaffold lunora/schema.ts (and list/get procedures) from an existing Postgres or MySQL database",examples:[["lunora introspect --url postgres://localhost/shop","Scaffold a schema + procedures from every table"],["lunora introspect --tables users,orders","Introspect only these tables (DATABASE_URL is read by default)"],["lunora introspect --dry-run","Print what would be written without touching the filesystem"],["lunora introspect --no-procedures --force","Regenerate just the schema, overwriting the existing file"]],group:"Data",loader:()=>import("../packem_chunks/handler22.mjs").then(e=>({default:e.execute})),name:"introspect",options:[{description:"Database connection string (default: $DATABASE_URL)",name:"url",type:String},{description:"Postgres schema (default `public`) or MySQL database name",name:"schema",type:String},{description:"Comma-separated table allow-list (default: every base table)",name:"tables",type:String},{description:"Also emit list/get procedure modules per table (default true; --no-procedures to skip)",name:"procedures",type:Boolean},{description:"Overwrite files that already exist",name:"force",type:Boolean},{description:"Print what would be written without writing it",name:"dry-run",type:Boolean}]},ee={description:"Link this checkout to its deployed Worker (writes .lunora/project.json)",examples:[["lunora link --url https://app.acme.workers.dev","Link to a deployed Worker URL"],["lunora link --url https://app.acme.workers.dev --env production","Link a named environment"],["lunora link --remove","Remove the link"]],group:"Deploy",loader:()=>import("../packem_chunks/handler14.mjs").then(e=>({default:e.execute})),name:"link",options:[{description:"Cloudflare environment name to record alongside the link",name:"env",type:String},{description:"Worker name (defaults to the `name` in wrangler config)",name:"name",type:String},{description:"Remove the existing link (.lunora/project.json)",name:"remove",type:Boolean},{description:"Deployed Worker URL to link (e.g. https://app.acme.workers.dev)",name:"url",type:String}]},te={argument:{description:"Worker name (defaults to the name in wrangler config)",name:"worker",type:String},description:"Stream live logs from a deployed Worker, or read the durable log archive with --durable",group:"Deploy",loader:()=>import("../packem_chunks/handler21.mjs").then(e=>({default:e.execute})),name:"logs",options:[{description:"Cloudflare environment name",name:"env",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Substring filter on log messages",name:"search",type:String},{description:"Filter by invocation status: ok, error, or canceled",name:"status",type:String},{description:"Tail a temporary-account deployment when unauthenticated (wrangler tail --temporary). Errors if you're already authenticated.",name:"temporary",type:Boolean},{description:"Read the durable log archive (pipelineLogSink → R2) via R2 SQL instead of tailing live",name:"durable",type:Boolean},{description:"durable: Iceberg table the Pipeline writes to (required with --durable)",name:"table",type:String},{description:"durable: Iceberg namespace (R2 Data Catalog database) the table lives in",name:"namespace",type:String},{description:"durable: lower time bound (epoch-millis or ISO 8601), inclusive",name:"since",type:String},{description:"durable: upper time bound (epoch-millis or ISO 8601), inclusive",name:"until",type:String},{description:"durable: exact severity filter (trace|debug|log|info|warn|error|fatal)",name:"level",type:String},{description:"durable: severity floor — this level and every more-severe one",name:"min-level",type:String},{description:"durable: keep function paths starting with this prefix (LIKE 'prefix%')",name:"function-prefix",type:String},{description:"durable: trace-id filter",name:"trace-id",type:String},{description:"durable: shard-key filter",name:"shard-key",type:String},{description:"durable: user-id filter",name:"user-id",type:String},{description:"durable: max rows (clamped to 1–10000; default 500)",name:"limit",type:String},{description:"durable: resume after a prior page — the opaque cursor token printed by the previous page (bare epoch-millis also accepted for back-compat)",name:"cursor",type:String},{description:"durable: emit one JSON object per line instead of a table",name:"ndjson",type:Boolean}]},re={argument:{description:"install [client…] | uninstall [client…] | serve",name:"args",type:String},description:"Connect your AI editor to Lunora over MCP (docs search + this project's dev server)",examples:[["lunora mcp install","Install into every MCP client already configured here"],["lunora mcp install claude-code cursor","Install into specific clients"],["lunora mcp install --list","List the supported clients and their config files"],["lunora mcp install --docs-only","Install only the hosted documentation server"],["lunora mcp install --print","Show the config that would be written, without writing it"],["lunora mcp install --global","Force every server into the machine-wide config"],["lunora mcp uninstall","Remove Lunora's MCP servers from every supported client"],["lunora mcp uninstall cursor","Remove them from one client"],["lunora mcp uninstall --print","Show what would be removed, without removing it"],["lunora mcp serve","Run the stdio MCP server (this is what your editor spawns)"],["lunora mcp serve --allow-writes","Also expose the mutation/action tools"]],group:"Develop",loader:()=>import("../packem_chunks/handler23.mjs").then(e=>({default:e.execute})),name:"mcp",options:[{description:"install: replace entries that already exist",name:"force",type:Boolean},{description:"install: list the supported clients and their config files",name:"list",type:Boolean},{description:"install/uninstall: print what would change instead of writing it",name:"print",type:Boolean},{description:"install/uninstall: only the hosted documentation server",name:"docs-only",type:Boolean},{description:"install/uninstall: only this project's local server",name:"local-only",type:Boolean},{description:"install/uninstall: the machine-wide config (install default: docs server global, local server per-project)",name:"global",type:Boolean},{description:"install/uninstall: this project's config instead of the machine-wide one",name:"project",type:Boolean},{description:"serve: also expose the mutation/action tools (default: read-only)",name:"allow-writes",type:Boolean},{description:"serve: skip the documentation tools",name:"no-docs",type:Boolean},{description:"Docs site origin backing the documentation tools (default https://lunora.sh)",name:"docs-url",type:String},{description:"serve: deployment URL to expose (default: the running dev server)",name:"url",type:String},{description:"serve: bearer token (default: LUNORA_ADMIN_TOKEN from the environment or .dev.vars)",name:"token",type:String}]},oe={argument:{description:"generate | create | up | down | status | d1-to-hyperdrive [name|id]",name:"subcommand",type:String},description:"Schema (generate), online data (create | up | down | status), and backend (d1-to-hyperdrive) migrations",examples:[["lunora migrate generate","Diff lunora/schema.ts and emit a SQL migration"],["lunora migrate create add_users_email","Scaffold a data migration"],["lunora migrate up backfill-names","Run a data migration across shards"],["lunora migrate status backfill-names","Report a migration's per-shard status"],["lunora migrate d1-to-hyperdrive --from-url https://old --to-url https://new","Copy .global() data from D1 to Hyperdrive"]],group:"Data",loader:()=>import("../packem_chunks/runMigrateGenerateCommand.mjs").then(e=>({default:e.execute})),name:"migrate",options:[{description:"Migration name slug (e.g. add_users_email)",name:"name",type:String},{description:"Target table for `create` (prompted for interactively when omitted)",name:"table",type:String},{description:"Preview a data migration without rewriting rows",name:"dry-run",type:Boolean},{description:"Rows per batch for a data migration",name:"batch-size",type:Number},{description:"Cap batches processed this run (maps to the runner's maxBatches)",name:"steps",type:Number},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String},{description:"Required with --prod for up/down — confirms running against production",name:"yes",type:Boolean},{description:"d1-to-hyperdrive: source (D1) worker URL (defaults to --url)",name:"from-url",type:String},{description:"d1-to-hyperdrive: source admin token (defaults to --token / LUNORA_ADMIN_TOKEN)",name:"from-token",type:String},{description:"d1-to-hyperdrive: target (Hyperdrive) worker URL (defaults to --url)",name:"to-url",type:String},{description:"d1-to-hyperdrive: target admin token (defaults to --token / LUNORA_ADMIN_TOKEN)",name:"to-token",type:String},{description:"d1-to-hyperdrive: comma-separated .global() tables to move (default: all global tables)",name:"tables",type:String},{description:"d1-to-hyperdrive: keep the intermediate NDJSON dump at this path",name:"out",type:String}]},ne={description:"Run codegen + binding reconcile + wrangler validation (no Vite) — for CI",examples:[["lunora prepare","Codegen + binding reconcile + validate (CI, before deploy)"]],group:"Deploy",loader:()=>import("../packem_chunks/handler15.mjs").then(e=>({default:e.execute})),name:"prepare",options:[{description:"Override the schema-drift gate (proceed even with breaking schema drift and no migration)",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${s} (default openapi)`,name:"api-spec",type:String},{description:"Re-bless the committed schema baseline (lunora/.lunora-schema.json) with the current shape",name:"update-schema-baseline",type:Boolean}]},ae={argument:{description:"<add|list|view|build> [item names…]",name:"args",type:String},description:"Component registry: add/list/view items, or build the catalog",examples:[["lunora registry list","List available registry items"],["lunora registry add presence","Scaffold a registry item into lunora/"],["lunora registry build --check","Verify the committed catalog is current"]],group:"Project",loader:()=>import("../packem_chunks/handler16.mjs").then(e=>({default:e.execute})),name:"registry",options:[{description:"add: print the plan and stop without writing",name:"dry-run",type:Boolean},{description:"add: preview the file changes (content diff) and write nothing",name:"diff",type:Boolean},{description:"add: force-overwrite existing files (take the incoming copy)",name:"overwrite",type:Boolean},{description:"add: skip the package.json mutation confirmation prompt",name:"yes",type:Boolean},{description:"Local registry root (offline; expects <name>/ subdirs)",name:"from",type:String},{description:"Override the remote registry source base (e.g. gh:owner/repo/registry)",name:"source",type:String},{description:"Fetch items from a git ref (branch, tag, or commit), e.g. --ref alpha. Overrides the version-derived default",name:"ref",type:String},{description:"Permit --source values outside gh:/github:/https://",name:"allow-unsafe-source",type:Boolean},{description:"Emit JSON output (add plan / list)",name:"json",type:Boolean},{description:"build: output path for the catalog (default <root>/index.json)",name:"out",type:String},{description:"build: verify the index is current instead of rewriting it",name:"check",type:Boolean}]},ie={description:"Clear local Miniflare state (and .lunora-cache with --all)",examples:[["lunora reset","Clear local Miniflare state"],["lunora reset --all","Also remove .lunora-cache"]],group:"Develop",loader:()=>import("../packem_chunks/runResetCommand.mjs").then(e=>({default:e.execute})),name:"reset",options:[{description:"Also remove .lunora-cache",name:"all",type:Boolean},{description:"Skip the confirmation prompt (required when stdin is not a TTY)",name:"yes",type:Boolean}]},se={argument:{description:"install | check",name:"subcommand",type:String},description:"Install the Lunora agent skills (AI rules) into .agents/skills/, or check they're present",examples:[["lunora rules install","Copy the Lunora agent skills into .agents/skills/"],["lunora rules install --overwrite","Reinstall, replacing edited skill files"],["lunora rules check","Report which Lunora skills are installed"],["lunora rules check --strict","Exit non-zero when rules are missing (CI gate)"]],group:"Project",loader:()=>import("../packem_chunks/handler17.mjs").then(e=>({default:e.execute})),name:"rules",options:[{description:"install: overwrite skill files that already exist (default: skip them)",name:"overwrite",type:Boolean},{description:"check: exit non-zero when the rules are missing (for CI gating)",name:"strict",type:Boolean}]},le={argument:{description:"Function path (e.g. messages:send)",name:"functionPath",type:String},description:"Send a single RPC to a running Lunora Worker",examples:[[`lunora run messages:send --args '{"text":"hi"}'`,"Call a function with JSON args"],["lunora run messages:list --shard channel:demo","Target a specific shard"]],group:"Develop",loader:()=>import("../packem_chunks/runRpcCommand.mjs").then(e=>({default:e.execute})),name:"run",options:[{description:"JSON-encoded args object",name:"args",type:String},{description:"Explicit shard key",name:"shard",type:String},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String}]},pe={description:"Generate deterministic fake data from lunora/schema.ts and bulk-insert it via the worker's admin endpoint",examples:[["lunora seed","Seed every table with the default row count"],["lunora seed --table posts --count 50","Seed 50 posts; FK-parent tables are seeded automatically"],["lunora seed --reset","Wipe local .wrangler/state, then seed from scratch"],["lunora seed --seed 7 --dry-run","Print the NDJSON for seed 7 without inserting"]],group:"Data",loader:()=>import("../packem_chunks/handler18.mjs").then(e=>({default:e.execute})),name:"seed",options:[{description:"Rows per table (default 10)",name:"count",type:Number},{description:"Seed only this table; its FK-parent tables are seeded automatically",name:"table",type:String},{description:"Deterministic seed — same value yields identical rows (default 0)",name:"seed",type:Number},{description:"Print the generated NDJSON instead of inserting",name:"dry-run",type:Boolean},{description:"Wipe local .wrangler/state before seeding (local dev only)",name:"reset",type:Boolean},{description:"Rows per HTTP request (default 500)",name:"batch-size",type:Number},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String},{description:"Skip the confirmation prompt when seeding a non-local/production target",name:"yes",type:Boolean}]},de={description:"Validate wrangler.jsonc + codegen dry-run + tsc --noEmit (no files written)",examples:[["lunora verify","Validate wrangler + codegen + tsc"],["lunora verify --no-typecheck","Skip the TypeScript type-check"],["lunora verify --health-url https://my-app.workers.dev","Also probe the deployment's /_lunora/health"]],group:"Deploy",loader:()=>import("../packem_chunks/handler19.mjs").then(e=>({default:e.execute})),name:"verify",options:[{description:"Treat breaking schema drift as a warning instead of a failure",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${s} (default openapi)`,name:"api-spec",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Probe this deployment's /_lunora/health endpoint (off by default; keeps verify offline-safe)",name:"health-url",type:String},{description:"Skip the TypeScript type-check step",name:"no-typecheck",type:Boolean}]},ce={description:"Open the Lunora studio in your browser (local dev by default, --remote for production)",examples:[["lunora view","Open the studio for local dev"],["lunora view --remote","Open the deployed studio"]],group:"Project",loader:()=>import("../packem_chunks/handler20.mjs").then(e=>({default:e.execute})),name:"view",options:[{description:"Open the deployed worker URL instead of localhost",name:"remote",type:Boolean}]},ue={filterStacktrace:()=>!1,hideErrorCodeView:!0},me=(e,t={})=>{const r=e instanceof Error?e.message:String(e),o=B(v(e)?{code:e.code,hint:e.hint,message:r}:r),n=new j({hint:o===void 0?void 0:A(o).split(`
|
|
2
|
-
`),message:t.reason===void 0?r:`${t.reason}: ${r}`,name:e instanceof Error&&e.name.length>0?e.name:"Error"});return n.stack="",I(n,ue)},ge=(e,t)=>{const r=Array.from({length:t.length+1},(o,n)=>n);for(let o=1;o<=e.length;o+=1){let n=r[0]??0;r[0]=o;for(let a=1;a<=t.length;a+=1){const i=r[a]??0,l=e[o-1]===t[a-1]?0:1;r[a]=Math.min((r[a-1]??0)+1,i+1,n+l),n=i}}return r[t.length]??0},he=(e,t)=>{let r,o=Number.POSITIVE_INFINITY;for(const a of t){const i=ge(e,a);i<o&&(o=i,r=a)}const n=Math.max(2,Math.ceil(e.length/3));return r!==void 0&&o<=n?r:void 0},ye=e=>`https://registry.npmjs.org/@lunora/cli/${e}`,fe=1440*60*1e3,ve=1500,be="0.0.0",we=/^v/u,ke=new Set(["alpha","beta","next"]),c=e=>{const t=e.trim().replace(we,""),r=t.indexOf("-");return r===-1?{core:t,prerelease:""}:{core:t.slice(0,r),prerelease:t.slice(r+1)}},h=e=>{const[t,r,o]=c(e).core.split(".").map(n=>{const a=Number.parseInt(n,10);return Number.isFinite(a)?a:0});return[t??0,r??0,o??0]},Se=(e,t)=>{const r=Number.parseInt(e,10),o=Number.parseInt(t,10);return String(r)===e&&String(o)===t?r>o?1:-1:e>t?1:-1},xe=(e,t)=>{if(e===t)return 0;if(e===""||t==="")return e===""?1:-1;const r=e.split("."),o=t.split(".");for(let n=0;n<Math.max(r.length,o.length);n+=1){const a=r[n],i=o[n];if(a===void 0||i===void 0)return a===void 0?-1:1;if(a!==i)return Se(a,i)}return 0},
|
|
3
|
-
`,"utf8")}catch{}},
|
|
1
|
+
import{mkdirSync as x,readFileSync as f,lstatSync as N,writeFileSync as O}from"node:fs";import{join as d,dirname as g}from"node:path";import{fileURLToPath as R}from"node:url";import{resolveHint as A,isLunoraError as v,flattenHint as B,findSolutionByMessage as L}from"@lunora/errors";import{createCerebro as D}from"@visulima/cerebro";import E from"@visulima/cerebro/command/completion";import C from"@visulima/cerebro/command/version";import{p as s}from"./api-spec-BENwiyUa.mjs";import{createLogger as b}from"./createLogger--C3x1FNE.mjs";import{VisulimaError as j,renderError as I}from"@visulima/error";import{homedir as _}from"node:os";const P={argument:{description:"Feature or registry item: ai | auth | email | storage | crons | presence | queue | workflow | flags | backup | …",name:"feature",type:String},description:"Add a feature or registry item (ai, auth, email, storage, crons, …) to the current Lunora project",examples:[["lunora add auth","Add authentication (asks which provider)"],["lunora add auth --provider clerk","Add Clerk auth without prompting"],["lunora add auth-ui","Add copy-in auth screens for your framework (auto-detected)"],["lunora add email","Add transactional email (Cloudflare Email Workers + dev mail catcher)"],["lunora add storage","Add the R2 storage registry item (asks for the bucket name)"],["lunora add storage --bucket my-app-uploads","Add storage with a bucket name, no prompt"],["lunora add crons","Add the scheduled-jobs registry item"],["lunora add storage --ref alpha","Add an item from the alpha branch's registry"]],group:"Project",loader:()=>import("../packem_chunks/handler.mjs").then(e=>({default:e.execute})),name:"add",options:[{description:"auth: provider to use without prompting (auth | clerk | auth0)",name:"provider",type:String},{description:"auth: D1 database name to use without prompting (lowercase alphanumeric + hyphens)",name:"db",type:String},{description:"storage: R2 bucket name to use without prompting (lowercase alphanumeric + hyphens)",name:"bucket",type:String},{description:"email: verified destination address to use without prompting",name:"mail-to",type:String},{description:"Skip prompts (auth provider, DB name, bucket name, mail destination) and use the defaults",name:"yes",type:Boolean},{description:"Local registry root (offline; expects <name>/ subdirs)",name:"from",type:String},{description:"Override the remote registry source base (e.g. gh:owner/repo/registry)",name:"source",type:String},{description:"Fetch items from a git ref (branch, tag, or commit), e.g. --ref alpha. Overrides the version-derived default",name:"ref",type:String},{description:"Permit --source values outside gh:/github:/https://",name:"allow-unsafe-source",type:Boolean},{description:"Output format: pretty (default) or json",name:"format",type:String}]},T={description:"Run wrangler dry-run and report bundle size, top modules, and _generated files",examples:[["lunora analyze","Report the worker bundle size + heaviest modules"]],group:"Deploy",loader:()=>import("../packem_chunks/handler2.mjs").then(e=>({default:e.execute})),name:"analyze",options:[{description:"Emit a JSON report instead of human text",name:"json",type:Boolean}]},$={argument:{description:"create | list | restore <id|file> | pitr",name:"subcommand",type:String},description:"Managed snapshot backups (create | list | restore) plus native point-in-time recovery (pitr)",examples:[["lunora backup create","Snapshot every table to a backup file"],["lunora backup list","List recorded snapshots"],["lunora backup restore <id>","Restore a snapshot by id"],["lunora backup pitr --at 2026-06-01T00:00:00Z","Point-in-time recovery (≤30 days)"]],group:"Data",loader:()=>import("../packem_chunks/handler3.mjs").then(e=>({default:e.execute})),name:"backup",options:[{description:"Backup directory (default .lunora-backups)",name:"dir",type:String},{description:"Comma-separated table allowlist (create)",name:"tables",type:String},{description:"pitr: time to read/restore to (ISO or epoch-ms, ≤30 days)",name:"at",type:String},{description:"pitr --restore: explicit bookmark to restore to (wins over --at)",name:"bookmark",type:String},{description:"pitr: perform a restore instead of just reading the bookmark",name:"restore",type:Boolean},{description:"pitr --restore: restart the shard now so recovery applies immediately",name:"restart",type:Boolean},{description:"pitr: target shard key (default: root shard)",name:"shard",type:String},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Confirm a production pitr --restore (required with --prod)",name:"yes",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String}]},U={description:"Codegen + validate + bundle the Worker to disk without deploying",examples:[["lunora build","Bundle to .lunora/build without deploying"],["lunora build --out-dir dist-worker","Bundle to a custom directory"]],group:"Deploy",loader:()=>import("../packem_chunks/handler4.mjs").then(e=>({default:e.execute})),name:"build",options:[{description:`Which API spec(s) to emit: ${s} (default openapi)`,name:"api-spec",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Directory to write the bundled Worker to (default .lunora/build)",name:"out-dir",type:String}]},M={description:"Run codegen for lunora/ functions and schema",examples:[["lunora codegen","Generate lunora/_generated/ from your schema + functions"]],group:"Develop",loader:()=>import("../packem_chunks/runCodegenCommand.mjs").then(e=>({default:e.execute})),name:"codegen",options:[{description:`Which API spec(s) to emit: ${s} (default openapi)`,name:"api-spec",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String}]},W={argument:{description:"<build|push|images|list|info|delete> [args…]",name:"args",type:String},description:"Build/push container images and manage container instances (wraps wrangler containers)",examples:[["lunora containers build ./containers/transcoder --tag transcoder:v1","Build a container image with the local Docker engine"],["lunora containers build ./containers/transcoder --tag transcoder:v1 --push","Build and push to the Cloudflare Registry in one step"],["lunora containers push transcoder:v1","Push a locally-tagged image to the Cloudflare Registry"],["lunora containers images list","List images in your Cloudflare Registry"],["lunora containers images delete transcoder:v1","Delete an image to free registry storage"]],group:"Deploy",loader:()=>import("../packem_chunks/handler5.mjs").then(e=>({default:e.execute})),name:"containers",options:[{description:"build: push the image to the Cloudflare Registry after building",name:"push",type:Boolean},{description:"build: name:tag for the image (forwarded to wrangler --tag)",name:"tag",type:String},{description:"Cloudflare environment name",name:"env",type:String}]},J={description:"Codegen, validate wrangler, then wrangler deploy",examples:[["lunora deploy","Deploy to Cloudflare"],["lunora deploy --env production","Deploy to a named environment"],["lunora deploy --dry-run","Validate + bundle without publishing"],["lunora deploy --migrate","Deploy, then run pending data migrations"]],group:"Deploy",loader:()=>import("../packem_chunks/runDeployCommand.mjs").then(e=>({default:e.execute})),name:"deploy",options:[{description:"Override the schema-drift gate (deploy even with breaking schema drift and no migration)",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${s} (default openapi)`,name:"api-spec",type:String},{description:"Validate, bundle, and run pre-deploy gates without publishing (wrangler deploy --dry-run)",name:"dry-run",type:Boolean},{description:"Cloudflare environment name",name:"env",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"After a successful deploy, run pending data migrations against the live worker",name:"migrate",type:Boolean},{description:"Skip codegen + the schema-drift gate (assumes `lunora build`/`prepare` already ran in this CI run). Wrangler still bundles the worker.",name:"prebuilt",type:Boolean},{description:"Admin bearer token for --migrate (falls back to LUNORA_ADMIN_TOKEN)",name:"migrate-token",type:String},{description:"Worker URL for --migrate (REQUIRED with --migrate; the deploy target URL is not captured automatically)",name:"migrate-url",type:String},{description:"Confirm running the production data migration triggered by --migrate (required with --migrate)",name:"migrate-yes",type:Boolean},{description:"Upload a preview version (wrangler versions upload) instead of going live — prints a preview URL; doesn't shift production traffic",name:"preview",type:Boolean},{description:"Deploy to a temporary Cloudflare account when unauthenticated (wrangler deploy --temporary; live ~60min, then claim or it's deleted). Wrangler errors if you're already authenticated.",name:"temporary",type:Boolean},{description:"Re-bless the committed schema baseline (lunora/.lunora-schema.json) with the current shape",name:"update-schema-baseline",type:Boolean}]},K={argument:{description:"list | inspect <version-id> | rollback [version-id] | promote <version-id>",name:"subcommand",type:String},description:"List deployments and roll back / promote / inspect Worker versions",examples:[["lunora deployments list","Show the 10 most recent deployments"],["lunora deployments inspect <version-id>","View a specific Worker version"],["lunora deployments rollback --yes","Roll back to the previous version"],["lunora deployments promote <version-id> --yes","Send 100% of traffic to a version"]],group:"Deploy",loader:()=>import("../packem_chunks/handler6.mjs").then(e=>({default:e.execute})),name:"deployments",options:[{description:"Cloudflare environment name",name:"env",type:String},{description:"Display `list` output as JSON",name:"json",type:Boolean},{description:"Reason/description recorded with a rollback or promote",name:"message",type:String},{description:"Confirm a rollback or promote (required — these change live traffic)",name:"yes",type:Boolean}]},q={argument:{description:"Optional subcommand: stop (shut the running dev server down) | status (report it) | logs (print its captured output)",name:"args",type:String},description:"Run the dev stack: wrangler worker + studio + codegen watch",examples:[["lunora dev","Run the worker + studio + codegen watch"],["lunora dev --background","Run detached: blocks until ready, prints URL + PID, then returns"],["lunora dev stop","Stop the background/tracked dev server (idempotent)"],["lunora dev status","Report the running dev server (URL, PID, uptime)"],["lunora dev logs","Print the captured dev-server log (background runs)"],["lunora dev --json","Machine-readable JSON log lines (also LUNORA_LOG_JSON=1)"],["lunora dev --no-studio","Skip the embedded studio server"],["lunora dev --worker-port 8080","Use a custom wrangler dev port"],["lunora dev --remote","Proxy D1/KV/R2 to the deployed worker (also LUNORA_REMOTE=1)"]],group:"Develop",loader:()=>import("../packem_chunks/planDevCommand.mjs").then(e=>({default:e.execute})),name:"dev",options:[{description:`Which API spec(s) codegen emits: ${s} (default openapi)`,name:"api-spec",type:String},{description:"Studio server port (default 6173)",name:"port",type:Number},{description:"wrangler dev port (default 8787)",name:"worker-port",type:Number},{description:"Run the dev server as a managed background process (auto-enabled when an AI agent is detected; LUNORA_AGENT_MODE=0 disables)",name:"background",type:Boolean},{description:"Emit machine-readable JSON log lines (also LUNORA_LOG_JSON=1; auto-enabled for AI agents)",name:"json",type:Boolean},{description:"How many trailing lines `lunora dev logs` prints (default 100, 0 = all)",name:"lines",type:Number},{description:"Don't start the embedded studio server",name:"no-studio",type:Boolean},{description:"Don't watch + regenerate codegen",name:"no-codegen",type:Boolean},{description:"Proxy D1/KV/R2 bindings to the deployed worker (or set LUNORA_REMOTE=1)",name:"remote",type:Boolean}]},F={argument:{description:"Optional path under the docs site (e.g. addons/studio)",name:"section",type:String},description:"Open the Lunora docs in your browser (optional [section] path)",examples:[["lunora docs","Open the Lunora docs"],["lunora docs addons/studio","Open a specific docs section"]],group:"Project",loader:()=>import("../packem_chunks/handler7.mjs").then(e=>({default:e.execute})),name:"docs"},H={description:"Preflight the current Lunora project (wrangler bindings, placeholders, dev secrets)",examples:[["lunora doctor","Run the project preflight checks"]],group:"Project",loader:()=>import("../packem_chunks/handler8.mjs").then(e=>({default:e.execute})),name:"doctor",options:[]},V={argument:{description:"list | get <KEY> | set <KEY> <VALUE> | unset <KEY> | generate [KEY] | push | diff | doctor",name:"subcommand",type:String},description:"Manage .dev.vars and sync secrets via wrangler (list | get | set | unset | generate | push | diff | doctor)",examples:[["lunora env list","List .dev.vars keys"],["lunora env set API_KEY secret","Set a local variable"],["lunora env generate","Generate strong values for the project's secrets (print KEY=value)"],["lunora env generate AUTH_SECRET --set","Generate one secret and write it to .dev.vars"],["lunora env push --yes","Upload secrets to Cloudflare"],["lunora env diff","Compare local .dev.vars keys against Cloudflare"]],group:"Data",loader:()=>import("../packem_chunks/handler9.mjs").then(e=>({default:e.execute})),name:"env",options:[{description:"Target production for `push` (passes --env production to wrangler)",name:"prod",type:Boolean},{description:"For `generate` — write the generated secrets into .dev.vars instead of printing them",name:"set",type:Boolean},{description:"Push secrets to a temporary-account deployment when unauthenticated (wrangler secret put --temporary). Errors if you're already authenticated.",name:"temporary",type:Boolean},{description:"Required for `push` — confirms uploading secrets to Cloudflare",name:"yes",type:Boolean}]},G={argument:{description:"Optional path (alias for --out)",name:"path",type:String},description:"Stream NDJSON of every shard-local + global table from the worker",examples:[["lunora export --out backup.ndjson","Dump every table to an NDJSON file"],["lunora export --tables messages,users","Export only specific tables"]],group:"Data",loader:()=>import("../packem_chunks/handler10.mjs").then(e=>({default:e.execute})),name:"export",options:[{description:"Output file path (`-` for stdout, default)",name:"out",type:String},{description:"Comma-separated table allowlist",name:"tables",type:String},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String}]},Y={argument:{description:"Source NDJSON file",name:"file",type:String},description:"Bulk-insert rows from an NDJSON file via the worker's admin endpoint",examples:[["lunora import backup.ndjson","Bulk-insert rows from an NDJSON file"]],group:"Data",loader:()=>import("../packem_chunks/handler11.mjs").then(e=>({default:e.execute})),name:"import",options:[{description:"Wrap each bare doc as `{table:<name>,doc:...}`",name:"table",type:String},{description:"Rows per HTTP request (default 500)",name:"batch-size",type:Number},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Confirm bulk-writing production (required with --prod)",name:"yes",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String}]},z={description:"Print resolved project config: @lunora/* versions, wrangler summary, schema overview",examples:[["lunora info","Print resolved project config"],["lunora info --json","Emit a JSON snapshot"]],group:"Project",loader:()=>import("../packem_chunks/handler12.mjs").then(e=>({default:e.execute})),name:"info",options:[{description:"Emit a JSON snapshot instead of human text",name:"json",type:Boolean}]},Q={argument:{description:"Project name",name:"name",type:String},description:"Scaffold a new Lunora project",examples:[["lunora init my-app","Scaffold with the default (vite) template"],["lunora init my-app -t next","Scaffold a Next.js app"],["lunora init my-app -t tanstack-start-react","Scaffold a TanStack Start (React) app"],["lunora init my-app -t tanstack-start-solid","Scaffold a TanStack Start (Solid) app"],["lunora init my-app --ref alpha","Scaffold from the alpha branch's templates"],["lunora init --here","Add Lunora to the current project"],["lunora init my-app --ci github","Scaffold + add a GitHub Actions deploy pipeline"],["lunora init my-app --ci gitlab","Scaffold + add a GitLab CI deploy pipeline"]],group:"Project",loader:()=>import("../packem_chunks/runInitCommand.mjs").then(e=>({default:e.execute})),name:"init",options:[{alias:"t",description:"Bespoke template (standalone | astro | next | nuxt | sveltekit | tanstack-start-react | tanstack-start-solid). For an SPA use --vite react|vue|solid|svelte.",name:"template",type:String},{description:"Scaffold via the create-vite overlay for a framework (react | vue | solid | svelte | vanilla) — official create-vite base + Lunora layer",name:"vite",type:String},{description:"Local templates root to copy from (offline-friendly; expects <type>/ subdirs)",name:"from",type:String},{description:"Override the remote template source (e.g. gh:owner/repo/sub#ref)",name:"source",type:String},{description:"Fetch templates from a git ref (branch, tag, or commit), e.g. --ref alpha. Overrides the version-derived default",name:"ref",type:String},{description:"Permit --source values outside gh:/github:/https:// (e.g. local file://)",name:"allow-unsafe-source",type:Boolean},{description:"Add Lunora to the current project: detect the framework, patch the config, scaffold lunora/, print per-framework wiring steps",name:"here",type:Boolean},{alias:"i",description:"After scaffolding, offer to add auth + email (defaults on when stdin is a TTY)",name:"interactive",type:Boolean},{alias:"y",description:"Skip the auth/email offer; scaffold only",name:"yes",type:Boolean},{description:"Also scaffold a CI deploy pipeline: github (.github/workflows/deploy.yml) or gitlab (.gitlab-ci.yml)",name:"ci",type:String},{description:"Add features non-interactively after scaffolding (comma-separated): ai | auth | backup | browser | cloudflare-access | crons | email | flags | hyperdrive | payment | presence | queue | storage | workflow",name:"add",type:String},{description:"Walk through every step (prompts + output) without writing files, installing, or running git",name:"dry-run",type:Boolean}]},X={description:"Report write-conflict hot-spots, error rates, and latency outliers from a running Worker",examples:[["lunora insights","Report against the local dev worker"],["lunora insights --shard channel:demo","Scope the report to one shard"],["lunora insights --json","Emit the raw report as JSON"],["lunora insights --prod --url https://app.example.com --token $LUNORA_ADMIN_TOKEN","Report against production"]],group:"Develop",loader:()=>import("../packem_chunks/handler13.mjs").then(e=>({default:e.execute})),name:"insights",options:[{description:"Explicit shard key (defaults to the root shard)",name:"shard",type:String},{description:"Max rows per section (default 10)",name:"limit",type:String},{description:"Emit a JSON report instead of human text",name:"json",type:Boolean},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (or LUNORA_ADMIN_TOKEN)",name:"token",type:String}]},Z={description:"Scaffold lunora/schema.ts (and list/get procedures) from an existing Postgres or MySQL database",examples:[["lunora introspect --url postgres://localhost/shop","Scaffold a schema + procedures from every table"],["lunora introspect --tables users,orders","Introspect only these tables (DATABASE_URL is read by default)"],["lunora introspect --dry-run","Print what would be written without touching the filesystem"],["lunora introspect --no-procedures --force","Regenerate just the schema, overwriting the existing file"]],group:"Data",loader:()=>import("../packem_chunks/handler22.mjs").then(e=>({default:e.execute})),name:"introspect",options:[{description:"Database connection string (default: $DATABASE_URL)",name:"url",type:String},{description:"Postgres schema (default `public`) or MySQL database name",name:"schema",type:String},{description:"Comma-separated table allow-list (default: every base table)",name:"tables",type:String},{description:"Also emit list/get procedure modules per table (default true; --no-procedures to skip)",name:"procedures",type:Boolean},{description:"Overwrite files that already exist",name:"force",type:Boolean},{description:"Print what would be written without writing it",name:"dry-run",type:Boolean}]},ee={description:"Link this checkout to its deployed Worker (writes .lunora/project.json)",examples:[["lunora link --url https://app.acme.workers.dev","Link to a deployed Worker URL"],["lunora link --url https://app.acme.workers.dev --env production","Link a named environment"],["lunora link --remove","Remove the link"]],group:"Deploy",loader:()=>import("../packem_chunks/handler14.mjs").then(e=>({default:e.execute})),name:"link",options:[{description:"Cloudflare environment name to record alongside the link",name:"env",type:String},{description:"Worker name (defaults to the `name` in wrangler config)",name:"name",type:String},{description:"Remove the existing link (.lunora/project.json)",name:"remove",type:Boolean},{description:"Deployed Worker URL to link (e.g. https://app.acme.workers.dev)",name:"url",type:String}]},te={argument:{description:"Worker name (defaults to the name in wrangler config)",name:"worker",type:String},description:"Stream live logs from a deployed Worker, or read the durable log archive with --durable",group:"Deploy",loader:()=>import("../packem_chunks/handler21.mjs").then(e=>({default:e.execute})),name:"logs",options:[{description:"Cloudflare environment name",name:"env",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Substring filter on log messages",name:"search",type:String},{description:"Filter by invocation status: ok, error, or canceled",name:"status",type:String},{description:"Tail a temporary-account deployment when unauthenticated (wrangler tail --temporary). Errors if you're already authenticated.",name:"temporary",type:Boolean},{description:"Read the durable log archive (pipelineLogSink → R2) via R2 SQL instead of tailing live",name:"durable",type:Boolean},{description:"durable: Iceberg table the Pipeline writes to (required with --durable)",name:"table",type:String},{description:"durable: Iceberg namespace (R2 Data Catalog database) the table lives in",name:"namespace",type:String},{description:"durable: lower time bound (epoch-millis or ISO 8601), inclusive",name:"since",type:String},{description:"durable: upper time bound (epoch-millis or ISO 8601), inclusive",name:"until",type:String},{description:"durable: exact severity filter (trace|debug|log|info|warn|error|fatal)",name:"level",type:String},{description:"durable: severity floor — this level and every more-severe one",name:"min-level",type:String},{description:"durable: keep function paths starting with this prefix (LIKE 'prefix%')",name:"function-prefix",type:String},{description:"durable: trace-id filter",name:"trace-id",type:String},{description:"durable: shard-key filter",name:"shard-key",type:String},{description:"durable: user-id filter",name:"user-id",type:String},{description:"durable: max rows (clamped to 1–10000; default 500)",name:"limit",type:String},{description:"durable: resume after a prior page — the opaque cursor token printed by the previous page (bare epoch-millis also accepted for back-compat)",name:"cursor",type:String},{description:"durable: emit one JSON object per line instead of a table",name:"ndjson",type:Boolean}]},re={argument:{description:"install [client…] | uninstall [client…] | serve",name:"args",type:String},description:"Connect your AI editor to Lunora over MCP (docs search + this project's dev server)",examples:[["lunora mcp install","Install into every MCP client already configured here"],["lunora mcp install claude-code cursor","Install into specific clients"],["lunora mcp install --list","List the supported clients and their config files"],["lunora mcp install --docs-only","Install only the hosted documentation server"],["lunora mcp install --print","Show the config that would be written, without writing it"],["lunora mcp install --global","Force every server into the machine-wide config"],["lunora mcp uninstall","Remove Lunora's MCP servers from every supported client"],["lunora mcp uninstall cursor","Remove them from one client"],["lunora mcp uninstall --print","Show what would be removed, without removing it"],["lunora mcp serve","Run the stdio MCP server (this is what your editor spawns)"],["lunora mcp serve --allow-writes","Also expose the mutation/action tools"]],group:"Develop",loader:()=>import("../packem_chunks/handler23.mjs").then(e=>({default:e.execute})),name:"mcp",options:[{description:"install: replace entries that already exist",name:"force",type:Boolean},{description:"install: list the supported clients and their config files",name:"list",type:Boolean},{description:"install/uninstall: print what would change instead of writing it",name:"print",type:Boolean},{description:"install/uninstall: only the hosted documentation server",name:"docs-only",type:Boolean},{description:"install/uninstall: only this project's local server",name:"local-only",type:Boolean},{description:"install/uninstall: the machine-wide config (install default: docs server global, local server per-project)",name:"global",type:Boolean},{description:"install/uninstall: this project's config instead of the machine-wide one",name:"project",type:Boolean},{description:"serve: also expose the mutation/action tools (default: read-only)",name:"allow-writes",type:Boolean},{description:"serve: skip the documentation tools",name:"no-docs",type:Boolean},{description:"Docs site origin backing the documentation tools (default https://lunora.sh)",name:"docs-url",type:String},{description:"serve: deployment URL to expose (default: the running dev server)",name:"url",type:String},{description:"serve: bearer token (default: LUNORA_ADMIN_TOKEN from the environment or .dev.vars)",name:"token",type:String}]},oe={argument:{description:"generate | create | up | down | status | d1-to-hyperdrive [name|id]",name:"subcommand",type:String},description:"Schema (generate), online data (create | up | down | status), and backend (d1-to-hyperdrive) migrations",examples:[["lunora migrate generate","Diff lunora/schema.ts and emit a SQL migration"],["lunora migrate create add_users_email","Scaffold a data migration"],["lunora migrate up backfill-names","Run a data migration across shards"],["lunora migrate status backfill-names","Report a migration's per-shard status"],["lunora migrate d1-to-hyperdrive --from-url https://old --to-url https://new","Copy .global() data from D1 to Hyperdrive"]],group:"Data",loader:()=>import("../packem_chunks/runMigrateGenerateCommand.mjs").then(e=>({default:e.execute})),name:"migrate",options:[{description:"Migration name slug (e.g. add_users_email)",name:"name",type:String},{description:"Target table for `create` (prompted for interactively when omitted)",name:"table",type:String},{description:"Preview a data migration without rewriting rows",name:"dry-run",type:Boolean},{description:"Rows per batch for a data migration",name:"batch-size",type:Number},{description:"Cap batches processed this run (maps to the runner's maxBatches)",name:"steps",type:Number},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String},{description:"Required with --prod for up/down — confirms running against production",name:"yes",type:Boolean},{description:"d1-to-hyperdrive: source (D1) worker URL (defaults to --url)",name:"from-url",type:String},{description:"d1-to-hyperdrive: source admin token (defaults to --token / LUNORA_ADMIN_TOKEN)",name:"from-token",type:String},{description:"d1-to-hyperdrive: target (Hyperdrive) worker URL (defaults to --url)",name:"to-url",type:String},{description:"d1-to-hyperdrive: target admin token (defaults to --token / LUNORA_ADMIN_TOKEN)",name:"to-token",type:String},{description:"d1-to-hyperdrive: comma-separated .global() tables to move (default: all global tables)",name:"tables",type:String},{description:"d1-to-hyperdrive: keep the intermediate NDJSON dump at this path",name:"out",type:String}]},ne={description:"Run codegen + binding reconcile + wrangler validation (no Vite) — for CI",examples:[["lunora prepare","Codegen + binding reconcile + validate (CI, before deploy)"]],group:"Deploy",loader:()=>import("../packem_chunks/handler15.mjs").then(e=>({default:e.execute})),name:"prepare",options:[{description:"Override the schema-drift gate (proceed even with breaking schema drift and no migration)",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${s} (default openapi)`,name:"api-spec",type:String},{description:"Re-bless the committed schema baseline (lunora/.lunora-schema.json) with the current shape",name:"update-schema-baseline",type:Boolean}]},ae={argument:{description:"<add|list|view|build> [item names…]",name:"args",type:String},description:"Component registry: add/list/view items, or build the catalog",examples:[["lunora registry list","List available registry items"],["lunora registry add presence","Scaffold a registry item into lunora/"],["lunora registry build --check","Verify the committed catalog is current"]],group:"Project",loader:()=>import("../packem_chunks/handler16.mjs").then(e=>({default:e.execute})),name:"registry",options:[{description:"add: print the plan and stop without writing",name:"dry-run",type:Boolean},{description:"add: preview the file changes (content diff) and write nothing",name:"diff",type:Boolean},{description:"add: force-overwrite existing files (take the incoming copy)",name:"overwrite",type:Boolean},{description:"add: skip the package.json mutation confirmation prompt",name:"yes",type:Boolean},{description:"Local registry root (offline; expects <name>/ subdirs)",name:"from",type:String},{description:"Override the remote registry source base (e.g. gh:owner/repo/registry)",name:"source",type:String},{description:"Fetch items from a git ref (branch, tag, or commit), e.g. --ref alpha. Overrides the version-derived default",name:"ref",type:String},{description:"Permit --source values outside gh:/github:/https://",name:"allow-unsafe-source",type:Boolean},{description:"Emit JSON output (add plan / list)",name:"json",type:Boolean},{description:"build: output path for the catalog (default <root>/index.json)",name:"out",type:String},{description:"build: verify the index is current instead of rewriting it",name:"check",type:Boolean}]},ie={description:"Clear local Miniflare state (and .lunora-cache with --all)",examples:[["lunora reset","Clear local Miniflare state"],["lunora reset --all","Also remove .lunora-cache"]],group:"Develop",loader:()=>import("../packem_chunks/runResetCommand.mjs").then(e=>({default:e.execute})),name:"reset",options:[{description:"Also remove .lunora-cache",name:"all",type:Boolean},{description:"Skip the confirmation prompt (required when stdin is not a TTY)",name:"yes",type:Boolean}]},se={argument:{description:"install | check",name:"subcommand",type:String},description:"Install the Lunora agent skills (AI rules) into .agents/skills/, or check they're present",examples:[["lunora rules install","Copy the Lunora agent skills into .agents/skills/"],["lunora rules install --overwrite","Reinstall, replacing edited skill files"],["lunora rules check","Report which Lunora skills are installed"],["lunora rules check --strict","Exit non-zero when rules are missing (CI gate)"]],group:"Project",loader:()=>import("../packem_chunks/handler17.mjs").then(e=>({default:e.execute})),name:"rules",options:[{description:"install: overwrite skill files that already exist (default: skip them)",name:"overwrite",type:Boolean},{description:"check: exit non-zero when the rules are missing (for CI gating)",name:"strict",type:Boolean}]},le={argument:{description:"Function path (e.g. messages:send)",name:"functionPath",type:String},description:"Send a single RPC to a running Lunora Worker",examples:[[`lunora run messages:send --args '{"text":"hi"}'`,"Call a function with JSON args"],["lunora run messages:list --shard channel:demo","Target a specific shard"],["lunora run messages:list --as user_123","Run as an authenticated user (needed when the app gates on identity)"]],group:"Develop",loader:()=>import("../packem_chunks/runRpcCommand.mjs").then(e=>({default:e.execute})),name:"run",options:[{description:"JSON-encoded args object",name:"args",type:String},{description:"Run as this user id — dispatches through the admin-gated `runAs` op so identity-gated apps accept the call",name:"as",type:String},{description:`JSON-encoded extra identity claims to forge alongside --as (e.g. '{"org":"acme"}')`,name:"claims",type:String},{description:"Explicit shard key",name:"shard",type:String},{description:"Worker URL (defaults to the running dev server, else http://localhost:8787)",name:"url",type:String},{description:"Admin bearer for --as (prefer LUNORA_ADMIN_TOKEN or .dev.vars; --token is visible to other local processes via the process table)",name:"token",type:String}]},pe={description:"Generate deterministic fake data from lunora/schema.ts and bulk-insert it via the worker's admin endpoint",examples:[["lunora seed","Seed every table with the default row count"],["lunora seed --table posts --count 50","Seed 50 posts; FK-parent tables are seeded automatically"],["lunora seed --reset","Wipe local .wrangler/state, then seed from scratch"],["lunora seed --seed 7 --dry-run","Print the NDJSON for seed 7 without inserting"],["lunora seed --seed 7 --now 1785000000000","Byte-identical rows across runs (pins the clock too)"]],group:"Data",loader:()=>import("../packem_chunks/handler18.mjs").then(e=>({default:e.execute})),name:"seed",options:[{description:"Rows per table (default 10)",name:"count",type:Number},{description:"Seed only this table; its FK-parent tables are seeded automatically",name:"table",type:String},{description:"Deterministic seed — same value yields identical rows (default 0)",name:"seed",type:Number},{description:"Epoch-ms reference for time columns (createdAt, expiresAt, …). Pin it with --seed for byte-identical rows across runs; defaults to now",name:"now",type:Number},{description:"Print the generated NDJSON instead of inserting",name:"dry-run",type:Boolean},{description:"Wipe local .wrangler/state before seeding (local dev only)",name:"reset",type:Boolean},{description:"Rows per HTTP request (default 500)",name:"batch-size",type:Number},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String},{description:"Skip the confirmation prompt when seeding a non-local/production target",name:"yes",type:Boolean}]},de={description:"Validate wrangler.jsonc + codegen dry-run + tsc --noEmit (no files written)",examples:[["lunora verify","Validate wrangler + codegen + tsc"],["lunora verify --no-typecheck","Skip the TypeScript type-check"],["lunora verify --health-url https://my-app.workers.dev","Also probe the deployment's /_lunora/health"]],group:"Deploy",loader:()=>import("../packem_chunks/handler19.mjs").then(e=>({default:e.execute})),name:"verify",options:[{description:"Treat breaking schema drift as a warning instead of a failure",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${s} (default openapi)`,name:"api-spec",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Probe this deployment's /_lunora/health endpoint (off by default; keeps verify offline-safe)",name:"health-url",type:String},{description:"Skip the TypeScript type-check step",name:"no-typecheck",type:Boolean}]},ce={description:"Open the Lunora studio in your browser (local dev by default, --remote for production)",examples:[["lunora view","Open the studio for local dev"],["lunora view --remote","Open the deployed studio"]],group:"Project",loader:()=>import("../packem_chunks/handler20.mjs").then(e=>({default:e.execute})),name:"view",options:[{description:"Open the deployed worker URL instead of localhost",name:"remote",type:Boolean}]},ue={filterStacktrace:()=>!1,hideErrorCodeView:!0},me=(e,t={})=>{const r=e instanceof Error?e.message:String(e),o=A(v(e)?{code:e.code,hint:e.hint,message:r}:r),n=new j({hint:o===void 0?void 0:B(o).split(`
|
|
2
|
+
`),message:t.reason===void 0?r:`${t.reason}: ${r}`,name:e instanceof Error&&e.name.length>0?e.name:"Error"});return n.stack="",I(n,ue)},ge=(e,t)=>{const r=Array.from({length:t.length+1},(o,n)=>n);for(let o=1;o<=e.length;o+=1){let n=r[0]??0;r[0]=o;for(let a=1;a<=t.length;a+=1){const i=r[a]??0,l=e[o-1]===t[a-1]?0:1;r[a]=Math.min((r[a-1]??0)+1,i+1,n+l),n=i}}return r[t.length]??0},he=(e,t)=>{let r,o=Number.POSITIVE_INFINITY;for(const a of t){const i=ge(e,a);i<o&&(o=i,r=a)}const n=Math.max(2,Math.ceil(e.length/3));return r!==void 0&&o<=n?r:void 0},ye=e=>`https://registry.npmjs.org/@lunora/cli/${e}`,fe=1440*60*1e3,ve=1500,be="0.0.0",we=/^v/u,ke=new Set(["alpha","beta","next"]),c=e=>{const t=e.trim().replace(we,""),r=t.indexOf("-");return r===-1?{core:t,prerelease:""}:{core:t.slice(0,r),prerelease:t.slice(r+1)}},h=e=>{const[t,r,o]=c(e).core.split(".").map(n=>{const a=Number.parseInt(n,10);return Number.isFinite(a)?a:0});return[t??0,r??0,o??0]},Se=(e,t)=>{const r=Number.parseInt(e,10),o=Number.parseInt(t,10);return String(r)===e&&String(o)===t?r>o?1:-1:e>t?1:-1},xe=(e,t)=>{if(e===t)return 0;if(e===""||t==="")return e===""?1:-1;const r=e.split("."),o=t.split(".");for(let n=0;n<Math.max(r.length,o.length);n+=1){const a=r[n],i=o[n];if(a===void 0||i===void 0)return a===void 0?-1:1;if(a!==i)return Se(a,i)}return 0},Ne=(e,t)=>{const r=h(e),o=h(t);for(let n=0;n<3;n+=1)if((r[n]??0)!==(o[n]??0))return(r[n]??0)>(o[n]??0)?1:-1;return xe(c(e).prerelease,c(t).prerelease)},Oe=e=>{const t=c(e).prerelease.split(".")[0]??"";return ke.has(t)?t:"latest"},Re=(e,t)=>Ne(t,e)>0,Ae=(e,t,r)=>t-e<r,Be=(e,t,r="latest")=>`Update available for @lunora/cli: ${e} → ${t} — run \`pnpm add -D @lunora/cli@${r}\``,w=e=>d(e,"lunora-cli-update.json"),Le=e=>{const t=e.XDG_CACHE_HOME&&e.XDG_CACHE_HOME.length>0?e.XDG_CACHE_HOME:d(_(),".cache"),r=d(t,"lunora");try{x(r,{mode:448,recursive:!0})}catch{}return r},De=e=>{try{const t=JSON.parse(f(w(e),"utf8"));if(t!==null&&typeof t=="object"){const{checkedAt:r,latest:o}=t;if(typeof o=="string"&&typeof r=="number"){const{tag:n}=t;return{checkedAt:r,latest:o,...typeof n=="string"?{tag:n}:{}}}}}catch{}},y=(e,t)=>{try{const r=w(e);try{if(N(r).isSymbolicLink())return}catch{}O(r,`${JSON.stringify(t)}
|
|
3
|
+
`,"utf8")}catch{}},Ee=async(e,t)=>{try{const r=await e(ye(t),{signal:AbortSignal.timeout(ve)});if(!r.ok)return;const o=await r.json(),n=o!==null&&typeof o=="object"?o.version:void 0;return typeof n=="string"?n:void 0}catch{return}},Ce=(e,t,r)=>e===be||!r||t.CI!==void 0||t.LUNORA_NO_UPDATE_NOTIFIER!==void 0,je=async e=>{const t=e.env??process.env,r=e.isTTY??process.stdout.isTTY;if(Ce(e.current,t,r))return;const o=e.cacheDir??Le(t),n=(e.now??Date.now)(),a=e.ttlMs??fe,i=Oe(e.current),l=De(o),S=l?.tag??"latest",u=l!==void 0&&S===i?l:void 0;let p=u?.latest;if(u===void 0||!Ae(u.checkedAt,n,a)){const m=await Ee(e.fetchImpl??globalThis.fetch,i);m===void 0?y(o,{checkedAt:n,latest:e.current,tag:i}):(p=m,y(o,{checkedAt:n,latest:m,tag:i}))}p!==void 0&&Re(e.current,p)&&e.logger.warn(Be(e.current,p,i))},Ie=["init","add","dev","codegen","build","deploy","containers","prepare","link","deployments","logs","run","insights","reset","migrate","export","import","seed","backup","verify","info","doctor","env","analyze","view","docs","registry","rules","mcp"],_e=8,Pe=()=>{try{let e=g(R(import.meta.url));for(let t=0;t<_e;t+=1){try{const o=JSON.parse(f(d(e,"package.json"),"utf8")),n=o!==null&&typeof o=="object"?o:void 0;if(n?.name==="@lunora/cli"&&typeof n.version=="string"&&n.version.length>0)return n.version}catch{}const r=g(e);if(r===e)break;e=r}}catch{}return"0.0.0"},k=Pe(),Te=[Q,P,q,M,U,J,W,ne,ee,K,te,le,X,ie,oe,G,Y,pe,Z,$,de,z,H,V,T,ce,F,ae,se,re],$e=e=>{const t={value:0},r=D("lunora",{argv:e.argv===void 0?void 0:[...e.argv],cwd:e.cwd,exit:o=>{t.value=typeof o=="number"?o:0},logger:e.logger,packageName:"@lunora/cli",packageVersion:k});for(const o of Te)r.addCommand(o);return r.addCommand(C),r.addCommand(E),{cli:r,exitCode:t}},Ue=/Command "(?<name>[^"]+)" not found/u,Me=e=>{const t=b(),r=e instanceof Error?e.message:String(e),o=Ue.exec(r);if(!o?.groups){v(e)||L(r)!==void 0?t.error(me(e)):t.error(r);return}const n=o.groups.name??"",a=he(n,Ie);t.error(`Unknown command "${n}".${a===void 0?"":` Did you mean "${a}"?`}`),t.info("Run `lunora --help` to list commands, or `lunora docs` to open the documentation.")},Xe=async(e={})=>{const{cli:t,exitCode:r}=$e(e);try{await t.run({shouldExitProcess:!1})}catch(o){return Me(o),1}return await je({current:k,logger:b()}),r.value};export{Ie as COMMANDS,k as VERSION,Xe as runCli};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import{createWriteStream as x,createReadStream as N}from"node:fs";import{unlink as I,stat as E}from"node:fs/promises";import{LunoraError as S}from"@lunora/errors";import{l as k}from"./admin-token-DV5A9T5b.mjs";import{u as O}from"./admin-url-Ca-KI3d_.mjs";const A="/_lunora/admin/export",_="/_lunora/admin/import",P=500,L=t=>{if(t===void 0)return;const r=t.split(",").map(o=>o.trim()).filter(o=>o.length>0);return r.length>0?r:void 0},T=async(t,r)=>{t.write(r)||await new Promise(o=>{t.once("drain",o)})},R=async(t,r)=>{const o=t.getReader(),u=new TextDecoder;let s=0,g=0,e="",a=!1;try{for(;!a;){const c=await o.read();if(a=c.done,c.value===void 0)continue;s+=c.value.length,e+=u.decode(c.value,{stream:!0});let l=e.indexOf(`
|
|
2
|
+
`);for(;l!==-1;){g+=1;const n=`${e.slice(0,l)}
|
|
3
|
+
`;await T(r,n),e=e.slice(l+1),l=e.indexOf(`
|
|
4
|
+
`)}}return e.length>0&&(g+=1,await T(r,`${e}
|
|
5
|
+
`)),{bytes:s,rows:g}}finally{o.releaseLock()}},j=async(t,r)=>{if(r!==void 0){t.destroy();try{await I(r)}catch{}}},B=async t=>{if(t.prod&&t.url===void 0)return t.logger.error("--prod requires an explicit --url (refusing to export from the implicit localhost worker)"),{bytes:0,code:1,rows:0};const r=O(t.url,t.logger,t.cwd);if(r===void 0)return{bytes:0,code:1,rows:0};const{token:o}=k({cwd:t.cwd??process.cwd(),token:t.token,url:r});if(!o)return t.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{bytes:0,code:1,rows:0};const u=`${r}${A}`,s=L(t.tables),g=t.fetchImpl??globalThis.fetch;if(typeof g!="function")throw new TypeError("no fetch implementation available — pass fetchImpl or run on Node >= 18");t.logger.info(`POST ${u} -> export${s?` (tables: ${s.join(",")})`:""}`);const e=await g(u,{body:JSON.stringify(s?{tables:s}:{}),headers:{authorization:`Bearer ${o}`,"content-type":"application/json"},method:"POST"});if(!e.ok){const d=await e.text();return t.logger.error(`export failed: HTTP ${String(e.status)}: ${d}`),{bytes:0,code:1,rows:0}}if(!e.body)return t.logger.error("export response carried no body"),{bytes:0,code:1,rows:0};const a=t.out===void 0||t.out==="-"?void 0:t.out,c=a===void 0?process.stdout:x(a,{encoding:"utf8"});let l,n;try{({bytes:l,rows:n}=await R(e.body,c))}catch(d){throw await j(c,a),d}return a!==void 0&&(await new Promise((d,y)=>{c.end(w=>{w?y(w):d()})}),t.logger.success(`wrote ${String(n)} rows to ${a} (${String(l)} bytes)`)),{bytes:l,code:0,rows:n}},q=async t=>{if(t.prod&&t.url===void 0){t.logger.error("--prod requires an explicit --url (refusing to import to the implicit localhost worker)");return}if(t.prod&&t.yes!==!0){t.logger.error("import --prod bulk-writes production. Re-run with --yes to confirm.");return}const r=O(t.url,t.logger,t.cwd);if(r===void 0)return;const{token:o}=k({cwd:t.cwd??process.cwd(),token:t.token,url:r});if(!o){t.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)");return}try{if(!(await E(t.file)).isFile()){t.logger.error(`not a file: ${t.file}`);return}}catch(s){const g=s instanceof Error?s.message:String(s);t.logger.error(`failed to stat ${t.file}: ${g}`);return}const u=t.fetchImpl??globalThis.fetch;if(typeof u!="function")throw new TypeError("no fetch implementation available — pass fetchImpl or run on Node >= 18");return{fetchImpl:u,requestUrl:`${r}${_}`,token:o}},F=async t=>{const r=await q(t);if(r===void 0)return{body:void 0,code:1,inserted:0};const{fetchImpl:o,requestUrl:u,token:s}=r,g=t.batchSize??P;t.logger.info(`POST ${u} -> import ${t.file}`);const e=N(t.file,{encoding:"utf8"}),a={},c=[];let l=0,n="",d=[],y=0;const w=async()=>{if(d.length===0)return;const p=d.join(`
|
|
6
|
+
`);d=[];const f=await o(u,{body:p,headers:{authorization:`Bearer ${s}`,"content-type":"application/x-ndjson"},method:"POST"});if(!f.ok){const m=await f.text().catch(()=>"<no body>");throw new S("INTERNAL",`import batch failed (HTTP ${String(f.status)}): ${m}`)}const i=await f.json();if(i.inserted)for(const[m,h]of Object.entries(i.inserted))a[m]=(a[m]??0)+h;Array.isArray(i.errors)&&c.push(...i.errors),typeof i.conflicts=="number"&&(l+=i.conflicts)},b=p=>{const f=p.trim();if(f.length===0)return;if(y+=1,t.table===void 0){d.push(f);return}let i;try{i=JSON.parse(f)}catch(m){const h=m instanceof Error?m.message:String(m);throw new S("INTERNAL",`invalid JSON on line ${String(y)}: ${h}`,{cause:m})}d.push(JSON.stringify({doc:i,table:t.table}))};for await(const p of e){const f=typeof p=="string"?p:p.toString("utf8");n+=f;let i=n.indexOf(`
|
|
7
|
+
`);for(;i!==-1;)b(n.slice(0,i)),n=n.slice(i+1),i=n.indexOf(`
|
|
8
|
+
`),d.length>=g&&await w()}n.length>0&&b(n),await w();const $=Object.values(a).reduce((p,f)=>p+f,0),v={conflicts:l,errors:c,inserted:a};return t.logger.info(JSON.stringify(v,void 0,2)),t.logger.success(`imported ${String($)} rows (${String(l)} conflicts, ${String(c.length)} errors)`),{body:v,code:c.length>0?1:0,inserted:$}};export{P as DEFAULT_IMPORT_BATCH_SIZE,B as runExportCommand,F as runImportCommand};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{readFileSync as a}from"node:fs";import{join as s}from"node:path";import{DEV_VARS_FILE as u,parseDevVariableEntries as c}from"@lunora/config";const n="LUNORA_ADMIN_TOKEN",v=new Set(["127.0.0.1","::1","[::1]","localhost"]),f=r=>{if(r===void 0||r==="")return!0;try{return v.has(new URL(r).hostname)}catch{return!1}},l=r=>{let e;try{e=a(s(r,u),"utf8")}catch{return}const o=c(e).find(t=>t.key===n);return o?.value===""?void 0:o?.value},p=({cwd:r,token:e,url:o})=>{if(e!==void 0&&e!=="")return{source:"flag",token:e};const t=process.env[n];if(t!==void 0&&t!=="")return{source:"env",token:t};if(!f(o))return{};const i=l(r);return i===void 0?{}:{source:"dev-vars",token:i}},h=r=>r==="flag"?"--token":r==="env"?n:u;export{p as l,h as v};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{readLiveDevServerState as l}from"@lunora/config";const n=new Set(["127.0.0.1","::1","[::1]","localhost"]),h=/\/$/u,a="http://localhost:8787",c=e=>e===void 0?a:l(e)?.url??a,i=(e,o,s)=>{const r=e??c(s);let t;try{t=new URL(r)}catch{o.error(`invalid --url: ${r}`);return}if(!n.has(t.hostname)&&t.protocol!=="https:"){o.error(`refusing to send the admin bearer over ${t.protocol}// to ${t.hostname} — use https for non-localhost targets`);return}return r.replace(h,"")};export{c as s,i as u};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/cli",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.125",
|
|
4
4
|
"description": "The Lunora CLI: init, dev, deploy, codegen, run, reset, and migrate commands",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agent-skills",
|
|
@@ -53,14 +53,14 @@
|
|
|
53
53
|
"dependencies": {
|
|
54
54
|
"@bomb.sh/tab": "0.0.21",
|
|
55
55
|
"@lunora/bindings": "1.0.0-alpha.13",
|
|
56
|
-
"@lunora/codegen": "1.0.0-alpha.
|
|
57
|
-
"@lunora/config": "1.0.0-alpha.
|
|
56
|
+
"@lunora/codegen": "1.0.0-alpha.76",
|
|
57
|
+
"@lunora/config": "1.0.0-alpha.102",
|
|
58
58
|
"@lunora/container": "1.0.0-alpha.17",
|
|
59
|
-
"@lunora/d1": "1.0.0-alpha.
|
|
59
|
+
"@lunora/d1": "1.0.0-alpha.51",
|
|
60
60
|
"@lunora/errors": "1.0.0-alpha.9",
|
|
61
61
|
"@lunora/mcp": "1.0.0-alpha.49",
|
|
62
|
-
"@lunora/runtime": "1.0.0-alpha.
|
|
63
|
-
"@lunora/seed": "1.0.0-alpha.
|
|
62
|
+
"@lunora/runtime": "1.0.0-alpha.45",
|
|
63
|
+
"@lunora/seed": "1.0.0-alpha.51",
|
|
64
64
|
"@visulima/cerebro": "3.0.0",
|
|
65
65
|
"@visulima/error": "6.0.0",
|
|
66
66
|
"@visulima/fs": "5.0.5",
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import{createWriteStream as T,createReadStream as x}from"node:fs";import{unlink as k,stat as I}from"node:fs/promises";import{LunoraError as S}from"@lunora/errors";import{a as O}from"./admin-url-DfVehV3e.mjs";const A="/_lunora/admin/export",E="/_lunora/admin/import",_=500,L=r=>{if(r===void 0)return;const t=r.split(",").map(o=>o.trim()).filter(o=>o.length>0);return t.length>0?t:void 0},N=async(r,t)=>{r.write(t)||await new Promise(o=>{r.once("drain",o)})},R=async(r,t)=>{const o=r.getReader(),u=new TextDecoder;let s=0,g=0,e="",a=!1;try{for(;!a;){const c=await o.read();if(a=c.done,c.value===void 0)continue;s+=c.value.length,e+=u.decode(c.value,{stream:!0});let l=e.indexOf(`
|
|
2
|
-
`);for(;l!==-1;){g+=1;const n=`${e.slice(0,l)}
|
|
3
|
-
`;await N(t,n),e=e.slice(l+1),l=e.indexOf(`
|
|
4
|
-
`)}}return e.length>0&&(g+=1,await N(t,`${e}
|
|
5
|
-
`)),{bytes:s,rows:g}}finally{o.releaseLock()}},P=async(r,t)=>{if(t!==void 0){r.destroy();try{await k(t)}catch{}}},M=async r=>{if(r.prod&&r.url===void 0)return r.logger.error("--prod requires an explicit --url (refusing to export from the implicit localhost worker)"),{bytes:0,code:1,rows:0};const t=r.token??process.env.LUNORA_ADMIN_TOKEN;if(!t)return r.logger.error("admin token required — pass --token or set LUNORA_ADMIN_TOKEN"),{bytes:0,code:1,rows:0};const o=O(r.url,r.logger);if(o===void 0)return{bytes:0,code:1,rows:0};const u=`${o}${A}`,s=L(r.tables),g=r.fetchImpl??globalThis.fetch;if(typeof g!="function")throw new TypeError("no fetch implementation available — pass fetchImpl or run on Node >= 18");r.logger.info(`POST ${u} -> export${s?` (tables: ${s.join(",")})`:""}`);const e=await g(u,{body:JSON.stringify(s?{tables:s}:{}),headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},method:"POST"});if(!e.ok){const d=await e.text();return r.logger.error(`export failed: HTTP ${String(e.status)}: ${d}`),{bytes:0,code:1,rows:0}}if(!e.body)return r.logger.error("export response carried no body"),{bytes:0,code:1,rows:0};const a=r.out===void 0||r.out==="-"?void 0:r.out,c=a===void 0?process.stdout:T(a,{encoding:"utf8"});let l,n;try{({bytes:l,rows:n}=await R(e.body,c))}catch(d){throw await P(c,a),d}return a!==void 0&&(await new Promise((d,w)=>{c.end(h=>{h?w(h):d()})}),r.logger.success(`wrote ${String(n)} rows to ${a} (${String(l)} bytes)`)),{bytes:l,code:0,rows:n}},U=async r=>{if(r.prod&&r.url===void 0){r.logger.error("--prod requires an explicit --url (refusing to import to the implicit localhost worker)");return}if(r.prod&&r.yes!==!0){r.logger.error("import --prod bulk-writes production. Re-run with --yes to confirm.");return}const t=r.token??process.env.LUNORA_ADMIN_TOKEN;if(!t){r.logger.error("admin token required — pass --token or set LUNORA_ADMIN_TOKEN");return}try{if(!(await I(r.file)).isFile()){r.logger.error(`not a file: ${r.file}`);return}}catch(s){const g=s instanceof Error?s.message:String(s);r.logger.error(`failed to stat ${r.file}: ${g}`);return}const o=O(r.url,r.logger);if(o===void 0)return;const u=r.fetchImpl??globalThis.fetch;if(typeof u!="function")throw new TypeError("no fetch implementation available — pass fetchImpl or run on Node >= 18");return{fetchImpl:u,requestUrl:`${o}${E}`,token:t}},C=async r=>{const t=await U(r);if(t===void 0)return{body:void 0,code:1,inserted:0};const{fetchImpl:o,requestUrl:u,token:s}=t,g=r.batchSize??_;r.logger.info(`POST ${u} -> import ${r.file}`);const e=x(r.file,{encoding:"utf8"}),a={},c=[];let l=0,n="",d=[],w=0;const h=async()=>{if(d.length===0)return;const p=d.join(`
|
|
6
|
-
`);d=[];const f=await o(u,{body:p,headers:{authorization:`Bearer ${s}`,"content-type":"application/x-ndjson"},method:"POST"});if(!f.ok){const m=await f.text().catch(()=>"<no body>");throw new S("INTERNAL",`import batch failed (HTTP ${String(f.status)}): ${m}`)}const i=await f.json();if(i.inserted)for(const[m,y]of Object.entries(i.inserted))a[m]=(a[m]??0)+y;Array.isArray(i.errors)&&c.push(...i.errors),typeof i.conflicts=="number"&&(l+=i.conflicts)},b=p=>{const f=p.trim();if(f.length===0)return;if(w+=1,r.table===void 0){d.push(f);return}let i;try{i=JSON.parse(f)}catch(m){const y=m instanceof Error?m.message:String(m);throw new S("INTERNAL",`invalid JSON on line ${String(w)}: ${y}`,{cause:m})}d.push(JSON.stringify({doc:i,table:r.table}))};for await(const p of e){const f=typeof p=="string"?p:p.toString("utf8");n+=f;let i=n.indexOf(`
|
|
7
|
-
`);for(;i!==-1;)b(n.slice(0,i)),n=n.slice(i+1),i=n.indexOf(`
|
|
8
|
-
`),d.length>=g&&await h()}n.length>0&&b(n),await h();const $=Object.values(a).reduce((p,f)=>p+f,0),v={conflicts:l,errors:c,inserted:a};return r.logger.info(JSON.stringify(v,void 0,2)),r.logger.success(`imported ${String($)} rows (${String(l)} conflicts, ${String(c.length)} errors)`),{body:v,code:c.length>0?1:0,inserted:$}};export{_ as DEFAULT_IMPORT_BATCH_SIZE,M as runExportCommand,C as runImportCommand};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const n=new Set(["127.0.0.1","::1","[::1]","localhost"]),s=/\/$/u,a=(r,e)=>{const o=r??"http://localhost:8787";let t;try{t=new URL(o)}catch{e.error(`invalid --url: ${o}`);return}if(!n.has(t.hostname)&&t.protocol!=="https:"){e.error(`refusing to send the admin bearer over ${t.protocol}// to ${t.hostname} — use https for non-localhost targets`);return}return o.replace(s,"")};export{a};
|