@lunora/cli 1.0.0-alpha.129 → 1.0.0-alpha.130

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.
Files changed (31) hide show
  1. package/dist/bin.mjs +1 -1
  2. package/dist/index.mjs +1 -1
  3. package/dist/packem_chunks/handler10.mjs +1 -1
  4. package/dist/packem_chunks/handler11.mjs +1 -1
  5. package/dist/packem_chunks/handler15.mjs +1 -1
  6. package/dist/packem_chunks/handler18.mjs +2 -2
  7. package/dist/packem_chunks/handler19.mjs +1 -1
  8. package/dist/packem_chunks/handler2.mjs +1 -1
  9. package/dist/packem_chunks/handler21.mjs +1 -1
  10. package/dist/packem_chunks/handler22.mjs +1 -1
  11. package/dist/packem_chunks/handler24.mjs +1 -1
  12. package/dist/packem_chunks/handler3.mjs +1 -1
  13. package/dist/packem_chunks/handler5.mjs +1 -1
  14. package/dist/packem_chunks/handler6.mjs +1 -1
  15. package/dist/packem_chunks/handler9.mjs +1 -1
  16. package/dist/packem_chunks/planDevCommand.mjs +1 -1
  17. package/dist/packem_chunks/runDeployCommand.mjs +1 -1
  18. package/dist/packem_chunks/runInitCommand.mjs +1 -1
  19. package/dist/packem_chunks/runMigrateGenerateCommand.mjs +7 -7
  20. package/dist/packem_shared/{COMMANDS-BHb52jlk.mjs → COMMANDS-CCuhsVyI.mjs} +1 -1
  21. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-xn-frBqK.mjs +12 -0
  22. package/dist/packem_shared/cli-0uJWyeda.mjs +3 -0
  23. package/dist/packem_shared/{detect-package-manager-B2eIuAiP.mjs → detect-package-manager-C4aS7HE4.mjs} +1 -1
  24. package/dist/packem_shared/post-codegen-hook-CjhP1OmV.mjs +1 -0
  25. package/dist/packem_shared/schema-drift-gate-d12lMICD.mjs +1 -0
  26. package/dist/packem_shared/{wrangler-secrets-DDDUuryf.mjs → wrangler-secrets-DHpbsDN9.mjs} +1 -1
  27. package/package.json +8 -8
  28. package/skills/lunora-migration-helper/SKILL.md +34 -0
  29. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-CEOt386P.mjs +0 -12
  30. package/dist/packem_shared/cli-BxL0WCh4.mjs +0 -3
  31. package/dist/packem_shared/schema-drift-gate-CpqG-xP4.mjs +0 -1
package/dist/bin.mjs CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import{e}from"./packem_shared/cli-BxL0WCh4.mjs";try{const r=await e();process.exit(r)}catch(r){process.stderr.write(`${r instanceof Error?r.message:String(r)}
2
+ import{p as s}from"./packem_shared/cli-0uJWyeda.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.mjs CHANGED
@@ -1 +1 @@
1
- import{s as o,t as n,e as a}from"./packem_shared/cli-BxL0WCh4.mjs";import{runCodegenCommand as t}from"./packem_chunks/runCodegenCommand.mjs";import{DEFAULT_IMPORT_BATCH_SIZE as p,runExportCommand as f,runImportCommand as x}from"./packem_shared/DEFAULT_IMPORT_BATCH_SIZE-CEOt386P.mjs";import{runDeployCommand as C}from"./packem_chunks/runDeployCommand.mjs";import{planDevCommand as s,runDevCommand as u}from"./packem_chunks/planDevCommand.mjs";import{runInitCommand as g}from"./packem_chunks/runInitCommand.mjs";import{runMigrateGenerateCommand as R}from"./packem_chunks/runMigrateGenerateCommand.mjs";import{runResetCommand as E}from"./packem_chunks/runResetCommand.mjs";import{runRpcCommand as A}from"./packem_chunks/runRpcCommand.mjs";import{insertSchemaExtension as M}from"./packem_shared/insertSchemaExtension-DZReBZ4_.mjs";import{createLogger as _,pail as h}from"./packem_shared/createLogger--C3x1FNE.mjs";import{diffSnapshots as L,renderAddColumn as O,renderCreateIndex as b,renderCreateTable as w,renderDropIndex as B,renderDropTable as F,renderMigrationFile as P,validatorKindToSqlType as U}from"./packem_shared/diffSnapshots-9bDd9nOK.mjs";import{default as q}from"./packem_shared/schemaIrToSnapshot-Clwd2A8e.mjs";import{createRecordingSpawner as N,defaultSpawner as Q}from"./packem_shared/createRecordingSpawner-ByIqBepG.mjs";import{default as j}from"./packem_shared/parseManifest-x3WsxKHz.mjs";import{REQUIRED_COMPATIBILITY_DATE as H,REQUIRED_FLAG as K,validateWranglerProject as Y,validateWranglerConfig as Z}from"@lunora/config/cloudflare";import{buildRegistryIndex as J}from"./packem_shared/buildRegistryIndex-DwySASBu.mjs";import{k as $,q as rr,D as er}from"./packem_shared/commands-C5pu77HK.mjs";export{o as COMMANDS,p as DEFAULT_IMPORT_BATCH_SIZE,H as REQUIRED_COMPATIBILITY_DATE,K as REQUIRED_FLAG,n as VERSION,J as buildRegistryIndex,_ as createLogger,N as createRecordingSpawner,Q as defaultSpawner,L as diffSnapshots,M as insertSchemaExtension,h as pail,j as parseManifest,s as planDevCommand,O as renderAddColumn,b as renderCreateIndex,w as renderCreateTable,B as renderDropIndex,F as renderDropTable,P as renderMigrationFile,$ as runAddCommand,rr as runBuildIndexCommand,a as runCli,t as runCodegenCommand,C as runDeployCommand,u as runDevCommand,f as runExportCommand,x as runImportCommand,g as runInitCommand,R as runMigrateGenerateCommand,er as runRegistryViewCommand,E as runResetCommand,A as runRpcCommand,q as schemaIrToSnapshot,Y as validateWrangler,Z as validateWranglerConfig,U as validatorKindToSqlType};
1
+ import{d as o,i as n,p as a}from"./packem_shared/cli-0uJWyeda.mjs";import{runCodegenCommand as t}from"./packem_chunks/runCodegenCommand.mjs";import{DEFAULT_IMPORT_BATCH_SIZE as p,runExportCommand as f,runImportCommand as i}from"./packem_shared/DEFAULT_IMPORT_BATCH_SIZE-xn-frBqK.mjs";import{runDeployCommand as C}from"./packem_chunks/runDeployCommand.mjs";import{planDevCommand as s,runDevCommand as u}from"./packem_chunks/planDevCommand.mjs";import{runInitCommand as g}from"./packem_chunks/runInitCommand.mjs";import{runMigrateGenerateCommand as R}from"./packem_chunks/runMigrateGenerateCommand.mjs";import{runResetCommand as E}from"./packem_chunks/runResetCommand.mjs";import{runRpcCommand as A}from"./packem_chunks/runRpcCommand.mjs";import{insertSchemaExtension as M}from"./packem_shared/insertSchemaExtension-DZReBZ4_.mjs";import{createLogger as _,pail as h}from"./packem_shared/createLogger--C3x1FNE.mjs";import{diffSnapshots as L,renderAddColumn as O,renderCreateIndex as b,renderCreateTable as w,renderDropIndex as B,renderDropTable as F,renderMigrationFile as P,validatorKindToSqlType as U}from"./packem_shared/diffSnapshots-9bDd9nOK.mjs";import{default as q}from"./packem_shared/schemaIrToSnapshot-Clwd2A8e.mjs";import{createRecordingSpawner as N,defaultSpawner as Q}from"./packem_shared/createRecordingSpawner-ByIqBepG.mjs";import{default as j}from"./packem_shared/parseManifest-x3WsxKHz.mjs";import{REQUIRED_COMPATIBILITY_DATE as H,REQUIRED_FLAG as K,validateWranglerProject as Y,validateWranglerConfig as Z}from"@lunora/config/cloudflare";import{buildRegistryIndex as J}from"./packem_shared/buildRegistryIndex-DwySASBu.mjs";import{k as $,q as rr,D as er}from"./packem_shared/commands-C5pu77HK.mjs";export{o as COMMANDS,p as DEFAULT_IMPORT_BATCH_SIZE,H as REQUIRED_COMPATIBILITY_DATE,K as REQUIRED_FLAG,n as VERSION,J as buildRegistryIndex,_ as createLogger,N as createRecordingSpawner,Q as defaultSpawner,L as diffSnapshots,M as insertSchemaExtension,h as pail,j as parseManifest,s as planDevCommand,O as renderAddColumn,b as renderCreateIndex,w as renderCreateTable,B as renderDropIndex,F as renderDropTable,P as renderMigrationFile,$ as runAddCommand,rr as runBuildIndexCommand,a as runCli,t as runCodegenCommand,C as runDeployCommand,u as runDevCommand,f as runExportCommand,i as runImportCommand,g as runInitCommand,R as runMigrateGenerateCommand,er as runRegistryViewCommand,E as runResetCommand,A as runRpcCommand,q as schemaIrToSnapshot,Y as validateWrangler,Z as validateWranglerConfig,U as validatorKindToSqlType};
@@ -1 +1 @@
1
- import{i as p}from"../packem_shared/command-Bjv4VmYA.mjs";import{s as u}from"../packem_shared/resolve-target-vxaXHmvg.mjs";import{runExportCommand as m}from"../packem_shared/DEFAULT_IMPORT_BATCH_SIZE-CEOt386P.mjs";const s=p(({argument:r,cwd:t,logger:e,options:o})=>m({cwd:t,logger:e,out:r[0]??o.out,prod:o.prod===!0,tables:o.tables,token:o.token,url:u({cwd:t,prod:o.prod===!0,url:o.url})}));export{s as execute};
1
+ import{i as p}from"../packem_shared/command-Bjv4VmYA.mjs";import{s as u}from"../packem_shared/resolve-target-vxaXHmvg.mjs";import{runExportCommand as m}from"../packem_shared/DEFAULT_IMPORT_BATCH_SIZE-xn-frBqK.mjs";const s=p(({argument:r,cwd:t,logger:e,options:o})=>m({cwd:t,logger:e,out:r[0]??o.out,prod:o.prod===!0,tables:o.tables,token:o.token,url:u({cwd:t,prod:o.prod===!0,url:o.url})}));export{s as execute};
@@ -1 +1 @@
1
- import{i as n}from"../packem_shared/command-Bjv4VmYA.mjs";import{s as p}from"../packem_shared/resolve-target-vxaXHmvg.mjs";import{runImportCommand as i}from"../packem_shared/DEFAULT_IMPORT_BATCH_SIZE-CEOt386P.mjs";const l=n(({argument:a,cwd:e,logger:r,options:o})=>{const t=a[0];return t?i({batchSize:o.batchSize,cwd:e,file:t,logger:r,prod:o.prod===!0,table:o.table,token:o.token,url:p({cwd:e,prod:o.prod===!0,url:o.url}),yes:o.yes===!0}):(r.error("import requires a path. Usage: lunora import <file.ndjson | convex-export-dir> [--table <name>]"),{code:1})});export{l as execute};
1
+ import{i as n}from"../packem_shared/command-Bjv4VmYA.mjs";import{s as p}from"../packem_shared/resolve-target-vxaXHmvg.mjs";import{runImportCommand as i}from"../packem_shared/DEFAULT_IMPORT_BATCH_SIZE-xn-frBqK.mjs";const l=n(({argument:a,cwd:e,logger:r,options:o})=>{const t=a[0];return t?i({batchSize:o.batchSize,cwd:e,file:t,logger:r,prod:o.prod===!0,table:o.table,token:o.token,url:p({cwd:e,prod:o.prod===!0,url:o.url}),yes:o.yes===!0}):(r.error("import requires a path. Usage: lunora import <file.ndjson | convex-export-dir> [--table <name>]"),{code:1})});export{l as execute};
@@ -1 +1 @@
1
- import{runCodegen as g}from"@lunora/codegen";import{resolveTargetOrThrow as d,resolveDeployDriver as p}from"@lunora/config";import{r as m}from"../packem_shared/api-spec-BENwiyUa.mjs";import{l as f}from"../packem_shared/codegen-error-DJN6pTH5.mjs";import{i as u}from"../packem_shared/command-Bjv4VmYA.mjs";import{a as h}from"../packem_shared/platform-diagnostics-C4TFj5Pu.mjs";import{k as w}from"../packem_shared/schema-drift-gate-CpqG-xP4.mjs";import{validateWranglerProject as v}from"@lunora/config/cloudflare";const S=async(e,t,a=[],i)=>{const s={crons:a,projectRoot:e},n=p(i);try{const r=await n.infer(s),l=[r.shardNamespaces.length>0?`${String(r.shardNamespaces.length)} shard namespace(s)`:void 0,r.queues.length>0?`${String(r.queues.length)} queue(s)`:void 0,r.workflows.length>0?`${String(r.workflows.length)} workflow(s)`:void 0,r.containers.length>0?`${String(r.containers.length)} container(s)`:void 0,r.globalDatabase?"global database":void 0,r.objectStorage?"object storage":void 0,r.keyValueStore?"key-value store":void 0].filter(c=>c!==void 0);l.length>0&&t.info(`${n.name} target requires: ${l.join(", ")}`)}catch{}const o=await n.provision(s);o.changed&&t.success(`provisioned: ${o.added.join(", ")} → ${o.configPath??"wrangler.jsonc"}`);for(const r of o.warnings)t.warn(r)},b=async e=>{const t=e.cwd??process.cwd(),a=d(t,e.target);e.logger.info("running codegen");let i;try{i=g({apiSpec:e.apiSpec,projectRoot:t,target:a}),e.logger.success("codegen complete"),h(i.platformDiagnostics,e.logger)}catch(o){const r=o instanceof Error?o.message:String(o);return e.logger.error(f(o)),{code:1,error:`codegen failed: ${r}`,validation:{problems:[],wranglerPath:void 0}}}const s=w({allowDrift:e.allowSchemaDrift===!0,codegen:i,logger:e.logger,updateBaseline:e.updateSchemaBaseline===!0});if(s.blocked)return{code:1,error:"schema drift gate blocked prepare",schemaDrift:{blocked:!0,reason:s.reason},validation:{problems:[],wranglerPath:void 0}};await S(t,e.logger,i.cronTriggers,a);const n=v({projectRoot:t});if(n.problems.length>0){e.logger.error("wrangler.jsonc validation failed:");for(const o of n.problems)e.logger.error(` - ${o}`);return{code:1,error:"wrangler validation failed",validation:n}}return s.rebless?.(),e.logger.success("project is ready to deploy"),{code:0,validation:n}},R=u(({cwd:e,logger:t,options:a})=>b({allowSchemaDrift:a.allowSchemaDrift===!0,apiSpec:m(a.apiSpec),cwd:e,logger:t,target:a.target,updateSchemaBaseline:a.updateSchemaBaseline===!0}));export{R as execute,b as runPrepareCommand};
1
+ import{runCodegen as g}from"@lunora/codegen";import{resolveTargetOrThrow as d,resolveDeployDriver as p}from"@lunora/config";import{r as m}from"../packem_shared/api-spec-BENwiyUa.mjs";import{l as f}from"../packem_shared/codegen-error-DJN6pTH5.mjs";import{i as u}from"../packem_shared/command-Bjv4VmYA.mjs";import{a as w}from"../packem_shared/platform-diagnostics-C4TFj5Pu.mjs";import{m as h}from"../packem_shared/post-codegen-hook-CjhP1OmV.mjs";import{R as v}from"../packem_shared/schema-drift-gate-d12lMICD.mjs";import{validateWranglerProject as S}from"@lunora/config/cloudflare";const b=async(r,o,a=[],i)=>{const l={crons:a,projectRoot:r},n=p(i);try{const e=await n.infer(l),s=[e.shardNamespaces.length>0?`${String(e.shardNamespaces.length)} shard namespace(s)`:void 0,e.queues.length>0?`${String(e.queues.length)} queue(s)`:void 0,e.workflows.length>0?`${String(e.workflows.length)} workflow(s)`:void 0,e.containers.length>0?`${String(e.containers.length)} container(s)`:void 0,e.globalDatabase?"global database":void 0,e.objectStorage?"object storage":void 0,e.keyValueStore?"key-value store":void 0].filter(c=>c!==void 0);s.length>0&&o.info(`${n.name} target requires: ${s.join(", ")}`)}catch{}const t=await n.provision(l);t.changed&&o.success(`provisioned: ${t.added.join(", ")} → ${t.configPath??"wrangler.jsonc"}`);for(const e of t.warnings)o.warn(e)},$=async r=>{const o=r.cwd??process.cwd(),a=d(o,r.target);r.logger.info("running codegen");let i;try{i=g({apiSpec:r.apiSpec,projectRoot:o,target:a}),r.logger.success("codegen complete"),w(i.platformDiagnostics,r.logger)}catch(e){const s=e instanceof Error?e.message:String(e);return r.logger.error(f(e)),{code:1,error:`codegen failed: ${s}`,validation:{problems:[],wranglerPath:void 0}}}const l=await h({cwd:o,logger:r.logger,spawner:r.spawner});if(l.error!==void 0)return r.logger.error(l.error),{code:1,error:l.error,validation:{problems:[],wranglerPath:void 0}};const n=v({allowDrift:r.allowSchemaDrift===!0,codegen:i,command:"prepare",logger:r.logger,updateBaseline:r.updateSchemaBaseline===!0});if(n.blocked)return{code:1,error:"schema drift gate blocked prepare",schemaDrift:{blocked:!0,reason:n.reason},validation:{problems:[],wranglerPath:void 0}};await b(o,r.logger,i.cronTriggers,a);const t=S({projectRoot:o});if(t.problems.length>0){r.logger.error("wrangler.jsonc validation failed:");for(const e of t.problems)r.logger.error(` - ${e}`);return{code:1,error:"wrangler validation failed",validation:t}}return n.rebless?.(),r.logger.success("project is ready to deploy"),{code:0,validation:t}},x=u(({cwd:r,logger:o,options:a})=>$({allowSchemaDrift:a.allowSchemaDrift===!0,apiSpec:m(a.apiSpec),cwd:r,logger:o,target:a.target,updateSchemaBaseline:a.updateSchemaBaseline===!0}));export{x as execute,$ as runPrepareCommand};
@@ -1,3 +1,3 @@
1
- import{existsSync as y}from"node:fs";import{mkdtemp as S,writeFile as v,rm as j}from"node:fs/promises";import{tmpdir as $}from"node:os";import{discoverSchema as k,schemaFromIr as C}from"@lunora/codegen";import{seedPlan as R}from"@lunora/seed";import{join as m}from"@visulima/path";import{Project as x}from"ts-morph";import{i as z}from"../packem_shared/command-Bjv4VmYA.mjs";import{s as A}from"../packem_shared/resolve-target-vxaXHmvg.mjs";import{i as F}from"../packem_shared/tui-prompts-CCt3jm1k.mjs";import{runImportCommand as I}from"../packem_shared/DEFAULT_IMPORT_BATCH_SIZE-CEOt386P.mjs";import{runResetCommand as T}from"./runResetCommand.mjs";const p=r=>{if(r===void 0)return!0;try{const{hostname:e}=new URL(r);return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||e==="::1"}catch{return!1}},N=(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:""}),U=(r,e)=>{if(!y(e))return r.logger.error(`schema not found: ${e} — run \`vis generate lunora-table --name=<name>\` to create one`),c(1);if(r.reset===!0&&(r.prod===!0||!p(r.url)))return r.logger.error("--reset only clears local .wrangler/state and cannot be combined with --prod or a remote --url"),c(1)},P=async(r,e,t,o)=>{const l=await S(m($(),"lunora-seed-")),a=m(l,"rows.ndjson");await v(a,r,"utf8");try{const n=await I({batchSize:o.batchSize,cwd:t,fetchImpl:o.fetchImpl,file:a,logger:o.logger,prod:o.prod,token:o.token,url:o.url}),d=n.body?.conflicts??0;return d>0&&o.logger.warn(`${String(d)} row(s) skipped — their _id already exists. Seeding is deterministic; re-run with --reset to wipe local state first, or a different --seed for fresh ids.`),{code:n.code,conflicts:d,generated:e,inserted:n.inserted,ndjson:r}}finally{await j(l,{force:!0,recursive:!0}).catch(()=>{})}},_=(r,e)=>{if(r.table===void 0||e.tables.some(o=>o.name===r.table))return;const t=e.tables.map(o=>o.name).join(", ");return r.logger.error(`unknown table "${r.table}" — schema defines: ${t||"(no tables)"}`),c(1)},B=async(r,e)=>{if(!(!(r.prod===!0||!p(r.url))||r.yes===!0)){if(!process.stdin.isTTY&&r.confirm===void 0)return r.logger.error("seed: refusing to insert into a non-local target without confirmation — re-run with --yes"),c(1);if(!await(r.confirm??F)(`This will insert ${String(e)} generated row(s) into ${r.url??"the production worker"}. Continue?`))return r.logger.info("seed: aborted"),c(1)}},G=async r=>{const e=r.cwd??process.cwd(),t=m(e,"lunora","schema.ts"),o=U(r,t);if(o!==void 0)return o;const l=new x({skipAddingFilesFromTsConfig:!0}),a=k(l,t),n=_(r,a);if(n!==void 0)return n;const d=C(a),g=R(d,{defaultCount:r.count??10,now:r.now,only:r.table===void 0?void 0:[r.table],seed:r.seed??0}),u=[];for(const{rows:f,table:h}of g)for(const b of f)u.push(JSON.stringify({doc:b,table:h},N));const i=u.length>0?`${u.join(`
1
+ import{existsSync as y}from"node:fs";import{mkdtemp as S,writeFile as v,rm as j}from"node:fs/promises";import{tmpdir as $}from"node:os";import{discoverSchema as k,schemaFromIr as C}from"@lunora/codegen";import{seedPlan as R}from"@lunora/seed";import{join as m}from"@visulima/path";import{Project as x}from"ts-morph";import{i as z}from"../packem_shared/command-Bjv4VmYA.mjs";import{s as A}from"../packem_shared/resolve-target-vxaXHmvg.mjs";import{i as F}from"../packem_shared/tui-prompts-CCt3jm1k.mjs";import{runImportCommand as I}from"../packem_shared/DEFAULT_IMPORT_BATCH_SIZE-xn-frBqK.mjs";import{runResetCommand as T}from"./runResetCommand.mjs";const p=r=>{if(r===void 0)return!0;try{const{hostname:e}=new URL(r);return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||e==="::1"}catch{return!1}},N=(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:""}),U=(r,e)=>{if(!y(e))return r.logger.error(`schema not found: ${e} — run \`vis generate lunora-table --name=<name>\` to create one`),c(1);if(r.reset===!0&&(r.prod===!0||!p(r.url)))return r.logger.error("--reset only clears local .wrangler/state and cannot be combined with --prod or a remote --url"),c(1)},P=async(r,e,t,o)=>{const l=await S(m($(),"lunora-seed-")),a=m(l,"rows.ndjson");await v(a,r,"utf8");try{const n=await I({batchSize:o.batchSize,cwd:t,fetchImpl:o.fetchImpl,file:a,logger:o.logger,prod:o.prod,token:o.token,url:o.url}),d=n.body?.conflicts??0;return d>0&&o.logger.warn(`${String(d)} row(s) skipped — their _id already exists. Seeding is deterministic; re-run with --reset to wipe local state first, or a different --seed for fresh ids.`),{code:n.code,conflicts:d,generated:e,inserted:n.inserted,ndjson:r}}finally{await j(l,{force:!0,recursive:!0}).catch(()=>{})}},_=(r,e)=>{if(r.table===void 0||e.tables.some(o=>o.name===r.table))return;const t=e.tables.map(o=>o.name).join(", ");return r.logger.error(`unknown table "${r.table}" — schema defines: ${t||"(no tables)"}`),c(1)},B=async(r,e)=>{if(!(!(r.prod===!0||!p(r.url))||r.yes===!0)){if(!process.stdin.isTTY&&r.confirm===void 0)return r.logger.error("seed: refusing to insert into a non-local target without confirmation — re-run with --yes"),c(1);if(!await(r.confirm??F)(`This will insert ${String(e)} generated row(s) into ${r.url??"the production worker"}. Continue?`))return r.logger.info("seed: aborted"),c(1)}},H=async r=>{const e=r.cwd??process.cwd(),t=m(e,"lunora","schema.ts"),o=U(r,t);if(o!==void 0)return o;const l=new x({skipAddingFilesFromTsConfig:!0}),a=k(l,t),n=_(r,a);if(n!==void 0)return n;const d=C(a),g=R(d,{defaultCount:r.count??10,now:r.now,only:r.table===void 0?void 0:[r.table],seed:r.seed??0}),u=[];for(const{rows:f,table:h}of g)for(const b of f)u.push(JSON.stringify({doc:b,table:h},N));const i=u.length>0?`${u.join(`
2
2
  `)}
3
- `:"",s=u.length;if(r.dryRun===!0)return i.length>0&&process.stdout.write(i),r.logger.info(`generated ${String(s)} row(s) across ${String(g.length)} table(s) — dry run, nothing inserted`),{code:0,conflicts:0,generated:s,inserted:0,ndjson:i};if(r.reset===!0){const f=await T({cwd:e,logger:r.logger,yes:!0});if(f.code!==0)return{code:f.code,conflicts:0,generated:s,inserted:0,ndjson:i}}if(s===0)return r.logger.warn("no rows generated — nothing to insert"),{code:0,conflicts:0,generated:0,inserted:0,ndjson:i};const w=await B(r,s);return w!==void 0?w:P(i,s,e,r)},W=z(async({cwd:r,logger:e,options:t})=>({code:(await G({batchSize:t.batchSize,count:t.count,cwd:r,dryRun:t.dryRun===!0,logger:e,prod:t.prod===!0,reset:t.reset===!0,now:t.now,seed:t.seed,table:t.table,token:t.token,url:A({cwd:r,prod:t.prod===!0,url:t.url}),yes:t.yes===!0})).code}));export{W as execute,G as runSeedCommand};
3
+ `:"",s=u.length;if(r.dryRun===!0)return i.length>0&&process.stdout.write(i),r.logger.info(`generated ${String(s)} row(s) across ${String(g.length)} table(s) — dry run, nothing inserted`),{code:0,conflicts:0,generated:s,inserted:0,ndjson:i};if(r.reset===!0){const f=await T({cwd:e,logger:r.logger,yes:!0});if(f.code!==0)return{code:f.code,conflicts:0,generated:s,inserted:0,ndjson:i}}if(s===0)return r.logger.warn("no rows generated — nothing to insert"),{code:0,conflicts:0,generated:0,inserted:0,ndjson:i};const w=await B(r,s);return w!==void 0?w:P(i,s,e,r)},V=z(async({cwd:r,logger:e,options:t})=>({code:(await H({batchSize:t.batchSize,count:t.count,cwd:r,dryRun:t.dryRun===!0,logger:e,prod:t.prod===!0,reset:t.reset===!0,now:t.now,seed:t.seed,table:t.table,token:t.token,url:A({cwd:r,prod:t.prod===!0,url:t.url}),yes:t.yes===!0})).code}));export{V as execute,H as runSeedCommand};
@@ -1 +1 @@
1
- import{existsSync as d}from"node:fs";import{join as m}from"node:path";import{runCodegen as w}from"@lunora/codegen";import{r as u}from"../packem_shared/api-spec-BENwiyUa.mjs";import{c as y}from"../packem_shared/codegen-error-DJN6pTH5.mjs";import{i as v}from"../packem_shared/command-Bjv4VmYA.mjs";import{i as S}from"../packem_shared/deploy-target-Dvr9vxpR.mjs";import{M as $,P as k}from"../packem_shared/detect-package-manager-B2eIuAiP.mjs";import{i as j,r as P,d as U,s as x}from"../packem_shared/output-format-D7cKB-O5.mjs";import{k as E}from"../packem_shared/schema-drift-gate-CpqG-xP4.mjs";import{defaultSpawner as b}from"../packem_shared/createRecordingSpawner-ByIqBepG.mjs";import{validateWranglerProject as D}from"@lunora/config/cloudflare";const T=async(r,o)=>{if(!d(m(r,"tsconfig.json")))return{warning:"no tsconfig.json found — skipping TypeScript type-check"};const e=$(k(r),"tsc",["--noEmit","-p","tsconfig.json"]),t=await o({args:e.args,command:e.command,cwd:r});return t.code===0?{}:{error:`type errors: tsc --noEmit exited ${String(t.code)}`}},R="/_lunora/health",p=r=>(r.endsWith("/")?r.slice(0,-1):r)+R,C=async(r,o)=>{const e=p(r);let t;try{t=await o(e)}catch(a){const i=a instanceof Error?a.message:String(a);return{error:`health probe failed: could not reach ${e} (${i})`}}return t.ok?{}:{error:`health probe failed: ${e} returned HTTP ${String(t.status)}`}},W=async(r,o)=>{if(r.healthUrl===void 0||r.healthUrl==="")return;const e=await C(r.healthUrl,r.healthFetch??(t=>fetch(t)));if(e.error===void 0){o.success(`verify: health probe ok (${p(r.healthUrl)})`);return}return e.error},A=(r,o,e,t)=>{if(o.length===0&&e.length===0)return r.success("verify: project is valid"),{code:0,errors:[],warnings:[],wranglerPath:t};if(e.length>0){r.warn("verify: warnings:");for(const a of e)r.warn(` - ${a}`)}if(o.length>0){r.error("verify: errors:");for(const a of o){r.error(` - ${a}`);const i=y(a);i!==void 0&&r.error(i)}return{code:1,errors:o,warnings:e,wranglerPath:t}}return r.success("verify: project is valid (with warnings)"),{code:0,errors:[],warnings:e,wranglerPath:t}},F=async r=>{const o=r.cwd??process.cwd(),e=x(r.format,r.logger),t=j("verify",r.format);if(t!==void 0)return r.logger.error(t),{code:1,error:t,errors:[],warnings:[],wranglerPath:void 0};const a=D({projectRoot:o}),i=[...a.report.errors],l=[...a.report.warnings];try{const n=S(o,r.target);if(n.target===void 0){const c=n.error??"unknown deploy target";return e.error(c),{code:1,error:c,errors:[c],warnings:[],wranglerPath:void 0}}const s=w({apiSpec:r.apiSpec,dryRun:!0,projectRoot:o,target:n.target}),h=E({allowDrift:r.allowSchemaDrift===!0,codegen:s,logger:e,readOnly:!0});h.blocked&&i.push(h.reason)}catch(n){const s=n instanceof Error?n.message:String(n);i.push(`codegen failed: ${s}`)}if(r.typecheck!==!1){const n=await T(o,r.spawner??b);n.error!==void 0&&i.push(n.error),n.warning!==void 0&&l.push(n.warning)}const f=await W(r,e);f!==void 0&&i.push(f);const g=A(e,i,l,a.wranglerPath);return P(r.format)&&U(g),g},L=v(async({cwd:r,logger:o,options:e})=>({code:(await F({allowSchemaDrift:e.allowSchemaDrift===!0,apiSpec:u(e.apiSpec),cwd:r,format:e.format,healthUrl:e.healthUrl,logger:o,target:e.target,typecheck:e.typecheck===!1?!1:void 0})).code}));export{L as execute,F as runVerifyCommand};
1
+ import{existsSync as p}from"node:fs";import{join as m}from"node:path";import{runCodegen as w}from"@lunora/codegen";import{r as u}from"../packem_shared/api-spec-BENwiyUa.mjs";import{c as y}from"../packem_shared/codegen-error-DJN6pTH5.mjs";import{i as v}from"../packem_shared/command-Bjv4VmYA.mjs";import{i as S}from"../packem_shared/deploy-target-Dvr9vxpR.mjs";import{M as $,P as j}from"../packem_shared/detect-package-manager-C4aS7HE4.mjs";import{i as k,r as P,d as U,s as x}from"../packem_shared/output-format-D7cKB-O5.mjs";import{R as E}from"../packem_shared/schema-drift-gate-d12lMICD.mjs";import{defaultSpawner as b}from"../packem_shared/createRecordingSpawner-ByIqBepG.mjs";import{validateWranglerProject as D}from"@lunora/config/cloudflare";const R=async(r,o)=>{if(!p(m(r,"tsconfig.json")))return{warning:"no tsconfig.json found — skipping TypeScript type-check"};const e=$(j(r),"tsc",["--noEmit","-p","tsconfig.json"]),t=await o({args:e.args,command:e.command,cwd:r});return t.code===0?{}:{error:`type errors: tsc --noEmit exited ${String(t.code)}`}},T="/_lunora/health",d=r=>(r.endsWith("/")?r.slice(0,-1):r)+T,C=async(r,o)=>{const e=d(r);let t;try{t=await o(e)}catch(a){const i=a instanceof Error?a.message:String(a);return{error:`health probe failed: could not reach ${e} (${i})`}}return t.ok?{}:{error:`health probe failed: ${e} returned HTTP ${String(t.status)}`}},W=async(r,o)=>{if(r.healthUrl===void 0||r.healthUrl==="")return;const e=await C(r.healthUrl,r.healthFetch??(t=>fetch(t)));if(e.error===void 0){o.success(`verify: health probe ok (${d(r.healthUrl)})`);return}return e.error},A=(r,o,e,t)=>{if(o.length===0&&e.length===0)return r.success("verify: project is valid"),{code:0,errors:[],warnings:[],wranglerPath:t};if(e.length>0){r.warn("verify: warnings:");for(const a of e)r.warn(` - ${a}`)}if(o.length>0){r.error("verify: errors:");for(const a of o){r.error(` - ${a}`);const i=y(a);i!==void 0&&r.error(i)}return{code:1,errors:o,warnings:e,wranglerPath:t}}return r.success("verify: project is valid (with warnings)"),{code:0,errors:[],warnings:e,wranglerPath:t}},F=async r=>{const o=r.cwd??process.cwd(),e=x(r.format,r.logger),t=k("verify",r.format);if(t!==void 0)return r.logger.error(t),{code:1,error:t,errors:[],warnings:[],wranglerPath:void 0};const a=D({projectRoot:o}),i=[...a.report.errors],l=[...a.report.warnings];try{const n=S(o,r.target);if(n.target===void 0){const c=n.error??"unknown deploy target";return e.error(c),{code:1,error:c,errors:[c],warnings:[],wranglerPath:void 0}}const s=w({apiSpec:r.apiSpec,dryRun:!0,projectRoot:o,target:n.target}),h=E({allowDrift:r.allowSchemaDrift===!0,codegen:s,command:"verify",logger:e,readOnly:!0});h.blocked&&i.push(h.reason)}catch(n){const s=n instanceof Error?n.message:String(n);i.push(`codegen failed: ${s}`)}if(r.typecheck!==!1){const n=await R(o,r.spawner??b);n.error!==void 0&&i.push(n.error),n.warning!==void 0&&l.push(n.warning)}const f=await W(r,e);f!==void 0&&i.push(f);const g=A(e,i,l,a.wranglerPath);return P(r.format)&&U(g),g},L=v(async({cwd:r,logger:o,options:e})=>({code:(await F({allowSchemaDrift:e.allowSchemaDrift===!0,apiSpec:u(e.apiSpec),cwd:r,format:e.format,healthUrl:e.healthUrl,logger:o,target:e.target,typecheck:e.typecheck===!1?!1:void 0})).code}));export{L as execute,F as runVerifyCommand};
@@ -1,2 +1,2 @@
1
- import{mkdtempSync as p,rmSync as c,existsSync as l,readdirSync as u,statSync as y}from"node:fs";import{tmpdir as g}from"node:os";import{join as f,relative as m}from"node:path";import{i as $}from"../packem_shared/command-Bjv4VmYA.mjs";import{M as S,P as z}from"../packem_shared/detect-package-manager-B2eIuAiP.mjs";import{defaultSpawner as B}from"../packem_shared/createRecordingSpawner-ByIqBepG.mjs";const w=t=>{const r=[],e=i=>{for(const o of u(i)){const n=f(i,o),s=y(n);s.isDirectory()?e(n):s.isFile()&&r.push({path:m(t,n),sizeBytes:s.size})}};return e(t),r},d=t=>t<1024?`${String(t)} B`:t<1024*1024?`${(t/1024).toFixed(1)} KiB`:`${(t/(1024*1024)).toFixed(2)} MiB`,h=t=>{const r=w(t),e=r.toSorted((o,n)=>n.sizeBytes-o.sizeBytes),i=r.reduce((o,n)=>o+n.sizeBytes,0);return{generatedFiles:r.filter(o=>o.path.includes("_generated")),outdir:t,topModules:e.slice(0,10),totalBytes:i,totalFiles:r.length}},F=(t,r)=>{if(r.info(`outdir: ${t.outdir}`),r.info(`total: ${String(t.totalFiles)} files, ${d(t.totalBytes)}`),t.topModules.length>0){r.info(""),r.info("top modules by size:");for(const e of t.topModules)r.info(` ${d(e.sizeBytes).padStart(10," ")} ${e.path}`)}if(t.generatedFiles.length>0){r.info(""),r.info(`_generated/ files: ${String(t.generatedFiles.length)}`);for(const e of t.generatedFiles)r.info(` ${d(e.sizeBytes).padStart(10," ")} ${e.path}`)}},v=async t=>{const r=t.cwd??process.cwd(),{logger:e}=t;let i,o,n=!1;if(t.inspectOnly)i=t.inspectOnly;else{i=p(f(g(),"lunora-analyze-")),n=!0;const s=S(z(r),"wrangler",["deploy","--dry-run","--outdir",i]);o={args:s.args,command:s.command,cwd:r},e.info(`analyze: building via ${o.command} ${o.args.join(" ")}`);const a=await(t.spawner??B)(o);if(a.code!==0)return e.error(`analyze: wrangler dry-run failed (exit ${String(a.code)})`),c(i,{force:!0,recursive:!0}),{code:a.code,descriptor:o,report:void 0}}try{if(!l(i))return e.error(`analyze: outdir not found at ${i}`),{code:1,descriptor:o,report:void 0};const s=h(i);return t.json?process.stdout.write(`${JSON.stringify(s,void 0,2)}
1
+ import{mkdtempSync as p,rmSync as c,existsSync as l,readdirSync as u,statSync as y}from"node:fs";import{tmpdir as g}from"node:os";import{join as f,relative as m}from"node:path";import{i as $}from"../packem_shared/command-Bjv4VmYA.mjs";import{M as S,P as z}from"../packem_shared/detect-package-manager-C4aS7HE4.mjs";import{defaultSpawner as B}from"../packem_shared/createRecordingSpawner-ByIqBepG.mjs";const w=t=>{const r=[],e=i=>{for(const o of u(i)){const n=f(i,o),s=y(n);s.isDirectory()?e(n):s.isFile()&&r.push({path:m(t,n),sizeBytes:s.size})}};return e(t),r},d=t=>t<1024?`${String(t)} B`:t<1024*1024?`${(t/1024).toFixed(1)} KiB`:`${(t/(1024*1024)).toFixed(2)} MiB`,h=t=>{const r=w(t),e=r.toSorted((o,n)=>n.sizeBytes-o.sizeBytes),i=r.reduce((o,n)=>o+n.sizeBytes,0);return{generatedFiles:r.filter(o=>o.path.includes("_generated")),outdir:t,topModules:e.slice(0,10),totalBytes:i,totalFiles:r.length}},F=(t,r)=>{if(r.info(`outdir: ${t.outdir}`),r.info(`total: ${String(t.totalFiles)} files, ${d(t.totalBytes)}`),t.topModules.length>0){r.info(""),r.info("top modules by size:");for(const e of t.topModules)r.info(` ${d(e.sizeBytes).padStart(10," ")} ${e.path}`)}if(t.generatedFiles.length>0){r.info(""),r.info(`_generated/ files: ${String(t.generatedFiles.length)}`);for(const e of t.generatedFiles)r.info(` ${d(e.sizeBytes).padStart(10," ")} ${e.path}`)}},v=async t=>{const r=t.cwd??process.cwd(),{logger:e}=t;let i,o,n=!1;if(t.inspectOnly)i=t.inspectOnly;else{i=p(f(g(),"lunora-analyze-")),n=!0;const s=S(z(r),"wrangler",["deploy","--dry-run","--outdir",i]);o={args:s.args,command:s.command,cwd:r},e.info(`analyze: building via ${o.command} ${o.args.join(" ")}`);const a=await(t.spawner??B)(o);if(a.code!==0)return e.error(`analyze: wrangler dry-run failed (exit ${String(a.code)})`),c(i,{force:!0,recursive:!0}),{code:a.code,descriptor:o,report:void 0}}try{if(!l(i))return e.error(`analyze: outdir not found at ${i}`),{code:1,descriptor:o,report:void 0};const s=h(i);return t.json?process.stdout.write(`${JSON.stringify(s,void 0,2)}
2
2
  `):F(s,e),{code:0,descriptor:o,report:s}}finally{if(n&&l(i))try{c(i,{force:!0,recursive:!0})}catch{}}},k=$(({cwd:t,logger:r,options:e})=>v({cwd:t,json:e.json===!0,logger:r}));export{k as execute,v as runAnalyzeCommand};
@@ -1,4 +1,4 @@
1
- import{writeFileSync as $,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-Bjv4VmYA.mjs";import{i as D,d as M,s as F,r as N}from"../packem_shared/output-format-D7cKB-O5.mjs";import{o as g}from"../packem_shared/cli-BxL0WCh4.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(`
1
+ import{writeFileSync as $,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-Bjv4VmYA.mjs";import{i as D,d as M,s as F,r as N}from"../packem_shared/output-format-D7cKB-O5.mjs";import{o as g}from"../packem_shared/cli-0uJWyeda.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,2 +1,2 @@
1
- import{readLinkedProject as g,resolveDeployDriver as p}from"@lunora/config";import{i as f}from"../packem_shared/command-Bjv4VmYA.mjs";import{M as v,P as h}from"../packem_shared/detect-package-manager-B2eIuAiP.mjs";import{defaultSpawner as b}from"../packem_shared/createRecordingSpawner-ByIqBepG.mjs";import{createR2Sql as w}from"@lunora/bindings/r2sql";import{createPipelineLogReader as y}from"@lunora/runtime";const S=new Set(["debug","error","fatal","info","log","trace","warn"]),u=/^\d+$/,c=(r,o)=>{if(r===void 0)return;const t=r.trim();if(u.test(t))return Number(t);const e=Date.parse(t);if(Number.isNaN(e))throw new TypeError(`logs: invalid ${o} "${r}" — pass epoch-millis or an ISO 8601 date`);return e},_=r=>Buffer.from(JSON.stringify(r),"utf8").toString("base64url"),$=r=>{const o=r.trim();if(u.test(o))return{ts:Number(o)};let t;try{t=JSON.parse(Buffer.from(o,"base64url").toString("utf8"))}catch{throw new TypeError(`logs: invalid --cursor "${r}" — expected the token printed by the previous page (or a bare epoch-millis ts)`)}if(typeof t!="object"||t===null||typeof t.ts!="number"||!Number.isFinite(t.ts))throw new TypeError(`logs: invalid --cursor "${r}" — expected the token printed by the previous page (or a bare epoch-millis ts)`);const{ts:e}=t,i=t.seen,n=Array.isArray(i)?i.filter(s=>typeof s=="string"):void 0;return n!==void 0&&n.length>0?{seen:n,ts:e}:{ts:e}},d=(r,o)=>{if(r!==void 0){if(!S.has(r))throw new TypeError(`logs: invalid ${o} "${r}" — expected one of trace, debug, log, info, warn, error, fatal`);return r}},L=r=>{const o={},t=c(r.since,"--since");t!==void 0&&(o.sinceTs=t);const e=c(r.until,"--until");e!==void 0&&(o.untilTs=e);const i=d(r.level,"--level");i!==void 0&&(o.level=i);const n=d(r.minLevel,"--min-level");if(n!==void 0&&(o.minLevel=n),r.functionPrefix!==void 0&&(o.functionPathPrefix=r.functionPrefix),r.traceId!==void 0&&(o.traceId=r.traceId),r.shardKey!==void 0&&(o.shardKey=r.shardKey),r.userId!==void 0&&(o.userId=r.userId),r.limit!==void 0){const s=Number(r.limit);if(!Number.isFinite(s))throw new TypeError(`logs: invalid --limit "${r.limit}" — expected a number`);o.limit=s}return r.cursor!==void 0&&(o.cursor=$(r.cursor)),o},T=r=>{const o=new Date(r.ts).toISOString(),t=r.level.toUpperCase().padEnd(5);return`${o} ${t} ${r.functionPath} ${r.message}`},I=async r=>{const o=r.environment??process.env,t=o.R2_SQL_ACCOUNT_ID,e=o.R2_SQL_TOKEN,i=o.R2_SQL_BUCKET,n=[];if((t===void 0||t.length===0)&&n.push("R2_SQL_ACCOUNT_ID"),(e===void 0||e.length===0)&&n.push("R2_SQL_TOKEN"),(i===void 0||i.length===0)&&n.push("R2_SQL_BUCKET"),(r.table===void 0||r.table.length===0)&&n.push("--table"),n.length>0)return r.logger.error(`logs --durable: R2 SQL not configured (missing ${n.join(", ")}). The Pipeline must write to an R2 Data Catalog (Iceberg) table, and you must supply R2_SQL_ACCOUNT_ID / R2_SQL_TOKEN / R2_SQL_BUCKET plus --table — see the observability docs.`),{code:1,error:"not configured"};let s;try{s=L(r)}catch(a){return r.logger.error(a instanceof Error?a.message:String(a)),{code:1,error:"invalid option"}}const m=w({accountId:t,apiToken:e,bucket:i,fetch:r.fetch}),l=await y(m,{namespace:r.namespace,table:r.table}).query(s);for(const a of l.rows)process.stdout.write(`${r.ndjson===!0?JSON.stringify(a):T(a)}
1
+ import{readLinkedProject as g,resolveDeployDriver as p}from"@lunora/config";import{i as f}from"../packem_shared/command-Bjv4VmYA.mjs";import{M as v,P as h}from"../packem_shared/detect-package-manager-C4aS7HE4.mjs";import{defaultSpawner as b}from"../packem_shared/createRecordingSpawner-ByIqBepG.mjs";import{createR2Sql as w}from"@lunora/bindings/r2sql";import{createPipelineLogReader as y}from"@lunora/runtime";const S=new Set(["debug","error","fatal","info","log","trace","warn"]),u=/^\d+$/,c=(r,o)=>{if(r===void 0)return;const t=r.trim();if(u.test(t))return Number(t);const e=Date.parse(t);if(Number.isNaN(e))throw new TypeError(`logs: invalid ${o} "${r}" — pass epoch-millis or an ISO 8601 date`);return e},_=r=>Buffer.from(JSON.stringify(r),"utf8").toString("base64url"),$=r=>{const o=r.trim();if(u.test(o))return{ts:Number(o)};let t;try{t=JSON.parse(Buffer.from(o,"base64url").toString("utf8"))}catch{throw new TypeError(`logs: invalid --cursor "${r}" — expected the token printed by the previous page (or a bare epoch-millis ts)`)}if(typeof t!="object"||t===null||typeof t.ts!="number"||!Number.isFinite(t.ts))throw new TypeError(`logs: invalid --cursor "${r}" — expected the token printed by the previous page (or a bare epoch-millis ts)`);const{ts:e}=t,i=t.seen,n=Array.isArray(i)?i.filter(s=>typeof s=="string"):void 0;return n!==void 0&&n.length>0?{seen:n,ts:e}:{ts:e}},d=(r,o)=>{if(r!==void 0){if(!S.has(r))throw new TypeError(`logs: invalid ${o} "${r}" — expected one of trace, debug, log, info, warn, error, fatal`);return r}},L=r=>{const o={},t=c(r.since,"--since");t!==void 0&&(o.sinceTs=t);const e=c(r.until,"--until");e!==void 0&&(o.untilTs=e);const i=d(r.level,"--level");i!==void 0&&(o.level=i);const n=d(r.minLevel,"--min-level");if(n!==void 0&&(o.minLevel=n),r.functionPrefix!==void 0&&(o.functionPathPrefix=r.functionPrefix),r.traceId!==void 0&&(o.traceId=r.traceId),r.shardKey!==void 0&&(o.shardKey=r.shardKey),r.userId!==void 0&&(o.userId=r.userId),r.limit!==void 0){const s=Number(r.limit);if(!Number.isFinite(s))throw new TypeError(`logs: invalid --limit "${r.limit}" — expected a number`);o.limit=s}return r.cursor!==void 0&&(o.cursor=$(r.cursor)),o},T=r=>{const o=new Date(r.ts).toISOString(),t=r.level.toUpperCase().padEnd(5);return`${o} ${t} ${r.functionPath} ${r.message}`},I=async r=>{const o=r.environment??process.env,t=o.R2_SQL_ACCOUNT_ID,e=o.R2_SQL_TOKEN,i=o.R2_SQL_BUCKET,n=[];if((t===void 0||t.length===0)&&n.push("R2_SQL_ACCOUNT_ID"),(e===void 0||e.length===0)&&n.push("R2_SQL_TOKEN"),(i===void 0||i.length===0)&&n.push("R2_SQL_BUCKET"),(r.table===void 0||r.table.length===0)&&n.push("--table"),n.length>0)return r.logger.error(`logs --durable: R2 SQL not configured (missing ${n.join(", ")}). The Pipeline must write to an R2 Data Catalog (Iceberg) table, and you must supply R2_SQL_ACCOUNT_ID / R2_SQL_TOKEN / R2_SQL_BUCKET plus --table — see the observability docs.`),{code:1,error:"not configured"};let s;try{s=L(r)}catch(a){return r.logger.error(a instanceof Error?a.message:String(a)),{code:1,error:"invalid option"}}const m=w({accountId:t,apiToken:e,bucket:i,fetch:r.fetch}),l=await y(m,{namespace:r.namespace,table:r.table}).query(s);for(const a of l.rows)process.stdout.write(`${r.ndjson===!0?JSON.stringify(a):T(a)}
2
2
  `);return l.rows.length===0?r.logger.info("logs --durable: no matching log records"):l.nextCursor!==void 0&&r.logger.info(`logs --durable: more rows available — pass --cursor ${_(l.nextCursor)} for the next page`),{code:0,rows:l.rows}},N=new Set(["json","pretty"]),x=async r=>{const o=r.cwd??process.cwd();if(r.format!==void 0&&!N.has(r.format))return r.logger.error(`logs: unknown --format "${r.format}" — expected pretty | json`),{code:1,descriptor:void 0,error:"invalid format"};const t=r.env??g(o)?.env,e=p(r.target);if(e.toolchain===void 0)return r.logger.error(`logs: deploy target "${e.id}" has no command-line toolchain`),{code:1,descriptor:void 0,error:"no toolchain"};const i=e.toolchain.tail({environment:t,format:r.format,search:r.search,status:r.status,temporary:r.temporary,worker:r.worker}),n=v(h(o),i.tool,i.args),s={args:n.args,command:n.command,cwd:o};return r.logger.info(`tailing logs via ${s.command} ${s.args.join(" ")}`),{code:(await(r.spawner??b)(s)).code,descriptor:s}},Q=f(({argument:r,cwd:o,logger:t,options:e})=>e.durable===!0?I({cursor:e.cursor,functionPrefix:e.functionPrefix,level:e.level,limit:e.limit,logger:t,minLevel:e.minLevel,namespace:e.namespace,ndjson:e.ndjson===!0,shardKey:e.shardKey,since:e.since,table:e.table,traceId:e.traceId,until:e.until,userId:e.userId}):x({cwd:o,env:e.env,format:e.format,logger:t,search:e.search,status:e.status,target:e.target,temporary:e.temporary===!0,worker:r[0]}));export{Q as execute,x as runLogsCommand};
@@ -1,4 +1,4 @@
1
- import{t as J}from"../packem_shared/cli-BxL0WCh4.mjs";import{i as W}from"../packem_shared/command-Bjv4VmYA.mjs";import{existsSync as u,readFileSync as y,realpathSync as D,statSync as T,writeFileSync as z,chmodSync as H,renameSync as I,unlinkSync as K,mkdirSync as q}from"node:fs";import{homedir as w}from"node:os";import{findWranglerFile as G}from"@lunora/config/cloudflare";import{join as s,dirname as V,relative as Z}from"@visulima/path";import{P as B,M as Q}from"../packem_shared/detect-package-manager-B2eIuAiP.mjs";import{stringify as X}from"smol-toml";import{modify as x,applyEdits as C,parse as Y}from"jsonc-parser";import{readLiveDevServerState as b}from"@lunora/config";import{resolveAdminToken as oo}from"@lunora/config/studio-host";import{connectLocalStdio as to}from"@lunora/mcp";const m=o=>({args:[...o.args],command:o.command,...o.env===void 0?{}:{env:o.env}}),$=o=>o.transport==="http"?{type:"http",url:o.url}:m(o),eo=o=>o.transport==="http"?{httpUrl:o.url}:m(o),ro=o=>o.transport==="http"?{serverUrl:o.url}:m(o),no=o=>({args:["-y","mcp-remote",o],command:"npx"}),ao=o=>o.transport==="http"?no(o.url):m(o),io=o=>o.transport==="http"?{url:o.url}:m(o),lo=o=>o.transport==="http"?{enabled:!0,type:"remote",url:o.url}:{command:[o.command,...o.args],enabled:!0,type:"local",...o.env===void 0?{}:{environment:o.env}},so=o=>o.transport==="http"?{disabled:!1,type:"streamableHttp",url:o.url}:{disabled:!1,...m(o)},co=({home:o,platform:t})=>{if(t==="darwin")return{global:s(o,"Library","Application Support","Claude","claude_desktop_config.json")};if(t==="win32"){const e=process.env.APPDATA;return e===void 0||e===""?{}:{global:s(e,"Claude","claude_desktop_config.json")}}return t==="linux"?{global:s(o,".config","Claude","claude_desktop_config.json")}:{}},po=(o,t)=>X({mcp_servers:{[o]:t.transport==="http"?{url:t.url}:{args:[...t.args],command:t.command,...t.env===void 0?{}:{env:t.env}}}}),h=[{buildEntry:$,paths:({projectRoot:o})=>({project:s(o,".mcp.json")}),format:"json",id:"claude-code",key:"mcpServers",label:"Claude Code"},{buildEntry:$,paths:({home:o,projectRoot:t})=>({global:s(o,".cursor","mcp.json"),project:s(t,".cursor","mcp.json")}),format:"json",id:"cursor",key:"mcpServers",label:"Cursor"},{buildEntry:$,paths:({projectRoot:o})=>({project:s(o,".vscode","mcp.json")}),format:"json",id:"vscode",key:"servers",label:"VS Code (GitHub Copilot)"},{buildEntry:eo,paths:({home:o,projectRoot:t})=>({global:s(o,".gemini","settings.json"),project:s(t,".gemini","settings.json")}),format:"json",id:"gemini",key:"mcpServers",label:"Gemini CLI"},{buildEntry:ao,paths:co,format:"json",id:"claude-desktop",key:"mcpServers",label:"Claude Desktop"},{buildEntry:ro,paths:({home:o})=>({global:s(o,".codeium","windsurf","mcp_config.json")}),format:"json",id:"windsurf",key:"mcpServers",label:"Windsurf"},{buildEntry:lo,paths:({home:o,projectRoot:t})=>({global:s(o,".config","opencode","opencode.json"),project:s(t,"opencode.json")}),format:"json",id:"opencode",key:"mcp",label:"OpenCode"},{buildEntry:so,paths:({home:o})=>({global:s(o,".cline","mcp.json")}),format:"json",id:"cline",key:"mcpServers",label:"Cline"},{buildEntry:io,paths:({home:o})=>({global:s(o,".config","zed","settings.json")}),format:"json",id:"zed",key:"context_servers",label:"Zed"},{paths:({home:o,projectRoot:t})=>({global:s(o,".codex","config.toml"),project:s(t,".codex","config.toml")}),format:"manual",id:"codex",label:"Codex CLI",renderSnippet:po}],E=h.map(o=>o.id),uo=o=>h.find(t=>t.id===o.toLowerCase()),v=(o,t)=>{let e=o,r;try{e=D(o),r=T(e).mode}catch{}const n=`${e}.lunora-${Math.random().toString(36).slice(2,10)}.tmp`;try{z(n,t,"utf8"),r!==void 0&&H(n,r),I(n,e)}catch(a){try{K(n)}catch{}throw a}},R={formattingOptions:{insertSpaces:!0,tabSize:4}},k=o=>{const t=[],e=Y(o,t,{allowTrailingComma:!0});return{errors:t,value:e}},g=o=>typeof o=="object"&&o!==null&&!Array.isArray(o),j=(o,t,e)=>{if(!g(o))return;const r=o[t];return g(r)?r[e]:void 0},U=o=>{if(!u(o.path))return"absent";let t;try{t=y(o.path,"utf8")}catch{return"invalid"}if(t.trim().length===0)return"absent";const{errors:e,value:r}=k(t);return e.length>0||!g(r)?"invalid":j(r,o.key,o.name)===void 0?"absent":"present"},mo=o=>U(o)==="present",fo=o=>{const{entry:t,force:e=!1,key:r,name:n,path:a}=o;if(!u(a))return q(V(a),{recursive:!0}),v(a,`${JSON.stringify({[r]:{[n]:t}},void 0,4)}
1
+ import{i as J}from"../packem_shared/cli-0uJWyeda.mjs";import{i as W}from"../packem_shared/command-Bjv4VmYA.mjs";import{existsSync as u,readFileSync as y,realpathSync as D,statSync as T,writeFileSync as z,chmodSync as H,renameSync as I,unlinkSync as K,mkdirSync as q}from"node:fs";import{homedir as w}from"node:os";import{findWranglerFile as G}from"@lunora/config/cloudflare";import{join as s,dirname as V,relative as Z}from"@visulima/path";import{P as B,M as Q}from"../packem_shared/detect-package-manager-C4aS7HE4.mjs";import{stringify as X}from"smol-toml";import{modify as x,applyEdits as C,parse as Y}from"jsonc-parser";import{readLiveDevServerState as b}from"@lunora/config";import{resolveAdminToken as oo}from"@lunora/config/studio-host";import{connectLocalStdio as to}from"@lunora/mcp";const m=o=>({args:[...o.args],command:o.command,...o.env===void 0?{}:{env:o.env}}),$=o=>o.transport==="http"?{type:"http",url:o.url}:m(o),eo=o=>o.transport==="http"?{httpUrl:o.url}:m(o),ro=o=>o.transport==="http"?{serverUrl:o.url}:m(o),no=o=>({args:["-y","mcp-remote",o],command:"npx"}),ao=o=>o.transport==="http"?no(o.url):m(o),io=o=>o.transport==="http"?{url:o.url}:m(o),lo=o=>o.transport==="http"?{enabled:!0,type:"remote",url:o.url}:{command:[o.command,...o.args],enabled:!0,type:"local",...o.env===void 0?{}:{environment:o.env}},so=o=>o.transport==="http"?{disabled:!1,type:"streamableHttp",url:o.url}:{disabled:!1,...m(o)},co=({home:o,platform:t})=>{if(t==="darwin")return{global:s(o,"Library","Application Support","Claude","claude_desktop_config.json")};if(t==="win32"){const e=process.env.APPDATA;return e===void 0||e===""?{}:{global:s(e,"Claude","claude_desktop_config.json")}}return t==="linux"?{global:s(o,".config","Claude","claude_desktop_config.json")}:{}},po=(o,t)=>X({mcp_servers:{[o]:t.transport==="http"?{url:t.url}:{args:[...t.args],command:t.command,...t.env===void 0?{}:{env:t.env}}}}),h=[{buildEntry:$,paths:({projectRoot:o})=>({project:s(o,".mcp.json")}),format:"json",id:"claude-code",key:"mcpServers",label:"Claude Code"},{buildEntry:$,paths:({home:o,projectRoot:t})=>({global:s(o,".cursor","mcp.json"),project:s(t,".cursor","mcp.json")}),format:"json",id:"cursor",key:"mcpServers",label:"Cursor"},{buildEntry:$,paths:({projectRoot:o})=>({project:s(o,".vscode","mcp.json")}),format:"json",id:"vscode",key:"servers",label:"VS Code (GitHub Copilot)"},{buildEntry:eo,paths:({home:o,projectRoot:t})=>({global:s(o,".gemini","settings.json"),project:s(t,".gemini","settings.json")}),format:"json",id:"gemini",key:"mcpServers",label:"Gemini CLI"},{buildEntry:ao,paths:co,format:"json",id:"claude-desktop",key:"mcpServers",label:"Claude Desktop"},{buildEntry:ro,paths:({home:o})=>({global:s(o,".codeium","windsurf","mcp_config.json")}),format:"json",id:"windsurf",key:"mcpServers",label:"Windsurf"},{buildEntry:lo,paths:({home:o,projectRoot:t})=>({global:s(o,".config","opencode","opencode.json"),project:s(t,"opencode.json")}),format:"json",id:"opencode",key:"mcp",label:"OpenCode"},{buildEntry:so,paths:({home:o})=>({global:s(o,".cline","mcp.json")}),format:"json",id:"cline",key:"mcpServers",label:"Cline"},{buildEntry:io,paths:({home:o})=>({global:s(o,".config","zed","settings.json")}),format:"json",id:"zed",key:"context_servers",label:"Zed"},{paths:({home:o,projectRoot:t})=>({global:s(o,".codex","config.toml"),project:s(t,".codex","config.toml")}),format:"manual",id:"codex",label:"Codex CLI",renderSnippet:po}],E=h.map(o=>o.id),uo=o=>h.find(t=>t.id===o.toLowerCase()),v=(o,t)=>{let e=o,r;try{e=D(o),r=T(e).mode}catch{}const n=`${e}.lunora-${Math.random().toString(36).slice(2,10)}.tmp`;try{z(n,t,"utf8"),r!==void 0&&H(n,r),I(n,e)}catch(a){try{K(n)}catch{}throw a}},R={formattingOptions:{insertSpaces:!0,tabSize:4}},k=o=>{const t=[],e=Y(o,t,{allowTrailingComma:!0});return{errors:t,value:e}},g=o=>typeof o=="object"&&o!==null&&!Array.isArray(o),j=(o,t,e)=>{if(!g(o))return;const r=o[t];return g(r)?r[e]:void 0},U=o=>{if(!u(o.path))return"absent";let t;try{t=y(o.path,"utf8")}catch{return"invalid"}if(t.trim().length===0)return"absent";const{errors:e,value:r}=k(t);return e.length>0||!g(r)?"invalid":j(r,o.key,o.name)===void 0?"absent":"present"},mo=o=>U(o)==="present",fo=o=>{const{entry:t,force:e=!1,key:r,name:n,path:a}=o;if(!u(a))return q(V(a),{recursive:!0}),v(a,`${JSON.stringify({[r]:{[n]:t}},void 0,4)}
2
2
  `),{action:"created",path:a};const i=y(a,"utf8");if(i.trim().length===0)return v(a,`${JSON.stringify({[r]:{[n]:t}},void 0,4)}
3
3
  `),{action:"created",path:a};const{errors:l,value:c}=k(i);if(l.length>0)return{action:"invalid",error:`parse error at offset ${String(l[0]?.offset??0)}`,path:a};if(!g(c))return{action:"invalid",error:"the file's root is not a JSON object",path:a};const f=c[r];if(f!==void 0&&!g(f))return{action:"invalid",error:`"${r}" is not an object`,path:a};if(j(c,r,n)!==void 0&&!e)return{action:"skipped",path:a};try{const d=x(i,[r,n],t,R);d.length>0&&v(a,C(i,d))}catch(d){return{action:"invalid",error:d instanceof Error?d.message:String(d),path:a}}return{action:"updated",path:a}},go=o=>{const{key:t,name:e,path:r}=o;if(!u(r))return{action:"absent",path:r};let n;try{n=y(r,"utf8")}catch(l){return{action:"invalid",error:l instanceof Error?l.message:String(l),path:r}}const{errors:a,value:i}=k(n);if(a.length>0)return{action:"invalid",error:`parse error at offset ${String(a[0]?.offset??0)}`,path:r};if(j(i,t,e)===void 0)return{action:"absent",path:r};try{const l=x(n,[t,e],void 0,R);l.length>0&&v(r,C(n,l))}catch(l){return{action:"invalid",error:l instanceof Error?l.message:String(l),path:r}}return{action:"removed",path:r}},ho=["global","project"],p=(o,t)=>{const e=Z(t,o);return e.length>0&&!e.startsWith("..")?e:o},vo=(o,t)=>{const e=o.paths(t);return ho.flatMap(r=>{const n=e[r];return n===void 0?[]:[{client:o,path:n,scope:r}]})},yo=(o,t,e,r)=>{const n=o.paths(t),a=e==="global"?"project":"global",i=n[e]??(r?void 0:n[a]);if(i!==void 0)return{client:o,path:i,scope:n[e]===void 0?a:e}},$o=o=>h.filter(t=>Object.values(t.paths(o)).some(e=>u(e))),N=(o,t,e,r)=>{if(o.length===0)return t();const n=[];for(const a of o){const i=uo(a);if(i===void 0){e.error(`mcp ${r}: unknown client "${a}". Known clients: ${E.join(", ")}.`);return}n.push(i)}return n},bo=o=>o.client.format==="json",wo="https://lunora.sh/mcp",_="lunora-docs",M="lunora",ko=o=>u(s(o,"lunora"))&&G(o)!==void 0,jo=o=>{const{args:t,command:e}=Q(o,"lunora",["mcp","serve"]);return{args:t,command:e,transport:"stdio"}},So=o=>({transport:"http",url:o}),Oo=o=>({home:o.home,platform:o.platform,projectRoot:o.cwd}),A=(o,t,e)=>yo(o,Oo(e),e.scope??t.preferredScope,e.scope!==void 0||!t.allowScopeFallback),xo=(o,t,e)=>{const r=A(o,t,e);if(r===void 0){e.logger.warn(`${o.label}: has no ${e.scope??t.preferredScope}-scoped config — skipped "${t.name}".`);return}const{path:n}=r,a=o.buildEntry(t.spec);if(e.print===!0){const c=p(n,e.cwd);return e.force!==!0&&mo({key:o.key,name:t.name,path:n})?(e.logger.info(`${o.label}: "${t.name}" already configured in ${c} — a real install would skip it (re-run with --force to replace).`),{action:"printed",path:n}):(e.logger.info(`${o.label} → ${c}
4
4
  ${JSON.stringify({[o.key]:{[t.name]:a}},void 0,4)}`),{action:"printed",path:n})}const i=fo({entry:a,force:e.force===!0,key:o.key,name:t.name,path:n}),l=p(n,e.cwd);return i.action==="invalid"?e.logger.error(`${o.label}: ${l} is not valid JSON (${i.error??"unknown error"}) — left untouched.`):i.action==="skipped"?e.logger.info(`${o.label}: "${t.name}" already configured in ${l} — re-run with --force to replace it.`):e.logger.success(`${o.label}: ${i.action==="created"?"created":"updated"} ${l} with "${t.name}".`),{action:i.action,path:n}},Co=(o,t,e)=>{const r=A(o,t,e)?.path;if(r===void 0){e.logger.warn(`${o.label}: no known config location on ${e.platform} — skipped.`);return}return e.logger.info(`${o.label}: add this to ${p(r,e.cwd)}
@@ -1,2 +1,2 @@
1
- import{existsSync as l}from"node:fs";import{mkdir as m,readFile as f,writeFile as g}from"node:fs/promises";import{join as s}from"node:path";import{LunoraError as k}from"@lunora/errors";import{u as w}from"../packem_shared/admin-url-Ca-KI3d_.mjs";import{i as b}from"../packem_shared/command-Bjv4VmYA.mjs";import{s as y}from"../packem_shared/resolve-target-vxaXHmvg.mjs";import{runExportCommand as h,runImportCommand as $}from"../packem_shared/DEFAULT_IMPORT_BATCH_SIZE-CEOt386P.mjs";const v=".lunora-backups",p="manifest.json",S="/_lunora/admin/pitr",N="__lunora_admin__:getPitrBookmark",_="__lunora_admin__:pitrRestore",O=t=>typeof t=="object"&&t!==null&&typeof t.id=="string"&&typeof t.file=="string",u=async t=>{const o=s(t,p);if(!l(o))return[];let r;try{r=JSON.parse(await f(o,"utf8"))}catch(e){const a=e instanceof Error?e.message:String(e);throw new k("INTERNAL",`backup: ${o} exists but is not valid JSON (${a}) — refusing to overwrite it; fix or remove it manually`,{cause:e})}if(!Array.isArray(r))throw new TypeError(`backup: ${o} exists but is not a JSON array — refusing to overwrite it; fix or remove it manually`);return r.filter(O)},x=async(t,o)=>{await g(s(t,p),`${JSON.stringify(o,void 0,2)}
1
+ import{existsSync as l}from"node:fs";import{mkdir as m,readFile as f,writeFile as g}from"node:fs/promises";import{join as s}from"node:path";import{LunoraError as k}from"@lunora/errors";import{u as w}from"../packem_shared/admin-url-Ca-KI3d_.mjs";import{i as b}from"../packem_shared/command-Bjv4VmYA.mjs";import{s as y}from"../packem_shared/resolve-target-vxaXHmvg.mjs";import{runExportCommand as h,runImportCommand as $}from"../packem_shared/DEFAULT_IMPORT_BATCH_SIZE-xn-frBqK.mjs";const v=".lunora-backups",p="manifest.json",S="/_lunora/admin/pitr",N="__lunora_admin__:getPitrBookmark",_="__lunora_admin__:pitrRestore",O=t=>typeof t=="object"&&t!==null&&typeof t.id=="string"&&typeof t.file=="string",u=async t=>{const o=s(t,p);if(!l(o))return[];let r;try{r=JSON.parse(await f(o,"utf8"))}catch(e){const a=e instanceof Error?e.message:String(e);throw new k("INTERNAL",`backup: ${o} exists but is not valid JSON (${a}) — refusing to overwrite it; fix or remove it manually`,{cause:e})}if(!Array.isArray(r))throw new TypeError(`backup: ${o} exists but is not a JSON array — refusing to overwrite it; fix or remove it manually`);return r.filter(O)},x=async(t,o)=>{await g(s(t,p),`${JSON.stringify(o,void 0,2)}
2
2
  `,"utf8")},I=async(t,o)=>{await m(o,{recursive:!0});const r=(t.now??(()=>new Date))().toISOString(),e=`lunora-backup-${r.replaceAll(/[.:]/gu,"-")}.ndjson`,a=await h({cwd:t.cwd,fetchImpl:t.fetchImpl,logger:t.logger,out:s(o,e),prod:t.prod,tables:t.tables,token:t.token,url:t.url});if(a.code!==0)return{code:a.code};const i={bytes:a.bytes,createdAt:r,file:e,id:r,rows:a.rows,tables:t.tables},n=await u(o);return n.push(i),await x(o,n),t.logger.success(`backup created: ${e} (${a.rows.toString()} rows, ${a.bytes.toString()} bytes)`),{code:0,entry:i}},A=async(t,o)=>{const r=await u(o);if(r.length===0)return t.logger.info(`no backups found in ${o}`),{code:0};for(const e of r)t.logger.info(`${e.id} ${e.rows.toString()} rows ${e.bytes.toString()} bytes ${e.file}`);return{code:0}},E=async(t,o)=>{const{target:r}=t;if(r===void 0||r.length===0)return t.logger.error("restore requires a backup id or file path. Usage: lunora backup restore <id|file>"),{code:1};const e=(await u(o)).find(i=>i.id===r),a=e?s(o,e.file):r;return l(a)?{code:(await $({cwd:t.cwd,fetchImpl:t.fetchImpl,file:a,logger:t.logger,prod:t.prod,token:t.token,url:t.url,yes:t.yes})).code}:(t.logger.error(`backup not found: ${r}`),{code:1})},T=t=>{const o=t.token??process.env.LUNORA_ADMIN_TOKEN;if(!o){t.logger.error("admin token required — pass --token or set LUNORA_ADMIN_TOKEN");return}if(t.prod&&t.url===void 0){t.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)");return}if(t.restore===!0&&t.at===void 0&&t.bookmark===void 0){t.logger.error("pitr --restore requires --at <time> or --bookmark <bookmark>");return}if(t.restore===!0&&t.prod===!0&&t.yes!==!0){t.logger.error("pitr --restore --prod restores production data in place. Re-run with --yes to confirm.");return}const r=w(t.url,t.logger,t.cwd);if(r===void 0)return;const e=t.pitrFetch??globalThis.fetch;if(typeof e!="function")throw new TypeError("no fetch implementation available — pass pitrFetch or run on Node >= 18");return{fetchImpl:e,requestUrl:`${r}${S}`,token:o}},q=(t,o)=>{const r={};return t.at!==void 0&&(r.time=t.at),o&&t.bookmark!==void 0&&(r.bookmark=t.bookmark),o&&t.restart===!0&&(r.restart=!0),r},J=async t=>{const o=T(t);if(o===void 0)return{code:1};const r=t.restore===!0,e=r?_:N,a=q(t,r),i=r?"restore":"bookmark";t.logger.info(`POST ${o.requestUrl} -> pitr ${i}${t.shard===void 0?"":` (shard "${t.shard}")`}`);const n=await o.fetchImpl(o.requestUrl,{body:JSON.stringify({args:a,functionPath:e,shardKey:t.shard}),headers:{authorization:`Bearer ${o.token}`,"content-type":"application/json"},method:"POST"}),d=await n.text();let c;try{c=JSON.parse(d)}catch{c=d}return t.logger.info(JSON.stringify(c,void 0,2)),{code:n.ok?0:1}},R=async t=>{const o=t.cwd??process.cwd(),r=s(o,t.dir??v);try{return t.subcommand==="create"?await I(t,r):t.subcommand==="list"?await A(t,r):t.subcommand==="pitr"?await J(t):await E(t,r)}catch(e){return t.logger.error(e instanceof Error?e.message:String(e)),{code:1}}},U=t=>t==="create"||t==="list"||t==="pitr"||t==="restore",M=b(({argument:t,cwd:o,logger:r,options:e})=>{const a=t[0];return U(a)?R({at:e.at,bookmark:e.bookmark,cwd:o,dir:e.dir,logger:r,prod:e.prod===!0,restart:e.restart===!0,restore:e.restore===!0,shard:e.shard,subcommand:a,tables:e.tables,target:t[1],token:e.token,url:y({cwd:o,prod:e.prod===!0,url:e.url}),yes:e.yes===!0}):(r.error(`backup: unknown subcommand "${a??""}" — expected create | list | restore | pitr`),{code:1})});export{M as execute,R as runBackupCommand};
@@ -1 +1 @@
1
- import{i as d}from"../packem_shared/command-Bjv4VmYA.mjs";import{M as g,P as m}from"../packem_shared/detect-package-manager-B2eIuAiP.mjs";import{r as p}from"../packem_shared/docker-CKvYE9YF.mjs";import{defaultSpawner as l}from"../packem_shared/createRecordingSpawner-ByIqBepG.mjs";const i=new Set(["build","delete","images","info","list","push"]),h=new Set(["build","push"]),w=async r=>{const[a,...n]=r.argument;if(a===void 0||!i.has(a))return r.logger.error(`lunora containers requires a subcommand: ${[...i].toSorted((c,u)=>c.localeCompare(u)).join(" | ")}. Example: lunora containers build ./containers/app --tag app:v1 --push`),{code:1};if(h.has(a)&&!(r.dockerAvailable??p)())return r.logger.error(`containers ${a} needs a running Docker-compatible engine (it builds/pushes images locally). Start Docker or Colima and retry. Note: container images must target linux/amd64.`),{code:1};const o=["containers",a,...n];r.tag!==void 0&&o.push("--tag",r.tag),r.push===!0&&o.push("--push"),r.env!==void 0&&o.push("--env",r.env);const t=r.cwd??process.cwd(),s=g(m(t),"wrangler",o),e={args:s.args,command:s.command,cwd:t};return r.logger.info(`running ${e.command} ${e.args.join(" ")}`),{code:(await(r.spawner??l)(e)).code,descriptor:e}},C=d(async({argument:r,cwd:a,logger:n,options:o})=>({code:(await w({argument:r,cwd:a,env:o.env,logger:n,push:o.push===!0,tag:o.tag})).code}));export{C as execute,w as runContainersCommand};
1
+ import{i as d}from"../packem_shared/command-Bjv4VmYA.mjs";import{M as g,P as m}from"../packem_shared/detect-package-manager-C4aS7HE4.mjs";import{r as p}from"../packem_shared/docker-CKvYE9YF.mjs";import{defaultSpawner as l}from"../packem_shared/createRecordingSpawner-ByIqBepG.mjs";const i=new Set(["build","delete","images","info","list","push"]),h=new Set(["build","push"]),w=async r=>{const[a,...n]=r.argument;if(a===void 0||!i.has(a))return r.logger.error(`lunora containers requires a subcommand: ${[...i].toSorted((c,u)=>c.localeCompare(u)).join(" | ")}. Example: lunora containers build ./containers/app --tag app:v1 --push`),{code:1};if(h.has(a)&&!(r.dockerAvailable??p)())return r.logger.error(`containers ${a} needs a running Docker-compatible engine (it builds/pushes images locally). Start Docker or Colima and retry. Note: container images must target linux/amd64.`),{code:1};const o=["containers",a,...n];r.tag!==void 0&&o.push("--tag",r.tag),r.push===!0&&o.push("--push"),r.env!==void 0&&o.push("--env",r.env);const t=r.cwd??process.cwd(),s=g(m(t),"wrangler",o),e={args:s.args,command:s.command,cwd:t};return r.logger.info(`running ${e.command} ${e.args.join(" ")}`),{code:(await(r.spawner??l)(e)).code,descriptor:e}},C=d(async({argument:r,cwd:a,logger:n,options:o})=>({code:(await w({argument:r,cwd:a,env:o.env,logger:n,push:o.push===!0,tag:o.tag})).code}));export{C as execute,w as runContainersCommand};
@@ -1 +1 @@
1
- import{i as d}from"../packem_shared/command-Bjv4VmYA.mjs";import{M as a,P as m}from"../packem_shared/detect-package-manager-B2eIuAiP.mjs";import{defaultSpawner as c}from"../packem_shared/createRecordingSpawner-ByIqBepG.mjs";const i=(r,e)=>(e!==void 0&&r.push("--env",e),r),p=r=>{const e=i(["deployments","list"],r.env);return r.json&&e.push("--json"),e},u=r=>{switch(r.subcommand){case"inspect":return r.versionId===void 0?{error:"deployments inspect requires a version id. Usage: lunora deployments inspect <version-id>"}:{args:i(["versions","view",r.versionId],r.env)};case"list":return{args:p(r)};case"promote":{if(r.versionId===void 0)return{error:"deployments promote requires a version id. Usage: lunora deployments promote <version-id> --yes"};if(!r.yes)return{error:"deployments promote shifts 100% of live traffic. Re-run with --yes to confirm."};const e=i(["versions","deploy",`${r.versionId}@100%`,"--yes"],r.env);return r.message!==void 0&&e.push("--message",r.message),{args:e}}case"rollback":{if(!r.yes)return{error:"deployments rollback changes the live version. Re-run with --yes to confirm."};const e=i(["rollback"],r.env);return r.versionId!==void 0&&e.push(r.versionId),e.push("--yes"),r.message!==void 0&&e.push("--message",r.message),{args:e}}default:return{error:`deployments: unknown subcommand "${r.subcommand}"`}}},l=async r=>{const{args:e,error:s}=u(r);if(s!==void 0||e===void 0)return r.logger.error(s??"deployments: nothing to run"),{code:1,descriptor:void 0,error:s};const o=r.cwd??process.cwd(),n=a(m(o),"wrangler",e),t={args:n.args,command:n.command,cwd:o};return r.logger.info(`${t.command} ${t.args.join(" ")}`),{code:(await(r.spawner??c)(t)).code,descriptor:t}},v=r=>r==="list"||r==="inspect"||r==="rollback"||r==="promote",w=d(({argument:r,cwd:e,logger:s,options:o})=>{const n=r[0];return v(n)?l({cwd:e,env:o.env,json:o.json===!0,logger:s,message:o.message,subcommand:n,versionId:r[1],yes:o.yes===!0}):(s.error(`deployments: unknown subcommand "${n??""}" — expected list | inspect | rollback | promote`),{code:1})});export{w as execute,l as runDeploymentsCommand};
1
+ import{i as d}from"../packem_shared/command-Bjv4VmYA.mjs";import{M as a,P as m}from"../packem_shared/detect-package-manager-C4aS7HE4.mjs";import{defaultSpawner as c}from"../packem_shared/createRecordingSpawner-ByIqBepG.mjs";const i=(r,e)=>(e!==void 0&&r.push("--env",e),r),p=r=>{const e=i(["deployments","list"],r.env);return r.json&&e.push("--json"),e},u=r=>{switch(r.subcommand){case"inspect":return r.versionId===void 0?{error:"deployments inspect requires a version id. Usage: lunora deployments inspect <version-id>"}:{args:i(["versions","view",r.versionId],r.env)};case"list":return{args:p(r)};case"promote":{if(r.versionId===void 0)return{error:"deployments promote requires a version id. Usage: lunora deployments promote <version-id> --yes"};if(!r.yes)return{error:"deployments promote shifts 100% of live traffic. Re-run with --yes to confirm."};const e=i(["versions","deploy",`${r.versionId}@100%`,"--yes"],r.env);return r.message!==void 0&&e.push("--message",r.message),{args:e}}case"rollback":{if(!r.yes)return{error:"deployments rollback changes the live version. Re-run with --yes to confirm."};const e=i(["rollback"],r.env);return r.versionId!==void 0&&e.push(r.versionId),e.push("--yes"),r.message!==void 0&&e.push("--message",r.message),{args:e}}default:return{error:`deployments: unknown subcommand "${r.subcommand}"`}}},l=async r=>{const{args:e,error:s}=u(r);if(s!==void 0||e===void 0)return r.logger.error(s??"deployments: nothing to run"),{code:1,descriptor:void 0,error:s};const o=r.cwd??process.cwd(),n=a(m(o),"wrangler",e),t={args:n.args,command:n.command,cwd:o};return r.logger.info(`${t.command} ${t.args.join(" ")}`),{code:(await(r.spawner??c)(t)).code,descriptor:t}},v=r=>r==="list"||r==="inspect"||r==="rollback"||r==="promote",w=d(({argument:r,cwd:e,logger:s,options:o})=>{const n=r[0];return v(n)?l({cwd:e,env:o.env,json:o.json===!0,logger:s,message:o.message,subcommand:n,versionId:r[1],yes:o.yes===!0}):(s.error(`deployments: unknown subcommand "${n??""}" — expected list | inspect | rollback | promote`),{code:1})});export{w as execute,l as runDeploymentsCommand};
@@ -1,4 +1,4 @@
1
- import{existsSync as f,readFileSync as m,writeFileSync as $}from"node:fs";import{join as S}from"node:path";import{DEV_VARS_FILE as u,DEV_VARS_KEY_PATTERN as b,resolveDeployDriver as R,resolveProjectTarget as _,generateSecretValue as x,DEV_VARS_EXAMPLE_FILE as v,parseDevVariableEntries as E,isPlaceholderValue as L,packageNamesFromBindings as z,inferLunoraBindings as K,requiredSecrets as Y,isMintableSecretKey as k}from"@lunora/config";import{i as j}from"../packem_shared/command-Bjv4VmYA.mjs";import{P as q,M as U}from"../packem_shared/detect-package-manager-B2eIuAiP.mjs";import{defaultSpawner as C}from"../packem_shared/createRecordingSpawner-ByIqBepG.mjs";import{R as D}from"../packem_shared/wrangler-secrets-DDDUuryf.mjs";const M=/[\r\n]/u,F=/["\\]/u,V=e=>{const o=new Map;for(const t of E(e))o.set(t.key,t);return o},Z=e=>e.replaceAll(/[.*+?^${}()|[\]\\]/gu,String.raw`\$&`),w=(e,o)=>new RegExp(String.raw`^[ \t]*${Z(e)}[ \t]*=.*(\r?\n|$)`,o?"gmu":"mu"),P=(e,o,t)=>{const r=`${o}="${t}"`;if(!w(o,!1).test(e))return e===""?`${r}
1
+ import{existsSync as f,readFileSync as m,writeFileSync as $}from"node:fs";import{join as S}from"node:path";import{DEV_VARS_FILE as u,DEV_VARS_KEY_PATTERN as b,resolveDeployDriver as R,resolveProjectTarget as _,generateSecretValue as x,DEV_VARS_EXAMPLE_FILE as v,parseDevVariableEntries as E,isPlaceholderValue as L,packageNamesFromBindings as z,inferLunoraBindings as K,requiredSecrets as Y,isMintableSecretKey as k}from"@lunora/config";import{i as j}from"../packem_shared/command-Bjv4VmYA.mjs";import{P as q,M as U}from"../packem_shared/detect-package-manager-C4aS7HE4.mjs";import{defaultSpawner as C}from"../packem_shared/createRecordingSpawner-ByIqBepG.mjs";import{R as D}from"../packem_shared/wrangler-secrets-DHpbsDN9.mjs";const M=/[\r\n]/u,F=/["\\]/u,V=e=>{const o=new Map;for(const t of E(e))o.set(t.key,t);return o},Z=e=>e.replaceAll(/[.*+?^${}()|[\]\\]/gu,String.raw`\$&`),w=(e,o)=>new RegExp(String.raw`^[ \t]*${Z(e)}[ \t]*=.*(\r?\n|$)`,o?"gmu":"mu"),P=(e,o,t)=>{const r=`${o}="${t}"`;if(!w(o,!1).test(e))return e===""?`${r}
2
2
  `:e.endsWith(`
3
3
  `)?`${e}${r}
4
4
  `:`${e}
@@ -1,4 +1,4 @@
1
- import{spawnSync as I,spawn as J}from"node:child_process";import{existsSync as N,watch as me,readFileSync as K,statSync as fe,openSync as z,readSync as ve,closeSync as Y,mkdirSync as we}from"node:fs";import{join as k,dirname as he}from"node:path";import{runCodegen as X}from"@lunora/codegen";import{detectAgentRules as Z,claimDevServerState as Q,clearDevServerState as f,readDevServerState as R,readLiveDevServerState as y,detectFramework as ee,readProjectDependencyNames as Se,DEV_HANDOFF_ENV as h,isRecordedProcessCurrent as ke,DEV_LOG_FILE as ye,DEV_LOG_FILE_ENV as re,DEV_DAEMON_ENV as T,updateDevServerState as oe,detectAiAgent as be,readProjectRemotePreference as $e,resolveTargetOrThrow as Ee,inferLunoraBindings as Ie,packageNamesFromBindings as Ne,ensureDevVarsExample as Re,ensureDevVariables as Te,isInteractive as Le,DEV_VARS_FILE as x,DEV_VARS_EXAMPLE_FILE as Oe,fillDevSecrets as Pe,claimAgentRulesHint as De,AGENT_RULES_HINT as xe,resolveDeployDriver as Ce,resolveProjectTarget as _e,discoverContainerInfo as Ae,streamContainerLogs as je,formatLunoraEvent as Me}from"@lunora/config";import{resolveRemoteEnabled as Fe,findWranglerFile as te,readWranglerJsonc as ne,materializeRemoteWranglerConfig as Ge}from"@lunora/config/cloudflare";import{r as He}from"../packem_shared/api-spec-BENwiyUa.mjs";import{l as Ue}from"../packem_shared/codegen-error-DJN6pTH5.mjs";import{a as Ve}from"../packem_shared/platform-diagnostics-C4TFj5Pu.mjs";import{i as We}from"../packem_shared/command-Bjv4VmYA.mjs";import{P as se,M as $,k as qe}from"../packem_shared/detect-package-manager-B2eIuAiP.mjs";import{createServer as Be,connect as Je}from"node:net";import{forceJsonLogging as Ke}from"../packem_shared/createLogger--C3x1FNE.mjs";import{networkInterfaces as ze}from"node:os";import{spawnShellCompat as ie}from"../packem_shared/createRecordingSpawner-ByIqBepG.mjs";import{createServer as Ye,request as Xe}from"node:http";import{loadStudioAssets as C,studioAssetsStamp as _,renderStudioHtml as Ze,resolveAdminToken as Qe,SCHEMA_EDIT_ENDPOINT as er,POLICY_SCAFFOLD_ENDPOINT as rr,SEED_ENDPOINT as or,serveJsonHandler as tr,isStandaloneModulePath as nr,readStandaloneAsset as sr,assetContentType as ir,handleSchemaEditRequest as ar,handlePolicyScaffoldRequest as dr,handleSeedRequest as cr}from"@lunora/config/studio-host";import{$ as lr}from"../packem_shared/tui-prompts-CCt3jm1k.mjs";import{d as v}from"../packem_shared/output-format-D7cKB-O5.mjs";const ur=100,pr=/[/\\]/u,A=(e,r,t)=>{const{apiSpec:o,logger:n,projectRoot:s,target:a}=e;try{const i=X({apiSpec:o,lunoraDirectory:r,projectRoot:s,target:a});n.success(`codegen: wrote ${r}/_generated (${t})`),Ve(i.platformDiagnostics,n)}catch(i){n.error(Ue(i,t))}},gr=e=>{const r=e.lunoraDirectory??"lunora",t=k(e.projectRoot,r),o=e.debounceMs??ur;A(e,r,"startup");let n,s;if(!N(t))return e.logger.warn(`codegen watch unavailable (no such directory: ${t}) — schema edits will NOT auto-regenerate. Run \`lunora codegen\` manually after each edit.`),{close:()=>{},watchAvailable:!1};try{s=me(t,{recursive:!0},(i,c)=>{typeof c=="string"&&c.split(pr).includes("_generated")||(n&&clearTimeout(n),n=setTimeout(()=>{A(e,r,`change: ${c??"?"}`)},o))})}catch(i){return e.logger.warn(`codegen watch unavailable (${i instanceof Error?i.message:String(i)}) — schema edits will NOT auto-regenerate. Run \`lunora codegen\` manually after each edit.`),{close:()=>{},watchAvailable:!1}}const a=s;return{close:()=>{n&&clearTimeout(n),a.close()},watchAvailable:!0}},mr=64,ae="127.0.0.1",fr=65535,vr=(e,r=ae)=>new Promise(t=>{const o=Be();o.once("error",()=>{t(!1)}),o.once("listening",()=>{o.close(()=>{t(!0)})}),o.listen(e,r)}),wr=async(e,r=ae,t=mr)=>{for(let o=e;o<e+t&&o<=fr;o+=1)if(await vr(o,r))return o;return e},j=(e=ze)=>Object.values(e()).some(r=>r?.some(t=>t.internal&&t.address==="::1")),M="/_lunora",F=e=>{const r=e.indexOf("?");return r===-1?e:e.slice(0,r)},hr=new Set(["127.0.0.1","::1","[::1]","localhost"]),G=e=>{if(e===void 0||e==="")return!1;const r=e.startsWith("[")?e.slice(0,e.indexOf("]")+1):e.split(":")[0]??e;return hr.has(r)},Sr=(e,r,t)=>{const o=Xe({headers:{...e.headers,host:t.host},hostname:t.hostname,method:e.method,path:e.url,port:t.port},n=>{r.writeHead(n.statusCode??502,n.headers),n.pipe(r)});o.on("error",n=>{r.statusCode=502,r.end(`lunora dev: worker unreachable (${n.message})`)}),e.pipe(o)},kr=5e3,yr=(e,r,t,o)=>{const n=Je({host:o.hostname,port:Number(o.port)},()=>{n.setTimeout(0);const s=[`${e.method??"GET"} ${e.url??"/"} HTTP/1.1`];for(const[a,i]of Object.entries(e.headers))if(a!=="host")for(const c of Array.isArray(i)?i:[i])c!==void 0&&s.push(`${a}: ${c}`);s.push(`host: ${o.host}`,"",""),n.write(s.join(`\r
1
+ import{spawnSync as I,spawn as J}from"node:child_process";import{existsSync as N,watch as me,readFileSync as K,statSync as fe,openSync as z,readSync as ve,closeSync as Y,mkdirSync as we}from"node:fs";import{join as k,dirname as he}from"node:path";import{runCodegen as X}from"@lunora/codegen";import{detectAgentRules as Z,claimDevServerState as Q,clearDevServerState as f,readDevServerState as R,readLiveDevServerState as y,detectFramework as ee,readProjectDependencyNames as Se,DEV_HANDOFF_ENV as h,isRecordedProcessCurrent as ke,DEV_LOG_FILE as ye,DEV_LOG_FILE_ENV as re,DEV_DAEMON_ENV as T,updateDevServerState as oe,detectAiAgent as be,readProjectRemotePreference as $e,resolveTargetOrThrow as Ee,inferLunoraBindings as Ie,packageNamesFromBindings as Ne,ensureDevVarsExample as Re,ensureDevVariables as Te,isInteractive as Le,DEV_VARS_FILE as x,DEV_VARS_EXAMPLE_FILE as Oe,fillDevSecrets as Pe,claimAgentRulesHint as De,AGENT_RULES_HINT as xe,resolveDeployDriver as Ce,resolveProjectTarget as _e,discoverContainerInfo as Ae,streamContainerLogs as je,formatLunoraEvent as Me}from"@lunora/config";import{resolveRemoteEnabled as Fe,findWranglerFile as te,readWranglerJsonc as ne,materializeRemoteWranglerConfig as Ge}from"@lunora/config/cloudflare";import{r as He}from"../packem_shared/api-spec-BENwiyUa.mjs";import{l as Ue}from"../packem_shared/codegen-error-DJN6pTH5.mjs";import{a as Ve}from"../packem_shared/platform-diagnostics-C4TFj5Pu.mjs";import{i as We}from"../packem_shared/command-Bjv4VmYA.mjs";import{P as se,M as $,l as qe}from"../packem_shared/detect-package-manager-C4aS7HE4.mjs";import{createServer as Be,connect as Je}from"node:net";import{forceJsonLogging as Ke}from"../packem_shared/createLogger--C3x1FNE.mjs";import{networkInterfaces as ze}from"node:os";import{spawnShellCompat as ie}from"../packem_shared/createRecordingSpawner-ByIqBepG.mjs";import{createServer as Ye,request as Xe}from"node:http";import{loadStudioAssets as C,studioAssetsStamp as _,renderStudioHtml as Ze,resolveAdminToken as Qe,SCHEMA_EDIT_ENDPOINT as er,POLICY_SCAFFOLD_ENDPOINT as rr,SEED_ENDPOINT as or,serveJsonHandler as tr,isStandaloneModulePath as nr,readStandaloneAsset as sr,assetContentType as ir,handleSchemaEditRequest as ar,handlePolicyScaffoldRequest as dr,handleSeedRequest as cr}from"@lunora/config/studio-host";import{$ as lr}from"../packem_shared/tui-prompts-CCt3jm1k.mjs";import{d as v}from"../packem_shared/output-format-D7cKB-O5.mjs";const ur=100,pr=/[/\\]/u,A=(e,r,t)=>{const{apiSpec:o,logger:n,projectRoot:s,target:a}=e;try{const i=X({apiSpec:o,lunoraDirectory:r,projectRoot:s,target:a});n.success(`codegen: wrote ${r}/_generated (${t})`),Ve(i.platformDiagnostics,n)}catch(i){n.error(Ue(i,t))}},gr=e=>{const r=e.lunoraDirectory??"lunora",t=k(e.projectRoot,r),o=e.debounceMs??ur;A(e,r,"startup");let n,s;if(!N(t))return e.logger.warn(`codegen watch unavailable (no such directory: ${t}) — schema edits will NOT auto-regenerate. Run \`lunora codegen\` manually after each edit.`),{close:()=>{},watchAvailable:!1};try{s=me(t,{recursive:!0},(i,c)=>{typeof c=="string"&&c.split(pr).includes("_generated")||(n&&clearTimeout(n),n=setTimeout(()=>{A(e,r,`change: ${c??"?"}`)},o))})}catch(i){return e.logger.warn(`codegen watch unavailable (${i instanceof Error?i.message:String(i)}) — schema edits will NOT auto-regenerate. Run \`lunora codegen\` manually after each edit.`),{close:()=>{},watchAvailable:!1}}const a=s;return{close:()=>{n&&clearTimeout(n),a.close()},watchAvailable:!0}},mr=64,ae="127.0.0.1",fr=65535,vr=(e,r=ae)=>new Promise(t=>{const o=Be();o.once("error",()=>{t(!1)}),o.once("listening",()=>{o.close(()=>{t(!0)})}),o.listen(e,r)}),wr=async(e,r=ae,t=mr)=>{for(let o=e;o<e+t&&o<=fr;o+=1)if(await vr(o,r))return o;return e},j=(e=ze)=>Object.values(e()).some(r=>r?.some(t=>t.internal&&t.address==="::1")),M="/_lunora",F=e=>{const r=e.indexOf("?");return r===-1?e:e.slice(0,r)},hr=new Set(["127.0.0.1","::1","[::1]","localhost"]),G=e=>{if(e===void 0||e==="")return!1;const r=e.startsWith("[")?e.slice(0,e.indexOf("]")+1):e.split(":")[0]??e;return hr.has(r)},Sr=(e,r,t)=>{const o=Xe({headers:{...e.headers,host:t.host},hostname:t.hostname,method:e.method,path:e.url,port:t.port},n=>{r.writeHead(n.statusCode??502,n.headers),n.pipe(r)});o.on("error",n=>{r.statusCode=502,r.end(`lunora dev: worker unreachable (${n.message})`)}),e.pipe(o)},kr=5e3,yr=(e,r,t,o)=>{const n=Je({host:o.hostname,port:Number(o.port)},()=>{n.setTimeout(0);const s=[`${e.method??"GET"} ${e.url??"/"} HTTP/1.1`];for(const[a,i]of Object.entries(e.headers))if(a!=="host")for(const c of Array.isArray(i)?i:[i])c!==void 0&&s.push(`${a}: ${c}`);s.push(`host: ${o.host}`,"",""),n.write(s.join(`\r
2
2
  `)),t.length>0&&n.write(t),n.pipe(r),r.pipe(n)});n.setTimeout(kr,()=>n.destroy()),n.on("error",()=>r.destroy()),r.on("error",()=>n.destroy())},br=async e=>{const r=e.host??"127.0.0.1",t=r==="127.0.0.1"||r==="localhost"||r==="::1",o=new URL(e.workerOrigin);let n=C(e.logger,import.meta.url),s=_(import.meta.url);const a=Ze({adminToken:t?Qe(e.cwd):void 0,basePath:"/",dataEditable:t,rulesInstalled:Z(e.cwd).installed,runAsIdentity:t,schemaEditable:t,scriptSrc:"/studio.js",styleHref:"/styles.css"}),i=(l,d,g)=>{l.statusCode=200,l.setHeader("Content-Type",g),l.end(d)},c=(l,d,g,b)=>{if(t){tr(l,d,g,e.cwd);return}d.statusCode=403,d.setHeader("Content-Type","text/plain"),d.end(b)},u=(l,d)=>{const g=l==="/styles.css",b=nr(l);if(!g&&!b)return!1;const O=_(import.meta.url);if(O!==s&&(n=C(e.logger,import.meta.url),s=O),n===void 0)return d.statusCode=501,d.setHeader("Content-Type","text/plain"),d.end("Lunora studio assets not found — install and build @lunora/studio."),!0;if(g)return i(d,n.styles,"text/css; charset=utf-8"),!0;const P=l.slice(l.lastIndexOf("/")+1),D=sr(P,import.meta.url);return D===void 0?(d.statusCode=404,d.setHeader("Content-Type","text/plain"),d.end("Not found"),!0):(i(d,D,ir(P)),!0)},p=Buffer.from(a),m=Ye((l,d)=>{const g=F(l.url??"/");if(t&&!G(l.headers.host)){d.statusCode=403,d.setHeader("Content-Type","text/plain"),d.end("Lunora studio: refusing a request whose Host is not a loopback literal (DNS-rebinding guard).");return}if(g.startsWith(M)){if(!t){d.statusCode=403,d.setHeader("Content-Type","text/plain"),d.end("Lunora studio: the worker admin proxy is only available on a loopback bind.");return}Sr(l,d,o);return}if(g===er){c(l,d,ar,"Lunora schema editing is only available on loopback hosts in dev.");return}if(g===rr){c(l,d,dr,"Lunora policy scaffolding is only available on loopback hosts in dev.");return}if(g===or){c(l,d,cr,"Lunora data seeding is only available on loopback hosts in dev.");return}u(g,d)||i(d,p,"text/html; charset=utf-8")});return m.on("upgrade",(l,d,g)=>{if(!t||!G(l.headers.host)){d.destroy();return}F(l.url??"").startsWith(M)?yr(l,d,g,o):d.destroy()}),await new Promise((l,d)=>{m.once("error",g=>{g.code==="EADDRINUSE"?d(new Error(`studio port ${String(e.port)} is already in use — pass a different port with --port, or stop the process using it`,{cause:g})):d(g)}),m.listen(e.port,r,()=>{l()})}),{close:()=>new Promise(l=>{m.close(()=>{l()})}),url:`http://${r==="0.0.0.0"||r==="::"?"localhost":r}:${String(e.port)}`}},$r=12e4,de=250,Er=1e4,Ir=100,Nr=40,w=256*1024,Rr="LUNORA_DEV_READY_TIMEOUT_MS",Tr=new Set(["nuxt","sveltekit"]),L=e=>Tr.has(ee(e).framework)?"framework-worker":Se(e).has("@lunora/vite")?"vite":"wrangler",ce=e=>{const r=se(e);let t;try{const o=K(k(e,"package.json"),"utf8");t=JSON.parse(o).scripts?.dev}catch{}if(t===void 0||t.trim()===""||t.includes("lunora")){const o=$(r,"vite",["dev"]);return{args:o.args,command:o.command}}return{args:["run","dev"],command:r}},E=e=>new Promise(r=>{setTimeout(r,e)}),Lr=async e=>{try{return await fetch(new URL("/_lunora/status",e),{signal:AbortSignal.timeout(1e3)}),!0}catch{return!1}},Or=e=>{we(he(e.logPath),{recursive:!0});const r=z(e.logPath,"w",384);let t;const o=ie(e.command,e.args);try{t=J(o.command,o.args,{cwd:e.cwd,detached:!0,env:e.env,shell:o.shell,stdio:["ignore",r,r],windowsHide:!0})}finally{Y(r)}return t.unref(),{exited:new Promise(n=>{t.on("error",()=>{n(1)}),t.on("exit",(s,a)=>{n(s??(a?1:0))})}),pid:t.pid}},Pr=e=>{try{const{size:r}=fe(e);if(r<=w)return K(e,"utf8");const t=z(e,"r");try{const o=Buffer.alloc(w),n=ve(t,o,0,w,r-w),s=o.toString("utf8",0,n);return s.slice(s.indexOf(`
3
3
  `)+1)}finally{Y(t)}}catch{return}},le=(e,r)=>{const t=Pr(e);if(t===void 0)return[];const o=t.split(`
4
4
  `);return o.at(-1)===""&&o.pop(),r>0?o.slice(-r):o},ue=(e,r)=>r?.logFile??k(e,ye),pe=e=>{e.info(" Stop: lunora dev stop"),e.info(" Status: lunora dev status"),e.info(" Logs: lunora dev logs")},S=(e,r)=>{e.warn(`Dev server already running at ${r.url} (pid ${String(r.pid)})`),pe(e)},Dr=(e,r)=>{e.success(`Dev server running at ${r.url} (pid ${String(r.pid)})`),r.studioUrl!==void 0&&e.info(` Studio: ${r.studioUrl}`),pe(e)},xr=async e=>{const{child:r,cwd:t,deadline:o,pollIntervalMs:n,probe:s}=e,a=r.exited.then(i=>({exitCode:i}));for(;Date.now()<o;){const i=y(t);if(i!==void 0&&i.pid!==process.pid&&await s(i.url))return{state:i,status:"ready"};const c=await Promise.race([a,E(n)]);if(c!==void 0)return{...c,status:"exited"}}return{status:"timeout"}},Cr=async e=>{const{cwd:r,logger:t}=e,o=ue(r,void 0),n=Number(process.env[Rr]??""),s=e.readyTimeoutMs??(Number.isFinite(n)&&n>0?n:$r),a=(e.spawnDetached??Or)({args:e.command.args,command:e.command.command,cwd:r,env:{...process.env,...e.env,[T]:"1",[re]:o,...process.env.FORCE_COLOR===void 0?{NO_COLOR:"1"}:{},...e.json?{LUNORA_LOG_JSON:"1"}:{}},logPath:o}),i=await xr({child:a,cwd:r,deadline:Date.now()+s,pollIntervalMs:e.pollIntervalMs??de,probe:e.probe??Lr});if(i.status==="ready")return Dr(t,i.state),{code:0};if(i.status==="exited"){t.error(`dev server exited before becoming ready (exit code ${String(i.exitCode)}). Last output:`);for(const u of le(o,Nr))t.error(` ${u}`);return f(r,a.pid??process.pid),{code:i.exitCode===0?1:i.exitCode}}a.pid!==void 0&&R(r)?.pid===process.pid&&oe(r,{logFile:o,pid:a.pid});const c=a.pid===void 0?"":` (pid ${String(a.pid)})`;return t.warn(`dev server did not confirm ready within ${String(Math.round(s/1e3))}s — it may still be compiling${c}. Check \`lunora dev status\` and \`lunora dev logs\`; \`lunora dev stop\` shuts it down.`),{code:1}},_r=(e,r)=>{const t=["dev"];return e.apiSpec!==void 0&&t.push("--api-spec",e.apiSpec),e.port!==void 0&&t.push("--port",String(e.port)),e.workerPort!==void 0&&t.push("--worker-port",String(e.workerPort)),e.codegen===!1&&t.push("--no-codegen"),e.studio===!1&&t.push("--no-studio"),e.worker===!1&&t.push("--no-worker"),e.target!==void 0&&t.push("--target",e.target),r&&t.push("--remote"),t},Ar=async e=>{const{cwd:r,jsonLogs:t,logger:o,options:n,remote:s}=e,a=e.run??Cr,i=L(r),c=i==="wrangler"?`http://localhost:${String(n.workerPort??8787)}`:"http://localhost:5173",u=Q(r,{background:!0,mode:"cli",pid:process.pid,startedAt:new Date().toISOString(),url:c});if(!u.ok)return u.existing!==void 0&&S(o,u.existing),{code:0};const p={[h]:String(process.pid)};try{return i==="vite"?await a({command:ce(r),cwd:r,env:{...s?{LUNORA_REMOTE:"1"}:{},...p},json:t,logger:o}):await a({command:{args:[process.argv[1]??"lunora",..._r(n,s)],command:process.execPath},cwd:r,env:p,json:t,logger:o})}finally{f(r,process.pid)}},jr=e=>{try{const r=I("ps",["-o","pgid=","-p",String(e)],{encoding:"utf8"}),t=Number.parseInt(r.stdout.trim(),10);return Number.isInteger(t)&&t>0?t:void 0}catch{return}},Mr=(e,r,t=process.platform,o=I)=>{if(t==="win32"){try{o("taskkill",["/pid",String(e.pid),"/T","/F"],{stdio:"ignore"})}catch{}return}if(e.background===!0)try{r(-(jr(e.pid)??e.pid),"SIGKILL");return}catch{}try{r(e.pid,"SIGKILL")}catch{}},Fr=(e,r)=>(r.json?v({pid:e.pid,stopped:!1}):r.logger.error(`dev server (pid ${String(e.pid)}) survived the force-kill — record kept; retry \`lunora dev stop\` or kill the process manually.`),{code:1}),Gr=async e=>{const{cwd:r,logger:t}=e,o=R(r),n=e.alive??(m=>m===o?.pid&&ke(o)),s=e.signal??((m,l)=>{process.kill(m,l)}),a=e.pollIntervalMs??de,i=e.stopGraceMs??Er,c=e.platform??process.platform,u=e.spawnSyncImpl??I;if(o===void 0||!n(o.pid))return o!==void 0&&f(r,o.pid),e.json?v({running:!1,stopped:!1}):t.info("No dev server running."),{code:0};try{s(o.pid,"SIGTERM")}catch{}const p=Date.now()+i;for(;n(o.pid)&&Date.now()<p;)await E(a);return n(o.pid)&&(Mr(o,s,c,u),await E(a),n(o.pid))?Fr(o,e):(f(r,o.pid),e.json?v({pid:o.pid,stopped:!0}):t.success(`Stopped dev server (pid ${String(o.pid)}).`),{code:0})},Hr=e=>{const{cwd:r,logger:t}=e,o=y(r);if(o===void 0)return e.json?v({running:!1}):t.info("No dev server running."),{code:0};const n=e.now??Date.now,s=o.startedAt===void 0?Number.NaN:Date.parse(o.startedAt),a=Number.isFinite(s)?Math.max(0,Math.round((n()-s)/1e3)):void 0;if(e.json)return v({background:o.background===!0,logFile:o.logFile,mode:o.mode,pid:o.pid,running:!0,startedAt:o.startedAt,studioUrl:o.studioUrl,uptimeSeconds:a,url:o.url}),{code:0};const i=[`pid ${String(o.pid)}`,...a===void 0?[]:[`uptime ${String(a)}s`],o.background===!0?"background":"foreground"];return t.success(`Dev server running at ${o.url} (${i.join(", ")})`),o.studioUrl!==void 0&&t.info(` Studio: ${o.studioUrl}`),o.logFile!==void 0&&t.info(` Logs: lunora dev logs (${o.logFile})`),{code:0}},Ur=e=>{const{cwd:r,logger:t}=e,o=R(r),n=ue(r,o);if(!N(n))return t.info("No dev server logs found — output is captured when the server runs in background mode (`lunora dev --background`)."),{code:0};const s=le(n,e.lines??Ir);return s.length>0&&process.stdout.write(`${s.join(`
@@ -1 +1 @@
1
- import{existsSync as h,readFileSync as T}from"node:fs";import{runCodegen as _,discoverMigrations as E}from"@lunora/codegen";import{readLinkedProject as S,writeLinkedProject as P,resolveDeployDriver as R,inferLunoraBindings as U,DEV_VARS_FILE as $,parseDevVariableEntries as A,isMintableSecretKey as j,discoverContainerInfo as C,packageNamesFromBindings as O,requiredSecrets as W,generateSecretValue as B,discoverSchemaInfo as K}from"@lunora/config";import{validateWranglerProject as M,reconcileWranglerBindings as q,reconcileWranglerCompatibilityDate as Y,reconcileWranglerCrons as F,findWranglerFile as D,readWranglerJsonc as x}from"@lunora/config/cloudflare";import{join as m}from"@visulima/path";import{Spinner as V}from"@visulima/spinner";import{Project as G}from"ts-morph";import{r as z}from"../packem_shared/api-spec-BENwiyUa.mjs";import{d as I}from"../packem_shared/wrangler-name-CHDf3rMP.mjs";import{i as H}from"../packem_shared/command-Bjv4VmYA.mjs";import{i as J}from"../packem_shared/deploy-target-Dvr9vxpR.mjs";import{M as v,P as y}from"../packem_shared/detect-package-manager-B2eIuAiP.mjs";import{o as Q,r as X}from"../packem_shared/docker-CKvYE9YF.mjs";import{i as Z,r as w,d as ee,s as re}from"../packem_shared/output-format-D7cKB-O5.mjs";import{containerBuildTag as te}from"@lunora/container";import{defaultSpawner as b}from"../packem_shared/createRecordingSpawner-ByIqBepG.mjs";import{t as oe}from"../packem_shared/resolve-target-vxaXHmvg.mjs";import{k as ne}from"../packem_shared/schema-drift-gate-CpqG-xP4.mjs";import{$ as ie}from"../packem_shared/tui-prompts-CCt3jm1k.mjs";import{m as ae,p as se}from"../packem_shared/vectorize-metadata-BvZbbqUD.mjs";import{R as ce}from"../packem_shared/wrangler-secrets-DDDUuryf.mjs";import{runMigrateDataCommand as le}from"./runMigrateGenerateCommand.mjs";const de=/https?:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/u,ge=/https:\/\/[^\s"'<>]+/u,ue=e=>{const r=de.exec(e);return r?r[0]:ge.exec(e)?.[0]},pe=({cwd:e,env:r,logger:t,now:n,output:o})=>{if(o===void 0||S(e)!==void 0)return;const i=ue(o);if(i!==void 0)try{const a=(n??(()=>new Date().toISOString()))();P(e,{env:r,linkedAt:a,workerName:I(e),workerUrl:i}),t.success(`link: recorded ${i} in .lunora/project.json (run \`lunora link\` to change)`)}catch{}},me=e=>{const{cwd:r,env:t,logger:n,migrated:o}=e;try{const i=S(r),a=i?.workerName??I(r);n.success("deploy complete"),n.info(` worker: ${a??"(see wrangler output above)"}`),t!==void 0&&n.info(` env: ${t}`),i?.workerUrl===void 0?n.info(" url: run `lunora link --url <https://your-worker>` to record it"):n.info(` url: ${i.workerUrl}`),o&&n.info(" migrations: applied"),n.info(" studio: lunora view --remote"),n.info(" logs: lunora logs")}catch{}},fe=async e=>{if(e.targets.length===0)return{builtTags:[],code:0};if(!(e.railpackAvailable??Q)()){const n="deploy blocked: a container uses `image: { build }` (Railpack), but Railpack isn't ready. Install the `railpack` CLI and start a BuildKit instance, e.g. `docker run --rm --privileged -d --name buildkit moby/buildkit` then `export BUILDKIT_HOST=docker-container://buildkit`. Alternatively switch the container's `image` to a Dockerfile path or a pre-built registry reference.";return e.logger.error(n),{builtTags:[],code:1,error:n}}const r=e.spawner??b,t=[];for(const n of e.targets){const o=te(n.exportName),i={args:["build",n.buildDir,"--name",o],command:"railpack",cwd:e.cwd},a=v(y(e.cwd),"wrangler",["containers","push",o]),s={args:a.args,command:a.command,cwd:e.cwd};e.logger.info(`railpack: building "${n.exportName}" → ${o} from ${n.buildDir}`);const d=await r(i);if(d.code!==0){const l=`railpack build failed for container "${n.exportName}" (${n.buildDir})`;return e.logger.error(l),{builtTags:t,code:d.code,error:l}}e.logger.info(`railpack: pushing ${o} to the Cloudflare Registry`);const c=await r(s);if(c.code!==0){const l=`wrangler containers push failed for "${n.exportName}" (${o})`;return e.logger.error(l),{builtTags:t,code:c.code,error:l}}t.push(o)}return{builtTags:t,code:0}},L="<replace-with-d1-create-id>",he=["LUNORA_ORIGIN_URL","LUNORA_WORKER_ORIGIN","AUTH_URL"],we=e=>{try{const{hostname:r}=new URL(e);return r==="localhost"||r==="127.0.0.1"||r==="::1"||r==="[::1]"}catch{return!1}},ve=e=>e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.includes("Dockerfile"),ye=(e,r,t)=>{const n=D(e);if(!n)return;const{parsed:o}=x(n),i=(o?.containers??[]).filter(s=>typeof s?.image=="string"&&ve(s.image));if(i.length===0||t())return;const a=`deploy blocked: wrangler.jsonc declares ${String(i.length)} container(s) built from a local Dockerfile, but no Docker-compatible engine is available. Start Docker (or Colima), or point the container's \`image\` at a pre-built registry reference. Note: container images must target linux/amd64.`;return r.error(a),a},be=e=>h(m(e,"src","worker.ts"))?"src/worker.ts":void 0,ke=(e,r)=>{for(const t of C(e,"lunora").containers){const{image:n}=t;if(n.kind==="dockerfile"&&!h(m(e,n.dockerfilePath))){const o=`deploy blocked: container "${t.exportName}" references a Dockerfile at "${n.dockerfilePath}" that does not exist. Create it or fix the \`image\` path in lunora/containers.ts.`;return r.error(o),o}if(n.kind==="build"&&!h(m(e,n.buildDir))){const o=`deploy blocked: container "${t.exportName}" references a Railpack build directory "${n.buildDir}" that does not exist. Create it or fix the \`image.build\` path in lunora/containers.ts.`;return r.error(o),o}}},$e=e=>w(e.format)?!1:e.interactive!==void 0?e.interactive:process.stdout.isTTY&&!process.env.CI,Se=e=>{const r=D(e);if(!r)return;const{parsed:t}=x(r);return t?(t.d1_databases??[]).find(n=>n.database_id===L)?.binding:void 0},Re=async(e,r)=>{const t=C(e,"lunora").containers.filter(o=>o.image.kind==="build").map(o=>({buildDir:o.image.buildDir,exportName:o.exportName}));if(t.length===0)return;const n=await fe({cwd:e,logger:r.logger,railpackAvailable:r.railpackAvailable,spawner:r.spawner,targets:t});return n.code===0?void 0:n.error??"railpack build failed"},De=(e,r,t)=>{if(t!==void 0)try{const n=F(e,t);n.changed&&r.success(`synced ${String(t.length)} cron trigger(s) → ${n.wranglerPath??"wrangler.jsonc"}`)}catch(n){const o=n instanceof Error?n.message:String(n);r.warn(`cron trigger sync skipped: ${o}`)}},xe=async(e,r,t,n)=>{try{R(n);const o=await U({projectRoot:e}),i=q(e,o);i.changed&&r.success(`provisioned bindings: ${i.added.join(", ")} → ${i.wranglerPath??"wrangler.jsonc"}`);for(const a of i.warnings)r.warn(a)}catch(o){const i=o instanceof Error?o.message:String(o);r.warn(`binding inference skipped: ${i}`)}try{const o=Y(e);o.changed&&r.success(`bumped compatibility_date to ${o.date??"unknown"} (Workers Cache enabled) → ${o.wranglerPath??"wrangler.jsonc"}`)}catch(o){const i=o instanceof Error?o.message:String(o);r.warn(`compatibility date sync skipped: ${i}`)}De(e,r,t)},Ne=(e,r)=>{const t=m(e,$);if(!h(t))return;let n;try{n=A(T(t,"utf8")).length}catch{return}n!==0&&r.warn(`Note: \`lunora deploy\` does not push secrets. ${$} has ${String(n)} key(s); if you changed them, run \`lunora env push --yes\` to update the deployed secrets.`)},je=/(?:KEY|PASSWORD|SECRET|TOKEN)$/u,Te=async e=>{let r=[];try{r=O(await U({projectRoot:e}))}catch{}const t=W(r).map(o=>o.key);let n=[];try{const o=m(e,$);h(o)&&(n=A(T(o,"utf8")).map(i=>i.key).filter(i=>je.test(i)))}catch{}return[...new Set([...t,...n])]},Ue=async(e,r,t,n)=>{const{logger:o}=r,i=r.spawner??b,a=y(e),s=r.env===void 0?"":` --env ${r.env}`,{toolchain:d}=R(n);if(d===void 0)return o.error("deploy target has no command-line toolchain; cannot push secrets"),!1;for(const c of t){const l=d.secretPut({environment:r.env,key:c,temporary:r.temporary}),p=v(a,l.tool,l.args),f=await i({args:p.args,command:p.command,cwd:e,input:B()});if(f.code!==0)return o.error(`failed to push secret ${c} (exit ${String(f.code)}); set it manually with \`wrangler secret put ${c}${s}\`.`),!1;o.success(`generated + pushed ${c}`)}return!0},Ae=async(e,r,t,n)=>{if(r.dryRun===!0||r.preview===!0)return;const{logger:o}=r,i=r.env===void 0?"":` --env ${r.env}`;let a;try{a=await(r.secretLister??ce)({cwd:e,env:r.env,temporary:r.temporary})}catch{return}if(!a.ok)return;const s=new Set(a.names),d=(await Te(e)).filter(l=>!s.has(l));if(d.length===0)return;if(!t)return`missing required secret(s) on the deploy target: ${d.join(", ")}. Set them with \`wrangler secret put <KEY>${i}\` (or \`lunora env generate --set\` then \`lunora env push --yes${r.env===void 0?"":" --prod"}\`), then re-deploy.`;for(const l of d.filter(p=>!j(p)))o.warn(`required secret ${l} is not set on the target — set it with: wrangler secret put ${l}${i}`);const c=d.filter(l=>j(l));if(c.length!==0){if(await(r.secretConfirm??ie())(`${String(c.length)} required secret(s) not set on the target (${c.join(", ")}). Generate strong values and push them now?`)){await Ue(e,r,c,n);return}o.warn(`${String(c.length)} required secret(s) not set on the target: ${c.join(", ")}. Generate + push with \`lunora env generate --set\` then \`lunora env push --yes${r.env===void 0?"":" --prod"}\`.`)}},Ce=async(e,r)=>{const t=new G({skipAddingFilesFromTsConfig:!0}),n=m(r,"lunora");let o;try{o=E(t,n)}catch(i){const a=i instanceof Error?i.message:String(i);return e.logger.warn(`--migrate: could not discover migrations (${a}); skipping`),0}if(o.length===0)return e.logger.info("--migrate: no data migrations declared in lunora/"),0;e.logger.info(`--migrate: running ${String(o.length)} migration(s) against deployed worker`);for(const i of o){e.logger.info(`--migrate: up "${i.id}" (table "${i.table}")`);const a={cwd:r,fetchImpl:e.fetchImpl,id:i.id,logger:e.logger,prod:!0,subcommand:"up",token:e.migrateToken,url:e.migrateUrl,yes:e.migrateYes===!0},s=await le(a);if(s.code!==0)return e.logger.error(`--migrate: migration "${i.id}" failed — see output above`),s.code;e.logger.success(`--migrate: "${i.id}" applied`)}return 0},Ie=e=>{if(!(!e.migrate||e.dryRun||e.preview)){if(e.migrateUrl===void 0){const r="--migrate requires --migrate-url <https://your-worker> — the deploy target URL is not captured automatically, refusing to default to localhost";return e.logger.error(r),r}if(e.migrateYes!==!0){const r="--migrate runs production data migrations after deploy. Re-run with --migrate-yes to confirm.";return e.logger.error(r),r}if((e.migrateToken??process.env.LUNORA_ADMIN_TOKEN)===void 0||(e.migrateToken??process.env.LUNORA_ADMIN_TOKEN)===""){const r="admin token required for --migrate — pass --migrate-token or set LUNORA_ADMIN_TOKEN";return e.logger.error(r),r}}},Le=(e,r,t,n,o)=>{let i;r?(i=new V({name:"dots"}),i.start("running codegen")):t.info("running codegen");try{const a=_({apiSpec:n,projectRoot:e,target:o});return i?.succeed("codegen complete"),i||t.success("codegen complete"),{result:a}}catch(a){i?.failed("codegen failed");const s=a instanceof Error?a.message:String(a);return t.error(`codegen failed: ${s}`),{error:`codegen failed: ${s}`}}},_e=(e,r)=>{const t=Se(e);if(t===void 0)return;const n=`deploy blocked: the "${t}" D1 binding has a placeholder database_id ("${L}"). Run \`wrangler d1 create <name>\` to create the database, then replace the placeholder in wrangler.jsonc with the real id before deploying.`;return r.error(n),n},Ee=(e,r)=>{const t=D(e);if(!t)return;const{parsed:n}=x(t),o=n?.vars;if(!o)return;const i=he.filter(s=>typeof o[s]=="string"&&we(o[s]));if(i.length===0)return;const a=`deploy blocked: ${i.join(", ")} in wrangler.jsonc point at localhost. A deployed Worker can't reach a loopback address, so this silently breaks scheduled-job dispatch / auth callbacks. Set each to the deployed worker's public URL (or move it to a secret with \`wrangler secret put\`) before deploying.`;return r.error(a),a},Pe=async(e,r)=>{const{info:t}=K(r,"lunora"),n=t?.vectorMetadata??[];if(n.length===0)return;const o=[];for(const a of n){const s=se(a.kind);if(s===void 0){e.logger.warn(`vector index "${a.index}" declares metadata "${a.property}", whose column type cannot be filtered on in Vectorize — it is stored with each vector but no filter will match it.`);continue}o.push({index:a.index,property:a.property,type:s})}if(o.length===0)return;const i=(await ae({cwd:r,entries:o,exec:v(y(r),"wrangler",[]),logger:e.logger,spawner:e.spawner??b})).filter(a=>a.status!=="failed").length;i>0&&e.logger.success(`vectorize metadata indexes ready: ${String(i)}/${String(o.length)}`)},Oe=async(e,r,t,n,o)=>{if(await Pe(e,r),e.migrate){const i=await Ce(e,r);return i===0&&o?.(),{code:i,descriptor:t,validation:n}}return o?.(),{code:0,descriptor:t,validation:n}},We=async(e,r)=>{const t=_e(e,r.logger);if(t!==void 0)return t;const n=Ee(e,r.logger);if(n!==void 0)return n;const o=ke(e,r.logger);if(o!==void 0)return o;const i=ye(e,r.logger,r.dockerAvailable??X);return i!==void 0?i:Re(e,r)},Be=(e,r,t)=>{const n=be(e);n!==void 0&&r.logger.info(`class-B composition: deploying ${n} (overrides wrangler main)`),r.temporary&&r.logger.info("temporary account: deploying to a short-lived Cloudflare account (~60min); wrangler will print a claim URL"),r.dryRun&&r.logger.info("dry run: validating + bundling without publishing"),r.outDir!==void 0&&r.logger.info(`build artifact: emitting bundle to ${r.outDir}`);const o=R(t),i={dryRun:r.dryRun,entry:n,environment:r.env,outDir:r.outDir,preview:r.preview,temporary:r.temporary};if(o.toolchain===void 0)throw new Error(`deploy target "${o.id}" has no command-line toolchain`);return o.toolchain.deploy(i)},Ke=(e,r)=>{if(e.problems.length===0)return!1;r.error("wrangler.jsonc validation failed:");for(const t of e.problems)r.error(` - ${t}`);return!0},Me=async e=>{const r=e.cwd??process.cwd(),t=$e(e),n=J(r,e.target);if(n.target===void 0){const g=n.error??"unknown deploy target";return e.logger.error(g),{code:1,descriptor:void 0,error:g,validation:{problems:[],wranglerPath:void 0}}}const{target:o}=n;let i;if(!e.skipCodegen){const g=Le(r,t,e.logger,e.apiSpec,o);if(g.error!==void 0)return{code:1,descriptor:void 0,error:g.error,validation:{problems:[],wranglerPath:void 0}};i=g.result}let a;if(i!==void 0){const g=ne({allowDrift:e.allowSchemaDrift===!0,codegen:i,logger:e.logger,updateBaseline:e.updateSchemaBaseline===!0});if(g.blocked)return{code:1,descriptor:void 0,error:"schema drift gate blocked deploy",schemaDrift:{blocked:!0,reason:g.reason},validation:{problems:[],wranglerPath:void 0}};a=g.rebless}await xe(r,e.logger,i?.cronTriggers,o);const s=Ie(e);if(s!==void 0)return{code:1,descriptor:void 0,error:s,validation:{problems:[],wranglerPath:void 0}};const d=await We(r,e);if(d!==void 0)return{code:1,descriptor:void 0,error:d,validation:{problems:[],wranglerPath:void 0}};const c=M({projectRoot:r});if(Ke(c,e.logger))return{code:1,descriptor:void 0,error:"wrangler validation failed",validation:c};Ne(r,e.logger);const l=await Ae(r,e,t,o);if(l!==void 0)return e.logger.error(l),{code:1,descriptor:void 0,error:l,validation:c};const p=!w(e.format)&&e.dryRun!==!0&&e.preview!==!0&&S(r)===void 0,f=Be(r,e,o),N=v(y(r),f.tool,f.args),u={args:N.args,captureStdout:p,command:N.command,cwd:r,stdoutToStderr:w(e.format)};e.logger.info(`deploying via ${u.command} ${u.args.join(" ")}`);const k=await(e.spawner??b)(u);return k.code!==0?{code:k.code,descriptor:u,validation:c}:e.dryRun?{code:0,descriptor:u,validation:c}:e.preview?{code:0,descriptor:u,validation:c}:(pe({cwd:r,env:e.env,logger:e.logger,output:k.stdout}),Oe(e,r,u,c,a))},qe=async e=>{const r=Z("deploy",e.format);if(r!==void 0)return e.logger.error(r),{code:1,descriptor:void 0,error:r,validation:{problems:[],wranglerPath:void 0}};const t=await Me({...e,logger:re(e.format,e.logger)});return w(e.format)?(ee(t),t):(t.code===0&&e.dryRun!==!0&&e.preview!==!0?me({cwd:e.cwd??process.cwd(),env:e.env,logger:e.logger,migrated:e.migrate===!0}):t.code===0&&e.preview===!0&&e.logger.success("preview version uploaded — see the preview URL in the wrangler output above"),t)},ur=H(async({cwd:e,logger:r,options:t})=>({code:(await qe({allowSchemaDrift:t.allowSchemaDrift===!0,apiSpec:z(t.apiSpec),cwd:e,dryRun:t.dryRun===!0,env:t.env,format:t.format,logger:r,migrate:t.migrate===!0,migrateToken:t.migrateToken,migrateUrl:oe({cwd:e,url:t.migrateUrl}),migrateYes:t.migrateYes===!0,preview:t.preview===!0,skipCodegen:t.prebuilt===!0,target:t.target,temporary:t.temporary===!0,updateSchemaBaseline:t.updateSchemaBaseline===!0})).code}));export{ur as execute,qe as runDeployCommand};
1
+ import{existsSync as h,readFileSync as T}from"node:fs";import{runCodegen as _,discoverMigrations as E}from"@lunora/codegen";import{readLinkedProject as S,writeLinkedProject as P,resolveDeployDriver as R,inferLunoraBindings as U,DEV_VARS_FILE as $,parseDevVariableEntries as A,isMintableSecretKey as j,discoverContainerInfo as C,packageNamesFromBindings as O,requiredSecrets as W,generateSecretValue as B,discoverSchemaInfo as K}from"@lunora/config";import{validateWranglerProject as M,reconcileWranglerBindings as q,reconcileWranglerCompatibilityDate as Y,reconcileWranglerCrons as F,findWranglerFile as D,readWranglerJsonc as x}from"@lunora/config/cloudflare";import{join as m}from"@visulima/path";import{Spinner as V}from"@visulima/spinner";import{Project as G}from"ts-morph";import{r as z}from"../packem_shared/api-spec-BENwiyUa.mjs";import{d as I}from"../packem_shared/wrangler-name-CHDf3rMP.mjs";import{i as H}from"../packem_shared/command-Bjv4VmYA.mjs";import{i as J}from"../packem_shared/deploy-target-Dvr9vxpR.mjs";import{M as v,P as y}from"../packem_shared/detect-package-manager-C4aS7HE4.mjs";import{o as Q,r as X}from"../packem_shared/docker-CKvYE9YF.mjs";import{i as Z,r as w,d as ee,s as re}from"../packem_shared/output-format-D7cKB-O5.mjs";import{m as te}from"../packem_shared/post-codegen-hook-CjhP1OmV.mjs";import{containerBuildTag as oe}from"@lunora/container";import{defaultSpawner as b}from"../packem_shared/createRecordingSpawner-ByIqBepG.mjs";import{t as ne}from"../packem_shared/resolve-target-vxaXHmvg.mjs";import{R as ie}from"../packem_shared/schema-drift-gate-d12lMICD.mjs";import{$ as ae}from"../packem_shared/tui-prompts-CCt3jm1k.mjs";import{m as se,p as ce}from"../packem_shared/vectorize-metadata-BvZbbqUD.mjs";import{R as le}from"../packem_shared/wrangler-secrets-DHpbsDN9.mjs";import{runMigrateDataCommand as de}from"./runMigrateGenerateCommand.mjs";const ge=/https?:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/u,ue=/https:\/\/[^\s"'<>]+/u,pe=e=>{const r=ge.exec(e);return r?r[0]:ue.exec(e)?.[0]},me=({cwd:e,env:r,logger:t,now:n,output:o})=>{if(o===void 0||S(e)!==void 0)return;const i=pe(o);if(i!==void 0)try{const a=(n??(()=>new Date().toISOString()))();P(e,{env:r,linkedAt:a,workerName:I(e),workerUrl:i}),t.success(`link: recorded ${i} in .lunora/project.json (run \`lunora link\` to change)`)}catch{}},fe=e=>{const{cwd:r,env:t,logger:n,migrated:o}=e;try{const i=S(r),a=i?.workerName??I(r);n.success("deploy complete"),n.info(` worker: ${a??"(see wrangler output above)"}`),t!==void 0&&n.info(` env: ${t}`),i?.workerUrl===void 0?n.info(" url: run `lunora link --url <https://your-worker>` to record it"):n.info(` url: ${i.workerUrl}`),o&&n.info(" migrations: applied"),n.info(" studio: lunora view --remote"),n.info(" logs: lunora logs")}catch{}},we=async e=>{if(e.targets.length===0)return{builtTags:[],code:0};if(!(e.railpackAvailable??Q)()){const n="deploy blocked: a container uses `image: { build }` (Railpack), but Railpack isn't ready. Install the `railpack` CLI and start a BuildKit instance, e.g. `docker run --rm --privileged -d --name buildkit moby/buildkit` then `export BUILDKIT_HOST=docker-container://buildkit`. Alternatively switch the container's `image` to a Dockerfile path or a pre-built registry reference.";return e.logger.error(n),{builtTags:[],code:1,error:n}}const r=e.spawner??b,t=[];for(const n of e.targets){const o=oe(n.exportName),i={args:["build",n.buildDir,"--name",o],command:"railpack",cwd:e.cwd},a=v(y(e.cwd),"wrangler",["containers","push",o]),c={args:a.args,command:a.command,cwd:e.cwd};e.logger.info(`railpack: building "${n.exportName}" → ${o} from ${n.buildDir}`);const l=await r(i);if(l.code!==0){const d=`railpack build failed for container "${n.exportName}" (${n.buildDir})`;return e.logger.error(d),{builtTags:t,code:l.code,error:d}}e.logger.info(`railpack: pushing ${o} to the Cloudflare Registry`);const s=await r(c);if(s.code!==0){const d=`wrangler containers push failed for "${n.exportName}" (${o})`;return e.logger.error(d),{builtTags:t,code:s.code,error:d}}t.push(o)}return{builtTags:t,code:0}},L="<replace-with-d1-create-id>",he=["LUNORA_ORIGIN_URL","LUNORA_WORKER_ORIGIN","AUTH_URL"],ve=e=>{try{const{hostname:r}=new URL(e);return r==="localhost"||r==="127.0.0.1"||r==="::1"||r==="[::1]"}catch{return!1}},ye=e=>e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.includes("Dockerfile"),be=(e,r,t)=>{const n=D(e);if(!n)return;const{parsed:o}=x(n),i=(o?.containers??[]).filter(c=>typeof c?.image=="string"&&ye(c.image));if(i.length===0||t())return;const a=`deploy blocked: wrangler.jsonc declares ${String(i.length)} container(s) built from a local Dockerfile, but no Docker-compatible engine is available. Start Docker (or Colima), or point the container's \`image\` at a pre-built registry reference. Note: container images must target linux/amd64.`;return r.error(a),a},ke=e=>h(m(e,"src","worker.ts"))?"src/worker.ts":void 0,$e=(e,r)=>{for(const t of C(e,"lunora").containers){const{image:n}=t;if(n.kind==="dockerfile"&&!h(m(e,n.dockerfilePath))){const o=`deploy blocked: container "${t.exportName}" references a Dockerfile at "${n.dockerfilePath}" that does not exist. Create it or fix the \`image\` path in lunora/containers.ts.`;return r.error(o),o}if(n.kind==="build"&&!h(m(e,n.buildDir))){const o=`deploy blocked: container "${t.exportName}" references a Railpack build directory "${n.buildDir}" that does not exist. Create it or fix the \`image.build\` path in lunora/containers.ts.`;return r.error(o),o}}},Se=e=>w(e.format)?!1:e.interactive!==void 0?e.interactive:process.stdout.isTTY&&!process.env.CI,Re=e=>{const r=D(e);if(!r)return;const{parsed:t}=x(r);return t?(t.d1_databases??[]).find(n=>n.database_id===L)?.binding:void 0},De=async(e,r)=>{const t=C(e,"lunora").containers.filter(o=>o.image.kind==="build").map(o=>({buildDir:o.image.buildDir,exportName:o.exportName}));if(t.length===0)return;const n=await we({cwd:e,logger:r.logger,railpackAvailable:r.railpackAvailable,spawner:r.spawner,targets:t});return n.code===0?void 0:n.error??"railpack build failed"},xe=(e,r,t)=>{if(t!==void 0)try{const n=F(e,t);n.changed&&r.success(`synced ${String(t.length)} cron trigger(s) → ${n.wranglerPath??"wrangler.jsonc"}`)}catch(n){const o=n instanceof Error?n.message:String(n);r.warn(`cron trigger sync skipped: ${o}`)}},Ne=async(e,r,t,n)=>{try{R(n);const o=await U({projectRoot:e}),i=q(e,o);i.changed&&r.success(`provisioned bindings: ${i.added.join(", ")} → ${i.wranglerPath??"wrangler.jsonc"}`);for(const a of i.warnings)r.warn(a)}catch(o){const i=o instanceof Error?o.message:String(o);r.warn(`binding inference skipped: ${i}`)}try{const o=Y(e);o.changed&&r.success(`bumped compatibility_date to ${o.date??"unknown"} (Workers Cache enabled) → ${o.wranglerPath??"wrangler.jsonc"}`)}catch(o){const i=o instanceof Error?o.message:String(o);r.warn(`compatibility date sync skipped: ${i}`)}xe(e,r,t)},je=(e,r)=>{const t=m(e,$);if(!h(t))return;let n;try{n=A(T(t,"utf8")).length}catch{return}n!==0&&r.warn(`Note: \`lunora deploy\` does not push secrets. ${$} has ${String(n)} key(s); if you changed them, run \`lunora env push --yes\` to update the deployed secrets.`)},Te=/(?:KEY|PASSWORD|SECRET|TOKEN)$/u,Ue=async e=>{let r=[];try{r=O(await U({projectRoot:e}))}catch{}const t=W(r).map(o=>o.key);let n=[];try{const o=m(e,$);h(o)&&(n=A(T(o,"utf8")).map(i=>i.key).filter(i=>Te.test(i)))}catch{}return[...new Set([...t,...n])]},Ae=async(e,r,t,n)=>{const{logger:o}=r,i=r.spawner??b,a=y(e),c=r.env===void 0?"":` --env ${r.env}`,{toolchain:l}=R(n);if(l===void 0)return o.error("deploy target has no command-line toolchain; cannot push secrets"),!1;for(const s of t){const d=l.secretPut({environment:r.env,key:s,temporary:r.temporary}),p=v(a,d.tool,d.args),f=await i({args:p.args,command:p.command,cwd:e,input:B()});if(f.code!==0)return o.error(`failed to push secret ${s} (exit ${String(f.code)}); set it manually with \`wrangler secret put ${s}${c}\`.`),!1;o.success(`generated + pushed ${s}`)}return!0},Ce=async(e,r,t,n)=>{if(r.dryRun===!0||r.preview===!0)return;const{logger:o}=r,i=r.env===void 0?"":` --env ${r.env}`;let a;try{a=await(r.secretLister??le)({cwd:e,env:r.env,temporary:r.temporary})}catch{return}if(!a.ok)return;const c=new Set(a.names),l=(await Ue(e)).filter(d=>!c.has(d));if(l.length===0)return;if(!t)return`missing required secret(s) on the deploy target: ${l.join(", ")}. Set them with \`wrangler secret put <KEY>${i}\` (or \`lunora env generate --set\` then \`lunora env push --yes${r.env===void 0?"":" --prod"}\`), then re-deploy.`;for(const d of l.filter(p=>!j(p)))o.warn(`required secret ${d} is not set on the target — set it with: wrangler secret put ${d}${i}`);const s=l.filter(d=>j(d));if(s.length!==0){if(await(r.secretConfirm??ae())(`${String(s.length)} required secret(s) not set on the target (${s.join(", ")}). Generate strong values and push them now?`)){await Ae(e,r,s,n);return}o.warn(`${String(s.length)} required secret(s) not set on the target: ${s.join(", ")}. Generate + push with \`lunora env generate --set\` then \`lunora env push --yes${r.env===void 0?"":" --prod"}\`.`)}},Ie=async(e,r)=>{const t=new G({skipAddingFilesFromTsConfig:!0}),n=m(r,"lunora");let o;try{o=E(t,n)}catch(i){const a=i instanceof Error?i.message:String(i);return e.logger.warn(`--migrate: could not discover migrations (${a}); skipping`),0}if(o.length===0)return e.logger.info("--migrate: no data migrations declared in lunora/"),0;e.logger.info(`--migrate: running ${String(o.length)} migration(s) against deployed worker`);for(const i of o){e.logger.info(`--migrate: up "${i.id}" (table "${i.table}")`);const a={cwd:r,fetchImpl:e.fetchImpl,id:i.id,logger:e.logger,prod:!0,subcommand:"up",token:e.migrateToken,url:e.migrateUrl,yes:e.migrateYes===!0},c=await de(a);if(c.code!==0)return e.logger.error(`--migrate: migration "${i.id}" failed — see output above`),c.code;e.logger.success(`--migrate: "${i.id}" applied`)}return 0},Le=e=>{if(!(!e.migrate||e.dryRun||e.preview)){if(e.migrateUrl===void 0){const r="--migrate requires --migrate-url <https://your-worker> — the deploy target URL is not captured automatically, refusing to default to localhost";return e.logger.error(r),r}if(e.migrateYes!==!0){const r="--migrate runs production data migrations after deploy. Re-run with --migrate-yes to confirm.";return e.logger.error(r),r}if((e.migrateToken??process.env.LUNORA_ADMIN_TOKEN)===void 0||(e.migrateToken??process.env.LUNORA_ADMIN_TOKEN)===""){const r="admin token required for --migrate — pass --migrate-token or set LUNORA_ADMIN_TOKEN";return e.logger.error(r),r}}},_e=async(e,r,t,n,o,i,a)=>{let c;r?(c=new V({name:"dots"}),c.start("running codegen")):t.info("running codegen");try{const l=_({apiSpec:n,projectRoot:e,target:o});c?.succeed("codegen complete"),c||t.success("codegen complete");const s=await te({cwd:e,logger:t,spawner:i,stdoutToStderr:a});return s.error!==void 0?(t.error(s.error),{error:s.error}):{result:l}}catch(l){c?.failed("codegen failed");const s=l instanceof Error?l.message:String(l);return t.error(`codegen failed: ${s}`),{error:`codegen failed: ${s}`}}},Ee=(e,r)=>{const t=Re(e);if(t===void 0)return;const n=`deploy blocked: the "${t}" D1 binding has a placeholder database_id ("${L}"). Run \`wrangler d1 create <name>\` to create the database, then replace the placeholder in wrangler.jsonc with the real id before deploying.`;return r.error(n),n},Pe=(e,r)=>{const t=D(e);if(!t)return;const{parsed:n}=x(t),o=n?.vars;if(!o)return;const i=he.filter(c=>typeof o[c]=="string"&&ve(o[c]));if(i.length===0)return;const a=`deploy blocked: ${i.join(", ")} in wrangler.jsonc point at localhost. A deployed Worker can't reach a loopback address, so this silently breaks scheduled-job dispatch / auth callbacks. Set each to the deployed worker's public URL (or move it to a secret with \`wrangler secret put\`) before deploying.`;return r.error(a),a},Oe=async(e,r)=>{const{info:t}=K(r,"lunora"),n=t?.vectorMetadata??[];if(n.length===0)return;const o=[];for(const a of n){const c=ce(a.kind);if(c===void 0){e.logger.warn(`vector index "${a.index}" declares metadata "${a.property}", whose column type cannot be filtered on in Vectorize — it is stored with each vector but no filter will match it.`);continue}o.push({index:a.index,property:a.property,type:c})}if(o.length===0)return;const i=(await se({cwd:r,entries:o,exec:v(y(r),"wrangler",[]),logger:e.logger,spawner:e.spawner??b})).filter(a=>a.status!=="failed").length;i>0&&e.logger.success(`vectorize metadata indexes ready: ${String(i)}/${String(o.length)}`)},We=async(e,r,t,n,o)=>{if(await Oe(e,r),e.migrate){const i=await Ie(e,r);return i===0&&o?.(),{code:i,descriptor:t,validation:n}}return o?.(),{code:0,descriptor:t,validation:n}},Be=async(e,r)=>{const t=Ee(e,r.logger);if(t!==void 0)return t;const n=Pe(e,r.logger);if(n!==void 0)return n;const o=$e(e,r.logger);if(o!==void 0)return o;const i=be(e,r.logger,r.dockerAvailable??X);return i!==void 0?i:De(e,r)},Ke=(e,r,t)=>{const n=ke(e);n!==void 0&&r.logger.info(`class-B composition: deploying ${n} (overrides wrangler main)`),r.temporary&&r.logger.info("temporary account: deploying to a short-lived Cloudflare account (~60min); wrangler will print a claim URL"),r.dryRun&&r.logger.info("dry run: validating + bundling without publishing"),r.outDir!==void 0&&r.logger.info(`build artifact: emitting bundle to ${r.outDir}`);const o=R(t),i={dryRun:r.dryRun,entry:n,environment:r.env,outDir:r.outDir,preview:r.preview,temporary:r.temporary};if(o.toolchain===void 0)throw new Error(`deploy target "${o.id}" has no command-line toolchain`);return o.toolchain.deploy(i)},Me=(e,r)=>{if(e.problems.length===0)return!1;r.error("wrangler.jsonc validation failed:");for(const t of e.problems)r.error(` - ${t}`);return!0},qe=async e=>{const r=e.cwd??process.cwd(),t=Se(e),n=J(r,e.target);if(n.target===void 0){const g=n.error??"unknown deploy target";return e.logger.error(g),{code:1,descriptor:void 0,error:g,validation:{problems:[],wranglerPath:void 0}}}const{target:o}=n;let i;if(!e.skipCodegen){const g=await _e(r,t,e.logger,e.apiSpec,o,e.spawner,w(e.format));if(g.error!==void 0)return{code:1,descriptor:void 0,error:g.error,validation:{problems:[],wranglerPath:void 0}};i=g.result}let a;if(i!==void 0){const g=ie({allowDrift:e.allowSchemaDrift===!0,codegen:i,command:"deploy",logger:e.logger,updateBaseline:e.updateSchemaBaseline===!0});if(g.blocked)return{code:1,descriptor:void 0,error:"schema drift gate blocked deploy",schemaDrift:{blocked:!0,reason:g.reason},validation:{problems:[],wranglerPath:void 0}};a=g.rebless}await Ne(r,e.logger,i?.cronTriggers,o);const c=Le(e);if(c!==void 0)return{code:1,descriptor:void 0,error:c,validation:{problems:[],wranglerPath:void 0}};const l=await Be(r,e);if(l!==void 0)return{code:1,descriptor:void 0,error:l,validation:{problems:[],wranglerPath:void 0}};const s=M({projectRoot:r});if(Me(s,e.logger))return{code:1,descriptor:void 0,error:"wrangler validation failed",validation:s};je(r,e.logger);const d=await Ce(r,e,t,o);if(d!==void 0)return e.logger.error(d),{code:1,descriptor:void 0,error:d,validation:s};const p=!w(e.format)&&e.dryRun!==!0&&e.preview!==!0&&S(r)===void 0,f=Ke(r,e,o),N=v(y(r),f.tool,f.args),u={args:N.args,captureStdout:p,command:N.command,cwd:r,stdoutToStderr:w(e.format)};e.logger.info(`deploying via ${u.command} ${u.args.join(" ")}`);const k=await(e.spawner??b)(u);return k.code!==0?{code:k.code,descriptor:u,validation:s}:e.dryRun?{code:0,descriptor:u,validation:s}:e.preview?{code:0,descriptor:u,validation:s}:(me({cwd:r,env:e.env,logger:e.logger,output:k.stdout}),We(e,r,u,s,a))},Ye=async e=>{const r=Z("deploy",e.format);if(r!==void 0)return e.logger.error(r),{code:1,descriptor:void 0,error:r,validation:{problems:[],wranglerPath:void 0}};const t=await qe({...e,logger:re(e.format,e.logger)});return w(e.format)?(ee(t),t):(t.code===0&&e.dryRun!==!0&&e.preview!==!0?fe({cwd:e.cwd??process.cwd(),env:e.env,logger:e.logger,migrated:e.migrate===!0}):t.code===0&&e.preview===!0&&e.logger.success("preview version uploaded — see the preview URL in the wrangler output above"),t)},mr=H(async({cwd:e,logger:r,options:t})=>({code:(await Ye({allowSchemaDrift:t.allowSchemaDrift===!0,apiSpec:z(t.apiSpec),cwd:e,dryRun:t.dryRun===!0,env:t.env,format:t.format,logger:r,migrate:t.migrate===!0,migrateToken:t.migrateToken,migrateUrl:ne({cwd:e,url:t.migrateUrl}),migrateYes:t.migrateYes===!0,preview:t.preview===!0,skipCodegen:t.prebuilt===!0,target:t.target,temporary:t.temporary===!0,updateSchemaBaseline:t.updateSchemaBaseline===!0})).code}));export{mr as execute,Ye as runDeployCommand};
@@ -1,4 +1,4 @@
1
- import{existsSync as h,mkdirSync as L,writeFileSync as m,readFileSync as b,readdirSync as X,rmSync as I,mkdtempSync as Y,lstatSync as Me,cpSync as W,renameSync as Le}from"node:fs";import{tmpdir as Z}from"node:os";import{detectFramework as Se,isInteractive as g,LUNA_ART as Ae,LUNA_NAME as Ne,LUNA_SIGNOFF as Ie,paintAnswer as _e,BADGES as f}from"@lunora/config";import{walkSync as Re}from"@visulima/fs";import{join as p,dirname as $,basename as S,resolve as B,relative as Te}from"@visulima/path";import{downloadTemplate as ee}from"giget";import{modify as Oe,applyEdits as je}from"jsonc-parser";import{join as E,dirname as Be}from"node:path";import{i as Ee}from"../packem_shared/command-Bjv4VmYA.mjs";import{P as te,t as Pe,d as De,k as ze}from"../packem_shared/detect-package-manager-B2eIuAiP.mjs";import Ue from"magic-string";import{Project as ae,SyntaxKind as v}from"ts-morph";import{P}from"../packem_shared/prompt-cancelled-C8Sj7OqI.mjs";import{P as re,g as oe,b as Ve,L as se,k as He}from"../packem_shared/commands-C5pu77HK.mjs";import{defaultSpawner as ie}from"../packem_shared/createRecordingSpawner-ByIqBepG.mjs";import{Y as We,h as qe,M as Fe,C as ne,U as Ke,i as le,X as ce,B as D,H as Je,W as Qe,Q as de,I as Ge,t as Xe}from"../packem_shared/tui-prompts-CCt3jm1k.mjs";import{l as pe,u as Ye,p as Ze,b as et,a as tt,m as at,n as rt,f as ue,q as he,h as ot}from"../packem_shared/storage-BazhWFmM.mjs";import{logStep as q}from"../packem_shared/createLogger--C3x1FNE.mjs";import st from"node:dns/promises";const it=`name: Deploy
1
+ import{existsSync as h,mkdirSync as L,writeFileSync as m,readFileSync as b,readdirSync as X,rmSync as I,mkdtempSync as Y,lstatSync as Me,cpSync as W,renameSync as Le}from"node:fs";import{tmpdir as Z}from"node:os";import{detectFramework as Se,isInteractive as g,LUNA_ART as Ae,LUNA_NAME as Ne,LUNA_SIGNOFF as Ie,paintAnswer as _e,BADGES as f}from"@lunora/config";import{walkSync as Re}from"@visulima/fs";import{join as p,dirname as $,basename as S,resolve as B,relative as Te}from"@visulima/path";import{downloadTemplate as ee}from"giget";import{modify as Oe,applyEdits as je}from"jsonc-parser";import{join as E,dirname as Be}from"node:path";import{i as Ee}from"../packem_shared/command-Bjv4VmYA.mjs";import{P as te,t as Pe,d as De,l as ze}from"../packem_shared/detect-package-manager-C4aS7HE4.mjs";import Ue from"magic-string";import{Project as ae,SyntaxKind as v}from"ts-morph";import{P}from"../packem_shared/prompt-cancelled-C8Sj7OqI.mjs";import{P as re,g as oe,b as Ve,L as se,k as He}from"../packem_shared/commands-C5pu77HK.mjs";import{defaultSpawner as ie}from"../packem_shared/createRecordingSpawner-ByIqBepG.mjs";import{Y as We,h as qe,M as Fe,C as ne,U as Ke,i as le,X as ce,B as D,H as Je,W as Qe,Q as de,I as Ge,t as Xe}from"../packem_shared/tui-prompts-CCt3jm1k.mjs";import{l as pe,u as Ye,p as Ze,b as et,a as tt,m as at,n as rt,f as ue,q as he,h as ot}from"../packem_shared/storage-BazhWFmM.mjs";import{logStep as q}from"../packem_shared/createLogger--C3x1FNE.mjs";import st from"node:dns/promises";const it=`name: Deploy
2
2
 
3
3
  on:
4
4
  push:
@@ -1,11 +1,11 @@
1
- import{existsSync as m,mkdirSync as S,writeFileSync as h,mkdtempSync as C,rmSync as I,readFileSync as k}from"node:fs";import{tmpdir as A}from"node:os";import{discoverSchema as T,discoverMigrations as N}from"@lunora/codegen";import{isInteractive as M,promptSelect as z,promptText as E}from"@lunora/config";import{LunoraError as $}from"@lunora/errors";import{join as c}from"@visulima/path";import{Project as w}from"ts-morph";import{u as F}from"../packem_shared/admin-url-Ca-KI3d_.mjs";import{i as O}from"../packem_shared/command-Bjv4VmYA.mjs";import{diffSnapshots as R,renderMigrationFile as q}from"../packem_shared/diffSnapshots-9bDd9nOK.mjs";import{s as D}from"../packem_shared/resolve-target-vxaXHmvg.mjs";import L from"../packem_shared/schemaIrToSnapshot-Clwd2A8e.mjs";import{runExportCommand as j,runImportCommand as B}from"../packem_shared/DEFAULT_IMPORT_BATCH_SIZE-CEOt386P.mjs";const H=".snapshot.json",x=/[^\da-z]+/gu,U=(r,e)=>{let o=0,t=r.length;for(;o<t&&r[o]===e;)o+=1;for(;t>o&&r[t-1]===e;)t-=1;return r.slice(o,t)},J=r=>{const e=U(r.toLowerCase().replaceAll(x,"_"),"_");return e===""?"auto":e},P=r=>{const e=(o,t=2)=>o.toString().padStart(t,"0");return`${String(r.getUTCFullYear())}${e(r.getUTCMonth()+1)}${e(r.getUTCDate())}${e(r.getUTCHours())}${e(r.getUTCMinutes())}${e(r.getUTCSeconds())}`},Z=r=>{if(m(r))try{const e=k(r,"utf8"),o=JSON.parse(e);if(o.version!==1)throw new $("INTERNAL",`unsupported snapshot version: ${o.version}`);return o}catch(e){const o=e instanceof Error?e.message:String(e);throw new $("INTERNAL",`failed to read ${r}: ${o}`,{cause:e})}},G=r=>{const e=r.cwd??process.cwd(),o=c(e,"lunora","schema.ts");if(!m(o))return r.logger.error(`schema not found: ${o} — run \`vis generate lunora-table --name=<name>\` to create one`),{code:1,empty:!0,migrationFile:""};const t=new w({skipAddingFilesFromTsConfig:!0}),n=T(t,o),a=L(n),i=c(e,"lunora","migrations"),s=c(i,H);let d;try{d=Z(s)}catch(p){return r.logger.error(p instanceof Error?p.message:String(p)),{code:1,empty:!0,migrationFile:""}}const l=R(d,a);if(l.empty)return r.logger.info("no schema changes detected — snapshot is already up to date"),{code:0,empty:!0,migrationFile:""};const u=(r.now??(()=>new Date))(),b=J(r.name??"auto"),y=`${P(u)}_${b}.sql`,g=c(i,y);S(i,{recursive:!0});const _=q(b,l,u.toISOString());return h(g,_,"utf8"),h(s,`${JSON.stringify(a,void 0,4)}
2
- `,"utf8"),r.logger.success(`wrote ${g}`),l.unsupported.length>0&&r.logger.warn(`${String(l.unsupported.length)} unsupported diff(s) — see the comment block in ${y} and write the SQL manually`),{code:0,empty:!1,migrationFile:g}},K="migrations.ts",v=/^[A-Za-z_]\w*$/u,Q=new Set(["await","break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","false","finally","for","function","if","implements","import","in","instanceof","interface","let","new","null","package","private","protected","public","return","static","super","switch","this","throw","true","try","typeof","var","void","while","with","yield"]),f='import { defineMigration } from "@lunora/server";',V="__lunora_admin__:runMigration",W="__lunora_admin__:migrationStatus",Y="/_lunora/migrate",X=r=>U(r.trim().toLowerCase().replaceAll(x,"-"),"-"),rr=r=>r.split("-").filter(e=>e.length>0).map((e,o)=>o===0?e:e.charAt(0).toUpperCase()+e.slice(1)).join(""),er=r=>{const e=c(r,"lunora","schema.ts");if(!m(e))return[];try{const o=new w({skipAddingFilesFromTsConfig:!0});return T(o,e).tables.map(t=>t.name)}catch{return[]}},tr=async r=>r.length>0?z("Which table does this migration iterate?",r.map(e=>({label:e,value:e}))):E("Target table for the migration: "),or=async(r,e)=>{if(e.table!==void 0)return e.table;const o=e.promptTable??(M()?tr:void 0);if(o===void 0){e.logger.error("migrate create requires a target table when not running interactively — re-run with --table <table>");return}const t=(await o(er(r)))?.trim();if(t===void 0||t===""){e.logger.error("no table selected — re-run with --table <table>");return}return t},nr=async r=>{const e=r.cwd??process.cwd(),o=X(r.name);if(o==="")return r.logger.error(`invalid migration name: "${r.name}" — must contain at least one alphanumeric character`),{code:1,file:""};const t=rr(o);if(!v.test(t)||Q.has(t))return r.logger.error(`invalid migration name: "${r.name}" derives the export \`${t}\`, which is not a valid identifier — pick a name that starts with a letter and isn't a reserved word`),{code:1,file:""};const n=await or(e,r);if(n===void 0)return{code:1,file:""};if(!v.test(n))return r.logger.error(`invalid table: "${n}" — must be a valid identifier ([A-Za-z_][A-Za-z0-9_]*)`),{code:1,file:""};const a=c(e,"lunora"),i=c(a,K);let s=m(i)?k(i,"utf8"):"";if(s.includes(`id: "${o}"`)||new RegExp(String.raw`\bexport const ${t}\b`,"u").test(s))return r.logger.error(`a migration with id "${o}" (export \`${t}\`) already exists in ${i}`),{code:1,file:""};s.trim()===""?s=`${f}
3
- `:s.includes(f)||(s=`${f}
4
- ${s}`);const d=`export const ${t} = defineMigration({
1
+ import{existsSync as m,mkdirSync as S,writeFileSync as f,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 N,discoverMigrations as z}from"@lunora/codegen";import{isInteractive as A,promptSelect as E,promptText as F}from"@lunora/config";import{LunoraError as $}from"@lunora/errors";import{join as c}from"@visulima/path";import{Project as h}from"ts-morph";import{u as O}from"../packem_shared/admin-url-Ca-KI3d_.mjs";import{i as R}from"../packem_shared/command-Bjv4VmYA.mjs";import{diffSnapshots as q,renderMigrationFile as D}from"../packem_shared/diffSnapshots-9bDd9nOK.mjs";import{s as L}from"../packem_shared/resolve-target-vxaXHmvg.mjs";import j from"../packem_shared/schemaIrToSnapshot-Clwd2A8e.mjs";import{runExportCommand as B,runImportCommand as H}from"../packem_shared/DEFAULT_IMPORT_BATCH_SIZE-xn-frBqK.mjs";const J=".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)},P=r=>{const e=U(r.toLowerCase().replaceAll(x,"_"),"_");return e===""?"auto":e},Z=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(m(r))try{const e=k(r,"utf8"),o=JSON.parse(e);if(o.version!==1)throw new $("INTERNAL",`unsupported snapshot version: ${o.version}`);return o}catch(e){const o=e instanceof Error?e.message:String(e);throw new $("INTERNAL",`failed to read ${r}: ${o}`,{cause:e})}},Q=r=>{const e=r.cwd??process.cwd(),o=c(e,"lunora","schema.ts");if(!m(o))return r.logger.error(`schema not found: ${o} — run \`vis generate lunora-table --name=<name>\` to create one`),{code:1,empty:!0,migrationFile:""};const t=new h({skipAddingFilesFromTsConfig:!0}),n=T(t,o),s=j(n),i=c(e,"lunora","migrations"),a=c(i,J);let d;try{d=K(a)}catch(p){return r.logger.error(p instanceof Error?p.message:String(p)),{code:1,empty:!0,migrationFile:""}}const l=q(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 u=(r.now??(()=>new Date))(),w=P(r.name??"auto"),b=`${Z(u)}_${w}.sql`,g=c(i,b);S(i,{recursive:!0});const _=D(w,l,u.toISOString());return f(g,_,"utf8"),f(a,`${JSON.stringify(s,void 0,4)}
2
+ `,"utf8"),r.logger.success(`wrote ${g}`),l.unsupported.length>0&&r.logger.warn(`${String(l.unsupported.length)} unsupported diff(s) — see the comment block in ${b} and write the SQL manually`),{code:0,empty:!1,migrationFile:g}},W="migrations.ts",y=/^[A-Za-z_]\w*$/u,Y=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,G=r=>`import { defineMigration } from "${N(r)?.has("lunorash")??!1?"lunorash/server":"@lunora/server"}";`,V="__lunora_admin__:runMigration",X="__lunora_admin__:migrationStatus",rr="/_lunora/migrate",er=r=>U(r.trim().toLowerCase().replaceAll(x,"-"),"-"),tr=r=>r.split("-").filter(e=>e.length>0).map((e,o)=>o===0?e:e.charAt(0).toUpperCase()+e.slice(1)).join(""),or=r=>{const e=c(r,"lunora","schema.ts");if(!m(e))return[];try{const o=new h({skipAddingFilesFromTsConfig:!0});return T(o,e).tables.map(t=>t.name)}catch{return[]}},nr=async r=>r.length>0?E("Which table does this migration iterate?",r.map(e=>({label:e,value:e}))):F("Target table for the migration: "),ir=async(r,e)=>{if(e.table!==void 0)return e.table;const o=e.promptTable??(A()?nr: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(or(r)))?.trim();if(t===void 0||t===""){e.logger.error("no table selected — re-run with --table <table>");return}return t},ar=async r=>{const e=r.cwd??process.cwd(),o=er(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=tr(o);if(!y.test(t)||Y.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 ir(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,W);let a=m(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=G(e);a.trim()===""?a=`${d}
3
+ `:v.test(a)?a=a.replace(v,d):a=`${d}
4
+ ${a}`;const l=`export const ${t} = defineMigration({
5
5
  id: "${o}",
6
6
  table: "${n}",
7
7
  up: (document) => document,
8
- });`;return S(a,{recursive:!0}),h(i,`${s.trimEnd()}
8
+ });`;return S(s,{recursive:!0}),f(i,`${a.trimEnd()}
9
9
 
10
- ${d}
11
- `,"utf8"),r.logger.success(`scaffolded migration "${o}" in ${i}`),{code:0,file:i}},ir=(r,e)=>{const o=new w({skipAddingFilesFromTsConfig:!0});return N(o,c(r,"lunora")).find(t=>t.id===e)?.table},ar=(r,e)=>{let o;try{o=ir(r,e.id)}catch(t){e.logger.error(t instanceof Error?t.message:String(t));return}if(o===void 0){e.logger.error(`migration "${e.id}" not found under lunora/ — declare it with defineMigration({ id: "${e.id}", ... })`);return}if(o===""){e.logger.error(`migration "${e.id}" must declare \`table\` as a static string literal`);return}return o},sr=r=>{const e=r.cwd??process.cwd();if(r.prod&&r.url===void 0){r.logger.error("--prod requires an explicit --url (refusing to migrate the implicit localhost worker)");return}if(r.prod&&(r.subcommand==="up"||r.subcommand==="down")&&!r.yes){r.logger.error(`migrate ${r.subcommand} --prod runs the migration against production. Re-run with --yes to confirm.`);return}const o=r.token??process.env.LUNORA_ADMIN_TOKEN;if(!o){r.logger.error("admin token required — pass --token or set LUNORA_ADMIN_TOKEN");return}const t=ar(e,r);if(t===void 0)return;const n=F(r.url,r.logger,r.cwd);if(n===void 0)return;const a=r.fetchImpl??globalThis.fetch;if(typeof a!="function")throw new TypeError("no fetch implementation available — pass fetchImpl or run on Node >= 18");return{fetchImpl:a,requestUrl:`${n}${Y}`,table:t,token:o}},cr=r=>{const e={id:r.id};return r.subcommand==="status"||(e.direction=r.subcommand,r.dryRun&&(e.dryRun=!0),r.batchSize!==void 0&&(e.batchSize=r.batchSize),r.maxBatches!==void 0&&(e.maxBatches=r.maxBatches)),e},dr=async r=>{const e=sr(r);if(e===void 0)return{body:void 0,code:1,requestUrl:""};const{fetchImpl:o,requestUrl:t,table:n,token:a}=e,i=r.subcommand==="status"?W:V,s=cr(r);r.logger.info(`POST ${t} -> ${r.subcommand} ${r.id} (table "${n}")`);const d=await o(t,{body:JSON.stringify({args:s,functionPath:i,table:n}),headers:{authorization:`Bearer ${a}`,"content-type":"application/json"},method:"POST"}),l=await d.text();let u;try{u=JSON.parse(l)}catch{u=l}return r.logger.info(JSON.stringify(u,void 0,2)),{body:u,code:d.ok?0:1,requestUrl:t}},lr=async r=>{const{logger:e}=r,o=r.fromUrl??r.toUrl,t=r.toUrl??r.fromUrl;if(o!==void 0&&o===t)return e.error("source and target are the same deployment — pass distinct --from-url and --to-url so the D1 export and Hyperdrive import don't run against one database"),{code:1};const n=r.out===void 0?C(c(A(),"lunora-d1ps-")):void 0,a=r.out??c(n,"dump.ndjson");try{e.info(`Exporting .global() data from the D1 source (${o??"http://localhost:8787"}) …`);const i=await j({fetchImpl:r.fetchImpl,logger:e,out:a,prod:r.prod,tables:r.tables,token:r.fromToken,url:o});if(i.code!==0)return{code:i.code};e.info(`Exported ${String(i.rows)} row(s) (${String(i.bytes)} bytes).`),e.info(`Importing into the Hyperdrive target (${t??"http://localhost:8787"}) …`);const s=await B({batchSize:r.batchSize,fetchImpl:r.fetchImpl,file:a,logger:e,prod:r.prod,token:r.toToken,url:t});return s.code!==0?{code:s.code}:(s.inserted===i.rows?e.info(`✓ Migrated ${String(i.rows)} row(s) — counts match. Verify your app reads from Hyperdrive, then decommission the D1 binding.`):e.warn(`Imported ${String(s.inserted)} of ${String(i.rows)} exported row(s) — the remainder likely already existed in the target (see conflicts above). Re-run after resolving, or inspect the dump with --out.`),{code:0})}finally{n!==void 0&&I(n,{force:!0,recursive:!0})}},Tr=O(({argument:r,cwd:e,logger:o,options:t})=>{const n=r[0];if(n==="generate")return G({cwd:e,logger:o,name:r[1]??t.name});if(n==="d1-to-hyperdrive")return lr({batchSize:t.batchSize,fromToken:t.fromToken??t.token,fromUrl:t.fromUrl??t.url,logger:o,out:t.out,prod:t.prod===!0,tables:t.tables,toToken:t.toToken??t.token,toUrl:t.toUrl??t.url});if(n==="create"){const a=r[1]??t.name;return a?nr({cwd:e,logger:o,name:a,table:t.table}):(o.error("migrate create requires a name. Usage: lunora migrate create <name> [--table <table>]"),{code:1})}if(n==="up"||n==="down"||n==="status"){const a=r[1]??t.name;return a?dr({batchSize:t.batchSize,cwd:e,dryRun:t.dryRun===!0,id:a,logger:o,maxBatches:t.steps,prod:t.prod===!0,subcommand:n,token:t.token,url:D({cwd:e,prod:t.prod===!0,url:t.url}),yes:t.yes===!0}):(o.error(`migrate ${n} requires a migration id. Usage: lunora migrate ${n} <id>`),{code:1})}return o.error(`unknown migrate subcommand: "${n??""}" — expected generate | create | up | down | status`),{code:1}});export{Tr as execute,nr as runMigrateCreateCommand,dr as runMigrateDataCommand,G as runMigrateGenerateCommand,lr as runMigrateToHyperdriveCommand};
10
+ ${l}
11
+ `,"utf8"),r.logger.success(`scaffolded migration "${o}" in ${i}`),{code:0,file:i}},sr=(r,e)=>{const o=new h({skipAddingFilesFromTsConfig:!0});return z(o,c(r,"lunora")).find(t=>t.id===e)?.table},cr=(r,e)=>{let o;try{o=sr(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},dr=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=cr(e,r);if(t===void 0)return;const n=O(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}${rr}`,table:t,token:o}},lr=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},ur=async r=>{const e=dr(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"?X:V,a=lr(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"}),l=await d.text();let u;try{u=JSON.parse(l)}catch{u=l}return r.logger.info(JSON.stringify(u,void 0,2)),{body:u,code:d.ok?0:1,requestUrl:t}},mr=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 B({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 H({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})}},Ur=R(({argument:r,cwd:e,logger:o,options:t})=>{const n=r[0];if(n==="generate")return Q({cwd:e,logger:o,name:r[1]??t.name});if(n==="d1-to-hyperdrive")return mr({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?ar({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?ur({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{Ur as execute,ar as runMigrateCreateCommand,ur as runMigrateDataCommand,Q as runMigrateGenerateCommand,mr 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{s as M,t as N,e as O}from"./cli-BxL0WCh4.mjs";import"./createLogger--C3x1FNE.mjs";export{M as COMMANDS,N as VERSION,O as runCli};
1
+ import"node:fs";import"node:path";import"node:url";import"@lunora/errors";import"@visulima/cerebro";import"@visulima/cerebro/command/completion";import"@visulima/cerebro/command/version";import{d as N,e as S,i as A,p as C}from"./cli-0uJWyeda.mjs";import"./createLogger--C3x1FNE.mjs";export{N as COMMANDS,S as REGISTERED_COMMAND_NAMES,A as VERSION,C as runCli};
@@ -0,0 +1,12 @@
1
+ import{createWriteStream as P,createReadStream as E}from"node:fs";import{unlink as _,stat as v,readdir as A}from"node:fs/promises";import{join as R}from"node:path";import{LunoraError as N}from"@lunora/errors";import{l as j}from"./admin-token-DV5A9T5b.mjs";import{u as C}from"./admin-url-Ca-KI3d_.mjs";const L="/_lunora/admin/export",q="/_lunora/admin/import",U=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 n=0,a=0,i="",l=!1;try{for(;!l;){const u=await o.read();if(l=u.done,u.value===void 0)continue;n+=u.value.length,i+=e.decode(u.value,{stream:!0});let d=i.indexOf(`
2
+ `);for(;d!==-1;){a+=1;const g=`${i.slice(0,d)}
3
+ `;await k(r,g),i=i.slice(d+1),d=i.indexOf(`
4
+ `)}}return i.length>0&&(a+=1,await k(r,`${i}
5
+ `)),{bytes:n,rows:a}}finally{o.releaseLock()}},F=async(t,r)=>{if(r!==void 0){t.destroy();try{await _(r)}catch{}}},ot=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=C(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}${L}`,n=z(t.tables),a=t.fetchImpl??globalThis.fetch;if(typeof a!="function")throw new TypeError("no fetch implementation available — pass fetchImpl or run on Node >= 18");t.logger.info(`POST ${e} -> export${n?` (tables: ${n.join(",")})`:""}`);const i=await a(e,{body:JSON.stringify(n?{tables:n}:{}),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 l=t.out===void 0||t.out==="-"?void 0:t.out,u=l===void 0?process.stdout:P(l,{encoding:"utf8"});let d,g;try{({bytes:d,rows:g}=await B(i.body,u))}catch(p){throw await F(u,l),p}return l!==void 0&&(await new Promise((p,b)=>{u.end(w=>{w?b(w):p()})}),t.logger.success(`wrote ${String(g)} rows to ${l} (${String(d)} bytes)`)),{bytes:d,code:0,rows:g}},H=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=C(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 n=await v(t.file);if(!n.isFile()&&!n.isDirectory()){t.logger.error(`not a file or directory: ${t.file}`);return}}catch(n){const a=n instanceof Error?n.message:String(n);t.logger.error(`failed to stat ${t.file}: ${a}`);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}${q}`,token:o}},I="_storage",M=async t=>{if(!(await v(t).catch(()=>{}))?.isDirectory())return;const r=[];for(const o of await A(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*K(t,r){let o="";for await(const n of E(t,{encoding:"utf8"})){o+=typeof n=="string"?n:n.toString("utf8");let a=o.indexOf(`
6
+ `);for(;a!==-1;){const i=o.slice(0,a).trim();o=o.slice(a+1),i.length>0&&(yield`${JSON.stringify({doc:JSON.parse(i),table:r})}
7
+ `),a=o.indexOf(`
8
+ `)}}const e=o.trim();e.length>0&&(yield`${JSON.stringify({doc:JSON.parse(e),table:r})}
9
+ `)}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*K(o,e)}}const Z=async t=>{const r=await M(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}},G=(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)`)},et=async t=>{const r=await H(t);if(r===void 0)return{body:void 0,code:1,inserted:0};const{fetchImpl:o,requestUrl:e,token:n}=r,a=t.batchSize??U,i=await Z(t);if(i.error)return{body:void 0,code:1,inserted:0};const{convexTables:l}=i;t.logger.info(l?`POST ${e} -> import Convex export ${t.file} (${String(l.length)} tables)`:`POST ${e} -> import ${t.file}`);const u=l?W(l,t.logger):E(t.file,{encoding:"utf8"}),d={},g=[];let p=0,b=0;const w=[];let m="",h=[],$=0;const D=c=>{for(const[s,f]of Object.entries(c.inserted??{}))d[s]=(d[s]??0)+f;g.push(...c.errors??[]),p+=c.conflicts??0,b+=c.received??0;for(const s of c.warnings??[])w.includes(s)||w.push(s)},S=async()=>{if(h.length===0)return;const c=h.join(`
10
+ `);h=[];const s=await o(e,{body:c,headers:{authorization:`Bearer ${n}`,"content-type":"application/x-ndjson"},method:"POST"});if(!s.ok){const y=await s.text().catch(()=>"<no body>");throw new N("INTERNAL",`import batch failed (HTTP ${String(s.status)}): ${y}`)}const f=await s.json();D(f)},x=c=>{const s=c.trim();if(s.length===0)return;if($+=1,t.table===void 0){h.push(s);return}let f;try{f=JSON.parse(s)}catch(y){const J=y instanceof Error?y.message:String(y);throw new N("INTERNAL",`invalid JSON on line ${String($)}: ${J}`,{cause:y})}h.push(JSON.stringify({doc:f,table:t.table}))};for await(const c of u){const s=typeof c=="string"?c:c.toString("utf8");m+=s;let f=m.indexOf(`
11
+ `);for(;f!==-1;)x(m.slice(0,f)),m=m.slice(f+1),f=m.indexOf(`
12
+ `),h.length>=a&&await S()}m.length>0&&x(m),await S();const O=Object.values(d).reduce((c,s)=>c+s,0),T={conflicts:p,errors:g,inserted:d,received:b,...w.length>0?{warnings:w}:{}};return t.logger.info(JSON.stringify(T,void 0,2)),G(t.logger,{conflicts:p,errorCount:g.length,insertedTotal:O,received:b,warnings:w}),{body:T,code:g.length>0?1:0,inserted:O}};export{U as DEFAULT_IMPORT_BATCH_SIZE,ot as runExportCommand,et as runImportCommand};
@@ -0,0 +1,3 @@
1
+ import{mkdirSync as A,readFileSync as w,lstatSync as B,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 E,isLunoraError as k,flattenHint as j,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{createLogger as S}from"./createLogger--C3x1FNE.mjs";import{VisulimaError as $,renderError as T}from"@visulima/error";import{homedir as U}from"node:os";const M={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",W={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:"write",type:Boolean}]},J={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}]},K={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}]},q={description:"Codegen + validate + bundle the Worker to disk without deploying",examples:[["lunora build","Bundle to .lunora/build without deploying"],["lunora build --out-dir dist-worker","Bundle to a custom directory"]],group:"Deploy",loader:()=>import("../packem_chunks/handler4.mjs").then(e=>({default:e.execute})),name:"build",options:[{description:`Which API spec(s) to emit: ${p} (default openapi)`,name:"api-spec",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Directory to write the bundled Worker to (default .lunora/build)",name:"out-dir",type:String},s]},F={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:"Don't fail on ERROR-level advisories (the gate defaults to on in CI, off locally)",name:"no-strict-advisories",type:Boolean},s]},H={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}]},V={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:"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}]},z={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}]},G={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}]},Y={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"},Q={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:[]},X={argument:{description:"list | get <KEY> | set <KEY> <VALUE> | unset <KEY> | generate [KEY] | push | diff | doctor",name:"subcommand",type:String},description:"Manage .dev.vars and sync secrets via wrangler (list | get | set | unset | generate | push | diff | doctor)",examples:[["lunora env list","List .dev.vars keys"],["lunora env set API_KEY secret","Set a local variable"],["lunora env generate","Generate strong values for the project's secrets (print KEY=value)"],["lunora env generate AUTH_SECRET --set","Generate one secret and write it to .dev.vars"],["lunora env push --yes","Upload secrets to Cloudflare"],["lunora env diff","Compare local .dev.vars keys against Cloudflare"]],group:"Data",loader:()=>import("../packem_chunks/handler9.mjs").then(e=>({default:e.execute})),name:"env",options:[{description:"Target production for `push` (passes --env production to wrangler)",name:"prod",type:Boolean},{description:"For `generate` — write the generated secrets into .dev.vars instead of printing them",name:"set",type:Boolean},{description:"Push secrets to a temporary-account deployment when unauthenticated (wrangler secret put --temporary). Errors if you're already authenticated.",name:"temporary",type:Boolean},{description:"Required for `push` — confirms uploading secrets to Cloudflare",name:"yes",type:Boolean}]},Z={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}]},ee={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}]},te={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}]},re={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}]},oe={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}]},ne={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/handler23.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}]},ae={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}]},ie={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}]},se={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/handler24.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}]},le={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}]},pe={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}]},de={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}]},ce={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}]},ue={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}]},me={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}]},ge={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}]},he={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]},ye={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}]},fe={filterStacktrace:()=>!1,hideErrorCodeView:!0},ve=(e,t={})=>{const r=e instanceof Error?e.message:String(e),o=E(k(e)?{code:e.code,hint:e.hint,message:r}:r),n=new $({hint:o===void 0?void 0:j(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="",T(n,fe)},be=(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},we=(e,t)=>{let r,o=Number.POSITIVE_INFINITY;for(const a of t){const i=be(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},ke=e=>`https://registry.npmjs.org/@lunora/cli/${e}`,Se=1440*60*1e3,xe=1500,Ne="0.0.0",Oe=/^v/u,Re=new Set(["alpha","beta","next"]),m=e=>{const t=e.trim().replace(Oe,""),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]},Ae=(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},Be=(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 Ae(a,i)}return 0},De=(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 Be(m(e).prerelease,m(t).prerelease)},Le=e=>{const t=m(e).prerelease.split(".")[0]??"";return Re.has(t)?t:"latest"},Ee=(e,t)=>De(t,e)>0,je=(e,t,r)=>t-e<r,Ce=(e,t,r="latest")=>`Update available for @lunora/cli: ${e} → ${t} — run \`pnpm add -D @lunora/cli@${r}\``,x=e=>u(e,"lunora-cli-update.json"),Ie=e=>{const t=e.XDG_CACHE_HOME&&e.XDG_CACHE_HOME.length>0?e.XDG_CACHE_HOME:u(U(),".cache"),r=u(t,"lunora");try{A(r,{mode:448,recursive:!0})}catch{}return r},_e=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(B(r).isSymbolicLink())return}catch{}D(r,`${JSON.stringify(t)}
3
+ `,"utf8")}catch{}},Pe=async(e,t)=>{try{const r=await e(ke(t),{signal:AbortSignal.timeout(xe)});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}},$e=(e,t,r)=>e===Ne||!r||t.CI!==void 0||t.LUNORA_NO_UPDATE_NOTIFIER!==void 0,Te=async e=>{const t=e.env??process.env,r=e.isTTY??process.stdout.isTTY;if($e(e.current,t,r))return;const o=e.cacheDir??Ie(t),n=(e.now??Date.now)(),a=e.ttlMs??Se,i=Le(e.current),d=_e(o),R=d?.tag??"latest",g=d!==void 0&&R===i?d:void 0;let c=g?.latest;if(g===void 0||!je(g.checkedAt,n,a)){const h=await Pe(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&&Ee(e.current,c)&&e.logger.warn(Ce(e.current,c,i))},Ue=["init","add","dev","codegen","build","deploy","containers","prepare","link","deployments","logs","run","insights","reset","migrate","export","import","seed","backup","verify","info","doctor","env","analyze","view","docs","registry","rules","mcp"],Me=8,We=()=>{try{let e=y(L(import.meta.url));for(let t=0;t<Me;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"},N=We(),Je=[re,M,G,F,W,q,V,H,pe,ae,z,ie,me,oe,ce,le,Z,ee,ge,ne,K,he,te,Q,X,J,ye,Y,de,ue,se],O=[...Je,P,_],it=O.map(e=>e.name),l=e=>e.replaceAll("{",String.raw`\{`).replaceAll("}",String.raw`\}`),Ke=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))),qe=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:Ke(e.examples)},...e.options===void 0?{}:{options:e.options.map(t=>({...t,description:l(t.description??"")}))}}),Fe=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:N});for(const o of O)r.addCommand(qe(o));return{cli:r,exitCode:t}},He=/Command "(?<name>[^"]+)" not found/u,Ve=e=>{const t=S(),r=e instanceof Error?e.message:String(e),o=He.exec(r);if(!o?.groups){k(e)||C(r)!==void 0?t.error(ve(e)):t.error(r);return}const n=o.groups.name??"",a=we(n,Ue);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.")},st=async(e={})=>{const{cli:t,exitCode:r}=Fe(e);try{await t.run({shouldExitProcess:!1})}catch(o){return Ve(o),1}return await Te({current:N,logger:S()}),r.value};export{Ue as d,it as e,N as i,f as o,st as p};
@@ -1 +1 @@
1
- import{spawnSync as t}from"node:child_process";import{LunoraError as m}from"@lunora/errors";import{findPackageManagerSync as o,identifyInitiatingPackageManager as p}from"@visulima/package/package-manager";const c=["pnpm","bun","yarn","npm"],i=new Set(["bun","npm","pnpm","yarn"]),s=n=>i.has(n),u=n=>{try{return t(n,["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}},d=(n=u)=>c.filter(a=>n(a)),y=n=>({args:["install"],command:n}),b=n=>{try{return o(n).packageManager}catch{}const a=p();if(a!==void 0){const e=a.name==="cnpm"?"npm":a.name;if(s(e))return e}const[r]=d();if(r!==void 0)return r;throw new m("INTERNAL","Could not detect a package manager: no lock file or `packageManager` field was found, and none (pnpm, bun, yarn, npm) is installed on PATH.")},k=(n,a,r)=>n==="yarn"?{args:[a,...r],command:"yarn"}:n==="bun"?{args:["x",a,...r],command:"bun"}:n==="npm"?{args:["--",a,...r],command:"npx"}:{args:["exec",a,...r],command:"pnpm"},w=(n,a)=>n==="npm"?`npm run ${a}`:n==="bun"?`bun run ${a}`:`${n} ${a}`;export{k as M,b as P,y as d,w as k,d as t};
1
+ import{spawnSync as m}from"node:child_process";import{LunoraError as o}from"@lunora/errors";import{findPackageManagerSync as t,identifyInitiatingPackageManager as p}from"@visulima/package/package-manager";const c=["pnpm","bun","yarn","npm"],i=new Set(["bun","npm","pnpm","yarn"]),s=n=>i.has(n),u=n=>{try{return m(n,["--version"],{stdio:"ignore",timeout:5e3}).status===0}catch{return!1}},d=(n=u)=>c.filter(a=>n(a)),y=n=>({args:["install"],command:n}),b=n=>{try{return t(n).packageManager}catch{}const a=p();if(a!==void 0){const e=a.name==="cnpm"?"npm":a.name;if(s(e))return e}const[r]=d();if(r!==void 0)return r;throw new o("INTERNAL","Could not detect a package manager: no lock file or `packageManager` field was found, and none (pnpm, bun, yarn, npm) is installed on PATH.")},k=(n,a,r)=>n==="yarn"?{args:[a,...r],command:"yarn"}:n==="bun"?{args:["x",a,...r],command:"bun"}:n==="npm"?{args:["--",a,...r],command:"npx"}:{args:["exec",a,...r],command:"pnpm"},w=(n,a)=>({args:["run",a],command:n}),M=(n,a)=>n==="npm"?`npm run ${a}`:n==="bun"?`bun run ${a}`:`${n} ${a}`;export{k as M,b as P,y as d,w as k,M as l,d as t};
@@ -0,0 +1 @@
1
+ import{existsSync as c,readFileSync as i}from"node:fs";import{join as u}from"@visulima/path";import{k as f,P as d}from"./detect-package-manager-C4aS7HE4.mjs";import{defaultSpawner as m}from"./createRecordingSpawner-ByIqBepG.mjs";const t="postcodegen",g=n=>{const e=u(n,"package.json");if(!c(e))return!1;try{const o=JSON.parse(i(e,"utf8"))?.scripts;return typeof o?.[t]=="string"&&o[t]!==""}catch{return!1}},$=async n=>{const{cwd:e,logger:o}=n;if(!g(e))return{ran:!1};let a;try{a=f(d(e),t)}catch(r){return{error:`cannot run \`${t}\`: ${r instanceof Error?r.message:String(r)}`,ran:!0}}o.info(`running \`${t}\``);let s;try{s=await(n.spawner??m)({args:a.args,command:a.command,cwd:e,stdoutToStderr:n.stdoutToStderr})}catch(r){return{error:`\`${t}\` failed to start: ${r instanceof Error?r.message:String(r)}`,ran:!0}}return s.code!==0?{error:`\`${t}\` exited ${String(s.code)}`,ran:!0}:{ran:!0}};export{$ as m};
@@ -0,0 +1 @@
1
+ import{existsSync as u,readFileSync as d,writeFileSync as g}from"node:fs";import{evaluateSchemaDrift as m,parseSchemaSnapshot as p,SchemaSnapshotParseError as b,serializeSchemaSnapshot as f}from"@lunora/codegen";const S=e=>{if(!u(e))return{status:"absent"};let s;try{s=d(e,"utf8")}catch{return{status:"corrupt"}}try{const a=p(s);return a===void 0?{status:"corrupt"}:{snapshot:a,status:"ok"}}catch(a){if(a instanceof b)return{status:"corrupt"};throw a}},k=(e,s)=>{g(e,f(s),"utf8")},y=e=>{const s=`schema-drift gate: the committed baseline ${e.snapshotPath} is unreadable or malformed, so schema drift cannot be checked. Fix it (e.g. resolve a merge conflict in lunora/.lunora-schema.json), or pass --update-schema-baseline to regenerate it from the current schema.`;return e.updateBaseline&&!e.readOnly?(e.logger.warn(`schema baseline was unreadable; regenerating from the current schema on success (--update-schema-baseline): ${e.snapshotPath}`),{blocked:!1,changes:[],reason:s,rebless:e.rebless}):(e.readOnly||e.logger.error(s),{blocked:!0,changes:[],reason:s})},w=(e,s)=>(s.readOnly||s.logger.error(e.reason),s.updateBaseline&&!s.readOnly?(s.logger.warn(`schema baseline will be re-blessed despite breaking drift on success (--update-schema-baseline): ${s.snapshotPath}`),{blocked:!1,changes:e.changes,reason:e.reason,rebless:s.rebless}):{blocked:!0,changes:e.changes,reason:e.reason}),v=e=>{const{allowDrift:s,codegen:a,command:h,logger:l,readOnly:t=!1,updateBaseline:i=!1}=e,n=a.schemaSnapshotPath,o=S(n),c={logger:l,readOnly:t,rebless:()=>{k(n,a.schemaSnapshot)},snapshotPath:n,updateBaseline:i};if(o.status==="corrupt")return y(c);const r=m({allowDrift:s,baseline:o.status==="ok"?o.snapshot:void 0,command:h,current:a.schemaSnapshot});return r.blocked?w(r,c):r.changes.length>0?(t||l.info(r.reason),{blocked:!1,changes:r.changes,reason:r.reason,rebless:t?void 0:c.rebless}):{blocked:!1,changes:r.changes,reason:r.reason}};export{v as R};
@@ -1 +1 @@
1
- import{execFile as c}from"node:child_process";import{resolveDeployDriver as i,resolveProjectTarget as l}from"@lunora/config";import{M as m,P as d}from"./detect-package-manager-B2eIuAiP.mjs";const p=r=>r?typeof r.code=="number"?r.code:1:0,f=(r,o,e)=>new Promise(n=>{c(r,[...o],{cwd:e},(t,a,s)=>{n({code:p(t),stderr:s,stdout:a})})}),u=r=>{let o;try{o=JSON.parse(r)}catch{return}return Array.isArray(o)?[...o.map(e=>e!==null&&typeof e=="object"?e.name:void 0).filter(e=>typeof e=="string"&&e.length>0)].toSorted((e,n)=>e.localeCompare(n)):void 0},w=async r=>{const o=i(l(r.cwd)).toolchain?.secretList({environment:r.env,temporary:r.temporary});if(o===void 0)return{error:"deploy target has no command-line toolchain",names:[],ok:!1};const{args:e,command:n}=m(d(r.cwd),o.tool,o.args),t=await(r.runner??f)(n,e,r.cwd);if(t.code!==0)return{error:t.stderr.trim()||`wrangler secret list exited ${String(t.code)}`,names:[],ok:!1};const a=u(t.stdout);return a===void 0?{error:"could not parse `wrangler secret list --format json` output",names:[],ok:!1}:{names:a,ok:!0}};export{w as R};
1
+ import{execFile as c}from"node:child_process";import{resolveDeployDriver as i,resolveProjectTarget as l}from"@lunora/config";import{M as m,P as d}from"./detect-package-manager-C4aS7HE4.mjs";const p=r=>r?typeof r.code=="number"?r.code:1:0,f=(r,o,e)=>new Promise(n=>{c(r,[...o],{cwd:e},(t,a,s)=>{n({code:p(t),stderr:s,stdout:a})})}),u=r=>{let o;try{o=JSON.parse(r)}catch{return}return Array.isArray(o)?[...o.map(e=>e!==null&&typeof e=="object"?e.name:void 0).filter(e=>typeof e=="string"&&e.length>0)].toSorted((e,n)=>e.localeCompare(n)):void 0},w=async r=>{const o=i(l(r.cwd)).toolchain?.secretList({environment:r.env,temporary:r.temporary});if(o===void 0)return{error:"deploy target has no command-line toolchain",names:[],ok:!1};const{args:e,command:n}=m(d(r.cwd),o.tool,o.args),t=await(r.runner??f)(n,e,r.cwd);if(t.code!==0)return{error:t.stderr.trim()||`wrangler secret list exited ${String(t.code)}`,names:[],ok:!1};const a=u(t.stdout);return a===void 0?{error:"could not parse `wrangler secret list --format json` output",names:[],ok:!1}:{names:a,ok:!0}};export{w as R};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/cli",
3
- "version": "1.0.0-alpha.129",
3
+ "version": "1.0.0-alpha.130",
4
4
  "description": "The Lunora CLI: init, dev, deploy, codegen, run, reset, and migrate 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.59",
55
+ "@lunora/advisor": "1.0.0-alpha.60",
56
56
  "@lunora/bindings": "1.0.0-alpha.15",
57
- "@lunora/codegen": "1.0.0-alpha.81",
58
- "@lunora/config": "1.0.0-alpha.106",
57
+ "@lunora/codegen": "1.0.0-alpha.82",
58
+ "@lunora/config": "1.0.0-alpha.107",
59
59
  "@lunora/container": "1.0.0-alpha.18",
60
- "@lunora/d1": "1.0.0-alpha.55",
60
+ "@lunora/d1": "1.0.0-alpha.56",
61
61
  "@lunora/errors": "1.0.0-alpha.10",
62
- "@lunora/mcp": "1.0.0-alpha.51",
63
- "@lunora/runtime": "1.0.0-alpha.48",
64
- "@lunora/seed": "1.0.0-alpha.55",
62
+ "@lunora/mcp": "1.0.0-alpha.52",
63
+ "@lunora/runtime": "1.0.0-alpha.49",
64
+ "@lunora/seed": "1.0.0-alpha.56",
65
65
  "@visulima/cerebro": "3.0.0",
66
66
  "@visulima/error": "6.0.0",
67
67
  "@visulima/fs": "5.0.5",
@@ -130,6 +130,40 @@ export default defineMigration({
130
130
  The transform must preserve row identity — the runner always keeps the original
131
131
  `_id` / `_creationTime`, so do not change them.
132
132
 
133
+ ### Reading another table
134
+
135
+ The transform's second argument is a **shard-scoped reader** (`ctx.db` with
136
+ `get` / `findFirst` / `findMany` / `count`), so the common backfill — read the
137
+ parent, copy a field down onto its children — is expressible. It may be `async`.
138
+
139
+ ```ts
140
+ up: async (doc, ctx) => {
141
+ const thread = await ctx.db.get(String(doc.threadId), "threads");
142
+
143
+ return thread ? { ...doc, userId: thread.userId } : undefined;
144
+ },
145
+ ```
146
+
147
+ It is a reader, not a writer: the runner accounts for exactly one rewrite per
148
+ row read, and a transform writing directly would make that count describe
149
+ something other than what happened. To touch a second table, run a second
150
+ migration over that table.
151
+
152
+ ### A shard key cannot be backfilled by a migration
153
+
154
+ If the field you are backfilling **is** the table's `.shardBy()` key, this is the
155
+ wrong tool, and no amount of reader access fixes it:
156
+
157
+ - a row whose shard key is unset does not belong to any shard, so a shard-scoped
158
+ query will never enumerate it; and
159
+ - writing the key would have to **move the row to a different Durable Object**,
160
+ which a per-shard runner has no way to do.
161
+
162
+ Re-keying is an export → transform → import (`lunora export`, rewrite the NDJSON,
163
+ `lunora import` — ids are preserved, so foreign keys survive), not a migration.
164
+ So the rule elsewhere in this skill that a data backfill is always an online
165
+ `defineMigration` has this one exception.
166
+
133
167
  ### Run it
134
168
 
135
169
  ```bash
@@ -1,12 +0,0 @@
1
- import{createWriteStream as J,createReadStream as I}from"node:fs";import{unlink as A,stat as h,readdir as D}from"node:fs/promises";import{join as P}from"node:path";import{LunoraError as T}from"@lunora/errors";import{l as E}from"./admin-token-DV5A9T5b.mjs";import{u as j}from"./admin-url-Ca-KI3d_.mjs";const _="/_lunora/admin/export",R="/_lunora/admin/import",q=500,L=t=>{if(t===void 0)return;const r=t.split(",").map(o=>o.trim()).filter(o=>o.length>0);return r.length>0?r:void 0},N=async(t,r)=>{t.write(r)||await new Promise(o=>{t.once("drain",o)})},U=async(t,r)=>{const o=t.getReader(),e=new TextDecoder;let i=0,s=0,n="",c=!1;try{for(;!c;){const f=await o.read();if(c=f.done,f.value===void 0)continue;i+=f.value.length,n+=e.decode(f.value,{stream:!0});let l=n.indexOf(`
2
- `);for(;l!==-1;){s+=1;const u=`${n.slice(0,l)}
3
- `;await N(r,u),n=n.slice(l+1),l=n.indexOf(`
4
- `)}}return n.length>0&&(s+=1,await N(r,`${n}
5
- `)),{bytes:i,rows:s}}finally{o.releaseLock()}},C=async(t,r)=>{if(r!==void 0){t.destroy();try{await A(r)}catch{}}},X=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=j(t.url,t.logger,t.cwd);if(r===void 0)return{bytes:0,code:1,rows:0};const{token:o}=E({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}${_}`,i=L(t.tables),s=t.fetchImpl??globalThis.fetch;if(typeof s!="function")throw new TypeError("no fetch implementation available — pass fetchImpl or run on Node >= 18");t.logger.info(`POST ${e} -> export${i?` (tables: ${i.join(",")})`:""}`);const n=await s(e,{body:JSON.stringify(i?{tables:i}:{}),headers:{authorization:`Bearer ${o}`,"content-type":"application/json"},method:"POST"});if(!n.ok){const p=await n.text();return t.logger.error(`export failed: HTTP ${String(n.status)}: ${p}`),{bytes:0,code:1,rows:0}}if(!n.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,f=c===void 0?process.stdout:J(c,{encoding:"utf8"});let l,u;try{({bytes:l,rows:u}=await U(n.body,f))}catch(p){throw await C(f,c),p}return c!==void 0&&(await new Promise((p,g)=>{f.end(y=>{y?g(y):p()})}),t.logger.success(`wrote ${String(u)} rows to ${c} (${String(l)} bytes)`)),{bytes:l,code:0,rows:u}},F=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=j(t.url,t.logger,t.cwd);if(r===void 0)return;const{token:o}=E({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 i=await h(t.file);if(!i.isFile()&&!i.isDirectory()){t.logger.error(`not a file or directory: ${t.file}`);return}}catch(i){const s=i instanceof Error?i.message:String(i);t.logger.error(`failed to stat ${t.file}: ${s}`);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}${R}`,token:o}},k="_storage",z=async t=>{if(!(await h(t).catch(()=>{}))?.isDirectory())return;const r=[];for(const o of await D(t,{withFileTypes:!0})){if(!o.isDirectory())continue;const e=P(t,o.name,"documents.jsonl");(await h(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*B(t,r){let o="";for await(const i of I(t,{encoding:"utf8"})){o+=typeof i=="string"?i:i.toString("utf8");let s=o.indexOf(`
6
- `);for(;s!==-1;){const n=o.slice(0,s).trim();o=o.slice(s+1),n.length>0&&(yield`${JSON.stringify({doc:JSON.parse(n),table:r})}
7
- `),s=o.indexOf(`
8
- `)}}const e=o.trim();e.length>0&&(yield`${JSON.stringify({doc:JSON.parse(e),table:r})}
9
- `)}async function*H(t,r){for(const{file:o,table:e}of t){if(e===k){r.warn(`skipping "${k}" — those rows describe stored files. Upload the exported blobs to R2 and re-point the keys.`);continue}yield*B(o,e)}}const M=async t=>{const r=await z(t.file),o=await h(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}},Y=async t=>{const r=await F(t);if(r===void 0)return{body:void 0,code:1,inserted:0};const{fetchImpl:o,requestUrl:e,token:i}=r,s=t.batchSize??q,n=await M(t);if(n.error)return{body:void 0,code:1,inserted:0};const{convexTables:c}=n;t.logger.info(c?`POST ${e} -> import Convex export ${t.file} (${String(c.length)} tables)`:`POST ${e} -> import ${t.file}`);const f=c?H(c,t.logger):I(t.file,{encoding:"utf8"}),l={},u=[];let p=0,g="",y=[],v=0;const $=async()=>{if(y.length===0)return;const w=y.join(`
10
- `);y=[];const d=await o(e,{body:w,headers:{authorization:`Bearer ${i}`,"content-type":"application/x-ndjson"},method:"POST"});if(!d.ok){const m=await d.text().catch(()=>"<no body>");throw new T("INTERNAL",`import batch failed (HTTP ${String(d.status)}): ${m}`)}const a=await d.json();if(a.inserted)for(const[m,b]of Object.entries(a.inserted))l[m]=(l[m]??0)+b;Array.isArray(a.errors)&&u.push(...a.errors),typeof a.conflicts=="number"&&(p+=a.conflicts)},S=w=>{const d=w.trim();if(d.length===0)return;if(v+=1,t.table===void 0){y.push(d);return}let a;try{a=JSON.parse(d)}catch(m){const b=m instanceof Error?m.message:String(m);throw new T("INTERNAL",`invalid JSON on line ${String(v)}: ${b}`,{cause:m})}y.push(JSON.stringify({doc:a,table:t.table}))};for await(const w of f){const d=typeof w=="string"?w:w.toString("utf8");g+=d;let a=g.indexOf(`
11
- `);for(;a!==-1;)S(g.slice(0,a)),g=g.slice(a+1),a=g.indexOf(`
12
- `),y.length>=s&&await $()}g.length>0&&S(g),await $();const x=Object.values(l).reduce((w,d)=>w+d,0),O={conflicts:p,errors:u,inserted:l};return t.logger.info(JSON.stringify(O,void 0,2)),t.logger.success(`imported ${String(x)} rows (${String(p)} conflicts, ${String(u.length)} errors)`),{body:O,code:u.length>0?1:0,inserted:x}};export{q as DEFAULT_IMPORT_BATCH_SIZE,X as runExportCommand,Y as runImportCommand};
@@ -1,3 +0,0 @@
1
- import{mkdirSync as O,readFileSync as b,lstatSync as R,writeFileSync as B}from"node:fs";import{join as c,dirname as h}from"node:path";import{fileURLToPath as A}from"node:url";import{resolveHint as D,isLunoraError as w,flattenHint as L,findSolutionByMessage as E}from"@lunora/errors";import{createCerebro as j}from"@visulima/cerebro";import C from"@visulima/cerebro/command/completion";import I from"@visulima/cerebro/command/version";import{p as l}from"./api-spec-BENwiyUa.mjs";import{g as s}from"./deploy-target-Dvr9vxpR.mjs";import{createLogger as k}from"./createLogger--C3x1FNE.mjs";import{VisulimaError as _,renderError as P}from"@visulima/error";import{homedir as T}from"node:os";const $={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}]},y="lunora.advisor.map.json",U={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 ${y})`,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 ${y})`,name:"out",type:String},{description:"Write the map artifact to disk (default true; use --no-write to skip)",name:"write",type:Boolean}]},M={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}]},W={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}]},J={description:"Codegen + validate + bundle the Worker to disk without deploying",examples:[["lunora build","Bundle to .lunora/build without deploying"],["lunora build --out-dir dist-worker","Bundle to a custom directory"]],group:"Deploy",loader:()=>import("../packem_chunks/handler4.mjs").then(e=>({default:e.execute})),name:"build",options:[{description:`Which API spec(s) to emit: ${l} (default openapi)`,name:"api-spec",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Directory to write the bundled Worker to (default .lunora/build)",name:"out-dir",type:String},s]},K={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: ${l} (default openapi)`,name:"api-spec",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Don't fail on ERROR-level advisories (the gate defaults to on in CI, off locally)",name:"no-strict-advisories",type:Boolean},s]},q={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}]},F={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: ${l} (default openapi)`,name:"api-spec",type:String},{description:"Validate, bundle, and run pre-deploy gates without publishing (wrangler deploy --dry-run)",name:"dry-run",type:Boolean},{description:"Cloudflare environment name",name:"env",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"After a successful deploy, run pending data migrations against the live worker",name:"migrate",type:Boolean},{description:"Skip codegen + the schema-drift gate (assumes `lunora build`/`prepare` already ran in this CI run). Wrangler still bundles the worker.",name:"prebuilt",type:Boolean},{description:"Admin bearer token for --migrate (falls back to LUNORA_ADMIN_TOKEN)",name:"migrate-token",type:String},{description:"Worker URL for --migrate (REQUIRED with --migrate; the deploy target URL is not captured automatically)",name:"migrate-url",type:String},{description:"Confirm running the production data migration triggered by --migrate (required with --migrate)",name:"migrate-yes",type:Boolean},{description:"Upload a preview version (wrangler versions upload) instead of going live — prints a preview URL; doesn't shift production traffic",name:"preview",type:Boolean},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}]},H={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}]},V={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: ${l} (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}]},z={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"},G={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:[]},Y={argument:{description:"list | get <KEY> | set <KEY> <VALUE> | unset <KEY> | generate [KEY] | push | diff | doctor",name:"subcommand",type:String},description:"Manage .dev.vars and sync secrets via wrangler (list | get | set | unset | generate | push | diff | doctor)",examples:[["lunora env list","List .dev.vars keys"],["lunora env set API_KEY secret","Set a local variable"],["lunora env generate","Generate strong values for the project's secrets (print KEY=value)"],["lunora env generate AUTH_SECRET --set","Generate one secret and write it to .dev.vars"],["lunora env push --yes","Upload secrets to Cloudflare"],["lunora env diff","Compare local .dev.vars keys against Cloudflare"]],group:"Data",loader:()=>import("../packem_chunks/handler9.mjs").then(e=>({default:e.execute})),name:"env",options:[{description:"Target production for `push` (passes --env production to wrangler)",name:"prod",type:Boolean},{description:"For `generate` — write the generated secrets into .dev.vars instead of printing them",name:"set",type:Boolean},{description:"Push secrets to a temporary-account deployment when unauthenticated (wrangler secret put --temporary). Errors if you're already authenticated.",name:"temporary",type:Boolean},{description:"Required for `push` — confirms uploading secrets to Cloudflare",name:"yes",type:Boolean}]},Q={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}]},X={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}]},Z={description:"Print resolved project config: @lunora/* versions, wrangler summary, schema overview",examples:[["lunora info","Print resolved project config"],["lunora info --json","Emit a JSON snapshot"]],group:"Project",loader:()=>import("../packem_chunks/handler12.mjs").then(e=>({default:e.execute})),name:"info",options:[{description:"Emit a JSON snapshot instead of human text",name:"json",type:Boolean}]},ee={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}]},te={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}]},re={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/handler23.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}]},oe={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}]},ne={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}]},ae={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/handler24.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}]},ie={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}]},se={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: ${l} (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}]},le={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}]},pe={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}]},de={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}]},ce={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}]},ue={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}]},me={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: ${l} (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]},ge={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}]},he={filterStacktrace:()=>!1,hideErrorCodeView:!0},ye=(e,t={})=>{const r=e instanceof Error?e.message:String(e),o=D(w(e)?{code:e.code,hint:e.hint,message:r}:r),n=new _({hint:o===void 0?void 0:L(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="",P(n,he)},fe=(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,p=e[o-1]===t[a-1]?0:1;r[a]=Math.min((r[a-1]??0)+1,i+1,n+p),n=i}}return r[t.length]??0},ve=(e,t)=>{let r,o=Number.POSITIVE_INFINITY;for(const a of t){const i=fe(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},be=e=>`https://registry.npmjs.org/@lunora/cli/${e}`,we=1440*60*1e3,ke=1500,Se="0.0.0",xe=/^v/u,Ne=new Set(["alpha","beta","next"]),u=e=>{const t=e.trim().replace(xe,""),r=t.indexOf("-");return r===-1?{core:t,prerelease:""}:{core:t.slice(0,r),prerelease:t.slice(r+1)}},f=e=>{const[t,r,o]=u(e).core.split(".").map(n=>{const a=Number.parseInt(n,10);return Number.isFinite(a)?a:0});return[t??0,r??0,o??0]},Oe=(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},Re=(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 Oe(a,i)}return 0},Be=(e,t)=>{const r=f(e),o=f(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 Re(u(e).prerelease,u(t).prerelease)},Ae=e=>{const t=u(e).prerelease.split(".")[0]??"";return Ne.has(t)?t:"latest"},De=(e,t)=>Be(t,e)>0,Le=(e,t,r)=>t-e<r,Ee=(e,t,r="latest")=>`Update available for @lunora/cli: ${e} → ${t} — run \`pnpm add -D @lunora/cli@${r}\``,S=e=>c(e,"lunora-cli-update.json"),je=e=>{const t=e.XDG_CACHE_HOME&&e.XDG_CACHE_HOME.length>0?e.XDG_CACHE_HOME:c(T(),".cache"),r=c(t,"lunora");try{O(r,{mode:448,recursive:!0})}catch{}return r},Ce=e=>{try{const t=JSON.parse(b(S(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{}},v=(e,t)=>{try{const r=S(e);try{if(R(r).isSymbolicLink())return}catch{}B(r,`${JSON.stringify(t)}
3
- `,"utf8")}catch{}},Ie=async(e,t)=>{try{const r=await e(be(t),{signal:AbortSignal.timeout(ke)});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}},_e=(e,t,r)=>e===Se||!r||t.CI!==void 0||t.LUNORA_NO_UPDATE_NOTIFIER!==void 0,Pe=async e=>{const t=e.env??process.env,r=e.isTTY??process.stdout.isTTY;if(_e(e.current,t,r))return;const o=e.cacheDir??je(t),n=(e.now??Date.now)(),a=e.ttlMs??we,i=Ae(e.current),p=Ce(o),N=p?.tag??"latest",m=p!==void 0&&N===i?p:void 0;let d=m?.latest;if(m===void 0||!Le(m.checkedAt,n,a)){const g=await Ie(e.fetchImpl??globalThis.fetch,i);g===void 0?v(o,{checkedAt:n,latest:e.current,tag:i}):(d=g,v(o,{checkedAt:n,latest:g,tag:i}))}d!==void 0&&De(e.current,d)&&e.logger.warn(Ee(e.current,d,i))},Te=["init","add","dev","codegen","build","deploy","containers","prepare","link","deployments","logs","run","insights","reset","migrate","export","import","seed","backup","verify","info","doctor","env","analyze","view","docs","registry","rules","mcp"],$e=8,Ue=()=>{try{let e=h(A(import.meta.url));for(let t=0;t<$e;t+=1){try{const o=JSON.parse(b(c(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=h(e);if(r===e)break;e=r}}catch{}return"0.0.0"},x=Ue(),Me=[ee,$,V,K,U,J,F,q,se,oe,H,ne,ce,te,pe,ie,Q,X,ue,re,W,me,Z,G,Y,M,ge,z,le,de,ae],We=e=>{const t={value:0},r=j("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:x});for(const o of Me)r.addCommand(o);return r.addCommand(I),r.addCommand(C),{cli:r,exitCode:t}},Je=/Command "(?<name>[^"]+)" not found/u,Ke=e=>{const t=k(),r=e instanceof Error?e.message:String(e),o=Je.exec(r);if(!o?.groups){w(e)||E(r)!==void 0?t.error(ye(e)):t.error(r);return}const n=o.groups.name??"",a=ve(n,Te);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.")},rt=async(e={})=>{const{cli:t,exitCode:r}=We(e);try{await t.run({shouldExitProcess:!1})}catch(o){return Ke(o),1}return await Pe({current:x,logger:k()}),r.value};export{rt as e,y as o,Te as s,x as t};
@@ -1 +0,0 @@
1
- import{existsSync as i,readFileSync as u,writeFileSync as d}from"node:fs";import{evaluateSchemaDrift as g,parseSchemaSnapshot as b,SchemaSnapshotParseError as p,serializeSchemaSnapshot as m}from"@lunora/codegen";const f=e=>{if(!i(e))return{status:"absent"};let s;try{s=u(e,"utf8")}catch{return{status:"corrupt"}}try{const a=b(s);return a===void 0?{status:"corrupt"}:{snapshot:a,status:"ok"}}catch(a){if(a instanceof p)return{status:"corrupt"};throw a}},S=(e,s)=>{d(e,m(s),"utf8")},k=e=>{const s=`schema-drift gate: the committed baseline ${e.snapshotPath} is unreadable or malformed, so schema drift cannot be checked. Fix it (e.g. resolve a merge conflict in lunora/.lunora-schema.json), or pass --update-schema-baseline to regenerate it from the current schema.`;return e.updateBaseline&&!e.readOnly?(e.logger.warn(`schema baseline was unreadable; regenerating from the current schema on success (--update-schema-baseline): ${e.snapshotPath}`),{blocked:!1,changes:[],reason:s,rebless:e.rebless}):(e.readOnly||e.logger.error(s),{blocked:!0,changes:[],reason:s})},y=(e,s)=>(s.readOnly||s.logger.error(e.reason),s.updateBaseline&&!s.readOnly?(s.logger.warn(`schema baseline will be re-blessed despite breaking drift on success (--update-schema-baseline): ${s.snapshotPath}`),{blocked:!1,changes:e.changes,reason:e.reason,rebless:s.rebless}):{blocked:!0,changes:e.changes,reason:e.reason}),P=e=>{const{allowDrift:s,codegen:a,logger:l,readOnly:t=!1,updateBaseline:h=!1}=e,n=a.schemaSnapshotPath,o=f(n),c={logger:l,readOnly:t,rebless:()=>{S(n,a.schemaSnapshot)},snapshotPath:n,updateBaseline:h};if(o.status==="corrupt")return k(c);const r=g({allowDrift:s,baseline:o.status==="ok"?o.snapshot:void 0,current:a.schemaSnapshot});return r.blocked?y(r,c):r.changes.length>0?(t||l.info(r.reason),{blocked:!1,changes:r.changes,reason:r.reason,rebless:t?void 0:c.rebless}):{blocked:!1,changes:r.changes,reason:r.reason}};export{P as k};