@lunora/cli 1.0.0-alpha.464 → 1.0.0-alpha.465
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.d.mts +1 -1
- package/dist/cli.d.ts +1 -1
- package/dist/index.d.mts +8 -0
- package/dist/index.d.ts +8 -0
- package/dist/packem_chunks/cli.mjs +2 -2
- package/dist/packem_chunks/handler.mjs +9 -9
- package/dist/packem_chunks/handler13.mjs +3 -1
- package/dist/packem_chunks/handler14.mjs +1 -1
- package/dist/packem_chunks/handler15.mjs +1 -3
- package/dist/packem_chunks/handler28.mjs +3 -15
- package/dist/packem_chunks/handler29.mjs +15 -1
- package/dist/packem_chunks/handler30.mjs +1 -1
- package/dist/packem_chunks/handler31.mjs +1 -0
- package/dist/packem_chunks/runInitCommand.mjs +242 -80
- package/dist/packem_shared/runDeployCommand-XD2h1M8H.mjs +1 -0
- package/package.json +2 -2
- package/skills/lunora-deploy/SKILL.md +39 -3
- package/dist/packem_shared/runDeployCommand-2tEbutD6.mjs +0 -1
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import{mkdirSync as
|
|
1
|
+
import{mkdirSync as Xe,writeFileSync as V,existsSync as b,readFileSync as E,rmSync as Q,readdirSync as ve,mkdtempSync as Hr,realpathSync as Wr,statSync as Qe}from"node:fs";import{dirname as U,join as y,resolve as N,relative as F,sep as B,extname as Gr}from"node:path";import{PROJECT_CONFIG_FILENAMES as Vr,isTestPath as fe,discoverMigrations as qr,readServiceBindings as pe,runCodegen as Kr}from"@lunora/codegen";import{readLinkedProject as ye,resolveSchemaDirectory as I,startDevProcess as zr,acceptsConnection as Jr,resolveTargetOrThrow as ge,detectFramework as Yr,DEFAULT_BUNDLE_META_PATH as Xr,STRICT_ADVISORIES_ENV as Qr,LAZY_FUNCTIONS_ENV as Zr,BUNDLE_META_PATH_ENV as et,BUILD_TARGET_ENV as rt,BUILD_ROOT_ENV as tt,canonicalPath as nt,COMPOSED_WORKER_ENTRY as Ce,discoverContainerInfo as Ze,D1_PLACEHOLDER_ID as Ie,discoverSchemaInfo as we,writeLinkedProject as ot,DEV_VARS_FILE as C,parseDevVariableEntries as er,secretSourcesFromBindings as st,inferLunoraBindings as rr,requiredSecrets as at,mintableSecretKeysFor as it,generateSecretValue as ct,upsertDevVariableLine as dt,writeDevVariablesFileAtomically as lt,isPlaceholderValue as ut,ensureGitignoreEntries as ft,resolveLazyFunctions as te,resolveDeployDriver as ne,MissingBuildOutputError as gt,clearApiSpecMarker as ht,createDiscoveryCache as mt,planToolchainInvocation as tr,probeCelldToolchain as vt,runPostCodegenHook as pt,readApiSpecMarker as yt}from"@lunora/config";import{bindingsNeedingDatabase as wt,findWranglerFile as O,readWranglerJsonc as R,mergeWranglerEnvironment as oe,HYPERDRIVE_PLACEHOLDER_ID as nr,applyModify as or,warnCloudflareCliConfigOnce as kt,validateWranglerProject as bt,wranglerCodegenInputs as $t,reconcileWranglerBindings as St,reconcileWranglerCompatibilityDate as Et,reconcileWranglerCrons as At,describePreservedCrons as Rt}from"@lunora/config/cloudflare";import{Spinner as Tt}from"@visulima/spinner";import{r as Pt}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{n as _t,r as Dt,a as Ct}from"../packem_shared/admin-url-DJB8P6Jh.mjs";import{r as ke,a as It,e as Ot}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as Nt}from"../packem_shared/api-spec-lYyq4vL6.mjs";import{e as jt,m as Lt,g as Mt,i as sr,d as xt,b as Ft}from"../packem_shared/vectorize-metadata-BVSF8z2h.mjs";import{w as Ut}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{d as Bt}from"../packem_shared/command-B6vu47iR.mjs";import{r as be}from"../packem_shared/wrangler-name-Dsk5K1f-.mjs";import{a as Ht}from"../packem_shared/deploy-target-resolve-BTCW1Iv4.mjs";import{EXIT_CODE as w}from"../packem_shared/EXIT_CODE-DVjUgIaG.mjs";import{spawn as Wt}from"node:child_process";import{randomUUID as ar,createHash as Gt}from"node:crypto";import{setTimeout as Vt}from"node:timers/promises";import{toolchainExecArgs as H,detectPackageManager as j,execArgsFor as $e}from"@lunora/config/cli";import{f as qt}from"../packem_shared/free-port-DjbFhaaT.mjs";import{containerBuildTag as Kt}from"@lunora/container";import{a as zt,i as Jt}from"../packem_shared/docker-DpVxvYpL.mjs";import{defaultSpawner as x}from"../packem_shared/createRecordingSpawner-01ZngIwK.mjs";import{r as Se}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{p as Yt,H as Xt,a as Qt,r as Zt,c as en,b as rn}from"../packem_shared/health-probe-BLnoq_oC.mjs";import{runAdvisor as tn,openShardAccess as Oe}from"@lunora/advisor";import{join as $,relative as W,dirname as ir}from"@visulima/path";import{Project as cr,SyntaxKind as p,Node as k}from"ts-morph";import{r as dr,c as lr}from"../packem_shared/cloudflare-credentials-BVmZnDZk.mjs";import{runMigrateDataCommand as nn}from"../packem_shared/runMigrateGenerateCommand-CFy3hXXu.mjs";import{c as on}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{l as sn}from"../packem_shared/wrangler-secrets-DlSlWvRH.mjs";const an=Object.freeze({edges:[],nodes:[],modules:[],unresolved:[],version:1}),cn=20,Ne=e=>`${e.from} -${e.kind}-> ${e.to}`,z=(e,r)=>{const t=new Set(e);return r.filter(n=>!t.has(n)).toSorted((n,o)=>n.localeCompare(o))},dn=(e,r)=>{const t=e.modules.map(a=>a.name),n=r.modules.map(a=>a.name),o=e.edges.map(a=>Ne(a)),s=r.edges.map(a=>Ne(a));return{addedEdges:z(o,s),addedModules:z(t,n),removedEdges:z(s,o),removedModules:z(n,t)}},J=(e,r,t)=>{if(t.length===0)return[];const n=t.slice(0,cn).map(s=>` ${e} ${s}`),o=t.length-n.length;return[`${r}:`,...n,...o>0?[` … and ${o.toString()} more`]:[]]},ln=e=>{const r=[...J("+","modules added",e.addedModules),...J("-","modules removed",e.removedModules),...J("+","edges added",e.addedEdges),...J("-","edges removed",e.removedEdges)];return r.length===0?void 0:`architecture changes since the last deploy:
|
|
2
2
|
${r.join(`
|
|
3
|
-
`)}`},
|
|
4
|
-
`,"utf8")}catch(c){n.warn(`could not record the deployed architecture at ${o}: ${c instanceof Error?c.message:String(c)}`)}}},
|
|
5
|
-
hint: if this module is part of a circular import, an import it reads is still undefined while it evaluates`:"",
|
|
6
|
-
`))},
|
|
3
|
+
`)}`},un=(e,r)=>y(e,".lunora",r===void 0?"architecture.json":`architecture.${r}.json`),fn=e=>{if(b(e))try{const r=JSON.parse(E(e,"utf8"));return r.version===1&&Array.isArray(r.modules)&&Array.isArray(r.edges)?r:void 0}catch{return}},gn=e=>{const{cwd:r,environment:t,logger:n}=e,o=un(r,t),s=fn(o),a=e.current??(s===void 0?void 0:an);if(a===void 0)return;const i=s===void 0?void 0:ln(dn(s,a));return i!==void 0&&n.info(i),()=>{try{Xe(U(o),{recursive:!0}),V(o,`${JSON.stringify(a,void 0,2)}
|
|
4
|
+
`,"utf8")}catch(c){n.warn(`could not record the deployed architecture at ${o}: ${c instanceof Error?c.message:String(c)}`)}}},hn=e=>{const{cwd:r,env:t,logger:n,mintedSecretsFile:o}=e;try{const s=ye(r),a=s?.workerName??be(r),i=e.url??s?.workerUrl;n.success("deploy complete"),n.info(` worker: ${a??"(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{}},mn=/\/index$/u,vn=/[^\dA-Za-z]/gu,pn=e=>e.replace(mn,"").split("/").map(r=>r.replaceAll(vn,"_")),yn=e=>pn(e).join("_"),wn=18787,je=3,ur=12e4,kn=5e3,ce=10,fr=new Set([".js",".mjs",".mts",".ts",".tsx"]),bn=/\(void 0\)|is not a function|before initialization|of undefined/u,$n=e=>typeof e=="object"&&e!==null&&typeof e.functionPath=="string"&&(e.deferred===void 0||["agent","module","queue","workflow"].includes(e.deferred))&&typeof e.message=="string",Sn=e=>{const r=I(e),t=new Map;let n;try{n=ve(y(e,r),{recursive:!0,encoding:"utf8"})}catch{return t}for(const o of n){const s=Gr(o);fr.has(s)&&!o.split(B).some(a=>a==="_generated"||a==="node_modules")&&t.set(yn(o.slice(0,-s.length).split(B).join("/")),y(r,o))}return t},Le=e=>bn.test(e)?`
|
|
5
|
+
hint: if this module is part of a circular import, an import it reads is still undefined while it evaluates`:"",En=(e,r)=>{const t=Sn(e),n=new Map,o=[];for(const{deferred:s,functionPath:a,message:i}of r){if(s!==void 0){o.push(` ${a.slice(s.length+1)} (${s}): ${i}${Le(i)}`);continue}const c=a.lastIndexOf(":"),l=a.slice(0,c),d=`${l}\0${i}`,f=n.get(d)??{exports:[],message:i,namespace:l};f.exports.push(a.slice(c+1)),n.set(d,f)}return[...[...n.values()].map(({exports:s,message:a,namespace:i})=>` ${t.get(i)??i} (${s.join(", ")}): ${a}${Le(a)}`),...o]},Y=e=>{for(const r of fr)for(const t of[`${e}${r}`,y(e,`index${r}`)])if(b(t))return t},An=(e,r)=>{const t=y(e,r,"_generated"),n=i=>{try{return E(y(t,i),"utf8")}catch{return""}},o=n("app.ts"),s=[],a=(i,c)=>{c!==void 0&&s.push({file:c,kind:i,label:F(e,c).split(B).join("/")})};return o.includes('import("./queues.js")')&&a("queue",Y(y(t,"queues"))),n("workflows.mjs").includes('import("../workflows.js")')&&a("workflow",Y(y(e,r,"workflows"))),(n("agents.mjs").includes('import("../agents.js")')||o.includes('import("../agents.js")'))&&a("agent",Y(y(e,r,"agents"))),s},Rn=/\.[cm]?js$/u,Tn=/(?:await|=>|return|[=[,])\s*import\(\s*"([^"]+)"\s*\)(?!\s*\.(?!(?:then|catch|finally)\b))/gu,Pn=(e,r,t)=>{const n=y(e,r,"_generated"),o=new Set(t.map(i=>i.file)),s=[];let a;try{a=ve(n).filter(i=>i.endsWith(".mjs")&&i!=="functions.ts")}catch{return s}for(const i of a.toSorted((c,l)=>c.localeCompare(l)))for(const c of E(y(n,i),"utf8").matchAll(Tn)){const l=c[1]??"",d=l.startsWith("."),f=d?Y(N(n,l.replace(Rn,""))):l;f!==void 0&&!o.has(f)&&(o.add(f),s.push({file:f,kind:"module",label:d?F(e,f).split(B).join("/"):l}))}return s};class _ extends Error{skipped;constructor(r,t=!1){super(r),this.skipped=t}}const _n=(e,r)=>{const t=O(e),n=t===void 0?void 0:R(t).parsed;if(n===void 0)return{hasContainers:!1,main:void 0};const{merged:o}=oe(n,r);return{hasContainers:(o.containers??[]).length>0,main:o.main}},Dn=({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:s,main:a}=_n(t,n),i=e??a;if(typeof i!="string"||i.startsWith("virtual:")||!b(N(t,i)))return{skip:"the Worker entry is not a file on disk"};if(s)return{skip:"the project declares containers, which `wrangler dev` would build locally before the real container build"};const c=wt(t,process.env,n,r);return c.length===0?{main:i}:{skip:`the Hyperdrive binding ${c.join(", ")} has no local database for wrangler dev`}},Cn=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(u=>{throw u instanceof Error&&u.name==="TimeoutError"?new _(`the smoke Worker booted but did not finish evaluating the lazy modules within ${String(ur/1e3)}s — a module may be awaiting something that never settles. Pass --no-smoke-load to ship anyway.`):u});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 s;try{s=JSON.parse(o)}catch{s=void 0}const{checked:a,deferredChecked:i=0,failures:c,run:l}=s??{};if(typeof a=="number"&&Array.isArray(c)&&c.every(u=>$n(u)))return l===r?{checked:a,deferredChecked:i,failures:c}:void 0;const d=n.headers.get("content-type")??"no content type",f=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}${f===""?"":`: ${f}`}). 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.`)},he=(e,r)=>{try{process.kill(-e,r)}catch{}},Me=e=>{try{return process.kill(-e,0),!0}catch{return!1}},In=e=>{const r=()=>{he(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},de=async e=>{if(e===void 0)return;e.dispose();const{pid:r}=e;he(r,"SIGTERM");const t=Date.now()+kn;for(;Me(r)&&Date.now()<t;)await Vt(50);Me(r)&&he(r,"SIGKILL")},On=e=>zr(e).catch(async r=>{if(!await Jr(e.port))throw r}),Nn=(e,{checked:r,deferredChecked:t,failures:n},o)=>{const s=t===0?`${String(r)} lazy function(s)`:`${String(r)} lazy function(s) and ${String(t)} deferred module(s)`;if(n.length===0){o.success(`${s} evaluate cleanly`);return}const a=En(e,n),i=a.length>ce?[` …and ${String(a.length-ce)} more module(s)`]:[];throw new _([`${String(n.length)} of ${t===0?`${String(r)} lazy function(s)`:`${String(r+t)} lazy module(s)`} fail to load:`,...a.slice(0,ce),...i,"Fix the module, or pass --no-smoke-load to ship anyway."].join(`
|
|
6
|
+
`))},jn=(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(`
|
|
7
7
|
`),o=`the smoke Worker did not start (${e instanceof Error?e.message:String(e)})${n===""?"":`
|
|
8
|
-
${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},
|
|
8
|
+
${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},Ln=e=>{try{return Xe(y(e,".lunora"),{recursive:!0}),Hr(y(e,".lunora","smoke-"))}catch(r){throw new _(`could not create a directory for the check (${r instanceof Error?r.message:String(r)})`,!0)}},Mn=async e=>{const{configPath:r,cwd:t,deferred:n,directory:o,environment:s,functionsFile:a,main:i,preferred:c,toolchain:l}=e;try{const d=y(o,"entry.ts"),f=ar();V(d,`export * from ${JSON.stringify(N(t,i))};
|
|
9
9
|
${a===void 0?"":`import { loadAllFunctions } from ${JSON.stringify(a)};
|
|
10
10
|
`}
|
|
11
|
-
const runId = ${JSON.stringify(
|
|
11
|
+
const runId = ${JSON.stringify(f)};
|
|
12
12
|
|
|
13
13
|
// Deferred event modules, evaluated here so a module that throws on import blocks like a function module does.
|
|
14
14
|
const deferred = [
|
|
@@ -39,5 +39,5 @@ export default {
|
|
|
39
39
|
});
|
|
40
40
|
},
|
|
41
41
|
};
|
|
42
|
-
`);const u=await Kt(c),{args:h,command:f}=H(N(t),l.dev({configPath:r===void 0?void 0:F(t,r),environment:s,extraArgs:[F(t,d),"--local","--local-protocol","http","--ip","127.0.0.1","--port",String(u),"--persist-to",F(t,y(o,"state"))]}));return{args:h,command:f,port:u,runId:g}}catch(d){throw new _(`could not prepare the check (${d instanceof Error?d.message:String(d)})`,!0)}},Fn=async e=>{const{configPath:r,cwd:t,environment:n,launcher:o,logger:s,toolchain:a}=e,i=y(t,I(t),"_generated","functions.ts"),c=b(i)&&E(i,"utf8").includes("export const loadAllFunctions"),l=I(t),d=Rn(t,l);if(!c&&d.length===0)return;const g=[...d,..._n(t,l,d)],u=Cn(e);if("skip"in u){s.warn(`smoke-load skipped: ${u.skip}, so lazy modules are not evaluated before deploy`);return}const{main:h}=u,f=[];let v,m;const T=Date.now()+gr,L=process.platform!=="win32",D=(P,S,q)=>{const M=Gt(P,[...S],{cwd:q.cwd,detached:L,shell:q.shell,stdio:["ignore","pipe","pipe"]});return L&&M.pid!==void 0&&(m={dispose:On(M.pid),pid:M.pid}),M};try{v=Mn(t),s.info("smoke-loading lazy function modules in workerd");let P=kn;for(let S=0;S<Ne;S+=1){const{args:q,command:M,port:ie,runId:Hr}=await xn({configPath:r,cwd:t,deferred:g,directory:v,environment:n,functionsFile:c?i:void 0,main:h,preferred:P,toolchain:a});P=ie+1;const De=await jn({args:q,command:M,cwd:t,spawn:o??D,label:"wrangler dev (smoke-load)",notFound:"`wrangler` was not found",onLine:K=>{f.push(K)},port:ie,readyTimeoutMs:Math.max(0,T-Date.now()),shell:process.platform==="win32"});if(De===void 0){await de(m),m=void 0;continue}try{const K=await In(ie,Hr,T);if(K!==void 0){Nn(t,K,s);return}}finally{await De.stop(),await de(m),m=void 0}}throw new _(`the smoke port was answered by other runs on all ${String(Ne)} attempts`,!0)}catch(P){return Ln(P,f,s)}finally{if(await de(m),v!==void 0)try{Q(v,{force:!0,recursive:!0})}catch{}}},Un=(e,r)=>r===void 0?e:j(e,r),Bn=async e=>{if(e.targets.length===0)return{builtTags:[],code:0};if(!(e.railpackAvailable??Jt)()){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=zt(n.exportName),s={args:["build",n.buildDir,"--name",o],command:"railpack",cwd:e.cwd},a=$e(N(e.cwd),"wrangler",["containers","push",o]),i={args:a.args,command:a.command,cwd:e.cwd};e.logger.info(`railpack: building "${n.exportName}" → ${o} from ${n.buildDir}`);const c=await r(s);if(c.code!==0){const d=`railpack build failed for container "${n.exportName}" (${n.buildDir})`;return e.logger.error(d),{builtTags:t,code:c.code,error:d}}e.logger.info(`railpack: pushing ${o} to the Cloudflare Registry`);const l=await r(i);if(l.code!==0){const d=`wrangler containers push failed for "${n.exportName}" (${o})`;return e.logger.error(d),{builtTags:t,code:l.code,error:d}}t.push(o)}return{builtTags:t,code:0}},Hn=new Set(["0.0.0.0","[::1]","[::]","localhost"]),Wn=[".local",".localhost"],Gn=["[fc","[fd"],Vn=/^\[fe[89ab][0-9a-f]:/u,qn=/^[a-z]+:\/\//u,xe=e=>{const r=e.split(".").map(Number);if(r.length!==4||r.some(o=>!Number.isInteger(o)))return!1;const[t=-1,n=-1]=r;return t===0||t===127||t===100&&n>=64&&n<=127||t===198&&(n===18||n===19)||t===10||t===192&&n===168||t===172&&n>=16&&n<=31||t===169&&n===254},Fe="[::ffff:",Kn=e=>{if(!e.startsWith(Fe)||!e.endsWith("]"))return;const r=e.slice(Fe.length,-1);if(r.includes("."))return r;const[t=0,n=0]=r.split(":").map(o=>Number.parseInt(o,16));return[Math.floor(t/256),t%256,Math.floor(n/256),n%256].join(".")},hr=e=>{let r=e.length;for(;r>0&&e[r-1]===".";)r-=1;return e.slice(0,r).toLowerCase()},zn=e=>{const r=e.toLowerCase(),t=Kn(r);return t!==void 0?xe(t):Hn.has(r)||Wn.some(n=>r.endsWith(n))||Gn.some(n=>r.startsWith(n))||Vn.test(r)||xe(r)},mr=e=>{const r=O(e);return r===void 0?void 0:R(r).parsed},vr=(e,r)=>{const t=typeof e?.name=="string"&&e.name!==""?e.name:void 0;if(r===void 0)return t;const n=e?.env?.[r]?.name;return typeof n=="string"&&n!==""?n:t===void 0?void 0:`${t}-${r}`},Z=(e,r)=>{let t=e.length;for(;t>0&&e[t-1]===r;)t-=1;return e.slice(0,t)},Jn=e=>{const r=e.replace(qn,""),t=r.indexOf("/"),n=(t===-1?r:r.slice(0,t)).toLowerCase(),o=t===-1?"":Z(r.slice(t),"*");return o==="/"?n:`${n}${o}`},Ue=e=>[e?.route,...Array.isArray(e?.routes)?e.routes:[]].flatMap(t=>{const n=typeof t=="string"?t:t?.pattern;return typeof n=="string"&&n!==""?[Jn(n)]:[]}),Yn=(e,r,t)=>{const n=t.indexOf("/"),o=n===-1?t:t.slice(0,n),s=n===-1?"":t.slice(n),a=o.startsWith("*");if(!(!(a?e.endsWith(o.slice(1)):e===o)||s!==""&&!`${Z(r,"/")}/`.startsWith(s)))return s.length*1e6+(a?0:5e5)+o.length},Xn=e=>e!==void 0&&(Object.hasOwn(e,"route")||Object.hasOwn(e,"routes")),pr=(e,r)=>{const t=Ue(e),o=[...new Set([...Object.keys(e?.env??{}),...r===void 0?[]:[r]])].map(s=>{const a=e?.env?.[s];return{id:`env:${s}`,label:`--env ${s}`,routes:Xn(a)?Ue(a):t}});return[{id:"top",label:"production",routes:t},...o]},Qn=(e,r,t,n)=>{const o=r===void 0?"top":`env:${r}`,s=pr(e,r).flatMap(c=>c.routes.flatMap(l=>{const d=Yn(t,n,l);return d===void 0?[]:[{block:c,score:d}]}));if(s.length===0)return{kind:"none"};const a=Math.max(...s.map(c=>c.score)),i=s.filter(c=>c.score===a);return i.some(c=>c.block.id===o)?{kind:"own"}:{kind:"other",label:i[0]?.block.label??"production"}},X=e=>Dt(`${e.origin}${e.pathname}`),Zn=(e,r,t,n,o)=>{const s=ye(e),a=s?.workerUrl!==void 0&&URL.canParse(s.workerUrl)?new URL(s.workerUrl):void 0;if(a===void 0)return;if(s?.env===r)return X(a)===X(t)?null:`${n}: this checkout is linked to ${X(a)}${o}`;const i=`${Z(a.pathname,"/")}/`;if(a.origin!==t.origin||!`${Z(t.pathname,"/")}/`.startsWith(i))return;const c=s?.env===void 0?"production":`--env ${s.env}`;return`${n}: this checkout links it to ${c}, not this deploy${o}`},yr=(e,r,t,n,o,s)=>{const a=Qn(e,r,t,n);if(a.kind==="other")return`${o}: wrangler routes it to ${a.label}, not this deploy${s}`;if(a.kind==="own")return;const i=pr(e,r);if(i.every(l=>l.routes.length===0))return;const c=i.find(l=>l.id===(r===void 0?"top":`env:${r}`))?.routes??[];return`${o}: this deploy${s} routes to ${c.length===0?"no declared route":c.join(", ")}, not ${t}`},eo=(e,r,t,n,o,s)=>{const a=mr(e);if(t.endsWith(".workers.dev")){const i=vr(a,r);return i!==void 0&&t.split(".")[0]!==i?`${o}: this deploy ships the Worker "${i}"${s}`:`${o}: no link ties this *.workers.dev host to your account${s}; run \`lunora link --url https://${t}${r===void 0?"":` --env ${r}`}\` once the Worker is deployed, then deploy again (or confirm the drift yourself with --allow-schema-drift)`}return yr(a,r,t,n,o,s)},ro=(e,r,t,n,o)=>{const s=mr(e),a=hr(t.hostname);if(a.endsWith(".workers.dev")){const i=vr(s,r);return i===void 0||a.split(".")[0]===i?void 0:`${n}: this deploy ships the Worker "${i}", not the one the link names${o}`}return yr(s,r,a,t.pathname,n,o)},to=(e,r,t)=>{let n;try{n=new URL(t)}catch{return`refused ${t} as the deployment to read rows from: it is not a URL`}const o=`refused ${X(n)} as the deployment to read rows from`,s=r===void 0?"":` (--env ${r})`,a=hr(n.hostname);if(zn(a))return`${o}: it is a local or private address, not the worker this deploy ships to`;const i=Zn(e,r,n,o,s);return i===void 0?eo(e,r,a,n.pathname,o,s):i??ro(e,r,n,o,s)},wr=e=>{const t=[O(e),y(e,"package.json"),y(e,"wrangler.dev.jsonc")].filter(n=>n!==void 0&&b(n)).map(n=>[n,E(n,"utf8")]);return()=>{for(const[n,o]of t)E(n,"utf8")!==o&&V(n,o,"utf8")}},no=(e,r=ir())=>j(e,".lunora",`vite-bundle-meta-${r}.json`),kr="LUNORA_CLIENT_BUILD",oo="virtual:lunora/worker",me=(e,r)=>["ts","mts","cts","js","mjs","cjs"].some(t=>b(y(e,`${r}.config.${t}`))),br=e=>me(e,"rsbuild")?"rsbuild":me(e,"vite")?"vite":void 0,so=e=>me(e,"vite")?"vite":br(e),ao=e=>{try{const{scripts:r}=JSON.parse(E(y(e,"package.json"),"utf8"));return typeof r?.build=="string"&&r.build!==""}catch{return!1}},se=(e,r)=>{if(process.env[kr]==="1")return;const t=O(e),n=t===void 0?void 0:R(t).parsed,o=n?.main===oo,s=(o?so(e):br(e))??(ao(e)?"script":void 0);if(s===void 0)return;const a=r===void 0?void 0:n?.env?.[r]?.assets?.directory,i=n?.assets?.directory??a;return o||Xr(e).class!=="C"||i!==void 0?s:void 0},io=async(e,r,t)=>{const n=t.spawner??x,o=N(e),s=r==="script"?{args:["run","build"],command:o}:$e(o,r,["build"]);t.logger.info(`running ${r} build before bundling the Worker`);const a=wr(e),i=t.bundleMetaPath??no(e);Q(y(e,Qr),{force:!0});try{const c=await n({args:s.args,command:s.command,cwd:e,env:{[nt]:ot(e),[tt]:t.target,[rt]:i,...t.lazyFunctions?{[et]:"1"}:{},...t.environment===void 0?{}:{CLOUDFLARE_ENV:t.environment},...t.strictAdvisories===!1?{[Zr]:"0"}:{},[kr]:"1"},stdoutToStderr:t.outputJson});return c.code===0?void 0:`${r} build failed with exit code ${String(c.code)}`}finally{a(),t.bundleMetaPath===void 0&&Q(i,{force:!0})}},ae=(e,r,t)=>r!==!1&&se(e,t)!==void 0,co=(e,r,t)=>ae(e,r,t)&&se(e,t)!=="script",Ee=e=>{const r=e.frameworkBuild===!1?void 0:se(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{fe(e.cwd,e.target)}catch(n){return n instanceof Error?n.message:String(n)}let t;try{t=fe(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`},$r=async e=>{const r=e.frameworkBuild===!1?void 0:se(e.cwd,e.environment);if(r===void 0)return;let t;try{t=e.target??fe(e.cwd)}catch(n){return n instanceof Error?n.message:String(n)}return io(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})},Be=e=>Array.isArray(e)?e.filter(r=>r!=null):void 0,Ae=(e,r)=>{const t=O(e);if(!t)return;const{parsed:n}=R(t);if(n===void 0)return;const{error:o,merged:s}=oe(n,r),a=o===void 0?s:n,{containers:i,d1_databases:c,vars:l}=a;return{containers:Be(i),d1_databases:Be(c),vars:typeof l=="object"&&l!==null&&!Array.isArray(l)?l:void 0}},lo=/^127(?:\.\d{1,3}){3}$/,uo=e=>{try{const{hostname:r}=new URL(e);return r==="localhost"||lo.test(r)||r==="::1"||r==="[::1]"}catch{return!1}},go=e=>e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.includes("Dockerfile"),fo=(e,r,t,n="deploy",o)=>{const s=(Ae(e,o)?.containers??[]).filter(i=>typeof i?.image=="string"&&go(i.image));if(s.length===0||t())return;const a=`${n} blocked: wrangler.jsonc declares ${String(s.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(a),a},Re=e=>b($(e,Ce))?Ce:void 0,ho=(e,r,t="deploy",n)=>{for(const o of er(e,"lunora",n).containers){const s=o.schedulingPolicy===void 0?o.image:void 0,i=[...s?.kind==="dockerfile"?[{field:"image",path:s.dockerfilePath}]:[],...Object.entries(o.schedulingPolicy==="durable_object"?o.images??{}:{}).flatMap(([c,l])=>l.kind==="dockerfile"?[{field:`images["${c}"]`,path:l.dockerfilePath}]:[])].find(c=>!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(s?.kind==="build"&&!b($(e,s.buildDir))){const c=`${t} blocked: container "${o.exportName}" references a Railpack build directory "${s.buildDir}" that does not exist. Create it or fix the \`image.build\` path in lunora/containers.ts.`;return r.error(c),c}}},mo=(e,r)=>r==="celld"?typeof e=="string"&&e!==Ie&&Lt(e):r==="cloudflare"&&e===Ie,vo=(e,r,t)=>(Ae(e,t)?.d1_databases??[]).find(n=>mo(n.database_id,r)),po=e=>{if(!e.migrate||e.dryRun)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}},yo=(e,r,t,n,o)=>{const s=vo(e,n,o);if(s===void 0)return;const a=`${t} blocked: the "${s.binding??"<unnamed>"}" D1 binding has a placeholder database_id ("${s.database_id??""}")`,i=n==="celld"?`${a}, which celld would use as the database's identity. Set database_id to the database celld should use, then ${t} again.`:`${a}. 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},wo=(e,r,t="deploy",n)=>{const o=Ae(e,n)?.vars;if(!o)return;const s=Object.entries(o).filter(([,i])=>typeof i=="string"&&uo(i)).map(([i])=>i).toSorted((i,c)=>i.localeCompare(c));if(s.length===0)return;const a=`${t} blocked: ${s.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(a),a},ko=["vite.config.ts","vite.config.mts","vite.config.cts","vite.config.js","vite.config.mjs","vite.config.cjs",...qr],Sr=/\.(?:[cm]?[jt]s|tsx|jsx)$/u,Er=/\.(?:test|spec)\.[cm]?[jt]sx?$/u,Ar="allowUnauthenticatedShardAccess",bo=/[\\/]/u,Rr=new Set(["_generated","build","dist","node_modules"]),Tr=(e,r)=>{const t=W(e,r).split(bo);return Sr.test(r)&&!Er.test(r)&&!ge(t.join("/"))&&t.every(n=>n===".."||!n.startsWith(".")&&!Rr.has(n))},He=(e,r,t)=>{const{parsed:n}=R(r);if(n===void 0)return[];const{error:o,merged:s}=oe(n,t),{main:a}=o===void 0?s:n,i=typeof a=="string"?$(cr(r),a):void 0;return i!==void 0&&b(i)&&Tr(e,i)?[i]:[]},Te=e=>e===void 0?!1:e.getKind()===p.FalseKeyword?!0:k.isParenthesizedExpression(e)||k.isAsExpression(e)||k.isSatisfiesExpression(e)||k.isTypeAssertion(e)||k.isNonNullExpression(e)?Te(e.getExpression()):!1,$o=e=>{try{return Ze(e).isFile()}catch{return!1}},So=new Set(["ELOOP","ENOENT","ENOTDIR"]),ee=(e,r,t)=>{const n=r instanceof Error&&"code"in r&&typeof r.code=="string"?r.code:"";So.has(n)||t.push(e)},Eo=(e,r)=>{try{return Ze(e)}catch(t){ee(e,t,r);return}},Pr=(e,r)=>{try{return E(e,"utf8")}catch(t){ee(e,t,r);return}},_r=(e,r,t,n=new Set)=>{let o;try{o=Gr(r)}catch(a){return ee(r,a,t),[]}if(n.has(o))return[];n.add(o);let s;try{s=ve(r)}catch(a){return ee(r,a,t),[]}return s.flatMap(a=>{const i=$(r,a),c=Eo(i,t);if(c===void 0)return[];const l=W(e,i).split(B).join("/");return c.isDirectory()?Rr.has(a)||a.startsWith(".")||ge(`${l}/`)?[]:_r(e,i,t,n):c.isFile()&&Sr.test(a)&&!Er.test(a)&&!ge(l)?[i]:[]})},Ao=e=>{const r=k.isComputedPropertyName(e)?e.getExpression():e;return k.isStringLiteral(r)||k.isNoSubstitutionTemplateLiteral(r)?r.getLiteralValue():e.getText()},le=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],Ro=/\.(?:[cm]?js|jsx)$/u,To=(e,r)=>{if(!r.startsWith("."))return;const t=j(cr(e),r),n=t.replace(Ro,"");return[t,...le.map(s=>`${t}${s}`),...le.map(s=>$(t,`index${s}`)),...le.map(s=>`${n}${s}`)].find(s=>$o(s))},Po=e=>{if(e.getExpression().getText()!=="require")return;const[r]=e.getArguments();return r!==void 0&&(k.isStringLiteral(r)||k.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():void 0},_o=e=>{const r=e.getModuleReference();if(!k.isExternalModuleReference(r))return;const t=r.getExpression();return k.isStringLiteral(t)?t.getLiteralValue():void 0},Do=(e,r,t,n)=>{const o=new Set(e),s=[...e],a=[];for(let i=0;i<s.length;i+=1){const c=s[i]??"",l=Pr(c,n);if(l===void 0)continue;const d=r.createSourceFile(W(t,c),l,{overwrite:!0}),g=[...d.getImportDeclarations().map(u=>u.getModuleSpecifierValue()),...d.getExportDeclarations().map(u=>u.getModuleSpecifierValue()),...d.getDescendantsOfKind(p.ImportEqualsDeclaration).map(u=>_o(u)),...d.getDescendantsOfKind(p.CallExpression).map(u=>Po(u))].filter(u=>u!==void 0);for(const u of g){const h=To(c,u);h!==void 0&&Tr(t,h)&&!o.has(h)&&(o.add(h),a.push(h),s.push(h))}}return a},Co=e=>{const r=e.getArgumentExpression();return r!==void 0&&(k.isStringLiteral(r)||k.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():void 0},Io=e=>k.isPropertyAccessExpression(e)?e.getName():k.isElementAccessExpression(e)?Co(e):void 0,Oo=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]),jo=e=>{const r=e.getOperatorToken().getKind();return!Oo.has(r)||Io(e.getLeft())!==Ar?!1:r!==p.EqualsToken||!Te(e.getRight())},No=(e,r,t)=>{const n=[],o=[...new Set([I(e),"src"])].filter(g=>b($(e,g))),s=O(e),a=[...ko.map(g=>$(e,g)).filter(g=>b(g)),...s===void 0?[]:He(e,s,r),...t.flatMap(g=>He(e,g,r))],i=new dr({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}),c=o.flatMap(g=>_r($(e,g),$(e,g),n));return{sites:[...new Set([...c,...a,...Do([...a,...c],i,e,n)])].flatMap(g=>{const u=Pr(g,n);if(u===void 0)return[];const h=i.createSourceFile(W(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 T=k.isPropertyAssignment(m)&&Te(m.getInitializer());return Ao(m.getNameNode())===Ar&&!T}).map(m=>m.getStartLineNumber()),v=h.getDescendantsOfKind(p.BinaryExpression).filter(m=>jo(m)).map(m=>m.getStartLineNumber());return[...f,...v].map(m=>({file:W(e,g),line:m}))}),unreadable:n}},Lo=(e,r,t,n,o,s)=>{if(t!=="deploy")return;const{sites:a,unreadable:i}=No(e,o,s),c=nn({openShardAccess:a,schema:{tables:[]}},{lints:[Oe]});if(c.length===0&&i.length===0)return;const l=[];if(c.length>0){const g=c.map(u=>`${String(u.metadata.file)}:${String(u.metadata.line)}`).join(", ");l.push(`${g} enable the open-shard option (any value but a literal false), so any caller may target any shard.`)}if(i.length>0&&l.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): ${l.join(" ")}`);return}const d=`deploy blocked (open_shard_access): ${l.join(" ")} ${Oe.remediation}`;return r.error(d),d},Mo=(e,r,t,n)=>{const o=Lo(e,r.logger,t,r.allowOpenShards===!0,r.env,n);return o===void 0?void 0:{code:w.USAGE,error:o}},xo=(e,r,t,n)=>{const o=yo(e,r.logger,t,n,r.env);if(o!==void 0)return{code:w.USAGE,error:o};const s=wo(e,r.logger,t,r.env);if(s!==void 0)return{code:w.USAGE,error:s};const a=ho(e,r.logger,t,r.discoveryCache);if(a!==void 0)return{code:w.USAGE,error:a};const i=fo(e,r.logger,r.dockerAvailable??Yt,t,r.env);return i===void 0?void 0:{code:w.MISSING_DEPENDENCY,error:i}},We=32,Dr=15e3,Fo=5432,Uo=3306,Bo=/[^a-z0-9-]/gu,Ho=/[^A-Za-z0-9]/gu,Wo=/-$/u,G=e=>`LUNORA_${e.replaceAll(Ho,"_").toUpperCase()}_URL`,Go=e=>{const r=new Map;for(const t of e){const n=G(t),o=r.get(n);if(o!==void 0)return{bindings:[o,t],variable:n};r.set(n,t)}},Ge=7,Vo=(e,r)=>{const t=`${e}-${r}`.toLowerCase(),n=t.replaceAll(Bo,"-");if(n===t&&n.length<=We)return n;const o=Vt("sha256").update(t).digest("hex").slice(0,Ge-1);return`${n.slice(0,We-Ge).replace(Wo,"")}-${o}`},Ve=e=>e==="postgresql"?"postgres":e==="mariadb"?"mysql":e,qo=e=>e==="mysql"?Uo:Fo,Ko=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===""?qo(Ve(t)):Number(r.port),scheme:Ve(t),user:decodeURIComponent(r.username)}}catch{return}},zo=(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 s of n)o=o.replaceAll(s,"<redacted>");return o.split(" ").map(s=>s.includes("://")?"<url>":s).join(" ")},Cr=e=>(Array.isArray(e)?e:[]).flatMap((r,t)=>{const{binding:n,id:o}=typeof r=="object"&&r!==null?r:{};return typeof n=="string"&&o===or?[{binding:n,index:t}]:[]}),re=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}`},Jo=e=>typeof e=="string"||typeof e=="number"?e.toString():void 0,Yo=["scheme","host","port","database","user"],Xo=e=>e==="postgresql"?"postgres":e,qe=(e,r)=>{const t=Jo(r);return e==="scheme"?Xo(t):t},Ke=50,Qo=async(e,r)=>{for(let t=1;t<=Ke;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 (${re(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(a=>a.name===r),s=typeof n.body.result_info=="object"&&n.body.result_info!==null?n.body.result_info:{};if(o!==void 0||typeof s.total_pages!="number"||t>=s.total_pages)return o}throw new Error(`the listing of Hyperdrive configs has more than ${String(Ke)} pages, so "${r}" can't be shown to be absent`)},Zo=async(e,r,t,n)=>{const o=n?{caching:{disabled:!0}}:{},s=await Qo(e,r);if(typeof s?.id=="string"){const c=Yo.filter(d=>qe(d,s.origin?.[d])!==qe(d,t[d]));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 l=await e(`/hyperdrive/configs/${encodeURIComponent(s.id)}`,{body:JSON.stringify({origin:t,...o}),method:"PATCH"});if(!l.ok)throw new Error(`updating its credentials failed (${re(l)})`);return{id:s.id,reused:!0}}const a=await e("/hyperdrive/configs",{body:JSON.stringify({name:r,origin:t,...o}),method:"POST"});if(!a.ok)throw new Error(`creating it failed (${re(a)})`);const{id:i}=typeof a.body.result=="object"&&a.body.result!==null?a.body.result:{};if(typeof i!="string")throw new TypeError("the response carried no id");return{id:i,reused:!1}},es=(e,r,t,n)=>r===void 0&&n?`${G(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 ${G(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.`,rs=async(e,r)=>{const t=Vo(e.workerName,e.binding),{id:n,reused:o}=await Zo(async(s,a)=>ur({accountId:e.accountId,apiToken:e.token,...e.fetch===void 0?{}:{fetch:e.fetch},init:{...a,signal:AbortSignal.timeout(Dr)},path:s}),t,e.origin,e.disableCaching);return e.logger.success(`${o?"reusing":"created"} Hyperdrive config "${t}" for ${e.binding} → ${e.wranglerPath}`),{id:n,text:sr(r,[...e.path,e.index,"id"],n)}},ts=e=>e===void 0||e===""?void 0:e,Ir=e=>{const r=y(U(e),".wrangler","deploy","config.json");try{const{configPath:t}=JSON.parse(E(r,"utf8"));return typeof t=="string"?j(U(r),t):void 0}catch{return}},ns=(e,r,t,n,o)=>{const s=Ir(e);if(s===void 0||s===e)return;if(n.built!==n.deployed){o.warn(`the build output ${s} 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 a;try{a=R(s)}catch{return}const i=Cr(a.parsed?.hyperdrive).find(c=>c.binding===r);i!==void 0&&V(s,sr(a.text,["hyperdrive",i.index,"id"],t),"utf8")},os=(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}`},Pe=(e,r)=>{const t=O(e),n=t===void 0?void 0:R(t).parsed;if(t===void 0||n===void 0)return;const o=r===void 0?void 0:n.env?.[r],s=Cr(r===void 0?n.hyperdrive:o?.hyperdrive);return s.length===0?void 0:{accountId:o?.account_id??n.account_id,entries:s,path:r===void 0?["hyperdrive"]:["env",r,"hyperdrive"],workerName:os(n,r),wranglerPath:t}},ss=(e,r,t)=>{const n=Go(e.map(({binding:o})=>o));if(n!==void 0){const o=`deploy blocked: the Hyperdrive bindings ${n.bindings.map(s=>`"${s}"`).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:s,supplied:a}of e){const i=es(o,s,r,a);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}}},as=async(e,r,t,n)=>{let o;try{o=await e(`/hyperdrive/configs/${encodeURIComponent(t)}`)}catch(a){n.warn(`could not check whether the "${r}" Hyperdrive config has query caching off (${a instanceof Error?a.message:String(a)}).`);return}if(!o.ok){n.warn(`could not check whether the "${r}" Hyperdrive config has query caching off (${re(o)}).`);return}const{caching:s}=typeof o.body.result=="object"&&o.body.result!==null?o.body.result:{};s?.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\`.`)},is=async(e,r)=>{const t=O(e.cwd),n=t===void 0?void 0:R(t).parsed,o=e.wranglerEnvironment===void 0?n:n?.env?.[e.wranglerEnvironment],{accountId:s,token:a}=lr(r,o?.account_id??n?.account_id);if(s===void 0||a===void 0)return;const i=async(c,l)=>ur({accountId:s,apiToken:a,...e.fetch===void 0?{}:{fetch:e.fetch},init:{...l,signal:AbortSignal.timeout(Dr)},path:c});for(const c of Array.isArray(o?.hyperdrive)?o.hyperdrive:[]){const{binding:l,id:d}=typeof c=="object"&&c!==null?c:{};typeof l=="string"&&typeof d=="string"&&d!==or&&await as(i,l,d,e.logger)}},cs=async e=>{const r=e.environment??process.env;e.disableCaching===!0&&e.checkOnly!==!0&&e.dryRun!==!0&&await is(e,r);const t=Pe(e.cwd,e.wranglerEnvironment);if(t===void 0)return;const{entries:n,path:o,wranglerPath:s}=t,{accountId:a,token:i}=lr(r,t.accountId),c=n.map(({binding:d})=>{const g=r[G(d)]??"";return{binding:d,origin:Ko(g),supplied:g!==""}}),l=ss(c,i!==void 0&&a!==void 0,e);if(l!==void 0)return l;if(!(e.dryRun===!0||e.checkOnly===!0))for(const[d,{binding:g,index:u}]of n.entries()){const h=c[d]?.origin;if(!(h===void 0||i===void 0||a===void 0))try{const{id:f,text:v}=await rs({accountId:a,binding:g,disableCaching:e.disableCaching===!0,fetch:e.fetch,index:u,logger:e.logger,origin:h,path:o,token:i,workerName:t.workerName,wranglerPath:s},E(s,"utf8"));V(s,v,"utf8"),ns(s,g,f,{built:ts(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: ${zo(v,c[d]?.origin)}`;return e.logger.error(m),m}}},ds=(e,r)=>{const t=Pe(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 ${G(t)} set to create the config, or put the id from \`wrangler hyperdrive create\` in wrangler.jsonc.`;return r.logger.error(n),n},ls=(e,r)=>{const t=Pe(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},Or=async(e,r,t,n,o="create")=>{if(n!=="cloudflare")return;if(t==="prepare")return ds(e,r);if(r.temporary===!0)return ls(e,r);const s=r.clientBuildEnvironment===void 0?void 0:{...process.env,CLOUDFLARE_ENV:r.clientBuildEnvironment},a=we(e,I(e),r.discoveryCache);return a.error!==void 0&&r.logger.warn(`could not read the schema (${a.error}), so Hyperdrive configs are set up with query caching off.`),cs({checkOnly:o==="check",cwd:e,disableCaching:a.error!==void 0||a.info?.hasHyperdriveGlobalTable===!0,dryRun:r.dryRun,environment:s,logger:r.logger,wranglerEnvironment:r.env})},us=/https?:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/u,gs=/https:\/\/[^\s"'<>]+/u,fs=e=>{if(e===void 0)return;const r=us.exec(e);return r?r[0]:gs.exec(e)?.[0]},ze=e=>e===void 0?"":` (--env ${e})`,hs=({cwd:e,env:r,logger:t,now:n,url:o})=>{if(o!==void 0)try{const s=ye(e);if(s!==void 0){if(s.workerUrl===o&&s.env===r)return;t.warn(`link: .lunora/project.json records ${s.workerUrl??"(no url)"}${ze(s.env)}, but this deploy published ${o}${ze(r)}. Keeping the recorded value — run \`lunora link --url ${o}${r===void 0?"":` --env ${r}`}\` to update it.`);return}const a=(n??(()=>new Date().toISOString()))();st(e,{env:r,linkedAt:a,workerName:be(e),workerUrl:o}),t.success(`link: recorded ${o} in .lunora/project.json (run \`lunora link\` to change)`)}catch{}},ms=async(e,r)=>{const t=new dr({skipAddingFilesFromTsConfig:!0}),n=$(r,"lunora");let o;try{o=Kr(t,n)}catch(s){const a=s instanceof Error?s.message:String(s);return e.logger.warn(`--migrate: could not discover migrations (${a}); 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 s of o){e.logger.info(`--migrate: up "${s.id}" (table "${s.table}")`);const a={cwd:r,fetchImpl:e.fetchImpl,id:s.id,logger:e.logger,prod:!0,subcommand:"up",token:e.migrateToken,url:e.migrateUrl,yes:e.migrateYes===!0},i=await on(a);if(i.code!==0)return e.logger.error(`--migrate: migration "${s.id}" failed — see output above`),i.code;e.logger.success(`--migrate: "${s.id}" applied`)}return 0},vs=async(e,r)=>{const{info:t}=we(r,"lunora",e.discoveryCache),n=t?.vectorMetadata??[];if(n.length===0)return;const o=[];for(const i of n){const c=Mt(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 a=(await xt({cwd:r,entries:o,exec:$e(N(r),"wrangler",[]),logger:e.logger,spawner:e.spawner??x})).filter(i=>i.status!=="failed").length;a>0&&e.logger.success(`vectorize metadata indexes ready: ${String(a)}/${String(o.length)}`)},Je=5,ps=2e3,ys=async(e,r,t)=>{if(e.healthCheck!==!0)return;const n=t??Se({cwd:r,env:e.env});if(n===void 0){const s="--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(s),{error:s,ok:!1,url:""}}const o=await Xt({attempts:Je,baseUrl:n,delayMs:ps,fetchImpl:e.healthFetch,paths:[Qt,Zt],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(Je)} attempt(s) — ${o.error}`),{error:o.error,ok:!1,url:o.url})},ws=async(e,r,t,n,o,s)=>{await vs(e,r);const a=e.migrate?await ms(e,r):0;return a===0&&o?.(),{code:a,descriptor:t,mintedSecretsFile:s,validation:n}},ks=async({cwd:e,descriptor:r,mintedSecretsFile:t,options:n,reblessSchemaBaseline:o,recordArchitecture:s,stdout:a,validation:i})=>{const c={deployedAt:new Date().toISOString(),dryRun:n.dryRun===!0,env:n.env,url:n.dryRun===!0?void 0:fs(a),workerName:be(e)};if(n.dryRun===!0)return n.healthCheck===!0&&n.logger.warn("--health-check skipped: a dry run publishes nothing"),{code:0,deployment:c,descriptor:r,mintedSecretsFile:t,validation:i};n.temporary!==!0&&(s?.(),hs({cwd:e,env:n.env,logger:n.logger,url:c.url}));const l=await ys(n,e,c.url);return l?.error!==void 0?{code:w.UNAVAILABLE,deployment:c,descriptor:r,healthCheck:l,mintedSecretsFile:t,validation:i}:{...await ws(n,e,r,i,o,t),deployment:c,healthCheck:l}},bs=(e,r,t)=>{const n=$(e,C);if(!b(n))return;let o;try{o=rr(E(n,"utf8")).length}catch{return}if(o===0)return;const s=t.toolchain?.secretPut!==void 0;r.warn(s?`Note: \`lunora deploy\` does not push secrets. ${C} 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. ${C} 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.`)},jr=async(e,r)=>{let t=[];try{t=at(await tr({cache:r,projectRoot:e,schemaDir:I(e)}))}catch{}const n=[...new Set(it(t).map(s=>s.key))];let o=[];try{const s=$(e,C);b(s)&&(o=rr(E(s,"utf8")).map(a=>a.key).filter(a=>ar(a)))}catch{}return{fromLocal:o.filter(s=>!n.includes(s)),fromPackages:n,mintableKeys:ct(t)}},$s=async(e,r,t,n)=>{const{logger:o}=r,s=r.spawner??x,a=N(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 l=t.map(u=>({key:u,value:dt()})),d=n.toolchain?.secretBulk;if(d!==void 0&&l.length>=2){const u=H(a,d({environment:r.env,temporary:r.temporary})),h=await s({args:u.args,command:u.command,cwd:e,input:JSON.stringify(Object.fromEntries(l.map(f=>[f.key,f.value])))});if(h.code===0){for(const{key:f}of l)o.success(`generated + pushed ${f}`);return{minted:l,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 l){const f=c({environment:r.env,key:u,temporary:r.temporary}),v=H(a,f),m=await s({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}},Ss=/^[\w-]+$/u,Ye=[".dev.vars",".dev.vars.*","!.dev.vars.example"],Es=(e,r)=>{try{const t=ft(e,Ye);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 \`${Ye.join("` and `")}\` by hand before committing.`)}},As=(e,r,t)=>{if(t.length===0)return;const n=t.map(i=>i.key).join(", ");if(r.env!==void 0&&!Ss.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?C:`${C}.${r.env}`;Es(e,r.logger);const s=$(e,o);let a=b(s)?E(s,"utf8"):"";for(const i of t)a=lt(a,i.key,i.value);return ut(s,a),r.logger.success(r.env===void 0?`${n}: value(s) recorded in ${o}`:`${n}: value(s) recorded in ${o} (kept separate from ${C} so \`lunora dev\` and a plain \`lunora env push\` don't inherit the --env ${r.env} value)`),o},Rs=/^<[^>]+>$/u,Ts=async(e,r,t)=>{let n;try{n=t.projectConfig?.(e,"deploy").vars??{}}catch(d){return{error:d instanceof Error?d.message:String(d)}}const o=d=>{const g=n[d];if(typeof g!="string")return!0;const u=g.trim();return u===""||Rs.test(u)?!0:ar(d)&>(g)},s=d=>Object.hasOwn(n,d)?`${d} (empty or a placeholder)`:d,{fromLocal:a,fromPackages:i}=await jr(e,r.discoveryCache),c=a.filter(d=>o(d));c.length>0&&r.logger.warn(`${C} key(s) not set in the wrangler vars: ${c.map(d=>s(d)).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 l=i.filter(d=>o(d));return l.length===0?{}:{error:`missing required secret(s) in the wrangler vars: ${l.map(d=>s(d)).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.`}},Ps=async(e,r,t,n)=>{if(r.dryRun===!0)return{};if(n.toolchain?.secretList===void 0)return Ts(e,r,n);const{logger:o}=r,s=r.env===void 0?"":` --env ${r.env}`;let a;try{a=await(r.secretLister??an)({cwd:e,env:r.env,target:n.id,temporary:r.temporary})}catch{return{}}if(!a.ok)return{};const i=new Set(a.names),{fromLocal:c,fromPackages:l,mintableKeys:d}=await jr(e,r.discoveryCache),g=[...l,...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>${s}\` (or \`lunora env generate --set\` then \`lunora env push --yes${s}\`), then re-deploy.`};for(const f of g.filter(v=>!d.has(v)))o.warn(`required secret ${f} is not set on the target — set it with: wrangler secret put ${f}${s}`);const u=g.filter(f=>d.has(f));if(u.length===0)return{};if(await(r.secretConfirm??sn())(`${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 $s(e,r,u,n),m=As(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${s}\`.`),{}},Nr=e=>e.format==="json"?!1:e.interactive!==void 0?e.interactive:process.stdout.isTTY&&!process.env.CI,_s=async(e,r)=>{if(r.dryRun===!0)return;const t=er(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 Bn({cwd:e,logger:r.logger,railpackAvailable:r.railpackAvailable,spawner:r.spawner,targets:t});return n.code===0?void 0:n.error??"railpack build failed"},Ds=(e,r,t)=>{if(t!==void 0)try{const n=Rt(e,t);n.changed&&r.success(`synced ${String(t.length)} cron trigger(s) → ${n.wranglerPath??"wrangler.jsonc"}`);for(const s of n.warnings)r.warn(s);const o=Tt(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}`)}},Cs=async(e,r,t,n,o,s)=>{try{ne(n);const a=await tr({cache:s,projectRoot:e,schemaDir:I(e)}),i=Et(e,a,{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:l,path:d,updated:g}=i.devConfig;r.success(`dev sidecar bindings: ${[...l,...g].join(", ")} → ${d}`)}for(const l of i.warnings)r.warn(l)}catch(a){const i=a instanceof Error?a.message:String(a);r.warn(`binding inference skipped: ${i}`)}try{const a=At(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}`)}Ds(e,r,t)},Is=async(e,r,t,n,o,s,a,i,c,l)=>{let d;r?(d=new Pt({name:"dots"}),d.start("running codegen")):t.info("running codegen");try{const g=zr({apiSpec:n,dryRun:!l,lazyFunctions:o,projectRoot:e,target:s,...St(e)});d?.succeed("codegen complete"),d||t.success("codegen complete");const u=Ot(g.platformDiagnostics,t);if(u.errors.length>0)return{error:u.errors.join("; ")};const{errorAdvisories:h,names:f,shouldBlock:v}=jt(g.advisories,c);if(v){const T=`${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(T),{error:T}}const m=l?await yt({cwd:e,logger:t,spawner:a,stdoutToStderr:i}):void 0;return m?.error!==void 0?{error:m.error}:{result:g}}catch(g){d?.failed("codegen failed");const u=g instanceof Error?g.message:String(g);return t.error(`codegen failed: ${u}`),{error:`codegen failed: ${u}`}}},Xe="--preview is not supported: Cloudflare gives a Worker that implements a Durable Object no version preview URL, and a version shares production's Durable Objects, D1 and R2. Deploy an isolated copy with `--env <name>` (its own Worker name, so its own Durable Object namespace, plus the env's own D1/R2 bindings), or validate without publishing with `--dry-run`.",Os=(e,r)=>({dryRun:r.dryRun,entry:Re(e),environment:r.env,outDir:r.outDir,temporary:r.temporary}),Lr=(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=Os(e,r);return nr(t,e,"deploy",s=>n.deploy({...o,configPath:s}))},js=(e,r,t)=>{const n=Lr(e,r,t),o=Re(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},A={problems:[],wranglerPath:void 0},ue=(e,r)=>({code:w.USAGE,descriptor:void 0,error:e,validation:A,...r}),Ns=(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},Ls=(e,r,t)=>{const n=r.format==="json",o=r.dryRun!==!0,s=js(e,r,t),a=H(N(e),s);return{args:a.args,captureStdout:o&&!n,captureStdoutSilently:o&&n,command:a.command,cwd:e,stdoutToStderr:n&&!o}},_e=e=>{if(e.skipServices===!0)return"--skip-services";if(e.temporary===!0)return"--temporary deploys the app to a throwaway account"},Ms=(e,r)=>_e(r)===void 0?pe(e).services.map(t=>t.wranglerPath):[],Mr=(e,r,t,n,o)=>({cwd:e,environment:r.env,frameworkBuild:n,lazyFunctions:te(r.lazyFunctions),logger:r.logger,outputJson:r.format==="json"||r.clientBuildOutputJson===!0,spawner:o,strictAdvisories:ke(r),target:t.id}),xs=(e,r,t)=>{const{toolchain:n}=t,o=n===void 0?`target "${t.id}" has no deploy command`:_e(r);if(o!==void 0||n===void 0){const s=e.map(a=>a.worker).join(", ");r.logger.warn(`services not deployed (${o??""}): ${s} — deploy them yourself if the app calls anything new`);return}return n},xr=(e,r)=>{for(const t of e){const n=Ee(r(U(t.wranglerPath)));if(n!==void 0)return`service ${t.name} (${t.worker}): ${n}`}},Fs=(e,r,t)=>{const{error:n,services:o}=pe(e);if(n!==void 0||o.length===0)return;const s=ne(t);if(s.toolchain===void 0||_e(r)!==void 0)return;const a=r.skipCodegen===!0?!1:r.frameworkBuild,i=[...new Map(o.map(c=>[c.wranglerPath,c])).values()];return xr(i,c=>Mr(c,r,s,a,x))},Fr=(e,r,t)=>{const n=e.cwd??process.cwd(),o=Wt(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:A}}if(e.preview===!0)return e.logger.error(Xe),{kind:"refused",code:w.USAGE,error:Xe,validation:A};try{Lr(n,e,ne(o.target))}catch(i){if(!(t&&i instanceof ht&&ae(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:A}}}const s=e.openShardGatePassed===!0?void 0:Mo(n,e,r,Ms(n,e));if(s!==void 0)return{kind:"refused",code:s.code,error:s.error,validation:A};const a=Fs(n,e,o.target);return a!==void 0?(e.logger.error(a),{kind:"refused",code:w.USAGE,error:a,validation:A}):{kind:"ok",target:o.target}},Us=(e,r)=>e.apiSpec??(e.clientBuildRan===!0?wt(r):void 0),Bs=async(e,r,t)=>{if(r!=="celld")return;const n=await(e.celldToolchain??pt)({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},Ur=(e,r)=>{const t=Se({cwd:e,env:r.env,url:r.migrateUrl}),n=t===void 0?void 0:to(e,r.env,t);if(n!==void 0)return{reason:n};const o=t===void 0?void 0:Ct(t,r.logger,e),s=o===void 0?void 0:_t({cwd:e,token:r.migrateToken,url:o}).token;return{target:o===void 0||!s?void 0:{baseUrl:o,fetchImpl:r.fetchImpl??It,token:s}}},Hs=(e,r,t)=>async n=>{const o=Ur(e,r);return"reason"in o?{kind:"inconclusive",reason:o.reason}:tn({changes:n,tables:t.schemaTables,target:o.target})},Ws=(e,r)=>async t=>{const n=Ur(e,r);return"reason"in n?n.reason:rn({changes:t,now:Date.now(),target:n.target})},Gs=(e,r,t,n)=>e==="deploy"?{checkStoredRows:Hs(r,t,n),countExpiringRows:Ws(r,t)}:{},Vs=async(e,r)=>{const t=e.cwd??process.cwd(),n=Nr(e),o=ke(e),s={problems:[],wranglerPath:void 0},a=Fr(e,r,!1);if(a.kind==="refused")return{code:a.code,error:a.error,validation:a.validation};const{target:i}=a,c=await Bs(e,i,r);if(c!==void 0)return e.logger.error(c),{code:w.MISSING_DEPENDENCY,error:c,target:i,validation:s};let l;if(!e.skipCodegen){const v=await Is(t,n,e.logger,Us(e,t),te(e.lazyFunctions),i,e.spawner,e.format==="json",o,e.clientBuildRan!==!0);if(v.error!==void 0)return{error:v.error,target:i,validation:A};l=v.result,e.discoveryCache?.clear()}let d;if(l!==void 0){const v=await en({allowDrift:e.allowSchemaDrift===!0,...Gs(r,t,e,l),codegen:l,command:r,logger:e.logger});if(v.blocked)return{error:`schema drift gate blocked ${r}`,schemaDrift:{blocked:!0,reason:v.reason},target:i,validation:s};d=v.rebless}const g=l&&hn({current:l.architecture,cwd:t,environment:e.env,logger:e.logger});await Cs(t,e.logger,l?.cronTriggers,i,e.env,e.discoveryCache);const u=await Or(t,e,r,i,"check");if(u!==void 0)return{error:u,target:i,validation:A};const h=xo(t,e,r,i);if(h!==void 0)return{code:h.code,error:h.error,target:i,validation:A};const f=$t({environment:e.env,projectRoot:t});return Ns(f,e.logger)?{error:"wrangler validation failed",target:i,validation:f}:{codegen:l,reblessSchemaBaseline:d,recordArchitecture:g,target:i,validation:f}},qs=e=>{Q(y(e,".wrangler","deploy","config.json"),{force:!0})},Ks=async(e,r,t)=>{const n=Ee(e);if(n!==void 0)return{built:!1,error:n};const o=ae(e.cwd,r,t);return o&&qs(e.cwd),{built:o,error:await $r(e)}},zs=(e,r,t)=>r||t===!1?Ir(e):void 0,Js=async(e,r,t,n)=>{const{error:o,services:s}=pe(e);if(o!==void 0)return{code:w.FAILURE,error:o};if(s.length===0)return;const a=xs(s,r,t);if(a===void 0)return;const i=N(e),c=[...new Map(s.map(u=>[u.wranglerPath,u])).values()],l=r.skipCodegen===!0?!1:r.frameworkBuild,d=u=>Mr(u,r,t,l,n),g=xr(c,d);if(g!==void 0)return r.logger.error(g),{code:w.USAGE,error:g};for(const u of c){const h=U(u.wranglerPath),f=d(h),{built:v,error:m}=await Ks(f,l,r.env);if(m!==void 0){const S=`service ${u.name} (${u.worker}): ${m}`;return r.logger.error(S),{code:w.FAILURE,error:S}}const T=zs(u.wranglerPath,v,l);let L;try{L=nr(t,h,"deploy",S=>a.deploy({configPath:S??T??u.wranglerPath,dryRun:r.dryRun===!0,environment:r.env}))}catch(S){return{code:w.FAILURE,error:`service ${u.name} (${u.worker}): ${S instanceof Error?S.message:String(S)}`}}L.commit();const D=H(i,L.command);r.logger.info(`deploying service ${u.name} (${u.worker}) via ${D.command} ${D.args.join(" ")}`);const P=await n({args:D.args,command:D.command,cwd:h,stdoutToStderr:r.format==="json"});if(P.code!==0)return{code:w.FAILURE,error:`service ${u.name} (${u.worker}): ${D.command} ${D.args.join(" ")} exited ${String(P.code)} — stopping before the app`}}},Ys=async(e,r,t,n)=>{if(r!=="cloudflare")return;const o=e===void 0?void 0:R(e).parsed,s=(t===void 0?void 0:o?.env?.[t]?.account_id)??o?.account_id,a=await Ut({accountId:s});(a.verdict==="near"||a.verdict==="full")&&n.warn(a.fix===void 0?a.message:`${a.message} ${a.fix}`)},Xs=e=>e.dryRun!==!0&&e.temporary!==!0,Qs=e=>e.temporary===!0?"temporary":e.dryRun===!0?"preview":"defer",Zs=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},ea=(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 s=Zs(o);r.error(s),n.push(s)}return n},Br=async(e,r,t,n,o,s,a)=>{const i=t==="cloudflare"&&r!==void 0?R(r).parsed:void 0;if(i===void 0)return;const c=(oe(i,n).merged.artifacts??[]).flatMap(f=>typeof f?.binding=="string"&&typeof f.namespace=="string"?[{binding:f.binding,namespace:f.namespace}]:[]),l=c.length===0?void 0:we(e,I(e),s).info?.jurisdiction;if(l===void 0)return;const d=[...new Map(c.map(f=>[f.namespace,f])).values()];if(a==="temporary"){o.warn(`--temporary deploys to a throwaway account, so the jurisdiction ("${l}") of Artifacts namespace ${d.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(d.map(async f=>Ft({...f,accountId:g,create:a==="create",jurisdiction:l,missingOk:a==="defer"||a==="preview"}))),h=ea(u,o,a);return h.length===0?void 0:h.join(`
|
|
43
|
-
`)},
|
|
42
|
+
`);const u=await qt(c),{args:h,command:g}=H(j(t),l.dev({configPath:r===void 0?void 0:F(t,r),environment:s,extraArgs:[F(t,d),"--local","--local-protocol","http","--ip","127.0.0.1","--port",String(u),"--persist-to",F(t,y(o,"state"))]}));return{args:h,command:g,port:u,runId:f}}catch(d){throw new _(`could not prepare the check (${d instanceof Error?d.message:String(d)})`,!0)}},xn=async e=>{const{configPath:r,cwd:t,environment:n,launcher:o,logger:s,toolchain:a}=e,i=y(t,I(t),"_generated","functions.ts"),c=b(i)&&E(i,"utf8").includes("export const loadAllFunctions"),l=I(t),d=An(t,l);if(!c&&d.length===0)return;const f=[...d,...Pn(t,l,d)],u=Dn(e);if("skip"in u){s.warn(`smoke-load skipped: ${u.skip}, so lazy modules are not evaluated before deploy`);return}const{main:h}=u,g=[];let v,m;const T=Date.now()+ur,L=process.platform!=="win32",D=(P,S,q)=>{const M=Wt(P,[...S],{cwd:q.cwd,detached:L,shell:q.shell,stdio:["ignore","pipe","pipe"]});return L&&M.pid!==void 0&&(m={dispose:In(M.pid),pid:M.pid}),M};try{v=Ln(t),s.info("smoke-loading lazy function modules in workerd");let P=wn;for(let S=0;S<je;S+=1){const{args:q,command:M,port:ie,runId:Br}=await Mn({configPath:r,cwd:t,deferred:f,directory:v,environment:n,functionsFile:c?i:void 0,main:h,preferred:P,toolchain:a});P=ie+1;const De=await On({args:q,command:M,cwd:t,spawn:o??D,label:"wrangler dev (smoke-load)",notFound:"`wrangler` was not found",onLine:K=>{g.push(K)},port:ie,readyTimeoutMs:Math.max(0,T-Date.now()),shell:process.platform==="win32"});if(De===void 0){await de(m),m=void 0;continue}try{const K=await Cn(ie,Br,T);if(K!==void 0){Nn(t,K,s);return}}finally{await De.stop(),await de(m),m=void 0}}throw new _(`the smoke port was answered by other runs on all ${String(je)} attempts`,!0)}catch(P){return jn(P,g,s)}finally{if(await de(m),v!==void 0)try{Q(v,{force:!0,recursive:!0})}catch{}}},Fn=(e,r)=>r===void 0?e:N(e,r),Un=async e=>{if(e.targets.length===0)return{builtTags:[],code:0};if(!(e.railpackAvailable??zt)()){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=Kt(n.exportName),s={args:["build",n.buildDir,"--name",o],command:"railpack",cwd:e.cwd},a=$e(j(e.cwd),"wrangler",["containers","push",o]),i={args:a.args,command:a.command,cwd:e.cwd};e.logger.info(`railpack: building "${n.exportName}" → ${o} from ${n.buildDir}`);const c=await r(s);if(c.code!==0){const d=`railpack build failed for container "${n.exportName}" (${n.buildDir})`;return e.logger.error(d),{builtTags:t,code:c.code,error:d}}e.logger.info(`railpack: pushing ${o} to the Cloudflare Registry`);const l=await r(i);if(l.code!==0){const d=`wrangler containers push failed for "${n.exportName}" (${o})`;return e.logger.error(d),{builtTags:t,code:l.code,error:d}}t.push(o)}return{builtTags:t,code:0}},Bn=new Set(["0.0.0.0","[::1]","[::]","localhost"]),Hn=[".local",".localhost"],Wn=["[fc","[fd"],Gn=/^\[fe[89ab][0-9a-f]:/u,Vn=/^[a-z]+:\/\//u,xe=e=>{const r=e.split(".").map(Number);if(r.length!==4||r.some(o=>!Number.isInteger(o)))return!1;const[t=-1,n=-1]=r;return t===0||t===127||t===100&&n>=64&&n<=127||t===198&&(n===18||n===19)||t===10||t===192&&n===168||t===172&&n>=16&&n<=31||t===169&&n===254},Fe="[::ffff:",qn=e=>{if(!e.startsWith(Fe)||!e.endsWith("]"))return;const r=e.slice(Fe.length,-1);if(r.includes("."))return r;const[t=0,n=0]=r.split(":").map(o=>Number.parseInt(o,16));return[Math.floor(t/256),t%256,Math.floor(n/256),n%256].join(".")},gr=e=>{let r=e.length;for(;r>0&&e[r-1]===".";)r-=1;return e.slice(0,r).toLowerCase()},Kn=e=>{const r=e.toLowerCase(),t=qn(r);return t!==void 0?xe(t):Bn.has(r)||Hn.some(n=>r.endsWith(n))||Wn.some(n=>r.startsWith(n))||Gn.test(r)||xe(r)},hr=e=>{const r=O(e);return r===void 0?void 0:R(r).parsed},mr=(e,r)=>{const t=typeof e?.name=="string"&&e.name!==""?e.name:void 0;if(r===void 0)return t;const n=e?.env?.[r]?.name;return typeof n=="string"&&n!==""?n:t===void 0?void 0:`${t}-${r}`},Z=(e,r)=>{let t=e.length;for(;t>0&&e[t-1]===r;)t-=1;return e.slice(0,t)},zn=e=>{const r=e.replace(Vn,""),t=r.indexOf("/"),n=(t===-1?r:r.slice(0,t)).toLowerCase(),o=t===-1?"":Z(r.slice(t),"*");return o==="/"?n:`${n}${o}`},Ue=e=>[e?.route,...Array.isArray(e?.routes)?e.routes:[]].flatMap(t=>{const n=typeof t=="string"?t:t?.pattern;return typeof n=="string"&&n!==""?[zn(n)]:[]}),Jn=(e,r,t)=>{const n=t.indexOf("/"),o=n===-1?t:t.slice(0,n),s=n===-1?"":t.slice(n),a=o.startsWith("*");if(!(!(a?e.endsWith(o.slice(1)):e===o)||s!==""&&!`${Z(r,"/")}/`.startsWith(s)))return s.length*1e6+(a?0:5e5)+o.length},Yn=e=>e!==void 0&&(Object.hasOwn(e,"route")||Object.hasOwn(e,"routes")),vr=(e,r)=>{const t=Ue(e),o=[...new Set([...Object.keys(e?.env??{}),...r===void 0?[]:[r]])].map(s=>{const a=e?.env?.[s];return{id:`env:${s}`,label:`--env ${s}`,routes:Yn(a)?Ue(a):t}});return[{id:"top",label:"production",routes:t},...o]},Xn=(e,r,t,n)=>{const o=r===void 0?"top":`env:${r}`,s=vr(e,r).flatMap(c=>c.routes.flatMap(l=>{const d=Jn(t,n,l);return d===void 0?[]:[{block:c,score:d}]}));if(s.length===0)return{kind:"none"};const a=Math.max(...s.map(c=>c.score)),i=s.filter(c=>c.score===a);return i.some(c=>c.block.id===o)?{kind:"own"}:{kind:"other",label:i[0]?.block.label??"production"}},X=e=>_t(`${e.origin}${e.pathname}`),Qn=(e,r,t,n,o)=>{const s=ye(e),a=s?.workerUrl!==void 0&&URL.canParse(s.workerUrl)?new URL(s.workerUrl):void 0;if(a===void 0)return;if(s?.env===r)return X(a)===X(t)?null:`${n}: this checkout is linked to ${X(a)}${o}`;const i=`${Z(a.pathname,"/")}/`;if(a.origin!==t.origin||!`${Z(t.pathname,"/")}/`.startsWith(i))return;const c=s?.env===void 0?"production":`--env ${s.env}`;return`${n}: this checkout links it to ${c}, not this deploy${o}`},pr=(e,r,t,n,o,s)=>{const a=Xn(e,r,t,n);if(a.kind==="other")return`${o}: wrangler routes it to ${a.label}, not this deploy${s}`;if(a.kind==="own")return;const i=vr(e,r);if(i.every(l=>l.routes.length===0))return;const c=i.find(l=>l.id===(r===void 0?"top":`env:${r}`))?.routes??[];return`${o}: this deploy${s} routes to ${c.length===0?"no declared route":c.join(", ")}, not ${t}`},Zn=(e,r,t,n,o,s)=>{const a=hr(e);if(t.endsWith(".workers.dev")){const i=mr(a,r);return i!==void 0&&t.split(".")[0]!==i?`${o}: this deploy ships the Worker "${i}"${s}`:`${o}: no link ties this *.workers.dev host to your account${s}; run \`lunora link --url https://${t}${r===void 0?"":` --env ${r}`}\` once the Worker is deployed, then deploy again (or confirm the drift yourself with --allow-schema-drift)`}return pr(a,r,t,n,o,s)},eo=(e,r,t,n,o)=>{const s=hr(e),a=gr(t.hostname);if(a.endsWith(".workers.dev")){const i=mr(s,r);return i===void 0||a.split(".")[0]===i?void 0:`${n}: this deploy ships the Worker "${i}", not the one the link names${o}`}return pr(s,r,a,t.pathname,n,o)},ro=(e,r,t)=>{let n;try{n=new URL(t)}catch{return`refused ${t} as the deployment to read rows from: it is not a URL`}const o=`refused ${X(n)} as the deployment to read rows from`,s=r===void 0?"":` (--env ${r})`,a=gr(n.hostname);if(Kn(a))return`${o}: it is a local or private address, not the worker this deploy ships to`;const i=Qn(e,r,n,o,s);return i===void 0?Zn(e,r,a,n.pathname,o,s):i??eo(e,r,n,o,s)},yr=e=>{const t=[O(e),y(e,"package.json"),y(e,"wrangler.dev.jsonc")].filter(n=>n!==void 0&&b(n)).map(n=>[n,E(n,"utf8")]);return()=>{for(const[n,o]of t)E(n,"utf8")!==o&&V(n,o,"utf8")}},to=(e,r=ar())=>N(e,".lunora",`vite-bundle-meta-${r}.json`),wr="LUNORA_CLIENT_BUILD",no="virtual:lunora/worker",me=(e,r)=>["ts","mts","cts","js","mjs","cjs"].some(t=>b(y(e,`${r}.config.${t}`))),kr=e=>me(e,"rsbuild")?"rsbuild":me(e,"vite")?"vite":void 0,oo=e=>me(e,"vite")?"vite":kr(e),so=e=>{try{const{scripts:r}=JSON.parse(E(y(e,"package.json"),"utf8"));return typeof r?.build=="string"&&r.build!==""}catch{return!1}},se=(e,r)=>{if(process.env[wr]==="1")return;const t=O(e),n=t===void 0?void 0:R(t).parsed,o=n?.main===no,s=(o?oo(e):kr(e))??(so(e)?"script":void 0);if(s===void 0)return;const a=r===void 0?void 0:n?.env?.[r]?.assets?.directory,i=n?.assets?.directory??a;return o||Yr(e).class!=="C"||i!==void 0?s:void 0},ao=async(e,r,t)=>{const n=t.spawner??x,o=j(e),s=r==="script"?{args:["run","build"],command:o}:$e(o,r,["build"]);t.logger.info(`running ${r} build before bundling the Worker`);const a=yr(e),i=t.bundleMetaPath??to(e);Q(y(e,Xr),{force:!0});try{const c=await n({args:s.args,command:s.command,cwd:e,env:{[tt]:nt(e),[rt]:t.target,[et]:i,...t.lazyFunctions?{[Zr]:"1"}:{},...t.environment===void 0?{}:{CLOUDFLARE_ENV:t.environment},...t.strictAdvisories===!1?{[Qr]:"0"}:{},[wr]:"1"},stdoutToStderr:t.outputJson});return c.code===0?void 0:`${r} build failed with exit code ${String(c.code)}`}finally{a(),t.bundleMetaPath===void 0&&Q(i,{force:!0})}},ae=(e,r,t)=>r!==!1&&se(e,t)!==void 0,io=(e,r,t)=>ae(e,r,t)&&se(e,t)!=="script",Ee=e=>{const r=e.frameworkBuild===!1?void 0:se(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{ge(e.cwd,e.target)}catch(n){return n instanceof Error?n.message:String(n)}let t;try{t=ge(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`},br=async e=>{const r=e.frameworkBuild===!1?void 0:se(e.cwd,e.environment);if(r===void 0)return;let t;try{t=e.target??ge(e.cwd)}catch(n){return n instanceof Error?n.message:String(n)}return ao(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})},Be=e=>Array.isArray(e)?e.filter(r=>r!=null):void 0,Ae=(e,r)=>{const t=O(e);if(!t)return;const{parsed:n}=R(t);if(n===void 0)return;const{error:o,merged:s}=oe(n,r),a=o===void 0?s:n,{containers:i,d1_databases:c,vars:l}=a;return{containers:Be(i),d1_databases:Be(c),vars:typeof l=="object"&&l!==null&&!Array.isArray(l)?l:void 0}},co=/^127(?:\.\d{1,3}){3}$/,lo=e=>{try{const{hostname:r}=new URL(e);return r==="localhost"||co.test(r)||r==="::1"||r==="[::1]"}catch{return!1}},uo=e=>e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.includes("Dockerfile"),fo=(e,r,t,n="deploy",o)=>{const s=(Ae(e,o)?.containers??[]).filter(i=>typeof i?.image=="string"&&uo(i.image));if(s.length===0||t())return;const a=`${n} blocked: wrangler.jsonc declares ${String(s.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(a),a},Re=e=>b($(e,Ce))?Ce:void 0,go=(e,r,t="deploy",n)=>{for(const o of Ze(e,"lunora",n).containers){const s=o.schedulingPolicy===void 0?o.image:void 0,i=[...s?.kind==="dockerfile"?[{field:"image",path:s.dockerfilePath}]:[],...Object.entries(o.schedulingPolicy==="durable_object"?o.images??{}:{}).flatMap(([c,l])=>l.kind==="dockerfile"?[{field:`images["${c}"]`,path:l.dockerfilePath}]:[])].find(c=>!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(s?.kind==="build"&&!b($(e,s.buildDir))){const c=`${t} blocked: container "${o.exportName}" references a Railpack build directory "${s.buildDir}" that does not exist. Create it or fix the \`image.build\` path in lunora/containers.ts.`;return r.error(c),c}}},ho=(e,r)=>r==="celld"?typeof e=="string"&&e!==Ie&&jt(e):r==="cloudflare"&&e===Ie,mo=(e,r,t)=>(Ae(e,t)?.d1_databases??[]).find(n=>ho(n.database_id,r)),vo=e=>{if(!e.migrate||e.dryRun)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}},po=(e,r,t,n,o)=>{const s=mo(e,n,o);if(s===void 0)return;const a=`${t} blocked: the "${s.binding??"<unnamed>"}" D1 binding has a placeholder database_id ("${s.database_id??""}")`,i=n==="celld"?`${a}, which celld would use as the database's identity. Set database_id to the database celld should use, then ${t} again.`:`${a}. 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},yo=(e,r,t="deploy",n)=>{const o=Ae(e,n)?.vars;if(!o)return;const s=Object.entries(o).filter(([,i])=>typeof i=="string"&&lo(i)).map(([i])=>i).toSorted((i,c)=>i.localeCompare(c));if(s.length===0)return;const a=`${t} blocked: ${s.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(a),a},wo=["vite.config.ts","vite.config.mts","vite.config.cts","vite.config.js","vite.config.mjs","vite.config.cjs",...Vr],$r=/\.(?:[cm]?[jt]s|tsx|jsx)$/u,Sr=/\.(?:test|spec)\.[cm]?[jt]sx?$/u,Er="allowUnauthenticatedShardAccess",ko=/[\\/]/u,Ar=new Set(["_generated","build","dist","node_modules"]),Rr=(e,r)=>{const t=W(e,r).split(ko);return $r.test(r)&&!Sr.test(r)&&!fe(t.join("/"))&&t.every(n=>n===".."||!n.startsWith(".")&&!Ar.has(n))},He=(e,r,t)=>{const{parsed:n}=R(r);if(n===void 0)return[];const{error:o,merged:s}=oe(n,t),{main:a}=o===void 0?s:n,i=typeof a=="string"?$(ir(r),a):void 0;return i!==void 0&&b(i)&&Rr(e,i)?[i]:[]},Te=e=>e===void 0?!1:e.getKind()===p.FalseKeyword?!0:k.isParenthesizedExpression(e)||k.isAsExpression(e)||k.isSatisfiesExpression(e)||k.isTypeAssertion(e)||k.isNonNullExpression(e)?Te(e.getExpression()):!1,bo=e=>{try{return Qe(e).isFile()}catch{return!1}},$o=new Set(["ELOOP","ENOENT","ENOTDIR"]),ee=(e,r,t)=>{const n=r instanceof Error&&"code"in r&&typeof r.code=="string"?r.code:"";$o.has(n)||t.push(e)},So=(e,r)=>{try{return Qe(e)}catch(t){ee(e,t,r);return}},Tr=(e,r)=>{try{return E(e,"utf8")}catch(t){ee(e,t,r);return}},Pr=(e,r,t,n=new Set)=>{let o;try{o=Wr(r)}catch(a){return ee(r,a,t),[]}if(n.has(o))return[];n.add(o);let s;try{s=ve(r)}catch(a){return ee(r,a,t),[]}return s.flatMap(a=>{const i=$(r,a),c=So(i,t);if(c===void 0)return[];const l=W(e,i).split(B).join("/");return c.isDirectory()?Ar.has(a)||a.startsWith(".")||fe(`${l}/`)?[]:Pr(e,i,t,n):c.isFile()&&$r.test(a)&&!Sr.test(a)&&!fe(l)?[i]:[]})},Eo=e=>{const r=k.isComputedPropertyName(e)?e.getExpression():e;return k.isStringLiteral(r)||k.isNoSubstitutionTemplateLiteral(r)?r.getLiteralValue():e.getText()},le=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],Ao=/\.(?:[cm]?js|jsx)$/u,Ro=(e,r)=>{if(!r.startsWith("."))return;const t=N(ir(e),r),n=t.replace(Ao,"");return[t,...le.map(s=>`${t}${s}`),...le.map(s=>$(t,`index${s}`)),...le.map(s=>`${n}${s}`)].find(s=>bo(s))},To=e=>{if(e.getExpression().getText()!=="require")return;const[r]=e.getArguments();return r!==void 0&&(k.isStringLiteral(r)||k.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():void 0},Po=e=>{const r=e.getModuleReference();if(!k.isExternalModuleReference(r))return;const t=r.getExpression();return k.isStringLiteral(t)?t.getLiteralValue():void 0},_o=(e,r,t,n)=>{const o=new Set(e),s=[...e],a=[];for(let i=0;i<s.length;i+=1){const c=s[i]??"",l=Tr(c,n);if(l===void 0)continue;const d=r.createSourceFile(W(t,c),l,{overwrite:!0}),f=[...d.getImportDeclarations().map(u=>u.getModuleSpecifierValue()),...d.getExportDeclarations().map(u=>u.getModuleSpecifierValue()),...d.getDescendantsOfKind(p.ImportEqualsDeclaration).map(u=>Po(u)),...d.getDescendantsOfKind(p.CallExpression).map(u=>To(u))].filter(u=>u!==void 0);for(const u of f){const h=Ro(c,u);h!==void 0&&Rr(t,h)&&!o.has(h)&&(o.add(h),a.push(h),s.push(h))}}return a},Do=e=>{const r=e.getArgumentExpression();return r!==void 0&&(k.isStringLiteral(r)||k.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():void 0},Co=e=>k.isPropertyAccessExpression(e)?e.getName():k.isElementAccessExpression(e)?Do(e):void 0,Io=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]),Oo=e=>{const r=e.getOperatorToken().getKind();return!Io.has(r)||Co(e.getLeft())!==Er?!1:r!==p.EqualsToken||!Te(e.getRight())},No=(e,r,t)=>{const n=[],o=[...new Set([I(e),"src"])].filter(f=>b($(e,f))),s=O(e),a=[...wo.map(f=>$(e,f)).filter(f=>b(f)),...s===void 0?[]:He(e,s,r),...t.flatMap(f=>He(e,f,r))],i=new cr({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}),c=o.flatMap(f=>Pr($(e,f),$(e,f),n));return{sites:[...new Set([...c,...a,..._o([...a,...c],i,e,n)])].flatMap(f=>{const u=Tr(f,n);if(u===void 0)return[];const h=i.createSourceFile(W(e,f),u,{overwrite:!0}),g=[...h.getDescendantsOfKind(p.PropertyAssignment),...h.getDescendantsOfKind(p.ShorthandPropertyAssignment),...h.getDescendantsOfKind(p.GetAccessor),...h.getDescendantsOfKind(p.MethodDeclaration)].filter(m=>{const T=k.isPropertyAssignment(m)&&Te(m.getInitializer());return Eo(m.getNameNode())===Er&&!T}).map(m=>m.getStartLineNumber()),v=h.getDescendantsOfKind(p.BinaryExpression).filter(m=>Oo(m)).map(m=>m.getStartLineNumber());return[...g,...v].map(m=>({file:W(e,f),line:m}))}),unreadable:n}},jo=(e,r,t,n,o,s)=>{if(t!=="deploy")return;const{sites:a,unreadable:i}=No(e,o,s),c=tn({openShardAccess:a,schema:{tables:[]}},{lints:[Oe]});if(c.length===0&&i.length===0)return;const l=[];if(c.length>0){const f=c.map(u=>`${String(u.metadata.file)}:${String(u.metadata.line)}`).join(", ");l.push(`${f} enable the open-shard option (any value but a literal false), so any caller may target any shard.`)}if(i.length>0&&l.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): ${l.join(" ")}`);return}const d=`deploy blocked (open_shard_access): ${l.join(" ")} ${Oe.remediation}`;return r.error(d),d},Lo=(e,r,t,n)=>{const o=jo(e,r.logger,t,r.allowOpenShards===!0,r.env,n);return o===void 0?void 0:{code:w.USAGE,error:o}},Mo=(e,r,t,n)=>{const o=po(e,r.logger,t,n,r.env);if(o!==void 0)return{code:w.USAGE,error:o};const s=yo(e,r.logger,t,r.env);if(s!==void 0)return{code:w.USAGE,error:s};const a=go(e,r.logger,t,r.discoveryCache);if(a!==void 0)return{code:w.USAGE,error:a};const i=fo(e,r.logger,r.dockerAvailable??Jt,t,r.env);return i===void 0?void 0:{code:w.MISSING_DEPENDENCY,error:i}},xo=/[^a-z0-9-]/gu,Fo=/-$/u,We=7,Uo=(e,r)=>{const t=e.toLowerCase(),n=t.replaceAll(xo,"-");if(n===t&&n.length<=r)return n;const o=Gt("sha256").update(t).digest("hex").slice(0,We-1);return`${n.slice(0,r-We).replace(Fo,"")}-${o}`},Bo=32,_r=15e3,Ho=5432,Wo=3306,Go=/[^A-Za-z0-9]/gu,G=e=>`LUNORA_${e.replaceAll(Go,"_").toUpperCase()}_URL`,Vo=e=>{const r=new Map;for(const t of e){const n=G(t),o=r.get(n);if(o!==void 0)return{bindings:[o,t],variable:n};r.set(n,t)}},qo=(e,r)=>Uo(`${e}-${r}`,Bo),Ge=e=>e==="postgresql"?"postgres":e==="mariadb"?"mysql":e,Ko=e=>e==="mysql"?Wo:Ho,zo=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===""?Ko(Ge(t)):Number(r.port),scheme:Ge(t),user:decodeURIComponent(r.username)}}catch{return}},Jo=(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 s of n)o=o.replaceAll(s,"<redacted>");return o.split(" ").map(s=>s.includes("://")?"<url>":s).join(" ")},Dr=e=>(Array.isArray(e)?e:[]).flatMap((r,t)=>{const{binding:n,id:o}=typeof r=="object"&&r!==null?r:{};return typeof n=="string"&&o===nr?[{binding:n,index:t}]:[]}),re=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}`},Yo=e=>typeof e=="string"||typeof e=="number"?e.toString():void 0,Xo=["scheme","host","port","database","user"],Qo=e=>e==="postgresql"?"postgres":e,Ve=(e,r)=>{const t=Yo(r);return e==="scheme"?Qo(t):t},qe=50,Zo=async(e,r)=>{for(let t=1;t<=qe;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 (${re(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(a=>a.name===r),s=typeof n.body.result_info=="object"&&n.body.result_info!==null?n.body.result_info:{};if(o!==void 0||typeof s.total_pages!="number"||t>=s.total_pages)return o}throw new Error(`the listing of Hyperdrive configs has more than ${String(qe)} pages, so "${r}" can't be shown to be absent`)},es=async(e,r,t,n)=>{const o=n?{caching:{disabled:!0}}:{},s=await Zo(e,r);if(typeof s?.id=="string"){const c=Xo.filter(d=>Ve(d,s.origin?.[d])!==Ve(d,t[d]));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 l=await e(`/hyperdrive/configs/${encodeURIComponent(s.id)}`,{body:JSON.stringify({origin:t,...o}),method:"PATCH"});if(!l.ok)throw new Error(`updating its credentials failed (${re(l)})`);return{id:s.id,reused:!0}}const a=await e("/hyperdrive/configs",{body:JSON.stringify({name:r,origin:t,...o}),method:"POST"});if(!a.ok)throw new Error(`creating it failed (${re(a)})`);const{id:i}=typeof a.body.result=="object"&&a.body.result!==null?a.body.result:{};if(typeof i!="string")throw new TypeError("the response carried no id");return{id:i,reused:!1}},rs=(e,r,t,n)=>r===void 0&&n?`${G(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 ${G(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.`,ts=async(e,r)=>{const t=qo(e.workerName,e.binding),{id:n,reused:o}=await es(async(s,a)=>lr({accountId:e.accountId,apiToken:e.token,...e.fetch===void 0?{}:{fetch:e.fetch},init:{...a,signal:AbortSignal.timeout(_r)},path:s}),t,e.origin,e.disableCaching);return e.logger.success(`${o?"reusing":"created"} Hyperdrive config "${t}" for ${e.binding} → ${e.wranglerPath}`),{id:n,text:or(r,[...e.path,e.index,"id"],n)}},ns=e=>e===void 0||e===""?void 0:e,Cr=e=>{const r=y(U(e),".wrangler","deploy","config.json");try{const{configPath:t}=JSON.parse(E(r,"utf8"));return typeof t=="string"?N(U(r),t):void 0}catch{return}},os=(e,r,t,n,o)=>{const s=Cr(e);if(s===void 0||s===e)return;if(n.built!==n.deployed){o.warn(`the build output ${s} 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 a;try{a=R(s)}catch{return}const i=Dr(a.parsed?.hyperdrive).find(c=>c.binding===r);i!==void 0&&V(s,or(a.text,["hyperdrive",i.index,"id"],t),"utf8")},ss=(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}`},Pe=(e,r)=>{const t=O(e),n=t===void 0?void 0:R(t).parsed;if(t===void 0||n===void 0)return;const o=r===void 0?void 0:n.env?.[r],s=Dr(r===void 0?n.hyperdrive:o?.hyperdrive);return s.length===0?void 0:{accountId:o?.account_id??n.account_id,entries:s,path:r===void 0?["hyperdrive"]:["env",r,"hyperdrive"],workerName:ss(n,r),wranglerPath:t}},as=(e,r,t)=>{const n=Vo(e.map(({binding:o})=>o));if(n!==void 0){const o=`deploy blocked: the Hyperdrive bindings ${n.bindings.map(s=>`"${s}"`).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:s,supplied:a}of e){const i=rs(o,s,r,a);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}}},is=async(e,r,t,n)=>{let o;try{o=await e(`/hyperdrive/configs/${encodeURIComponent(t)}`)}catch(a){n.warn(`could not check whether the "${r}" Hyperdrive config has query caching off (${a instanceof Error?a.message:String(a)}).`);return}if(!o.ok){n.warn(`could not check whether the "${r}" Hyperdrive config has query caching off (${re(o)}).`);return}const{caching:s}=typeof o.body.result=="object"&&o.body.result!==null?o.body.result:{};s?.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\`.`)},cs=async(e,r)=>{const t=O(e.cwd),n=t===void 0?void 0:R(t).parsed,o=e.wranglerEnvironment===void 0?n:n?.env?.[e.wranglerEnvironment],{accountId:s,token:a}=dr(r,o?.account_id??n?.account_id);if(s===void 0||a===void 0)return;const i=async(c,l)=>lr({accountId:s,apiToken:a,...e.fetch===void 0?{}:{fetch:e.fetch},init:{...l,signal:AbortSignal.timeout(_r)},path:c});for(const c of Array.isArray(o?.hyperdrive)?o.hyperdrive:[]){const{binding:l,id:d}=typeof c=="object"&&c!==null?c:{};typeof l=="string"&&typeof d=="string"&&d!==nr&&await is(i,l,d,e.logger)}},ds=async e=>{const r=e.environment??process.env;e.disableCaching===!0&&e.checkOnly!==!0&&e.dryRun!==!0&&await cs(e,r);const t=Pe(e.cwd,e.wranglerEnvironment);if(t===void 0)return;const{entries:n,path:o,wranglerPath:s}=t,{accountId:a,token:i}=dr(r,t.accountId),c=n.map(({binding:d})=>{const f=r[G(d)]??"";return{binding:d,origin:zo(f),supplied:f!==""}}),l=as(c,i!==void 0&&a!==void 0,e);if(l!==void 0)return l;if(!(e.dryRun===!0||e.checkOnly===!0))for(const[d,{binding:f,index:u}]of n.entries()){const h=c[d]?.origin;if(!(h===void 0||i===void 0||a===void 0))try{const{id:g,text:v}=await ts({accountId:a,binding:f,disableCaching:e.disableCaching===!0,fetch:e.fetch,index:u,logger:e.logger,origin:h,path:o,token:i,workerName:t.workerName,wranglerPath:s},E(s,"utf8"));V(s,v,"utf8"),os(s,f,g,{built:ns(r.CLOUDFLARE_ENV),deployed:e.wranglerEnvironment},e.logger)}catch(g){const v=g instanceof Error?g.message:String(g),m=`deploy blocked: the "${f}" Hyperdrive config could not be set up: ${Jo(v,c[d]?.origin)}`;return e.logger.error(m),m}}},ls=(e,r)=>{const t=Pe(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 ${G(t)} set to create the config, or put the id from \`wrangler hyperdrive create\` in wrangler.jsonc.`;return r.logger.error(n),n},us=(e,r)=>{const t=Pe(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},Ir=async(e,r,t,n,o="create")=>{if(n!=="cloudflare")return;if(t==="prepare")return ls(e,r);if(r.temporary===!0)return us(e,r);const s=r.clientBuildEnvironment===void 0?void 0:{...process.env,CLOUDFLARE_ENV:r.clientBuildEnvironment},a=we(e,I(e),r.discoveryCache);return a.error!==void 0&&r.logger.warn(`could not read the schema (${a.error}), so Hyperdrive configs are set up with query caching off.`),ds({checkOnly:o==="check",cwd:e,disableCaching:a.error!==void 0||a.info?.hasHyperdriveGlobalTable===!0,dryRun:r.dryRun,environment:s,logger:r.logger,wranglerEnvironment:r.env})},fs=/https?:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/u,gs=/https:\/\/[^\s"'<>]+/u,hs=e=>{if(e===void 0)return;const r=fs.exec(e);return r?r[0]:gs.exec(e)?.[0]},Ke=e=>e===void 0?"":` (--env ${e})`,ms=({cwd:e,env:r,logger:t,now:n,url:o})=>{if(o!==void 0)try{const s=ye(e);if(s!==void 0){if(s.workerUrl===o&&s.env===r)return;t.warn(`link: .lunora/project.json records ${s.workerUrl??"(no url)"}${Ke(s.env)}, but this deploy published ${o}${Ke(r)}. Keeping the recorded value — run \`lunora link --url ${o}${r===void 0?"":` --env ${r}`}\` to update it.`);return}const a=(n??(()=>new Date().toISOString()))();ot(e,{env:r,linkedAt:a,workerName:be(e),workerUrl:o}),t.success(`link: recorded ${o} in .lunora/project.json (run \`lunora link\` to change)`)}catch{}},vs=async(e,r)=>{const t=new cr({skipAddingFilesFromTsConfig:!0}),n=$(r,"lunora");let o;try{o=qr(t,n)}catch(s){const a=s instanceof Error?s.message:String(s);return e.logger.warn(`--migrate: could not discover migrations (${a}); 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 s of o){e.logger.info(`--migrate: up "${s.id}" (table "${s.table}")`);const a={cwd:r,fetchImpl:e.fetchImpl,id:s.id,logger:e.logger,prod:!0,subcommand:"up",token:e.migrateToken,url:e.migrateUrl,yes:e.migrateYes===!0},i=await nn(a);if(i.code!==0)return e.logger.error(`--migrate: migration "${s.id}" failed — see output above`),i.code;e.logger.success(`--migrate: "${s.id}" applied`)}return 0},ps=async(e,r)=>{const{info:t}=we(r,"lunora",e.discoveryCache),n=t?.vectorMetadata??[];if(n.length===0)return;const o=[];for(const i of n){const c=Lt(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 a=(await Mt({cwd:r,entries:o,exec:$e(j(r),"wrangler",[]),logger:e.logger,spawner:e.spawner??x})).filter(i=>i.status!=="failed").length;a>0&&e.logger.success(`vectorize metadata indexes ready: ${String(a)}/${String(o.length)}`)},ze=5,ys=2e3,ws=async(e,r,t)=>{if(e.healthCheck!==!0)return;const n=t??Se({cwd:r,env:e.env});if(n===void 0){const s="--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(s),{error:s,ok:!1,url:""}}const o=await Yt({attempts:ze,baseUrl:n,delayMs:ys,fetchImpl:e.healthFetch,paths:[Xt,Qt],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(ze)} attempt(s) — ${o.error}`),{error:o.error,ok:!1,url:o.url})},ks=async(e,r,t,n,o,s)=>{e.isolatedPreview!==!0&&await ps(e,r);const a=e.migrate?await vs(e,r):0;return a===0&&o?.(),{code:a,descriptor:t,mintedSecretsFile:s,validation:n}},bs=async({cwd:e,descriptor:r,mintedSecretsFile:t,options:n,reblessSchemaBaseline:o,recordArchitecture:s,stdout:a,validation:i})=>{const c={deployedAt:new Date().toISOString(),dryRun:n.dryRun===!0,env:n.env,url:n.dryRun===!0?void 0:hs(a),workerName:be(e)};if(n.dryRun===!0)return n.healthCheck===!0&&n.logger.warn("--health-check skipped: a dry run publishes nothing"),{code:0,deployment:c,descriptor:r,mintedSecretsFile:t,validation:i};n.temporary!==!0&&n.isolatedPreview!==!0&&(s?.(),ms({cwd:e,env:n.env,logger:n.logger,url:c.url}));const l=await ws(n,e,c.url);if(l?.error!==void 0)return{code:w.UNAVAILABLE,deployment:c,descriptor:r,healthCheck:l,mintedSecretsFile:t,validation:i};const d=n.isolatedPreview===!0?void 0:o;return{...await ks(n,e,r,i,d,t),deployment:c,healthCheck:l}},$s=(e,r,t)=>{const n=$(e,C);if(!b(n))return;let o;try{o=er(E(n,"utf8")).length}catch{return}if(o===0)return;const s=t.toolchain?.secretPut!==void 0;r.warn(s?`Note: \`lunora deploy\` does not push secrets. ${C} 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. ${C} 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.`)},Or=async(e,r)=>{let t=[];try{t=st(await rr({cache:r,projectRoot:e,schemaDir:I(e)}))}catch{}const n=[...new Set(at(t).map(s=>s.key))];let o=[];try{const s=$(e,C);b(s)&&(o=er(E(s,"utf8")).map(a=>a.key).filter(a=>sr(a)))}catch{}return{fromLocal:o.filter(s=>!n.includes(s)),fromPackages:n,mintableKeys:it(t)}},Ss=async(e,r,t,n)=>{const{logger:o}=r,s=r.spawner??x,a=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 l=t.map(u=>({key:u,value:ct()})),d=n.toolchain?.secretBulk;if(d!==void 0&&l.length>=2){const u=H(a,d({environment:r.env,temporary:r.temporary})),h=await s({args:u.args,command:u.command,cwd:e,input:JSON.stringify(Object.fromEntries(l.map(g=>[g.key,g.value])))});if(h.code===0){for(const{key:g}of l)o.success(`generated + pushed ${g}`);return{minted:l,ok:!0}}o.warn(`bulk secret push failed (exit ${String(h.code)}); retrying one key at a time`)}const f=[];for(const{key:u,value:h}of l){const g=c({environment:r.env,key:u,temporary:r.temporary}),v=H(a,g),m=await s({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:f,ok:!1};f.push({key:u,value:h}),o.success(`generated + pushed ${u}`)}return{minted:f,ok:!0}},Es=/^[\w-]+$/u,Je=[".dev.vars",".dev.vars.*","!.dev.vars.example"],As=(e,r)=>{try{const t=ft(e,Je);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 \`${Je.join("` and `")}\` by hand before committing.`)}},Rs=(e,r,t)=>{if(t.length===0)return;const n=t.map(i=>i.key).join(", ");if(r.env!==void 0&&!Es.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?C:`${C}.${r.env}`;As(e,r.logger);const s=$(e,o);let a=b(s)?E(s,"utf8"):"";for(const i of t)a=dt(a,i.key,i.value);return lt(s,a),r.logger.success(r.env===void 0?`${n}: value(s) recorded in ${o}`:`${n}: value(s) recorded in ${o} (kept separate from ${C} so \`lunora dev\` and a plain \`lunora env push\` don't inherit the --env ${r.env} value)`),o},Ts=/^<[^>]+>$/u,Ps=async(e,r,t)=>{let n;try{n=t.projectConfig?.(e,"deploy").vars??{}}catch(d){return{error:d instanceof Error?d.message:String(d)}}const o=d=>{const f=n[d];if(typeof f!="string")return!0;const u=f.trim();return u===""||Ts.test(u)?!0:sr(d)&&ut(f)},s=d=>Object.hasOwn(n,d)?`${d} (empty or a placeholder)`:d,{fromLocal:a,fromPackages:i}=await Or(e,r.discoveryCache),c=a.filter(d=>o(d));c.length>0&&r.logger.warn(`${C} key(s) not set in the wrangler vars: ${c.map(d=>s(d)).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 l=i.filter(d=>o(d));return l.length===0?{}:{error:`missing required secret(s) in the wrangler vars: ${l.map(d=>s(d)).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.`}},_s=async(e,r,t,n)=>{if(r.dryRun===!0||r.isolatedPreview===!0)return{};if(n.toolchain?.secretList===void 0)return Ps(e,r,n);const{logger:o}=r,s=r.env===void 0?"":` --env ${r.env}`;let a;try{a=await(r.secretLister??sn)({cwd:e,env:r.env,target:n.id,temporary:r.temporary})}catch{return{}}if(!a.ok)return{};const i=new Set(a.names),{fromLocal:c,fromPackages:l,mintableKeys:d}=await Or(e,r.discoveryCache),f=[...l,...c].filter(g=>!i.has(g));if(f.length===0)return{};if(!t)return{error:`missing required secret(s) on the deploy target: ${f.join(", ")}. Set them with \`wrangler secret put <KEY>${s}\` (or \`lunora env generate --set\` then \`lunora env push --yes${s}\`), then re-deploy.`};for(const g of f.filter(v=>!d.has(v)))o.warn(`required secret ${g} is not set on the target — set it with: wrangler secret put ${g}${s}`);const u=f.filter(g=>d.has(g));if(u.length===0)return{};if(await(r.secretConfirm??on())(`${String(u.length)} required secret(s) not set on the target (${u.join(", ")}). Generate strong values and push them now?`)){const{minted:g,ok:v}=await Ss(e,r,u,n),m=Rs(e,r,g);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${s}\`.`),{}},Nr=e=>e.format==="json"?!1:e.interactive!==void 0?e.interactive:process.stdout.isTTY&&!process.env.CI,Ds=async(e,r)=>{if(r.dryRun===!0)return;const t=Ze(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 Un({cwd:e,logger:r.logger,railpackAvailable:r.railpackAvailable,spawner:r.spawner,targets:t});return n.code===0?void 0:n.error??"railpack build failed"},Cs=(e,r,t)=>{if(t!==void 0)try{const n=At(e,t);n.changed&&r.success(`synced ${String(t.length)} cron trigger(s) → ${n.wranglerPath??"wrangler.jsonc"}`);for(const s of n.warnings)r.warn(s);const o=Rt(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}`)}},Is=async(e,r,t,n,o,s)=>{try{ne(n);const a=await rr({cache:s,projectRoot:e,schemaDir:I(e)}),i=St(e,a,{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:l,path:d,updated:f}=i.devConfig;r.success(`dev sidecar bindings: ${[...l,...f].join(", ")} → ${d}`)}for(const l of i.warnings)r.warn(l)}catch(a){const i=a instanceof Error?a.message:String(a);r.warn(`binding inference skipped: ${i}`)}try{const a=Et(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}`)}Cs(e,r,t)},Os=async(e,r,t,n,o,s,a,i,c,l)=>{let d;r?(d=new Tt({name:"dots"}),d.start("running codegen")):t.info("running codegen");try{const f=Kr({apiSpec:n,dryRun:!l,lazyFunctions:o,projectRoot:e,target:s,...$t(e)});d?.succeed("codegen complete"),d||t.success("codegen complete");const u=It(f.platformDiagnostics,t);if(u.errors.length>0)return{error:u.errors.join("; ")};const{errorAdvisories:h,names:g,shouldBlock:v}=Ot(f.advisories,c);if(v){const T=`${h.length.toString()} ERROR-level ${h.length===1?"advisory":"advisories"} (${g.join(", ")}). Pass --no-strict-advisories to downgrade this to a warning and continue.`;return t.error(T),{error:T}}const m=l?await pt({cwd:e,logger:t,spawner:a,stdoutToStderr:i}):void 0;return m?.error!==void 0?{error:m.error}:{result:f}}catch(f){d?.failed("codegen failed");const u=f instanceof Error?f.message:String(f);return t.error(`codegen failed: ${u}`),{error:`codegen failed: ${u}`}}},Ye="--preview is not supported: Cloudflare gives a Worker that implements a Durable Object no version preview URL, and a version shares production's Durable Objects, D1 and R2. Deploy an isolated copy with `lunora preview deploy <name>` (its own Worker, Durable Object namespace, D1, R2 and KV; `lunora preview delete <name>` removes it), or validate without publishing with `--dry-run`.",Ns=(e,r)=>({dryRun:r.dryRun,entry:Re(e),environment:r.env,outDir:r.outDir,secretsFile:r.secretsFile,temporary:r.temporary}),jr=(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=Ns(e,r);return tr(t,e,"deploy",s=>n.deploy({...o,configPath:s}))},js=(e,r,t)=>{const n=jr(e,r,t),o=Re(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},A={problems:[],wranglerPath:void 0},ue=(e,r)=>({code:w.USAGE,descriptor:void 0,error:e,validation:A,...r}),Ls=(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},Ms=(e,r,t)=>{const n=r.format==="json",o=r.dryRun!==!0,s=js(e,r,t),a=H(j(e),s);return{args:a.args,captureStdout:o&&!n,captureStdoutSilently:o&&n,command:a.command,cwd:e,stdoutToStderr:n&&!o}},_e=e=>{if(e.skipServices===!0)return"--skip-services";if(e.isolatedPreview===!0)return"a preview never deploys services: they are production's Workers";if(e.temporary===!0)return"--temporary deploys the app to a throwaway account"},xs=(e,r)=>_e(r)===void 0?pe(e).services.map(t=>t.wranglerPath):[],Lr=(e,r,t,n,o)=>({cwd:e,environment:r.env,frameworkBuild:n,lazyFunctions:te(r.lazyFunctions),logger:r.logger,outputJson:r.format==="json"||r.clientBuildOutputJson===!0,spawner:o,strictAdvisories:ke(r),target:t.id}),Fs=(e,r,t)=>{const{toolchain:n}=t,o=n===void 0?`target "${t.id}" has no deploy command`:_e(r);if(o!==void 0||n===void 0){const s=e.map(a=>a.worker).join(", ");r.logger.warn(`services not deployed (${o??""}): ${s} — deploy them yourself if the app calls anything new`);return}return n},Mr=(e,r)=>{for(const t of e){const n=Ee(r(U(t.wranglerPath)));if(n!==void 0)return`service ${t.name} (${t.worker}): ${n}`}},Us=(e,r,t)=>{const{error:n,services:o}=pe(e);if(n!==void 0||o.length===0)return;const s=ne(t);if(s.toolchain===void 0||_e(r)!==void 0)return;const a=r.skipCodegen===!0?!1:r.frameworkBuild,i=[...new Map(o.map(c=>[c.wranglerPath,c])).values()];return Mr(i,c=>Lr(c,r,s,a,x))},xr=(e,r,t)=>{const n=e.cwd??process.cwd(),o=Ht(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:A}}if(e.preview===!0)return e.logger.error(Ye),{kind:"refused",code:w.USAGE,error:Ye,validation:A};try{jr(n,e,ne(o.target))}catch(i){if(!(t&&i instanceof gt&&ae(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:A}}}const s=e.openShardGatePassed===!0?void 0:Lo(n,e,r,xs(n,e));if(s!==void 0)return{kind:"refused",code:s.code,error:s.error,validation:A};const a=Us(n,e,o.target);return a!==void 0?(e.logger.error(a),{kind:"refused",code:w.USAGE,error:a,validation:A}):{kind:"ok",target:o.target}},Bs=(e,r)=>e.apiSpec??(e.clientBuildRan===!0?yt(r):void 0),Hs=async(e,r,t)=>{if(r!=="celld")return;const n=await(e.celldToolchain??vt)({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},Fr=(e,r)=>{const t=Se({cwd:e,env:r.env,url:r.migrateUrl}),n=t===void 0?void 0:ro(e,r.env,t);if(n!==void 0)return{reason:n};const o=t===void 0?void 0:Dt(t,r.logger,e),s=o===void 0?void 0:Pt({cwd:e,token:r.migrateToken,url:o}).token;return{target:o===void 0||!s?void 0:{baseUrl:o,fetchImpl:r.fetchImpl??Ct,token:s}}},Ws=(e,r,t)=>async n=>{const o=Fr(e,r);return"reason"in o?{kind:"inconclusive",reason:o.reason}:rn({changes:n,tables:t.schemaTables,target:o.target})},Gs=(e,r)=>async t=>{const n=Fr(e,r);return"reason"in n?n.reason:en({changes:t,now:Date.now(),target:n.target})},Vs=(e,r,t,n)=>e==="deploy"?{checkStoredRows:Ws(r,t,n),countExpiringRows:Gs(r,t)}:{},qs=async(e,r)=>{const t=e.cwd??process.cwd(),n=Nr(e),o=ke(e),s={problems:[],wranglerPath:void 0},a=xr(e,r,!1);if(a.kind==="refused")return{code:a.code,error:a.error,validation:a.validation};const{target:i}=a,c=await Hs(e,i,r);if(c!==void 0)return e.logger.error(c),{code:w.MISSING_DEPENDENCY,error:c,target:i,validation:s};let l;if(!e.skipCodegen){const v=await Os(t,n,e.logger,Bs(e,t),te(e.lazyFunctions),i,e.spawner,e.format==="json",o,e.clientBuildRan!==!0);if(v.error!==void 0)return{error:v.error,target:i,validation:A};l=v.result,e.discoveryCache?.clear()}let d;if(l!==void 0){const v=await Zt({allowDrift:e.allowSchemaDrift===!0,...Vs(r,t,e,l),codegen:l,command:r,logger:e.logger});if(v.blocked)return{error:`schema drift gate blocked ${r}`,schemaDrift:{blocked:!0,reason:v.reason},target:i,validation:s};d=v.rebless}const f=l&&gn({current:l.architecture,cwd:t,environment:e.env,logger:e.logger});await Is(t,e.logger,l?.cronTriggers,i,e.env,e.discoveryCache);const u=await Ir(t,e,r,i,"check");if(u!==void 0)return{error:u,target:i,validation:A};const h=Mo(t,e,r,i);if(h!==void 0)return{code:h.code,error:h.error,target:i,validation:A};const g=bt({environment:e.env,projectRoot:t});return Ls(g,e.logger)?{error:"wrangler validation failed",target:i,validation:g}:{codegen:l,reblessSchemaBaseline:d,recordArchitecture:f,target:i,validation:g}},Ks=e=>{Q(y(e,".wrangler","deploy","config.json"),{force:!0})},zs=async(e,r,t)=>{const n=Ee(e);if(n!==void 0)return{built:!1,error:n};const o=ae(e.cwd,r,t);return o&&Ks(e.cwd),{built:o,error:await br(e)}},Js=(e,r,t)=>r||t===!1?Cr(e):void 0,Ys=async(e,r,t,n)=>{const{error:o,services:s}=pe(e);if(o!==void 0)return{code:w.FAILURE,error:o};if(s.length===0)return;const a=Fs(s,r,t);if(a===void 0)return;const i=j(e),c=[...new Map(s.map(u=>[u.wranglerPath,u])).values()],l=r.skipCodegen===!0?!1:r.frameworkBuild,d=u=>Lr(u,r,t,l,n),f=Mr(c,d);if(f!==void 0)return r.logger.error(f),{code:w.USAGE,error:f};for(const u of c){const h=U(u.wranglerPath),g=d(h),{built:v,error:m}=await zs(g,l,r.env);if(m!==void 0){const S=`service ${u.name} (${u.worker}): ${m}`;return r.logger.error(S),{code:w.FAILURE,error:S}}const T=Js(u.wranglerPath,v,l);let L;try{L=tr(t,h,"deploy",S=>a.deploy({configPath:S??T??u.wranglerPath,dryRun:r.dryRun===!0,environment:r.env}))}catch(S){return{code:w.FAILURE,error:`service ${u.name} (${u.worker}): ${S instanceof Error?S.message:String(S)}`}}L.commit();const D=H(i,L.command);r.logger.info(`deploying service ${u.name} (${u.worker}) via ${D.command} ${D.args.join(" ")}`);const P=await n({args:D.args,command:D.command,cwd:h,stdoutToStderr:r.format==="json"});if(P.code!==0)return{code:w.FAILURE,error:`service ${u.name} (${u.worker}): ${D.command} ${D.args.join(" ")} exited ${String(P.code)} — stopping before the app`}}},Xs=async(e,r,t,n)=>{if(r!=="cloudflare")return;const o=e===void 0?void 0:R(e).parsed,s=(t===void 0?void 0:o?.env?.[t]?.account_id)??o?.account_id,a=await Ft({accountId:s});(a.verdict==="near"||a.verdict==="full")&&n.warn(a.fix===void 0?a.message:`${a.message} ${a.fix}`)},Qs=e=>e.dryRun!==!0&&e.temporary!==!0,Zs=e=>e.temporary===!0?"temporary":e.dryRun===!0?"preview":"defer",ea=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},ra=(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 s=ea(o);r.error(s),n.push(s)}return n},Ur=async(e,r,t,n,o,s,a)=>{const i=t==="cloudflare"&&r!==void 0?R(r).parsed:void 0;if(i===void 0)return;const c=(oe(i,n).merged.artifacts??[]).flatMap(g=>typeof g?.binding=="string"&&typeof g.namespace=="string"?[{binding:g.binding,namespace:g.namespace}]:[]),l=c.length===0?void 0:we(e,I(e),s).info?.jurisdiction;if(l===void 0)return;const d=[...new Map(c.map(g=>[g.namespace,g])).values()];if(a==="temporary"){o.warn(`--temporary deploys to a throwaway account, so the jurisdiction ("${l}") of Artifacts namespace ${d.map(g=>`"${g.namespace}"`).join(", ")} was not checked: it is created there on first use, in no jurisdiction.`);return}const f=(n===void 0?void 0:i.env?.[n]?.account_id)??i.account_id,u=await Promise.all(d.map(async g=>xt({...g,accountId:f,create:a==="create",jurisdiction:l,missingOk:a==="defer"||a==="preview"}))),h=ra(u,o,a);return h.length===0?void 0:h.join(`
|
|
43
|
+
`)},ta=async(e,r,t,n,o,s)=>{const a=Qs(r)?await Ur(e,s,o,r.env,r.logger,r.discoveryCache,"create"):void 0;if(a!==void 0)return{code:w.FAILURE,error:a};const i=await Ir(e,r,"deploy",o);return i!==void 0?{code:w.FAILURE,error:i}:Ys(e,r,t,n)},na=async(e,r,t,n)=>{if(!(r.smokeLoad===!1||t.toolchain===void 0))return xn({composedEntry:Re(e),configPath:n,cwd:e,environment:r.env,launcher:r.smokeLauncher,logger:r.logger,toolchain:t.toolchain})},oa=async e=>{const r={...e,discoveryCache:e.discoveryCache??mt()},t=r.cwd??process.cwd(),n=Nr(r),o=await qs(r,r.commandName??"deploy");if(o.error!==void 0){if(o.validation.problems.length>0)return{code:w.USAGE,descriptor:void 0,error:o.error,validation:o.validation};const m=o.schemaDrift===void 0?void 0:{schemaDrift:o.schemaDrift};return ue(o.error,{...m,...o.code===void 0?{}:{code:o.code}})}const{validation:s}=o,a=ne(o.target),i=vo(r)??await Ur(t,s.wranglerPath,o.target,r.env,r.logger,r.discoveryCache,Zs(r))??await na(t,r,a,s.wranglerPath);if(i!==void 0)return ue(i);const c=a.toolchain?.prebuildsContainerImages===!0?await Ds(t,r):void 0;if(c!==void 0)return ue(c);$s(t,r.logger,a),kt(t,m=>{r.logger.warn(m)}),await Xs(s.wranglerPath,o.target,r.env,r.logger);const{error:l,mintedSecretsFile:d}=await _s(t,r,n,a);if(l!==void 0)return r.logger.error(l),{code:w.USAGE,descriptor:void 0,error:l,mintedSecretsFile:d,validation:s};const f=r.spawner??x,u=await ta(t,r,a,f,o.target,s.wranglerPath);if(u!==void 0)return{code:u.code,descriptor:void 0,error:u.error,mintedSecretsFile:d,validation:s};const h=Ms(t,r,a);r.logger.info(`deploying via ${h.command} ${h.args.join(" ")}`);const g=await f(h);return h.captureStdoutSilently===!0&&g.stdout!==void 0&&g.stdout!==""&&process.stderr.write(g.stdout),g.code!==0?{code:g.code,descriptor:h,mintedSecretsFile:d,validation:s}:{...await bs({...o,cwd:t,descriptor:h,mintedSecretsFile:d,options:r,stdout:g.stdout}),logsAvailable:a.toolchain?.tail!==void 0}},sa=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:ke(e),lazyFunctions:te(e.lazyFunctions),logger:r,outputJson:e.format==="json"||e.clientBuildOutputJson===!0,spawner:e.spawner,target:e.target},o=Ee(n);if(o!==void 0)return r.error(o),{code:w.USAGE,descriptor:void 0,error:o,validation:A};ht(t);const s=await br(n);if(s!==void 0)return r.error(s),{code:w.FAILURE,descriptor:void 0,error:s,validation:A}},aa=(e,r)=>{const t=r.skipCodegen===!0?!1:r.frameworkBuild;return ae(e,t,r.env)?r.env:void 0},ia=async e=>{const{logger:r}=e,t=e.cwd??process.cwd(),n=xr(e,e.commandName??"deploy",!0);if(n.kind==="refused")return{code:n.code??w.USAGE,descriptor:void 0,error:n.error,validation:n.validation};const o=await sa(e);if(o!==void 0)return o;const s=e.dryRun===!0?yr(t):void 0;let a;try{if(a=await oa({...e,clientBuildEnvironment:aa(t,e),clientBuildRan:io(t,e.skipCodegen===!0?!1:e.frameworkBuild,e.env),logger:r,openShardGatePassed:!0}),a.code===0&&e.emitBindings!==void 0){const{error:i}=Ut({destination:e.emitBindings,logger:r,projectRoot:e.cwd??process.cwd()});i!==void 0&&(r.error(i),a={...a,code:w.USAGE})}}finally{s?.()}return e.format==="json"||a.code===0&&e.dryRun!==!0&&e.isolatedPreview!==!0&&hn({cwd:e.cwd??process.cwd(),env:e.env,logger:e.logger,logsAvailable:a.logsAvailable===!0,mintedSecretsFile:a.mintedSecretsFile,url:a.deployment?.url}),a},Ba=Bt(async({cwd:e,format:r,logger:t,options:n})=>{const o=Fn(e,n.root),s=await ia({allowOpenShards:n.allowOpenShards===!0,allowSchemaDrift:n.allowSchemaDrift===!0,apiSpec:Nt(n.apiSpec),frameworkBuild:n.prebuilt===!0?!1:n.frameworkBuild,lazyFunctions:te(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:Se({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});return{code:s.code,data:{deployment:s.deployment,healthCheck:s.healthCheck,mintedSecretsFile:s.mintedSecretsFile,schemaDrift:s.schemaDrift,validation:s.validation},error:s.error}});export{qs as a,Is as b,Uo as c,yr as d,Or as e,Ba as f,Fn as p,ia as r,na as s,to as v};
|
|
@@ -1 +1,3 @@
|
|
|
1
|
-
import{d as
|
|
1
|
+
import{existsSync as S}from"node:fs";import{mkdtemp as v,writeFile as k,rm as j}from"node:fs/promises";import{tmpdir as R}from"node:os";import{discoverSchema as C,schemaFromIr as T}from"@lunora/codegen";import{seedPlan as $}from"@lunora/seed";import{join as w}from"@visulima/path";import{Project as O}from"ts-morph";import{a as E}from"../packem_shared/shared-CV7ESvuj.mjs";import{t as y}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{d as A}from"../packem_shared/command-B6vu47iR.mjs";import{EXIT_CODE as u}from"../packem_shared/EXIT_CODE-DVjUgIaG.mjs";import{a as F}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{b as p}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{runResetCommand as N}from"./runResetCommand.mjs";import{r as U}from"../packem_shared/import-C-XRRHrZ.mjs";const x=(e,r)=>typeof r=="bigint"?Number(r):r instanceof ArrayBuffer?[...new Uint8Array(r)]:r,f=(e,r)=>({code:e,error:r,ndjson:""}),I=(e,r)=>{if(!S(r)){const o=`schema not found: ${r} — run \`vis generate lunora-table --name=<name>\` to create one`;return e.logger.error(o),f(u.NOT_FOUND,o)}if(e.reset===!0&&y({prod:e.prod,url:e.url})){const o="--reset only clears local .wrangler/state and cannot be combined with --prod or a remote --url";return e.logger.error(o),f(u.USAGE,o)}},z=async(e,r,o,t,n)=>{const s=await v(w(R(),"lunora-seed-")),d=w(s,"rows.ndjson");await k(d,e,"utf8");try{const a=await U({batchSize:n.batchSize,cwd:t,fetchImpl:n.fetchImpl,file:d,logger:n.logger,prod:n.prod,token:n.token,url:n.url,yes:!0}),i=a.body?.conflicts??0;return i>0&&n.logger.warn(`${String(i)} row(s) skipped — their _id already exists. Seeding is deterministic; re-run with --reset to wipe local state first, or a different --seed for fresh ids.`),{code:a.code,data:{conflicts:i,generated:r,inserted:a.inserted,tables:o},ndjson:e,...a.error===void 0?{}:{error:a.error}}}finally{await j(s,{force:!0,recursive:!0}).catch(()=>{})}},D=(e,r)=>{if(e.table===void 0||r.tables.some(n=>n.name===e.table))return;const o=r.tables.map(n=>n.name).join(", "),t=`unknown table "${e.table}" — schema defines: ${o||"(no tables)"}`;return e.logger.error(t),f(u.USAGE,t)},_=async(e,r)=>{if(!y({prod:e.prod,url:e.url})||e.yes===!0)return;if(!process.stdin.isTTY&&e.confirm===void 0){const s="seed: refusing to insert into a non-local target without confirmation — re-run with --yes";return e.logger.error(s),f(u.USAGE,s)}if(!await(e.confirm??p)(`This will insert ${String(r)} generated row(s) into ${e.url??"the production worker"}. Continue?`))return e.logger.info("seed: aborted"),f(u.CANCELLED,"seed: aborted at the confirmation prompt")},G=e=>{const r=[];for(const{rows:o,table:t}of e)for(const n of o)r.push(JSON.stringify({doc:n,table:t},x));return{lines:r,ndjson:r.length>0?`${r.join(`
|
|
2
|
+
`)}
|
|
3
|
+
${E(r.length)}`:""}},L=async e=>{const r=e.cwd??process.cwd(),o=e.format==="json",t=w(r,"lunora","schema.ts"),n=I(e,t);if(n!==void 0)return n;const s=new O({skipAddingFilesFromTsConfig:!0}),d=C(s,t),a=D(e,d);if(a!==void 0)return a;const i=T(d),l=$(i,{allowOrphans:e.allowOrphans===!0,defaultCount:e.count??10,now:e.now,only:e.table===void 0?void 0:[e.table],seed:e.seed??0}),{lines:h,ndjson:c}=G(l),m=h.length;if(e.dryRun===!0)return!o&&c.length>0&&process.stdout.write(c),e.logger.info(`generated ${String(m)} row(s) across ${String(l.length)} table(s) — dry run, nothing inserted`),{code:0,data:{conflicts:0,generated:m,inserted:0,rows:o?h.map(g=>JSON.parse(g)):void 0,tables:l.length},ndjson:c};if(m===0)return e.logger.warn("no rows generated — nothing to insert"),{code:0,data:{conflicts:0,generated:0,inserted:0,tables:l.length},ndjson:c};if(e.reset===!0){const g=await N({confirm:e.confirm,cwd:r,logger:e.logger,yes:e.yes});if(g.code!==0)return{code:g.code,error:"seed: --reset could not clear local state",ndjson:c}}const b=await _(e,m);return b!==void 0?b:z(c,m,l.length,r,e)},te=A(async({cwd:e,format:r,logger:o,options:t})=>{const n=await L({allowOrphans:t.allowOrphans===!0,batchSize:t.batchSize,count:t.count,cwd:e,dryRun:t.dryRun===!0,format:r,logger:o,prod:t.prod===!0,reset:t.reset===!0,now:t.now,seed:t.seed,table:t.table,token:t.token,url:F({cwd:e,prod:t.prod===!0,url:t.url}),yes:t.yes===!0});return{code:n.code,data:n.data,error:n.error}});export{te as execute,L as runSeedCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{d as l}from"../packem_shared/command-B6vu47iR.mjs";import{EXIT_CODE as n}from"../packem_shared/EXIT_CODE-DVjUgIaG.mjs";import{r as s,b as t,a as o}from"../packem_shared/commands-DC3ZX1yk.mjs";const y=l(({argument:a,cwd:u,format:m,logger:e,options:r})=>{const f=a[0],c=a.slice(1);if(f==="add")return s({allowUnsafeSource:r.allowUnsafeSource===!0,cwd:u,diff:r.diff===!0,dryRun:r.dryRun===!0,format:m,from:r.from,logger:e,names:c,overwrite:r.overwrite===!0,ref:r.ref,source:r.source,yes:r.yes===!0});if(f==="list")return s({allowUnsafeSource:r.allowUnsafeSource===!0,cwd:u,format:m,from:r.from,list:!0,logger:e,names:[],ref:r.ref,source:r.source});if(f==="view")return t({allowUnsafeSource:r.allowUnsafeSource===!0,cwd:u,from:r.from,logger:e,names:c,ref:r.ref,source:r.source});if(f==="build")return o({check:r.check===!0,cwd:u,from:r.from,logger:e,names:[],out:r.out});const d="registry: unknown subcommand. Usage: lunora registry <add|list|view|build> [names…]";return e.error(d),{code:n.USAGE,error:d}});export{y as execute};
|
|
@@ -1,3 +1 @@
|
|
|
1
|
-
import{existsSync as
|
|
2
|
-
`)}
|
|
3
|
-
${E(r.length)}`:""}},L=async e=>{const r=e.cwd??process.cwd(),o=e.format==="json",t=w(r,"lunora","schema.ts"),n=I(e,t);if(n!==void 0)return n;const s=new O({skipAddingFilesFromTsConfig:!0}),d=C(s,t),a=D(e,d);if(a!==void 0)return a;const i=T(d),l=$(i,{allowOrphans:e.allowOrphans===!0,defaultCount:e.count??10,now:e.now,only:e.table===void 0?void 0:[e.table],seed:e.seed??0}),{lines:h,ndjson:c}=G(l),m=h.length;if(e.dryRun===!0)return!o&&c.length>0&&process.stdout.write(c),e.logger.info(`generated ${String(m)} row(s) across ${String(l.length)} table(s) — dry run, nothing inserted`),{code:0,data:{conflicts:0,generated:m,inserted:0,rows:o?h.map(g=>JSON.parse(g)):void 0,tables:l.length},ndjson:c};if(m===0)return e.logger.warn("no rows generated — nothing to insert"),{code:0,data:{conflicts:0,generated:0,inserted:0,tables:l.length},ndjson:c};if(e.reset===!0){const g=await N({confirm:e.confirm,cwd:r,logger:e.logger,yes:e.yes});if(g.code!==0)return{code:g.code,error:"seed: --reset could not clear local state",ndjson:c}}const b=await _(e,m);return b!==void 0?b:z(c,m,l.length,r,e)},te=A(async({cwd:e,format:r,logger:o,options:t})=>{const n=await L({allowOrphans:t.allowOrphans===!0,batchSize:t.batchSize,count:t.count,cwd:e,dryRun:t.dryRun===!0,format:r,logger:o,prod:t.prod===!0,reset:t.reset===!0,now:t.now,seed:t.seed,table:t.table,token:t.token,url:F({cwd:e,prod:t.prod===!0,url:t.url}),yes:t.yes===!0});return{code:n.code,data:n.data,error:n.error}});export{te as execute,L as runSeedCommand};
|
|
1
|
+
import{existsSync as u,readdirSync as d,statSync as g,mkdirSync as h,writeFileSync as w,readFileSync as y}from"node:fs";import{fileURLToPath as v}from"node:url";import{AGENT_RULES_DIR as a,detectAgentRules as R,LUNORA_SKILL_NAMES as L}from"@lunora/config";import{join as i,relative as A,resolve as E,dirname as m}from"@visulima/path";import{f as I}from"../packem_shared/cli-manifest-DoQ_3bzs.mjs";import{d as $}from"../packem_shared/command-B6vu47iR.mjs";import{EXIT_CODE as _}from"../packem_shared/EXIT_CODE-DVjUgIaG.mjs";const b=(e=m(v(import.meta.url)))=>{const r=I(e),t=r===void 0?void 0:i(r,"skills");return t!==void 0&&u(t)?t:void 0},j=e=>d(e).filter(r=>{const t=i(e,r);return g(t).isDirectory()&&u(i(t,"SKILL.md"))}),f=(e,r,t)=>{h(r,{recursive:!0});let n=!1;for(const o of d(e)){const l=i(e,o),s=i(r,o);if(g(l).isDirectory()){n=f(l,s,t)||n;continue}u(s)&&!t||(w(s,y(l)),n=!0)}return n},D=["pnpm-workspace.yaml","pnpm-lock.yaml","yarn.lock","package-lock.json","bun.lock","bun.lockb",".git"],O=e=>{let r=e;for(;;){if(D.some(n=>u(i(r,n))))return r;const t=m(r);if(t===r)return e;r=t}},k=(e,r)=>r===void 0?O(e):E(e,r),U=e=>{const r=e.cwd??process.cwd(),t=k(r,e.dir),n=e.overwrite===!0,o=b();if(o===void 0)return e.logger.error("rules: could not locate the bundled skills (is @lunora/cli installed correctly?)."),{code:1,installed:[],skipped:[]};const l=[],s=[];for(const c of j(o)){const S=i(t,a,c);f(i(o,c),S,n)?l.push(c):s.push(c)}const p=A(r,i(t,a))||a;return l.length>0&&e.logger.success(`Installed ${String(l.length)} Lunora skill(s) into ${p}/: ${l.join(", ")}.`),s.length>0&&e.logger.info(`Skipped ${String(s.length)} existing skill(s) (re-run with --overwrite to replace): ${s.join(", ")}.`),e.logger.info("Your AI coding agent will pick these up automatically. Start with the `lunora` skill."),{code:0,installed:l,skipped:s}},x=e=>{const r=e.cwd??process.cwd(),t=k(r,e.dir),n=R(t);return n.installed?(e.logger.success(`Lunora agent rules are installed (${String(n.present.length)}/${String(L.length)} skills).`),n.missing.length>0&&e.logger.info(`Missing: ${n.missing.join(", ")}. Run \`lunora rules install\` to add them.`),{code:0,installed:n.present,skipped:[]}):(e.logger.warn("Lunora agent rules are not installed. Run `lunora rules install` so your AI agent knows how to use Lunora."),{code:e.strict===!0?1:0,installed:n.present,skipped:[]})},G=$(({argument:e,cwd:r,logger:t,options:n})=>{const o=e[0]??"check";return o==="install"?U({cwd:r,dir:n.dir,logger:t,overwrite:n.overwrite===!0}):o==="check"?x({cwd:r,dir:n.dir,logger:t,strict:n.strict===!0}):(t.error("rules: unknown subcommand. Usage: lunora rules <install|check>"),{code:_.USAGE})});export{G as execute,j as listBundledSkills,b as resolveBundledSkillsDirectory,x as runRulesCheck,U as runRulesInstall};
|