@lunora/cli 1.0.0-alpha.331 → 1.0.0-alpha.333

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.mjs CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import{r as e}from"./packem_shared/cli-BQ3AyV_K.mjs";try{const r=await e();process.exit(r)}catch(r){process.stderr.write(`${r instanceof Error?r.message:String(r)}
2
+ import{r as e}from"./packem_shared/cli-CIDgoZP8.mjs";try{const r=await e();process.exit(r)}catch(r){process.stderr.write(`${r instanceof Error?r.message:String(r)}
3
3
  `),process.exit(1)}
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { CodegenOptions, Finding, FieldSnapshot, SchemaIR } from '@lunora/codegen';
2
- import { ensureDevVariables, ensureDevVarsExample, fillDevSecrets, LintTool, LintIgnoreOutcome, PackageManager, PackageManagerProbe } from '@lunora/config';
2
+ import { ensureDevVariables, ensureDevVarsExample, fillDevSecrets, startCelldDevSession, LintTool, LintIgnoreOutcome, PackageManager, PackageManagerProbe } from '@lunora/config';
3
3
  import { materializeRemoteWranglerConfig } from '@lunora/config/cloudflare';
4
4
  export { REQUIRED_COMPATIBILITY_DATE, REQUIRED_FLAG, type WranglerProjectValidationOptions as WranglerValidationOptions, type WranglerValidationReport, type WranglerProjectValidationResult as WranglerValidationResult, validateWranglerProject as validateWrangler, validateWranglerConfig } from '@lunora/config/cloudflare';
5
5
  /** Every command name the CLI registers (drives the `CommandName` type + tests). */
@@ -661,6 +661,8 @@ interface DeployCommandOptions {
661
661
  /** Remote-secret lister for the missing-secret offer; injected in tests. Defaults to `wrangler secret list`. */
662
662
  secretLister?: (inputs: ListRemoteSecretsInputs) => Promise<ListRemoteSecretsResult>;
663
663
  skipCodegen?: boolean;
664
+ /** Deploy only the app, leaving the `lunora.config` services it binds as they are (`--skip-services`). */
665
+ skipServices?: boolean;
664
666
  spawner?: Spawner;
665
667
  /**
666
668
  * Fail the deploy when codegen reports an ERROR-level advisory. Same
@@ -949,6 +951,8 @@ interface DevCommandOptions {
949
951
  probeReady?: ReadinessProbe;
950
952
  /** Proxy D1/KV/R2 bindings to the deployed worker during dev (`LUNORA_REMOTE=1` / `--remote`); DO shards stay local. */
951
953
  remote?: boolean;
954
+ /** Starts the celld dev session for the celld target; injected in tests. */
955
+ startCelldSession?: typeof startCelldDevSession;
952
956
  /** Injection seam for tests — defaults to the real codegen watcher. */
953
957
  startCodegen?: typeof startCodegenWatch;
954
958
  /** Injection seam for tests — defaults to the real studio server. */
@@ -988,6 +992,12 @@ interface DevRemotePlan {
988
992
  reason?: string;
989
993
  }
990
994
  interface DevCommandPlan {
995
+ /**
996
+ * `true` when the worker is a celld dev session (a target running its own
997
+ * dev server) rather than {@link DevCommandPlan.wrangler}'s process: services
998
+ * registered first, a service edit re-registering it and restarting the app.
999
+ */
1000
+ celldSession?: true;
991
1001
  /** Which stack the child runs — see {@link DevFlavor}. */
992
1002
  flavor: DevFlavor;
993
1003
  /**
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { CodegenOptions, Finding, FieldSnapshot, SchemaIR } from '@lunora/codegen';
2
- import { ensureDevVariables, ensureDevVarsExample, fillDevSecrets, LintTool, LintIgnoreOutcome, PackageManager, PackageManagerProbe } from '@lunora/config';
2
+ import { ensureDevVariables, ensureDevVarsExample, fillDevSecrets, startCelldDevSession, LintTool, LintIgnoreOutcome, PackageManager, PackageManagerProbe } from '@lunora/config';
3
3
  import { materializeRemoteWranglerConfig } from '@lunora/config/cloudflare';
4
4
  export { REQUIRED_COMPATIBILITY_DATE, REQUIRED_FLAG, type WranglerProjectValidationOptions as WranglerValidationOptions, type WranglerValidationReport, type WranglerProjectValidationResult as WranglerValidationResult, validateWranglerProject as validateWrangler, validateWranglerConfig } from '@lunora/config/cloudflare';
5
5
  /** Every command name the CLI registers (drives the `CommandName` type + tests). */
@@ -661,6 +661,8 @@ interface DeployCommandOptions {
661
661
  /** Remote-secret lister for the missing-secret offer; injected in tests. Defaults to `wrangler secret list`. */
662
662
  secretLister?: (inputs: ListRemoteSecretsInputs) => Promise<ListRemoteSecretsResult>;
663
663
  skipCodegen?: boolean;
664
+ /** Deploy only the app, leaving the `lunora.config` services it binds as they are (`--skip-services`). */
665
+ skipServices?: boolean;
664
666
  spawner?: Spawner;
665
667
  /**
666
668
  * Fail the deploy when codegen reports an ERROR-level advisory. Same
@@ -949,6 +951,8 @@ interface DevCommandOptions {
949
951
  probeReady?: ReadinessProbe;
950
952
  /** Proxy D1/KV/R2 bindings to the deployed worker during dev (`LUNORA_REMOTE=1` / `--remote`); DO shards stay local. */
951
953
  remote?: boolean;
954
+ /** Starts the celld dev session for the celld target; injected in tests. */
955
+ startCelldSession?: typeof startCelldDevSession;
952
956
  /** Injection seam for tests — defaults to the real codegen watcher. */
953
957
  startCodegen?: typeof startCodegenWatch;
954
958
  /** Injection seam for tests — defaults to the real studio server. */
@@ -988,6 +992,12 @@ interface DevRemotePlan {
988
992
  reason?: string;
989
993
  }
990
994
  interface DevCommandPlan {
995
+ /**
996
+ * `true` when the worker is a celld dev session (a target running its own
997
+ * dev server) rather than {@link DevCommandPlan.wrangler}'s process: services
998
+ * registered first, a service edit re-registering it and restarting the app.
999
+ */
1000
+ celldSession?: true;
991
1001
  /** Which stack the child runs — see {@link DevFlavor}. */
992
1002
  flavor: DevFlavor;
993
1003
  /**
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{C as o,V as a,r as n}from"./packem_shared/cli-BQ3AyV_K.mjs";import{runCodegenCommand as m}from"./packem_chunks/runCodegenCommand.mjs";import{runDeployCommand as p}from"./packem_chunks/runDeployCommand.mjs";import{runDevCommand as f}from"./packem_chunks/runDevCommand.mjs";import{p as i}from"./packem_shared/plan-CtBB0rrT.mjs";import{runInitCommand as l}from"./packem_chunks/runInitCommand.mjs";import{runMigrateGenerateCommand as I}from"./packem_shared/runMigrateGenerateCommand-Ii_WMZEA.mjs";import{runResetCommand as g}from"./packem_chunks/runResetCommand.mjs";import{runRpcCommand as T}from"./packem_chunks/runRpcCommand.mjs";import{EXIT_CODE as S,exitCodeForCode as A,exitCodeForError as c,exitCodeForStatus as M}from"./packem_shared/EXIT_CODE-D_XCixv8.mjs";import{insertSchemaExtension as v}from"./packem_shared/insertSchemaExtension-DuiV6cba.mjs";import{createLogger as b,pail as O}from"./packem_shared/createLogger-Cl18I8AX.mjs";import{diffSnapshots as y,renderAddColumn as L,renderCreateIndex as w,renderCreateTable as B,renderDropIndex as P,renderDropTable as U,renderMigrationFile as V,validatorKindToSqlType as W}from"./packem_shared/diffSnapshots-WWwx-KvZ.mjs";import{default as N}from"./packem_shared/schemaIrToSnapshot-BjK-0IRo.mjs";import{createRecordingSpawner as j,defaultSpawner as q}from"./packem_shared/createRecordingSpawner-sS7LEN7x.mjs";import{default as K}from"./packem_shared/parseManifest-CwPTKdtS.mjs";import{D as Y,r as Z}from"./packem_shared/import-BRM1hs7j.mjs";import{REQUIRED_COMPATIBILITY_DATE as z,REQUIRED_FLAG as J,validateWranglerProject as $,validateWranglerConfig as rr}from"@lunora/config/cloudflare";import{b as or}from"./packem_shared/catalog-CahzmDLV.mjs";import{r as nr,a as tr,b as mr}from"./packem_shared/commands-Cg06JNO2.mjs";import{runExportCommand as pr}from"./packem_shared/runExportCommand-slAq5BCF.mjs";export{o as COMMANDS,Y as DEFAULT_IMPORT_BATCH_SIZE,S as EXIT_CODE,z as REQUIRED_COMPATIBILITY_DATE,J as REQUIRED_FLAG,a as VERSION,or as buildRegistryIndex,b as createLogger,j as createRecordingSpawner,q as defaultSpawner,y as diffSnapshots,A as exitCodeForCode,c as exitCodeForError,M as exitCodeForStatus,v as insertSchemaExtension,O as pail,K as parseManifest,i as planDevCommand,L as renderAddColumn,w as renderCreateIndex,B as renderCreateTable,P as renderDropIndex,U as renderDropTable,V as renderMigrationFile,nr as runAddCommand,tr as runBuildIndexCommand,n as runCli,m as runCodegenCommand,p as runDeployCommand,f as runDevCommand,pr as runExportCommand,Z as runImportCommand,l as runInitCommand,I as runMigrateGenerateCommand,mr as runRegistryViewCommand,g as runResetCommand,T as runRpcCommand,N as schemaIrToSnapshot,$ as validateWrangler,rr as validateWranglerConfig,W as validatorKindToSqlType};
1
+ import{C as o,V as a,r as n}from"./packem_shared/cli-CIDgoZP8.mjs";import{runCodegenCommand as m}from"./packem_chunks/runCodegenCommand.mjs";import{runDeployCommand as p}from"./packem_chunks/runDeployCommand.mjs";import{runDevCommand as f}from"./packem_chunks/runDevCommand.mjs";import{p as i}from"./packem_shared/plan-BzTGWr2e.mjs";import{runInitCommand as l}from"./packem_chunks/runInitCommand.mjs";import{runMigrateGenerateCommand as I}from"./packem_shared/runMigrateGenerateCommand-Ii_WMZEA.mjs";import{runResetCommand as g}from"./packem_chunks/runResetCommand.mjs";import{runRpcCommand as T}from"./packem_chunks/runRpcCommand.mjs";import{EXIT_CODE as S,exitCodeForCode as A,exitCodeForError as c,exitCodeForStatus as M}from"./packem_shared/EXIT_CODE-D_XCixv8.mjs";import{insertSchemaExtension as v}from"./packem_shared/insertSchemaExtension-DuiV6cba.mjs";import{createLogger as b,pail as O}from"./packem_shared/createLogger-Cl18I8AX.mjs";import{diffSnapshots as y,renderAddColumn as L,renderCreateIndex as w,renderCreateTable as B,renderDropIndex as P,renderDropTable as U,renderMigrationFile as V,validatorKindToSqlType as W}from"./packem_shared/diffSnapshots-WWwx-KvZ.mjs";import{default as N}from"./packem_shared/schemaIrToSnapshot-BjK-0IRo.mjs";import{createRecordingSpawner as j,defaultSpawner as q}from"./packem_shared/createRecordingSpawner-sS7LEN7x.mjs";import{default as K}from"./packem_shared/parseManifest-CwPTKdtS.mjs";import{D as Y,r as Z}from"./packem_shared/import-BRM1hs7j.mjs";import{REQUIRED_COMPATIBILITY_DATE as z,REQUIRED_FLAG as J,validateWranglerProject as $,validateWranglerConfig as rr}from"@lunora/config/cloudflare";import{b as or}from"./packem_shared/catalog-CahzmDLV.mjs";import{r as nr,a as tr,b as mr}from"./packem_shared/commands-Cg06JNO2.mjs";import{runExportCommand as pr}from"./packem_shared/runExportCommand-slAq5BCF.mjs";export{o as COMMANDS,Y as DEFAULT_IMPORT_BATCH_SIZE,S as EXIT_CODE,z as REQUIRED_COMPATIBILITY_DATE,J as REQUIRED_FLAG,a as VERSION,or as buildRegistryIndex,b as createLogger,j as createRecordingSpawner,q as defaultSpawner,y as diffSnapshots,A as exitCodeForCode,c as exitCodeForError,M as exitCodeForStatus,v as insertSchemaExtension,O as pail,K as parseManifest,i as planDevCommand,L as renderAddColumn,w as renderCreateIndex,B as renderCreateTable,P as renderDropIndex,U as renderDropTable,V as renderMigrationFile,nr as runAddCommand,tr as runBuildIndexCommand,n as runCli,m as runCodegenCommand,p as runDeployCommand,f as runDevCommand,pr as runExportCommand,Z as runImportCommand,l as runInitCommand,I as runMigrateGenerateCommand,mr as runRegistryViewCommand,g as runResetCommand,T as runRpcCommand,N as schemaIrToSnapshot,$ as validateWrangler,rr as validateWranglerConfig,W as validatorKindToSqlType};
@@ -1,4 +1,4 @@
1
- import{writeFileSync as h,existsSync as S,readFileSync as p}from"node:fs";import{isAbsolute as v,join as w}from"node:path";import{byCodepoint as b,scoreAdvisor as y,parseAdvisorMap as x,compareToBaseline as j}from"@lunora/advisor";import{runCodegen as A}from"@lunora/codegen";import{d as M}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as D}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{D as u}from"../packem_shared/cli-BQ3AyV_K.mjs";const l={clean:"·",exempt:"–",failing:"✗",warned:"!"},d=(e,r)=>e.length>=r?e:e+" ".repeat(r-e.length),E=e=>`${e.id} (${e.visibility} ${e.kind})`,f=e=>{let r=0;for(const n of e)r=Math.max(r,n.id.length);return r},g=(e,r)=>` ${d(String(e.score),3)} ${l[e.coverage]} ${d(e.id,r)} ${e.visibility} ${e.kind}`,R=e=>{if(!e.comparable)return[` baseline not comparable (${e.reason}) — regenerate it; this run cannot verify anything`];if(!e.regressed)return[` no regression against baseline (score ${e.scoreDelta>=0?"+":""}${String(e.scoreDelta)})`];const r=[` REGRESSED against baseline (score ${e.scoreDelta>=0?"+":""}${String(e.scoreDelta)})`];for(const n of e.dropped)r.push(` ${n.id}: ${String(n.before)} → ${String(n.after)}`);for(const n of e.newFailing)r.push(` ${n}: now failing`);for(const n of e.worsened)r.push(` ${n}: more findings than the baseline`);return e.projectRegressed&&r.push(" project: new schema/config rules fired"),r},F=(e,r)=>{const n=e.procedures.filter(i=>i.coverage!=="clean"&&i.coverage!=="exempt"),t=f(n),o=[`advisor health ${String(e.score)}/100 — ${e.grade}`,` ${String(e.summary.clean)} clean · ${String(e.summary.warned)} warned · ${String(e.summary.failing)} failing · ${String(e.summary.exempt)} exempt (${String(e.summary.procedures)} procedures, ${String(e.summary.rulesFired)} rules fired)`];return e.project.checks.length>0&&o.push("",` project ${String(e.project.score)}/100 — ${e.project.checks.map(i=>i.name).join(", ")}`),n.length>0&&o.push("",...n.map(i=>g(i,t)),""," run with --all for every procedure, or --entry <file#export> for one"),r!==void 0&&o.push("",...R(r)),o.join(`
1
+ import{writeFileSync as h,existsSync as S,readFileSync as p}from"node:fs";import{isAbsolute as v,join as w}from"node:path";import{byCodepoint as b,scoreAdvisor as y,parseAdvisorMap as x,compareToBaseline as j}from"@lunora/advisor";import{runCodegen as A}from"@lunora/codegen";import{d as M}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as D}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{D as u}from"../packem_shared/cli-CIDgoZP8.mjs";const l={clean:"·",exempt:"–",failing:"✗",warned:"!"},d=(e,r)=>e.length>=r?e:e+" ".repeat(r-e.length),E=e=>`${e.id} (${e.visibility} ${e.kind})`,f=e=>{let r=0;for(const n of e)r=Math.max(r,n.id.length);return r},g=(e,r)=>` ${d(String(e.score),3)} ${l[e.coverage]} ${d(e.id,r)} ${e.visibility} ${e.kind}`,R=e=>{if(!e.comparable)return[` baseline not comparable (${e.reason}) — regenerate it; this run cannot verify anything`];if(!e.regressed)return[` no regression against baseline (score ${e.scoreDelta>=0?"+":""}${String(e.scoreDelta)})`];const r=[` REGRESSED against baseline (score ${e.scoreDelta>=0?"+":""}${String(e.scoreDelta)})`];for(const n of e.dropped)r.push(` ${n.id}: ${String(n.before)} → ${String(n.after)}`);for(const n of e.newFailing)r.push(` ${n}: now failing`);for(const n of e.worsened)r.push(` ${n}: more findings than the baseline`);return e.projectRegressed&&r.push(" project: new schema/config rules fired"),r},F=(e,r)=>{const n=e.procedures.filter(i=>i.coverage!=="clean"&&i.coverage!=="exempt"),t=f(n),o=[`advisor health ${String(e.score)}/100 — ${e.grade}`,` ${String(e.summary.clean)} clean · ${String(e.summary.warned)} warned · ${String(e.summary.failing)} failing · ${String(e.summary.exempt)} exempt (${String(e.summary.procedures)} procedures, ${String(e.summary.rulesFired)} rules fired)`];return e.project.checks.length>0&&o.push("",` project ${String(e.project.score)}/100 — ${e.project.checks.map(i=>i.name).join(", ")}`),n.length>0&&o.push("",...n.map(i=>g(i,t)),""," run with --all for every procedure, or --entry <file#export> for one"),r!==void 0&&o.push("",...R(r)),o.join(`
2
2
  `)},k=e=>e.coverage==="exempt"?[` exempt: ${e.exemptReason===void 0||e.exemptReason===""?"no reason given":e.exemptReason}`]:e.checks.map(r=>{const n=r.occurrences>1?`, ×${String(r.occurrences)}`:"";return` ${r.name} (−${String(r.weight)}${n})`}),T=e=>{const r=new Map;for(const n of e){const t=r.get(n.file);t===void 0?r.set(n.file,[n]):t.push(n)}return[...r].toSorted(([n],[t])=>b(n,t))},B=e=>{const r=f(e.procedures),n=[`advisor health ${String(e.score)}/100 — ${e.grade}`,"",` legend: ${l.clean} clean ${l.warned} warned ${l.failing} failing ${l.exempt} exempt`];for(const[t,o]of T(e.procedures)){n.push("",` ${t}`);for(const i of o)n.push(g(i,r),...k(i))}return n.join(`
3
3
  `)},C=(e,r)=>{const n=e.procedures.find(o=>o.id===r);if(n===void 0){const o=e.procedures.slice(0,10).map(i=>` ${i.id}`);return[`no procedure ${r} in the map. Known ids:`,...o,e.procedures.length>10?" …":""].filter(Boolean).join(`
4
4
  `)}const t=[`${E(n)} — ${String(n.score)}/100, ${n.coverage}`,` weight in the global mean: ${String(n.weight)}`];if(n.checks.length===0)return t.push(""," no rule fired"),t.join(`
@@ -1 +1,3 @@
1
- import{existsSync as f,readFileSync as g,realpathSync as w}from"node:fs";import{join as u}from"node:path";import{DEV_VARS_FILE as m,parseDevVariableEntries as x,isPlaceholderValue as _,discoverSchemaInfo as A,inferLunoraBindings as R}from"@lunora/config";import{findWranglerFile as $,readWranglerJsonc as S,validateWranglerProject as I,UNEXPORTED_CLASS_MARKER as b,collectExportGaps as L}from"@lunora/config/cloudflare";import{i as N,m as j,c as O}from"../packem_shared/secret-key-DsMeUoEg.mjs";import{r as E,d as D}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{d as P}from"../packem_shared/command-CAXl2A1S.mjs";import{i as V}from"../packem_shared/path-containment-CgxYZggb.mjs";import{b as y,c as k,a as h}from"../packem_shared/variables-acxcvVQa.mjs";const C=(t,e)=>{const n=new Set,r=o=>{for(const[c,s]of Object.entries(o??{}))typeof s=="string"&&s.trim().length>0&&n.add(c)};r(t.vars);for(const o of Object.values(t.env??{}))r(o.vars);const a=u(e,m);if(f(a))try{r(Object.fromEntries(x(g(a,"utf8")).map(o=>[o.key,o.value])))}catch{}return n},U=(t,e,n,r)=>{if(t===void 0||!n)return;const a=C(t,e),o=a.has(y),c=t.ai?.binding;!o&&(typeof c!="string"||c.length===0)&&r.push({code:"ai-binding-missing",fix:`Run \`lunora dev\` (it adds the binding), add \`"ai": { "binding": "AI" }\` to wrangler.jsonc, or set ${y} to an OpenAI-compatible proxy.`,level:"warn",message:"the project uses ctx.ai (@lunora/ai / env.AI) but wrangler.jsonc declares no `ai` binding — model calls will fail at runtime."}),a.has(k)&&r.push({code:"ai-gateway-token-unused",fix:"Make the gateway unauthenticated for ctx.ai, or remove the token. A bring-your-own AI SDK provider built with `resolveAiGateway` does send it.",level:"warn",message:`${k} is set, but ctx.ai's Workers AI binding cannot send a gateway token — it is ignored on that path.`}),!o&&!a.has(h)&&r.push({code:"ai-gateway-default",fix:`Run \`lunora ai gateway\` to create a gateway for this app and write ${h} into wrangler vars.`,level:"info",message:`no ${h} in vars or ${m} — \`<provider>/<model>\` slugs route through the account's \`default\` AI Gateway.`})},M=t=>{const e=t.trim();if(e==="")return!0;const n=e.toLowerCase();return n.includes("replace")||n.startsWith("<")&&n.endsWith(">")},T=t=>{const e=$(t);if(e===void 0)return{parsed:void 0,path:void 0};const{parsed:n}=S(e);return{parsed:n,path:e}},W=(t,e,n,r)=>{if(n===void 0){r.push({code:"wrangler-missing",fix:"Run `lunora init` (or `lunora dev`) to scaffold and reconcile wrangler.jsonc.",level:"fail",message:"wrangler.jsonc not found."});return}if(e===void 0){r.push({code:"wrangler-unparseable",fix:`Check ${n} is valid JSONC.`,level:"fail",message:`Could not parse ${n}.`});return}const{report:a}=I({projectRoot:t});for(const s of a.errors.filter(l=>l.includes(b)))r.push({code:"wrangler-class-unexported",level:"fail",message:s});for(const s of a.warnings.filter(l=>l.includes("LUNORA_ORIGIN_URL")))r.push({code:"scheduler-origin-missing",fix:"Set LUNORA_ORIGIN_URL in wrangler vars to the worker's public URL (or `wrangler secret put LUNORA_ORIGIN_URL`).",level:"warn",message:s});const o=s=>s.includes(b)||s.includes("SHARD");for(const s of a.errors.filter(l=>!o(l)))r.push({code:"wrangler-invalid",fix:"Fix the reported wrangler.jsonc problem; `lunora verify` reports the same set.",level:"fail",message:s});for(const s of a.warnings.filter(l=>!l.includes("LUNORA_ORIGIN_URL")))r.push({code:"wrangler-advisory",level:"warn",message:s});const c=a.errors.find(s=>s.includes("SHARD"));c===void 0?r.push({code:"wrangler-shard-binding-ok",level:"pass",message:"wrangler.jsonc present with a SHARD durable-object binding."}):r.push({code:"wrangler-shard-binding-missing",fix:"Run `lunora dev` to auto-reconcile, or add the binding manually.",level:"fail",message:c})},G=(t,e)=>{f(u(t,"lunora.json"))&&e.push({code:"stale-lunora-json",fix:'Move `target` / `remote` into `lunora.config.ts` (`export default { target: "…" }`), then delete lunora.json.',level:"warn",message:"lunora.json is present but no longer read — lunora.config.* replaced it, so any `target` or `remote` in it is being ignored."})},F=(t,e)=>{t===void 0||t.limits?.cpu_ms!==void 0||e.push({code:"cpu-limit-missing",fix:'Add `"limits": { "cpu_ms": 30000 }` to wrangler.jsonc, tuned to your slowest legitimate handler.',level:"info",message:"no limits.cpu_ms is set — a runaway handler can burn CPU up to the platform default before anything stops it."})},K=(t,e)=>{const n=(t?.r2_buckets??[]).map(r=>r?.bucket_name).filter(r=>typeof r=="string"&&r.length>0);n.length!==0&&e.push({code:"r2-lifecycle-unset",fix:"wrangler r2 bucket lifecycle list <bucket> — add an abort-incomplete-multipart rule if none exists.",level:"info",message:`R2 bucket(s) ${n.join(", ")}: verify a lifecycle rule aborts incomplete multipart uploads — orphaned parts are billed but invisible in a listing.`})},z=(t,e)=>{const{error:n,info:r}=A(t,"lunora");if(n!==void 0){e.push({code:"schema-unreadable",fix:"Fix the parse error, then re-run `lunora doctor`. `lunora codegen` reports the same failure with the offending source.",level:"fail",message:`lunora/schema.ts could not be parsed, so every schema-derived check was skipped: ${n}`});return}for(const a of r?.vectorMetadata??[]){const o=j(a.kind);if(o===void 0){e.push({code:"vector-metadata-unfilterable",fix:"Filter on a string, number or boolean column, or drop it from `metadata`.",level:"warn",message:`vector index "${a.index}" declares metadata "${a.property}", whose type Vectorize cannot filter on.`});continue}e.push({code:"vector-metadata-index-required",fix:`wrangler ${O({index:a.index,property:a.property,type:o}).join(" ")}`,level:"info",message:`vector index "${a.index}" filters on metadata "${a.property}" — that needs a Vectorize metadata index (\`lunora deploy\` creates it).`})}},B=(t,e)=>{if(t===void 0)return;const n=(t.d1_databases??[]).filter(Boolean);for(const r of n){const a=typeof r.database_id=="string"?r.database_id:"";if(M(a)){const o=typeof r.binding=="string"&&r.binding.length>0?r.binding:"<unnamed>";e.push({code:"d1-placeholder-id",fix:"Run `wrangler d1 create <name>` and paste the returned database_id into wrangler.jsonc.",level:"fail",message:`D1 binding "${o}" has a placeholder database_id ("${a||"<empty>"}").`})}}},H=(t,e)=>{if(t===void 0)return;const n=(t.send_email??[]).filter(Boolean);for(const r of n){const a=typeof r.destination_address=="string"?r.destination_address:"";if(a!==""&&_(a)){const o=typeof r.name=="string"&&r.name.length>0?r.name:"send_email";e.push({code:"email-destination-placeholder",fix:"Set destination_address to a verified Cloudflare Email Routing address.",level:"warn",message:`send_email binding "${o}" has a placeholder destination_address ("${a}").`})}}},J=(t,e)=>{const n=u(t,m);if(!f(n))return;let r;try{r=g(n,"utf8")}catch{return}const a=x(r).filter(o=>N(o.key)&&_(o.value)).map(o=>o.key);a.length>0&&e.push({code:"dev-vars-missing-secret",fix:"Run `lunora dev` to auto-generate secrets, or fill them in by hand.",level:"warn",message:`${m} has unfilled secret value(s): ${a.join(", ")}.`})},X=(t,e)=>{const{source:n}=E({cwd:t});n===void 0?e.push({code:"admin-token-missing",fix:"Set LUNORA_ADMIN_TOKEN (env or `.dev.vars`) to enable admin RPCs / studio.",level:"info",message:"LUNORA_ADMIN_TOKEN is not set."}):e.push({code:"admin-token-set",level:"pass",message:`LUNORA_ADMIN_TOKEN is set (${D(n)}).`})},Y=async(t,e)=>{try{return await R({projectRoot:t})}catch(n){e.push({code:"declared-export-unchecked",fix:"Make sure the worker entry resolves (see `lunora codegen`), then re-run.",level:"warn",message:`could not check whether declared containers/workflows/agents are re-exported by the worker entry: ${n instanceof Error?n.message:String(n)}`});return}},q=(t,e)=>{const n=L(t),r=[...t.containers.map(a=>({...a,kind:"container"})),...t.workflows.map(a=>({...a,kind:"workflow"})),...t.agents.map(a=>({...a,kind:"agent"}))];for(const a of r.filter(o=>o.exported))e.push({code:"declared-export-ok",level:"pass",message:`${a.kind} "${a.exportName}" is exported by the worker entry.`});for(const a of n)e.push({code:"declared-export-missing",fix:`Add \`export * from "./lunora/_generated/${a.module}"\` to your worker entry (or re-run \`vis generate lunora-${a.kind}\`).`,level:"fail",message:`${a.kind} "${a.exportName}" is declared but ${a.className} is not exported by the worker entry.`})},Q=/^[\^~><= ]+/u,Z=/^(?<core>\d+\.\d+\.\d+)(?:-(?<channel>[a-z]+)\.(?<counter>\d+))?$/u,ee=t=>{const e=t.replace(Q,"").trim(),n=Z.exec(e);if(!n?.groups)return;const{channel:r,core:a,counter:o}=n.groups;return{channel:r??"",core:a??"",counter:o===void 0?void 0:Number.parseInt(o,10),raw:e}},ne=(t,e)=>{const n=u(t,"package.json");if(!f(n))return;let r;try{r=JSON.parse(g(n,"utf8"))}catch{return}const a={...r.devDependencies,...r.dependencies},o=[];for(const[i,d]of Object.entries(a)){if(i!=="lunorash"&&!i.startsWith("@lunora/"))continue;const v=ee(d);v&&o.push({name:i,version:v})}if(o.length<2)return;const c=i=>i.map(d=>`${d.name}@${d.version.raw}`).join(", "),s=new Set(o.map(i=>i.version.core)),l=new Set(o.map(i=>i.version.channel));if(s.size>1){e.push({code:"version-skew-cores",fix:'Run `pnpm update "@lunora/*" lunorash` (or `npm`/`yarn` equivalent) so every Lunora package moves to the same release.',level:"warn",message:`Lunora packages span ${String(s.size)} different versions: ${c(o)}.`});return}if(l.size>1){e.push({code:"version-skew-channels",fix:"Pick one channel (all stable, or all alpha/beta) and update the odd package out.",level:"warn",message:`Lunora packages mix release channels (${[...l].map(i=>i===""?"stable":i).join(" + ")}): ${c(o)}.`});return}const p=o.map(i=>i.version.counter).filter(i=>i!==void 0);if(p.length>1){const i=Math.min(...p),d=Math.max(...p);e.push({code:"version-counter-spread",level:"info",message:p.length===o.length&&i===d?`Lunora packages are all at ${[...l][0]??""}.${String(d)}.`:`Lunora pre-release counters span ${String(i)}–${String(d)}: ${c(o)}.`})}},re=[u("@lunora","cli"),"lunorash"],ae=(t,e,n)=>{if(e===void 0)return;const r=[];for(const o of re){const c=u(t,"node_modules",o);if(f(c))try{r.push(w(c))}catch{}}if(r.length===0)return;let a;try{a=w(e)}catch{return}r.some(o=>V(o,a))||n.push({code:"cli-shadowed",fix:"Run the project's own CLI: `pnpm exec lunora …` (or `npx lunora …`).",level:"warn",message:`the running lunora (${a}) is not the project's own install (${r.join(", ")}).`})},te=async t=>{const e=t.cwd??process.cwd(),n=[],{parsed:r,path:a}=T(e);W(e,r,a,n),B(r,n),H(r,n),F(r,n),K(r,n),J(e,n),X(e,n),ne(e,n),z(e,n),G(e,n),ae(e,t.executablePath??process.argv[1],n);const o=await Y(e,n);o!==void 0&&q(o,n),U(r,e,o?.usesAi===!0,n);const c={fail:0,info:0,pass:0,warn:0};for(const l of n)c[l.level]+=1;const s=c.fail>0?1:0;return{code:s,findings:n,ok:s===0,summary:c}},oe={fail:"FAIL",info:"INFO",pass:"PASS",warn:"WARN"},se=(t,e)=>{e.info("lunora doctor — project preflight");for(const a of t.findings){const o=`[${oe[a.level]}] ${a.message}`;a.level==="fail"?e.error(o):a.level==="warn"?e.warn(o):e.info(o),a.fix!==void 0&&a.level!=="pass"&&e.info(` fix: ${a.fix}`)}const{fail:n,warn:r}=t.summary;n>0?e.error(`${String(n)} failure(s), ${String(r)} warning(s).`):r>0?e.warn(`0 failures, ${String(r)} warning(s).`):e.success("all checks passed.")},ie=async t=>{const{logger:e}=t,n=await te({...t});return se(n,e),n},ve=P(async({cwd:t,format:e,logger:n})=>{const r=await ie({cwd:t,format:e,logger:n});return{code:r.code,data:{findings:r.findings,summary:r.summary}}});export{ve as execute,te as runDoctor,ie as runDoctorCommand};
1
+ import{writeFileSync as E,existsSync as w,cpSync as j,statSync as b,lstatSync as I,readdirSync as N,mkdirSync as D,readFileSync as M}from"node:fs";import{join as u,sep as x,relative as B,resolve as O,dirname as K}from"node:path";import{SDK_TARGETS as V,SDK_LANGUAGES as G,generateSdk as P,isTypedSchema as Q}from"@lunora/codegen";import{LunoraError as d}from"@lunora/errors";import{d as J}from"../packem_shared/command-CAXl2A1S.mjs";import{r as _,a as U,b as q,c as H,s as W}from"../packem_shared/resolve-DUCSc7jQ.mjs";const $="gh:anolilab/lunora/sdks",v="lunora-transport.json",X=/_test\.|Tests?\./u,k=t=>t.startsWith("test_")||X.test(t),A=(t,n="")=>N(t).toSorted((e,r)=>e.localeCompare(r)).flatMap(e=>{const r=u(t,e),a=n.length>0?`${n}/${e}`:e;return b(r).isDirectory()?A(r,a):[a]}),C=(t,n)=>{const e=I(n);if(e.isSymbolicLink())throw new d("INTERNAL",`refusing to vendor "${B(t,n)}" — it is a symlink, not a regular file`);if(e.isDirectory())for(const r of N(n))k(r)||C(t,u(n,r))},F=(t,n,e,r)=>{const a=u(t,e);if(!w(a))throw new d("NOT_FOUND",`transport is missing ${e}`);C(t,a);const s=u(n,r);return j(a,s,{filter:o=>!k(o.slice(o.lastIndexOf(x)+1)),force:!0,recursive:!0}),b(s).isDirectory()?A(s).map(o=>`${r}/${o}`):[r]},R=(t,n)=>n.vendor.every(e=>w(u(t,e.from))),z=async(t,n)=>{const{language:e,logger:r,outputDirectory:a,registryOptions:s,target:o}=n,{cleanup:f,directory:h}=await H(e,{...s,ref:t},$);try{if(!R(h,o)){r.warn(`${$}/${e} does not exist at ${t}.`);return}return{files:o.vendor.flatMap(c=>F(h,a,c.from,c.to)).toSorted((c,l)=>c.localeCompare(l)),ref:t,source:`${$}/${e}`,versionMatched:t===_()}}finally{f()}},Y=(t,n)=>{const{language:e,outputDirectory:r,target:a}=n,s=u(t,e);if(!w(s))throw new d("NOT_FOUND",`no transport at ${s} — --from must point at a directory of per-language transports (the repo's \`sdks/\`)`);if(!R(s,a)){const o=a.vendor.map(f=>f.from).join(", ");throw new d("NOT_FOUND",`${s} is not a ${e} transport — expected it to contain ${o}`)}return{files:a.vendor.flatMap(o=>F(s,r,o.from,o.to)).toSorted((o,f)=>o.localeCompare(f)),ref:"local",source:s,versionMatched:!1}},Z=async t=>{const{allowUnsafeSource:n,from:e,language:r,logger:a,outputDirectory:s,ref:o,source:f,target:h}=t;if(e!==void 0)return Y(e,{language:r,outputDirectory:s,target:h});const c={allowUnsafeSource:n,logger:a,names:[],source:f},l=async i=>z(await q(i,a),{language:r,logger:a,outputDirectory:s,registryOptions:c,target:h});if(o!==void 0&&o.length>0){const i=await l(o);if(i===void 0)throw new d("NOT_FOUND",`--ref ${o} carries no ${r} transport — pick a ref that does, or pass --from <dir> to copy a local one`);return i}const m=_(),g=await l(m).catch(i=>{const y=i instanceof Error?i.message.split(`
2
+ `)[0]??i.message:String(i);a.warn(`could not fetch the transport at ${m} (${y}).`)});if(g!==void 0)return g;const p=await l(void 0);if(p===void 0)throw new d("NOT_FOUND",`no ${r} transport at ${m} or on the release branch. This language may not be released yet — pass --from <dir> to copy one from a checkout, or --ref <tag> to name a ref that has it.`);return a.warn(`FALLBACK: the transport is NOT version-matched to this CLI (${U()}). Wanted ${m}, used ${p.ref}. The vendored wire protocol may not be the one this surface was generated against; ${v} records what was actually copied.`),p},ee=(t,n,e)=>{const r={cliVersion:U(),files:e.files,language:n,note:e.versionMatched?"Vendored by `lunora sdk generate` at the ref matching the CLI that generated the surface beside it. Regenerate with a newer CLI to upgrade.":"Vendored by `lunora sdk generate` from a ref that is NOT this CLI's release tag, so the transport and the generated surface may be different protocol vintages.",ref:e.ref,source:e.source,versionMatched:e.versionMatched};E(u(t,v),`${JSON.stringify(r,void 0,4)}
3
+ `,"utf8")},te=u("lunora","_generated","openrpc.json"),re=t=>{if(!w(t))throw new d("NOT_FOUND",`no OpenRPC document at ${t} — run \`lunora codegen --api-spec openrpc\` (or \`--api-spec both\`) first, or pass --spec`);let n;try{n=JSON.parse(M(t,"utf8"))}catch(e){throw new d("BAD_REQUEST",`${t} is not valid JSON: ${e instanceof Error?e.message:String(e)}`)}if(n===null||typeof n!="object"||!Array.isArray(n.methods))throw new d("BAD_REQUEST",`${t} is not an OpenRPC document (no \`methods\` array)`);return n},de=J(async({argument:t,cwd:n,logger:e,options:r})=>{const a=t[0]??"generate";if(a!=="generate")throw new d("BAD_REQUEST",`unknown subcommand "${a}" — the only one is \`lunora sdk generate\``);const s=r.lang??"python",o=V[s];if(o===void 0)throw new d("BAD_REQUEST",`unsupported --lang "${s}" — expected one of: ${G.join(" | ")}`);const f=W("sdk generate",{allowUnsafeSource:r.allowUnsafeSource,logger:e,names:[],source:r.source});if(f!==void 0)throw new d("BAD_REQUEST",f);const h=O(n,r.spec??te),c=O(n,r.out??u("sdk",s)),l=re(h);l.methods.length===0&&e.warn(`${h} declares no methods — writing an empty SDK.`);const{files:m,undeclared:g,unrepresentable:p}=await P(l,o);D(c,{recursive:!0});const i=await Z({allowUnsafeSource:r.allowUnsafeSource,from:r.from,language:s,logger:e,outputDirectory:c,ref:r.ref,source:r.source,target:o});ee(c,s,i);for(const[S,L]of Object.entries(m)){const T=u(c,S);D(K(T),{recursive:!0}),E(T,L,"utf8")}const y=l.methods.filter(S=>!Q(S.result?.schema)).length;return e.success(`Generated ${s} SDK for ${String(l.methods.length)} function(s) → ${c}`),e.info(`Vendored the ${s} transport (${String(i.files.length)} file(s)) from ${i.source} @ ${i.ref}${i.versionMatched?" — version-matched to this CLI":""}; see ${v}.`),e.info(o.requires.length>0?`Install in the consuming project: ${o.requires.join(", ")}.`:"Nothing to install — the transport is vendored and needs only the standard library."),g.length>0&&e.warn(`${String(g.length)} schema(s) are not expressible as a named ${s} model, so those arguments or returns stay untyped: ${g.join(", ")}`),p.length>0&&e.warn(`${String(p.length)} function(s) take or return a \`v.bigint()\`/\`v.bytes()\`, which no generated model can carry — their parameters stay untyped, so pass wire values directly: ${p.join(", ")}`),y>0&&e.warn(`${String(y)} of ${String(l.methods.length)} function(s) return an untyped result — declare \`.output()\` on them for typed returns.`),{code:0}});export{de as execute};
@@ -1,3 +1,3 @@
1
- import{writeFileSync as E,existsSync as w,cpSync as j,statSync as b,lstatSync as I,readdirSync as N,mkdirSync as D,readFileSync as M}from"node:fs";import{join as u,sep as x,relative as B,resolve as O,dirname as K}from"node:path";import{SDK_TARGETS as V,SDK_LANGUAGES as G,generateSdk as P,isTypedSchema as Q}from"@lunora/codegen";import{LunoraError as d}from"@lunora/errors";import{d as J}from"../packem_shared/command-CAXl2A1S.mjs";import{r as _,a as U,b as q,c as H,s as W}from"../packem_shared/resolve-DUCSc7jQ.mjs";const $="gh:anolilab/lunora/sdks",v="lunora-transport.json",X=/_test\.|Tests?\./u,k=t=>t.startsWith("test_")||X.test(t),A=(t,n="")=>N(t).toSorted((e,r)=>e.localeCompare(r)).flatMap(e=>{const r=u(t,e),a=n.length>0?`${n}/${e}`:e;return b(r).isDirectory()?A(r,a):[a]}),C=(t,n)=>{const e=I(n);if(e.isSymbolicLink())throw new d("INTERNAL",`refusing to vendor "${B(t,n)}" — it is a symlink, not a regular file`);if(e.isDirectory())for(const r of N(n))k(r)||C(t,u(n,r))},F=(t,n,e,r)=>{const a=u(t,e);if(!w(a))throw new d("NOT_FOUND",`transport is missing ${e}`);C(t,a);const s=u(n,r);return j(a,s,{filter:o=>!k(o.slice(o.lastIndexOf(x)+1)),force:!0,recursive:!0}),b(s).isDirectory()?A(s).map(o=>`${r}/${o}`):[r]},R=(t,n)=>n.vendor.every(e=>w(u(t,e.from))),z=async(t,n)=>{const{language:e,logger:r,outputDirectory:a,registryOptions:s,target:o}=n,{cleanup:f,directory:h}=await H(e,{...s,ref:t},$);try{if(!R(h,o)){r.warn(`${$}/${e} does not exist at ${t}.`);return}return{files:o.vendor.flatMap(c=>F(h,a,c.from,c.to)).toSorted((c,l)=>c.localeCompare(l)),ref:t,source:`${$}/${e}`,versionMatched:t===_()}}finally{f()}},Y=(t,n)=>{const{language:e,outputDirectory:r,target:a}=n,s=u(t,e);if(!w(s))throw new d("NOT_FOUND",`no transport at ${s} — --from must point at a directory of per-language transports (the repo's \`sdks/\`)`);if(!R(s,a)){const o=a.vendor.map(f=>f.from).join(", ");throw new d("NOT_FOUND",`${s} is not a ${e} transport — expected it to contain ${o}`)}return{files:a.vendor.flatMap(o=>F(s,r,o.from,o.to)).toSorted((o,f)=>o.localeCompare(f)),ref:"local",source:s,versionMatched:!1}},Z=async t=>{const{allowUnsafeSource:n,from:e,language:r,logger:a,outputDirectory:s,ref:o,source:f,target:h}=t;if(e!==void 0)return Y(e,{language:r,outputDirectory:s,target:h});const c={allowUnsafeSource:n,logger:a,names:[],source:f},l=async i=>z(await q(i,a),{language:r,logger:a,outputDirectory:s,registryOptions:c,target:h});if(o!==void 0&&o.length>0){const i=await l(o);if(i===void 0)throw new d("NOT_FOUND",`--ref ${o} carries no ${r} transport — pick a ref that does, or pass --from <dir> to copy a local one`);return i}const m=_(),g=await l(m).catch(i=>{const y=i instanceof Error?i.message.split(`
2
- `)[0]??i.message:String(i);a.warn(`could not fetch the transport at ${m} (${y}).`)});if(g!==void 0)return g;const p=await l(void 0);if(p===void 0)throw new d("NOT_FOUND",`no ${r} transport at ${m} or on the release branch. This language may not be released yet — pass --from <dir> to copy one from a checkout, or --ref <tag> to name a ref that has it.`);return a.warn(`FALLBACK: the transport is NOT version-matched to this CLI (${U()}). Wanted ${m}, used ${p.ref}. The vendored wire protocol may not be the one this surface was generated against; ${v} records what was actually copied.`),p},ee=(t,n,e)=>{const r={cliVersion:U(),files:e.files,language:n,note:e.versionMatched?"Vendored by `lunora sdk generate` at the ref matching the CLI that generated the surface beside it. Regenerate with a newer CLI to upgrade.":"Vendored by `lunora sdk generate` from a ref that is NOT this CLI's release tag, so the transport and the generated surface may be different protocol vintages.",ref:e.ref,source:e.source,versionMatched:e.versionMatched};E(u(t,v),`${JSON.stringify(r,void 0,4)}
3
- `,"utf8")},te=u("lunora","_generated","openrpc.json"),re=t=>{if(!w(t))throw new d("NOT_FOUND",`no OpenRPC document at ${t} — run \`lunora codegen --api-spec openrpc\` (or \`--api-spec both\`) first, or pass --spec`);let n;try{n=JSON.parse(M(t,"utf8"))}catch(e){throw new d("BAD_REQUEST",`${t} is not valid JSON: ${e instanceof Error?e.message:String(e)}`)}if(n===null||typeof n!="object"||!Array.isArray(n.methods))throw new d("BAD_REQUEST",`${t} is not an OpenRPC document (no \`methods\` array)`);return n},de=J(async({argument:t,cwd:n,logger:e,options:r})=>{const a=t[0]??"generate";if(a!=="generate")throw new d("BAD_REQUEST",`unknown subcommand "${a}" — the only one is \`lunora sdk generate\``);const s=r.lang??"python",o=V[s];if(o===void 0)throw new d("BAD_REQUEST",`unsupported --lang "${s}" — expected one of: ${G.join(" | ")}`);const f=W("sdk generate",{allowUnsafeSource:r.allowUnsafeSource,logger:e,names:[],source:r.source});if(f!==void 0)throw new d("BAD_REQUEST",f);const h=O(n,r.spec??te),c=O(n,r.out??u("sdk",s)),l=re(h);l.methods.length===0&&e.warn(`${h} declares no methods — writing an empty SDK.`);const{files:m,undeclared:g,unrepresentable:p}=await P(l,o);D(c,{recursive:!0});const i=await Z({allowUnsafeSource:r.allowUnsafeSource,from:r.from,language:s,logger:e,outputDirectory:c,ref:r.ref,source:r.source,target:o});ee(c,s,i);for(const[S,L]of Object.entries(m)){const T=u(c,S);D(K(T),{recursive:!0}),E(T,L,"utf8")}const y=l.methods.filter(S=>!Q(S.result?.schema)).length;return e.success(`Generated ${s} SDK for ${String(l.methods.length)} function(s) → ${c}`),e.info(`Vendored the ${s} transport (${String(i.files.length)} file(s)) from ${i.source} @ ${i.ref}${i.versionMatched?" — version-matched to this CLI":""}; see ${v}.`),e.info(o.requires.length>0?`Install in the consuming project: ${o.requires.join(", ")}.`:"Nothing to install — the transport is vendored and needs only the standard library."),g.length>0&&e.warn(`${String(g.length)} schema(s) are not expressible as a named ${s} model, so those arguments or returns stay untyped: ${g.join(", ")}`),p.length>0&&e.warn(`${String(p.length)} function(s) take or return a \`v.bigint()\`/\`v.bytes()\`, which no generated model can carry — their parameters stay untyped, so pass wire values directly: ${p.join(", ")}`),y>0&&e.warn(`${String(y)} of ${String(l.methods.length)} function(s) return an untyped result — declare \`.output()\` on them for typed returns.`),{code:0}});export{de as execute};
1
+ import z,{join as m,resolve as I}from"node:path";import{isInteractive as J,promptYesNo as W}from"@lunora/config";import{backupObjectKey as v,isBackupManifestEntry as D,normalizeBackupPrefix as Y,BACKUP_KEY_PREFIX as X,backupManifestKey as Q,isBackupManifestKey as V,backupObjectKeyOfManifest as G}from"@lunora/runtime";import{r as E,t as Z}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{r as A,a as T}from"../packem_shared/admin-url-DJB8P6Jh.mjs";import{d as ee}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as u,isRefusal as p,exitCodeForStatus as k}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{a as re}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{runExportCommand as te}from"../packem_shared/runExportCommand-slAq5BCF.mjs";import{b as ae,l as oe,M as U,u as ne,r as ie}from"../packem_shared/import-BRM1hs7j.mjs";import{readAndLogBody as y}from"./runRpcCommand.mjs";import{randomUUID as j,createHash as se}from"node:crypto";import{existsSync as N,createReadStream as ce,createWriteStream as de}from"node:fs";import{mkdir as ue,rm as b,rename as C,readFile as q,writeFile as le,realpath as _,mkdtemp as x}from"node:fs/promises";import{LunoraError as w}from"@lunora/errors";import{i as R}from"../packem_shared/path-containment-CgxYZggb.mjs";import{tmpdir as O}from"node:os";import{Readable as fe}from"node:stream";import{pipeline as me}from"node:stream/promises";const S="manifest.json",L=async e=>{const t=se("sha256");let r=0;for await(const a of ce(e)){const o=a;r+=o.byteLength,t.update(o)}return{bytes:r,sha256:t.digest("hex")}},P=async e=>{const t=m(e,S);if(!N(t))return[];let r;try{r=JSON.parse(await q(t,"utf8"))}catch(a){const o=a instanceof Error?a.message:String(a);throw new w("INTERNAL",`backup: ${t} exists but is not valid JSON (${o}) — refusing to overwrite it; fix or remove it manually`,{cause:a})}if(!Array.isArray(r))throw new TypeError(`backup: ${t} exists but is not a JSON array — refusing to overwrite it; fix or remove it manually`);return r.filter(a=>D(a))},ge=async(e,t)=>{const r=m(e,`${S}.${j()}.tmp`);try{await le(r,`${JSON.stringify(t,void 0,2)}
2
+ `,"utf8"),await C(r,m(e,S))}catch(a){throw await b(r,{force:!0}),a}},he=async(e,t)=>{const r=I(e),a=I(r,t.file),o=()=>{throw new w("INTERNAL",`backup: entry ${t.id} points outside ${r} (${t.file}) — refusing to read it`)};if(R(r,a)||o(),!!N(a))return R(await _(r),await _(a))||o(),a},we=e=>{const t=r=>v("",r);return{commit:async(r,a)=>{await C(a,m(e,r))},label:e,list:async()=>P(e),locate:t,materialize:async(r,a)=>{const o=i=>i===void 0?void 0:{path:i,release:()=>Promise.resolve()};return o(r===void 0?N(a)?a:void 0:await he(e,r))},record:async r=>{const a=await P(e);a.push(r),await ge(e,a)},stage:async r=>{await ue(e,{recursive:!0});const a=m(e,`${t(r)}.${j()}.partial`);return{path:a,release:()=>b(a,{force:!0})}}}},be="/_lunora/admin/storage/object",ke="/_lunora/admin/storage",B=8,ye=(e,t=z)=>{const r=t.basename(e);return r===""||r==="."||r===".."?"snapshot.ndjson":r},pe=e=>{const{context:t,logger:r}=e,a=Y(e.prefix??X),o=`bucket ${t.bucket??"(default)"} under ${a}`,i=ae(t),n=c=>`${t.baseUrl}${be}?key=${encodeURIComponent(c)}${i}`,f=async c=>{const s=await t.fetchImpl(n(c),{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(!s.ok){const l=await s.text().catch(()=>"<no body>");throw new w("INTERNAL",`backup: could not read ${c} (HTTP ${String(s.status)}): ${l}`)}return s.text()},H=async c=>{try{const s=JSON.parse(await f(c));if(D(s))return s;r.warn(`backup: ignoring ${c} — not a backup manifest`)}catch(s){r.warn(`backup: ignoring ${c} — ${s instanceof Error?s.message:String(s)}`)}};return{commit:async(c,s,l)=>{if(l.bytes>U)throw new w("INTERNAL",`backup: the snapshot is ${String(l.bytes)} bytes, above the ${String(U)}-byte limit for a checksum-verified upload — nothing was written. Narrow it with \`--tables\`, or write it to a directory with \`--dir\` and move the file yourself (\`wrangler r2 object put\`).`);const d=await q(s);await ne(t,c,d,{contentType:"application/x-ndjson",id:c,sha256:l.sha256,size:l.bytes},r)},label:o,list:async()=>{const s=(await oe(t,a)).map(d=>d.key).filter(d=>V(d)),l=[];for(let d=0;d<s.length;d+=B){const g=await Promise.all(s.slice(d,d+B).map(async h=>H(h)));l.push(...g.filter(h=>h!==void 0))}return l.toSorted((d,g)=>d.id.localeCompare(g.id))},locate:c=>v(a,c),materialize:async(c,s)=>{const l=c?.file??s,d=await t.fetchImpl(n(l),{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(d.status===404)return;if(!d.ok||d.body===null){const $=await d.text().catch(()=>"<no body>");throw new w("INTERNAL",`backup: could not download ${l} (HTTP ${String(d.status)}): ${$}`)}const g=await x(m(O(),"lunora-backup-")),h=m(g,ye(l));try{await me(fe.from(d.body),de(h))}catch($){throw await b(g,{force:!0,recursive:!0}),$}return{path:h,release:async()=>b(g,{force:!0,recursive:!0})}},record:async c=>{const s=Q(c.file),l=await t.fetchImpl(`${t.baseUrl}${ke}?key=${encodeURIComponent(s)}${i}`,{body:`${JSON.stringify(c,void 0,2)}
3
+ `,headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json"},method:"PUT"});if(!l.ok){const d=await l.text().catch(()=>"<no body>");throw new w("INTERNAL",`backup: snapshot ${c.file} was written but its manifest was not (HTTP ${String(l.status)}): ${d}`)}},stage:async c=>{const s=await x(m(O(),"lunora-backup-"));return{path:m(s,v("",c)),release:async()=>b(s,{force:!0,recursive:!0})}}}},$e=".lunora-backups",F="/_lunora/admin/backup/retention",ve="/_lunora/admin/backup/prune",Se="/_lunora/admin/pitr",Ee="__lunora_admin__:getPitrBookmark",Ae="__lunora_admin__:pitrRestore",Te=async(e,t)=>{const r=(e.now??(()=>new Date))().toISOString(),a=await t.stage(r);try{const o=await te({cwd:e.cwd,fetchImpl:e.fetchImpl,logger:e.logger,out:a.path,prod:e.prod,tables:e.tables,token:e.token,url:e.url});if(o.code!==0)return{code:o.code};const i=t.locate(r),n=await L(a.path);await t.commit(i,a.path,n);const f={bytes:n.bytes,createdAt:r,file:i,id:r,rows:o.rows,sha256:n.sha256,tables:e.tables};return await t.record(f),e.logger.success(`backup created: ${i} (${o.rows.toString()} rows, ${n.bytes.toString()} bytes)`),{code:0,entry:f}}finally{await a.release().catch(o=>{e.logger.warn(`backup: could not clean up staging (${o instanceof Error?o.message:String(o)})`)})}},Ne=async(e,t,r)=>{if(t?.sha256===void 0)return r.error(t===void 0?"--verify needs a recorded checksum, and a snapshot restored by path/key has no manifest entry — restore it by its backup id instead":`--verify: backup ${t.id} carries no recorded checksum — it was taken by a release before checksums existed`),{code:u.USAGE};const a=await L(e);if(a.sha256!==t.sha256)return r.error(`--verify: ${t.file} does not match its recorded checksum (expected ${t.sha256}, got ${a.sha256}) — nothing was imported`),{code:1};r.success(`verified ${t.file} against its recorded sha256`)},Ie=async(e,t)=>{const r=await t.list();if(r.length===0)return e.logger.info(`no backups found in ${t.label}`),{code:0,entries:[]};for(const a of r)e.logger.info(`${a.id} ${a.rows.toString()} rows ${a.bytes.toString()} bytes ${a.file}`);return{code:0,entries:r}},Ue=async(e,t)=>{const{target:r}=e;if(r===void 0||r.length===0)return e.logger.error("restore requires a backup id or file path. Usage: lunora backup restore <id|file>"),{code:u.USAGE};const o=(await t.list()).find(n=>n.id===r),i=await t.materialize(o,r);if(i===void 0)return e.logger.error(`backup not found: ${r}`),{code:u.NOT_FOUND};try{if(e.verify===!0){const f=await Ne(i.path,o,e.logger);if(f!==void 0)return f}const n=await ie({cwd:e.cwd,fetchImpl:e.fetchImpl,file:i.path,logger:e.logger,prod:e.prod,token:e.token,url:e.url,yes:e.yes});return{code:n.code,entry:o,restored:n.inserted}}finally{await i.release().catch(n=>{e.logger.warn(`backup: could not clean up the downloaded snapshot (${n instanceof Error?n.message:String(n)})`)})}},_e=e=>{if(e.prod&&e.url===void 0)return e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)"),{refused:u.USAGE};if(e.restore===!0&&e.at===void 0&&e.bookmark===void 0)return e.logger.error("pitr --restore requires --at <time> or --bookmark <bookmark>"),{refused:u.USAGE};const t=A(e.url,e.logger,e.cwd);if(t===void 0)return{refused:u.USAGE};if(e.restore===!0&&Z({prod:e.prod,url:t})&&e.yes!==!0)return e.logger.error(`pitr --restore restores data in place at ${t}, which is not local. Re-run with --yes to confirm.`),{refused:u.USAGE};const{token:r}=E({cwd:e.cwd??process.cwd(),token:e.token,url:t});return r?{fetchImpl:e.adminFetch??T,requestUrl:`${t}${Se}`,token:r}:(e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{refused:u.AUTH})},xe=(e,t)=>{const r={};return e.at!==void 0&&(r.time=e.at),t&&e.bookmark!==void 0&&(r.bookmark=e.bookmark),t&&e.restart===!0&&(r.restart=!0),r},Re=async e=>{const t=_e(e);if(p(t))return{code:t.refused};const r=e.restore===!0,a=r?Ae:Ee,o=xe(e,r),i=r?"restore":"bookmark";e.logger.info(`POST ${t.requestUrl} -> pitr ${i}${e.shard===void 0?"":` (shard "${e.shard}")`}`);const n=await t.fetchImpl(t.requestUrl,{body:JSON.stringify({args:o,functionPath:a,shardKey:e.shard}),headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json"},method:"POST"});return{body:await y(n,e.logger),code:n.ok?0:k(n.status)}},Oe=(e,t)=>{if(e.bucket===void 0)return e.prefix!==void 0?(e.logger.error("--prefix applies only to an R2 destination — pass --bucket alongside it, or use --dir to point at a local directory."),{refused:u.USAGE}):we(m(t,e.dir??$e));if(e.dir!==void 0)return e.logger.error("--dir applies only to a local destination and does not apply alongside --bucket — drop one."),{refused:u.USAGE};if(e.prod===!0&&e.url===void 0)return e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)"),{refused:u.USAGE};const r=A(e.url,e.logger,e.cwd);if(r===void 0)return{refused:u.USAGE};const{token:a}=E({cwd:t,token:e.token,url:r});if(!a)return e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{refused:u.AUTH};const o=e.fetchImpl??T;return pe({context:{baseUrl:r,bucket:e.bucket==="default"?void 0:e.bucket,fetchImpl:o,token:a},logger:e.logger,prefix:e.prefix})},M=e=>{const t=[e.bucket===void 0?void 0:"--bucket",e.prefix===void 0?void 0:"--prefix",e.dir===void 0?void 0:"--dir"].filter(i=>i!==void 0);if(t.length>0)return e.logger.error(`${t.join(" / ")} ${t.length===1?"does":"do"} not apply here — retention and prune act on the store the worker itself is configured with (\`backupStore\`), not a destination you name.`),{refused:u.USAGE};if(e.prod===!0&&e.url===void 0)return e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)"),{refused:u.USAGE};const r=A(e.url,e.logger,e.cwd);if(r===void 0)return{refused:u.USAGE};const{token:a}=E({cwd:e.cwd??process.cwd(),token:e.token,url:r});if(!a)return e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{refused:u.AUTH};const o=e.adminFetch??T;return{baseUrl:r,fetchImpl:o,token:a}},K=(e,t)=>{e.logger.info(`backup retention would keep the newest ${t.keep.toString()} of ${t.eligible.toString()} under ${t.prefix} and delete ${t.wouldDelete.length.toString()}`);for(const r of t.wouldDelete)e.logger.info(` ${G(r)}`)},Pe=async e=>{const t=M(e);if(p(t))return{code:t.refused};const r=await t.fetchImpl(`${t.baseUrl}${F}`,{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(!r.ok)return await y(r,e.logger),{code:k(r.status)};const a=await r.json();return a.cron===void 0?(e.logger.info("no scheduled backup is configured (`backupCron`), so retention would delete nothing"),{code:0,preview:a}):a.keep<=0?(e.logger.info(`retention is off for cron "${a.cron}" (\`backupRetain\` unset) — every snapshot under ${a.prefix} is kept`),{code:0,preview:a}):(K(e,a),a.eligible===0&&e.logger.info(`no snapshot under ${a.prefix} was written by this cron, so retention has nothing of its own to remove`),{code:0,preview:a})},Be=(e,t)=>{e.logger.success(`deleted ${t.deleted.length.toString()} backup(s)`);for(const r of t.deleted)e.logger.info(` ${G(r)}`);t.failed.length>0&&e.logger.warn(`${t.failed.length.toString()} could not be removed — the snapshot may be gone with its manifest left behind; run again to retry`),t.ignored>0&&e.logger.info(`${t.ignored.toString()} were already gone by the time the delete ran`),t.remaining>0&&e.logger.info(`${t.remaining.toString()} more are past the window — run \`lunora backup prune\` again`)},De=async e=>{const t=M(e);if(p(t))return{code:t.refused};const r=await t.fetchImpl(`${t.baseUrl}${F}`,{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(!r.ok)return await y(r,e.logger),{code:k(r.status)};const a=await r.json();if(a.keep<=0||a.cron===void 0)return e.logger.error("backup prune needs a retention window: set `backupRetain` (and `backupCron`) on the worker. Without one there is nothing past the window to remove."),{code:u.USAGE,preview:a};if(a.wouldDelete.length===0)return e.logger.info(`nothing to prune — ${a.eligible.toString()} snapshot(s) under ${a.prefix} and retention keeps the newest ${a.keep.toString()}`),{code:0,preview:a};if(K(e,a),e.yes!==!0){const n=e.confirm??(J()?W:void 0);if(n===void 0)return e.logger.error("refusing to delete backups without confirmation — re-run with --yes (there is no undo for an object-store delete)"),{code:u.USAGE,preview:a};if(!await n(`delete ${a.wouldDelete.length.toString()} backup(s)? This cannot be undone. [y/N] `))return e.logger.info("nothing was deleted"),{code:0,preview:a}}const o=await t.fetchImpl(`${t.baseUrl}${ve}`,{body:JSON.stringify({confirm:a.wouldDelete}),headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json"},method:"POST"});if(!o.ok)return await y(o,e.logger),{code:k(o.status),preview:a};const i=await o.json();return Be(e,i),{code:i.failed.length>0?1:0,deleted:i.deleted,preview:a}},Ge=async(e,t)=>{try{if(e.subcommand==="pitr")return await Re(e);if(e.subcommand==="retention")return await Pe(e);if(e.subcommand==="prune")return await De(e);const r=Oe(e,t);return p(r)?{code:r.refused}:e.subcommand==="create"?await Te(e,r):e.subcommand==="list"?await Ie(e,r):await Ue(e,r)}catch(r){return e.logger.error(r instanceof Error?r.message:String(r)),{code:1}}},je=async e=>{const t=e.cwd??process.cwd(),r=await Ge(e,t);return{...r,data:{subcommand:e.subcommand,...r.entries===void 0?{}:{entries:r.entries},...r.entry===void 0?{}:{entry:r.entry},...r.restored===void 0?{}:{restored:r.restored},...r.preview===void 0?{}:{preview:r.preview},...r.deleted===void 0?{}:{deleted:r.deleted},...r.body===void 0?{}:{result:r.body}}}},Ce=e=>e==="create"||e==="list"||e==="pitr"||e==="prune"||e==="restore"||e==="retention",nr=ee(async({argument:e,cwd:t,format:r,logger:a,options:o})=>{const i=e[0];if(!Ce(i)){const f=`backup: unknown subcommand "${i??""}" — expected create | list | restore | retention | prune | pitr`;return a.error(f),{code:u.USAGE,error:f}}const n=await je({at:o.at,bookmark:o.bookmark,bucket:o.bucket,cwd:t,dir:o.dir,format:r,logger:a,prefix:o.prefix,prod:o.prod===!0,restart:o.restart===!0,restore:o.restore===!0,shard:o.shard,subcommand:i,tables:o.tables,target:e[1],token:o.token,url:re({cwd:t,prod:o.prod===!0,url:o.url}),verify:o.verify===!0,yes:o.yes===!0});return{code:n.code,data:n.data,error:n.error}});export{nr as execute,je as runBackupCommand};
@@ -1,3 +1 @@
1
- import z,{join as m,resolve as I}from"node:path";import{isInteractive as J,promptYesNo as W}from"@lunora/config";import{backupObjectKey as v,isBackupManifestEntry as D,normalizeBackupPrefix as Y,BACKUP_KEY_PREFIX as X,backupManifestKey as Q,isBackupManifestKey as V,backupObjectKeyOfManifest as G}from"@lunora/runtime";import{r as E,t as Z}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{r as A,a as T}from"../packem_shared/admin-url-DJB8P6Jh.mjs";import{d as ee}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as u,isRefusal as p,exitCodeForStatus as k}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{a as re}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{runExportCommand as te}from"../packem_shared/runExportCommand-slAq5BCF.mjs";import{b as ae,l as oe,M as U,u as ne,r as ie}from"../packem_shared/import-BRM1hs7j.mjs";import{readAndLogBody as y}from"./runRpcCommand.mjs";import{randomUUID as j,createHash as se}from"node:crypto";import{existsSync as N,createReadStream as ce,createWriteStream as de}from"node:fs";import{mkdir as ue,rm as b,rename as C,readFile as q,writeFile as le,realpath as _,mkdtemp as x}from"node:fs/promises";import{LunoraError as w}from"@lunora/errors";import{i as R}from"../packem_shared/path-containment-CgxYZggb.mjs";import{tmpdir as O}from"node:os";import{Readable as fe}from"node:stream";import{pipeline as me}from"node:stream/promises";const S="manifest.json",L=async e=>{const t=se("sha256");let r=0;for await(const a of ce(e)){const o=a;r+=o.byteLength,t.update(o)}return{bytes:r,sha256:t.digest("hex")}},P=async e=>{const t=m(e,S);if(!N(t))return[];let r;try{r=JSON.parse(await q(t,"utf8"))}catch(a){const o=a instanceof Error?a.message:String(a);throw new w("INTERNAL",`backup: ${t} exists but is not valid JSON (${o}) — refusing to overwrite it; fix or remove it manually`,{cause:a})}if(!Array.isArray(r))throw new TypeError(`backup: ${t} exists but is not a JSON array — refusing to overwrite it; fix or remove it manually`);return r.filter(a=>D(a))},ge=async(e,t)=>{const r=m(e,`${S}.${j()}.tmp`);try{await le(r,`${JSON.stringify(t,void 0,2)}
2
- `,"utf8"),await C(r,m(e,S))}catch(a){throw await b(r,{force:!0}),a}},he=async(e,t)=>{const r=I(e),a=I(r,t.file),o=()=>{throw new w("INTERNAL",`backup: entry ${t.id} points outside ${r} (${t.file}) — refusing to read it`)};if(R(r,a)||o(),!!N(a))return R(await _(r),await _(a))||o(),a},we=e=>{const t=r=>v("",r);return{commit:async(r,a)=>{await C(a,m(e,r))},label:e,list:async()=>P(e),locate:t,materialize:async(r,a)=>{const o=i=>i===void 0?void 0:{path:i,release:()=>Promise.resolve()};return o(r===void 0?N(a)?a:void 0:await he(e,r))},record:async r=>{const a=await P(e);a.push(r),await ge(e,a)},stage:async r=>{await ue(e,{recursive:!0});const a=m(e,`${t(r)}.${j()}.partial`);return{path:a,release:()=>b(a,{force:!0})}}}},be="/_lunora/admin/storage/object",ke="/_lunora/admin/storage",B=8,ye=(e,t=z)=>{const r=t.basename(e);return r===""||r==="."||r===".."?"snapshot.ndjson":r},pe=e=>{const{context:t,logger:r}=e,a=Y(e.prefix??X),o=`bucket ${t.bucket??"(default)"} under ${a}`,i=ae(t),n=c=>`${t.baseUrl}${be}?key=${encodeURIComponent(c)}${i}`,f=async c=>{const s=await t.fetchImpl(n(c),{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(!s.ok){const l=await s.text().catch(()=>"<no body>");throw new w("INTERNAL",`backup: could not read ${c} (HTTP ${String(s.status)}): ${l}`)}return s.text()},H=async c=>{try{const s=JSON.parse(await f(c));if(D(s))return s;r.warn(`backup: ignoring ${c} — not a backup manifest`)}catch(s){r.warn(`backup: ignoring ${c} — ${s instanceof Error?s.message:String(s)}`)}};return{commit:async(c,s,l)=>{if(l.bytes>U)throw new w("INTERNAL",`backup: the snapshot is ${String(l.bytes)} bytes, above the ${String(U)}-byte limit for a checksum-verified upload — nothing was written. Narrow it with \`--tables\`, or write it to a directory with \`--dir\` and move the file yourself (\`wrangler r2 object put\`).`);const d=await q(s);await ne(t,c,d,{contentType:"application/x-ndjson",id:c,sha256:l.sha256,size:l.bytes},r)},label:o,list:async()=>{const s=(await oe(t,a)).map(d=>d.key).filter(d=>V(d)),l=[];for(let d=0;d<s.length;d+=B){const g=await Promise.all(s.slice(d,d+B).map(async h=>H(h)));l.push(...g.filter(h=>h!==void 0))}return l.toSorted((d,g)=>d.id.localeCompare(g.id))},locate:c=>v(a,c),materialize:async(c,s)=>{const l=c?.file??s,d=await t.fetchImpl(n(l),{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(d.status===404)return;if(!d.ok||d.body===null){const $=await d.text().catch(()=>"<no body>");throw new w("INTERNAL",`backup: could not download ${l} (HTTP ${String(d.status)}): ${$}`)}const g=await x(m(O(),"lunora-backup-")),h=m(g,ye(l));try{await me(fe.from(d.body),de(h))}catch($){throw await b(g,{force:!0,recursive:!0}),$}return{path:h,release:async()=>b(g,{force:!0,recursive:!0})}},record:async c=>{const s=Q(c.file),l=await t.fetchImpl(`${t.baseUrl}${ke}?key=${encodeURIComponent(s)}${i}`,{body:`${JSON.stringify(c,void 0,2)}
3
- `,headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json"},method:"PUT"});if(!l.ok){const d=await l.text().catch(()=>"<no body>");throw new w("INTERNAL",`backup: snapshot ${c.file} was written but its manifest was not (HTTP ${String(l.status)}): ${d}`)}},stage:async c=>{const s=await x(m(O(),"lunora-backup-"));return{path:m(s,v("",c)),release:async()=>b(s,{force:!0,recursive:!0})}}}},$e=".lunora-backups",F="/_lunora/admin/backup/retention",ve="/_lunora/admin/backup/prune",Se="/_lunora/admin/pitr",Ee="__lunora_admin__:getPitrBookmark",Ae="__lunora_admin__:pitrRestore",Te=async(e,t)=>{const r=(e.now??(()=>new Date))().toISOString(),a=await t.stage(r);try{const o=await te({cwd:e.cwd,fetchImpl:e.fetchImpl,logger:e.logger,out:a.path,prod:e.prod,tables:e.tables,token:e.token,url:e.url});if(o.code!==0)return{code:o.code};const i=t.locate(r),n=await L(a.path);await t.commit(i,a.path,n);const f={bytes:n.bytes,createdAt:r,file:i,id:r,rows:o.rows,sha256:n.sha256,tables:e.tables};return await t.record(f),e.logger.success(`backup created: ${i} (${o.rows.toString()} rows, ${n.bytes.toString()} bytes)`),{code:0,entry:f}}finally{await a.release().catch(o=>{e.logger.warn(`backup: could not clean up staging (${o instanceof Error?o.message:String(o)})`)})}},Ne=async(e,t,r)=>{if(t?.sha256===void 0)return r.error(t===void 0?"--verify needs a recorded checksum, and a snapshot restored by path/key has no manifest entry — restore it by its backup id instead":`--verify: backup ${t.id} carries no recorded checksum — it was taken by a release before checksums existed`),{code:u.USAGE};const a=await L(e);if(a.sha256!==t.sha256)return r.error(`--verify: ${t.file} does not match its recorded checksum (expected ${t.sha256}, got ${a.sha256}) — nothing was imported`),{code:1};r.success(`verified ${t.file} against its recorded sha256`)},Ie=async(e,t)=>{const r=await t.list();if(r.length===0)return e.logger.info(`no backups found in ${t.label}`),{code:0,entries:[]};for(const a of r)e.logger.info(`${a.id} ${a.rows.toString()} rows ${a.bytes.toString()} bytes ${a.file}`);return{code:0,entries:r}},Ue=async(e,t)=>{const{target:r}=e;if(r===void 0||r.length===0)return e.logger.error("restore requires a backup id or file path. Usage: lunora backup restore <id|file>"),{code:u.USAGE};const o=(await t.list()).find(n=>n.id===r),i=await t.materialize(o,r);if(i===void 0)return e.logger.error(`backup not found: ${r}`),{code:u.NOT_FOUND};try{if(e.verify===!0){const f=await Ne(i.path,o,e.logger);if(f!==void 0)return f}const n=await ie({cwd:e.cwd,fetchImpl:e.fetchImpl,file:i.path,logger:e.logger,prod:e.prod,token:e.token,url:e.url,yes:e.yes});return{code:n.code,entry:o,restored:n.inserted}}finally{await i.release().catch(n=>{e.logger.warn(`backup: could not clean up the downloaded snapshot (${n instanceof Error?n.message:String(n)})`)})}},_e=e=>{if(e.prod&&e.url===void 0)return e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)"),{refused:u.USAGE};if(e.restore===!0&&e.at===void 0&&e.bookmark===void 0)return e.logger.error("pitr --restore requires --at <time> or --bookmark <bookmark>"),{refused:u.USAGE};const t=A(e.url,e.logger,e.cwd);if(t===void 0)return{refused:u.USAGE};if(e.restore===!0&&Z({prod:e.prod,url:t})&&e.yes!==!0)return e.logger.error(`pitr --restore restores data in place at ${t}, which is not local. Re-run with --yes to confirm.`),{refused:u.USAGE};const{token:r}=E({cwd:e.cwd??process.cwd(),token:e.token,url:t});return r?{fetchImpl:e.adminFetch??T,requestUrl:`${t}${Se}`,token:r}:(e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{refused:u.AUTH})},xe=(e,t)=>{const r={};return e.at!==void 0&&(r.time=e.at),t&&e.bookmark!==void 0&&(r.bookmark=e.bookmark),t&&e.restart===!0&&(r.restart=!0),r},Re=async e=>{const t=_e(e);if(p(t))return{code:t.refused};const r=e.restore===!0,a=r?Ae:Ee,o=xe(e,r),i=r?"restore":"bookmark";e.logger.info(`POST ${t.requestUrl} -> pitr ${i}${e.shard===void 0?"":` (shard "${e.shard}")`}`);const n=await t.fetchImpl(t.requestUrl,{body:JSON.stringify({args:o,functionPath:a,shardKey:e.shard}),headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json"},method:"POST"});return{body:await y(n,e.logger),code:n.ok?0:k(n.status)}},Oe=(e,t)=>{if(e.bucket===void 0)return e.prefix!==void 0?(e.logger.error("--prefix applies only to an R2 destination — pass --bucket alongside it, or use --dir to point at a local directory."),{refused:u.USAGE}):we(m(t,e.dir??$e));if(e.dir!==void 0)return e.logger.error("--dir applies only to a local destination and does not apply alongside --bucket — drop one."),{refused:u.USAGE};if(e.prod===!0&&e.url===void 0)return e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)"),{refused:u.USAGE};const r=A(e.url,e.logger,e.cwd);if(r===void 0)return{refused:u.USAGE};const{token:a}=E({cwd:t,token:e.token,url:r});if(!a)return e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{refused:u.AUTH};const o=e.fetchImpl??T;return pe({context:{baseUrl:r,bucket:e.bucket==="default"?void 0:e.bucket,fetchImpl:o,token:a},logger:e.logger,prefix:e.prefix})},M=e=>{const t=[e.bucket===void 0?void 0:"--bucket",e.prefix===void 0?void 0:"--prefix",e.dir===void 0?void 0:"--dir"].filter(i=>i!==void 0);if(t.length>0)return e.logger.error(`${t.join(" / ")} ${t.length===1?"does":"do"} not apply here — retention and prune act on the store the worker itself is configured with (\`backupStore\`), not a destination you name.`),{refused:u.USAGE};if(e.prod===!0&&e.url===void 0)return e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)"),{refused:u.USAGE};const r=A(e.url,e.logger,e.cwd);if(r===void 0)return{refused:u.USAGE};const{token:a}=E({cwd:e.cwd??process.cwd(),token:e.token,url:r});if(!a)return e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{refused:u.AUTH};const o=e.adminFetch??T;return{baseUrl:r,fetchImpl:o,token:a}},K=(e,t)=>{e.logger.info(`backup retention would keep the newest ${t.keep.toString()} of ${t.eligible.toString()} under ${t.prefix} and delete ${t.wouldDelete.length.toString()}`);for(const r of t.wouldDelete)e.logger.info(` ${G(r)}`)},Pe=async e=>{const t=M(e);if(p(t))return{code:t.refused};const r=await t.fetchImpl(`${t.baseUrl}${F}`,{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(!r.ok)return await y(r,e.logger),{code:k(r.status)};const a=await r.json();return a.cron===void 0?(e.logger.info("no scheduled backup is configured (`backupCron`), so retention would delete nothing"),{code:0,preview:a}):a.keep<=0?(e.logger.info(`retention is off for cron "${a.cron}" (\`backupRetain\` unset) — every snapshot under ${a.prefix} is kept`),{code:0,preview:a}):(K(e,a),a.eligible===0&&e.logger.info(`no snapshot under ${a.prefix} was written by this cron, so retention has nothing of its own to remove`),{code:0,preview:a})},Be=(e,t)=>{e.logger.success(`deleted ${t.deleted.length.toString()} backup(s)`);for(const r of t.deleted)e.logger.info(` ${G(r)}`);t.failed.length>0&&e.logger.warn(`${t.failed.length.toString()} could not be removed — the snapshot may be gone with its manifest left behind; run again to retry`),t.ignored>0&&e.logger.info(`${t.ignored.toString()} were already gone by the time the delete ran`),t.remaining>0&&e.logger.info(`${t.remaining.toString()} more are past the window — run \`lunora backup prune\` again`)},De=async e=>{const t=M(e);if(p(t))return{code:t.refused};const r=await t.fetchImpl(`${t.baseUrl}${F}`,{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(!r.ok)return await y(r,e.logger),{code:k(r.status)};const a=await r.json();if(a.keep<=0||a.cron===void 0)return e.logger.error("backup prune needs a retention window: set `backupRetain` (and `backupCron`) on the worker. Without one there is nothing past the window to remove."),{code:u.USAGE,preview:a};if(a.wouldDelete.length===0)return e.logger.info(`nothing to prune — ${a.eligible.toString()} snapshot(s) under ${a.prefix} and retention keeps the newest ${a.keep.toString()}`),{code:0,preview:a};if(K(e,a),e.yes!==!0){const n=e.confirm??(J()?W:void 0);if(n===void 0)return e.logger.error("refusing to delete backups without confirmation — re-run with --yes (there is no undo for an object-store delete)"),{code:u.USAGE,preview:a};if(!await n(`delete ${a.wouldDelete.length.toString()} backup(s)? This cannot be undone. [y/N] `))return e.logger.info("nothing was deleted"),{code:0,preview:a}}const o=await t.fetchImpl(`${t.baseUrl}${ve}`,{body:JSON.stringify({confirm:a.wouldDelete}),headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json"},method:"POST"});if(!o.ok)return await y(o,e.logger),{code:k(o.status),preview:a};const i=await o.json();return Be(e,i),{code:i.failed.length>0?1:0,deleted:i.deleted,preview:a}},Ge=async(e,t)=>{try{if(e.subcommand==="pitr")return await Re(e);if(e.subcommand==="retention")return await Pe(e);if(e.subcommand==="prune")return await De(e);const r=Oe(e,t);return p(r)?{code:r.refused}:e.subcommand==="create"?await Te(e,r):e.subcommand==="list"?await Ie(e,r):await Ue(e,r)}catch(r){return e.logger.error(r instanceof Error?r.message:String(r)),{code:1}}},je=async e=>{const t=e.cwd??process.cwd(),r=await Ge(e,t);return{...r,data:{subcommand:e.subcommand,...r.entries===void 0?{}:{entries:r.entries},...r.entry===void 0?{}:{entry:r.entry},...r.restored===void 0?{}:{restored:r.restored},...r.preview===void 0?{}:{preview:r.preview},...r.deleted===void 0?{}:{deleted:r.deleted},...r.body===void 0?{}:{result:r.body}}}},Ce=e=>e==="create"||e==="list"||e==="pitr"||e==="prune"||e==="restore"||e==="retention",nr=ee(async({argument:e,cwd:t,format:r,logger:a,options:o})=>{const i=e[0];if(!Ce(i)){const f=`backup: unknown subcommand "${i??""}" — expected create | list | restore | retention | prune | pitr`;return a.error(f),{code:u.USAGE,error:f}}const n=await je({at:o.at,bookmark:o.bookmark,bucket:o.bucket,cwd:t,dir:o.dir,format:r,logger:a,prefix:o.prefix,prod:o.prod===!0,restart:o.restart===!0,restore:o.restore===!0,shard:o.shard,subcommand:i,tables:o.tables,target:e[1],token:o.token,url:re({cwd:t,prod:o.prod===!0,url:o.url}),verify:o.verify===!0,yes:o.yes===!0});return{code:n.code,data:n.data,error:n.error}});export{nr as execute,je as runBackupCommand};
1
+ import{existsSync as f,readFileSync as g,realpathSync as w}from"node:fs";import{join as u}from"node:path";import{DEV_VARS_FILE as m,parseDevVariableEntries as x,isPlaceholderValue as $,discoverSchemaInfo as _,inferLunoraBindings as A}from"@lunora/config";import{findWranglerFile as R,readWranglerJsonc as S,validateWranglerProject as I,UNEXPORTED_CLASS_MARKER as b,collectExportGaps as L}from"@lunora/config/cloudflare";import{i as N,m as j,c as O}from"../packem_shared/secret-key-DsMeUoEg.mjs";import{r as E,d as D}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{d as P}from"../packem_shared/command-CAXl2A1S.mjs";import{i as V}from"../packem_shared/path-containment-CgxYZggb.mjs";import{b as y,c as k,a as h}from"../packem_shared/variables-acxcvVQa.mjs";import{readServiceBindings as C}from"@lunora/codegen";const U=(t,n)=>{const e=new Set,r=a=>{for(const[c,s]of Object.entries(a??{}))typeof s=="string"&&s.trim().length>0&&e.add(c)};r(t.vars);for(const a of Object.values(t.env??{}))r(a.vars);const o=u(n,m);if(f(o))try{r(Object.fromEntries(x(g(o,"utf8")).map(a=>[a.key,a.value])))}catch{}return e},M=(t,n,e,r)=>{if(t===void 0||!e)return;const o=U(t,n),a=o.has(y),c=t.ai?.binding;!a&&(typeof c!="string"||c.length===0)&&r.push({code:"ai-binding-missing",fix:`Run \`lunora dev\` (it adds the binding), add \`"ai": { "binding": "AI" }\` to wrangler.jsonc, or set ${y} to an OpenAI-compatible proxy.`,level:"warn",message:"the project uses ctx.ai (@lunora/ai / env.AI) but wrangler.jsonc declares no `ai` binding — model calls will fail at runtime."}),o.has(k)&&r.push({code:"ai-gateway-token-unused",fix:"Make the gateway unauthenticated for ctx.ai, or remove the token. A bring-your-own AI SDK provider built with `resolveAiGateway` does send it.",level:"warn",message:`${k} is set, but ctx.ai's Workers AI binding cannot send a gateway token — it is ignored on that path.`}),!a&&!o.has(h)&&r.push({code:"ai-gateway-default",fix:`Run \`lunora ai gateway\` to create a gateway for this app and write ${h} into wrangler vars.`,level:"info",message:`no ${h} in vars or ${m} — \`<provider>/<model>\` slugs route through the account's \`default\` AI Gateway.`})},T=(t,n)=>{for(const e of C(t).services)for(const r of e.publicScopes){const o=r===""?"":` (env.${r})`;n.push({code:"service-workers-dev",fix:`Set \`"workers_dev": false\`${o} in ${e.wranglerPath} — the app's service binding is its only way in, so internal auth (HMAC) can go too.`,level:"warn",message:`service ${e.name} (${e.worker}) is bound by the app but still public on workers.dev${o}.`})}},W=t=>{const n=t.trim();if(n==="")return!0;const e=n.toLowerCase();return e.includes("replace")||e.startsWith("<")&&e.endsWith(">")},G=t=>{const n=R(t);if(n===void 0)return{parsed:void 0,path:void 0};const{parsed:e}=S(n);return{parsed:e,path:n}},F=(t,n,e,r)=>{if(e===void 0){r.push({code:"wrangler-missing",fix:"Run `lunora init` (or `lunora dev`) to scaffold and reconcile wrangler.jsonc.",level:"fail",message:"wrangler.jsonc not found."});return}if(n===void 0){r.push({code:"wrangler-unparseable",fix:`Check ${e} is valid JSONC.`,level:"fail",message:`Could not parse ${e}.`});return}const{report:o}=I({projectRoot:t});for(const s of o.errors.filter(l=>l.includes(b)))r.push({code:"wrangler-class-unexported",level:"fail",message:s});for(const s of o.warnings.filter(l=>l.includes("LUNORA_ORIGIN_URL")))r.push({code:"scheduler-origin-missing",fix:"Set LUNORA_ORIGIN_URL in wrangler vars to the worker's public URL (or `wrangler secret put LUNORA_ORIGIN_URL`).",level:"warn",message:s});const a=s=>s.includes(b)||s.includes("SHARD");for(const s of o.errors.filter(l=>!a(l)))r.push({code:"wrangler-invalid",fix:"Fix the reported wrangler.jsonc problem; `lunora verify` reports the same set.",level:"fail",message:s});for(const s of o.warnings.filter(l=>!l.includes("LUNORA_ORIGIN_URL")))r.push({code:"wrangler-advisory",level:"warn",message:s});const c=o.errors.find(s=>s.includes("SHARD"));c===void 0?r.push({code:"wrangler-shard-binding-ok",level:"pass",message:"wrangler.jsonc present with a SHARD durable-object binding."}):r.push({code:"wrangler-shard-binding-missing",fix:"Run `lunora dev` to auto-reconcile, or add the binding manually.",level:"fail",message:c})},K=(t,n)=>{f(u(t,"lunora.json"))&&n.push({code:"stale-lunora-json",fix:'Move `target` / `remote` into `lunora.config.ts` (`export default { target: "…" }`), then delete lunora.json.',level:"warn",message:"lunora.json is present but no longer read — lunora.config.* replaced it, so any `target` or `remote` in it is being ignored."})},B=(t,n)=>{t===void 0||t.limits?.cpu_ms!==void 0||n.push({code:"cpu-limit-missing",fix:'Add `"limits": { "cpu_ms": 30000 }` to wrangler.jsonc, tuned to your slowest legitimate handler.',level:"info",message:"no limits.cpu_ms is set — a runaway handler can burn CPU up to the platform default before anything stops it."})},z=(t,n)=>{const e=(t?.r2_buckets??[]).map(r=>r?.bucket_name).filter(r=>typeof r=="string"&&r.length>0);e.length!==0&&n.push({code:"r2-lifecycle-unset",fix:"wrangler r2 bucket lifecycle list <bucket> — add an abort-incomplete-multipart rule if none exists.",level:"info",message:`R2 bucket(s) ${e.join(", ")}: verify a lifecycle rule aborts incomplete multipart uploads — orphaned parts are billed but invisible in a listing.`})},H=(t,n)=>{const{error:e,info:r}=_(t,"lunora");if(e!==void 0){n.push({code:"schema-unreadable",fix:"Fix the parse error, then re-run `lunora doctor`. `lunora codegen` reports the same failure with the offending source.",level:"fail",message:`lunora/schema.ts could not be parsed, so every schema-derived check was skipped: ${e}`});return}for(const o of r?.vectorMetadata??[]){const a=j(o.kind);if(a===void 0){n.push({code:"vector-metadata-unfilterable",fix:"Filter on a string, number or boolean column, or drop it from `metadata`.",level:"warn",message:`vector index "${o.index}" declares metadata "${o.property}", whose type Vectorize cannot filter on.`});continue}n.push({code:"vector-metadata-index-required",fix:`wrangler ${O({index:o.index,property:o.property,type:a}).join(" ")}`,level:"info",message:`vector index "${o.index}" filters on metadata "${o.property}" — that needs a Vectorize metadata index (\`lunora deploy\` creates it).`})}},J=(t,n)=>{if(t===void 0)return;const e=(t.d1_databases??[]).filter(Boolean);for(const r of e){const o=typeof r.database_id=="string"?r.database_id:"";if(W(o)){const a=typeof r.binding=="string"&&r.binding.length>0?r.binding:"<unnamed>";n.push({code:"d1-placeholder-id",fix:"Run `wrangler d1 create <name>` and paste the returned database_id into wrangler.jsonc.",level:"fail",message:`D1 binding "${a}" has a placeholder database_id ("${o||"<empty>"}").`})}}},X=(t,n)=>{if(t===void 0)return;const e=(t.send_email??[]).filter(Boolean);for(const r of e){const o=typeof r.destination_address=="string"?r.destination_address:"";if(o!==""&&$(o)){const a=typeof r.name=="string"&&r.name.length>0?r.name:"send_email";n.push({code:"email-destination-placeholder",fix:"Set destination_address to a verified Cloudflare Email Routing address.",level:"warn",message:`send_email binding "${a}" has a placeholder destination_address ("${o}").`})}}},Y=(t,n)=>{const e=u(t,m);if(!f(e))return;let r;try{r=g(e,"utf8")}catch{return}const o=x(r).filter(a=>N(a.key)&&$(a.value)).map(a=>a.key);o.length>0&&n.push({code:"dev-vars-missing-secret",fix:"Run `lunora dev` to auto-generate secrets, or fill them in by hand.",level:"warn",message:`${m} has unfilled secret value(s): ${o.join(", ")}.`})},q=(t,n)=>{const{source:e}=E({cwd:t});e===void 0?n.push({code:"admin-token-missing",fix:"Set LUNORA_ADMIN_TOKEN (env or `.dev.vars`) to enable admin RPCs / studio.",level:"info",message:"LUNORA_ADMIN_TOKEN is not set."}):n.push({code:"admin-token-set",level:"pass",message:`LUNORA_ADMIN_TOKEN is set (${D(e)}).`})},Q=async(t,n)=>{try{return await A({projectRoot:t})}catch(e){n.push({code:"declared-export-unchecked",fix:"Make sure the worker entry resolves (see `lunora codegen`), then re-run.",level:"warn",message:`could not check whether declared containers/workflows/agents are re-exported by the worker entry: ${e instanceof Error?e.message:String(e)}`});return}},Z=(t,n)=>{const e=L(t),r=[...t.containers.map(o=>({...o,kind:"container"})),...t.workflows.map(o=>({...o,kind:"workflow"})),...t.agents.map(o=>({...o,kind:"agent"}))];for(const o of r.filter(a=>a.exported))n.push({code:"declared-export-ok",level:"pass",message:`${o.kind} "${o.exportName}" is exported by the worker entry.`});for(const o of e)n.push({code:"declared-export-missing",fix:`Add \`export * from "./lunora/_generated/${o.module}"\` to your worker entry (or re-run \`vis generate lunora-${o.kind}\`).`,level:"fail",message:`${o.kind} "${o.exportName}" is declared but ${o.className} is not exported by the worker entry.`})},ee=/^[\^~><= ]+/u,ne=/^(?<core>\d+\.\d+\.\d+)(?:-(?<channel>[a-z]+)\.(?<counter>\d+))?$/u,re=t=>{const n=t.replace(ee,"").trim(),e=ne.exec(n);if(!e?.groups)return;const{channel:r,core:o,counter:a}=e.groups;return{channel:r??"",core:o??"",counter:a===void 0?void 0:Number.parseInt(a,10),raw:n}},oe=(t,n)=>{const e=u(t,"package.json");if(!f(e))return;let r;try{r=JSON.parse(g(e,"utf8"))}catch{return}const o={...r.devDependencies,...r.dependencies},a=[];for(const[i,d]of Object.entries(o)){if(i!=="lunorash"&&!i.startsWith("@lunora/"))continue;const v=re(d);v&&a.push({name:i,version:v})}if(a.length<2)return;const c=i=>i.map(d=>`${d.name}@${d.version.raw}`).join(", "),s=new Set(a.map(i=>i.version.core)),l=new Set(a.map(i=>i.version.channel));if(s.size>1){n.push({code:"version-skew-cores",fix:'Run `pnpm update "@lunora/*" lunorash` (or `npm`/`yarn` equivalent) so every Lunora package moves to the same release.',level:"warn",message:`Lunora packages span ${String(s.size)} different versions: ${c(a)}.`});return}if(l.size>1){n.push({code:"version-skew-channels",fix:"Pick one channel (all stable, or all alpha/beta) and update the odd package out.",level:"warn",message:`Lunora packages mix release channels (${[...l].map(i=>i===""?"stable":i).join(" + ")}): ${c(a)}.`});return}const p=a.map(i=>i.version.counter).filter(i=>i!==void 0);if(p.length>1){const i=Math.min(...p),d=Math.max(...p);n.push({code:"version-counter-spread",level:"info",message:p.length===a.length&&i===d?`Lunora packages are all at ${[...l][0]??""}.${String(d)}.`:`Lunora pre-release counters span ${String(i)}–${String(d)}: ${c(a)}.`})}},te=[u("@lunora","cli"),"lunorash"],ae=(t,n,e)=>{if(n===void 0)return;const r=[];for(const a of te){const c=u(t,"node_modules",a);if(f(c))try{r.push(w(c))}catch{}}if(r.length===0)return;let o;try{o=w(n)}catch{return}r.some(a=>V(a,o))||e.push({code:"cli-shadowed",fix:"Run the project's own CLI: `pnpm exec lunora …` (or `npx lunora …`).",level:"warn",message:`the running lunora (${o}) is not the project's own install (${r.join(", ")}).`})},se=async t=>{const n=t.cwd??process.cwd(),e=[],{parsed:r,path:o}=G(n);F(n,r,o,e),J(r,e),X(r,e),B(r,e),z(r,e),Y(n,e),q(n,e),oe(n,e),H(n,e),K(n,e),ae(n,t.executablePath??process.argv[1],e),T(n,e);const a=await Q(n,e);a!==void 0&&Z(a,e),M(r,n,a?.usesAi===!0,e);const c={fail:0,info:0,pass:0,warn:0};for(const l of e)c[l.level]+=1;const s=c.fail>0?1:0;return{code:s,findings:e,ok:s===0,summary:c}},ie={fail:"FAIL",info:"INFO",pass:"PASS",warn:"WARN"},ce=(t,n)=>{n.info("lunora doctor — project preflight");for(const o of t.findings){const a=`[${ie[o.level]}] ${o.message}`;o.level==="fail"?n.error(a):o.level==="warn"?n.warn(a):n.info(a),o.fix!==void 0&&o.level!=="pass"&&n.info(` fix: ${o.fix}`)}const{fail:e,warn:r}=t.summary;e>0?n.error(`${String(e)} failure(s), ${String(r)} warning(s).`):r>0?n.warn(`0 failures, ${String(r)} warning(s).`):n.success("all checks passed.")},le=async t=>{const{logger:n}=t,e=await se({...t});return ce(e,n),e},ye=P(async({cwd:t,format:n,logger:e})=>{const r=await le({cwd:t,format:n,logger:e});return{code:r.code,data:{findings:r.findings,summary:r.summary}}});export{ye as execute,se as runDoctor,le as runDoctorCommand};
@@ -1,4 +1,4 @@
1
- import{V as R}from"../packem_shared/cli-BQ3AyV_K.mjs";import{d as G}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as d}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{existsSync as f,readFileSync as h,mkdirSync as J,realpathSync as W,statSync as V,writeFileSync as z,chmodSync as H,renameSync as K,unlinkSync as q}from"node:fs";import{homedir as w}from"node:os";import{findWranglerFile as X}from"@lunora/config/cloudflare";import{join as s,dirname as B,relative as Z}from"@visulima/path";import{stringify as Q}from"smol-toml";import{parse as Y,modify as ee,applyEdits as re}from"jsonc-parser";import{detectPackageManager as te,execArgsFor as ne,readLiveDevServerState as S,DEV_STATE_DIR as oe}from"@lunora/config";import{resolveAdminToken as ae}from"@lunora/config/studio-host";import{connectLocalStdio as le}from"@lunora/mcp";import{resolve as y}from"node:path";import{i as ce}from"../packem_shared/path-containment-CgxYZggb.mjs";const m=e=>({args:[...e.args],command:e.command,...e.env===void 0?{}:{env:e.env}}),b=e=>e.transport==="http"?{type:"http",url:e.url}:m(e),se=e=>e.transport==="http"?{httpUrl:e.url}:m(e),ie=e=>e.transport==="http"?{serverUrl:e.url}:m(e),de=e=>({args:["-y","mcp-remote",e],command:"npx"}),ue=e=>e.transport==="http"?de(e.url):m(e),fe=e=>e.transport==="http"?{url:e.url}:m(e),me=e=>e.transport==="http"?{enabled:!0,type:"remote",url:e.url}:{command:[e.command,...e.args],enabled:!0,type:"local",...e.env===void 0?{}:{environment:e.env}},pe=e=>e.transport==="http"?{disabled:!1,type:"streamableHttp",url:e.url}:{disabled:!1,...m(e)},ge=({home:e,platform:r})=>{if(r==="darwin")return{global:s(e,"Library","Application Support","Claude","claude_desktop_config.json")};if(r==="win32"){const t=process.env.APPDATA;return t===void 0||t===""?{}:{global:s(t,"Claude","claude_desktop_config.json")}}return r==="linux"?{global:s(e,".config","Claude","claude_desktop_config.json")}:{}},ve=(e,r)=>Q({mcp_servers:{[e]:r.transport==="http"?{url:r.url}:{args:[...r.args],command:r.command,...r.env===void 0?{}:{env:r.env}}}}),v=[{buildEntry:b,paths:({projectRoot:e})=>({project:s(e,".mcp.json")}),format:"json",id:"claude-code",key:"mcpServers",label:"Claude Code"},{buildEntry:b,paths:({home:e,projectRoot:r})=>({global:s(e,".cursor","mcp.json"),project:s(r,".cursor","mcp.json")}),format:"json",id:"cursor",key:"mcpServers",label:"Cursor"},{buildEntry:b,paths:({projectRoot:e})=>({project:s(e,".vscode","mcp.json")}),format:"json",id:"vscode",key:"servers",label:"VS Code (GitHub Copilot)"},{buildEntry:se,paths:({home:e,projectRoot:r})=>({global:s(e,".gemini","settings.json"),project:s(r,".gemini","settings.json")}),format:"json",id:"gemini",key:"mcpServers",label:"Gemini CLI"},{buildEntry:ue,paths:ge,format:"json",id:"claude-desktop",key:"mcpServers",label:"Claude Desktop"},{buildEntry:ie,paths:({home:e})=>({global:s(e,".codeium","windsurf","mcp_config.json")}),format:"json",id:"windsurf",key:"mcpServers",label:"Windsurf"},{buildEntry:me,paths:({home:e,projectRoot:r})=>({global:s(e,".config","opencode","opencode.json"),project:s(r,"opencode.json")}),format:"json",id:"opencode",key:"mcp",label:"OpenCode"},{buildEntry:pe,paths:({home:e})=>({global:s(e,".cline","mcp.json")}),format:"json",id:"cline",key:"mcpServers",label:"Cline"},{buildEntry:fe,paths:({home:e})=>({global:s(e,".config","zed","settings.json")}),format:"json",id:"zed",key:"context_servers",label:"Zed"},{paths:({home:e,projectRoot:r})=>({global:s(e,".codex","config.toml"),project:s(r,".codex","config.toml")}),format:"manual",id:"codex",label:"Codex CLI",renderSnippet:ve}],x=v.map(e=>e.id),he=e=>v.find(r=>r.id===e.toLowerCase()),M=(e,r)=>{let t=e,n;try{t=W(e),n=V(t).mode}catch{}const a=`${t}.lunora-${Math.random().toString(36).slice(2,10)}.tmp`;try{z(a,r,"utf8"),n!==void 0&&H(a,n),K(a,t)}catch(o){try{q(a)}catch{}throw o}},ye={formattingOptions:{insertSpaces:!0,tabSize:4}},k=e=>{const r=[],t=Y(e,r,{allowTrailingComma:!0});return{errors:r,value:t}},g=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),E=(e,r,t)=>{if(!g(e))return;const n=e[r];return g(n)?n[t]:void 0},L=e=>{if(!f(e.path))return"absent";let r;try{r=h(e.path,"utf8")}catch{return"invalid"}if(r.trim().length===0)return"absent";const{errors:t,value:n}=k(r);return t.length>0||!g(n)?"invalid":E(n,e.key,e.name)===void 0?"absent":"present"},be=e=>L(e)==="present",U=(e,r,t,n,a)=>{try{const o=ee(e,[t,n],a,ye);o.length>0&&M(r,re(e,o));return}catch(o){return o instanceof Error?o.message:String(o)}},Se=e=>{const{entry:r,force:t=!1,key:n,name:a,path:o}=e,l=f(o)?h(o,"utf8"):"";if(l.trim().length===0)return J(B(o),{recursive:!0}),M(o,`${JSON.stringify({[n]:{[a]:r}},void 0,4)}
1
+ import{V as R}from"../packem_shared/cli-CIDgoZP8.mjs";import{d as G}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as d}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{existsSync as f,readFileSync as h,mkdirSync as J,realpathSync as W,statSync as V,writeFileSync as z,chmodSync as H,renameSync as K,unlinkSync as q}from"node:fs";import{homedir as w}from"node:os";import{findWranglerFile as X}from"@lunora/config/cloudflare";import{join as s,dirname as B,relative as Z}from"@visulima/path";import{stringify as Q}from"smol-toml";import{parse as Y,modify as ee,applyEdits as re}from"jsonc-parser";import{detectPackageManager as te,execArgsFor as ne,readLiveDevServerState as S,DEV_STATE_DIR as oe}from"@lunora/config";import{resolveAdminToken as ae}from"@lunora/config/studio-host";import{connectLocalStdio as le}from"@lunora/mcp";import{resolve as y}from"node:path";import{i as ce}from"../packem_shared/path-containment-CgxYZggb.mjs";const m=e=>({args:[...e.args],command:e.command,...e.env===void 0?{}:{env:e.env}}),b=e=>e.transport==="http"?{type:"http",url:e.url}:m(e),se=e=>e.transport==="http"?{httpUrl:e.url}:m(e),ie=e=>e.transport==="http"?{serverUrl:e.url}:m(e),de=e=>({args:["-y","mcp-remote",e],command:"npx"}),ue=e=>e.transport==="http"?de(e.url):m(e),fe=e=>e.transport==="http"?{url:e.url}:m(e),me=e=>e.transport==="http"?{enabled:!0,type:"remote",url:e.url}:{command:[e.command,...e.args],enabled:!0,type:"local",...e.env===void 0?{}:{environment:e.env}},pe=e=>e.transport==="http"?{disabled:!1,type:"streamableHttp",url:e.url}:{disabled:!1,...m(e)},ge=({home:e,platform:r})=>{if(r==="darwin")return{global:s(e,"Library","Application Support","Claude","claude_desktop_config.json")};if(r==="win32"){const t=process.env.APPDATA;return t===void 0||t===""?{}:{global:s(t,"Claude","claude_desktop_config.json")}}return r==="linux"?{global:s(e,".config","Claude","claude_desktop_config.json")}:{}},ve=(e,r)=>Q({mcp_servers:{[e]:r.transport==="http"?{url:r.url}:{args:[...r.args],command:r.command,...r.env===void 0?{}:{env:r.env}}}}),v=[{buildEntry:b,paths:({projectRoot:e})=>({project:s(e,".mcp.json")}),format:"json",id:"claude-code",key:"mcpServers",label:"Claude Code"},{buildEntry:b,paths:({home:e,projectRoot:r})=>({global:s(e,".cursor","mcp.json"),project:s(r,".cursor","mcp.json")}),format:"json",id:"cursor",key:"mcpServers",label:"Cursor"},{buildEntry:b,paths:({projectRoot:e})=>({project:s(e,".vscode","mcp.json")}),format:"json",id:"vscode",key:"servers",label:"VS Code (GitHub Copilot)"},{buildEntry:se,paths:({home:e,projectRoot:r})=>({global:s(e,".gemini","settings.json"),project:s(r,".gemini","settings.json")}),format:"json",id:"gemini",key:"mcpServers",label:"Gemini CLI"},{buildEntry:ue,paths:ge,format:"json",id:"claude-desktop",key:"mcpServers",label:"Claude Desktop"},{buildEntry:ie,paths:({home:e})=>({global:s(e,".codeium","windsurf","mcp_config.json")}),format:"json",id:"windsurf",key:"mcpServers",label:"Windsurf"},{buildEntry:me,paths:({home:e,projectRoot:r})=>({global:s(e,".config","opencode","opencode.json"),project:s(r,"opencode.json")}),format:"json",id:"opencode",key:"mcp",label:"OpenCode"},{buildEntry:pe,paths:({home:e})=>({global:s(e,".cline","mcp.json")}),format:"json",id:"cline",key:"mcpServers",label:"Cline"},{buildEntry:fe,paths:({home:e})=>({global:s(e,".config","zed","settings.json")}),format:"json",id:"zed",key:"context_servers",label:"Zed"},{paths:({home:e,projectRoot:r})=>({global:s(e,".codex","config.toml"),project:s(r,".codex","config.toml")}),format:"manual",id:"codex",label:"Codex CLI",renderSnippet:ve}],x=v.map(e=>e.id),he=e=>v.find(r=>r.id===e.toLowerCase()),M=(e,r)=>{let t=e,n;try{t=W(e),n=V(t).mode}catch{}const a=`${t}.lunora-${Math.random().toString(36).slice(2,10)}.tmp`;try{z(a,r,"utf8"),n!==void 0&&H(a,n),K(a,t)}catch(o){try{q(a)}catch{}throw o}},ye={formattingOptions:{insertSpaces:!0,tabSize:4}},k=e=>{const r=[],t=Y(e,r,{allowTrailingComma:!0});return{errors:r,value:t}},g=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),E=(e,r,t)=>{if(!g(e))return;const n=e[r];return g(n)?n[t]:void 0},L=e=>{if(!f(e.path))return"absent";let r;try{r=h(e.path,"utf8")}catch{return"invalid"}if(r.trim().length===0)return"absent";const{errors:t,value:n}=k(r);return t.length>0||!g(n)?"invalid":E(n,e.key,e.name)===void 0?"absent":"present"},be=e=>L(e)==="present",U=(e,r,t,n,a)=>{try{const o=ee(e,[t,n],a,ye);o.length>0&&M(r,re(e,o));return}catch(o){return o instanceof Error?o.message:String(o)}},Se=e=>{const{entry:r,force:t=!1,key:n,name:a,path:o}=e,l=f(o)?h(o,"utf8"):"";if(l.trim().length===0)return J(B(o),{recursive:!0}),M(o,`${JSON.stringify({[n]:{[a]:r}},void 0,4)}
2
2
  `),{action:"created",path:o};const{errors:c,value:i}=k(l);if(c.length>0)return{action:"invalid",error:`parse error at offset ${String(c[0]?.offset??0)}`,path:o};if(!g(i))return{action:"invalid",error:"the file's root is not a JSON object",path:o};const p=i[n];if(p!==void 0&&!g(p))return{action:"invalid",error:`"${n}" is not an object`,path:o};if(E(i,n,a)!==void 0&&!t)return{action:"skipped",path:o};const $=U(l,o,n,a,r);return $===void 0?{action:"updated",path:o}:{action:"invalid",error:$,path:o}},we=e=>{const{key:r,name:t,path:n}=e;if(!f(n))return{action:"absent",path:n};let a;try{a=h(n,"utf8")}catch(i){return{action:"invalid",error:i instanceof Error?i.message:String(i),path:n}}const{errors:o,value:l}=k(a);if(o.length>0)return{action:"invalid",error:`parse error at offset ${String(o[0]?.offset??0)}`,path:n};if(E(l,r,t)===void 0)return{action:"absent",path:n};const c=U(a,n,r,t,void 0);return c===void 0?{action:"removed",path:n}:{action:"invalid",error:c,path:n}},ke=["global","project"],u=(e,r)=>{const t=Z(r,e);return t.length>0&&!t.startsWith("..")?t:e},Ee=(e,r)=>{const t=e.paths(r);return ke.flatMap(n=>{const a=t[n];return a===void 0?[]:[{client:e,path:a,scope:n}]})},$e=(e,r,t,n)=>{const a=e.paths(r),o=t==="global"?"project":"global",l=a[t]??(n?void 0:a[o]);if(l!==void 0)return{client:e,path:l,scope:a[t]===void 0?o:t}},je=e=>v.filter(r=>Object.values(r.paths(e)).some(t=>f(t))),A=(e,r,t,n)=>{if(e.length===0)return r();const a=[];for(const o of e){const l=he(o);if(l===void 0){t.error(`mcp ${n}: unknown client "${o}". Known clients: ${x.join(", ")}.`);return}a.push(l)}return a},Oe=e=>e.client.format==="json",Ce="https://lunora.sh/mcp",N="lunora-docs",D="lunora",_e=e=>f(s(e,"lunora"))&&X(e)!==void 0,xe=e=>{const{args:r,command:t}=ne(e,"lunora",["mcp","serve"]);return{args:r,command:t,transport:"stdio"}},Me=e=>({transport:"http",url:e}),Le=e=>({home:e.home,platform:e.platform,projectRoot:e.cwd}),T=(e,r,t)=>$e(e,Le(t),t.scope??r.preferredScope,t.scope!==void 0||!r.allowScopeFallback),Ue=(e,r,t)=>{const n=T(e,r,t);if(n===void 0){t.logger.warn(`${e.label}: has no ${t.scope??r.preferredScope}-scoped config — skipped "${r.name}".`);return}const{path:a}=n,o=e.buildEntry(r.spec);if(t.print===!0){const i=u(a,t.cwd);return t.force!==!0&&be({key:e.key,name:r.name,path:a})?(t.logger.info(`${e.label}: "${r.name}" already configured in ${i} — a real install would skip it (re-run with --force to replace).`),{action:"printed",path:a}):(t.logger.info(`${e.label} → ${i}
3
3
  ${JSON.stringify({[e.key]:{[r.name]:o}},void 0,4)}`),{action:"printed",path:a})}const l=Se({entry:o,force:t.force===!0,key:e.key,name:r.name,path:a}),c=u(a,t.cwd);return l.action==="invalid"?t.logger.error(`${e.label}: ${c} is not valid JSON (${l.error??"unknown error"}) — left untouched.`):l.action==="skipped"?t.logger.info(`${e.label}: "${r.name}" already configured in ${c} — re-run with --force to replace it.`):t.logger.success(`${e.label}: ${l.action==="created"?"created":"updated"} ${c} with "${r.name}".`),{action:l.action,path:a}},Ae=(e,r,t)=>{const n=T(e,r,t)?.path;if(n===void 0){t.logger.warn(`${e.label}: no known config location on ${t.platform} — skipped.`);return}return t.logger.info(`${e.label}: add this to ${u(n,t.cwd)}
4
4
 
@@ -1,7 +1,7 @@
1
- import{discoverMigrations as K,runCodegen as q}from"@lunora/codegen";import{readLinkedProject as N,execArgsFor as _,detectPackageManager as b,discoverContainerInfo as I,COMPOSED_WORKER_ENTRY as C,writeLinkedProject as Y,discoverSchemaInfo as z,DEV_VARS_FILE as p,parseDevVariableEntries as L,isMintableSecretKey as P,packageNamesFromBindings as J,inferLunoraBindings as U,requiredSecrets as X,generateSecretValue as Q,toolchainExecArgs as O,upsertDevVariableLine as Z,writeDevVariablesFileAtomically as ee,resolveDeployDriver as E,planToolchainInvocation as re,runPostCodegenHook as te}from"@lunora/config";import{findWranglerFile as W,readWranglerJsonc as ne,mergeWranglerEnvironment as ae,validateWranglerProject as oe,reconcileWranglerBindings as ie,reconcileWranglerCompatibilityDate as se,reconcileWranglerCrons as ce,describePreservedCrons as le}from"@lunora/config/cloudflare";import{Spinner as de}from"@visulima/spinner";import{r as ue,a as ge,e as me}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as fe,a as he}from"../packem_shared/deploy-target-DCWwiuAe.mjs";import{w as ve}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{d as pe}from"../packem_shared/command-CAXl2A1S.mjs";import{r as R}from"../packem_shared/wrangler-name-Dsk5K1f-.mjs";import{EXIT_CODE as h}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{containerBuildTag as ye}from"@lunora/container";import{a as we,i as ke}from"../packem_shared/docker-DpVxvYpL.mjs";import{defaultSpawner as $}from"../packem_shared/createRecordingSpawner-sS7LEN7x.mjs";import{r as F}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{p as be,H as $e,a as Se,r as De}from"../packem_shared/health-probe-Bw9JFfIy.mjs";import{readFileSync as w,writeFileSync as M,existsSync as y}from"node:fs";import{join as v}from"@visulima/path";import{Project as Ee}from"ts-morph";import{m as Re,e as Ae,i as Ce}from"../packem_shared/secret-key-DsMeUoEg.mjs";import{runMigrateDataCommand as Pe}from"../packem_shared/runMigrateGenerateCommand-Ii_WMZEA.mjs";import{c as je}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{l as xe}from"../packem_shared/wrangler-secrets-CuUdFBaA.mjs";const Te=e=>{const{cwd:r,env:a,logger:t,mintedSecretsFile:n}=e;try{const o=N(r),i=o?.workerName??R(r),s=e.url??o?.workerUrl;t.success("deploy complete"),t.info(` worker: ${i??"(see wrangler output above)"}`),a!==void 0&&t.info(` env: ${a}`),s===void 0?t.info(" url: run `lunora link --url <https://your-worker>` to record it"):t.info(` url: ${s}`),n!==void 0&&t.info(` secrets: generated value(s) recorded in ${n}`),e.logsAvailable&&t.info(" logs: lunora logs")}catch{}},Ne=async e=>{if(e.targets.length===0)return{builtTags:[],code:0};if(!(e.railpackAvailable??we)()){const t="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(t),{builtTags:[],code:1,error:t}}const r=e.spawner??$,a=[];for(const t of e.targets){const n=ye(t.exportName),o={args:["build",t.buildDir,"--name",n],command:"railpack",cwd:e.cwd},i=_(b(e.cwd),"wrangler",["containers","push",n]),s={args:i.args,command:i.command,cwd:e.cwd};e.logger.info(`railpack: building "${t.exportName}" → ${n} from ${t.buildDir}`);const c=await r(o);if(c.code!==0){const d=`railpack build failed for container "${t.exportName}" (${t.buildDir})`;return e.logger.error(d),{builtTags:a,code:c.code,error:d}}e.logger.info(`railpack: pushing ${n} to the Cloudflare Registry`);const l=await r(s);if(l.code!==0){const d=`wrangler containers push failed for "${t.exportName}" (${n})`;return e.logger.error(d),{builtTags:a,code:l.code,error:d}}a.push(n)}return{builtTags:a,code:0}},_e=e=>{const r=W(e),a=r===void 0?void 0:w(r,"utf8");return()=>{r!==void 0&&a!==void 0&&M(r,a,"utf8")}},B="<replace-with-d1-create-id>",j=e=>Array.isArray(e)?e.filter(r=>r!=null):void 0,A=(e,r)=>{const a=W(e);if(!a)return;const{parsed:t}=ne(a);if(t===void 0)return;const{error:n,merged:o}=ae(t,r),i=n===void 0?o:t,{containers:s,d1_databases:c,vars:l}=i;return{containers:j(s),d1_databases:j(c),vars:typeof l=="object"&&l!==null&&!Array.isArray(l)?l:void 0}},Ie=/^127(?:\.\d{1,3}){3}$/,Le=e=>{try{const{hostname:r}=new URL(e);return r==="localhost"||Ie.test(r)||r==="::1"||r==="[::1]"}catch{return!1}},Ue=e=>e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.includes("Dockerfile"),Oe=(e,r,a,t="deploy",n)=>{const o=(A(e,n)?.containers??[]).filter(s=>typeof s?.image=="string"&&Ue(s.image));if(o.length===0||a())return;const i=`${t} blocked: wrangler.jsonc declares ${String(o.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(i),i},V=e=>y(v(e,C))?C:void 0,We=(e,r,a="deploy")=>{for(const t of I(e,"lunora").containers){const n=t.schedulingPolicy===void 0?t.image:void 0,i=[...n?.kind==="dockerfile"?[{field:"image",path:n.dockerfilePath}]:[],...Object.entries(t.schedulingPolicy==="durable_object"?t.images??{}:{}).flatMap(([s,c])=>c.kind==="dockerfile"?[{field:`images["${s}"]`,path:c.dockerfilePath}]:[])].find(s=>!y(v(e,s.path)));if(i!==void 0){const s=`${a} blocked: container "${t.exportName}" references a Dockerfile at "${i.path}" that does not exist. Create it or fix the \`${i.field}\` path in lunora/containers.ts.`;return r.error(s),s}if(n?.kind==="build"&&!y(v(e,n.buildDir))){const s=`${a} 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(s),s}}},Fe=(e,r)=>(A(e,r)?.d1_databases??[]).find(a=>a.database_id===B)?.binding,Me=e=>{if(!e.migrate||e.dryRun||e.preview)return;if(e.migrateUrl===void 0){const a="--migrate requires --migrate-url <https://your-worker> — the deploy target URL is only known after wrangler runs, and this gate runs before it; refusing to default to localhost";return e.logger.error(a),a}if(e.migrateYes!==!0){const a="--migrate runs production data migrations after deploy. Re-run with --migrate-yes to confirm.";return e.logger.error(a),a}const r=e.migrateToken??process.env.LUNORA_ADMIN_TOKEN;if(r===void 0||r===""){const a="admin token required for --migrate — pass --migrate-token or set LUNORA_ADMIN_TOKEN";return e.logger.error(a),a}},Be=(e,r,a="deploy",t)=>{const n=Fe(e,t);if(n===void 0)return;const o=`${a} blocked: the "${n}" D1 binding has a placeholder database_id ("${B}"). 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(o),o},Ve=(e,r,a="deploy",t)=>{const n=A(e,t)?.vars;if(!n)return;const o=Object.entries(n).filter(([,s])=>typeof s=="string"&&Le(s)).map(([s])=>s).toSorted((s,c)=>s.localeCompare(c));if(o.length===0)return;const i=`${a} blocked: ${o.join(", ")} in wrangler.jsonc point at localhost. A deployed Worker can't reach a loopback address, so this silently breaks scheduled-job dispatch, reverse cross-shard relations, and 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(i),i},He=(e,r,a)=>{const t=Be(e,r.logger,a,r.env);if(t!==void 0)return{code:h.USAGE,error:t};const n=Ve(e,r.logger,a,r.env);if(n!==void 0)return{code:h.USAGE,error:n};const o=We(e,r.logger,a);if(o!==void 0)return{code:h.USAGE,error:o};const i=Oe(e,r.logger,r.dockerAvailable??ke,a,r.env);return i===void 0?void 0:{code:h.MISSING_DEPENDENCY,error:i}},Ge=/https?:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/u,Ke=/https:\/\/[^\s"'<>]+/u,qe=e=>{if(e===void 0)return;const r=Ge.exec(e);return r?r[0]:Ke.exec(e)?.[0]},x=e=>e===void 0?"":` (--env ${e})`,Ye=({cwd:e,env:r,logger:a,now:t,url:n})=>{if(n!==void 0)try{const o=N(e);if(o!==void 0){if(o.workerUrl===n&&o.env===r)return;a.warn(`link: .lunora/project.json records ${o.workerUrl??"(no url)"}${x(o.env)}, but this deploy published ${n}${x(r)}. Keeping the recorded value — run \`lunora link --url ${n}${r===void 0?"":` --env ${r}`}\` to update it.`);return}const i=(t??(()=>new Date().toISOString()))();Y(e,{env:r,linkedAt:i,workerName:R(e),workerUrl:n}),a.success(`link: recorded ${n} in .lunora/project.json (run \`lunora link\` to change)`)}catch{}},ze=async(e,r)=>{const a=new Ee({skipAddingFilesFromTsConfig:!0}),t=v(r,"lunora");let n;try{n=K(a,t)}catch(o){const i=o instanceof Error?o.message:String(o);return e.logger.warn(`--migrate: could not discover migrations (${i}); skipping`),0}if(n.length===0)return e.logger.info("--migrate: no data migrations declared in lunora/"),0;e.logger.info(`--migrate: running ${String(n.length)} migration(s) against deployed worker`);for(const o of n){e.logger.info(`--migrate: up "${o.id}" (table "${o.table}")`);const i={cwd:r,fetchImpl:e.fetchImpl,id:o.id,logger:e.logger,prod:!0,subcommand:"up",token:e.migrateToken,url:e.migrateUrl,yes:e.migrateYes===!0},s=await Pe(i);if(s.code!==0)return e.logger.error(`--migrate: migration "${o.id}" failed — see output above`),s.code;e.logger.success(`--migrate: "${o.id}" applied`)}return 0},Je=async(e,r)=>{const{info:a}=z(r,"lunora"),t=a?.vectorMetadata??[];if(t.length===0)return;const n=[];for(const s of t){const c=Re(s.kind);if(c===void 0){e.logger.warn(`vector index "${s.index}" declares metadata "${s.property}", whose column type cannot be filtered on in Vectorize — it is stored with each vector but no filter will match it.`);continue}n.push({index:s.index,property:s.property,type:c})}if(n.length===0)return;const i=(await Ae({cwd:r,entries:n,exec:_(b(r),"wrangler",[]),logger:e.logger,spawner:e.spawner??$})).filter(s=>s.status!=="failed").length;i>0&&e.logger.success(`vectorize metadata indexes ready: ${String(i)}/${String(n.length)}`)},T=5,Xe=2e3,Qe=async(e,r,a)=>{if(e.healthCheck!==!0)return;const t=a??F({cwd:r,env:e.env});if(t===void 0){const o="--health-check: the deploy succeeded, but no URL to probe could be resolved — wrangler's output carried none and this checkout has no link for this environment. Run `lunora link --url <https://your-worker>` and re-deploy, or drop --health-check.";return e.logger.error(o),{error:o,ok:!1,url:""}}const n=await be({attempts:T,baseUrl:t,delayMs:Xe,fetchImpl:e.healthFetch,paths:[$e,Se],sleep:e.healthSleep});return n.error===void 0?(e.logger.success(`health check ok (${n.url})`),{ok:!0,url:n.url}):(e.logger.error(`--health-check: the deploy succeeded, but the new version did not answer after ${String(T)} attempt(s) — ${n.error}`),{error:n.error,ok:!1,url:n.url})},Ze=async(e,r,a,t,n,o)=>{await Je(e,r);const i=e.migrate?await ze(e,r):0;return i===0&&n?.(),{code:i,descriptor:a,mintedSecretsFile:o,validation:t}},er=async({cwd:e,descriptor:r,mintedSecretsFile:a,options:t,reblessSchemaBaseline:n,stdout:o,validation:i})=>{const s={deployedAt:new Date().toISOString(),dryRun:t.dryRun===!0,env:t.env,preview:t.preview===!0,url:t.dryRun===!0?void 0:qe(o),workerName:R(e)};if(t.dryRun===!0||t.preview===!0)return t.healthCheck===!0&&t.logger.warn(`--health-check skipped: ${t.dryRun===!0?"a dry run publishes nothing":"a preview version serves no live traffic"}`),{code:0,deployment:s,descriptor:r,mintedSecretsFile:a,validation:i};t.temporary!==!0&&Ye({cwd:e,env:t.env,logger:t.logger,url:s.url});const c=await Qe(t,e,s.url);return c?.error!==void 0?{code:h.UNAVAILABLE,deployment:s,descriptor:r,healthCheck:c,mintedSecretsFile:a,validation:i}:{...await Ze(t,e,r,i,n,a),deployment:s,healthCheck:c}},rr=(e,r,a)=>{const t=v(e,p);if(!y(t))return;let n;try{n=L(w(t,"utf8")).length}catch{return}if(n===0)return;const o=a.toolchain?.secretPut!==void 0;r.warn(o?`Note: \`lunora deploy\` does not push secrets. ${p} has ${String(n)} key(s); if you changed them, run \`lunora env push --yes\` to update the deployed secrets.`:`Note: ${a.name} deploys read no secrets. ${p} has ${String(n)} key(s) that only the dev server sees; put the values the deployed worker needs in wrangler \`vars\`.`)},tr=async e=>{let r=[];try{r=J(await U({projectRoot:e}))}catch{}const a=X(r).map(n=>n.key);let t=[];try{const n=v(e,p);y(n)&&(t=L(w(n,"utf8")).map(o=>o.key).filter(o=>Ce(o)))}catch{}return[...new Set([...a,...t])]},nr=async(e,r,a,t)=>{const{logger:n}=r,o=r.spawner??$,i=b(e),s=r.env===void 0?"":` --env ${r.env}`,c=t.toolchain?.secretPut;if(c===void 0)return n.error(`deploy target "${t.id}" has no secret store; cannot push secrets`),{minted:[],ok:!1};const l=[];for(const d of a){const m=Q(),u=c({environment:r.env,key:d,temporary:r.temporary}),g=O(i,u),f=await o({args:g.args,command:g.command,cwd:e,input:m});if(f.code!==0)return n.error(`failed to push secret ${d} (exit ${String(f.code)}); set it manually with \`wrangler secret put ${d}${s}\`.`),{minted:l,ok:!1};l.push({key:d,value:m}),n.success(`generated + pushed ${d}`)}return{minted:l,ok:!0}},ar=/^[\w-]+$/u,S=[".dev.vars",".dev.vars.*","!.dev.vars.example"],or=/\r?\n/u,ir=(e,r)=>{const a=v(e,".gitignore");try{const t=y(a)?w(a,"utf8"):"",n=new Set(t.split(or).map(c=>c.trim())),o=S.filter(c=>!n.has(c));if(o.length===0)return;const i=o.some(c=>!c.startsWith("!"))?[...o.filter(c=>!c.startsWith("!")),...S.filter(c=>c.startsWith("!"))]:o,s=t.length>0&&!t.endsWith(`
1
+ import{join as Y,dirname as z}from"node:path";import{discoverMigrations as J,readServiceBindings as X,runCodegen as Q}from"@lunora/codegen";import{readLinkedProject as N,execArgsFor as I,detectPackageManager as b,discoverContainerInfo as L,COMPOSED_WORKER_ENTRY as C,writeLinkedProject as Z,discoverSchemaInfo as ee,DEV_VARS_FILE as w,parseDevVariableEntries as U,isMintableSecretKey as P,packageNamesFromBindings as re,inferLunoraBindings as F,requiredSecrets as te,generateSecretValue as ne,toolchainExecArgs as E,upsertDevVariableLine as ae,writeDevVariablesFileAtomically as oe,resolveDeployDriver as R,planToolchainInvocation as O,runPostCodegenHook as ie}from"@lunora/config";import{findWranglerFile as W,readWranglerJsonc as se,mergeWranglerEnvironment as ce,validateWranglerProject as le,reconcileWranglerBindings as de,reconcileWranglerCompatibilityDate as ue,reconcileWranglerCrons as ge,describePreservedCrons as me}from"@lunora/config/cloudflare";import{Spinner as fe}from"@visulima/spinner";import{r as he,a as ve,e as pe}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as ye,a as we}from"../packem_shared/deploy-target-DCWwiuAe.mjs";import{w as ke}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{d as be}from"../packem_shared/command-CAXl2A1S.mjs";import{r as A}from"../packem_shared/wrangler-name-Dsk5K1f-.mjs";import{EXIT_CODE as h}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{containerBuildTag as $e}from"@lunora/container";import{a as Se,i as De}from"../packem_shared/docker-DpVxvYpL.mjs";import{defaultSpawner as $}from"../packem_shared/createRecordingSpawner-sS7LEN7x.mjs";import{r as M}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{p as Ee,H as Re,a as Ae,r as je}from"../packem_shared/health-probe-Bw9JFfIy.mjs";import{existsSync as p,readFileSync as k,writeFileSync as B}from"node:fs";import{join as y}from"@visulima/path";import{Project as Ce}from"ts-morph";import{m as Pe,e as xe,i as Te}from"../packem_shared/secret-key-DsMeUoEg.mjs";import{runMigrateDataCommand as _e}from"../packem_shared/runMigrateGenerateCommand-Ii_WMZEA.mjs";import{c as Ne}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{l as Ie}from"../packem_shared/wrangler-secrets-CuUdFBaA.mjs";const Le=e=>{const{cwd:r,env:a,logger:t,mintedSecretsFile:n}=e;try{const o=N(r),i=o?.workerName??A(r),s=e.url??o?.workerUrl;t.success("deploy complete"),t.info(` worker: ${i??"(see wrangler output above)"}`),a!==void 0&&t.info(` env: ${a}`),s===void 0?t.info(" url: run `lunora link --url <https://your-worker>` to record it"):t.info(` url: ${s}`),n!==void 0&&t.info(` secrets: generated value(s) recorded in ${n}`),e.logsAvailable&&t.info(" logs: lunora logs")}catch{}},Ue=async e=>{if(e.targets.length===0)return{builtTags:[],code:0};if(!(e.railpackAvailable??Se)()){const t="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(t),{builtTags:[],code:1,error:t}}const r=e.spawner??$,a=[];for(const t of e.targets){const n=$e(t.exportName),o={args:["build",t.buildDir,"--name",n],command:"railpack",cwd:e.cwd},i=I(b(e.cwd),"wrangler",["containers","push",n]),s={args:i.args,command:i.command,cwd:e.cwd};e.logger.info(`railpack: building "${t.exportName}" → ${n} from ${t.buildDir}`);const c=await r(o);if(c.code!==0){const l=`railpack build failed for container "${t.exportName}" (${t.buildDir})`;return e.logger.error(l),{builtTags:a,code:c.code,error:l}}e.logger.info(`railpack: pushing ${n} to the Cloudflare Registry`);const d=await r(s);if(d.code!==0){const l=`wrangler containers push failed for "${t.exportName}" (${n})`;return e.logger.error(l),{builtTags:a,code:d.code,error:l}}a.push(n)}return{builtTags:a,code:0}},Fe=e=>{const a=[W(e),Y(e,"package.json")].filter(t=>t!==void 0&&p(t)).map(t=>[t,k(t,"utf8")]);return()=>{for(const[t,n]of a)k(t,"utf8")!==n&&B(t,n,"utf8")}},V="<replace-with-d1-create-id>",x=e=>Array.isArray(e)?e.filter(r=>r!=null):void 0,j=(e,r)=>{const a=W(e);if(!a)return;const{parsed:t}=se(a);if(t===void 0)return;const{error:n,merged:o}=ce(t,r),i=n===void 0?o:t,{containers:s,d1_databases:c,vars:d}=i;return{containers:x(s),d1_databases:x(c),vars:typeof d=="object"&&d!==null&&!Array.isArray(d)?d:void 0}},Oe=/^127(?:\.\d{1,3}){3}$/,We=e=>{try{const{hostname:r}=new URL(e);return r==="localhost"||Oe.test(r)||r==="::1"||r==="[::1]"}catch{return!1}},Me=e=>e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.includes("Dockerfile"),Be=(e,r,a,t="deploy",n)=>{const o=(j(e,n)?.containers??[]).filter(s=>typeof s?.image=="string"&&Me(s.image));if(o.length===0||a())return;const i=`${t} blocked: wrangler.jsonc declares ${String(o.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(i),i},H=e=>p(y(e,C))?C:void 0,Ve=(e,r,a="deploy")=>{for(const t of L(e,"lunora").containers){const n=t.schedulingPolicy===void 0?t.image:void 0,i=[...n?.kind==="dockerfile"?[{field:"image",path:n.dockerfilePath}]:[],...Object.entries(t.schedulingPolicy==="durable_object"?t.images??{}:{}).flatMap(([s,c])=>c.kind==="dockerfile"?[{field:`images["${s}"]`,path:c.dockerfilePath}]:[])].find(s=>!p(y(e,s.path)));if(i!==void 0){const s=`${a} blocked: container "${t.exportName}" references a Dockerfile at "${i.path}" that does not exist. Create it or fix the \`${i.field}\` path in lunora/containers.ts.`;return r.error(s),s}if(n?.kind==="build"&&!p(y(e,n.buildDir))){const s=`${a} 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(s),s}}},He=(e,r)=>(j(e,r)?.d1_databases??[]).find(a=>a.database_id===V)?.binding,Ge=e=>{if(!e.migrate||e.dryRun||e.preview)return;if(e.migrateUrl===void 0){const a="--migrate requires --migrate-url <https://your-worker> — the deploy target URL is only known after wrangler runs, and this gate runs before it; refusing to default to localhost";return e.logger.error(a),a}if(e.migrateYes!==!0){const a="--migrate runs production data migrations after deploy. Re-run with --migrate-yes to confirm.";return e.logger.error(a),a}const r=e.migrateToken??process.env.LUNORA_ADMIN_TOKEN;if(r===void 0||r===""){const a="admin token required for --migrate — pass --migrate-token or set LUNORA_ADMIN_TOKEN";return e.logger.error(a),a}},Ke=(e,r,a="deploy",t)=>{const n=He(e,t);if(n===void 0)return;const o=`${a} blocked: the "${n}" D1 binding has a placeholder database_id ("${V}"). 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(o),o},qe=(e,r,a="deploy",t)=>{const n=j(e,t)?.vars;if(!n)return;const o=Object.entries(n).filter(([,s])=>typeof s=="string"&&We(s)).map(([s])=>s).toSorted((s,c)=>s.localeCompare(c));if(o.length===0)return;const i=`${a} blocked: ${o.join(", ")} in wrangler.jsonc point at localhost. A deployed Worker can't reach a loopback address, so this silently breaks scheduled-job dispatch, reverse cross-shard relations, and 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(i),i},Ye=(e,r,a)=>{const t=Ke(e,r.logger,a,r.env);if(t!==void 0)return{code:h.USAGE,error:t};const n=qe(e,r.logger,a,r.env);if(n!==void 0)return{code:h.USAGE,error:n};const o=Ve(e,r.logger,a);if(o!==void 0)return{code:h.USAGE,error:o};const i=Be(e,r.logger,r.dockerAvailable??De,a,r.env);return i===void 0?void 0:{code:h.MISSING_DEPENDENCY,error:i}},ze=/https?:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/u,Je=/https:\/\/[^\s"'<>]+/u,Xe=e=>{if(e===void 0)return;const r=ze.exec(e);return r?r[0]:Je.exec(e)?.[0]},T=e=>e===void 0?"":` (--env ${e})`,Qe=({cwd:e,env:r,logger:a,now:t,url:n})=>{if(n!==void 0)try{const o=N(e);if(o!==void 0){if(o.workerUrl===n&&o.env===r)return;a.warn(`link: .lunora/project.json records ${o.workerUrl??"(no url)"}${T(o.env)}, but this deploy published ${n}${T(r)}. Keeping the recorded value — run \`lunora link --url ${n}${r===void 0?"":` --env ${r}`}\` to update it.`);return}const i=(t??(()=>new Date().toISOString()))();Z(e,{env:r,linkedAt:i,workerName:A(e),workerUrl:n}),a.success(`link: recorded ${n} in .lunora/project.json (run \`lunora link\` to change)`)}catch{}},Ze=async(e,r)=>{const a=new Ce({skipAddingFilesFromTsConfig:!0}),t=y(r,"lunora");let n;try{n=J(a,t)}catch(o){const i=o instanceof Error?o.message:String(o);return e.logger.warn(`--migrate: could not discover migrations (${i}); skipping`),0}if(n.length===0)return e.logger.info("--migrate: no data migrations declared in lunora/"),0;e.logger.info(`--migrate: running ${String(n.length)} migration(s) against deployed worker`);for(const o of n){e.logger.info(`--migrate: up "${o.id}" (table "${o.table}")`);const i={cwd:r,fetchImpl:e.fetchImpl,id:o.id,logger:e.logger,prod:!0,subcommand:"up",token:e.migrateToken,url:e.migrateUrl,yes:e.migrateYes===!0},s=await _e(i);if(s.code!==0)return e.logger.error(`--migrate: migration "${o.id}" failed — see output above`),s.code;e.logger.success(`--migrate: "${o.id}" applied`)}return 0},er=async(e,r)=>{const{info:a}=ee(r,"lunora"),t=a?.vectorMetadata??[];if(t.length===0)return;const n=[];for(const s of t){const c=Pe(s.kind);if(c===void 0){e.logger.warn(`vector index "${s.index}" declares metadata "${s.property}", whose column type cannot be filtered on in Vectorize — it is stored with each vector but no filter will match it.`);continue}n.push({index:s.index,property:s.property,type:c})}if(n.length===0)return;const i=(await xe({cwd:r,entries:n,exec:I(b(r),"wrangler",[]),logger:e.logger,spawner:e.spawner??$})).filter(s=>s.status!=="failed").length;i>0&&e.logger.success(`vectorize metadata indexes ready: ${String(i)}/${String(n.length)}`)},_=5,rr=2e3,tr=async(e,r,a)=>{if(e.healthCheck!==!0)return;const t=a??M({cwd:r,env:e.env});if(t===void 0){const o="--health-check: the deploy succeeded, but no URL to probe could be resolved — wrangler's output carried none and this checkout has no link for this environment. Run `lunora link --url <https://your-worker>` and re-deploy, or drop --health-check.";return e.logger.error(o),{error:o,ok:!1,url:""}}const n=await Ee({attempts:_,baseUrl:t,delayMs:rr,fetchImpl:e.healthFetch,paths:[Re,Ae],sleep:e.healthSleep});return n.error===void 0?(e.logger.success(`health check ok (${n.url})`),{ok:!0,url:n.url}):(e.logger.error(`--health-check: the deploy succeeded, but the new version did not answer after ${String(_)} attempt(s) — ${n.error}`),{error:n.error,ok:!1,url:n.url})},nr=async(e,r,a,t,n,o)=>{await er(e,r);const i=e.migrate?await Ze(e,r):0;return i===0&&n?.(),{code:i,descriptor:a,mintedSecretsFile:o,validation:t}},ar=async({cwd:e,descriptor:r,mintedSecretsFile:a,options:t,reblessSchemaBaseline:n,stdout:o,validation:i})=>{const s={deployedAt:new Date().toISOString(),dryRun:t.dryRun===!0,env:t.env,preview:t.preview===!0,url:t.dryRun===!0?void 0:Xe(o),workerName:A(e)};if(t.dryRun===!0||t.preview===!0)return t.healthCheck===!0&&t.logger.warn(`--health-check skipped: ${t.dryRun===!0?"a dry run publishes nothing":"a preview version serves no live traffic"}`),{code:0,deployment:s,descriptor:r,mintedSecretsFile:a,validation:i};t.temporary!==!0&&Qe({cwd:e,env:t.env,logger:t.logger,url:s.url});const c=await tr(t,e,s.url);return c?.error!==void 0?{code:h.UNAVAILABLE,deployment:s,descriptor:r,healthCheck:c,mintedSecretsFile:a,validation:i}:{...await nr(t,e,r,i,n,a),deployment:s,healthCheck:c}},or=(e,r,a)=>{const t=y(e,w);if(!p(t))return;let n;try{n=U(k(t,"utf8")).length}catch{return}if(n===0)return;const o=a.toolchain?.secretPut!==void 0;r.warn(o?`Note: \`lunora deploy\` does not push secrets. ${w} has ${String(n)} key(s); if you changed them, run \`lunora env push --yes\` to update the deployed secrets.`:`Note: ${a.name} deploys read no secrets. ${w} has ${String(n)} key(s) that only the dev server sees; put the values the deployed worker needs in wrangler \`vars\`.`)},ir=async e=>{let r=[];try{r=re(await F({projectRoot:e}))}catch{}const a=te(r).map(n=>n.key);let t=[];try{const n=y(e,w);p(n)&&(t=U(k(n,"utf8")).map(o=>o.key).filter(o=>Te(o)))}catch{}return[...new Set([...a,...t])]},sr=async(e,r,a,t)=>{const{logger:n}=r,o=r.spawner??$,i=b(e),s=r.env===void 0?"":` --env ${r.env}`,c=t.toolchain?.secretPut;if(c===void 0)return n.error(`deploy target "${t.id}" has no secret store; cannot push secrets`),{minted:[],ok:!1};const d=[];for(const l of a){const m=ne(),u=c({environment:r.env,key:l,temporary:r.temporary}),g=E(i,u),f=await o({args:g.args,command:g.command,cwd:e,input:m});if(f.code!==0)return n.error(`failed to push secret ${l} (exit ${String(f.code)}); set it manually with \`wrangler secret put ${l}${s}\`.`),{minted:d,ok:!1};d.push({key:l,value:m}),n.success(`generated + pushed ${l}`)}return{minted:d,ok:!0}},cr=/^[\w-]+$/u,S=[".dev.vars",".dev.vars.*","!.dev.vars.example"],lr=/\r?\n/u,dr=(e,r)=>{const a=y(e,".gitignore");try{const t=p(a)?k(a,"utf8"):"",n=new Set(t.split(lr).map(c=>c.trim())),o=S.filter(c=>!n.has(c));if(o.length===0)return;const i=o.some(c=>!c.startsWith("!"))?[...o.filter(c=>!c.startsWith("!")),...S.filter(c=>c.startsWith("!"))]:o,s=t.length>0&&!t.endsWith(`
2
2
  `)?`
3
- `:"";M(a,`${t}${s}
3
+ `:"";B(a,`${t}${s}
4
4
  # Lunora — never commit a minted secret
5
5
  ${i.join(`
6
6
  `)}
7
- `,"utf8"),r.info(`.gitignore: added ${o.join(", ")} so the recorded secret cannot be committed`)}catch(t){r.warn(`could not update .gitignore (${t instanceof Error?t.message:String(t)}) — add \`${S.join("` and `")}\` by hand before committing.`)}},sr=(e,r,a)=>{if(a.length===0)return;const t=a.map(s=>s.key).join(", ");if(r.env!==void 0&&!ar.test(r.env)){r.logger.warn(`${t}: minted and pushed for --env ${r.env}, but "${r.env}" isn't a safe filename fragment — the value could not be recorded. Capture it manually if you need it again.`);return}const n=r.env===void 0?p:`${p}.${r.env}`;ir(e,r.logger);const o=v(e,n);let i=y(o)?w(o,"utf8"):"";for(const s of a)i=Z(i,s.key,s.value);return ee(o,i),r.logger.success(r.env===void 0?`${t}: value(s) recorded in ${n}`:`${t}: value(s) recorded in ${n} (kept separate from ${p} so \`lunora dev\` and a plain \`lunora env push\` don't inherit the --env ${r.env} value)`),n},cr=async(e,r,a,t)=>{if(r.dryRun===!0||r.preview===!0)return{};const{logger:n}=r,o=r.env===void 0?"":` --env ${r.env}`;let i;try{i=await(r.secretLister??xe)({cwd:e,env:r.env,temporary:r.temporary})}catch{return{}}if(!i.ok)return{};const s=new Set(i.names),l=(await tr(e)).filter(u=>!s.has(u));if(l.length===0)return{};if(!a)return{error:`missing required secret(s) on the deploy target: ${l.join(", ")}. Set them with \`wrangler secret put <KEY>${o}\` (or \`lunora env generate --set\` then \`lunora env push --yes${o}\`), then re-deploy.`};for(const u of l.filter(g=>!P(g)))n.warn(`required secret ${u} is not set on the target — set it with: wrangler secret put ${u}${o}`);const d=l.filter(u=>P(u));if(d.length===0)return{};if(await(r.secretConfirm??je())(`${String(d.length)} required secret(s) not set on the target (${d.join(", ")}). Generate strong values and push them now?`)){const{minted:u,ok:g}=await nr(e,r,d,t),f=sr(e,r,u);return g?{mintedSecretsFile:f}:{error:"failed to push required secret(s) — set them manually and re-deploy",mintedSecretsFile:f}}return n.warn(`${String(d.length)} required secret(s) not set on the target: ${d.join(", ")}. Generate + push with \`lunora env generate --set\` then \`lunora env push --yes${o}\`.`),{}},H=e=>e.format==="json"?!1:e.interactive!==void 0?e.interactive:process.stdout.isTTY&&!process.env.CI,lr=async(e,r)=>{if(r.dryRun===!0)return;const a=I(e,"lunora").containers.flatMap(n=>n.schedulingPolicy===void 0&&n.image.kind==="build"?[{buildDir:n.image.buildDir,exportName:n.exportName}]:[]);if(a.length===0)return;const t=await Ne({cwd:e,logger:r.logger,railpackAvailable:r.railpackAvailable,spawner:r.spawner,targets:a});return t.code===0?void 0:t.error??"railpack build failed"},dr=(e,r,a)=>{if(a!==void 0)try{const t=ce(e,a);t.changed&&r.success(`synced ${String(a.length)} cron trigger(s) → ${t.wranglerPath??"wrangler.jsonc"}`);for(const o of t.warnings)r.warn(o);const n=le(t.preserved);n!==void 0&&r.info(n)}catch(t){const n=t instanceof Error?t.message:String(t);r.warn(`cron trigger sync skipped: ${n}`)}},ur=async(e,r,a,t,n)=>{try{E(t);const o=await U({projectRoot:e}),i=ie(e,o,n),s=i.wranglerPath??"wrangler.jsonc";i.added.length>0&&r.success(`provisioned bindings: ${i.added.join(", ")} → ${s}`),i.updated.length>0&&r.success(`updated bindings: ${i.updated.join(", ")} → ${s}`);for(const c of i.warnings)r.warn(c)}catch(o){const i=o instanceof Error?o.message:String(o);r.warn(`binding inference skipped: ${i}`)}try{const o=se(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}`)}dr(e,r,a)},gr=async(e,r,a,t,n,o,i,s)=>{let c;r?(c=new de({name:"dots"}),c.start("running codegen")):a.info("running codegen");try{const l=q({apiSpec:t,projectRoot:e,target:n});c?.succeed("codegen complete"),c||a.success("codegen complete");const d=ge(l.platformDiagnostics,a);if(d.errors.length>0)return{error:d.errors.join("; ")};const{errorAdvisories:m,names:u,shouldBlock:g}=me(l.advisories,s);if(g){const k=`${m.length.toString()} ERROR-level ${m.length===1?"advisory":"advisories"} (${u.join(", ")}). Pass --no-strict-advisories to downgrade this to a warning and continue.`;return a.error(k),{error:k}}const f=await te({cwd:e,logger:a,spawner:o,stdoutToStderr:i});return f.error!==void 0?{error:f.error}:{result:l}}catch(l){c?.failed("codegen failed");const d=l instanceof Error?l.message:String(l);return a.error(`codegen failed: ${d}`),{error:`codegen failed: ${d}`}}},mr=(e,r)=>({dryRun:r.dryRun,entry:V(e),environment:r.env,outDir:r.outDir,preview:r.preview,temporary:r.temporary}),G=(e,r,a)=>{const{toolchain:t}=a;if(t===void 0)throw new Error(`deploy target "${a.id}" has no command-line toolchain`);const n=mr(e,r);return re(a,e,"deploy",o=>t.deploy({...n,configPath:o}))},fr=(e,r,a)=>{const t=G(e,r,a),n=V(e);return 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}`),t.commit(),t.projection!==void 0&&t.projection.dropped.length>0&&r.logger.warn(`${a.name} ignores these wrangler keys, so they were left out of ${t.projection.configPath}: ${t.projection.dropped.join(", ")}`),t.command},D=(e,r)=>({code:h.USAGE,descriptor:void 0,error:e,validation:{problems:[],wranglerPath:void 0},...r}),hr=(e,r)=>{for(const a of e.report?.warnings??[])r.warn(`wrangler.jsonc: ${a}`);if(e.problems.length===0)return!1;r.error("wrangler.jsonc validation failed:");for(const a of e.problems)r.error(` - ${a}`);return!0},vr=(e,r,a)=>{const t=r.format==="json",n=r.dryRun!==!0,o=fr(e,r,a),i=O(b(e),o);return{args:i.args,captureStdout:n&&!t,captureStdoutSilently:n&&t,command:i.command,cwd:e,stdoutToStderr:t&&!n}},pr=async(e,r)=>{const a=e.cwd??process.cwd(),t=H(e),n=ue(e),o={problems:[],wranglerPath:void 0},i=he(a,e.target);if(i.target===void 0){const u=i.error??"unknown deploy target";return e.logger.error(u),{error:u,validation:o}}const{target:s}=i;try{G(a,e,E(s))}catch(u){const g=u instanceof Error?u.message:String(u);return e.logger.error(g),{error:g,target:s,validation:o}}let c;if(!e.skipCodegen){const u=await gr(a,t,e.logger,e.apiSpec,s,e.spawner,e.format==="json",n);if(u.error!==void 0)return{error:u.error,target:s,validation:o};c=u.result}let l;if(c!==void 0){const u=De({allowDrift:e.allowSchemaDrift===!0,codegen:c,command:r,logger:e.logger,updateBaseline:e.updateSchemaBaseline===!0});if(u.blocked)return{error:`schema drift gate blocked ${r}`,schemaDrift:{blocked:!0,reason:u.reason},target:s,validation:o};l=u.rebless}await ur(a,e.logger,c?.cronTriggers,s,e.env);const d=He(a,e,r);if(d!==void 0)return{code:d.code,error:d.error,target:s,validation:o};const m=oe({environment:e.env,projectRoot:a});return hr(m,e.logger)?{error:"wrangler validation failed",target:s,validation:m}:{codegen:c,reblessSchemaBaseline:l,target:s,validation:m}},yr=async e=>{const r=e.cwd??process.cwd(),a=H(e),t=await pr(e,e.commandName??"deploy");if(t.error!==void 0){if(t.validation.problems.length>0)return{code:h.USAGE,descriptor:void 0,error:t.error,validation:t.validation};const k=t.schemaDrift===void 0?void 0:{schemaDrift:t.schemaDrift};return D(t.error,{...k,...t.code===void 0?{}:{code:t.code}})}const{reblessSchemaBaseline:n,validation:o}=t,i=E(t.target),s=Me(e);if(s!==void 0)return D(s);const c=i.toolchain?.prebuildsContainerImages===!0?await lr(r,e):void 0;if(c!==void 0)return D(c);rr(r,e.logger,i);const{error:l,mintedSecretsFile:d}=await cr(r,e,a,i);if(l!==void 0)return e.logger.error(l),{code:h.USAGE,descriptor:void 0,error:l,mintedSecretsFile:d,validation:o};const m=vr(r,e,i);e.logger.info(`deploying via ${m.command} ${m.args.join(" ")}`);const g=await(e.spawner??$)(m);return m.captureStdoutSilently===!0&&g.stdout!==void 0&&g.stdout!==""&&process.stderr.write(g.stdout),g.code!==0?{code:g.code,descriptor:m,mintedSecretsFile:d,validation:o}:{...await er({cwd:r,descriptor:m,mintedSecretsFile:d,options:e,reblessSchemaBaseline:n,stdout:g.stdout,validation:o}),logsAvailable:i.toolchain?.tail!==void 0}},wr=async e=>{const{logger:r}=e,a=e.dryRun===!0?_e(e.cwd??process.cwd()):void 0;let t;try{if(t=await yr({...e,logger:r}),t.code===0&&e.emitBindings!==void 0){const{error:n}=ve({destination:e.emitBindings,logger:r,projectRoot:e.cwd??process.cwd()});n!==void 0&&(r.error(n),t={...t,code:h.USAGE})}}finally{a?.()}if(e.format==="json")return t;if(t.code===0&&e.dryRun!==!0&&e.preview!==!0)Te({cwd:e.cwd??process.cwd(),env:e.env,logger:e.logger,logsAvailable:t.logsAvailable===!0,mintedSecretsFile:t.mintedSecretsFile,url:t.deployment?.url});else if(t.code===0&&e.preview===!0){const n=t.deployment?.url;e.logger.success(n===void 0?"preview version uploaded":`preview version uploaded — ${n}`)}return t},Br=pe(async({cwd:e,format:r,logger:a,options:t})=>{const n=await wr({allowSchemaDrift:t.allowSchemaDrift===!0,apiSpec:fe(t.apiSpec),cwd:e,dryRun:t.dryRun===!0,env:t.env,format:r,healthCheck:t.healthCheck===!0,logger:a,migrate:t.migrate===!0,migrateToken:t.migrateToken,migrateUrl:F({cwd:e,env:t.env,url:t.migrateUrl}),migrateYes:t.migrateYes===!0,preview:t.preview===!0,skipCodegen:t.prebuilt===!0,strictAdvisories:t.strictAdvisories,target:t.target,temporary:t.temporary===!0,updateSchemaBaseline:t.updateSchemaBaseline===!0});return{code:n.code,data:{deployment:n.deployment,healthCheck:n.healthCheck,mintedSecretsFile:n.mintedSecretsFile,schemaDrift:n.schemaDrift,validation:n.validation},error:n.error}});export{Br as execute,ur as provisionBindings,wr as runDeployCommand,pr as runPreDeployPipeline};
7
+ `,"utf8"),r.info(`.gitignore: added ${o.join(", ")} so the recorded secret cannot be committed`)}catch(t){r.warn(`could not update .gitignore (${t instanceof Error?t.message:String(t)}) — add \`${S.join("` and `")}\` by hand before committing.`)}},ur=(e,r,a)=>{if(a.length===0)return;const t=a.map(s=>s.key).join(", ");if(r.env!==void 0&&!cr.test(r.env)){r.logger.warn(`${t}: minted and pushed for --env ${r.env}, but "${r.env}" isn't a safe filename fragment — the value could not be recorded. Capture it manually if you need it again.`);return}const n=r.env===void 0?w:`${w}.${r.env}`;dr(e,r.logger);const o=y(e,n);let i=p(o)?k(o,"utf8"):"";for(const s of a)i=ae(i,s.key,s.value);return oe(o,i),r.logger.success(r.env===void 0?`${t}: value(s) recorded in ${n}`:`${t}: value(s) recorded in ${n} (kept separate from ${w} so \`lunora dev\` and a plain \`lunora env push\` don't inherit the --env ${r.env} value)`),n},gr=async(e,r,a,t)=>{if(r.dryRun===!0||r.preview===!0)return{};const{logger:n}=r,o=r.env===void 0?"":` --env ${r.env}`;let i;try{i=await(r.secretLister??Ie)({cwd:e,env:r.env,temporary:r.temporary})}catch{return{}}if(!i.ok)return{};const s=new Set(i.names),d=(await ir(e)).filter(u=>!s.has(u));if(d.length===0)return{};if(!a)return{error:`missing required secret(s) on the deploy target: ${d.join(", ")}. Set them with \`wrangler secret put <KEY>${o}\` (or \`lunora env generate --set\` then \`lunora env push --yes${o}\`), then re-deploy.`};for(const u of d.filter(g=>!P(g)))n.warn(`required secret ${u} is not set on the target — set it with: wrangler secret put ${u}${o}`);const l=d.filter(u=>P(u));if(l.length===0)return{};if(await(r.secretConfirm??Ne())(`${String(l.length)} required secret(s) not set on the target (${l.join(", ")}). Generate strong values and push them now?`)){const{minted:u,ok:g}=await sr(e,r,l,t),f=ur(e,r,u);return g?{mintedSecretsFile:f}:{error:"failed to push required secret(s) — set them manually and re-deploy",mintedSecretsFile:f}}return n.warn(`${String(l.length)} required secret(s) not set on the target: ${l.join(", ")}. Generate + push with \`lunora env generate --set\` then \`lunora env push --yes${o}\`.`),{}},G=e=>e.format==="json"?!1:e.interactive!==void 0?e.interactive:process.stdout.isTTY&&!process.env.CI,mr=async(e,r)=>{if(r.dryRun===!0)return;const a=L(e,"lunora").containers.flatMap(n=>n.schedulingPolicy===void 0&&n.image.kind==="build"?[{buildDir:n.image.buildDir,exportName:n.exportName}]:[]);if(a.length===0)return;const t=await Ue({cwd:e,logger:r.logger,railpackAvailable:r.railpackAvailable,spawner:r.spawner,targets:a});return t.code===0?void 0:t.error??"railpack build failed"},fr=(e,r,a)=>{if(a!==void 0)try{const t=ge(e,a);t.changed&&r.success(`synced ${String(a.length)} cron trigger(s) → ${t.wranglerPath??"wrangler.jsonc"}`);for(const o of t.warnings)r.warn(o);const n=me(t.preserved);n!==void 0&&r.info(n)}catch(t){const n=t instanceof Error?t.message:String(t);r.warn(`cron trigger sync skipped: ${n}`)}},hr=async(e,r,a,t,n)=>{try{R(t);const o=await F({projectRoot:e}),i=de(e,o,n),s=i.wranglerPath??"wrangler.jsonc";if(i.added.length>0&&r.success(`provisioned bindings: ${i.added.join(", ")} → ${s}`),i.updated.length>0&&r.success(`updated bindings: ${i.updated.join(", ")} → ${s}`),i.devConfig!==void 0){const{added:c,path:d,updated:l}=i.devConfig;r.success(`dev sidecar bindings: ${[...c,...l].join(", ")} → ${d}`)}for(const c of i.warnings)r.warn(c)}catch(o){const i=o instanceof Error?o.message:String(o);r.warn(`binding inference skipped: ${i}`)}try{const o=ue(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}`)}fr(e,r,a)},vr=async(e,r,a,t,n,o,i,s)=>{let c;r?(c=new fe({name:"dots"}),c.start("running codegen")):a.info("running codegen");try{const d=Q({apiSpec:t,projectRoot:e,target:n});c?.succeed("codegen complete"),c||a.success("codegen complete");const l=ve(d.platformDiagnostics,a);if(l.errors.length>0)return{error:l.errors.join("; ")};const{errorAdvisories:m,names:u,shouldBlock:g}=pe(d.advisories,s);if(g){const v=`${m.length.toString()} ERROR-level ${m.length===1?"advisory":"advisories"} (${u.join(", ")}). Pass --no-strict-advisories to downgrade this to a warning and continue.`;return a.error(v),{error:v}}const f=await ie({cwd:e,logger:a,spawner:o,stdoutToStderr:i});return f.error!==void 0?{error:f.error}:{result:d}}catch(d){c?.failed("codegen failed");const l=d instanceof Error?d.message:String(d);return a.error(`codegen failed: ${l}`),{error:`codegen failed: ${l}`}}},pr=(e,r)=>({dryRun:r.dryRun,entry:H(e),environment:r.env,outDir:r.outDir,preview:r.preview,temporary:r.temporary}),K=(e,r,a)=>{const{toolchain:t}=a;if(t===void 0)throw new Error(`deploy target "${a.id}" has no command-line toolchain`);const n=pr(e,r);return O(a,e,"deploy",o=>t.deploy({...n,configPath:o}))},yr=(e,r,a)=>{const t=K(e,r,a),n=H(e);return 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}`),t.commit(),t.projection!==void 0&&t.projection.dropped.length>0&&r.logger.warn(`${a.name} ignores these wrangler keys, so they were left out of ${t.projection.configPath}: ${t.projection.dropped.join(", ")}`),t.command},D=(e,r)=>({code:h.USAGE,descriptor:void 0,error:e,validation:{problems:[],wranglerPath:void 0},...r}),wr=(e,r)=>{for(const a of e.report?.warnings??[])r.warn(`wrangler.jsonc: ${a}`);if(e.problems.length===0)return!1;r.error("wrangler.jsonc validation failed:");for(const a of e.problems)r.error(` - ${a}`);return!0},kr=(e,r,a)=>{const t=r.format==="json",n=r.dryRun!==!0,o=yr(e,r,a),i=E(b(e),o);return{args:i.args,captureStdout:n&&!t,captureStdoutSilently:n&&t,command:i.command,cwd:e,stdoutToStderr:t&&!n}},br=async(e,r)=>{const a=e.cwd??process.cwd(),t=G(e),n=he(e),o={problems:[],wranglerPath:void 0},i=we(a,e.target);if(i.target===void 0){const u=i.error??"unknown deploy target";return e.logger.error(u),{error:u,validation:o}}const{target:s}=i;try{K(a,e,R(s))}catch(u){const g=u instanceof Error?u.message:String(u);return e.logger.error(g),{error:g,target:s,validation:o}}let c;if(!e.skipCodegen){const u=await vr(a,t,e.logger,e.apiSpec,s,e.spawner,e.format==="json",n);if(u.error!==void 0)return{error:u.error,target:s,validation:o};c=u.result}let d;if(c!==void 0){const u=je({allowDrift:e.allowSchemaDrift===!0,codegen:c,command:r,logger:e.logger,updateBaseline:e.updateSchemaBaseline===!0});if(u.blocked)return{error:`schema drift gate blocked ${r}`,schemaDrift:{blocked:!0,reason:u.reason},target:s,validation:o};d=u.rebless}await hr(a,e.logger,c?.cronTriggers,s,e.env);const l=Ye(a,e,r);if(l!==void 0)return{code:l.code,error:l.error,target:s,validation:o};const m=le({environment:e.env,projectRoot:a});return wr(m,e.logger)?{error:"wrangler validation failed",target:s,validation:m}:{codegen:c,reblessSchemaBaseline:d,target:s,validation:m}},$r=e=>{if(e.skipServices===!0)return"--skip-services";if(e.preview===!0)return"--preview uploads the app version only";if(e.temporary===!0)return"--temporary deploys the app to a throwaway account"},Sr=async(e,r,a,t)=>{const{error:n,services:o}=X(e);if(n!==void 0)return n;if(o.length===0)return;const{toolchain:i}=a,s=i===void 0?`target "${a.id}" has no deploy command`:$r(r);if(s!==void 0||i===void 0){const l=o.map(m=>m.worker).join(", ");r.logger.warn(`services not deployed (${s??""}): ${l} — deploy them yourself if the app calls anything new`);return}const c=b(e),d=[...new Map(o.map(l=>[l.wranglerPath,l])).values()];for(const l of d){const m=z(l.wranglerPath);let u;try{u=O(a,m,"deploy",v=>i.deploy({configPath:v??l.wranglerPath,dryRun:r.dryRun===!0,environment:r.env}))}catch(v){return`service ${l.name} (${l.worker}): ${v instanceof Error?v.message:String(v)}`}u.commit();const g=E(c,u.command);r.logger.info(`deploying service ${l.name} (${l.worker}) via ${g.command} ${g.args.join(" ")}`);const f=await t({args:g.args,command:g.command,cwd:m,stdoutToStderr:r.format==="json"});if(f.code!==0)return`service ${l.name} (${l.worker}): ${g.command} ${g.args.join(" ")} exited ${String(f.code)} — stopping before the app`}},Dr=async e=>{const r=e.cwd??process.cwd(),a=G(e),t=await br(e,e.commandName??"deploy");if(t.error!==void 0){if(t.validation.problems.length>0)return{code:h.USAGE,descriptor:void 0,error:t.error,validation:t.validation};const q=t.schemaDrift===void 0?void 0:{schemaDrift:t.schemaDrift};return D(t.error,{...q,...t.code===void 0?{}:{code:t.code}})}const{reblessSchemaBaseline:n,validation:o}=t,i=R(t.target),s=Ge(e);if(s!==void 0)return D(s);const c=i.toolchain?.prebuildsContainerImages===!0?await mr(r,e):void 0;if(c!==void 0)return D(c);or(r,e.logger,i);const{error:d,mintedSecretsFile:l}=await gr(r,e,a,i);if(d!==void 0)return e.logger.error(d),{code:h.USAGE,descriptor:void 0,error:d,mintedSecretsFile:l,validation:o};const m=e.spawner??$,u=await Sr(r,e,i,m);if(u!==void 0)return{code:h.FAILURE,descriptor:void 0,error:u,mintedSecretsFile:l,validation:o};const g=kr(r,e,i);e.logger.info(`deploying via ${g.command} ${g.args.join(" ")}`);const f=await m(g);return g.captureStdoutSilently===!0&&f.stdout!==void 0&&f.stdout!==""&&process.stderr.write(f.stdout),f.code!==0?{code:f.code,descriptor:g,mintedSecretsFile:l,validation:o}:{...await ar({cwd:r,descriptor:g,mintedSecretsFile:l,options:e,reblessSchemaBaseline:n,stdout:f.stdout,validation:o}),logsAvailable:i.toolchain?.tail!==void 0}},Er=async e=>{const{logger:r}=e,a=e.dryRun===!0?Fe(e.cwd??process.cwd()):void 0;let t;try{if(t=await Dr({...e,logger:r}),t.code===0&&e.emitBindings!==void 0){const{error:n}=ke({destination:e.emitBindings,logger:r,projectRoot:e.cwd??process.cwd()});n!==void 0&&(r.error(n),t={...t,code:h.USAGE})}}finally{a?.()}if(e.format==="json")return t;if(t.code===0&&e.dryRun!==!0&&e.preview!==!0)Le({cwd:e.cwd??process.cwd(),env:e.env,logger:e.logger,logsAvailable:t.logsAvailable===!0,mintedSecretsFile:t.mintedSecretsFile,url:t.deployment?.url});else if(t.code===0&&e.preview===!0){const n=t.deployment?.url;e.logger.success(n===void 0?"preview version uploaded":`preview version uploaded — ${n}`)}return t},zr=be(async({cwd:e,format:r,logger:a,options:t})=>{const n=await Er({allowSchemaDrift:t.allowSchemaDrift===!0,apiSpec:ye(t.apiSpec),cwd:e,dryRun:t.dryRun===!0,env:t.env,format:r,healthCheck:t.healthCheck===!0,logger:a,migrate:t.migrate===!0,migrateToken:t.migrateToken,migrateUrl:M({cwd:e,env:t.env,url:t.migrateUrl}),migrateYes:t.migrateYes===!0,preview:t.preview===!0,skipCodegen:t.prebuilt===!0,skipServices:t.skipServices===!0,strictAdvisories:t.strictAdvisories,target:t.target,temporary:t.temporary===!0,updateSchemaBaseline:t.updateSchemaBaseline===!0});return{code:n.code,data:{deployment:n.deployment,healthCheck:n.healthCheck,mintedSecretsFile:n.mintedSecretsFile,schemaDrift:n.schemaDrift,validation:n.validation},error:n.error}});export{zr as execute,hr as provisionBindings,Er as runDeployCommand,br as runPreDeployPipeline};
@@ -1,3 +1,2 @@
1
- import{runCodegen as P}from"@lunora/codegen";import{runPostCodegenHook as G,detectAgentRules as O,updateDevServerState as $,readDevServerState as j,discoverContainerInfo as F,streamContainerLogs as H,formatLunoraEvent as V,DEV_DAEMON_ENV as C,detectAiAgent as B,readProjectRemotePreference as U,readLiveDevServerState as M,DEV_HANDOFF_ENV as y,clearDevServerState as W,claimDevServerState as X,DEV_LOG_FILE_ENV as K,inferLunoraBindings as Y,packageNamesFromBindings as J,ensureDevVarsExample as z,ensureDevVariables as Q,isInteractive as Z,DEV_VARS_FILE as T,DEV_VARS_EXAMPLE_FILE as q,fillDevSecrets as ee,DEV_BINDINGS_FILE as te,DEV_STATE_FILE as x,claimAgentRulesHint as re,AGENT_RULES_HINT as oe}from"@lunora/config";import{resolveRemoteEnabled as ne}from"@lunora/config/cloudflare";import{p as ie,a as ae}from"../packem_shared/deploy-target-DCWwiuAe.mjs";import{w as se}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{existsSync as ce,watch as de}from"node:fs";import{join as le}from"node:path";import{a as ue}from"../packem_shared/codegen-error-AmH54ofi.mjs";import{a as fe}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{d as me}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as ge}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{forceJsonLogging as ve}from"../packem_shared/createLogger-Cl18I8AX.mjs";import{createServer as we,request as he}from"node:http";import{connect as pe}from"node:net";import{pipeline as Se}from"node:stream";import{loadStudioAssets as k,studioAssetsStamp as I,renderStudioHtml as ye,resolveAdminToken as Ee,requestPathname as R,transportRejectionReason as D,SCHEMA_EDIT_ENDPOINT as be,POLICY_SCAFFOLD_ENDPOINT as Te,SEED_ENDPOINT as ke,sendStudioDocument as Ie,serveJsonHandler as Re,isStandaloneModulePath as De,readStandaloneAsset as _e,assetContentType as Le,handleSchemaEditRequest as Ne,handlePolicyScaffoldRequest as Ae,handleSeedRequest as Pe,applyStudioAssetCache as Oe}from"@lunora/config/studio-host";import{c as $e}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{setTimeout as Ce}from"node:timers/promises";import{r as Me,d as xe,P as Ge,a as je,b as E,s as Fe,c as He,e as Ve,f as Be,g as Ue}from"../packem_shared/plan-CtBB0rrT.mjs";import{provisionBindings as We}from"./runDeployCommand.mjs";import{spawn as Xe}from"node:child_process";import{spawnShellCompat as Ke}from"../packem_shared/createRecordingSpawner-sS7LEN7x.mjs";const Ye=100,Je=300,ze=/[/\\]/u,Qe=(e,t,r)=>{const{apiSpec:n,logger:o,projectRoot:a,target:c}=e;try{const i=P({apiSpec:n,lunoraDirectory:t,projectRoot:a,target:c});o.success(`codegen: wrote ${t}/_generated (${r})`),fe(i.platformDiagnostics,o)}catch(i){return o.error(ue(i,r)),!1}return!0},Ze=e=>{const t=e.lunoraDirectory??"lunora",r=le(e.projectRoot,t),n=e.debounceMs??Ye;let o=!1,a=!1,c=!1,i,d=0,f=Promise.resolve(),w;const p=new Promise(m=>{w=m}),h=m=>{o||(i=m,!a&&(a=!0,f=(async()=>{try{for(;i!==void 0;){const v=i;if(i=void 0,!!Qe(e,t,v)){c=!0;try{(await G({cwd:e.projectRoot,logger:e.logger,spawner:e.spawner,stdoutToStderr:e.jsonLogs})).ran&&(d=Date.now())}finally{c=!1}}}}catch(v){e.logger.error(`codegen watch: ${v instanceof Error?v.message:String(v)}`)}finally{a=!1,w()}})()))};h("startup");const l=m=>(e.logger.warn(`codegen watch unavailable (${m}) — schema edits will NOT auto-regenerate. Run \`lunora codegen\` manually after each edit.`),{close:()=>(o=!0,i=void 0,f),ready:p,watchAvailable:!1});let s,u;if(!ce(r))return l(`no such directory: ${r}`);try{u=de(r,{recursive:!0},(m,v)=>{if(!(typeof v=="string"&&v.split(ze).includes("_generated"))){if(c||Date.now()-d<Je){s&&(clearTimeout(s),s=void 0);return}s&&clearTimeout(s),s=setTimeout(()=>{h(`change: ${v??"?"}`)},n)}})}catch(m){return l(m instanceof Error?m.message:String(m))}const g=u;return{close:()=>(o=!0,i=void 0,s&&clearTimeout(s),g.close(),f),ready:p,watchAvailable:!0}},_="/_lunora",L=3e4,N=(e,t,r)=>{const n=he({headers:{...e.headers,host:r.host},hostname:r.hostname,method:e.method,path:e.url,port:r.port},o=>{t.writeHead(o.statusCode??502,o.headers),Se(o,t,()=>{})});n.setTimeout(L,()=>{n.destroy(new Error(`no response within ${String(L)}ms`))}),n.on("error",o=>{if(t.headersSent){t.destroy();return}t.statusCode=o.message.startsWith("no response within")?504:502,t.end(`lunora dev: worker unreachable (${o.message})`)}),t.on("close",()=>{t.writableFinished||n.destroy()}),e.pipe(n)},qe=5e3,et=(e,t,r,n)=>{const o=pe({host:n.hostname,port:Number(n.port)},()=>{o.setTimeout(0);const a=[`${e.method??"GET"} ${e.url??"/"} HTTP/1.1`];for(const[c,i]of Object.entries(e.headers))if(c!=="host")for(const d of Array.isArray(i)?i:[i])d!==void 0&&a.push(`${c}: ${d}`);a.push(`host: ${n.host}`,"",""),o.write(a.join(`\r
2
- `)),r.length>0&&o.write(r),o.pipe(t),t.pipe(o)});o.setTimeout(qe,()=>o.destroy()),o.on("error",()=>t.destroy()),t.on("error",()=>o.destroy())},tt=async e=>{const t=e.host??"127.0.0.1",r=t==="127.0.0.1"||t==="localhost"||t==="::1",n=new URL(e.workerOrigin);let o=k(e.logger,import.meta.url),a=I(import.meta.url);const c=ye({adminToken:r?Ee(e.cwd):void 0,basePath:"/",dataEditable:r,rulesInstalled:O(e.cwd).installed,runAsIdentity:r,schemaEditable:r,scriptSrc:"/studio.js",styleHref:"/styles.css"}),i=(l,s,u,g,m)=>{Oe(l,s,m,a)||(s.statusCode=200,s.setHeader("Content-Type",g),s.end(u))},d=(l,s,u)=>{l.statusCode=s,l.setHeader("Content-Type","text/plain"),l.end(u)},f=(l,s,u,g)=>{if(r){Re(l,s,u,e.cwd,{apiSpec:e.apiSpec});return}d(s,403,g)},w=(l,s,u)=>{const g=l==="/styles.css",m=De(l);if(!g&&!m)return!1;const v=I(import.meta.url);if(v!==a&&(o=k(e.logger,import.meta.url),a=v),o===void 0)return d(u,501,"Lunora studio assets not found — install and build @lunora/studio."),!0;if(g)return i(s,u,o.styles,"text/css; charset=utf-8","styles.css"),!0;const S=l.slice(l.lastIndexOf("/")+1),b=_e(S,import.meta.url);return b===void 0?(d(u,404,"Not found"),!0):(i(s,u,b,Le(S),S),!0)},p=Buffer.from(c),h=we((l,s)=>{const u=R(l.url??"/");if(r){const m=D(l,e.logger);if(m!==void 0){d(s,403,m);return}}if(u.startsWith(_)){if(!r){d(s,403,"Lunora studio: the worker admin proxy is only available on a loopback bind.");return}N(l,s,n);return}if(u===be){f(l,s,Ne,"Lunora schema editing is only available on loopback hosts in dev.");return}if(u===Te){f(l,s,Ae,"Lunora policy scaffolding is only available on loopback hosts in dev.");return}if(u===ke){f(l,s,Pe,"Lunora data seeding is only available on loopback hosts in dev.");return}if(w(u,l,s))return;const g=l.headers["sec-fetch-mode"];if(r&&typeof g=="string"&&g!=="navigate"){N(l,s,n);return}Ie(s,p)});return h.on("upgrade",(l,s,u)=>{if(!r||D(l,e.logger)!==void 0){s.destroy();return}R(l.url??"").startsWith(_)?et(l,s,u,n):s.destroy()}),await new Promise((l,s)=>{h.once("error",u=>{u.code==="EADDRINUSE"?s(new Error(`studio port ${String(e.port)} is already in use — pass a different port with --port, or stop the process using it`,{cause:u})):s(u)}),h.listen(e.port,t,()=>{l()})}),{close:()=>new Promise(l=>{h.close(()=>{l()})}),url:`http://${t==="0.0.0.0"||t==="::"?"localhost":t}:${String(e.port)}`}},rt=async e=>{const{cwd:t,logger:r,origin:n,signal:o}=e,a=e.probe??xe,c=Me(e.readyTimeoutMs),i=Date.now()+c,d=()=>o.aborted;for(;!d()&&Date.now()<i;){let f=!1;try{f=await a(n,o)}catch{}if(d()||Date.now()>=i)break;if(f)return $(t,{readyAt:new Date().toISOString()},{expectedPid:process.pid}),j(t)?.readyAt!==void 0;try{await Ce(Ge,void 0,{signal:o})}catch{}}return d()||r.warn(`server did not answer on ${n} within ${String(Math.round(c/1e3))}s — .lunora/dev.json will have no readyAt, so anything polling for readiness will keep waiting. The server itself is unaffected; raise LUNORA_DEV_READY_TIMEOUT_MS if it is just slow to boot.`),!1},ot=5e3,A=(e,t,r,n)=>{if(e.length===0)return;const o=V(e);if(o){n[o.level](`[lunora] ${o.text}`);return}const a=`[${t}] ${e}`;r==="stderr"?n.warn(a):n.info(a)},nt=(e,t,r)=>{const n=(o,a)=>{if(!o)return;let c="";o.on("data",i=>{c+=i.toString("utf8");const d=c.split(`
3
- `);c=d.pop()??"";for(const f of d)A(f.trimEnd(),t,a,r)}),o.on("end",()=>{A(c.trimEnd(),t,a,r),c=""})};n(e.stdout,"stdout"),n(e.stderr,"stderr")},it=(e,t)=>{const r=Ke(e.command,e.args),n=Xe(r.command,r.args,{cwd:e.cwd??process.cwd(),env:e.env?{...process.env,...e.env}:process.env,shell:r.shell,stdio:["inherit","pipe","pipe"]});return nt(n,e.tag,t),{exited:new Promise(o=>{n.on("error",a=>{t.error(`[${e.tag}] failed to start: ${a.message}`),o(1)}),n.on("exit",(a,c)=>{o(a??(c?1:0))})}),kill:o=>{try{n.kill(o)}catch{}}}},at=(e,t)=>{if(process.env.LUNORA_CONTAINER_LOGS==="0")return;const n=F(e,"lunora").containers.map(o=>({className:o.className,exportName:o.exportName}));if(n.length!==0)return H({containers:n,onLine:o=>{const a=`[container:${o.name}] ${o.text}`;o.level==="error"?t.warn(a):t.info(a)},onUnavailable:o=>{t.warn(`[container] Docker engine unreachable — container logs unavailable (${o})`)}})},st=async e=>{e.readyProbe?.abort(),await e.codegen?.close().catch(()=>{}),e.containerLogs?.close(),await e.studio?.close().catch(()=>{});try{e.remoteCleanup?.()}catch{}},ct=async e=>await new Promise(t=>{const r={},n=c=>{e.info(`received ${c} — shutting down`),r.sigint&&process.off("SIGINT",r.sigint),r.sigterm&&process.off("SIGTERM",r.sigterm),t(0)},o=()=>{n("SIGINT")},a=()=>{n("SIGTERM")};r.sigint=o,r.sigterm=a,process.on("SIGINT",o),process.on("SIGTERM",a)}),dt=async(e,t,r)=>{let n=0,o;const a=f=>{e.kill(f),t?.kill(f)},c=()=>{n+=1,n===1?(r.info("received SIGINT — shutting down (press Ctrl-C again to force-kill)"),a("SIGTERM"),o=setTimeout(()=>{a("SIGKILL")},ot),o.unref()):a("SIGKILL")},i=()=>{a("SIGTERM")};process.on("SIGINT",c),process.on("SIGTERM",i);const d=await Promise.race([e.exited.then(f=>({code:f,who:"worker"})),...t===void 0?[]:[t.exited.then(f=>({code:f,who:"sidecar"}))]]);return t!==void 0&&(d.who==="sidecar"?(r.warn("[worker] the Lunora sidecar (wrangler dev) exited — shutting down the framework dev server"),e.kill("SIGTERM")):t.kill("SIGTERM"),await Promise.allSettled([e.exited,t.exited])),o&&clearTimeout(o),process.off("SIGINT",c),process.off("SIGTERM",i),d.code},lt=(e,t,r,n)=>{e.info(""),e.success("Lunora dev"),e.info(` ➜ Worker: ${t.workerOrigin}`),r!==void 0&&e.info(` ➜ Studio: ${r}`),t.runsCodegenWatch&&e.info(" ➜ Codegen: watching lunora/"),n!==void 0&&e.info(` ➜ Supervisor: ${n} (needs) · ${x} (status)`),t.remote.enabled&&(t.remote.bindings.length>0?e.info(` ➜ Remote: ${t.remote.bindings.join(", ")} → deployed worker`):e.warn(` ➜ Remote: requested but inactive (${t.remote.reason??"no eligible bindings"}) — running fully local`)),e.info("")},ut=(e,t)=>{O(t).installed||!re()||(e.info(` ⓘ ${oe}`),e.info(""))},ft=async(e,t)=>{try{const n=await Y({projectRoot:t}),o=J(n),a=(e.ensureExample??z)(t,o);a.length>0&&e.logger.info(`Updated .dev.vars.example with secrets for: ${o.join(", ")} (${a.join(", ")})`)}catch{}(await(e.ensureEnv??Q)({confirm:$e(),cwd:t,info:n=>{e.logger.info(n)}})).status==="declined"&&!Z()&&e.logger.info(`hint: ${T} was not scaffolded (non-interactive run). Copy ${q} → ${T} and fill in secrets, or run \`lunora dev\` in an interactive terminal to scaffold automatically.`);try{(e.fillSecrets??ee)({cwd:t,info:n=>{e.logger.info(n)}})}catch{}},mt=(e,t,r,n,o)=>{if(e.flavor!=="wrangler")return;n!==void 0&&$(t,{studioUrl:n});let a;try{a=at(t,r)}catch{}return lt(r,e,n,o),a},gt=(e,t)=>{const r=Number(process.env[y]),n=X(t,{background:process.env[C]==="1",logFile:process.env[K],mode:"cli",pid:process.pid,startedAt:new Date().toISOString(),url:e.workerOrigin},Number.isInteger(r)&&r>0?{supersedePid:r}:void 0);return n.ok?void 0:n.existing},vt=e=>{const{cwd:t,destination:r,logger:n,plan:o}=e,a=r!==void 0,c=r??te,i=se({destination:c,dev:{...o.flavor==="wrangler"?{origin:o.workerOrigin}:{},statusFile:x},logger:a?n:{...n,success:()=>{},warn:()=>{}},projectRoot:t});return i.error!==void 0?a?i:(n.debug?.(`skipped the default binding manifest: ${i.error}`),{}):{written:c}},wt=async(e,t,r,n)=>{if(t.studioEnabled)try{return await(e.startStudio??tt)({apiSpec:e.apiSpec,cwd:r,logger:{warnOnce:o=>{n.warn(o)}},port:t.studioPort,workerOrigin:t.workerOrigin})}catch(o){n.warn(`studio server failed to start (${o instanceof Error?o.message:String(o)}) — continuing without it`);return}},ht=e=>{const t=[e.runsCodegenWatch?"codegen watch":void 0,e.studioEnabled?"studio":void 0].filter(n=>n!==void 0);return`--no-worker: not starting wrangler. ${t.length>0?`${t.join(" + ")} running`:"nothing else to run"}; your task runner owns the worker on ${e.workerOrigin}.`},pt=(e,t,r,n,o)=>{if(!(e.sidecar===void 0||!Ue(t)))try{P({apiSpec:t.apiSpec,lunoraDirectory:"lunora",projectRoot:r,target:o})}catch(a){n.warn(`codegen (pre-sidecar) failed: ${a instanceof Error?a.message:String(a)} — the framework dev server will retry`)}},St=e=>e.flavor==="vite"?"starting vite dev (worker + studio + codegen run inside Vite via @lunora/vite)":`starting ${e.wrangler.tag} dev + studio`,yt=async e=>{const{logger:t}=e,r=e.cwd??process.cwd(),n=e.flavor??He(r),o=ae(r,e.target);if(o.target===void 0)throw new Error(o.error??"unknown deploy target");const{target:a}=o,c=Ve(a,n,t);c==="wrangler"&&await We(r,t,void 0,a,void 0);const i=await Be({...e,flavor:c,target:a}),d={remoteCleanup:i.remote.cleanup};try{const f=Number(process.env[y]),w=M(r);if(w!==void 0&&w.pid!==process.pid&&w.pid!==f)return E(t,w),{code:0,plan:i};const p=gt(i,r);if(p!==void 0)return E(t,p),{code:0,plan:i};(i.flavor==="vite"||i.flavor==="framework-worker")&&(i.wrangler.env={...i.wrangler.env,[y]:String(process.pid)}),await ft(e,r),t.info(St(i)),i.ipv4LoopbackForced&&t.info("no IPv6 loopback (::1) on this host — binding the worker to 127.0.0.1 (--ip) so wrangler dev doesn't crash. Pin `dev.ip` in wrangler.jsonc to override."),i.runsCodegenWatch&&(d.codegen=(e.startCodegen??Ze)({apiSpec:e.apiSpec,jsonLogs:e.jsonLogs,logger:t,projectRoot:r,target:a})),d.studio=await wt(e,i,r,t);const h=vt({cwd:r,destination:e.emitBindings,logger:t,plan:i});if(h.error!==void 0)return t.error(h.error),{code:ge.USAGE,plan:i};await d.codegen?.ready;const l=d.studio?.url;i.frameworkHint!==void 0&&t.warn(i.frameworkHint);const s=()=>{i.flavor==="wrangler"&&(d.readyProbe=new AbortController,rt({cwd:r,logger:t,origin:i.workerOrigin,probe:e.probeReady,signal:d.readyProbe.signal}))};if(!i.workerEnabled)return s(),t.info(ht(i)),{code:await(e.waitForInterrupt??ct)(t),plan:i};pt(i,e,r,t,a);const u=e.startWorker??it,g=u(i.wrangler,t),m=i.sidecar===void 0?void 0:u(i.sidecar,t);return s(),d.containerLogs=mt(i,r,t,l,h.written),ut(t,r),{code:await dt(g,m,t),plan:i}}finally{d.readyProbe?.abort(),W(r,process.pid),await st(d)}},Et=e=>({codegen:e.codegen===!1?!1:void 0,studio:e.studio===!1?!1:void 0,worker:e.worker===!1?!1:void 0}),Ut=me(async({argument:e,cwd:t,logger:r,options:n})=>{const o=n.json===!0,a=je({cwd:t,json:o,lines:n.lines,logger:r,subcommand:e[0]});if(a!==void 0)return a;const c=process.env[C]==="1",i=c?void 0:B(),d=o||i!==void 0;d&&ve(),i!==void 0&&n.background!==!0&&r.info(`AI agent detected (${i.name} via ${i.variable}) — starting the dev server in background mode with JSON logs. Set LUNORA_AGENT_MODE=0 to opt out.`);const f=ne({configPreference:U(t),envValue:process.env.LUNORA_REMOTE,flag:n.remote});if(!c&&(n.background===!0||i!==void 0)){const w=M(t);return w!==void 0?(E(r,w),{code:0}):Fe({cwd:t,jsonLogs:d,logger:r,options:n,remote:f})}return yt({apiSpec:ie(n.apiSpec),cwd:t,emitBindings:n.emitBindings,inspectorPort:n.inspectorPort,jsonLogs:d,logger:r,port:n.port,remote:f,target:n.target,workerPort:n.workerPort,...Et(n)})});export{Ut as execute,Et as negatableDevFlags,yt as runDevCommand};
1
+ import{runCodegen as $}from"@lunora/codegen";import{runPostCodegenHook as F,detectAgentRules as N,updateDevServerState as C,readDevServerState as x,DEV_DAEMON_ENV as I,detectAiAgent as H,readProjectRemotePreference as V,readLiveDevServerState as j,DEV_HANDOFF_ENV as p,clearDevServerState as W,claimDevServerState as B,DEV_LOG_FILE_ENV as U,inferLunoraBindings as G,packageNamesFromBindings as X,ensureDevVarsExample as Y,ensureDevVariables as J,isInteractive as K,DEV_VARS_FILE as k,DEV_VARS_EXAMPLE_FILE as z,fillDevSecrets as Q,DEV_BINDINGS_FILE as Z,DEV_STATE_FILE as M,claimAgentRulesHint as q,AGENT_RULES_HINT as ee}from"@lunora/config";import{resolveRemoteEnabled as re}from"@lunora/config/cloudflare";import{p as te,a as oe}from"../packem_shared/deploy-target-DCWwiuAe.mjs";import{w as ne}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{existsSync as ae,watch as ie}from"node:fs";import{join as se}from"node:path";import{a as ce}from"../packem_shared/codegen-error-AmH54ofi.mjs";import{a as de}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{d as le}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as D}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{forceJsonLogging as ue}from"../packem_shared/createLogger-Cl18I8AX.mjs";import{createServer as fe,request as ge}from"node:http";import{connect as ve}from"node:net";import{pipeline as me}from"node:stream";import{loadStudioAssets as T,studioAssetsStamp as _,renderStudioHtml as we,resolveAdminToken as he,requestPathname as A,transportRejectionReason as R,SCHEMA_EDIT_ENDPOINT as Se,POLICY_SCAFFOLD_ENDPOINT as ye,SEED_ENDPOINT as pe,sendStudioDocument as Ee,serveJsonHandler as be,isStandaloneModulePath as ke,readStandaloneAsset as De,assetContentType as Te,handleSchemaEditRequest as _e,handlePolicyScaffoldRequest as Ae,handleSeedRequest as Re,applyStudioAssetCache as Pe}from"@lunora/config/studio-host";import{c as Oe}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{setTimeout as Le}from"node:timers/promises";import{r as $e,d as Ne,P as Ce,a as Ie,b as E,s as je,c as Me,e as Fe,f as xe,w as He,g as Ve,h as We,t as Be,i as Ue,j as Ge,k as Xe}from"../packem_shared/plan-BzTGWr2e.mjs";import{provisionBindings as Ye}from"./runDeployCommand.mjs";const Je=100,Ke=300,ze=/[/\\]/u,Qe=(e,r,t)=>{const{apiSpec:o,logger:n,projectRoot:i,target:u}=e;try{const a=$({apiSpec:o,lunoraDirectory:r,projectRoot:i,target:u});n.success(`codegen: wrote ${r}/_generated (${t})`),de(a.platformDiagnostics,n)}catch(a){return n.error(ce(a,t)),!1}return!0},Ze=e=>{const r=e.lunoraDirectory??"lunora",t=se(e.projectRoot,r),o=e.debounceMs??Je;let n=!1,i=!1,u=!1,a,d=0,g=Promise.resolve(),w;const S=new Promise(f=>{w=f}),h=f=>{n||(a=f,!i&&(i=!0,g=(async()=>{try{for(;a!==void 0;){const m=a;if(a=void 0,!!Qe(e,r,m)){u=!0;try{(await F({cwd:e.projectRoot,logger:e.logger,spawner:e.spawner,stdoutToStderr:e.jsonLogs})).ran&&(d=Date.now())}finally{u=!1}}}}catch(m){e.logger.error(`codegen watch: ${m instanceof Error?m.message:String(m)}`)}finally{i=!1,w()}})()))};h("startup");const c=f=>(e.logger.warn(`codegen watch unavailable (${f}) — schema edits will NOT auto-regenerate. Run \`lunora codegen\` manually after each edit.`),{close:()=>(n=!0,a=void 0,g),ready:S,watchAvailable:!1});let s,l;if(!ae(t))return c(`no such directory: ${t}`);try{l=ie(t,{recursive:!0},(f,m)=>{if(!(typeof m=="string"&&m.split(ze).includes("_generated"))){if(u||Date.now()-d<Ke){s&&(clearTimeout(s),s=void 0);return}s&&clearTimeout(s),s=setTimeout(()=>{h(`change: ${m??"?"}`)},o)}})}catch(f){return c(f instanceof Error?f.message:String(f))}const v=l;return{close:()=>(n=!0,a=void 0,s&&clearTimeout(s),v.close(),g),ready:S,watchAvailable:!0}},P="/_lunora",O=3e4,L=(e,r,t)=>{const o=ge({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),me(n,r,()=>{})});o.setTimeout(O,()=>{o.destroy(new Error(`no response within ${String(O)}ms`))}),o.on("error",n=>{if(r.headersSent){r.destroy();return}r.statusCode=n.message.startsWith("no response within")?504:502,r.end(`lunora dev: worker unreachable (${n.message})`)}),r.on("close",()=>{r.writableFinished||o.destroy()}),e.pipe(o)},qe=5e3,er=(e,r,t,o)=>{const n=ve({host:o.hostname,port:Number(o.port)},()=>{n.setTimeout(0);const i=[`${e.method??"GET"} ${e.url??"/"} HTTP/1.1`];for(const[u,a]of Object.entries(e.headers))if(u!=="host")for(const d of Array.isArray(a)?a:[a])d!==void 0&&i.push(`${u}: ${d}`);i.push(`host: ${o.host}`,"",""),n.write(i.join(`\r
2
+ `)),t.length>0&&n.write(t),n.pipe(r),r.pipe(n)});n.setTimeout(qe,()=>n.destroy()),n.on("error",()=>r.destroy()),r.on("error",()=>n.destroy())},rr=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=T(e.logger,import.meta.url),i=_(import.meta.url);const u=we({adminToken:t?he(e.cwd):void 0,basePath:"/",dataEditable:t,rulesInstalled:N(e.cwd).installed,runAsIdentity:t,schemaEditable:t,scriptSrc:"/studio.js",styleHref:"/styles.css"}),a=(c,s,l,v,f)=>{Pe(c,s,f,i)||(s.statusCode=200,s.setHeader("Content-Type",v),s.end(l))},d=(c,s,l)=>{c.statusCode=s,c.setHeader("Content-Type","text/plain"),c.end(l)},g=(c,s,l,v)=>{if(t){be(c,s,l,e.cwd,{apiSpec:e.apiSpec});return}d(s,403,v)},w=(c,s,l)=>{const v=c==="/styles.css",f=ke(c);if(!v&&!f)return!1;const m=_(import.meta.url);if(m!==i&&(n=T(e.logger,import.meta.url),i=m),n===void 0)return d(l,501,"Lunora studio assets not found — install and build @lunora/studio."),!0;if(v)return a(s,l,n.styles,"text/css; charset=utf-8","styles.css"),!0;const y=c.slice(c.lastIndexOf("/")+1),b=De(y,import.meta.url);return b===void 0?(d(l,404,"Not found"),!0):(a(s,l,b,Te(y),y),!0)},S=Buffer.from(u),h=fe((c,s)=>{const l=A(c.url??"/");if(t){const f=R(c,e.logger);if(f!==void 0){d(s,403,f);return}}if(l.startsWith(P)){if(!t){d(s,403,"Lunora studio: the worker admin proxy is only available on a loopback bind.");return}L(c,s,o);return}if(l===Se){g(c,s,_e,"Lunora schema editing is only available on loopback hosts in dev.");return}if(l===ye){g(c,s,Ae,"Lunora policy scaffolding is only available on loopback hosts in dev.");return}if(l===pe){g(c,s,Re,"Lunora data seeding is only available on loopback hosts in dev.");return}if(w(l,c,s))return;const v=c.headers["sec-fetch-mode"];if(t&&typeof v=="string"&&v!=="navigate"){L(c,s,o);return}Ee(s,S)});return h.on("upgrade",(c,s,l)=>{if(!t||R(c,e.logger)!==void 0){s.destroy();return}A(c.url??"").startsWith(P)?er(c,s,l,o):s.destroy()}),await new Promise((c,s)=>{h.once("error",l=>{l.code==="EADDRINUSE"?s(new Error(`studio port ${String(e.port)} is already in use — pass a different port with --port, or stop the process using it`,{cause:l})):s(l)}),h.listen(e.port,r,()=>{c()})}),{close:()=>new Promise(c=>{h.close(()=>{c()})}),url:`http://${r==="0.0.0.0"||r==="::"?"localhost":r}:${String(e.port)}`}},tr=async e=>{const{cwd:r,logger:t,origin:o,signal:n}=e,i=e.probe??Ne,u=$e(e.readyTimeoutMs),a=Date.now()+u,d=()=>n.aborted;for(;!d()&&Date.now()<a;){let g=!1;try{g=await i(o,n)}catch{}if(d()||Date.now()>=a)break;if(g)return C(r,{readyAt:new Date().toISOString()},{expectedPid:process.pid}),x(r)?.readyAt!==void 0;try{await Le(Ce,void 0,{signal:n})}catch{}}return d()||t.warn(`server did not answer on ${o} within ${String(Math.round(u/1e3))}s — .lunora/dev.json will have no readyAt, so anything polling for readiness will keep waiting. The server itself is unaffected; raise LUNORA_DEV_READY_TIMEOUT_MS if it is just slow to boot.`),!1},or=(e,r,t,o)=>{e.info(""),e.success("Lunora dev"),e.info(` ➜ Worker: ${r.workerOrigin}`),t!==void 0&&e.info(` ➜ Studio: ${t}`),r.runsCodegenWatch&&e.info(" ➜ Codegen: watching lunora/"),o!==void 0&&e.info(` ➜ Supervisor: ${o} (needs) · ${M} (status)`),r.remote.enabled&&(r.remote.bindings.length>0?e.info(` ➜ Remote: ${r.remote.bindings.join(", ")} → deployed worker`):e.warn(` ➜ Remote: requested but inactive (${r.remote.reason??"no eligible bindings"}) — running fully local`)),e.info("")},nr=(e,r)=>{N(r).installed||!q()||(e.info(` ⓘ ${ee}`),e.info(""))},ar=async(e,r)=>{try{const o=await G({projectRoot:r}),n=X(o),i=(e.ensureExample??Y)(r,n);i.length>0&&e.logger.info(`Updated .dev.vars.example with secrets for: ${n.join(", ")} (${i.join(", ")})`)}catch{}(await(e.ensureEnv??J)({confirm:Oe(),cwd:r,info:o=>{e.logger.info(o)}})).status==="declined"&&!K()&&e.logger.info(`hint: ${k} was not scaffolded (non-interactive run). Copy ${z} → ${k} and fill in secrets, or run \`lunora dev\` in an interactive terminal to scaffold automatically.`);try{(e.fillSecrets??Q)({cwd:r,info:o=>{e.logger.info(o)}})}catch{}},ir=(e,r,t,o,n)=>{if(e.flavor!=="wrangler")return;o!==void 0&&C(r,{studioUrl:o});let i;try{i=Xe(r,t)}catch{}return or(t,e,o,n),i},sr=(e,r)=>{const t=Number(process.env[p]),o=B(r,{background:process.env[I]==="1",logFile:process.env[U],mode:"cli",pid:process.pid,startedAt:new Date().toISOString(),url:e.workerOrigin},Number.isInteger(t)&&t>0?{supersedePid:t}:void 0);return o.ok?void 0:o.existing},cr=e=>{const{cwd:r,destination:t,logger:o,plan:n}=e,i=t!==void 0,u=t??Z,a=ne({destination:u,dev:{...n.flavor==="wrangler"?{origin:n.workerOrigin}:{},statusFile:M},logger:i?o:{...o,success:()=>{},warn:()=>{}},projectRoot:r});return a.error!==void 0?i?a:(o.debug?.(`skipped the default binding manifest: ${a.error}`),{}):{written:u}},dr=async(e,r,t,o)=>{if(r.studioEnabled)try{return await(e.startStudio??rr)({apiSpec:e.apiSpec,cwd:t,logger:{warnOnce:n=>{o.warn(n)}},port:r.studioPort,workerOrigin:r.workerOrigin})}catch(n){o.warn(`studio server failed to start (${n instanceof Error?n.message:String(n)}) — continuing without it`);return}},lr=e=>{const r=[e.runsCodegenWatch?"codegen watch":void 0,e.studioEnabled?"studio":void 0].filter(o=>o!==void 0);return`--no-worker: not starting wrangler. ${r.length>0?`${r.join(" + ")} running`:"nothing else to run"}; your task runner owns the worker on ${e.workerOrigin}.`},ur=(e,r,t,o,n)=>{if(!(e.sidecar===void 0||!Ue(r)))try{$({apiSpec:r.apiSpec,lunoraDirectory:"lunora",projectRoot:t,target:n})}catch(i){o.warn(`codegen (pre-sidecar) failed: ${i instanceof Error?i.message:String(i)} — the framework dev server will retry`)}},fr=e=>e.flavor==="vite"?"starting vite dev (worker + studio + codegen run inside Vite via @lunora/vite)":`starting ${e.wrangler.tag} dev + studio`,gr=async(e,r,t,o,n)=>{try{return e.celldSession===!0?await Ge({logger:n,port:e.workerPort,projectRoot:o,start:r.startCelldSession}):t(e.wrangler,n)}catch(i){n.error(`could not start the worker: ${i instanceof Error?i.message:String(i)}`);return}},vr=async e=>{const{logger:r}=e,t=e.cwd??process.cwd(),o=e.flavor??Me(t),n=oe(t,e.target);if(n.target===void 0)throw new Error(n.error??"unknown deploy target");const{target:i}=n,u=Fe(i,o,r);u==="wrangler"&&await Ye(t,r,void 0,i,void 0);const a=await xe({...e,flavor:u,target:i}),d={remoteCleanup:a.remote.cleanup};try{const g=Number(process.env[p]),w=j(t);if(w!==void 0&&w.pid!==process.pid&&w.pid!==g)return E(r,w),{code:0,plan:a};const S=sr(a,t);if(S!==void 0)return E(r,S),{code:0,plan:a};(a.flavor==="vite"||a.flavor==="framework-worker")&&(a.wrangler.env={...a.wrangler.env,[p]:String(process.pid)}),await ar(e,t),r.info(fr(a)),a.ipv4LoopbackForced&&r.info("no IPv6 loopback (::1) on this host — binding the worker to 127.0.0.1 (--ip) so wrangler dev doesn't crash. Pin `dev.ip` in wrangler.jsonc to override."),a.runsCodegenWatch&&(d.codegen=(e.startCodegen??Ze)({apiSpec:e.apiSpec,jsonLogs:e.jsonLogs,logger:r,projectRoot:t,target:i})),d.studio=await dr(e,a,t,r);const h=cr({cwd:t,destination:e.emitBindings,logger:r,plan:a});if(h.error!==void 0)return r.error(h.error),{code:D.USAGE,plan:a};await d.codegen?.ready;const c=d.studio?.url;a.frameworkHint!==void 0&&r.warn(a.frameworkHint);const s=()=>{a.flavor==="wrangler"&&(d.readyProbe=new AbortController,tr({cwd:t,logger:r,origin:a.workerOrigin,probe:e.probeReady,signal:d.readyProbe.signal}))};if(!a.workerEnabled)return s(),r.info(lr(a)),{code:await(e.waitForInterrupt??He)(r),plan:a};ur(a,e,t,r,i);const l=e.startWorker??Ve,v=await gr(a,e,l,t,r);if(v===void 0)return{code:D.FAILURE,plan:a};const f=a.sidecar===void 0?void 0:l(a.sidecar,r);return s(),d.containerLogs=ir(a,t,r,c,h.written),nr(r,t),{code:await We(v,f,r),plan:a}}finally{d.readyProbe?.abort(),W(t,process.pid),await Be(d)}},mr=e=>({codegen:e.codegen===!1?!1:void 0,studio:e.studio===!1?!1:void 0,worker:e.worker===!1?!1:void 0}),jr=le(async({argument:e,cwd:r,logger:t,options:o})=>{const n=o.json===!0,i=Ie({cwd:r,json:n,lines:o.lines,logger:t,subcommand:e[0]});if(i!==void 0)return i;const u=process.env[I]==="1",a=u?void 0:H(),d=n||a!==void 0;d&&ue(),a!==void 0&&o.background!==!0&&t.info(`AI agent detected (${a.name} via ${a.variable}) — starting the dev server in background mode with JSON logs. Set LUNORA_AGENT_MODE=0 to opt out.`);const g=re({configPreference:V(r),envValue:process.env.LUNORA_REMOTE,flag:o.remote});if(!u&&(o.background===!0||a!==void 0)){const w=j(r);return w!==void 0?(E(t,w),{code:0}):je({cwd:r,jsonLogs:d,logger:t,options:o,remote:g})}return vr({apiSpec:te(o.apiSpec),cwd:r,emitBindings:o.emitBindings,inspectorPort:o.inspectorPort,jsonLogs:d,logger:t,port:o.port,remote:g,target:o.target,workerPort:o.workerPort,...mr(o)})});export{jr as execute,mr as negatableDevFlags,vr as runDevCommand};
@@ -1 +1 @@
1
- import{C as i,R as m,V as p,r as s}from"./cli-BQ3AyV_K.mjs";import"./EXIT_CODE-D_XCixv8.mjs";import"./createLogger-Cl18I8AX.mjs";import"./render-lunora-error-C3OJY5wk.mjs";export{i as COMMANDS,m as REGISTERED_COMMAND_NAMES,p as VERSION,s as runCli};
1
+ import{C as i,R as m,V as p,r as s}from"./cli-CIDgoZP8.mjs";import"./EXIT_CODE-D_XCixv8.mjs";import"./createLogger-Cl18I8AX.mjs";import"./render-lunora-error-C3OJY5wk.mjs";export{i as COMMANDS,m as REGISTERED_COMMAND_NAMES,p as VERSION,s as runCli};
@@ -0,0 +1,2 @@
1
+ import{mkdirSync as A,readFileSync as S,lstatSync as B,writeFileSync as D}from"node:fs";import{join as m,dirname as y}from"node:path";import{fileURLToPath as E}from"node:url";import{isLunoraError as L,findSolutionByMessage as I}from"@lunora/errors";import{createCerebro as j}from"@visulima/cerebro";import T from"@visulima/cerebro/command/completion";import _ from"@visulima/cerebro/command/version";import{O as a}from"./output-format-B4eQHi5y.mjs";import{A as p,T as l}from"./deploy-target-DCWwiuAe.mjs";import{SDK_LANGUAGES as P}from"@lunora/codegen";import{exitCodeForError as U,EXIT_CODE as M}from"./EXIT_CODE-D_XCixv8.mjs";import{setCommandLogger as v,createLogger as x}from"./createLogger-Cl18I8AX.mjs";import{r as W}from"./render-lunora-error-C3OJY5wk.mjs";import{homedir as J}from"node:os";import{addArgsFor as F,detectPackageManager as K}from"@lunora/config";const H={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},a]},b="lunora.advisor.map.json",$={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/handler19.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 ${b})`,name:"baseline",type:String},{description:"Inspect a single procedure by `file#exportName`",name:"entry",type:String},a,{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 ${b})`,name:"out",type:String},{description:"Write the map artifact to disk (the default)",name:"write",type:Boolean},{description:"Don't write the map artifact to disk — report only",name:"no-write",type:Boolean}]},G={argument:{description:"gateway",name:"subcommand",type:String},description:"Provision a Cloudflare AI Gateway for ctx.ai and write its id into wrangler vars",examples:[["lunora ai gateway","Create (or reuse) a gateway named after the worker and wire it into wrangler vars"],["lunora ai gateway --id my-gateway","Use an explicit gateway id"],["lunora ai gateway --no-logs","Create the gateway with prompt/response log collection off"],["lunora ai gateway --dry-run","Print what would be created and written, without calling Cloudflare"]],group:"Deploy",loader:()=>import("../packem_chunks/handler20.mjs").then(e=>({default:e.execute})),name:"ai",options:[{description:"Gateway id (default: the worker `name` from wrangler.jsonc)",name:"id",type:String},{description:"Collect request/response logs in the gateway (default)",name:"logs",type:Boolean},{description:"Create the gateway with log collection off (prompts and responses are not stored)",name:"no-logs",type:Boolean},{description:"Print what would be created and written, without calling Cloudflare or editing files",name:"dry-run",type:Boolean},a]},V={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:[a]},q={argument:{description:"create | list | restore <id|file> | retention | prune | pitr",name:"subcommand",type:String},description:"Managed snapshot backups (create | list | restore) to a directory or an R2 bucket, 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 list --format json","Same, as a single JSON document on stdout"],["lunora backup restore <id>","Restore a snapshot by id"],["lunora backup create --bucket default","Snapshot into an R2 bucket instead of a directory"],["lunora backup restore <id> --bucket default --verify","Restore from R2, checksum first"],["lunora backup retention","Show what the platform's retention would delete next"],["lunora backup prune","Delete the snapshots past the retention window (the only command that deletes backups)"],["lunora backup pitr --at 2026-06-01T00:00:00Z","Point-in-time recovery (≤30 days)"]],group:"Data",loader:()=>import("../packem_chunks/handler23.mjs").then(e=>({default:e.execute})),name:"backup",options:[{description:"Backup directory (default .lunora-backups)",name:"dir",type:String},{description:"Store snapshots in this R2 bucket instead of a directory (use `default` for the app's default bucket)",name:"bucket",type:String},{description:"Key prefix for bucket-backed snapshots (default backups/)",name:"prefix",type:String},{description:"restore: verify the snapshot's checksum before importing anything",name:"verify",type:Boolean},{description:"Comma-separated table allowlist (create)",name:"tables",type:String},a,{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 destructive step without prompting: a production pitr --restore, or backup prune",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:"Codegen + validate + bundle the Worker to disk without deploying",examples:[["lunora build","Bundle to .lunora/build without deploying"],["lunora build --out-dir dist-worker","Bundle to a custom directory"],["lunora build --emit-bindings bindings.json","Also write what the bundle needs provisioned, for an external deployer"]],group:"Deploy",loader:()=>import("../packem_chunks/handler21.mjs").then(e=>({default:e.execute})),name:"build",options:[{description:"Override the schema-drift gate for this run (build even with breaking schema drift and no migration; the committed baseline is not advanced)",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${p} (default openapi)`,name:"api-spec",type:String},{description:"Write a JSON manifest of the bindings + crons the bundle needs to this path, for an IaC program to consume",name:"emit-bindings",type:String},a,{description:"Directory to write the bundled Worker to (default .lunora/build)",name:"out-dir",type:String},{description:"Fail the build on ERROR-level codegen advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail the build on ERROR-level codegen advisories (the gate defaults to on in CI, off locally). Never downgrades platform diagnostics.",name:"no-strict-advisories",type:Boolean},l]},Y={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},a,{description:"Fail on ERROR-level advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail on ERROR-level advisories (the gate defaults to on in CI, off locally)",name:"no-strict-advisories",type:Boolean},l]},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 list --format json","List container instances as JSON (also `info`, `images list`)"],["lunora containers images delete transcoder:v1","Delete an image to free registry storage"]],group:"Deploy",loader:()=>import("../packem_chunks/handler3.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},{...a,description:"Output format: pretty (default) or json (read subcommands: list | info | images list)"}]},X={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 --migrate-yes --migrate-url <url>","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 for this run (deploy even with breaking schema drift and no migration; the committed baseline is not advanced — use --update-schema-baseline to accept the new shape)",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},a,{description:"After the deploy, probe the new version's health route (/_lunora/health/ready, falling back to /_lunora/health) and fail if it never answers",name:"health-check",type:Boolean},{description:"After a successful deploy, run pending data migrations against the live worker",name:"migrate",type:Boolean},{description:"Skip codegen + the schema-drift gate (assumes `lunora build`/`prepare` already ran in this CI run). Wrangler still bundles the worker.",name:"prebuilt",type:Boolean},{description:"Admin bearer token for --migrate (falls back to LUNORA_ADMIN_TOKEN)",name:"migrate-token",type:String},{description:"Worker URL for --migrate (REQUIRED with --migrate; the deploy target URL is not captured automatically)",name:"migrate-url",type:String},{description:"Confirm running the production data migration triggered by --migrate (required with --migrate)",name:"migrate-yes",type:Boolean},{description:"Fail the deploy on ERROR-level codegen advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail the deploy on ERROR-level codegen advisories (the gate defaults to on in CI, off locally). Never downgrades platform diagnostics.",name:"no-strict-advisories",type:Boolean},{description:"Upload a preview version (wrangler versions upload) instead of going live — prints a preview URL; doesn't shift production traffic",name:"preview",type:Boolean},{description:"Deploy only the app, not the lunora.config services it binds (they deploy first by default)",name:"skip-services",type:Boolean},l,{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/handler4.mjs").then(e=>({default:e.execute})),name:"deployments",options:[{description:"Cloudflare environment name",name:"env",type:String},{...a,description:"Output format: pretty (default) or json (`list` only)"},{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}]},ee={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, ready/starting)"],["lunora dev status --json","Same as JSON — poll `.ready` to gate a dependent step in a task graph"],["lunora dev logs","Print the captured dev-server log (background runs)"],["lunora dev --json","Stream machine-readable JSON log LINES (a stream, not a --format json document)"],["lunora dev --emit-bindings dev-manifest.json","Write what this worker needs + where it serves, for a task runner"],["lunora dev --no-studio","Skip the embedded studio server"],["lunora dev --worker-port 8080","Use a custom wrangler dev port"],["lunora dev --inspector-port 9235","Pin wrangler's devtools inspector port instead of letting it walk up from 9229"],["lunora dev --remote","Proxy D1/KV/R2 to the deployed worker (also LUNORA_REMOTE=1)"]],group:"Develop",loader:()=>import("../packem_chunks/runDevCommand.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:"Write the binding manifest (plus the dev origin) to <file>, for a supervisor that owns the rest of the graph",name:"emit-bindings",type:String},{description:"wrangler dev inspector port, for `wrangler dev` only (defaults to `dev.inspector_port` in wrangler.jsonc; unset, wrangler probes upward from 9229 and can take a sibling worker's pinned port)",name:"inspector-port",type:Number},{description:"Studio server port (default 6173)",name:"port",type:Number},l,{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:"Machine-readable JSON log lines while the server runs, and a JSON result for `dev status`/`dev stop` (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:"Serve the embedded studio at /__lunora (default)",name:"studio",type:Boolean},{description:"Don't start the embedded studio server",name:"no-studio",type:Boolean},{description:"Spawn wrangler dev for the worker (default)",name:"worker",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:"Run codegen on startup and watch for changes (default)",name:"codegen",type:Boolean},{description:"Don't run codegen — no watch, no startup generate (or set LUNORA_CODEGEN=0)",name:"no-codegen",type:Boolean},{description:"Proxy D1/KV/R2 bindings to the deployed worker (or set LUNORA_REMOTE=1)",name:"remote",type:Boolean}]},te={argument:{description:"Optional path under the docs site (e.g. packages/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 packages/studio","Open a specific docs section"]],group:"Project",loader:()=>import("../packem_chunks/handler5.mjs").then(e=>({default:e.execute})),name:"docs"},re={description:"Preflight the current Lunora project (wrangler bindings, placeholders, dev secrets)",examples:[["lunora doctor","Run the project preflight checks"],["lunora doctor --format json","Emit the findings as a machine-readable JSON document"]],group:"Project",loader:()=>import("../packem_chunks/handler24.mjs").then(e=>({default:e.execute})),name:"doctor",options:[a]},oe={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"],["lunora env diff --format json","Same, as a single JSON document on stdout"]],group:"Data",loader:()=>import("../packem_chunks/handler6.mjs").then(e=>({default:e.execute})),name:"env",options:[{description:"Target this Cloudflare environment for `push`/`diff` (passes --env <name> to wrangler)",name:"env",type:String},{description:"Alias for --env production",name:"prod",type:Boolean},a,{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}]},ne={description:"Run every *.eval.ts under evals/ via @lunora/testing's evaluate/agentHarness — no live worker needed",examples:[["lunora eval","Run every eval under evals/, print the aggregate table"],["lunora eval --threshold 0.8","Non-zero exit if any eval's average score falls below 0.8"],["lunora eval --dir evals/support --format json","Run a subset and emit a machine-readable result"]],group:"Develop",loader:()=>import("../packem_chunks/handler25.mjs").then(e=>({default:e.execute})),name:"eval",options:[{description:"Directory to discover *.eval.ts files under (default evals/)",name:"dir",type:String},a,{description:"Score gate every eval's average must meet ([0,1]); a per-eval `threshold` export wins over this for that eval",name:"threshold",type:Number}]},ae={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"],["lunora export --out backup.ndjson --format json","Write the dump to a file and report rows/bytes as JSON"]],group:"Data",loader:()=>import("../packem_chunks/handler7.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},{...a,description:"Output format: pretty (default) or json — json needs --out <file>, since stdout carries the NDJSON"},{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}]},ie={argument:{description:"Source NDJSON file, or a `npx convex export --path <dir>` directory",name:"file",type:String},description:"Bulk-insert rows from an NDJSON file — or a Convex export directory — via the worker's admin endpoint",examples:[["lunora import backup.ndjson","Bulk-insert rows from an NDJSON file"],["lunora import ./convex-export","Import a `npx convex export --path` directory (ids are preserved, so no remapping)"],["lunora import ./convex-export --with-storage","Also migrate blobs (verified sha256 upload) + `{ $storage }` refs"],["lunora import ./convex-export --scan","Write a candidate `lunora/import-convex.json` storage-column mapping (imports nothing)"],["lunora import ./snapshot.zip --with-storage --verify","Import a `npx convex export --path` zip snapshot with blob + row-parity checks"],["lunora import ./supabase-csv --from supabase","Import a directory of `COPY … TO STDOUT WITH CSV HEADER` dumps"],["lunora import ./firestore-json --from firebase --verify","Import Firestore documents (REST/Admin-SDK JSON) with row-parity checks"]],group:"Data",loader:()=>import("../packem_chunks/handler8.mjs").then(e=>({default:e.execute})),name:"import",options:[{description:"Source reader for a dump that cannot be detected: supabase | firebase (Convex and NDJSON are auto-detected)",name:"from",type:String},{description:"Wrap each bare doc as `{table:<name>,doc:...}`",name:"table",type:String},a,{description:"Rows per HTTP request (default 500)",name:"batch-size",type:Number},{description:"Also migrate file storage — Convex `_storage` blobs, or a Supabase/Firebase bucket (verified upload)",name:"with-storage",type:Boolean},{description:"Directory of storage objects to upload alongside the rows (Firebase: after `gcloud storage cp -r`)",name:"storage-dir",type:String},{description:"Write a candidate `lunora/import-convex.json` storage-column mapping and exit",name:"scan",type:Boolean},{description:"Verify row parity + dangling-storage after import (non-zero exit on mismatch)",name:"verify",type:Boolean},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Confirm bulk-writing production (required with --prod)",name:"yes",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String}]},se={description:"Print resolved project config: @lunora/* versions, wrangler summary, schema overview",examples:[["lunora info","Print resolved project config"],["lunora info --format json","Emit a JSON snapshot"],["lunora info --bindings","List what this Worker needs provisioned: bindings, crons, vars"],["lunora info --bindings --format json","Emit the manifest a deployer or task runner consumes"],["lunora info --bindings --out reqs.json","Write that manifest to a file"]],group:"Project",loader:()=>import("../packem_chunks/handler9.mjs").then(e=>({default:e.execute})),name:"info",options:[{description:"Report only what this Worker needs provisioned, as the binding manifest",name:"bindings",type:Boolean},a,{description:"With --bindings: write the manifest to <file> instead of stdout",name:"out",type:String}]},le={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 -t solid-v2","Scaffold a Solid 2.0 SPA"],["lunora init my-app -t rspack-react","Scaffold a React SPA on Rsbuild"],["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:"Template: analog | astro | expo | next | nuxt | react-router | rspack-react | solid-v2 | standalone | sveltekit | tanstack-start-react | tanstack-start-react-rspack | tanstack-start-solid | vinext | vinext-pages. Also accepts an overlay framework (react | vue | solid | svelte), same as --vite.",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 | auth-ui | 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}]},de={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 --format 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/handler10.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},a,{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}]},pe={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/handler27.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 (the default)",name:"procedures",type:Boolean},{description:"Emit only the schema — skip the per-table list/get procedure modules",name:"no-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},a]},ce={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/handler11.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}]},ue={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/handler26.mjs").then(e=>({default:e.execute})),name:"logs",options:[{description:"Cloudflare environment name",name:"env",type:String},a,{description:"Substring filter on log messages",name:"search",type:String},{description:"Filter by invocation status: ok, error, or canceled",name:"status",type:String},l,{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}]},me={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"],["lunora mcp serve --token $LUNORA_ADMIN_TOKEN","Expose the observability tools (logs, issues, advisories, insights, migrations) too"]],group:"Develop",loader:()=>import("../packem_chunks/handler28.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: expose the documentation tools (default)",name:"docs",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). Also gates the observability tools (logs, issues, advisories, query insights, migration status) — without a token they are not exposed at all",name:"token",type:String}]},ge={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 status backfill-names --format json","Same, as a single JSON document on stdout"],["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/dispatch.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},a,{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}]},he={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/handler12.mjs").then(e=>({default:e.execute})),name:"prepare",options:[{description:"Override the schema-drift gate for this run (proceed even with breaking schema drift and no migration; the committed baseline is not advanced)",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${p} (default openapi)`,name:"api-spec",type:String},{description:"Fail on ERROR-level codegen advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail on ERROR-level codegen advisories (the gate defaults to on in CI, off locally). Never downgrades platform diagnostics.",name:"no-strict-advisories",type:Boolean},l,{description:"Re-bless the committed schema baseline (lunora/.lunora-schema.json) with the current shape",name:"update-schema-baseline",type:Boolean}]},fe={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 --from ./registry --check","Verify the committed catalog is current"]],group:"Project",loader:()=>import("../packem_chunks/handler13.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},{...a,description:"Output format: pretty (default) or json (add plan / list)"},{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}]},ye={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}]},ve={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/handler14.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}]},be={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)"],["lunora run messages:list --format json","Emit the RPC result as a single JSON document on stdout"]],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},a,{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}]},we={argument:{description:"<generate>",name:"args",type:String},description:"Generate a self-contained typed client SDK for another language from the project's OpenRPC surface",examples:[["lunora sdk generate --lang python","Emit a Python SDK, transport included, into ./sdk/python"],["lunora sdk generate --lang go --out ./clients/go","Choose the language and output directory"],["lunora sdk generate --lang dart","A Flutter-ready Dart client — live queries arrive as a Stream"],["lunora sdk generate --lang kotlin","Any of the registered targets; --lang lists them"],["lunora sdk generate --lang rust --from ./sdks","Copy the transport from a local checkout instead of fetching it"]],group:"Project",loader:()=>import("../packem_chunks/handler22.mjs").then(e=>({default:e.execute})),name:"sdk",options:[{description:`Target language: ${P.join(" | ")}`,name:"lang",type:String},{description:"Output directory (default ./sdk/<lang>)",name:"out",type:String},{description:"Path to the OpenRPC document (default ./lunora/_generated/openrpc.json)",name:"spec",type:String},{description:"Copy the transport from a local directory of per-language transports (the repo's `sdks/`) instead of fetching it",name:"from",type:String},{description:"Git ref to fetch the transport from (default: this CLI's own release tag, so the transport matches the generated surface)",name:"ref",type:String},{description:"Override the remote transport source base (default gh:anolilab/lunora/sdks)",name:"source",type:String},{description:"Permit --source values outside gh:/github:/https://",name:"allow-unsafe-source",type:Boolean}]},ke={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 --format json","Report generated / inserted / conflicts per table as JSON"],["lunora seed --seed 7 --now 1785000000000","Byte-identical rows across runs (pins the clock too)"]],group:"Data",loader:()=>import("../packem_chunks/handler15.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},a,{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}]},Se={argument:{description:"prune",name:"subcommand",type:String},description:"Maintain the shard registry: prune shards that no longer hold any rows of their .shardBy() table",examples:[["lunora shards prune --dry-run","Show which registered shards are empty, without removing anything"],["lunora shards prune","Remove the empty shards from the registry"],["lunora shards prune --tables messages","Only prune the shards listed for `messages`"],["lunora shards prune --prod --url https://app.example.com","Prune production"]],group:"Data",loader:()=>import("../packem_chunks/handler16.mjs").then(e=>({default:e.execute})),name:"shards",options:[{description:"Comma-separated .shardBy() tables (default: all of them)",name:"tables",type:String},{description:"Report what would be pruned without changing the registry",name:"dry-run",type:Boolean},a,{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (defaults to the running dev server)",name:"url",type:String},{description:"Admin bearer token (or LUNORA_ADMIN_TOKEN)",name:"token",type:String}]},xe={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"],["lunora verify --env production","Validate the env.production view, as `lunora deploy --env production` will"]],group:"Deploy",loader:()=>import("../packem_chunks/handler17.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:"Cloudflare environment name — validate the env.<name> view of wrangler.jsonc, as `lunora deploy --env` does",name:"env",type:String},a,{description:"Probe this deployment's /_lunora/health endpoint (off by default; keeps verify offline-safe)",name:"health-url",type:String},{description:"Fail verification on ERROR-level codegen advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail verification on ERROR-level codegen advisories (the gate defaults to on in CI, off locally). Never downgrades platform diagnostics.",name:"no-strict-advisories",type:Boolean},{description:"Run the TypeScript type-check step (default)",name:"typecheck",type:Boolean},{description:"Skip the TypeScript type-check step",name:"no-typecheck",type:Boolean},l]},Ce={description:"Open the Lunora studio in your browser (the running dev server's, or the default local one)",examples:[["lunora view","Open the studio for the running dev server"]],group:"Project",loader:()=>import("../packem_chunks/handler18.mjs").then(e=>({default:e.execute})),name:"view"},Re=(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 i=1;i<=t.length;i+=1){const s=r[i]??0,c=e[o-1]===t[i-1]?0:1;r[i]=Math.min((r[i-1]??0)+1,s+1,n+c),n=s}}return r[t.length]??0},Ne=(e,t)=>{let r,o=Number.POSITIVE_INFINITY;for(const i of t){const s=Re(e,i);s<o&&(o=s,r=i)}const n=Math.max(2,Math.ceil(e.length/3));return r!==void 0&&o<=n?r:void 0},Oe=e=>`https://registry.npmjs.org/@lunora/cli/${e}`,Ae=1440*60*1e3,Be=1500,De="0.0.0",Ee=/^v/u,Le=new Set(["alpha","beta","next"]),g=e=>{const t=e.trim().replace(Ee,""),r=t.indexOf("-");return r===-1?{core:t,prerelease:""}:{core:t.slice(0,r),prerelease:t.slice(r+1)}},w=e=>{const[t,r,o]=g(e).core.split(".").map(n=>{const i=Number.parseInt(n,10);return Number.isFinite(i)?i:0});return[t??0,r??0,o??0]},Ie=(e,t)=>{const r=Number.parseInt(e,10),o=Number.parseInt(t,10);return String(r)===e&&String(o)===t?r>o?1:-1:e>t?1:-1},je=(e,t)=>{if(e===t)return 0;if(e===""||t==="")return e===""?1:-1;const r=e.split("."),o=t.split(".");for(let n=0;n<Math.max(r.length,o.length);n+=1){const i=r[n],s=o[n];if(i===void 0||s===void 0)return i===void 0?-1:1;if(i!==s)return Ie(i,s)}return 0},Te=(e,t)=>{const r=w(e),o=w(t);for(let n=0;n<3;n+=1)if((r[n]??0)!==(o[n]??0))return(r[n]??0)>(o[n]??0)?1:-1;return je(g(e).prerelease,g(t).prerelease)},_e=e=>{const t=g(e).prerelease.split(".")[0]??"";return Le.has(t)?t:"latest"},Pe=(e,t)=>Te(t,e)>0,Ue=(e,t,r)=>t-e<r,Me=(e,t,r="latest",o)=>{const n=`Update available for @lunora/cli: ${e} → ${t}`;if(o===void 0)return`${n} — add @lunora/cli@${r} as a dev dependency to update`;const{args:i,command:s}=F(o,[`@lunora/cli@${r}`],{dev:!0});return`${n} — run \`${s} ${i.join(" ")}\``},C=e=>m(e,"lunora-cli-update.json"),We=e=>{const t=e.XDG_CACHE_HOME&&e.XDG_CACHE_HOME.length>0?e.XDG_CACHE_HOME:m(J(),".cache"),r=m(t,"lunora");try{A(r,{mode:448,recursive:!0})}catch{}return r},Je=e=>{try{const t=JSON.parse(S(C(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{}},k=(e,t)=>{try{const r=C(e);try{if(B(r).isSymbolicLink())return}catch{}D(r,`${JSON.stringify(t)}
2
+ `,"utf8")}catch{}},Fe=async(e,t)=>{try{const r=await e(Oe(t),{signal:AbortSignal.timeout(Be)});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}},Ke=(e,t,r)=>e===De||!r||t.CI!==void 0||t.LUNORA_NO_UPDATE_NOTIFIER!==void 0,He=async e=>{const t=e.env??process.env,r=e.isTTY??process.stdout.isTTY;if(Ke(e.current,t,r))return;const o=e.cacheDir??We(t),n=(e.now??Date.now)(),i=e.ttlMs??Ae,s=_e(e.current),c=Je(o),O=c?.tag??"latest",h=c!==void 0&&O===s?c:void 0;let u=h?.latest;if(h===void 0||!Ue(h.checkedAt,n,i)){const f=await Fe(e.fetchImpl??globalThis.fetch,s);f===void 0?k(o,{checkedAt:n,latest:e.current,tag:s}):(u=f,k(o,{checkedAt:n,latest:f,tag:s}))}u!==void 0&&Pe(e.current,u)&&e.logger.warn(Me(e.current,u,s,e.manager))},$e=["init","add","dev","codegen","build","deploy","containers","ai","prepare","link","deployments","logs","run","insights","reset","migrate","export","import","seed","shards","backup","eval","verify","info","doctor","env","analyze","view","docs","registry","rules","mcp"],Ge=8,Ve=()=>{try{let e=y(E(import.meta.url));for(let t=0;t<Ge;t+=1){try{const o=JSON.parse(S(m(e,"package.json"),"utf8")),n=o!==null&&typeof o=="object"?o:void 0;if(n?.name==="@lunora/cli"&&typeof n.version=="string"&&n.version.length>0)return n.version}catch{}const r=y(e);if(r===e)break;e=r}}catch{}return"0.0.0"},R=Ve(),qe=[le,H,ee,Y,$,z,X,Q,G,he,ce,Z,ue,be,de,ye,ge,ae,ie,ke,Se,pe,q,ne,xe,se,re,oe,V,Ce,te,fe,ve,me,we],N=[...qe,_,T],ft=N.map(e=>e.name),d=e=>e.replaceAll("{",String.raw`\{`).replaceAll("}",String.raw`\}`),ze=e=>e.every(t=>typeof t=="string")?e.map(t=>d(t)):e.map(t=>typeof t=="string"?[d(t)]:t.map(r=>d(r))),Ye=e=>({...e,...e.argument===void 0?{}:{argument:{...e.argument,description:d(e.argument.description??"")}},...e.description===void 0?{}:{description:d(e.description)},...e.examples===void 0?{}:{examples:ze(e.examples)},...e.options===void 0?{}:{options:e.options.map(t=>({...t,description:d(t.description??"")}))}}),Qe=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:R});for(const o of N)r.addCommand(Ye(o));return{cli:r,exitCode:t}},Xe=/Command "(?<name>[^"]+)" not found/u,Ze=e=>{const t=x(),r=e instanceof Error?e.message:String(e),o=Xe.exec(r);if(!o?.groups)return L(e)||I(r)!==void 0?t.error(W(e)):t.error(r),U(e);const n=o.groups.name??"",i=Ne(n,$e);return t.error(`Unknown command "${n}".${i===void 0?"":` Did you mean "${i}"?`}`),t.info("Run `lunora --help` to list commands, or `lunora docs` to open the documentation."),M.USAGE},et=e=>({debug:t=>{e.debug(t)},error:t=>{e.error(t)},info:t=>{e.info(t)},success:t=>{e.info(t)},warn:t=>{e.warn(t)}}),yt=async(e={})=>{const{cli:t,exitCode:r}=Qe(e);e.logger!==void 0&&v(et(e.logger));try{await t.run({shouldExitProcess:!1})}catch(n){return Ze(n)}finally{v(void 0)}let o;try{o=K(process.cwd())}catch{}return await He({current:R,logger:x(),manager:o}),r.value};export{$e as C,b as D,ft as R,R as V,yt as r};
@@ -0,0 +1,6 @@
1
+ import{existsSync as N,readFileSync as P,mkdirSync as se,openSync as x,closeSync as C,statSync as ie,readSync as ae}from"node:fs";import{join as w,dirname as ce}from"node:path";import{readServiceBindings as de}from"@lunora/codegen";import{targetRunsOwnDevServer as I,resolveProjectTarget as M,claimDevServerState as le,DEV_HANDOFF_ENV as ue,clearDevServerState as m,readDevServerState as b,readLiveDevServerState as G,isDevServerReady as O,detectFramework as F,readProjectDependencyNames as ve,DEV_LOG_FILE_ENV as ge,DEV_DAEMON_ENV as pe,updateDevServerState as fe,detectPackageManager as L,execArgsFor as U,isRecordedProcessCurrent as me,DEV_LOG_FILE as we,CODEGEN_ENV as j,isCodegenDisabled as he,discoverContainerInfo as Se,streamContainerLogs as ke,formatLunoraEvent as Ee,planToolchainInvocation as ye,toolchainExecArgs as V,startCelldDevSession as Pe,resolveDeployDriver as W,DEV_VARS_FILE as B,runScriptCommand as Ie,parseDevVariableEntries as be}from"@lunora/config";import{findWranglerFile as h,readWranglerJsonc as _,materializeRemoteWranglerConfig as Le}from"@lunora/config/cloudflare";import{createServer as _e}from"node:net";import{networkInterfaces as Re}from"node:os";import{spawnSync as R,spawn as K}from"node:child_process";import{setTimeout as S}from"node:timers/promises";import{EXIT_CODE as H}from"./EXIT_CODE-D_XCixv8.mjs";import{a as p}from"./output-format-B4eQHi5y.mjs";import{spawnShellCompat as z}from"./createRecordingSpawner-sS7LEN7x.mjs";const Te=12e4,J=250,Oe=1e3,Ae="LUNORA_DEV_READY_TIMEOUT_MS",De=e=>{if(e!==void 0)return e;const r=Number(process.env[Ae]??"");return Number.isFinite(r)&&r>0?r:Te},$e=async(e,r)=>{try{const o=AbortSignal.timeout(Oe);return await(await fetch(new URL("/_lunora/status",e),{redirect:"manual",signal:r===void 0?o:AbortSignal.any([r,o])})).body?.cancel(),!0}catch{return!1}},Ne=1e4,xe=100,Ce=40,f=256*1024,Me=new Set(["nuxt","sveltekit"]),Ge=["@lunora/rspack","@lunora/vite"],T=e=>{if(Me.has(F(e).framework))return"framework-worker";const r=ve(e);return Ge.some(o=>r.has(o))?"vite":"wrangler"},Y=e=>{const r=L(e);let o;try{const t=P(w(e,"package.json"),"utf8");o=JSON.parse(t).scripts?.dev}catch{}if(o===void 0||o.trim()===""||o.includes("lunora")){const t=U(r,"vite",["dev"]);return{args:t.args,command:t.command}}return{args:["run","dev"],command:r}},Fe=e=>{se(ce(e.logPath),{recursive:!0});const r=x(e.logPath,"w",384);let o;const t=z(e.command,e.args);try{o=K(t.command,t.args,{cwd:e.cwd,detached:!0,env:e.env,shell:t.shell,stdio:["ignore",r,r],windowsHide:!0})}finally{C(r)}return o.unref(),{exited:new Promise(n=>{o.on("error",()=>{n(1)}),o.on("exit",(s,i)=>{n(s??(i?1:0))})}),pid:o.pid}},Ue=e=>{try{const{size:r}=ie(e);if(r<=f)return P(e,"utf8");const o=x(e,"r");try{const t=Buffer.alloc(f),n=ae(o,t,0,f,r-f),s=t.toString("utf8",0,n);return s.slice(s.indexOf(`
2
+ `)+1)}finally{C(o)}}catch{return}},X=(e,r)=>{const o=Ue(e);if(o===void 0)return[];const t=o.split(`
3
+ `);return t.at(-1)===""&&t.pop(),r>0?t.slice(-r):t},q=(e,r)=>r?.logFile??w(e,we),Q=e=>{e.info(" Stop: lunora dev stop"),e.info(" Status: lunora dev status"),e.info(" Logs: lunora dev logs")},je=(e,r)=>{e.warn(`Dev server already running at ${r.url} (pid ${String(r.pid)})`),Q(e)},Ve=(e,r)=>{e.success(`Dev server running at ${r.url} (pid ${String(r.pid)})`),r.studioUrl!==void 0&&e.info(` Studio: ${r.studioUrl}`),Q(e)},We=async e=>{const{child:r,cwd:o,deadline:t,pollIntervalMs:n,probe:s}=e,i=r.exited.then(a=>({exitCode:a}));for(;Date.now()<t;){const a=G(o);if(a!==void 0&&a.pid!==process.pid&&await s(a.url))return{state:a,status:"ready"};const c=await Promise.race([i,S(n)]);if(c!==void 0)return{...c,status:"exited"}}return{status:"timeout"}},Be=async e=>{const{cwd:r,logger:o}=e,t=q(r,void 0),n=De(e.readyTimeoutMs),s=(e.spawnDetached??Fe)({args:e.command.args,command:e.command.command,cwd:r,env:{...process.env,...e.env,[pe]:"1",[ge]:t,...process.env.FORCE_COLOR===void 0?{NO_COLOR:"1"}:{},...e.json?{LUNORA_LOG_JSON:"1"}:{}},logPath:t}),i=await We({child:s,cwd:r,deadline:Date.now()+n,pollIntervalMs:e.pollIntervalMs??J,probe:e.probe??$e});if(i.status==="ready")return Ve(o,i.state),{code:0};if(i.status==="exited"){o.error(`dev server exited before becoming ready (exit code ${String(i.exitCode)}). Last output:`);for(const c of X(t,Ce))o.error(` ${c}`);return m(r,s.pid??process.pid),{code:i.exitCode===0?1:i.exitCode}}s.pid!==void 0&&b(r)?.pid===process.pid&&fe(r,{logFile:t,pid:s.pid});const a=s.pid===void 0?"":` (pid ${String(s.pid)})`;return o.warn(`dev server did not confirm ready within ${String(Math.round(n/1e3))}s — it may still be compiling${a}. Check \`lunora dev status\` and \`lunora dev logs\`; \`lunora dev stop\` shuts it down.`),{code:H.UNAVAILABLE}},Z=e=>e.codegen!==!1&&!he(process.env[j]),ee=e=>{const r={...e.remote===!0?{LUNORA_REMOTE:"1"}:{},...e.codegen===!1?{[j]:"0"}:{}};return Object.keys(r).length>0?{env:r}:{}},Ke=(e,r)=>{const o=["dev"];return e.apiSpec!==void 0&&o.push("--api-spec",e.apiSpec),e.port!==void 0&&o.push("--port",String(e.port)),e.workerPort!==void 0&&o.push("--worker-port",String(e.workerPort)),e.inspectorPort!==void 0&&o.push("--inspector-port",String(e.inspectorPort)),e.emitBindings!==void 0&&o.push("--emit-bindings",e.emitBindings),e.codegen===!1&&o.push("--no-codegen"),e.studio===!1&&o.push("--no-studio"),e.worker===!1&&o.push("--no-worker"),e.target!==void 0&&o.push("--target",e.target),r&&o.push("--remote"),o},Ir=async e=>{const{cwd:r,jsonLogs:o,logger:t,options:n,remote:s}=e,i=e.run??Be,a=T(r),c=a==="vite"&&I(n.target??M(r))?"wrangler":a,d=c==="wrangler"?`http://localhost:${String(n.workerPort??8787)}`:"http://localhost:5173",l=le(r,{background:!0,mode:"cli",pid:process.pid,startedAt:new Date().toISOString(),url:d});if(!l.ok)return l.existing!==void 0&&je(t,l.existing),{code:0};const u={[ue]:String(process.pid)};try{return c==="vite"?await i({command:Y(r),cwd:r,env:{...ee({...n,remote:s}).env,...u},json:o,logger:t}):await i({command:{args:[process.argv[1]??"lunora",...Ke(n,s)],command:process.execPath},cwd:r,env:u,json:o,logger:t})}finally{m(r,process.pid)}},He=e=>{try{const r=R("ps",["-o","pgid=","-p",String(e)],{encoding:"utf8"}),o=Number.parseInt(r.stdout.trim(),10);return Number.isInteger(o)&&o>0?o:void 0}catch{return}},ze=(e,r,o=process.platform,t=R)=>{if(o==="win32"){try{t("taskkill",["/pid",String(e.pid),"/T","/F"],{stdio:"ignore"})}catch{}return}if(e.background===!0)try{r(-(He(e.pid)??e.pid),"SIGKILL");return}catch{}try{r(e.pid,"SIGKILL")}catch{}},Je=(e,r)=>(r.json?p({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}),Ye=async e=>{const{cwd:r,logger:o}=e,t=b(r),n=e.alive??(u=>u===t?.pid&&me(t)),s=e.signal??((u,v)=>{process.kill(u,v)}),i=e.pollIntervalMs??J,a=e.stopGraceMs??Ne,c=e.platform??process.platform,d=e.spawnSyncImpl??R;if(t===void 0||!n(t.pid))return t!==void 0&&m(r,t.pid),e.json?p({running:!1,stopped:!1}):o.info("No dev server running."),{code:0};try{s(t.pid,"SIGTERM")}catch{}const l=Date.now()+a;for(;n(t.pid)&&Date.now()<l;)await S(i);return n(t.pid)&&(ze(t,s,c,d),await S(i),n(t.pid))?Je(t,e):(m(r,t.pid),e.json?p({pid:t.pid,stopped:!0}):o.success(`Stopped dev server (pid ${String(t.pid)}).`),{code:0})},Xe=e=>{const{cwd:r,logger:o}=e,t=G(r);if(t===void 0)return e.json?p({running:!1}):o.info("No dev server running."),{code:0};const n=e.now??Date.now,s=t.startedAt===void 0?Number.NaN:Date.parse(t.startedAt),i=Number.isFinite(s)?Math.max(0,Math.round((n()-s)/1e3)):void 0;if(e.json)return p({background:t.background===!0,logFile:t.logFile,mode:t.mode,pid:t.pid,ready:O(t),readyAt:t.readyAt,running:!0,startedAt:t.startedAt,studioUrl:t.studioUrl,uptimeSeconds:i,url:t.url}),{code:0};const a=[`pid ${String(t.pid)}`,...i===void 0?[]:[`uptime ${String(i)}s`],t.background===!0?"background":"foreground",O(t)?"ready":"starting"];return o.success(`Dev server running at ${t.url} (${a.join(", ")})`),t.studioUrl!==void 0&&o.info(` Studio: ${t.studioUrl}`),t.logFile!==void 0&&o.info(` Logs: lunora dev logs (${t.logFile})`),{code:0}},qe=e=>{const{cwd:r,logger:o}=e,t=b(r),n=q(r,t);if(!N(n))return o.info("No dev server logs found — output is captured when the server runs in background mode (`lunora dev --background`)."),{code:0};const s=X(n,e.lines??xe);return s.length>0&&process.stdout.write(`${s.join(`
4
+ `)}
5
+ `),{code:0}},br=e=>{const{cwd:r,json:o,lines:t,logger:n,subcommand:s}=e;if(s==="stop")return Ye({cwd:r,json:o,logger:n});if(s==="status")return Xe({cwd:r,json:o,logger:n});if(s==="logs")return qe({cwd:r,lines:t,logger:n});if(s!==void 0)return n.error(`dev: unknown subcommand "${s}" — expected stop | status | logs (or no subcommand to start the dev server)`),{code:H.USAGE}},Qe=5e3,k=(e,r,o,t)=>{if(e.length===0)return;const n=Ee(e);if(n){t[n.level](`[lunora] ${n.text}`);return}const s=`[${r}] ${e}`;o==="stderr"?t.warn(s):t.info(s)},Ze=(e,r,o)=>{const t=(n,s)=>{if(!n)return;let i="";n.on("data",a=>{i+=a.toString("utf8");const c=i.split(`
6
+ `);i=c.pop()??"";for(const d of c)k(d.trimEnd(),r,s,o)}),n.on("end",()=>{k(i.trimEnd(),r,s,o),i=""})};t(e.stdout,"stdout"),t(e.stderr,"stderr")},Lr=(e,r)=>{const o=z(e.command,e.args),t=K(o.command,o.args,{cwd:e.cwd??process.cwd(),env:e.env?{...process.env,...e.env}:process.env,shell:o.shell,stdio:["inherit","pipe","pipe"]});return Ze(t,e.tag,r),{exited:new Promise(n=>{t.on("error",s=>{r.error(`[${e.tag}] failed to start: ${s.message}`),n(1)}),t.on("exit",(s,i)=>{n(s??(i?1:0))})}),kill:n=>{try{t.kill(n)}catch{}}}},_r=(e,r)=>{if(process.env.LUNORA_CONTAINER_LOGS==="0")return;const t=Se(e,"lunora").containers.map(n=>({className:n.className,exportName:n.exportName}));if(t.length!==0)return ke({containers:t,onLine:n=>{const s=`[container:${n.name}] ${n.text}`;n.level==="error"?r.warn(s):r.info(s)},onUnavailable:n=>{r.warn(`[container] Docker engine unreachable — container logs unavailable (${n})`)}})},Rr=async e=>{e.readyProbe?.abort(),await e.codegen?.close().catch(()=>{}),e.containerLogs?.close(),await e.studio?.close().catch(()=>{});try{e.remoteCleanup?.()}catch{}},Tr=async e=>await new Promise(r=>{const o={},t=i=>{e.info(`received ${i} — shutting down`),o.sigint&&process.off("SIGINT",o.sigint),o.sigterm&&process.off("SIGTERM",o.sigterm),r(0)},n=()=>{t("SIGINT")},s=()=>{t("SIGTERM")};o.sigint=n,o.sigterm=s,process.on("SIGINT",n),process.on("SIGTERM",s)}),Or=async(e,r,o)=>{let t=0,n;const s=d=>{e.kill(d),r?.kill(d)},i=()=>{t+=1,t===1?(o.info("received SIGINT — shutting down (press Ctrl-C again to force-kill)"),s("SIGTERM"),n=setTimeout(()=>{s("SIGKILL")},Qe),n.unref()):s("SIGKILL")},a=()=>{s("SIGTERM")};process.on("SIGINT",i),process.on("SIGTERM",a);const c=await Promise.race([e.exited.then(d=>({code:d,who:"worker"})),...r===void 0?[]:[r.exited.then(d=>({code:d,who:"sidecar"}))]]);return r!==void 0&&(c.who==="sidecar"?(o.warn("[worker] the Lunora sidecar (wrangler dev) exited — shutting down the framework dev server"),e.kill("SIGTERM")):r.kill("SIGTERM"),await Promise.allSettled([e.exited,r.exited])),n&&clearTimeout(n),process.off("SIGINT",i),process.off("SIGTERM",a),c.code},Ar=(e,r,o)=>I(e)?(r!=="wrangler"&&o.info(`target ${e} runs its own dev server, so lunora dev serves the worker on it — start the frontend's dev server separately`),"wrangler"):r,Dr=async e=>{const{logger:r}=e,o=await(e.start??Pe)({log:(s,{stream:i,tag:a})=>{k(s,a,i,r)},port:e.port,projectRoot:e.projectRoot});let t=()=>{};const n=new Promise(s=>{t=s});return{exited:Promise.race([n,o.exited]),kill:()=>{o.stop().then(()=>0,()=>1).then(t).catch(()=>{})}}},er=e=>{const{cwd:r,driver:o,options:t,studioPort:n,workerPort:s}=e,{projectConfig:i,toolchain:a}=o;if(i===void 0||a===void 0)throw new Error(`deploy target "${o.id}" runs its own dev server but ships no config projection or toolchain for it`);if(t.remote===!0)throw new Error(`--remote proxies bindings to Cloudflare; ${o.name} has no remote bindings to proxy to`);t.inspectorPort!==void 0&&t.logger.warn(`--inspector-port is a wrangler dev flag; ${o.name} dev has no inspector to pin`);const{command:c,commit:d,projection:l}=ye(o,r,"dev",v=>a.dev({configPath:v,extraArgs:["--port",String(s)]}));d(),l!==void 0&&l.dropped.length>0&&t.logger.info(`${o.name} ignores these wrangler keys, so its dev server runs without them: ${l.dropped.join(", ")}`);const u=V(L(r),c);return{flavor:"wrangler",ipv4LoopbackForced:!1,remote:{bindings:[],cleanup:()=>{},enabled:!1},runsCodegenWatch:Z(t),celldSession:!0,studioEnabled:t.studio!==!1,studioPort:n,workerEnabled:t.worker!==!1,workerOrigin:`http://localhost:${String(s)}`,workerPort:s,wrangler:{args:u.args,command:u.command,cwd:r,tag:c.tool}}},rr=64,re="127.0.0.1",tr=65535,or=(e,r=re)=>new Promise(o=>{const t=_e();t.once("error",()=>{o(!1)}),t.once("listening",()=>{t.close(()=>{o(!0)})}),t.listen(e,r)}),nr=async(e,r=re,o=rr)=>{for(let t=e;t<e+o&&t<=tr;t+=1)if(await or(t,r))return t;return e},te=(e=Re)=>Object.values(e()).some(r=>r?.some(o=>o.internal&&o.address==="::1")),E="wrangler.dev.jsonc",y=6173,g=8787,A=5173,sr=(e,r)=>{const o=()=>{};if(!e.remote)return{args:[],plan:{bindings:[],cleanup:o,enabled:!1}};const n=(e.materializeRemote??Le)({enabled:!0,projectRoot:r}),s=n.remoteBindings.map(a=>`${a.binding} (${a.kind})`),{cleanup:i}=n;return n.configPath===void 0?{args:[],plan:{bindings:s,cleanup:i,enabled:!0,reason:n.reason}}:{args:["--config",n.configPath],plan:{bindings:s,cleanup:i,enabled:!0}}},oe=e=>[...new Set(de(e).services.map(r=>r.wranglerPath))].flatMap(r=>["--config",r]),ir=(e,r)=>{const o=oe(e),t=h(e);return o.length===0||t===void 0?[]:[...r.length>0?[]:["--config",t],...o]},D=e=>_(e).parsed?.dev?.ip,ne=(e,r,o)=>{if(o!==void 0){const n=w(e,o);if(N(n)&&D(n)!==void 0)return[]}const t=h(e);return t!==void 0&&D(t)!==void 0?[]:r()?[]:["--ip","127.0.0.1"]},ar=new Set(["127.0.0.1","::1","[::1]","localhost"]),cr=(e,r)=>{let o;try{o=P(w(e,B),"utf8")}catch{return[]}const t=[];for(const n of be(o)){let s;try{s=new URL(n.value)}catch{continue}ar.has(s.hostname)&&s.port===String(r)&&t.push(n.key)}return t},$=async(e,r)=>{if(e.workerPort!==void 0)return e.workerPort;const o=h(r);if(o!==void 0){const{parsed:s}=_(o);if(typeof s?.dev?.port=="number")return s.dev.port}const t=await(e.findFreePort??nr)(g);if(t===g)return t;const n=cr(r,g);if(n.length>0)throw new Error(`port ${String(g)} is in use, but ${B} pins the worker origin to it (${n.join(", ")}). Serving on ${String(t)} would leave those URLs pointing at nothing. Stop whatever holds ${String(g)}, or run \`lunora dev --worker-port ${String(t)}\` and update those values to match.`);return t},dr=(e,r)=>{if(e.inspectorPort!==void 0)return e.inspectorPort;const o=h(r);if(o===void 0)return;const{parsed:t}=_(o),n=t?.dev?.inspector_port;return typeof n=="number"?n:void 0},lr=(e,r,o)=>{const t=ne(r,e.hasIpv6Loopback??te,E),n=W(e.target??M(r));if(n.toolchain===void 0)throw new Error(`deploy target "${n.id}" has no dev server to run the worker sidecar`);const s=n.toolchain.dev({configPath:E,extraArgs:[...t,"--var","WORKER_ENV:development",...oe(r)]}),i=V(o,s);return{args:i.args,command:i.command,cwd:r,tag:"worker"}},ur=e=>{const r=e.cwd??process.cwd(),o=L(r),t=e.flavor??T(r);if(t==="vite"||t==="framework-worker"){const u=Y(r);let v;return t==="framework-worker"&&(v=lr(e,r,o)),e.worker===!1&&e.logger.warn(`--no-worker does not apply to the ${t} flavor: Vite owns the worker, codegen and studio in-process. Run your framework's dev script instead.`),e.inspectorPort!==void 0&&e.logger.warn(t==="framework-worker"?`--inspector-port does not apply to the ${t} flavor: pin \`dev.inspector_port\` in ${E} — that is the config the worker sidecar runs.`:`--inspector-port does not apply to the ${t} flavor: Vite owns the worker. Pin it in vite.config — \`lunora({ cloudflare: { inspectorPort: ${String(e.inspectorPort)} } })\`.`),{runsCodegenWatch:!1,flavor:t,ipv4LoopbackForced:!1,remote:{bindings:[],cleanup:()=>{},enabled:e.remote===!0},...v?{sidecar:v}:{},studioEnabled:!1,studioPort:e.port??y,workerEnabled:!0,workerOrigin:`http://localhost:${String(A)}`,workerPort:A,wrangler:{args:u.args,command:u.command,cwd:r,...ee(e),tag:"vite"}}}const n=F(r),s=n.framework==="none"?void 0:`this project uses ${n.framework} — the worker runs inside Vite there. run \`${Ie(o,"dev")}\` for the full app (frontend + HMR); \`lunora dev\` starts only the worker.`,i=e.workerPort??g,a=sr(e,r),c=ne(r,e.hasIpv6Loopback??te),d=e.inspectorPort===void 0?[]:["--inspector-port",String(e.inspectorPort)],l=U(o,"wrangler",["dev","--port",String(i),...d,...c,"--var","WORKER_ENV:development",...a.args,...ir(r,a.args)]);return{runsCodegenWatch:Z(e),flavor:t,frameworkHint:s,ipv4LoopbackForced:c.length>0,remote:a.plan,studioEnabled:e.studio!==!1,studioPort:e.port??y,workerEnabled:e.worker!==!1,workerOrigin:`http://localhost:${String(i)}`,workerPort:i,wrangler:{args:l.args,command:l.command,cwd:r,tag:"wrangler"}}},$r=async e=>{const r=e.cwd??process.cwd();if(e.target!==void 0&&I(e.target))return er({cwd:r,driver:W(e.target),options:e,studioPort:e.port??y,workerPort:await $(e,r)});const o=e.flavor??T(r),t=o==="wrangler"?await $(e,r):e.workerPort,n=o==="wrangler"?dr(e,r):e.inspectorPort;return ur({...e,cwd:r,flavor:o,inspectorPort:n,workerPort:t})};export{J as P,br as a,je as b,T as c,$e as d,Ar as e,$r as f,Lr as g,Or as h,Z as i,Dr as j,_r as k,dr as l,$ as m,ur as p,De as r,Ir as s,Rr as t,Tr as w};
@@ -1 +1 @@
1
- import{f as r,p as a,h as s,i as l}from"./plan-CtBB0rrT.mjs";export{r as buildDevPlan,a as planDevCommand,s as resolveInspectorPort,l as resolveWorkerPort};
1
+ import{f as r,p as a,l as s,m as l}from"./plan-BzTGWr2e.mjs";export{r as buildDevPlan,a as planDevCommand,s as resolveInspectorPort,l as resolveWorkerPort};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/cli",
3
- "version": "1.0.0-alpha.331",
3
+ "version": "1.0.0-alpha.333",
4
4
  "description": "The Lunora CLI: init, dev, deploy, codegen, migrate, seed, doctor, insights, logs, registry, and the rest of the project commands",
5
5
  "keywords": [
6
6
  "agent-skills",
@@ -52,16 +52,16 @@
52
52
  },
53
53
  "dependencies": {
54
54
  "@bomb.sh/tab": "0.0.22",
55
- "@lunora/advisor": "1.0.0-alpha.176",
56
- "@lunora/bindings": "1.0.0-alpha.88",
57
- "@lunora/codegen": "1.0.0-alpha.244",
58
- "@lunora/config": "1.0.0-alpha.289",
55
+ "@lunora/advisor": "1.0.0-alpha.178",
56
+ "@lunora/bindings": "1.0.0-alpha.89",
57
+ "@lunora/codegen": "1.0.0-alpha.246",
58
+ "@lunora/config": "1.0.0-alpha.291",
59
59
  "@lunora/container": "1.0.0-alpha.64",
60
- "@lunora/d1": "1.0.0-alpha.155",
60
+ "@lunora/d1": "1.0.0-alpha.156",
61
61
  "@lunora/errors": "1.0.0-alpha.48",
62
- "@lunora/mcp": "1.0.0-alpha.202",
63
- "@lunora/runtime": "1.0.0-alpha.168",
64
- "@lunora/seed": "1.0.0-alpha.174",
62
+ "@lunora/mcp": "1.0.0-alpha.203",
63
+ "@lunora/runtime": "1.0.0-alpha.169",
64
+ "@lunora/seed": "1.0.0-alpha.176",
65
65
  "@visulima/cerebro": "3.1.1",
66
66
  "@visulima/error": "6.1.0",
67
67
  "@visulima/fs": "6.0.7",
@@ -306,6 +306,33 @@ export default defineModule({ description: "Invoices and payments", tables: ["in
306
306
  - Keep ids typed `Id<"table">` — a write through an untyped `string` id cannot
307
307
  be attributed to a table.
308
308
 
309
+ ## Services: calling sibling Workers
310
+
311
+ A Worker the app calls (a parser, an LLM gateway) is declared in
312
+ `lunora.config.ts`, not discovered. Each one becomes a typed `ctx.services.<key>`
313
+ on **actions** (not queries/mutations: a cross-Worker call cannot be replayed or
314
+ rolled back; HTTP actions reach it through `ctx.runAction`):
315
+
316
+ ```ts
317
+ // lunora.config.ts
318
+ export default {
319
+ services: {
320
+ documentParser: { dir: "services/document-parser" }, // fetch service
321
+ llmGateway: { dir: "services/llm-gateway", entrypoint: "Gateway" }, // RPC
322
+ },
323
+ };
324
+
325
+ // in an action
326
+ const parsed = await ctx.services.documentParser.fetch("https://parser/parse", { body, method: "POST" });
327
+ const text = await ctx.services.llmGateway.complete(prompt); // typed from the Gateway class
328
+ ```
329
+
330
+ - The Worker name and entry come from `<dir>/wrangler.jsonc`; Lunora writes the
331
+ `services[]` binding (`SERVICE_<KEY>`), runs it in the same `lunora dev` /
332
+ `vite dev` session, and deploys it before the app.
333
+ - A bound service needs no URL, no `*_URL` var and no HMAC: set
334
+ `"workers_dev": false` on it (`lunora doctor` warns otherwise).
335
+
309
336
  ## HTTP endpoints
310
337
 
311
338
  For webhooks or non-RPC HTTP, use `httpRouter` / `httpRoute` + `httpAction`:
@@ -1,2 +0,0 @@
1
- import{mkdirSync as A,readFileSync as S,lstatSync as B,writeFileSync as D}from"node:fs";import{join as m,dirname as y}from"node:path";import{fileURLToPath as E}from"node:url";import{isLunoraError as L,findSolutionByMessage as I}from"@lunora/errors";import{createCerebro as j}from"@visulima/cerebro";import T from"@visulima/cerebro/command/completion";import _ from"@visulima/cerebro/command/version";import{O as a}from"./output-format-B4eQHi5y.mjs";import{A as p,T as l}from"./deploy-target-DCWwiuAe.mjs";import{SDK_LANGUAGES as P}from"@lunora/codegen";import{exitCodeForError as U,EXIT_CODE as M}from"./EXIT_CODE-D_XCixv8.mjs";import{setCommandLogger as v,createLogger as x}from"./createLogger-Cl18I8AX.mjs";import{r as W}from"./render-lunora-error-C3OJY5wk.mjs";import{homedir as J}from"node:os";import{addArgsFor as F,detectPackageManager as K}from"@lunora/config";const H={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},a]},b="lunora.advisor.map.json",$={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/handler19.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 ${b})`,name:"baseline",type:String},{description:"Inspect a single procedure by `file#exportName`",name:"entry",type:String},a,{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 ${b})`,name:"out",type:String},{description:"Write the map artifact to disk (the default)",name:"write",type:Boolean},{description:"Don't write the map artifact to disk — report only",name:"no-write",type:Boolean}]},G={argument:{description:"gateway",name:"subcommand",type:String},description:"Provision a Cloudflare AI Gateway for ctx.ai and write its id into wrangler vars",examples:[["lunora ai gateway","Create (or reuse) a gateway named after the worker and wire it into wrangler vars"],["lunora ai gateway --id my-gateway","Use an explicit gateway id"],["lunora ai gateway --no-logs","Create the gateway with prompt/response log collection off"],["lunora ai gateway --dry-run","Print what would be created and written, without calling Cloudflare"]],group:"Deploy",loader:()=>import("../packem_chunks/handler20.mjs").then(e=>({default:e.execute})),name:"ai",options:[{description:"Gateway id (default: the worker `name` from wrangler.jsonc)",name:"id",type:String},{description:"Collect request/response logs in the gateway (default)",name:"logs",type:Boolean},{description:"Create the gateway with log collection off (prompts and responses are not stored)",name:"no-logs",type:Boolean},{description:"Print what would be created and written, without calling Cloudflare or editing files",name:"dry-run",type:Boolean},a]},V={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:[a]},q={argument:{description:"create | list | restore <id|file> | retention | prune | pitr",name:"subcommand",type:String},description:"Managed snapshot backups (create | list | restore) to a directory or an R2 bucket, 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 list --format json","Same, as a single JSON document on stdout"],["lunora backup restore <id>","Restore a snapshot by id"],["lunora backup create --bucket default","Snapshot into an R2 bucket instead of a directory"],["lunora backup restore <id> --bucket default --verify","Restore from R2, checksum first"],["lunora backup retention","Show what the platform's retention would delete next"],["lunora backup prune","Delete the snapshots past the retention window (the only command that deletes backups)"],["lunora backup pitr --at 2026-06-01T00:00:00Z","Point-in-time recovery (≤30 days)"]],group:"Data",loader:()=>import("../packem_chunks/handler24.mjs").then(e=>({default:e.execute})),name:"backup",options:[{description:"Backup directory (default .lunora-backups)",name:"dir",type:String},{description:"Store snapshots in this R2 bucket instead of a directory (use `default` for the app's default bucket)",name:"bucket",type:String},{description:"Key prefix for bucket-backed snapshots (default backups/)",name:"prefix",type:String},{description:"restore: verify the snapshot's checksum before importing anything",name:"verify",type:Boolean},{description:"Comma-separated table allowlist (create)",name:"tables",type:String},a,{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 destructive step without prompting: a production pitr --restore, or backup prune",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:"Codegen + validate + bundle the Worker to disk without deploying",examples:[["lunora build","Bundle to .lunora/build without deploying"],["lunora build --out-dir dist-worker","Bundle to a custom directory"],["lunora build --emit-bindings bindings.json","Also write what the bundle needs provisioned, for an external deployer"]],group:"Deploy",loader:()=>import("../packem_chunks/handler21.mjs").then(e=>({default:e.execute})),name:"build",options:[{description:"Override the schema-drift gate for this run (build even with breaking schema drift and no migration; the committed baseline is not advanced)",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${p} (default openapi)`,name:"api-spec",type:String},{description:"Write a JSON manifest of the bindings + crons the bundle needs to this path, for an IaC program to consume",name:"emit-bindings",type:String},a,{description:"Directory to write the bundled Worker to (default .lunora/build)",name:"out-dir",type:String},{description:"Fail the build on ERROR-level codegen advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail the build on ERROR-level codegen advisories (the gate defaults to on in CI, off locally). Never downgrades platform diagnostics.",name:"no-strict-advisories",type:Boolean},l]},Y={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},a,{description:"Fail on ERROR-level advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail on ERROR-level advisories (the gate defaults to on in CI, off locally)",name:"no-strict-advisories",type:Boolean},l]},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 list --format json","List container instances as JSON (also `info`, `images list`)"],["lunora containers images delete transcoder:v1","Delete an image to free registry storage"]],group:"Deploy",loader:()=>import("../packem_chunks/handler3.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},{...a,description:"Output format: pretty (default) or json (read subcommands: list | info | images list)"}]},X={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 --migrate-yes --migrate-url <url>","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 for this run (deploy even with breaking schema drift and no migration; the committed baseline is not advanced — use --update-schema-baseline to accept the new shape)",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},a,{description:"After the deploy, probe the new version's health route (/_lunora/health/ready, falling back to /_lunora/health) and fail if it never answers",name:"health-check",type:Boolean},{description:"After a successful deploy, run pending data migrations against the live worker",name:"migrate",type:Boolean},{description:"Skip codegen + the schema-drift gate (assumes `lunora build`/`prepare` already ran in this CI run). Wrangler still bundles the worker.",name:"prebuilt",type:Boolean},{description:"Admin bearer token for --migrate (falls back to LUNORA_ADMIN_TOKEN)",name:"migrate-token",type:String},{description:"Worker URL for --migrate (REQUIRED with --migrate; the deploy target URL is not captured automatically)",name:"migrate-url",type:String},{description:"Confirm running the production data migration triggered by --migrate (required with --migrate)",name:"migrate-yes",type:Boolean},{description:"Fail the deploy on ERROR-level codegen advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail the deploy on ERROR-level codegen advisories (the gate defaults to on in CI, off locally). Never downgrades platform diagnostics.",name:"no-strict-advisories",type:Boolean},{description:"Upload a preview version (wrangler versions upload) instead of going live — prints a preview URL; doesn't shift production traffic",name:"preview",type:Boolean},l,{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/handler4.mjs").then(e=>({default:e.execute})),name:"deployments",options:[{description:"Cloudflare environment name",name:"env",type:String},{...a,description:"Output format: pretty (default) or json (`list` only)"},{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}]},ee={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, ready/starting)"],["lunora dev status --json","Same as JSON — poll `.ready` to gate a dependent step in a task graph"],["lunora dev logs","Print the captured dev-server log (background runs)"],["lunora dev --json","Stream machine-readable JSON log LINES (a stream, not a --format json document)"],["lunora dev --emit-bindings dev-manifest.json","Write what this worker needs + where it serves, for a task runner"],["lunora dev --no-studio","Skip the embedded studio server"],["lunora dev --worker-port 8080","Use a custom wrangler dev port"],["lunora dev --inspector-port 9235","Pin wrangler's devtools inspector port instead of letting it walk up from 9229"],["lunora dev --remote","Proxy D1/KV/R2 to the deployed worker (also LUNORA_REMOTE=1)"]],group:"Develop",loader:()=>import("../packem_chunks/runDevCommand.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:"Write the binding manifest (plus the dev origin) to <file>, for a supervisor that owns the rest of the graph",name:"emit-bindings",type:String},{description:"wrangler dev inspector port, for `wrangler dev` only (defaults to `dev.inspector_port` in wrangler.jsonc; unset, wrangler probes upward from 9229 and can take a sibling worker's pinned port)",name:"inspector-port",type:Number},{description:"Studio server port (default 6173)",name:"port",type:Number},l,{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:"Machine-readable JSON log lines while the server runs, and a JSON result for `dev status`/`dev stop` (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:"Serve the embedded studio at /__lunora (default)",name:"studio",type:Boolean},{description:"Don't start the embedded studio server",name:"no-studio",type:Boolean},{description:"Spawn wrangler dev for the worker (default)",name:"worker",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:"Run codegen on startup and watch for changes (default)",name:"codegen",type:Boolean},{description:"Don't run codegen — no watch, no startup generate (or set LUNORA_CODEGEN=0)",name:"no-codegen",type:Boolean},{description:"Proxy D1/KV/R2 bindings to the deployed worker (or set LUNORA_REMOTE=1)",name:"remote",type:Boolean}]},te={argument:{description:"Optional path under the docs site (e.g. packages/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 packages/studio","Open a specific docs section"]],group:"Project",loader:()=>import("../packem_chunks/handler5.mjs").then(e=>({default:e.execute})),name:"docs"},re={description:"Preflight the current Lunora project (wrangler bindings, placeholders, dev secrets)",examples:[["lunora doctor","Run the project preflight checks"],["lunora doctor --format json","Emit the findings as a machine-readable JSON document"]],group:"Project",loader:()=>import("../packem_chunks/handler22.mjs").then(e=>({default:e.execute})),name:"doctor",options:[a]},oe={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"],["lunora env diff --format json","Same, as a single JSON document on stdout"]],group:"Data",loader:()=>import("../packem_chunks/handler6.mjs").then(e=>({default:e.execute})),name:"env",options:[{description:"Target this Cloudflare environment for `push`/`diff` (passes --env <name> to wrangler)",name:"env",type:String},{description:"Alias for --env production",name:"prod",type:Boolean},a,{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}]},ne={description:"Run every *.eval.ts under evals/ via @lunora/testing's evaluate/agentHarness — no live worker needed",examples:[["lunora eval","Run every eval under evals/, print the aggregate table"],["lunora eval --threshold 0.8","Non-zero exit if any eval's average score falls below 0.8"],["lunora eval --dir evals/support --format json","Run a subset and emit a machine-readable result"]],group:"Develop",loader:()=>import("../packem_chunks/handler25.mjs").then(e=>({default:e.execute})),name:"eval",options:[{description:"Directory to discover *.eval.ts files under (default evals/)",name:"dir",type:String},a,{description:"Score gate every eval's average must meet ([0,1]); a per-eval `threshold` export wins over this for that eval",name:"threshold",type:Number}]},ae={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"],["lunora export --out backup.ndjson --format json","Write the dump to a file and report rows/bytes as JSON"]],group:"Data",loader:()=>import("../packem_chunks/handler7.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},{...a,description:"Output format: pretty (default) or json — json needs --out <file>, since stdout carries the NDJSON"},{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}]},ie={argument:{description:"Source NDJSON file, or a `npx convex export --path <dir>` directory",name:"file",type:String},description:"Bulk-insert rows from an NDJSON file — or a Convex export directory — via the worker's admin endpoint",examples:[["lunora import backup.ndjson","Bulk-insert rows from an NDJSON file"],["lunora import ./convex-export","Import a `npx convex export --path` directory (ids are preserved, so no remapping)"],["lunora import ./convex-export --with-storage","Also migrate blobs (verified sha256 upload) + `{ $storage }` refs"],["lunora import ./convex-export --scan","Write a candidate `lunora/import-convex.json` storage-column mapping (imports nothing)"],["lunora import ./snapshot.zip --with-storage --verify","Import a `npx convex export --path` zip snapshot with blob + row-parity checks"],["lunora import ./supabase-csv --from supabase","Import a directory of `COPY … TO STDOUT WITH CSV HEADER` dumps"],["lunora import ./firestore-json --from firebase --verify","Import Firestore documents (REST/Admin-SDK JSON) with row-parity checks"]],group:"Data",loader:()=>import("../packem_chunks/handler8.mjs").then(e=>({default:e.execute})),name:"import",options:[{description:"Source reader for a dump that cannot be detected: supabase | firebase (Convex and NDJSON are auto-detected)",name:"from",type:String},{description:"Wrap each bare doc as `{table:<name>,doc:...}`",name:"table",type:String},a,{description:"Rows per HTTP request (default 500)",name:"batch-size",type:Number},{description:"Also migrate file storage — Convex `_storage` blobs, or a Supabase/Firebase bucket (verified upload)",name:"with-storage",type:Boolean},{description:"Directory of storage objects to upload alongside the rows (Firebase: after `gcloud storage cp -r`)",name:"storage-dir",type:String},{description:"Write a candidate `lunora/import-convex.json` storage-column mapping and exit",name:"scan",type:Boolean},{description:"Verify row parity + dangling-storage after import (non-zero exit on mismatch)",name:"verify",type:Boolean},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Confirm bulk-writing production (required with --prod)",name:"yes",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String}]},se={description:"Print resolved project config: @lunora/* versions, wrangler summary, schema overview",examples:[["lunora info","Print resolved project config"],["lunora info --format json","Emit a JSON snapshot"],["lunora info --bindings","List what this Worker needs provisioned: bindings, crons, vars"],["lunora info --bindings --format json","Emit the manifest a deployer or task runner consumes"],["lunora info --bindings --out reqs.json","Write that manifest to a file"]],group:"Project",loader:()=>import("../packem_chunks/handler9.mjs").then(e=>({default:e.execute})),name:"info",options:[{description:"Report only what this Worker needs provisioned, as the binding manifest",name:"bindings",type:Boolean},a,{description:"With --bindings: write the manifest to <file> instead of stdout",name:"out",type:String}]},le={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 -t solid-v2","Scaffold a Solid 2.0 SPA"],["lunora init my-app -t rspack-react","Scaffold a React SPA on Rsbuild"],["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:"Template: analog | astro | expo | next | nuxt | react-router | rspack-react | solid-v2 | standalone | sveltekit | tanstack-start-react | tanstack-start-react-rspack | tanstack-start-solid | vinext | vinext-pages. Also accepts an overlay framework (react | vue | solid | svelte), same as --vite.",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 | auth-ui | 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}]},de={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 --format 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/handler10.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},a,{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}]},pe={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/handler27.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 (the default)",name:"procedures",type:Boolean},{description:"Emit only the schema — skip the per-table list/get procedure modules",name:"no-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},a]},ce={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/handler11.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}]},ue={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/handler26.mjs").then(e=>({default:e.execute})),name:"logs",options:[{description:"Cloudflare environment name",name:"env",type:String},a,{description:"Substring filter on log messages",name:"search",type:String},{description:"Filter by invocation status: ok, error, or canceled",name:"status",type:String},l,{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}]},me={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"],["lunora mcp serve --token $LUNORA_ADMIN_TOKEN","Expose the observability tools (logs, issues, advisories, insights, migrations) too"]],group:"Develop",loader:()=>import("../packem_chunks/handler28.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: expose the documentation tools (default)",name:"docs",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). Also gates the observability tools (logs, issues, advisories, query insights, migration status) — without a token they are not exposed at all",name:"token",type:String}]},ge={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 status backfill-names --format json","Same, as a single JSON document on stdout"],["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/dispatch.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},a,{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}]},he={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/handler12.mjs").then(e=>({default:e.execute})),name:"prepare",options:[{description:"Override the schema-drift gate for this run (proceed even with breaking schema drift and no migration; the committed baseline is not advanced)",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${p} (default openapi)`,name:"api-spec",type:String},{description:"Fail on ERROR-level codegen advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail on ERROR-level codegen advisories (the gate defaults to on in CI, off locally). Never downgrades platform diagnostics.",name:"no-strict-advisories",type:Boolean},l,{description:"Re-bless the committed schema baseline (lunora/.lunora-schema.json) with the current shape",name:"update-schema-baseline",type:Boolean}]},fe={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 --from ./registry --check","Verify the committed catalog is current"]],group:"Project",loader:()=>import("../packem_chunks/handler13.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},{...a,description:"Output format: pretty (default) or json (add plan / list)"},{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}]},ye={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}]},ve={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/handler14.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}]},be={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)"],["lunora run messages:list --format json","Emit the RPC result as a single JSON document on stdout"]],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},a,{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}]},we={argument:{description:"<generate>",name:"args",type:String},description:"Generate a self-contained typed client SDK for another language from the project's OpenRPC surface",examples:[["lunora sdk generate --lang python","Emit a Python SDK, transport included, into ./sdk/python"],["lunora sdk generate --lang go --out ./clients/go","Choose the language and output directory"],["lunora sdk generate --lang dart","A Flutter-ready Dart client — live queries arrive as a Stream"],["lunora sdk generate --lang kotlin","Any of the registered targets; --lang lists them"],["lunora sdk generate --lang rust --from ./sdks","Copy the transport from a local checkout instead of fetching it"]],group:"Project",loader:()=>import("../packem_chunks/handler23.mjs").then(e=>({default:e.execute})),name:"sdk",options:[{description:`Target language: ${P.join(" | ")}`,name:"lang",type:String},{description:"Output directory (default ./sdk/<lang>)",name:"out",type:String},{description:"Path to the OpenRPC document (default ./lunora/_generated/openrpc.json)",name:"spec",type:String},{description:"Copy the transport from a local directory of per-language transports (the repo's `sdks/`) instead of fetching it",name:"from",type:String},{description:"Git ref to fetch the transport from (default: this CLI's own release tag, so the transport matches the generated surface)",name:"ref",type:String},{description:"Override the remote transport source base (default gh:anolilab/lunora/sdks)",name:"source",type:String},{description:"Permit --source values outside gh:/github:/https://",name:"allow-unsafe-source",type:Boolean}]},ke={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 --format json","Report generated / inserted / conflicts per table as JSON"],["lunora seed --seed 7 --now 1785000000000","Byte-identical rows across runs (pins the clock too)"]],group:"Data",loader:()=>import("../packem_chunks/handler15.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},a,{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}]},Se={argument:{description:"prune",name:"subcommand",type:String},description:"Maintain the shard registry: prune shards that no longer hold any rows of their .shardBy() table",examples:[["lunora shards prune --dry-run","Show which registered shards are empty, without removing anything"],["lunora shards prune","Remove the empty shards from the registry"],["lunora shards prune --tables messages","Only prune the shards listed for `messages`"],["lunora shards prune --prod --url https://app.example.com","Prune production"]],group:"Data",loader:()=>import("../packem_chunks/handler16.mjs").then(e=>({default:e.execute})),name:"shards",options:[{description:"Comma-separated .shardBy() tables (default: all of them)",name:"tables",type:String},{description:"Report what would be pruned without changing the registry",name:"dry-run",type:Boolean},a,{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (defaults to the running dev server)",name:"url",type:String},{description:"Admin bearer token (or LUNORA_ADMIN_TOKEN)",name:"token",type:String}]},xe={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"],["lunora verify --env production","Validate the env.production view, as `lunora deploy --env production` will"]],group:"Deploy",loader:()=>import("../packem_chunks/handler17.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:"Cloudflare environment name — validate the env.<name> view of wrangler.jsonc, as `lunora deploy --env` does",name:"env",type:String},a,{description:"Probe this deployment's /_lunora/health endpoint (off by default; keeps verify offline-safe)",name:"health-url",type:String},{description:"Fail verification on ERROR-level codegen advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail verification on ERROR-level codegen advisories (the gate defaults to on in CI, off locally). Never downgrades platform diagnostics.",name:"no-strict-advisories",type:Boolean},{description:"Run the TypeScript type-check step (default)",name:"typecheck",type:Boolean},{description:"Skip the TypeScript type-check step",name:"no-typecheck",type:Boolean},l]},Ce={description:"Open the Lunora studio in your browser (the running dev server's, or the default local one)",examples:[["lunora view","Open the studio for the running dev server"]],group:"Project",loader:()=>import("../packem_chunks/handler18.mjs").then(e=>({default:e.execute})),name:"view"},Re=(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 i=1;i<=t.length;i+=1){const s=r[i]??0,c=e[o-1]===t[i-1]?0:1;r[i]=Math.min((r[i-1]??0)+1,s+1,n+c),n=s}}return r[t.length]??0},Ne=(e,t)=>{let r,o=Number.POSITIVE_INFINITY;for(const i of t){const s=Re(e,i);s<o&&(o=s,r=i)}const n=Math.max(2,Math.ceil(e.length/3));return r!==void 0&&o<=n?r:void 0},Oe=e=>`https://registry.npmjs.org/@lunora/cli/${e}`,Ae=1440*60*1e3,Be=1500,De="0.0.0",Ee=/^v/u,Le=new Set(["alpha","beta","next"]),g=e=>{const t=e.trim().replace(Ee,""),r=t.indexOf("-");return r===-1?{core:t,prerelease:""}:{core:t.slice(0,r),prerelease:t.slice(r+1)}},w=e=>{const[t,r,o]=g(e).core.split(".").map(n=>{const i=Number.parseInt(n,10);return Number.isFinite(i)?i:0});return[t??0,r??0,o??0]},Ie=(e,t)=>{const r=Number.parseInt(e,10),o=Number.parseInt(t,10);return String(r)===e&&String(o)===t?r>o?1:-1:e>t?1:-1},je=(e,t)=>{if(e===t)return 0;if(e===""||t==="")return e===""?1:-1;const r=e.split("."),o=t.split(".");for(let n=0;n<Math.max(r.length,o.length);n+=1){const i=r[n],s=o[n];if(i===void 0||s===void 0)return i===void 0?-1:1;if(i!==s)return Ie(i,s)}return 0},Te=(e,t)=>{const r=w(e),o=w(t);for(let n=0;n<3;n+=1)if((r[n]??0)!==(o[n]??0))return(r[n]??0)>(o[n]??0)?1:-1;return je(g(e).prerelease,g(t).prerelease)},_e=e=>{const t=g(e).prerelease.split(".")[0]??"";return Le.has(t)?t:"latest"},Pe=(e,t)=>Te(t,e)>0,Ue=(e,t,r)=>t-e<r,Me=(e,t,r="latest",o)=>{const n=`Update available for @lunora/cli: ${e} → ${t}`;if(o===void 0)return`${n} — add @lunora/cli@${r} as a dev dependency to update`;const{args:i,command:s}=F(o,[`@lunora/cli@${r}`],{dev:!0});return`${n} — run \`${s} ${i.join(" ")}\``},C=e=>m(e,"lunora-cli-update.json"),We=e=>{const t=e.XDG_CACHE_HOME&&e.XDG_CACHE_HOME.length>0?e.XDG_CACHE_HOME:m(J(),".cache"),r=m(t,"lunora");try{A(r,{mode:448,recursive:!0})}catch{}return r},Je=e=>{try{const t=JSON.parse(S(C(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{}},k=(e,t)=>{try{const r=C(e);try{if(B(r).isSymbolicLink())return}catch{}D(r,`${JSON.stringify(t)}
2
- `,"utf8")}catch{}},Fe=async(e,t)=>{try{const r=await e(Oe(t),{signal:AbortSignal.timeout(Be)});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}},Ke=(e,t,r)=>e===De||!r||t.CI!==void 0||t.LUNORA_NO_UPDATE_NOTIFIER!==void 0,He=async e=>{const t=e.env??process.env,r=e.isTTY??process.stdout.isTTY;if(Ke(e.current,t,r))return;const o=e.cacheDir??We(t),n=(e.now??Date.now)(),i=e.ttlMs??Ae,s=_e(e.current),c=Je(o),O=c?.tag??"latest",h=c!==void 0&&O===s?c:void 0;let u=h?.latest;if(h===void 0||!Ue(h.checkedAt,n,i)){const f=await Fe(e.fetchImpl??globalThis.fetch,s);f===void 0?k(o,{checkedAt:n,latest:e.current,tag:s}):(u=f,k(o,{checkedAt:n,latest:f,tag:s}))}u!==void 0&&Pe(e.current,u)&&e.logger.warn(Me(e.current,u,s,e.manager))},$e=["init","add","dev","codegen","build","deploy","containers","ai","prepare","link","deployments","logs","run","insights","reset","migrate","export","import","seed","shards","backup","eval","verify","info","doctor","env","analyze","view","docs","registry","rules","mcp"],Ge=8,Ve=()=>{try{let e=y(E(import.meta.url));for(let t=0;t<Ge;t+=1){try{const o=JSON.parse(S(m(e,"package.json"),"utf8")),n=o!==null&&typeof o=="object"?o:void 0;if(n?.name==="@lunora/cli"&&typeof n.version=="string"&&n.version.length>0)return n.version}catch{}const r=y(e);if(r===e)break;e=r}}catch{}return"0.0.0"},R=Ve(),qe=[le,H,ee,Y,$,z,X,Q,G,he,ce,Z,ue,be,de,ye,ge,ae,ie,ke,Se,pe,q,ne,xe,se,re,oe,V,Ce,te,fe,ve,me,we],N=[...qe,_,T],ft=N.map(e=>e.name),d=e=>e.replaceAll("{",String.raw`\{`).replaceAll("}",String.raw`\}`),ze=e=>e.every(t=>typeof t=="string")?e.map(t=>d(t)):e.map(t=>typeof t=="string"?[d(t)]:t.map(r=>d(r))),Ye=e=>({...e,...e.argument===void 0?{}:{argument:{...e.argument,description:d(e.argument.description??"")}},...e.description===void 0?{}:{description:d(e.description)},...e.examples===void 0?{}:{examples:ze(e.examples)},...e.options===void 0?{}:{options:e.options.map(t=>({...t,description:d(t.description??"")}))}}),Qe=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:R});for(const o of N)r.addCommand(Ye(o));return{cli:r,exitCode:t}},Xe=/Command "(?<name>[^"]+)" not found/u,Ze=e=>{const t=x(),r=e instanceof Error?e.message:String(e),o=Xe.exec(r);if(!o?.groups)return L(e)||I(r)!==void 0?t.error(W(e)):t.error(r),U(e);const n=o.groups.name??"",i=Ne(n,$e);return t.error(`Unknown command "${n}".${i===void 0?"":` Did you mean "${i}"?`}`),t.info("Run `lunora --help` to list commands, or `lunora docs` to open the documentation."),M.USAGE},et=e=>({debug:t=>{e.debug(t)},error:t=>{e.error(t)},info:t=>{e.info(t)},success:t=>{e.info(t)},warn:t=>{e.warn(t)}}),yt=async(e={})=>{const{cli:t,exitCode:r}=Qe(e);e.logger!==void 0&&v(et(e.logger));try{await t.run({shouldExitProcess:!1})}catch(n){return Ze(n)}finally{v(void 0)}let o;try{o=K(process.cwd())}catch{}return await He({current:R,logger:x(),manager:o}),r.value};export{$e as C,b as D,ft as R,R as V,yt as r};
@@ -1,5 +0,0 @@
1
- import{existsSync as T,readFileSync as E,mkdirSync as re,openSync as N,closeSync as F,statSync as te,readSync as oe}from"node:fs";import{join as w,dirname as ne}from"node:path";import{targetRunsOwnDevServer as P,resolveProjectTarget as x,claimDevServerState as se,DEV_HANDOFF_ENV as ae,clearDevServerState as m,readDevServerState as y,readLiveDevServerState as C,isDevServerReady as A,detectFramework as M,readProjectDependencyNames as ie,DEV_LOG_FILE_ENV as ce,DEV_DAEMON_ENV as de,updateDevServerState as le,detectPackageManager as b,execArgsFor as U,isRecordedProcessCurrent as ue,DEV_LOG_FILE as ve,CODEGEN_ENV as j,isCodegenDisabled as ge,planToolchainInvocation as pe,toolchainExecArgs as V,resolveDeployDriver as G,DEV_VARS_FILE as W,runScriptCommand as fe,parseDevVariableEntries as me}from"@lunora/config";import{findWranglerFile as _,readWranglerJsonc as L,materializeRemoteWranglerConfig as we}from"@lunora/config/cloudflare";import{createServer as he}from"node:net";import{networkInterfaces as Se}from"node:os";import{spawnSync as D,spawn as ke}from"node:child_process";import{setTimeout as h}from"node:timers/promises";import{EXIT_CODE as B}from"./EXIT_CODE-D_XCixv8.mjs";import{a as p}from"./output-format-B4eQHi5y.mjs";import{spawnShellCompat as Ee}from"./createRecordingSpawner-sS7LEN7x.mjs";const Pe=12e4,K=250,ye=1e3,be="LUNORA_DEV_READY_TIMEOUT_MS",_e=e=>{if(e!==void 0)return e;const r=Number(process.env[be]??"");return Number.isFinite(r)&&r>0?r:Pe},Le=async(e,r)=>{try{const o=AbortSignal.timeout(ye);return await(await fetch(new URL("/_lunora/status",e),{redirect:"manual",signal:r===void 0?o:AbortSignal.any([r,o])})).body?.cancel(),!0}catch{return!1}},De=1e4,Oe=100,Ae=40,f=256*1024,Re=new Set(["nuxt","sveltekit"]),Ie=["@lunora/rspack","@lunora/vite"],O=e=>{if(Re.has(M(e).framework))return"framework-worker";const r=ie(e);return Ie.some(o=>r.has(o))?"vite":"wrangler"},H=e=>{const r=b(e);let o;try{const t=E(w(e,"package.json"),"utf8");o=JSON.parse(t).scripts?.dev}catch{}if(o===void 0||o.trim()===""||o.includes("lunora")){const t=U(r,"vite",["dev"]);return{args:t.args,command:t.command}}return{args:["run","dev"],command:r}},$e=e=>{re(ne(e.logPath),{recursive:!0});const r=N(e.logPath,"w",384);let o;const t=Ee(e.command,e.args);try{o=ke(t.command,t.args,{cwd:e.cwd,detached:!0,env:e.env,shell:t.shell,stdio:["ignore",r,r],windowsHide:!0})}finally{F(r)}return o.unref(),{exited:new Promise(n=>{o.on("error",()=>{n(1)}),o.on("exit",(s,a)=>{n(s??(a?1:0))})}),pid:o.pid}},Te=e=>{try{const{size:r}=te(e);if(r<=f)return E(e,"utf8");const o=N(e,"r");try{const t=Buffer.alloc(f),n=oe(o,t,0,f,r-f),s=t.toString("utf8",0,n);return s.slice(s.indexOf(`
2
- `)+1)}finally{F(o)}}catch{return}},z=(e,r)=>{const o=Te(e);if(o===void 0)return[];const t=o.split(`
3
- `);return t.at(-1)===""&&t.pop(),r>0?t.slice(-r):t},J=(e,r)=>r?.logFile??w(e,ve),Y=e=>{e.info(" Stop: lunora dev stop"),e.info(" Status: lunora dev status"),e.info(" Logs: lunora dev logs")},Ne=(e,r)=>{e.warn(`Dev server already running at ${r.url} (pid ${String(r.pid)})`),Y(e)},Fe=(e,r)=>{e.success(`Dev server running at ${r.url} (pid ${String(r.pid)})`),r.studioUrl!==void 0&&e.info(` Studio: ${r.studioUrl}`),Y(e)},xe=async e=>{const{child:r,cwd:o,deadline:t,pollIntervalMs:n,probe:s}=e,a=r.exited.then(i=>({exitCode:i}));for(;Date.now()<t;){const i=C(o);if(i!==void 0&&i.pid!==process.pid&&await s(i.url))return{state:i,status:"ready"};const c=await Promise.race([a,h(n)]);if(c!==void 0)return{...c,status:"exited"}}return{status:"timeout"}},Ce=async e=>{const{cwd:r,logger:o}=e,t=J(r,void 0),n=_e(e.readyTimeoutMs),s=(e.spawnDetached??$e)({args:e.command.args,command:e.command.command,cwd:r,env:{...process.env,...e.env,[de]:"1",[ce]:t,...process.env.FORCE_COLOR===void 0?{NO_COLOR:"1"}:{},...e.json?{LUNORA_LOG_JSON:"1"}:{}},logPath:t}),a=await xe({child:s,cwd:r,deadline:Date.now()+n,pollIntervalMs:e.pollIntervalMs??K,probe:e.probe??Le});if(a.status==="ready")return Fe(o,a.state),{code:0};if(a.status==="exited"){o.error(`dev server exited before becoming ready (exit code ${String(a.exitCode)}). Last output:`);for(const c of z(t,Ae))o.error(` ${c}`);return m(r,s.pid??process.pid),{code:a.exitCode===0?1:a.exitCode}}s.pid!==void 0&&y(r)?.pid===process.pid&&le(r,{logFile:t,pid:s.pid});const i=s.pid===void 0?"":` (pid ${String(s.pid)})`;return o.warn(`dev server did not confirm ready within ${String(Math.round(n/1e3))}s — it may still be compiling${i}. Check \`lunora dev status\` and \`lunora dev logs\`; \`lunora dev stop\` shuts it down.`),{code:B.UNAVAILABLE}},X=e=>e.codegen!==!1&&!ge(process.env[j]),q=e=>{const r={...e.remote===!0?{LUNORA_REMOTE:"1"}:{},...e.codegen===!1?{[j]:"0"}:{}};return Object.keys(r).length>0?{env:r}:{}},Me=(e,r)=>{const o=["dev"];return e.apiSpec!==void 0&&o.push("--api-spec",e.apiSpec),e.port!==void 0&&o.push("--port",String(e.port)),e.workerPort!==void 0&&o.push("--worker-port",String(e.workerPort)),e.inspectorPort!==void 0&&o.push("--inspector-port",String(e.inspectorPort)),e.emitBindings!==void 0&&o.push("--emit-bindings",e.emitBindings),e.codegen===!1&&o.push("--no-codegen"),e.studio===!1&&o.push("--no-studio"),e.worker===!1&&o.push("--no-worker"),e.target!==void 0&&o.push("--target",e.target),r&&o.push("--remote"),o},gr=async e=>{const{cwd:r,jsonLogs:o,logger:t,options:n,remote:s}=e,a=e.run??Ce,i=O(r),c=i==="vite"&&P(n.target??x(r))?"wrangler":i,u=c==="wrangler"?`http://localhost:${String(n.workerPort??8787)}`:"http://localhost:5173",d=se(r,{background:!0,mode:"cli",pid:process.pid,startedAt:new Date().toISOString(),url:u});if(!d.ok)return d.existing!==void 0&&Ne(t,d.existing),{code:0};const l={[ae]:String(process.pid)};try{return c==="vite"?await a({command:H(r),cwd:r,env:{...q({...n,remote:s}).env,...l},json:o,logger:t}):await a({command:{args:[process.argv[1]??"lunora",...Me(n,s)],command:process.execPath},cwd:r,env:l,json:o,logger:t})}finally{m(r,process.pid)}},Ue=e=>{try{const r=D("ps",["-o","pgid=","-p",String(e)],{encoding:"utf8"}),o=Number.parseInt(r.stdout.trim(),10);return Number.isInteger(o)&&o>0?o:void 0}catch{return}},je=(e,r,o=process.platform,t=D)=>{if(o==="win32"){try{t("taskkill",["/pid",String(e.pid),"/T","/F"],{stdio:"ignore"})}catch{}return}if(e.background===!0)try{r(-(Ue(e.pid)??e.pid),"SIGKILL");return}catch{}try{r(e.pid,"SIGKILL")}catch{}},Ve=(e,r)=>(r.json?p({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}),Ge=async e=>{const{cwd:r,logger:o}=e,t=y(r),n=e.alive??(l=>l===t?.pid&&ue(t)),s=e.signal??((l,v)=>{process.kill(l,v)}),a=e.pollIntervalMs??K,i=e.stopGraceMs??De,c=e.platform??process.platform,u=e.spawnSyncImpl??D;if(t===void 0||!n(t.pid))return t!==void 0&&m(r,t.pid),e.json?p({running:!1,stopped:!1}):o.info("No dev server running."),{code:0};try{s(t.pid,"SIGTERM")}catch{}const d=Date.now()+i;for(;n(t.pid)&&Date.now()<d;)await h(a);return n(t.pid)&&(je(t,s,c,u),await h(a),n(t.pid))?Ve(t,e):(m(r,t.pid),e.json?p({pid:t.pid,stopped:!0}):o.success(`Stopped dev server (pid ${String(t.pid)}).`),{code:0})},We=e=>{const{cwd:r,logger:o}=e,t=C(r);if(t===void 0)return e.json?p({running:!1}):o.info("No dev server running."),{code:0};const n=e.now??Date.now,s=t.startedAt===void 0?Number.NaN:Date.parse(t.startedAt),a=Number.isFinite(s)?Math.max(0,Math.round((n()-s)/1e3)):void 0;if(e.json)return p({background:t.background===!0,logFile:t.logFile,mode:t.mode,pid:t.pid,ready:A(t),readyAt:t.readyAt,running:!0,startedAt:t.startedAt,studioUrl:t.studioUrl,uptimeSeconds:a,url:t.url}),{code:0};const i=[`pid ${String(t.pid)}`,...a===void 0?[]:[`uptime ${String(a)}s`],t.background===!0?"background":"foreground",A(t)?"ready":"starting"];return o.success(`Dev server running at ${t.url} (${i.join(", ")})`),t.studioUrl!==void 0&&o.info(` Studio: ${t.studioUrl}`),t.logFile!==void 0&&o.info(` Logs: lunora dev logs (${t.logFile})`),{code:0}},Be=e=>{const{cwd:r,logger:o}=e,t=y(r),n=J(r,t);if(!T(n))return o.info("No dev server logs found — output is captured when the server runs in background mode (`lunora dev --background`)."),{code:0};const s=z(n,e.lines??Oe);return s.length>0&&process.stdout.write(`${s.join(`
4
- `)}
5
- `),{code:0}},pr=e=>{const{cwd:r,json:o,lines:t,logger:n,subcommand:s}=e;if(s==="stop")return Ge({cwd:r,json:o,logger:n});if(s==="status")return We({cwd:r,json:o,logger:n});if(s==="logs")return Be({cwd:r,lines:t,logger:n});if(s!==void 0)return n.error(`dev: unknown subcommand "${s}" — expected stop | status | logs (or no subcommand to start the dev server)`),{code:B.USAGE}},fr=(e,r,o)=>P(e)?(r!=="wrangler"&&o.info(`target ${e} runs its own dev server, so lunora dev serves the worker on it — start the frontend's dev server separately`),"wrangler"):r,Ke=e=>{const{cwd:r,driver:o,options:t,studioPort:n,workerPort:s}=e,{projectConfig:a,toolchain:i}=o;if(a===void 0||i===void 0)throw new Error(`deploy target "${o.id}" runs its own dev server but ships no config projection or toolchain for it`);if(t.remote===!0)throw new Error(`--remote proxies bindings to Cloudflare; ${o.name} has no remote bindings to proxy to`);t.inspectorPort!==void 0&&t.logger.warn(`--inspector-port is a wrangler dev flag; ${o.name} dev has no inspector to pin`);const{command:c,commit:u,projection:d}=pe(o,r,"dev",v=>i.dev({configPath:v,extraArgs:["--port",String(s)]}));u(),d!==void 0&&d.dropped.length>0&&t.logger.info(`${o.name} ignores these wrangler keys, so its dev server runs without them: ${d.dropped.join(", ")}`);const l=V(b(r),c);return{flavor:"wrangler",ipv4LoopbackForced:!1,remote:{bindings:[],cleanup:()=>{},enabled:!1},runsCodegenWatch:X(t),studioEnabled:t.studio!==!1,studioPort:n,workerEnabled:t.worker!==!1,workerOrigin:`http://localhost:${String(s)}`,workerPort:s,wrangler:{args:l.args,command:l.command,cwd:r,tag:c.tool}}},He=64,Q="127.0.0.1",ze=65535,Je=(e,r=Q)=>new Promise(o=>{const t=he();t.once("error",()=>{o(!1)}),t.once("listening",()=>{t.close(()=>{o(!0)})}),t.listen(e,r)}),Ye=async(e,r=Q,o=He)=>{for(let t=e;t<e+o&&t<=ze;t+=1)if(await Je(t,r))return t;return e},Z=(e=Se)=>Object.values(e()).some(r=>r?.some(o=>o.internal&&o.address==="::1")),S="wrangler.dev.jsonc",k=6173,g=8787,R=5173,Xe=(e,r)=>{const o=()=>{};if(!e.remote)return{args:[],plan:{bindings:[],cleanup:o,enabled:!1}};const n=(e.materializeRemote??we)({enabled:!0,projectRoot:r}),s=n.remoteBindings.map(i=>`${i.binding} (${i.kind})`),{cleanup:a}=n;return n.configPath===void 0?{args:[],plan:{bindings:s,cleanup:a,enabled:!0,reason:n.reason}}:{args:["--config",n.configPath],plan:{bindings:s,cleanup:a,enabled:!0}}},I=e=>L(e).parsed?.dev?.ip,ee=(e,r,o)=>{if(o!==void 0){const n=w(e,o);if(T(n)&&I(n)!==void 0)return[]}const t=_(e);return t!==void 0&&I(t)!==void 0?[]:r()?[]:["--ip","127.0.0.1"]},qe=new Set(["127.0.0.1","::1","[::1]","localhost"]),Qe=(e,r)=>{let o;try{o=E(w(e,W),"utf8")}catch{return[]}const t=[];for(const n of me(o)){let s;try{s=new URL(n.value)}catch{continue}qe.has(s.hostname)&&s.port===String(r)&&t.push(n.key)}return t},$=async(e,r)=>{if(e.workerPort!==void 0)return e.workerPort;const o=_(r);if(o!==void 0){const{parsed:s}=L(o);if(typeof s?.dev?.port=="number")return s.dev.port}const t=await(e.findFreePort??Ye)(g);if(t===g)return t;const n=Qe(r,g);if(n.length>0)throw new Error(`port ${String(g)} is in use, but ${W} pins the worker origin to it (${n.join(", ")}). Serving on ${String(t)} would leave those URLs pointing at nothing. Stop whatever holds ${String(g)}, or run \`lunora dev --worker-port ${String(t)}\` and update those values to match.`);return t},Ze=(e,r)=>{if(e.inspectorPort!==void 0)return e.inspectorPort;const o=_(r);if(o===void 0)return;const{parsed:t}=L(o),n=t?.dev?.inspector_port;return typeof n=="number"?n:void 0},er=(e,r,o)=>{const t=ee(r,e.hasIpv6Loopback??Z,S),n=G(e.target??x(r));if(n.toolchain===void 0)throw new Error(`deploy target "${n.id}" has no dev server to run the worker sidecar`);const s=n.toolchain.dev({configPath:S,extraArgs:[...t,"--var","WORKER_ENV:development"]}),a=V(o,s);return{args:a.args,command:a.command,cwd:r,tag:"worker"}},rr=e=>{const r=e.cwd??process.cwd(),o=b(r),t=e.flavor??O(r);if(t==="vite"||t==="framework-worker"){const l=H(r);let v;return t==="framework-worker"&&(v=er(e,r,o)),e.worker===!1&&e.logger.warn(`--no-worker does not apply to the ${t} flavor: Vite owns the worker, codegen and studio in-process. Run your framework's dev script instead.`),e.inspectorPort!==void 0&&e.logger.warn(t==="framework-worker"?`--inspector-port does not apply to the ${t} flavor: pin \`dev.inspector_port\` in ${S} — that is the config the worker sidecar runs.`:`--inspector-port does not apply to the ${t} flavor: Vite owns the worker. Pin it in vite.config — \`lunora({ cloudflare: { inspectorPort: ${String(e.inspectorPort)} } })\`.`),{runsCodegenWatch:!1,flavor:t,ipv4LoopbackForced:!1,remote:{bindings:[],cleanup:()=>{},enabled:e.remote===!0},...v?{sidecar:v}:{},studioEnabled:!1,studioPort:e.port??k,workerEnabled:!0,workerOrigin:`http://localhost:${String(R)}`,workerPort:R,wrangler:{args:l.args,command:l.command,cwd:r,...q(e),tag:"vite"}}}const n=M(r),s=n.framework==="none"?void 0:`this project uses ${n.framework} — the worker runs inside Vite there. run \`${fe(o,"dev")}\` for the full app (frontend + HMR); \`lunora dev\` starts only the worker.`,a=e.workerPort??g,i=Xe(e,r),c=ee(r,e.hasIpv6Loopback??Z),u=e.inspectorPort===void 0?[]:["--inspector-port",String(e.inspectorPort)],d=U(o,"wrangler",["dev","--port",String(a),...u,...c,"--var","WORKER_ENV:development",...i.args]);return{runsCodegenWatch:X(e),flavor:t,frameworkHint:s,ipv4LoopbackForced:c.length>0,remote:i.plan,studioEnabled:e.studio!==!1,studioPort:e.port??k,workerEnabled:e.worker!==!1,workerOrigin:`http://localhost:${String(a)}`,workerPort:a,wrangler:{args:d.args,command:d.command,cwd:r,tag:"wrangler"}}},mr=async e=>{const r=e.cwd??process.cwd();if(e.target!==void 0&&P(e.target))return Ke({cwd:r,driver:G(e.target),options:e,studioPort:e.port??k,workerPort:await $(e,r)});const o=e.flavor??O(r),t=o==="wrangler"?await $(e,r):e.workerPort,n=o==="wrangler"?Ze(e,r):e.inspectorPort;return rr({...e,cwd:r,flavor:o,inspectorPort:n,workerPort:t})};export{K as P,pr as a,Ne as b,O as c,Le as d,fr as e,mr as f,X as g,Ze as h,$ as i,rr as p,_e as r,gr as s};