@lunora/cli 1.0.0-alpha.429 → 1.0.0-alpha.430
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.mjs +1 -1
- package/dist/index.d.mts +7 -1
- package/dist/index.d.ts +7 -1
- package/dist/index.mjs +1 -1
- package/dist/packem_chunks/handler.mjs +11 -17
- package/dist/packem_chunks/handler18.mjs +1 -1
- package/dist/packem_chunks/handler25.mjs +1 -99
- package/dist/packem_chunks/handler26.mjs +99 -2
- package/dist/packem_chunks/handler27.mjs +1 -1
- package/dist/packem_chunks/handler28.mjs +1 -1
- package/dist/packem_chunks/handler5.mjs +3 -3
- package/dist/packem_chunks/runDevCommand.mjs +5 -5
- package/dist/packem_shared/{COMMANDS-DtyQBrMA.mjs → COMMANDS-D7MfgxzU.mjs} +1 -1
- package/dist/packem_shared/{cli-D7VWwtaw.mjs → cli-CDNZwrAT.mjs} +1 -1
- package/dist/packem_shared/{plan-CuoEuHK9.mjs → plan-lzllz0Cn.mjs} +3 -3
- package/dist/packem_shared/{planDevCommand-opPvknj3.mjs → planDevCommand-HmQ01PRq.mjs} +1 -1
- package/dist/packem_shared/runDeployCommand-DsFzrpXY.mjs +1 -0
- package/dist/packem_shared/vectorize-metadata-BDrKVEF4.mjs +2 -0
- package/dist/packem_shared/{wrangler-secrets-CvOCvsB9.mjs → wrangler-secrets-DlSlWvRH.mjs} +1 -1
- package/package.json +9 -9
- package/dist/packem_shared/runDeployCommand-vYNbXHHs.mjs +0 -1
- package/dist/packem_shared/secret-key-8DPOH98z.mjs +0 -1
package/dist/bin.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{r as e}from"./packem_shared/cli-
|
|
2
|
+
import{r as e}from"./packem_shared/cli-CDNZwrAT.mjs";try{const r=await e();process.exit(r)}catch(r){process.stderr.write(`${r instanceof Error?r.message:String(r)}
|
|
3
3
|
`),process.exit(1)}
|
package/dist/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { CodegenOptions, Finding, FieldSnapshot, SchemaIR } from '@lunora/codegen';
|
|
2
|
-
import { DiscoveryCache, DevProcessSpawner, ensureDevVariables, ensureDevVarsExample, fillDevSecrets, startCelldDevSession, LintTool, LintIgnoreOutcome } from '@lunora/config';
|
|
2
|
+
import { CelldToolchainProbeOptions, CelldToolchainProbe, DiscoveryCache, DevProcessSpawner, ensureDevVariables, ensureDevVarsExample, fillDevSecrets, startCelldDevSession, writeCelldDevProjection, LintTool, LintIgnoreOutcome } from '@lunora/config';
|
|
3
3
|
import { materializeDevWranglerConfig, materializeServiceDevConfigs, startLocalHyperdrive, WithheldBinding } from '@lunora/config/cloudflare';
|
|
4
4
|
export { REQUIRED_COMPATIBILITY_DATE, REQUIRED_FLAG, type WranglerProjectValidationOptions as WranglerValidationOptions, type WranglerValidationReport, type WranglerProjectValidationResult as WranglerValidationResult, validateWranglerProject as validateWrangler, validateWranglerConfig } from '@lunora/config/cloudflare';
|
|
5
5
|
import { PackageManager, PackageManagerProbe } from '@lunora/config/cli';
|
|
@@ -520,6 +520,8 @@ interface ListRemoteSecretsInputs {
|
|
|
520
520
|
env?: string;
|
|
521
521
|
/** Injected command runner; defaults to a real `wrangler secret list`. */
|
|
522
522
|
runner?: SecretListRunner;
|
|
523
|
+
/** The deploy target the caller resolved (`--target`, else the config's). Defaults to the config's. */
|
|
524
|
+
target?: string;
|
|
523
525
|
/** Target a temporary-account deployment (`--temporary`). */
|
|
524
526
|
temporary?: boolean;
|
|
525
527
|
}
|
|
@@ -575,6 +577,8 @@ interface DeployCommandOptions {
|
|
|
575
577
|
apiSpec?: ApiSpec;
|
|
576
578
|
/** The Vite metafile path this run's client build keeps for `lunora build`'s copy; unset, the build's metafile is discarded. */
|
|
577
579
|
bundleMetaPath?: string;
|
|
580
|
+
/** The celld toolchain check a celld deploy runs before codegen; injected in tests. Defaults to `probeCelldToolchain`. */
|
|
581
|
+
celldToolchain?: (options: CelldToolchainProbeOptions) => Promise<CelldToolchainProbe>;
|
|
578
582
|
/**
|
|
579
583
|
* The `--env` this run's client build was given as `CLOUDFLARE_ENV`. Set only when a client build ran, so the generated config
|
|
580
584
|
* it wrote is for that environment; without it the environment's Hyperdrive id is not written into that config.
|
|
@@ -1052,6 +1056,8 @@ interface DevCommandOptions {
|
|
|
1052
1056
|
worker?: boolean;
|
|
1053
1057
|
/** `wrangler dev` port. */
|
|
1054
1058
|
workerPort?: number;
|
|
1059
|
+
/** Writes the celld projection for a `--no-worker` run; injected in tests. */
|
|
1060
|
+
writeCelldProjection?: typeof writeCelldDevProjection;
|
|
1055
1061
|
}
|
|
1056
1062
|
interface DevRemotePlan {
|
|
1057
1063
|
/** Short binding labels remoted (e.g. `"DB (D1)"`), for the banner. */
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { CodegenOptions, Finding, FieldSnapshot, SchemaIR } from '@lunora/codegen';
|
|
2
|
-
import { DiscoveryCache, DevProcessSpawner, ensureDevVariables, ensureDevVarsExample, fillDevSecrets, startCelldDevSession, LintTool, LintIgnoreOutcome } from '@lunora/config';
|
|
2
|
+
import { CelldToolchainProbeOptions, CelldToolchainProbe, DiscoveryCache, DevProcessSpawner, ensureDevVariables, ensureDevVarsExample, fillDevSecrets, startCelldDevSession, writeCelldDevProjection, LintTool, LintIgnoreOutcome } from '@lunora/config';
|
|
3
3
|
import { materializeDevWranglerConfig, materializeServiceDevConfigs, startLocalHyperdrive, WithheldBinding } from '@lunora/config/cloudflare';
|
|
4
4
|
export { REQUIRED_COMPATIBILITY_DATE, REQUIRED_FLAG, type WranglerProjectValidationOptions as WranglerValidationOptions, type WranglerValidationReport, type WranglerProjectValidationResult as WranglerValidationResult, validateWranglerProject as validateWrangler, validateWranglerConfig } from '@lunora/config/cloudflare';
|
|
5
5
|
import { PackageManager, PackageManagerProbe } from '@lunora/config/cli';
|
|
@@ -520,6 +520,8 @@ interface ListRemoteSecretsInputs {
|
|
|
520
520
|
env?: string;
|
|
521
521
|
/** Injected command runner; defaults to a real `wrangler secret list`. */
|
|
522
522
|
runner?: SecretListRunner;
|
|
523
|
+
/** The deploy target the caller resolved (`--target`, else the config's). Defaults to the config's. */
|
|
524
|
+
target?: string;
|
|
523
525
|
/** Target a temporary-account deployment (`--temporary`). */
|
|
524
526
|
temporary?: boolean;
|
|
525
527
|
}
|
|
@@ -575,6 +577,8 @@ interface DeployCommandOptions {
|
|
|
575
577
|
apiSpec?: ApiSpec;
|
|
576
578
|
/** The Vite metafile path this run's client build keeps for `lunora build`'s copy; unset, the build's metafile is discarded. */
|
|
577
579
|
bundleMetaPath?: string;
|
|
580
|
+
/** The celld toolchain check a celld deploy runs before codegen; injected in tests. Defaults to `probeCelldToolchain`. */
|
|
581
|
+
celldToolchain?: (options: CelldToolchainProbeOptions) => Promise<CelldToolchainProbe>;
|
|
578
582
|
/**
|
|
579
583
|
* The `--env` this run's client build was given as `CLOUDFLARE_ENV`. Set only when a client build ran, so the generated config
|
|
580
584
|
* it wrote is for that environment; without it the environment's Hyperdrive id is not written into that config.
|
|
@@ -1052,6 +1056,8 @@ interface DevCommandOptions {
|
|
|
1052
1056
|
worker?: boolean;
|
|
1053
1057
|
/** `wrangler dev` port. */
|
|
1054
1058
|
workerPort?: number;
|
|
1059
|
+
/** Writes the celld projection for a `--no-worker` run; injected in tests. */
|
|
1060
|
+
writeCelldProjection?: typeof writeCelldDevProjection;
|
|
1055
1061
|
}
|
|
1056
1062
|
interface DevRemotePlan {
|
|
1057
1063
|
/** Short binding labels remoted (e.g. `"DB (D1)"`), for the banner. */
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{C as o,V as a,r as n}from"./packem_shared/cli-
|
|
1
|
+
import{C as o,V as a,r as n}from"./packem_shared/cli-CDNZwrAT.mjs";import{runCodegenCommand as m}from"./packem_chunks/runCodegenCommand.mjs";import{r as p}from"./packem_chunks/handler.mjs";import{runDevCommand as f}from"./packem_chunks/runDevCommand.mjs";import{p as i}from"./packem_shared/plan-lzllz0Cn.mjs";import{runInitCommand as l}from"./packem_chunks/runInitCommand.mjs";import{runMigrateGenerateCommand as I}from"./packem_shared/runMigrateGenerateCommand-BwemPIOz.mjs";import{runResetCommand as g}from"./packem_chunks/runResetCommand.mjs";import{runRpcCommand as T}from"./packem_chunks/runRpcCommand.mjs";import{EXIT_CODE as S,exitCodeForCode as A,exitCodeForError as c,exitCodeForStatus as M}from"./packem_shared/EXIT_CODE-D_XCixv8.mjs";import{insertSchemaExtension as v}from"./packem_shared/insertSchemaExtension-DuiV6cba.mjs";import{createLogger as b,pail as O}from"./packem_shared/createLogger-4TujevyB.mjs";import{diffSnapshots as y,renderAddColumn as L,renderCreateIndex as w,renderCreateTable as B,renderDropIndex as P,renderDropTable as U,renderMigrationFile as V,validatorKindToSqlType as W}from"./packem_shared/diffSnapshots-htqNZT8Q.mjs";import{default as N}from"./packem_shared/schemaIrToSnapshot-BHuNOfgs.mjs";import{createRecordingSpawner as j,defaultSpawner as q}from"./packem_shared/createRecordingSpawner-01ZngIwK.mjs";import{default as K}from"./packem_shared/parseManifest-CwPTKdtS.mjs";import{D as Y,r as Z}from"./packem_shared/import-BRM1hs7j.mjs";import{REQUIRED_COMPATIBILITY_DATE as z,REQUIRED_FLAG as J,validateWranglerProject as $,validateWranglerConfig as rr}from"@lunora/config/cloudflare";import{b as or}from"./packem_shared/catalog-CahzmDLV.mjs";import{r as nr,a as tr,b as mr}from"./packem_shared/commands-DvSfLvyt.mjs";import{runExportCommand as pr}from"./packem_shared/runExportCommand-slAq5BCF.mjs";export{o as COMMANDS,Y as DEFAULT_IMPORT_BATCH_SIZE,S as EXIT_CODE,z as REQUIRED_COMPATIBILITY_DATE,J as REQUIRED_FLAG,a as VERSION,or as buildRegistryIndex,b as createLogger,j as createRecordingSpawner,q as defaultSpawner,y as diffSnapshots,A as exitCodeForCode,c as exitCodeForError,M as exitCodeForStatus,v as insertSchemaExtension,O as pail,K as parseManifest,i as planDevCommand,L as renderAddColumn,w as renderCreateIndex,B as renderCreateTable,P as renderDropIndex,U as renderDropTable,V as renderMigrationFile,nr as runAddCommand,tr as runBuildIndexCommand,n as runCli,m as runCodegenCommand,p as runDeployCommand,f as runDevCommand,pr as runExportCommand,Z as runImportCommand,l as runInitCommand,I as runMigrateGenerateCommand,mr as runRegistryViewCommand,g as runResetCommand,T as runRpcCommand,N as schemaIrToSnapshot,$ as validateWrangler,rr as validateWranglerConfig,W as validatorKindToSqlType};
|
|
@@ -1,25 +1,19 @@
|
|
|
1
|
-
import{mkdirSync as xe,writeFileSync as
|
|
1
|
+
import{mkdirSync as xe,writeFileSync as H,existsSync as S,readFileSync as A,rmSync as W,mkdtempSync as kr,readdirSync as Me,realpathSync as br,statSync as Fe}from"node:fs";import{dirname as M,join as k,resolve as j,relative as Z,extname as Sr,sep as oe}from"node:path";import{PROJECT_CONFIG_FILENAMES as $r,isTestPath as ae,discoverMigrations as Er,readServiceBindings as le,runCodegen as Ar}from"@lunora/codegen";import{readLinkedProject as Ue,resolveSchemaDirectory as I,startDevProcess as Tr,acceptsConnection as Rr,resolveTargetOrThrow as se,detectFramework as Dr,DEFAULT_BUNDLE_META_PATH as _r,STRICT_ADVISORIES_ENV as Pr,LAZY_FUNCTIONS_ENV as Nr,BUNDLE_META_PATH_ENV as Cr,BUILD_TARGET_ENV as Or,BUILD_ROOT_ENV as jr,canonicalPath as Ir,COMPOSED_WORKER_ENTRY as be,discoverContainerInfo as Be,D1_PLACEHOLDER_ID as Se,writeLinkedProject as Lr,discoverSchemaInfo as He,DEV_VARS_FILE as P,parseDevVariableEntries as Ge,secretSourcesFromBindings as xr,inferLunoraBindings as Ve,requiredSecrets as Mr,mintableSecretKeysFor as Fr,generateSecretValue as Ur,upsertDevVariableLine as Br,writeDevVariablesFileAtomically as Hr,isPlaceholderValue as Gr,ensureGitignoreEntries as Vr,resolveLazyFunctions as z,resolveDeployDriver as J,MissingBuildOutputError as qr,clearApiSpecMarker as Wr,createDiscoveryCache as Kr,planToolchainInvocation as qe,probeCelldToolchain as zr,runPostCodegenHook as Jr,readApiSpecMarker as Yr}from"@lunora/config";import{bindingsNeedingDatabase as Xr,findWranglerFile as L,readWranglerJsonc as N,mergeWranglerEnvironment as Y,applyModify as We,HYPERDRIVE_PLACEHOLDER_ID as Qr,warnCloudflareCliConfigOnce as Zr,validateWranglerProject as et,wranglerCodegenInputs as rt,reconcileWranglerBindings as tt,reconcileWranglerCompatibilityDate as nt,reconcileWranglerCrons as ot,describePreservedCrons as at}from"@lunora/config/cloudflare";import{Spinner as st}from"@visulima/spinner";import{r as ue,a as it,e as ct}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as dt}from"../packem_shared/api-spec-lYyq4vL6.mjs";import{i as lt,m as ut,g as gt,c as Ke,f as ft,e as mt}from"../packem_shared/vectorize-metadata-BDrKVEF4.mjs";import{w as ht}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{d as vt}from"../packem_shared/command-CB4JM-Jl.mjs";import{r as ge}from"../packem_shared/wrangler-name-Dsk5K1f-.mjs";import{a as pt}from"../packem_shared/deploy-target-resolve-BTCW1Iv4.mjs";import{EXIT_CODE as y}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{spawn as yt}from"node:child_process";import{randomUUID as ze,createHash as wt}from"node:crypto";import{setTimeout as kt}from"node:timers/promises";import{toolchainExecArgs as F,detectPackageManager as C,execArgsFor as fe}from"@lunora/config/cli";import{f as bt}from"../packem_shared/free-port-DjbFhaaT.mjs";import{containerBuildTag as St}from"@lunora/container";import{a as $t,i as Et}from"../packem_shared/docker-DpVxvYpL.mjs";import{defaultSpawner as x}from"../packem_shared/createRecordingSpawner-01ZngIwK.mjs";import{r as Je}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{p as At,H as Tt,a as Rt,r as Dt}from"../packem_shared/health-probe-Bw9JFfIy.mjs";import{runAdvisor as _t,openShardAccess as $e}from"@lunora/advisor";import{join as b,relative as U,dirname as Ye}from"@visulima/path";import{Project as Xe,SyntaxKind as p,Node as w}from"ts-morph";import{r as Pt,c as Nt}from"../packem_shared/cloudflare-credentials-BVmZnDZk.mjs";import{runMigrateDataCommand as Ct}from"../packem_shared/runMigrateGenerateCommand-BwemPIOz.mjs";import{c as Ot}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{l as jt}from"../packem_shared/wrangler-secrets-DlSlWvRH.mjs";const It=Object.freeze({edges:[],nodes:[],modules:[],unresolved:[],version:1}),Lt=20,Ee=e=>`${e.from} -${e.kind}-> ${e.to}`,V=(e,r)=>{const t=new Set(e);return r.filter(n=>!t.has(n)).toSorted((n,o)=>n.localeCompare(o))},xt=(e,r)=>{const t=e.modules.map(s=>s.name),n=r.modules.map(s=>s.name),o=e.edges.map(s=>Ee(s)),a=r.edges.map(s=>Ee(s));return{addedEdges:V(o,a),addedModules:V(t,n),removedEdges:V(a,o),removedModules:V(n,t)}},q=(e,r,t)=>{if(t.length===0)return[];const n=t.slice(0,Lt).map(a=>` ${e} ${a}`),o=t.length-n.length;return[`${r}:`,...n,...o>0?[` … and ${o.toString()} more`]:[]]},Mt=e=>{const r=[...q("+","modules added",e.addedModules),...q("-","modules removed",e.removedModules),...q("+","edges added",e.addedEdges),...q("-","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){
|
|
5
|
-
hint: if this module is part of a circular import, an import it reads is still undefined while it evaluates`:"";return` ${
|
|
6
|
-
`))},
|
|
7
|
-
`),o=`the smoke Worker did not start (${e instanceof Error?e.message:String(e)})${
|
|
8
|
-
${
|
|
9
|
-
import { loadAllFunctions } from ${JSON.stringify(
|
|
3
|
+
`)}`},Ft=(e,r)=>k(e,".lunora",r===void 0?"architecture.json":`architecture.${r}.json`),Ut=e=>{if(S(e))try{const r=JSON.parse(A(e,"utf8"));return r.version===1&&Array.isArray(r.modules)&&Array.isArray(r.edges)?r:void 0}catch{return}},Bt=e=>{const{cwd:r,environment:t,logger:n}=e,o=Ft(r,t),a=Ut(o),s=e.current??(a===void 0?void 0:It);if(s===void 0)return;const i=a===void 0?void 0:Mt(xt(a,s));return i!==void 0&&n.info(i),()=>{try{xe(M(o),{recursive:!0}),H(o,`${JSON.stringify(s,void 0,2)}
|
|
4
|
+
`,"utf8")}catch(c){n.warn(`could not record the deployed architecture at ${o}: ${c instanceof Error?c.message:String(c)}`)}}},Ht=e=>{const{cwd:r,env:t,logger:n,mintedSecretsFile:o}=e;try{const a=Ue(r),s=a?.workerName??ge(r),i=e.url??a?.workerUrl;n.success("deploy complete"),n.info(` worker: ${s??"(see wrangler output above)"}`),t!==void 0&&n.info(` env: ${t}`),i===void 0?n.info(" url: run `lunora link --url <https://your-worker>` to record it"):n.info(` url: ${i}`),o!==void 0&&n.info(` secrets: generated value(s) recorded in ${o}`),e.logsAvailable&&n.info(" logs: lunora logs")}catch{}},Gt=/\/index$/u,Vt=/[^\dA-Za-z]/gu,qt=e=>e.replace(Gt,"").split("/").map(r=>r.replaceAll(Vt,"_")),Wt=e=>qt(e).join("_"),Kt=18787,Ae=3,Qe=12e4,zt=5e3,ee=10,Jt=new Set([".js",".mjs",".mts",".ts",".tsx"]),Yt=/\(void 0\)|is not a function|before initialization|of undefined/u,Xt=e=>typeof e=="object"&&e!==null&&typeof e.functionPath=="string"&&typeof e.message=="string",Qt=e=>{const r=I(e),t=new Map;let n;try{n=Me(k(e,r),{recursive:!0,encoding:"utf8"})}catch{return t}for(const o of n){const a=Sr(o);Jt.has(a)&&!o.split(oe).some(s=>s==="_generated"||s==="node_modules")&&t.set(Wt(o.slice(0,-a.length).split(oe).join("/")),k(r,o))}return t},Zt=(e,r)=>{const t=Qt(e),n=new Map;for(const{functionPath:o,message:a}of r){const s=o.lastIndexOf(":"),i=o.slice(0,s),c=`${i}\0${a}`,d=n.get(c)??{exports:[],message:a,namespace:i};d.exports.push(o.slice(s+1)),n.set(c,d)}return[...n.values()].map(({exports:o,message:a,namespace:s})=>{const i=Yt.test(a)?`
|
|
5
|
+
hint: if this module is part of a circular import, an import it reads is still undefined while it evaluates`:"";return` ${t.get(s)??s} (${o.join(", ")}): ${a}${i}`})};class D extends Error{skipped;constructor(r,t=!1){super(r),this.skipped=t}}const en=(e,r)=>{const t=L(e),n=t===void 0?void 0:N(t).parsed;if(n===void 0)return{hasContainers:!1,main:void 0};const{merged:o}=Y(n,r);return{hasContainers:(o.containers??[]).length>0,main:o.main}},rn=({composedEntry:e,configPath:r,cwd:t,environment:n,toolchain:o})=>{if(o.devServer!=="workerd")return{skip:"this deploy target does not run on workerd"};const{hasContainers:a,main:s}=en(t,n),i=e??s;if(typeof i!="string"||i.startsWith("virtual:")||!S(j(t,i)))return{skip:"the Worker entry is not a file on disk"};if(a)return{skip:"the project declares containers, which `wrangler dev` would build locally before the real container build"};const c=Xr(t,process.env,n,r);return c.length===0?{main:i}:{skip:`the Hyperdrive binding ${c.join(", ")} has no local database for wrangler dev`}},tn=async(e,r,t)=>{const n=await fetch(`http://127.0.0.1:${String(e)}/_lunora/__smoke_load`,{signal:AbortSignal.timeout(Math.max(0,t-Date.now()))}).catch(g=>{throw g instanceof Error&&g.name==="TimeoutError"?new D(`the smoke Worker booted but did not finish evaluating the lazy modules within ${String(Qe/1e3)}s — a module may be awaiting something that never settles. Pass --no-smoke-load to ship anyway.`):g});if(n.status>=500)throw new D(`the smoke Worker booted but failed while evaluating the lazy modules (HTTP ${String(n.status)}). Pass --no-smoke-load to ship anyway.`);const o=await n.text().catch(()=>"");let a;try{a=JSON.parse(o)}catch{a=void 0}const{checked:s,failures:i,run:c}=a??{};if(typeof s=="number"&&Array.isArray(i)&&i.every(g=>Xt(g)))return c===r?{checked:s,failures:i}:void 0;const d=n.headers.get("content-type")??"no content type",u=o.replaceAll(/\s+/gu," ").trim().slice(0,120);throw new D(`the smoke Worker answered with something other than the probe's result (HTTP ${String(n.status)}, ${d}${u===""?"":`: ${u}`}). 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.`)},ie=(e,r)=>{try{process.kill(-e,r)}catch{}},Te=e=>{try{return process.kill(-e,0),!0}catch{return!1}},nn=e=>{const r=()=>{ie(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},re=async e=>{if(e===void 0)return;e.dispose();const{pid:r}=e;ie(r,"SIGTERM");const t=Date.now()+zt;for(;Te(r)&&Date.now()<t;)await kt(50);Te(r)&&ie(r,"SIGKILL")},on=e=>Tr(e).catch(async r=>{if(!await Rr(e.port))throw r}),an=(e,{checked:r,failures:t},n)=>{if(t.length===0){n.success(`${String(r)} lazy function(s) evaluate cleanly`);return}const o=Zt(e,t),a=o.length>ee?[` …and ${String(o.length-ee)} more module(s)`]:[];throw new D([`${String(t.length)} of ${String(r)} lazy function(s) fail to load:`,...o.slice(0,ee),...a,"Fix the module, or pass --no-smoke-load to ship anyway."].join(`
|
|
6
|
+
`))},sn=(e,r,t)=>{if(e instanceof D&&!e.skipped)return t.error(e.message),e.message;if(e instanceof D){t.warn(`smoke-load skipped: ${e.message}`);return}const n=r.slice(-5).join(`
|
|
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},cn=e=>{try{return xe(k(e,".lunora"),{recursive:!0}),kr(k(e,".lunora","smoke-"))}catch(r){throw new D(`could not create a directory for the check (${r instanceof Error?r.message:String(r)})`,!0)}},dn=async e=>{const{configPath:r,cwd:t,directory:n,environment:o,functionsFile:a,main:s,preferred:i,toolchain:c}=e;try{const d=k(n,"entry.ts"),u=ze();H(d,`export * from ${JSON.stringify(j(t,s))};
|
|
9
|
+
import { loadAllFunctions } from ${JSON.stringify(a)};
|
|
10
10
|
|
|
11
|
-
const runId = ${JSON.stringify(
|
|
11
|
+
const runId = ${JSON.stringify(u)};
|
|
12
12
|
|
|
13
13
|
export default {
|
|
14
14
|
async fetch() {
|
|
15
15
|
return Response.json({ ...(await loadAllFunctions()), run: runId });
|
|
16
16
|
},
|
|
17
17
|
};
|
|
18
|
-
`);const u=await vt(i),{args:d,command:f}=U(I(n),c.dev({configPath:r===void 0?void 0:Z(n,r),environment:o,extraArgs:[Z(n,l),"--local","--local-protocol","http","--ip","127.0.0.1","--port",String(u),"--persist-to",Z(n,S(t,"state"))]}));return{args:d,command:f,port:u,runId:g}}catch(l){throw new D(`could not prepare the check (${l instanceof Error?l.message:String(l)})`,!0)}},on=async e=>{const{configPath:r,cwd:n,environment:t,launcher:o,logger:s,toolchain:a}=e,i=S(n,L(n),"_generated","functions.ts");if(!b(i)||!E(i,"utf8").includes("export const loadAllFunctions"))return;const c=Yt(e);if("skip"in c){s.warn(`smoke-load skipped: ${c.skip}, so lazy modules are not evaluated before deploy`);return}const{main:l}=c,g=[];let u,d;const f=Date.now()+Xe,m=process.platform!=="win32",w=(h,A,_)=>{const $=ft(h,[...A],{cwd:_.cwd,detached:m,shell:_.shell,stdio:["ignore","pipe","pipe"]});return m&&$.pid!==void 0&&(d={dispose:Qt($.pid),pid:$.pid}),$};try{u=tn(n),s.info("smoke-loading lazy function modules in workerd");let h=Ht;for(let A=0;A<Te;A+=1){const{args:_,command:$,port:O,runId:T}=await nn({configPath:r,cwd:n,directory:u,environment:t,functionsFile:i,main:l,preferred:h,toolchain:a});h=O+1;const be=await Zt({args:_,command:$,cwd:n,spawn:o??w,label:"wrangler dev (smoke-load)",notFound:"`wrangler` was not found",onLine:G=>{g.push(G)},port:O,readyTimeoutMs:Math.max(0,f-Date.now()),shell:process.platform==="win32"});if(be===void 0){await re(d),d=void 0;continue}try{const G=await Xt(O,T,f);if(G!==void 0){en(n,G,s);return}}finally{await be.stop(),await re(d),d=void 0}}throw new D(`the smoke port was answered by other runs on all ${String(Te)} attempts`,!0)}catch(h){return rn(h,g,s)}finally{if(await re(d),u!==void 0)try{W(u,{force:!0,recursive:!0})}catch{}}},sn=(e,r)=>r===void 0?e:j(e,r),an=async e=>{if(e.targets.length===0)return{builtTags:[],code:0};if(!(e.railpackAvailable??yt)()){const t="deploy blocked: a container uses `image: { build }` (Railpack), but Railpack isn't ready. Install the `railpack` CLI and start a BuildKit instance, e.g. `docker run --rm --privileged -d --name buildkit moby/buildkit` then `export BUILDKIT_HOST=docker-container://buildkit`. Alternatively switch the container's `image` to a Dockerfile path or a pre-built registry reference.";return e.logger.error(t),{builtTags:[],code:1,error:t}}const r=e.spawner??M,n=[];for(const t of e.targets){const o=pt(t.exportName),s={args:["build",t.buildDir,"--name",o],command:"railpack",cwd:e.cwd},a=me(I(e.cwd),"wrangler",["containers","push",o]),i={args:a.args,command:a.command,cwd:e.cwd};e.logger.info(`railpack: building "${t.exportName}" → ${o} from ${t.buildDir}`);const c=await r(s);if(c.code!==0){const g=`railpack build failed for container "${t.exportName}" (${t.buildDir})`;return e.logger.error(g),{builtTags:n,code:c.code,error:g}}e.logger.info(`railpack: pushing ${o} to the Cloudflare Registry`);const l=await r(i);if(l.code!==0){const g=`wrangler containers push failed for "${t.exportName}" (${o})`;return e.logger.error(g),{builtTags:n,code:l.code,error:g}}n.push(o)}return{builtTags:n,code:0}},Qe=e=>{const n=[x(e),S(e,"package.json"),S(e,"wrangler.dev.jsonc")].filter(t=>t!==void 0&&b(t)).map(t=>[t,E(t,"utf8")]);return()=>{for(const[t,o]of n)E(t,"utf8")!==o&&C(t,o,"utf8")}},cn=(e,r=ze())=>j(e,".lunora",`vite-bundle-meta-${r}.json`),Ze="LUNORA_CLIENT_BUILD",dn="virtual:lunora/worker",de=(e,r)=>["ts","mts","cts","js","mjs","cjs"].some(n=>b(S(e,`${r}.config.${n}`))),er=e=>de(e,"rsbuild")?"rsbuild":de(e,"vite")?"vite":void 0,ln=e=>de(e,"vite")?"vite":er(e),un=e=>{try{const{scripts:r}=JSON.parse(E(S(e,"package.json"),"utf8"));return typeof r?.build=="string"&&r.build!==""}catch{return!1}},X=(e,r)=>{if(process.env[Ze]==="1")return;const n=x(e),t=n===void 0?void 0:P(n).parsed,o=t?.main===dn,s=(o?ln(e):er(e))??(un(e)?"script":void 0);if(s===void 0)return;const a=r===void 0?void 0:t?.env?.[r]?.assets?.directory,i=t?.assets?.directory??a;return o||Rr(e).class!=="C"||i!==void 0?s:void 0},gn=async(e,r,n)=>{const t=n.spawner??M,o=I(e),s=r==="script"?{args:["run","build"],command:o}:me(o,r,["build"]);n.logger.info(`running ${r} build before bundling the Worker`);const a=Qe(e),i=n.bundleMetaPath??cn(e);W(S(e,Dr),{force:!0});try{const c=await t({args:s.args,command:s.command,cwd:e,env:{[Or]:Cr(e),[Ir]:n.target,[Nr]:i,...n.lazyFunctions?{[Pr]:"1"}:{},...n.environment===void 0?{}:{CLOUDFLARE_ENV:n.environment},...n.strictAdvisories===!1?{[_r]:"0"}:{},[Ze]:"1"},stdoutToStderr:n.outputJson});return c.code===0?void 0:`${r} build failed with exit code ${String(c.code)}`}finally{a(),n.bundleMetaPath===void 0&&W(i,{force:!0})}},Q=(e,r,n)=>r!==!1&&X(e,n)!==void 0,fn=(e,r,n)=>Q(e,r,n)&&X(e,n)!=="script",he=e=>{const r=e.frameworkBuild===!1?void 0:X(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(t){return t instanceof Error?t.message:String(t)}let n;try{n=ie(e.cwd)}catch(t){return`the project's configured target cannot be used, and the ${r} plugin reads it: ${t instanceof Error?t.message:String(t)}`}if(e.target!==void 0&&e.target!==n)return`this run targets "${e.target}", but the project's target is "${n}", which the ${r} plugin reads; set it in the project config, or pass --no-framework-build`},rr=async e=>{const r=e.frameworkBuild===!1?void 0:X(e.cwd,e.environment);if(r===void 0)return;let n;try{n=e.target??ie(e.cwd)}catch(t){return t instanceof Error?t.message:String(t)}return gn(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:n})},tr="<replace-with-d1-create-id>",De=e=>Array.isArray(e)?e.filter(r=>r!=null):void 0,ve=(e,r)=>{const n=x(e);if(!n)return;const{parsed:t}=P(n);if(t===void 0)return;const{error:o,merged:s}=Y(t,r),a=o===void 0?s:t,{containers:i,d1_databases:c,vars:l}=a;return{containers:De(i),d1_databases:De(c),vars:typeof l=="object"&&l!==null&&!Array.isArray(l)?l:void 0}},mn=/^127(?:\.\d{1,3}){3}$/,hn=e=>{try{const{hostname:r}=new URL(e);return r==="localhost"||mn.test(r)||r==="::1"||r==="[::1]"}catch{return!1}},vn=e=>e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.includes("Dockerfile"),pn=(e,r,n,t="deploy",o)=>{const s=(ve(e,o)?.containers??[]).filter(i=>typeof i?.image=="string"&&vn(i.image));if(s.length===0||n())return;const a=`${t} 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},pe=e=>b(k(e,Se))?Se:void 0,yn=(e,r,n="deploy",t)=>{for(const o of Be(e,"lunora",t).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(k(e,c.path)));if(i!==void 0){const c=`${n} 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(k(e,s.buildDir))){const c=`${n} 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}}},wn=(e,r)=>(ve(e,r)?.d1_databases??[]).find(n=>n.database_id===tr)?.binding,kn=e=>{if(!e.migrate||e.dryRun||e.preview)return;if(e.migrateUrl===void 0){const n="--migrate requires --migrate-url <https://your-worker> — the deploy target URL is only known after wrangler runs, and this gate runs before it; refusing to default to localhost";return e.logger.error(n),n}if(e.migrateYes!==!0){const n="--migrate runs production data migrations after deploy. Re-run with --migrate-yes to confirm.";return e.logger.error(n),n}const r=e.migrateToken??process.env.LUNORA_ADMIN_TOKEN;if(r===void 0||r===""){const n="admin token required for --migrate — pass --migrate-token or set LUNORA_ADMIN_TOKEN";return e.logger.error(n),n}},bn=(e,r,n="deploy",t)=>{const o=wn(e,t);if(o===void 0)return;const s=`${n} blocked: the "${o}" D1 binding has a placeholder database_id ("${tr}"). Run \`wrangler d1 create <name>\` to create the database, then replace the placeholder in wrangler.jsonc with the real id before deploying.`;return r.error(s),s},Sn=(e,r,n="deploy",t)=>{const o=ve(e,t)?.vars;if(!o)return;const s=Object.entries(o).filter(([,i])=>typeof i=="string"&&hn(i)).map(([i])=>i).toSorted((i,c)=>i.localeCompare(c));if(s.length===0)return;const a=`${n} 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},$n=["vite.config.ts","vite.config.mts","vite.config.cts","vite.config.js","vite.config.mjs","vite.config.cjs",...Sr],nr=/\.(?:[cm]?[jt]s|tsx|jsx)$/u,or=/\.(?:test|spec)\.[cm]?[jt]sx?$/u,sr="allowUnauthenticatedShardAccess",En=/[\\/]/u,ar=new Set(["_generated","build","dist","node_modules"]),ir=(e,r)=>{const n=B(e,r).split(En);return nr.test(r)&&!or.test(r)&&!ae(n.join("/"))&&n.every(t=>t===".."||!t.startsWith(".")&&!ar.has(t))},_e=(e,r,n)=>{const{parsed:t}=P(r);if(t===void 0)return[];const{error:o,merged:s}=Y(t,n),{main:a}=o===void 0?s:t,i=typeof a=="string"?k(Je(r),a):void 0;return i!==void 0&&b(i)&&ir(e,i)?[i]:[]},ye=e=>e===void 0?!1:e.getKind()===v.FalseKeyword?!0:y.isParenthesizedExpression(e)||y.isAsExpression(e)||y.isSatisfiesExpression(e)||y.isTypeAssertion(e)||y.isNonNullExpression(e)?ye(e.getExpression()):!1,An=e=>{try{return Fe(e).isFile()}catch{return!1}},Tn=new Set(["ELOOP","ENOENT","ENOTDIR"]),z=(e,r,n)=>{const t=r instanceof Error&&"code"in r&&typeof r.code=="string"?r.code:"";Tn.has(t)||n.push(e)},Rn=(e,r)=>{try{return Fe(e)}catch(n){z(e,n,r);return}},cr=(e,r)=>{try{return E(e,"utf8")}catch(n){z(e,n,r);return}},dr=(e,r,n,t=new Set)=>{let o;try{o=kr(r)}catch(a){return z(r,a,n),[]}if(t.has(o))return[];t.add(o);let s;try{s=Me(r)}catch(a){return z(r,a,n),[]}return s.flatMap(a=>{const i=k(r,a),c=Rn(i,n);if(c===void 0)return[];const l=B(e,i).split(se).join("/");return c.isDirectory()?ar.has(a)||a.startsWith(".")||ae(`${l}/`)?[]:dr(e,i,n,t):c.isFile()&&nr.test(a)&&!or.test(a)&&!ae(l)?[i]:[]})},Dn=e=>{const r=y.isComputedPropertyName(e)?e.getExpression():e;return y.isStringLiteral(r)||y.isNoSubstitutionTemplateLiteral(r)?r.getLiteralValue():e.getText()},te=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],_n=/\.(?:[cm]?js|jsx)$/u,Pn=(e,r)=>{if(!r.startsWith("."))return;const n=j(Je(e),r),t=n.replace(_n,"");return[n,...te.map(s=>`${n}${s}`),...te.map(s=>k(n,`index${s}`)),...te.map(s=>`${t}${s}`)].find(s=>An(s))},Nn=e=>{if(e.getExpression().getText()!=="require")return;const[r]=e.getArguments();return r!==void 0&&(y.isStringLiteral(r)||y.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():void 0},In=e=>{const r=e.getModuleReference();if(!y.isExternalModuleReference(r))return;const n=r.getExpression();return y.isStringLiteral(n)?n.getLiteralValue():void 0},On=(e,r,n,t)=>{const o=new Set(e),s=[...e],a=[];for(let i=0;i<s.length;i+=1){const c=s[i]??"",l=cr(c,t);if(l===void 0)continue;const g=r.createSourceFile(B(n,c),l,{overwrite:!0}),u=[...g.getImportDeclarations().map(d=>d.getModuleSpecifierValue()),...g.getExportDeclarations().map(d=>d.getModuleSpecifierValue()),...g.getDescendantsOfKind(v.ImportEqualsDeclaration).map(d=>In(d)),...g.getDescendantsOfKind(v.CallExpression).map(d=>Nn(d))].filter(d=>d!==void 0);for(const d of u){const f=Pn(c,d);f!==void 0&&ir(n,f)&&!o.has(f)&&(o.add(f),a.push(f),s.push(f))}}return a},Cn=e=>{const r=e.getArgumentExpression();return r!==void 0&&(y.isStringLiteral(r)||y.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():void 0},jn=e=>y.isPropertyAccessExpression(e)?e.getName():y.isElementAccessExpression(e)?Cn(e):void 0,Ln=new Set([v.AmpersandAmpersandEqualsToken,v.AmpersandEqualsToken,v.AsteriskAsteriskEqualsToken,v.AsteriskEqualsToken,v.BarBarEqualsToken,v.BarEqualsToken,v.CaretEqualsToken,v.EqualsToken,v.GreaterThanGreaterThanEqualsToken,v.GreaterThanGreaterThanGreaterThanEqualsToken,v.LessThanLessThanEqualsToken,v.MinusEqualsToken,v.PercentEqualsToken,v.PlusEqualsToken,v.QuestionQuestionEqualsToken,v.SlashEqualsToken]),xn=e=>{const r=e.getOperatorToken().getKind();return!Ln.has(r)||jn(e.getLeft())!==sr?!1:r!==v.EqualsToken||!ye(e.getRight())},Mn=(e,r,n)=>{const t=[],o=[...new Set([L(e),"src"])].filter(u=>b(k(e,u))),s=x(e),a=[...$n.map(u=>k(e,u)).filter(u=>b(u)),...s===void 0?[]:_e(e,s,r),...n.flatMap(u=>_e(e,u,r))],i=new Ye({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}),c=o.flatMap(u=>dr(k(e,u),k(e,u),t));return{sites:[...new Set([...c,...a,...On([...a,...c],i,e,t)])].flatMap(u=>{const d=cr(u,t);if(d===void 0)return[];const f=i.createSourceFile(B(e,u),d,{overwrite:!0}),m=[...f.getDescendantsOfKind(v.PropertyAssignment),...f.getDescendantsOfKind(v.ShorthandPropertyAssignment),...f.getDescendantsOfKind(v.GetAccessor),...f.getDescendantsOfKind(v.MethodDeclaration)].filter(h=>{const A=y.isPropertyAssignment(h)&&ye(h.getInitializer());return Dn(h.getNameNode())===sr&&!A}).map(h=>h.getStartLineNumber()),w=f.getDescendantsOfKind(v.BinaryExpression).filter(h=>xn(h)).map(h=>h.getStartLineNumber());return[...m,...w].map(h=>({file:B(e,u),line:h}))}),unreadable:t}},Fn=(e,r,n,t,o,s)=>{if(n!=="deploy")return;const{sites:a,unreadable:i}=Mn(e,o,s),c=Et({openShardAccess:a,schema:{tables:[]}},{lints:[Ee]});if(c.length===0&&i.length===0)return;const l=[];if(c.length>0){const u=c.map(d=>`${String(d.metadata.file)}:${String(d.metadata.line)}`).join(", ");l.push(`${u} 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.`),t){r.warn(`deploying past the open-shard gate (--allow-open-shards): ${l.join(" ")}`);return}const g=`deploy blocked (open_shard_access): ${l.join(" ")} ${Ee.remediation}`;return r.error(g),g},Un=(e,r,n,t)=>{const o=Fn(e,r.logger,n,r.allowOpenShards===!0,r.env,t);return o===void 0?void 0:{code:p.USAGE,error:o}},Bn=(e,r,n)=>{const t=bn(e,r.logger,n,r.env);if(t!==void 0)return{code:p.USAGE,error:t};const o=Sn(e,r.logger,n,r.env);if(o!==void 0)return{code:p.USAGE,error:o};const s=yn(e,r.logger,n,r.discoveryCache);if(s!==void 0)return{code:p.USAGE,error:s};const a=pn(e,r.logger,r.dockerAvailable??wt,n,r.env);return a===void 0?void 0:{code:p.MISSING_DEPENDENCY,error:a}},Pe=32,Hn=15e3,Gn=5432,qn=3306,Vn=/[^a-z0-9-]/gu,Wn=/[^A-Za-z0-9]/gu,zn=/-$/u,H=e=>`LUNORA_${e.replaceAll(Wn,"_").toUpperCase()}_URL`,Kn=e=>{const r=new Map;for(const n of e){const t=H(n),o=r.get(t);if(o!==void 0)return{bindings:[o,n],variable:t};r.set(t,n)}},Ne=7,Jn=(e,r)=>{const n=`${e}-${r}`.toLowerCase(),t=n.replaceAll(Vn,"-");if(t===n&&t.length<=Pe)return t;const o=mt("sha256").update(n).digest("hex").slice(0,Ne-1);return`${t.slice(0,Pe-Ne).replace(zn,"")}-${o}`},Ie=e=>e==="postgresql"?"postgres":e==="mariadb"?"mysql":e,Yn=e=>e==="mysql"?qn:Gn,Xn=e=>{try{const r=new URL(e),n=r.protocol.slice(0,-1),t=decodeURIComponent(r.pathname.slice(1));return!["mariadb","mysql","postgres","postgresql"].includes(n)||r.hostname===""||t===""?void 0:{database:t,host:r.hostname,password:decodeURIComponent(r.password),port:r.port===""?Yn(Ie(n)):Number(r.port),scheme:Ie(n),user:decodeURIComponent(r.username)}}catch{return}},Qn=(e,r)=>{const n=typeof r?.password=="string"?r.password:"",t=n===""?[]:[n,JSON.stringify(n).slice(1,-1),encodeURIComponent(n)];let o=e;for(const s of t)o=o.replaceAll(s,"<redacted>");return o.split(" ").map(s=>s.includes("://")?"<url>":s).join(" ")},lr=e=>(Array.isArray(e)?e:[]).flatMap((r,n)=>{const{binding:t,id:o}=typeof r=="object"&&r!==null?r:{};return typeof t=="string"&&o===zr?[{binding:t,index:n}]:[]}),le=e=>{let r="";try{const{errors:n}=JSON.parse(e.text);r=(n??[]).flatMap(t=>typeof t.message=="string"?[t.message]:[]).slice(0,2).join("; ")}catch{}return r===""?`HTTP ${String(e.status)}`:`HTTP ${String(e.status)}: ${r}`},Zn=e=>typeof e=="string"||typeof e=="number"?e.toString():void 0,eo=["scheme","host","port","database","user"],ro=e=>e==="postgresql"?"postgres":e,Oe=(e,r)=>{const n=Zn(r);return e==="scheme"?ro(n):n},Ce=50,to=async(e,r)=>{for(let n=1;n<=Ce;n+=1){const t=await e(n===1?"/hyperdrive/configs":`/hyperdrive/configs?page=${String(n)}`);if(!t.ok)throw new Error(`listing Hyperdrive configs failed (${le(t)})`);if(!Array.isArray(t.body.result))throw new TypeError("the listing of Hyperdrive configs had no result list");const o=t.body.result.find(a=>a.name===r),s=typeof t.body.result_info=="object"&&t.body.result_info!==null?t.body.result_info:{};if(o!==void 0||typeof s.total_pages!="number"||n>=s.total_pages)return o}throw new Error(`the listing of Hyperdrive configs has more than ${String(Ce)} pages, so "${r}" can't be shown to be absent`)},no=async(e,r,n)=>{const t=await to(e,r);if(typeof t?.id=="string"){const a=eo.filter(c=>Oe(c,t.origin?.[c])!==Oe(c,n[c]));if(a.length>0)throw new Error(`a Hyperdrive config named "${r}" already exists for a different origin, or one that can't be confirmed (${a.join(", ")}). Delete it, or rename the Worker, so the binding does not reach the wrong database.`);const i=await e(`/hyperdrive/configs/${encodeURIComponent(t.id)}`,{body:JSON.stringify({origin:n}),method:"PATCH"});if(!i.ok)throw new Error(`updating its credentials failed (${le(i)})`);return{id:t.id,reused:!0}}const o=await e("/hyperdrive/configs",{body:JSON.stringify({name:r,origin:n}),method:"POST"});if(!o.ok)throw new Error(`creating it failed (${le(o)})`);const{id:s}=typeof o.body.result=="object"&&o.body.result!==null?o.body.result:{};if(typeof s!="string")throw new TypeError("the response carried no id");return{id:s,reused:!1}},oo=(e,r,n,t)=>r===void 0&&t?`${H(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 ${H(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.`:n?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.`,so=async(e,r)=>{const n=Jn(e.workerName,e.binding),{id:t,reused:o}=await no(async(s,a)=>Tt({accountId:e.accountId,apiToken:e.token,...e.fetch===void 0?{}:{fetch:e.fetch},init:{...a,signal:AbortSignal.timeout(Hn)},path:s}),n,e.origin);return e.logger.success(`${o?"reusing":"created"} Hyperdrive config "${n}" for ${e.binding} → ${e.wranglerPath}`),{id:t,text:We(r,[...e.path,e.index,"id"],t)}},ao=e=>e===void 0||e===""?void 0:e,ur=e=>{const r=S(F(e),".wrangler","deploy","config.json");try{const{configPath:n}=JSON.parse(E(r,"utf8"));return typeof n=="string"?j(F(r),n):void 0}catch{return}},io=(e,r,n,t,o)=>{const s=ur(e);if(s===void 0||s===e)return;if(t.built!==t.deployed){o.warn(`the build output ${s} was made for ${t.built===void 0?"the default environment":`"${t.built}"`}, not ${t.deployed===void 0?"the default environment":`"${t.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=P(s)}catch{return}const i=lr(a.parsed?.hyperdrive).find(c=>c.binding===r);i!==void 0&&C(s,We(a.text,["hyperdrive",i.index,"id"],n),"utf8")},co=(e,r)=>{const n=typeof e.name=="string"&&e.name!==""?e.name:"lunora";if(r===void 0)return n;const t=e.env?.[r]?.name;return typeof t=="string"&&t!==""?t:`${n}-${r}`},we=(e,r)=>{const n=x(e),t=n===void 0?void 0:P(n).parsed;if(n===void 0||t===void 0)return;const o=r===void 0?void 0:t.env?.[r],s=lr(r===void 0?t.hyperdrive:o?.hyperdrive);return s.length===0?void 0:{accountId:o?.account_id??t.account_id,entries:s,path:r===void 0?["hyperdrive"]:["env",r,"hyperdrive"],workerName:co(t,r),wranglerPath:n}},lo=(e,r,n)=>{const t=Kn(e.map(({binding:o})=>o));if(t!==void 0){const o=`deploy blocked: the Hyperdrive bindings ${t.bindings.map(s=>`"${s}"`).join(" and ")} both read ${t.variable} and would share one config. Rename one so their names differ in letters or digits, not only in punctuation.`;return n.logger.error(o),o}for(const{binding:o,origin:s,supplied:a}of e){const i=oo(o,s,r,a);if(i!==void 0&&n.dryRun===!0)n.logger.warn(`dry run: ${i} A real deploy stops here.`);else if(i!==void 0){const c=`deploy blocked: ${i}`;return n.logger.error(c),c}}},uo=async e=>{const r=we(e.cwd,e.wranglerEnvironment);if(r===void 0)return;const{entries:n,path:t,wranglerPath:o}=r,s=e.environment??process.env,{accountId:a,token:i}=At(s,r.accountId),c=n.map(({binding:g})=>{const u=s[H(g)]??"";return{binding:g,origin:Xn(u),supplied:u!==""}}),l=lo(c,i!==void 0&&a!==void 0,e);if(l!==void 0)return l;if(!(e.dryRun===!0||e.checkOnly===!0))for(const[g,{binding:u,index:d}]of n.entries()){const f=c[g]?.origin;if(!(f===void 0||i===void 0||a===void 0))try{const{id:m,text:w}=await so({accountId:a,binding:u,fetch:e.fetch,index:d,logger:e.logger,origin:f,path:t,token:i,workerName:r.workerName,wranglerPath:o},E(o,"utf8"));C(o,w,"utf8"),io(o,u,m,{built:ao(s.CLOUDFLARE_ENV),deployed:e.wranglerEnvironment},e.logger)}catch(m){const w=m instanceof Error?m.message:String(m),h=`deploy blocked: the "${u}" Hyperdrive config could not be set up: ${Qn(w,c[g]?.origin)}`;return e.logger.error(h),h}}},go=(e,r)=>{const n=we(e,r.env)?.entries[0]?.binding;if(n===void 0)return;const t=`prepare blocked: the "${n}" Hyperdrive binding still has its placeholder id. Run \`lunora deploy\` with ${H(n)} set to create the config, or put the id from \`wrangler hyperdrive create\` in wrangler.jsonc.`;return r.logger.error(t),t},fo=(e,r)=>{const n=we(e,r.env)?.entries[0]?.binding;if(n===void 0)return;const t=`deploy blocked: the "${n}" 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(t),t},gr=async(e,r,n,t,o="create")=>{if(t!=="cloudflare")return;if(n==="prepare")return go(e,r);if(r.temporary===!0)return fo(e,r);const s=r.clientBuildEnvironment===void 0?void 0:{...process.env,CLOUDFLARE_ENV:r.clientBuildEnvironment};return uo({checkOnly:o==="check",cwd:e,dryRun:r.dryRun,environment:s,logger:r.logger,wranglerEnvironment:r.env})},mo=/https?:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/u,ho=/https:\/\/[^\s"'<>]+/u,vo=e=>{if(e===void 0)return;const r=mo.exec(e);return r?r[0]:ho.exec(e)?.[0]},je=e=>e===void 0?"":` (--env ${e})`,po=({cwd:e,env:r,logger:n,now:t,url:o})=>{if(o!==void 0)try{const s=Ue(e);if(s!==void 0){if(s.workerUrl===o&&s.env===r)return;n.warn(`link: .lunora/project.json records ${s.workerUrl??"(no url)"}${je(s.env)}, but this deploy published ${o}${je(r)}. Keeping the recorded value — run \`lunora link --url ${o}${r===void 0?"":` --env ${r}`}\` to update it.`);return}const a=(t??(()=>new Date().toISOString()))();jr(e,{env:r,linkedAt:a,workerName:fe(e),workerUrl:o}),n.success(`link: recorded ${o} in .lunora/project.json (run \`lunora link\` to change)`)}catch{}},yo=async(e,r)=>{const n=new Ye({skipAddingFilesFromTsConfig:!0}),t=k(r,"lunora");let o;try{o=$r(n,t)}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 Rt(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},wo=async(e,r)=>{const{info:n}=He(r,"lunora",e.discoveryCache),t=n?.vectorMetadata??[];if(t.length===0)return;const o=[];for(const i of t){const c=st(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 at({cwd:r,entries:o,exec:me(I(r),"wrangler",[]),logger:e.logger,spawner:e.spawner??M})).filter(i=>i.status!=="failed").length;a>0&&e.logger.success(`vectorize metadata indexes ready: ${String(a)}/${String(o.length)}`)},Le=5,ko=2e3,bo=async(e,r,n)=>{if(e.healthCheck!==!0)return;const t=n??Ke({cwd:r,env:e.env});if(t===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 kt({attempts:Le,baseUrl:t,delayMs:ko,fetchImpl:e.healthFetch,paths:[bt,St],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})},So=async(e,r,n,t,o,s)=>{await wo(e,r);const a=e.migrate?await yo(e,r):0;return a===0&&o?.(),{code:a,descriptor:n,mintedSecretsFile:s,validation:t}},$o=async({cwd:e,descriptor:r,mintedSecretsFile:n,options:t,reblessSchemaBaseline:o,recordArchitecture:s,stdout:a,validation:i})=>{const c={deployedAt:new Date().toISOString(),dryRun:t.dryRun===!0,env:t.env,preview:t.preview===!0,url:t.dryRun===!0?void 0:vo(a),workerName:fe(e)};if(t.dryRun===!0||t.preview===!0)return t.healthCheck===!0&&t.logger.warn(`--health-check skipped: ${t.dryRun===!0?"a dry run publishes nothing":"a preview version serves no live traffic"}`),{code:0,deployment:c,descriptor:r,mintedSecretsFile:n,validation:i};t.temporary!==!0&&(s?.(),po({cwd:e,env:t.env,logger:t.logger,url:c.url}));const l=await bo(t,e,c.url);return l?.error!==void 0?{code:p.UNAVAILABLE,deployment:c,descriptor:r,healthCheck:l,mintedSecretsFile:n,validation:i}:{...await So(t,e,r,i,o,n),deployment:c,healthCheck:l}},Eo=(e,r,n)=>{const t=k(e,N);if(!b(t))return;let o;try{o=Ge(E(t,"utf8")).length}catch{return}if(o===0)return;const s=n.toolchain?.secretPut!==void 0;r.warn(s?`Note: \`lunora deploy\` does not push secrets. ${N} has ${String(o)} key(s); if you changed them, run \`lunora env push --yes\` to update the deployed secrets.`:`Note: ${n.name} deploys read no secrets. ${N} has ${String(o)} key(s) that only the dev server sees; put the values the deployed worker needs in wrangler \`vars\`.`)},Ao=async(e,r)=>{let n=[];try{n=Lr(await qe({cache:r,projectRoot:e,schemaDir:L(e)}))}catch{}const t=xr(n).map(s=>s.key);let o=[];try{const s=k(e,N);b(s)&&(o=Ge(E(s,"utf8")).map(a=>a.key).filter(a=>it(a)))}catch{}return[...new Set([...t,...o])]},To=async(e,r,n,t)=>{const{logger:o}=r,s=r.spawner??M,a=I(e),i=r.env===void 0?"":` --env ${r.env}`,c=t.toolchain?.secretPut;if(c===void 0)return o.error(`deploy target "${t.id}" has no secret store; cannot push secrets`),{minted:[],ok:!1};const l=n.map(d=>({key:d,value:Mr()})),g=t.toolchain?.secretBulk;if(g!==void 0&&l.length>=2){const d=U(a,g({environment:r.env,temporary:r.temporary})),f=await s({args:d.args,command:d.command,cwd:e,input:JSON.stringify(Object.fromEntries(l.map(m=>[m.key,m.value])))});if(f.code===0){for(const{key:m}of l)o.success(`generated + pushed ${m}`);return{minted:l,ok:!0}}o.warn(`bulk secret push failed (exit ${String(f.code)}); retrying one key at a time`)}const u=[];for(const{key:d,value:f}of l){const m=c({environment:r.env,key:d,temporary:r.temporary}),w=U(a,m),h=await s({args:w.args,command:w.command,cwd:e,input:f});if(h.code!==0)return o.error(`failed to push secret ${d} (exit ${String(h.code)}); set it manually with \`wrangler secret put ${d}${i}\`.`),{minted:u,ok:!1};u.push({key:d,value:f}),o.success(`generated + pushed ${d}`)}return{minted:u,ok:!0}},Ro=/^[\w-]+$/u,ne=[".dev.vars",".dev.vars.*","!.dev.vars.example"],Do=/\r?\n/u,_o=(e,r)=>{const n=k(e,".gitignore");try{const t=b(n)?E(n,"utf8"):"",o=new Set(t.split(Do).map(c=>c.trim())),s=ne.filter(c=>!o.has(c));if(s.length===0)return;const a=s.some(c=>!c.startsWith("!"))?[...s.filter(c=>!c.startsWith("!")),...ne.filter(c=>c.startsWith("!"))]:s,i=t.length>0&&!t.endsWith(`
|
|
19
|
-
`)
|
|
20
|
-
`:"";C(n,`${t}${i}
|
|
21
|
-
# Lunora — never commit a minted secret
|
|
22
|
-
${a.join(`
|
|
23
|
-
`)}
|
|
24
|
-
`,"utf8"),r.info(`.gitignore: added ${s.join(", ")} so the recorded secret cannot be committed`)}catch(t){r.warn(`could not update .gitignore (${t instanceof Error?t.message:String(t)}) — add \`${ne.join("` and `")}\` by hand before committing.`)}},Po=(e,r,n)=>{if(n.length===0)return;const t=n.map(i=>i.key).join(", ");if(r.env!==void 0&&!Ro.test(r.env)){r.logger.warn(`${t}: minted and pushed for --env ${r.env}, but "${r.env}" isn't a safe filename fragment — the value could not be recorded. Capture it manually if you need it again.`);return}const o=r.env===void 0?N:`${N}.${r.env}`;_o(e,r.logger);const s=k(e,o);let a=b(s)?E(s,"utf8"):"";for(const i of n)a=Fr(a,i.key,i.value);return Ur(s,a),r.logger.success(r.env===void 0?`${t}: value(s) recorded in ${o}`:`${t}: value(s) recorded in ${o} (kept separate from ${N} so \`lunora dev\` and a plain \`lunora env push\` don't inherit the --env ${r.env} value)`),o},No=async(e,r,n,t)=>{if(r.dryRun===!0||r.preview===!0)return{};const{logger:o}=r,s=r.env===void 0?"":` --env ${r.env}`;let a;try{a=await(r.secretLister??_t)({cwd:e,env:r.env,temporary:r.temporary})}catch{return{}}if(!a.ok)return{};const i=new Set(a.names),l=(await Ao(e,r.discoveryCache)).filter(d=>!i.has(d));if(l.length===0)return{};if(!n)return{error:`missing required secret(s) on the deploy target: ${l.join(", ")}. Set them with \`wrangler secret put <KEY>${s}\` (or \`lunora env generate --set\` then \`lunora env push --yes${s}\`), then re-deploy.`};for(const d of l.filter(f=>!$e(f)))o.warn(`required secret ${d} is not set on the target — set it with: wrangler secret put ${d}${s}`);const g=l.filter(d=>$e(d));if(g.length===0)return{};if(await(r.secretConfirm??Dt())(`${String(g.length)} required secret(s) not set on the target (${g.join(", ")}). Generate strong values and push them now?`)){const{minted:d,ok:f}=await To(e,r,g,t),m=Po(e,r,d);return f?{mintedSecretsFile:m}:{error:"failed to push required secret(s) — set them manually and re-deploy",mintedSecretsFile:m}}return o.warn(`${String(g.length)} required secret(s) not set on the target: ${g.join(", ")}. Generate + push with \`lunora env generate --set\` then \`lunora env push --yes${s}\`.`),{}},fr=e=>e.format==="json"?!1:e.interactive!==void 0?e.interactive:process.stdout.isTTY&&!process.env.CI,Io=async(e,r)=>{if(r.dryRun===!0)return;const n=Be(e,"lunora",r.discoveryCache).containers.flatMap(o=>o.schedulingPolicy===void 0&&o.image.kind==="build"?[{buildDir:o.image.buildDir,exportName:o.exportName}]:[]);if(n.length===0)return;const t=await an({cwd:e,logger:r.logger,railpackAvailable:r.railpackAvailable,spawner:r.spawner,targets:n});return t.code===0?void 0:t.error??"railpack build failed"},Oo=(e,r,n)=>{if(n!==void 0)try{const t=Zr(e,n);t.changed&&r.success(`synced ${String(n.length)} cron trigger(s) → ${t.wranglerPath??"wrangler.jsonc"}`);for(const s of t.warnings)r.warn(s);const o=et(t.preserved);o!==void 0&&r.info(o)}catch(t){const o=t instanceof Error?t.message:String(t);r.warn(`cron trigger sync skipped: ${o}`)}},Co=async(e,r,n,t,o,s)=>{try{J(t);const a=await qe({cache:s,projectRoot:e,schemaDir:L(e)}),i=Xr(e,a,{environment:o,target:t}),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:g,updated:u}=i.devConfig;r.success(`dev sidecar bindings: ${[...l,...u].join(", ")} → ${g}`)}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=Qr(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}`)}Oo(e,r,n)},jo=async(e,r,n,t,o,s,a,i,c,l)=>{let g;r?(g=new rt({name:"dots"}),g.start("running codegen")):n.info("running codegen");try{const u=Er({apiSpec:t,dryRun:!l,lazyFunctions:o,projectRoot:e,target:s,...Yr(e)});g?.succeed("codegen complete"),g||n.success("codegen complete");const d=tt(u.platformDiagnostics,n);if(d.errors.length>0)return{error:d.errors.join("; ")};const{errorAdvisories:f,names:m,shouldBlock:w}=nt(u.advisories,c);if(w){const A=`${f.length.toString()} ERROR-level ${f.length===1?"advisory":"advisories"} (${m.join(", ")}). Pass --no-strict-advisories to downgrade this to a warning and continue.`;return n.error(A),{error:A}}const h=l?await qr({cwd:e,logger:n,spawner:a,stdoutToStderr:i}):void 0;return h?.error!==void 0?{error:h.error}:{result:u}}catch(u){g?.failed("codegen failed");const d=u instanceof Error?u.message:String(u);return n.error(`codegen failed: ${d}`),{error:`codegen failed: ${d}`}}},Lo=(e,r)=>({dryRun:r.dryRun,entry:pe(e),environment:r.env,outDir:r.outDir,preview:r.preview,temporary:r.temporary}),mr=(e,r,n)=>{const{toolchain:t}=n;if(t===void 0)throw new Error(`deploy target "${n.id}" has no command-line toolchain`);const o=Lo(e,r);return Ve(n,e,"deploy",s=>t.deploy({...o,configPath:s}))},xo=(e,r,n)=>{const t=mr(e,r,n),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}`),t.commit(),t.projection!==void 0&&t.projection.dropped.length>0&&r.logger.warn(`${n.name} ignores these wrangler keys, so they were left out of ${t.projection.configPath}: ${t.projection.dropped.join(", ")}`),t.command},R={problems:[],wranglerPath:void 0},oe=(e,r)=>({code:p.USAGE,descriptor:void 0,error:e,validation:R,...r}),Mo=(e,r)=>{for(const n of e.report?.warnings??[])r.warn(`wrangler.jsonc: ${n}`);if(e.problems.length===0)return!1;r.error("wrangler.jsonc validation failed:");for(const n of e.problems)r.error(` - ${n}`);return!0},Fo=(e,r,n)=>{const t=r.format==="json",o=r.dryRun!==!0,s=xo(e,r,n),a=U(I(e),s);return{args:a.args,captureStdout:o&&!t,captureStdoutSilently:o&&t,command:a.command,cwd:e,stdoutToStderr:t&&!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"},Uo=(e,r)=>ke(r)===void 0?ue(e).services.map(n=>n.wranglerPath):[],hr=(e,r,n,t,o)=>({cwd:e,environment:r.env,frameworkBuild:t,lazyFunctions:K(r.lazyFunctions),logger:r.logger,outputJson:r.format==="json"||r.clientBuildOutputJson===!0,spawner:o,strictAdvisories:ge(r),target:n.id}),Bo=(e,r,n)=>{const{toolchain:t}=n,o=t===void 0?`target "${n.id}" has no deploy command`:ke(r);if(o!==void 0||t===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 t},vr=(e,r)=>{for(const n of e){const t=he(r(F(n.wranglerPath)));if(t!==void 0)return`service ${n.name} (${n.worker}): ${t}`}},Ho=(e,r,n)=>{const{error:t,services:o}=ue(e);if(t!==void 0||o.length===0)return;const s=J(n);if(s.toolchain===void 0||ke(r)!==void 0)return;const a=r.skipCodegen===!0?!1:r.frameworkBuild,i=[...new Map(o.map(c=>[c.wranglerPath,c])).values()];return vr(i,c=>hr(c,r,s,a,M))},pr=(e,r,n)=>{const t=e.cwd??process.cwd(),o=gt(t,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{mr(t,e,J(o.target))}catch(i){if(!(n&&i instanceof Br&&Q(t,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 s=e.openShardGatePassed===!0?void 0:Un(t,e,r,Uo(t,e));if(s!==void 0)return{kind:"refused",code:s.code,error:s.error,validation:R};const a=Ho(t,e,o.target);return a!==void 0?(e.logger.error(a),{kind:"refused",code:p.USAGE,error:a,validation:R}):{kind:"ok",target:o.target}},Go=(e,r)=>e.apiSpec??(e.clientBuildRan===!0?Vr(r):void 0),qo=async(e,r)=>{const n=e.cwd??process.cwd(),t=fr(e),o=ge(e),s={problems:[],wranglerPath:void 0},a=pr(e,r,!1);if(a.kind==="refused")return{code:a.code,error:a.error,validation:a.validation};const{target:i}=a;let c;if(!e.skipCodegen){const m=await jo(n,t,e.logger,Go(e,n),K(e.lazyFunctions),i,e.spawner,e.format==="json",o,e.clientBuildRan!==!0);if(m.error!==void 0)return{error:m.error,target:i,validation:R};c=m.result,e.discoveryCache?.clear()}let l;if(c!==void 0){const m=$t({allowDrift:e.allowSchemaDrift===!0,codegen:c,command:r,logger:e.logger,updateBaseline:e.updateSchemaBaseline===!0});if(m.blocked)return{error:`schema drift gate blocked ${r}`,schemaDrift:{blocked:!0,reason:m.reason},target:i,validation:s};l=m.rebless}const g=c&&Lt({current:c.architecture,cwd:n,environment:e.env,logger:e.logger});await Co(n,e.logger,c?.cronTriggers,i,e.env,e.discoveryCache);const u=await gr(n,e,r,i,"check");if(u!==void 0)return{error:u,target:i,validation:R};const d=Bn(n,e,r);if(d!==void 0)return{code:d.code,error:d.error,target:i,validation:R};const f=Jr({environment:e.env,projectRoot:n});return Mo(f,e.logger)?{error:"wrangler validation failed",target:i,validation:f}:{codegen:c,reblessSchemaBaseline:l,recordArchitecture:g,target:i,validation:f}},Vo=e=>{W(S(e,".wrangler","deploy","config.json"),{force:!0})},Wo=async(e,r,n)=>{const t=he(e);if(t!==void 0)return{built:!1,error:t};const o=Q(e.cwd,r,n);return o&&Vo(e.cwd),{built:o,error:await rr(e)}},zo=(e,r,n)=>r||n===!1?ur(e):void 0,Ko=async(e,r,n,t)=>{const{error:o,services:s}=ue(e);if(o!==void 0)return{code:p.FAILURE,error:o};if(s.length===0)return;const a=Bo(s,r,n);if(a===void 0)return;const i=I(e),c=[...new Map(s.map(d=>[d.wranglerPath,d])).values()],l=r.skipCodegen===!0?!1:r.frameworkBuild,g=d=>hr(d,r,n,l,t),u=vr(c,g);if(u!==void 0)return r.logger.error(u),{code:p.USAGE,error:u};for(const d of c){const f=F(d.wranglerPath),m=g(f),{built:w,error:h}=await Wo(m,l,r.env);if(h!==void 0){const T=`service ${d.name} (${d.worker}): ${h}`;return r.logger.error(T),{code:p.FAILURE,error:T}}const A=zo(d.wranglerPath,w,l);let _;try{_=Ve(n,f,"deploy",T=>a.deploy({configPath:T??A??d.wranglerPath,dryRun:r.dryRun===!0,environment:r.env}))}catch(T){return{code:p.FAILURE,error:`service ${d.name} (${d.worker}): ${T instanceof Error?T.message:String(T)}`}}_.commit();const $=U(i,_.command);r.logger.info(`deploying service ${d.name} (${d.worker}) via ${$.command} ${$.args.join(" ")}`);const O=await t({args:$.args,command:$.command,cwd:f,stdoutToStderr:r.format==="json"});if(O.code!==0)return{code:p.FAILURE,error:`service ${d.name} (${d.worker}): ${$.command} ${$.args.join(" ")} exited ${String(O.code)} — stopping before the app`}}},Jo=async(e,r,n,t)=>{if(r!=="cloudflare")return;const o=e===void 0?void 0:P(e).parsed,s=(n===void 0?void 0:o?.env?.[n]?.account_id)??o?.account_id,a=await dt({accountId:s});(a.verdict==="near"||a.verdict==="full")&&t.warn(a.fix===void 0?a.message:`${a.message} ${a.fix}`)},Yo=e=>e.dryRun!==!0&&e.temporary!==!0,Xo=e=>e.temporary===!0?"temporary":e.dryRun===!0?"preview":"defer",Qo=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},Zo=(e,r,n)=>{const t=[];for(const o of e)if(o.verdict==="ok")o.changesAccount===!0&&r.info(o.message);else if(o.verdict==="unchecked"&&n==="preview")r.warn(`dry run: ${o.message}${o.fix===void 0?"":` ${o.fix}`} A real deploy stops here.`);else{const s=Qo(o);r.error(s),t.push(s)}return t},yr=async(e,r,n,t,o,s,a)=>{const i=n==="cloudflare"&&r!==void 0?P(r).parsed:void 0;if(i===void 0)return;const c=(Y(i,t).merged.artifacts??[]).flatMap(m=>typeof m?.binding=="string"&&typeof m.namespace=="string"?[{binding:m.binding,namespace:m.namespace}]:[]),l=c.length===0?void 0:He(e,L(e),s).info?.jurisdiction;if(l===void 0)return;const g=[...new Map(c.map(m=>[m.namespace,m])).values()];if(a==="temporary"){o.warn(`--temporary deploys to a throwaway account, so the jurisdiction ("${l}") of Artifacts namespace ${g.map(m=>`"${m.namespace}"`).join(", ")} was not checked: it is created there on first use, in no jurisdiction.`);return}const u=(t===void 0?void 0:i.env?.[t]?.account_id)??i.account_id,d=await Promise.all(g.map(async m=>ct({...m,accountId:u,create:a==="create",jurisdiction:l,missingOk:a==="defer"||a==="preview"}))),f=Zo(d,o,a);return f.length===0?void 0:f.join(`
|
|
25
|
-
`)},es=async(e,r,n,t,o,s)=>{const a=Yo(r)?await yr(e,s,o,r.env,r.logger,r.discoveryCache,"create"):void 0;if(a!==void 0)return{code:p.FAILURE,error:a};const i=await gr(e,r,"deploy",o);return i!==void 0?{code:p.FAILURE,error:i}:Ko(e,r,n,t)},rs=async(e,r,n,t)=>{if(!(r.smokeLoad===!1||n.toolchain===void 0))return on({composedEntry:pe(e),configPath:t,cwd:e,environment:r.env,launcher:r.smokeLauncher,logger:r.logger,toolchain:n.toolchain})},ts=async e=>{const r={...e,discoveryCache:e.discoveryCache??Gr()},n=r.cwd??process.cwd(),t=fr(r),o=await qo(r,r.commandName??"deploy");if(o.error!==void 0){if(o.validation.problems.length>0)return{code:p.USAGE,descriptor:void 0,error:o.error,validation:o.validation};const h=o.schemaDrift===void 0?void 0:{schemaDrift:o.schemaDrift};return oe(o.error,{...h,...o.code===void 0?{}:{code:o.code}})}const{validation:s}=o,a=J(o.target),i=kn(r)??await yr(n,s.wranglerPath,o.target,r.env,r.logger,r.discoveryCache,Xo(r))??await rs(n,r,a,s.wranglerPath);if(i!==void 0)return oe(i);const c=a.toolchain?.prebuildsContainerImages===!0?await Io(n,r):void 0;if(c!==void 0)return oe(c);Eo(n,r.logger,a),Kr(n,h=>{r.logger.warn(h)}),await Jo(s.wranglerPath,o.target,r.env,r.logger);const{error:l,mintedSecretsFile:g}=await No(n,r,t,a);if(l!==void 0)return r.logger.error(l),{code:p.USAGE,descriptor:void 0,error:l,mintedSecretsFile:g,validation:s};const u=r.spawner??M,d=await es(n,r,a,u,o.target,s.wranglerPath);if(d!==void 0)return{code:d.code,descriptor:void 0,error:d.error,mintedSecretsFile:g,validation:s};const f=Fo(n,r,a);r.logger.info(`deploying via ${f.command} ${f.args.join(" ")}`);const m=await u(f);return f.captureStdoutSilently===!0&&m.stdout!==void 0&&m.stdout!==""&&process.stderr.write(m.stdout),m.code!==0?{code:m.code,descriptor:f,mintedSecretsFile:g,validation:s}:{...await $o({...o,cwd:n,descriptor:f,mintedSecretsFile:g,options:r,stdout:m.stdout}),logsAvailable:a.toolchain?.tail!==void 0}},ns=async e=>{const{logger:r}=e,n=e.cwd??process.cwd(),t={apiSpec:e.apiSpec,cwd:n,environment:e.env,bundleMetaPath:e.bundleMetaPath,frameworkBuild:e.skipCodegen===!0?!1:e.frameworkBuild,strictAdvisories:ge(e),lazyFunctions:K(e.lazyFunctions),logger:r,outputJson:e.format==="json"||e.clientBuildOutputJson===!0,spawner:e.spawner,target:e.target},o=he(t);if(o!==void 0)return r.error(o),{code:p.USAGE,descriptor:void 0,error:o,validation:R};Hr(n);const s=await rr(t);if(s!==void 0)return r.error(s),{code:p.FAILURE,descriptor:void 0,error:s,validation:R}},os=(e,r)=>{const n=r.skipCodegen===!0?!1:r.frameworkBuild;return Q(e,n,r.env)?r.env:void 0},ss=async e=>{const{logger:r}=e,n=e.cwd??process.cwd(),t=pr(e,e.commandName??"deploy",!0);if(t.kind==="refused")return{code:t.code??p.USAGE,descriptor:void 0,error:t.error,validation:t.validation};const o=await ns(e);if(o!==void 0)return o;const s=e.dryRun===!0?Qe(n):void 0;let a;try{if(a=await ts({...e,clientBuildEnvironment:os(n,e),clientBuildRan:fn(n,e.skipCodegen===!0?!1:e.frameworkBuild,e.env),logger:r,openShardGatePassed:!0}),a.code===0&&e.emitBindings!==void 0){const{error:i}=lt({destination:e.emitBindings,logger:r,projectRoot:e.cwd??process.cwd()});i!==void 0&&(r.error(i),a={...a,code:p.USAGE})}}finally{s?.()}if(e.format==="json")return a;if(a.code===0&&e.dryRun!==!0&&e.preview!==!0)xt({cwd:e.cwd??process.cwd(),env:e.env,logger:e.logger,logsAvailable:a.logsAvailable===!0,mintedSecretsFile:a.mintedSecretsFile,url:a.deployment?.url});else if(a.code===0&&e.preview===!0){const i=a.deployment?.url;e.logger.success(i===void 0?"preview version uploaded":`preview version uploaded — ${i}`)}return a},xs=ut(async({cwd:e,format:r,logger:n,options:t})=>{const o=sn(e,t.root),s=await ss({allowOpenShards:t.allowOpenShards===!0,allowSchemaDrift:t.allowSchemaDrift===!0,apiSpec:ot(t.apiSpec),frameworkBuild:t.prebuilt===!0?!1:t.frameworkBuild,lazyFunctions:K(t.lazyFunctions),cwd:o,dryRun:t.dryRun===!0,env:t.env,format:r,healthCheck:t.healthCheck===!0,logger:n,migrate:t.migrate===!0,migrateToken:t.migrateToken,migrateUrl:Ke({cwd:o,env:t.env,url:t.migrateUrl}),migrateYes:t.migrateYes===!0,preview:t.preview===!0,skipCodegen:t.prebuilt===!0,skipServices:t.skipServices===!0,smokeLoad:t.smokeLoad,strictAdvisories:t.strictAdvisories,target:t.target,temporary:t.temporary===!0,updateSchemaBaseline:t.updateSchemaBaseline===!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{qo as a,Co as b,xs as e,sn as p,ss as r,rs as s,cn as v};
|
|
18
|
+
`);const g=await bt(i),{args:l,command:m}=F(C(t),c.dev({configPath:r===void 0?void 0:Z(t,r),environment:o,extraArgs:[Z(t,d),"--local","--local-protocol","http","--ip","127.0.0.1","--port",String(g),"--persist-to",Z(t,k(n,"state"))]}));return{args:l,command:m,port:g,runId:u}}catch(d){throw new D(`could not prepare the check (${d instanceof Error?d.message:String(d)})`,!0)}},ln=async e=>{const{configPath:r,cwd:t,environment:n,launcher:o,logger:a,toolchain:s}=e,i=k(t,I(t),"_generated","functions.ts");if(!S(i)||!A(i,"utf8").includes("export const loadAllFunctions"))return;const c=rn(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,u=[];let g,l;const m=Date.now()+Qe,f=process.platform!=="win32",v=(h,E,_)=>{const $=yt(h,[...E],{cwd:_.cwd,detached:f,shell:_.shell,stdio:["ignore","pipe","pipe"]});return f&&$.pid!==void 0&&(l={dispose:nn($.pid),pid:$.pid}),$};try{g=cn(t),a.info("smoke-loading lazy function modules in workerd");let h=Kt;for(let E=0;E<Ae;E+=1){const{args:_,command:$,port:O,runId:T}=await dn({configPath:r,cwd:t,directory:g,environment:n,functionsFile:i,main:d,preferred:h,toolchain:s});h=O+1;const ke=await on({args:_,command:$,cwd:t,spawn:o??v,label:"wrangler dev (smoke-load)",notFound:"`wrangler` was not found",onLine:G=>{u.push(G)},port:O,readyTimeoutMs:Math.max(0,m-Date.now()),shell:process.platform==="win32"});if(ke===void 0){await re(l),l=void 0;continue}try{const G=await tn(O,T,m);if(G!==void 0){an(t,G,a);return}}finally{await ke.stop(),await re(l),l=void 0}}throw new D(`the smoke port was answered by other runs on all ${String(Ae)} attempts`,!0)}catch(h){return sn(h,u,a)}finally{if(await re(l),g!==void 0)try{W(g,{force:!0,recursive:!0})}catch{}}},un=(e,r)=>r===void 0?e:j(e,r),gn=async e=>{if(e.targets.length===0)return{builtTags:[],code:0};if(!(e.railpackAvailable??$t)()){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=St(n.exportName),a={args:["build",n.buildDir,"--name",o],command:"railpack",cwd:e.cwd},s=fe(C(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 u=`railpack build failed for container "${n.exportName}" (${n.buildDir})`;return e.logger.error(u),{builtTags:t,code:c.code,error:u}}e.logger.info(`railpack: pushing ${o} to the Cloudflare Registry`);const d=await r(i);if(d.code!==0){const u=`wrangler containers push failed for "${n.exportName}" (${o})`;return e.logger.error(u),{builtTags:t,code:d.code,error:u}}t.push(o)}return{builtTags:t,code:0}},Ze=e=>{const t=[L(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")}},fn=(e,r=ze())=>j(e,".lunora",`vite-bundle-meta-${r}.json`),er="LUNORA_CLIENT_BUILD",mn="virtual:lunora/worker",ce=(e,r)=>["ts","mts","cts","js","mjs","cjs"].some(t=>S(k(e,`${r}.config.${t}`))),rr=e=>ce(e,"rsbuild")?"rsbuild":ce(e,"vite")?"vite":void 0,hn=e=>ce(e,"vite")?"vite":rr(e),vn=e=>{try{const{scripts:r}=JSON.parse(A(k(e,"package.json"),"utf8"));return typeof r?.build=="string"&&r.build!==""}catch{return!1}},X=(e,r)=>{if(process.env[er]==="1")return;const t=L(e),n=t===void 0?void 0:N(t).parsed,o=n?.main===mn,a=(o?hn(e):rr(e))??(vn(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||Dr(e).class!=="C"||i!==void 0?a:void 0},pn=async(e,r,t)=>{const n=t.spawner??x,o=C(e),a=r==="script"?{args:["run","build"],command:o}:fe(o,r,["build"]);t.logger.info(`running ${r} build before bundling the Worker`);const s=Ze(e),i=t.bundleMetaPath??fn(e);W(k(e,_r),{force:!0});try{const c=await n({args:a.args,command:a.command,cwd:e,env:{[jr]:Ir(e),[Or]:t.target,[Cr]:i,...t.lazyFunctions?{[Nr]:"1"}:{},...t.environment===void 0?{}:{CLOUDFLARE_ENV:t.environment},...t.strictAdvisories===!1?{[Pr]:"0"}:{},[er]:"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})}},Q=(e,r,t)=>r!==!1&&X(e,t)!==void 0,yn=(e,r,t)=>Q(e,r,t)&&X(e,t)!=="script",me=e=>{const r=e.frameworkBuild===!1?void 0:X(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{se(e.cwd,e.target)}catch(n){return n instanceof Error?n.message:String(n)}let t;try{t=se(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`},tr=async e=>{const r=e.frameworkBuild===!1?void 0:X(e.cwd,e.environment);if(r===void 0)return;let t;try{t=e.target??se(e.cwd)}catch(n){return n instanceof Error?n.message:String(n)}return pn(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})},Re=e=>Array.isArray(e)?e.filter(r=>r!=null):void 0,he=(e,r)=>{const t=L(e);if(!t)return;const{parsed:n}=N(t);if(n===void 0)return;const{error:o,merged:a}=Y(n,r),s=o===void 0?a:n,{containers:i,d1_databases:c,vars:d}=s;return{containers:Re(i),d1_databases:Re(c),vars:typeof d=="object"&&d!==null&&!Array.isArray(d)?d:void 0}},wn=/^127(?:\.\d{1,3}){3}$/,kn=e=>{try{const{hostname:r}=new URL(e);return r==="localhost"||wn.test(r)||r==="::1"||r==="[::1]"}catch{return!1}},bn=e=>e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.includes("Dockerfile"),Sn=(e,r,t,n="deploy",o)=>{const a=(he(e,o)?.containers??[]).filter(i=>typeof i?.image=="string"&&bn(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},ve=e=>S(b(e,be))?be:void 0,$n=(e,r,t="deploy",n)=>{for(const o of Be(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}}},En=(e,r)=>r==="celld"?typeof e=="string"&&e!==Se&<(e):r==="cloudflare"&&e===Se,An=(e,r,t)=>(he(e,t)?.d1_databases??[]).find(n=>En(n.database_id,r)),Tn=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}},Rn=(e,r,t,n,o)=>{const a=An(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 \`wrangler d1 create <name>\` to create the database, then replace the placeholder in wrangler.jsonc with the real id before deploying.`;return r.error(i),i},Dn=(e,r,t="deploy",n)=>{const o=he(e,n)?.vars;if(!o)return;const a=Object.entries(o).filter(([,i])=>typeof i=="string"&&kn(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},_n=["vite.config.ts","vite.config.mts","vite.config.cts","vite.config.js","vite.config.mjs","vite.config.cjs",...$r],nr=/\.(?:[cm]?[jt]s|tsx|jsx)$/u,or=/\.(?:test|spec)\.[cm]?[jt]sx?$/u,ar="allowUnauthenticatedShardAccess",Pn=/[\\/]/u,sr=new Set(["_generated","build","dist","node_modules"]),ir=(e,r)=>{const t=U(e,r).split(Pn);return nr.test(r)&&!or.test(r)&&!ae(t.join("/"))&&t.every(n=>n===".."||!n.startsWith(".")&&!sr.has(n))},De=(e,r,t)=>{const{parsed:n}=N(r);if(n===void 0)return[];const{error:o,merged:a}=Y(n,t),{main:s}=o===void 0?a:n,i=typeof s=="string"?b(Ye(r),s):void 0;return i!==void 0&&S(i)&&ir(e,i)?[i]:[]},pe=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)?pe(e.getExpression()):!1,Nn=e=>{try{return Fe(e).isFile()}catch{return!1}},Cn=new Set(["ELOOP","ENOENT","ENOTDIR"]),K=(e,r,t)=>{const n=r instanceof Error&&"code"in r&&typeof r.code=="string"?r.code:"";Cn.has(n)||t.push(e)},On=(e,r)=>{try{return Fe(e)}catch(t){K(e,t,r);return}},cr=(e,r)=>{try{return A(e,"utf8")}catch(t){K(e,t,r);return}},dr=(e,r,t,n=new Set)=>{let o;try{o=br(r)}catch(s){return K(r,s,t),[]}if(n.has(o))return[];n.add(o);let a;try{a=Me(r)}catch(s){return K(r,s,t),[]}return a.flatMap(s=>{const i=b(r,s),c=On(i,t);if(c===void 0)return[];const d=U(e,i).split(oe).join("/");return c.isDirectory()?sr.has(s)||s.startsWith(".")||ae(`${d}/`)?[]:dr(e,i,t,n):c.isFile()&&nr.test(s)&&!or.test(s)&&!ae(d)?[i]:[]})},jn=e=>{const r=w.isComputedPropertyName(e)?e.getExpression():e;return w.isStringLiteral(r)||w.isNoSubstitutionTemplateLiteral(r)?r.getLiteralValue():e.getText()},te=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],In=/\.(?:[cm]?js|jsx)$/u,Ln=(e,r)=>{if(!r.startsWith("."))return;const t=j(Ye(e),r),n=t.replace(In,"");return[t,...te.map(a=>`${t}${a}`),...te.map(a=>b(t,`index${a}`)),...te.map(a=>`${n}${a}`)].find(a=>Nn(a))},xn=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},Mn=e=>{const r=e.getModuleReference();if(!w.isExternalModuleReference(r))return;const t=r.getExpression();return w.isStringLiteral(t)?t.getLiteralValue():void 0},Fn=(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=cr(c,n);if(d===void 0)continue;const u=r.createSourceFile(U(t,c),d,{overwrite:!0}),g=[...u.getImportDeclarations().map(l=>l.getModuleSpecifierValue()),...u.getExportDeclarations().map(l=>l.getModuleSpecifierValue()),...u.getDescendantsOfKind(p.ImportEqualsDeclaration).map(l=>Mn(l)),...u.getDescendantsOfKind(p.CallExpression).map(l=>xn(l))].filter(l=>l!==void 0);for(const l of g){const m=Ln(c,l);m!==void 0&&ir(t,m)&&!o.has(m)&&(o.add(m),s.push(m),a.push(m))}}return s},Un=e=>{const r=e.getArgumentExpression();return r!==void 0&&(w.isStringLiteral(r)||w.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():void 0},Bn=e=>w.isPropertyAccessExpression(e)?e.getName():w.isElementAccessExpression(e)?Un(e):void 0,Hn=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]),Gn=e=>{const r=e.getOperatorToken().getKind();return!Hn.has(r)||Bn(e.getLeft())!==ar?!1:r!==p.EqualsToken||!pe(e.getRight())},Vn=(e,r,t)=>{const n=[],o=[...new Set([I(e),"src"])].filter(g=>S(b(e,g))),a=L(e),s=[..._n.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 Xe({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}),c=o.flatMap(g=>dr(b(e,g),b(e,g),n));return{sites:[...new Set([...c,...s,...Fn([...s,...c],i,e,n)])].flatMap(g=>{const l=cr(g,n);if(l===void 0)return[];const m=i.createSourceFile(U(e,g),l,{overwrite:!0}),f=[...m.getDescendantsOfKind(p.PropertyAssignment),...m.getDescendantsOfKind(p.ShorthandPropertyAssignment),...m.getDescendantsOfKind(p.GetAccessor),...m.getDescendantsOfKind(p.MethodDeclaration)].filter(h=>{const E=w.isPropertyAssignment(h)&&pe(h.getInitializer());return jn(h.getNameNode())===ar&&!E}).map(h=>h.getStartLineNumber()),v=m.getDescendantsOfKind(p.BinaryExpression).filter(h=>Gn(h)).map(h=>h.getStartLineNumber());return[...f,...v].map(h=>({file:U(e,g),line:h}))}),unreadable:n}},qn=(e,r,t,n,o,a)=>{if(t!=="deploy")return;const{sites:s,unreadable:i}=Vn(e,o,a),c=_t({openShardAccess:s,schema:{tables:[]}},{lints:[$e]});if(c.length===0&&i.length===0)return;const d=[];if(c.length>0){const g=c.map(l=>`${String(l.metadata.file)}:${String(l.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 u=`deploy blocked (open_shard_access): ${d.join(" ")} ${$e.remediation}`;return r.error(u),u},Wn=(e,r,t,n)=>{const o=qn(e,r.logger,t,r.allowOpenShards===!0,r.env,n);return o===void 0?void 0:{code:y.USAGE,error:o}},Kn=(e,r,t,n)=>{const o=Rn(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=$n(e,r.logger,t,r.discoveryCache);if(s!==void 0)return{code:y.USAGE,error:s};const i=Sn(e,r.logger,r.dockerAvailable??Et,t,r.env);return i===void 0?void 0:{code:y.MISSING_DEPENDENCY,error:i}},_e=32,zn=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<=_e)return n;const o=wt("sha256").update(t).digest("hex").slice(0,Pe-1);return`${n.slice(0,_e-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(" ")},lr=e=>(Array.isArray(e)?e:[]).flatMap((r,t)=>{const{binding:n,id:o}=typeof r=="object"&&r!==null?r:{};return typeof n=="string"&&o===Qr?[{binding:n,index:t}]:[]}),de=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,Ce=(e,r)=>{const t=ao(r);return e==="scheme"?io(t):t},Oe=50,co=async(e,r)=>{for(let t=1;t<=Oe;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 (${de(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(Oe)} pages, so "${r}" can't be shown to be absent`)},lo=async(e,r,t)=>{const n=await co(e,r);if(typeof n?.id=="string"){const s=so.filter(c=>Ce(c,n.origin?.[c])!==Ce(c,t[c]));if(s.length>0)throw new Error(`a Hyperdrive config named "${r}" already exists for a different origin, or one that can't be confirmed (${s.join(", ")}). Delete it, or rename the Worker, so the binding does not reach the wrong database.`);const i=await e(`/hyperdrive/configs/${encodeURIComponent(n.id)}`,{body:JSON.stringify({origin:t}),method:"PATCH"});if(!i.ok)throw new Error(`updating its credentials failed (${de(i)})`);return{id:n.id,reused:!0}}const o=await e("/hyperdrive/configs",{body:JSON.stringify({name:r,origin:t}),method:"POST"});if(!o.ok)throw new Error(`creating it failed (${de(o)})`);const{id:a}=typeof o.body.result=="object"&&o.body.result!==null?o.body.result:{};if(typeof a!="string")throw new TypeError("the response carried no id");return{id:a,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)=>Nt({accountId:e.accountId,apiToken:e.token,...e.fetch===void 0?{}:{fetch:e.fetch},init:{...s,signal:AbortSignal.timeout(zn)},path:a}),t,e.origin);return e.logger.success(`${o?"reusing":"created"} Hyperdrive config "${t}" for ${e.binding} → ${e.wranglerPath}`),{id:n,text:We(r,[...e.path,e.index,"id"],n)}},fo=e=>e===void 0||e===""?void 0:e,ur=e=>{const r=k(M(e),".wrangler","deploy","config.json");try{const{configPath:t}=JSON.parse(A(r,"utf8"));return typeof t=="string"?j(M(r),t):void 0}catch{return}},mo=(e,r,t,n,o)=>{const a=ur(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=N(a)}catch{return}const i=lr(s.parsed?.hyperdrive).find(c=>c.binding===r);i!==void 0&&H(a,We(s.text,["hyperdrive",i.index,"id"],t),"utf8")},ho=(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}`},ye=(e,r)=>{const t=L(e),n=t===void 0?void 0:N(t).parsed;if(t===void 0||n===void 0)return;const o=r===void 0?void 0:n.env?.[r],a=lr(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:ho(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=>{const r=ye(e.cwd,e.wranglerEnvironment);if(r===void 0)return;const{entries:t,path:n,wranglerPath:o}=r,a=e.environment??process.env,{accountId:s,token:i}=Pt(a,r.accountId),c=t.map(({binding:u})=>{const g=a[B(u)]??"";return{binding:u,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[u,{binding:g,index:l}]of t.entries()){const m=c[u]?.origin;if(!(m===void 0||i===void 0||s===void 0))try{const{id:f,text:v}=await go({accountId:s,binding:g,fetch:e.fetch,index:l,logger:e.logger,origin:m,path:n,token:i,workerName:r.workerName,wranglerPath:o},A(o,"utf8"));H(o,v,"utf8"),mo(o,g,f,{built:fo(a.CLOUDFLARE_ENV),deployed:e.wranglerEnvironment},e.logger)}catch(f){const v=f instanceof Error?f.message:String(f),h=`deploy blocked: the "${g}" Hyperdrive config could not be set up: ${oo(v,c[u]?.origin)}`;return e.logger.error(h),h}}},yo=(e,r)=>{const t=ye(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},wo=(e,r)=>{const t=ye(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},gr=async(e,r,t,n,o="create")=>{if(n!=="cloudflare")return;if(t==="prepare")return yo(e,r);if(r.temporary===!0)return wo(e,r);const a=r.clientBuildEnvironment===void 0?void 0:{...process.env,CLOUDFLARE_ENV:r.clientBuildEnvironment};return po({checkOnly:o==="check",cwd:e,dryRun:r.dryRun,environment:a,logger:r.logger,wranglerEnvironment:r.env})},ko=/https?:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/u,bo=/https:\/\/[^\s"'<>]+/u,So=e=>{if(e===void 0)return;const r=ko.exec(e);return r?r[0]:bo.exec(e)?.[0]},je=e=>e===void 0?"":` (--env ${e})`,$o=({cwd:e,env:r,logger:t,now:n,url:o})=>{if(o!==void 0)try{const a=Ue(e);if(a!==void 0){if(a.workerUrl===o&&a.env===r)return;t.warn(`link: .lunora/project.json records ${a.workerUrl??"(no url)"}${je(a.env)}, but this deploy published ${o}${je(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()))();Lr(e,{env:r,linkedAt:s,workerName:ge(e),workerUrl:o}),t.success(`link: recorded ${o} in .lunora/project.json (run \`lunora link\` to change)`)}catch{}},Eo=async(e,r)=>{const t=new Xe({skipAddingFilesFromTsConfig:!0}),n=b(r,"lunora");let o;try{o=Er(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 Ct(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},Ao=async(e,r)=>{const{info:t}=He(r,"lunora",e.discoveryCache),n=t?.vectorMetadata??[];if(n.length===0)return;const o=[];for(const i of n){const c=ut(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 gt({cwd:r,entries:o,exec:fe(C(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)}`)},Ie=5,To=2e3,Ro=async(e,r,t)=>{if(e.healthCheck!==!0)return;const n=t??Je({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 At({attempts:Ie,baseUrl:n,delayMs:To,fetchImpl:e.healthFetch,paths:[Tt,Rt],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(Ie)} attempt(s) — ${o.error}`),{error:o.error,ok:!1,url:o.url})},Do=async(e,r,t,n,o,a)=>{await Ao(e,r);const s=e.migrate?await Eo(e,r):0;return s===0&&o?.(),{code:s,descriptor:t,mintedSecretsFile:a,validation:n}},_o=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:So(s),workerName:ge(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?.(),$o({cwd:e,env:n.env,logger:n.logger,url:c.url}));const d=await Ro(n,e,c.url);return d?.error!==void 0?{code:y.UNAVAILABLE,deployment:c,descriptor:r,healthCheck:d,mintedSecretsFile:t,validation:i}:{...await Do(n,e,r,i,o,t),deployment:c,healthCheck:d}},Po=(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.`)},fr=async(e,r)=>{let t=[];try{t=xr(await Ve({cache:r,projectRoot:e,schemaDir:I(e)}))}catch{}const n=[...new Set(Mr(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=>Ke(s)))}catch{}return{fromLocal:o.filter(a=>!n.includes(a)),fromPackages:n,mintableKeys:Fr(t)}},No=async(e,r,t,n)=>{const{logger:o}=r,a=r.spawner??x,s=C(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(l=>({key:l,value:Ur()})),u=n.toolchain?.secretBulk;if(u!==void 0&&d.length>=2){const l=F(s,u({environment:r.env,temporary:r.temporary})),m=await a({args:l.args,command:l.command,cwd:e,input:JSON.stringify(Object.fromEntries(d.map(f=>[f.key,f.value])))});if(m.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(m.code)}); retrying one key at a time`)}const g=[];for(const{key:l,value:m}of d){const f=c({environment:r.env,key:l,temporary:r.temporary}),v=F(s,f),h=await a({args:v.args,command:v.command,cwd:e,input:m});if(h.code!==0)return o.error(`failed to push secret ${l} (exit ${String(h.code)}); set it manually with \`wrangler secret put ${l}${i}\`.`),{minted:g,ok:!1};g.push({key:l,value:m}),o.success(`generated + pushed ${l}`)}return{minted:g,ok:!0}},Co=/^[\w-]+$/u,Le=[".dev.vars",".dev.vars.*","!.dev.vars.example"],Oo=(e,r)=>{try{const t=Vr(e,Le);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 \`${Le.join("` and `")}\` by hand before committing.`)}},jo=(e,r,t)=>{if(t.length===0)return;const n=t.map(i=>i.key).join(", ");if(r.env!==void 0&&!Co.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}`;Oo(e,r.logger);const a=b(e,o);let s=S(a)?A(a,"utf8"):"";for(const i of t)s=Br(s,i.key,i.value);return Hr(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},Io=/^<[^>]+>$/u,Lo=async(e,r,t)=>{let n;try{n=t.projectConfig?.(e,"deploy").vars??{}}catch(u){return{error:u instanceof Error?u.message:String(u)}}const o=u=>{const g=n[u];if(typeof g!="string")return!0;const l=g.trim();return l===""||Io.test(l)?!0:Ke(u)&&Gr(g)},a=u=>Object.hasOwn(n,u)?`${u} (empty or a placeholder)`:u,{fromLocal:s,fromPackages:i}=await fr(e,r.discoveryCache),c=s.filter(u=>o(u));c.length>0&&r.logger.warn(`${P} key(s) not set in the wrangler vars: ${c.map(u=>a(u)).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(u=>o(u));return d.length===0?{}:{error:`missing required secret(s) in the wrangler vars: ${d.map(u=>a(u)).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.`}},xo=async(e,r,t,n)=>{if(r.dryRun===!0||r.preview===!0)return{};if(n.toolchain?.secretList===void 0)return Lo(e,r,n);const{logger:o}=r,a=r.env===void 0?"":` --env ${r.env}`;let s;try{s=await(r.secretLister??jt)({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:u}=await fr(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=>!u.has(v)))o.warn(`required secret ${f} is not set on the target — set it with: wrangler secret put ${f}${a}`);const l=g.filter(f=>u.has(f));if(l.length===0)return{};if(await(r.secretConfirm??Ot())(`${String(l.length)} required secret(s) not set on the target (${l.join(", ")}). Generate strong values and push them now?`)){const{minted:f,ok:v}=await No(e,r,l,n),h=jo(e,r,f);return v?{mintedSecretsFile:h}:{error:"failed to push required secret(s) — set them manually and re-deploy",mintedSecretsFile:h}}return o.warn(`${String(l.length)} required secret(s) not set on the target: ${l.join(", ")}. Generate + push with \`lunora env generate --set\` then \`lunora env push --yes${a}\`.`),{}},mr=e=>e.format==="json"?!1:e.interactive!==void 0?e.interactive:process.stdout.isTTY&&!process.env.CI,Mo=async(e,r)=>{if(r.dryRun===!0)return;const t=Be(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 gn({cwd:e,logger:r.logger,railpackAvailable:r.railpackAvailable,spawner:r.spawner,targets:t});return n.code===0?void 0:n.error??"railpack build failed"},Fo=(e,r,t)=>{if(t!==void 0)try{const n=ot(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=at(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}`)}},Uo=async(e,r,t,n,o,a)=>{try{J(n);const s=await Ve({cache:a,projectRoot:e,schemaDir:I(e)}),i=tt(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:u,updated:g}=i.devConfig;r.success(`dev sidecar bindings: ${[...d,...g].join(", ")} → ${u}`)}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=nt(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}`)}Fo(e,r,t)},Bo=async(e,r,t,n,o,a,s,i,c,d)=>{let u;r?(u=new st({name:"dots"}),u.start("running codegen")):t.info("running codegen");try{const g=Ar({apiSpec:n,dryRun:!d,lazyFunctions:o,projectRoot:e,target:a,...rt(e)});u?.succeed("codegen complete"),u||t.success("codegen complete");const l=it(g.platformDiagnostics,t);if(l.errors.length>0)return{error:l.errors.join("; ")};const{errorAdvisories:m,names:f,shouldBlock:v}=ct(g.advisories,c);if(v){const E=`${m.length.toString()} ERROR-level ${m.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 h=d?await Jr({cwd:e,logger:t,spawner:s,stdoutToStderr:i}):void 0;return h?.error!==void 0?{error:h.error}:{result:g}}catch(g){u?.failed("codegen failed");const l=g instanceof Error?g.message:String(g);return t.error(`codegen failed: ${l}`),{error:`codegen failed: ${l}`}}},Ho=(e,r)=>({dryRun:r.dryRun,entry:ve(e),environment:r.env,outDir:r.outDir,preview:r.preview,temporary:r.temporary}),hr=(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=Ho(e,r);return qe(t,e,"deploy",a=>n.deploy({...o,configPath:a}))},Go=(e,r,t)=>{const n=hr(e,r,t),o=ve(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},ne=(e,r)=>({code:y.USAGE,descriptor:void 0,error:e,validation:R,...r}),Vo=(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},qo=(e,r,t)=>{const n=r.format==="json",o=r.dryRun!==!0,a=Go(e,r,t),s=F(C(e),a);return{args:s.args,captureStdout:o&&!n,captureStdoutSilently:o&&n,command:s.command,cwd:e,stdoutToStderr:n&&!o}},we=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"},Wo=(e,r)=>we(r)===void 0?le(e).services.map(t=>t.wranglerPath):[],vr=(e,r,t,n,o)=>({cwd:e,environment:r.env,frameworkBuild:n,lazyFunctions:z(r.lazyFunctions),logger:r.logger,outputJson:r.format==="json"||r.clientBuildOutputJson===!0,spawner:o,strictAdvisories:ue(r),target:t.id}),Ko=(e,r,t)=>{const{toolchain:n}=t,o=n===void 0?`target "${t.id}" has no deploy command`:we(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},pr=(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}`}},zo=(e,r,t)=>{const{error:n,services:o}=le(e);if(n!==void 0||o.length===0)return;const a=J(t);if(a.toolchain===void 0||we(r)!==void 0)return;const s=r.skipCodegen===!0?!1:r.frameworkBuild,i=[...new Map(o.map(c=>[c.wranglerPath,c])).values()];return pr(i,c=>vr(c,r,a,s,x))},yr=(e,r,t)=>{const n=e.cwd??process.cwd(),o=pt(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{hr(n,e,J(o.target))}catch(i){if(!(t&&i instanceof qr&&Q(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:Wn(n,e,r,Wo(n,e));if(a!==void 0)return{kind:"refused",code:a.code,error:a.error,validation:R};const s=zo(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}},Jo=(e,r)=>e.apiSpec??(e.clientBuildRan===!0?Yr(r):void 0),Yo=async(e,r,t)=>{if(r!=="celld")return;const n=await(e.celldToolchain??zr)({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},Xo=async(e,r)=>{const t=e.cwd??process.cwd(),n=mr(e),o=ue(e),a={problems:[],wranglerPath:void 0},s=yr(e,r,!1);if(s.kind==="refused")return{code:s.code,error:s.error,validation:s.validation};const{target:i}=s,c=await Yo(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 Bo(t,n,e.logger,Jo(e,t),z(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 u;if(d!==void 0){const v=Dt({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};u=v.rebless}const g=d&&Bt({current:d.architecture,cwd:t,environment:e.env,logger:e.logger});await Uo(t,e.logger,d?.cronTriggers,i,e.env,e.discoveryCache);const l=await gr(t,e,r,i,"check");if(l!==void 0)return{error:l,target:i,validation:R};const m=Kn(t,e,r,i);if(m!==void 0)return{code:m.code,error:m.error,target:i,validation:R};const f=et({environment:e.env,projectRoot:t});return Vo(f,e.logger)?{error:"wrangler validation failed",target:i,validation:f}:{codegen:d,reblessSchemaBaseline:u,recordArchitecture:g,target:i,validation:f}},Qo=e=>{W(k(e,".wrangler","deploy","config.json"),{force:!0})},Zo=async(e,r,t)=>{const n=me(e);if(n!==void 0)return{built:!1,error:n};const o=Q(e.cwd,r,t);return o&&Qo(e.cwd),{built:o,error:await tr(e)}},ea=(e,r,t)=>r||t===!1?ur(e):void 0,ra=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=Ko(a,r,t);if(s===void 0)return;const i=C(e),c=[...new Map(a.map(l=>[l.wranglerPath,l])).values()],d=r.skipCodegen===!0?!1:r.frameworkBuild,u=l=>vr(l,r,t,d,n),g=pr(c,u);if(g!==void 0)return r.logger.error(g),{code:y.USAGE,error:g};for(const l of c){const m=M(l.wranglerPath),f=u(m),{built:v,error:h}=await Zo(f,d,r.env);if(h!==void 0){const T=`service ${l.name} (${l.worker}): ${h}`;return r.logger.error(T),{code:y.FAILURE,error:T}}const E=ea(l.wranglerPath,v,d);let _;try{_=qe(t,m,"deploy",T=>s.deploy({configPath:T??E??l.wranglerPath,dryRun:r.dryRun===!0,environment:r.env}))}catch(T){return{code:y.FAILURE,error:`service ${l.name} (${l.worker}): ${T instanceof Error?T.message:String(T)}`}}_.commit();const $=F(i,_.command);r.logger.info(`deploying service ${l.name} (${l.worker}) via ${$.command} ${$.args.join(" ")}`);const O=await n({args:$.args,command:$.command,cwd:m,stdoutToStderr:r.format==="json"});if(O.code!==0)return{code:y.FAILURE,error:`service ${l.name} (${l.worker}): ${$.command} ${$.args.join(" ")} exited ${String(O.code)} — stopping before the app`}}},ta=async(e,r,t,n)=>{if(r!=="cloudflare")return;const o=e===void 0?void 0:N(e).parsed,a=(t===void 0?void 0:o?.env?.[t]?.account_id)??o?.account_id,s=await mt({accountId:a});(s.verdict==="near"||s.verdict==="full")&&n.warn(s.fix===void 0?s.message:`${s.message} ${s.fix}`)},na=e=>e.dryRun!==!0&&e.temporary!==!0,oa=e=>e.temporary===!0?"temporary":e.dryRun===!0?"preview":"defer",aa=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},sa=(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=aa(o);r.error(a),n.push(a)}return n},wr=async(e,r,t,n,o,a,s)=>{const i=t==="cloudflare"&&r!==void 0?N(r).parsed:void 0;if(i===void 0)return;const c=(Y(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:He(e,I(e),a).info?.jurisdiction;if(d===void 0)return;const u=[...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 ${u.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,l=await Promise.all(u.map(async f=>ft({...f,accountId:g,create:s==="create",jurisdiction:d,missingOk:s==="defer"||s==="preview"}))),m=sa(l,o,s);return m.length===0?void 0:m.join(`
|
|
19
|
+
`)},ia=async(e,r,t,n,o,a)=>{const s=na(r)?await wr(e,a,o,r.env,r.logger,r.discoveryCache,"create"):void 0;if(s!==void 0)return{code:y.FAILURE,error:s};const i=await gr(e,r,"deploy",o);return i!==void 0?{code:y.FAILURE,error:i}:ra(e,r,t,n)},ca=async(e,r,t,n)=>{if(!(r.smokeLoad===!1||t.toolchain===void 0))return ln({composedEntry:ve(e),configPath:n,cwd:e,environment:r.env,launcher:r.smokeLauncher,logger:r.logger,toolchain:t.toolchain})},da=async e=>{const r={...e,discoveryCache:e.discoveryCache??Kr()},t=r.cwd??process.cwd(),n=mr(r),o=await Xo(r,r.commandName??"deploy");if(o.error!==void 0){if(o.validation.problems.length>0)return{code:y.USAGE,descriptor:void 0,error:o.error,validation:o.validation};const h=o.schemaDrift===void 0?void 0:{schemaDrift:o.schemaDrift};return ne(o.error,{...h,...o.code===void 0?{}:{code:o.code}})}const{validation:a}=o,s=J(o.target),i=Tn(r)??await wr(t,a.wranglerPath,o.target,r.env,r.logger,r.discoveryCache,oa(r))??await ca(t,r,s,a.wranglerPath);if(i!==void 0)return ne(i);const c=s.toolchain?.prebuildsContainerImages===!0?await Mo(t,r):void 0;if(c!==void 0)return ne(c);Po(t,r.logger,s),Zr(t,h=>{r.logger.warn(h)}),await ta(a.wranglerPath,o.target,r.env,r.logger);const{error:d,mintedSecretsFile:u}=await xo(t,r,n,s);if(d!==void 0)return r.logger.error(d),{code:y.USAGE,descriptor:void 0,error:d,mintedSecretsFile:u,validation:a};const g=r.spawner??x,l=await ia(t,r,s,g,o.target,a.wranglerPath);if(l!==void 0)return{code:l.code,descriptor:void 0,error:l.error,mintedSecretsFile:u,validation:a};const m=qo(t,r,s);r.logger.info(`deploying via ${m.command} ${m.args.join(" ")}`);const f=await g(m);return m.captureStdoutSilently===!0&&f.stdout!==void 0&&f.stdout!==""&&process.stderr.write(f.stdout),f.code!==0?{code:f.code,descriptor:m,mintedSecretsFile:u,validation:a}:{...await _o({...o,cwd:t,descriptor:m,mintedSecretsFile:u,options:r,stdout:f.stdout}),logsAvailable:s.toolchain?.tail!==void 0}},la=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:ue(e),lazyFunctions:z(e.lazyFunctions),logger:r,outputJson:e.format==="json"||e.clientBuildOutputJson===!0,spawner:e.spawner,target:e.target},o=me(n);if(o!==void 0)return r.error(o),{code:y.USAGE,descriptor:void 0,error:o,validation:R};Wr(t);const a=await tr(n);if(a!==void 0)return r.error(a),{code:y.FAILURE,descriptor:void 0,error:a,validation:R}},ua=(e,r)=>{const t=r.skipCodegen===!0?!1:r.frameworkBuild;return Q(e,t,r.env)?r.env:void 0},ga=async e=>{const{logger:r}=e,t=e.cwd??process.cwd(),n=yr(e,e.commandName??"deploy",!0);if(n.kind==="refused")return{code:n.code??y.USAGE,descriptor:void 0,error:n.error,validation:n.validation};const o=await la(e);if(o!==void 0)return o;const a=e.dryRun===!0?Ze(t):void 0;let s;try{if(s=await da({...e,clientBuildEnvironment:ua(t,e),clientBuildRan:yn(t,e.skipCodegen===!0?!1:e.frameworkBuild,e.env),logger:r,openShardGatePassed:!0}),s.code===0&&e.emitBindings!==void 0){const{error:i}=ht({destination:e.emitBindings,logger:r,projectRoot:e.cwd??process.cwd()});i!==void 0&&(r.error(i),s={...s,code:y.USAGE})}}finally{a?.()}if(e.format==="json")return s;if(s.code===0&&e.dryRun!==!0&&e.preview!==!0)Ht({cwd:e.cwd??process.cwd(),env:e.env,logger:e.logger,logsAvailable:s.logsAvailable===!0,mintedSecretsFile:s.mintedSecretsFile,url:s.deployment?.url});else if(s.code===0&&e.preview===!0){const i=s.deployment?.url;e.logger.success(i===void 0?"preview version uploaded":`preview version uploaded — ${i}`)}return s},Va=vt(async({cwd:e,format:r,logger:t,options:n})=>{const o=un(e,n.root),a=await ga({allowOpenShards:n.allowOpenShards===!0,allowSchemaDrift:n.allowSchemaDrift===!0,apiSpec:dt(n.apiSpec),frameworkBuild:n.prebuilt===!0?!1:n.frameworkBuild,lazyFunctions:z(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:Je({cwd:o,env:n.env,url:n.migrateUrl}),migrateYes:n.migrateYes===!0,preview:n.preview===!0,skipCodegen:n.prebuilt===!0,skipServices:n.skipServices===!0,smokeLoad:n.smokeLoad,strictAdvisories:n.strictAdvisories,target:n.target,temporary:n.temporary===!0,updateSchemaBaseline:n.updateSchemaBaseline===!0});return{code:a.code,data:{deployment:a.deployment,healthCheck:a.healthCheck,mintedSecretsFile:a.mintedSecretsFile,schemaDrift:a.schemaDrift,validation:a.validation},error:a.error}});export{Xo as a,Uo as b,Va as e,un as p,ga as r,ca as s,fn as v};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{writeFileSync as h,existsSync as S,readFileSync as p}from"node:fs";import{isAbsolute as v,join as w}from"node:path";import{byCodepoint as b,scoreAdvisor as y,parseAdvisorMap as x,compareToBaseline as j}from"@lunora/advisor";import{runCodegen as A}from"@lunora/codegen";import{resolveLazyFunctions as M}from"@lunora/config";import{wranglerCodegenInputs as F}from"@lunora/config/cloudflare";import{d as D}from"../packem_shared/command-CB4JM-Jl.mjs";import{EXIT_CODE as E}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{D as u}from"../packem_shared/cli-
|
|
1
|
+
import{writeFileSync as h,existsSync as S,readFileSync as p}from"node:fs";import{isAbsolute as v,join as w}from"node:path";import{byCodepoint as b,scoreAdvisor as y,parseAdvisorMap as x,compareToBaseline as j}from"@lunora/advisor";import{runCodegen as A}from"@lunora/codegen";import{resolveLazyFunctions as M}from"@lunora/config";import{wranglerCodegenInputs as F}from"@lunora/config/cloudflare";import{d as D}from"../packem_shared/command-CB4JM-Jl.mjs";import{EXIT_CODE as E}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{D as u}from"../packem_shared/cli-CDNZwrAT.mjs";const l={clean:"·",exempt:"–",failing:"✗",warned:"!"},d=(e,r)=>e.length>=r?e:e+" ".repeat(r-e.length),R=e=>`${e.id} (${e.visibility} ${e.kind})`,f=e=>{let r=0;for(const n of e)r=Math.max(r,n.id.length);return r},g=(e,r)=>` ${d(String(e.score),3)} ${l[e.coverage]} ${d(e.id,r)} ${e.visibility} ${e.kind}`,k=e=>{if(!e.comparable)return[` baseline not comparable (${e.reason}) — regenerate it; this run cannot verify anything`];if(!e.regressed)return[` no regression against baseline (score ${e.scoreDelta>=0?"+":""}${String(e.scoreDelta)})`];const r=[` REGRESSED against baseline (score ${e.scoreDelta>=0?"+":""}${String(e.scoreDelta)})`];for(const n of e.dropped)r.push(` ${n.id}: ${String(n.before)} → ${String(n.after)}`);for(const n of e.newFailing)r.push(` ${n}: now failing`);for(const n of e.worsened)r.push(` ${n}: more findings than the baseline`);return e.projectRegressed&&r.push(" project: new schema/config rules fired"),r},C=(e,r)=>{const n=e.procedures.filter(i=>i.coverage!=="clean"&&i.coverage!=="exempt"),t=f(n),o=[`advisor health ${String(e.score)}/100 — ${e.grade}`,` ${String(e.summary.clean)} clean · ${String(e.summary.warned)} warned · ${String(e.summary.failing)} failing · ${String(e.summary.exempt)} exempt (${String(e.summary.procedures)} procedures, ${String(e.summary.rulesFired)} rules fired)`];return e.project.checks.length>0&&o.push("",` project ${String(e.project.score)}/100 — ${e.project.checks.map(i=>i.name).join(", ")}`),n.length>0&&o.push("",...n.map(i=>g(i,t)),""," run with --all for every procedure, or --entry <file#export> for one"),r!==void 0&&o.push("",...k(r)),o.join(`
|
|
2
2
|
`)},T=e=>e.coverage==="exempt"?[` exempt: ${e.exemptReason===void 0||e.exemptReason===""?"no reason given":e.exemptReason}`]:e.checks.map(r=>{const n=r.occurrences>1?`, ×${String(r.occurrences)}`:"";return` ${r.name} (−${String(r.weight)}${n})`}),B=e=>{const r=new Map;for(const n of e){const t=r.get(n.file);t===void 0?r.set(n.file,[n]):t.push(n)}return[...r].toSorted(([n],[t])=>b(n,t))},I=e=>{const r=f(e.procedures),n=[`advisor health ${String(e.score)}/100 — ${e.grade}`,"",` legend: ${l.clean} clean ${l.warned} warned ${l.failing} failing ${l.exempt} exempt`];for(const[t,o]of B(e.procedures)){n.push("",` ${t}`);for(const i of o)n.push(g(i,r),...T(i))}return n.join(`
|
|
3
3
|
`)},L=(e,r)=>{const n=e.procedures.find(o=>o.id===r);if(n===void 0){const o=e.procedures.slice(0,10).map(i=>` ${i.id}`);return[`no procedure ${r} in the map. Known ids:`,...o,e.procedures.length>10?" …":""].filter(Boolean).join(`
|
|
4
4
|
`)}const t=[`${R(n)} — ${String(n.score)}/100, ${n.coverage}`,` weight in the global mean: ${String(n.weight)}`];if(n.checks.length===0)return t.push(""," no rule fired"),t.join(`
|