@lunora/cli 1.0.0-alpha.461 → 1.0.0-alpha.463
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/index.d.mts +76 -55
- package/dist/index.d.ts +76 -55
- package/dist/index.mjs +1 -1
- package/dist/packem_chunks/cli.mjs +2 -2
- package/dist/packem_chunks/dispatch.mjs +1 -1
- package/dist/packem_chunks/handler.mjs +35 -11
- package/dist/packem_chunks/handler12.mjs +1 -1
- package/dist/packem_chunks/handler15.mjs +2 -2
- package/dist/packem_chunks/handler17.mjs +1 -1
- package/dist/packem_chunks/handler24.mjs +3 -3
- package/dist/packem_chunks/handler6.mjs +1 -1
- package/dist/packem_chunks/handler7.mjs +1 -1
- package/dist/packem_chunks/runInitCommand.mjs +87 -63
- package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-CyOfZWMk.mjs +1 -0
- package/dist/packem_shared/export-rows-EzdNDYpa.mjs +3 -0
- package/dist/packem_shared/health-probe-BLnoq_oC.mjs +13 -0
- package/dist/packem_shared/import-C-XRRHrZ.mjs +13 -0
- package/dist/packem_shared/runDeployCommand-2tEbutD6.mjs +1 -0
- package/dist/packem_shared/runExportCommand-Dy6pSX68.mjs +5 -0
- package/dist/packem_shared/{runMigrateGenerateCommand-Bd2W9t1k.mjs → runMigrateGenerateCommand-CFy3hXXu.mjs} +3 -3
- package/dist/packem_shared/shared-CV7ESvuj.mjs +2 -0
- package/package.json +9 -8
- package/skills/lunora-deploy/SKILL.md +18 -17
- package/skills/lunora-migration-helper/SKILL.md +25 -11
- package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-5xxKz-zB.mjs +0 -1
- package/dist/packem_shared/health-probe-Bw9JFfIy.mjs +0 -1
- package/dist/packem_shared/import-DoAUdyfU.mjs +0 -13
- package/dist/packem_shared/runDeployCommand-Tgy9tGRV.mjs +0 -1
- package/dist/packem_shared/runExportCommand-DiMCQ-Il.mjs +0 -5
- package/dist/packem_shared/shared-D-zCOmgY.mjs +0 -1
|
@@ -1,19 +1,43 @@
|
|
|
1
|
-
import{mkdirSync as
|
|
1
|
+
import{mkdirSync as Qe,writeFileSync as V,existsSync as b,readFileSync as E,rmSync as Q,readdirSync as ve,mkdtempSync as Wr,realpathSync as Gr,statSync as Ze}from"node:fs";import{dirname as U,join as y,resolve as j,relative as F,sep as B,extname as Vr}from"node:path";import{PROJECT_CONFIG_FILENAMES as qr,isTestPath as ge,discoverMigrations as Kr,readServiceBindings as pe,runCodegen as zr}from"@lunora/codegen";import{readLinkedProject as ye,resolveSchemaDirectory as I,startDevProcess as Jr,acceptsConnection as Yr,resolveTargetOrThrow as fe,detectFramework as Xr,DEFAULT_BUNDLE_META_PATH as Qr,STRICT_ADVISORIES_ENV as Zr,LAZY_FUNCTIONS_ENV as et,BUNDLE_META_PATH_ENV as rt,BUILD_TARGET_ENV as tt,BUILD_ROOT_ENV as nt,canonicalPath as ot,COMPOSED_WORKER_ENTRY as Ce,discoverContainerInfo as er,D1_PLACEHOLDER_ID as Ie,discoverSchemaInfo as we,writeLinkedProject as st,DEV_VARS_FILE as C,parseDevVariableEntries as rr,secretSourcesFromBindings as at,inferLunoraBindings as tr,requiredSecrets as it,mintableSecretKeysFor as ct,generateSecretValue as dt,upsertDevVariableLine as lt,writeDevVariablesFileAtomically as ut,isPlaceholderValue as gt,ensureGitignoreEntries as ft,resolveLazyFunctions as te,resolveDeployDriver as ne,MissingBuildOutputError as ht,clearApiSpecMarker as mt,createDiscoveryCache as vt,planToolchainInvocation as nr,probeCelldToolchain as pt,runPostCodegenHook as yt,readApiSpecMarker as wt}from"@lunora/config";import{bindingsNeedingDatabase as kt,findWranglerFile as O,readWranglerJsonc as R,mergeWranglerEnvironment as oe,HYPERDRIVE_PLACEHOLDER_ID as or,applyModify as sr,warnCloudflareCliConfigOnce as bt,validateWranglerProject as $t,wranglerCodegenInputs as St,reconcileWranglerBindings as Et,reconcileWranglerCompatibilityDate as At,reconcileWranglerCrons as Rt,describePreservedCrons as Tt}from"@lunora/config/cloudflare";import{Spinner as Pt}from"@visulima/spinner";import{r as _t}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{n as Dt,r as Ct,a as It}from"../packem_shared/admin-url-DJB8P6Jh.mjs";import{r as ke,a as Ot,e as jt}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as Nt}from"../packem_shared/api-spec-lYyq4vL6.mjs";import{e as Lt,m as Mt,g as xt,i as ar,d as Ft,b as Ut}from"../packem_shared/vectorize-metadata-BVSF8z2h.mjs";import{w as Bt}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{d as Ht}from"../packem_shared/command-B6vu47iR.mjs";import{r as be}from"../packem_shared/wrangler-name-Dsk5K1f-.mjs";import{a as Wt}from"../packem_shared/deploy-target-resolve-BTCW1Iv4.mjs";import{EXIT_CODE as w}from"../packem_shared/EXIT_CODE-DVjUgIaG.mjs";import{spawn as Gt}from"node:child_process";import{randomUUID as ir,createHash as Vt}from"node:crypto";import{setTimeout as qt}from"node:timers/promises";import{toolchainExecArgs as H,detectPackageManager as N,execArgsFor as $e}from"@lunora/config/cli";import{f as Kt}from"../packem_shared/free-port-DjbFhaaT.mjs";import{containerBuildTag as zt}from"@lunora/container";import{a as Jt,i as Yt}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 Xt,H as Qt,a as Zt,r as en,c as rn,b as tn}from"../packem_shared/health-probe-BLnoq_oC.mjs";import{runAdvisor as nn,openShardAccess as Oe}from"@lunora/advisor";import{join as $,relative as W,dirname as cr}from"@visulima/path";import{Project as dr,SyntaxKind as p,Node as k}from"ts-morph";import{r as lr,c as ur}from"../packem_shared/cloudflare-credentials-BVmZnDZk.mjs";import{runMigrateDataCommand as on}from"../packem_shared/runMigrateGenerateCommand-CFy3hXXu.mjs";import{c as sn}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{l as an}from"../packem_shared/wrangler-secrets-DlSlWvRH.mjs";const cn=Object.freeze({edges:[],nodes:[],modules:[],unresolved:[],version:1}),dn=20,je=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))},ln=(e,r)=>{const t=e.modules.map(a=>a.name),n=r.modules.map(a=>a.name),o=e.edges.map(a=>je(a)),s=r.edges.map(a=>je(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,dn).map(s=>` ${e} ${s}`),o=t.length-n.length;return[`${r}:`,...n,...o>0?[` … and ${o.toString()} more`]:[]]},un=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
|
+
`)}`},gn=(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}},hn=e=>{const{cwd:r,environment:t,logger:n}=e,o=gn(r,t),s=fn(o),a=e.current??(s===void 0?void 0:cn);if(a===void 0)return;const i=s===void 0?void 0:un(ln(s,a));return i!==void 0&&n.info(i),()=>{try{Qe(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)}`)}}},mn=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{}},vn=/\/index$/u,pn=/[^\dA-Za-z]/gu,yn=e=>e.replace(vn,"").split("/").map(r=>r.replaceAll(pn,"_")),wn=e=>yn(e).join("_"),kn=18787,Ne=3,gr=12e4,bn=5e3,ce=10,fr=new Set([".js",".mjs",".mts",".ts",".tsx"]),$n=/\(void 0\)|is not a function|before initialization|of undefined/u,Sn=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",En=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=Vr(o);fr.has(s)&&!o.split(B).some(a=>a==="_generated"||a==="node_modules")&&t.set(wn(o.slice(0,-s.length).split(B).join("/")),y(r,o))}return t},Le=e=>$n.test(e)?`
|
|
5
|
+
hint: if this module is part of a circular import, an import it reads is still undefined while it evaluates`:"",An=(e,r)=>{const t=En(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}`,g=n.get(d)??{exports:[],message:i,namespace:l};g.exports.push(a.slice(c+1)),n.set(d,g)}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},Rn=(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},Tn=/\.[cm]?js$/u,Pn=/(?:await|=>|return|[=[,])\s*import\(\s*"([^"]+)"\s*\)(?!\s*\.(?!(?:then|catch|finally)\b))/gu,_n=(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(Pn)){const l=c[1]??"",d=l.startsWith("."),g=d?Y(j(n,l.replace(Tn,""))):l;g!==void 0&&!o.has(g)&&(o.add(g),s.push({file:g,kind:"module",label:d?F(e,g).split(B).join("/"):l}))}return s};class _ extends Error{skipped;constructor(r,t=!1){super(r),this.skipped=t}}const Dn=(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}},Cn=({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}=Dn(t,n),i=e??a;if(typeof i!="string"||i.startsWith("virtual:")||!b(j(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=kt(t,process.env,n,r);return c.length===0?{main:i}:{skip:`the Hyperdrive binding ${c.join(", ")} has no local database for wrangler dev`}},In=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(gr/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=>Sn(u)))return l===r?{checked:a,deferredChecked:i,failures:c}:void 0;const d=n.headers.get("content-type")??"no content type",g=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}${g===""?"":`: ${g}`}). 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}},On=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()+bn;for(;Me(r)&&Date.now()<t;)await qt(50);Me(r)&&he(r,"SIGKILL")},jn=e=>Jr(e).catch(async r=>{if(!await Yr(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=An(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
|
+
`))},Ln=(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},
|
|
9
|
-
import { loadAllFunctions } from ${JSON.stringify(a)};
|
|
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},Mn=e=>{try{return Qe(y(e,".lunora"),{recursive:!0}),Wr(y(e,".lunora","smoke-"))}catch(r){throw new _(`could not create a directory for the check (${r instanceof Error?r.message:String(r)})`,!0)}},xn=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"),g=ir();V(d,`export * from ${JSON.stringify(j(t,i))};
|
|
9
|
+
${a===void 0?"":`import { loadAllFunctions } from ${JSON.stringify(a)};
|
|
10
|
+
`}
|
|
11
|
+
const runId = ${JSON.stringify(g)};
|
|
10
12
|
|
|
11
|
-
|
|
13
|
+
// Deferred event modules, evaluated here so a module that throws on import blocks like a function module does.
|
|
14
|
+
const deferred = [
|
|
15
|
+
${n.map(v=>` { kind: ${JSON.stringify(v.kind)}, label: ${JSON.stringify(v.label)}, load: () => import(${JSON.stringify(v.file)}) },`).join(`
|
|
16
|
+
`)}
|
|
17
|
+
];
|
|
12
18
|
|
|
13
19
|
export default {
|
|
14
20
|
async fetch() {
|
|
15
|
-
|
|
21
|
+
const functions = ${a===void 0?"{ checked: 0, failures: [] }":"await loadAllFunctions()"};
|
|
22
|
+
const loaded = await Promise.all(
|
|
23
|
+
deferred.map(async ({ kind, label, load }) => {
|
|
24
|
+
try {
|
|
25
|
+
await load();
|
|
26
|
+
|
|
27
|
+
return undefined;
|
|
28
|
+
} catch (error) {
|
|
29
|
+
return { deferred: kind, functionPath: kind + ":" + label, message: error instanceof Error ? error.message : String(error) };
|
|
30
|
+
}
|
|
31
|
+
}),
|
|
32
|
+
);
|
|
33
|
+
|
|
34
|
+
return Response.json({
|
|
35
|
+
checked: functions.checked,
|
|
36
|
+
deferredChecked: deferred.length,
|
|
37
|
+
failures: [...functions.failures, ...loaded.filter((failure) => failure !== undefined)],
|
|
38
|
+
run: runId,
|
|
39
|
+
});
|
|
16
40
|
},
|
|
17
41
|
};
|
|
18
|
-
`);const g=await Et(i),{args:u,command:h}=F(j(t),c.dev({configPath:r===void 0?void 0:ee(t,r),environment:o,extraArgs:[ee(t,d),"--local","--local-protocol","http","--ip","127.0.0.1","--port",String(g),"--persist-to",ee(t,k(n,"state"))]}));return{args:u,command:h,port:g,runId:l}}catch(d){throw new _(`could not prepare the check (${d instanceof Error?d.message:String(d)})`,!0)}},un=async e=>{const{configPath:r,cwd:t,environment:n,launcher:o,logger:a,toolchain:s}=e,i=k(t,N(t),"_generated","functions.ts");if(!S(i)||!A(i,"utf8").includes("export const loadAllFunctions"))return;const c=tn(e);if("skip"in c){a.warn(`smoke-load skipped: ${c.skip}, so lazy modules are not evaluated before deploy`);return}const{main:d}=c,l=[];let g,u;const h=Date.now()+rr,f=process.platform!=="win32",v=(m,E,C)=>{const $=bt(m,[...E],{cwd:C.cwd,detached:f,shell:C.shell,stdio:["ignore","pipe","pipe"]});return f&&$.pid!==void 0&&(u={dispose:on($.pid),pid:$.pid}),$};try{g=dn(t),a.info("smoke-loading lazy function modules in workerd");let m=zt;for(let E=0;E<Te;E+=1){const{args:C,command:$,port:I,runId:T}=await ln({configPath:r,cwd:t,directory:g,environment:n,functionsFile:i,main:d,preferred:m,toolchain:s});m=I+1;const be=await an({args:C,command:$,cwd:t,spawn:o??v,label:"wrangler dev (smoke-load)",notFound:"`wrangler` was not found",onLine:G=>{l.push(G)},port:I,readyTimeoutMs:Math.max(0,h-Date.now()),shell:process.platform==="win32"});if(be===void 0){await te(u),u=void 0;continue}try{const G=await nn(I,T,h);if(G!==void 0){sn(t,G,a);return}}finally{await be.stop(),await te(u),u=void 0}}throw new _(`the smoke port was answered by other runs on all ${String(Te)} attempts`,!0)}catch(m){return cn(m,l,a)}finally{if(await te(u),g!==void 0)try{W(g,{force:!0,recursive:!0})}catch{}}},gn=(e,r)=>r===void 0?e:L(e,r),fn=async e=>{if(e.targets.length===0)return{builtTags:[],code:0};if(!(e.railpackAvailable??Tt)()){const n="deploy blocked: a container uses `image: { build }` (Railpack), but Railpack isn't ready. Install the `railpack` CLI and start a BuildKit instance, e.g. `docker run --rm --privileged -d --name buildkit moby/buildkit` then `export BUILDKIT_HOST=docker-container://buildkit`. Alternatively switch the container's `image` to a Dockerfile path or a pre-built registry reference.";return e.logger.error(n),{builtTags:[],code:1,error:n}}const r=e.spawner??x,t=[];for(const n of e.targets){const o=At(n.exportName),a={args:["build",n.buildDir,"--name",o],command:"railpack",cwd:e.cwd},s=he(j(e.cwd),"wrangler",["containers","push",o]),i={args:s.args,command:s.command,cwd:e.cwd};e.logger.info(`railpack: building "${n.exportName}" → ${o} from ${n.buildDir}`);const c=await r(a);if(c.code!==0){const l=`railpack build failed for container "${n.exportName}" (${n.buildDir})`;return e.logger.error(l),{builtTags:t,code:c.code,error:l}}e.logger.info(`railpack: pushing ${o} to the Cloudflare Registry`);const d=await r(i);if(d.code!==0){const l=`wrangler containers push failed for "${n.exportName}" (${o})`;return e.logger.error(l),{builtTags:t,code:d.code,error:l}}t.push(o)}return{builtTags:t,code:0}},tr=e=>{const t=[O(e),k(e,"package.json"),k(e,"wrangler.dev.jsonc")].filter(n=>n!==void 0&&S(n)).map(n=>[n,A(n,"utf8")]);return()=>{for(const[n,o]of t)A(n,"utf8")!==o&&H(n,o,"utf8")}},hn=(e,r=Je())=>L(e,".lunora",`vite-bundle-meta-${r}.json`),nr="LUNORA_CLIENT_BUILD",mn="virtual:lunora/worker",de=(e,r)=>["ts","mts","cts","js","mjs","cjs"].some(t=>S(k(e,`${r}.config.${t}`))),or=e=>de(e,"rsbuild")?"rsbuild":de(e,"vite")?"vite":void 0,vn=e=>de(e,"vite")?"vite":or(e),pn=e=>{try{const{scripts:r}=JSON.parse(A(k(e,"package.json"),"utf8"));return typeof r?.build=="string"&&r.build!==""}catch{return!1}},Q=(e,r)=>{if(process.env[nr]==="1")return;const t=O(e),n=t===void 0?void 0:D(t).parsed,o=n?.main===mn,a=(o?vn(e):or(e))??(pn(e)?"script":void 0);if(a===void 0)return;const s=r===void 0?void 0:n?.env?.[r]?.assets?.directory,i=n?.assets?.directory??s;return o||Nr(e).class!=="C"||i!==void 0?a:void 0},yn=async(e,r,t)=>{const n=t.spawner??x,o=j(e),a=r==="script"?{args:["run","build"],command:o}:he(o,r,["build"]);t.logger.info(`running ${r} build before bundling the Worker`);const s=tr(e),i=t.bundleMetaPath??hn(e);W(k(e,Or),{force:!0});try{const c=await n({args:a.args,command:a.command,cwd:e,env:{[Mr]:Fr(e),[xr]:t.target,[Lr]:i,...t.lazyFunctions?{[Ir]:"1"}:{},...t.environment===void 0?{}:{CLOUDFLARE_ENV:t.environment},...t.strictAdvisories===!1?{[jr]:"0"}:{},[nr]:"1"},stdoutToStderr:t.outputJson});return c.code===0?void 0:`${r} build failed with exit code ${String(c.code)}`}finally{s(),t.bundleMetaPath===void 0&&W(i,{force:!0})}},Z=(e,r,t)=>r!==!1&&Q(e,t)!==void 0,wn=(e,r,t)=>Z(e,r,t)&&Q(e,t)!=="script",me=e=>{const r=e.frameworkBuild===!1?void 0:Q(e.cwd,e.environment);if(r===void 0||r==="script")return;if(e.apiSpec!==void 0)return`--api-spec is read from the ${r} plugin config when the client build runs; set it there, or pass --no-framework-build`;if(e.target!==void 0)try{ie(e.cwd,e.target)}catch(n){return n instanceof Error?n.message:String(n)}let t;try{t=ie(e.cwd)}catch(n){return`the project's configured target cannot be used, and the ${r} plugin reads it: ${n instanceof Error?n.message:String(n)}`}if(e.target!==void 0&&e.target!==t)return`this run targets "${e.target}", but the project's target is "${t}", which the ${r} plugin reads; set it in the project config, or pass --no-framework-build`},ar=async e=>{const r=e.frameworkBuild===!1?void 0:Q(e.cwd,e.environment);if(r===void 0)return;let t;try{t=e.target??ie(e.cwd)}catch(n){return n instanceof Error?n.message:String(n)}return yn(e.cwd,r,{bundleMetaPath:e.bundleMetaPath,environment:e.environment,strictAdvisories:e.strictAdvisories,lazyFunctions:e.lazyFunctions,logger:e.logger,outputJson:e.outputJson,spawner:e.spawner,target:t})},_e=e=>Array.isArray(e)?e.filter(r=>r!=null):void 0,ve=(e,r)=>{const t=O(e);if(!t)return;const{parsed:n}=D(t);if(n===void 0)return;const{error:o,merged:a}=X(n,r),s=o===void 0?a:n,{containers:i,d1_databases:c,vars:d}=s;return{containers:_e(i),d1_databases:_e(c),vars:typeof d=="object"&&d!==null&&!Array.isArray(d)?d:void 0}},kn=/^127(?:\.\d{1,3}){3}$/,bn=e=>{try{const{hostname:r}=new URL(e);return r==="localhost"||kn.test(r)||r==="::1"||r==="[::1]"}catch{return!1}},Sn=e=>e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.includes("Dockerfile"),$n=(e,r,t,n="deploy",o)=>{const a=(ve(e,o)?.containers??[]).filter(i=>typeof i?.image=="string"&&Sn(i.image));if(a.length===0||t())return;const s=`${n} blocked: wrangler.jsonc declares ${String(a.length)} container(s) built from a local Dockerfile, but no Docker-compatible engine is available. Start Docker (or Colima), or point the container's \`image\` at a pre-built registry reference. Note: container images must target linux/amd64.`;return r.error(s),s},pe=e=>S(b(e,Se))?Se:void 0,En=(e,r,t="deploy",n)=>{for(const o of He(e,"lunora",n).containers){const a=o.schedulingPolicy===void 0?o.image:void 0,i=[...a?.kind==="dockerfile"?[{field:"image",path:a.dockerfilePath}]:[],...Object.entries(o.schedulingPolicy==="durable_object"?o.images??{}:{}).flatMap(([c,d])=>d.kind==="dockerfile"?[{field:`images["${c}"]`,path:d.dockerfilePath}]:[])].find(c=>!S(b(e,c.path)));if(i!==void 0){const c=`${t} blocked: container "${o.exportName}" references a Dockerfile at "${i.path}" that does not exist. Create it or fix the \`${i.field}\` path in lunora/containers.ts.`;return r.error(c),c}if(a?.kind==="build"&&!S(b(e,a.buildDir))){const c=`${t} blocked: container "${o.exportName}" references a Railpack build directory "${a.buildDir}" that does not exist. Create it or fix the \`image.build\` path in lunora/containers.ts.`;return r.error(c),c}}},An=(e,r)=>r==="celld"?typeof e=="string"&&e!==$e&&ft(e):r==="cloudflare"&&e===$e,Tn=(e,r,t)=>(ve(e,t)?.d1_databases??[]).find(n=>An(n.database_id,r)),Rn=e=>{if(!e.migrate||e.dryRun||e.preview)return;if(e.migrateUrl===void 0){const t="--migrate requires --migrate-url <https://your-worker> — the deploy target URL is only known after wrangler runs, and this gate runs before it; refusing to default to localhost";return e.logger.error(t),t}if(e.migrateYes!==!0){const t="--migrate runs production data migrations after deploy. Re-run with --migrate-yes to confirm.";return e.logger.error(t),t}const r=e.migrateToken??process.env.LUNORA_ADMIN_TOKEN;if(r===void 0||r===""){const t="admin token required for --migrate — pass --migrate-token or set LUNORA_ADMIN_TOKEN";return e.logger.error(t),t}},_n=(e,r,t,n,o)=>{const a=Tn(e,n,o);if(a===void 0)return;const s=`${t} blocked: the "${a.binding??"<unnamed>"}" D1 binding has a placeholder database_id ("${a.database_id??""}")`,i=n==="celld"?`${s}, which celld would use as the database's identity. Set database_id to the database celld should use, then ${t} again.`:`${s}. Run \`lunora doctor --fix\` to create the database and write its id into wrangler.jsonc, or run \`wrangler d1 create <name>\` and paste the id in yourself.`;return r.error(i),i},Dn=(e,r,t="deploy",n)=>{const o=ve(e,n)?.vars;if(!o)return;const a=Object.entries(o).filter(([,i])=>typeof i=="string"&&bn(i)).map(([i])=>i).toSorted((i,c)=>i.localeCompare(c));if(a.length===0)return;const s=`${t} blocked: ${a.join(", ")} in wrangler.jsonc point at localhost. A deployed Worker can't reach a loopback address, so this silently breaks scheduled-job dispatch, reverse cross-shard relations, and auth callbacks. Set each to the deployed worker's public URL (or move it to a secret with \`wrangler secret put\`) before deploying.`;return r.error(s),s},Cn=["vite.config.ts","vite.config.mts","vite.config.cts","vite.config.js","vite.config.mjs","vite.config.cjs",...Rr],sr=/\.(?:[cm]?[jt]s|tsx|jsx)$/u,ir=/\.(?:test|spec)\.[cm]?[jt]sx?$/u,cr="allowUnauthenticatedShardAccess",Pn=/[\\/]/u,dr=new Set(["_generated","build","dist","node_modules"]),lr=(e,r)=>{const t=U(e,r).split(Pn);return sr.test(r)&&!ir.test(r)&&!se(t.join("/"))&&t.every(n=>n===".."||!n.startsWith(".")&&!dr.has(n))},De=(e,r,t)=>{const{parsed:n}=D(r);if(n===void 0)return[];const{error:o,merged:a}=X(n,t),{main:s}=o===void 0?a:n,i=typeof s=="string"?b(Xe(r),s):void 0;return i!==void 0&&S(i)&&lr(e,i)?[i]:[]},ye=e=>e===void 0?!1:e.getKind()===p.FalseKeyword?!0:w.isParenthesizedExpression(e)||w.isAsExpression(e)||w.isSatisfiesExpression(e)||w.isTypeAssertion(e)||w.isNonNullExpression(e)?ye(e.getExpression()):!1,Nn=e=>{try{return Ue(e).isFile()}catch{return!1}},On=new Set(["ELOOP","ENOENT","ENOTDIR"]),K=(e,r,t)=>{const n=r instanceof Error&&"code"in r&&typeof r.code=="string"?r.code:"";On.has(n)||t.push(e)},jn=(e,r)=>{try{return Ue(e)}catch(t){K(e,t,r);return}},ur=(e,r)=>{try{return A(e,"utf8")}catch(t){K(e,t,r);return}},gr=(e,r,t,n=new Set)=>{let o;try{o=Ar(r)}catch(s){return K(r,s,t),[]}if(n.has(o))return[];n.add(o);let a;try{a=Fe(r)}catch(s){return K(r,s,t),[]}return a.flatMap(s=>{const i=b(r,s),c=jn(i,t);if(c===void 0)return[];const d=U(e,i).split(ae).join("/");return c.isDirectory()?dr.has(s)||s.startsWith(".")||se(`${d}/`)?[]:gr(e,i,t,n):c.isFile()&&sr.test(s)&&!ir.test(s)&&!se(d)?[i]:[]})},In=e=>{const r=w.isComputedPropertyName(e)?e.getExpression():e;return w.isStringLiteral(r)||w.isNoSubstitutionTemplateLiteral(r)?r.getLiteralValue():e.getText()},ne=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],Ln=/\.(?:[cm]?js|jsx)$/u,xn=(e,r)=>{if(!r.startsWith("."))return;const t=L(Xe(e),r),n=t.replace(Ln,"");return[t,...ne.map(a=>`${t}${a}`),...ne.map(a=>b(t,`index${a}`)),...ne.map(a=>`${n}${a}`)].find(a=>Nn(a))},Mn=e=>{if(e.getExpression().getText()!=="require")return;const[r]=e.getArguments();return r!==void 0&&(w.isStringLiteral(r)||w.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():void 0},Fn=e=>{const r=e.getModuleReference();if(!w.isExternalModuleReference(r))return;const t=r.getExpression();return w.isStringLiteral(t)?t.getLiteralValue():void 0},Un=(e,r,t,n)=>{const o=new Set(e),a=[...e],s=[];for(let i=0;i<a.length;i+=1){const c=a[i]??"",d=ur(c,n);if(d===void 0)continue;const l=r.createSourceFile(U(t,c),d,{overwrite:!0}),g=[...l.getImportDeclarations().map(u=>u.getModuleSpecifierValue()),...l.getExportDeclarations().map(u=>u.getModuleSpecifierValue()),...l.getDescendantsOfKind(p.ImportEqualsDeclaration).map(u=>Fn(u)),...l.getDescendantsOfKind(p.CallExpression).map(u=>Mn(u))].filter(u=>u!==void 0);for(const u of g){const h=xn(c,u);h!==void 0&&lr(t,h)&&!o.has(h)&&(o.add(h),s.push(h),a.push(h))}}return s},Bn=e=>{const r=e.getArgumentExpression();return r!==void 0&&(w.isStringLiteral(r)||w.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():void 0},Hn=e=>w.isPropertyAccessExpression(e)?e.getName():w.isElementAccessExpression(e)?Bn(e):void 0,Gn=new Set([p.AmpersandAmpersandEqualsToken,p.AmpersandEqualsToken,p.AsteriskAsteriskEqualsToken,p.AsteriskEqualsToken,p.BarBarEqualsToken,p.BarEqualsToken,p.CaretEqualsToken,p.EqualsToken,p.GreaterThanGreaterThanEqualsToken,p.GreaterThanGreaterThanGreaterThanEqualsToken,p.LessThanLessThanEqualsToken,p.MinusEqualsToken,p.PercentEqualsToken,p.PlusEqualsToken,p.QuestionQuestionEqualsToken,p.SlashEqualsToken]),qn=e=>{const r=e.getOperatorToken().getKind();return!Gn.has(r)||Hn(e.getLeft())!==cr?!1:r!==p.EqualsToken||!ye(e.getRight())},Vn=(e,r,t)=>{const n=[],o=[...new Set([N(e),"src"])].filter(g=>S(b(e,g))),a=O(e),s=[...Cn.map(g=>b(e,g)).filter(g=>S(g)),...a===void 0?[]:De(e,a,r),...t.flatMap(g=>De(e,g,r))],i=new Qe({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}),c=o.flatMap(g=>gr(b(e,g),b(e,g),n));return{sites:[...new Set([...c,...s,...Un([...s,...c],i,e,n)])].flatMap(g=>{const u=ur(g,n);if(u===void 0)return[];const h=i.createSourceFile(U(e,g),u,{overwrite:!0}),f=[...h.getDescendantsOfKind(p.PropertyAssignment),...h.getDescendantsOfKind(p.ShorthandPropertyAssignment),...h.getDescendantsOfKind(p.GetAccessor),...h.getDescendantsOfKind(p.MethodDeclaration)].filter(m=>{const E=w.isPropertyAssignment(m)&&ye(m.getInitializer());return In(m.getNameNode())===cr&&!E}).map(m=>m.getStartLineNumber()),v=h.getDescendantsOfKind(p.BinaryExpression).filter(m=>qn(m)).map(m=>m.getStartLineNumber());return[...f,...v].map(m=>({file:U(e,g),line:m}))}),unreadable:n}},Wn=(e,r,t,n,o,a)=>{if(t!=="deploy")return;const{sites:s,unreadable:i}=Vn(e,o,a),c=Nt({openShardAccess:s,schema:{tables:[]}},{lints:[Ee]});if(c.length===0&&i.length===0)return;const d=[];if(c.length>0){const g=c.map(u=>`${String(u.metadata.file)}:${String(u.metadata.line)}`).join(", ");d.push(`${g} enable the open-shard option (any value but a literal false), so any caller may target any shard.`)}if(i.length>0&&d.push(`could not read ${i.join(", ")}, so the open-shard option cannot be ruled out there.`),n){r.warn(`deploying past the open-shard gate (--allow-open-shards): ${d.join(" ")}`);return}const l=`deploy blocked (open_shard_access): ${d.join(" ")} ${Ee.remediation}`;return r.error(l),l},Kn=(e,r,t,n)=>{const o=Wn(e,r.logger,t,r.allowOpenShards===!0,r.env,n);return o===void 0?void 0:{code:y.USAGE,error:o}},zn=(e,r,t,n)=>{const o=_n(e,r.logger,t,n,r.env);if(o!==void 0)return{code:y.USAGE,error:o};const a=Dn(e,r.logger,t,r.env);if(a!==void 0)return{code:y.USAGE,error:a};const s=En(e,r.logger,t,r.discoveryCache);if(s!==void 0)return{code:y.USAGE,error:s};const i=$n(e,r.logger,r.dockerAvailable??Rt,t,r.env);return i===void 0?void 0:{code:y.MISSING_DEPENDENCY,error:i}},Ce=32,fr=15e3,Jn=5432,Yn=3306,Xn=/[^a-z0-9-]/gu,Qn=/[^A-Za-z0-9]/gu,Zn=/-$/u,B=e=>`LUNORA_${e.replaceAll(Qn,"_").toUpperCase()}_URL`,eo=e=>{const r=new Map;for(const t of e){const n=B(t),o=r.get(n);if(o!==void 0)return{bindings:[o,t],variable:n};r.set(n,t)}},Pe=7,ro=(e,r)=>{const t=`${e}-${r}`.toLowerCase(),n=t.replaceAll(Xn,"-");if(n===t&&n.length<=Ce)return n;const o=St("sha256").update(t).digest("hex").slice(0,Pe-1);return`${n.slice(0,Ce-Pe).replace(Zn,"")}-${o}`},Ne=e=>e==="postgresql"?"postgres":e==="mariadb"?"mysql":e,to=e=>e==="mysql"?Yn:Jn,no=e=>{try{const r=new URL(e),t=r.protocol.slice(0,-1),n=decodeURIComponent(r.pathname.slice(1));return!["mariadb","mysql","postgres","postgresql"].includes(t)||r.hostname===""||n===""?void 0:{database:n,host:r.hostname,password:decodeURIComponent(r.password),port:r.port===""?to(Ne(t)):Number(r.port),scheme:Ne(t),user:decodeURIComponent(r.username)}}catch{return}},oo=(e,r)=>{const t=typeof r?.password=="string"?r.password:"",n=t===""?[]:[t,JSON.stringify(t).slice(1,-1),encodeURIComponent(t)];let o=e;for(const a of n)o=o.replaceAll(a,"<redacted>");return o.split(" ").map(a=>a.includes("://")?"<url>":a).join(" ")},hr=e=>(Array.isArray(e)?e:[]).flatMap((r,t)=>{const{binding:n,id:o}=typeof r=="object"&&r!==null?r:{};return typeof n=="string"&&o===We?[{binding:n,index:t}]:[]}),z=e=>{let r="";try{const{errors:t}=JSON.parse(e.text);r=(t??[]).flatMap(n=>typeof n.message=="string"?[n.message]:[]).slice(0,2).join("; ")}catch{}return r===""?`HTTP ${String(e.status)}`:`HTTP ${String(e.status)}: ${r}`},ao=e=>typeof e=="string"||typeof e=="number"?e.toString():void 0,so=["scheme","host","port","database","user"],io=e=>e==="postgresql"?"postgres":e,Oe=(e,r)=>{const t=ao(r);return e==="scheme"?io(t):t},je=50,co=async(e,r)=>{for(let t=1;t<=je;t+=1){const n=await e(t===1?"/hyperdrive/configs":`/hyperdrive/configs?page=${String(t)}`);if(!n.ok)throw new Error(`listing Hyperdrive configs failed (${z(n)})`);if(!Array.isArray(n.body.result))throw new TypeError("the listing of Hyperdrive configs had no result list");const o=n.body.result.find(s=>s.name===r),a=typeof n.body.result_info=="object"&&n.body.result_info!==null?n.body.result_info:{};if(o!==void 0||typeof a.total_pages!="number"||t>=a.total_pages)return o}throw new Error(`the listing of Hyperdrive configs has more than ${String(je)} pages, so "${r}" can't be shown to be absent`)},lo=async(e,r,t,n)=>{const o=n?{caching:{disabled:!0}}:{},a=await co(e,r);if(typeof a?.id=="string"){const c=so.filter(l=>Oe(l,a.origin?.[l])!==Oe(l,t[l]));if(c.length>0)throw new Error(`a Hyperdrive config named "${r}" already exists for a different origin, or one that can't be confirmed (${c.join(", ")}). Delete it, or rename the Worker, so the binding does not reach the wrong database.`);const d=await e(`/hyperdrive/configs/${encodeURIComponent(a.id)}`,{body:JSON.stringify({origin:t,...o}),method:"PATCH"});if(!d.ok)throw new Error(`updating its credentials failed (${z(d)})`);return{id:a.id,reused:!0}}const s=await e("/hyperdrive/configs",{body:JSON.stringify({name:r,origin:t,...o}),method:"POST"});if(!s.ok)throw new Error(`creating it failed (${z(s)})`);const{id:i}=typeof s.body.result=="object"&&s.body.result!==null?s.body.result:{};if(typeof i!="string")throw new TypeError("the response carried no id");return{id:i,reused:!1}},uo=(e,r,t,n)=>r===void 0&&n?`${B(e)} is set but is not a usable connection string for the "${e}" Hyperdrive binding: it needs a postgres://, postgresql:// or mysql:// scheme, a host and a database name, with any special characters percent-encoded.`:r===void 0?`the "${e}" Hyperdrive binding has no config yet. Set ${B(e)} to its postgres:// or mysql:// connection string and Lunora creates the config, or run \`wrangler hyperdrive create\` and put its id in wrangler.jsonc.`:t?void 0:`creating the "${e}" Hyperdrive config needs CLOUDFLARE_API_TOKEN (Hyperdrive: Edit) and CLOUDFLARE_ACCOUNT_ID, or run \`wrangler hyperdrive create\` and put its id in wrangler.jsonc.`,go=async(e,r)=>{const t=ro(e.workerName,e.binding),{id:n,reused:o}=await lo(async(a,s)=>er({accountId:e.accountId,apiToken:e.token,...e.fetch===void 0?{}:{fetch:e.fetch},init:{...s,signal:AbortSignal.timeout(fr)},path:a}),t,e.origin,e.disableCaching);return e.logger.success(`${o?"reusing":"created"} Hyperdrive config "${t}" for ${e.binding} → ${e.wranglerPath}`),{id:n,text:Ke(r,[...e.path,e.index,"id"],n)}},fo=e=>e===void 0||e===""?void 0:e,mr=e=>{const r=k(M(e),".wrangler","deploy","config.json");try{const{configPath:t}=JSON.parse(A(r,"utf8"));return typeof t=="string"?L(M(r),t):void 0}catch{return}},ho=(e,r,t,n,o)=>{const a=mr(e);if(a===void 0||a===e)return;if(n.built!==n.deployed){o.warn(`the build output ${a} was made for ${n.built===void 0?"the default environment":`"${n.built}"`}, not ${n.deployed===void 0?"the default environment":`"${n.deployed}"`}, so the "${r}" Hyperdrive id was not written there. Build with CLOUDFLARE_ENV set to the environment you deploy, then deploy again.`);return}let s;try{s=D(a)}catch{return}const i=hr(s.parsed?.hyperdrive).find(c=>c.binding===r);i!==void 0&&H(a,Ke(s.text,["hyperdrive",i.index,"id"],t),"utf8")},mo=(e,r)=>{const t=typeof e.name=="string"&&e.name!==""?e.name:"lunora";if(r===void 0)return t;const n=e.env?.[r]?.name;return typeof n=="string"&&n!==""?n:`${t}-${r}`},we=(e,r)=>{const t=O(e),n=t===void 0?void 0:D(t).parsed;if(t===void 0||n===void 0)return;const o=r===void 0?void 0:n.env?.[r],a=hr(r===void 0?n.hyperdrive:o?.hyperdrive);return a.length===0?void 0:{accountId:o?.account_id??n.account_id,entries:a,path:r===void 0?["hyperdrive"]:["env",r,"hyperdrive"],workerName:mo(n,r),wranglerPath:t}},vo=(e,r,t)=>{const n=eo(e.map(({binding:o})=>o));if(n!==void 0){const o=`deploy blocked: the Hyperdrive bindings ${n.bindings.map(a=>`"${a}"`).join(" and ")} both read ${n.variable} and would share one config. Rename one so their names differ in letters or digits, not only in punctuation.`;return t.logger.error(o),o}for(const{binding:o,origin:a,supplied:s}of e){const i=uo(o,a,r,s);if(i!==void 0&&t.dryRun===!0)t.logger.warn(`dry run: ${i} A real deploy stops here.`);else if(i!==void 0){const c=`deploy blocked: ${i}`;return t.logger.error(c),c}}},po=async(e,r,t,n)=>{let o;try{o=await e(`/hyperdrive/configs/${encodeURIComponent(t)}`)}catch(s){n.warn(`could not check whether the "${r}" Hyperdrive config has query caching off (${s instanceof Error?s.message:String(s)}).`);return}if(!o.ok){n.warn(`could not check whether the "${r}" Hyperdrive config has query caching off (${z(o)}).`);return}const{caching:a}=typeof o.body.result=="object"&&o.body.result!==null?o.body.result:{};a?.disabled!==!0&&n.warn(`the "${r}" Hyperdrive config has query caching on, so .global() tables would read rows up to 75 s old. Run \`wrangler hyperdrive update ${t} --caching-disabled\`.`)},yo=async(e,r)=>{const t=O(e.cwd),n=t===void 0?void 0:D(t).parsed,o=e.wranglerEnvironment===void 0?n:n?.env?.[e.wranglerEnvironment],{accountId:a,token:s}=Ze(r,o?.account_id??n?.account_id);if(a===void 0||s===void 0)return;const i=async(c,d)=>er({accountId:a,apiToken:s,...e.fetch===void 0?{}:{fetch:e.fetch},init:{...d,signal:AbortSignal.timeout(fr)},path:c});for(const c of Array.isArray(o?.hyperdrive)?o.hyperdrive:[]){const{binding:d,id:l}=typeof c=="object"&&c!==null?c:{};typeof d=="string"&&typeof l=="string"&&l!==We&&await po(i,d,l,e.logger)}},wo=async e=>{const r=e.environment??process.env;e.disableCaching===!0&&e.checkOnly!==!0&&e.dryRun!==!0&&await yo(e,r);const t=we(e.cwd,e.wranglerEnvironment);if(t===void 0)return;const{entries:n,path:o,wranglerPath:a}=t,{accountId:s,token:i}=Ze(r,t.accountId),c=n.map(({binding:l})=>{const g=r[B(l)]??"";return{binding:l,origin:no(g),supplied:g!==""}}),d=vo(c,i!==void 0&&s!==void 0,e);if(d!==void 0)return d;if(!(e.dryRun===!0||e.checkOnly===!0))for(const[l,{binding:g,index:u}]of n.entries()){const h=c[l]?.origin;if(!(h===void 0||i===void 0||s===void 0))try{const{id:f,text:v}=await go({accountId:s,binding:g,disableCaching:e.disableCaching===!0,fetch:e.fetch,index:u,logger:e.logger,origin:h,path:o,token:i,workerName:t.workerName,wranglerPath:a},A(a,"utf8"));H(a,v,"utf8"),ho(a,g,f,{built:fo(r.CLOUDFLARE_ENV),deployed:e.wranglerEnvironment},e.logger)}catch(f){const v=f instanceof Error?f.message:String(f),m=`deploy blocked: the "${g}" Hyperdrive config could not be set up: ${oo(v,c[l]?.origin)}`;return e.logger.error(m),m}}},ko=(e,r)=>{const t=we(e,r.env)?.entries[0]?.binding;if(t===void 0)return;const n=`prepare blocked: the "${t}" Hyperdrive binding still has its placeholder id. Run \`lunora deploy\` with ${B(t)} set to create the config, or put the id from \`wrangler hyperdrive create\` in wrangler.jsonc.`;return r.logger.error(n),n},bo=(e,r)=>{const t=we(e,r.env)?.entries[0]?.binding;if(t===void 0)return;const n=`deploy blocked: the "${t}" Hyperdrive binding has no config, and a --temporary deploy cannot create one: it would be made in your account while the Worker goes to a temporary one, which a temporary account has no database for. Deploy without --temporary.`;return r.logger.error(n),n},vr=async(e,r,t,n,o="create")=>{if(n!=="cloudflare")return;if(t==="prepare")return ko(e,r);if(r.temporary===!0)return bo(e,r);const a=r.clientBuildEnvironment===void 0?void 0:{...process.env,CLOUDFLARE_ENV:r.clientBuildEnvironment},s=ue(e,N(e),r.discoveryCache);return s.error!==void 0&&r.logger.warn(`could not read the schema (${s.error}), so Hyperdrive configs are set up with query caching off.`),wo({checkOnly:o==="check",cwd:e,disableCaching:s.error!==void 0||s.info?.hasHyperdriveGlobalTable===!0,dryRun:r.dryRun,environment:a,logger:r.logger,wranglerEnvironment:r.env})},So=/https?:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/u,$o=/https:\/\/[^\s"'<>]+/u,Eo=e=>{if(e===void 0)return;const r=So.exec(e);return r?r[0]:$o.exec(e)?.[0]},Ie=e=>e===void 0?"":` (--env ${e})`,Ao=({cwd:e,env:r,logger:t,now:n,url:o})=>{if(o!==void 0)try{const a=Be(e);if(a!==void 0){if(a.workerUrl===o&&a.env===r)return;t.warn(`link: .lunora/project.json records ${a.workerUrl??"(no url)"}${Ie(a.env)}, but this deploy published ${o}${Ie(r)}. Keeping the recorded value — run \`lunora link --url ${o}${r===void 0?"":` --env ${r}`}\` to update it.`);return}const s=(n??(()=>new Date().toISOString()))();Ur(e,{env:r,linkedAt:s,workerName:fe(e),workerUrl:o}),t.success(`link: recorded ${o} in .lunora/project.json (run \`lunora link\` to change)`)}catch{}},To=async(e,r)=>{const t=new Qe({skipAddingFilesFromTsConfig:!0}),n=b(r,"lunora");let o;try{o=_r(t,n)}catch(a){const s=a instanceof Error?a.message:String(a);return e.logger.warn(`--migrate: could not discover migrations (${s}); skipping`),0}if(o.length===0)return e.logger.info("--migrate: no data migrations declared in lunora/"),0;e.logger.info(`--migrate: running ${String(o.length)} migration(s) against deployed worker`);for(const a of o){e.logger.info(`--migrate: up "${a.id}" (table "${a.table}")`);const s={cwd:r,fetchImpl:e.fetchImpl,id:a.id,logger:e.logger,prod:!0,subcommand:"up",token:e.migrateToken,url:e.migrateUrl,yes:e.migrateYes===!0},i=await Ot(s);if(i.code!==0)return e.logger.error(`--migrate: migration "${a.id}" failed — see output above`),i.code;e.logger.success(`--migrate: "${a.id}" applied`)}return 0},Ro=async(e,r)=>{const{info:t}=ue(r,"lunora",e.discoveryCache),n=t?.vectorMetadata??[];if(n.length===0)return;const o=[];for(const i of n){const c=ht(i.kind);if(c===void 0){e.logger.warn(`vector index "${i.index}" declares metadata "${i.property}", whose column type cannot be filtered on in Vectorize — it is stored with each vector but no filter will match it.`);continue}o.push({index:i.index,property:i.property,type:c})}if(o.length===0)return;const s=(await mt({cwd:r,entries:o,exec:he(j(r),"wrangler",[]),logger:e.logger,spawner:e.spawner??x})).filter(i=>i.status!=="failed").length;s>0&&e.logger.success(`vectorize metadata indexes ready: ${String(s)}/${String(o.length)}`)},Le=5,_o=2e3,Do=async(e,r,t)=>{if(e.healthCheck!==!0)return;const n=t??Ye({cwd:r,env:e.env});if(n===void 0){const a="--health-check: the deploy succeeded, but no URL to probe could be resolved — wrangler's output carried none and this checkout has no link for this environment. Run `lunora link --url <https://your-worker>` and re-deploy, or drop --health-check.";return e.logger.error(a),{error:a,ok:!1,url:""}}const o=await _t({attempts:Le,baseUrl:n,delayMs:_o,fetchImpl:e.healthFetch,paths:[Dt,Ct],sleep:e.healthSleep});return o.error===void 0?(e.logger.success(`health check ok (${o.url})`),{ok:!0,url:o.url}):(e.logger.error(`--health-check: the deploy succeeded, but the new version did not answer after ${String(Le)} attempt(s) — ${o.error}`),{error:o.error,ok:!1,url:o.url})},Co=async(e,r,t,n,o,a)=>{await Ro(e,r);const s=e.migrate?await To(e,r):0;return s===0&&o?.(),{code:s,descriptor:t,mintedSecretsFile:a,validation:n}},Po=async({cwd:e,descriptor:r,mintedSecretsFile:t,options:n,reblessSchemaBaseline:o,recordArchitecture:a,stdout:s,validation:i})=>{const c={deployedAt:new Date().toISOString(),dryRun:n.dryRun===!0,env:n.env,preview:n.preview===!0,url:n.dryRun===!0?void 0:Eo(s),workerName:fe(e)};if(n.dryRun===!0||n.preview===!0)return n.healthCheck===!0&&n.logger.warn(`--health-check skipped: ${n.dryRun===!0?"a dry run publishes nothing":"a preview version serves no live traffic"}`),{code:0,deployment:c,descriptor:r,mintedSecretsFile:t,validation:i};n.temporary!==!0&&(a?.(),Ao({cwd:e,env:n.env,logger:n.logger,url:c.url}));const d=await Do(n,e,c.url);return d?.error!==void 0?{code:y.UNAVAILABLE,deployment:c,descriptor:r,healthCheck:d,mintedSecretsFile:t,validation:i}:{...await Co(n,e,r,i,o,t),deployment:c,healthCheck:d}},No=(e,r,t)=>{const n=b(e,P);if(!S(n))return;let o;try{o=Ge(A(n,"utf8")).length}catch{return}if(o===0)return;const a=t.toolchain?.secretPut!==void 0;r.warn(a?`Note: \`lunora deploy\` does not push secrets. ${P} has ${String(o)} key(s); if you changed them, run \`lunora env push --yes\` to update the deployed secrets.`:`Note: ${t.name} deploys read no secrets. ${P} has ${String(o)} key(s) that only the dev server sees; a key the app reads from env must be a \`vars\` entry in the deployed config, one it loads from a secret manager at runtime need not.`)},pr=async(e,r)=>{let t=[];try{t=Br(await qe({cache:r,projectRoot:e,schemaDir:N(e)}))}catch{}const n=[...new Set(Hr(t).map(a=>a.key))];let o=[];try{const a=b(e,P);S(a)&&(o=Ge(A(a,"utf8")).map(s=>s.key).filter(s=>ze(s)))}catch{}return{fromLocal:o.filter(a=>!n.includes(a)),fromPackages:n,mintableKeys:Gr(t)}},Oo=async(e,r,t,n)=>{const{logger:o}=r,a=r.spawner??x,s=j(e),i=r.env===void 0?"":` --env ${r.env}`,c=n.toolchain?.secretPut;if(c===void 0)return o.error(`deploy target "${n.id}" has no secret store; cannot push secrets`),{minted:[],ok:!1};const d=t.map(u=>({key:u,value:qr()})),l=n.toolchain?.secretBulk;if(l!==void 0&&d.length>=2){const u=F(s,l({environment:r.env,temporary:r.temporary})),h=await a({args:u.args,command:u.command,cwd:e,input:JSON.stringify(Object.fromEntries(d.map(f=>[f.key,f.value])))});if(h.code===0){for(const{key:f}of d)o.success(`generated + pushed ${f}`);return{minted:d,ok:!0}}o.warn(`bulk secret push failed (exit ${String(h.code)}); retrying one key at a time`)}const g=[];for(const{key:u,value:h}of d){const f=c({environment:r.env,key:u,temporary:r.temporary}),v=F(s,f),m=await a({args:v.args,command:v.command,cwd:e,input:h});if(m.code!==0)return o.error(`failed to push secret ${u} (exit ${String(m.code)}); set it manually with \`wrangler secret put ${u}${i}\`.`),{minted:g,ok:!1};g.push({key:u,value:h}),o.success(`generated + pushed ${u}`)}return{minted:g,ok:!0}},jo=/^[\w-]+$/u,xe=[".dev.vars",".dev.vars.*","!.dev.vars.example"],Io=(e,r)=>{try{const t=zr(e,xe);t.length>0&&r.info(`.gitignore: added ${t.join(", ")} so the recorded secret cannot be committed`)}catch(t){r.warn(`could not update .gitignore (${t instanceof Error?t.message:String(t)}) — add \`${xe.join("` and `")}\` by hand before committing.`)}},Lo=(e,r,t)=>{if(t.length===0)return;const n=t.map(i=>i.key).join(", ");if(r.env!==void 0&&!jo.test(r.env)){r.logger.warn(`${n}: minted and pushed for --env ${r.env}, but "${r.env}" isn't a safe filename fragment — the value could not be recorded. Capture it manually if you need it again.`);return}const o=r.env===void 0?P:`${P}.${r.env}`;Io(e,r.logger);const a=b(e,o);let s=S(a)?A(a,"utf8"):"";for(const i of t)s=Vr(s,i.key,i.value);return Wr(a,s),r.logger.success(r.env===void 0?`${n}: value(s) recorded in ${o}`:`${n}: value(s) recorded in ${o} (kept separate from ${P} so \`lunora dev\` and a plain \`lunora env push\` don't inherit the --env ${r.env} value)`),o},xo=/^<[^>]+>$/u,Mo=async(e,r,t)=>{let n;try{n=t.projectConfig?.(e,"deploy").vars??{}}catch(l){return{error:l instanceof Error?l.message:String(l)}}const o=l=>{const g=n[l];if(typeof g!="string")return!0;const u=g.trim();return u===""||xo.test(u)?!0:ze(l)&&Kr(g)},a=l=>Object.hasOwn(n,l)?`${l} (empty or a placeholder)`:l,{fromLocal:s,fromPackages:i}=await pr(e,r.discoveryCache),c=s.filter(l=>o(l));c.length>0&&r.logger.warn(`${P} key(s) not set in the wrangler vars: ${c.map(l=>a(l)).join(", ")}. ${t.name} has no secret store: a key the app reads from env must be a \`vars\` entry; one it loads from a secret manager at runtime need not.`);const d=i.filter(l=>o(l));return d.length===0?{}:{error:`missing required secret(s) in the wrangler vars: ${d.map(l=>a(l)).join(", ")}. ${t.name} has no secret store and Lunora reads these from env, so each must be a real \`vars\` value in the config the deploy ships — write it there from your secret manager at deploy time rather than committing it. Add them, then re-deploy.`}},Fo=async(e,r,t,n)=>{if(r.dryRun===!0||r.preview===!0)return{};if(n.toolchain?.secretList===void 0)return Mo(e,r,n);const{logger:o}=r,a=r.env===void 0?"":` --env ${r.env}`;let s;try{s=await(r.secretLister??It)({cwd:e,env:r.env,target:n.id,temporary:r.temporary})}catch{return{}}if(!s.ok)return{};const i=new Set(s.names),{fromLocal:c,fromPackages:d,mintableKeys:l}=await pr(e,r.discoveryCache),g=[...d,...c].filter(f=>!i.has(f));if(g.length===0)return{};if(!t)return{error:`missing required secret(s) on the deploy target: ${g.join(", ")}. Set them with \`wrangler secret put <KEY>${a}\` (or \`lunora env generate --set\` then \`lunora env push --yes${a}\`), then re-deploy.`};for(const f of g.filter(v=>!l.has(v)))o.warn(`required secret ${f} is not set on the target — set it with: wrangler secret put ${f}${a}`);const u=g.filter(f=>l.has(f));if(u.length===0)return{};if(await(r.secretConfirm??jt())(`${String(u.length)} required secret(s) not set on the target (${u.join(", ")}). Generate strong values and push them now?`)){const{minted:f,ok:v}=await Oo(e,r,u,n),m=Lo(e,r,f);return v?{mintedSecretsFile:m}:{error:"failed to push required secret(s) — set them manually and re-deploy",mintedSecretsFile:m}}return o.warn(`${String(u.length)} required secret(s) not set on the target: ${u.join(", ")}. Generate + push with \`lunora env generate --set\` then \`lunora env push --yes${a}\`.`),{}},yr=e=>e.format==="json"?!1:e.interactive!==void 0?e.interactive:process.stdout.isTTY&&!process.env.CI,Uo=async(e,r)=>{if(r.dryRun===!0)return;const t=He(e,"lunora",r.discoveryCache).containers.flatMap(o=>o.schedulingPolicy===void 0&&o.image.kind==="build"?[{buildDir:o.image.buildDir,exportName:o.exportName}]:[]);if(t.length===0)return;const n=await fn({cwd:e,logger:r.logger,railpackAvailable:r.railpackAvailable,spawner:r.spawner,targets:t});return n.code===0?void 0:n.error??"railpack build failed"},Bo=(e,r,t)=>{if(t!==void 0)try{const n=it(e,t);n.changed&&r.success(`synced ${String(t.length)} cron trigger(s) → ${n.wranglerPath??"wrangler.jsonc"}`);for(const a of n.warnings)r.warn(a);const o=ct(n.preserved);o!==void 0&&r.info(o)}catch(n){const o=n instanceof Error?n.message:String(n);r.warn(`cron trigger sync skipped: ${o}`)}},Ho=async(e,r,t,n,o,a)=>{try{Y(n);const s=await qe({cache:a,projectRoot:e,schemaDir:N(e)}),i=at(e,s,{environment:o,target:n}),c=i.wranglerPath??"wrangler.jsonc";if(i.added.length>0&&r.success(`provisioned bindings: ${i.added.join(", ")} → ${c}`),i.updated.length>0&&r.success(`updated bindings: ${i.updated.join(", ")} → ${c}`),i.devConfig!==void 0){const{added:d,path:l,updated:g}=i.devConfig;r.success(`dev sidecar bindings: ${[...d,...g].join(", ")} → ${l}`)}for(const d of i.warnings)r.warn(d)}catch(s){const i=s instanceof Error?s.message:String(s);r.warn(`binding inference skipped: ${i}`)}try{const s=st(e);s.changed&&r.success(`bumped compatibility_date to ${s.date??"unknown"} (Workers Cache enabled) → ${s.wranglerPath??"wrangler.jsonc"}`)}catch(s){const i=s instanceof Error?s.message:String(s);r.warn(`compatibility date sync skipped: ${i}`)}Bo(e,r,t)},Go=async(e,r,t,n,o,a,s,i,c,d)=>{let l;r?(l=new dt({name:"dots"}),l.start("running codegen")):t.info("running codegen");try{const g=Dr({apiSpec:n,dryRun:!d,lazyFunctions:o,projectRoot:e,target:a,...ot(e)});l?.succeed("codegen complete"),l||t.success("codegen complete");const u=lt(g.platformDiagnostics,t);if(u.errors.length>0)return{error:u.errors.join("; ")};const{errorAdvisories:h,names:f,shouldBlock:v}=ut(g.advisories,c);if(v){const E=`${h.length.toString()} ERROR-level ${h.length===1?"advisory":"advisories"} (${f.join(", ")}). Pass --no-strict-advisories to downgrade this to a warning and continue.`;return t.error(E),{error:E}}const m=d?await Zr({cwd:e,logger:t,spawner:s,stdoutToStderr:i}):void 0;return m?.error!==void 0?{error:m.error}:{result:g}}catch(g){l?.failed("codegen failed");const u=g instanceof Error?g.message:String(g);return t.error(`codegen failed: ${u}`),{error:`codegen failed: ${u}`}}},qo=(e,r)=>({dryRun:r.dryRun,entry:pe(e),environment:r.env,outDir:r.outDir,preview:r.preview,temporary:r.temporary}),wr=(e,r,t)=>{const{toolchain:n}=t;if(n===void 0)throw new Error(`deploy target "${t.id}" has no command-line toolchain`);const o=qo(e,r);return Ve(t,e,"deploy",a=>n.deploy({...o,configPath:a}))},Vo=(e,r,t)=>{const n=wr(e,r,t),o=pe(e);return o!==void 0&&r.logger.info(`class-B composition: deploying ${o} (overrides wrangler main)`),r.temporary&&r.logger.info("temporary account: deploying to a short-lived Cloudflare account (~60min); wrangler will print a claim URL"),r.dryRun&&r.logger.info("dry run: validating + bundling without publishing"),r.outDir!==void 0&&r.logger.info(`build artifact: emitting bundle to ${r.outDir}`),n.commit(),n.projection!==void 0&&n.projection.dropped.length>0&&r.logger.warn(`${t.name} ignores these wrangler keys, so they were left out of ${n.projection.configPath}: ${n.projection.dropped.join(", ")}`),n.command},R={problems:[],wranglerPath:void 0},oe=(e,r)=>({code:y.USAGE,descriptor:void 0,error:e,validation:R,...r}),Wo=(e,r)=>{for(const t of e.report?.warnings??[])r.warn(`wrangler.jsonc: ${t}`);if(e.problems.length===0)return!1;r.error("wrangler.jsonc validation failed:");for(const t of e.problems)r.error(` - ${t}`);return!0},Ko=(e,r,t)=>{const n=r.format==="json",o=r.dryRun!==!0,a=Vo(e,r,t),s=F(j(e),a);return{args:s.args,captureStdout:o&&!n,captureStdoutSilently:o&&n,command:s.command,cwd:e,stdoutToStderr:n&&!o}},ke=e=>{if(e.skipServices===!0)return"--skip-services";if(e.preview===!0)return"--preview uploads the app version only";if(e.temporary===!0)return"--temporary deploys the app to a throwaway account"},zo=(e,r)=>ke(r)===void 0?le(e).services.map(t=>t.wranglerPath):[],kr=(e,r,t,n,o)=>({cwd:e,environment:r.env,frameworkBuild:n,lazyFunctions:J(r.lazyFunctions),logger:r.logger,outputJson:r.format==="json"||r.clientBuildOutputJson===!0,spawner:o,strictAdvisories:ge(r),target:t.id}),Jo=(e,r,t)=>{const{toolchain:n}=t,o=n===void 0?`target "${t.id}" has no deploy command`:ke(r);if(o!==void 0||n===void 0){const a=e.map(s=>s.worker).join(", ");r.logger.warn(`services not deployed (${o??""}): ${a} — deploy them yourself if the app calls anything new`);return}return n},br=(e,r)=>{for(const t of e){const n=me(r(M(t.wranglerPath)));if(n!==void 0)return`service ${t.name} (${t.worker}): ${n}`}},Yo=(e,r,t)=>{const{error:n,services:o}=le(e);if(n!==void 0||o.length===0)return;const a=Y(t);if(a.toolchain===void 0||ke(r)!==void 0)return;const s=r.skipCodegen===!0?!1:r.frameworkBuild,i=[...new Map(o.map(c=>[c.wranglerPath,c])).values()];return br(i,c=>kr(c,r,a,s,x))},Sr=(e,r,t)=>{const n=e.cwd??process.cwd(),o=kt(n,e.target);if(o.target===void 0){const i=o.error??"unknown deploy target";return e.logger.error(i),{kind:"refused",error:i,validation:R}}try{wr(n,e,Y(o.target))}catch(i){if(!(t&&i instanceof Jr&&Z(n,e.skipCodegen===!0?!1:e.frameworkBuild,e.env))){const c=i instanceof Error?i.message:String(i);return e.logger.error(c),{kind:"refused",error:c,validation:R}}}const a=e.openShardGatePassed===!0?void 0:Kn(n,e,r,zo(n,e));if(a!==void 0)return{kind:"refused",code:a.code,error:a.error,validation:R};const s=Yo(n,e,o.target);return s!==void 0?(e.logger.error(s),{kind:"refused",code:y.USAGE,error:s,validation:R}):{kind:"ok",target:o.target}},Xo=(e,r)=>e.apiSpec??(e.clientBuildRan===!0?et(r):void 0),Qo=async(e,r,t)=>{if(r!=="celld")return;const n=await(e.celldToolchain??Qr)({dryRun:t==="prepare"||e.dryRun===!0,env:process.env,purpose:"deploy"});for(const o of n.warnings)e.logger.warn(o);return n.errors.length>0?n.errors.join("; "):void 0},Zo=async(e,r)=>{const t=e.cwd??process.cwd(),n=yr(e),o=ge(e),a={problems:[],wranglerPath:void 0},s=Sr(e,r,!1);if(s.kind==="refused")return{code:s.code,error:s.error,validation:s.validation};const{target:i}=s,c=await Qo(e,i,r);if(c!==void 0)return e.logger.error(c),{code:y.MISSING_DEPENDENCY,error:c,target:i,validation:a};let d;if(!e.skipCodegen){const v=await Go(t,n,e.logger,Xo(e,t),J(e.lazyFunctions),i,e.spawner,e.format==="json",o,e.clientBuildRan!==!0);if(v.error!==void 0)return{error:v.error,target:i,validation:R};d=v.result,e.discoveryCache?.clear()}let l;if(d!==void 0){const v=Pt({allowDrift:e.allowSchemaDrift===!0,codegen:d,command:r,logger:e.logger,updateBaseline:e.updateSchemaBaseline===!0});if(v.blocked)return{error:`schema drift gate blocked ${r}`,schemaDrift:{blocked:!0,reason:v.reason},target:i,validation:a};l=v.rebless}const g=d&&Ht({current:d.architecture,cwd:t,environment:e.env,logger:e.logger});await Ho(t,e.logger,d?.cronTriggers,i,e.env,e.discoveryCache);const u=await vr(t,e,r,i,"check");if(u!==void 0)return{error:u,target:i,validation:R};const h=zn(t,e,r,i);if(h!==void 0)return{code:h.code,error:h.error,target:i,validation:R};const f=nt({environment:e.env,projectRoot:t});return Wo(f,e.logger)?{error:"wrangler validation failed",target:i,validation:f}:{codegen:d,reblessSchemaBaseline:l,recordArchitecture:g,target:i,validation:f}},ea=e=>{W(k(e,".wrangler","deploy","config.json"),{force:!0})},ra=async(e,r,t)=>{const n=me(e);if(n!==void 0)return{built:!1,error:n};const o=Z(e.cwd,r,t);return o&&ea(e.cwd),{built:o,error:await ar(e)}},ta=(e,r,t)=>r||t===!1?mr(e):void 0,na=async(e,r,t,n)=>{const{error:o,services:a}=le(e);if(o!==void 0)return{code:y.FAILURE,error:o};if(a.length===0)return;const s=Jo(a,r,t);if(s===void 0)return;const i=j(e),c=[...new Map(a.map(u=>[u.wranglerPath,u])).values()],d=r.skipCodegen===!0?!1:r.frameworkBuild,l=u=>kr(u,r,t,d,n),g=br(c,l);if(g!==void 0)return r.logger.error(g),{code:y.USAGE,error:g};for(const u of c){const h=M(u.wranglerPath),f=l(h),{built:v,error:m}=await ra(f,d,r.env);if(m!==void 0){const T=`service ${u.name} (${u.worker}): ${m}`;return r.logger.error(T),{code:y.FAILURE,error:T}}const E=ta(u.wranglerPath,v,d);let C;try{C=Ve(t,h,"deploy",T=>s.deploy({configPath:T??E??u.wranglerPath,dryRun:r.dryRun===!0,environment:r.env}))}catch(T){return{code:y.FAILURE,error:`service ${u.name} (${u.worker}): ${T instanceof Error?T.message:String(T)}`}}C.commit();const $=F(i,C.command);r.logger.info(`deploying service ${u.name} (${u.worker}) via ${$.command} ${$.args.join(" ")}`);const I=await n({args:$.args,command:$.command,cwd:h,stdoutToStderr:r.format==="json"});if(I.code!==0)return{code:y.FAILURE,error:`service ${u.name} (${u.worker}): ${$.command} ${$.args.join(" ")} exited ${String(I.code)} — stopping before the app`}}},oa=async(e,r,t,n)=>{if(r!=="cloudflare")return;const o=e===void 0?void 0:D(e).parsed,a=(t===void 0?void 0:o?.env?.[t]?.account_id)??o?.account_id,s=await pt({accountId:a});(s.verdict==="near"||s.verdict==="full")&&n.warn(s.fix===void 0?s.message:`${s.message} ${s.fix}`)},aa=e=>e.dryRun!==!0&&e.temporary!==!0,sa=e=>e.temporary===!0?"temporary":e.dryRun===!0?"preview":"defer",ia=e=>{const r=e.fix===void 0?e.message:`${e.message} ${e.fix}`;return e.verdict==="unchecked"?`${r} The deploy stops until it can be checked, as a namespace made by the first repo is unrestricted.`:r},ca=(e,r,t)=>{const n=[];for(const o of e)if(o.verdict==="ok")o.changesAccount===!0&&r.info(o.message);else if(o.verdict==="unchecked"&&t==="preview")r.warn(`dry run: ${o.message}${o.fix===void 0?"":` ${o.fix}`} A real deploy stops here.`);else{const a=ia(o);r.error(a),n.push(a)}return n},$r=async(e,r,t,n,o,a,s)=>{const i=t==="cloudflare"&&r!==void 0?D(r).parsed:void 0;if(i===void 0)return;const c=(X(i,n).merged.artifacts??[]).flatMap(f=>typeof f?.binding=="string"&&typeof f.namespace=="string"?[{binding:f.binding,namespace:f.namespace}]:[]),d=c.length===0?void 0:ue(e,N(e),a).info?.jurisdiction;if(d===void 0)return;const l=[...new Map(c.map(f=>[f.namespace,f])).values()];if(s==="temporary"){o.warn(`--temporary deploys to a throwaway account, so the jurisdiction ("${d}") of Artifacts namespace ${l.map(f=>`"${f.namespace}"`).join(", ")} was not checked: it is created there on first use, in no jurisdiction.`);return}const g=(n===void 0?void 0:i.env?.[n]?.account_id)??i.account_id,u=await Promise.all(l.map(async f=>vt({...f,accountId:g,create:s==="create",jurisdiction:d,missingOk:s==="defer"||s==="preview"}))),h=ca(u,o,s);return h.length===0?void 0:h.join(`
|
|
19
|
-
`)},
|
|
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
|
+
`)},ra=async(e,r,t,n,o,s)=>{const a=Xs(r)?await Br(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 Or(e,r,"deploy",o);return i!==void 0?{code:w.FAILURE,error:i}:Js(e,r,t,n)},ta=async(e,r,t,n)=>{if(!(r.smokeLoad===!1||t.toolchain===void 0))return Fn({composedEntry:Re(e),configPath:n,cwd:e,environment:r.env,launcher:r.smokeLauncher,logger:r.logger,toolchain:t.toolchain})},na=async e=>{const r={...e,discoveryCache:e.discoveryCache??vt()},t=r.cwd??process.cwd(),n=Nr(r),o=await Vs(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=po(r)??await Br(t,s.wranglerPath,o.target,r.env,r.logger,r.discoveryCache,Qs(r))??await ta(t,r,a,s.wranglerPath);if(i!==void 0)return ue(i);const c=a.toolchain?.prebuildsContainerImages===!0?await _s(t,r):void 0;if(c!==void 0)return ue(c);bs(t,r.logger,a),bt(t,m=>{r.logger.warn(m)}),await Ys(s.wranglerPath,o.target,r.env,r.logger);const{error:l,mintedSecretsFile:d}=await Ps(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 g=r.spawner??x,u=await ra(t,r,a,g,o.target,s.wranglerPath);if(u!==void 0)return{code:u.code,descriptor:void 0,error:u.error,mintedSecretsFile:d,validation:s};const h=Ls(t,r,a);r.logger.info(`deploying via ${h.command} ${h.args.join(" ")}`);const f=await g(h);return h.captureStdoutSilently===!0&&f.stdout!==void 0&&f.stdout!==""&&process.stderr.write(f.stdout),f.code!==0?{code:f.code,descriptor:h,mintedSecretsFile:d,validation:s}:{...await ks({...o,cwd:t,descriptor:h,mintedSecretsFile:d,options:r,stdout:f.stdout}),logsAvailable:a.toolchain?.tail!==void 0}},oa=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};mt(t);const s=await $r(n);if(s!==void 0)return r.error(s),{code:w.FAILURE,descriptor:void 0,error:s,validation:A}},sa=(e,r)=>{const t=r.skipCodegen===!0?!1:r.frameworkBuild;return ae(e,t,r.env)?r.env:void 0},aa=async e=>{const{logger:r}=e,t=e.cwd??process.cwd(),n=Fr(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 oa(e);if(o!==void 0)return o;const s=e.dryRun===!0?wr(t):void 0;let a;try{if(a=await na({...e,clientBuildEnvironment:sa(t,e),clientBuildRan:co(t,e.skipCodegen===!0?!1:e.frameworkBuild,e.env),logger:r,openShardGatePassed:!0}),a.code===0&&e.emitBindings!==void 0){const{error:i}=Bt({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&&mn({cwd:e.cwd??process.cwd(),env:e.env,logger:e.logger,logsAvailable:a.logsAvailable===!0,mintedSecretsFile:a.mintedSecretsFile,url:a.deployment?.url}),a},Ua=Ht(async({cwd:e,format:r,logger:t,options:n})=>{const o=Un(e,n.root),s=await aa({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{Vs as a,Cs as b,Ua as e,Un as p,aa as r,ta as s,no as v};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{resolveLazyFunctions as
|
|
1
|
+
import{resolveLazyFunctions as c,resolveDeployDriver as t}from"@lunora/config";import{p as s}from"../packem_shared/api-spec-lYyq4vL6.mjs";import{d as l}from"../packem_shared/command-B6vu47iR.mjs";import{EXIT_CODE as o}from"../packem_shared/EXIT_CODE-DVjUgIaG.mjs";import{a as d,s as m}from"./handler.mjs";const n=async r=>{const a=r.cwd??process.cwd(),e=await d({allowSchemaDrift:r.allowSchemaDrift,apiSpec:r.apiSpec,lazyFunctions:c(r.lazyFunctions),cwd:a,logger:r.logger,spawner:r.spawner,strictAdvisories:r.strictAdvisories,target:r.target},"prepare");if(e.error!==void 0)return{code:e.code??o.USAGE,error:e.error,...e.schemaDrift===void 0?{}:{schemaDrift:e.schemaDrift},validation:e.validation};const i=await m(a,{env:void 0,logger:r.logger,smokeLauncher:r.smokeLauncher,smokeLoad:r.smokeLoad},t(e.target),e.validation.wranglerPath);return i!==void 0?{code:o.FAILURE,error:i,validation:e.validation}:(e.reblessSchemaBaseline?.(),r.logger.success("project is ready to deploy"),{code:0,validation:e.validation})},w=l(({cwd:r,logger:a,options:e})=>n({allowSchemaDrift:e.allowSchemaDrift===!0,apiSpec:s(e.apiSpec),lazyFunctions:c(e.lazyFunctions),cwd:r,logger:a,smokeLoad:e.smokeLoad,strictAdvisories:e.strictAdvisories,target:e.target}));export{w as execute,n as runPrepareCommand};
|
|
@@ -1,3 +1,3 @@
|
|
|
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
|
|
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
2
|
`)}
|
|
3
|
-
`:""}},
|
|
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{existsSync as h}from"node:fs";import{join as p}from"node:path";import{runCodegen as g}from"@lunora/codegen";import{resolveLazyFunctions as u}from"@lunora/config";import{validateWranglerProject as v,wranglerCodegenInputs as y}from"@lunora/config/cloudflare";import{a as w,e as S,r as k}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as j}from"../packem_shared/api-spec-lYyq4vL6.mjs";import{r as E}from"../packem_shared/codegen-error-AmH54ofi.mjs";import{d as A}from"../packem_shared/command-B6vu47iR.mjs";import{r as D}from"../packem_shared/deploy-target-resolve-BTCW1Iv4.mjs";import{EXIT_CODE as R}from"../packem_shared/EXIT_CODE-DVjUgIaG.mjs";import{r as $,p as b}from"../packem_shared/health-probe-
|
|
1
|
+
import{existsSync as h}from"node:fs";import{join as p}from"node:path";import{runCodegen as g}from"@lunora/codegen";import{resolveLazyFunctions as u}from"@lunora/config";import{validateWranglerProject as v,wranglerCodegenInputs as y}from"@lunora/config/cloudflare";import{a as w,e as S,r as k}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as j}from"../packem_shared/api-spec-lYyq4vL6.mjs";import{r as E}from"../packem_shared/codegen-error-AmH54ofi.mjs";import{d as A}from"../packem_shared/command-B6vu47iR.mjs";import{r as D}from"../packem_shared/deploy-target-resolve-BTCW1Iv4.mjs";import{EXIT_CODE as R}from"../packem_shared/EXIT_CODE-DVjUgIaG.mjs";import{r as $,p as b}from"../packem_shared/health-probe-BLnoq_oC.mjs";import{defaultSpawner as F}from"../packem_shared/createRecordingSpawner-01ZngIwK.mjs";import{execArgsFor as U,detectPackageManager as x}from"@lunora/config/cli";const P=async(r,a,t)=>{if(!h(p(r,"tsconfig.json")))return{warning:"no tsconfig.json found — skipping TypeScript type-check"};const o=U(x(r),"tsc",["--noEmit","-p","tsconfig.json"]),e=await a({args:o.args,command:o.command,cwd:r,stdoutToStderr:t==="json"});return e.code===0?{}:{error:`type errors: tsc --noEmit exited ${String(e.code)}`}},T=async(r,a)=>{if(r.healthUrl===void 0||r.healthUrl==="")return;const t=await b({baseUrl:r.healthUrl,fetchImpl:r.healthFetch});if(t.error===void 0){a.success(`verify: health probe ok (${t.url})`);return}return t.error},z=(r,a)=>{const{errorAdvisories:t,names:o,shouldBlock:e}=S(r,k(a));if(e)return`${t.length.toString()} ERROR-level ${t.length===1?"advisory":"advisories"} (${o.join(", ")}). Pass --no-strict-advisories to downgrade this to a warning and continue.`},C=(r,a,t,o)=>{if(a.length===0&&t.length===0)return r.success("verify: project is valid"),{code:0,errors:[],warnings:[],wranglerPath:o};if(t.length>0){r.warn("verify: warnings:");for(const e of t)r.warn(` - ${e}`)}if(a.length>0){r.error("verify: errors:");for(const e of a){r.error(` - ${e}`);const s=E(e);s!==void 0&&r.error(s)}return{code:1,error:a[0],errors:a,warnings:t,wranglerPath:o}}return r.success("verify: project is valid (with warnings)"),{code:0,errors:[],warnings:t,wranglerPath:o}},H=async r=>{const a=r.cwd??process.cwd(),{logger:t}=r,o=v({environment:r.env,projectRoot:a}),e=[...o.report.errors],s=[...o.report.warnings];try{const n=D(a,r.target);if(n.target===void 0){const c=n.error??"unknown deploy target";return t.error(c),{code:R.USAGE,error:c,errors:[c],warnings:[],wranglerPath:void 0}}const i=g({apiSpec:r.apiSpec,lazyFunctions:u(r.lazyFunctions),dryRun:!0,projectRoot:a,target:n.target,...y(a)}),l=w(i.platformDiagnostics,t);e.push(...l.errors),s.push(...l.warnings);const f=z(i.advisories,r);f!==void 0&&e.push(f);const m=await $({allowDrift:r.allowSchemaDrift===!0,codegen:i,command:"verify",logger:t,readOnly:!0});m.blocked&&e.push(m.reason)}catch(n){const i=n instanceof Error?n.message:String(n);e.push(`codegen failed: ${i}`)}if(r.typecheck!==!1){const n=await P(a,r.spawner??F,r.format??"pretty");n.error!==void 0&&e.push(n.error),n.warning!==void 0&&s.push(n.warning)}const d=await T(r,t);return d!==void 0&&e.push(d),C(t,e,s,o.wranglerPath)},Q=A(async({cwd:r,format:a,logger:t,options:o})=>{const e=await H({allowSchemaDrift:o.allowSchemaDrift===!0,apiSpec:j(o.apiSpec),lazyFunctions:u(o.lazyFunctions),cwd:r,env:o.env,format:a,healthUrl:o.healthUrl,logger:t,strictAdvisories:o.strictAdvisories,target:o.target,typecheck:o.typecheck===!1?!1:void 0});return{code:e.code,data:{errors:e.errors,warnings:e.warnings,wranglerPath:e.wranglerPath},error:e.error}});export{Q as execute,H as runVerifyCommand};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import z,{join as m,resolve as
|
|
2
|
-
`,"utf8"),await
|
|
3
|
-
`,headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json"},method:"PUT"});if(!l.ok){const d=await l.text().catch(()=>"<no body>");throw new w("INTERNAL",`backup: snapshot ${c.file} was written but its manifest was not (HTTP ${String(l.status)}): ${d}`)}},stage:async c=>{const s=await x(m(O(),"lunora-backup-"));return{path:m(s,v("",c)),release:async()=>b(s,{force:!0,recursive:!0})}}}},$e=".lunora-backups",F="/_lunora/admin/backup/retention",ve="/_lunora/admin/backup/prune",Se="/_lunora/admin/pitr",Ee="__lunora_admin__:getPitrBookmark",Ae="__lunora_admin__:pitrRestore",Te=async(e,t)=>{const r=(e.now??(()=>new Date))().toISOString(),a=await t.stage(r);try{const o=await te({cwd:e.cwd,fetchImpl:e.fetchImpl,logger:e.logger,out:a.path,prod:e.prod,tables:e.tables,token:e.token,url:e.url});if(o.code!==0)return{code:o.code};const i=t.locate(r),n=await L(a.path);await t.commit(i,a.path,n);const f={bytes:n.bytes,createdAt:r,file:i,id:r,rows:o.rows,sha256:n.sha256,tables:e.tables};return await t.record(f),e.logger.success(`backup created: ${i} (${o.rows.toString()} rows, ${n.bytes.toString()} bytes)`),{code:0,entry:f}}finally{await a.release().catch(o=>{e.logger.warn(`backup: could not clean up staging (${o instanceof Error?o.message:String(o)})`)})}},Ne=async(e,t,r)=>{if(t?.sha256===void 0)return r.error(t===void 0?"--verify needs a recorded checksum, and a snapshot restored by path/key has no manifest entry — restore it by its backup id instead":`--verify: backup ${t.id} carries no recorded checksum — it was taken by a release before checksums existed`),{code:u.USAGE};const a=await L(e);if(a.sha256!==t.sha256)return r.error(`--verify: ${t.file} does not match its recorded checksum (expected ${t.sha256}, got ${a.sha256}) — nothing was imported`),{code:1};r.success(`verified ${t.file} against its recorded sha256`)},Ie=async(e,t)=>{const r=await t.list();if(r.length===0)return e.logger.info(`no backups found in ${t.label}`),{code:0,entries:[]};for(const a of r)e.logger.info(`${a.id} ${a.rows.toString()} rows ${a.bytes.toString()} bytes ${a.file}`);return{code:0,entries:r}},Ue=async(e,t)=>{const{target:r}=e;if(r===void 0||r.length===0)return e.logger.error("restore requires a backup id or file path. Usage: lunora backup restore <id|file>"),{code:u.USAGE};const o=(await t.list()).find(n=>n.id===r),i=await t.materialize(o,r);if(i===void 0)return e.logger.error(`backup not found: ${r}`),{code:u.NOT_FOUND};try{if(e.verify===!0){const f=await Ne(i.path,o,e.logger);if(f!==void 0)return f}const n=await ie({cwd:e.cwd,fetchImpl:e.fetchImpl,file:i.path,logger:e.logger,prod:e.prod,replace:e.replace,token:e.token,url:e.url,yes:e.yes});return{code:n.code,entry:o,restored:n.inserted+(n.replaced??0)}}finally{await i.release().catch(n=>{e.logger.warn(`backup: could not clean up the downloaded snapshot (${n instanceof Error?n.message:String(n)})`)})}},_e=e=>{if(e.prod&&e.url===void 0)return e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)"),{refused:u.USAGE};if(e.restore===!0&&e.at===void 0&&e.bookmark===void 0)return e.logger.error("pitr --restore requires --at <time> or --bookmark <bookmark>"),{refused:u.USAGE};const t=A(e.url,e.logger,e.cwd);if(t===void 0)return{refused:u.USAGE};if(e.restore===!0&&Z({prod:e.prod,url:t})&&e.yes!==!0)return e.logger.error(`pitr --restore restores data in place at ${t}, which is not local. Re-run with --yes to confirm.`),{refused:u.USAGE};const{token:r}=E({cwd:e.cwd??process.cwd(),token:e.token,url:t});return r?{fetchImpl:e.adminFetch??T,requestUrl:`${t}${Se}`,token:r}:(e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{refused:u.AUTH})},xe=(e,t)=>{const r={};return e.at!==void 0&&(r.time=e.at),t&&e.bookmark!==void 0&&(r.bookmark=e.bookmark),t&&e.restart===!0&&(r.restart=!0),r},Re=async e=>{const t=_e(e);if(p(t))return{code:t.refused};const r=e.restore===!0,a=r?Ae:Ee,o=xe(e,r),i=r?"restore":"bookmark";e.logger.info(`POST ${t.requestUrl} -> pitr ${i}${e.shard===void 0?"":` (shard "${e.shard}")`}`);const n=await t.fetchImpl(t.requestUrl,{body:JSON.stringify({args:o,functionPath:a,shardKey:e.shard}),headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json"},method:"POST"});return{body:await y(n,e.logger),code:n.ok?0:k(n.status)}},Oe=(e,t)=>{if(e.bucket===void 0)return e.prefix!==void 0?(e.logger.error("--prefix applies only to an R2 destination — pass --bucket alongside it, or use --dir to point at a local directory."),{refused:u.USAGE}):we(m(t,e.dir??$e));if(e.dir!==void 0)return e.logger.error("--dir applies only to a local destination and does not apply alongside --bucket — drop one."),{refused:u.USAGE};if(e.prod===!0&&e.url===void 0)return e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)"),{refused:u.USAGE};const r=A(e.url,e.logger,e.cwd);if(r===void 0)return{refused:u.USAGE};const{token:a}=E({cwd:t,token:e.token,url:r});if(!a)return e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{refused:u.AUTH};const o=e.fetchImpl??T;return pe({context:{baseUrl:r,bucket:e.bucket==="default"?void 0:e.bucket,fetchImpl:o,token:a},logger:e.logger,prefix:e.prefix})},M=e=>{const t=[e.bucket===void 0?void 0:"--bucket",e.prefix===void 0?void 0:"--prefix",e.dir===void 0?void 0:"--dir"].filter(i=>i!==void 0);if(t.length>0)return e.logger.error(`${t.join(" / ")} ${t.length===1?"does":"do"} not apply here — retention and prune act on the store the worker itself is configured with (\`backupStore\`), not a destination you name.`),{refused:u.USAGE};if(e.prod===!0&&e.url===void 0)return e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)"),{refused:u.USAGE};const r=A(e.url,e.logger,e.cwd);if(r===void 0)return{refused:u.USAGE};const{token:a}=E({cwd:e.cwd??process.cwd(),token:e.token,url:r});if(!a)return e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{refused:u.AUTH};const o=e.adminFetch??T;return{baseUrl:r,fetchImpl:o,token:a}},K=(e,t)=>{e.logger.info(`backup retention would keep the newest ${t.keep.toString()} of ${t.eligible.toString()} under ${t.prefix} and delete ${t.wouldDelete.length.toString()}`);for(const r of t.wouldDelete)e.logger.info(` ${G(r)}`)},Pe=async e=>{const t=M(e);if(p(t))return{code:t.refused};const r=await t.fetchImpl(`${t.baseUrl}${F}`,{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(!r.ok)return await y(r,e.logger),{code:k(r.status)};const a=await r.json();return a.cron===void 0?(e.logger.info("no scheduled backup is configured (`backupCron`), so retention would delete nothing"),{code:0,preview:a}):a.keep<=0?(e.logger.info(`retention is off for cron "${a.cron}" (\`backupRetain\` unset) — every snapshot under ${a.prefix} is kept`),{code:0,preview:a}):(K(e,a),a.eligible===0&&e.logger.info(`no snapshot under ${a.prefix} was written by this cron, so retention has nothing of its own to remove`),{code:0,preview:a})},Be=(e,t)=>{e.logger.success(`deleted ${t.deleted.length.toString()} backup(s)`);for(const r of t.deleted)e.logger.info(` ${G(r)}`);t.failed.length>0&&e.logger.warn(`${t.failed.length.toString()} could not be removed — the snapshot may be gone with its manifest left behind; run again to retry`),t.ignored>0&&e.logger.info(`${t.ignored.toString()} were already gone by the time the delete ran`),t.remaining>0&&e.logger.info(`${t.remaining.toString()} more are past the window — run \`lunora backup prune\` again`)},De=async e=>{const t=M(e);if(p(t))return{code:t.refused};const r=await t.fetchImpl(`${t.baseUrl}${F}`,{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(!r.ok)return await y(r,e.logger),{code:k(r.status)};const a=await r.json();if(a.keep<=0||a.cron===void 0)return e.logger.error("backup prune needs a retention window: set `backupRetain` (and `backupCron`) on the worker. Without one there is nothing past the window to remove."),{code:u.USAGE,preview:a};if(a.wouldDelete.length===0)return e.logger.info(`nothing to prune — ${a.eligible.toString()} snapshot(s) under ${a.prefix} and retention keeps the newest ${a.keep.toString()}`),{code:0,preview:a};if(K(e,a),e.yes!==!0){const n=e.confirm??(J()?W:void 0);if(n===void 0)return e.logger.error("refusing to delete backups without confirmation — re-run with --yes (there is no undo for an object-store delete)"),{code:u.USAGE,preview:a};if(!await n(`delete ${a.wouldDelete.length.toString()} backup(s)? This cannot be undone. [y/N] `))return e.logger.info("nothing was deleted"),{code:0,preview:a}}const o=await t.fetchImpl(`${t.baseUrl}${ve}`,{body:JSON.stringify({confirm:a.wouldDelete}),headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json"},method:"POST"});if(!o.ok)return await y(o,e.logger),{code:k(o.status),preview:a};const i=await o.json();return Be(e,i),{code:i.failed.length>0?1:0,deleted:i.deleted,preview:a}},Ge=async(e,t)=>{try{if(e.subcommand==="pitr")return await Re(e);if(e.subcommand==="retention")return await Pe(e);if(e.subcommand==="prune")return await De(e);const r=Oe(e,t);return p(r)?{code:r.refused}:e.subcommand==="create"?await Te(e,r):e.subcommand==="list"?await Ie(e,r):await Ue(e,r)}catch(r){return e.logger.error(r instanceof Error?r.message:String(r)),{code:1}}},je=async e=>{const t=e.cwd??process.cwd(),r=await Ge(e,t);return{...r,data:{subcommand:e.subcommand,...r.entries===void 0?{}:{entries:r.entries},...r.entry===void 0?{}:{entry:r.entry},...r.restored===void 0?{}:{restored:r.restored},...r.preview===void 0?{}:{preview:r.preview},...r.deleted===void 0?{}:{deleted:r.deleted},...r.body===void 0?{}:{result:r.body}}}},Ce=e=>e==="create"||e==="list"||e==="pitr"||e==="prune"||e==="restore"||e==="retention",nr=ee(async({argument:e,cwd:t,format:r,logger:a,options:o})=>{const i=e[0];if(!Ce(i)){const f=`backup: unknown subcommand "${i??""}" — expected create | list | restore | retention | prune | pitr`;return a.error(f),{code:u.USAGE,error:f}}const n=await je({at:o.at,bookmark:o.bookmark,bucket:o.bucket,cwd:t,dir:o.dir,format:r,logger:a,prefix:o.prefix,prod:o.prod===!0,replace:o.replace===!0,restart:o.restart===!0,restore:o.restore===!0,shard:o.shard,subcommand:i,tables:o.tables,target:e[1],token:o.token,url:re({cwd:t,prod:o.prod===!0,url:o.url}),verify:o.verify===!0,yes:o.yes===!0});return{code:n.code,data:n.data,error:n.error}});export{nr as execute,je as runBackupCommand};
|
|
1
|
+
import z,{join as m,resolve as U}from"node:path";import{isInteractive as J,promptYesNo as W}from"@lunora/config";import{backupObjectKey as S,isBackupManifestEntry as G,normalizeBackupPrefix as Y,BACKUP_KEY_PREFIX as X,backupManifestKey as Q,isBackupManifestKey as V,backupObjectKeyOfManifest as j}from"@lunora/runtime";import{r as A,t as Z}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{r as T,a as I}from"../packem_shared/admin-url-DJB8P6Jh.mjs";import{d as ee}from"../packem_shared/command-B6vu47iR.mjs";import{EXIT_CODE as u,isRefusal as $,exitCodeForStatus as y}from"../packem_shared/EXIT_CODE-DVjUgIaG.mjs";import{a as re}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{runExportCommand as te}from"../packem_shared/runExportCommand-Dy6pSX68.mjs";import{b as ae,l as oe,M as _,u as ne,p as ie,a as se,r as ce}from"../packem_shared/import-C-XRRHrZ.mjs";import{readAndLogBody as p}from"./runRpcCommand.mjs";import{randomUUID as q,createHash as de}from"node:crypto";import{existsSync as N,createReadStream as ue,createWriteStream as le}from"node:fs";import{mkdir as fe,rm as k,rename as M,readFile as C,writeFile as me,realpath as R,mkdtemp as x}from"node:fs/promises";import{LunoraError as b}from"@lunora/errors";import{i as O}from"../packem_shared/path-containment-CgxYZggb.mjs";import{tmpdir as P}from"node:os";import{Readable as ge}from"node:stream";import{pipeline as he}from"node:stream/promises";const E="manifest.json",L=async e=>{const t=de("sha256");let r=0;for await(const a of ue(e)){const o=a;r+=o.byteLength,t.update(o)}return{bytes:r,sha256:t.digest("hex")}},B=async e=>{const t=m(e,E);if(!N(t))return[];let r;try{r=JSON.parse(await C(t,"utf8"))}catch(a){const o=a instanceof Error?a.message:String(a);throw new b("INTERNAL",`backup: ${t} exists but is not valid JSON (${o}) — refusing to overwrite it; fix or remove it manually`,{cause:a})}if(!Array.isArray(r))throw new TypeError(`backup: ${t} exists but is not a JSON array — refusing to overwrite it; fix or remove it manually`);return r.filter(a=>G(a))},we=async(e,t)=>{const r=m(e,`${E}.${q()}.tmp`);try{await me(r,`${JSON.stringify(t,void 0,2)}
|
|
2
|
+
`,"utf8"),await M(r,m(e,E))}catch(a){throw await k(r,{force:!0}),a}},be=async(e,t)=>{const r=U(e),a=U(r,t.file),o=()=>{throw new b("INTERNAL",`backup: entry ${t.id} points outside ${r} (${t.file}) — refusing to read it`)};if(O(r,a)||o(),!!N(a))return O(await R(r),await R(a))||o(),a},ke=e=>{const t=r=>S("",r);return{commit:async(r,a)=>{await M(a,m(e,r))},label:e,list:async()=>B(e),locate:t,materialize:async(r,a)=>{const o=i=>i===void 0?void 0:{path:i,release:()=>Promise.resolve()};return o(r===void 0?N(a)?a:void 0:await be(e,r))},record:async r=>{const a=await B(e);a.push(r),await we(e,a)},stage:async r=>{await fe(e,{recursive:!0});const a=m(e,`${t(r)}.${q()}.partial`);return{path:a,release:()=>k(a,{force:!0})}}}},ye="/_lunora/admin/storage/object",pe="/_lunora/admin/storage",D=8,$e=(e,t=z)=>{const r=t.basename(e);return r===""||r==="."||r===".."?"snapshot.ndjson":r},ve=e=>{const{context:t,logger:r}=e,a=Y(e.prefix??X),o=`bucket ${t.bucket??"(default)"} under ${a}`,i=ae(t),n=c=>`${t.baseUrl}${ye}?key=${encodeURIComponent(c)}${i}`,f=async c=>{const s=await t.fetchImpl(n(c),{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(!s.ok){const l=await s.text().catch(()=>"<no body>");throw new b("INTERNAL",`backup: could not read ${c} (HTTP ${String(s.status)}): ${l}`)}return s.text()},g=async c=>{try{const s=JSON.parse(await f(c));if(G(s))return s;r.warn(`backup: ignoring ${c} — not a backup manifest`)}catch(s){r.warn(`backup: ignoring ${c} — ${s instanceof Error?s.message:String(s)}`)}};return{commit:async(c,s,l)=>{if(l.bytes>_)throw new b("INTERNAL",`backup: the snapshot is ${String(l.bytes)} bytes, above the ${String(_)}-byte limit for a checksum-verified upload — nothing was written. Narrow it with \`--tables\`, or write it to a directory with \`--dir\` and move the file yourself (\`wrangler r2 object put\`).`);const d=await C(s);await ne(t,c,d,{contentType:"application/x-ndjson",id:c,sha256:l.sha256,size:l.bytes},r)},label:o,list:async()=>{const s=(await oe(t,a)).map(d=>d.key).filter(d=>V(d)),l=[];for(let d=0;d<s.length;d+=D){const h=await Promise.all(s.slice(d,d+D).map(async w=>g(w)));l.push(...h.filter(w=>w!==void 0))}return l.toSorted((d,h)=>d.id.localeCompare(h.id))},locate:c=>S(a,c),materialize:async(c,s)=>{const l=c?.file??s,d=await t.fetchImpl(n(l),{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(d.status===404)return;if(!d.ok||d.body===null){const v=await d.text().catch(()=>"<no body>");throw new b("INTERNAL",`backup: could not download ${l} (HTTP ${String(d.status)}): ${v}`)}const h=await x(m(P(),"lunora-backup-")),w=m(h,$e(l));try{await he(ge.from(d.body),le(w))}catch(v){throw await k(h,{force:!0,recursive:!0}),v}return{path:w,release:async()=>k(h,{force:!0,recursive:!0})}},record:async c=>{const s=Q(c.file),l=await t.fetchImpl(`${t.baseUrl}${pe}?key=${encodeURIComponent(s)}${i}`,{body:`${JSON.stringify(c,void 0,2)}
|
|
3
|
+
`,headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json"},method:"PUT"});if(!l.ok){const d=await l.text().catch(()=>"<no body>");throw new b("INTERNAL",`backup: snapshot ${c.file} was written but its manifest was not (HTTP ${String(l.status)}): ${d}`)}},stage:async c=>{const s=await x(m(P(),"lunora-backup-"));return{path:m(s,S("",c)),release:async()=>k(s,{force:!0,recursive:!0})}}}},Se=".lunora-backups",F="/_lunora/admin/backup/retention",Ee="/_lunora/admin/backup/prune",Ae="/_lunora/admin/pitr",Te="__lunora_admin__:getPitrBookmark",Ie="__lunora_admin__:pitrRestore",Ne=async(e,t)=>{const r=(e.now??(()=>new Date))().toISOString(),a=await t.stage(r);try{const o=await te({cwd:e.cwd,fetchImpl:e.fetchImpl,logger:e.logger,out:a.path,prod:e.prod,tables:e.tables,token:e.token,url:e.url});if(o.code!==0)return{code:o.code};const i=t.locate(r),n=await L(a.path);await t.commit(i,a.path,n);const f={bytes:n.bytes,createdAt:r,file:i,id:r,rows:o.rows,sha256:n.sha256,tables:e.tables};return await t.record(f),e.logger.success(`backup created: ${i} (${o.rows.toString()} rows, ${n.bytes.toString()} bytes)`),{code:0,entry:f}}finally{await a.release().catch(o=>{e.logger.warn(`backup: could not clean up staging (${o instanceof Error?o.message:String(o)})`)})}},Ue=async(e,t,r)=>{if(t?.sha256===void 0)return r.error(t===void 0?"--verify needs a recorded checksum, and a snapshot restored by path/key has no manifest entry — restore it by its backup id instead":`--verify: backup ${t.id} carries no recorded checksum — it was taken by a release before checksums existed`),{code:u.USAGE};const a=await L(e);if(a.sha256!==t.sha256)return r.error(`--verify: ${t.file} does not match its recorded checksum (expected ${t.sha256}, got ${a.sha256}) — nothing was imported`),{code:1};r.success(`verified ${t.file} against its recorded sha256`)},_e=async(e,t)=>{const r=await t.list();if(r.length===0)return e.logger.info(`no backups found in ${t.label}`),{code:0,entries:[]};for(const a of r)e.logger.info(`${a.id} ${a.rows.toString()} rows ${a.bytes.toString()} bytes ${a.file}`);return{code:0,entries:r}},Re=async(e,t)=>{const{target:r}=e;if(r===void 0||r.length===0)return e.logger.error("restore requires a backup id or file path. Usage: lunora backup restore <id|file>"),{code:u.USAGE};const o=(await t.list()).find(n=>n.id===r),i=await t.materialize(o,r);if(i===void 0)return e.logger.error(`backup not found: ${r}`),{code:u.NOT_FOUND};try{if(e.verify===!0){const f=await Ue(i.path,o,e.logger);if(f!==void 0)return f}const n=await ce({cwd:e.cwd,fetchImpl:e.fetchImpl,file:i.path,format:e.format,logger:e.logger,dryRun:e.dryRun,mode:e.mode??"require-empty",prod:e.prod,token:e.token,url:e.url,yes:e.yes});return{code:n.code,entry:o,...n.body?.plan===void 0?{}:{plan:n.body.plan},restored:n.inserted+(n.replaced??0)}}finally{await i.release().catch(n=>{e.logger.warn(`backup: could not clean up the downloaded snapshot (${n instanceof Error?n.message:String(n)})`)})}},xe=e=>{if(e.prod&&e.url===void 0)return e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)"),{refused:u.USAGE};if(e.restore===!0&&e.at===void 0&&e.bookmark===void 0)return e.logger.error("pitr --restore requires --at <time> or --bookmark <bookmark>"),{refused:u.USAGE};const t=T(e.url,e.logger,e.cwd);if(t===void 0)return{refused:u.USAGE};if(e.restore===!0&&Z({prod:e.prod,url:t})&&e.yes!==!0)return e.logger.error(`pitr --restore restores data in place at ${t}, which is not local. Re-run with --yes to confirm.`),{refused:u.USAGE};const{token:r}=A({cwd:e.cwd??process.cwd(),token:e.token,url:t});return r?{fetchImpl:e.adminFetch??I,requestUrl:`${t}${Ae}`,token:r}:(e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{refused:u.AUTH})},Oe=(e,t)=>{const r={};return e.at!==void 0&&(r.time=e.at),t&&e.bookmark!==void 0&&(r.bookmark=e.bookmark),t&&e.restart===!0&&(r.restart=!0),r},Pe=async e=>{const t=xe(e);if($(t))return{code:t.refused};const r=e.restore===!0,a=r?Ie:Te,o=Oe(e,r),i=r?"restore":"bookmark";e.logger.info(`POST ${t.requestUrl} -> pitr ${i}${e.shard===void 0?"":` (shard "${e.shard}")`}`);const n=await t.fetchImpl(t.requestUrl,{body:JSON.stringify({args:o,functionPath:a,shardKey:e.shard}),headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json"},method:"POST"});return{body:await p(n,e.logger),code:n.ok?0:y(n.status)}},Be=(e,t)=>{if(e.bucket===void 0)return e.prefix!==void 0?(e.logger.error("--prefix applies only to an R2 destination — pass --bucket alongside it, or use --dir to point at a local directory."),{refused:u.USAGE}):ke(m(t,e.dir??Se));if(e.dir!==void 0)return e.logger.error("--dir applies only to a local destination and does not apply alongside --bucket — drop one."),{refused:u.USAGE};if(e.prod===!0&&e.url===void 0)return e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)"),{refused:u.USAGE};const r=T(e.url,e.logger,e.cwd);if(r===void 0)return{refused:u.USAGE};const{token:a}=A({cwd:t,token:e.token,url:r});if(!a)return e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{refused:u.AUTH};const o=e.fetchImpl??I;return ve({context:{baseUrl:r,bucket:e.bucket==="default"?void 0:e.bucket,fetchImpl:o,token:a},logger:e.logger,prefix:e.prefix})},K=e=>{const t=[e.bucket===void 0?void 0:"--bucket",e.prefix===void 0?void 0:"--prefix",e.dir===void 0?void 0:"--dir"].filter(i=>i!==void 0);if(t.length>0)return e.logger.error(`${t.join(" / ")} ${t.length===1?"does":"do"} not apply here — retention and prune act on the store the worker itself is configured with (\`backupStore\`), not a destination you name.`),{refused:u.USAGE};if(e.prod===!0&&e.url===void 0)return e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)"),{refused:u.USAGE};const r=T(e.url,e.logger,e.cwd);if(r===void 0)return{refused:u.USAGE};const{token:a}=A({cwd:e.cwd??process.cwd(),token:e.token,url:r});if(!a)return e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{refused:u.AUTH};const o=e.adminFetch??I;return{baseUrl:r,fetchImpl:o,token:a}},H=(e,t)=>{e.logger.info(`backup retention would keep the newest ${t.keep.toString()} of ${t.eligible.toString()} under ${t.prefix} and delete ${t.wouldDelete.length.toString()}`);for(const r of t.wouldDelete)e.logger.info(` ${j(r)}`)},De=async e=>{const t=K(e);if($(t))return{code:t.refused};const r=await t.fetchImpl(`${t.baseUrl}${F}`,{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(!r.ok)return await p(r,e.logger),{code:y(r.status)};const a=await r.json();return a.cron===void 0?(e.logger.info("no scheduled backup is configured (`backupCron`), so retention would delete nothing"),{code:0,preview:a}):a.keep<=0?(e.logger.info(`retention is off for cron "${a.cron}" (\`backupRetain\` unset) — every snapshot under ${a.prefix} is kept`),{code:0,preview:a}):(H(e,a),a.eligible===0&&e.logger.info(`no snapshot under ${a.prefix} was written by this cron, so retention has nothing of its own to remove`),{code:0,preview:a})},Ge=(e,t)=>{e.logger.success(`deleted ${t.deleted.length.toString()} backup(s)`);for(const r of t.deleted)e.logger.info(` ${j(r)}`);t.failed.length>0&&e.logger.warn(`${t.failed.length.toString()} could not be removed — the snapshot may be gone with its manifest left behind; run again to retry`),t.ignored>0&&e.logger.info(`${t.ignored.toString()} were already gone by the time the delete ran`),t.remaining>0&&e.logger.info(`${t.remaining.toString()} more are past the window — run \`lunora backup prune\` again`)},je=async e=>{const t=K(e);if($(t))return{code:t.refused};const r=await t.fetchImpl(`${t.baseUrl}${F}`,{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(!r.ok)return await p(r,e.logger),{code:y(r.status)};const a=await r.json();if(a.keep<=0||a.cron===void 0)return e.logger.error("backup prune needs a retention window: set `backupRetain` (and `backupCron`) on the worker. Without one there is nothing past the window to remove."),{code:u.USAGE,preview:a};if(a.wouldDelete.length===0)return e.logger.info(`nothing to prune — ${a.eligible.toString()} snapshot(s) under ${a.prefix} and retention keeps the newest ${a.keep.toString()}`),{code:0,preview:a};if(H(e,a),e.yes!==!0){const n=e.confirm??(J()?W:void 0);if(n===void 0)return e.logger.error("refusing to delete backups without confirmation — re-run with --yes (there is no undo for an object-store delete)"),{code:u.USAGE,preview:a};if(!await n(`delete ${a.wouldDelete.length.toString()} backup(s)? This cannot be undone. [y/N] `))return e.logger.info("nothing was deleted"),{code:0,preview:a}}const o=await t.fetchImpl(`${t.baseUrl}${Ee}`,{body:JSON.stringify({confirm:a.wouldDelete}),headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json"},method:"POST"});if(!o.ok)return await p(o,e.logger),{code:y(o.status),preview:a};const i=await o.json();return Ge(e,i),{code:i.failed.length>0?1:0,deleted:i.deleted,preview:a}},qe=async(e,t)=>{try{if(e.subcommand==="pitr")return await Pe(e);if(e.subcommand==="retention")return await De(e);if(e.subcommand==="prune")return await je(e);const r=Be(e,t);return $(r)?{code:r.refused}:e.subcommand==="create"?await Ne(e,r):e.subcommand==="list"?await _e(e,r):await Re(e,r)}catch(r){return e.logger.error(r instanceof Error?r.message:String(r)),{code:1}}},Me=async e=>{const t=e.cwd??process.cwd(),r=await qe(e,t);return{...r,data:{subcommand:e.subcommand,...r.entries===void 0?{}:{entries:r.entries},...r.entry===void 0?{}:{entry:r.entry},...r.plan===void 0?{}:{plan:r.plan},...r.restored===void 0?{}:{restored:r.restored},...r.preview===void 0?{}:{preview:r.preview},...r.deleted===void 0?{}:{deleted:r.deleted},...r.body===void 0?{}:{result:r.body}}}},Ce=e=>e==="create"||e==="list"||e==="pitr"||e==="prune"||e==="restore"||e==="retention",sr=ee(async({argument:e,cwd:t,format:r,logger:a,options:o})=>{const i=e[0];if(!Ce(i)){const g=`backup: unknown subcommand "${i??""}" — expected create | list | restore | retention | prune | pitr`;return a.error(g),{code:u.USAGE,error:g}}const n=ie(o.mode,"require-empty");if(n===void 0){const g=`--mode ${String(o.mode)} is not a known mode. Expected one of: ${se.join(", ")}.`;return a.error(g),{code:u.USAGE,error:g}}const f=await Me({at:o.at,bookmark:o.bookmark,bucket:o.bucket,cwd:t,dir:o.dir,format:r,logger:a,prefix:o.prefix,dryRun:o.dryRun===!0,mode:n,prod:o.prod===!0,restart:o.restart===!0,restore:o.restore===!0,shard:o.shard,subcommand:i,tables:o.tables,target:e[1],token:o.token,url:re({cwd:t,prod:o.prod===!0,url:o.url}),verify:o.verify===!0,yes:o.yes===!0});return{code:f.code,data:f.data,error:f.error}});export{sr as execute,Me as runBackupCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d}from"../packem_shared/command-B6vu47iR.mjs";import{a as l}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{runExportCommand as m}from"../packem_shared/runExportCommand-
|
|
1
|
+
import{d}from"../packem_shared/command-B6vu47iR.mjs";import{a as l}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{runExportCommand as m}from"../packem_shared/runExportCommand-Dy6pSX68.mjs";const k=d(({argument:o,cwd:e,format:t,logger:u,options:r})=>m({cwd:e,format:t,logger:u,out:o[0]??r.out,prod:r.prod===!0,tables:r.tables,token:r.token,url:l({cwd:e,prod:r.prod===!0,url:r.url})}));export{k as execute};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d}from"../packem_shared/command-B6vu47iR.mjs";import{EXIT_CODE as
|
|
1
|
+
import{d as c}from"../packem_shared/command-B6vu47iR.mjs";import{EXIT_CODE as t}from"../packem_shared/EXIT_CODE-DVjUgIaG.mjs";import{a as i}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{I as u,p as S,a as l,r as s}from"../packem_shared/import-C-XRRHrZ.mjs";const I=c(({argument:n,cwd:a,format:f,logger:o,options:r})=>{const d=n[0];if(!d){const e="import requires a path. Usage: lunora import <file.ndjson | convex-export-dir> [--table <name>]";return o.error(e),{code:t.USAGE,error:e}}if(r.from!==void 0&&!u.includes(r.from)){const e=`--from ${r.from} is not a known source. Expected one of: ${u.join(", ")}.`;return o.error(e),{code:t.USAGE,error:e}}const m=S(r.mode,"append");if(m===void 0){const e=`--mode ${String(r.mode)} is not a known mode. Expected one of: ${l.join(", ")}.`;return o.error(e),{code:t.USAGE,error:e}}return s({batchSize:r.batchSize,cwd:a,dryRun:r.dryRun===!0,file:d,format:f,from:r.from,logger:o,mode:m,prod:r.prod===!0,scan:r.scan===!0,storageDir:r.storageDir,table:r.table,token:r.token,url:i({cwd:a,prod:r.prod===!0,url:r.url}),verify:r.verify===!0,withStorage:r.withStorage===!0,yes:r.yes===!0})});export{I as execute};
|