@lunora/cli 1.0.0-alpha.359 → 1.0.0-alpha.360

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.
@@ -1,8 +1,11 @@
1
- import{join as Q,dirname as Z}from"node:path";import{discoverMigrations as ee,readServiceBindings as re,runCodegen as te}from"@lunora/codegen";import{readLinkedProject as U,execArgsFor as O,detectPackageManager as b,discoverContainerInfo as B,COMPOSED_WORKER_ENTRY as _,writeLinkedProject as ne,discoverSchemaInfo as F,DEV_VARS_FILE as w,parseDevVariableEntries as M,isMintableSecretKey as T,packageNamesFromBindings as ae,inferLunoraBindings as W,resolveSchemaDirectory as R,requiredSecrets as oe,generateSecretValue as ie,toolchainExecArgs as A,upsertDevVariableLine as se,writeDevVariablesFileAtomically as ce,resolveDeployDriver as j,planToolchainInvocation as V,runPostCodegenHook as le}from"@lunora/config";import{findWranglerFile as H,readWranglerJsonc as C,mergeWranglerEnvironment as G,warnCloudflareCliConfigOnce as de,validateWranglerProject as ue,reconcileWranglerBindings as ge,reconcileWranglerCompatibilityDate as me,reconcileWranglerCrons as fe,describePreservedCrons as ve}from"@lunora/config/cloudflare";import{Spinner as he}from"@visulima/spinner";import{r as pe,a as ye,e as we}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as ke,a as be}from"../packem_shared/deploy-target-DCWwiuAe.mjs";import{m as $e,e as Se,i as De,b as Ee,a as Re}from"../packem_shared/secret-key-BCrqNJ68.mjs";import{w as Ae}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{d as je}from"../packem_shared/command-CAXl2A1S.mjs";import{r as P}from"../packem_shared/wrangler-name-Dsk5K1f-.mjs";import{EXIT_CODE as v}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{containerBuildTag as Ce}from"@lunora/container";import{a as Pe,i as xe}from"../packem_shared/docker-DpVxvYpL.mjs";import{defaultSpawner as $}from"../packem_shared/createRecordingSpawner-Ch7zuQQE.mjs";import{r as K}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{p as _e,H as Te,a as Ne,r as Ie}from"../packem_shared/health-probe-Bw9JFfIy.mjs";import{existsSync as p,readFileSync as k,writeFileSync as q}from"node:fs";import{join as y}from"@visulima/path";import{Project as Le}from"ts-morph";import{runMigrateDataCommand as Ue}from"../packem_shared/runMigrateGenerateCommand-Ii_WMZEA.mjs";import{c as Oe}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{l as Be}from"../packem_shared/wrangler-secrets-3chIVv3H.mjs";const Fe=e=>{const{cwd:r,env:a,logger:t,mintedSecretsFile:n}=e;try{const o=U(r),i=o?.workerName??P(r),s=e.url??o?.workerUrl;t.success("deploy complete"),t.info(` worker: ${i??"(see wrangler output above)"}`),a!==void 0&&t.info(` env: ${a}`),s===void 0?t.info(" url: run `lunora link --url <https://your-worker>` to record it"):t.info(` url: ${s}`),n!==void 0&&t.info(` secrets: generated value(s) recorded in ${n}`),e.logsAvailable&&t.info(" logs: lunora logs")}catch{}},Me=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??$,a=[];for(const t of e.targets){const n=Ce(t.exportName),o={args:["build",t.buildDir,"--name",n],command:"railpack",cwd:e.cwd},i=O(b(e.cwd),"wrangler",["containers","push",n]),s={args:i.args,command:i.command,cwd:e.cwd};e.logger.info(`railpack: building "${t.exportName}" → ${n} from ${t.buildDir}`);const c=await r(o);if(c.code!==0){const l=`railpack build failed for container "${t.exportName}" (${t.buildDir})`;return e.logger.error(l),{builtTags:a,code:c.code,error:l}}e.logger.info(`railpack: pushing ${n} to the Cloudflare Registry`);const d=await r(s);if(d.code!==0){const l=`wrangler containers push failed for "${t.exportName}" (${n})`;return e.logger.error(l),{builtTags:a,code:d.code,error:l}}a.push(n)}return{builtTags:a,code:0}},We=e=>{const a=[H(e),Q(e,"package.json")].filter(t=>t!==void 0&&p(t)).map(t=>[t,k(t,"utf8")]);return()=>{for(const[t,n]of a)k(t,"utf8")!==n&&q(t,n,"utf8")}},Y="<replace-with-d1-create-id>",N=e=>Array.isArray(e)?e.filter(r=>r!=null):void 0,x=(e,r)=>{const a=H(e);if(!a)return;const{parsed:t}=C(a);if(t===void 0)return;const{error:n,merged:o}=G(t,r),i=n===void 0?o:t,{containers:s,d1_databases:c,vars:d}=i;return{containers:N(s),d1_databases:N(c),vars:typeof d=="object"&&d!==null&&!Array.isArray(d)?d:void 0}},Ve=/^127(?:\.\d{1,3}){3}$/,He=e=>{try{const{hostname:r}=new URL(e);return r==="localhost"||Ve.test(r)||r==="::1"||r==="[::1]"}catch{return!1}},Ge=e=>e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.includes("Dockerfile"),Ke=(e,r,a,t="deploy",n)=>{const o=(x(e,n)?.containers??[]).filter(s=>typeof s?.image=="string"&&Ge(s.image));if(o.length===0||a())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},z=e=>p(y(e,_))?_:void 0,qe=(e,r,a="deploy")=>{for(const t of B(e,"lunora").containers){const n=t.schedulingPolicy===void 0?t.image:void 0,i=[...n?.kind==="dockerfile"?[{field:"image",path:n.dockerfilePath}]:[],...Object.entries(t.schedulingPolicy==="durable_object"?t.images??{}:{}).flatMap(([s,c])=>c.kind==="dockerfile"?[{field:`images["${s}"]`,path:c.dockerfilePath}]:[])].find(s=>!p(y(e,s.path)));if(i!==void 0){const s=`${a} blocked: container "${t.exportName}" references a Dockerfile at "${i.path}" that does not exist. Create it or fix the \`${i.field}\` path in lunora/containers.ts.`;return r.error(s),s}if(n?.kind==="build"&&!p(y(e,n.buildDir))){const s=`${a} blocked: container "${t.exportName}" references a Railpack build directory "${n.buildDir}" that does not exist. Create it or fix the \`image.build\` path in lunora/containers.ts.`;return r.error(s),s}}},Ye=(e,r)=>(x(e,r)?.d1_databases??[]).find(a=>a.database_id===Y)?.binding,ze=e=>{if(!e.migrate||e.dryRun||e.preview)return;if(e.migrateUrl===void 0){const a="--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(a),a}if(e.migrateYes!==!0){const a="--migrate runs production data migrations after deploy. Re-run with --migrate-yes to confirm.";return e.logger.error(a),a}const r=e.migrateToken??process.env.LUNORA_ADMIN_TOKEN;if(r===void 0||r===""){const a="admin token required for --migrate — pass --migrate-token or set LUNORA_ADMIN_TOKEN";return e.logger.error(a),a}},Je=(e,r,a="deploy",t)=>{const n=Ye(e,t);if(n===void 0)return;const o=`${a} blocked: the "${n}" D1 binding has a placeholder database_id ("${Y}"). 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},Xe=(e,r,a="deploy",t)=>{const n=x(e,t)?.vars;if(!n)return;const o=Object.entries(n).filter(([,s])=>typeof s=="string"&&He(s)).map(([s])=>s).toSorted((s,c)=>s.localeCompare(c));if(o.length===0)return;const i=`${a} 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},Qe=(e,r,a)=>{const t=Je(e,r.logger,a,r.env);if(t!==void 0)return{code:v.USAGE,error:t};const n=Xe(e,r.logger,a,r.env);if(n!==void 0)return{code:v.USAGE,error:n};const o=qe(e,r.logger,a);if(o!==void 0)return{code:v.USAGE,error:o};const i=Ke(e,r.logger,r.dockerAvailable??xe,a,r.env);return i===void 0?void 0:{code:v.MISSING_DEPENDENCY,error:i}},Ze=/https?:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/u,er=/https:\/\/[^\s"'<>]+/u,rr=e=>{if(e===void 0)return;const r=Ze.exec(e);return r?r[0]:er.exec(e)?.[0]},I=e=>e===void 0?"":` (--env ${e})`,tr=({cwd:e,env:r,logger:a,now:t,url:n})=>{if(n!==void 0)try{const o=U(e);if(o!==void 0){if(o.workerUrl===n&&o.env===r)return;a.warn(`link: .lunora/project.json records ${o.workerUrl??"(no url)"}${I(o.env)}, but this deploy published ${n}${I(r)}. Keeping the recorded value — run \`lunora link --url ${n}${r===void 0?"":` --env ${r}`}\` to update it.`);return}const i=(t??(()=>new Date().toISOString()))();ne(e,{env:r,linkedAt:i,workerName:P(e),workerUrl:n}),a.success(`link: recorded ${n} in .lunora/project.json (run \`lunora link\` to change)`)}catch{}},nr=async(e,r)=>{const a=new Le({skipAddingFilesFromTsConfig:!0}),t=y(r,"lunora");let n;try{n=ee(a,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(n.length===0)return e.logger.info("--migrate: no data migrations declared in lunora/"),0;e.logger.info(`--migrate: running ${String(n.length)} migration(s) against deployed worker`);for(const o of n){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 Ue(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},ar=async(e,r)=>{const{info:a}=F(r,"lunora"),t=a?.vectorMetadata??[];if(t.length===0)return;const n=[];for(const s of t){const c=$e(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}n.push({index:s.index,property:s.property,type:c})}if(n.length===0)return;const i=(await Se({cwd:r,entries:n,exec:O(b(r),"wrangler",[]),logger:e.logger,spawner:e.spawner??$})).filter(s=>s.status!=="failed").length;i>0&&e.logger.success(`vectorize metadata indexes ready: ${String(i)}/${String(n.length)}`)},L=5,or=2e3,ir=async(e,r,a)=>{if(e.healthCheck!==!0)return;const t=a??K({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 n=await _e({attempts:L,baseUrl:t,delayMs:or,fetchImpl:e.healthFetch,paths:[Te,Ne],sleep:e.healthSleep});return n.error===void 0?(e.logger.success(`health check ok (${n.url})`),{ok:!0,url:n.url}):(e.logger.error(`--health-check: the deploy succeeded, but the new version did not answer after ${String(L)} attempt(s) — ${n.error}`),{error:n.error,ok:!1,url:n.url})},sr=async(e,r,a,t,n,o)=>{await ar(e,r);const i=e.migrate?await nr(e,r):0;return i===0&&n?.(),{code:i,descriptor:a,mintedSecretsFile:o,validation:t}},cr=async({cwd:e,descriptor:r,mintedSecretsFile:a,options:t,reblessSchemaBaseline:n,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:rr(o),workerName:P(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:a,validation:i};t.temporary!==!0&&tr({cwd:e,env:t.env,logger:t.logger,url:s.url});const c=await ir(t,e,s.url);return c?.error!==void 0?{code:v.UNAVAILABLE,deployment:s,descriptor:r,healthCheck:c,mintedSecretsFile:a,validation:i}:{...await sr(t,e,r,i,n,a),deployment:s,healthCheck:c}},lr=(e,r,a)=>{const t=y(e,w);if(!p(t))return;let n;try{n=M(k(t,"utf8")).length}catch{return}if(n===0)return;const o=a.toolchain?.secretPut!==void 0;r.warn(o?`Note: \`lunora deploy\` does not push secrets. ${w} has ${String(n)} key(s); if you changed them, run \`lunora env push --yes\` to update the deployed secrets.`:`Note: ${a.name} deploys read no secrets. ${w} has ${String(n)} key(s) that only the dev server sees; put the values the deployed worker needs in wrangler \`vars\`.`)},dr=async e=>{let r=[];try{r=ae(await W({projectRoot:e,schemaDir:R(e)}))}catch{}const a=oe(r).map(n=>n.key);let t=[];try{const n=y(e,w);p(n)&&(t=M(k(n,"utf8")).map(o=>o.key).filter(o=>De(o)))}catch{}return[...new Set([...a,...t])]},ur=async(e,r,a,t)=>{const{logger:n}=r,o=r.spawner??$,i=b(e),s=r.env===void 0?"":` --env ${r.env}`,c=t.toolchain?.secretPut;if(c===void 0)return n.error(`deploy target "${t.id}" has no secret store; cannot push secrets`),{minted:[],ok:!1};const d=[];for(const l of a){const g=ie(),u=c({environment:r.env,key:l,temporary:r.temporary}),m=A(i,u),f=await o({args:m.args,command:m.command,cwd:e,input:g});if(f.code!==0)return n.error(`failed to push secret ${l} (exit ${String(f.code)}); set it manually with \`wrangler secret put ${l}${s}\`.`),{minted:d,ok:!1};d.push({key:l,value:g}),n.success(`generated + pushed ${l}`)}return{minted:d,ok:!0}},gr=/^[\w-]+$/u,D=[".dev.vars",".dev.vars.*","!.dev.vars.example"],mr=/\r?\n/u,fr=(e,r)=>{const a=y(e,".gitignore");try{const t=p(a)?k(a,"utf8"):"",n=new Set(t.split(mr).map(c=>c.trim())),o=D.filter(c=>!n.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(`
1
+ import{dirname as F,join as B}from"node:path";import{discoverMigrations as te,readServiceBindings as ne,runCodegen as oe}from"@lunora/codegen";import{readLinkedProject as W,execArgsFor as H,detectPackageManager as b,discoverContainerInfo as V,COMPOSED_WORKER_ENTRY as N,writeLinkedProject as ae,discoverSchemaInfo as G,DEV_VARS_FILE as w,parseDevVariableEntries as K,isMintableSecretKey as I,packageNamesFromBindings as ie,inferLunoraBindings as q,resolveSchemaDirectory as R,requiredSecrets as se,generateSecretValue as ce,toolchainExecArgs as j,upsertDevVariableLine as de,writeDevVariablesFileAtomically as le,resolveDeployDriver as C,planToolchainInvocation as Y,runPostCodegenHook as ue}from"@lunora/config";import{findWranglerFile as z,readWranglerJsonc as P,mergeWranglerEnvironment as J,warnCloudflareCliConfigOnce as ge,validateWranglerProject as me,reconcileWranglerBindings as fe,reconcileWranglerCompatibilityDate as ve,reconcileWranglerCrons as he,describePreservedCrons as pe}from"@lunora/config/cloudflare";import{Spinner as ye}from"@visulima/spinner";import{r as we,a as ke,e as be}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as $e,a as Se}from"../packem_shared/deploy-target-DCWwiuAe.mjs";import{mkdirSync as De,writeFileSync as x,existsSync as p,readFileSync as k}from"node:fs";import{m as Ee,e as Ae,i as Re,b as je,a as Ce}from"../packem_shared/secret-key-BCrqNJ68.mjs";import{w as Pe}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{d as xe}from"../packem_shared/command-CAXl2A1S.mjs";import{r as _}from"../packem_shared/wrangler-name-Dsk5K1f-.mjs";import{EXIT_CODE as h}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{containerBuildTag as _e}from"@lunora/container";import{a as Te,i as Ne}from"../packem_shared/docker-DpVxvYpL.mjs";import{defaultSpawner as D}from"../packem_shared/createRecordingSpawner-Ch7zuQQE.mjs";import{r as X}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{p as Ie,H as Le,a as Me,r as Ue}from"../packem_shared/health-probe-Bw9JFfIy.mjs";import{join as y}from"@visulima/path";import{Project as Oe}from"ts-morph";import{runMigrateDataCommand as Fe}from"../packem_shared/runMigrateGenerateCommand-Ii_WMZEA.mjs";import{c as Be}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{l as We}from"../packem_shared/wrangler-secrets-3chIVv3H.mjs";const He=Object.freeze({edges:[],nodes:[],modules:[],unresolved:[],version:1}),Ve=20,L=e=>`${e.from} -${e.kind}-> ${e.to}`,$=(e,r)=>{const o=new Set(e);return r.filter(t=>!o.has(t)).toSorted((t,n)=>t.localeCompare(n))},Ge=(e,r)=>{const o=e.modules.map(i=>i.name),t=r.modules.map(i=>i.name),n=e.edges.map(i=>L(i)),a=r.edges.map(i=>L(i));return{addedEdges:$(n,a),addedModules:$(o,t),removedEdges:$(a,n),removedModules:$(t,o)}},S=(e,r,o)=>{if(o.length===0)return[];const t=o.slice(0,Ve).map(a=>` ${e} ${a}`),n=o.length-t.length;return[`${r}:`,...t,...n>0?[` … and ${n.toString()} more`]:[]]},Ke=e=>{const r=[...S("+","modules added",e.addedModules),...S("-","modules removed",e.removedModules),...S("+","edges added",e.addedEdges),...S("-","edges removed",e.removedEdges)];return r.length===0?void 0:`architecture changes since the last deploy:
2
+ ${r.join(`
3
+ `)}`},qe=(e,r)=>B(e,".lunora",r===void 0?"architecture.json":`architecture.${r}.json`),Ye=e=>{if(p(e))try{const r=JSON.parse(k(e,"utf8"));return r.version===1&&Array.isArray(r.modules)&&Array.isArray(r.edges)?r:void 0}catch{return}},ze=e=>{const{cwd:r,environment:o,logger:t}=e,n=qe(r,o),a=Ye(n),i=e.current??(a===void 0?void 0:He);if(i===void 0)return;const s=a===void 0?void 0:Ke(Ge(a,i));return s!==void 0&&t.info(s),()=>{try{De(F(n),{recursive:!0}),x(n,`${JSON.stringify(i,void 0,2)}
4
+ `,"utf8")}catch(c){t.warn(`could not record the deployed architecture at ${n}: ${c instanceof Error?c.message:String(c)}`)}}},Je=e=>{const{cwd:r,env:o,logger:t,mintedSecretsFile:n}=e;try{const a=W(r),i=a?.workerName??_(r),s=e.url??a?.workerUrl;t.success("deploy complete"),t.info(` worker: ${i??"(see wrangler output above)"}`),o!==void 0&&t.info(` env: ${o}`),s===void 0?t.info(" url: run `lunora link --url <https://your-worker>` to record it"):t.info(` url: ${s}`),n!==void 0&&t.info(` secrets: generated value(s) recorded in ${n}`),e.logsAvailable&&t.info(" logs: lunora logs")}catch{}},Xe=async e=>{if(e.targets.length===0)return{builtTags:[],code:0};if(!(e.railpackAvailable??Te)()){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??D,o=[];for(const t of e.targets){const n=_e(t.exportName),a={args:["build",t.buildDir,"--name",n],command:"railpack",cwd:e.cwd},i=H(b(e.cwd),"wrangler",["containers","push",n]),s={args:i.args,command:i.command,cwd:e.cwd};e.logger.info(`railpack: building "${t.exportName}" → ${n} from ${t.buildDir}`);const c=await r(a);if(c.code!==0){const d=`railpack build failed for container "${t.exportName}" (${t.buildDir})`;return e.logger.error(d),{builtTags:o,code:c.code,error:d}}e.logger.info(`railpack: pushing ${n} to the Cloudflare Registry`);const l=await r(s);if(l.code!==0){const d=`wrangler containers push failed for "${t.exportName}" (${n})`;return e.logger.error(d),{builtTags:o,code:l.code,error:d}}o.push(n)}return{builtTags:o,code:0}},Qe=e=>{const o=[z(e),B(e,"package.json")].filter(t=>t!==void 0&&p(t)).map(t=>[t,k(t,"utf8")]);return()=>{for(const[t,n]of o)k(t,"utf8")!==n&&x(t,n,"utf8")}},Q="<replace-with-d1-create-id>",M=e=>Array.isArray(e)?e.filter(r=>r!=null):void 0,T=(e,r)=>{const o=z(e);if(!o)return;const{parsed:t}=P(o);if(t===void 0)return;const{error:n,merged:a}=J(t,r),i=n===void 0?a:t,{containers:s,d1_databases:c,vars:l}=i;return{containers:M(s),d1_databases:M(c),vars:typeof l=="object"&&l!==null&&!Array.isArray(l)?l:void 0}},Ze=/^127(?:\.\d{1,3}){3}$/,er=e=>{try{const{hostname:r}=new URL(e);return r==="localhost"||Ze.test(r)||r==="::1"||r==="[::1]"}catch{return!1}},rr=e=>e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.includes("Dockerfile"),tr=(e,r,o,t="deploy",n)=>{const a=(T(e,n)?.containers??[]).filter(s=>typeof s?.image=="string"&&rr(s.image));if(a.length===0||o())return;const i=`${t} blocked: wrangler.jsonc declares ${String(a.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},Z=e=>p(y(e,N))?N:void 0,nr=(e,r,o="deploy")=>{for(const t of V(e,"lunora").containers){const n=t.schedulingPolicy===void 0?t.image:void 0,i=[...n?.kind==="dockerfile"?[{field:"image",path:n.dockerfilePath}]:[],...Object.entries(t.schedulingPolicy==="durable_object"?t.images??{}:{}).flatMap(([s,c])=>c.kind==="dockerfile"?[{field:`images["${s}"]`,path:c.dockerfilePath}]:[])].find(s=>!p(y(e,s.path)));if(i!==void 0){const s=`${o} blocked: container "${t.exportName}" references a Dockerfile at "${i.path}" that does not exist. Create it or fix the \`${i.field}\` path in lunora/containers.ts.`;return r.error(s),s}if(n?.kind==="build"&&!p(y(e,n.buildDir))){const s=`${o} blocked: container "${t.exportName}" references a Railpack build directory "${n.buildDir}" that does not exist. Create it or fix the \`image.build\` path in lunora/containers.ts.`;return r.error(s),s}}},or=(e,r)=>(T(e,r)?.d1_databases??[]).find(o=>o.database_id===Q)?.binding,ar=e=>{if(!e.migrate||e.dryRun||e.preview)return;if(e.migrateUrl===void 0){const o="--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(o),o}if(e.migrateYes!==!0){const o="--migrate runs production data migrations after deploy. Re-run with --migrate-yes to confirm.";return e.logger.error(o),o}const r=e.migrateToken??process.env.LUNORA_ADMIN_TOKEN;if(r===void 0||r===""){const o="admin token required for --migrate — pass --migrate-token or set LUNORA_ADMIN_TOKEN";return e.logger.error(o),o}},ir=(e,r,o="deploy",t)=>{const n=or(e,t);if(n===void 0)return;const a=`${o} blocked: the "${n}" D1 binding has a placeholder database_id ("${Q}"). 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(a),a},sr=(e,r,o="deploy",t)=>{const n=T(e,t)?.vars;if(!n)return;const a=Object.entries(n).filter(([,s])=>typeof s=="string"&&er(s)).map(([s])=>s).toSorted((s,c)=>s.localeCompare(c));if(a.length===0)return;const i=`${o} blocked: ${a.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},cr=(e,r,o)=>{const t=ir(e,r.logger,o,r.env);if(t!==void 0)return{code:h.USAGE,error:t};const n=sr(e,r.logger,o,r.env);if(n!==void 0)return{code:h.USAGE,error:n};const a=nr(e,r.logger,o);if(a!==void 0)return{code:h.USAGE,error:a};const i=tr(e,r.logger,r.dockerAvailable??Ne,o,r.env);return i===void 0?void 0:{code:h.MISSING_DEPENDENCY,error:i}},dr=/https?:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/u,lr=/https:\/\/[^\s"'<>]+/u,ur=e=>{if(e===void 0)return;const r=dr.exec(e);return r?r[0]:lr.exec(e)?.[0]},U=e=>e===void 0?"":` (--env ${e})`,gr=({cwd:e,env:r,logger:o,now:t,url:n})=>{if(n!==void 0)try{const a=W(e);if(a!==void 0){if(a.workerUrl===n&&a.env===r)return;o.warn(`link: .lunora/project.json records ${a.workerUrl??"(no url)"}${U(a.env)}, but this deploy published ${n}${U(r)}. Keeping the recorded value — run \`lunora link --url ${n}${r===void 0?"":` --env ${r}`}\` to update it.`);return}const i=(t??(()=>new Date().toISOString()))();ae(e,{env:r,linkedAt:i,workerName:_(e),workerUrl:n}),o.success(`link: recorded ${n} in .lunora/project.json (run \`lunora link\` to change)`)}catch{}},mr=async(e,r)=>{const o=new Oe({skipAddingFilesFromTsConfig:!0}),t=y(r,"lunora");let n;try{n=te(o,t)}catch(a){const i=a instanceof Error?a.message:String(a);return e.logger.warn(`--migrate: could not discover migrations (${i}); skipping`),0}if(n.length===0)return e.logger.info("--migrate: no data migrations declared in lunora/"),0;e.logger.info(`--migrate: running ${String(n.length)} migration(s) against deployed worker`);for(const a of n){e.logger.info(`--migrate: up "${a.id}" (table "${a.table}")`);const i={cwd:r,fetchImpl:e.fetchImpl,id:a.id,logger:e.logger,prod:!0,subcommand:"up",token:e.migrateToken,url:e.migrateUrl,yes:e.migrateYes===!0},s=await Fe(i);if(s.code!==0)return e.logger.error(`--migrate: migration "${a.id}" failed — see output above`),s.code;e.logger.success(`--migrate: "${a.id}" applied`)}return 0},fr=async(e,r)=>{const{info:o}=G(r,"lunora"),t=o?.vectorMetadata??[];if(t.length===0)return;const n=[];for(const s of t){const c=Ee(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}n.push({index:s.index,property:s.property,type:c})}if(n.length===0)return;const i=(await Ae({cwd:r,entries:n,exec:H(b(r),"wrangler",[]),logger:e.logger,spawner:e.spawner??D})).filter(s=>s.status!=="failed").length;i>0&&e.logger.success(`vectorize metadata indexes ready: ${String(i)}/${String(n.length)}`)},O=5,vr=2e3,hr=async(e,r,o)=>{if(e.healthCheck!==!0)return;const t=o??X({cwd:r,env:e.env});if(t===void 0){const a="--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(a),{error:a,ok:!1,url:""}}const n=await Ie({attempts:O,baseUrl:t,delayMs:vr,fetchImpl:e.healthFetch,paths:[Le,Me],sleep:e.healthSleep});return n.error===void 0?(e.logger.success(`health check ok (${n.url})`),{ok:!0,url:n.url}):(e.logger.error(`--health-check: the deploy succeeded, but the new version did not answer after ${String(O)} attempt(s) — ${n.error}`),{error:n.error,ok:!1,url:n.url})},pr=async(e,r,o,t,n,a)=>{await fr(e,r);const i=e.migrate?await mr(e,r):0;return i===0&&n?.(),{code:i,descriptor:o,mintedSecretsFile:a,validation:t}},yr=async({cwd:e,descriptor:r,mintedSecretsFile:o,options:t,reblessSchemaBaseline:n,recordArchitecture:a,stdout:i,validation:s})=>{const c={deployedAt:new Date().toISOString(),dryRun:t.dryRun===!0,env:t.env,preview:t.preview===!0,url:t.dryRun===!0?void 0:ur(i),workerName:_(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:c,descriptor:r,mintedSecretsFile:o,validation:s};t.temporary!==!0&&(a?.(),gr({cwd:e,env:t.env,logger:t.logger,url:c.url}));const l=await hr(t,e,c.url);return l?.error!==void 0?{code:h.UNAVAILABLE,deployment:c,descriptor:r,healthCheck:l,mintedSecretsFile:o,validation:s}:{...await pr(t,e,r,s,n,o),deployment:c,healthCheck:l}},wr=(e,r,o)=>{const t=y(e,w);if(!p(t))return;let n;try{n=K(k(t,"utf8")).length}catch{return}if(n===0)return;const a=o.toolchain?.secretPut!==void 0;r.warn(a?`Note: \`lunora deploy\` does not push secrets. ${w} has ${String(n)} key(s); if you changed them, run \`lunora env push --yes\` to update the deployed secrets.`:`Note: ${o.name} deploys read no secrets. ${w} has ${String(n)} key(s) that only the dev server sees; put the values the deployed worker needs in wrangler \`vars\`.`)},kr=async e=>{let r=[];try{r=ie(await q({projectRoot:e,schemaDir:R(e)}))}catch{}const o=se(r).map(n=>n.key);let t=[];try{const n=y(e,w);p(n)&&(t=K(k(n,"utf8")).map(a=>a.key).filter(a=>Re(a)))}catch{}return[...new Set([...o,...t])]},br=async(e,r,o,t)=>{const{logger:n}=r,a=r.spawner??D,i=b(e),s=r.env===void 0?"":` --env ${r.env}`,c=t.toolchain?.secretPut;if(c===void 0)return n.error(`deploy target "${t.id}" has no secret store; cannot push secrets`),{minted:[],ok:!1};const l=[];for(const d of o){const g=ce(),m=c({environment:r.env,key:d,temporary:r.temporary}),u=j(i,m),f=await a({args:u.args,command:u.command,cwd:e,input:g});if(f.code!==0)return n.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}),n.success(`generated + pushed ${d}`)}return{minted:l,ok:!0}},$r=/^[\w-]+$/u,E=[".dev.vars",".dev.vars.*","!.dev.vars.example"],Sr=/\r?\n/u,Dr=(e,r)=>{const o=y(e,".gitignore");try{const t=p(o)?k(o,"utf8"):"",n=new Set(t.split(Sr).map(c=>c.trim())),a=E.filter(c=>!n.has(c));if(a.length===0)return;const i=a.some(c=>!c.startsWith("!"))?[...a.filter(c=>!c.startsWith("!")),...E.filter(c=>c.startsWith("!"))]:a,s=t.length>0&&!t.endsWith(`
2
5
  `)?`
3
- `:"";q(a,`${t}${s}
6
+ `:"";x(o,`${t}${s}
4
7
  # Lunora — never commit a minted secret
5
8
  ${i.join(`
6
9
  `)}
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.`)}},vr=(e,r,a)=>{if(a.length===0)return;const t=a.map(s=>s.key).join(", ");if(r.env!==void 0&&!gr.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 n=r.env===void 0?w:`${w}.${r.env}`;fr(e,r.logger);const o=y(e,n);let i=p(o)?k(o,"utf8"):"";for(const s of a)i=se(i,s.key,s.value);return ce(o,i),r.logger.success(r.env===void 0?`${t}: value(s) recorded in ${n}`:`${t}: value(s) recorded in ${n} (kept separate from ${w} so \`lunora dev\` and a plain \`lunora env push\` don't inherit the --env ${r.env} value)`),n},hr=async(e,r,a,t)=>{if(r.dryRun===!0||r.preview===!0)return{};const{logger:n}=r,o=r.env===void 0?"":` --env ${r.env}`;let i;try{i=await(r.secretLister??Be)({cwd:e,env:r.env,temporary:r.temporary})}catch{return{}}if(!i.ok)return{};const s=new Set(i.names),d=(await dr(e)).filter(u=>!s.has(u));if(d.length===0)return{};if(!a)return{error:`missing required secret(s) on the deploy target: ${d.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 d.filter(m=>!T(m)))n.warn(`required secret ${u} is not set on the target — set it with: wrangler secret put ${u}${o}`);const l=d.filter(u=>T(u));if(l.length===0)return{};if(await(r.secretConfirm??Oe())(`${String(l.length)} required secret(s) not set on the target (${l.join(", ")}). Generate strong values and push them now?`)){const{minted:u,ok:m}=await ur(e,r,l,t),f=vr(e,r,u);return m?{mintedSecretsFile:f}:{error:"failed to push required secret(s) — set them manually and re-deploy",mintedSecretsFile:f}}return n.warn(`${String(l.length)} required secret(s) not set on the target: ${l.join(", ")}. Generate + push with \`lunora env generate --set\` then \`lunora env push --yes${o}\`.`),{}},J=e=>e.format==="json"?!1:e.interactive!==void 0?e.interactive:process.stdout.isTTY&&!process.env.CI,pr=async(e,r)=>{if(r.dryRun===!0)return;const a=B(e,"lunora").containers.flatMap(n=>n.schedulingPolicy===void 0&&n.image.kind==="build"?[{buildDir:n.image.buildDir,exportName:n.exportName}]:[]);if(a.length===0)return;const t=await Me({cwd:e,logger:r.logger,railpackAvailable:r.railpackAvailable,spawner:r.spawner,targets:a});return t.code===0?void 0:t.error??"railpack build failed"},yr=(e,r,a)=>{if(a!==void 0)try{const t=fe(e,a);t.changed&&r.success(`synced ${String(a.length)} cron trigger(s) → ${t.wranglerPath??"wrangler.jsonc"}`);for(const o of t.warnings)r.warn(o);const n=ve(t.preserved);n!==void 0&&r.info(n)}catch(t){const n=t instanceof Error?t.message:String(t);r.warn(`cron trigger sync skipped: ${n}`)}},wr=async(e,r,a,t,n)=>{try{j(t);const o=await W({projectRoot:e,schemaDir:R(e)}),i=ge(e,o,n),s=i.wranglerPath??"wrangler.jsonc";if(i.added.length>0&&r.success(`provisioned bindings: ${i.added.join(", ")} → ${s}`),i.updated.length>0&&r.success(`updated bindings: ${i.updated.join(", ")} → ${s}`),i.devConfig!==void 0){const{added:c,path:d,updated:l}=i.devConfig;r.success(`dev sidecar bindings: ${[...c,...l].join(", ")} → ${d}`)}for(const c of i.warnings)r.warn(c)}catch(o){const i=o instanceof Error?o.message:String(o);r.warn(`binding inference skipped: ${i}`)}try{const o=me(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}`)}yr(e,r,a)},kr=async(e,r,a,t,n,o,i,s)=>{let c;r?(c=new he({name:"dots"}),c.start("running codegen")):a.info("running codegen");try{const d=te({apiSpec:t,projectRoot:e,target:n});c?.succeed("codegen complete"),c||a.success("codegen complete");const l=ye(d.platformDiagnostics,a);if(l.errors.length>0)return{error:l.errors.join("; ")};const{errorAdvisories:g,names:u,shouldBlock:m}=we(d.advisories,s);if(m){const h=`${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 a.error(h),{error:h}}const f=await le({cwd:e,logger:a,spawner:o,stdoutToStderr:i});return f.error!==void 0?{error:f.error}:{result:d}}catch(d){c?.failed("codegen failed");const l=d instanceof Error?d.message:String(d);return a.error(`codegen failed: ${l}`),{error:`codegen failed: ${l}`}}},br=(e,r)=>({dryRun:r.dryRun,entry:z(e),environment:r.env,outDir:r.outDir,preview:r.preview,temporary:r.temporary}),X=(e,r,a)=>{const{toolchain:t}=a;if(t===void 0)throw new Error(`deploy target "${a.id}" has no command-line toolchain`);const n=br(e,r);return V(a,e,"deploy",o=>t.deploy({...n,configPath:o}))},$r=(e,r,a)=>{const t=X(e,r,a),n=z(e);return n!==void 0&&r.logger.info(`class-B composition: deploying ${n} (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}`),t.commit(),t.projection!==void 0&&t.projection.dropped.length>0&&r.logger.warn(`${a.name} ignores these wrangler keys, so they were left out of ${t.projection.configPath}: ${t.projection.dropped.join(", ")}`),t.command},E=(e,r)=>({code:v.USAGE,descriptor:void 0,error:e,validation:{problems:[],wranglerPath:void 0},...r}),Sr=(e,r)=>{for(const a of e.report?.warnings??[])r.warn(`wrangler.jsonc: ${a}`);if(e.problems.length===0)return!1;r.error("wrangler.jsonc validation failed:");for(const a of e.problems)r.error(` - ${a}`);return!0},Dr=(e,r,a)=>{const t=r.format==="json",n=r.dryRun!==!0,o=$r(e,r,a),i=A(b(e),o);return{args:i.args,captureStdout:n&&!t,captureStdoutSilently:n&&t,command:i.command,cwd:e,stdoutToStderr:t&&!n}},Er=async(e,r)=>{const a=e.cwd??process.cwd(),t=J(e),n=pe(e),o={problems:[],wranglerPath:void 0},i=be(a,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;try{X(a,e,j(s))}catch(u){const m=u instanceof Error?u.message:String(u);return e.logger.error(m),{error:m,target:s,validation:o}}let c;if(!e.skipCodegen){const u=await kr(a,t,e.logger,e.apiSpec,s,e.spawner,e.format==="json",n);if(u.error!==void 0)return{error:u.error,target:s,validation:o};c=u.result}let d;if(c!==void 0){const u=Ie({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};d=u.rebless}await wr(a,e.logger,c?.cronTriggers,s,e.env);const l=Qe(a,e,r);if(l!==void 0)return{code:l.code,error:l.error,target:s,validation:o};const g=ue({environment:e.env,projectRoot:a});return Sr(g,e.logger)?{error:"wrangler validation failed",target:s,validation:g}:{codegen:c,reblessSchemaBaseline:d,target:s,validation:g}},Rr=e=>{if(e.skipServices===!0)return"--skip-services";if(e.preview===!0)return"--preview uploads the app version only";if(e.temporary===!0)return"--temporary deploys the app to a throwaway account"},Ar=async(e,r,a,t)=>{const{error:n,services:o}=re(e);if(n!==void 0)return n;if(o.length===0)return;const{toolchain:i}=a,s=i===void 0?`target "${a.id}" has no deploy command`:Rr(r);if(s!==void 0||i===void 0){const l=o.map(g=>g.worker).join(", ");r.logger.warn(`services not deployed (${s??""}): ${l} — deploy them yourself if the app calls anything new`);return}const c=b(e),d=[...new Map(o.map(l=>[l.wranglerPath,l])).values()];for(const l of d){const g=Z(l.wranglerPath);let u;try{u=V(a,g,"deploy",h=>i.deploy({configPath:h??l.wranglerPath,dryRun:r.dryRun===!0,environment:r.env}))}catch(h){return`service ${l.name} (${l.worker}): ${h instanceof Error?h.message:String(h)}`}u.commit();const m=A(c,u.command);r.logger.info(`deploying service ${l.name} (${l.worker}) via ${m.command} ${m.args.join(" ")}`);const f=await t({args:m.args,command:m.command,cwd:g,stdoutToStderr:r.format==="json"});if(f.code!==0)return`service ${l.name} (${l.worker}): ${m.command} ${m.args.join(" ")} exited ${String(f.code)} — stopping before the app`}},jr=async(e,r,a,t)=>{if(r!=="cloudflare")return;const n=e===void 0?void 0:C(e).parsed,o=(a===void 0?void 0:n?.env?.[a]?.account_id)??n?.account_id,i=await Re({accountId:o});(i.verdict==="near"||i.verdict==="full")&&t.warn(i.fix===void 0?i.message:`${i.message} ${i.fix}`)},Cr=async(e,r,a,t,n)=>{const o=a==="cloudflare"&&r!==void 0?C(r).parsed:void 0;if(o===void 0)return;const i=(G(o,t).merged.artifacts??[]).flatMap(g=>typeof g?.binding=="string"&&typeof g.namespace=="string"?[{binding:g.binding,namespace:g.namespace}]:[]),s=i.length===0?void 0:F(e,R(e)).info?.jurisdiction;if(s===void 0)return;const c=(t===void 0?void 0:o.env?.[t]?.account_id)??o.account_id,d=await Promise.all(i.map(async g=>Ee({...g,accountId:c,jurisdiction:s}))),l=[];for(const g of d){const u=g.fix===void 0?g.message:`${g.message} ${g.fix}`;g.verdict==="unchecked"?n.warn(u):g.verdict!=="ok"&&(n.error(u),l.push(u))}return l.length===0?void 0:l.join(`
8
- `)},Pr=async e=>{const r=e.cwd??process.cwd(),a=J(e),t=await Er(e,e.commandName??"deploy");if(t.error!==void 0){if(t.validation.problems.length>0)return{code:v.USAGE,descriptor:void 0,error:t.error,validation:t.validation};const S=t.schemaDrift===void 0?void 0:{schemaDrift:t.schemaDrift};return E(t.error,{...S,...t.code===void 0?{}:{code:t.code}})}const{reblessSchemaBaseline:n,validation:o}=t,i=j(t.target),s=ze(e)??await Cr(r,o.wranglerPath,t.target,e.env,e.logger);if(s!==void 0)return E(s);const c=i.toolchain?.prebuildsContainerImages===!0?await pr(r,e):void 0;if(c!==void 0)return E(c);lr(r,e.logger,i),de(r,S=>{e.logger.warn(S)}),await jr(o.wranglerPath,t.target,e.env,e.logger);const{error:d,mintedSecretsFile:l}=await hr(r,e,a,i);if(d!==void 0)return e.logger.error(d),{code:v.USAGE,descriptor:void 0,error:d,mintedSecretsFile:l,validation:o};const g=e.spawner??$,u=await Ar(r,e,i,g);if(u!==void 0)return{code:v.FAILURE,descriptor:void 0,error:u,mintedSecretsFile:l,validation:o};const m=Dr(r,e,i);e.logger.info(`deploying via ${m.command} ${m.args.join(" ")}`);const f=await g(m);return m.captureStdoutSilently===!0&&f.stdout!==void 0&&f.stdout!==""&&process.stderr.write(f.stdout),f.code!==0?{code:f.code,descriptor:m,mintedSecretsFile:l,validation:o}:{...await cr({cwd:r,descriptor:m,mintedSecretsFile:l,options:e,reblessSchemaBaseline:n,stdout:f.stdout,validation:o}),logsAvailable:i.toolchain?.tail!==void 0}},xr=async e=>{const{logger:r}=e,a=e.dryRun===!0?We(e.cwd??process.cwd()):void 0;let t;try{if(t=await Pr({...e,logger:r}),t.code===0&&e.emitBindings!==void 0){const{error:n}=Ae({destination:e.emitBindings,logger:r,projectRoot:e.cwd??process.cwd()});n!==void 0&&(r.error(n),t={...t,code:v.USAGE})}}finally{a?.()}if(e.format==="json")return t;if(t.code===0&&e.dryRun!==!0&&e.preview!==!0)Fe({cwd:e.cwd??process.cwd(),env:e.env,logger:e.logger,logsAvailable:t.logsAvailable===!0,mintedSecretsFile:t.mintedSecretsFile,url:t.deployment?.url});else if(t.code===0&&e.preview===!0){const n=t.deployment?.url;e.logger.success(n===void 0?"preview version uploaded":`preview version uploaded — ${n}`)}return t},rt=je(async({cwd:e,format:r,logger:a,options:t})=>{const n=await xr({allowSchemaDrift:t.allowSchemaDrift===!0,apiSpec:ke(t.apiSpec),cwd:e,dryRun:t.dryRun===!0,env:t.env,format:r,healthCheck:t.healthCheck===!0,logger:a,migrate:t.migrate===!0,migrateToken:t.migrateToken,migrateUrl:K({cwd:e,env:t.env,url:t.migrateUrl}),migrateYes:t.migrateYes===!0,preview:t.preview===!0,skipCodegen:t.prebuilt===!0,skipServices:t.skipServices===!0,strictAdvisories:t.strictAdvisories,target:t.target,temporary:t.temporary===!0,updateSchemaBaseline:t.updateSchemaBaseline===!0});return{code:n.code,data:{deployment:n.deployment,healthCheck:n.healthCheck,mintedSecretsFile:n.mintedSecretsFile,schemaDrift:n.schemaDrift,validation:n.validation},error:n.error}});export{rt as execute,wr as provisionBindings,xr as runDeployCommand,Er as runPreDeployPipeline};
10
+ `,"utf8"),r.info(`.gitignore: added ${a.join(", ")} so the recorded secret cannot be committed`)}catch(t){r.warn(`could not update .gitignore (${t instanceof Error?t.message:String(t)}) — add \`${E.join("` and `")}\` by hand before committing.`)}},Er=(e,r,o)=>{if(o.length===0)return;const t=o.map(s=>s.key).join(", ");if(r.env!==void 0&&!$r.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 n=r.env===void 0?w:`${w}.${r.env}`;Dr(e,r.logger);const a=y(e,n);let i=p(a)?k(a,"utf8"):"";for(const s of o)i=de(i,s.key,s.value);return le(a,i),r.logger.success(r.env===void 0?`${t}: value(s) recorded in ${n}`:`${t}: value(s) recorded in ${n} (kept separate from ${w} so \`lunora dev\` and a plain \`lunora env push\` don't inherit the --env ${r.env} value)`),n},Ar=async(e,r,o,t)=>{if(r.dryRun===!0||r.preview===!0)return{};const{logger:n}=r,a=r.env===void 0?"":` --env ${r.env}`;let i;try{i=await(r.secretLister??We)({cwd:e,env:r.env,temporary:r.temporary})}catch{return{}}if(!i.ok)return{};const s=new Set(i.names),l=(await kr(e)).filter(m=>!s.has(m));if(l.length===0)return{};if(!o)return{error:`missing required secret(s) on the deploy target: ${l.join(", ")}. Set them with \`wrangler secret put <KEY>${a}\` (or \`lunora env generate --set\` then \`lunora env push --yes${a}\`), then re-deploy.`};for(const m of l.filter(u=>!I(u)))n.warn(`required secret ${m} is not set on the target — set it with: wrangler secret put ${m}${a}`);const d=l.filter(m=>I(m));if(d.length===0)return{};if(await(r.secretConfirm??Be())(`${String(d.length)} required secret(s) not set on the target (${d.join(", ")}). Generate strong values and push them now?`)){const{minted:m,ok:u}=await br(e,r,d,t),f=Er(e,r,m);return u?{mintedSecretsFile:f}:{error:"failed to push required secret(s) — set them manually and re-deploy",mintedSecretsFile:f}}return n.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${a}\`.`),{}},ee=e=>e.format==="json"?!1:e.interactive!==void 0?e.interactive:process.stdout.isTTY&&!process.env.CI,Rr=async(e,r)=>{if(r.dryRun===!0)return;const o=V(e,"lunora").containers.flatMap(n=>n.schedulingPolicy===void 0&&n.image.kind==="build"?[{buildDir:n.image.buildDir,exportName:n.exportName}]:[]);if(o.length===0)return;const t=await Xe({cwd:e,logger:r.logger,railpackAvailable:r.railpackAvailable,spawner:r.spawner,targets:o});return t.code===0?void 0:t.error??"railpack build failed"},jr=(e,r,o)=>{if(o!==void 0)try{const t=he(e,o);t.changed&&r.success(`synced ${String(o.length)} cron trigger(s) → ${t.wranglerPath??"wrangler.jsonc"}`);for(const a of t.warnings)r.warn(a);const n=pe(t.preserved);n!==void 0&&r.info(n)}catch(t){const n=t instanceof Error?t.message:String(t);r.warn(`cron trigger sync skipped: ${n}`)}},Cr=async(e,r,o,t,n)=>{try{C(t);const a=await q({projectRoot:e,schemaDir:R(e)}),i=fe(e,a,n),s=i.wranglerPath??"wrangler.jsonc";if(i.added.length>0&&r.success(`provisioned bindings: ${i.added.join(", ")} → ${s}`),i.updated.length>0&&r.success(`updated bindings: ${i.updated.join(", ")} → ${s}`),i.devConfig!==void 0){const{added:c,path:l,updated:d}=i.devConfig;r.success(`dev sidecar bindings: ${[...c,...d].join(", ")} → ${l}`)}for(const c of i.warnings)r.warn(c)}catch(a){const i=a instanceof Error?a.message:String(a);r.warn(`binding inference skipped: ${i}`)}try{const a=ve(e);a.changed&&r.success(`bumped compatibility_date to ${a.date??"unknown"} (Workers Cache enabled) → ${a.wranglerPath??"wrangler.jsonc"}`)}catch(a){const i=a instanceof Error?a.message:String(a);r.warn(`compatibility date sync skipped: ${i}`)}jr(e,r,o)},Pr=async(e,r,o,t,n,a,i,s)=>{let c;r?(c=new ye({name:"dots"}),c.start("running codegen")):o.info("running codegen");try{const l=oe({apiSpec:t,projectRoot:e,target:n});c?.succeed("codegen complete"),c||o.success("codegen complete");const d=ke(l.platformDiagnostics,o);if(d.errors.length>0)return{error:d.errors.join("; ")};const{errorAdvisories:g,names:m,shouldBlock:u}=be(l.advisories,s);if(u){const v=`${g.length.toString()} ERROR-level ${g.length===1?"advisory":"advisories"} (${m.join(", ")}). Pass --no-strict-advisories to downgrade this to a warning and continue.`;return o.error(v),{error:v}}const f=await ue({cwd:e,logger:o,spawner:a,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 o.error(`codegen failed: ${d}`),{error:`codegen failed: ${d}`}}},xr=(e,r)=>({dryRun:r.dryRun,entry:Z(e),environment:r.env,outDir:r.outDir,preview:r.preview,temporary:r.temporary}),re=(e,r,o)=>{const{toolchain:t}=o;if(t===void 0)throw new Error(`deploy target "${o.id}" has no command-line toolchain`);const n=xr(e,r);return Y(o,e,"deploy",a=>t.deploy({...n,configPath:a}))},_r=(e,r,o)=>{const t=re(e,r,o),n=Z(e);return n!==void 0&&r.logger.info(`class-B composition: deploying ${n} (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}`),t.commit(),t.projection!==void 0&&t.projection.dropped.length>0&&r.logger.warn(`${o.name} ignores these wrangler keys, so they were left out of ${t.projection.configPath}: ${t.projection.dropped.join(", ")}`),t.command},A=(e,r)=>({code:h.USAGE,descriptor:void 0,error:e,validation:{problems:[],wranglerPath:void 0},...r}),Tr=(e,r)=>{for(const o of e.report?.warnings??[])r.warn(`wrangler.jsonc: ${o}`);if(e.problems.length===0)return!1;r.error("wrangler.jsonc validation failed:");for(const o of e.problems)r.error(` - ${o}`);return!0},Nr=(e,r,o)=>{const t=r.format==="json",n=r.dryRun!==!0,a=_r(e,r,o),i=j(b(e),a);return{args:i.args,captureStdout:n&&!t,captureStdoutSilently:n&&t,command:i.command,cwd:e,stdoutToStderr:t&&!n}},Ir=async(e,r)=>{const o=e.cwd??process.cwd(),t=ee(e),n=we(e),a={problems:[],wranglerPath:void 0},i=Se(o,e.target);if(i.target===void 0){const u=i.error??"unknown deploy target";return e.logger.error(u),{error:u,validation:a}}const{target:s}=i;try{re(o,e,C(s))}catch(u){const f=u instanceof Error?u.message:String(u);return e.logger.error(f),{error:f,target:s,validation:a}}let c;if(!e.skipCodegen){const u=await Pr(o,t,e.logger,e.apiSpec,s,e.spawner,e.format==="json",n);if(u.error!==void 0)return{error:u.error,target:s,validation:a};c=u.result}let l;if(c!==void 0){const u=Ue({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:a};l=u.rebless}const d=c&&ze({current:c.architecture,cwd:o,environment:e.env,logger:e.logger});await Cr(o,e.logger,c?.cronTriggers,s,e.env);const g=cr(o,e,r);if(g!==void 0)return{code:g.code,error:g.error,target:s,validation:a};const m=me({environment:e.env,projectRoot:o});return Tr(m,e.logger)?{error:"wrangler validation failed",target:s,validation:m}:{codegen:c,reblessSchemaBaseline:l,recordArchitecture:d,target:s,validation:m}},Lr=e=>{if(e.skipServices===!0)return"--skip-services";if(e.preview===!0)return"--preview uploads the app version only";if(e.temporary===!0)return"--temporary deploys the app to a throwaway account"},Mr=async(e,r,o,t)=>{const{error:n,services:a}=ne(e);if(n!==void 0)return n;if(a.length===0)return;const{toolchain:i}=o,s=i===void 0?`target "${o.id}" has no deploy command`:Lr(r);if(s!==void 0||i===void 0){const d=a.map(g=>g.worker).join(", ");r.logger.warn(`services not deployed (${s??""}): ${d} — deploy them yourself if the app calls anything new`);return}const c=b(e),l=[...new Map(a.map(d=>[d.wranglerPath,d])).values()];for(const d of l){const g=F(d.wranglerPath);let m;try{m=Y(o,g,"deploy",v=>i.deploy({configPath:v??d.wranglerPath,dryRun:r.dryRun===!0,environment:r.env}))}catch(v){return`service ${d.name} (${d.worker}): ${v instanceof Error?v.message:String(v)}`}m.commit();const u=j(c,m.command);r.logger.info(`deploying service ${d.name} (${d.worker}) via ${u.command} ${u.args.join(" ")}`);const f=await t({args:u.args,command:u.command,cwd:g,stdoutToStderr:r.format==="json"});if(f.code!==0)return`service ${d.name} (${d.worker}): ${u.command} ${u.args.join(" ")} exited ${String(f.code)} — stopping before the app`}},Ur=async(e,r,o,t)=>{if(r!=="cloudflare")return;const n=e===void 0?void 0:P(e).parsed,a=(o===void 0?void 0:n?.env?.[o]?.account_id)??n?.account_id,i=await Ce({accountId:a});(i.verdict==="near"||i.verdict==="full")&&t.warn(i.fix===void 0?i.message:`${i.message} ${i.fix}`)},Or=async(e,r,o,t,n)=>{const a=o==="cloudflare"&&r!==void 0?P(r).parsed:void 0;if(a===void 0)return;const i=(J(a,t).merged.artifacts??[]).flatMap(g=>typeof g?.binding=="string"&&typeof g.namespace=="string"?[{binding:g.binding,namespace:g.namespace}]:[]),s=i.length===0?void 0:G(e,R(e)).info?.jurisdiction;if(s===void 0)return;const c=(t===void 0?void 0:a.env?.[t]?.account_id)??a.account_id,l=await Promise.all(i.map(async g=>je({...g,accountId:c,jurisdiction:s}))),d=[];for(const g of l){const m=g.fix===void 0?g.message:`${g.message} ${g.fix}`;g.verdict==="unchecked"?n.warn(m):g.verdict!=="ok"&&(n.error(m),d.push(m))}return d.length===0?void 0:d.join(`
11
+ `)},Fr=async e=>{const r=e.cwd??process.cwd(),o=ee(e),t=await Ir(e,e.commandName??"deploy");if(t.error!==void 0){if(t.validation.problems.length>0)return{code:h.USAGE,descriptor:void 0,error:t.error,validation:t.validation};const v=t.schemaDrift===void 0?void 0:{schemaDrift:t.schemaDrift};return A(t.error,{...v,...t.code===void 0?{}:{code:t.code}})}const{validation:n}=t,a=C(t.target),i=ar(e)??await Or(r,n.wranglerPath,t.target,e.env,e.logger);if(i!==void 0)return A(i);const s=a.toolchain?.prebuildsContainerImages===!0?await Rr(r,e):void 0;if(s!==void 0)return A(s);wr(r,e.logger,a),ge(r,v=>{e.logger.warn(v)}),await Ur(n.wranglerPath,t.target,e.env,e.logger);const{error:c,mintedSecretsFile:l}=await Ar(r,e,o,a);if(c!==void 0)return e.logger.error(c),{code:h.USAGE,descriptor:void 0,error:c,mintedSecretsFile:l,validation:n};const d=e.spawner??D,g=await Mr(r,e,a,d);if(g!==void 0)return{code:h.FAILURE,descriptor:void 0,error:g,mintedSecretsFile:l,validation:n};const m=Nr(r,e,a);e.logger.info(`deploying via ${m.command} ${m.args.join(" ")}`);const u=await d(m);return m.captureStdoutSilently===!0&&u.stdout!==void 0&&u.stdout!==""&&process.stderr.write(u.stdout),u.code!==0?{code:u.code,descriptor:m,mintedSecretsFile:l,validation:n}:{...await yr({...t,cwd:r,descriptor:m,mintedSecretsFile:l,options:e,stdout:u.stdout}),logsAvailable:a.toolchain?.tail!==void 0}},Br=async e=>{const{logger:r}=e,o=e.dryRun===!0?Qe(e.cwd??process.cwd()):void 0;let t;try{if(t=await Fr({...e,logger:r}),t.code===0&&e.emitBindings!==void 0){const{error:n}=Pe({destination:e.emitBindings,logger:r,projectRoot:e.cwd??process.cwd()});n!==void 0&&(r.error(n),t={...t,code:h.USAGE})}}finally{o?.()}if(e.format==="json")return t;if(t.code===0&&e.dryRun!==!0&&e.preview!==!0)Je({cwd:e.cwd??process.cwd(),env:e.env,logger:e.logger,logsAvailable:t.logsAvailable===!0,mintedSecretsFile:t.mintedSecretsFile,url:t.deployment?.url});else if(t.code===0&&e.preview===!0){const n=t.deployment?.url;e.logger.success(n===void 0?"preview version uploaded":`preview version uploaded — ${n}`)}return t},ut=xe(async({cwd:e,format:r,logger:o,options:t})=>{const n=await Br({allowSchemaDrift:t.allowSchemaDrift===!0,apiSpec:$e(t.apiSpec),cwd:e,dryRun:t.dryRun===!0,env:t.env,format:r,healthCheck:t.healthCheck===!0,logger:o,migrate:t.migrate===!0,migrateToken:t.migrateToken,migrateUrl:X({cwd:e,env:t.env,url:t.migrateUrl}),migrateYes:t.migrateYes===!0,preview:t.preview===!0,skipCodegen:t.prebuilt===!0,skipServices:t.skipServices===!0,strictAdvisories:t.strictAdvisories,target:t.target,temporary:t.temporary===!0,updateSchemaBaseline:t.updateSchemaBaseline===!0});return{code:n.code,data:{deployment:n.deployment,healthCheck:n.healthCheck,mintedSecretsFile:n.mintedSecretsFile,schemaDrift:n.schemaDrift,validation:n.validation},error:n.error}});export{ut as execute,Cr as provisionBindings,Br as runDeployCommand,Ir as runPreDeployPipeline};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/cli",
3
- "version": "1.0.0-alpha.359",
3
+ "version": "1.0.0-alpha.360",
4
4
  "description": "The Lunora CLI: init, dev, deploy, codegen, migrate, seed, doctor, insights, logs, registry, and the rest of the project commands",
5
5
  "keywords": [
6
6
  "agent-skills",
@@ -52,16 +52,16 @@
52
52
  },
53
53
  "dependencies": {
54
54
  "@bomb.sh/tab": "0.0.22",
55
- "@lunora/advisor": "1.0.0-alpha.197",
55
+ "@lunora/advisor": "1.0.0-alpha.198",
56
56
  "@lunora/bindings": "1.0.0-alpha.100",
57
- "@lunora/codegen": "1.0.0-alpha.274",
58
- "@lunora/config": "1.0.0-alpha.318",
57
+ "@lunora/codegen": "1.0.0-alpha.275",
58
+ "@lunora/config": "1.0.0-alpha.319",
59
59
  "@lunora/container": "1.0.0-alpha.69",
60
60
  "@lunora/d1": "1.0.0-alpha.167",
61
61
  "@lunora/errors": "1.0.0-alpha.50",
62
- "@lunora/mcp": "1.0.0-alpha.221",
63
- "@lunora/runtime": "1.0.0-alpha.184",
64
- "@lunora/seed": "1.0.0-alpha.199",
62
+ "@lunora/mcp": "1.0.0-alpha.222",
63
+ "@lunora/runtime": "1.0.0-alpha.185",
64
+ "@lunora/seed": "1.0.0-alpha.200",
65
65
  "@visulima/cerebro": "3.1.2",
66
66
  "@visulima/error": "6.1.0",
67
67
  "@visulima/fs": "6.0.28",
@@ -88,7 +88,8 @@ import type { Id } from "#lunora/_generated/server.js";
88
88
  import { action, mutation, query, v } from "#lunora/_generated/server.js";
89
89
 
90
90
  // `api` / `internal` come from codegen:
91
- // import { api, internal } from "./_generated/api";
91
+ // import { api } from "./_generated/api";
92
+ // import { internal } from "./_generated/internal";
92
93
 
93
94
  export const listByChannel = query.input({ channelId: v.id("channels") }).query(async ({ ctx, args: { channelId } }) =>
94
95
  ctx.db
@@ -254,7 +255,7 @@ dead-letter queue.
254
255
  // lunora/queues.ts
255
256
  import { defineSubscription, defineTopic } from "@lunora/queue";
256
257
 
257
- import { internal } from "./_generated/api";
258
+ import { internal } from "./_generated/internal";
258
259
 
259
260
  export const signups = defineTopic<{ userId: string }>();
260
261
 
@@ -351,7 +352,7 @@ never mount.
351
352
  // lunora/http.ts
352
353
  import { httpAction, httpRouter } from "@lunora/server";
353
354
 
354
- import { internal } from "./_generated/api";
355
+ import { internal } from "./_generated/internal";
355
356
 
356
357
  const app = httpRouter();
357
358
 
@@ -86,7 +86,7 @@ I/O). From a mutation, schedule it as a follow-up so the request is not blocked:
86
86
  ```ts
87
87
  import { internalMutation, v } from "#lunora/_generated/server.js";
88
88
 
89
- import { internal } from "./_generated/api";
89
+ import { internal } from "./_generated/internal";
90
90
 
91
91
  export const inviteUser = internalMutation.input({ email: v.string() }).mutation(async ({ ctx, args: { email } }) => {
92
92
  // ...authenticate the caller and persist the invite, then send the mail as a
@@ -33,13 +33,13 @@ which owns the alarm and durable storage.
33
33
 
34
34
  Available on `ctx.scheduler` in a **mutation or an action** — never a `query`,
35
35
  which is deterministic and re-runs. Target functions are passed by reference
36
- from the generated `api` / `internal` proxy (a `"file:fn"` path string also
36
+ from the generated `api` / `internal` objects (a `"file:fn"` path string also
37
37
  works):
38
38
 
39
39
  ```ts
40
40
  import { mutation, v } from "#lunora/_generated/server.js";
41
41
 
42
- import { internal } from "./_generated/api";
42
+ import { internal } from "./_generated/internal";
43
43
 
44
44
  export const startTrial = mutation.input({ userId: v.string() }).mutation(async ({ ctx, args: { userId } }) => {
45
45
  // run an internal action 14 days from now
@@ -84,7 +84,7 @@ project — both **yours** to edit. No extra DO binding is required.
84
84
  ```ts
85
85
  import { cronJobs } from "@lunora/server";
86
86
 
87
- import { internal } from "./_generated/api";
87
+ import { internal } from "./_generated/internal";
88
88
 
89
89
  const crons = cronJobs();
90
90
 
@@ -98,8 +98,9 @@ export default crons;
98
98
  ```
99
99
 
100
100
  - `name` must be a non-empty **string literal**, unique across the project.
101
- - `fnRef` must be a static two-segment access on the proxy
102
- (`internal.<file>.<fn>` or `api.<file>.<fn>`) so codegen can discover it.
101
+ - `fnRef` must be a static property access on the generated object
102
+ (`internal.<…path>.<fn>` or `api.<…path>.<fn>`, one segment per folder and
103
+ file, e.g. `internal.crons.jobs.run`) so codegen can discover it.
103
104
  Cron targets must be **internal** functions — a client can never invoke them.
104
105
  - All schedules are UTC and validated at definition time
105
106
  (`hourUTC: 25` throws immediately).