UNPKG

@lunora/cli

Version:

The Lunora CLI: init, dev, deploy, codegen, migrate, seed, doctor, insights, logs, registry, and the rest of the project commands

20 lines • 60.8 kB
import{mkdirSync as Me,writeFileSync as H,existsSync as S,readFileSync as A,rmSync as W,mkdtempSync as Er,readdirSync as Fe,realpathSync as Ar,statSync as Ue}from"node:fs";import{dirname as M,join as k,resolve as L,relative as ee,extname as Tr,sep as ae}from"node:path";import{PROJECT_CONFIG_FILENAMES as Rr,isTestPath as se,discoverMigrations as _r,readServiceBindings as le,runCodegen as Dr}from"@lunora/codegen";import{readLinkedProject as Be,resolveSchemaDirectory as N,startDevProcess as Cr,acceptsConnection as Pr,resolveTargetOrThrow as ie,detectFramework as Nr,DEFAULT_BUNDLE_META_PATH as Or,STRICT_ADVISORIES_ENV as jr,LAZY_FUNCTIONS_ENV as Ir,BUNDLE_META_PATH_ENV as Lr,BUILD_TARGET_ENV as xr,BUILD_ROOT_ENV as Mr,canonicalPath as Fr,COMPOSED_WORKER_ENTRY as Se,discoverContainerInfo as He,D1_PLACEHOLDER_ID as $e,discoverSchemaInfo as ue,writeLinkedProject as Ur,DEV_VARS_FILE as P,parseDevVariableEntries as Ge,secretSourcesFromBindings as Br,inferLunoraBindings as qe,requiredSecrets as Hr,mintableSecretKeysFor as Gr,generateSecretValue as qr,upsertDevVariableLine as Vr,writeDevVariablesFileAtomically as Wr,isPlaceholderValue as Kr,ensureGitignoreEntries as zr,resolveLazyFunctions as J,resolveDeployDriver as Y,MissingBuildOutputError as Jr,clearApiSpecMarker as Yr,createDiscoveryCache as Xr,planToolchainInvocation as Ve,probeCelldToolchain as Qr,runPostCodegenHook as Zr,readApiSpecMarker as et}from"@lunora/config";import{bindingsNeedingDatabase as rt,findWranglerFile as O,readWranglerJsonc as D,mergeWranglerEnvironment as X,HYPERDRIVE_PLACEHOLDER_ID as We,applyModify as Ke,warnCloudflareCliConfigOnce as tt,validateWranglerProject as nt,wranglerCodegenInputs as ot,reconcileWranglerBindings as at,reconcileWranglerCompatibilityDate as st,reconcileWranglerCrons as it,describePreservedCrons as ct}from"@lunora/config/cloudflare";import{Spinner as dt}from"@visulima/spinner";import{r as ge,a as lt,e as ut}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as gt}from"../packem_shared/api-spec-lYyq4vL6.mjs";import{e as ft,m as ht,g as mt,i as ze,d as vt,b as pt}from"../packem_shared/vectorize-metadata-BVSF8z2h.mjs";import{w as yt}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{d as wt}from"../packem_shared/command-B6vu47iR.mjs";import{r as fe}from"../packem_shared/wrangler-name-Dsk5K1f-.mjs";import{a as kt}from"../packem_shared/deploy-target-resolve-BTCW1Iv4.mjs";import{EXIT_CODE as y}from"../packem_shared/EXIT_CODE-DVjUgIaG.mjs";import{spawn as bt}from"node:child_process";import{randomUUID as Je,createHash as St}from"node:crypto";import{setTimeout as $t}from"node:timers/promises";import{toolchainExecArgs as F,detectPackageManager as j,execArgsFor as he}from"@lunora/config/cli";import{f as Et}from"../packem_shared/free-port-DjbFhaaT.mjs";import{containerBuildTag as At}from"@lunora/container";import{a as Tt,i as Rt}from"../packem_shared/docker-DpVxvYpL.mjs";import{defaultSpawner as x}from"../packem_shared/createRecordingSpawner-01ZngIwK.mjs";import{r as Ye}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{p as _t,H as Dt,a as Ct,r as Pt}from"../packem_shared/health-probe-Bw9JFfIy.mjs";import{runAdvisor as Nt,openShardAccess as Ee}from"@lunora/advisor";import{join as b,relative as U,dirname as Xe}from"@visulima/path";import{Project as Qe,SyntaxKind as p,Node as w}from"ts-morph";import{r as Ze,c as er}from"../packem_shared/cloudflare-credentials-BVmZnDZk.mjs";import{runMigrateDataCommand as Ot}from"../packem_shared/runMigrateGenerateCommand-Bd2W9t1k.mjs";import{c as jt}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{l as It}from"../packem_shared/wrangler-secrets-DlSlWvRH.mjs";const Lt=Object.freeze({edges:[],nodes:[],modules:[],unresolved:[],version:1}),xt=20,Ae=e=>`${e.from} -${e.kind}-> ${e.to}`,q=(e,r)=>{const t=new Set(e);return r.filter(n=>!t.has(n)).toSorted((n,o)=>n.localeCompare(o))},Mt=(e,r)=>{const t=e.modules.map(s=>s.name),n=r.modules.map(s=>s.name),o=e.edges.map(s=>Ae(s)),a=r.edges.map(s=>Ae(s));return{addedEdges:q(o,a),addedModules:q(t,n),removedEdges:q(a,o),removedModules:q(n,t)}},V=(e,r,t)=>{if(t.length===0)return[];const n=t.slice(0,xt).map(a=>`  ${e} ${a}`),o=t.length-n.length;return[`${r}:`,...n,...o>0?[`  … and ${o.toString()} more`]:[]]},Ft=e=>{const r=[...V("+","modules added",e.addedModules),...V("-","modules removed",e.removedModules),...V("+","edges added",e.addedEdges),...V("-","edges removed",e.removedEdges)];return r.length===0?void 0:`architecture changes since the last deploy:
${r.join(`
`)}`},Ut=(e,r)=>k(e,".lunora",r===void 0?"architecture.json":`architecture.${r}.json`),Bt=e=>{if(S(e))try{const r=JSON.parse(A(e,"utf8"));return r.version===1&&Array.isArray(r.modules)&&Array.isArray(r.edges)?r:void 0}catch{return}},Ht=e=>{const{cwd:r,environment:t,logger:n}=e,o=Ut(r,t),a=Bt(o),s=e.current??(a===void 0?void 0:Lt);if(s===void 0)return;const i=a===void 0?void 0:Ft(Mt(a,s));return i!==void 0&&n.info(i),()=>{try{Me(M(o),{recursive:!0}),H(o,`${JSON.stringify(s,void 0,2)}
`,"utf8")}catch(c){n.warn(`could not record the deployed architecture at ${o}: ${c instanceof Error?c.message:String(c)}`)}}},Gt=e=>{const{cwd:r,env:t,logger:n,mintedSecretsFile:o}=e;try{const a=Be(r),s=a?.workerName??fe(r),i=e.url??a?.workerUrl;n.success("deploy complete"),n.info(`  worker:  ${s??"(see wrangler output above)"}`),t!==void 0&&n.info(`  env:     ${t}`),i===void 0?n.info("  url:     run `lunora link --url <https://your-worker>` to record it"):n.info(`  url:     ${i}`),o!==void 0&&n.info(`  secrets: generated value(s) recorded in ${o}`),e.logsAvailable&&n.info("  logs:    lunora logs")}catch{}},qt=/\/index$/u,Vt=/[^\dA-Za-z]/gu,Wt=e=>e.replace(qt,"").split("/").map(r=>r.replaceAll(Vt,"_")),Kt=e=>Wt(e).join("_"),zt=18787,Te=3,rr=12e4,Jt=5e3,re=10,Yt=new Set([".js",".mjs",".mts",".ts",".tsx"]),Xt=/\(void 0\)|is not a function|before initialization|of undefined/u,Qt=e=>typeof e=="object"&&e!==null&&typeof e.functionPath=="string"&&typeof e.message=="string",Zt=e=>{const r=N(e),t=new Map;let n;try{n=Fe(k(e,r),{recursive:!0,encoding:"utf8"})}catch{return t}for(const o of n){const a=Tr(o);Yt.has(a)&&!o.split(ae).some(s=>s==="_generated"||s==="node_modules")&&t.set(Kt(o.slice(0,-a.length).split(ae).join("/")),k(r,o))}return t},en=(e,r)=>{const t=Zt(e),n=new Map;for(const{functionPath:o,message:a}of r){const s=o.lastIndexOf(":"),i=o.slice(0,s),c=`${i}\0${a}`,d=n.get(c)??{exports:[],message:a,namespace:i};d.exports.push(o.slice(s+1)),n.set(c,d)}return[...n.values()].map(({exports:o,message:a,namespace:s})=>{const i=Xt.test(a)?`
      hint: if this module is part of a circular import, an import it reads is still undefined while it evaluates`:"";return`  ${t.get(s)??s} (${o.join(", ")}): ${a}${i}`})};class _ extends Error{skipped;constructor(r,t=!1){super(r),this.skipped=t}}const rn=(e,r)=>{const t=O(e),n=t===void 0?void 0:D(t).parsed;if(n===void 0)return{hasContainers:!1,main:void 0};const{merged:o}=X(n,r);return{hasContainers:(o.containers??[]).length>0,main:o.main}},tn=({composedEntry:e,configPath:r,cwd:t,environment:n,toolchain:o})=>{if(o.devServer!=="workerd")return{skip:"this deploy target does not run on workerd"};const{hasContainers:a,main:s}=rn(t,n),i=e??s;if(typeof i!="string"||i.startsWith("virtual:")||!S(L(t,i)))return{skip:"the Worker entry is not a file on disk"};if(a)return{skip:"the project declares containers, which `wrangler dev` would build locally before the real container build"};const c=rt(t,process.env,n,r);return c.length===0?{main:i}:{skip:`the Hyperdrive binding ${c.join(", ")} has no local database for wrangler dev`}},nn=async(e,r,t)=>{const n=await fetch(`http://127.0.0.1:${String(e)}/_lunora/__smoke_load`,{signal:AbortSignal.timeout(Math.max(0,t-Date.now()))}).catch(g=>{throw g instanceof Error&&g.name==="TimeoutError"?new _(`the smoke Worker booted but did not finish evaluating the lazy modules within ${String(rr/1e3)}s — a module may be awaiting something that never settles. Pass --no-smoke-load to ship anyway.`):g});if(n.status>=500)throw new _(`the smoke Worker booted but failed while evaluating the lazy modules (HTTP ${String(n.status)}). Pass --no-smoke-load to ship anyway.`);const o=await n.text().catch(()=>"");let a;try{a=JSON.parse(o)}catch{a=void 0}const{checked:s,failures:i,run:c}=a??{};if(typeof s=="number"&&Array.isArray(i)&&i.every(g=>Qt(g)))return c===r?{checked:s,failures:i}:void 0;const d=n.headers.get("content-type")??"no content type",l=o.replaceAll(/\s+/gu," ").trim().slice(0,120);throw new _(`the smoke Worker answered with something other than the probe's result (HTTP ${String(n.status)}, ${d}${l===""?"":`: ${l}`}). A route that does not send /_lunora/* to the Worker first answers with the app's assets, so check run_worker_first. Pass --no-smoke-load to ship anyway.`)},ce=(e,r)=>{try{process.kill(-e,r)}catch{}},Re=e=>{try{return process.kill(-e,0),!0}catch{return!1}},on=e=>{const r=()=>{ce(e,"SIGKILL")},t=o=>{r(),process.kill(process.pid,o)},n=()=>{process.removeListener("exit",r),process.removeListener("SIGINT",t),process.removeListener("SIGTERM",t)};return process.once("exit",r),process.once("SIGINT",t),process.once("SIGTERM",t),n},te=async e=>{if(e===void 0)return;e.dispose();const{pid:r}=e;ce(r,"SIGTERM");const t=Date.now()+Jt;for(;Re(r)&&Date.now()<t;)await $t(50);Re(r)&&ce(r,"SIGKILL")},an=e=>Cr(e).catch(async r=>{if(!await Pr(e.port))throw r}),sn=(e,{checked:r,failures:t},n)=>{if(t.length===0){n.success(`${String(r)} lazy function(s) evaluate cleanly`);return}const o=en(e,t),a=o.length>re?[`  …and ${String(o.length-re)} more module(s)`]:[];throw new _([`${String(t.length)} of ${String(r)} lazy function(s) fail to load:`,...o.slice(0,re),...a,"Fix the module, or pass --no-smoke-load to ship anyway."].join(`
`))},cn=(e,r,t)=>{if(e instanceof _&&!e.skipped)return t.error(e.message),e.message;if(e instanceof _){t.warn(`smoke-load skipped: ${e.message}`);return}const n=r.slice(-5).join(`
`),o=`the smoke Worker did not start (${e instanceof Error?e.message:String(e)})${n===""?"":`
${n}`}. Either the entry fails when it loads, or local wrangler cannot run the project (a remote-only binding or a missing assets directory). Fix whichever it is, or pass --no-smoke-load to ship anyway.`;return t.error(o),o},dn=e=>{try{return Me(k(e,".lunora"),{recursive:!0}),Er(k(e,".lunora","smoke-"))}catch(r){throw new _(`could not create a directory for the check (${r instanceof Error?r.message:String(r)})`,!0)}},ln=async e=>{const{configPath:r,cwd:t,directory:n,environment:o,functionsFile:a,main:s,preferred:i,toolchain:c}=e;try{const d=k(n,"entry.ts"),l=Je();H(d,`export * from ${JSON.stringify(L(t,s))};
import { loadAllFunctions } from ${JSON.stringify(a)};

const runId = ${JSON.stringify(l)};

export default {
    async fetch() {
        return Response.json({ ...(await loadAllFunctions()), run: runId });
    },
};
`);const g=await Et(i),{args:u,command:h}=F(j(t),c.dev({configPath:r===void 0?void 0:ee(t,r),environment:o,extraArgs:[ee(t,d),"--local","--local-protocol","http","--ip","127.0.0.1","--port",String(g),"--persist-to",ee(t,k(n,"state"))]}));return{args:u,command:h,port:g,runId:l}}catch(d){throw new _(`could not prepare the check (${d instanceof Error?d.message:String(d)})`,!0)}},un=async e=>{const{configPath:r,cwd:t,environment:n,launcher:o,logger:a,toolchain:s}=e,i=k(t,N(t),"_generated","functions.ts");if(!S(i)||!A(i,"utf8").includes("export const loadAllFunctions"))return;const c=tn(e);if("skip"in c){a.warn(`smoke-load skipped: ${c.skip}, so lazy modules are not evaluated before deploy`);return}const{main:d}=c,l=[];let g,u;const h=Date.now()+rr,f=process.platform!=="win32",v=(m,E,C)=>{const $=bt(m,[...E],{cwd:C.cwd,detached:f,shell:C.shell,stdio:["ignore","pipe","pipe"]});return f&&$.pid!==void 0&&(u={dispose:on($.pid),pid:$.pid}),$};try{g=dn(t),a.info("smoke-loading lazy function modules in workerd");let m=zt;for(let E=0;E<Te;E+=1){const{args:C,command:$,port:I,runId:T}=await ln({configPath:r,cwd:t,directory:g,environment:n,functionsFile:i,main:d,preferred:m,toolchain:s});m=I+1;const be=await an({args:C,command:$,cwd:t,spawn:o??v,label:"wrangler dev (smoke-load)",notFound:"`wrangler` was not found",onLine:G=>{l.push(G)},port:I,readyTimeoutMs:Math.max(0,h-Date.now()),shell:process.platform==="win32"});if(be===void 0){await te(u),u=void 0;continue}try{const G=await nn(I,T,h);if(G!==void 0){sn(t,G,a);return}}finally{await be.stop(),await te(u),u=void 0}}throw new _(`the smoke port was answered by other runs on all ${String(Te)} attempts`,!0)}catch(m){return cn(m,l,a)}finally{if(await te(u),g!==void 0)try{W(g,{force:!0,recursive:!0})}catch{}}},gn=(e,r)=>r===void 0?e:L(e,r),fn=async e=>{if(e.targets.length===0)return{builtTags:[],code:0};if(!(e.railpackAvailable??Tt)()){const n="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(n),{builtTags:[],code:1,error:n}}const r=e.spawner??x,t=[];for(const n of e.targets){const o=At(n.exportName),a={args:["build",n.buildDir,"--name",o],command:"railpack",cwd:e.cwd},s=he(j(e.cwd),"wrangler",["containers","push",o]),i={args:s.args,command:s.command,cwd:e.cwd};e.logger.info(`railpack: building "${n.exportName}" → ${o} from ${n.buildDir}`);const c=await r(a);if(c.code!==0){const l=`railpack build failed for container "${n.exportName}" (${n.buildDir})`;return e.logger.error(l),{builtTags:t,code:c.code,error:l}}e.logger.info(`railpack: pushing ${o} to the Cloudflare Registry`);const d=await r(i);if(d.code!==0){const l=`wrangler containers push failed for "${n.exportName}" (${o})`;return e.logger.error(l),{builtTags:t,code:d.code,error:l}}t.push(o)}return{builtTags:t,code:0}},tr=e=>{const t=[O(e),k(e,"package.json"),k(e,"wrangler.dev.jsonc")].filter(n=>n!==void 0&&S(n)).map(n=>[n,A(n,"utf8")]);return()=>{for(const[n,o]of t)A(n,"utf8")!==o&&H(n,o,"utf8")}},hn=(e,r=Je())=>L(e,".lunora",`vite-bundle-meta-${r}.json`),nr="LUNORA_CLIENT_BUILD",mn="virtual:lunora/worker",de=(e,r)=>["ts","mts","cts","js","mjs","cjs"].some(t=>S(k(e,`${r}.config.${t}`))),or=e=>de(e,"rsbuild")?"rsbuild":de(e,"vite")?"vite":void 0,vn=e=>de(e,"vite")?"vite":or(e),pn=e=>{try{const{scripts:r}=JSON.parse(A(k(e,"package.json"),"utf8"));return typeof r?.build=="string"&&r.build!==""}catch{return!1}},Q=(e,r)=>{if(process.env[nr]==="1")return;const t=O(e),n=t===void 0?void 0:D(t).parsed,o=n?.main===mn,a=(o?vn(e):or(e))??(pn(e)?"script":void 0);if(a===void 0)return;const s=r===void 0?void 0:n?.env?.[r]?.assets?.directory,i=n?.assets?.directory??s;return o||Nr(e).class!=="C"||i!==void 0?a:void 0},yn=async(e,r,t)=>{const n=t.spawner??x,o=j(e),a=r==="script"?{args:["run","build"],command:o}:he(o,r,["build"]);t.logger.info(`running ${r} build before bundling the Worker`);const s=tr(e),i=t.bundleMetaPath??hn(e);W(k(e,Or),{force:!0});try{const c=await n({args:a.args,command:a.command,cwd:e,env:{[Mr]:Fr(e),[xr]:t.target,[Lr]:i,...t.lazyFunctions?{[Ir]:"1"}:{},...t.environment===void 0?{}:{CLOUDFLARE_ENV:t.environment},...t.strictAdvisories===!1?{[jr]:"0"}:{},[nr]:"1"},stdoutToStderr:t.outputJson});return c.code===0?void 0:`${r} build failed with exit code ${String(c.code)}`}finally{s(),t.bundleMetaPath===void 0&&W(i,{force:!0})}},Z=(e,r,t)=>r!==!1&&Q(e,t)!==void 0,wn=(e,r,t)=>Z(e,r,t)&&Q(e,t)!=="script",me=e=>{const r=e.frameworkBuild===!1?void 0:Q(e.cwd,e.environment);if(r===void 0||r==="script")return;if(e.apiSpec!==void 0)return`--api-spec is read from the ${r} plugin config when the client build runs; set it there, or pass --no-framework-build`;if(e.target!==void 0)try{ie(e.cwd,e.target)}catch(n){return n instanceof Error?n.message:String(n)}let t;try{t=ie(e.cwd)}catch(n){return`the project's configured target cannot be used, and the ${r} plugin reads it: ${n instanceof Error?n.message:String(n)}`}if(e.target!==void 0&&e.target!==t)return`this run targets "${e.target}", but the project's target is "${t}", which the ${r} plugin reads; set it in the project config, or pass --no-framework-build`},ar=async e=>{const r=e.frameworkBuild===!1?void 0:Q(e.cwd,e.environment);if(r===void 0)return;let t;try{t=e.target??ie(e.cwd)}catch(n){return n instanceof Error?n.message:String(n)}return yn(e.cwd,r,{bundleMetaPath:e.bundleMetaPath,environment:e.environment,strictAdvisories:e.strictAdvisories,lazyFunctions:e.lazyFunctions,logger:e.logger,outputJson:e.outputJson,spawner:e.spawner,target:t})},_e=e=>Array.isArray(e)?e.filter(r=>r!=null):void 0,ve=(e,r)=>{const t=O(e);if(!t)return;const{parsed:n}=D(t);if(n===void 0)return;const{error:o,merged:a}=X(n,r),s=o===void 0?a:n,{containers:i,d1_databases:c,vars:d}=s;return{containers:_e(i),d1_databases:_e(c),vars:typeof d=="object"&&d!==null&&!Array.isArray(d)?d:void 0}},kn=/^127(?:\.\d{1,3}){3}$/,bn=e=>{try{const{hostname:r}=new URL(e);return r==="localhost"||kn.test(r)||r==="::1"||r==="[::1]"}catch{return!1}},Sn=e=>e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.includes("Dockerfile"),$n=(e,r,t,n="deploy",o)=>{const a=(ve(e,o)?.containers??[]).filter(i=>typeof i?.image=="string"&&Sn(i.image));if(a.length===0||t())return;const s=`${n} 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(s),s},pe=e=>S(b(e,Se))?Se:void 0,En=(e,r,t="deploy",n)=>{for(const o of He(e,"lunora",n).containers){const a=o.schedulingPolicy===void 0?o.image:void 0,i=[...a?.kind==="dockerfile"?[{field:"image",path:a.dockerfilePath}]:[],...Object.entries(o.schedulingPolicy==="durable_object"?o.images??{}:{}).flatMap(([c,d])=>d.kind==="dockerfile"?[{field:`images["${c}"]`,path:d.dockerfilePath}]:[])].find(c=>!S(b(e,c.path)));if(i!==void 0){const c=`${t} blocked: container "${o.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(c),c}if(a?.kind==="build"&&!S(b(e,a.buildDir))){const c=`${t} blocked: container "${o.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(c),c}}},An=(e,r)=>r==="celld"?typeof e=="string"&&e!==$e&&ft(e):r==="cloudflare"&&e===$e,Tn=(e,r,t)=>(ve(e,t)?.d1_databases??[]).find(n=>An(n.database_id,r)),Rn=e=>{if(!e.migrate||e.dryRun||e.preview)return;if(e.migrateUrl===void 0){const t="--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(t),t}if(e.migrateYes!==!0){const t="--migrate runs production data migrations after deploy. Re-run with --migrate-yes to confirm.";return e.logger.error(t),t}const r=e.migrateToken??process.env.LUNORA_ADMIN_TOKEN;if(r===void 0||r===""){const t="admin token required for --migrate — pass --migrate-token or set LUNORA_ADMIN_TOKEN";return e.logger.error(t),t}},_n=(e,r,t,n,o)=>{const a=Tn(e,n,o);if(a===void 0)return;const s=`${t} blocked: the "${a.binding??"<unnamed>"}" D1 binding has a placeholder database_id ("${a.database_id??""}")`,i=n==="celld"?`${s}, which celld would use as the database's identity. Set database_id to the database celld should use, then ${t} again.`:`${s}. Run \`lunora doctor --fix\` to create the database and write its id into wrangler.jsonc, or run \`wrangler d1 create <name>\` and paste the id in yourself.`;return r.error(i),i},Dn=(e,r,t="deploy",n)=>{const o=ve(e,n)?.vars;if(!o)return;const a=Object.entries(o).filter(([,i])=>typeof i=="string"&&bn(i)).map(([i])=>i).toSorted((i,c)=>i.localeCompare(c));if(a.length===0)return;const s=`${t} 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(s),s},Cn=["vite.config.ts","vite.config.mts","vite.config.cts","vite.config.js","vite.config.mjs","vite.config.cjs",...Rr],sr=/\.(?:[cm]?[jt]s|tsx|jsx)$/u,ir=/\.(?:test|spec)\.[cm]?[jt]sx?$/u,cr="allowUnauthenticatedShardAccess",Pn=/[\\/]/u,dr=new Set(["_generated","build","dist","node_modules"]),lr=(e,r)=>{const t=U(e,r).split(Pn);return sr.test(r)&&!ir.test(r)&&!se(t.join("/"))&&t.every(n=>n===".."||!n.startsWith(".")&&!dr.has(n))},De=(e,r,t)=>{const{parsed:n}=D(r);if(n===void 0)return[];const{error:o,merged:a}=X(n,t),{main:s}=o===void 0?a:n,i=typeof s=="string"?b(Xe(r),s):void 0;return i!==void 0&&S(i)&&lr(e,i)?[i]:[]},ye=e=>e===void 0?!1:e.getKind()===p.FalseKeyword?!0:w.isParenthesizedExpression(e)||w.isAsExpression(e)||w.isSatisfiesExpression(e)||w.isTypeAssertion(e)||w.isNonNullExpression(e)?ye(e.getExpression()):!1,Nn=e=>{try{return Ue(e).isFile()}catch{return!1}},On=new Set(["ELOOP","ENOENT","ENOTDIR"]),K=(e,r,t)=>{const n=r instanceof Error&&"code"in r&&typeof r.code=="string"?r.code:"";On.has(n)||t.push(e)},jn=(e,r)=>{try{return Ue(e)}catch(t){K(e,t,r);return}},ur=(e,r)=>{try{return A(e,"utf8")}catch(t){K(e,t,r);return}},gr=(e,r,t,n=new Set)=>{let o;try{o=Ar(r)}catch(s){return K(r,s,t),[]}if(n.has(o))return[];n.add(o);let a;try{a=Fe(r)}catch(s){return K(r,s,t),[]}return a.flatMap(s=>{const i=b(r,s),c=jn(i,t);if(c===void 0)return[];const d=U(e,i).split(ae).join("/");return c.isDirectory()?dr.has(s)||s.startsWith(".")||se(`${d}/`)?[]:gr(e,i,t,n):c.isFile()&&sr.test(s)&&!ir.test(s)&&!se(d)?[i]:[]})},In=e=>{const r=w.isComputedPropertyName(e)?e.getExpression():e;return w.isStringLiteral(r)||w.isNoSubstitutionTemplateLiteral(r)?r.getLiteralValue():e.getText()},ne=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],Ln=/\.(?:[cm]?js|jsx)$/u,xn=(e,r)=>{if(!r.startsWith("."))return;const t=L(Xe(e),r),n=t.replace(Ln,"");return[t,...ne.map(a=>`${t}${a}`),...ne.map(a=>b(t,`index${a}`)),...ne.map(a=>`${n}${a}`)].find(a=>Nn(a))},Mn=e=>{if(e.getExpression().getText()!=="require")return;const[r]=e.getArguments();return r!==void 0&&(w.isStringLiteral(r)||w.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():void 0},Fn=e=>{const r=e.getModuleReference();if(!w.isExternalModuleReference(r))return;const t=r.getExpression();return w.isStringLiteral(t)?t.getLiteralValue():void 0},Un=(e,r,t,n)=>{const o=new Set(e),a=[...e],s=[];for(let i=0;i<a.length;i+=1){const c=a[i]??"",d=ur(c,n);if(d===void 0)continue;const l=r.createSourceFile(U(t,c),d,{overwrite:!0}),g=[...l.getImportDeclarations().map(u=>u.getModuleSpecifierValue()),...l.getExportDeclarations().map(u=>u.getModuleSpecifierValue()),...l.getDescendantsOfKind(p.ImportEqualsDeclaration).map(u=>Fn(u)),...l.getDescendantsOfKind(p.CallExpression).map(u=>Mn(u))].filter(u=>u!==void 0);for(const u of g){const h=xn(c,u);h!==void 0&&lr(t,h)&&!o.has(h)&&(o.add(h),s.push(h),a.push(h))}}return s},Bn=e=>{const r=e.getArgumentExpression();return r!==void 0&&(w.isStringLiteral(r)||w.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():void 0},Hn=e=>w.isPropertyAccessExpression(e)?e.getName():w.isElementAccessExpression(e)?Bn(e):void 0,Gn=new Set([p.AmpersandAmpersandEqualsToken,p.AmpersandEqualsToken,p.AsteriskAsteriskEqualsToken,p.AsteriskEqualsToken,p.BarBarEqualsToken,p.BarEqualsToken,p.CaretEqualsToken,p.EqualsToken,p.GreaterThanGreaterThanEqualsToken,p.GreaterThanGreaterThanGreaterThanEqualsToken,p.LessThanLessThanEqualsToken,p.MinusEqualsToken,p.PercentEqualsToken,p.PlusEqualsToken,p.QuestionQuestionEqualsToken,p.SlashEqualsToken]),qn=e=>{const r=e.getOperatorToken().getKind();return!Gn.has(r)||Hn(e.getLeft())!==cr?!1:r!==p.EqualsToken||!ye(e.getRight())},Vn=(e,r,t)=>{const n=[],o=[...new Set([N(e),"src"])].filter(g=>S(b(e,g))),a=O(e),s=[...Cn.map(g=>b(e,g)).filter(g=>S(g)),...a===void 0?[]:De(e,a,r),...t.flatMap(g=>De(e,g,r))],i=new Qe({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}),c=o.flatMap(g=>gr(b(e,g),b(e,g),n));return{sites:[...new Set([...c,...s,...Un([...s,...c],i,e,n)])].flatMap(g=>{const u=ur(g,n);if(u===void 0)return[];const h=i.createSourceFile(U(e,g),u,{overwrite:!0}),f=[...h.getDescendantsOfKind(p.PropertyAssignment),...h.getDescendantsOfKind(p.ShorthandPropertyAssignment),...h.getDescendantsOfKind(p.GetAccessor),...h.getDescendantsOfKind(p.MethodDeclaration)].filter(m=>{const E=w.isPropertyAssignment(m)&&ye(m.getInitializer());return In(m.getNameNode())===cr&&!E}).map(m=>m.getStartLineNumber()),v=h.getDescendantsOfKind(p.BinaryExpression).filter(m=>qn(m)).map(m=>m.getStartLineNumber());return[...f,...v].map(m=>({file:U(e,g),line:m}))}),unreadable:n}},Wn=(e,r,t,n,o,a)=>{if(t!=="deploy")return;const{sites:s,unreadable:i}=Vn(e,o,a),c=Nt({openShardAccess:s,schema:{tables:[]}},{lints:[Ee]});if(c.length===0&&i.length===0)return;const d=[];if(c.length>0){const g=c.map(u=>`${String(u.metadata.file)}:${String(u.metadata.line)}`).join(", ");d.push(`${g} enable the open-shard option (any value but a literal false), so any caller may target any shard.`)}if(i.length>0&&d.push(`could not read ${i.join(", ")}, so the open-shard option cannot be ruled out there.`),n){r.warn(`deploying past the open-shard gate (--allow-open-shards): ${d.join(" ")}`);return}const l=`deploy blocked (open_shard_access): ${d.join(" ")} ${Ee.remediation}`;return r.error(l),l},Kn=(e,r,t,n)=>{const o=Wn(e,r.logger,t,r.allowOpenShards===!0,r.env,n);return o===void 0?void 0:{code:y.USAGE,error:o}},zn=(e,r,t,n)=>{const o=_n(e,r.logger,t,n,r.env);if(o!==void 0)return{code:y.USAGE,error:o};const a=Dn(e,r.logger,t,r.env);if(a!==void 0)return{code:y.USAGE,error:a};const s=En(e,r.logger,t,r.discoveryCache);if(s!==void 0)return{code:y.USAGE,error:s};const i=$n(e,r.logger,r.dockerAvailable??Rt,t,r.env);return i===void 0?void 0:{code:y.MISSING_DEPENDENCY,error:i}},Ce=32,fr=15e3,Jn=5432,Yn=3306,Xn=/[^a-z0-9-]/gu,Qn=/[^A-Za-z0-9]/gu,Zn=/-$/u,B=e=>`LUNORA_${e.replaceAll(Qn,"_").toUpperCase()}_URL`,eo=e=>{const r=new Map;for(const t of e){const n=B(t),o=r.get(n);if(o!==void 0)return{bindings:[o,t],variable:n};r.set(n,t)}},Pe=7,ro=(e,r)=>{const t=`${e}-${r}`.toLowerCase(),n=t.replaceAll(Xn,"-");if(n===t&&n.length<=Ce)return n;const o=St("sha256").update(t).digest("hex").slice(0,Pe-1);return`${n.slice(0,Ce-Pe).replace(Zn,"")}-${o}`},Ne=e=>e==="postgresql"?"postgres":e==="mariadb"?"mysql":e,to=e=>e==="mysql"?Yn:Jn,no=e=>{try{const r=new URL(e),t=r.protocol.slice(0,-1),n=decodeURIComponent(r.pathname.slice(1));return!["mariadb","mysql","postgres","postgresql"].includes(t)||r.hostname===""||n===""?void 0:{database:n,host:r.hostname,password:decodeURIComponent(r.password),port:r.port===""?to(Ne(t)):Number(r.port),scheme:Ne(t),user:decodeURIComponent(r.username)}}catch{return}},oo=(e,r)=>{const t=typeof r?.password=="string"?r.password:"",n=t===""?[]:[t,JSON.stringify(t).slice(1,-1),encodeURIComponent(t)];let o=e;for(const a of n)o=o.replaceAll(a,"<redacted>");return o.split(" ").map(a=>a.includes("://")?"<url>":a).join(" ")},hr=e=>(Array.isArray(e)?e:[]).flatMap((r,t)=>{const{binding:n,id:o}=typeof r=="object"&&r!==null?r:{};return typeof n=="string"&&o===We?[{binding:n,index:t}]:[]}),z=e=>{let r="";try{const{errors:t}=JSON.parse(e.text);r=(t??[]).flatMap(n=>typeof n.message=="string"?[n.message]:[]).slice(0,2).join("; ")}catch{}return r===""?`HTTP ${String(e.status)}`:`HTTP ${String(e.status)}: ${r}`},ao=e=>typeof e=="string"||typeof e=="number"?e.toString():void 0,so=["scheme","host","port","database","user"],io=e=>e==="postgresql"?"postgres":e,Oe=(e,r)=>{const t=ao(r);return e==="scheme"?io(t):t},je=50,co=async(e,r)=>{for(let t=1;t<=je;t+=1){const n=await e(t===1?"/hyperdrive/configs":`/hyperdrive/configs?page=${String(t)}`);if(!n.ok)throw new Error(`listing Hyperdrive configs failed (${z(n)})`);if(!Array.isArray(n.body.result))throw new TypeError("the listing of Hyperdrive configs had no result list");const o=n.body.result.find(s=>s.name===r),a=typeof n.body.result_info=="object"&&n.body.result_info!==null?n.body.result_info:{};if(o!==void 0||typeof a.total_pages!="number"||t>=a.total_pages)return o}throw new Error(`the listing of Hyperdrive configs has more than ${String(je)} pages, so "${r}" can't be shown to be absent`)},lo=async(e,r,t,n)=>{const o=n?{caching:{disabled:!0}}:{},a=await co(e,r);if(typeof a?.id=="string"){const c=so.filter(l=>Oe(l,a.origin?.[l])!==Oe(l,t[l]));if(c.length>0)throw new Error(`a Hyperdrive config named "${r}" already exists for a different origin, or one that can't be confirmed (${c.join(", ")}). Delete it, or rename the Worker, so the binding does not reach the wrong database.`);const d=await e(`/hyperdrive/configs/${encodeURIComponent(a.id)}`,{body:JSON.stringify({origin:t,...o}),method:"PATCH"});if(!d.ok)throw new Error(`updating its credentials failed (${z(d)})`);return{id:a.id,reused:!0}}const s=await e("/hyperdrive/configs",{body:JSON.stringify({name:r,origin:t,...o}),method:"POST"});if(!s.ok)throw new Error(`creating it failed (${z(s)})`);const{id:i}=typeof s.body.result=="object"&&s.body.result!==null?s.body.result:{};if(typeof i!="string")throw new TypeError("the response carried no id");return{id:i,reused:!1}},uo=(e,r,t,n)=>r===void 0&&n?`${B(e)} is set but is not a usable connection string for the "${e}" Hyperdrive binding: it needs a postgres://, postgresql:// or mysql:// scheme, a host and a database name, with any special characters percent-encoded.`:r===void 0?`the "${e}" Hyperdrive binding has no config yet. Set ${B(e)} to its postgres:// or mysql:// connection string and Lunora creates the config, or run \`wrangler hyperdrive create\` and put its id in wrangler.jsonc.`:t?void 0:`creating the "${e}" Hyperdrive config needs CLOUDFLARE_API_TOKEN (Hyperdrive: Edit) and CLOUDFLARE_ACCOUNT_ID, or run \`wrangler hyperdrive create\` and put its id in wrangler.jsonc.`,go=async(e,r)=>{const t=ro(e.workerName,e.binding),{id:n,reused:o}=await lo(async(a,s)=>er({accountId:e.accountId,apiToken:e.token,...e.fetch===void 0?{}:{fetch:e.fetch},init:{...s,signal:AbortSignal.timeout(fr)},path:a}),t,e.origin,e.disableCaching);return e.logger.success(`${o?"reusing":"created"} Hyperdrive config "${t}" for ${e.binding} → ${e.wranglerPath}`),{id:n,text:Ke(r,[...e.path,e.index,"id"],n)}},fo=e=>e===void 0||e===""?void 0:e,mr=e=>{const r=k(M(e),".wrangler","deploy","config.json");try{const{configPath:t}=JSON.parse(A(r,"utf8"));return typeof t=="string"?L(M(r),t):void 0}catch{return}},ho=(e,r,t,n,o)=>{const a=mr(e);if(a===void 0||a===e)return;if(n.built!==n.deployed){o.warn(`the build output ${a} was made for ${n.built===void 0?"the default environment":`"${n.built}"`}, not ${n.deployed===void 0?"the default environment":`"${n.deployed}"`}, so the "${r}" Hyperdrive id was not written there. Build with CLOUDFLARE_ENV set to the environment you deploy, then deploy again.`);return}let s;try{s=D(a)}catch{return}const i=hr(s.parsed?.hyperdrive).find(c=>c.binding===r);i!==void 0&&H(a,Ke(s.text,["hyperdrive",i.index,"id"],t),"utf8")},mo=(e,r)=>{const t=typeof e.name=="string"&&e.name!==""?e.name:"lunora";if(r===void 0)return t;const n=e.env?.[r]?.name;return typeof n=="string"&&n!==""?n:`${t}-${r}`},we=(e,r)=>{const t=O(e),n=t===void 0?void 0:D(t).parsed;if(t===void 0||n===void 0)return;const o=r===void 0?void 0:n.env?.[r],a=hr(r===void 0?n.hyperdrive:o?.hyperdrive);return a.length===0?void 0:{accountId:o?.account_id??n.account_id,entries:a,path:r===void 0?["hyperdrive"]:["env",r,"hyperdrive"],workerName:mo(n,r),wranglerPath:t}},vo=(e,r,t)=>{const n=eo(e.map(({binding:o})=>o));if(n!==void 0){const o=`deploy blocked: the Hyperdrive bindings ${n.bindings.map(a=>`"${a}"`).join(" and ")} both read ${n.variable} and would share one config. Rename one so their names differ in letters or digits, not only in punctuation.`;return t.logger.error(o),o}for(const{binding:o,origin:a,supplied:s}of e){const i=uo(o,a,r,s);if(i!==void 0&&t.dryRun===!0)t.logger.warn(`dry run: ${i} A real deploy stops here.`);else if(i!==void 0){const c=`deploy blocked: ${i}`;return t.logger.error(c),c}}},po=async(e,r,t,n)=>{let o;try{o=await e(`/hyperdrive/configs/${encodeURIComponent(t)}`)}catch(s){n.warn(`could not check whether the "${r}" Hyperdrive config has query caching off (${s instanceof Error?s.message:String(s)}).`);return}if(!o.ok){n.warn(`could not check whether the "${r}" Hyperdrive config has query caching off (${z(o)}).`);return}const{caching:a}=typeof o.body.result=="object"&&o.body.result!==null?o.body.result:{};a?.disabled!==!0&&n.warn(`the "${r}" Hyperdrive config has query caching on, so .global() tables would read rows up to 75 s old. Run \`wrangler hyperdrive update ${t} --caching-disabled\`.`)},yo=async(e,r)=>{const t=O(e.cwd),n=t===void 0?void 0:D(t).parsed,o=e.wranglerEnvironment===void 0?n:n?.env?.[e.wranglerEnvironment],{accountId:a,token:s}=Ze(r,o?.account_id??n?.account_id);if(a===void 0||s===void 0)return;const i=async(c,d)=>er({accountId:a,apiToken:s,...e.fetch===void 0?{}:{fetch:e.fetch},init:{...d,signal:AbortSignal.timeout(fr)},path:c});for(const c of Array.isArray(o?.hyperdrive)?o.hyperdrive:[]){const{binding:d,id:l}=typeof c=="object"&&c!==null?c:{};typeof d=="string"&&typeof l=="string"&&l!==We&&await po(i,d,l,e.logger)}},wo=async e=>{const r=e.environment??process.env;e.disableCaching===!0&&e.checkOnly!==!0&&e.dryRun!==!0&&await yo(e,r);const t=we(e.cwd,e.wranglerEnvironment);if(t===void 0)return;const{entries:n,path:o,wranglerPath:a}=t,{accountId:s,token:i}=Ze(r,t.accountId),c=n.map(({binding:l})=>{const g=r[B(l)]??"";return{binding:l,origin:no(g),supplied:g!==""}}),d=vo(c,i!==void 0&&s!==void 0,e);if(d!==void 0)return d;if(!(e.dryRun===!0||e.checkOnly===!0))for(const[l,{binding:g,index:u}]of n.entries()){const h=c[l]?.origin;if(!(h===void 0||i===void 0||s===void 0))try{const{id:f,text:v}=await go({accountId:s,binding:g,disableCaching:e.disableCaching===!0,fetch:e.fetch,index:u,logger:e.logger,origin:h,path:o,token:i,workerName:t.workerName,wranglerPath:a},A(a,"utf8"));H(a,v,"utf8"),ho(a,g,f,{built:fo(r.CLOUDFLARE_ENV),deployed:e.wranglerEnvironment},e.logger)}catch(f){const v=f instanceof Error?f.message:String(f),m=`deploy blocked: the "${g}" Hyperdrive config could not be set up: ${oo(v,c[l]?.origin)}`;return e.logger.error(m),m}}},ko=(e,r)=>{const t=we(e,r.env)?.entries[0]?.binding;if(t===void 0)return;const n=`prepare blocked: the "${t}" Hyperdrive binding still has its placeholder id. Run \`lunora deploy\` with ${B(t)} set to create the config, or put the id from \`wrangler hyperdrive create\` in wrangler.jsonc.`;return r.logger.error(n),n},bo=(e,r)=>{const t=we(e,r.env)?.entries[0]?.binding;if(t===void 0)return;const n=`deploy blocked: the "${t}" Hyperdrive binding has no config, and a --temporary deploy cannot create one: it would be made in your account while the Worker goes to a temporary one, which a temporary account has no database for. Deploy without --temporary.`;return r.logger.error(n),n},vr=async(e,r,t,n,o="create")=>{if(n!=="cloudflare")return;if(t==="prepare")return ko(e,r);if(r.temporary===!0)return bo(e,r);const a=r.clientBuildEnvironment===void 0?void 0:{...process.env,CLOUDFLARE_ENV:r.clientBuildEnvironment},s=ue(e,N(e),r.discoveryCache);return s.error!==void 0&&r.logger.warn(`could not read the schema (${s.error}), so Hyperdrive configs are set up with query caching off.`),wo({checkOnly:o==="check",cwd:e,disableCaching:s.error!==void 0||s.info?.hasHyperdriveGlobalTable===!0,dryRun:r.dryRun,environment:a,logger:r.logger,wranglerEnvironment:r.env})},So=/https?:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/u,$o=/https:\/\/[^\s"'<>]+/u,Eo=e=>{if(e===void 0)return;const r=So.exec(e);return r?r[0]:$o.exec(e)?.[0]},Ie=e=>e===void 0?"":` (--env ${e})`,Ao=({cwd:e,env:r,logger:t,now:n,url:o})=>{if(o!==void 0)try{const a=Be(e);if(a!==void 0){if(a.workerUrl===o&&a.env===r)return;t.warn(`link: .lunora/project.json records ${a.workerUrl??"(no url)"}${Ie(a.env)}, but this deploy published ${o}${Ie(r)}. Keeping the recorded value — run \`lunora link --url ${o}${r===void 0?"":` --env ${r}`}\` to update it.`);return}const s=(n??(()=>new Date().toISOString()))();Ur(e,{env:r,linkedAt:s,workerName:fe(e),workerUrl:o}),t.success(`link: recorded ${o} in .lunora/project.json (run \`lunora link\` to change)`)}catch{}},To=async(e,r)=>{const t=new Qe({skipAddingFilesFromTsConfig:!0}),n=b(r,"lunora");let o;try{o=_r(t,n)}catch(a){const s=a instanceof Error?a.message:String(a);return e.logger.warn(`--migrate: could not discover migrations (${s}); skipping`),0}if(o.length===0)return e.logger.info("--migrate: no data migrations declared in lunora/"),0;e.logger.info(`--migrate: running ${String(o.length)} migration(s) against deployed worker`);for(const a of o){e.logger.info(`--migrate: up "${a.id}" (table "${a.table}")`);const s={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},i=await Ot(s);if(i.code!==0)return e.logger.error(`--migrate: migration "${a.id}" failed — see output above`),i.code;e.logger.success(`--migrate: "${a.id}" applied`)}return 0},Ro=async(e,r)=>{const{info:t}=ue(r,"lunora",e.discoveryCache),n=t?.vectorMetadata??[];if(n.length===0)return;const o=[];for(const i of n){const c=ht(i.kind);if(c===void 0){e.logger.warn(`vector index "${i.index}" declares metadata "${i.property}", whose column type cannot be filtered on in Vectorize — it is stored with each vector but no filter will match it.`);continue}o.push({index:i.index,property:i.property,type:c})}if(o.length===0)return;const s=(await mt({cwd:r,entries:o,exec:he(j(r),"wrangler",[]),logger:e.logger,spawner:e.spawner??x})).filter(i=>i.status!=="failed").length;s>0&&e.logger.success(`vectorize metadata indexes ready: ${String(s)}/${String(o.length)}`)},Le=5,_o=2e3,Do=async(e,r,t)=>{if(e.healthCheck!==!0)return;const n=t??Ye({cwd:r,env:e.env});if(n===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 o=await _t({attempts:Le,baseUrl:n,delayMs:_o,fetchImpl:e.healthFetch,paths:[Dt,Ct],sleep:e.healthSleep});return o.error===void 0?(e.logger.success(`health check ok (${o.url})`),{ok:!0,url:o.url}):(e.logger.error(`--health-check: the deploy succeeded, but the new version did not answer after ${String(Le)} attempt(s) — ${o.error}`),{error:o.error,ok:!1,url:o.url})},Co=async(e,r,t,n,o,a)=>{await Ro(e,r);const s=e.migrate?await To(e,r):0;return s===0&&o?.(),{code:s,descriptor:t,mintedSecretsFile:a,validation:n}},Po=async({cwd:e,descriptor:r,mintedSecretsFile:t,options:n,reblessSchemaBaseline:o,recordArchitecture:a,stdout:s,validation:i})=>{const c={deployedAt:new Date().toISOString(),dryRun:n.dryRun===!0,env:n.env,preview:n.preview===!0,url:n.dryRun===!0?void 0:Eo(s),workerName:fe(e)};if(n.dryRun===!0||n.preview===!0)return n.healthCheck===!0&&n.logger.warn(`--health-check skipped: ${n.dryRun===!0?"a dry run publishes nothing":"a preview version serves no live traffic"}`),{code:0,deployment:c,descriptor:r,mintedSecretsFile:t,validation:i};n.temporary!==!0&&(a?.(),Ao({cwd:e,env:n.env,logger:n.logger,url:c.url}));const d=await Do(n,e,c.url);return d?.error!==void 0?{code:y.UNAVAILABLE,deployment:c,descriptor:r,healthCheck:d,mintedSecretsFile:t,validation:i}:{...await Co(n,e,r,i,o,t),deployment:c,healthCheck:d}},No=(e,r,t)=>{const n=b(e,P);if(!S(n))return;let o;try{o=Ge(A(n,"utf8")).length}catch{return}if(o===0)return;const a=t.toolchain?.secretPut!==void 0;r.warn(a?`Note: \`lunora deploy\` does not push secrets. ${P} has ${String(o)} key(s); if you changed them, run \`lunora env push --yes\` to update the deployed secrets.`:`Note: ${t.name} deploys read no secrets. ${P} has ${String(o)} key(s) that only the dev server sees; a key the app reads from env must be a \`vars\` entry in the deployed config, one it loads from a secret manager at runtime need not.`)},pr=async(e,r)=>{let t=[];try{t=Br(await qe({cache:r,projectRoot:e,schemaDir:N(e)}))}catch{}const n=[...new Set(Hr(t).map(a=>a.key))];let o=[];try{const a=b(e,P);S(a)&&(o=Ge(A(a,"utf8")).map(s=>s.key).filter(s=>ze(s)))}catch{}return{fromLocal:o.filter(a=>!n.includes(a)),fromPackages:n,mintableKeys:Gr(t)}},Oo=async(e,r,t,n)=>{const{logger:o}=r,a=r.spawner??x,s=j(e),i=r.env===void 0?"":` --env ${r.env}`,c=n.toolchain?.secretPut;if(c===void 0)return o.error(`deploy target "${n.id}" has no secret store; cannot push secrets`),{minted:[],ok:!1};const d=t.map(u=>({key:u,value:qr()})),l=n.toolchain?.secretBulk;if(l!==void 0&&d.length>=2){const u=F(s,l({environment:r.env,temporary:r.temporary})),h=await a({args:u.args,command:u.command,cwd:e,input:JSON.stringify(Object.fromEntries(d.map(f=>[f.key,f.value])))});if(h.code===0){for(const{key:f}of d)o.success(`generated + pushed ${f}`);return{minted:d,ok:!0}}o.warn(`bulk secret push failed (exit ${String(h.code)}); retrying one key at a time`)}const g=[];for(const{key:u,value:h}of d){const f=c({environment:r.env,key:u,temporary:r.temporary}),v=F(s,f),m=await a({args:v.args,command:v.command,cwd:e,input:h});if(m.code!==0)return o.error(`failed to push secret ${u} (exit ${String(m.code)}); set it manually with \`wrangler secret put ${u}${i}\`.`),{minted:g,ok:!1};g.push({key:u,value:h}),o.success(`generated + pushed ${u}`)}return{minted:g,ok:!0}},jo=/^[\w-]+$/u,xe=[".dev.vars",".dev.vars.*","!.dev.vars.example"],Io=(e,r)=>{try{const t=zr(e,xe);t.length>0&&r.info(`.gitignore: added ${t.join(", ")} so the recorded secret cannot be committed`)}catch(t){r.warn(`could not update .gitignore (${t instanceof Error?t.message:String(t)}) — add \`${xe.join("` and `")}\` by hand before committing.`)}},Lo=(e,r,t)=>{if(t.length===0)return;const n=t.map(i=>i.key).join(", ");if(r.env!==void 0&&!jo.test(r.env)){r.logger.warn(`${n}: 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 o=r.env===void 0?P:`${P}.${r.env}`;Io(e,r.logger);const a=b(e,o);let s=S(a)?A(a,"utf8"):"";for(const i of t)s=Vr(s,i.key,i.value);return Wr(a,s),r.logger.success(r.env===void 0?`${n}: value(s) recorded in ${o}`:`${n}: value(s) recorded in ${o} (kept separate from ${P} so \`lunora dev\` and a plain \`lunora env push\` don't inherit the --env ${r.env} value)`),o},xo=/^<[^>]+>$/u,Mo=async(e,r,t)=>{let n;try{n=t.projectConfig?.(e,"deploy").vars??{}}catch(l){return{error:l instanceof Error?l.message:String(l)}}const o=l=>{const g=n[l];if(typeof g!="string")return!0;const u=g.trim();return u===""||xo.test(u)?!0:ze(l)&&Kr(g)},a=l=>Object.hasOwn(n,l)?`${l} (empty or a placeholder)`:l,{fromLocal:s,fromPackages:i}=await pr(e,r.discoveryCache),c=s.filter(l=>o(l));c.length>0&&r.logger.warn(`${P} key(s) not set in the wrangler vars: ${c.map(l=>a(l)).join(", ")}. ${t.name} has no secret store: a key the app reads from env must be a \`vars\` entry; one it loads from a secret manager at runtime need not.`);const d=i.filter(l=>o(l));return d.length===0?{}:{error:`missing required secret(s) in the wrangler vars: ${d.map(l=>a(l)).join(", ")}. ${t.name} has no secret store and Lunora reads these from env, so each must be a real \`vars\` value in the config the deploy ships — write it there from your secret manager at deploy time rather than committing it. Add them, then re-deploy.`}},Fo=async(e,r,t,n)=>{if(r.dryRun===!0||r.preview===!0)return{};if(n.toolchain?.secretList===void 0)return Mo(e,r,n);const{logger:o}=r,a=r.env===void 0?"":` --env ${r.env}`;let s;try{s=await(r.secretLister??It)({cwd:e,env:r.env,target:n.id,temporary:r.temporary})}catch{return{}}if(!s.ok)return{};const i=new Set(s.names),{fromLocal:c,fromPackages:d,mintableKeys:l}=await pr(e,r.discoveryCache),g=[...d,...c].filter(f=>!i.has(f));if(g.length===0)return{};if(!t)return{error:`missing required secret(s) on the deploy target: ${g.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 f of g.filter(v=>!l.has(v)))o.warn(`required secret ${f} is not set on the target — set it with: wrangler secret put ${f}${a}`);const u=g.filter(f=>l.has(f));if(u.length===0)return{};if(await(r.secretConfirm??jt())(`${String(u.length)} required secret(s) not set on the target (${u.join(", ")}). Generate strong values and push them now?`)){const{minted:f,ok:v}=await Oo(e,r,u,n),m=Lo(e,r,f);return v?{mintedSecretsFile:m}:{error:"failed to push required secret(s) — set them manually and re-deploy",mintedSecretsFile:m}}return o.warn(`${String(u.length)} required secret(s) not set on the target: ${u.join(", ")}. Generate + push with \`lunora env generate --set\` then \`lunora env push --yes${a}\`.`),{}},yr=e=>e.format==="json"?!1:e.interactive!==void 0?e.interactive:process.stdout.isTTY&&!process.env.CI,Uo=async(e,r)=>{if(r.dryRun===!0)return;const t=He(e,"lunora",r.discoveryCache).containers.flatMap(o=>o.schedulingPolicy===void 0&&o.image.kind==="build"?[{buildDir:o.image.buildDir,exportName:o.exportName}]:[]);if(t.length===0)return;const n=await fn({cwd:e,logger:r.logger,railpackAvailable:r.railpackAvailable,spawner:r.spawner,targets:t});return n.code===0?void 0:n.error??"railpack build failed"},Bo=(e,r,t)=>{if(t!==void 0)try{const n=it(e,t);n.changed&&r.success(`synced ${String(t.length)} cron trigger(s) → ${n.wranglerPath??"wrangler.jsonc"}`);for(const a of n.warnings)r.warn(a);const o=ct(n.preserved);o!==void 0&&r.info(o)}catch(n){const o=n instanceof Error?n.message:String(n);r.warn(`cron trigger sync skipped: ${o}`)}},Ho=async(e,r,t,n,o,a)=>{try{Y(n);const s=await qe({cache:a,projectRoot:e,schemaDir:N(e)}),i=at(e,s,{environment:o,target:n}),c=i.wranglerPath??"wrangler.jsonc";if(i.added.length>0&&r.success(`provisioned bindings: ${i.added.join(", ")} → ${c}`),i.updated.length>0&&r.success(`updated bindings: ${i.updated.join(", ")} → ${c}`),i.devConfig!==void 0){const{added:d,path:l,updated:g}=i.devConfig;r.success(`dev sidecar bindings: ${[...d,...g].join(", ")} → ${l}`)}for(const d of i.warnings)r.warn(d)}catch(s){const i=s instanceof Error?s.message:String(s);r.warn(`binding inference skipped: ${i}`)}try{const s=st(e);s.changed&&r.success(`bumped compatibility_date to ${s.date??"unknown"} (Workers Cache enabled) → ${s.wranglerPath??"wrangler.jsonc"}`)}catch(s){const i=s instanceof Error?s.message:String(s);r.warn(`compatibility date sync skipped: ${i}`)}Bo(e,r,t)},Go=async(e,r,t,n,o,a,s,i,c,d)=>{let l;r?(l=new dt({name:"dots"}),l.start("running codegen")):t.info("running codegen");try{const g=Dr({apiSpec:n,dryRun:!d,lazyFunctions:o,projectRoot:e,target:a,...ot(e)});l?.succeed("codegen complete"),l||t.success("codegen complete");const u=lt(g.platformDiagnostics,t);if(u.errors.length>0)return{error:u.errors.join("; ")};const{errorAdvisories:h,names:f,shouldBlock:v}=ut(g.advisories,c);if(v){const E=`${h.length.toString()} ERROR-level ${h.length===1?"advisory":"advisories"} (${f.join(", ")}). Pass --no-strict-advisories to downgrade this to a warning and continue.`;return t.error(E),{error:E}}const m=d?await Zr({cwd:e,logger:t,spawner:s,stdoutToStderr:i}):void 0;return m?.error!==void 0?{error:m.error}:{result:g}}catch(g){l?.failed("codegen failed");const u=g instanceof Error?g.message:String(g);return t.error(`codegen failed: ${u}`),{error:`codegen failed: ${u}`}}},qo=(e,r)=>({dryRun:r.dryRun,entry:pe(e),environment:r.env,outDir:r.outDir,preview:r.preview,temporary:r.temporary}),wr=(e,r,t)=>{const{toolchain:n}=t;if(n===void 0)throw new Error(`deploy target "${t.id}" has no command-line toolchain`);const o=qo(e,r);return Ve(t,e,"deploy",a=>n.deploy({...o,configPath:a}))},Vo=(e,r,t)=>{const n=wr(e,r,t),o=pe(e);return o!==void 0&&r.logger.info(`class-B composition: deploying ${o} (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}`),n.commit(),n.projection!==void 0&&n.projection.dropped.length>0&&r.logger.warn(`${t.name} ignores these wrangler keys, so they were left out of ${n.projection.configPath}: ${n.projection.dropped.join(", ")}`),n.command},R={problems:[],wranglerPath:void 0},oe=(e,r)=>({code:y.USAGE,descriptor:void 0,error:e,validation:R,...r}),Wo=(e,r)=>{for(const t of e.report?.warnings??[])r.warn(`wrangler.jsonc: ${t}`);if(e.problems.length===0)return!1;r.error("wrangler.jsonc validation failed:");for(const t of e.problems)r.error(`  - ${t}`);return!0},Ko=(e,r,t)=>{const n=r.format==="json",o=r.dryRun!==!0,a=Vo(e,r,t),s=F(j(e),a);return{args:s.args,captureStdout:o&&!n,captureStdoutSilently:o&&n,command:s.command,cwd:e,stdoutToStderr:n&&!o}},ke=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"},zo=(e,r)=>ke(r)===void 0?le(e).services.map(t=>t.wranglerPath):[],kr=(e,r,t,n,o)=>({cwd:e,environment:r.env,frameworkBuild:n,lazyFunctions:J(r.lazyFunctions),logger:r.logger,outputJson:r.format==="json"||r.clientBuildOutputJson===!0,spawner:o,strictAdvisories:ge(r),target:t.id}),Jo=(e,r,t)=>{const{toolchain:n}=t,o=n===void 0?`target "${t.id}" has no deploy command`:ke(r);if(o!==void 0||n===void 0){const a=e.map(s=>s.worker).join(", ");r.logger.warn(`services not deployed (${o??""}): ${a} — deploy them yourself if the app calls anything new`);return}return n},br=(e,r)=>{for(const t of e){const n=me(r(M(t.wranglerPath)));if(n!==void 0)return`service ${t.name} (${t.worker}): ${n}`}},Yo=(e,r,t)=>{const{error:n,services:o}=le(e);if(n!==void 0||o.length===0)return;const a=Y(t);if(a.toolchain===void 0||ke(r)!==void 0)return;const s=r.skipCodegen===!0?!1:r.frameworkBuild,i=[...new Map(o.map(c=>[c.wranglerPath,c])).values()];return br(i,c=>kr(c,r,a,s,x))},Sr=(e,r,t)=>{const n=e.cwd??process.cwd(),o=kt(n,e.target);if(o.target===void 0){const i=o.error??"unknown deploy target";return e.logger.error(i),{kind:"refused",error:i,validation:R}}try{wr(n,e,Y(o.target))}catch(i){if(!(t&&i instanceof Jr&&Z(n,e.skipCodegen===!0?!1:e.frameworkBuild,e.env))){const c=i instanceof Error?i.message:String(i);return e.logger.error(c),{kind:"refused",error:c,validation:R}}}const a=e.openShardGatePassed===!0?void 0:Kn(n,e,r,zo(n,e));if(a!==void 0)return{kind:"refused",code:a.code,error:a.error,validation:R};const s=Yo(n,e,o.target);return s!==void 0?(e.logger.error(s),{kind:"refused",code:y.USAGE,error:s,validation:R}):{kind:"ok",target:o.target}},Xo=(e,r)=>e.apiSpec??(e.clientBuildRan===!0?et(r):void 0),Qo=async(e,r,t)=>{if(r!=="celld")return;const n=await(e.celldToolchain??Qr)({dryRun:t==="prepare"||e.dryRun===!0,env:process.env,purpose:"deploy"});for(const o of n.warnings)e.logger.warn(o);return n.errors.length>0?n.errors.join("; "):void 0},Zo=async(e,r)=>{const t=e.cwd??process.cwd(),n=yr(e),o=ge(e),a={problems:[],wranglerPath:void 0},s=Sr(e,r,!1);if(s.kind==="refused")return{code:s.code,error:s.error,validation:s.validation};const{target:i}=s,c=await Qo(e,i,r);if(c!==void 0)return e.logger.error(c),{code:y.MISSING_DEPENDENCY,error:c,target:i,validation:a};let d;if(!e.skipCodegen){const v=await Go(t,n,e.logger,Xo(e,t),J(e.lazyFunctions),i,e.spawner,e.format==="json",o,e.clientBuildRan!==!0);if(v.error!==void 0)return{error:v.error,target:i,validation:R};d=v.result,e.discoveryCache?.clear()}let l;if(d!==void 0){const v=Pt({allowDrift:e.allowSchemaDrift===!0,codegen:d,command:r,logger:e.logger,updateBaseline:e.updateSchemaBaseline===!0});if(v.blocked)return{error:`schema drift gate blocked ${r}`,schemaDrift:{blocked:!0,reason:v.reason},target:i,validation:a};l=v.rebless}const g=d&&Ht({current:d.architecture,cwd:t,environment:e.env,logger:e.logger});await Ho(t,e.logger,d?.cronTriggers,i,e.env,e.discoveryCache);const u=await vr(t,e,r,i,"check");if(u!==void 0)return{error:u,target:i,validation:R};const h=zn(t,e,r,i);if(h!==void 0)return{code:h.code,error:h.error,target:i,validation:R};const f=nt({environment:e.env,projectRoot:t});return Wo(f,e.logger)?{error:"wrangler validation failed",target:i,validation:f}:{codegen:d,reblessSchemaBaseline:l,recordArchitecture:g,target:i,validation:f}},ea=e=>{W(k(e,".wrangler","deploy","config.json"),{force:!0})},ra=async(e,r,t)=>{const n=me(e);if(n!==void 0)return{built:!1,error:n};const o=Z(e.cwd,r,t);return o&&ea(e.cwd),{built:o,error:await ar(e)}},ta=(e,r,t)=>r||t===!1?mr(e):void 0,na=async(e,r,t,n)=>{const{error:o,services:a}=le(e);if(o!==void 0)return{code:y.FAILURE,error:o};if(a.length===0)return;const s=Jo(a,r,t);if(s===void 0)return;const i=j(e),c=[...new Map(a.map(u=>[u.wranglerPath,u])).values()],d=r.skipCodegen===!0?!1:r.frameworkBuild,l=u=>kr(u,r,t,d,n),g=br(c,l);if(g!==void 0)return r.logger.error(g),{code:y.USAGE,error:g};for(const u of c){const h=M(u.wranglerPath),f=l(h),{built:v,error:m}=await ra(f,d,r.env);if(m!==void 0){const T=`service ${u.name} (${u.worker}): ${m}`;return r.logger.error(T),{code:y.FAILURE,error:T}}const E=ta(u.wranglerPath,v,d);let C;try{C=Ve(t,h,"deploy",T=>s.deploy({configPath:T??E??u.wranglerPath,dryRun:r.dryRun===!0,environment:r.env}))}catch(T){return{code:y.FAILURE,error:`service ${u.name} (${u.worker}): ${T instanceof Error?T.message:String(T)}`}}C.commit();const $=F(i,C.command);r.logger.info(`deploying service ${u.name} (${u.worker}) via ${$.command} ${$.args.join(" ")}`);const I=await n({args:$.args,command:$.command,cwd:h,stdoutToStderr:r.format==="json"});if(I.code!==0)return{code:y.FAILURE,error:`service ${u.name} (${u.worker}): ${$.command} ${$.args.join(" ")} exited ${String(I.code)} — stopping before the app`}}},oa=async(e,r,t,n)=>{if(r!=="cloudflare")return;const o=e===void 0?void 0:D(e).parsed,a=(t===void 0?void 0:o?.env?.[t]?.account_id)??o?.account_id,s=await pt({accountId:a});(s.verdict==="near"||s.verdict==="full")&&n.warn(s.fix===void 0?s.message:`${s.message} ${s.fix}`)},aa=e=>e.dryRun!==!0&&e.temporary!==!0,sa=e=>e.temporary===!0?"temporary":e.dryRun===!0?"preview":"defer",ia=e=>{const r=e.fix===void 0?e.message:`${e.message} ${e.fix}`;return e.verdict==="unchecked"?`${r} The deploy stops until it can be checked, as a namespace made by the first repo is unrestricted.`:r},ca=(e,r,t)=>{const n=[];for(const o of e)if(o.verdict==="ok")o.changesAccount===!0&&r.info(o.message);else if(o.verdict==="unchecked"&&t==="preview")r.warn(`dry run: ${o.message}${o.fix===void 0?"":` ${o.fix}`} A real deploy stops here.`);else{const a=ia(o);r.error(a),n.push(a)}return n},$r=async(e,r,t,n,o,a,s)=>{const i=t==="cloudflare"&&r!==void 0?D(r).parsed:void 0;if(i===void 0)return;const c=(X(i,n).merged.artifacts??[]).flatMap(f=>typeof f?.binding=="string"&&typeof f.namespace=="string"?[{binding:f.binding,namespace:f.namespace}]:[]),d=c.length===0?void 0:ue(e,N(e),a).info?.jurisdiction;if(d===void 0)return;const l=[...new Map(c.map(f=>[f.namespace,f])).values()];if(s==="temporary"){o.warn(`--temporary deploys to a throwaway account, so the jurisdiction ("${d}") of Artifacts namespace ${l.map(f=>`"${f.namespace}"`).join(", ")} was not checked: it is created there on first use, in no jurisdiction.`);return}const g=(n===void 0?void 0:i.env?.[n]?.account_id)??i.account_id,u=await Promise.all(l.map(async f=>vt({...f,accountId:g,create:s==="create",jurisdiction:d,missingOk:s==="defer"||s==="preview"}))),h=ca(u,o,s);return h.length===0?void 0:h.join(`
`)},da=async(e,r,t,n,o,a)=>{const s=aa(r)?await $r(e,a,o,r.env,r.logger,r.discoveryCache,"create"):void 0;if(s!==void 0)return{code:y.FAILURE,error:s};const i=await vr(e,r,"deploy",o);return i!==void 0?{code:y.FAILURE,error:i}:na(e,r,t,n)},la=async(e,r,t,n)=>{if(!(r.smokeLoad===!1||t.toolchain===void 0))return un({composedEntry:pe(e),configPath:n,cwd:e,environment:r.env,launcher:r.smokeLauncher,logger:r.logger,toolchain:t.toolchain})},ua=async e=>{const r={...e,discoveryCache:e.discoveryCache??Xr()},t=r.cwd??process.cwd(),n=yr(r),o=await Zo(r,r.commandName??"deploy");if(o.error!==void 0){if(o.validation.problems.length>0)return{code:y.USAGE,descriptor:void 0,error:o.error,validation:o.validation};const m=o.schemaDrift===void 0?void 0:{schemaDrift:o.schemaDrift};return oe(o.error,{...m,...o.code===void 0?{}:{code:o.code}})}const{validation:a}=o,s=Y(o.target),i=Rn(r)??await $r(t,a.wranglerPath,o.target,r.env,r.logger,r.discoveryCache,sa(r))??await la(t,r,s,a.wranglerPath);if(i!==void 0)return oe(i);const c=s.toolchain?.prebuildsContainerImages===!0?await Uo(t,r):void 0;if(c!==void 0)return oe(c);No(t,r.logger,s),tt(t,m=>{r.logger.warn(m)}),await oa(a.wranglerPath,o.target,r.env,r.logger);const{error:d,mintedSecretsFile:l}=await Fo(t,r,n,s);if(d!==void 0)return r.logger.error(d),{code:y.USAGE,descriptor:void 0,error:d,mintedSecretsFile:l,validation:a};const g=r.spawner??x,u=await da(t,r,s,g,o.target,a.wranglerPath);if(u!==void 0)return{code:u.code,descriptor:void 0,error:u.error,mintedSecretsFile:l,validation:a};const h=Ko(t,r,s);r.logger.info(`deploying via ${h.command} ${h.args.join(" ")}`);const f=await g(h);return h.captureStdoutSilently===!0&&f.stdout!==void 0&&f.stdout!==""&&process.stderr.write(f.stdout),f.code!==0?{code:f.code,descriptor:h,mintedSecretsFile:l,validation:a}:{...await Po({...o,cwd:t,descriptor:h,mintedSecretsFile:l,options:r,stdout:f.stdout}),logsAvailable:s.toolchain?.tail!==void 0}},ga=async e=>{const{logger:r}=e,t=e.cwd??process.cwd(),n={apiSpec:e.apiSpec,cwd:t,environment:e.env,bundleMetaPath:e.bundleMetaPath,frameworkBuild:e.skipCodegen===!0?!1:e.frameworkBuild,strictAdvisories:ge(e),lazyFunctions:J(e.lazyFunctions),logger:r,outputJson:e.format==="json"||e.clientBuildOutputJson===!0,spawner:e.spawner,target:e.target},o=me(n);if(o!==void 0)return r.error(o),{code:y.USAGE,descriptor:void 0,error:o,validation:R};Yr(t);const a=await ar(n);if(a!==void 0)return r.error(a),{code:y.FAILURE,descriptor:void 0,error:a,validation:R}},fa=(e,r)=>{const t=r.skipCodegen===!0?!1:r.frameworkBuild;return Z(e,t,r.env)?r.env:void 0},ha=async e=>{const{logger:r}=e,t=e.cwd??process.cwd(),n=Sr(e,e.commandName??"deploy",!0);if(n.kind==="refused")return{code:n.code??y.USAGE,descriptor:void 0,error:n.error,validation:n.validation};const o=await ga(e);if(o!==void 0)return o;const a=e.dryRun===!0?tr(t):void 0;let s;try{if(s=await ua({...e,clientBuildEnvironment:fa(t,e),clientBuildRan:wn(t,e.skipCodegen===!0?!1:e.frameworkBuild,e.env),logger:r,openShardGatePassed:!0}),s.code===0&&e.emitBindings!==void 0){const{error:i}=yt({destination:e.emitBindings,logger:r,projectRoot:e.cwd??process.cwd()});i!==void 0&&(r.error(i),s={...s,code:y.USAGE})}}finally{a?.()}if(e.format==="json")return s;if(s.code===0&&e.dryRun!==!0&&e.preview!==!0)Gt({cwd:e.cwd??process.cwd(),env:e.env,logger:e.logger,logsAvailable:s.logsAvailable===!0,mintedSecretsFile:s.mintedSecretsFile,url:s.deployment?.url});else if(s.code===0&&e.preview===!0){const i=s.deployment?.url;e.logger.success(i===void 0?"preview version uploaded":`preview version uploaded — ${i}`)}return s},Wa=wt(async({cwd:e,format:r,logger:t,options:n})=>{const o=gn(e,n.root),a=await ha({allowOpenShards:n.allowOpenShards===!0,allowSchemaDrift:n.allowSchemaDrift===!0,apiSpec:gt(n.apiSpec),frameworkBuild:n.prebuilt===!0?!1:n.frameworkBuild,lazyFunctions:J(n.lazyFunctions),cwd:o,dryRun:n.dryRun===!0,env:n.env,format:r,healthCheck:n.healthCheck===!0,logger:t,migrate:n.migrate===!0,migrateToken:n.migrateToken,migrateUrl:Ye({cwd:o,env:n.env,url:n.migrateUrl}),migrateYes:n.migrateYes===!0,preview:n.preview===!0,skipCodegen:n.prebuilt===!0,skipServices:n.skipServices===!0,smokeLoad:n.smokeLoad,strictAdvisories:n.strictAdvisories,target:n.target,temporary:n.temporary===!0,updateSchemaBaseline:n.updateSchemaBaseline===!0});return{code:a.code,data:{deployment:a.deployment,healthCheck:a.healthCheck,mintedSecretsFile:a.mintedSecretsFile,schemaDrift:a.schemaDrift,validation:a.validation},error:a.error}});export{Zo as a,Ho as b,Wa as e,gn as p,ha as r,la as s,hn as v};