@lunora/cli 1.0.0-alpha.489 → 1.0.0-alpha.490
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +201 -104
- package/README.md +3 -3
- package/dist/index.d.mts +8 -3
- package/dist/index.d.ts +8 -3
- package/dist/packem_chunks/cli.mjs +2 -2
- package/dist/packem_chunks/dispatch.mjs +1 -1
- package/dist/packem_chunks/handler.mjs +15 -15
- package/dist/packem_chunks/handler10.mjs +1 -2
- package/dist/packem_chunks/handler11.mjs +1 -1
- package/dist/packem_chunks/handler12.mjs +1 -1
- package/dist/packem_chunks/handler13.mjs +3 -1
- package/dist/packem_chunks/handler14.mjs +1 -3
- package/dist/packem_chunks/handler15.mjs +1 -1
- package/dist/packem_chunks/handler16.mjs +1 -1
- package/dist/packem_chunks/handler17.mjs +1 -1
- package/dist/packem_chunks/handler18.mjs +1 -1
- package/dist/packem_chunks/handler19.mjs +1 -1
- package/dist/packem_chunks/handler20.mjs +1 -1
- package/dist/packem_chunks/handler24.mjs +1 -1
- package/dist/packem_chunks/handler29.mjs +1 -1
- package/dist/packem_chunks/handler3.mjs +1 -1
- package/dist/packem_chunks/handler4.mjs +1 -1
- package/dist/packem_chunks/handler5.mjs +3 -1
- package/dist/packem_chunks/handler6.mjs +1 -3
- package/dist/packem_chunks/handler7.mjs +1 -1
- package/dist/packem_chunks/handler8.mjs +1 -1
- package/dist/packem_chunks/handler9.mjs +2 -1
- package/dist/packem_chunks/runRpcCommand.mjs +1 -1
- package/dist/packem_shared/{resolve-target-BRvw8Pf7.mjs → resolve-target-C_ZloTvd.mjs} +1 -1
- package/dist/packem_shared/{runDeployCommand-D4hsYdg0.mjs → runDeployCommand-DhgZz8Sj.mjs} +1 -1
- package/dist/packem_shared/sql-u1MSmopg.mjs +3 -0
- package/package.json +4 -4
|
@@ -1,18 +1,18 @@
|
|
|
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
|
|
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 vt,realpathSync as pt}from"node:fs";import{dirname as R,join as v,resolve as I,relative as L,sep as x,extname as yt}from"node:path";import{PROJECT_CONFIG_FILENAMES as wt,isTestPath as we,discoverMigrations as kt,readServiceBindings as bt,readBoundServiceBindings as yr,runCodegen as $t}from"@lunora/codegen";import{readLinkedProject as Ce,discoverSchemaInfo as Pe,resolveSchemaDirectory as O,startDevProcess as St,acceptsConnection as Et,readApiSpecMarker as wr,resolveTargetOrThrow as ke,detectFramework as At,DEFAULT_BUNDLE_META_PATH as Rt,STRICT_ADVISORIES_ENV as Tt,LAZY_FUNCTIONS_ENV as Ct,BUNDLE_META_PATH_ENV as Pt,BUILD_TARGET_ENV as It,BUILD_ROOT_ENV as _t,canonicalPath as Dt,COMPOSED_WORKER_ENTRY as Ve,discoverContainerInfo as kr,D1_PLACEHOLDER_ID as Ke,writeLinkedProject as jt,DEV_VARS_FILE as N,parseDevVariableEntries as br,secretSourcesFromBindings as Ot,inferLunoraBindings as $r,requiredSecrets as Lt,mintableSecretKeysFor as Nt,generateSecretValue as xt,upsertDevVariableLine as Ft,writeDevVariablesFileAtomically as Mt,isPlaceholderValue as Ut,ensureGitignoreEntries as Bt,resolveLazyFunctions as de,resolveDeployDriver as le,MissingBuildOutputError as Wt,clearApiSpecMarker as qt,createDiscoveryCache as Ht,planToolchainInvocation as Sr,probeCelldToolchain as Gt,runPostCodegenHook as Vt}from"@lunora/config";import{findWranglerFile as j,readWranglerJsonc as _,HYPERDRIVE_PLACEHOLDER_ID as Er,applyModify as Ar,mergeWranglerEnvironment as ue,bindingsNeedingDatabase as Kt,warnCloudflareCliConfigOnce as zt,validateWranglerProject as Jt,wranglerCodegenInputs as Yt,reconcileWranglerBindings as Xt,reconcileWranglerCompatibilityDate as Qt,reconcileWranglerCrons as Zt,describePreservedCrons as en}from"@lunora/config/cloudflare";import{Spinner as rn}from"@visulima/spinner";import{r as tn}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{n as nn,r as on,a as sn}from"../packem_shared/admin-url-DJB8P6Jh.mjs";import{r as Ie,a as an,e as cn}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as dn}from"../packem_shared/api-spec-lYyq4vL6.mjs";import{e as ln,m as un,g as fn,i as Rr,d as gn,b as hn}from"../packem_shared/vectorize-metadata-DK61NmVx.mjs";import{w as mn}from"../packem_shared/binding-manifest-file-BZyQFSTF.mjs";import{d as vn}from"../packem_shared/command-BpMv2n0o.mjs";import{r as _e}from"../packem_shared/wrangler-name-Dsk5K1f-.mjs";import{a as pn}from"../packem_shared/deploy-target-resolve-BTCW1Iv4.mjs";import{EXIT_CODE as y}from"../packem_shared/EXIT_CODE-DQVhSE-1.mjs";import{spawn as Tr,spawnSync as yn}from"node:child_process";import{createHash as wn,randomUUID as Cr}from"node:crypto";import{setTimeout as kn}from"node:timers/promises";import{stripVTControlCharacters as bn}from"node:util";import{toolchainExecArgs as z,detectPackageManager as F,execArgsFor as De}from"@lunora/config/cli";import{ts as w,Project as Pr,SyntaxKind as k,Node as S}from"ts-morph";import{r as Ir,c as _r}from"../packem_shared/cloudflare-credentials-BVmZnDZk.mjs";import{f as $n}from"../packem_shared/free-port-DjbFhaaT.mjs";import{l as V}from"../packem_shared/js-literal-FWLi94Lh.mjs";import{containerBuildTag as Sn}from"@lunora/container";import{a as En,i as An}from"../packem_shared/docker-DpVxvYpL.mjs";import{defaultSpawner as H}from"../packem_shared/createRecordingSpawner-DchLi0gR.mjs";import{r as je}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{p as Rn,H as Tn,a as Cn,r as Pn,c as In,b as _n}from"../packem_shared/health-probe-By9T5x2y.mjs";import{runAdvisor as Dn,openShardAccess as ze}from"@lunora/advisor";import{join as A,relative as J,dirname as Dr}from"@visulima/path";import{runMigrateDataCommand as jn}from"../packem_shared/runMigrateGenerateCommand-DHdSMKbu.mjs";import{r as On}from"../packem_shared/sql-u1MSmopg.mjs";import{c as Ln}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{l as Nn}from"../packem_shared/wrangler-secrets-C9siMBwN.mjs";const xn=Object.freeze({edges:[],nodes:[],modules:[],unresolved:[],version:1}),Fn=20,Je=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))},Mn=(e,r)=>{const t=e.modules.map(i=>i.name),n=r.modules.map(i=>i.name),o=e.edges.map(i=>Je(i)),s=r.edges.map(i=>Je(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,Fn).map(s=>` ${e} ${s}`),o=t.length-n.length;return[`${r}:`,...n,...o>0?[` … and ${o.toString()} more`]:[]]},Un=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
|
-
`)}`},
|
|
4
|
-
`,"utf8")}catch(c){n.warn(`could not record the deployed architecture at ${o}: ${c instanceof Error?c.message:String(c)}`)}}},Hn=e=>{const{cwd:r,env:t,logger:n,mintedSecretsFile:o}=e;try{const s=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{}},qn=/\/index$/u,Gn=/[^\dA-Za-z]/gu,Vn=e=>e.replace(qn,"").split("/").map(r=>r.replaceAll(Gn,"_")),Kn=e=>Vn(e).join("_"),zn=/[^a-z0-9-]/gu,Jn=/-$/u,Ye=7,Yn=(e,r)=>{const t=e.toLowerCase(),n=t.replaceAll(zn,"-");if(n===t&&n.length<=r)return n;const o=wn("sha256").update(t).digest("hex").slice(0,Ye-1);return`${n.slice(0,r-Ye).replace(Jn,"")}-${o}`},Xn=32,Dr=15e3,Qn=5432,Zn=3306,eo=/[^A-Za-z0-9]/gu,Y=e=>`LUNORA_${e.replaceAll(eo,"_").toUpperCase()}_URL`,ro=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)}},to=(e,r)=>Yn(`${e}-${r}`,Xn),Xe=e=>e==="postgresql"?"postgres":e==="mariadb"?"mysql":e,no=e=>e==="mysql"?Zn:Qn,oo=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===""?no(Xe(t)):Number(r.port),scheme:Xe(t),user:decodeURIComponent(r.username)}}catch{return}},so=(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===Er?[{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}`},io=e=>typeof e=="string"||typeof e=="number"?e.toString():void 0,ao=["scheme","host","port","database","user"],co=e=>e==="postgresql"?"postgres":e,Qe=(e,r)=>{const t=io(r);return e==="scheme"?co(t):t},Ze=50,lo=async(e,r)=>{for(let t=1;t<=Ze;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(Ze)} pages, so "${r}" can't be shown to be absent`)},uo=async(e,r,t,n)=>{const o=n?{caching:{disabled:!0}}:{},s=await lo(e,r);if(typeof s?.id=="string"){const c=ao.filter(d=>Qe(d,s.origin?.[d])!==Qe(d,t[d]));if(c.length>0)throw new Error(`a Hyperdrive config named "${r}" already exists for a different origin, or one that can't be confirmed (${c.join(", ")}). Delete it, or rename the Worker, so the binding does not reach the wrong database.`);const l=await e(`/hyperdrive/configs/${encodeURIComponent(s.id)}`,{body:JSON.stringify({origin:t,...o}),method:"PATCH"});if(!l.ok)throw new Error(`updating its credentials failed (${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}},fo=(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.`,go=async(e,r)=>{const t=to(e.workerName,e.binding),{id:n,reused:o}=await uo(async(s,i)=>Ir({accountId:e.accountId,apiToken:e.token,...e.fetch===void 0?{}:{fetch:e.fetch},init:{...i,signal:AbortSignal.timeout(Dr)},path:s}),t,e.origin,e.disableCaching);return e.logger.success(`${o?"reusing":"created"} Hyperdrive config "${t}" for ${e.binding} → ${e.wranglerPath}`),{id:n,text:Ar(r,[...e.path,e.index,"id"],n)}},ho=e=>e===void 0||e===""?void 0:e,Oe=e=>{const r=p(R(e),".wrangler","deploy","config.json");try{const{configPath:t}=JSON.parse(E(r,"utf8"));return typeof t=="string"?_(R(r),t):void 0}catch{return}},mo=(e,r,t,n,o)=>{const s=Oe(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=I(s)}catch{return}const a=Or(i.parsed?.hyperdrive).find(c=>c.binding===r);a!==void 0&&X(s,Ar(i.text,["hyperdrive",a.index,"id"],t),"utf8")},po=(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??D(e),o=n===void 0?void 0:I(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:po(o,r),wranglerPath:n}},vo=(e,r,t)=>{const n=ro(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=fo(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}}},yo=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\`.`)},wo=async(e,r)=>{const t=e.wranglerPath??D(e.cwd),n=t===void 0?void 0:I(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)=>Ir({accountId:s,apiToken:i,...e.fetch===void 0?{}:{fetch:e.fetch},init:{...l,signal:AbortSignal.timeout(Dr)},path:c});for(const c of Array.isArray(o?.hyperdrive)?o.hyperdrive:[]){const{binding:l,id:d}=typeof c=="object"&&c!==null?c:{};typeof l=="string"&&typeof d=="string"&&d!==Er&&await yo(a,l,d,e.logger)}},ko=async e=>{const r=e.environment??process.env;e.disableCaching===!0&&e.checkOnly!==!0&&e.dryRun!==!0&&await wo(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:oo(u),supplied:u!==""}}),l=vo(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 go({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"),mo(s,u,h,{built:ho(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: ${so(v,c[d]?.origin)}`;return e.logger.error(m),m}}},bo=(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},$o=(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 bo(e,r);if(r.temporary===!0)return $o(e,r);const i=r.clientBuildEnvironment===void 0?void 0:{...process.env,CLOUDFLARE_ENV:r.clientBuildEnvironment},a=Pe(e,O(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.`),ko({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})},So=(e,r,t)=>fe(e,r,t)!==void 0,pe=[".ts",".tsx",".mts",".js",".mjs"],Eo=/^[a-z]+:/u,er=/\.[cm]?js$/u,Ao=e=>!e.startsWith(".")&&!e.startsWith("/")&&!e.startsWith("#")&&!Eo.test(e),Ro=e=>e.split("/").slice(0,e.startsWith("@")?2:1).join("/"),To=e=>e.split(x).some(r=>r==="_generated"||r==="node_modules"),Co=e=>e.split(x).includes("node_modules"),rr=(e,r)=>{const t=_(R(e),r),n=er.test(t)?t.replace(er,""):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())},Po=/^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}},_o=(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)}}},Io=(e,r)=>{const t=p(e,r,"_generated"),n=K(e).find(o=>Po.test(o));return[...b(t)?K(t).filter(o=>o.endsWith(".ts")).map(o=>p(t,o)):[],...n===void 0?[]:[p(e,n)]]},jo=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},tr=e=>e!==void 0&&(w.isNamedImports(e)||w.isNamedExports(e))&&e.elements.length>0&&e.elements.every(r=>r.isTypeOnly),Do=(e,r)=>{if(w.isImportDeclaration(e)){const{importClause:t}=e;return!(t?.phaseModifier===w.SyntaxKind.TypeKeyword||!r&&t?.name===void 0&&tr(t?.namedBindings))&&w.isStringLiteral(e.moduleSpecifier)?e.moduleSpecifier.text:void 0}if(w.isExportDeclaration(e))return!(e.isTypeOnly||!r&&tr(e.exportClause))&&e.moduleSpecifier!==void 0&&w.isStringLiteral(e.moduleSpecifier)?e.moduleSpecifier.text:void 0},Oo=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},Lo=(e,r)=>{const t=w.createSourceFile(e,E(e,"utf8"),w.ScriptTarget.Latest,!1),n=[],o=[],s=i=>{const a=Oo(i),c=a??Do(i,r);c?.startsWith(".")||c?.startsWith("#")?o.push(c):a!==void 0&&Ao(a)&&n.push(a),w.forEachChild(i,s)};return s(t),{dynamicPackages:n,relative:o}},No=(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}},xo=(e,r,t)=>{const n=jo(e),o=new Set,s=new Set,i=r!==void 0&&b(_(e,r))?[_(e,r)]:Io(e,t);for(let a=i.shift();a!==void 0;a=i.shift())if(!o.has(a)&&!Co(L(e,a))){o.add(a);const{dynamicPackages:c,relative:l}=Lo(a,n);if(!To(L(e,a)))for(const d of c)s.add(d);i.push(...l.flatMap(d=>{if(!d.startsWith("#"))return rr(a,d)??[];const u=_o(e,d);return u===void 0?[]:rr(p(e,"package.json"),u)??[]}))}return[...s].filter(a=>No(e,Ro(a))).toSorted((a,c)=>a.localeCompare(c))},Fo=18787,nr=3,$e=12e4,Lr=5e3,W=10,Nr=new Set([".js",".mjs",".mts",".ts",".tsx"]),Mo=/\(void 0\)|is not a function|before initialization|of undefined/u,Uo=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",Bo=e=>{const r=O(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=yt(o);Nr.has(s)&&!o.split(x).some(i=>i==="_generated"||i==="node_modules")&&t.set(Kn(o.slice(0,-s.length).split(x).join("/")),p(r,o))}return t},or=e=>Mo.test(e)?`
|
|
5
|
-
hint: if this module is part of a circular import, an import it reads is still undefined while it evaluates`:"",
|
|
3
|
+
`)}`},Bn=(e,r)=>v(e,".lunora",r===void 0?"architecture.json":`architecture.${r}.json`),Wn=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}},qn=e=>{const{cwd:r,environment:t,logger:n}=e,o=Bn(r,t),s=Wn(o),i=e.current??(s===void 0?void 0:xn);if(i===void 0)return;const a=s===void 0?void 0:Un(Mn(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)}`)}}},Hn=e=>{const{cwd:r,env:t,logger:n,mintedSecretsFile:o}=e;try{const s=Ce(r),i=s?.workerName??_e(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{}},Gn=/\/index$/u,Vn=/[^\dA-Za-z]/gu,Kn=e=>e.replace(Gn,"").split("/").map(r=>r.replaceAll(Vn,"_")),zn=e=>Kn(e).join("_"),Jn=/[^a-z0-9-]/gu,Yn=/-$/u,Ye=7,Xn=(e,r)=>{const t=e.toLowerCase(),n=t.replaceAll(Jn,"-");if(n===t&&n.length<=r)return n;const o=wn("sha256").update(t).digest("hex").slice(0,Ye-1);return`${n.slice(0,r-Ye).replace(Yn,"")}-${o}`},Qn=32,jr=15e3,Zn=5432,eo=3306,ro=/[^A-Za-z0-9]/gu,Y=e=>`LUNORA_${e.replaceAll(ro,"_").toUpperCase()}_URL`,to=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)}},no=(e,r)=>Xn(`${e}-${r}`,Qn),Xe=e=>e==="postgresql"?"postgres":e==="mariadb"?"mysql":e,oo=e=>e==="mysql"?eo:Zn,so=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===""?oo(Xe(t)):Number(r.port),scheme:Xe(t),user:decodeURIComponent(r.username)}}catch{return}},io=(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===Er?[{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}`},ao=e=>typeof e=="string"||typeof e=="number"?e.toString():void 0,co=["scheme","host","port","database","user"],lo=e=>e==="postgresql"?"postgres":e,Qe=(e,r)=>{const t=ao(r);return e==="scheme"?lo(t):t},Ze=50,uo=async(e,r)=>{for(let t=1;t<=Ze;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(Ze)} pages, so "${r}" can't be shown to be absent`)},fo=async(e,r,t,n)=>{const o=n?{caching:{disabled:!0}}:{},s=await uo(e,r);if(typeof s?.id=="string"){const c=co.filter(d=>Qe(d,s.origin?.[d])!==Qe(d,t[d]));if(c.length>0)throw new Error(`a Hyperdrive config named "${r}" already exists for a different origin, or one that can't be confirmed (${c.join(", ")}). Delete it, or rename the Worker, so the binding does not reach the wrong database.`);const l=await e(`/hyperdrive/configs/${encodeURIComponent(s.id)}`,{body:JSON.stringify({origin:t,...o}),method:"PATCH"});if(!l.ok)throw new Error(`updating its credentials failed (${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}},go=(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.`,ho=async(e,r)=>{const t=no(e.workerName,e.binding),{id:n,reused:o}=await fo(async(s,i)=>_r({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:Ar(r,[...e.path,e.index,"id"],n)}},mo=e=>e===void 0||e===""?void 0:e,Oe=e=>{const r=v(R(e),".wrangler","deploy","config.json");try{const{configPath:t}=JSON.parse(E(r,"utf8"));return typeof t=="string"?I(R(r),t):void 0}catch{return}},vo=(e,r,t,n,o)=>{const s=Oe(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=_(s)}catch{return}const a=Or(i.parsed?.hyperdrive).find(c=>c.binding===r);a!==void 0&&X(s,Ar(i.text,["hyperdrive",a.index,"id"],t),"utf8")},po=(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??j(e),o=n===void 0?void 0:_(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:po(o,r),wranglerPath:n}},yo=(e,r,t)=>{const n=to(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=go(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}}},wo=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\`.`)},ko=async(e,r)=>{const t=e.wranglerPath??j(e.cwd),n=t===void 0?void 0:_(t).parsed,o=e.wranglerEnvironment===void 0?n:n?.env?.[e.wranglerEnvironment],{accountId:s,token:i}=Ir(r,o?.account_id??n?.account_id);if(s===void 0||i===void 0)return;const a=async(c,l)=>_r({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!==Er&&await wo(a,l,d,e.logger)}},bo=async e=>{const r=e.environment??process.env;e.disableCaching===!0&&e.checkOnly!==!0&&e.dryRun!==!0&&await ko(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}=Ir(r,t.accountId),c=n.map(({binding:d})=>{const u=r[Y(d)]??"";return{binding:d,origin:so(u),supplied:u!==""}}),l=yo(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:p}=await ho({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,p,"utf8"),vo(s,u,h,{built:mo(r.CLOUDFLARE_ENV),deployed:e.wranglerEnvironment},e.logger)}catch(h){const p=h instanceof Error?h.message:String(h),m=`deploy blocked: the "${u}" Hyperdrive config could not be set up: ${io(p,c[d]?.origin)}`;return e.logger.error(m),m}}},$o=(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},So=(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},q=async(e,r,t,n,o="create",s)=>{if(n!=="cloudflare")return;if(t==="prepare")return $o(e,r);if(r.temporary===!0)return So(e,r);const i=r.clientBuildEnvironment===void 0?void 0:{...process.env,CLOUDFLARE_ENV:r.clientBuildEnvironment},a=Pe(e,O(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.`),bo({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})},Eo=(e,r,t)=>fe(e,r,t)!==void 0,ve=[".ts",".tsx",".mts",".js",".mjs"],Ao=/^[a-z]+:/u,er=/\.[cm]?js$/u,Ro=e=>!e.startsWith(".")&&!e.startsWith("/")&&!e.startsWith("#")&&!Ao.test(e),To=e=>e.split("/").slice(0,e.startsWith("@")?2:1).join("/"),Co=e=>e.split(x).some(r=>r==="_generated"||r==="node_modules"),Po=e=>e.split(x).includes("node_modules"),rr=(e,r)=>{const t=I(R(e),r),n=er.test(t)?t.replace(er,""):void 0;return[t,...n===void 0?[]:ve.map(s=>`${n}${s}`),...ve.map(s=>`${t}${s}`),...ve.map(s=>v(t,`index${s}`))].find(s=>b(s)&&Te(s).isFile())},Io=/^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}},_o=(e,r)=>{let t;try{t=JSON.parse(E(v(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)}}},Do=(e,r)=>{const t=v(e,r,"_generated"),n=K(e).find(o=>Io.test(o));return[...b(t)?K(t).filter(o=>o.endsWith(".ts")).map(o=>v(t,o)):[],...n===void 0?[]:[v(e,n)]]},jo=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},tr=e=>e!==void 0&&(w.isNamedImports(e)||w.isNamedExports(e))&&e.elements.length>0&&e.elements.every(r=>r.isTypeOnly),Oo=(e,r)=>{if(w.isImportDeclaration(e)){const{importClause:t}=e;return!(t?.phaseModifier===w.SyntaxKind.TypeKeyword||!r&&t?.name===void 0&&tr(t?.namedBindings))&&w.isStringLiteral(e.moduleSpecifier)?e.moduleSpecifier.text:void 0}if(w.isExportDeclaration(e))return!(e.isTypeOnly||!r&&tr(e.exportClause))&&e.moduleSpecifier!==void 0&&w.isStringLiteral(e.moduleSpecifier)?e.moduleSpecifier.text:void 0},Lo=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},No=(e,r)=>{const t=w.createSourceFile(e,E(e,"utf8"),w.ScriptTarget.Latest,!1),n=[],o=[],s=i=>{const a=Lo(i),c=a??Oo(i,r);c?.startsWith(".")||c?.startsWith("#")?o.push(c):a!==void 0&&Ro(a)&&n.push(a),w.forEachChild(i,s)};return s(t),{dynamicPackages:n,relative:o}},xo=(e,r)=>{for(let t=e;;t=R(t)){if(b(v(t,"node_modules",r,"package.json")))return!0;if(R(t)===t)return!1}},Fo=(e,r,t)=>{const n=jo(e),o=new Set,s=new Set,i=r!==void 0&&b(I(e,r))?[I(e,r)]:Do(e,t);for(let a=i.shift();a!==void 0;a=i.shift())if(!o.has(a)&&!Po(L(e,a))){o.add(a);const{dynamicPackages:c,relative:l}=No(a,n);if(!Co(L(e,a)))for(const d of c)s.add(d);i.push(...l.flatMap(d=>{if(!d.startsWith("#"))return rr(a,d)??[];const u=_o(e,d);return u===void 0?[]:rr(v(e,"package.json"),u)??[]}))}return[...s].filter(a=>xo(e,To(a))).toSorted((a,c)=>a.localeCompare(c))},Mo=18787,nr=3,$e=12e4,Lr=5e3,W=10,Nr=new Set([".js",".mjs",".mts",".ts",".tsx"]),Uo=/\(void 0\)|is not a function|before initialization|of undefined/u,Bo=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",Wo=e=>{const r=O(e),t=new Map;let n;try{n=K(v(e,r),{recursive:!0,encoding:"utf8"})}catch{return t}for(const o of n){const s=yt(o);Nr.has(s)&&!o.split(x).some(i=>i==="_generated"||i==="node_modules")&&t.set(zn(o.slice(0,-s.length).split(x).join("/")),v(r,o))}return t},or=e=>Uo.test(e)?`
|
|
5
|
+
hint: if this module is part of a circular import, an import it reads is still undefined while it evaluates`:"",qo=(e,r)=>{const t=Wo(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}${or(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}${or(i)}`),...o]},te=e=>{for(const r of Nr)for(const t of[`${e}${r}`,v(e,`index${r}`)])if(b(t))return t},Ho=(e,r)=>{const t=v(e,r,"_generated"),n=a=>{try{return E(v(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(x).join("/")})};return o.includes('import("./queues.js")')&&i("queue",te(v(t,"queues"))),n("workflows.ts").includes('import("../workflows.js")')&&i("workflow",te(v(e,r,"workflows"))),(n("agents.ts").includes('import("../agents.js")')||o.includes('import("../agents.js")'))&&i("agent",te(v(e,r,"agents"))),s},Go=/\.[cm]?js$/u,Vo=(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},Ko=(e,r,t)=>{const n=v(e,r,"_generated"),o=new Set(t.map(a=>a.file)),s=[];let i;try{i=K(n).filter(a=>a.endsWith(".ts")&&a!=="functions.ts")}catch{return s}for(const a of i.toSorted((c,l)=>c.localeCompare(l)))for(const c of Vo(v(n,a),E(v(n,a),"utf8"))){const l=c.startsWith("."),d=l?te(I(n,c.replace(Go,""))):c;d!==void 0&&!o.has(d)&&(o.add(d),s.push({file:d,kind:"module",label:l?L(e,d).split(x).join("/"):c}))}return s};class D extends Error{skipped;constructor(r,t=!1){super(r),this.skipped=t}}const sr=/^[$_\p{ID_Start}][$\u200C\u200D\p{ID_Continue}]*$/u,xr=(e,r,t)=>{const n=t??j(e),o=n===void 0?void 0:_(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"&&sr.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")&&sr.test(u)?[u]:[]),l=s.assets?.directory;return{assetsDirectory:l===void 0||n===void 0?void 0:I(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")])]}},zo=({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}=xr(t,n,r),u=e??l,f=r??j(t);let g;if(f!==void 0&&Oe(f)!==void 0)g={stubs:{durableObjects:i,entrypoints:a,workflows:d}};else if(typeof u=="string"&&!u.startsWith("virtual:")&&b(I(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 p=Kt(t,process.env,n,r);return p.length>0?{skip:`the Hyperdrive binding ${p.join(", ")} has no local database for wrangler dev`}:{base:g,configFile:f,missingAssets:h}},Jo=/The Workers runtime failed to start|Build failed with \d+ error/u,Yo=/\[ERROR\]|Uncaught/u,ir=e=>{const r=e.map(o=>bn(o).trim()).filter(o=>o!==""),t=r.filter(o=>Yo.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
|
|
8
|
-
Fix the entry, or pass --no-smoke-load to ship anyway.`):d instanceof Error&&d.name==="TimeoutError"?new
|
|
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
|
|
10
|
-
`)},
|
|
11
|
-
`))},
|
|
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 D(`the smoke Worker's runtime did not start, so nothing was evaluated:${ir(t)}
|
|
8
|
+
Fix the entry, or pass --no-smoke-load to ship anyway.`):d instanceof Error&&d.name==="TimeoutError"?new D(n===void 0?`the smoke Worker accepted the connection but answered no request within ${String($e/1e3)}s, so its runtime did not start:${ir(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 D(`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}},Ne=(e,r)=>{const t=e.headers.get("content-type")??"no content type",n=r.replaceAll(/\s+/gu," ").trim().slice(0,120);return new D(`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.`)},Fr=(e,r)=>typeof e=="string"&&e!==r,Se=Symbol("another run's Worker"),ar=async(e,r)=>{const t=await Le(e),n=t.body?.message;if(Fr(t.body?.run,r))return Se;if(t.body?.run!==r||n!==void 0&&typeof n!="string")throw Ne(t.response,t.text);return n},Xo=async(e,r)=>{const t=await Le({...e,pending:"the lazy function modules",query:"step=functions"}),{checked:n,failures:o}=t.body??{};if(!Fr(t.body?.run,r)){if(t.body?.run!==r||typeof n!="number"||!Array.isArray(o)||!o.every(s=>Bo(s)))throw Ne(t.response,t.text);return{checked:n,failures:o}}},Qo=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 Ne(i.response,i.text);if(i.body.run!==o)return;let a=0,c=[];if(t){const d=await Xo(s,o);if(d===void 0)return;a=d.checked,c=d.failures}for(const[d,u]of r.entries()){const f=await ar({...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 ar({...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{}},cr=e=>{try{return process.kill(-e,0),!0}catch{return!1}},Mr=e=>({args:["/pid",String(e),"/T","/F"],command:v(process.env.SystemRoot??String.raw`C:\Windows`,"System32","taskkill.exe")}),Ur=e=>e.error===void 0&&e.status===0,Br=(e,r)=>{const t=String(e),o=r.error===void 0&&r.status===128?`the root process ${t} has already exited, so a process it started may still hold the smoke server's port; find that port's owner with netstat -ano and end its PID with taskkill /PID <pid> /T /F`:`end it with taskkill /PID ${t} /T /F`,s=r.error===void 0?`taskkill exited with status ${String(r.status)}`:r.error.stack??r.error.message;process.stderr.write(`lunora: the smoke process tree ${t} may still be running; ${o} (${s.replaceAll(/\r?\n/gu,String.raw`\n`)})
|
|
10
|
+
`)},Zo=e=>{const{args:r,command:t}=Mr(e),n=yn(t,r,{stdio:"ignore",timeout:Lr});Ur(n)||Br(e,n)},es=e=>{const r=()=>{if(process.platform==="win32"){Zo(e);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},rs=e=>new Promise(r=>{const{args:t,command:n}=Mr(e),o=Tr(n,t,{stdio:"ignore",windowsHide:!0});o.once("error",s=>{r({error:s})}),o.once("exit",s=>{const i={status:s};r(Ur(i)?void 0:i)})}),ie=async e=>{if(e===void 0)return;e.dispose();const{pid:r}=e;if(process.platform==="win32"){const n=await rs(r);n!==void 0&&Br(r,n);return}Ee(r,"SIGTERM");const t=Date.now()+Lr;for(;cr(r)&&Date.now()<t;)await kn(50);cr(r)&&Ee(r,"SIGKILL")},ts=(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(", "),ns=async(e,r)=>{if(process.platform==="win32"){try{await ie(r)}finally{await e.stop()}return}try{await e.stop()}finally{await ie(r)}},os=e=>St(e).catch(async r=>{if(!await Et(e.port))throw r}),ss=({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 "),is=(e,r,t)=>{const{checked:n,deferredChecked:o,failures:s,integrations:i}=r;if(s.length===0&&i.failures.length===0){t.success(`${ss(r)} evaluate cleanly`);return}const a=qo(e,s),c=a.length>W?[` …and ${String(a.length-W)} more module(s)`]:[];throw new D([...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(`
|
|
11
|
+
`))},as=(e,r,t)=>{if(e instanceof D&&!e.skipped)return t.error(e.message),e.message;if(e instanceof D){t.warn(`smoke-load skipped: ${e.message}`);return}const n=r.slice(-5).join(`
|
|
12
12
|
`),o=`the smoke Worker did not start (${e instanceof Error?e.message:String(e)})${n===""?"":`
|
|
13
|
-
${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},
|
|
14
|
-
`)},
|
|
15
|
-
`),
|
|
13
|
+
${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},cs=e=>{try{return Re(v(e,".lunora"),{recursive:!0}),vt(v(e,".lunora","smoke-"))}catch(r){throw new D(`could not create a directory for the check (${r instanceof Error?r.message:String(r)})`,!0)}},ds=(e,r)=>{if("main"in r)return`export * from ${V(I(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(`
|
|
14
|
+
`)},ls=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=v(s,"entry.ts"),g=Cr();l&&Re(v(s,"assets"),{recursive:!0});const h=c.map(T=>` [${V(T)}, () => import(${V(T)})],`).join(`
|
|
15
|
+
`),p="stubs"in r&&r.stubs.entrypoints.includes("default");X(f,`${ds(n,r)}
|
|
16
16
|
${a===void 0?"":`import { loadAllFunctions } from ${V(a)};
|
|
17
17
|
`}
|
|
18
18
|
const runId = ${JSON.stringify(g)};
|
|
@@ -55,10 +55,10 @@ const smokeProbe = {
|
|
|
55
55
|
},
|
|
56
56
|
};
|
|
57
57
|
|
|
58
|
-
${
|
|
58
|
+
${p?`export default class extends WorkerEntrypoint {
|
|
59
59
|
fetch(request: Request) {
|
|
60
60
|
return smokeProbe.fetch(request);
|
|
61
61
|
}
|
|
62
62
|
}`:"export default smokeProbe;"}
|
|
63
|
-
`);const m=await $n(d),{args:$,command:C}=z(F(n),u.dev({configPath:t===void 0?void 0:L(n,t),environment:i,extraArgs:[L(n,f),"--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:C,port:m,runId:g}}catch(f){throw new j(`could not prepare the check (${f instanceof Error?f.message:String(f)})`,!0)}},ls=async e=>{const{composedEntry:r,cwd:t,environment:n,launcher:o,logger:s,toolchain:i}=e,a=O(t),c=p(t,a,"_generated","functions.ts"),l=b(c)&&E(c,"utf8").includes("export const loadAllFunctions"),d=l?c:void 0,u=Ho(t,a),f=[...u,...Vo(t,a,u)],g=xo(t,r??xr(t,n,e.configPath).main,a);if(!l&&f.length===0&&g.length===0)return;const h=Ko(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 He=Date.now()+$e,gt=process.platform!=="win32",ht=(U,Q,Z)=>{const B=Tr(U,[...Q],{cwd:Z.cwd,detached:gt,shell:Z.shell,stdio:["ignore","pipe","pipe"]});return B.pid!==void 0&&(M={dispose:Zo(B.pid),pid:B.pid}),B};try{T=as(t),s.info(`smoke-loading ${rs(d!==void 0,f.length,g.length)} in workerd`);let U=Fo;for(let Q=0;Q<nr;Q+=1){const{args:Z,command:B,port:me,runId:mt}=await ds({base:v,configPath:m,cwd:t,deferred:f,directory:T,environment:n,functionsFile:d,integrationModules:g,missingAssets:$,preferred:U,toolchain:i}),qe=new AbortController;U=me+1;const Ge=await ns({args:Z,command:B,cwd:t,spawn:o??ht,label:"wrangler dev (smoke-load)",notFound:"`wrangler` was not found",onLine:G=>{C.push(G),zo.test(G)&&qe.abort()},port:me,readyTimeoutMs:Math.max(0,He-Date.now()),shell:process.platform==="win32"});if(Ge===void 0){await ie(M),M=void 0;continue}try{const G=await Xo({deadline:He,deferred:f,functions:d!==void 0,integrationModules:g,output:C,port:me,runId:mt,startupFailed:qe.signal});if(G!==void 0){ss(t,G,s);return}}finally{await ts(Ge,M),M=void 0}}throw new j(`the smoke port was answered by other runs on all ${String(nr)} attempts`,!0)}catch(U){return is(U,C,s)}finally{if(await ie(M),T!==void 0)try{oe(T,{force:!0,recursive:!0})}catch{}}},us=(e,r)=>r===void 0?e:_(e,r),fs=async e=>{if(e.targets.length===0)return{builtTags:[],code:0};if(!(e.railpackAvailable??En)()){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=Sn(n.exportName),s={args:["build",n.buildDir,"--name",o],command:"railpack",cwd:e.cwd},i=je(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}},gs=new Set(["0.0.0.0","[::1]","[::]","localhost"]),hs=[".local",".localhost"],ms=["[fc","[fd"],ps=/^\[fe[89ab][0-9a-f]:/u,vs=/^[a-z]+:\/\//u,dr=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},lr="[::ffff:",ys=e=>{if(!e.startsWith(lr)||!e.endsWith("]"))return;const r=e.slice(lr.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(".")},Wr=e=>{let r=e.length;for(;r>0&&e[r-1]===".";)r-=1;return e.slice(0,r).toLowerCase()},ws=e=>{const r=e.toLowerCase(),t=ys(r);return t!==void 0?dr(t):gs.has(r)||hs.some(n=>r.endsWith(n))||ms.some(n=>r.startsWith(n))||ps.test(r)||dr(r)},Hr=e=>{const r=D(e);return r===void 0?void 0:I(r).parsed},qr=(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)},ks=e=>{const r=e.replace(vs,""),t=r.indexOf("/"),n=(t===-1?r:r.slice(0,t)).toLowerCase(),o=t===-1?"":ae(r.slice(t),"*");return o==="/"?n:`${n}${o}`},ur=e=>[e?.route,...Array.isArray(e?.routes)?e.routes:[]].flatMap(t=>{const n=typeof t=="string"?t:t?.pattern;return typeof n=="string"&&n!==""?[ks(n)]:[]}),bs=(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},$s=e=>e!==void 0&&(Object.hasOwn(e,"route")||Object.hasOwn(e,"routes")),Gr=(e,r)=>{const t=ur(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:$s(i)?ur(i):t}});return[{id:"top",label:"production",routes:t},...o]},Ss=(e,r,t,n)=>{const o=r===void 0?"top":`env:${r}`,s=Gr(e,r).flatMap(c=>c.routes.flatMap(l=>{const d=bs(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=>nn(`${e.origin}${e.pathname}`),Es=(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}`},Vr=(e,r,t,n,o,s)=>{const i=Ss(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=Gr(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}`},As=(e,r,t,n,o,s)=>{const i=Hr(e);if(t.endsWith(".workers.dev")){const a=qr(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 Vr(i,r,t,n,o,s)},Rs=(e,r,t,n,o)=>{const s=Hr(e),i=Wr(t.hostname);if(i.endsWith(".workers.dev")){const a=qr(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 Vr(s,r,i,t.pathname,n,o)},Ts=(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=Wr(n.hostname);if(ws(i))return`${o}: it is a local or private address, not the worker this deploy ships to`;const a=Es(e,r,n,o,s);return a===void 0?As(e,r,i,n.pathname,o,s):a??Rs(e,r,n,o,s)},Kr=e=>{const t=[D(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")}},Cs=(e,r=Cr())=>_(e,".lunora",`vite-bundle-meta-${r}.json`),zr="LUNORA_CLIENT_BUILD",Jr="virtual:lunora/worker",Ae=(e,r)=>["ts","mts","cts","js","mjs","cjs"].some(t=>b(p(e,`${r}.config.${t}`))),Yr=e=>Ae(e,"rsbuild")?"rsbuild":Ae(e,"vite")?"vite":void 0,Ps=e=>Ae(e,"vite")?"vite":Yr(e),_s=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[zr]==="1")return;const t=D(e),n=t===void 0?void 0:I(t).parsed,o=n?.main===Jr,s=(o?Ps(e):Yr(e))??(_s(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||At(e).class!=="C"||a!==void 0?s:void 0},Is=async(e,r,t)=>{const n=t.spawner??q,o=F(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=Kr(e),a=t.bundleMetaPath??Cs(e);oe(p(e,Rt),{force:!0});try{const c=await n({args:s.args,command:s.command,cwd:e,env:{[It]:jt(e),[_t]:t.target,[Pt]:a,...t.lazyFunctions?{[Ct]:"1"}:{},...t.environment===void 0?{}:{CLOUDFLARE_ENV:t.environment},...t.strictAdvisories===!1?{[Tt]:"0"}:{},[zr]:"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})}},xe=(e,r,t)=>r!==!1&&ge(e,t)!==void 0,js=(e,r,t)=>{const n=r===!1?void 0:ge(e,t);if(n===void 0||n==="script")return!1;const o=D(e);return o!==void 0&&I(o).parsed?.main===Jr||wr(e)!==void 0},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`},Xr=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 Is(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})},fr=e=>Array.isArray(e)?e.filter(r=>r!=null):void 0,Me=(e,r,t=D(e))=>{if(!t)return;const{parsed:n}=I(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:fr(a),d1_databases:fr(c),vars:typeof l=="object"&&l!==null&&!Array.isArray(l)?l:void 0}},Ds=/^127(?:\.\d{1,3}){3}$/,Os=e=>{try{const{hostname:r}=new URL(e);return r==="localhost"||Ds.test(r)||r==="::1"||r==="[::1]"}catch{return!1}},Ls=e=>e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.includes("Dockerfile"),Ns=(e,r,t,n="deploy",o)=>{const s=(Me(e,o)?.containers??[]).filter(a=>typeof a?.image=="string"&&Ls(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,xs=(e,r,t="deploy",n)=>{for(const o of kr(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}}},Fs=(e,r)=>r==="celld"?typeof e=="string"&&e!==Ke&&ln(e):r==="cloudflare"&&e===Ke,Ms=(e,r,t,n)=>(Me(e,t,n)?.d1_databases??[]).find(o=>Fs(o.database_id,r)),Us=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=Ms(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},Bs=(e,r,t="deploy",n)=>{const o=Me(e,n)?.vars;if(!o)return;const s=Object.entries(o).filter(([,a])=>typeof a=="string"&&Os(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},Ws=["vite.config.ts","vite.config.mts","vite.config.cts","vite.config.js","vite.config.mjs","vite.config.cjs",...wt],Qr=/\.(?:[cm]?[jt]s|tsx|jsx)$/u,Zr=/\.(?:test|spec)\.[cm]?[jt]sx?$/u,et="allowUnauthenticatedShardAccess",Hs=/[\\/]/u,rt=new Set(["_generated","build","dist","node_modules"]),tt=(e,r)=>{const t=J(e,r).split(Hs);return Qr.test(r)&&!Zr.test(r)&&!we(t.join("/"))&&t.every(n=>n===".."||!n.startsWith(".")&&!rt.has(n))},gr=(e,r,t)=>{const{parsed:n}=I(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(jr(r),i):void 0;return a!==void 0&&b(a)&&tt(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,qs=e=>{try{return Te(e).isFile()}catch{return!1}},Gs=new Set(["ELOOP","ENOENT","ENOTDIR"]),ce=(e,r,t)=>{const n=r instanceof Error&&"code"in r&&typeof r.code=="string"?r.code:"";Gs.has(n)||t.push(e)},Vs=(e,r)=>{try{return Te(e)}catch(t){ce(e,t,r);return}},nt=(e,r)=>{try{return E(e,"utf8")}catch(t){ce(e,t,r);return}},ot=(e,r,t,n=new Set)=>{let o;try{o=vt(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=Vs(a,t);if(c===void 0)return[];const l=J(e,a).split(x).join("/");return c.isDirectory()?rt.has(i)||i.startsWith(".")||we(`${l}/`)?[]:ot(e,a,t,n):c.isFile()&&Qr.test(i)&&!Zr.test(i)&&!we(l)?[a]:[]})},Ks=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"],zs=/\.(?:[cm]?js|jsx)$/u,Js=(e,r)=>{if(!r.startsWith("."))return;const t=_(jr(e),r),n=t.replace(zs,"");return[t,...ve.map(s=>`${t}${s}`),...ve.map(s=>A(t,`index${s}`)),...ve.map(s=>`${n}${s}`)].find(s=>qs(s))},Ys=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},Xs=e=>{const r=e.getModuleReference();if(!S.isExternalModuleReference(r))return;const t=r.getExpression();return S.isStringLiteral(t)?t.getLiteralValue():void 0},Qs=(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=nt(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=>Xs(f)),...d.getDescendantsOfKind(k.CallExpression).map(f=>Ys(f))].filter(f=>f!==void 0);for(const f of u){const g=Js(c,f);g!==void 0&&tt(t,g)&&!o.has(g)&&(o.add(g),i.push(g),s.push(g))}}return i},Zs=e=>{const r=e.getArgumentExpression();return r!==void 0&&(S.isStringLiteral(r)||S.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():void 0},ei=e=>S.isPropertyAccessExpression(e)?e.getName():S.isElementAccessExpression(e)?Zs(e):void 0,ri=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]),ti=e=>{const r=e.getOperatorToken().getKind();return!ri.has(r)||ei(e.getLeft())!==et?!1:r!==k.EqualsToken||!We(e.getRight())},ni=(e,r,t)=>{const n=[],o=[...new Set([O(e),"src"])].filter(u=>b(A(e,u))),s=D(e),i=[...Ws.map(u=>A(e,u)).filter(u=>b(u)),...s===void 0?[]:gr(e,s,r),...t.flatMap(u=>gr(e,u,r))],a=new Pr({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}),c=o.flatMap(u=>ot(A(e,u),A(e,u),n));return{sites:[...new Set([...c,...i,...Qs([...i,...c],a,e,n)])].flatMap(u=>{const f=nt(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 Ks(m.getNameNode())===et&&!$}).map(m=>m.getStartLineNumber()),v=g.getDescendantsOfKind(k.BinaryExpression).filter(m=>ti(m)).map(m=>m.getStartLineNumber());return[...h,...v].map(m=>({file:J(e,u),line:m}))}),unreadable:n}},oi=(e,r,t,n,o,s)=>{if(t!=="deploy")return;const{sites:i,unreadable:a}=ni(e,o,s),c=jn({openShardAccess:i,schema:{tables:[]}},{lints:[ze]});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(" ")} ${ze.remediation}`;return r.error(d),d},si=(e,r,t,n)=>{const o=oi(e,r.logger,t,r.allowOpenShards===!0,r.env,n);return o===void 0?void 0:{code:y.USAGE,error:o}},ii=(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=Bs(e,r.logger,t,r.env);if(s!==void 0)return{code:y.USAGE,error:s};const i=xs(e,r.logger,t,r.discoveryCache);if(i!==void 0)return{code:y.USAGE,error:i};const a=Ns(e,r.logger,r.dockerAvailable??An,t,r.env);return a===void 0?void 0:{code:y.MISSING_DEPENDENCY,error:a}},ai=/https?:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/u,ci=/https:\/\/[^\s"'<>]+/u,di=e=>{if(e===void 0)return;const r=ai.exec(e);return r?r[0]:ci.exec(e)?.[0]},hr=e=>e===void 0?"":` (--env ${e})`,li=({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)"}${hr(s.env)}, but this deploy published ${o}${hr(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()))();Dt(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{}},ui=async(e,r)=>{const t=new Pr({skipAddingFilesFromTsConfig:!0}),n=A(r,"lunora");let o;try{o=kt(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 Dn(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},fi=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=un(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 fn({cwd:r,entries:o,exec:je(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)}`)},mr=5,gi=2e3,hi=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 Rn({attempts:mr,baseUrl:n,delayMs:gi,fetchImpl:e.healthFetch,paths:[Tn,Cn],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(mr)} attempt(s) — ${o.error}`),{error:o.error,ok:!1,url:o.url})},mi=async(e,r,t,n,o,s)=>{e.isolatedPreview!==!0&&await fi(e,r);const i=e.migrate?await ui(e,r):0;return i===0&&o?.(),{code:i,descriptor:t,mintedSecretsFile:s,validation:n}},pi=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:di(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?.(),li({cwd:e,env:n.env,logger:n.logger,url:c.url}));const l=await hi(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 mi(n,e,r,a,d,t),deployment:c,healthCheck:l}},vi=(e,r,t)=>{const n=A(e,N);if(!b(n))return;let o;try{o=br(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. ${N} 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. ${N} 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.`)},st=async(e,r)=>{let t=[];try{t=Ot(await $r({cache:r,projectRoot:e,schemaDir:O(e)}))}catch{}const n=[...new Set(Lt(t).map(s=>s.key))];let o=[];try{const s=A(e,N);b(s)&&(o=br(E(s,"utf8")).map(i=>i.key).filter(i=>Rr(i)))}catch{}return{fromLocal:o.filter(s=>!n.includes(s)),fromPackages:n,mintableKeys:Nt(t)}},yi=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:xt()})),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}},wi=/^[\w-]+$/u,pr=[".dev.vars",".dev.vars.*","!.dev.vars.example"],ki=(e,r)=>{try{const t=Bt(e,pr);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 \`${pr.join("` and `")}\` by hand before committing.`)}},bi=(e,r,t)=>{if(t.length===0)return;const n=t.map(a=>a.key).join(", ");if(r.env!==void 0&&!wi.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?N:`${N}.${r.env}`;ki(e,r.logger);const s=A(e,o);let i=b(s)?E(s,"utf8"):"";for(const a of t)i=Ft(i,a.key,a.value);return Mt(s,i),r.logger.success(r.env===void 0?`${n}: value(s) recorded in ${o}`:`${n}: value(s) recorded in ${o} (kept separate from ${N} so \`lunora dev\` and a plain \`lunora env push\` don't inherit the --env ${r.env} value)`),o},$i=/^<[^>]+>$/u,Si=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===""||$i.test(f)?!0:Rr(d)&&Ut(u)},s=d=>Object.hasOwn(n,d)?`${d} (empty or a placeholder)`:d,{fromLocal:i,fromPackages:a}=await st(e,r.discoveryCache),c=i.filter(d=>o(d));c.length>0&&r.logger.warn(`${N} 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.`}},Ei=async(e,r,t,n)=>{if(r.dryRun===!0||r.isolatedPreview===!0)return{};if(n.toolchain?.secretList===void 0)return Si(e,r,n);const{logger:o}=r,s=r.env===void 0?"":` --env ${r.env}`;let i;try{i=await(r.secretLister??Ln)({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 st(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??On())(`${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 yi(e,r,f,n),m=bi(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}\`.`),{}},it=e=>e.format==="json"?!1:e.interactive!==void 0?e.interactive:process.stdout.isTTY&&!process.env.CI,Ai=async(e,r)=>{if(r.dryRun===!0)return;const t=kr(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 fs({cwd:e,logger:r.logger,railpackAvailable:r.railpackAvailable,spawner:r.spawner,targets:t});return n.code===0?void 0:n.error??"railpack build failed"},Ri=(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=en(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}`)}},Ti=async(e,r,t,n,o,s,i=!1)=>{try{le(n);const a=await $r({cache:s,projectRoot:e,schemaDir:O(e),skipCompanion:i}),c=Xt(e,a,{environment:o,target:n}),l=c.wranglerPath??"wrangler.jsonc";if(c.added.length>0&&r.success(`provisioned bindings: ${c.added.join(", ")} → ${l}`),c.updated.length>0&&r.success(`updated bindings: ${c.updated.join(", ")} → ${l}`),c.devConfig!==void 0){const{added:d,path:u,updated:f}=c.devConfig;r.success(`dev sidecar bindings: ${[...d,...f].join(", ")} → ${u}`)}for(const d of c.warnings)r.warn(d)}catch(a){const c=a instanceof Error?a.message:String(a);r.warn(`binding inference skipped: ${c}`)}try{const a=Qt(e);a.changed&&r.success(`bumped compatibility_date to ${a.date??"unknown"} (Workers Cache enabled) → ${a.wranglerPath??"wrangler.jsonc"}`)}catch(a){const c=a instanceof Error?a.message:String(a);r.warn(`compatibility date sync skipped: ${c}`)}Ri(e,r,t)},Ci=async(e,r,t,n,o,s,i,a,c,l)=>{let d;r?(d=new rn({name:"dots"}),d.start("running codegen")):t.info("running codegen");try{const u=$t({apiSpec:n,dryRun:!l,lazyFunctions:o,projectRoot:e,target:s,...Yt(e)});d?.succeed("codegen complete"),d||t.success("codegen complete");const f=an(u.platformDiagnostics,t);if(f.errors.length>0)return{error:f.errors.join("; ")};const{errorAdvisories:g,names:h,shouldBlock:v}=cn(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 Vt({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}`}}},vr="--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`.",Pi=(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}),at=(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=Pi(e,r);return Sr(t,e,"deploy",s=>n.deploy({...o,configPath:s}))},_i=(e,r,t)=>{const n=at(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},P={problems:[],wranglerPath:void 0},ye=(e,r)=>({code:y.USAGE,descriptor:void 0,error:e,validation:P,...r}),Ii=(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},ji=(e,r,t)=>{const n=r.format==="json",o=r.dryRun!==!0,s=_i(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"},Di=(e,r)=>he(r)===void 0?bt(e).services.map(t=>t.wranglerPath):[],ct=(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:_e(r),target:t.id}),Oi=(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},dt=(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}`}},Li=(e,r,t)=>{const{error:n,services:o}=yr(e,O(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 dt(a,c=>ct(c,r,s,i,q))},lt=(e,r,t)=>{const n=e.cwd??process.cwd(),o=vn(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:P}}if(e.preview===!0)return e.logger.error(vr),{kind:"refused",code:y.USAGE,error:vr,validation:P};try{at(n,e,le(o.target))}catch(a){if(!(t&&a instanceof Wt&&xe(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:P}}}const s=e.openShardGatePassed===!0?void 0:si(n,e,r,Di(n,e));if(s!==void 0)return{kind:"refused",code:s.code,error:s.error,validation:P};const i=Li(n,e,o.target);return i!==void 0?(e.logger.error(i),{kind:"refused",code:y.USAGE,error:i,validation:P}):{kind:"ok",target:o.target}},Ni=(e,r)=>e.apiSpec??(e.clientBuildRan===!0?wr(r):void 0),xi=async(e,r,t)=>{if(r!=="celld")return;const n=await(e.celldToolchain??Gt)({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},ut=(e,r)=>{const t=De({cwd:e,env:r.env,url:r.migrateUrl}),n=t===void 0?void 0:Ts(e,r.env,t);if(n!==void 0)return{reason:n};const o=t===void 0?void 0:on(t,r.logger,e),s=o===void 0?void 0:tn({cwd:e,token:r.migrateToken,url:o}).token;return{target:o===void 0||!s?void 0:{baseUrl:o,fetchImpl:r.fetchImpl??sn,token:s}}},Fi=(e,r,t)=>async n=>{const o=ut(e,r);return"reason"in o?{kind:"inconclusive",reason:o.reason}:In({changes:n,tables:t.schemaTables,target:o.target})},Mi=(e,r)=>async t=>{const n=ut(e,r);return"reason"in n?n.reason:_n({changes:t,now:Date.now(),target:n.target})},Ui=(e,r,t,n)=>e==="deploy"?{checkStoredRows:Fi(r,t,n),countExpiringRows:Mi(r,t)}:{},Bi=async(e,r)=>{const t=e.cwd??process.cwd(),n=it(e),o=_e(e),s={problems:[],wranglerPath:void 0},i=lt(e,r,!1);if(i.kind==="refused")return{code:i.code,error:i.error,validation:i.validation};const{target:a}=i,c=await xi(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 Ci(t,n,e.logger,Ni(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:P};l=v.result,e.discoveryCache?.clear()}let d;if(l!==void 0){const v=await Pn({allowDrift:e.allowSchemaDrift===!0,...Ui(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&&Wn({current:l.architecture,cwd:t,environment:e.env,logger:e.logger});await Ti(t,e.logger,l?.cronTriggers,a,e.env,e.discoveryCache,he(e)!==void 0);const f=await H(t,e,r,a,"check");if(f!==void 0)return{error:f,target:a,validation:P};const g=ii(t,e,r,a);if(g!==void 0)return{code:g.code,error:g.error,target:a,validation:P};const h=Jt({environment:e.env,projectRoot:t});return Ii(h,e.logger)?{error:"wrangler validation failed",target:a,validation:h}:{codegen:l,reblessSchemaBaseline:d,recordArchitecture:u,target:a,validation:h}},Wi=e=>{oe(p(e,".wrangler","deploy","config.json"),{force:!0})},Hi=async(e,r,t)=>{const n=Fe(e);if(n!==void 0)return{built:!1,error:n};const o=xe(e.cwd,r,t);return o&&Wi(e.cwd),{built:o,error:await Xr(e)}},qi=(e,r,t)=>r||t===!1?Oe(e):void 0,Gi=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)},Vi=(e,r,t)=>e.map((n,o)=>{const s=r[o]===!0,i=qi(n.wranglerPath,s,t);return{built:s,config:i??n.wranglerPath,resolved:i!==void 0,service:n}}),Ki=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&&So(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}`}},zi=async(e,r,t)=>{for(const n of e){const o=await Ki(n,r,t);if(o!==void 0)return o}},Ji=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}`}},Yi=async(e,r,t,n,o)=>{const s=[];for(const i of e){const{built:a,error:c}=await Hi(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}},Xi=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=Sr(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`}},Qi=async(e,r,t,n)=>{const{error:o,services:s}=yr(e,O(e));if(o!==void 0)return{code:y.FAILURE,error:o};if(s.length===0)return;const i=Oi(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=$=>ct($,r,t,l,n),u=dt(c,d);if(u!==void 0)return r.logger.error(u),{code:y.USAGE,error:u};for(const $ of c){const C=await Gi($.wranglerPath,r,t);if(C!==void 0)return{code:y.USAGE,error:`service ${$.name} (${$.worker}): ${C}`}}const{builds:f,failure:g}=await Yi(c,d,l,r.env,r.logger);if(g!==void 0)return g;const h=Vi(c,f,l),v=await zi(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 Ji($,r,t);if(C!==void 0)return C;const T=await Xi($,m);if(T!==void 0)return T}},Zi=async(e,r,t,n)=>{if(r!=="cloudflare")return;const o=e===void 0?void 0:I(e).parsed,s=(t===void 0?void 0:o?.env?.[t]?.account_id)??o?.account_id,i=await hn({accountId:s});(i.verdict==="near"||i.verdict==="full")&&n.warn(i.fix===void 0?i.message:`${i.message} ${i.fix}`)},ea=e=>e.dryRun!==!0&&e.temporary!==!0,ra=e=>e.temporary===!0?"temporary":e.dryRun===!0?"preview":"defer",ta=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},na=(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=ta(o);r.error(s),n.push(s)}return n},ft=async(e,r,t,n,o,s,i)=>{const a=t==="cloudflare"&&r!==void 0?I(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,O(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=>gn({...h,accountId:u,create:i==="create",jurisdiction:l,missingOk:i==="defer"||i==="preview"}))),g=na(f,o,i);return g.length===0?void 0:g.join(`
|
|
64
|
-
`)},
|
|
63
|
+
`);const m=await $n(d),{args:$,command:C}=z(F(n),u.dev({configPath:t===void 0?void 0:L(n,t),environment:i,extraArgs:[L(n,f),"--local","--local-protocol","http","--ip","127.0.0.1","--port",String(m),"--persist-to",L(n,v(s,"state")),...l?["--assets",L(n,v(s,"assets"))]:[]]}));return{args:$,command:C,port:m,runId:g}}catch(f){throw new D(`could not prepare the check (${f instanceof Error?f.message:String(f)})`,!0)}},us=async e=>{const{composedEntry:r,cwd:t,environment:n,launcher:o,logger:s,toolchain:i}=e,a=O(t),c=v(t,a,"_generated","functions.ts"),l=b(c)&&E(c,"utf8").includes("export const loadAllFunctions"),d=l?c:void 0,u=Ho(t,a),f=[...u,...Ko(t,a,u)],g=Fo(t,r??xr(t,n,e.configPath).main,a);if(!l&&f.length===0&&g.length===0)return;const h=zo(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:p,configFile:m,missingAssets:$}=h,C=[];let T,M;const qe=Date.now()+$e,gt=process.platform!=="win32",ht=(U,Q,Z)=>{const B=Tr(U,[...Q],{cwd:Z.cwd,detached:gt,shell:Z.shell,stdio:["ignore","pipe","pipe"]});return B.pid!==void 0&&(M={dispose:es(B.pid),pid:B.pid}),B};try{T=cs(t),s.info(`smoke-loading ${ts(d!==void 0,f.length,g.length)} in workerd`);let U=Mo;for(let Q=0;Q<nr;Q+=1){const{args:Z,command:B,port:me,runId:mt}=await ls({base:p,configPath:m,cwd:t,deferred:f,directory:T,environment:n,functionsFile:d,integrationModules:g,missingAssets:$,preferred:U,toolchain:i}),He=new AbortController;U=me+1;const Ge=await os({args:Z,command:B,cwd:t,spawn:o??ht,label:"wrangler dev (smoke-load)",notFound:"`wrangler` was not found",onLine:G=>{C.push(G),Jo.test(G)&&He.abort()},port:me,readyTimeoutMs:Math.max(0,qe-Date.now()),shell:process.platform==="win32"});if(Ge===void 0){await ie(M),M=void 0;continue}try{const G=await Qo({deadline:qe,deferred:f,functions:d!==void 0,integrationModules:g,output:C,port:me,runId:mt,startupFailed:He.signal});if(G!==void 0){is(t,G,s);return}}finally{await ns(Ge,M),M=void 0}}throw new D(`the smoke port was answered by other runs on all ${String(nr)} attempts`,!0)}catch(U){return as(U,C,s)}finally{if(await ie(M),T!==void 0)try{oe(T,{force:!0,recursive:!0})}catch{}}},fs=(e,r)=>r===void 0?e:I(e,r),gs=async e=>{if(e.targets.length===0)return{builtTags:[],code:0};if(!(e.railpackAvailable??En)()){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??H,t=[];for(const n of e.targets){const o=Sn(n.exportName),s={args:["build",n.buildDir,"--name",o],command:"railpack",cwd:e.cwd},i=De(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}},hs=new Set(["0.0.0.0","[::1]","[::]","localhost"]),ms=[".local",".localhost"],vs=["[fc","[fd"],ps=/^\[fe[89ab][0-9a-f]:/u,ys=/^[a-z]+:\/\//u,dr=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},lr="[::ffff:",ws=e=>{if(!e.startsWith(lr)||!e.endsWith("]"))return;const r=e.slice(lr.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(".")},Wr=e=>{let r=e.length;for(;r>0&&e[r-1]===".";)r-=1;return e.slice(0,r).toLowerCase()},ks=e=>{const r=e.toLowerCase(),t=ws(r);return t!==void 0?dr(t):hs.has(r)||ms.some(n=>r.endsWith(n))||vs.some(n=>r.startsWith(n))||ps.test(r)||dr(r)},qr=e=>{const r=j(e);return r===void 0?void 0:_(r).parsed},Hr=(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)},bs=e=>{const r=e.replace(ys,""),t=r.indexOf("/"),n=(t===-1?r:r.slice(0,t)).toLowerCase(),o=t===-1?"":ae(r.slice(t),"*");return o==="/"?n:`${n}${o}`},ur=e=>[e?.route,...Array.isArray(e?.routes)?e.routes:[]].flatMap(t=>{const n=typeof t=="string"?t:t?.pattern;return typeof n=="string"&&n!==""?[bs(n)]:[]}),$s=(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},Ss=e=>e!==void 0&&(Object.hasOwn(e,"route")||Object.hasOwn(e,"routes")),Gr=(e,r)=>{const t=ur(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:Ss(i)?ur(i):t}});return[{id:"top",label:"production",routes:t},...o]},Es=(e,r,t,n)=>{const o=r===void 0?"top":`env:${r}`,s=Gr(e,r).flatMap(c=>c.routes.flatMap(l=>{const d=$s(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=>nn(`${e.origin}${e.pathname}`),As=(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}`},Vr=(e,r,t,n,o,s)=>{const i=Es(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=Gr(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}`},Rs=(e,r,t,n,o,s)=>{const i=qr(e);if(t.endsWith(".workers.dev")){const a=Hr(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 Vr(i,r,t,n,o,s)},Ts=(e,r,t,n,o)=>{const s=qr(e),i=Wr(t.hostname);if(i.endsWith(".workers.dev")){const a=Hr(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 Vr(s,r,i,t.pathname,n,o)},Cs=(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=Wr(n.hostname);if(ks(i))return`${o}: it is a local or private address, not the worker this deploy ships to`;const a=As(e,r,n,o,s);return a===void 0?Rs(e,r,i,n.pathname,o,s):a??Ts(e,r,n,o,s)},Kr=e=>{const t=[j(e),v(e,"package.json"),v(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")}},Ps=(e,r=Cr())=>I(e,".lunora",`vite-bundle-meta-${r}.json`),zr="LUNORA_CLIENT_BUILD",Jr="virtual:lunora/worker",Ae=(e,r)=>["ts","mts","cts","js","mjs","cjs"].some(t=>b(v(e,`${r}.config.${t}`))),Yr=e=>Ae(e,"rsbuild")?"rsbuild":Ae(e,"vite")?"vite":void 0,Is=e=>Ae(e,"vite")?"vite":Yr(e),_s=e=>{try{const{scripts:r}=JSON.parse(E(v(e,"package.json"),"utf8"));return typeof r?.build=="string"&&r.build!==""}catch{return!1}},ge=(e,r)=>{if(process.env[zr]==="1")return;const t=j(e),n=t===void 0?void 0:_(t).parsed,o=n?.main===Jr,s=(o?Is(e):Yr(e))??(_s(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||At(e).class!=="C"||a!==void 0?s:void 0},Ds=async(e,r,t)=>{const n=t.spawner??H,o=F(e),s=r==="script"?{args:["run","build"],command:o}:De(o,r,["build"]);t.logger.info(`running ${r} build before bundling the Worker`);const i=Kr(e),a=t.bundleMetaPath??Ps(e);oe(v(e,Rt),{force:!0});try{const c=await n({args:s.args,command:s.command,cwd:e,env:{[_t]:Dt(e),[It]:t.target,[Pt]:a,...t.lazyFunctions?{[Ct]:"1"}:{},...t.environment===void 0?{}:{CLOUDFLARE_ENV:t.environment},...t.strictAdvisories===!1?{[Tt]:"0"}:{},[zr]:"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})}},xe=(e,r,t)=>r!==!1&&ge(e,t)!==void 0,js=(e,r,t)=>{const n=r===!1?void 0:ge(e,t);if(n===void 0||n==="script")return!1;const o=j(e);return o!==void 0&&_(o).parsed?.main===Jr||wr(e)!==void 0},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`},Xr=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 Ds(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})},fr=e=>Array.isArray(e)?e.filter(r=>r!=null):void 0,Me=(e,r,t=j(e))=>{if(!t)return;const{parsed:n}=_(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:fr(a),d1_databases:fr(c),vars:typeof l=="object"&&l!==null&&!Array.isArray(l)?l:void 0}},Os=/^127(?:\.\d{1,3}){3}$/,Ls=e=>{try{const{hostname:r}=new URL(e);return r==="localhost"||Os.test(r)||r==="::1"||r==="[::1]"}catch{return!1}},Ns=e=>e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.includes("Dockerfile"),xs=(e,r,t,n="deploy",o)=>{const s=(Me(e,o)?.containers??[]).filter(a=>typeof a?.image=="string"&&Ns(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,Fs=(e,r,t="deploy",n)=>{for(const o of kr(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}}},Ms=(e,r)=>r==="celld"?typeof e=="string"&&e!==Ke&&ln(e):r==="cloudflare"&&e===Ke,Us=(e,r,t,n)=>(Me(e,t,n)?.d1_databases??[]).find(o=>Ms(o.database_id,r)),Bs=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 SQL migrations and data migrations after deploy. Re-run with --migrate-yes to confirm the target.";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=Us(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},Ws=(e,r,t="deploy",n)=>{const o=Me(e,n)?.vars;if(!o)return;const s=Object.entries(o).filter(([,a])=>typeof a=="string"&&Ls(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},qs=["vite.config.ts","vite.config.mts","vite.config.cts","vite.config.js","vite.config.mjs","vite.config.cjs",...wt],Qr=/\.(?:[cm]?[jt]s|tsx|jsx)$/u,Zr=/\.(?:test|spec)\.[cm]?[jt]sx?$/u,et="allowUnauthenticatedShardAccess",Hs=/[\\/]/u,rt=new Set(["_generated","build","dist","node_modules"]),tt=(e,r)=>{const t=J(e,r).split(Hs);return Qr.test(r)&&!Zr.test(r)&&!we(t.join("/"))&&t.every(n=>n===".."||!n.startsWith(".")&&!rt.has(n))},gr=(e,r,t)=>{const{parsed:n}=_(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(Dr(r),i):void 0;return a!==void 0&&b(a)&&tt(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,Gs=e=>{try{return Te(e).isFile()}catch{return!1}},Vs=new Set(["ELOOP","ENOENT","ENOTDIR"]),ce=(e,r,t)=>{const n=r instanceof Error&&"code"in r&&typeof r.code=="string"?r.code:"";Vs.has(n)||t.push(e)},Ks=(e,r)=>{try{return Te(e)}catch(t){ce(e,t,r);return}},nt=(e,r)=>{try{return E(e,"utf8")}catch(t){ce(e,t,r);return}},ot=(e,r,t,n=new Set)=>{let o;try{o=pt(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=Ks(a,t);if(c===void 0)return[];const l=J(e,a).split(x).join("/");return c.isDirectory()?rt.has(i)||i.startsWith(".")||we(`${l}/`)?[]:ot(e,a,t,n):c.isFile()&&Qr.test(i)&&!Zr.test(i)&&!we(l)?[a]:[]})},zs=e=>{const r=S.isComputedPropertyName(e)?e.getExpression():e;return S.isStringLiteral(r)||S.isNoSubstitutionTemplateLiteral(r)?r.getLiteralValue():e.getText()},pe=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],Js=/\.(?:[cm]?js|jsx)$/u,Ys=(e,r)=>{if(!r.startsWith("."))return;const t=I(Dr(e),r),n=t.replace(Js,"");return[t,...pe.map(s=>`${t}${s}`),...pe.map(s=>A(t,`index${s}`)),...pe.map(s=>`${n}${s}`)].find(s=>Gs(s))},Xs=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},Qs=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=nt(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=>Qs(f)),...d.getDescendantsOfKind(k.CallExpression).map(f=>Xs(f))].filter(f=>f!==void 0);for(const f of u){const g=Ys(c,f);g!==void 0&&tt(t,g)&&!o.has(g)&&(o.add(g),i.push(g),s.push(g))}}return i},ei=e=>{const r=e.getArgumentExpression();return r!==void 0&&(S.isStringLiteral(r)||S.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():void 0},ri=e=>S.isPropertyAccessExpression(e)?e.getName():S.isElementAccessExpression(e)?ei(e):void 0,ti=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]),ni=e=>{const r=e.getOperatorToken().getKind();return!ti.has(r)||ri(e.getLeft())!==et?!1:r!==k.EqualsToken||!We(e.getRight())},oi=(e,r,t)=>{const n=[],o=[...new Set([O(e),"src"])].filter(u=>b(A(e,u))),s=j(e),i=[...qs.map(u=>A(e,u)).filter(u=>b(u)),...s===void 0?[]:gr(e,s,r),...t.flatMap(u=>gr(e,u,r))],a=new Pr({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}),c=o.flatMap(u=>ot(A(e,u),A(e,u),n));return{sites:[...new Set([...c,...i,...Zs([...i,...c],a,e,n)])].flatMap(u=>{const f=nt(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 zs(m.getNameNode())===et&&!$}).map(m=>m.getStartLineNumber()),p=g.getDescendantsOfKind(k.BinaryExpression).filter(m=>ni(m)).map(m=>m.getStartLineNumber());return[...h,...p].map(m=>({file:J(e,u),line:m}))}),unreadable:n}},si=(e,r,t,n,o,s)=>{if(t!=="deploy")return;const{sites:i,unreadable:a}=oi(e,o,s),c=Dn({openShardAccess:i,schema:{tables:[]}},{lints:[ze]});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(" ")} ${ze.remediation}`;return r.error(d),d},ii=(e,r,t,n)=>{const o=si(e,r.logger,t,r.allowOpenShards===!0,r.env,n);return o===void 0?void 0:{code:y.USAGE,error:o}},ai=(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=Ws(e,r.logger,t,r.env);if(s!==void 0)return{code:y.USAGE,error:s};const i=Fs(e,r.logger,t,r.discoveryCache);if(i!==void 0)return{code:y.USAGE,error:i};const a=xs(e,r.logger,r.dockerAvailable??An,t,r.env);return a===void 0?void 0:{code:y.MISSING_DEPENDENCY,error:a}},ci=/https?:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/u,di=/https:\/\/[^\s"'<>]+/u,li=e=>{if(e===void 0)return;const r=ci.exec(e);return r?r[0]:di.exec(e)?.[0]},hr=e=>e===void 0?"":` (--env ${e})`,ui=({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)"}${hr(s.env)}, but this deploy published ${o}${hr(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()))();jt(e,{env:r,linkedAt:i,workerName:_e(e),workerUrl:o}),t.success(`link: recorded ${o} in .lunora/project.json (run \`lunora link\` to change)`)}catch{}},fi=async(e,r)=>{const t=await On({cwd:r,fetchImpl:e.fetchImpl,logger:e.logger,allowDestructive:e.migrateAllowDestructive===!0,prod:!0,token:e.migrateToken,url:e.migrateUrl,yes:e.migrateYes===!0});return t.code!==0&&e.logger.error("--migrate: the SQL migration files failed — see output above"),t.code},gi=async(e,r)=>{const t=await fi(e,r);if(t!==0)return t;const n=new Pr({skipAddingFilesFromTsConfig:!0}),o=A(r,"lunora");let s;try{s=kt(n,o)}catch(i){const a=i instanceof Error?i.message:String(i);return e.logger.warn(`--migrate: could not discover migrations (${a}); skipping`),0}if(s.length===0)return e.logger.info("--migrate: no data migrations declared in lunora/"),0;e.logger.info(`--migrate: running ${String(s.length)} migration(s) against deployed worker`);for(const i of s){e.logger.info(`--migrate: up "${i.id}" (table "${i.table}")`);const a={cwd:r,fetchImpl:e.fetchImpl,id:i.id,logger:e.logger,prod:!0,subcommand:"up",token:e.migrateToken,url:e.migrateUrl,yes:e.migrateYes===!0},c=await jn(a);if(c.code!==0)return e.logger.error(`--migrate: migration "${i.id}" failed — see output above`),c.code;e.logger.success(`--migrate: "${i.id}" applied`)}return 0},hi=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=un(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 fn({cwd:r,entries:o,exec:De(F(r),"wrangler",[]),logger:e.logger,spawner:e.spawner??H})).filter(a=>a.status!=="failed").length;i>0&&e.logger.success(`vectorize metadata indexes ready: ${String(i)}/${String(o.length)}`)},mr=5,mi=2e3,vi=async(e,r,t)=>{if(e.healthCheck!==!0)return;const n=t??je({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 Rn({attempts:mr,baseUrl:n,delayMs:mi,fetchImpl:e.healthFetch,paths:[Tn,Cn],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(mr)} attempt(s) — ${o.error}`),{error:o.error,ok:!1,url:o.url})},pi=async(e,r,t,n,o,s)=>{e.isolatedPreview!==!0&&await hi(e,r);const i=e.migrate?await gi(e,r):0;return i===0&&o?.(),{code:i,descriptor:t,mintedSecretsFile:s,validation:n}},yi=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:li(i),workerName:_e(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?.(),ui({cwd:e,env:n.env,logger:n.logger,url:c.url}));const l=await vi(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 pi(n,e,r,a,d,t),deployment:c,healthCheck:l}},wi=(e,r,t)=>{const n=A(e,N);if(!b(n))return;let o;try{o=br(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. ${N} 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. ${N} 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.`)},st=async(e,r)=>{let t=[];try{t=Ot(await $r({cache:r,projectRoot:e,schemaDir:O(e)}))}catch{}const n=[...new Set(Lt(t).map(s=>s.key))];let o=[];try{const s=A(e,N);b(s)&&(o=br(E(s,"utf8")).map(i=>i.key).filter(i=>Rr(i)))}catch{}return{fromLocal:o.filter(s=>!n.includes(s)),fromPackages:n,mintableKeys:Nt(t)}},ki=async(e,r,t,n)=>{const{logger:o}=r,s=r.spawner??H,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:xt()})),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}),p=z(i,h),m=await s({args:p.args,command:p.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}},bi=/^[\w-]+$/u,vr=[".dev.vars",".dev.vars.*","!.dev.vars.example"],$i=(e,r)=>{try{const t=Bt(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.`)}},Si=(e,r,t)=>{if(t.length===0)return;const n=t.map(a=>a.key).join(", ");if(r.env!==void 0&&!bi.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?N:`${N}.${r.env}`;$i(e,r.logger);const s=A(e,o);let i=b(s)?E(s,"utf8"):"";for(const a of t)i=Ft(i,a.key,a.value);return Mt(s,i),r.logger.success(r.env===void 0?`${n}: value(s) recorded in ${o}`:`${n}: value(s) recorded in ${o} (kept separate from ${N} so \`lunora dev\` and a plain \`lunora env push\` don't inherit the --env ${r.env} value)`),o},Ei=/^<[^>]+>$/u,Ai=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===""||Ei.test(f)?!0:Rr(d)&&Ut(u)},s=d=>Object.hasOwn(n,d)?`${d} (empty or a placeholder)`:d,{fromLocal:i,fromPackages:a}=await st(e,r.discoveryCache),c=i.filter(d=>o(d));c.length>0&&r.logger.warn(`${N} 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.`}},Ri=async(e,r,t,n)=>{if(r.dryRun===!0||r.isolatedPreview===!0)return{};if(n.toolchain?.secretList===void 0)return Ai(e,r,n);const{logger:o}=r,s=r.env===void 0?"":` --env ${r.env}`;let i;try{i=await(r.secretLister??Nn)({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 st(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(p=>!d.has(p)))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??Ln())(`${String(f.length)} required secret(s) not set on the target (${f.join(", ")}). Generate strong values and push them now?`)){const{minted:h,ok:p}=await ki(e,r,f,n),m=Si(e,r,h);return p?{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}\`.`),{}},it=e=>e.format==="json"?!1:e.interactive!==void 0?e.interactive:process.stdout.isTTY&&!process.env.CI,Ti=async(e,r)=>{if(r.dryRun===!0)return;const t=kr(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 gs({cwd:e,logger:r.logger,railpackAvailable:r.railpackAvailable,spawner:r.spawner,targets:t});return n.code===0?void 0:n.error??"railpack build failed"},Ci=(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=en(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}`)}},Pi=async(e,r,t,n,o,s,i=!1)=>{try{le(n);const a=await $r({cache:s,projectRoot:e,schemaDir:O(e),skipCompanion:i}),c=Xt(e,a,{environment:o,target:n}),l=c.wranglerPath??"wrangler.jsonc";if(c.added.length>0&&r.success(`provisioned bindings: ${c.added.join(", ")} → ${l}`),c.updated.length>0&&r.success(`updated bindings: ${c.updated.join(", ")} → ${l}`),c.devConfig!==void 0){const{added:d,path:u,updated:f}=c.devConfig;r.success(`dev sidecar bindings: ${[...d,...f].join(", ")} → ${u}`)}for(const d of c.warnings)r.warn(d)}catch(a){const c=a instanceof Error?a.message:String(a);r.warn(`binding inference skipped: ${c}`)}try{const a=Qt(e);a.changed&&r.success(`bumped compatibility_date to ${a.date??"unknown"} (Workers Cache enabled) → ${a.wranglerPath??"wrangler.jsonc"}`)}catch(a){const c=a instanceof Error?a.message:String(a);r.warn(`compatibility date sync skipped: ${c}`)}Ci(e,r,t)},Ii=async(e,r,t,n,o,s,i,a,c,l)=>{let d;r?(d=new rn({name:"dots"}),d.start("running codegen")):t.info("running codegen");try{const u=$t({apiSpec:n,dryRun:!l,lazyFunctions:o,projectRoot:e,target:s,...Yt(e)});d?.succeed("codegen complete"),d||t.success("codegen complete");const f=an(u.platformDiagnostics,t);if(f.errors.length>0)return{error:f.errors.join("; ")};const{errorAdvisories:g,names:h,shouldBlock:p}=cn(u.advisories,c);if(p){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 Vt({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}`}}},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`.",_i=(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}),at=(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=_i(e,r);return Sr(t,e,"deploy",s=>n.deploy({...o,configPath:s}))},Di=(e,r,t)=>{const n=at(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},P={problems:[],wranglerPath:void 0},ye=(e,r)=>({code:y.USAGE,descriptor:void 0,error:e,validation:P,...r}),ji=(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},Oi=(e,r,t)=>{const n=r.format==="json",o=r.dryRun!==!0,s=Di(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"},Li=(e,r)=>he(r)===void 0?bt(e).services.map(t=>t.wranglerPath):[],ct=(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}),Ni=(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},dt=(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}`}},xi=(e,r,t)=>{const{error:n,services:o}=yr(e,O(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 dt(a,c=>ct(c,r,s,i,H))},lt=(e,r,t)=>{const n=e.cwd??process.cwd(),o=pn(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:P}}if(e.preview===!0)return e.logger.error(pr),{kind:"refused",code:y.USAGE,error:pr,validation:P};try{at(n,e,le(o.target))}catch(a){if(!(t&&a instanceof Wt&&xe(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:P}}}const s=e.openShardGatePassed===!0?void 0:ii(n,e,r,Li(n,e));if(s!==void 0)return{kind:"refused",code:s.code,error:s.error,validation:P};const i=xi(n,e,o.target);return i!==void 0?(e.logger.error(i),{kind:"refused",code:y.USAGE,error:i,validation:P}):{kind:"ok",target:o.target}},Fi=(e,r)=>e.apiSpec??(e.clientBuildRan===!0?wr(r):void 0),Mi=async(e,r,t)=>{if(r!=="celld")return;const n=await(e.celldToolchain??Gt)({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},ut=(e,r)=>{const t=je({cwd:e,env:r.env,url:r.migrateUrl}),n=t===void 0?void 0:Cs(e,r.env,t);if(n!==void 0)return{reason:n};const o=t===void 0?void 0:on(t,r.logger,e),s=o===void 0?void 0:tn({cwd:e,token:r.migrateToken,url:o}).token;return{target:o===void 0||!s?void 0:{baseUrl:o,fetchImpl:r.fetchImpl??sn,token:s}}},Ui=(e,r,t)=>async n=>{const o=ut(e,r);return"reason"in o?{kind:"inconclusive",reason:o.reason}:_n({changes:n,tables:t.schemaTables,target:o.target})},Bi=(e,r)=>async t=>{const n=ut(e,r);return"reason"in n?n.reason:In({changes:t,now:Date.now(),target:n.target})},Wi=(e,r,t,n)=>e==="deploy"?{checkStoredRows:Ui(r,t,n),countExpiringRows:Bi(r,t)}:{},qi=async(e,r)=>{const t=e.cwd??process.cwd(),n=it(e),o=Ie(e),s={problems:[],wranglerPath:void 0},i=lt(e,r,!1);if(i.kind==="refused")return{code:i.code,error:i.error,validation:i.validation};const{target:a}=i,c=await Mi(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 p=await Ii(t,n,e.logger,Fi(e,t),de(e.lazyFunctions),a,e.spawner,e.format==="json",o,e.clientBuildRan!==!0);if(p.error!==void 0)return{error:p.error,target:a,validation:P};l=p.result,e.discoveryCache?.clear()}let d;if(l!==void 0){const p=await Pn({allowDrift:e.allowSchemaDrift===!0,...Wi(r,t,e,l),codegen:l,command:r,logger:e.logger});if(p.blocked)return{error:`schema drift gate blocked ${r}`,schemaDrift:{blocked:!0,reason:p.reason},target:a,validation:s};d=p.rebless}const u=l&&qn({current:l.architecture,cwd:t,environment:e.env,logger:e.logger});await Pi(t,e.logger,l?.cronTriggers,a,e.env,e.discoveryCache,he(e)!==void 0);const f=await q(t,e,r,a,"check");if(f!==void 0)return{error:f,target:a,validation:P};const g=ai(t,e,r,a);if(g!==void 0)return{code:g.code,error:g.error,target:a,validation:P};const h=Jt({environment:e.env,projectRoot:t});return ji(h,e.logger)?{error:"wrangler validation failed",target:a,validation:h}:{codegen:l,reblessSchemaBaseline:d,recordArchitecture:u,target:a,validation:h}},Hi=e=>{oe(v(e,".wrangler","deploy","config.json"),{force:!0})},Gi=async(e,r,t)=>{const n=Fe(e);if(n!==void 0)return{built:!1,error:n};const o=xe(e.cwd,r,t);return o&&Hi(e.cwd),{built:o,error:await Xr(e)}},Vi=(e,r,t)=>r||t===!1?Oe(e):void 0,Ki=async(e,r,t)=>{const n=R(e);return Be(n,r.logger,"deploy",t.id,r.env,e)??q(n,r,"deploy",t.id,"check",e)},zi=(e,r,t)=>e.map((n,o)=>{const s=r[o]===!0,i=Vi(n.wranglerPath,s,t);return{built:s,config:i??n.wranglerPath,resolved:i!==void 0,service:n}}),Ji=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&&Eo(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 q(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}`}},Yi=async(e,r,t)=>{for(const n of e){const o=await Ji(n,r,t);if(o!==void 0)return o}},Xi=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 q(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 q(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}`}},Qi=async(e,r,t,n,o)=>{const s=[];for(const i of e){const{built:a,error:c}=await Gi(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}},Zi=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=Sr(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`}},ea=async(e,r,t,n)=>{const{error:o,services:s}=yr(e,O(e));if(o!==void 0)return{code:y.FAILURE,error:o};if(s.length===0)return;const i=Ni(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=$=>ct($,r,t,l,n),u=dt(c,d);if(u!==void 0)return r.logger.error(u),{code:y.USAGE,error:u};for(const $ of c){const C=await Ki($.wranglerPath,r,t);if(C!==void 0)return{code:y.USAGE,error:`service ${$.name} (${$.worker}): ${C}`}}const{builds:f,failure:g}=await Qi(c,d,l,r.env,r.logger);if(g!==void 0)return g;const h=zi(c,f,l),p=await Yi(h,r,t);if(p!==void 0)return p;const m={driver:t,manager:a,options:r,spawner:n,toolchain:i};for(const $ of h){const C=await Xi($,r,t);if(C!==void 0)return C;const T=await Zi($,m);if(T!==void 0)return T}},ra=async(e,r,t,n)=>{if(r!=="cloudflare")return;const o=e===void 0?void 0:_(e).parsed,s=(t===void 0?void 0:o?.env?.[t]?.account_id)??o?.account_id,i=await hn({accountId:s});(i.verdict==="near"||i.verdict==="full")&&n.warn(i.fix===void 0?i.message:`${i.message} ${i.fix}`)},ta=e=>e.dryRun!==!0&&e.temporary!==!0,na=e=>e.temporary===!0?"temporary":e.dryRun===!0?"preview":"defer",oa=e=>{const r=e.fix===void 0?e.message:`${e.message} ${e.fix}`;return e.verdict==="unchecked"?`${r} The deploy stops until it can be checked, as a namespace made by the first repo is unrestricted.`:r},sa=(e,r,t)=>{const n=[];for(const o of e)if(o.verdict==="ok")o.changesAccount===!0&&r.info(o.message);else if(o.verdict==="unchecked"&&t==="preview")r.warn(`dry run: ${o.message}${o.fix===void 0?"":` ${o.fix}`} A real deploy stops here.`);else{const s=oa(o);r.error(s),n.push(s)}return n},ft=async(e,r,t,n,o,s,i)=>{const a=t==="cloudflare"&&r!==void 0?_(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,O(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=>gn({...h,accountId:u,create:i==="create",jurisdiction:l,missingOk:i==="defer"||i==="preview"}))),g=sa(f,o,i);return g.length===0?void 0:g.join(`
|
|
64
|
+
`)},ia=async(e,r,t,n,o,s)=>{const i=ta(r)?await ft(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 q(e,r,"deploy",o);return a!==void 0?{code:y.FAILURE,error:a}:ea(e,r,t,n)},aa=async(e,r,t,n)=>{if(!(r.smokeLoad===!1||t.toolchain===void 0))return us({composedEntry:Ue(e),configPath:n,cwd:e,environment:r.env,launcher:r.smokeLauncher,logger:r.logger,toolchain:t.toolchain})},ca=async e=>{const r={...e,discoveryCache:e.discoveryCache??Ht()},t=r.cwd??process.cwd(),n=it(r),o=await qi(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=Bs(r)??await ft(t,s.wranglerPath,o.target,r.env,r.logger,r.discoveryCache,na(r))??await aa(t,r,i,s.wranglerPath);if(a!==void 0)return ye(a);const c=i.toolchain?.prebuildsContainerImages===!0?await Ti(t,r):void 0;if(c!==void 0)return ye(c);wi(t,r.logger,i),zt(t,m=>{r.logger.warn(m)}),await ra(s.wranglerPath,o.target,r.env,r.logger);const{error:l,mintedSecretsFile:d}=await Ri(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??H,f=await ia(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=Oi(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 yi({...o,cwd:t,descriptor:g,mintedSecretsFile:d,options:r,stdout:h.stdout}),logsAvailable:i.toolchain?.tail!==void 0}},da=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:P};qt(t);const s=await Xr(n);if(s!==void 0)return r.error(s),{code:y.FAILURE,descriptor:void 0,error:s,validation:P}},la=(e,r)=>{const t=r.skipCodegen===!0?!1:r.frameworkBuild;return xe(e,t,r.env)?r.env:void 0},ua=async e=>{const{logger:r}=e,t=e.cwd??process.cwd(),n=lt(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 da(e);if(o!==void 0)return o;const s=e.dryRun===!0?Kr(t):void 0;let i;try{if(i=await ca({...e,clientBuildEnvironment:la(t,e),clientBuildRan:js(t,e.skipCodegen===!0?!1:e.frameworkBuild,e.env),logger:r,openShardGatePassed:!0}),i.code===0&&e.emitBindings!==void 0){const{error:a}=mn({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&&Hn({cwd:e.cwd??process.cwd(),env:e.env,logger:e.logger,logsAvailable:i.logsAvailable===!0,mintedSecretsFile:i.mintedSecretsFile,url:i.deployment?.url}),i},za=vn(async({cwd:e,format:r,logger:t,options:n})=>{const o=fs(e,n.root),s=await ua({allowOpenShards:n.allowOpenShards===!0,allowSchemaDrift:n.allowSchemaDrift===!0,apiSpec:dn(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:je({cwd:o,env:n.env,url:n.migrateUrl}),migrateAllowDestructive:n.migrateAllowDestructive===!0,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{qi as a,Pi as b,Xn as c,Kr as d,st as e,za as f,fs as p,ua as r,aa as s,Ps as v};
|
|
@@ -1,2 +1 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`)},i=(r,o,t)=>(r.error(o),{code:t,error:o}),F=r=>r===void 0||!Number.isFinite(r)||r<=0?_:Math.floor(r),A=async r=>{const{logger:o}=r;if(r.prod&&r.url===void 0)return i(o,"--prod requires an explicit --url (refusing to report from the implicit localhost worker)",u.USAGE);const t=M(r.url,o,r.cwd);if(t===void 0)return{code:u.USAGE,error:"could not resolve a usable worker URL"};const{token:n}=v({cwd:r.cwd??process.cwd(),token:r.token,url:t});if(!n)return i(o,"admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)",u.AUTH);const a=`${t}/_lunora/rpc`,e=y,s={args:{},functionPath:O};r.shard!==void 0&&(s.shardKey=r.shard),o.info(`POST ${a} -> insights`);const l=await e(a,{body:JSON.stringify(s),headers:{authorization:`Bearer ${n}`,"content-type":"application/json"},method:"POST"}),c=await l.text();if(!l.ok)return i(o,`insights failed: HTTP ${String(l.status)}: ${c}`,T(l.status));let d;try{d=JSON.parse(c)}catch{return i(o,`insights failed: worker returned non-JSON: ${c}`,1)}const S=d.result??d,{functions:h}=S;if(!Array.isArray(h))return i(o,"insights failed: response carried no `functions` array",1);const g=k(h,F(r.limit));return r.format!=="json"&&o.info(E(g)),{code:0,report:g}},L=x(async({cwd:r,format:o,logger:t,options:n})=>{const a=n.limit===void 0?void 0:Number.parseInt(n.limit,10),e=await A({cwd:r,fetchImpl:void 0,format:o,limit:a,logger:t,prod:n.prod,shard:n.shard,token:n.token,url:I({cwd:r,prod:n.prod===!0,url:n.url})});return{code:e.code,data:e.report,error:e.error}});export{k as buildInsightsReport,L as execute,E as formatInsightsReport,A as runInsightsCommand};
|
|
1
|
+
import{existsSync as u,rmSync as a}from"node:fs";import{join as i}from"node:path";import{writeLinkedProject as d,LINKED_PROJECT_FILE as o}from"@lunora/config";import{d as k}from"../packem_shared/command-BpMv2n0o.mjs";import{EXIT_CODE as c}from"../packem_shared/EXIT_CODE-DQVhSE-1.mjs";import{r as s}from"../packem_shared/wrangler-name-Dsk5K1f-.mjs";const v=r=>{try{const{protocol:n}=new URL(r);return n==="http:"||n==="https:"}catch{return!1}},f=(r,n)=>{const e=i(r,o);return u(e)?(a(e),n.success(`link: removed ${o}`),{code:0}):(n.warn(`link: no ${o} to remove`),{code:0})},w=r=>{const n=r.cwd??process.cwd(),{logger:e}=r;if(r.remove)return f(n,e);if(r.url===void 0||r.url==="")return e.error("link requires a deployed Worker URL. Usage: lunora link --url <https://your-worker>"),{code:c.USAGE};if(!v(r.url))return e.error(`link: invalid --url "${r.url}" — expected an http(s) URL`),{code:c.USAGE};const l=r.now??(()=>new Date().toISOString()),t={env:r.env,linkedAt:l(),workerName:r.name??s(n),workerUrl:r.url},m=d(n,t);return e.success(`link: ${t.workerName??"(unnamed worker)"} -> ${r.url}`),e.info(`link: wrote ${m}`),t.env!==void 0&&e.info(`link: environment "${t.env}"`),{code:0,link:t}},y=k(({cwd:r,logger:n,options:e})=>w({cwd:r,env:e.env,logger:n,name:e.name,remove:e.remove===!0,url:e.url}));export{y as execute,w as runLinkCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{r as h}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{r as k,a as v}from"../packem_shared/admin-url-DJB8P6Jh.mjs";import{d as m}from"../packem_shared/command-BpMv2n0o.mjs";import{EXIT_CODE as d,exitCodeForStatus as w}from"../packem_shared/EXIT_CODE-DQVhSE-1.mjs";import{a as f}from"../packem_shared/resolve-target-C_ZloTvd.mjs";const A="/_lunora/admin/pause",i=(e,r,o)=>(e.error(r),{code:o,error:r}),l=e=>e.paused?`paused${e.pausedAt===void 0?"":` since ${new Date(e.pausedAt).toISOString()}`}${e.reason===void 0?"":` — ${e.reason}`}`:"running",p=async e=>{const{logger:r}=e;if(e.prod&&e.url===void 0)return i(r,`--prod requires an explicit --url (refusing to ${e.action} the implicit localhost worker)`,d.USAGE);const o=k(e.url,r,e.cwd);if(o===void 0)return{code:d.USAGE,error:"could not resolve a usable worker URL"};const{token:n}=h({cwd:e.cwd??process.cwd(),token:e.token,url:o});if(!n)return i(r,"admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)",d.AUTH);const t=`${o}${A}`,a=e.fetchImpl??v,s=e.action==="status"?await a(t,{headers:{authorization:`Bearer ${n}`},method:"GET"}):await a(t,{body:JSON.stringify({paused:e.action==="pause",...e.reason===void 0?{}:{reason:e.reason}}),headers:{authorization:`Bearer ${n}`,"content-type":"application/json"},method:"POST"}),u=await s.text();if(!s.ok)return i(r,`${e.action} failed: HTTP ${String(s.status)}: ${u}`,w(s.status));let c;try{c=JSON.parse(u)}catch{return i(r,`${e.action} failed: worker returned non-JSON: ${u}`,1)}return e.format!=="json"&&(c.supported?e.action==="status"?r.info(l(c)):r.success(`${o}: ${l(c)}`):r.warn("this deployment has no scheduler, so it cannot be paused")),{code:0,result:c}},$=(e,r)=>{if(e==="resume")return r.length===0?void 0:`resume takes no arguments, got "${r.join(" ")}"`;if(r.length>1||r.length===1&&r[0]!=="status")return`unknown arguments "${r.join(" ")}" — expected status, or none to pause`},O=m(async({argument:e,cwd:r,format:o,logger:n,options:t})=>{const a=$("pause",e);if(a!==void 0)return n.error(`pause: ${a}`),{code:d.USAGE,error:a};const[s]=e,u=await p({action:s==="status"?"status":"pause",cwd:r,format:o,logger:n,prod:t.prod,reason:t.reason,token:t.token,url:f({cwd:r,prod:t.prod===!0,url:t.url})});return{code:u.code,data:u.result,error:u.error}}),T=m(async({argument:e,cwd:r,format:o,logger:n,options:t})=>{const a=$("resume",e);if(a!==void 0)return n.error(`resume: ${a}`),{code:d.USAGE,error:a};const s=await p({action:"resume",cwd:r,format:o,logger:n,prod:t.prod,token:t.token,url:f({cwd:r,prod:t.prod===!0,url:t.url})});return{code:s.code,data:s.result,error:s.error}});export{O as executePause,T as executeResume,$ as pauseUsageError,p as runPauseCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{resolveLazyFunctions as c,resolveDeployDriver as t}from"@lunora/config";import{p as s}from"../packem_shared/api-spec-lYyq4vL6.mjs";import{d as l}from"../packem_shared/command-BpMv2n0o.mjs";import{EXIT_CODE as o}from"../packem_shared/EXIT_CODE-DQVhSE-1.mjs";import{a as d,s as m}from"./handler.mjs";const n=async r=>{const a=r.cwd??process.cwd(),e=await d({allowSchemaDrift:r.allowSchemaDrift,apiSpec:r.apiSpec,lazyFunctions:c(r.lazyFunctions),cwd:a,logger:r.logger,spawner:r.spawner,strictAdvisories:r.strictAdvisories,target:r.target},"prepare");if(e.error!==void 0)return{code:e.code??o.USAGE,error:e.error,...e.schemaDrift===void 0?{}:{schemaDrift:e.schemaDrift},validation:e.validation};const i=await m(a,{env:void 0,logger:r.logger,smokeLauncher:r.smokeLauncher,smokeLoad:r.smokeLoad},t(e.target),e.validation.wranglerPath);return i!==void 0?{code:o.FAILURE,error:i,validation:e.validation}:(e.reblessSchemaBaseline?.(),r.logger.success("project is ready to deploy"),{code:0,validation:e.validation})},w=l(({cwd:r,logger:a,options:e})=>n({allowSchemaDrift:e.allowSchemaDrift===!0,apiSpec:s(e.apiSpec),lazyFunctions:c(e.lazyFunctions),cwd:r,logger:a,smokeLoad:e.smokeLoad,strictAdvisories:e.strictAdvisories,target:e.target}));export{w as execute,n as runPrepareCommand};
|
|
@@ -1 +1,3 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{existsSync as S}from"node:fs";import{mkdtemp as v,writeFile as k,rm as j}from"node:fs/promises";import{tmpdir as R}from"node:os";import{discoverSchema as C,schemaFromIr as T}from"@lunora/codegen";import{seedPlan as $}from"@lunora/seed";import{join as w}from"@visulima/path";import{Project as O}from"ts-morph";import{a as E}from"../packem_shared/shared-CV7ESvuj.mjs";import{t as y}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{d as A}from"../packem_shared/command-BpMv2n0o.mjs";import{EXIT_CODE as u}from"../packem_shared/EXIT_CODE-DQVhSE-1.mjs";import{a as F}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{b as p}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{runResetCommand as N}from"./runResetCommand.mjs";import{r as U}from"../packem_shared/import-3Y59Ry9F.mjs";const x=(e,r)=>typeof r=="bigint"?Number(r):r instanceof ArrayBuffer?[...new Uint8Array(r)]:r,f=(e,r)=>({code:e,error:r,ndjson:""}),I=(e,r)=>{if(!S(r)){const o=`schema not found: ${r} — run \`vis generate lunora-table --name=<name>\` to create one`;return e.logger.error(o),f(u.NOT_FOUND,o)}if(e.reset===!0&&y({prod:e.prod,url:e.url})){const o="--reset only clears local .wrangler/state and cannot be combined with --prod or a remote --url";return e.logger.error(o),f(u.USAGE,o)}},z=async(e,r,o,t,n)=>{const s=await v(w(R(),"lunora-seed-")),d=w(s,"rows.ndjson");await k(d,e,"utf8");try{const a=await U({batchSize:n.batchSize,cwd:t,fetchImpl:n.fetchImpl,file:d,logger:n.logger,prod:n.prod,token:n.token,url:n.url,yes:!0}),i=a.body?.conflicts??0;return i>0&&n.logger.warn(`${String(i)} row(s) skipped — their _id already exists. Seeding is deterministic; re-run with --reset to wipe local state first, or a different --seed for fresh ids.`),{code:a.code,data:{conflicts:i,generated:r,inserted:a.inserted,tables:o},ndjson:e,...a.error===void 0?{}:{error:a.error}}}finally{await j(s,{force:!0,recursive:!0}).catch(()=>{})}},D=(e,r)=>{if(e.table===void 0||r.tables.some(n=>n.name===e.table))return;const o=r.tables.map(n=>n.name).join(", "),t=`unknown table "${e.table}" — schema defines: ${o||"(no tables)"}`;return e.logger.error(t),f(u.USAGE,t)},_=async(e,r)=>{if(!y({prod:e.prod,url:e.url})||e.yes===!0)return;if(!process.stdin.isTTY&&e.confirm===void 0){const s="seed: refusing to insert into a non-local target without confirmation — re-run with --yes";return e.logger.error(s),f(u.USAGE,s)}if(!await(e.confirm??p)(`This will insert ${String(r)} generated row(s) into ${e.url??"the production worker"}. Continue?`))return e.logger.info("seed: aborted"),f(u.CANCELLED,"seed: aborted at the confirmation prompt")},G=e=>{const r=[];for(const{rows:o,table:t}of e)for(const n of o)r.push(JSON.stringify({doc:n,table:t},x));return{lines:r,ndjson:r.length>0?`${r.join(`
|
|
2
|
+
`)}
|
|
3
|
+
${E(r.length)}`:""}},L=async e=>{const r=e.cwd??process.cwd(),o=e.format==="json",t=w(r,"lunora","schema.ts"),n=I(e,t);if(n!==void 0)return n;const s=new O({skipAddingFilesFromTsConfig:!0}),d=C(s,t),a=D(e,d);if(a!==void 0)return a;const i=T(d),l=$(i,{allowOrphans:e.allowOrphans===!0,defaultCount:e.count??10,now:e.now,only:e.table===void 0?void 0:[e.table],seed:e.seed??0}),{lines:h,ndjson:c}=G(l),m=h.length;if(e.dryRun===!0)return!o&&c.length>0&&process.stdout.write(c),e.logger.info(`generated ${String(m)} row(s) across ${String(l.length)} table(s) — dry run, nothing inserted`),{code:0,data:{conflicts:0,generated:m,inserted:0,rows:o?h.map(g=>JSON.parse(g)):void 0,tables:l.length},ndjson:c};if(m===0)return e.logger.warn("no rows generated — nothing to insert"),{code:0,data:{conflicts:0,generated:0,inserted:0,tables:l.length},ndjson:c};if(e.reset===!0){const g=await N({confirm:e.confirm,cwd:r,logger:e.logger,yes:e.yes});if(g.code!==0)return{code:g.code,error:"seed: --reset could not clear local state",ndjson:c}}const b=await _(e,m);return b!==void 0?b:z(c,m,l.length,r,e)},te=A(async({cwd:e,format:r,logger:o,options:t})=>{const n=await L({allowOrphans:t.allowOrphans===!0,batchSize:t.batchSize,count:t.count,cwd:e,dryRun:t.dryRun===!0,format:r,logger:o,prod:t.prod===!0,reset:t.reset===!0,now:t.now,seed:t.seed,table:t.table,token:t.token,url:F({cwd:e,prod:t.prod===!0,url:t.url}),yes:t.yes===!0});return{code:n.code,data:n.data,error:n.error}});export{te as execute,L as runSeedCommand};
|
|
@@ -1,3 +1 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`)}
|
|
3
|
-
${E(r.length)}`:""}},L=async e=>{const r=e.cwd??process.cwd(),o=e.format==="json",t=w(r,"lunora","schema.ts"),n=I(e,t);if(n!==void 0)return n;const s=new O({skipAddingFilesFromTsConfig:!0}),d=C(s,t),a=D(e,d);if(a!==void 0)return a;const i=T(d),l=$(i,{allowOrphans:e.allowOrphans===!0,defaultCount:e.count??10,now:e.now,only:e.table===void 0?void 0:[e.table],seed:e.seed??0}),{lines:h,ndjson:c}=G(l),m=h.length;if(e.dryRun===!0)return!o&&c.length>0&&process.stdout.write(c),e.logger.info(`generated ${String(m)} row(s) across ${String(l.length)} table(s) — dry run, nothing inserted`),{code:0,data:{conflicts:0,generated:m,inserted:0,rows:o?h.map(g=>JSON.parse(g)):void 0,tables:l.length},ndjson:c};if(m===0)return e.logger.warn("no rows generated — nothing to insert"),{code:0,data:{conflicts:0,generated:0,inserted:0,tables:l.length},ndjson:c};if(e.reset===!0){const g=await N({confirm:e.confirm,cwd:r,logger:e.logger,yes:e.yes});if(g.code!==0)return{code:g.code,error:"seed: --reset could not clear local state",ndjson:c}}const b=await _(e,m);return b!==void 0?b:z(c,m,l.length,r,e)},te=A(async({cwd:e,format:r,logger:o,options:t})=>{const n=await L({allowOrphans:t.allowOrphans===!0,batchSize:t.batchSize,count:t.count,cwd:e,dryRun:t.dryRun===!0,format:r,logger:o,prod:t.prod===!0,reset:t.reset===!0,now:t.now,seed:t.seed,table:t.table,token:t.token,url:F({cwd:e,prod:t.prod===!0,url:t.url}),yes:t.yes===!0});return{code:n.code,data:n.data,error:n.error}});export{te as execute,L as runSeedCommand};
|
|
1
|
+
import{d as l}from"../packem_shared/command-BpMv2n0o.mjs";import{EXIT_CODE as n}from"../packem_shared/EXIT_CODE-DQVhSE-1.mjs";import{r as s,b as t,a as o}from"../packem_shared/commands-CkuCMUP_.mjs";const y=l(({argument:a,cwd:u,format:m,logger:e,options:r})=>{const f=a[0],c=a.slice(1);if(f==="add")return s({allowUnsafeSource:r.allowUnsafeSource===!0,cwd:u,diff:r.diff===!0,dryRun:r.dryRun===!0,format:m,from:r.from,logger:e,names:c,overwrite:r.overwrite===!0,ref:r.ref,source:r.source,yes:r.yes===!0});if(f==="list")return s({allowUnsafeSource:r.allowUnsafeSource===!0,cwd:u,format:m,from:r.from,list:!0,logger:e,names:[],ref:r.ref,source:r.source});if(f==="view")return t({allowUnsafeSource:r.allowUnsafeSource===!0,cwd:u,from:r.from,logger:e,names:c,ref:r.ref,source:r.source});if(f==="build")return o({check:r.check===!0,cwd:u,from:r.from,logger:e,names:[],out:r.out});const d="registry: unknown subcommand. Usage: lunora registry <add|list|view|build> [names…]";return e.error(d),{code:n.USAGE,error:d}});export{y as execute};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d as
|
|
1
|
+
import{existsSync as u,readdirSync as d,statSync as g,mkdirSync as h,writeFileSync as w,readFileSync as y}from"node:fs";import{fileURLToPath as v}from"node:url";import{AGENT_RULES_DIR as a,detectAgentRules as R,LUNORA_SKILL_NAMES as L}from"@lunora/config";import{join as i,relative as A,resolve as E,dirname as m}from"@visulima/path";import{f as I}from"../packem_shared/cli-manifest-DoQ_3bzs.mjs";import{d as $}from"../packem_shared/command-BpMv2n0o.mjs";import{EXIT_CODE as _}from"../packem_shared/EXIT_CODE-DQVhSE-1.mjs";const b=(e=m(v(import.meta.url)))=>{const r=I(e),t=r===void 0?void 0:i(r,"skills");return t!==void 0&&u(t)?t:void 0},j=e=>d(e).filter(r=>{const t=i(e,r);return g(t).isDirectory()&&u(i(t,"SKILL.md"))}),f=(e,r,t)=>{h(r,{recursive:!0});let n=!1;for(const o of d(e)){const l=i(e,o),s=i(r,o);if(g(l).isDirectory()){n=f(l,s,t)||n;continue}u(s)&&!t||(w(s,y(l)),n=!0)}return n},D=["pnpm-workspace.yaml","pnpm-lock.yaml","yarn.lock","package-lock.json","bun.lock","bun.lockb",".git"],O=e=>{let r=e;for(;;){if(D.some(n=>u(i(r,n))))return r;const t=m(r);if(t===r)return e;r=t}},k=(e,r)=>r===void 0?O(e):E(e,r),U=e=>{const r=e.cwd??process.cwd(),t=k(r,e.dir),n=e.overwrite===!0,o=b();if(o===void 0)return e.logger.error("rules: could not locate the bundled skills (is @lunora/cli installed correctly?)."),{code:1,installed:[],skipped:[]};const l=[],s=[];for(const c of j(o)){const S=i(t,a,c);f(i(o,c),S,n)?l.push(c):s.push(c)}const p=A(r,i(t,a))||a;return l.length>0&&e.logger.success(`Installed ${String(l.length)} Lunora skill(s) into ${p}/: ${l.join(", ")}.`),s.length>0&&e.logger.info(`Skipped ${String(s.length)} existing skill(s) (re-run with --overwrite to replace): ${s.join(", ")}.`),e.logger.info("Your AI coding agent will pick these up automatically. Start with the `lunora` skill."),{code:0,installed:l,skipped:s}},x=e=>{const r=e.cwd??process.cwd(),t=k(r,e.dir),n=R(t);return n.installed?(e.logger.success(`Lunora agent rules are installed (${String(n.present.length)}/${String(L.length)} skills).`),n.missing.length>0&&e.logger.info(`Missing: ${n.missing.join(", ")}. Run \`lunora rules install\` to add them.`),{code:0,installed:n.present,skipped:[]}):(e.logger.warn("Lunora agent rules are not installed. Run `lunora rules install` so your AI agent knows how to use Lunora."),{code:e.strict===!0?1:0,installed:n.present,skipped:[]})},G=$(({argument:e,cwd:r,logger:t,options:n})=>{const o=e[0]??"check";return o==="install"?U({cwd:r,dir:n.dir,logger:t,overwrite:n.overwrite===!0}):o==="check"?x({cwd:r,dir:n.dir,logger:t,strict:n.strict===!0}):(t.error("rules: unknown subcommand. Usage: lunora rules <install|check>"),{code:_.USAGE})});export{G as execute,j as listBundledSkills,b as resolveBundledSkillsDirectory,x as runRulesCheck,U as runRulesInstall};
|