@lunora/cli 1.0.0-alpha.47 → 1.0.0-alpha.471

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.
Files changed (146) hide show
  1. package/LICENSE.md +33 -0
  2. package/README.md +3 -1
  3. package/dist/bin.mjs +3 -10
  4. package/dist/cli.d.mts +31 -0
  5. package/dist/cli.d.ts +31 -0
  6. package/dist/cli.mjs +1 -0
  7. package/dist/index.d.mts +1167 -416
  8. package/dist/index.d.ts +1167 -416
  9. package/dist/index.mjs +1 -19
  10. package/dist/packem_chunks/cli.mjs +2 -0
  11. package/dist/packem_chunks/dispatch.mjs +1 -0
  12. package/dist/packem_chunks/handler.mjs +55 -158
  13. package/dist/packem_chunks/handler10.mjs +2 -16
  14. package/dist/packem_chunks/handler11.mjs +1 -22
  15. package/dist/packem_chunks/handler12.mjs +1 -192
  16. package/dist/packem_chunks/handler13.mjs +1 -131
  17. package/dist/packem_chunks/handler14.mjs +3 -65
  18. package/dist/packem_chunks/handler15.mjs +1 -58
  19. package/dist/packem_chunks/handler16.mjs +1 -80
  20. package/dist/packem_chunks/handler17.mjs +1 -43
  21. package/dist/packem_chunks/handler18.mjs +1 -105
  22. package/dist/packem_chunks/handler19.mjs +1 -170
  23. package/dist/packem_chunks/handler2.mjs +1 -114
  24. package/dist/packem_chunks/handler20.mjs +1 -94
  25. package/dist/packem_chunks/handler21.mjs +7 -94
  26. package/dist/packem_chunks/handler22.mjs +1 -0
  27. package/dist/packem_chunks/handler23.mjs +3 -0
  28. package/dist/packem_chunks/handler24.mjs +3 -0
  29. package/dist/packem_chunks/handler25.mjs +2 -0
  30. package/dist/packem_chunks/handler26.mjs +1 -0
  31. package/dist/packem_chunks/handler27.mjs +2 -0
  32. package/dist/packem_chunks/handler28.mjs +99 -0
  33. package/dist/packem_chunks/handler29.mjs +3 -0
  34. package/dist/packem_chunks/handler3.mjs +1 -204
  35. package/dist/packem_chunks/handler30.mjs +15 -0
  36. package/dist/packem_chunks/handler31.mjs +1 -0
  37. package/dist/packem_chunks/handler32.mjs +1 -0
  38. package/dist/packem_chunks/handler4.mjs +1 -33
  39. package/dist/packem_chunks/handler5.mjs +1 -49
  40. package/dist/packem_chunks/handler6.mjs +3 -91
  41. package/dist/packem_chunks/handler7.mjs +1 -42
  42. package/dist/packem_chunks/handler8.mjs +1 -174
  43. package/dist/packem_chunks/handler9.mjs +1 -315
  44. package/dist/packem_chunks/runCodegenCommand.mjs +4 -52
  45. package/dist/packem_chunks/runDevCommand.mjs +6 -0
  46. package/dist/packem_chunks/runInitCommand.mjs +423 -1447
  47. package/dist/packem_chunks/runResetCommand.mjs +1 -41
  48. package/dist/packem_chunks/runRpcCommand.mjs +1 -68
  49. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Ck9tABfr.mjs +1 -0
  50. package/dist/packem_shared/EXIT_CODE-DQVhSE-1.mjs +1 -0
  51. package/dist/packem_shared/admin-token-VdUnvnKW.mjs +1 -0
  52. package/dist/packem_shared/admin-url-DJB8P6Jh.mjs +1 -0
  53. package/dist/packem_shared/api-spec-lYyq4vL6.mjs +1 -0
  54. package/dist/packem_shared/binding-manifest-file-CQ1eQYy1.mjs +2 -0
  55. package/dist/packem_shared/buildRegistryIndex-Dc8D8AR6.mjs +1 -0
  56. package/dist/packem_shared/cap-error-body-YBKO32BF.mjs +1 -0
  57. package/dist/packem_shared/catalog-CahzmDLV.mjs +1 -0
  58. package/dist/packem_shared/cli-manifest-DoQ_3bzs.mjs +1 -0
  59. package/dist/packem_shared/cloudflare-credentials-BVmZnDZk.mjs +1 -0
  60. package/dist/packem_shared/codegen-error-AmH54ofi.mjs +3 -0
  61. package/dist/packem_shared/command-BpMv2n0o.mjs +1 -0
  62. package/dist/packem_shared/commands-CkuCMUP_.mjs +13 -0
  63. package/dist/packem_shared/createLogger-4TujevyB.mjs +2 -0
  64. package/dist/packem_shared/createRecordingSpawner-DchLi0gR.mjs +1 -0
  65. package/dist/packem_shared/deploy-target-resolve-BTCW1Iv4.mjs +1 -0
  66. package/dist/packem_shared/diffSnapshots-Y1G8am6C.mjs +7 -0
  67. package/dist/packem_shared/docker-DpVxvYpL.mjs +1 -0
  68. package/dist/packem_shared/export-rows-EzdNDYpa.mjs +3 -0
  69. package/dist/packem_shared/free-port-DjbFhaaT.mjs +1 -0
  70. package/dist/packem_shared/health-probe-BLnoq_oC.mjs +13 -0
  71. package/dist/packem_shared/import-3Y59Ry9F.mjs +13 -0
  72. package/dist/packem_shared/index-oHZBGBwB.mjs +1 -0
  73. package/dist/packem_shared/insertSchemaExtension-CbTH3lCQ.mjs +10 -0
  74. package/dist/packem_shared/js-literal-FWLi94Lh.mjs +1 -0
  75. package/dist/packem_shared/lint-ignore-report-DKZagpqk.mjs +2 -0
  76. package/dist/packem_shared/mcp-config-file-GR1Y_CVw.mjs +2 -0
  77. package/dist/packem_shared/open-url-EnKy--w-.mjs +1 -0
  78. package/dist/packem_shared/output-format-DWe_tkTR.mjs +2 -0
  79. package/dist/packem_shared/parseManifest-CwPTKdtS.mjs +1 -0
  80. package/dist/packem_shared/path-containment-CgxYZggb.mjs +1 -0
  81. package/dist/packem_shared/plan-pog5AvMk.mjs +5 -0
  82. package/dist/packem_shared/planDevCommand-Bl6OrwXm.mjs +1 -0
  83. package/dist/packem_shared/platform-diagnostics-Cn2g6Jh-.mjs +4 -0
  84. package/dist/packem_shared/prompt-cancelled-BvsNxg_Q.mjs +1 -0
  85. package/dist/packem_shared/render-lunora-error-JsLelWwR.mjs +2 -0
  86. package/dist/packem_shared/resolve-Bdc9KEUv.mjs +5 -0
  87. package/dist/packem_shared/resolve-target-BRvw8Pf7.mjs +1 -0
  88. package/dist/packem_shared/runAddCommand-gThKW-ZB.mjs +1 -0
  89. package/dist/packem_shared/runDeployCommand-CNgOUx91.mjs +1 -0
  90. package/dist/packem_shared/runExportCommand-_PtkJJDT.mjs +5 -0
  91. package/dist/packem_shared/runMigrateGenerateCommand-CguLEIZp.mjs +11 -0
  92. package/dist/packem_shared/schemaIrToSnapshot-Ck7DSPdf.mjs +1 -0
  93. package/dist/packem_shared/shared-CV7ESvuj.mjs +2 -0
  94. package/dist/packem_shared/storage-3GOIFVZm.mjs +1 -0
  95. package/dist/packem_shared/tui-prompts-B3YwUhGw.mjs +4 -0
  96. package/dist/packem_shared/variables-CPYyJtsL.mjs +1 -0
  97. package/dist/packem_shared/vectorize-metadata-DK61NmVx.mjs +2 -0
  98. package/dist/packem_shared/wrangler-name-Dsk5K1f-.mjs +1 -0
  99. package/dist/packem_shared/wrangler-secrets-C9siMBwN.mjs +1 -0
  100. package/package.json +45 -19
  101. package/skills/README.md +36 -17
  102. package/skills/lunora/SKILL.md +158 -65
  103. package/skills/lunora-cloudflare-audit/SKILL.md +164 -0
  104. package/skills/lunora-create-package/SKILL.md +97 -84
  105. package/skills/lunora-deploy/SKILL.md +212 -102
  106. package/skills/lunora-functions/SKILL.md +367 -60
  107. package/skills/lunora-migration-helper/SKILL.md +194 -149
  108. package/skills/lunora-performance-audit/SKILL.md +137 -95
  109. package/skills/lunora-quickstart/SKILL.md +136 -136
  110. package/skills/lunora-realtime/SKILL.md +217 -97
  111. package/skills/lunora-setup-auth/SKILL.md +203 -101
  112. package/skills/lunora-setup-hyperdrive/SKILL.md +153 -110
  113. package/skills/lunora-setup-hyperdrive-global/SKILL.md +152 -94
  114. package/skills/lunora-setup-mail/SKILL.md +87 -113
  115. package/skills/lunora-setup-scheduler/SKILL.md +133 -97
  116. package/skills/lunora-setup-storage/SKILL.md +189 -95
  117. package/dist/packem_chunks/planDevCommand.mjs +0 -541
  118. package/dist/packem_chunks/runDeployCommand.mjs +0 -594
  119. package/dist/packem_chunks/runMigrateGenerateCommand.mjs +0 -397
  120. package/dist/packem_shared/COMMANDS-B0ftFD_3.mjs +0 -948
  121. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Ck-2bU08.mjs +0 -244
  122. package/dist/packem_shared/admin-url-4UzT-CI4.mjs +0 -19
  123. package/dist/packem_shared/api-spec-CtA6ilu4.mjs +0 -13
  124. package/dist/packem_shared/buildRegistryIndex-BcYe607_.mjs +0 -38
  125. package/dist/packem_shared/codegen-error-DJG-ghs_.mjs +0 -31
  126. package/dist/packem_shared/command-D3lB_4Az.mjs +0 -19
  127. package/dist/packem_shared/commands-B-gR09Z_.mjs +0 -845
  128. package/dist/packem_shared/createLogger-B40gPzQo.mjs +0 -78
  129. package/dist/packem_shared/createRecordingSpawner-DxI3mebw.mjs +0 -43
  130. package/dist/packem_shared/detect-package-manager-DYp7n3mJ.mjs +0 -61
  131. package/dist/packem_shared/diffSnapshots-BeDvvNiF.mjs +0 -161
  132. package/dist/packem_shared/docker-hMQ97KSQ.mjs +0 -21
  133. package/dist/packem_shared/insertSchemaExtension-DAqbfr9Z.mjs +0 -64
  134. package/dist/packem_shared/open-url-Dfq6fAyT.mjs +0 -41
  135. package/dist/packem_shared/output-format-wUvAN6AL.mjs +0 -17
  136. package/dist/packem_shared/parseArgs-YXFuKdEk.mjs +0 -56
  137. package/dist/packem_shared/parseManifest--vZf2FY1.mjs +0 -94
  138. package/dist/packem_shared/prompt-cancelled-APzX1Im-.mjs +0 -9
  139. package/dist/packem_shared/resolve-target-qbsJ_5sF.mjs +0 -16
  140. package/dist/packem_shared/runAddCommand-bnY6-HKb.mjs +0 -4
  141. package/dist/packem_shared/schema-drift-gate-BtBt0as0.mjs +0 -79
  142. package/dist/packem_shared/schemaIrToSnapshot-DdsljJT-.mjs +0 -43
  143. package/dist/packem_shared/storage-BIsph-Vk.mjs +0 -84
  144. package/dist/packem_shared/tui-prompts-BjEN8XgP.mjs +0 -658
  145. package/dist/packem_shared/wrangler-name-cy4yhm9j.mjs +0 -12
  146. package/dist/packem_shared/wrangler-secrets-P2_ZUR-k.mjs +0 -47
@@ -1,160 +1,57 @@
1
- import { existsSync } from 'node:fs';
2
- import { findWranglerFile } from '@lunora/config';
3
- import { join, basename } from '@visulima/path';
4
- import { d as defineHandler } from '../packem_shared/command-D3lB_4Az.mjs';
5
- import { v as validateOutputFormat, i as isJsonFormat, p as printJson, l as loggerForFormat } from '../packem_shared/output-format-wUvAN6AL.mjs';
6
- import { t as tuiText, a as tuiSelect } from '../packem_shared/tui-prompts-BjEN8XgP.mjs';
7
- import { n as normalizeFeature, E as EMAIL_ITEM, s as sanitizeBucketName, d as deriveBucketName, p as promptBucketName, r as resolveTypedDestination, M as MAIL_DESTINATION_PROMPT, a as sanitizeDatabaseName, b as deriveDatabaseName, c as promptDatabaseName, D as DEFAULT_AUTH_ITEM, e as promptAuthProvider, A as AUTH_PROVIDER_OPTIONS, w as withStorageBucketName, f as withMailDestination, g as withAuthDatabaseName } from '../packem_shared/storage-BIsph-Vk.mjs';
8
- import { r as runAddCommand } from '../packem_shared/commands-B-gR09Z_.mjs';
1
+ import{mkdirSync as hr,writeFileSync as X,existsSync as b,readFileSync as E,readdirSync as K,statSync as Re,rmSync as oe,mkdtempSync as ot,realpathSync as st}from"node:fs";import{dirname as j,join as p,resolve as I,relative as L,sep as x,extname as it}from"node:path";import{PROJECT_CONFIG_FILENAMES as at,isTestPath as ye,discoverMigrations as ct,readServiceBindings as Te,runCodegen as dt}from"@lunora/codegen";import{readLinkedProject as _e,discoverSchemaInfo as Ce,resolveSchemaDirectory as M,startDevProcess as lt,acceptsConnection as ut,resolveTargetOrThrow as we,detectFramework as ft,DEFAULT_BUNDLE_META_PATH as gt,STRICT_ADVISORIES_ENV as ht,LAZY_FUNCTIONS_ENV as mt,BUNDLE_META_PATH_ENV as pt,BUILD_TARGET_ENV as vt,BUILD_ROOT_ENV as yt,canonicalPath as wt,COMPOSED_WORKER_ENTRY as He,discoverContainerInfo as mr,D1_PLACEHOLDER_ID as qe,writeLinkedProject as kt,DEV_VARS_FILE as N,parseDevVariableEntries as pr,secretSourcesFromBindings as bt,inferLunoraBindings as vr,requiredSecrets as $t,mintableSecretKeysFor as St,generateSecretValue as Et,upsertDevVariableLine as At,writeDevVariablesFileAtomically as Rt,isPlaceholderValue as Tt,ensureGitignoreEntries as _t,resolveLazyFunctions as ce,resolveDeployDriver as de,MissingBuildOutputError as Ct,clearApiSpecMarker as It,createDiscoveryCache as Pt,planToolchainInvocation as yr,probeCelldToolchain as jt,runPostCodegenHook as Ot,readApiSpecMarker as Dt}from"@lunora/config";import{findWranglerFile as O,readWranglerJsonc as P,HYPERDRIVE_PLACEHOLDER_ID as wr,applyModify as kr,bindingsNeedingDatabase as Nt,mergeWranglerEnvironment as le,warnCloudflareCliConfigOnce as Lt,validateWranglerProject as xt,wranglerCodegenInputs as Mt,reconcileWranglerBindings as Ft,reconcileWranglerCompatibilityDate as Ut,reconcileWranglerCrons as Bt,describePreservedCrons as Wt}from"@lunora/config/cloudflare";import{Spinner as Ht}from"@visulima/spinner";import{r as qt}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{n as Gt,r as Vt,a as Kt}from"../packem_shared/admin-url-DJB8P6Jh.mjs";import{r as Ie,a as zt,e as Jt}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as Yt}from"../packem_shared/api-spec-lYyq4vL6.mjs";import{e as Xt,m as Qt,g as Zt,i as br,d as en,b as rn}from"../packem_shared/vectorize-metadata-DK61NmVx.mjs";import{w as tn}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{d as nn}from"../packem_shared/command-BpMv2n0o.mjs";import{r as Pe}from"../packem_shared/wrangler-name-Dsk5K1f-.mjs";import{a as on}from"../packem_shared/deploy-target-resolve-BTCW1Iv4.mjs";import{EXIT_CODE as w}from"../packem_shared/EXIT_CODE-DQVhSE-1.mjs";import{spawn as sn}from"node:child_process";import{createHash as an,randomUUID as $r}from"node:crypto";import{setTimeout as cn}from"node:timers/promises";import{stripVTControlCharacters as dn}from"node:util";import{toolchainExecArgs as z,detectPackageManager as F,execArgsFor as je}from"@lunora/config/cli";import{r as Sr,c as Er}from"../packem_shared/cloudflare-credentials-BVmZnDZk.mjs";import{f as ln}from"../packem_shared/free-port-DjbFhaaT.mjs";import{ts as k,Project as Ar,SyntaxKind as y,Node as $}from"ts-morph";import{l as V}from"../packem_shared/js-literal-FWLi94Lh.mjs";import{containerBuildTag as un}from"@lunora/container";import{a as fn,i as gn}from"../packem_shared/docker-DpVxvYpL.mjs";import{defaultSpawner as H}from"../packem_shared/createRecordingSpawner-DchLi0gR.mjs";import{a as Oe}from"../packem_shared/resolve-target-BRvw8Pf7.mjs";import{p as hn,H as mn,a as pn,r as vn,c as yn,b as wn}from"../packem_shared/health-probe-BLnoq_oC.mjs";import{runAdvisor as kn,openShardAccess as Ge}from"@lunora/advisor";import{join as A,relative as J,dirname as Rr}from"@visulima/path";import{runMigrateDataCommand as bn}from"../packem_shared/runMigrateGenerateCommand-CguLEIZp.mjs";import{c as $n}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{l as Sn}from"../packem_shared/wrangler-secrets-C9siMBwN.mjs";const En=Object.freeze({edges:[],nodes:[],modules:[],unresolved:[],version:1}),An=20,Ve=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))},Rn=(e,r)=>{const t=e.modules.map(i=>i.name),n=r.modules.map(i=>i.name),o=e.edges.map(i=>Ve(i)),s=r.edges.map(i=>Ve(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,An).map(s=>` ${e} ${s}`),o=t.length-n.length;return[`${r}:`,...n,...o>0?[` … and ${o.toString()} more`]:[]]},Tn=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
+ ${r.join(`
3
+ `)}`},_n=(e,r)=>p(e,".lunora",r===void 0?"architecture.json":`architecture.${r}.json`),Cn=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}},In=e=>{const{cwd:r,environment:t,logger:n}=e,o=_n(r,t),s=Cn(o),i=e.current??(s===void 0?void 0:En);if(i===void 0)return;const a=s===void 0?void 0:Tn(Rn(s,i));return a!==void 0&&n.info(a),()=>{try{hr(j(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)}`)}}},Pn=e=>{const{cwd:r,env:t,logger:n,mintedSecretsFile:o}=e;try{const s=_e(r),i=s?.workerName??Pe(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{}},jn=/\/index$/u,On=/[^\dA-Za-z]/gu,Dn=e=>e.replace(jn,"").split("/").map(r=>r.replaceAll(On,"_")),Nn=e=>Dn(e).join("_"),Ln=/[^a-z0-9-]/gu,xn=/-$/u,Ke=7,Mn=(e,r)=>{const t=e.toLowerCase(),n=t.replaceAll(Ln,"-");if(n===t&&n.length<=r)return n;const o=an("sha256").update(t).digest("hex").slice(0,Ke-1);return`${n.slice(0,r-Ke).replace(xn,"")}-${o}`},Fn=32,Tr=15e3,Un=5432,Bn=3306,Wn=/[^A-Za-z0-9]/gu,Y=e=>`LUNORA_${e.replaceAll(Wn,"_").toUpperCase()}_URL`,Hn=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)}},qn=(e,r)=>Mn(`${e}-${r}`,Fn),ze=e=>e==="postgresql"?"postgres":e==="mariadb"?"mysql":e,Gn=e=>e==="mysql"?Bn:Un,Vn=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===""?Gn(ze(t)):Number(r.port),scheme:ze(t),user:decodeURIComponent(r.username)}}catch{return}},Kn=(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(" ")},_r=e=>(Array.isArray(e)?e:[]).flatMap((r,t)=>{const{binding:n,id:o}=typeof r=="object"&&r!==null?r:{};return typeof n=="string"&&o===wr?[{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}`},zn=e=>typeof e=="string"||typeof e=="number"?e.toString():void 0,Jn=["scheme","host","port","database","user"],Yn=e=>e==="postgresql"?"postgres":e,Je=(e,r)=>{const t=zn(r);return e==="scheme"?Yn(t):t},Ye=50,Xn=async(e,r)=>{for(let t=1;t<=Ye;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(Ye)} pages, so "${r}" can't be shown to be absent`)},Qn=async(e,r,t,n)=>{const o=n?{caching:{disabled:!0}}:{},s=await Xn(e,r);if(typeof s?.id=="string"){const c=Jn.filter(d=>Je(d,s.origin?.[d])!==Je(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}},Zn=(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.`,eo=async(e,r)=>{const t=qn(e.workerName,e.binding),{id:n,reused:o}=await Qn(async(s,i)=>Er({accountId:e.accountId,apiToken:e.token,...e.fetch===void 0?{}:{fetch:e.fetch},init:{...i,signal:AbortSignal.timeout(Tr)},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:kr(r,[...e.path,e.index,"id"],n)}},ro=e=>e===void 0||e===""?void 0:e,De=e=>{const r=p(j(e),".wrangler","deploy","config.json");try{const{configPath:t}=JSON.parse(E(r,"utf8"));return typeof t=="string"?I(j(r),t):void 0}catch{return}},to=(e,r,t,n,o)=>{const s=De(e);if(s===void 0||s===e)return;if(n.built!==n.deployed){o.warn(`the build output ${s} was made for ${n.built===void 0?"the default environment":`"${n.built}"`}, not ${n.deployed===void 0?"the default environment":`"${n.deployed}"`}, so the "${r}" Hyperdrive id was not written there. Build with CLOUDFLARE_ENV set to the environment you deploy, then deploy again.`);return}let i;try{i=P(s)}catch{return}const a=_r(i.parsed?.hyperdrive).find(c=>c.binding===r);a!==void 0&&X(s,kr(i.text,["hyperdrive",a.index,"id"],t),"utf8")},no=(e,r)=>{const t=typeof e.name=="string"&&e.name!==""?e.name:"lunora";if(r===void 0)return t;const n=e.env?.[r]?.name;return typeof n=="string"&&n!==""?n:`${t}-${r}`},Ne=(e,r)=>{const t=O(e),n=t===void 0?void 0:P(t).parsed;if(t===void 0||n===void 0)return;const o=r===void 0?void 0:n.env?.[r],s=_r(r===void 0?n.hyperdrive:o?.hyperdrive);return s.length===0?void 0:{accountId:o?.account_id??n.account_id,entries:s,path:r===void 0?["hyperdrive"]:["env",r,"hyperdrive"],workerName:no(n,r),wranglerPath:t}},oo=(e,r,t)=>{const n=Hn(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=Zn(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}}},so=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\`.`)},io=async(e,r)=>{const t=O(e.cwd),n=t===void 0?void 0:P(t).parsed,o=e.wranglerEnvironment===void 0?n:n?.env?.[e.wranglerEnvironment],{accountId:s,token:i}=Sr(r,o?.account_id??n?.account_id);if(s===void 0||i===void 0)return;const a=async(c,l)=>Er({accountId:s,apiToken:i,...e.fetch===void 0?{}:{fetch:e.fetch},init:{...l,signal:AbortSignal.timeout(Tr)},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!==wr&&await so(a,l,d,e.logger)}},ao=async e=>{const r=e.environment??process.env;e.disableCaching===!0&&e.checkOnly!==!0&&e.dryRun!==!0&&await io(e,r);const t=Ne(e.cwd,e.wranglerEnvironment);if(t===void 0)return;const{entries:n,path:o,wranglerPath:s}=t,{accountId:i,token:a}=Sr(r,t.accountId),c=n.map(({binding:d})=>{const u=r[Y(d)]??"";return{binding:d,origin:Vn(u),supplied:u!==""}}),l=oo(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 h=c[d]?.origin;if(!(h===void 0||a===void 0||i===void 0))try{const{id:g,text:v}=await eo({accountId:i,binding:u,disableCaching:e.disableCaching===!0,fetch:e.fetch,index:f,logger:e.logger,origin:h,path:o,token:a,workerName:t.workerName,wranglerPath:s},E(s,"utf8"));X(s,v,"utf8"),to(s,u,g,{built:ro(r.CLOUDFLARE_ENV),deployed:e.wranglerEnvironment},e.logger)}catch(g){const v=g instanceof Error?g.message:String(g),m=`deploy blocked: the "${u}" Hyperdrive config could not be set up: ${Kn(v,c[d]?.origin)}`;return e.logger.error(m),m}}},co=(e,r)=>{const t=Ne(e,r.env)?.entries[0]?.binding;if(t===void 0)return;const n=`prepare blocked: the "${t}" Hyperdrive binding still has its placeholder id. Run \`lunora deploy\` with ${Y(t)} set to create the config, or put the id from \`wrangler hyperdrive create\` in wrangler.jsonc.`;return r.logger.error(n),n},lo=(e,r)=>{const t=Ne(e,r.env)?.entries[0]?.binding;if(t===void 0)return;const n=`deploy blocked: the "${t}" Hyperdrive binding has no config, and a --temporary deploy cannot create one: it would be made in your account while the Worker goes to a temporary one, which a temporary account has no database for. Deploy without --temporary.`;return r.logger.error(n),n},Cr=async(e,r,t,n,o="create")=>{if(n!=="cloudflare")return;if(t==="prepare")return co(e,r);if(r.temporary===!0)return lo(e,r);const s=r.clientBuildEnvironment===void 0?void 0:{...process.env,CLOUDFLARE_ENV:r.clientBuildEnvironment},i=Ce(e,M(e),r.discoveryCache);return i.error!==void 0&&r.logger.warn(`could not read the schema (${i.error}), so Hyperdrive configs are set up with query caching off.`),ao({checkOnly:o==="check",cwd:e,disableCaching:i.error!==void 0||i.info?.hasHyperdriveGlobalTable===!0,dryRun:r.dryRun,environment:s,logger:r.logger,wranglerEnvironment:r.env})},he=[".ts",".tsx",".mts",".js",".mjs"],uo=/^[a-z]+:/u,Xe=/\.[cm]?js$/u,fo=e=>!e.startsWith(".")&&!e.startsWith("/")&&!e.startsWith("#")&&!uo.test(e),go=e=>e.split("/").slice(0,e.startsWith("@")?2:1).join("/"),ho=e=>e.split(x).some(r=>r==="_generated"||r==="node_modules"),mo=e=>e.split(x).includes("node_modules"),Qe=(e,r)=>{const t=I(j(e),r),n=Xe.test(t)?t.replace(Xe,""):void 0;return[t,...n===void 0?[]:he.map(s=>`${n}${s}`),...he.map(s=>`${t}${s}`),...he.map(s=>p(t,`index${s}`))].find(s=>b(s)&&Re(s).isFile())},po=/^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}},vo=(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)}}},yo=(e,r)=>{const t=p(e,r,"_generated"),n=K(e).find(o=>po.test(o));return[...b(t)?K(t).filter(o=>o.endsWith(".ts")).map(o=>p(t,o)):[],...n===void 0?[]:[p(e,n)]]},wo=e=>{const r=k.findConfigFile(e,n=>k.sys.fileExists(n));if(r===void 0)return!1;const t=k.readConfigFile(r,n=>k.sys.readFile(n));return k.parseJsonConfigFileContent(t.config??{},k.sys,j(r)).options.verbatimModuleSyntax===!0},Ze=e=>e!==void 0&&(k.isNamedImports(e)||k.isNamedExports(e))&&e.elements.length>0&&e.elements.every(r=>r.isTypeOnly),ko=(e,r)=>{if(k.isImportDeclaration(e)){const{importClause:t}=e;return!(t?.phaseModifier===k.SyntaxKind.TypeKeyword||!r&&t?.name===void 0&&Ze(t?.namedBindings))&&k.isStringLiteral(e.moduleSpecifier)?e.moduleSpecifier.text:void 0}if(k.isExportDeclaration(e))return!(e.isTypeOnly||!r&&Ze(e.exportClause))&&e.moduleSpecifier!==void 0&&k.isStringLiteral(e.moduleSpecifier)?e.moduleSpecifier.text:void 0},bo=e=>{if(!k.isCallExpression(e)||e.expression.kind!==k.SyntaxKind.ImportKeyword)return;const[r]=e.arguments;return r!==void 0&&k.isStringLiteralLike(r)?r.text:void 0},$o=(e,r)=>{const t=k.createSourceFile(e,E(e,"utf8"),k.ScriptTarget.Latest,!1),n=[],o=[],s=i=>{const a=bo(i),c=a??ko(i,r);c?.startsWith(".")||c?.startsWith("#")?o.push(c):a!==void 0&&fo(a)&&n.push(a),k.forEachChild(i,s)};return s(t),{dynamicPackages:n,relative:o}},So=(e,r)=>{for(let t=e;;t=j(t)){if(b(p(t,"node_modules",r,"package.json")))return!0;if(j(t)===t)return!1}},Eo=(e,r,t)=>{const n=wo(e),o=new Set,s=new Set,i=r!==void 0&&b(I(e,r))?[I(e,r)]:yo(e,t);for(let a=i.shift();a!==void 0;a=i.shift())if(!o.has(a)&&!mo(L(e,a))){o.add(a);const{dynamicPackages:c,relative:l}=$o(a,n);if(!ho(L(e,a)))for(const d of c)s.add(d);i.push(...l.flatMap(d=>{if(!d.startsWith("#"))return Qe(a,d)??[];const u=vo(e,d);return u===void 0?[]:Qe(p(e,"package.json"),u)??[]}))}return[...s].filter(a=>So(e,go(a))).toSorted((a,c)=>a.localeCompare(c))},Ao=18787,er=3,be=12e4,Ro=5e3,W=10,Ir=new Set([".js",".mjs",".mts",".ts",".tsx"]),To=/\(void 0\)|is not a function|before initialization|of undefined/u,_o=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",Co=e=>{const r=M(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=it(o);Ir.has(s)&&!o.split(x).some(i=>i==="_generated"||i==="node_modules")&&t.set(Nn(o.slice(0,-s.length).split(x).join("/")),p(r,o))}return t},rr=e=>To.test(e)?`
5
+ hint: if this module is part of a circular import, an import it reads is still undefined while it evaluates`:"",Io=(e,r)=>{const t=Co(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}${rr(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}${rr(i)}`),...o]},te=e=>{for(const r of Ir)for(const t of[`${e}${r}`,p(e,`index${r}`)])if(b(t))return t},Po=(e,r)=>{const t=p(e,r,"_generated"),n=a=>{try{return E(p(t,a),"utf8")}catch{return""}},o=n("app.ts"),s=[],i=(a,c)=>{c!==void 0&&s.push({file:c,kind:a,label:L(e,c).split(x).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},jo=/\.[cm]?js$/u,Oo=/(?:await|=>|return|[=[,])\s*import\(\s*"([^"]+)"\s*\)(?!\s*\.(?!(?:then|catch|finally)\b))/gu,Do=(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 E(p(n,a),"utf8").matchAll(Oo)){const l=c[1]??"",d=l.startsWith("."),u=d?te(I(n,l.replace(jo,""))):l;u!==void 0&&!o.has(u)&&(o.add(u),s.push({file:u,kind:"module",label:d?L(e,u).split(x).join("/"):l}))}return s};class C extends Error{skipped;constructor(r,t=!1){super(r),this.skipped=t}}const No=/^[$_\p{ID_Start}][$\u200C\u200D\p{ID_Continue}]*$/u,Pr=(e,r,t)=>{const n=t??O(e),o=n===void 0?void 0:P(n).parsed;if(o===void 0)return{durableObjectClasses:[],hasContainers:!1,main:void 0,workflowClasses:[]};const{merged:s}=le(o,r),i=a=>[...new Set(a.flatMap(c=>c?.script_name===void 0&&typeof c?.class_name=="string"&&No.test(c.class_name)?[c.class_name]:[]))];return{durableObjectClasses:i(s.durable_objects?.bindings??[]),hasContainers:(s.containers??[]).length>0,main:s.main,workflowClasses:i(s.workflows??[])}},Lo=({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{durableObjectClasses:s,hasContainers:i,main:a,workflowClasses:c}=Pr(t,n,r),l=e??a,d=r??O(t);let u;if(d!==void 0&&De(d)!==void 0)u={stubs:{durableObjects:s,workflows:c}};else if(typeof l=="string"&&!l.startsWith("virtual:")&&b(I(t,l)))u={main:l};else return{skip:"the Worker entry is not a file on disk"};if(i)return{skip:"the project declares containers, which `wrangler dev` would build locally before the real container build"};const f=Nt(t,process.env,n,r);return f.length>0?{skip:`the Hyperdrive binding ${f.join(", ")} has no local database for wrangler dev`}:{base:u,configFile:d}},xo=/The Workers runtime failed to start|Build failed with \d+ error/u,Mo=/\[ERROR\]|Uncaught/u,tr=e=>{const r=e.map(o=>dn(o).trim()).filter(o=>o!==""),t=r.filter(o=>Mo.test(o)),n=t.length>0?t.slice(0,10):r.slice(-10);return n.length===0?"":`
6
+ ${n.map(o=>` ${o}`).join(`
7
+ `)}`},$e=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 C(`the smoke Worker's runtime did not start, so nothing was evaluated:${tr(t)}
8
+ Fix the entry, or pass --no-smoke-load to ship anyway.`):d instanceof Error&&d.name==="TimeoutError"?new C(n===void 0?`the smoke Worker accepted the connection but answered no request within ${String(be/1e3)}s, so its runtime did not start:${tr(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 C(`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}},Se=(e,r)=>{const t=e.headers.get("content-type")??"no content type",n=r.replaceAll(/\s+/gu," ").trim().slice(0,120);return new C(`the smoke Worker answered with something other than the probe's result (HTTP ${String(e.status)}, ${t}${n===""?"":`: ${n}`}). A route that does not send /_lunora/* to the Worker first answers with the app's assets, so check run_worker_first. Pass --no-smoke-load to ship anyway.`)},nr=async(e,r)=>{const t=await $e(e),n=t.body?.message;if(t.body?.run!==r||n!==void 0&&typeof n!="string")throw Se(t.response,t.text);return n},Fo=async e=>{const{deferred:r,functions:t,integrationModules:n,runId:o,...s}=e,i=await $e({...s,pending:void 0,query:"step=ping"});if(typeof i.body?.run!="string")throw Se(i.response,i.text);if(i.body.run!==o)return;let a=0,c=[];if(t){const d=await $e({...s,pending:"the lazy function modules",query:"step=functions"}),{checked:u,failures:f}=d.body??{};if(d.body?.run!==o||typeof u!="number"||!Array.isArray(f)||!f.every(h=>_o(h)))throw Se(d.response,d.text);a=u,c=f}for(const[d,u]of r.entries()){const f=await nr({...s,pending:`${u.kind} module ${u.label}`,query:`step=deferred&index=${String(d)}`},o);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 nr({...s,pending:`import(${JSON.stringify(d)})`,query:new URLSearchParams({specifier:d,step:"integration"}).toString()},o);u!==void 0&&l.push({message:u,specifier:d})}return{checked:a,deferredChecked:r.length,failures:c,integrations:{checked:n.length,failures:l}}},Ee=(e,r)=>{try{process.kill(-e,r)}catch{}},or=e=>{try{return process.kill(-e,0),!0}catch{return!1}},Uo=e=>{const r=()=>{Ee(e,"SIGKILL")},t=o=>{r(),process.kill(process.pid,o)},n=()=>{process.removeListener("exit",r),process.removeListener("SIGINT",t),process.removeListener("SIGTERM",t)};return process.once("exit",r),process.once("SIGINT",t),process.once("SIGTERM",t),n},me=async e=>{if(e===void 0)return;e.dispose();const{pid:r}=e;Ee(r,"SIGTERM");const t=Date.now()+Ro;for(;or(r)&&Date.now()<t;)await cn(50);or(r)&&Ee(r,"SIGKILL")},Bo=e=>lt(e).catch(async r=>{if(!await ut(e.port))throw r}),Wo=({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 "),Ho=(e,r,t)=>{const{checked:n,deferredChecked:o,failures:s,integrations:i}=r;if(s.length===0&&i.failures.length===0){t.success(`${Wo(r)} evaluate cleanly`);return}const a=Io(e,s),c=a.length>W?[` …and ${String(a.length-W)} more module(s)`]:[];throw new C([...s.length===0?[]:[`${String(s.length)} of ${o===0?`${String(n)} lazy function(s)`:`${String(n+o)} lazy module(s)`} fail to load:`,...a.slice(0,W),...c],...i.failures.length===0?[]:[`${String(i.failures.length)} of ${String(i.checked)} integration module(s) fail to load in workerd (each would fail its first use instead):`,...i.failures.slice(0,W).map(({message:l,specifier:d})=>` import("${d}"): ${l}`),...i.failures.length>W?[` …and ${String(i.failures.length-W)} more integration module(s)`]:[]],"Fix the module, or pass --no-smoke-load to ship anyway."].join(`
10
+ `))},qo=(e,r,t)=>{if(e instanceof C&&!e.skipped)return t.error(e.message),e.message;if(e instanceof C){t.warn(`smoke-load skipped: ${e.message}`);return}const n=r.slice(-5).join(`
11
+ `),o=`the smoke Worker did not start (${e instanceof Error?e.message:String(e)})${n===""?"":`
12
+ ${n}`}. Either the entry fails when it loads, or local wrangler cannot run the project (a remote-only binding or a missing assets directory). Fix whichever it is, or pass --no-smoke-load to ship anyway.`;return t.error(o),o},Go=e=>{try{return hr(p(e,".lunora"),{recursive:!0}),ot(p(e,".lunora","smoke-"))}catch(r){throw new C(`could not create a directory for the check (${r instanceof Error?r.message:String(r)})`,!0)}},Vo=(e,r)=>{if("main"in r)return`export * from ${V(I(e,r.main))};`;const{durableObjects:t,workflows:n}=r.stubs;return['import { DurableObject, WorkflowEntrypoint } from "cloudflare:workers";',...t.map(o=>`export class ${o} extends DurableObject {}`),...n.map(o=>`export class ${o} extends WorkflowEntrypoint { async run() {} }`)].join(`
13
+ `)},Ko=async e=>{const{base:r,configPath:t,cwd:n,deferred:o,directory:s,environment:i,functionsFile:a,integrationModules:c,preferred:l,toolchain:d}=e;try{const u=p(s,"entry.ts"),f=$r(),h=c.map(S=>` [${V(S)}, () => import(${V(S)})],`).join(`
14
+ `);X(u,`${Vo(n,r)}
15
+ ${a===void 0?"":`import { loadAllFunctions } from ${V(a)};
16
+ `}
17
+ const runId = ${JSON.stringify(f)};
9
18
 
10
- const providerToItem = (provider) => {
11
- const value = provider.trim().toLowerCase();
12
- const match = AUTH_PROVIDER_OPTIONS.find(
13
- (option) => option.value === value || option.label.toLowerCase() === value || value === "auth0" && option.value === "auth-auth0" || value === "clerk" && option.value === "auth-clerk"
14
- );
15
- return match?.value;
16
- };
17
- const resolveAuthItem = async (options) => {
18
- if (options.provider !== void 0 && options.provider !== "") {
19
- const item = providerToItem(options.provider);
20
- if (item === void 0) {
21
- options.logger.warn(`add: unknown --provider "${options.provider}" — using "${DEFAULT_AUTH_ITEM}" (email & password).`);
22
- return DEFAULT_AUTH_ITEM;
23
- }
24
- return item;
25
- }
26
- if (options.yes === true) {
27
- return DEFAULT_AUTH_ITEM;
28
- }
29
- const select = options.promptSelect ?? ((message, choices, settings) => tuiSelect(message, choices, settings));
30
- return promptAuthProvider(select);
31
- };
32
- const textPrompt = (options) => options.promptText ?? ((message, settings) => tuiText(message, settings));
33
- const resolveStorageBucketName = async (options) => {
34
- const projectName = basename(options.cwd ?? process.cwd());
35
- if (options.bucket !== void 0 && options.bucket !== "") {
36
- const sanitized = sanitizeBucketName(options.bucket);
37
- if (sanitized !== void 0) {
38
- return sanitized;
39
- }
40
- const fallback = deriveBucketName(projectName);
41
- options.logger.warn(`add: "${options.bucket}" isn't a valid R2 bucket name (lowercase alphanumeric + hyphens, 3–63 chars) — using "${fallback}".`);
42
- return fallback;
43
- }
44
- if (options.yes === true) {
45
- return deriveBucketName(projectName);
46
- }
47
- return promptBucketName(textPrompt(options), projectName);
48
- };
49
- const resolveMailDestination = async (options) => {
50
- const warn = (message) => {
51
- options.logger.warn(`add: ${message}`);
52
- };
53
- if (options.mailTo !== void 0 && options.mailTo !== "") {
54
- return resolveTypedDestination(options.mailTo, warn);
55
- }
56
- if (options.yes === true) {
57
- return void 0;
58
- }
59
- return resolveTypedDestination(await textPrompt(options)(MAIL_DESTINATION_PROMPT, { placeholder: "you@yourdomain.com" }), warn);
60
- };
61
- const resolveAuthDatabaseName = async (options) => {
62
- const projectName = basename(options.cwd ?? process.cwd());
63
- if (options.db !== void 0 && options.db !== "") {
64
- const sanitized = sanitizeDatabaseName(options.db);
65
- if (sanitized !== void 0) {
66
- return sanitized;
67
- }
68
- const fallback = deriveDatabaseName(projectName);
69
- options.logger.warn(`add: "${options.db}" isn't a usable D1 database name — using "${fallback}".`);
70
- return fallback;
71
- }
72
- if (options.yes === true) {
73
- return deriveDatabaseName(projectName);
74
- }
75
- return promptDatabaseName(textPrompt(options), projectName);
76
- };
77
- const resolveFeatureItems = async (feature, options) => {
78
- if (feature.kind === "auth") {
79
- return [await resolveAuthItem(options)];
80
- }
81
- if (feature.kind === "email") {
82
- return [EMAIL_ITEM];
83
- }
84
- return [feature.item];
85
- };
86
- const runAddFeature = async (options) => {
87
- const cwd = options.cwd ?? process.cwd();
88
- const feature = options.feature === void 0 ? void 0 : normalizeFeature(options.feature);
89
- if (feature === void 0) {
90
- options.logger.error("add requires a feature or registry item. Usage: lunora add <auth|email|storage|crons|presence|…>");
91
- return { code: 1, items: [] };
92
- }
93
- if (!existsSync(join(cwd, "lunora")) || findWranglerFile(cwd) === void 0) {
94
- options.logger.error("add: not a Lunora project here (need a lunora/ directory and a wrangler.jsonc). Run `lunora init` first.");
95
- return { code: 1, items: [] };
96
- }
97
- const items = await resolveFeatureItems(feature, options);
98
- const transforms = [];
99
- if (items.includes("storage")) {
100
- const bucketName = await resolveStorageBucketName(options);
101
- transforms.push((manifest) => withStorageBucketName(manifest, bucketName));
102
- }
103
- if (items.includes("mail")) {
104
- const destination = await resolveMailDestination(options);
105
- if (destination !== void 0) {
106
- transforms.push((manifest) => withMailDestination(manifest, destination));
107
- }
108
- }
109
- if (items.some((name) => name === "auth" || name.startsWith("auth-"))) {
110
- const databaseName = await resolveAuthDatabaseName(options);
111
- transforms.push((manifest) => withAuthDatabaseName(manifest, databaseName));
112
- }
113
- const transformManifest = transforms.length > 0 ? (manifest) => {
114
- let result2 = manifest;
115
- for (const transform of transforms) {
116
- result2 = transform(result2);
117
- }
118
- return result2;
119
- } : void 0;
120
- const result = await runAddCommand({
121
- allowUnsafeSource: options.allowUnsafeSource,
122
- cwd,
123
- from: options.from,
124
- logger: options.logger,
125
- names: [...items],
126
- ref: options.ref,
127
- source: options.source,
128
- transformManifest,
129
- yes: true
130
- });
131
- return { code: result.code, items };
132
- };
133
- const execute = defineHandler(async ({ argument, cwd, logger, options }) => {
134
- const formatError = validateOutputFormat("add", options.format);
135
- if (formatError !== void 0) {
136
- logger.error(formatError);
137
- return { code: 1 };
138
- }
139
- const effectiveLogger = loggerForFormat(options.format, logger);
140
- const result = await runAddFeature({
141
- allowUnsafeSource: options.allowUnsafeSource === true,
142
- bucket: options.bucket,
143
- cwd,
144
- db: options.db,
145
- feature: argument[0],
146
- from: options.from,
147
- logger: effectiveLogger,
148
- mailTo: options.mailTo,
149
- provider: options.provider,
150
- ref: options.ref,
151
- source: options.source,
152
- yes: options.yes === true
153
- });
154
- if (isJsonFormat(options.format)) {
155
- printJson({ code: result.code, items: result.items });
156
- }
157
- return { code: result.code };
158
- });
19
+ // Deferred event modules, evaluated one per request so a module that throws on import blocks like a function module does.
20
+ const deferred = [
21
+ ${o.map(S=>` () => import(${V(S.file)}),`).join(`
22
+ `)}
23
+ ];
159
24
 
160
- export { execute, runAddFeature };
25
+ const integrationLoaders = new Map<string, () => Promise<unknown>>([
26
+ ${h}
27
+ ]);
28
+
29
+ export default {
30
+ async fetch(request: Request) {
31
+ const url = new URL(request.url);
32
+ const step = url.searchParams.get("step");
33
+
34
+ if (step === "functions") {
35
+ return Response.json({ ...${a===void 0?"{ checked: 0, failures: [] }":"(await loadAllFunctions())"}, run: runId });
36
+ }
37
+
38
+ const load =
39
+ step === "deferred"
40
+ ? deferred[Number(url.searchParams.get("index"))]
41
+ : step === "integration"
42
+ ? integrationLoaders.get(url.searchParams.get("specifier") ?? "")
43
+ : undefined;
44
+
45
+ if (load !== undefined) {
46
+ try {
47
+ await load();
48
+ } catch (error) {
49
+ return Response.json({ message: error instanceof Error ? error.message : String(error), run: runId });
50
+ }
51
+ }
52
+
53
+ return Response.json({ run: runId });
54
+ },
55
+ };
56
+ `);const g=await ln(l),{args:v,command:m}=z(F(n),d.dev({configPath:t===void 0?void 0:L(n,t),environment:i,extraArgs:[L(n,u),"--local","--local-protocol","http","--ip","127.0.0.1","--port",String(g),"--persist-to",L(n,p(s,"state"))]}));return{args:v,command:m,port:g,runId:f}}catch(u){throw new C(`could not prepare the check (${u instanceof Error?u.message:String(u)})`,!0)}},zo=async e=>{const{composedEntry:r,cwd:t,environment:n,launcher:o,logger:s,toolchain:i}=e,a=M(t),c=p(t,a,"_generated","functions.ts"),l=b(c)&&E(c,"utf8").includes("export const loadAllFunctions"),d=l?c:void 0,u=Po(t,a);if(!l&&u.length===0)return;const f=[...u,...Do(t,a,u)],h=Lo(e);if("skip"in h){s.warn(`smoke-load skipped: ${h.skip}, so lazy modules and import()ed integration modules are not evaluated before deploy`);return}const{base:g,configFile:v}=h,m=Eo(t,r??Pr(t,n,e.configPath).main,a),S=[];let D,R;const q=Date.now()+be,T=process.platform!=="win32",tt=(U,Q,Z)=>{const B=sn(U,[...Q],{cwd:Z.cwd,detached:T,shell:Z.shell,stdio:["ignore","pipe","pipe"]});return T&&B.pid!==void 0&&(R={dispose:Uo(B.pid),pid:B.pid}),B};try{D=Go(t),s.info(d===void 0?"smoke-loading import()ed integration modules in workerd":"smoke-loading lazy function modules in workerd");let U=Ao;for(let Q=0;Q<er;Q+=1){const{args:Z,command:B,port:ge,runId:nt}=await Ko({base:g,configPath:v,cwd:t,deferred:f,directory:D,environment:n,functionsFile:d,integrationModules:m,preferred:U,toolchain:i}),Be=new AbortController;U=ge+1;const We=await Bo({args:Z,command:B,cwd:t,spawn:o??tt,label:"wrangler dev (smoke-load)",notFound:"`wrangler` was not found",onLine:G=>{S.push(G),xo.test(G)&&Be.abort()},port:ge,readyTimeoutMs:Math.max(0,q-Date.now()),shell:process.platform==="win32"});if(We===void 0){await me(R),R=void 0;continue}try{const G=await Fo({deadline:q,deferred:f,functions:d!==void 0,integrationModules:m,output:S,port:ge,runId:nt,startupFailed:Be.signal});if(G!==void 0){Ho(t,G,s);return}}finally{await We.stop(),await me(R),R=void 0}}throw new C(`the smoke port was answered by other runs on all ${String(er)} attempts`,!0)}catch(U){return qo(U,S,s)}finally{if(await me(R),D!==void 0)try{oe(D,{force:!0,recursive:!0})}catch{}}},Jo=(e,r)=>r===void 0?e:I(e,r),Yo=async e=>{if(e.targets.length===0)return{builtTags:[],code:0};if(!(e.railpackAvailable??fn)()){const n="deploy blocked: a container uses `image: { build }` (Railpack), but Railpack isn't ready. Install the `railpack` CLI and start a BuildKit instance, e.g. `docker run --rm --privileged -d --name buildkit moby/buildkit` then `export BUILDKIT_HOST=docker-container://buildkit`. Alternatively switch the container's `image` to a Dockerfile path or a pre-built registry reference.";return e.logger.error(n),{builtTags:[],code:1,error:n}}const r=e.spawner??H,t=[];for(const n of e.targets){const o=un(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}},Xo=new Set(["0.0.0.0","[::1]","[::]","localhost"]),Qo=[".local",".localhost"],Zo=["[fc","[fd"],es=/^\[fe[89ab][0-9a-f]:/u,rs=/^[a-z]+:\/\//u,sr=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},ir="[::ffff:",ts=e=>{if(!e.startsWith(ir)||!e.endsWith("]"))return;const r=e.slice(ir.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(".")},jr=e=>{let r=e.length;for(;r>0&&e[r-1]===".";)r-=1;return e.slice(0,r).toLowerCase()},ns=e=>{const r=e.toLowerCase(),t=ts(r);return t!==void 0?sr(t):Xo.has(r)||Qo.some(n=>r.endsWith(n))||Zo.some(n=>r.startsWith(n))||es.test(r)||sr(r)},Or=e=>{const r=O(e);return r===void 0?void 0:P(r).parsed},Dr=(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}`},ie=(e,r)=>{let t=e.length;for(;t>0&&e[t-1]===r;)t-=1;return e.slice(0,t)},os=e=>{const r=e.replace(rs,""),t=r.indexOf("/"),n=(t===-1?r:r.slice(0,t)).toLowerCase(),o=t===-1?"":ie(r.slice(t),"*");return o==="/"?n:`${n}${o}`},ar=e=>[e?.route,...Array.isArray(e?.routes)?e.routes:[]].flatMap(t=>{const n=typeof t=="string"?t:t?.pattern;return typeof n=="string"&&n!==""?[os(n)]:[]}),ss=(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!==""&&!`${ie(r,"/")}/`.startsWith(s)))return s.length*1e6+(i?0:5e5)+o.length},is=e=>e!==void 0&&(Object.hasOwn(e,"route")||Object.hasOwn(e,"routes")),Nr=(e,r)=>{const t=ar(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:is(i)?ar(i):t}});return[{id:"top",label:"production",routes:t},...o]},as=(e,r,t,n)=>{const o=r===void 0?"top":`env:${r}`,s=Nr(e,r).flatMap(c=>c.routes.flatMap(l=>{const d=ss(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=>Gt(`${e.origin}${e.pathname}`),cs=(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=`${ie(i.pathname,"/")}/`;if(i.origin!==t.origin||!`${ie(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}`},Lr=(e,r,t,n,o,s)=>{const i=as(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=Nr(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}`},ds=(e,r,t,n,o,s)=>{const i=Or(e);if(t.endsWith(".workers.dev")){const a=Dr(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 Lr(i,r,t,n,o,s)},ls=(e,r,t,n,o)=>{const s=Or(e),i=jr(t.hostname);if(i.endsWith(".workers.dev")){const a=Dr(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 Lr(s,r,i,t.pathname,n,o)},us=(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=jr(n.hostname);if(ns(i))return`${o}: it is a local or private address, not the worker this deploy ships to`;const a=cs(e,r,n,o,s);return a===void 0?ds(e,r,i,n.pathname,o,s):a??ls(e,r,n,o,s)},xr=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")}},fs=(e,r=$r())=>I(e,".lunora",`vite-bundle-meta-${r}.json`),Mr="LUNORA_CLIENT_BUILD",gs="virtual:lunora/worker",Ae=(e,r)=>["ts","mts","cts","js","mjs","cjs"].some(t=>b(p(e,`${r}.config.${t}`))),Fr=e=>Ae(e,"rsbuild")?"rsbuild":Ae(e,"vite")?"vite":void 0,hs=e=>Ae(e,"vite")?"vite":Fr(e),ms=e=>{try{const{scripts:r}=JSON.parse(E(p(e,"package.json"),"utf8"));return typeof r?.build=="string"&&r.build!==""}catch{return!1}},ue=(e,r)=>{if(process.env[Mr]==="1")return;const t=O(e),n=t===void 0?void 0:P(t).parsed,o=n?.main===gs,s=(o?hs(e):Fr(e))??(ms(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||ft(e).class!=="C"||a!==void 0?s:void 0},ps=async(e,r,t)=>{const n=t.spawner??H,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=xr(e),a=t.bundleMetaPath??fs(e);oe(p(e,gt),{force:!0});try{const c=await n({args:s.args,command:s.command,cwd:e,env:{[yt]:wt(e),[vt]:t.target,[pt]:a,...t.lazyFunctions?{[mt]:"1"}:{},...t.environment===void 0?{}:{CLOUDFLARE_ENV:t.environment},...t.strictAdvisories===!1?{[ht]:"0"}:{},[Mr]:"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})}},fe=(e,r,t)=>r!==!1&&ue(e,t)!==void 0,vs=(e,r,t)=>fe(e,r,t)&&ue(e,t)!=="script",Le=e=>{const r=e.frameworkBuild===!1?void 0:ue(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`},Ur=async e=>{const r=e.frameworkBuild===!1?void 0:ue(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 ps(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})},cr=e=>Array.isArray(e)?e.filter(r=>r!=null):void 0,xe=(e,r)=>{const t=O(e);if(!t)return;const{parsed:n}=P(t);if(n===void 0)return;const{error:o,merged:s}=le(n,r),i=o===void 0?s:n,{containers:a,d1_databases:c,vars:l}=i;return{containers:cr(a),d1_databases:cr(c),vars:typeof l=="object"&&l!==null&&!Array.isArray(l)?l:void 0}},ys=/^127(?:\.\d{1,3}){3}$/,ws=e=>{try{const{hostname:r}=new URL(e);return r==="localhost"||ys.test(r)||r==="::1"||r==="[::1]"}catch{return!1}},ks=e=>e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.includes("Dockerfile"),bs=(e,r,t,n="deploy",o)=>{const s=(xe(e,o)?.containers??[]).filter(a=>typeof a?.image=="string"&&ks(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},Me=e=>b(A(e,He))?He:void 0,$s=(e,r,t="deploy",n)=>{for(const o of mr(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}}},Ss=(e,r)=>r==="celld"?typeof e=="string"&&e!==qe&&Xt(e):r==="cloudflare"&&e===qe,Es=(e,r,t)=>(xe(e,t)?.d1_databases??[]).find(n=>Ss(n.database_id,r)),As=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}},Rs=(e,r,t,n,o)=>{const s=Es(e,n,o);if(s===void 0)return;const i=`${t} blocked: the "${s.binding??"<unnamed>"}" D1 binding has a placeholder database_id ("${s.database_id??""}")`,a=n==="celld"?`${i}, which celld would use as the database's identity. Set database_id to the database celld should use, then ${t} again.`:`${i}. Run \`lunora doctor --fix\` to create the database and write its id into wrangler.jsonc, or run \`wrangler d1 create <name>\` and paste the id in yourself.`;return r.error(a),a},Ts=(e,r,t="deploy",n)=>{const o=xe(e,n)?.vars;if(!o)return;const s=Object.entries(o).filter(([,a])=>typeof a=="string"&&ws(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},_s=["vite.config.ts","vite.config.mts","vite.config.cts","vite.config.js","vite.config.mjs","vite.config.cjs",...at],Br=/\.(?:[cm]?[jt]s|tsx|jsx)$/u,Wr=/\.(?:test|spec)\.[cm]?[jt]sx?$/u,Hr="allowUnauthenticatedShardAccess",Cs=/[\\/]/u,qr=new Set(["_generated","build","dist","node_modules"]),Gr=(e,r)=>{const t=J(e,r).split(Cs);return Br.test(r)&&!Wr.test(r)&&!ye(t.join("/"))&&t.every(n=>n===".."||!n.startsWith(".")&&!qr.has(n))},dr=(e,r,t)=>{const{parsed:n}=P(r);if(n===void 0)return[];const{error:o,merged:s}=le(n,t),{main:i}=o===void 0?s:n,a=typeof i=="string"?A(Rr(r),i):void 0;return a!==void 0&&b(a)&&Gr(e,a)?[a]:[]},Fe=e=>e===void 0?!1:e.getKind()===y.FalseKeyword?!0:$.isParenthesizedExpression(e)||$.isAsExpression(e)||$.isSatisfiesExpression(e)||$.isTypeAssertion(e)||$.isNonNullExpression(e)?Fe(e.getExpression()):!1,Is=e=>{try{return Re(e).isFile()}catch{return!1}},Ps=new Set(["ELOOP","ENOENT","ENOTDIR"]),ae=(e,r,t)=>{const n=r instanceof Error&&"code"in r&&typeof r.code=="string"?r.code:"";Ps.has(n)||t.push(e)},js=(e,r)=>{try{return Re(e)}catch(t){ae(e,t,r);return}},Vr=(e,r)=>{try{return E(e,"utf8")}catch(t){ae(e,t,r);return}},Kr=(e,r,t,n=new Set)=>{let o;try{o=st(r)}catch(i){return ae(r,i,t),[]}if(n.has(o))return[];n.add(o);let s;try{s=K(r)}catch(i){return ae(r,i,t),[]}return s.flatMap(i=>{const a=A(r,i),c=js(a,t);if(c===void 0)return[];const l=J(e,a).split(x).join("/");return c.isDirectory()?qr.has(i)||i.startsWith(".")||ye(`${l}/`)?[]:Kr(e,a,t,n):c.isFile()&&Br.test(i)&&!Wr.test(i)&&!ye(l)?[a]:[]})},Os=e=>{const r=$.isComputedPropertyName(e)?e.getExpression():e;return $.isStringLiteral(r)||$.isNoSubstitutionTemplateLiteral(r)?r.getLiteralValue():e.getText()},pe=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],Ds=/\.(?:[cm]?js|jsx)$/u,Ns=(e,r)=>{if(!r.startsWith("."))return;const t=I(Rr(e),r),n=t.replace(Ds,"");return[t,...pe.map(s=>`${t}${s}`),...pe.map(s=>A(t,`index${s}`)),...pe.map(s=>`${n}${s}`)].find(s=>Is(s))},Ls=e=>{if(e.getExpression().getText()!=="require")return;const[r]=e.getArguments();return r!==void 0&&($.isStringLiteral(r)||$.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():void 0},xs=e=>{const r=e.getModuleReference();if(!$.isExternalModuleReference(r))return;const t=r.getExpression();return $.isStringLiteral(t)?t.getLiteralValue():void 0},Ms=(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=Vr(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(y.ImportEqualsDeclaration).map(f=>xs(f)),...d.getDescendantsOfKind(y.CallExpression).map(f=>Ls(f))].filter(f=>f!==void 0);for(const f of u){const h=Ns(c,f);h!==void 0&&Gr(t,h)&&!o.has(h)&&(o.add(h),i.push(h),s.push(h))}}return i},Fs=e=>{const r=e.getArgumentExpression();return r!==void 0&&($.isStringLiteral(r)||$.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():void 0},Us=e=>$.isPropertyAccessExpression(e)?e.getName():$.isElementAccessExpression(e)?Fs(e):void 0,Bs=new Set([y.AmpersandAmpersandEqualsToken,y.AmpersandEqualsToken,y.AsteriskAsteriskEqualsToken,y.AsteriskEqualsToken,y.BarBarEqualsToken,y.BarEqualsToken,y.CaretEqualsToken,y.EqualsToken,y.GreaterThanGreaterThanEqualsToken,y.GreaterThanGreaterThanGreaterThanEqualsToken,y.LessThanLessThanEqualsToken,y.MinusEqualsToken,y.PercentEqualsToken,y.PlusEqualsToken,y.QuestionQuestionEqualsToken,y.SlashEqualsToken]),Ws=e=>{const r=e.getOperatorToken().getKind();return!Bs.has(r)||Us(e.getLeft())!==Hr?!1:r!==y.EqualsToken||!Fe(e.getRight())},Hs=(e,r,t)=>{const n=[],o=[...new Set([M(e),"src"])].filter(u=>b(A(e,u))),s=O(e),i=[..._s.map(u=>A(e,u)).filter(u=>b(u)),...s===void 0?[]:dr(e,s,r),...t.flatMap(u=>dr(e,u,r))],a=new Ar({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}),c=o.flatMap(u=>Kr(A(e,u),A(e,u),n));return{sites:[...new Set([...c,...i,...Ms([...i,...c],a,e,n)])].flatMap(u=>{const f=Vr(u,n);if(f===void 0)return[];const h=a.createSourceFile(J(e,u),f,{overwrite:!0}),g=[...h.getDescendantsOfKind(y.PropertyAssignment),...h.getDescendantsOfKind(y.ShorthandPropertyAssignment),...h.getDescendantsOfKind(y.GetAccessor),...h.getDescendantsOfKind(y.MethodDeclaration)].filter(m=>{const S=$.isPropertyAssignment(m)&&Fe(m.getInitializer());return Os(m.getNameNode())===Hr&&!S}).map(m=>m.getStartLineNumber()),v=h.getDescendantsOfKind(y.BinaryExpression).filter(m=>Ws(m)).map(m=>m.getStartLineNumber());return[...g,...v].map(m=>({file:J(e,u),line:m}))}),unreadable:n}},qs=(e,r,t,n,o,s)=>{if(t!=="deploy")return;const{sites:i,unreadable:a}=Hs(e,o,s),c=kn({openShardAccess:i,schema:{tables:[]}},{lints:[Ge]});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(" ")} ${Ge.remediation}`;return r.error(d),d},Gs=(e,r,t,n)=>{const o=qs(e,r.logger,t,r.allowOpenShards===!0,r.env,n);return o===void 0?void 0:{code:w.USAGE,error:o}},Vs=(e,r,t,n)=>{const o=Rs(e,r.logger,t,n,r.env);if(o!==void 0)return{code:w.USAGE,error:o};const s=Ts(e,r.logger,t,r.env);if(s!==void 0)return{code:w.USAGE,error:s};const i=$s(e,r.logger,t,r.discoveryCache);if(i!==void 0)return{code:w.USAGE,error:i};const a=bs(e,r.logger,r.dockerAvailable??gn,t,r.env);return a===void 0?void 0:{code:w.MISSING_DEPENDENCY,error:a}},Ks=/https?:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/u,zs=/https:\/\/[^\s"'<>]+/u,Js=e=>{if(e===void 0)return;const r=Ks.exec(e);return r?r[0]:zs.exec(e)?.[0]},lr=e=>e===void 0?"":` (--env ${e})`,Ys=({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)"}${lr(s.env)}, but this deploy published ${o}${lr(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()))();kt(e,{env:r,linkedAt:i,workerName:Pe(e),workerUrl:o}),t.success(`link: recorded ${o} in .lunora/project.json (run \`lunora link\` to change)`)}catch{}},Xs=async(e,r)=>{const t=new Ar({skipAddingFilesFromTsConfig:!0}),n=A(r,"lunora");let o;try{o=ct(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 bn(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},Qs=async(e,r)=>{const{info:t}=Ce(r,"lunora",e.discoveryCache),n=t?.vectorMetadata??[];if(n.length===0)return;const o=[];for(const a of n){const c=Qt(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 Zt({cwd:r,entries:o,exec:je(F(r),"wrangler",[]),logger:e.logger,spawner:e.spawner??H})).filter(a=>a.status!=="failed").length;i>0&&e.logger.success(`vectorize metadata indexes ready: ${String(i)}/${String(o.length)}`)},ur=5,Zs=2e3,ei=async(e,r,t)=>{if(e.healthCheck!==!0)return;const n=t??Oe({cwd:r,env:e.env});if(n===void 0){const s="--health-check: the deploy succeeded, but no URL to probe could be resolved — wrangler's output carried none and this checkout has no link for this environment. Run `lunora link --url <https://your-worker>` and re-deploy, or drop --health-check.";return e.logger.error(s),{error:s,ok:!1,url:""}}const o=await hn({attempts:ur,baseUrl:n,delayMs:Zs,fetchImpl:e.healthFetch,paths:[mn,pn],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(ur)} attempt(s) — ${o.error}`),{error:o.error,ok:!1,url:o.url})},ri=async(e,r,t,n,o,s)=>{e.isolatedPreview!==!0&&await Qs(e,r);const i=e.migrate?await Xs(e,r):0;return i===0&&o?.(),{code:i,descriptor:t,mintedSecretsFile:s,validation:n}},ti=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:Js(i),workerName:Pe(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?.(),Ys({cwd:e,env:n.env,logger:n.logger,url:c.url}));const l=await ei(n,e,c.url);if(l?.error!==void 0)return{code:w.UNAVAILABLE,deployment:c,descriptor:r,healthCheck:l,mintedSecretsFile:t,validation:a};const d=n.isolatedPreview===!0?void 0:o;return{...await ri(n,e,r,a,d,t),deployment:c,healthCheck:l}},ni=(e,r,t)=>{const n=A(e,N);if(!b(n))return;let o;try{o=pr(E(n,"utf8")).length}catch{return}if(o===0)return;const s=t.toolchain?.secretPut!==void 0;r.warn(s?`Note: \`lunora deploy\` does not push secrets. ${N} has ${String(o)} key(s); if you changed them, run \`lunora env push --yes\` to update the deployed secrets.`:`Note: ${t.name} deploys read no secrets. ${N} has ${String(o)} key(s) that only the dev server sees; a key the app reads from env must be a \`vars\` entry in the deployed config, one it loads from a secret manager at runtime need not.`)},zr=async(e,r)=>{let t=[];try{t=bt(await vr({cache:r,projectRoot:e,schemaDir:M(e)}))}catch{}const n=[...new Set($t(t).map(s=>s.key))];let o=[];try{const s=A(e,N);b(s)&&(o=pr(E(s,"utf8")).map(i=>i.key).filter(i=>br(i)))}catch{}return{fromLocal:o.filter(s=>!n.includes(s)),fromPackages:n,mintableKeys:St(t)}},oi=async(e,r,t,n)=>{const{logger:o}=r,s=r.spawner??H,i=F(e),a=r.env===void 0?"":` --env ${r.env}`,c=n.toolchain?.secretPut;if(c===void 0)return o.error(`deploy target "${n.id}" has no secret store; cannot push secrets`),{minted:[],ok:!1};const l=t.map(f=>({key:f,value:Et()})),d=n.toolchain?.secretBulk;if(d!==void 0&&l.length>=2){const f=z(i,d({environment:r.env,temporary:r.temporary})),h=await s({args:f.args,command:f.command,cwd:e,input:JSON.stringify(Object.fromEntries(l.map(g=>[g.key,g.value])))});if(h.code===0){for(const{key:g}of l)o.success(`generated + pushed ${g}`);return{minted:l,ok:!0}}o.warn(`bulk secret push failed (exit ${String(h.code)}); retrying one key at a time`)}const u=[];for(const{key:f,value:h}of l){const g=c({environment:r.env,key:f,temporary:r.temporary}),v=z(i,g),m=await s({args:v.args,command:v.command,cwd:e,input:h});if(m.code!==0)return o.error(`failed to push secret ${f} (exit ${String(m.code)}); set it manually with \`wrangler secret put ${f}${a}\`.`),{minted:u,ok:!1};u.push({key:f,value:h}),o.success(`generated + pushed ${f}`)}return{minted:u,ok:!0}},si=/^[\w-]+$/u,fr=[".dev.vars",".dev.vars.*","!.dev.vars.example"],ii=(e,r)=>{try{const t=_t(e,fr);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 \`${fr.join("` and `")}\` by hand before committing.`)}},ai=(e,r,t)=>{if(t.length===0)return;const n=t.map(a=>a.key).join(", ");if(r.env!==void 0&&!si.test(r.env)){r.logger.warn(`${n}: minted and pushed for --env ${r.env}, but "${r.env}" isn't a safe filename fragment — the value could not be recorded. Capture it manually if you need it again.`);return}const o=r.env===void 0?N:`${N}.${r.env}`;ii(e,r.logger);const s=A(e,o);let i=b(s)?E(s,"utf8"):"";for(const a of t)i=At(i,a.key,a.value);return Rt(s,i),r.logger.success(r.env===void 0?`${n}: value(s) recorded in ${o}`:`${n}: value(s) recorded in ${o} (kept separate from ${N} so \`lunora dev\` and a plain \`lunora env push\` don't inherit the --env ${r.env} value)`),o},ci=/^<[^>]+>$/u,di=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===""||ci.test(f)?!0:br(d)&&Tt(u)},s=d=>Object.hasOwn(n,d)?`${d} (empty or a placeholder)`:d,{fromLocal:i,fromPackages:a}=await zr(e,r.discoveryCache),c=i.filter(d=>o(d));c.length>0&&r.logger.warn(`${N} key(s) not set in the wrangler vars: ${c.map(d=>s(d)).join(", ")}. ${t.name} has no secret store: a key the app reads from env must be a \`vars\` entry; one it loads from a secret manager at runtime need not.`);const l=a.filter(d=>o(d));return l.length===0?{}:{error:`missing required secret(s) in the wrangler vars: ${l.map(d=>s(d)).join(", ")}. ${t.name} has no secret store and Lunora reads these from env, so each must be a real \`vars\` value in the config the deploy ships — write it there from your secret manager at deploy time rather than committing it. Add them, then re-deploy.`}},li=async(e,r,t,n)=>{if(r.dryRun===!0||r.isolatedPreview===!0)return{};if(n.toolchain?.secretList===void 0)return di(e,r,n);const{logger:o}=r,s=r.env===void 0?"":` --env ${r.env}`;let i;try{i=await(r.secretLister??Sn)({cwd:e,env:r.env,target:n.id,temporary:r.temporary})}catch{return{}}if(!i.ok)return{};const a=new Set(i.names),{fromLocal:c,fromPackages:l,mintableKeys:d}=await zr(e,r.discoveryCache),u=[...l,...c].filter(g=>!a.has(g));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 g of u.filter(v=>!d.has(v)))o.warn(`required secret ${g} is not set on the target — set it with: wrangler secret put ${g}${s}`);const f=u.filter(g=>d.has(g));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:g,ok:v}=await oi(e,r,f,n),m=ai(e,r,g);return v?{mintedSecretsFile:m}:{error:"failed to push required secret(s) — set them manually and re-deploy",mintedSecretsFile:m}}return o.warn(`${String(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}\`.`),{}},Jr=e=>e.format==="json"?!1:e.interactive!==void 0?e.interactive:process.stdout.isTTY&&!process.env.CI,ui=async(e,r)=>{if(r.dryRun===!0)return;const t=mr(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 Yo({cwd:e,logger:r.logger,railpackAvailable:r.railpackAvailable,spawner:r.spawner,targets:t});return n.code===0?void 0:n.error??"railpack build failed"},fi=(e,r,t)=>{if(t!==void 0)try{const n=Bt(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=Wt(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}`)}},gi=async(e,r,t,n,o,s)=>{try{de(n);const i=await vr({cache:s,projectRoot:e,schemaDir:M(e)}),a=Ft(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=Ut(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}`)}fi(e,r,t)},hi=async(e,r,t,n,o,s,i,a,c,l)=>{let d;r?(d=new Ht({name:"dots"}),d.start("running codegen")):t.info("running codegen");try{const u=dt({apiSpec:n,dryRun:!l,lazyFunctions:o,projectRoot:e,target:s,...Mt(e)});d?.succeed("codegen complete"),d||t.success("codegen complete");const f=zt(u.platformDiagnostics,t);if(f.errors.length>0)return{error:f.errors.join("; ")};const{errorAdvisories:h,names:g,shouldBlock:v}=Jt(u.advisories,c);if(v){const S=`${h.length.toString()} ERROR-level ${h.length===1?"advisory":"advisories"} (${g.join(", ")}). Pass --no-strict-advisories to downgrade this to a warning and continue.`;return t.error(S),{error:S}}const m=l?await Ot({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}`}}},gr="--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`.",mi=(e,r)=>({dryRun:r.dryRun,entry:Me(e),environment:r.env,outDir:r.outDir,secretsFile:r.secretsFile,outFile:r.outFile,preview:r.preview,temporary:r.temporary}),Yr=(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=mi(e,r);return yr(t,e,"deploy",s=>n.deploy({...o,configPath:s}))},pi=(e,r,t)=>{const n=Yr(e,r,t),o=Me(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},ve=(e,r)=>({code:w.USAGE,descriptor:void 0,error:e,validation:_,...r}),vi=(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},yi=(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}},Ue=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"},wi=(e,r)=>Ue(r)===void 0?Te(e).services.map(t=>t.wranglerPath):[],Xr=(e,r,t,n,o)=>({cwd:e,environment:r.env,frameworkBuild:n,lazyFunctions:ce(r.lazyFunctions),logger:r.logger,outputJson:r.format==="json"||r.clientBuildOutputJson===!0,spawner:o,strictAdvisories:Ie(r),target:t.id}),ki=(e,r,t)=>{const{toolchain:n}=t,o=n===void 0?`target "${t.id}" has no deploy command`:Ue(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},Qr=(e,r)=>{for(const t of e){const n=Le(r(j(t.wranglerPath)));if(n!==void 0)return`service ${t.name} (${t.worker}): ${n}`}},bi=(e,r,t)=>{const{error:n,services:o}=Te(e);if(n!==void 0||o.length===0)return;const s=de(t);if(s.toolchain===void 0||Ue(r)!==void 0)return;const i=r.skipCodegen===!0?!1:r.frameworkBuild,a=[...new Map(o.map(c=>[c.wranglerPath,c])).values()];return Qr(a,c=>Xr(c,r,s,i,H))},Zr=(e,r,t)=>{const n=e.cwd??process.cwd(),o=on(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(gr),{kind:"refused",code:w.USAGE,error:gr,validation:_};try{Yr(n,e,de(o.target))}catch(a){if(!(t&&a instanceof Ct&&fe(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:Gs(n,e,r,wi(n,e));if(s!==void 0)return{kind:"refused",code:s.code,error:s.error,validation:_};const i=bi(n,e,o.target);return i!==void 0?(e.logger.error(i),{kind:"refused",code:w.USAGE,error:i,validation:_}):{kind:"ok",target:o.target}},$i=(e,r)=>e.apiSpec??(e.clientBuildRan===!0?Dt(r):void 0),Si=async(e,r,t)=>{if(r!=="celld")return;const n=await(e.celldToolchain??jt)({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},et=(e,r)=>{const t=Oe({cwd:e,env:r.env,url:r.migrateUrl}),n=t===void 0?void 0:us(e,r.env,t);if(n!==void 0)return{reason:n};const o=t===void 0?void 0:Vt(t,r.logger,e),s=o===void 0?void 0:qt({cwd:e,token:r.migrateToken,url:o}).token;return{target:o===void 0||!s?void 0:{baseUrl:o,fetchImpl:r.fetchImpl??Kt,token:s}}},Ei=(e,r,t)=>async n=>{const o=et(e,r);return"reason"in o?{kind:"inconclusive",reason:o.reason}:wn({changes:n,tables:t.schemaTables,target:o.target})},Ai=(e,r)=>async t=>{const n=et(e,r);return"reason"in n?n.reason:yn({changes:t,now:Date.now(),target:n.target})},Ri=(e,r,t,n)=>e==="deploy"?{checkStoredRows:Ei(r,t,n),countExpiringRows:Ai(r,t)}:{},Ti=async(e,r)=>{const t=e.cwd??process.cwd(),n=Jr(e),o=Ie(e),s={problems:[],wranglerPath:void 0},i=Zr(e,r,!1);if(i.kind==="refused")return{code:i.code,error:i.error,validation:i.validation};const{target:a}=i,c=await Si(e,a,r);if(c!==void 0)return e.logger.error(c),{code:w.MISSING_DEPENDENCY,error:c,target:a,validation:s};let l;if(!e.skipCodegen){const v=await hi(t,n,e.logger,$i(e,t),ce(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 vn({allowDrift:e.allowSchemaDrift===!0,...Ri(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&&In({current:l.architecture,cwd:t,environment:e.env,logger:e.logger});await gi(t,e.logger,l?.cronTriggers,a,e.env,e.discoveryCache);const f=await Cr(t,e,r,a,"check");if(f!==void 0)return{error:f,target:a,validation:_};const h=Vs(t,e,r,a);if(h!==void 0)return{code:h.code,error:h.error,target:a,validation:_};const g=xt({environment:e.env,projectRoot:t});return vi(g,e.logger)?{error:"wrangler validation failed",target:a,validation:g}:{codegen:l,reblessSchemaBaseline:d,recordArchitecture:u,target:a,validation:g}},_i=e=>{oe(p(e,".wrangler","deploy","config.json"),{force:!0})},Ci=async(e,r,t)=>{const n=Le(e);if(n!==void 0)return{built:!1,error:n};const o=fe(e.cwd,r,t);return o&&_i(e.cwd),{built:o,error:await Ur(e)}},Ii=(e,r,t)=>r||t===!1?De(e):void 0,Pi=async(e,r,t,n)=>{const{error:o,services:s}=Te(e);if(o!==void 0)return{code:w.FAILURE,error:o};if(s.length===0)return;const i=ki(s,r,t);if(i===void 0)return;const a=F(e),c=[...new Map(s.map(f=>[f.wranglerPath,f])).values()],l=r.skipCodegen===!0?!1:r.frameworkBuild,d=f=>Xr(f,r,t,l,n),u=Qr(c,d);if(u!==void 0)return r.logger.error(u),{code:w.USAGE,error:u};for(const f of c){const h=j(f.wranglerPath),g=d(h),{built:v,error:m}=await Ci(g,l,r.env);if(m!==void 0){const T=`service ${f.name} (${f.worker}): ${m}`;return r.logger.error(T),{code:w.FAILURE,error:T}}const S=Ii(f.wranglerPath,v,l);let D;try{D=yr(t,h,"deploy",T=>i.deploy({configPath:T??S??f.wranglerPath,dryRun:r.dryRun===!0,environment:r.env}))}catch(T){return{code:w.FAILURE,error:`service ${f.name} (${f.worker}): ${T instanceof Error?T.message:String(T)}`}}D.commit();const R=z(a,D.command);r.logger.info(`deploying service ${f.name} (${f.worker}) via ${R.command} ${R.args.join(" ")}`);const q=await n({args:R.args,command:R.command,cwd:h,stdoutToStderr:r.format==="json"});if(q.code!==0)return{code:w.FAILURE,error:`service ${f.name} (${f.worker}): ${R.command} ${R.args.join(" ")} exited ${String(q.code)} — stopping before the app`}}},ji=async(e,r,t,n)=>{if(r!=="cloudflare")return;const o=e===void 0?void 0:P(e).parsed,s=(t===void 0?void 0:o?.env?.[t]?.account_id)??o?.account_id,i=await rn({accountId:s});(i.verdict==="near"||i.verdict==="full")&&n.warn(i.fix===void 0?i.message:`${i.message} ${i.fix}`)},Oi=e=>e.dryRun!==!0&&e.temporary!==!0,Di=e=>e.temporary===!0?"temporary":e.dryRun===!0?"preview":"defer",Ni=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},Li=(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=Ni(o);r.error(s),n.push(s)}return n},rt=async(e,r,t,n,o,s,i)=>{const a=t==="cloudflare"&&r!==void 0?P(r).parsed:void 0;if(a===void 0)return;const c=(le(a,n).merged.artifacts??[]).flatMap(g=>typeof g?.binding=="string"&&typeof g.namespace=="string"?[{binding:g.binding,namespace:g.namespace}]:[]),l=c.length===0?void 0:Ce(e,M(e),s).info?.jurisdiction;if(l===void 0)return;const d=[...new Map(c.map(g=>[g.namespace,g])).values()];if(i==="temporary"){o.warn(`--temporary deploys to a throwaway account, so the jurisdiction ("${l}") of Artifacts namespace ${d.map(g=>`"${g.namespace}"`).join(", ")} was not checked: it is created there on first use, in no jurisdiction.`);return}const u=(n===void 0?void 0:a.env?.[n]?.account_id)??a.account_id,f=await Promise.all(d.map(async g=>en({...g,accountId:u,create:i==="create",jurisdiction:l,missingOk:i==="defer"||i==="preview"}))),h=Li(f,o,i);return h.length===0?void 0:h.join(`
57
+ `)},xi=async(e,r,t,n,o,s)=>{const i=Oi(r)?await rt(e,s,o,r.env,r.logger,r.discoveryCache,"create"):void 0;if(i!==void 0)return{code:w.FAILURE,error:i};const a=await Cr(e,r,"deploy",o);return a!==void 0?{code:w.FAILURE,error:a}:Pi(e,r,t,n)},Mi=async(e,r,t,n)=>{if(!(r.smokeLoad===!1||t.toolchain===void 0))return zo({composedEntry:Me(e),configPath:n,cwd:e,environment:r.env,launcher:r.smokeLauncher,logger:r.logger,toolchain:t.toolchain})},Fi=async e=>{const r={...e,discoveryCache:e.discoveryCache??Pt()},t=r.cwd??process.cwd(),n=Jr(r),o=await Ti(r,r.commandName??"deploy");if(o.error!==void 0){if(o.validation.problems.length>0)return{code:w.USAGE,descriptor:void 0,error:o.error,validation:o.validation};const m=o.schemaDrift===void 0?void 0:{schemaDrift:o.schemaDrift};return ve(o.error,{...m,...o.code===void 0?{}:{code:o.code}})}const{validation:s}=o,i=de(o.target),a=As(r)??await rt(t,s.wranglerPath,o.target,r.env,r.logger,r.discoveryCache,Di(r))??await Mi(t,r,i,s.wranglerPath);if(a!==void 0)return ve(a);const c=i.toolchain?.prebuildsContainerImages===!0?await ui(t,r):void 0;if(c!==void 0)return ve(c);ni(t,r.logger,i),Lt(t,m=>{r.logger.warn(m)}),await ji(s.wranglerPath,o.target,r.env,r.logger);const{error:l,mintedSecretsFile:d}=await li(t,r,n,i);if(l!==void 0)return r.logger.error(l),{code:w.USAGE,descriptor:void 0,error:l,mintedSecretsFile:d,validation:s};const u=r.spawner??H,f=await xi(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 h=yi(t,r,i);r.logger.info(`deploying via ${h.command} ${h.args.join(" ")}`);const g=await u(h);return h.captureStdoutSilently===!0&&g.stdout!==void 0&&g.stdout!==""&&process.stderr.write(g.stdout),g.code!==0?{code:g.code,descriptor:h,mintedSecretsFile:d,validation:s}:{...await ti({...o,cwd:t,descriptor:h,mintedSecretsFile:d,options:r,stdout:g.stdout}),logsAvailable:i.toolchain?.tail!==void 0}},Ui=async e=>{const{logger:r}=e,t=e.cwd??process.cwd(),n={apiSpec:e.apiSpec,cwd:t,environment:e.env,bundleMetaPath:e.bundleMetaPath,frameworkBuild:e.skipCodegen===!0?!1:e.frameworkBuild,strictAdvisories:Ie(e),lazyFunctions:ce(e.lazyFunctions),logger:r,outputJson:e.format==="json"||e.clientBuildOutputJson===!0,spawner:e.spawner,target:e.target},o=Le(n);if(o!==void 0)return r.error(o),{code:w.USAGE,descriptor:void 0,error:o,validation:_};It(t);const s=await Ur(n);if(s!==void 0)return r.error(s),{code:w.FAILURE,descriptor:void 0,error:s,validation:_}},Bi=(e,r)=>{const t=r.skipCodegen===!0?!1:r.frameworkBuild;return fe(e,t,r.env)?r.env:void 0},Wi=async e=>{const{logger:r}=e,t=e.cwd??process.cwd(),n=Zr(e,e.commandName??"deploy",!0);if(n.kind==="refused")return{code:n.code??w.USAGE,descriptor:void 0,error:n.error,validation:n.validation};const o=await Ui(e);if(o!==void 0)return o;const s=e.dryRun===!0?xr(t):void 0;let i;try{if(i=await Fi({...e,clientBuildEnvironment:Bi(t,e),clientBuildRan:vs(t,e.skipCodegen===!0?!1:e.frameworkBuild,e.env),logger:r,openShardGatePassed:!0}),i.code===0&&e.emitBindings!==void 0){const{error:a}=tn({destination:e.emitBindings,logger:r,projectRoot:e.cwd??process.cwd()});a!==void 0&&(r.error(a),i={...i,code:w.USAGE})}}finally{s?.()}return e.format==="json"||i.code===0&&e.dryRun!==!0&&e.isolatedPreview!==!0&&Pn({cwd:e.cwd??process.cwd(),env:e.env,logger:e.logger,logsAvailable:i.logsAvailable===!0,mintedSecretsFile:i.mintedSecretsFile,url:i.deployment?.url}),i},Ea=nn(async({cwd:e,format:r,logger:t,options:n})=>{const o=Jo(e,n.root),s=await Wi({allowOpenShards:n.allowOpenShards===!0,allowSchemaDrift:n.allowSchemaDrift===!0,apiSpec:Yt(n.apiSpec),frameworkBuild:n.prebuilt===!0?!1:n.frameworkBuild,lazyFunctions:ce(n.lazyFunctions),cwd:o,dryRun:n.dryRun===!0,env:n.env,format:r,healthCheck:n.healthCheck===!0,logger:t,migrate:n.migrate===!0,migrateToken:n.migrateToken,migrateUrl:Oe({cwd:o,env:n.env,url:n.migrateUrl}),migrateYes:n.migrateYes===!0,preview:n.preview===!0,skipCodegen:n.prebuilt===!0,skipServices:n.skipServices===!0,smokeLoad:n.smokeLoad,strictAdvisories:n.strictAdvisories,target:n.target,temporary:n.temporary===!0});return{code:s.code,data:{deployment:s.deployment,healthCheck:s.healthCheck,mintedSecretsFile:s.mintedSecretsFile,schemaDrift:s.schemaDrift,validation:s.validation},error:s.error}});export{Ti as a,gi as b,Mn as c,xr as d,zr as e,Ea as f,Jo as p,Wi as r,Mi as s,fs as v};
@@ -1,16 +1,2 @@
1
- import { d as defineHandler } from '../packem_shared/command-D3lB_4Az.mjs';
2
- import { a as resolveProductionWorkerUrl } from '../packem_shared/resolve-target-qbsJ_5sF.mjs';
3
- import { runExportCommand } from '../packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Ck-2bU08.mjs';
4
-
5
- const execute = defineHandler(
6
- ({ argument, cwd, logger, options }) => runExportCommand({
7
- logger,
8
- out: argument[0] ?? options.out,
9
- prod: options.prod === true,
10
- tables: options.tables,
11
- token: options.token,
12
- url: resolveProductionWorkerUrl({ cwd, prod: options.prod === true, url: options.url })
13
- })
14
- );
15
-
16
- export { execute };
1
+ import{r as v}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{r as M,a as y}from"../packem_shared/admin-url-DJB8P6Jh.mjs";import{d as x}from"../packem_shared/command-BpMv2n0o.mjs";import{EXIT_CODE as u,exitCodeForStatus as T}from"../packem_shared/EXIT_CODE-DQVhSE-1.mjs";import{r as I}from"../packem_shared/resolve-target-BRvw8Pf7.mjs";const O="__lunora_admin__:getFunctionStats",_=10,f=(r,o)=>({calls:r.calls,conflicts:r.conflicts??0,errors:r.errors,lastErrorMessage:r.lastErrorMessage,maxDurationMs:r.maxDurationMs,meanDurationMs:r.calls===0?0:r.totalDurationMs/r.calls,path:r.path,rate:o}),k=(r,o)=>{const t=r.filter(e=>(e.conflicts??0)>0).map(e=>f(e,e.calls===0?0:(e.conflicts??0)/e.calls)).toSorted((e,s)=>s.rate-e.rate||s.conflicts-e.conflicts).slice(0,o),n=r.filter(e=>e.errors>0).map(e=>f(e,e.calls===0?0:e.errors/e.calls)).toSorted((e,s)=>s.rate-e.rate||s.errors-e.errors).slice(0,o),a=r.map(e=>f(e,0)).toSorted((e,s)=>s.maxDurationMs-e.maxDurationMs).slice(0,o);return{errorHotspots:n,latencyOutliers:a,totalFunctions:r.length,writeContention:t}},p=r=>`${(r*100).toFixed(1)}%`,$=r=>r<1e3?`${Math.round(r).toString()}ms`:`${(r/1e3).toFixed(2)}s`,m=(r,o,t,n)=>[r,...o.length===0?[` ${t}`]:o.map(a=>` ${n(a)}`)],E=r=>{const o=t=>t.lastErrorMessage?` — ${t.lastErrorMessage}`:"";return[`Insights over ${r.totalFunctions.toString()} function${r.totalFunctions===1?"":"s"}`,"",...m("Write-conflict hot-spots (OCC contention — candidates for sharding):",r.writeContention,"none — no write conflicts observed",t=>`${t.path} ${t.conflicts.toString()}/${t.calls.toString()} calls (${p(t.rate)})`),"",...m("Error hot-spots:",r.errorHotspots,"none — no errors observed",t=>`${t.path} ${t.errors.toString()}/${t.calls.toString()} calls (${p(t.rate)})${o(t)}`),"",...m("Latency outliers (slowest single call):",r.latencyOutliers,"none — no functions have run",t=>`${t.path} max ${$(t.maxDurationMs)}, mean ${$(t.meanDurationMs)} over ${t.calls.toString()} calls`)].join(`
2
+ `)},i=(r,o,t)=>(r.error(o),{code:t,error:o}),F=r=>r===void 0||!Number.isFinite(r)||r<=0?_:Math.floor(r),A=async r=>{const{logger:o}=r;if(r.prod&&r.url===void 0)return i(o,"--prod requires an explicit --url (refusing to report from the implicit localhost worker)",u.USAGE);const t=M(r.url,o,r.cwd);if(t===void 0)return{code:u.USAGE,error:"could not resolve a usable worker URL"};const{token:n}=v({cwd:r.cwd??process.cwd(),token:r.token,url:t});if(!n)return i(o,"admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)",u.AUTH);const a=`${t}/_lunora/rpc`,e=y,s={args:{},functionPath:O};r.shard!==void 0&&(s.shardKey=r.shard),o.info(`POST ${a} -> insights`);const l=await e(a,{body:JSON.stringify(s),headers:{authorization:`Bearer ${n}`,"content-type":"application/json"},method:"POST"}),c=await l.text();if(!l.ok)return i(o,`insights failed: HTTP ${String(l.status)}: ${c}`,T(l.status));let d;try{d=JSON.parse(c)}catch{return i(o,`insights failed: worker returned non-JSON: ${c}`,1)}const S=d.result??d,{functions:h}=S;if(!Array.isArray(h))return i(o,"insights failed: response carried no `functions` array",1);const g=k(h,F(r.limit));return r.format!=="json"&&o.info(E(g)),{code:0,report:g}},L=x(async({cwd:r,format:o,logger:t,options:n})=>{const a=n.limit===void 0?void 0:Number.parseInt(n.limit,10),e=await A({cwd:r,fetchImpl:void 0,format:o,limit:a,logger:t,prod:n.prod,shard:n.shard,token:n.token,url:I({cwd:r,prod:n.prod===!0,url:n.url})});return{code:e.code,data:e.report,error:e.error}});export{k as buildInsightsReport,L as execute,E as formatInsightsReport,A as runInsightsCommand};
@@ -1,22 +1 @@
1
- import { d as defineHandler } from '../packem_shared/command-D3lB_4Az.mjs';
2
- import { a as resolveProductionWorkerUrl } from '../packem_shared/resolve-target-qbsJ_5sF.mjs';
3
- import { runImportCommand } from '../packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Ck-2bU08.mjs';
4
-
5
- const execute = defineHandler(({ argument, cwd, logger, options }) => {
6
- const file = argument[0];
7
- if (!file) {
8
- logger.error("import requires a file. Usage: lunora import <path> [--table <name>]");
9
- return { code: 1 };
10
- }
11
- return runImportCommand({
12
- batchSize: options.batchSize,
13
- file,
14
- logger,
15
- prod: options.prod === true,
16
- table: options.table,
17
- token: options.token,
18
- url: resolveProductionWorkerUrl({ cwd, prod: options.prod === true, url: options.url })
19
- });
20
- });
21
-
22
- export { execute };
1
+ import{existsSync as u,rmSync as a}from"node:fs";import{join as i}from"node:path";import{writeLinkedProject as d,LINKED_PROJECT_FILE as o}from"@lunora/config";import{d as k}from"../packem_shared/command-BpMv2n0o.mjs";import{EXIT_CODE as c}from"../packem_shared/EXIT_CODE-DQVhSE-1.mjs";import{r as s}from"../packem_shared/wrangler-name-Dsk5K1f-.mjs";const v=r=>{try{const{protocol:n}=new URL(r);return n==="http:"||n==="https:"}catch{return!1}},f=(r,n)=>{const e=i(r,o);return u(e)?(a(e),n.success(`link: removed ${o}`),{code:0}):(n.warn(`link: no ${o} to remove`),{code:0})},w=r=>{const n=r.cwd??process.cwd(),{logger:e}=r;if(r.remove)return f(n,e);if(r.url===void 0||r.url==="")return e.error("link requires a deployed Worker URL. Usage: lunora link --url <https://your-worker>"),{code:c.USAGE};if(!v(r.url))return e.error(`link: invalid --url "${r.url}" — expected an http(s) URL`),{code:c.USAGE};const l=r.now??(()=>new Date().toISOString()),t={env:r.env,linkedAt:l(),workerName:r.name??s(n),workerUrl:r.url},m=d(n,t);return e.success(`link: ${t.workerName??"(unnamed worker)"} -> ${r.url}`),e.info(`link: wrote ${m}`),t.env!==void 0&&e.info(`link: environment "${t.env}"`),{code:0,link:t}},y=k(({cwd:r,logger:n,options:e})=>w({cwd:r,env:e.env,logger:n,name:e.name,remove:e.remove===!0,url:e.url}));export{y as execute,w as runLinkCommand};