@lunora/cli 1.0.0-alpha.325 → 1.0.0-alpha.327
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 +1 -1
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.mjs +1 -1
- package/dist/packem_chunks/handler10.mjs +2 -1
- package/dist/packem_chunks/handler11.mjs +1 -2
- package/dist/packem_chunks/handler12.mjs +1 -1
- package/dist/packem_chunks/handler13.mjs +1 -1
- package/dist/packem_chunks/handler14.mjs +1 -1
- package/dist/packem_chunks/handler15.mjs +3 -1
- package/dist/packem_chunks/handler16.mjs +1 -3
- package/dist/packem_chunks/handler17.mjs +1 -1
- package/dist/packem_chunks/handler18.mjs +7 -1
- package/dist/packem_chunks/handler19.mjs +1 -7
- package/dist/packem_chunks/handler21.mjs +1 -3
- package/dist/packem_chunks/handler22.mjs +3 -3
- package/dist/packem_chunks/handler23.mjs +3 -1
- package/dist/packem_chunks/handler24.mjs +1 -2
- package/dist/packem_chunks/handler25.mjs +2 -99
- package/dist/packem_chunks/handler26.mjs +99 -10
- package/dist/packem_chunks/handler27.mjs +10 -0
- package/dist/packem_chunks/handler6.mjs +3 -1
- package/dist/packem_chunks/handler7.mjs +1 -3
- package/dist/packem_chunks/handler8.mjs +1 -1
- package/dist/packem_chunks/handler9.mjs +1 -1
- package/dist/packem_chunks/runDevCommand.mjs +3 -3
- package/dist/packem_chunks/runInitCommand.mjs +17 -17
- package/dist/packem_shared/{COMMANDS-diXlISPS.mjs → COMMANDS-CP6waB2N.mjs} +1 -1
- package/dist/packem_shared/cli-BzOfNDAr.mjs +2 -0
- package/dist/packem_shared/variables-acxcvVQa.mjs +1 -0
- package/package.json +9 -9
- package/skills/lunora-quickstart/SKILL.md +15 -13
- package/dist/packem_shared/cli-o9i8dzCS.mjs +0 -2
package/dist/bin.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{r as e}from"./packem_shared/cli-
|
|
2
|
+
import{r as e}from"./packem_shared/cli-BzOfNDAr.mjs";try{const r=await e();process.exit(r)}catch(r){process.stderr.write(`${r instanceof Error?r.message:String(r)}
|
|
3
3
|
`),process.exit(1)}
|
package/dist/index.d.mts
CHANGED
|
@@ -3,7 +3,7 @@ import { ensureDevVariables, ensureDevVarsExample, fillDevSecrets, LintTool, Lin
|
|
|
3
3
|
import { materializeRemoteWranglerConfig } from '@lunora/config/cloudflare';
|
|
4
4
|
export { REQUIRED_COMPATIBILITY_DATE, REQUIRED_FLAG, type WranglerProjectValidationOptions as WranglerValidationOptions, type WranglerValidationReport, type WranglerProjectValidationResult as WranglerValidationResult, validateWranglerProject as validateWrangler, validateWranglerConfig } from '@lunora/config/cloudflare';
|
|
5
5
|
/** Every command name the CLI registers (drives the `CommandName` type + tests). */
|
|
6
|
-
declare const COMMANDS: readonly ["init", "add", "dev", "codegen", "build", "deploy", "containers", "prepare", "link", "deployments", "logs", "run", "insights", "reset", "migrate", "export", "import", "seed", "backup", "eval", "verify", "info", "doctor", "env", "analyze", "view", "docs", "registry", "rules", "mcp"];
|
|
6
|
+
declare const COMMANDS: readonly ["init", "add", "dev", "codegen", "build", "deploy", "containers", "ai", "prepare", "link", "deployments", "logs", "run", "insights", "reset", "migrate", "export", "import", "seed", "backup", "eval", "verify", "info", "doctor", "env", "analyze", "view", "docs", "registry", "rules", "mcp"];
|
|
7
7
|
type CommandName = (typeof COMMANDS)[number];
|
|
8
8
|
declare const VERSION: string;
|
|
9
9
|
interface RunCliOptions {
|
|
@@ -1315,7 +1315,7 @@ interface LintToolOfferDeps {
|
|
|
1315
1315
|
defaults?: ReadonlyArray<LintTool>;
|
|
1316
1316
|
}) => Promise<LintTool[]>;
|
|
1317
1317
|
}
|
|
1318
|
-
type Template = "analog" | "astro" | "expo" | "next" | "nuxt" | "react-router" | "solid-v2" | "standalone" | "sveltekit" | "tanstack-start-react" | "tanstack-start-solid" | "vinext" | "vinext-pages";
|
|
1318
|
+
type Template = "analog" | "astro" | "expo" | "next" | "nuxt" | "react-router" | "rspack-react" | "solid-v2" | "standalone" | "sveltekit" | "tanstack-start-react" | "tanstack-start-react-rspack" | "tanstack-start-solid" | "vinext" | "vinext-pages";
|
|
1319
1319
|
interface InitCommandOptions {
|
|
1320
1320
|
/**
|
|
1321
1321
|
* Add features non-interactively after scaffolding (the `--add` flag): a
|
package/dist/index.d.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { ensureDevVariables, ensureDevVarsExample, fillDevSecrets, LintTool, Lin
|
|
|
3
3
|
import { materializeRemoteWranglerConfig } from '@lunora/config/cloudflare';
|
|
4
4
|
export { REQUIRED_COMPATIBILITY_DATE, REQUIRED_FLAG, type WranglerProjectValidationOptions as WranglerValidationOptions, type WranglerValidationReport, type WranglerProjectValidationResult as WranglerValidationResult, validateWranglerProject as validateWrangler, validateWranglerConfig } from '@lunora/config/cloudflare';
|
|
5
5
|
/** Every command name the CLI registers (drives the `CommandName` type + tests). */
|
|
6
|
-
declare const COMMANDS: readonly ["init", "add", "dev", "codegen", "build", "deploy", "containers", "prepare", "link", "deployments", "logs", "run", "insights", "reset", "migrate", "export", "import", "seed", "backup", "eval", "verify", "info", "doctor", "env", "analyze", "view", "docs", "registry", "rules", "mcp"];
|
|
6
|
+
declare const COMMANDS: readonly ["init", "add", "dev", "codegen", "build", "deploy", "containers", "ai", "prepare", "link", "deployments", "logs", "run", "insights", "reset", "migrate", "export", "import", "seed", "backup", "eval", "verify", "info", "doctor", "env", "analyze", "view", "docs", "registry", "rules", "mcp"];
|
|
7
7
|
type CommandName = (typeof COMMANDS)[number];
|
|
8
8
|
declare const VERSION: string;
|
|
9
9
|
interface RunCliOptions {
|
|
@@ -1315,7 +1315,7 @@ interface LintToolOfferDeps {
|
|
|
1315
1315
|
defaults?: ReadonlyArray<LintTool>;
|
|
1316
1316
|
}) => Promise<LintTool[]>;
|
|
1317
1317
|
}
|
|
1318
|
-
type Template = "analog" | "astro" | "expo" | "next" | "nuxt" | "react-router" | "solid-v2" | "standalone" | "sveltekit" | "tanstack-start-react" | "tanstack-start-solid" | "vinext" | "vinext-pages";
|
|
1318
|
+
type Template = "analog" | "astro" | "expo" | "next" | "nuxt" | "react-router" | "rspack-react" | "solid-v2" | "standalone" | "sveltekit" | "tanstack-start-react" | "tanstack-start-react-rspack" | "tanstack-start-solid" | "vinext" | "vinext-pages";
|
|
1319
1319
|
interface InitCommandOptions {
|
|
1320
1320
|
/**
|
|
1321
1321
|
* Add features non-interactively after scaffolding (the `--add` flag): a
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{C as o,V as a,r as n}from"./packem_shared/cli-
|
|
1
|
+
import{C as o,V as a,r as n}from"./packem_shared/cli-BzOfNDAr.mjs";import{runCodegenCommand as m}from"./packem_chunks/runCodegenCommand.mjs";import{runDeployCommand as p}from"./packem_chunks/runDeployCommand.mjs";import{runDevCommand as f}from"./packem_chunks/runDevCommand.mjs";import{p as i}from"./packem_shared/plan-B-KsxVne.mjs";import{runInitCommand as l}from"./packem_chunks/runInitCommand.mjs";import{runMigrateGenerateCommand as I}from"./packem_shared/runMigrateGenerateCommand-CDHswpMU.mjs";import{runResetCommand as g}from"./packem_chunks/runResetCommand.mjs";import{runRpcCommand as T}from"./packem_chunks/runRpcCommand.mjs";import{EXIT_CODE as S,exitCodeForCode as A,exitCodeForError as c,exitCodeForStatus as M}from"./packem_shared/EXIT_CODE-08cwt3MK.mjs";import{insertSchemaExtension as v}from"./packem_shared/insertSchemaExtension-DuiV6cba.mjs";import{createLogger as b,pail as O}from"./packem_shared/createLogger-Cl18I8AX.mjs";import{diffSnapshots as y,renderAddColumn as L,renderCreateIndex as w,renderCreateTable as B,renderDropIndex as P,renderDropTable as U,renderMigrationFile as V,validatorKindToSqlType as W}from"./packem_shared/diffSnapshots-WWwx-KvZ.mjs";import{default as N}from"./packem_shared/schemaIrToSnapshot-BjK-0IRo.mjs";import{createRecordingSpawner as j,defaultSpawner as q}from"./packem_shared/createRecordingSpawner-sS7LEN7x.mjs";import{default as K}from"./packem_shared/parseManifest-CwPTKdtS.mjs";import{D as Y,r as Z}from"./packem_shared/import-D7qdpSmJ.mjs";import{REQUIRED_COMPATIBILITY_DATE as z,REQUIRED_FLAG as J,validateWranglerProject as $,validateWranglerConfig as rr}from"@lunora/config/cloudflare";import{b as or}from"./packem_shared/catalog-CahzmDLV.mjs";import{r as nr,a as tr,b as mr}from"./packem_shared/commands-CNqednoX.mjs";import{runExportCommand as pr}from"./packem_shared/runExportCommand-DxsJHYZt.mjs";export{o as COMMANDS,Y as DEFAULT_IMPORT_BATCH_SIZE,S as EXIT_CODE,z as REQUIRED_COMPATIBILITY_DATE,J as REQUIRED_FLAG,a as VERSION,or as buildRegistryIndex,b as createLogger,j as createRecordingSpawner,q as defaultSpawner,y as diffSnapshots,A as exitCodeForCode,c as exitCodeForError,M as exitCodeForStatus,v as insertSchemaExtension,O as pail,K as parseManifest,i as planDevCommand,L as renderAddColumn,w as renderCreateIndex,B as renderCreateTable,P as renderDropIndex,U as renderDropTable,V as renderMigrationFile,nr as runAddCommand,tr as runBuildIndexCommand,n as runCli,m as runCodegenCommand,p as runDeployCommand,f as runDevCommand,pr as runExportCommand,Z as runImportCommand,l as runInitCommand,I as runMigrateGenerateCommand,mr as runRegistryViewCommand,g as runResetCommand,T as runRpcCommand,N as schemaIrToSnapshot,$ as validateWrangler,rr as validateWranglerConfig,W as validatorKindToSqlType};
|
|
@@ -1 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{r as v}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{r as y}from"../packem_shared/admin-url-BhF5ufg1.mjs";import{d as M}from"../packem_shared/command-B--jgXSc.mjs";import{EXIT_CODE as d,exitCodeForStatus as T}from"../packem_shared/EXIT_CODE-08cwt3MK.mjs";import{a as x}from"../packem_shared/resolve-target-C_ZloTvd.mjs";const I="__lunora_admin__:getFunctionStats",E=10,f=(r,o)=>({calls:r.calls,conflicts:r.conflicts??0,errors:r.errors,lastErrorMessage:r.lastErrorMessage,maxDurationMs:r.maxDurationMs,meanDurationMs:r.calls===0?0:r.totalDurationMs/r.calls,path:r.path,rate:o}),O=(r,o)=>{const t=r.filter(e=>(e.conflicts??0)>0).map(e=>f(e,e.calls===0?0:(e.conflicts??0)/e.calls)).toSorted((e,s)=>s.rate-e.rate||s.conflicts-e.conflicts).slice(0,o),n=r.filter(e=>e.errors>0).map(e=>f(e,e.calls===0?0:e.errors/e.calls)).toSorted((e,s)=>s.rate-e.rate||s.errors-e.errors).slice(0,o),a=r.map(e=>f(e,0)).toSorted((e,s)=>s.maxDurationMs-e.maxDurationMs).slice(0,o);return{errorHotspots:n,latencyOutliers:a,totalFunctions:r.length,writeContention:t}},p=r=>`${(r*100).toFixed(1)}%`,$=r=>r<1e3?`${Math.round(r).toString()}ms`:`${(r/1e3).toFixed(2)}s`,m=(r,o,t,n)=>[r,...o.length===0?[` ${t}`]:o.map(a=>` ${n(a)}`)],_=r=>{const o=t=>t.lastErrorMessage?` — ${t.lastErrorMessage}`:"";return[`Insights over ${r.totalFunctions.toString()} function${r.totalFunctions===1?"":"s"}`,"",...m("Write-conflict hot-spots (OCC contention — candidates for sharding):",r.writeContention,"none — no write conflicts observed",t=>`${t.path} ${t.conflicts.toString()}/${t.calls.toString()} calls (${p(t.rate)})`),"",...m("Error hot-spots:",r.errorHotspots,"none — no errors observed",t=>`${t.path} ${t.errors.toString()}/${t.calls.toString()} calls (${p(t.rate)})${o(t)}`),"",...m("Latency outliers (slowest single call):",r.latencyOutliers,"none — no functions have run",t=>`${t.path} max ${$(t.maxDurationMs)}, mean ${$(t.meanDurationMs)} over ${t.calls.toString()} calls`)].join(`
|
|
2
|
+
`)},i=(r,o,t)=>(r.error(o),{code:t,error:o}),k=r=>r===void 0||!Number.isFinite(r)||r<=0?E:Math.floor(r),A=async r=>{const{logger:o}=r;if(r.prod&&r.url===void 0)return i(o,"--prod requires an explicit --url (refusing to report from the implicit localhost worker)",d.USAGE);const t=y(r.url,o,r.cwd);if(t===void 0)return{code:d.USAGE,error:"could not resolve a usable worker URL"};const{token:n}=v({cwd:r.cwd??process.cwd(),token:r.token,url:t});if(!n)return i(o,"admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)",d.AUTH);const a=`${t}/_lunora/rpc`,e=globalThis.fetch;if(typeof e!="function")throw new TypeError("no fetch implementation available — pass fetchImpl or run on Node >= 18");const s={args:{},functionPath:I};r.shard!==void 0&&(s.shardKey=r.shard),o.info(`POST ${a} -> insights`);const l=await e(a,{body:JSON.stringify(s),headers:{authorization:`Bearer ${n}`,"content-type":"application/json"},method:"POST"}),c=await l.text();if(!l.ok)return i(o,`insights failed: HTTP ${String(l.status)}: ${c}`,T(l.status));let u;try{u=JSON.parse(c)}catch{return i(o,`insights failed: worker returned non-JSON: ${c}`,1)}const S=u.result??u,{functions:h}=S;if(!Array.isArray(h))return i(o,"insights failed: response carried no `functions` array",1);const g=O(h,k(r.limit));return r.format!=="json"&&o.info(_(g)),{code:0,report:g}},C=M(async({cwd:r,format:o,logger:t,options:n})=>{const a=n.limit===void 0?void 0:Number.parseInt(n.limit,10),e=await A({cwd:r,fetchImpl:void 0,format:o,limit:a,logger:t,prod:n.prod,shard:n.shard,token:n.token,url:x({cwd:r,prod:n.prod===!0,url:n.url})});return{code:e.code,data:e.report,error:e.error}});export{O as buildInsightsReport,C as execute,_ as formatInsightsReport,A as runInsightsCommand};
|
|
@@ -1,2 +1 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`)},i=(r,o,t)=>(r.error(o),{code:t,error:o}),k=r=>r===void 0||!Number.isFinite(r)||r<=0?E:Math.floor(r),A=async r=>{const{logger:o}=r;if(r.prod&&r.url===void 0)return i(o,"--prod requires an explicit --url (refusing to report from the implicit localhost worker)",d.USAGE);const t=y(r.url,o,r.cwd);if(t===void 0)return{code:d.USAGE,error:"could not resolve a usable worker URL"};const{token:n}=v({cwd:r.cwd??process.cwd(),token:r.token,url:t});if(!n)return i(o,"admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)",d.AUTH);const a=`${t}/_lunora/rpc`,e=globalThis.fetch;if(typeof e!="function")throw new TypeError("no fetch implementation available — pass fetchImpl or run on Node >= 18");const s={args:{},functionPath:I};r.shard!==void 0&&(s.shardKey=r.shard),o.info(`POST ${a} -> insights`);const l=await e(a,{body:JSON.stringify(s),headers:{authorization:`Bearer ${n}`,"content-type":"application/json"},method:"POST"}),c=await l.text();if(!l.ok)return i(o,`insights failed: HTTP ${String(l.status)}: ${c}`,T(l.status));let u;try{u=JSON.parse(c)}catch{return i(o,`insights failed: worker returned non-JSON: ${c}`,1)}const S=u.result??u,{functions:h}=S;if(!Array.isArray(h))return i(o,"insights failed: response carried no `functions` array",1);const g=O(h,k(r.limit));return r.format!=="json"&&o.info(_(g)),{code:0,report:g}},C=M(async({cwd:r,format:o,logger:t,options:n})=>{const a=n.limit===void 0?void 0:Number.parseInt(n.limit,10),e=await A({cwd:r,fetchImpl:void 0,format:o,limit:a,logger:t,prod:n.prod,shard:n.shard,token:n.token,url:x({cwd:r,prod:n.prod===!0,url:n.url})});return{code:e.code,data:e.report,error:e.error}});export{O as buildInsightsReport,C as execute,_ as formatInsightsReport,A as runInsightsCommand};
|
|
1
|
+
import{existsSync as u,rmSync as a}from"node:fs";import{join as i}from"node:path";import{writeLinkedProject as d,LINKED_PROJECT_FILE as o}from"@lunora/config";import{d as k}from"../packem_shared/command-B--jgXSc.mjs";import{EXIT_CODE as c}from"../packem_shared/EXIT_CODE-08cwt3MK.mjs";import{r as s}from"../packem_shared/wrangler-name-Dsk5K1f-.mjs";const v=r=>{try{const{protocol:n}=new URL(r);return n==="http:"||n==="https:"}catch{return!1}},f=(r,n)=>{const e=i(r,o);return u(e)?(a(e),n.success(`link: removed ${o}`),{code:0}):(n.warn(`link: no ${o} to remove`),{code:0})},w=r=>{const n=r.cwd??process.cwd(),{logger:e}=r;if(r.remove)return f(n,e);if(r.url===void 0||r.url==="")return e.error("link requires a deployed Worker URL. Usage: lunora link --url <https://your-worker>"),{code:c.USAGE};if(!v(r.url))return e.error(`link: invalid --url "${r.url}" — expected an http(s) URL`),{code:c.USAGE};const l=r.now??(()=>new Date().toISOString()),t={env:r.env,linkedAt:l(),workerName:r.name??s(n),workerUrl:r.url},m=d(n,t);return e.success(`link: ${t.workerName??"(unnamed worker)"} -> ${r.url}`),e.info(`link: wrote ${m}`),t.env!==void 0&&e.info(`link: environment "${t.env}"`),{code:0,link:t}},y=k(({cwd:r,logger:n,options:e})=>w({cwd:r,env:e.env,logger:n,name:e.name,remove:e.remove===!0,url:e.url}));export{y as execute,w as runLinkCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{p as i}from"../packem_shared/deploy-target-DCWwiuAe.mjs";import{d as c}from"../packem_shared/command-B--jgXSc.mjs";import{EXIT_CODE as t}from"../packem_shared/EXIT_CODE-08cwt3MK.mjs";import{runPreDeployPipeline as d}from"./runDeployCommand.mjs";const l=async r=>{const a=r.cwd??process.cwd(),e=await d({allowSchemaDrift:r.allowSchemaDrift,apiSpec:r.apiSpec,cwd:a,logger:r.logger,spawner:r.spawner,strictAdvisories:r.strictAdvisories,target:r.target,updateSchemaBaseline:r.updateSchemaBaseline},"prepare");return e.error!==void 0?{code:e.code??t.USAGE,error:e.error,...e.schemaDrift===void 0?{}:{schemaDrift:e.schemaDrift},validation:e.validation}:(e.reblessSchemaBaseline?.(),r.logger.success("project is ready to deploy"),{code:0,validation:e.validation})},S=c(({cwd:r,logger:a,options:e})=>l({allowSchemaDrift:e.allowSchemaDrift===!0,apiSpec:i(e.apiSpec),cwd:r,logger:a,strictAdvisories:e.strictAdvisories,target:e.target,updateSchemaBaseline:e.updateSchemaBaseline===!0}));export{S as execute,l as runPrepareCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{d as l}from"../packem_shared/command-B--jgXSc.mjs";import{EXIT_CODE as n}from"../packem_shared/EXIT_CODE-08cwt3MK.mjs";import{r as s,b as t,a as o}from"../packem_shared/commands-CNqednoX.mjs";const y=l(({argument:a,cwd:u,format:m,logger:e,options:r})=>{const f=a[0],c=a.slice(1);if(f==="add")return s({allowUnsafeSource:r.allowUnsafeSource===!0,cwd:u,diff:r.diff===!0,dryRun:r.dryRun===!0,format:m,from:r.from,logger:e,names:c,overwrite:r.overwrite===!0,ref:r.ref,source:r.source,yes:r.yes===!0});if(f==="list")return s({allowUnsafeSource:r.allowUnsafeSource===!0,cwd:u,format:m,from:r.from,list:!0,logger:e,names:[],ref:r.ref,source:r.source});if(f==="view")return t({allowUnsafeSource:r.allowUnsafeSource===!0,cwd:u,from:r.from,logger:e,names:c,ref:r.ref,source:r.source});if(f==="build")return o({check:r.check===!0,cwd:u,from:r.from,logger:e,names:[],out:r.out});const d="registry: unknown subcommand. Usage: lunora registry <add|list|view|build> [names…]";return e.error(d),{code:n.USAGE,error:d}});export{y as execute};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d as
|
|
1
|
+
import{existsSync as c,readFileSync as g,readdirSync as f,statSync as k,mkdirSync as w,writeFileSync as y}from"node:fs";import{fileURLToPath as R}from"node:url";import{AGENT_RULES_DIR as u,detectAgentRules as v,LUNORA_SKILL_NAMES as L}from"@lunora/config";import{join as i,relative as A,resolve as E,dirname as d}from"@visulima/path";import{d as I}from"../packem_shared/command-B--jgXSc.mjs";import{EXIT_CODE as $}from"../packem_shared/EXIT_CODE-08cwt3MK.mjs";const b=(e=d(R(import.meta.url)))=>{let r=e;for(let n=0;n<6;n+=1){const t=i(r,"package.json");if(c(t))try{if(JSON.parse(g(t,"utf8")).name==="@lunora/cli"){const o=i(r,"skills");return c(o)?o:void 0}}catch{}const s=d(r);if(s===r)break;r=s}},_=e=>f(e).filter(r=>{const n=i(e,r);return k(n).isDirectory()&&c(i(n,"SKILL.md"))}),m=(e,r,n)=>{w(r,{recursive:!0});let t=!1;for(const s of f(e)){const l=i(e,s),o=i(r,s);if(k(l).isDirectory()){t=m(l,o,n)||t;continue}c(o)&&!n||(y(o,g(l)),t=!0)}return t},j=["pnpm-workspace.yaml","pnpm-lock.yaml","yarn.lock","package-lock.json","bun.lock","bun.lockb",".git"],O=e=>{let r=e;for(;;){if(j.some(t=>c(i(r,t))))return r;const n=d(r);if(n===r)return e;r=n}},p=(e,r)=>r===void 0?O(e):E(e,r),x=e=>{const r=e.cwd??process.cwd(),n=p(r,e.dir),t=e.overwrite===!0,s=b();if(s===void 0)return e.logger.error("rules: could not locate the bundled skills (is @lunora/cli installed correctly?)."),{code:1,installed:[],skipped:[]};const l=[],o=[];for(const a of _(s)){const h=i(n,u,a);m(i(s,a),h,t)?l.push(a):o.push(a)}const S=A(r,i(n,u))||u;return l.length>0&&e.logger.success(`Installed ${String(l.length)} Lunora skill(s) into ${S}/: ${l.join(", ")}.`),o.length>0&&e.logger.info(`Skipped ${String(o.length)} existing skill(s) (re-run with --overwrite to replace): ${o.join(", ")}.`),e.logger.info("Your AI coding agent will pick these up automatically. Start with the `lunora` skill."),{code:0,installed:l,skipped:o}},D=e=>{const r=e.cwd??process.cwd(),n=p(r,e.dir),t=v(n);return t.installed?(e.logger.success(`Lunora agent rules are installed (${String(t.present.length)}/${String(L.length)} skills).`),t.missing.length>0&&e.logger.info(`Missing: ${t.missing.join(", ")}. Run \`lunora rules install\` to add them.`),{code:0,installed:t.present,skipped:[]}):(e.logger.warn("Lunora agent rules are not installed. Run `lunora rules install` so your AI agent knows how to use Lunora."),{code:e.strict===!0?1:0,installed:t.present,skipped:[]})},B=I(({argument:e,cwd:r,logger:n,options:t})=>{const s=e[0]??"check";return s==="install"?x({cwd:r,dir:t.dir,logger:n,overwrite:t.overwrite===!0}):s==="check"?D({cwd:r,dir:t.dir,logger:n,strict:t.strict===!0}):(n.error("rules: unknown subcommand. Usage: lunora rules <install|check>"),{code:$.USAGE})});export{B as execute,_ as listBundledSkills,b as resolveBundledSkillsDirectory,D as runRulesCheck,x as runRulesInstall};
|
|
@@ -1 +1,3 @@
|
|
|
1
|
-
import{existsSync as
|
|
1
|
+
import{existsSync as S}from"node:fs";import{mkdtemp as v,writeFile as k,rm as j}from"node:fs/promises";import{tmpdir as R}from"node:os";import{discoverSchema as C,schemaFromIr as T}from"@lunora/codegen";import{seedPlan as $}from"@lunora/seed";import{join as w}from"@visulima/path";import{Project as A}from"ts-morph";import{t as y}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{d as E}from"../packem_shared/command-B--jgXSc.mjs";import{EXIT_CODE as u}from"../packem_shared/EXIT_CODE-08cwt3MK.mjs";import{a as F}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{b as N}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{runResetCommand as U}from"./runResetCommand.mjs";import{r as I}from"../packem_shared/import-D7qdpSmJ.mjs";const O=(e,r)=>typeof r=="bigint"?Number(r):r instanceof ArrayBuffer?[...new Uint8Array(r)]:r,f=(e,r)=>({code:e,error:r,ndjson:""}),x=(e,r)=>{if(!S(r)){const o=`schema not found: ${r} — run \`vis generate lunora-table --name=<name>\` to create one`;return e.logger.error(o),f(u.NOT_FOUND,o)}if(e.reset===!0&&y({prod:e.prod,url:e.url})){const o="--reset only clears local .wrangler/state and cannot be combined with --prod or a remote --url";return e.logger.error(o),f(u.USAGE,o)}},z=async(e,r,o,t,n)=>{const s=await v(w(R(),"lunora-seed-")),d=w(s,"rows.ndjson");await k(d,e,"utf8");try{const a=await I({batchSize:n.batchSize,cwd:t,fetchImpl:n.fetchImpl,file:d,logger:n.logger,prod:n.prod,token:n.token,url:n.url,yes:!0}),i=a.body?.conflicts??0;return i>0&&n.logger.warn(`${String(i)} row(s) skipped — their _id already exists. Seeding is deterministic; re-run with --reset to wipe local state first, or a different --seed for fresh ids.`),{code:a.code,data:{conflicts:i,generated:r,inserted:a.inserted,tables:o},ndjson:e,...a.error===void 0?{}:{error:a.error}}}finally{await j(s,{force:!0,recursive:!0}).catch(()=>{})}},D=(e,r)=>{if(e.table===void 0||r.tables.some(n=>n.name===e.table))return;const o=r.tables.map(n=>n.name).join(", "),t=`unknown table "${e.table}" — schema defines: ${o||"(no tables)"}`;return e.logger.error(t),f(u.USAGE,t)},_=async(e,r)=>{if(!y({prod:e.prod,url:e.url})||e.yes===!0)return;if(!process.stdin.isTTY&&e.confirm===void 0){const s="seed: refusing to insert into a non-local target without confirmation — re-run with --yes";return e.logger.error(s),f(u.USAGE,s)}if(!await(e.confirm??N)(`This will insert ${String(r)} generated row(s) into ${e.url??"the production worker"}. Continue?`))return e.logger.info("seed: aborted"),f(u.CANCELLED,"seed: aborted at the confirmation prompt")},G=e=>{const r=[];for(const{rows:o,table:t}of e)for(const n of o)r.push(JSON.stringify({doc:n,table:t},O));return{lines:r,ndjson:r.length>0?`${r.join(`
|
|
2
|
+
`)}
|
|
3
|
+
`:""}},P=async e=>{const r=e.cwd??process.cwd(),o=e.format==="json",t=w(r,"lunora","schema.ts"),n=x(e,t);if(n!==void 0)return n;const s=new A({skipAddingFilesFromTsConfig:!0}),d=C(s,t),a=D(e,d);if(a!==void 0)return a;const i=T(d),l=$(i,{defaultCount:e.count??10,now:e.now,only:e.table===void 0?void 0:[e.table],seed:e.seed??0}),{lines:h,ndjson:c}=G(l),m=h.length;if(e.dryRun===!0)return!o&&c.length>0&&process.stdout.write(c),e.logger.info(`generated ${String(m)} row(s) across ${String(l.length)} table(s) — dry run, nothing inserted`),{code:0,data:{conflicts:0,generated:m,inserted:0,rows:o?h.map(g=>JSON.parse(g)):void 0,tables:l.length},ndjson:c};if(m===0)return e.logger.warn("no rows generated — nothing to insert"),{code:0,data:{conflicts:0,generated:0,inserted:0,tables:l.length},ndjson:c};if(e.reset===!0){const g=await U({confirm:e.confirm,cwd:r,logger:e.logger,yes:e.yes});if(g.code!==0)return{code:g.code,error:"seed: --reset could not clear local state",ndjson:c}}const b=await _(e,m);return b!==void 0?b:z(c,m,l.length,r,e)},ee=E(async({cwd:e,format:r,logger:o,options:t})=>{const n=await P({batchSize:t.batchSize,count:t.count,cwd:e,dryRun:t.dryRun===!0,format:r,logger:o,prod:t.prod===!0,reset:t.reset===!0,now:t.now,seed:t.seed,table:t.table,token:t.token,url:F({cwd:e,prod:t.prod===!0,url:t.url}),yes:t.yes===!0});return{code:n.code,data:n.data,error:n.error}});export{ee as execute,P as runSeedCommand};
|
|
@@ -1,3 +1 @@
|
|
|
1
|
-
import{existsSync as
|
|
2
|
-
`)}
|
|
3
|
-
`:""}},P=async e=>{const r=e.cwd??process.cwd(),o=e.format==="json",t=w(r,"lunora","schema.ts"),n=x(e,t);if(n!==void 0)return n;const s=new A({skipAddingFilesFromTsConfig:!0}),d=C(s,t),a=D(e,d);if(a!==void 0)return a;const i=T(d),l=$(i,{defaultCount:e.count??10,now:e.now,only:e.table===void 0?void 0:[e.table],seed:e.seed??0}),{lines:h,ndjson:c}=G(l),m=h.length;if(e.dryRun===!0)return!o&&c.length>0&&process.stdout.write(c),e.logger.info(`generated ${String(m)} row(s) across ${String(l.length)} table(s) — dry run, nothing inserted`),{code:0,data:{conflicts:0,generated:m,inserted:0,rows:o?h.map(g=>JSON.parse(g)):void 0,tables:l.length},ndjson:c};if(m===0)return e.logger.warn("no rows generated — nothing to insert"),{code:0,data:{conflicts:0,generated:0,inserted:0,tables:l.length},ndjson:c};if(e.reset===!0){const g=await U({confirm:e.confirm,cwd:r,logger:e.logger,yes:e.yes});if(g.code!==0)return{code:g.code,error:"seed: --reset could not clear local state",ndjson:c}}const b=await _(e,m);return b!==void 0?b:z(c,m,l.length,r,e)},ee=E(async({cwd:e,format:r,logger:o,options:t})=>{const n=await P({batchSize:t.batchSize,count:t.count,cwd:e,dryRun:t.dryRun===!0,format:r,logger:o,prod:t.prod===!0,reset:t.reset===!0,now:t.now,seed:t.seed,table:t.table,token:t.token,url:F({cwd:e,prod:t.prod===!0,url:t.url}),yes:t.yes===!0});return{code:n.code,data:n.data,error:n.error}});export{ee as execute,P as runSeedCommand};
|
|
1
|
+
import{existsSync as m}from"node:fs";import{join as p}from"node:path";import{runCodegen as u}from"@lunora/codegen";import{a as v,e as g,r as y}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as w,r as S}from"../packem_shared/deploy-target-DCWwiuAe.mjs";import{r as k}from"../packem_shared/codegen-error-AmH54ofi.mjs";import{d as j}from"../packem_shared/command-B--jgXSc.mjs";import{EXIT_CODE as E}from"../packem_shared/EXIT_CODE-08cwt3MK.mjs";import{r as A,p as D}from"../packem_shared/health-probe-Bw9JFfIy.mjs";import{defaultSpawner as R}from"../packem_shared/createRecordingSpawner-sS7LEN7x.mjs";import{validateWranglerProject as $}from"@lunora/config/cloudflare";import{execArgsFor as b,detectPackageManager as U}from"@lunora/config";const x=async(r,a,t)=>{if(!m(p(r,"tsconfig.json")))return{warning:"no tsconfig.json found — skipping TypeScript type-check"};const o=b(U(r),"tsc",["--noEmit","-p","tsconfig.json"]),e=await a({args:o.args,command:o.command,cwd:r,stdoutToStderr:t==="json"});return e.code===0?{}:{error:`type errors: tsc --noEmit exited ${String(e.code)}`}},P=async(r,a)=>{if(r.healthUrl===void 0||r.healthUrl==="")return;const t=await D({baseUrl:r.healthUrl,fetchImpl:r.healthFetch});if(t.error===void 0){a.success(`verify: health probe ok (${t.url})`);return}return t.error},T=(r,a)=>{const{errorAdvisories:t,names:o,shouldBlock:e}=g(r,y(a));if(e)return`${t.length.toString()} ERROR-level ${t.length===1?"advisory":"advisories"} (${o.join(", ")}). Pass --no-strict-advisories to downgrade this to a warning and continue.`},C=(r,a,t,o)=>{if(a.length===0&&t.length===0)return r.success("verify: project is valid"),{code:0,errors:[],warnings:[],wranglerPath:o};if(t.length>0){r.warn("verify: warnings:");for(const e of t)r.warn(` - ${e}`)}if(a.length>0){r.error("verify: errors:");for(const e of a){r.error(` - ${e}`);const n=k(e);n!==void 0&&r.error(n)}return{code:1,error:a[0],errors:a,warnings:t,wranglerPath:o}}return r.success("verify: project is valid (with warnings)"),{code:0,errors:[],warnings:t,wranglerPath:o}},H=async r=>{const a=r.cwd??process.cwd(),{logger:t}=r,o=$({environment:r.env,projectRoot:a}),e=[...o.report.errors],n=[...o.report.warnings];try{const s=S(a,r.target);if(s.target===void 0){const c=s.error??"unknown deploy target";return t.error(c),{code:E.USAGE,error:c,errors:[c],warnings:[],wranglerPath:void 0}}const i=u({apiSpec:r.apiSpec,dryRun:!0,projectRoot:a,target:s.target}),f=v(i.platformDiagnostics,t);e.push(...f.errors),n.push(...f.warnings);const l=T(i.advisories,r);l!==void 0&&e.push(l);const h=A({allowDrift:r.allowSchemaDrift===!0,codegen:i,command:"verify",logger:t,readOnly:!0});h.blocked&&e.push(h.reason)}catch(s){const i=s instanceof Error?s.message:String(s);e.push(`codegen failed: ${i}`)}if(r.typecheck!==!1){const s=await x(a,r.spawner??R,r.format??"pretty");s.error!==void 0&&e.push(s.error),s.warning!==void 0&&n.push(s.warning)}const d=await P(r,t);return d!==void 0&&e.push(d),C(t,e,n,o.wranglerPath)},J=j(async({cwd:r,format:a,logger:t,options:o})=>{const e=await H({allowSchemaDrift:o.allowSchemaDrift===!0,apiSpec:w(o.apiSpec),cwd:r,env:o.env,format:a,healthUrl:o.healthUrl,logger:t,strictAdvisories:o.strictAdvisories,target:o.target,typecheck:o.typecheck===!1?!1:void 0});return{code:e.code,data:{errors:e.errors,warnings:e.warnings,wranglerPath:e.wranglerPath},error:e.error}});export{J as execute,H as runVerifyCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{readLiveDevServerState as c}from"@lunora/config";import{d as i}from"../packem_shared/command-B--jgXSc.mjs";import{o as a}from"../packem_shared/open-url-EnKy--w-.mjs";const n="http://127.0.0.1:6173",d="/__lunora",u=/\/$/u,l=r=>{const e=c(r);return e===void 0?n:e.studioUrl!==void 0?e.studioUrl:e.mode==="vite"?`${e.url.replace(u,"")}${d}`:n},m=async r=>{const e=l(r.cwd??process.cwd()),{logger:t}=r;t.info(`opening ${e}`);try{await a(e,{opener:r.opener})}catch(o){const s=o instanceof Error?o.message:String(o);return t.error(`view: failed to open URL: ${s}`),{code:1,url:e}}return{code:0,url:e}},v=i(({cwd:r,logger:e})=>m({cwd:r,logger:e}));export{v as execute,m as runViewCommand};
|
|
@@ -1 +1,7 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{writeFileSync as h,existsSync as S,readFileSync as p}from"node:fs";import{isAbsolute as v,join as w}from"node:path";import{byCodepoint as b,scoreAdvisor as y,parseAdvisorMap as x,compareToBaseline as j}from"@lunora/advisor";import{runCodegen as A}from"@lunora/codegen";import{d as M}from"../packem_shared/command-B--jgXSc.mjs";import{EXIT_CODE as D}from"../packem_shared/EXIT_CODE-08cwt3MK.mjs";import{D as u}from"../packem_shared/cli-BzOfNDAr.mjs";const l={clean:"·",exempt:"–",failing:"✗",warned:"!"},d=(e,r)=>e.length>=r?e:e+" ".repeat(r-e.length),E=e=>`${e.id} (${e.visibility} ${e.kind})`,f=e=>{let r=0;for(const n of e)r=Math.max(r,n.id.length);return r},g=(e,r)=>` ${d(String(e.score),3)} ${l[e.coverage]} ${d(e.id,r)} ${e.visibility} ${e.kind}`,R=e=>{if(!e.comparable)return[` baseline not comparable (${e.reason}) — regenerate it; this run cannot verify anything`];if(!e.regressed)return[` no regression against baseline (score ${e.scoreDelta>=0?"+":""}${String(e.scoreDelta)})`];const r=[` REGRESSED against baseline (score ${e.scoreDelta>=0?"+":""}${String(e.scoreDelta)})`];for(const n of e.dropped)r.push(` ${n.id}: ${String(n.before)} → ${String(n.after)}`);for(const n of e.newFailing)r.push(` ${n}: now failing`);for(const n of e.worsened)r.push(` ${n}: more findings than the baseline`);return e.projectRegressed&&r.push(" project: new schema/config rules fired"),r},F=(e,r)=>{const n=e.procedures.filter(i=>i.coverage!=="clean"&&i.coverage!=="exempt"),t=f(n),o=[`advisor health ${String(e.score)}/100 — ${e.grade}`,` ${String(e.summary.clean)} clean · ${String(e.summary.warned)} warned · ${String(e.summary.failing)} failing · ${String(e.summary.exempt)} exempt (${String(e.summary.procedures)} procedures, ${String(e.summary.rulesFired)} rules fired)`];return e.project.checks.length>0&&o.push("",` project ${String(e.project.score)}/100 — ${e.project.checks.map(i=>i.name).join(", ")}`),n.length>0&&o.push("",...n.map(i=>g(i,t)),""," run with --all for every procedure, or --entry <file#export> for one"),r!==void 0&&o.push("",...R(r)),o.join(`
|
|
2
|
+
`)},k=e=>e.coverage==="exempt"?[` exempt: ${e.exemptReason===void 0||e.exemptReason===""?"no reason given":e.exemptReason}`]:e.checks.map(r=>{const n=r.occurrences>1?`, ×${String(r.occurrences)}`:"";return` ${r.name} (−${String(r.weight)}${n})`}),T=e=>{const r=new Map;for(const n of e){const t=r.get(n.file);t===void 0?r.set(n.file,[n]):t.push(n)}return[...r].toSorted(([n],[t])=>b(n,t))},B=e=>{const r=f(e.procedures),n=[`advisor health ${String(e.score)}/100 — ${e.grade}`,"",` legend: ${l.clean} clean ${l.warned} warned ${l.failing} failing ${l.exempt} exempt`];for(const[t,o]of T(e.procedures)){n.push("",` ${t}`);for(const i of o)n.push(g(i,r),...k(i))}return n.join(`
|
|
3
|
+
`)},C=(e,r)=>{const n=e.procedures.find(o=>o.id===r);if(n===void 0){const o=e.procedures.slice(0,10).map(i=>` ${i.id}`);return[`no procedure ${r} in the map. Known ids:`,...o,e.procedures.length>10?" …":""].filter(Boolean).join(`
|
|
4
|
+
`)}const t=[`${E(n)} — ${String(n.score)}/100, ${n.coverage}`,` weight in the global mean: ${String(n.weight)}`];if(n.checks.length===0)return t.push(""," no rule fired"),t.join(`
|
|
5
|
+
`);t.push(""," rules fired:");for(const o of n.checks)t.push(` [${o.level}] ${o.name} −${String(o.weight)}${o.occurrences>1?` (×${String(o.occurrences)})`:""}`);return t.join(`
|
|
6
|
+
`)},I=new Date(0).toISOString(),m=(e,r)=>v(r)?r:w(e,r),L=e=>{if(e===void 0)return{value:void 0};if(e===null||e==="")return{error:"--min-score needs a value between 0 and 100"};const r=Number(e);return Number.isFinite(r)&&r>=0&&r<=100?{value:r}:{error:"--min-score must be a number between 0 and 100"}},N=(e,r,n)=>{const t=m(r,n===null||n===""?u:n);if(!S(t))return{error:`baseline not found at ${t} — generate one with \`lunora advisor\` and commit it`};const o=x(JSON.parse(p(t,"utf8")));return o===void 0?{error:`baseline at ${t} is malformed — regenerate it with \`lunora advisor\``}:{comparison:j(e,o)}},P=e=>`baseline is not comparable (${e}) — regenerate it; this run verified nothing`,_=(e,r,n)=>r.entry!==void 0?C(e,r.entry):r.all===!0?B(e):F(e,n),G=e=>{const r=e.cwd??process.cwd(),n=e.format==="json",{logger:t}=e,o=L(e.minScore);if("error"in o)return e.logger.error(o.error),{code:D.USAGE,error:o.error};const{advisorContext:i,advisories:$}=A({dryRun:!0,projectRoot:r}),a=y(i?.procedureProtections??[],$,{generatedAt:e.generatedAt??I}),s={map:a};if(e.baseline!==void 0){const c=N(a,r,e.baseline);if("error"in c)return e.logger.error(c.error),{...s,error:c.error};s.comparison=c.comparison,c.comparison.comparable||e.logger.error(P(c.comparison.reason))}if(e.write!==!1){const c=m(r,e.out??u);h(c,`${JSON.stringify(a,void 0,4)}
|
|
7
|
+
`,"utf8"),s.written=c}return s.belowMinScore=o.value!==void 0&&a.score<o.value,s.belowMinScore&&t.error(`advisor score ${String(a.score)} is below the required ${String(o.value)}`),n||(t.info(_(a,e,s.comparison)),s.written!==void 0&&t.success(`wrote ${s.written}`)),s},H=e=>e.error!==void 0||e.belowMinScore===!0?!0:e.comparison!==void 0&&(!e.comparison.comparable||e.comparison.regressed),z=M(({cwd:e,format:r,logger:n,options:t})=>{const o=G({all:t.all,baseline:t.baseline,cwd:e,entry:t.entry,format:r,logger:n,minScore:t.minScore,out:t.out,write:t.write});return{code:o.code??(H(o)?1:0),data:{belowMinScore:o.belowMinScore,comparison:o.comparison,map:o.map,written:o.written},error:o.error}});export{z as execute,G as runAdvisorCommand};
|
|
@@ -1,7 +1 @@
|
|
|
1
|
-
import{writeFileSync as
|
|
2
|
-
`)},k=e=>e.coverage==="exempt"?[` exempt: ${e.exemptReason===void 0||e.exemptReason===""?"no reason given":e.exemptReason}`]:e.checks.map(r=>{const n=r.occurrences>1?`, ×${String(r.occurrences)}`:"";return` ${r.name} (−${String(r.weight)}${n})`}),T=e=>{const r=new Map;for(const n of e){const t=r.get(n.file);t===void 0?r.set(n.file,[n]):t.push(n)}return[...r].toSorted(([n],[t])=>b(n,t))},B=e=>{const r=f(e.procedures),n=[`advisor health ${String(e.score)}/100 — ${e.grade}`,"",` legend: ${l.clean} clean ${l.warned} warned ${l.failing} failing ${l.exempt} exempt`];for(const[t,o]of T(e.procedures)){n.push("",` ${t}`);for(const i of o)n.push(g(i,r),...k(i))}return n.join(`
|
|
3
|
-
`)},C=(e,r)=>{const n=e.procedures.find(o=>o.id===r);if(n===void 0){const o=e.procedures.slice(0,10).map(i=>` ${i.id}`);return[`no procedure ${r} in the map. Known ids:`,...o,e.procedures.length>10?" …":""].filter(Boolean).join(`
|
|
4
|
-
`)}const t=[`${E(n)} — ${String(n.score)}/100, ${n.coverage}`,` weight in the global mean: ${String(n.weight)}`];if(n.checks.length===0)return t.push(""," no rule fired"),t.join(`
|
|
5
|
-
`);t.push(""," rules fired:");for(const o of n.checks)t.push(` [${o.level}] ${o.name} −${String(o.weight)}${o.occurrences>1?` (×${String(o.occurrences)})`:""}`);return t.join(`
|
|
6
|
-
`)},I=new Date(0).toISOString(),m=(e,r)=>v(r)?r:w(e,r),L=e=>{if(e===void 0)return{value:void 0};if(e===null||e==="")return{error:"--min-score needs a value between 0 and 100"};const r=Number(e);return Number.isFinite(r)&&r>=0&&r<=100?{value:r}:{error:"--min-score must be a number between 0 and 100"}},N=(e,r,n)=>{const t=m(r,n===null||n===""?u:n);if(!S(t))return{error:`baseline not found at ${t} — generate one with \`lunora advisor\` and commit it`};const o=x(JSON.parse(p(t,"utf8")));return o===void 0?{error:`baseline at ${t} is malformed — regenerate it with \`lunora advisor\``}:{comparison:j(e,o)}},P=e=>`baseline is not comparable (${e}) — regenerate it; this run verified nothing`,_=(e,r,n)=>r.entry!==void 0?C(e,r.entry):r.all===!0?B(e):F(e,n),G=e=>{const r=e.cwd??process.cwd(),n=e.format==="json",{logger:t}=e,o=L(e.minScore);if("error"in o)return e.logger.error(o.error),{code:D.USAGE,error:o.error};const{advisorContext:i,advisories:$}=A({dryRun:!0,projectRoot:r}),a=y(i?.procedureProtections??[],$,{generatedAt:e.generatedAt??I}),s={map:a};if(e.baseline!==void 0){const c=N(a,r,e.baseline);if("error"in c)return e.logger.error(c.error),{...s,error:c.error};s.comparison=c.comparison,c.comparison.comparable||e.logger.error(P(c.comparison.reason))}if(e.write!==!1){const c=m(r,e.out??u);h(c,`${JSON.stringify(a,void 0,4)}
|
|
7
|
-
`,"utf8"),s.written=c}return s.belowMinScore=o.value!==void 0&&a.score<o.value,s.belowMinScore&&t.error(`advisor score ${String(a.score)} is below the required ${String(o.value)}`),n||(t.info(_(a,e,s.comparison)),s.written!==void 0&&t.success(`wrote ${s.written}`)),s},H=e=>e.error!==void 0||e.belowMinScore===!0?!0:e.comparison!==void 0&&(!e.comparison.comparable||e.comparison.regressed),z=M(({cwd:e,format:r,logger:n,options:t})=>{const o=G({all:t.all,baseline:t.baseline,cwd:e,entry:t.entry,format:r,logger:n,minScore:t.minScore,out:t.out,write:t.write});return{code:o.code??(H(o)?1:0),data:{belowMinScore:o.belowMinScore,comparison:o.comparison,map:o.map,written:o.written},error:o.error}});export{z as execute,G as runAdvisorCommand};
|
|
1
|
+
import{writeFileSync as E}from"node:fs";import{findWranglerFile as b,readWranglerJsonc as x,applyModify as G}from"@lunora/config/cloudflare";import{d as R}from"../packem_shared/command-B--jgXSc.mjs";import{EXIT_CODE as g,exitCodeForStatus as A}from"../packem_shared/EXIT_CODE-08cwt3MK.mjs";import{A as T,a as U}from"../packem_shared/variables-acxcvVQa.mjs";const p=256,D=e=>e.length>p?`${e.slice(0,p)}… (truncated)`:e,S="https://api.cloudflare.com/client/v4/accounts",m=64,_={byok:"https://developers.cloudflare.com/ai-gateway/configuration/bring-your-own-keys/",unifiedBilling:"https://developers.cloudflare.com/ai-gateway/features/unified-billing/"},f=e=>typeof e=="string"&&e.trim().length>0?e.trim():void 0,l=(e,t,n)=>(e.error(n),{code:t,error:n}),v=async(e,t,n,a={})=>{const o=await e(t,{...a,headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json"}}),r=await o.text();let i;try{i=JSON.parse(r)}catch{}return{body:i,ok:o.ok&&i?.success!==!1,status:o.status,text:r}},$=e=>{const t=(e.body?.errors??[]).map(n=>n.message).filter(n=>typeof n=="string");return`${String(e.status)}: ${D(t.length>0?t.join("; "):e.text)}`},L=(e,t,n)=>{let a=e;const o=[];for(const[r,i]of Object.entries(n))t?.[r]!==i&&(a=G(a,["vars",r],i),o.push(r));return{changed:o,text:a}},k=(e,t)=>{e.info(`next: \`<provider>/<model>\` slugs (e.g. "anthropic/claude-sonnet-5") now route through gateway "${t}". Before the first call,`),e.info(` configure how the provider is paid for in the Cloudflare dashboard (AI > AI Gateway > ${t}):`),e.info(` - Unified Billing (OpenAI, Anthropic, Google, xAI, Groq, DeepSeek): load credits — ${_.unifiedBilling}`),e.info(` - a key stored on the gateway (Mistral, Perplexity, OpenRouter, …): ${_.byok}`),e.info(" Then redeploy (`lunora deploy`) so the Worker picks up the new vars.")},N=async(e,t,n,a,o,r)=>{const i=`${S}/${encodeURIComponent(n)}/ai-gateway/gateways`,c=await v(t,`${i}/${encodeURIComponent(o)}`,a);if(c.ok){const s=c.body?.result?.collect_logs;return{action:"existing",collectLogs:typeof s=="boolean"?s:r}}if(c.status===401||c.status===403)return l(e,A(c.status),`ai gateway: could not read AI Gateway "${o}" (${$(c)})`);const u=await v(t,i,a,{body:JSON.stringify({cache_invalidate_on_update:!0,cache_ttl:0,collect_logs:r,id:o,rate_limiting_interval:0,rate_limiting_limit:0}),method:"POST"});return u.ok?{action:"created",collectLogs:r}:l(e,A(u.status),`ai gateway: could not create AI Gateway "${o}" (${$(u)})`)},j=e=>{const{logger:t}=e,n=b(e.cwd);if(n===void 0)return l(t,g.NOT_FOUND,"ai gateway: no wrangler.jsonc found — run `lunora init` (or `lunora dev`) first.");const{parsed:a,text:o}=x(n);if(a===void 0)return l(t,g.USAGE,`ai gateway: could not parse ${n} as JSONC.`);const r=f(e.id)??f(a.name);return r===void 0?l(t,g.USAGE,"ai gateway: no gateway id — pass --id <id>, or set `name` in wrangler.jsonc."):r.length>m?l(t,g.USAGE,`ai gateway: gateway id "${r}" is longer than ${String(m)} characters — pass a shorter --id.`):{gatewayId:r,parsed:a,text:o,wranglerPath:n}},h=e=>e?"on":"off",P=(e,t)=>(e.info(`ai gateway (dry run): would create or reuse AI Gateway "${t.gatewayId}" (log collection ${h(t.collectLogs)}).`),e.info(t.varsWritten.length===0?`ai gateway (dry run): ${t.wranglerPath} vars are already up to date.`:`ai gateway (dry run): would write ${t.varsWritten.join(", ")} into ${t.wranglerPath} vars.`),t.accountId===void 0&&e.warn("ai gateway (dry run): no CLOUDFLARE_ACCOUNT_ID (or `account_id` in wrangler.jsonc) — a real run will stop there."),{code:0,data:t}),W=async e=>{const{logger:t}=e,n=j(e);if("code"in n)return n;const{gatewayId:a,parsed:o,text:r,wranglerPath:i}=n,c=e.environment??process.env,u=e.logs!==!1,s=f(c.CLOUDFLARE_ACCOUNT_ID)??f(o.account_id),I={[U]:a,...s===void 0?{}:{[T]:s}},y=L(r,o.vars,I);if(e.dryRun===!0)return P(t,{accountId:s,action:"planned",collectLogs:u,dryRun:!0,gatewayId:a,varsWritten:y.changed,wranglerPath:i});const w=f(c.CLOUDFLARE_API_TOKEN);if(w===void 0||s===void 0){const O=[w===void 0?"CLOUDFLARE_API_TOKEN (an API token with AI Gateway Write)":void 0,s===void 0?"CLOUDFLARE_ACCOUNT_ID (or `account_id` in wrangler.jsonc)":void 0].filter(C=>C!==void 0);return l(t,g.AUTH,`ai gateway: missing ${O.join(" and ")}.`)}const d=await N(t,e.fetch??globalThis.fetch.bind(globalThis),s,w,a,u);return"code"in d?d:(d.action==="created"?t.success(`ai gateway: created AI Gateway "${a}" (log collection ${h(d.collectLogs)}).`):t.info(`ai gateway: AI Gateway "${a}" already exists — reusing it (log collection ${h(d.collectLogs)}; change it in the dashboard).`),y.changed.length>0?(E(i,y.text,"utf8"),t.success(`ai gateway: wrote ${y.changed.join(", ")} into ${i} vars.`)):t.info(`ai gateway: ${i} vars are already up to date.`),k(t,a),{code:0,data:{accountId:s,action:d.action,collectLogs:d.collectLogs,dryRun:!1,gatewayId:a,varsWritten:y.changed,wranglerPath:i}})},F=async e=>e.subcommand!=="gateway"?l(e.logger,g.USAGE,`ai: unknown subcommand "${e.subcommand??""}" — expected: gateway. Example: lunora ai gateway`):W(e),V=R(({argument:e,cwd:t,logger:n,options:a})=>F({cwd:t,dryRun:a.dryRun===!0,id:a.id,logger:n,logs:a.logs,subcommand:e[0]}));export{V as execute,F as runAiCommand};
|
|
@@ -1,3 +1 @@
|
|
|
1
|
-
import{writeFileSync as E,existsSync as w,cpSync as j,statSync as b,lstatSync as I,readdirSync as N,mkdirSync as D,readFileSync as M}from"node:fs";import{join as u,sep as x,relative as B,resolve as O,dirname as K}from"node:path";import{SDK_TARGETS as V,SDK_LANGUAGES as G,generateSdk as P,isTypedSchema as Q}from"@lunora/codegen";import{LunoraError as d}from"@lunora/errors";import{d as J}from"../packem_shared/command-B--jgXSc.mjs";import{r as _,a as U,b as q,c as H,s as W}from"../packem_shared/resolve-DUCSc7jQ.mjs";const $="gh:anolilab/lunora/sdks",v="lunora-transport.json",X=/_test\.|Tests?\./u,k=t=>t.startsWith("test_")||X.test(t),A=(t,n="")=>N(t).toSorted((e,r)=>e.localeCompare(r)).flatMap(e=>{const r=u(t,e),a=n.length>0?`${n}/${e}`:e;return b(r).isDirectory()?A(r,a):[a]}),C=(t,n)=>{const e=I(n);if(e.isSymbolicLink())throw new d("INTERNAL",`refusing to vendor "${B(t,n)}" — it is a symlink, not a regular file`);if(e.isDirectory())for(const r of N(n))k(r)||C(t,u(n,r))},F=(t,n,e,r)=>{const a=u(t,e);if(!w(a))throw new d("NOT_FOUND",`transport is missing ${e}`);C(t,a);const s=u(n,r);return j(a,s,{filter:o=>!k(o.slice(o.lastIndexOf(x)+1)),force:!0,recursive:!0}),b(s).isDirectory()?A(s).map(o=>`${r}/${o}`):[r]},R=(t,n)=>n.vendor.every(e=>w(u(t,e.from))),z=async(t,n)=>{const{language:e,logger:r,outputDirectory:a,registryOptions:s,target:o}=n,{cleanup:f,directory:h}=await H(e,{...s,ref:t},$);try{if(!R(h,o)){r.warn(`${$}/${e} does not exist at ${t}.`);return}return{files:o.vendor.flatMap(c=>F(h,a,c.from,c.to)).toSorted((c,l)=>c.localeCompare(l)),ref:t,source:`${$}/${e}`,versionMatched:t===_()}}finally{f()}},Y=(t,n)=>{const{language:e,outputDirectory:r,target:a}=n,s=u(t,e);if(!w(s))throw new d("NOT_FOUND",`no transport at ${s} — --from must point at a directory of per-language transports (the repo's \`sdks/\`)`);if(!R(s,a)){const o=a.vendor.map(f=>f.from).join(", ");throw new d("NOT_FOUND",`${s} is not a ${e} transport — expected it to contain ${o}`)}return{files:a.vendor.flatMap(o=>F(s,r,o.from,o.to)).toSorted((o,f)=>o.localeCompare(f)),ref:"local",source:s,versionMatched:!1}},Z=async t=>{const{allowUnsafeSource:n,from:e,language:r,logger:a,outputDirectory:s,ref:o,source:f,target:h}=t;if(e!==void 0)return Y(e,{language:r,outputDirectory:s,target:h});const c={allowUnsafeSource:n,logger:a,names:[],source:f},l=async i=>z(await q(i,a),{language:r,logger:a,outputDirectory:s,registryOptions:c,target:h});if(o!==void 0&&o.length>0){const i=await l(o);if(i===void 0)throw new d("NOT_FOUND",`--ref ${o} carries no ${r} transport — pick a ref that does, or pass --from <dir> to copy a local one`);return i}const m=_(),g=await l(m).catch(i=>{const y=i instanceof Error?i.message.split(`
|
|
2
|
-
`)[0]??i.message:String(i);a.warn(`could not fetch the transport at ${m} (${y}).`)});if(g!==void 0)return g;const p=await l(void 0);if(p===void 0)throw new d("NOT_FOUND",`no ${r} transport at ${m} or on the release branch. This language may not be released yet — pass --from <dir> to copy one from a checkout, or --ref <tag> to name a ref that has it.`);return a.warn(`FALLBACK: the transport is NOT version-matched to this CLI (${U()}). Wanted ${m}, used ${p.ref}. The vendored wire protocol may not be the one this surface was generated against; ${v} records what was actually copied.`),p},ee=(t,n,e)=>{const r={cliVersion:U(),files:e.files,language:n,note:e.versionMatched?"Vendored by `lunora sdk generate` at the ref matching the CLI that generated the surface beside it. Regenerate with a newer CLI to upgrade.":"Vendored by `lunora sdk generate` from a ref that is NOT this CLI's release tag, so the transport and the generated surface may be different protocol vintages.",ref:e.ref,source:e.source,versionMatched:e.versionMatched};E(u(t,v),`${JSON.stringify(r,void 0,4)}
|
|
3
|
-
`,"utf8")},te=u("lunora","_generated","openrpc.json"),re=t=>{if(!w(t))throw new d("NOT_FOUND",`no OpenRPC document at ${t} — run \`lunora codegen --api-spec openrpc\` (or \`--api-spec both\`) first, or pass --spec`);let n;try{n=JSON.parse(M(t,"utf8"))}catch(e){throw new d("BAD_REQUEST",`${t} is not valid JSON: ${e instanceof Error?e.message:String(e)}`)}if(n===null||typeof n!="object"||!Array.isArray(n.methods))throw new d("BAD_REQUEST",`${t} is not an OpenRPC document (no \`methods\` array)`);return n},de=J(async({argument:t,cwd:n,logger:e,options:r})=>{const a=t[0]??"generate";if(a!=="generate")throw new d("BAD_REQUEST",`unknown subcommand "${a}" — the only one is \`lunora sdk generate\``);const s=r.lang??"python",o=V[s];if(o===void 0)throw new d("BAD_REQUEST",`unsupported --lang "${s}" — expected one of: ${G.join(" | ")}`);const f=W("sdk generate",{allowUnsafeSource:r.allowUnsafeSource,logger:e,names:[],source:r.source});if(f!==void 0)throw new d("BAD_REQUEST",f);const h=O(n,r.spec??te),c=O(n,r.out??u("sdk",s)),l=re(h);l.methods.length===0&&e.warn(`${h} declares no methods — writing an empty SDK.`);const{files:m,undeclared:g,unrepresentable:p}=await P(l,o);D(c,{recursive:!0});const i=await Z({allowUnsafeSource:r.allowUnsafeSource,from:r.from,language:s,logger:e,outputDirectory:c,ref:r.ref,source:r.source,target:o});ee(c,s,i);for(const[S,L]of Object.entries(m)){const T=u(c,S);D(K(T),{recursive:!0}),E(T,L,"utf8")}const y=l.methods.filter(S=>!Q(S.result?.schema)).length;return e.success(`Generated ${s} SDK for ${String(l.methods.length)} function(s) → ${c}`),e.info(`Vendored the ${s} transport (${String(i.files.length)} file(s)) from ${i.source} @ ${i.ref}${i.versionMatched?" — version-matched to this CLI":""}; see ${v}.`),e.info(o.requires.length>0?`Install in the consuming project: ${o.requires.join(", ")}.`:"Nothing to install — the transport is vendored and needs only the standard library."),g.length>0&&e.warn(`${String(g.length)} schema(s) are not expressible as a named ${s} model, so those arguments or returns stay untyped: ${g.join(", ")}`),p.length>0&&e.warn(`${String(p.length)} function(s) take or return a \`v.bigint()\`/\`v.bytes()\`, which no generated model can carry — their parameters stay untyped, so pass wire values directly: ${p.join(", ")}`),y>0&&e.warn(`${String(y)} of ${String(l.methods.length)} function(s) return an untyped result — declare \`.output()\` on them for typed returns.`),{code:0}});export{de as execute};
|
|
1
|
+
import{existsSync as f,readFileSync as g,realpathSync as w}from"node:fs";import{join as u}from"node:path";import{DEV_VARS_FILE as m,parseDevVariableEntries as x,isPlaceholderValue as _,discoverSchemaInfo as A,inferLunoraBindings as R}from"@lunora/config";import{findWranglerFile as $,readWranglerJsonc as S,validateWranglerProject as I,UNEXPORTED_CLASS_MARKER as b,collectExportGaps as L}from"@lunora/config/cloudflare";import{i as N,m as j,c as O}from"../packem_shared/secret-key-DsMeUoEg.mjs";import{r as E,d as D}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{d as P}from"../packem_shared/command-B--jgXSc.mjs";import{i as V}from"../packem_shared/path-containment-CgxYZggb.mjs";import{b as y,c as k,a as h}from"../packem_shared/variables-acxcvVQa.mjs";const C=(t,e)=>{const n=new Set,r=o=>{for(const[c,s]of Object.entries(o??{}))typeof s=="string"&&s.trim().length>0&&n.add(c)};r(t.vars);for(const o of Object.values(t.env??{}))r(o.vars);const a=u(e,m);if(f(a))try{r(Object.fromEntries(x(g(a,"utf8")).map(o=>[o.key,o.value])))}catch{}return n},U=(t,e,n,r)=>{if(t===void 0||!n)return;const a=C(t,e),o=a.has(y),c=t.ai?.binding;!o&&(typeof c!="string"||c.length===0)&&r.push({code:"ai-binding-missing",fix:`Run \`lunora dev\` (it adds the binding), add \`"ai": { "binding": "AI" }\` to wrangler.jsonc, or set ${y} to an OpenAI-compatible proxy.`,level:"warn",message:"the project uses ctx.ai (@lunora/ai / env.AI) but wrangler.jsonc declares no `ai` binding — model calls will fail at runtime."}),a.has(k)&&r.push({code:"ai-gateway-token-unused",fix:"Make the gateway unauthenticated for ctx.ai, or remove the token. A bring-your-own AI SDK provider built with `resolveAiGateway` does send it.",level:"warn",message:`${k} is set, but ctx.ai's Workers AI binding cannot send a gateway token — it is ignored on that path.`}),!o&&!a.has(h)&&r.push({code:"ai-gateway-default",fix:`Run \`lunora ai gateway\` to create a gateway for this app and write ${h} into wrangler vars.`,level:"info",message:`no ${h} in vars or ${m} — \`<provider>/<model>\` slugs route through the account's \`default\` AI Gateway.`})},M=t=>{const e=t.trim();if(e==="")return!0;const n=e.toLowerCase();return n.includes("replace")||n.startsWith("<")&&n.endsWith(">")},T=t=>{const e=$(t);if(e===void 0)return{parsed:void 0,path:void 0};const{parsed:n}=S(e);return{parsed:n,path:e}},W=(t,e,n,r)=>{if(n===void 0){r.push({code:"wrangler-missing",fix:"Run `lunora init` (or `lunora dev`) to scaffold and reconcile wrangler.jsonc.",level:"fail",message:"wrangler.jsonc not found."});return}if(e===void 0){r.push({code:"wrangler-unparseable",fix:`Check ${n} is valid JSONC.`,level:"fail",message:`Could not parse ${n}.`});return}const{report:a}=I({projectRoot:t});for(const s of a.errors.filter(l=>l.includes(b)))r.push({code:"wrangler-class-unexported",level:"fail",message:s});for(const s of a.warnings.filter(l=>l.includes("LUNORA_ORIGIN_URL")))r.push({code:"scheduler-origin-missing",fix:"Set LUNORA_ORIGIN_URL in wrangler vars to the worker's public URL (or `wrangler secret put LUNORA_ORIGIN_URL`).",level:"warn",message:s});const o=s=>s.includes(b)||s.includes("SHARD");for(const s of a.errors.filter(l=>!o(l)))r.push({code:"wrangler-invalid",fix:"Fix the reported wrangler.jsonc problem; `lunora verify` reports the same set.",level:"fail",message:s});for(const s of a.warnings.filter(l=>!l.includes("LUNORA_ORIGIN_URL")))r.push({code:"wrangler-advisory",level:"warn",message:s});const c=a.errors.find(s=>s.includes("SHARD"));c===void 0?r.push({code:"wrangler-shard-binding-ok",level:"pass",message:"wrangler.jsonc present with a SHARD durable-object binding."}):r.push({code:"wrangler-shard-binding-missing",fix:"Run `lunora dev` to auto-reconcile, or add the binding manually.",level:"fail",message:c})},G=(t,e)=>{f(u(t,"lunora.json"))&&e.push({code:"stale-lunora-json",fix:'Move `target` / `remote` into `lunora.config.ts` (`export default { target: "…" }`), then delete lunora.json.',level:"warn",message:"lunora.json is present but no longer read — lunora.config.* replaced it, so any `target` or `remote` in it is being ignored."})},F=(t,e)=>{t===void 0||t.limits?.cpu_ms!==void 0||e.push({code:"cpu-limit-missing",fix:'Add `"limits": { "cpu_ms": 30000 }` to wrangler.jsonc, tuned to your slowest legitimate handler.',level:"info",message:"no limits.cpu_ms is set — a runaway handler can burn CPU up to the platform default before anything stops it."})},K=(t,e)=>{const n=(t?.r2_buckets??[]).map(r=>r?.bucket_name).filter(r=>typeof r=="string"&&r.length>0);n.length!==0&&e.push({code:"r2-lifecycle-unset",fix:"wrangler r2 bucket lifecycle list <bucket> — add an abort-incomplete-multipart rule if none exists.",level:"info",message:`R2 bucket(s) ${n.join(", ")}: verify a lifecycle rule aborts incomplete multipart uploads — orphaned parts are billed but invisible in a listing.`})},z=(t,e)=>{const{error:n,info:r}=A(t,"lunora");if(n!==void 0){e.push({code:"schema-unreadable",fix:"Fix the parse error, then re-run `lunora doctor`. `lunora codegen` reports the same failure with the offending source.",level:"fail",message:`lunora/schema.ts could not be parsed, so every schema-derived check was skipped: ${n}`});return}for(const a of r?.vectorMetadata??[]){const o=j(a.kind);if(o===void 0){e.push({code:"vector-metadata-unfilterable",fix:"Filter on a string, number or boolean column, or drop it from `metadata`.",level:"warn",message:`vector index "${a.index}" declares metadata "${a.property}", whose type Vectorize cannot filter on.`});continue}e.push({code:"vector-metadata-index-required",fix:`wrangler ${O({index:a.index,property:a.property,type:o}).join(" ")}`,level:"info",message:`vector index "${a.index}" filters on metadata "${a.property}" — that needs a Vectorize metadata index (\`lunora deploy\` creates it).`})}},B=(t,e)=>{if(t===void 0)return;const n=(t.d1_databases??[]).filter(Boolean);for(const r of n){const a=typeof r.database_id=="string"?r.database_id:"";if(M(a)){const o=typeof r.binding=="string"&&r.binding.length>0?r.binding:"<unnamed>";e.push({code:"d1-placeholder-id",fix:"Run `wrangler d1 create <name>` and paste the returned database_id into wrangler.jsonc.",level:"fail",message:`D1 binding "${o}" has a placeholder database_id ("${a||"<empty>"}").`})}}},H=(t,e)=>{if(t===void 0)return;const n=(t.send_email??[]).filter(Boolean);for(const r of n){const a=typeof r.destination_address=="string"?r.destination_address:"";if(a!==""&&_(a)){const o=typeof r.name=="string"&&r.name.length>0?r.name:"send_email";e.push({code:"email-destination-placeholder",fix:"Set destination_address to a verified Cloudflare Email Routing address.",level:"warn",message:`send_email binding "${o}" has a placeholder destination_address ("${a}").`})}}},J=(t,e)=>{const n=u(t,m);if(!f(n))return;let r;try{r=g(n,"utf8")}catch{return}const a=x(r).filter(o=>N(o.key)&&_(o.value)).map(o=>o.key);a.length>0&&e.push({code:"dev-vars-missing-secret",fix:"Run `lunora dev` to auto-generate secrets, or fill them in by hand.",level:"warn",message:`${m} has unfilled secret value(s): ${a.join(", ")}.`})},X=(t,e)=>{const{source:n}=E({cwd:t});n===void 0?e.push({code:"admin-token-missing",fix:"Set LUNORA_ADMIN_TOKEN (env or `.dev.vars`) to enable admin RPCs / studio.",level:"info",message:"LUNORA_ADMIN_TOKEN is not set."}):e.push({code:"admin-token-set",level:"pass",message:`LUNORA_ADMIN_TOKEN is set (${D(n)}).`})},Y=async(t,e)=>{try{return await R({projectRoot:t})}catch(n){e.push({code:"declared-export-unchecked",fix:"Make sure the worker entry resolves (see `lunora codegen`), then re-run.",level:"warn",message:`could not check whether declared containers/workflows/agents are re-exported by the worker entry: ${n instanceof Error?n.message:String(n)}`});return}},q=(t,e)=>{const n=L(t),r=[...t.containers.map(a=>({...a,kind:"container"})),...t.workflows.map(a=>({...a,kind:"workflow"})),...t.agents.map(a=>({...a,kind:"agent"}))];for(const a of r.filter(o=>o.exported))e.push({code:"declared-export-ok",level:"pass",message:`${a.kind} "${a.exportName}" is exported by the worker entry.`});for(const a of n)e.push({code:"declared-export-missing",fix:`Add \`export * from "./lunora/_generated/${a.module}"\` to your worker entry (or re-run \`vis generate lunora-${a.kind}\`).`,level:"fail",message:`${a.kind} "${a.exportName}" is declared but ${a.className} is not exported by the worker entry.`})},Q=/^[\^~><= ]+/u,Z=/^(?<core>\d+\.\d+\.\d+)(?:-(?<channel>[a-z]+)\.(?<counter>\d+))?$/u,ee=t=>{const e=t.replace(Q,"").trim(),n=Z.exec(e);if(!n?.groups)return;const{channel:r,core:a,counter:o}=n.groups;return{channel:r??"",core:a??"",counter:o===void 0?void 0:Number.parseInt(o,10),raw:e}},ne=(t,e)=>{const n=u(t,"package.json");if(!f(n))return;let r;try{r=JSON.parse(g(n,"utf8"))}catch{return}const a={...r.devDependencies,...r.dependencies},o=[];for(const[i,d]of Object.entries(a)){if(i!=="lunorash"&&!i.startsWith("@lunora/"))continue;const v=ee(d);v&&o.push({name:i,version:v})}if(o.length<2)return;const c=i=>i.map(d=>`${d.name}@${d.version.raw}`).join(", "),s=new Set(o.map(i=>i.version.core)),l=new Set(o.map(i=>i.version.channel));if(s.size>1){e.push({code:"version-skew-cores",fix:'Run `pnpm update "@lunora/*" lunorash` (or `npm`/`yarn` equivalent) so every Lunora package moves to the same release.',level:"warn",message:`Lunora packages span ${String(s.size)} different versions: ${c(o)}.`});return}if(l.size>1){e.push({code:"version-skew-channels",fix:"Pick one channel (all stable, or all alpha/beta) and update the odd package out.",level:"warn",message:`Lunora packages mix release channels (${[...l].map(i=>i===""?"stable":i).join(" + ")}): ${c(o)}.`});return}const p=o.map(i=>i.version.counter).filter(i=>i!==void 0);if(p.length>1){const i=Math.min(...p),d=Math.max(...p);e.push({code:"version-counter-spread",level:"info",message:p.length===o.length&&i===d?`Lunora packages are all at ${[...l][0]??""}.${String(d)}.`:`Lunora pre-release counters span ${String(i)}–${String(d)}: ${c(o)}.`})}},re=[u("@lunora","cli"),"lunorash"],ae=(t,e,n)=>{if(e===void 0)return;const r=[];for(const o of re){const c=u(t,"node_modules",o);if(f(c))try{r.push(w(c))}catch{}}if(r.length===0)return;let a;try{a=w(e)}catch{return}r.some(o=>V(o,a))||n.push({code:"cli-shadowed",fix:"Run the project's own CLI: `pnpm exec lunora …` (or `npx lunora …`).",level:"warn",message:`the running lunora (${a}) is not the project's own install (${r.join(", ")}).`})},te=async t=>{const e=t.cwd??process.cwd(),n=[],{parsed:r,path:a}=T(e);W(e,r,a,n),B(r,n),H(r,n),F(r,n),K(r,n),J(e,n),X(e,n),ne(e,n),z(e,n),G(e,n),ae(e,t.executablePath??process.argv[1],n);const o=await Y(e,n);o!==void 0&&q(o,n),U(r,e,o?.usesAi===!0,n);const c={fail:0,info:0,pass:0,warn:0};for(const l of n)c[l.level]+=1;const s=c.fail>0?1:0;return{code:s,findings:n,ok:s===0,summary:c}},oe={fail:"FAIL",info:"INFO",pass:"PASS",warn:"WARN"},se=(t,e)=>{e.info("lunora doctor — project preflight");for(const a of t.findings){const o=`[${oe[a.level]}] ${a.message}`;a.level==="fail"?e.error(o):a.level==="warn"?e.warn(o):e.info(o),a.fix!==void 0&&a.level!=="pass"&&e.info(` fix: ${a.fix}`)}const{fail:n,warn:r}=t.summary;n>0?e.error(`${String(n)} failure(s), ${String(r)} warning(s).`):r>0?e.warn(`0 failures, ${String(r)} warning(s).`):e.success("all checks passed.")},ie=async t=>{const{logger:e}=t,n=await te({...t});return se(n,e),n},ve=P(async({cwd:t,format:e,logger:n})=>{const r=await ie({cwd:t,format:e,logger:n});return{code:r.code,data:{findings:r.findings,summary:r.summary}}});export{ve as execute,te as runDoctor,ie as runDoctorCommand};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
3
|
-
`,headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json"},method:"PUT"});if(!l.ok){const d=await l.text().catch(()=>"<no body>");throw new w("INTERNAL",`backup: snapshot ${c.file} was written but its manifest was not (HTTP ${String(l.status)}): ${d}`)}},stage:async c=>{const s=await _(m(R(),"lunora-backup-"));return{path:m(s,v("",c)),release:async()=>b(s,{force:!0,recursive:!0})}}}},pe=".lunora-backups",F="/_lunora/admin/backup/retention",$e="/_lunora/admin/backup/prune",ve="/_lunora/admin/pitr",Se="__lunora_admin__:getPitrBookmark",Ee="__lunora_admin__:pitrRestore",Te=async(e,t)=>{const r=(e.now??(()=>new Date))().toISOString(),a=await t.stage(r);try{const o=await re({cwd:e.cwd,fetchImpl:e.fetchImpl,logger:e.logger,out:a.path,prod:e.prod,tables:e.tables,token:e.token,url:e.url});if(o.code!==0)return{code:o.code};const i=t.locate(r),n=await q(a.path);await t.commit(i,a.path,n);const f={bytes:n.bytes,createdAt:r,file:i,id:r,rows:o.rows,sha256:n.sha256,tables:e.tables};return await t.record(f),e.logger.success(`backup created: ${i} (${o.rows.toString()} rows, ${n.bytes.toString()} bytes)`),{code:0,entry:f}}finally{await a.release().catch(o=>{e.logger.warn(`backup: could not clean up staging (${o instanceof Error?o.message:String(o)})`)})}},Ae=async(e,t,r)=>{if(t?.sha256===void 0)return r.error(t===void 0?"--verify needs a recorded checksum, and a snapshot restored by path/key has no manifest entry — restore it by its backup id instead":`--verify: backup ${t.id} carries no recorded checksum — it was taken by a release before checksums existed`),{code:u.USAGE};const a=await q(e);if(a.sha256!==t.sha256)return r.error(`--verify: ${t.file} does not match its recorded checksum (expected ${t.sha256}, got ${a.sha256}) — nothing was imported`),{code:1};r.success(`verified ${t.file} against its recorded sha256`)},Ne=async(e,t)=>{const r=await t.list();if(r.length===0)return e.logger.info(`no backups found in ${t.label}`),{code:0,entries:[]};for(const a of r)e.logger.info(`${a.id} ${a.rows.toString()} rows ${a.bytes.toString()} bytes ${a.file}`);return{code:0,entries:r}},Ie=async(e,t)=>{const{target:r}=e;if(r===void 0||r.length===0)return e.logger.error("restore requires a backup id or file path. Usage: lunora backup restore <id|file>"),{code:u.USAGE};const o=(await t.list()).find(n=>n.id===r),i=await t.materialize(o,r);if(i===void 0)return e.logger.error(`backup not found: ${r}`),{code:u.NOT_FOUND};try{if(e.verify===!0){const f=await Ae(i.path,o,e.logger);if(f!==void 0)return f}const n=await ne({cwd:e.cwd,fetchImpl:e.fetchImpl,file:i.path,logger:e.logger,prod:e.prod,token:e.token,url:e.url,yes:e.yes});return{code:n.code,entry:o,restored:n.inserted}}finally{await i.release().catch(n=>{e.logger.warn(`backup: could not clean up the downloaded snapshot (${n instanceof Error?n.message:String(n)})`)})}},Ue=e=>{if(e.prod&&e.url===void 0)return e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)"),{refused:u.USAGE};if(e.restore===!0&&e.at===void 0&&e.bookmark===void 0)return e.logger.error("pitr --restore requires --at <time> or --bookmark <bookmark>"),{refused:u.USAGE};const t=T(e.url,e.logger,e.cwd);if(t===void 0)return{refused:u.USAGE};if(e.restore===!0&&V({prod:e.prod,url:t})&&e.yes!==!0)return e.logger.error(`pitr --restore restores data in place at ${t}, which is not local. Re-run with --yes to confirm.`),{refused:u.USAGE};const{token:r}=E({cwd:e.cwd??process.cwd(),token:e.token,url:t});if(!r)return e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{refused:u.AUTH};const a=e.adminFetch??globalThis.fetch;if(typeof a!="function")throw new TypeError("no fetch implementation available — pass pitrFetch or run on Node >= 18");return{fetchImpl:a,requestUrl:`${t}${ve}`,token:r}},_e=(e,t)=>{const r={};return e.at!==void 0&&(r.time=e.at),t&&e.bookmark!==void 0&&(r.bookmark=e.bookmark),t&&e.restart===!0&&(r.restart=!0),r},xe=async e=>{const t=Ue(e);if(p(t))return{code:t.refused};const r=e.restore===!0,a=r?Ee:Se,o=_e(e,r),i=r?"restore":"bookmark";e.logger.info(`POST ${t.requestUrl} -> pitr ${i}${e.shard===void 0?"":` (shard "${e.shard}")`}`);const n=await t.fetchImpl(t.requestUrl,{body:JSON.stringify({args:o,functionPath:a,shardKey:e.shard}),headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json"},method:"POST"});return{body:await y(n,e.logger),code:n.ok?0:k(n.status)}},Re=(e,t)=>{if(e.bucket===void 0)return e.prefix!==void 0?(e.logger.error("--prefix applies only to an R2 destination — pass --bucket alongside it, or use --dir to point at a local directory."),{refused:u.USAGE}):he(m(t,e.dir??pe));if(e.dir!==void 0)return e.logger.error("--dir applies only to a local destination and does not apply alongside --bucket — drop one."),{refused:u.USAGE};if(e.prod===!0&&e.url===void 0)return e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)"),{refused:u.USAGE};const r=T(e.url,e.logger,e.cwd);if(r===void 0)return{refused:u.USAGE};const{token:a}=E({cwd:t,token:e.token,url:r});if(!a)return e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{refused:u.AUTH};const o=e.fetchImpl??globalThis.fetch;if(typeof o!="function")throw new TypeError("no fetch implementation available — pass fetchImpl or run on Node >= 18");return ye({context:{baseUrl:r,bucket:e.bucket==="default"?void 0:e.bucket,fetchImpl:o,token:a},logger:e.logger,prefix:e.prefix})},L=e=>{const t=[e.bucket===void 0?void 0:"--bucket",e.prefix===void 0?void 0:"--prefix",e.dir===void 0?void 0:"--dir"].filter(i=>i!==void 0);if(t.length>0)return e.logger.error(`${t.join(" / ")} ${t.length===1?"does":"do"} not apply here — retention and prune act on the store the worker itself is configured with (\`backupStore\`), not a destination you name.`),{refused:u.USAGE};if(e.prod===!0&&e.url===void 0)return e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)"),{refused:u.USAGE};const r=T(e.url,e.logger,e.cwd);if(r===void 0)return{refused:u.USAGE};const{token:a}=E({cwd:e.cwd??process.cwd(),token:e.token,url:r});if(!a)return e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{refused:u.AUTH};const o=e.adminFetch??globalThis.fetch;if(typeof o!="function")throw new TypeError("no fetch implementation available — pass pitrFetch or run on Node >= 18");return{baseUrl:r,fetchImpl:o,token:a}},M=(e,t)=>{e.logger.info(`backup retention would keep the newest ${t.keep.toString()} of ${t.eligible.toString()} under ${t.prefix} and delete ${t.wouldDelete.length.toString()}`);for(const r of t.wouldDelete)e.logger.info(` ${D(r)}`)},Oe=async e=>{const t=L(e);if(p(t))return{code:t.refused};const r=await t.fetchImpl(`${t.baseUrl}${F}`,{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(!r.ok)return await y(r,e.logger),{code:k(r.status)};const a=await r.json();return a.cron===void 0?(e.logger.info("no scheduled backup is configured (`backupCron`), so retention would delete nothing"),{code:0,preview:a}):a.keep<=0?(e.logger.info(`retention is off for cron "${a.cron}" (\`backupRetain\` unset) — every snapshot under ${a.prefix} is kept`),{code:0,preview:a}):(M(e,a),a.eligible===0&&e.logger.info(`no snapshot under ${a.prefix} was written by this cron, so retention has nothing of its own to remove`),{code:0,preview:a})},Pe=(e,t)=>{e.logger.success(`deleted ${t.deleted.length.toString()} backup(s)`);for(const r of t.deleted)e.logger.info(` ${D(r)}`);t.failed.length>0&&e.logger.warn(`${t.failed.length.toString()} could not be removed — the snapshot may be gone with its manifest left behind; run again to retry`),t.ignored>0&&e.logger.info(`${t.ignored.toString()} were already gone by the time the delete ran`),t.remaining>0&&e.logger.info(`${t.remaining.toString()} more are past the window — run \`lunora backup prune\` again`)},Be=async e=>{const t=L(e);if(p(t))return{code:t.refused};const r=await t.fetchImpl(`${t.baseUrl}${F}`,{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(!r.ok)return await y(r,e.logger),{code:k(r.status)};const a=await r.json();if(a.keep<=0||a.cron===void 0)return e.logger.error("backup prune needs a retention window: set `backupRetain` (and `backupCron`) on the worker. Without one there is nothing past the window to remove."),{code:u.USAGE,preview:a};if(a.wouldDelete.length===0)return e.logger.info(`nothing to prune — ${a.eligible.toString()} snapshot(s) under ${a.prefix} and retention keeps the newest ${a.keep.toString()}`),{code:0,preview:a};if(M(e,a),e.yes!==!0){const n=e.confirm??(z()?J:void 0);if(n===void 0)return e.logger.error("refusing to delete backups without confirmation — re-run with --yes (there is no undo for an object-store delete)"),{code:u.USAGE,preview:a};if(!await n(`delete ${a.wouldDelete.length.toString()} backup(s)? This cannot be undone. [y/N] `))return e.logger.info("nothing was deleted"),{code:0,preview:a}}const o=await t.fetchImpl(`${t.baseUrl}${$e}`,{body:JSON.stringify({confirm:a.wouldDelete}),headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json"},method:"POST"});if(!o.ok)return await y(o,e.logger),{code:k(o.status),preview:a};const i=await o.json();return Pe(e,i),{code:i.failed.length>0?1:0,deleted:i.deleted,preview:a}},De=async(e,t)=>{try{if(e.subcommand==="pitr")return await xe(e);if(e.subcommand==="retention")return await Oe(e);if(e.subcommand==="prune")return await Be(e);const r=Re(e,t);return p(r)?{code:r.refused}:e.subcommand==="create"?await Te(e,r):e.subcommand==="list"?await Ne(e,r):await Ie(e,r)}catch(r){return e.logger.error(r instanceof Error?r.message:String(r)),{code:1}}},Ge=async e=>{const t=e.cwd??process.cwd(),r=await De(e,t);return{...r,data:{subcommand:e.subcommand,...r.entries===void 0?{}:{entries:r.entries},...r.entry===void 0?{}:{entry:r.entry},...r.restored===void 0?{}:{restored:r.restored},...r.preview===void 0?{}:{preview:r.preview},...r.deleted===void 0?{}:{deleted:r.deleted},...r.body===void 0?{}:{result:r.body}}}},je=e=>e==="create"||e==="list"||e==="pitr"||e==="prune"||e==="restore"||e==="retention",or=Z(async({argument:e,cwd:t,format:r,logger:a,options:o})=>{const i=e[0];if(!je(i)){const f=`backup: unknown subcommand "${i??""}" — expected create | list | restore | retention | prune | pitr`;return a.error(f),{code:u.USAGE,error:f}}const n=await Ge({at:o.at,bookmark:o.bookmark,bucket:o.bucket,cwd:t,dir:o.dir,format:r,logger:a,prefix:o.prefix,prod:o.prod===!0,restart:o.restart===!0,restore:o.restore===!0,shard:o.shard,subcommand:i,tables:o.tables,target:e[1],token:o.token,url:ee({cwd:t,prod:o.prod===!0,url:o.url}),verify:o.verify===!0,yes:o.yes===!0});return{code:n.code,data:n.data,error:n.error}});export{or as execute,Ge as runBackupCommand};
|
|
1
|
+
import{writeFileSync as E,existsSync as w,cpSync as j,statSync as b,lstatSync as I,readdirSync as N,mkdirSync as D,readFileSync as M}from"node:fs";import{join as u,sep as x,relative as B,resolve as O,dirname as K}from"node:path";import{SDK_TARGETS as V,SDK_LANGUAGES as G,generateSdk as P,isTypedSchema as Q}from"@lunora/codegen";import{LunoraError as d}from"@lunora/errors";import{d as J}from"../packem_shared/command-B--jgXSc.mjs";import{r as _,a as U,b as q,c as H,s as W}from"../packem_shared/resolve-DUCSc7jQ.mjs";const $="gh:anolilab/lunora/sdks",v="lunora-transport.json",X=/_test\.|Tests?\./u,k=t=>t.startsWith("test_")||X.test(t),A=(t,n="")=>N(t).toSorted((e,r)=>e.localeCompare(r)).flatMap(e=>{const r=u(t,e),a=n.length>0?`${n}/${e}`:e;return b(r).isDirectory()?A(r,a):[a]}),C=(t,n)=>{const e=I(n);if(e.isSymbolicLink())throw new d("INTERNAL",`refusing to vendor "${B(t,n)}" — it is a symlink, not a regular file`);if(e.isDirectory())for(const r of N(n))k(r)||C(t,u(n,r))},F=(t,n,e,r)=>{const a=u(t,e);if(!w(a))throw new d("NOT_FOUND",`transport is missing ${e}`);C(t,a);const s=u(n,r);return j(a,s,{filter:o=>!k(o.slice(o.lastIndexOf(x)+1)),force:!0,recursive:!0}),b(s).isDirectory()?A(s).map(o=>`${r}/${o}`):[r]},R=(t,n)=>n.vendor.every(e=>w(u(t,e.from))),z=async(t,n)=>{const{language:e,logger:r,outputDirectory:a,registryOptions:s,target:o}=n,{cleanup:f,directory:h}=await H(e,{...s,ref:t},$);try{if(!R(h,o)){r.warn(`${$}/${e} does not exist at ${t}.`);return}return{files:o.vendor.flatMap(c=>F(h,a,c.from,c.to)).toSorted((c,l)=>c.localeCompare(l)),ref:t,source:`${$}/${e}`,versionMatched:t===_()}}finally{f()}},Y=(t,n)=>{const{language:e,outputDirectory:r,target:a}=n,s=u(t,e);if(!w(s))throw new d("NOT_FOUND",`no transport at ${s} — --from must point at a directory of per-language transports (the repo's \`sdks/\`)`);if(!R(s,a)){const o=a.vendor.map(f=>f.from).join(", ");throw new d("NOT_FOUND",`${s} is not a ${e} transport — expected it to contain ${o}`)}return{files:a.vendor.flatMap(o=>F(s,r,o.from,o.to)).toSorted((o,f)=>o.localeCompare(f)),ref:"local",source:s,versionMatched:!1}},Z=async t=>{const{allowUnsafeSource:n,from:e,language:r,logger:a,outputDirectory:s,ref:o,source:f,target:h}=t;if(e!==void 0)return Y(e,{language:r,outputDirectory:s,target:h});const c={allowUnsafeSource:n,logger:a,names:[],source:f},l=async i=>z(await q(i,a),{language:r,logger:a,outputDirectory:s,registryOptions:c,target:h});if(o!==void 0&&o.length>0){const i=await l(o);if(i===void 0)throw new d("NOT_FOUND",`--ref ${o} carries no ${r} transport — pick a ref that does, or pass --from <dir> to copy a local one`);return i}const m=_(),g=await l(m).catch(i=>{const y=i instanceof Error?i.message.split(`
|
|
2
|
+
`)[0]??i.message:String(i);a.warn(`could not fetch the transport at ${m} (${y}).`)});if(g!==void 0)return g;const p=await l(void 0);if(p===void 0)throw new d("NOT_FOUND",`no ${r} transport at ${m} or on the release branch. This language may not be released yet — pass --from <dir> to copy one from a checkout, or --ref <tag> to name a ref that has it.`);return a.warn(`FALLBACK: the transport is NOT version-matched to this CLI (${U()}). Wanted ${m}, used ${p.ref}. The vendored wire protocol may not be the one this surface was generated against; ${v} records what was actually copied.`),p},ee=(t,n,e)=>{const r={cliVersion:U(),files:e.files,language:n,note:e.versionMatched?"Vendored by `lunora sdk generate` at the ref matching the CLI that generated the surface beside it. Regenerate with a newer CLI to upgrade.":"Vendored by `lunora sdk generate` from a ref that is NOT this CLI's release tag, so the transport and the generated surface may be different protocol vintages.",ref:e.ref,source:e.source,versionMatched:e.versionMatched};E(u(t,v),`${JSON.stringify(r,void 0,4)}
|
|
3
|
+
`,"utf8")},te=u("lunora","_generated","openrpc.json"),re=t=>{if(!w(t))throw new d("NOT_FOUND",`no OpenRPC document at ${t} — run \`lunora codegen --api-spec openrpc\` (or \`--api-spec both\`) first, or pass --spec`);let n;try{n=JSON.parse(M(t,"utf8"))}catch(e){throw new d("BAD_REQUEST",`${t} is not valid JSON: ${e instanceof Error?e.message:String(e)}`)}if(n===null||typeof n!="object"||!Array.isArray(n.methods))throw new d("BAD_REQUEST",`${t} is not an OpenRPC document (no \`methods\` array)`);return n},de=J(async({argument:t,cwd:n,logger:e,options:r})=>{const a=t[0]??"generate";if(a!=="generate")throw new d("BAD_REQUEST",`unknown subcommand "${a}" — the only one is \`lunora sdk generate\``);const s=r.lang??"python",o=V[s];if(o===void 0)throw new d("BAD_REQUEST",`unsupported --lang "${s}" — expected one of: ${G.join(" | ")}`);const f=W("sdk generate",{allowUnsafeSource:r.allowUnsafeSource,logger:e,names:[],source:r.source});if(f!==void 0)throw new d("BAD_REQUEST",f);const h=O(n,r.spec??te),c=O(n,r.out??u("sdk",s)),l=re(h);l.methods.length===0&&e.warn(`${h} declares no methods — writing an empty SDK.`);const{files:m,undeclared:g,unrepresentable:p}=await P(l,o);D(c,{recursive:!0});const i=await Z({allowUnsafeSource:r.allowUnsafeSource,from:r.from,language:s,logger:e,outputDirectory:c,ref:r.ref,source:r.source,target:o});ee(c,s,i);for(const[S,L]of Object.entries(m)){const T=u(c,S);D(K(T),{recursive:!0}),E(T,L,"utf8")}const y=l.methods.filter(S=>!Q(S.result?.schema)).length;return e.success(`Generated ${s} SDK for ${String(l.methods.length)} function(s) → ${c}`),e.info(`Vendored the ${s} transport (${String(i.files.length)} file(s)) from ${i.source} @ ${i.ref}${i.versionMatched?" — version-matched to this CLI":""}; see ${v}.`),e.info(o.requires.length>0?`Install in the consuming project: ${o.requires.join(", ")}.`:"Nothing to install — the transport is vendored and needs only the standard library."),g.length>0&&e.warn(`${String(g.length)} schema(s) are not expressible as a named ${s} model, so those arguments or returns stay untyped: ${g.join(", ")}`),p.length>0&&e.warn(`${String(p.length)} function(s) take or return a \`v.bigint()\`/\`v.bytes()\`, which no generated model can carry — their parameters stay untyped, so pass wire values directly: ${p.join(", ")}`),y>0&&e.warn(`${String(y)} of ${String(l.methods.length)} function(s) return an untyped result — declare \`.output()\` on them for typed returns.`),{code:0}});export{de as execute};
|
|
@@ -1 +1,3 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import H,{join as m,resolve as N}from"node:path";import{isInteractive as z,promptYesNo as J}from"@lunora/config";import{backupObjectKey as v,isBackupManifestEntry as B,normalizeBackupPrefix as W,BACKUP_KEY_PREFIX as Y,backupManifestKey as X,isBackupManifestKey as Q,backupObjectKeyOfManifest as D}from"@lunora/runtime";import{r as E,t as V}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{r as T}from"../packem_shared/admin-url-BhF5ufg1.mjs";import{d as Z}from"../packem_shared/command-B--jgXSc.mjs";import{EXIT_CODE as u,isRefusal as p,exitCodeForStatus as k}from"../packem_shared/EXIT_CODE-08cwt3MK.mjs";import{a as ee}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{runExportCommand as re}from"../packem_shared/runExportCommand-DxsJHYZt.mjs";import{b as te,l as ae,M as I,u as oe,r as ne}from"../packem_shared/import-D7qdpSmJ.mjs";import{readAndLogBody as y}from"./runRpcCommand.mjs";import{randomUUID as G,createHash as ie}from"node:crypto";import{existsSync as A,createReadStream as se,createWriteStream as ce}from"node:fs";import{mkdir as de,rm as b,rename as j,readFile as C,writeFile as ue,realpath as U,mkdtemp as _}from"node:fs/promises";import{LunoraError as w}from"@lunora/errors";import{i as x}from"../packem_shared/path-containment-CgxYZggb.mjs";import{tmpdir as R}from"node:os";import{Readable as le}from"node:stream";import{pipeline as fe}from"node:stream/promises";const S="manifest.json",q=async e=>{const t=ie("sha256");let r=0;for await(const a of se(e)){const o=a;r+=o.byteLength,t.update(o)}return{bytes:r,sha256:t.digest("hex")}},O=async e=>{const t=m(e,S);if(!A(t))return[];let r;try{r=JSON.parse(await C(t,"utf8"))}catch(a){const o=a instanceof Error?a.message:String(a);throw new w("INTERNAL",`backup: ${t} exists but is not valid JSON (${o}) — refusing to overwrite it; fix or remove it manually`,{cause:a})}if(!Array.isArray(r))throw new TypeError(`backup: ${t} exists but is not a JSON array — refusing to overwrite it; fix or remove it manually`);return r.filter(a=>B(a))},me=async(e,t)=>{const r=m(e,`${S}.${G()}.tmp`);try{await ue(r,`${JSON.stringify(t,void 0,2)}
|
|
2
|
+
`,"utf8"),await j(r,m(e,S))}catch(a){throw await b(r,{force:!0}),a}},ge=async(e,t)=>{const r=N(e),a=N(r,t.file),o=()=>{throw new w("INTERNAL",`backup: entry ${t.id} points outside ${r} (${t.file}) — refusing to read it`)};if(x(r,a)||o(),!!A(a))return x(await U(r),await U(a))||o(),a},he=e=>{const t=r=>v("",r);return{commit:async(r,a)=>{await j(a,m(e,r))},label:e,list:async()=>O(e),locate:t,materialize:async(r,a)=>{const o=i=>i===void 0?void 0:{path:i,release:()=>Promise.resolve()};return o(r===void 0?A(a)?a:void 0:await ge(e,r))},record:async r=>{const a=await O(e);a.push(r),await me(e,a)},stage:async r=>{await de(e,{recursive:!0});const a=m(e,`${t(r)}.${G()}.partial`);return{path:a,release:()=>b(a,{force:!0})}}}},we="/_lunora/admin/storage/object",be="/_lunora/admin/storage",P=8,ke=(e,t=H)=>{const r=t.basename(e);return r===""||r==="."||r===".."?"snapshot.ndjson":r},ye=e=>{const{context:t,logger:r}=e,a=W(e.prefix??Y),o=`bucket ${t.bucket??"(default)"} under ${a}`,i=te(t),n=c=>`${t.baseUrl}${we}?key=${encodeURIComponent(c)}${i}`,f=async c=>{const s=await t.fetchImpl(n(c),{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(!s.ok){const l=await s.text().catch(()=>"<no body>");throw new w("INTERNAL",`backup: could not read ${c} (HTTP ${String(s.status)}): ${l}`)}return s.text()},K=async c=>{try{const s=JSON.parse(await f(c));if(B(s))return s;r.warn(`backup: ignoring ${c} — not a backup manifest`)}catch(s){r.warn(`backup: ignoring ${c} — ${s instanceof Error?s.message:String(s)}`)}};return{commit:async(c,s,l)=>{if(l.bytes>I)throw new w("INTERNAL",`backup: the snapshot is ${String(l.bytes)} bytes, above the ${String(I)}-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 C(s);await oe(t,c,d,{contentType:"application/x-ndjson",id:c,sha256:l.sha256,size:l.bytes},r)},label:o,list:async()=>{const s=(await ae(t,a)).map(d=>d.key).filter(d=>Q(d)),l=[];for(let d=0;d<s.length;d+=P){const g=await Promise.all(s.slice(d,d+P).map(async h=>K(h)));l.push(...g.filter(h=>h!==void 0))}return l.toSorted((d,g)=>d.id.localeCompare(g.id))},locate:c=>v(a,c),materialize:async(c,s)=>{const l=c?.file??s,d=await t.fetchImpl(n(l),{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(d.status===404)return;if(!d.ok||d.body===null){const $=await d.text().catch(()=>"<no body>");throw new w("INTERNAL",`backup: could not download ${l} (HTTP ${String(d.status)}): ${$}`)}const g=await _(m(R(),"lunora-backup-")),h=m(g,ke(l));try{await fe(le.from(d.body),ce(h))}catch($){throw await b(g,{force:!0,recursive:!0}),$}return{path:h,release:async()=>b(g,{force:!0,recursive:!0})}},record:async c=>{const s=X(c.file),l=await t.fetchImpl(`${t.baseUrl}${be}?key=${encodeURIComponent(s)}${i}`,{body:`${JSON.stringify(c,void 0,2)}
|
|
3
|
+
`,headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json"},method:"PUT"});if(!l.ok){const d=await l.text().catch(()=>"<no body>");throw new w("INTERNAL",`backup: snapshot ${c.file} was written but its manifest was not (HTTP ${String(l.status)}): ${d}`)}},stage:async c=>{const s=await _(m(R(),"lunora-backup-"));return{path:m(s,v("",c)),release:async()=>b(s,{force:!0,recursive:!0})}}}},pe=".lunora-backups",F="/_lunora/admin/backup/retention",$e="/_lunora/admin/backup/prune",ve="/_lunora/admin/pitr",Se="__lunora_admin__:getPitrBookmark",Ee="__lunora_admin__:pitrRestore",Te=async(e,t)=>{const r=(e.now??(()=>new Date))().toISOString(),a=await t.stage(r);try{const o=await re({cwd:e.cwd,fetchImpl:e.fetchImpl,logger:e.logger,out:a.path,prod:e.prod,tables:e.tables,token:e.token,url:e.url});if(o.code!==0)return{code:o.code};const i=t.locate(r),n=await q(a.path);await t.commit(i,a.path,n);const f={bytes:n.bytes,createdAt:r,file:i,id:r,rows:o.rows,sha256:n.sha256,tables:e.tables};return await t.record(f),e.logger.success(`backup created: ${i} (${o.rows.toString()} rows, ${n.bytes.toString()} bytes)`),{code:0,entry:f}}finally{await a.release().catch(o=>{e.logger.warn(`backup: could not clean up staging (${o instanceof Error?o.message:String(o)})`)})}},Ae=async(e,t,r)=>{if(t?.sha256===void 0)return r.error(t===void 0?"--verify needs a recorded checksum, and a snapshot restored by path/key has no manifest entry — restore it by its backup id instead":`--verify: backup ${t.id} carries no recorded checksum — it was taken by a release before checksums existed`),{code:u.USAGE};const a=await q(e);if(a.sha256!==t.sha256)return r.error(`--verify: ${t.file} does not match its recorded checksum (expected ${t.sha256}, got ${a.sha256}) — nothing was imported`),{code:1};r.success(`verified ${t.file} against its recorded sha256`)},Ne=async(e,t)=>{const r=await t.list();if(r.length===0)return e.logger.info(`no backups found in ${t.label}`),{code:0,entries:[]};for(const a of r)e.logger.info(`${a.id} ${a.rows.toString()} rows ${a.bytes.toString()} bytes ${a.file}`);return{code:0,entries:r}},Ie=async(e,t)=>{const{target:r}=e;if(r===void 0||r.length===0)return e.logger.error("restore requires a backup id or file path. Usage: lunora backup restore <id|file>"),{code:u.USAGE};const o=(await t.list()).find(n=>n.id===r),i=await t.materialize(o,r);if(i===void 0)return e.logger.error(`backup not found: ${r}`),{code:u.NOT_FOUND};try{if(e.verify===!0){const f=await Ae(i.path,o,e.logger);if(f!==void 0)return f}const n=await ne({cwd:e.cwd,fetchImpl:e.fetchImpl,file:i.path,logger:e.logger,prod:e.prod,token:e.token,url:e.url,yes:e.yes});return{code:n.code,entry:o,restored:n.inserted}}finally{await i.release().catch(n=>{e.logger.warn(`backup: could not clean up the downloaded snapshot (${n instanceof Error?n.message:String(n)})`)})}},Ue=e=>{if(e.prod&&e.url===void 0)return e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)"),{refused:u.USAGE};if(e.restore===!0&&e.at===void 0&&e.bookmark===void 0)return e.logger.error("pitr --restore requires --at <time> or --bookmark <bookmark>"),{refused:u.USAGE};const t=T(e.url,e.logger,e.cwd);if(t===void 0)return{refused:u.USAGE};if(e.restore===!0&&V({prod:e.prod,url:t})&&e.yes!==!0)return e.logger.error(`pitr --restore restores data in place at ${t}, which is not local. Re-run with --yes to confirm.`),{refused:u.USAGE};const{token:r}=E({cwd:e.cwd??process.cwd(),token:e.token,url:t});if(!r)return e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{refused:u.AUTH};const a=e.adminFetch??globalThis.fetch;if(typeof a!="function")throw new TypeError("no fetch implementation available — pass pitrFetch or run on Node >= 18");return{fetchImpl:a,requestUrl:`${t}${ve}`,token:r}},_e=(e,t)=>{const r={};return e.at!==void 0&&(r.time=e.at),t&&e.bookmark!==void 0&&(r.bookmark=e.bookmark),t&&e.restart===!0&&(r.restart=!0),r},xe=async e=>{const t=Ue(e);if(p(t))return{code:t.refused};const r=e.restore===!0,a=r?Ee:Se,o=_e(e,r),i=r?"restore":"bookmark";e.logger.info(`POST ${t.requestUrl} -> pitr ${i}${e.shard===void 0?"":` (shard "${e.shard}")`}`);const n=await t.fetchImpl(t.requestUrl,{body:JSON.stringify({args:o,functionPath:a,shardKey:e.shard}),headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json"},method:"POST"});return{body:await y(n,e.logger),code:n.ok?0:k(n.status)}},Re=(e,t)=>{if(e.bucket===void 0)return e.prefix!==void 0?(e.logger.error("--prefix applies only to an R2 destination — pass --bucket alongside it, or use --dir to point at a local directory."),{refused:u.USAGE}):he(m(t,e.dir??pe));if(e.dir!==void 0)return e.logger.error("--dir applies only to a local destination and does not apply alongside --bucket — drop one."),{refused:u.USAGE};if(e.prod===!0&&e.url===void 0)return e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)"),{refused:u.USAGE};const r=T(e.url,e.logger,e.cwd);if(r===void 0)return{refused:u.USAGE};const{token:a}=E({cwd:t,token:e.token,url:r});if(!a)return e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{refused:u.AUTH};const o=e.fetchImpl??globalThis.fetch;if(typeof o!="function")throw new TypeError("no fetch implementation available — pass fetchImpl or run on Node >= 18");return ye({context:{baseUrl:r,bucket:e.bucket==="default"?void 0:e.bucket,fetchImpl:o,token:a},logger:e.logger,prefix:e.prefix})},L=e=>{const t=[e.bucket===void 0?void 0:"--bucket",e.prefix===void 0?void 0:"--prefix",e.dir===void 0?void 0:"--dir"].filter(i=>i!==void 0);if(t.length>0)return e.logger.error(`${t.join(" / ")} ${t.length===1?"does":"do"} not apply here — retention and prune act on the store the worker itself is configured with (\`backupStore\`), not a destination you name.`),{refused:u.USAGE};if(e.prod===!0&&e.url===void 0)return e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)"),{refused:u.USAGE};const r=T(e.url,e.logger,e.cwd);if(r===void 0)return{refused:u.USAGE};const{token:a}=E({cwd:e.cwd??process.cwd(),token:e.token,url:r});if(!a)return e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{refused:u.AUTH};const o=e.adminFetch??globalThis.fetch;if(typeof o!="function")throw new TypeError("no fetch implementation available — pass pitrFetch or run on Node >= 18");return{baseUrl:r,fetchImpl:o,token:a}},M=(e,t)=>{e.logger.info(`backup retention would keep the newest ${t.keep.toString()} of ${t.eligible.toString()} under ${t.prefix} and delete ${t.wouldDelete.length.toString()}`);for(const r of t.wouldDelete)e.logger.info(` ${D(r)}`)},Oe=async e=>{const t=L(e);if(p(t))return{code:t.refused};const r=await t.fetchImpl(`${t.baseUrl}${F}`,{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(!r.ok)return await y(r,e.logger),{code:k(r.status)};const a=await r.json();return a.cron===void 0?(e.logger.info("no scheduled backup is configured (`backupCron`), so retention would delete nothing"),{code:0,preview:a}):a.keep<=0?(e.logger.info(`retention is off for cron "${a.cron}" (\`backupRetain\` unset) — every snapshot under ${a.prefix} is kept`),{code:0,preview:a}):(M(e,a),a.eligible===0&&e.logger.info(`no snapshot under ${a.prefix} was written by this cron, so retention has nothing of its own to remove`),{code:0,preview:a})},Pe=(e,t)=>{e.logger.success(`deleted ${t.deleted.length.toString()} backup(s)`);for(const r of t.deleted)e.logger.info(` ${D(r)}`);t.failed.length>0&&e.logger.warn(`${t.failed.length.toString()} could not be removed — the snapshot may be gone with its manifest left behind; run again to retry`),t.ignored>0&&e.logger.info(`${t.ignored.toString()} were already gone by the time the delete ran`),t.remaining>0&&e.logger.info(`${t.remaining.toString()} more are past the window — run \`lunora backup prune\` again`)},Be=async e=>{const t=L(e);if(p(t))return{code:t.refused};const r=await t.fetchImpl(`${t.baseUrl}${F}`,{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(!r.ok)return await y(r,e.logger),{code:k(r.status)};const a=await r.json();if(a.keep<=0||a.cron===void 0)return e.logger.error("backup prune needs a retention window: set `backupRetain` (and `backupCron`) on the worker. Without one there is nothing past the window to remove."),{code:u.USAGE,preview:a};if(a.wouldDelete.length===0)return e.logger.info(`nothing to prune — ${a.eligible.toString()} snapshot(s) under ${a.prefix} and retention keeps the newest ${a.keep.toString()}`),{code:0,preview:a};if(M(e,a),e.yes!==!0){const n=e.confirm??(z()?J:void 0);if(n===void 0)return e.logger.error("refusing to delete backups without confirmation — re-run with --yes (there is no undo for an object-store delete)"),{code:u.USAGE,preview:a};if(!await n(`delete ${a.wouldDelete.length.toString()} backup(s)? This cannot be undone. [y/N] `))return e.logger.info("nothing was deleted"),{code:0,preview:a}}const o=await t.fetchImpl(`${t.baseUrl}${$e}`,{body:JSON.stringify({confirm:a.wouldDelete}),headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json"},method:"POST"});if(!o.ok)return await y(o,e.logger),{code:k(o.status),preview:a};const i=await o.json();return Pe(e,i),{code:i.failed.length>0?1:0,deleted:i.deleted,preview:a}},De=async(e,t)=>{try{if(e.subcommand==="pitr")return await xe(e);if(e.subcommand==="retention")return await Oe(e);if(e.subcommand==="prune")return await Be(e);const r=Re(e,t);return p(r)?{code:r.refused}:e.subcommand==="create"?await Te(e,r):e.subcommand==="list"?await Ne(e,r):await Ie(e,r)}catch(r){return e.logger.error(r instanceof Error?r.message:String(r)),{code:1}}},Ge=async e=>{const t=e.cwd??process.cwd(),r=await De(e,t);return{...r,data:{subcommand:e.subcommand,...r.entries===void 0?{}:{entries:r.entries},...r.entry===void 0?{}:{entry:r.entry},...r.restored===void 0?{}:{restored:r.restored},...r.preview===void 0?{}:{preview:r.preview},...r.deleted===void 0?{}:{deleted:r.deleted},...r.body===void 0?{}:{result:r.body}}}},je=e=>e==="create"||e==="list"||e==="pitr"||e==="prune"||e==="restore"||e==="retention",or=Z(async({argument:e,cwd:t,format:r,logger:a,options:o})=>{const i=e[0];if(!je(i)){const f=`backup: unknown subcommand "${i??""}" — expected create | list | restore | retention | prune | pitr`;return a.error(f),{code:u.USAGE,error:f}}const n=await Ge({at:o.at,bookmark:o.bookmark,bucket:o.bucket,cwd:t,dir:o.dir,format:r,logger:a,prefix:o.prefix,prod:o.prod===!0,restart:o.restart===!0,restore:o.restore===!0,shard:o.shard,subcommand:i,tables:o.tables,target:e[1],token:o.token,url:ee({cwd:t,prod:o.prod===!0,url:o.url}),verify:o.verify===!0,yes:o.yes===!0});return{code:n.code,data:n.data,error:n.error}});export{or as execute,Ge as runBackupCommand};
|