@lunora/cli 1.0.0-alpha.243 → 1.0.0-alpha.245
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 +7 -6
- package/dist/index.d.ts +7 -6
- package/dist/index.mjs +1 -1
- package/dist/packem_chunks/handler.mjs +1 -1
- package/dist/packem_chunks/handler10.mjs +1 -1
- package/dist/packem_chunks/handler11.mjs +1 -1
- 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 +1 -1
- package/dist/packem_chunks/handler16.mjs +1 -1
- package/dist/packem_chunks/handler17.mjs +1 -1
- package/dist/packem_chunks/handler18.mjs +1 -1
- package/dist/packem_chunks/handler19.mjs +3 -3
- package/dist/packem_chunks/handler2.mjs +1 -1
- package/dist/packem_chunks/handler20.mjs +1 -1
- package/dist/packem_chunks/handler21.mjs +1 -1
- package/dist/packem_chunks/handler22.mjs +1 -1
- package/dist/packem_chunks/handler23.mjs +1 -1
- package/dist/packem_chunks/handler24.mjs +1 -1
- package/dist/packem_chunks/handler25.mjs +1 -1
- package/dist/packem_chunks/handler26.mjs +1 -1
- package/dist/packem_chunks/handler3.mjs +1 -1
- package/dist/packem_chunks/handler4.mjs +1 -1
- package/dist/packem_chunks/handler5.mjs +1 -1
- package/dist/packem_chunks/handler6.mjs +1 -1
- package/dist/packem_chunks/handler7.mjs +1 -1
- package/dist/packem_chunks/handler8.mjs +1 -1
- package/dist/packem_chunks/handler9.mjs +1 -1
- package/dist/packem_chunks/planDevCommand.mjs +1 -1
- package/dist/packem_chunks/runCodegenCommand.mjs +1 -1
- package/dist/packem_chunks/runDeployCommand.mjs +2 -2
- package/dist/packem_chunks/runInitCommand.mjs +1 -1
- package/dist/packem_chunks/runMigrateGenerateCommand.mjs +1 -1
- package/dist/packem_chunks/runResetCommand.mjs +1 -1
- package/dist/packem_chunks/runRpcCommand.mjs +1 -1
- package/dist/packem_shared/COMMANDS-B6hj4Jv-.mjs +1 -0
- package/dist/packem_shared/cli-D87Rz8eI.mjs +3 -0
- package/dist/packem_shared/{command-DwC11Cwe.mjs → command-CrAs0XG_.mjs} +1 -1
- package/dist/packem_shared/createLogger-Cl18I8AX.mjs +2 -0
- package/dist/packem_shared/deploy-target-DCWwiuAe.mjs +1 -0
- package/dist/packem_shared/output-format-B91O3X28.mjs +2 -0
- package/package.json +9 -9
- package/dist/packem_shared/COMMANDS-rRB9TbDL.mjs +0 -1
- package/dist/packem_shared/cli-DIb5Ay4K.mjs +0 -3
- package/dist/packem_shared/createLogger-hGafwf-3.mjs +0 -2
- package/dist/packem_shared/deploy-target-B0Xcb2jV.mjs +0 -1
- package/dist/packem_shared/output-format-DfogXx0p.mjs +0 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync as p,readFileSync as v,realpathSync as h}from"node:fs";import{join as u}from"node:path";import{isPlaceholderValue as w,DEV_VARS_FILE as g,parseDevVariableEntries as k,discoverSchemaInfo as x,inferLunoraBindings as b}from"@lunora/config";import{findWranglerFile as y,readWranglerJsonc as $,validateWranglerConfig as _,collectExportGaps as R}from"@lunora/config/cloudflare";import{i as S,m as N,c as L}from"../packem_shared/vectorize-metadata-dXpl2_Ar.mjs";import{r as A,d as I}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{d as E}from"../packem_shared/command-DwC11Cwe.mjs";import{v as O,i as j,p as D,l as V}from"../packem_shared/output-format-DfogXx0p.mjs";import{i as C}from"../packem_shared/path-containment-CgxYZggb.mjs";const F=o=>{const e=o.trim();if(e==="")return!0;const n=e.toLowerCase();return n.includes("replace")||n.startsWith("<")&&n.endsWith(">")},P=o=>{const e=y(o);if(e===void 0)return{parsed:void 0,path:void 0};const{parsed:n}=$(e);return{parsed:n,path:e}},U=(o,e,n)=>{if(e===void 0){n.push({code:"wrangler-missing",fix:"Run `lunora init` (or `lunora dev`) to scaffold and reconcile wrangler.jsonc.",level:"fail",message:"wrangler.jsonc not found."});return}if(o===void 0){n.push({code:"wrangler-unparseable",fix:`Check ${e} is valid JSONC.`,level:"fail",message:`Could not parse ${e}.`});return}const a=_(o);for(const r of a.warnings.filter(i=>i.includes("LUNORA_ORIGIN_URL")))n.push({code:"scheduler-origin-missing",fix:"Set LUNORA_ORIGIN_URL in wrangler vars to the worker's public URL (or `wrangler secret put LUNORA_ORIGIN_URL`).",level:"warn",message:r});const s=a.errors.find(r=>r.includes("SHARD"));s===void 0?n.push({code:"wrangler-shard-binding-ok",level:"pass",message:"wrangler.jsonc present with a SHARD durable-object binding."}):n.push({code:"wrangler-shard-binding-missing",fix:"Run `lunora dev` to auto-reconcile, or add the binding manually.",level:"fail",message:s})},M=(o,e)=>{const{error:n,info:a}=x(o,"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 s of a?.vectorMetadata??[]){const r=N(s.kind);if(r===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 "${s.index}" declares metadata "${s.property}", whose type Vectorize cannot filter on.`});continue}e.push({code:"vector-metadata-index-required",fix:`wrangler ${L({index:s.index,property:s.property,type:r}).join(" ")}`,level:"info",message:`vector index "${s.index}" filters on metadata "${s.property}" — that needs a Vectorize metadata index (\`lunora deploy\` creates it).`})}},W=(o,e)=>{if(o===void 0)return;const n=(o.d1_databases??[]).filter(Boolean);for(const a of n){const s=typeof a.database_id=="string"?a.database_id:"";if(F(s)){const r=typeof a.binding=="string"&&a.binding.length>0?a.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 "${r}" has a placeholder database_id ("${s||"<empty>"}").`})}}},T=(o,e)=>{if(o===void 0)return;const n=(o.send_email??[]).filter(Boolean);for(const a of n){const s=typeof a.destination_address=="string"?a.destination_address:"";if(s!==""&&w(s)){const r=typeof a.name=="string"&&a.name.length>0?a.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 "${r}" has a placeholder destination_address ("${s}").`})}}},z=(o,e)=>{const n=u(o,g);if(!p(n))return;let a;try{a=v(n,"utf8")}catch{return}const s=k(a).filter(r=>S(r.key)&&w(r.value)).map(r=>r.key);s.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:`${g} has unfilled secret value(s): ${s.join(", ")}.`})},G=(o,e)=>{const{source:n}=A({cwd:o});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 (${I(n)}).`})},B=async(o,e)=>{let n;try{n=await b({projectRoot:o})}catch(r){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: ${r instanceof Error?r.message:String(r)}`});return}const a=R(n),s=[...n.containers.map(r=>({...r,kind:"container"})),...n.workflows.map(r=>({...r,kind:"workflow"})),...n.agents.map(r=>({...r,kind:"agent"}))];for(const r of s.filter(i=>i.exported))e.push({code:"declared-export-ok",level:"pass",message:`${r.kind} "${r.exportName}" is exported by the worker entry.`});for(const r of a)e.push({code:"declared-export-missing",fix:`Add \`export * from "./lunora/_generated/${r.module}"\` to your worker entry (or re-run \`vis generate lunora-${r.kind}\`).`,level:"fail",message:`${r.kind} "${r.exportName}" is declared but ${r.className} is not exported by the worker entry.`})},J=/^[\^~><= ]+/u,K=/^(?<core>\d+\.\d+\.\d+)(?:-(?<channel>[a-z]+)\.(?<counter>\d+))?$/u,H=o=>{const e=o.replace(J,"").trim(),n=K.exec(e);if(!n?.groups)return;const{channel:a,core:s,counter:r}=n.groups;return{channel:a??"",core:s??"",counter:r===void 0?void 0:Number.parseInt(r,10),raw:e}},q=(o,e)=>{const n=u(o,"package.json");if(!p(n))return;let a;try{a=JSON.parse(v(n,"utf8"))}catch{return}const s={...a.devDependencies,...a.dependencies},r=[];for(const[t,c]of Object.entries(s)){if(t!=="lunorash"&&!t.startsWith("@lunora/"))continue;const m=H(c);m&&r.push({name:t,version:m})}if(r.length<2)return;const i=t=>t.map(c=>`${c.name}@${c.version.raw}`).join(", "),l=new Set(r.map(t=>t.version.core)),f=new Set(r.map(t=>t.version.channel));if(l.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(l.size)} different versions: ${i(r)}.`});return}if(f.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 (${[...f].map(t=>t===""?"stable":t).join(" + ")}): ${i(r)}.`});return}const d=r.map(t=>t.version.counter).filter(t=>t!==void 0);if(d.length>1){const t=Math.min(...d),c=Math.max(...d);e.push({code:"version-counter-spread",level:"info",message:d.length===r.length&&t===c?`Lunora packages are all at ${[...f][0]??""}.${String(c)}.`:`Lunora pre-release counters span ${String(t)}–${String(c)}: ${i(r)}.`})}},X=[u("@lunora","cli"),"lunorash"],Q=(o,e,n)=>{if(e===void 0)return;const a=[];for(const r of X){const i=u(o,"node_modules",r);if(p(i))try{a.push(h(i))}catch{}}if(a.length===0)return;let s;try{s=h(e)}catch{return}a.some(r=>C(r,s))||n.push({code:"cli-shadowed",fix:"Run the project's own CLI: `pnpm exec lunora …` (or `npx lunora …`).",level:"warn",message:`the running lunora (${s}) is not the project's own install (${a.join(", ")}).`})},Y=async o=>{const e=o.cwd??process.cwd(),n=[],{parsed:a,path:s}=P(e);U(a,s,n),W(a,n),T(a,n),z(e,n),G(e,n),q(e,n),M(e,n),Q(e,o.executablePath??process.argv[1],n),await B(e,n);const r={fail:0,info:0,pass:0,warn:0};for(const l of n)r[l.level]+=1;const i=r.fail>0?1:0;return{code:i,findings:n,ok:i===0,summary:r}},Z={fail:"FAIL",info:"INFO",pass:"PASS",warn:"WARN"},ee=(o,e)=>{e.info("lunora doctor — project preflight");for(const s of o.findings){const r=`[${Z[s.level]}] ${s.message}`;s.level==="fail"?e.error(r):s.level==="warn"?e.warn(r):e.info(r),s.fix!==void 0&&s.level!=="pass"&&e.info(` fix: ${s.fix}`)}const{fail:n,warn:a}=o.summary;n>0?e.error(`${String(n)} failure(s), ${String(a)} warning(s).`):a>0?e.warn(`0 failures, ${String(a)} warning(s).`):e.success("all checks passed.")},re=async o=>{const e=O("doctor",o.format);if(e!==void 0)return o.logger.error(e),{code:1,findings:[],ok:!1,summary:{fail:0,info:0,pass:0,warn:0}};const n=V(o.format,o.logger),a=await Y({...o});return ee(a,n),j(o.format)&&D(a),a},ue=E(async({cwd:o,logger:e,options:n})=>({code:(await re({cwd:o,format:n.format,logger:e})).code}));export{ue as execute,Y as runDoctor,re as runDoctorCommand};
|
|
1
|
+
import{existsSync as p,readFileSync as w,realpathSync as h}from"node:fs";import{join as u}from"node:path";import{isPlaceholderValue as k,DEV_VARS_FILE as g,parseDevVariableEntries as b,discoverSchemaInfo as x,inferLunoraBindings as y}from"@lunora/config";import{findWranglerFile as _,readWranglerJsonc as $,validateWranglerProject as R,UNEXPORTED_CLASS_MARKER as v,collectExportGaps as S}from"@lunora/config/cloudflare";import{i as L,m as N,c as A}from"../packem_shared/vectorize-metadata-dXpl2_Ar.mjs";import{r as j,d as I}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{d as E}from"../packem_shared/command-CrAs0XG_.mjs";import{v as O,l as D,i as C,p as P}from"../packem_shared/output-format-B91O3X28.mjs";import{i as U}from"../packem_shared/path-containment-CgxYZggb.mjs";const F=a=>{const e=a.trim();if(e==="")return!0;const r=e.toLowerCase();return r.includes("replace")||r.startsWith("<")&&r.endsWith(">")},V=a=>{const e=_(a);if(e===void 0)return{parsed:void 0,path:void 0};const{parsed:r}=$(e);return{parsed:r,path:e}},M=(a,e,r,n)=>{if(r===void 0){n.push({code:"wrangler-missing",fix:"Run `lunora init` (or `lunora dev`) to scaffold and reconcile wrangler.jsonc.",level:"fail",message:"wrangler.jsonc not found."});return}if(e===void 0){n.push({code:"wrangler-unparseable",fix:`Check ${r} is valid JSONC.`,level:"fail",message:`Could not parse ${r}.`});return}const{report:t}=R({projectRoot:a});for(const i of t.errors.filter(l=>l.includes(v)))n.push({code:"wrangler-class-unexported",level:"fail",message:i});for(const i of t.warnings.filter(l=>l.includes("LUNORA_ORIGIN_URL")))n.push({code:"scheduler-origin-missing",fix:"Set LUNORA_ORIGIN_URL in wrangler vars to the worker's public URL (or `wrangler secret put LUNORA_ORIGIN_URL`).",level:"warn",message:i});const o=i=>i.includes(v)||i.includes("SHARD");for(const i of t.errors.filter(l=>!o(l)))n.push({code:"wrangler-invalid",fix:"Fix the reported wrangler.jsonc problem; `lunora verify` reports the same set.",level:"fail",message:i});for(const i of t.warnings.filter(l=>!l.includes("LUNORA_ORIGIN_URL")))n.push({code:"wrangler-advisory",level:"warn",message:i});const c=t.errors.find(i=>i.includes("SHARD"));c===void 0?n.push({code:"wrangler-shard-binding-ok",level:"pass",message:"wrangler.jsonc present with a SHARD durable-object binding."}):n.push({code:"wrangler-shard-binding-missing",fix:"Run `lunora dev` to auto-reconcile, or add the binding manually.",level:"fail",message:c})},T=(a,e)=>{p(u(a,"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."})},W=(a,e)=>{a===void 0||a.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."})},G=(a,e)=>{const r=(a?.r2_buckets??[]).map(n=>n?.bucket_name).filter(n=>typeof n=="string"&&n.length>0);r.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) ${r.join(", ")}: verify a lifecycle rule aborts incomplete multipart uploads — orphaned parts are billed but invisible in a listing.`})},z=(a,e)=>{const{error:r,info:n}=x(a,"lunora");if(r!==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: ${r}`});return}for(const t of n?.vectorMetadata??[]){const o=N(t.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 "${t.index}" declares metadata "${t.property}", whose type Vectorize cannot filter on.`});continue}e.push({code:"vector-metadata-index-required",fix:`wrangler ${A({index:t.index,property:t.property,type:o}).join(" ")}`,level:"info",message:`vector index "${t.index}" filters on metadata "${t.property}" — that needs a Vectorize metadata index (\`lunora deploy\` creates it).`})}},K=(a,e)=>{if(a===void 0)return;const r=(a.d1_databases??[]).filter(Boolean);for(const n of r){const t=typeof n.database_id=="string"?n.database_id:"";if(F(t)){const o=typeof n.binding=="string"&&n.binding.length>0?n.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 ("${t||"<empty>"}").`})}}},B=(a,e)=>{if(a===void 0)return;const r=(a.send_email??[]).filter(Boolean);for(const n of r){const t=typeof n.destination_address=="string"?n.destination_address:"";if(t!==""&&k(t)){const o=typeof n.name=="string"&&n.name.length>0?n.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 ("${t}").`})}}},J=(a,e)=>{const r=u(a,g);if(!p(r))return;let n;try{n=w(r,"utf8")}catch{return}const t=b(n).filter(o=>L(o.key)&&k(o.value)).map(o=>o.key);t.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:`${g} has unfilled secret value(s): ${t.join(", ")}.`})},H=(a,e)=>{const{source:r}=j({cwd:a});r===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 (${I(r)}).`})},q=async(a,e)=>{let r;try{r=await y({projectRoot:a})}catch(o){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: ${o instanceof Error?o.message:String(o)}`});return}const n=S(r),t=[...r.containers.map(o=>({...o,kind:"container"})),...r.workflows.map(o=>({...o,kind:"workflow"})),...r.agents.map(o=>({...o,kind:"agent"}))];for(const o of t.filter(c=>c.exported))e.push({code:"declared-export-ok",level:"pass",message:`${o.kind} "${o.exportName}" is exported by the worker entry.`});for(const o of n)e.push({code:"declared-export-missing",fix:`Add \`export * from "./lunora/_generated/${o.module}"\` to your worker entry (or re-run \`vis generate lunora-${o.kind}\`).`,level:"fail",message:`${o.kind} "${o.exportName}" is declared but ${o.className} is not exported by the worker entry.`})},X=/^[\^~><= ]+/u,Q=/^(?<core>\d+\.\d+\.\d+)(?:-(?<channel>[a-z]+)\.(?<counter>\d+))?$/u,Y=a=>{const e=a.replace(X,"").trim(),r=Q.exec(e);if(!r?.groups)return;const{channel:n,core:t,counter:o}=r.groups;return{channel:n??"",core:t??"",counter:o===void 0?void 0:Number.parseInt(o,10),raw:e}},Z=(a,e)=>{const r=u(a,"package.json");if(!p(r))return;let n;try{n=JSON.parse(w(r,"utf8"))}catch{return}const t={...n.devDependencies,...n.dependencies},o=[];for(const[s,d]of Object.entries(t)){if(s!=="lunorash"&&!s.startsWith("@lunora/"))continue;const m=Y(d);m&&o.push({name:s,version:m})}if(o.length<2)return;const c=s=>s.map(d=>`${d.name}@${d.version.raw}`).join(", "),i=new Set(o.map(s=>s.version.core)),l=new Set(o.map(s=>s.version.channel));if(i.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(i.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(s=>s===""?"stable":s).join(" + ")}): ${c(o)}.`});return}const f=o.map(s=>s.version.counter).filter(s=>s!==void 0);if(f.length>1){const s=Math.min(...f),d=Math.max(...f);e.push({code:"version-counter-spread",level:"info",message:f.length===o.length&&s===d?`Lunora packages are all at ${[...l][0]??""}.${String(d)}.`:`Lunora pre-release counters span ${String(s)}–${String(d)}: ${c(o)}.`})}},ee=[u("@lunora","cli"),"lunorash"],re=(a,e,r)=>{if(e===void 0)return;const n=[];for(const o of ee){const c=u(a,"node_modules",o);if(p(c))try{n.push(h(c))}catch{}}if(n.length===0)return;let t;try{t=h(e)}catch{return}n.some(o=>U(o,t))||r.push({code:"cli-shadowed",fix:"Run the project's own CLI: `pnpm exec lunora …` (or `npx lunora …`).",level:"warn",message:`the running lunora (${t}) is not the project's own install (${n.join(", ")}).`})},ne=async a=>{const e=a.cwd??process.cwd(),r=[],{parsed:n,path:t}=V(e);M(e,n,t,r),K(n,r),B(n,r),W(n,r),G(n,r),J(e,r),H(e,r),Z(e,r),z(e,r),T(e,r),re(e,a.executablePath??process.argv[1],r),await q(e,r);const o={fail:0,info:0,pass:0,warn:0};for(const i of r)o[i.level]+=1;const c=o.fail>0?1:0;return{code:c,findings:r,ok:c===0,summary:o}},oe={fail:"FAIL",info:"INFO",pass:"PASS",warn:"WARN"},ae=(a,e)=>{e.info("lunora doctor — project preflight");for(const t of a.findings){const o=`[${oe[t.level]}] ${t.message}`;t.level==="fail"?e.error(o):t.level==="warn"?e.warn(o):e.info(o),t.fix!==void 0&&t.level!=="pass"&&e.info(` fix: ${t.fix}`)}const{fail:r,warn:n}=a.summary;r>0?e.error(`${String(r)} failure(s), ${String(n)} warning(s).`):n>0?e.warn(`0 failures, ${String(n)} warning(s).`):e.success("all checks passed.")},te=async a=>{const e=O("doctor",a.format);if(e!==void 0)return a.logger.error(e),{code:1,findings:[],ok:!1,summary:{fail:0,info:0,pass:0,warn:0}};const r=D(a.format,a.logger),n=await ne({...a});return ae(n,r),C(a.format)&&P(n),n},he=E(async({cwd:a,logger:e,options:r})=>({code:(await te({cwd:a,format:r.format,logger:e})).code}));export{he as execute,ne as runDoctor,te as runDoctorCommand};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{existsSync as h,readFileSync as V}from"node:fs";import{join as P}from"node:path";import{DEV_VARS_FILE as u,DEV_VARS_KEY_PATTERN as k,writeDevVariablesFileAtomically as $,removeDevVariableLine as K,upsertDevVariableLine as A,isPlaceholderValue as w,detectPackageManager as N,resolveDeployDriver as U,resolveProjectTarget as z,execArgsFor as j,generateSecretValue as M,DEV_VARS_EXAMPLE_FILE as p,parseDevVariableEntries as L,packageNamesFromBindings as Y,inferLunoraBindings as x,requiredSecrets as C,isMintableSecretKey as S}from"@lunora/config";import{d as q}from"../packem_shared/command-
|
|
1
|
+
import{existsSync as h,readFileSync as V}from"node:fs";import{join as P}from"node:path";import{DEV_VARS_FILE as u,DEV_VARS_KEY_PATTERN as k,writeDevVariablesFileAtomically as $,removeDevVariableLine as K,upsertDevVariableLine as A,isPlaceholderValue as w,detectPackageManager as N,resolveDeployDriver as U,resolveProjectTarget as z,execArgsFor as j,generateSecretValue as M,DEV_VARS_EXAMPLE_FILE as p,parseDevVariableEntries as L,packageNamesFromBindings as Y,inferLunoraBindings as x,requiredSecrets as C,isMintableSecretKey as S}from"@lunora/config";import{d as q}from"../packem_shared/command-CrAs0XG_.mjs";import{defaultSpawner as F}from"../packem_shared/createRecordingSpawner-DJlNacZ6.mjs";import{l as T}from"../packem_shared/wrangler-secrets-CCdt0mUl.mjs";const Z=/[\r\n]/u,B=/["\\]/u,_=r=>new Map(L(r).map(o=>[o.key,o])),y=r=>h(r)?V(r,"utf8"):"",R=r=>r.length<=4?"****":`${r.slice(0,4)}${"*".repeat(Math.min(8,r.length-4))}`,f=r=>_(y(r)),D=r=>r.env??(r.prod===!0?"production":void 0),G=r=>{const o=f(r.devVariablesPath);if(o.size===0)return r.logger.info(`${u}: (empty)`),{code:0,descriptors:[]};for(const t of o.values())r.logger.info(`${t.key}=${R(t.value)}`);return{code:0,descriptors:[]}},I=r=>{const{devVariablesPath:o,logger:t,options:e}=r;if(!e.key)return t.error("env get requires a key. Usage: lunora env get <KEY>"),{code:1,descriptors:[]};const s=f(o).get(e.key);return s?(process.stdout.write(`${s.value}
|
|
2
2
|
`),{code:0,descriptors:[]}):(t.error(`env: ${e.key} is not set in ${u}`),{code:1,descriptors:[]})},O=r=>{const{devVariablesPath:o,logger:t,options:e}=r;if(!e.key)return t.error("env set requires a key. Usage: lunora env set <KEY> <VALUE>"),{code:1,descriptors:[]};if(!k.test(e.key))return t.error(`env: invalid key "${e.key}" — must match [A-Za-z_][A-Za-z0-9_]*`),{code:1,descriptors:[]};if(e.value===void 0)return t.error("env set requires a value. Usage: lunora env set <KEY> <VALUE>"),{code:1,descriptors:[]};if(Z.test(e.value))return t.error(`env: value for "${e.key}" contains a newline, which .dev.vars cannot represent`),{code:1,descriptors:[]};if(B.test(e.value))return t.error(`env: value for "${e.key}" contains a double-quote or backslash, which .dev.vars cannot round-trip`),{code:1,descriptors:[]};const s=y(o);return $(o,A(s,e.key,e.value)),t.success(`env: set ${e.key} (${R(e.value)}) in ${u}`),{code:0,descriptors:[]}},H=r=>{const{devVariablesPath:o,logger:t,options:e}=r;if(!e.key)return t.error("env unset requires a key. Usage: lunora env unset <KEY>"),{code:1,descriptors:[]};if(!k.test(e.key))return t.error(`env: invalid key "${e.key}" — must match [A-Za-z_][A-Za-z0-9_]*`),{code:1,descriptors:[]};const s=y(o);return _(s).has(e.key)?($(o,K(s,e.key)),t.success(`env: unset ${e.key} in ${u}`),{code:0,descriptors:[]}):(t.warn(`env: ${e.key} was not set in ${u}`),{code:0,descriptors:[]})},W=async r=>{const{devVariablesPath:o,logger:t,options:e}=r;if(!e.yes)return t.error("env push uploads secrets to Cloudflare. Re-run with --yes to confirm."),{code:1,descriptors:[]};const s=f(o);if(s.size===0)return t.warn(`${u}: nothing to push (empty)`),{code:0,descriptors:[]};const n=[...s.values()].filter(a=>w(a.value)).map(a=>a.key);if(n.length>0)return t.error(`env push: refusing to upload placeholder value(s) for ${n.join(", ")} — run \`lunora env doctor\` to review, and \`lunora env generate --set\` (or \`lunora env set <KEY> <VALUE>\`) to fill them, then re-run.`),{code:1,descriptors:[]};const i=e.spawner??F,l=e.cwd??process.cwd(),d=N(l),c=[],v=D(e);for(const a of s.values()){const m=U(z(l)).toolchain?.secretPut({environment:v,key:a.key,temporary:e.temporary});if(m===void 0)return t.error("deploy target has no command-line toolchain; cannot push secrets"),{code:1,descriptors:[]};const E=j(d,m.tool,m.args),b={args:E.args,command:E.command,cwd:l,input:a.value};c.push(b),t.info(`pushing ${a.key} -> wrangler secret${v===void 0?"":` (${v})`}`);const g=await i(b);if(g.code!==0)return t.error(`env push: failed at ${a.key} (exit ${String(g.code)})`),{code:g.code,descriptors:c}}return t.success(`env: pushed ${String(s.size)} secret(s)`),{code:0,descriptors:c}},X=r=>(r.options.secretLister??T)({cwd:r.cwd,env:D(r.options),temporary:r.options.temporary}),J=async r=>{const{devVariablesPath:o,logger:t}=r,e=await X(r);if(!e.ok)return t.error(`env diff: ${e.error??"failed to list remote secrets"}`),{code:1,descriptors:[]};const s=new Set(f(o).keys()),n=new Set(e.names),i=[...s].filter(c=>!n.has(c)).toSorted((c,v)=>c.localeCompare(v)),l=e.names.filter(c=>!s.has(c)),d=[...s].filter(c=>n.has(c)).toSorted((c,v)=>c.localeCompare(v));for(const c of i)t.info(`local only (run \`lunora env push\`): ${c}`);for(const c of l)t.info(`remote only (in Cloudflare, not ${u}): ${c}`);return t.info(`in both: ${String(d.length)} secret(s)`),i.length===0&&l.length===0&&t.success("env diff: local and remote secret names match"),{code:0,descriptors:[]}},Q=r=>{const{cwd:o,devVariablesPath:t,logger:e}=r,s=P(o,p);if(!h(s))return e.info(`env doctor: no ${p} to check against — nothing to validate.`),{code:0,descriptors:[]};const n=L(V(s,"utf8")).map(a=>a.key),i=f(t);if(!h(t))return e.error(`env doctor: ${u} is missing. Run \`lunora dev\` to scaffold it, or \`lunora env set <KEY> <VALUE>\`.`),e.info(`expected (from ${p}): ${n.join(", ")}`),{code:1,descriptors:[]};const l=n.filter(a=>!i.has(a)),d=[...i.values()].filter(a=>w(a.value)).map(a=>a.key),c=new Set(n),v=[...i.keys()].filter(a=>!c.has(a));for(const a of l)e.error(`missing: ${a} is in ${p} but not ${u}`);for(const a of d)e.error(`unset: ${a} still has a placeholder value`);for(const a of v)e.info(`extra: ${a} is set locally but not listed in ${p}`);return l.length===0&&d.length===0?(e.success(`env doctor: ${u} looks good (${String(i.size)} var(s)).`),{code:0,descriptors:[]}):{code:1,descriptors:[]}},ee=async r=>{let o=[];try{o=Y(await x({projectRoot:r.cwd}))}catch{}const t=C(o).map(s=>s.key).filter(s=>S(s)),e=[...f(r.devVariablesPath).keys()].filter(s=>S(s));return[...new Set([...t,...e])]},re=(r,o,t)=>{const e=f(r),s=n=>{const i=e.get(n);return i!==void 0&&i.value!==""&&!w(i.value)};return{live:o.filter(n=>s(n.key)).map(n=>n.key),writable:t?o:o.filter(n=>!s(n.key))}},te=(r,o)=>{const{devVariablesPath:t,logger:e,options:s}=r,{live:n,writable:i}=re(t,o,s.yes===!0);if(i.length===0)return e.error(`env generate --set: ${n.join(", ")} already hold(s) a live secret and rotating it is irreversible (outstanding signed URLs and bearers stop verifying). Re-run with --yes to rotate anyway.`),{code:1,descriptors:[]};n.length>0&&e.warn(`env generate --set: left ${n.join(", ")} untouched (already set) — re-run with --yes to rotate them too`);let l=y(t);for(const d of i)l=A(l,d.key,d.value);return $(t,l),e.success(`env: generated ${String(i.length)} secret(s) into ${u}: ${i.map(d=>d.key).join(", ")}`),{code:0,descriptors:[]}},oe=async r=>{const{logger:o,options:t}=r;let e;if(t.key===void 0){if(e=await ee(r),e.length===0)return o.info("env generate: no locally-generatable secrets for this project. Name one explicitly: lunora env generate <KEY>"),{code:0,descriptors:[]}}else{if(!k.test(t.key))return o.error(`env: invalid key "${t.key}" — must match [A-Za-z_][A-Za-z0-9_]*`),{code:1,descriptors:[]};e=[t.key]}const s=e.map(n=>({key:n,value:M()}));if(t.set===!0)return te(r,s);for(const n of s)process.stdout.write(`${n.key}=${n.value}
|
|
3
3
|
`);return{code:0,descriptors:[]}},se=async r=>{const o=r.cwd??process.cwd(),t={cwd:o,devVariablesPath:P(o,u),logger:r.logger,options:r};switch(r.subcommand){case"diff":return J(t);case"doctor":return Q(t);case"generate":return oe(t);case"get":return I(t);case"list":return G(t);case"push":return W(t);case"set":return O(t);case"unset":return H(t);default:return r.logger.error(`env: unknown subcommand "${r.subcommand}"`),{code:1,descriptors:[]}}},ne=new Set(["diff","doctor","generate","get","list","push","set","unset"]),ae=r=>typeof r=="string"&&ne.has(r),fe=q(({argument:r,cwd:o,logger:t,options:e})=>{const s=r[0];return ae(s)?se({cwd:o,env:e.env,key:r[1],logger:t,prod:e.prod===!0,set:e.set===!0,subcommand:s,temporary:e.temporary===!0,value:r[2],yes:e.yes===!0}):(t.error(`env: unknown subcommand "${s??""}" — expected list | get | set | unset | push | diff | doctor | generate`),{code:1})});export{fe as execute,se as runEnvCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d as u}from"../packem_shared/command-
|
|
1
|
+
import{d as u}from"../packem_shared/command-CrAs0XG_.mjs";import{r as d}from"../packem_shared/resolve-target-BRvw8Pf7.mjs";import{runExportCommand as l}from"../packem_shared/runExportCommand-Dq-SpjAe.mjs";const p=u(({argument:o,cwd:e,logger:t,options:r})=>l({cwd:e,logger:t,out:o[0]??r.out,prod:r.prod===!0,tables:r.tables,token:r.token,url:d({cwd:e,prod:r.prod===!0,url:r.url})}));export{p as execute};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d as o}from"../packem_shared/command-
|
|
1
|
+
import{d as o}from"../packem_shared/command-CrAs0XG_.mjs";import{r as f}from"../packem_shared/resolve-target-BRvw8Pf7.mjs";import{I as u,r as d}from"../packem_shared/import-Dqd1MOOv.mjs";const n=o(({argument:m,cwd:a,logger:e,options:r})=>{const t=m[0];return t?r.from!==void 0&&!u.includes(r.from)?(e.error(`--from ${r.from} is not a known source. Expected one of: ${u.join(", ")}.`),{code:1}):d({batchSize:r.batchSize,cwd:a,file:t,from:r.from,logger:e,prod:r.prod===!0,scan:r.scan===!0,storageDir:r.storageDir,table:r.table,token:r.token,url:f({cwd:a,prod:r.prod===!0,url:r.url}),verify:r.verify===!0,withStorage:r.withStorage===!0,yes:r.yes===!0}):(e.error("import requires a path. Usage: lunora import <file.ndjson | convex-export-dir> [--table <name>]"),{code:1})});export{n as execute};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{spawnSync as $,spawn as re}from"node:child_process";import{existsSync as N,watch as Te,readFileSync as C,mkdirSync as Re,openSync as te,closeSync as ne,statSync as _e,readSync as Le}from"node:fs";import{join as k,dirname as Ie}from"node:path";import{runCodegen as oe}from"@lunora/codegen";import{runPostCodegenHook as Oe,detectAgentRules as ie,updateDevServerState as M,readDevServerState as O,claimDevServerState as ae,DEV_HANDOFF_ENV as R,clearDevServerState as y,readLiveDevServerState as D,isDevServerReady as G,detectFramework as se,readProjectDependencyNames as De,DEV_LOG_FILE_ENV as ce,DEV_DAEMON_ENV as x,detectPackageManager as de,execArgsFor as A,isRecordedProcessCurrent as Pe,DEV_LOG_FILE as Ae,CODEGEN_ENV as le,isCodegenDisabled as $e,detectAiAgent as Ne,readProjectRemotePreference as Ce,inferLunoraBindings as Me,packageNamesFromBindings as xe,ensureDevVarsExample as Fe,ensureDevVariables as je,isInteractive as Ge,DEV_VARS_FILE as _,DEV_VARS_EXAMPLE_FILE as Ue,fillDevSecrets as Ve,DEV_BINDINGS_FILE as We,DEV_STATE_FILE as ue,claimAgentRulesHint as He,AGENT_RULES_HINT as Be,resolveDeployDriver as Ke,resolveProjectTarget as Ye,runScriptCommand as Je,discoverContainerInfo as Xe,streamContainerLogs as ze,parseDevVariableEntries as Qe,formatLunoraEvent as Ze}from"@lunora/config";import{resolveRemoteEnabled as qe,findWranglerFile as fe,readWranglerJsonc as ge,materializeRemoteWranglerConfig as er}from"@lunora/config/cloudflare";import{p as rr,a as tr}from"../packem_shared/deploy-target-
|
|
1
|
+
import{spawnSync as $,spawn as re}from"node:child_process";import{existsSync as N,watch as Te,readFileSync as C,mkdirSync as Re,openSync as te,closeSync as ne,statSync as _e,readSync as Le}from"node:fs";import{join as k,dirname as Ie}from"node:path";import{runCodegen as oe}from"@lunora/codegen";import{runPostCodegenHook as Oe,detectAgentRules as ie,updateDevServerState as M,readDevServerState as O,claimDevServerState as ae,DEV_HANDOFF_ENV as R,clearDevServerState as y,readLiveDevServerState as D,isDevServerReady as G,detectFramework as se,readProjectDependencyNames as De,DEV_LOG_FILE_ENV as ce,DEV_DAEMON_ENV as x,detectPackageManager as de,execArgsFor as A,isRecordedProcessCurrent as Pe,DEV_LOG_FILE as Ae,CODEGEN_ENV as le,isCodegenDisabled as $e,detectAiAgent as Ne,readProjectRemotePreference as Ce,inferLunoraBindings as Me,packageNamesFromBindings as xe,ensureDevVarsExample as Fe,ensureDevVariables as je,isInteractive as Ge,DEV_VARS_FILE as _,DEV_VARS_EXAMPLE_FILE as Ue,fillDevSecrets as Ve,DEV_BINDINGS_FILE as We,DEV_STATE_FILE as ue,claimAgentRulesHint as He,AGENT_RULES_HINT as Be,resolveDeployDriver as Ke,resolveProjectTarget as Ye,runScriptCommand as Je,discoverContainerInfo as Xe,streamContainerLogs as ze,parseDevVariableEntries as Qe,formatLunoraEvent as Ze}from"@lunora/config";import{resolveRemoteEnabled as qe,findWranglerFile as fe,readWranglerJsonc as ge,materializeRemoteWranglerConfig as er}from"@lunora/config/cloudflare";import{p as rr,a as tr}from"../packem_shared/deploy-target-DCWwiuAe.mjs";import{w as nr}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{a as or}from"../packem_shared/codegen-error-AmH54ofi.mjs";import{a as ir}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{d as ar}from"../packem_shared/command-CrAs0XG_.mjs";import{createServer as sr,connect as cr}from"node:net";import{forceJsonLogging as dr}from"../packem_shared/createLogger-Cl18I8AX.mjs";import{networkInterfaces as lr}from"node:os";import{spawnShellCompat as ve}from"../packem_shared/createRecordingSpawner-DJlNacZ6.mjs";import{createServer as ur,request as fr}from"node:http";import{pipeline as gr}from"node:stream";import{loadStudioAssets as U,studioAssetsStamp as V,renderStudioHtml as vr,resolveAdminToken as mr,transportRejectionReason as W,SCHEMA_EDIT_ENDPOINT as pr,POLICY_SCAFFOLD_ENDPOINT as wr,SEED_ENDPOINT as hr,sendStudioDocument as Sr,serveJsonHandler as yr,isStandaloneModulePath as Er,readStandaloneAsset as kr,assetContentType as br,handleSchemaEditRequest as Tr,handlePolicyScaffoldRequest as Rr,handleSeedRequest as _r,applyStudioAssetCache as Lr}from"@lunora/config/studio-host";import{c as Ir}from"../packem_shared/tui-prompts-DzYd2fL3.mjs";import{setTimeout as L}from"node:timers/promises";import{provisionBindings as Or}from"./runDeployCommand.mjs";import{p as E}from"../packem_shared/output-format-B91O3X28.mjs";const Dr=100,Pr=300,Ar=/[/\\]/u,$r=(e,r,n)=>{const{apiSpec:t,logger:o,projectRoot:i,target:a}=e;try{const s=oe({apiSpec:t,lunoraDirectory:r,projectRoot:i,target:a});o.success(`codegen: wrote ${r}/_generated (${n})`),ir(s.platformDiagnostics,o)}catch(s){return o.error(or(s,n)),!1}return!0},Nr=e=>{const r=e.lunoraDirectory??"lunora",n=k(e.projectRoot,r),t=e.debounceMs??Dr;let o=!1,i=!1,a=!1,s,d=0,u=Promise.resolve(),g;const m=new Promise(v=>{g=v}),p=v=>{o||(s=v,!i&&(i=!0,u=(async()=>{try{for(;s!==void 0;){const h=s;if(s=void 0,!!$r(e,r,h)){a=!0;try{(await Oe({cwd:e.projectRoot,logger:e.logger,spawner:e.spawner,stdoutToStderr:e.jsonLogs})).ran&&(d=Date.now())}finally{a=!1}}}}catch(h){e.logger.error(`codegen watch: ${h instanceof Error?h.message:String(h)}`)}finally{i=!1,g()}})()))};p("startup");const l=v=>(e.logger.warn(`codegen watch unavailable (${v}) — schema edits will NOT auto-regenerate. Run \`lunora codegen\` manually after each edit.`),{close:()=>(o=!0,s=void 0,u),ready:m,watchAvailable:!1});let c,f;if(!N(n))return l(`no such directory: ${n}`);try{f=Te(n,{recursive:!0},(v,h)=>{if(!(typeof h=="string"&&h.split(Ar).includes("_generated"))){if(a||Date.now()-d<Pr){c&&(clearTimeout(c),c=void 0);return}c&&clearTimeout(c),c=setTimeout(()=>{p(`change: ${h??"?"}`)},t)}})}catch(v){return l(v instanceof Error?v.message:String(v))}const w=f;return{close:()=>(o=!0,s=void 0,c&&clearTimeout(c),w.close(),u),ready:m,watchAvailable:!0}},Cr=64,me="127.0.0.1",Mr=65535,xr=(e,r=me)=>new Promise(n=>{const t=sr();t.once("error",()=>{n(!1)}),t.once("listening",()=>{t.close(()=>{n(!0)})}),t.listen(e,r)}),Fr=async(e,r=me,n=Cr)=>{for(let t=e;t<e+n&&t<=Mr;t+=1)if(await xr(t,r))return t;return e},H=(e=lr)=>Object.values(e()).some(r=>r?.some(n=>n.internal&&n.address==="::1")),B="/_lunora",K=e=>{const r=e.indexOf("?");return r===-1?e:e.slice(0,r)},Y=3e4,J=(e,r,n)=>{const t=fr({headers:{...e.headers,host:n.host},hostname:n.hostname,method:e.method,path:e.url,port:n.port},o=>{r.writeHead(o.statusCode??502,o.headers),gr(o,r,()=>{})});t.setTimeout(Y,()=>{t.destroy(new Error(`no response within ${String(Y)}ms`))}),t.on("error",o=>{if(r.headersSent){r.destroy();return}r.statusCode=o.message.startsWith("no response within")?504:502,r.end(`lunora dev: worker unreachable (${o.message})`)}),r.on("close",()=>{r.writableFinished||t.destroy()}),e.pipe(t)},jr=5e3,Gr=(e,r,n,t)=>{const o=cr({host:t.hostname,port:Number(t.port)},()=>{o.setTimeout(0);const i=[`${e.method??"GET"} ${e.url??"/"} HTTP/1.1`];for(const[a,s]of Object.entries(e.headers))if(a!=="host")for(const d of Array.isArray(s)?s:[s])d!==void 0&&i.push(`${a}: ${d}`);i.push(`host: ${t.host}`,"",""),o.write(i.join(`\r
|
|
2
2
|
`)),n.length>0&&o.write(n),o.pipe(r),r.pipe(o)});o.setTimeout(jr,()=>o.destroy()),o.on("error",()=>r.destroy()),r.on("error",()=>o.destroy())},Ur=async e=>{const r=e.host??"127.0.0.1",n=r==="127.0.0.1"||r==="localhost"||r==="::1",t=new URL(e.workerOrigin);let o=U(e.logger,import.meta.url),i=V(import.meta.url);const a=vr({adminToken:n?mr(e.cwd):void 0,basePath:"/",dataEditable:n,rulesInstalled:ie(e.cwd).installed,runAsIdentity:n,schemaEditable:n,scriptSrc:"/studio.js",styleHref:"/styles.css"}),s=(l,c,f,w,v)=>{Lr(l,c,v,i)||(c.statusCode=200,c.setHeader("Content-Type",w),c.end(f))},d=(l,c,f)=>{l.statusCode=c,l.setHeader("Content-Type","text/plain"),l.end(f)},u=(l,c,f,w)=>{if(n){yr(l,c,f,e.cwd,{apiSpec:e.apiSpec});return}d(c,403,w)},g=(l,c,f)=>{const w=l==="/styles.css",v=Er(l);if(!w&&!v)return!1;const h=V(import.meta.url);if(h!==i&&(o=U(e.logger,import.meta.url),i=h),o===void 0)return d(f,501,"Lunora studio assets not found — install and build @lunora/studio."),!0;if(w)return s(c,f,o.styles,"text/css; charset=utf-8","styles.css"),!0;const b=l.slice(l.lastIndexOf("/")+1),j=kr(b,import.meta.url);return j===void 0?(d(f,404,"Not found"),!0):(s(c,f,j,br(b),b),!0)},m=Buffer.from(a),p=ur((l,c)=>{const f=K(l.url??"/");if(n){const v=W(l,e.logger);if(v!==void 0){d(c,403,v);return}}if(f.startsWith(B)){if(!n){d(c,403,"Lunora studio: the worker admin proxy is only available on a loopback bind.");return}J(l,c,t);return}if(f===pr){u(l,c,Tr,"Lunora schema editing is only available on loopback hosts in dev.");return}if(f===wr){u(l,c,Rr,"Lunora policy scaffolding is only available on loopback hosts in dev.");return}if(f===hr){u(l,c,_r,"Lunora data seeding is only available on loopback hosts in dev.");return}if(g(f,l,c))return;const w=l.headers["sec-fetch-mode"];if(n&&typeof w=="string"&&w!=="navigate"){J(l,c,t);return}Sr(c,m)});return p.on("upgrade",(l,c,f)=>{if(!n||W(l,e.logger)!==void 0){c.destroy();return}K(l.url??"").startsWith(B)?Gr(l,c,f,t):c.destroy()}),await new Promise((l,c)=>{p.once("error",f=>{f.code==="EADDRINUSE"?c(new Error(`studio port ${String(e.port)} is already in use — pass a different port with --port, or stop the process using it`,{cause:f})):c(f)}),p.listen(e.port,r,()=>{l()})}),{close:()=>new Promise(l=>{p.close(()=>{l()})}),url:`http://${r==="0.0.0.0"||r==="::"?"localhost":r}:${String(e.port)}`}},Vr=12e4,F=250,Wr=1e3,Hr="LUNORA_DEV_READY_TIMEOUT_MS",pe=e=>{if(e!==void 0)return e;const r=Number(process.env[Hr]??"");return Number.isFinite(r)&&r>0?r:Vr},we=async(e,r)=>{try{const n=AbortSignal.timeout(Wr);return await(await fetch(new URL("/_lunora/status",e),{redirect:"manual",signal:r===void 0?n:AbortSignal.any([r,n])})).body?.cancel(),!0}catch{return!1}},Br=async e=>{const{cwd:r,logger:n,origin:t,signal:o}=e,i=e.probe??we,a=pe(e.readyTimeoutMs),s=Date.now()+a,d=()=>o.aborted;for(;!d()&&Date.now()<s;){let u=!1;try{u=await i(t,o)}catch{}if(d()||Date.now()>=s)break;if(u)return M(r,{readyAt:new Date().toISOString()},{expectedPid:process.pid}),O(r)?.readyAt!==void 0;try{await L(F,void 0,{signal:o})}catch{}}return d()||n.warn(`server did not answer on ${t} within ${String(Math.round(a/1e3))}s — .lunora/dev.json will have no readyAt, so anything polling for readiness will keep waiting. The server itself is unaffected; raise LUNORA_DEV_READY_TIMEOUT_MS if it is just slow to boot.`),!1},Kr=1e4,Yr=100,Jr=40,T=256*1024,Xr=new Set(["nuxt","sveltekit"]),P=e=>Xr.has(se(e).framework)?"framework-worker":De(e).has("@lunora/vite")?"vite":"wrangler",he=e=>{const r=de(e);let n;try{const t=C(k(e,"package.json"),"utf8");n=JSON.parse(t).scripts?.dev}catch{}if(n===void 0||n.trim()===""||n.includes("lunora")){const t=A(r,"vite",["dev"]);return{args:t.args,command:t.command}}return{args:["run","dev"],command:r}},zr=e=>{Re(Ie(e.logPath),{recursive:!0});const r=te(e.logPath,"w",384);let n;const t=ve(e.command,e.args);try{n=re(t.command,t.args,{cwd:e.cwd,detached:!0,env:e.env,shell:t.shell,stdio:["ignore",r,r],windowsHide:!0})}finally{ne(r)}return n.unref(),{exited:new Promise(o=>{n.on("error",()=>{o(1)}),n.on("exit",(i,a)=>{o(i??(a?1:0))})}),pid:n.pid}},Qr=e=>{try{const{size:r}=_e(e);if(r<=T)return C(e,"utf8");const n=te(e,"r");try{const t=Buffer.alloc(T),o=Le(n,t,0,T,r-T),i=t.toString("utf8",0,o);return i.slice(i.indexOf(`
|
|
3
3
|
`)+1)}finally{ne(n)}}catch{return}},Se=(e,r)=>{const n=Qr(e);if(n===void 0)return[];const t=n.split(`
|
|
4
4
|
`);return t.at(-1)===""&&t.pop(),r>0?t.slice(-r):t},ye=(e,r)=>r?.logFile??k(e,Ae),Ee=e=>{e.info(" Stop: lunora dev stop"),e.info(" Status: lunora dev status"),e.info(" Logs: lunora dev logs")},I=(e,r)=>{e.warn(`Dev server already running at ${r.url} (pid ${String(r.pid)})`),Ee(e)},Zr=(e,r)=>{e.success(`Dev server running at ${r.url} (pid ${String(r.pid)})`),r.studioUrl!==void 0&&e.info(` Studio: ${r.studioUrl}`),Ee(e)},qr=async e=>{const{child:r,cwd:n,deadline:t,pollIntervalMs:o,probe:i}=e,a=r.exited.then(s=>({exitCode:s}));for(;Date.now()<t;){const s=D(n);if(s!==void 0&&s.pid!==process.pid&&await i(s.url))return{state:s,status:"ready"};const d=await Promise.race([a,L(o)]);if(d!==void 0)return{...d,status:"exited"}}return{status:"timeout"}},et=async e=>{const{cwd:r,logger:n}=e,t=ye(r,void 0),o=pe(e.readyTimeoutMs),i=(e.spawnDetached??zr)({args:e.command.args,command:e.command.command,cwd:r,env:{...process.env,...e.env,[x]:"1",[ce]:t,...process.env.FORCE_COLOR===void 0?{NO_COLOR:"1"}:{},...e.json?{LUNORA_LOG_JSON:"1"}:{}},logPath:t}),a=await qr({child:i,cwd:r,deadline:Date.now()+o,pollIntervalMs:e.pollIntervalMs??F,probe:e.probe??we});if(a.status==="ready")return Zr(n,a.state),{code:0};if(a.status==="exited"){n.error(`dev server exited before becoming ready (exit code ${String(a.exitCode)}). Last output:`);for(const d of Se(t,Jr))n.error(` ${d}`);return y(r,i.pid??process.pid),{code:a.exitCode===0?1:a.exitCode}}i.pid!==void 0&&O(r)?.pid===process.pid&&M(r,{logFile:t,pid:i.pid});const s=i.pid===void 0?"":` (pid ${String(i.pid)})`;return n.warn(`dev server did not confirm ready within ${String(Math.round(o/1e3))}s — it may still be compiling${s}. Check \`lunora dev status\` and \`lunora dev logs\`; \`lunora dev stop\` shuts it down.`),{code:1}},ke=e=>e.codegen!==!1&&!$e(process.env[le]),be=e=>{const r={...e.remote===!0?{LUNORA_REMOTE:"1"}:{},...e.codegen===!1?{[le]:"0"}:{}};return Object.keys(r).length>0?{env:r}:{}},rt=(e,r)=>{const n=["dev"];return e.apiSpec!==void 0&&n.push("--api-spec",e.apiSpec),e.port!==void 0&&n.push("--port",String(e.port)),e.workerPort!==void 0&&n.push("--worker-port",String(e.workerPort)),e.emitBindings!==void 0&&n.push("--emit-bindings",e.emitBindings),e.codegen===!1&&n.push("--no-codegen"),e.studio===!1&&n.push("--no-studio"),e.worker===!1&&n.push("--no-worker"),e.target!==void 0&&n.push("--target",e.target),r&&n.push("--remote"),n},tt=async e=>{const{cwd:r,jsonLogs:n,logger:t,options:o,remote:i}=e,a=e.run??et,s=P(r),d=s==="wrangler"?`http://localhost:${String(o.workerPort??8787)}`:"http://localhost:5173",u=ae(r,{background:!0,mode:"cli",pid:process.pid,startedAt:new Date().toISOString(),url:d});if(!u.ok)return u.existing!==void 0&&I(t,u.existing),{code:0};const g={[R]:String(process.pid)};try{return s==="vite"?await a({command:he(r),cwd:r,env:{...be({...o,remote:i}).env,...g},json:n,logger:t}):await a({command:{args:[process.argv[1]??"lunora",...rt(o,i)],command:process.execPath},cwd:r,env:g,json:n,logger:t})}finally{y(r,process.pid)}},nt=e=>{try{const r=$("ps",["-o","pgid=","-p",String(e)],{encoding:"utf8"}),n=Number.parseInt(r.stdout.trim(),10);return Number.isInteger(n)&&n>0?n:void 0}catch{return}},ot=(e,r,n=process.platform,t=$)=>{if(n==="win32"){try{t("taskkill",["/pid",String(e.pid),"/T","/F"],{stdio:"ignore"})}catch{}return}if(e.background===!0)try{r(-(nt(e.pid)??e.pid),"SIGKILL");return}catch{}try{r(e.pid,"SIGKILL")}catch{}},it=(e,r)=>(r.json?E({pid:e.pid,stopped:!1}):r.logger.error(`dev server (pid ${String(e.pid)}) survived the force-kill — record kept; retry \`lunora dev stop\` or kill the process manually.`),{code:1}),at=async e=>{const{cwd:r,logger:n}=e,t=O(r),o=e.alive??(m=>m===t?.pid&&Pe(t)),i=e.signal??((m,p)=>{process.kill(m,p)}),a=e.pollIntervalMs??F,s=e.stopGraceMs??Kr,d=e.platform??process.platform,u=e.spawnSyncImpl??$;if(t===void 0||!o(t.pid))return t!==void 0&&y(r,t.pid),e.json?E({running:!1,stopped:!1}):n.info("No dev server running."),{code:0};try{i(t.pid,"SIGTERM")}catch{}const g=Date.now()+s;for(;o(t.pid)&&Date.now()<g;)await L(a);return o(t.pid)&&(ot(t,i,d,u),await L(a),o(t.pid))?it(t,e):(y(r,t.pid),e.json?E({pid:t.pid,stopped:!0}):n.success(`Stopped dev server (pid ${String(t.pid)}).`),{code:0})},st=e=>{const{cwd:r,logger:n}=e,t=D(r);if(t===void 0)return e.json?E({running:!1}):n.info("No dev server running."),{code:0};const o=e.now??Date.now,i=t.startedAt===void 0?Number.NaN:Date.parse(t.startedAt),a=Number.isFinite(i)?Math.max(0,Math.round((o()-i)/1e3)):void 0;if(e.json)return E({background:t.background===!0,logFile:t.logFile,mode:t.mode,pid:t.pid,ready:G(t),readyAt:t.readyAt,running:!0,startedAt:t.startedAt,studioUrl:t.studioUrl,uptimeSeconds:a,url:t.url}),{code:0};const s=[`pid ${String(t.pid)}`,...a===void 0?[]:[`uptime ${String(a)}s`],t.background===!0?"background":"foreground",G(t)?"ready":"starting"];return n.success(`Dev server running at ${t.url} (${s.join(", ")})`),t.studioUrl!==void 0&&n.info(` Studio: ${t.studioUrl}`),t.logFile!==void 0&&n.info(` Logs: lunora dev logs (${t.logFile})`),{code:0}},ct=e=>{const{cwd:r,logger:n}=e,t=O(r),o=ye(r,t);if(!N(o))return n.info("No dev server logs found — output is captured when the server runs in background mode (`lunora dev --background`)."),{code:0};const i=Se(o,e.lines??Yr);return i.length>0&&process.stdout.write(`${i.join(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{runCodegen as y}from"@lunora/codegen";import{applyLintIgnores as A,detectLintTools as x,inferLunoraBindings as S}from"@lunora/config";import{collectWranglerSecretVariables as T,collectExportGaps as k}from"@lunora/config/cloudflare";import{r as b,a as D,e as R}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as C,r as E}from"../packem_shared/deploy-target-
|
|
1
|
+
import{runCodegen as y}from"@lunora/codegen";import{applyLintIgnores as A,detectLintTools as x,inferLunoraBindings as S}from"@lunora/config";import{collectWranglerSecretVariables as T,collectExportGaps as k}from"@lunora/config/cloudflare";import{r as b,a as D,e as R}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as C,r as E}from"../packem_shared/deploy-target-DCWwiuAe.mjs";import{d as L}from"../packem_shared/command-CrAs0XG_.mjs";import{r as j}from"../packem_shared/lint-ignore-report-DKZagpqk.mjs";import{l as f,v as I,p as O,i as G}from"../packem_shared/output-format-B91O3X28.mjs";const p=3,F=r=>{const t=r.cwd??process.cwd(),o=G(r.format),e=f(r.format,r.logger),a=I("codegen",r.format);if(a!==void 0)return r.logger.error(a),{advisories:[],cronTriggers:[],error:a,failedAdvisories:0,outputDirectory:""};const g=b(r),n=E(t,r.target);if(n.target===void 0)return r.logger.error(n.error??"unknown deploy target"),{advisories:[],cronTriggers:[],error:n.error??"unknown deploy target",failedAdvisories:0,outputDirectory:""};const{target:v}=n,s=y({apiSpec:r.apiSpec,projectRoot:t,target:v,wranglerVariables:T(t)}),l={advisories:s.advisories.map(i=>({detail:i.detail,level:i.level,name:i.name,remediation:i.remediation})),cronTriggers:s.cronTriggers,failedAdvisories:0,outputDirectory:s.outputDirectory};if(e.success(`codegen wrote dataModel.ts, api.ts, server.ts to ${s.outputDirectory}`),s.advisories.length>0){const i=s.advisories.length,$=s.advisories.map(c=>` [${c.level}] ${c.name} — ${c.detail}
|
|
2
2
|
↳ ${c.remediation}`);e.warn(`${i.toString()} schema ${i===1?"advisory":"advisories"}:
|
|
3
3
|
${$.join(`
|
|
4
4
|
`)}`)}const m=D(s.platformDiagnostics,e);m.errors.length>0&&(l.error=m.errors.join("; "));const{errorAdvisories:d,names:h,shouldBlock:w}=R(l.advisories,g);w&&e.error(`${d.length.toString()} ERROR-level ${d.length===1?"advisory":"advisories"} (${h.join(", ")}). Codegen wrote its output; this exit code is the gate. Pass --no-strict-advisories to downgrade it to a warning.`),s.cronTriggers.length>p&&e.warn(`${s.cronTriggers.length.toString()} distinct cron expressions declared — Cloudflare allows at most ${p.toString()} Cron Triggers per Worker. Consolidate schedules (jobs can share one expression) or move finer-grained work to Durable Object alarms via @lunora/scheduler (runAfter/runAt).`);const u={...l,failedAdvisories:g?d.length:0};return o&&O(u),u},N=async(r,t)=>{let o;try{o=k(await S({projectRoot:r}))}catch(e){t.warn(`could not check whether declared containers/workflows/agents are re-exported by the worker entry: ${e instanceof Error?e.message:String(e)}. Run \`lunora doctor\` to check explicitly.`);return}for(const e of o)t.warn(`${e.kind} "${e.exportName}" is declared but ${e.className} is not exported by the worker entry — add \`export * from "./lunora/_generated/${e.module}"\` so wrangler can provision its binding. Until then it deploys with nothing to run.`)},_=(r,t)=>{try{j(A(r,x(r)),t)}catch{}},q=L(async({cwd:r,logger:t,options:o})=>{const e=F({apiSpec:C(o.apiSpec),cwd:r,format:o.format,logger:t,strictAdvisories:o.strictAdvisories,target:o.target});if(e.outputDirectory!==""){const a=f(o.format,t);_(r,a),await N(r,a)}return{code:e.error===void 0&&e.failedAdvisories===0?0:1}});export{q as execute,F as runCodegenCommand};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{readFileSync as p,writeFileSync as T,existsSync as v}from"node:fs";import{runCodegen as B,discoverMigrations as V}from"@lunora/codegen";import{readLinkedProject as L,writeLinkedProject as K,execArgsFor as k,detectPackageManager as b,discoverContainerInfo as I,DEV_VARS_FILE as y,parseDevVariableEntries as U,isMintableSecretKey as P,runPostCodegenHook as q,resolveDeployDriver as R,inferLunoraBindings as F,packageNamesFromBindings as Y,requiredSecrets as G,generateSecretValue as z,upsertDevVariableLine as J,writeDevVariablesFileAtomically as Q,COMPOSED_WORKER_ENTRY as _,discoverSchemaInfo as X}from"@lunora/config";import{findWranglerFile as W,validateWranglerProject as Z,reconcileWranglerBindings as ee,reconcileWranglerCompatibilityDate as re,reconcileWranglerCrons as te,describePreservedCrons as ne,readWranglerJsonc as ae,mergeWranglerEnvironment as oe}from"@lunora/config/cloudflare";import{join as h}from"@visulima/path";import{Spinner as ie}from"@visulima/spinner";import{Project as se}from"ts-morph";import{i as ce,m as le,e as de}from"../packem_shared/vectorize-metadata-dXpl2_Ar.mjs";import{r as ue,a as ge,e as me}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as fe,a as he}from"../packem_shared/deploy-target-
|
|
1
|
+
import{readFileSync as p,writeFileSync as T,existsSync as v}from"node:fs";import{runCodegen as B,discoverMigrations as V}from"@lunora/codegen";import{readLinkedProject as L,writeLinkedProject as K,execArgsFor as k,detectPackageManager as b,discoverContainerInfo as I,DEV_VARS_FILE as y,parseDevVariableEntries as U,isMintableSecretKey as P,runPostCodegenHook as q,resolveDeployDriver as R,inferLunoraBindings as F,packageNamesFromBindings as Y,requiredSecrets as G,generateSecretValue as z,upsertDevVariableLine as J,writeDevVariablesFileAtomically as Q,COMPOSED_WORKER_ENTRY as _,discoverSchemaInfo as X}from"@lunora/config";import{findWranglerFile as W,validateWranglerProject as Z,reconcileWranglerBindings as ee,reconcileWranglerCompatibilityDate as re,reconcileWranglerCrons as te,describePreservedCrons as ne,readWranglerJsonc as ae,mergeWranglerEnvironment as oe}from"@lunora/config/cloudflare";import{join as h}from"@visulima/path";import{Spinner as ie}from"@visulima/spinner";import{Project as se}from"ts-morph";import{i as ce,m as le,e as de}from"../packem_shared/vectorize-metadata-dXpl2_Ar.mjs";import{r as ue,a as ge,e as me}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as fe,a as he}from"../packem_shared/deploy-target-DCWwiuAe.mjs";import{r as E}from"../packem_shared/wrangler-name-Dsk5K1f-.mjs";import{w as ve}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{d as ye}from"../packem_shared/command-CrAs0XG_.mjs";import{a as pe,i as we}from"../packem_shared/docker-DpVxvYpL.mjs";import{r as ke,p as be,H as $e,a as Se}from"../packem_shared/schema-drift-gate-BDCkQ1S6.mjs";import{v as De,l as Re,i as $,p as Ee}from"../packem_shared/output-format-B91O3X28.mjs";import{containerBuildTag as Ae}from"@lunora/container";import{defaultSpawner as S}from"../packem_shared/createRecordingSpawner-DJlNacZ6.mjs";import{a as O}from"../packem_shared/resolve-target-BRvw8Pf7.mjs";import{c as Ce}from"../packem_shared/tui-prompts-DzYd2fL3.mjs";import{l as Pe}from"../packem_shared/wrangler-secrets-CCdt0mUl.mjs";import{runMigrateDataCommand as _e}from"./runMigrateGenerateCommand.mjs";const xe=/https?:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/u,je=/https:\/\/[^\s"'<>]+/u,Ne=e=>{if(e===void 0)return;const r=xe.exec(e);return r?r[0]:je.exec(e)?.[0]},x=e=>e===void 0?"":` (--env ${e})`,Te=({cwd:e,env:r,logger:n,now:t,url:a})=>{if(a!==void 0)try{const o=L(e);if(o!==void 0){if(o.workerUrl===a&&o.env===r)return;n.warn(`link: .lunora/project.json records ${o.workerUrl??"(no url)"}${x(o.env)}, but this deploy published ${a}${x(r)}. Keeping the recorded value — run \`lunora link --url ${a}${r===void 0?"":` --env ${r}`}\` to update it.`);return}const i=(t??(()=>new Date().toISOString()))();K(e,{env:r,linkedAt:i,workerName:E(e),workerUrl:a}),n.success(`link: recorded ${a} in .lunora/project.json (run \`lunora link\` to change)`)}catch{}},Le=e=>{const{cwd:r,env:n,logger:t,mintedSecretsFile:a}=e;try{const o=L(r),i=o?.workerName??E(r),s=e.url??o?.workerUrl;t.success("deploy complete"),t.info(` worker: ${i??"(see wrangler output above)"}`),n!==void 0&&t.info(` env: ${n}`),s===void 0?t.info(" url: run `lunora link --url <https://your-worker>` to record it"):t.info(` url: ${s}`),a!==void 0&&t.info(` secrets: generated value(s) recorded in ${a}`),t.info(" logs: lunora logs")}catch{}},Ie=async e=>{if(e.targets.length===0)return{builtTags:[],code:0};if(!(e.railpackAvailable??pe)()){const t="deploy blocked: a container uses `image: { build }` (Railpack), but Railpack isn't ready. Install the `railpack` CLI and start a BuildKit instance, e.g. `docker run --rm --privileged -d --name buildkit moby/buildkit` then `export BUILDKIT_HOST=docker-container://buildkit`. Alternatively switch the container's `image` to a Dockerfile path or a pre-built registry reference.";return e.logger.error(t),{builtTags:[],code:1,error:t}}const r=e.spawner??S,n=[];for(const t of e.targets){const a=Ae(t.exportName),o={args:["build",t.buildDir,"--name",a],command:"railpack",cwd:e.cwd},i=k(b(e.cwd),"wrangler",["containers","push",a]),s={args:i.args,command:i.command,cwd:e.cwd};e.logger.info(`railpack: building "${t.exportName}" → ${a} from ${t.buildDir}`);const c=await r(o);if(c.code!==0){const d=`railpack build failed for container "${t.exportName}" (${t.buildDir})`;return e.logger.error(d),{builtTags:n,code:c.code,error:d}}e.logger.info(`railpack: pushing ${a} to the Cloudflare Registry`);const l=await r(s);if(l.code!==0){const d=`wrangler containers push failed for "${t.exportName}" (${a})`;return e.logger.error(d),{builtTags:n,code:l.code,error:d}}n.push(a)}return{builtTags:n,code:0}},Ue=e=>{const r=W(e),n=r===void 0?void 0:p(r,"utf8");return()=>{r!==void 0&&n!==void 0&&T(r,n,"utf8")}},H="<replace-with-d1-create-id>",j=e=>Array.isArray(e)?e.filter(r=>r!=null):void 0,A=(e,r)=>{const n=W(e);if(!n)return;const{parsed:t}=ae(n);if(t===void 0)return;const{error:a,merged:o}=oe(t,r),i=a===void 0?o:t,{containers:s,d1_databases:c,vars:l}=i;return{containers:j(s),d1_databases:j(c),vars:typeof l=="object"&&l!==null&&!Array.isArray(l)?l:void 0}},Fe=["LUNORA_ORIGIN_URL","AUTH_URL"],We=e=>{try{const{hostname:r}=new URL(e);return r==="localhost"||r==="127.0.0.1"||r==="::1"||r==="[::1]"}catch{return!1}},Oe=e=>e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.includes("Dockerfile"),He=(e,r,n,t="deploy",a)=>{const o=(A(e,a)?.containers??[]).filter(s=>typeof s?.image=="string"&&Oe(s.image));if(o.length===0||n())return;const i=`${t} blocked: wrangler.jsonc declares ${String(o.length)} container(s) built from a local Dockerfile, but no Docker-compatible engine is available. Start Docker (or Colima), or point the container's \`image\` at a pre-built registry reference. Note: container images must target linux/amd64.`;return r.error(i),i},Me=e=>v(h(e,_))?_:void 0,Be=(e,r,n="deploy")=>{for(const t of I(e,"lunora").containers){const{image:a}=t;if(a.kind==="dockerfile"&&!v(h(e,a.dockerfilePath))){const o=`${n} blocked: container "${t.exportName}" references a Dockerfile at "${a.dockerfilePath}" that does not exist. Create it or fix the \`image\` path in lunora/containers.ts.`;return r.error(o),o}if(a.kind==="build"&&!v(h(e,a.buildDir))){const o=`${n} blocked: container "${t.exportName}" references a Railpack build directory "${a.buildDir}" that does not exist. Create it or fix the \`image.build\` path in lunora/containers.ts.`;return r.error(o),o}}},M=e=>$(e.format)?!1:e.interactive!==void 0?e.interactive:process.stdout.isTTY&&!process.env.CI,Ve=(e,r)=>(A(e,r)?.d1_databases??[]).find(n=>n.database_id===H)?.binding,Ke=async(e,r)=>{if(r.dryRun===!0)return;const n=I(e,"lunora").containers.filter(a=>a.image.kind==="build").map(a=>({buildDir:a.image.buildDir,exportName:a.exportName}));if(n.length===0)return;const t=await Ie({cwd:e,logger:r.logger,railpackAvailable:r.railpackAvailable,spawner:r.spawner,targets:n});return t.code===0?void 0:t.error??"railpack build failed"},qe=(e,r,n)=>{if(n!==void 0)try{const t=te(e,n);t.changed&&r.success(`synced ${String(n.length)} cron trigger(s) → ${t.wranglerPath??"wrangler.jsonc"}`);for(const o of t.warnings)r.warn(o);const a=ne(t.preserved);a!==void 0&&r.info(a)}catch(t){const a=t instanceof Error?t.message:String(t);r.warn(`cron trigger sync skipped: ${a}`)}},Ye=async(e,r,n,t,a)=>{try{R(t);const o=await F({projectRoot:e}),i=ee(e,o,a);i.changed&&r.success(`provisioned bindings: ${i.added.join(", ")} → ${i.wranglerPath??"wrangler.jsonc"}`);for(const s of i.warnings)r.warn(s)}catch(o){const i=o instanceof Error?o.message:String(o);r.warn(`binding inference skipped: ${i}`)}try{const o=re(e);o.changed&&r.success(`bumped compatibility_date to ${o.date??"unknown"} (Workers Cache enabled) → ${o.wranglerPath??"wrangler.jsonc"}`)}catch(o){const i=o instanceof Error?o.message:String(o);r.warn(`compatibility date sync skipped: ${i}`)}qe(e,r,n)},Ge=(e,r)=>{const n=h(e,y);if(!v(n))return;let t;try{t=U(p(n,"utf8")).length}catch{return}t!==0&&r.warn(`Note: \`lunora deploy\` does not push secrets. ${y} has ${String(t)} key(s); if you changed them, run \`lunora env push --yes\` to update the deployed secrets.`)},ze=async e=>{let r=[];try{r=Y(await F({projectRoot:e}))}catch{}const n=G(r).map(a=>a.key);let t=[];try{const a=h(e,y);v(a)&&(t=U(p(a,"utf8")).map(o=>o.key).filter(o=>ce(o)))}catch{}return[...new Set([...n,...t])]},Je=async(e,r,n,t)=>{const{logger:a}=r,o=r.spawner??S,i=b(e),s=r.env===void 0?"":` --env ${r.env}`,{toolchain:c}=R(t);if(c===void 0)return a.error("deploy target has no command-line toolchain; cannot push secrets"),{minted:[],ok:!1};const l=[];for(const d of n){const g=z(),u=c.secretPut({environment:r.env,key:d,temporary:r.temporary}),m=k(i,u.tool,u.args),f=await o({args:m.args,command:m.command,cwd:e,input:g});if(f.code!==0)return a.error(`failed to push secret ${d} (exit ${String(f.code)}); set it manually with \`wrangler secret put ${d}${s}\`.`),{minted:l,ok:!1};l.push({key:d,value:g}),a.success(`generated + pushed ${d}`)}return{minted:l,ok:!0}},Qe=/^[\w-]+$/u,D=[".dev.vars",".dev.vars.*","!.dev.vars.example"],Xe=/\r?\n/u,Ze=(e,r)=>{const n=h(e,".gitignore");try{const t=v(n)?p(n,"utf8"):"",a=new Set(t.split(Xe).map(c=>c.trim())),o=D.filter(c=>!a.has(c));if(o.length===0)return;const i=o.some(c=>!c.startsWith("!"))?[...o.filter(c=>!c.startsWith("!")),...D.filter(c=>c.startsWith("!"))]:o,s=t.length>0&&!t.endsWith(`
|
|
2
2
|
`)?`
|
|
3
3
|
`:"";T(n,`${t}${s}
|
|
4
4
|
# Lunora — never commit a minted secret
|
|
5
5
|
${i.join(`
|
|
6
6
|
`)}
|
|
7
|
-
`,"utf8"),r.info(`.gitignore: added ${o.join(", ")} so the recorded secret cannot be committed`)}catch(t){r.warn(`could not update .gitignore (${t instanceof Error?t.message:String(t)}) — add \`${D.join("` and `")}\` by hand before committing.`)}},er=(e,r,n)=>{if(n.length===0)return;const t=n.map(s=>s.key).join(", ");if(r.env!==void 0&&!Qe.test(r.env)){r.logger.warn(`${t}: minted and pushed for --env ${r.env}, but "${r.env}" isn't a safe filename fragment — the value could not be recorded. Capture it manually if you need it again.`);return}const a=r.env===void 0?y:`${y}.${r.env}`;Ze(e,r.logger);const o=h(e,a);let i=v(o)?p(o,"utf8"):"";for(const s of n)i=J(i,s.key,s.value);return Q(o,i),r.logger.success(r.env===void 0?`${t}: value(s) recorded in ${a}`:`${t}: value(s) recorded in ${a} (kept separate from ${y} so \`lunora dev\` and a plain \`lunora env push\` don't inherit the --env ${r.env} value)`),a},rr=async(e,r,n,t)=>{if(r.dryRun===!0||r.preview===!0)return{};const{logger:a}=r,o=r.env===void 0?"":` --env ${r.env}`;let i;try{i=await(r.secretLister??Pe)({cwd:e,env:r.env,temporary:r.temporary})}catch{return{}}if(!i.ok)return{};const s=new Set(i.names),l=(await ze(e)).filter(u=>!s.has(u));if(l.length===0)return{};if(!n)return{error:`missing required secret(s) on the deploy target: ${l.join(", ")}. Set them with \`wrangler secret put <KEY>${o}\` (or \`lunora env generate --set\` then \`lunora env push --yes${o}\`), then re-deploy.`};for(const u of l.filter(m=>!P(m)))a.warn(`required secret ${u} is not set on the target — set it with: wrangler secret put ${u}${o}`);const d=l.filter(u=>P(u));if(d.length===0)return{};if(await(r.secretConfirm??Ce())(`${String(d.length)} required secret(s) not set on the target (${d.join(", ")}). Generate strong values and push them now?`)){const{minted:u,ok:m}=await Je(e,r,d,t),f=er(e,r,u);return m?{mintedSecretsFile:f}:{error:"failed to push required secret(s) — set them manually and re-deploy",mintedSecretsFile:f}}return a.warn(`${String(d.length)} required secret(s) not set on the target: ${d.join(", ")}. Generate + push with \`lunora env generate --set\` then \`lunora env push --yes${o}\`.`),{}},tr=async(e,r)=>{const n=new se({skipAddingFilesFromTsConfig:!0}),t=h(r,"lunora");let a;try{a=V(n,t)}catch(o){const i=o instanceof Error?o.message:String(o);return e.logger.warn(`--migrate: could not discover migrations (${i}); skipping`),0}if(a.length===0)return e.logger.info("--migrate: no data migrations declared in lunora/"),0;e.logger.info(`--migrate: running ${String(a.length)} migration(s) against deployed worker`);for(const o of a){e.logger.info(`--migrate: up "${o.id}" (table "${o.table}")`);const i={cwd:r,fetchImpl:e.fetchImpl,id:o.id,logger:e.logger,prod:!0,subcommand:"up",token:e.migrateToken,url:e.migrateUrl,yes:e.migrateYes===!0},s=await _e(i);if(s.code!==0)return e.logger.error(`--migrate: migration "${o.id}" failed — see output above`),s.code;e.logger.success(`--migrate: "${o.id}" applied`)}return 0},nr=e=>{if(!e.migrate||e.dryRun||e.preview)return;if(e.migrateUrl===void 0){const n="--migrate requires --migrate-url <https://your-worker> — the deploy target URL is only known after wrangler runs, and this gate runs before it; refusing to default to localhost";return e.logger.error(n),n}if(e.migrateYes!==!0){const n="--migrate runs production data migrations after deploy. Re-run with --migrate-yes to confirm.";return e.logger.error(n),n}const r=e.migrateToken??process.env.LUNORA_ADMIN_TOKEN;if(r===void 0||r===""){const n="admin token required for --migrate — pass --migrate-token or set LUNORA_ADMIN_TOKEN";return e.logger.error(n),n}},ar=async(e,r,n,t,a,o,i,s)=>{let c;r?(c=new ie({name:"dots"}),c.start("running codegen")):n.info("running codegen");try{const l=B({apiSpec:t,projectRoot:e,target:a});c?.succeed("codegen complete"),c||n.success("codegen complete");const d=ge(l.platformDiagnostics,n);if(d.errors.length>0)return{error:d.errors.join("; ")};const{errorAdvisories:g,names:u,shouldBlock:m}=me(l.advisories,s);if(m){const C=`${g.length.toString()} ERROR-level ${g.length===1?"advisory":"advisories"} (${u.join(", ")}). Pass --no-strict-advisories to downgrade this to a warning and continue.`;return n.error(C),{error:C}}const f=await q({cwd:e,logger:n,spawner:o,stdoutToStderr:i});return f.error!==void 0?{error:f.error}:{result:l}}catch(l){c?.failed("codegen failed");const d=l instanceof Error?l.message:String(l);return n.error(`codegen failed: ${d}`),{error:`codegen failed: ${d}`}}},or=(e,r,n="deploy",t)=>{const a=Ve(e,t);if(a===void 0)return;const o=`${n} blocked: the "${a}" D1 binding has a placeholder database_id ("${H}"). Run \`wrangler d1 create <name>\` to create the database, then replace the placeholder in wrangler.jsonc with the real id before deploying.`;return r.error(o),o},ir=(e,r,n="deploy",t)=>{const a=A(e,t)?.vars;if(!a)return;const o=Fe.filter(s=>typeof a[s]=="string"&&We(a[s]));if(o.length===0)return;const i=`${n} blocked: ${o.join(", ")} in wrangler.jsonc point at localhost. A deployed Worker can't reach a loopback address, so this silently breaks scheduled-job dispatch, reverse cross-shard relations, and auth callbacks. Set each to the deployed worker's public URL (or move it to a secret with \`wrangler secret put\`) before deploying.`;return r.error(i),i},sr=async(e,r)=>{const{info:n}=X(r,"lunora"),t=n?.vectorMetadata??[];if(t.length===0)return;const a=[];for(const s of t){const c=le(s.kind);if(c===void 0){e.logger.warn(`vector index "${s.index}" declares metadata "${s.property}", whose column type cannot be filtered on in Vectorize — it is stored with each vector but no filter will match it.`);continue}a.push({index:s.index,property:s.property,type:c})}if(a.length===0)return;const i=(await de({cwd:r,entries:a,exec:k(b(r),"wrangler",[]),logger:e.logger,spawner:e.spawner??S})).filter(s=>s.status!=="failed").length;i>0&&e.logger.success(`vectorize metadata indexes ready: ${String(i)}/${String(a.length)}`)},N=5,cr=2e3,lr=async(e,r,n)=>{if(e.healthCheck!==!0)return;const t=n??O({cwd:r,env:e.env});if(t===void 0){const o="--health-check: the deploy succeeded, but no URL to probe could be resolved — wrangler's output carried none and this checkout has no link for this environment. Run `lunora link --url <https://your-worker>` and re-deploy, or drop --health-check.";return e.logger.error(o),{error:o,ok:!1,url:""}}const a=await be({attempts:N,baseUrl:t,delayMs:cr,fetchImpl:e.healthFetch,paths:[$e,Se],sleep:e.healthSleep});return a.error===void 0?(e.logger.success(`health check ok (${a.url})`),{ok:!0,url:a.url}):(e.logger.error(`--health-check: the deploy succeeded, but the new version did not answer after ${String(N)} attempt(s) — ${a.error}`),{error:a.error,ok:!1,url:a.url})},dr=async(e,r,n,t,a,o)=>{await sr(e,r);const i=e.migrate?await tr(e,r):0;return i===0&&a?.(),{code:i,descriptor:n,mintedSecretsFile:o,validation:t}},ur=(e,r,n)=>{const t=or(e,r.logger,n,r.env);if(t!==void 0)return t;const a=ir(e,r.logger,n,r.env);if(a!==void 0)return a;const o=Be(e,r.logger,n);return o!==void 0?o:He(e,r.logger,r.dockerAvailable??we,n,r.env)},gr=(e,r,n)=>{const t=Me(e);t!==void 0&&r.logger.info(`class-B composition: deploying ${t} (overrides wrangler main)`),r.temporary&&r.logger.info("temporary account: deploying to a short-lived Cloudflare account (~60min); wrangler will print a claim URL"),r.dryRun&&r.logger.info("dry run: validating + bundling without publishing"),r.outDir!==void 0&&r.logger.info(`build artifact: emitting bundle to ${r.outDir}`);const a=R(n),o={dryRun:r.dryRun,entry:t,environment:r.env,outDir:r.outDir,preview:r.preview,temporary:r.temporary};if(a.toolchain===void 0)throw new Error(`deploy target "${a.id}" has no command-line toolchain`);return a.toolchain.deploy(o)},w=(e,r)=>({code:1,descriptor:void 0,error:e,validation:{problems:[],wranglerPath:void 0},...r}),mr=(e,r)=>{for(const n of e.report?.warnings??[])r.warn(`wrangler.jsonc: ${n}`);if(e.problems.length===0)return!1;r.error("wrangler.jsonc validation failed:");for(const n of e.problems)r.error(` - ${n}`);return!0},fr=(e,r,n)=>{const t=$(r.format),a=r.dryRun!==!0,o=gr(e,r,n),i=k(b(e),o.tool,o.args);return{args:i.args,captureStdout:a&&!t,captureStdoutSilently:a&&t,command:i.command,cwd:e,stdoutToStderr:t&&!a}},hr=async({cwd:e,descriptor:r,mintedSecretsFile:n,options:t,reblessSchemaBaseline:a,stdout:o,validation:i})=>{const s={deployedAt:new Date().toISOString(),dryRun:t.dryRun===!0,env:t.env,preview:t.preview===!0,url:t.dryRun===!0?void 0:Ne(o),workerName:E(e)};if(t.dryRun===!0||t.preview===!0)return t.healthCheck===!0&&t.logger.warn(`--health-check skipped: ${t.dryRun===!0?"a dry run publishes nothing":"a preview version serves no live traffic"}`),{code:0,deployment:s,descriptor:r,mintedSecretsFile:n,validation:i};t.temporary!==!0&&Te({cwd:e,env:t.env,logger:t.logger,url:s.url});const c=await lr(t,e,s.url);return c?.error!==void 0?{code:1,deployment:s,descriptor:r,healthCheck:c,mintedSecretsFile:n,validation:i}:{...await dr(t,e,r,i,a,n),deployment:s,healthCheck:c}},vr=async(e,r)=>{const n=e.cwd??process.cwd(),t=M(e),a=ue(e),o={problems:[],wranglerPath:void 0},i=he(n,e.target);if(i.target===void 0){const u=i.error??"unknown deploy target";return e.logger.error(u),{error:u,validation:o}}const{target:s}=i;let c;if(!e.skipCodegen){const u=await ar(n,t,e.logger,e.apiSpec,s,e.spawner,$(e.format),a);if(u.error!==void 0)return{error:u.error,target:s,validation:o};c=u.result}let l;if(c!==void 0){const u=ke({allowDrift:e.allowSchemaDrift===!0,codegen:c,command:r,logger:e.logger,updateBaseline:e.updateSchemaBaseline===!0});if(u.blocked)return{error:`schema drift gate blocked ${r}`,schemaDrift:{blocked:!0,reason:u.reason},target:s,validation:o};l=u.rebless}await Ye(n,e.logger,c?.cronTriggers,s,e.env);const d=ur(n,e,r);if(d!==void 0)return{error:d,target:s,validation:o};const g=Z({environment:e.env,projectRoot:n});return mr(g,e.logger)?{error:"wrangler validation failed",target:s,validation:g}:{codegen:c,reblessSchemaBaseline:l,target:s,validation:g}},yr=async e=>{const r=e.cwd??process.cwd(),n=M(e),t=await vr(e,e.commandName??"deploy");if(t.error!==void 0){if(t.validation.problems.length>0)return{code:1,descriptor:void 0,error:t.error,validation:t.validation};const f=t.schemaDrift===void 0?void 0:{schemaDrift:t.schemaDrift};return w(t.error,f)}const{reblessSchemaBaseline:a,validation:o}=t,i=t.target,s=nr(e);if(s!==void 0)return w(s);const c=await Ke(r,e);if(c!==void 0)return w(c);Ge(r,e.logger);const{error:l,mintedSecretsFile:d}=await rr(r,e,n,i);if(l!==void 0)return e.logger.error(l),{code:1,descriptor:void 0,error:l,mintedSecretsFile:d,validation:o};const g=fr(r,e,i);e.logger.info(`deploying via ${g.command} ${g.args.join(" ")}`);const m=await(e.spawner??S)(g);return g.captureStdoutSilently===!0&&m.stdout!==void 0&&m.stdout!==""&&process.stderr.write(m.stdout),m.code!==0?{code:m.code,descriptor:g,mintedSecretsFile:d,validation:o}:hr({cwd:r,descriptor:g,mintedSecretsFile:d,options:e,reblessSchemaBaseline:a,stdout:m.stdout,validation:o})},pr=async e=>{const r=De("deploy",e.format);if(r!==void 0)return e.logger.error(r),w(r);const n=Ee(e.format,e.logger),t=e.dryRun===!0?Ue(e.cwd??process.cwd()):void 0;let a;try{if(a=await yr({...e,logger:n}),a.code===0&&e.emitBindings!==void 0){const{error:o}=ve({destination:e.emitBindings,logger:n,projectRoot:e.cwd??process.cwd()});o!==void 0&&(n.error(o),a={...a,code:1})}}finally{t?.()}if($(e.format))return Re(a),a;if(a.code===0&&e.dryRun!==!0&&e.preview!==!0)Le({cwd:e.cwd??process.cwd(),env:e.env,logger:e.logger,mintedSecretsFile:a.mintedSecretsFile,url:a.deployment?.url});else if(a.code===0&&e.preview===!0){const o=a.deployment?.url;e.logger.success(o===void 0?"preview version uploaded":`preview version uploaded — ${o}`)}return a},Hr=ye(async({cwd:e,logger:r,options:n})=>({code:(await pr({allowSchemaDrift:n.allowSchemaDrift===!0,apiSpec:fe(n.apiSpec),cwd:e,dryRun:n.dryRun===!0,env:n.env,format:n.format,healthCheck:n.healthCheck===!0,logger:r,migrate:n.migrate===!0,migrateToken:n.migrateToken,migrateUrl:O({cwd:e,env:n.env,url:n.migrateUrl}),migrateYes:n.migrateYes===!0,preview:n.preview===!0,skipCodegen:n.prebuilt===!0,strictAdvisories:n.strictAdvisories,target:n.target,temporary:n.temporary===!0,updateSchemaBaseline:n.updateSchemaBaseline===!0})).code}));export{Hr as execute,Ye as provisionBindings,pr as runDeployCommand,vr as runPreDeployPipeline};
|
|
7
|
+
`,"utf8"),r.info(`.gitignore: added ${o.join(", ")} so the recorded secret cannot be committed`)}catch(t){r.warn(`could not update .gitignore (${t instanceof Error?t.message:String(t)}) — add \`${D.join("` and `")}\` by hand before committing.`)}},er=(e,r,n)=>{if(n.length===0)return;const t=n.map(s=>s.key).join(", ");if(r.env!==void 0&&!Qe.test(r.env)){r.logger.warn(`${t}: minted and pushed for --env ${r.env}, but "${r.env}" isn't a safe filename fragment — the value could not be recorded. Capture it manually if you need it again.`);return}const a=r.env===void 0?y:`${y}.${r.env}`;Ze(e,r.logger);const o=h(e,a);let i=v(o)?p(o,"utf8"):"";for(const s of n)i=J(i,s.key,s.value);return Q(o,i),r.logger.success(r.env===void 0?`${t}: value(s) recorded in ${a}`:`${t}: value(s) recorded in ${a} (kept separate from ${y} so \`lunora dev\` and a plain \`lunora env push\` don't inherit the --env ${r.env} value)`),a},rr=async(e,r,n,t)=>{if(r.dryRun===!0||r.preview===!0)return{};const{logger:a}=r,o=r.env===void 0?"":` --env ${r.env}`;let i;try{i=await(r.secretLister??Pe)({cwd:e,env:r.env,temporary:r.temporary})}catch{return{}}if(!i.ok)return{};const s=new Set(i.names),l=(await ze(e)).filter(u=>!s.has(u));if(l.length===0)return{};if(!n)return{error:`missing required secret(s) on the deploy target: ${l.join(", ")}. Set them with \`wrangler secret put <KEY>${o}\` (or \`lunora env generate --set\` then \`lunora env push --yes${o}\`), then re-deploy.`};for(const u of l.filter(m=>!P(m)))a.warn(`required secret ${u} is not set on the target — set it with: wrangler secret put ${u}${o}`);const d=l.filter(u=>P(u));if(d.length===0)return{};if(await(r.secretConfirm??Ce())(`${String(d.length)} required secret(s) not set on the target (${d.join(", ")}). Generate strong values and push them now?`)){const{minted:u,ok:m}=await Je(e,r,d,t),f=er(e,r,u);return m?{mintedSecretsFile:f}:{error:"failed to push required secret(s) — set them manually and re-deploy",mintedSecretsFile:f}}return a.warn(`${String(d.length)} required secret(s) not set on the target: ${d.join(", ")}. Generate + push with \`lunora env generate --set\` then \`lunora env push --yes${o}\`.`),{}},tr=async(e,r)=>{const n=new se({skipAddingFilesFromTsConfig:!0}),t=h(r,"lunora");let a;try{a=V(n,t)}catch(o){const i=o instanceof Error?o.message:String(o);return e.logger.warn(`--migrate: could not discover migrations (${i}); skipping`),0}if(a.length===0)return e.logger.info("--migrate: no data migrations declared in lunora/"),0;e.logger.info(`--migrate: running ${String(a.length)} migration(s) against deployed worker`);for(const o of a){e.logger.info(`--migrate: up "${o.id}" (table "${o.table}")`);const i={cwd:r,fetchImpl:e.fetchImpl,id:o.id,logger:e.logger,prod:!0,subcommand:"up",token:e.migrateToken,url:e.migrateUrl,yes:e.migrateYes===!0},s=await _e(i);if(s.code!==0)return e.logger.error(`--migrate: migration "${o.id}" failed — see output above`),s.code;e.logger.success(`--migrate: "${o.id}" applied`)}return 0},nr=e=>{if(!e.migrate||e.dryRun||e.preview)return;if(e.migrateUrl===void 0){const n="--migrate requires --migrate-url <https://your-worker> — the deploy target URL is only known after wrangler runs, and this gate runs before it; refusing to default to localhost";return e.logger.error(n),n}if(e.migrateYes!==!0){const n="--migrate runs production data migrations after deploy. Re-run with --migrate-yes to confirm.";return e.logger.error(n),n}const r=e.migrateToken??process.env.LUNORA_ADMIN_TOKEN;if(r===void 0||r===""){const n="admin token required for --migrate — pass --migrate-token or set LUNORA_ADMIN_TOKEN";return e.logger.error(n),n}},ar=async(e,r,n,t,a,o,i,s)=>{let c;r?(c=new ie({name:"dots"}),c.start("running codegen")):n.info("running codegen");try{const l=B({apiSpec:t,projectRoot:e,target:a});c?.succeed("codegen complete"),c||n.success("codegen complete");const d=ge(l.platformDiagnostics,n);if(d.errors.length>0)return{error:d.errors.join("; ")};const{errorAdvisories:g,names:u,shouldBlock:m}=me(l.advisories,s);if(m){const C=`${g.length.toString()} ERROR-level ${g.length===1?"advisory":"advisories"} (${u.join(", ")}). Pass --no-strict-advisories to downgrade this to a warning and continue.`;return n.error(C),{error:C}}const f=await q({cwd:e,logger:n,spawner:o,stdoutToStderr:i});return f.error!==void 0?{error:f.error}:{result:l}}catch(l){c?.failed("codegen failed");const d=l instanceof Error?l.message:String(l);return n.error(`codegen failed: ${d}`),{error:`codegen failed: ${d}`}}},or=(e,r,n="deploy",t)=>{const a=Ve(e,t);if(a===void 0)return;const o=`${n} blocked: the "${a}" D1 binding has a placeholder database_id ("${H}"). Run \`wrangler d1 create <name>\` to create the database, then replace the placeholder in wrangler.jsonc with the real id before deploying.`;return r.error(o),o},ir=(e,r,n="deploy",t)=>{const a=A(e,t)?.vars;if(!a)return;const o=Fe.filter(s=>typeof a[s]=="string"&&We(a[s]));if(o.length===0)return;const i=`${n} blocked: ${o.join(", ")} in wrangler.jsonc point at localhost. A deployed Worker can't reach a loopback address, so this silently breaks scheduled-job dispatch, reverse cross-shard relations, and auth callbacks. Set each to the deployed worker's public URL (or move it to a secret with \`wrangler secret put\`) before deploying.`;return r.error(i),i},sr=async(e,r)=>{const{info:n}=X(r,"lunora"),t=n?.vectorMetadata??[];if(t.length===0)return;const a=[];for(const s of t){const c=le(s.kind);if(c===void 0){e.logger.warn(`vector index "${s.index}" declares metadata "${s.property}", whose column type cannot be filtered on in Vectorize — it is stored with each vector but no filter will match it.`);continue}a.push({index:s.index,property:s.property,type:c})}if(a.length===0)return;const i=(await de({cwd:r,entries:a,exec:k(b(r),"wrangler",[]),logger:e.logger,spawner:e.spawner??S})).filter(s=>s.status!=="failed").length;i>0&&e.logger.success(`vectorize metadata indexes ready: ${String(i)}/${String(a.length)}`)},N=5,cr=2e3,lr=async(e,r,n)=>{if(e.healthCheck!==!0)return;const t=n??O({cwd:r,env:e.env});if(t===void 0){const o="--health-check: the deploy succeeded, but no URL to probe could be resolved — wrangler's output carried none and this checkout has no link for this environment. Run `lunora link --url <https://your-worker>` and re-deploy, or drop --health-check.";return e.logger.error(o),{error:o,ok:!1,url:""}}const a=await be({attempts:N,baseUrl:t,delayMs:cr,fetchImpl:e.healthFetch,paths:[$e,Se],sleep:e.healthSleep});return a.error===void 0?(e.logger.success(`health check ok (${a.url})`),{ok:!0,url:a.url}):(e.logger.error(`--health-check: the deploy succeeded, but the new version did not answer after ${String(N)} attempt(s) — ${a.error}`),{error:a.error,ok:!1,url:a.url})},dr=async(e,r,n,t,a,o)=>{await sr(e,r);const i=e.migrate?await tr(e,r):0;return i===0&&a?.(),{code:i,descriptor:n,mintedSecretsFile:o,validation:t}},ur=(e,r,n)=>{const t=or(e,r.logger,n,r.env);if(t!==void 0)return t;const a=ir(e,r.logger,n,r.env);if(a!==void 0)return a;const o=Be(e,r.logger,n);return o!==void 0?o:He(e,r.logger,r.dockerAvailable??we,n,r.env)},gr=(e,r,n)=>{const t=Me(e);t!==void 0&&r.logger.info(`class-B composition: deploying ${t} (overrides wrangler main)`),r.temporary&&r.logger.info("temporary account: deploying to a short-lived Cloudflare account (~60min); wrangler will print a claim URL"),r.dryRun&&r.logger.info("dry run: validating + bundling without publishing"),r.outDir!==void 0&&r.logger.info(`build artifact: emitting bundle to ${r.outDir}`);const a=R(n),o={dryRun:r.dryRun,entry:t,environment:r.env,outDir:r.outDir,preview:r.preview,temporary:r.temporary};if(a.toolchain===void 0)throw new Error(`deploy target "${a.id}" has no command-line toolchain`);return a.toolchain.deploy(o)},w=(e,r)=>({code:1,descriptor:void 0,error:e,validation:{problems:[],wranglerPath:void 0},...r}),mr=(e,r)=>{for(const n of e.report?.warnings??[])r.warn(`wrangler.jsonc: ${n}`);if(e.problems.length===0)return!1;r.error("wrangler.jsonc validation failed:");for(const n of e.problems)r.error(` - ${n}`);return!0},fr=(e,r,n)=>{const t=$(r.format),a=r.dryRun!==!0,o=gr(e,r,n),i=k(b(e),o.tool,o.args);return{args:i.args,captureStdout:a&&!t,captureStdoutSilently:a&&t,command:i.command,cwd:e,stdoutToStderr:t&&!a}},hr=async({cwd:e,descriptor:r,mintedSecretsFile:n,options:t,reblessSchemaBaseline:a,stdout:o,validation:i})=>{const s={deployedAt:new Date().toISOString(),dryRun:t.dryRun===!0,env:t.env,preview:t.preview===!0,url:t.dryRun===!0?void 0:Ne(o),workerName:E(e)};if(t.dryRun===!0||t.preview===!0)return t.healthCheck===!0&&t.logger.warn(`--health-check skipped: ${t.dryRun===!0?"a dry run publishes nothing":"a preview version serves no live traffic"}`),{code:0,deployment:s,descriptor:r,mintedSecretsFile:n,validation:i};t.temporary!==!0&&Te({cwd:e,env:t.env,logger:t.logger,url:s.url});const c=await lr(t,e,s.url);return c?.error!==void 0?{code:1,deployment:s,descriptor:r,healthCheck:c,mintedSecretsFile:n,validation:i}:{...await dr(t,e,r,i,a,n),deployment:s,healthCheck:c}},vr=async(e,r)=>{const n=e.cwd??process.cwd(),t=M(e),a=ue(e),o={problems:[],wranglerPath:void 0},i=he(n,e.target);if(i.target===void 0){const u=i.error??"unknown deploy target";return e.logger.error(u),{error:u,validation:o}}const{target:s}=i;let c;if(!e.skipCodegen){const u=await ar(n,t,e.logger,e.apiSpec,s,e.spawner,$(e.format),a);if(u.error!==void 0)return{error:u.error,target:s,validation:o};c=u.result}let l;if(c!==void 0){const u=ke({allowDrift:e.allowSchemaDrift===!0,codegen:c,command:r,logger:e.logger,updateBaseline:e.updateSchemaBaseline===!0});if(u.blocked)return{error:`schema drift gate blocked ${r}`,schemaDrift:{blocked:!0,reason:u.reason},target:s,validation:o};l=u.rebless}await Ye(n,e.logger,c?.cronTriggers,s,e.env);const d=ur(n,e,r);if(d!==void 0)return{error:d,target:s,validation:o};const g=Z({environment:e.env,projectRoot:n});return mr(g,e.logger)?{error:"wrangler validation failed",target:s,validation:g}:{codegen:c,reblessSchemaBaseline:l,target:s,validation:g}},yr=async e=>{const r=e.cwd??process.cwd(),n=M(e),t=await vr(e,e.commandName??"deploy");if(t.error!==void 0){if(t.validation.problems.length>0)return{code:1,descriptor:void 0,error:t.error,validation:t.validation};const f=t.schemaDrift===void 0?void 0:{schemaDrift:t.schemaDrift};return w(t.error,f)}const{reblessSchemaBaseline:a,validation:o}=t,i=t.target,s=nr(e);if(s!==void 0)return w(s);const c=await Ke(r,e);if(c!==void 0)return w(c);Ge(r,e.logger);const{error:l,mintedSecretsFile:d}=await rr(r,e,n,i);if(l!==void 0)return e.logger.error(l),{code:1,descriptor:void 0,error:l,mintedSecretsFile:d,validation:o};const g=fr(r,e,i);e.logger.info(`deploying via ${g.command} ${g.args.join(" ")}`);const m=await(e.spawner??S)(g);return g.captureStdoutSilently===!0&&m.stdout!==void 0&&m.stdout!==""&&process.stderr.write(m.stdout),m.code!==0?{code:m.code,descriptor:g,mintedSecretsFile:d,validation:o}:hr({cwd:r,descriptor:g,mintedSecretsFile:d,options:e,reblessSchemaBaseline:a,stdout:m.stdout,validation:o})},pr=async e=>{const r=De("deploy",e.format);if(r!==void 0)return e.logger.error(r),w(r);const n=Re(e.format,e.logger),t=e.dryRun===!0?Ue(e.cwd??process.cwd()):void 0;let a;try{if(a=await yr({...e,logger:n}),a.code===0&&e.emitBindings!==void 0){const{error:o}=ve({destination:e.emitBindings,logger:n,projectRoot:e.cwd??process.cwd()});o!==void 0&&(n.error(o),a={...a,code:1})}}finally{t?.()}if($(e.format))return Ee(a),a;if(a.code===0&&e.dryRun!==!0&&e.preview!==!0)Le({cwd:e.cwd??process.cwd(),env:e.env,logger:e.logger,mintedSecretsFile:a.mintedSecretsFile,url:a.deployment?.url});else if(a.code===0&&e.preview===!0){const o=a.deployment?.url;e.logger.success(o===void 0?"preview version uploaded":`preview version uploaded — ${o}`)}return a},Hr=ye(async({cwd:e,logger:r,options:n})=>({code:(await pr({allowSchemaDrift:n.allowSchemaDrift===!0,apiSpec:fe(n.apiSpec),cwd:e,dryRun:n.dryRun===!0,env:n.env,format:n.format,healthCheck:n.healthCheck===!0,logger:r,migrate:n.migrate===!0,migrateToken:n.migrateToken,migrateUrl:O({cwd:e,env:n.env,url:n.migrateUrl}),migrateYes:n.migrateYes===!0,preview:n.preview===!0,skipCodegen:n.prebuilt===!0,strictAdvisories:n.strictAdvisories,target:n.target,temporary:n.temporary===!0,updateSchemaBaseline:n.updateSchemaBaseline===!0})).code}));export{Hr as execute,Ye as provisionBindings,pr as runDeployCommand,vr as runPreDeployPipeline};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{existsSync as m,mkdirSync as L,writeFileSync as v,readFileSync as x,readdirSync as ie,rmSync as R,lstatSync as le,mkdtempSync as ce,copyFileSync as Ke,renameSync as qe}from"node:fs";import{tmpdir as de}from"node:os";import{installArgsFor as ue,execArgsFor as Ge,detectFramework as Ye,isInteractive as w,LUNA_ART as Je,LUNA_NAME as Xe,LUNA_SIGNOFF as Qe,BADGES as g,paintAnswer as Ze,detectPackageManager as H,detectInstalledManagers as et,runScriptCommand as tt,detectLintTools as rt,addArgsFor as at,applyLintIgnores as ot}from"@lunora/config";import{walkSync as nt}from"@visulima/fs";import{join as p,dirname as M,basename as N,resolve as pe,relative as he}from"@visulima/path";import{downloadTemplate as me}from"giget";import{modify as st,applyEdits as it}from"jsonc-parser";import{join as z,dirname as lt}from"node:path";import{d as ct}from"../packem_shared/command-
|
|
1
|
+
import{existsSync as m,mkdirSync as L,writeFileSync as v,readFileSync as x,readdirSync as ie,rmSync as R,lstatSync as le,mkdtempSync as ce,copyFileSync as Ke,renameSync as qe}from"node:fs";import{tmpdir as de}from"node:os";import{installArgsFor as ue,execArgsFor as Ge,detectFramework as Ye,isInteractive as w,LUNA_ART as Je,LUNA_NAME as Xe,LUNA_SIGNOFF as Qe,BADGES as g,paintAnswer as Ze,detectPackageManager as H,detectInstalledManagers as et,runScriptCommand as tt,detectLintTools as rt,addArgsFor as at,applyLintIgnores as ot}from"@lunora/config";import{walkSync as nt}from"@visulima/fs";import{join as p,dirname as M,basename as N,resolve as pe,relative as he}from"@visulima/path";import{downloadTemplate as me}from"giget";import{modify as st,applyEdits as it}from"jsonc-parser";import{join as z,dirname as lt}from"node:path";import{d as ct}from"../packem_shared/command-CrAs0XG_.mjs";import dt from"magic-string";import{Project as ut,SyntaxKind as f}from"ts-morph";import{P as K}from"../packem_shared/prompt-cancelled-C8Sj7OqI.mjs";import{l as fe,m as pt,n as ge,o as ve,b as ht}from"../packem_shared/resolve-B9ReA3FV.mjs";import{defaultSpawner as we}from"../packem_shared/createRecordingSpawner-DJlNacZ6.mjs";import{d as mt,e as ft,f as gt,a as ye,t as q,g as be,h as vt,b as xe,i as ke,w as wt,j as yt,k as Ce,l as bt}from"../packem_shared/tui-prompts-DzYd2fL3.mjs";import{A as Se,E as Le,p as xt,w as kt,M as Ct,r as St,k as Lt,e as Mt,c as Me,l as Ae,i as At,f as Et}from"../packem_shared/storage-B0ixDDxG.mjs";import{logStep as J}from"../packem_shared/createLogger-Cl18I8AX.mjs";import{r as Nt}from"../packem_shared/lint-ignore-report-DKZagpqk.mjs";import It from"node:dns/promises";import{r as _t}from"../packem_shared/commands-I18aR_DJ.mjs";const G={bun:{githubCacheKey:void 0,githubSetupStep:` - uses: oven-sh/setup-bun@v2
|
|
2
2
|
`,gitlabImage:"oven/bun:1",gitlabProvisionScript:[],installCmd:"bun install --frozen-lockfile",lockfile:"bun.lockb"},npm:{githubCacheKey:"npm",githubSetupStep:"",gitlabImage:"node:22",gitlabProvisionScript:[],installCmd:"npm ci",lockfile:"package-lock.json"},pnpm:{githubCacheKey:"pnpm",githubSetupStep:` - uses: pnpm/action-setup@v4
|
|
3
3
|
with:
|
|
4
4
|
version: latest
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{existsSync as f,mkdirSync as _,writeFileSync as b,mkdtempSync as N,rmSync as M,readFileSync as k}from"node:fs";import{tmpdir as x}from"node:os";import{discoverSchema as U,readPackageDependencies as C,discoverMigrations as F}from"@lunora/codegen";import{isInteractive as O,promptSelect as P,promptText as D}from"@lunora/config";import{LunoraError as $}from"@lunora/errors";import{join as c}from"@visulima/path";import{Project as v}from"ts-morph";import{r as z,t as j}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{n as q,r as L}from"../packem_shared/admin-url-BhF5ufg1.mjs";import{d as B}from"../packem_shared/command-
|
|
1
|
+
import{existsSync as f,mkdirSync as _,writeFileSync as b,mkdtempSync as N,rmSync as M,readFileSync as k}from"node:fs";import{tmpdir as x}from"node:os";import{discoverSchema as U,readPackageDependencies as C,discoverMigrations as F}from"@lunora/codegen";import{isInteractive as O,promptSelect as P,promptText as D}from"@lunora/config";import{LunoraError as $}from"@lunora/errors";import{join as c}from"@visulima/path";import{Project as v}from"ts-morph";import{r as z,t as j}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{n as q,r as L}from"../packem_shared/admin-url-BhF5ufg1.mjs";import{d as B}from"../packem_shared/command-CrAs0XG_.mjs";import{diffSnapshots as H,renderMigrationFile as G}from"../packem_shared/diffSnapshots-DtC5Cs4Z.mjs";import{r as W}from"../packem_shared/resolve-target-BRvw8Pf7.mjs";import J from"../packem_shared/schemaIrToSnapshot-irmd5g0Y.mjs";import{readAndLogBody as V}from"./runRpcCommand.mjs";import{runExportCommand as Z}from"../packem_shared/runExportCommand-Dq-SpjAe.mjs";import{r as K}from"../packem_shared/import-Dqd1MOOv.mjs";const m="__lunora_reproject__",X=e=>{if(!e.startsWith(m))return;const r=e.slice(m.length);return r===""?void 0:r},Q=".snapshot.json",A=/[^\da-z]+/gu,E=(e,r)=>{let a=0,t=e.length;for(;a<t&&e[a]===r;)a+=1;for(;t>a&&e[t-1]===r;)t-=1;return e.slice(a,t)},Y=e=>{const r=E(e.toLowerCase().replaceAll(A,"_"),"_");return r===""?"auto":r},ee=e=>{const r=(a,t=2)=>a.toString().padStart(t,"0");return`${String(e.getUTCFullYear())}${r(e.getUTCMonth()+1)}${r(e.getUTCDate())}${r(e.getUTCHours())}${r(e.getUTCMinutes())}${r(e.getUTCSeconds())}`},re=e=>{if(f(e))try{const r=k(e,"utf8"),a=JSON.parse(r);if(a.version!==1)throw new $("INTERNAL",`unsupported snapshot version: ${a.version}`);return a}catch(r){const a=r instanceof Error?r.message:String(r);throw new $("INTERNAL",`failed to read ${e}: ${a}`,{cause:r})}},te=e=>{const r=e.cwd??process.cwd(),a=c(r,"lunora","schema.ts");if(!f(a))return e.logger.error(`schema not found: ${a} — run \`vis generate lunora-table --name=<name>\` to create one`),{code:1,empty:!0,migrationFile:""};const t=new v({skipAddingFilesFromTsConfig:!0}),n=U(t,a),s=J(n),o=c(r,"lunora","migrations"),i=c(o,Q);let l;try{l=re(i)}catch(h){return e.logger.error(h instanceof Error?h.message:String(h)),{code:1,empty:!0,migrationFile:""}}const d=H(l,s);if(d.empty)return e.logger.info("no schema changes detected — snapshot is already up to date"),{code:0,empty:!0,migrationFile:""};const p=(e.now??(()=>new Date))(),w=Y(e.name??"auto"),y=`${ee(p)}_${w}.sql`,g=c(o,y);_(o,{recursive:!0});const R=G(w,d,p.toISOString());return b(g,R,"utf8"),b(i,`${JSON.stringify(s,void 0,4)}
|
|
2
2
|
`,"utf8"),e.logger.success(`wrote ${g}`),d.unsupported.length>0&&e.logger.warn(`${String(d.unsupported.length)} unsupported diff(s) — see the comment block in ${y} and write the SQL manually`),{code:0,empty:!1,migrationFile:g}},ae="migrations.ts",S=/^[A-Za-z_]\w*$/u,ne=new Set(["await","break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","false","finally","for","function","if","implements","import","in","instanceof","interface","let","new","null","package","private","protected","public","return","static","super","switch","this","throw","true","try","typeof","var","void","while","with","yield"]),T=/^import\s*\{\s*defineMigration\s*\}\s*from\s*["'](?:@lunora\/server|lunorash\/server)["'][^\n]*$/mu,oe=e=>`import { defineMigration } from "${C(e)?.has("lunorash")??!1?"lunorash/server":"@lunora/server"}";`,ie="__lunora_admin__:runMigration",se="__lunora_admin__:migrationStatus",ce="/_lunora/migrate",le=e=>E(e.trim().toLowerCase().replaceAll(A,"-"),"-"),de=e=>e.split("-").filter(r=>r.length>0).map((r,a)=>a===0?r:r.charAt(0).toUpperCase()+r.slice(1)).join(""),ue=e=>{const r=c(e,"lunora","schema.ts");if(!f(r))return[];try{const a=new v({skipAddingFilesFromTsConfig:!0});return U(a,r).tables.map(t=>t.name)}catch{return[]}},me=async e=>e.length>0?P("Which table does this migration iterate?",e.map(r=>({label:r,value:r}))):D("Target table for the migration: "),fe=async(e,r)=>{if(r.table!==void 0)return r.table;const a=r.promptTable??(O()?me:void 0);if(a===void 0){r.logger.error("migrate create requires a target table when not running interactively — re-run with --table <table>");return}const n=(await a(ue(e)))?.trim();if(n===void 0||n===""){r.logger.error("no table selected — re-run with --table <table>");return}return n},ge=async e=>{const r=e.cwd??process.cwd(),a=le(e.name);if(a==="")return e.logger.error(`invalid migration name: "${e.name}" — must contain at least one alphanumeric character`),{code:1,file:""};const t=de(a);if(!S.test(t)||ne.has(t))return e.logger.error(`invalid migration name: "${e.name}" derives the export \`${t}\`, which is not a valid identifier — pick a name that starts with a letter and isn't a reserved word`),{code:1,file:""};const n=await fe(r,e);if(n===void 0)return{code:1,file:""};if(!S.test(n))return e.logger.error(`invalid table: "${n}" — must be a valid identifier ([A-Za-z_][A-Za-z0-9_]*)`),{code:1,file:""};const s=c(r,"lunora"),o=c(s,ae);let i=f(o)?k(o,"utf8"):"";if(i.includes(`id: "${a}"`)||new RegExp(String.raw`\bexport const ${t}\b`,"u").test(i))return e.logger.error(`a migration with id "${a}" (export \`${t}\`) already exists in ${o}`),{code:1,file:""};const l=oe(r);i.trim()===""?i=`${l}
|
|
3
3
|
`:T.test(i)?i=i.replace(T,l):i=`${l}
|
|
4
4
|
${i}`;const d=`export const ${t} = defineMigration({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync as i,rmSync as d}from"node:fs";import{join as n,relative as m}from"@visulima/path";import{d as f}from"../packem_shared/command-
|
|
1
|
+
import{existsSync as i,rmSync as d}from"node:fs";import{join as n,relative as m}from"@visulima/path";import{d as f}from"../packem_shared/command-CrAs0XG_.mjs";import{b as a}from"../packem_shared/tui-prompts-DzYd2fL3.mjs";const l=async e=>{const o=e.cwd??process.cwd(),t=[n(o,".wrangler","state")];if(e.all&&t.push(n(o,".lunora-cache")),!e.yes){const r=t.map(s=>m(o,s)).join(" and ");if(!process.stdin.isTTY&&e.confirm===void 0)return e.logger.error(`reset: stdin is not a TTY — re-run with --yes to confirm deleting ${r}`),{code:1,removed:[]};if(!await(e.confirm??a)(`This will delete ${r}. Continue?`))return e.logger.info("reset: aborted"),{code:1,removed:[]}}const c=[];for(const r of t)i(r)?(d(r,{force:!0,recursive:!0}),c.push(r),e.logger.success(`removed ${r}`)):e.logger.info(`skipped (not present): ${r}`);return{code:0,removed:c}},p=f(({cwd:e,logger:o,options:t})=>l({all:t.all===!0,cwd:e,logger:o,yes:t.yes===!0}));export{p as execute,l as runResetCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as l}from"@lunora/errors";import{r as y,d as v}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{r as A,a as b}from"../packem_shared/admin-url-BhF5ufg1.mjs";import{d as N}from"../packem_shared/command-
|
|
1
|
+
import{LunoraError as l}from"@lunora/errors";import{r as y,d as v}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{r as A,a as b}from"../packem_shared/admin-url-BhF5ufg1.mjs";import{d as N}from"../packem_shared/command-CrAs0XG_.mjs";import{a as _}from"../packem_shared/resolve-target-BRvw8Pf7.mjs";const f=(r,t="--args")=>{if(r===void 0||r.length===0)return{};let e;try{e=JSON.parse(r)}catch(a){const n=a instanceof Error?a.message:String(a);throw new l("INTERNAL",`failed to parse ${t} as JSON: ${n}`,{cause:a})}if(typeof e!="object"||e===null||Array.isArray(e))throw new l("INTERNAL",`${t} must be a JSON object (e.g. '{"id":1}'), got ${Array.isArray(e)?"an array":typeof e}`);return e},S=/\/$/u,P="__lunora_admin__:runAs",I="__lunora_admin__:",O=async(r,t)=>{const e=await r.text();let a;try{a=JSON.parse(e)}catch{a=e}return t.info(JSON.stringify(a,void 0,2)),a},$=(r,t)=>{const e=t.body?.error?.code;t.runAs||t.status!==403||e!=="FORBIDDEN_SHARD"||r.info("this app authorizes per shard, so an anonymous call is denied — retry with --as <userId> to run as an authenticated user")},R=({args:r,claims:t,options:e,runAs:a})=>{const n=a?{args:{args:r,functionPath:e.functionPath,identity:t,userId:e.as},functionPath:P}:{args:r,functionPath:e.functionPath};return e.shard!==void 0&&(n.shardKey=e.shard),n},T=({cwd:r,logger:t,needsBearer:e,url:a})=>e?A(a,t,r):(_({cwd:r,url:a})??b(r)).replace(S,""),k=({args:r,claims:t},e)=>{try{return{args:f(r),claims:t===void 0?void 0:f(t,"--claims")}}catch(a){e.error(a instanceof Error?a.message:String(a));return}},E=async r=>{const t=r.cwd??process.cwd(),e=r.as!==void 0&&r.as!=="";if(r.claims!==void 0&&!e)return r.logger.error("--claims requires --as <userId> — extra identity claims only travel inside the admin-gated `runAs` dispatch."),{body:void 0,code:1,requestUrl:r.url??""};const a=e||r.functionPath.startsWith(I),n=T({cwd:t,logger:r.logger,needsBearer:a,url:r.url});if(n===void 0)return{body:void 0,code:1,requestUrl:r.url??""};const s=`${n}/_lunora/rpc`,i=r.fetchImpl??globalThis.fetch;if(typeof i!="function")throw new TypeError("no fetch implementation available — pass --fetch via dependency injection or run on Node >= 18");const c=k(r,r.logger);if(c===void 0)return{body:void 0,code:1,requestUrl:s};const{source:g,token:o}=a?y({cwd:t,token:r.token,url:n}):{};if(a&&o===void 0)return r.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{body:void 0,code:1,requestUrl:s};o!==void 0&&r.logger.debug?.(`admin bearer from ${v(g)}`);const h={"content-type":"application/json",...o===void 0?{}:{authorization:`Bearer ${o}`}},m=R({args:c.args,claims:c.claims,options:r,runAs:e});r.logger.info(`POST ${s} -> ${r.functionPath}${e?` (as ${r.as??""})`:""}`);const d=await i(s,{body:JSON.stringify(m),headers:h,method:"POST"}),u=await O(d,r.logger);return $(r.logger,{body:u,runAs:e,status:d.status}),{body:u,code:d.ok?0:1,requestUrl:s}},L=N(({argument:r,cwd:t,logger:e,options:a})=>{const n=r[0];return n?E({args:a.args,as:a.as,claims:a.claims,cwd:t,functionPath:n,logger:e,shard:a.shard,token:a.token,url:a.url}):(e.error("missing function path. Usage: lunora run <functionPath> [--args <json>]"),{code:1})});export{L as execute,O as readAndLogBody,E as runRpcCommand};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{C as a,R as s,V as C,r as N}from"./cli-D87Rz8eI.mjs";import"./createLogger-Cl18I8AX.mjs";export{a as COMMANDS,s as REGISTERED_COMMAND_NAMES,C as VERSION,N as runCli};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{mkdirSync as A,readFileSync as k,lstatSync as B,writeFileSync as D}from"node:fs";import{join as u,dirname as f}from"node:path";import{fileURLToPath as E}from"node:url";import{resolveHint as L,isLunoraError as S,flattenHint as I,findSolutionByMessage as j}from"@lunora/errors";import{createCerebro as _}from"@visulima/cerebro";import T from"@visulima/cerebro/command/completion";import P from"@visulima/cerebro/command/version";import{A as d,T as s}from"./deploy-target-DCWwiuAe.mjs";import{SDK_LANGUAGES as M}from"@lunora/codegen";import{setCommandLogger as y,createLogger as x}from"./createLogger-Cl18I8AX.mjs";import{VisulimaError as U,renderError as W}from"@visulima/error";import{homedir as J}from"node:os";import{addArgsFor as K,detectPackageManager as F}from"@lunora/config";const H={argument:{description:"Feature or registry item: ai | auth | email | storage | crons | presence | queue | workflow | flags | backup | …",name:"feature",type:String},description:"Add a feature or registry item (ai, auth, email, storage, crons, …) to the current Lunora project",examples:[["lunora add auth","Add authentication (asks which provider)"],["lunora add auth --provider clerk","Add Clerk auth without prompting"],["lunora add auth-ui","Add copy-in auth screens for your framework (auto-detected)"],["lunora add email","Add transactional email (Cloudflare Email Workers + dev mail catcher)"],["lunora add storage","Add the R2 storage registry item (asks for the bucket name)"],["lunora add storage --bucket my-app-uploads","Add storage with a bucket name, no prompt"],["lunora add crons","Add the scheduled-jobs registry item"],["lunora add storage --ref alpha","Add an item from the alpha branch's registry"]],group:"Project",loader:()=>import("../packem_chunks/handler.mjs").then(e=>({default:e.execute})),name:"add",options:[{description:"auth: provider to use without prompting (auth | clerk | auth0)",name:"provider",type:String},{description:"auth: D1 database name to use without prompting (lowercase alphanumeric + hyphens)",name:"db",type:String},{description:"storage: R2 bucket name to use without prompting (lowercase alphanumeric + hyphens)",name:"bucket",type:String},{description:"email: verified destination address to use without prompting",name:"mail-to",type:String},{description:"Skip prompts (auth provider, DB name, bucket name, mail destination) and use the defaults",name:"yes",type:Boolean},{description:"Local registry root (offline; expects <name>/ subdirs)",name:"from",type:String},{description:"Override the remote registry source base (e.g. gh:owner/repo/registry)",name:"source",type:String},{description:"Fetch items from a git ref (branch, tag, or commit), e.g. --ref alpha. Overrides the version-derived default",name:"ref",type:String},{description:"Permit --source values outside gh:/github:/https://",name:"allow-unsafe-source",type:Boolean},{description:"Output format: pretty (default) or json",name:"format",type:String}]},v="lunora.advisor.map.json",$={description:"Score your app's advisor findings into a health map, and gate CI on it",examples:[["lunora advisor","Score the app and write lunora.advisor.map.json"],["lunora advisor --all","Show every procedure as a check matrix"],["lunora advisor --entry messages#sendMessage","Inspect one procedure"],["lunora advisor --min-score 80","Exit non-zero when the score drops below 80"],["lunora advisor --baseline","Fail on any regression against the committed map"]],group:"Develop",loader:()=>import("../packem_chunks/handler19.mjs").then(e=>({default:e.execute})),name:"advisor",options:[{description:"Show every procedure as a check matrix, not just the ones with findings",name:"all",type:Boolean},{description:`Compare against a committed map and fail on regression (default ${v})`,name:"baseline",type:String},{description:"Inspect a single procedure by `file#exportName`",name:"entry",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Exit non-zero when the global score is below this value (0-100)",name:"min-score",type:String},{description:`Where to write the map (default ${v})`,name:"out",type:String},{description:"Write the map artifact to disk (the default)",name:"write",type:Boolean},{description:"Don't write the map artifact to disk — report only",name:"no-write",type:Boolean}]},V={description:"Run wrangler dry-run and report bundle size, top modules, and _generated files",examples:[["lunora analyze","Report the worker bundle size + heaviest modules"]],group:"Deploy",loader:()=>import("../packem_chunks/handler2.mjs").then(e=>({default:e.execute})),name:"analyze",options:[{description:"Emit a JSON report instead of human text",name:"json",type:Boolean}]},G={argument:{description:"create | list | restore <id|file> | retention | prune | pitr",name:"subcommand",type:String},description:"Managed snapshot backups (create | list | restore) to a directory or an R2 bucket, plus native point-in-time recovery (pitr)",examples:[["lunora backup create","Snapshot every table to a backup file"],["lunora backup list","List recorded snapshots"],["lunora backup restore <id>","Restore a snapshot by id"],["lunora backup create --bucket default","Snapshot into an R2 bucket instead of a directory"],["lunora backup restore <id> --bucket default --verify","Restore from R2, checksum first"],["lunora backup retention","Show what the platform's retention would delete next"],["lunora backup prune","Delete the snapshots past the retention window (the only command that deletes backups)"],["lunora backup pitr --at 2026-06-01T00:00:00Z","Point-in-time recovery (≤30 days)"]],group:"Data",loader:()=>import("../packem_chunks/handler22.mjs").then(e=>({default:e.execute})),name:"backup",options:[{description:"Backup directory (default .lunora-backups)",name:"dir",type:String},{description:"Store snapshots in this R2 bucket instead of a directory (use `default` for the app's default bucket)",name:"bucket",type:String},{description:"Key prefix for bucket-backed snapshots (default backups/)",name:"prefix",type:String},{description:"restore: verify the snapshot's checksum before importing anything",name:"verify",type:Boolean},{description:"Comma-separated table allowlist (create)",name:"tables",type:String},{description:"pitr: time to read/restore to (ISO or epoch-ms, ≤30 days)",name:"at",type:String},{description:"pitr --restore: explicit bookmark to restore to (wins over --at)",name:"bookmark",type:String},{description:"pitr: perform a restore instead of just reading the bookmark",name:"restore",type:Boolean},{description:"pitr --restore: restart the shard now so recovery applies immediately",name:"restart",type:Boolean},{description:"pitr: target shard key (default: root shard)",name:"shard",type:String},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Confirm a destructive step without prompting: a production pitr --restore, or backup prune",name:"yes",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String}]},q={description:"Codegen + validate + bundle the Worker to disk without deploying",examples:[["lunora build","Bundle to .lunora/build without deploying"],["lunora build --out-dir dist-worker","Bundle to a custom directory"],["lunora build --emit-bindings bindings.json","Also write what the bundle needs provisioned, for an external deployer"]],group:"Deploy",loader:()=>import("../packem_chunks/handler20.mjs").then(e=>({default:e.execute})),name:"build",options:[{description:"Override the schema-drift gate for this run (build even with breaking schema drift and no migration; the committed baseline is not advanced)",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${d} (default openapi)`,name:"api-spec",type:String},{description:"Write a JSON manifest of the bindings + crons the bundle needs to this path, for an IaC program to consume",name:"emit-bindings",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Directory to write the bundled Worker to (default .lunora/build)",name:"out-dir",type:String},{description:"Fail the build on ERROR-level codegen advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail the build on ERROR-level codegen advisories (the gate defaults to on in CI, off locally). Never downgrades platform diagnostics.",name:"no-strict-advisories",type:Boolean},s]},z={description:"Run codegen for lunora/ functions and schema",examples:[["lunora codegen","Generate lunora/_generated/ from your schema + functions"]],group:"Develop",loader:()=>import("../packem_chunks/runCodegenCommand.mjs").then(e=>({default:e.execute})),name:"codegen",options:[{description:`Which API spec(s) to emit: ${d} (default openapi)`,name:"api-spec",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Fail on ERROR-level advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail on ERROR-level advisories (the gate defaults to on in CI, off locally)",name:"no-strict-advisories",type:Boolean},s]},Y={argument:{description:"<build|push|images|list|info|delete> [args…]",name:"args",type:String},description:"Build/push container images and manage container instances (wraps wrangler containers)",examples:[["lunora containers build ./containers/transcoder --tag transcoder:v1","Build a container image with the local Docker engine"],["lunora containers build ./containers/transcoder --tag transcoder:v1 --push","Build and push to the Cloudflare Registry in one step"],["lunora containers push transcoder:v1","Push a locally-tagged image to the Cloudflare Registry"],["lunora containers images list","List images in your Cloudflare Registry"],["lunora containers images delete transcoder:v1","Delete an image to free registry storage"]],group:"Deploy",loader:()=>import("../packem_chunks/handler3.mjs").then(e=>({default:e.execute})),name:"containers",options:[{description:"build: push the image to the Cloudflare Registry after building",name:"push",type:Boolean},{description:"build: name:tag for the image (forwarded to wrangler --tag)",name:"tag",type:String},{description:"Cloudflare environment name",name:"env",type:String}]},Q={description:"Codegen, validate wrangler, then wrangler deploy",examples:[["lunora deploy","Deploy to Cloudflare"],["lunora deploy --env production","Deploy to a named environment"],["lunora deploy --dry-run","Validate + bundle without publishing"],["lunora deploy --migrate --migrate-yes --migrate-url <url>","Deploy, then run pending data migrations"]],group:"Deploy",loader:()=>import("../packem_chunks/runDeployCommand.mjs").then(e=>({default:e.execute})),name:"deploy",options:[{description:"Override the schema-drift gate for this run (deploy even with breaking schema drift and no migration; the committed baseline is not advanced — use --update-schema-baseline to accept the new shape)",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${d} (default openapi)`,name:"api-spec",type:String},{description:"Validate, bundle, and run pre-deploy gates without publishing (wrangler deploy --dry-run)",name:"dry-run",type:Boolean},{description:"Cloudflare environment name",name:"env",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"After the deploy, probe the new version's health route (/_lunora/health/ready, falling back to /_lunora/health) and fail if it never answers",name:"health-check",type:Boolean},{description:"After a successful deploy, run pending data migrations against the live worker",name:"migrate",type:Boolean},{description:"Skip codegen + the schema-drift gate (assumes `lunora build`/`prepare` already ran in this CI run). Wrangler still bundles the worker.",name:"prebuilt",type:Boolean},{description:"Admin bearer token for --migrate (falls back to LUNORA_ADMIN_TOKEN)",name:"migrate-token",type:String},{description:"Worker URL for --migrate (REQUIRED with --migrate; the deploy target URL is not captured automatically)",name:"migrate-url",type:String},{description:"Confirm running the production data migration triggered by --migrate (required with --migrate)",name:"migrate-yes",type:Boolean},{description:"Fail the deploy on ERROR-level codegen advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail the deploy on ERROR-level codegen advisories (the gate defaults to on in CI, off locally). Never downgrades platform diagnostics.",name:"no-strict-advisories",type:Boolean},{description:"Upload a preview version (wrangler versions upload) instead of going live — prints a preview URL; doesn't shift production traffic",name:"preview",type:Boolean},s,{description:"Deploy to a temporary Cloudflare account when unauthenticated (wrangler deploy --temporary; live ~60min, then claim or it's deleted). Wrangler errors if you're already authenticated.",name:"temporary",type:Boolean},{description:"Re-bless the committed schema baseline (lunora/.lunora-schema.json) with the current shape",name:"update-schema-baseline",type:Boolean}]},X={argument:{description:"list | inspect <version-id> | rollback [version-id] | promote <version-id>",name:"subcommand",type:String},description:"List deployments and roll back / promote / inspect Worker versions",examples:[["lunora deployments list","Show the 10 most recent deployments"],["lunora deployments inspect <version-id>","View a specific Worker version"],["lunora deployments rollback --yes","Roll back to the previous version"],["lunora deployments promote <version-id> --yes","Send 100% of traffic to a version"]],group:"Deploy",loader:()=>import("../packem_chunks/handler4.mjs").then(e=>({default:e.execute})),name:"deployments",options:[{description:"Cloudflare environment name",name:"env",type:String},{description:"Display `list` output as JSON",name:"json",type:Boolean},{description:"Reason/description recorded with a rollback or promote",name:"message",type:String},{description:"Confirm a rollback or promote (required — these change live traffic)",name:"yes",type:Boolean}]},Z={argument:{description:"Optional subcommand: stop (shut the running dev server down) | status (report it) | logs (print its captured output)",name:"args",type:String},description:"Run the dev stack: wrangler worker + studio + codegen watch",examples:[["lunora dev","Run the worker + studio + codegen watch"],["lunora dev --background","Run detached: blocks until ready, prints URL + PID, then returns"],["lunora dev stop","Stop the background/tracked dev server (idempotent)"],["lunora dev status","Report the running dev server (URL, PID, uptime, ready/starting)"],["lunora dev status --json","Same as JSON — poll `.ready` to gate a dependent step in a task graph"],["lunora dev logs","Print the captured dev-server log (background runs)"],["lunora dev --json","Machine-readable JSON log lines (also LUNORA_LOG_JSON=1)"],["lunora dev --emit-bindings dev-manifest.json","Write what this worker needs + where it serves, for a task runner"],["lunora dev --no-studio","Skip the embedded studio server"],["lunora dev --worker-port 8080","Use a custom wrangler dev port"],["lunora dev --remote","Proxy D1/KV/R2 to the deployed worker (also LUNORA_REMOTE=1)"]],group:"Develop",loader:()=>import("../packem_chunks/planDevCommand.mjs").then(e=>({default:e.execute})),name:"dev",options:[{description:`Which API spec(s) codegen emits: ${d} (default openapi)`,name:"api-spec",type:String},{description:"Write the binding manifest (plus the dev origin) to <file>, for a supervisor that owns the rest of the graph",name:"emit-bindings",type:String},{description:"Studio server port (default 6173)",name:"port",type:Number},s,{description:"wrangler dev port (default 8787)",name:"worker-port",type:Number},{description:"Run the dev server as a managed background process (auto-enabled when an AI agent is detected; LUNORA_AGENT_MODE=0 disables)",name:"background",type:Boolean},{description:"Emit machine-readable JSON log lines (also LUNORA_LOG_JSON=1; auto-enabled for AI agents)",name:"json",type:Boolean},{description:"How many trailing lines `lunora dev logs` prints (default 100, 0 = all)",name:"lines",type:Number},{description:"Serve the embedded studio at /__lunora (default)",name:"studio",type:Boolean},{description:"Don't start the embedded studio server",name:"no-studio",type:Boolean},{description:"Spawn wrangler dev for the worker (default)",name:"worker",type:Boolean},{description:"Don't spawn wrangler dev — an external task runner owns the worker; codegen watch + studio still run",name:"no-worker",type:Boolean},{description:"Run codegen on startup and watch for changes (default)",name:"codegen",type:Boolean},{description:"Don't run codegen — no watch, no startup generate (or set LUNORA_CODEGEN=0)",name:"no-codegen",type:Boolean},{description:"Proxy D1/KV/R2 bindings to the deployed worker (or set LUNORA_REMOTE=1)",name:"remote",type:Boolean}]},ee={argument:{description:"Optional path under the docs site (e.g. packages/studio)",name:"section",type:String},description:"Open the Lunora docs in your browser (optional [section] path)",examples:[["lunora docs","Open the Lunora docs"],["lunora docs packages/studio","Open a specific docs section"]],group:"Project",loader:()=>import("../packem_chunks/handler5.mjs").then(e=>({default:e.execute})),name:"docs"},te={description:"Preflight the current Lunora project (wrangler bindings, placeholders, dev secrets)",examples:[["lunora doctor","Run the project preflight checks"],["lunora doctor --format json","Emit the findings as a machine-readable JSON document"]],group:"Project",loader:()=>import("../packem_chunks/handler6.mjs").then(e=>({default:e.execute})),name:"doctor",options:[{description:"Output format: pretty (default) or json",name:"format",type:String}]},re={argument:{description:"list | get <KEY> | set <KEY> <VALUE> | unset <KEY> | generate [KEY] | push | diff | doctor",name:"subcommand",type:String},description:"Manage .dev.vars and sync secrets via wrangler (list | get | set | unset | generate | push | diff | doctor)",examples:[["lunora env list","List .dev.vars keys"],["lunora env set API_KEY secret","Set a local variable"],["lunora env generate","Generate strong values for the project's secrets (print KEY=value)"],["lunora env generate AUTH_SECRET --set","Generate one secret and write it to .dev.vars"],["lunora env push --yes","Upload secrets to Cloudflare"],["lunora env diff","Compare local .dev.vars keys against Cloudflare"]],group:"Data",loader:()=>import("../packem_chunks/handler7.mjs").then(e=>({default:e.execute})),name:"env",options:[{description:"Target this Cloudflare environment for `push`/`diff` (passes --env <name> to wrangler)",name:"env",type:String},{description:"Alias for --env production",name:"prod",type:Boolean},{description:"For `generate` — write the generated secrets into .dev.vars instead of printing them",name:"set",type:Boolean},{description:"Push secrets to a temporary-account deployment when unauthenticated (wrangler secret put --temporary). Errors if you're already authenticated.",name:"temporary",type:Boolean},{description:"Required for `push` — confirms uploading secrets to Cloudflare",name:"yes",type:Boolean}]},oe={description:"Run every *.eval.ts under evals/ via @lunora/testing's evaluate/agentHarness — no live worker needed",examples:[["lunora eval","Run every eval under evals/, print the aggregate table"],["lunora eval --threshold 0.8","Non-zero exit if any eval's average score falls below 0.8"],["lunora eval --dir evals/support --format json","Run a subset and emit a machine-readable result"]],group:"Develop",loader:()=>import("../packem_chunks/handler23.mjs").then(e=>({default:e.execute})),name:"eval",options:[{description:"Directory to discover *.eval.ts files under (default evals/)",name:"dir",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Score gate every eval's average must meet ([0,1]); a per-eval `threshold` export wins over this for that eval",name:"threshold",type:Number}]},ne={argument:{description:"Optional path (alias for --out)",name:"path",type:String},description:"Stream NDJSON of every shard-local + global table from the worker",examples:[["lunora export --out backup.ndjson","Dump every table to an NDJSON file"],["lunora export --tables messages,users","Export only specific tables"]],group:"Data",loader:()=>import("../packem_chunks/handler8.mjs").then(e=>({default:e.execute})),name:"export",options:[{description:"Output file path (`-` for stdout, default)",name:"out",type:String},{description:"Comma-separated table allowlist",name:"tables",type:String},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String}]},ae={argument:{description:"Source NDJSON file, or a `npx convex export --path <dir>` directory",name:"file",type:String},description:"Bulk-insert rows from an NDJSON file — or a Convex export directory — via the worker's admin endpoint",examples:[["lunora import backup.ndjson","Bulk-insert rows from an NDJSON file"],["lunora import ./convex-export","Import a `npx convex export --path` directory (ids are preserved, so no remapping)"],["lunora import ./convex-export --with-storage","Also migrate blobs (verified sha256 upload) + `{ $storage }` refs"],["lunora import ./convex-export --scan","Write a candidate `lunora/import-convex.json` storage-column mapping (imports nothing)"],["lunora import ./snapshot.zip --with-storage --verify","Import a `npx convex export --path` zip snapshot with blob + row-parity checks"],["lunora import ./supabase-csv --from supabase","Import a directory of `COPY … TO STDOUT WITH CSV HEADER` dumps"],["lunora import ./firestore-json --from firebase --verify","Import Firestore documents (REST/Admin-SDK JSON) with row-parity checks"]],group:"Data",loader:()=>import("../packem_chunks/handler9.mjs").then(e=>({default:e.execute})),name:"import",options:[{description:"Source reader for a dump that cannot be detected: supabase | firebase (Convex and NDJSON are auto-detected)",name:"from",type:String},{description:"Wrap each bare doc as `{table:<name>,doc:...}`",name:"table",type:String},{description:"Rows per HTTP request (default 500)",name:"batch-size",type:Number},{description:"Also migrate file storage — Convex `_storage` blobs, or a Supabase/Firebase bucket (verified upload)",name:"with-storage",type:Boolean},{description:"Directory of storage objects to upload alongside the rows (Firebase: after `gcloud storage cp -r`)",name:"storage-dir",type:String},{description:"Write a candidate `lunora/import-convex.json` storage-column mapping and exit",name:"scan",type:Boolean},{description:"Verify row parity + dangling-storage after import (non-zero exit on mismatch)",name:"verify",type:Boolean},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Confirm bulk-writing production (required with --prod)",name:"yes",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String}]},ie={description:"Print resolved project config: @lunora/* versions, wrangler summary, schema overview",examples:[["lunora info","Print resolved project config"],["lunora info --json","Emit a JSON snapshot"],["lunora info --bindings","List what this Worker needs provisioned: bindings, crons, vars"],["lunora info --bindings --json","Emit the manifest a deployer or task runner consumes"],["lunora info --bindings --out reqs.json","Write that manifest to a file"]],group:"Project",loader:()=>import("../packem_chunks/handler10.mjs").then(e=>({default:e.execute})),name:"info",options:[{description:"Report only what this Worker needs provisioned, as the binding manifest",name:"bindings",type:Boolean},{description:"Emit JSON instead of human text",name:"json",type:Boolean},{description:"With --bindings: write the manifest to <file> instead of stdout",name:"out",type:String}]},se={argument:{description:"Project name",name:"name",type:String},description:"Scaffold a new Lunora project",examples:[["lunora init my-app","Scaffold with the default (vite) template"],["lunora init my-app -t next","Scaffold a Next.js app"],["lunora init my-app -t tanstack-start-react","Scaffold a TanStack Start (React) app"],["lunora init my-app -t tanstack-start-solid","Scaffold a TanStack Start (Solid) app"],["lunora init my-app -t solid-v2","Scaffold a Solid 2.0 SPA"],["lunora init my-app --ref alpha","Scaffold from the alpha branch's templates"],["lunora init --here","Add Lunora to the current project"],["lunora init my-app --ci github","Scaffold + add a GitHub Actions deploy pipeline"],["lunora init my-app --ci gitlab","Scaffold + add a GitLab CI deploy pipeline"]],group:"Project",loader:()=>import("../packem_chunks/runInitCommand.mjs").then(e=>({default:e.execute})),name:"init",options:[{alias:"t",description:"Template: analog | astro | expo | next | nuxt | react-router | solid-v2 | standalone | sveltekit | tanstack-start-react | tanstack-start-solid | vinext | vinext-pages. Also accepts an overlay framework (react | vue | solid | svelte), same as --vite.",name:"template",type:String},{description:"Scaffold via the create-vite overlay for a framework (react | vue | solid | svelte | vanilla) — official create-vite base + Lunora layer",name:"vite",type:String},{description:"Local templates root to copy from (offline-friendly; expects <type>/ subdirs)",name:"from",type:String},{description:"Override the remote template source (e.g. gh:owner/repo/sub#ref)",name:"source",type:String},{description:"Fetch templates from a git ref (branch, tag, or commit), e.g. --ref alpha. Overrides the version-derived default",name:"ref",type:String},{description:"Permit --source values outside gh:/github:/https:// (e.g. local file://)",name:"allow-unsafe-source",type:Boolean},{description:"Add Lunora to the current project: detect the framework, patch the config, scaffold lunora/, print per-framework wiring steps",name:"here",type:Boolean},{alias:"i",description:"After scaffolding, offer to add auth + email (defaults on when stdin is a TTY)",name:"interactive",type:Boolean},{alias:"y",description:"Skip the auth/email offer; scaffold only",name:"yes",type:Boolean},{description:"Also scaffold a CI deploy pipeline: github (.github/workflows/deploy.yml) or gitlab (.gitlab-ci.yml)",name:"ci",type:String},{description:"Add features non-interactively after scaffolding (comma-separated): ai | auth | backup | browser | cloudflare-access | crons | email | flags | hyperdrive | payment | presence | queue | storage | workflow",name:"add",type:String},{description:"Walk through every step (prompts + output) without writing files, installing, or running git",name:"dry-run",type:Boolean}]},le={description:"Report write-conflict hot-spots, error rates, and latency outliers from a running Worker",examples:[["lunora insights","Report against the local dev worker"],["lunora insights --shard channel:demo","Scope the report to one shard"],["lunora insights --json","Emit the raw report as JSON"],["lunora insights --prod --url https://app.example.com --token $LUNORA_ADMIN_TOKEN","Report against production"]],group:"Develop",loader:()=>import("../packem_chunks/handler11.mjs").then(e=>({default:e.execute})),name:"insights",options:[{description:"Explicit shard key (defaults to the root shard)",name:"shard",type:String},{description:"Max rows per section (default 10)",name:"limit",type:String},{description:"Emit a JSON report instead of human text",name:"json",type:Boolean},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (or LUNORA_ADMIN_TOKEN)",name:"token",type:String}]},de={description:"Scaffold lunora/schema.ts (and list/get procedures) from an existing Postgres or MySQL database",examples:[["lunora introspect --url postgres://localhost/shop","Scaffold a schema + procedures from every table"],["lunora introspect --tables users,orders","Introspect only these tables (DATABASE_URL is read by default)"],["lunora introspect --dry-run","Print what would be written without touching the filesystem"],["lunora introspect --no-procedures --force","Regenerate just the schema, overwriting the existing file"]],group:"Data",loader:()=>import("../packem_chunks/handler25.mjs").then(e=>({default:e.execute})),name:"introspect",options:[{description:"Database connection string (default: $DATABASE_URL)",name:"url",type:String},{description:"Postgres schema (default `public`) or MySQL database name",name:"schema",type:String},{description:"Comma-separated table allow-list (default: every base table)",name:"tables",type:String},{description:"Also emit list/get procedure modules per table (the default)",name:"procedures",type:Boolean},{description:"Emit only the schema — skip the per-table list/get procedure modules",name:"no-procedures",type:Boolean},{description:"Overwrite files that already exist",name:"force",type:Boolean},{description:"Print what would be written without writing it",name:"dry-run",type:Boolean}]},pe={description:"Link this checkout to its deployed Worker (writes .lunora/project.json)",examples:[["lunora link --url https://app.acme.workers.dev","Link to a deployed Worker URL"],["lunora link --url https://app.acme.workers.dev --env production","Link a named environment"],["lunora link --remove","Remove the link"]],group:"Deploy",loader:()=>import("../packem_chunks/handler12.mjs").then(e=>({default:e.execute})),name:"link",options:[{description:"Cloudflare environment name to record alongside the link",name:"env",type:String},{description:"Worker name (defaults to the `name` in wrangler config)",name:"name",type:String},{description:"Remove the existing link (.lunora/project.json)",name:"remove",type:Boolean},{description:"Deployed Worker URL to link (e.g. https://app.acme.workers.dev)",name:"url",type:String}]},ce={argument:{description:"Worker name (defaults to the name in wrangler config)",name:"worker",type:String},description:"Stream live logs from a deployed Worker, or read the durable log archive with --durable",group:"Deploy",loader:()=>import("../packem_chunks/handler24.mjs").then(e=>({default:e.execute})),name:"logs",options:[{description:"Cloudflare environment name",name:"env",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Substring filter on log messages",name:"search",type:String},{description:"Filter by invocation status: ok, error, or canceled",name:"status",type:String},s,{description:"Tail a temporary-account deployment when unauthenticated (wrangler tail --temporary). Errors if you're already authenticated.",name:"temporary",type:Boolean},{description:"Read the durable log archive (pipelineLogSink → R2) via R2 SQL instead of tailing live",name:"durable",type:Boolean},{description:"durable: Iceberg table the Pipeline writes to (required with --durable)",name:"table",type:String},{description:"durable: Iceberg namespace (R2 Data Catalog database) the table lives in",name:"namespace",type:String},{description:"durable: lower time bound (epoch-millis or ISO 8601), inclusive",name:"since",type:String},{description:"durable: upper time bound (epoch-millis or ISO 8601), inclusive",name:"until",type:String},{description:"durable: exact severity filter (trace|debug|log|info|warn|error|fatal)",name:"level",type:String},{description:"durable: severity floor — this level and every more-severe one",name:"min-level",type:String},{description:"durable: keep function paths starting with this prefix (LIKE 'prefix%')",name:"function-prefix",type:String},{description:"durable: trace-id filter",name:"trace-id",type:String},{description:"durable: shard-key filter",name:"shard-key",type:String},{description:"durable: user-id filter",name:"user-id",type:String},{description:"durable: max rows (clamped to 1–10000; default 500)",name:"limit",type:String},{description:"durable: resume after a prior page — the opaque cursor token printed by the previous page (bare epoch-millis also accepted for back-compat)",name:"cursor",type:String},{description:"durable: emit one JSON object per line instead of a table",name:"ndjson",type:Boolean}]},ue={argument:{description:"install [client…] | uninstall [client…] | serve",name:"args",type:String},description:"Connect your AI editor to Lunora over MCP (docs search + this project's dev server)",examples:[["lunora mcp install","Install into every MCP client already configured here"],["lunora mcp install claude-code cursor","Install into specific clients"],["lunora mcp install --list","List the supported clients and their config files"],["lunora mcp install --docs-only","Install only the hosted documentation server"],["lunora mcp install --print","Show the config that would be written, without writing it"],["lunora mcp install --global","Force every server into the machine-wide config"],["lunora mcp uninstall","Remove Lunora's MCP servers from every supported client"],["lunora mcp uninstall cursor","Remove them from one client"],["lunora mcp uninstall --print","Show what would be removed, without removing it"],["lunora mcp serve","Run the stdio MCP server (this is what your editor spawns)"],["lunora mcp serve --allow-writes","Also expose the mutation/action tools"],["lunora mcp serve --token $LUNORA_ADMIN_TOKEN","Expose the observability tools (logs, issues, advisories, insights, migrations) too"]],group:"Develop",loader:()=>import("../packem_chunks/handler26.mjs").then(e=>({default:e.execute})),name:"mcp",options:[{description:"install: replace entries that already exist",name:"force",type:Boolean},{description:"install: list the supported clients and their config files",name:"list",type:Boolean},{description:"install/uninstall: print what would change instead of writing it",name:"print",type:Boolean},{description:"install/uninstall: only the hosted documentation server",name:"docs-only",type:Boolean},{description:"install/uninstall: only this project's local server",name:"local-only",type:Boolean},{description:"install/uninstall: the machine-wide config (install default: docs server global, local server per-project)",name:"global",type:Boolean},{description:"install/uninstall: this project's config instead of the machine-wide one",name:"project",type:Boolean},{description:"serve: also expose the mutation/action tools (default: read-only)",name:"allow-writes",type:Boolean},{description:"serve: expose the documentation tools (default)",name:"docs",type:Boolean},{description:"serve: skip the documentation tools",name:"no-docs",type:Boolean},{description:"Docs site origin backing the documentation tools (default https://lunora.sh)",name:"docs-url",type:String},{description:"serve: deployment URL to expose (default: the running dev server)",name:"url",type:String},{description:"serve: bearer token (default: LUNORA_ADMIN_TOKEN from the environment or .dev.vars). Also gates the observability tools (logs, issues, advisories, query insights, migration status) — without a token they are not exposed at all",name:"token",type:String}]},me={argument:{description:"generate | create | up | down | status | d1-to-hyperdrive [name|id]",name:"subcommand",type:String},description:"Schema (generate), online data (create | up | down | status), and backend (d1-to-hyperdrive) migrations",examples:[["lunora migrate generate","Diff lunora/schema.ts and emit a SQL migration"],["lunora migrate create add_users_email","Scaffold a data migration"],["lunora migrate up backfill-names","Run a data migration across shards"],["lunora migrate status backfill-names","Report a migration's per-shard status"],["lunora migrate d1-to-hyperdrive --from-url https://old --to-url https://new","Copy .global() data from D1 to Hyperdrive"]],group:"Data",loader:()=>import("../packem_chunks/runMigrateGenerateCommand.mjs").then(e=>({default:e.execute})),name:"migrate",options:[{description:"Migration name slug (e.g. add_users_email)",name:"name",type:String},{description:"Target table for `create` (prompted for interactively when omitted)",name:"table",type:String},{description:"Preview a data migration without rewriting rows",name:"dry-run",type:Boolean},{description:"Rows per batch for a data migration",name:"batch-size",type:Number},{description:"Cap batches processed this run (maps to the runner's maxBatches)",name:"steps",type:Number},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String},{description:"Required with --prod for up/down — confirms running against production",name:"yes",type:Boolean},{description:"d1-to-hyperdrive: source (D1) worker URL (defaults to --url)",name:"from-url",type:String},{description:"d1-to-hyperdrive: source admin token (defaults to --token / LUNORA_ADMIN_TOKEN)",name:"from-token",type:String},{description:"d1-to-hyperdrive: target (Hyperdrive) worker URL (defaults to --url)",name:"to-url",type:String},{description:"d1-to-hyperdrive: target admin token (defaults to --token / LUNORA_ADMIN_TOKEN)",name:"to-token",type:String},{description:"d1-to-hyperdrive: comma-separated .global() tables to move (default: all global tables)",name:"tables",type:String},{description:"d1-to-hyperdrive: keep the intermediate NDJSON dump at this path",name:"out",type:String}]},ge={description:"Run codegen + binding reconcile + wrangler validation (no Vite) — for CI",examples:[["lunora prepare","Codegen + binding reconcile + validate (CI, before deploy)"]],group:"Deploy",loader:()=>import("../packem_chunks/handler13.mjs").then(e=>({default:e.execute})),name:"prepare",options:[{description:"Override the schema-drift gate for this run (proceed even with breaking schema drift and no migration; the committed baseline is not advanced)",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${d} (default openapi)`,name:"api-spec",type:String},{description:"Fail on ERROR-level codegen advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail on ERROR-level codegen advisories (the gate defaults to on in CI, off locally). Never downgrades platform diagnostics.",name:"no-strict-advisories",type:Boolean},s,{description:"Re-bless the committed schema baseline (lunora/.lunora-schema.json) with the current shape",name:"update-schema-baseline",type:Boolean}]},he={argument:{description:"<add|list|view|build> [item names…]",name:"args",type:String},description:"Component registry: add/list/view items, or build the catalog",examples:[["lunora registry list","List available registry items"],["lunora registry add presence","Scaffold a registry item into lunora/"],["lunora registry build --check","Verify the committed catalog is current"]],group:"Project",loader:()=>import("../packem_chunks/handler14.mjs").then(e=>({default:e.execute})),name:"registry",options:[{description:"add: print the plan and stop without writing",name:"dry-run",type:Boolean},{description:"add: preview the file changes (content diff) and write nothing",name:"diff",type:Boolean},{description:"add: force-overwrite existing files (take the incoming copy)",name:"overwrite",type:Boolean},{description:"add: skip the package.json mutation confirmation prompt",name:"yes",type:Boolean},{description:"Local registry root (offline; expects <name>/ subdirs)",name:"from",type:String},{description:"Override the remote registry source base (e.g. gh:owner/repo/registry)",name:"source",type:String},{description:"Fetch items from a git ref (branch, tag, or commit), e.g. --ref alpha. Overrides the version-derived default",name:"ref",type:String},{description:"Permit --source values outside gh:/github:/https://",name:"allow-unsafe-source",type:Boolean},{description:"Emit JSON output (add plan / list)",name:"json",type:Boolean},{description:"build: output path for the catalog (default <root>/index.json)",name:"out",type:String},{description:"build: verify the index is current instead of rewriting it",name:"check",type:Boolean}]},fe={description:"Clear local Miniflare state (and .lunora-cache with --all)",examples:[["lunora reset","Clear local Miniflare state"],["lunora reset --all","Also remove .lunora-cache"]],group:"Develop",loader:()=>import("../packem_chunks/runResetCommand.mjs").then(e=>({default:e.execute})),name:"reset",options:[{description:"Also remove .lunora-cache",name:"all",type:Boolean},{description:"Skip the confirmation prompt (required when stdin is not a TTY)",name:"yes",type:Boolean}]},ye={argument:{description:"install | check",name:"subcommand",type:String},description:"Install the Lunora agent skills (AI rules) into .agents/skills/, or check they're present",examples:[["lunora rules install","Copy the Lunora agent skills into .agents/skills/"],["lunora rules install --overwrite","Reinstall, replacing edited skill files"],["lunora rules check","Report which Lunora skills are installed"],["lunora rules check --strict","Exit non-zero when rules are missing (CI gate)"],["lunora rules install --dir packages/app","Install into a specific root instead of the workspace root"]],group:"Project",loader:()=>import("../packem_chunks/handler15.mjs").then(e=>({default:e.execute})),name:"rules",options:[{description:"Install/check root (default: the detected workspace root, not the current directory)",name:"dir",type:String},{description:"install: overwrite skill files that already exist (default: skip them)",name:"overwrite",type:Boolean},{description:"check: exit non-zero when the rules are missing (for CI gating)",name:"strict",type:Boolean}]},ve={argument:{description:"Function path (e.g. messages:send)",name:"functionPath",type:String},description:"Send a single RPC to a running Lunora Worker",examples:[[`lunora run messages:send --args '{"text":"hi"}'`,"Call a function with JSON args"],["lunora run messages:list --shard channel:demo","Target a specific shard"],["lunora run messages:list --as user_123","Run as an authenticated user (needed when the app gates on identity)"]],group:"Develop",loader:()=>import("../packem_chunks/runRpcCommand.mjs").then(e=>({default:e.execute})),name:"run",options:[{description:"JSON-encoded args object",name:"args",type:String},{description:"Run as this user id — dispatches through the admin-gated `runAs` op so identity-gated apps accept the call",name:"as",type:String},{description:`JSON-encoded extra identity claims to forge alongside --as (e.g. '{"org":"acme"}')`,name:"claims",type:String},{description:"Explicit shard key",name:"shard",type:String},{description:"Worker URL (defaults to the running dev server, else http://localhost:8787)",name:"url",type:String},{description:"Admin bearer for --as (prefer LUNORA_ADMIN_TOKEN or .dev.vars; --token is visible to other local processes via the process table)",name:"token",type:String}]},be={argument:{description:"<generate>",name:"args",type:String},description:"Generate a self-contained typed client SDK for another language from the project's OpenRPC surface",examples:[["lunora sdk generate --lang python","Emit a Python SDK, transport included, into ./sdk/python"],["lunora sdk generate --lang go --out ./clients/go","Choose the language and output directory"],["lunora sdk generate --lang dart","A Flutter-ready Dart client — live queries arrive as a Stream"],["lunora sdk generate --lang kotlin","Any of the registered targets; --lang lists them"],["lunora sdk generate --lang rust --from ./sdks","Copy the transport from a local checkout instead of fetching it"]],group:"Project",loader:()=>import("../packem_chunks/handler21.mjs").then(e=>({default:e.execute})),name:"sdk",options:[{description:`Target language: ${M.join(" | ")}`,name:"lang",type:String},{description:"Output directory (default ./sdk/<lang>)",name:"out",type:String},{description:"Path to the OpenRPC document (default ./lunora/_generated/openrpc.json)",name:"spec",type:String},{description:"Copy the transport from a local directory of per-language transports (the repo's `sdks/`) instead of fetching it",name:"from",type:String},{description:"Git ref to fetch the transport from (default: this CLI's own release tag, so the transport matches the generated surface)",name:"ref",type:String},{description:"Override the remote transport source base (default gh:anolilab/lunora/sdks)",name:"source",type:String},{description:"Permit --source values outside gh:/github:/https://",name:"allow-unsafe-source",type:Boolean}]},we={description:"Generate deterministic fake data from lunora/schema.ts and bulk-insert it via the worker's admin endpoint",examples:[["lunora seed","Seed every table with the default row count"],["lunora seed --table posts --count 50","Seed 50 posts; FK-parent tables are seeded automatically"],["lunora seed --reset","Wipe local .wrangler/state, then seed from scratch"],["lunora seed --seed 7 --dry-run","Print the NDJSON for seed 7 without inserting"],["lunora seed --seed 7 --now 1785000000000","Byte-identical rows across runs (pins the clock too)"]],group:"Data",loader:()=>import("../packem_chunks/handler16.mjs").then(e=>({default:e.execute})),name:"seed",options:[{description:"Rows per table (default 10)",name:"count",type:Number},{description:"Seed only this table; its FK-parent tables are seeded automatically",name:"table",type:String},{description:"Deterministic seed — same value yields identical rows (default 0)",name:"seed",type:Number},{description:"Epoch-ms reference for time columns (createdAt, expiresAt, …). Pin it with --seed for byte-identical rows across runs; defaults to now",name:"now",type:Number},{description:"Print the generated NDJSON instead of inserting",name:"dry-run",type:Boolean},{description:"Wipe local .wrangler/state before seeding (local dev only)",name:"reset",type:Boolean},{description:"Rows per HTTP request (default 500)",name:"batch-size",type:Number},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String},{description:"Skip the confirmation prompt when seeding a non-local/production target",name:"yes",type:Boolean}]},ke={description:"Validate wrangler.jsonc + codegen dry-run + tsc --noEmit (no files written)",examples:[["lunora verify","Validate wrangler + codegen + tsc"],["lunora verify --no-typecheck","Skip the TypeScript type-check"],["lunora verify --health-url https://my-app.workers.dev","Also probe the deployment's /_lunora/health"],["lunora verify --env production","Validate the env.production view, as `lunora deploy --env production` will"]],group:"Deploy",loader:()=>import("../packem_chunks/handler17.mjs").then(e=>({default:e.execute})),name:"verify",options:[{description:"Treat breaking schema drift as a warning instead of a failure",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${d} (default openapi)`,name:"api-spec",type:String},{description:"Cloudflare environment name — validate the env.<name> view of wrangler.jsonc, as `lunora deploy --env` does",name:"env",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Probe this deployment's /_lunora/health endpoint (off by default; keeps verify offline-safe)",name:"health-url",type:String},{description:"Fail verification on ERROR-level codegen advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail verification on ERROR-level codegen advisories (the gate defaults to on in CI, off locally). Never downgrades platform diagnostics.",name:"no-strict-advisories",type:Boolean},{description:"Run the TypeScript type-check step (default)",name:"typecheck",type:Boolean},{description:"Skip the TypeScript type-check step",name:"no-typecheck",type:Boolean},s]},Se={description:"Open the Lunora studio in your browser (the running dev server's, or the default local one)",examples:[["lunora view","Open the studio for the running dev server"]],group:"Project",loader:()=>import("../packem_chunks/handler18.mjs").then(e=>({default:e.execute})),name:"view"},xe={filterStacktrace:()=>!1,hideErrorCodeView:!0},Re=(e,t={})=>{const r=e instanceof Error?e.message:String(e),o=L(S(e)?{code:e.code,hint:e.hint,message:r}:r),n=new U({hint:o===void 0?void 0:I(o).split(`
|
|
2
|
+
`),message:t.reason===void 0?r:`${t.reason}: ${r}`,name:e instanceof Error&&e.name.length>0?e.name:"Error"});return n.stack="",W(n,xe)},Ce=(e,t)=>{const r=Array.from({length:t.length+1},(o,n)=>n);for(let o=1;o<=e.length;o+=1){let n=r[0]??0;r[0]=o;for(let a=1;a<=t.length;a+=1){const i=r[a]??0,p=e[o-1]===t[a-1]?0:1;r[a]=Math.min((r[a-1]??0)+1,i+1,n+p),n=i}}return r[t.length]??0},Ne=(e,t)=>{let r,o=Number.POSITIVE_INFINITY;for(const a of t){const i=Ce(e,a);i<o&&(o=i,r=a)}const n=Math.max(2,Math.ceil(e.length/3));return r!==void 0&&o<=n?r:void 0},Oe=e=>`https://registry.npmjs.org/@lunora/cli/${e}`,Ae=1440*60*1e3,Be=1500,De="0.0.0",Ee=/^v/u,Le=new Set(["alpha","beta","next"]),m=e=>{const t=e.trim().replace(Ee,""),r=t.indexOf("-");return r===-1?{core:t,prerelease:""}:{core:t.slice(0,r),prerelease:t.slice(r+1)}},b=e=>{const[t,r,o]=m(e).core.split(".").map(n=>{const a=Number.parseInt(n,10);return Number.isFinite(a)?a:0});return[t??0,r??0,o??0]},Ie=(e,t)=>{const r=Number.parseInt(e,10),o=Number.parseInt(t,10);return String(r)===e&&String(o)===t?r>o?1:-1:e>t?1:-1},je=(e,t)=>{if(e===t)return 0;if(e===""||t==="")return e===""?1:-1;const r=e.split("."),o=t.split(".");for(let n=0;n<Math.max(r.length,o.length);n+=1){const a=r[n],i=o[n];if(a===void 0||i===void 0)return a===void 0?-1:1;if(a!==i)return Ie(a,i)}return 0},_e=(e,t)=>{const r=b(e),o=b(t);for(let n=0;n<3;n+=1)if((r[n]??0)!==(o[n]??0))return(r[n]??0)>(o[n]??0)?1:-1;return je(m(e).prerelease,m(t).prerelease)},Te=e=>{const t=m(e).prerelease.split(".")[0]??"";return Le.has(t)?t:"latest"},Pe=(e,t)=>_e(t,e)>0,Me=(e,t,r)=>t-e<r,Ue=(e,t,r="latest",o)=>{const n=`Update available for @lunora/cli: ${e} → ${t}`;if(o===void 0)return`${n} — add @lunora/cli@${r} as a dev dependency to update`;const{args:a,command:i}=K(o,[`@lunora/cli@${r}`],{dev:!0});return`${n} — run \`${i} ${a.join(" ")}\``},R=e=>u(e,"lunora-cli-update.json"),We=e=>{const t=e.XDG_CACHE_HOME&&e.XDG_CACHE_HOME.length>0?e.XDG_CACHE_HOME:u(J(),".cache"),r=u(t,"lunora");try{A(r,{mode:448,recursive:!0})}catch{}return r},Je=e=>{try{const t=JSON.parse(k(R(e),"utf8"));if(t!==null&&typeof t=="object"){const{checkedAt:r,latest:o}=t;if(typeof o=="string"&&typeof r=="number"){const{tag:n}=t;return{checkedAt:r,latest:o,...typeof n=="string"?{tag:n}:{}}}}}catch{}},w=(e,t)=>{try{const r=R(e);try{if(B(r).isSymbolicLink())return}catch{}D(r,`${JSON.stringify(t)}
|
|
3
|
+
`,"utf8")}catch{}},Ke=async(e,t)=>{try{const r=await e(Oe(t),{signal:AbortSignal.timeout(Be)});if(!r.ok)return;const o=await r.json(),n=o!==null&&typeof o=="object"?o.version:void 0;return typeof n=="string"?n:void 0}catch{return}},Fe=(e,t,r)=>e===De||!r||t.CI!==void 0||t.LUNORA_NO_UPDATE_NOTIFIER!==void 0,He=async e=>{const t=e.env??process.env,r=e.isTTY??process.stdout.isTTY;if(Fe(e.current,t,r))return;const o=e.cacheDir??We(t),n=(e.now??Date.now)(),a=e.ttlMs??Ae,i=Te(e.current),p=Je(o),O=p?.tag??"latest",g=p!==void 0&&O===i?p:void 0;let c=g?.latest;if(g===void 0||!Me(g.checkedAt,n,a)){const h=await Ke(e.fetchImpl??globalThis.fetch,i);h===void 0?w(o,{checkedAt:n,latest:e.current,tag:i}):(c=h,w(o,{checkedAt:n,latest:h,tag:i}))}c!==void 0&&Pe(e.current,c)&&e.logger.warn(Ue(e.current,c,i,e.manager))},$e=["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"],Ve=8,Ge=()=>{try{let e=f(E(import.meta.url));for(let t=0;t<Ve;t+=1){try{const o=JSON.parse(k(u(e,"package.json"),"utf8")),n=o!==null&&typeof o=="object"?o:void 0;if(n?.name==="@lunora/cli"&&typeof n.version=="string"&&n.version.length>0)return n.version}catch{}const r=f(e);if(r===e)break;e=r}}catch{}return"0.0.0"},C=Ge(),qe=[se,H,Z,z,$,q,Q,Y,ge,pe,X,ce,ve,le,fe,me,ne,ae,we,de,G,oe,ke,ie,te,re,V,Se,ee,he,ye,ue,be],N=[...qe,P,T],gt=N.map(e=>e.name),l=e=>e.replaceAll("{",String.raw`\{`).replaceAll("}",String.raw`\}`),ze=e=>e.every(t=>typeof t=="string")?e.map(t=>l(t)):e.map(t=>typeof t=="string"?[l(t)]:t.map(r=>l(r))),Ye=e=>({...e,...e.argument===void 0?{}:{argument:{...e.argument,description:l(e.argument.description??"")}},...e.description===void 0?{}:{description:l(e.description)},...e.examples===void 0?{}:{examples:ze(e.examples)},...e.options===void 0?{}:{options:e.options.map(t=>({...t,description:l(t.description??"")}))}}),Qe=e=>{const t={value:0},r=_("lunora",{argv:e.argv===void 0?void 0:[...e.argv],cwd:e.cwd,exit:o=>{t.value=typeof o=="number"?o:0},logger:e.logger,packageName:"@lunora/cli",packageVersion:C});for(const o of N)r.addCommand(Ye(o));return{cli:r,exitCode:t}},Xe=/Command "(?<name>[^"]+)" not found/u,Ze=e=>{const t=x(),r=e instanceof Error?e.message:String(e),o=Xe.exec(r);if(!o?.groups){S(e)||j(r)!==void 0?t.error(Re(e)):t.error(r);return}const n=o.groups.name??"",a=Ne(n,$e);t.error(`Unknown command "${n}".${a===void 0?"":` Did you mean "${a}"?`}`),t.info("Run `lunora --help` to list commands, or `lunora docs` to open the documentation.")},et=e=>({debug:t=>{e.debug(t)},error:t=>{e.error(t)},info:t=>{e.info(t)},success:t=>{e.info(t)},warn:t=>{e.warn(t)}}),ht=async(e={})=>{const{cli:t,exitCode:r}=Qe(e);e.logger!==void 0&&y(et(e.logger));try{await t.run({shouldExitProcess:!1})}catch(n){return Ze(n),1}finally{y(void 0)}let o;try{o=F(process.cwd())}catch{}return await He({current:C,logger:x(),manager:o}),r.value};export{$e as C,v as D,gt as R,C as V,ht as r};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createLogger as n}from"./createLogger-
|
|
1
|
+
import{createLogger as n}from"./createLogger-Cl18I8AX.mjs";import{P as t,a}from"./prompt-cancelled-C8Sj7OqI.mjs";const p=c=>async r=>{const s=n();try{const{code:e}=await c({argument:r.argument,cwd:r.process.cwd,logger:s,options:r.options});r.process.exit(e)}catch(e){if(e instanceof t){r.process.exit(a);return}s.error(e instanceof Error?e.message:String(e)),r.process.exit(1)}};export{p as d};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{STEP_BADGE_NAMES as i,LunoraReporter as u}from"@lunora/config";import{JsonReporter as d}from"@visulima/pail/reporter/json";import{createPail as l}from"@visulima/pail/server";let n,c=!1,a;const P=r=>{a=r},p=()=>{if(c)return!0;const r=process.env.LUNORA_LOG_JSON;return r==="1"||r==="true"},f=r=>new r,m=()=>[f(p()?d:u)],_=()=>{c||(c=!0,n=void 0)},L=Object.fromEntries(i.map(r=>[r,{label:r,logLevel:"informational"}])),g=new WeakSet,E=r=>g.has(r),t=()=>(n??=l({reporters:m(),scope:["lunora"],stderr:process.stderr,stdout:process.stdout,types:L}),n),v=()=>{if(a!==void 0)return a;const r={debug:e=>{t().debug(e)},error:e=>{t().error(e)},info:e=>{t().info(e)},success:e=>{t().success(e)},warn:e=>{t().warn(e)}};return g.add(r),r},O=()=>{const r=(o,s)=>{process.stderr.write(`${o} ${s}
|
|
2
|
+
`)},e={debug:o=>{r("debug",o)},error:o=>{r("error",o)},info:o=>{r("info ",o)},success:o=>{r("ok ",o)},warn:o=>{r("warn ",o)}};return g.add(e),e},R=new Proxy({},{get(r,e){const o=t(),s=o[e];return typeof s=="function"?s.bind(o):s}}),J=(r,e)=>{t()[r](e)};export{v as createLogger,O as createStderrLogger,_ as forceJsonLogging,E as isProcessStreamLogger,J as logStep,R as pail,P as setCommandLogger};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as a}from"@lunora/errors";import{deployTargetIds as s,DEFAULT_DEPLOY_TARGET as i,resolveTargetOrThrow as g,isRunnableTarget as c,runnableTargetIds as l}from"@lunora/config";const o=["both","none","openapi","openrpc"],p=o.join(" | "),f=r=>{if(!(typeof r!="string"||r.length===0)){if(o.includes(r))return r;throw new a("INTERNAL",`invalid --api-spec "${r}" — expected one of: ${p}`)}},T=(()=>{const r=s();return r.length>1?`${r.join(" | ")} (default ${i})`:r.join(" | ")})(),A={description:`Deploy target: ${T}. Also settable as "target" in lunora.config.*`,name:"target",type:String},d=(r,t)=>{try{return{target:g(r,t)}}catch(e){return{error:e instanceof Error?e.message:String(e)}}},h=(r,t)=>{const e=d(r,t);if(e.target===void 0)return e;if(!c(e.target)){const n=l();return{error:`deploy target "${e.target}" has no command-line toolchain, so the Lunora CLI cannot deploy or serve it — it can only generate for it (\`lunora codegen --target ${e.target}\`). Deployable targets: ${n.join(", ")}`}}return e};export{p as A,A as T,h as a,f as p,d as r};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{isProcessStreamLogger as s,createStderrLogger as r}from"./createLogger-Cl18I8AX.mjs";const e=new Set(["json","pretty"]),a=(t,o)=>{if(o!==void 0&&!e.has(o))return`${t}: unknown --format "${o}" — expected pretty | json`},n=t=>t==="json",c=(t,o)=>n(t)&&s(o)?r():o,p=t=>{process.stdout.write(`${JSON.stringify(t,void 0,2)}
|
|
2
|
+
`)};export{n as i,c as l,p,a as v};
|