@lunora/cli 1.0.0-alpha.477 → 1.0.0-alpha.479

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,29 +1,29 @@
1
- import{mkdirSync as Ae,writeFileSync as X,existsSync as b,readFileSync as E,readdirSync as K,statSync as Re,rmSync as oe,mkdtempSync as lt,realpathSync as ut}from"node:fs";import{dirname as I,join as p,resolve as C,relative as L,sep as M,extname as ft}from"node:path";import{PROJECT_CONFIG_FILENAMES as gt,isTestPath as ye,discoverMigrations as ht,readServiceBindings as Te,runCodegen as mt}from"@lunora/codegen";import{readLinkedProject as Ce,discoverSchemaInfo as _e,resolveSchemaDirectory as F,startDevProcess as pt,acceptsConnection as vt,resolveTargetOrThrow as we,detectFramework as yt,DEFAULT_BUNDLE_META_PATH as wt,STRICT_ADVISORIES_ENV as kt,LAZY_FUNCTIONS_ENV as bt,BUNDLE_META_PATH_ENV as $t,BUILD_TARGET_ENV as St,BUILD_ROOT_ENV as Et,canonicalPath as At,COMPOSED_WORKER_ENTRY as Ve,discoverContainerInfo as vr,D1_PLACEHOLDER_ID as Ge,writeLinkedProject as Rt,DEV_VARS_FILE as x,parseDevVariableEntries as yr,secretSourcesFromBindings as Tt,inferLunoraBindings as wr,requiredSecrets as Ct,mintableSecretKeysFor as _t,generateSecretValue as Pt,upsertDevVariableLine as It,writeDevVariablesFileAtomically as jt,isPlaceholderValue as Ot,ensureGitignoreEntries as Dt,resolveLazyFunctions as de,resolveDeployDriver as le,MissingBuildOutputError as Nt,clearApiSpecMarker as Lt,createDiscoveryCache as xt,planToolchainInvocation as kr,probeCelldToolchain as Mt,runPostCodegenHook as Ft,readApiSpecMarker as Ut}from"@lunora/config";import{findWranglerFile as N,readWranglerJsonc as j,HYPERDRIVE_PLACEHOLDER_ID as br,applyModify as $r,mergeWranglerEnvironment as ue,bindingsNeedingDatabase as Bt,warnCloudflareCliConfigOnce as Wt,validateWranglerProject as Ht,wranglerCodegenInputs as qt,reconcileWranglerBindings as Vt,reconcileWranglerCompatibilityDate as Gt,reconcileWranglerCrons as Kt,describePreservedCrons as zt}from"@lunora/config/cloudflare";import{Spinner as Jt}from"@visulima/spinner";import{r as Yt}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{n as Xt,r as Qt,a as Zt}from"../packem_shared/admin-url-DJB8P6Jh.mjs";import{r as Pe,a as en,e as rn}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as tn}from"../packem_shared/api-spec-lYyq4vL6.mjs";import{e as nn,m as on,g as sn,i as Sr,d as an,b as cn}from"../packem_shared/vectorize-metadata-DK61NmVx.mjs";import{w as dn}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{d as ln}from"../packem_shared/command-BpMv2n0o.mjs";import{r as Ie}from"../packem_shared/wrangler-name-Dsk5K1f-.mjs";import{a as un}from"../packem_shared/deploy-target-resolve-BTCW1Iv4.mjs";import{EXIT_CODE as k}from"../packem_shared/EXIT_CODE-DQVhSE-1.mjs";import{spawn as Er,spawnSync as fn}from"node:child_process";import{createHash as gn,randomUUID as Ar}from"node:crypto";import{setTimeout as hn}from"node:timers/promises";import{stripVTControlCharacters as mn}from"node:util";import{toolchainExecArgs as z,detectPackageManager as U,execArgsFor as je}from"@lunora/config/cli";import{ts as y,Project as Rr,SyntaxKind as w,Node as $}from"ts-morph";import{r as Tr,c as Cr}from"../packem_shared/cloudflare-credentials-BVmZnDZk.mjs";import{f as pn}from"../packem_shared/free-port-DjbFhaaT.mjs";import{l as G}from"../packem_shared/js-literal-FWLi94Lh.mjs";import{containerBuildTag as vn}from"@lunora/container";import{a as yn,i as wn}from"../packem_shared/docker-DpVxvYpL.mjs";import{defaultSpawner as q}from"../packem_shared/createRecordingSpawner-DchLi0gR.mjs";import{a as Oe}from"../packem_shared/resolve-target-BRvw8Pf7.mjs";import{p as kn,H as bn,a as $n,r as Sn,c as En,b as An}from"../packem_shared/health-probe-BLnoq_oC.mjs";import{runAdvisor as Rn,openShardAccess as Ke}from"@lunora/advisor";import{join as A,relative as J,dirname as _r}from"@visulima/path";import{runMigrateDataCommand as Tn}from"../packem_shared/runMigrateGenerateCommand-CguLEIZp.mjs";import{c as Cn}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{l as _n}from"../packem_shared/wrangler-secrets-C9siMBwN.mjs";const Pn=Object.freeze({edges:[],nodes:[],modules:[],unresolved:[],version:1}),In=20,ze=e=>`${e.from} -${e.kind}-> ${e.to}`,ee=(e,r)=>{const t=new Set(e);return r.filter(n=>!t.has(n)).toSorted((n,o)=>n.localeCompare(o))},jn=(e,r)=>{const t=e.modules.map(i=>i.name),n=r.modules.map(i=>i.name),o=e.edges.map(i=>ze(i)),s=r.edges.map(i=>ze(i));return{addedEdges:ee(o,s),addedModules:ee(t,n),removedEdges:ee(s,o),removedModules:ee(n,t)}},re=(e,r,t)=>{if(t.length===0)return[];const n=t.slice(0,In).map(s=>` ${e} ${s}`),o=t.length-n.length;return[`${r}:`,...n,...o>0?[` … and ${o.toString()} more`]:[]]},On=e=>{const r=[...re("+","modules added",e.addedModules),...re("-","modules removed",e.removedModules),...re("+","edges added",e.addedEdges),...re("-","edges removed",e.removedEdges)];return r.length===0?void 0:`architecture changes since the last deploy:
1
+ import{mkdirSync as Re,writeFileSync as X,existsSync as b,readFileSync as E,readdirSync as K,statSync as Te,rmSync as oe,mkdtempSync as ut,realpathSync as ft}from"node:fs";import{dirname as R,join as p,resolve as P,relative as D,sep as N,extname as gt}from"node:path";import{PROJECT_CONFIG_FILENAMES as ht,isTestPath as we,discoverMigrations as mt,readServiceBindings as Ce,runCodegen as pt}from"@lunora/codegen";import{readLinkedProject as _e,discoverSchemaInfo as Pe,resolveSchemaDirectory as x,startDevProcess as vt,acceptsConnection as yt,resolveTargetOrThrow as ke,detectFramework as wt,DEFAULT_BUNDLE_META_PATH as kt,STRICT_ADVISORIES_ENV as bt,LAZY_FUNCTIONS_ENV as $t,BUNDLE_META_PATH_ENV as St,BUILD_TARGET_ENV as Et,BUILD_ROOT_ENV as At,canonicalPath as Rt,COMPOSED_WORKER_ENTRY as Ke,discoverContainerInfo as wr,D1_PLACEHOLDER_ID as ze,writeLinkedProject as Tt,DEV_VARS_FILE as L,parseDevVariableEntries as kr,secretSourcesFromBindings as Ct,inferLunoraBindings as br,requiredSecrets as _t,mintableSecretKeysFor as Pt,generateSecretValue as It,upsertDevVariableLine as jt,writeDevVariablesFileAtomically as Ot,isPlaceholderValue as Dt,ensureGitignoreEntries as Lt,resolveLazyFunctions as de,resolveDeployDriver as le,MissingBuildOutputError as Nt,clearApiSpecMarker as xt,createDiscoveryCache as Ft,planToolchainInvocation as $r,probeCelldToolchain as Mt,runPostCodegenHook as Ut,readApiSpecMarker as Bt}from"@lunora/config";import{findWranglerFile as O,readWranglerJsonc as j,HYPERDRIVE_PLACEHOLDER_ID as Sr,applyModify as Er,mergeWranglerEnvironment as ue,bindingsNeedingDatabase as Wt,warnCloudflareCliConfigOnce as Ht,validateWranglerProject as qt,wranglerCodegenInputs as Gt,reconcileWranglerBindings as Vt,reconcileWranglerCompatibilityDate as Kt,reconcileWranglerCrons as zt,describePreservedCrons as Jt}from"@lunora/config/cloudflare";import{Spinner as Yt}from"@visulima/spinner";import{r as Xt}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{n as Qt,r as Zt,a as en}from"../packem_shared/admin-url-DJB8P6Jh.mjs";import{r as Ie,a as rn,e as tn}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as nn}from"../packem_shared/api-spec-lYyq4vL6.mjs";import{e as on,m as sn,g as an,i as Ar,d as cn,b as dn}from"../packem_shared/vectorize-metadata-DK61NmVx.mjs";import{w as ln}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{d as un}from"../packem_shared/command-BpMv2n0o.mjs";import{r as je}from"../packem_shared/wrangler-name-Dsk5K1f-.mjs";import{a as fn}from"../packem_shared/deploy-target-resolve-BTCW1Iv4.mjs";import{EXIT_CODE as y}from"../packem_shared/EXIT_CODE-DQVhSE-1.mjs";import{spawn as Rr,spawnSync as gn}from"node:child_process";import{createHash as hn,randomUUID as Tr}from"node:crypto";import{setTimeout as mn}from"node:timers/promises";import{stripVTControlCharacters as pn}from"node:util";import{toolchainExecArgs as z,detectPackageManager as F,execArgsFor as Oe}from"@lunora/config/cli";import{ts as w,Project as Cr,SyntaxKind as k,Node as S}from"ts-morph";import{r as _r,c as Pr}from"../packem_shared/cloudflare-credentials-BVmZnDZk.mjs";import{f as vn}from"../packem_shared/free-port-DjbFhaaT.mjs";import{l as V}from"../packem_shared/js-literal-FWLi94Lh.mjs";import{containerBuildTag as yn}from"@lunora/container";import{a as wn,i as kn}from"../packem_shared/docker-DpVxvYpL.mjs";import{defaultSpawner as q}from"../packem_shared/createRecordingSpawner-DchLi0gR.mjs";import{a as De}from"../packem_shared/resolve-target-BRvw8Pf7.mjs";import{p as bn,H as $n,a as Sn,r as En,c as An,b as Rn}from"../packem_shared/health-probe-BLnoq_oC.mjs";import{runAdvisor as Tn,openShardAccess as Je}from"@lunora/advisor";import{join as A,relative as J,dirname as Ir}from"@visulima/path";import{runMigrateDataCommand as Cn}from"../packem_shared/runMigrateGenerateCommand-CguLEIZp.mjs";import{c as _n}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{l as Pn}from"../packem_shared/wrangler-secrets-C9siMBwN.mjs";const In=Object.freeze({edges:[],nodes:[],modules:[],unresolved:[],version:1}),jn=20,Ye=e=>`${e.from} -${e.kind}-> ${e.to}`,ee=(e,r)=>{const t=new Set(e);return r.filter(n=>!t.has(n)).toSorted((n,o)=>n.localeCompare(o))},On=(e,r)=>{const t=e.modules.map(i=>i.name),n=r.modules.map(i=>i.name),o=e.edges.map(i=>Ye(i)),s=r.edges.map(i=>Ye(i));return{addedEdges:ee(o,s),addedModules:ee(t,n),removedEdges:ee(s,o),removedModules:ee(n,t)}},re=(e,r,t)=>{if(t.length===0)return[];const n=t.slice(0,jn).map(s=>` ${e} ${s}`),o=t.length-n.length;return[`${r}:`,...n,...o>0?[` … and ${o.toString()} more`]:[]]},Dn=e=>{const r=[...re("+","modules added",e.addedModules),...re("-","modules removed",e.removedModules),...re("+","edges added",e.addedEdges),...re("-","edges removed",e.removedEdges)];return r.length===0?void 0:`architecture changes since the last deploy:
2
2
  ${r.join(`
3
- `)}`},Dn=(e,r)=>p(e,".lunora",r===void 0?"architecture.json":`architecture.${r}.json`),Nn=e=>{if(b(e))try{const r=JSON.parse(E(e,"utf8"));return r.version===1&&Array.isArray(r.modules)&&Array.isArray(r.edges)?r:void 0}catch{return}},Ln=e=>{const{cwd:r,environment:t,logger:n}=e,o=Dn(r,t),s=Nn(o),i=e.current??(s===void 0?void 0:Pn);if(i===void 0)return;const a=s===void 0?void 0:On(jn(s,i));return a!==void 0&&n.info(a),()=>{try{Ae(I(o),{recursive:!0}),X(o,`${JSON.stringify(i,void 0,2)}
4
- `,"utf8")}catch(c){n.warn(`could not record the deployed architecture at ${o}: ${c instanceof Error?c.message:String(c)}`)}}},xn=e=>{const{cwd:r,env:t,logger:n,mintedSecretsFile:o}=e;try{const s=Ce(r),i=s?.workerName??Ie(r),a=e.url??s?.workerUrl;n.success("deploy complete"),n.info(` worker: ${i??"(see wrangler output above)"}`),t!==void 0&&n.info(` env: ${t}`),a===void 0?n.info(" url: run `lunora link --url <https://your-worker>` to record it"):n.info(` url: ${a}`),o!==void 0&&n.info(` secrets: generated value(s) recorded in ${o}`),e.logsAvailable&&n.info(" logs: lunora logs")}catch{}},Mn=/\/index$/u,Fn=/[^\dA-Za-z]/gu,Un=e=>e.replace(Mn,"").split("/").map(r=>r.replaceAll(Fn,"_")),Bn=e=>Un(e).join("_"),Wn=/[^a-z0-9-]/gu,Hn=/-$/u,Je=7,qn=(e,r)=>{const t=e.toLowerCase(),n=t.replaceAll(Wn,"-");if(n===t&&n.length<=r)return n;const o=gn("sha256").update(t).digest("hex").slice(0,Je-1);return`${n.slice(0,r-Je).replace(Hn,"")}-${o}`},Vn=32,Pr=15e3,Gn=5432,Kn=3306,zn=/[^A-Za-z0-9]/gu,Y=e=>`LUNORA_${e.replaceAll(zn,"_").toUpperCase()}_URL`,Jn=e=>{const r=new Map;for(const t of e){const n=Y(t),o=r.get(n);if(o!==void 0)return{bindings:[o,t],variable:n};r.set(n,t)}},Yn=(e,r)=>qn(`${e}-${r}`,Vn),Ye=e=>e==="postgresql"?"postgres":e==="mariadb"?"mysql":e,Xn=e=>e==="mysql"?Kn:Gn,Qn=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===""?Xn(Ye(t)):Number(r.port),scheme:Ye(t),user:decodeURIComponent(r.username)}}catch{return}},Zn=(e,r)=>{const t=typeof r?.password=="string"?r.password:"",n=t===""?[]:[t,JSON.stringify(t).slice(1,-1),encodeURIComponent(t)];let o=e;for(const s of n)o=o.replaceAll(s,"<redacted>");return o.split(" ").map(s=>s.includes("://")?"<url>":s).join(" ")},Ir=e=>(Array.isArray(e)?e:[]).flatMap((r,t)=>{const{binding:n,id:o}=typeof r=="object"&&r!==null?r:{};return typeof n=="string"&&o===br?[{binding:n,index:t}]:[]}),se=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}`},eo=e=>typeof e=="string"||typeof e=="number"?e.toString():void 0,ro=["scheme","host","port","database","user"],to=e=>e==="postgresql"?"postgres":e,Xe=(e,r)=>{const t=eo(r);return e==="scheme"?to(t):t},Qe=50,no=async(e,r)=>{for(let t=1;t<=Qe;t+=1){const n=await e(t===1?"/hyperdrive/configs":`/hyperdrive/configs?page=${String(t)}`);if(!n.ok)throw new Error(`listing Hyperdrive configs failed (${se(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(i=>i.name===r),s=typeof n.body.result_info=="object"&&n.body.result_info!==null?n.body.result_info:{};if(o!==void 0||typeof s.total_pages!="number"||t>=s.total_pages)return o}throw new Error(`the listing of Hyperdrive configs has more than ${String(Qe)} pages, so "${r}" can't be shown to be absent`)},oo=async(e,r,t,n)=>{const o=n?{caching:{disabled:!0}}:{},s=await no(e,r);if(typeof s?.id=="string"){const c=ro.filter(d=>Xe(d,s.origin?.[d])!==Xe(d,t[d]));if(c.length>0)throw new Error(`a Hyperdrive config named "${r}" already exists for a different origin, or one that can't be confirmed (${c.join(", ")}). Delete it, or rename the Worker, so the binding does not reach the wrong database.`);const l=await e(`/hyperdrive/configs/${encodeURIComponent(s.id)}`,{body:JSON.stringify({origin:t,...o}),method:"PATCH"});if(!l.ok)throw new Error(`updating its credentials failed (${se(l)})`);return{id:s.id,reused:!0}}const i=await e("/hyperdrive/configs",{body:JSON.stringify({name:r,origin:t,...o}),method:"POST"});if(!i.ok)throw new Error(`creating it failed (${se(i)})`);const{id:a}=typeof i.body.result=="object"&&i.body.result!==null?i.body.result:{};if(typeof a!="string")throw new TypeError("the response carried no id");return{id:a,reused:!1}},so=(e,r,t,n)=>r===void 0&&n?`${Y(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 ${Y(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.`,io=async(e,r)=>{const t=Yn(e.workerName,e.binding),{id:n,reused:o}=await oo(async(s,i)=>Cr({accountId:e.accountId,apiToken:e.token,...e.fetch===void 0?{}:{fetch:e.fetch},init:{...i,signal:AbortSignal.timeout(Pr)},path:s}),t,e.origin,e.disableCaching);return e.logger.success(`${o?"reusing":"created"} Hyperdrive config "${t}" for ${e.binding} → ${e.wranglerPath}`),{id:n,text:$r(r,[...e.path,e.index,"id"],n)}},ao=e=>e===void 0||e===""?void 0:e,De=e=>{const r=p(I(e),".wrangler","deploy","config.json");try{const{configPath:t}=JSON.parse(E(r,"utf8"));return typeof t=="string"?C(I(r),t):void 0}catch{return}},co=(e,r,t,n,o)=>{const s=De(e);if(s===void 0||s===e)return;if(n.built!==n.deployed){o.warn(`the build output ${s} was made for ${n.built===void 0?"the default environment":`"${n.built}"`}, not ${n.deployed===void 0?"the default environment":`"${n.deployed}"`}, so the "${r}" Hyperdrive id was not written there. Build with CLOUDFLARE_ENV set to the environment you deploy, then deploy again.`);return}let i;try{i=j(s)}catch{return}const a=Ir(i.parsed?.hyperdrive).find(c=>c.binding===r);a!==void 0&&X(s,$r(i.text,["hyperdrive",a.index,"id"],t),"utf8")},lo=(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}`},Ne=(e,r)=>{const t=N(e),n=t===void 0?void 0:j(t).parsed;if(t===void 0||n===void 0)return;const o=r===void 0?void 0:n.env?.[r],s=Ir(r===void 0?n.hyperdrive:o?.hyperdrive);return s.length===0?void 0:{accountId:o?.account_id??n.account_id,entries:s,path:r===void 0?["hyperdrive"]:["env",r,"hyperdrive"],workerName:lo(n,r),wranglerPath:t}},uo=(e,r,t)=>{const n=Jn(e.map(({binding:o})=>o));if(n!==void 0){const o=`deploy blocked: the Hyperdrive bindings ${n.bindings.map(s=>`"${s}"`).join(" and ")} both read ${n.variable} and would share one config. Rename one so their names differ in letters or digits, not only in punctuation.`;return t.logger.error(o),o}for(const{binding:o,origin:s,supplied:i}of e){const a=so(o,s,r,i);if(a!==void 0&&t.dryRun===!0)t.logger.warn(`dry run: ${a} A real deploy stops here.`);else if(a!==void 0){const c=`deploy blocked: ${a}`;return t.logger.error(c),c}}},fo=async(e,r,t,n)=>{let o;try{o=await e(`/hyperdrive/configs/${encodeURIComponent(t)}`)}catch(i){n.warn(`could not check whether the "${r}" Hyperdrive config has query caching off (${i instanceof Error?i.message:String(i)}).`);return}if(!o.ok){n.warn(`could not check whether the "${r}" Hyperdrive config has query caching off (${se(o)}).`);return}const{caching:s}=typeof o.body.result=="object"&&o.body.result!==null?o.body.result:{};s?.disabled!==!0&&n.warn(`the "${r}" Hyperdrive config has query caching on, so .global() tables would read rows up to 75 s old. Run \`wrangler hyperdrive update ${t} --caching-disabled\`.`)},go=async(e,r)=>{const t=N(e.cwd),n=t===void 0?void 0:j(t).parsed,o=e.wranglerEnvironment===void 0?n:n?.env?.[e.wranglerEnvironment],{accountId:s,token:i}=Tr(r,o?.account_id??n?.account_id);if(s===void 0||i===void 0)return;const a=async(c,l)=>Cr({accountId:s,apiToken:i,...e.fetch===void 0?{}:{fetch:e.fetch},init:{...l,signal:AbortSignal.timeout(Pr)},path:c});for(const c of Array.isArray(o?.hyperdrive)?o.hyperdrive:[]){const{binding:l,id:d}=typeof c=="object"&&c!==null?c:{};typeof l=="string"&&typeof d=="string"&&d!==br&&await fo(a,l,d,e.logger)}},ho=async e=>{const r=e.environment??process.env;e.disableCaching===!0&&e.checkOnly!==!0&&e.dryRun!==!0&&await go(e,r);const t=Ne(e.cwd,e.wranglerEnvironment);if(t===void 0)return;const{entries:n,path:o,wranglerPath:s}=t,{accountId:i,token:a}=Tr(r,t.accountId),c=n.map(({binding:d})=>{const f=r[Y(d)]??"";return{binding:d,origin:Qn(f),supplied:f!==""}}),l=uo(c,a!==void 0&&i!==void 0,e);if(l!==void 0)return l;if(!(e.dryRun===!0||e.checkOnly===!0))for(const[d,{binding:f,index:u}]of n.entries()){const h=c[d]?.origin;if(!(h===void 0||a===void 0||i===void 0))try{const{id:g,text:v}=await io({accountId:i,binding:f,disableCaching:e.disableCaching===!0,fetch:e.fetch,index:u,logger:e.logger,origin:h,path:o,token:a,workerName:t.workerName,wranglerPath:s},E(s,"utf8"));X(s,v,"utf8"),co(s,f,g,{built:ao(r.CLOUDFLARE_ENV),deployed:e.wranglerEnvironment},e.logger)}catch(g){const v=g instanceof Error?g.message:String(g),m=`deploy blocked: the "${f}" Hyperdrive config could not be set up: ${Zn(v,c[d]?.origin)}`;return e.logger.error(m),m}}},mo=(e,r)=>{const t=Ne(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 ${Y(t)} set to create the config, or put the id from \`wrangler hyperdrive create\` in wrangler.jsonc.`;return r.logger.error(n),n},po=(e,r)=>{const t=Ne(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},jr=async(e,r,t,n,o="create")=>{if(n!=="cloudflare")return;if(t==="prepare")return mo(e,r);if(r.temporary===!0)return po(e,r);const s=r.clientBuildEnvironment===void 0?void 0:{...process.env,CLOUDFLARE_ENV:r.clientBuildEnvironment},i=_e(e,F(e),r.discoveryCache);return i.error!==void 0&&r.logger.warn(`could not read the schema (${i.error}), so Hyperdrive configs are set up with query caching off.`),ho({checkOnly:o==="check",cwd:e,disableCaching:i.error!==void 0||i.info?.hasHyperdriveGlobalTable===!0,dryRun:r.dryRun,environment:s,logger:r.logger,wranglerEnvironment:r.env})},me=[".ts",".tsx",".mts",".js",".mjs"],vo=/^[a-z]+:/u,Ze=/\.[cm]?js$/u,yo=e=>!e.startsWith(".")&&!e.startsWith("/")&&!e.startsWith("#")&&!vo.test(e),wo=e=>e.split("/").slice(0,e.startsWith("@")?2:1).join("/"),ko=e=>e.split(M).some(r=>r==="_generated"||r==="node_modules"),bo=e=>e.split(M).includes("node_modules"),er=(e,r)=>{const t=C(I(e),r),n=Ze.test(t)?t.replace(Ze,""):void 0;return[t,...n===void 0?[]:me.map(s=>`${n}${s}`),...me.map(s=>`${t}${s}`),...me.map(s=>p(t,`index${s}`))].find(s=>b(s)&&Re(s).isFile())},$o=/^lunora\.config\.[cm]?[jt]s$/u,ke=e=>{if(typeof e=="string")return e;if(typeof e=="object"&&e!==null)for(const[r,t]of Object.entries(e)){const n=r==="types"?void 0:ke(t);if(n!==void 0)return n}},So=(e,r)=>{let t;try{t=JSON.parse(E(p(e,"package.json"),"utf8")).imports}catch{return}const n=ke(t?.[r]);if(n!==void 0)return n;for(const[o,s]of Object.entries(t??{})){const[i="",a=""]=o.split("*"),c=ke(s);if(c!==void 0&&o.includes("*")&&r.startsWith(i)&&r.endsWith(a)&&r.length>=o.length-1){const l=r.slice(i.length,r.length-a.length);return c.replaceAll("*",()=>l)}}},Eo=(e,r)=>{const t=p(e,r,"_generated"),n=K(e).find(o=>$o.test(o));return[...b(t)?K(t).filter(o=>o.endsWith(".ts")).map(o=>p(t,o)):[],...n===void 0?[]:[p(e,n)]]},Ao=e=>{const r=y.findConfigFile(e,n=>y.sys.fileExists(n));if(r===void 0)return!1;const t=y.readConfigFile(r,n=>y.sys.readFile(n));return y.parseJsonConfigFileContent(t.config??{},y.sys,I(r)).options.verbatimModuleSyntax===!0},rr=e=>e!==void 0&&(y.isNamedImports(e)||y.isNamedExports(e))&&e.elements.length>0&&e.elements.every(r=>r.isTypeOnly),Ro=(e,r)=>{if(y.isImportDeclaration(e)){const{importClause:t}=e;return!(t?.phaseModifier===y.SyntaxKind.TypeKeyword||!r&&t?.name===void 0&&rr(t?.namedBindings))&&y.isStringLiteral(e.moduleSpecifier)?e.moduleSpecifier.text:void 0}if(y.isExportDeclaration(e))return!(e.isTypeOnly||!r&&rr(e.exportClause))&&e.moduleSpecifier!==void 0&&y.isStringLiteral(e.moduleSpecifier)?e.moduleSpecifier.text:void 0},To=e=>{if(!y.isCallExpression(e)||e.expression.kind!==y.SyntaxKind.ImportKeyword)return;const[r]=e.arguments;return r!==void 0&&y.isStringLiteralLike(r)?r.text:void 0},Co=(e,r)=>{const t=y.createSourceFile(e,E(e,"utf8"),y.ScriptTarget.Latest,!1),n=[],o=[],s=i=>{const a=To(i),c=a??Ro(i,r);c?.startsWith(".")||c?.startsWith("#")?o.push(c):a!==void 0&&yo(a)&&n.push(a),y.forEachChild(i,s)};return s(t),{dynamicPackages:n,relative:o}},_o=(e,r)=>{for(let t=e;;t=I(t)){if(b(p(t,"node_modules",r,"package.json")))return!0;if(I(t)===t)return!1}},Po=(e,r,t)=>{const n=Ao(e),o=new Set,s=new Set,i=r!==void 0&&b(C(e,r))?[C(e,r)]:Eo(e,t);for(let a=i.shift();a!==void 0;a=i.shift())if(!o.has(a)&&!bo(L(e,a))){o.add(a);const{dynamicPackages:c,relative:l}=Co(a,n);if(!ko(L(e,a)))for(const d of c)s.add(d);i.push(...l.flatMap(d=>{if(!d.startsWith("#"))return er(a,d)??[];const f=So(e,d);return f===void 0?[]:er(p(e,"package.json"),f)??[]}))}return[...s].filter(a=>_o(e,wo(a))).toSorted((a,c)=>a.localeCompare(c))},Io=18787,tr=3,be=12e4,jo=5e3,H=10,Or=new Set([".js",".mjs",".mts",".ts",".tsx"]),Oo=/\(void 0\)|is not a function|before initialization|of undefined/u,Do=e=>typeof e=="object"&&e!==null&&typeof e.functionPath=="string"&&(e.deferred===void 0||["agent","module","queue","workflow"].includes(e.deferred))&&typeof e.message=="string",No=e=>{const r=F(e),t=new Map;let n;try{n=K(p(e,r),{recursive:!0,encoding:"utf8"})}catch{return t}for(const o of n){const s=ft(o);Or.has(s)&&!o.split(M).some(i=>i==="_generated"||i==="node_modules")&&t.set(Bn(o.slice(0,-s.length).split(M).join("/")),p(r,o))}return t},nr=e=>Oo.test(e)?`
5
- hint: if this module is part of a circular import, an import it reads is still undefined while it evaluates`:"",Lo=(e,r)=>{const t=No(e),n=new Map,o=[];for(const{deferred:s,functionPath:i,message:a}of r){if(s!==void 0){o.push(` ${i.slice(s.length+1)} (${s}): ${a}${nr(a)}`);continue}const c=i.lastIndexOf(":"),l=i.slice(0,c),d=`${l}\0${a}`,f=n.get(d)??{exports:[],message:a,namespace:l};f.exports.push(i.slice(c+1)),n.set(d,f)}return[...[...n.values()].map(({exports:s,message:i,namespace:a})=>` ${t.get(a)??a} (${s.join(", ")}): ${i}${nr(i)}`),...o]},te=e=>{for(const r of Or)for(const t of[`${e}${r}`,p(e,`index${r}`)])if(b(t))return t},xo=(e,r)=>{const t=p(e,r,"_generated"),n=a=>{try{return E(p(t,a),"utf8")}catch{return""}},o=n("app.ts"),s=[],i=(a,c)=>{c!==void 0&&s.push({file:c,kind:a,label:L(e,c).split(M).join("/")})};return o.includes('import("./queues.js")')&&i("queue",te(p(t,"queues"))),n("workflows.mjs").includes('import("../workflows.js")')&&i("workflow",te(p(e,r,"workflows"))),(n("agents.mjs").includes('import("../agents.js")')||o.includes('import("../agents.js")'))&&i("agent",te(p(e,r,"agents"))),s},Mo=/\.[cm]?js$/u,Fo=(e,r)=>{const t=[],n=o=>{if(y.isCallExpression(o)&&o.expression.kind===y.SyntaxKind.ImportKeyword){const[s]=o.arguments;s!==void 0&&y.isStringLiteralLike(s)&&t.push(s.text)}y.forEachChild(o,n)};return n(y.createSourceFile(e,r,y.ScriptTarget.Latest,!1,y.ScriptKind.TS)),t},Uo=(e,r,t)=>{const n=p(e,r,"_generated"),o=new Set(t.map(a=>a.file)),s=[];let i;try{i=K(n).filter(a=>a.endsWith(".mjs")&&a!=="functions.ts")}catch{return s}for(const a of i.toSorted((c,l)=>c.localeCompare(l)))for(const c of Fo(p(n,a),E(p(n,a),"utf8"))){const l=c.startsWith("."),d=l?te(C(n,c.replace(Mo,""))):c;d!==void 0&&!o.has(d)&&(o.add(d),s.push({file:d,kind:"module",label:l?L(e,d).split(M).join("/"):c}))}return s};class P extends Error{skipped;constructor(r,t=!1){super(r),this.skipped=t}}const or=/^[$_\p{ID_Start}][$\u200C\u200D\p{ID_Continue}]*$/u,Dr=(e,r,t)=>{const n=t??N(e),o=n===void 0?void 0:j(n).parsed;if(o===void 0)return{assetsDirectory:void 0,durableObjectClasses:[],entrypointClasses:[],hasContainers:!1,main:void 0,workflowClasses:[]};const{merged:s}=ue(o,r),i=d=>[...new Set(d.flatMap(f=>f?.script_name===void 0&&typeof f?.class_name=="string"&&or.test(f.class_name)?[f.class_name]:[]))],a=s.exports??{},c=d=>Object.entries(a).flatMap(([f,u])=>u?.type===d&&(u.state===void 0||u.state==="created")&&or.test(f)?[f]:[]),l=s.assets?.directory;return{assetsDirectory:l===void 0||n===void 0?void 0:C(I(n),l),durableObjectClasses:[...new Set([...i(s.durable_objects?.bindings??[]),...c("durable-object")])],entrypointClasses:c("worker"),hasContainers:(s.containers??[]).length>0,main:s.main,workflowClasses:[...new Set([...i(s.workflows??[]),...c("workflow")])]}},Bo=({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{assetsDirectory:s,durableObjectClasses:i,entrypointClasses:a,hasContainers:c,main:l,workflowClasses:d}=Dr(t,n,r),f=e??l,u=r??N(t);let h;if(u!==void 0&&De(u)!==void 0)h={stubs:{durableObjects:i,entrypoints:a,workflows:d}};else if(typeof f=="string"&&!f.startsWith("virtual:")&&b(C(t,f)))h={main:f};else return{skip:"the Worker entry is not a file on disk"};const g=s!==void 0&&!b(s);if(c)return{skip:"the project declares containers, which `wrangler dev` would build locally before the real container build"};const v=Bt(t,process.env,n,r);return v.length>0?{skip:`the Hyperdrive binding ${v.join(", ")} has no local database for wrangler dev`}:{base:h,configFile:u,missingAssets:g}},Wo=/The Workers runtime failed to start|Build failed with \d+ error/u,Ho=/\[ERROR\]|Uncaught/u,sr=e=>{const r=e.map(o=>mn(o).trim()).filter(o=>o!==""),t=r.filter(o=>Ho.test(o)),n=t.length>0?t.slice(0,10):r.slice(-10);return n.length===0?"":`
3
+ `)}`},Ln=(e,r)=>p(e,".lunora",r===void 0?"architecture.json":`architecture.${r}.json`),Nn=e=>{if(b(e))try{const r=JSON.parse(E(e,"utf8"));return r.version===1&&Array.isArray(r.modules)&&Array.isArray(r.edges)?r:void 0}catch{return}},xn=e=>{const{cwd:r,environment:t,logger:n}=e,o=Ln(r,t),s=Nn(o),i=e.current??(s===void 0?void 0:In);if(i===void 0)return;const a=s===void 0?void 0:Dn(On(s,i));return a!==void 0&&n.info(a),()=>{try{Re(R(o),{recursive:!0}),X(o,`${JSON.stringify(i,void 0,2)}
4
+ `,"utf8")}catch(c){n.warn(`could not record the deployed architecture at ${o}: ${c instanceof Error?c.message:String(c)}`)}}},Fn=e=>{const{cwd:r,env:t,logger:n,mintedSecretsFile:o}=e;try{const s=_e(r),i=s?.workerName??je(r),a=e.url??s?.workerUrl;n.success("deploy complete"),n.info(` worker: ${i??"(see wrangler output above)"}`),t!==void 0&&n.info(` env: ${t}`),a===void 0?n.info(" url: run `lunora link --url <https://your-worker>` to record it"):n.info(` url: ${a}`),o!==void 0&&n.info(` secrets: generated value(s) recorded in ${o}`),e.logsAvailable&&n.info(" logs: lunora logs")}catch{}},Mn=/\/index$/u,Un=/[^\dA-Za-z]/gu,Bn=e=>e.replace(Mn,"").split("/").map(r=>r.replaceAll(Un,"_")),Wn=e=>Bn(e).join("_"),Hn=/[^a-z0-9-]/gu,qn=/-$/u,Xe=7,Gn=(e,r)=>{const t=e.toLowerCase(),n=t.replaceAll(Hn,"-");if(n===t&&n.length<=r)return n;const o=hn("sha256").update(t).digest("hex").slice(0,Xe-1);return`${n.slice(0,r-Xe).replace(qn,"")}-${o}`},Vn=32,jr=15e3,Kn=5432,zn=3306,Jn=/[^A-Za-z0-9]/gu,Y=e=>`LUNORA_${e.replaceAll(Jn,"_").toUpperCase()}_URL`,Yn=e=>{const r=new Map;for(const t of e){const n=Y(t),o=r.get(n);if(o!==void 0)return{bindings:[o,t],variable:n};r.set(n,t)}},Xn=(e,r)=>Gn(`${e}-${r}`,Vn),Qe=e=>e==="postgresql"?"postgres":e==="mariadb"?"mysql":e,Qn=e=>e==="mysql"?zn:Kn,Zn=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===""?Qn(Qe(t)):Number(r.port),scheme:Qe(t),user:decodeURIComponent(r.username)}}catch{return}},eo=(e,r)=>{const t=typeof r?.password=="string"?r.password:"",n=t===""?[]:[t,JSON.stringify(t).slice(1,-1),encodeURIComponent(t)];let o=e;for(const s of n)o=o.replaceAll(s,"<redacted>");return o.split(" ").map(s=>s.includes("://")?"<url>":s).join(" ")},Or=e=>(Array.isArray(e)?e:[]).flatMap((r,t)=>{const{binding:n,id:o}=typeof r=="object"&&r!==null?r:{};return typeof n=="string"&&o===Sr?[{binding:n,index:t}]:[]}),se=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}`},ro=e=>typeof e=="string"||typeof e=="number"?e.toString():void 0,to=["scheme","host","port","database","user"],no=e=>e==="postgresql"?"postgres":e,Ze=(e,r)=>{const t=ro(r);return e==="scheme"?no(t):t},er=50,oo=async(e,r)=>{for(let t=1;t<=er;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 (${se(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(i=>i.name===r),s=typeof n.body.result_info=="object"&&n.body.result_info!==null?n.body.result_info:{};if(o!==void 0||typeof s.total_pages!="number"||t>=s.total_pages)return o}throw new Error(`the listing of Hyperdrive configs has more than ${String(er)} pages, so "${r}" can't be shown to be absent`)},so=async(e,r,t,n)=>{const o=n?{caching:{disabled:!0}}:{},s=await oo(e,r);if(typeof s?.id=="string"){const c=to.filter(d=>Ze(d,s.origin?.[d])!==Ze(d,t[d]));if(c.length>0)throw new Error(`a Hyperdrive config named "${r}" already exists for a different origin, or one that can't be confirmed (${c.join(", ")}). Delete it, or rename the Worker, so the binding does not reach the wrong database.`);const l=await e(`/hyperdrive/configs/${encodeURIComponent(s.id)}`,{body:JSON.stringify({origin:t,...o}),method:"PATCH"});if(!l.ok)throw new Error(`updating its credentials failed (${se(l)})`);return{id:s.id,reused:!0}}const i=await e("/hyperdrive/configs",{body:JSON.stringify({name:r,origin:t,...o}),method:"POST"});if(!i.ok)throw new Error(`creating it failed (${se(i)})`);const{id:a}=typeof i.body.result=="object"&&i.body.result!==null?i.body.result:{};if(typeof a!="string")throw new TypeError("the response carried no id");return{id:a,reused:!1}},io=(e,r,t,n)=>r===void 0&&n?`${Y(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 ${Y(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.`,ao=async(e,r)=>{const t=Xn(e.workerName,e.binding),{id:n,reused:o}=await so(async(s,i)=>Pr({accountId:e.accountId,apiToken:e.token,...e.fetch===void 0?{}:{fetch:e.fetch},init:{...i,signal:AbortSignal.timeout(jr)},path:s}),t,e.origin,e.disableCaching);return e.logger.success(`${o?"reusing":"created"} Hyperdrive config "${t}" for ${e.binding} → ${e.wranglerPath}`),{id:n,text:Er(r,[...e.path,e.index,"id"],n)}},co=e=>e===void 0||e===""?void 0:e,Le=e=>{const r=p(R(e),".wrangler","deploy","config.json");try{const{configPath:t}=JSON.parse(E(r,"utf8"));return typeof t=="string"?P(R(r),t):void 0}catch{return}},lo=(e,r,t,n,o)=>{const s=Le(e);if(s===void 0||s===e)return;if(n.built!==n.deployed){o.warn(`the build output ${s} was made for ${n.built===void 0?"the default environment":`"${n.built}"`}, not ${n.deployed===void 0?"the default environment":`"${n.deployed}"`}, so the "${r}" Hyperdrive id was not written there. Build with CLOUDFLARE_ENV set to the environment you deploy, then deploy again.`);return}let i;try{i=j(s)}catch{return}const a=Or(i.parsed?.hyperdrive).find(c=>c.binding===r);a!==void 0&&X(s,Er(i.text,["hyperdrive",a.index,"id"],t),"utf8")},uo=(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}`},fe=(e,r,t)=>{const n=t??O(e),o=n===void 0?void 0:j(n).parsed;if(n===void 0||o===void 0)return;const s=r===void 0?void 0:o.env?.[r],i=Or(r===void 0?o.hyperdrive:s?.hyperdrive);return i.length===0?void 0:{accountId:s?.account_id??o.account_id,entries:i,path:r===void 0?["hyperdrive"]:["env",r,"hyperdrive"],workerName:uo(o,r),wranglerPath:n}},fo=(e,r,t)=>{const n=Yn(e.map(({binding:o})=>o));if(n!==void 0){const o=`deploy blocked: the Hyperdrive bindings ${n.bindings.map(s=>`"${s}"`).join(" and ")} both read ${n.variable} and would share one config. Rename one so their names differ in letters or digits, not only in punctuation.`;return t.logger.error(o),o}for(const{binding:o,origin:s,supplied:i}of e){const a=io(o,s,r,i);if(a!==void 0&&t.dryRun===!0)t.logger.warn(`dry run: ${a} A real deploy stops here.`);else if(a!==void 0){const c=`deploy blocked: ${a}`;return t.logger.error(c),c}}},go=async(e,r,t,n)=>{let o;try{o=await e(`/hyperdrive/configs/${encodeURIComponent(t)}`)}catch(i){n.warn(`could not check whether the "${r}" Hyperdrive config has query caching off (${i instanceof Error?i.message:String(i)}).`);return}if(!o.ok){n.warn(`could not check whether the "${r}" Hyperdrive config has query caching off (${se(o)}).`);return}const{caching:s}=typeof o.body.result=="object"&&o.body.result!==null?o.body.result:{};s?.disabled!==!0&&n.warn(`the "${r}" Hyperdrive config has query caching on, so .global() tables would read rows up to 75 s old. Run \`wrangler hyperdrive update ${t} --caching-disabled\`.`)},ho=async(e,r)=>{const t=e.wranglerPath??O(e.cwd),n=t===void 0?void 0:j(t).parsed,o=e.wranglerEnvironment===void 0?n:n?.env?.[e.wranglerEnvironment],{accountId:s,token:i}=_r(r,o?.account_id??n?.account_id);if(s===void 0||i===void 0)return;const a=async(c,l)=>Pr({accountId:s,apiToken:i,...e.fetch===void 0?{}:{fetch:e.fetch},init:{...l,signal:AbortSignal.timeout(jr)},path:c});for(const c of Array.isArray(o?.hyperdrive)?o.hyperdrive:[]){const{binding:l,id:d}=typeof c=="object"&&c!==null?c:{};typeof l=="string"&&typeof d=="string"&&d!==Sr&&await go(a,l,d,e.logger)}},mo=async e=>{const r=e.environment??process.env;e.disableCaching===!0&&e.checkOnly!==!0&&e.dryRun!==!0&&await ho(e,r);const t=fe(e.cwd,e.wranglerEnvironment,e.wranglerPath);if(t===void 0)return;const{entries:n,path:o,wranglerPath:s}=t,{accountId:i,token:a}=_r(r,t.accountId),c=n.map(({binding:d})=>{const u=r[Y(d)]??"";return{binding:d,origin:Zn(u),supplied:u!==""}}),l=fo(c,a!==void 0&&i!==void 0,e);if(l!==void 0)return l;if(!(e.dryRun===!0||e.checkOnly===!0))for(const[d,{binding:u,index:f}]of n.entries()){const g=c[d]?.origin;if(!(g===void 0||a===void 0||i===void 0))try{const{id:h,text:v}=await ao({accountId:i,binding:u,disableCaching:e.disableCaching===!0,fetch:e.fetch,index:f,logger:e.logger,origin:g,path:o,token:a,workerName:t.workerName,wranglerPath:s},E(s,"utf8"));X(s,v,"utf8"),lo(s,u,h,{built:co(r.CLOUDFLARE_ENV),deployed:e.wranglerEnvironment},e.logger)}catch(h){const v=h instanceof Error?h.message:String(h),m=`deploy blocked: the "${u}" Hyperdrive config could not be set up: ${eo(v,c[d]?.origin)}`;return e.logger.error(m),m}}},po=(e,r)=>{const t=fe(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 ${Y(t)} set to create the config, or put the id from \`wrangler hyperdrive create\` in wrangler.jsonc.`;return r.logger.error(n),n},vo=(e,r)=>{const t=fe(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},H=async(e,r,t,n,o="create",s)=>{if(n!=="cloudflare")return;if(t==="prepare")return po(e,r);if(r.temporary===!0)return vo(e,r);const i=r.clientBuildEnvironment===void 0?void 0:{...process.env,CLOUDFLARE_ENV:r.clientBuildEnvironment},a=Pe(e,x(e),r.discoveryCache);return a.error!==void 0&&r.logger.warn(`could not read the schema (${a.error}), so Hyperdrive configs are set up with query caching off.`),mo({checkOnly:o==="check",cwd:e,disableCaching:a.error!==void 0||a.info?.hasHyperdriveGlobalTable===!0,dryRun:r.dryRun,environment:i,logger:r.logger,wranglerEnvironment:r.env,wranglerPath:s})},yo=(e,r,t)=>fe(e,r,t)!==void 0,pe=[".ts",".tsx",".mts",".js",".mjs"],wo=/^[a-z]+:/u,rr=/\.[cm]?js$/u,ko=e=>!e.startsWith(".")&&!e.startsWith("/")&&!e.startsWith("#")&&!wo.test(e),bo=e=>e.split("/").slice(0,e.startsWith("@")?2:1).join("/"),$o=e=>e.split(N).some(r=>r==="_generated"||r==="node_modules"),So=e=>e.split(N).includes("node_modules"),tr=(e,r)=>{const t=P(R(e),r),n=rr.test(t)?t.replace(rr,""):void 0;return[t,...n===void 0?[]:pe.map(s=>`${n}${s}`),...pe.map(s=>`${t}${s}`),...pe.map(s=>p(t,`index${s}`))].find(s=>b(s)&&Te(s).isFile())},Eo=/^lunora\.config\.[cm]?[jt]s$/u,be=e=>{if(typeof e=="string")return e;if(typeof e=="object"&&e!==null)for(const[r,t]of Object.entries(e)){const n=r==="types"?void 0:be(t);if(n!==void 0)return n}},Ao=(e,r)=>{let t;try{t=JSON.parse(E(p(e,"package.json"),"utf8")).imports}catch{return}const n=be(t?.[r]);if(n!==void 0)return n;for(const[o,s]of Object.entries(t??{})){const[i="",a=""]=o.split("*"),c=be(s);if(c!==void 0&&o.includes("*")&&r.startsWith(i)&&r.endsWith(a)&&r.length>=o.length-1){const l=r.slice(i.length,r.length-a.length);return c.replaceAll("*",()=>l)}}},Ro=(e,r)=>{const t=p(e,r,"_generated"),n=K(e).find(o=>Eo.test(o));return[...b(t)?K(t).filter(o=>o.endsWith(".ts")).map(o=>p(t,o)):[],...n===void 0?[]:[p(e,n)]]},To=e=>{const r=w.findConfigFile(e,n=>w.sys.fileExists(n));if(r===void 0)return!1;const t=w.readConfigFile(r,n=>w.sys.readFile(n));return w.parseJsonConfigFileContent(t.config??{},w.sys,R(r)).options.verbatimModuleSyntax===!0},nr=e=>e!==void 0&&(w.isNamedImports(e)||w.isNamedExports(e))&&e.elements.length>0&&e.elements.every(r=>r.isTypeOnly),Co=(e,r)=>{if(w.isImportDeclaration(e)){const{importClause:t}=e;return!(t?.phaseModifier===w.SyntaxKind.TypeKeyword||!r&&t?.name===void 0&&nr(t?.namedBindings))&&w.isStringLiteral(e.moduleSpecifier)?e.moduleSpecifier.text:void 0}if(w.isExportDeclaration(e))return!(e.isTypeOnly||!r&&nr(e.exportClause))&&e.moduleSpecifier!==void 0&&w.isStringLiteral(e.moduleSpecifier)?e.moduleSpecifier.text:void 0},_o=e=>{if(!w.isCallExpression(e)||e.expression.kind!==w.SyntaxKind.ImportKeyword)return;const[r]=e.arguments;return r!==void 0&&w.isStringLiteralLike(r)?r.text:void 0},Po=(e,r)=>{const t=w.createSourceFile(e,E(e,"utf8"),w.ScriptTarget.Latest,!1),n=[],o=[],s=i=>{const a=_o(i),c=a??Co(i,r);c?.startsWith(".")||c?.startsWith("#")?o.push(c):a!==void 0&&ko(a)&&n.push(a),w.forEachChild(i,s)};return s(t),{dynamicPackages:n,relative:o}},Io=(e,r)=>{for(let t=e;;t=R(t)){if(b(p(t,"node_modules",r,"package.json")))return!0;if(R(t)===t)return!1}},jo=(e,r,t)=>{const n=To(e),o=new Set,s=new Set,i=r!==void 0&&b(P(e,r))?[P(e,r)]:Ro(e,t);for(let a=i.shift();a!==void 0;a=i.shift())if(!o.has(a)&&!So(D(e,a))){o.add(a);const{dynamicPackages:c,relative:l}=Po(a,n);if(!$o(D(e,a)))for(const d of c)s.add(d);i.push(...l.flatMap(d=>{if(!d.startsWith("#"))return tr(a,d)??[];const u=Ao(e,d);return u===void 0?[]:tr(p(e,"package.json"),u)??[]}))}return[...s].filter(a=>Io(e,bo(a))).toSorted((a,c)=>a.localeCompare(c))},Oo=18787,or=3,$e=12e4,Do=5e3,W=10,Dr=new Set([".js",".mjs",".mts",".ts",".tsx"]),Lo=/\(void 0\)|is not a function|before initialization|of undefined/u,No=e=>typeof e=="object"&&e!==null&&typeof e.functionPath=="string"&&(e.deferred===void 0||["agent","module","queue","workflow"].includes(e.deferred))&&typeof e.message=="string",xo=e=>{const r=x(e),t=new Map;let n;try{n=K(p(e,r),{recursive:!0,encoding:"utf8"})}catch{return t}for(const o of n){const s=gt(o);Dr.has(s)&&!o.split(N).some(i=>i==="_generated"||i==="node_modules")&&t.set(Wn(o.slice(0,-s.length).split(N).join("/")),p(r,o))}return t},sr=e=>Lo.test(e)?`
5
+ hint: if this module is part of a circular import, an import it reads is still undefined while it evaluates`:"",Fo=(e,r)=>{const t=xo(e),n=new Map,o=[];for(const{deferred:s,functionPath:i,message:a}of r){if(s!==void 0){o.push(` ${i.slice(s.length+1)} (${s}): ${a}${sr(a)}`);continue}const c=i.lastIndexOf(":"),l=i.slice(0,c),d=`${l}\0${a}`,u=n.get(d)??{exports:[],message:a,namespace:l};u.exports.push(i.slice(c+1)),n.set(d,u)}return[...[...n.values()].map(({exports:s,message:i,namespace:a})=>` ${t.get(a)??a} (${s.join(", ")}): ${i}${sr(i)}`),...o]},te=e=>{for(const r of Dr)for(const t of[`${e}${r}`,p(e,`index${r}`)])if(b(t))return t},Mo=(e,r)=>{const t=p(e,r,"_generated"),n=a=>{try{return E(p(t,a),"utf8")}catch{return""}},o=n("app.ts"),s=[],i=(a,c)=>{c!==void 0&&s.push({file:c,kind:a,label:D(e,c).split(N).join("/")})};return o.includes('import("./queues.js")')&&i("queue",te(p(t,"queues"))),n("workflows.mjs").includes('import("../workflows.js")')&&i("workflow",te(p(e,r,"workflows"))),(n("agents.mjs").includes('import("../agents.js")')||o.includes('import("../agents.js")'))&&i("agent",te(p(e,r,"agents"))),s},Uo=/\.[cm]?js$/u,Bo=(e,r)=>{const t=[],n=o=>{if(w.isCallExpression(o)&&o.expression.kind===w.SyntaxKind.ImportKeyword){const[s]=o.arguments;s!==void 0&&w.isStringLiteralLike(s)&&t.push(s.text)}w.forEachChild(o,n)};return n(w.createSourceFile(e,r,w.ScriptTarget.Latest,!1,w.ScriptKind.TS)),t},Wo=(e,r,t)=>{const n=p(e,r,"_generated"),o=new Set(t.map(a=>a.file)),s=[];let i;try{i=K(n).filter(a=>a.endsWith(".mjs")&&a!=="functions.ts")}catch{return s}for(const a of i.toSorted((c,l)=>c.localeCompare(l)))for(const c of Bo(p(n,a),E(p(n,a),"utf8"))){const l=c.startsWith("."),d=l?te(P(n,c.replace(Uo,""))):c;d!==void 0&&!o.has(d)&&(o.add(d),s.push({file:d,kind:"module",label:l?D(e,d).split(N).join("/"):c}))}return s};class I extends Error{skipped;constructor(r,t=!1){super(r),this.skipped=t}}const ir=/^[$_\p{ID_Start}][$\u200C\u200D\p{ID_Continue}]*$/u,Lr=(e,r,t)=>{const n=t??O(e),o=n===void 0?void 0:j(n).parsed;if(o===void 0)return{assetsDirectory:void 0,durableObjectClasses:[],entrypointClasses:[],hasContainers:!1,main:void 0,workflowClasses:[]};const{merged:s}=ue(o,r),i=d=>[...new Set(d.flatMap(u=>u?.script_name===void 0&&typeof u?.class_name=="string"&&ir.test(u.class_name)?[u.class_name]:[]))],a=s.exports??{},c=d=>Object.entries(a).flatMap(([u,f])=>f?.type===d&&(f.state===void 0||f.state==="created")&&ir.test(u)?[u]:[]),l=s.assets?.directory;return{assetsDirectory:l===void 0||n===void 0?void 0:P(R(n),l),durableObjectClasses:[...new Set([...i(s.durable_objects?.bindings??[]),...c("durable-object")])],entrypointClasses:c("worker"),hasContainers:(s.containers??[]).length>0,main:s.main,workflowClasses:[...new Set([...i(s.workflows??[]),...c("workflow")])]}},Ho=({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{assetsDirectory:s,durableObjectClasses:i,entrypointClasses:a,hasContainers:c,main:l,workflowClasses:d}=Lr(t,n,r),u=e??l,f=r??O(t);let g;if(f!==void 0&&Le(f)!==void 0)g={stubs:{durableObjects:i,entrypoints:a,workflows:d}};else if(typeof u=="string"&&!u.startsWith("virtual:")&&b(P(t,u)))g={main:u};else return{skip:"the Worker entry is not a file on disk"};const h=s!==void 0&&!b(s);if(c)return{skip:"the project declares containers, which `wrangler dev` would build locally before the real container build"};const v=Wt(t,process.env,n,r);return v.length>0?{skip:`the Hyperdrive binding ${v.join(", ")} has no local database for wrangler dev`}:{base:g,configFile:f,missingAssets:h}},qo=/The Workers runtime failed to start|Build failed with \d+ error/u,Go=/\[ERROR\]|Uncaught/u,ar=e=>{const r=e.map(o=>pn(o).trim()).filter(o=>o!==""),t=r.filter(o=>Go.test(o)),n=t.length>0?t.slice(0,10):r.slice(-10);return n.length===0?"":`
6
6
  ${n.map(o=>` ${o}`).join(`
7
- `)}`},Le=async e=>{const{deadline:r,output:t,pending:n,port:o,query:s,startupFailed:i}=e,a=await fetch(`http://127.0.0.1:${String(o)}/_lunora/__smoke_load?${s}`,{signal:AbortSignal.any([AbortSignal.timeout(Math.max(0,r-Date.now())),i])}).catch(d=>{throw i.aborted?new P(`the smoke Worker's runtime did not start, so nothing was evaluated:${sr(t)}
8
- Fix the entry, or pass --no-smoke-load to ship anyway.`):d instanceof Error&&d.name==="TimeoutError"?new P(n===void 0?`the smoke Worker accepted the connection but answered no request within ${String(be/1e3)}s, so its runtime did not start:${sr(t)}
9
- Pass --no-smoke-load to ship anyway.`:`the smoke Worker did not finish evaluating ${n} within ${String(be/1e3)}s — it may be awaiting something that never settles. Pass --no-smoke-load to ship anyway.`):d});if(a.status>=500)throw new P(`the smoke Worker booted but failed while ${n===void 0?"answering a request that evaluates nothing":`evaluating ${n}`} (HTTP ${String(a.status)}). Pass --no-smoke-load to ship anyway.`);const c=await a.text().catch(()=>"");let l;try{l=JSON.parse(c)}catch{l=void 0}return{body:typeof l=="object"&&l!==null?l:void 0,response:a,text:c}},xe=(e,r)=>{const t=e.headers.get("content-type")??"no content type",n=r.replaceAll(/\s+/gu," ").trim().slice(0,120);return new P(`the smoke Worker answered with something other than the probe's result (HTTP ${String(e.status)}, ${t}${n===""?"":`: ${n}`}). 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.`)},Nr=(e,r)=>typeof e=="string"&&e!==r,$e=Symbol("another run's Worker"),ir=async(e,r)=>{const t=await Le(e),n=t.body?.message;if(Nr(t.body?.run,r))return $e;if(t.body?.run!==r||n!==void 0&&typeof n!="string")throw xe(t.response,t.text);return n},qo=async(e,r)=>{const t=await Le({...e,pending:"the lazy function modules",query:"step=functions"}),{checked:n,failures:o}=t.body??{};if(!Nr(t.body?.run,r)){if(t.body?.run!==r||typeof n!="number"||!Array.isArray(o)||!o.every(s=>Do(s)))throw xe(t.response,t.text);return{checked:n,failures:o}}},Vo=async e=>{const{deferred:r,functions:t,integrationModules:n,runId:o,...s}=e,i=await Le({...s,pending:void 0,query:"step=ping"});if(typeof i.body?.run!="string")throw xe(i.response,i.text);if(i.body.run!==o)return;let a=0,c=[];if(t){const d=await qo(s,o);if(d===void 0)return;a=d.checked,c=d.failures}for(const[d,f]of r.entries()){const u=await ir({...s,pending:`${f.kind} module ${f.label}`,query:`step=deferred&index=${String(d)}`},o);if(u===$e)return;u!==void 0&&c.push({deferred:f.kind,functionPath:`${f.kind}:${f.label}`,message:u})}const l=[];for(const d of n){const f=await ir({...s,pending:`import(${JSON.stringify(d)})`,query:new URLSearchParams({specifier:d,step:"integration"}).toString()},o);if(f===$e)return;f!==void 0&&l.push({message:f,specifier:d})}return{checked:a,deferredChecked:r.length,failures:c,integrations:{checked:n.length,failures:l}}},Se=(e,r)=>{try{process.kill(-e,r)}catch{}},ar=e=>{try{return process.kill(-e,0),!0}catch{return!1}},Lr=e=>({args:["/pid",String(e),"/T","/F"],command:p(process.env.SystemRoot??String.raw`C:\Windows`,"System32","taskkill.exe")}),Go=e=>{const r=()=>{if(process.platform==="win32"){const{args:o,command:s}=Lr(e);fn(s,o,{stdio:"ignore"});return}Se(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},Ko=e=>new Promise(r=>{const{args:t,command:n}=Lr(e),o=Er(n,t,{stdio:"ignore",windowsHide:!0});o.once("error",()=>{r()}),o.once("exit",()=>{r()})}),ie=async e=>{if(e===void 0)return;e.dispose();const{pid:r}=e;if(process.platform==="win32"){await Ko(r);return}Se(r,"SIGTERM");const t=Date.now()+jo;for(;ar(r)&&Date.now()<t;)await hn(50);ar(r)&&Se(r,"SIGKILL")},zo=(e,r,t)=>[e?"lazy function modules":void 0,r===0?void 0:`${String(r)} deferred module(s)`,t===0?void 0:`${String(t)} integration module(s)`].filter(n=>n!==void 0).join(", "),Jo=async(e,r)=>{if(process.platform==="win32"){try{await ie(r)}finally{await e.stop()}return}try{await e.stop()}finally{await ie(r)}},Yo=e=>pt(e).catch(async r=>{if(!await vt(e.port))throw r}),Xo=({checked:e,deferredChecked:r,integrations:t})=>[`${String(e)} lazy function(s)`,...r>0?[`${String(r)} deferred module(s)`]:[],...t.checked>0?[`${String(t.checked)} integration module(s) loaded with import()`]:[]].join(" and "),Qo=(e,r,t)=>{const{checked:n,deferredChecked:o,failures:s,integrations:i}=r;if(s.length===0&&i.failures.length===0){t.success(`${Xo(r)} evaluate cleanly`);return}const a=Lo(e,s),c=a.length>H?[` …and ${String(a.length-H)} more module(s)`]:[];throw new P([...s.length===0?[]:[`${String(s.length)} of ${o===0?`${String(n)} lazy function(s)`:`${String(n+o)} lazy module(s)`} fail to load:`,...a.slice(0,H),...c],...i.failures.length===0?[]:[`${String(i.failures.length)} of ${String(i.checked)} integration module(s) fail to load in workerd (each would fail its first use instead):`,...i.failures.slice(0,H).map(({message:l,specifier:d})=>` import("${d}"): ${l}`),...i.failures.length>H?[` …and ${String(i.failures.length-H)} more integration module(s)`]:[]],"Fix the module, or pass --no-smoke-load to ship anyway."].join(`
10
- `))},Zo=(e,r,t)=>{if(e instanceof P&&!e.skipped)return t.error(e.message),e.message;if(e instanceof P){t.warn(`smoke-load skipped: ${e.message}`);return}const n=r.slice(-5).join(`
7
+ `)}`},Ne=async e=>{const{deadline:r,output:t,pending:n,port:o,query:s,startupFailed:i}=e,a=await fetch(`http://127.0.0.1:${String(o)}/_lunora/__smoke_load?${s}`,{signal:AbortSignal.any([AbortSignal.timeout(Math.max(0,r-Date.now())),i])}).catch(d=>{throw i.aborted?new I(`the smoke Worker's runtime did not start, so nothing was evaluated:${ar(t)}
8
+ Fix the entry, or pass --no-smoke-load to ship anyway.`):d instanceof Error&&d.name==="TimeoutError"?new I(n===void 0?`the smoke Worker accepted the connection but answered no request within ${String($e/1e3)}s, so its runtime did not start:${ar(t)}
9
+ Pass --no-smoke-load to ship anyway.`:`the smoke Worker did not finish evaluating ${n} within ${String($e/1e3)}s — it may be awaiting something that never settles. Pass --no-smoke-load to ship anyway.`):d});if(a.status>=500)throw new I(`the smoke Worker booted but failed while ${n===void 0?"answering a request that evaluates nothing":`evaluating ${n}`} (HTTP ${String(a.status)}). Pass --no-smoke-load to ship anyway.`);const c=await a.text().catch(()=>"");let l;try{l=JSON.parse(c)}catch{l=void 0}return{body:typeof l=="object"&&l!==null?l:void 0,response:a,text:c}},xe=(e,r)=>{const t=e.headers.get("content-type")??"no content type",n=r.replaceAll(/\s+/gu," ").trim().slice(0,120);return new I(`the smoke Worker answered with something other than the probe's result (HTTP ${String(e.status)}, ${t}${n===""?"":`: ${n}`}). 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.`)},Nr=(e,r)=>typeof e=="string"&&e!==r,Se=Symbol("another run's Worker"),cr=async(e,r)=>{const t=await Ne(e),n=t.body?.message;if(Nr(t.body?.run,r))return Se;if(t.body?.run!==r||n!==void 0&&typeof n!="string")throw xe(t.response,t.text);return n},Vo=async(e,r)=>{const t=await Ne({...e,pending:"the lazy function modules",query:"step=functions"}),{checked:n,failures:o}=t.body??{};if(!Nr(t.body?.run,r)){if(t.body?.run!==r||typeof n!="number"||!Array.isArray(o)||!o.every(s=>No(s)))throw xe(t.response,t.text);return{checked:n,failures:o}}},Ko=async e=>{const{deferred:r,functions:t,integrationModules:n,runId:o,...s}=e,i=await Ne({...s,pending:void 0,query:"step=ping"});if(typeof i.body?.run!="string")throw xe(i.response,i.text);if(i.body.run!==o)return;let a=0,c=[];if(t){const d=await Vo(s,o);if(d===void 0)return;a=d.checked,c=d.failures}for(const[d,u]of r.entries()){const f=await cr({...s,pending:`${u.kind} module ${u.label}`,query:`step=deferred&index=${String(d)}`},o);if(f===Se)return;f!==void 0&&c.push({deferred:u.kind,functionPath:`${u.kind}:${u.label}`,message:f})}const l=[];for(const d of n){const u=await cr({...s,pending:`import(${JSON.stringify(d)})`,query:new URLSearchParams({specifier:d,step:"integration"}).toString()},o);if(u===Se)return;u!==void 0&&l.push({message:u,specifier:d})}return{checked:a,deferredChecked:r.length,failures:c,integrations:{checked:n.length,failures:l}}},Ee=(e,r)=>{try{process.kill(-e,r)}catch{}},dr=e=>{try{return process.kill(-e,0),!0}catch{return!1}},xr=e=>({args:["/pid",String(e),"/T","/F"],command:p(process.env.SystemRoot??String.raw`C:\Windows`,"System32","taskkill.exe")}),zo=e=>{const r=()=>{if(process.platform==="win32"){const{args:o,command:s}=xr(e);gn(s,o,{stdio:"ignore"});return}Ee(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},Jo=e=>new Promise(r=>{const{args:t,command:n}=xr(e),o=Rr(n,t,{stdio:"ignore",windowsHide:!0});o.once("error",()=>{r()}),o.once("exit",()=>{r()})}),ie=async e=>{if(e===void 0)return;e.dispose();const{pid:r}=e;if(process.platform==="win32"){await Jo(r);return}Ee(r,"SIGTERM");const t=Date.now()+Do;for(;dr(r)&&Date.now()<t;)await mn(50);dr(r)&&Ee(r,"SIGKILL")},Yo=(e,r,t)=>[e?"lazy function modules":void 0,r===0?void 0:`${String(r)} deferred module(s)`,t===0?void 0:`${String(t)} integration module(s)`].filter(n=>n!==void 0).join(", "),Xo=async(e,r)=>{if(process.platform==="win32"){try{await ie(r)}finally{await e.stop()}return}try{await e.stop()}finally{await ie(r)}},Qo=e=>vt(e).catch(async r=>{if(!await yt(e.port))throw r}),Zo=({checked:e,deferredChecked:r,integrations:t})=>[`${String(e)} lazy function(s)`,...r>0?[`${String(r)} deferred module(s)`]:[],...t.checked>0?[`${String(t.checked)} integration module(s) loaded with import()`]:[]].join(" and "),es=(e,r,t)=>{const{checked:n,deferredChecked:o,failures:s,integrations:i}=r;if(s.length===0&&i.failures.length===0){t.success(`${Zo(r)} evaluate cleanly`);return}const a=Fo(e,s),c=a.length>W?[` …and ${String(a.length-W)} more module(s)`]:[];throw new I([...s.length===0?[]:[`${String(s.length)} of ${o===0?`${String(n)} lazy function(s)`:`${String(n+o)} lazy module(s)`} fail to load:`,...a.slice(0,W),...c],...i.failures.length===0?[]:[`${String(i.failures.length)} of ${String(i.checked)} integration module(s) fail to load in workerd (each would fail its first use instead):`,...i.failures.slice(0,W).map(({message:l,specifier:d})=>` import("${d}"): ${l}`),...i.failures.length>W?[` …and ${String(i.failures.length-W)} more integration module(s)`]:[]],"Fix the module, or pass --no-smoke-load to ship anyway."].join(`
10
+ `))},rs=(e,r,t)=>{if(e instanceof I&&!e.skipped)return t.error(e.message),e.message;if(e instanceof I){t.warn(`smoke-load skipped: ${e.message}`);return}const n=r.slice(-5).join(`
11
11
  `),o=`the smoke Worker did not start (${e instanceof Error?e.message:String(e)})${n===""?"":`
12
- ${n}`}. Either the entry fails when it loads, or local wrangler cannot run the project (a remote-only binding). Fix whichever it is, or pass --no-smoke-load to ship anyway.`;return t.error(o),o},es=e=>{try{return Ae(p(e,".lunora"),{recursive:!0}),lt(p(e,".lunora","smoke-"))}catch(r){throw new P(`could not create a directory for the check (${r instanceof Error?r.message:String(r)})`,!0)}},rs=(e,r)=>{if("main"in r)return`export * from ${G(C(e,r.main))};`;const{durableObjects:t,entrypoints:n,workflows:o}=r.stubs,s=new Set,i=(a,c)=>a==="default"||s.has(a)?[]:(s.add(a),[`export class ${a} ${c}`]);return['import { DurableObject, WorkerEntrypoint, WorkflowEntrypoint } from "cloudflare:workers";',...t.flatMap(a=>i(a,"extends DurableObject {}")),...n.flatMap(a=>i(a,"extends WorkerEntrypoint {}")),...o.flatMap(a=>i(a,"extends WorkflowEntrypoint { async run() {} }"))].join(`
13
- `)},ts=async e=>{const{base:r,configPath:t,cwd:n,deferred:o,directory:s,environment:i,functionsFile:a,integrationModules:c,missingAssets:l,preferred:d,toolchain:f}=e;try{const u=p(s,"entry.ts"),h=Ar();l&&Ae(p(s,"assets"),{recursive:!0});const g=c.map(S=>` [${G(S)}, () => import(${G(S)})],`).join(`
14
- `),v="stubs"in r&&r.stubs.entrypoints.includes("default");X(u,`${rs(n,r)}
15
- ${a===void 0?"":`import { loadAllFunctions } from ${G(a)};
12
+ ${n}`}. Either the entry fails when it loads, or local wrangler cannot run the project (a remote-only binding). Fix whichever it is, or pass --no-smoke-load to ship anyway.`;return t.error(o),o},ts=e=>{try{return Re(p(e,".lunora"),{recursive:!0}),ut(p(e,".lunora","smoke-"))}catch(r){throw new I(`could not create a directory for the check (${r instanceof Error?r.message:String(r)})`,!0)}},ns=(e,r)=>{if("main"in r)return`export * from ${V(P(e,r.main))};`;const{durableObjects:t,entrypoints:n,workflows:o}=r.stubs,s=new Set,i=(a,c)=>a==="default"||s.has(a)?[]:(s.add(a),[`export class ${a} ${c}`]);return['import { DurableObject, WorkerEntrypoint, WorkflowEntrypoint } from "cloudflare:workers";',...t.flatMap(a=>i(a,"extends DurableObject {}")),...n.flatMap(a=>i(a,"extends WorkerEntrypoint {}")),...o.flatMap(a=>i(a,"extends WorkflowEntrypoint { async run() {} }"))].join(`
13
+ `)},os=async e=>{const{base:r,configPath:t,cwd:n,deferred:o,directory:s,environment:i,functionsFile:a,integrationModules:c,missingAssets:l,preferred:d,toolchain:u}=e;try{const f=p(s,"entry.ts"),g=Tr();l&&Re(p(s,"assets"),{recursive:!0});const h=c.map(T=>` [${V(T)}, () => import(${V(T)})],`).join(`
14
+ `),v="stubs"in r&&r.stubs.entrypoints.includes("default");X(f,`${ns(n,r)}
15
+ ${a===void 0?"":`import { loadAllFunctions } from ${V(a)};
16
16
  `}
17
- const runId = ${JSON.stringify(h)};
17
+ const runId = ${JSON.stringify(g)};
18
18
 
19
19
  // Deferred event modules, evaluated one per request so a module that throws on import blocks like a function module does.
20
20
  const deferred = [
21
- ${o.map(S=>` () => import(${G(S.file)}),`).join(`
21
+ ${o.map(T=>` () => import(${V(T.file)}),`).join(`
22
22
  `)}
23
23
  ];
24
24
 
25
25
  const integrationLoaders = new Map<string, () => Promise<unknown>>([
26
- ${g}
26
+ ${h}
27
27
  ]);
28
28
 
29
29
  const smokeProbe = {
@@ -59,5 +59,5 @@ ${v?`export default class extends WorkerEntrypoint {
59
59
  return smokeProbe.fetch(request);
60
60
  }
61
61
  }`:"export default smokeProbe;"}
62
- `);const m=await pn(d),{args:_,command:O}=z(U(n),f.dev({configPath:t===void 0?void 0:L(n,t),environment:i,extraArgs:[L(n,u),"--local","--local-protocol","http","--ip","127.0.0.1","--port",String(m),"--persist-to",L(n,p(s,"state")),...l?["--assets",L(n,p(s,"assets"))]:[]]}));return{args:_,command:O,port:m,runId:h}}catch(u){throw new P(`could not prepare the check (${u instanceof Error?u.message:String(u)})`,!0)}},ns=async e=>{const{composedEntry:r,cwd:t,environment:n,launcher:o,logger:s,toolchain:i}=e,a=F(t),c=p(t,a,"_generated","functions.ts"),l=b(c)&&E(c,"utf8").includes("export const loadAllFunctions"),d=l?c:void 0,f=xo(t,a),u=[...f,...Uo(t,a,f)],h=Po(t,r??Dr(t,n,e.configPath).main,a);if(!l&&u.length===0&&h.length===0)return;const g=Bo(e);if("skip"in g){s.warn(`smoke-load skipped: ${g.skip}, so the modules the Worker loads on demand are not evaluated before deploy`);return}const{base:v,configFile:m,missingAssets:_}=g,O=[];let S,D;const R=Date.now()+be,at=process.platform!=="win32",ct=(B,Q,Z)=>{const W=Er(B,[...Q],{cwd:Z.cwd,detached:at,shell:Z.shell,stdio:["ignore","pipe","pipe"]});return W.pid!==void 0&&(D={dispose:Go(W.pid),pid:W.pid}),W};try{S=es(t),s.info(`smoke-loading ${zo(d!==void 0,u.length,h.length)} in workerd`);let B=Io;for(let Q=0;Q<tr;Q+=1){const{args:Z,command:W,port:he,runId:dt}=await ts({base:v,configPath:m,cwd:t,deferred:u,directory:S,environment:n,functionsFile:d,integrationModules:h,missingAssets:_,preferred:B,toolchain:i}),He=new AbortController;B=he+1;const qe=await Yo({args:Z,command:W,cwd:t,spawn:o??ct,label:"wrangler dev (smoke-load)",notFound:"`wrangler` was not found",onLine:V=>{O.push(V),Wo.test(V)&&He.abort()},port:he,readyTimeoutMs:Math.max(0,R-Date.now()),shell:process.platform==="win32"});if(qe===void 0){await ie(D),D=void 0;continue}try{const V=await Vo({deadline:R,deferred:u,functions:d!==void 0,integrationModules:h,output:O,port:he,runId:dt,startupFailed:He.signal});if(V!==void 0){Qo(t,V,s);return}}finally{await Jo(qe,D),D=void 0}}throw new P(`the smoke port was answered by other runs on all ${String(tr)} attempts`,!0)}catch(B){return Zo(B,O,s)}finally{if(await ie(D),S!==void 0)try{oe(S,{force:!0,recursive:!0})}catch{}}},os=(e,r)=>r===void 0?e:C(e,r),ss=async e=>{if(e.targets.length===0)return{builtTags:[],code:0};if(!(e.railpackAvailable??yn)()){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??q,t=[];for(const n of e.targets){const o=vn(n.exportName),s={args:["build",n.buildDir,"--name",o],command:"railpack",cwd:e.cwd},i=je(U(e.cwd),"wrangler",["containers","push",o]),a={args:i.args,command:i.command,cwd:e.cwd};e.logger.info(`railpack: building "${n.exportName}" → ${o} from ${n.buildDir}`);const c=await r(s);if(c.code!==0){const d=`railpack build failed for container "${n.exportName}" (${n.buildDir})`;return e.logger.error(d),{builtTags:t,code:c.code,error:d}}e.logger.info(`railpack: pushing ${o} to the Cloudflare Registry`);const l=await r(a);if(l.code!==0){const d=`wrangler containers push failed for "${n.exportName}" (${o})`;return e.logger.error(d),{builtTags:t,code:l.code,error:d}}t.push(o)}return{builtTags:t,code:0}},is=new Set(["0.0.0.0","[::1]","[::]","localhost"]),as=[".local",".localhost"],cs=["[fc","[fd"],ds=/^\[fe[89ab][0-9a-f]:/u,ls=/^[a-z]+:\/\//u,cr=e=>{const r=e.split(".").map(Number);if(r.length!==4||r.some(o=>!Number.isInteger(o)))return!1;const[t=-1,n=-1]=r;return t===0||t===127||t===100&&n>=64&&n<=127||t===198&&(n===18||n===19)||t===10||t===192&&n===168||t===172&&n>=16&&n<=31||t===169&&n===254},dr="[::ffff:",us=e=>{if(!e.startsWith(dr)||!e.endsWith("]"))return;const r=e.slice(dr.length,-1);if(r.includes("."))return r;const[t=0,n=0]=r.split(":").map(o=>Number.parseInt(o,16));return[Math.floor(t/256),t%256,Math.floor(n/256),n%256].join(".")},xr=e=>{let r=e.length;for(;r>0&&e[r-1]===".";)r-=1;return e.slice(0,r).toLowerCase()},fs=e=>{const r=e.toLowerCase(),t=us(r);return t!==void 0?cr(t):is.has(r)||as.some(n=>r.endsWith(n))||cs.some(n=>r.startsWith(n))||ds.test(r)||cr(r)},Mr=e=>{const r=N(e);return r===void 0?void 0:j(r).parsed},Fr=(e,r)=>{const t=typeof e?.name=="string"&&e.name!==""?e.name:void 0;if(r===void 0)return t;const n=e?.env?.[r]?.name;return typeof n=="string"&&n!==""?n:t===void 0?void 0:`${t}-${r}`},ae=(e,r)=>{let t=e.length;for(;t>0&&e[t-1]===r;)t-=1;return e.slice(0,t)},gs=e=>{const r=e.replace(ls,""),t=r.indexOf("/"),n=(t===-1?r:r.slice(0,t)).toLowerCase(),o=t===-1?"":ae(r.slice(t),"*");return o==="/"?n:`${n}${o}`},lr=e=>[e?.route,...Array.isArray(e?.routes)?e.routes:[]].flatMap(t=>{const n=typeof t=="string"?t:t?.pattern;return typeof n=="string"&&n!==""?[gs(n)]:[]}),hs=(e,r,t)=>{const n=t.indexOf("/"),o=n===-1?t:t.slice(0,n),s=n===-1?"":t.slice(n),i=o.startsWith("*");if(!(!(i?e.endsWith(o.slice(1)):e===o)||s!==""&&!`${ae(r,"/")}/`.startsWith(s)))return s.length*1e6+(i?0:5e5)+o.length},ms=e=>e!==void 0&&(Object.hasOwn(e,"route")||Object.hasOwn(e,"routes")),Ur=(e,r)=>{const t=lr(e),o=[...new Set([...Object.keys(e?.env??{}),...r===void 0?[]:[r]])].map(s=>{const i=e?.env?.[s];return{id:`env:${s}`,label:`--env ${s}`,routes:ms(i)?lr(i):t}});return[{id:"top",label:"production",routes:t},...o]},ps=(e,r,t,n)=>{const o=r===void 0?"top":`env:${r}`,s=Ur(e,r).flatMap(c=>c.routes.flatMap(l=>{const d=hs(t,n,l);return d===void 0?[]:[{block:c,score:d}]}));if(s.length===0)return{kind:"none"};const i=Math.max(...s.map(c=>c.score)),a=s.filter(c=>c.score===i);return a.some(c=>c.block.id===o)?{kind:"own"}:{kind:"other",label:a[0]?.block.label??"production"}},ne=e=>Xt(`${e.origin}${e.pathname}`),vs=(e,r,t,n,o)=>{const s=Ce(e),i=s?.workerUrl!==void 0&&URL.canParse(s.workerUrl)?new URL(s.workerUrl):void 0;if(i===void 0)return;if(s?.env===r)return ne(i)===ne(t)?null:`${n}: this checkout is linked to ${ne(i)}${o}`;const a=`${ae(i.pathname,"/")}/`;if(i.origin!==t.origin||!`${ae(t.pathname,"/")}/`.startsWith(a))return;const c=s?.env===void 0?"production":`--env ${s.env}`;return`${n}: this checkout links it to ${c}, not this deploy${o}`},Br=(e,r,t,n,o,s)=>{const i=ps(e,r,t,n);if(i.kind==="other")return`${o}: wrangler routes it to ${i.label}, not this deploy${s}`;if(i.kind==="own")return;const a=Ur(e,r);if(a.every(l=>l.routes.length===0))return;const c=a.find(l=>l.id===(r===void 0?"top":`env:${r}`))?.routes??[];return`${o}: this deploy${s} routes to ${c.length===0?"no declared route":c.join(", ")}, not ${t}`},ys=(e,r,t,n,o,s)=>{const i=Mr(e);if(t.endsWith(".workers.dev")){const a=Fr(i,r);return a!==void 0&&t.split(".")[0]!==a?`${o}: this deploy ships the Worker "${a}"${s}`:`${o}: no link ties this *.workers.dev host to your account${s}; run \`lunora link --url https://${t}${r===void 0?"":` --env ${r}`}\` once the Worker is deployed, then deploy again (or confirm the drift yourself with --allow-schema-drift)`}return Br(i,r,t,n,o,s)},ws=(e,r,t,n,o)=>{const s=Mr(e),i=xr(t.hostname);if(i.endsWith(".workers.dev")){const a=Fr(s,r);return a===void 0||i.split(".")[0]===a?void 0:`${n}: this deploy ships the Worker "${a}", not the one the link names${o}`}return Br(s,r,i,t.pathname,n,o)},ks=(e,r,t)=>{let n;try{n=new URL(t)}catch{return`refused ${t} as the deployment to read rows from: it is not a URL`}const o=`refused ${ne(n)} as the deployment to read rows from`,s=r===void 0?"":` (--env ${r})`,i=xr(n.hostname);if(fs(i))return`${o}: it is a local or private address, not the worker this deploy ships to`;const a=vs(e,r,n,o,s);return a===void 0?ys(e,r,i,n.pathname,o,s):a??ws(e,r,n,o,s)},Wr=e=>{const t=[N(e),p(e,"package.json"),p(e,"wrangler.dev.jsonc")].filter(n=>n!==void 0&&b(n)).map(n=>[n,E(n,"utf8")]);return()=>{for(const[n,o]of t)E(n,"utf8")!==o&&X(n,o,"utf8")}},bs=(e,r=Ar())=>C(e,".lunora",`vite-bundle-meta-${r}.json`),Hr="LUNORA_CLIENT_BUILD",$s="virtual:lunora/worker",Ee=(e,r)=>["ts","mts","cts","js","mjs","cjs"].some(t=>b(p(e,`${r}.config.${t}`))),qr=e=>Ee(e,"rsbuild")?"rsbuild":Ee(e,"vite")?"vite":void 0,Ss=e=>Ee(e,"vite")?"vite":qr(e),Es=e=>{try{const{scripts:r}=JSON.parse(E(p(e,"package.json"),"utf8"));return typeof r?.build=="string"&&r.build!==""}catch{return!1}},fe=(e,r)=>{if(process.env[Hr]==="1")return;const t=N(e),n=t===void 0?void 0:j(t).parsed,o=n?.main===$s,s=(o?Ss(e):qr(e))??(Es(e)?"script":void 0);if(s===void 0)return;const i=r===void 0?void 0:n?.env?.[r]?.assets?.directory,a=n?.assets?.directory??i;return o||yt(e).class!=="C"||a!==void 0?s:void 0},As=async(e,r,t)=>{const n=t.spawner??q,o=U(e),s=r==="script"?{args:["run","build"],command:o}:je(o,r,["build"]);t.logger.info(`running ${r} build before bundling the Worker`);const i=Wr(e),a=t.bundleMetaPath??bs(e);oe(p(e,wt),{force:!0});try{const c=await n({args:s.args,command:s.command,cwd:e,env:{[Et]:At(e),[St]:t.target,[$t]:a,...t.lazyFunctions?{[bt]:"1"}:{},...t.environment===void 0?{}:{CLOUDFLARE_ENV:t.environment},...t.strictAdvisories===!1?{[kt]:"0"}:{},[Hr]:"1"},stdoutToStderr:t.outputJson});return c.code===0?void 0:`${r} build failed with exit code ${String(c.code)}`}finally{i(),t.bundleMetaPath===void 0&&oe(a,{force:!0})}},ge=(e,r,t)=>r!==!1&&fe(e,t)!==void 0,Rs=(e,r,t)=>ge(e,r,t)&&fe(e,t)!=="script",Me=e=>{const r=e.frameworkBuild===!1?void 0:fe(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{we(e.cwd,e.target)}catch(n){return n instanceof Error?n.message:String(n)}let t;try{t=we(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`},Vr=async e=>{const r=e.frameworkBuild===!1?void 0:fe(e.cwd,e.environment);if(r===void 0)return;let t;try{t=e.target??we(e.cwd)}catch(n){return n instanceof Error?n.message:String(n)}return As(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})},ur=e=>Array.isArray(e)?e.filter(r=>r!=null):void 0,Fe=(e,r)=>{const t=N(e);if(!t)return;const{parsed:n}=j(t);if(n===void 0)return;const{error:o,merged:s}=ue(n,r),i=o===void 0?s:n,{containers:a,d1_databases:c,vars:l}=i;return{containers:ur(a),d1_databases:ur(c),vars:typeof l=="object"&&l!==null&&!Array.isArray(l)?l:void 0}},Ts=/^127(?:\.\d{1,3}){3}$/,Cs=e=>{try{const{hostname:r}=new URL(e);return r==="localhost"||Ts.test(r)||r==="::1"||r==="[::1]"}catch{return!1}},_s=e=>e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.includes("Dockerfile"),Ps=(e,r,t,n="deploy",o)=>{const s=(Fe(e,o)?.containers??[]).filter(a=>typeof a?.image=="string"&&_s(a.image));if(s.length===0||t())return;const i=`${n} blocked: wrangler.jsonc declares ${String(s.length)} container(s) built from a local Dockerfile, but no Docker-compatible engine is available. Start Docker (or Colima), or point the container's \`image\` at a pre-built registry reference. Note: container images must target linux/amd64.`;return r.error(i),i},Ue=e=>b(A(e,Ve))?Ve:void 0,Is=(e,r,t="deploy",n)=>{for(const o of vr(e,"lunora",n).containers){const s=o.schedulingPolicy===void 0?o.image:void 0,a=[...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(A(e,c.path)));if(a!==void 0){const c=`${t} blocked: container "${o.exportName}" references a Dockerfile at "${a.path}" that does not exist. Create it or fix the \`${a.field}\` path in lunora/containers.ts.`;return r.error(c),c}if(s?.kind==="build"&&!b(A(e,s.buildDir))){const c=`${t} blocked: container "${o.exportName}" references a Railpack build directory "${s.buildDir}" that does not exist. Create it or fix the \`image.build\` path in lunora/containers.ts.`;return r.error(c),c}}},js=(e,r)=>r==="celld"?typeof e=="string"&&e!==Ge&&nn(e):r==="cloudflare"&&e===Ge,Os=(e,r,t)=>(Fe(e,t)?.d1_databases??[]).find(n=>js(n.database_id,r)),Ds=e=>{if(!e.migrate||e.dryRun)return;if(e.migrateUrl===void 0){const t="--migrate requires --migrate-url <https://your-worker> — the deploy target URL is only known after wrangler runs, and this gate runs before it; refusing to default to localhost";return e.logger.error(t),t}if(e.migrateYes!==!0){const t="--migrate runs production data migrations after deploy. Re-run with --migrate-yes to confirm.";return e.logger.error(t),t}const r=e.migrateToken??process.env.LUNORA_ADMIN_TOKEN;if(r===void 0||r===""){const t="admin token required for --migrate — pass --migrate-token or set LUNORA_ADMIN_TOKEN";return e.logger.error(t),t}},Ns=(e,r,t,n,o)=>{const s=Os(e,n,o);if(s===void 0)return;const i=`${t} blocked: the "${s.binding??"<unnamed>"}" D1 binding has a placeholder database_id ("${s.database_id??""}")`,a=n==="celld"?`${i}, which celld would use as the database's identity. Set database_id to the database celld should use, then ${t} again.`:`${i}. Run \`lunora doctor --fix\` to create the database and write its id into wrangler.jsonc, or run \`wrangler d1 create <name>\` and paste the id in yourself.`;return r.error(a),a},Ls=(e,r,t="deploy",n)=>{const o=Fe(e,n)?.vars;if(!o)return;const s=Object.entries(o).filter(([,a])=>typeof a=="string"&&Cs(a)).map(([a])=>a).toSorted((a,c)=>a.localeCompare(c));if(s.length===0)return;const i=`${t} blocked: ${s.join(", ")} in wrangler.jsonc point at localhost. A deployed Worker can't reach a loopback address, so this silently breaks scheduled-job dispatch, reverse cross-shard relations, and auth callbacks. Set each to the deployed worker's public URL (or move it to a secret with \`wrangler secret put\`) before deploying.`;return r.error(i),i},xs=["vite.config.ts","vite.config.mts","vite.config.cts","vite.config.js","vite.config.mjs","vite.config.cjs",...gt],Gr=/\.(?:[cm]?[jt]s|tsx|jsx)$/u,Kr=/\.(?:test|spec)\.[cm]?[jt]sx?$/u,zr="allowUnauthenticatedShardAccess",Ms=/[\\/]/u,Jr=new Set(["_generated","build","dist","node_modules"]),Yr=(e,r)=>{const t=J(e,r).split(Ms);return Gr.test(r)&&!Kr.test(r)&&!ye(t.join("/"))&&t.every(n=>n===".."||!n.startsWith(".")&&!Jr.has(n))},fr=(e,r,t)=>{const{parsed:n}=j(r);if(n===void 0)return[];const{error:o,merged:s}=ue(n,t),{main:i}=o===void 0?s:n,a=typeof i=="string"?A(_r(r),i):void 0;return a!==void 0&&b(a)&&Yr(e,a)?[a]:[]},Be=e=>e===void 0?!1:e.getKind()===w.FalseKeyword?!0:$.isParenthesizedExpression(e)||$.isAsExpression(e)||$.isSatisfiesExpression(e)||$.isTypeAssertion(e)||$.isNonNullExpression(e)?Be(e.getExpression()):!1,Fs=e=>{try{return Re(e).isFile()}catch{return!1}},Us=new Set(["ELOOP","ENOENT","ENOTDIR"]),ce=(e,r,t)=>{const n=r instanceof Error&&"code"in r&&typeof r.code=="string"?r.code:"";Us.has(n)||t.push(e)},Bs=(e,r)=>{try{return Re(e)}catch(t){ce(e,t,r);return}},Xr=(e,r)=>{try{return E(e,"utf8")}catch(t){ce(e,t,r);return}},Qr=(e,r,t,n=new Set)=>{let o;try{o=ut(r)}catch(i){return ce(r,i,t),[]}if(n.has(o))return[];n.add(o);let s;try{s=K(r)}catch(i){return ce(r,i,t),[]}return s.flatMap(i=>{const a=A(r,i),c=Bs(a,t);if(c===void 0)return[];const l=J(e,a).split(M).join("/");return c.isDirectory()?Jr.has(i)||i.startsWith(".")||ye(`${l}/`)?[]:Qr(e,a,t,n):c.isFile()&&Gr.test(i)&&!Kr.test(i)&&!ye(l)?[a]:[]})},Ws=e=>{const r=$.isComputedPropertyName(e)?e.getExpression():e;return $.isStringLiteral(r)||$.isNoSubstitutionTemplateLiteral(r)?r.getLiteralValue():e.getText()},pe=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],Hs=/\.(?:[cm]?js|jsx)$/u,qs=(e,r)=>{if(!r.startsWith("."))return;const t=C(_r(e),r),n=t.replace(Hs,"");return[t,...pe.map(s=>`${t}${s}`),...pe.map(s=>A(t,`index${s}`)),...pe.map(s=>`${n}${s}`)].find(s=>Fs(s))},Vs=e=>{if(e.getExpression().getText()!=="require")return;const[r]=e.getArguments();return r!==void 0&&($.isStringLiteral(r)||$.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():void 0},Gs=e=>{const r=e.getModuleReference();if(!$.isExternalModuleReference(r))return;const t=r.getExpression();return $.isStringLiteral(t)?t.getLiteralValue():void 0},Ks=(e,r,t,n)=>{const o=new Set(e),s=[...e],i=[];for(let a=0;a<s.length;a+=1){const c=s[a]??"",l=Xr(c,n);if(l===void 0)continue;const d=r.createSourceFile(J(t,c),l,{overwrite:!0}),f=[...d.getImportDeclarations().map(u=>u.getModuleSpecifierValue()),...d.getExportDeclarations().map(u=>u.getModuleSpecifierValue()),...d.getDescendantsOfKind(w.ImportEqualsDeclaration).map(u=>Gs(u)),...d.getDescendantsOfKind(w.CallExpression).map(u=>Vs(u))].filter(u=>u!==void 0);for(const u of f){const h=qs(c,u);h!==void 0&&Yr(t,h)&&!o.has(h)&&(o.add(h),i.push(h),s.push(h))}}return i},zs=e=>{const r=e.getArgumentExpression();return r!==void 0&&($.isStringLiteral(r)||$.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():void 0},Js=e=>$.isPropertyAccessExpression(e)?e.getName():$.isElementAccessExpression(e)?zs(e):void 0,Ys=new Set([w.AmpersandAmpersandEqualsToken,w.AmpersandEqualsToken,w.AsteriskAsteriskEqualsToken,w.AsteriskEqualsToken,w.BarBarEqualsToken,w.BarEqualsToken,w.CaretEqualsToken,w.EqualsToken,w.GreaterThanGreaterThanEqualsToken,w.GreaterThanGreaterThanGreaterThanEqualsToken,w.LessThanLessThanEqualsToken,w.MinusEqualsToken,w.PercentEqualsToken,w.PlusEqualsToken,w.QuestionQuestionEqualsToken,w.SlashEqualsToken]),Xs=e=>{const r=e.getOperatorToken().getKind();return!Ys.has(r)||Js(e.getLeft())!==zr?!1:r!==w.EqualsToken||!Be(e.getRight())},Qs=(e,r,t)=>{const n=[],o=[...new Set([F(e),"src"])].filter(f=>b(A(e,f))),s=N(e),i=[...xs.map(f=>A(e,f)).filter(f=>b(f)),...s===void 0?[]:fr(e,s,r),...t.flatMap(f=>fr(e,f,r))],a=new Rr({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}),c=o.flatMap(f=>Qr(A(e,f),A(e,f),n));return{sites:[...new Set([...c,...i,...Ks([...i,...c],a,e,n)])].flatMap(f=>{const u=Xr(f,n);if(u===void 0)return[];const h=a.createSourceFile(J(e,f),u,{overwrite:!0}),g=[...h.getDescendantsOfKind(w.PropertyAssignment),...h.getDescendantsOfKind(w.ShorthandPropertyAssignment),...h.getDescendantsOfKind(w.GetAccessor),...h.getDescendantsOfKind(w.MethodDeclaration)].filter(m=>{const _=$.isPropertyAssignment(m)&&Be(m.getInitializer());return Ws(m.getNameNode())===zr&&!_}).map(m=>m.getStartLineNumber()),v=h.getDescendantsOfKind(w.BinaryExpression).filter(m=>Xs(m)).map(m=>m.getStartLineNumber());return[...g,...v].map(m=>({file:J(e,f),line:m}))}),unreadable:n}},Zs=(e,r,t,n,o,s)=>{if(t!=="deploy")return;const{sites:i,unreadable:a}=Qs(e,o,s),c=Rn({openShardAccess:i,schema:{tables:[]}},{lints:[Ke]});if(c.length===0&&a.length===0)return;const l=[];if(c.length>0){const f=c.map(u=>`${String(u.metadata.file)}:${String(u.metadata.line)}`).join(", ");l.push(`${f} enable the open-shard option (any value but a literal false), so any caller may target any shard.`)}if(a.length>0&&l.push(`could not read ${a.join(", ")}, so the open-shard option cannot be ruled out there.`),n){r.warn(`deploying past the open-shard gate (--allow-open-shards): ${l.join(" ")}`);return}const d=`deploy blocked (open_shard_access): ${l.join(" ")} ${Ke.remediation}`;return r.error(d),d},ei=(e,r,t,n)=>{const o=Zs(e,r.logger,t,r.allowOpenShards===!0,r.env,n);return o===void 0?void 0:{code:k.USAGE,error:o}},ri=(e,r,t,n)=>{const o=Ns(e,r.logger,t,n,r.env);if(o!==void 0)return{code:k.USAGE,error:o};const s=Ls(e,r.logger,t,r.env);if(s!==void 0)return{code:k.USAGE,error:s};const i=Is(e,r.logger,t,r.discoveryCache);if(i!==void 0)return{code:k.USAGE,error:i};const a=Ps(e,r.logger,r.dockerAvailable??wn,t,r.env);return a===void 0?void 0:{code:k.MISSING_DEPENDENCY,error:a}},ti=/https?:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/u,ni=/https:\/\/[^\s"'<>]+/u,oi=e=>{if(e===void 0)return;const r=ti.exec(e);return r?r[0]:ni.exec(e)?.[0]},gr=e=>e===void 0?"":` (--env ${e})`,si=({cwd:e,env:r,logger:t,now:n,url:o})=>{if(o!==void 0)try{const s=Ce(e);if(s!==void 0){if(s.workerUrl===o&&s.env===r)return;t.warn(`link: .lunora/project.json records ${s.workerUrl??"(no url)"}${gr(s.env)}, but this deploy published ${o}${gr(r)}. Keeping the recorded value — run \`lunora link --url ${o}${r===void 0?"":` --env ${r}`}\` to update it.`);return}const i=(n??(()=>new Date().toISOString()))();Rt(e,{env:r,linkedAt:i,workerName:Ie(e),workerUrl:o}),t.success(`link: recorded ${o} in .lunora/project.json (run \`lunora link\` to change)`)}catch{}},ii=async(e,r)=>{const t=new Rr({skipAddingFilesFromTsConfig:!0}),n=A(r,"lunora");let o;try{o=ht(t,n)}catch(s){const i=s instanceof Error?s.message:String(s);return e.logger.warn(`--migrate: could not discover migrations (${i}); 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 i={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},a=await Tn(i);if(a.code!==0)return e.logger.error(`--migrate: migration "${s.id}" failed — see output above`),a.code;e.logger.success(`--migrate: "${s.id}" applied`)}return 0},ai=async(e,r)=>{const{info:t}=_e(r,"lunora",e.discoveryCache),n=t?.vectorMetadata??[];if(n.length===0)return;const o=[];for(const a of n){const c=on(a.kind);if(c===void 0){e.logger.warn(`vector index "${a.index}" declares metadata "${a.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:a.index,property:a.property,type:c})}if(o.length===0)return;const i=(await sn({cwd:r,entries:o,exec:je(U(r),"wrangler",[]),logger:e.logger,spawner:e.spawner??q})).filter(a=>a.status!=="failed").length;i>0&&e.logger.success(`vectorize metadata indexes ready: ${String(i)}/${String(o.length)}`)},hr=5,ci=2e3,di=async(e,r,t)=>{if(e.healthCheck!==!0)return;const n=t??Oe({cwd:r,env:e.env});if(n===void 0){const s="--health-check: the deploy succeeded, but no URL to probe could be resolved — wrangler's output carried none and this checkout has no link for this environment. Run `lunora link --url <https://your-worker>` and re-deploy, or drop --health-check.";return e.logger.error(s),{error:s,ok:!1,url:""}}const o=await kn({attempts:hr,baseUrl:n,delayMs:ci,fetchImpl:e.healthFetch,paths:[bn,$n],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(hr)} attempt(s) — ${o.error}`),{error:o.error,ok:!1,url:o.url})},li=async(e,r,t,n,o,s)=>{e.isolatedPreview!==!0&&await ai(e,r);const i=e.migrate?await ii(e,r):0;return i===0&&o?.(),{code:i,descriptor:t,mintedSecretsFile:s,validation:n}},ui=async({cwd:e,descriptor:r,mintedSecretsFile:t,options:n,reblessSchemaBaseline:o,recordArchitecture:s,stdout:i,validation:a})=>{const c={deployedAt:new Date().toISOString(),dryRun:n.dryRun===!0,env:n.env,url:n.dryRun===!0?void 0:oi(i),workerName:Ie(e)};if(n.dryRun===!0)return n.healthCheck===!0&&n.logger.warn("--health-check skipped: a dry run publishes nothing"),{code:0,deployment:c,descriptor:r,mintedSecretsFile:t,validation:a};n.temporary!==!0&&n.isolatedPreview!==!0&&(s?.(),si({cwd:e,env:n.env,logger:n.logger,url:c.url}));const l=await di(n,e,c.url);if(l?.error!==void 0)return{code:k.UNAVAILABLE,deployment:c,descriptor:r,healthCheck:l,mintedSecretsFile:t,validation:a};const d=n.isolatedPreview===!0?void 0:o;return{...await li(n,e,r,a,d,t),deployment:c,healthCheck:l}},fi=(e,r,t)=>{const n=A(e,x);if(!b(n))return;let o;try{o=yr(E(n,"utf8")).length}catch{return}if(o===0)return;const s=t.toolchain?.secretPut!==void 0;r.warn(s?`Note: \`lunora deploy\` does not push secrets. ${x} 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. ${x} 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.`)},Zr=async(e,r)=>{let t=[];try{t=Tt(await wr({cache:r,projectRoot:e,schemaDir:F(e)}))}catch{}const n=[...new Set(Ct(t).map(s=>s.key))];let o=[];try{const s=A(e,x);b(s)&&(o=yr(E(s,"utf8")).map(i=>i.key).filter(i=>Sr(i)))}catch{}return{fromLocal:o.filter(s=>!n.includes(s)),fromPackages:n,mintableKeys:_t(t)}},gi=async(e,r,t,n)=>{const{logger:o}=r,s=r.spawner??q,i=U(e),a=r.env===void 0?"":` --env ${r.env}`,c=n.toolchain?.secretPut;if(c===void 0)return o.error(`deploy target "${n.id}" has no secret store; cannot push secrets`),{minted:[],ok:!1};const l=t.map(u=>({key:u,value:Pt()})),d=n.toolchain?.secretBulk;if(d!==void 0&&l.length>=2){const u=z(i,d({environment:r.env,temporary:r.temporary})),h=await s({args:u.args,command:u.command,cwd:e,input:JSON.stringify(Object.fromEntries(l.map(g=>[g.key,g.value])))});if(h.code===0){for(const{key:g}of l)o.success(`generated + pushed ${g}`);return{minted:l,ok:!0}}o.warn(`bulk secret push failed (exit ${String(h.code)}); retrying one key at a time`)}const f=[];for(const{key:u,value:h}of l){const g=c({environment:r.env,key:u,temporary:r.temporary}),v=z(i,g),m=await s({args:v.args,command:v.command,cwd:e,input:h});if(m.code!==0)return o.error(`failed to push secret ${u} (exit ${String(m.code)}); set it manually with \`wrangler secret put ${u}${a}\`.`),{minted:f,ok:!1};f.push({key:u,value:h}),o.success(`generated + pushed ${u}`)}return{minted:f,ok:!0}},hi=/^[\w-]+$/u,mr=[".dev.vars",".dev.vars.*","!.dev.vars.example"],mi=(e,r)=>{try{const t=Dt(e,mr);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 \`${mr.join("` and `")}\` by hand before committing.`)}},pi=(e,r,t)=>{if(t.length===0)return;const n=t.map(a=>a.key).join(", ");if(r.env!==void 0&&!hi.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?x:`${x}.${r.env}`;mi(e,r.logger);const s=A(e,o);let i=b(s)?E(s,"utf8"):"";for(const a of t)i=It(i,a.key,a.value);return jt(s,i),r.logger.success(r.env===void 0?`${n}: value(s) recorded in ${o}`:`${n}: value(s) recorded in ${o} (kept separate from ${x} so \`lunora dev\` and a plain \`lunora env push\` don't inherit the --env ${r.env} value)`),o},vi=/^<[^>]+>$/u,yi=async(e,r,t)=>{let n;try{n=t.projectConfig?.(e,"deploy").vars??{}}catch(d){return{error:d instanceof Error?d.message:String(d)}}const o=d=>{const f=n[d];if(typeof f!="string")return!0;const u=f.trim();return u===""||vi.test(u)?!0:Sr(d)&&Ot(f)},s=d=>Object.hasOwn(n,d)?`${d} (empty or a placeholder)`:d,{fromLocal:i,fromPackages:a}=await Zr(e,r.discoveryCache),c=i.filter(d=>o(d));c.length>0&&r.logger.warn(`${x} key(s) not set in the wrangler vars: ${c.map(d=>s(d)).join(", ")}. ${t.name} has no secret store: a key the app reads from env must be a \`vars\` entry; one it loads from a secret manager at runtime need not.`);const l=a.filter(d=>o(d));return l.length===0?{}:{error:`missing required secret(s) in the wrangler vars: ${l.map(d=>s(d)).join(", ")}. ${t.name} has no secret store and Lunora reads these from env, so each must be a real \`vars\` value in the config the deploy ships — write it there from your secret manager at deploy time rather than committing it. Add them, then re-deploy.`}},wi=async(e,r,t,n)=>{if(r.dryRun===!0||r.isolatedPreview===!0)return{};if(n.toolchain?.secretList===void 0)return yi(e,r,n);const{logger:o}=r,s=r.env===void 0?"":` --env ${r.env}`;let i;try{i=await(r.secretLister??_n)({cwd:e,env:r.env,target:n.id,temporary:r.temporary})}catch{return{}}if(!i.ok)return{};const a=new Set(i.names),{fromLocal:c,fromPackages:l,mintableKeys:d}=await Zr(e,r.discoveryCache),f=[...l,...c].filter(g=>!a.has(g));if(f.length===0)return{};if(!t)return{error:`missing required secret(s) on the deploy target: ${f.join(", ")}. Set them with \`wrangler secret put <KEY>${s}\` (or \`lunora env generate --set\` then \`lunora env push --yes${s}\`), then re-deploy.`};for(const g of f.filter(v=>!d.has(v)))o.warn(`required secret ${g} is not set on the target — set it with: wrangler secret put ${g}${s}`);const u=f.filter(g=>d.has(g));if(u.length===0)return{};if(await(r.secretConfirm??Cn())(`${String(u.length)} required secret(s) not set on the target (${u.join(", ")}). Generate strong values and push them now?`)){const{minted:g,ok:v}=await gi(e,r,u,n),m=pi(e,r,g);return v?{mintedSecretsFile:m}:{error:"failed to push required secret(s) — set them manually and re-deploy",mintedSecretsFile:m}}return o.warn(`${String(u.length)} required secret(s) not set on the target: ${u.join(", ")}. Generate + push with \`lunora env generate --set\` then \`lunora env push --yes${s}\`.`),{}},et=e=>e.format==="json"?!1:e.interactive!==void 0?e.interactive:process.stdout.isTTY&&!process.env.CI,ki=async(e,r)=>{if(r.dryRun===!0)return;const t=vr(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 ss({cwd:e,logger:r.logger,railpackAvailable:r.railpackAvailable,spawner:r.spawner,targets:t});return n.code===0?void 0:n.error??"railpack build failed"},bi=(e,r,t)=>{if(t!==void 0)try{const n=Kt(e,t);n.changed&&r.success(`synced ${String(t.length)} cron trigger(s) → ${n.wranglerPath??"wrangler.jsonc"}`);for(const s of n.warnings)r.warn(s);const o=zt(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}`)}},$i=async(e,r,t,n,o,s)=>{try{le(n);const i=await wr({cache:s,projectRoot:e,schemaDir:F(e)}),a=Vt(e,i,{environment:o,target:n}),c=a.wranglerPath??"wrangler.jsonc";if(a.added.length>0&&r.success(`provisioned bindings: ${a.added.join(", ")} → ${c}`),a.updated.length>0&&r.success(`updated bindings: ${a.updated.join(", ")} → ${c}`),a.devConfig!==void 0){const{added:l,path:d,updated:f}=a.devConfig;r.success(`dev sidecar bindings: ${[...l,...f].join(", ")} → ${d}`)}for(const l of a.warnings)r.warn(l)}catch(i){const a=i instanceof Error?i.message:String(i);r.warn(`binding inference skipped: ${a}`)}try{const i=Gt(e);i.changed&&r.success(`bumped compatibility_date to ${i.date??"unknown"} (Workers Cache enabled) → ${i.wranglerPath??"wrangler.jsonc"}`)}catch(i){const a=i instanceof Error?i.message:String(i);r.warn(`compatibility date sync skipped: ${a}`)}bi(e,r,t)},Si=async(e,r,t,n,o,s,i,a,c,l)=>{let d;r?(d=new Jt({name:"dots"}),d.start("running codegen")):t.info("running codegen");try{const f=mt({apiSpec:n,dryRun:!l,lazyFunctions:o,projectRoot:e,target:s,...qt(e)});d?.succeed("codegen complete"),d||t.success("codegen complete");const u=en(f.platformDiagnostics,t);if(u.errors.length>0)return{error:u.errors.join("; ")};const{errorAdvisories:h,names:g,shouldBlock:v}=rn(f.advisories,c);if(v){const _=`${h.length.toString()} ERROR-level ${h.length===1?"advisory":"advisories"} (${g.join(", ")}). Pass --no-strict-advisories to downgrade this to a warning and continue.`;return t.error(_),{error:_}}const m=l?await Ft({cwd:e,logger:t,spawner:i,stdoutToStderr:a}):void 0;return m?.error!==void 0?{error:m.error}:{result:f}}catch(f){d?.failed("codegen failed");const u=f instanceof Error?f.message:String(f);return t.error(`codegen failed: ${u}`),{error:`codegen failed: ${u}`}}},pr="--preview is not supported: Cloudflare gives a Worker that implements a Durable Object no version preview URL, and a version shares production's Durable Objects, D1 and R2. Deploy an isolated copy with `lunora preview deploy <name>` (its own Worker, Durable Object namespace, D1, R2 and KV; `lunora preview delete <name>` removes it), or validate without publishing with `--dry-run`.",Ei=(e,r)=>({dryRun:r.dryRun,entry:Ue(e),environment:r.env,outDir:r.outDir,secretsFile:r.secretsFile,outFile:r.outFile,preview:r.preview,temporary:r.temporary}),rt=(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=Ei(e,r);return kr(t,e,"deploy",s=>n.deploy({...o,configPath:s}))},Ai=(e,r,t)=>{const n=rt(e,r,t),o=Ue(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},T={problems:[],wranglerPath:void 0},ve=(e,r)=>({code:k.USAGE,descriptor:void 0,error:e,validation:T,...r}),Ri=(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},Ti=(e,r,t)=>{const n=r.format==="json",o=r.dryRun!==!0,s=Ai(e,r,t),i=z(U(e),s);return{args:i.args,captureStdout:o&&!n,captureStdoutSilently:o&&n,command:i.command,cwd:e,stdoutToStderr:n&&!o}},We=e=>{if(e.skipServices===!0)return"--skip-services";if(e.isolatedPreview===!0)return"a preview never deploys services: they are production's Workers";if(e.temporary===!0)return"--temporary deploys the app to a throwaway account"},Ci=(e,r)=>We(r)===void 0?Te(e).services.map(t=>t.wranglerPath):[],tt=(e,r,t,n,o)=>({cwd:e,environment:r.env,frameworkBuild:n,lazyFunctions:de(r.lazyFunctions),logger:r.logger,outputJson:r.format==="json"||r.clientBuildOutputJson===!0,spawner:o,strictAdvisories:Pe(r),target:t.id}),_i=(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 s=e.map(i=>i.worker).join(", ");r.logger.warn(`services not deployed (${o??""}): ${s} — deploy them yourself if the app calls anything new`);return}return n},nt=(e,r)=>{for(const t of e){const n=Me(r(I(t.wranglerPath)));if(n!==void 0)return`service ${t.name} (${t.worker}): ${n}`}},Pi=(e,r,t)=>{const{error:n,services:o}=Te(e);if(n!==void 0||o.length===0)return;const s=le(t);if(s.toolchain===void 0||We(r)!==void 0)return;const i=r.skipCodegen===!0?!1:r.frameworkBuild,a=[...new Map(o.map(c=>[c.wranglerPath,c])).values()];return nt(a,c=>tt(c,r,s,i,q))},ot=(e,r,t)=>{const n=e.cwd??process.cwd(),o=un(n,e.target);if(o.target===void 0){const a=o.error??"unknown deploy target";return e.logger.error(a),{kind:"refused",error:a,validation:T}}if(e.preview===!0)return e.logger.error(pr),{kind:"refused",code:k.USAGE,error:pr,validation:T};try{rt(n,e,le(o.target))}catch(a){if(!(t&&a instanceof Nt&&ge(n,e.skipCodegen===!0?!1:e.frameworkBuild,e.env))){const c=a instanceof Error?a.message:String(a);return e.logger.error(c),{kind:"refused",error:c,validation:T}}}const s=e.openShardGatePassed===!0?void 0:ei(n,e,r,Ci(n,e));if(s!==void 0)return{kind:"refused",code:s.code,error:s.error,validation:T};const i=Pi(n,e,o.target);return i!==void 0?(e.logger.error(i),{kind:"refused",code:k.USAGE,error:i,validation:T}):{kind:"ok",target:o.target}},Ii=(e,r)=>e.apiSpec??(e.clientBuildRan===!0?Ut(r):void 0),ji=async(e,r,t)=>{if(r!=="celld")return;const n=await(e.celldToolchain??Mt)({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},st=(e,r)=>{const t=Oe({cwd:e,env:r.env,url:r.migrateUrl}),n=t===void 0?void 0:ks(e,r.env,t);if(n!==void 0)return{reason:n};const o=t===void 0?void 0:Qt(t,r.logger,e),s=o===void 0?void 0:Yt({cwd:e,token:r.migrateToken,url:o}).token;return{target:o===void 0||!s?void 0:{baseUrl:o,fetchImpl:r.fetchImpl??Zt,token:s}}},Oi=(e,r,t)=>async n=>{const o=st(e,r);return"reason"in o?{kind:"inconclusive",reason:o.reason}:An({changes:n,tables:t.schemaTables,target:o.target})},Di=(e,r)=>async t=>{const n=st(e,r);return"reason"in n?n.reason:En({changes:t,now:Date.now(),target:n.target})},Ni=(e,r,t,n)=>e==="deploy"?{checkStoredRows:Oi(r,t,n),countExpiringRows:Di(r,t)}:{},Li=async(e,r)=>{const t=e.cwd??process.cwd(),n=et(e),o=Pe(e),s={problems:[],wranglerPath:void 0},i=ot(e,r,!1);if(i.kind==="refused")return{code:i.code,error:i.error,validation:i.validation};const{target:a}=i,c=await ji(e,a,r);if(c!==void 0)return e.logger.error(c),{code:k.MISSING_DEPENDENCY,error:c,target:a,validation:s};let l;if(!e.skipCodegen){const v=await Si(t,n,e.logger,Ii(e,t),de(e.lazyFunctions),a,e.spawner,e.format==="json",o,e.clientBuildRan!==!0);if(v.error!==void 0)return{error:v.error,target:a,validation:T};l=v.result,e.discoveryCache?.clear()}let d;if(l!==void 0){const v=await Sn({allowDrift:e.allowSchemaDrift===!0,...Ni(r,t,e,l),codegen:l,command:r,logger:e.logger});if(v.blocked)return{error:`schema drift gate blocked ${r}`,schemaDrift:{blocked:!0,reason:v.reason},target:a,validation:s};d=v.rebless}const f=l&&Ln({current:l.architecture,cwd:t,environment:e.env,logger:e.logger});await $i(t,e.logger,l?.cronTriggers,a,e.env,e.discoveryCache);const u=await jr(t,e,r,a,"check");if(u!==void 0)return{error:u,target:a,validation:T};const h=ri(t,e,r,a);if(h!==void 0)return{code:h.code,error:h.error,target:a,validation:T};const g=Ht({environment:e.env,projectRoot:t});return Ri(g,e.logger)?{error:"wrangler validation failed",target:a,validation:g}:{codegen:l,reblessSchemaBaseline:d,recordArchitecture:f,target:a,validation:g}},xi=e=>{oe(p(e,".wrangler","deploy","config.json"),{force:!0})},Mi=async(e,r,t)=>{const n=Me(e);if(n!==void 0)return{built:!1,error:n};const o=ge(e.cwd,r,t);return o&&xi(e.cwd),{built:o,error:await Vr(e)}},Fi=(e,r,t)=>r||t===!1?De(e):void 0,Ui=async(e,r,t,n)=>{const{error:o,services:s}=Te(e);if(o!==void 0)return{code:k.FAILURE,error:o};if(s.length===0)return;const i=_i(s,r,t);if(i===void 0)return;const a=U(e),c=[...new Map(s.map(u=>[u.wranglerPath,u])).values()],l=r.skipCodegen===!0?!1:r.frameworkBuild,d=u=>tt(u,r,t,l,n),f=nt(c,d);if(f!==void 0)return r.logger.error(f),{code:k.USAGE,error:f};for(const u of c){const h=I(u.wranglerPath),g=d(h),{built:v,error:m}=await Mi(g,l,r.env);if(m!==void 0){const R=`service ${u.name} (${u.worker}): ${m}`;return r.logger.error(R),{code:k.FAILURE,error:R}}const _=Fi(u.wranglerPath,v,l);let O;try{O=kr(t,h,"deploy",R=>i.deploy({configPath:R??_??u.wranglerPath,dryRun:r.dryRun===!0,environment:r.env}))}catch(R){return{code:k.FAILURE,error:`service ${u.name} (${u.worker}): ${R instanceof Error?R.message:String(R)}`}}O.commit();const S=z(a,O.command);r.logger.info(`deploying service ${u.name} (${u.worker}) via ${S.command} ${S.args.join(" ")}`);const D=await n({args:S.args,command:S.command,cwd:h,stdoutToStderr:r.format==="json"});if(D.code!==0)return{code:k.FAILURE,error:`service ${u.name} (${u.worker}): ${S.command} ${S.args.join(" ")} exited ${String(D.code)} — stopping before the app`}}},Bi=async(e,r,t,n)=>{if(r!=="cloudflare")return;const o=e===void 0?void 0:j(e).parsed,s=(t===void 0?void 0:o?.env?.[t]?.account_id)??o?.account_id,i=await cn({accountId:s});(i.verdict==="near"||i.verdict==="full")&&n.warn(i.fix===void 0?i.message:`${i.message} ${i.fix}`)},Wi=e=>e.dryRun!==!0&&e.temporary!==!0,Hi=e=>e.temporary===!0?"temporary":e.dryRun===!0?"preview":"defer",qi=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},Vi=(e,r,t)=>{const n=[];for(const o of e)if(o.verdict==="ok")o.changesAccount===!0&&r.info(o.message);else if(o.verdict==="unchecked"&&t==="preview")r.warn(`dry run: ${o.message}${o.fix===void 0?"":` ${o.fix}`} A real deploy stops here.`);else{const s=qi(o);r.error(s),n.push(s)}return n},it=async(e,r,t,n,o,s,i)=>{const a=t==="cloudflare"&&r!==void 0?j(r).parsed:void 0;if(a===void 0)return;const c=(ue(a,n).merged.artifacts??[]).flatMap(g=>typeof g?.binding=="string"&&typeof g.namespace=="string"?[{binding:g.binding,namespace:g.namespace}]:[]),l=c.length===0?void 0:_e(e,F(e),s).info?.jurisdiction;if(l===void 0)return;const d=[...new Map(c.map(g=>[g.namespace,g])).values()];if(i==="temporary"){o.warn(`--temporary deploys to a throwaway account, so the jurisdiction ("${l}") of Artifacts namespace ${d.map(g=>`"${g.namespace}"`).join(", ")} was not checked: it is created there on first use, in no jurisdiction.`);return}const f=(n===void 0?void 0:a.env?.[n]?.account_id)??a.account_id,u=await Promise.all(d.map(async g=>an({...g,accountId:f,create:i==="create",jurisdiction:l,missingOk:i==="defer"||i==="preview"}))),h=Vi(u,o,i);return h.length===0?void 0:h.join(`
63
- `)},Gi=async(e,r,t,n,o,s)=>{const i=Wi(r)?await it(e,s,o,r.env,r.logger,r.discoveryCache,"create"):void 0;if(i!==void 0)return{code:k.FAILURE,error:i};const a=await jr(e,r,"deploy",o);return a!==void 0?{code:k.FAILURE,error:a}:Ui(e,r,t,n)},Ki=async(e,r,t,n)=>{if(!(r.smokeLoad===!1||t.toolchain===void 0))return ns({composedEntry:Ue(e),configPath:n,cwd:e,environment:r.env,launcher:r.smokeLauncher,logger:r.logger,toolchain:t.toolchain})},zi=async e=>{const r={...e,discoveryCache:e.discoveryCache??xt()},t=r.cwd??process.cwd(),n=et(r),o=await Li(r,r.commandName??"deploy");if(o.error!==void 0){if(o.validation.problems.length>0)return{code:k.USAGE,descriptor:void 0,error:o.error,validation:o.validation};const m=o.schemaDrift===void 0?void 0:{schemaDrift:o.schemaDrift};return ve(o.error,{...m,...o.code===void 0?{}:{code:o.code}})}const{validation:s}=o,i=le(o.target),a=Ds(r)??await it(t,s.wranglerPath,o.target,r.env,r.logger,r.discoveryCache,Hi(r))??await Ki(t,r,i,s.wranglerPath);if(a!==void 0)return ve(a);const c=i.toolchain?.prebuildsContainerImages===!0?await ki(t,r):void 0;if(c!==void 0)return ve(c);fi(t,r.logger,i),Wt(t,m=>{r.logger.warn(m)}),await Bi(s.wranglerPath,o.target,r.env,r.logger);const{error:l,mintedSecretsFile:d}=await wi(t,r,n,i);if(l!==void 0)return r.logger.error(l),{code:k.USAGE,descriptor:void 0,error:l,mintedSecretsFile:d,validation:s};const f=r.spawner??q,u=await Gi(t,r,i,f,o.target,s.wranglerPath);if(u!==void 0)return{code:u.code,descriptor:void 0,error:u.error,mintedSecretsFile:d,validation:s};const h=Ti(t,r,i);r.logger.info(`deploying via ${h.command} ${h.args.join(" ")}`);const g=await f(h);return h.captureStdoutSilently===!0&&g.stdout!==void 0&&g.stdout!==""&&process.stderr.write(g.stdout),g.code!==0?{code:g.code,descriptor:h,mintedSecretsFile:d,validation:s}:{...await ui({...o,cwd:t,descriptor:h,mintedSecretsFile:d,options:r,stdout:g.stdout}),logsAvailable:i.toolchain?.tail!==void 0}},Ji=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:Pe(e),lazyFunctions:de(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:k.USAGE,descriptor:void 0,error:o,validation:T};Lt(t);const s=await Vr(n);if(s!==void 0)return r.error(s),{code:k.FAILURE,descriptor:void 0,error:s,validation:T}},Yi=(e,r)=>{const t=r.skipCodegen===!0?!1:r.frameworkBuild;return ge(e,t,r.env)?r.env:void 0},Xi=async e=>{const{logger:r}=e,t=e.cwd??process.cwd(),n=ot(e,e.commandName??"deploy",!0);if(n.kind==="refused")return{code:n.code??k.USAGE,descriptor:void 0,error:n.error,validation:n.validation};const o=await Ji(e);if(o!==void 0)return o;const s=e.dryRun===!0?Wr(t):void 0;let i;try{if(i=await zi({...e,clientBuildEnvironment:Yi(t,e),clientBuildRan:Rs(t,e.skipCodegen===!0?!1:e.frameworkBuild,e.env),logger:r,openShardGatePassed:!0}),i.code===0&&e.emitBindings!==void 0){const{error:a}=dn({destination:e.emitBindings,logger:r,projectRoot:e.cwd??process.cwd()});a!==void 0&&(r.error(a),i={...i,code:k.USAGE})}}finally{s?.()}return e.format==="json"||i.code===0&&e.dryRun!==!0&&e.isolatedPreview!==!0&&xn({cwd:e.cwd??process.cwd(),env:e.env,logger:e.logger,logsAvailable:i.logsAvailable===!0,mintedSecretsFile:i.mintedSecretsFile,url:i.deployment?.url}),i},Oa=ln(async({cwd:e,format:r,logger:t,options:n})=>{const o=os(e,n.root),s=await Xi({allowOpenShards:n.allowOpenShards===!0,allowSchemaDrift:n.allowSchemaDrift===!0,apiSpec:tn(n.apiSpec),frameworkBuild:n.prebuilt===!0?!1:n.frameworkBuild,lazyFunctions:de(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:Oe({cwd:o,env:n.env,url:n.migrateUrl}),migrateYes:n.migrateYes===!0,preview:n.preview===!0,skipCodegen:n.prebuilt===!0,skipServices:n.skipServices===!0,smokeLoad:n.smokeLoad,strictAdvisories:n.strictAdvisories,target:n.target,temporary:n.temporary===!0});return{code:s.code,data:{deployment:s.deployment,healthCheck:s.healthCheck,mintedSecretsFile:s.mintedSecretsFile,schemaDrift:s.schemaDrift,validation:s.validation},error:s.error}});export{Li as a,$i as b,qn as c,Wr as d,Zr as e,Oa as f,os as p,Xi as r,Ki as s,bs as v};
62
+ `);const m=await vn(d),{args:$,command:C}=z(F(n),u.dev({configPath:t===void 0?void 0:D(n,t),environment:i,extraArgs:[D(n,f),"--local","--local-protocol","http","--ip","127.0.0.1","--port",String(m),"--persist-to",D(n,p(s,"state")),...l?["--assets",D(n,p(s,"assets"))]:[]]}));return{args:$,command:C,port:m,runId:g}}catch(f){throw new I(`could not prepare the check (${f instanceof Error?f.message:String(f)})`,!0)}},ss=async e=>{const{composedEntry:r,cwd:t,environment:n,launcher:o,logger:s,toolchain:i}=e,a=x(t),c=p(t,a,"_generated","functions.ts"),l=b(c)&&E(c,"utf8").includes("export const loadAllFunctions"),d=l?c:void 0,u=Mo(t,a),f=[...u,...Wo(t,a,u)],g=jo(t,r??Lr(t,n,e.configPath).main,a);if(!l&&f.length===0&&g.length===0)return;const h=Ho(e);if("skip"in h){s.warn(`smoke-load skipped: ${h.skip}, so the modules the Worker loads on demand are not evaluated before deploy`);return}const{base:v,configFile:m,missingAssets:$}=h,C=[];let T,M;const qe=Date.now()+$e,ct=process.platform!=="win32",dt=(U,Q,Z)=>{const B=Rr(U,[...Q],{cwd:Z.cwd,detached:ct,shell:Z.shell,stdio:["ignore","pipe","pipe"]});return B.pid!==void 0&&(M={dispose:zo(B.pid),pid:B.pid}),B};try{T=ts(t),s.info(`smoke-loading ${Yo(d!==void 0,f.length,g.length)} in workerd`);let U=Oo;for(let Q=0;Q<or;Q+=1){const{args:Z,command:B,port:me,runId:lt}=await os({base:v,configPath:m,cwd:t,deferred:f,directory:T,environment:n,functionsFile:d,integrationModules:g,missingAssets:$,preferred:U,toolchain:i}),Ge=new AbortController;U=me+1;const Ve=await Qo({args:Z,command:B,cwd:t,spawn:o??dt,label:"wrangler dev (smoke-load)",notFound:"`wrangler` was not found",onLine:G=>{C.push(G),qo.test(G)&&Ge.abort()},port:me,readyTimeoutMs:Math.max(0,qe-Date.now()),shell:process.platform==="win32"});if(Ve===void 0){await ie(M),M=void 0;continue}try{const G=await Ko({deadline:qe,deferred:f,functions:d!==void 0,integrationModules:g,output:C,port:me,runId:lt,startupFailed:Ge.signal});if(G!==void 0){es(t,G,s);return}}finally{await Xo(Ve,M),M=void 0}}throw new I(`the smoke port was answered by other runs on all ${String(or)} attempts`,!0)}catch(U){return rs(U,C,s)}finally{if(await ie(M),T!==void 0)try{oe(T,{force:!0,recursive:!0})}catch{}}},is=(e,r)=>r===void 0?e:P(e,r),as=async e=>{if(e.targets.length===0)return{builtTags:[],code:0};if(!(e.railpackAvailable??wn)()){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??q,t=[];for(const n of e.targets){const o=yn(n.exportName),s={args:["build",n.buildDir,"--name",o],command:"railpack",cwd:e.cwd},i=Oe(F(e.cwd),"wrangler",["containers","push",o]),a={args:i.args,command:i.command,cwd:e.cwd};e.logger.info(`railpack: building "${n.exportName}" → ${o} from ${n.buildDir}`);const c=await r(s);if(c.code!==0){const d=`railpack build failed for container "${n.exportName}" (${n.buildDir})`;return e.logger.error(d),{builtTags:t,code:c.code,error:d}}e.logger.info(`railpack: pushing ${o} to the Cloudflare Registry`);const l=await r(a);if(l.code!==0){const d=`wrangler containers push failed for "${n.exportName}" (${o})`;return e.logger.error(d),{builtTags:t,code:l.code,error:d}}t.push(o)}return{builtTags:t,code:0}},cs=new Set(["0.0.0.0","[::1]","[::]","localhost"]),ds=[".local",".localhost"],ls=["[fc","[fd"],us=/^\[fe[89ab][0-9a-f]:/u,fs=/^[a-z]+:\/\//u,lr=e=>{const r=e.split(".").map(Number);if(r.length!==4||r.some(o=>!Number.isInteger(o)))return!1;const[t=-1,n=-1]=r;return t===0||t===127||t===100&&n>=64&&n<=127||t===198&&(n===18||n===19)||t===10||t===192&&n===168||t===172&&n>=16&&n<=31||t===169&&n===254},ur="[::ffff:",gs=e=>{if(!e.startsWith(ur)||!e.endsWith("]"))return;const r=e.slice(ur.length,-1);if(r.includes("."))return r;const[t=0,n=0]=r.split(":").map(o=>Number.parseInt(o,16));return[Math.floor(t/256),t%256,Math.floor(n/256),n%256].join(".")},Fr=e=>{let r=e.length;for(;r>0&&e[r-1]===".";)r-=1;return e.slice(0,r).toLowerCase()},hs=e=>{const r=e.toLowerCase(),t=gs(r);return t!==void 0?lr(t):cs.has(r)||ds.some(n=>r.endsWith(n))||ls.some(n=>r.startsWith(n))||us.test(r)||lr(r)},Mr=e=>{const r=O(e);return r===void 0?void 0:j(r).parsed},Ur=(e,r)=>{const t=typeof e?.name=="string"&&e.name!==""?e.name:void 0;if(r===void 0)return t;const n=e?.env?.[r]?.name;return typeof n=="string"&&n!==""?n:t===void 0?void 0:`${t}-${r}`},ae=(e,r)=>{let t=e.length;for(;t>0&&e[t-1]===r;)t-=1;return e.slice(0,t)},ms=e=>{const r=e.replace(fs,""),t=r.indexOf("/"),n=(t===-1?r:r.slice(0,t)).toLowerCase(),o=t===-1?"":ae(r.slice(t),"*");return o==="/"?n:`${n}${o}`},fr=e=>[e?.route,...Array.isArray(e?.routes)?e.routes:[]].flatMap(t=>{const n=typeof t=="string"?t:t?.pattern;return typeof n=="string"&&n!==""?[ms(n)]:[]}),ps=(e,r,t)=>{const n=t.indexOf("/"),o=n===-1?t:t.slice(0,n),s=n===-1?"":t.slice(n),i=o.startsWith("*");if(!(!(i?e.endsWith(o.slice(1)):e===o)||s!==""&&!`${ae(r,"/")}/`.startsWith(s)))return s.length*1e6+(i?0:5e5)+o.length},vs=e=>e!==void 0&&(Object.hasOwn(e,"route")||Object.hasOwn(e,"routes")),Br=(e,r)=>{const t=fr(e),o=[...new Set([...Object.keys(e?.env??{}),...r===void 0?[]:[r]])].map(s=>{const i=e?.env?.[s];return{id:`env:${s}`,label:`--env ${s}`,routes:vs(i)?fr(i):t}});return[{id:"top",label:"production",routes:t},...o]},ys=(e,r,t,n)=>{const o=r===void 0?"top":`env:${r}`,s=Br(e,r).flatMap(c=>c.routes.flatMap(l=>{const d=ps(t,n,l);return d===void 0?[]:[{block:c,score:d}]}));if(s.length===0)return{kind:"none"};const i=Math.max(...s.map(c=>c.score)),a=s.filter(c=>c.score===i);return a.some(c=>c.block.id===o)?{kind:"own"}:{kind:"other",label:a[0]?.block.label??"production"}},ne=e=>Qt(`${e.origin}${e.pathname}`),ws=(e,r,t,n,o)=>{const s=_e(e),i=s?.workerUrl!==void 0&&URL.canParse(s.workerUrl)?new URL(s.workerUrl):void 0;if(i===void 0)return;if(s?.env===r)return ne(i)===ne(t)?null:`${n}: this checkout is linked to ${ne(i)}${o}`;const a=`${ae(i.pathname,"/")}/`;if(i.origin!==t.origin||!`${ae(t.pathname,"/")}/`.startsWith(a))return;const c=s?.env===void 0?"production":`--env ${s.env}`;return`${n}: this checkout links it to ${c}, not this deploy${o}`},Wr=(e,r,t,n,o,s)=>{const i=ys(e,r,t,n);if(i.kind==="other")return`${o}: wrangler routes it to ${i.label}, not this deploy${s}`;if(i.kind==="own")return;const a=Br(e,r);if(a.every(l=>l.routes.length===0))return;const c=a.find(l=>l.id===(r===void 0?"top":`env:${r}`))?.routes??[];return`${o}: this deploy${s} routes to ${c.length===0?"no declared route":c.join(", ")}, not ${t}`},ks=(e,r,t,n,o,s)=>{const i=Mr(e);if(t.endsWith(".workers.dev")){const a=Ur(i,r);return a!==void 0&&t.split(".")[0]!==a?`${o}: this deploy ships the Worker "${a}"${s}`:`${o}: no link ties this *.workers.dev host to your account${s}; run \`lunora link --url https://${t}${r===void 0?"":` --env ${r}`}\` once the Worker is deployed, then deploy again (or confirm the drift yourself with --allow-schema-drift)`}return Wr(i,r,t,n,o,s)},bs=(e,r,t,n,o)=>{const s=Mr(e),i=Fr(t.hostname);if(i.endsWith(".workers.dev")){const a=Ur(s,r);return a===void 0||i.split(".")[0]===a?void 0:`${n}: this deploy ships the Worker "${a}", not the one the link names${o}`}return Wr(s,r,i,t.pathname,n,o)},$s=(e,r,t)=>{let n;try{n=new URL(t)}catch{return`refused ${t} as the deployment to read rows from: it is not a URL`}const o=`refused ${ne(n)} as the deployment to read rows from`,s=r===void 0?"":` (--env ${r})`,i=Fr(n.hostname);if(hs(i))return`${o}: it is a local or private address, not the worker this deploy ships to`;const a=ws(e,r,n,o,s);return a===void 0?ks(e,r,i,n.pathname,o,s):a??bs(e,r,n,o,s)},Hr=e=>{const t=[O(e),p(e,"package.json"),p(e,"wrangler.dev.jsonc")].filter(n=>n!==void 0&&b(n)).map(n=>[n,E(n,"utf8")]);return()=>{for(const[n,o]of t)E(n,"utf8")!==o&&X(n,o,"utf8")}},Ss=(e,r=Tr())=>P(e,".lunora",`vite-bundle-meta-${r}.json`),qr="LUNORA_CLIENT_BUILD",Es="virtual:lunora/worker",Ae=(e,r)=>["ts","mts","cts","js","mjs","cjs"].some(t=>b(p(e,`${r}.config.${t}`))),Gr=e=>Ae(e,"rsbuild")?"rsbuild":Ae(e,"vite")?"vite":void 0,As=e=>Ae(e,"vite")?"vite":Gr(e),Rs=e=>{try{const{scripts:r}=JSON.parse(E(p(e,"package.json"),"utf8"));return typeof r?.build=="string"&&r.build!==""}catch{return!1}},ge=(e,r)=>{if(process.env[qr]==="1")return;const t=O(e),n=t===void 0?void 0:j(t).parsed,o=n?.main===Es,s=(o?As(e):Gr(e))??(Rs(e)?"script":void 0);if(s===void 0)return;const i=r===void 0?void 0:n?.env?.[r]?.assets?.directory,a=n?.assets?.directory??i;return o||wt(e).class!=="C"||a!==void 0?s:void 0},Ts=async(e,r,t)=>{const n=t.spawner??q,o=F(e),s=r==="script"?{args:["run","build"],command:o}:Oe(o,r,["build"]);t.logger.info(`running ${r} build before bundling the Worker`);const i=Hr(e),a=t.bundleMetaPath??Ss(e);oe(p(e,kt),{force:!0});try{const c=await n({args:s.args,command:s.command,cwd:e,env:{[At]:Rt(e),[Et]:t.target,[St]:a,...t.lazyFunctions?{[$t]:"1"}:{},...t.environment===void 0?{}:{CLOUDFLARE_ENV:t.environment},...t.strictAdvisories===!1?{[bt]:"0"}:{},[qr]:"1"},stdoutToStderr:t.outputJson});return c.code===0?void 0:`${r} build failed with exit code ${String(c.code)}`}finally{i(),t.bundleMetaPath===void 0&&oe(a,{force:!0})}},he=(e,r,t)=>r!==!1&&ge(e,t)!==void 0,Cs=(e,r,t)=>he(e,r,t)&&ge(e,t)!=="script",Fe=e=>{const r=e.frameworkBuild===!1?void 0:ge(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{ke(e.cwd,e.target)}catch(n){return n instanceof Error?n.message:String(n)}let t;try{t=ke(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`},Vr=async e=>{const r=e.frameworkBuild===!1?void 0:ge(e.cwd,e.environment);if(r===void 0)return;let t;try{t=e.target??ke(e.cwd)}catch(n){return n instanceof Error?n.message:String(n)}return Ts(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})},gr=e=>Array.isArray(e)?e.filter(r=>r!=null):void 0,Me=(e,r,t=O(e))=>{if(!t)return;const{parsed:n}=j(t);if(n===void 0)return;const{error:o,merged:s}=ue(n,r),i=o===void 0?s:n,{containers:a,d1_databases:c,vars:l}=i;return{containers:gr(a),d1_databases:gr(c),vars:typeof l=="object"&&l!==null&&!Array.isArray(l)?l:void 0}},_s=/^127(?:\.\d{1,3}){3}$/,Ps=e=>{try{const{hostname:r}=new URL(e);return r==="localhost"||_s.test(r)||r==="::1"||r==="[::1]"}catch{return!1}},Is=e=>e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.includes("Dockerfile"),js=(e,r,t,n="deploy",o)=>{const s=(Me(e,o)?.containers??[]).filter(a=>typeof a?.image=="string"&&Is(a.image));if(s.length===0||t())return;const i=`${n} blocked: wrangler.jsonc declares ${String(s.length)} container(s) built from a local Dockerfile, but no Docker-compatible engine is available. Start Docker (or Colima), or point the container's \`image\` at a pre-built registry reference. Note: container images must target linux/amd64.`;return r.error(i),i},Ue=e=>b(A(e,Ke))?Ke:void 0,Os=(e,r,t="deploy",n)=>{for(const o of wr(e,"lunora",n).containers){const s=o.schedulingPolicy===void 0?o.image:void 0,a=[...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(A(e,c.path)));if(a!==void 0){const c=`${t} blocked: container "${o.exportName}" references a Dockerfile at "${a.path}" that does not exist. Create it or fix the \`${a.field}\` path in lunora/containers.ts.`;return r.error(c),c}if(s?.kind==="build"&&!b(A(e,s.buildDir))){const c=`${t} blocked: container "${o.exportName}" references a Railpack build directory "${s.buildDir}" that does not exist. Create it or fix the \`image.build\` path in lunora/containers.ts.`;return r.error(c),c}}},Ds=(e,r)=>r==="celld"?typeof e=="string"&&e!==ze&&on(e):r==="cloudflare"&&e===ze,Ls=(e,r,t,n)=>(Me(e,t,n)?.d1_databases??[]).find(o=>Ds(o.database_id,r)),Ns=e=>{if(!e.migrate||e.dryRun)return;if(e.migrateUrl===void 0){const t="--migrate requires --migrate-url <https://your-worker> — the deploy target URL is only known after wrangler runs, and this gate runs before it; refusing to default to localhost";return e.logger.error(t),t}if(e.migrateYes!==!0){const t="--migrate runs production data migrations after deploy. Re-run with --migrate-yes to confirm.";return e.logger.error(t),t}const r=e.migrateToken??process.env.LUNORA_ADMIN_TOKEN;if(r===void 0||r===""){const t="admin token required for --migrate — pass --migrate-token or set LUNORA_ADMIN_TOKEN";return e.logger.error(t),t}},Be=(e,r,t,n,o,s)=>{const i=Ls(e,n,o,s);if(i===void 0)return;const a=`${t} blocked: the "${i.binding??"<unnamed>"}" D1 binding has a placeholder database_id ("${i.database_id??""}")`,c=s===void 0?"Run `lunora doctor --fix` to create the database and write its id into wrangler.jsonc, or run `wrangler d1 create <name>` and paste the id in yourself.":`Run \`wrangler d1 create <name>\` and put the returned database_id in ${s}.`,l=n==="celld"?`${a}, which celld would use as the database's identity. Set database_id to the database celld should use, then ${t} again.`:`${a}. ${c}`;return r.error(l),l},xs=(e,r,t="deploy",n)=>{const o=Me(e,n)?.vars;if(!o)return;const s=Object.entries(o).filter(([,a])=>typeof a=="string"&&Ps(a)).map(([a])=>a).toSorted((a,c)=>a.localeCompare(c));if(s.length===0)return;const i=`${t} blocked: ${s.join(", ")} in wrangler.jsonc point at localhost. A deployed Worker can't reach a loopback address, so this silently breaks scheduled-job dispatch, reverse cross-shard relations, and auth callbacks. Set each to the deployed worker's public URL (or move it to a secret with \`wrangler secret put\`) before deploying.`;return r.error(i),i},Fs=["vite.config.ts","vite.config.mts","vite.config.cts","vite.config.js","vite.config.mjs","vite.config.cjs",...ht],Kr=/\.(?:[cm]?[jt]s|tsx|jsx)$/u,zr=/\.(?:test|spec)\.[cm]?[jt]sx?$/u,Jr="allowUnauthenticatedShardAccess",Ms=/[\\/]/u,Yr=new Set(["_generated","build","dist","node_modules"]),Xr=(e,r)=>{const t=J(e,r).split(Ms);return Kr.test(r)&&!zr.test(r)&&!we(t.join("/"))&&t.every(n=>n===".."||!n.startsWith(".")&&!Yr.has(n))},hr=(e,r,t)=>{const{parsed:n}=j(r);if(n===void 0)return[];const{error:o,merged:s}=ue(n,t),{main:i}=o===void 0?s:n,a=typeof i=="string"?A(Ir(r),i):void 0;return a!==void 0&&b(a)&&Xr(e,a)?[a]:[]},We=e=>e===void 0?!1:e.getKind()===k.FalseKeyword?!0:S.isParenthesizedExpression(e)||S.isAsExpression(e)||S.isSatisfiesExpression(e)||S.isTypeAssertion(e)||S.isNonNullExpression(e)?We(e.getExpression()):!1,Us=e=>{try{return Te(e).isFile()}catch{return!1}},Bs=new Set(["ELOOP","ENOENT","ENOTDIR"]),ce=(e,r,t)=>{const n=r instanceof Error&&"code"in r&&typeof r.code=="string"?r.code:"";Bs.has(n)||t.push(e)},Ws=(e,r)=>{try{return Te(e)}catch(t){ce(e,t,r);return}},Qr=(e,r)=>{try{return E(e,"utf8")}catch(t){ce(e,t,r);return}},Zr=(e,r,t,n=new Set)=>{let o;try{o=ft(r)}catch(i){return ce(r,i,t),[]}if(n.has(o))return[];n.add(o);let s;try{s=K(r)}catch(i){return ce(r,i,t),[]}return s.flatMap(i=>{const a=A(r,i),c=Ws(a,t);if(c===void 0)return[];const l=J(e,a).split(N).join("/");return c.isDirectory()?Yr.has(i)||i.startsWith(".")||we(`${l}/`)?[]:Zr(e,a,t,n):c.isFile()&&Kr.test(i)&&!zr.test(i)&&!we(l)?[a]:[]})},Hs=e=>{const r=S.isComputedPropertyName(e)?e.getExpression():e;return S.isStringLiteral(r)||S.isNoSubstitutionTemplateLiteral(r)?r.getLiteralValue():e.getText()},ve=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],qs=/\.(?:[cm]?js|jsx)$/u,Gs=(e,r)=>{if(!r.startsWith("."))return;const t=P(Ir(e),r),n=t.replace(qs,"");return[t,...ve.map(s=>`${t}${s}`),...ve.map(s=>A(t,`index${s}`)),...ve.map(s=>`${n}${s}`)].find(s=>Us(s))},Vs=e=>{if(e.getExpression().getText()!=="require")return;const[r]=e.getArguments();return r!==void 0&&(S.isStringLiteral(r)||S.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():void 0},Ks=e=>{const r=e.getModuleReference();if(!S.isExternalModuleReference(r))return;const t=r.getExpression();return S.isStringLiteral(t)?t.getLiteralValue():void 0},zs=(e,r,t,n)=>{const o=new Set(e),s=[...e],i=[];for(let a=0;a<s.length;a+=1){const c=s[a]??"",l=Qr(c,n);if(l===void 0)continue;const d=r.createSourceFile(J(t,c),l,{overwrite:!0}),u=[...d.getImportDeclarations().map(f=>f.getModuleSpecifierValue()),...d.getExportDeclarations().map(f=>f.getModuleSpecifierValue()),...d.getDescendantsOfKind(k.ImportEqualsDeclaration).map(f=>Ks(f)),...d.getDescendantsOfKind(k.CallExpression).map(f=>Vs(f))].filter(f=>f!==void 0);for(const f of u){const g=Gs(c,f);g!==void 0&&Xr(t,g)&&!o.has(g)&&(o.add(g),i.push(g),s.push(g))}}return i},Js=e=>{const r=e.getArgumentExpression();return r!==void 0&&(S.isStringLiteral(r)||S.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():void 0},Ys=e=>S.isPropertyAccessExpression(e)?e.getName():S.isElementAccessExpression(e)?Js(e):void 0,Xs=new Set([k.AmpersandAmpersandEqualsToken,k.AmpersandEqualsToken,k.AsteriskAsteriskEqualsToken,k.AsteriskEqualsToken,k.BarBarEqualsToken,k.BarEqualsToken,k.CaretEqualsToken,k.EqualsToken,k.GreaterThanGreaterThanEqualsToken,k.GreaterThanGreaterThanGreaterThanEqualsToken,k.LessThanLessThanEqualsToken,k.MinusEqualsToken,k.PercentEqualsToken,k.PlusEqualsToken,k.QuestionQuestionEqualsToken,k.SlashEqualsToken]),Qs=e=>{const r=e.getOperatorToken().getKind();return!Xs.has(r)||Ys(e.getLeft())!==Jr?!1:r!==k.EqualsToken||!We(e.getRight())},Zs=(e,r,t)=>{const n=[],o=[...new Set([x(e),"src"])].filter(u=>b(A(e,u))),s=O(e),i=[...Fs.map(u=>A(e,u)).filter(u=>b(u)),...s===void 0?[]:hr(e,s,r),...t.flatMap(u=>hr(e,u,r))],a=new Cr({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}),c=o.flatMap(u=>Zr(A(e,u),A(e,u),n));return{sites:[...new Set([...c,...i,...zs([...i,...c],a,e,n)])].flatMap(u=>{const f=Qr(u,n);if(f===void 0)return[];const g=a.createSourceFile(J(e,u),f,{overwrite:!0}),h=[...g.getDescendantsOfKind(k.PropertyAssignment),...g.getDescendantsOfKind(k.ShorthandPropertyAssignment),...g.getDescendantsOfKind(k.GetAccessor),...g.getDescendantsOfKind(k.MethodDeclaration)].filter(m=>{const $=S.isPropertyAssignment(m)&&We(m.getInitializer());return Hs(m.getNameNode())===Jr&&!$}).map(m=>m.getStartLineNumber()),v=g.getDescendantsOfKind(k.BinaryExpression).filter(m=>Qs(m)).map(m=>m.getStartLineNumber());return[...h,...v].map(m=>({file:J(e,u),line:m}))}),unreadable:n}},ei=(e,r,t,n,o,s)=>{if(t!=="deploy")return;const{sites:i,unreadable:a}=Zs(e,o,s),c=Tn({openShardAccess:i,schema:{tables:[]}},{lints:[Je]});if(c.length===0&&a.length===0)return;const l=[];if(c.length>0){const u=c.map(f=>`${String(f.metadata.file)}:${String(f.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(a.length>0&&l.push(`could not read ${a.join(", ")}, so the open-shard option cannot be ruled out there.`),n){r.warn(`deploying past the open-shard gate (--allow-open-shards): ${l.join(" ")}`);return}const d=`deploy blocked (open_shard_access): ${l.join(" ")} ${Je.remediation}`;return r.error(d),d},ri=(e,r,t,n)=>{const o=ei(e,r.logger,t,r.allowOpenShards===!0,r.env,n);return o===void 0?void 0:{code:y.USAGE,error:o}},ti=(e,r,t,n)=>{const o=Be(e,r.logger,t,n,r.env);if(o!==void 0)return{code:y.USAGE,error:o};const s=xs(e,r.logger,t,r.env);if(s!==void 0)return{code:y.USAGE,error:s};const i=Os(e,r.logger,t,r.discoveryCache);if(i!==void 0)return{code:y.USAGE,error:i};const a=js(e,r.logger,r.dockerAvailable??kn,t,r.env);return a===void 0?void 0:{code:y.MISSING_DEPENDENCY,error:a}},ni=/https?:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/u,oi=/https:\/\/[^\s"'<>]+/u,si=e=>{if(e===void 0)return;const r=ni.exec(e);return r?r[0]:oi.exec(e)?.[0]},mr=e=>e===void 0?"":` (--env ${e})`,ii=({cwd:e,env:r,logger:t,now:n,url:o})=>{if(o!==void 0)try{const s=_e(e);if(s!==void 0){if(s.workerUrl===o&&s.env===r)return;t.warn(`link: .lunora/project.json records ${s.workerUrl??"(no url)"}${mr(s.env)}, but this deploy published ${o}${mr(r)}. Keeping the recorded value — run \`lunora link --url ${o}${r===void 0?"":` --env ${r}`}\` to update it.`);return}const i=(n??(()=>new Date().toISOString()))();Tt(e,{env:r,linkedAt:i,workerName:je(e),workerUrl:o}),t.success(`link: recorded ${o} in .lunora/project.json (run \`lunora link\` to change)`)}catch{}},ai=async(e,r)=>{const t=new Cr({skipAddingFilesFromTsConfig:!0}),n=A(r,"lunora");let o;try{o=mt(t,n)}catch(s){const i=s instanceof Error?s.message:String(s);return e.logger.warn(`--migrate: could not discover migrations (${i}); 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 i={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},a=await Cn(i);if(a.code!==0)return e.logger.error(`--migrate: migration "${s.id}" failed — see output above`),a.code;e.logger.success(`--migrate: "${s.id}" applied`)}return 0},ci=async(e,r)=>{const{info:t}=Pe(r,"lunora",e.discoveryCache),n=t?.vectorMetadata??[];if(n.length===0)return;const o=[];for(const a of n){const c=sn(a.kind);if(c===void 0){e.logger.warn(`vector index "${a.index}" declares metadata "${a.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:a.index,property:a.property,type:c})}if(o.length===0)return;const i=(await an({cwd:r,entries:o,exec:Oe(F(r),"wrangler",[]),logger:e.logger,spawner:e.spawner??q})).filter(a=>a.status!=="failed").length;i>0&&e.logger.success(`vectorize metadata indexes ready: ${String(i)}/${String(o.length)}`)},pr=5,di=2e3,li=async(e,r,t)=>{if(e.healthCheck!==!0)return;const n=t??De({cwd:r,env:e.env});if(n===void 0){const s="--health-check: the deploy succeeded, but no URL to probe could be resolved — wrangler's output carried none and this checkout has no link for this environment. Run `lunora link --url <https://your-worker>` and re-deploy, or drop --health-check.";return e.logger.error(s),{error:s,ok:!1,url:""}}const o=await bn({attempts:pr,baseUrl:n,delayMs:di,fetchImpl:e.healthFetch,paths:[$n,Sn],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(pr)} attempt(s) — ${o.error}`),{error:o.error,ok:!1,url:o.url})},ui=async(e,r,t,n,o,s)=>{e.isolatedPreview!==!0&&await ci(e,r);const i=e.migrate?await ai(e,r):0;return i===0&&o?.(),{code:i,descriptor:t,mintedSecretsFile:s,validation:n}},fi=async({cwd:e,descriptor:r,mintedSecretsFile:t,options:n,reblessSchemaBaseline:o,recordArchitecture:s,stdout:i,validation:a})=>{const c={deployedAt:new Date().toISOString(),dryRun:n.dryRun===!0,env:n.env,url:n.dryRun===!0?void 0:si(i),workerName:je(e)};if(n.dryRun===!0)return n.healthCheck===!0&&n.logger.warn("--health-check skipped: a dry run publishes nothing"),{code:0,deployment:c,descriptor:r,mintedSecretsFile:t,validation:a};n.temporary!==!0&&n.isolatedPreview!==!0&&(s?.(),ii({cwd:e,env:n.env,logger:n.logger,url:c.url}));const l=await li(n,e,c.url);if(l?.error!==void 0)return{code:y.UNAVAILABLE,deployment:c,descriptor:r,healthCheck:l,mintedSecretsFile:t,validation:a};const d=n.isolatedPreview===!0?void 0:o;return{...await ui(n,e,r,a,d,t),deployment:c,healthCheck:l}},gi=(e,r,t)=>{const n=A(e,L);if(!b(n))return;let o;try{o=kr(E(n,"utf8")).length}catch{return}if(o===0)return;const s=t.toolchain?.secretPut!==void 0;r.warn(s?`Note: \`lunora deploy\` does not push secrets. ${L} 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. ${L} 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.`)},et=async(e,r)=>{let t=[];try{t=Ct(await br({cache:r,projectRoot:e,schemaDir:x(e)}))}catch{}const n=[...new Set(_t(t).map(s=>s.key))];let o=[];try{const s=A(e,L);b(s)&&(o=kr(E(s,"utf8")).map(i=>i.key).filter(i=>Ar(i)))}catch{}return{fromLocal:o.filter(s=>!n.includes(s)),fromPackages:n,mintableKeys:Pt(t)}},hi=async(e,r,t,n)=>{const{logger:o}=r,s=r.spawner??q,i=F(e),a=r.env===void 0?"":` --env ${r.env}`,c=n.toolchain?.secretPut;if(c===void 0)return o.error(`deploy target "${n.id}" has no secret store; cannot push secrets`),{minted:[],ok:!1};const l=t.map(f=>({key:f,value:It()})),d=n.toolchain?.secretBulk;if(d!==void 0&&l.length>=2){const f=z(i,d({environment:r.env,temporary:r.temporary})),g=await s({args:f.args,command:f.command,cwd:e,input:JSON.stringify(Object.fromEntries(l.map(h=>[h.key,h.value])))});if(g.code===0){for(const{key:h}of l)o.success(`generated + pushed ${h}`);return{minted:l,ok:!0}}o.warn(`bulk secret push failed (exit ${String(g.code)}); retrying one key at a time`)}const u=[];for(const{key:f,value:g}of l){const h=c({environment:r.env,key:f,temporary:r.temporary}),v=z(i,h),m=await s({args:v.args,command:v.command,cwd:e,input:g});if(m.code!==0)return o.error(`failed to push secret ${f} (exit ${String(m.code)}); set it manually with \`wrangler secret put ${f}${a}\`.`),{minted:u,ok:!1};u.push({key:f,value:g}),o.success(`generated + pushed ${f}`)}return{minted:u,ok:!0}},mi=/^[\w-]+$/u,vr=[".dev.vars",".dev.vars.*","!.dev.vars.example"],pi=(e,r)=>{try{const t=Lt(e,vr);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 \`${vr.join("` and `")}\` by hand before committing.`)}},vi=(e,r,t)=>{if(t.length===0)return;const n=t.map(a=>a.key).join(", ");if(r.env!==void 0&&!mi.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?L:`${L}.${r.env}`;pi(e,r.logger);const s=A(e,o);let i=b(s)?E(s,"utf8"):"";for(const a of t)i=jt(i,a.key,a.value);return Ot(s,i),r.logger.success(r.env===void 0?`${n}: value(s) recorded in ${o}`:`${n}: value(s) recorded in ${o} (kept separate from ${L} so \`lunora dev\` and a plain \`lunora env push\` don't inherit the --env ${r.env} value)`),o},yi=/^<[^>]+>$/u,wi=async(e,r,t)=>{let n;try{n=t.projectConfig?.(e,"deploy").vars??{}}catch(d){return{error:d instanceof Error?d.message:String(d)}}const o=d=>{const u=n[d];if(typeof u!="string")return!0;const f=u.trim();return f===""||yi.test(f)?!0:Ar(d)&&Dt(u)},s=d=>Object.hasOwn(n,d)?`${d} (empty or a placeholder)`:d,{fromLocal:i,fromPackages:a}=await et(e,r.discoveryCache),c=i.filter(d=>o(d));c.length>0&&r.logger.warn(`${L} key(s) not set in the wrangler vars: ${c.map(d=>s(d)).join(", ")}. ${t.name} has no secret store: a key the app reads from env must be a \`vars\` entry; one it loads from a secret manager at runtime need not.`);const l=a.filter(d=>o(d));return l.length===0?{}:{error:`missing required secret(s) in the wrangler vars: ${l.map(d=>s(d)).join(", ")}. ${t.name} has no secret store and Lunora reads these from env, so each must be a real \`vars\` value in the config the deploy ships — write it there from your secret manager at deploy time rather than committing it. Add them, then re-deploy.`}},ki=async(e,r,t,n)=>{if(r.dryRun===!0||r.isolatedPreview===!0)return{};if(n.toolchain?.secretList===void 0)return wi(e,r,n);const{logger:o}=r,s=r.env===void 0?"":` --env ${r.env}`;let i;try{i=await(r.secretLister??Pn)({cwd:e,env:r.env,target:n.id,temporary:r.temporary})}catch{return{}}if(!i.ok)return{};const a=new Set(i.names),{fromLocal:c,fromPackages:l,mintableKeys:d}=await et(e,r.discoveryCache),u=[...l,...c].filter(h=>!a.has(h));if(u.length===0)return{};if(!t)return{error:`missing required secret(s) on the deploy target: ${u.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 h of u.filter(v=>!d.has(v)))o.warn(`required secret ${h} is not set on the target — set it with: wrangler secret put ${h}${s}`);const f=u.filter(h=>d.has(h));if(f.length===0)return{};if(await(r.secretConfirm??_n())(`${String(f.length)} required secret(s) not set on the target (${f.join(", ")}). Generate strong values and push them now?`)){const{minted:h,ok:v}=await hi(e,r,f,n),m=vi(e,r,h);return v?{mintedSecretsFile:m}:{error:"failed to push required secret(s) — set them manually and re-deploy",mintedSecretsFile:m}}return o.warn(`${String(f.length)} required secret(s) not set on the target: ${f.join(", ")}. Generate + push with \`lunora env generate --set\` then \`lunora env push --yes${s}\`.`),{}},rt=e=>e.format==="json"?!1:e.interactive!==void 0?e.interactive:process.stdout.isTTY&&!process.env.CI,bi=async(e,r)=>{if(r.dryRun===!0)return;const t=wr(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 as({cwd:e,logger:r.logger,railpackAvailable:r.railpackAvailable,spawner:r.spawner,targets:t});return n.code===0?void 0:n.error??"railpack build failed"},$i=(e,r,t)=>{if(t!==void 0)try{const n=zt(e,t);n.changed&&r.success(`synced ${String(t.length)} cron trigger(s) → ${n.wranglerPath??"wrangler.jsonc"}`);for(const s of n.warnings)r.warn(s);const o=Jt(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}`)}},Si=async(e,r,t,n,o,s)=>{try{le(n);const i=await br({cache:s,projectRoot:e,schemaDir:x(e)}),a=Vt(e,i,{environment:o,target:n}),c=a.wranglerPath??"wrangler.jsonc";if(a.added.length>0&&r.success(`provisioned bindings: ${a.added.join(", ")} → ${c}`),a.updated.length>0&&r.success(`updated bindings: ${a.updated.join(", ")} → ${c}`),a.devConfig!==void 0){const{added:l,path:d,updated:u}=a.devConfig;r.success(`dev sidecar bindings: ${[...l,...u].join(", ")} → ${d}`)}for(const l of a.warnings)r.warn(l)}catch(i){const a=i instanceof Error?i.message:String(i);r.warn(`binding inference skipped: ${a}`)}try{const i=Kt(e);i.changed&&r.success(`bumped compatibility_date to ${i.date??"unknown"} (Workers Cache enabled) → ${i.wranglerPath??"wrangler.jsonc"}`)}catch(i){const a=i instanceof Error?i.message:String(i);r.warn(`compatibility date sync skipped: ${a}`)}$i(e,r,t)},Ei=async(e,r,t,n,o,s,i,a,c,l)=>{let d;r?(d=new Yt({name:"dots"}),d.start("running codegen")):t.info("running codegen");try{const u=pt({apiSpec:n,dryRun:!l,lazyFunctions:o,projectRoot:e,target:s,...Gt(e)});d?.succeed("codegen complete"),d||t.success("codegen complete");const f=rn(u.platformDiagnostics,t);if(f.errors.length>0)return{error:f.errors.join("; ")};const{errorAdvisories:g,names:h,shouldBlock:v}=tn(u.advisories,c);if(v){const $=`${g.length.toString()} ERROR-level ${g.length===1?"advisory":"advisories"} (${h.join(", ")}). Pass --no-strict-advisories to downgrade this to a warning and continue.`;return t.error($),{error:$}}const m=l?await Ut({cwd:e,logger:t,spawner:i,stdoutToStderr:a}):void 0;return m?.error!==void 0?{error:m.error}:{result:u}}catch(u){d?.failed("codegen failed");const f=u instanceof Error?u.message:String(u);return t.error(`codegen failed: ${f}`),{error:`codegen failed: ${f}`}}},yr="--preview is not supported: Cloudflare gives a Worker that implements a Durable Object no version preview URL, and a version shares production's Durable Objects, D1 and R2. Deploy an isolated copy with `lunora preview deploy <name>` (its own Worker, Durable Object namespace, D1, R2 and KV; `lunora preview delete <name>` removes it), or validate without publishing with `--dry-run`.",Ai=(e,r)=>({dryRun:r.dryRun,entry:Ue(e),environment:r.env,outDir:r.outDir,secretsFile:r.secretsFile,outFile:r.outFile,preview:r.preview,temporary:r.temporary}),tt=(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=Ai(e,r);return $r(t,e,"deploy",s=>n.deploy({...o,configPath:s}))},Ri=(e,r,t)=>{const n=tt(e,r,t),o=Ue(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},_={problems:[],wranglerPath:void 0},ye=(e,r)=>({code:y.USAGE,descriptor:void 0,error:e,validation:_,...r}),Ti=(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},Ci=(e,r,t)=>{const n=r.format==="json",o=r.dryRun!==!0,s=Ri(e,r,t),i=z(F(e),s);return{args:i.args,captureStdout:o&&!n,captureStdoutSilently:o&&n,command:i.command,cwd:e,stdoutToStderr:n&&!o}},He=e=>{if(e.skipServices===!0)return"--skip-services";if(e.isolatedPreview===!0)return"a preview never deploys services: they are production's Workers";if(e.temporary===!0)return"--temporary deploys the app to a throwaway account"},_i=(e,r)=>He(r)===void 0?Ce(e).services.map(t=>t.wranglerPath):[],nt=(e,r,t,n,o)=>({cwd:e,environment:r.env,frameworkBuild:n,lazyFunctions:de(r.lazyFunctions),logger:r.logger,outputJson:r.format==="json"||r.clientBuildOutputJson===!0,spawner:o,strictAdvisories:Ie(r),target:t.id}),Pi=(e,r,t)=>{const{toolchain:n}=t,o=n===void 0?`target "${t.id}" has no deploy command`:He(r);if(o!==void 0||n===void 0){const s=e.map(i=>i.worker).join(", ");r.logger.warn(`services not deployed (${o??""}): ${s} — deploy them yourself if the app calls anything new`);return}return n},ot=(e,r)=>{for(const t of e){const n=Fe(r(R(t.wranglerPath)));if(n!==void 0)return`service ${t.name} (${t.worker}): ${n}`}},Ii=(e,r,t)=>{const{error:n,services:o}=Ce(e);if(n!==void 0||o.length===0)return;const s=le(t);if(s.toolchain===void 0||He(r)!==void 0)return;const i=r.skipCodegen===!0?!1:r.frameworkBuild,a=[...new Map(o.map(c=>[c.wranglerPath,c])).values()];return ot(a,c=>nt(c,r,s,i,q))},st=(e,r,t)=>{const n=e.cwd??process.cwd(),o=fn(n,e.target);if(o.target===void 0){const a=o.error??"unknown deploy target";return e.logger.error(a),{kind:"refused",error:a,validation:_}}if(e.preview===!0)return e.logger.error(yr),{kind:"refused",code:y.USAGE,error:yr,validation:_};try{tt(n,e,le(o.target))}catch(a){if(!(t&&a instanceof Nt&&he(n,e.skipCodegen===!0?!1:e.frameworkBuild,e.env))){const c=a instanceof Error?a.message:String(a);return e.logger.error(c),{kind:"refused",error:c,validation:_}}}const s=e.openShardGatePassed===!0?void 0:ri(n,e,r,_i(n,e));if(s!==void 0)return{kind:"refused",code:s.code,error:s.error,validation:_};const i=Ii(n,e,o.target);return i!==void 0?(e.logger.error(i),{kind:"refused",code:y.USAGE,error:i,validation:_}):{kind:"ok",target:o.target}},ji=(e,r)=>e.apiSpec??(e.clientBuildRan===!0?Bt(r):void 0),Oi=async(e,r,t)=>{if(r!=="celld")return;const n=await(e.celldToolchain??Mt)({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},it=(e,r)=>{const t=De({cwd:e,env:r.env,url:r.migrateUrl}),n=t===void 0?void 0:$s(e,r.env,t);if(n!==void 0)return{reason:n};const o=t===void 0?void 0:Zt(t,r.logger,e),s=o===void 0?void 0:Xt({cwd:e,token:r.migrateToken,url:o}).token;return{target:o===void 0||!s?void 0:{baseUrl:o,fetchImpl:r.fetchImpl??en,token:s}}},Di=(e,r,t)=>async n=>{const o=it(e,r);return"reason"in o?{kind:"inconclusive",reason:o.reason}:Rn({changes:n,tables:t.schemaTables,target:o.target})},Li=(e,r)=>async t=>{const n=it(e,r);return"reason"in n?n.reason:An({changes:t,now:Date.now(),target:n.target})},Ni=(e,r,t,n)=>e==="deploy"?{checkStoredRows:Di(r,t,n),countExpiringRows:Li(r,t)}:{},xi=async(e,r)=>{const t=e.cwd??process.cwd(),n=rt(e),o=Ie(e),s={problems:[],wranglerPath:void 0},i=st(e,r,!1);if(i.kind==="refused")return{code:i.code,error:i.error,validation:i.validation};const{target:a}=i,c=await Oi(e,a,r);if(c!==void 0)return e.logger.error(c),{code:y.MISSING_DEPENDENCY,error:c,target:a,validation:s};let l;if(!e.skipCodegen){const v=await Ei(t,n,e.logger,ji(e,t),de(e.lazyFunctions),a,e.spawner,e.format==="json",o,e.clientBuildRan!==!0);if(v.error!==void 0)return{error:v.error,target:a,validation:_};l=v.result,e.discoveryCache?.clear()}let d;if(l!==void 0){const v=await En({allowDrift:e.allowSchemaDrift===!0,...Ni(r,t,e,l),codegen:l,command:r,logger:e.logger});if(v.blocked)return{error:`schema drift gate blocked ${r}`,schemaDrift:{blocked:!0,reason:v.reason},target:a,validation:s};d=v.rebless}const u=l&&xn({current:l.architecture,cwd:t,environment:e.env,logger:e.logger});await Si(t,e.logger,l?.cronTriggers,a,e.env,e.discoveryCache);const f=await H(t,e,r,a,"check");if(f!==void 0)return{error:f,target:a,validation:_};const g=ti(t,e,r,a);if(g!==void 0)return{code:g.code,error:g.error,target:a,validation:_};const h=qt({environment:e.env,projectRoot:t});return Ti(h,e.logger)?{error:"wrangler validation failed",target:a,validation:h}:{codegen:l,reblessSchemaBaseline:d,recordArchitecture:u,target:a,validation:h}},Fi=e=>{oe(p(e,".wrangler","deploy","config.json"),{force:!0})},Mi=async(e,r,t)=>{const n=Fe(e);if(n!==void 0)return{built:!1,error:n};const o=he(e.cwd,r,t);return o&&Fi(e.cwd),{built:o,error:await Vr(e)}},Ui=(e,r,t)=>r||t===!1?Le(e):void 0,Bi=async(e,r,t)=>{const n=R(e);return Be(n,r.logger,"deploy",t.id,r.env,e)??H(n,r,"deploy",t.id,"check",e)},Wi=(e,r,t)=>e.map((n,o)=>{const s=r[o]===!0,i=Ui(n.wranglerPath,s,t);return{built:s,config:i??n.wranglerPath,resolved:i!==void 0,service:n}}),Hi=async(e,r,t)=>{const{config:n,resolved:o,service:s}=e;if(!b(n))return;const i=R(s.wranglerPath),a=o?void 0:r.env,c=Be(i,r.logger,"deploy",t.id,a,n);if(c!==void 0)return{code:y.USAGE,error:`service ${s.name} (${s.worker}): ${c}`};if(o&&!e.built&&r.env!==void 0&&yo(i,void 0,n)){const d=`service ${s.name} (${s.worker}): its prebuilt config ${n} still has a Hyperdrive placeholder, and it was not built for --env ${r.env}, so it cannot be resolved here. Build it with CLOUDFLARE_ENV=${r.env}.`;return r.logger.error(d),{code:y.USAGE,error:d}}const l=await H(i,{...r,clientBuildEnvironment:void 0,env:a},"deploy",t.id,"check",n);return l===void 0?void 0:{code:y.USAGE,error:`service ${s.name} (${s.worker}): ${l}`}},qi=async(e,r,t)=>{for(const n of e){const o=await Hi(n,r,t);if(o!==void 0)return o}},Gi=async(e,r,t)=>{const{config:n,resolved:o,service:s}=e;if(!b(n))return;const i=R(s.wranglerPath),a=o?void 0:r.env,c=e.built?r.env:void 0,l=await H(i,{...r,clientBuildEnvironment:c,env:a},"deploy",t.id,"create",n);if(l!==void 0)return{code:y.FAILURE,error:`service ${s.name} (${s.worker}): ${l}`};if(n===s.wranglerPath)return;const d=await H(i,{...r,clientBuildEnvironment:void 0},"deploy",t.id,"create",s.wranglerPath);return d===void 0?void 0:{code:y.FAILURE,error:`service ${s.name} (${s.worker}): ${d}`}},Vi=async(e,r,t,n,o)=>{const s=[];for(const i of e){const{built:a,error:c}=await Mi(r(R(i.wranglerPath)),t,n);if(c!==void 0){const l=`service ${i.name} (${i.worker}): ${c}`;return o.error(l),{builds:s,failure:{code:y.FAILURE,error:l}}}s.push(a)}return{builds:s}},Ki=async(e,r)=>{const{driver:t,manager:n,options:o,spawner:s,toolchain:i}=r,{config:a,service:c}=e,l=R(c.wranglerPath);let d;try{d=$r(t,l,"deploy",g=>i.deploy({configPath:g??a,dryRun:o.dryRun===!0,environment:o.env}))}catch(g){return{code:y.FAILURE,error:`service ${c.name} (${c.worker}): ${g instanceof Error?g.message:String(g)}`}}d.commit();const u=z(n,d.command);o.logger.info(`deploying service ${c.name} (${c.worker}) via ${u.command} ${u.args.join(" ")}`);const f=await s({args:u.args,command:u.command,cwd:l,stdoutToStderr:o.format==="json"});if(f.code!==0)return{code:y.FAILURE,error:`service ${c.name} (${c.worker}): ${u.command} ${u.args.join(" ")} exited ${String(f.code)} — stopping before the app`}},zi=async(e,r,t,n)=>{const{error:o,services:s}=Ce(e);if(o!==void 0)return{code:y.FAILURE,error:o};if(s.length===0)return;const i=Pi(s,r,t);if(i===void 0)return;const a=F(e),c=[...new Map(s.map($=>[$.wranglerPath,$])).values()],l=r.skipCodegen===!0?!1:r.frameworkBuild,d=$=>nt($,r,t,l,n),u=ot(c,d);if(u!==void 0)return r.logger.error(u),{code:y.USAGE,error:u};for(const $ of c){const C=await Bi($.wranglerPath,r,t);if(C!==void 0)return{code:y.USAGE,error:`service ${$.name} (${$.worker}): ${C}`}}const{builds:f,failure:g}=await Vi(c,d,l,r.env,r.logger);if(g!==void 0)return g;const h=Wi(c,f,l),v=await qi(h,r,t);if(v!==void 0)return v;const m={driver:t,manager:a,options:r,spawner:n,toolchain:i};for(const $ of h){const C=await Gi($,r,t);if(C!==void 0)return C;const T=await Ki($,m);if(T!==void 0)return T}},Ji=async(e,r,t,n)=>{if(r!=="cloudflare")return;const o=e===void 0?void 0:j(e).parsed,s=(t===void 0?void 0:o?.env?.[t]?.account_id)??o?.account_id,i=await dn({accountId:s});(i.verdict==="near"||i.verdict==="full")&&n.warn(i.fix===void 0?i.message:`${i.message} ${i.fix}`)},Yi=e=>e.dryRun!==!0&&e.temporary!==!0,Xi=e=>e.temporary===!0?"temporary":e.dryRun===!0?"preview":"defer",Qi=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},Zi=(e,r,t)=>{const n=[];for(const o of e)if(o.verdict==="ok")o.changesAccount===!0&&r.info(o.message);else if(o.verdict==="unchecked"&&t==="preview")r.warn(`dry run: ${o.message}${o.fix===void 0?"":` ${o.fix}`} A real deploy stops here.`);else{const s=Qi(o);r.error(s),n.push(s)}return n},at=async(e,r,t,n,o,s,i)=>{const a=t==="cloudflare"&&r!==void 0?j(r).parsed:void 0;if(a===void 0)return;const c=(ue(a,n).merged.artifacts??[]).flatMap(h=>typeof h?.binding=="string"&&typeof h.namespace=="string"?[{binding:h.binding,namespace:h.namespace}]:[]),l=c.length===0?void 0:Pe(e,x(e),s).info?.jurisdiction;if(l===void 0)return;const d=[...new Map(c.map(h=>[h.namespace,h])).values()];if(i==="temporary"){o.warn(`--temporary deploys to a throwaway account, so the jurisdiction ("${l}") of Artifacts namespace ${d.map(h=>`"${h.namespace}"`).join(", ")} was not checked: it is created there on first use, in no jurisdiction.`);return}const u=(n===void 0?void 0:a.env?.[n]?.account_id)??a.account_id,f=await Promise.all(d.map(async h=>cn({...h,accountId:u,create:i==="create",jurisdiction:l,missingOk:i==="defer"||i==="preview"}))),g=Zi(f,o,i);return g.length===0?void 0:g.join(`
63
+ `)},ea=async(e,r,t,n,o,s)=>{const i=Yi(r)?await at(e,s,o,r.env,r.logger,r.discoveryCache,"create"):void 0;if(i!==void 0)return{code:y.FAILURE,error:i};const a=await H(e,r,"deploy",o);return a!==void 0?{code:y.FAILURE,error:a}:zi(e,r,t,n)},ra=async(e,r,t,n)=>{if(!(r.smokeLoad===!1||t.toolchain===void 0))return ss({composedEntry:Ue(e),configPath:n,cwd:e,environment:r.env,launcher:r.smokeLauncher,logger:r.logger,toolchain:t.toolchain})},ta=async e=>{const r={...e,discoveryCache:e.discoveryCache??Ft()},t=r.cwd??process.cwd(),n=rt(r),o=await xi(r,r.commandName??"deploy");if(o.error!==void 0){if(o.validation.problems.length>0)return{code:y.USAGE,descriptor:void 0,error:o.error,validation:o.validation};const m=o.schemaDrift===void 0?void 0:{schemaDrift:o.schemaDrift};return ye(o.error,{...m,...o.code===void 0?{}:{code:o.code}})}const{validation:s}=o,i=le(o.target),a=Ns(r)??await at(t,s.wranglerPath,o.target,r.env,r.logger,r.discoveryCache,Xi(r))??await ra(t,r,i,s.wranglerPath);if(a!==void 0)return ye(a);const c=i.toolchain?.prebuildsContainerImages===!0?await bi(t,r):void 0;if(c!==void 0)return ye(c);gi(t,r.logger,i),Ht(t,m=>{r.logger.warn(m)}),await Ji(s.wranglerPath,o.target,r.env,r.logger);const{error:l,mintedSecretsFile:d}=await ki(t,r,n,i);if(l!==void 0)return r.logger.error(l),{code:y.USAGE,descriptor:void 0,error:l,mintedSecretsFile:d,validation:s};const u=r.spawner??q,f=await ea(t,r,i,u,o.target,s.wranglerPath);if(f!==void 0)return{code:f.code,descriptor:void 0,error:f.error,mintedSecretsFile:d,validation:s};const g=Ci(t,r,i);r.logger.info(`deploying via ${g.command} ${g.args.join(" ")}`);const h=await u(g);return g.captureStdoutSilently===!0&&h.stdout!==void 0&&h.stdout!==""&&process.stderr.write(h.stdout),h.code!==0?{code:h.code,descriptor:g,mintedSecretsFile:d,validation:s}:{...await fi({...o,cwd:t,descriptor:g,mintedSecretsFile:d,options:r,stdout:h.stdout}),logsAvailable:i.toolchain?.tail!==void 0}},na=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:Ie(e),lazyFunctions:de(e.lazyFunctions),logger:r,outputJson:e.format==="json"||e.clientBuildOutputJson===!0,spawner:e.spawner,target:e.target},o=Fe(n);if(o!==void 0)return r.error(o),{code:y.USAGE,descriptor:void 0,error:o,validation:_};xt(t);const s=await Vr(n);if(s!==void 0)return r.error(s),{code:y.FAILURE,descriptor:void 0,error:s,validation:_}},oa=(e,r)=>{const t=r.skipCodegen===!0?!1:r.frameworkBuild;return he(e,t,r.env)?r.env:void 0},sa=async e=>{const{logger:r}=e,t=e.cwd??process.cwd(),n=st(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 na(e);if(o!==void 0)return o;const s=e.dryRun===!0?Hr(t):void 0;let i;try{if(i=await ta({...e,clientBuildEnvironment:oa(t,e),clientBuildRan:Cs(t,e.skipCodegen===!0?!1:e.frameworkBuild,e.env),logger:r,openShardGatePassed:!0}),i.code===0&&e.emitBindings!==void 0){const{error:a}=ln({destination:e.emitBindings,logger:r,projectRoot:e.cwd??process.cwd()});a!==void 0&&(r.error(a),i={...i,code:y.USAGE})}}finally{s?.()}return e.format==="json"||i.code===0&&e.dryRun!==!0&&e.isolatedPreview!==!0&&Fn({cwd:e.cwd??process.cwd(),env:e.env,logger:e.logger,logsAvailable:i.logsAvailable===!0,mintedSecretsFile:i.mintedSecretsFile,url:i.deployment?.url}),i},Ba=un(async({cwd:e,format:r,logger:t,options:n})=>{const o=is(e,n.root),s=await sa({allowOpenShards:n.allowOpenShards===!0,allowSchemaDrift:n.allowSchemaDrift===!0,apiSpec:nn(n.apiSpec),frameworkBuild:n.prebuilt===!0?!1:n.frameworkBuild,lazyFunctions:de(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:De({cwd:o,env:n.env,url:n.migrateUrl}),migrateYes:n.migrateYes===!0,preview:n.preview===!0,skipCodegen:n.prebuilt===!0,skipServices:n.skipServices===!0,smokeLoad:n.smokeLoad,strictAdvisories:n.strictAdvisories,target:n.target,temporary:n.temporary===!0});return{code:s.code,data:{deployment:s.deployment,healthCheck:s.healthCheck,mintedSecretsFile:s.mintedSecretsFile,schemaDrift:s.schemaDrift,validation:s.validation},error:s.error}});export{xi as a,Si as b,Gn as c,Hr as d,et as e,Ba as f,is as p,sa as r,ra as s,Ss as v};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/cli",
3
- "version": "1.0.0-alpha.477",
3
+ "version": "1.0.0-alpha.479",
4
4
  "description": "The Lunora CLI: init, dev, deploy, codegen, migrate, seed, doctor, insights, logs, registry, and the rest of the project commands",
5
5
  "keywords": [
6
6
  "agent-skills",