@lunora/cli 1.0.0-alpha.146 → 1.0.0-alpha.147
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 +24 -12
- package/dist/index.d.ts +24 -12
- 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/handler18.mjs +2 -2
- package/dist/packem_chunks/handler21.mjs +1 -1
- package/dist/packem_chunks/handler25.mjs +1 -1
- package/dist/packem_chunks/handler3.mjs +2 -2
- package/dist/packem_chunks/runMigrateGenerateCommand.mjs +3 -3
- package/dist/packem_shared/{COMMANDS-smh_Sw-C.mjs → COMMANDS-DNQLU6rs.mjs} +1 -1
- package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-C4qrFAn_.mjs +8 -0
- package/dist/packem_shared/cli-C-iz79JI.mjs +3 -0
- package/dist/packem_shared/runExportCommand-DFpdjDoT.mjs +5 -0
- package/dist/packem_shared/shared-BF5QIWFD.mjs +1 -0
- package/package.json +12 -11
- package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-DSLYaBzg.mjs +0 -9
- package/dist/packem_shared/cli-CIFLIzNi.mjs +0 -3
package/dist/bin.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{f as s}from"./packem_shared/cli-
|
|
2
|
+
import{f as s}from"./packem_shared/cli-C-iz79JI.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
|
@@ -89,15 +89,14 @@ interface CodegenCommandResult {
|
|
|
89
89
|
outputDirectory: string;
|
|
90
90
|
}
|
|
91
91
|
declare const runCodegenCommand: (options: CodegenCommandOptions) => CodegenCommandResult;
|
|
92
|
-
/** Rows per HTTP request when importing. Convex uses ~500; same here. */
|
|
93
|
-
declare const DEFAULT_IMPORT_BATCH_SIZE = 500;
|
|
94
92
|
/**
|
|
95
|
-
* Minimal projection of `globalThis.fetch` for the
|
|
96
|
-
*
|
|
97
|
-
*
|
|
93
|
+
* Minimal projection of `globalThis.fetch` for the transfer commands: `body` is
|
|
94
|
+
* exposed as a stream-iterable (the export path pipes it) and accepts bytes (the
|
|
95
|
+
* blob path uploads them). The JSON-only commands use the narrower `FetchLike`
|
|
96
|
+
* in `../run/handler` instead.
|
|
98
97
|
*/
|
|
99
98
|
type StreamingFetchLike = (input: string, init?: {
|
|
100
|
-
body?: string;
|
|
99
|
+
body?: string | Uint8Array;
|
|
101
100
|
headers?: Record<string, string>;
|
|
102
101
|
method?: string;
|
|
103
102
|
}) => Promise<{
|
|
@@ -134,6 +133,8 @@ interface ExportCommandResult {
|
|
|
134
133
|
* the body in memory.
|
|
135
134
|
*/
|
|
136
135
|
declare const runExportCommand: (options: ExportCommandOptions) => Promise<ExportCommandResult>;
|
|
136
|
+
/** Rows per HTTP request when importing. Convex uses ~500; same here. */
|
|
137
|
+
declare const DEFAULT_IMPORT_BATCH_SIZE = 500;
|
|
137
138
|
interface ImportCommandOptions {
|
|
138
139
|
/** Rows per HTTP request. Defaults to {@link DEFAULT_IMPORT_BATCH_SIZE}. */
|
|
139
140
|
batchSize?: number;
|
|
@@ -143,6 +144,11 @@ interface ImportCommandOptions {
|
|
|
143
144
|
file: string;
|
|
144
145
|
logger: Logger;
|
|
145
146
|
prod?: boolean;
|
|
147
|
+
/**
|
|
148
|
+
* Scan the export for columns holding `_storage` ids and write a candidate
|
|
149
|
+
* `lunora/import-convex.json`. Scan-only: nothing is imported.
|
|
150
|
+
*/
|
|
151
|
+
scan?: boolean;
|
|
146
152
|
/**
|
|
147
153
|
* Wrap each line as `{table:<name>,doc:<line>}`. Use when the source NDJSON
|
|
148
154
|
* is bare docs from a single table — Convex's `convex import --table users`
|
|
@@ -151,6 +157,18 @@ interface ImportCommandOptions {
|
|
|
151
157
|
table?: string;
|
|
152
158
|
token?: string;
|
|
153
159
|
url?: string;
|
|
160
|
+
/**
|
|
161
|
+
* Verify per-table row parity + dangling-storage after import. Exits non-zero
|
|
162
|
+
* when a table's inserted count differs from its source line count, or when a
|
|
163
|
+
* document references a storage id that was not migrated.
|
|
164
|
+
*/
|
|
165
|
+
verify?: boolean;
|
|
166
|
+
/**
|
|
167
|
+
* Also migrate Convex `_storage` blobs: read `_storage/documents.jsonl`, upload
|
|
168
|
+
* each blob with sha256+size verification, and build the `storageId → key` map.
|
|
169
|
+
* Off by default so the plain-document import path is unchanged.
|
|
170
|
+
*/
|
|
171
|
+
withStorage?: boolean;
|
|
154
172
|
/** Confirm bulk-writing production. Required alongside `--prod`. */
|
|
155
173
|
yes?: boolean;
|
|
156
174
|
}
|
|
@@ -160,12 +178,6 @@ interface ImportCommandResult {
|
|
|
160
178
|
/** Total inserted rows across batches. */
|
|
161
179
|
inserted: number;
|
|
162
180
|
}
|
|
163
|
-
/**
|
|
164
|
-
* Stream an NDJSON file — or a `npx convex export --path <dir>` directory — in
|
|
165
|
-
* chunks, POSTing each batch to `/_lunora/admin/import`. The line buffer stays
|
|
166
|
-
* bounded by `batchSize`, so a multi-GiB source imports without buffering
|
|
167
|
-
* everything in memory.
|
|
168
|
-
*/
|
|
169
181
|
declare const runImportCommand: (options: ImportCommandOptions) => Promise<ImportCommandResult>;
|
|
170
182
|
/**
|
|
171
183
|
* Injectable probe for a Docker-compatible container engine. Tests pass a
|
package/dist/index.d.ts
CHANGED
|
@@ -89,15 +89,14 @@ interface CodegenCommandResult {
|
|
|
89
89
|
outputDirectory: string;
|
|
90
90
|
}
|
|
91
91
|
declare const runCodegenCommand: (options: CodegenCommandOptions) => CodegenCommandResult;
|
|
92
|
-
/** Rows per HTTP request when importing. Convex uses ~500; same here. */
|
|
93
|
-
declare const DEFAULT_IMPORT_BATCH_SIZE = 500;
|
|
94
92
|
/**
|
|
95
|
-
* Minimal projection of `globalThis.fetch` for the
|
|
96
|
-
*
|
|
97
|
-
*
|
|
93
|
+
* Minimal projection of `globalThis.fetch` for the transfer commands: `body` is
|
|
94
|
+
* exposed as a stream-iterable (the export path pipes it) and accepts bytes (the
|
|
95
|
+
* blob path uploads them). The JSON-only commands use the narrower `FetchLike`
|
|
96
|
+
* in `../run/handler` instead.
|
|
98
97
|
*/
|
|
99
98
|
type StreamingFetchLike = (input: string, init?: {
|
|
100
|
-
body?: string;
|
|
99
|
+
body?: string | Uint8Array;
|
|
101
100
|
headers?: Record<string, string>;
|
|
102
101
|
method?: string;
|
|
103
102
|
}) => Promise<{
|
|
@@ -134,6 +133,8 @@ interface ExportCommandResult {
|
|
|
134
133
|
* the body in memory.
|
|
135
134
|
*/
|
|
136
135
|
declare const runExportCommand: (options: ExportCommandOptions) => Promise<ExportCommandResult>;
|
|
136
|
+
/** Rows per HTTP request when importing. Convex uses ~500; same here. */
|
|
137
|
+
declare const DEFAULT_IMPORT_BATCH_SIZE = 500;
|
|
137
138
|
interface ImportCommandOptions {
|
|
138
139
|
/** Rows per HTTP request. Defaults to {@link DEFAULT_IMPORT_BATCH_SIZE}. */
|
|
139
140
|
batchSize?: number;
|
|
@@ -143,6 +144,11 @@ interface ImportCommandOptions {
|
|
|
143
144
|
file: string;
|
|
144
145
|
logger: Logger;
|
|
145
146
|
prod?: boolean;
|
|
147
|
+
/**
|
|
148
|
+
* Scan the export for columns holding `_storage` ids and write a candidate
|
|
149
|
+
* `lunora/import-convex.json`. Scan-only: nothing is imported.
|
|
150
|
+
*/
|
|
151
|
+
scan?: boolean;
|
|
146
152
|
/**
|
|
147
153
|
* Wrap each line as `{table:<name>,doc:<line>}`. Use when the source NDJSON
|
|
148
154
|
* is bare docs from a single table — Convex's `convex import --table users`
|
|
@@ -151,6 +157,18 @@ interface ImportCommandOptions {
|
|
|
151
157
|
table?: string;
|
|
152
158
|
token?: string;
|
|
153
159
|
url?: string;
|
|
160
|
+
/**
|
|
161
|
+
* Verify per-table row parity + dangling-storage after import. Exits non-zero
|
|
162
|
+
* when a table's inserted count differs from its source line count, or when a
|
|
163
|
+
* document references a storage id that was not migrated.
|
|
164
|
+
*/
|
|
165
|
+
verify?: boolean;
|
|
166
|
+
/**
|
|
167
|
+
* Also migrate Convex `_storage` blobs: read `_storage/documents.jsonl`, upload
|
|
168
|
+
* each blob with sha256+size verification, and build the `storageId → key` map.
|
|
169
|
+
* Off by default so the plain-document import path is unchanged.
|
|
170
|
+
*/
|
|
171
|
+
withStorage?: boolean;
|
|
154
172
|
/** Confirm bulk-writing production. Required alongside `--prod`. */
|
|
155
173
|
yes?: boolean;
|
|
156
174
|
}
|
|
@@ -160,12 +178,6 @@ interface ImportCommandResult {
|
|
|
160
178
|
/** Total inserted rows across batches. */
|
|
161
179
|
inserted: number;
|
|
162
180
|
}
|
|
163
|
-
/**
|
|
164
|
-
* Stream an NDJSON file — or a `npx convex export --path <dir>` directory — in
|
|
165
|
-
* chunks, POSTing each batch to `/_lunora/admin/import`. The line buffer stays
|
|
166
|
-
* bounded by `batchSize`, so a multi-GiB source imports without buffering
|
|
167
|
-
* everything in memory.
|
|
168
|
-
*/
|
|
169
181
|
declare const runImportCommand: (options: ImportCommandOptions) => Promise<ImportCommandResult>;
|
|
170
182
|
/**
|
|
171
183
|
* Injectable probe for a Docker-compatible container engine. Tests pass a
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d as o,i as n,f as a}from"./packem_shared/cli-
|
|
1
|
+
import{d as o,i as n,f as a}from"./packem_shared/cli-C-iz79JI.mjs";import{runCodegenCommand as t}from"./packem_chunks/runCodegenCommand.mjs";import{runDeployCommand as p}from"./packem_chunks/runDeployCommand.mjs";import{planDevCommand as x,runDevCommand as i}from"./packem_chunks/planDevCommand.mjs";import{runInitCommand as l}from"./packem_chunks/runInitCommand.mjs";import{runMigrateGenerateCommand as u}from"./packem_chunks/runMigrateGenerateCommand.mjs";import{runResetCommand as g}from"./packem_chunks/runResetCommand.mjs";import{runRpcCommand as R}from"./packem_chunks/runRpcCommand.mjs";import{insertSchemaExtension as D}from"./packem_shared/insertSchemaExtension-DZReBZ4_.mjs";import{createLogger as A,pail as c}from"./packem_shared/createLogger-BoSxdb2T.mjs";import{diffSnapshots as v,renderAddColumn as _,renderCreateIndex as h,renderCreateTable as y,renderDropIndex as F,renderDropTable as L,renderMigrationFile as O,validatorKindToSqlType as b}from"./packem_shared/diffSnapshots-BbwCuhoN.mjs";import{default as B}from"./packem_shared/schemaIrToSnapshot-Dahp39qH.mjs";import{createRecordingSpawner as U,defaultSpawner as W}from"./packem_shared/createRecordingSpawner-SKs4R1fc.mjs";import{default as N}from"./packem_shared/parseManifest-x3WsxKHz.mjs";import{DEFAULT_IMPORT_BATCH_SIZE as V,runImportCommand as j}from"./packem_shared/DEFAULT_IMPORT_BATCH_SIZE-C4qrFAn_.mjs";import{REQUIRED_COMPATIBILITY_DATE as H,REQUIRED_FLAG as K,validateWranglerProject as Y,validateWranglerConfig as Z}from"@lunora/config/cloudflare";import{buildRegistryIndex as z}from"./packem_shared/buildRegistryIndex-DwySASBu.mjs";import{I as X,F as $,E as rr}from"./packem_shared/commands-CG9qEtqR.mjs";import{runExportCommand as or}from"./packem_shared/runExportCommand-DFpdjDoT.mjs";export{o as COMMANDS,V as DEFAULT_IMPORT_BATCH_SIZE,H as REQUIRED_COMPATIBILITY_DATE,K as REQUIRED_FLAG,n as VERSION,z as buildRegistryIndex,A as createLogger,U as createRecordingSpawner,W as defaultSpawner,v as diffSnapshots,D as insertSchemaExtension,c as pail,N as parseManifest,x as planDevCommand,_ as renderAddColumn,h as renderCreateIndex,y as renderCreateTable,F as renderDropIndex,L as renderDropTable,O as renderMigrationFile,X as runAddCommand,$ as runBuildIndexCommand,a as runCli,t as runCodegenCommand,p as runDeployCommand,i as runDevCommand,or as runExportCommand,j as runImportCommand,l as runInitCommand,u as runMigrateGenerateCommand,rr as runRegistryViewCommand,g as runResetCommand,R as runRpcCommand,B as schemaIrToSnapshot,Y as validateWrangler,Z as validateWranglerConfig,b as validatorKindToSqlType};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as p}from"../packem_shared/command-0l-ZPhIX.mjs";import{d as u}from"../packem_shared/resolve-target-CeiNrCAx.mjs";import{runExportCommand as d}from"../packem_shared/
|
|
1
|
+
import{i as p}from"../packem_shared/command-0l-ZPhIX.mjs";import{d as u}from"../packem_shared/resolve-target-CeiNrCAx.mjs";import{runExportCommand as d}from"../packem_shared/runExportCommand-DFpdjDoT.mjs";const a=p(({argument:r,cwd:t,logger:e,options:o})=>d({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{a as execute};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i
|
|
1
|
+
import{i}from"../packem_shared/command-0l-ZPhIX.mjs";import{d as n}from"../packem_shared/resolve-target-CeiNrCAx.mjs";import{runImportCommand as u}from"../packem_shared/DEFAULT_IMPORT_BATCH_SIZE-C4qrFAn_.mjs";const s=i(({argument:a,cwd:r,logger:o,options:e})=>{const t=a[0];return t?u({batchSize:e.batchSize,cwd:r,file:t,logger:o,prod:e.prod===!0,scan:e.scan===!0,table:e.table,token:e.token,url:n({cwd:r,prod:e.prod===!0,url:e.url}),verify:e.verify===!0,withStorage:e.withStorage===!0,yes:e.yes===!0}):(o.error("import requires a path. Usage: lunora import <file.ndjson | convex-export-dir> [--table <name>]"),{code:1})});export{s as execute};
|
|
@@ -1,3 +1,3 @@
|
|
|
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 x}from"@lunora/seed";import{join as m}from"@visulima/path";import{Project as z}from"ts-morph";import{d as F}from"../packem_shared/admin-token-BKmc3AUm.mjs";import{i as I}from"../packem_shared/command-0l-ZPhIX.mjs";import{d as R}from"../packem_shared/resolve-target-CeiNrCAx.mjs";import{o as T}from"../packem_shared/tui-prompts-BU3irGxV.mjs";import{
|
|
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 x}from"@lunora/seed";import{join as m}from"@visulima/path";import{Project as z}from"ts-morph";import{d as F}from"../packem_shared/admin-token-BKmc3AUm.mjs";import{i as I}from"../packem_shared/command-0l-ZPhIX.mjs";import{d as R}from"../packem_shared/resolve-target-CeiNrCAx.mjs";import{o as T}from"../packem_shared/tui-prompts-BU3irGxV.mjs";import{runResetCommand as A}from"./runResetCommand.mjs";import{runImportCommand as N}from"../packem_shared/DEFAULT_IMPORT_BATCH_SIZE-C4qrFAn_.mjs";const p=r=>r===""?!1:F(r),B=(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:""}),P=(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)},U=async(r,e,o,t)=>{const l=await S(m(j(),"lunora-seed-")),a=m(l,"rows.ndjson");await v(a,r,"utf8");try{const n=await N({batchSize:t.batchSize,cwd:o,fetchImpl:t.fetchImpl,file:a,logger:t.logger,prod:t.prod,token:t.token,url:t.url}),d=n.body?.conflicts??0;return d>0&&t.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(t=>t.name===r.table))return;const o=e.tables.map(t=>t.name).join(", ");return r.logger.error(`unknown table "${r.table}" — schema defines: ${o||"(no tables)"}`),c(1)},H=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??T)(`This will insert ${String(e)} generated row(s) into ${r.url??"the production worker"}. Continue?`))return r.logger.info("seed: aborted"),c(1)}},J=async r=>{const e=r.cwd??process.cwd(),o=m(e,"lunora","schema.ts"),t=P(r,o);if(t!==void 0)return t;const l=new z({skipAddingFilesFromTsConfig:!0}),a=k(l,o),n=_(r,a);if(n!==void 0)return n;const d=C(a),g=x(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},B));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
|
|
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 A({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 H(r,s);return w!==void 0?w:U(i,s,e,r)},Z=I(async({cwd:r,logger:e,options:o})=>({code:(await J({batchSize:o.batchSize,count:o.count,cwd:r,dryRun:o.dryRun===!0,logger:e,prod:o.prod===!0,reset:o.reset===!0,now:o.now,seed:o.seed,table:o.table,token:o.token,url:R({cwd:r,prod:o.prod===!0,url:o.url}),yes:o.yes===!0})).code}));export{Z as execute,J as runSeedCommand};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{writeFileSync as h,existsSync as v,readFileSync as S}from"node:fs";import{isAbsolute as w,join as b}from"node:path";import{byCodepoint as y,scoreAdvisor as x,parseAdvisorMap as j,compareToBaseline as R}from"@lunora/advisor";import{runCodegen as k}from"@lunora/codegen";import{i as A}from"../packem_shared/command-0l-ZPhIX.mjs";import{i as D,d as M,s as F,t as N}from"../packem_shared/output-format-Cv3aLqhP.mjs";import{o as g}from"../packem_shared/cli-
|
|
1
|
+
import{writeFileSync as h,existsSync as v,readFileSync as S}from"node:fs";import{isAbsolute as w,join as b}from"node:path";import{byCodepoint as y,scoreAdvisor as x,parseAdvisorMap as j,compareToBaseline as R}from"@lunora/advisor";import{runCodegen as k}from"@lunora/codegen";import{i as A}from"../packem_shared/command-0l-ZPhIX.mjs";import{i as D,d as M,s as F,t as N}from"../packem_shared/output-format-Cv3aLqhP.mjs";import{o as g}from"../packem_shared/cli-C-iz79JI.mjs";const l={clean:"·",exempt:"–",failing:"✗",warned:"!"},u=(r,e)=>r.length>=e?r:r+" ".repeat(e-r.length),C=r=>`${r.id} (${r.visibility} ${r.kind})`,m=r=>{let e=0;for(const o of r)e=Math.max(e,o.id.length);return e},p=(r,e)=>` ${u(String(r.score),3)} ${l[r.coverage]} ${u(r.id,e)} ${r.visibility} ${r.kind}`,E=r=>{if(!r.comparable)return[` baseline not comparable (${r.reason}) — regenerate it; this run cannot verify anything`];if(!r.regressed)return[` no regression against baseline (score ${r.scoreDelta>=0?"+":""}${String(r.scoreDelta)})`];const e=[` REGRESSED against baseline (score ${r.scoreDelta>=0?"+":""}${String(r.scoreDelta)})`];for(const o of r.dropped)e.push(` ${o.id}: ${String(o.before)} → ${String(o.after)}`);for(const o of r.newFailing)e.push(` ${o}: now failing`);for(const o of r.worsened)e.push(` ${o}: more findings than the baseline`);return r.projectRegressed&&e.push(" project: new schema/config rules fired"),e},J=(r,e)=>{const o=r.procedures.filter(i=>i.coverage!=="clean"&&i.coverage!=="exempt"),n=m(o),t=[`advisor health ${String(r.score)}/100 — ${r.grade}`,` ${String(r.summary.clean)} clean · ${String(r.summary.warned)} warned · ${String(r.summary.failing)} failing · ${String(r.summary.exempt)} exempt (${String(r.summary.procedures)} procedures, ${String(r.summary.rulesFired)} rules fired)`];return r.project.checks.length>0&&t.push("",` project ${String(r.project.score)}/100 — ${r.project.checks.map(i=>i.name).join(", ")}`),o.length>0&&t.push("",...o.map(i=>p(i,n)),""," run with --all for every procedure, or --entry <file#export> for one"),e!==void 0&&t.push("",...E(e)),t.join(`
|
|
2
2
|
`)},O=r=>r.coverage==="exempt"?[` exempt: ${r.exemptReason===void 0||r.exemptReason===""?"no reason given":r.exemptReason}`]:r.checks.map(e=>{const o=e.occurrences>1?`, ×${String(e.occurrences)}`:"";return` ${e.name} (−${String(e.weight)}${o})`}),B=r=>{const e=new Map;for(const o of r){const n=e.get(o.file);n===void 0?e.set(o.file,[o]):n.push(o)}return[...e].toSorted(([o],[n])=>y(o,n))},P=r=>{const e=m(r.procedures),o=[`advisor health ${String(r.score)}/100 — ${r.grade}`,"",` legend: ${l.clean} clean ${l.warned} warned ${l.failing} failing ${l.exempt} exempt`];for(const[n,t]of B(r.procedures)){o.push("",` ${n}`);for(const i of t)o.push(p(i,e),...O(i))}return o.join(`
|
|
3
3
|
`)},T=(r,e)=>{const o=r.procedures.find(t=>t.id===e);if(o===void 0){const t=r.procedures.slice(0,10).map(i=>` ${i.id}`);return[`no procedure ${e} in the map. Known ids:`,...t,r.procedures.length>10?" …":""].filter(Boolean).join(`
|
|
4
4
|
`)}const n=[`${C(o)} — ${String(o.score)}/100, ${o.coverage}`,` weight in the global mean: ${String(o.weight)}`];if(o.checks.length===0)return n.push(""," no rule fired"),n.join(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{i as L}from"../packem_shared/cli-
|
|
1
|
+
import{i as L}from"../packem_shared/cli-C-iz79JI.mjs";import{i as J}from"../packem_shared/command-0l-ZPhIX.mjs";import{existsSync as p,readFileSync as h,mkdirSync as P,realpathSync as W,statSync as D,writeFileSync as T,chmodSync as z,renameSync as H,unlinkSync as I}from"node:fs";import{homedir as $}from"node:os";import{findWranglerFile as K}from"@lunora/config/cloudflare";import{join as s,dirname as q,relative as G}from"@visulima/path";import{l as V,M as Z}from"../packem_shared/detect-package-manager-DXDstphE.mjs";import{stringify as B}from"smol-toml";import{parse as Q,modify as X,applyEdits as Y}from"jsonc-parser";import{readLiveDevServerState as y}from"@lunora/config";import{resolveAdminToken as oo}from"@lunora/config/studio-host";import{connectLocalStdio as to}from"@lunora/mcp";const u=o=>({args:[...o.args],command:o.command,...o.env===void 0?{}:{env:o.env}}),v=o=>o.transport==="http"?{type:"http",url:o.url}:u(o),eo=o=>o.transport==="http"?{httpUrl:o.url}:u(o),ro=o=>o.transport==="http"?{serverUrl:o.url}:u(o),no=o=>({args:["-y","mcp-remote",o],command:"npx"}),ao=o=>o.transport==="http"?no(o.url):u(o),io=o=>o.transport==="http"?{url:o.url}:u(o),lo=o=>o.transport==="http"?{enabled:!0,type:"remote",url:o.url}:{command:[o.command,...o.args],enabled:!0,type:"local",...o.env===void 0?{}:{environment:o.env}},so=o=>o.transport==="http"?{disabled:!1,type:"streamableHttp",url:o.url}:{disabled:!1,...u(o)},co=({home:o,platform:t})=>{if(t==="darwin")return{global:s(o,"Library","Application Support","Claude","claude_desktop_config.json")};if(t==="win32"){const e=process.env.APPDATA;return e===void 0||e===""?{}:{global:s(e,"Claude","claude_desktop_config.json")}}return t==="linux"?{global:s(o,".config","Claude","claude_desktop_config.json")}:{}},po=(o,t)=>B({mcp_servers:{[o]:t.transport==="http"?{url:t.url}:{args:[...t.args],command:t.command,...t.env===void 0?{}:{env:t.env}}}}),g=[{buildEntry:v,paths:({projectRoot:o})=>({project:s(o,".mcp.json")}),format:"json",id:"claude-code",key:"mcpServers",label:"Claude Code"},{buildEntry:v,paths:({home:o,projectRoot:t})=>({global:s(o,".cursor","mcp.json"),project:s(t,".cursor","mcp.json")}),format:"json",id:"cursor",key:"mcpServers",label:"Cursor"},{buildEntry:v,paths:({projectRoot:o})=>({project:s(o,".vscode","mcp.json")}),format:"json",id:"vscode",key:"servers",label:"VS Code (GitHub Copilot)"},{buildEntry:eo,paths:({home:o,projectRoot:t})=>({global:s(o,".gemini","settings.json"),project:s(t,".gemini","settings.json")}),format:"json",id:"gemini",key:"mcpServers",label:"Gemini CLI"},{buildEntry:ao,paths:co,format:"json",id:"claude-desktop",key:"mcpServers",label:"Claude Desktop"},{buildEntry:ro,paths:({home:o})=>({global:s(o,".codeium","windsurf","mcp_config.json")}),format:"json",id:"windsurf",key:"mcpServers",label:"Windsurf"},{buildEntry:lo,paths:({home:o,projectRoot:t})=>({global:s(o,".config","opencode","opencode.json"),project:s(t,"opencode.json")}),format:"json",id:"opencode",key:"mcp",label:"OpenCode"},{buildEntry:so,paths:({home:o})=>({global:s(o,".cline","mcp.json")}),format:"json",id:"cline",key:"mcpServers",label:"Cline"},{buildEntry:io,paths:({home:o})=>({global:s(o,".config","zed","settings.json")}),format:"json",id:"zed",key:"context_servers",label:"Zed"},{paths:({home:o,projectRoot:t})=>({global:s(o,".codex","config.toml"),project:s(t,".codex","config.toml")}),format:"manual",id:"codex",label:"Codex CLI",renderSnippet:po}],O=g.map(o=>o.id),uo=o=>g.find(t=>t.id===o.toLowerCase()),x=(o,t)=>{let e=o,r;try{e=W(o),r=D(e).mode}catch{}const a=`${e}.lunora-${Math.random().toString(36).slice(2,10)}.tmp`;try{T(a,t,"utf8"),r!==void 0&&z(a,r),H(a,e)}catch(n){try{I(a)}catch{}throw n}},mo={formattingOptions:{insertSpaces:!0,tabSize:4}},b=o=>{const t=[],e=Q(o,t,{allowTrailingComma:!0});return{errors:t,value:e}},f=o=>typeof o=="object"&&o!==null&&!Array.isArray(o),w=(o,t,e)=>{if(!f(o))return;const r=o[t];return f(r)?r[e]:void 0},C=o=>{if(!p(o.path))return"absent";let t;try{t=h(o.path,"utf8")}catch{return"invalid"}if(t.trim().length===0)return"absent";const{errors:e,value:r}=b(t);return e.length>0||!f(r)?"invalid":w(r,o.key,o.name)===void 0?"absent":"present"},fo=o=>C(o)==="present",E=(o,t,e,r,a)=>{try{const n=X(o,[e,r],a,mo);n.length>0&&x(t,Y(o,n));return}catch(n){return n instanceof Error?n.message:String(n)}},go=o=>{const{entry:t,force:e=!1,key:r,name:a,path:n}=o,i=p(n)?h(n,"utf8"):"";if(i.trim().length===0)return P(q(n),{recursive:!0}),x(n,`${JSON.stringify({[r]:{[a]:t}},void 0,4)}
|
|
2
2
|
`),{action:"created",path:n};const{errors:l,value:c}=b(i);if(l.length>0)return{action:"invalid",error:`parse error at offset ${String(l[0]?.offset??0)}`,path:n};if(!f(c))return{action:"invalid",error:"the file's root is not a JSON object",path:n};const m=c[r];if(m!==void 0&&!f(m))return{action:"invalid",error:`"${r}" is not an object`,path:n};if(w(c,r,a)!==void 0&&!e)return{action:"skipped",path:n};const j=E(i,n,r,a,t);return j===void 0?{action:"updated",path:n}:{action:"invalid",error:j,path:n}},ho=o=>{const{key:t,name:e,path:r}=o;if(!p(r))return{action:"absent",path:r};let a;try{a=h(r,"utf8")}catch(c){return{action:"invalid",error:c instanceof Error?c.message:String(c),path:r}}const{errors:n,value:i}=b(a);if(n.length>0)return{action:"invalid",error:`parse error at offset ${String(n[0]?.offset??0)}`,path:r};if(w(i,t,e)===void 0)return{action:"absent",path:r};const l=E(a,r,t,e,void 0);return l===void 0?{action:"removed",path:r}:{action:"invalid",error:l,path:r}},vo=["global","project"],d=(o,t)=>{const e=G(t,o);return e.length>0&&!e.startsWith("..")?e:o},yo=(o,t)=>{const e=o.paths(t);return vo.flatMap(r=>{const a=e[r];return a===void 0?[]:[{client:o,path:a,scope:r}]})},$o=(o,t,e,r)=>{const a=o.paths(t),n=e==="global"?"project":"global",i=a[e]??(r?void 0:a[n]);if(i!==void 0)return{client:o,path:i,scope:a[e]===void 0?n:e}},bo=o=>g.filter(t=>Object.values(t.paths(o)).some(e=>p(e))),R=(o,t,e,r)=>{if(o.length===0)return t();const a=[];for(const n of o){const i=uo(n);if(i===void 0){e.error(`mcp ${r}: unknown client "${n}". Known clients: ${O.join(", ")}.`);return}a.push(i)}return a},wo=o=>o.client.format==="json",jo="https://lunora.sh/mcp",U="lunora-docs",N="lunora",ko=o=>p(s(o,"lunora"))&&K(o)!==void 0,So=o=>{const{args:t,command:e}=Z(o,"lunora",["mcp","serve"]);return{args:t,command:e,transport:"stdio"}},Oo=o=>({transport:"http",url:o}),xo=o=>({home:o.home,platform:o.platform,projectRoot:o.cwd}),_=(o,t,e)=>$o(o,xo(e),e.scope??t.preferredScope,e.scope!==void 0||!t.allowScopeFallback),Co=(o,t,e)=>{const r=_(o,t,e);if(r===void 0){e.logger.warn(`${o.label}: has no ${e.scope??t.preferredScope}-scoped config — skipped "${t.name}".`);return}const{path:a}=r,n=o.buildEntry(t.spec);if(e.print===!0){const c=d(a,e.cwd);return e.force!==!0&&fo({key:o.key,name:t.name,path:a})?(e.logger.info(`${o.label}: "${t.name}" already configured in ${c} — a real install would skip it (re-run with --force to replace).`),{action:"printed",path:a}):(e.logger.info(`${o.label} → ${c}
|
|
3
3
|
${JSON.stringify({[o.key]:{[t.name]:n}},void 0,4)}`),{action:"printed",path:a})}const i=go({entry:n,force:e.force===!0,key:o.key,name:t.name,path:a}),l=d(a,e.cwd);return i.action==="invalid"?e.logger.error(`${o.label}: ${l} is not valid JSON (${i.error??"unknown error"}) — left untouched.`):i.action==="skipped"?e.logger.info(`${o.label}: "${t.name}" already configured in ${l} — re-run with --force to replace it.`):e.logger.success(`${o.label}: ${i.action==="created"?"created":"updated"} ${l} with "${t.name}".`),{action:i.action,path:a}},Eo=(o,t,e)=>{const r=_(o,t,e)?.path;if(r===void 0){e.logger.warn(`${o.label}: no known config location on ${e.platform} — skipped.`);return}return e.logger.info(`${o.label}: add this to ${d(r,e.cwd)}
|
|
4
4
|
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{existsSync as u}from"node:fs";import{mkdir as l,readFile as p,writeFile as m}from"node:fs/promises";import{join as n}from"node:path";import{LunoraError as
|
|
2
|
-
`,"utf8")},O=async(t,o)=>{await l(o,{recursive:!0});const e=(t.now??(()=>new Date))().toISOString(),r=`lunora-backup-${e.replaceAll(/[.:]/gu,"-")}.ndjson`,a=await
|
|
1
|
+
import{existsSync as u}from"node:fs";import{mkdir as l,readFile as p,writeFile as m}from"node:fs/promises";import{join as n}from"node:path";import{LunoraError as f}from"@lunora/errors";import{u as g}from"../packem_shared/admin-url-Ca-KI3d_.mjs";import{i as k}from"../packem_shared/command-0l-ZPhIX.mjs";import{d as w}from"../packem_shared/resolve-target-CeiNrCAx.mjs";import{readAndLogBody as b}from"./runRpcCommand.mjs";import{runExportCommand as y}from"../packem_shared/runExportCommand-DFpdjDoT.mjs";import{runImportCommand as h}from"../packem_shared/DEFAULT_IMPORT_BATCH_SIZE-C4qrFAn_.mjs";const $=".lunora-backups",d="manifest.json",v="/_lunora/admin/pitr",S="__lunora_admin__:getPitrBookmark",_="__lunora_admin__:pitrRestore",N=t=>typeof t=="object"&&t!==null&&typeof t.id=="string"&&typeof t.file=="string",c=async t=>{const o=n(t,d);if(!u(o))return[];let e;try{e=JSON.parse(await p(o,"utf8"))}catch(r){const a=r instanceof Error?r.message:String(r);throw new f("INTERNAL",`backup: ${o} exists but is not valid JSON (${a}) — refusing to overwrite it; fix or remove it manually`,{cause:r})}if(!Array.isArray(e))throw new TypeError(`backup: ${o} exists but is not a JSON array — refusing to overwrite it; fix or remove it manually`);return e.filter(N)},I=async(t,o)=>{await m(n(t,d),`${JSON.stringify(o,void 0,2)}
|
|
2
|
+
`,"utf8")},O=async(t,o)=>{await l(o,{recursive:!0});const e=(t.now??(()=>new Date))().toISOString(),r=`lunora-backup-${e.replaceAll(/[.:]/gu,"-")}.ndjson`,a=await y({cwd:t.cwd,fetchImpl:t.fetchImpl,logger:t.logger,out:n(o,r),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:e,file:r,id:e,rows:a.rows,tables:t.tables},s=await c(o);return s.push(i),await I(o,s),t.logger.success(`backup created: ${r} (${a.rows.toString()} rows, ${a.bytes.toString()} bytes)`),{code:0,entry:i}},A=async(t,o)=>{const e=await c(o);if(e.length===0)return t.logger.info(`no backups found in ${o}`),{code:0};for(const r of e)t.logger.info(`${r.id} ${r.rows.toString()} rows ${r.bytes.toString()} bytes ${r.file}`);return{code:0}},E=async(t,o)=>{const{target:e}=t;if(e===void 0||e.length===0)return t.logger.error("restore requires a backup id or file path. Usage: lunora backup restore <id|file>"),{code:1};const r=(await c(o)).find(i=>i.id===e),a=r?n(o,r.file):e;return u(a)?{code:(await h({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: ${e}`),{code:1})},x=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 e=g(t.url,t.logger,t.cwd);if(e===void 0)return;const r=t.pitrFetch??globalThis.fetch;if(typeof r!="function")throw new TypeError("no fetch implementation available — pass pitrFetch or run on Node >= 18");return{fetchImpl:r,requestUrl:`${e}${v}`,token:o}},T=(t,o)=>{const e={};return t.at!==void 0&&(e.time=t.at),o&&t.bookmark!==void 0&&(e.bookmark=t.bookmark),o&&t.restart===!0&&(e.restart=!0),e},q=async t=>{const o=x(t);if(o===void 0)return{code:1};const e=t.restore===!0,r=e?_:S,a=T(t,e),i=e?"restore":"bookmark";t.logger.info(`POST ${o.requestUrl} -> pitr ${i}${t.shard===void 0?"":` (shard "${t.shard}")`}`);const s=await o.fetchImpl(o.requestUrl,{body:JSON.stringify({args:a,functionPath:r,shardKey:t.shard}),headers:{authorization:`Bearer ${o.token}`,"content-type":"application/json"},method:"POST"});return await b(s,t.logger),{code:s.ok?0:1}},L=async t=>{const o=t.cwd??process.cwd(),e=n(o,t.dir??$);try{return t.subcommand==="create"?await O(t,e):t.subcommand==="list"?await A(t,e):t.subcommand==="pitr"?await q(t):await E(t,e)}catch(r){return t.logger.error(r instanceof Error?r.message:String(r)),{code:1}}},R=t=>t==="create"||t==="list"||t==="pitr"||t==="restore",z=k(({argument:t,cwd:o,logger:e,options:r})=>{const a=t[0];return R(a)?L({at:r.at,bookmark:r.bookmark,cwd:o,dir:r.dir,logger:e,prod:r.prod===!0,restart:r.restart===!0,restore:r.restore===!0,shard:r.shard,subcommand:a,tables:r.tables,target:t[1],token:r.token,url:w({cwd:o,prod:r.prod===!0,url:r.url}),yes:r.yes===!0}):(e.error(`backup: unknown subcommand "${a??""}" — expected create | list | restore | pitr`),{code:1})});export{z as execute,L as runBackupCommand};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{existsSync as u,mkdirSync as S,writeFileSync as p,mkdtempSync as C,rmSync as I,readFileSync as k}from"node:fs";import{tmpdir as M}from"node:os";import{discoverSchema as T,readPackageDependencies as A,discoverMigrations as
|
|
2
|
-
`,"utf8"),r.logger.success(`wrote ${m}`),l.unsupported.length>0&&r.logger.warn(`${String(l.unsupported.length)} unsupported diff(s) — see the comment block in ${b} and write the SQL manually`),{code:0,empty:!1,migrationFile:m}},Y="migrations.ts",y=/^[A-Za-z_]\w*$/u,G=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"]),v=/^import\s*\{\s*defineMigration\s*\}\s*from\s*["'](?:@lunora\/server|lunorash\/server)["'][^\n]*$/mu,V=r=>`import { defineMigration } from "${A(r)?.has("lunorash")??!1?"lunorash/server":"@lunora/server"}";`,X="__lunora_admin__:runMigration",rr="__lunora_admin__:migrationStatus",er="/_lunora/migrate",tr=r=>U(r.trim().toLowerCase().replaceAll(x,"-"),"-"),or=r=>r.split("-").filter(e=>e.length>0).map((e,o)=>o===0?e:e.charAt(0).toUpperCase()+e.slice(1)).join(""),nr=r=>{const e=c(r,"lunora","schema.ts");if(!u(e))return[];try{const o=new f({skipAddingFilesFromTsConfig:!0});return T(o,e).tables.map(t=>t.name)}catch{return[]}},ir=async r=>r.length>0?F("Which table does this migration iterate?",r.map(e=>({label:e,value:e}))):N("Target table for the migration: "),ar=async(r,e)=>{if(e.table!==void 0)return e.table;const o=e.promptTable??(
|
|
1
|
+
import{existsSync as u,mkdirSync as S,writeFileSync as p,mkdtempSync as C,rmSync as I,readFileSync as k}from"node:fs";import{tmpdir as M}from"node:os";import{discoverSchema as T,readPackageDependencies as A,discoverMigrations as E}from"@lunora/codegen";import{isInteractive as z,promptSelect as F,promptText as N}from"@lunora/config";import{LunoraError as $}from"@lunora/errors";import{join as c}from"@visulima/path";import{Project as f}from"ts-morph";import{u as R}from"../packem_shared/admin-url-Ca-KI3d_.mjs";import{i as q}from"../packem_shared/command-0l-ZPhIX.mjs";import{diffSnapshots as O,renderMigrationFile as D}from"../packem_shared/diffSnapshots-BbwCuhoN.mjs";import{d as L}from"../packem_shared/resolve-target-CeiNrCAx.mjs";import j from"../packem_shared/schemaIrToSnapshot-Dahp39qH.mjs";import{readAndLogBody as B}from"./runRpcCommand.mjs";import{runExportCommand as H}from"../packem_shared/runExportCommand-DFpdjDoT.mjs";import{runImportCommand as P}from"../packem_shared/DEFAULT_IMPORT_BATCH_SIZE-C4qrFAn_.mjs";const Z=".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},Q=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())}`},K=r=>{if(u(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})}},W=r=>{const e=r.cwd??process.cwd(),o=c(e,"lunora","schema.ts");if(!u(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 f({skipAddingFilesFromTsConfig:!0}),n=T(t,o),s=j(n),i=c(e,"lunora","migrations"),a=c(i,Z);let d;try{d=K(a)}catch(g){return r.logger.error(g instanceof Error?g.message:String(g)),{code:1,empty:!0,migrationFile:""}}const l=O(d,s);if(l.empty)return r.logger.info("no schema changes detected — snapshot is already up to date"),{code:0,empty:!0,migrationFile:""};const h=(r.now??(()=>new Date))(),w=J(r.name??"auto"),b=`${Q(h)}_${w}.sql`,m=c(i,b);S(i,{recursive:!0});const _=D(w,l,h.toISOString());return p(m,_,"utf8"),p(a,`${JSON.stringify(s,void 0,4)}
|
|
2
|
+
`,"utf8"),r.logger.success(`wrote ${m}`),l.unsupported.length>0&&r.logger.warn(`${String(l.unsupported.length)} unsupported diff(s) — see the comment block in ${b} and write the SQL manually`),{code:0,empty:!1,migrationFile:m}},Y="migrations.ts",y=/^[A-Za-z_]\w*$/u,G=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"]),v=/^import\s*\{\s*defineMigration\s*\}\s*from\s*["'](?:@lunora\/server|lunorash\/server)["'][^\n]*$/mu,V=r=>`import { defineMigration } from "${A(r)?.has("lunorash")??!1?"lunorash/server":"@lunora/server"}";`,X="__lunora_admin__:runMigration",rr="__lunora_admin__:migrationStatus",er="/_lunora/migrate",tr=r=>U(r.trim().toLowerCase().replaceAll(x,"-"),"-"),or=r=>r.split("-").filter(e=>e.length>0).map((e,o)=>o===0?e:e.charAt(0).toUpperCase()+e.slice(1)).join(""),nr=r=>{const e=c(r,"lunora","schema.ts");if(!u(e))return[];try{const o=new f({skipAddingFilesFromTsConfig:!0});return T(o,e).tables.map(t=>t.name)}catch{return[]}},ir=async r=>r.length>0?F("Which table does this migration iterate?",r.map(e=>({label:e,value:e}))):N("Target table for the migration: "),ar=async(r,e)=>{if(e.table!==void 0)return e.table;const o=e.promptTable??(z()?ir: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(nr(r)))?.trim();if(t===void 0||t===""){e.logger.error("no table selected — re-run with --table <table>");return}return t},sr=async r=>{const e=r.cwd??process.cwd(),o=tr(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=or(o);if(!y.test(t)||G.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 ar(e,r);if(n===void 0)return{code:1,file:""};if(!y.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 s=c(e,"lunora"),i=c(s,Y);let a=u(i)?k(i,"utf8"):"";if(a.includes(`id: "${o}"`)||new RegExp(String.raw`\bexport const ${t}\b`,"u").test(a))return r.logger.error(`a migration with id "${o}" (export \`${t}\`) already exists in ${i}`),{code:1,file:""};const d=V(e);a.trim()===""?a=`${d}
|
|
3
3
|
`:v.test(a)?a=a.replace(v,d):a=`${d}
|
|
4
4
|
${a}`;const l=`export const ${t} = defineMigration({
|
|
5
5
|
id: "${o}",
|
|
@@ -8,4 +8,4 @@ ${a}`;const l=`export const ${t} = defineMigration({
|
|
|
8
8
|
});`;return S(s,{recursive:!0}),p(i,`${a.trimEnd()}
|
|
9
9
|
|
|
10
10
|
${l}
|
|
11
|
-
`,"utf8"),r.logger.success(`scaffolded migration "${o}" in ${i}`),{code:0,file:i}},cr=(r,e)=>{const o=new f({skipAddingFilesFromTsConfig:!0});return
|
|
11
|
+
`,"utf8"),r.logger.success(`scaffolded migration "${o}" in ${i}`),{code:0,file:i}},cr=(r,e)=>{const o=new f({skipAddingFilesFromTsConfig:!0});return E(o,c(r,"lunora")).find(t=>t.id===e)?.table},dr=(r,e)=>{let o;try{o=cr(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},lr=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=dr(e,r);if(t===void 0)return;const n=R(r.url,r.logger,r.cwd);if(n===void 0)return;const s=r.fetchImpl??globalThis.fetch;if(typeof s!="function")throw new TypeError("no fetch implementation available — pass fetchImpl or run on Node >= 18");return{fetchImpl:s,requestUrl:`${n}${er}`,table:t,token:o}},ur=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},mr=async r=>{const e=lr(r);if(e===void 0)return{body:void 0,code:1,requestUrl:""};const{fetchImpl:o,requestUrl:t,table:n,token:s}=e,i=r.subcommand==="status"?rr:X,a=ur(r);r.logger.info(`POST ${t} -> ${r.subcommand} ${r.id} (table "${n}")`);const d=await o(t,{body:JSON.stringify({args:a,functionPath:i,table:n}),headers:{authorization:`Bearer ${s}`,"content-type":"application/json"},method:"POST"});return{body:await B(d,r.logger),code:d.ok?0:1,requestUrl:t}},gr=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(M(),"lunora-d1ps-")):void 0,s=r.out??c(n,"dump.ndjson");try{e.info(`Exporting .global() data from the D1 source (${o??"http://localhost:8787"}) …`);const i=await H({fetchImpl:r.fetchImpl,logger:e,out:s,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 a=await P({batchSize:r.batchSize,fetchImpl:r.fetchImpl,file:s,logger:e,prod:r.prod,token:r.toToken,url:t});return a.code!==0?{code:a.code}:(a.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(a.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})}},Ir=q(({argument:r,cwd:e,logger:o,options:t})=>{const n=r[0];if(n==="generate")return W({cwd:e,logger:o,name:r[1]??t.name});if(n==="d1-to-hyperdrive")return gr({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 s=r[1]??t.name;return s?sr({cwd:e,logger:o,name:s,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 s=r[1]??t.name;return s?mr({batchSize:t.batchSize,cwd:e,dryRun:t.dryRun===!0,id:s,logger:o,maxBatches:t.steps,prod:t.prod===!0,subcommand:n,token:t.token,url:L({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{Ir as execute,sr as runMigrateCreateCommand,mr as runMigrateDataCommand,W as runMigrateGenerateCommand,gr as runMigrateToHyperdriveCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"node:fs";import"node:path";import"node:url";import"@lunora/errors";import"@visulima/cerebro";import"@visulima/cerebro/command/completion";import"@visulima/cerebro/command/version";import{d as S,t as A,i as C,f as D}from"./cli-
|
|
1
|
+
import"node:fs";import"node:path";import"node:url";import"@lunora/errors";import"@visulima/cerebro";import"@visulima/cerebro/command/completion";import"@visulima/cerebro/command/version";import{d as S,t as A,i as C,f as D}from"./cli-C-iz79JI.mjs";import"./detect-package-manager-DXDstphE.mjs";import"./createLogger-BoSxdb2T.mjs";export{S as COMMANDS,A as REGISTERED_COMMAND_NAMES,C as VERSION,D as runCli};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import{createReadStream as U}from"node:fs";import{stat as b,readdir as K,readFile as N,realpath as R,mkdir as V,writeFile as Y}from"node:fs/promises";import{l as Q}from"./admin-token-BKmc3AUm.mjs";import{u as X}from"./admin-url-Ca-KI3d_.mjs";import{LunoraError as h}from"@lunora/errors";import{join as w,resolve as tt,sep as et}from"node:path";import{createInterface as rt}from"node:readline";import ot from"adm-zip";import{r as T,e as nt,n as it}from"./shared-BF5QIWFD.mjs";const st=t=>{const e={conflicts:0,errors:[],inserted:{},received:0,warnings:[]};let o=[],r=0;const n=s=>{for(const[a,d]of Object.entries(s.inserted??{}))e.inserted[a]=(e.inserted[a]??0)+d;e.errors.push(...s.errors??[]),e.conflicts+=s.conflicts??0,e.received+=s.received??0;for(const a of s.warnings??[])e.warnings.includes(a)||e.warnings.push(a)},i=async()=>{if(o.length===0)return;const s=o.join(`
|
|
2
|
+
`);o=[],r=0;const a=await t.fetchImpl(t.requestUrl,{body:s,headers:{authorization:`Bearer ${t.token}`,"content-type":"application/x-ndjson"},method:"POST"});if(!a.ok){const d=await a.text().catch(()=>"<no body>");throw new h("INTERNAL",`import batch failed (HTTP ${String(a.status)}): ${d}`)}n(await a.json())};return{flush:i,push:async s=>{const a=Buffer.byteLength(s)+1;o.length>0&&r+a>t.maxBatchBytes&&await i(),o.push(s),r+=a,o.length>=t.batchSize&&await i()},totals:e}},at=t=>{for(const e of t.getEntries()){const o=e.entryName.replaceAll("\\","/").split("/");if(o.length>=2&&o[o.length-2]==="_storage")return o.slice(0,-1).join("/")}return"_storage"},ct=async t=>{const e=await b(t).catch(()=>{});if(e?.isDirectory())return{kind:"directory",root:t};if(e?.isFile()&&t.toLowerCase().endsWith(".zip")){const o=new ot(t);return{kind:"zip",storagePrefix:at(o),zip:o,zipPath:t}}},lt=async t=>{const e=[];for(const o of await K(t,{withFileTypes:!0})){if(!o.isDirectory())continue;const r=w(t,o.name,"documents.jsonl");(await b(r).catch(()=>{}))?.isFile()&&e.push({file:r,table:o.name})}return e},dt=t=>{const e=[];for(const o of t.getEntries()){if(o.isDirectory)continue;const r=o.entryName.replaceAll("\\","/"),n=r.split("/");n.length>=2&&n[n.length-1]==="documents.jsonl"&&e.push({file:r,table:n[n.length-2]})}return e},ft=async t=>{const e=t.kind==="directory"?await lt(t.root):dt(t.zip);return e.length>0?e.toSorted((o,r)=>o.table.localeCompare(r.table)):void 0},P=async function*(t,e){if(t.kind==="directory"){for await(const r of rt({crlfDelay:Number.POSITIVE_INFINITY,input:U(e.file,{encoding:"utf8"})}))yield r;return}const o=t.zip.readAsText(e.file);for(const r of o.split(`
|
|
3
|
+
`))yield r},gt=async(t,e)=>{if(t.kind==="directory"){const r=await R(w(t.root,"_storage")),n=await R(tt(r,e)).catch(()=>{});if(n===void 0||n!==r&&!n.startsWith(r+et))throw new Error(`blob ${e} resolves outside the snapshot's _storage directory`);return N(n)}const o=t.zip.readFile(`${t.storagePrefix}/${e}`);if(o===null)throw new Error(`missing blob ${e} in archive`);return Buffer.from(o)},ut=async(t,e)=>t.kind==="directory"?N(e.file,"utf8"):t.zip.readAsText(e.file),L=8,ht=1e3,pt=/^[\dA-F]{64}$/i,wt=/^[\d+/A-Z]{43}=$/i,mt=t=>pt.test(t)?t.toLowerCase():wt.test(t)?Buffer.from(t,"base64").toString("hex"):void 0,yt=(t,e)=>{const o=JSON.parse(t),r=o._id;if(typeof r!="string"||r.length===0||r.includes("/")||r.includes("\\"))throw new h("INTERNAL",`${e}: \`_id\` must be a path-free non-empty string`);if(typeof o.sha256!="string")throw new h("INTERNAL",`${e}: \`sha256\` is missing — re-export with \`npx convex export --include-file-storage\``);const n=mt(o.sha256);if(n===void 0)throw new h("INTERNAL",`${e}: \`sha256\` is neither base16 nor base64 SHA-256 (${o.sha256})`);if(typeof o.size!="number"||!Number.isInteger(o.size)||o.size<0)throw new h("INTERNAL",`${e}: \`size\` must be a non-negative integer`);return{contentType:typeof o.contentType=="string"?o.contentType:void 0,id:r,sha256:n,size:o.size}},I=async(t,e,o)=>{const r=[];try{const n=await ut(t,e);for(const[i,s]of n.split(`
|
|
4
|
+
`).entries()){const a=s.trim();a.length>0&&r.push(yt(a,`_storage/documents.jsonl line ${String(i+1)}`))}}catch(n){const i=n instanceof Error?n.message:String(n);throw o.error(`failed to read _storage metadata: ${i}`),n}return r},J=32*1048576,_=async(t,e)=>{const o=[];let r;do{const n=`${t.baseUrl}${T}?prefix=${encodeURIComponent(e)}&limit=${String(ht)}${r===void 0?"":`&cursor=${encodeURIComponent(r)}`}`,i=await t.fetchImpl(n,{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(!i.ok){const a=await i.text().catch(()=>"<no body>");throw new h("INTERNAL",`storage list failed (HTTP ${String(i.status)}): ${a}`)}const s=await i.json();o.push(...s.objects??[]),r=s.truncated===!0?s.cursor:void 0}while(r!==void 0);return o},$t=async(t,e,o,r)=>{const n=`${t.baseUrl}${T}?key=${encodeURIComponent(e)}&expectedSha256=${r.sha256}&expectedSize=${String(r.size)}`,i=await t.fetchImpl(n,{body:new Uint8Array(o),headers:{authorization:`Bearer ${t.token}`,"content-type":r.contentType??"application/octet-stream"},method:"PUT"});if(!i.ok){const a=await i.text().catch(()=>"<no body>");throw new h("INTERNAL",`blob upload failed (HTTP ${String(i.status)}): ${a}`)}const s=await i.json();if(s.sha256!==r.sha256)throw new h("INTERNAL",`blob upload verification failed: expected ${r.sha256}, got ${s.sha256??"none"}`);return e},bt=async(t,e)=>(await t.fetchImpl(`${t.baseUrl}${T}?key=${encodeURIComponent(e)}`,{headers:{authorization:`Bearer ${t.token}`},method:"DELETE"}).catch(()=>{}))?.ok===!0,vt=async(t,e,o,r,n)=>{const i=`${t.baseUrl}${nt}?key=${encodeURIComponent(e)}&method=PUT&contentType=${encodeURIComponent(r.contentType??"application/octet-stream")}`,s=await t.fetchImpl(i,{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(!s.ok){const u=await s.text().catch(()=>"<no body>");throw new h("INTERNAL",`blob ${e} is ${String(r.size)} bytes, above the ${String(J)}-byte verified-upload cap, and no signed PUT URL could be minted (HTTP ${String(s.status)}): ${u}`)}const{url:a}=await s.json(),d=await t.fetchImpl(a,{body:new Uint8Array(o),headers:{"content-type":r.contentType??"application/octet-stream"},method:"PUT"});if(!d.ok){const u=await d.text().catch(()=>"<no body>");throw new h("INTERNAL",`signed PUT failed (HTTP ${String(d.status)}): ${u}`)}const f=(await _(t,e)).find(u=>u.key===e);if(f===void 0)throw new h("INTERNAL",`post-upload verification failed: blob not found at key ${e}`);const l=f.size!==void 0&&f.size!==r.size,c=f.sha256!==void 0&&f.sha256.toLowerCase()!==r.sha256;if(l||c){const u=await bt(t,e);throw new h("INTERNAL",`post-upload verification failed: expected sha256=${r.sha256} size=${String(r.size)}, got sha256=${f.sha256??"none"} size=${String(f.size??"none")}${u?" (the object was removed)":` — AND the object could not be removed: delete ${e} by hand before re-running, or the next run will treat it as already migrated`}`)}const g=[f.size===void 0?"size":void 0,f.sha256===void 0?"sha256":void 0].filter(Boolean);return g.length>0&&n.warn(`blob ${e} went through the signed-PUT path and the host reports no ${g.join(" or ")} for it — that much of the write is unverified`),e},St=async(t,e,o,r,n)=>{const i=`${r}${o.sha256}`;if(e.length!==o.size)throw new h("INTERNAL",`blob ${o.id} is ${String(e.length)} bytes on disk but the export declares ${String(o.size)}`);return e.length<=J?$t(t,i,e,o):vt(t,i,e,o,n)},xt=async(t,e,o,r,n)=>{const i=await I(e,o,n),s=new Map,a=await _(t,r),d=new Map(a.map(c=>[c.key,c])),f=[];for(const c of i){const g=`${r}${c.sha256}`;d.get(g)?.size===c.size?s.set(c.id,g):f.push(c)}n.info(`migrating ${String(f.length)} storage blobs${s.size>0?` (${String(s.size)} already present)`:""}...`);const l=async c=>{try{const g=await gt(e,c.id);s.set(c.id,await St(t,g,c,r,n))}catch(g){const u=g instanceof Error?g.message:String(g);throw n.error(`failed to upload blob ${c.id}: ${u}`),g}};for(let c=0;c<f.length;c+=L){const g=(await Promise.allSettled(f.slice(c,c+L).map(u=>l(u)))).find(u=>u.status==="rejected");if(g!==void 0)throw g.reason}return n.success(`migrated ${String(f.length)} storage blobs`),s},m="_storage",B=t=>t.startsWith("_");async function*Nt(t,e,o){let r=0;for await(const n of P(t,e)){const i=n.trim();if(r+=1,i.length===0)continue;let s;try{s=JSON.parse(i)}catch(a){throw new h("INTERNAL",`${e.table}/documents.jsonl line ${String(r)}: invalid JSON — ${a instanceof Error?a.message:String(a)}`,{cause:a})}o.set(e.table,(o.get(e.table)??0)+1),yield`${JSON.stringify({doc:s,table:e.table})}
|
|
5
|
+
`}}async function*Tt(t,e,o,r,n){for(const i of e){if(B(i.table)){i.table===m&&!r&&o.warn(`skipping "${m}" — those rows describe stored files, and their blobs were not migrated. Re-run with --with-storage to upload them and rewrite the references.`);continue}n.has(i.table)||n.set(i.table,0),yield*Nt(t,i,n)}}const It=async t=>{if(!await b(t.file).then(()=>!0,()=>!1))return!1;for(const[e,o]of[["--scan",t.scan],["--verify",t.verify],["--with-storage",t.withStorage]])if(o===!0)return t.logger.error(`${e} requires a Convex export directory or .zip snapshot — ${t.file} is not one.`),!0;return!1},kt=async t=>{const e=await ct(t.file),o=e===void 0?void 0:await ft(e);if(e!==void 0&&o===void 0)return t.logger.error(`${t.file} is a ${e.kind==="zip"?".zip":"directory"} but holds no <table>/documents.jsonl — expected a \`npx convex export --path\` snapshot, or pass an NDJSON file.`),{kind:"invalid"};if(e===void 0||o===void 0)return await It(t)?{kind:"invalid"}:{kind:"ndjson"};if(t.table!==void 0)return t.logger.error("--table cannot be combined with a Convex export directory — each row's table comes from its source directory."),{kind:"invalid"};const r=o.find(n=>n.table===m);if(t.verify===!0&&t.withStorage!==!0&&r!==void 0){const n=await I(e,r,t.logger);if(n.length>0)return t.logger.error(`--verify on an export carrying ${String(n.length)} stored file(s) requires --with-storage — otherwise every file reference stays unmigrated and only row counts would be checked.`),{kind:"invalid"}}return{kind:"convex",snapshot:e,tables:o}},$=w("lunora","import-convex.json"),Et=(t,e)=>{if(t===null||typeof t!="object"||Array.isArray(t))throw new h("INTERNAL",`${e}: expected a JSON object`);const o=t;if(o.keyPrefix!==void 0&&typeof o.keyPrefix!="string")throw new h("INTERNAL",`${e}: \`keyPrefix\` must be a string`);const r=o.storageColumns;if(r!==void 0){if(r===null||typeof r!="object"||Array.isArray(r))throw new h("INTERNAL",`${e}: \`storageColumns\` must be an object of table → column names`);for(const[n,i]of Object.entries(r))if(!Array.isArray(i)||i.some(s=>typeof s!="string"))throw new h("INTERNAL",`${e}: \`storageColumns.${n}\` must be an array of column names`)}return{keyPrefix:o.keyPrefix,storageColumns:r}},zt=async(t,e)=>{const o=w(t,$);let r;try{r=await N(o,"utf8")}catch(i){if(i.code==="ENOENT"){e.info(`no ${$} found — rewriting only self-describing { $storage } refs (run with --scan to generate one)`);return}throw i}let n;try{n=JSON.parse(r)}catch(i){throw new h("INTERNAL",`${o}: invalid JSON — ${i instanceof Error?i.message:String(i)}`,{cause:i})}return Et(n,o)},At=(t,e,o,r)=>{const n=[],i=[];let s=0;const a=l=>r?.[o]?.includes(l)===!0,d=(l,c)=>{if(Array.isArray(l))return l.map(g=>d(g,c));if(l!==null&&typeof l=="object"){const g=l;if(typeof g.$storage=="string"){const u=g.$storage,p=e.get(u);return p===void 0?(i.push({column:c,storageId:u,table:o}),l):(s+=1,p)}return Object.fromEntries(Object.entries(g).map(([u,p])=>[u,d(p,c)]))}return typeof l=="string"&&e.has(l)?a(c)?(s+=1,e.get(l)??l):(n.push({column:c,storageId:l,table:o}),l):l},f=Object.fromEntries(Object.entries(t).map(([l,c])=>[l,d(c,l)]));return{ambiguous:n,document:f,rewritten:s,unmigrated:i}},jt=(t,e,o)=>{try{return JSON.parse(t)}catch(r){throw new h("INTERNAL",`${e}/documents.jsonl line ${String(o)}: invalid JSON — ${r instanceof Error?r.message:String(r)}`,{cause:r})}},x=(t,e)=>typeof t=="string"?e.has(t):Array.isArray(t)?t.some(o=>x(o,e)):t!==null&&typeof t=="object"?typeof t.$storage=="string"?!1:Object.values(t).some(o=>x(o,e)):!1,Ot=async(t,e,o)=>{const r=[];let n=0;for await(const i of P(t,e)){const s=i.trim();if(n+=1,s.length!==0)for(const[a,d]of Object.entries(jt(s,e.table,n)))x(d,o)&&!r.includes(a)&&r.push(a)}return r},Rt=async(t,e,o)=>{const r={};for(const n of e){if(B(n.table))continue;const i=await Ot(t,n,o);i.length>0&&(r[n.table]=i)}return r},Lt=async(t,e,o)=>{const r=w(e,$),n=`${JSON.stringify(t,void 0,4)}
|
|
6
|
+
`;await V(w(e,"lunora"),{recursive:!0});try{await Y(r,n,{encoding:"utf8",flag:"wx"}),o.success(`wrote candidate mapping to ${r} — review it, then re-run without --scan`)}catch(i){if(i.code!=="EEXIST")throw i;o.warn(`${r} already exists — leaving it untouched. Candidate mapping:`),o.info(n)}},Ct=async(t,e,o,r)=>{const n=e.find(d=>d.table===m);if(n===void 0){r.error("no `_storage` table in this export — re-export with `npx convex export --include-file-storage`");return}const i=await I(t,n,r),s=new Set(i.map(d=>d.id));r.info(`found ${String(s.size)} storage ids`);const a={keyPrefix:"",storageColumns:await Rt(t,e,s)};return await Lt(a,o,r),a},Ut=t=>{const{report:e,storageColumns:o,storageIdMap:r,table:n}=t,i=(a,d)=>{let f;try{f=JSON.parse(a)}catch(l){const c=l instanceof Error?l.message:String(l);throw new h("INTERNAL",`invalid JSON on line ${String(d)}: ${c}`,{cause:l})}return JSON.stringify({doc:f,table:n})},s=(a,d,f)=>{const l=JSON.parse(a);if(typeof l.table!="string")throw new h("INTERNAL",`line ${String(d)}: import envelope is missing a string \`table\``);if(l.doc!==null&&typeof l.doc=="object"&&!Array.isArray(l.doc)){const c=At(l.doc,f,l.table,o);l.doc=c.document,e.rewritten+=c.rewritten,e.ambiguous.push(...c.ambiguous),e.unmigrated.push(...c.unmigrated)}return JSON.stringify(l)};return(a,d)=>{const f=a.trim();if(f.length!==0)return n!==void 0?i(f,d):r===void 0?f:s(f,d,r)}},S=20,Pt=(t,e,o)=>{let r=0;if(o.conflicts===0)for(const[n,i]of e){const s=o.inserted[n]??0;s<i&&(r+=1,t.error(`verify: ${n} inserted ${String(s)} of ${String(i)} source rows (${String(i-s)} missing)`))}else{const n=[...e.values()].reduce((s,a)=>s+a,0),i=Object.values(o.inserted).reduce((s,a)=>s+a,0)+o.conflicts;i<n&&(r+=1,t.error(`verify: ${String(i)} of ${String(n)} source rows accounted for across all tables (${String(n-i)} missing; ${String(o.conflicts)} already present)`))}return r>0?t.error(`verify: ${String(r)} row-parity check(s) failed`):t.success("verify: all source rows accounted for"),r},C=(t,e,o)=>{const r=new Set;for(const n of e){const i=`${n.table} ${n.column} ${n.storageId}`;r.has(i)||(r.add(i),r.size<=S&&t.warn(o(n)))}r.size>S&&t.warn(`… and ${String(r.size-S)} more`)},Jt=(t,e,o)=>(t.info(`storage refs: ${String(e.rewritten)} rewritten, ${String(e.unmigrated.length)} unmigrated, ${String(e.ambiguous.length)} ambiguous`),C(t,e.unmigrated,r=>`unmigrated storage reference ${r.table}.${r.column}: ${r.storageId} has no exported blob — re-export with \`npx convex export --include-file-storage\``),C(t,e.ambiguous,r=>`unrewritten storage id in ${r.table}.${r.column}: ${r.storageId} — if that column holds storage references, add it to ${$} and re-import`),o&&e.unmigrated.length>0?(t.error(`verify: ${String(e.unmigrated.length)} storage reference(s) resolved to no migrated blob`),!0):!1),_t=500,Bt=9e5,Mt=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 e=X(t.url,t.logger,t.cwd);if(e===void 0)return;const{token:o}=Q({cwd:t.cwd??process.cwd(),token:t.token,url:e});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{const n=await b(t.file);if(!n.isFile()&&!n.isDirectory()){t.logger.error(`not a file or directory: ${t.file}`);return}}catch(n){const i=n instanceof Error?n.message:String(n);t.logger.error(`failed to stat ${t.file}: ${i}`);return}const r=t.fetchImpl??globalThis.fetch;if(typeof r!="function")throw new TypeError("no fetch implementation available — pass fetchImpl or run on Node >= 18");return{baseUrl:e,fetchImpl:r,requestUrl:`${e}${it}`,token:o}},Dt=(t,e,o)=>({conflicts:t.conflicts,errors:t.errors,inserted:t.inserted,received:t.received,...e===void 0?{}:{storage:{ambiguous:o.ambiguous,blobs:e.size,rewritten:o.rewritten,unmigrated:o.unmigrated}},...t.warnings.length>0?{warnings:t.warnings}:{}}),Ft=async(t,e,o,r)=>{let n="",i=0;const s=async a=>{i+=1;const d=e(a,i);d!==void 0&&await o.push(d)};try{for await(const a of t){n+=typeof a=="string"?a:a.toString("utf8");let d=n.indexOf(`
|
|
7
|
+
`);for(;d!==-1;)await s(n.slice(0,d)),n=n.slice(d+1),d=n.indexOf(`
|
|
8
|
+
`)}n.length>0&&await s(n),await o.flush();return}catch(a){return r.error(`import failed part-way through: ${a instanceof Error?a.message:String(a)}`),r.error("the rows below had already been written — re-run the same command to resume (existing rows conflict rather than duplicate)"),a}},qt=async(t,e,o,r)=>{const n=await zt(o,r),i=e.tables.find(a=>a.table===m);if(i===void 0){r.error("--with-storage requires a Convex export with a `_storage` metadata table — re-export with `npx convex export --include-file-storage`.");return}const s=await xt(t,e.snapshot,i,n?.keyPrefix??"",r);return r.info(`storage map: ${String(s.size)} blobs mapped`),{mapping:n,storageIdMap:s}},Ht=(t,e)=>{for(const r of e.warnings)t.warn(r);const o=e.received-e.insertedTotal-e.conflicts-e.errorCount;o>0&&t.warn(`${String(o)} of ${String(e.received)} rows were neither inserted, conflicted, nor reported as errors`),t.success(`imported ${String(e.insertedTotal)} of ${String(e.received)} rows (${String(e.conflicts)} conflicts, ${String(e.errorCount)} errors)`)},ee=async t=>{const e=await kt(t);if(e.kind==="invalid")return{body:void 0,code:1,inserted:0};const o=t.cwd??process.cwd();if(t.scan===!0&&e.kind==="convex"){const y=await Ct(e.snapshot,e.tables,o,t.logger);return{body:y,code:y===void 0?1:0,inserted:0}}const r=await Mt(t);if(r===void 0)return{body:void 0,code:1,inserted:0};const{baseUrl:n,fetchImpl:i,requestUrl:s,token:a}=r,d=t.batchSize??_t,f=t.withStorage===!0&&e.kind==="convex"?await qt({baseUrl:n,fetchImpl:i,token:a},e,o,t.logger):{mapping:void 0,storageIdMap:void 0};if(f===void 0)return{body:void 0,code:1,inserted:0};const{mapping:l,storageIdMap:c}=f,g=l?.storageColumns,u={ambiguous:[],rewritten:0,unmigrated:[]};t.logger.info(e.kind==="convex"?`POST ${s} -> import Convex export ${t.file} (${String(e.tables.length)} tables)`:`POST ${s} -> import ${t.file}`);const p=new Map,M=e.kind==="convex"?Tt(e.snapshot,e.tables,t.logger,c!==void 0,p):U(t.file,{encoding:"utf8"}),v=st({batchSize:d,fetchImpl:i,maxBatchBytes:Bt,requestUrl:s,token:a}),D=Ut({report:u,storageColumns:g,storageIdMap:c,table:t.table}),k=await Ft(M,D,v,t.logger),{conflicts:E,errors:z,inserted:A,received:F,warnings:q}=v.totals,H=t.verify===!0&&k===void 0?Pt(t.logger,p,{conflicts:E,inserted:A}):0,W=c!==void 0&&Jt(t.logger,u,t.verify===!0),j=Object.values(A).reduce((y,G)=>y+G,0),O=Dt(v.totals,c,u);t.logger.info(JSON.stringify(O,void 0,2)),Ht(t.logger,{conflicts:E,errorCount:z.length,insertedTotal:j,received:F,warnings:q});const Z=k!==void 0||z.length>0||H>0||W;return{body:O,code:Z?1:0,inserted:j}};export{_t as DEFAULT_IMPORT_BATCH_SIZE,ee as runImportCommand};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{mkdirSync as B,readFileSync as w,lstatSync as A,writeFileSync as D}from"node:fs";import{join as u,dirname as y}from"node:path";import{fileURLToPath as L}from"node:url";import{resolveHint as j,isLunoraError as k,flattenHint as E,findSolutionByMessage as C}from"@lunora/errors";import{createCerebro as I}from"@visulima/cerebro";import $ from"@visulima/cerebro/command/completion";import _ from"@visulima/cerebro/command/version";import{p}from"./api-spec-BENwiyUa.mjs";import{g as s}from"./deploy-target-Dvr9vxpR.mjs";import{P,l as T}from"./detect-package-manager-DXDstphE.mjs";import{createLogger as S}from"./createLogger-BoSxdb2T.mjs";import{VisulimaError as U,renderError as M}from"@visulima/error";import{homedir as W}from"node:os";const J={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}]},f="lunora.advisor.map.json",K={description:"Score your app's advisor findings into a health map, and gate CI on it",examples:[["lunora advisor","Score the app and write lunora.advisor.map.json"],["lunora advisor --all","Show every procedure as a check matrix"],["lunora advisor --entry messages#sendMessage","Inspect one procedure"],["lunora advisor --min-score 80","Exit non-zero when the score drops below 80"],["lunora advisor --baseline","Fail on any regression against the committed map"]],group:"Develop",loader:()=>import("../packem_chunks/handler21.mjs").then(e=>({default:e.execute})),name:"advisor",options:[{description:"Show every procedure as a check matrix, not just the ones with findings",name:"all",type:Boolean},{description:`Compare against a committed map and fail on regression (default ${f})`,name:"baseline",type:String},{description:"Inspect a single procedure by `file#exportName`",name:"entry",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Exit non-zero when the global score is below this value (0-100)",name:"min-score",type:String},{description:`Where to write the map (default ${f})`,name:"out",type:String},{description:"Write the map artifact to disk (default true; use --no-write to skip)",name:"no-write",type:Boolean}]},F={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}]},q={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}]},H={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"],["lunora build --emit-bindings bindings.json","Also write what the bundle needs provisioned, for an external deployer"]],group:"Deploy",loader:()=>import("../packem_chunks/handler4.mjs").then(e=>({default:e.execute})),name:"build",options:[{description:`Which API spec(s) to emit: ${p} (default openapi)`,name:"api-spec",type:String},{description:"Write a JSON manifest of the bindings + crons the bundle needs to this path, for an IaC program to consume",name:"emit-bindings",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},s]},z={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: ${p} (default openapi)`,name:"api-spec",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Fail on ERROR-level advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail on ERROR-level advisories (the gate defaults to on in CI, off locally)",name:"no-strict-advisories",type:Boolean},s]},V={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}]},G={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: ${p} (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:"Fail the deploy on ERROR-level codegen advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail the deploy on ERROR-level codegen advisories (the gate defaults to on in CI, off locally). Never downgrades platform diagnostics.",name:"no-strict-advisories",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},s,{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}]},Y={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: ${p} (default openapi)`,name:"api-spec",type:String},{description:"Studio server port (default 6173)",name:"port",type:Number},s,{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 spawn wrangler dev — an external task runner owns the worker; codegen watch + studio still run",name:"no-worker",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}]},X={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"},Z={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:[]},ee={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 this Cloudflare environment for `push`/`diff` (passes --env <name> to wrangler)",name:"env",type:String},{description:"Alias for --env production",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}]},te={description:"Run every *.eval.ts under evals/ via @lunora/testing's evaluate/agentHarness — no live worker needed",examples:[["lunora eval","Run every eval under evals/, print the aggregate table"],["lunora eval --threshold 0.8","Non-zero exit if any eval's average score falls below 0.8"],["lunora eval --dir evals/support --format json","Run a subset and emit a machine-readable result"]],group:"Develop",loader:()=>import("../packem_chunks/handler23.mjs").then(e=>({default:e.execute})),name:"eval",options:[{description:"Directory to discover *.eval.ts files under (default evals/)",name:"dir",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Score gate every eval's average must meet ([0,1]); a per-eval `threshold` export wins over this for that eval",name:"threshold",type:Number}]},re={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}]},oe={argument:{description:"Source NDJSON file, or a `npx convex export --path <dir>` directory",name:"file",type:String},description:"Bulk-insert rows from an NDJSON file — or a Convex export directory — via the worker's admin endpoint",examples:[["lunora import backup.ndjson","Bulk-insert rows from an NDJSON file"],["lunora import ./convex-export","Import a `npx convex export --path` directory (ids are preserved, so no remapping)"],["lunora import ./convex-export --with-storage","Also migrate blobs (verified sha256 upload) + `{ $storage }` refs"],["lunora import ./convex-export --scan","Write a candidate `lunora/import-convex.json` storage-column mapping (imports nothing)"],["lunora import ./snapshot.zip --with-storage --verify","Import a `npx convex export --path` zip snapshot with blob + row-parity checks"]],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:"Also migrate Convex `_storage` blobs (verified upload)",name:"with-storage",type:Boolean},{description:"Write a candidate `lunora/import-convex.json` storage-column mapping and exit",name:"scan",type:Boolean},{description:"Verify row parity + dangling-storage after import (non-zero exit on mismatch)",name:"verify",type:Boolean},{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}]},ne={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}]},ae={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}]},ie={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}]},se={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/handler24.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}]},le={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}]},pe={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/handler22.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},s,{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}]},de={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/handler25.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}]},ce={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}]},ue={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: ${p} (default openapi)`,name:"api-spec",type:String},s,{description:"Re-bless the committed schema baseline (lunora/.lunora-schema.json) with the current shape",name:"update-schema-baseline",type:Boolean}]},me={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}]},ge={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}]},he={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)"],["lunora rules install --dir packages/app","Install into a specific root instead of the workspace root"]],group:"Project",loader:()=>import("../packem_chunks/handler17.mjs").then(e=>({default:e.execute})),name:"rules",options:[{description:"Install/check root (default: the detected workspace root, not the current directory)",name:"dir",type:String},{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}]},ye={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}]},fe={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}]},ve={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: ${p} (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},s]},be={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}]},we={filterStacktrace:()=>!1,hideErrorCodeView:!0},ke=(e,t={})=>{const r=e instanceof Error?e.message:String(e),o=j(k(e)?{code:e.code,hint:e.hint,message:r}:r),n=new U({hint:o===void 0?void 0:E(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="",M(n,we)},Se=(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,d=e[o-1]===t[a-1]?0:1;r[a]=Math.min((r[a-1]??0)+1,i+1,n+d),n=i}}return r[t.length]??0},xe=(e,t)=>{let r,o=Number.POSITIVE_INFINITY;for(const a of t){const i=Se(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},Re=e=>`https://registry.npmjs.org/@lunora/cli/${e}`,Oe=1440*60*1e3,Ne=1500,Be="0.0.0",Ae=/^v/u,De=new Set(["alpha","beta","next"]),m=e=>{const t=e.trim().replace(Ae,""),r=t.indexOf("-");return r===-1?{core:t,prerelease:""}:{core:t.slice(0,r),prerelease:t.slice(r+1)}},v=e=>{const[t,r,o]=m(e).core.split(".").map(n=>{const a=Number.parseInt(n,10);return Number.isFinite(a)?a:0});return[t??0,r??0,o??0]},Le=(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},je=(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 Le(a,i)}return 0},Ee=(e,t)=>{const r=v(e),o=v(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 je(m(e).prerelease,m(t).prerelease)},Ce=e=>{const t=m(e).prerelease.split(".")[0]??"";return De.has(t)?t:"latest"},Ie=(e,t)=>Ee(t,e)>0,$e=(e,t,r)=>t-e<r,_e=(e,t,r="latest",o)=>{const n=`Update available for @lunora/cli: ${e} → ${t}`;if(o===void 0)return`${n} — add @lunora/cli@${r} as a dev dependency to update`;const{args:a,command:i}=P(o,[`@lunora/cli@${r}`],{dev:!0});return`${n} — run \`${i} ${a.join(" ")}\``},x=e=>u(e,"lunora-cli-update.json"),Pe=e=>{const t=e.XDG_CACHE_HOME&&e.XDG_CACHE_HOME.length>0?e.XDG_CACHE_HOME:u(W(),".cache"),r=u(t,"lunora");try{B(r,{mode:448,recursive:!0})}catch{}return r},Te=e=>{try{const t=JSON.parse(w(x(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{}},b=(e,t)=>{try{const r=x(e);try{if(A(r).isSymbolicLink())return}catch{}D(r,`${JSON.stringify(t)}
|
|
3
|
+
`,"utf8")}catch{}},Ue=async(e,t)=>{try{const r=await e(Re(t),{signal:AbortSignal.timeout(Ne)});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}},Me=(e,t,r)=>e===Be||!r||t.CI!==void 0||t.LUNORA_NO_UPDATE_NOTIFIER!==void 0,We=async e=>{const t=e.env??process.env,r=e.isTTY??process.stdout.isTTY;if(Me(e.current,t,r))return;const o=e.cacheDir??Pe(t),n=(e.now??Date.now)(),a=e.ttlMs??Oe,i=Ce(e.current),d=Te(o),N=d?.tag??"latest",g=d!==void 0&&N===i?d:void 0;let c=g?.latest;if(g===void 0||!$e(g.checkedAt,n,a)){const h=await Ue(e.fetchImpl??globalThis.fetch,i);h===void 0?b(o,{checkedAt:n,latest:e.current,tag:i}):(c=h,b(o,{checkedAt:n,latest:h,tag:i}))}c!==void 0&&Ie(e.current,c)&&e.logger.warn(_e(e.current,c,i,e.manager))},Je=["init","add","dev","codegen","build","deploy","containers","prepare","link","deployments","logs","run","insights","reset","migrate","export","import","seed","backup","eval","verify","info","doctor","env","analyze","view","docs","registry","rules","mcp"],Ke=8,Fe=()=>{try{let e=y(L(import.meta.url));for(let t=0;t<Ke;t+=1){try{const o=JSON.parse(w(u(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=y(e);if(r===e)break;e=r}}catch{}return"0.0.0"},R=Fe(),qe=[ae,J,Q,z,K,H,G,V,ue,le,Y,pe,ye,ie,ge,ce,re,oe,fe,se,q,te,ve,ne,Z,ee,F,be,X,me,he,de],O=[...qe,_,$],dt=O.map(e=>e.name),l=e=>e.replaceAll("{",String.raw`\{`).replaceAll("}",String.raw`\}`),He=e=>e.every(t=>typeof t=="string")?e.map(t=>l(t)):e.map(t=>typeof t=="string"?[l(t)]:t.map(r=>l(r))),ze=e=>({...e,...e.argument===void 0?{}:{argument:{...e.argument,description:l(e.argument.description??"")}},...e.description===void 0?{}:{description:l(e.description)},...e.examples===void 0?{}:{examples:He(e.examples)},...e.options===void 0?{}:{options:e.options.map(t=>({...t,description:l(t.description??"")}))}}),Ve=e=>{const t={value:0},r=I("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:R});for(const o of O)r.addCommand(ze(o));return{cli:r,exitCode:t}},Ge=/Command "(?<name>[^"]+)" not found/u,Ye=e=>{const t=S(),r=e instanceof Error?e.message:String(e),o=Ge.exec(r);if(!o?.groups){k(e)||C(r)!==void 0?t.error(ke(e)):t.error(r);return}const n=o.groups.name??"",a=xe(n,Je);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.")},ct=async(e={})=>{const{cli:t,exitCode:r}=Ve(e);try{await t.run({shouldExitProcess:!1})}catch(n){return Ye(n),1}let o;try{o=T(process.cwd())}catch{}return await We({current:R,logger:S(),manager:o}),r.value};export{Je as d,ct as f,R as i,f as o,dt as t};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{createWriteStream as m}from"node:fs";import{unlink as g}from"node:fs/promises";import{l as y}from"./admin-token-BKmc3AUm.mjs";import{u as v}from"./admin-url-Ca-KI3d_.mjs";import{t as h}from"./shared-BF5QIWFD.mjs";const b=o=>{if(o===void 0)return;const t=o.split(",").map(e=>e.trim()).filter(e=>e.length>0);return t.length>0?t:void 0},w=async(o,t)=>{o.write(t)||await new Promise((e,a)=>{let i=r=>{};const s=()=>{o.removeListener("error",i),e()};i=r=>{o.removeListener("drain",s),a(r)},o.once("drain",s),o.once("error",i)})},$=async(o,t)=>{const e=o.getReader(),a=new TextDecoder;let i=0,s=0,r="",n=!1;try{for(;!n;){const c=await e.read();if(n=c.done,c.value===void 0)continue;i+=c.value.length,r+=a.decode(c.value,{stream:!0});let d=r.indexOf(`
|
|
2
|
+
`);for(;d!==-1;){s+=1;const l=`${r.slice(0,d)}
|
|
3
|
+
`;await w(t,l),r=r.slice(d+1),d=r.indexOf(`
|
|
4
|
+
`)}}return r.length>0&&(s+=1,await w(t,`${r}
|
|
5
|
+
`)),{bytes:i,rows:s}}finally{e.releaseLock()}},p=async(o,t)=>{if(t!==void 0){o.destroy();try{await g(t)}catch{}}},x=async(o,t,e)=>{await new Promise((i,s)=>{o.end(r=>{const n=r??e();n===void 0?i():s(n)})});const a=e();if(a!==void 0)throw await p(o,t),a},P=async o=>{if(o.prod&&o.url===void 0)return o.logger.error("--prod requires an explicit --url (refusing to export from the implicit localhost worker)"),{bytes:0,code:1,rows:0};const t=v(o.url,o.logger,o.cwd);if(t===void 0)return{bytes:0,code:1,rows:0};const{token:e}=y({cwd:o.cwd??process.cwd(),token:o.token,url:t});if(!e)return o.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 a=`${t}${h}`,i=b(o.tables),s=o.fetchImpl??globalThis.fetch;if(typeof s!="function")throw new TypeError("no fetch implementation available — pass fetchImpl or run on Node >= 18");o.logger.info(`POST ${a} -> export${i?` (tables: ${i.join(",")})`:""}`);const r=await s(a,{body:JSON.stringify(i?{tables:i}:{}),headers:{authorization:`Bearer ${e}`,"content-type":"application/json"},method:"POST"});if(!r.ok){const u=await r.text();return o.logger.error(`export failed: HTTP ${String(r.status)}: ${u}`),{bytes:0,code:1,rows:0}}if(!r.body)return o.logger.error("export response carried no body"),{bytes:0,code:1,rows:0};const n=o.out===void 0||o.out==="-"?void 0:o.out,c=n===void 0?process.stdout:m(n,{encoding:"utf8"});let d;n!==void 0&&c.on("error",u=>{d??=u});let l,f;try{({bytes:l,rows:f}=await $(r.body,c))}catch(u){throw await p(c,n),u}return n!==void 0&&(await x(c,n,()=>d),o.logger.success(`wrote ${String(f)} rows to ${n} (${String(l)} bytes)`)),{bytes:l,code:0,rows:f}};export{P as runExportCommand};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const r="/_lunora/admin/export",a="/_lunora/admin/import",n="/_lunora/admin/storage",o="/_lunora/admin/storage/url";export{o as e,a as n,n as r,r as t};
|
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.147",
|
|
4
4
|
"description": "The Lunora CLI: init, dev, deploy, codegen, migrate, seed, doctor, insights, logs, registry, and the rest of the project commands",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agent-skills",
|
|
@@ -52,16 +52,16 @@
|
|
|
52
52
|
},
|
|
53
53
|
"dependencies": {
|
|
54
54
|
"@bomb.sh/tab": "0.0.21",
|
|
55
|
-
"@lunora/advisor": "1.0.0-alpha.
|
|
56
|
-
"@lunora/bindings": "1.0.0-alpha.
|
|
57
|
-
"@lunora/codegen": "1.0.0-alpha.
|
|
58
|
-
"@lunora/config": "1.0.0-alpha.
|
|
59
|
-
"@lunora/container": "1.0.0-alpha.
|
|
60
|
-
"@lunora/d1": "1.0.0-alpha.
|
|
61
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
62
|
-
"@lunora/mcp": "1.0.0-alpha.
|
|
63
|
-
"@lunora/runtime": "1.0.0-alpha.
|
|
64
|
-
"@lunora/seed": "1.0.0-alpha.
|
|
55
|
+
"@lunora/advisor": "1.0.0-alpha.68",
|
|
56
|
+
"@lunora/bindings": "1.0.0-alpha.21",
|
|
57
|
+
"@lunora/codegen": "1.0.0-alpha.93",
|
|
58
|
+
"@lunora/config": "1.0.0-alpha.122",
|
|
59
|
+
"@lunora/container": "1.0.0-alpha.24",
|
|
60
|
+
"@lunora/d1": "1.0.0-alpha.65",
|
|
61
|
+
"@lunora/errors": "1.0.0-alpha.15",
|
|
62
|
+
"@lunora/mcp": "1.0.0-alpha.58",
|
|
63
|
+
"@lunora/runtime": "1.0.0-alpha.54",
|
|
64
|
+
"@lunora/seed": "1.0.0-alpha.63",
|
|
65
65
|
"@visulima/cerebro": "3.0.0",
|
|
66
66
|
"@visulima/error": "6.0.0",
|
|
67
67
|
"@visulima/fs": "5.0.5",
|
|
@@ -70,6 +70,7 @@
|
|
|
70
70
|
"@visulima/path": "3.0.0",
|
|
71
71
|
"@visulima/spinner": "1.0.0",
|
|
72
72
|
"@visulima/tui": "1.0.5",
|
|
73
|
+
"adm-zip": "0.6.0",
|
|
73
74
|
"cfonts": "^3.3.1",
|
|
74
75
|
"giget": "3.3.1",
|
|
75
76
|
"jsonc-parser": "^3.3.1",
|
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
import{createWriteStream as D,createReadStream as E}from"node:fs";import{unlink as A,stat as v,readdir as J}from"node:fs/promises";import{join as R}from"node:path";import{createInterface as L}from"node:readline";import{LunoraError as O}from"@lunora/errors";import{l as j}from"./admin-token-BKmc3AUm.mjs";import{u as P}from"./admin-url-Ca-KI3d_.mjs";const q="/_lunora/admin/export",U="/_lunora/admin/import",F=500,z=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},k=async(t,r)=>{t.write(r)||await new Promise(o=>{t.once("drain",o)})},B=async(t,r)=>{const o=t.getReader(),e=new TextDecoder;let s=0,f=0,i="",c=!1;try{for(;!c;){const u=await o.read();if(c=u.done,u.value===void 0)continue;s+=u.value.length,i+=e.decode(u.value,{stream:!0});let l=i.indexOf(`
|
|
2
|
-
`);for(;l!==-1;){f+=1;const g=`${i.slice(0,l)}
|
|
3
|
-
`;await k(r,g),i=i.slice(l+1),l=i.indexOf(`
|
|
4
|
-
`)}}return i.length>0&&(f+=1,await k(r,`${i}
|
|
5
|
-
`)),{bytes:s,rows:f}}finally{o.releaseLock()}},H=async(t,r)=>{if(r!==void 0){t.destroy();try{await A(r)}catch{}}},nt=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=P(t.url,t.logger,t.cwd);if(r===void 0)return{bytes:0,code:1,rows:0};const{token:o}=j({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 e=`${r}${q}`,s=z(t.tables),f=t.fetchImpl??globalThis.fetch;if(typeof f!="function")throw new TypeError("no fetch implementation available — pass fetchImpl or run on Node >= 18");t.logger.info(`POST ${e} -> export${s?` (tables: ${s.join(",")})`:""}`);const i=await f(e,{body:JSON.stringify(s?{tables:s}:{}),headers:{authorization:`Bearer ${o}`,"content-type":"application/json"},method:"POST"});if(!i.ok){const p=await i.text();return t.logger.error(`export failed: HTTP ${String(i.status)}: ${p}`),{bytes:0,code:1,rows:0}}if(!i.body)return t.logger.error("export response carried no body"),{bytes:0,code:1,rows:0};const c=t.out===void 0||t.out==="-"?void 0:t.out,u=c===void 0?process.stdout:D(c,{encoding:"utf8"});let l,g;try{({bytes:l,rows:g}=await B(i.body,u))}catch(p){throw await H(u,c),p}return c!==void 0&&(await new Promise((p,b)=>{u.end(w=>{w?b(w):p()})}),t.logger.success(`wrote ${String(g)} rows to ${c} (${String(l)} bytes)`)),{bytes:l,code:0,rows:g}},M=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=P(t.url,t.logger,t.cwd);if(r===void 0)return;const{token:o}=j({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{const s=await v(t.file);if(!s.isFile()&&!s.isDirectory()){t.logger.error(`not a file or directory: ${t.file}`);return}}catch(s){const f=s instanceof Error?s.message:String(s);t.logger.error(`failed to stat ${t.file}: ${f}`);return}const e=t.fetchImpl??globalThis.fetch;if(typeof e!="function")throw new TypeError("no fetch implementation available — pass fetchImpl or run on Node >= 18");return{fetchImpl:e,requestUrl:`${r}${U}`,token:o}},I="_storage",K=async t=>{if(!(await v(t).catch(()=>{}))?.isDirectory())return;const r=[];for(const o of await J(t,{withFileTypes:!0})){if(!o.isDirectory())continue;const e=R(t,o.name,"documents.jsonl");(await v(e).catch(()=>{}))?.isFile()&&r.push({file:e,table:o.name})}return r.length>0?r.toSorted((o,e)=>o.table.localeCompare(e.table)):void 0};async function*V(t,r){for await(const o of L({crlfDelay:Number.POSITIVE_INFINITY,input:E(t,{encoding:"utf8"})})){const e=o.trim();e.length>0&&(yield`${JSON.stringify({doc:JSON.parse(e),table:r})}
|
|
6
|
-
`)}}async function*W(t,r){for(const{file:o,table:e}of t){if(e===I){r.warn(`skipping "${I}" — those rows describe stored files. Upload the exported blobs to R2 and re-point the keys.`);continue}yield*V(o,e)}}const Y=async t=>{const r=await K(t.file),o=await v(t.file);return r===void 0&&o.isDirectory()?(t.logger.error(`${t.file} is a directory but holds no <table>/documents.jsonl — expected a \`npx convex export --path <dir>\` dump, or pass an NDJSON file.`),{error:!0}):r&&t.table!==void 0?(t.logger.error("--table cannot be combined with a Convex export directory — each row's table comes from its source directory."),{error:!0}):{convexTables:r,error:!1}},Z=(t,r)=>{for(const e of r.warnings)t.warn(e);const o=r.received-r.insertedTotal-r.conflicts-r.errorCount;o>0&&t.warn(`${String(o)} of ${String(r.received)} rows were neither inserted, conflicted, nor reported as errors`),t.success(`imported ${String(r.insertedTotal)} of ${String(r.received)} rows (${String(r.conflicts)} conflicts, ${String(r.errorCount)} errors)`)},it=async t=>{const r=await M(t);if(r===void 0)return{body:void 0,code:1,inserted:0};const{fetchImpl:o,requestUrl:e,token:s}=r,f=t.batchSize??F,i=await Y(t);if(i.error)return{body:void 0,code:1,inserted:0};const{convexTables:c}=i;t.logger.info(c?`POST ${e} -> import Convex export ${t.file} (${String(c.length)} tables)`:`POST ${e} -> import ${t.file}`);const u=c?W(c,t.logger):E(t.file,{encoding:"utf8"}),l={},g=[];let p=0,b=0;const w=[];let m="",h=[],$=0;const _=a=>{for(const[n,d]of Object.entries(a.inserted??{}))l[n]=(l[n]??0)+d;g.push(...a.errors??[]),p+=a.conflicts??0,b+=a.received??0;for(const n of a.warnings??[])w.includes(n)||w.push(n)},S=async()=>{if(h.length===0)return;const a=h.join(`
|
|
7
|
-
`);h=[];const n=await o(e,{body:a,headers:{authorization:`Bearer ${s}`,"content-type":"application/x-ndjson"},method:"POST"});if(!n.ok){const y=await n.text().catch(()=>"<no body>");throw new O("INTERNAL",`import batch failed (HTTP ${String(n.status)}): ${y}`)}const d=await n.json();_(d)},T=a=>{const n=a.trim();if(n.length===0)return;if($+=1,t.table===void 0){h.push(n);return}let d;try{d=JSON.parse(n)}catch(y){const C=y instanceof Error?y.message:String(y);throw new O("INTERNAL",`invalid JSON on line ${String($)}: ${C}`,{cause:y})}h.push(JSON.stringify({doc:d,table:t.table}))};for await(const a of u){const n=typeof a=="string"?a:a.toString("utf8");m+=n;let d=m.indexOf(`
|
|
8
|
-
`);for(;d!==-1;)T(m.slice(0,d)),m=m.slice(d+1),d=m.indexOf(`
|
|
9
|
-
`),h.length>=f&&await S()}m.length>0&&T(m),await S();const x=Object.values(l).reduce((a,n)=>a+n,0),N={conflicts:p,errors:g,inserted:l,received:b,...w.length>0?{warnings:w}:{}};return t.logger.info(JSON.stringify(N,void 0,2)),Z(t.logger,{conflicts:p,errorCount:g.length,insertedTotal:x,received:b,warnings:w}),{body:N,code:g.length>0?1:0,inserted:x}};export{F as DEFAULT_IMPORT_BATCH_SIZE,nt as runExportCommand,it as runImportCommand};
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{mkdirSync as B,readFileSync as w,lstatSync as A,writeFileSync as D}from"node:fs";import{join as u,dirname as y}from"node:path";import{fileURLToPath as L}from"node:url";import{resolveHint as j,isLunoraError as k,flattenHint as E,findSolutionByMessage as C}from"@lunora/errors";import{createCerebro as I}from"@visulima/cerebro";import $ from"@visulima/cerebro/command/completion";import P from"@visulima/cerebro/command/version";import{p}from"./api-spec-BENwiyUa.mjs";import{g as s}from"./deploy-target-Dvr9vxpR.mjs";import{P as _,l as T}from"./detect-package-manager-DXDstphE.mjs";import{createLogger as S}from"./createLogger-BoSxdb2T.mjs";import{VisulimaError as U,renderError as M}from"@visulima/error";import{homedir as W}from"node:os";const J={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}]},f="lunora.advisor.map.json",K={description:"Score your app's advisor findings into a health map, and gate CI on it",examples:[["lunora advisor","Score the app and write lunora.advisor.map.json"],["lunora advisor --all","Show every procedure as a check matrix"],["lunora advisor --entry messages#sendMessage","Inspect one procedure"],["lunora advisor --min-score 80","Exit non-zero when the score drops below 80"],["lunora advisor --baseline","Fail on any regression against the committed map"]],group:"Develop",loader:()=>import("../packem_chunks/handler21.mjs").then(e=>({default:e.execute})),name:"advisor",options:[{description:"Show every procedure as a check matrix, not just the ones with findings",name:"all",type:Boolean},{description:`Compare against a committed map and fail on regression (default ${f})`,name:"baseline",type:String},{description:"Inspect a single procedure by `file#exportName`",name:"entry",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Exit non-zero when the global score is below this value (0-100)",name:"min-score",type:String},{description:`Where to write the map (default ${f})`,name:"out",type:String},{description:"Write the map artifact to disk (default true; use --no-write to skip)",name:"no-write",type:Boolean}]},F={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}]},q={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}]},H={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"],["lunora build --emit-bindings bindings.json","Also write what the bundle needs provisioned, for an external deployer"]],group:"Deploy",loader:()=>import("../packem_chunks/handler4.mjs").then(e=>({default:e.execute})),name:"build",options:[{description:`Which API spec(s) to emit: ${p} (default openapi)`,name:"api-spec",type:String},{description:"Write a JSON manifest of the bindings + crons the bundle needs to this path, for an IaC program to consume",name:"emit-bindings",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},s]},V={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: ${p} (default openapi)`,name:"api-spec",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Fail on ERROR-level advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail on ERROR-level advisories (the gate defaults to on in CI, off locally)",name:"no-strict-advisories",type:Boolean},s]},z={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}]},G={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: ${p} (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:"Fail the deploy on ERROR-level codegen advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail the deploy on ERROR-level codegen advisories (the gate defaults to on in CI, off locally). Never downgrades platform diagnostics.",name:"no-strict-advisories",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},s,{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}]},Y={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: ${p} (default openapi)`,name:"api-spec",type:String},{description:"Studio server port (default 6173)",name:"port",type:Number},s,{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 spawn wrangler dev — an external task runner owns the worker; codegen watch + studio still run",name:"no-worker",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}]},X={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"},Z={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:[]},ee={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 this Cloudflare environment for `push`/`diff` (passes --env <name> to wrangler)",name:"env",type:String},{description:"Alias for --env production",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}]},te={description:"Run every *.eval.ts under evals/ via @lunora/testing's evaluate/agentHarness — no live worker needed",examples:[["lunora eval","Run every eval under evals/, print the aggregate table"],["lunora eval --threshold 0.8","Non-zero exit if any eval's average score falls below 0.8"],["lunora eval --dir evals/support --format json","Run a subset and emit a machine-readable result"]],group:"Develop",loader:()=>import("../packem_chunks/handler23.mjs").then(e=>({default:e.execute})),name:"eval",options:[{description:"Directory to discover *.eval.ts files under (default evals/)",name:"dir",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Score gate every eval's average must meet ([0,1]); a per-eval `threshold` export wins over this for that eval",name:"threshold",type:Number}]},re={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}]},oe={argument:{description:"Source NDJSON file, or a `npx convex export --path <dir>` directory",name:"file",type:String},description:"Bulk-insert rows from an NDJSON file — or a Convex export directory — via the worker's admin endpoint",examples:[["lunora import backup.ndjson","Bulk-insert rows from an NDJSON file"],["lunora import ./convex-export","Import a `npx convex export --path` directory (ids are preserved, so no remapping)"]],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}]},ne={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}]},ae={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}]},ie={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}]},se={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/handler24.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}]},le={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}]},pe={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/handler22.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},s,{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}]},de={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/handler25.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}]},ce={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}]},ue={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: ${p} (default openapi)`,name:"api-spec",type:String},s,{description:"Re-bless the committed schema baseline (lunora/.lunora-schema.json) with the current shape",name:"update-schema-baseline",type:Boolean}]},me={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}]},ge={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}]},he={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)"],["lunora rules install --dir packages/app","Install into a specific root instead of the workspace root"]],group:"Project",loader:()=>import("../packem_chunks/handler17.mjs").then(e=>({default:e.execute})),name:"rules",options:[{description:"Install/check root (default: the detected workspace root, not the current directory)",name:"dir",type:String},{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}]},ye={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}]},fe={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}]},ve={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: ${p} (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},s]},be={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}]},we={filterStacktrace:()=>!1,hideErrorCodeView:!0},ke=(e,t={})=>{const r=e instanceof Error?e.message:String(e),o=j(k(e)?{code:e.code,hint:e.hint,message:r}:r),n=new U({hint:o===void 0?void 0:E(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="",M(n,we)},Se=(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,d=e[o-1]===t[a-1]?0:1;r[a]=Math.min((r[a-1]??0)+1,i+1,n+d),n=i}}return r[t.length]??0},xe=(e,t)=>{let r,o=Number.POSITIVE_INFINITY;for(const a of t){const i=Se(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},Re=e=>`https://registry.npmjs.org/@lunora/cli/${e}`,Oe=1440*60*1e3,Ne=1500,Be="0.0.0",Ae=/^v/u,De=new Set(["alpha","beta","next"]),m=e=>{const t=e.trim().replace(Ae,""),r=t.indexOf("-");return r===-1?{core:t,prerelease:""}:{core:t.slice(0,r),prerelease:t.slice(r+1)}},v=e=>{const[t,r,o]=m(e).core.split(".").map(n=>{const a=Number.parseInt(n,10);return Number.isFinite(a)?a:0});return[t??0,r??0,o??0]},Le=(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},je=(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 Le(a,i)}return 0},Ee=(e,t)=>{const r=v(e),o=v(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 je(m(e).prerelease,m(t).prerelease)},Ce=e=>{const t=m(e).prerelease.split(".")[0]??"";return De.has(t)?t:"latest"},Ie=(e,t)=>Ee(t,e)>0,$e=(e,t,r)=>t-e<r,Pe=(e,t,r="latest",o)=>{const n=`Update available for @lunora/cli: ${e} → ${t}`;if(o===void 0)return`${n} — add @lunora/cli@${r} as a dev dependency to update`;const{args:a,command:i}=_(o,[`@lunora/cli@${r}`],{dev:!0});return`${n} — run \`${i} ${a.join(" ")}\``},x=e=>u(e,"lunora-cli-update.json"),_e=e=>{const t=e.XDG_CACHE_HOME&&e.XDG_CACHE_HOME.length>0?e.XDG_CACHE_HOME:u(W(),".cache"),r=u(t,"lunora");try{B(r,{mode:448,recursive:!0})}catch{}return r},Te=e=>{try{const t=JSON.parse(w(x(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{}},b=(e,t)=>{try{const r=x(e);try{if(A(r).isSymbolicLink())return}catch{}D(r,`${JSON.stringify(t)}
|
|
3
|
-
`,"utf8")}catch{}},Ue=async(e,t)=>{try{const r=await e(Re(t),{signal:AbortSignal.timeout(Ne)});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}},Me=(e,t,r)=>e===Be||!r||t.CI!==void 0||t.LUNORA_NO_UPDATE_NOTIFIER!==void 0,We=async e=>{const t=e.env??process.env,r=e.isTTY??process.stdout.isTTY;if(Me(e.current,t,r))return;const o=e.cacheDir??_e(t),n=(e.now??Date.now)(),a=e.ttlMs??Oe,i=Ce(e.current),d=Te(o),N=d?.tag??"latest",g=d!==void 0&&N===i?d:void 0;let c=g?.latest;if(g===void 0||!$e(g.checkedAt,n,a)){const h=await Ue(e.fetchImpl??globalThis.fetch,i);h===void 0?b(o,{checkedAt:n,latest:e.current,tag:i}):(c=h,b(o,{checkedAt:n,latest:h,tag:i}))}c!==void 0&&Ie(e.current,c)&&e.logger.warn(Pe(e.current,c,i,e.manager))},Je=["init","add","dev","codegen","build","deploy","containers","prepare","link","deployments","logs","run","insights","reset","migrate","export","import","seed","backup","eval","verify","info","doctor","env","analyze","view","docs","registry","rules","mcp"],Ke=8,Fe=()=>{try{let e=y(L(import.meta.url));for(let t=0;t<Ke;t+=1){try{const o=JSON.parse(w(u(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=y(e);if(r===e)break;e=r}}catch{}return"0.0.0"},R=Fe(),qe=[ae,J,Q,V,K,H,G,z,ue,le,Y,pe,ye,ie,ge,ce,re,oe,fe,se,q,te,ve,ne,Z,ee,F,be,X,me,he,de],O=[...qe,P,$],dt=O.map(e=>e.name),l=e=>e.replaceAll("{",String.raw`\{`).replaceAll("}",String.raw`\}`),He=e=>e.every(t=>typeof t=="string")?e.map(t=>l(t)):e.map(t=>typeof t=="string"?[l(t)]:t.map(r=>l(r))),Ve=e=>({...e,...e.argument===void 0?{}:{argument:{...e.argument,description:l(e.argument.description??"")}},...e.description===void 0?{}:{description:l(e.description)},...e.examples===void 0?{}:{examples:He(e.examples)},...e.options===void 0?{}:{options:e.options.map(t=>({...t,description:l(t.description??"")}))}}),ze=e=>{const t={value:0},r=I("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:R});for(const o of O)r.addCommand(Ve(o));return{cli:r,exitCode:t}},Ge=/Command "(?<name>[^"]+)" not found/u,Ye=e=>{const t=S(),r=e instanceof Error?e.message:String(e),o=Ge.exec(r);if(!o?.groups){k(e)||C(r)!==void 0?t.error(ke(e)):t.error(r);return}const n=o.groups.name??"",a=xe(n,Je);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.")},ct=async(e={})=>{const{cli:t,exitCode:r}=ze(e);try{await t.run({shouldExitProcess:!1})}catch(n){return Ye(n),1}let o;try{o=T(process.cwd())}catch{}return await We({current:R,logger:S(),manager:o}),r.value};export{Je as d,ct as f,R as i,f as o,dt as t};
|