@lunora/cli 1.0.0-alpha.164 → 1.0.0-alpha.166

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 (112) hide show
  1. package/dist/bin.mjs +1 -1
  2. package/dist/index.d.mts +0 -2
  3. package/dist/index.d.ts +0 -2
  4. package/dist/index.mjs +1 -1
  5. package/dist/packem_chunks/handler.mjs +1 -1
  6. package/dist/packem_chunks/handler10.mjs +2 -2
  7. package/dist/packem_chunks/handler11.mjs +2 -2
  8. package/dist/packem_chunks/handler12.mjs +1 -1
  9. package/dist/packem_chunks/handler13.mjs +1 -1
  10. package/dist/packem_chunks/handler14.mjs +1 -1
  11. package/dist/packem_chunks/handler15.mjs +1 -1
  12. package/dist/packem_chunks/handler16.mjs +2 -2
  13. package/dist/packem_chunks/handler17.mjs +1 -1
  14. package/dist/packem_chunks/handler18.mjs +1 -1
  15. package/dist/packem_chunks/handler19.mjs +7 -7
  16. package/dist/packem_chunks/handler2.mjs +2 -2
  17. package/dist/packem_chunks/handler20.mjs +2 -2
  18. package/dist/packem_chunks/handler21.mjs +2 -2
  19. package/dist/packem_chunks/handler22.mjs +3 -3
  20. package/dist/packem_chunks/handler23.mjs +3 -3
  21. package/dist/packem_chunks/handler24.mjs +1 -1
  22. package/dist/packem_chunks/handler25.mjs +19 -19
  23. package/dist/packem_chunks/handler26.mjs +9 -9
  24. package/dist/packem_chunks/handler3.mjs +1 -1
  25. package/dist/packem_chunks/handler4.mjs +1 -1
  26. package/dist/packem_chunks/handler5.mjs +1 -1
  27. package/dist/packem_chunks/handler6.mjs +1 -1
  28. package/dist/packem_chunks/handler7.mjs +3 -3
  29. package/dist/packem_chunks/handler8.mjs +1 -1
  30. package/dist/packem_chunks/handler9.mjs +1 -1
  31. package/dist/packem_chunks/planDevCommand.mjs +6 -6
  32. package/dist/packem_chunks/runCodegenCommand.mjs +3 -3
  33. package/dist/packem_chunks/runDeployCommand.mjs +1 -1
  34. package/dist/packem_chunks/runInitCommand.mjs +46 -46
  35. package/dist/packem_chunks/runMigrateGenerateCommand.mjs +8 -8
  36. package/dist/packem_chunks/runResetCommand.mjs +1 -1
  37. package/dist/packem_chunks/runRpcCommand.mjs +1 -1
  38. package/dist/packem_shared/COMMANDS-BWf5k_qi.mjs +1 -0
  39. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-D5cNE-NH.mjs +1 -0
  40. package/dist/packem_shared/admin-token-rxXZbVMZ.mjs +1 -0
  41. package/dist/packem_shared/admin-url-Cil3Or6N.mjs +1 -0
  42. package/dist/packem_shared/advisory-gate-Cl8IEFIj.mjs +1 -0
  43. package/dist/packem_shared/api-spec-lYyq4vL6.mjs +1 -0
  44. package/dist/packem_shared/buildRegistryIndex-Zi3bBqpc.mjs +1 -0
  45. package/dist/packem_shared/cli-ULexksQd.mjs +3 -0
  46. package/dist/packem_shared/codegen-error-C04fGQjf.mjs +3 -0
  47. package/dist/packem_shared/command-DwC11Cwe.mjs +1 -0
  48. package/dist/packem_shared/commands-B-YnEi2t.mjs +19 -0
  49. package/dist/packem_shared/createLogger-hGafwf-3.mjs +2 -0
  50. package/dist/packem_shared/createRecordingSpawner-DJlNacZ6.mjs +1 -0
  51. package/dist/packem_shared/deploy-target-D9GPy_tq.mjs +1 -0
  52. package/dist/packem_shared/detect-package-manager-DSaAqRof.mjs +1 -0
  53. package/dist/packem_shared/diffSnapshots-CIOFQN_a.mjs +5 -0
  54. package/dist/packem_shared/{docker-CKvYE9YF.mjs → docker-DpVxvYpL.mjs} +1 -1
  55. package/dist/packem_shared/health-probe-QEPfFdgJ.mjs +1 -0
  56. package/dist/packem_shared/import-Db3Gk4mx.mjs +12 -0
  57. package/dist/packem_shared/insertSchemaExtension-DY4pA8wE.mjs +8 -0
  58. package/dist/packem_shared/lint-ignore-report-0sVOnXcO.mjs +2 -0
  59. package/dist/packem_shared/open-url-EnKy--w-.mjs +1 -0
  60. package/dist/packem_shared/output-format-DfogXx0p.mjs +2 -0
  61. package/dist/packem_shared/parseManifest-CwPTKdtS.mjs +1 -0
  62. package/dist/packem_shared/path-containment-CgxYZggb.mjs +1 -0
  63. package/dist/packem_shared/platform-diagnostics-uOXqysk3.mjs +4 -0
  64. package/dist/packem_shared/post-codegen-hook-DRdEoTsQ.mjs +1 -0
  65. package/dist/packem_shared/resolve-DZAGzg67.mjs +1 -0
  66. package/dist/packem_shared/resolve-target-C_ZloTvd.mjs +1 -0
  67. package/dist/packem_shared/runAddCommand-BZty6_vX.mjs +1 -0
  68. package/dist/packem_shared/runExportCommand-DmXKEWSq.mjs +5 -0
  69. package/dist/packem_shared/{schema-drift-gate-d12lMICD.mjs → schema-drift-gate-AscQpYH5.mjs} +1 -1
  70. package/dist/packem_shared/schemaIrToSnapshot-qpRoV7HY.mjs +1 -0
  71. package/dist/packem_shared/shared-D-zCOmgY.mjs +1 -0
  72. package/dist/packem_shared/tui-prompts-Dd0pDuNr.mjs +4 -0
  73. package/dist/packem_shared/vectorize-metadata-Cs8ycNaL.mjs +1 -0
  74. package/dist/packem_shared/wrangler-name-Dsk5K1f-.mjs +1 -0
  75. package/dist/packem_shared/wrangler-secrets-CE7jcf8E.mjs +1 -0
  76. package/package.json +23 -22
  77. package/dist/packem_shared/COMMANDS-BJhEvtLN.mjs +0 -1
  78. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-D7L8R74L.mjs +0 -1
  79. package/dist/packem_shared/admin-token-BKmc3AUm.mjs +0 -1
  80. package/dist/packem_shared/admin-url-Ca-KI3d_.mjs +0 -1
  81. package/dist/packem_shared/advisory-gate-yaOOyUQl.mjs +0 -1
  82. package/dist/packem_shared/api-spec-BENwiyUa.mjs +0 -1
  83. package/dist/packem_shared/buildRegistryIndex-DwySASBu.mjs +0 -1
  84. package/dist/packem_shared/cli-Cu92injU.mjs +0 -3
  85. package/dist/packem_shared/codegen-error-DJN6pTH5.mjs +0 -3
  86. package/dist/packem_shared/command-0l-ZPhIX.mjs +0 -1
  87. package/dist/packem_shared/commands-DB63_8xW.mjs +0 -19
  88. package/dist/packem_shared/createLogger-BoSxdb2T.mjs +0 -2
  89. package/dist/packem_shared/createRecordingSpawner-SKs4R1fc.mjs +0 -1
  90. package/dist/packem_shared/deploy-target-Dvr9vxpR.mjs +0 -1
  91. package/dist/packem_shared/detect-package-manager-DXDstphE.mjs +0 -1
  92. package/dist/packem_shared/diffSnapshots-cgOtkd-G.mjs +0 -5
  93. package/dist/packem_shared/health-probe-CiFgh1hn.mjs +0 -1
  94. package/dist/packem_shared/import-C9in1wC3.mjs +0 -12
  95. package/dist/packem_shared/insertSchemaExtension-DZReBZ4_.mjs +0 -8
  96. package/dist/packem_shared/lint-ignore-report-m43j10IE.mjs +0 -2
  97. package/dist/packem_shared/open-url-zbbAo_D7.mjs +0 -1
  98. package/dist/packem_shared/output-format-Cv3aLqhP.mjs +0 -2
  99. package/dist/packem_shared/parseManifest-x3WsxKHz.mjs +0 -1
  100. package/dist/packem_shared/path-containment-CcTCKfzV.mjs +0 -1
  101. package/dist/packem_shared/platform-diagnostics-C4TFj5Pu.mjs +0 -4
  102. package/dist/packem_shared/post-codegen-hook-DhL1RH5u.mjs +0 -1
  103. package/dist/packem_shared/resolve-BZp6jitE.mjs +0 -1
  104. package/dist/packem_shared/resolve-target-CeiNrCAx.mjs +0 -1
  105. package/dist/packem_shared/runAddCommand-DiEQBX7C.mjs +0 -1
  106. package/dist/packem_shared/runExportCommand-BpE4AbuX.mjs +0 -5
  107. package/dist/packem_shared/schemaIrToSnapshot-DV2DilTz.mjs +0 -1
  108. package/dist/packem_shared/shared-Ce9bKz5c.mjs +0 -1
  109. package/dist/packem_shared/tui-prompts-BU3irGxV.mjs +0 -4
  110. package/dist/packem_shared/vectorize-metadata-BvZbbqUD.mjs +0 -1
  111. package/dist/packem_shared/wrangler-name-CHDf3rMP.mjs +0 -1
  112. package/dist/packem_shared/wrangler-secrets-D0Tv5GWn.mjs +0 -1
@@ -1,3 +1,3 @@
1
- import M,{join as l,resolve as S}from"node:path";import{isInteractive as C,promptYesNo as F}from"@lunora/config";import{backupObjectKey as k,isBackupManifestEntry as U,normalizeBackupPrefix as J,BACKUP_KEY_PREFIX as G,backupManifestKey as H,isBackupManifestKey as W,backupObjectKeyOfManifest as A}from"@lunora/runtime";import{l as R}from"../packem_shared/admin-token-BKmc3AUm.mjs";import{u as y}from"../packem_shared/admin-url-Ca-KI3d_.mjs";import{i as Y}from"../packem_shared/command-0l-ZPhIX.mjs";import{d as X}from"../packem_shared/resolve-target-CeiNrCAx.mjs";import{readAndLogBody as m}from"./runRpcCommand.mjs";import{randomUUID as j,createHash as Q}from"node:crypto";import{existsSync as $,createReadStream as V,createWriteStream as Z}from"node:fs";import{mkdir as tt,rm as g,rename as B,readFile as P,writeFile as et,realpath as N,mkdtemp as x}from"node:fs/promises";import{LunoraError as f}from"@lunora/errors";import{e as T}from"../packem_shared/path-containment-CcTCKfzV.mjs";import{tmpdir as I}from"node:os";import{Readable as rt}from"node:stream";import{pipeline as ot}from"node:stream/promises";import{m as nt,a as E,b as at,c as it,S as st}from"../packem_shared/import-C9in1wC3.mjs";import{runExportCommand as ct}from"../packem_shared/runExportCommand-BpE4AbuX.mjs";const b="manifest.json",L=async t=>{const e=Q("sha256");let o=0;for await(const r of V(t)){const n=r;o+=n.byteLength,e.update(n)}return{bytes:o,sha256:e.digest("hex")}},_=async t=>{const e=l(t,b);if(!$(e))return[];let o;try{o=JSON.parse(await P(e,"utf8"))}catch(r){const n=r instanceof Error?r.message:String(r);throw new f("INTERNAL",`backup: ${e} exists but is not valid JSON (${n}) — refusing to overwrite it; fix or remove it manually`,{cause:r})}if(!Array.isArray(o))throw new TypeError(`backup: ${e} exists but is not a JSON array — refusing to overwrite it; fix or remove it manually`);return o.filter(r=>U(r))},dt=async(t,e)=>{const o=l(t,`${b}.${j()}.tmp`);try{await et(o,`${JSON.stringify(e,void 0,2)}
2
- `,"utf8"),await B(o,l(t,b))}catch(r){throw await g(o,{force:!0}),r}},ut=async(t,e)=>{const o=S(t),r=S(o,e.file),n=()=>{throw new f("INTERNAL",`backup: entry ${e.id} points outside ${o} (${e.file}) — refusing to read it`)};if(T(o,r)||n(),!!$(r))return T(await N(o),await N(r))||n(),r},lt=t=>{const e=o=>k("",o);return{commit:async(o,r)=>{await B(r,l(t,o))},label:t,list:async()=>_(t),locate:e,materialize:async(o,r)=>(a=>a===void 0?void 0:{path:a,release:()=>Promise.resolve()})(o===void 0?$(r)?r:void 0:await ut(t,o)),record:async o=>{const r=await _(t);r.push(o),await dt(t,r)},stage:async o=>{await tt(t,{recursive:!0});const r=l(t,`${e(o)}.${j()}.partial`);return{path:r,release:()=>g(r,{force:!0})}}}},pt="/_lunora/admin/storage/object",ft="/_lunora/admin/storage",O=8,gt=(t,e=M)=>{const o=e.basename(t);return o===""||o==="."||o===".."?"snapshot.ndjson":o},ht=t=>{const{context:e,logger:o}=t,r=J(t.prefix??G),n=`bucket ${e.bucket??"(default)"} under ${r}`,a=it(e),u=s=>`${e.baseUrl}${pt}?key=${encodeURIComponent(s)}${a}`,h=async s=>{const c=await e.fetchImpl(u(s),{headers:{authorization:`Bearer ${e.token}`},method:"GET"});if(!c.ok){const i=await c.text().catch(()=>"<no body>");throw new f("INTERNAL",`backup: could not read ${s} (HTTP ${String(c.status)}): ${i}`)}return c.text()},K=async s=>{try{const c=JSON.parse(await h(s));if(U(c))return c;o.warn(`backup: ignoring ${s} — not a backup manifest`)}catch(c){o.warn(`backup: ignoring ${s} — ${c instanceof Error?c.message:String(c)}`)}};return{commit:async(s,c,i)=>{if(i.bytes>E)throw new f("INTERNAL",`backup: the snapshot is ${String(i.bytes)} bytes, above the ${String(E)}-byte limit for a checksum-verified upload — nothing was written. Narrow it with \`--tables\`, or write it to a directory with \`--dir\` and move the file yourself (\`wrangler r2 object put\`).`);const d=await P(c);await at(e,s,d,{contentType:"application/x-ndjson",id:s,sha256:i.sha256,size:i.bytes},o)},label:n,list:async()=>{const s=(await nt(e,r)).map(i=>i.key).filter(i=>W(i)),c=[];for(let i=0;i<s.length;i+=O){const d=await Promise.all(s.slice(i,i+O).map(async p=>K(p)));c.push(...d.filter(p=>p!==void 0))}return c.toSorted((i,d)=>i.id.localeCompare(d.id))},locate:s=>k(r,s),materialize:async(s,c)=>{const i=s?.file??c,d=await e.fetchImpl(u(i),{headers:{authorization:`Bearer ${e.token}`},method:"GET"});if(d.status===404)return;if(!d.ok||d.body===null){const w=await d.text().catch(()=>"<no body>");throw new f("INTERNAL",`backup: could not download ${i} (HTTP ${String(d.status)}): ${w}`)}const p=await x(l(I(),"lunora-backup-")),v=l(p,gt(i));try{await ot(rt.from(d.body),Z(v))}catch(w){throw await g(p,{force:!0,recursive:!0}),w}return{path:v,release:async()=>g(p,{force:!0,recursive:!0})}},record:async s=>{const c=H(s.file),i=await e.fetchImpl(`${e.baseUrl}${ft}?key=${encodeURIComponent(c)}${a}`,{body:`${JSON.stringify(s,void 0,2)}
3
- `,headers:{authorization:`Bearer ${e.token}`,"content-type":"application/json"},method:"PUT"});if(!i.ok){const d=await i.text().catch(()=>"<no body>");throw new f("INTERNAL",`backup: snapshot ${s.file} was written but its manifest was not (HTTP ${String(i.status)}): ${d}`)}},stage:async s=>{const c=await x(l(I(),"lunora-backup-"));return{path:l(c,k("",s)),release:async()=>g(c,{force:!0,recursive:!0})}}}},mt=".lunora-backups",D="/_lunora/admin/backup/retention",wt="/_lunora/admin/backup/prune",kt="/_lunora/admin/pitr",bt="__lunora_admin__:getPitrBookmark",yt="__lunora_admin__:pitrRestore",$t=async(t,e)=>{const o=(t.now??(()=>new Date))().toISOString(),r=await e.stage(o);try{const n=await ct({cwd:t.cwd,fetchImpl:t.fetchImpl,logger:t.logger,out:r.path,prod:t.prod,tables:t.tables,token:t.token,url:t.url});if(n.code!==0)return{code:n.code};const a=e.locate(o),u=await L(r.path);await e.commit(a,r.path,u);const h={bytes:u.bytes,createdAt:o,file:a,id:o,rows:n.rows,sha256:u.sha256,tables:t.tables};return await e.record(h),t.logger.success(`backup created: ${a} (${n.rows.toString()} rows, ${u.bytes.toString()} bytes)`),{code:0,entry:h}}finally{await r.release().catch(n=>{t.logger.warn(`backup: could not clean up staging (${n instanceof Error?n.message:String(n)})`)})}},vt=async(t,e,o)=>{if(e?.sha256===void 0)return o.error(e===void 0?"--verify needs a recorded checksum, and a snapshot restored by path/key has no manifest entry — restore it by its backup id instead":`--verify: backup ${e.id} carries no recorded checksum — it was taken by a release before checksums existed`),{code:1};const r=await L(t);if(r.sha256!==e.sha256)return o.error(`--verify: ${e.file} does not match its recorded checksum (expected ${e.sha256}, got ${r.sha256}) — nothing was imported`),{code:1};o.success(`verified ${e.file} against its recorded sha256`)},St=async(t,e)=>{const o=await e.list();if(o.length===0)return t.logger.info(`no backups found in ${e.label}`),{code:0};for(const r of o)t.logger.info(`${r.id} ${r.rows.toString()} rows ${r.bytes.toString()} bytes ${r.file}`);return{code:0}},Nt=async(t,e)=>{const{target:o}=t;if(o===void 0||o.length===0)return t.logger.error("restore requires a backup id or file path. Usage: lunora backup restore <id|file>"),{code:1};const r=(await e.list()).find(a=>a.id===o),n=await e.materialize(r,o);if(n===void 0)return t.logger.error(`backup not found: ${o}`),{code:1};try{if(t.verify===!0){const a=await vt(n.path,r,t.logger);if(a!==void 0)return a}return{code:(await st({cwd:t.cwd,fetchImpl:t.fetchImpl,file:n.path,logger:t.logger,prod:t.prod,token:t.token,url:t.url,yes:t.yes})).code}}finally{await n.release().catch(a=>{t.logger.warn(`backup: could not clean up the downloaded snapshot (${a instanceof Error?a.message:String(a)})`)})}},xt=t=>{const e=t.token??process.env.LUNORA_ADMIN_TOKEN;if(!e){t.logger.error("admin token required — pass --token or set LUNORA_ADMIN_TOKEN");return}if(t.prod&&t.url===void 0){t.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)");return}if(t.restore===!0&&t.at===void 0&&t.bookmark===void 0){t.logger.error("pitr --restore requires --at <time> or --bookmark <bookmark>");return}if(t.restore===!0&&t.prod===!0&&t.yes!==!0){t.logger.error("pitr --restore --prod restores production data in place. Re-run with --yes to confirm.");return}const o=y(t.url,t.logger,t.cwd);if(o===void 0)return;const r=t.adminFetch??globalThis.fetch;if(typeof r!="function")throw new TypeError("no fetch implementation available — pass pitrFetch or run on Node >= 18");return{fetchImpl:r,requestUrl:`${o}${kt}`,token:e}},Tt=(t,e)=>{const o={};return t.at!==void 0&&(o.time=t.at),e&&t.bookmark!==void 0&&(o.bookmark=t.bookmark),e&&t.restart===!0&&(o.restart=!0),o},It=async t=>{const e=xt(t);if(e===void 0)return{code:1};const o=t.restore===!0,r=o?yt:bt,n=Tt(t,o),a=o?"restore":"bookmark";t.logger.info(`POST ${e.requestUrl} -> pitr ${a}${t.shard===void 0?"":` (shard "${t.shard}")`}`);const u=await e.fetchImpl(e.requestUrl,{body:JSON.stringify({args:n,functionPath:r,shardKey:t.shard}),headers:{authorization:`Bearer ${e.token}`,"content-type":"application/json"},method:"POST"});return await m(u,t.logger),{code:u.ok?0:1}},Et=(t,e)=>{if(t.bucket===void 0)return lt(l(e,t.dir??mt));if(t.prod===!0&&t.url===void 0){t.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)");return}const o=y(t.url,t.logger,t.cwd);if(o===void 0)return;const{token:r}=R({cwd:e,token:t.token,url:o});if(!r){t.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)");return}const n=t.fetchImpl??globalThis.fetch;if(typeof n!="function")throw new TypeError("no fetch implementation available — pass fetchImpl or run on Node >= 18");return ht({context:{baseUrl:o,bucket:t.bucket==="default"?void 0:t.bucket,fetchImpl:n,token:r},logger:t.logger,prefix:t.prefix})},q=t=>{const e=[t.bucket===void 0?void 0:"--bucket",t.prefix===void 0?void 0:"--prefix",t.dir===void 0?void 0:"--dir"].filter(a=>a!==void 0);if(e.length>0){t.logger.error(`${e.join(" / ")} ${e.length===1?"does":"do"} not apply here — retention and prune act on the store the worker itself is configured with (\`backupStore\`), not a destination you name.`);return}if(t.prod===!0&&t.url===void 0){t.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)");return}const o=y(t.url,t.logger,t.cwd);if(o===void 0)return;const{token:r}=R({cwd:t.cwd??process.cwd(),token:t.token,url:o});if(!r){t.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)");return}const n=t.adminFetch??globalThis.fetch;if(typeof n!="function")throw new TypeError("no fetch implementation available — pass pitrFetch or run on Node >= 18");return{baseUrl:o,fetchImpl:n,token:r}},z=(t,e)=>{t.logger.info(`backup retention would keep the newest ${e.keep.toString()} of ${e.eligible.toString()} under ${e.prefix} and delete ${e.wouldDelete.length.toString()}`);for(const o of e.wouldDelete)t.logger.info(` ${A(o)}`)},_t=async t=>{const e=q(t);if(e===void 0)return{code:1};const o=await e.fetchImpl(`${e.baseUrl}${D}`,{headers:{authorization:`Bearer ${e.token}`},method:"GET"});if(!o.ok)return await m(o,t.logger),{code:1};const r=await o.json();return r.cron===void 0?(t.logger.info("no scheduled backup is configured (`backupCron`), so retention would delete nothing"),{code:0,preview:r}):r.keep<=0?(t.logger.info(`retention is off for cron "${r.cron}" (\`backupRetain\` unset) — every snapshot under ${r.prefix} is kept`),{code:0,preview:r}):(z(t,r),r.eligible===0&&t.logger.info(`no snapshot under ${r.prefix} was written by this cron, so retention has nothing of its own to remove`),{code:0,preview:r})},Ot=(t,e)=>{t.logger.success(`deleted ${e.deleted.length.toString()} backup(s)`);for(const o of e.deleted)t.logger.info(` ${A(o)}`);e.failed.length>0&&t.logger.warn(`${e.failed.length.toString()} could not be removed — the snapshot may be gone with its manifest left behind; run again to retry`),e.ignored>0&&t.logger.info(`${e.ignored.toString()} were already gone by the time the delete ran`),e.remaining>0&&t.logger.info(`${e.remaining.toString()} more are past the window — run \`lunora backup prune\` again`)},Ut=async t=>{const e=q(t);if(e===void 0)return{code:1};const o=await e.fetchImpl(`${e.baseUrl}${D}`,{headers:{authorization:`Bearer ${e.token}`},method:"GET"});if(!o.ok)return await m(o,t.logger),{code:1};const r=await o.json();if(r.keep<=0||r.cron===void 0)return t.logger.error("backup prune needs a retention window: set `backupRetain` (and `backupCron`) on the worker. Without one there is nothing past the window to remove."),{code:1,preview:r};if(r.wouldDelete.length===0)return t.logger.info(`nothing to prune — ${r.eligible.toString()} snapshot(s) under ${r.prefix} and retention keeps the newest ${r.keep.toString()}`),{code:0,preview:r};if(z(t,r),t.yes!==!0){const u=t.confirm??(C()?F:void 0);if(u===void 0)return t.logger.error("refusing to delete backups without confirmation — re-run with --yes (there is no undo for an object-store delete)"),{code:1,preview:r};if(!await u(`delete ${r.wouldDelete.length.toString()} backup(s)? This cannot be undone. [y/N] `))return t.logger.info("nothing was deleted"),{code:0,preview:r}}const n=await e.fetchImpl(`${e.baseUrl}${wt}`,{body:JSON.stringify({confirm:r.wouldDelete}),headers:{authorization:`Bearer ${e.token}`,"content-type":"application/json"},method:"POST"});if(!n.ok)return await m(n,t.logger),{code:1,preview:r};const a=await n.json();return Ot(t,a),{code:a.failed.length>0?1:0,deleted:a.deleted,preview:r}},At=async t=>{const e=t.cwd??process.cwd();try{if(t.subcommand==="pitr")return await It(t);if(t.subcommand==="retention")return await _t(t);if(t.subcommand==="prune")return await Ut(t);const o=Et(t,e);return o===void 0?{code:1}:t.subcommand==="create"?await $t(t,o):t.subcommand==="list"?await St(t,o):await Nt(t,o)}catch(o){return t.logger.error(o instanceof Error?o.message:String(o)),{code:1}}},Rt=t=>t==="create"||t==="list"||t==="pitr"||t==="prune"||t==="restore"||t==="retention",Vt=Y(({argument:t,cwd:e,logger:o,options:r})=>{const n=t[0];return Rt(n)?At({at:r.at,bookmark:r.bookmark,bucket:r.bucket,cwd:e,dir:r.dir,logger:o,prefix:r.prefix,prod:r.prod===!0,restart:r.restart===!0,restore:r.restore===!0,shard:r.shard,subcommand:n,tables:r.tables,target:t[1],token:r.token,url:X({cwd:e,prod:r.prod===!0,url:r.url}),verify:r.verify===!0,yes:r.yes===!0}):(o.error(`backup: unknown subcommand "${n??""}" — expected create | list | restore | retention | prune | pitr`),{code:1})});export{Vt as execute,At as runBackupCommand};
1
+ import K,{join as l,resolve as T}from"node:path";import{isInteractive as F,promptYesNo as z}from"@lunora/config";import{backupObjectKey as p,isBackupManifestEntry as x,normalizeBackupPrefix as H,BACKUP_KEY_PREFIX as J,backupManifestKey as G,isBackupManifestKey as Y,backupObjectKeyOfManifest as O}from"@lunora/runtime";import{r as A}from"../packem_shared/admin-token-rxXZbVMZ.mjs";import{r as v}from"../packem_shared/admin-url-Cil3Or6N.mjs";import{d as W}from"../packem_shared/command-DwC11Cwe.mjs";import{a as X}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{readAndLogBody as b}from"./runRpcCommand.mjs";import{randomUUID as U,createHash as Q}from"node:crypto";import{existsSync as $,createReadStream as V,createWriteStream as Z}from"node:fs";import{mkdir as ee,rm as w,rename as B,readFile as D,writeFile as re,realpath as N,mkdtemp as S}from"node:fs/promises";import{LunoraError as h}from"@lunora/errors";import{i as E}from"../packem_shared/path-containment-CgxYZggb.mjs";import{tmpdir as I}from"node:os";import{Readable as te}from"node:stream";import{pipeline as ae}from"node:stream/promises";import{b as oe,l as ne,M as _,u as ie,r as ce}from"../packem_shared/import-Db3Gk4mx.mjs";import{runExportCommand as se}from"../packem_shared/runExportCommand-DmXKEWSq.mjs";const y="manifest.json",j=async e=>{const r=Q("sha256");let a=0;for await(const t of V(e)){const o=t;a+=o.byteLength,r.update(o)}return{bytes:a,sha256:r.digest("hex")}},P=async e=>{const r=l(e,y);if(!$(r))return[];let a;try{a=JSON.parse(await D(r,"utf8"))}catch(t){const o=t instanceof Error?t.message:String(t);throw new h("INTERNAL",`backup: ${r} exists but is not valid JSON (${o}) — refusing to overwrite it; fix or remove it manually`,{cause:t})}if(!Array.isArray(a))throw new TypeError(`backup: ${r} exists but is not a JSON array — refusing to overwrite it; fix or remove it manually`);return a.filter(t=>x(t))},ue=async(e,r)=>{const a=l(e,`${y}.${U()}.tmp`);try{await re(a,`${JSON.stringify(r,void 0,2)}
2
+ `,"utf8"),await B(a,l(e,y))}catch(t){throw await w(a,{force:!0}),t}},de=async(e,r)=>{const a=T(e),t=T(a,r.file),o=()=>{throw new h("INTERNAL",`backup: entry ${r.id} points outside ${a} (${r.file}) — refusing to read it`)};if(E(a,t)||o(),!!$(t))return E(await N(a),await N(t))||o(),t},le=e=>{const r=a=>p("",a);return{commit:async(a,t)=>{await B(t,l(e,a))},label:e,list:async()=>P(e),locate:r,materialize:async(a,t)=>{const o=i=>i===void 0?void 0:{path:i,release:()=>Promise.resolve()};return o(a===void 0?$(t)?t:void 0:await de(e,a))},record:async a=>{const t=await P(e);t.push(a),await ue(e,t)},stage:async a=>{await ee(e,{recursive:!0});const t=l(e,`${r(a)}.${U()}.partial`);return{path:t,release:()=>w(t,{force:!0})}}}},fe="/_lunora/admin/storage/object",me="/_lunora/admin/storage",R=8,ge=(e,r=K)=>{const a=r.basename(e);return a===""||a==="."||a===".."?"snapshot.ndjson":a},he=e=>{const{context:r,logger:a}=e,t=H(e.prefix??J),o=`bucket ${r.bucket??"(default)"} under ${t}`,i=oe(r),u=c=>`${r.baseUrl}${fe}?key=${encodeURIComponent(c)}${i}`,f=async c=>{const n=await r.fetchImpl(u(c),{headers:{authorization:`Bearer ${r.token}`},method:"GET"});if(!n.ok){const d=await n.text().catch(()=>"<no body>");throw new h("INTERNAL",`backup: could not read ${c} (HTTP ${String(n.status)}): ${d}`)}return n.text()},C=async c=>{try{const n=JSON.parse(await f(c));if(x(n))return n;a.warn(`backup: ignoring ${c} — not a backup manifest`)}catch(n){a.warn(`backup: ignoring ${c} — ${n instanceof Error?n.message:String(n)}`)}};return{commit:async(c,n,d)=>{if(d.bytes>_)throw new h("INTERNAL",`backup: the snapshot is ${String(d.bytes)} bytes, above the ${String(_)}-byte limit for a checksum-verified upload — nothing was written. Narrow it with \`--tables\`, or write it to a directory with \`--dir\` and move the file yourself (\`wrangler r2 object put\`).`);const s=await D(n);await ie(r,c,s,{contentType:"application/x-ndjson",id:c,sha256:d.sha256,size:d.bytes},a)},label:o,list:async()=>{const n=(await ne(r,t)).map(s=>s.key).filter(s=>Y(s)),d=[];for(let s=0;s<n.length;s+=R){const m=await Promise.all(n.slice(s,s+R).map(async g=>C(g)));d.push(...m.filter(g=>g!==void 0))}return d.toSorted((s,m)=>s.id.localeCompare(m.id))},locate:c=>p(t,c),materialize:async(c,n)=>{const d=c?.file??n,s=await r.fetchImpl(u(d),{headers:{authorization:`Bearer ${r.token}`},method:"GET"});if(s.status===404)return;if(!s.ok||s.body===null){const k=await s.text().catch(()=>"<no body>");throw new h("INTERNAL",`backup: could not download ${d} (HTTP ${String(s.status)}): ${k}`)}const m=await S(l(I(),"lunora-backup-")),g=l(m,ge(d));try{await ae(te.from(s.body),Z(g))}catch(k){throw await w(m,{force:!0,recursive:!0}),k}return{path:g,release:async()=>w(m,{force:!0,recursive:!0})}},record:async c=>{const n=G(c.file),d=await r.fetchImpl(`${r.baseUrl}${me}?key=${encodeURIComponent(n)}${i}`,{body:`${JSON.stringify(c,void 0,2)}
3
+ `,headers:{authorization:`Bearer ${r.token}`,"content-type":"application/json"},method:"PUT"});if(!d.ok){const s=await d.text().catch(()=>"<no body>");throw new h("INTERNAL",`backup: snapshot ${c.file} was written but its manifest was not (HTTP ${String(d.status)}): ${s}`)}},stage:async c=>{const n=await S(l(I(),"lunora-backup-"));return{path:l(n,p("",c)),release:async()=>w(n,{force:!0,recursive:!0})}}}},we=".lunora-backups",L="/_lunora/admin/backup/retention",be="/_lunora/admin/backup/prune",ke="/_lunora/admin/pitr",pe="__lunora_admin__:getPitrBookmark",ye="__lunora_admin__:pitrRestore",ve=async(e,r)=>{const a=(e.now??(()=>new Date))().toISOString(),t=await r.stage(a);try{const o=await se({cwd:e.cwd,fetchImpl:e.fetchImpl,logger:e.logger,out:t.path,prod:e.prod,tables:e.tables,token:e.token,url:e.url});if(o.code!==0)return{code:o.code};const i=r.locate(a),u=await j(t.path);await r.commit(i,t.path,u);const f={bytes:u.bytes,createdAt:a,file:i,id:a,rows:o.rows,sha256:u.sha256,tables:e.tables};return await r.record(f),e.logger.success(`backup created: ${i} (${o.rows.toString()} rows, ${u.bytes.toString()} bytes)`),{code:0,entry:f}}finally{await t.release().catch(o=>{e.logger.warn(`backup: could not clean up staging (${o instanceof Error?o.message:String(o)})`)})}},$e=async(e,r,a)=>{if(r?.sha256===void 0)return a.error(r===void 0?"--verify needs a recorded checksum, and a snapshot restored by path/key has no manifest entry — restore it by its backup id instead":`--verify: backup ${r.id} carries no recorded checksum — it was taken by a release before checksums existed`),{code:1};const t=await j(e);if(t.sha256!==r.sha256)return a.error(`--verify: ${r.file} does not match its recorded checksum (expected ${r.sha256}, got ${t.sha256}) — nothing was imported`),{code:1};a.success(`verified ${r.file} against its recorded sha256`)},Te=async(e,r)=>{const a=await r.list();if(a.length===0)return e.logger.info(`no backups found in ${r.label}`),{code:0};for(const t of a)e.logger.info(`${t.id} ${t.rows.toString()} rows ${t.bytes.toString()} bytes ${t.file}`);return{code:0}},Ne=async(e,r)=>{const{target:a}=e;if(a===void 0||a.length===0)return e.logger.error("restore requires a backup id or file path. Usage: lunora backup restore <id|file>"),{code:1};const o=(await r.list()).find(u=>u.id===a),i=await r.materialize(o,a);if(i===void 0)return e.logger.error(`backup not found: ${a}`),{code:1};try{if(e.verify===!0){const f=await $e(i.path,o,e.logger);if(f!==void 0)return f}return{code:(await ce({cwd:e.cwd,fetchImpl:e.fetchImpl,file:i.path,logger:e.logger,prod:e.prod,token:e.token,url:e.url,yes:e.yes})).code}}finally{await i.release().catch(u=>{e.logger.warn(`backup: could not clean up the downloaded snapshot (${u instanceof Error?u.message:String(u)})`)})}},Se=e=>{const r=e.token??process.env.LUNORA_ADMIN_TOKEN;if(!r){e.logger.error("admin token required — pass --token or set LUNORA_ADMIN_TOKEN");return}if(e.prod&&e.url===void 0){e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)");return}if(e.restore===!0&&e.at===void 0&&e.bookmark===void 0){e.logger.error("pitr --restore requires --at <time> or --bookmark <bookmark>");return}if(e.restore===!0&&e.prod===!0&&e.yes!==!0){e.logger.error("pitr --restore --prod restores production data in place. Re-run with --yes to confirm.");return}const a=v(e.url,e.logger,e.cwd);if(a===void 0)return;const t=e.adminFetch??globalThis.fetch;if(typeof t!="function")throw new TypeError("no fetch implementation available — pass pitrFetch or run on Node >= 18");return{fetchImpl:t,requestUrl:`${a}${ke}`,token:r}},Ee=(e,r)=>{const a={};return e.at!==void 0&&(a.time=e.at),r&&e.bookmark!==void 0&&(a.bookmark=e.bookmark),r&&e.restart===!0&&(a.restart=!0),a},Ie=async e=>{const r=Se(e);if(r===void 0)return{code:1};const a=e.restore===!0,t=a?ye:pe,o=Ee(e,a),i=a?"restore":"bookmark";e.logger.info(`POST ${r.requestUrl} -> pitr ${i}${e.shard===void 0?"":` (shard "${e.shard}")`}`);const u=await r.fetchImpl(r.requestUrl,{body:JSON.stringify({args:o,functionPath:t,shardKey:e.shard}),headers:{authorization:`Bearer ${r.token}`,"content-type":"application/json"},method:"POST"});return await b(u,e.logger),{code:u.ok?0:1}},_e=(e,r)=>{if(e.bucket===void 0)return le(l(r,e.dir??we));if(e.prod===!0&&e.url===void 0){e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)");return}const a=v(e.url,e.logger,e.cwd);if(a===void 0)return;const{token:t}=A({cwd:r,token:e.token,url:a});if(!t){e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)");return}const o=e.fetchImpl??globalThis.fetch;if(typeof o!="function")throw new TypeError("no fetch implementation available — pass fetchImpl or run on Node >= 18");return he({context:{baseUrl:a,bucket:e.bucket==="default"?void 0:e.bucket,fetchImpl:o,token:t},logger:e.logger,prefix:e.prefix})},q=e=>{const r=[e.bucket===void 0?void 0:"--bucket",e.prefix===void 0?void 0:"--prefix",e.dir===void 0?void 0:"--dir"].filter(i=>i!==void 0);if(r.length>0){e.logger.error(`${r.join(" / ")} ${r.length===1?"does":"do"} not apply here — retention and prune act on the store the worker itself is configured with (\`backupStore\`), not a destination you name.`);return}if(e.prod===!0&&e.url===void 0){e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)");return}const a=v(e.url,e.logger,e.cwd);if(a===void 0)return;const{token:t}=A({cwd:e.cwd??process.cwd(),token:e.token,url:a});if(!t){e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)");return}const o=e.adminFetch??globalThis.fetch;if(typeof o!="function")throw new TypeError("no fetch implementation available — pass pitrFetch or run on Node >= 18");return{baseUrl:a,fetchImpl:o,token:t}},M=(e,r)=>{e.logger.info(`backup retention would keep the newest ${r.keep.toString()} of ${r.eligible.toString()} under ${r.prefix} and delete ${r.wouldDelete.length.toString()}`);for(const a of r.wouldDelete)e.logger.info(` ${O(a)}`)},Pe=async e=>{const r=q(e);if(r===void 0)return{code:1};const a=await r.fetchImpl(`${r.baseUrl}${L}`,{headers:{authorization:`Bearer ${r.token}`},method:"GET"});if(!a.ok)return await b(a,e.logger),{code:1};const t=await a.json();return t.cron===void 0?(e.logger.info("no scheduled backup is configured (`backupCron`), so retention would delete nothing"),{code:0,preview:t}):t.keep<=0?(e.logger.info(`retention is off for cron "${t.cron}" (\`backupRetain\` unset) — every snapshot under ${t.prefix} is kept`),{code:0,preview:t}):(M(e,t),t.eligible===0&&e.logger.info(`no snapshot under ${t.prefix} was written by this cron, so retention has nothing of its own to remove`),{code:0,preview:t})},Re=(e,r)=>{e.logger.success(`deleted ${r.deleted.length.toString()} backup(s)`);for(const a of r.deleted)e.logger.info(` ${O(a)}`);r.failed.length>0&&e.logger.warn(`${r.failed.length.toString()} could not be removed — the snapshot may be gone with its manifest left behind; run again to retry`),r.ignored>0&&e.logger.info(`${r.ignored.toString()} were already gone by the time the delete ran`),r.remaining>0&&e.logger.info(`${r.remaining.toString()} more are past the window — run \`lunora backup prune\` again`)},xe=async e=>{const r=q(e);if(r===void 0)return{code:1};const a=await r.fetchImpl(`${r.baseUrl}${L}`,{headers:{authorization:`Bearer ${r.token}`},method:"GET"});if(!a.ok)return await b(a,e.logger),{code:1};const t=await a.json();if(t.keep<=0||t.cron===void 0)return e.logger.error("backup prune needs a retention window: set `backupRetain` (and `backupCron`) on the worker. Without one there is nothing past the window to remove."),{code:1,preview:t};if(t.wouldDelete.length===0)return e.logger.info(`nothing to prune — ${t.eligible.toString()} snapshot(s) under ${t.prefix} and retention keeps the newest ${t.keep.toString()}`),{code:0,preview:t};if(M(e,t),e.yes!==!0){const u=e.confirm??(F()?z:void 0);if(u===void 0)return e.logger.error("refusing to delete backups without confirmation — re-run with --yes (there is no undo for an object-store delete)"),{code:1,preview:t};if(!await u(`delete ${t.wouldDelete.length.toString()} backup(s)? This cannot be undone. [y/N] `))return e.logger.info("nothing was deleted"),{code:0,preview:t}}const o=await r.fetchImpl(`${r.baseUrl}${be}`,{body:JSON.stringify({confirm:t.wouldDelete}),headers:{authorization:`Bearer ${r.token}`,"content-type":"application/json"},method:"POST"});if(!o.ok)return await b(o,e.logger),{code:1,preview:t};const i=await o.json();return Re(e,i),{code:i.failed.length>0?1:0,deleted:i.deleted,preview:t}},Oe=async e=>{const r=e.cwd??process.cwd();try{if(e.subcommand==="pitr")return await Ie(e);if(e.subcommand==="retention")return await Pe(e);if(e.subcommand==="prune")return await xe(e);const a=_e(e,r);return a===void 0?{code:1}:e.subcommand==="create"?await ve(e,a):e.subcommand==="list"?await Te(e,a):await Ne(e,a)}catch(a){return e.logger.error(a instanceof Error?a.message:String(a)),{code:1}}},Ae=e=>e==="create"||e==="list"||e==="pitr"||e==="prune"||e==="restore"||e==="retention",Ve=W(({argument:e,cwd:r,logger:a,options:t})=>{const o=e[0];return Ae(o)?Oe({at:t.at,bookmark:t.bookmark,bucket:t.bucket,cwd:r,dir:t.dir,logger:a,prefix:t.prefix,prod:t.prod===!0,restart:t.restart===!0,restore:t.restore===!0,shard:t.shard,subcommand:o,tables:t.tables,target:e[1],token:t.token,url:X({cwd:r,prod:t.prod===!0,url:t.url}),verify:t.verify===!0,yes:t.yes===!0}):(a.error(`backup: unknown subcommand "${o??""}" — expected create | list | restore | retention | prune | pitr`),{code:1})});export{Ve as execute,Oe as runBackupCommand};
@@ -1 +1 @@
1
- import{readdirSync as E,lstatSync as x,existsSync as N}from"node:fs";import{join as p,basename as R}from"node:path";import{pathToFileURL as b}from"node:url";import{i as F}from"../packem_shared/command-0l-ZPhIX.mjs";import{i as O,t as g,d as v,s as T}from"../packem_shared/output-format-Cv3aLqhP.mjs";const h=".eval.ts",_=new Set([".git","_generated","dist","node_modules"]),$=(r,o=[])=>{let e;try{e=E(r)}catch{return o}for(const t of e){const n=p(r,t);let s;try{s=x(n)}catch{continue}if(s.isDirectory()){if(_.has(t))continue;$(n,o)}else s.isFile()&&t.endsWith(h)&&o.push(n)}return o.toSorted((t,n)=>t.localeCompare(n))},A=r=>typeof r=="object"&&r!==null&&typeof r.run=="function",S=r=>typeof r=="number"&&Number.isFinite(r)&&r>=0&&r<=1,C="evals",I='"lunora eval" needs native TypeScript execution — run Node ≥23.6, or a TS loader/transform (tracked in plans/245-eval-runner-design.md §8.3)',L=/unknown file extension ".ts"/i,y=r=>r instanceof Error?r.code==="ERR_UNKNOWN_FILE_EXTENSION"?!0:L.test(r.message):!1,m=r=>R(r,h),U=r=>({average:r.result?.average,error:r.error,items:r.result?.items,name:r.name,passed:r.passed,path:r.path,threshold:r.threshold}),w=r=>({code:r.code,error:r.error,evals:r.evals.map(o=>U(o))}),l=(r,o,e)=>{r.error(e);const t={code:1,error:e,evals:[]};return g(o)&&v(w(t)),t},k=(r,o,e)=>{if(!N(r))return e.info(`eval: no "${o}" directory — nothing to run`),[];const t=$(r);return t.length===0&&e.info(`eval: no ${h} files found under "${o}"`),t},D=async r=>{const o=(await import(b(r).href)).default;if(!A(o))throw new Error("does not default-export an eval module (expected `{ run(): Promise<EvalResult>, name?, threshold? }`)");return o},H=async(r,o)=>{let e;try{e=await D(r)}catch(s){if(y(s))throw s;return{error:s instanceof Error?s.message:String(s),name:m(r),passed:!1,path:r}}const t=e.name??m(r);if(e.threshold!==void 0&&!S(e.threshold))return{error:`invalid \`threshold\` export: must be a number in [0, 1] — received ${JSON.stringify(e.threshold)}`,name:t,passed:!1,path:r};const n=e.threshold??o;try{const s=await e.run(),d=n===void 0||s.average>=n;return{name:t,passed:d,path:r,result:s,threshold:n}}catch(s){return{error:s instanceof Error?s.message:String(s),name:t,passed:!1,path:r,threshold:n}}},M=async(r,o)=>{const e=[];for(const t of r)e.push(await H(t,o));return e},j=r=>{if(r.error!==void 0)return`ERROR: ${r.error}`;const o=r.passed?"pass":"FAIL",e=r.result?.items.length??0;return`${o} (${String(e)} cases)`},J=r=>{if(r.length===0)return[];const o=Math.max(4,...r.map(t=>t.name.length)),e=[`${"NAME".padEnd(o)} SCORE THRESHOLD STATUS`];for(const t of r){const n=t.result===void 0?"—":t.result.average.toFixed(3),s=t.threshold===void 0?"—":t.threshold.toFixed(3);e.push(`${t.name.padEnd(o)} ${n.padEnd(6)} ${s.padEnd(9)} ${j(t)}`)}return e},W=async r=>{const o=r.cwd??process.cwd(),e=T(r.format,r.logger),t=O("eval",r.format);if(t!==void 0)return r.logger.error(t),{code:1,error:t,evals:[]};if(r.threshold!==void 0&&!S(r.threshold))return l(e,r.format,`eval: --threshold must be a number in [0, 1] — received "${String(r.threshold)}"`);const n=r.dir??C,s=p(o,n),d=k(s,n,e);let i;try{i=await M(d,r.threshold)}catch(a){if(!y(a))throw a;return l(e,r.format,I)}if(r.threshold!==void 0&&i.length===0){const a=`eval: --threshold ${String(r.threshold)} was set but 0 eval files were discovered under "${n}" — nothing was gated`;return l(e,r.format,a)}for(const a of J(i))e.info(a);const c=i.filter(a=>!a.passed),u=c.length>0?1:0;u===0?e.success(`eval: ${String(i.length)} eval(s) passed`):e.error(`eval: ${String(c.length)}/${String(i.length)} eval(s) failed`);const f={code:u,evals:i};return g(r.format)&&v(w(f)),f},B=F(async({cwd:r,logger:o,options:e})=>({code:(await W({cwd:r,dir:e.dir,format:e.format,logger:o,threshold:e.threshold})).code}));export{B as execute,W as runEvalCommand};
1
+ import{readdirSync as w,lstatSync as R,existsSync as T}from"node:fs";import{join as v,basename as $}from"node:path";import{pathToFileURL as O}from"node:url";import{d as _}from"../packem_shared/command-DwC11Cwe.mjs";import{v as N,i as g,p as E,l as x}from"../packem_shared/output-format-DfogXx0p.mjs";const c=".eval.ts",b=new Set([".git","_generated","dist","node_modules"]),p=(e,s=[])=>{let r;try{r=w(e)}catch{return s}for(const t of r){const o=v(e,t);let n;try{n=R(o)}catch{continue}if(n.isDirectory()){if(b.has(t))continue;p(o,s)}else n.isFile()&&t.endsWith(c)&&s.push(o)}return s.toSorted((t,o)=>t.localeCompare(o))},L=e=>typeof e=="object"&&e!==null&&typeof e.run=="function",S=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=1,I="evals",A='"lunora eval" needs native TypeScript execution — run Node ≥23.6, or a TS loader/transform (tracked in plans/245-eval-runner-design.md §8.3)',D=/unknown file extension ".ts"/i,y=e=>e instanceof Error?e.code==="ERR_UNKNOWN_FILE_EXTENSION"?!0:D.test(e.message):!1,m=e=>$(e,c),M=e=>({average:e.result?.average,error:e.error,items:e.result?.items,name:e.name,passed:e.passed,path:e.path,threshold:e.threshold}),F=e=>({code:e.code,error:e.error,evals:e.evals.map(s=>M(s))}),i=(e,s,r)=>{e.error(r);const t={code:1,error:r,evals:[]};return g(s)&&E(F(t)),t},U=(e,s,r)=>{if(!T(e))return r.info(`eval: no "${s}" directory — nothing to run`),[];const t=p(e);return t.length===0&&r.info(`eval: no ${c} files found under "${s}"`),t},C=async e=>{const r=(await import(O(e).href)).default;if(!L(r))throw new Error("does not default-export an eval module (expected `{ run(): Promise<EvalResult>, name?, threshold? }`)");return r},J=async(e,s)=>{let r;try{r=await C(e)}catch(n){if(y(n))throw n;return{error:n instanceof Error?n.message:String(n),name:m(e),passed:!1,path:e}}const t=r.name??m(e);if(r.threshold!==void 0&&!S(r.threshold))return{error:`invalid \`threshold\` export: must be a number in [0, 1] — received ${JSON.stringify(r.threshold)}`,name:t,passed:!1,path:e};const o=r.threshold??s;try{const n=await r.run(),l=o===void 0||n.average>=o;return{name:t,passed:l,path:e,result:n,threshold:o}}catch(n){return{error:n instanceof Error?n.message:String(n),name:t,passed:!1,path:e,threshold:o}}},W=async(e,s)=>{const r=[];for(const t of e)r.push(await J(t,s));return r},H=e=>{if(e.error!==void 0)return`ERROR: ${e.error}`;const s=e.passed?"pass":"FAIL",r=e.result?.items.length??0;return`${s} (${String(r)} cases)`},V=e=>{if(e.length===0)return[];const s=Math.max(4,...e.map(t=>t.name.length)),r=[`${"NAME".padEnd(s)} SCORE THRESHOLD STATUS`];for(const t of e){const o=t.result===void 0?"—":t.result.average.toFixed(3),n=t.threshold===void 0?"—":t.threshold.toFixed(3);r.push(`${t.name.padEnd(s)} ${o.padEnd(6)} ${n.padEnd(9)} ${H(t)}`)}return r},X=async e=>{const s=e.cwd??process.cwd(),r=x(e.format,e.logger),t=N("eval",e.format);if(t!==void 0)return e.logger.error(t),{code:1,error:t,evals:[]};if(e.threshold!==void 0&&!S(e.threshold))return i(r,e.format,`eval: --threshold must be a number in [0, 1] — received "${String(e.threshold)}"`);const o=e.dir??I,n=v(s,o),l=U(n,o,r);let d;try{d=await W(l,e.threshold)}catch(a){if(!y(a))throw a;return i(r,e.format,A)}if(e.threshold!==void 0&&d.length===0){const a=`eval: --threshold ${String(e.threshold)} was set but 0 eval files were discovered under "${o}" — nothing was gated`;return i(r,e.format,a)}for(const a of V(d))r.info(a);const h=d.filter(a=>!a.passed),f=h.length>0?1:0;f===0?r.success(`eval: ${String(d.length)} eval(s) passed`):r.error(`eval: ${String(h.length)}/${String(d.length)} eval(s) failed`);const u={code:f,evals:d};return g(e.format)&&E(F(u)),u},z=_(async({cwd:e,logger:s,options:r})=>({code:(await X({cwd:e,dir:r.dir,format:r.format,logger:s,threshold:r.threshold})).code}));export{z as execute,X as runEvalCommand};
@@ -1,13 +1,13 @@
1
- import{existsSync as T,readFileSync as O}from"node:fs";import{writeFile as x,mkdir as D}from"node:fs/promises";import{join as v}from"@visulima/path";import{i as B}from"../packem_shared/command-0l-ZPhIX.mjs";import{createRequire as q}from"node:module";import{LunoraError as w}from"@lunora/errors";import{P as U,l as F}from"../packem_shared/detect-package-manager-DXDstphE.mjs";import{parseSchema as Y,applyAdditiveEdit as j}from"@lunora/config";const H=/^\//,J=(e,n)=>{try{const{args:t,command:a}=U(F(e),[n],{dev:!0});return`${a} ${t.join(" ")}`}catch{return`<your-package-manager> add -D ${n}`}},R=(e,n,t)=>{const a=q(v(t,"noop.cjs"));try{a.resolve(e)}catch{throw new w("INTERNAL",`\`lunora introspect\` needs the \`${n}\` driver to read this database, and it isn't installed.
1
+ import{existsSync as T,readFileSync as O}from"node:fs";import{writeFile as I,mkdir as k}from"node:fs/promises";import{join as b}from"@visulima/path";import{d as B}from"../packem_shared/command-DwC11Cwe.mjs";import{createRequire as U}from"node:module";import{LunoraError as N}from"@lunora/errors";import{b as Y,d as q}from"../packem_shared/detect-package-manager-DSaAqRof.mjs";import{parseSchema as F,applyAdditiveEdit as P}from"@lunora/config";const H=/^\//,K=(e,t)=>{try{const{args:n,command:r}=Y(q(e),[t],{dev:!0});return`${r} ${n.join(" ")}`}catch{return`<your-package-manager> add -D ${t}`}},L=(e,t,n)=>{const r=U(b(n,"noop.cjs"));try{r.resolve(e)}catch{throw new N("INTERNAL",`\`lunora introspect\` needs the \`${t}\` driver to read this database, and it isn't installed.
2
2
 
3
3
  Install it in your project:
4
4
 
5
- ${J(t,n)}`)}return a(e)},P=e=>{const n=e.slice(0,Math.max(0,e.indexOf(":"))).toLowerCase();if(n==="postgres"||n==="postgresql")return"postgres";if(n==="mysql"||n==="mariadb")return"mysql";throw new w("INTERNAL",`Unrecognised database URL scheme \`${n}\`. Expected a \`postgres://\`, \`postgresql://\`, \`mysql://\`, or \`mariadb://\` connection string.`)},W=e=>{try{const n=new URL(e).pathname.replace(H,"");return n===""?void 0:decodeURIComponent(n)}catch{return}},K=async(e,n,t,a=process.cwd())=>{if(n==="postgres"){const o=R("pg","pg",a).Client,c=new o({connectionString:e});return await c.connect(),{close:async()=>{await c.end()},execute:async(m,d)=>(await c.query(m,[...d])).rows,schema:t??"public"}}const s=R("mysql2/promise","mysql2",a).createConnection,r=await s(e),i=t??W(e);if(i===void 0)throw new w("INTERNAL","A MySQL connection string must name a database (`mysql://host/<database>`), or pass `--schema`.");return{close:async()=>{await r.end()},execute:async(o,c)=>{const[m]=await r.execute(o,[...c]);return Array.isArray(m)?m:[]},schema:i}},h=new Set(["_creationTime","_id"]),Q={bigint:"v.bigint()",bigserial:"v.bigint()",bit:"v.string()",bool:"v.boolean()",boolean:"v.boolean()",box:"v.string()",bpchar:"v.string()",bytea:"v.bytes()",char:"v.string()",character:"v.string()","character varying":"v.string()",cidr:"v.string()",circle:"v.string()",citext:"v.string()",date:"v.date()","double precision":"v.number()",float4:"v.number()",float8:"v.number()",inet:"v.string()",int:"v.number()",int2:"v.number()",int4:"v.number()",int8:"v.bigint()",integer:"v.number()",interval:"v.string()",json:"v.any()",jsonb:"v.any()",line:"v.string()",lseg:"v.string()",macaddr:"v.string()",money:"v.number()",name:"v.string()",numeric:"v.number()",path:"v.string()",point:"v.string()",polygon:"v.string()",real:"v.number()",serial:"v.number()",smallint:"v.number()",smallserial:"v.number()",text:"v.string()",time:"v.string()","time with time zone":"v.string()","time without time zone":"v.string()",timestamp:"v.timestamp()","timestamp with time zone":"v.timestamp()","timestamp without time zone":"v.timestamp()",timestamptz:"v.timestamp()",tsquery:"v.string()",tsvector:"v.string()",uuid:"v.string()",varbit:"v.string()",varchar:"v.string()",xml:"v.string()"},G={bigint:"v.bigint()",binary:"v.bytes()",bit:"v.number()",blob:"v.bytes()",char:"v.string()",date:"v.date()",datetime:"v.timestamp()",decimal:"v.number()",double:"v.number()",enum:"v.string()",float:"v.number()",int:"v.number()",integer:"v.number()",json:"v.any()",longblob:"v.bytes()",longtext:"v.string()",mediumblob:"v.bytes()",mediumint:"v.number()",mediumtext:"v.string()",numeric:"v.number()",set:"v.string()",smallint:"v.number()",text:"v.string()",time:"v.string()",timestamp:"v.timestamp()",tinyblob:"v.bytes()",tinyint:"v.number()",tinytext:"v.string()",varbinary:"v.bytes()",varchar:"v.string()",year:"v.number()"},N=(e,n)=>{const t=(n==="postgres"?Q:G)[e.dataType],a=e.references===void 0?t:`v.id(${JSON.stringify(e.references.table)})`;let s=a??"v.any()";for(let r=0;r<e.arrayDepth;r+=1)s=`v.array(${s})`;return e.nullable&&(s=`v.optional(${s})`),{expression:s,known:a!==void 0}},M=/^[A-Z_$][\w$]*$/i,z=/[^\dA-Z]+(.)?/gi,X=/^\d+/,Z=/[^\w-]/g,V=/[\u003C\u003E\u002F\u2028\u2029]/g,ee={"/":String.raw`\u002F`,"\u2028":String.raw`\u2028`,"\u2029":String.raw`\u2029`,"<":String.raw`\u003C`,">":String.raw`\u003E`},b=e=>JSON.stringify(e).replaceAll(V,n=>ee[n]??n),$=e=>M.test(e)?e:b(e),te=e=>M.test(e)?`.${e}`:`[${b(e)}]`,I=e=>e.replaceAll("*/",String.raw`*\/`),ne=e=>{const n=e.replaceAll(Z,"_");return n===""?"table":n},ae=e=>{const n=e.replaceAll(z,(t,a)=>a?.toUpperCase()??"").replace(X,"");return n===""?"table":`${n.charAt(0).toLowerCase()}${n.slice(1)}`},C=e=>e.columns.filter(n=>!h.has(n.name)),re=e=>{const n=new Set(e.primaryKey);for(const t of e.indexes)for(const a of t.columns)n.add(a);for(const t of e.columns)t.references!==void 0&&n.add(t.name);return[...n].filter(t=>!h.has(t))},k=(e,n,t,a)=>e.references===void 0||n.has(e.references.table)?e:(a.push(`${t}.${e.name}: references \`${e.references.table}\`, which isn't in the generated schema — emitted as a plain column instead of \`v.id(...)\`.`),{arrayDepth:e.arrayDepth,dataType:e.dataType,name:e.name,nullable:e.nullable}),se=(e,n,t,a)=>{const s=[];for(const i of e.columns){if(h.has(i.name)){a.push(`${e.name}.${i.name}: skipped — \`${i.name}\` is a Lunora system column. Rename it in the source database or map it by hand.`);continue}const o=k(i,t,e.name,a),{expression:c,known:m}=N(o,n);!m&&o.references===void 0&&(a.push(`${e.name}.${i.name}: no mapping for SQL type \`${i.dataType}\` — emitted as \`v.any()\`.`),s.push(` // TODO: \`${I(i.dataType)}\` has no direct validator; narrow this.`)),s.push(` ${$(i.name)}: ${c},`)}const r=[' .global({ backend: "hyperdrive" })'];if(e.primaryKey.length>0&&e.primaryKey.every(i=>!h.has(i))){const i=e.primaryKey.map(o=>b(o)).join(", ");r.push(` .index(${b(`by_${e.primaryKey.join("_")}`)}, [${i}], { unique: true })`)}for(const i of e.indexes){const o=i.columns.filter(d=>!h.has(d));if(o.length===0)continue;const c=o.map(d=>b(d)).join(", "),m=i.unique?", { unique: true }":"";r.push(` .index(${b(i.name)}, [${c}]${m})`)}return` ${$(e.name)}: defineTable({
5
+ ${K(n,t)}`)}return r(e)},j=e=>{const t=e.slice(0,Math.max(0,e.indexOf(":"))).toLowerCase();if(t==="postgres"||t==="postgresql")return"postgres";if(t==="mysql"||t==="mariadb")return"mysql";throw new N("INTERNAL",`Unrecognised database URL scheme \`${t}\`. Expected a \`postgres://\`, \`postgresql://\`, \`mysql://\`, or \`mariadb://\` connection string.`)},G=e=>{try{const t=new URL(e).pathname.replace(H,"");return t===""?void 0:decodeURIComponent(t)}catch{return}},J=async(e,t,n,r=process.cwd())=>{if(t==="postgres"){const m=L("pg","pg",r).Client,u=new m({connectionString:e});return await u.connect(),{close:async()=>{await u.end()},execute:async(l,d)=>(await u.query(l,[...d])).rows,schema:n??"public"}}const a=L("mysql2/promise","mysql2",r).createConnection,o=await a(e),i=n??G(e);if(i===void 0)throw new N("INTERNAL","A MySQL connection string must name a database (`mysql://host/<database>`), or pass `--schema`.");return{close:async()=>{await o.end()},execute:async(c,m)=>{const[u]=await o.execute(c,[...m]);return Array.isArray(u)?u:[]},schema:i}},h=new Set(["_creationTime","_id"]),Q={bigint:"v.bigint()",bigserial:"v.bigint()",bit:"v.string()",bool:"v.boolean()",boolean:"v.boolean()",box:"v.string()",bpchar:"v.string()",bytea:"v.bytes()",char:"v.string()",character:"v.string()","character varying":"v.string()",cidr:"v.string()",circle:"v.string()",citext:"v.string()",date:"v.date()","double precision":"v.number()",float4:"v.number()",float8:"v.number()",inet:"v.string()",int:"v.number()",int2:"v.number()",int4:"v.number()",int8:"v.bigint()",integer:"v.number()",interval:"v.string()",json:"v.any()",jsonb:"v.any()",line:"v.string()",lseg:"v.string()",macaddr:"v.string()",money:"v.number()",name:"v.string()",numeric:"v.number()",path:"v.string()",point:"v.string()",polygon:"v.string()",real:"v.number()",serial:"v.number()",smallint:"v.number()",smallserial:"v.number()",text:"v.string()",time:"v.string()","time with time zone":"v.string()","time without time zone":"v.string()",timestamp:"v.timestamp()","timestamp with time zone":"v.timestamp()","timestamp without time zone":"v.timestamp()",timestamptz:"v.timestamp()",tsquery:"v.string()",tsvector:"v.string()",uuid:"v.string()",varbit:"v.string()",varchar:"v.string()",xml:"v.string()"},W={bigint:"v.bigint()",binary:"v.bytes()",bit:"v.number()",blob:"v.bytes()",char:"v.string()",date:"v.date()",datetime:"v.timestamp()",decimal:"v.number()",double:"v.number()",enum:"v.string()",float:"v.number()",int:"v.number()",integer:"v.number()",json:"v.any()",longblob:"v.bytes()",longtext:"v.string()",mediumblob:"v.bytes()",mediumint:"v.number()",mediumtext:"v.string()",numeric:"v.number()",set:"v.string()",smallint:"v.number()",text:"v.string()",time:"v.string()",timestamp:"v.timestamp()",tinyblob:"v.bytes()",tinyint:"v.number()",tinytext:"v.string()",varbinary:"v.bytes()",varchar:"v.string()",year:"v.number()"},w=(e,t)=>{const r=(t==="postgres"?Q:W)[e.dataType],s=e.references===void 0?r:`v.id(${JSON.stringify(e.references.table)})`;let a=s??"v.any()";for(let o=0;o<e.arrayDepth;o+=1)a=`v.array(${a})`;return e.nullable&&(a=`v.optional(${a})`),{expression:a,known:s!==void 0}},M=/^[A-Z_$][\w$]*$/i,X=/[^\dA-Z]+(.)?/gi,z=/^\d+/,Z=/[^\w-]/g,V=/[\u003C\u003E\u002F\u2028\u2029]/g,ee={"/":String.raw`\u002F`,"\u2028":String.raw`\u2028`,"\u2029":String.raw`\u2029`,"<":String.raw`\u003C`,">":String.raw`\u003E`},f=e=>JSON.stringify(e).replaceAll(V,t=>ee[t]??t),S=e=>M.test(e)?e:f(e),ne=e=>M.test(e)?`.${e}`:`[${f(e)}]`,x=e=>e.replaceAll("*/",String.raw`*\/`),te=e=>{const t=e.replaceAll(Z,"_");return t===""?"table":t},re=e=>{const n=e.replaceAll(X,(r,s)=>s?.toUpperCase()??"").replace(z,"");return n===""?"table":`${n.charAt(0).toLowerCase()}${n.slice(1)}`},C=e=>e.columns.filter(t=>!h.has(t.name)),ae=e=>{const t=new Set(e.primaryKey);for(const n of e.indexes)for(const r of n.columns)t.add(r);for(const n of e.columns)n.references!==void 0&&t.add(n.name);return[...t].filter(n=>!h.has(n))},D=(e,t,n,r)=>e.references===void 0||t.has(e.references.table)?e:(r.push(`${n}.${e.name}: references \`${e.references.table}\`, which isn't in the generated schema — emitted as a plain column instead of \`v.id(...)\`.`),{arrayDepth:e.arrayDepth,dataType:e.dataType,name:e.name,nullable:e.nullable}),se=(e,t,n,r)=>{const s=[];for(const o of e.columns){if(h.has(o.name)){r.push(`${e.name}.${o.name}: skipped — \`${o.name}\` is a Lunora system column. Rename it in the source database or map it by hand.`);continue}const i=D(o,n,e.name,r),{expression:c,known:m}=w(i,t);!m&&i.references===void 0&&(r.push(`${e.name}.${o.name}: no mapping for SQL type \`${o.dataType}\` — emitted as \`v.any()\`.`),s.push(` // TODO: \`${x(o.dataType)}\` has no direct validator; narrow this.`)),s.push(` ${S(o.name)}: ${c},`)}const a=[' .global({ backend: "hyperdrive" })'];if(e.primaryKey.length>0&&e.primaryKey.every(o=>!h.has(o))){const o=e.primaryKey.map(i=>f(i)).join(", ");a.push(` .index(${f(`by_${e.primaryKey.join("_")}`)}, [${o}], { unique: true })`)}for(const o of e.indexes){const i=o.columns.filter(u=>!h.has(u));if(i.length===0)continue;const c=i.map(u=>f(u)).join(", "),m=o.unique?", { unique: true }":"";a.push(` .index(${f(o.name)}, [${c}]${m})`)}return` ${S(e.name)}: defineTable({
6
6
  ${s.join(`
7
7
  `)}
8
8
  })
9
- ${r.join(`
10
- `)},`},ie=(e,n,t)=>{const a=new Set(e.tables.map(r=>r.name)),s=e.tables.map(r=>se(r,e.dialect,a,t)).join(`
9
+ ${a.join(`
10
+ `)},`},oe=(e,t,n)=>{const r=new Set(e.tables.map(a=>a.name)),s=e.tables.map(a=>se(a,e.dialect,r,n)).join(`
11
11
  `);return`/**
12
12
  * Generated by \`lunora introspect\` from an existing ${e.dialect==="postgres"?"Postgres":"MySQL"} database.
13
13
  *
@@ -17,25 +17,25 @@ ${r.join(`
17
17
  * its rows live in the external database. Re-running \`lunora introspect\` will not
18
18
  * overwrite it unless you pass \`--force\`.
19
19
  */
20
- import { defineSchema, defineTable, v } from "${n.serverImport}";
20
+ import { defineSchema, defineTable, v } from "${t.serverImport}";
21
21
 
22
22
  export default defineSchema({
23
23
  ${s}
24
24
  });
25
- `},oe=(e,n,t,a=new Set([e.name]),s=[])=>{const r=ae(e.name),i=re(e),o=new Map(C(e).map(l=>[l.name,l])),c=i.map(l=>{const g=o.get(l);if(g===void 0)return;const p=k({...g,nullable:!1},a,e.name,[]),{expression:E,known:A}=N(p,n);return!A&&p.references===void 0&&s.push(`${e.name}.${l}: filter falls back to \`v.any()\` (no mapping for SQL type \`${g.dataType}\`).`),` ${$(l)}: ${E},`}).filter(l=>l!==void 0),m=[b("_creationTime"),...i.map(l=>b(l))].join(", "),d=`ctx.db${te(e.name)}`;return`/**
26
- * Generated by \`lunora introspect\` for the \`${I(e.name)}\` table — a
25
+ `},ie=(e,t,n,r=new Set([e.name]),s=[])=>{const a=re(e.name),o=ae(e),i=new Map(C(e).map(l=>[l.name,l])),c=o.map(l=>{const d=i.get(l);if(d===void 0)return;const p=D({...d,nullable:!1},r,e.name,[]),{expression:y,known:A}=w(p,t);return!A&&p.references===void 0&&s.push(`${e.name}.${l}: filter falls back to \`v.any()\` (no mapping for SQL type \`${d.dataType}\`).`),` ${S(l)}: ${y},`}).filter(l=>l!==void 0),m=[f("_creationTime"),...o.map(l=>f(l))].join(", "),u=`ctx.db${ne(e.name)}`;return`/**
26
+ * Generated by \`lunora introspect\` for the \`${x(e.name)}\` table — a
27
27
  * starting point you own and edit.
28
28
  *
29
29
  * Both procedures are RPC-only. Add \`.expose({ rest: true })\` once you've decided
30
30
  * this data should be public, and gate them with your auth/RLS middleware first —
31
31
  * \`introspect\` cannot know who is allowed to read this table.
32
32
  */
33
- import { defineListArgs, v } from "${t.serverImport}";
33
+ import { defineListArgs, v } from "${n.serverImport}";
34
34
 
35
35
  import type { Doc } from "./_generated/dataModel";
36
36
  import { c } from "./_generated/server";
37
37
 
38
- const ${r}List = defineListArgs<Doc<${b(e.name)}>>()({
38
+ const ${a}List = defineListArgs<Doc<${f(e.name)}>>()({
39
39
  // Only index-backed columns are published as filterable, so a caller cannot
40
40
  // reach a column you did not choose to expose. Note that \`contains\` and the
41
41
  // negative operators still scan — narrow this list, and review it, before
@@ -47,22 +47,22 @@ ${c.join(`
47
47
  orderBy: [${m}],
48
48
  });
49
49
 
50
- export const list = c.query.input(${r}List.args).query(({ args, ctx }) => ${d}.findMany(${r}List.toQueryArgs(args)));
50
+ export const list = c.query.input(${a}List.args).query(({ args, ctx }) => ${u}.findMany(${a}List.toQueryArgs(args)));
51
51
 
52
- export const get = c.query.input({ id: v.id(${b(e.name)}) }).query(({ args, ctx }) => ${d}.get(args.id));
53
- `},ce=(e,n)=>{const t=[],a=new Set(e.tables.map(r=>r.name)),s=[{contents:ie(e,n,t),path:"schema.ts"}];if(n.procedures){const r=new Map([["schema","the generated schema module"]]);for(const i of e.tables){if(C(i).length===0){t.push(`${i.name}: no usable columns — procedure module skipped.`);continue}const o=ne(i.name);o!==i.name&&t.push(`${i.name}: written as \`${o}.ts\` — the table name isn't usable as a filename.`);const c=r.get(o);if(c!==void 0){t.push(`${i.name}: procedure module skipped — its filename \`${o}.ts\` collides with table \`${c}\`.`);continue}r.set(o,i.name),s.push({contents:oe(i,e.dialect,n,a,t),path:`${o}.ts`})}}return{files:s,warnings:t}},_=/^[A-Z_$][\w$]*$/i,me=e=>e.startsWith("v.optional(")&&e.endsWith(")")?e.slice(11,-1):e,le=(e,n,t)=>{const a=[],s=new Set(n?.columns.map(r=>r.name));for(const r of e.columns){if(h.has(r.name)||s.has(r.name))continue;if(!_.test(r.name)){t.warnings.push(`${e.name}.${r.name}: skipped — column names must be bare identifiers to merge.`);continue}const i=r.references!==void 0&&!t.present.has(r.references.table),{expression:o}=N(i?{...r,references:void 0}:r,t.dialect);a.push({column:r.name,kind:"addOptionalColumn",table:e.name,validator:me(o)}),!r.nullable&&n!==void 0&&t.warnings.push(`${e.name}.${r.name}: added as \`v.optional(...)\` — a required column on an existing table needs a backfill migration.`)}return a},ue=(e,n,t)=>{const a=[],s=new Set(n?.indexes.map(r=>r.name));for(const r of e.indexes){const i=r.columns.filter(o=>!h.has(o));if(!(s.has(r.name)||i.length===0)){if(!_.test(r.name)||!i.every(o=>_.test(o))){t.push(`${e.name}: index \`${r.name}\` skipped — index and column names must be bare identifiers to merge.`);continue}a.push({fields:i,kind:"addIndex",name:r.name,table:e.name,...r.unique?{unique:!0}:{}})}}return a},de=(e,n,t)=>{const a=[],s=[],r=new Map(n.map(o=>[o.name,o])),i=new Set([...r.keys(),...e.tables.map(o=>o.name)]);for(const o of e.tables){if(!_.test(o.name)){s.push(`${o.name}: skipped — merging into an existing schema needs a table name that is a bare identifier.`);continue}const c=r.get(o.name);c===void 0&&a.push({global:{backend:"hyperdrive"},kind:"addTable",table:o.name}),a.push(...le(o,c,{dialect:t,present:i,warnings:s}),...ue(o,c,s))}return{edits:a,warnings:s}},pe=(e,n,t)=>{const a=Y(e);if(!a.ok)return{applied:0,warnings:[`lunora/schema.ts could not be parsed (${a.reason}) — leave it alone and merge by hand, or pass --force.`]};const s=de(n,a.tables,t),r=[...s.warnings];let i=e,o=0;for(const c of s.edits){const m=j(i,c);m.ok?(i=m.text,o+=1):r.push(`${c.table}: skipped one edit (${m.reason}).`)}return{applied:o,warnings:r,...o===0?{}:{text:i}}},u=(e,n)=>{const t=e[n]??e[n.toLowerCase()]??e[n.toUpperCase()];return typeof t=="string"?t:typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"?String(t):""},ge=`
52
+ export const get = c.query.input({ id: v.id(${f(e.name)}) }).query(({ args, ctx }) => ${u}.get(args.id));
53
+ `},ce=(e,t)=>{const n=[],r=new Set(e.tables.map(a=>a.name)),s=[{contents:oe(e,t,n),path:"schema.ts"}];if(t.procedures){const a=new Map([["schema","the generated schema module"]]);for(const o of e.tables){if(C(o).length===0){n.push(`${o.name}: no usable columns — procedure module skipped.`);continue}const i=te(o.name);i!==o.name&&n.push(`${o.name}: written as \`${i}.ts\` — the table name isn't usable as a filename.`);const c=a.get(i);if(c!==void 0){n.push(`${o.name}: procedure module skipped — its filename \`${i}.ts\` collides with table \`${c}\`.`);continue}a.set(i,o.name),s.push({contents:ie(o,e.dialect,t,r,n),path:`${i}.ts`})}}return{files:s,warnings:n}},_=/^[A-Z_$][\w$]*$/i,me=e=>e.startsWith("v.optional(")&&e.endsWith(")")?e.slice(11,-1):e,le=(e,t,n)=>{const r=[],s=new Set(t?.columns.map(a=>a.name));for(const a of e.columns){if(h.has(a.name)||s.has(a.name))continue;if(!_.test(a.name)){n.warnings.push(`${e.name}.${a.name}: skipped — column names must be bare identifiers to merge.`);continue}const o=a.references!==void 0&&!n.present.has(a.references.table),{expression:i}=w(o?{...a,references:void 0}:a,n.dialect);r.push({column:a.name,kind:"addOptionalColumn",table:e.name,validator:me(i)}),!a.nullable&&t!==void 0&&n.warnings.push(`${e.name}.${a.name}: added as \`v.optional(...)\` — a required column on an existing table needs a backfill migration.`)}return r},ue=(e,t,n)=>{const r=[],s=new Set(t?.indexes.map(a=>a.name));for(const a of e.indexes){const o=a.columns.filter(i=>!h.has(i));if(!(s.has(a.name)||o.length===0)){if(!_.test(a.name)||!o.every(i=>_.test(i))){n.push(`${e.name}: index \`${a.name}\` skipped — index and column names must be bare identifiers to merge.`);continue}r.push({fields:o,kind:"addIndex",name:a.name,table:e.name,...a.unique?{unique:!0}:{}})}}return r},de=(e,t,n)=>{const r=[],s=[],a=new Map(t.map(i=>[i.name,i])),o=new Set([...a.keys(),...e.tables.map(i=>i.name)]);for(const i of e.tables){if(!_.test(i.name)){s.push(`${i.name}: skipped — merging into an existing schema needs a table name that is a bare identifier.`);continue}const c=a.get(i.name);c===void 0&&r.push({global:{backend:"hyperdrive"},kind:"addTable",table:i.name}),r.push(...le(i,c,{dialect:n,present:o,warnings:s}),...ue(i,c,s))}return{edits:r,warnings:s}},pe=(e,t,n)=>{const r=F(e);if(!r.ok)return{applied:0,warnings:[`lunora/schema.ts could not be parsed (${r.reason}) — leave it alone and merge by hand, or pass --force.`]};const s=de(t,r.tables,n),a=[...s.warnings];let o=e,i=0;for(const c of s.edits){const m=P(o,c);m.ok?(o=m.text,i+=1):a.push(`${c.table}: skipped one edit (${m.reason}).`)}return{applied:i,warnings:a,...i===0?{}:{text:o}}},g=(e,t)=>{const n=e[t]??e[t.toLowerCase()]??e[t.toUpperCase()];return typeof n=="string"?n:typeof n=="number"||typeof n=="bigint"||typeof n=="boolean"?String(n):""},ge=`
54
54
  SELECT c.table_name, c.column_name, c.is_nullable, c.data_type, c.udt_name
55
55
  FROM information_schema.columns c
56
56
  JOIN information_schema.tables t
57
57
  ON t.table_schema = c.table_schema AND t.table_name = c.table_name
58
58
  WHERE c.table_schema = $1 AND t.table_type = 'BASE TABLE'
59
- ORDER BY c.table_name, c.ordinal_position`,be=`
59
+ ORDER BY c.table_name, c.ordinal_position`,fe=`
60
60
  SELECT tc.table_name, kcu.column_name
61
61
  FROM information_schema.table_constraints tc
62
62
  JOIN information_schema.key_column_usage kcu
63
63
  ON kcu.constraint_name = tc.constraint_name AND kcu.table_schema = tc.table_schema
64
64
  WHERE tc.table_schema = $1 AND tc.constraint_type = 'PRIMARY KEY'
65
- ORDER BY tc.table_name, kcu.ordinal_position`,fe=`
65
+ ORDER BY tc.table_name, kcu.ordinal_position`,ve=`
66
66
  SELECT tc.table_name, kcu.column_name, ccu.table_name AS foreign_table, ccu.column_name AS foreign_column
67
67
  FROM information_schema.table_constraints tc
68
68
  JOIN information_schema.key_column_usage kcu
@@ -78,22 +78,22 @@ export const get = c.query.input({ id: v.id(${b(e.name)}) }).query(({ args, ctx
78
78
  CROSS JOIN LATERAL unnest(ix.indkey) WITH ORDINALITY AS k(attnum, ord)
79
79
  JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum
80
80
  WHERE n.nspname = $1 AND t.relkind = 'r' AND NOT ix.indisprimary
81
- ORDER BY t.relname, i.relname, k.ord`,ve=`
81
+ ORDER BY t.relname, i.relname, k.ord`,be=`
82
82
  SELECT c.TABLE_NAME, c.COLUMN_NAME, c.IS_NULLABLE, c.DATA_TYPE
83
83
  FROM information_schema.COLUMNS c
84
84
  JOIN information_schema.TABLES t
85
85
  ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME
86
86
  WHERE c.TABLE_SCHEMA = ? AND t.TABLE_TYPE = 'BASE TABLE'
87
- ORDER BY c.TABLE_NAME, c.ORDINAL_POSITION`,ye=`
87
+ ORDER BY c.TABLE_NAME, c.ORDINAL_POSITION`,Ee=`
88
88
  SELECT TABLE_NAME, COLUMN_NAME
89
89
  FROM information_schema.KEY_COLUMN_USAGE
90
90
  WHERE TABLE_SCHEMA = ? AND CONSTRAINT_NAME = 'PRIMARY'
91
91
  ORDER BY TABLE_NAME, ORDINAL_POSITION`,_e=`
92
92
  SELECT TABLE_NAME, COLUMN_NAME, REFERENCED_TABLE_NAME AS foreign_table, REFERENCED_COLUMN_NAME AS foreign_column
93
93
  FROM information_schema.KEY_COLUMN_USAGE
94
- WHERE TABLE_SCHEMA = ? AND REFERENCED_TABLE_NAME IS NOT NULL`,Ee=`
94
+ WHERE TABLE_SCHEMA = ? AND REFERENCED_TABLE_NAME IS NOT NULL`,ye=`
95
95
  SELECT TABLE_NAME, INDEX_NAME AS index_name, NON_UNIQUE, COLUMN_NAME
96
96
  FROM information_schema.STATISTICS
97
97
  WHERE TABLE_SCHEMA = ? AND INDEX_NAME <> 'PRIMARY'
98
- ORDER BY TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX`,y=e=>{const n=new Map;for(const t of e){const a=u(t,"table_name"),s=n.get(a);s===void 0?n.set(a,[t]):s.push(t)}return n},Ae=(e,n)=>{const t=u(e,"data_type").toLowerCase();if(n!=="postgres")return{arrayDepth:0,dataType:t};const a=u(e,"udt_name").toLowerCase();return t==="array"&&a.startsWith("_")?{arrayDepth:1,dataType:a.slice(1)}:{arrayDepth:0,dataType:a===""?t:a}},$e=(e,n)=>{const t=new Map;for(const a of e){const s=u(a,"index_name"),r=n==="postgres"?u(a,"is_unique")==="true":u(a,"NON_UNIQUE")==="0",i=t.get(s);i===void 0?t.set(s,{columns:[u(a,"column_name")],unique:r}):i.columns.push(u(a,"column_name"))}return[...t.entries()].map(([a,s])=>({columns:s.columns,name:a,unique:s.unique}))},we=async(e,n,t)=>{const a=n==="postgres",[s,r,i,o]=await Promise.all([e(a?ge:ve,[t]),e(a?be:ye,[t]),e(a?fe:_e,[t]),e(a?he:Ee,[t])]),c=y(r),m=y(i),d=y(o),l=[];for(const[g,p]of y(s)){const E=new Map((m.get(g)??[]).map(f=>[u(f,"column_name"),{column:u(f,"foreign_column"),table:u(f,"foreign_table")}])),A=p.map(f=>{const S=u(f,"column_name"),L=E.get(S);return{...Ae(f,n),name:S,nullable:u(f,"is_nullable").toUpperCase()==="YES",...L===void 0?{}:{references:L}}});l.push({columns:A,indexes:$e(d.get(g)??[],n),name:g,primaryKey:(c.get(g)??[]).map(f=>u(f,"column_name"))})}return l.sort((g,p)=>g.name.localeCompare(p.name)),{dialect:n,tables:l}},Ne=e=>{try{const n=JSON.parse(O(v(e,"package.json"),"utf8"));return n.dependencies?.lunorash===void 0&&n.devDependencies?.lunorash===void 0?"@lunora/server":"lunorash/server"}catch{return"@lunora/server"}},Se=async(e,n,t)=>{const a=v(n,e.path);return T(a)&&t.force!==!0?(t.logger.warn(`skipped lunora/${e.path} — it already exists (pass --force to overwrite)`),!1):t.dryRun===!0?(t.logger.info(`would write lunora/${e.path} (${String(e.contents.split(`
99
- `).length)} lines)`),!1):(await D(n,{recursive:!0}),await x(a,e.contents,"utf8"),t.logger.info(`wrote lunora/${e.path}`),!0)},Le=(e,n)=>{const t=n.tables;if(t===void 0||t.length===0)return e.tables;for(const a of t)e.tables.some(s=>s.name===a)||n.logger.warn(`--tables: no table named "${a}" exists in this schema — skipped.`);return e.tables.filter(a=>t.includes(a.name))},Re=async(e,n,t,a)=>{const s=pe(O(e,"utf8"),n,t);for(const r of s.warnings)a.logger.warn(r);return s.text===void 0?(a.logger.info("lunora/schema.ts is already up to date with the database."),!1):a.dryRun===!0?(a.logger.info(`would merge ${String(s.applied)} addition(s) into lunora/schema.ts`),!1):(await x(e,s.text,"utf8"),a.logger.info(`merged ${String(s.applied)} addition(s) into lunora/schema.ts`),!0)},Te=async e=>{const n=e.cwd??process.cwd();if(e.connection===void 0&&(e.url===void 0||e.url===""))return e.logger.error("`lunora introspect` needs a database URL: pass --url, or set DATABASE_URL."),{code:1,written:[]};const t=e.connection===void 0?P(e.url):e.dialect??"postgres",a=e.connection??await K(e.url,t,e.schema,n);let s;try{s=await we(a.execute,t,a.schema)}finally{e.connection===void 0&&await a.close()}const r=Le(s,e);if(r.length===0)return e.logger.error("no tables found to introspect — check --schema and --tables."),{code:1,written:[]};const{files:i,warnings:o}=ce({...s,tables:r},{procedures:e.procedures!==!1,serverImport:Ne(n)}),c=v(n,"lunora"),m=[],d=v(c,"schema.ts"),l=T(d)&&e.force!==!0,g=l?i.filter(p=>p.path!=="schema.ts"):i;l&&await Re(d,{tables:r},t,e)&&m.push("schema.ts");for(const p of g)await Se(p,c,e)&&m.push(p.path);for(const p of o)e.logger.warn(p);return e.logger.info(`introspected ${String(r.length)} table(s) from ${t}. Review the generated files before running \`lunora dev\`.`),{code:0,written:m}},qe=B(async({cwd:e,logger:n,options:t})=>({code:(await Te({cwd:e,dryRun:t.dryRun===!0,force:t.force===!0,logger:n,procedures:t.procedures!==!1,schema:t.schema,tables:t.tables===void 0?void 0:t.tables.split(",").map(a=>a.trim()),url:t.url??process.env.DATABASE_URL})).code}));export{qe as execute,Ne as resolveServerImport,Te as runIntrospectCommand};
98
+ ORDER BY TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX`,E=e=>{const t=new Map;for(const n of e){const r=g(n,"table_name"),s=t.get(r);s===void 0?t.set(r,[n]):s.push(n)}return t},Ae=(e,t)=>{const n=g(e,"data_type").toLowerCase();if(t!=="postgres")return{arrayDepth:0,dataType:n};const r=g(e,"udt_name").toLowerCase();return n==="array"&&r.startsWith("_")?{arrayDepth:1,dataType:r.slice(1)}:{arrayDepth:0,dataType:r===""?n:r}},Se=(e,t)=>{const n=new Map;for(const r of e){const s=g(r,"index_name"),a=t==="postgres"?g(r,"is_unique")==="true":g(r,"NON_UNIQUE")==="0",o=n.get(s);o===void 0?n.set(s,{columns:[g(r,"column_name")],unique:a}):o.columns.push(g(r,"column_name"))}return[...n.entries()].map(([r,s])=>({columns:s.columns,name:r,unique:s.unique}))},Ne=async(e,t,n)=>{const r=t==="postgres",[s,a,o,i]=await Promise.all([e(r?ge:be,[n]),e(r?fe:Ee,[n]),e(r?ve:_e,[n]),e(r?he:ye,[n])]),c=E(a),m=E(o),u=E(i),l=[];for(const[d,p]of E(s)){const y=new Map((m.get(d)??[]).map(v=>[g(v,"column_name"),{column:g(v,"foreign_column"),table:g(v,"foreign_table")}])),A=p.map(v=>{const R=g(v,"column_name"),$=y.get(R);return{...Ae(v,t),name:R,nullable:g(v,"is_nullable").toUpperCase()==="YES",...$===void 0?{}:{references:$}}});l.push({columns:A,indexes:Se(u.get(d)??[],t),name:d,primaryKey:(c.get(d)??[]).map(v=>g(v,"column_name"))})}return l.sort((d,p)=>d.name.localeCompare(p.name)),{dialect:t,tables:l}},we=e=>{try{const t=JSON.parse(O(b(e,"package.json"),"utf8"));return t.dependencies?.lunorash===void 0&&t.devDependencies?.lunorash===void 0?"@lunora/server":"lunorash/server"}catch{return"@lunora/server"}},Re=async(e,t,n)=>{const r=b(t,e.path);return T(r)&&n.force!==!0?(n.logger.warn(`skipped lunora/${e.path} — it already exists (pass --force to overwrite)`),!1):n.dryRun===!0?(n.logger.info(`would write lunora/${e.path} (${String(e.contents.split(`
99
+ `).length)} lines)`),!1):(await k(t,{recursive:!0}),await I(r,e.contents,"utf8"),n.logger.info(`wrote lunora/${e.path}`),!0)},$e=(e,t)=>{const n=t.tables;if(n===void 0||n.length===0)return e.tables;for(const r of n)e.tables.some(s=>s.name===r)||t.logger.warn(`--tables: no table named "${r}" exists in this schema — skipped.`);return e.tables.filter(r=>n.includes(r.name))},Le=async(e,t,n,r)=>{const s=pe(O(e,"utf8"),t,n);for(const a of s.warnings)r.logger.warn(a);return s.text===void 0?(r.logger.info("lunora/schema.ts is already up to date with the database."),!1):r.dryRun===!0?(r.logger.info(`would merge ${String(s.applied)} addition(s) into lunora/schema.ts`),!1):(await I(e,s.text,"utf8"),r.logger.info(`merged ${String(s.applied)} addition(s) into lunora/schema.ts`),!0)},Te=async e=>{const t=e.cwd??process.cwd();if(e.connection===void 0&&(e.url===void 0||e.url===""))return e.logger.error("`lunora introspect` needs a database URL: pass --url, or set DATABASE_URL."),{code:1,written:[]};const n=e.connection===void 0?j(e.url):e.dialect??"postgres",r=e.connection??await J(e.url,n,e.schema,t);let s;try{s=await Ne(r.execute,n,r.schema)}finally{e.connection===void 0&&await r.close()}const a=$e(s,e);if(a.length===0)return e.logger.error("no tables found to introspect — check --schema and --tables."),{code:1,written:[]};const{files:o,warnings:i}=ce({...s,tables:a},{procedures:e.procedures!==!1,serverImport:we(t)}),c=b(t,"lunora"),m=[],u=b(c,"schema.ts"),l=T(u)&&e.force!==!0,d=l?o.filter(p=>p.path!=="schema.ts"):o;l&&await Le(u,{...s,tables:a},n,e)&&m.push("schema.ts");for(const p of d)await Re(p,c,e)&&m.push(p.path);for(const p of i)e.logger.warn(p);return e.logger.info(`introspected ${String(a.length)} table(s) from ${n}. Review the generated files before running \`lunora dev\`.`),{code:0,written:m}},Ue=B(async({cwd:e,logger:t,options:n})=>({code:(await Te({cwd:e,dryRun:n.dryRun===!0,force:n.force===!0,logger:t,procedures:n.procedures!==!1,schema:n.schema,tables:n.tables===void 0?void 0:n.tables.split(",").map(s=>s.trim()),url:n.url??process.env.DATABASE_URL})).code}));export{Ue as execute,we as resolveServerImport,Te as runIntrospectCommand};
@@ -1,10 +1,10 @@
1
- import{i as L}from"../packem_shared/cli-Cu92injU.mjs";import{i as J}from"../packem_shared/command-0l-ZPhIX.mjs";import{existsSync as p,readFileSync as h,mkdirSync as P,realpathSync as W,statSync as D,writeFileSync as T,chmodSync as z,renameSync as H,unlinkSync as I}from"node:fs";import{homedir as $}from"node:os";import{findWranglerFile as K}from"@lunora/config/cloudflare";import{join as s,dirname as q,relative as G}from"@visulima/path";import{l as V,M as Z}from"../packem_shared/detect-package-manager-DXDstphE.mjs";import{stringify as B}from"smol-toml";import{parse as Q,modify as X,applyEdits as Y}from"jsonc-parser";import{readLiveDevServerState as y}from"@lunora/config";import{resolveAdminToken as oo}from"@lunora/config/studio-host";import{connectLocalStdio as to}from"@lunora/mcp";const u=o=>({args:[...o.args],command:o.command,...o.env===void 0?{}:{env:o.env}}),v=o=>o.transport==="http"?{type:"http",url:o.url}:u(o),eo=o=>o.transport==="http"?{httpUrl:o.url}:u(o),ro=o=>o.transport==="http"?{serverUrl:o.url}:u(o),no=o=>({args:["-y","mcp-remote",o],command:"npx"}),ao=o=>o.transport==="http"?no(o.url):u(o),io=o=>o.transport==="http"?{url:o.url}:u(o),lo=o=>o.transport==="http"?{enabled:!0,type:"remote",url:o.url}:{command:[o.command,...o.args],enabled:!0,type:"local",...o.env===void 0?{}:{environment:o.env}},so=o=>o.transport==="http"?{disabled:!1,type:"streamableHttp",url:o.url}:{disabled:!1,...u(o)},co=({home:o,platform:t})=>{if(t==="darwin")return{global:s(o,"Library","Application Support","Claude","claude_desktop_config.json")};if(t==="win32"){const e=process.env.APPDATA;return e===void 0||e===""?{}:{global:s(e,"Claude","claude_desktop_config.json")}}return t==="linux"?{global:s(o,".config","Claude","claude_desktop_config.json")}:{}},po=(o,t)=>B({mcp_servers:{[o]:t.transport==="http"?{url:t.url}:{args:[...t.args],command:t.command,...t.env===void 0?{}:{env:t.env}}}}),g=[{buildEntry:v,paths:({projectRoot:o})=>({project:s(o,".mcp.json")}),format:"json",id:"claude-code",key:"mcpServers",label:"Claude Code"},{buildEntry:v,paths:({home:o,projectRoot:t})=>({global:s(o,".cursor","mcp.json"),project:s(t,".cursor","mcp.json")}),format:"json",id:"cursor",key:"mcpServers",label:"Cursor"},{buildEntry:v,paths:({projectRoot:o})=>({project:s(o,".vscode","mcp.json")}),format:"json",id:"vscode",key:"servers",label:"VS Code (GitHub Copilot)"},{buildEntry:eo,paths:({home:o,projectRoot:t})=>({global:s(o,".gemini","settings.json"),project:s(t,".gemini","settings.json")}),format:"json",id:"gemini",key:"mcpServers",label:"Gemini CLI"},{buildEntry:ao,paths:co,format:"json",id:"claude-desktop",key:"mcpServers",label:"Claude Desktop"},{buildEntry:ro,paths:({home:o})=>({global:s(o,".codeium","windsurf","mcp_config.json")}),format:"json",id:"windsurf",key:"mcpServers",label:"Windsurf"},{buildEntry:lo,paths:({home:o,projectRoot:t})=>({global:s(o,".config","opencode","opencode.json"),project:s(t,"opencode.json")}),format:"json",id:"opencode",key:"mcp",label:"OpenCode"},{buildEntry:so,paths:({home:o})=>({global:s(o,".cline","mcp.json")}),format:"json",id:"cline",key:"mcpServers",label:"Cline"},{buildEntry:io,paths:({home:o})=>({global:s(o,".config","zed","settings.json")}),format:"json",id:"zed",key:"context_servers",label:"Zed"},{paths:({home:o,projectRoot:t})=>({global:s(o,".codex","config.toml"),project:s(t,".codex","config.toml")}),format:"manual",id:"codex",label:"Codex CLI",renderSnippet:po}],O=g.map(o=>o.id),uo=o=>g.find(t=>t.id===o.toLowerCase()),x=(o,t)=>{let e=o,r;try{e=W(o),r=D(e).mode}catch{}const a=`${e}.lunora-${Math.random().toString(36).slice(2,10)}.tmp`;try{T(a,t,"utf8"),r!==void 0&&z(a,r),H(a,e)}catch(n){try{I(a)}catch{}throw n}},mo={formattingOptions:{insertSpaces:!0,tabSize:4}},b=o=>{const t=[],e=Q(o,t,{allowTrailingComma:!0});return{errors:t,value:e}},f=o=>typeof o=="object"&&o!==null&&!Array.isArray(o),w=(o,t,e)=>{if(!f(o))return;const r=o[t];return f(r)?r[e]:void 0},C=o=>{if(!p(o.path))return"absent";let t;try{t=h(o.path,"utf8")}catch{return"invalid"}if(t.trim().length===0)return"absent";const{errors:e,value:r}=b(t);return e.length>0||!f(r)?"invalid":w(r,o.key,o.name)===void 0?"absent":"present"},fo=o=>C(o)==="present",E=(o,t,e,r,a)=>{try{const n=X(o,[e,r],a,mo);n.length>0&&x(t,Y(o,n));return}catch(n){return n instanceof Error?n.message:String(n)}},go=o=>{const{entry:t,force:e=!1,key:r,name:a,path:n}=o,i=p(n)?h(n,"utf8"):"";if(i.trim().length===0)return P(q(n),{recursive:!0}),x(n,`${JSON.stringify({[r]:{[a]:t}},void 0,4)}
2
- `),{action:"created",path:n};const{errors:l,value:c}=b(i);if(l.length>0)return{action:"invalid",error:`parse error at offset ${String(l[0]?.offset??0)}`,path:n};if(!f(c))return{action:"invalid",error:"the file's root is not a JSON object",path:n};const m=c[r];if(m!==void 0&&!f(m))return{action:"invalid",error:`"${r}" is not an object`,path:n};if(w(c,r,a)!==void 0&&!e)return{action:"skipped",path:n};const j=E(i,n,r,a,t);return j===void 0?{action:"updated",path:n}:{action:"invalid",error:j,path:n}},ho=o=>{const{key:t,name:e,path:r}=o;if(!p(r))return{action:"absent",path:r};let a;try{a=h(r,"utf8")}catch(c){return{action:"invalid",error:c instanceof Error?c.message:String(c),path:r}}const{errors:n,value:i}=b(a);if(n.length>0)return{action:"invalid",error:`parse error at offset ${String(n[0]?.offset??0)}`,path:r};if(w(i,t,e)===void 0)return{action:"absent",path:r};const l=E(a,r,t,e,void 0);return l===void 0?{action:"removed",path:r}:{action:"invalid",error:l,path:r}},vo=["global","project"],d=(o,t)=>{const e=G(t,o);return e.length>0&&!e.startsWith("..")?e:o},yo=(o,t)=>{const e=o.paths(t);return vo.flatMap(r=>{const a=e[r];return a===void 0?[]:[{client:o,path:a,scope:r}]})},$o=(o,t,e,r)=>{const a=o.paths(t),n=e==="global"?"project":"global",i=a[e]??(r?void 0:a[n]);if(i!==void 0)return{client:o,path:i,scope:a[e]===void 0?n:e}},bo=o=>g.filter(t=>Object.values(t.paths(o)).some(e=>p(e))),R=(o,t,e,r)=>{if(o.length===0)return t();const a=[];for(const n of o){const i=uo(n);if(i===void 0){e.error(`mcp ${r}: unknown client "${n}". Known clients: ${O.join(", ")}.`);return}a.push(i)}return a},wo=o=>o.client.format==="json",jo="https://lunora.sh/mcp",U="lunora-docs",N="lunora",ko=o=>p(s(o,"lunora"))&&K(o)!==void 0,So=o=>{const{args:t,command:e}=Z(o,"lunora",["mcp","serve"]);return{args:t,command:e,transport:"stdio"}},Oo=o=>({transport:"http",url:o}),xo=o=>({home:o.home,platform:o.platform,projectRoot:o.cwd}),_=(o,t,e)=>$o(o,xo(e),e.scope??t.preferredScope,e.scope!==void 0||!t.allowScopeFallback),Co=(o,t,e)=>{const r=_(o,t,e);if(r===void 0){e.logger.warn(`${o.label}: has no ${e.scope??t.preferredScope}-scoped config — skipped "${t.name}".`);return}const{path:a}=r,n=o.buildEntry(t.spec);if(e.print===!0){const c=d(a,e.cwd);return e.force!==!0&&fo({key:o.key,name:t.name,path:a})?(e.logger.info(`${o.label}: "${t.name}" already configured in ${c} — a real install would skip it (re-run with --force to replace).`),{action:"printed",path:a}):(e.logger.info(`${o.label} → ${c}
3
- ${JSON.stringify({[o.key]:{[t.name]:n}},void 0,4)}`),{action:"printed",path:a})}const i=go({entry:n,force:e.force===!0,key:o.key,name:t.name,path:a}),l=d(a,e.cwd);return i.action==="invalid"?e.logger.error(`${o.label}: ${l} is not valid JSON (${i.error??"unknown error"}) — left untouched.`):i.action==="skipped"?e.logger.info(`${o.label}: "${t.name}" already configured in ${l} — re-run with --force to replace it.`):e.logger.success(`${o.label}: ${i.action==="created"?"created":"updated"} ${l} with "${t.name}".`),{action:i.action,path:a}},Eo=(o,t,e)=>{const r=_(o,t,e)?.path;if(r===void 0){e.logger.warn(`${o.label}: no known config location on ${e.platform} — skipped.`);return}return e.logger.info(`${o.label}: add this to ${d(r,e.cwd)}
1
+ import{V as R}from"../packem_shared/cli-ULexksQd.mjs";import{d as T}from"../packem_shared/command-DwC11Cwe.mjs";import{existsSync as u,readFileSync as v,mkdirSync as D,realpathSync as I,statSync as J,writeFileSync as W,chmodSync as z,renameSync as G,unlinkSync as H}from"node:fs";import{homedir as b}from"node:os";import{findWranglerFile as V}from"@lunora/config/cloudflare";import{join as s,dirname as K,relative as q}from"@visulima/path";import{d as B,e as X}from"../packem_shared/detect-package-manager-DSaAqRof.mjs";import{stringify as Z}from"smol-toml";import{parse as Q,modify as Y,applyEdits as ee}from"jsonc-parser";import{readLiveDevServerState as y}from"@lunora/config";import{resolveAdminToken as re}from"@lunora/config/studio-host";import{connectLocalStdio as te}from"@lunora/mcp";const f=e=>({args:[...e.args],command:e.command,...e.env===void 0?{}:{env:e.env}}),h=e=>e.transport==="http"?{type:"http",url:e.url}:f(e),ne=e=>e.transport==="http"?{httpUrl:e.url}:f(e),oe=e=>e.transport==="http"?{serverUrl:e.url}:f(e),ae=e=>({args:["-y","mcp-remote",e],command:"npx"}),le=e=>e.transport==="http"?ae(e.url):f(e),ce=e=>e.transport==="http"?{url:e.url}:f(e),se=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}},ie=e=>e.transport==="http"?{disabled:!1,type:"streamableHttp",url:e.url}:{disabled:!1,...f(e)},de=({home:e,platform:r})=>{if(r==="darwin")return{global:s(e,"Library","Application Support","Claude","claude_desktop_config.json")};if(r==="win32"){const t=process.env.APPDATA;return t===void 0||t===""?{}:{global:s(t,"Claude","claude_desktop_config.json")}}return r==="linux"?{global:s(e,".config","Claude","claude_desktop_config.json")}:{}},ue=(e,r)=>Z({mcp_servers:{[e]:r.transport==="http"?{url:r.url}:{args:[...r.args],command:r.command,...r.env===void 0?{}:{env:r.env}}}}),p=[{buildEntry:h,paths:({projectRoot:e})=>({project:s(e,".mcp.json")}),format:"json",id:"claude-code",key:"mcpServers",label:"Claude Code"},{buildEntry:h,paths:({home:e,projectRoot:r})=>({global:s(e,".cursor","mcp.json"),project:s(r,".cursor","mcp.json")}),format:"json",id:"cursor",key:"mcpServers",label:"Cursor"},{buildEntry:h,paths:({projectRoot:e})=>({project:s(e,".vscode","mcp.json")}),format:"json",id:"vscode",key:"servers",label:"VS Code (GitHub Copilot)"},{buildEntry:ne,paths:({home:e,projectRoot:r})=>({global:s(e,".gemini","settings.json"),project:s(r,".gemini","settings.json")}),format:"json",id:"gemini",key:"mcpServers",label:"Gemini CLI"},{buildEntry:le,paths:de,format:"json",id:"claude-desktop",key:"mcpServers",label:"Claude Desktop"},{buildEntry:oe,paths:({home:e})=>({global:s(e,".codeium","windsurf","mcp_config.json")}),format:"json",id:"windsurf",key:"mcpServers",label:"Windsurf"},{buildEntry:se,paths:({home:e,projectRoot:r})=>({global:s(e,".config","opencode","opencode.json"),project:s(r,"opencode.json")}),format:"json",id:"opencode",key:"mcp",label:"OpenCode"},{buildEntry:ie,paths:({home:e})=>({global:s(e,".cline","mcp.json")}),format:"json",id:"cline",key:"mcpServers",label:"Cline"},{buildEntry:ce,paths:({home:e})=>({global:s(e,".config","zed","settings.json")}),format:"json",id:"zed",key:"context_servers",label:"Zed"},{paths:({home:e,projectRoot:r})=>({global:s(e,".codex","config.toml"),project:s(r,".codex","config.toml")}),format:"manual",id:"codex",label:"Codex CLI",renderSnippet:ue}],O=p.map(e=>e.id),fe=e=>p.find(r=>r.id===e.toLowerCase()),C=(e,r)=>{let t=e,n;try{t=I(e),n=J(t).mode}catch{}const a=`${t}.lunora-${Math.random().toString(36).slice(2,10)}.tmp`;try{W(a,r,"utf8"),n!==void 0&&z(a,n),G(a,t)}catch(o){try{H(a)}catch{}throw o}},me={formattingOptions:{insertSpaces:!0,tabSize:4}},w=e=>{const r=[],t=Q(e,r,{allowTrailingComma:!0});return{errors:r,value:t}},g=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),S=(e,r,t)=>{if(!g(e))return;const n=e[r];return g(n)?n[t]:void 0},x=e=>{if(!u(e.path))return"absent";let r;try{r=v(e.path,"utf8")}catch{return"invalid"}if(r.trim().length===0)return"absent";const{errors:t,value:n}=w(r);return t.length>0||!g(n)?"invalid":S(n,e.key,e.name)===void 0?"absent":"present"},ge=e=>x(e)==="present",M=(e,r,t,n,a)=>{try{const o=Y(e,[t,n],a,me);o.length>0&&C(r,ee(e,o));return}catch(o){return o instanceof Error?o.message:String(o)}},pe=e=>{const{entry:r,force:t=!1,key:n,name:a,path:o}=e,l=u(o)?v(o,"utf8"):"";if(l.trim().length===0)return D(K(o),{recursive:!0}),C(o,`${JSON.stringify({[n]:{[a]:r}},void 0,4)}
2
+ `),{action:"created",path:o};const{errors:c,value:i}=w(l);if(c.length>0)return{action:"invalid",error:`parse error at offset ${String(c[0]?.offset??0)}`,path:o};if(!g(i))return{action:"invalid",error:"the file's root is not a JSON object",path:o};const m=i[n];if(m!==void 0&&!g(m))return{action:"invalid",error:`"${n}" is not an object`,path:o};if(S(i,n,a)!==void 0&&!t)return{action:"skipped",path:o};const k=M(l,o,n,a,r);return k===void 0?{action:"updated",path:o}:{action:"invalid",error:k,path:o}},ve=e=>{const{key:r,name:t,path:n}=e;if(!u(n))return{action:"absent",path:n};let a;try{a=v(n,"utf8")}catch(i){return{action:"invalid",error:i instanceof Error?i.message:String(i),path:n}}const{errors:o,value:l}=w(a);if(o.length>0)return{action:"invalid",error:`parse error at offset ${String(o[0]?.offset??0)}`,path:n};if(S(l,r,t)===void 0)return{action:"absent",path:n};const c=M(a,n,r,t,void 0);return c===void 0?{action:"removed",path:n}:{action:"invalid",error:c,path:n}},he=["global","project"],d=(e,r)=>{const t=q(r,e);return t.length>0&&!t.startsWith("..")?t:e},ye=(e,r)=>{const t=e.paths(r);return he.flatMap(n=>{const a=t[n];return a===void 0?[]:[{client:e,path:a,scope:n}]})},be=(e,r,t,n)=>{const a=e.paths(r),o=t==="global"?"project":"global",l=a[t]??(n?void 0:a[o]);if(l!==void 0)return{client:e,path:l,scope:a[t]===void 0?o:t}},we=e=>p.filter(r=>Object.values(r.paths(e)).some(t=>u(t))),_=(e,r,t,n)=>{if(e.length===0)return r();const a=[];for(const o of e){const l=fe(o);if(l===void 0){t.error(`mcp ${n}: unknown client "${o}". Known clients: ${O.join(", ")}.`);return}a.push(l)}return a},Se=e=>e.client.format==="json",ke="https://lunora.sh/mcp",L="lunora-docs",N="lunora",je=e=>u(s(e,"lunora"))&&V(e)!==void 0,$e=e=>{const{args:r,command:t}=X(e,"lunora",["mcp","serve"]);return{args:r,command:t,transport:"stdio"}},Ee=e=>({transport:"http",url:e}),Oe=e=>({home:e.home,platform:e.platform,projectRoot:e.cwd}),U=(e,r,t)=>be(e,Oe(t),t.scope??r.preferredScope,t.scope!==void 0||!r.allowScopeFallback),Ce=(e,r,t)=>{const n=U(e,r,t);if(n===void 0){t.logger.warn(`${e.label}: has no ${t.scope??r.preferredScope}-scoped config — skipped "${r.name}".`);return}const{path:a}=n,o=e.buildEntry(r.spec);if(t.print===!0){const i=d(a,t.cwd);return t.force!==!0&&ge({key:e.key,name:r.name,path:a})?(t.logger.info(`${e.label}: "${r.name}" already configured in ${i} — a real install would skip it (re-run with --force to replace).`),{action:"printed",path:a}):(t.logger.info(`${e.label} → ${i}
3
+ ${JSON.stringify({[e.key]:{[r.name]:o}},void 0,4)}`),{action:"printed",path:a})}const l=pe({entry:o,force:t.force===!0,key:e.key,name:r.name,path:a}),c=d(a,t.cwd);return l.action==="invalid"?t.logger.error(`${e.label}: ${c} is not valid JSON (${l.error??"unknown error"}) — left untouched.`):l.action==="skipped"?t.logger.info(`${e.label}: "${r.name}" already configured in ${c} — re-run with --force to replace it.`):t.logger.success(`${e.label}: ${l.action==="created"?"created":"updated"} ${c} with "${r.name}".`),{action:l.action,path:a}},xe=(e,r,t)=>{const n=U(e,r,t)?.path;if(n===void 0){t.logger.warn(`${e.label}: no known config location on ${t.platform} — skipped.`);return}return t.logger.info(`${e.label}: add this to ${d(n,t.cwd)}
4
4
 
5
- ${o.renderSnippet(t.name,t.spec)}`),{action:"printed",path:r}},Ro=o=>{const t=[];return o.localOnly!==!0&&t.push({allowScopeFallback:!0,name:U,preferredScope:"global",spec:Oo(o.docsUrl??jo)}),o.docsOnly!==!0&&ko(o.cwd)&&t.push({allowScopeFallback:!1,name:N,preferredScope:"project",spec:So(V(o.cwd))}),t},Uo=o=>{const t=o.home??$(),e=o.platform??process.platform;o.logger.info("Supported MCP clients:");for(const r of g){const a=r.paths({home:t,platform:e,projectRoot:o.cwd}),n=i=>{const l=a[i];return l===void 0?"—":d(l,o.cwd)};o.logger.info(` ${r.id.padEnd(15)} ${r.label.padEnd(24)} project: ${n("project").padEnd(30)} global: ${n("global")}`)}return{code:0,written:[]}},No=o=>o.docsOnly===!0&&o.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).",_o=(o,t,e)=>{const r=[];for(const a of o)for(const n of t){const i=a.format==="json"?Co(a,n,e):Eo(a,n,e);i!==void 0&&r.push({action:i.action,client:a.id,path:i.path,server:n.name})}return r},Mo=o=>{const t=o.home??$(),e=o.platform??process.platform,r=R(o.clients,()=>bo({home:t,platform:e,projectRoot:o.cwd}),o.logger,"install");if(r===void 0)return{code:1,written:[]};if(r.length===0)return o.logger.error(`mcp install: no MCP client config found — name one explicitly, e.g. \`lunora mcp install claude-code\`. Known clients: ${O.join(", ")}.`),{code:1,written:[]};o.clients.length===0&&o.logger.info(`Detected ${String(r.length)} configured client(s): ${r.map(i=>i.label).join(", ")}.`);const a=Ro(o);if(a.length===0)return o.logger.error(`mcp install: nothing to install — ${No(o)}`),{code:1,written:[]};const n=_o(r,a,{...o,home:t,platform:e});return n.some(i=>i.action==="created"||i.action==="updated")&&o.logger.info("Restart your editor (or reload its MCP servers) to pick up the change."),{code:n.some(i=>i.action==="invalid")?1:0,written:n}},M=100,A=1e3,Ao=o=>({content:[{text:JSON.stringify(o,void 0,2),type:"text"}]}),Fo=o=>({content:[{text:o,type:"text"}]}),Lo=o=>{const t=typeof o=="string"?Number(o):o;return typeof t!="number"||!Number.isFinite(t)?M:Math.min(A,Math.max(1,Math.floor(t)))},Jo=(o,t)=>{const e=h(o,"utf8").split(`
6
- `);return e.at(-1)===""&&e.pop(),e.slice(-t).join(`
7
- `)},Po=o=>[{definition:{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=y(o);return Ao(t===void 0?{hint:"Start it with `lunora dev` in the project directory.",running:!1}:{background:t.background===!0,logFile:t.logFile,mode:t.mode,pid:t.pid,running:!0,startedAt:t.startedAt,studioUrl:t.studioUrl,url:t.url})}},{definition:{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(M)}, max ${String(A)})`,type:"number"}},type:"object"},name:"lunora_dev_logs"},handle:async t=>{const e=y(o);if(e===void 0)return{content:[{text:"no dev server is running — start one with `lunora dev`",type:"text"}],isError:!0};if(e.logFile===void 0||!p(e.logFile))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 r=Lo(t.lines),a=Jo(e.logFile,r);return Fo(a.length===0?"(the dev server log is empty)":a)}}],Wo=new Set(["127.0.0.1","::1","localhost"]),F=o=>{try{const{hostname:t}=new URL(o);return Wo.has(t.startsWith("[")?t.slice(1,-1):t)}catch{return!1}},k=o=>{const t=o.url??y(o.cwd)?.url;if(t===void 0||t.length===0)return;if(o.token!==void 0&&o.token.length>0)return{token:o.token,url:t};if(o.url!==void 0&&!F(o.url))return{url:t};const e=oo(o.cwd);return e===void 0||e.length===0?{url:t}:{token:e,url:t}},Do=async o=>{await new Promise(t=>{const e=()=>{t()};o.onclose=e,process.stdin.once("close",e),process.stdin.once("end",e)})},To=(o,t)=>{if(o===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(o.token!==void 0)return`lunora mcp serve: ready — deployment at ${o.url}
8
- `;const e=t.url!==void 0&&!F(t.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 ${o.url} (${e})
9
- `},zo=async(o,t=to)=>{const e=o.writeError??(n=>{process.stderr.write(n)});let r;try{r=await t({allowWrites:o.allowWrites===!0,deployment:()=>k(o),docs:o.noDocs===!0?!1:{...o.docsUrl===void 0?{}:{baseUrl:o.docsUrl}},extraTools:Po(o.cwd),version:o.version})}catch(n){const i=n instanceof Error?n.message:String(n);return e(`lunora mcp serve: failed to start — ${i}
10
- `),{code:1,deployment:void 0}}const a=k(o);return e(To(a,o)),await Do(r),{code:0,deployment:a}},Ho=o=>{const t=[];return o.localOnly!==!0&&t.push(U),o.docsOnly!==!0&&t.push(N),t},Io=(o,t,e,r)=>{const a=ho({key:o.key,name:t,path:e}),n=d(e,r.cwd);return a.action==="removed"?r.logger.success(`${o.label}: removed "${t}" from ${n}.`):a.action==="invalid"&&r.logger.error(`${o.label}: ${n} is not valid JSON (${a.error??"unknown error"}) — left untouched.`),{action:a.action,path:e}},Ko=(o,t,e,r)=>{const a=C({key:o.key,name:t,path:e}),n=d(e,r.cwd);return a==="invalid"?(r.logger.error(`${o.label}: ${n} is not valid JSON — a real run would report it and exit non-zero.`),{action:"invalid",path:e}):a==="absent"?{action:"absent",path:e}:(r.logger.info(`${o.label}: would remove "${t}" from ${n}.`),{action:"removed",path:e})},qo=(o,t,e)=>o.flatMap(r=>yo(r,t)).filter(wo).filter(r=>e===void 0||r.scope===e),Go=o=>{const t=o.home??$(),e=o.platform??process.platform,r=R(o.clients,()=>g,o.logger,"uninstall");if(r===void 0)return{code:1,removed:[]};const a=Ho(o);if(a.length===0)return o.logger.error("mcp uninstall: nothing to remove — `--docs-only` and `--local-only` are mutually exclusive, pass at most one."),{code:1,removed:[]};const n=[],i={home:t,platform:e,projectRoot:o.cwd};for(const l of qo(r,i,o.scope))for(const c of a){const m=o.print===!0?Ko(l.client,c,l.path,o):Io(l.client,c,l.path,o);m.action!=="absent"&&n.push({...m,client:l.client.id,server:c})}return n.length===0?o.logger.info("Nothing to remove — no Lunora MCP servers were configured in the clients checked."):o.print===!0&&o.logger.info("Nothing was changed — re-run without --print to remove these."),{code:n.some(l=>l.action==="invalid")?1:0,removed:n}},S=o=>o.global===!0?"global":o.project===!0?"project":void 0,Vo=async(o,t)=>{const{code:e}=await zo({allowWrites:t.allowWrites===!0,cwd:o,noDocs:t.docs===!1,version:L,...t.docsUrl===void 0?{}:{docsUrl:t.docsUrl},...t.token===void 0?{}:{token:t.token},...t.url===void 0?{}:{url:t.url}});return{code:e}},lt=J(async({argument:o,cwd:t,logger:e,options:r})=>{const[a,...n]=o;if(a==="serve")return Vo(t,r);if(a==="uninstall"){const i=S(r),{code:l}=Go({clients:n,cwd:t,docsOnly:r.docsOnly===!0,localOnly:r.localOnly===!0,logger:e,print:r.print===!0,...i===void 0?{}:{scope:i}});return{code:l}}if(a==="install"){if(r.list===!0)return Uo({cwd:t,logger:e});const i=S(r),{code:l}=Mo({clients:n,cwd:t,docsOnly:r.docsOnly===!0,force:r.force===!0,localOnly:r.localOnly===!0,logger:e,print:r.print===!0,...i===void 0?{}:{scope:i},...r.docsUrl===void 0?{}:{docsUrl:r.docsUrl}});return{code:l}}return e.error("mcp: unknown subcommand. Usage: lunora mcp <install|uninstall|serve>"),{code:1}});export{lt as execute};
5
+ ${e.renderSnippet(r.name,r.spec)}`),{action:"printed",path:n}},Me=e=>{const r=[];return e.localOnly!==!0&&r.push({allowScopeFallback:!0,name:L,preferredScope:"global",spec:Ee(e.docsUrl??ke)}),e.docsOnly!==!0&&je(e.cwd)&&r.push({allowScopeFallback:!1,name:N,preferredScope:"project",spec:$e(B(e.cwd))}),r},_e=e=>{const r=e.home??b(),t=e.platform??process.platform;e.logger.info("Supported MCP clients:");for(const n of p){const a=n.paths({home:r,platform:t,projectRoot:e.cwd}),o=l=>{const c=a[l];return c===void 0?"—":d(c,e.cwd)};e.logger.info(` ${n.id.padEnd(15)} ${n.label.padEnd(24)} project: ${o("project").padEnd(30)} global: ${o("global")}`)}return{code:0,written:[]}},Le=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).",Ne=(e,r,t)=>{const n=[];for(const a of e)for(const o of r){const l=a.format==="json"?Ce(a,o,t):xe(a,o,t);l!==void 0&&n.push({action:l.action,client:a.id,path:l.path,server:o.name})}return n},Ue=e=>{const r=e.home??b(),t=e.platform??process.platform,n=_(e.clients,()=>we({home:r,platform:t,projectRoot:e.cwd}),e.logger,"install");if(n===void 0)return{code:1,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: ${O.join(", ")}.`),{code:1,written:[]};e.clients.length===0&&e.logger.info(`Detected ${String(n.length)} configured client(s): ${n.map(l=>l.label).join(", ")}.`);const a=Me(e);if(a.length===0)return e.logger.error(`mcp install: nothing to install — ${Le(e)}`),{code:1,written:[]};const o=Ne(n,a,{...e,home:r,platform:t});return o.some(l=>l.action==="created"||l.action==="updated")&&e.logger.info("Restart your editor (or reload its MCP servers) to pick up the change."),{code:o.some(l=>l.action==="invalid")?1:0,written:o}},A=100,F=1e3,j=e=>({content:[{text:JSON.stringify(e,void 0,2),type:"text"}]}),Ae=e=>({content:[{text:e,type:"text"}]}),Fe=e=>{const r=typeof e=="string"?Number(e):e;return typeof r!="number"||!Number.isFinite(r)?A:Math.min(F,Math.max(1,Math.floor(r)))},Pe=(e,r)=>{const t=v(e,"utf8").split(`
6
+ `);return t.at(-1)===""&&t.pop(),t.slice(-r).join(`
7
+ `)},Re=e=>[{definition:{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 r=y(e);return j(r===void 0?{hint:"Start it with `lunora dev` in the project directory.",running:!1}:{background:r.background===!0,logFile:r.logFile,mode:r.mode,pid:r.pid,running:!0,startedAt:r.startedAt,studioUrl:r.studioUrl,url:r.url})}},{definition:{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(A)}, max ${String(F)})`,type:"number"}},type:"object"},name:"lunora_dev_logs"},handle:async r=>{const t=y(e);if(t===void 0)return{content:[{text:"no dev server is running — start one with `lunora dev`",type:"text"}],isError:!0};if(t.logFile===void 0||!u(t.logFile))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 n=Fe(r.lines),a=Pe(t.logFile,n);return Ae(a.length===0?"(the dev server log is empty)":a)}}],Te=new Set(["127.0.0.1","::1","localhost"]),P=e=>{try{const{hostname:r}=new URL(e);return Te.has(r.startsWith("[")?r.slice(1,-1):r)}catch{return!1}},$=e=>{const r=e.url??y(e.cwd)?.url;if(r===void 0||r.length===0)return;if(e.token!==void 0&&e.token.length>0)return{token:e.token,url:r};if(e.url!==void 0&&!P(e.url))return{url:r};const t=re(e.cwd);return t===void 0||t.length===0?{url:r}:{token:t,url:r}},De=async e=>{await new Promise(r=>{const t=()=>{r()};e.onclose=t,process.stdin.once("close",t),process.stdin.once("end",t)})},Ie=(e,r)=>{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}
8
+ `;const n=r.url!==void 0&&!P(r.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} (${n})
9
+ `},Je=async(e,r=te)=>{const t=e.writeError??(o=>{process.stderr.write(o)});let n;try{n=await r({allowWrites:e.allowWrites===!0,deployment:()=>$(e),docs:e.noDocs===!0?!1:{...e.docsUrl===void 0?{}:{baseUrl:e.docsUrl}},extraTools:Re(e.cwd),version:e.version})}catch(o){const l=o instanceof Error?o.message:String(o);return t(`lunora mcp serve: failed to start — ${l}
10
+ `),{code:1,deployment:void 0}}const a=$(e);return t(Ie(a,e)),await De(n),{code:0,deployment:a}},We=e=>{const r=[];return e.localOnly!==!0&&r.push(L),e.docsOnly!==!0&&r.push(N),r},ze=(e,r,t,n)=>{const a=ve({key:e.key,name:r,path:t}),o=d(t,n.cwd);return a.action==="removed"?n.logger.success(`${e.label}: removed "${r}" from ${o}.`):a.action==="invalid"&&n.logger.error(`${e.label}: ${o} is not valid JSON (${a.error??"unknown error"}) — left untouched.`),{action:a.action,path:t}},Ge=(e,r,t,n)=>{const a=x({key:e.key,name:r,path:t}),o=d(t,n.cwd);return a==="invalid"?(n.logger.error(`${e.label}: ${o} is not valid JSON — a real run would report it and exit non-zero.`),{action:"invalid",path:t}):a==="absent"?{action:"absent",path:t}:(n.logger.info(`${e.label}: would remove "${r}" from ${o}.`),{action:"removed",path:t})},He=(e,r,t)=>e.flatMap(n=>ye(n,r)).filter(Se).filter(n=>t===void 0||n.scope===t),Ve=e=>{const r=e.home??b(),t=e.platform??process.platform,n=_(e.clients,()=>p,e.logger,"uninstall");if(n===void 0)return{code:1,removed:[]};const a=We(e);if(a.length===0)return e.logger.error("mcp uninstall: nothing to remove — `--docs-only` and `--local-only` are mutually exclusive, pass at most one."),{code:1,removed:[]};const o=[],l={home:r,platform:t,projectRoot:e.cwd};for(const c of He(n,l,e.scope))for(const i of a){const m=e.print===!0?Ge(c.client,i,c.path,e):ze(c.client,i,c.path,e);m.action!=="absent"&&o.push({...m,client:c.client.id,server:i})}return o.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:o.some(c=>c.action==="invalid")?1:0,removed:o}},E=e=>e.global===!0?"global":e.project===!0?"project":void 0,Ke=async(e,r)=>{const{code:t}=await Je({allowWrites:r.allowWrites===!0,cwd:e,noDocs:r.docs===!1,version:R,...r.docsUrl===void 0?{}:{docsUrl:r.docsUrl},...r.token===void 0?{}:{token:r.token},...r.url===void 0?{}:{url:r.url}});return{code:t}},lr=T(async({argument:e,cwd:r,logger:t,options:n})=>{const[a,...o]=e;if(a==="serve")return Ke(r,n);if(a==="uninstall"){const l=E(n),{code:c}=Ve({clients:o,cwd:r,docsOnly:n.docsOnly===!0,localOnly:n.localOnly===!0,logger:t,print:n.print===!0,...l===void 0?{}:{scope:l}});return{code:c}}if(a==="install"){if(n.list===!0)return _e({cwd:r,logger:t});const l=E(n),{code:c}=Ue({clients:o,cwd:r,docsOnly:n.docsOnly===!0,force:n.force===!0,localOnly:n.localOnly===!0,logger:t,print:n.print===!0,...l===void 0?{}:{scope:l},...n.docsUrl===void 0?{}:{docsUrl:n.docsUrl}});return{code:c}}return t.error("mcp: unknown subcommand. Usage: lunora mcp <install|uninstall|serve>"),{code:1}});export{lr as execute};
@@ -1 +1 @@
1
- import{i as d}from"../packem_shared/command-0l-ZPhIX.mjs";import{M as g,l as m}from"../packem_shared/detect-package-manager-DXDstphE.mjs";import{r as p}from"../packem_shared/docker-CKvYE9YF.mjs";import{defaultSpawner as l}from"../packem_shared/createRecordingSpawner-SKs4R1fc.mjs";const i=new Set(["build","delete","images","info","list","push"]),h=new Set(["build","push"]),w=async r=>{const[a,...n]=r.argument;if(a===void 0||!i.has(a))return r.logger.error(`lunora containers requires a subcommand: ${[...i].toSorted((c,u)=>c.localeCompare(u)).join(" | ")}. Example: lunora containers build ./containers/app --tag app:v1 --push`),{code:1};if(h.has(a)&&!(r.dockerAvailable??p)())return r.logger.error(`containers ${a} needs a running Docker-compatible engine (it builds/pushes images locally). Start Docker or Colima and retry. Note: container images must target linux/amd64.`),{code:1};const o=["containers",a,...n];r.tag!==void 0&&o.push("--tag",r.tag),r.push===!0&&o.push("--push"),r.env!==void 0&&o.push("--env",r.env);const t=r.cwd??process.cwd(),s=g(m(t),"wrangler",o),e={args:s.args,command:s.command,cwd:t};return r.logger.info(`running ${e.command} ${e.args.join(" ")}`),{code:(await(r.spawner??l)(e)).code,descriptor:e}},C=d(async({argument:r,cwd:a,logger:n,options:o})=>({code:(await w({argument:r,cwd:a,env:o.env,logger:n,push:o.push===!0,tag:o.tag})).code}));export{C as execute,w as runContainersCommand};
1
+ import{d as i}from"../packem_shared/command-DwC11Cwe.mjs";import{e as l,d as m}from"../packem_shared/detect-package-manager-DSaAqRof.mjs";import{i as g}from"../packem_shared/docker-DpVxvYpL.mjs";import{defaultSpawner as p}from"../packem_shared/createRecordingSpawner-DJlNacZ6.mjs";const o=new Set(["build","delete","images","info","list","push"]),f=new Set(["build","push"]),h=async e=>{const[a,...s]=e.argument;if(a===void 0||!o.has(a))return e.logger.error(`lunora containers requires a subcommand: ${[...o].toSorted((u,d)=>u.localeCompare(d)).join(" | ")}. Example: lunora containers build ./containers/app --tag app:v1 --push`),{code:1};if(f.has(a)&&!(e.dockerAvailable??g)())return e.logger.error(`containers ${a} needs a running Docker-compatible engine (it builds/pushes images locally). Start Docker or Colima and retry. Note: container images must target linux/amd64.`),{code:1};const r=["containers",a,...s];e.tag!==void 0&&r.push("--tag",e.tag),e.push===!0&&r.push("--push"),e.env!==void 0&&r.push("--env",e.env);const t=e.cwd??process.cwd(),c=l(m(t),"wrangler",r),n={args:c.args,command:c.command,cwd:t};return e.logger.info(`running ${n.command} ${n.args.join(" ")}`),{code:(await(e.spawner??p)(n)).code,descriptor:n}},D=i(async({argument:e,cwd:a,logger:s,options:r})=>({code:(await h({argument:e,cwd:a,env:r.env,logger:s,push:r.push===!0,tag:r.tag})).code}));export{D as execute,h as runContainersCommand};
@@ -1 +1 @@
1
- import{i as d}from"../packem_shared/command-0l-ZPhIX.mjs";import{M as a,l as m}from"../packem_shared/detect-package-manager-DXDstphE.mjs";import{defaultSpawner as c}from"../packem_shared/createRecordingSpawner-SKs4R1fc.mjs";const i=(r,e)=>(e!==void 0&&r.push("--env",e),r),p=r=>{const e=i(["deployments","list"],r.env);return r.json&&e.push("--json"),e},u=r=>{switch(r.subcommand){case"inspect":return r.versionId===void 0?{error:"deployments inspect requires a version id. Usage: lunora deployments inspect <version-id>"}:{args:i(["versions","view",r.versionId],r.env)};case"list":return{args:p(r)};case"promote":{if(r.versionId===void 0)return{error:"deployments promote requires a version id. Usage: lunora deployments promote <version-id> --yes"};if(!r.yes)return{error:"deployments promote shifts 100% of live traffic. Re-run with --yes to confirm."};const e=i(["versions","deploy",`${r.versionId}@100%`,"--yes"],r.env);return r.message!==void 0&&e.push("--message",r.message),{args:e}}case"rollback":{if(!r.yes)return{error:"deployments rollback changes the live version. Re-run with --yes to confirm."};const e=i(["rollback"],r.env);return r.versionId!==void 0&&e.push(r.versionId),e.push("--yes"),r.message!==void 0&&e.push("--message",r.message),{args:e}}default:return{error:`deployments: unknown subcommand "${r.subcommand}"`}}},l=async r=>{const{args:e,error:s}=u(r);if(s!==void 0||e===void 0)return r.logger.error(s??"deployments: nothing to run"),{code:1,descriptor:void 0,error:s};const o=r.cwd??process.cwd(),n=a(m(o),"wrangler",e),t={args:n.args,command:n.command,cwd:o};return r.logger.info(`${t.command} ${t.args.join(" ")}`),{code:(await(r.spawner??c)(t)).code,descriptor:t}},v=r=>r==="list"||r==="inspect"||r==="rollback"||r==="promote",w=d(({argument:r,cwd:e,logger:s,options:o})=>{const n=r[0];return v(n)?l({cwd:e,env:o.env,json:o.json===!0,logger:s,message:o.message,subcommand:n,versionId:r[1],yes:o.yes===!0}):(s.error(`deployments: unknown subcommand "${n??""}" — expected list | inspect | rollback | promote`),{code:1})});export{w as execute,l as runDeploymentsCommand};
1
+ import{d}from"../packem_shared/command-DwC11Cwe.mjs";import{e as a,d as m}from"../packem_shared/detect-package-manager-DSaAqRof.mjs";import{defaultSpawner as i}from"../packem_shared/createRecordingSpawner-DJlNacZ6.mjs";const t=(e,r)=>(r!==void 0&&e.push("--env",r),e),u=e=>{const r=t(["deployments","list"],e.env);return e.json&&r.push("--json"),r},l=e=>{switch(e.subcommand){case"inspect":return e.versionId===void 0?{error:"deployments inspect requires a version id. Usage: lunora deployments inspect <version-id>"}:{args:t(["versions","view",e.versionId],e.env)};case"list":return{args:u(e)};case"promote":{if(e.versionId===void 0)return{error:"deployments promote requires a version id. Usage: lunora deployments promote <version-id> --yes"};if(!e.yes)return{error:"deployments promote shifts 100% of live traffic. Re-run with --yes to confirm."};const r=t(["versions","deploy",`${e.versionId}@100%`,"--yes"],e.env);return e.message!==void 0&&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}"`}}},v=async e=>{const{args:r,error:n}=l(e);if(n!==void 0||r===void 0)return e.logger.error(n??"deployments: nothing to run"),{code:1,descriptor:void 0,error:n};const s=e.cwd??process.cwd(),o=a(m(s),"wrangler",r),c={args:o.args,command:o.command,cwd:s};return e.logger.info(`${c.command} ${c.args.join(" ")}`),{code:(await(e.spawner??i)(c)).code,descriptor:c}},g=e=>e==="list"||e==="inspect"||e==="rollback"||e==="promote",h=d(({argument:e,cwd:r,logger:n,options:s})=>{const o=e[0];return g(o)?v({cwd:r,env:s.env,json:s.json===!0,logger:n,message:s.message,subcommand:o,versionId:e[1],yes:s.yes===!0}):(n.error(`deployments: unknown subcommand "${o??""}" — expected list | inspect | rollback | promote`),{code:1})});export{h as execute,v as runDeploymentsCommand};
@@ -1 +1 @@
1
- import{i as s}from"../packem_shared/command-0l-ZPhIX.mjs";import{f as c}from"../packem_shared/open-url-zbbAo_D7.mjs";const t="https://lunora.sh/docs",g=r=>{let o=0,n=r.length;for(;o<n&&r[o]==="/";)o+=1;for(;n>o&&r[n-1]==="/";)n-=1;return r.slice(o,n)},l=r=>{if(!r||r.length===0)return t;const o=g(r);return o.length===0?t:`${t}/${o}`},i=async r=>{const o=l(r.section);r.logger.info(`opening ${o}`);try{await c(o,{opener:r.opener})}catch(n){const e=n instanceof Error?n.message:String(n);return r.logger.error(`docs: failed to open URL: ${e}`),{code:1,url:o}}return{code:0,url:o}},f=s(({argument:r,logger:o})=>i({logger:o,section:r[0]}));export{f as execute,i as runDocsCommand};
1
+ import{d as s}from"../packem_shared/command-DwC11Cwe.mjs";import{o as c}from"../packem_shared/open-url-EnKy--w-.mjs";const n="https://lunora.sh/docs",l=r=>{let e=0,t=r.length;for(;e<t&&r[e]==="/";)e+=1;for(;t>e&&r[t-1]==="/";)t-=1;return r.slice(e,t)},i=r=>{if(!r||r.length===0)return n;const e=l(r);return e.length===0?n:`${n}/${e}`},a=async r=>{const e=i(r.section);r.logger.info(`opening ${e}`);try{await c(e,{opener:r.opener})}catch(t){const o=t instanceof Error?t.message:String(t);return r.logger.error(`docs: failed to open URL: ${o}`),{code:1,url:e}}return{code:0,url:e}},m=s(({argument:r,logger:e})=>a({logger:e,section:r[0]}));export{m as execute,a as runDocsCommand};