@lunora/cli 1.0.0-alpha.413 → 1.0.0-alpha.415

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-CPcfZdt0.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-lWJrDHQn.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
@@ -567,6 +567,8 @@ interface RunCommandResult {
567
567
  }
568
568
  declare const runRpcCommand: (options: RunCommandOptions) => Promise<RunCommandResult>;
569
569
  interface DeployCommandOptions {
570
+ /** Deploy even though the app enables the open-shard option (the `open_shard_access` gate). */
571
+ allowOpenShards?: boolean;
570
572
  /** Override the schema-drift gate — deploy even with breaking drift and no new migration. */
571
573
  allowSchemaDrift?: boolean;
572
574
  /** Which API spec(s) codegen emits. Defaults to codegen's `"openapi"` when omitted. */
package/dist/index.d.ts CHANGED
@@ -567,6 +567,8 @@ interface RunCommandResult {
567
567
  }
568
568
  declare const runRpcCommand: (options: RunCommandOptions) => Promise<RunCommandResult>;
569
569
  interface DeployCommandOptions {
570
+ /** Deploy even though the app enables the open-shard option (the `open_shard_access` gate). */
571
+ allowOpenShards?: boolean;
570
572
  /** Override the schema-drift gate — deploy even with breaking drift and no new migration. */
571
573
  allowSchemaDrift?: boolean;
572
574
  /** Which API spec(s) codegen emits. Defaults to codegen's `"openapi"` when omitted. */
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{C as o,V as a,r as n}from"./packem_shared/cli-CPcfZdt0.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-DFY3CqHD.mjs";import{runInitCommand as l}from"./packem_chunks/runInitCommand.mjs";import{runMigrateGenerateCommand as I}from"./packem_shared/runMigrateGenerateCommand-BwemPIOz.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-4TujevyB.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-htqNZT8Q.mjs";import{default as N}from"./packem_shared/schemaIrToSnapshot-BHuNOfgs.mjs";import{createRecordingSpawner as j,defaultSpawner as q}from"./packem_shared/createRecordingSpawner-Ch7zuQQE.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-DvSfLvyt.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-lWJrDHQn.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-DFY3CqHD.mjs";import{runInitCommand as l}from"./packem_chunks/runInitCommand.mjs";import{runMigrateGenerateCommand as I}from"./packem_shared/runMigrateGenerateCommand-BwemPIOz.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-4TujevyB.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-htqNZT8Q.mjs";import{default as N}from"./packem_shared/schemaIrToSnapshot-BHuNOfgs.mjs";import{createRecordingSpawner as j,defaultSpawner as q}from"./packem_shared/createRecordingSpawner-Ch7zuQQE.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-DvSfLvyt.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{resolveLazyFunctions as M}from"@lunora/config";import{wranglerCodegenInputs as F}from"@lunora/config/cloudflare";import{d as D}from"../packem_shared/command-CB4JM-Jl.mjs";import{EXIT_CODE as E}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{D as u}from"../packem_shared/cli-CPcfZdt0.mjs";const l={clean:"·",exempt:"–",failing:"✗",warned:"!"},d=(e,r)=>e.length>=r?e:e+" ".repeat(r-e.length),R=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}`,k=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},C=(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("",...k(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{resolveLazyFunctions as M}from"@lunora/config";import{wranglerCodegenInputs as F}from"@lunora/config/cloudflare";import{d as D}from"../packem_shared/command-CB4JM-Jl.mjs";import{EXIT_CODE as E}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{D as u}from"../packem_shared/cli-lWJrDHQn.mjs";const l={clean:"·",exempt:"–",failing:"✗",warned:"!"},d=(e,r)=>e.length>=r?e:e+" ".repeat(r-e.length),R=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}`,k=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},C=(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("",...k(r)),o.join(`
2
2
  `)},T=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})`}),B=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))},I=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 B(e.procedures)){n.push("",` ${t}`);for(const i of o)n.push(g(i,r),...T(i))}return n.join(`
3
3
  `)},L=(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=[`${R(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,4 +1,4 @@
1
- import{V as M}from"../packem_shared/cli-CPcfZdt0.mjs";import{d as A}from"../packem_shared/command-CB4JM-Jl.mjs";import{EXIT_CODE as d}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{existsSync as h,readFileSync as N}from"node:fs";import{homedir as y}from"node:os";import{findWranglerFile as D}from"@lunora/config/cloudflare";import{join as c,relative as T}from"@visulima/path";import{stringify as I}from"smol-toml";import{h as P,u as F,i as R,r as H}from"../packem_shared/mcp-config-file-CcDTeXIq.mjs";import{detectPackageManager as W,execArgsFor as G}from"@lunora/config/cli";import{readLiveDevServerState as v,DEV_STATE_DIR as J}from"@lunora/config";import{resolveAdminToken as V}from"@lunora/config/studio-host";import{connectLocalStdio as z}from"@lunora/mcp";import{resolve as p}from"node:path";import{i as K}from"../packem_shared/path-containment-CgxYZggb.mjs";const m=e=>({args:[...e.args],command:e.command,...e.env===void 0?{}:{env:e.env}}),g=e=>e.transport==="http"?{type:"http",url:e.url}:m(e),q=e=>e.transport==="http"?{httpUrl:e.url}:m(e),X=e=>e.transport==="http"?{serverUrl:e.url}:m(e),B=e=>({args:["-y","mcp-remote",e],command:"npx"}),Z=e=>e.transport==="http"?B(e.url):m(e),Q=e=>e.transport==="http"?{url:e.url}:m(e),Y=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}},ee=e=>e.transport==="http"?{disabled:!1,type:"streamableHttp",url:e.url}:{disabled:!1,...m(e)},re=({home:e,platform:r})=>{if(r==="darwin")return{global:c(e,"Library","Application Support","Claude","claude_desktop_config.json")};if(r==="win32"){const t=process.env.APPDATA;return t===void 0||t===""?{}:{global:c(t,"Claude","claude_desktop_config.json")}}return r==="linux"?{global:c(e,".config","Claude","claude_desktop_config.json")}:{}},te=(e,r)=>I({mcp_servers:{[e]:r.transport==="http"?{url:r.url}:{args:[...r.args],command:r.command,...r.env===void 0?{}:{env:r.env}}}}),f=[{buildEntry:g,paths:({projectRoot:e})=>({project:c(e,".mcp.json")}),format:"json",id:"claude-code",key:"mcpServers",label:"Claude Code"},{buildEntry:g,paths:({home:e,projectRoot:r})=>({global:c(e,".cursor","mcp.json"),project:c(r,".cursor","mcp.json")}),format:"json",id:"cursor",key:"mcpServers",label:"Cursor"},{buildEntry:g,paths:({projectRoot:e})=>({project:c(e,".vscode","mcp.json")}),format:"json",id:"vscode",key:"servers",label:"VS Code (GitHub Copilot)"},{buildEntry:q,paths:({home:e,projectRoot:r})=>({global:c(e,".gemini","settings.json"),project:c(r,".gemini","settings.json")}),format:"json",id:"gemini",key:"mcpServers",label:"Gemini CLI"},{buildEntry:Z,paths:re,format:"json",id:"claude-desktop",key:"mcpServers",label:"Claude Desktop"},{buildEntry:X,paths:({home:e})=>({global:c(e,".codeium","windsurf","mcp_config.json")}),format:"json",id:"windsurf",key:"mcpServers",label:"Windsurf"},{buildEntry:Y,paths:({home:e,projectRoot:r})=>({global:c(e,".config","opencode","opencode.json"),project:c(r,"opencode.json")}),format:"json",id:"opencode",key:"mcp",label:"OpenCode"},{buildEntry:ee,paths:({home:e})=>({global:c(e,".cline","mcp.json")}),format:"json",id:"cline",key:"mcpServers",label:"Cline"},{buildEntry:Q,paths:({home:e})=>({global:c(e,".config","zed","settings.json")}),format:"json",id:"zed",key:"context_servers",label:"Zed"},{paths:({home:e,projectRoot:r})=>({global:c(e,".codex","config.toml"),project:c(r,".codex","config.toml")}),format:"manual",id:"codex",label:"Codex CLI",renderSnippet:te}],$=f.map(e=>e.id),ne=e=>f.find(r=>r.id===e.toLowerCase()),oe=["global","project"],u=(e,r)=>{const t=T(r,e);return t.length>0&&!t.startsWith("..")?t:e},le=(e,r)=>{const t=e.paths(r);return oe.flatMap(n=>{const o=t[n];return o===void 0?[]:[{client:e,path:o,scope:n}]})},ae=(e,r,t,n)=>{const o=e.paths(r),l=t==="global"?"project":"global",a=o[t]??(n?void 0:o[l]);if(a!==void 0)return{client:e,path:a,scope:o[t]===void 0?l:t}},se=e=>f.filter(r=>Object.values(r.paths(e)).some(t=>h(t))),j=(e,r,t,n)=>{if(e.length===0)return r();const o=[];for(const l of e){const a=ne(l);if(a===void 0){t.error(`mcp ${n}: unknown client "${l}". Known clients: ${$.join(", ")}.`);return}o.push(a)}return o},ce=e=>e.client.format==="json",ie="https://lunora.sh/mcp",O="lunora-docs",C="lunora",de=e=>h(c(e,"lunora"))&&D(e)!==void 0,ue=e=>{const{args:r,command:t}=G(e,"lunora",["mcp","serve"]);return{args:r,command:t,transport:"stdio"}},me=e=>({transport:"http",url:e}),fe=e=>({home:e.home,platform:e.platform,projectRoot:e.cwd}),_=(e,r,t)=>ae(e,fe(t),t.scope??r.preferredScope,t.scope!==void 0||!r.allowScopeFallback),pe=(e,r,t)=>{const n=_(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:o}=n,l=e.buildEntry(r.spec);if(t.print===!0){const i=u(o,t.cwd);return t.force!==!0&&P({key:e.key,name:r.name,path:o})?(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:o}):(t.logger.info(`${e.label} → ${i}
1
+ import{V as M}from"../packem_shared/cli-lWJrDHQn.mjs";import{d as A}from"../packem_shared/command-CB4JM-Jl.mjs";import{EXIT_CODE as d}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{existsSync as h,readFileSync as N}from"node:fs";import{homedir as y}from"node:os";import{findWranglerFile as D}from"@lunora/config/cloudflare";import{join as c,relative as T}from"@visulima/path";import{stringify as I}from"smol-toml";import{h as P,u as F,i as R,r as H}from"../packem_shared/mcp-config-file-CcDTeXIq.mjs";import{detectPackageManager as W,execArgsFor as G}from"@lunora/config/cli";import{readLiveDevServerState as v,DEV_STATE_DIR as J}from"@lunora/config";import{resolveAdminToken as V}from"@lunora/config/studio-host";import{connectLocalStdio as z}from"@lunora/mcp";import{resolve as p}from"node:path";import{i as K}from"../packem_shared/path-containment-CgxYZggb.mjs";const m=e=>({args:[...e.args],command:e.command,...e.env===void 0?{}:{env:e.env}}),g=e=>e.transport==="http"?{type:"http",url:e.url}:m(e),q=e=>e.transport==="http"?{httpUrl:e.url}:m(e),X=e=>e.transport==="http"?{serverUrl:e.url}:m(e),B=e=>({args:["-y","mcp-remote",e],command:"npx"}),Z=e=>e.transport==="http"?B(e.url):m(e),Q=e=>e.transport==="http"?{url:e.url}:m(e),Y=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}},ee=e=>e.transport==="http"?{disabled:!1,type:"streamableHttp",url:e.url}:{disabled:!1,...m(e)},re=({home:e,platform:r})=>{if(r==="darwin")return{global:c(e,"Library","Application Support","Claude","claude_desktop_config.json")};if(r==="win32"){const t=process.env.APPDATA;return t===void 0||t===""?{}:{global:c(t,"Claude","claude_desktop_config.json")}}return r==="linux"?{global:c(e,".config","Claude","claude_desktop_config.json")}:{}},te=(e,r)=>I({mcp_servers:{[e]:r.transport==="http"?{url:r.url}:{args:[...r.args],command:r.command,...r.env===void 0?{}:{env:r.env}}}}),f=[{buildEntry:g,paths:({projectRoot:e})=>({project:c(e,".mcp.json")}),format:"json",id:"claude-code",key:"mcpServers",label:"Claude Code"},{buildEntry:g,paths:({home:e,projectRoot:r})=>({global:c(e,".cursor","mcp.json"),project:c(r,".cursor","mcp.json")}),format:"json",id:"cursor",key:"mcpServers",label:"Cursor"},{buildEntry:g,paths:({projectRoot:e})=>({project:c(e,".vscode","mcp.json")}),format:"json",id:"vscode",key:"servers",label:"VS Code (GitHub Copilot)"},{buildEntry:q,paths:({home:e,projectRoot:r})=>({global:c(e,".gemini","settings.json"),project:c(r,".gemini","settings.json")}),format:"json",id:"gemini",key:"mcpServers",label:"Gemini CLI"},{buildEntry:Z,paths:re,format:"json",id:"claude-desktop",key:"mcpServers",label:"Claude Desktop"},{buildEntry:X,paths:({home:e})=>({global:c(e,".codeium","windsurf","mcp_config.json")}),format:"json",id:"windsurf",key:"mcpServers",label:"Windsurf"},{buildEntry:Y,paths:({home:e,projectRoot:r})=>({global:c(e,".config","opencode","opencode.json"),project:c(r,"opencode.json")}),format:"json",id:"opencode",key:"mcp",label:"OpenCode"},{buildEntry:ee,paths:({home:e})=>({global:c(e,".cline","mcp.json")}),format:"json",id:"cline",key:"mcpServers",label:"Cline"},{buildEntry:Q,paths:({home:e})=>({global:c(e,".config","zed","settings.json")}),format:"json",id:"zed",key:"context_servers",label:"Zed"},{paths:({home:e,projectRoot:r})=>({global:c(e,".codex","config.toml"),project:c(r,".codex","config.toml")}),format:"manual",id:"codex",label:"Codex CLI",renderSnippet:te}],$=f.map(e=>e.id),ne=e=>f.find(r=>r.id===e.toLowerCase()),oe=["global","project"],u=(e,r)=>{const t=T(r,e);return t.length>0&&!t.startsWith("..")?t:e},le=(e,r)=>{const t=e.paths(r);return oe.flatMap(n=>{const o=t[n];return o===void 0?[]:[{client:e,path:o,scope:n}]})},ae=(e,r,t,n)=>{const o=e.paths(r),l=t==="global"?"project":"global",a=o[t]??(n?void 0:o[l]);if(a!==void 0)return{client:e,path:a,scope:o[t]===void 0?l:t}},se=e=>f.filter(r=>Object.values(r.paths(e)).some(t=>h(t))),j=(e,r,t,n)=>{if(e.length===0)return r();const o=[];for(const l of e){const a=ne(l);if(a===void 0){t.error(`mcp ${n}: unknown client "${l}". Known clients: ${$.join(", ")}.`);return}o.push(a)}return o},ce=e=>e.client.format==="json",ie="https://lunora.sh/mcp",O="lunora-docs",C="lunora",de=e=>h(c(e,"lunora"))&&D(e)!==void 0,ue=e=>{const{args:r,command:t}=G(e,"lunora",["mcp","serve"]);return{args:r,command:t,transport:"stdio"}},me=e=>({transport:"http",url:e}),fe=e=>({home:e.home,platform:e.platform,projectRoot:e.cwd}),_=(e,r,t)=>ae(e,fe(t),t.scope??r.preferredScope,t.scope!==void 0||!r.allowScopeFallback),pe=(e,r,t)=>{const n=_(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:o}=n,l=e.buildEntry(r.spec);if(t.print===!0){const i=u(o,t.cwd);return t.force!==!0&&P({key:e.key,name:r.name,path:o})?(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:o}):(t.logger.info(`${e.label} → ${i}
2
2
  ${JSON.stringify({[e.key]:{[r.name]:l}},void 0,4)}`),{action:"printed",path:o})}const a=F({entry:l,force:t.force===!0,key:e.key,name:r.name,path:o}),s=u(o,t.cwd);return a.action==="invalid"?t.logger.error(`${e.label}: ${s} is not valid JSON (${a.error??"unknown error"}) — left untouched.`):a.action==="skipped"?t.logger.info(`${e.label}: "${r.name}" already configured in ${s} — re-run with --force to replace it.`):t.logger.success(`${e.label}: ${a.action==="created"?"created":"updated"} ${s} with "${r.name}".`),{action:a.action,path:o}},ge=(e,r,t)=>{const n=_(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)}
3
3
 
4
4
  ${e.renderSnippet(r.name,r.spec)}`),{action:"printed",path:n}},ve=e=>{const r=[];return e.localOnly!==!0&&r.push({allowScopeFallback:!0,name:O,preferredScope:"global",spec:me(e.docsUrl??ie)}),e.docsOnly!==!0&&de(e.cwd)&&r.push({allowScopeFallback:!1,name:C,preferredScope:"project",spec:ue(W(e.cwd))}),r},he=e=>{const r=e.home??y(),t=e.platform??process.platform;e.logger.info("Supported MCP clients:");for(const n of f){const o=n.paths({home:r,platform:t,projectRoot:e.cwd}),l=a=>{const s=o[a];return s===void 0?"—":u(s,e.cwd)};e.logger.info(` ${n.id.padEnd(15)} ${n.label.padEnd(24)} project: ${l("project").padEnd(30)} global: ${l("global")}`)}return{code:0,written:[]}},ye=e=>e.docsOnly===!0&&e.localOnly===!0?"`--docs-only` and `--local-only` are mutually exclusive — pass at most one.":"`--local-only` was set but this directory is not a Lunora project (no `lunora/` directory and wrangler config).",be=(e,r,t)=>{const n=[];for(const o of e)for(const l of r){const a=o.format==="json"?pe(o,l,t):ge(o,l,t);a!==void 0&&n.push({action:a.action,client:o.id,path:a.path,server:l.name})}return n},we=e=>{const r=e.home??y(),t=e.platform??process.platform,n=j(e.clients,()=>se({home:r,platform:t,projectRoot:e.cwd}),e.logger,"install");if(n===void 0)return{code:d.USAGE,written:[]};if(n.length===0)return e.logger.error(`mcp install: no MCP client config found — name one explicitly, e.g. \`lunora mcp install claude-code\`. Known clients: ${$.join(", ")}.`),{code:d.NOT_FOUND,written:[]};e.clients.length===0&&e.logger.info(`Detected ${String(n.length)} configured client(s): ${n.map(a=>a.label).join(", ")}.`);const o=ve(e);if(o.length===0)return e.logger.error(`mcp install: nothing to install — ${ye(e)}`),{code:d.USAGE,written:[]};const l=be(n,o,{...e,home:r,platform:t});return l.some(a=>a.action==="created"||a.action==="updated")&&e.logger.info("Restart your editor (or reload its MCP servers) to pick up the change."),{code:l.some(a=>a.action==="invalid")?1:0,written:l}},x=100,L=1e3,w=e=>({content:[{text:JSON.stringify(e,void 0,2),type:"text"}]}),Se=e=>({content:[{text:e,type:"text"}]}),ke=e=>{const r=typeof e=="string"?Number(e):e;return typeof r!="number"||!Number.isFinite(r)?x:Math.min(L,Math.max(1,Math.floor(r)))},S=(e,r)=>{if(r===void 0)return;const t=p(e,J);return K(t,p(e,r))?p(e,r):void 0},Ee=(e,r)=>{const t=N(e,"utf8").split(`
@@ -1 +1 @@
1
- import{d as Ue}from"../packem_shared/command-CB4JM-Jl.mjs";import{r as De}from"../packem_shared/deploy-target-resolve-BTCW1Iv4.mjs";import{exitCodeForStatus as j,EXIT_CODE as u}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{writeFileSync as ve,mkdirSync as Re,renameSync as Me,rmSync as je}from"node:fs";import{findWranglerFile as J,readWranglerJsonc as W,applyModify as Le}from"@lunora/config/cloudflare";import{c as L}from"../packem_shared/cap-error-body-YBKO32BF.mjs";import{r as H,n as X,c as Pe}from"../packem_shared/cloudflare-credentials-BVmZnDZk.mjs";import{c as Ge,b as Fe}from"../packem_shared/variables-CPYyJtsL.mjs";import{b as xe}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{a as qe}from"../packem_shared/docker-AqLAkOyY.mjs";import{defaultSpawner as be}from"../packem_shared/createRecordingSpawner-Ch7zuQQE.mjs";import{execArgsFor as $e,detectPackageManager as Ae}from"@lunora/config/cli";import{a as O}from"../packem_shared/cli-CPcfZdt0.mjs";import{resolve as Be,dirname as Je}from"node:path";const We="https://api.cloudflare.com/client/v4/accounts",Q=64,Z={byok:"https://developers.cloudflare.com/ai-gateway/configuration/bring-your-own-keys/",unifiedBilling:"https://developers.cloudflare.com/ai-gateway/features/unified-billing/"},$=(e,t,r)=>(e.error(r),{code:t,error:r}),ee=async(e,t,r,o={})=>{const n=await e(t,{...o,headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}}),a=await n.text();let s;try{s=JSON.parse(a)}catch{}return{body:s,ok:n.ok&&s?.success!==!1,status:n.status,text:a}},te=e=>{const t=(e.body?.errors??[]).map(r=>r.message).filter(r=>typeof r=="string");return`${String(e.status)}: ${L(t.length>0?t.join("; "):e.text)}`},He=(e,t,r)=>{let o=e;const n=[];for(const[a,s]of Object.entries(r))t?.[a]!==s&&(o=Le(o,["vars",a],s),n.push(a));return{changed:n,text:o}},Ye=(e,t)=>{e.info(`next: \`<provider>/<model>\` slugs (e.g. "anthropic/claude-sonnet-5") now route through gateway "${t}". Before the first call,`),e.info(` configure how the provider is paid for in the Cloudflare dashboard (AI > AI Gateway > ${t}):`),e.info(` - Unified Billing (OpenAI, Anthropic, Google, xAI, Groq, DeepSeek): load credits — ${Z.unifiedBilling}`),e.info(` - a key stored on the gateway (Mistral, Perplexity, OpenRouter, …): ${Z.byok}`),e.info(" Then redeploy (`lunora deploy`) so the Worker picks up the new vars.")},Ke=async(e,t,r,o,n,a)=>{const s=`${We}/${encodeURIComponent(r)}/ai-gateway/gateways`,i=await ee(t,`${s}/${encodeURIComponent(n)}`,o);if(i.ok){const d=i.body?.result?.collect_logs;return{action:"existing",collectLogs:typeof d=="boolean"?d:a}}if(i.status===401||i.status===403)return $(e,j(i.status),`ai-gateway: could not read AI Gateway "${n}" (${te(i)})`);const c=await ee(t,s,o,{body:JSON.stringify({cache_invalidate_on_update:!0,cache_ttl:0,collect_logs:a,id:n,rate_limiting_interval:0,rate_limiting_limit:0}),method:"POST"});return c.ok?{action:"created",collectLogs:a}:$(e,j(c.status),`ai-gateway: could not create AI Gateway "${n}" (${te(c)})`)},Ve=e=>{const{logger:t}=e,r=J(e.cwd);if(r===void 0)return $(t,u.NOT_FOUND,"ai-gateway: no wrangler.jsonc found — run `lunora init` (or `lunora dev`) first.");const{parsed:o,text:n}=W(r);if(o===void 0)return $(t,u.USAGE,`ai-gateway: could not parse ${r} as JSONC.`);const a=X(e.id)??X(o.name);return a===void 0?$(t,u.USAGE,"ai-gateway: no gateway id — pass --id <id>, or set `name` in wrangler.jsonc."):a.length>Q?$(t,u.USAGE,`ai-gateway: gateway id "${a}" is longer than ${String(Q)} characters — pass a shorter --id.`):{gatewayId:a,parsed:o,text:n,wranglerPath:r}},P=e=>e?"on":"off",ze=(e,t)=>(e.info(`ai-gateway (dry run): would create or reuse AI Gateway "${t.gatewayId}" (log collection ${P(t.collectLogs)}).`),e.info(t.varsWritten.length===0?`ai-gateway (dry run): ${t.wranglerPath} vars are already up to date.`:`ai-gateway (dry run): would write ${t.varsWritten.join(", ")} into ${t.wranglerPath} vars.`),t.accountId===void 0&&e.warn("ai-gateway (dry run): no CLOUDFLARE_ACCOUNT_ID (or `account_id` in wrangler.jsonc) — a real run will stop there."),{code:0,data:t}),Xe=async e=>{const{logger:t}=e,r=Ve(e);if("code"in r)return r;const{gatewayId:o,parsed:n,text:a,wranglerPath:s}=r,i=e.logs!==!1,{accountId:c,token:d}=H(e.environment??process.env,n.account_id),f={[Fe]:o,...c===void 0?{}:{[Ge]:c}},l=He(a,n.vars,f);if(e.dryRun===!0)return ze(t,{accountId:c,action:"planned",collectLogs:i,dryRun:!0,gatewayId:o,varsWritten:l.changed,wranglerPath:s});if(d===void 0||c===void 0){const g=[d===void 0?"CLOUDFLARE_API_TOKEN (an API token with AI Gateway Write)":void 0,c===void 0?"CLOUDFLARE_ACCOUNT_ID (or `account_id` in wrangler.jsonc)":void 0].filter(y=>y!==void 0);return $(t,u.AUTH,`ai-gateway: missing ${g.join(" and ")}.`)}const h=await Ke(t,e.fetch??globalThis.fetch.bind(globalThis),c,d,o,i);return"code"in h?h:(h.action==="created"?t.success(`ai-gateway: created AI Gateway "${o}" (log collection ${P(h.collectLogs)}).`):t.info(`ai-gateway: AI Gateway "${o}" already exists — reusing it (log collection ${P(h.collectLogs)}; change it in the dashboard).`),l.changed.length>0?(ve(s,l.text,"utf8"),t.success(`ai-gateway: wrote ${l.changed.join(", ")} into ${s} vars.`)):t.info(`ai-gateway: ${s} vars are already up to date.`),Ye(t,o),{code:0,data:{accountId:c,action:h.action,collectLogs:h.collectLogs,dryRun:!1,gatewayId:o,varsWritten:l.changed,wranglerPath:s}})},Qe=15e3,Ze="https://api.cloudflare.com/client/v4/graphql",E={analytics:"Account Analytics Read",notificationsRead:"Notifications Read",notificationsWrite:"Notifications Write"},et={auth:u.AUTH,failure:u.FAILURE,"not-found":u.NOT_FOUND,permission:u.PERMISSION,"rate-limited":u.RATE_LIMITED,rejected:u.USAGE,unavailable:u.UNAVAILABLE};class _ extends Error{kind;status;constructor(t,r,o){super(t),this.name="CloudflareApiError",this.kind=r,this.status=o}}const tt=e=>e===401?"auth":e===403?"permission":e===404?"not-found":e===429?"rate-limited":e>=500?"unavailable":"rejected",Se=e=>{try{const r=JSON.parse(e);if(Array.isArray(r.errors)){const o=r.errors.map(n=>typeof n=="object"&&n!==null&&"message"in n?String(n.message):void 0).filter(n=>n!==void 0&&n.length>0);if(o.length>0)return o}}catch{}const t=e.trim().slice(0,200);return t.length>0?[t]:[]},rt=9106,ot=(e,t)=>{try{const r=JSON.parse(e);return Array.isArray(r.errors)&&r.errors.some(o=>typeof o=="object"&&o!==null&&"code"in o&&o.code===t)}catch{return!1}},re=(e,t,r,o)=>{const n=t===400&&ot(r,rt)?"auth":tt(t),a=Se(r).join("; ");let s="";return n==="auth"?s=` — check that CLOUDFLARE_API_TOKEN is a valid token; it needs the "${o}" permission on this account`:n==="permission"&&(s=` — the API token needs the "${o}" permission on this account`),new _(`${e} failed (HTTP ${String(t)})${a.length>0?`: ${a}`:""}${s}.`,n,t)},oe=(e,t)=>{const r=t instanceof Error&&(t.name==="TimeoutError"||t.name==="AbortError");let o=t instanceof Error?t.message:String(t);return r&&(o="no answer in time"),new _(`${e} failed: ${o}.`,"unavailable")},nt=10,at=e=>{const{accountId:t,token:r}=e,o=e.timeoutMs??Qe,n=e.fetch??globalThis.fetch.bind(globalThis),a=async(s,i,c,d)=>{let f;try{f=await Pe({accountId:t,apiToken:r,fetch:n,init:{method:i,signal:AbortSignal.timeout(o),...d===void 0?{}:{body:JSON.stringify(d)}},path:c})}catch(l){throw oe(s,l)}if(!f.ok)throw re(s,f.status,f.text,i==="GET"?E.notificationsRead:E.notificationsWrite);return f.body};return{accountId:t,graphql:async(s,i,c={})=>{let d;try{d=await n(Ze,{body:JSON.stringify({query:i,variables:c}),headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},method:"POST",signal:AbortSignal.timeout(o)})}catch(l){throw oe(s,l)}const f=await d.text();if(!d.ok)throw re(s,d.status,f,E.analytics);try{const l=JSON.parse(f);return{data:l.data??void 0,errors:Array.isArray(l.errors)&&l.errors.length>0?Se(f):[]}}catch{throw new _(`${s} failed: the GraphQL API answered with something that is not JSON.`,"unavailable",d.status)}},notifications:async(s,i,c,d)=>(await a(s,i,c,d)).result,notificationsList:async(s,i,c=nt)=>{const d=async f=>{const l=await a(s,"GET",`${i}${i.includes("?")?"&":"?"}page=${String(f)}`),h=Array.isArray(l.result)?l.result:[],g=l.result_info;return typeof g?.total_pages=="number"&&f<g.total_pages&&f<c?[...h,...await d(f+1)]:h};return d(1)}}},A="billing_usage_alert",ne={"do-duration":"worker_durable_objects_duration","do-requests":"worker_durable_objects_requests","do-rows-read":"worker_durable_objects_storage_reads","do-rows-written":"worker_durable_objects_storage_writes","workers-requests":"worker_requests"},st=6,C=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0,U=(e,t)=>{const r=t.toLowerCase(),o=Object.keys(e).find(n=>n.toLowerCase()===r);return o===void 0?void 0:e[o]},G=(e,t)=>{for(const r of t){const o=U(e,r);if(typeof o=="string"&&o.length>0)return o}},it=e=>{if(typeof e=="string"&&e.length>0)return{id:e,source:"available-alerts"};const t=C(e),r=t===void 0?void 0:G(t,["id","value","key","name"]);if(t===void 0||r===void 0)return;const o=G(t,["description","label","display_name","displayName","name"]);return{id:r,source:"available-alerts",...o===void 0||o===r?{}:{label:o}}},ct=["AvailableValues","available_values","values","options","enum","choices"],_e=e=>e.map(t=>it(t)).filter(t=>t!==void 0),dt=e=>G(e,["key","name","filter","id"])!=="product"?[]:ct.flatMap(t=>{const r=U(e,t);return Array.isArray(r)?_e(r):[]}),F=(e,t,r)=>{if(t>st)return;if(Array.isArray(e)){for(const n of e)F(n,t+1,r);return}const o=C(e);if(o!==void 0){r.push(...dt(o));for(const[n,a]of Object.entries(o))n.toLowerCase()==="product"&&Array.isArray(a)?r.push(..._e(a)):typeof a=="object"&&a!==null&&F(a,t+1,r)}},lt=e=>{const t=C(e);if(t!==void 0){for(const r of Object.values(t))if(Array.isArray(r)){const o=r.map(n=>C(n)).find(n=>n!==void 0&&U(n,"type")===A);if(o!==void 0)return o}}},ut=e=>e.filter(t=>t.alert_type===A&&Array.isArray(t.filters?.product)).flatMap(t=>(t.filters?.product).filter(r=>typeof r=="string"&&r.length>0)).map(t=>({id:t,source:"existing-policy"})),ft=(e,t,r)=>{const o=lt(e),n=[];o!==void 0&&F(U(o,"filter_options"),0,n);const a=new Map;for(const s of[...n,...ut(r)])a.has(s.id)||a.set(s.id,s);return{eligible:t?o!==void 0:void 0,products:[...a.values()]}},mt=/[^a-z\d]+/u,ht=e=>`${e.id} ${e.label??""}`.toLowerCase().split(mt).filter(t=>t.length>0),gt={"d1-rows-read":{all:[["d1"],["read"]]},"d1-rows-written":{all:[["d1"],["writ"]]},"do-duration":{all:[["durable"],["duration"]]},"do-requests":{all:[["durable"],["request"]]},"do-rows-read":{all:[["durable"],["read"]],none:["request"]},"do-rows-written":{all:[["durable"],["writ"]]},"workers-cpu":{all:[["worker"],["cpu"]],none:["durable"]},"workers-requests":{all:[["worker"],["request"]],none:["durable","cpu","kv","d1"]}},pt=(e,t)=>{const r=ht(t),o=s=>r.some(i=>i.startsWith(s)),{all:n,none:a=[]}=gt[e];return n.every(s=>s.some(i=>o(i)))&&!a.some(s=>o(s))},Ee=(e,t)=>{const r=ne[e],o=r===void 0?void 0:t.find(s=>s.id===r);if(o!==void 0)return{product:o,status:"matched"};const n=new Set(Object.values(ne)),a=t.filter(s=>!n.has(s.id)&&pt(e,s));return a.length===1&&a[0]!==void 0?{product:a[0],status:"matched"}:a.length>1?{candidates:a.map(s=>s.id),status:"ambiguous"}:r===void 0?{status:"no-product"}:{product:{id:r,source:"documented"},status:"matched"}},ae="workersInvocationsAdaptive",yt="durableObjectsInvocationsAdaptiveGroups",M="durableObjectsPeriodicGroups",se="d1AnalyticsAdaptiveGroups",S=[{candidates:[{field:"requests",unit:"count"}],dataset:ae,filter:"datetime",id:"workers-requests",label:"Workers requests"},{candidates:[{field:"cpuTimeUs",unit:"microseconds"}],dataset:ae,filter:"datetime",id:"workers-cpu",label:"Workers CPU time"},{candidates:[{field:"requests",unit:"count"}],dataset:yt,filter:"date",id:"do-requests",label:"Durable Objects requests"},{candidates:[{field:"activeTime",unit:"unknown"}],dataset:M,filter:"date",id:"do-duration",label:"Durable Objects duration"},{candidates:[{field:"rowsRead",unit:"count"}],dataset:M,filter:"date",id:"do-rows-read",label:"Durable Objects rows read"},{candidates:[{field:"rowsWritten",unit:"count"}],dataset:M,filter:"date",id:"do-rows-written",label:"Durable Objects rows written"},{candidates:[{field:"rowsRead",unit:"count"}],dataset:se,filter:"datetime-hour",id:"d1-rows-read",label:"D1 rows read"},{candidates:[{field:"rowsWritten",unit:"count"}],dataset:se,filter:"datetime-hour",id:"d1-rows-written",label:"D1 rows written"}],ie=e=>String(e).padStart(2,"0"),wt=e=>{const t=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth()-1,1)),r=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),0)),o=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),1)),n=a=>`${String(a.getUTCFullYear())}-${ie(a.getUTCMonth()+1)}-${ie(a.getUTCDate())}`;return{endDate:n(r),nextStartDate:n(o),startDate:n(t)}},vt=(e,t)=>{const r=JSON.stringify(`${t.startDate}T00:00:00Z`),o=JSON.stringify(`${t.nextStartDate}T00:00:00Z`);switch(e){case"date":return`{ date_geq: ${JSON.stringify(t.startDate)}, date_lt: ${JSON.stringify(t.nextStartDate)} }`;case"datetime":return`{ datetime_geq: ${r}, datetime_lt: ${o} }`;default:return`{ AND: [{ datetimeHour_geq: ${r}, datetimeHour_lt: ${o} }] }`}},bt=e=>`query LunoraTypeFields { __type(name: ${JSON.stringify(e)}) { fields { name type { name ofType { name ofType { name ofType { name } } } } } } }`,$t=e=>{let t=e;for(;t!=null;){if(typeof t.name=="string"&&t.name.length>0)return t.name;t=t.ofType}},At=e=>{const t=new Map;return async r=>{const o=t.get(r);if(o!==void 0)return o;const n=e.graphql(`Reading the analytics schema (${r})`,bt(r)).then(a=>{if(a.errors.length>0)throw new _(`Reading the analytics schema failed: ${a.errors.join("; ")}.`,"rejected");const i=a.data?.__type?.fields??[];return new Map(i.map(c=>[c.name,$t(c.type)]))});return t.set(r,n),n}},Te=async(e,t,r)=>{const o=await e(t),[n,...a]=r;if(n===void 0)return o;const s=o.get(n);if(s===void 0)throw new _(`the analytics schema has no \`${n}\` on \`${t}\``,"rejected");return Te(e,s,a)},St=e=>e instanceof Error?e.message:String(e),_t=async(e,t,r,o,n)=>{const{id:a,label:s}=o;try{const i=await Te(t,r,["viewer","accounts",o.dataset,"sum"]),c=o.candidates.find(y=>i.has(y.field));if(c===void 0){const y=o.candidates.map(m=>`\`${m.field}\``).join(", ");return{id:a,label:s,reason:`\`${o.dataset}.sum\` exposes no ${y} field`,status:"unavailable"}}const d=`query LunoraUsage($accountTag: string) { viewer { accounts(filter: { accountTag: $accountTag }) { ${o.dataset}(limit: 1, filter: ${vt(o.filter,n)}) { sum { ${c.field} } } } } }`,f=await e.graphql(`Reading ${s}`,d,{accountTag:e.accountId});if(f.errors.length>0)return{id:a,label:s,reason:f.errors.join("; "),status:"unavailable"};const l=f.data?.viewer?.accounts?.[0]?.[o.dataset],h=Array.isArray(l)?l[0]:void 0,g=h===void 0?0:h.sum?.[c.field];return typeof g!="number"||!Number.isFinite(g)?{id:a,label:s,reason:`the response carried no number for \`${c.field}\``,status:"unavailable"}:{field:`${o.dataset}.sum.${c.field}`,id:a,label:s,status:"ok",unit:c.unit,value:g}}catch(i){return{id:a,label:s,reason:St(i),status:"unavailable"}}},Et=async(e,t)=>{const r=await e.graphql("Reading the analytics schema","query LunoraQueryRoot { __schema { queryType { name } } }"),o=r.data?.__schema?.queryType?.name;if(r.errors.length>0||o===void 0){const a=r.errors.length>0?r.errors.join("; "):"the schema root could not be read";return S.map(({id:s,label:i})=>({id:s,label:i,reason:a,status:"unavailable"}))}const n=At(e);return Promise.all(S.map(async a=>_t(e,n,o,a,t)))},D="Lunora usage: ",Tt=3,Y="Cloudflare does not document the unit of a usage alert's limit; limits are sent as plain request counts. Check the stored limit in the dashboard.",It={"do-requests":1e6,"workers-requests":1e7},kt=100,Ot=e=>{const t=Math.ceil(e);if(t<=0)return 0;const r=10**Math.max(0,Math.floor(Math.log10(t))-1);return Math.ceil(t/r)*r},Ct=(e,t,r)=>{const o=Ot(e*t);return o>r?{basis:"history",threshold:o}:{basis:"floor",threshold:r}},x=e=>{const t=e.filters?.product;return Array.isArray(t)?t.filter(r=>typeof r=="string"):[]},Nt=e=>{const t=e.filters?.limit,r=Array.isArray(t)?t[0]:void 0,o=typeof r=="string"?Number(r):Number.NaN;return Number.isFinite(o)?o:void 0},K=e=>{const t={};for(const[r,o]of Object.entries(e?.mechanisms??{}))Array.isArray(o)&&(t[r]=o.filter(n=>typeof n=="object"&&n!==null&&"id"in n&&typeof n.id=="string"));return t},Ut=(e,t)=>{const r={};for(const[o,n]of[...Object.entries(e),...Object.entries(t)]){const a=new Set((r[o]??[]).map(s=>s.id));r[o]=[...r[o]??[],...n.filter(s=>!a.has(s.id))]}return Object.fromEntries(Object.entries(r).filter(([,o])=>o.length>0))},N=e=>Object.entries(e).flatMap(([t,r])=>r.map(o=>`${t}:${o.id}`)),Dt=(e,t)=>JSON.stringify(N(e).toSorted((r,o)=>r.localeCompare(o)))===JSON.stringify(N(t).toSorted((r,o)=>r.localeCompare(o))),Rt=(e,t)=>e.enabled===!0&&e.name===t.name&&JSON.stringify(e.filters?.limit)===JSON.stringify(t.filters.limit)&&JSON.stringify(x(e))===JSON.stringify(t.filters.product)&&Dt(K(e),t.mechanisms),Mt=(e,t)=>{const r={};return e.length>0&&(r.email=e.map(o=>({id:o}))),t.length>0&&(r.webhooks=t.map(o=>({id:o}))),r},jt=(e,t,r)=>{const o=r.thresholds?.[e],n=r.usage.find(c=>c.id===e),a=n?.status==="ok"?n.value:void 0;if(o!==void 0)return{basis:"explicit",lastMonth:a,threshold:o};const s=It[e];return s===void 0?{kind:"unit-unverified",reason:`the unit Cloudflare meters "${t.id}" in is not documented and cannot be matched to the usage reading; set one yourself with --threshold ${e}=<n>`}:a!==void 0?{...Ct(a,r.multiplier,s),lastMonth:a}:r.allowFloor===!0?{basis:"floor-usage-unavailable",lastMonth:void 0,threshold:s}:{kind:"usage-unavailable",reason:`last month's usage could not be read (${n?.status==="unavailable"?n.reason:"no reading"}), and an alert at the floor could fire every month on an account that already exceeds it; pass --threshold ${e}=<n>, or --allow-floor`}},Lt=(e,t)=>{const r=Nt(e);if(r===void 0||t===void 0||r<=0||t<=0)return;const o=Math.max(r/t,t/r);return o>=kt?`its limit ${String(r)} differs from the ${String(t)} this would plan by ${String(Math.round(o))}× — one of the two may be in the wrong unit`:void 0},q=e=>`${D}${e}`,Pt=(e,t)=>e===void 0?"create":Rt(e,t)?"unchanged":"update",Gt=(e,t)=>{switch(e){case"explicit":return"set with --threshold";case"floor-usage-unavailable":return"the included monthly allowance, applied with --allow-floor because usage could not be read";case"history":return`${String(t)}× last month`;default:return"the included monthly allowance (floor)"}},Ft=(e,t,r)=>{const{id:o,label:n}=e,a=Ee(o,t.products);if(a.status==="no-product")return{kind:"no-product",metric:o,reason:"Cloudflare has no usage alert for this product; the account-wide budget alert is its guard"};if(a.status==="ambiguous")return{kind:"ambiguous",metric:o,reason:`several offered products could mean this metric (${a.candidates.join(", ")})`};const{product:s}=a,i=r.find(p=>p.name===q(n)),c=r.find(p=>p.enabled===!0&&p.name?.startsWith(D)!==!0&&x(p).includes(s.id)),d=jt(o,s,t);if(i===void 0&&c!==void 0){const p=Lt(c,"threshold"in d?d.threshold:void 0);return{kind:"covered",metric:o,reason:`already alerted by the existing policy "${c.name??c.id??"?"}"`,...p===void 0?{}:{warning:p}}}if(!("threshold"in d))return{...d,metric:o};const f=Mt(t.emails,t.webhooks),l=K(i),h=i===void 0||t.replaceRecipients===!0?f:Ut(l,f),g=new Set(N(l)),y=new Set(N(h)),m={alert_type:A,description:`Managed by \`lunora cloudflare alerts setup\`: ${Gt(d.basis,t.multiplier)}.`,enabled:!0,filters:{limit:[String(d.threshold)],product:[s.id]},mechanisms:h,name:q(n)},w=i===void 0?[]:x(i);return{action:Pt(i,m),basis:d.basis,body:m,lastMonth:d.lastMonth,metric:o,...i?.id===void 0?{}:{policyId:i.id},...i!==void 0&&JSON.stringify(w)!==JSON.stringify([s.id])?{previousProduct:w}:{},product:s.id,productSource:s.source,recipients:{added:[...y].filter(p=>!g.has(p)),removed:[...g].filter(p=>!y.has(p))},threshold:d.threshold}},xt=e=>{const t=e.policies.filter(n=>n.alert_type===A),r=new Set(S.map(n=>q(n.label))),o={alerts:[],duplicates:[],orphans:t.filter(n=>n.name?.startsWith(D)===!0&&!r.has(n.name)),skipped:[]};for(const n of r)o.duplicates.push(...t.filter(a=>a.name===n).slice(1));for(const n of S){const a=Ft(n,e,t);"action"in a?o.alerts.push(a):o.skipped.push(a)}return o},qt="Cloudflare's API has no endpoint that sends a test notification — not for webhooks and not for email — so `lunora cloudflare alerts test` sends nothing.",Bt="To test a webhook for real, create it in the dashboard (Alerts > Destinations > Webhooks > Create) and finish with Save and Test.",Jt="Email destinations cannot be tested at all: Cloudflare offers no test send for them. Check the address on each policy below instead.",ce=e=>Array.isArray(e)?e:[],de=30,Wt=async(e,t,r,o,n)=>{const a=t.filter(m=>m.alert_type===A&&m.name?.startsWith(D)===!0),s=a.map(m=>K(m)),i=new Set([...s.flatMap(m=>(m.webhooks??[]).map(w=>w.id)),...r]),c=[...new Set(s.flatMap(m=>(m.email??[]).map(w=>w.id)))],d=new Set(a.map(m=>m.id)),f=new Date(n.getTime()-de*24*60*60*1e3).toISOString(),[l,h]=await Promise.all([e.notifications("Listing webhook destinations","GET","/alerting/v3/destinations/webhooks"),a.length===0?Promise.resolve([]):e.notificationsList("Reading notification history",`/alerting/v3/history?per_page=25&since=${encodeURIComponent(f)}`)]),g=ce(l).map(m=>({...m,referenced:m.id!==void 0&&i.has(m.id)})),y=ce(h).filter(m=>m.alert_type===A&&m.policy_id!==void 0&&d.has(m.policy_id));o.warn(qt),a.length===0&&o.info("No `lunora cloudflare alerts setup` policies exist on this account yet — run `lunora cloudflare alerts setup` first.");for(const m of[...i].filter(w=>!g.some(p=>p.id===w)))o.warn(`Webhook destination ${m} is referenced but does not exist on this account.`);for(const m of g.filter(w=>w.referenced))o.info(`webhook "${m.name??m.id??"?"}" (${m.type??"generic"}): last delivered ${m.last_success??"never"}, last failed ${m.last_failure??"never"}`);if(o.info(Bt),c.length>0&&o.info(`${Jt} Addresses on the policies: ${c.join(", ")}.`),y.length===0)o.info(`Cloudflare's notification history shows nothing sent for these policies in the last ${String(de)} days (they only fire once a threshold is crossed).`);else for(const m of y)o.info(`sent ${m.sent??"?"}: "${m.name??"?"}" via ${m.mechanism_type??"?"} to ${m.mechanism??"?"}`);return{emails:c,history:y,testSent:!1,webhooks:g}},R="Budget alert (account-wide USD threshold): Cloudflare documents no API to create or read one, so this cannot be checked. Create it in the dashboard: Manage Account > Billing > Billable Usage > Create budget alert.",Ht="Alerts > Overview > Create an Alert, alert type Usage Based Billing",b=(e,t,r,o)=>(e.error(r),{code:t,error:r,...o===void 0?{}:{data:o}}),V=(e,t,r)=>{if(t instanceof _)return b(e,et[t.kind],t.message,r);throw t},z=(e,t)=>({accountId:e.accountId,budgetAlert:{checkable:!1,dashboardPath:"Manage Account > Billing > Billable Usage"},limitUnitCaveat:Y,...t===void 0?{}:{eligible:t.discovery.eligible,period:t.period,products:t.discovery.products}}),I=e=>e.toLocaleString("en-US",{maximumFractionDigits:0}),Ie=(e,t)=>{t===!1&&e.warn("This account is not eligible for Usage Based Billing notifications (they are offered to Pay-as-you-go accounts; most Enterprise contracts are not supported).")},ke=e=>({code:u.SUCCESS,data:e}),Yt=/^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/u,Oe=new Set(S.map(e=>e.id)),Kt=e=>Oe.has(e),Vt=e=>{const t={};for(const r of e.flatMap(o=>o.split(","))){const[o="",n=""]=r.split("=").map(s=>s.trim()),a=Number(n);if(!Kt(o))return{error:`--threshold "${r}": unknown metric "${o}" — one of ${[...Oe].join(", ")}.`};if(!Number.isFinite(a)||a<=0)return{error:`--threshold "${r}": the limit must be a positive number.`};t[o]=Math.ceil(a)}return t},zt=e=>{const t=(e.emails??[]).flatMap(s=>s.split(",")).map(s=>s.trim()).filter(s=>s.length>0),r=(e.webhooks??[]).map(s=>s.trim()).filter(s=>s.length>0),o=e.multiplier===void 0?Tt:Number(e.multiplier),n=Vt(e.thresholds??[]);if(t.length===0&&r.length===0)return{error:"alerts setup needs somewhere to send the alerts: pass --email <address> and/or --webhook <destination-id>."};const a=t.find(s=>!Yt.test(s));return a!==void 0?{error:`--email "${a}" is not an email address.`}:!Number.isFinite(o)||o<1?{error:`--multiplier must be a number of at least 1 (got "${e.multiplier??""}").`}:"error"in n?n:{allowFloor:e.allowFloor===!0,emails:t,multiplier:o,replaceRecipients:e.replaceRecipients===!0,thresholds:n,webhooks:r}},Xt={explicit:()=>"set with --threshold",floor:e=>`floor: included monthly allowance; last month ${I(e.lastMonth??0)}`,"floor-usage-unavailable":()=>"floor: usage could not be read, applied with --allow-floor",history:e=>`last month ${I(e.lastMonth??0)}`},Qt=e=>{const t=[...e.added.map(r=>`+${r}`),...e.removed.map(r=>`-${r}`)];return t.length===0?"recipients unchanged":`recipients ${t.join(" ")}`},Zt=e=>{const t=e.productSource==="documented"?"documented id":"offered by the account",r=e.previousProduct===void 0?"":`, product was ${e.previousProduct.join(", ")||"none"}`;return`${e.action.padEnd(9)} ${e.body.name} — product ${e.product} (${t}${r}), limit ${I(e.threshold)} (${Xt[e.basis](e)}); ${Qt(e.recipients)}`},B=e=>S.find(t=>t.id===e)?.label??e,er=(e,t,r,o)=>{o.info(`Usage alerts at ${String(t)}× last month (${r.startDate} to ${r.endDate}), never below the included allowance:`);for(const n of e.alerts)o.info(` ${Zt(n)}`);for(const n of e.skipped)o.info(` skipped ${B(n.metric)} — ${n.reason}`),n.warning!==void 0&&o.warn(`${B(n.metric)}: the existing alert ${n.warning}.`);for(const n of e.orphans)o.warn(`"${n.name??"?"}" (${n.id??"?"}) is named like a \`lunora cloudflare alerts\` policy but matches no metric; it was left alone.`);for(const n of e.duplicates)o.warn(`"${n.name??"?"}" exists more than once; ${n.id??"?"} was left alone — delete the extra one in the dashboard.`);e.skipped.some(n=>n.kind==="unit-unverified"||n.kind==="ambiguous")&&o.info(`To set the skipped ones by hand: ${Ht}.`),o.info(Y),o.info(R)},tr=async(e,t)=>{if(e.yes===!0)return;if(e.confirm===void 0&&(!process.stdin.isTTY||e.format==="json"))return b(e.logger,u.USAGE,"alerts setup: refusing to change notification policies without confirmation — re-run with --yes.");const r=t.flatMap(a=>a.recipients.removed),o=r.length===0?"":` This REMOVES recipients: ${[...new Set(r)].join(", ")}.`;if(!await(e.confirm??xe)(`Apply ${String(t.length)} notification policy change(s)?${o}`))return e.logger.info("alerts setup: aborted"),{code:u.CANCELLED,error:"alerts setup: aborted at the confirmation prompt"}},rr=async(e,t,r,o)=>{const a=(await Promise.all(t.map(async s=>e.notifications(`Reading webhook destination ${s}`,"GET",`/alerting/v3/destinations/webhooks/${encodeURIComponent(s)}`).then(()=>{},i=>({error:i,id:s}))))).find(s=>s!==void 0);if(a!==void 0)return a.error instanceof _&&a.error.kind==="not-found"?b(r,u.USAGE,`--webhook ${a.id}: no such webhook destination on account ${e.accountId}.`,o):V(r,a.error,o)},or=async(e,t)=>{const r=t.action==="create"?await e.notifications(`Creating "${t.body.name}"`,"POST","/alerting/v3/policies",t.body):await e.notifications(`Updating "${t.body.name}"`,"PUT",`/alerting/v3/policies/${encodeURIComponent(t.policyId??"")}`,t.body);return typeof r=="object"&&r!==null&&"id"in r&&typeof r.id=="string"?r.id:t.policyId},nr=async(e,t,r)=>await Promise.all(t.map(async({alert:n,id:a})=>{try{const s=await e.notifications(`Reading back "${n.body.name}"`,"GET",`/alerting/v3/policies/${encodeURIComponent(a)}`),i={enabled:s?.enabled,id:a,limit:s?.filters?.limit,name:s?.name,product:s?.filters?.product};return r.info(`Cloudflare stored "${i.name??n.body.name}": product ${JSON.stringify(i.product)}, limit ${JSON.stringify(i.limit)}.`),JSON.stringify(i.limit)!==JSON.stringify(n.body.filters.limit)&&r.warn(`"${n.body.name}": Cloudflare stored limit ${JSON.stringify(i.limit)}, not the ${JSON.stringify(n.body.filters.limit)} sent.`),i}catch(s){return r.warn(`Could not read "${n.body.name}" back: ${s instanceof Error?s.message:String(s)}`),{id:a}}})),ar=async(e,t,r,o)=>{const n=[],a=[];let s;for(const c of t)try{const d=await or(e,c);n.push({action:c.action,metric:c.metric,...d===void 0?{}:{policyId:d}}),d!==void 0&&a.push({alert:c,id:d}),r.success(`${c.action==="create"?"Created":"Updated"} "${c.body.name}".`)}catch(d){s=d;break}const i={...o,applied:n,stored:await nr(e,a,r)};return s===void 0?i:V(r,s,i)},le=(e,t,r)=>{const o=t.skipped.filter(n=>n.kind==="usage-unavailable");return o.length>0?b(r,u.FAILURE,`alerts setup: no alert was set for ${o.map(n=>B(n.metric)).join(", ")} because last month's usage could not be read — pass --threshold <metric>=<n>, or --allow-floor to accept the floor.`,e):{code:u.SUCCESS,data:e}},sr=async(e,t,r,o)=>{const{logger:n}=r,a=z(e,t),s=await rr(e,o.webhooks,n,a);if(s!==void 0)return s;if(t.discovery.eligible===!1)return Ie(n,!1),n.info(R),b(n,u.PERMISSION,"alerts setup: the account cannot create Usage Based Billing notifications.",a);const i=xt({...o,policies:t.policies,products:t.discovery.products,usage:t.usage});a.plan=i,er(i,o.multiplier,t.period,n);const c=i.alerts.filter(l=>l.action!=="unchanged");if(r.dryRun===!0||c.length===0)return n.info(r.dryRun===!0?"Dry run: nothing was changed.":"Every alert is already up to date."),le(a,i,n);const d=await tr(r,c);if(d!==void 0)return{...d,data:a};const f=await ar(e,c,n,a);return"code"in f?f:le(f,i,n)},ir=e=>e.status!=="ok"?`unavailable (${e.reason})`:e.unit==="microseconds"?`${I(e.value)} µs`:I(e.value),cr=(e,t,r)=>t?"no-product":e===void 0?"unknown":r.some(o=>o.enabled)?"active":r.length>0?"disabled-only":"none",ue=e=>e.map(t=>`"${t.name??t.id??"?"}" (limit ${JSON.stringify(t.limit)})${t.enabled?"":" — disabled, not protecting you"}`).join(", "),dr={active:e=>`alert: ${ue(e.alerts)}`,"disabled-only":e=>`alert: none active; ${ue(e.alerts)}`,"no-product":()=>"alert: none possible — Cloudflare has no usage alert for this; the budget alert is its guard",none:()=>"alert: none",unknown:()=>"alert: unknown (several offered products could mean this)"},lr=(e,t,r)=>{const o=Ee(e.id,t.discovery.products),n=o.status==="matched"?o.product:void 0,a=(n===void 0?[]:r.filter(s=>Array.isArray(s.filters?.product)&&s.filters.product.includes(n.id))).map(s=>({enabled:s.enabled===!0,id:s.id,limit:s.filters?.limit,name:s.name}));return{alerts:a,coverage:cr(n?.id,o.status==="no-product",a),id:e.id,label:e.label,...n===void 0?{}:{product:n.id,productSource:n.source},usage:e}},ur=(e,t,r)=>{const o=t.policies.filter(a=>a.alert_type===A),n=t.usage.map(a=>lr(a,t,o));r.info(`Cloudflare account ${e.accountId} — usage ${t.period.startDate} to ${t.period.endDate}`);for(const a of n)r.info(` ${a.label}: ${ir(a.usage)} — ${dr[a.coverage](a)}`);return r.info(`Usage Based Billing notifications on the account: ${String(o.length)} (${String(o.filter(a=>a.enabled===!0).length)} enabled).`),r.info(Y),Ie(r,t.discovery.eligible),r.info(R),ke({...z(e,t),metrics:n})},fr=e=>{const t=J(e);return t===void 0?void 0:W(t).parsed?.account_id},mr=e=>{const{accountId:t,token:r}=H(e.environment??process.env,fr(e.cwd));return r===void 0?b(e.logger,u.AUTH,`CLOUDFLARE_API_TOKEN is not set. \`lunora cloudflare alerts\` calls the Cloudflare API with an API token (a wrangler login session is not reused); create one with the "${E.notificationsWrite}" and "${E.analytics}" permissions ("${E.notificationsRead}" is enough for status and test).`):t===void 0?b(e.logger,u.USAGE,"No Cloudflare account: set CLOUDFLARE_ACCOUNT_ID or `account_id` in wrangler.jsonc."):at({accountId:t,token:r,...e.fetch===void 0?{}:{fetch:e.fetch}})},Ce=async e=>{const t=await e.notifications("Listing notification policies","GET","/alerting/v3/policies");return Array.isArray(t)?t:[]},hr=async(e,t)=>{const r=wt(t.now??new Date),{logger:o}=t,[n,a,s]=await Promise.all([Ce(e),e.notifications("Listing the alert types this account is eligible for","GET","/alerting/v3/available_alerts").then(i=>({ok:!0,value:i}),i=>({error:i,ok:!1})),Et(e,r).catch(i=>{const c=i instanceof Error?i.message:String(i);return o.warn(`Usage could not be read: ${c}`),S.map(({id:d,label:f})=>({id:d,label:f,reason:c,status:"unavailable"}))})]);return a.ok||o.warn(`Could not read which alert types the account is eligible for: ${a.error instanceof Error?a.error.message:String(a.error)}`),{discovery:ft(a.ok?a.value:void 0,a.ok,n),period:r,policies:n,usage:s}},gr=async(e,t)=>{const r=await Ce(e),o=await Wt(e,r,t.webhooks??[],t.logger,t.now??new Date);return t.logger.info(R),ke({...z(e),deliveries:o})},pr=async e=>{const t=e.subcommand==="setup"?zt(e):void 0;if(t!==void 0&&"error"in t)return b(e.logger,u.USAGE,t.error);const r=mr(e);if(!("graphql"in r))return r;try{if(e.subcommand==="test")return await gr(r,e);const o=await hr(r,e);return t===void 0?ur(r,o,e.logger):await sr(r,o,e,t)}catch(o){return V(e.logger,o)}},fe=new Set(["build","delete","images","info","list","push"]),yr=new Set(["build","push"]),me=new Set(["images list","info","list"]),wr=async e=>{const[t,...r]=e.argument;if(t===void 0||!fe.has(t)){const l=`lunora cloudflare containers requires a subcommand: ${[...fe].toSorted((h,g)=>h.localeCompare(g)).join(" | ")}. Example: lunora cloudflare containers build ./containers/app --tag app:v1 --push`;return e.logger.error(l),{code:u.USAGE,error:l}}const o=e.format==="json",n=t==="images"?`images ${r[0]??""}`.trim():t;if(o&&!me.has(n)){const l=`containers ${n}: --format json is only available for the read subcommands (${[...me].toSorted((h,g)=>h.localeCompare(g)).join(" | ")}) — wrangler has no JSON rendering for the rest.`;return e.logger.error(l),{code:u.USAGE,error:l}}if(yr.has(t)&&!(e.dockerAvailable??qe)()){const l=`containers ${t} needs a running Docker-compatible engine (it builds/pushes images locally). Start Docker or Colima and retry. Note: container images must target linux/amd64.`;return e.logger.error(l),{code:u.MISSING_DEPENDENCY,error:l}}const a=["containers",t,...r];o&&a.push("--json"),e.tag!==void 0&&a.push("--tag",e.tag),e.push===!0&&a.push("--push"),e.env!==void 0&&a.push("--env",e.env);const s=e.cwd??process.cwd(),i=$e(Ae(s),"wrangler",a),c={args:i.args,command:i.command,cwd:s};return e.logger.info(`running ${c.command} ${c.args.join(" ")}`),{code:(await(e.spawner??be)(c)).code,delegated:o,descriptor:c}},k=(e,t)=>(t!==void 0&&e.push("--env",t),e),vr=e=>{const t=k(["deployments","list"],e.env);return e.format==="json"&&t.push("--json"),t},br=e=>{switch(e.subcommand){case"inspect":return e.versionId===void 0?{error:"deployments inspect requires a version id. Usage: lunora cloudflare deployments inspect <version-id>"}:{args:k(["versions","view",e.versionId],e.env)};case"list":return{args:vr(e)};case"promote":{if(e.versionId===void 0)return{error:"deployments promote requires a version id. Usage: lunora cloudflare deployments promote <version-id> --yes"};if(!e.yes)return{error:"deployments promote shifts 100% of live traffic. Re-run with --yes to confirm."};const t=k(["versions","deploy",`${e.versionId}@100%`,"--yes"],e.env);return e.message!==void 0&&t.push("--message",e.message),{args:t}}case"rollback":{if(!e.yes)return{error:"deployments rollback changes the live version. Re-run with --yes to confirm."};const t=k(["rollback"],e.env);return e.versionId!==void 0&&t.push(e.versionId),t.push("--yes"),e.message!==void 0&&t.push("--message",e.message),{args:t}}default:return{error:`deployments: unknown subcommand "${e.subcommand}"`}}},$r=async e=>{if(e.format==="json"&&e.subcommand!=="list"){const d=`deployments ${e.subcommand}: --format json is only available for \`deployments list\` — wrangler has no JSON rendering for the others.`;return e.logger.error(d),{code:u.USAGE,descriptor:void 0,error:d}}const{args:t,error:r}=br(e);if(r!==void 0||t===void 0)return e.logger.error(r??"deployments: nothing to run"),{code:u.USAGE,descriptor:void 0,error:r};const{logger:o}=e,n=e.cwd??process.cwd(),a=$e(Ae(n),"wrangler",t),s={args:a.args,command:a.command,cwd:n};return o.info(`${s.command} ${s.args.join(" ")}`),{code:(await(e.spawner??be)(s)).code,delegated:e.format==="json",descriptor:s}},Ar=e=>e==="list"||e==="inspect"||e==="rollback"||e==="promote",Sr="https://api.cloudflare.com/client/v4/accounts",Ne="Workers Scripts Read",he=1e3,ge=5e4,_r=1e4,Er=3e4,pe=[31,139],ye=["cpu","heap"],Tr=/^[\da-f]{64}$/iu,v=(e,t,r)=>(e.error(r),{code:t,error:r}),we=e=>{try{const t=JSON.parse(e);if(Array.isArray(t.errors)){const r=t.errors.map(o=>typeof o=="object"&&o!==null&&"message"in o?String(o.message):"").filter(o=>o.length>0);if(r.length>0)return L(r.join("; "))}}catch{}return L(e.trim())},Ir=e=>{switch(e){case 401:case 403:return` — check that CLOUDFLARE_API_TOKEN is valid and has the "${Ne}" permission on this account`;case 404:return" — check the worker name, version, and (for a Durable Object) the namespace and actor ids";case 429:return" — rate limited; wait and retry";default:return""}},kr=e=>{const t=e.type??"cpu";if(!ye.includes(t))return{error:`profile: invalid --type "${e.type??""}" — expected ${ye.join(" | ")}`};const r=e.durationMs===void 0?_r:Number(e.durationMs);return!Number.isInteger(r)||r<he||r>ge?{error:`profile: invalid --duration-ms "${e.durationMs??""}" — expected an integer from ${String(he)} to ${String(ge)}`}:e.namespaceId===void 0!=(e.actorId===void 0)?{error:"profile: --namespace-id and --actor-id must be passed together to profile a Durable Object"}:e.actorId!==void 0&&!Tr.test(e.actorId)?{error:"profile: --actor-id must be a 64-character hexadecimal Durable Object id"}:{durationMs:r,profileType:t}},Or=e=>{const{logger:t}=e,r=J(e.cwd),o=r===void 0?void 0:W(r).parsed,{accountId:n,token:a}=H(e.environment??process.env,o?.account_id);if(a===void 0)return v(t,u.AUTH,`CLOUDFLARE_API_TOKEN is not set. \`lunora cloudflare profile\` calls the Cloudflare API with an API token (a wrangler login session is not reused); create one with the "${Ne}" permission.`);if(n===void 0)return v(t,u.USAGE,"No Cloudflare account: set CLOUDFLARE_ACCOUNT_ID or `account_id` in wrangler.jsonc.");const s=typeof o?.name=="string"&&o.name.length>0?o.name:void 0,i=e.worker??s;if(i===void 0)return v(t,u.USAGE,"profile: no Worker name — pass one, or set `name` in wrangler.jsonc.");const c=e.env===void 0?void 0:o?.env?.[e.env]?.name;let d=i;return e.worker===void 0&&e.env!==void 0&&(d=typeof c=="string"&&c.length>0?c:`${i}-${e.env}`),{accountId:n,sourceMapsMissing:o!==void 0&&o.upload_source_maps!==!0,token:a,worker:d}},Cr=(e,t)=>{const r=`${e}.${String(process.pid)}.tmp`;try{Re(Je(e),{recursive:!0}),ve(r,t),Me(r,e);return}catch(o){try{je(r,{force:!0})}catch{}return o instanceof Error?o.message:String(o)}},Nr=async(e,{accountId:t,token:r,worker:o},{durationMs:n,profileType:a,version:s})=>{const{logger:i}=e,c={duration_ms:n,profile_type:a,...e.namespaceId===void 0||e.actorId===void 0?{}:{actor_id:e.actorId,namespace_id:e.namespaceId}},d=`${Sr}/${encodeURIComponent(t)}/workers/workers/${encodeURIComponent(o)}/versions/${encodeURIComponent(s)}/profile`,f=e.fetch??globalThis.fetch.bind(globalThis);let l,h;try{l=await f(d,{body:JSON.stringify(c),headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},method:"POST",signal:AbortSignal.timeout(n+Er)}),h=new Uint8Array(await l.arrayBuffer())}catch(g){return v(i,u.UNAVAILABLE,`profile failed: ${g instanceof Error?g.message:String(g)}.`)}if(!l.ok){const g=we(new TextDecoder().decode(h));return v(i,j(l.status),`profile failed (HTTP ${String(l.status)})${g.length>0?`: ${g}`:""}${Ir(l.status)}.`)}if(h[0]!==pe[0]||h[1]!==pe[1]){const g=we(new TextDecoder().decode(h));return v(i,u.FAILURE,`profile failed: the API answered 200 with something that is not a gzip profile${g.length>0?`: ${g}`:""}.`)}return{bytes:h}},Ur=async e=>{const{logger:t}=e,r=kr(e);if("error"in r)return v(t,u.USAGE,r.error);const o=Or(e);if("code"in o)return o;const{durationMs:n,profileType:a}=r,{worker:s}=o,i=e.version??"latest";t.info(`Profiling ${s}@${i} (${a}) for ${String(n)} ms — keep traffic flowing to it…`);const c=await Nr(e,o,{durationMs:n,profileType:a,version:i});if("code"in c)return c;const{bytes:d}=c,f=(e.now??new Date).toISOString().replaceAll(/[:.]/gu,"-"),l=Be(e.cwd,e.out??`${s}-${a}-${f}.pprof.gz`),h=Cr(l,d);return h!==void 0?v(t,u.FAILURE,`profile failed: could not write ${l}: ${h}.`):(t.success(`Wrote ${String(d.byteLength)} bytes to ${l}`),t.info("Open it with `go tool pprof -http=: <file>` (pprof reads gzip directly) or upload it to a flamegraph viewer."),o.sourceMapsMissing&&t.warn("wrangler config has no `upload_source_maps: true` — TypeScript function names in the profile may be mangled."),{code:u.SUCCESS,data:{bytes:d.byteLength,durationMs:n,file:l,profileType:a,version:i,worker:s}})},Dr={ai:{absorbs:"gateway",tool:"ai-gateway"},alert:{tool:"alerts"}},Rr=(e,t)=>{const r=Dr[e];if(r!==void 0)return{rest:r.absorbs!==void 0&&t[0]===r.absorbs?t.slice(1):t,tool:r.tool};const o=O.find(n=>n.name===e)?.name;return o===void 0?void 0:{rest:t,tool:o}},Mr={celld:"celld",node:"Node"},jr=e=>e==="status"||e==="setup"||e==="test",T=(e,t,r)=>(e.error(r),{code:t,error:r}),Lr=e=>{const t=Math.max(...O.map(r=>r.name.length));e.info("lunora cloudflare <tool> — tools for an app deployed to your own Cloudflare account:");for(const r of O)e.info(` ${r.name.padEnd(t)} ${r.summary}`),r.usage!==""&&e.info(` ${" ".repeat(t)} lunora cloudflare ${r.name} ${r.usage}`);return e.info("Run `lunora cloudflare --help` for every tool's arguments and options."),{code:0}},Pr=(e,t,r)=>{const{error:o,target:n}=De(e,r);return n===void 0?o??"no deploy target":n==="cloudflare"?void 0:`${r===void 0?`this project deploys to ${Mr[n]??`"${n}"`}`:`\`--target ${n}\``} — \`lunora cloudflare ${t}\` only applies to Cloudflare.`},Gr=(e,{logger:t,rest:r})=>r.length===0?void 0:T(t,u.USAGE,`cloudflare ${e}: takes no arguments, got "${r.join(" ")}"`),Fr=async e=>{const{cwd:t,logger:r,options:o}=e;return Gr("ai-gateway",e)??Xe({cwd:t,dryRun:o.dryRun===!0,id:o.id,logger:r,logs:o.logs})},xr=async({cwd:e,format:t,logger:r,options:o,rest:n})=>{const a=n[0]??"status";return jr(a)?pr({allowFloor:o.allowFloor===!0,cwd:e,dryRun:o.dryRun===!0,format:t,logger:r,replaceRecipients:o.replaceRecipients===!0,subcommand:a,yes:o.yes===!0,...o.email===void 0?{}:{emails:o.email},...o.webhook===void 0?{}:{webhooks:o.webhook},...o.multiplier===void 0?{}:{multiplier:o.multiplier},...o.threshold===void 0?{}:{thresholds:o.threshold}}):T(r,u.USAGE,`cloudflare alerts: unknown subcommand "${a}" — expected status | setup | test`)},qr=async({cwd:e,format:t,logger:r,options:o,rest:n})=>{const a=await wr({argument:n,cwd:e,env:o.env,format:t,logger:r,push:o.push===!0,tag:o.tag});return{code:a.code,delegated:a.delegated,error:a.error}},Br=async({cwd:e,format:t,logger:r,options:o,rest:n})=>{const[a,s]=n;if(!Ar(a))return T(r,u.USAGE,`cloudflare deployments: unknown subcommand "${a??""}" — expected list | inspect | rollback | promote`);const i=await $r({cwd:e,env:o.env,format:t,logger:r,message:o.message,subcommand:a,versionId:s,yes:o.yes===!0});return{code:i.code,delegated:i.delegated,error:i.error}},Jr=async({cwd:e,logger:t,options:r,rest:o})=>o.length>1?T(t,u.USAGE,`cloudflare profile: takes at most one argument (the worker), got "${o.join(" ")}"`):Ur({actorId:r.actorId,cwd:e,durationMs:r.durationMs,env:r.env,logger:t,namespaceId:r.namespaceId,out:r.out,type:r.type,version:r.versionId,worker:o[0]}),Wr={"ai-gateway":Fr,alerts:xr,containers:qr,deployments:Br,profile:Jr},so=Ue(async({argument:e,cwd:t,format:r,logger:o,options:n})=>{const[a,...s]=e;if(a===void 0||a==="")return Lr(o);const i=Rr(a,s);if(i===void 0)return T(o,u.USAGE,`cloudflare: unknown tool "${a}" — expected ${O.map(f=>f.name).join(" | ")}`);const{tool:c}=i,d=Pr(t,c,n.target);return d!==void 0?T(o,u.USAGE,d):Wr[c]({cwd:t,format:r,logger:o,options:n,rest:i.rest})});export{so as execute};
1
+ import{d as Ue}from"../packem_shared/command-CB4JM-Jl.mjs";import{r as De}from"../packem_shared/deploy-target-resolve-BTCW1Iv4.mjs";import{exitCodeForStatus as j,EXIT_CODE as u}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{writeFileSync as ve,mkdirSync as Re,renameSync as Me,rmSync as je}from"node:fs";import{findWranglerFile as J,readWranglerJsonc as W,applyModify as Le}from"@lunora/config/cloudflare";import{c as L}from"../packem_shared/cap-error-body-YBKO32BF.mjs";import{r as H,n as X,c as Pe}from"../packem_shared/cloudflare-credentials-BVmZnDZk.mjs";import{c as Ge,b as Fe}from"../packem_shared/variables-CPYyJtsL.mjs";import{b as xe}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{a as qe}from"../packem_shared/docker-AqLAkOyY.mjs";import{defaultSpawner as be}from"../packem_shared/createRecordingSpawner-Ch7zuQQE.mjs";import{execArgsFor as $e,detectPackageManager as Ae}from"@lunora/config/cli";import{a as O}from"../packem_shared/cli-lWJrDHQn.mjs";import{resolve as Be,dirname as Je}from"node:path";const We="https://api.cloudflare.com/client/v4/accounts",Q=64,Z={byok:"https://developers.cloudflare.com/ai-gateway/configuration/bring-your-own-keys/",unifiedBilling:"https://developers.cloudflare.com/ai-gateway/features/unified-billing/"},$=(e,t,r)=>(e.error(r),{code:t,error:r}),ee=async(e,t,r,o={})=>{const n=await e(t,{...o,headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}}),a=await n.text();let s;try{s=JSON.parse(a)}catch{}return{body:s,ok:n.ok&&s?.success!==!1,status:n.status,text:a}},te=e=>{const t=(e.body?.errors??[]).map(r=>r.message).filter(r=>typeof r=="string");return`${String(e.status)}: ${L(t.length>0?t.join("; "):e.text)}`},He=(e,t,r)=>{let o=e;const n=[];for(const[a,s]of Object.entries(r))t?.[a]!==s&&(o=Le(o,["vars",a],s),n.push(a));return{changed:n,text:o}},Ye=(e,t)=>{e.info(`next: \`<provider>/<model>\` slugs (e.g. "anthropic/claude-sonnet-5") now route through gateway "${t}". Before the first call,`),e.info(` configure how the provider is paid for in the Cloudflare dashboard (AI > AI Gateway > ${t}):`),e.info(` - Unified Billing (OpenAI, Anthropic, Google, xAI, Groq, DeepSeek): load credits — ${Z.unifiedBilling}`),e.info(` - a key stored on the gateway (Mistral, Perplexity, OpenRouter, …): ${Z.byok}`),e.info(" Then redeploy (`lunora deploy`) so the Worker picks up the new vars.")},Ke=async(e,t,r,o,n,a)=>{const s=`${We}/${encodeURIComponent(r)}/ai-gateway/gateways`,i=await ee(t,`${s}/${encodeURIComponent(n)}`,o);if(i.ok){const d=i.body?.result?.collect_logs;return{action:"existing",collectLogs:typeof d=="boolean"?d:a}}if(i.status===401||i.status===403)return $(e,j(i.status),`ai-gateway: could not read AI Gateway "${n}" (${te(i)})`);const c=await ee(t,s,o,{body:JSON.stringify({cache_invalidate_on_update:!0,cache_ttl:0,collect_logs:a,id:n,rate_limiting_interval:0,rate_limiting_limit:0}),method:"POST"});return c.ok?{action:"created",collectLogs:a}:$(e,j(c.status),`ai-gateway: could not create AI Gateway "${n}" (${te(c)})`)},Ve=e=>{const{logger:t}=e,r=J(e.cwd);if(r===void 0)return $(t,u.NOT_FOUND,"ai-gateway: no wrangler.jsonc found — run `lunora init` (or `lunora dev`) first.");const{parsed:o,text:n}=W(r);if(o===void 0)return $(t,u.USAGE,`ai-gateway: could not parse ${r} as JSONC.`);const a=X(e.id)??X(o.name);return a===void 0?$(t,u.USAGE,"ai-gateway: no gateway id — pass --id <id>, or set `name` in wrangler.jsonc."):a.length>Q?$(t,u.USAGE,`ai-gateway: gateway id "${a}" is longer than ${String(Q)} characters — pass a shorter --id.`):{gatewayId:a,parsed:o,text:n,wranglerPath:r}},P=e=>e?"on":"off",ze=(e,t)=>(e.info(`ai-gateway (dry run): would create or reuse AI Gateway "${t.gatewayId}" (log collection ${P(t.collectLogs)}).`),e.info(t.varsWritten.length===0?`ai-gateway (dry run): ${t.wranglerPath} vars are already up to date.`:`ai-gateway (dry run): would write ${t.varsWritten.join(", ")} into ${t.wranglerPath} vars.`),t.accountId===void 0&&e.warn("ai-gateway (dry run): no CLOUDFLARE_ACCOUNT_ID (or `account_id` in wrangler.jsonc) — a real run will stop there."),{code:0,data:t}),Xe=async e=>{const{logger:t}=e,r=Ve(e);if("code"in r)return r;const{gatewayId:o,parsed:n,text:a,wranglerPath:s}=r,i=e.logs!==!1,{accountId:c,token:d}=H(e.environment??process.env,n.account_id),f={[Fe]:o,...c===void 0?{}:{[Ge]:c}},l=He(a,n.vars,f);if(e.dryRun===!0)return ze(t,{accountId:c,action:"planned",collectLogs:i,dryRun:!0,gatewayId:o,varsWritten:l.changed,wranglerPath:s});if(d===void 0||c===void 0){const g=[d===void 0?"CLOUDFLARE_API_TOKEN (an API token with AI Gateway Write)":void 0,c===void 0?"CLOUDFLARE_ACCOUNT_ID (or `account_id` in wrangler.jsonc)":void 0].filter(y=>y!==void 0);return $(t,u.AUTH,`ai-gateway: missing ${g.join(" and ")}.`)}const h=await Ke(t,e.fetch??globalThis.fetch.bind(globalThis),c,d,o,i);return"code"in h?h:(h.action==="created"?t.success(`ai-gateway: created AI Gateway "${o}" (log collection ${P(h.collectLogs)}).`):t.info(`ai-gateway: AI Gateway "${o}" already exists — reusing it (log collection ${P(h.collectLogs)}; change it in the dashboard).`),l.changed.length>0?(ve(s,l.text,"utf8"),t.success(`ai-gateway: wrote ${l.changed.join(", ")} into ${s} vars.`)):t.info(`ai-gateway: ${s} vars are already up to date.`),Ye(t,o),{code:0,data:{accountId:c,action:h.action,collectLogs:h.collectLogs,dryRun:!1,gatewayId:o,varsWritten:l.changed,wranglerPath:s}})},Qe=15e3,Ze="https://api.cloudflare.com/client/v4/graphql",E={analytics:"Account Analytics Read",notificationsRead:"Notifications Read",notificationsWrite:"Notifications Write"},et={auth:u.AUTH,failure:u.FAILURE,"not-found":u.NOT_FOUND,permission:u.PERMISSION,"rate-limited":u.RATE_LIMITED,rejected:u.USAGE,unavailable:u.UNAVAILABLE};class _ extends Error{kind;status;constructor(t,r,o){super(t),this.name="CloudflareApiError",this.kind=r,this.status=o}}const tt=e=>e===401?"auth":e===403?"permission":e===404?"not-found":e===429?"rate-limited":e>=500?"unavailable":"rejected",Se=e=>{try{const r=JSON.parse(e);if(Array.isArray(r.errors)){const o=r.errors.map(n=>typeof n=="object"&&n!==null&&"message"in n?String(n.message):void 0).filter(n=>n!==void 0&&n.length>0);if(o.length>0)return o}}catch{}const t=e.trim().slice(0,200);return t.length>0?[t]:[]},rt=9106,ot=(e,t)=>{try{const r=JSON.parse(e);return Array.isArray(r.errors)&&r.errors.some(o=>typeof o=="object"&&o!==null&&"code"in o&&o.code===t)}catch{return!1}},re=(e,t,r,o)=>{const n=t===400&&ot(r,rt)?"auth":tt(t),a=Se(r).join("; ");let s="";return n==="auth"?s=` — check that CLOUDFLARE_API_TOKEN is a valid token; it needs the "${o}" permission on this account`:n==="permission"&&(s=` — the API token needs the "${o}" permission on this account`),new _(`${e} failed (HTTP ${String(t)})${a.length>0?`: ${a}`:""}${s}.`,n,t)},oe=(e,t)=>{const r=t instanceof Error&&(t.name==="TimeoutError"||t.name==="AbortError");let o=t instanceof Error?t.message:String(t);return r&&(o="no answer in time"),new _(`${e} failed: ${o}.`,"unavailable")},nt=10,at=e=>{const{accountId:t,token:r}=e,o=e.timeoutMs??Qe,n=e.fetch??globalThis.fetch.bind(globalThis),a=async(s,i,c,d)=>{let f;try{f=await Pe({accountId:t,apiToken:r,fetch:n,init:{method:i,signal:AbortSignal.timeout(o),...d===void 0?{}:{body:JSON.stringify(d)}},path:c})}catch(l){throw oe(s,l)}if(!f.ok)throw re(s,f.status,f.text,i==="GET"?E.notificationsRead:E.notificationsWrite);return f.body};return{accountId:t,graphql:async(s,i,c={})=>{let d;try{d=await n(Ze,{body:JSON.stringify({query:i,variables:c}),headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},method:"POST",signal:AbortSignal.timeout(o)})}catch(l){throw oe(s,l)}const f=await d.text();if(!d.ok)throw re(s,d.status,f,E.analytics);try{const l=JSON.parse(f);return{data:l.data??void 0,errors:Array.isArray(l.errors)&&l.errors.length>0?Se(f):[]}}catch{throw new _(`${s} failed: the GraphQL API answered with something that is not JSON.`,"unavailable",d.status)}},notifications:async(s,i,c,d)=>(await a(s,i,c,d)).result,notificationsList:async(s,i,c=nt)=>{const d=async f=>{const l=await a(s,"GET",`${i}${i.includes("?")?"&":"?"}page=${String(f)}`),h=Array.isArray(l.result)?l.result:[],g=l.result_info;return typeof g?.total_pages=="number"&&f<g.total_pages&&f<c?[...h,...await d(f+1)]:h};return d(1)}}},A="billing_usage_alert",ne={"do-duration":"worker_durable_objects_duration","do-requests":"worker_durable_objects_requests","do-rows-read":"worker_durable_objects_storage_reads","do-rows-written":"worker_durable_objects_storage_writes","workers-requests":"worker_requests"},st=6,C=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0,U=(e,t)=>{const r=t.toLowerCase(),o=Object.keys(e).find(n=>n.toLowerCase()===r);return o===void 0?void 0:e[o]},G=(e,t)=>{for(const r of t){const o=U(e,r);if(typeof o=="string"&&o.length>0)return o}},it=e=>{if(typeof e=="string"&&e.length>0)return{id:e,source:"available-alerts"};const t=C(e),r=t===void 0?void 0:G(t,["id","value","key","name"]);if(t===void 0||r===void 0)return;const o=G(t,["description","label","display_name","displayName","name"]);return{id:r,source:"available-alerts",...o===void 0||o===r?{}:{label:o}}},ct=["AvailableValues","available_values","values","options","enum","choices"],_e=e=>e.map(t=>it(t)).filter(t=>t!==void 0),dt=e=>G(e,["key","name","filter","id"])!=="product"?[]:ct.flatMap(t=>{const r=U(e,t);return Array.isArray(r)?_e(r):[]}),F=(e,t,r)=>{if(t>st)return;if(Array.isArray(e)){for(const n of e)F(n,t+1,r);return}const o=C(e);if(o!==void 0){r.push(...dt(o));for(const[n,a]of Object.entries(o))n.toLowerCase()==="product"&&Array.isArray(a)?r.push(..._e(a)):typeof a=="object"&&a!==null&&F(a,t+1,r)}},lt=e=>{const t=C(e);if(t!==void 0){for(const r of Object.values(t))if(Array.isArray(r)){const o=r.map(n=>C(n)).find(n=>n!==void 0&&U(n,"type")===A);if(o!==void 0)return o}}},ut=e=>e.filter(t=>t.alert_type===A&&Array.isArray(t.filters?.product)).flatMap(t=>(t.filters?.product).filter(r=>typeof r=="string"&&r.length>0)).map(t=>({id:t,source:"existing-policy"})),ft=(e,t,r)=>{const o=lt(e),n=[];o!==void 0&&F(U(o,"filter_options"),0,n);const a=new Map;for(const s of[...n,...ut(r)])a.has(s.id)||a.set(s.id,s);return{eligible:t?o!==void 0:void 0,products:[...a.values()]}},mt=/[^a-z\d]+/u,ht=e=>`${e.id} ${e.label??""}`.toLowerCase().split(mt).filter(t=>t.length>0),gt={"d1-rows-read":{all:[["d1"],["read"]]},"d1-rows-written":{all:[["d1"],["writ"]]},"do-duration":{all:[["durable"],["duration"]]},"do-requests":{all:[["durable"],["request"]]},"do-rows-read":{all:[["durable"],["read"]],none:["request"]},"do-rows-written":{all:[["durable"],["writ"]]},"workers-cpu":{all:[["worker"],["cpu"]],none:["durable"]},"workers-requests":{all:[["worker"],["request"]],none:["durable","cpu","kv","d1"]}},pt=(e,t)=>{const r=ht(t),o=s=>r.some(i=>i.startsWith(s)),{all:n,none:a=[]}=gt[e];return n.every(s=>s.some(i=>o(i)))&&!a.some(s=>o(s))},Ee=(e,t)=>{const r=ne[e],o=r===void 0?void 0:t.find(s=>s.id===r);if(o!==void 0)return{product:o,status:"matched"};const n=new Set(Object.values(ne)),a=t.filter(s=>!n.has(s.id)&&pt(e,s));return a.length===1&&a[0]!==void 0?{product:a[0],status:"matched"}:a.length>1?{candidates:a.map(s=>s.id),status:"ambiguous"}:r===void 0?{status:"no-product"}:{product:{id:r,source:"documented"},status:"matched"}},ae="workersInvocationsAdaptive",yt="durableObjectsInvocationsAdaptiveGroups",M="durableObjectsPeriodicGroups",se="d1AnalyticsAdaptiveGroups",S=[{candidates:[{field:"requests",unit:"count"}],dataset:ae,filter:"datetime",id:"workers-requests",label:"Workers requests"},{candidates:[{field:"cpuTimeUs",unit:"microseconds"}],dataset:ae,filter:"datetime",id:"workers-cpu",label:"Workers CPU time"},{candidates:[{field:"requests",unit:"count"}],dataset:yt,filter:"date",id:"do-requests",label:"Durable Objects requests"},{candidates:[{field:"activeTime",unit:"unknown"}],dataset:M,filter:"date",id:"do-duration",label:"Durable Objects duration"},{candidates:[{field:"rowsRead",unit:"count"}],dataset:M,filter:"date",id:"do-rows-read",label:"Durable Objects rows read"},{candidates:[{field:"rowsWritten",unit:"count"}],dataset:M,filter:"date",id:"do-rows-written",label:"Durable Objects rows written"},{candidates:[{field:"rowsRead",unit:"count"}],dataset:se,filter:"datetime-hour",id:"d1-rows-read",label:"D1 rows read"},{candidates:[{field:"rowsWritten",unit:"count"}],dataset:se,filter:"datetime-hour",id:"d1-rows-written",label:"D1 rows written"}],ie=e=>String(e).padStart(2,"0"),wt=e=>{const t=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth()-1,1)),r=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),0)),o=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),1)),n=a=>`${String(a.getUTCFullYear())}-${ie(a.getUTCMonth()+1)}-${ie(a.getUTCDate())}`;return{endDate:n(r),nextStartDate:n(o),startDate:n(t)}},vt=(e,t)=>{const r=JSON.stringify(`${t.startDate}T00:00:00Z`),o=JSON.stringify(`${t.nextStartDate}T00:00:00Z`);switch(e){case"date":return`{ date_geq: ${JSON.stringify(t.startDate)}, date_lt: ${JSON.stringify(t.nextStartDate)} }`;case"datetime":return`{ datetime_geq: ${r}, datetime_lt: ${o} }`;default:return`{ AND: [{ datetimeHour_geq: ${r}, datetimeHour_lt: ${o} }] }`}},bt=e=>`query LunoraTypeFields { __type(name: ${JSON.stringify(e)}) { fields { name type { name ofType { name ofType { name ofType { name } } } } } } }`,$t=e=>{let t=e;for(;t!=null;){if(typeof t.name=="string"&&t.name.length>0)return t.name;t=t.ofType}},At=e=>{const t=new Map;return async r=>{const o=t.get(r);if(o!==void 0)return o;const n=e.graphql(`Reading the analytics schema (${r})`,bt(r)).then(a=>{if(a.errors.length>0)throw new _(`Reading the analytics schema failed: ${a.errors.join("; ")}.`,"rejected");const i=a.data?.__type?.fields??[];return new Map(i.map(c=>[c.name,$t(c.type)]))});return t.set(r,n),n}},Te=async(e,t,r)=>{const o=await e(t),[n,...a]=r;if(n===void 0)return o;const s=o.get(n);if(s===void 0)throw new _(`the analytics schema has no \`${n}\` on \`${t}\``,"rejected");return Te(e,s,a)},St=e=>e instanceof Error?e.message:String(e),_t=async(e,t,r,o,n)=>{const{id:a,label:s}=o;try{const i=await Te(t,r,["viewer","accounts",o.dataset,"sum"]),c=o.candidates.find(y=>i.has(y.field));if(c===void 0){const y=o.candidates.map(m=>`\`${m.field}\``).join(", ");return{id:a,label:s,reason:`\`${o.dataset}.sum\` exposes no ${y} field`,status:"unavailable"}}const d=`query LunoraUsage($accountTag: string) { viewer { accounts(filter: { accountTag: $accountTag }) { ${o.dataset}(limit: 1, filter: ${vt(o.filter,n)}) { sum { ${c.field} } } } } }`,f=await e.graphql(`Reading ${s}`,d,{accountTag:e.accountId});if(f.errors.length>0)return{id:a,label:s,reason:f.errors.join("; "),status:"unavailable"};const l=f.data?.viewer?.accounts?.[0]?.[o.dataset],h=Array.isArray(l)?l[0]:void 0,g=h===void 0?0:h.sum?.[c.field];return typeof g!="number"||!Number.isFinite(g)?{id:a,label:s,reason:`the response carried no number for \`${c.field}\``,status:"unavailable"}:{field:`${o.dataset}.sum.${c.field}`,id:a,label:s,status:"ok",unit:c.unit,value:g}}catch(i){return{id:a,label:s,reason:St(i),status:"unavailable"}}},Et=async(e,t)=>{const r=await e.graphql("Reading the analytics schema","query LunoraQueryRoot { __schema { queryType { name } } }"),o=r.data?.__schema?.queryType?.name;if(r.errors.length>0||o===void 0){const a=r.errors.length>0?r.errors.join("; "):"the schema root could not be read";return S.map(({id:s,label:i})=>({id:s,label:i,reason:a,status:"unavailable"}))}const n=At(e);return Promise.all(S.map(async a=>_t(e,n,o,a,t)))},D="Lunora usage: ",Tt=3,Y="Cloudflare does not document the unit of a usage alert's limit; limits are sent as plain request counts. Check the stored limit in the dashboard.",It={"do-requests":1e6,"workers-requests":1e7},kt=100,Ot=e=>{const t=Math.ceil(e);if(t<=0)return 0;const r=10**Math.max(0,Math.floor(Math.log10(t))-1);return Math.ceil(t/r)*r},Ct=(e,t,r)=>{const o=Ot(e*t);return o>r?{basis:"history",threshold:o}:{basis:"floor",threshold:r}},x=e=>{const t=e.filters?.product;return Array.isArray(t)?t.filter(r=>typeof r=="string"):[]},Nt=e=>{const t=e.filters?.limit,r=Array.isArray(t)?t[0]:void 0,o=typeof r=="string"?Number(r):Number.NaN;return Number.isFinite(o)?o:void 0},K=e=>{const t={};for(const[r,o]of Object.entries(e?.mechanisms??{}))Array.isArray(o)&&(t[r]=o.filter(n=>typeof n=="object"&&n!==null&&"id"in n&&typeof n.id=="string"));return t},Ut=(e,t)=>{const r={};for(const[o,n]of[...Object.entries(e),...Object.entries(t)]){const a=new Set((r[o]??[]).map(s=>s.id));r[o]=[...r[o]??[],...n.filter(s=>!a.has(s.id))]}return Object.fromEntries(Object.entries(r).filter(([,o])=>o.length>0))},N=e=>Object.entries(e).flatMap(([t,r])=>r.map(o=>`${t}:${o.id}`)),Dt=(e,t)=>JSON.stringify(N(e).toSorted((r,o)=>r.localeCompare(o)))===JSON.stringify(N(t).toSorted((r,o)=>r.localeCompare(o))),Rt=(e,t)=>e.enabled===!0&&e.name===t.name&&JSON.stringify(e.filters?.limit)===JSON.stringify(t.filters.limit)&&JSON.stringify(x(e))===JSON.stringify(t.filters.product)&&Dt(K(e),t.mechanisms),Mt=(e,t)=>{const r={};return e.length>0&&(r.email=e.map(o=>({id:o}))),t.length>0&&(r.webhooks=t.map(o=>({id:o}))),r},jt=(e,t,r)=>{const o=r.thresholds?.[e],n=r.usage.find(c=>c.id===e),a=n?.status==="ok"?n.value:void 0;if(o!==void 0)return{basis:"explicit",lastMonth:a,threshold:o};const s=It[e];return s===void 0?{kind:"unit-unverified",reason:`the unit Cloudflare meters "${t.id}" in is not documented and cannot be matched to the usage reading; set one yourself with --threshold ${e}=<n>`}:a!==void 0?{...Ct(a,r.multiplier,s),lastMonth:a}:r.allowFloor===!0?{basis:"floor-usage-unavailable",lastMonth:void 0,threshold:s}:{kind:"usage-unavailable",reason:`last month's usage could not be read (${n?.status==="unavailable"?n.reason:"no reading"}), and an alert at the floor could fire every month on an account that already exceeds it; pass --threshold ${e}=<n>, or --allow-floor`}},Lt=(e,t)=>{const r=Nt(e);if(r===void 0||t===void 0||r<=0||t<=0)return;const o=Math.max(r/t,t/r);return o>=kt?`its limit ${String(r)} differs from the ${String(t)} this would plan by ${String(Math.round(o))}× — one of the two may be in the wrong unit`:void 0},q=e=>`${D}${e}`,Pt=(e,t)=>e===void 0?"create":Rt(e,t)?"unchanged":"update",Gt=(e,t)=>{switch(e){case"explicit":return"set with --threshold";case"floor-usage-unavailable":return"the included monthly allowance, applied with --allow-floor because usage could not be read";case"history":return`${String(t)}× last month`;default:return"the included monthly allowance (floor)"}},Ft=(e,t,r)=>{const{id:o,label:n}=e,a=Ee(o,t.products);if(a.status==="no-product")return{kind:"no-product",metric:o,reason:"Cloudflare has no usage alert for this product; the account-wide budget alert is its guard"};if(a.status==="ambiguous")return{kind:"ambiguous",metric:o,reason:`several offered products could mean this metric (${a.candidates.join(", ")})`};const{product:s}=a,i=r.find(p=>p.name===q(n)),c=r.find(p=>p.enabled===!0&&p.name?.startsWith(D)!==!0&&x(p).includes(s.id)),d=jt(o,s,t);if(i===void 0&&c!==void 0){const p=Lt(c,"threshold"in d?d.threshold:void 0);return{kind:"covered",metric:o,reason:`already alerted by the existing policy "${c.name??c.id??"?"}"`,...p===void 0?{}:{warning:p}}}if(!("threshold"in d))return{...d,metric:o};const f=Mt(t.emails,t.webhooks),l=K(i),h=i===void 0||t.replaceRecipients===!0?f:Ut(l,f),g=new Set(N(l)),y=new Set(N(h)),m={alert_type:A,description:`Managed by \`lunora cloudflare alerts setup\`: ${Gt(d.basis,t.multiplier)}.`,enabled:!0,filters:{limit:[String(d.threshold)],product:[s.id]},mechanisms:h,name:q(n)},w=i===void 0?[]:x(i);return{action:Pt(i,m),basis:d.basis,body:m,lastMonth:d.lastMonth,metric:o,...i?.id===void 0?{}:{policyId:i.id},...i!==void 0&&JSON.stringify(w)!==JSON.stringify([s.id])?{previousProduct:w}:{},product:s.id,productSource:s.source,recipients:{added:[...y].filter(p=>!g.has(p)),removed:[...g].filter(p=>!y.has(p))},threshold:d.threshold}},xt=e=>{const t=e.policies.filter(n=>n.alert_type===A),r=new Set(S.map(n=>q(n.label))),o={alerts:[],duplicates:[],orphans:t.filter(n=>n.name?.startsWith(D)===!0&&!r.has(n.name)),skipped:[]};for(const n of r)o.duplicates.push(...t.filter(a=>a.name===n).slice(1));for(const n of S){const a=Ft(n,e,t);"action"in a?o.alerts.push(a):o.skipped.push(a)}return o},qt="Cloudflare's API has no endpoint that sends a test notification — not for webhooks and not for email — so `lunora cloudflare alerts test` sends nothing.",Bt="To test a webhook for real, create it in the dashboard (Alerts > Destinations > Webhooks > Create) and finish with Save and Test.",Jt="Email destinations cannot be tested at all: Cloudflare offers no test send for them. Check the address on each policy below instead.",ce=e=>Array.isArray(e)?e:[],de=30,Wt=async(e,t,r,o,n)=>{const a=t.filter(m=>m.alert_type===A&&m.name?.startsWith(D)===!0),s=a.map(m=>K(m)),i=new Set([...s.flatMap(m=>(m.webhooks??[]).map(w=>w.id)),...r]),c=[...new Set(s.flatMap(m=>(m.email??[]).map(w=>w.id)))],d=new Set(a.map(m=>m.id)),f=new Date(n.getTime()-de*24*60*60*1e3).toISOString(),[l,h]=await Promise.all([e.notifications("Listing webhook destinations","GET","/alerting/v3/destinations/webhooks"),a.length===0?Promise.resolve([]):e.notificationsList("Reading notification history",`/alerting/v3/history?per_page=25&since=${encodeURIComponent(f)}`)]),g=ce(l).map(m=>({...m,referenced:m.id!==void 0&&i.has(m.id)})),y=ce(h).filter(m=>m.alert_type===A&&m.policy_id!==void 0&&d.has(m.policy_id));o.warn(qt),a.length===0&&o.info("No `lunora cloudflare alerts setup` policies exist on this account yet — run `lunora cloudflare alerts setup` first.");for(const m of[...i].filter(w=>!g.some(p=>p.id===w)))o.warn(`Webhook destination ${m} is referenced but does not exist on this account.`);for(const m of g.filter(w=>w.referenced))o.info(`webhook "${m.name??m.id??"?"}" (${m.type??"generic"}): last delivered ${m.last_success??"never"}, last failed ${m.last_failure??"never"}`);if(o.info(Bt),c.length>0&&o.info(`${Jt} Addresses on the policies: ${c.join(", ")}.`),y.length===0)o.info(`Cloudflare's notification history shows nothing sent for these policies in the last ${String(de)} days (they only fire once a threshold is crossed).`);else for(const m of y)o.info(`sent ${m.sent??"?"}: "${m.name??"?"}" via ${m.mechanism_type??"?"} to ${m.mechanism??"?"}`);return{emails:c,history:y,testSent:!1,webhooks:g}},R="Budget alert (account-wide USD threshold): Cloudflare documents no API to create or read one, so this cannot be checked. Create it in the dashboard: Manage Account > Billing > Billable Usage > Create budget alert.",Ht="Alerts > Overview > Create an Alert, alert type Usage Based Billing",b=(e,t,r,o)=>(e.error(r),{code:t,error:r,...o===void 0?{}:{data:o}}),V=(e,t,r)=>{if(t instanceof _)return b(e,et[t.kind],t.message,r);throw t},z=(e,t)=>({accountId:e.accountId,budgetAlert:{checkable:!1,dashboardPath:"Manage Account > Billing > Billable Usage"},limitUnitCaveat:Y,...t===void 0?{}:{eligible:t.discovery.eligible,period:t.period,products:t.discovery.products}}),I=e=>e.toLocaleString("en-US",{maximumFractionDigits:0}),Ie=(e,t)=>{t===!1&&e.warn("This account is not eligible for Usage Based Billing notifications (they are offered to Pay-as-you-go accounts; most Enterprise contracts are not supported).")},ke=e=>({code:u.SUCCESS,data:e}),Yt=/^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/u,Oe=new Set(S.map(e=>e.id)),Kt=e=>Oe.has(e),Vt=e=>{const t={};for(const r of e.flatMap(o=>o.split(","))){const[o="",n=""]=r.split("=").map(s=>s.trim()),a=Number(n);if(!Kt(o))return{error:`--threshold "${r}": unknown metric "${o}" — one of ${[...Oe].join(", ")}.`};if(!Number.isFinite(a)||a<=0)return{error:`--threshold "${r}": the limit must be a positive number.`};t[o]=Math.ceil(a)}return t},zt=e=>{const t=(e.emails??[]).flatMap(s=>s.split(",")).map(s=>s.trim()).filter(s=>s.length>0),r=(e.webhooks??[]).map(s=>s.trim()).filter(s=>s.length>0),o=e.multiplier===void 0?Tt:Number(e.multiplier),n=Vt(e.thresholds??[]);if(t.length===0&&r.length===0)return{error:"alerts setup needs somewhere to send the alerts: pass --email <address> and/or --webhook <destination-id>."};const a=t.find(s=>!Yt.test(s));return a!==void 0?{error:`--email "${a}" is not an email address.`}:!Number.isFinite(o)||o<1?{error:`--multiplier must be a number of at least 1 (got "${e.multiplier??""}").`}:"error"in n?n:{allowFloor:e.allowFloor===!0,emails:t,multiplier:o,replaceRecipients:e.replaceRecipients===!0,thresholds:n,webhooks:r}},Xt={explicit:()=>"set with --threshold",floor:e=>`floor: included monthly allowance; last month ${I(e.lastMonth??0)}`,"floor-usage-unavailable":()=>"floor: usage could not be read, applied with --allow-floor",history:e=>`last month ${I(e.lastMonth??0)}`},Qt=e=>{const t=[...e.added.map(r=>`+${r}`),...e.removed.map(r=>`-${r}`)];return t.length===0?"recipients unchanged":`recipients ${t.join(" ")}`},Zt=e=>{const t=e.productSource==="documented"?"documented id":"offered by the account",r=e.previousProduct===void 0?"":`, product was ${e.previousProduct.join(", ")||"none"}`;return`${e.action.padEnd(9)} ${e.body.name} — product ${e.product} (${t}${r}), limit ${I(e.threshold)} (${Xt[e.basis](e)}); ${Qt(e.recipients)}`},B=e=>S.find(t=>t.id===e)?.label??e,er=(e,t,r,o)=>{o.info(`Usage alerts at ${String(t)}× last month (${r.startDate} to ${r.endDate}), never below the included allowance:`);for(const n of e.alerts)o.info(` ${Zt(n)}`);for(const n of e.skipped)o.info(` skipped ${B(n.metric)} — ${n.reason}`),n.warning!==void 0&&o.warn(`${B(n.metric)}: the existing alert ${n.warning}.`);for(const n of e.orphans)o.warn(`"${n.name??"?"}" (${n.id??"?"}) is named like a \`lunora cloudflare alerts\` policy but matches no metric; it was left alone.`);for(const n of e.duplicates)o.warn(`"${n.name??"?"}" exists more than once; ${n.id??"?"} was left alone — delete the extra one in the dashboard.`);e.skipped.some(n=>n.kind==="unit-unverified"||n.kind==="ambiguous")&&o.info(`To set the skipped ones by hand: ${Ht}.`),o.info(Y),o.info(R)},tr=async(e,t)=>{if(e.yes===!0)return;if(e.confirm===void 0&&(!process.stdin.isTTY||e.format==="json"))return b(e.logger,u.USAGE,"alerts setup: refusing to change notification policies without confirmation — re-run with --yes.");const r=t.flatMap(a=>a.recipients.removed),o=r.length===0?"":` This REMOVES recipients: ${[...new Set(r)].join(", ")}.`;if(!await(e.confirm??xe)(`Apply ${String(t.length)} notification policy change(s)?${o}`))return e.logger.info("alerts setup: aborted"),{code:u.CANCELLED,error:"alerts setup: aborted at the confirmation prompt"}},rr=async(e,t,r,o)=>{const a=(await Promise.all(t.map(async s=>e.notifications(`Reading webhook destination ${s}`,"GET",`/alerting/v3/destinations/webhooks/${encodeURIComponent(s)}`).then(()=>{},i=>({error:i,id:s}))))).find(s=>s!==void 0);if(a!==void 0)return a.error instanceof _&&a.error.kind==="not-found"?b(r,u.USAGE,`--webhook ${a.id}: no such webhook destination on account ${e.accountId}.`,o):V(r,a.error,o)},or=async(e,t)=>{const r=t.action==="create"?await e.notifications(`Creating "${t.body.name}"`,"POST","/alerting/v3/policies",t.body):await e.notifications(`Updating "${t.body.name}"`,"PUT",`/alerting/v3/policies/${encodeURIComponent(t.policyId??"")}`,t.body);return typeof r=="object"&&r!==null&&"id"in r&&typeof r.id=="string"?r.id:t.policyId},nr=async(e,t,r)=>await Promise.all(t.map(async({alert:n,id:a})=>{try{const s=await e.notifications(`Reading back "${n.body.name}"`,"GET",`/alerting/v3/policies/${encodeURIComponent(a)}`),i={enabled:s?.enabled,id:a,limit:s?.filters?.limit,name:s?.name,product:s?.filters?.product};return r.info(`Cloudflare stored "${i.name??n.body.name}": product ${JSON.stringify(i.product)}, limit ${JSON.stringify(i.limit)}.`),JSON.stringify(i.limit)!==JSON.stringify(n.body.filters.limit)&&r.warn(`"${n.body.name}": Cloudflare stored limit ${JSON.stringify(i.limit)}, not the ${JSON.stringify(n.body.filters.limit)} sent.`),i}catch(s){return r.warn(`Could not read "${n.body.name}" back: ${s instanceof Error?s.message:String(s)}`),{id:a}}})),ar=async(e,t,r,o)=>{const n=[],a=[];let s;for(const c of t)try{const d=await or(e,c);n.push({action:c.action,metric:c.metric,...d===void 0?{}:{policyId:d}}),d!==void 0&&a.push({alert:c,id:d}),r.success(`${c.action==="create"?"Created":"Updated"} "${c.body.name}".`)}catch(d){s=d;break}const i={...o,applied:n,stored:await nr(e,a,r)};return s===void 0?i:V(r,s,i)},le=(e,t,r)=>{const o=t.skipped.filter(n=>n.kind==="usage-unavailable");return o.length>0?b(r,u.FAILURE,`alerts setup: no alert was set for ${o.map(n=>B(n.metric)).join(", ")} because last month's usage could not be read — pass --threshold <metric>=<n>, or --allow-floor to accept the floor.`,e):{code:u.SUCCESS,data:e}},sr=async(e,t,r,o)=>{const{logger:n}=r,a=z(e,t),s=await rr(e,o.webhooks,n,a);if(s!==void 0)return s;if(t.discovery.eligible===!1)return Ie(n,!1),n.info(R),b(n,u.PERMISSION,"alerts setup: the account cannot create Usage Based Billing notifications.",a);const i=xt({...o,policies:t.policies,products:t.discovery.products,usage:t.usage});a.plan=i,er(i,o.multiplier,t.period,n);const c=i.alerts.filter(l=>l.action!=="unchanged");if(r.dryRun===!0||c.length===0)return n.info(r.dryRun===!0?"Dry run: nothing was changed.":"Every alert is already up to date."),le(a,i,n);const d=await tr(r,c);if(d!==void 0)return{...d,data:a};const f=await ar(e,c,n,a);return"code"in f?f:le(f,i,n)},ir=e=>e.status!=="ok"?`unavailable (${e.reason})`:e.unit==="microseconds"?`${I(e.value)} µs`:I(e.value),cr=(e,t,r)=>t?"no-product":e===void 0?"unknown":r.some(o=>o.enabled)?"active":r.length>0?"disabled-only":"none",ue=e=>e.map(t=>`"${t.name??t.id??"?"}" (limit ${JSON.stringify(t.limit)})${t.enabled?"":" — disabled, not protecting you"}`).join(", "),dr={active:e=>`alert: ${ue(e.alerts)}`,"disabled-only":e=>`alert: none active; ${ue(e.alerts)}`,"no-product":()=>"alert: none possible — Cloudflare has no usage alert for this; the budget alert is its guard",none:()=>"alert: none",unknown:()=>"alert: unknown (several offered products could mean this)"},lr=(e,t,r)=>{const o=Ee(e.id,t.discovery.products),n=o.status==="matched"?o.product:void 0,a=(n===void 0?[]:r.filter(s=>Array.isArray(s.filters?.product)&&s.filters.product.includes(n.id))).map(s=>({enabled:s.enabled===!0,id:s.id,limit:s.filters?.limit,name:s.name}));return{alerts:a,coverage:cr(n?.id,o.status==="no-product",a),id:e.id,label:e.label,...n===void 0?{}:{product:n.id,productSource:n.source},usage:e}},ur=(e,t,r)=>{const o=t.policies.filter(a=>a.alert_type===A),n=t.usage.map(a=>lr(a,t,o));r.info(`Cloudflare account ${e.accountId} — usage ${t.period.startDate} to ${t.period.endDate}`);for(const a of n)r.info(` ${a.label}: ${ir(a.usage)} — ${dr[a.coverage](a)}`);return r.info(`Usage Based Billing notifications on the account: ${String(o.length)} (${String(o.filter(a=>a.enabled===!0).length)} enabled).`),r.info(Y),Ie(r,t.discovery.eligible),r.info(R),ke({...z(e,t),metrics:n})},fr=e=>{const t=J(e);return t===void 0?void 0:W(t).parsed?.account_id},mr=e=>{const{accountId:t,token:r}=H(e.environment??process.env,fr(e.cwd));return r===void 0?b(e.logger,u.AUTH,`CLOUDFLARE_API_TOKEN is not set. \`lunora cloudflare alerts\` calls the Cloudflare API with an API token (a wrangler login session is not reused); create one with the "${E.notificationsWrite}" and "${E.analytics}" permissions ("${E.notificationsRead}" is enough for status and test).`):t===void 0?b(e.logger,u.USAGE,"No Cloudflare account: set CLOUDFLARE_ACCOUNT_ID or `account_id` in wrangler.jsonc."):at({accountId:t,token:r,...e.fetch===void 0?{}:{fetch:e.fetch}})},Ce=async e=>{const t=await e.notifications("Listing notification policies","GET","/alerting/v3/policies");return Array.isArray(t)?t:[]},hr=async(e,t)=>{const r=wt(t.now??new Date),{logger:o}=t,[n,a,s]=await Promise.all([Ce(e),e.notifications("Listing the alert types this account is eligible for","GET","/alerting/v3/available_alerts").then(i=>({ok:!0,value:i}),i=>({error:i,ok:!1})),Et(e,r).catch(i=>{const c=i instanceof Error?i.message:String(i);return o.warn(`Usage could not be read: ${c}`),S.map(({id:d,label:f})=>({id:d,label:f,reason:c,status:"unavailable"}))})]);return a.ok||o.warn(`Could not read which alert types the account is eligible for: ${a.error instanceof Error?a.error.message:String(a.error)}`),{discovery:ft(a.ok?a.value:void 0,a.ok,n),period:r,policies:n,usage:s}},gr=async(e,t)=>{const r=await Ce(e),o=await Wt(e,r,t.webhooks??[],t.logger,t.now??new Date);return t.logger.info(R),ke({...z(e),deliveries:o})},pr=async e=>{const t=e.subcommand==="setup"?zt(e):void 0;if(t!==void 0&&"error"in t)return b(e.logger,u.USAGE,t.error);const r=mr(e);if(!("graphql"in r))return r;try{if(e.subcommand==="test")return await gr(r,e);const o=await hr(r,e);return t===void 0?ur(r,o,e.logger):await sr(r,o,e,t)}catch(o){return V(e.logger,o)}},fe=new Set(["build","delete","images","info","list","push"]),yr=new Set(["build","push"]),me=new Set(["images list","info","list"]),wr=async e=>{const[t,...r]=e.argument;if(t===void 0||!fe.has(t)){const l=`lunora cloudflare containers requires a subcommand: ${[...fe].toSorted((h,g)=>h.localeCompare(g)).join(" | ")}. Example: lunora cloudflare containers build ./containers/app --tag app:v1 --push`;return e.logger.error(l),{code:u.USAGE,error:l}}const o=e.format==="json",n=t==="images"?`images ${r[0]??""}`.trim():t;if(o&&!me.has(n)){const l=`containers ${n}: --format json is only available for the read subcommands (${[...me].toSorted((h,g)=>h.localeCompare(g)).join(" | ")}) — wrangler has no JSON rendering for the rest.`;return e.logger.error(l),{code:u.USAGE,error:l}}if(yr.has(t)&&!(e.dockerAvailable??qe)()){const l=`containers ${t} needs a running Docker-compatible engine (it builds/pushes images locally). Start Docker or Colima and retry. Note: container images must target linux/amd64.`;return e.logger.error(l),{code:u.MISSING_DEPENDENCY,error:l}}const a=["containers",t,...r];o&&a.push("--json"),e.tag!==void 0&&a.push("--tag",e.tag),e.push===!0&&a.push("--push"),e.env!==void 0&&a.push("--env",e.env);const s=e.cwd??process.cwd(),i=$e(Ae(s),"wrangler",a),c={args:i.args,command:i.command,cwd:s};return e.logger.info(`running ${c.command} ${c.args.join(" ")}`),{code:(await(e.spawner??be)(c)).code,delegated:o,descriptor:c}},k=(e,t)=>(t!==void 0&&e.push("--env",t),e),vr=e=>{const t=k(["deployments","list"],e.env);return e.format==="json"&&t.push("--json"),t},br=e=>{switch(e.subcommand){case"inspect":return e.versionId===void 0?{error:"deployments inspect requires a version id. Usage: lunora cloudflare deployments inspect <version-id>"}:{args:k(["versions","view",e.versionId],e.env)};case"list":return{args:vr(e)};case"promote":{if(e.versionId===void 0)return{error:"deployments promote requires a version id. Usage: lunora cloudflare deployments promote <version-id> --yes"};if(!e.yes)return{error:"deployments promote shifts 100% of live traffic. Re-run with --yes to confirm."};const t=k(["versions","deploy",`${e.versionId}@100%`,"--yes"],e.env);return e.message!==void 0&&t.push("--message",e.message),{args:t}}case"rollback":{if(!e.yes)return{error:"deployments rollback changes the live version. Re-run with --yes to confirm."};const t=k(["rollback"],e.env);return e.versionId!==void 0&&t.push(e.versionId),t.push("--yes"),e.message!==void 0&&t.push("--message",e.message),{args:t}}default:return{error:`deployments: unknown subcommand "${e.subcommand}"`}}},$r=async e=>{if(e.format==="json"&&e.subcommand!=="list"){const d=`deployments ${e.subcommand}: --format json is only available for \`deployments list\` — wrangler has no JSON rendering for the others.`;return e.logger.error(d),{code:u.USAGE,descriptor:void 0,error:d}}const{args:t,error:r}=br(e);if(r!==void 0||t===void 0)return e.logger.error(r??"deployments: nothing to run"),{code:u.USAGE,descriptor:void 0,error:r};const{logger:o}=e,n=e.cwd??process.cwd(),a=$e(Ae(n),"wrangler",t),s={args:a.args,command:a.command,cwd:n};return o.info(`${s.command} ${s.args.join(" ")}`),{code:(await(e.spawner??be)(s)).code,delegated:e.format==="json",descriptor:s}},Ar=e=>e==="list"||e==="inspect"||e==="rollback"||e==="promote",Sr="https://api.cloudflare.com/client/v4/accounts",Ne="Workers Scripts Read",he=1e3,ge=5e4,_r=1e4,Er=3e4,pe=[31,139],ye=["cpu","heap"],Tr=/^[\da-f]{64}$/iu,v=(e,t,r)=>(e.error(r),{code:t,error:r}),we=e=>{try{const t=JSON.parse(e);if(Array.isArray(t.errors)){const r=t.errors.map(o=>typeof o=="object"&&o!==null&&"message"in o?String(o.message):"").filter(o=>o.length>0);if(r.length>0)return L(r.join("; "))}}catch{}return L(e.trim())},Ir=e=>{switch(e){case 401:case 403:return` — check that CLOUDFLARE_API_TOKEN is valid and has the "${Ne}" permission on this account`;case 404:return" — check the worker name, version, and (for a Durable Object) the namespace and actor ids";case 429:return" — rate limited; wait and retry";default:return""}},kr=e=>{const t=e.type??"cpu";if(!ye.includes(t))return{error:`profile: invalid --type "${e.type??""}" — expected ${ye.join(" | ")}`};const r=e.durationMs===void 0?_r:Number(e.durationMs);return!Number.isInteger(r)||r<he||r>ge?{error:`profile: invalid --duration-ms "${e.durationMs??""}" — expected an integer from ${String(he)} to ${String(ge)}`}:e.namespaceId===void 0!=(e.actorId===void 0)?{error:"profile: --namespace-id and --actor-id must be passed together to profile a Durable Object"}:e.actorId!==void 0&&!Tr.test(e.actorId)?{error:"profile: --actor-id must be a 64-character hexadecimal Durable Object id"}:{durationMs:r,profileType:t}},Or=e=>{const{logger:t}=e,r=J(e.cwd),o=r===void 0?void 0:W(r).parsed,{accountId:n,token:a}=H(e.environment??process.env,o?.account_id);if(a===void 0)return v(t,u.AUTH,`CLOUDFLARE_API_TOKEN is not set. \`lunora cloudflare profile\` calls the Cloudflare API with an API token (a wrangler login session is not reused); create one with the "${Ne}" permission.`);if(n===void 0)return v(t,u.USAGE,"No Cloudflare account: set CLOUDFLARE_ACCOUNT_ID or `account_id` in wrangler.jsonc.");const s=typeof o?.name=="string"&&o.name.length>0?o.name:void 0,i=e.worker??s;if(i===void 0)return v(t,u.USAGE,"profile: no Worker name — pass one, or set `name` in wrangler.jsonc.");const c=e.env===void 0?void 0:o?.env?.[e.env]?.name;let d=i;return e.worker===void 0&&e.env!==void 0&&(d=typeof c=="string"&&c.length>0?c:`${i}-${e.env}`),{accountId:n,sourceMapsMissing:o!==void 0&&o.upload_source_maps!==!0,token:a,worker:d}},Cr=(e,t)=>{const r=`${e}.${String(process.pid)}.tmp`;try{Re(Je(e),{recursive:!0}),ve(r,t),Me(r,e);return}catch(o){try{je(r,{force:!0})}catch{}return o instanceof Error?o.message:String(o)}},Nr=async(e,{accountId:t,token:r,worker:o},{durationMs:n,profileType:a,version:s})=>{const{logger:i}=e,c={duration_ms:n,profile_type:a,...e.namespaceId===void 0||e.actorId===void 0?{}:{actor_id:e.actorId,namespace_id:e.namespaceId}},d=`${Sr}/${encodeURIComponent(t)}/workers/workers/${encodeURIComponent(o)}/versions/${encodeURIComponent(s)}/profile`,f=e.fetch??globalThis.fetch.bind(globalThis);let l,h;try{l=await f(d,{body:JSON.stringify(c),headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},method:"POST",signal:AbortSignal.timeout(n+Er)}),h=new Uint8Array(await l.arrayBuffer())}catch(g){return v(i,u.UNAVAILABLE,`profile failed: ${g instanceof Error?g.message:String(g)}.`)}if(!l.ok){const g=we(new TextDecoder().decode(h));return v(i,j(l.status),`profile failed (HTTP ${String(l.status)})${g.length>0?`: ${g}`:""}${Ir(l.status)}.`)}if(h[0]!==pe[0]||h[1]!==pe[1]){const g=we(new TextDecoder().decode(h));return v(i,u.FAILURE,`profile failed: the API answered 200 with something that is not a gzip profile${g.length>0?`: ${g}`:""}.`)}return{bytes:h}},Ur=async e=>{const{logger:t}=e,r=kr(e);if("error"in r)return v(t,u.USAGE,r.error);const o=Or(e);if("code"in o)return o;const{durationMs:n,profileType:a}=r,{worker:s}=o,i=e.version??"latest";t.info(`Profiling ${s}@${i} (${a}) for ${String(n)} ms — keep traffic flowing to it…`);const c=await Nr(e,o,{durationMs:n,profileType:a,version:i});if("code"in c)return c;const{bytes:d}=c,f=(e.now??new Date).toISOString().replaceAll(/[:.]/gu,"-"),l=Be(e.cwd,e.out??`${s}-${a}-${f}.pprof.gz`),h=Cr(l,d);return h!==void 0?v(t,u.FAILURE,`profile failed: could not write ${l}: ${h}.`):(t.success(`Wrote ${String(d.byteLength)} bytes to ${l}`),t.info("Open it with `go tool pprof -http=: <file>` (pprof reads gzip directly) or upload it to a flamegraph viewer."),o.sourceMapsMissing&&t.warn("wrangler config has no `upload_source_maps: true` — TypeScript function names in the profile may be mangled."),{code:u.SUCCESS,data:{bytes:d.byteLength,durationMs:n,file:l,profileType:a,version:i,worker:s}})},Dr={ai:{absorbs:"gateway",tool:"ai-gateway"},alert:{tool:"alerts"}},Rr=(e,t)=>{const r=Dr[e];if(r!==void 0)return{rest:r.absorbs!==void 0&&t[0]===r.absorbs?t.slice(1):t,tool:r.tool};const o=O.find(n=>n.name===e)?.name;return o===void 0?void 0:{rest:t,tool:o}},Mr={celld:"celld",node:"Node"},jr=e=>e==="status"||e==="setup"||e==="test",T=(e,t,r)=>(e.error(r),{code:t,error:r}),Lr=e=>{const t=Math.max(...O.map(r=>r.name.length));e.info("lunora cloudflare <tool> — tools for an app deployed to your own Cloudflare account:");for(const r of O)e.info(` ${r.name.padEnd(t)} ${r.summary}`),r.usage!==""&&e.info(` ${" ".repeat(t)} lunora cloudflare ${r.name} ${r.usage}`);return e.info("Run `lunora cloudflare --help` for every tool's arguments and options."),{code:0}},Pr=(e,t,r)=>{const{error:o,target:n}=De(e,r);return n===void 0?o??"no deploy target":n==="cloudflare"?void 0:`${r===void 0?`this project deploys to ${Mr[n]??`"${n}"`}`:`\`--target ${n}\``} — \`lunora cloudflare ${t}\` only applies to Cloudflare.`},Gr=(e,{logger:t,rest:r})=>r.length===0?void 0:T(t,u.USAGE,`cloudflare ${e}: takes no arguments, got "${r.join(" ")}"`),Fr=async e=>{const{cwd:t,logger:r,options:o}=e;return Gr("ai-gateway",e)??Xe({cwd:t,dryRun:o.dryRun===!0,id:o.id,logger:r,logs:o.logs})},xr=async({cwd:e,format:t,logger:r,options:o,rest:n})=>{const a=n[0]??"status";return jr(a)?pr({allowFloor:o.allowFloor===!0,cwd:e,dryRun:o.dryRun===!0,format:t,logger:r,replaceRecipients:o.replaceRecipients===!0,subcommand:a,yes:o.yes===!0,...o.email===void 0?{}:{emails:o.email},...o.webhook===void 0?{}:{webhooks:o.webhook},...o.multiplier===void 0?{}:{multiplier:o.multiplier},...o.threshold===void 0?{}:{thresholds:o.threshold}}):T(r,u.USAGE,`cloudflare alerts: unknown subcommand "${a}" — expected status | setup | test`)},qr=async({cwd:e,format:t,logger:r,options:o,rest:n})=>{const a=await wr({argument:n,cwd:e,env:o.env,format:t,logger:r,push:o.push===!0,tag:o.tag});return{code:a.code,delegated:a.delegated,error:a.error}},Br=async({cwd:e,format:t,logger:r,options:o,rest:n})=>{const[a,s]=n;if(!Ar(a))return T(r,u.USAGE,`cloudflare deployments: unknown subcommand "${a??""}" — expected list | inspect | rollback | promote`);const i=await $r({cwd:e,env:o.env,format:t,logger:r,message:o.message,subcommand:a,versionId:s,yes:o.yes===!0});return{code:i.code,delegated:i.delegated,error:i.error}},Jr=async({cwd:e,logger:t,options:r,rest:o})=>o.length>1?T(t,u.USAGE,`cloudflare profile: takes at most one argument (the worker), got "${o.join(" ")}"`):Ur({actorId:r.actorId,cwd:e,durationMs:r.durationMs,env:r.env,logger:t,namespaceId:r.namespaceId,out:r.out,type:r.type,version:r.versionId,worker:o[0]}),Wr={"ai-gateway":Fr,alerts:xr,containers:qr,deployments:Br,profile:Jr},so=Ue(async({argument:e,cwd:t,format:r,logger:o,options:n})=>{const[a,...s]=e;if(a===void 0||a==="")return Lr(o);const i=Rr(a,s);if(i===void 0)return T(o,u.USAGE,`cloudflare: unknown tool "${a}" — expected ${O.map(f=>f.name).join(" | ")}`);const{tool:c}=i,d=Pr(t,c,n.target);return d!==void 0?T(o,u.USAGE,d):Wr[c]({cwd:t,format:r,logger:o,options:n,rest:i.rest})});export{so as execute};
@@ -1,12 +1,12 @@
1
- import{dirname as L,join as w,resolve as q,relative as F,extname as Ne,sep as re}from"node:path";import{discoverMigrations as xe,runCodegen as Le,readServiceBindings as Oe}from"@lunora/codegen";import{readLinkedProject as he,resolveSchemaDirectory as P,startDevProcess as Me,acceptsConnection as Ue,COMPOSED_WORKER_ENTRY as te,discoverContainerInfo as pe,writeLinkedProject as Fe,discoverSchemaInfo as ve,DEV_VARS_FILE as S,parseDevVariableEntries as ye,isMintableSecretKey as ne,secretSourcesFromBindings as He,inferLunoraBindings as we,requiredSecrets as We,generateSecretValue as Be,upsertDevVariableLine as Ge,writeDevVariablesFileAtomically as Ve,resolveLazyFunctions as ke,createDiscoveryCache as ze,resolveDeployDriver as K,planToolchainInvocation as be,runPostCodegenHook as qe}from"@lunora/config";import{bindingsNeedingDatabase as Ke,findWranglerFile as O,readWranglerJsonc as A,mergeWranglerEnvironment as Y,applyModify as $e,HYPERDRIVE_PLACEHOLDER_ID as Ye,warnCloudflareCliConfigOnce as Je,validateWranglerProject as Xe,wranglerCodegenInputs as Qe,reconcileWranglerBindings as Ze,reconcileWranglerCompatibilityDate as er,reconcileWranglerCrons as rr,describePreservedCrons as tr}from"@lunora/config/cloudflare";import{Spinner as nr}from"@visulima/spinner";import{r as or,a as ar,e as ir}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as sr}from"../packem_shared/api-spec-lYyq4vL6.mjs";import{mkdirSync as Se,writeFileSync as D,existsSync as v,readFileSync as k,rmSync as cr,mkdtempSync as dr,readdirSync as lr}from"node:fs";import{m as ur,e as gr,i as fr,b as mr,a as hr}from"../packem_shared/secret-key-8DPOH98z.mjs";import{w as pr}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{d as vr}from"../packem_shared/command-CB4JM-Jl.mjs";import{r as J}from"../packem_shared/wrangler-name-Dsk5K1f-.mjs";import{a as yr}from"../packem_shared/deploy-target-resolve-BTCW1Iv4.mjs";import{EXIT_CODE as y}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{spawn as wr}from"node:child_process";import{randomUUID as kr,createHash as br}from"node:crypto";import{setTimeout as $r}from"node:timers/promises";import{toolchainExecArgs as C,detectPackageManager as R,execArgsFor as Ee}from"@lunora/config/cli";import{f as Sr}from"../packem_shared/free-port-DjbFhaaT.mjs";import{containerBuildTag as Er}from"@lunora/container";import{i as Ar,a as Dr}from"../packem_shared/docker-AqLAkOyY.mjs";import{defaultSpawner as M}from"../packem_shared/createRecordingSpawner-Ch7zuQQE.mjs";import{r as Ae}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{p as Rr,H as Cr,a as _r,r as Pr}from"../packem_shared/health-probe-Bw9JFfIy.mjs";import{join as $}from"@visulima/path";import{r as Ir,c as Tr}from"../packem_shared/cloudflare-credentials-BVmZnDZk.mjs";import{Project as jr}from"ts-morph";import{runMigrateDataCommand as Nr}from"../packem_shared/runMigrateGenerateCommand-BwemPIOz.mjs";import{c as xr}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{l as Lr}from"../packem_shared/wrangler-secrets-CTQPpalP.mjs";const Or=Object.freeze({edges:[],nodes:[],modules:[],unresolved:[],version:1}),Mr=20,oe=e=>`${e.from} -${e.kind}-> ${e.to}`,N=(e,r)=>{const n=new Set(e);return r.filter(t=>!n.has(t)).toSorted((t,o)=>t.localeCompare(o))},Ur=(e,r)=>{const n=e.modules.map(i=>i.name),t=r.modules.map(i=>i.name),o=e.edges.map(i=>oe(i)),a=r.edges.map(i=>oe(i));return{addedEdges:N(o,a),addedModules:N(n,t),removedEdges:N(a,o),removedModules:N(t,n)}},x=(e,r,n)=>{if(n.length===0)return[];const t=n.slice(0,Mr).map(a=>` ${e} ${a}`),o=n.length-t.length;return[`${r}:`,...t,...o>0?[` … and ${o.toString()} more`]:[]]},Fr=e=>{const r=[...x("+","modules added",e.addedModules),...x("-","modules removed",e.removedModules),...x("+","edges added",e.addedEdges),...x("-","edges removed",e.removedEdges)];return r.length===0?void 0:`architecture changes since the last deploy:
1
+ import{dirname as U,join as $,resolve as q,relative as K,extname as tr,sep as Q}from"node:path";import{PROJECT_CONFIG_FILENAMES as nr,isTestPath as Z,discoverMigrations as or,readServiceBindings as Ee,runCodegen as sr}from"@lunora/codegen";import{readLinkedProject as Ae,resolveSchemaDirectory as _,startDevProcess as ar,acceptsConnection as ir,COMPOSED_WORKER_ENTRY as de,discoverContainerInfo as Te,writeLinkedProject as cr,discoverSchemaInfo as Re,DEV_VARS_FILE as A,parseDevVariableEntries as De,isMintableSecretKey as le,secretSourcesFromBindings as dr,inferLunoraBindings as _e,requiredSecrets as lr,generateSecretValue as ur,upsertDevVariableLine as gr,writeDevVariablesFileAtomically as fr,resolveLazyFunctions as Pe,createDiscoveryCache as hr,resolveDeployDriver as te,planToolchainInvocation as Oe,runPostCodegenHook as mr}from"@lunora/config";import{bindingsNeedingDatabase as pr,findWranglerFile as j,readWranglerJsonc as T,mergeWranglerEnvironment as G,applyModify as Ne,HYPERDRIVE_PLACEHOLDER_ID as vr,warnCloudflareCliConfigOnce as yr,validateWranglerProject as wr,wranglerCodegenInputs as kr,reconcileWranglerBindings as br,reconcileWranglerCompatibilityDate as Sr,reconcileWranglerCrons as $r,describePreservedCrons as Er}from"@lunora/config/cloudflare";import{Spinner as Ar}from"@visulima/spinner";import{r as Tr,a as Rr,e as Dr}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as _r}from"../packem_shared/api-spec-lYyq4vL6.mjs";import{mkdirSync as Ie,writeFileSync as P,existsSync as k,readFileSync as S,rmSync as Pr,mkdtempSync as Or,readdirSync as Ce,realpathSync as Nr,statSync as je}from"node:fs";import{m as Ir,e as Cr,i as jr,b as xr,a as Lr}from"../packem_shared/secret-key-8DPOH98z.mjs";import{w as Mr}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{d as Fr}from"../packem_shared/command-CB4JM-Jl.mjs";import{r as ne}from"../packem_shared/wrangler-name-Dsk5K1f-.mjs";import{a as Ur}from"../packem_shared/deploy-target-resolve-BTCW1Iv4.mjs";import{EXIT_CODE as b}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{spawn as Hr}from"node:child_process";import{randomUUID as qr,createHash as Gr}from"node:crypto";import{setTimeout as Wr}from"node:timers/promises";import{toolchainExecArgs as N,detectPackageManager as O,execArgsFor as xe}from"@lunora/config/cli";import{f as Br}from"../packem_shared/free-port-DjbFhaaT.mjs";import{containerBuildTag as Kr}from"@lunora/container";import{i as Vr,a as zr}from"../packem_shared/docker-AqLAkOyY.mjs";import{defaultSpawner as W}from"../packem_shared/createRecordingSpawner-Ch7zuQQE.mjs";import{r as Le}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{p as Jr,H as Yr,a as Xr,r as Qr}from"../packem_shared/health-probe-Bw9JFfIy.mjs";import{runAdvisor as Zr,openShardAccess as ue}from"@lunora/advisor";import{join as w,relative as I,dirname as Me}from"@visulima/path";import{Project as Fe,SyntaxKind as v,Node as y}from"ts-morph";import{r as et,c as rt}from"../packem_shared/cloudflare-credentials-BVmZnDZk.mjs";import{runMigrateDataCommand as tt}from"../packem_shared/runMigrateGenerateCommand-BwemPIOz.mjs";import{c as nt}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{l as ot}from"../packem_shared/wrangler-secrets-CTQPpalP.mjs";const st=Object.freeze({edges:[],nodes:[],modules:[],unresolved:[],version:1}),at=20,ge=e=>`${e.from} -${e.kind}-> ${e.to}`,M=(e,r)=>{const n=new Set(e);return r.filter(t=>!n.has(t)).toSorted((t,o)=>t.localeCompare(o))},it=(e,r)=>{const n=e.modules.map(a=>a.name),t=r.modules.map(a=>a.name),o=e.edges.map(a=>ge(a)),s=r.edges.map(a=>ge(a));return{addedEdges:M(o,s),addedModules:M(n,t),removedEdges:M(s,o),removedModules:M(t,n)}},F=(e,r,n)=>{if(n.length===0)return[];const t=n.slice(0,at).map(s=>` ${e} ${s}`),o=n.length-t.length;return[`${r}:`,...t,...o>0?[` … and ${o.toString()} more`]:[]]},ct=e=>{const r=[...F("+","modules added",e.addedModules),...F("-","modules removed",e.removedModules),...F("+","edges added",e.addedEdges),...F("-","edges removed",e.removedEdges)];return r.length===0?void 0:`architecture changes since the last deploy:
2
2
  ${r.join(`
3
- `)}`},Hr=(e,r)=>w(e,".lunora",r===void 0?"architecture.json":`architecture.${r}.json`),Wr=e=>{if(v(e))try{const r=JSON.parse(k(e,"utf8"));return r.version===1&&Array.isArray(r.modules)&&Array.isArray(r.edges)?r:void 0}catch{return}},Br=e=>{const{cwd:r,environment:n,logger:t}=e,o=Hr(r,n),a=Wr(o),i=e.current??(a===void 0?void 0:Or);if(i===void 0)return;const s=a===void 0?void 0:Fr(Ur(a,i));return s!==void 0&&t.info(s),()=>{try{Se(L(o),{recursive:!0}),D(o,`${JSON.stringify(i,void 0,2)}
4
- `,"utf8")}catch(c){t.warn(`could not record the deployed architecture at ${o}: ${c instanceof Error?c.message:String(c)}`)}}},Gr=e=>{const{cwd:r,env:n,logger:t,mintedSecretsFile:o}=e;try{const a=he(r),i=a?.workerName??J(r),s=e.url??a?.workerUrl;t.success("deploy complete"),t.info(` worker: ${i??"(see wrangler output above)"}`),n!==void 0&&t.info(` env: ${n}`),s===void 0?t.info(" url: run `lunora link --url <https://your-worker>` to record it"):t.info(` url: ${s}`),o!==void 0&&t.info(` secrets: generated value(s) recorded in ${o}`),e.logsAvailable&&t.info(" logs: lunora logs")}catch{}},Vr=/\/index$/u,zr=/[^\dA-Za-z]/gu,qr=e=>e.replace(Vr,"").split("/").map(r=>r.replaceAll(zr,"_")),Kr=e=>qr(e).join("_"),Yr=18787,ae=3,De=12e4,Jr=5e3,H=10,Xr=new Set([".js",".mjs",".mts",".ts",".tsx"]),Qr=/\(void 0\)|is not a function|before initialization|of undefined/u,Zr=e=>typeof e=="object"&&e!==null&&typeof e.functionPath=="string"&&typeof e.message=="string",et=e=>{const r=P(e),n=new Map;let t;try{t=lr(w(e,r),{recursive:!0,encoding:"utf8"})}catch{return n}for(const o of t){const a=Ne(o);Xr.has(a)&&!o.split(re).some(i=>i==="_generated"||i==="node_modules")&&n.set(Kr(o.slice(0,-a.length).split(re).join("/")),w(r,o))}return n},rt=(e,r)=>{const n=et(e),t=new Map;for(const{functionPath:o,message:a}of r){const i=o.lastIndexOf(":"),s=o.slice(0,i),c=`${s}\0${a}`,d=t.get(c)??{exports:[],message:a,namespace:s};d.exports.push(o.slice(i+1)),t.set(c,d)}return[...t.values()].map(({exports:o,message:a,namespace:i})=>{const s=Qr.test(a)?`
5
- hint: if this module is part of a circular import, an import it reads is still undefined while it evaluates`:"";return` ${n.get(i)??i} (${o.join(", ")}): ${a}${s}`})};class b extends Error{skipped;constructor(r,n=!1){super(r),this.skipped=n}}const tt=(e,r)=>{const n=O(e),t=n===void 0?void 0:A(n).parsed;if(t===void 0)return{hasContainers:!1,main:void 0};const{merged:o}=Y(t,r);return{hasContainers:(o.containers??[]).length>0,main:o.main}},nt=({composedEntry:e,configPath:r,cwd:n,environment:t,toolchain:o})=>{if(o.devServer!=="workerd")return{skip:"this deploy target does not run on workerd"};const{hasContainers:a,main:i}=tt(n,t),s=e??i;if(typeof s!="string"||s.startsWith("virtual:")||!v(q(n,s)))return{skip:"the Worker entry is not a file on disk"};if(a)return{skip:"the project declares containers, which `wrangler dev` would build locally before the real container build"};const c=Ke(n,process.env,t,r);return c.length===0?{main:s}:{skip:`the Hyperdrive binding ${c.join(", ")} has no local database for wrangler dev`}},ot=async(e,r,n)=>{const t=await fetch(`http://127.0.0.1:${String(e)}/_lunora/__smoke_load`,{signal:AbortSignal.timeout(Math.max(0,n-Date.now()))}).catch(g=>{throw g instanceof Error&&g.name==="TimeoutError"?new b(`the smoke Worker booted but did not finish evaluating the lazy modules within ${String(De/1e3)}s — a module may be awaiting something that never settles. Pass --no-smoke-load to ship anyway.`):g});if(t.status>=500)throw new b(`the smoke Worker booted but failed while evaluating the lazy modules (HTTP ${String(t.status)}). Pass --no-smoke-load to ship anyway.`);const o=await t.text().catch(()=>"");let a;try{a=JSON.parse(o)}catch{a=void 0}const{checked:i,failures:s,run:c}=a??{};if(typeof i=="number"&&Array.isArray(s)&&s.every(g=>Zr(g)))return c===r?{checked:i,failures:s}:void 0;const d=t.headers.get("content-type")??"no content type",l=o.replaceAll(/\s+/gu," ").trim().slice(0,120);throw new b(`the smoke Worker answered with something other than the probe's result (HTTP ${String(t.status)}, ${d}${l===""?"":`: ${l}`}). A route that does not send /_lunora/* to the Worker first answers with the app's assets, so check run_worker_first. Pass --no-smoke-load to ship anyway.`)},V=(e,r)=>{try{process.kill(-e,r)}catch{}},ie=e=>{try{return process.kill(-e,0),!0}catch{return!1}},at=e=>{const r=()=>{V(e,"SIGKILL")},n=o=>{r(),process.kill(process.pid,o)},t=()=>{process.removeListener("exit",r),process.removeListener("SIGINT",n),process.removeListener("SIGTERM",n)};return process.once("exit",r),process.once("SIGINT",n),process.once("SIGTERM",n),t},W=async e=>{if(e===void 0)return;e.dispose();const{pid:r}=e;V(r,"SIGTERM");const n=Date.now()+Jr;for(;ie(r)&&Date.now()<n;)await $r(50);ie(r)&&V(r,"SIGKILL")},it=e=>Me(e).catch(async r=>{if(!await Ue(e.port))throw r}),st=(e,{checked:r,failures:n},t)=>{if(n.length===0){t.success(`${String(r)} lazy function(s) evaluate cleanly`);return}const o=rt(e,n),a=o.length>H?[` …and ${String(o.length-H)} more module(s)`]:[];throw new b([`${String(n.length)} of ${String(r)} lazy function(s) fail to load:`,...o.slice(0,H),...a,"Fix the module, or pass --no-smoke-load to ship anyway."].join(`
6
- `))},ct=(e,r,n)=>{if(e instanceof b&&!e.skipped)return n.error(e.message),e.message;if(e instanceof b){n.warn(`smoke-load skipped: ${e.message}`);return}const t=r.slice(-5).join(`
3
+ `)}`},dt=(e,r)=>$(e,".lunora",r===void 0?"architecture.json":`architecture.${r}.json`),lt=e=>{if(k(e))try{const r=JSON.parse(S(e,"utf8"));return r.version===1&&Array.isArray(r.modules)&&Array.isArray(r.edges)?r:void 0}catch{return}},ut=e=>{const{cwd:r,environment:n,logger:t}=e,o=dt(r,n),s=lt(o),a=e.current??(s===void 0?void 0:st);if(a===void 0)return;const i=s===void 0?void 0:ct(it(s,a));return i!==void 0&&t.info(i),()=>{try{Ie(U(o),{recursive:!0}),P(o,`${JSON.stringify(a,void 0,2)}
4
+ `,"utf8")}catch(c){t.warn(`could not record the deployed architecture at ${o}: ${c instanceof Error?c.message:String(c)}`)}}},gt=e=>{const{cwd:r,env:n,logger:t,mintedSecretsFile:o}=e;try{const s=Ae(r),a=s?.workerName??ne(r),i=e.url??s?.workerUrl;t.success("deploy complete"),t.info(` worker: ${a??"(see wrangler output above)"}`),n!==void 0&&t.info(` env: ${n}`),i===void 0?t.info(" url: run `lunora link --url <https://your-worker>` to record it"):t.info(` url: ${i}`),o!==void 0&&t.info(` secrets: generated value(s) recorded in ${o}`),e.logsAvailable&&t.info(" logs: lunora logs")}catch{}},ft=/\/index$/u,ht=/[^\dA-Za-z]/gu,mt=e=>e.replace(ft,"").split("/").map(r=>r.replaceAll(ht,"_")),pt=e=>mt(e).join("_"),vt=18787,fe=3,Ue=12e4,yt=5e3,V=10,wt=new Set([".js",".mjs",".mts",".ts",".tsx"]),kt=/\(void 0\)|is not a function|before initialization|of undefined/u,bt=e=>typeof e=="object"&&e!==null&&typeof e.functionPath=="string"&&typeof e.message=="string",St=e=>{const r=_(e),n=new Map;let t;try{t=Ce($(e,r),{recursive:!0,encoding:"utf8"})}catch{return n}for(const o of t){const s=tr(o);wt.has(s)&&!o.split(Q).some(a=>a==="_generated"||a==="node_modules")&&n.set(pt(o.slice(0,-s.length).split(Q).join("/")),$(r,o))}return n},$t=(e,r)=>{const n=St(e),t=new Map;for(const{functionPath:o,message:s}of r){const a=o.lastIndexOf(":"),i=o.slice(0,a),c=`${i}\0${s}`,d=t.get(c)??{exports:[],message:s,namespace:i};d.exports.push(o.slice(a+1)),t.set(c,d)}return[...t.values()].map(({exports:o,message:s,namespace:a})=>{const i=kt.test(s)?`
5
+ hint: if this module is part of a circular import, an import it reads is still undefined while it evaluates`:"";return` ${n.get(a)??a} (${o.join(", ")}): ${s}${i}`})};class E extends Error{skipped;constructor(r,n=!1){super(r),this.skipped=n}}const Et=(e,r)=>{const n=j(e),t=n===void 0?void 0:T(n).parsed;if(t===void 0)return{hasContainers:!1,main:void 0};const{merged:o}=G(t,r);return{hasContainers:(o.containers??[]).length>0,main:o.main}},At=({composedEntry:e,configPath:r,cwd:n,environment:t,toolchain:o})=>{if(o.devServer!=="workerd")return{skip:"this deploy target does not run on workerd"};const{hasContainers:s,main:a}=Et(n,t),i=e??a;if(typeof i!="string"||i.startsWith("virtual:")||!k(q(n,i)))return{skip:"the Worker entry is not a file on disk"};if(s)return{skip:"the project declares containers, which `wrangler dev` would build locally before the real container build"};const c=pr(n,process.env,t,r);return c.length===0?{main:i}:{skip:`the Hyperdrive binding ${c.join(", ")} has no local database for wrangler dev`}},Tt=async(e,r,n)=>{const t=await fetch(`http://127.0.0.1:${String(e)}/_lunora/__smoke_load`,{signal:AbortSignal.timeout(Math.max(0,n-Date.now()))}).catch(u=>{throw u instanceof Error&&u.name==="TimeoutError"?new E(`the smoke Worker booted but did not finish evaluating the lazy modules within ${String(Ue/1e3)}s — a module may be awaiting something that never settles. Pass --no-smoke-load to ship anyway.`):u});if(t.status>=500)throw new E(`the smoke Worker booted but failed while evaluating the lazy modules (HTTP ${String(t.status)}). Pass --no-smoke-load to ship anyway.`);const o=await t.text().catch(()=>"");let s;try{s=JSON.parse(o)}catch{s=void 0}const{checked:a,failures:i,run:c}=s??{};if(typeof a=="number"&&Array.isArray(i)&&i.every(u=>bt(u)))return c===r?{checked:a,failures:i}:void 0;const d=t.headers.get("content-type")??"no content type",l=o.replaceAll(/\s+/gu," ").trim().slice(0,120);throw new E(`the smoke Worker answered with something other than the probe's result (HTTP ${String(t.status)}, ${d}${l===""?"":`: ${l}`}). A route that does not send /_lunora/* to the Worker first answers with the app's assets, so check run_worker_first. Pass --no-smoke-load to ship anyway.`)},ee=(e,r)=>{try{process.kill(-e,r)}catch{}},he=e=>{try{return process.kill(-e,0),!0}catch{return!1}},Rt=e=>{const r=()=>{ee(e,"SIGKILL")},n=o=>{r(),process.kill(process.pid,o)},t=()=>{process.removeListener("exit",r),process.removeListener("SIGINT",n),process.removeListener("SIGTERM",n)};return process.once("exit",r),process.once("SIGINT",n),process.once("SIGTERM",n),t},z=async e=>{if(e===void 0)return;e.dispose();const{pid:r}=e;ee(r,"SIGTERM");const n=Date.now()+yt;for(;he(r)&&Date.now()<n;)await Wr(50);he(r)&&ee(r,"SIGKILL")},Dt=e=>ar(e).catch(async r=>{if(!await ir(e.port))throw r}),_t=(e,{checked:r,failures:n},t)=>{if(n.length===0){t.success(`${String(r)} lazy function(s) evaluate cleanly`);return}const o=$t(e,n),s=o.length>V?[` …and ${String(o.length-V)} more module(s)`]:[];throw new E([`${String(n.length)} of ${String(r)} lazy function(s) fail to load:`,...o.slice(0,V),...s,"Fix the module, or pass --no-smoke-load to ship anyway."].join(`
6
+ `))},Pt=(e,r,n)=>{if(e instanceof E&&!e.skipped)return n.error(e.message),e.message;if(e instanceof E){n.warn(`smoke-load skipped: ${e.message}`);return}const t=r.slice(-5).join(`
7
7
  `),o=`the smoke Worker did not start (${e instanceof Error?e.message:String(e)})${t===""?"":`
8
- ${t}`}. Either the entry fails when it loads, or local wrangler cannot run the project (a remote-only binding or a missing assets directory). Fix whichever it is, or pass --no-smoke-load to ship anyway.`;return n.error(o),o},dt=e=>{try{return Se(w(e,".lunora"),{recursive:!0}),dr(w(e,".lunora","smoke-"))}catch(r){throw new b(`could not create a directory for the check (${r instanceof Error?r.message:String(r)})`,!0)}},lt=async e=>{const{configPath:r,cwd:n,directory:t,environment:o,functionsFile:a,main:i,preferred:s,toolchain:c}=e;try{const d=w(t,"entry.ts"),l=kr();D(d,`export * from ${JSON.stringify(q(n,i))};
9
- import { loadAllFunctions } from ${JSON.stringify(a)};
8
+ ${t}`}. Either the entry fails when it loads, or local wrangler cannot run the project (a remote-only binding or a missing assets directory). Fix whichever it is, or pass --no-smoke-load to ship anyway.`;return n.error(o),o},Ot=e=>{try{return Ie($(e,".lunora"),{recursive:!0}),Or($(e,".lunora","smoke-"))}catch(r){throw new E(`could not create a directory for the check (${r instanceof Error?r.message:String(r)})`,!0)}},Nt=async e=>{const{configPath:r,cwd:n,directory:t,environment:o,functionsFile:s,main:a,preferred:i,toolchain:c}=e;try{const d=$(t,"entry.ts"),l=qr();P(d,`export * from ${JSON.stringify(q(n,a))};
9
+ import { loadAllFunctions } from ${JSON.stringify(s)};
10
10
 
11
11
  const runId = ${JSON.stringify(l)};
12
12
 
@@ -15,11 +15,11 @@ export default {
15
15
  return Response.json({ ...(await loadAllFunctions()), run: runId });
16
16
  },
17
17
  };
18
- `);const g=await Sr(s),{args:f,command:m}=C(R(n),c.dev({configPath:r===void 0?void 0:F(n,r),environment:o,extraArgs:[F(n,d),"--local","--local-protocol","http","--ip","127.0.0.1","--port",String(g),"--persist-to",F(n,w(t,"state"))]}));return{args:f,command:m,port:g,runId:l}}catch(d){throw new b(`could not prepare the check (${d instanceof Error?d.message:String(d)})`,!0)}},ut=async e=>{const{configPath:r,cwd:n,environment:t,launcher:o,logger:a,toolchain:i}=e,s=w(n,P(n),"_generated","functions.ts");if(!v(s)||!k(s,"utf8").includes("export const loadAllFunctions"))return;const c=nt(e);if("skip"in c){a.warn(`smoke-load skipped: ${c.skip}, so lazy modules are not evaluated before deploy`);return}const{main:d}=c,l=[];let g,f;const m=Date.now()+De,u=process.platform!=="win32",h=(p,I,T)=>{const E=wr(p,[...I],{cwd:T.cwd,detached:u,shell:T.shell,stdio:["ignore","pipe","pipe"]});return u&&E.pid!==void 0&&(f={dispose:at(E.pid),pid:E.pid}),E};try{g=dt(n),a.info("smoke-loading lazy function modules in workerd");let p=Yr;for(let I=0;I<ae;I+=1){const{args:T,command:E,port:U,runId:je}=await lt({configPath:r,cwd:n,directory:g,environment:t,functionsFile:s,main:d,preferred:p,toolchain:i});p=U+1;const ee=await it({args:T,command:E,cwd:n,spawn:o??h,label:"wrangler dev (smoke-load)",notFound:"`wrangler` was not found",onLine:j=>{l.push(j)},port:U,readyTimeoutMs:Math.max(0,m-Date.now()),shell:process.platform==="win32"});if(ee===void 0){await W(f),f=void 0;continue}try{const j=await ot(U,je,m);if(j!==void 0){st(n,j,a);return}}finally{await ee.stop(),await W(f),f=void 0}}throw new b(`the smoke port was answered by other runs on all ${String(ae)} attempts`,!0)}catch(p){return ct(p,l,a)}finally{if(await W(f),g!==void 0)try{cr(g,{force:!0,recursive:!0})}catch{}}},gt=async e=>{if(e.targets.length===0)return{builtTags:[],code:0};if(!(e.railpackAvailable??Ar)()){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??M,n=[];for(const t of e.targets){const o=Er(t.exportName),a={args:["build",t.buildDir,"--name",o],command:"railpack",cwd:e.cwd},i=Ee(R(e.cwd),"wrangler",["containers","push",o]),s={args:i.args,command:i.command,cwd:e.cwd};e.logger.info(`railpack: building "${t.exportName}" → ${o} from ${t.buildDir}`);const c=await r(a);if(c.code!==0){const l=`railpack build failed for container "${t.exportName}" (${t.buildDir})`;return e.logger.error(l),{builtTags:n,code:c.code,error:l}}e.logger.info(`railpack: pushing ${o} to the Cloudflare Registry`);const d=await r(s);if(d.code!==0){const l=`wrangler containers push failed for "${t.exportName}" (${o})`;return e.logger.error(l),{builtTags:n,code:d.code,error:l}}n.push(o)}return{builtTags:n,code:0}},ft=e=>{const n=[O(e),w(e,"package.json")].filter(t=>t!==void 0&&v(t)).map(t=>[t,k(t,"utf8")]);return()=>{for(const[t,o]of n)k(t,"utf8")!==o&&D(t,o,"utf8")}},Re="<replace-with-d1-create-id>",se=e=>Array.isArray(e)?e.filter(r=>r!=null):void 0,X=(e,r)=>{const n=O(e);if(!n)return;const{parsed:t}=A(n);if(t===void 0)return;const{error:o,merged:a}=Y(t,r),i=o===void 0?a:t,{containers:s,d1_databases:c,vars:d}=i;return{containers:se(s),d1_databases:se(c),vars:typeof d=="object"&&d!==null&&!Array.isArray(d)?d:void 0}},mt=/^127(?:\.\d{1,3}){3}$/,ht=e=>{try{const{hostname:r}=new URL(e);return r==="localhost"||mt.test(r)||r==="::1"||r==="[::1]"}catch{return!1}},pt=e=>e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.includes("Dockerfile"),vt=(e,r,n,t="deploy",o)=>{const a=(X(e,o)?.containers??[]).filter(s=>typeof s?.image=="string"&&pt(s.image));if(a.length===0||n())return;const i=`${t} blocked: wrangler.jsonc declares ${String(a.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},Q=e=>v($(e,te))?te:void 0,yt=(e,r,n="deploy",t)=>{for(const o of pe(e,"lunora",t).containers){const a=o.schedulingPolicy===void 0?o.image:void 0,s=[...a?.kind==="dockerfile"?[{field:"image",path:a.dockerfilePath}]:[],...Object.entries(o.schedulingPolicy==="durable_object"?o.images??{}:{}).flatMap(([c,d])=>d.kind==="dockerfile"?[{field:`images["${c}"]`,path:d.dockerfilePath}]:[])].find(c=>!v($(e,c.path)));if(s!==void 0){const c=`${n} blocked: container "${o.exportName}" references a Dockerfile at "${s.path}" that does not exist. Create it or fix the \`${s.field}\` path in lunora/containers.ts.`;return r.error(c),c}if(a?.kind==="build"&&!v($(e,a.buildDir))){const c=`${n} blocked: container "${o.exportName}" references a Railpack build directory "${a.buildDir}" that does not exist. Create it or fix the \`image.build\` path in lunora/containers.ts.`;return r.error(c),c}}},wt=(e,r)=>(X(e,r)?.d1_databases??[]).find(n=>n.database_id===Re)?.binding,kt=e=>{if(!e.migrate||e.dryRun||e.preview)return;if(e.migrateUrl===void 0){const n="--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(n),n}if(e.migrateYes!==!0){const n="--migrate runs production data migrations after deploy. Re-run with --migrate-yes to confirm.";return e.logger.error(n),n}const r=e.migrateToken??process.env.LUNORA_ADMIN_TOKEN;if(r===void 0||r===""){const n="admin token required for --migrate — pass --migrate-token or set LUNORA_ADMIN_TOKEN";return e.logger.error(n),n}},bt=(e,r,n="deploy",t)=>{const o=wt(e,t);if(o===void 0)return;const a=`${n} blocked: the "${o}" D1 binding has a placeholder database_id ("${Re}"). 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(a),a},$t=(e,r,n="deploy",t)=>{const o=X(e,t)?.vars;if(!o)return;const a=Object.entries(o).filter(([,s])=>typeof s=="string"&&ht(s)).map(([s])=>s).toSorted((s,c)=>s.localeCompare(c));if(a.length===0)return;const i=`${n} blocked: ${a.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},St=(e,r,n)=>{const t=bt(e,r.logger,n,r.env);if(t!==void 0)return{code:y.USAGE,error:t};const o=$t(e,r.logger,n,r.env);if(o!==void 0)return{code:y.USAGE,error:o};const a=yt(e,r.logger,n,r.discoveryCache);if(a!==void 0)return{code:y.USAGE,error:a};const i=vt(e,r.logger,r.dockerAvailable??Dr,n,r.env);return i===void 0?void 0:{code:y.MISSING_DEPENDENCY,error:i}},ce=32,Et=15e3,At=5432,Dt=3306,Rt=/[^a-z0-9-]/gu,Ct=/[^A-Za-z0-9]/gu,_t=/-$/u,_=e=>`LUNORA_${e.replaceAll(Ct,"_").toUpperCase()}_URL`,Pt=e=>{const r=new Map;for(const n of e){const t=_(n),o=r.get(t);if(o!==void 0)return{bindings:[o,n],variable:t};r.set(t,n)}},de=7,It=(e,r)=>{const n=`${e}-${r}`.toLowerCase(),t=n.replaceAll(Rt,"-");if(t===n&&t.length<=ce)return t;const o=br("sha256").update(n).digest("hex").slice(0,de-1);return`${t.slice(0,ce-de).replace(_t,"")}-${o}`},le=e=>e==="postgresql"?"postgres":e==="mariadb"?"mysql":e,Tt=e=>e==="mysql"?Dt:At,jt=e=>{try{const r=new URL(e),n=r.protocol.slice(0,-1),t=decodeURIComponent(r.pathname.slice(1));return!["mariadb","mysql","postgres","postgresql"].includes(n)||r.hostname===""||t===""?void 0:{database:t,host:r.hostname,password:decodeURIComponent(r.password),port:r.port===""?Tt(le(n)):Number(r.port),scheme:le(n),user:decodeURIComponent(r.username)}}catch{return}},Nt=(e,r)=>{const n=typeof r?.password=="string"?r.password:"",t=n===""?[]:[n,JSON.stringify(n).slice(1,-1),encodeURIComponent(n)];let o=e;for(const a of t)o=o.replaceAll(a,"<redacted>");return o.split(" ").map(a=>a.includes("://")?"<url>":a).join(" ")},Ce=e=>(Array.isArray(e)?e:[]).flatMap((r,n)=>{const{binding:t,id:o}=typeof r=="object"&&r!==null?r:{};return typeof t=="string"&&o===Ye?[{binding:t,index:n}]:[]}),z=e=>{let r="";try{const{errors:n}=JSON.parse(e.text);r=(n??[]).flatMap(t=>typeof t.message=="string"?[t.message]:[]).slice(0,2).join("; ")}catch{}return r===""?`HTTP ${String(e.status)}`:`HTTP ${String(e.status)}: ${r}`},xt=e=>typeof e=="string"||typeof e=="number"?e.toString():void 0,Lt=["scheme","host","port","database","user"],Ot=e=>e==="postgresql"?"postgres":e,ue=(e,r)=>{const n=xt(r);return e==="scheme"?Ot(n):n},ge=50,Mt=async(e,r)=>{for(let n=1;n<=ge;n+=1){const t=await e(n===1?"/hyperdrive/configs":`/hyperdrive/configs?page=${String(n)}`);if(!t.ok)throw new Error(`listing Hyperdrive configs failed (${z(t)})`);if(!Array.isArray(t.body.result))throw new TypeError("the listing of Hyperdrive configs had no result list");const o=t.body.result.find(i=>i.name===r),a=typeof t.body.result_info=="object"&&t.body.result_info!==null?t.body.result_info:{};if(o!==void 0||typeof a.total_pages!="number"||n>=a.total_pages)return o}throw new Error(`the listing of Hyperdrive configs has more than ${String(ge)} pages, so "${r}" can't be shown to be absent`)},Ut=async(e,r,n)=>{const t=await Mt(e,r);if(typeof t?.id=="string"){const i=Lt.filter(c=>ue(c,t.origin?.[c])!==ue(c,n[c]));if(i.length>0)throw new Error(`a Hyperdrive config named "${r}" already exists for a different origin, or one that can't be confirmed (${i.join(", ")}). Delete it, or rename the Worker, so the binding does not reach the wrong database.`);const s=await e(`/hyperdrive/configs/${encodeURIComponent(t.id)}`,{body:JSON.stringify({origin:n}),method:"PATCH"});if(!s.ok)throw new Error(`updating its credentials failed (${z(s)})`);return{id:t.id,reused:!0}}const o=await e("/hyperdrive/configs",{body:JSON.stringify({name:r,origin:n}),method:"POST"});if(!o.ok)throw new Error(`creating it failed (${z(o)})`);const{id:a}=typeof o.body.result=="object"&&o.body.result!==null?o.body.result:{};if(typeof a!="string")throw new TypeError("the response carried no id");return{id:a,reused:!1}},Ft=(e,r,n,t)=>r===void 0&&t?`${_(e)} is set but is not a usable connection string for the "${e}" Hyperdrive binding: it needs a postgres://, postgresql:// or mysql:// scheme, a host and a database name, with any special characters percent-encoded.`:r===void 0?`the "${e}" Hyperdrive binding has no config yet. Set ${_(e)} to its postgres:// or mysql:// connection string and Lunora creates the config, or run \`wrangler hyperdrive create\` and put its id in wrangler.jsonc.`:n?void 0:`creating the "${e}" Hyperdrive config needs CLOUDFLARE_API_TOKEN (Hyperdrive: Edit) and CLOUDFLARE_ACCOUNT_ID, or run \`wrangler hyperdrive create\` and put its id in wrangler.jsonc.`,Ht=async(e,r)=>{const n=It(e.workerName,e.binding),{id:t,reused:o}=await Ut(async(a,i)=>Tr({accountId:e.accountId,apiToken:e.token,...e.fetch===void 0?{}:{fetch:e.fetch},init:{...i,signal:AbortSignal.timeout(Et)},path:a}),n,e.origin);return e.logger.success(`${o?"reusing":"created"} Hyperdrive config "${n}" for ${e.binding} → ${e.wranglerPath}`),{id:t,text:$e(r,[...e.path,e.index,"id"],t)}},Wt=e=>e===void 0||e===""?void 0:e,Bt=e=>{const r=w(L(e),".wrangler","deploy","config.json");try{const{configPath:n}=JSON.parse(k(r,"utf8"));return typeof n=="string"?q(L(r),n):void 0}catch{return}},Gt=(e,r,n,t,o)=>{const a=Bt(e);if(a===void 0||a===e)return;if(t.built!==t.deployed){o.warn(`the build output ${a} was made for ${t.built===void 0?"the default environment":`"${t.built}"`}, not ${t.deployed===void 0?"the default environment":`"${t.deployed}"`}, so the "${r}" Hyperdrive id was not written there. Build with CLOUDFLARE_ENV set to the environment you deploy, then deploy again.`);return}let i;try{i=A(a)}catch{return}const s=Ce(i.parsed?.hyperdrive).find(c=>c.binding===r);s!==void 0&&D(a,$e(i.text,["hyperdrive",s.index,"id"],n),"utf8")},Vt=(e,r)=>{const n=typeof e.name=="string"&&e.name!==""?e.name:"lunora";if(r===void 0)return n;const t=e.env?.[r]?.name;return typeof t=="string"&&t!==""?t:`${n}-${r}`},Z=(e,r)=>{const n=O(e),t=n===void 0?void 0:A(n).parsed;if(n===void 0||t===void 0)return;const o=r===void 0?void 0:t.env?.[r],a=Ce(r===void 0?t.hyperdrive:o?.hyperdrive);return a.length===0?void 0:{accountId:o?.account_id??t.account_id,entries:a,path:r===void 0?["hyperdrive"]:["env",r,"hyperdrive"],workerName:Vt(t,r),wranglerPath:n}},zt=(e,r,n)=>{const t=Pt(e.map(({binding:o})=>o));if(t!==void 0){const o=`deploy blocked: the Hyperdrive bindings ${t.bindings.map(a=>`"${a}"`).join(" and ")} both read ${t.variable} and would share one config. Rename one so their names differ in letters or digits, not only in punctuation.`;return n.logger.error(o),o}for(const{binding:o,origin:a,supplied:i}of e){const s=Ft(o,a,r,i);if(s!==void 0&&n.dryRun===!0)n.logger.warn(`dry run: ${s} A real deploy stops here.`);else if(s!==void 0){const c=`deploy blocked: ${s}`;return n.logger.error(c),c}}},qt=async e=>{const r=Z(e.cwd,e.wranglerEnvironment);if(r===void 0)return;const{entries:n,path:t,wranglerPath:o}=r,a=e.environment??process.env,{accountId:i,token:s}=Ir(a,r.accountId),c=n.map(({binding:l})=>{const g=a[_(l)]??"";return{binding:l,origin:jt(g),supplied:g!==""}}),d=zt(c,s!==void 0&&i!==void 0,e);if(d!==void 0)return d;if(!(e.dryRun===!0||e.checkOnly===!0))for(const[l,{binding:g,index:f}]of n.entries()){const m=c[l]?.origin;if(!(m===void 0||s===void 0||i===void 0))try{const{id:u,text:h}=await Ht({accountId:i,binding:g,fetch:e.fetch,index:f,logger:e.logger,origin:m,path:t,token:s,workerName:r.workerName,wranglerPath:o},k(o,"utf8"));D(o,h,"utf8"),Gt(o,g,u,{built:Wt(a.CLOUDFLARE_ENV),deployed:e.wranglerEnvironment},e.logger)}catch(u){const h=u instanceof Error?u.message:String(u),p=`deploy blocked: the "${g}" Hyperdrive config could not be set up: ${Nt(h,c[l]?.origin)}`;return e.logger.error(p),p}}},Kt=(e,r)=>{const n=Z(e,r.env)?.entries[0]?.binding;if(n===void 0)return;const t=`prepare blocked: the "${n}" Hyperdrive binding still has its placeholder id. Run \`lunora deploy\` with ${_(n)} set to create the config, or put the id from \`wrangler hyperdrive create\` in wrangler.jsonc.`;return r.logger.error(t),t},Yt=(e,r)=>{const n=Z(e,r.env)?.entries[0]?.binding;if(n===void 0)return;const t=`deploy blocked: the "${n}" Hyperdrive binding has no config, and a --temporary deploy cannot create one: it would be made in your account while the Worker goes to a temporary one, which a temporary account has no database for. Deploy without --temporary.`;return r.logger.error(t),t},_e=async(e,r,n,t,o="create")=>{if(t==="cloudflare")return n==="prepare"?Kt(e,r):r.temporary===!0?Yt(e,r):qt({checkOnly:o==="check",cwd:e,dryRun:r.dryRun,logger:r.logger,wranglerEnvironment:r.env})},Jt=/https?:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/u,Xt=/https:\/\/[^\s"'<>]+/u,Qt=e=>{if(e===void 0)return;const r=Jt.exec(e);return r?r[0]:Xt.exec(e)?.[0]},fe=e=>e===void 0?"":` (--env ${e})`,Zt=({cwd:e,env:r,logger:n,now:t,url:o})=>{if(o!==void 0)try{const a=he(e);if(a!==void 0){if(a.workerUrl===o&&a.env===r)return;n.warn(`link: .lunora/project.json records ${a.workerUrl??"(no url)"}${fe(a.env)}, but this deploy published ${o}${fe(r)}. Keeping the recorded value — run \`lunora link --url ${o}${r===void 0?"":` --env ${r}`}\` to update it.`);return}const i=(t??(()=>new Date().toISOString()))();Fe(e,{env:r,linkedAt:i,workerName:J(e),workerUrl:o}),n.success(`link: recorded ${o} in .lunora/project.json (run \`lunora link\` to change)`)}catch{}},en=async(e,r)=>{const n=new jr({skipAddingFilesFromTsConfig:!0}),t=$(r,"lunora");let o;try{o=xe(n,t)}catch(a){const i=a instanceof Error?a.message:String(a);return e.logger.warn(`--migrate: could not discover migrations (${i}); skipping`),0}if(o.length===0)return e.logger.info("--migrate: no data migrations declared in lunora/"),0;e.logger.info(`--migrate: running ${String(o.length)} migration(s) against deployed worker`);for(const a of o){e.logger.info(`--migrate: up "${a.id}" (table "${a.table}")`);const i={cwd:r,fetchImpl:e.fetchImpl,id:a.id,logger:e.logger,prod:!0,subcommand:"up",token:e.migrateToken,url:e.migrateUrl,yes:e.migrateYes===!0},s=await Nr(i);if(s.code!==0)return e.logger.error(`--migrate: migration "${a.id}" failed — see output above`),s.code;e.logger.success(`--migrate: "${a.id}" applied`)}return 0},rn=async(e,r)=>{const{info:n}=ve(r,"lunora",e.discoveryCache),t=n?.vectorMetadata??[];if(t.length===0)return;const o=[];for(const s of t){const c=ur(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}o.push({index:s.index,property:s.property,type:c})}if(o.length===0)return;const i=(await gr({cwd:r,entries:o,exec:Ee(R(r),"wrangler",[]),logger:e.logger,spawner:e.spawner??M})).filter(s=>s.status!=="failed").length;i>0&&e.logger.success(`vectorize metadata indexes ready: ${String(i)}/${String(o.length)}`)},me=5,tn=2e3,nn=async(e,r,n)=>{if(e.healthCheck!==!0)return;const t=n??Ae({cwd:r,env:e.env});if(t===void 0){const a="--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(a),{error:a,ok:!1,url:""}}const o=await Rr({attempts:me,baseUrl:t,delayMs:tn,fetchImpl:e.healthFetch,paths:[Cr,_r],sleep:e.healthSleep});return o.error===void 0?(e.logger.success(`health check ok (${o.url})`),{ok:!0,url:o.url}):(e.logger.error(`--health-check: the deploy succeeded, but the new version did not answer after ${String(me)} attempt(s) — ${o.error}`),{error:o.error,ok:!1,url:o.url})},on=async(e,r,n,t,o,a)=>{await rn(e,r);const i=e.migrate?await en(e,r):0;return i===0&&o?.(),{code:i,descriptor:n,mintedSecretsFile:a,validation:t}},an=async({cwd:e,descriptor:r,mintedSecretsFile:n,options:t,reblessSchemaBaseline:o,recordArchitecture:a,stdout:i,validation:s})=>{const c={deployedAt:new Date().toISOString(),dryRun:t.dryRun===!0,env:t.env,preview:t.preview===!0,url:t.dryRun===!0?void 0:Qt(i),workerName:J(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:c,descriptor:r,mintedSecretsFile:n,validation:s};t.temporary!==!0&&(a?.(),Zt({cwd:e,env:t.env,logger:t.logger,url:c.url}));const d=await nn(t,e,c.url);return d?.error!==void 0?{code:y.UNAVAILABLE,deployment:c,descriptor:r,healthCheck:d,mintedSecretsFile:n,validation:s}:{...await on(t,e,r,s,o,n),deployment:c,healthCheck:d}},sn=(e,r,n)=>{const t=$(e,S);if(!v(t))return;let o;try{o=ye(k(t,"utf8")).length}catch{return}if(o===0)return;const a=n.toolchain?.secretPut!==void 0;r.warn(a?`Note: \`lunora deploy\` does not push secrets. ${S} has ${String(o)} key(s); if you changed them, run \`lunora env push --yes\` to update the deployed secrets.`:`Note: ${n.name} deploys read no secrets. ${S} has ${String(o)} key(s) that only the dev server sees; put the values the deployed worker needs in wrangler \`vars\`.`)},cn=async(e,r)=>{let n=[];try{n=He(await we({cache:r,projectRoot:e,schemaDir:P(e)}))}catch{}const t=We(n).map(a=>a.key);let o=[];try{const a=$(e,S);v(a)&&(o=ye(k(a,"utf8")).map(i=>i.key).filter(i=>fr(i)))}catch{}return[...new Set([...t,...o])]},dn=async(e,r,n,t)=>{const{logger:o}=r,a=r.spawner??M,i=R(e),s=r.env===void 0?"":` --env ${r.env}`,c=t.toolchain?.secretPut;if(c===void 0)return o.error(`deploy target "${t.id}" has no secret store; cannot push secrets`),{minted:[],ok:!1};const d=n.map(f=>({key:f,value:Be()})),l=t.toolchain?.secretBulk;if(l!==void 0&&d.length>=2){const f=C(i,l({environment:r.env,temporary:r.temporary})),m=await a({args:f.args,command:f.command,cwd:e,input:JSON.stringify(Object.fromEntries(d.map(u=>[u.key,u.value])))});if(m.code===0){for(const{key:u}of d)o.success(`generated + pushed ${u}`);return{minted:d,ok:!0}}o.warn(`bulk secret push failed (exit ${String(m.code)}); retrying one key at a time`)}const g=[];for(const{key:f,value:m}of d){const u=c({environment:r.env,key:f,temporary:r.temporary}),h=C(i,u),p=await a({args:h.args,command:h.command,cwd:e,input:m});if(p.code!==0)return o.error(`failed to push secret ${f} (exit ${String(p.code)}); set it manually with \`wrangler secret put ${f}${s}\`.`),{minted:g,ok:!1};g.push({key:f,value:m}),o.success(`generated + pushed ${f}`)}return{minted:g,ok:!0}},ln=/^[\w-]+$/u,B=[".dev.vars",".dev.vars.*","!.dev.vars.example"],un=/\r?\n/u,gn=(e,r)=>{const n=$(e,".gitignore");try{const t=v(n)?k(n,"utf8"):"",o=new Set(t.split(un).map(c=>c.trim())),a=B.filter(c=>!o.has(c));if(a.length===0)return;const i=a.some(c=>!c.startsWith("!"))?[...a.filter(c=>!c.startsWith("!")),...B.filter(c=>c.startsWith("!"))]:a,s=t.length>0&&!t.endsWith(`
18
+ `);const u=await Br(i),{args:g,command:f}=N(O(n),c.dev({configPath:r===void 0?void 0:K(n,r),environment:o,extraArgs:[K(n,d),"--local","--local-protocol","http","--ip","127.0.0.1","--port",String(u),"--persist-to",K(n,$(t,"state"))]}));return{args:g,command:f,port:u,runId:l}}catch(d){throw new E(`could not prepare the check (${d instanceof Error?d.message:String(d)})`,!0)}},It=async e=>{const{configPath:r,cwd:n,environment:t,launcher:o,logger:s,toolchain:a}=e,i=$(n,_(n),"_generated","functions.ts");if(!k(i)||!S(i,"utf8").includes("export const loadAllFunctions"))return;const c=At(e);if("skip"in c){s.warn(`smoke-load skipped: ${c.skip}, so lazy modules are not evaluated before deploy`);return}const{main:d}=c,l=[];let u,g;const f=Date.now()+Ue,h=process.platform!=="win32",m=(p,R,x)=>{const D=Hr(p,[...R],{cwd:x.cwd,detached:h,shell:x.shell,stdio:["ignore","pipe","pipe"]});return h&&D.pid!==void 0&&(g={dispose:Rt(D.pid),pid:D.pid}),D};try{u=Ot(n),s.info("smoke-loading lazy function modules in workerd");let p=vt;for(let R=0;R<fe;R+=1){const{args:x,command:D,port:B,runId:rr}=await Nt({configPath:r,cwd:n,directory:u,environment:t,functionsFile:i,main:d,preferred:p,toolchain:a});p=B+1;const ce=await Dt({args:x,command:D,cwd:n,spawn:o??m,label:"wrangler dev (smoke-load)",notFound:"`wrangler` was not found",onLine:L=>{l.push(L)},port:B,readyTimeoutMs:Math.max(0,f-Date.now()),shell:process.platform==="win32"});if(ce===void 0){await z(g),g=void 0;continue}try{const L=await Tt(B,rr,f);if(L!==void 0){_t(n,L,s);return}}finally{await ce.stop(),await z(g),g=void 0}}throw new E(`the smoke port was answered by other runs on all ${String(fe)} attempts`,!0)}catch(p){return Pt(p,l,s)}finally{if(await z(g),u!==void 0)try{Pr(u,{force:!0,recursive:!0})}catch{}}},Ct=async e=>{if(e.targets.length===0)return{builtTags:[],code:0};if(!(e.railpackAvailable??Vr)()){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??W,n=[];for(const t of e.targets){const o=Kr(t.exportName),s={args:["build",t.buildDir,"--name",o],command:"railpack",cwd:e.cwd},a=xe(O(e.cwd),"wrangler",["containers","push",o]),i={args:a.args,command:a.command,cwd:e.cwd};e.logger.info(`railpack: building "${t.exportName}" → ${o} from ${t.buildDir}`);const c=await r(s);if(c.code!==0){const l=`railpack build failed for container "${t.exportName}" (${t.buildDir})`;return e.logger.error(l),{builtTags:n,code:c.code,error:l}}e.logger.info(`railpack: pushing ${o} to the Cloudflare Registry`);const d=await r(i);if(d.code!==0){const l=`wrangler containers push failed for "${t.exportName}" (${o})`;return e.logger.error(l),{builtTags:n,code:d.code,error:l}}n.push(o)}return{builtTags:n,code:0}},jt=e=>{const n=[j(e),$(e,"package.json")].filter(t=>t!==void 0&&k(t)).map(t=>[t,S(t,"utf8")]);return()=>{for(const[t,o]of n)S(t,"utf8")!==o&&P(t,o,"utf8")}},He="<replace-with-d1-create-id>",me=e=>Array.isArray(e)?e.filter(r=>r!=null):void 0,oe=(e,r)=>{const n=j(e);if(!n)return;const{parsed:t}=T(n);if(t===void 0)return;const{error:o,merged:s}=G(t,r),a=o===void 0?s:t,{containers:i,d1_databases:c,vars:d}=a;return{containers:me(i),d1_databases:me(c),vars:typeof d=="object"&&d!==null&&!Array.isArray(d)?d:void 0}},xt=/^127(?:\.\d{1,3}){3}$/,Lt=e=>{try{const{hostname:r}=new URL(e);return r==="localhost"||xt.test(r)||r==="::1"||r==="[::1]"}catch{return!1}},Mt=e=>e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.includes("Dockerfile"),Ft=(e,r,n,t="deploy",o)=>{const s=(oe(e,o)?.containers??[]).filter(i=>typeof i?.image=="string"&&Mt(i.image));if(s.length===0||n())return;const a=`${t} blocked: wrangler.jsonc declares ${String(s.length)} container(s) built from a local Dockerfile, but no Docker-compatible engine is available. Start Docker (or Colima), or point the container's \`image\` at a pre-built registry reference. Note: container images must target linux/amd64.`;return r.error(a),a},se=e=>k(w(e,de))?de:void 0,Ut=(e,r,n="deploy",t)=>{for(const o of Te(e,"lunora",t).containers){const s=o.schedulingPolicy===void 0?o.image:void 0,i=[...s?.kind==="dockerfile"?[{field:"image",path:s.dockerfilePath}]:[],...Object.entries(o.schedulingPolicy==="durable_object"?o.images??{}:{}).flatMap(([c,d])=>d.kind==="dockerfile"?[{field:`images["${c}"]`,path:d.dockerfilePath}]:[])].find(c=>!k(w(e,c.path)));if(i!==void 0){const c=`${n} blocked: container "${o.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(c),c}if(s?.kind==="build"&&!k(w(e,s.buildDir))){const c=`${n} blocked: container "${o.exportName}" references a Railpack build directory "${s.buildDir}" that does not exist. Create it or fix the \`image.build\` path in lunora/containers.ts.`;return r.error(c),c}}},Ht=(e,r)=>(oe(e,r)?.d1_databases??[]).find(n=>n.database_id===He)?.binding,qt=e=>{if(!e.migrate||e.dryRun||e.preview)return;if(e.migrateUrl===void 0){const n="--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(n),n}if(e.migrateYes!==!0){const n="--migrate runs production data migrations after deploy. Re-run with --migrate-yes to confirm.";return e.logger.error(n),n}const r=e.migrateToken??process.env.LUNORA_ADMIN_TOKEN;if(r===void 0||r===""){const n="admin token required for --migrate — pass --migrate-token or set LUNORA_ADMIN_TOKEN";return e.logger.error(n),n}},Gt=(e,r,n="deploy",t)=>{const o=Ht(e,t);if(o===void 0)return;const s=`${n} blocked: the "${o}" D1 binding has a placeholder database_id ("${He}"). 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(s),s},Wt=(e,r,n="deploy",t)=>{const o=oe(e,t)?.vars;if(!o)return;const s=Object.entries(o).filter(([,i])=>typeof i=="string"&&Lt(i)).map(([i])=>i).toSorted((i,c)=>i.localeCompare(c));if(s.length===0)return;const a=`${n} blocked: ${s.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(a),a},Bt=["vite.config.ts","vite.config.mts","vite.config.cts","vite.config.js","vite.config.mjs","vite.config.cjs",...nr],qe=/\.(?:[cm]?[jt]s|tsx|jsx)$/u,Ge=/\.(?:test|spec)\.[cm]?[jt]sx?$/u,We="allowUnauthenticatedShardAccess",Kt=/[\\/]/u,Be=new Set(["_generated","build","dist","node_modules"]),Ke=(e,r)=>{const n=I(e,r).split(Kt);return qe.test(r)&&!Ge.test(r)&&!Z(n.join("/"))&&n.every(t=>t===".."||!t.startsWith(".")&&!Be.has(t))},pe=(e,r,n)=>{const{parsed:t}=T(r);if(t===void 0)return[];const{error:o,merged:s}=G(t,n),{main:a}=o===void 0?s:t,i=typeof a=="string"?w(Me(r),a):void 0;return i!==void 0&&k(i)&&Ke(e,i)?[i]:[]},ae=e=>e===void 0?!1:e.getKind()===v.FalseKeyword?!0:y.isParenthesizedExpression(e)||y.isAsExpression(e)||y.isSatisfiesExpression(e)||y.isTypeAssertion(e)||y.isNonNullExpression(e)?ae(e.getExpression()):!1,Vt=e=>{try{return je(e).isFile()}catch{return!1}},zt=new Set(["ELOOP","ENOENT","ENOTDIR"]),H=(e,r,n)=>{const t=r instanceof Error&&"code"in r&&typeof r.code=="string"?r.code:"";zt.has(t)||n.push(e)},Jt=(e,r)=>{try{return je(e)}catch(n){H(e,n,r);return}},Ve=(e,r)=>{try{return S(e,"utf8")}catch(n){H(e,n,r);return}},ze=(e,r,n,t=new Set)=>{let o;try{o=Nr(r)}catch(a){return H(r,a,n),[]}if(t.has(o))return[];t.add(o);let s;try{s=Ce(r)}catch(a){return H(r,a,n),[]}return s.flatMap(a=>{const i=w(r,a),c=Jt(i,n);if(c===void 0)return[];const d=I(e,i).split(Q).join("/");return c.isDirectory()?Be.has(a)||a.startsWith(".")||Z(`${d}/`)?[]:ze(e,i,n,t):c.isFile()&&qe.test(a)&&!Ge.test(a)&&!Z(d)?[i]:[]})},Yt=e=>{const r=y.isComputedPropertyName(e)?e.getExpression():e;return y.isStringLiteral(r)||y.isNoSubstitutionTemplateLiteral(r)?r.getLiteralValue():e.getText()},J=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],Xt=/\.(?:[cm]?js|jsx)$/u,Qt=(e,r)=>{if(!r.startsWith("."))return;const n=q(Me(e),r),t=n.replace(Xt,"");return[n,...J.map(s=>`${n}${s}`),...J.map(s=>w(n,`index${s}`)),...J.map(s=>`${t}${s}`)].find(s=>Vt(s))},Zt=e=>{if(e.getExpression().getText()!=="require")return;const[r]=e.getArguments();return r!==void 0&&(y.isStringLiteral(r)||y.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():void 0},en=e=>{const r=e.getModuleReference();if(!y.isExternalModuleReference(r))return;const n=r.getExpression();return y.isStringLiteral(n)?n.getLiteralValue():void 0},rn=(e,r,n,t)=>{const o=new Set(e),s=[...e],a=[];for(let i=0;i<s.length;i+=1){const c=s[i]??"",d=Ve(c,t);if(d===void 0)continue;const l=r.createSourceFile(I(n,c),d,{overwrite:!0}),u=[...l.getImportDeclarations().map(g=>g.getModuleSpecifierValue()),...l.getExportDeclarations().map(g=>g.getModuleSpecifierValue()),...l.getDescendantsOfKind(v.ImportEqualsDeclaration).map(g=>en(g)),...l.getDescendantsOfKind(v.CallExpression).map(g=>Zt(g))].filter(g=>g!==void 0);for(const g of u){const f=Qt(c,g);f!==void 0&&Ke(n,f)&&!o.has(f)&&(o.add(f),a.push(f),s.push(f))}}return a},tn=e=>{const r=e.getArgumentExpression();return r!==void 0&&(y.isStringLiteral(r)||y.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():void 0},nn=e=>y.isPropertyAccessExpression(e)?e.getName():y.isElementAccessExpression(e)?tn(e):void 0,on=new Set([v.AmpersandAmpersandEqualsToken,v.AmpersandEqualsToken,v.AsteriskAsteriskEqualsToken,v.AsteriskEqualsToken,v.BarBarEqualsToken,v.BarEqualsToken,v.CaretEqualsToken,v.EqualsToken,v.GreaterThanGreaterThanEqualsToken,v.GreaterThanGreaterThanGreaterThanEqualsToken,v.LessThanLessThanEqualsToken,v.MinusEqualsToken,v.PercentEqualsToken,v.PlusEqualsToken,v.QuestionQuestionEqualsToken,v.SlashEqualsToken]),sn=e=>{const r=e.getOperatorToken().getKind();return!on.has(r)||nn(e.getLeft())!==We?!1:r!==v.EqualsToken||!ae(e.getRight())},an=(e,r,n)=>{const t=[],o=[...new Set([_(e),"src"])].filter(u=>k(w(e,u))),s=j(e),a=[...Bt.map(u=>w(e,u)).filter(u=>k(u)),...s===void 0?[]:pe(e,s,r),...n.flatMap(u=>pe(e,u,r))],i=new Fe({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}),c=o.flatMap(u=>ze(w(e,u),w(e,u),t));return{sites:[...new Set([...c,...a,...rn([...a,...c],i,e,t)])].flatMap(u=>{const g=Ve(u,t);if(g===void 0)return[];const f=i.createSourceFile(I(e,u),g,{overwrite:!0}),h=[...f.getDescendantsOfKind(v.PropertyAssignment),...f.getDescendantsOfKind(v.ShorthandPropertyAssignment),...f.getDescendantsOfKind(v.GetAccessor),...f.getDescendantsOfKind(v.MethodDeclaration)].filter(p=>{const R=y.isPropertyAssignment(p)&&ae(p.getInitializer());return Yt(p.getNameNode())===We&&!R}).map(p=>p.getStartLineNumber()),m=f.getDescendantsOfKind(v.BinaryExpression).filter(p=>sn(p)).map(p=>p.getStartLineNumber());return[...h,...m].map(p=>({file:I(e,u),line:p}))}),unreadable:t}},cn=(e,r,n,t,o,s)=>{if(n!=="deploy")return;const{sites:a,unreadable:i}=an(e,o,s),c=Zr({openShardAccess:a,schema:{tables:[]}},{lints:[ue]});if(c.length===0&&i.length===0)return;const d=[];if(c.length>0){const u=c.map(g=>`${String(g.metadata.file)}:${String(g.metadata.line)}`).join(", ");d.push(`${u} enable the open-shard option (any value but a literal false), so any caller may target any shard.`)}if(i.length>0&&d.push(`could not read ${i.join(", ")}, so the open-shard option cannot be ruled out there.`),t){r.warn(`deploying past the open-shard gate (--allow-open-shards): ${d.join(" ")}`);return}const l=`deploy blocked (open_shard_access): ${d.join(" ")} ${ue.remediation}`;return r.error(l),l},dn=(e,r,n,t)=>{const o=cn(e,r.logger,n,r.allowOpenShards===!0,r.env,t);return o===void 0?void 0:{code:b.USAGE,error:o}},ln=(e,r,n)=>{const t=Gt(e,r.logger,n,r.env);if(t!==void 0)return{code:b.USAGE,error:t};const o=Wt(e,r.logger,n,r.env);if(o!==void 0)return{code:b.USAGE,error:o};const s=Ut(e,r.logger,n,r.discoveryCache);if(s!==void 0)return{code:b.USAGE,error:s};const a=Ft(e,r.logger,r.dockerAvailable??zr,n,r.env);return a===void 0?void 0:{code:b.MISSING_DEPENDENCY,error:a}},ve=32,un=15e3,gn=5432,fn=3306,hn=/[^a-z0-9-]/gu,mn=/[^A-Za-z0-9]/gu,pn=/-$/u,C=e=>`LUNORA_${e.replaceAll(mn,"_").toUpperCase()}_URL`,vn=e=>{const r=new Map;for(const n of e){const t=C(n),o=r.get(t);if(o!==void 0)return{bindings:[o,n],variable:t};r.set(t,n)}},ye=7,yn=(e,r)=>{const n=`${e}-${r}`.toLowerCase(),t=n.replaceAll(hn,"-");if(t===n&&t.length<=ve)return t;const o=Gr("sha256").update(n).digest("hex").slice(0,ye-1);return`${t.slice(0,ve-ye).replace(pn,"")}-${o}`},we=e=>e==="postgresql"?"postgres":e==="mariadb"?"mysql":e,wn=e=>e==="mysql"?fn:gn,kn=e=>{try{const r=new URL(e),n=r.protocol.slice(0,-1),t=decodeURIComponent(r.pathname.slice(1));return!["mariadb","mysql","postgres","postgresql"].includes(n)||r.hostname===""||t===""?void 0:{database:t,host:r.hostname,password:decodeURIComponent(r.password),port:r.port===""?wn(we(n)):Number(r.port),scheme:we(n),user:decodeURIComponent(r.username)}}catch{return}},bn=(e,r)=>{const n=typeof r?.password=="string"?r.password:"",t=n===""?[]:[n,JSON.stringify(n).slice(1,-1),encodeURIComponent(n)];let o=e;for(const s of t)o=o.replaceAll(s,"<redacted>");return o.split(" ").map(s=>s.includes("://")?"<url>":s).join(" ")},Je=e=>(Array.isArray(e)?e:[]).flatMap((r,n)=>{const{binding:t,id:o}=typeof r=="object"&&r!==null?r:{};return typeof t=="string"&&o===vr?[{binding:t,index:n}]:[]}),re=e=>{let r="";try{const{errors:n}=JSON.parse(e.text);r=(n??[]).flatMap(t=>typeof t.message=="string"?[t.message]:[]).slice(0,2).join("; ")}catch{}return r===""?`HTTP ${String(e.status)}`:`HTTP ${String(e.status)}: ${r}`},Sn=e=>typeof e=="string"||typeof e=="number"?e.toString():void 0,$n=["scheme","host","port","database","user"],En=e=>e==="postgresql"?"postgres":e,ke=(e,r)=>{const n=Sn(r);return e==="scheme"?En(n):n},be=50,An=async(e,r)=>{for(let n=1;n<=be;n+=1){const t=await e(n===1?"/hyperdrive/configs":`/hyperdrive/configs?page=${String(n)}`);if(!t.ok)throw new Error(`listing Hyperdrive configs failed (${re(t)})`);if(!Array.isArray(t.body.result))throw new TypeError("the listing of Hyperdrive configs had no result list");const o=t.body.result.find(a=>a.name===r),s=typeof t.body.result_info=="object"&&t.body.result_info!==null?t.body.result_info:{};if(o!==void 0||typeof s.total_pages!="number"||n>=s.total_pages)return o}throw new Error(`the listing of Hyperdrive configs has more than ${String(be)} pages, so "${r}" can't be shown to be absent`)},Tn=async(e,r,n)=>{const t=await An(e,r);if(typeof t?.id=="string"){const a=$n.filter(c=>ke(c,t.origin?.[c])!==ke(c,n[c]));if(a.length>0)throw new Error(`a Hyperdrive config named "${r}" already exists for a different origin, or one that can't be confirmed (${a.join(", ")}). Delete it, or rename the Worker, so the binding does not reach the wrong database.`);const i=await e(`/hyperdrive/configs/${encodeURIComponent(t.id)}`,{body:JSON.stringify({origin:n}),method:"PATCH"});if(!i.ok)throw new Error(`updating its credentials failed (${re(i)})`);return{id:t.id,reused:!0}}const o=await e("/hyperdrive/configs",{body:JSON.stringify({name:r,origin:n}),method:"POST"});if(!o.ok)throw new Error(`creating it failed (${re(o)})`);const{id:s}=typeof o.body.result=="object"&&o.body.result!==null?o.body.result:{};if(typeof s!="string")throw new TypeError("the response carried no id");return{id:s,reused:!1}},Rn=(e,r,n,t)=>r===void 0&&t?`${C(e)} is set but is not a usable connection string for the "${e}" Hyperdrive binding: it needs a postgres://, postgresql:// or mysql:// scheme, a host and a database name, with any special characters percent-encoded.`:r===void 0?`the "${e}" Hyperdrive binding has no config yet. Set ${C(e)} to its postgres:// or mysql:// connection string and Lunora creates the config, or run \`wrangler hyperdrive create\` and put its id in wrangler.jsonc.`:n?void 0:`creating the "${e}" Hyperdrive config needs CLOUDFLARE_API_TOKEN (Hyperdrive: Edit) and CLOUDFLARE_ACCOUNT_ID, or run \`wrangler hyperdrive create\` and put its id in wrangler.jsonc.`,Dn=async(e,r)=>{const n=yn(e.workerName,e.binding),{id:t,reused:o}=await Tn(async(s,a)=>rt({accountId:e.accountId,apiToken:e.token,...e.fetch===void 0?{}:{fetch:e.fetch},init:{...a,signal:AbortSignal.timeout(un)},path:s}),n,e.origin);return e.logger.success(`${o?"reusing":"created"} Hyperdrive config "${n}" for ${e.binding} → ${e.wranglerPath}`),{id:t,text:Ne(r,[...e.path,e.index,"id"],t)}},_n=e=>e===void 0||e===""?void 0:e,Pn=e=>{const r=$(U(e),".wrangler","deploy","config.json");try{const{configPath:n}=JSON.parse(S(r,"utf8"));return typeof n=="string"?q(U(r),n):void 0}catch{return}},On=(e,r,n,t,o)=>{const s=Pn(e);if(s===void 0||s===e)return;if(t.built!==t.deployed){o.warn(`the build output ${s} was made for ${t.built===void 0?"the default environment":`"${t.built}"`}, not ${t.deployed===void 0?"the default environment":`"${t.deployed}"`}, so the "${r}" Hyperdrive id was not written there. Build with CLOUDFLARE_ENV set to the environment you deploy, then deploy again.`);return}let a;try{a=T(s)}catch{return}const i=Je(a.parsed?.hyperdrive).find(c=>c.binding===r);i!==void 0&&P(s,Ne(a.text,["hyperdrive",i.index,"id"],n),"utf8")},Nn=(e,r)=>{const n=typeof e.name=="string"&&e.name!==""?e.name:"lunora";if(r===void 0)return n;const t=e.env?.[r]?.name;return typeof t=="string"&&t!==""?t:`${n}-${r}`},ie=(e,r)=>{const n=j(e),t=n===void 0?void 0:T(n).parsed;if(n===void 0||t===void 0)return;const o=r===void 0?void 0:t.env?.[r],s=Je(r===void 0?t.hyperdrive:o?.hyperdrive);return s.length===0?void 0:{accountId:o?.account_id??t.account_id,entries:s,path:r===void 0?["hyperdrive"]:["env",r,"hyperdrive"],workerName:Nn(t,r),wranglerPath:n}},In=(e,r,n)=>{const t=vn(e.map(({binding:o})=>o));if(t!==void 0){const o=`deploy blocked: the Hyperdrive bindings ${t.bindings.map(s=>`"${s}"`).join(" and ")} both read ${t.variable} and would share one config. Rename one so their names differ in letters or digits, not only in punctuation.`;return n.logger.error(o),o}for(const{binding:o,origin:s,supplied:a}of e){const i=Rn(o,s,r,a);if(i!==void 0&&n.dryRun===!0)n.logger.warn(`dry run: ${i} A real deploy stops here.`);else if(i!==void 0){const c=`deploy blocked: ${i}`;return n.logger.error(c),c}}},Cn=async e=>{const r=ie(e.cwd,e.wranglerEnvironment);if(r===void 0)return;const{entries:n,path:t,wranglerPath:o}=r,s=e.environment??process.env,{accountId:a,token:i}=et(s,r.accountId),c=n.map(({binding:l})=>{const u=s[C(l)]??"";return{binding:l,origin:kn(u),supplied:u!==""}}),d=In(c,i!==void 0&&a!==void 0,e);if(d!==void 0)return d;if(!(e.dryRun===!0||e.checkOnly===!0))for(const[l,{binding:u,index:g}]of n.entries()){const f=c[l]?.origin;if(!(f===void 0||i===void 0||a===void 0))try{const{id:h,text:m}=await Dn({accountId:a,binding:u,fetch:e.fetch,index:g,logger:e.logger,origin:f,path:t,token:i,workerName:r.workerName,wranglerPath:o},S(o,"utf8"));P(o,m,"utf8"),On(o,u,h,{built:_n(s.CLOUDFLARE_ENV),deployed:e.wranglerEnvironment},e.logger)}catch(h){const m=h instanceof Error?h.message:String(h),p=`deploy blocked: the "${u}" Hyperdrive config could not be set up: ${bn(m,c[l]?.origin)}`;return e.logger.error(p),p}}},jn=(e,r)=>{const n=ie(e,r.env)?.entries[0]?.binding;if(n===void 0)return;const t=`prepare blocked: the "${n}" Hyperdrive binding still has its placeholder id. Run \`lunora deploy\` with ${C(n)} set to create the config, or put the id from \`wrangler hyperdrive create\` in wrangler.jsonc.`;return r.logger.error(t),t},xn=(e,r)=>{const n=ie(e,r.env)?.entries[0]?.binding;if(n===void 0)return;const t=`deploy blocked: the "${n}" Hyperdrive binding has no config, and a --temporary deploy cannot create one: it would be made in your account while the Worker goes to a temporary one, which a temporary account has no database for. Deploy without --temporary.`;return r.logger.error(t),t},Ye=async(e,r,n,t,o="create")=>{if(t==="cloudflare")return n==="prepare"?jn(e,r):r.temporary===!0?xn(e,r):Cn({checkOnly:o==="check",cwd:e,dryRun:r.dryRun,logger:r.logger,wranglerEnvironment:r.env})},Ln=/https?:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/u,Mn=/https:\/\/[^\s"'<>]+/u,Fn=e=>{if(e===void 0)return;const r=Ln.exec(e);return r?r[0]:Mn.exec(e)?.[0]},Se=e=>e===void 0?"":` (--env ${e})`,Un=({cwd:e,env:r,logger:n,now:t,url:o})=>{if(o!==void 0)try{const s=Ae(e);if(s!==void 0){if(s.workerUrl===o&&s.env===r)return;n.warn(`link: .lunora/project.json records ${s.workerUrl??"(no url)"}${Se(s.env)}, but this deploy published ${o}${Se(r)}. Keeping the recorded value — run \`lunora link --url ${o}${r===void 0?"":` --env ${r}`}\` to update it.`);return}const a=(t??(()=>new Date().toISOString()))();cr(e,{env:r,linkedAt:a,workerName:ne(e),workerUrl:o}),n.success(`link: recorded ${o} in .lunora/project.json (run \`lunora link\` to change)`)}catch{}},Hn=async(e,r)=>{const n=new Fe({skipAddingFilesFromTsConfig:!0}),t=w(r,"lunora");let o;try{o=or(n,t)}catch(s){const a=s instanceof Error?s.message:String(s);return e.logger.warn(`--migrate: could not discover migrations (${a}); skipping`),0}if(o.length===0)return e.logger.info("--migrate: no data migrations declared in lunora/"),0;e.logger.info(`--migrate: running ${String(o.length)} migration(s) against deployed worker`);for(const s of o){e.logger.info(`--migrate: up "${s.id}" (table "${s.table}")`);const a={cwd:r,fetchImpl:e.fetchImpl,id:s.id,logger:e.logger,prod:!0,subcommand:"up",token:e.migrateToken,url:e.migrateUrl,yes:e.migrateYes===!0},i=await tt(a);if(i.code!==0)return e.logger.error(`--migrate: migration "${s.id}" failed — see output above`),i.code;e.logger.success(`--migrate: "${s.id}" applied`)}return 0},qn=async(e,r)=>{const{info:n}=Re(r,"lunora",e.discoveryCache),t=n?.vectorMetadata??[];if(t.length===0)return;const o=[];for(const i of t){const c=Ir(i.kind);if(c===void 0){e.logger.warn(`vector index "${i.index}" declares metadata "${i.property}", whose column type cannot be filtered on in Vectorize — it is stored with each vector but no filter will match it.`);continue}o.push({index:i.index,property:i.property,type:c})}if(o.length===0)return;const a=(await Cr({cwd:r,entries:o,exec:xe(O(r),"wrangler",[]),logger:e.logger,spawner:e.spawner??W})).filter(i=>i.status!=="failed").length;a>0&&e.logger.success(`vectorize metadata indexes ready: ${String(a)}/${String(o.length)}`)},$e=5,Gn=2e3,Wn=async(e,r,n)=>{if(e.healthCheck!==!0)return;const t=n??Le({cwd:r,env:e.env});if(t===void 0){const s="--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(s),{error:s,ok:!1,url:""}}const o=await Jr({attempts:$e,baseUrl:t,delayMs:Gn,fetchImpl:e.healthFetch,paths:[Yr,Xr],sleep:e.healthSleep});return o.error===void 0?(e.logger.success(`health check ok (${o.url})`),{ok:!0,url:o.url}):(e.logger.error(`--health-check: the deploy succeeded, but the new version did not answer after ${String($e)} attempt(s) — ${o.error}`),{error:o.error,ok:!1,url:o.url})},Bn=async(e,r,n,t,o,s)=>{await qn(e,r);const a=e.migrate?await Hn(e,r):0;return a===0&&o?.(),{code:a,descriptor:n,mintedSecretsFile:s,validation:t}},Kn=async({cwd:e,descriptor:r,mintedSecretsFile:n,options:t,reblessSchemaBaseline:o,recordArchitecture:s,stdout:a,validation:i})=>{const c={deployedAt:new Date().toISOString(),dryRun:t.dryRun===!0,env:t.env,preview:t.preview===!0,url:t.dryRun===!0?void 0:Fn(a),workerName:ne(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:c,descriptor:r,mintedSecretsFile:n,validation:i};t.temporary!==!0&&(s?.(),Un({cwd:e,env:t.env,logger:t.logger,url:c.url}));const d=await Wn(t,e,c.url);return d?.error!==void 0?{code:b.UNAVAILABLE,deployment:c,descriptor:r,healthCheck:d,mintedSecretsFile:n,validation:i}:{...await Bn(t,e,r,i,o,n),deployment:c,healthCheck:d}},Vn=(e,r,n)=>{const t=w(e,A);if(!k(t))return;let o;try{o=De(S(t,"utf8")).length}catch{return}if(o===0)return;const s=n.toolchain?.secretPut!==void 0;r.warn(s?`Note: \`lunora deploy\` does not push secrets. ${A} has ${String(o)} key(s); if you changed them, run \`lunora env push --yes\` to update the deployed secrets.`:`Note: ${n.name} deploys read no secrets. ${A} has ${String(o)} key(s) that only the dev server sees; put the values the deployed worker needs in wrangler \`vars\`.`)},zn=async(e,r)=>{let n=[];try{n=dr(await _e({cache:r,projectRoot:e,schemaDir:_(e)}))}catch{}const t=lr(n).map(s=>s.key);let o=[];try{const s=w(e,A);k(s)&&(o=De(S(s,"utf8")).map(a=>a.key).filter(a=>jr(a)))}catch{}return[...new Set([...t,...o])]},Jn=async(e,r,n,t)=>{const{logger:o}=r,s=r.spawner??W,a=O(e),i=r.env===void 0?"":` --env ${r.env}`,c=t.toolchain?.secretPut;if(c===void 0)return o.error(`deploy target "${t.id}" has no secret store; cannot push secrets`),{minted:[],ok:!1};const d=n.map(g=>({key:g,value:ur()})),l=t.toolchain?.secretBulk;if(l!==void 0&&d.length>=2){const g=N(a,l({environment:r.env,temporary:r.temporary})),f=await s({args:g.args,command:g.command,cwd:e,input:JSON.stringify(Object.fromEntries(d.map(h=>[h.key,h.value])))});if(f.code===0){for(const{key:h}of d)o.success(`generated + pushed ${h}`);return{minted:d,ok:!0}}o.warn(`bulk secret push failed (exit ${String(f.code)}); retrying one key at a time`)}const u=[];for(const{key:g,value:f}of d){const h=c({environment:r.env,key:g,temporary:r.temporary}),m=N(a,h),p=await s({args:m.args,command:m.command,cwd:e,input:f});if(p.code!==0)return o.error(`failed to push secret ${g} (exit ${String(p.code)}); set it manually with \`wrangler secret put ${g}${i}\`.`),{minted:u,ok:!1};u.push({key:g,value:f}),o.success(`generated + pushed ${g}`)}return{minted:u,ok:!0}},Yn=/^[\w-]+$/u,Y=[".dev.vars",".dev.vars.*","!.dev.vars.example"],Xn=/\r?\n/u,Qn=(e,r)=>{const n=w(e,".gitignore");try{const t=k(n)?S(n,"utf8"):"",o=new Set(t.split(Xn).map(c=>c.trim())),s=Y.filter(c=>!o.has(c));if(s.length===0)return;const a=s.some(c=>!c.startsWith("!"))?[...s.filter(c=>!c.startsWith("!")),...Y.filter(c=>c.startsWith("!"))]:s,i=t.length>0&&!t.endsWith(`
19
19
  `)?`
20
- `:"";D(n,`${t}${s}
20
+ `:"";P(n,`${t}${i}
21
21
  # Lunora — never commit a minted secret
22
- ${i.join(`
22
+ ${a.join(`
23
23
  `)}
24
- `,"utf8"),r.info(`.gitignore: added ${a.join(", ")} so the recorded secret cannot be committed`)}catch(t){r.warn(`could not update .gitignore (${t instanceof Error?t.message:String(t)}) — add \`${B.join("` and `")}\` by hand before committing.`)}},fn=(e,r,n)=>{if(n.length===0)return;const t=n.map(s=>s.key).join(", ");if(r.env!==void 0&&!ln.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 o=r.env===void 0?S:`${S}.${r.env}`;gn(e,r.logger);const a=$(e,o);let i=v(a)?k(a,"utf8"):"";for(const s of n)i=Ge(i,s.key,s.value);return Ve(a,i),r.logger.success(r.env===void 0?`${t}: value(s) recorded in ${o}`:`${t}: value(s) recorded in ${o} (kept separate from ${S} so \`lunora dev\` and a plain \`lunora env push\` don't inherit the --env ${r.env} value)`),o},mn=async(e,r,n,t)=>{if(r.dryRun===!0||r.preview===!0)return{};const{logger:o}=r,a=r.env===void 0?"":` --env ${r.env}`;let i;try{i=await(r.secretLister??Lr)({cwd:e,env:r.env,temporary:r.temporary})}catch{return{}}if(!i.ok)return{};const s=new Set(i.names),d=(await cn(e,r.discoveryCache)).filter(f=>!s.has(f));if(d.length===0)return{};if(!n)return{error:`missing required secret(s) on the deploy target: ${d.join(", ")}. Set them with \`wrangler secret put <KEY>${a}\` (or \`lunora env generate --set\` then \`lunora env push --yes${a}\`), then re-deploy.`};for(const f of d.filter(m=>!ne(m)))o.warn(`required secret ${f} is not set on the target — set it with: wrangler secret put ${f}${a}`);const l=d.filter(f=>ne(f));if(l.length===0)return{};if(await(r.secretConfirm??xr())(`${String(l.length)} required secret(s) not set on the target (${l.join(", ")}). Generate strong values and push them now?`)){const{minted:f,ok:m}=await dn(e,r,l,t),u=fn(e,r,f);return m?{mintedSecretsFile:u}:{error:"failed to push required secret(s) — set them manually and re-deploy",mintedSecretsFile:u}}return o.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${a}\`.`),{}},Pe=e=>e.format==="json"?!1:e.interactive!==void 0?e.interactive:process.stdout.isTTY&&!process.env.CI,hn=async(e,r)=>{if(r.dryRun===!0)return;const n=pe(e,"lunora",r.discoveryCache).containers.flatMap(o=>o.schedulingPolicy===void 0&&o.image.kind==="build"?[{buildDir:o.image.buildDir,exportName:o.exportName}]:[]);if(n.length===0)return;const t=await gt({cwd:e,logger:r.logger,railpackAvailable:r.railpackAvailable,spawner:r.spawner,targets:n});return t.code===0?void 0:t.error??"railpack build failed"},pn=(e,r,n)=>{if(n!==void 0)try{const t=rr(e,n);t.changed&&r.success(`synced ${String(n.length)} cron trigger(s) → ${t.wranglerPath??"wrangler.jsonc"}`);for(const a of t.warnings)r.warn(a);const o=tr(t.preserved);o!==void 0&&r.info(o)}catch(t){const o=t instanceof Error?t.message:String(t);r.warn(`cron trigger sync skipped: ${o}`)}},vn=async(e,r,n,t,o,a)=>{try{K(t);const i=await we({cache:a,projectRoot:e,schemaDir:P(e)}),s=Ze(e,i,{environment:o,target:t}),c=s.wranglerPath??"wrangler.jsonc";if(s.added.length>0&&r.success(`provisioned bindings: ${s.added.join(", ")} → ${c}`),s.updated.length>0&&r.success(`updated bindings: ${s.updated.join(", ")} → ${c}`),s.devConfig!==void 0){const{added:d,path:l,updated:g}=s.devConfig;r.success(`dev sidecar bindings: ${[...d,...g].join(", ")} → ${l}`)}for(const d of s.warnings)r.warn(d)}catch(i){const s=i instanceof Error?i.message:String(i);r.warn(`binding inference skipped: ${s}`)}try{const i=er(e);i.changed&&r.success(`bumped compatibility_date to ${i.date??"unknown"} (Workers Cache enabled) → ${i.wranglerPath??"wrangler.jsonc"}`)}catch(i){const s=i instanceof Error?i.message:String(i);r.warn(`compatibility date sync skipped: ${s}`)}pn(e,r,n)},yn=async(e,r,n,t,o,a,i,s,c)=>{let d;r?(d=new nr({name:"dots"}),d.start("running codegen")):n.info("running codegen");try{const l=Le({apiSpec:t,lazyFunctions:o,projectRoot:e,target:a,...Qe(e)});d?.succeed("codegen complete"),d||n.success("codegen complete");const g=ar(l.platformDiagnostics,n);if(g.errors.length>0)return{error:g.errors.join("; ")};const{errorAdvisories:f,names:m,shouldBlock:u}=ir(l.advisories,c);if(u){const p=`${f.length.toString()} ERROR-level ${f.length===1?"advisory":"advisories"} (${m.join(", ")}). Pass --no-strict-advisories to downgrade this to a warning and continue.`;return n.error(p),{error:p}}const h=await qe({cwd:e,logger:n,spawner:i,stdoutToStderr:s});return h.error!==void 0?{error:h.error}:{result:l}}catch(l){d?.failed("codegen failed");const g=l instanceof Error?l.message:String(l);return n.error(`codegen failed: ${g}`),{error:`codegen failed: ${g}`}}},wn=(e,r)=>({dryRun:r.dryRun,entry:Q(e),environment:r.env,outDir:r.outDir,preview:r.preview,temporary:r.temporary}),Ie=(e,r,n)=>{const{toolchain:t}=n;if(t===void 0)throw new Error(`deploy target "${n.id}" has no command-line toolchain`);const o=wn(e,r);return be(n,e,"deploy",a=>t.deploy({...o,configPath:a}))},kn=(e,r,n)=>{const t=Ie(e,r,n),o=Q(e);return o!==void 0&&r.logger.info(`class-B composition: deploying ${o} (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(`${n.name} ignores these wrangler keys, so they were left out of ${t.projection.configPath}: ${t.projection.dropped.join(", ")}`),t.command},G=(e,r)=>({code:y.USAGE,descriptor:void 0,error:e,validation:{problems:[],wranglerPath:void 0},...r}),bn=(e,r)=>{for(const n of e.report?.warnings??[])r.warn(`wrangler.jsonc: ${n}`);if(e.problems.length===0)return!1;r.error("wrangler.jsonc validation failed:");for(const n of e.problems)r.error(` - ${n}`);return!0},$n=(e,r,n)=>{const t=r.format==="json",o=r.dryRun!==!0,a=kn(e,r,n),i=C(R(e),a);return{args:i.args,captureStdout:o&&!t,captureStdoutSilently:o&&t,command:i.command,cwd:e,stdoutToStderr:t&&!o}},Sn=async(e,r)=>{const n=e.cwd??process.cwd(),t=Pe(e),o=or(e),a={problems:[],wranglerPath:void 0},i=yr(n,e.target);if(i.target===void 0){const u=i.error??"unknown deploy target";return e.logger.error(u),{error:u,validation:a}}const{target:s}=i;try{Ie(n,e,K(s))}catch(u){const h=u instanceof Error?u.message:String(u);return e.logger.error(h),{error:h,target:s,validation:a}}let c;if(!e.skipCodegen){const u=await yn(n,t,e.logger,e.apiSpec,ke(e.lazyFunctions),s,e.spawner,e.format==="json",o);if(u.error!==void 0)return{error:u.error,target:s,validation:a};c=u.result,e.discoveryCache?.clear()}let d;if(c!==void 0){const u=Pr({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:a};d=u.rebless}const l=c&&Br({current:c.architecture,cwd:n,environment:e.env,logger:e.logger});await vn(n,e.logger,c?.cronTriggers,s,e.env,e.discoveryCache);const g=await _e(n,e,r,s,"check");if(g!==void 0)return{error:g,target:s,validation:a};const f=St(n,e,r);if(f!==void 0)return{code:f.code,error:f.error,target:s,validation:a};const m=Xe({environment:e.env,projectRoot:n});return bn(m,e.logger)?{error:"wrangler validation failed",target:s,validation:m}:{codegen:c,reblessSchemaBaseline:d,recordArchitecture:l,target:s,validation:m}},En=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"},An=async(e,r,n,t)=>{const{error:o,services:a}=Oe(e);if(o!==void 0)return o;if(a.length===0)return;const{toolchain:i}=n,s=i===void 0?`target "${n.id}" has no deploy command`:En(r);if(s!==void 0||i===void 0){const l=a.map(g=>g.worker).join(", ");r.logger.warn(`services not deployed (${s??""}): ${l} — deploy them yourself if the app calls anything new`);return}const c=R(e),d=[...new Map(a.map(l=>[l.wranglerPath,l])).values()];for(const l of d){const g=L(l.wranglerPath);let f;try{f=be(n,g,"deploy",h=>i.deploy({configPath:h??l.wranglerPath,dryRun:r.dryRun===!0,environment:r.env}))}catch(h){return`service ${l.name} (${l.worker}): ${h instanceof Error?h.message:String(h)}`}f.commit();const m=C(c,f.command);r.logger.info(`deploying service ${l.name} (${l.worker}) via ${m.command} ${m.args.join(" ")}`);const u=await t({args:m.args,command:m.command,cwd:g,stdoutToStderr:r.format==="json"});if(u.code!==0)return`service ${l.name} (${l.worker}): ${m.command} ${m.args.join(" ")} exited ${String(u.code)} — stopping before the app`}},Dn=async(e,r,n,t)=>{if(r!=="cloudflare")return;const o=e===void 0?void 0:A(e).parsed,a=(n===void 0?void 0:o?.env?.[n]?.account_id)??o?.account_id,i=await hr({accountId:a});(i.verdict==="near"||i.verdict==="full")&&t.warn(i.fix===void 0?i.message:`${i.message} ${i.fix}`)},Rn=e=>e.dryRun!==!0&&e.temporary!==!0,Cn=e=>e.temporary===!0?"temporary":e.dryRun===!0?"preview":"defer",_n=e=>{const r=e.fix===void 0?e.message:`${e.message} ${e.fix}`;return e.verdict==="unchecked"?`${r} The deploy stops until it can be checked, as a namespace made by the first repo is unrestricted.`:r},Pn=(e,r,n)=>{const t=[];for(const o of e)if(o.verdict==="ok")o.changesAccount===!0&&r.info(o.message);else if(o.verdict==="unchecked"&&n==="preview")r.warn(`dry run: ${o.message}${o.fix===void 0?"":` ${o.fix}`} A real deploy stops here.`);else{const a=_n(o);r.error(a),t.push(a)}return t},Te=async(e,r,n,t,o,a,i)=>{const s=n==="cloudflare"&&r!==void 0?A(r).parsed:void 0;if(s===void 0)return;const c=(Y(s,t).merged.artifacts??[]).flatMap(u=>typeof u?.binding=="string"&&typeof u.namespace=="string"?[{binding:u.binding,namespace:u.namespace}]:[]),d=c.length===0?void 0:ve(e,P(e),a).info?.jurisdiction;if(d===void 0)return;const l=[...new Map(c.map(u=>[u.namespace,u])).values()];if(i==="temporary"){o.warn(`--temporary deploys to a throwaway account, so the jurisdiction ("${d}") of Artifacts namespace ${l.map(u=>`"${u.namespace}"`).join(", ")} was not checked: it is created there on first use, in no jurisdiction.`);return}const g=(t===void 0?void 0:s.env?.[t]?.account_id)??s.account_id,f=await Promise.all(l.map(async u=>mr({...u,accountId:g,create:i==="create",jurisdiction:d,missingOk:i==="defer"||i==="preview"}))),m=Pn(f,o,i);return m.length===0?void 0:m.join(`
25
- `)},In=async(e,r,n,t,o,a)=>(Rn(r)?await Te(e,a,o,r.env,r.logger,r.discoveryCache,"create"):void 0)??await _e(e,r,"deploy",o)??await An(e,r,n,t),Tn=async(e,r,n,t)=>{if(!(r.smokeLoad===!1||n.toolchain===void 0))return ut({composedEntry:Q(e),configPath:t,cwd:e,environment:r.env,launcher:r.smokeLauncher,logger:r.logger,toolchain:n.toolchain})},jn=async e=>{const r={...e,discoveryCache:e.discoveryCache??ze()},n=r.cwd??process.cwd(),t=Pe(r),o=await Sn(r,r.commandName??"deploy");if(o.error!==void 0){if(o.validation.problems.length>0)return{code:y.USAGE,descriptor:void 0,error:o.error,validation:o.validation};const p=o.schemaDrift===void 0?void 0:{schemaDrift:o.schemaDrift};return G(o.error,{...p,...o.code===void 0?{}:{code:o.code}})}const{validation:a}=o,i=K(o.target),s=kt(r)??await Te(n,a.wranglerPath,o.target,r.env,r.logger,r.discoveryCache,Cn(r))??await Tn(n,r,i,a.wranglerPath);if(s!==void 0)return G(s);const c=i.toolchain?.prebuildsContainerImages===!0?await hn(n,r):void 0;if(c!==void 0)return G(c);sn(n,r.logger,i),Je(n,p=>{r.logger.warn(p)}),await Dn(a.wranglerPath,o.target,r.env,r.logger);const{error:d,mintedSecretsFile:l}=await mn(n,r,t,i);if(d!==void 0)return r.logger.error(d),{code:y.USAGE,descriptor:void 0,error:d,mintedSecretsFile:l,validation:a};const g=r.spawner??M,f=await In(n,r,i,g,o.target,a.wranglerPath);if(f!==void 0)return{code:y.FAILURE,descriptor:void 0,error:f,mintedSecretsFile:l,validation:a};const m=$n(n,r,i);r.logger.info(`deploying via ${m.command} ${m.args.join(" ")}`);const u=await g(m);return m.captureStdoutSilently===!0&&u.stdout!==void 0&&u.stdout!==""&&process.stderr.write(u.stdout),u.code!==0?{code:u.code,descriptor:m,mintedSecretsFile:l,validation:a}:{...await an({...o,cwd:n,descriptor:m,mintedSecretsFile:l,options:r,stdout:u.stdout}),logsAvailable:i.toolchain?.tail!==void 0}},Nn=async e=>{const{logger:r}=e,n=e.dryRun===!0?ft(e.cwd??process.cwd()):void 0;let t;try{if(t=await jn({...e,logger:r}),t.code===0&&e.emitBindings!==void 0){const{error:o}=pr({destination:e.emitBindings,logger:r,projectRoot:e.cwd??process.cwd()});o!==void 0&&(r.error(o),t={...t,code:y.USAGE})}}finally{n?.()}if(e.format==="json")return t;if(t.code===0&&e.dryRun!==!0&&e.preview!==!0)Gr({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 o=t.deployment?.url;e.logger.success(o===void 0?"preview version uploaded":`preview version uploaded — ${o}`)}return t},go=vr(async({cwd:e,format:r,logger:n,options:t})=>{const o=await Nn({allowSchemaDrift:t.allowSchemaDrift===!0,apiSpec:sr(t.apiSpec),lazyFunctions:ke(t.lazyFunctions),cwd:e,dryRun:t.dryRun===!0,env:t.env,format:r,healthCheck:t.healthCheck===!0,logger:n,migrate:t.migrate===!0,migrateToken:t.migrateToken,migrateUrl:Ae({cwd:e,env:t.env,url:t.migrateUrl}),migrateYes:t.migrateYes===!0,preview:t.preview===!0,skipCodegen:t.prebuilt===!0,skipServices:t.skipServices===!0,smokeLoad:t.smokeLoad,strictAdvisories:t.strictAdvisories,target:t.target,temporary:t.temporary===!0,updateSchemaBaseline:t.updateSchemaBaseline===!0});return{code:o.code,data:{deployment:o.deployment,healthCheck:o.healthCheck,mintedSecretsFile:o.mintedSecretsFile,schemaDrift:o.schemaDrift,validation:o.validation},error:o.error}});export{go as execute,vn as provisionBindings,Nn as runDeployCommand,Sn as runPreDeployPipeline,Tn as smokeLoadLazyModules};
24
+ `,"utf8"),r.info(`.gitignore: added ${s.join(", ")} so the recorded secret cannot be committed`)}catch(t){r.warn(`could not update .gitignore (${t instanceof Error?t.message:String(t)}) — add \`${Y.join("` and `")}\` by hand before committing.`)}},Zn=(e,r,n)=>{if(n.length===0)return;const t=n.map(i=>i.key).join(", ");if(r.env!==void 0&&!Yn.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 o=r.env===void 0?A:`${A}.${r.env}`;Qn(e,r.logger);const s=w(e,o);let a=k(s)?S(s,"utf8"):"";for(const i of n)a=gr(a,i.key,i.value);return fr(s,a),r.logger.success(r.env===void 0?`${t}: value(s) recorded in ${o}`:`${t}: value(s) recorded in ${o} (kept separate from ${A} so \`lunora dev\` and a plain \`lunora env push\` don't inherit the --env ${r.env} value)`),o},eo=async(e,r,n,t)=>{if(r.dryRun===!0||r.preview===!0)return{};const{logger:o}=r,s=r.env===void 0?"":` --env ${r.env}`;let a;try{a=await(r.secretLister??ot)({cwd:e,env:r.env,temporary:r.temporary})}catch{return{}}if(!a.ok)return{};const i=new Set(a.names),d=(await zn(e,r.discoveryCache)).filter(g=>!i.has(g));if(d.length===0)return{};if(!n)return{error:`missing required secret(s) on the deploy target: ${d.join(", ")}. Set them with \`wrangler secret put <KEY>${s}\` (or \`lunora env generate --set\` then \`lunora env push --yes${s}\`), then re-deploy.`};for(const g of d.filter(f=>!le(f)))o.warn(`required secret ${g} is not set on the target — set it with: wrangler secret put ${g}${s}`);const l=d.filter(g=>le(g));if(l.length===0)return{};if(await(r.secretConfirm??nt())(`${String(l.length)} required secret(s) not set on the target (${l.join(", ")}). Generate strong values and push them now?`)){const{minted:g,ok:f}=await Jn(e,r,l,t),h=Zn(e,r,g);return f?{mintedSecretsFile:h}:{error:"failed to push required secret(s) — set them manually and re-deploy",mintedSecretsFile:h}}return o.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${s}\`.`),{}},Xe=e=>e.format==="json"?!1:e.interactive!==void 0?e.interactive:process.stdout.isTTY&&!process.env.CI,ro=async(e,r)=>{if(r.dryRun===!0)return;const n=Te(e,"lunora",r.discoveryCache).containers.flatMap(o=>o.schedulingPolicy===void 0&&o.image.kind==="build"?[{buildDir:o.image.buildDir,exportName:o.exportName}]:[]);if(n.length===0)return;const t=await Ct({cwd:e,logger:r.logger,railpackAvailable:r.railpackAvailable,spawner:r.spawner,targets:n});return t.code===0?void 0:t.error??"railpack build failed"},to=(e,r,n)=>{if(n!==void 0)try{const t=$r(e,n);t.changed&&r.success(`synced ${String(n.length)} cron trigger(s) → ${t.wranglerPath??"wrangler.jsonc"}`);for(const s of t.warnings)r.warn(s);const o=Er(t.preserved);o!==void 0&&r.info(o)}catch(t){const o=t instanceof Error?t.message:String(t);r.warn(`cron trigger sync skipped: ${o}`)}},no=async(e,r,n,t,o,s)=>{try{te(t);const a=await _e({cache:s,projectRoot:e,schemaDir:_(e)}),i=br(e,a,{environment:o,target:t}),c=i.wranglerPath??"wrangler.jsonc";if(i.added.length>0&&r.success(`provisioned bindings: ${i.added.join(", ")} → ${c}`),i.updated.length>0&&r.success(`updated bindings: ${i.updated.join(", ")} → ${c}`),i.devConfig!==void 0){const{added:d,path:l,updated:u}=i.devConfig;r.success(`dev sidecar bindings: ${[...d,...u].join(", ")} → ${l}`)}for(const d of i.warnings)r.warn(d)}catch(a){const i=a instanceof Error?a.message:String(a);r.warn(`binding inference skipped: ${i}`)}try{const a=Sr(e);a.changed&&r.success(`bumped compatibility_date to ${a.date??"unknown"} (Workers Cache enabled) → ${a.wranglerPath??"wrangler.jsonc"}`)}catch(a){const i=a instanceof Error?a.message:String(a);r.warn(`compatibility date sync skipped: ${i}`)}to(e,r,n)},oo=async(e,r,n,t,o,s,a,i,c)=>{let d;r?(d=new Ar({name:"dots"}),d.start("running codegen")):n.info("running codegen");try{const l=sr({apiSpec:t,lazyFunctions:o,projectRoot:e,target:s,...kr(e)});d?.succeed("codegen complete"),d||n.success("codegen complete");const u=Rr(l.platformDiagnostics,n);if(u.errors.length>0)return{error:u.errors.join("; ")};const{errorAdvisories:g,names:f,shouldBlock:h}=Dr(l.advisories,c);if(h){const p=`${g.length.toString()} ERROR-level ${g.length===1?"advisory":"advisories"} (${f.join(", ")}). Pass --no-strict-advisories to downgrade this to a warning and continue.`;return n.error(p),{error:p}}const m=await mr({cwd:e,logger:n,spawner:a,stdoutToStderr:i});return m.error!==void 0?{error:m.error}:{result:l}}catch(l){d?.failed("codegen failed");const u=l instanceof Error?l.message:String(l);return n.error(`codegen failed: ${u}`),{error:`codegen failed: ${u}`}}},so=(e,r)=>({dryRun:r.dryRun,entry:se(e),environment:r.env,outDir:r.outDir,preview:r.preview,temporary:r.temporary}),Qe=(e,r,n)=>{const{toolchain:t}=n;if(t===void 0)throw new Error(`deploy target "${n.id}" has no command-line toolchain`);const o=so(e,r);return Oe(n,e,"deploy",s=>t.deploy({...o,configPath:s}))},ao=(e,r,n)=>{const t=Qe(e,r,n),o=se(e);return o!==void 0&&r.logger.info(`class-B composition: deploying ${o} (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(`${n.name} ignores these wrangler keys, so they were left out of ${t.projection.configPath}: ${t.projection.dropped.join(", ")}`),t.command},X=(e,r)=>({code:b.USAGE,descriptor:void 0,error:e,validation:{problems:[],wranglerPath:void 0},...r}),io=(e,r)=>{for(const n of e.report?.warnings??[])r.warn(`wrangler.jsonc: ${n}`);if(e.problems.length===0)return!1;r.error("wrangler.jsonc validation failed:");for(const n of e.problems)r.error(` - ${n}`);return!0},co=(e,r,n)=>{const t=r.format==="json",o=r.dryRun!==!0,s=ao(e,r,n),a=N(O(e),s);return{args:a.args,captureStdout:o&&!t,captureStdoutSilently:o&&t,command:a.command,cwd:e,stdoutToStderr:t&&!o}},Ze=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"},lo=(e,r)=>Ze(r)===void 0?Ee(e).services.map(n=>n.wranglerPath):[],uo=async(e,r)=>{const n=e.cwd??process.cwd(),t=Xe(e),o=Tr(e),s={problems:[],wranglerPath:void 0},a=Ur(n,e.target);if(a.target===void 0){const m=a.error??"unknown deploy target";return e.logger.error(m),{error:m,validation:s}}const{target:i}=a;try{Qe(n,e,te(i))}catch(m){const p=m instanceof Error?m.message:String(m);return e.logger.error(p),{error:p,target:i,validation:s}}const c=dn(n,e,r,lo(n,e));if(c!==void 0)return{code:c.code,error:c.error,target:i,validation:s};let d;if(!e.skipCodegen){const m=await oo(n,t,e.logger,e.apiSpec,Pe(e.lazyFunctions),i,e.spawner,e.format==="json",o);if(m.error!==void 0)return{error:m.error,target:i,validation:s};d=m.result,e.discoveryCache?.clear()}let l;if(d!==void 0){const m=Qr({allowDrift:e.allowSchemaDrift===!0,codegen:d,command:r,logger:e.logger,updateBaseline:e.updateSchemaBaseline===!0});if(m.blocked)return{error:`schema drift gate blocked ${r}`,schemaDrift:{blocked:!0,reason:m.reason},target:i,validation:s};l=m.rebless}const u=d&&ut({current:d.architecture,cwd:n,environment:e.env,logger:e.logger});await no(n,e.logger,d?.cronTriggers,i,e.env,e.discoveryCache);const g=await Ye(n,e,r,i,"check");if(g!==void 0)return{error:g,target:i,validation:s};const f=ln(n,e,r);if(f!==void 0)return{code:f.code,error:f.error,target:i,validation:s};const h=wr({environment:e.env,projectRoot:n});return io(h,e.logger)?{error:"wrangler validation failed",target:i,validation:h}:{codegen:d,reblessSchemaBaseline:l,recordArchitecture:u,target:i,validation:h}},go=async(e,r,n,t)=>{const{error:o,services:s}=Ee(e);if(o!==void 0)return o;if(s.length===0)return;const{toolchain:a}=n,i=a===void 0?`target "${n.id}" has no deploy command`:Ze(r);if(i!==void 0||a===void 0){const l=s.map(u=>u.worker).join(", ");r.logger.warn(`services not deployed (${i??""}): ${l} — deploy them yourself if the app calls anything new`);return}const c=O(e),d=[...new Map(s.map(l=>[l.wranglerPath,l])).values()];for(const l of d){const u=U(l.wranglerPath);let g;try{g=Oe(n,u,"deploy",m=>a.deploy({configPath:m??l.wranglerPath,dryRun:r.dryRun===!0,environment:r.env}))}catch(m){return`service ${l.name} (${l.worker}): ${m instanceof Error?m.message:String(m)}`}g.commit();const f=N(c,g.command);r.logger.info(`deploying service ${l.name} (${l.worker}) via ${f.command} ${f.args.join(" ")}`);const h=await t({args:f.args,command:f.command,cwd:u,stdoutToStderr:r.format==="json"});if(h.code!==0)return`service ${l.name} (${l.worker}): ${f.command} ${f.args.join(" ")} exited ${String(h.code)} — stopping before the app`}},fo=async(e,r,n,t)=>{if(r!=="cloudflare")return;const o=e===void 0?void 0:T(e).parsed,s=(n===void 0?void 0:o?.env?.[n]?.account_id)??o?.account_id,a=await Lr({accountId:s});(a.verdict==="near"||a.verdict==="full")&&t.warn(a.fix===void 0?a.message:`${a.message} ${a.fix}`)},ho=e=>e.dryRun!==!0&&e.temporary!==!0,mo=e=>e.temporary===!0?"temporary":e.dryRun===!0?"preview":"defer",po=e=>{const r=e.fix===void 0?e.message:`${e.message} ${e.fix}`;return e.verdict==="unchecked"?`${r} The deploy stops until it can be checked, as a namespace made by the first repo is unrestricted.`:r},vo=(e,r,n)=>{const t=[];for(const o of e)if(o.verdict==="ok")o.changesAccount===!0&&r.info(o.message);else if(o.verdict==="unchecked"&&n==="preview")r.warn(`dry run: ${o.message}${o.fix===void 0?"":` ${o.fix}`} A real deploy stops here.`);else{const s=po(o);r.error(s),t.push(s)}return t},er=async(e,r,n,t,o,s,a)=>{const i=n==="cloudflare"&&r!==void 0?T(r).parsed:void 0;if(i===void 0)return;const c=(G(i,t).merged.artifacts??[]).flatMap(h=>typeof h?.binding=="string"&&typeof h.namespace=="string"?[{binding:h.binding,namespace:h.namespace}]:[]),d=c.length===0?void 0:Re(e,_(e),s).info?.jurisdiction;if(d===void 0)return;const l=[...new Map(c.map(h=>[h.namespace,h])).values()];if(a==="temporary"){o.warn(`--temporary deploys to a throwaway account, so the jurisdiction ("${d}") of Artifacts namespace ${l.map(h=>`"${h.namespace}"`).join(", ")} was not checked: it is created there on first use, in no jurisdiction.`);return}const u=(t===void 0?void 0:i.env?.[t]?.account_id)??i.account_id,g=await Promise.all(l.map(async h=>xr({...h,accountId:u,create:a==="create",jurisdiction:d,missingOk:a==="defer"||a==="preview"}))),f=vo(g,o,a);return f.length===0?void 0:f.join(`
25
+ `)},yo=async(e,r,n,t,o,s)=>(ho(r)?await er(e,s,o,r.env,r.logger,r.discoveryCache,"create"):void 0)??await Ye(e,r,"deploy",o)??await go(e,r,n,t),wo=async(e,r,n,t)=>{if(!(r.smokeLoad===!1||n.toolchain===void 0))return It({composedEntry:se(e),configPath:t,cwd:e,environment:r.env,launcher:r.smokeLauncher,logger:r.logger,toolchain:n.toolchain})},ko=async e=>{const r={...e,discoveryCache:e.discoveryCache??hr()},n=r.cwd??process.cwd(),t=Xe(r),o=await uo(r,r.commandName??"deploy");if(o.error!==void 0){if(o.validation.problems.length>0)return{code:b.USAGE,descriptor:void 0,error:o.error,validation:o.validation};const p=o.schemaDrift===void 0?void 0:{schemaDrift:o.schemaDrift};return X(o.error,{...p,...o.code===void 0?{}:{code:o.code}})}const{validation:s}=o,a=te(o.target),i=qt(r)??await er(n,s.wranglerPath,o.target,r.env,r.logger,r.discoveryCache,mo(r))??await wo(n,r,a,s.wranglerPath);if(i!==void 0)return X(i);const c=a.toolchain?.prebuildsContainerImages===!0?await ro(n,r):void 0;if(c!==void 0)return X(c);Vn(n,r.logger,a),yr(n,p=>{r.logger.warn(p)}),await fo(s.wranglerPath,o.target,r.env,r.logger);const{error:d,mintedSecretsFile:l}=await eo(n,r,t,a);if(d!==void 0)return r.logger.error(d),{code:b.USAGE,descriptor:void 0,error:d,mintedSecretsFile:l,validation:s};const u=r.spawner??W,g=await yo(n,r,a,u,o.target,s.wranglerPath);if(g!==void 0)return{code:b.FAILURE,descriptor:void 0,error:g,mintedSecretsFile:l,validation:s};const f=co(n,r,a);r.logger.info(`deploying via ${f.command} ${f.args.join(" ")}`);const h=await u(f);return f.captureStdoutSilently===!0&&h.stdout!==void 0&&h.stdout!==""&&process.stderr.write(h.stdout),h.code!==0?{code:h.code,descriptor:f,mintedSecretsFile:l,validation:s}:{...await Kn({...o,cwd:n,descriptor:f,mintedSecretsFile:l,options:r,stdout:h.stdout}),logsAvailable:a.toolchain?.tail!==void 0}},bo=async e=>{const{logger:r}=e,n=e.dryRun===!0?jt(e.cwd??process.cwd()):void 0;let t;try{if(t=await ko({...e,logger:r}),t.code===0&&e.emitBindings!==void 0){const{error:o}=Mr({destination:e.emitBindings,logger:r,projectRoot:e.cwd??process.cwd()});o!==void 0&&(r.error(o),t={...t,code:b.USAGE})}}finally{n?.()}if(e.format==="json")return t;if(t.code===0&&e.dryRun!==!0&&e.preview!==!0)gt({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 o=t.deployment?.url;e.logger.success(o===void 0?"preview version uploaded":`preview version uploaded — ${o}`)}return t},Zo=Fr(async({cwd:e,format:r,logger:n,options:t})=>{const o=await bo({allowOpenShards:t.allowOpenShards===!0,allowSchemaDrift:t.allowSchemaDrift===!0,apiSpec:_r(t.apiSpec),lazyFunctions:Pe(t.lazyFunctions),cwd:e,dryRun:t.dryRun===!0,env:t.env,format:r,healthCheck:t.healthCheck===!0,logger:n,migrate:t.migrate===!0,migrateToken:t.migrateToken,migrateUrl:Le({cwd:e,env:t.env,url:t.migrateUrl}),migrateYes:t.migrateYes===!0,preview:t.preview===!0,skipCodegen:t.prebuilt===!0,skipServices:t.skipServices===!0,smokeLoad:t.smokeLoad,strictAdvisories:t.strictAdvisories,target:t.target,temporary:t.temporary===!0,updateSchemaBaseline:t.updateSchemaBaseline===!0});return{code:o.code,data:{deployment:o.deployment,healthCheck:o.healthCheck,mintedSecretsFile:o.mintedSecretsFile,schemaDrift:o.schemaDrift,validation:o.validation},error:o.error}});export{Zo as execute,no as provisionBindings,bo as runDeployCommand,uo as runPreDeployPipeline,wo as smokeLoadLazyModules};
@@ -1096,8 +1096,8 @@ import type { RateLimitConfigMap } from "lunorash/ratelimit";
1096
1096
  * \`lunora/messages.ts\`).
1097
1097
  */
1098
1098
  export const limits = {
1099
- /** Chat writes: 30 per caller per minute, refilling continuously over 60s. */
1100
- send: { kind: "token bucket", period: 60_000, rate: 30 },
1099
+ /** Chat writes: 10 per caller per minute, refilling continuously over 60s. */
1100
+ send: { kind: "token bucket", period: 60_000, rate: 10 },
1101
1101
  } as const satisfies RateLimitConfigMap;
1102
1102
 
1103
1103
  export type LimitName = keyof typeof limits;
@@ -1 +1 @@
1
- import{C as E,R as M,V as a,r as s}from"./cli-CPcfZdt0.mjs";import"./cli-manifest-DoQ_3bzs.mjs";import"./EXIT_CODE-D_XCixv8.mjs";import"./createLogger-4TujevyB.mjs";import"./render-lunora-error-B6893vbU.mjs";export{E as COMMANDS,M as REGISTERED_COMMAND_NAMES,a as VERSION,s as runCli};
1
+ import{C as E,R as M,V as a,r as s}from"./cli-lWJrDHQn.mjs";import"./cli-manifest-DoQ_3bzs.mjs";import"./EXIT_CODE-D_XCixv8.mjs";import"./createLogger-4TujevyB.mjs";import"./render-lunora-error-B6893vbU.mjs";export{E as COMMANDS,M as REGISTERED_COMMAND_NAMES,a as VERSION,s as runCli};
@@ -0,0 +1,2 @@
1
+ import{isLunoraError as L,findSolutionByMessage as I}from"@lunora/errors";import{createCerebro as j}from"@visulima/cerebro";import _ from"@visulima/cerebro/command/completion";import T from"@visulima/cerebro/command/version";import{O as s}from"./output-format-DWe_tkTR.mjs";import{A as m}from"./api-spec-lYyq4vL6.mjs";import{deployTargetIds as P,DEFAULT_DEPLOY_TARGET as U,addArgsFor as M,detectPackageManager as W}from"@lunora/config/cli";import{SDK_LANGUAGES as z}from"@lunora/codegen/sdk";import{r as $}from"./cli-manifest-DoQ_3bzs.mjs";import{EXIT_CODE as y,exitCodeForError as F}from"./EXIT_CODE-D_XCixv8.mjs";import{setCommandLogger as k,createLogger as v}from"./createLogger-4TujevyB.mjs";import{r as J}from"./render-lunora-error-B6893vbU.mjs";import{mkdirSync as K,readFileSync as G,lstatSync as H,writeFileSync as V}from"node:fs";import{homedir as q}from"node:os";import{join as b}from"node:path";const Y={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},s]},S="lunora.advisor.map.json",Q={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/handler17.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 ${S})`,name:"baseline",type:String},{description:"Inspect a single procedure by `file#exportName`",name:"entry",type:String},s,{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 ${S})`,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}]},X={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:[s]},Z={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/handler21.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},s,{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}]},ee=(()=>{const e=P();return e.length>1?`${e.join(" | ")} (default ${U})`:e.join(" | ")})(),p={description:`Deploy target: ${ee}. Also settable as "target" in lunora.config.*`,name:"target",type:String},te={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/handler18.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: ${m} (default openapi)`,name:"api-spec",type:String},{description:"Use per-module lazy function imports (opt-in; default eager)",name:"lazy-functions",type:Boolean},{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},s,{description:"Evaluate every lazy function module in workerd before shipping (default; nothing to check for an eager registry)",name:"smoke-load",type:Boolean},{description:"Skip evaluating lazy function modules before shipping",name:"no-smoke-load",type:Boolean},{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},p]},re=[{name:"alerts",summary:"usage alerts that catch a runaway bill",usage:"[status | setup | test]"},{name:"ai-gateway",summary:"create or reuse an AI Gateway for ctx.ai and write its id into wrangler vars",usage:""},{name:"containers",summary:"build and push container images, manage instances (wraps wrangler containers)",usage:"<build|push|images|list|info|delete> [args…]"},{name:"deployments",summary:"deployment history; roll back or promote Worker versions",usage:"list | inspect <version-id> | rollback [version-id] | promote <version-id>"},{name:"profile",summary:"capture an on-demand CPU or heap profile (pprof) from the live Worker or one of its Durable Objects",usage:"[worker]"}],R={argument:{description:`${re.map(e=>e.name).join(" | ")}, then the tool's own arguments`,name:"tool",type:String},description:"Cloudflare-only tools: usage alerts, AI Gateway, containers, deployments, profiling",examples:[["lunora cloudflare","List the tools"],["lunora cloudflare alerts","Show last month's usage and which products have an alert"],["lunora cloudflare alerts setup --email ops@example.com --dry-run","Show the alerts setup would create, without creating them"],["lunora cloudflare alerts setup --email ops@example.com --multiplier 5 --yes","Create or update the alerts at 5x last month"],["lunora cloudflare alerts setup --email ops@example.com --threshold do-duration=500000 --yes","Also alert on Durable Objects duration at a limit you choose"],["lunora cloudflare alerts test","Show what Cloudflare has delivered to your alert destinations"],["lunora cloudflare ai-gateway","Create (or reuse) a gateway named after the worker and wire it into wrangler vars"],["lunora cloudflare ai-gateway --id my-gateway --no-logs","Use an explicit gateway id, with prompt/response log collection off"],["lunora cloudflare ai-gateway --dry-run","Print what would be created and written, without calling Cloudflare"],["lunora cloudflare containers build ./containers/transcoder --tag transcoder:v1 --push","Build an image and push it to the Cloudflare Registry"],["lunora cloudflare containers images list","List images in your Cloudflare Registry"],["lunora cloudflare containers list --format json","List container instances as JSON (also `info`, `images list`)"],["lunora cloudflare containers images delete transcoder:v1","Delete an image to free registry storage"],["lunora cloudflare deployments list","Show the 10 most recent deployments"],["lunora cloudflare deployments inspect <version-id>","View a specific Worker version"],["lunora cloudflare deployments rollback --yes","Roll back to the previous version"],["lunora cloudflare deployments promote <version-id> --yes","Send 100% of traffic to a version"],["lunora cloudflare profile","Capture a 10s CPU profile of the latest version into ./<worker>-cpu-<time>.pprof.gz"],["lunora cloudflare profile --type heap --duration-ms 30000 --out heap.pprof.gz","Capture a 30s heap (allocation) profile"],["lunora cloudflare profile --namespace-id <id> --actor-id <64-hex>","Profile one Durable Object instance"]],group:"Deploy",loader:()=>import("../packem_chunks/handler27.mjs").then(e=>({default:e.execute})),name:"cloudflare",options:[{description:"alerts setup: email address to notify. Repeatable",lazyMultiple:!0,name:"email",type:String},{description:"alerts setup / test: Cloudflare webhook destination id. Repeatable",lazyMultiple:!0,name:"webhook",type:String},{description:"alerts setup: alert at this many times last month's usage (default 3)",name:"multiplier",type:String},{description:"alerts setup: set one metric's limit yourself, in the product's unit: <metric>=<n>. Repeatable",lazyMultiple:!0,name:"threshold",type:String},{description:"alerts setup: accept the floor for a metric whose usage could not be read",name:"allow-floor",type:Boolean},{description:"alerts setup: replace an updated alert's recipients instead of adding to them",name:"replace-recipients",type:Boolean},{description:"alerts setup / ai-gateway: show the plan without creating, updating or writing anything",name:"dry-run",type:Boolean},{description:"alerts setup: apply the plan without asking (required when stdin is not a TTY). deployments rollback / promote: confirm the traffic change (required)",name:"yes",type:Boolean},{description:"ai-gateway: gateway id (default: the worker `name` from wrangler.jsonc)",name:"id",type:String},{description:"ai-gateway: collect request/response logs in the gateway (default)",name:"logs",type:Boolean},{description:"ai-gateway: create the gateway with log collection off (prompts and responses are not stored)",name:"no-logs",type:Boolean},{description:"containers build: name:tag for the image (forwarded to wrangler --tag)",name:"tag",type:String},{description:"containers build: push the image to the Cloudflare Registry after building",name:"push",type:Boolean},{description:"containers / deployments / profile: Cloudflare environment name",name:"env",type:String},{description:"profile: capture window in ms, 1000–50000 (default 10000)",name:"duration-ms",type:String},{description:"profile: cpu (default) or heap",name:"type",type:String},{description:"profile: Worker version id to profile (default latest)",name:"version-id",type:String},{description:"profile: file to write the gzip pprof to (default <worker>-<type>-<time>.pprof.gz)",name:"out",type:String},{description:"profile: Durable Object namespace id (with --actor-id)",name:"namespace-id",type:String},{description:"profile: Durable Object instance id, 64 hex characters (with --namespace-id)",name:"actor-id",type:String},{description:"deployments rollback / promote: reason recorded with the change",name:"message",type:String},{...s,description:"Output format: pretty (default) or json (containers: list | info | images list; deployments: list only)"},p]},oe={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: ${m} (default openapi)`,name:"api-spec",type:String},{description:"Use per-module lazy imports for registered functions (opt-in; default eager)",name:"lazy-functions",type:Boolean},s,{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},p]},ne={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:"Deploy even though the app enables the open-shard option (any value but a literal false; any caller may target any shard). Without it, deploy refuses until shards are gated with `authorizeShard`",name:"allow-open-shards",type:Boolean},{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: ${m} (default openapi)`,name:"api-spec",type:String},{description:"Use per-module lazy function imports (opt-in; default eager)",name:"lazy-functions",type:Boolean},{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},s,{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},{description:"Evaluate every lazy function module in workerd before shipping (default; nothing to check for an eager registry)",name:"smoke-load",type:Boolean},{description:"Skip evaluating lazy function modules before shipping",name:"no-smoke-load",type:Boolean},p,{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}]},ae={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)"],["lunora dev --local","Start no remote proxy session, e.g. in CI where a service's `ai` binding has no credentials"],["lunora dev --tunnel","Share the worker on a public *.trycloudflare.com URL (needs cloudflared ≥ 2026.9.3)"],["lunora dev --tunnel --allow-mail you@example.com","Same, but visitors must confirm an allowed email with a one-time PIN"]],group:"Develop",loader:()=>import("../packem_chunks/runDevCommand.mjs").then(e=>({default:e.execute})),name:"dev",options:[{description:`Which API spec(s) codegen emits: ${m} (default openapi)`,name:"api-spec",type:String},{description:"Use per-module lazy imports for codegen (opt-in; default eager)",name:"lazy-functions",type:Boolean},{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},p,{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},{description:"Pass --local to wrangler dev: no remote proxy session, so an `ai` binding (in the app or a service) cannot stop dev from starting without Cloudflare credentials — it fails when called instead",name:"local",type:Boolean},{description:"Share the worker through a Cloudflare quick tunnel (*.trycloudflare.com, needs cloudflared ≥ 2026.9.3). PUBLIC unless --allow-mail is given",name:"tunnel",type:Boolean},{description:"With --tunnel: only these emails get in, after a one-time PIN (passed to cloudflared as --allowed-mail). Repeatable; accepts a comma list and '*@domain'",lazyMultiple:!0,name:"allow-mail",type:String}]},ie={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/handler3.mjs").then(e=>({default:e.execute})),name:"docs"},se={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"],["lunora doctor --fix","Create the D1 databases the config names and mint the local dev secrets"],["lunora doctor --fix --dry-run","Show what --fix would create or write, without doing it"]],group:"Project",loader:()=>import("../packem_chunks/handler25.mjs").then(e=>({default:e.execute})),name:"doctor",options:[s,{description:"Resolve what can be resolved: create placeholder D1 databases, mint missing .dev.vars secrets",name:"fix",type:Boolean},{description:"With --fix: print the changes without making them",name:"dry-run",type:Boolean}]},le={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/handler4.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},s,{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}]},de={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/handler22.mjs").then(e=>({default:e.execute})),name:"eval",options:[{description:"Directory to discover *.eval.ts files under (default evals/)",name:"dir",type:String},s,{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}]},pe={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/handler5.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},{...s,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}]},ce={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/handler6.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},s,{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}]},ue={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/handler7.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},s,{description:"With --bindings: write the manifest to <file> instead of stdout",name:"out",type:String}]},me={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}]},he={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/handler8.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},s,{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}]},ge={description:"Scaffold lunora/schema.ts (and list/get procedures) from an existing Postgres or MySQL database",examples:[["lunora introspect --url postgres://localhost/shop","Scaffold a schema + procedures from every table"],["lunora introspect --tables users,orders","Introspect only these tables (DATABASE_URL is read by default)"],["lunora introspect --dry-run","Print what would be written without touching the filesystem"],["lunora introspect --no-procedures --force","Regenerate just the schema, overwriting the existing file"]],group:"Data",loader:()=>import("../packem_chunks/handler24.mjs").then(e=>({default:e.execute})),name:"introspect",options:[{description:"Database connection string (default: $DATABASE_URL)",name:"url",type:String},{description:"Postgres schema (default `public`) or MySQL database name",name:"schema",type:String},{description:"Comma-separated table allow-list (default: every base table)",name:"tables",type:String},{description:"Also emit list/get procedure modules per table (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},s]},fe={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/handler9.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}]},ye={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/handler23.mjs").then(e=>({default:e.execute})),name:"logs",options:[{description:"Cloudflare environment name",name:"env",type:String},s,{description:"Substring filter on log messages",name:"search",type:String},{description:"Filter by invocation status: ok, error, or canceled",name:"status",type:String},p,{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}]},ve={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/handler26.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}]},be={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},s,{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}]},we={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/handler10.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: ${m} (default openapi)`,name:"api-spec",type:String},{description:"Use per-module lazy function imports (opt-in; default eager)",name:"lazy-functions",type:Boolean},{description:"Evaluate every lazy function module in workerd before passing (default; nothing to check for an eager registry)",name:"smoke-load",type:Boolean},{description:"Skip evaluating lazy function modules before passing",name:"no-smoke-load",type:Boolean},{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},p,{description:"Re-bless the committed schema baseline (lunora/.lunora-schema.json) with the current shape",name:"update-schema-baseline",type:Boolean}]},ke={description:"Capture an on-demand CPU or heap profile (pprof) from a running Node-target app",examples:[["lunora profile --target node --url https://app.example.com/__profile","Capture a 10 s CPU profile of the app"],["lunora profile --target node --url http://localhost:3000/__profile --type heap --duration-ms 30000","Capture a 30 s heap profile of a local app"],["lunora profile --target node --url https://app.example.com/__profile --out cpu.pprof.gz","Write the profile to a named file"]],group:"Develop",loader:()=>import("../packem_chunks/handler19.mjs").then(e=>({default:e.execute})),name:"profile",options:[{description:"Capture window in ms, 1000–50000 (default 10000)",name:"duration-ms",type:String},{description:"cpu (default) or heap",name:"type",type:String},{description:"File to write the gzip pprof to (default profile-<type>-<time>.pprof.gz)",name:"out",type:String},{description:"Full URL of the profile route the app mounts createNodeProfileHandler on",name:"url",type:String},{description:"Admin bearer token (or LUNORA_ADMIN_TOKEN)",name:"token",type:String},p]},Se={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/handler11.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},{...s,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}]},xe={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}]},Ce={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/handler12.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}]},Re={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},s,{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}]},Oe={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/handler20.mjs").then(e=>({default:e.execute})),name:"sdk",options:[{description:`Target language: ${z.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}]},Ne={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/handler13.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},s,{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}]},Ae={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/handler14.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},s,{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}]},Be={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/handler15.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: ${m} (default openapi)`,name:"api-spec",type:String},{description:"Use per-module lazy function imports (opt-in; default eager)",name:"lazy-functions",type:Boolean},{description:"Cloudflare environment name — validate the env.<name> view of wrangler.jsonc, as `lunora deploy --env` does",name:"env",type:String},s,{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},p]},De={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/handler16.mjs").then(e=>({default:e.execute})),name:"view"},Ee=(e,t)=>{const r=Array.from({length:t.length+1},(o,n)=>n);for(let o=1;o<=e.length;o+=1){let n=r[0]??0;r[0]=o;for(let a=1;a<=t.length;a+=1){const i=r[a]??0,l=e[o-1]===t[a-1]?0:1;r[a]=Math.min((r[a-1]??0)+1,i+1,n+l),n=i}}return r[t.length]??0},O=(e,t)=>{let r,o=Number.POSITIVE_INFINITY;for(const a of t){const i=Ee(e,a);i<o&&(o=i,r=a)}const n=Math.max(2,Math.ceil(e.length/3));return r!==void 0&&o<=n?r:void 0},Le=e=>`https://registry.npmjs.org/@lunora/cli/${e}`,Ie=1440*60*1e3,je=1500,_e="0.0.0",Te=/^v/u,Pe=new Set(["alpha","beta","next"]),g=e=>{const t=e.trim().replace(Te,""),r=t.indexOf("-");return r===-1?{core:t,prerelease:""}:{core:t.slice(0,r),prerelease:t.slice(r+1)}},x=e=>{const[t,r,o]=g(e).core.split(".").map(n=>{const a=Number.parseInt(n,10);return Number.isFinite(a)?a:0});return[t??0,r??0,o??0]},Ue=(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},Me=(e,t)=>{if(e===t)return 0;if(e===""||t==="")return e===""?1:-1;const r=e.split("."),o=t.split(".");for(let n=0;n<Math.max(r.length,o.length);n+=1){const a=r[n],i=o[n];if(a===void 0||i===void 0)return a===void 0?-1:1;if(a!==i)return Ue(a,i)}return 0},We=(e,t)=>{const r=x(e),o=x(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 Me(g(e).prerelease,g(t).prerelease)},ze=e=>{const t=g(e).prerelease.split(".")[0]??"";return Pe.has(t)?t:"latest"},$e=(e,t)=>We(t,e)>0,Fe=(e,t,r)=>t-e<r,Je=(e,t,r="latest",o)=>{const n=`Update available for @lunora/cli: ${e} → ${t}`;if(o===void 0)return`${n} — add @lunora/cli@${r} as a dev dependency to update`;const{args:a,command:i}=M(o,[`@lunora/cli@${r}`],{dev:!0});return`${n} — run \`${i} ${a.join(" ")}\``},N=e=>b(e,"lunora-cli-update.json"),Ke=e=>{const t=e.XDG_CACHE_HOME&&e.XDG_CACHE_HOME.length>0?e.XDG_CACHE_HOME:b(q(),".cache"),r=b(t,"lunora");try{K(r,{mode:448,recursive:!0})}catch{}return r},Ge=e=>{try{const t=JSON.parse(G(N(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{}},C=(e,t)=>{try{const r=N(e);try{if(H(r).isSymbolicLink())return}catch{}V(r,`${JSON.stringify(t)}
2
+ `,"utf8")}catch{}},He=async(e,t)=>{try{const r=await e(Le(t),{signal:AbortSignal.timeout(je)});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}},Ve=(e,t,r)=>e===_e||!r||t.CI!==void 0||t.LUNORA_NO_UPDATE_NOTIFIER!==void 0,qe=async e=>{const t=e.env??process.env,r=e.isTTY??process.stdout.isTTY;if(Ve(e.current,t,r))return;const o=e.cacheDir??Ke(t),n=(e.now??Date.now)(),a=e.ttlMs??Ie,i=ze(e.current),l=Ge(o),c=l?.tag??"latest",d=l!==void 0&&c===i?l:void 0;let h=d?.latest;if(d===void 0||!Fe(d.checkedAt,n,a)){const f=await He(e.fetchImpl??globalThis.fetch,i);f===void 0?C(o,{checkedAt:n,latest:e.current,tag:i}):(h=f,C(o,{checkedAt:n,latest:f,tag:i}))}h!==void 0&&$e(e.current,h)&&e.logger.warn(Je(e.current,h,i,e.manager))},A=["init","add","dev","codegen","build","deploy","prepare","link","cloudflare","logs","run","insights","profile","reset","migrate","export","import","seed","shards","backup","eval","verify","info","doctor","env","analyze","view","docs","registry","rules","mcp"],B=$(),Ye=[me,Y,ae,oe,Q,te,ne,we,fe,R,ye,Re,he,ke,xe,be,pe,ce,Ne,Ae,ge,Z,de,Be,ue,se,le,X,De,ie,Se,Ce,ve,Oe],D=[...Ye,T,_],Ct=D.map(e=>e.name),u=e=>e.replaceAll("{",String.raw`\{`).replaceAll("}",String.raw`\}`),Qe=e=>e.every(t=>typeof t=="string")?e.map(t=>u(t)):e.map(t=>typeof t=="string"?[u(t)]:t.map(r=>u(r))),Xe=e=>({...e,...e.argument===void 0?{}:{argument:{...e.argument,description:u(e.argument.description??"")}},...e.description===void 0?{}:{description:u(e.description)},...e.examples===void 0?{}:{examples:Qe(e.examples)},...e.options===void 0?{}:{options:e.options.map(t=>({...t,description:u(t.description??"")}))}}),Ze=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:B});for(const o of D)r.addCommand(Xe(o));return{cli:r,exitCode:t}},et=/Command "(?<name>[^"]+)" not found/u,w={ai:{absorbs:"gateway",to:"cloudflare ai-gateway"},alerts:{to:"cloudflare alerts"},containers:{to:"cloudflare containers"},deployments:{to:"cloudflare deployments"}},tt=new Set((R.options??[]).filter(e=>e.type!==Boolean).map(e=>`--${e.name}`)),rt=/^[\w@%+=:,./-]+$/u,ot=e=>rt.test(e)?e:`'${e.replaceAll("'",String.raw`'\''`)}'`,nt=(e,t)=>{const r=e.indexOf(t);return r===-1?[...e]:[...e.slice(0,r),...e.slice(r+1)]},at=(e,t)=>e.findIndex((r,o)=>r===t&&(o===0||!tt.has(e[o-1]??""))),it=e=>{const t=O(e,[...A,...Object.keys(w)]);return t!==void 0&&Object.hasOwn(w,t)?t:void 0},E=(e,t,r)=>{const o=it(e),n=o===void 0?void 0:w[o];if(o===void 0||n===void 0)return;const a=e===o?"":`\`lunora ${e}\` is not a command. `;let i=[...t];if(n.absorbs!==void 0){const d=at(i,n.absorbs);if(d===-1&&r===void 0)return`${a}\`lunora ${o}\` had one subcommand, \`${n.absorbs}\`; it moved to \`lunora ${n.to}\`.`;i=d===-1?i:[...i.slice(0,d),...i.slice(d+1)]}const l=n.absorbs===void 0?o:`${o} ${n.absorbs}`,c=r??["lunora",n.to,...i.map(d=>ot(d))].join(" ");return`${a}\`lunora ${l}\` moved to \`lunora ${n.to}\`. Run: ${c}`},st=(e,t)=>{const r=v(),o=e instanceof Error?e.message:String(e),n=et.exec(o);if(!n?.groups)return L(e)||I(o)!==void 0?r.error(J(e)):r.error(o),F(e);const a=n.groups.name??"",i=a.split(" ")[0]??"",l=E(i,nt(t,i));if(l!==void 0)return r.error(l),y.USAGE;const c=O(a,A);return r.error(`Unknown command "${a}".${c===void 0?"":` Did you mean "${c}"?`}`),r.info("Run `lunora --help` to list commands, or `lunora docs` to open the documentation."),y.USAGE},lt=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)}}),Rt=async(e={})=>{const{cli:t,exitCode:r}=Ze(e);e.logger!==void 0&&k(lt(e.logger));const o=e.argv??process.argv.slice(2);try{const a=o[0]==="help"&&o[1]!==void 0?E(o[1],o.slice(2),"lunora help cloudflare"):void 0;if(a!==void 0)return v().error(a),y.USAGE;await t.run({shouldExitProcess:!1})}catch(a){return st(a,o)}finally{k(void 0)}let n;try{n=W(process.cwd())}catch{}return await qe({current:B,logger:v(),manager:n}),r.value};export{A as C,S as D,Ct as R,B as V,re as a,Rt as r};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/cli",
3
- "version": "1.0.0-alpha.413",
3
+ "version": "1.0.0-alpha.415",
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.245",
56
- "@lunora/bindings": "1.0.0-alpha.129",
57
- "@lunora/codegen": "1.0.0-alpha.338",
58
- "@lunora/config": "1.0.0-alpha.389",
59
- "@lunora/container": "1.0.0-alpha.88",
60
- "@lunora/d1": "1.0.0-alpha.197",
55
+ "@lunora/advisor": "1.0.0-alpha.247",
56
+ "@lunora/bindings": "1.0.0-alpha.130",
57
+ "@lunora/codegen": "1.0.0-alpha.340",
58
+ "@lunora/config": "1.0.0-alpha.391",
59
+ "@lunora/container": "1.0.0-alpha.89",
60
+ "@lunora/d1": "1.0.0-alpha.198",
61
61
  "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
62
- "@lunora/mcp": "1.0.0-alpha.252",
63
- "@lunora/runtime": "1.0.0-alpha.227",
64
- "@lunora/seed": "1.0.0-alpha.245",
62
+ "@lunora/mcp": "1.0.0-alpha.254",
63
+ "@lunora/runtime": "1.0.0-alpha.228",
64
+ "@lunora/seed": "1.0.0-alpha.246",
65
65
  "@visulima/cerebro": "3.1.2",
66
66
  "@visulima/error": "6.1.0",
67
67
  "@visulima/fs": "6.0.29",
@@ -1,2 +0,0 @@
1
- import{isLunoraError as L,findSolutionByMessage as I}from"@lunora/errors";import{createCerebro as j}from"@visulima/cerebro";import _ from"@visulima/cerebro/command/completion";import T from"@visulima/cerebro/command/version";import{O as s}from"./output-format-DWe_tkTR.mjs";import{A as m}from"./api-spec-lYyq4vL6.mjs";import{deployTargetIds as P,DEFAULT_DEPLOY_TARGET as U,addArgsFor as M,detectPackageManager as W}from"@lunora/config/cli";import{SDK_LANGUAGES as z}from"@lunora/codegen/sdk";import{r as $}from"./cli-manifest-DoQ_3bzs.mjs";import{EXIT_CODE as y,exitCodeForError as F}from"./EXIT_CODE-D_XCixv8.mjs";import{setCommandLogger as k,createLogger as v}from"./createLogger-4TujevyB.mjs";import{r as J}from"./render-lunora-error-B6893vbU.mjs";import{mkdirSync as K,readFileSync as G,lstatSync as H,writeFileSync as V}from"node:fs";import{homedir as q}from"node:os";import{join as b}from"node:path";const Y={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},s]},S="lunora.advisor.map.json",Q={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/handler17.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 ${S})`,name:"baseline",type:String},{description:"Inspect a single procedure by `file#exportName`",name:"entry",type:String},s,{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 ${S})`,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}]},X={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:[s]},Z={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/handler21.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},s,{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}]},ee=(()=>{const e=P();return e.length>1?`${e.join(" | ")} (default ${U})`:e.join(" | ")})(),p={description:`Deploy target: ${ee}. Also settable as "target" in lunora.config.*`,name:"target",type:String},te={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/handler18.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: ${m} (default openapi)`,name:"api-spec",type:String},{description:"Use per-module lazy function imports (opt-in; default eager)",name:"lazy-functions",type:Boolean},{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},s,{description:"Evaluate every lazy function module in workerd before shipping (default; nothing to check for an eager registry)",name:"smoke-load",type:Boolean},{description:"Skip evaluating lazy function modules before shipping",name:"no-smoke-load",type:Boolean},{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},p]},re=[{name:"alerts",summary:"usage alerts that catch a runaway bill",usage:"[status | setup | test]"},{name:"ai-gateway",summary:"create or reuse an AI Gateway for ctx.ai and write its id into wrangler vars",usage:""},{name:"containers",summary:"build and push container images, manage instances (wraps wrangler containers)",usage:"<build|push|images|list|info|delete> [args…]"},{name:"deployments",summary:"deployment history; roll back or promote Worker versions",usage:"list | inspect <version-id> | rollback [version-id] | promote <version-id>"},{name:"profile",summary:"capture an on-demand CPU or heap profile (pprof) from the live Worker or one of its Durable Objects",usage:"[worker]"}],R={argument:{description:`${re.map(e=>e.name).join(" | ")}, then the tool's own arguments`,name:"tool",type:String},description:"Cloudflare-only tools: usage alerts, AI Gateway, containers, deployments, profiling",examples:[["lunora cloudflare","List the tools"],["lunora cloudflare alerts","Show last month's usage and which products have an alert"],["lunora cloudflare alerts setup --email ops@example.com --dry-run","Show the alerts setup would create, without creating them"],["lunora cloudflare alerts setup --email ops@example.com --multiplier 5 --yes","Create or update the alerts at 5x last month"],["lunora cloudflare alerts setup --email ops@example.com --threshold do-duration=500000 --yes","Also alert on Durable Objects duration at a limit you choose"],["lunora cloudflare alerts test","Show what Cloudflare has delivered to your alert destinations"],["lunora cloudflare ai-gateway","Create (or reuse) a gateway named after the worker and wire it into wrangler vars"],["lunora cloudflare ai-gateway --id my-gateway --no-logs","Use an explicit gateway id, with prompt/response log collection off"],["lunora cloudflare ai-gateway --dry-run","Print what would be created and written, without calling Cloudflare"],["lunora cloudflare containers build ./containers/transcoder --tag transcoder:v1 --push","Build an image and push it to the Cloudflare Registry"],["lunora cloudflare containers images list","List images in your Cloudflare Registry"],["lunora cloudflare containers list --format json","List container instances as JSON (also `info`, `images list`)"],["lunora cloudflare containers images delete transcoder:v1","Delete an image to free registry storage"],["lunora cloudflare deployments list","Show the 10 most recent deployments"],["lunora cloudflare deployments inspect <version-id>","View a specific Worker version"],["lunora cloudflare deployments rollback --yes","Roll back to the previous version"],["lunora cloudflare deployments promote <version-id> --yes","Send 100% of traffic to a version"],["lunora cloudflare profile","Capture a 10s CPU profile of the latest version into ./<worker>-cpu-<time>.pprof.gz"],["lunora cloudflare profile --type heap --duration-ms 30000 --out heap.pprof.gz","Capture a 30s heap (allocation) profile"],["lunora cloudflare profile --namespace-id <id> --actor-id <64-hex>","Profile one Durable Object instance"]],group:"Deploy",loader:()=>import("../packem_chunks/handler27.mjs").then(e=>({default:e.execute})),name:"cloudflare",options:[{description:"alerts setup: email address to notify. Repeatable",lazyMultiple:!0,name:"email",type:String},{description:"alerts setup / test: Cloudflare webhook destination id. Repeatable",lazyMultiple:!0,name:"webhook",type:String},{description:"alerts setup: alert at this many times last month's usage (default 3)",name:"multiplier",type:String},{description:"alerts setup: set one metric's limit yourself, in the product's unit: <metric>=<n>. Repeatable",lazyMultiple:!0,name:"threshold",type:String},{description:"alerts setup: accept the floor for a metric whose usage could not be read",name:"allow-floor",type:Boolean},{description:"alerts setup: replace an updated alert's recipients instead of adding to them",name:"replace-recipients",type:Boolean},{description:"alerts setup / ai-gateway: show the plan without creating, updating or writing anything",name:"dry-run",type:Boolean},{description:"alerts setup: apply the plan without asking (required when stdin is not a TTY). deployments rollback / promote: confirm the traffic change (required)",name:"yes",type:Boolean},{description:"ai-gateway: gateway id (default: the worker `name` from wrangler.jsonc)",name:"id",type:String},{description:"ai-gateway: collect request/response logs in the gateway (default)",name:"logs",type:Boolean},{description:"ai-gateway: create the gateway with log collection off (prompts and responses are not stored)",name:"no-logs",type:Boolean},{description:"containers build: name:tag for the image (forwarded to wrangler --tag)",name:"tag",type:String},{description:"containers build: push the image to the Cloudflare Registry after building",name:"push",type:Boolean},{description:"containers / deployments / profile: Cloudflare environment name",name:"env",type:String},{description:"profile: capture window in ms, 1000–50000 (default 10000)",name:"duration-ms",type:String},{description:"profile: cpu (default) or heap",name:"type",type:String},{description:"profile: Worker version id to profile (default latest)",name:"version-id",type:String},{description:"profile: file to write the gzip pprof to (default <worker>-<type>-<time>.pprof.gz)",name:"out",type:String},{description:"profile: Durable Object namespace id (with --actor-id)",name:"namespace-id",type:String},{description:"profile: Durable Object instance id, 64 hex characters (with --namespace-id)",name:"actor-id",type:String},{description:"deployments rollback / promote: reason recorded with the change",name:"message",type:String},{...s,description:"Output format: pretty (default) or json (containers: list | info | images list; deployments: list only)"},p]},oe={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: ${m} (default openapi)`,name:"api-spec",type:String},{description:"Use per-module lazy imports for registered functions (opt-in; default eager)",name:"lazy-functions",type:Boolean},s,{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},p]},ne={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: ${m} (default openapi)`,name:"api-spec",type:String},{description:"Use per-module lazy function imports (opt-in; default eager)",name:"lazy-functions",type:Boolean},{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},s,{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},{description:"Evaluate every lazy function module in workerd before shipping (default; nothing to check for an eager registry)",name:"smoke-load",type:Boolean},{description:"Skip evaluating lazy function modules before shipping",name:"no-smoke-load",type:Boolean},p,{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}]},ae={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)"],["lunora dev --local","Start no remote proxy session, e.g. in CI where a service's `ai` binding has no credentials"],["lunora dev --tunnel","Share the worker on a public *.trycloudflare.com URL (needs cloudflared ≥ 2026.9.3)"],["lunora dev --tunnel --allow-mail you@example.com","Same, but visitors must confirm an allowed email with a one-time PIN"]],group:"Develop",loader:()=>import("../packem_chunks/runDevCommand.mjs").then(e=>({default:e.execute})),name:"dev",options:[{description:`Which API spec(s) codegen emits: ${m} (default openapi)`,name:"api-spec",type:String},{description:"Use per-module lazy imports for codegen (opt-in; default eager)",name:"lazy-functions",type:Boolean},{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},p,{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},{description:"Pass --local to wrangler dev: no remote proxy session, so an `ai` binding (in the app or a service) cannot stop dev from starting without Cloudflare credentials — it fails when called instead",name:"local",type:Boolean},{description:"Share the worker through a Cloudflare quick tunnel (*.trycloudflare.com, needs cloudflared ≥ 2026.9.3). PUBLIC unless --allow-mail is given",name:"tunnel",type:Boolean},{description:"With --tunnel: only these emails get in, after a one-time PIN (passed to cloudflared as --allowed-mail). Repeatable; accepts a comma list and '*@domain'",lazyMultiple:!0,name:"allow-mail",type:String}]},ie={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/handler3.mjs").then(e=>({default:e.execute})),name:"docs"},se={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"],["lunora doctor --fix","Create the D1 databases the config names and mint the local dev secrets"],["lunora doctor --fix --dry-run","Show what --fix would create or write, without doing it"]],group:"Project",loader:()=>import("../packem_chunks/handler25.mjs").then(e=>({default:e.execute})),name:"doctor",options:[s,{description:"Resolve what can be resolved: create placeholder D1 databases, mint missing .dev.vars secrets",name:"fix",type:Boolean},{description:"With --fix: print the changes without making them",name:"dry-run",type:Boolean}]},le={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/handler4.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},s,{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}]},de={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/handler22.mjs").then(e=>({default:e.execute})),name:"eval",options:[{description:"Directory to discover *.eval.ts files under (default evals/)",name:"dir",type:String},s,{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}]},pe={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/handler5.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},{...s,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}]},ce={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/handler6.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},s,{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}]},ue={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/handler7.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},s,{description:"With --bindings: write the manifest to <file> instead of stdout",name:"out",type:String}]},me={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}]},ge={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/handler8.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},s,{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}]},he={description:"Scaffold lunora/schema.ts (and list/get procedures) from an existing Postgres or MySQL database",examples:[["lunora introspect --url postgres://localhost/shop","Scaffold a schema + procedures from every table"],["lunora introspect --tables users,orders","Introspect only these tables (DATABASE_URL is read by default)"],["lunora introspect --dry-run","Print what would be written without touching the filesystem"],["lunora introspect --no-procedures --force","Regenerate just the schema, overwriting the existing file"]],group:"Data",loader:()=>import("../packem_chunks/handler24.mjs").then(e=>({default:e.execute})),name:"introspect",options:[{description:"Database connection string (default: $DATABASE_URL)",name:"url",type:String},{description:"Postgres schema (default `public`) or MySQL database name",name:"schema",type:String},{description:"Comma-separated table allow-list (default: every base table)",name:"tables",type:String},{description:"Also emit list/get procedure modules per table (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},s]},fe={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/handler9.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}]},ye={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/handler23.mjs").then(e=>({default:e.execute})),name:"logs",options:[{description:"Cloudflare environment name",name:"env",type:String},s,{description:"Substring filter on log messages",name:"search",type:String},{description:"Filter by invocation status: ok, error, or canceled",name:"status",type:String},p,{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}]},ve={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/handler26.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}]},be={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},s,{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}]},we={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/handler10.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: ${m} (default openapi)`,name:"api-spec",type:String},{description:"Use per-module lazy function imports (opt-in; default eager)",name:"lazy-functions",type:Boolean},{description:"Evaluate every lazy function module in workerd before passing (default; nothing to check for an eager registry)",name:"smoke-load",type:Boolean},{description:"Skip evaluating lazy function modules before passing",name:"no-smoke-load",type:Boolean},{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},p,{description:"Re-bless the committed schema baseline (lunora/.lunora-schema.json) with the current shape",name:"update-schema-baseline",type:Boolean}]},ke={description:"Capture an on-demand CPU or heap profile (pprof) from a running Node-target app",examples:[["lunora profile --target node --url https://app.example.com/__profile","Capture a 10 s CPU profile of the app"],["lunora profile --target node --url http://localhost:3000/__profile --type heap --duration-ms 30000","Capture a 30 s heap profile of a local app"],["lunora profile --target node --url https://app.example.com/__profile --out cpu.pprof.gz","Write the profile to a named file"]],group:"Develop",loader:()=>import("../packem_chunks/handler19.mjs").then(e=>({default:e.execute})),name:"profile",options:[{description:"Capture window in ms, 1000–50000 (default 10000)",name:"duration-ms",type:String},{description:"cpu (default) or heap",name:"type",type:String},{description:"File to write the gzip pprof to (default profile-<type>-<time>.pprof.gz)",name:"out",type:String},{description:"Full URL of the profile route the app mounts createNodeProfileHandler on",name:"url",type:String},{description:"Admin bearer token (or LUNORA_ADMIN_TOKEN)",name:"token",type:String},p]},Se={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/handler11.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},{...s,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}]},xe={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}]},Ce={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/handler12.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}]},Re={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},s,{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}]},Oe={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/handler20.mjs").then(e=>({default:e.execute})),name:"sdk",options:[{description:`Target language: ${z.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}]},Ne={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/handler13.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},s,{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}]},Ae={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/handler14.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},s,{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}]},Be={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/handler15.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: ${m} (default openapi)`,name:"api-spec",type:String},{description:"Use per-module lazy function imports (opt-in; default eager)",name:"lazy-functions",type:Boolean},{description:"Cloudflare environment name — validate the env.<name> view of wrangler.jsonc, as `lunora deploy --env` does",name:"env",type:String},s,{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},p]},De={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/handler16.mjs").then(e=>({default:e.execute})),name:"view"},Ee=(e,t)=>{const r=Array.from({length:t.length+1},(o,n)=>n);for(let o=1;o<=e.length;o+=1){let n=r[0]??0;r[0]=o;for(let a=1;a<=t.length;a+=1){const i=r[a]??0,l=e[o-1]===t[a-1]?0:1;r[a]=Math.min((r[a-1]??0)+1,i+1,n+l),n=i}}return r[t.length]??0},O=(e,t)=>{let r,o=Number.POSITIVE_INFINITY;for(const a of t){const i=Ee(e,a);i<o&&(o=i,r=a)}const n=Math.max(2,Math.ceil(e.length/3));return r!==void 0&&o<=n?r:void 0},Le=e=>`https://registry.npmjs.org/@lunora/cli/${e}`,Ie=1440*60*1e3,je=1500,_e="0.0.0",Te=/^v/u,Pe=new Set(["alpha","beta","next"]),h=e=>{const t=e.trim().replace(Te,""),r=t.indexOf("-");return r===-1?{core:t,prerelease:""}:{core:t.slice(0,r),prerelease:t.slice(r+1)}},x=e=>{const[t,r,o]=h(e).core.split(".").map(n=>{const a=Number.parseInt(n,10);return Number.isFinite(a)?a:0});return[t??0,r??0,o??0]},Ue=(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},Me=(e,t)=>{if(e===t)return 0;if(e===""||t==="")return e===""?1:-1;const r=e.split("."),o=t.split(".");for(let n=0;n<Math.max(r.length,o.length);n+=1){const a=r[n],i=o[n];if(a===void 0||i===void 0)return a===void 0?-1:1;if(a!==i)return Ue(a,i)}return 0},We=(e,t)=>{const r=x(e),o=x(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 Me(h(e).prerelease,h(t).prerelease)},ze=e=>{const t=h(e).prerelease.split(".")[0]??"";return Pe.has(t)?t:"latest"},$e=(e,t)=>We(t,e)>0,Fe=(e,t,r)=>t-e<r,Je=(e,t,r="latest",o)=>{const n=`Update available for @lunora/cli: ${e} → ${t}`;if(o===void 0)return`${n} — add @lunora/cli@${r} as a dev dependency to update`;const{args:a,command:i}=M(o,[`@lunora/cli@${r}`],{dev:!0});return`${n} — run \`${i} ${a.join(" ")}\``},N=e=>b(e,"lunora-cli-update.json"),Ke=e=>{const t=e.XDG_CACHE_HOME&&e.XDG_CACHE_HOME.length>0?e.XDG_CACHE_HOME:b(q(),".cache"),r=b(t,"lunora");try{K(r,{mode:448,recursive:!0})}catch{}return r},Ge=e=>{try{const t=JSON.parse(G(N(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{}},C=(e,t)=>{try{const r=N(e);try{if(H(r).isSymbolicLink())return}catch{}V(r,`${JSON.stringify(t)}
2
- `,"utf8")}catch{}},He=async(e,t)=>{try{const r=await e(Le(t),{signal:AbortSignal.timeout(je)});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}},Ve=(e,t,r)=>e===_e||!r||t.CI!==void 0||t.LUNORA_NO_UPDATE_NOTIFIER!==void 0,qe=async e=>{const t=e.env??process.env,r=e.isTTY??process.stdout.isTTY;if(Ve(e.current,t,r))return;const o=e.cacheDir??Ke(t),n=(e.now??Date.now)(),a=e.ttlMs??Ie,i=ze(e.current),l=Ge(o),c=l?.tag??"latest",d=l!==void 0&&c===i?l:void 0;let g=d?.latest;if(d===void 0||!Fe(d.checkedAt,n,a)){const f=await He(e.fetchImpl??globalThis.fetch,i);f===void 0?C(o,{checkedAt:n,latest:e.current,tag:i}):(g=f,C(o,{checkedAt:n,latest:f,tag:i}))}g!==void 0&&$e(e.current,g)&&e.logger.warn(Je(e.current,g,i,e.manager))},A=["init","add","dev","codegen","build","deploy","prepare","link","cloudflare","logs","run","insights","profile","reset","migrate","export","import","seed","shards","backup","eval","verify","info","doctor","env","analyze","view","docs","registry","rules","mcp"],B=$(),Ye=[me,Y,ae,oe,Q,te,ne,we,fe,R,ye,Re,ge,ke,xe,be,pe,ce,Ne,Ae,he,Z,de,Be,ue,se,le,X,De,ie,Se,Ce,ve,Oe],D=[...Ye,T,_],Ct=D.map(e=>e.name),u=e=>e.replaceAll("{",String.raw`\{`).replaceAll("}",String.raw`\}`),Qe=e=>e.every(t=>typeof t=="string")?e.map(t=>u(t)):e.map(t=>typeof t=="string"?[u(t)]:t.map(r=>u(r))),Xe=e=>({...e,...e.argument===void 0?{}:{argument:{...e.argument,description:u(e.argument.description??"")}},...e.description===void 0?{}:{description:u(e.description)},...e.examples===void 0?{}:{examples:Qe(e.examples)},...e.options===void 0?{}:{options:e.options.map(t=>({...t,description:u(t.description??"")}))}}),Ze=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:B});for(const o of D)r.addCommand(Xe(o));return{cli:r,exitCode:t}},et=/Command "(?<name>[^"]+)" not found/u,w={ai:{absorbs:"gateway",to:"cloudflare ai-gateway"},alerts:{to:"cloudflare alerts"},containers:{to:"cloudflare containers"},deployments:{to:"cloudflare deployments"}},tt=new Set((R.options??[]).filter(e=>e.type!==Boolean).map(e=>`--${e.name}`)),rt=/^[\w@%+=:,./-]+$/u,ot=e=>rt.test(e)?e:`'${e.replaceAll("'",String.raw`'\''`)}'`,nt=(e,t)=>{const r=e.indexOf(t);return r===-1?[...e]:[...e.slice(0,r),...e.slice(r+1)]},at=(e,t)=>e.findIndex((r,o)=>r===t&&(o===0||!tt.has(e[o-1]??""))),it=e=>{const t=O(e,[...A,...Object.keys(w)]);return t!==void 0&&Object.hasOwn(w,t)?t:void 0},E=(e,t,r)=>{const o=it(e),n=o===void 0?void 0:w[o];if(o===void 0||n===void 0)return;const a=e===o?"":`\`lunora ${e}\` is not a command. `;let i=[...t];if(n.absorbs!==void 0){const d=at(i,n.absorbs);if(d===-1&&r===void 0)return`${a}\`lunora ${o}\` had one subcommand, \`${n.absorbs}\`; it moved to \`lunora ${n.to}\`.`;i=d===-1?i:[...i.slice(0,d),...i.slice(d+1)]}const l=n.absorbs===void 0?o:`${o} ${n.absorbs}`,c=r??["lunora",n.to,...i.map(d=>ot(d))].join(" ");return`${a}\`lunora ${l}\` moved to \`lunora ${n.to}\`. Run: ${c}`},st=(e,t)=>{const r=v(),o=e instanceof Error?e.message:String(e),n=et.exec(o);if(!n?.groups)return L(e)||I(o)!==void 0?r.error(J(e)):r.error(o),F(e);const a=n.groups.name??"",i=a.split(" ")[0]??"",l=E(i,nt(t,i));if(l!==void 0)return r.error(l),y.USAGE;const c=O(a,A);return r.error(`Unknown command "${a}".${c===void 0?"":` Did you mean "${c}"?`}`),r.info("Run `lunora --help` to list commands, or `lunora docs` to open the documentation."),y.USAGE},lt=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)}}),Rt=async(e={})=>{const{cli:t,exitCode:r}=Ze(e);e.logger!==void 0&&k(lt(e.logger));const o=e.argv??process.argv.slice(2);try{const a=o[0]==="help"&&o[1]!==void 0?E(o[1],o.slice(2),"lunora help cloudflare"):void 0;if(a!==void 0)return v().error(a),y.USAGE;await t.run({shouldExitProcess:!1})}catch(a){return st(a,o)}finally{k(void 0)}let n;try{n=W(process.cwd())}catch{}return await qe({current:B,logger:v(),manager:n}),r.value};export{A as C,S as D,Ct as R,B as V,re as a,Rt as r};