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