@lunora/cli 1.0.0-alpha.469 → 1.0.0-alpha.470

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/dist/index.d.mts +12 -0
  2. package/dist/index.d.ts +12 -0
  3. package/dist/index.mjs +1 -1
  4. package/dist/packem_chunks/cli.mjs +2 -2
  5. package/dist/packem_chunks/dispatch.mjs +1 -1
  6. package/dist/packem_chunks/handler.mjs +2 -2
  7. package/dist/packem_chunks/handler10.mjs +2 -1
  8. package/dist/packem_chunks/handler11.mjs +1 -1
  9. package/dist/packem_chunks/handler12.mjs +1 -1
  10. package/dist/packem_chunks/handler13.mjs +1 -3
  11. package/dist/packem_chunks/handler14.mjs +3 -1
  12. package/dist/packem_chunks/handler15.mjs +1 -1
  13. package/dist/packem_chunks/handler16.mjs +1 -1
  14. package/dist/packem_chunks/handler17.mjs +1 -1
  15. package/dist/packem_chunks/handler18.mjs +1 -1
  16. package/dist/packem_chunks/handler19.mjs +1 -1
  17. package/dist/packem_chunks/handler20.mjs +1 -7
  18. package/dist/packem_chunks/handler21.mjs +7 -2
  19. package/dist/packem_chunks/handler24.mjs +1 -1
  20. package/dist/packem_chunks/handler25.mjs +2 -1
  21. package/dist/packem_chunks/handler26.mjs +1 -2
  22. package/dist/packem_chunks/handler27.mjs +2 -99
  23. package/dist/packem_chunks/handler28.mjs +99 -3
  24. package/dist/packem_chunks/handler29.mjs +3 -15
  25. package/dist/packem_chunks/handler3.mjs +1 -1
  26. package/dist/packem_chunks/handler30.mjs +15 -1
  27. package/dist/packem_chunks/handler31.mjs +1 -1
  28. package/dist/packem_chunks/handler32.mjs +1 -0
  29. package/dist/packem_chunks/handler4.mjs +1 -1
  30. package/dist/packem_chunks/handler5.mjs +1 -3
  31. package/dist/packem_chunks/handler6.mjs +3 -1
  32. package/dist/packem_chunks/handler7.mjs +1 -1
  33. package/dist/packem_chunks/handler8.mjs +1 -1
  34. package/dist/packem_chunks/handler9.mjs +1 -2
  35. package/dist/packem_chunks/runDevCommand.mjs +1 -1
  36. package/dist/packem_chunks/runInitCommand.mjs +37 -27
  37. package/dist/packem_chunks/runRpcCommand.mjs +1 -1
  38. package/dist/packem_shared/createRecordingSpawner-DchLi0gR.mjs +1 -0
  39. package/dist/packem_shared/{plan-KTxWYvt_.mjs → plan-pog5AvMk.mjs} +1 -1
  40. package/dist/packem_shared/{planDevCommand-CEDLRkjW.mjs → planDevCommand-Bl6OrwXm.mjs} +1 -1
  41. package/dist/packem_shared/{resolve-target-C_ZloTvd.mjs → resolve-target-BRvw8Pf7.mjs} +1 -1
  42. package/dist/packem_shared/{runDeployCommand-5ng8LjBN.mjs → runDeployCommand-CNgOUx91.mjs} +1 -1
  43. package/dist/packem_shared/{vectorize-metadata-BVSF8z2h.mjs → vectorize-metadata-DK61NmVx.mjs} +1 -1
  44. package/dist/packem_shared/{wrangler-secrets-DlSlWvRH.mjs → wrangler-secrets-C9siMBwN.mjs} +1 -1
  45. package/package.json +8 -8
  46. package/dist/packem_shared/createRecordingSpawner-01ZngIwK.mjs +0 -1
@@ -1,15 +1,3 @@
1
- import{V as te}from"./cli.mjs";import{d as re}from"../packem_shared/command-BpMv2n0o.mjs";import{EXIT_CODE as f}from"../packem_shared/EXIT_CODE-DQVhSE-1.mjs";import{existsSync as m,readFileSync as F,statSync as ne,watch as oe}from"node:fs";import{homedir as C}from"node:os";import{findWranglerFile as le}from"@lunora/config/cloudflare";import{join as i,relative as ae}from"@visulima/path";import{stringify as ce}from"smol-toml";import{h as se,u as ie,i as de,r as ue}from"../packem_shared/mcp-config-file-GR1Y_CVw.mjs";import{detectPackageManager as me,execArgsFor as fe}from"@lunora/config/cli";import{resolve as $,join as pe,dirname as L}from"node:path";import{readLiveDevServerState as b,DEV_STATE_DIR as ge}from"@lunora/config";import{resolveAdminToken as he}from"@lunora/config/studio-host";import{connectLocalStdio as ve,connectFunctionStdio as ye}from"@lunora/mcp";import{i as we}from"../packem_shared/path-containment-CgxYZggb.mjs";const g=e=>({args:[...e.args],command:e.command,...e.env===void 0?{}:{env:e.env}}),j=e=>e.transport==="http"?{type:"http",url:e.url}:g(e),be=e=>e.transport==="http"?{httpUrl:e.url}:g(e),Se=e=>e.transport==="http"?{serverUrl:e.url}:g(e),ke=e=>({args:["-y","mcp-remote",e],command:"npx"}),Ee=e=>e.transport==="http"?ke(e.url):g(e),$e=e=>e.transport==="http"?{url:e.url}:g(e),je=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}},Oe=e=>e.transport==="http"?{disabled:!1,type:"streamableHttp",url:e.url}:{disabled:!1,...g(e)},Ce=({home:e,platform:t})=>{if(t==="darwin")return{global:i(e,"Library","Application Support","Claude","claude_desktop_config.json")};if(t==="win32"){const r=process.env.APPDATA;return r===void 0||r===""?{}:{global:i(r,"Claude","claude_desktop_config.json")}}return t==="linux"?{global:i(e,".config","Claude","claude_desktop_config.json")}:{}},_e=(e,t)=>ce({mcp_servers:{[e]:t.transport==="http"?{url:t.url}:{args:[...t.args],command:t.command,...t.env===void 0?{}:{env:t.env}}}}),v=[{buildEntry:j,paths:({projectRoot:e})=>({project:i(e,".mcp.json")}),format:"json",id:"claude-code",key:"mcpServers",label:"Claude Code"},{buildEntry:j,paths:({home:e,projectRoot:t})=>({global:i(e,".cursor","mcp.json"),project:i(t,".cursor","mcp.json")}),format:"json",id:"cursor",key:"mcpServers",label:"Cursor"},{buildEntry:j,paths:({projectRoot:e})=>({project:i(e,".vscode","mcp.json")}),format:"json",id:"vscode",key:"servers",label:"VS Code (GitHub Copilot)"},{buildEntry:be,paths:({home:e,projectRoot:t})=>({global:i(e,".gemini","settings.json"),project:i(t,".gemini","settings.json")}),format:"json",id:"gemini",key:"mcpServers",label:"Gemini CLI"},{buildEntry:Ee,paths:Ce,format:"json",id:"claude-desktop",key:"mcpServers",label:"Claude Desktop"},{buildEntry:Se,paths:({home:e})=>({global:i(e,".codeium","windsurf","mcp_config.json")}),format:"json",id:"windsurf",key:"mcpServers",label:"Windsurf"},{buildEntry:je,paths:({home:e,projectRoot:t})=>({global:i(e,".config","opencode","opencode.json"),project:i(t,"opencode.json")}),format:"json",id:"opencode",key:"mcp",label:"OpenCode"},{buildEntry:Oe,paths:({home:e})=>({global:i(e,".cline","mcp.json")}),format:"json",id:"cline",key:"mcpServers",label:"Cline"},{buildEntry:$e,paths:({home:e})=>({global:i(e,".config","zed","settings.json")}),format:"json",id:"zed",key:"context_servers",label:"Zed"},{paths:({home:e,projectRoot:t})=>({global:i(e,".codex","config.toml"),project:i(t,".codex","config.toml")}),format:"manual",id:"codex",label:"Codex CLI",renderSnippet:_e}],P=v.map(e=>e.id),Me=e=>v.find(t=>t.id===e.toLowerCase()),Ue=["global","project"],p=(e,t)=>{const r=ae(t,e);return r.length>0&&!r.startsWith("..")?r:e},xe=(e,t)=>{const r=e.paths(t);return Ue.flatMap(n=>{const o=r[n];return o===void 0?[]:[{client:e,path:o,scope:n}]})},Le=(e,t,r,n)=>{const o=e.paths(t),l=r==="global"?"project":"global",a=o[r]??(n?void 0:o[l]);if(a!==void 0)return{client:e,path:a,scope:o[r]===void 0?l:r}},Ne=e=>v.filter(t=>Object.values(t.paths(e)).some(r=>m(r))),I=(e,t,r,n)=>{if(e.length===0)return t();const o=[];for(const l of e){const a=Me(l);if(a===void 0){r.error(`mcp ${n}: unknown client "${l}". Known clients: ${P.join(", ")}.`);return}o.push(a)}return o},Ae=e=>e.client.format==="json",De="https://lunora.sh/mcp",R="lunora-docs",H="lunora",Te=e=>m(i(e,"lunora"))&&le(e)!==void 0,Fe=e=>{const{args:t,command:r}=fe(e,"lunora",["mcp","serve"]);return{args:t,command:r,transport:"stdio"}},Pe=e=>({transport:"http",url:e}),Ie=e=>({home:e.home,platform:e.platform,projectRoot:e.cwd}),W=(e,t,r)=>Le(e,Ie(r),r.scope??t.preferredScope,r.scope!==void 0||!t.allowScopeFallback),Re=(e,t,r)=>{const n=W(e,t,r);if(n===void 0){r.logger.warn(`${e.label}: has no ${r.scope??t.preferredScope}-scoped config — skipped "${t.name}".`);return}const{path:o}=n,l=e.buildEntry(t.spec);if(r.print===!0){const d=p(o,r.cwd);return r.force!==!0&&se({key:e.key,name:t.name,path:o})?(r.logger.info(`${e.label}: "${t.name}" already configured in ${d} — a real install would skip it (re-run with --force to replace).`),{action:"printed",path:o}):(r.logger.info(`${e.label} → ${d}
2
- ${JSON.stringify({[e.key]:{[t.name]:l}},void 0,4)}`),{action:"printed",path:o})}const a=ie({entry:l,force:r.force===!0,key:e.key,name:t.name,path:o}),c=p(o,r.cwd);return a.action==="invalid"?r.logger.error(`${e.label}: ${c} is not valid JSON (${a.error??"unknown error"}) — left untouched.`):a.action==="skipped"?r.logger.info(`${e.label}: "${t.name}" already configured in ${c} — re-run with --force to replace it.`):r.logger.success(`${e.label}: ${a.action==="created"?"created":"updated"} ${c} with "${t.name}".`),{action:a.action,path:o}},He=(e,t,r)=>{const n=W(e,t,r)?.path;if(n===void 0){r.logger.warn(`${e.label}: no known config location on ${r.platform} — skipped.`);return}return r.logger.info(`${e.label}: add this to ${p(n,r.cwd)}
3
-
4
- ${e.renderSnippet(t.name,t.spec)}`),{action:"printed",path:n}},We=e=>{const t=[];return e.localOnly!==!0&&t.push({allowScopeFallback:!0,name:R,preferredScope:"global",spec:Pe(e.docsUrl??De)}),e.docsOnly!==!0&&Te(e.cwd)&&t.push({allowScopeFallback:!1,name:H,preferredScope:"project",spec:Fe(me(e.cwd))}),t},Ge=e=>{const t=e.home??C(),r=e.platform??process.platform;e.logger.info("Supported MCP clients:");for(const n of v){const o=n.paths({home:t,platform:r,projectRoot:e.cwd}),l=a=>{const c=o[a];return c===void 0?"—":p(c,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:[]}},Je=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).",Ve=(e,t,r)=>{const n=[];for(const o of e)for(const l of t){const a=o.format==="json"?Re(o,l,r):He(o,l,r);a!==void 0&&n.push({action:a.action,client:o.id,path:a.path,server:l.name})}return n},ze=e=>{const t=e.home??C(),r=e.platform??process.platform,n=I(e.clients,()=>Ne({home:t,platform:r,projectRoot:e.cwd}),e.logger,"install");if(n===void 0)return{code:f.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: ${P.join(", ")}.`),{code:f.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=We(e);if(o.length===0)return e.logger.error(`mcp install: nothing to install — ${Je(e)}`),{code:f.USAGE,written:[]};const l=Ve(n,o,{...e,home:t,platform:r});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}},G=100,J=1e3,N=e=>({content:[{text:JSON.stringify(e,void 0,2),type:"text"}]}),Ke=e=>({content:[{text:e,type:"text"}]}),qe=e=>{const t=typeof e=="string"?Number(e):e;return typeof t!="number"||!Number.isFinite(t)?G:Math.min(J,Math.max(1,Math.floor(t)))},A=(e,t)=>{if(t===void 0)return;const r=$(e,ge);return we(r,$(e,t))?$(e,t):void 0},Be=(e,t)=>{const r=F(e,"utf8").split(`
5
- `);return r.at(-1)===""&&r.pop(),r.slice(-t).join(`
6
- `)},Xe=e=>[{definition:{annotations:{destructiveHint:!1,idempotentHint:!0,openWorldHint:!1,readOnlyHint:!0,title:"Check the local dev server"},description:"Report whether a `lunora dev` server is running for this project, and its URL, studio URL, mode and uptime. Call this first when a query or mutation tool fails to connect.",inputSchema:{properties:{},type:"object"},name:"lunora_dev_status"},handle:async()=>{const t=b(e);return N(t===void 0?{hint:"Start it with `lunora dev` in the project directory.",running:!1}:{background:t.background===!0,logFile:A(e,t.logFile),mode:t.mode,pid:t.pid,running:!0,startedAt:t.startedAt,studioUrl:t.studioUrl,url:t.url})}},{definition:{annotations:{destructiveHint:!1,idempotentHint:!0,openWorldHint:!1,readOnlyHint:!0,title:"Read the local dev server log"},description:"Return the tail of the running dev server's captured log — worker output, request errors, and stack traces. Only available when the server was started in the background (`lunora dev --background`); a foreground server prints to its own terminal.",inputSchema:{properties:{lines:{description:`How many trailing lines to return (default ${String(G)}, max ${String(J)})`,type:"number"}},type:"object"},name:"lunora_dev_logs"},handle:async t=>{const r=b(e);if(r===void 0)return{content:[{text:"no dev server is running — start one with `lunora dev`",type:"text"}],isError:!0};const n=A(e,r.logFile);if(n===void 0||!m(n))return{content:[{text:"this dev server is not capturing its output to a file (it runs in the foreground) — restart it with `lunora dev --background` to make its logs readable here",type:"text"}],isError:!0};const o=qe(t.lines),l=Be(n,o);return Ke(l.length===0?"(the dev server log is empty)":l)}}],O={methods:[],openrpc:"1.3.2"},Ze=e=>e instanceof Error&&e.code==="ENOENT",Qe=new Set(["127.0.0.1","::1","localhost"]),V=e=>{try{const{hostname:t}=new URL(e);return Qe.has(t.startsWith("[")?t.slice(1,-1):t)}catch{return!1}},D=e=>{const t=e.url??b(e.cwd)?.url;if(t===void 0||t.length===0)return;if(e.token!==void 0&&e.token.length>0)return{token:e.token,url:t};if(!V(t))return{url:t};const r=he(e.cwd);return r===void 0||r.length===0?{url:t}:{token:r,url:t}},z=async e=>{await new Promise(t=>{const r=()=>{t()};e.onclose=r,process.stdin.once("close",r),process.stdin.once("end",r)})},Ye=e=>{if(e===void 0)return"lunora mcp serve: ready (documentation tools). No dev server running yet — start `lunora dev` and the deployment tools start working, no restart needed.\n";if(e.token!==void 0)return`lunora mcp serve: ready — deployment at ${e.url}
7
- `;const r=!V(e.url)?"the project's admin token was NOT sent to this non-local url; pass --token to authenticate deliberately":"no LUNORA_ADMIN_TOKEN in the environment or .dev.vars; the deployment tools will be refused until one is set";return`lunora mcp serve: ready — deployment at ${e.url} (${r})
8
- `},K=e=>{process.stderr.write(e)},et=async(e,t)=>{const r=e.writeError??K,n=pe(e.cwd,"lunora","_generated","openrpc.json"),o=()=>e.url??b(e.cwd)?.url;let l,a;const c=s=>{r(`lunora mcp serve --functions: kept the last tool list — the rewritten document did not load: ${String(s)}
9
- `)};let d={mtimeMs:-1,spec:O};const y=()=>{let s;try{s=ne(n).mtimeMs,a=void 0}catch(u){if(Ze(u))d.spec!==O&&(d={mtimeMs:-1,spec:O});else{const E=u.code??String(u);a!==E&&(a=E,c(u))}return d.spec}if(s!==d.mtimeMs)try{d={mtimeMs:s,spec:JSON.parse(F(n,"utf8"))}}catch(u){l!==s&&(l=s,c(u))}return d.spec};let w;try{w=await t({allowWrites:e.allowWrites===!0,onReloadError:c,openRpcSpec:y,url:o,version:e.version,...e.token===void 0||e.token.length===0?{}:{token:e.token}})}catch(s){const u=s instanceof Error?s.message:String(s);return r(`lunora mcp serve --functions: failed to start — ${u}
10
- `),{code:1,deployment:void 0}}const q=e.token===void 0||e.token.length===0,S=o(),B=S===void 0||S.length===0?"no deployment yet (start `lunora dev` or pass --url; calls fail until one runs)":S,X=m(n)?"":" (no openrpc.json yet: run `lunora codegen --api-spec openrpc`; the functions appear once it exists)";r(`lunora mcp serve --functions: ready — ${B}${q?" (no --token: only public functions answer, and writes are refused)":""}${X}
11
- `);const k=L(n),_=s=>{r(`lunora mcp serve --functions: the tool list will not be announced on a change — ${String(s)}
12
- `)},Z=()=>{if(m(k))return k;const s=L(k);return m(s)?s:e.cwd};let M=m(n),h;const U=()=>{const s=Z();if(h?.directory!==s){h?.watcher.close(),h=void 0;try{const u=oe(s,(E,Q)=>{const x=m(n),Y=Q==="openrpc.json"||x!==M;M=x,U(),Y&&w.sendToolListChanged?.().catch(ee=>{r(`lunora mcp serve --functions: could not announce the tool list change — ${String(ee)}
13
- `)})});u.on("error",_),h={directory:s,watcher:u}}catch(u){_(u)}}};U();try{await z(w)}finally{h?.watcher.close();try{await w.close?.()}catch(s){r(`lunora mcp serve --functions: could not close the server — ${String(s)}
14
- `)}}return{code:0,deployment:void 0}},tt=async(e,t=ve,r=ye)=>{if(e.functions===!0)return et(e,r);const n=e.writeError??K;let o;try{o=await t({allowWrites:e.allowWrites===!0,deployment:()=>D(e),docs:e.noDocs===!0?!1:{...e.docsUrl===void 0?{}:{baseUrl:e.docsUrl}},extraTools:Xe(e.cwd),version:e.version})}catch(a){const c=a instanceof Error?a.message:String(a);return n(`lunora mcp serve: failed to start — ${c}
15
- `),{code:1,deployment:void 0}}const l=D(e);return n(Ye(l)),await z(o),{code:0,deployment:l}},rt=e=>{const t=[];return e.localOnly!==!0&&t.push(R),e.docsOnly!==!0&&t.push(H),t},nt=(e,t,r,n)=>{const o=ue({key:e.key,name:t,path:r}),l=p(r,n.cwd);return o.action==="removed"?n.logger.success(`${e.label}: removed "${t}" from ${l}.`):o.action==="invalid"&&n.logger.error(`${e.label}: ${l} is not valid JSON (${o.error??"unknown error"}) — left untouched.`),{action:o.action,path:r}},ot=(e,t,r,n)=>{const o=de({key:e.key,name:t,path:r}),l=p(r,n.cwd);return o==="invalid"?(n.logger.error(`${e.label}: ${l} is not valid JSON — a real run would report it and exit non-zero.`),{action:"invalid",path:r}):o==="absent"?{action:"absent",path:r}:(n.logger.info(`${e.label}: would remove "${t}" from ${l}.`),{action:"removed",path:r})},lt=(e,t,r)=>e.flatMap(n=>xe(n,t)).filter(Ae).filter(n=>r===void 0||n.scope===r),at=e=>{const t=e.home??C(),r=e.platform??process.platform,n=I(e.clients,()=>v,e.logger,"uninstall");if(n===void 0)return{code:f.USAGE,removed:[]};const o=rt(e);if(o.length===0)return e.logger.error("mcp uninstall: nothing to remove — `--docs-only` and `--local-only` are mutually exclusive, pass at most one."),{code:f.USAGE,removed:[]};const l=[],a={home:t,platform:r,projectRoot:e.cwd};for(const c of lt(n,a,e.scope))for(const d of o){const y=e.print===!0?ot(c.client,d,c.path,e):nt(c.client,d,c.path,e);y.action!=="absent"&&l.push({...y,client:c.client.id,server:d})}return l.length===0?e.logger.info("Nothing to remove — no Lunora MCP servers were configured in the clients checked."):e.print===!0&&e.logger.info("Nothing was changed — re-run without --print to remove these."),{code:l.some(c=>c.action==="invalid")?1:0,removed:l}},T=e=>e.global===!0?"global":e.project===!0?"project":void 0,ct=async(e,t)=>{const{code:r}=await tt({allowWrites:t.allowWrites===!0,cwd:e,functions:t.functions===!0,noDocs:t.docs===!1,version:te,...t.docsUrl===void 0?{}:{docsUrl:t.docsUrl},...t.token===void 0?{}:{token:t.token},...t.url===void 0?{}:{url:t.url}});return{code:r}},Et=re(async({argument:e,cwd:t,logger:r,options:n})=>{const[o,...l]=e;if(o==="serve")return ct(t,n);if(o==="uninstall"){const a=T(n),{code:c}=at({clients:l,cwd:t,docsOnly:n.docsOnly===!0,localOnly:n.localOnly===!0,logger:r,print:n.print===!0,...a===void 0?{}:{scope:a}});return{code:c}}if(o==="install"){if(n.list===!0)return Ge({cwd:t,logger:r});const a=T(n),{code:c}=ze({clients:l,cwd:t,docsOnly:n.docsOnly===!0,force:n.force===!0,localOnly:n.localOnly===!0,logger:r,print:n.print===!0,...a===void 0?{}:{scope:a},...n.docsUrl===void 0?{}:{docsUrl:n.docsUrl}});return{code:c}}return r.error("mcp: unknown subcommand. Usage: lunora mcp <install|uninstall|serve>"),{code:f.USAGE}});export{Et as execute};
1
+ import{randomUUID as V,createHash as gr,createHmac as yr}from"node:crypto";import{mkdirSync as $r,writeFileSync as ne,linkSync as xe,rmSync as F,statSync as Ce,unlinkSync as kr,readFileSync as L,existsSync as Q,mkdtempSync as Er}from"node:fs";import{tmpdir as br}from"node:os";import{join as ee,dirname as _r}from"node:path";import{SCHEMA_SNAPSHOT_FILENAME as Sr,readServiceBindings as Rr}from"@lunora/codegen";import{generateSecretValue as Ir}from"@lunora/config";import{readManifest as Ke,recordManifestKey as Or,findWranglerFile as He,readWranglerJsonc as $e,applyModify as Tr}from"@lunora/config/cloudflare";import{n as pe,r as Ar,c as Cr}from"../packem_shared/cloudflare-credentials-BVmZnDZk.mjs";import{d as jr}from"../packem_shared/command-BpMv2n0o.mjs";import{r as Ur}from"../packem_shared/deploy-target-resolve-BTCW1Iv4.mjs";import{EXIT_CODE as w}from"../packem_shared/EXIT_CODE-DQVhSE-1.mjs";import{c as oe,d as Nr,b as Lr,e as Dr,r as Pr}from"./handler.mjs";import{runSeedCommand as Fr}from"./handler14.mjs";const Be=r=>{if(!Number.isInteger(r)||r<=0)return!1;try{return process.kill(r,0),!0}catch(e){return e.code==="EPERM"}},ve=r=>Number(L(r,"utf8")),je=r=>{try{return ve(r)}catch{return}},Mr=(r,e)=>{const t=`${r}.retire-${String(e)}`;try{xe(r,t)}catch{return!1}try{return ve(t)!==e||Be(ve(t))?!1:(Ce(r).ino===Ce(t).ino&&kr(r),!0)}finally{F(t,{force:!0})}},Wr=(r,e={})=>{const t=ee(r,".lunora","preview.lock"),n=`${t}.${String(process.pid)}.${V()}`;$r(_r(t),{recursive:!0}),ne(n,String(process.pid));try{for(let o=0;o<3;o+=1){try{return xe(n,t),{release:()=>{je(t)===process.pid&&F(t,{force:!0})}}}catch(i){if(i.code!=="EEXIST")throw i}const s=je(t);if(s!==void 0){if(Be(s))return{error:`another preview command is running in this checkout (pid ${String(s)}); wait for it, or remove ${t} if it is not`};if(e.afterReadingOwner?.(),!Mr(t,s))return{error:`another preview command is taking over the lock at ${t}; run this again in a moment. If none is running, remove ${t}.retire-${String(s)}`}}}return{error:`could not take the preview lock ${t}`}}finally{F(n,{force:!0})}},xr=[["SIGINT",130],["SIGTERM",143]],Kr=5e3,H=new Set,Ge=r=>process.exit(r);let Ve=Ge,Z=[],he;const Hr=async r=>{const e=[...H].map(async n=>{try{await n()}catch{}});H.clear();const t=new Promise(n=>{setTimeout(n,Kr).unref()});await Promise.race([Promise.all(e),t]),Ve(r)},Br=r=>(he??=Hr(r),he),ie=(r,e)=>(H.add(r),Z.length===0&&(Z=xr.map(([t,n])=>{const o=()=>{Br(n).catch(()=>{})};return process.on(t,o),[t,o]})),()=>{if(H.delete(r),H.size===0){for(const[t,n]of Z)process.off(t,n);Z=[],Ve=Ge,he=void 0}}),Gr=/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu,ke=r=>{const e=Ke(r)?.lunora?.appId;return typeof e=="string"&&Gr.test(e)?e.toLowerCase():void 0},Vr=r=>{const e=Ke(r);if(e===void 0||e.lunoraIsForeign||e.lunora?.appId!==void 0)return;const t=V();return Or(e,"appId",t),ke(r)===t?t:void 0},se=63,Ee=new Set(["$schema","account_id","alias","assets","base_dir","build","cache","compatibility_date","compatibility_flags","dev","env","find_additional_modules","jsx_factory","jsx_fragment","keep_names","keep_vars","limits","logpush","main","migrations","minify","name","no_bundle","observability","placement","preview_urls","routes","rules","send_metrics","triggers","tsconfig","upload_source_maps","workers_dev"]),Ye=["ai","browser","define","images","media","secrets","vars","version_metadata","worker_loaders"],Yr=new Set(["env","name","routes","triggers","workers_dev"]),Jr=new Set(["tail_consumers"]),Y={d1_databases:"d1",kv_namespaces:"kv",r2_buckets:"r2"},R=r=>r==null?!1:Array.isArray(r)?r.length>0:typeof r!="object"||Object.keys(r).length>0,I=r=>(Array.isArray(r)?r:[]).filter(e=>typeof e=="object"&&e!==null),Je=(r,e)=>{if(!(Ee.has(r)||Jr.has(r)||Ye.includes(r)||r in Y)){if(r==="route")return`"route": write it as "routes" so the preview can clear it — a preview must never claim production's hostname`;if(r==="durable_objects"){const t=I(e.bindings).find(n=>n.script_name!==void 0);return t===void 0?void 0:`"durable_objects": the "${String(t.name)}" binding reaches another Worker's Durable Objects (script_name "${String(t.script_name)}"), which the preview would share`}if(r==="exports"){const t=Object.entries(e).find(([,n])=>n?.type==="workflow");return t===void 0?void 0:`"exports": workflow "${t[0]}" has an account-wide name, so the preview would take over production's workflow`}return`"${r}": a preview cannot isolate this binding yet, and copying it would point the preview at production's resource`}},Ue="LUNORA_ORIGIN_URL",U="LUNORA_PREVIEW",M=r=>`${r.production}/${r.slug}`,Xr=/[^a-z0-9]+/u,Xe=r=>{const e=r.toLowerCase().split(Xr).filter(t=>t!=="").join("-");return e===""||e===r?e:`${e}-${gr("sha256").update(r).digest("hex").slice(0,6)}`},ae=(r,e)=>oe(`${r}-preview-${e}`,se),be=(r,e)=>{const t=typeof r.name=="string"?r.name:"",n=Xe(e);return t===""?{error:`wrangler.jsonc has no "name", which the preview Worker's name is derived from`}:n===""?{error:`"${e}" has no letter or digit to name a preview by`}:{names:{environment:oe(`preview-${n}`,se),production:t,slug:n,worker:ae(t,n)}}},J=(r,e,t)=>{const n=t?.vars?.[U],o=typeof n=="string"?n.lastIndexOf("/"):-1;if(typeof n!="string"||o<=0)return!1;const s=n.slice(0,o),i=n.slice(o+1);return Xe(i)===i&&M({production:s,slug:i})===n&&e===oe(`preview-${i}`,se)&&t?.name===ae(s,i)},ce=(r,e)=>{const t=Object.entries(r.env??{}).filter(([i,a])=>!J(r,i,a)),n=t.find(([i])=>i===e)?.[1];if(n===void 0)return{error:`wrangler.jsonc declares no environment "${e}"${t.length===0?", and no environments at all":`; the environments are: ${t.map(([i])=>i).join(", ")}`}`};const o=typeof r.name=="string"?r.name:"";return{config:{...Object.fromEntries(Object.entries(r).filter(([i])=>Ee.has(i)||i==="exports")),...n,env:r.env,name:typeof n.name=="string"?n.name:`${o}-${e}`}}},zr=r=>Object.entries(r.env??{}).filter(([e,t])=>!J(r,e,t)).filter(([,e])=>typeof e.account_id=="string"&&e.account_id!==""&&e.account_id!==r.account_id).map(([e])=>e),ze=(r,e)=>oe(`${r}-${e}`,se),Ne=(r,e)=>{const t=I(r==="durable_objects"?e?.bindings:e);return new Set(t.map(n=>String(r==="durable_objects"?n.name:n.binding)))},Qr=r=>Object.entries(r.env??{}).flatMap(([e,t])=>J(r,e,t)?[]:Object.entries(t).flatMap(([n,o])=>{const s=r[n];if(n in Y||n==="durable_objects"){const i=Ne(n,s),a=[...Ne(n,o)].filter(c=>!i.has(c));return a.length===0?[]:[`"env.${e}.${n}": binding ${a.map(c=>`"${c}"`).join(", ")} is declared only in this environment, and a preview is planned from the top-level config, which lacks it; pass --env ${e} to preview that environment`]}return Je(n,o)!==void 0&&R(o)&&!R(s)?[`"env.${e}.${n}": declared only in this environment, and a preview is planned from the top-level config, which has none; pass --env ${e} to preview that environment`]:[]})),Qe=(r,e)=>Object.entries(Y).flatMap(([t,n])=>I(r[t]).map(o=>{const s=String(o.binding);return{binding:s,kind:n,name:ze(e,s)}})),Ze=(r,e,t)=>{const n=be(r,e);if(n.error!==void 0)return{error:n.error};const{environment:o,worker:s}=n.names;if(r.env?.[o]!==void 0&&!J(r,o,r.env[o]))return{error:`wrangler.jsonc already declares "env.${o}"; a preview writes that block itself, so name the preview differently`};const i=Object.entries(r).flatMap(([f,l])=>{const m=R(l)?Je(f,l):void 0;return m===void 0?[]:[m]});i.push(...t===void 0?Qr(r):[]);const a=I(r.r2_buckets).find(f=>f.jurisdiction!==void 0);if(a!==void 0&&i.push(`"r2_buckets": the "${String(a.binding)}" bucket has a jurisdiction, which a preview bucket is not created in yet`),i.length>0)return{error:`this app cannot be previewed in isolation yet:
2
+ - ${i.join(`
3
+ - `)}`};const c=Object.keys(Y).find(f=>I(r[f]).some(l=>typeof l.binding!="string"||l.binding===""));if(c!==void 0)return{error:`"${c}": every entry needs a non-empty "binding"`};const d=Qe(r,s),u=d.find((f,l)=>d.findIndex(m=>m.kind===f.kind&&m.name===f.name)!==l);return u!==void 0?{error:`two bindings would share the preview resource name "${u.name}"; rename one of them (binding names differ only by case or punctuation)`}:{plan:{...n.names,...t===void 0?{}:{sourceEnv:t},resources:d}}},_e=(r,e)=>`${r}:${e}`,le=(r,e)=>Object.fromEntries(Object.entries(r).filter(([t])=>t!==e)),Zr=(r,e,t,n)=>{const o=String(e.binding),s=t.resources.find(a=>a.kind===r&&a.binding===o),i=n.get(_e(r,o));if(s===void 0||i===void 0)throw new Error(`no preview ${r} resource for the "${o}" binding`);return r==="d1"?{...le(e,"preview_database_id"),database_id:i,database_name:s.name}:r==="kv"?{...le(e,"preview_id"),id:i}:{...le(e,"preview_bucket_name"),bucket_name:i}},qr=(r,e,t)=>{if(t.sourceEnv!==void 0)for(const[n,o]of Object.entries(r))Ee.has(n)&&!(n in e)&&!Yr.has(n)&&R(o)&&(e[n]=o)},qe=(r,e,t,n={},o)=>{const s=r,i={name:e.worker,routes:[],triggers:{crons:[]},workers_dev:!0},a={[U]:M(e)};for(const d of Ye)R(s[d])&&(i[d]=s[d]);const c=R(r.vars)?{...r.vars}:{};Ue in c&&(c[Ue]=o??e.worker),i.vars={...c,...n,...a},qr(s,i,e),R(r.durable_objects)&&(i.durable_objects=r.durable_objects),R(s.exports)&&(i.exports=s.exports);for(const[d,u]of Object.entries(Y)){const f=I(s[d]);f.length>0&&(i[d]=f.map(l=>Zr(u,l,e,t)))}return i},et={analytics_engine_datasets:["dataset"],d1_databases:["database_id","database_name","preview_database_id"],hyperdrive:["id"],kv_namespaces:["id","preview_id"],r2_buckets:["bucket_name","preview_bucket_name"],vectorize:["index_name"]},rt={d1_databases:"d1",kv_namespaces:"kv",r2_buckets:"r2"},er=(r,e)=>`${r}:${e}`,tt=r=>{const e=Object.entries(et).flatMap(([t,n])=>I(r[t]).flatMap(o=>n.map(s=>[rt[t]??t,o[s]])));return[["worker",r.name],...e].flatMap(([t,n])=>typeof n=="string"&&n!==""?[er(t,n)]:[])},nt=r=>new Set([r,...Object.entries(r.env??{}).flatMap(([e,t])=>J(r,e,t)?[]:[t])].flatMap(e=>tt(e))),Se=(r,e)=>[{kind:"worker",value:r},...e.flatMap(t=>[...t.id===void 0?[]:[{kind:t.kind,value:t.id}],{kind:t.kind,value:t.name}])],B=(r,e)=>{const t=nt(r);return e.filter(n=>t.has(er(n.kind,n.value))).map(n=>n.value)},fe="lunora-preview-registry",re=50,de=r=>{try{const{errors:e}=JSON.parse(r.text),t=(e??[]).flatMap(n=>typeof n.message=="string"?[n.message]:[]).join("; ");return t===""?`HTTP ${String(r.status)}`:`HTTP ${String(r.status)}: ${t}`}catch{return`HTTP ${String(r.status)}`}},k=(r,e)=>{if(!r.ok)throw new Error(`${e} failed (${de(r)})`);return r.body},X=r=>typeof r.result=="object"&&r.result!==null?r.result:{},rr=async(r,e,t,n)=>{const o=e.includes("?")?"&":"?";for(let s=1;s<=re;s+=1){const i=k(await r(`${e}${o}per_page=100&page=${String(s)}`),`listing ${t}`);if(!Array.isArray(i.result))throw new TypeError(`the listing of ${t} had no result list`);const a=i.result.find(d=>n(d)),c=typeof i.result_info=="object"&&i.result_info!==null?i.result_info:{};if(a!==void 0||typeof c.total_pages!="number"||s>=c.total_pages)return a}throw new Error(`the listing of ${t} has more than ${String(re)} pages`)},me=async(r,e)=>{const t=await rr(r,"/storage/kv/namespaces","KV namespaces",n=>n.title===e);return typeof t?.id=="string"?t.id:void 0},tr=async(r,e)=>{const{id:t}=X(k(await r("/storage/kv/namespaces",{body:JSON.stringify({title:e}),method:"POST"}),`creating KV namespace "${e}"`));if(typeof t!="string")throw new TypeError(`creating KV namespace "${e}" returned no id`);return t},Re=async(r,e)=>{const t=await me(r,fe);if(t!==void 0||!e)return t;try{return await tr(r,fe)}catch(n){const o=await me(r,fe);if(o===void 0)throw n;return o}},D=(r,e)=>`${r}/${e}`,Ie=(r,e)=>`/storage/kv/namespaces/${encodeURIComponent(r)}/values/${encodeURIComponent(e)}`,ot=new Set(["d1","kv","r2"]),it=(r,e)=>{const t=e;return typeof t=="object"&&t!==null&&ot.has(t.kind)&&typeof t.binding=="string"&&typeof t.id=="string"&&(t.pending===void 0||t.pending===!0)&&t.name===ze(r,t.binding)&&(t.kind!=="r2"||t.id===t.name)},st=r=>{const e=r;return typeof e=="object"&&e!==null&&typeof e.repository=="string"&&typeof e.pullRequest=="string"},at=r=>{const e=r;return typeof e=="object"&&e!==null&&e.version===1&&typeof e.worker=="string"&&typeof e.production=="string"&&(e.appId===void 0||typeof e.appId=="string")&&(e.sourceEnv===void 0||typeof e.sourceEnv=="string")&&(e.origin===void 0||st(e.origin))&&Array.isArray(e.resources)&&e.resources.every(t=>it(e.worker,t))},ge=async(r,e,t)=>{const n=await r(Ie(e,t));if(!n.ok&&n.status===404)return;const o=k(n,`reading the preview record "${t}"`);if(!at(o))throw new TypeError(`the preview record "${t}" is not one this CLI wrote; refusing to act on it`);return o},j=async(r,e,t)=>{k(await r(Ie(e,D(t.appId??t.production,t.name)),{body:JSON.stringify(t),method:"PUT"}),"writing the preview record")},nr=async(r,e,t)=>{k(await r(Ie(e,D(t.appId??t.production,t.name)),{method:"DELETE"}),"removing the preview record")},Le=async(r,e,t)=>{const n=`${t}/`,o=[];let s="";for(let a=1;;a+=1){if(a>re)throw new Error(`the preview records of "${t}" span more than ${String(re)} pages`);const c=`prefix=${encodeURIComponent(n)}${s===""?"":`&cursor=${encodeURIComponent(s)}`}`,d=k(await r(`/storage/kv/namespaces/${encodeURIComponent(e)}/keys?${c}`),"listing preview records");o.push(...(Array.isArray(d.result)?d.result:[]).flatMap(f=>typeof f.name=="string"?[f.name]:[]));const u=typeof d.result_info=="object"&&d.result_info!==null?d.result_info:{};if(typeof u.cursor!="string"||u.cursor==="")break;s=u.cursor}const i=await Promise.all(o.map(async a=>{try{return{key:a,record:await ge(r,e,a)}}catch(c){if(c instanceof TypeError)return{key:a,unreadable:!0};throw c}}));return{records:i.flatMap(a=>a.record===void 0?[]:[a.record]),unreadable:i.flatMap(a=>a.unreadable===!0?[a.key]:[])}},W=async(r,e,t)=>{if(e==="d1"){const o=await rr(r,`/d1/database?name=${encodeURIComponent(t)}`,"D1 databases",s=>s.name===t);return typeof o?.uuid=="string"?o.uuid:void 0}if(e==="kv")return me(r,t);const n=await r(`/r2/buckets/${encodeURIComponent(t)}`);if(!(!n.ok&&n.status===404))return k(n,`looking up R2 bucket "${t}"`),t},or=async(r,e,t)=>{if(e==="kv")return tr(r,t);if(e==="r2")return k(await r("/r2/buckets",{body:JSON.stringify({name:t}),method:"POST"}),`creating R2 bucket "${t}"`),t;const{uuid:n}=X(k(await r("/d1/database",{body:JSON.stringify({name:t}),method:"POST"}),`creating D1 database "${t}"`));if(typeof n!="string")throw new TypeError(`creating D1 database "${t}" returned no id`);return n},q="lunora-preview-locks",G=1800,ct=/UNIQUE constraint failed|SQLITE_CONSTRAINT/iu,dt="CREATE TABLE IF NOT EXISTS lunora_preview_locks (app_id TEXT NOT NULL, name TEXT NOT NULL, owner_token TEXT NOT NULL, expires_at INTEGER NOT NULL, PRIMARY KEY (app_id, name))",ut="INSERT INTO lunora_preview_locks (app_id, name, owner_token, expires_at) VALUES (?, ?, ?, unixepoch() + ?)",lt="SELECT owner_token, expires_at, unixepoch() AS now FROM lunora_preview_locks WHERE app_id = ? AND name = ?",ft="UPDATE lunora_preview_locks SET owner_token = ?, expires_at = unixepoch() + ? WHERE app_id = ? AND name = ? AND owner_token = ? AND expires_at <= unixepoch()",wt="DELETE FROM lunora_preview_locks WHERE app_id = ? AND name = ? AND owner_token = ?",E=async(r,e,t,n)=>{const o=await r(`/d1/database/${encodeURIComponent(e)}/query`,{body:JSON.stringify({params:n,sql:t}),method:"POST"});if(!o.ok&&ct.test(o.text))return;const s=k(o,"using the preview lock database").result?.[0];return{changes:typeof s?.meta?.changes=="number"?s.meta.changes:0,rows:Array.isArray(s?.results)?s.results:[]}},pt=4,vt=50,ht=async r=>new Promise(e=>{setTimeout(e,r)}),z="lunora_preview_lock_owner",ir="lunora-preview-locks/v1",mt=`CREATE TABLE IF NOT EXISTS ${z} (marker TEXT NOT NULL)`,gt=`INSERT INTO ${z} (marker) VALUES (?)`,yt="SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?",$t=`SELECT marker FROM ${z}`,De=async(r,e)=>((await E(r,e,yt,[z]))?.rows.length??0)===0?!1:(await E(r,e,$t,[]))?.rows.some(o=>o.marker===ir)===!0,sr=async r=>{let e=await W(r,"d1",q),t=!1;if(e===void 0)try{e=await or(r,"d1",q),t=!0}catch(n){if(e=await W(r,"d1",q),e===void 0)throw n}if(t)await E(r,e,mt,[]),await E(r,e,gt,[ir]);else{let n=await De(r,e);for(let o=1;o<=pt&&!n;o+=1)await ht(vt*o),n=await De(r,e);if(!n)throw new Error(`a D1 database named "${q}" exists but was not made by lunora preview (it has no ${z} marker), so it is not used or written to. Rename it, or delete it if it is an empty leftover, then run this again`)}return await E(r,e,dt,[]),e},ar=async(r,e,t,n)=>{const o=V();for(let s=0;s<2;s+=1){if(await E(r,e,ut,[t,n,o,G])!==void 0)return{token:o};const a=(await E(r,e,lt,[t,n]))?.rows[0];if(a===void 0)continue;const c=Number(a.expires_at),d=Number.isFinite(c)&&c<=Number(a.now);return typeof a.owner_token!="string"||!d?{held:new Date(c*1e3).toISOString()}:(await E(r,e,ft,[o,G,t,n,a.owner_token]))?.changes===1?{token:o}:{held:"just now"}}return{held:"just now"}},cr="UPDATE lunora_preview_locks SET expires_at = unixepoch() + ? WHERE app_id = ? AND name = ? AND owner_token = ?",dr=(r,e,t,n,o,s,i=G*1e3/3)=>{let a=Date.now();const c=async()=>{try{(await E(r,e,cr,[G,t,n,o]))?.changes===1?a=Date.now():s()}catch{Date.now()-a>=2*i&&s()}},d=setInterval(()=>{c().catch(()=>{})},i);return d.unref(),()=>{clearInterval(d)}},ur=async(r,e,t,n,o)=>(await E(r,e,cr,[G,t,n,o]))?.changes===1,te=async(r,e,t,n,o)=>{try{await E(r,e,wt,[t,n,o])}catch{}},lr={d1:r=>`/d1/database/${encodeURIComponent(r)}`,kv:r=>`/storage/kv/namespaces/${encodeURIComponent(r)}`,r2:r=>`/r2/buckets/${encodeURIComponent(r)}`},Oe=async(r,e)=>{if(e.pending===!0)return"present";const t=await r(lr[e.kind](e.id));if(!t.ok&&t.status===404)return"missing";const n=X(k(t,`looking up ${e.kind} "${e.name}"`));return{d1:n.name,kv:n.title,r2:n.name}[e.kind]===e.name?"present":"changed"},Pe=10,kt=(r,e)=>{const t=`/r2/buckets/${encodeURIComponent(r)}/objects/`,n=`${t}${e.split("/").map(o=>encodeURIComponent(o)).join("/")}`;return e.split("/").some(o=>o==="."||o==="..")?{error:`the object key ${JSON.stringify(e)} has a "." or ".." segment, which cannot be addressed without leaving the bucket`}:new URL(`https://api.invalid/accounts/a${n}`).pathname.startsWith(`/accounts/a${t}`)?{path:n}:{error:`the object key ${JSON.stringify(e)} resolves outside bucket "${r}"`}},Et=async(r,e,t)=>{const n=kt(e,t);if(n.error!==void 0)throw new Error(`${n.error}; remove the object by hand, then delete the preview again`);const o=await r(n.path,{method:"DELETE"});if(!o.ok&&o.status!==404)throw new Error(`deleting object "${t}" failed (${de(o)})`)},bt=async(r,e)=>{let t="";for(;;){const n=await r(`/r2/buckets/${encodeURIComponent(e)}/objects?per_page=1000`);if(!n.ok&&n.status===404)return;const o=k(n,`listing the objects of R2 bucket "${e}"`),s=(Array.isArray(o.result)?o.result:[]).flatMap(a=>typeof a.key=="string"?[a.key]:[]);if(s.length===0)return;const i=`${String(s.length)}:${s[0]??""}:${s.at(-1)??""}`;if(i===t)throw new Error(`R2 bucket "${e}" still holds the same ${String(s.length)} objects after deleting them`);t=i;for(let a=0;a<s.length;a+=Pe)await Promise.all(s.slice(a,a+Pe).map(async c=>Et(r,e,c)))}},fr=async(r,e)=>{e.kind==="r2"&&await bt(r,e.id);const t=await r(lr[e.kind](e.id),{method:"DELETE"});if(!(t.ok||t.status===404))throw new Error(de(t))},_t=async(r,e)=>{const t=await r(`/workers/scripts/${encodeURIComponent(e)}?force=true`,{method:"DELETE"});if(!t.ok&&t.status!==404)throw new Error(de(t))},ue=async(r,e,t)=>{const n=await r(`/workers/scripts/${encodeURIComponent(e)}/settings`);if(!n.ok&&n.status===404)return{exists:!1};const{bindings:o}=X(k(n,`reading Worker "${e}"`)),s=(Array.isArray(o)?o:[]).find(i=>i.type==="plain_text"&&i.name===t)?.text;return typeof s=="string"?{exists:!0,marker:s}:{exists:!0}},St=async r=>{const{subdomain:e}=X(k(await r("/workers/subdomain"),"reading the workers.dev subdomain"));if(typeof e!="string"||e==="")throw new TypeError("the account has no workers.dev subdomain; register one in the Cloudflare dashboard (Workers & Pages) first");return e},Fe=["deploy","list","delete"],Rt=15e3,It=5,Ot=1e3,we="LUNORA_ADMIN_TOKEN",Tt="LUNORA_PREVIEW_SECRET_SEED",At={celld:"celld has no isolated previews: it has no Wrangler environments, and an app's Durable Objects and storage live in its fleet bucket. Deploy the copy as its own config, with CELLD_BUCKET naming a bucket of its own, and delete that bucket to remove it.",node:"the Node target has no `lunora deploy`, so there is nothing to preview: run a second process with its own database for a copy."},p=(r,e,t=w.USAGE)=>(r.error(e),{code:t,error:e}),C=r=>({environment:r.environment,name:r.name,resources:r.resources,url:r.url,worker:r.worker}),Ct=async(r,e)=>{if(r===void 0)return e();r.begin();try{return await e()}finally{r.end()}},wr=(r,e)=>{const t=pe(r.GITHUB_REPOSITORY)??pe(r.CI_PROJECT_PATH);return t===void 0?void 0:{pullRequest:e,repository:t}},jt=(r,e)=>e!==void 0&&r.origin?.repository===e.repository&&r.origin.pullRequest===e.pullRequest,Ut=r=>`the record for preview "${r}" was not made by a deploy of this pull request in this repository, so the identity the pull request's files name cannot be used to delete it; nothing was deleted`,Nt=(r,e)=>{const t=Se(e.worker,e.resources);return[...B(r.config,t),...r.alsoProduction===void 0?[]:B(r.alsoProduction,t)]},Lt=(r,e,t)=>{Object.assign(r,{origin:wr(e.environment??process.env,t)??r.origin})},Dt=r=>{const e=r.cwd??process.cwd(),t=Ur(e,r.target);if(t.target===void 0)return{error:t.error??"unknown deploy target"};if(t.target!=="cloudflare")return{error:`lunora preview: ${At[t.target]??`target "${t.target}" has no isolated previews.`}`};const n=He(e),o=n===void 0?void 0:$e(n).parsed;return n===void 0||o===void 0?{error:"lunora preview needs a readable wrangler.jsonc (or wrangler.json) in the project root"}:{context:{config:o,cwd:e,appId:ke(e),wranglerPath:n}}},pr=(r,e)=>{if(e.env!==void 0)return ce(r,e.env);const t=zr(r);return t.length>0&&pe((e.environment??process.env).CLOUDFLARE_ACCOUNT_ID)===void 0?{error:`environment(s) ${t.join(", ")} name an account_id other than the top level's, so the account to look in is not clear: pass --env <name> to use that environment's account, or set CLOUDFLARE_ACCOUNT_ID`}:{config:r}},Te=(r,e)=>{const{accountId:t,token:n}=Ar(r.environment??process.env,e.account_id);if(t===void 0||n===void 0)return{error:"lunora preview needs CLOUDFLARE_API_TOKEN (Workers Scripts, D1, Workers KV Storage and Workers R2 Storage: Edit) and CLOUDFLARE_ACCOUNT_ID (or `account_id` in wrangler.jsonc)"};const o=r.sleep??(async s=>new Promise(i=>{setTimeout(i,s)}));return{request:async(s,i)=>{for(let a=0;;a+=1){const c=await Cr({accountId:t,apiToken:n,...r.fetch===void 0?{}:{fetch:r.fetch},init:{...i,signal:AbortSignal.timeout(Rt)},path:s});if(c.ok||c.status!==429||a===It)return c;await o(Ot*2**a)}}}},Pt=r=>{const e={};for(const t of r){const n=t.indexOf("="),o=n===-1?"":t.slice(0,n);if(o==="")return{error:`--var ${t}: expected KEY=VALUE`};if(o===U)return{error:`--var ${o}: the preview sets ${o} itself; \`delete\` relies on it`};e[o]=t.slice(n+1)}return{variables:e}},$=r=>r instanceof Error?r.message:String(r),Ft=async(r,e,t,n)=>{const o=n.environment??process.env,s={},i=o[Tt],a=h=>i===void 0||i===""?Ir():yr("sha256",i).update(`${t}/${h}`).digest("hex");for(const h of n.secrets??[]){const y=o[h];if(y===void 0||y==="")return{error:`--secret ${h}: ${h} is not set in the environment, so there is no value to give the preview`};s[h]=y}const{fromLocal:c,fromPackages:d,mintableKeys:u}=await Dr(r,void 0);for(const h of[...d,...c,we])s[h]===void 0&&(u.has(h)||h===we)&&(s[h]=a(h));const f=[...new Set([...d,...c])].filter(h=>s[h]===void 0),m=(Array.isArray(e.secrets?.required)?e.secrets.required.filter(h=>typeof h=="string"):[]).filter(h=>s[h]===void 0);return m.length>0?{error:`the config requires ${m.join(", ")}, which a preview only gets when you pass ${m.map(h=>`--secret ${h}`).join(" ")}`}:{adminToken:s[we]??"",missing:f,values:s}},Mt=async(r,e,t,n)=>{const o=await Oe(r,t);if(o!=="present")throw new Error(`the record lists ${t.kind} "${t.name}" (${t.id}), which is ${o==="missing"?"gone":"now a different resource"}; run \`lunora preview delete ${e.slug}\`, then deploy again`);return n.info(`reusing preview ${t.kind} "${t.name}" for ${t.binding}`),t.id},Wt=3,xt=async(r,e,t,n)=>{let o;for(let s=1;s<=Wt;s+=1)try{await j(r,e,t);return}catch(i){o=i}try{await fr(r,n),t.resources.splice(t.resources.indexOf(n),1),await j(r,e,t).catch(()=>{})}catch{n.pending=!0}throw new Error(`${$(o)}; the ${n.kind} "${n.name}" just made could not be recorded, so it was removed again`)},Me=async(r,e,t,n,o)=>{let s=t.resources.find(i=>i.kind===n.kind&&i.binding===n.binding);if(s===void 0){if(await W(r,n.kind,n.name)!==void 0)throw new Error(`a ${n.kind} resource named "${n.name}" already exists but no preview record says this preview created it; refusing to bind or later delete it. Rename or remove it, then deploy again.`);s={binding:n.binding,id:n.kind==="r2"?n.name:"",kind:n.kind,name:n.name,pending:!0},t.resources.push(s),await j(r,e,t)}return s.id=await or(r,n.kind,n.name),delete s.pending,await xt(r,e,t,s),o.success(`created preview ${n.kind} "${n.name}" for ${n.binding}`),s.id},Kt=async(r,e,t,n,o,s,i)=>{const a=n.resources.find(c=>c.kind===o.kind&&c.binding===o.binding);if(i(),a?.pending===!0){if(await W(r,o.kind,o.name)!==void 0)throw new Error(`a ${o.kind} resource named "${o.name}" exists, but the record only claims it (a deploy was interrupted between creating it and confirming it), so nothing shows it is this preview's and it is left alone. If it is, delete it by hand, then deploy again`);return Me(r,e,n,o,s)}return a===void 0?Me(r,e,n,o,s):Mt(r,t,a,s)},Ht=async(r,e,t,n,o,s)=>{const i=new Map;for(const a of t.resources)i.set(_e(a.kind,a.binding),await Kt(r,e,t,n,a,o,s));return i},Ae=async(r,e,t)=>{const n=new Set((t?.resources??[]).map(i=>`${i.kind}:${i.name}`)),o=e.filter(i=>!n.has(`${i.kind}:${i.name}`));return(await Promise.all(o.map(async i=>await W(r,i.kind,i.name)===void 0?[]:[i]))).flat().map(i=>`${i.kind} "${i.name}"`)},vr=async(r,e,t,n,o,s,i=!0)=>{if(t!==void 0){const d=await ge(r,e,D(t,o));if(d!==void 0){if(d.appId!==t||d.name!==o)throw new Error(`the record at "${D(t,o)}" does not name this project and preview; refusing to act on it`);return d}}const a=await ge(r,e,D(n,o));if(a===void 0)return;if(a.appId!==void 0||a.production!==n||a.name!==o||a.worker!==ae(n,o))throw new Error(`the record at "${D(n,o)}" is not the one this CLI wrote for that Worker and preview; refusing to act on it`);if(t===void 0)throw new Error(`preview "${o}" is recorded under the Worker name, from before projects had an id. Add an app id to package.json (\`"lunora": { "appId": "${V()}" }\`), commit it, and run this again: it re-keys the record`);const c={...a,appId:t};return i&&(await j(r,e,c),await nr(r,e,a),s.warn(`preview "${o}" was recorded under the Worker name "${n}"; it is now recorded under project ${t}`)),c},Bt=async(r,e,t,n)=>{if(t===void 0&&n)return{code:w.USAGE,error:`a Worker named "${e.worker}" exists but no preview record says this preview deployed it; refusing to deploy over it`};if(t!==void 0&&t.worker!==e.worker)return{code:w.USAGE,error:`the record for preview "${e.slug}" names Worker "${t.worker}", not "${e.worker}" (the app was renamed since it was deployed); run \`lunora preview delete ${e.slug}\` first, then deploy it again`};const o=await Ae(r,e.resources,t);return o.length===0?void 0:{code:w.FAILURE,error:`${o.join(", ")} already exist(s) but no preview record read says this preview created it, so nothing was written or deployed. If a deploy of this preview just ran, its record may not have reached this location yet: run the deploy again. Otherwise rename or remove it, then deploy again.`}},Gt=r=>{const e=Er(ee(br(),"lunora-preview-")),t=ee(e,"secrets.json");return ne(t,JSON.stringify(r),{encoding:"utf8",mode:384}),{directory:e,path:t}},Vt=r=>({environment:r.environment,name:r.slug,resources:r.resources,worker:r.worker}),Yt=(r,e,t)=>{r.info(`dry run: preview "${e.slug}" would deploy Worker "${e.worker}" (env.${e.environment}, its own Durable Object namespace)`);for(const s of e.resources)r.info(` ${s.kind} "${s.name}" for ${s.binding} (created, or reused when this preview's record lists it)`);const{vars:n}=t,o=n===void 0?t:{...t,vars:Object.fromEntries(Object.keys(n).map(s=>[s,"<redacted>"]))};r.info(` env.${e.environment}: ${JSON.stringify(o)}`)},hr=(r,e)=>`another run is deploying or deleting preview "${r}" (its hold lapses at ${e}); wait for it. A run that crashed lets go by itself`,mr=(r,e,t)=>{const n=`the hold on preview "${e}" was lost while this run worked, so another run may have changed it too; check it with \`lunora preview list\` and run \`lunora preview delete ${e}\` if it looks wrong`;return r.error(n),{...t,code:t.code===w.SUCCESS?w.FAILURE:t.code,error:n}},Jt=async(r,e,t)=>{try{const n=await ue(r,e,U);return n.exists&&n.marker===t?"present":"absent"}catch{return"unknown"}},ye=(r,e)=>{if(r.lost)throw new Error(`the hold on preview "${e}" can no longer be vouched for, so this run stopped before changing anything more; check it with \`lunora preview list\`, then run again`)},Xt=async(r,e,t,n,o,s)=>{const{config:i,cwd:a,wranglerPath:c}=r,{logger:d}=n,{appId:u,hold:f,namespace:l,secrets:m,subdomain:h}=s;let y,_;const v=`https://${e.worker}.${h}.workers.dev`;try{const g=await ue(o,e.worker,U);if(g.exists&&g.marker!==M(e))return p(d,`a Worker named "${e.worker}" already exists and was not deployed as preview "${e.slug}"; refusing to deploy over it`);const b=new Date().toISOString(),T=await vr(o,l,u,e.production,e.slug,d),A=await Bt(o,e,T,g.exists);if(A!==void 0)return p(d,A.error,A.code);const N=B(r.committed??i,Se(e.worker,T?.resources??[]));if(N.length>0)return p(d,`preview "${e.slug}" would bind production's ${N.join(", ")}; refusing to deploy, nothing was created`);y=T??{createdAt:b,environment:e.environment,name:e.slug,production:e.production,appId:u,...e.sourceEnv===void 0?{}:{sourceEnv:e.sourceEnv},resources:[],updatedAt:b,version:1,worker:e.worker},Lt(y,n,e.slug),await f.verify(),await j(o,l,y),_=await Ht(o,l,e,y,d,()=>{ye(f,e.slug)})}catch(g){return p(d,`preview "${e.slug}": ${$(g)}`,w.FAILURE)}const O=B(r.committed??i,[..._].map(([g,b])=>({kind:g.slice(0,g.indexOf(":")),value:b})));if(O.length>0)return p(d,`preview "${e.slug}" would bind production's ${O.join(", ")}; refusing to deploy`);const x=L(c,"utf8");ne(c,Tr(x,["env",e.environment],qe(i,e,_,t,v)),"utf8");const S=Gt(m.values),K=ie(()=>{F(S.directory,{force:!0,recursive:!0})});try{ye(f,e.slug);const g=await Ct(r.baseline,async()=>Pr({allowSchemaDrift:!0,cwd:a,env:e.environment,fetchImpl:n.adminFetch,format:n.format,healthCheck:!0,healthFetch:n.healthFetch,healthSleep:n.healthSleep,interactive:!1,isolatedPreview:!0,logger:d,migrate:!0,migrateToken:m.adminToken,migrateUrl:v,migrateYes:!0,secretsFile:S.path,spawner:n.spawner,target:"cloudflare"})),b=g.code===0?"present":await Jt(o,e.worker,M(e));if(b==="present"?y.url=v:b==="absent"&&delete y.url,y.updatedAt=new Date().toISOString(),await f.verify(),await j(o,l,y),g.code!==0)return{code:g.code,data:{preview:C(y)},error:g.error??`preview "${e.slug}" did not deploy`}}catch(g){return p(d,`preview "${e.slug}": ${$(g)}`,w.FAILURE)}finally{F(S.directory,{force:!0,recursive:!0}),K()}if(n.seed===!0){const g=await Fr({cwd:a,fetchImpl:n.adminFetch,format:n.format,logger:d,prod:!0,token:m.adminToken,url:y.url,yes:!0});if(g.code!==0)return{code:g.code,data:{preview:C(y)},error:g.error??`seeding preview "${e.slug}" failed`}}return d.success(`preview "${e.slug}" is live at ${y.url??v} — remove it with \`lunora preview delete ${e.slug}\``),{code:w.SUCCESS,data:{preview:C(y)}}},zt=async(r,e,t,n,o)=>{const{appId:s,config:i,cwd:a}=r,{logger:c}=n;if(s===void 0)return p(c,"the project has no id to key the preview record by");const d=await Ft(a,i,e.worker,n);if(d.error!==void 0)return p(c,d.error);for(const v of d.missing)c.warn(`the preview has no ${v}: production's is never copied. Pass --secret ${v} with ${v} set in the environment to give it one.`);let u,f,l,m;try{f=await St(o),u=await Re(o,!0)??"",l=await sr(o);const v=await ar(o,l,s,e.slug);if(v.held!==void 0)return p(c,hr(e.slug,v.held));({token:m}=v)}catch(v){return p(c,`preview "${e.slug}": ${$(v)}`,w.FAILURE)}const h={lost:!1,verify:async()=>{if(!await ur(o,l,s,e.slug,m))throw h.lost=!0,new Error(`the hold on preview "${e.slug}" is no longer this run's, so its record was left as the other run has it`)}},y=dr(o,l,s,e.slug,m,()=>{h.lost=!0}),_=ie(async()=>{y(),await te(o,l,s,e.slug,m)});try{const v=await Xt(r,e,t,n,o,{appId:s,hold:h,namespace:u,secrets:d,subdomain:f});return h.lost?mr(c,e.slug,v):v}finally{y(),await te(o,l,s,e.slug,m),_()}},Qt=(r,e)=>{if(r.appId!==void 0)return{appId:r.appId};const t=e.environment??process.env,n='package.json has a "lunora.appId" that is not a UUID, or no `lunora` object this CLI can add one to';if(e.dryRun===!0)return e.logger.info(" app id: none yet; the first deploy writes one to package.json for you to commit"),{appId:void 0};if(t.CI!==void 0&&t.CI!==""&&t.CI!=="false")return{error:`package.json has no "lunora.appId", and a CI run cannot mint one (its checkout is discarded, so the preview could never be found again to delete). Commit \`"lunora": { "appId": "${V()}" }\` to package.json`};const o=Vr(r.cwd);return o===void 0?{error:n}:(e.logger.warn(`wrote an app id to package.json ("lunora.appId"); commit it so CI finds this project's previews`),{appId:o})},Zt=async(r,e,t)=>{const{cwd:n}=r,{logger:o}=e,s=Pt(e.vars??[]);if(s.error!==void 0)return p(o,s.error);const{variables:i}=s,a=Wr(n);if(a.error!==void 0)return p(o,a.error);const c=Qt(r,e);if(c.error!==void 0)return a.release(),p(o,c.error);let d=()=>{};const u=ee(n,"lunora",Sr);let f;try{f=Q(u)?L(u):void 0}catch(v){return a.release(),p(o,`could not read ${u}: ${$(v)}`)}let l=!1,m;const h={begin:()=>{l=!0},end:()=>{m=Q(u)?L(u):void 0,l=!1}},y=()=>{try{if(d(),f===void 0){const v=Q(u)?L(u):void 0;v!==void 0&&(l||m!==void 0&&v.equals(m))&&F(u,{force:!0})}else f.equals(Q(u)?L(u):Buffer.alloc(0))||ne(u,f)}finally{a.release()}},_=ie(y);try{d=Nr(n),await Lr(n,o,void 0,"cloudflare",void 0);const{services:v}=Rr(n);if(v.length>0)return p(o,`this app cannot be previewed in isolation yet: it declares lunora.config services (${v.map(A=>A.name).join(", ")}), which a preview would share with production`);const O=$e(r.wranglerPath).parsed??r.config,x=e.env===void 0?{config:O}:ce(O,e.env);if(x.error!==void 0)return p(o,x.error);const{config:S}=x,K=Ze(S,t,e.env);if(K.error!==void 0)return p(o,K.error);const{plan:g}=K,b=B(O,Se(g.worker,g.resources));if(b.length>0)return p(o,`preview "${g.slug}" names collide with production's ${b.join(", ")}; name the preview differently`);if(e.dryRun===!0){const A=new Map(g.resources.map(N=>[_e(N.kind,N.binding),`<${N.name}>`]));return Yt(o,g,qe(S,g,A,i,`https://${g.worker}.<your-subdomain>.workers.dev`)),o.info(` secrets: every one Lunora can mint, fresh${(e.secrets??[]).length>0?`; from the environment: ${(e.secrets??[]).join(", ")}`:""}`),{code:w.SUCCESS,data:{plan:Vt(g)}}}const T=Te(e,S);return T.error!==void 0?p(o,T.error,w.AUTH):await zt({...r,baseline:h,committed:O,config:S,appId:c.appId},g,i,e,T.request)}finally{y(),_()}},qt=async(r,e,t)=>{try{if(e.pending===!0)return await W(r,e.kind,e.name)===void 0?!0:(t.error(`${e.kind} "${e.name}" exists, but the record only claims it (a deploy was interrupted before confirming it), so nothing shows it is this preview's: it was left alone. If it is, delete it by hand, then run \`lunora preview delete\` again`),!1);const n=await Oe(r,e);return n==="changed"?(t.error(`${e.kind} "${e.name}" (${e.id}): the recorded id now names a different resource, so it was left alone`),!1):(n==="present"&&(await fr(r,e),t.success(`deleted ${e.kind} "${e.name}"`)),!0)}catch(n){return t.error(`deleting ${e.kind} "${e.name}" failed (${$(n)}); it stays on record for the next \`lunora preview delete\``),!1}},en=async(r,e,t,n,o,s,i)=>{try{s();const u=await ue(r,t.worker,U);if(u.exists&&u.marker!==M({production:t.production,slug:t.name}))return p(o,`Worker "${t.worker}" was not deployed as preview "${t.name}"; refusing to delete anything`);u.exists&&(await _t(r,t.worker),o.success(`deleted Worker "${t.worker}"`))}catch(u){return p(o,`deleting Worker "${t.worker}" failed (${$(u)}); its resources were left in place`,w.FAILURE)}const a=[];for(const u of t.resources)s(),await qt(r,u,o)||a.push(u);const c={...t,resources:a,updatedAt:new Date().toISOString()};let d;try{d=await Ae(r,n?.resources??[],t),d.length===0&&(await i(),await(a.length===0?nr(r,e,t):j(r,e,c)))}catch(u){return p(o,`preview "${t.name}": ${$(u)}`,w.FAILURE)}return d.length>0?p(o,`${d.join(", ")} exist(s) under this preview's names but not in the record read (a deploy may have just recorded it); the record was left as it is — run \`lunora preview delete ${t.name}\` again. If that keeps failing, the resource was never recorded (a deploy stopped between creating and recording it): delete it by hand, then run delete once more`,w.FAILURE):a.length>0?{code:w.FAILURE,data:{preview:C(c)},error:`${String(a.length)} preview resource(s) could not be deleted`}:{code:w.SUCCESS,data:{deleted:C(t)}}},rn=async(r,e,t)=>{const n=[{config:e}];for(const s of Object.keys(e.env??{})){const i=ce(e,s);i.config!==void 0&&n.push({config:i.config,env:s})}const o=await Promise.all(n.map(async s=>{const{names:i}=be(s.config,t);if(i===void 0)return[];const a=Qe(s.config,i.worker),c=await ue(r,i.worker,U),d=await Ae(r,a,void 0);return[...c.exists&&c.marker===M(i)?[`Worker "${i.worker}" exists`]:[],...d.map(u=>`${u} exists`)]}));return[...new Set(o.flat())]},tn=(r,e)=>{const t=e.sourceEnv===void 0?{config:r}:ce(r,e.sourceEnv);return t.config===void 0?void 0:Ze({...t.config,name:e.production},e.name,e.sourceEnv).plan},nn=async(r,e,t,n)=>{const o=await rn(r,e,t);return o.length===0?void 0:p(n,`no record of preview "${t}" could be read, but ${o.join(" and ")}; nothing was deleted. If a deploy just ran, its record may not have reached this location yet: run delete again. Otherwise delete from a checkout whose package.json has the lunora.appId that deployed it`,w.FAILURE)},on=(r,e)=>{e.info(`dry run: would delete Worker "${r.worker}" and its Durable Objects`);for(const t of r.resources)e.info(` ${t.kind} "${t.name}" (${t.binding})`);return{code:w.SUCCESS,data:{plan:C(r)}}},sn=(r,e,t)=>e.worker===ae(e.production,e.name)&&e.appId===r.appId&&e.name===t,We=async(r,e,{hold:t,names:n,namespace:o,request:s})=>{const{config:i}=r,{logger:a}=e;let c;try{if(c=o===void 0?void 0:await vr(s,o,r.appId,n.production,n.slug,a,e.dryRun!==!0),o===void 0||c===void 0){const l=await nn(s,i,n.slug,a);if(l!==void 0)return l}}catch(l){return p(a,`preview "${n.slug}": ${$(l)}`,w.FAILURE)}if(o===void 0||c===void 0)return p(a,`no preview "${n.slug}" of "${n.production}" is on record; nothing was deleted`,w.NOT_FOUND);const d=Nt(r,c);if(!sn(r,c,n.slug)||d.length>0)return p(a,`the record for preview "${n.slug}" names ${d.length>0?`production's ${d.join(", ")}`:`Worker "${c.worker}", which is not the Worker of this preview`}; refusing to delete anything`);if(r.requireOrigin===!0&&!jt(c,wr(e.environment??process.env,n.slug)))return p(a,Ut(n.slug),w.FAILURE);let u;try{u=await Promise.all(c.resources.map(async l=>Oe(s,l)))}catch(l){return p(a,`preview "${n.slug}": ${$(l)}`,w.FAILURE)}const f=c.resources.filter((l,m)=>u[m]==="changed");return f.length>0?p(a,`the record for preview "${n.slug}" lists ${f.map(l=>`${l.kind} ${l.id}`).join(", ")}, which no longer name(s) the recorded resource; refusing to delete anything`):e.dryRun===!0?on(c,a):en(s,o,c,tn(i,c),a,()=>{ye(t,c.name)},t.verify)},P=async(r,e,t)=>{const{config:n}=r,{logger:o}=e,s=be(n,t);if(s.error!==void 0)return p(o,s.error);const{names:i}=s,a=pr(n,e);if(a.error!==void 0)return p(o,a.error,e.env===void 0?w.AUTH:w.USAGE);const c=Te(e,a.config);if(c.error!==void 0)return p(o,c.error,w.AUTH);const{request:d}=c;let u;try{u=await Re(d,!1)}catch(v){return p(o,`preview "${i.slug}": ${$(v)}`,w.FAILURE)}if(r.appId===void 0||u===void 0||e.dryRun===!0)return We(r,e,{hold:{lost:!1,verify:()=>Promise.resolve()},names:i,namespace:u,request:d});const{appId:f}=r;let l,m;try{l=await sr(d);const v=await ar(d,l,f,i.slug);if(v.held!==void 0)return p(o,hr(i.slug,v.held));({token:m}=v)}catch(v){return p(o,`preview "${i.slug}": ${$(v)}`,w.FAILURE)}const h={lost:!1,verify:async()=>{if(!await ur(d,l,f,i.slug,m))throw h.lost=!0,new Error(`the hold on preview "${i.slug}" is no longer this run's, so its record was left as the other run has it`)}},y=dr(d,l,f,i.slug,m,()=>{h.lost=!0}),_=ie(async()=>{y(),await te(d,l,f,i.slug,m)});try{const v=await We(r,e,{hold:h,names:i,namespace:u,request:d});return h.lost?mr(o,i.slug,v):v}catch(v){return p(o,`preview "${i.slug}": ${$(v)}`,w.FAILURE)}finally{y(),await te(d,l,f,i.slug,m),_()}},an=async(r,e)=>{const{config:t}=r,{logger:n}=e,o=typeof t.name=="string"?t.name:"",s=pr(t,e);if(s.error!==void 0)return p(n,s.error,e.env===void 0?w.AUTH:w.USAGE);const i=Te(e,s.config);if(i.error!==void 0)return p(n,i.error,w.AUTH);let a;try{const c=await Re(i.request,!1),d={records:[],unreadable:[]},u=c===void 0||r.appId===void 0?d:await Le(i.request,c,r.appId),f=c===void 0?d:await Le(i.request,c,o);a=[...u.records,...f.records],f.records.length>0&&n.warn(`${String(f.records.length)} preview(s) are recorded under the Worker name, from before projects had an id: ${f.records.map(l=>l.name).join(", ")}. ${r.appId===void 0?"Add an app id to package.json, then run":"Run"} \`lunora preview delete <name>\` (or deploy it again) to re-key each`);for(const l of[...u.unreadable,...f.unreadable])n.warn(`the registry key "${l}" is not a preview record this CLI wrote; it is not listed, and \`delete\` will refuse it`)}catch(c){return p(n,$(c),w.FAILURE)}a.length===0&&n.info(`no previews of "${o}" are on record`);for(const c of a)n.info(`${c.name} ${c.url??"(not deployed)"} Worker ${c.worker}, ${String(c.resources.length)} resource(s), updated ${c.updatedAt}`);return{code:w.SUCCESS,data:{previews:a.map(c=>C(c))}}},cn=/^[\dA-Za-z][\w-]{0,62}$/u,dn=r=>{const e=ke(r);if(e===void 0)return{error:'its package.json has no readable "lunora.appId"'};const t=He(r);let n;try{n=t===void 0?void 0:$e(t).parsed}catch{n=void 0}const o=n?.name;return n===void 0||typeof o!="string"||!cn.test(o)?{error:"its wrangler config has no readable, valid Worker name"}:{identity:{appId:e,config:n,production:o}}},un=async(r,e,t,n)=>{const o=[...e];if(o.some(i=>i.code===w.SUCCESS)){for(const[i,a]of o.entries())if(a.code!==w.SUCCESS&&a.code!==w.NOT_FOUND){const c=await P(r[i],t,n);o[i]=c.code===w.NOT_FOUND?{code:w.SUCCESS}:c}}const s=o.find(i=>i.code!==w.SUCCESS&&i.code!==w.NOT_FOUND);return s!==void 0?s:o.find(i=>i.code===w.SUCCESS&&i.data!==void 0)??o.find(i=>i.code===w.SUCCESS)??p(t.logger,`no preview "${n}" is on record under this checkout's project or under the pull request head's, whose id or Worker name differs; nothing was deleted`,w.FAILURE)},ln=async(r,e,t,n)=>{const o=dn(n);if(o.error!==void 0){e.logger.warn(`the pull request head's identity could not be read (${o.error}); looking for the preview under this checkout's only`);const l=await P(r,e,t);return l.code===w.NOT_FOUND?p(e.logger,`no preview "${t}" is on record under this checkout's project, and the pull request head's identity could not be read (${o.error}), so it cannot be ruled out under that; nothing was deleted`,w.FAILURE):l}const{appId:s,config:i,production:a}=o.identity,c={...r,alsoProduction:i};if(s===r.appId&&a===r.config.name)return P(c,e,t);const d={...c,appId:s,config:{...r.config,...typeof i.account_id=="string"?{account_id:i.account_id}:{},name:a},requireOrigin:!0},u=[c,d],f=[await P(c,e,t),await P(d,e,t)];return un(u,f,e,t)},fn=async r=>{const{logger:e,subcommand:t}=r;if(!Fe.includes(t))return p(e,`usage: lunora preview <${Fe.join(" | ")}> [name]`);const n=Dt(r);return n.error!==void 0?p(e,n.error):r.headDir!==void 0&&t!=="delete"?p(e,"--head-dir applies to `lunora preview delete` only"):t==="list"?an(n.context,r):r.name===void 0||r.name===""?p(e,`usage: lunora preview ${t??""} <name> — e.g. the pull request number`):t==="deploy"?Zt(n.context,r,r.name):r.headDir===void 0?P(n.context,r,r.name):ln(n.context,r,r.name,r.headDir)},Rn=jr(async({argument:r,cwd:e,format:t,logger:n,options:o})=>{const s=await fn({cwd:e,dryRun:o.dryRun===!0,env:o.env,format:t,headDir:o.headDir,logger:n,name:r[1],secrets:o.secret??[],seed:o.seed===!0,subcommand:r[0],target:o.target,vars:o.var});return{code:s.code,data:s.data,error:s.error}});export{Rn as execute,fn as runPreviewCommand};
@@ -1 +1 @@
1
- import{mkdtempSync as p,rmSync as u,existsSync as m,readdirSync as $,statSync as g}from"node:fs";import{tmpdir as S}from"node:os";import{join as y,relative as w}from"node:path";import{d as z}from"../packem_shared/command-BpMv2n0o.mjs";import{EXIT_CODE as B}from"../packem_shared/EXIT_CODE-DQVhSE-1.mjs";import{defaultSpawner as F}from"../packem_shared/createRecordingSpawner-01ZngIwK.mjs";import{execArgsFor as h,detectPackageManager as x}from"@lunora/config/cli";const v=e=>{const t=[],n=o=>{for(const s of $(o)){const r=y(o,s),i=g(r);i.isDirectory()?n(r):i.isFile()&&t.push({path:w(e,r),sizeBytes:i.size})}};return n(e),t},l=e=>e<1024?`${String(e)} B`:e<1024*1024?`${(e/1024).toFixed(1)} KiB`:`${(e/(1024*1024)).toFixed(2)} MiB`,M=e=>{const t=v(e),n=t.toSorted((r,i)=>i.sizeBytes-r.sizeBytes),o=t.reduce((r,i)=>r+i.sizeBytes,0);return{generatedFiles:t.filter(r=>r.path.includes("_generated")),outdir:e,topModules:n.slice(0,10),totalBytes:o,totalFiles:t.length}},O=(e,t)=>{if(t.info(`outdir: ${e.outdir}`),t.info(`total: ${String(e.totalFiles)} files, ${l(e.totalBytes)}`),e.topModules.length>0){t.info(""),t.info("top modules by size:");for(const n of e.topModules)t.info(` ${l(n.sizeBytes).padStart(10," ")} ${n.path}`)}if(e.generatedFiles.length>0){t.info(""),t.info(`_generated/ files: ${String(e.generatedFiles.length)}`);for(const n of e.generatedFiles)t.info(` ${l(n.sizeBytes).padStart(10," ")} ${n.path}`)}},j=async e=>{const t=e.cwd??process.cwd(),n=e.format==="json",{logger:o}=e;let s,r,i=!1;if(e.inspectOnly)s=e.inspectOnly;else{s=p(y(S(),"lunora-analyze-")),i=!0;const a=h(x(t),"wrangler",["deploy","--dry-run","--outdir",s]);r={args:a.args,command:a.command,cwd:t,stdoutToStderr:n},o.info(`analyze: building via ${r.command} ${r.args.join(" ")}`);const d=await(e.spawner??F)(r);if(d.code!==0){const f=`analyze: wrangler dry-run failed (exit ${String(d.code)})`;return o.error(f),u(s,{force:!0,recursive:!0}),{code:d.code,descriptor:r,error:f,report:void 0}}}try{if(!m(s)){const c=`analyze: outdir not found at ${s}`;return o.error(c),{code:B.NOT_FOUND,descriptor:r,error:c,report:void 0}}const a=M(s);return n||O(a,o),{code:0,descriptor:r,report:a}}finally{if(i&&m(s))try{u(s,{force:!0,recursive:!0})}catch{}}},N=z(async({cwd:e,format:t,logger:n})=>{const o=await j({cwd:e,format:t,logger:n});return{code:o.code,data:o.report,error:o.error}});export{N as execute,j as runAnalyzeCommand};
1
+ import{r as S}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{r as $,a as w}from"../packem_shared/admin-url-DJB8P6Jh.mjs";import{d as A}from"../packem_shared/command-BpMv2n0o.mjs";import{EXIT_CODE as d,exitCodeForStatus as x}from"../packem_shared/EXIT_CODE-DQVhSE-1.mjs";import{r as y}from"../packem_shared/resolve-target-BRvw8Pf7.mjs";const u="/_lunora/admin/tokens",p=864e5,k=["create","list","revoke"],o=(e,r,t)=>(e.error(r),{code:t,error:r}),l=(e,r)=>e===void 0?r:new Date(e).toISOString(),D=(e,r)=>{if(e==="list")return{method:"GET",path:u};if(e==="revoke")return{method:"DELETE",path:`${u}?name=${encodeURIComponent(r.name??"")}`};const t=r.expiresDays===void 0?void 0:(r.now??Date.now)()+r.expiresDays*p;return{body:JSON.stringify({expiresAt:t,name:r.name}),method:"POST",path:u}},U=(e,r,t,s)=>{if(r==="create"){e.success(`created admin token "${String(t.name)}" — copy it now, it is not shown again:`),e.info(String(t.token));return}if(r==="revoke"){e.success(`revoked admin token "${String(s)}"`);return}const n=t.tokens??[];n.length===0&&e.info("no named admin tokens");for(const a of n)e.info(`${a.name} created ${l(a.createdAt,"?")} last used ${l(a.lastUsedAt,"never")} expires ${l(a.expiresAt,"never")}${a.revoked===!0?" revoked (its row still holds the name: revoke it again to free it)":""}`)},E=async e=>{const{logger:r}=e,t=k.find(h=>h===e.subcommand);if(t===void 0)return o(r,`admin-token: unknown subcommand "${e.subcommand??""}" — expected ${k.join(" | ")}`,d.USAGE);if(t!=="list"&&(e.name===void 0||e.name===""))return o(r,`admin-token ${t}: a token name is required`,d.USAGE);if(e.expiresDays!==void 0&&(!Number.isFinite(e.expiresDays)||e.expiresDays<=0))return o(r,"--expires-days must be a positive number",d.USAGE);if(e.prod&&e.url===void 0)return o(r,"--prod requires an explicit --url",d.USAGE);const s=$(e.url,r,e.cwd);if(s===void 0)return{code:d.USAGE,error:"could not resolve a usable worker URL"};const{token:n}=S({cwd:e.cwd??process.cwd(),token:e.token,url:s});if(!n)return o(r,"root admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)",d.AUTH);const{body:a,method:f,path:v}=D(t,e),c=await(e.fetchImpl??w)(`${s}${v}`,{body:a,headers:{authorization:`Bearer ${n}`,"content-type":"application/json"},method:f}),m=await c.text();if(!c.ok)return o(r,`admin-token ${t} failed: HTTP ${String(c.status)}: ${m}`,x(c.status));let i;try{i=JSON.parse(m)}catch{return o(r,`admin-token ${t} failed: worker returned non-JSON: ${m}`,1)}return t==="create"&&(typeof i.token!="string"||i.token.length===0)?o(r,"admin-token create failed: the worker's answer did not include the created token",1):(e.format!=="json"&&U(r,t,i,e.name),{code:0,data:i})},G=A(async({argument:e,cwd:r,format:t,logger:s,options:n})=>{const a=await E({cwd:r,expiresDays:n.expiresDays,format:t,logger:s,name:e[1],prod:n.prod,subcommand:e[0],token:n.token,url:y({cwd:r,prod:n.prod===!0,url:n.url})});return{code:a.code,data:a.data,error:a.error}});export{G as execute,E as runAdminTokenCommand};
@@ -1 +1,15 @@
1
- import{existsSync as b,readFileSync as L,realpathSync as A}from"node:fs";import{join as h}from"node:path";import{readProjectTarget as u,DEFAULT_TARGET as f,readServiceBindings as B}from"@lunora/codegen";import{DEV_VARS_FILE as m,parseDevVariableEntries as C,isPlaceholderValue as O,readProjectDependencies as M,discoverSchemaInfo as G,inferLunoraBindings as V,resolveSchemaDirectory as K,probeCelldToolchain as q,D1_PLACEHOLDER_ID as W}from"@lunora/config";import{GLOBAL_FETCH_STRICTLY_PUBLIC_FLAG as g,resolveObservabilitySampling as y,findWranglerFile as T,readWranglerJsonc as D,buildBindingManifest as H,validateWranglerProject as z,UNEXPORTED_CLASS_MARKER as x,detectCloudflareCliConfig as J,collectExportGaps as Y}from"@lunora/config/cloudflare";import{a as Q,i as X,m as Z,c as ee,b as te,d as ne,e as oe,f as re}from"../packem_shared/vectorize-metadata-BVSF8z2h.mjs";import{r as se,d as ae}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{r as ie,n as w,c as ce}from"../packem_shared/cloudflare-credentials-BVmZnDZk.mjs";import{d as le}from"../packem_shared/command-BpMv2n0o.mjs";import{i as de}from"../packem_shared/path-containment-CgxYZggb.mjs";import{A as $,a as R,b as k}from"../packem_shared/variables-CPYyJtsL.mjs";const ue=(o,t)=>{const e=new Set,n=s=>{for(const[a,c]of Object.entries(s??{}))typeof c=="string"&&c.trim().length>0&&e.add(a)};n(o.vars);for(const s of Object.values(o.env??{}))n(s.vars);const r=h(t,m);if(b(r))try{n(Object.fromEntries(C(L(r,"utf8")).map(s=>[s.key,s.value])))}catch{}return e},fe=(o,t,e,n)=>{if(o===void 0||!e)return;const r=ue(o,t),s=r.has($),a=o.ai?.binding;!s&&(typeof a!="string"||a.length===0)&&n.push({code:"ai-binding-missing",fix:`Run \`lunora dev\` (it adds the binding), add \`"ai": { "binding": "AI" }\` to wrangler.jsonc, or set ${$} to an OpenAI-compatible proxy.`,level:"warn",message:"the project uses ctx.ai (@lunora/ai / env.AI) but wrangler.jsonc declares no `ai` binding — model calls will fail at runtime."}),r.has(R)&&n.push({code:"ai-gateway-token-unused",fix:"Make the gateway unauthenticated for ctx.ai, or remove the token. A bring-your-own AI SDK provider built with `resolveAiGateway` does send it.",level:"warn",message:`${R} is set, but ctx.ai's Workers AI binding cannot send a gateway token — it is ignored on that path.`}),!s&&!r.has(k)&&n.push({code:"ai-gateway-default",fix:`Run \`lunora cloudflare ai-gateway\` to create a gateway for this app and write ${k} into wrangler vars.`,level:"info",message:`no ${k} in vars or ${m} — \`<provider>/<model>\` slugs route through the account's \`default\` AI Gateway.`})},pe=(o,t,e)=>{if(o===void 0||!t)return;const n=[];(o.compatibility_flags??[]).includes(g)||n.push("the top level");for(const[r,s]of Object.entries(o.env??{}))s.compatibility_flags!==void 0&&!s.compatibility_flags.includes(g)&&n.push(`env.${r}`);n.length>0&&e.push({code:"cimd-fetch-not-strictly-public",fix:`Add "${g}" to "compatibility_flags" in wrangler.jsonc.`,level:"warn",message:`@lunora/auth/cimd/workers is imported, but ${n.join(", ")} of wrangler.jsonc lacks the ${g} compatibility flag — workersCimdFetch() refuses to build without it.`})},N=5e3,he="https://api.cloudflare.com/client/v4/user/tokens/verify",U=o=>{if(typeof o!="object"||o===null||!("result"in o)||"success"in o&&o.success===!1)return;const{result:t}=o;return typeof t=="object"&&t!==null&&"status"in t&&typeof t.status=="string"?t.status:void 0},ge=async(o,t)=>{const e=await t(he,{headers:{Authorization:`Bearer ${o}`},signal:AbortSignal.timeout(N)}),n=await e.json().catch(()=>{});return{reported:e.ok?U(n):void 0,status:e.status}},me=async(o,t,e)=>{const n=await ce({accountId:o,apiToken:t,fetch:e,init:{signal:AbortSignal.timeout(N)},path:"/tokens/verify"});return n.ok?{reported:U(n.body),status:200}:{reported:void 0,status:n.status}},ve=async(o,t,e)=>{const n=await me(o,t,e);return n.reported!==void 0?n.reported==="active"?{verdict:"active"}:{verdict:"rejected"}:n.status===401||n.status===403?{verdict:"rejected"}:{reason:`HTTP ${String(n.status)}`,verdict:"unchecked"}},be=async(o,t,e)=>{const n=await ge(o,e);if(n.reported!==void 0)return n.reported==="active"?{verdict:"active"}:{verdict:"rejected"};if(n.status!==401&&n.status!==403)return{reason:`HTTP ${String(n.status)}`,verdict:"unchecked"};if(t.length===0)return{reason:"the user endpoint refused it, and no account id is set to check an account-owned token",verdict:"unchecked"};const r=await Promise.all(t.map(async s=>await ve(s,o,e).catch(a=>({reason:a instanceof Error?a.message:String(a),verdict:"unchecked"}))));return r.find(s=>s.verdict==="active")??r.find(s=>s.verdict==="unchecked")??{verdict:"rejected"}},we=o=>{const t=[o?.account_id,...Object.values(o?.env??{}).map(e=>e?.account_id)];return[...new Set(t.map(e=>w(e)).filter(e=>e!==void 0))]},ke=async(o,t,e)=>{const n=t.environment??process.env,r=we(o),{accountId:s,token:a}=ie(n,r[0]),c=w(n.CLOUDFLARE_ACCOUNT_ID)===void 0?r:[s].filter(d=>d!==void 0);if(a===void 0){e.push({code:"cloudflare-token-unchecked",fix:"Set CLOUDFLARE_API_TOKEN to verify it.",level:"info",message:"the Cloudflare API token was not verified: CLOUDFLARE_API_TOKEN is not set."});return}const i=t.fetch??globalThis.fetch.bind(globalThis);let l;try{l=await be(a,c,i)}catch(d){l={reason:d instanceof Error?d.message:String(d),verdict:"unchecked"}}l.verdict==="active"?e.push({code:"cloudflare-token-ok",level:"pass",message:"the Cloudflare API token is active."}):l.verdict==="rejected"?e.push({code:"cloudflare-token-rejected",fix:"Create a token at https://dash.cloudflare.com/profile/api-tokens with the Workers Scripts Edit permission, then set CLOUDFLARE_API_TOKEN to it.",level:"fail",message:"the Cloudflare API token is not active, so deploys with it will fail."}):e.push({code:"cloudflare-token-unchecked",level:"info",message:`the Cloudflare API token could not be verified (${l.reason}).`})},S=o=>{const{logs:t,traces:e}=y(o);return Object.entries({logs:t,traces:e}).filter(([,n])=>n.enabled&&n.headSamplingRate>=1).map(([n])=>n)},ye=(o,t)=>{if(o===void 0)return;const e=[],n=S(o.observability);n.length>0&&e.push(`${n.join(" + ")} (top level)`);for(const[r,s]of Object.entries(o.env??{})){const a=s?.observability;if(a===void 0)continue;const c=S(a);c.length>0&&e.push(`${c.join(" + ")} (env.${r})`)}e.length!==0&&t.push({code:"observability-full-sampling",fix:"For a high-traffic Worker, lower head_sampling_rate in wrangler.jsonc: under observability for logs, under observability.traces for traces — e.g. 0.1 keeps 10% of requests. Lunora never changes a rate you set.",level:"info",message:`observability samples every request (head_sampling_rate 1) for ${e.join(", ")}. From 2026-12-01 Workers Observability is billed: Free caps ingestion at 0.5 GB/day; Paid includes 50 GB per billing cycle, then $0.25/GB.`})},v=o=>o.enabled&&o.headSamplingRate>0,j=o=>{if(!o||o.redact_query_string===!0)return!1;const{logs:t,traces:e}=y(o);return v(t)||v(e)},E=o=>{const{logs:t,traces:e}=y(o);return[v(t)&&"request logs",v(e)&&"traces"].filter(Boolean).join(" and ")},_e=(o,t)=>{if(o===void 0)return;const e=[],n=new Set;j(o.observability)&&(e.push("top level"),n.add(E(o.observability)));for(const[r,s]of Object.entries(o.env??{})){const a=s?.observability;j(a)&&(e.push(`env.${r}`),n.add(E(a)))}e.length!==0&&t.push({code:"observability-query-unredacted",fix:'Set "redact_query_string": true in each observability block listed above in wrangler.jsonc. Lunora never changes a value you set.',level:"warn",message:`${[...n].join(" / ")} keep query strings (redact_query_string is not true) for ${e.join(", ")}. Emailed auth links carry their token in the query, so that token is stored with the request URL.`})},P={ai:"Workers AI",browser:"Browser Rendering",images:"Cloudflare Images (Image Transformations)"},I=["Argo Smart Routing","Log Explorer"],Ae=o=>{const t=[["top level",o],...Object.entries(o.env??{}).flatMap(([n,r])=>r?[[`env.${n}`,r]]:[])],e=new Map;for(const[n,r]of t)for(const s of H(r).bindings)P[s.type]!==void 0&&e.set(s.type,[...e.get(s.type)??[],n]);return e},xe=(o,t)=>{if((u(o)??f)!=="cloudflare")return;const e=T(o),n=e===void 0?void 0:D(e).parsed;if(n!==void 0)for(const[r,s]of Ae(n)){const a=P[r]??r;t.push({code:"paid-product-bound",fix:"Create an account budget alert in the dashboard: Manage Account > Billing > Billable Usage > Create budget alert. Lunora cannot create or read one.",level:"info",message:`${a} is bound (${s.join(", ")}) and billed per use. No documented usage-alert product covers it, and lunora cannot read budget alerts, so an account budget alert is the only cap.`})}t.push({code:"paid-product-unknown",level:"info",message:`enablement of ${I.join(" and ")} cannot be read by lunora (dashboard settings); check the dashboard if your account uses ${I.length>1?"them":"it"}.`})},$e=(o,t)=>{for(const e of B(o).services)for(const n of e.publicScopes){const r=n===""?"":` (env.${n})`;t.push({code:"service-workers-dev",fix:`If ${e.name} has no public route (custom domain or route, including ones set outside ${e.wranglerPath}), set \`"workers_dev": false\`${r}. Keep its internal auth (HMAC) either way.`,level:"warn",message:`service ${e.name} (${e.worker}) has no route in its wrangler config and still serves on workers.dev${r}; a custom domain set elsewhere would also be public.`})}},F=o=>{const t=T(o);if(t===void 0)return{parsed:void 0,path:void 0};const{parsed:e}=D(t);return{parsed:e,path:t}},Re=(o,t,e,n)=>{if(e===void 0){n.push({code:"wrangler-missing",fix:"Run `lunora init` (or `lunora dev`) to scaffold and reconcile wrangler.jsonc.",level:"fail",message:"wrangler.jsonc not found."});return}if(t===void 0){n.push({code:"wrangler-unparseable",fix:`Check ${e} is valid JSONC.`,level:"fail",message:`Could not parse ${e}.`});return}const{report:r}=z({projectRoot:o});for(const c of r.errors.filter(i=>i.includes(x)))n.push({code:"wrangler-class-unexported",level:"fail",message:c});for(const c of r.warnings.filter(i=>i.includes("LUNORA_ORIGIN_URL")))n.push({code:"scheduler-origin-missing",fix:"Set LUNORA_ORIGIN_URL in wrangler vars to the worker's public URL (or `wrangler secret put LUNORA_ORIGIN_URL`).",level:"warn",message:c});const s=c=>c.includes(x)||c.includes("SHARD");for(const c of r.errors.filter(i=>!s(i)))n.push({code:"wrangler-invalid",fix:"Fix the reported wrangler.jsonc problem; `lunora verify` reports the same set.",level:"fail",message:c});for(const c of r.warnings.filter(i=>!i.includes("LUNORA_ORIGIN_URL")))n.push({code:"wrangler-advisory",level:"warn",message:c});const a=r.errors.find(c=>c.includes("SHARD"));a===void 0?n.push({code:"wrangler-shard-binding-ok",level:"pass",message:"wrangler.jsonc present with a SHARD durable-object binding."}):n.push({code:"wrangler-shard-binding-missing",fix:"Run `lunora dev` to auto-reconcile, or add the binding manually.",level:"fail",message:a})},Se=(o,t)=>{b(h(o,"lunora.json"))&&t.push({code:"stale-lunora-json",fix:'Move `target` / `remote` into `lunora.config.ts` (`export default { target: "…" }`), then delete lunora.json.',level:"warn",message:"lunora.json is present but no longer read — lunora.config.* replaced it, so any `target` or `remote` in it is being ignored."})},je=(o,t)=>{const e=J(o);e!==void 0&&t.push({code:"cf-config-present",fix:e.fix,level:"warn",message:e.message})},Ee=(o,t)=>{o===void 0||o.limits?.cpu_ms!==void 0||t.push({code:"cpu-limit-missing",fix:'Add `"limits": { "cpu_ms": 30000 }` to wrangler.jsonc, tuned to your slowest legitimate handler.',level:"info",message:"no limits.cpu_ms is set — a runaway handler can burn CPU up to the platform default before anything stops it."})},Ie=(o,t)=>{const e=(o?.r2_buckets??[]).map(n=>n?.bucket_name).filter(n=>typeof n=="string"&&n.length>0);e.length!==0&&t.push({code:"r2-lifecycle-unset",fix:"wrangler r2 bucket lifecycle list <bucket> — add an abort-incomplete-multipart rule if none exists.",level:"info",message:`R2 bucket(s) ${e.join(", ")}: verify a lifecycle rule aborts incomplete multipart uploads — orphaned parts are billed but invisible in a listing.`})},Le=(o,t)=>{const{error:e,info:n}=G(o,"lunora");if(e!==void 0){t.push({code:"schema-unreadable",fix:"Fix the parse error, then re-run `lunora doctor`. `lunora codegen` reports the same failure with the offending source.",level:"fail",message:`lunora/schema.ts could not be parsed, so every schema-derived check was skipped: ${e}`});return}for(const r of n?.vectorMetadata??[]){const s=Z(r.kind);if(s===void 0){t.push({code:"vector-metadata-unfilterable",fix:"Filter on a string, number or boolean column, or drop it from `metadata`.",level:"warn",message:`vector index "${r.index}" declares metadata "${r.property}", whose type Vectorize cannot filter on.`});continue}t.push({code:"vector-metadata-index-required",fix:`wrangler ${ee({index:r.index,property:r.property,type:s}).join(" ")}`,level:"info",message:`vector index "${r.index}" filters on metadata "${r.property}" — that needs a Vectorize metadata index (\`lunora deploy\` creates it).`})}},Ce=o=>{const t=o?.d1_databases;return Array.isArray(t)?t.filter(Boolean):[]},Oe=(o,t,e)=>{const n=Ce(o),r=[];for(const s of n){const a=typeof s.database_id=="string"?s.database_id:"";if(e?oe(a)&&a!==W:re(a)){const i=typeof s.binding=="string"&&s.binding.length>0?s.binding:"<unnamed>";r.push({code:"d1-placeholder-id",fix:e?"Set database_id to the database celld should use.":"Run `lunora doctor --fix` to create the database and write its id into wrangler.jsonc, or run `wrangler d1 create <name>` and paste the returned database_id in yourself.",level:"fail",message:`D1 binding "${i}"${t} has a placeholder database_id ("${a||"<empty>"}").`})}}return r},Te=(o,t,e)=>{if(t===void 0)return;const n=(u(o)??f)==="celld",r=[{config:t,suffix:""},...Object.entries(n?{}:t.env??{}).map(([s,a])=>({config:a,suffix:` in env.${s}`}))];for(const{config:s,suffix:a}of r)e.push(...Oe(s,a,n))},De=(o,t)=>{if(o===void 0)return;const e=(o.send_email??[]).filter(Boolean);for(const n of e){const r=typeof n.destination_address=="string"?n.destination_address:"";if(r!==""&&O(r)){const s=typeof n.name=="string"&&n.name.length>0?n.name:"send_email";t.push({code:"email-destination-placeholder",fix:"Set destination_address to a verified Cloudflare Email Routing address.",level:"warn",message:`send_email binding "${s}" has a placeholder destination_address ("${r}").`})}}},Ne=(o,t)=>{const e=h(o,m);if(!b(e))return;let n;try{n=L(e,"utf8")}catch{return}const r=C(n).filter(s=>X(s.key)&&O(s.value)).map(s=>s.key);r.length>0&&t.push({code:"dev-vars-missing-secret",fix:"Run `lunora dev` to auto-generate secrets, or fill them in by hand.",level:"warn",message:`${m} has unfilled secret value(s): ${r.join(", ")}.`})},Ue=(o,t)=>{const{source:e}=se({cwd:o});e===void 0?t.push({code:"admin-token-missing",fix:"Set LUNORA_ADMIN_TOKEN (env or `.dev.vars`) to enable admin RPCs / studio.",level:"info",message:"LUNORA_ADMIN_TOKEN is not set."}):t.push({code:"admin-token-set",level:"pass",message:`LUNORA_ADMIN_TOKEN is set (${ae(e)}).`})},Pe=async(o,t)=>{try{return await V({projectRoot:o,schemaDir:K(o)})}catch(e){t.push({code:"declared-export-unchecked",fix:"Make sure the worker entry resolves (see `lunora codegen`), then re-run.",level:"warn",message:`could not check whether declared containers/workflows/agents are re-exported by the worker entry: ${e instanceof Error?e.message:String(e)}`});return}},Fe=(o,t)=>{const e=Y(o),n=[...o.containers.map(r=>({...r,kind:"container"})),...o.workflows.map(r=>({...r,kind:"workflow"})),...o.agents.map(r=>({...r,kind:"agent"}))];for(const r of n.filter(s=>s.exported))t.push({code:"declared-export-ok",level:"pass",message:`${r.kind} "${r.exportName}" is exported by the worker entry.`});for(const r of e)t.push({code:"declared-export-missing",fix:`Add \`export * from "./lunora/_generated/${r.module}"\` to your worker entry (or re-run \`vis generate lunora-${r.kind}\`).`,level:"fail",message:`${r.kind} "${r.exportName}" is declared but ${r.className} is not exported by the worker entry.`})},Be=/^[\^~><= ]+/u,Me=/^(?<core>\d+\.\d+\.\d+)(?:-(?<channel>[a-z]+)\.(?<counter>\d+))?$/u,Ge=o=>{const t=o.replace(Be,"").trim(),e=Me.exec(t);if(!e?.groups)return;const{channel:n,core:r,counter:s}=e.groups;return{channel:n??"",core:r??"",counter:s===void 0?void 0:Number.parseInt(s,10),raw:t}},Ve=(o,t)=>{const e=M(o),n=[];for(const[i,l]of Object.entries(e)){if(i!=="lunorash"&&!i.startsWith("@lunora/"))continue;const d=Ge(l);d&&n.push({name:i,version:d})}if(n.length<2)return;const r=i=>i.map(l=>`${l.name}@${l.version.raw}`).join(", "),s=new Set(n.map(i=>i.version.core)),a=new Set(n.map(i=>i.version.channel));if(s.size>1){t.push({code:"version-skew-cores",fix:'Run `pnpm update "@lunora/*" lunorash` (or `npm`/`yarn` equivalent) so every Lunora package moves to the same release.',level:"warn",message:`Lunora packages span ${String(s.size)} different versions: ${r(n)}.`});return}if(a.size>1){t.push({code:"version-skew-channels",fix:"Pick one channel (all stable, or all alpha/beta) and update the odd package out.",level:"warn",message:`Lunora packages mix release channels (${[...a].map(i=>i===""?"stable":i).join(" + ")}): ${r(n)}.`});return}const c=n.map(i=>i.version.counter).filter(i=>i!==void 0);if(c.length>1){const i=Math.min(...c),l=Math.max(...c);t.push({code:"version-counter-spread",level:"info",message:c.length===n.length&&i===l?`Lunora packages are all at ${[...a][0]??""}.${String(l)}.`:`Lunora pre-release counters span ${String(i)}–${String(l)}: ${r(n)}.`})}},Ke=[h("@lunora","cli"),"lunorash"],qe=(o,t,e)=>{if(t===void 0)return;const n=[];for(const s of Ke){const a=h(o,"node_modules",s);if(b(a))try{n.push(A(a))}catch{}}if(n.length===0)return;let r;try{r=A(t)}catch{return}n.some(s=>de(s,r))||e.push({code:"cli-shadowed",fix:"Run the project's own CLI: `pnpm exec lunora …` (or `npx lunora …`).",level:"warn",message:`the running lunora (${r}) is not the project's own install (${n.join(", ")}).`})},We={full:{code:"do-class-budget-full",level:"warn"},near:{code:"do-class-budget-near",level:"warn"},ok:{code:"do-class-budget-ok",level:"pass"},unchecked:{code:"do-class-budget-unchecked",level:"info"}},He=o=>{const t=new Map,e=(n,r)=>{const s=w(n);s!==void 0&&t.set(s,[...t.get(s)??[],r])};e(o?.account_id,"top level");for(const[n,r]of Object.entries(o?.env??{}))e(r?.account_id,`env.${n}`);return t},ze=async(o,t,e,n)=>{if((u(o)??f)!=="cloudflare")return;const s=w((e.environment??process.env).CLOUDFLARE_ACCOUNT_ID)!==void 0?[]:[...He(t)],a=s.length===0?[[void 0,[]]]:s,c=await Promise.all(a.map(async([i,l])=>({accountId:i,blocks:l,budget:await te({accountId:i,environment:e.environment,fetch:e.fetch})})));for(const{accountId:i,blocks:l,budget:d}of c)n.push({...We[d.verdict],message:c.length>1?`account ${String(i)} (${l.join(", ")}): ${d.message}`:d.message,...d.fix===void 0?{}:{fix:d.fix}})},Je="CELLD_BUCKET is not set — a live `lunora deploy` needs it to name the fleet bucket; `lunora dev` and a dry run do not.",Ye=async(o,t,e)=>{if((u(o)??f)!=="celld")return;const n={...process.env,...t.environment},r=await q({dryRun:!0,env:n,purpose:"deploy"}),s=(n.CELLD_BUCKET??"").trim()===""?[...r.warnings,Je]:r.warnings;for(const a of r.errors)e.push({code:"celld-toolchain-missing",level:"fail",message:a});for(const a of s)e.push({code:"celld-toolchain-warn",level:"warn",message:a});r.errors.length===0&&s.length===0&&e.push({code:"celld-toolchain-ok",level:"pass",message:"celld, esbuild and CELLD_BUCKET are in place for a deploy."})},Qe={mismatch:{code:"artifacts-jurisdiction-mismatch",level:"fail"},missing:{code:"artifacts-namespace-missing",level:"fail"},ok:{code:"artifacts-jurisdiction-ok",level:"pass"},unchecked:{code:"artifacts-jurisdiction-unchecked",level:"warn"}},Xe=async(o,t,e,n,r)=>{if(e===void 0||t===void 0||(u(o)??f)!=="cloudflare")return;const s=[["",t],...Object.entries(t.env??{}).map(([i,l])=>[`env.${i}: `,l])],a=new Map;for(const[i,l]of s){const d=l.account_id??t.account_id;for(const p of l.artifacts??[]){const _=`${String(d)}/${String(p?.namespace)}`;typeof p?.binding=="string"&&typeof p.namespace=="string"&&!a.has(_)&&a.set(_,{accountId:d,binding:p.binding,label:i,namespace:p.namespace})}}const c=await Promise.all([...a.values()].map(async({label:i,...l})=>({check:await ne({...l,environment:n.environment,fetch:n.fetch,jurisdiction:e,missingOk:!0}),label:i})));for(const{check:i,label:l}of c)r.push({...Qe[i.verdict],message:`${l}${i.message}`,...i.fix===void 0?{}:{fix:i.fix}})},Ze=async o=>{const t=o.cwd??process.cwd(),e=[],{parsed:n,path:r}=F(t);Re(t,n,r,e),je(t,e),Te(t,n,e),De(n,e),Ee(n,e),Ie(n,e),ye(n,e),_e(n,e),Ne(t,e),Ue(t,e),Ve(t,e),Le(t,e),Se(t,e),qe(t,o.executablePath??process.argv[1],e),$e(t,e),xe(t,e);const s=await Pe(t,e);s!==void 0&&Fe(s,e),fe(n,t,s?.usesAi===!0,e),await Ye(t,o,e),await ze(t,n,o,e),(u(t)??f)==="cloudflare"&&await ke(n,o,e),await Xe(t,n,s?.jurisdiction,o,e),pe(n,s?.usesCimdWorkers===!0,e);const a={fail:0,info:0,pass:0,warn:0};for(const i of e)a[i.level]+=1;const c=a.fail>0?1:0;return{code:c,findings:e,ok:c===0,summary:a}},et={fail:"FAIL",info:"INFO",pass:"PASS",warn:"WARN"},tt=(o,t)=>{t.info("lunora doctor — project preflight");for(const r of o.findings){const s=`[${et[r.level]}] ${r.message}`;r.level==="fail"?t.error(s):r.level==="warn"?t.warn(s):t.info(s),r.fix!==void 0&&r.level!=="pass"&&t.info(` fix: ${r.fix}`)}const{fail:e,warn:n}=o.summary;e>0?t.error(`${String(e)} failure(s), ${String(n)} warning(s).`):n>0?t.warn(`0 failures, ${String(n)} warning(s).`):t.success("all checks passed.")},nt=async o=>{const{logger:t}=o,e=await Ze({...o});return tt(e,t),e},ht=le(async({cwd:o,format:t,logger:e,options:n})=>{if(n.fix===!0){const{path:s}=F(o),a=await Q({configPath:s,cwd:o,dryRun:n.dryRun===!0,logger:e});for(const c of a.applied)e.info(`fix: ${c}`);for(const c of a.skipped)e.warn(`not fixed: ${c}`)}const r=await nt({cwd:o,format:t,logger:e});return{code:r.code,data:{findings:r.findings,summary:r.summary}}});export{ht as execute,Ze as runDoctor,nt as runDoctorCommand};
1
+ import{V as te}from"./cli.mjs";import{d as re}from"../packem_shared/command-BpMv2n0o.mjs";import{EXIT_CODE as f}from"../packem_shared/EXIT_CODE-DQVhSE-1.mjs";import{existsSync as m,readFileSync as F,statSync as ne,watch as oe}from"node:fs";import{homedir as C}from"node:os";import{findWranglerFile as le}from"@lunora/config/cloudflare";import{join as i,relative as ae}from"@visulima/path";import{stringify as ce}from"smol-toml";import{h as se,u as ie,i as de,r as ue}from"../packem_shared/mcp-config-file-GR1Y_CVw.mjs";import{detectPackageManager as me,execArgsFor as fe}from"@lunora/config/cli";import{resolve as $,join as pe,dirname as L}from"node:path";import{readLiveDevServerState as b,DEV_STATE_DIR as ge}from"@lunora/config";import{resolveAdminToken as he}from"@lunora/config/studio-host";import{connectLocalStdio as ve,connectFunctionStdio as ye}from"@lunora/mcp";import{i as we}from"../packem_shared/path-containment-CgxYZggb.mjs";const g=e=>({args:[...e.args],command:e.command,...e.env===void 0?{}:{env:e.env}}),j=e=>e.transport==="http"?{type:"http",url:e.url}:g(e),be=e=>e.transport==="http"?{httpUrl:e.url}:g(e),Se=e=>e.transport==="http"?{serverUrl:e.url}:g(e),ke=e=>({args:["-y","mcp-remote",e],command:"npx"}),Ee=e=>e.transport==="http"?ke(e.url):g(e),$e=e=>e.transport==="http"?{url:e.url}:g(e),je=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}},Oe=e=>e.transport==="http"?{disabled:!1,type:"streamableHttp",url:e.url}:{disabled:!1,...g(e)},Ce=({home:e,platform:t})=>{if(t==="darwin")return{global:i(e,"Library","Application Support","Claude","claude_desktop_config.json")};if(t==="win32"){const r=process.env.APPDATA;return r===void 0||r===""?{}:{global:i(r,"Claude","claude_desktop_config.json")}}return t==="linux"?{global:i(e,".config","Claude","claude_desktop_config.json")}:{}},_e=(e,t)=>ce({mcp_servers:{[e]:t.transport==="http"?{url:t.url}:{args:[...t.args],command:t.command,...t.env===void 0?{}:{env:t.env}}}}),v=[{buildEntry:j,paths:({projectRoot:e})=>({project:i(e,".mcp.json")}),format:"json",id:"claude-code",key:"mcpServers",label:"Claude Code"},{buildEntry:j,paths:({home:e,projectRoot:t})=>({global:i(e,".cursor","mcp.json"),project:i(t,".cursor","mcp.json")}),format:"json",id:"cursor",key:"mcpServers",label:"Cursor"},{buildEntry:j,paths:({projectRoot:e})=>({project:i(e,".vscode","mcp.json")}),format:"json",id:"vscode",key:"servers",label:"VS Code (GitHub Copilot)"},{buildEntry:be,paths:({home:e,projectRoot:t})=>({global:i(e,".gemini","settings.json"),project:i(t,".gemini","settings.json")}),format:"json",id:"gemini",key:"mcpServers",label:"Gemini CLI"},{buildEntry:Ee,paths:Ce,format:"json",id:"claude-desktop",key:"mcpServers",label:"Claude Desktop"},{buildEntry:Se,paths:({home:e})=>({global:i(e,".codeium","windsurf","mcp_config.json")}),format:"json",id:"windsurf",key:"mcpServers",label:"Windsurf"},{buildEntry:je,paths:({home:e,projectRoot:t})=>({global:i(e,".config","opencode","opencode.json"),project:i(t,"opencode.json")}),format:"json",id:"opencode",key:"mcp",label:"OpenCode"},{buildEntry:Oe,paths:({home:e})=>({global:i(e,".cline","mcp.json")}),format:"json",id:"cline",key:"mcpServers",label:"Cline"},{buildEntry:$e,paths:({home:e})=>({global:i(e,".config","zed","settings.json")}),format:"json",id:"zed",key:"context_servers",label:"Zed"},{paths:({home:e,projectRoot:t})=>({global:i(e,".codex","config.toml"),project:i(t,".codex","config.toml")}),format:"manual",id:"codex",label:"Codex CLI",renderSnippet:_e}],P=v.map(e=>e.id),Me=e=>v.find(t=>t.id===e.toLowerCase()),Ue=["global","project"],p=(e,t)=>{const r=ae(t,e);return r.length>0&&!r.startsWith("..")?r:e},xe=(e,t)=>{const r=e.paths(t);return Ue.flatMap(n=>{const o=r[n];return o===void 0?[]:[{client:e,path:o,scope:n}]})},Le=(e,t,r,n)=>{const o=e.paths(t),l=r==="global"?"project":"global",a=o[r]??(n?void 0:o[l]);if(a!==void 0)return{client:e,path:a,scope:o[r]===void 0?l:r}},Ne=e=>v.filter(t=>Object.values(t.paths(e)).some(r=>m(r))),I=(e,t,r,n)=>{if(e.length===0)return t();const o=[];for(const l of e){const a=Me(l);if(a===void 0){r.error(`mcp ${n}: unknown client "${l}". Known clients: ${P.join(", ")}.`);return}o.push(a)}return o},Ae=e=>e.client.format==="json",De="https://lunora.sh/mcp",R="lunora-docs",H="lunora",Te=e=>m(i(e,"lunora"))&&le(e)!==void 0,Fe=e=>{const{args:t,command:r}=fe(e,"lunora",["mcp","serve"]);return{args:t,command:r,transport:"stdio"}},Pe=e=>({transport:"http",url:e}),Ie=e=>({home:e.home,platform:e.platform,projectRoot:e.cwd}),W=(e,t,r)=>Le(e,Ie(r),r.scope??t.preferredScope,r.scope!==void 0||!t.allowScopeFallback),Re=(e,t,r)=>{const n=W(e,t,r);if(n===void 0){r.logger.warn(`${e.label}: has no ${r.scope??t.preferredScope}-scoped config — skipped "${t.name}".`);return}const{path:o}=n,l=e.buildEntry(t.spec);if(r.print===!0){const d=p(o,r.cwd);return r.force!==!0&&se({key:e.key,name:t.name,path:o})?(r.logger.info(`${e.label}: "${t.name}" already configured in ${d} — a real install would skip it (re-run with --force to replace).`),{action:"printed",path:o}):(r.logger.info(`${e.label} → ${d}
2
+ ${JSON.stringify({[e.key]:{[t.name]:l}},void 0,4)}`),{action:"printed",path:o})}const a=ie({entry:l,force:r.force===!0,key:e.key,name:t.name,path:o}),c=p(o,r.cwd);return a.action==="invalid"?r.logger.error(`${e.label}: ${c} is not valid JSON (${a.error??"unknown error"}) — left untouched.`):a.action==="skipped"?r.logger.info(`${e.label}: "${t.name}" already configured in ${c} — re-run with --force to replace it.`):r.logger.success(`${e.label}: ${a.action==="created"?"created":"updated"} ${c} with "${t.name}".`),{action:a.action,path:o}},He=(e,t,r)=>{const n=W(e,t,r)?.path;if(n===void 0){r.logger.warn(`${e.label}: no known config location on ${r.platform} — skipped.`);return}return r.logger.info(`${e.label}: add this to ${p(n,r.cwd)}
3
+
4
+ ${e.renderSnippet(t.name,t.spec)}`),{action:"printed",path:n}},We=e=>{const t=[];return e.localOnly!==!0&&t.push({allowScopeFallback:!0,name:R,preferredScope:"global",spec:Pe(e.docsUrl??De)}),e.docsOnly!==!0&&Te(e.cwd)&&t.push({allowScopeFallback:!1,name:H,preferredScope:"project",spec:Fe(me(e.cwd))}),t},Ge=e=>{const t=e.home??C(),r=e.platform??process.platform;e.logger.info("Supported MCP clients:");for(const n of v){const o=n.paths({home:t,platform:r,projectRoot:e.cwd}),l=a=>{const c=o[a];return c===void 0?"—":p(c,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:[]}},Je=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).",Ve=(e,t,r)=>{const n=[];for(const o of e)for(const l of t){const a=o.format==="json"?Re(o,l,r):He(o,l,r);a!==void 0&&n.push({action:a.action,client:o.id,path:a.path,server:l.name})}return n},ze=e=>{const t=e.home??C(),r=e.platform??process.platform,n=I(e.clients,()=>Ne({home:t,platform:r,projectRoot:e.cwd}),e.logger,"install");if(n===void 0)return{code:f.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: ${P.join(", ")}.`),{code:f.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=We(e);if(o.length===0)return e.logger.error(`mcp install: nothing to install — ${Je(e)}`),{code:f.USAGE,written:[]};const l=Ve(n,o,{...e,home:t,platform:r});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}},G=100,J=1e3,N=e=>({content:[{text:JSON.stringify(e,void 0,2),type:"text"}]}),Ke=e=>({content:[{text:e,type:"text"}]}),qe=e=>{const t=typeof e=="string"?Number(e):e;return typeof t!="number"||!Number.isFinite(t)?G:Math.min(J,Math.max(1,Math.floor(t)))},A=(e,t)=>{if(t===void 0)return;const r=$(e,ge);return we(r,$(e,t))?$(e,t):void 0},Be=(e,t)=>{const r=F(e,"utf8").split(`
5
+ `);return r.at(-1)===""&&r.pop(),r.slice(-t).join(`
6
+ `)},Xe=e=>[{definition:{annotations:{destructiveHint:!1,idempotentHint:!0,openWorldHint:!1,readOnlyHint:!0,title:"Check the local dev server"},description:"Report whether a `lunora dev` server is running for this project, and its URL, studio URL, mode and uptime. Call this first when a query or mutation tool fails to connect.",inputSchema:{properties:{},type:"object"},name:"lunora_dev_status"},handle:async()=>{const t=b(e);return N(t===void 0?{hint:"Start it with `lunora dev` in the project directory.",running:!1}:{background:t.background===!0,logFile:A(e,t.logFile),mode:t.mode,pid:t.pid,running:!0,startedAt:t.startedAt,studioUrl:t.studioUrl,url:t.url})}},{definition:{annotations:{destructiveHint:!1,idempotentHint:!0,openWorldHint:!1,readOnlyHint:!0,title:"Read the local dev server log"},description:"Return the tail of the running dev server's captured log — worker output, request errors, and stack traces. Only available when the server was started in the background (`lunora dev --background`); a foreground server prints to its own terminal.",inputSchema:{properties:{lines:{description:`How many trailing lines to return (default ${String(G)}, max ${String(J)})`,type:"number"}},type:"object"},name:"lunora_dev_logs"},handle:async t=>{const r=b(e);if(r===void 0)return{content:[{text:"no dev server is running — start one with `lunora dev`",type:"text"}],isError:!0};const n=A(e,r.logFile);if(n===void 0||!m(n))return{content:[{text:"this dev server is not capturing its output to a file (it runs in the foreground) — restart it with `lunora dev --background` to make its logs readable here",type:"text"}],isError:!0};const o=qe(t.lines),l=Be(n,o);return Ke(l.length===0?"(the dev server log is empty)":l)}}],O={methods:[],openrpc:"1.3.2"},Ze=e=>e instanceof Error&&e.code==="ENOENT",Qe=new Set(["127.0.0.1","::1","localhost"]),V=e=>{try{const{hostname:t}=new URL(e);return Qe.has(t.startsWith("[")?t.slice(1,-1):t)}catch{return!1}},D=e=>{const t=e.url??b(e.cwd)?.url;if(t===void 0||t.length===0)return;if(e.token!==void 0&&e.token.length>0)return{token:e.token,url:t};if(!V(t))return{url:t};const r=he(e.cwd);return r===void 0||r.length===0?{url:t}:{token:r,url:t}},z=async e=>{await new Promise(t=>{const r=()=>{t()};e.onclose=r,process.stdin.once("close",r),process.stdin.once("end",r)})},Ye=e=>{if(e===void 0)return"lunora mcp serve: ready (documentation tools). No dev server running yet — start `lunora dev` and the deployment tools start working, no restart needed.\n";if(e.token!==void 0)return`lunora mcp serve: ready — deployment at ${e.url}
7
+ `;const r=!V(e.url)?"the project's admin token was NOT sent to this non-local url; pass --token to authenticate deliberately":"no LUNORA_ADMIN_TOKEN in the environment or .dev.vars; the deployment tools will be refused until one is set";return`lunora mcp serve: ready — deployment at ${e.url} (${r})
8
+ `},K=e=>{process.stderr.write(e)},et=async(e,t)=>{const r=e.writeError??K,n=pe(e.cwd,"lunora","_generated","openrpc.json"),o=()=>e.url??b(e.cwd)?.url;let l,a;const c=s=>{r(`lunora mcp serve --functions: kept the last tool list — the rewritten document did not load: ${String(s)}
9
+ `)};let d={mtimeMs:-1,spec:O};const y=()=>{let s;try{s=ne(n).mtimeMs,a=void 0}catch(u){if(Ze(u))d.spec!==O&&(d={mtimeMs:-1,spec:O});else{const E=u.code??String(u);a!==E&&(a=E,c(u))}return d.spec}if(s!==d.mtimeMs)try{d={mtimeMs:s,spec:JSON.parse(F(n,"utf8"))}}catch(u){l!==s&&(l=s,c(u))}return d.spec};let w;try{w=await t({allowWrites:e.allowWrites===!0,onReloadError:c,openRpcSpec:y,url:o,version:e.version,...e.token===void 0||e.token.length===0?{}:{token:e.token}})}catch(s){const u=s instanceof Error?s.message:String(s);return r(`lunora mcp serve --functions: failed to start — ${u}
10
+ `),{code:1,deployment:void 0}}const q=e.token===void 0||e.token.length===0,S=o(),B=S===void 0||S.length===0?"no deployment yet (start `lunora dev` or pass --url; calls fail until one runs)":S,X=m(n)?"":" (no openrpc.json yet: run `lunora codegen --api-spec openrpc`; the functions appear once it exists)";r(`lunora mcp serve --functions: ready — ${B}${q?" (no --token: only public functions answer, and writes are refused)":""}${X}
11
+ `);const k=L(n),_=s=>{r(`lunora mcp serve --functions: the tool list will not be announced on a change — ${String(s)}
12
+ `)},Z=()=>{if(m(k))return k;const s=L(k);return m(s)?s:e.cwd};let M=m(n),h;const U=()=>{const s=Z();if(h?.directory!==s){h?.watcher.close(),h=void 0;try{const u=oe(s,(E,Q)=>{const x=m(n),Y=Q==="openrpc.json"||x!==M;M=x,U(),Y&&w.sendToolListChanged?.().catch(ee=>{r(`lunora mcp serve --functions: could not announce the tool list change — ${String(ee)}
13
+ `)})});u.on("error",_),h={directory:s,watcher:u}}catch(u){_(u)}}};U();try{await z(w)}finally{h?.watcher.close();try{await w.close?.()}catch(s){r(`lunora mcp serve --functions: could not close the server — ${String(s)}
14
+ `)}}return{code:0,deployment:void 0}},tt=async(e,t=ve,r=ye)=>{if(e.functions===!0)return et(e,r);const n=e.writeError??K;let o;try{o=await t({allowWrites:e.allowWrites===!0,deployment:()=>D(e),docs:e.noDocs===!0?!1:{...e.docsUrl===void 0?{}:{baseUrl:e.docsUrl}},extraTools:Xe(e.cwd),version:e.version})}catch(a){const c=a instanceof Error?a.message:String(a);return n(`lunora mcp serve: failed to start — ${c}
15
+ `),{code:1,deployment:void 0}}const l=D(e);return n(Ye(l)),await z(o),{code:0,deployment:l}},rt=e=>{const t=[];return e.localOnly!==!0&&t.push(R),e.docsOnly!==!0&&t.push(H),t},nt=(e,t,r,n)=>{const o=ue({key:e.key,name:t,path:r}),l=p(r,n.cwd);return o.action==="removed"?n.logger.success(`${e.label}: removed "${t}" from ${l}.`):o.action==="invalid"&&n.logger.error(`${e.label}: ${l} is not valid JSON (${o.error??"unknown error"}) — left untouched.`),{action:o.action,path:r}},ot=(e,t,r,n)=>{const o=de({key:e.key,name:t,path:r}),l=p(r,n.cwd);return o==="invalid"?(n.logger.error(`${e.label}: ${l} is not valid JSON — a real run would report it and exit non-zero.`),{action:"invalid",path:r}):o==="absent"?{action:"absent",path:r}:(n.logger.info(`${e.label}: would remove "${t}" from ${l}.`),{action:"removed",path:r})},lt=(e,t,r)=>e.flatMap(n=>xe(n,t)).filter(Ae).filter(n=>r===void 0||n.scope===r),at=e=>{const t=e.home??C(),r=e.platform??process.platform,n=I(e.clients,()=>v,e.logger,"uninstall");if(n===void 0)return{code:f.USAGE,removed:[]};const o=rt(e);if(o.length===0)return e.logger.error("mcp uninstall: nothing to remove — `--docs-only` and `--local-only` are mutually exclusive, pass at most one."),{code:f.USAGE,removed:[]};const l=[],a={home:t,platform:r,projectRoot:e.cwd};for(const c of lt(n,a,e.scope))for(const d of o){const y=e.print===!0?ot(c.client,d,c.path,e):nt(c.client,d,c.path,e);y.action!=="absent"&&l.push({...y,client:c.client.id,server:d})}return l.length===0?e.logger.info("Nothing to remove — no Lunora MCP servers were configured in the clients checked."):e.print===!0&&e.logger.info("Nothing was changed — re-run without --print to remove these."),{code:l.some(c=>c.action==="invalid")?1:0,removed:l}},T=e=>e.global===!0?"global":e.project===!0?"project":void 0,ct=async(e,t)=>{const{code:r}=await tt({allowWrites:t.allowWrites===!0,cwd:e,functions:t.functions===!0,noDocs:t.docs===!1,version:te,...t.docsUrl===void 0?{}:{docsUrl:t.docsUrl},...t.token===void 0?{}:{token:t.token},...t.url===void 0?{}:{url:t.url}});return{code:r}},Et=re(async({argument:e,cwd:t,logger:r,options:n})=>{const[o,...l]=e;if(o==="serve")return ct(t,n);if(o==="uninstall"){const a=T(n),{code:c}=at({clients:l,cwd:t,docsOnly:n.docsOnly===!0,localOnly:n.localOnly===!0,logger:r,print:n.print===!0,...a===void 0?{}:{scope:a}});return{code:c}}if(o==="install"){if(n.list===!0)return Ge({cwd:t,logger:r});const a=T(n),{code:c}=ze({clients:l,cwd:t,docsOnly:n.docsOnly===!0,force:n.force===!0,localOnly:n.localOnly===!0,logger:r,print:n.print===!0,...a===void 0?{}:{scope:a},...n.docsUrl===void 0?{}:{docsUrl:n.docsUrl}});return{code:c}}return r.error("mcp: unknown subcommand. Usage: lunora mcp <install|uninstall|serve>"),{code:f.USAGE}});export{Et as execute};
@@ -1 +1 @@
1
- import{d as Ue}from"../packem_shared/command-BpMv2n0o.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-DQVhSE-1.mjs";import{writeFileSync as Ae,mkdirSync as Re,renameSync as Me,rmSync as je}from"node:fs";import{findWranglerFile as W,readWranglerJsonc as H,applyModify as Le}from"@lunora/config/cloudflare";import{c as L}from"../packem_shared/cap-error-body-YBKO32BF.mjs";import{r as Y,n as ee,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{i as qe}from"../packem_shared/docker-DpVxvYpL.mjs";import{defaultSpawner as P}from"../packem_shared/createRecordingSpawner-01ZngIwK.mjs";import{execArgsFor as K,detectPackageManager as V}from"@lunora/config/cli";import{a as I}from"./cli.mjs";import{resolve as Be,dirname as Je}from"node:path";const We="https://api.cloudflare.com/client/v4/accounts",te=64,re={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}),oe=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}},ne=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 — ${re.unifiedBilling}`),e.info(` - a key stored on the gateway (Mistral, Perplexity, OpenRouter, …): ${re.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 oe(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}" (${ne(i)})`);const c=await oe(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}" (${ne(c)})`)},Ve=e=>{const{logger:t}=e,r=W(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}=H(r);if(o===void 0)return $(t,u.USAGE,`ai-gateway: could not parse ${r} as JSONC.`);const a=ee(e.id)??ee(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>te?$(t,u.USAGE,`ai-gateway: gateway id "${a}" is longer than ${String(te)} characters — pass a shorter --id.`):{gatewayId:a,parsed:o,text:n,wranglerPath:r}},G=e=>e?"on":"off",ze=(e,t)=>(e.info(`ai-gateway (dry run): would create or reuse AI Gateway "${t.gatewayId}" (log collection ${G(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}=Y(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 ${G(h.collectLogs)}).`):t.info(`ai-gateway: AI Gateway "${o}" already exists — reusing it (log collection ${G(h.collectLogs)}; change it in the dashboard).`),l.changed.length>0?(Ae(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}},ae=(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)},se=(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 se(s,l)}if(!f.ok)throw ae(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 se(s,l)}const f=await d.text();if(!d.ok)throw ae(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",ie={"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]},F=(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:F(t,["id","value","key","name"]);if(t===void 0||r===void 0)return;const o=F(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=>F(e,["key","name","filter","id"])!=="product"?[]:ct.flatMap(t=>{const r=U(e,t);return Array.isArray(r)?_e(r):[]}),x=(e,t,r)=>{if(t>st)return;if(Array.isArray(e)){for(const n of e)x(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&&x(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&&x(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=ie[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(ie)),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"}},ce="workersInvocationsAdaptive",yt="durableObjectsInvocationsAdaptiveGroups",M="durableObjectsPeriodicGroups",de="d1AnalyticsAdaptiveGroups",S=[{candidates:[{field:"requests",unit:"count"}],dataset:ce,filter:"datetime",id:"workers-requests",label:"Workers requests"},{candidates:[{field:"cpuTimeUs",unit:"microseconds"}],dataset:ce,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:de,filter:"datetime-hour",id:"d1-rows-read",label:"D1 rows read"},{candidates:[{field:"rowsWritten",unit:"count"}],dataset:de,filter:"datetime-hour",id:"d1-rows-written",label:"D1 rows written"}],le=e=>String(e).padStart(2,"0"),vt=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())}-${le(a.getUTCMonth()+1)}-${le(a.getUTCDate())}`;return{endDate:n(r),nextStartDate:n(o),startDate:n(t)}},wt=(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: ${wt(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,z="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.",kt={"do-requests":1e6,"workers-requests":1e7},Ot=100,It=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=It(e*t);return o>r?{basis:"history",threshold:o}:{basis:"floor",threshold:r}},q=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},X=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(q(e))===JSON.stringify(t.filters.product)&&Dt(X(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=kt[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>=Ot?`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},B=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===B(n)),c=r.find(p=>p.enabled===!0&&p.name?.startsWith(D)!==!0&&q(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=X(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:B(n)},v=i===void 0?[]:q(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(v)!==JSON.stringify([s.id])?{previousProduct:v}:{},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=>B(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.",ue=e=>Array.isArray(e)?e:[],fe=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=>X(m)),i=new Set([...s.flatMap(m=>(m.webhooks??[]).map(v=>v.id)),...r]),c=[...new Set(s.flatMap(m=>(m.email??[]).map(v=>v.id)))],d=new Set(a.map(m=>m.id)),f=new Date(n.getTime()-fe*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=ue(l).map(m=>({...m,referenced:m.id!==void 0&&i.has(m.id)})),y=ue(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(v=>!g.some(p=>p.id===v)))o.warn(`Webhook destination ${m} is referenced but does not exist on this account.`);for(const m of g.filter(v=>v.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(fe)} 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}}),Q=(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:z,...t===void 0?{}:{eligible:t.discovery.eligible,period:t.period,products:t.discovery.products}}),O=e=>e.toLocaleString("en-US",{maximumFractionDigits:0}),ke=(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).")},Oe=e=>({code:u.SUCCESS,data:e}),Yt=/^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/u,Ie=new Set(S.map(e=>e.id)),Kt=e=>Ie.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 ${[...Ie].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 ${O(e.lastMonth??0)}`,"floor-usage-unavailable":()=>"floor: usage could not be read, applied with --allow-floor",history:e=>`last month ${O(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 ${O(e.threshold)} (${Xt[e.basis](e)}); ${Qt(e.recipients)}`},J=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 ${J(n.metric)} — ${n.reason}`),n.warning!==void 0&&o.warn(`${J(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(z),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):Q(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:Q(r,s,i)},me=(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=>J(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 ke(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."),me(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:me(f,i,n)},ir=e=>e.status!=="ok"?`unavailable (${e.reason})`:e.unit==="microseconds"?`${O(e.value)} µs`:O(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",he=e=>e.map(t=>`"${t.name??t.id??"?"}" (limit ${JSON.stringify(t.limit)})${t.enabled?"":" — disabled, not protecting you"}`).join(", "),dr={active:e=>`alert: ${he(e.alerts)}`,"disabled-only":e=>`alert: none active; ${he(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(z),ke(r,t.discovery.eligible),r.info(R),Oe({...Z(e,t),metrics:n})},fr=e=>{const t=W(e);return t===void 0?void 0:H(t).parsed?.account_id},mr=e=>{const{accountId:t,token:r}=Y(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=vt(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),Oe({...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 Q(e.logger,o)}},ge=new Set(["build","delete","images","info","list","push"]),yr=new Set(["build","push"]),pe=new Set(["images list","info","list"]),vr=async e=>{const[t,...r]=e.argument;if(t===void 0||!ge.has(t)){const l=`lunora cloudflare containers requires a subcommand: ${[...ge].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&&!pe.has(n)){const l=`containers ${n}: --format json is only available for the read subcommands (${[...pe].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=K(V(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??P)(c)).code,delegated:o,descriptor:c}},T=(e,t)=>(t!==void 0&&e.push("--env",t),e),wr=(e,t)=>{const r=T(["deployments",t],e.env);return e.format==="json"&&r.push("--json"),r},br=(e,t,r)=>e.from===void 0?{error:`deployments promote --percent below 100 needs --from <live-version-id>, the version that keeps the other ${String(100-r)}% of traffic. List them with \`lunora cloudflare deployments list\`.`}:e.from===t?{error:"deployments promote --from must name a different version than the one being promoted."}:e.confirmSharedState!==!0?{error:"A partial promote runs two versions against one Durable Object database. Wrangler does not report whether their schemas or migrations match, so re-run with --confirm-shared-state once you have checked both. Durable Object class migrations must go out at 100%."}:{args:T(["versions","deploy",`${t}@${String(r)}%`,`${e.from}@${String(100-r)}%`,"--yes"],e.env)},$r=(e,t)=>{const r=e.percent??100;return!Number.isInteger(r)||r<1||r>100?{error:`deployments promote --percent must be a whole number from 1 to 100, got ${String(r)}.`}:e.yes?r<100?br(e,t,r):e.from!==void 0?{error:"deployments promote --from applies only to a partial promote (--percent below 100)."}:{args:T(["versions","deploy",`${t}@100%`,"--yes"],e.env)}:{error:`deployments promote shifts ${String(r)}% of live traffic. Re-run with --yes to confirm.`}},Ar=e=>{if(!(e.subcommand==="promote"||e.percent===void 0&&e.from===void 0&&e.confirmSharedState!==!0))return`deployments ${e.subcommand}: --percent, --from and --confirm-shared-state apply to deployments promote only.`},Sr=e=>{const t=Ar(e);if(t!==void 0)return{error:t};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:T(["versions","view",e.versionId],e.env)};case"list":case"status":return{args:wr(e,e.subcommand)};case"promote":{if(e.versionId===void 0)return{error:"deployments promote requires a version id. Usage: lunora cloudflare deployments promote <version-id> --yes"};const{args:r,error:o}=$r(e,e.versionId);return r===void 0||e.message===void 0?{args:r,error:o}:(r.push("--message",e.message),{args:r})}case"rollback":{if(!e.yes)return{error:"deployments rollback changes the live version. Re-run with --yes to confirm."};const r=T(["rollback"],e.env);return e.versionId!==void 0&&r.push(e.versionId),r.push("--yes"),e.message!==void 0&&r.push("--message",e.message),{args:r}}default:return{error:`deployments: unknown subcommand "${e.subcommand}"`}}},_r=e=>{let t;try{t=JSON.parse(e??"")}catch{return}const r=t?.versions;if(Array.isArray(r))return r.flatMap(o=>{const n=o?.version_id;return typeof n=="string"?[n]:[]})},Er=async(e,t,r)=>{const o=K(V(r),"wrangler",T(["deployments","status","--json"],e.env)),n=await t({args:o.args,captureStdoutSilently:!0,command:o.command,cwd:r}),a=n.code===0?_r(n.stdout):void 0;if(a===void 0){const s="deployments promote --from: could not read the live deployment (`wrangler deployments status`), so --from cannot be verified. Nothing was changed.";return e.logger.error(s),{code:u.FAILURE,descriptor:void 0,error:s}}if(e.from!==void 0&&!a.includes(e.from)){const s=`deployments promote --from ${e.from} is not a live version (live: ${a.join(", ")||"none"}). Check \`lunora cloudflare deployments status\`.`;return e.logger.error(s),{code:u.USAGE,descriptor:void 0,error:s}}},Tr=async e=>{if(e.format==="json"&&e.subcommand!=="list"&&e.subcommand!=="status"){const d=`deployments ${e.subcommand}: --format json is only available for \`deployments list\` and \`deployments status\` — 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}=Sr(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();if(e.subcommand==="promote"&&e.from!==void 0){const d=await Er(e,e.spawner??P,n);if(d!==void 0)return d}const a=K(V(n),"wrangler",t),s={args:a.args,command:a.command,cwd:n};return o.info(`${s.command} ${s.args.join(" ")}`),{code:(await(e.spawner??P)(s)).code,delegated:e.format==="json",descriptor:s}},kr=e=>e==="list"||e==="inspect"||e==="rollback"||e==="promote"||e==="status",Or="https://api.cloudflare.com/client/v4/accounts",Ne="Workers Scripts Read",ye=1e3,ve=5e4,Ir=1e4,Cr=3e4,we=[31,139],be=["cpu","heap"],Nr=/^[\da-f]{64}$/iu,w=(e,t,r)=>(e.error(r),{code:t,error:r}),$e=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())},Ur=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""}},Dr=e=>{const t=e.type??"cpu";if(!be.includes(t))return{error:`profile: invalid --type "${e.type??""}" — expected ${be.join(" | ")}`};const r=e.durationMs===void 0?Ir:Number(e.durationMs);return!Number.isInteger(r)||r<ye||r>ve?{error:`profile: invalid --duration-ms "${e.durationMs??""}" — expected an integer from ${String(ye)} to ${String(ve)}`}: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&&!Nr.test(e.actorId)?{error:"profile: --actor-id must be a 64-character hexadecimal Durable Object id"}:{durationMs:r,profileType:t}},Rr=e=>{const{logger:t}=e,r=W(e.cwd),o=r===void 0?void 0:H(r).parsed,{accountId:n,token:a}=Y(e.environment??process.env,o?.account_id);if(a===void 0)return w(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 w(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 w(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}},Mr=(e,t)=>{const r=`${e}.${String(process.pid)}.tmp`;try{Re(Je(e),{recursive:!0}),Ae(r,t),Me(r,e);return}catch(o){try{je(r,{force:!0})}catch{}return o instanceof Error?o.message:String(o)}},jr=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=`${Or}/${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+Cr)}),h=new Uint8Array(await l.arrayBuffer())}catch(g){return w(i,u.UNAVAILABLE,`profile failed: ${g instanceof Error?g.message:String(g)}.`)}if(!l.ok){const g=$e(new TextDecoder().decode(h));return w(i,j(l.status),`profile failed (HTTP ${String(l.status)})${g.length>0?`: ${g}`:""}${Ur(l.status)}.`)}if(h[0]!==we[0]||h[1]!==we[1]){const g=$e(new TextDecoder().decode(h));return w(i,u.FAILURE,`profile failed: the API answered 200 with something that is not a gzip profile${g.length>0?`: ${g}`:""}.`)}return{bytes:h}},Lr=async e=>{const{logger:t}=e,r=Dr(e);if("error"in r)return w(t,u.USAGE,r.error);const o=Rr(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 jr(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=Mr(l,d);return h!==void 0?w(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}})},Pr={ai:{absorbs:"gateway",tool:"ai-gateway"},alert:{tool:"alerts"}},Gr=(e,t)=>{const r=Pr[e];if(r!==void 0)return{rest:r.absorbs!==void 0&&t[0]===r.absorbs?t.slice(1):t,tool:r.tool};const o=I.find(n=>n.name===e)?.name;return o===void 0?void 0:{rest:t,tool:o}},Fr={celld:"celld",node:"Node"},xr=e=>e==="status"||e==="setup"||e==="test",k=(e,t,r)=>(e.error(r),{code:t,error:r}),qr=e=>{const t=Math.max(...I.map(r=>r.name.length));e.info("lunora cloudflare <tool> — tools for an app deployed to your own Cloudflare account:");for(const r of I)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}},Br=(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 ${Fr[n]??`"${n}"`}`:`\`--target ${n}\``} — \`lunora cloudflare ${t}\` only applies to Cloudflare.`},Jr=(e,{logger:t,rest:r})=>r.length===0?void 0:k(t,u.USAGE,`cloudflare ${e}: takes no arguments, got "${r.join(" ")}"`),Wr=async e=>{const{cwd:t,logger:r,options:o}=e;return Jr("ai-gateway",e)??Xe({cwd:t,dryRun:o.dryRun===!0,id:o.id,logger:r,logs:o.logs})},Hr=async({cwd:e,format:t,logger:r,options:o,rest:n})=>{const a=n[0]??"status";return xr(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}}):k(r,u.USAGE,`cloudflare alerts: unknown subcommand "${a}" — expected status | setup | test`)},Yr=async({cwd:e,format:t,logger:r,options:o,rest:n})=>{const a=await vr({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}},Kr=async({cwd:e,format:t,logger:r,options:o,rest:n})=>{const[a,s]=n;if(!kr(a))return k(r,u.USAGE,`cloudflare deployments: unknown subcommand "${a??""}" — expected list | status | inspect | rollback | promote`);const i=await Tr({confirmSharedState:o.confirmSharedState===!0,cwd:e,env:o.env,format:t,from:o.from,logger:r,message:o.message,percent:o.percent===void 0?void 0:Number(o.percent),subcommand:a,versionId:s,yes:o.yes===!0});return{code:i.code,delegated:i.delegated,error:i.error}},Vr=async({cwd:e,logger:t,options:r,rest:o})=>o.length>1?k(t,u.USAGE,`cloudflare profile: takes at most one argument (the worker), got "${o.join(" ")}"`):Lr({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]}),zr={"ai-gateway":Wr,alerts:Hr,containers:Yr,deployments:Kr,profile:Vr},fo=Ue(async({argument:e,cwd:t,format:r,logger:o,options:n})=>{const[a,...s]=e;if(a===void 0||a==="")return qr(o);const i=Gr(a,s);if(i===void 0)return k(o,u.USAGE,`cloudflare: unknown tool "${a}" — expected ${I.map(f=>f.name).join(" | ")}`);const{tool:c}=i,d=Br(t,c,n.target);return d!==void 0?k(o,u.USAGE,d):zr[c]({cwd:t,format:r,logger:o,options:n,rest:i.rest})});export{fo as execute};
1
+ import{existsSync as b,readFileSync as L,realpathSync as A}from"node:fs";import{join as h}from"node:path";import{readProjectTarget as u,DEFAULT_TARGET as f,readServiceBindings as B}from"@lunora/codegen";import{DEV_VARS_FILE as m,parseDevVariableEntries as C,isPlaceholderValue as O,readProjectDependencies as M,discoverSchemaInfo as G,inferLunoraBindings as V,resolveSchemaDirectory as K,probeCelldToolchain as q,D1_PLACEHOLDER_ID as W}from"@lunora/config";import{GLOBAL_FETCH_STRICTLY_PUBLIC_FLAG as g,resolveObservabilitySampling as y,findWranglerFile as T,readWranglerJsonc as D,buildBindingManifest as H,validateWranglerProject as z,UNEXPORTED_CLASS_MARKER as x,detectCloudflareCliConfig as J,collectExportGaps as Y}from"@lunora/config/cloudflare";import{a as Q,i as X,m as Z,c as ee,b as te,d as ne,e as oe,f as re}from"../packem_shared/vectorize-metadata-DK61NmVx.mjs";import{r as se,d as ae}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{r as ie,n as w,c as ce}from"../packem_shared/cloudflare-credentials-BVmZnDZk.mjs";import{d as le}from"../packem_shared/command-BpMv2n0o.mjs";import{i as de}from"../packem_shared/path-containment-CgxYZggb.mjs";import{A as $,a as R,b as k}from"../packem_shared/variables-CPYyJtsL.mjs";const ue=(o,t)=>{const e=new Set,n=s=>{for(const[a,c]of Object.entries(s??{}))typeof c=="string"&&c.trim().length>0&&e.add(a)};n(o.vars);for(const s of Object.values(o.env??{}))n(s.vars);const r=h(t,m);if(b(r))try{n(Object.fromEntries(C(L(r,"utf8")).map(s=>[s.key,s.value])))}catch{}return e},fe=(o,t,e,n)=>{if(o===void 0||!e)return;const r=ue(o,t),s=r.has($),a=o.ai?.binding;!s&&(typeof a!="string"||a.length===0)&&n.push({code:"ai-binding-missing",fix:`Run \`lunora dev\` (it adds the binding), add \`"ai": { "binding": "AI" }\` to wrangler.jsonc, or set ${$} to an OpenAI-compatible proxy.`,level:"warn",message:"the project uses ctx.ai (@lunora/ai / env.AI) but wrangler.jsonc declares no `ai` binding — model calls will fail at runtime."}),r.has(R)&&n.push({code:"ai-gateway-token-unused",fix:"Make the gateway unauthenticated for ctx.ai, or remove the token. A bring-your-own AI SDK provider built with `resolveAiGateway` does send it.",level:"warn",message:`${R} is set, but ctx.ai's Workers AI binding cannot send a gateway token — it is ignored on that path.`}),!s&&!r.has(k)&&n.push({code:"ai-gateway-default",fix:`Run \`lunora cloudflare ai-gateway\` to create a gateway for this app and write ${k} into wrangler vars.`,level:"info",message:`no ${k} in vars or ${m} — \`<provider>/<model>\` slugs route through the account's \`default\` AI Gateway.`})},pe=(o,t,e)=>{if(o===void 0||!t)return;const n=[];(o.compatibility_flags??[]).includes(g)||n.push("the top level");for(const[r,s]of Object.entries(o.env??{}))s.compatibility_flags!==void 0&&!s.compatibility_flags.includes(g)&&n.push(`env.${r}`);n.length>0&&e.push({code:"cimd-fetch-not-strictly-public",fix:`Add "${g}" to "compatibility_flags" in wrangler.jsonc.`,level:"warn",message:`@lunora/auth/cimd/workers is imported, but ${n.join(", ")} of wrangler.jsonc lacks the ${g} compatibility flag — workersCimdFetch() refuses to build without it.`})},N=5e3,he="https://api.cloudflare.com/client/v4/user/tokens/verify",U=o=>{if(typeof o!="object"||o===null||!("result"in o)||"success"in o&&o.success===!1)return;const{result:t}=o;return typeof t=="object"&&t!==null&&"status"in t&&typeof t.status=="string"?t.status:void 0},ge=async(o,t)=>{const e=await t(he,{headers:{Authorization:`Bearer ${o}`},signal:AbortSignal.timeout(N)}),n=await e.json().catch(()=>{});return{reported:e.ok?U(n):void 0,status:e.status}},me=async(o,t,e)=>{const n=await ce({accountId:o,apiToken:t,fetch:e,init:{signal:AbortSignal.timeout(N)},path:"/tokens/verify"});return n.ok?{reported:U(n.body),status:200}:{reported:void 0,status:n.status}},ve=async(o,t,e)=>{const n=await me(o,t,e);return n.reported!==void 0?n.reported==="active"?{verdict:"active"}:{verdict:"rejected"}:n.status===401||n.status===403?{verdict:"rejected"}:{reason:`HTTP ${String(n.status)}`,verdict:"unchecked"}},be=async(o,t,e)=>{const n=await ge(o,e);if(n.reported!==void 0)return n.reported==="active"?{verdict:"active"}:{verdict:"rejected"};if(n.status!==401&&n.status!==403)return{reason:`HTTP ${String(n.status)}`,verdict:"unchecked"};if(t.length===0)return{reason:"the user endpoint refused it, and no account id is set to check an account-owned token",verdict:"unchecked"};const r=await Promise.all(t.map(async s=>await ve(s,o,e).catch(a=>({reason:a instanceof Error?a.message:String(a),verdict:"unchecked"}))));return r.find(s=>s.verdict==="active")??r.find(s=>s.verdict==="unchecked")??{verdict:"rejected"}},we=o=>{const t=[o?.account_id,...Object.values(o?.env??{}).map(e=>e?.account_id)];return[...new Set(t.map(e=>w(e)).filter(e=>e!==void 0))]},ke=async(o,t,e)=>{const n=t.environment??process.env,r=we(o),{accountId:s,token:a}=ie(n,r[0]),c=w(n.CLOUDFLARE_ACCOUNT_ID)===void 0?r:[s].filter(d=>d!==void 0);if(a===void 0){e.push({code:"cloudflare-token-unchecked",fix:"Set CLOUDFLARE_API_TOKEN to verify it.",level:"info",message:"the Cloudflare API token was not verified: CLOUDFLARE_API_TOKEN is not set."});return}const i=t.fetch??globalThis.fetch.bind(globalThis);let l;try{l=await be(a,c,i)}catch(d){l={reason:d instanceof Error?d.message:String(d),verdict:"unchecked"}}l.verdict==="active"?e.push({code:"cloudflare-token-ok",level:"pass",message:"the Cloudflare API token is active."}):l.verdict==="rejected"?e.push({code:"cloudflare-token-rejected",fix:"Create a token at https://dash.cloudflare.com/profile/api-tokens with the Workers Scripts Edit permission, then set CLOUDFLARE_API_TOKEN to it.",level:"fail",message:"the Cloudflare API token is not active, so deploys with it will fail."}):e.push({code:"cloudflare-token-unchecked",level:"info",message:`the Cloudflare API token could not be verified (${l.reason}).`})},S=o=>{const{logs:t,traces:e}=y(o);return Object.entries({logs:t,traces:e}).filter(([,n])=>n.enabled&&n.headSamplingRate>=1).map(([n])=>n)},ye=(o,t)=>{if(o===void 0)return;const e=[],n=S(o.observability);n.length>0&&e.push(`${n.join(" + ")} (top level)`);for(const[r,s]of Object.entries(o.env??{})){const a=s?.observability;if(a===void 0)continue;const c=S(a);c.length>0&&e.push(`${c.join(" + ")} (env.${r})`)}e.length!==0&&t.push({code:"observability-full-sampling",fix:"For a high-traffic Worker, lower head_sampling_rate in wrangler.jsonc: under observability for logs, under observability.traces for traces — e.g. 0.1 keeps 10% of requests. Lunora never changes a rate you set.",level:"info",message:`observability samples every request (head_sampling_rate 1) for ${e.join(", ")}. From 2026-12-01 Workers Observability is billed: Free caps ingestion at 0.5 GB/day; Paid includes 50 GB per billing cycle, then $0.25/GB.`})},v=o=>o.enabled&&o.headSamplingRate>0,j=o=>{if(!o||o.redact_query_string===!0)return!1;const{logs:t,traces:e}=y(o);return v(t)||v(e)},E=o=>{const{logs:t,traces:e}=y(o);return[v(t)&&"request logs",v(e)&&"traces"].filter(Boolean).join(" and ")},_e=(o,t)=>{if(o===void 0)return;const e=[],n=new Set;j(o.observability)&&(e.push("top level"),n.add(E(o.observability)));for(const[r,s]of Object.entries(o.env??{})){const a=s?.observability;j(a)&&(e.push(`env.${r}`),n.add(E(a)))}e.length!==0&&t.push({code:"observability-query-unredacted",fix:'Set "redact_query_string": true in each observability block listed above in wrangler.jsonc. Lunora never changes a value you set.',level:"warn",message:`${[...n].join(" / ")} keep query strings (redact_query_string is not true) for ${e.join(", ")}. Emailed auth links carry their token in the query, so that token is stored with the request URL.`})},P={ai:"Workers AI",browser:"Browser Rendering",images:"Cloudflare Images (Image Transformations)"},I=["Argo Smart Routing","Log Explorer"],Ae=o=>{const t=[["top level",o],...Object.entries(o.env??{}).flatMap(([n,r])=>r?[[`env.${n}`,r]]:[])],e=new Map;for(const[n,r]of t)for(const s of H(r).bindings)P[s.type]!==void 0&&e.set(s.type,[...e.get(s.type)??[],n]);return e},xe=(o,t)=>{if((u(o)??f)!=="cloudflare")return;const e=T(o),n=e===void 0?void 0:D(e).parsed;if(n!==void 0)for(const[r,s]of Ae(n)){const a=P[r]??r;t.push({code:"paid-product-bound",fix:"Create an account budget alert in the dashboard: Manage Account > Billing > Billable Usage > Create budget alert. Lunora cannot create or read one.",level:"info",message:`${a} is bound (${s.join(", ")}) and billed per use. No documented usage-alert product covers it, and lunora cannot read budget alerts, so an account budget alert is the only cap.`})}t.push({code:"paid-product-unknown",level:"info",message:`enablement of ${I.join(" and ")} cannot be read by lunora (dashboard settings); check the dashboard if your account uses ${I.length>1?"them":"it"}.`})},$e=(o,t)=>{for(const e of B(o).services)for(const n of e.publicScopes){const r=n===""?"":` (env.${n})`;t.push({code:"service-workers-dev",fix:`If ${e.name} has no public route (custom domain or route, including ones set outside ${e.wranglerPath}), set \`"workers_dev": false\`${r}. Keep its internal auth (HMAC) either way.`,level:"warn",message:`service ${e.name} (${e.worker}) has no route in its wrangler config and still serves on workers.dev${r}; a custom domain set elsewhere would also be public.`})}},F=o=>{const t=T(o);if(t===void 0)return{parsed:void 0,path:void 0};const{parsed:e}=D(t);return{parsed:e,path:t}},Re=(o,t,e,n)=>{if(e===void 0){n.push({code:"wrangler-missing",fix:"Run `lunora init` (or `lunora dev`) to scaffold and reconcile wrangler.jsonc.",level:"fail",message:"wrangler.jsonc not found."});return}if(t===void 0){n.push({code:"wrangler-unparseable",fix:`Check ${e} is valid JSONC.`,level:"fail",message:`Could not parse ${e}.`});return}const{report:r}=z({projectRoot:o});for(const c of r.errors.filter(i=>i.includes(x)))n.push({code:"wrangler-class-unexported",level:"fail",message:c});for(const c of r.warnings.filter(i=>i.includes("LUNORA_ORIGIN_URL")))n.push({code:"scheduler-origin-missing",fix:"Set LUNORA_ORIGIN_URL in wrangler vars to the worker's public URL (or `wrangler secret put LUNORA_ORIGIN_URL`).",level:"warn",message:c});const s=c=>c.includes(x)||c.includes("SHARD");for(const c of r.errors.filter(i=>!s(i)))n.push({code:"wrangler-invalid",fix:"Fix the reported wrangler.jsonc problem; `lunora verify` reports the same set.",level:"fail",message:c});for(const c of r.warnings.filter(i=>!i.includes("LUNORA_ORIGIN_URL")))n.push({code:"wrangler-advisory",level:"warn",message:c});const a=r.errors.find(c=>c.includes("SHARD"));a===void 0?n.push({code:"wrangler-shard-binding-ok",level:"pass",message:"wrangler.jsonc present with a SHARD durable-object binding."}):n.push({code:"wrangler-shard-binding-missing",fix:"Run `lunora dev` to auto-reconcile, or add the binding manually.",level:"fail",message:a})},Se=(o,t)=>{b(h(o,"lunora.json"))&&t.push({code:"stale-lunora-json",fix:'Move `target` / `remote` into `lunora.config.ts` (`export default { target: "…" }`), then delete lunora.json.',level:"warn",message:"lunora.json is present but no longer read — lunora.config.* replaced it, so any `target` or `remote` in it is being ignored."})},je=(o,t)=>{const e=J(o);e!==void 0&&t.push({code:"cf-config-present",fix:e.fix,level:"warn",message:e.message})},Ee=(o,t)=>{o===void 0||o.limits?.cpu_ms!==void 0||t.push({code:"cpu-limit-missing",fix:'Add `"limits": { "cpu_ms": 30000 }` to wrangler.jsonc, tuned to your slowest legitimate handler.',level:"info",message:"no limits.cpu_ms is set — a runaway handler can burn CPU up to the platform default before anything stops it."})},Ie=(o,t)=>{const e=(o?.r2_buckets??[]).map(n=>n?.bucket_name).filter(n=>typeof n=="string"&&n.length>0);e.length!==0&&t.push({code:"r2-lifecycle-unset",fix:"wrangler r2 bucket lifecycle list <bucket> — add an abort-incomplete-multipart rule if none exists.",level:"info",message:`R2 bucket(s) ${e.join(", ")}: verify a lifecycle rule aborts incomplete multipart uploads — orphaned parts are billed but invisible in a listing.`})},Le=(o,t)=>{const{error:e,info:n}=G(o,"lunora");if(e!==void 0){t.push({code:"schema-unreadable",fix:"Fix the parse error, then re-run `lunora doctor`. `lunora codegen` reports the same failure with the offending source.",level:"fail",message:`lunora/schema.ts could not be parsed, so every schema-derived check was skipped: ${e}`});return}for(const r of n?.vectorMetadata??[]){const s=Z(r.kind);if(s===void 0){t.push({code:"vector-metadata-unfilterable",fix:"Filter on a string, number or boolean column, or drop it from `metadata`.",level:"warn",message:`vector index "${r.index}" declares metadata "${r.property}", whose type Vectorize cannot filter on.`});continue}t.push({code:"vector-metadata-index-required",fix:`wrangler ${ee({index:r.index,property:r.property,type:s}).join(" ")}`,level:"info",message:`vector index "${r.index}" filters on metadata "${r.property}" — that needs a Vectorize metadata index (\`lunora deploy\` creates it).`})}},Ce=o=>{const t=o?.d1_databases;return Array.isArray(t)?t.filter(Boolean):[]},Oe=(o,t,e)=>{const n=Ce(o),r=[];for(const s of n){const a=typeof s.database_id=="string"?s.database_id:"";if(e?oe(a)&&a!==W:re(a)){const i=typeof s.binding=="string"&&s.binding.length>0?s.binding:"<unnamed>";r.push({code:"d1-placeholder-id",fix:e?"Set database_id to the database celld should use.":"Run `lunora doctor --fix` to create the database and write its id into wrangler.jsonc, or run `wrangler d1 create <name>` and paste the returned database_id in yourself.",level:"fail",message:`D1 binding "${i}"${t} has a placeholder database_id ("${a||"<empty>"}").`})}}return r},Te=(o,t,e)=>{if(t===void 0)return;const n=(u(o)??f)==="celld",r=[{config:t,suffix:""},...Object.entries(n?{}:t.env??{}).map(([s,a])=>({config:a,suffix:` in env.${s}`}))];for(const{config:s,suffix:a}of r)e.push(...Oe(s,a,n))},De=(o,t)=>{if(o===void 0)return;const e=(o.send_email??[]).filter(Boolean);for(const n of e){const r=typeof n.destination_address=="string"?n.destination_address:"";if(r!==""&&O(r)){const s=typeof n.name=="string"&&n.name.length>0?n.name:"send_email";t.push({code:"email-destination-placeholder",fix:"Set destination_address to a verified Cloudflare Email Routing address.",level:"warn",message:`send_email binding "${s}" has a placeholder destination_address ("${r}").`})}}},Ne=(o,t)=>{const e=h(o,m);if(!b(e))return;let n;try{n=L(e,"utf8")}catch{return}const r=C(n).filter(s=>X(s.key)&&O(s.value)).map(s=>s.key);r.length>0&&t.push({code:"dev-vars-missing-secret",fix:"Run `lunora dev` to auto-generate secrets, or fill them in by hand.",level:"warn",message:`${m} has unfilled secret value(s): ${r.join(", ")}.`})},Ue=(o,t)=>{const{source:e}=se({cwd:o});e===void 0?t.push({code:"admin-token-missing",fix:"Set LUNORA_ADMIN_TOKEN (env or `.dev.vars`) to enable admin RPCs / studio.",level:"info",message:"LUNORA_ADMIN_TOKEN is not set."}):t.push({code:"admin-token-set",level:"pass",message:`LUNORA_ADMIN_TOKEN is set (${ae(e)}).`})},Pe=async(o,t)=>{try{return await V({projectRoot:o,schemaDir:K(o)})}catch(e){t.push({code:"declared-export-unchecked",fix:"Make sure the worker entry resolves (see `lunora codegen`), then re-run.",level:"warn",message:`could not check whether declared containers/workflows/agents are re-exported by the worker entry: ${e instanceof Error?e.message:String(e)}`});return}},Fe=(o,t)=>{const e=Y(o),n=[...o.containers.map(r=>({...r,kind:"container"})),...o.workflows.map(r=>({...r,kind:"workflow"})),...o.agents.map(r=>({...r,kind:"agent"}))];for(const r of n.filter(s=>s.exported))t.push({code:"declared-export-ok",level:"pass",message:`${r.kind} "${r.exportName}" is exported by the worker entry.`});for(const r of e)t.push({code:"declared-export-missing",fix:`Add \`export * from "./lunora/_generated/${r.module}"\` to your worker entry (or re-run \`vis generate lunora-${r.kind}\`).`,level:"fail",message:`${r.kind} "${r.exportName}" is declared but ${r.className} is not exported by the worker entry.`})},Be=/^[\^~><= ]+/u,Me=/^(?<core>\d+\.\d+\.\d+)(?:-(?<channel>[a-z]+)\.(?<counter>\d+))?$/u,Ge=o=>{const t=o.replace(Be,"").trim(),e=Me.exec(t);if(!e?.groups)return;const{channel:n,core:r,counter:s}=e.groups;return{channel:n??"",core:r??"",counter:s===void 0?void 0:Number.parseInt(s,10),raw:t}},Ve=(o,t)=>{const e=M(o),n=[];for(const[i,l]of Object.entries(e)){if(i!=="lunorash"&&!i.startsWith("@lunora/"))continue;const d=Ge(l);d&&n.push({name:i,version:d})}if(n.length<2)return;const r=i=>i.map(l=>`${l.name}@${l.version.raw}`).join(", "),s=new Set(n.map(i=>i.version.core)),a=new Set(n.map(i=>i.version.channel));if(s.size>1){t.push({code:"version-skew-cores",fix:'Run `pnpm update "@lunora/*" lunorash` (or `npm`/`yarn` equivalent) so every Lunora package moves to the same release.',level:"warn",message:`Lunora packages span ${String(s.size)} different versions: ${r(n)}.`});return}if(a.size>1){t.push({code:"version-skew-channels",fix:"Pick one channel (all stable, or all alpha/beta) and update the odd package out.",level:"warn",message:`Lunora packages mix release channels (${[...a].map(i=>i===""?"stable":i).join(" + ")}): ${r(n)}.`});return}const c=n.map(i=>i.version.counter).filter(i=>i!==void 0);if(c.length>1){const i=Math.min(...c),l=Math.max(...c);t.push({code:"version-counter-spread",level:"info",message:c.length===n.length&&i===l?`Lunora packages are all at ${[...a][0]??""}.${String(l)}.`:`Lunora pre-release counters span ${String(i)}–${String(l)}: ${r(n)}.`})}},Ke=[h("@lunora","cli"),"lunorash"],qe=(o,t,e)=>{if(t===void 0)return;const n=[];for(const s of Ke){const a=h(o,"node_modules",s);if(b(a))try{n.push(A(a))}catch{}}if(n.length===0)return;let r;try{r=A(t)}catch{return}n.some(s=>de(s,r))||e.push({code:"cli-shadowed",fix:"Run the project's own CLI: `pnpm exec lunora …` (or `npx lunora …`).",level:"warn",message:`the running lunora (${r}) is not the project's own install (${n.join(", ")}).`})},We={full:{code:"do-class-budget-full",level:"warn"},near:{code:"do-class-budget-near",level:"warn"},ok:{code:"do-class-budget-ok",level:"pass"},unchecked:{code:"do-class-budget-unchecked",level:"info"}},He=o=>{const t=new Map,e=(n,r)=>{const s=w(n);s!==void 0&&t.set(s,[...t.get(s)??[],r])};e(o?.account_id,"top level");for(const[n,r]of Object.entries(o?.env??{}))e(r?.account_id,`env.${n}`);return t},ze=async(o,t,e,n)=>{if((u(o)??f)!=="cloudflare")return;const s=w((e.environment??process.env).CLOUDFLARE_ACCOUNT_ID)!==void 0?[]:[...He(t)],a=s.length===0?[[void 0,[]]]:s,c=await Promise.all(a.map(async([i,l])=>({accountId:i,blocks:l,budget:await te({accountId:i,environment:e.environment,fetch:e.fetch})})));for(const{accountId:i,blocks:l,budget:d}of c)n.push({...We[d.verdict],message:c.length>1?`account ${String(i)} (${l.join(", ")}): ${d.message}`:d.message,...d.fix===void 0?{}:{fix:d.fix}})},Je="CELLD_BUCKET is not set — a live `lunora deploy` needs it to name the fleet bucket; `lunora dev` and a dry run do not.",Ye=async(o,t,e)=>{if((u(o)??f)!=="celld")return;const n={...process.env,...t.environment},r=await q({dryRun:!0,env:n,purpose:"deploy"}),s=(n.CELLD_BUCKET??"").trim()===""?[...r.warnings,Je]:r.warnings;for(const a of r.errors)e.push({code:"celld-toolchain-missing",level:"fail",message:a});for(const a of s)e.push({code:"celld-toolchain-warn",level:"warn",message:a});r.errors.length===0&&s.length===0&&e.push({code:"celld-toolchain-ok",level:"pass",message:"celld, esbuild and CELLD_BUCKET are in place for a deploy."})},Qe={mismatch:{code:"artifacts-jurisdiction-mismatch",level:"fail"},missing:{code:"artifacts-namespace-missing",level:"fail"},ok:{code:"artifacts-jurisdiction-ok",level:"pass"},unchecked:{code:"artifacts-jurisdiction-unchecked",level:"warn"}},Xe=async(o,t,e,n,r)=>{if(e===void 0||t===void 0||(u(o)??f)!=="cloudflare")return;const s=[["",t],...Object.entries(t.env??{}).map(([i,l])=>[`env.${i}: `,l])],a=new Map;for(const[i,l]of s){const d=l.account_id??t.account_id;for(const p of l.artifacts??[]){const _=`${String(d)}/${String(p?.namespace)}`;typeof p?.binding=="string"&&typeof p.namespace=="string"&&!a.has(_)&&a.set(_,{accountId:d,binding:p.binding,label:i,namespace:p.namespace})}}const c=await Promise.all([...a.values()].map(async({label:i,...l})=>({check:await ne({...l,environment:n.environment,fetch:n.fetch,jurisdiction:e,missingOk:!0}),label:i})));for(const{check:i,label:l}of c)r.push({...Qe[i.verdict],message:`${l}${i.message}`,...i.fix===void 0?{}:{fix:i.fix}})},Ze=async o=>{const t=o.cwd??process.cwd(),e=[],{parsed:n,path:r}=F(t);Re(t,n,r,e),je(t,e),Te(t,n,e),De(n,e),Ee(n,e),Ie(n,e),ye(n,e),_e(n,e),Ne(t,e),Ue(t,e),Ve(t,e),Le(t,e),Se(t,e),qe(t,o.executablePath??process.argv[1],e),$e(t,e),xe(t,e);const s=await Pe(t,e);s!==void 0&&Fe(s,e),fe(n,t,s?.usesAi===!0,e),await Ye(t,o,e),await ze(t,n,o,e),(u(t)??f)==="cloudflare"&&await ke(n,o,e),await Xe(t,n,s?.jurisdiction,o,e),pe(n,s?.usesCimdWorkers===!0,e);const a={fail:0,info:0,pass:0,warn:0};for(const i of e)a[i.level]+=1;const c=a.fail>0?1:0;return{code:c,findings:e,ok:c===0,summary:a}},et={fail:"FAIL",info:"INFO",pass:"PASS",warn:"WARN"},tt=(o,t)=>{t.info("lunora doctor — project preflight");for(const r of o.findings){const s=`[${et[r.level]}] ${r.message}`;r.level==="fail"?t.error(s):r.level==="warn"?t.warn(s):t.info(s),r.fix!==void 0&&r.level!=="pass"&&t.info(` fix: ${r.fix}`)}const{fail:e,warn:n}=o.summary;e>0?t.error(`${String(e)} failure(s), ${String(n)} warning(s).`):n>0?t.warn(`0 failures, ${String(n)} warning(s).`):t.success("all checks passed.")},nt=async o=>{const{logger:t}=o,e=await Ze({...o});return tt(e,t),e},ht=le(async({cwd:o,format:t,logger:e,options:n})=>{if(n.fix===!0){const{path:s}=F(o),a=await Q({configPath:s,cwd:o,dryRun:n.dryRun===!0,logger:e});for(const c of a.applied)e.info(`fix: ${c}`);for(const c of a.skipped)e.warn(`not fixed: ${c}`)}const r=await nt({cwd:o,format:t,logger:e});return{code:r.code,data:{findings:r.findings,summary:r.summary}}});export{ht as execute,Ze as runDoctor,nt as runDoctorCommand};