@lunora/cli 1.0.0-alpha.159 → 1.0.0-alpha.160

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.mjs CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import{f as s}from"./packem_shared/cli-DiEQDidI.mjs";try{const r=await s();process.exit(r)}catch(r){process.stderr.write(`${r instanceof Error?r.message:String(r)}
2
+ import{u as s}from"./packem_shared/cli-Cu92injU.mjs";try{const r=await s();process.exit(r)}catch(r){process.stderr.write(`${r instanceof Error?r.message:String(r)}
3
3
  `),process.exit(1)}
package/dist/index.d.mts CHANGED
@@ -1017,7 +1017,7 @@ interface LintToolOfferDeps {
1017
1017
  defaults?: ReadonlyArray<LintTool>;
1018
1018
  }) => Promise<LintTool[]>;
1019
1019
  }
1020
- type Template = "analog" | "astro" | "expo" | "next" | "nuxt" | "react-router" | "standalone" | "sveltekit" | "tanstack-start-react" | "tanstack-start-solid";
1020
+ type Template = "analog" | "astro" | "expo" | "next" | "nuxt" | "react-router" | "standalone" | "sveltekit" | "tanstack-start-react" | "tanstack-start-solid" | "vinext" | "vinext-pages";
1021
1021
  interface InitCommandOptions {
1022
1022
  /**
1023
1023
  * Add features non-interactively after scaffolding (the `--add` flag): a
package/dist/index.d.ts CHANGED
@@ -1017,7 +1017,7 @@ interface LintToolOfferDeps {
1017
1017
  defaults?: ReadonlyArray<LintTool>;
1018
1018
  }) => Promise<LintTool[]>;
1019
1019
  }
1020
- type Template = "analog" | "astro" | "expo" | "next" | "nuxt" | "react-router" | "standalone" | "sveltekit" | "tanstack-start-react" | "tanstack-start-solid";
1020
+ type Template = "analog" | "astro" | "expo" | "next" | "nuxt" | "react-router" | "standalone" | "sveltekit" | "tanstack-start-react" | "tanstack-start-solid" | "vinext" | "vinext-pages";
1021
1021
  interface InitCommandOptions {
1022
1022
  /**
1023
1023
  * Add features non-interactively after scaffolding (the `--add` flag): a
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{d as o,i as a,f as n}from"./packem_shared/cli-DiEQDidI.mjs";import{runCodegenCommand as t}from"./packem_chunks/runCodegenCommand.mjs";import{runDeployCommand as p}from"./packem_chunks/runDeployCommand.mjs";import{planDevCommand as x,runDevCommand as i}from"./packem_chunks/planDevCommand.mjs";import{runInitCommand as C}from"./packem_chunks/runInitCommand.mjs";import{runMigrateGenerateCommand as u}from"./packem_chunks/runMigrateGenerateCommand.mjs";import{runResetCommand as g}from"./packem_chunks/runResetCommand.mjs";import{runRpcCommand as E}from"./packem_chunks/runRpcCommand.mjs";import{insertSchemaExtension as D}from"./packem_shared/insertSchemaExtension-DZReBZ4_.mjs";import{createLogger as A,pail as c}from"./packem_shared/createLogger-BoSxdb2T.mjs";import{diffSnapshots as v,renderAddColumn as _,renderCreateIndex as h,renderCreateTable as y,renderDropIndex as F,renderDropTable as L,renderMigrationFile as O,validatorKindToSqlType as b}from"./packem_shared/diffSnapshots-cgOtkd-G.mjs";import{default as B}from"./packem_shared/schemaIrToSnapshot-DV2DilTz.mjs";import{createRecordingSpawner as U,defaultSpawner as W}from"./packem_shared/createRecordingSpawner-SKs4R1fc.mjs";import{default as N}from"./packem_shared/parseManifest-x3WsxKHz.mjs";import{R as V,S as j}from"./packem_shared/import-C9in1wC3.mjs";import{REQUIRED_COMPATIBILITY_DATE as H,REQUIRED_FLAG as K,validateWranglerProject as Y,validateWranglerConfig as Z}from"@lunora/config/cloudflare";import{buildRegistryIndex as z}from"./packem_shared/buildRegistryIndex-DwySASBu.mjs";import{I as X,F as $,E as rr}from"./packem_shared/commands-CG9qEtqR.mjs";import{runExportCommand as or}from"./packem_shared/runExportCommand-BpE4AbuX.mjs";export{o as COMMANDS,V as DEFAULT_IMPORT_BATCH_SIZE,H as REQUIRED_COMPATIBILITY_DATE,K as REQUIRED_FLAG,a as VERSION,z as buildRegistryIndex,A as createLogger,U as createRecordingSpawner,W as defaultSpawner,v as diffSnapshots,D as insertSchemaExtension,c as pail,N as parseManifest,x as planDevCommand,_ as renderAddColumn,h as renderCreateIndex,y as renderCreateTable,F as renderDropIndex,L as renderDropTable,O as renderMigrationFile,X as runAddCommand,$ as runBuildIndexCommand,n as runCli,t as runCodegenCommand,p as runDeployCommand,i as runDevCommand,or as runExportCommand,j as runImportCommand,C as runInitCommand,u as runMigrateGenerateCommand,rr as runRegistryViewCommand,g as runResetCommand,E as runRpcCommand,B as schemaIrToSnapshot,Y as validateWrangler,Z as validateWranglerConfig,b as validatorKindToSqlType};
1
+ import{p as o,i as a,u as n}from"./packem_shared/cli-Cu92injU.mjs";import{runCodegenCommand as t}from"./packem_chunks/runCodegenCommand.mjs";import{runDeployCommand as p}from"./packem_chunks/runDeployCommand.mjs";import{planDevCommand as x,runDevCommand as i}from"./packem_chunks/planDevCommand.mjs";import{runInitCommand as C}from"./packem_chunks/runInitCommand.mjs";import{runMigrateGenerateCommand as u}from"./packem_chunks/runMigrateGenerateCommand.mjs";import{runResetCommand as g}from"./packem_chunks/runResetCommand.mjs";import{runRpcCommand as E}from"./packem_chunks/runRpcCommand.mjs";import{insertSchemaExtension as D}from"./packem_shared/insertSchemaExtension-DZReBZ4_.mjs";import{createLogger as A,pail as c}from"./packem_shared/createLogger-BoSxdb2T.mjs";import{diffSnapshots as v,renderAddColumn as _,renderCreateIndex as h,renderCreateTable as y,renderDropIndex as F,renderDropTable as L,renderMigrationFile as O,validatorKindToSqlType as b}from"./packem_shared/diffSnapshots-cgOtkd-G.mjs";import{default as B}from"./packem_shared/schemaIrToSnapshot-DV2DilTz.mjs";import{createRecordingSpawner as U,defaultSpawner as W}from"./packem_shared/createRecordingSpawner-SKs4R1fc.mjs";import{default as N}from"./packem_shared/parseManifest-x3WsxKHz.mjs";import{R as V,S as j}from"./packem_shared/import-C9in1wC3.mjs";import{REQUIRED_COMPATIBILITY_DATE as H,REQUIRED_FLAG as K,validateWranglerProject as Y,validateWranglerConfig as Z}from"@lunora/config/cloudflare";import{buildRegistryIndex as z}from"./packem_shared/buildRegistryIndex-DwySASBu.mjs";import{I as X,F as $,E as rr}from"./packem_shared/commands-BJueH6Qo.mjs";import{runExportCommand as or}from"./packem_shared/runExportCommand-BpE4AbuX.mjs";export{o as COMMANDS,V as DEFAULT_IMPORT_BATCH_SIZE,H as REQUIRED_COMPATIBILITY_DATE,K as REQUIRED_FLAG,a as VERSION,z as buildRegistryIndex,A as createLogger,U as createRecordingSpawner,W as defaultSpawner,v as diffSnapshots,D as insertSchemaExtension,c as pail,N as parseManifest,x as planDevCommand,_ as renderAddColumn,h as renderCreateIndex,y as renderCreateTable,F as renderDropIndex,L as renderDropTable,O as renderMigrationFile,X as runAddCommand,$ as runBuildIndexCommand,n as runCli,t as runCodegenCommand,p as runDeployCommand,i as runDevCommand,or as runExportCommand,j as runImportCommand,C as runInitCommand,u as runMigrateGenerateCommand,rr as runRegistryViewCommand,g as runResetCommand,E as runRpcCommand,B as schemaIrToSnapshot,Y as validateWrangler,Z as validateWranglerConfig,b as validatorKindToSqlType};
@@ -1 +1 @@
1
- import{existsSync as b,readFileSync as k}from"node:fs";import{applyLintIgnores as $,detectLintTools as S}from"@lunora/config";import{findWranglerFile as T}from"@lunora/config/cloudflare";import{join as g,basename as h}from"@visulima/path";import{i as j}from"../packem_shared/command-0l-ZPhIX.mjs";import{d as L,r as U,l as x,i as R,o as m,u as B,a as f,b as D,c as F,e as p,f as M,n as N,g as c,h as W,j as q,s as u,k as A,m as C,p as I,q as O,t as J}from"../packem_shared/lint-ignore-report-CKDXv9MQ.mjs";import{i as K,t as P,d as Q,s as X}from"../packem_shared/output-format-Cv3aLqhP.mjs";import{v as w,B as Y}from"../packem_shared/tui-prompts-BU3irGxV.mjs";import{I as Z}from"../packem_shared/commands-CG9qEtqR.mjs";const z=r=>{const e=r.trim().toLowerCase();return C.find(a=>a.value===e||a.label.toLowerCase()===e||e==="auth0"&&a.value==="auth-auth0"||e==="clerk"&&a.value==="auth-clerk")?.value},v=r=>{try{const e=JSON.parse(k(g(r,"package.json"),"utf8"));return{...e.dependencies,...e.devDependencies}}catch{return{}}},E=async r=>{const e=r.cwd??process.cwd(),a=q(v(e));return a!==void 0?a:r.yes===!0?(r.logger.warn(`add: couldn't detect your framework — using "${u}". Pass a specific item (e.g. \`lunora add auth-ui-vue\`) to override.`),u):await(r.promptSelect??((o,t,d)=>w(o,t,d)))("Which framework is your app?",A,{default:u})??u},G=async r=>{if(r.provider!==void 0&&r.provider!==""){const a=z(r.provider);return a===void 0?(r.logger.warn(`add: unknown --provider "${r.provider}" — using "${c}" (email & password).`),c):a}if(r.yes===!0)return c;const e=r.promptSelect??((a,o,t)=>w(a,o,t));return W(e)},l=r=>r.promptText??((e,a)=>Y(e,a)),H=async r=>{const e=h(r.cwd??process.cwd());if(r.bucket!==void 0&&r.bucket!==""){const a=R(r.bucket);if(a!==void 0)return a;const o=m(e);return r.logger.warn(`add: "${r.bucket}" isn't a valid R2 bucket name (lowercase alphanumeric + hyphens, 3–63 chars) — using "${o}".`),o}return r.yes===!0?m(e):B(l(r),e)},V=async r=>{const e=a=>{r.logger.warn(`add: ${a}`)};if(r.mailTo!==void 0&&r.mailTo!=="")return f(r.mailTo,e);if(r.yes!==!0)return f(await l(r)(D,{placeholder:"you@yourdomain.com"}),e)},_=async r=>{const e=h(r.cwd??process.cwd());if(r.db!==void 0&&r.db!==""){const a=F(r.db);if(a!==void 0)return a;const o=p(e);return r.logger.warn(`add: "${r.db}" isn't a usable D1 database name — using "${o}".`),o}return r.yes===!0?p(e):M(l(r),e)},rr=async(r,e)=>r.kind==="auth"?[await G(e)]:r.kind==="auth-ui"?[await E(e)]:r.kind==="email"?[x]:[r.item],er=(r,e)=>{N($(r,S(r)),e)},ar=async r=>{const e=r.cwd??process.cwd(),a=r.feature===void 0?void 0:L(r.feature);if(a===void 0)return r.logger.error("add requires a feature or registry item. Usage: lunora add <auth|email|storage|crons|presence|…>"),{code:1,items:[]};if(!b(g(e,"lunora"))||T(e)===void 0)return r.logger.error("add: not a Lunora project here (need a lunora/ directory and a wrangler.jsonc). Run `lunora init` first."),{code:1,items:[]};if(a.kind==="auth-ui"&&U(v(e)))return r.logger.error("add: auth-ui has no React Native port — the screens render DOM elements and a stylesheet, which Metro has nothing to mount. Build the screens with React Native primitives against the same better-auth client (`@lunora/react-native/auth`); `lunora add auth` still installs the server half."),{code:1,items:[]};const o=await rr(a,r),t=[];if(o.includes("storage")){const s=await H(r);t.push(i=>I(i,s))}if(o.includes("mail")){const s=await V(r);s!==void 0&&t.push(i=>O(i,s))}if(o.some(s=>s==="auth"||s.startsWith("auth-"))){const s=await _(r);t.push(i=>J(i,s))}const d=t.length>0?s=>{let i=s;for(const y of t)i=y(i);return i}:void 0,n=await Z({allowUnsafeSource:r.allowUnsafeSource,cwd:e,from:r.from,logger:r.logger,names:[...o],ref:r.ref,source:r.source,transformManifest:d,yes:!0});return n.code===0&&er(e,r.logger),{code:n.code,items:o}},mr=j(async({argument:r,cwd:e,logger:a,options:o})=>{const t=K("add",o.format);if(t!==void 0)return a.error(t),{code:1};const d=X(o.format,a),n=await ar({allowUnsafeSource:o.allowUnsafeSource===!0,bucket:o.bucket,cwd:e,db:o.db,feature:r[0],from:o.from,logger:d,mailTo:o.mailTo,provider:o.provider,ref:o.ref,source:o.source,yes:o.yes===!0});return P(o.format)&&Q({code:n.code,items:n.items}),{code:n.code}});export{mr as execute,ar as runAddFeature};
1
+ import{existsSync as b,readFileSync as k}from"node:fs";import{applyLintIgnores as $,detectLintTools as S}from"@lunora/config";import{findWranglerFile as T}from"@lunora/config/cloudflare";import{join as g,basename as h}from"@visulima/path";import{i as j}from"../packem_shared/command-0l-ZPhIX.mjs";import{d as L,r as U,l as x,i as R,o as m,u as B,a as f,b as D,c as F,e as p,f as M,n as N,g as c,h as W,j as q,s as u,k as A,m as C,p as I,q as O,t as J}from"../packem_shared/lint-ignore-report-BR2og7ff.mjs";import{i as K,t as P,d as Q,s as X}from"../packem_shared/output-format-Cv3aLqhP.mjs";import{v as w,B as Y}from"../packem_shared/tui-prompts-BU3irGxV.mjs";import{I as Z}from"../packem_shared/commands-BJueH6Qo.mjs";const z=r=>{const e=r.trim().toLowerCase();return C.find(a=>a.value===e||a.label.toLowerCase()===e||e==="auth0"&&a.value==="auth-auth0"||e==="clerk"&&a.value==="auth-clerk")?.value},v=r=>{try{const e=JSON.parse(k(g(r,"package.json"),"utf8"));return{...e.dependencies,...e.devDependencies}}catch{return{}}},E=async r=>{const e=r.cwd??process.cwd(),a=q(v(e));return a!==void 0?a:r.yes===!0?(r.logger.warn(`add: couldn't detect your framework — using "${u}". Pass a specific item (e.g. \`lunora add auth-ui-vue\`) to override.`),u):await(r.promptSelect??((o,t,d)=>w(o,t,d)))("Which framework is your app?",A,{default:u})??u},G=async r=>{if(r.provider!==void 0&&r.provider!==""){const a=z(r.provider);return a===void 0?(r.logger.warn(`add: unknown --provider "${r.provider}" — using "${c}" (email & password).`),c):a}if(r.yes===!0)return c;const e=r.promptSelect??((a,o,t)=>w(a,o,t));return W(e)},l=r=>r.promptText??((e,a)=>Y(e,a)),H=async r=>{const e=h(r.cwd??process.cwd());if(r.bucket!==void 0&&r.bucket!==""){const a=R(r.bucket);if(a!==void 0)return a;const o=m(e);return r.logger.warn(`add: "${r.bucket}" isn't a valid R2 bucket name (lowercase alphanumeric + hyphens, 3–63 chars) — using "${o}".`),o}return r.yes===!0?m(e):B(l(r),e)},V=async r=>{const e=a=>{r.logger.warn(`add: ${a}`)};if(r.mailTo!==void 0&&r.mailTo!=="")return f(r.mailTo,e);if(r.yes!==!0)return f(await l(r)(D,{placeholder:"you@yourdomain.com"}),e)},_=async r=>{const e=h(r.cwd??process.cwd());if(r.db!==void 0&&r.db!==""){const a=F(r.db);if(a!==void 0)return a;const o=p(e);return r.logger.warn(`add: "${r.db}" isn't a usable D1 database name — using "${o}".`),o}return r.yes===!0?p(e):M(l(r),e)},rr=async(r,e)=>r.kind==="auth"?[await G(e)]:r.kind==="auth-ui"?[await E(e)]:r.kind==="email"?[x]:[r.item],er=(r,e)=>{N($(r,S(r)),e)},ar=async r=>{const e=r.cwd??process.cwd(),a=r.feature===void 0?void 0:L(r.feature);if(a===void 0)return r.logger.error("add requires a feature or registry item. Usage: lunora add <auth|email|storage|crons|presence|…>"),{code:1,items:[]};if(!b(g(e,"lunora"))||T(e)===void 0)return r.logger.error("add: not a Lunora project here (need a lunora/ directory and a wrangler.jsonc). Run `lunora init` first."),{code:1,items:[]};if(a.kind==="auth-ui"&&U(v(e)))return r.logger.error("add: auth-ui has no React Native port — the screens render DOM elements and a stylesheet, which Metro has nothing to mount. Build the screens with React Native primitives against the same better-auth client (`@lunora/react-native/auth`); `lunora add auth` still installs the server half."),{code:1,items:[]};const o=await rr(a,r),t=[];if(o.includes("storage")){const s=await H(r);t.push(i=>I(i,s))}if(o.includes("mail")){const s=await V(r);s!==void 0&&t.push(i=>O(i,s))}if(o.some(s=>s==="auth"||s.startsWith("auth-"))){const s=await _(r);t.push(i=>J(i,s))}const d=t.length>0?s=>{let i=s;for(const y of t)i=y(i);return i}:void 0,n=await Z({allowUnsafeSource:r.allowUnsafeSource,cwd:e,from:r.from,logger:r.logger,names:[...o],ref:r.ref,source:r.source,transformManifest:d,yes:!0});return n.code===0&&er(e,r.logger),{code:n.code,items:o}},mr=j(async({argument:r,cwd:e,logger:a,options:o})=>{const t=K("add",o.format);if(t!==void 0)return a.error(t),{code:1};const d=X(o.format,a),n=await ar({allowUnsafeSource:o.allowUnsafeSource===!0,bucket:o.bucket,cwd:e,db:o.db,feature:r[0],from:o.from,logger:d,mailTo:o.mailTo,provider:o.provider,ref:o.ref,source:o.source,yes:o.yes===!0});return P(o.format)&&Q({code:n.code,items:n.items}),{code:n.code}});export{mr as execute,ar as runAddFeature};
@@ -1 +1 @@
1
- import{i as n}from"../packem_shared/command-0l-ZPhIX.mjs";import{I as c,E as f,F as a}from"../packem_shared/commands-CG9qEtqR.mjs";const i=n(({argument:u,cwd:s,logger:o,options:e})=>{const r=u[0],t=u.slice(1);return r==="add"?c({allowUnsafeSource:e.allowUnsafeSource===!0,cwd:s,diff:e.diff===!0,dryRun:e.dryRun===!0,from:e.from,json:e.json===!0,logger:o,names:t,overwrite:e.overwrite===!0,ref:e.ref,source:e.source,yes:e.yes===!0}):r==="list"?c({cwd:s,from:e.from,json:e.json===!0,list:!0,logger:o,names:[],ref:e.ref,source:e.source}):r==="view"?f({allowUnsafeSource:e.allowUnsafeSource===!0,cwd:s,from:e.from,logger:o,names:t,ref:e.ref,source:e.source}):r==="build"?a({check:e.check===!0,from:e.from,logger:o,out:e.out}):(o.error("registry: unknown subcommand. Usage: lunora registry <add|list|view|build> [names…]"),{code:1})});export{i as execute};
1
+ import{i as n}from"../packem_shared/command-0l-ZPhIX.mjs";import{I as c,E as f,F as a}from"../packem_shared/commands-BJueH6Qo.mjs";const i=n(({argument:u,cwd:s,logger:o,options:e})=>{const r=u[0],t=u.slice(1);return r==="add"?c({allowUnsafeSource:e.allowUnsafeSource===!0,cwd:s,diff:e.diff===!0,dryRun:e.dryRun===!0,from:e.from,json:e.json===!0,logger:o,names:t,overwrite:e.overwrite===!0,ref:e.ref,source:e.source,yes:e.yes===!0}):r==="list"?c({cwd:s,from:e.from,json:e.json===!0,list:!0,logger:o,names:[],ref:e.ref,source:e.source}):r==="view"?f({allowUnsafeSource:e.allowUnsafeSource===!0,cwd:s,from:e.from,logger:o,names:t,ref:e.ref,source:e.source}):r==="build"?a({check:e.check===!0,from:e.from,logger:o,out:e.out}):(o.error("registry: unknown subcommand. Usage: lunora registry <add|list|view|build> [names…]"),{code:1})});export{i as execute};
@@ -1,4 +1,4 @@
1
- import{writeFileSync as h,existsSync as v,readFileSync as S}from"node:fs";import{isAbsolute as w,join as b}from"node:path";import{byCodepoint as y,scoreAdvisor as x,parseAdvisorMap as j,compareToBaseline as R}from"@lunora/advisor";import{runCodegen as k}from"@lunora/codegen";import{i as A}from"../packem_shared/command-0l-ZPhIX.mjs";import{i as D,d as M,s as F,t as N}from"../packem_shared/output-format-Cv3aLqhP.mjs";import{o as g}from"../packem_shared/cli-DiEQDidI.mjs";const l={clean:"·",exempt:"–",failing:"✗",warned:"!"},u=(r,e)=>r.length>=e?r:r+" ".repeat(e-r.length),C=r=>`${r.id} (${r.visibility} ${r.kind})`,m=r=>{let e=0;for(const o of r)e=Math.max(e,o.id.length);return e},p=(r,e)=>` ${u(String(r.score),3)} ${l[r.coverage]} ${u(r.id,e)} ${r.visibility} ${r.kind}`,E=r=>{if(!r.comparable)return[` baseline not comparable (${r.reason}) — regenerate it; this run cannot verify anything`];if(!r.regressed)return[` no regression against baseline (score ${r.scoreDelta>=0?"+":""}${String(r.scoreDelta)})`];const e=[` REGRESSED against baseline (score ${r.scoreDelta>=0?"+":""}${String(r.scoreDelta)})`];for(const o of r.dropped)e.push(` ${o.id}: ${String(o.before)} → ${String(o.after)}`);for(const o of r.newFailing)e.push(` ${o}: now failing`);for(const o of r.worsened)e.push(` ${o}: more findings than the baseline`);return r.projectRegressed&&e.push(" project: new schema/config rules fired"),e},J=(r,e)=>{const o=r.procedures.filter(i=>i.coverage!=="clean"&&i.coverage!=="exempt"),n=m(o),t=[`advisor health ${String(r.score)}/100 — ${r.grade}`,` ${String(r.summary.clean)} clean · ${String(r.summary.warned)} warned · ${String(r.summary.failing)} failing · ${String(r.summary.exempt)} exempt (${String(r.summary.procedures)} procedures, ${String(r.summary.rulesFired)} rules fired)`];return r.project.checks.length>0&&t.push("",` project ${String(r.project.score)}/100 — ${r.project.checks.map(i=>i.name).join(", ")}`),o.length>0&&t.push("",...o.map(i=>p(i,n)),""," run with --all for every procedure, or --entry <file#export> for one"),e!==void 0&&t.push("",...E(e)),t.join(`
1
+ import{writeFileSync as h,existsSync as v,readFileSync as S}from"node:fs";import{isAbsolute as w,join as b}from"node:path";import{byCodepoint as y,scoreAdvisor as x,parseAdvisorMap as j,compareToBaseline as R}from"@lunora/advisor";import{runCodegen as k}from"@lunora/codegen";import{i as A}from"../packem_shared/command-0l-ZPhIX.mjs";import{i as D,d as M,s as F,t as N}from"../packem_shared/output-format-Cv3aLqhP.mjs";import{o as g}from"../packem_shared/cli-Cu92injU.mjs";const l={clean:"·",exempt:"–",failing:"✗",warned:"!"},u=(r,e)=>r.length>=e?r:r+" ".repeat(e-r.length),C=r=>`${r.id} (${r.visibility} ${r.kind})`,m=r=>{let e=0;for(const o of r)e=Math.max(e,o.id.length);return e},p=(r,e)=>` ${u(String(r.score),3)} ${l[r.coverage]} ${u(r.id,e)} ${r.visibility} ${r.kind}`,E=r=>{if(!r.comparable)return[` baseline not comparable (${r.reason}) — regenerate it; this run cannot verify anything`];if(!r.regressed)return[` no regression against baseline (score ${r.scoreDelta>=0?"+":""}${String(r.scoreDelta)})`];const e=[` REGRESSED against baseline (score ${r.scoreDelta>=0?"+":""}${String(r.scoreDelta)})`];for(const o of r.dropped)e.push(` ${o.id}: ${String(o.before)} → ${String(o.after)}`);for(const o of r.newFailing)e.push(` ${o}: now failing`);for(const o of r.worsened)e.push(` ${o}: more findings than the baseline`);return r.projectRegressed&&e.push(" project: new schema/config rules fired"),e},J=(r,e)=>{const o=r.procedures.filter(i=>i.coverage!=="clean"&&i.coverage!=="exempt"),n=m(o),t=[`advisor health ${String(r.score)}/100 — ${r.grade}`,` ${String(r.summary.clean)} clean · ${String(r.summary.warned)} warned · ${String(r.summary.failing)} failing · ${String(r.summary.exempt)} exempt (${String(r.summary.procedures)} procedures, ${String(r.summary.rulesFired)} rules fired)`];return r.project.checks.length>0&&t.push("",` project ${String(r.project.score)}/100 — ${r.project.checks.map(i=>i.name).join(", ")}`),o.length>0&&t.push("",...o.map(i=>p(i,n)),""," run with --all for every procedure, or --entry <file#export> for one"),e!==void 0&&t.push("",...E(e)),t.join(`
2
2
  `)},O=r=>r.coverage==="exempt"?[` exempt: ${r.exemptReason===void 0||r.exemptReason===""?"no reason given":r.exemptReason}`]:r.checks.map(e=>{const o=e.occurrences>1?`, ×${String(e.occurrences)}`:"";return` ${e.name} (−${String(e.weight)}${o})`}),B=r=>{const e=new Map;for(const o of r){const n=e.get(o.file);n===void 0?e.set(o.file,[o]):n.push(o)}return[...e].toSorted(([o],[n])=>y(o,n))},P=r=>{const e=m(r.procedures),o=[`advisor health ${String(r.score)}/100 — ${r.grade}`,"",` legend: ${l.clean} clean ${l.warned} warned ${l.failing} failing ${l.exempt} exempt`];for(const[n,t]of B(r.procedures)){o.push("",` ${n}`);for(const i of t)o.push(p(i,e),...O(i))}return o.join(`
3
3
  `)},T=(r,e)=>{const o=r.procedures.find(t=>t.id===e);if(o===void 0){const t=r.procedures.slice(0,10).map(i=>` ${i.id}`);return[`no procedure ${e} in the map. Known ids:`,...t,r.procedures.length>10?" …":""].filter(Boolean).join(`
4
4
  `)}const n=[`${C(o)} — ${String(o.score)}/100, ${o.coverage}`,` weight in the global mean: ${String(o.weight)}`];if(o.checks.length===0)return n.push(""," no rule fired"),n.join(`
@@ -1,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 arrayrefusing 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{writeFileSync as T,existsSync as w,cpSync as C,statSync as N,readdirSync as F,mkdirSync as O,readFileSync as I}from"node:fs";import{join as f,sep as M,resolve as b,dirname as R}from"node:path";import{SDK_LANGUAGES as L,generateSdk as x,SDK_TARGETS as B,isTypedSchema as G}from"@lunora/codegen";import{LunoraError as u}from"@lunora/errors";import{i as K}from"../packem_shared/command-0l-ZPhIX.mjs";import{I as U,i as E,b as Q,R as V,a as J}from"../packem_shared/resolve-BZp6jitE.mjs";const S="gh:anolilab/lunora/sdks",v="lunora-transport.json",q=/_test\.|Tests?\./u,P=r=>r.startsWith("test_")||q.test(r),_=(r,a="")=>F(r).toSorted((e,t)=>e.localeCompare(t)).flatMap(e=>{const t=f(r,e),s=a.length>0?`${a}/${e}`:e;return N(t).isDirectory()?_(t,s):[s]}),k=(r,a,e,t)=>{const s=f(r,e);if(!w(s))throw new u("NOT_FOUND",`transport is missing ${e}`);const n=f(a,t);return C(s,n,{filter:o=>!P(o.slice(o.lastIndexOf(M)+1)),force:!0,recursive:!0}),N(n).isDirectory()?_(n).map(o=>`${t}/${o}`):[t]},A=(r,a)=>a.vendor.every(e=>w(f(r,e.from))),W=async(r,a)=>{const{language:e,logger:t,outputDirectory:s,registryOptions:n,target:o}=a,{cleanup:d,directory:g}=await V(e,{...n,ref:r},S);try{if(!A(g,o)){t.warn(`${S}/${e} does not exist at ${r}.`);return}return{files:o.vendor.flatMap(c=>k(g,s,c.from,c.to)).toSorted((c,l)=>c.localeCompare(l)),ref:r,source:`${S}/${e}`,versionMatched:r===U()}}finally{d()}},z=(r,a)=>{const{language:e,outputDirectory:t,target:s}=a,n=f(r,e);if(!w(n))throw new u("NOT_FOUND",`no transport at ${n} — --from must point at a directory of per-language transports (the repo's \`sdks/\`)`);if(!A(n,s)){const o=s.vendor.map(d=>d.from).join(", ");throw new u("NOT_FOUND",`${n} is not a ${e} transportexpected it to contain ${o}`)}return{files:s.vendor.flatMap(o=>k(n,t,o.from,o.to)).toSorted((o,d)=>o.localeCompare(d)),ref:"local",source:n,versionMatched:!1}},H=async r=>{const{allowUnsafeSource:a,from:e,language:t,logger:s,outputDirectory:n,ref:o,source:d,target:g}=r;if(e!==void 0)return z(e,{language:t,outputDirectory:n,target:g});const c={allowUnsafeSource:a,logger:s,names:[],source:d},l=async i=>W(await Q(i,s),{language:t,logger:s,outputDirectory:n,registryOptions:c,target:g});if(o!==void 0&&o.length>0){const i=await l(o);if(i===void 0)throw new u("NOT_FOUND",`--ref ${o} carries no ${t} transport — pick a ref that does, or pass --from <dir> to copy a local one`);return i}const p=U(),m=await l(p).catch(i=>{const y=i instanceof Error?i.message.split(`
2
+ `)[0]??i.message:String(i);s.warn(`could not fetch the transport at ${p} (${y}).`)});if(m!==void 0)return m;const h=await l(void 0);if(h===void 0)throw new u("NOT_FOUND",`no ${t} transport at ${p} or on the release branch. This language may not be released yet pass --from <dir> to copy one from a checkout, or --ref <tag> to name a ref that has it.`);return s.warn(`FALLBACK: the transport is NOT version-matched to this CLI (${E()}). Wanted ${p}, used ${h.ref}. The vendored wire protocol may not be the one this surface was generated against; ${v} records what was actually copied.`),h},X=(r,a,e)=>{const t={cliVersion:E(),files:e.files,language:a,note:e.versionMatched?"Vendored by `lunora sdk generate` at the ref matching the CLI that generated the surface beside it. Regenerate with a newer CLI to upgrade.":"Vendored by `lunora sdk generate` from a ref that is NOT this CLI's release tag, so the transport and the generated surface may be different protocol vintages.",ref:e.ref,source:e.source,versionMatched:e.versionMatched};T(f(r,v),`${JSON.stringify(t,void 0,4)}
3
+ `,"utf8")},Y=f("lunora","_generated","openrpc.json"),Z=r=>{if(!w(r))throw new u("NOT_FOUND",`no OpenRPC document at ${r} run \`lunora codegen --api-spec openrpc\` (or \`--api-spec both\`) first, or pass --spec`);let a;try{a=JSON.parse(I(r,"utf8"))}catch(e){throw new u("BAD_REQUEST",`${r} is not valid JSON: ${e instanceof Error?e.message:String(e)}`)}if(a===null||typeof a!="object"||!Array.isArray(a.methods))throw new u("BAD_REQUEST",`${r} is not an OpenRPC document (no \`methods\` array)`);return a},se=K(async({argument:r,cwd:a,logger:e,options:t})=>{const s=r[0]??"generate";if(s!=="generate")throw new u("BAD_REQUEST",`unknown subcommand "${s}" the only one is \`lunora sdk generate\``);const n=t.lang??"python",o=B[n];if(o===void 0)throw new u("BAD_REQUEST",`unsupported --lang "${n}" expected one of: ${L.join(" | ")}`);const d=J("sdk generate",{allowUnsafeSource:t.allowUnsafeSource,source:t.source});if(d!==void 0)throw new u("BAD_REQUEST",d);const g=b(a,t.spec??Y),c=b(a,t.out??f("sdk",n)),l=Z(g);l.methods.length===0&&e.warn(`${g} declares no methods writing an empty SDK.`);const{files:p,undeclared:m,unrepresentable:h}=await x(l,o);O(c,{recursive:!0});const i=await H({allowUnsafeSource:t.allowUnsafeSource,from:t.from,language:n,logger:e,outputDirectory:c,ref:t.ref,source:t.source,target:o});X(c,n,i);for(const[$,j]of Object.entries(p)){const D=f(c,$);O(R(D),{recursive:!0}),T(D,j,"utf8")}const y=l.methods.filter($=>!G($.result?.schema)).length;return e.success(`Generated ${n} SDK for ${String(l.methods.length)} function(s) ${c}`),e.info(`Vendored the ${n} transport (${String(i.files.length)} file(s)) from ${i.source} @ ${i.ref}${i.versionMatched?" version-matched to this CLI":""}; see ${v}.`),e.info(o.requires.length>0?`Install in the consuming project: ${o.requires.join(", ")}.`:"Nothing to install — the transport is vendored and needs only the standard library."),m.length>0&&e.warn(`${String(m.length)} schema(s) are not expressible as a named ${n} model, so those arguments or returns stay untyped: ${m.join(", ")}`),h.length>0&&e.warn(`${String(h.length)} function(s) take or return a \`v.bigint()\`/\`v.bytes()\`, which no generated model can carrytheir parameters stay untyped, so pass wire values directly: ${h.join(", ")}`),y>0&&e.warn(`${String(y)} of ${String(l.methods.length)} function(s) return an untyped result declare \`.output()\` on them for typed returns.`),{code:0}});export{se as execute};
@@ -1 +1,3 @@
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 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 arrayrefusing 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,99 +1 @@
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.
2
-
3
- Install it in your project:
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({
6
- ${s.join(`
7
- `)}
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(`
11
- `);return`/**
12
- * Generated by \`lunora introspect\` from an existing ${e.dialect==="postgres"?"Postgres":"MySQL"} database.
13
- *
14
- * This file is a STARTING POINT, not a build artifact — it is written once and is
15
- * yours to edit. Review it before shipping: column types are mapped
16
- * conservatively, and every table is \`.global({ backend: "hyperdrive" })\` because
17
- * its rows live in the external database. Re-running \`lunora introspect\` will not
18
- * overwrite it unless you pass \`--force\`.
19
- */
20
- import { defineSchema, defineTable, v } from "${n.serverImport}";
21
-
22
- export default defineSchema({
23
- ${s}
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
27
- * starting point you own and edit.
28
- *
29
- * Both procedures are RPC-only. Add \`.expose({ rest: true })\` once you've decided
30
- * this data should be public, and gate them with your auth/RLS middleware first —
31
- * \`introspect\` cannot know who is allowed to read this table.
32
- */
33
- import { defineListArgs, v } from "${t.serverImport}";
34
-
35
- import type { Doc } from "./_generated/dataModel";
36
- import { c } from "./_generated/server";
37
-
38
- const ${r}List = defineListArgs<Doc<${b(e.name)}>>()({
39
- // Only index-backed columns are published as filterable, so a caller cannot
40
- // reach a column you did not choose to expose. Note that \`contains\` and the
41
- // negative operators still scan — narrow this list, and review it, before
42
- // adding \`.expose({ rest: true })\`.
43
- filter: {
44
- ${c.join(`
45
- `)}
46
- },
47
- orderBy: [${m}],
48
- });
49
-
50
- export const list = c.query.input(${r}List.args).query(({ args, ctx }) => ${d}.findMany(${r}List.toQueryArgs(args)));
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=`
54
- SELECT c.table_name, c.column_name, c.is_nullable, c.data_type, c.udt_name
55
- FROM information_schema.columns c
56
- JOIN information_schema.tables t
57
- ON t.table_schema = c.table_schema AND t.table_name = c.table_name
58
- WHERE c.table_schema = $1 AND t.table_type = 'BASE TABLE'
59
- ORDER BY c.table_name, c.ordinal_position`,be=`
60
- SELECT tc.table_name, kcu.column_name
61
- FROM information_schema.table_constraints tc
62
- JOIN information_schema.key_column_usage kcu
63
- ON kcu.constraint_name = tc.constraint_name AND kcu.table_schema = tc.table_schema
64
- WHERE tc.table_schema = $1 AND tc.constraint_type = 'PRIMARY KEY'
65
- ORDER BY tc.table_name, kcu.ordinal_position`,fe=`
66
- SELECT tc.table_name, kcu.column_name, ccu.table_name AS foreign_table, ccu.column_name AS foreign_column
67
- FROM information_schema.table_constraints tc
68
- JOIN information_schema.key_column_usage kcu
69
- ON kcu.constraint_name = tc.constraint_name AND kcu.table_schema = tc.table_schema
70
- JOIN information_schema.constraint_column_usage ccu
71
- ON ccu.constraint_name = tc.constraint_name AND ccu.table_schema = tc.table_schema
72
- WHERE tc.table_schema = $1 AND tc.constraint_type = 'FOREIGN KEY'`,he=`
73
- SELECT t.relname AS table_name, i.relname AS index_name, ix.indisunique AS is_unique, a.attname AS column_name
74
- FROM pg_class t
75
- JOIN pg_index ix ON t.oid = ix.indrelid
76
- JOIN pg_class i ON i.oid = ix.indexrelid
77
- JOIN pg_namespace n ON n.oid = t.relnamespace
78
- CROSS JOIN LATERAL unnest(ix.indkey) WITH ORDINALITY AS k(attnum, ord)
79
- JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum
80
- WHERE n.nspname = $1 AND t.relkind = 'r' AND NOT ix.indisprimary
81
- ORDER BY t.relname, i.relname, k.ord`,ve=`
82
- SELECT c.TABLE_NAME, c.COLUMN_NAME, c.IS_NULLABLE, c.DATA_TYPE
83
- FROM information_schema.COLUMNS c
84
- JOIN information_schema.TABLES t
85
- ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME
86
- WHERE c.TABLE_SCHEMA = ? AND t.TABLE_TYPE = 'BASE TABLE'
87
- ORDER BY c.TABLE_NAME, c.ORDINAL_POSITION`,ye=`
88
- SELECT TABLE_NAME, COLUMN_NAME
89
- FROM information_schema.KEY_COLUMN_USAGE
90
- WHERE TABLE_SCHEMA = ? AND CONSTRAINT_NAME = 'PRIMARY'
91
- ORDER BY TABLE_NAME, ORDINAL_POSITION`,_e=`
92
- SELECT TABLE_NAME, COLUMN_NAME, REFERENCED_TABLE_NAME AS foreign_table, REFERENCED_COLUMN_NAME AS foreign_column
93
- FROM information_schema.KEY_COLUMN_USAGE
94
- WHERE TABLE_SCHEMA = ? AND REFERENCED_TABLE_NAME IS NOT NULL`,Ee=`
95
- SELECT TABLE_NAME, INDEX_NAME AS index_name, NON_UNIQUE, COLUMN_NAME
96
- FROM information_schema.STATISTICS
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};
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};