@lunora/config 1.0.0-alpha.459 → 1.0.0-alpha.460

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 (74) hide show
  1. package/dist/cli/index.mjs +1 -1
  2. package/dist/cloudflare/index.d.mts +1097 -1068
  3. package/dist/cloudflare/index.d.ts +1097 -1068
  4. package/dist/cloudflare/index.mjs +1 -1
  5. package/dist/index.d.mts +119 -6
  6. package/dist/index.d.ts +119 -6
  7. package/dist/index.mjs +1 -1
  8. package/dist/packem_shared/BINDING_MANIFEST_VERSION-CR06-eW7.mjs +1 -0
  9. package/dist/packem_shared/{CLOUDFLARE_CLI_CONFIG_WARNING_ENV-BKMrOuXV.mjs → CLOUDFLARE_CLI_CONFIG_WARNING_ENV-75Y5zVF8.mjs} +1 -1
  10. package/dist/packem_shared/{COMPOSED_WORKER_ENTRY-BcFt6ts5.mjs → COMPOSED_WORKER_ENTRY-LpLlp-aF.mjs} +1 -1
  11. package/dist/packem_shared/{DEFAULT_DEPLOY_TARGET-DllYb7Tj.mjs → DEFAULT_DEPLOY_TARGET-CAJl2nEI.mjs} +1 -1
  12. package/dist/packem_shared/DEV_VARS_EXAMPLE_FILE-hBT89IXh.mjs +6 -0
  13. package/dist/packem_shared/{DEV_WORKER_ENV_VALUE-DdPmCpf3.mjs → DEV_WORKER_ENV_VALUE-FoysLtF0.mjs} +1 -1
  14. package/dist/packem_shared/LUNORA_EVENT_SOURCE-Cq0oj0_9.mjs +9 -0
  15. package/dist/packem_shared/PACKAGE_SECRETS_REGISTRY-CPWkw-qE.mjs +1 -0
  16. package/dist/packem_shared/{POLICY_SCAFFOLD_ENDPOINT-uJ8CZJh-.mjs → POLICY_SCAFFOLD_ENDPOINT-UcPFeEyM.mjs} +1 -1
  17. package/dist/packem_shared/REMOTE_ELIGIBLE_KEYS-D66_hwjD.mjs +1 -0
  18. package/dist/packem_shared/REQUIRED_COMPATIBILITY_DATE-BPxR2Ht_.mjs +1 -0
  19. package/dist/packem_shared/{SCHEMA_EDIT_ENDPOINT-C4h_C4TI.mjs → SCHEMA_EDIT_ENDPOINT-C-ic_pvD.mjs} +1 -1
  20. package/dist/packem_shared/{STUDIO_PATH-C6kNFiHy.mjs → STUDIO_PATH-CDf-EtPs.mjs} +1 -1
  21. package/dist/packem_shared/UNEXPORTED_CLASS_MARKER-Zw1oiigQ.mjs +1 -0
  22. package/dist/packem_shared/WRANGLER_FILES-BF8PUjuo.mjs +1 -0
  23. package/dist/packem_shared/{assertBuildTargetMatches-CqrrwiQ-.mjs → assertBuildTargetMatches-tkKAa5zl.mjs} +1 -1
  24. package/dist/packem_shared/{assertWranglerSatisfiesSchema-071lEemx.mjs → assertWranglerSatisfiesSchema-CZWQnfly.mjs} +1 -1
  25. package/dist/packem_shared/{bindingsNeedingDatabase-6eD6Qtqf.mjs → bindingsNeedingDatabase-3KyGflIq.mjs} +1 -1
  26. package/dist/packem_shared/buildPackageSecretsBlock-DrSD60vH.mjs +19 -0
  27. package/dist/packem_shared/{celld-config-DoBVipuN.mjs → celld-config-CpvLkAEg.mjs} +1 -1
  28. package/dist/packem_shared/checkDevEnv-egiW2lSF.mjs +3 -0
  29. package/dist/packem_shared/{collectExportGaps-C5OYqfkE.mjs → collectExportGaps-BYo3bcXi.mjs} +2 -2
  30. package/dist/packem_shared/{createStudioDocumentCache-B3Sf1bIl.mjs → createStudioDocumentCache-XBG1aWbl.mjs} +1 -1
  31. package/dist/packem_shared/{describePreservedCrons-Bt2rPPeY.mjs → describePreservedCrons-i5XT6rtl.mjs} +1 -1
  32. package/dist/packem_shared/devTriggerHints-CN_RJxWW.mjs +1 -0
  33. package/dist/packem_shared/{devVariablesStamp-Cetr3qFz.mjs → devVariablesStamp-BQkGEn9d.mjs} +1 -1
  34. package/dist/packem_shared/{emitProjectAssetHeaders-2FtExZPG.mjs → emitProjectAssetHeaders-6iinmRWE.mjs} +1 -1
  35. package/dist/packem_shared/guards-CoCtgpeR.mjs +1 -0
  36. package/dist/packem_shared/hasCloudflareCredentials-ByCrwaLT.mjs +1 -0
  37. package/dist/packem_shared/inferLunoraBindings-Biq1OW9V.mjs +1 -0
  38. package/dist/packem_shared/{materializeServiceDevConfigs-qUY4_iu1.mjs → materializeServiceDevConfigs-CI1HXv7f.mjs} +1 -1
  39. package/dist/packem_shared/pendingBindingChanges-5fPhwxMt.mjs +1 -0
  40. package/dist/packem_shared/{infer-bindings.d-Tkaosiub.d.mts → placeholder-ids.d-DvGHP6bl.d.mts} +18 -18
  41. package/dist/packem_shared/{infer-bindings.d-Tkaosiub.d.ts → placeholder-ids.d-DvGHP6bl.d.ts} +18 -18
  42. package/dist/packem_shared/queue-info-D38n7YdX.mjs +1 -0
  43. package/dist/packem_shared/reconcile-services-CjgIJKim.mjs +1 -0
  44. package/dist/packem_shared/reconcileWranglerBindings-D7mXDfAe.mjs +1 -0
  45. package/dist/packem_shared/{reconcileWranglerCompatibilityDate-hocXEuRA.mjs → reconcileWranglerCompatibilityDate-Cj94osA-.mjs} +1 -1
  46. package/dist/packem_shared/scanWranglerVariablesForSecrets-DojbojUo.mjs +1 -0
  47. package/dist/packem_shared/secret-key-xi4VK8Jw.mjs +1 -0
  48. package/dist/packem_shared/{startCelldDevSession-Bg_RN5uf.mjs → startCelldDevSession-DQ7YylR_.mjs} +1 -1
  49. package/dist/packem_shared/validate-bindings-CQbR23li.mjs +1 -0
  50. package/dist/packem_shared/withTailConsumer-CKXL6P6s.mjs +1 -0
  51. package/dist/packem_shared/{worker-entry-checks-CHrum2AN.mjs → worker-entry-checks-DH-ApvvX.mjs} +1 -1
  52. package/dist/packem_shared/wranglerCodegenInputs-Cz9ByxSo.mjs +1 -0
  53. package/dist/packem_shared/{write-atomic-NN-EjI8U.mjs → write-atomic-CcNMkFsX.mjs} +1 -1
  54. package/dist/studio-host/index.mjs +1 -1
  55. package/package.json +4 -2
  56. package/dist/packem_shared/BINDING_MANIFEST_VERSION-CfXEYG8e.mjs +0 -1
  57. package/dist/packem_shared/DEV_VARS_EXAMPLE_FILE-CqLorAxT.mjs +0 -6
  58. package/dist/packem_shared/LUNORA_EVENT_SOURCE-D_VGT1JJ.mjs +0 -9
  59. package/dist/packem_shared/PACKAGE_SECRETS_REGISTRY-CnY7jg9j.mjs +0 -1
  60. package/dist/packem_shared/REMOTE_ELIGIBLE_KEYS-DooK0pzs.mjs +0 -1
  61. package/dist/packem_shared/REQUIRED_COMPATIBILITY_DATE-CKjEIFrf.mjs +0 -1
  62. package/dist/packem_shared/UNEXPORTED_CLASS_MARKER-YnIX5BDi.mjs +0 -1
  63. package/dist/packem_shared/WRANGLER_FILES-UNW-xY5u.mjs +0 -1
  64. package/dist/packem_shared/buildPackageSecretsBlock-B4Odg5OF.mjs +0 -19
  65. package/dist/packem_shared/hasCloudflareCredentials-Bak5w1_6.mjs +0 -1
  66. package/dist/packem_shared/inferLunoraBindings-D0QDcugr.mjs +0 -1
  67. package/dist/packem_shared/package-secrets-registry-TouCAMQN.mjs +0 -1
  68. package/dist/packem_shared/reconcile-assets-h8q3F4Sy.mjs +0 -1
  69. package/dist/packem_shared/reconcile-services-C4TwY8YH.mjs +0 -1
  70. package/dist/packem_shared/reconcileBindingsSafely-BI6znzGg.mjs +0 -1
  71. package/dist/packem_shared/scanWranglerVariablesForSecrets-CkonQUdG.mjs +0 -1
  72. package/dist/packem_shared/spa-assets-BwJFTBeO.mjs +0 -1
  73. package/dist/packem_shared/withTailConsumer-_EZ9WqMc.mjs +0 -1
  74. package/dist/packem_shared/wranglerCodegenInputs-BZUWdHzz.mjs +0 -1
@@ -0,0 +1 @@
1
+ import{applyModify as g}from"./applyModify-DKP2l6S9.mjs";import{hasCloudflareCredentials as v}from"./hasCloudflareCredentials-ByCrwaLT.mjs";import{withheldBindings as y,writeDevConfig as E,noopCleanup as R}from"./describeWithheld-CbyzZjZF.mjs";import{readManifest as w}from"./readManifest-Cighz3WC.mjs";import{o as S}from"./reconcile-services-CjgIJKim.mjs";import{findWranglerFile as _,readWranglerJsonc as j}from"./WRANGLER_FILES-BF8PUjuo.mjs";const h={ai:{label:"AI",shape:"object"},ai_search:{label:"AI Search",shape:"array"},ai_search_namespaces:{label:"AI Search namespace",shape:"array"},analytics:{label:"Analytics SQL",shape:"object"},d1_databases:{label:"D1",shape:"array"},kv_namespaces:{label:"KV",shape:"array"},queues:{label:"Queue",shape:"producers"},r2_buckets:{label:"R2",shape:"array"},services:{label:"Service",shape:"array"},vectorize:{label:"Vectorize",shape:"array"}},B=Object.keys(h),m=(e,n)=>typeof e.binding=="string"?e.binding:n,f=(e,n,r,t)=>{const i=[];for(const[s,o]of n.entries())o!=null&&(e==="kv_namespaces"&&(typeof o.id!="string"||o.id==="")||i.push({binding:m(o,`#${String(s)}`),kind:r,path:[...t,s],section:e}));return i},u=(e,n)=>h[e].shape===n,C=(e,n)=>{const{label:r}=h[e];if(u(e,"array"))return f(e,n[e]??[],r,[]);if(u(e,"object")){const t=n[e];return t==null?[]:[{binding:m(t,e),kind:r,path:[],section:e}]}return f(e,n.queues?.producers??[],r,["producers"])},I=e=>B.flatMap(n=>C(n,e)),k=(e,n)=>{let r=e;for(const t of n)r=g(r,[t.section,...t.path,"remote"],!0);return r},W=(e,n)=>({bindings:e.remoteBindings.map(r=>`${r.binding} (${r.kind})`),cleanup:e.cleanup,configPath:e.configPath,enabled:n,reason:e.reason,withheld:e.withheld}),$=e=>{const n=a=>({cleanup:R,reason:a,remoteBindings:[],withheld:[]}),r=_(e.projectRoot);if(!r)return n("wrangler.jsonc not found");const{parsed:t,text:i}=j(r);if(t===void 0)return n(`failed to parse ${r} as JSONC`);const s=S(w(e.projectRoot)),o=e.remote?I(t).filter(a=>a.section!=="services"||!s.has(a.binding)):[],l=y(t,e.hasCredentials??(()=>v({projectRoot:e.projectRoot}))),c=l.some(({kind:a})=>a==="ai")?o.filter(a=>a.section!=="ai"):o;if(c.length===0&&l.length===0)return n(e.remote?"no remote-eligible bindings to proxy":void 0);let d=i;for(const{kind:a}of l)d=g(d,[a],void 0);const b=c.length>0?k(d,c):d,p=E(e.projectRoot,"dev",b);return{cleanup:p.cleanup,configPath:p.configPath,remoteBindings:c,withheld:l}},L=e=>{if(e===void 0)return!1;const n=e.trim().toLowerCase();return n==="1"||n==="true"},D=e=>e.flag===!0||L(e.envValue)?!0:e.configPreference??!1;export{h as REMOTE_ELIGIBLE_KEYS,k as injectRemoteFlags,L as isRemoteEnvEnabled,$ as materializeDevWranglerConfig,I as planRemoteBindings,D as resolveRemoteEnabled,W as toRemotePlan};
@@ -0,0 +1 @@
1
+ import{MERGED_DURABLE_OBJECT as m}from"./COMPOSED_WORKER_ENTRY-LpLlp-aF.mjs";import{o as R,v as S,a as I,b as j,c as A,d as L,e as f,g as k,h as B,H as C,i as N,R as T,S as w,j as q,k as U,W as G,l as P}from"./validate-bindings-CQbR23li.mjs";import{i as u,p as g,a as _}from"./guards-CoCtgpeR.mjs";import{validateTailConsumers as W,validateSendEmail as K,validateSecretsRequired as M,validateLogpush as V,validateLimits as x,validatePlacement as H,validateObservability as Q,validateAssets as F,validateCache as Y,validateExports as J,validateCorsVariables as z,validateSchedulerOrigin as X}from"./withTailConsumer-CKXL6P6s.mjs";import{isCacheEnabled as Z,WORKERS_CACHE_MIN_DATE as E}from"./WORKERS_CACHE_MIN_DATE-0k9ABJtF.mjs";import{mergeWranglerEnvironment as ee}from"./mergeWranglerEnvironment-D5ekKj5x.mjs";const v=t=>u(t)?new Set([...g(t.producers).map(i=>i.queue),...g(t.consumers).flatMap(i=>[i.queue,i.dead_letter_queue])].filter(i=>_(i))):new Set,b=(t,i,n)=>{const e=u(t)?t.account_id:void 0;return _(e)?e:_(i.account_id)?i.account_id:_(n)?n:void 0},te=(t,i,n,e=process.env.CLOUDFLARE_ACCOUNT_ID)=>{if(i===void 0||!u(t.env))return;const s=t.env[i],r=v(u(s)?s.queues:void 0);if(r.size===0)return;const a=b(s,t,e),p=[{account:b(void 0,t,e),names:v(t.queues),scope:"the top level"},...Object.entries(t.env).filter(([c])=>c!==i).map(([c,o])=>({account:b(o,t,e),names:v(u(o)?o.queues:void 0),scope:`env.${c}`}))].filter(c=>a===void 0||c.account===void 0||c.account===a);for(const c of r){const o=p.filter(({names:l})=>l.has(c)).map(({scope:l})=>l);o.length>0&&n.push(`env.${i}.queues names queue "${c}", which ${o.join(" and ")} also ${o.length===1?"names":"name"}. Queue names are unique per Cloudflare account, so deployed to one account the environments share that queue: messages produced in one are consumed by the other. Give env.${i} its own name (e.g. "${c}-${i}") unless the sharing is intended — the renamed queue starts empty, and messages already in "${c}" stay there.`)}},ie=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),O=t=>Array.isArray(t)?t.flatMap((i,n)=>ie(i)?[[n,i]]:[]):[],y=t=>typeof t.binding=="string"?t.binding:"",ae=(t,i,n)=>{for(const[e,s]of O(t.kv_namespaces))typeof s.id=="string"&&s.id!==""||n.push(`kv_namespaces[${String(e)}] ("${y(s)}") is not created yet and the schema pins data to "${i}" — create it with \`wrangler kv namespace create <name> --jurisdiction=${i}\`; a namespace's jurisdiction cannot be changed afterwards`)},se=(t,i,n)=>{for(const[e,s]of O(t.r2_buckets)){const r=s.jurisdiction;if(r===i)continue;const a=typeof r=="string"?`names the "${r}" jurisdiction`:"names no jurisdiction";n.push(`r2_buckets[${String(e)}] ("${y(s)}") ${a}, but the schema pins data to "${i}" — create the bucket with \`wrangler r2 bucket create <name> --jurisdiction=${i}\` and set "jurisdiction": "${i}" on the binding`)}},ne=(t,i,n)=>{const e=i?.jurisdiction;e!==void 0&&(ae(t,e,n),se(t,e,n))},D="2026-04-07",pe="web_socket_auto_reply_to_close",h="2026-10-01",$="durable_object_io_tasks_prevent_eviction",oe="durable_object_io_tasks_do_not_prevent_eviction",re=/^\d{4}-\d{2}-\d{2}$/,ce=(t,i,n)=>{t>=h||i.includes($)||i.includes(oe)||n.push(`compatibility_date "${t}" predates "${h}", so pending I/O (waitUntil, cross-Durable-Object RPC, service-binding calls, timers) does not keep a Durable Object alive once its last client disconnects — live-query refreshes and durable streams can be cut off mid-flight. Set compatibility_date >= "${h}" or add the "${$}" compatibility flag`)},de=(t,i,n)=>{const{error:e,merged:s,unverifiedKeys:r}=ee(t,i);return e!==void 0?{error:e,wrangler:s}:(r.length>0&&n.push(`env.${String(i)} overrides ${r.join(", ")}, which this validator doesn't have a verified inheritance rule for — validated against the TOP-LEVEL value only. Double-check ${r.length===1?"it":"them"} by hand for "${String(i)}".`),{wrangler:s})},le=(t,i,n)=>{const e=[],s=[];if(!t||typeof t!="object")return e.push("wrangler config is not a valid object"),{errors:e,valid:!1,warnings:s};const{error:r,wrangler:a}=de(t,n,s);if(r!==void 0)return e.push(r),{errors:e,valid:!1,warnings:s};R(a.durable_objects?.bindings).find(d=>d.name==="SHARD"&&(d.class_name==="ShardDO"||d.class_name===m))||e.push(`durable_objects.bindings must include { "name": "SHARD", "class_name": "ShardDO" } (or "${m}" when the app merges its Durable Objects) — your dev server auto-reconciles this on startup, or add the binding manually`),S(a,e);const o=a.compatibility_date??"",l=re.test(o);o&&!l?e.push(`compatibility_date must be in YYYY-MM-DD format (got "${o}")`):o<D&&e.push(`compatibility_date must be >= "${D}" (got "${o||"<missing>"}")`),Z(a)&&l&&o<E&&e.push(`cache.enabled requires compatibility_date >= "${E}" (got "${o||"<missing>"}")`),l&&ce(o,a.compatibility_flags??[],s),I(a,i,e),ne(a,i,s),j(a,e),A(a,i?.vectorIndexNames??[],e),W(a,e),L(a,e,s),f(a.workflows,"workflows",G,e),k(a,e),B(a,e),te(t,n,s),f(a.secrets_store_secrets,"secrets_store_secrets",P,e);for(const d of C)N(a,d,e,s);for(const d of T)f(a[d.key],d.key,d,e);for(const d of w)q(a,d,e);return U(a,e),K(a,e,s),M(a,e),V(a,e),x(a,e),H(a,e),Q(a,e,s),F(a,e),Y(a,e),J(a,e),z(a,e),X(a,n,s),{errors:e,valid:e.length===0,warnings:s}},me=le;export{D as REQUIRED_COMPATIBILITY_DATE,pe as REQUIRED_FLAG,me as validateWrangler,le as validateWranglerConfig};
@@ -1 +1 @@
1
- import{existsSync as a,readFileSync as d}from"node:fs";import{classifyEdit as l,applyAdditiveEdit as c}from"./applyAdditiveEdit-DEwPKcJg.mjs";import{parseSchema as u}from"./parseSchema-D1Wbr1qv.mjs";import{w as f,r as p}from"./write-atomic-NN-EjI8U.mjs";import{join as m}from"node:path";const F="/__lunora/schema-edit",b=t=>t==="destructive"||t==="duplicate-table"||t==="duplicate-column"||t==="duplicate-index"?409:t==="unknown-table"?404:t==="invalid-identifier"||t==="invalid-validator"?400:422,y=t=>({body:{error:t.reason,ok:!1},status:422}),k=t=>{if(!a(t))return{response:{body:{error:"no-schema-file",ok:!1},status:404}};const e=u(d(t,"utf8"));return e.ok?{tables:e.tables}:{response:y(e)}},g=t=>({body:{edit:t,message:"This edit changes stored data and must go through a migration. Review the migration before applying.",needsMigration:!0,ok:!1},status:409}),h=(t,e)=>{const r=t.body;if(r==null||typeof r!="object"||typeof r.kind!="string")return{body:{error:"invalid-edit",ok:!1},status:400};if(l(r)==="destructive")return g(r);if(!a(e))return{body:{error:"no-schema-file",ok:!1},status:404};const o=c(d(e,"utf8"),r);if(!o.ok)return{body:{error:o.reason,ok:!1},status:b(o.reason)};f(e,o.text);let i;try{i=p(t,{path:e,text:o.text})}catch(s){return{body:{error:s instanceof Error?s.message:String(s),ok:!1},status:500}}const n=u(o.text);return{body:{diagnostics:i,ok:!0,tables:n.ok?n.tables:[]},status:200}},R=t=>{const e=m(t.projectRoot,t.schemaDirectory??"lunora","schema.ts");if(t.method==="GET"){const r=k(e);return"response"in r?r.response:{body:{ok:!0,tables:r.tables},status:200}}return t.method==="POST"?h(t,e):{body:{error:"method-not-allowed",ok:!1},status:405}};export{F as SCHEMA_EDIT_ENDPOINT,R as handleSchemaEditRequest};
1
+ import{existsSync as a,readFileSync as d}from"node:fs";import{classifyEdit as l,applyAdditiveEdit as c}from"./applyAdditiveEdit-DEwPKcJg.mjs";import{parseSchema as u}from"./parseSchema-D1Wbr1qv.mjs";import{w as f,r as p}from"./write-atomic-CcNMkFsX.mjs";import{join as m}from"node:path";const F="/__lunora/schema-edit",b=t=>t==="destructive"||t==="duplicate-table"||t==="duplicate-column"||t==="duplicate-index"?409:t==="unknown-table"?404:t==="invalid-identifier"||t==="invalid-validator"?400:422,y=t=>({body:{error:t.reason,ok:!1},status:422}),k=t=>{if(!a(t))return{response:{body:{error:"no-schema-file",ok:!1},status:404}};const e=u(d(t,"utf8"));return e.ok?{tables:e.tables}:{response:y(e)}},g=t=>({body:{edit:t,message:"This edit changes stored data and must go through a migration. Review the migration before applying.",needsMigration:!0,ok:!1},status:409}),h=(t,e)=>{const r=t.body;if(r==null||typeof r!="object"||typeof r.kind!="string")return{body:{error:"invalid-edit",ok:!1},status:400};if(l(r)==="destructive")return g(r);if(!a(e))return{body:{error:"no-schema-file",ok:!1},status:404};const o=c(d(e,"utf8"),r);if(!o.ok)return{body:{error:o.reason,ok:!1},status:b(o.reason)};f(e,o.text);let i;try{i=p(t,{path:e,text:o.text})}catch(s){return{body:{error:s instanceof Error?s.message:String(s),ok:!1},status:500}}const n=u(o.text);return{body:{diagnostics:i,ok:!0,tables:n.ok?n.tables:[]},status:200}},R=t=>{const e=m(t.projectRoot,t.schemaDirectory??"lunora","schema.ts");if(t.method==="GET"){const r=k(e);return"response"in r?r.response:{body:{ok:!0,tables:r.tables},status:200}}return t.method==="POST"?h(t,e):{body:{error:"method-not-allowed",ok:!1},status:405}};export{F as SCHEMA_EDIT_ENDPOINT,R as handleSchemaEditRequest};
@@ -1 +1 @@
1
- import{resolveAdminToken as A}from"./devVariablesStamp-Cetr3qFz.mjs";import{handleAdvisorProceduresRequest as I,ADVISOR_PROCEDURES_ENDPOINT as O}from"./ADVISOR_PROCEDURES_ENDPOINT-BPnqzAgT.mjs";import{sendStudioDocument as _,sendStudioAsset as h}from"./sendStudioAsset-B81Pex91.mjs";import{isStandaloneModulePath as y,studioAssetsStamp as N,loadStudioAssets as E,readStandaloneAsset as H,assetContentType as R}from"./assetContentType-CUb5bpbI.mjs";import v from"./createStudioDocumentCache-B3Sf1bIl.mjs";import{detectAgentRules as C}from"./AGENT_RULES_DIR-Bd6JPtNa.mjs";import{handlePolicyScaffoldRequest as L,POLICY_SCAFFOLD_ENDPOINT as b}from"./POLICY_SCAFFOLD_ENDPOINT-uJ8CZJh-.mjs";import x from"./renderStudioHtml-CRDTNivi.mjs";import{handleSchemaEditRequest as $,SCHEMA_EDIT_ENDPOINT as k}from"./SCHEMA_EDIT_ENDPOINT-C4h_C4TI.mjs";import{handleSeedRequest as U,SEED_ENDPOINT as g}from"./SEED_ENDPOINT-C1fhrehH.mjs";import{serveJsonHandler as j}from"./serveJsonHandler-B8_GE6QC.mjs";import{transportRejectionReason as F}from"./ALLOW_FORWARDED_ENV-BUndghJx.mjs";import"./STUDIO_WRITE_TEMP_SUFFIX-BTTELz3K.mjs";const i="/__lunora",M=`${i}/studio.js`,m=`${i}/styles.css`,P=/\/$/,q={[b]:L,[k]:$,[g]:U,[O]:I},w=new Set(["127.0.0.1","::1","localhost"]),st=t=>t!==void 0&&t!==!1&&!w.has(t),T=t=>t===void 0||t==="/"?"":t.replace(P,""),nt=t=>`${T(t)}${i}`,B=t=>{try{return new URL(t,"http://localhost").pathname}catch{const d=t.indexOf("?");return d===-1?t:t.slice(0,d)}},at=t=>{const{logger:d,projectRoot:c}=t,u=T(t.base);let l,S;const p=v(c,()=>x({adminToken:A(c),advisorProcedures:!0,basePath:i,dataEditable:!0,rulesInstalled:C(c).installed,runAsIdentity:!0,schemaEditable:!0,scriptSrc:M,styleHref:m})),D=(s,o,e)=>{const n=N();if((l===void 0||n!==S)&&(l=E(d),S=n),l===void 0){e.statusCode=501,e.setHeader("Content-Type","text/plain"),e.end("Lunora studio assets not found — install and build @lunora/studio.");return}const a=s===m,r=s.slice(s.lastIndexOf("/")+1);if(a){h(o,e,l.styles,"text/css; charset=utf-8",r,n);return}const f=H(r);if(f===void 0){e.statusCode=404,e.setHeader("Content-Type","text/plain"),e.end("Not found");return}h(o,e,f,R(r),r,n)};return(s,o,e)=>{const n=B(s.url??"").replace(P,""),a=u!==""&&n.startsWith(u)?n.slice(u.length):n;if(a!==i&&!a.startsWith(`${i}/`)){e();return}if(t.isNonLoopbackBind||F(s,d)!==void 0){o.statusCode=403,o.setHeader("Content-Type","text/plain"),o.end("Lunora studio is only available on loopback hosts in dev.");return}const r=q[a];if(r!==void 0){j(s,o,r,c,{apiSpec:t.apiSpec,lazyFunctions:t.lazyFunctions,schemaDirectory:t.schemaDirectory});return}if(a===m||y(a)){D(a,s,o);return}_(o,p())}};export{i as STUDIO_PATH,M as STUDIO_SCRIPT_PATH,m as STUDIO_STYLE_PATH,at as createStudioMiddleware,st as isNonLoopbackHost,B as requestPathname,nt as studioMountPath};
1
+ import{resolveAdminToken as A}from"./devVariablesStamp-BQkGEn9d.mjs";import{handleAdvisorProceduresRequest as I,ADVISOR_PROCEDURES_ENDPOINT as O}from"./ADVISOR_PROCEDURES_ENDPOINT-BPnqzAgT.mjs";import{sendStudioDocument as _,sendStudioAsset as h}from"./sendStudioAsset-B81Pex91.mjs";import{isStandaloneModulePath as y,studioAssetsStamp as N,loadStudioAssets as E,readStandaloneAsset as H,assetContentType as R}from"./assetContentType-CUb5bpbI.mjs";import v from"./createStudioDocumentCache-XBG1aWbl.mjs";import{detectAgentRules as C}from"./AGENT_RULES_DIR-Bd6JPtNa.mjs";import{handlePolicyScaffoldRequest as L,POLICY_SCAFFOLD_ENDPOINT as b}from"./POLICY_SCAFFOLD_ENDPOINT-UcPFeEyM.mjs";import x from"./renderStudioHtml-CRDTNivi.mjs";import{handleSchemaEditRequest as $,SCHEMA_EDIT_ENDPOINT as k}from"./SCHEMA_EDIT_ENDPOINT-C-ic_pvD.mjs";import{handleSeedRequest as U,SEED_ENDPOINT as g}from"./SEED_ENDPOINT-C1fhrehH.mjs";import{serveJsonHandler as j}from"./serveJsonHandler-B8_GE6QC.mjs";import{transportRejectionReason as F}from"./ALLOW_FORWARDED_ENV-BUndghJx.mjs";import"./STUDIO_WRITE_TEMP_SUFFIX-BTTELz3K.mjs";const i="/__lunora",M=`${i}/studio.js`,m=`${i}/styles.css`,P=/\/$/,q={[b]:L,[k]:$,[g]:U,[O]:I},w=new Set(["127.0.0.1","::1","localhost"]),st=t=>t!==void 0&&t!==!1&&!w.has(t),T=t=>t===void 0||t==="/"?"":t.replace(P,""),nt=t=>`${T(t)}${i}`,B=t=>{try{return new URL(t,"http://localhost").pathname}catch{const d=t.indexOf("?");return d===-1?t:t.slice(0,d)}},at=t=>{const{logger:d,projectRoot:c}=t,u=T(t.base);let l,S;const p=v(c,()=>x({adminToken:A(c),advisorProcedures:!0,basePath:i,dataEditable:!0,rulesInstalled:C(c).installed,runAsIdentity:!0,schemaEditable:!0,scriptSrc:M,styleHref:m})),D=(s,o,e)=>{const n=N();if((l===void 0||n!==S)&&(l=E(d),S=n),l===void 0){e.statusCode=501,e.setHeader("Content-Type","text/plain"),e.end("Lunora studio assets not found — install and build @lunora/studio.");return}const a=s===m,r=s.slice(s.lastIndexOf("/")+1);if(a){h(o,e,l.styles,"text/css; charset=utf-8",r,n);return}const f=H(r);if(f===void 0){e.statusCode=404,e.setHeader("Content-Type","text/plain"),e.end("Not found");return}h(o,e,f,R(r),r,n)};return(s,o,e)=>{const n=B(s.url??"").replace(P,""),a=u!==""&&n.startsWith(u)?n.slice(u.length):n;if(a!==i&&!a.startsWith(`${i}/`)){e();return}if(t.isNonLoopbackBind||F(s,d)!==void 0){o.statusCode=403,o.setHeader("Content-Type","text/plain"),o.end("Lunora studio is only available on loopback hosts in dev.");return}const r=q[a];if(r!==void 0){j(s,o,r,c,{apiSpec:t.apiSpec,lazyFunctions:t.lazyFunctions,schemaDirectory:t.schemaDirectory});return}if(a===m||y(a)){D(a,s,o);return}_(o,p())}};export{i as STUDIO_PATH,M as STUDIO_SCRIPT_PATH,m as STUDIO_STYLE_PATH,at as createStudioMiddleware,st as isNonLoopbackHost,B as requestPathname,nt as studioMountPath};
@@ -0,0 +1 @@
1
+ import{existsSync as h}from"node:fs";import{dirname as y,join as p}from"node:path";import{discoverSchemaInfo as w}from"./discoverSchemaInfo-DRPnqgif.mjs";import{MERGED_DURABLE_OBJECT as i,GENERATED_DIRECTORY as E,MERGED_ROLE_DURABLE_OBJECTS as u,COMPOSED_ENTRY_DURABLE_OBJECTS as $,GENERATED_CLASS_MODULES as k,isFrameworkDurableObject as D}from"./COMPOSED_WORKER_ENTRY-LpLlp-aF.mjs";import{o as R,f as j}from"./validate-bindings-CQbR23li.mjs";import{validateSchedulerOrigin as x}from"./withTailConsumer-CKXL6P6s.mjs";import{l as O,r as _,s as A}from"./worker-entry-checks-DH-ApvvX.mjs";import{mergeWranglerEnvironment as S}from"./mergeWranglerEnvironment-D5ekKj5x.mjs";import{findWranglerFile as W,readWranglerJsonc as C}from"./WRANGLER_FILES-BF8PUjuo.mjs";import{validateWranglerConfig as T}from"./REQUIRED_COMPATIBILITY_DATE-BPxR2Ht_.mjs";const v=r=>Array.isArray(r)?r:[],L=(r,t,o)=>Object.entries(r?.images??{}).flatMap(([s,n])=>{const e=n?.dockerfile;return typeof e!="string"||h(e.startsWith("/")?e:p(t,e))?[]:[`containers images["${s}"] dockerfile "${e}" does not exist (resolved relative to ${o}); create the Dockerfile`]}),I=(r,t,o)=>{const s=[];for(const n of v(r)){const e=n?.image;typeof e=="string"&&(e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.includes("Dockerfile"))&&!h(e.startsWith("/")?e:p(t,e))&&s.push(`containers image "${e}" does not exist (resolved relative to ${o}); create the Dockerfile or point image at a registry reference`),s.push(...L(n,t,o))}return s},P=(r,t)=>{const o=r?.vectorIndexNames??[],s=[];if(o.length>0&&s.push({message:e=>`schema declares vector index(es) ${o.map(l=>`"${l}"`).join(", ")} but nothing chains .vectors(...) onto defineApp() (composed in: ${e}) — \`ctx.vectors\` is then a throwing stub and buildWorkerOptions rejects EVERY request, /_lunora/health included. Add \`.vectors((env) => ({ ${String(o[0])}: env.<BINDING> }))\` to the chain.`,method:"vectors"}),r?.hasD1GlobalTable&&s.push({message:e=>`schema declares .global() table(s) but nothing chains .global(...) onto defineApp() (composed in: ${e}) — the shard then has no global writer, so every read or write of a global table throws INTERNAL ("requires a globalDb writer"). Add \`.global({ d1: (env) => env.DB })\` to the chain.`,method:"global"}),r?.hasHyperdriveGlobalTable&&s.push({message:e=>`schema declares .global({ backend: "hyperdrive" }) table(s) but nothing chains .hyperdriveGlobal(...) onto defineApp() (composed in: ${e}) — the shard then has no global writer, so every read or write of those tables throws INTERNAL. Add \`.hyperdriveGlobal({ engine: "postgres", exec: (env) => buildPgExec(fromPostgresJs(async () => (await import("postgres")).default(env.HYPERDRIVE.connectionString, { fetch_types: false, max: 5 }))) })\` to the chain (\`buildPgExec\` from \`@lunora/hyperdrive/global\`, \`fromPostgresJs\` from \`@lunora/hyperdrive\`).`,method:"hyperdriveGlobal"}),s.length===0)return[];const n=A(t,new Set(s.map(e=>e.method)));return n===void 0?[]:s.filter(e=>!n.chained.has(e.method)).map(e=>e.message(n.site))},G="does not export it",B=(r,t)=>{if(t.exports?.has(i)===!0&&u.has(r))return`This app merges its Durable Objects (\`durableObjects.merge\` in lunora.config), so ${i} hosts ${r}: bind only \`SHARD\` to "${i}" and drop the SCHEDULER / SHARD_REGISTRY bindings. Do that only if this Worker has never been deployed — a deployed ${r} namespace keeps its data, which the merged class cannot reach; turn \`durableObjects.merge\` off to keep it.`;if(r===i)return`${i} is the merged class (\`durableObjects.merge\` in lunora.config), and merging cannot be undone once deployed: the shard data lives in ${i}. Turn \`durableObjects.merge\` back on. Only a Worker that has never been deployed may rebind SHARD to "ShardDO".`;if(t.kind!=="composed")return`Re-export it from the module that defines it (\`export { ${r} } from "./…";\`), or add it to the app builder's own export (\`export const { ${r} } = app;\`).`;const o=`it exports ${$.join(", ")}, SchedulerDO when its binding is declared, and every class codegen emits from your ${k.map(s=>`${s}.ts`).join(" / ")} declarations`;return D(r)?`\`@lunora/vite\` generates that entry — ${o}, and ${r} is not among them. Class-A composition does not carry ${r}, so drop the binding; a project that needs it has to own its worker entry (add \`src/worker.ts\`, which \`lunora deploy\` bundles in place of \`main\`, and compose \`defineApp()\` there).`:`\`@lunora/vite\` generates that entry, so there is no file to add a re-export to: ${o}. Declare "${r}" in one of those and re-run \`lunora codegen\`, or drop the binding.`},M=(r,t)=>{const o=t.exports;if(o===void 0)return[];const s=[];for(const e of R(r.durable_objects?.bindings))typeof e.class_name=="string"&&e.class_name.length>0&&e.script_name===void 0&&s.push({className:e.class_name,label:"durable_objects.bindings"});for(const e of v(r.workflows))typeof e?.class_name=="string"&&e.class_name.length>0&&e.script_name===void 0&&s.push({className:e.class_name,label:"workflows"});for(const[e,l]of Object.entries(r.exports??{}))l?.type==="workflow"&&s.push({className:e,label:"workflows"});return s.filter(e=>!o.has(e.className)).map(e=>`${e.label} declares class "${e.className}" but the ${t.kind==="composed"?"composed class-A worker entry":"worker entry"} (${t.path}) ${G} — wrangler refuses to bundle a Worker whose ${e.label==="workflows"?"Workflow":"Durable Object"} classes are not exported. ${B(e.className,t)}`)},N=r=>[...j(r.migrations)].filter(t=>u.has(t)).map(t=>`migrations create class "${t}", which this app hosts in ${i} because it merges its Durable Objects (\`durableObjects.merge\`). Before the first deploy, replace "${t}" with "${i}" in new_sqlite_classes; a Worker already deployed with "${t}" keeps its data there and cannot merge — turn \`durableObjects.merge\` off.`),U=r=>r?.origin!=="absent"?[]:[`main is set but no readable file is there (looked in ${r.path}) — wrangler cannot resolve the worker entry, so a deploy will fail there. Point main at the entry that composes your app, or remove it to fall back to the conventional locations.`],Z=r=>{const t=r.schemaDir??"lunora",o=W(r.projectRoot);if(!o){const c=`wrangler.jsonc not found in ${r.projectRoot}; create one declaring at least the SHARD durable object binding.`;return{problems:[c],report:{errors:[c],valid:!1,warnings:[]},wranglerPath:void 0}}const{parsed:s}=C(o);if(s===void 0){const c=`failed to parse ${o} as JSONC.`;return{problems:[c],report:{errors:[c],valid:!1,warnings:[]},wranglerPath:o}}const{error:n,merged:e}=S(s,r.environment);if(n!==void 0)return{problems:[n],report:{errors:[n],valid:!1,warnings:[]},wranglerPath:o};const{error:l,info:f}=w(r.projectRoot,t,r.cache),a=T(s,f,r.environment);l!==void 0&&a.warnings.push(`schema parse failed in ${t}/schema.ts: ${l}`);const g=y(o),b=O(e.main,r.projectRoot,o),m=_(b,r.projectRoot,t);a.errors.push(...I(e.containers??[],g,o)),a.warnings.push(...U(b)),m!==void 0&&a.errors.push(...M(e,m)),m?.exports?.has(i)===!0&&(a.errors.push(...N(e)),h(p(r.projectRoot,t,E,"scheduler.ts"))&&x(e,r.environment,a.warnings,"the merged LunoraDO hosts the scheduler")),a.errors.push(...P(f,r.projectRoot));const d=e.assets?.directory;if(typeof d=="string"&&d.length>0){const c=d.startsWith("/")?d:p(g,d);h(c)||a.warnings.push(`assets.directory "${d}" does not exist yet — it is created by the client build; run the build before deploy`)}return a.valid=a.errors.length===0,{problems:a.errors,report:a,wranglerPath:o}};export{G as UNEXPORTED_CLASS_MARKER,Z as validateWranglerProject};
@@ -0,0 +1 @@
1
+ import{existsSync as n,readFileSync as a}from"node:fs";import{parse as s}from"jsonc-parser";import{join as c}from"node:path";const i=["wrangler.jsonc","wrangler.json"],d=t=>{for(const r of i){const e=c(t,r);if(n(e))return e}},l=t=>{const r=a(t,"utf8"),e=[],o=s(r,e,{allowTrailingComma:!0});return e.length>0||o===null||typeof o!="object"?{parsed:void 0,text:r}:{parsed:o,text:r}},m=t=>{const r=d(t);if(r!==void 0)try{return{parsed:l(r).parsed,path:r}}catch{return{parsed:void 0,path:r}}};export{i as WRANGLER_FILES,d as findWranglerFile,m as readProjectWrangler,l as readWranglerJsonc};
@@ -1 +1 @@
1
- import{readProjectConfigLiterals as s,readProjectTarget as c}from"@lunora/codegen";import n from"./canonicalPath-DrfMiT3U.mjs";import{BUILD_TARGET_ENV as i,BUILD_ROOT_ENV as a}from"./BUILD_ROOT_ENV-Dg4MV3wY.mjs";import{DEFAULT_DEPLOY_TARGET as p,resolveDeployDriver as f}from"./DEFAULT_DEPLOY_TARGET-DllYb7Tj.mjs";const d=e=>{if(typeof e=="boolean")return e;if(e!==null&&typeof e=="object")return!0},P=e=>d(s(e).remote),T=e=>c(e),g=(e,t)=>t??T(e)??p,j=(e,t)=>{const r=g(e,t);return f(r),r},v=(e,t)=>{const r=process.env[i],o=process.env[a];if(!(o===void 0||o===""||n(o)!==n(t))&&r!==void 0&&r!==""&&r!==e)throw new Error(`the plugin resolves target "${e}" but the CLI resolved "${r}" for this run; set the same target in the plugin options and the project config`)};export{v as assertBuildTargetMatches,d as interpretRemote,P as readProjectRemotePreference,T as readProjectTarget,g as resolveProjectTarget,j as resolveTargetOrThrow};
1
+ import{readProjectConfigLiterals as s,readProjectTarget as c}from"@lunora/codegen";import n from"./canonicalPath-DrfMiT3U.mjs";import{BUILD_TARGET_ENV as i,BUILD_ROOT_ENV as a}from"./BUILD_ROOT_ENV-Dg4MV3wY.mjs";import{DEFAULT_DEPLOY_TARGET as p,resolveDeployDriver as f}from"./DEFAULT_DEPLOY_TARGET-CAJl2nEI.mjs";const d=e=>{if(typeof e=="boolean")return e;if(e!==null&&typeof e=="object")return!0},P=e=>d(s(e).remote),T=e=>c(e),g=(e,t)=>t??T(e)??p,j=(e,t)=>{const r=g(e,t);return f(r),r},v=(e,t)=>{const r=process.env[i],o=process.env[a];if(!(o===void 0||o===""||n(o)!==n(t))&&r!==void 0&&r!==""&&r!==e)throw new Error(`the plugin resolves target "${e}" but the CLI resolved "${r}" for this run; set the same target in the plugin options and the project config`)};export{v as assertBuildTargetMatches,d as interpretRemote,P as readProjectRemotePreference,T as readProjectTarget,g as resolveProjectTarget,j as resolveTargetOrThrow};
@@ -1,3 +1,3 @@
1
- import{LunoraError as n}from"@lunora/errors";import{lunoraLine as i}from"./LUNORA_TAG-DQTGPqcJ.mjs";import{validateWranglerProject as c}from"./UNEXPORTED_CLASS_MARKER-YnIX5BDi.mjs";const m=(e,o,t)=>{const r=c({cache:e.cache,projectRoot:e.projectRoot,schemaDir:e.schemaDir});if(!r.wranglerPath)throw new n("INTERNAL",["[lunora] wrangler.jsonc not found.",` searched in: ${e.projectRoot}`," create a wrangler.jsonc declaring at least the SHARD durable object binding."].join(`
1
+ import{LunoraError as n}from"@lunora/errors";import{lunoraLine as i}from"./LUNORA_TAG-DQTGPqcJ.mjs";import{validateWranglerProject as c}from"./UNEXPORTED_CLASS_MARKER-Zw1oiigQ.mjs";const m=(e,o,t)=>{const r=c({cache:e.cache,projectRoot:e.projectRoot,schemaDir:e.schemaDir});if(!r.wranglerPath)throw new n("INTERNAL",["[lunora] wrangler.jsonc not found.",` searched in: ${e.projectRoot}`," create a wrangler.jsonc declaring at least the SHARD durable object binding."].join(`
2
2
  `));for(const a of r.report.warnings)o(i(`wrangler validator: ${a}`));if(r.problems.length>0)throw new n("INTERNAL",["[lunora] wrangler configuration is missing bindings required by your schema.",` file: ${r.wranglerPath}`,"",...r.problems.map(a=>` - ${a}`),"",` ${t}`].join(`
3
3
  `))};export{m as assertWranglerSatisfiesSchema};
@@ -1,3 +1,3 @@
1
- import{createHash as O,randomUUID as v}from"node:crypto";import{mkdirSync as _,rmSync as y,readFileSync as N,writeFileSync as I,linkSync as w,renameSync as R}from"node:fs";import{findWranglerFile as C,readWranglerJsonc as k}from"./WRANGLER_FILES-UNW-xY5u.mjs";import{join as $}from"node:path";const E=["CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_","WRANGLER_HYPERDRIVE_LOCAL_CONNECTION_STRING_"],p=e=>`${E[0]}${e}`,D="pnpm add -D @electric-sql/pglite @electric-sql/pglite-socket",m="postgres://postgres:postgres@127.0.0.1:1/postgres",A=(e,t,r)=>typeof t.localConnectionString=="string"&&t.localConnectionString!==""||E.some(o=>{const n=r[`${o}${e}`]??"";return n!==""&&n!==m}),H=(e,t,r=t.CLOUDFLARE_ENV,o)=>{const n=o??C(e),i=n===void 0?void 0:k(n).parsed,c=r===void 0||r===""?void 0:i?.env?.[r];return((c===void 0?i?.hyperdrive:c.hyperdrive)??[]).flatMap(a=>typeof a?.binding=="string"&&a.binding!==""&&!A(a.binding,a,t)?[a.binding]:[])},T=async({PGlite:e,PGLiteSocketServer:t,vector:r},o)=>{const n=await e.create({dataDir:o,...r===void 0?{}:{extensions:{vector:r}}});let i;try{i=new t({db:n,host:"127.0.0.1",maxConnections:16,port:0}),await i.start()}catch(a){throw await Promise.allSettled([i?.stop(),n.close()]),a}const[c="127.0.0.1",g="5432"]=i.getServerConn().split(":");return{connectionString:`postgres://postgres:postgres@${c}:${g}/postgres`,stop:async()=>{try{await i.stop()}finally{await n.close()}}}},P=/[^\w-]/gu,F=e=>{const t=e.replaceAll(P,"_");return t===e?e:`${t}-${O("sha256").update(e).digest("hex").slice(0,8)}`},q=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},x=e=>{try{const t=JSON.parse(N($(e,"package.json"),"utf8")),r=new Set([...Object.keys(t.dependencies??{}),...Object.keys(t.devDependencies??{})]);return r.has("mysql2")&&!r.has("pg")&&!r.has("postgres")}catch{return!1}},f=new Set,G=()=>{for(const e of f)y(e,{force:!0});f.clear()};let h=!1;const U=()=>{h||(h=!0,process.once("exit",G))},S=e=>{try{const[t="",r=""]=N(e,"utf8").split(`
1
+ import{createHash as O,randomUUID as v}from"node:crypto";import{mkdirSync as _,rmSync as y,readFileSync as N,writeFileSync as I,linkSync as w,renameSync as R}from"node:fs";import{findWranglerFile as C,readWranglerJsonc as k}from"./WRANGLER_FILES-BF8PUjuo.mjs";import{join as $}from"node:path";const E=["CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_","WRANGLER_HYPERDRIVE_LOCAL_CONNECTION_STRING_"],p=e=>`${E[0]}${e}`,D="pnpm add -D @electric-sql/pglite @electric-sql/pglite-socket",m="postgres://postgres:postgres@127.0.0.1:1/postgres",A=(e,t,r)=>typeof t.localConnectionString=="string"&&t.localConnectionString!==""||E.some(o=>{const n=r[`${o}${e}`]??"";return n!==""&&n!==m}),H=(e,t,r=t.CLOUDFLARE_ENV,o)=>{const n=o??C(e),i=n===void 0?void 0:k(n).parsed,c=r===void 0||r===""?void 0:i?.env?.[r];return((c===void 0?i?.hyperdrive:c.hyperdrive)??[]).flatMap(a=>typeof a?.binding=="string"&&a.binding!==""&&!A(a.binding,a,t)?[a.binding]:[])},T=async({PGlite:e,PGLiteSocketServer:t,vector:r},o)=>{const n=await e.create({dataDir:o,...r===void 0?{}:{extensions:{vector:r}}});let i;try{i=new t({db:n,host:"127.0.0.1",maxConnections:16,port:0}),await i.start()}catch(a){throw await Promise.allSettled([i?.stop(),n.close()]),a}const[c="127.0.0.1",g="5432"]=i.getServerConn().split(":");return{connectionString:`postgres://postgres:postgres@${c}:${g}/postgres`,stop:async()=>{try{await i.stop()}finally{await n.close()}}}},P=/[^\w-]/gu,F=e=>{const t=e.replaceAll(P,"_");return t===e?e:`${t}-${O("sha256").update(e).digest("hex").slice(0,8)}`},q=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},x=e=>{try{const t=JSON.parse(N($(e,"package.json"),"utf8")),r=new Set([...Object.keys(t.dependencies??{}),...Object.keys(t.devDependencies??{})]);return r.has("mysql2")&&!r.has("pg")&&!r.has("postgres")}catch{return!1}},f=new Set,G=()=>{for(const e of f)y(e,{force:!0});f.clear()};let h=!1;const U=()=>{h||(h=!0,process.once("exit",G))},S=e=>{try{const[t="",r=""]=N(e,"utf8").split(`
2
2
  `),o=Number.parseInt(t,10);return Number.isInteger(o)?{kind:"pid",pid:o,token:r}:{kind:"garbage",pid:-1,token:""}}catch(t){return{kind:t.code==="ENOENT"?"gone":"unreadable",pid:-1,token:""}}},L=e=>e.kind==="pid"&&e.pid!==process.pid&&q(e.pid),j=(e,t)=>{try{w(e,t)}catch(r){if(r.code!=="EEXIST")throw r;return}return f.add(t),U(),{release:()=>{f.delete(t)&&y(t,{force:!0})}}},W=(e,t)=>{const r=`${e}.stale.${v()}`;try{R(e,r)}catch{return}const o=S(r);try{if(o.token!==t.token&&L(o)){try{w(r,e)}catch{}return{holder:o.pid}}return}finally{y(r,{force:!0})}},M=e=>{const t=`${e}.${String(process.pid)}.${v()}`;I(t,`${String(process.pid)}
3
3
  ${v()}`,"utf8");try{for(let r=0;r<3;r+=1){const o=j(t,e);if(o!==void 0)return o;if(f.has(e))return{holder:process.pid};const n=S(e);if(n.kind==="unreadable"||L(n))return{holder:n.pid};const i=n.kind==="gone"?void 0:W(e,n);if(i!==void 0)return i}return{holder:S(e).pid}}finally{y(t,{force:!0})}},V=/@electric-sql\/pglite/u,B=async()=>{try{const[{PGlite:e},{PGLiteSocketServer:t}]=await Promise.all([import("@electric-sql/pglite"),import("@electric-sql/pglite-socket")]),r=await import("@electric-sql/pglite-pgvector").then(o=>o.vector,()=>{});return{createServer:async o=>T({PGlite:e,PGLiteSocketServer:t,vector:r},o)}}catch(e){const{code:t,message:r}=e;if((t==="ERR_MODULE_NOT_FOUND"||t==="MODULE_NOT_FOUND")&&V.test(r??""))return;throw e}},Q=async e=>{try{return{runtime:await e()}}catch(t){return{failure:t instanceof Error?t.message:String(t)}}},J=async(e,t,r)=>{try{const o=await e.createServer(t);return{connectionString:o.connectionString,stop:async()=>{try{await o.stop()}finally{r.release()}}}}catch(o){throw r.release(),o}},X=(e,t)=>`Hyperdrive binding ${e.map(r=>`"${r}"`).join(", ")}: the embedded Postgres is installed but failed to load (${t}), so \`ctx.sql\` will fail to connect in dev. Set ${p(e[0]??"<BINDING>")} to use a database of your own.`,Y=(e,t)=>{const r=e.map(n=>`"${n}"`).join(", "),o=p(e[0]??"<BINDING>");return t?`Hyperdrive binding ${r}: this project's SQL driver is mysql2, and the embedded database speaks PostgreSQL, so \`ctx.sql\` will fail to connect in dev. Set ${o} to a local MySQL connection string.`:`Hyperdrive binding ${r} has no local database, so \`ctx.sql\` will fail to connect in dev. Run \`${D}\` for an embedded Postgres, or set ${o}.`},te=async e=>{const t=e.env??process.env,r=H(e.projectRoot,t,void 0,e.wranglerConfigPath);if(r.length===0)return;const o=new Map,n=s=>{t[p(s)]=m,o.set(s,m)},i=[],c=async()=>{const s=i.splice(0),l=[...o];o.clear();for(const[d,u]of l)t[p(d)]===u&&Reflect.deleteProperty(t,p(d));await Promise.allSettled(s.map(async d=>d.stop()))},g=x(e.projectRoot),{failure:a,runtime:b}=g?{failure:void 0,runtime:void 0}:await Q(e.load??B);if(b===void 0){e.onWarning?.(a===void 0?Y(r,g):X(r,a));for(const s of r)n(s);return{bindings:[],stop:c}}try{for(const s of r){const l=$(e.projectRoot,".wrangler","state","lunora-pglite",F(s));_(l,{recursive:!0});const d=M(`${l}.lock`);if("holder"in d){e.onWarning?.(`Hyperdrive binding "${s}": another process (pid ${String(d.holder)}) has its embedded Postgres open, so \`ctx.sql\` will fail to connect here. Stop it, or set ${p(s)} to use a database of your own.`),n(s);continue}const u=await J(b,l,d);i.push({binding:s,stop:u.stop}),t[p(s)]=u.connectionString,o.set(s,u.connectionString)}}catch(s){e.onWarning?.(`Could not start the embedded Postgres for Hyperdrive: ${s instanceof Error?s.message:String(s)}`),await c();for(const l of r)n(l);return{bindings:[],stop:c}}return{bindings:i.map(({binding:s})=>s),stop:c}};export{H as bindingsNeedingDatabase,G as releaseHeldLocks,T as serveDatabase,te as startLocalHyperdrive};
@@ -0,0 +1,19 @@
1
+ import{randomBytes as V}from"node:crypto";import{existsSync as j,readFileSync as x,writeFileSync as h,linkSync as B,rmSync as m,renameSync as L,statSync as O}from"node:fs";import{join as g}from"node:path";import{LunoraError as z}from"@lunora/errors";import{DEV_VARS_FILE as u,DEV_VARS_EXAMPLE_FILE as f,parseDevVariableLine as K,parseDevVariableEntries as E,DEV_VARS_NEWLINE as b}from"./DEV_VARS_EXAMPLE_FILE-hBT89IXh.mjs";import{MINTABLE_SECRET_KEYS as W,SHARD_RELAY_SECRET_KEY as y,CORE_SECRETS as P,mintableSecretKeysFor as U,SHARD_RELAY_HOST_PLACEHOLDER as Y,secretsForPackages as X}from"./PACKAGE_SECRETS_REGISTRY-CPWkw-qE.mjs";const H=e=>[...P,...X(e)],k=32,G=["replace","openssl","changeme","change-me","change_me","change-this","change_this","your-","your_","example","placeholder","todo","fill-me","fill_me","fill-in","fill_in","xxx"],q=/[.*+?^${}()|[\]\\]/gu,J=/[a-z0-9]$/u,T=e=>{const t=e.trim().toLowerCase();return t===""||t.startsWith("<")&&t.endsWith(">")?!0:G.some(n=>{const r=n.replaceAll(q,String.raw`\$&`),s=J.test(n)?`(^|[^a-z0-9])${r}([^a-z0-9]|$)`:`(^|[^a-z0-9])${r}`;return new RegExp(s,"u").test(t)})},p=e=>V(e).toString("hex"),w=new Set([...W,y]),Q=(e,t,n=w)=>e===y?n.has(e)&&(t.trim()===""||t===Y):n.has(e),F=(e,t,n,r)=>Q(e,t,r)&&T(t)?n(k):void 0,me=(e=p)=>e(k),M=(e,t,n,r=w)=>e.split(b).map(o=>{const s=K(o),i=s?F(s.key,s.value,t,r):void 0;return!s||i===void 0?o:(n.push(s.key),`${s.key}="${i}"`)}),Z=e=>{if(e.devVarsExists)return{status:"exists"};if(e.exampleContent===void 0)return{status:"no-example"};const t=[];return{content:M(e.exampleContent,e.randomHex??p,t).join(`
2
+ `),generatedKeys:t,status:"generate"}},ee=e=>e.includes('"')||e.includes("\\")?"":e.replaceAll("\r",String.raw`\r`).replaceAll(`
3
+ `,String.raw`\n`),A=e=>{const t=e.randomHex??p,n=new Set(E(e.existingContent).map(i=>i.key)),r=[],o=[],s=[];for(const i of e.exampleContent.split(b)){const a=K(i);if(!a||n.has(a.key))continue;const l=F(a.key,a.value,t,w);s.push(a.key),l===void 0?r.push(`${a.key}="${ee(a.value)}"`):(o.push(a.key),r.push(`${a.key}="${l}"`))}return{additions:r,generatedKeys:o,missingKeys:s}},R=e=>e.length>0?` (generated ${e.join(", ")})`:"",I=e=>`${e}.tmp-${String(process.pid)}`,v=(e,t,n={})=>{const r=I(e);try{h(r,t,{encoding:"utf8",...n}),L(r,e)}catch(o){throw m(r,{force:!0}),o}},te=(e,t)=>{try{return h(e,t,{encoding:"utf8",flag:"wx",mode:384}),!0}catch(n){if(n.code==="EEXIST")return!1;throw n}},N=(e,t)=>{const n=I(e);try{h(n,t,{encoding:"utf8",flag:"wx",mode:384});try{return B(n,e),!0}catch(r){const{code:o}=r;if(o==="EEXIST")return!1;if(o==="EPERM"||o==="ENOTSUP")return te(e,t);throw r}}finally{m(n,{force:!0})}},ge=(e,t)=>{v(e,t,{mode:384})},D=5,C=e=>{try{const t=O(e);return{mtimeMs:t.mtimeMs,size:t.size}}catch{return}},ne=(e,t)=>e===void 0||t===void 0?!1:e.mtimeMs===t.mtimeMs&&e.size===t.size,re=(e,t)=>{for(let n=0;n<D;n+=1){const r=C(e),o=x(e,"utf8"),s=t(o);if(s.length===0)return[];const i=o.length>0&&!o.endsWith(`
4
+ `)?`
5
+ `:"",a=`${o}${i}${s.join(`
6
+ `)}
7
+ `,l=`${e}.tmp-${String(process.pid)}-${V(6).toString("hex")}`;try{h(l,a,{encoding:"utf8",mode:384});const c=C(e);if(!ne(r,c)){m(l,{force:!0});continue}return L(l,e),s}catch(c){throw m(l,{force:!0}),c}}throw new z("INTERNAL",`Failed to append to ${e} after ${String(D)} attempts — a concurrent writer kept winning the race.`)},se=new Set(["EACCES","EISDIR","EPERM"]),$=e=>{try{return{content:x(e,"utf8"),kind:"read"}}catch(t){const{code:n}=t;if(n==="ENOENT")return{kind:"missing"};if(n!==void 0&&se.has(n))return{code:n,kind:"unreadable"};throw t}},he=async e=>{const t=g(e.cwd,u),n=$(t),r=$(g(e.cwd,f));for(const[d,S]of[[u,n],[f,r]])if(S.kind==="unreadable")return(e.warn??e.info)(`skipped the ${u} scaffold: ${d} is not a readable file (${S.code})`),{addedKeys:[],generatedKeys:[],status:"unreadable"};if(r.kind!=="read")return{addedKeys:[],generatedKeys:[],status:"no-example"};const o=r.content;if(n.kind!=="read"){const d=Z({devVarsExists:!1,exampleContent:o,randomHex:e.randomHex});return d.status!=="generate"?{addedKeys:[],generatedKeys:[],status:"no-example"}:e.yes===!0||await e.confirm(`No ${u} found. Generate it from ${f} (secrets auto-filled)?`)?N(t,d.content)?(e.info(`Created ${u}${R(d.generatedKeys)}.`),{addedKeys:[],generatedKeys:d.generatedKeys,status:"generated"}):{addedKeys:[],generatedKeys:[],status:"skipped-exists"}:(e.info(`Skipped — copy ${f} to ${u} and fill it in when you're ready.`),{addedKeys:[],generatedKeys:[],status:"declined"})}const s=A({existingContent:n.content,exampleContent:o,randomHex:e.randomHex});if(s.missingKeys.length===0)return{addedKeys:[],generatedKeys:[],status:"exists"};const i=s.missingKeys.join(", ");if(!(e.yes===!0||await e.confirm(`${u} is missing ${String(s.missingKeys.length)} key(s) from ${f} (${i}). Add them?`)))return e.info(`Skipped — add ${i} to ${u} when you're ready.`),{addedKeys:[],generatedKeys:[],status:"declined"};const c=re(t,d=>A({existingContent:d,exampleContent:o,randomHex:e.randomHex}).additions).map(d=>K(d)?.key).filter(d=>d!==void 0);if(c.length===0)return{addedKeys:[],generatedKeys:[],status:"exists"};const _=s.generatedKeys.filter(d=>c.includes(d));return e.info(`Updated ${u} — added ${c.join(", ")}${R(_)}.`),{addedKeys:c,generatedKeys:_,status:"augmented"}},oe=e=>[`# ${e.description}`,`# Docs: ${e.docsUrl}`,`${e.key}="${e.placeholderValue}"`].join(`
8
+ `),ie=(e,t)=>{const n=H(e).filter(r=>!t.has(r.key));return n.length===0?"":n.map(r=>oe(r)).join(`
9
+
10
+ `)},Ee=(e,t)=>{const n=g(e,f),r=j(n)?x(n,"utf8"):"",o=new Set(E(r).map(a=>a.key)),s=ie(t,o);if(s==="")return[];const i=r.length>0&&!r.endsWith(`
11
+ `)?`
12
+ `:"";return v(n,`${r}${i}
13
+ ${s}
14
+ `),H(t).filter(a=>!o.has(a.key)).map(a=>a.key)},ae=e=>{const t=e.randomHex??p,n=[],r=M(e.existingContent,t,n,e.mintable),o=new Set(E(e.existingContent).map(c=>c.key)),s=[],i=[];for(const c of P)o.has(c.key)||(s.push(c.key),i.push(`# ${c.description}`,`${c.key}="${t(k)}"`));const a=r.join(`
15
+ `);if(i.length===0)return{addedKeys:s,content:a,filledKeys:n};const l=a===""||a.endsWith(`
16
+ `)?"":`
17
+ `;return{addedKeys:s,content:`${a}${l}${i.join(`
18
+ `)}
19
+ `,filledKeys:n}},pe=e=>{const t=g(e.cwd,u),n=$(t);if(n.kind==="unreadable")return{addedKeys:[],filledKeys:[],status:"unchanged"};const r=n.kind==="read",o=r?n.content:"",s=e.secretSources===void 0?void 0:U(e.secretSources),i=ae({existingContent:o,mintable:s,randomHex:e.randomHex}),a=E(i.content).find(c=>c.key===y)?.value;if(s!==void 0&&!s.has(y)&&a!==void 0&&T(a)&&e.info?.(`${y} is still a placeholder. This worker only calls an event log hosted elsewhere, so set it to the ${y} of the worker that hosts EventLogDO.`),i.filledKeys.length===0&&i.addedKeys.length===0)return{addedKeys:[],filledKeys:[],status:"unchanged"};if(r)v(t,i.content,{mode:384});else if(!N(t,i.content))return{addedKeys:[],filledKeys:[],status:"unchanged"};const l=[...i.filledKeys,...i.addedKeys];return e.info?.(`Generated ${String(l.length)} dev secret(s) in ${u}: ${l.join(", ")}`),{addedKeys:i.addedKeys,filledKeys:i.filledKeys,status:r?"filled":"created"}};export{ie as buildPackageSecretsBlock,he as ensureDevVariables,Ee as ensureDevVarsExample,pe as fillDevSecrets,me as generateSecretValue,Q as isMintableSecretKey,T as isPlaceholderValue,ae as planDevSecretsFill,A as planDevVariablesAugment,Z as planDevVariablesScaffold,H as requiredSecrets,ge as writeDevVariablesFileAtomically};
@@ -1,3 +1,3 @@
1
- import{writeFileSync as $,rmSync as W,existsSync as w,readFileSync as A}from"node:fs";import{dirname as E,resolve as h,join as v,sep as y,relative as _,isAbsolute as B}from"node:path";import{MissingBuildOutputError as x}from"./MissingBuildOutputError-BAyekzof.mjs";import{D1_PLACEHOLDER_ID as F}from"./D1_PLACEHOLDER_ID-ZnDjVymH.mjs";import{findWranglerFile as K,readWranglerJsonc as Y}from"./WRANGLER_FILES-UNW-xY5u.mjs";import{DEV_VARS_FILE as G,parseDevVariableEntries as J}from"./DEV_VARS_EXAMPLE_FILE-CqLorAxT.mjs";import D from"./ensureGitignoreEntries-Tsk8Qkw7.mjs";import{c as k}from"./celld-binding-id-9MiUoteo.mjs";const q=".celld.wrangler.json",C=[".celld/",".celld.wrangler.json",".celld.service.*.wrangler.json"],M=v(".wrangler","deploy","config.json"),U=new Set(["$schema","assets","compatibility_date","compatibility_flags","containers","d1_databases","define","durable_objects","kv_namespaces","main","migrations","name","no_bundle","queues","r2_buckets","rules","services","triggers","vars","worker_loaders","workflows"]),H=new Set(["class_name","image","instance_type","max_instances","name","runtime"]),X=new Set(["CompiledWasm","Data","Text"]),z=/\r?\n/u,Q=/[!*?[]/u,Z=/[.[]/u,ee=["deleted_classes","new_classes","renamed_classes","transferred_classes"],c=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),I=e=>Array.isArray(e)&&e.length===0||c(e)&&Object.values(e).every(s=>I(s)),re=e=>Array.isArray(e)?e.map(s=>{if(!c(s))return s;const r=ee.find(t=>s[t]!==void 0);if(r!==void 0)throw new Error(`migration "${String(s.tag)}" uses \`${r}\`, which celld refuses — celld accepts only \`new_sqlite_classes\` migrations`);return{new_sqlite_classes:s.new_sqlite_classes,tag:s.tag}}):e,se=(e,s)=>Array.isArray(e)?e.map((r,t)=>c(r)?Object.fromEntries(Object.entries(r).filter(([n])=>{const i=H.has(n);return i||s.push(`containers[${String(t)}].${n}`),i})):r):e,te=(e,s)=>Array.isArray(e)?e.filter((r,t)=>{const n=c(r)&&typeof r.type=="string"&&X.has(r.type);return n||s.push(`rules[${String(t)}]`),n}):e,ne=e=>{const s=[],r={};for(const[t,n]of Object.entries(c(e)?e:{}))c(n)&&n.type==="workflow"?s.push({binding:t,class_name:t,name:n.name}):r[t]=n;return{bindings:s,rest:r}},ie=(e,s)=>Array.isArray(e)?e.map(r=>!c(r)||r.database_id!==F?r:typeof r.database_name=="string"?{...r,database_id:r.database_name}:typeof r.binding=="string"?{...r,database_id:k(s,r.binding)}:r):e,oe=(e,s)=>Array.isArray(e)?e.map(r=>c(r)&&r.id===void 0&&typeof r.binding=="string"?{...r,id:k(s,r.binding)}:r):e,N=e=>{const s=[],r={},t=ne(e.exports),n={...e,exports:t.rest};for(const[i,o]of Object.entries(n)){if(!U.has(i)){I(o)||s.push(i);continue}switch(i){case"containers":{r[i]=se(o,s);break}case"d1_databases":{r[i]=ie(o,e.name);break}case"kv_namespaces":{r[i]=oe(o,e.name);break}case"migrations":{r[i]=re(o);break}case"rules":{r[i]=te(o,s);break}default:r[i]=o}}if(t.bindings.length>0){const i=Array.isArray(r.workflows)?r.workflows:[];r.workflows=[...i,...t.bindings]}return{config:r,dropped:s}},ae=e=>{const[s=[],...r]=e.map(n=>h(n).split(y));let t=0;for(;t<s.length&&r.every(n=>n[t]===s[t]);)t+=1;return s.slice(0,t).join(y)||y},P=(e,s,r)=>{const t=i=>_(r,h(s,i)).split(y).join("/"),n={...e};return typeof e.main=="string"&&(n.main=t(e.main)),c(e.assets)&&typeof e.assets.directory=="string"&&(n.assets={...e.assets,directory:t(e.assets.directory)}),n},ce=e=>{const s=v(e,".assetsignore");if(!w(s))return;const r=A(s,"utf8").split(z).map(t=>t.trim()).filter(t=>t!==""&&!t.startsWith("#")).filter(t=>Q.test(t)||w(v(e,t)));if(r.length>0)throw new Error(`${s} hides ${r.join(", ")} from the assets, and celld has no .assetsignore — remove those files from ${e} first`);return s},le=(e,s)=>{const r=v(e,M);if(!w(r))throw new x(`wrangler \`main\` is the Vite virtual module "${s}", so celld deploys the Vite build output — and there is none yet. Run the project's build (\`vite build\`) first`);const{configPath:t}=JSON.parse(A(r,"utf8"));if(typeof t!="string")throw new TypeError(`${r} names no configPath`);return h(E(r),t)},S=e=>{const{parsed:s}=Y(e);if(s===void 0)throw new Error(`${e} is not valid JSONC`);return s},T=(e,s,r,t)=>{const{d1_databases:n}=e;if(!Array.isArray(n)||t===r)return e;const i=Array.isArray(s.d1_databases)?s.d1_databases.filter(o=>c(o)):[];return{...e,d1_databases:n.map(o=>{if(!c(o))return o;const a=i.find(m=>m.binding===o.binding),l=a?.migrations_dir,p=h(r,typeof l=="string"?l:"migrations"),d=w(p)?{...o,migrations_dir:_(t,p).split(y).join("/")}:o,f=a?.migrations_pattern;return typeof f=="string"?{...d,migrations_pattern:_(t,h(r,f)).split(y).join("/")}:d})}},de=(e,s,r,t)=>{const{main:n}=r;if(typeof n!="string"||!n.startsWith("virtual:"))return{fromBuild:!1,source:r,sourcePath:s};if(t==="dev")throw new Error(`wrangler \`main\` is the Vite virtual module "${n}", which only a Vite build can resolve — \`celld dev\` rebuilds from a source file. Use \`vite dev\` for the dev loop and \`lunora deploy\` to ship the build to celld, or point \`main\` at a worker file`);const i=le(e,n);return{fromBuild:!0,source:S(i),sourcePath:i}},fe=(e,s,r,t,n)=>{const i=s.filter(l=>Object.hasOwn(r,l.split(Z)[0]??l));let o=e;e.no_bundle!==void 0&&(o=Object.fromEntries(Object.entries(e).filter(([l])=>l!=="no_bundle")),i.push("no_bundle (celld re-bundles the build output)"));const a=t===void 0?void 0:ce(t);return a!==void 0&&i.push(`${_(n,a)} (matched no files)`),{assetsIgnore:a,projected:o,reported:i}},R=(e,s={})=>{const r=c(e.vars)?e.vars:{};return{...e,vars:{...r,WORKER_ENV:"development",...s}}},_e=(e,s)=>{const r=K(e);if(r===void 0)throw new Error(`no wrangler.jsonc or wrangler.json in ${e} — celld deploys from the project's Wrangler config`);const t=S(r),{fromBuild:n,source:i,sourcePath:o}=de(e,r,t,s),a=E(o),{config:l,dropped:p}=N(i),{assets:d}=i,f=c(d)&&typeof d.directory=="string"?h(a,d.directory):void 0,m=typeof i.main=="string"?E(h(a,i.main)):void 0,u=ae([a,m,f].filter(L=>L!==void 0));if(!n&&u!==a)throw new Error(`wrangler \`main\` and \`assets.directory\` must sit inside ${a} — celld resolves everything against the config's directory`);const b=T(P(l,a,u),t,e,u),g=n?fe(b,p,t,f,u):{assetsIgnore:void 0,projected:b,reported:p},j=s==="dev"?R(g.projected):g.projected,O=v(u,q),V=`${JSON.stringify(j,void 0,4)}
1
+ import{writeFileSync as $,rmSync as W,existsSync as w,readFileSync as A}from"node:fs";import{dirname as E,resolve as h,join as v,sep as y,relative as _,isAbsolute as B}from"node:path";import{MissingBuildOutputError as x}from"./MissingBuildOutputError-BAyekzof.mjs";import{D1_PLACEHOLDER_ID as F}from"./D1_PLACEHOLDER_ID-ZnDjVymH.mjs";import{findWranglerFile as K,readWranglerJsonc as Y}from"./WRANGLER_FILES-BF8PUjuo.mjs";import{DEV_VARS_FILE as G,parseDevVariableEntries as J}from"./DEV_VARS_EXAMPLE_FILE-hBT89IXh.mjs";import D from"./ensureGitignoreEntries-Tsk8Qkw7.mjs";import{c as k}from"./celld-binding-id-9MiUoteo.mjs";const q=".celld.wrangler.json",C=[".celld/",".celld.wrangler.json",".celld.service.*.wrangler.json"],M=v(".wrangler","deploy","config.json"),U=new Set(["$schema","assets","compatibility_date","compatibility_flags","containers","d1_databases","define","durable_objects","kv_namespaces","main","migrations","name","no_bundle","queues","r2_buckets","rules","services","triggers","vars","worker_loaders","workflows"]),H=new Set(["class_name","image","instance_type","max_instances","name","runtime"]),X=new Set(["CompiledWasm","Data","Text"]),z=/\r?\n/u,Q=/[!*?[]/u,Z=/[.[]/u,ee=["deleted_classes","new_classes","renamed_classes","transferred_classes"],c=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),I=e=>Array.isArray(e)&&e.length===0||c(e)&&Object.values(e).every(s=>I(s)),re=e=>Array.isArray(e)?e.map(s=>{if(!c(s))return s;const r=ee.find(t=>s[t]!==void 0);if(r!==void 0)throw new Error(`migration "${String(s.tag)}" uses \`${r}\`, which celld refuses — celld accepts only \`new_sqlite_classes\` migrations`);return{new_sqlite_classes:s.new_sqlite_classes,tag:s.tag}}):e,se=(e,s)=>Array.isArray(e)?e.map((r,t)=>c(r)?Object.fromEntries(Object.entries(r).filter(([n])=>{const i=H.has(n);return i||s.push(`containers[${String(t)}].${n}`),i})):r):e,te=(e,s)=>Array.isArray(e)?e.filter((r,t)=>{const n=c(r)&&typeof r.type=="string"&&X.has(r.type);return n||s.push(`rules[${String(t)}]`),n}):e,ne=e=>{const s=[],r={};for(const[t,n]of Object.entries(c(e)?e:{}))c(n)&&n.type==="workflow"?s.push({binding:t,class_name:t,name:n.name}):r[t]=n;return{bindings:s,rest:r}},ie=(e,s)=>Array.isArray(e)?e.map(r=>!c(r)||r.database_id!==F?r:typeof r.database_name=="string"?{...r,database_id:r.database_name}:typeof r.binding=="string"?{...r,database_id:k(s,r.binding)}:r):e,oe=(e,s)=>Array.isArray(e)?e.map(r=>c(r)&&r.id===void 0&&typeof r.binding=="string"?{...r,id:k(s,r.binding)}:r):e,N=e=>{const s=[],r={},t=ne(e.exports),n={...e,exports:t.rest};for(const[i,o]of Object.entries(n)){if(!U.has(i)){I(o)||s.push(i);continue}switch(i){case"containers":{r[i]=se(o,s);break}case"d1_databases":{r[i]=ie(o,e.name);break}case"kv_namespaces":{r[i]=oe(o,e.name);break}case"migrations":{r[i]=re(o);break}case"rules":{r[i]=te(o,s);break}default:r[i]=o}}if(t.bindings.length>0){const i=Array.isArray(r.workflows)?r.workflows:[];r.workflows=[...i,...t.bindings]}return{config:r,dropped:s}},ae=e=>{const[s=[],...r]=e.map(n=>h(n).split(y));let t=0;for(;t<s.length&&r.every(n=>n[t]===s[t]);)t+=1;return s.slice(0,t).join(y)||y},P=(e,s,r)=>{const t=i=>_(r,h(s,i)).split(y).join("/"),n={...e};return typeof e.main=="string"&&(n.main=t(e.main)),c(e.assets)&&typeof e.assets.directory=="string"&&(n.assets={...e.assets,directory:t(e.assets.directory)}),n},ce=e=>{const s=v(e,".assetsignore");if(!w(s))return;const r=A(s,"utf8").split(z).map(t=>t.trim()).filter(t=>t!==""&&!t.startsWith("#")).filter(t=>Q.test(t)||w(v(e,t)));if(r.length>0)throw new Error(`${s} hides ${r.join(", ")} from the assets, and celld has no .assetsignore — remove those files from ${e} first`);return s},le=(e,s)=>{const r=v(e,M);if(!w(r))throw new x(`wrangler \`main\` is the Vite virtual module "${s}", so celld deploys the Vite build output — and there is none yet. Run the project's build (\`vite build\`) first`);const{configPath:t}=JSON.parse(A(r,"utf8"));if(typeof t!="string")throw new TypeError(`${r} names no configPath`);return h(E(r),t)},S=e=>{const{parsed:s}=Y(e);if(s===void 0)throw new Error(`${e} is not valid JSONC`);return s},T=(e,s,r,t)=>{const{d1_databases:n}=e;if(!Array.isArray(n)||t===r)return e;const i=Array.isArray(s.d1_databases)?s.d1_databases.filter(o=>c(o)):[];return{...e,d1_databases:n.map(o=>{if(!c(o))return o;const a=i.find(m=>m.binding===o.binding),l=a?.migrations_dir,p=h(r,typeof l=="string"?l:"migrations"),d=w(p)?{...o,migrations_dir:_(t,p).split(y).join("/")}:o,f=a?.migrations_pattern;return typeof f=="string"?{...d,migrations_pattern:_(t,h(r,f)).split(y).join("/")}:d})}},de=(e,s,r,t)=>{const{main:n}=r;if(typeof n!="string"||!n.startsWith("virtual:"))return{fromBuild:!1,source:r,sourcePath:s};if(t==="dev")throw new Error(`wrangler \`main\` is the Vite virtual module "${n}", which only a Vite build can resolve — \`celld dev\` rebuilds from a source file. Use \`vite dev\` for the dev loop and \`lunora deploy\` to ship the build to celld, or point \`main\` at a worker file`);const i=le(e,n);return{fromBuild:!0,source:S(i),sourcePath:i}},fe=(e,s,r,t,n)=>{const i=s.filter(l=>Object.hasOwn(r,l.split(Z)[0]??l));let o=e;e.no_bundle!==void 0&&(o=Object.fromEntries(Object.entries(e).filter(([l])=>l!=="no_bundle")),i.push("no_bundle (celld re-bundles the build output)"));const a=t===void 0?void 0:ce(t);return a!==void 0&&i.push(`${_(n,a)} (matched no files)`),{assetsIgnore:a,projected:o,reported:i}},R=(e,s={})=>{const r=c(e.vars)?e.vars:{};return{...e,vars:{...r,WORKER_ENV:"development",...s}}},_e=(e,s)=>{const r=K(e);if(r===void 0)throw new Error(`no wrangler.jsonc or wrangler.json in ${e} — celld deploys from the project's Wrangler config`);const t=S(r),{fromBuild:n,source:i,sourcePath:o}=de(e,r,t,s),a=E(o),{config:l,dropped:p}=N(i),{assets:d}=i,f=c(d)&&typeof d.directory=="string"?h(a,d.directory):void 0,m=typeof i.main=="string"?E(h(a,i.main)):void 0,u=ae([a,m,f].filter(L=>L!==void 0));if(!n&&u!==a)throw new Error(`wrangler \`main\` and \`assets.directory\` must sit inside ${a} — celld resolves everything against the config's directory`);const b=T(P(l,a,u),t,e,u),g=n?fe(b,p,t,f,u):{assetsIgnore:void 0,projected:b,reported:p},j=s==="dev"?R(g.projected):g.projected,O=v(u,q),V=`${JSON.stringify(j,void 0,4)}
2
2
  `;return{configPath:O,dropped:g.reported,vars:c(j.vars)?j.vars:{},write:()=>{if(!n)try{D(u,C)}catch{}$(O,V),g.assetsIgnore!==void 0&&W(g.assetsIgnore)}}},be=(e,s)=>{const r=S(s),t=E(s),{config:n,dropped:i}=N(r),o=typeof r.name=="string"?r.name:"service",a=_(e,t);if(a===".."||a.startsWith(`..${y}`)||B(a))throw new Error(`service ${o} (${t}) must sit inside ${e} — celld dev runs it from a config beside the app's`);const l=v(t,G),p=w(l)?Object.fromEntries(J(A(l,"utf8")).map(({key:b,value:g})=>[b,g])):{},d=T(P(n,t,e),r,t,e),f=v(e,`.celld.service.${o.replaceAll(/[^\w.-]/gu,"-")}.wrangler.json`),m=R(d,p),u=`${JSON.stringify(m,void 0,4)}
3
3
  `;return{configPath:f,dropped:i,vars:c(m.vars)?m.vars:{},write:()=>{D(e,C),$(f,u)}}};export{be as a,_e as p};
@@ -0,0 +1,3 @@
1
+ import{existsSync as b}from"node:fs";import{ENV_FILENAME as k}from"@lunora/codegen";import{ENV_FILENAME as fe}from"@lunora/codegen";import{i as w}from"./secret-key-xi4VK8Jw.mjs";import{buildBindingManifest as O}from"./BINDING_MANIFEST_VERSION-CR06-eW7.mjs";import{readProjectWrangler as N,readWranglerJsonc as S}from"./WRANGLER_FILES-BF8PUjuo.mjs";import{dirname as L,join as g}from"node:path";import{expand as $}from"dotenv-expand";import{readDevVariablesRecord as y,wranglerDotenvFiles as P}from"./DEV_VARS_EXAMPLE_FILE-hBT89IXh.mjs";const C=Symbol.for("lunora.env"),T=e=>{if(typeof e!="function")return;let t;try{t=Reflect.get(e,C)}catch{return}return typeof t=="function"?t:void 0},I=[/^sk_/u,/^pk_/u,/^rk_/u,/^ghp_/u,/^gho_/u,/^ghs_/u,/^ghr_/u,/^github_pat_/u,/^xox[baprs]-/u,/^AKIA/u,/^AIza/u,/^Bearer\s/u],V=/[\w./+-]{24,}/gu,j=/^[\w./+-]+$/u,x=/\b(?:(?:sk|pk|rk|ghp|gho|ghs|ghr)_[\w./+-]*|github_pat_[\w./+-]*|xox[baprs]-[\w./+-]*)/gu,F=/\b(?:AKIA|AIza)[\w./+-]+|Bearer\s+[\w./+-]+/gu,U=/:\/\/([\w.%+-]*):[\w.%+\-!$&'()*,;=~]+@/gu,u="[redacted]",K=e=>{if(I.some(n=>n.test(e)))return!0;const t=e.trim();return t.length>=24&&j.test(t)},p=new Set([`
2
+ `,"\r","\u2028","\u2029"]),M=(e,t)=>{const n=e.charAt(t);let r=-1,o=t+1;for(;o<e.length;){const s=e.charAt(o);if(s===n)return o;if(p.has(s))break;const c=e.charAt(o+1);s==="\\"&&o+1<e.length&&!p.has(c)?(c===n&&(r=o+1),o+=2):o+=1}return r},q=(e,t)=>{let n="",r=0;for(;r<e.length;){const o=e.charAt(r),s=o==='"'||o==="'"?M(e,r):-1;s===-1?(n+=o,r+=1):(n+=t(e.slice(r,s+1),e.slice(r+1,s)),r=s+1)}return n},B=/\b(?<key>[A-Za-z_]\w*)\s*[=:]\s*(?:"(?:[^"\\\n]|\\[^\n])*"|'(?:[^'\\\n]|\\[^\n])*'|\S+)/gu,h=e=>{let t=e;return t=q(t,(n,r)=>K(r)?u:n),t=t.replaceAll(U,(n,r)=>`://${r}:${u}@`),t=t.replaceAll(x,u),t=t.replaceAll(F,u),t=t.replaceAll(B,(n,...r)=>{const o=r.at(-1);return o?.key!==void 0&&w(o.key)?`${o.key}=${u}`:n}),t=t.replaceAll(V,u),t},m=(e,t,n)=>{const r=e[t];if(r===void 0)return n;switch(r.toLowerCase()){case"false":return!1;case"true":return!0;default:throw new Error(`Expected ${t} to be "true" or "false", but got ${JSON.stringify(r)}`)}},D=(e,t)=>(t===void 0?void 0:e?.env?.[t])??e??{},H=(e,t)=>{const n=t===void 0?[".dev.vars"]:[`.dev.vars.${t}`,".dev.vars"];for(const r of n){const o=y(g(e,r));if(o!==void 0)return{file:r,values:o}}},W=(e,t,n,r)=>{const o={},s=[];for(const a of P(t)){let i;try{i=y(g(e,a))}catch{continue}i!==void 0&&(Object.assign(o,i),s.push(a))}const c={};if(n)for(const[a,i]of Object.entries(r))i!==void 0&&(c[a]=i);return $({parsed:o,processEnv:c}),{files:s,values:c}},J=e=>{const t=e.processEnv??process.env,n=e.configPath===void 0?e.projectRoot:L(e.configPath),r=D(e.config,e.environment),o={...r.vars},s=e.config===void 0?[]:["wrangler vars"],c=r.secrets??void 0;let a;const i=H(n,e.environment);if(i!==void 0)a=i.values,s.push(i.file);else if(m(t,"CLOUDFLARE_LOAD_DEV_VARS_FROM_DOT_ENV",!0)){const d=c!==void 0||m(t,"CLOUDFLARE_INCLUDE_PROCESS_ENV",!1),v=W(n,e.environment,d,t);a=v.values,s.push(...v.files,...d?["process.env"]:[])}const f=new Set(Array.isArray(c?.required)?c.required.filter(d=>typeof d=="string"):[]);for(const[d,v]of Object.entries(a??{}))(c===void 0||d in o||f.has(d))&&(o[d]=v);return{env:{...o,...e.vars},sources:s}},z=e=>{if(e.configPath===void 0)return N(e.projectRoot);if(b(e.configPath))try{return{parsed:S(e.configPath).parsed,path:e.configPath}}catch{return{parsed:void 0,path:e.configPath}}},G=async e=>{const{createJiti:t}=await import("jiti");return t(e,{interopDefault:!1,moduleCache:!1}).import(e)},_=3,A=/[\w-]/u,Q=(e,t,n)=>{let r="",o=0,s=e.indexOf(t);for(;s!==-1;){const c=e.charAt(s-1),a=e.charAt(s+t.length),i=!A.test(c)&&!A.test(a);r+=e.slice(o,s)+(i?n:t),o=s+t.length,s=e.indexOf(t,o)}return r+e.slice(o)},X=(e,t)=>{const n=t[e.key];if(typeof n!="string")return{...e,message:h(e.message)};const r=[];if(URL.canParse(n)){const{password:a}=new URL(n);r.push(a);try{r.push(decodeURIComponent(a))}catch{}}let o=n;for(const a of r)o=o.replace(`:${a}@`,`:${u}@`);const s=w(e.key)||h(n)!==n;let{message:c}=e;o!==n?c=c.replaceAll(n,o):n.length>=_&&(c=s?c.replaceAll(n,u):Q(c,n,u));for(const a of r.filter(i=>i.length>=_).toSorted((i,f)=>f.length-i.length))c=c.replaceAll(a,u);return{...e,message:h(c)}},Y=e=>e instanceof Error?e.message:String(e),Z=async e=>{const t=g(e.projectRoot,e.schemaDirectory,k);if(!b(t))return{kind:"absent"};const n=await(e.load??G)(t),r=Object.values(n??{}).map(l=>T(l)).find(l=>l!==void 0);if(r===void 0)return{kind:"absent"};const o=e.processEnv??process.env,s=o.CLOUDFLARE_ENV,c=e.environment??(s===""?void 0:s),a=z(e);if(e.configPath!==void 0&&a===void 0)return{error:`${e.configPath} does not exist`,kind:"unloadable"};if(a!==void 0&&a.parsed===void 0)return{error:`${a.path} could not be read as JSONC`,kind:"unloadable"};const i=J({config:a?.parsed,configPath:a?.path,environment:c,processEnv:o,projectRoot:e.projectRoot,vars:e.vars}),{env:f}=i,d=D(a?.parsed,c),v=new Set(e.withheld),R=new Set(a===void 0?[]:O(d).bindings.filter(l=>l.type!=="queue_consumer").map(l=>l.binding).filter(l=>!v.has(l))),E=r(f).filter(l=>!R.has(l.key)).map(l=>X(l,f));return E.length===0?{kind:"valid"}:{failures:E,kind:"invalid",sources:i.sources}},ie=async e=>{try{return await Z(e)}catch(t){return{error:h(Y(t)),kind:"unloadable"}}},le=(e,t,{wasInvalid:n=!1}={})=>{const r=`${t}/${k}`;if(e.kind==="unloadable")return{level:"info",message:`${r}: the dev env could not be checked, so a missing key surfaces on first read instead: ${e.error}`};if(e.kind==="valid"&&n)return{level:"info",message:`${r}: the dev env satisfies the contract again`};if(e.kind==="absent"&&n)return{level:"info",message:`${r}: no env contract is loaded any more, so the warning above no longer applies`};if(e.kind!=="invalid")return;const o=e.sources.length===0?"no env files":e.sources.join(" + "),s=e.failures.map(c=>` - ${c.key}: ${c.message}`);return{level:"warn",message:[`${r}: ${String(e.failures.length)} key(s) missing or invalid in the dev env (${o}) — the first request that reads one will fail:`,...s].join(`
3
+ `)}};export{fe as ENV_FILENAME,ie as checkDevEnv,le as describeDevEnvCheck};
@@ -1,2 +1,2 @@
1
- import{readFileSync as ee,writeFileSync as ne}from"node:fs";import{createRequire as se}from"node:module";import{join as Q}from"node:path";import{containerBuildTag as te}from"@lunora/container";import{readJsonSync as ie}from"@visulima/fs";import{c as oe}from"./celld-binding-id-9MiUoteo.mjs";import{applyModify as _}from"./applyModify-DKP2l6S9.mjs";import{recordManifestKey as re,readManifest as Y}from"./readManifest-Cighz3WC.mjs";import{D1_PLACEHOLDER_ID as U,HYPERDRIVE_PLACEHOLDER_ID as ae}from"./D1_PLACEHOLDER_ID-ZnDjVymH.mjs";import{m as de,w as ce,n as le,s as G,o as D,p as T,q as ue}from"./reconcile-assets-h8q3F4Sy.mjs";import{parseTree as ge,findNodeAtLocation as me}from"jsonc-parser";import{r as pe,a as fe,b as be,c as he}from"./reconcile-services-C4TwY8YH.mjs";import{DEV_VARS_FILE as ve,parseDevVariableEntries as we}from"./DEV_VARS_EXAMPLE_FILE-CqLorAxT.mjs";import{secretSourcesFromBindings as _e}from"./inferLunoraBindings-D0QDcugr.mjs";import{requiredSecrets as ye}from"./buildPackageSecretsBlock-B4Odg5OF.mjs";import{b as Se}from"./spa-assets-BwJFTBeO.mjs";import{s as Ee}from"./worker-entry-checks-CHrum2AN.mjs";import{DEFAULT_OBSERVABILITY as xe}from"./DEFAULT_OBSERVABILITY-CPLADr5u.mjs";import{findWranglerFile as Ae,readWranglerJsonc as Oe}from"./WRANGLER_FILES-UNW-xY5u.mjs";const $e=[["maxBatchSize","max_batch_size"],["maxBatchTimeout","max_batch_timeout"],["maxConcurrency","max_concurrency"],["maxRetries","max_retries"],["deadLetterQueue","dead_letter_queue"],["retryDelay","retry_delay"]],P=e=>Object.fromEntries($e.filter(([n])=>e.tuning[n]!==void 0).map(([n,s])=>[s,e.tuning[n]])),B="queueTuning",Ne=/^[\t ]*(?:,[\t ]*)?(?:\/\/[^\n\r]*)?\r?\n/u,ke=/^[\t ]*,/u,Ce=(e,n)=>{const s=ge(e),t=s===void 0?void 0:me(s,[...n])?.parent;if(t?.type==="property"){const o=t.offset+t.length,i=e.lastIndexOf(`
2
- `,t.offset-1)+1,r=Ne.exec(e.slice(o));if(r!==null&&e.slice(i,t.offset).trim()===""){const m=t.parent?.children??[],u=m.indexOf(t),d=u===m.length-1&&u>0?m[u-1]:void 0,c=d===void 0?void 0:ke.exec(e.slice(d.offset+d.length))??void 0;return(c===void 0||d===void 0?e.slice(0,i):e.slice(0,d.offset+d.length)+e.slice(d.offset+d.length+c[0].length,i))+e.slice(o+r[0].length)}}return _(e,n,void 0)},J=(e,n,s,t,o,i=new Set)=>{const r=s.join("."),m={},u=[],d=[];let c=e;return{entries:n.map((l,v)=>{const g=t(l);if(g===void 0||l.queue===void 0)return l;const b=Object.fromEntries(Object.entries(P(g)).filter(([f])=>!i.has(f))),h=Object.entries(o[l.queue]??{}).filter(([f])=>!Object.hasOwn(b,f)),y=Object.entries(b).filter(([f,S])=>l[f]!==S),E=h.filter(([f,S])=>l[f]===S).map(([f])=>f),O=Object.fromEntries(Object.entries({...l,...b}).filter(([f])=>!E.includes(f)));for(const[f,S]of y)c=_(c,[...s,v,f],S);for(const f of E)c=Ce(c,[...s,v,f]);for(const[f,S]of h){const A=l[f];A!==void 0&&A!==S&&d.push(`${r}/${l.queue}: ${f} is no longer declared by defineQueue, but it was changed by hand to ${JSON.stringify(A)} from the declared ${JSON.stringify(S)}, so it was kept. Delete it from wrangler.jsonc if it should go.`)}return(y.length>0||E.length>0)&&u.push(`${r}/${l.queue} (${[...y.map(([f])=>f),...E.map(f=>`removed ${f}`)].join(", ")})`),Object.keys(b).length>0&&(m[l.queue]=b),O}),owned:m,text:c,updated:u,warnings:d}},Te=(e,n,s,t)=>{const o=n.queues??{},i=o.producers??[],r=o.consumers??[],m=new Set(i.map(g=>g?.binding)),u=new Set(r.map(g=>g.queue)),d=s.filter(g=>!m.has(g.bindingName)),c=s.filter(g=>!u.has(g.name)),p=J(e,r,["queues","consumers"],g=>s.find(b=>b.name===g.queue),t);let l=p.text;const v={...p.owned};if(d.length>0||c.length>0){const g=[...i,...d.map(h=>({binding:h.bindingName,queue:h.name}))],b=[...p.entries,...c.map(h=>({queue:h.name,...h.mode==="pull"?{type:"http_pull"}:{},...P(h)}))];for(const h of c){const y=P(h);Object.keys(y).length>0&&(v[h.name]=y)}l=_(l,["queues"],{consumers:b,producers:g})}return{added:[...d.map(g=>`queues.producers/${g.bindingName}`),...c.map(g=>`queues.consumers/${g.name}`)],owned:v,text:l,updated:p.updated,warnings:p.warnings}},Ie=(e,n,s,t,o)=>{const i=n.env?.[t],r=i?.queues?.consumers??[],m=i?.queues?.producers??[],u=l=>{const v=m.find(g=>g?.queue===l.queue)?.binding;return v!==void 0?s.find(g=>g.bindingName===v):s.find(g=>g.name===l.queue&&!m.some(b=>b?.binding===g.bindingName))},d=J(e,r,["env",t,"queues","consumers"],u,o,new Set(["dead_letter_queue"])),c=r.filter(l=>l.queue!==void 0&&u(l)===void 0).map(l=>`env.${t}.queues.consumers/${String(l.queue)}: no defineQueue export matches it — this block declares no producer mapping one of their bindings to "${String(l.queue)}", and no export is named that — so it was not retuned. A consumer for a queue another worker produces is skipped the same way.`),p=r.flatMap(l=>{const v=u(l)?.tuning.deadLetterQueue;return v===void 0||l.dead_letter_queue!==void 0?[]:[`env.${t}.queues.consumers/${String(l.queue)}: defineQueue declares deadLetterQueue "${v}", but this consumer has no dead_letter_queue, so its exhausted messages are dropped. Queue names differ per environment, so reconcile does not write it here; add it by hand.`]});return{added:[],owned:d.owned,text:d.text,updated:d.updated,warnings:[...d.warnings,...p,...c]}},Re=(e,n)=>{if(e?.lunoraIsForeign===!0)return n.push(`${e.path}: \`lunora\` is not an object, so the queue tuning ownership record cannot be read or written — an option removed from defineQueue stays deployed.`),{};const s=e?.lunora?.[B],t=o=>typeof o=="object"&&o!==null&&!Array.isArray(o);return s===void 0?{}:!t(s)||!Object.values(s).every(o=>t(o)&&Object.values(o).every(i=>t(i)))?(n.push(`${e?.path??"package.json"}: \`lunora.${B}\` is not a map of scope → queue → fields, so it is ignored — an option removed from defineQueue stays deployed until the next pass records it again.`),{}):s},je=(e,n,s)=>{const t=Object.fromEntries(Object.entries({...n,...s}).filter(([,o])=>Object.keys(o).length>0));re(e,B,Object.keys(t).length===0?void 0:t)},qe="https://api.cloudflare.com/client/v4/accounts/<ACCOUNT_ID>/artifacts/namespaces",De=e=>{const n='add an "artifacts" binding ({ binding: "ARTIFACTS", namespace }) — codegen reads env.ARTIFACTS unless `.artifacts()` on defineApp points ctx.artifacts at another binding';return e===void 0?`ctx.artifacts is used; ${n}. The namespace is created by the first repo create() if it does not exist yet.`:`ctx.artifacts is used and the schema pins data to "${e}"; create the namespace in that jurisdiction BEFORE the first repo, with POST ${qe} and body { "namespace": "<name>", "jurisdiction": "${e}" }, then ${n}. A namespace's jurisdiction cannot be changed, and one created implicitly by the first repo create() is unrestricted. With CLOUDFLARE_API_TOKEN set, \`lunora deploy\` creates a missing namespace in that jurisdiction for a binding you have added.`},I="PIPELINES",R="ARTIFACTS",Pe=(e,n,s)=>{const t=n!==void 0&&(s===void 0||s==="cloudflare"),o=e.flagshipBinding!==void 0&&!(n?.flagship??[]).some(d=>d.binding===e.flagshipBinding),i=e.usesPipelines&&!(n?.pipelines??[]).some(d=>d.binding===I),r=e.usesArtifacts?n?.artifacts??[]:[],m=r.some(d=>d.binding===R)?[]:r.flatMap(d=>d.binding===void 0?[]:[d.binding]);return[[e.usesKv&&(n?.kv_namespaces?.length??0)===0&&(!t||e.jurisdiction!==void 0),e.jurisdiction===void 0?'ctx.kv is used but no kv_namespaces binding exists; add one ({ binding: "KV" }) — wrangler creates the namespace on the first deploy.':`ctx.kv is used and the schema pins data to "${e.jurisdiction}"; run \`wrangler kv namespace create <name> --jurisdiction ${e.jurisdiction}\` and add a kv_namespaces entry ({ binding: "KV", id }) — a namespace wrangler creates on deploy is unrestricted.`],[e.usesHyperdrive&&(n?.hyperdrive?.length??0)===0&&!t,'@lunora/hyperdrive is used but no hyperdrive binding exists; add one ({ binding: "HYPERDRIVE", id }) — on a Cloudflare target `lunora deploy` creates the Hyperdrive config from a connection string.'],[e.usesArtifacts&&r.length===0&&(!t||e.jurisdiction!==void 0),De(e.jurisdiction)],[i,`ctx.pipelines is used but no "${I}" pipelines binding exists; run 'wrangler pipelines create <name>' and add a 'pipelines' binding ({ binding: "${I}", stream }) — codegen resolves this one name, and the pipeline resource can't be auto-provisioned.`],[m.length>0,`ctx.artifacts is used and ${m.map(d=>`"${d}"`).join(", ")} ${m.length===1?"is":"are"} bound, but none is named "${R}"; make sure \`.artifacts()\` on defineApp points ctx.artifacts at it — otherwise it reads env.${R} and throws.`],[o,`lunora/flags.ts uses Flagship in binding mode but no flagship binding "${e.flagshipBinding??""}" exists; add a flagship entry ({ binding: "${e.flagshipBinding??""}", app_id }) — the app_id can't be auto-provisioned.`]].filter(([d])=>d).map(([,d])=>d)},Be=e=>[[e.usesX402Charge,"@lunora/x402/charge is used; set the recipient wallet address as a [vars] entry (the var name is your choice) and pass it to the charge config — the x402 facilitator settles USDC to that address."],[e.usesX402,"@lunora/x402/pay is used (ActionCtx-only, spends real funds); add a secrets_store_secrets[] binding holding the agent wallet key (binding name == signer.secretName) and pair the pay rail with a spend policy — ctx.secrets reads a Secrets Store binding, not .dev.vars."]].filter(([s])=>s).map(([,s])=>s),j=(e,n,s)=>s.filter(t=>!t.exported).map(t=>`${e} "${t.exportName}" is declared but ${t.className} is not exported by the worker entry; add \`export * from "./lunora/_generated/${n}"\` so its binding can be provisioned.`),Le=(e,n)=>{const s=new Set([...e.workflows,...e.agents].map(i=>i.className));if(s.size===0)return[];const t=Object.entries(n.exports??{}).flatMap(([i,r])=>r?.type==="workflow"?[i]:[]),o=(n.workflows??[]).flatMap(i=>i.class_name===void 0||i.script_name!==void 0?[]:[i.class_name]);return[...new Set([...t,...o])].filter(i=>!s.has(i)).map(i=>`wrangler.jsonc declares workflow "${i}" but no defineWorkflow/defineAgent export generates that class — a leftover from a rename will fail the deploy (wrangler rejects a class the worker does not export). Remove it if it is not hand-wired.`)},We=(e,n)=>{if(e.queues.length===0)return[];const s=new Set(e.queues.map(o=>o.name)),t=new Set(e.queues.map(o=>o.bindingName));return[...(n.queues?.consumers??[]).flatMap(o=>{const{queue:i}=o;return i===void 0||s.has(i)?[]:[`wrangler.jsonc subscribes queues.consumers[] to "${i}" but no defineQueue export declares that queue — a leftover from a rename keeps delivering batches this worker has no handler for (they retry to exhaustion, then drop or dead-letter). Remove it if it is not hand-wired.`]}),...(n.queues?.producers??[]).flatMap(o=>{const i=o?.binding;return i===void 0||t.has(i)?[]:[`wrangler.jsonc declares queues.producers[] binding "${i}" but no defineQueue export declares it — a leftover from a rename. Remove it if it is not hand-wired.`]})]},Me=(e,n)=>[...Le(e,n),...We(e,n)],X=[{keys:["STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET"],label:"Stripe"},{keys:["POLAR_ACCESS_TOKEN","POLAR_WEBHOOK_SECRET"],label:"Polar"},{keys:["CREEM_API_KEY","CREEM_WEBHOOK_SECRET"],label:"Creem"},{keys:["AUTUMN_SECRET_KEY","AUTUMN_WEBHOOK_SECRET"],label:"Autumn"},{keys:["DODO_PAYMENTS_API_KEY","DODO_PAYMENTS_WEBHOOK_KEY"],label:"Dodo Payments"}],Ke=()=>X.map(({keys:e,label:n})=>`${e[0]} + ${e[1]} (${n})`).join(" or "),Fe=e=>{let n;try{n=ee(Q(e,ve),"utf8")}catch{return!1}const s=new Map(we(n).map(t=>[t.key,t.value]));return X.some(({keys:t})=>t.every(o=>(s.get(o)??"")!==""))},He=(e,n)=>{const s=n?.secrets?.required;if(!Array.isArray(s))return[];const t=new Set(s),o=ye(_e(e)).map(i=>i.key).filter(i=>!t.has(i));return o.length===0?[]:[`wrangler.jsonc declares secrets.required without ${o.join(", ")}, which this app needs — wrangler dev loads only the listed keys from .dev.vars, so add ${o.length===1?"it":"them"} to secrets.required.`]},q=(e,n,s,t)=>{const o=new Set(e.durableObjects.map(u=>u.className)),i=[],r=(s?.r2_buckets?.length??0)>0,m=(s?.d1_databases?.some(u=>u.binding==="DB")??!1)||e.needsD1;return e.usesStorage&&!r&&i.push("@lunora/storage is used but R2 bucket bindings have user-defined names; add an r2_buckets entry and pass env.<BINDING> to createStorage()."),e.usesAuth&&!o.has("SessionDO")&&!m&&i.push("@lunora/auth is used but the worker entry exports no SessionDO; sessions are D1-backed, or export SessionDO to enable DO-backed sessions."),e.usesScheduler&&!o.has("SchedulerDO")&&i.push("@lunora/scheduler is used but the worker entry exports no SchedulerDO; export it so the SCHEDULER binding can be provisioned."),i.push(...j("container","containers",e.containers),...j("workflow","workflows",e.workflows),...j("agent","agents",e.agents)),e.containers.length>0&&s?.observability?.enabled===!1&&i.push("containers are declared but observability is explicitly disabled in wrangler.jsonc — container logs will not be captured."),e.usesPayments&&!Fe(n)&&i.push(`@lunora/payment is used; set one provider's secret pair in .dev.vars — ${Ke()}.`),i.push(...Be(e),...Pe(e,s,t),...He(e,s)),s!==void 0&&i.push(...Me(e,s)),i},Ye=e=>[["container","containers",e.containers],["workflow","workflows",e.workflows],["agent","agents",e.agents]].flatMap(([s,t,o])=>o.filter(i=>!i.exported).map(({className:i,exportName:r})=>({className:i,exportName:r,kind:s,module:t}))),Ve=e=>{const n=new Set(D(e).map(t=>t.tag));let s=1;for(;n.has(`v${String(s)}`);)s+=1;return`v${String(s)}`},Qe=e=>{const n=new Set;for(const s of D(e)){for(const t of T(s.deleted_classes))n.delete(t);for(const{from:t,to:o}of D(s.renamed_classes))t!==void 0&&n.delete(t),o!==void 0&&n.add(o);for(const t of[...T(s.new_classes),...T(s.new_sqlite_classes)])n.add(t)}return n},Ue=(e,n,s)=>{const t=n.durable_objects?.bindings??[],o=new Set(t.map(c=>c.name)),i=s.filter(c=>!o.has(c.binding));let r=e;const m=[];if(i.length>0){const c=[...t,...i.map(p=>({class_name:p.className,name:p.binding}))];r=_(r,["durable_objects","bindings"],c),m.push(...i.map(p=>`${p.binding}/${p.className}`))}const u=n.migrations??[],d=s.map(c=>c.className).filter(c=>!Qe(u).has(c));if(d.length>0){const c=[...u,{new_sqlite_classes:d,tag:Ve(u)}];r=_(r,["migrations"],c)}return{added:m,text:r}},W=e=>e===void 0||e==="cloudflare",Ge=(e,n)=>e.includes("DB (D1)")&&W(n)?[`wrote a DB binding with a placeholder database_id ("${U}") — run \`wrangler d1 create <name>\` and replace it before deploying.`]:[],Je=(e,n)=>{const s=n.d1_databases??[];if(s.some(i=>i.binding==="DB"))return{added:[],text:e};const t=typeof n.name=="string"&&n.name.length>0?n.name:"lunora",o=[...s,{binding:"DB",database_id:U,database_name:t}];return{added:["DB (D1)"],text:_(e,["d1_databases"],o)}},Xe={ai:{binding:"AI",label:"AI (Workers AI)"},analytics:{binding:"ANALYTICS_SQL",label:"ANALYTICS_SQL (Analytics SQL)"},browser:{binding:"BROWSER",label:"BROWSER (Browser Rendering)"},images:{binding:"IMAGES",label:"IMAGES (Cloudflare Images)"}},ze=(e,n)=>e.usesAnalyticsSql&&Ee(n,new Set(["analyticsSql"]))?.chained.has("analyticsSql")!==!0,Ze=new Set(["ratelimits","send_email"]),en=["durable_objects","logfwdr","unsafe"],nn=new Set(["data_blobs","text_blobs","vars","wasm_modules"]),M=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),L=(e,n,s)=>M(e)&&e[n]===s,sn=(e,n,s)=>{if(nn.has(e))return M(n)&&Object.hasOwn(n,s);const t=Ze.has(e)?"name":"binding";return Array.isArray(n)?n.some(o=>L(o,t,s)):L(n,"binding",s)},$=(e,n)=>{const s=e,t=Object.entries(s).find(([i,r])=>i!=="env"&&sn(i,r,n));if(t!==void 0)return t[0];for(const i of en){const r=s[i];if(M(r)&&Array.isArray(r.bindings)&&r.bindings.some(m=>L(m,"name",n)))return`${i}.bindings`}if(e.queues?.producers?.some(i=>i?.binding===n)===!0)return"queues.producers";const o=e.secrets?.required;if(Array.isArray(o)&&o.includes(n))return"secrets.required"},N=(e,n,s)=>{const{binding:t,label:o}=Xe[s],i=n[s]?.binding;if(typeof i=="string"&&i.length>0)return{added:[],text:e};const r=$(n,t);return r!==void 0?{added:[],text:e,warnings:[`${s}: not adding the ${o} binding — the name "${t}" is already bound by \`${r}\` in wrangler.jsonc. Rename that binding, then set ${s}.binding by hand.`]}:{added:[o],text:_(e,[s],{binding:t})}},K=(e,n,s)=>`${e}: not adding "${n}" — the name is already bound by \`${s}\` in wrangler.jsonc. Add a ${e} entry under another binding name and point the matching \`defineApp()\` override at it.`,tn=(e,n,s)=>{if(!W(s)||(n.hyperdrive?.length??0)>0)return{added:[],text:e};const t=$(n,"HYPERDRIVE");return t!==void 0?{added:[],text:e,warnings:[K("hyperdrive","HYPERDRIVE",t)]}:{added:["HYPERDRIVE (Hyperdrive, created on deploy)"],text:_(e,["hyperdrive"],[{binding:"HYPERDRIVE",id:ae}])}},on=new Set(["celld","cloudflare"]),rn=(e,n,s,t)=>{if(t!==void 0&&!on.has(t)||s!==void 0||(n.kv_namespaces?.length??0)>0)return{added:[],text:e};const o=$(n,"KV");return o!==void 0?{added:[],text:e,warnings:[K("kv_namespaces","KV",o)]}:{added:[t==="celld"?`KV (Workers KV, celld namespace ${oe(n.name,"KV")})`:"KV (Workers KV, created on deploy)"],text:_(e,["kv_namespaces"],[{binding:"KV"}])}},an=(e,n,s,t)=>{if(!W(t)||s!==void 0||(n.artifacts?.length??0)>0)return{added:[],text:e};const o=$(n,"ARTIFACTS");if(o!==void 0)return{added:[],text:e,warnings:[K("artifacts","ARTIFACTS",o)]};const i=typeof n.name=="string"&&n.name.length>0?n.name:"lunora";return{added:["ARTIFACTS (Cloudflare Artifacts)"],text:_(e,["artifacts"],[{binding:"ARTIFACTS",namespace:i}])}},V=(e,n,s,t,o)=>{if((n[s]?.length??0)>0)return{added:[],text:e};const i=$(n,t.binding);return i!==void 0?{added:[],text:e,warnings:[`${s}: not adding ${JSON.stringify(t)} — the name "${t.binding}" is already bound by \`${i}\` in wrangler.jsonc. Add a ${s} entry under another binding name and point the matching \`defineApp()\` override at it.`]}:{added:[o],text:_(e,[s],[t])}},dn=(e,n)=>{const s=n.worker_loaders??[];return s.some(t=>t.binding==="LOADER")?{added:[],text:e}:{added:["LOADER (Worker Loader)"],text:_(e,["worker_loaders"],[...s,{binding:"LOADER"}])}},cn=e=>{if(typeof e=="string")return e;const n={};return e.diskMb!==void 0&&(n.disk_mb=e.diskMb),e.memoryMib!==void 0&&(n.memory_mib=e.memoryMib),e.vcpu!==void 0&&(n.vcpu=e.vcpu),n},ln=e=>{const{image:n}=e;return n.kind==="dockerfile"?n.dockerfilePath:n.kind==="registry"?n.reference:te(e.exportName)},z=e=>{const n={};for(const[s,t]of Object.entries(e.images??{}))n[s]=t.kind==="registry"?{image:t.reference}:{build_context:t.buildContext,dockerfile:t.dockerfilePath,...e.buildArgs===void 0?{}:{build_vars:e.buildArgs}};return{class_name:e.className,scheduling_policy:"durable_object",...Object.keys(n).length>0?{images:n}:{},...e.name===void 0?{}:{name:e.name}}},un=e=>{if(e.schedulingPolicy==="durable_object")return z(e);const{image:n}=e,s={class_name:e.className,image:ln(e)};return n.kind==="dockerfile"&&(s.image_build_context=n.buildContext),e.buildArgs!==void 0&&n.kind!=="registry"&&(s.image_vars=e.buildArgs),e.instanceType!==void 0&&(s.instance_type=cn(e.instanceType)),e.maxInstances!==void 0&&(s.max_instances=e.maxInstances),e.name!==void 0&&(s.name=e.name),e.rollout?.stepPercentage!==void 0&&(s.rollout_step_percentage=e.rollout.stepPercentage),e.rollout?.gracePeriodSeconds!==void 0&&(s.rollout_active_grace_period=e.rollout.gracePeriodSeconds),s},gn=(e,n,s)=>{const t=n.containers??[],o=new Set(t.map(d=>d.class_name)),i=s.filter(d=>!o.has(d.className));let r=i.length===0?e:_(e,["containers"],[...t,...i.map(d=>un(d))]);const m=[],u=[];for(const[d,c]of t.entries()){const p=s.find(g=>g.className===c.class_name);if(p===void 0)continue;const l=p.schedulingPolicy??"default";if((c.scheduling_policy??"default")!==l){u.push(`containers/${p.className} has scheduling_policy "${c.scheduling_policy??"default"}" in wrangler.jsonc but defineContainer "${p.exportName}" declares "${l}" — the policy is immutable, so replace the entry (and its container application) by hand.`);continue}const v=p.schedulingPolicy==="durable_object"?z(p).images:void 0;v!==void 0&&JSON.stringify(c.images)!==JSON.stringify(v)&&(r=_(r,["containers",d,"images"],v),m.push(`containers/${p.className}.images`))}return{added:i.map(d=>`containers/${d.className}`),text:r,updated:m,warnings:u}},mn=(e,n)=>{if(n.observability!==void 0)return{added:[],text:e};const s=_(e,["observability"],{...xe});return{added:["observability"],text:s}},pn=(e,n)=>n.upload_source_maps!==void 0?{added:[],text:e}:{added:["upload_source_maps"],text:_(e,["upload_source_maps"],!0)},Z=[{minimum:[4,142],name:"wrangler"},{minimum:[1,61],name:"@cloudflare/vite-plugin"}],fn=Z.map(({minimum:e,name:n})=>`${n}@^${e.join(".")}.0`).join(" "),bn=(e,n)=>{try{const s=se(Q(e,"package.json")).resolve(`${n}/package.json`),[t=0,o=0]=String(ie(s).version).split(".").map(Number);return[t,o]}catch{return}},hn=e=>{const n=Z.flatMap(({minimum:s,name:t})=>{const o=bn(e,t);return o!==void 0&&(o[0]<s[0]||o[0]===s[0]&&o[1]<s[1])?[`${t} ${o.join(".")} (needs >= ${s.join(".")})`]:[]});return n.length===0?void 0:`workflows are declared in wrangler \`exports\`, which ${n.join(" and ")} cannot run — reconcile left workflows[] untouched. Upgrade (\`pnpm add -D ${fn}\`) and re-run.`},vn=e=>Object.entries(e.env??{}).flatMap(([n,s])=>Array.isArray(s?.workflows)?[`env.${n}.workflows declares workflow bindings, but Lunora now declares workflows in \`exports\` and resolves them on ctx.exports — move them to that environment's own \`exports\` by hand.`]:[]),wn=(e,n,s)=>{let t=e;const o=[],i=[];for(const r of s){const m=n[r.className];if(m?.type==="workflow")for(const{of:u,path:d}of ue){const c=u(r),p=G(m,d),l=`exports/${r.className}.${d.join(".")}`;if(c===void 0){p!==void 0&&i.push(`${l} is set in wrangler.jsonc but defineWorkflow "${r.exportName}" does not declare it — reconcile leaves it in place. Remove it by hand if it was dropped from the definition.`);continue}JSON.stringify(p)!==JSON.stringify(c)&&(t=_(t,["exports",r.className,...d],c),o.push(l))}}return{text:t,updated:o,warnings:i}},_n=(e,n,s,t,o)=>{if(o!==void 0)return{added:[],text:e,warnings:[o]};const i=[...s.map(b=>({settings:ce(b),workflow:b})),...t.map(b=>({settings:{},workflow:b}))],r=new Set(i.map(({workflow:b})=>b.className)),m=n.workflows??[],u=m.filter(b=>b.script_name===void 0&&b.class_name!==void 0&&r.has(b.class_name)),d=n.exports??{},c=[],p=[],l=[];let v=e;for(const{settings:b,workflow:h}of i){if(d[h.className]!==void 0&&d[h.className]!==null)continue;const y=u.find(f=>f.class_name===h.className),E=Object.fromEntries(le.flatMap(f=>{const S=G(y,[f]);return S===void 0?[]:[[f,S]]})),O=y?.name??h.name;y?.name!==void 0&&y.name!==h.name&&l.push(`workflows/${h.className} is deployed as "${y.name}" but declared as "${h.name}" — its export keeps "${y.name}" so running instances survive. Change the declaration to match, or rename deliberately (it starts a new, empty workflow).`),v=_(v,["exports",h.className],{type:"workflow",...E,...b,name:O}),(y===void 0?c:p).push(`exports/${h.className}`)}if(u.length>0){const b=m.filter(h=>!u.includes(h));v=_(v,["workflows"],b.length===0?void 0:b),p.push(...u.map(h=>`workflows/${String(h.class_name)} → exports`))}l.push(...vn(n));const g=wn(v,d,s);return{added:c,text:g.text,updated:[...p,...g.updated],warnings:[...l,...g.warnings]}},Wn=(e,n,{environment:s,target:t}={})=>{const o=Ae(e),i=Ye(n);if(!o)return{added:[],changed:!1,exportGaps:i,reason:"wrangler.jsonc not found",updated:[],warnings:q(n,e)};const{parsed:r,text:m}=Oe(o);if(r===void 0)return{added:[],changed:!1,exportGaps:i,reason:`failed to parse ${o} as JSONC`,updated:[],warnings:q(n,e),wranglerPath:o};const u=q(n,e,r,t);if(s!==void 0){const a=r.env?.[s]!==void 0;u.push(a?`auto-provisioned bindings are written to the top level of wrangler.jsonc only (queue consumers "env.${s}" already declares are retuned, nothing is added) — "env.${s}" has its own (non-inheritable) bindings and must be reconciled by hand; \`lunora deploy --env ${s}\` now validates them, so a gap here will be reported at deploy time.`:`--env "${s}" was requested but wrangler.jsonc declares no "env.${s}" block — auto-provisioned bindings are written to the top level only and will not apply to that environment.`)}const d=n.containers.filter(a=>a.exported),c=n.agents.filter(a=>a.exported&&a.voice===!0&&a.voiceBindingName!==void 0&&a.voiceClassName!==void 0),p=[...n.durableObjects,...d.map(a=>({binding:a.bindingName,className:a.className})),...c.map(a=>({binding:a.voiceBindingName,className:a.voiceClassName}))],l=n.workflows.filter(a=>a.exported),v=n.agents.filter(a=>a.exported),g=Y(e),b=Re(g,u),h={},y=pe(g);let E;const O=[{enabled:!0,run:a=>Ue(a,r,p)},{enabled:n.needsD1,run:a=>Je(a,r)},{enabled:n.usesKv,run:a=>rn(a,r,n.jurisdiction,t)},{enabled:n.usesHyperdrive,run:a=>tn(a,r,t)},{enabled:n.usesArtifacts,run:a=>an(a,r,n.jurisdiction,t)},{enabled:n.usesAi,run:a=>N(a,r,"ai")},{enabled:n.usesAiSearch,run:a=>V(a,r,"ai_search_namespaces",{binding:"AI_SEARCH",namespace:"default"},"AI_SEARCH (AI Search namespace)")},{enabled:ze(n,e),run:a=>N(a,r,"analytics")},{enabled:n.usesBrowser,run:a=>N(a,r,"browser")},{enabled:n.usesImages,run:a=>N(a,r,"images")},{enabled:n.usesAnalytics,run:a=>V(a,r,"analytics_engine_datasets",{binding:"ANALYTICS",dataset:"ANALYTICS"},"ANALYTICS (Analytics Engine)")},{enabled:n.usesWorkerLoader,run:a=>dn(a,r)},{enabled:!0,run:a=>mn(a,r)},{enabled:t===void 0||t==="cloudflare",run:a=>pn(a,r)},{enabled:(t===void 0||t==="cloudflare")&&n.workerRoutes!==void 0,run:a=>de(a,r,n.workerRoutes??[],g,Se(e))},{enabled:d.length>0,run:a=>gn(a,r,d)},{enabled:l.length>0||v.length>0,run:a=>_n(a,r,l,v,hn(e))},{enabled:n.queues.length>0,run:a=>{const w=Te(a,r,n.queues,b.queues??{});return h.queues=w.owned,{...w,record:{consequence:"an option removed from defineQueue stays deployed",key:"queueTuning",label:"queue tuning",write:C=>{je(C,b,h)}}}}},{enabled:n.services!==void 0&&(n.services.length>0||Object.keys(y).length>0),run:a=>{const w=fe(a,r,n.services??[],y);return E=w.owned,{...w,record:{consequence:"a service removed from lunora.config stays bound",key:"services",label:"service bindings",write:C=>{he(C,E??w.owned)}}}}},...s===void 0||r.env?.[s]===void 0?[]:[{enabled:n.queues.length>0,run:a=>{const w=`env.${s}.queues`,x=Ie(a,r,n.queues,s,b[w]??{});return h[w]=x.owned,x}}]];let f=m;const S=[],A=[],F=[];for(const a of O){if(!a.enabled)continue;const w=a.run(f);f=w.text,S.push(...w.added),A.push(...w.updated??[]),u.push(...w.warnings??[]),F.push(...[w.record].filter(x=>x!==void 0))}const H=a=>{if(g!==void 0)for(const w of F)try{w.write(Y(e)??g)}catch(x){u.push(`${a?"wrangler.jsonc was updated, but ":""}recording the ${w.label} reconcile owns in ${g.path} (lunora.${w.key}) failed: ${x instanceof Error?x.message:String(x)}. Until it is recorded, ${w.consequence}.`)}};let k;if(n.services!==void 0){const a=be(e,n.services,y);u.push(...a.warnings),E={...E,...a.owned},k=a.added.length>0||a.updated.length>0?{added:a.added,path:a.path,updated:a.updated}:void 0}return u.push(...Ge(S,t)),f===m?(H(!1),{added:S,changed:!1,devConfig:k,exportGaps:i,reason:"bindings already in sync",updated:A,warnings:u,wranglerPath:o}):(ne(o,f,"utf8"),H(!0),{added:S,changed:!0,devConfig:k,exportGaps:i,updated:A,warnings:u,wranglerPath:o})};export{Ye as collectExportGaps,Wn as reconcileWranglerBindings};
1
+ import{createRequire as ee}from"node:module";import{join as V}from"node:path";import{containerBuildTag as ne}from"@lunora/container";import{readJsonSync as se}from"@visulima/fs";import{c as te}from"./celld-binding-id-9MiUoteo.mjs";import{applyModify as w}from"./applyModify-DKP2l6S9.mjs";import{recordManifestKey as ie,readManifest as oe}from"./readManifest-Cighz3WC.mjs";import{D1_PLACEHOLDER_ID as Q,HYPERDRIVE_PLACEHOLDER_ID as re}from"./D1_PLACEHOLDER_ID-ZnDjVymH.mjs";import{m as ae,w as de,n as ce,s as G,o as q,p as C,q as le}from"./validate-bindings-CQbR23li.mjs";import{parseTree as ue,findNodeAtLocation as ge}from"jsonc-parser";import{r as me,a as pe,p as fe,b as be}from"./reconcile-services-CjgIJKim.mjs";import{readFileSync as he}from"node:fs";import{DEV_VARS_FILE as ve,parseDevVariableEntries as we}from"./DEV_VARS_EXAMPLE_FILE-hBT89IXh.mjs";import{secretSourcesFromBindings as _e}from"./inferLunoraBindings-Biq1OW9V.mjs";import{requiredSecrets as ye}from"./buildPackageSecretsBlock-DrSD60vH.mjs";import{b as Se}from"./guards-CoCtgpeR.mjs";import{s as Ee}from"./worker-entry-checks-DH-ApvvX.mjs";import{DEFAULT_OBSERVABILITY as xe}from"./DEFAULT_OBSERVABILITY-CPLADr5u.mjs";import{findWranglerFile as Ae,readWranglerJsonc as Oe}from"./WRANGLER_FILES-BF8PUjuo.mjs";const Ne=[["maxBatchSize","max_batch_size"],["maxBatchTimeout","max_batch_timeout"],["maxConcurrency","max_concurrency"],["maxRetries","max_retries"],["deadLetterQueue","dead_letter_queue"],["retryDelay","retry_delay"]],D=e=>Object.fromEntries(Ne.filter(([n])=>e.tuning[n]!==void 0).map(([n,s])=>[s,e.tuning[n]])),P="queueTuning",ke=/^[\t ]*(?:,[\t ]*)?(?:\/\/[^\n\r]*)?\r?\n/u,$e=/^[\t ]*,/u,Ce=(e,n)=>{const s=ue(e),t=s===void 0?void 0:ge(s,[...n])?.parent;if(t?.type==="property"){const o=t.offset+t.length,i=e.lastIndexOf(`
2
+ `,t.offset-1)+1,r=ke.exec(e.slice(o));if(r!==null&&e.slice(i,t.offset).trim()===""){const m=t.parent?.children??[],u=m.indexOf(t),d=u===m.length-1&&u>0?m[u-1]:void 0,c=d===void 0?void 0:$e.exec(e.slice(d.offset+d.length))??void 0;return(c===void 0||d===void 0?e.slice(0,i):e.slice(0,d.offset+d.length)+e.slice(d.offset+d.length+c[0].length,i))+e.slice(o+r[0].length)}}return w(e,n,void 0)},U=(e,n,s,t,o,i=new Set)=>{const r=s.join("."),m={},u=[],d=[];let c=e;return{entries:n.map((l,v)=>{const g=t(l);if(g===void 0||l.queue===void 0)return l;const f=Object.fromEntries(Object.entries(D(g)).filter(([h])=>!i.has(h))),b=Object.entries(o[l.queue]??{}).filter(([h])=>!Object.hasOwn(f,h)),_=Object.entries(f).filter(([h,y])=>l[h]!==y),E=b.filter(([h,y])=>l[h]===y).map(([h])=>h),x=Object.fromEntries(Object.entries({...l,...f}).filter(([h])=>!E.includes(h)));for(const[h,y]of _)c=w(c,[...s,v,h],y);for(const h of E)c=Ce(c,[...s,v,h]);for(const[h,y]of b){const A=l[h];A!==void 0&&A!==y&&d.push(`${r}/${l.queue}: ${h} is no longer declared by defineQueue, but it was changed by hand to ${JSON.stringify(A)} from the declared ${JSON.stringify(y)}, so it was kept. Delete it from wrangler.jsonc if it should go.`)}return(_.length>0||E.length>0)&&u.push(`${r}/${l.queue} (${[..._.map(([h])=>h),...E.map(h=>`removed ${h}`)].join(", ")})`),Object.keys(f).length>0&&(m[l.queue]=f),x}),owned:m,text:c,updated:u,warnings:d}},Te=(e,n,s,t)=>{const o=n.queues??{},i=o.producers??[],r=o.consumers??[],m=new Set(i.map(g=>g?.binding)),u=new Set(r.map(g=>g.queue)),d=s.filter(g=>!m.has(g.bindingName)),c=s.filter(g=>!u.has(g.name)),p=U(e,r,["queues","consumers"],g=>s.find(f=>f.name===g.queue),t);let l=p.text;const v={...p.owned};if(d.length>0||c.length>0){const g=[...i,...d.map(b=>({binding:b.bindingName,queue:b.name}))],f=[...p.entries,...c.map(b=>({queue:b.name,...b.mode==="pull"?{type:"http_pull"}:{},...D(b)}))];for(const b of c){const _=D(b);Object.keys(_).length>0&&(v[b.name]=_)}l=w(l,["queues"],{consumers:f,producers:g})}return{added:[...d.map(g=>`queues.producers/${g.bindingName}`),...c.map(g=>`queues.consumers/${g.name}`)],owned:v,text:l,updated:p.updated,warnings:p.warnings}},Ie=(e,n,s,t,o)=>{const i=n.env?.[t],r=i?.queues?.consumers??[],m=i?.queues?.producers??[],u=l=>{const v=m.find(g=>g?.queue===l.queue)?.binding;return v!==void 0?s.find(g=>g.bindingName===v):s.find(g=>g.name===l.queue&&!m.some(f=>f?.binding===g.bindingName))},d=U(e,r,["env",t,"queues","consumers"],u,o,new Set(["dead_letter_queue"])),c=r.filter(l=>l.queue!==void 0&&u(l)===void 0).map(l=>`env.${t}.queues.consumers/${String(l.queue)}: no defineQueue export matches it — this block declares no producer mapping one of their bindings to "${String(l.queue)}", and no export is named that — so it was not retuned. A consumer for a queue another worker produces is skipped the same way.`),p=r.flatMap(l=>{const v=u(l)?.tuning.deadLetterQueue;return v===void 0||l.dead_letter_queue!==void 0?[]:[`env.${t}.queues.consumers/${String(l.queue)}: defineQueue declares deadLetterQueue "${v}", but this consumer has no dead_letter_queue, so its exhausted messages are dropped. Queue names differ per environment, so reconcile does not write it here; add it by hand.`]});return{added:[],owned:d.owned,text:d.text,updated:d.updated,warnings:[...d.warnings,...p,...c]}},Re=(e,n)=>{if(e?.lunoraIsForeign===!0)return n.push(`${e.path}: \`lunora\` is not an object, so the queue tuning ownership record cannot be read or written — an option removed from defineQueue stays deployed.`),{};const s=e?.lunora?.[P],t=o=>typeof o=="object"&&o!==null&&!Array.isArray(o);return s===void 0?{}:!t(s)||!Object.values(s).every(o=>t(o)&&Object.values(o).every(i=>t(i)))?(n.push(`${e?.path??"package.json"}: \`lunora.${P}\` is not a map of scope → queue → fields, so it is ignored — an option removed from defineQueue stays deployed until the next pass records it again.`),{}):s},je=(e,n,s)=>{const t=Object.fromEntries(Object.entries({...n,...s}).filter(([,o])=>Object.keys(o).length>0));ie(e,P,Object.keys(t).length===0?void 0:t)},qe="https://api.cloudflare.com/client/v4/accounts/<ACCOUNT_ID>/artifacts/namespaces",De=e=>{const n='add an "artifacts" binding ({ binding: "ARTIFACTS", namespace }) — codegen reads env.ARTIFACTS unless `.artifacts()` on defineApp points ctx.artifacts at another binding';return e===void 0?`ctx.artifacts is used; ${n}. The namespace is created by the first repo create() if it does not exist yet.`:`ctx.artifacts is used and the schema pins data to "${e}"; create the namespace in that jurisdiction BEFORE the first repo, with POST ${qe} and body { "namespace": "<name>", "jurisdiction": "${e}" }, then ${n}. A namespace's jurisdiction cannot be changed, and one created implicitly by the first repo create() is unrestricted. With CLOUDFLARE_API_TOKEN set, \`lunora deploy\` creates a missing namespace in that jurisdiction for a binding you have added.`},T="PIPELINES",I="ARTIFACTS",Pe=(e,n,s)=>{const t=n!==void 0&&(s===void 0||s==="cloudflare"),o=e.flagshipBinding!==void 0&&!(n?.flagship??[]).some(d=>d.binding===e.flagshipBinding),i=e.usesPipelines&&!(n?.pipelines??[]).some(d=>d.binding===T),r=e.usesArtifacts?n?.artifacts??[]:[],m=r.some(d=>d.binding===I)?[]:r.flatMap(d=>d.binding===void 0?[]:[d.binding]);return[[e.usesKv&&(n?.kv_namespaces?.length??0)===0&&(!t||e.jurisdiction!==void 0),e.jurisdiction===void 0?'ctx.kv is used but no kv_namespaces binding exists; add one ({ binding: "KV" }) — wrangler creates the namespace on the first deploy.':`ctx.kv is used and the schema pins data to "${e.jurisdiction}"; run \`wrangler kv namespace create <name> --jurisdiction ${e.jurisdiction}\` and add a kv_namespaces entry ({ binding: "KV", id }) — a namespace wrangler creates on deploy is unrestricted.`],[e.usesHyperdrive&&(n?.hyperdrive?.length??0)===0&&!t,'@lunora/hyperdrive is used but no hyperdrive binding exists; add one ({ binding: "HYPERDRIVE", id }) — on a Cloudflare target `lunora deploy` creates the Hyperdrive config from a connection string.'],[e.usesArtifacts&&r.length===0&&(!t||e.jurisdiction!==void 0),De(e.jurisdiction)],[i,`ctx.pipelines is used but no "${T}" pipelines binding exists; run 'wrangler pipelines create <name>' and add a 'pipelines' binding ({ binding: "${T}", stream }) — codegen resolves this one name, and the pipeline resource can't be auto-provisioned.`],[m.length>0,`ctx.artifacts is used and ${m.map(d=>`"${d}"`).join(", ")} ${m.length===1?"is":"are"} bound, but none is named "${I}"; make sure \`.artifacts()\` on defineApp points ctx.artifacts at it — otherwise it reads env.${I} and throws.`],[o,`lunora/flags.ts uses Flagship in binding mode but no flagship binding "${e.flagshipBinding??""}" exists; add a flagship entry ({ binding: "${e.flagshipBinding??""}", app_id }) — the app_id can't be auto-provisioned.`]].filter(([d])=>d).map(([,d])=>d)},Be=e=>[[e.usesX402Charge,"@lunora/x402/charge is used; set the recipient wallet address as a [vars] entry (the var name is your choice) and pass it to the charge config — the x402 facilitator settles USDC to that address."],[e.usesX402,"@lunora/x402/pay is used (ActionCtx-only, spends real funds); add a secrets_store_secrets[] binding holding the agent wallet key (binding name == signer.secretName) and pair the pay rail with a spend policy — ctx.secrets reads a Secrets Store binding, not .dev.vars."]].filter(([s])=>s).map(([,s])=>s),R=(e,n,s)=>s.filter(t=>!t.exported).map(t=>`${e} "${t.exportName}" is declared but ${t.className} is not exported by the worker entry; add \`export * from "./lunora/_generated/${n}"\` so its binding can be provisioned.`),Le=(e,n)=>{const s=new Set([...e.workflows,...e.agents].map(i=>i.className));if(s.size===0)return[];const t=Object.entries(n.exports??{}).flatMap(([i,r])=>r?.type==="workflow"?[i]:[]),o=(n.workflows??[]).flatMap(i=>i.class_name===void 0||i.script_name!==void 0?[]:[i.class_name]);return[...new Set([...t,...o])].filter(i=>!s.has(i)).map(i=>`wrangler.jsonc declares workflow "${i}" but no defineWorkflow/defineAgent export generates that class — a leftover from a rename will fail the deploy (wrangler rejects a class the worker does not export). Remove it if it is not hand-wired.`)},We=(e,n)=>{if(e.queues.length===0)return[];const s=new Set(e.queues.map(o=>o.name)),t=new Set(e.queues.map(o=>o.bindingName));return[...(n.queues?.consumers??[]).flatMap(o=>{const{queue:i}=o;return i===void 0||s.has(i)?[]:[`wrangler.jsonc subscribes queues.consumers[] to "${i}" but no defineQueue export declares that queue — a leftover from a rename keeps delivering batches this worker has no handler for (they retry to exhaustion, then drop or dead-letter). Remove it if it is not hand-wired.`]}),...(n.queues?.producers??[]).flatMap(o=>{const i=o?.binding;return i===void 0||t.has(i)?[]:[`wrangler.jsonc declares queues.producers[] binding "${i}" but no defineQueue export declares it — a leftover from a rename. Remove it if it is not hand-wired.`]})]},Me=(e,n)=>[...Le(e,n),...We(e,n)],J=[{keys:["STRIPE_SECRET_KEY","STRIPE_WEBHOOK_SECRET"],label:"Stripe"},{keys:["POLAR_ACCESS_TOKEN","POLAR_WEBHOOK_SECRET"],label:"Polar"},{keys:["CREEM_API_KEY","CREEM_WEBHOOK_SECRET"],label:"Creem"},{keys:["AUTUMN_SECRET_KEY","AUTUMN_WEBHOOK_SECRET"],label:"Autumn"},{keys:["DODO_PAYMENTS_API_KEY","DODO_PAYMENTS_WEBHOOK_KEY"],label:"Dodo Payments"}],Ke=()=>J.map(({keys:e,label:n})=>`${e[0]} + ${e[1]} (${n})`).join(" or "),Fe=e=>{let n;try{n=he(V(e,ve),"utf8")}catch{return!1}const s=new Map(we(n).map(t=>[t.key,t.value]));return J.some(({keys:t})=>t.every(o=>(s.get(o)??"")!==""))},He=(e,n)=>{const s=n?.secrets?.required;if(!Array.isArray(s))return[];const t=new Set(s),o=ye(_e(e)).map(i=>i.key).filter(i=>!t.has(i));return o.length===0?[]:[`wrangler.jsonc declares secrets.required without ${o.join(", ")}, which this app needs — wrangler dev loads only the listed keys from .dev.vars, so add ${o.length===1?"it":"them"} to secrets.required.`]},j=(e,n,s,t)=>{const o=new Set(e.durableObjects.map(u=>u.className)),i=[],r=(s?.r2_buckets?.length??0)>0,m=(s?.d1_databases?.some(u=>u.binding==="DB")??!1)||e.needsD1;return e.usesStorage&&!r&&i.push("@lunora/storage is used but R2 bucket bindings have user-defined names; add an r2_buckets entry and pass env.<BINDING> to createStorage()."),e.usesAuth&&!o.has("SessionDO")&&!m&&i.push("@lunora/auth is used but the worker entry exports no SessionDO; sessions are D1-backed, or export SessionDO to enable DO-backed sessions."),e.usesScheduler&&!o.has("SchedulerDO")&&i.push("@lunora/scheduler is used but the worker entry exports no SchedulerDO; export it so the SCHEDULER binding can be provisioned."),i.push(...R("container","containers",e.containers),...R("workflow","workflows",e.workflows),...R("agent","agents",e.agents)),e.containers.length>0&&s?.observability?.enabled===!1&&i.push("containers are declared but observability is explicitly disabled in wrangler.jsonc — container logs will not be captured."),e.usesPayments&&!Fe(n)&&i.push(`@lunora/payment is used; set one provider's secret pair in .dev.vars — ${Ke()}.`),i.push(...Be(e),...Pe(e,s,t),...He(e,s)),s!==void 0&&i.push(...Me(e,s)),i},Ye=e=>[["container","containers",e.containers],["workflow","workflows",e.workflows],["agent","agents",e.agents]].flatMap(([s,t,o])=>o.filter(i=>!i.exported).map(({className:i,exportName:r})=>({className:i,exportName:r,kind:s,module:t}))),Ve=e=>{const n=new Set(q(e).map(t=>t.tag));let s=1;for(;n.has(`v${String(s)}`);)s+=1;return`v${String(s)}`},Qe=e=>{const n=new Set;for(const s of q(e)){for(const t of C(s.deleted_classes))n.delete(t);for(const{from:t,to:o}of q(s.renamed_classes))t!==void 0&&n.delete(t),o!==void 0&&n.add(o);for(const t of[...C(s.new_classes),...C(s.new_sqlite_classes)])n.add(t)}return n},Ge=(e,n,s)=>{const t=n.durable_objects?.bindings??[],o=new Set(t.map(c=>c.name)),i=s.filter(c=>!o.has(c.binding));let r=e;const m=[];if(i.length>0){const c=[...t,...i.map(p=>({class_name:p.className,name:p.binding}))];r=w(r,["durable_objects","bindings"],c),m.push(...i.map(p=>`${p.binding}/${p.className}`))}const u=n.migrations??[],d=s.map(c=>c.className).filter(c=>!Qe(u).has(c));if(d.length>0){const c=[...u,{new_sqlite_classes:d,tag:Ve(u)}];r=w(r,["migrations"],c)}return{added:m,text:r}},L=e=>e===void 0||e==="cloudflare",Ue=(e,n)=>e.includes("DB (D1)")&&L(n)?[`wrote a DB binding with a placeholder database_id ("${Q}") — run \`wrangler d1 create <name>\` and replace it before deploying.`]:[],Je=(e,n)=>{const s=n.d1_databases??[];if(s.some(i=>i.binding==="DB"))return{added:[],text:e};const t=typeof n.name=="string"&&n.name.length>0?n.name:"lunora",o=[...s,{binding:"DB",database_id:Q,database_name:t}];return{added:["DB (D1)"],text:w(e,["d1_databases"],o)}},Xe={ai:{binding:"AI",label:"AI (Workers AI)"},analytics:{binding:"ANALYTICS_SQL",label:"ANALYTICS_SQL (Analytics SQL)"},browser:{binding:"BROWSER",label:"BROWSER (Browser Rendering)"},images:{binding:"IMAGES",label:"IMAGES (Cloudflare Images)"}},ze=(e,n)=>e.usesAnalyticsSql&&Ee(n,new Set(["analyticsSql"]))?.chained.has("analyticsSql")!==!0,Ze=new Set(["ratelimits","send_email"]),en=["durable_objects","logfwdr","unsafe"],nn=new Set(["data_blobs","text_blobs","vars","wasm_modules"]),W=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),B=(e,n,s)=>W(e)&&e[n]===s,sn=(e,n,s)=>{if(nn.has(e))return W(n)&&Object.hasOwn(n,s);const t=Ze.has(e)?"name":"binding";return Array.isArray(n)?n.some(o=>B(o,t,s)):B(n,"binding",s)},N=(e,n)=>{const s=e,t=Object.entries(s).find(([i,r])=>i!=="env"&&sn(i,r,n));if(t!==void 0)return t[0];for(const i of en){const r=s[i];if(W(r)&&Array.isArray(r.bindings)&&r.bindings.some(m=>B(m,"name",n)))return`${i}.bindings`}if(e.queues?.producers?.some(i=>i?.binding===n)===!0)return"queues.producers";const o=e.secrets?.required;if(Array.isArray(o)&&o.includes(n))return"secrets.required"},k=(e,n,s)=>{const{binding:t,label:o}=Xe[s],i=n[s]?.binding;if(typeof i=="string"&&i.length>0)return{added:[],text:e};const r=N(n,t);return r!==void 0?{added:[],text:e,warnings:[`${s}: not adding the ${o} binding — the name "${t}" is already bound by \`${r}\` in wrangler.jsonc. Rename that binding, then set ${s}.binding by hand.`]}:{added:[o],text:w(e,[s],{binding:t})}},M=(e,n,s)=>`${e}: not adding "${n}" — the name is already bound by \`${s}\` in wrangler.jsonc. Add a ${e} entry under another binding name and point the matching \`defineApp()\` override at it.`,tn=(e,n,s)=>{if(!L(s)||(n.hyperdrive?.length??0)>0)return{added:[],text:e};const t=N(n,"HYPERDRIVE");return t!==void 0?{added:[],text:e,warnings:[M("hyperdrive","HYPERDRIVE",t)]}:{added:["HYPERDRIVE (Hyperdrive, created on deploy)"],text:w(e,["hyperdrive"],[{binding:"HYPERDRIVE",id:re}])}},on=new Set(["celld","cloudflare"]),rn=(e,n,s,t)=>{if(t!==void 0&&!on.has(t)||s!==void 0||(n.kv_namespaces?.length??0)>0)return{added:[],text:e};const o=N(n,"KV");return o!==void 0?{added:[],text:e,warnings:[M("kv_namespaces","KV",o)]}:{added:[t==="celld"?`KV (Workers KV, celld namespace ${te(n.name,"KV")})`:"KV (Workers KV, created on deploy)"],text:w(e,["kv_namespaces"],[{binding:"KV"}])}},an=(e,n,s,t)=>{if(!L(t)||s!==void 0||(n.artifacts?.length??0)>0)return{added:[],text:e};const o=N(n,"ARTIFACTS");if(o!==void 0)return{added:[],text:e,warnings:[M("artifacts","ARTIFACTS",o)]};const i=typeof n.name=="string"&&n.name.length>0?n.name:"lunora";return{added:["ARTIFACTS (Cloudflare Artifacts)"],text:w(e,["artifacts"],[{binding:"ARTIFACTS",namespace:i}])}},Y=(e,n,s,t,o)=>{if((n[s]?.length??0)>0)return{added:[],text:e};const i=N(n,t.binding);return i!==void 0?{added:[],text:e,warnings:[`${s}: not adding ${JSON.stringify(t)} — the name "${t.binding}" is already bound by \`${i}\` in wrangler.jsonc. Add a ${s} entry under another binding name and point the matching \`defineApp()\` override at it.`]}:{added:[o],text:w(e,[s],[t])}},dn=(e,n)=>{const s=n.worker_loaders??[];return s.some(t=>t.binding==="LOADER")?{added:[],text:e}:{added:["LOADER (Worker Loader)"],text:w(e,["worker_loaders"],[...s,{binding:"LOADER"}])}},cn=e=>{if(typeof e=="string")return e;const n={};return e.diskMb!==void 0&&(n.disk_mb=e.diskMb),e.memoryMib!==void 0&&(n.memory_mib=e.memoryMib),e.vcpu!==void 0&&(n.vcpu=e.vcpu),n},ln=e=>{const{image:n}=e;return n.kind==="dockerfile"?n.dockerfilePath:n.kind==="registry"?n.reference:ne(e.exportName)},X=e=>{const n={};for(const[s,t]of Object.entries(e.images??{}))n[s]=t.kind==="registry"?{image:t.reference}:{build_context:t.buildContext,dockerfile:t.dockerfilePath,...e.buildArgs===void 0?{}:{build_vars:e.buildArgs}};return{class_name:e.className,scheduling_policy:"durable_object",...Object.keys(n).length>0?{images:n}:{},...e.name===void 0?{}:{name:e.name}}},un=e=>{if(e.schedulingPolicy==="durable_object")return X(e);const{image:n}=e,s={class_name:e.className,image:ln(e)};return n.kind==="dockerfile"&&(s.image_build_context=n.buildContext),e.buildArgs!==void 0&&n.kind!=="registry"&&(s.image_vars=e.buildArgs),e.instanceType!==void 0&&(s.instance_type=cn(e.instanceType)),e.maxInstances!==void 0&&(s.max_instances=e.maxInstances),e.name!==void 0&&(s.name=e.name),e.rollout?.stepPercentage!==void 0&&(s.rollout_step_percentage=e.rollout.stepPercentage),e.rollout?.gracePeriodSeconds!==void 0&&(s.rollout_active_grace_period=e.rollout.gracePeriodSeconds),s},gn=(e,n,s)=>{const t=n.containers??[],o=new Set(t.map(d=>d.class_name)),i=s.filter(d=>!o.has(d.className));let r=i.length===0?e:w(e,["containers"],[...t,...i.map(d=>un(d))]);const m=[],u=[];for(const[d,c]of t.entries()){const p=s.find(g=>g.className===c.class_name);if(p===void 0)continue;const l=p.schedulingPolicy??"default";if((c.scheduling_policy??"default")!==l){u.push(`containers/${p.className} has scheduling_policy "${c.scheduling_policy??"default"}" in wrangler.jsonc but defineContainer "${p.exportName}" declares "${l}" — the policy is immutable, so replace the entry (and its container application) by hand.`);continue}const v=p.schedulingPolicy==="durable_object"?X(p).images:void 0;v!==void 0&&JSON.stringify(c.images)!==JSON.stringify(v)&&(r=w(r,["containers",d,"images"],v),m.push(`containers/${p.className}.images`))}return{added:i.map(d=>`containers/${d.className}`),text:r,updated:m,warnings:u}},mn=(e,n)=>{if(n.observability!==void 0)return{added:[],text:e};const s=w(e,["observability"],{...xe});return{added:["observability"],text:s}},pn=(e,n)=>n.upload_source_maps!==void 0?{added:[],text:e}:{added:["upload_source_maps"],text:w(e,["upload_source_maps"],!0)},z=[{minimum:[4,142],name:"wrangler"},{minimum:[1,61],name:"@cloudflare/vite-plugin"}],fn=z.map(({minimum:e,name:n})=>`${n}@^${e.join(".")}.0`).join(" "),bn=(e,n)=>{try{const s=ee(V(e,"package.json")).resolve(`${n}/package.json`),[t=0,o=0]=String(se(s).version).split(".").map(Number);return[t,o]}catch{return}},hn=e=>{const n=z.flatMap(({minimum:s,name:t})=>{const o=bn(e,t);return o!==void 0&&(o[0]<s[0]||o[0]===s[0]&&o[1]<s[1])?[`${t} ${o.join(".")} (needs >= ${s.join(".")})`]:[]});return n.length===0?void 0:`workflows are declared in wrangler \`exports\`, which ${n.join(" and ")} cannot run — reconcile left workflows[] untouched. Upgrade (\`pnpm add -D ${fn}\`) and re-run.`},vn=e=>Object.entries(e.env??{}).flatMap(([n,s])=>Array.isArray(s?.workflows)?[`env.${n}.workflows declares workflow bindings, but Lunora now declares workflows in \`exports\` and resolves them on ctx.exports — move them to that environment's own \`exports\` by hand.`]:[]),wn=(e,n,s)=>{let t=e;const o=[],i=[];for(const r of s){const m=n[r.className];if(m?.type==="workflow")for(const{of:u,path:d}of le){const c=u(r),p=G(m,d),l=`exports/${r.className}.${d.join(".")}`;if(c===void 0){p!==void 0&&i.push(`${l} is set in wrangler.jsonc but defineWorkflow "${r.exportName}" does not declare it — reconcile leaves it in place. Remove it by hand if it was dropped from the definition.`);continue}JSON.stringify(p)!==JSON.stringify(c)&&(t=w(t,["exports",r.className,...d],c),o.push(l))}}return{text:t,updated:o,warnings:i}},_n=(e,n,s,t,o)=>{if(o!==void 0)return{added:[],text:e,warnings:[o]};const i=[...s.map(f=>({settings:de(f),workflow:f})),...t.map(f=>({settings:{},workflow:f}))],r=new Set(i.map(({workflow:f})=>f.className)),m=n.workflows??[],u=m.filter(f=>f.script_name===void 0&&f.class_name!==void 0&&r.has(f.class_name)),d=n.exports??{},c=[],p=[],l=[];let v=e;for(const{settings:f,workflow:b}of i){if(d[b.className]!==void 0&&d[b.className]!==null)continue;const _=u.find(h=>h.class_name===b.className),E=Object.fromEntries(ce.flatMap(h=>{const y=G(_,[h]);return y===void 0?[]:[[h,y]]})),x=_?.name??b.name;_?.name!==void 0&&_.name!==b.name&&l.push(`workflows/${b.className} is deployed as "${_.name}" but declared as "${b.name}" — its export keeps "${_.name}" so running instances survive. Change the declaration to match, or rename deliberately (it starts a new, empty workflow).`),v=w(v,["exports",b.className],{type:"workflow",...E,...f,name:x}),(_===void 0?c:p).push(`exports/${b.className}`)}if(u.length>0){const f=m.filter(b=>!u.includes(b));v=w(v,["workflows"],f.length===0?void 0:f),p.push(...u.map(b=>`workflows/${String(b.class_name)} → exports`))}l.push(...vn(n));const g=wn(v,d,s);return{added:c,text:g.text,updated:[...p,...g.updated],warnings:[...l,...g.warnings]}},Wn=(e,n,{environment:s,target:t}={})=>{const o=Ae(e),i=Ye(n);if(!o)return{added:[],exportGaps:i,reason:"wrangler.jsonc not found",updated:[],warnings:j(n,e)};const{parsed:r,text:m}=Oe(o);if(r===void 0)return{added:[],exportGaps:i,reason:`failed to parse ${o} as JSONC`,updated:[],warnings:j(n,e),wranglerPath:o};const u=j(n,e,r,t);if(s!==void 0){const a=r.env?.[s]!==void 0;u.push(a?`auto-provisioned bindings are written to the top level of wrangler.jsonc only (queue consumers "env.${s}" already declares are retuned, nothing is added) — "env.${s}" has its own (non-inheritable) bindings and must be reconciled by hand; \`lunora deploy --env ${s}\` now validates them, so a gap here will be reported at deploy time.`:`--env "${s}" was requested but wrangler.jsonc declares no "env.${s}" block — auto-provisioned bindings are written to the top level only and will not apply to that environment.`)}const d=n.containers.filter(a=>a.exported),c=n.agents.filter(a=>a.exported&&a.voice===!0&&a.voiceBindingName!==void 0&&a.voiceClassName!==void 0),p=[...n.durableObjects,...d.map(a=>({binding:a.bindingName,className:a.className})),...c.map(a=>({binding:a.voiceBindingName,className:a.voiceClassName}))],l=n.workflows.filter(a=>a.exported),v=n.agents.filter(a=>a.exported),g=oe(e),f=Re(g,u),b={},_=me(g);let E,x={unwritten:{},written:{}};const h=[{enabled:!0,run:a=>Ge(a,r,p)},{enabled:n.needsD1,run:a=>Je(a,r)},{enabled:n.usesKv,run:a=>rn(a,r,n.jurisdiction,t)},{enabled:n.usesHyperdrive,run:a=>tn(a,r,t)},{enabled:n.usesArtifacts,run:a=>an(a,r,n.jurisdiction,t)},{enabled:n.usesAi,run:a=>k(a,r,"ai")},{enabled:n.usesAiSearch,run:a=>Y(a,r,"ai_search_namespaces",{binding:"AI_SEARCH",namespace:"default"},"AI_SEARCH (AI Search namespace)")},{enabled:ze(n,e),run:a=>k(a,r,"analytics")},{enabled:n.usesBrowser,run:a=>k(a,r,"browser")},{enabled:n.usesImages,run:a=>k(a,r,"images")},{enabled:n.usesAnalytics,run:a=>Y(a,r,"analytics_engine_datasets",{binding:"ANALYTICS",dataset:"ANALYTICS"},"ANALYTICS (Analytics Engine)")},{enabled:n.usesWorkerLoader,run:a=>dn(a,r)},{enabled:!0,run:a=>mn(a,r)},{enabled:t===void 0||t==="cloudflare",run:a=>pn(a,r)},{enabled:(t===void 0||t==="cloudflare")&&n.workerRoutes!==void 0,run:a=>ae(a,r,n.workerRoutes??[],g,Se(e))},{enabled:d.length>0,run:a=>gn(a,r,d)},{enabled:l.length>0||v.length>0,run:a=>_n(a,r,l,v,hn(e))},{enabled:n.queues.length>0,run:a=>{const S=Te(a,r,n.queues,f.queues??{});return b.queues=S.owned,{...S,record:{consequence:"an option removed from defineQueue stays deployed",key:"queueTuning",label:"queue tuning",write:$=>{je($,f,b)}}}}},{enabled:n.services!==void 0&&(n.services.length>0||Object.keys(_).length>0),run:a=>{const S=pe(a,r,n.services??[],_);return E=S.owned,{...S,record:{consequence:"a service removed from lunora.config stays bound",key:"services",label:"service bindings",write:($,{devConfigWritten:Z})=>{be($,{...E,...Z?x.written:x.unwritten})}}}}},...s===void 0||r.env?.[s]===void 0?[]:[{enabled:n.queues.length>0,run:a=>{const S=`env.${s}.queues`,O=Ie(a,r,n.queues,s,f[S]??{});return b[S]=O.owned,O}}]];let y=m;const A=[],K=[],F=[];for(const a of h){if(!a.enabled)continue;const S=a.run(y);y=S.text,A.push(...S.added),K.push(...S.updated??[]),u.push(...S.warnings??[]),F.push(...[S.record].filter(O=>O!==void 0))}let H;if(n.services!==void 0){const a=fe(e,n.services,_);u.push(...a.warnings),x={unwritten:a.previouslyOwned,written:a.owned},H=a}return u.push(...Ue(A,t)),{added:A,devConfig:H,edit:{manifest:g,original:m,records:F,text:y},exportGaps:i,updated:K,warnings:u,wranglerPath:o}};export{Ye as collectExportGaps,Wn as planWranglerBindings};
@@ -1 +1 @@
1
- import{devVariablesStamp as u}from"./devVariablesStamp-Cetr3qFz.mjs";const c=(o,r)=>{let t,e;return()=>{const a=u(o);return(t===void 0||a!==e)&&(e=a,t={value:r()}),t.value}};export{c as default};
1
+ import{devVariablesStamp as u}from"./devVariablesStamp-BQkGEn9d.mjs";const c=(o,r)=>{let t,e;return()=>{const a=u(o);return(t===void 0||a!==e)&&(e=a,t={value:r()}),t.value}};export{c as default};
@@ -1 +1 @@
1
- import{writeFileSync as u}from"node:fs";import{modify as y,applyEdits as w}from"jsonc-parser";import{readManifest as m,formattingFor as v,recordManifestKey as $}from"./readManifest-Cighz3WC.mjs";import{findWranglerFile as x,readWranglerJsonc as C}from"./WRANGLER_FILES-UNW-xY5u.mjs";const b=(r,n)=>r.length===n.length&&r.every((e,t)=>e===n[t]),j=(r,n)=>{if(r?.lunoraIsForeign===!0)return n.push(`${r.path}: \`lunora\` is not an object, so the cron ownership record cannot be read or written — a removed cron will keep firing.`),[];const e=r?.lunora?.crons;if(e===void 0)return[];if(!Array.isArray(e))return n.push(`${r?.path??"package.json"}: \`lunora.crons\` is not an array of cron expressions — the crons it recorded are now treated as hand-written and will not be cleared.`),[];const t=e.filter(o=>typeof o=="string");return t.length!==e.length&&n.push(`${r?.path??"package.json"}: \`lunora.crons\` dropped ${String(e.length-t.length)} non-string entry(s) — anything it recorded there is now treated as hand-written and will not be cleared.`),t},k=(r,n)=>{$(r,"crons",n.length===0?void 0:[...n])},W=(r,n)=>{const e=x(r);if(!e)return{changed:!1,preserved:[],reason:"wrangler.jsonc not found",warnings:[]};const{parsed:t,text:o}=C(e);if(t===void 0)return{changed:!1,preserved:[],reason:`failed to parse ${e} as JSONC`,warnings:[],wranglerPath:e};const g=Array.isArray(t.triggers?.crons)?t.triggers.crons.filter(i=>typeof i=="string"):[],c=[...n],s=[],d=m(r),p=j(d,s),a=g.filter(i=>!c.includes(i)&&!p.includes(i)),l=[...c,...a],f=()=>{d!==void 0&&k(d,c)};if(b(g,l))return f(),{changed:!1,preserved:a,reason:"triggers.crons already in sync",warnings:s,wranglerPath:e};const h=y(o,["triggers","crons"],l,{formattingOptions:v(o)});return h.length===0?{changed:!1,preserved:a,reason:"no structural edit produced",warnings:s,wranglerPath:e}:(u(e,w(o,h),"utf8"),f(),{changed:!0,preserved:a,warnings:s,wranglerPath:e})},J=r=>r.length===0?void 0:`kept ${String(r.length)} hand-written cron trigger(s): ${r.join(", ")}`;export{J as describePreservedCrons,W as reconcileWranglerCrons};
1
+ import{writeFileSync as u}from"node:fs";import{modify as y,applyEdits as w}from"jsonc-parser";import{readManifest as m,formattingFor as v,recordManifestKey as $}from"./readManifest-Cighz3WC.mjs";import{findWranglerFile as x,readWranglerJsonc as C}from"./WRANGLER_FILES-BF8PUjuo.mjs";const b=(r,n)=>r.length===n.length&&r.every((e,t)=>e===n[t]),j=(r,n)=>{if(r?.lunoraIsForeign===!0)return n.push(`${r.path}: \`lunora\` is not an object, so the cron ownership record cannot be read or written — a removed cron will keep firing.`),[];const e=r?.lunora?.crons;if(e===void 0)return[];if(!Array.isArray(e))return n.push(`${r?.path??"package.json"}: \`lunora.crons\` is not an array of cron expressions — the crons it recorded are now treated as hand-written and will not be cleared.`),[];const t=e.filter(o=>typeof o=="string");return t.length!==e.length&&n.push(`${r?.path??"package.json"}: \`lunora.crons\` dropped ${String(e.length-t.length)} non-string entry(s) — anything it recorded there is now treated as hand-written and will not be cleared.`),t},k=(r,n)=>{$(r,"crons",n.length===0?void 0:[...n])},W=(r,n)=>{const e=x(r);if(!e)return{changed:!1,preserved:[],reason:"wrangler.jsonc not found",warnings:[]};const{parsed:t,text:o}=C(e);if(t===void 0)return{changed:!1,preserved:[],reason:`failed to parse ${e} as JSONC`,warnings:[],wranglerPath:e};const g=Array.isArray(t.triggers?.crons)?t.triggers.crons.filter(i=>typeof i=="string"):[],c=[...n],s=[],d=m(r),p=j(d,s),a=g.filter(i=>!c.includes(i)&&!p.includes(i)),l=[...c,...a],f=()=>{d!==void 0&&k(d,c)};if(b(g,l))return f(),{changed:!1,preserved:a,reason:"triggers.crons already in sync",warnings:s,wranglerPath:e};const h=y(o,["triggers","crons"],l,{formattingOptions:v(o)});return h.length===0?{changed:!1,preserved:a,reason:"no structural edit produced",warnings:s,wranglerPath:e}:(u(e,w(o,h),"utf8"),f(),{changed:!0,preserved:a,warnings:s,wranglerPath:e})},J=r=>r.length===0?void 0:`kept ${String(r.length)} hand-written cron trigger(s): ${r.join(", ")}`;export{J as describePreservedCrons,W as reconcileWranglerCrons};
@@ -0,0 +1 @@
1
+ import{readProjectWrangler as $}from"./WRANGLER_FILES-BF8PUjuo.mjs";import{d as h}from"./queue-info-D38n7YdX.mjs";const i=3,v=e=>Array.isArray(e)?e.filter(r=>typeof r=="string"&&r!==""):[],p=e=>encodeURIComponent(e).replaceAll("%20","+"),S=(e,r,n)=>{const o=[n.studioUrl===void 0?void 0:`run one now in ${n.studioUrl}/schedule`,n.scheduledUrl===void 0?void 0:`curl "${n.scheduledUrl}?cron=${p(r)}"`].filter(t=>t!==void 0);return o.length===0?void 0:{label:"Crons",text:`${String(e)} scheduled → ${o.join(", or ")}`}},U=(e,r)=>{if(r===void 0)return;const n=e.slice(0,i).join(", "),o=e.length>i?` +${String(e.length-i)} more`:"";return{label:"Queues",text:`${n}${o} → send a test message in ${r}/queues`}},A=e=>{const r=$(e.projectRoot)?.parsed;if(r===void 0)return[];const n=process.env.CLOUDFLARE_ENV,o=e.environment??(n===""?void 0:n),t=o===void 0?void 0:r.env?.[o]??void 0,a=t?.triggers===void 0?r.triggers:t.triggers,c=t===void 0?r.queues:t.queues,d=[...new Set(v(a?.crons))],m=Array.isArray(c?.producers)?c.producers:[],u=new Set(v(m.map(s=>s?.binding))),f=u.size===0?[]:h(e.projectRoot,e.schemaDirectory).queues,g=[...new Set(f.filter(s=>u.has(s.bindingName)).map(s=>s.name))],[l]=d;return[l===void 0?void 0:S(d.length,l,e),g.length===0?void 0:U(g,e.studioUrl)].filter(s=>s!==void 0)},E=(e,r,n,o={})=>{const t=`${e}:`.padEnd(n).slice(e.length);return` ${o.arrow?.("➜")??"➜"} ${o.label?.(e)??e}${t}${r}`};export{A as devTriggerHints,E as formatDevBannerRow};
@@ -1 +1 @@
1
- import{statSync as n,readFileSync as i}from"node:fs";import{join as o}from"node:path";import{parseDevVariableEntries as a}from"./DEV_VARS_EXAMPLE_FILE-CqLorAxT.mjs";const v=(t,e)=>{const r=a(t).find(s=>s.key===e);return r===void 0||r.value===""?void 0:r.value},f=t=>{let e;try{e=v(i(o(t,".dev.vars"),"utf8"),"LUNORA_ADMIN_TOKEN")}catch{e=void 0}const r=process.env.LUNORA_ADMIN_TOKEN;return typeof r=="string"&&r!==""&&r!==e&&console.warn("[lunora] LUNORA_ADMIN_TOKEN is exported in this shell but differs from .dev.vars — the local worker only verifies the .dev.vars token, so the studio uses that one."),e},m=t=>{try{const e=n(o(t,".dev.vars"));return`${String(e.ctimeMs)}:${String(e.size)}`}catch{return"0"}};export{m as devVariablesStamp,v as parseDevVariable,f as resolveAdminToken};
1
+ import{statSync as n,readFileSync as i}from"node:fs";import{join as o}from"node:path";import{parseDevVariableEntries as a}from"./DEV_VARS_EXAMPLE_FILE-hBT89IXh.mjs";const v=(t,e)=>{const r=a(t).find(s=>s.key===e);return r===void 0||r.value===""?void 0:r.value},f=t=>{let e;try{e=v(i(o(t,".dev.vars"),"utf8"),"LUNORA_ADMIN_TOKEN")}catch{e=void 0}const r=process.env.LUNORA_ADMIN_TOKEN;return typeof r=="string"&&r!==""&&r!==e&&console.warn("[lunora] LUNORA_ADMIN_TOKEN is exported in this shell but differs from .dev.vars — the local worker only verifies the .dev.vars token, so the studio uses that one."),e},m=t=>{try{const e=n(o(t,".dev.vars"));return`${String(e.ctimeMs)}:${String(e.size)}`}catch{return"0"}};export{m as devVariablesStamp,v as parseDevVariable,f as resolveAdminToken};
@@ -1 +1 @@
1
- import{readdirSync as w,existsSync as g}from"node:fs";import{join as l,relative as p,sep as y,isAbsolute as _,resolve as f,dirname as A}from"node:path";import{readProjectSecurityHeaders as D}from"@lunora/codegen";import{i as d}from"./is-plain-object-CWxHeOY1.mjs";import{w as E,e as S}from"./asset-headers-CPuEX21i.mjs";import u from"./canonicalPath-DrfMiT3U.mjs";import{resolveProjectTarget as j}from"./assertBuildTargetMatches-CqrrwiQ-.mjs";import{findWranglerFile as P,readWranglerJsonc as $}from"./WRANGLER_FILES-UNW-xY5u.mjs";const R=/\[(name|hash|extname|ext|format)(?::(\d+))?\]/gu,b=/[$()*+.?[\\\]^{|}]/gu,H=/\.map$/u,T=8,h=e=>e.replaceAll(b,String.raw`\$&`),x=e=>{let t="",r=0;for(const o of e.matchAll(R)){t+=h(e.slice(r,o.index));const[,s,n]=o;switch(s){case"extname":{t+=String.raw`(?:\.[^/]+)?`;break}case"hash":{t+=String.raw`[\w-]{${n??String(T)}}`;break}case"name":{t+=".*";break}default:t+="[^/]*"}r=o.index+o[0].length}return new RegExp(`^${t}${h(e.slice(r))}$`,"u")},L=(e,t)=>{try{return w(l(e,t),{recursive:!0,withFileTypes:!0}).filter(r=>r.isFile()).map(r=>p(e,l(r.parentPath,r.name)).split(y).join("/"))}catch{return[]}},U=(e,t,r)=>{const o=r.map(s=>x(s));return L(e,t).every(s=>o.some(n=>n.test(s.replace(H,""))))},F=()=>{const e=process.env.CLOUDFLARE_ENV;return e===void 0||e===""?void 0:e},m=(e,t,r,{inherit:o})=>{const s=d(e)?e:void 0,n=d(s?.[r])?s[r]:void 0;if(t===void 0)return n;const i=s?.env,c=d(i)?i[t]:void 0,a=d(c)?c[r]:void 0;return d(a)?a:o?n:void 0},N=(e,t,r)=>S(D(e),m(t,r,"vars",{inherit:!1})?.LUNORA_SECURITY_HEADERS),k=(e,t)=>{const{hashedDirectory:r,hashedNamePatterns:o,outputDirectory:s,publicDirectory:n}=e;if(!(r===void 0||r===""||t!==void 0&&t!=="none")&&!(o!==void 0&&!U(s,r,o)))return n!==void 0&&g(l(n,r))?void 0:r},C=e=>{const t=j(e.projectRoot,e.target);if(t!=="cloudflare")return{reason:`target "${t}" does not serve _headers`,written:!1};const r=e.wranglerPath??P(e.projectRoot),o=r===void 0?void 0:$(r).parsed,s=F(),n=m(o,s,"assets",{inherit:!0});if(e.requireAssetsDirectory){const a=n?.directory;if(typeof a!="string"||r===void 0)return{reason:"wrangler declares no assets.directory",written:!1};const v=_(a)?a:f(A(r),a);if(u(v)!==u(e.outputDirectory))return{reason:`the build output is not wrangler's assets.directory (${a})`,written:!1}}const i=o!==void 0,c=E(e.outputDirectory,{headers:N(f(e.projectRoot,e.schemaDir??"lunora"),o,s),immutableDirectory:i?k(e,n?.not_found_handling):void 0});return!i&&e.hashedDirectory!==void 0&&e.hashedDirectory!==""&&c.warnings.push(`_headers: no long-term caching for ${e.hashedDirectory}/, because ${r===void 0?"no wrangler.jsonc or wrangler.json was found":`${r} could not be read or parsed`} and assets.not_found_handling decides whether that is safe`),{result:c,written:!0}},K=(e,t)=>{const r=C(e);if(r.written){r.result.deferred.length>0&&t.info(`_headers: kept your own ${r.result.deferred.join(", ")} for static assets instead of Lunora's default`);for(const o of r.result.warnings)t.warn(o)}return r};export{K as emitProjectAssetHeaders};
1
+ import{readdirSync as w,existsSync as g}from"node:fs";import{join as l,relative as p,sep as y,isAbsolute as _,resolve as f,dirname as A}from"node:path";import{readProjectSecurityHeaders as D}from"@lunora/codegen";import{i as d}from"./is-plain-object-CWxHeOY1.mjs";import{w as E,e as S}from"./asset-headers-CPuEX21i.mjs";import u from"./canonicalPath-DrfMiT3U.mjs";import{resolveProjectTarget as j}from"./assertBuildTargetMatches-tkKAa5zl.mjs";import{findWranglerFile as P,readWranglerJsonc as $}from"./WRANGLER_FILES-BF8PUjuo.mjs";const R=/\[(name|hash|extname|ext|format)(?::(\d+))?\]/gu,b=/[$()*+.?[\\\]^{|}]/gu,H=/\.map$/u,T=8,h=e=>e.replaceAll(b,String.raw`\$&`),x=e=>{let t="",r=0;for(const o of e.matchAll(R)){t+=h(e.slice(r,o.index));const[,s,n]=o;switch(s){case"extname":{t+=String.raw`(?:\.[^/]+)?`;break}case"hash":{t+=String.raw`[\w-]{${n??String(T)}}`;break}case"name":{t+=".*";break}default:t+="[^/]*"}r=o.index+o[0].length}return new RegExp(`^${t}${h(e.slice(r))}$`,"u")},L=(e,t)=>{try{return w(l(e,t),{recursive:!0,withFileTypes:!0}).filter(r=>r.isFile()).map(r=>p(e,l(r.parentPath,r.name)).split(y).join("/"))}catch{return[]}},U=(e,t,r)=>{const o=r.map(s=>x(s));return L(e,t).every(s=>o.some(n=>n.test(s.replace(H,""))))},F=()=>{const e=process.env.CLOUDFLARE_ENV;return e===void 0||e===""?void 0:e},m=(e,t,r,{inherit:o})=>{const s=d(e)?e:void 0,n=d(s?.[r])?s[r]:void 0;if(t===void 0)return n;const i=s?.env,c=d(i)?i[t]:void 0,a=d(c)?c[r]:void 0;return d(a)?a:o?n:void 0},N=(e,t,r)=>S(D(e),m(t,r,"vars",{inherit:!1})?.LUNORA_SECURITY_HEADERS),k=(e,t)=>{const{hashedDirectory:r,hashedNamePatterns:o,outputDirectory:s,publicDirectory:n}=e;if(!(r===void 0||r===""||t!==void 0&&t!=="none")&&!(o!==void 0&&!U(s,r,o)))return n!==void 0&&g(l(n,r))?void 0:r},C=e=>{const t=j(e.projectRoot,e.target);if(t!=="cloudflare")return{reason:`target "${t}" does not serve _headers`,written:!1};const r=e.wranglerPath??P(e.projectRoot),o=r===void 0?void 0:$(r).parsed,s=F(),n=m(o,s,"assets",{inherit:!0});if(e.requireAssetsDirectory){const a=n?.directory;if(typeof a!="string"||r===void 0)return{reason:"wrangler declares no assets.directory",written:!1};const v=_(a)?a:f(A(r),a);if(u(v)!==u(e.outputDirectory))return{reason:`the build output is not wrangler's assets.directory (${a})`,written:!1}}const i=o!==void 0,c=E(e.outputDirectory,{headers:N(f(e.projectRoot,e.schemaDir??"lunora"),o,s),immutableDirectory:i?k(e,n?.not_found_handling):void 0});return!i&&e.hashedDirectory!==void 0&&e.hashedDirectory!==""&&c.warnings.push(`_headers: no long-term caching for ${e.hashedDirectory}/, because ${r===void 0?"no wrangler.jsonc or wrangler.json was found":`${r} could not be read or parsed`} and assets.not_found_handling decides whether that is safe`),{result:c,written:!0}},K=(e,t)=>{const r=C(e);if(r.written){r.result.deferred.length>0&&t.info(`_headers: kept your own ${r.result.deferred.join(", ")} for static assets instead of Lunora's default`);for(const o of r.result.warnings)t.warn(o)}return r};export{K as emitProjectAssetHeaders};
@@ -0,0 +1 @@
1
+ import{readdirSync as i}from"node:fs";import{i as n}from"./is-plain-object-CWxHeOY1.mjs";import{join as r}from"node:path";const o=["assets","static","_astro"],a=new Set(["_headers","_redirects","_routes.json"]),e=/^[\w.~@%+-]+$/u,l=t=>{if(!n(t)||t.not_found_handling!=="single-page-application")return;const{binding:s}=t;return typeof s=="string"&&s!==""?s:void 0},c=t=>{try{return i(r(t,"public"),{withFileTypes:!0}).filter(s=>e.test(s.name)&&!a.has(s.name)).map(s=>s.isDirectory()?`/${s.name}/*`:`/${s.name}`)}catch{return[]}},A=t=>[...o.map(s=>`/${s}/*`),...c(t)],p=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),_=t=>typeof t=="string"&&t.length>0,g=t=>Array.isArray(t)?t.filter(s=>p(s)):[];export{_ as a,A as b,p as i,g as p,l as s};
@@ -0,0 +1 @@
1
+ import{spawnSync as E}from"node:child_process";import{readdirSync as _,existsSync as m}from"node:fs";import{homedir as u}from"node:os";import{join as s,dirname as a}from"node:path";import{readDevVariablesRecord as L,wranglerDotenvFiles as A}from"./DEV_VARS_EXAMPLE_FILE-hBT89IXh.mjs";const v=[...A(),".env.development",".env.development.local"],l=["CLOUDFLARE_API_TOKEN","CF_API_TOKEN"],f=["CLOUDFLARE_API_KEY","CF_API_KEY"],g=["CLOUDFLARE_EMAIL","CF_EMAIL"],w=new Set([...l,...f,...g]),O=/"loggedIn"\s*:\s*false/u,S=1e4,d=new Map,c=e=>e!==void 0&&e.trim()!=="",D=(e,t)=>[t,e.XDG_CONFIG_HOME,s(t,"Library","Preferences"),s(t,".config"),e.APPDATA===void 0?void 0:s(e.APPDATA,"xdg.config"),s(t,"AppData","Roaming","xdg.config")].filter(o=>c(o)),p=e=>{try{return _(e).length>0}catch{return!1}},C=e=>{for(let t=e;;t=a(t)){const o=s(t,"node_modules","wrangler","bin","wrangler.js");if(m(o))return o;if(a(t)===t)return}},I=(e,t)=>{const o=d.get(e);if(o!==void 0&&Date.now()-o.at<S)return o.loggedOut;const r=C(e);if(r===void 0)return!1;const{stdout:i}=E(process.execPath,[r,"whoami","--json"],{cwd:e,encoding:"utf8",env:{...t,WRANGLER_SEND_METRICS:"false"},stdio:["ignore","pipe","ignore"],timeout:3e3}),n=O.test(i);return d.set(e,{at:Date.now(),loggedOut:n}),n},T=e=>{const t=new Set;for(const o of v){let r;try{r=L(s(e,o))}catch{continue}for(const[i,n]of Object.entries(r??{}))w.has(i)&&c(n)&&t.add(i)}return t},R=(e={})=>{const t=e.env??process.env,o=e.projectRoot===void 0?new Set:T(e.projectRoot),r=n=>c(t[n])||o.has(n);return l.some(n=>r(n))||f.some(n=>r(n))&&g.some(n=>r(n))?!0:D(t,e.home??u()).some(n=>p(s(n,".wrangler","config")))&&(e.projectRoot===void 0||!I(e.projectRoot,t))};export{R as hasCloudflareCredentials};
@@ -0,0 +1 @@
1
+ import{statSync as j,readFileSync as k,existsSync as B,readdirSync as ue}from"node:fs";import{relative as pe,sep as me,isAbsolute as fe,join as E,dirname as $,resolve as ge}from"node:path";import{discoverFlags as he,FLAGS_FILENAME as Se,CAPABILITY_PROBES as Q,COMPANION_BINDING as z,ALL_NOTIFY_CHANNELS as Ee,readBoundServiceBindings as xe,discoverHttpRoutes as ye,discoverNotifyChannels as ve,NOTIFY_FILENAME as Ne,createTargetScope as Te,mayReadCapabilityContext as be,sourceCapabilitySignals as Ce,foldCapabilitySignals as V,capabilitiesUsedBy as Ae}from"@lunora/codegen";import{init as Re}from"es-module-lexer";import{ts as n,Node as m,Project as Z}from"ts-morph";import{discoverAgentInfo as Ie}from"./discoverAgentInfo-pqFMJBtJ.mjs";import{discoverContainerInfo as Oe}from"./discoverContainerInfo-DzXr7Vm3.mjs";import{escapeRegExp as _e}from"./DEV_VARS_EXAMPLE_FILE-hBT89IXh.mjs";import{d as M}from"./discover-info-DC2MrAIM.mjs";import{PACKAGE_SECRETS_REGISTRY as we}from"./PACKAGE_SECRETS_REGISTRY-CPWkw-qE.mjs";import{d as De}from"./queue-info-D38n7YdX.mjs";import{discoverSchemaInfo as Le}from"./discoverSchemaInfo-DRPnqgif.mjs";import{resolveWorkerEntry as Pe,composedEntryDurableObjects as $e,GENERATED_DIRECTORY as _,DURABLE_OBJECT_BINDINGS as Fe,detectExportedDurableObjects as je,detectClassExports as L,isMergedProject as ee}from"./COMPOSED_WORKER_ENTRY-LpLlp-aF.mjs";import{discoverWorkflowInfo as ke}from"./discoverWorkflowInfo-zW7Tt0Tn.mjs";const Be="/api/auth",Me="/.well-known/oauth-protected-resource",Ke="/.well-known/oauth-authorization-server",Ge=String.raw`\/\*[\s\S]*?\*\/`,Ue=String.raw`\/\/[^\n]*`,We=String.raw`"(?:[^"\\\n]|\\.)*"`,Ve=String.raw`'(?:[^'\\\n]|\\.)*'`,He=String.raw`\x60(?:[^\x60\\$]|\\.|\$(?!\{))*\x60`,Ye=new RegExp([Ge,Ue,We,Ve,He].join("|"),"gu"),Xe=/[^\n]/gu,qe=e=>e.replaceAll(Xe," "),Je=e=>e.replaceAll(Ye,t=>t.startsWith("//")||t.startsWith("/*")?qe(t):t),Qe=(e,t)=>{const{error:o,value:s}=M(e,t,Se,he);return o===void 0?{flags:s}:{error:o}},te=(e,t)=>{const o=pe(t,e);return o!==""&&o!==".."&&!o.startsWith(`..${me}`)&&!fe(o)},b="@lunora/replica",h="EventLogDOClient",ze=/\.[cm]?[jt]sx?$/u,H=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],Y=new Map,K=e=>{const{mtimeMs:t}=j(e),o=Y.get(e);if(o?.mtimeMs===t)return o.source;const s=n.createSourceFile(e,k(e,"utf8"),n.ScriptTarget.Latest);return Y.set(e,{mtimeMs:t,source:s}),s},X=new WeakMap,Ze=e=>{const t=X.get(e);if(t!==void 0&&t[0]?.wasForgotten()!==!0)return t;const o=e.getDescendantsOfKind(n.SyntaxKind.Identifier);return X.set(e,o),o},q=e=>n.sys.fileExists(e)?j(e).mtimeMs:-1,J=new Map,et=e=>{const t=n.findConfigFile($(e),i=>n.sys.fileExists(i));if(t===void 0)return{};const o=J.get(t);if(o!==void 0&&[...o.mtimes].every(([i,c])=>q(i)===c))return o.options;const s=n.readJsonConfigFile(t,i=>n.sys.readFile(i)),{options:r}=n.parseJsonSourceFileConfigFileContent(s,n.sys,$(t)),a=new Map([t,...s.extendedSourceFiles??[]].map(i=>[i,q(i)]));return J.set(t,{mtimes:a,options:r}),r},G=(e,t)=>{if(t===b)return;if(!t.startsWith("./")&&!t.startsWith("../")){const a={moduleResolution:n.ModuleResolutionKind.Bundler,...et(e)},i=n.resolveModuleName(t,e,a,n.sys).resolvedModule;return i?.isExternalLibraryImport===!0?void 0:i?.resolvedFileName}const o=E($(e),t.replace(ze,"")),s=H.map(a=>`${o}${a}`),r=H.map(a=>E(o,`index${a}`));return[...s,...r].find(a=>B(a))},tt=e=>{const t=new Map;for(const o of e.statements){if(!n.isImportDeclaration(o)||o.importClause?.phaseModifier===n.SyntaxKind.TypeKeyword||!n.isStringLiteral(o.moduleSpecifier))continue;const s=o.importClause?.namedBindings,r=s!==void 0&&n.isNamedImports(s)?s.elements:[];for(const a of r)a.isTypeOnly||t.set(a.name.text,{module:o.moduleSpecifier.text,name:(a.propertyName??a.name).text})}return t},st=e=>{const t=new Map;for(const o of e.statements){if(!n.isImportDeclaration(o)||o.importClause?.phaseModifier===n.SyntaxKind.TypeKeyword||!n.isStringLiteral(o.moduleSpecifier))continue;const s=o.importClause?.namedBindings;s!==void 0&&n.isNamespaceImport(s)&&t.set(s.name.text,o.moduleSpecifier.text)}return t},w=e=>n.canHaveModifiers(e)&&(n.getModifiers(e)??[]).some(t=>t.kind===n.SyntaxKind.ExportKeyword),ot=e=>n.isVariableStatement(e)?w(e)?e.declarationList.declarations.flatMap(t=>n.isIdentifier(t.name)?[t.name.text]:[]):[]:(n.isClassDeclaration(e)||n.isFunctionDeclaration(e))&&w(e)?e.name===void 0?[]:[e.name.text]:n.isExportDeclaration(e)&&e.moduleSpecifier===void 0&&!e.isTypeOnly&&e.exportClause!==void 0&&n.isNamedExports(e.exportClause)?e.exportClause.elements.map(t=>t.name.text):[],rt=e=>new Set(e.statements.flatMap(t=>ot(t))),nt=(e,t,o)=>{if(n.isIdentifier(e))return t.get(e.text);if(n.isPropertyAccessExpression(e)&&n.isIdentifier(e.expression)){const s=o.get(e.expression.text);return s===void 0?void 0:{module:s,name:e.name.text}}},it=(e,t,o)=>w(e)?e.declarationList.declarations.flatMap(s=>{if(!n.isIdentifier(s.name)||s.initializer===void 0)return[];const r=nt(s.initializer,t,o);return r===void 0?[]:[{exported:s.name.text,module:r.module,name:r.name}]}):[],at=(e,t)=>{const o=e.heritageClauses?.find(r=>r.token===n.SyntaxKind.ExtendsKeyword)?.types[0]?.expression;if(!w(e)||e.name===void 0||o===void 0||!n.isIdentifier(o))return[];const s=t.get(o.text);return s===void 0?[]:[{exported:e.name.text,module:s.module,name:s.name}]},ct=e=>{const t=tt(e),o=st(e);return e.statements.flatMap(s=>{if(n.isVariableStatement(s))return it(s,t,o);if(n.isClassDeclaration(s))return at(s,t);if(!n.isExportDeclaration(s)||s.isTypeOnly)return[];const{exportClause:r,moduleSpecifier:a}=s,i=a!==void 0&&n.isStringLiteral(a)?a.text:void 0;return r===void 0?i===void 0?[]:[{exported:void 0,module:i,name:void 0}]:n.isNamedExports(r)?r.elements.flatMap(c=>{if(c.isTypeOnly)return[];const d=c.name.text,l=(c.propertyName??c.name).text;if(i!==void 0)return[{exported:d,module:i,name:l}];const u=t.get(l);return u===void 0?[]:[{exported:d,module:u.module,name:u.name}]}):[]})},U=(e,t,o,s,r=new Set)=>{const a=JSON.stringify([e,o,[...r]]);if(s.has(a))return!1;s.add(a);const i=K(e),c=ct(i),d=new Set([...r,...rt(i),...c.flatMap(l=>l.exported===void 0?[]:[l.exported])]);return c.some(l=>{if(o!==void 0&&l.exported!==void 0&&l.exported!==o||l.exported!==void 0&&r.has(l.exported))return!1;if(l.exported===void 0){const g=o??(l.module===b?t:void 0);if(g!==void 0&&d.has(g))return!1}const u=l.exported===void 0?o:l.name;if(l.module===b)return u===void 0||u===t;const v=G(e,l.module);return v!==void 0&&U(v,t,u,s,l.exported===void 0?d:r)})},F=(e,t)=>Ze(e).some(o=>{const s=o.getParent();return o.getText()!==t||m.isNamespaceImport(s)||m.isPropertyAccessExpression(s)&&s.getNameNode()===o||m.isQualifiedName(s)&&s.getRight()===o?!1:m.isPropertyAccessExpression(s)?s.getName()===h:m.isQualifiedName(s)?!m.isTypeReference(s.getParent())&&s.getRight().getText()===h:!0}),dt=e=>{const[t]=e.getArguments();return e.getExpression().getKind()===n.SyntaxKind.ImportKeyword&&t!==void 0&&(m.isStringLiteral(t)||m.isNoSubstitutionTemplateLiteral(t))&&t.getLiteralValue()===b},lt=e=>{const t=e.getPropertyNameNode();if(t===void 0)return e.getNameNode().getText();const o=m.isComputedPropertyName(t)?t.getExpression():t;return m.isStringLiteral(o)||m.isNoSubstitutionTemplateLiteral(o)?o.getLiteralValue():t.getText()},ut=e=>{let t=e,o=!1;for(let r=e.getParent();m.isParenthesizedExpression(r)||m.isAwaitExpression(r);r=t.getParent())o||=m.isAwaitExpression(r),t=r;if(!o)return!0;const s=t.getParent();if(m.isVariableDeclaration(s)){const r=s.getNameNode();return!m.isObjectBindingPattern(r)||r.getElements().some(a=>a.getDotDotDotToken()!==void 0||lt(a)===h)}return m.isPropertyAccessExpression(s)&&s.getExpression()===t?s.getName()===h:!0},pt=(e,t)=>K(e).statements.some(o=>n.isExportDeclaration(o)&&o.moduleSpecifier!==void 0&&n.isStringLiteral(o.moduleSpecifier)&&o.moduleSpecifier.text===b&&o.exportClause!==void 0&&n.isNamespaceExport(o.exportClause)&&o.exportClause.name.text===t),mt=e=>e.getImportDeclarations().some(t=>{const o=t.getNamespaceImport(),s=t.isTypeOnly()?[]:t.getNamedImports().filter(d=>!d.isTypeOnly()),r=s.some(d=>d.getNameNode().getText()===h),a=s.filter(d=>F(e,(d.getAliasNode()??d.getNameNode()).getText())),i=o!==void 0&&F(e,o.getText());if(!r&&!i&&a.length===0)return!1;const c=G(e.getFilePath(),t.getModuleSpecifierValue());return c===void 0?!1:(r||i)&&U(c,h,h,new Set)||a.some(d=>pt(c,d.getNameNode().getText()))}),se=e=>{const t=e.getImportDeclarations().filter(o=>o.getModuleSpecifierValue()===b&&!o.isTypeOnly());return t.some(o=>o.getNamedImports().some(s=>!s.isTypeOnly()&&s.getNameNode().getText()===h))||t.some(o=>{const s=o.getNamespaceImport();return s!==void 0&&F(e,s.getText())})||e.getExportDeclarations().some(o=>o.getModuleSpecifierValue()===b&&!o.isTypeOnly()&&o.getNamedExports().some(s=>!s.isTypeOnly()&&s.getNameNode().getText()===h))||mt(e)||e.getDescendantsOfKind(n.SyntaxKind.CallExpression).some(o=>dt(o)&&ut(o))},ft=e=>{const t=[],o=s=>{if(n.isImportDeclaration(s)&&s.importClause?.phaseModifier!==n.SyntaxKind.TypeKeyword&&n.isStringLiteral(s.moduleSpecifier))t.push(s.moduleSpecifier.text);else if(n.isExportDeclaration(s)&&!s.isTypeOnly&&s.moduleSpecifier!==void 0&&n.isStringLiteral(s.moduleSpecifier))t.push(s.moduleSpecifier.text);else if(n.isCallExpression(s)&&s.expression.kind===n.SyntaxKind.ImportKeyword){const[r]=s.arguments;r!==void 0&&(n.isStringLiteral(r)||n.isNoSubstitutionTemplateLiteral(r))&&t.push(r.text)}n.forEachChild(s,o)};return o(e),t},gt=new Set([".cjs",".cts",".js",".jsx",".mjs",".mts",".ts",".tsx"]),ht=new Set([".git",".lunora-cache",".wrangler","dist",_,"node_modules"]),St=["lunora","src"],Et=/\benv\s*\.\s*DB\b/,xt=/\benv\s*\.\s*AI\b/,oe=["ai","aiSearch","analytics","analyticsSql","artifacts","browser","hyperdrive","images","kv","mail","notify","payments","pipelines","r2sql","scheduler","storage","x402"],re=e=>`uses${e.charAt(0).toUpperCase()}${e.slice(1)}`,ne=[["usesAuth","@lunora/auth"],["usesCimdWorkers","@lunora/auth/cimd/workers"],["usesX402Charge","@lunora/x402/charge"],["usesPaymentAutumn","@lunora/payment/autumn"],["usesPaymentCreem","@lunora/payment/creem"],["usesPaymentDodopayments","@lunora/payment/dodopayments"],["usesPaymentPolar","@lunora/payment/polar"],["usesPaymentStripe","@lunora/payment/stripe"]],ie=[...oe.map(e=>[re(e),Q[e].moduleSpecifier]),...ne].toSorted(([e],[t])=>e.localeCompare(t)),yt=[["usesNotifyFcm","@lunora/notify:fcm"],["usesNotifyFcmTokenSource","@lunora/notify:fcmTokenSource"],["usesNotifyWebPush","@lunora/notify:webPush"],["hostsShardRegistry","@lunora/do:shardRegistry"],["hostsEventLog","@lunora/replica:eventLog"],["usesEventLogClient","@lunora/replica:eventLogClient"],["usesRequestSecretTool","@lunora/agent:requestSecretTool"]],vt=["@lunora/agent","@lunora/agent/sandbox"],ae=new RegExp(String.raw`["'\x60](?:${[...ie.map(([,e])=>e),...vt,b].map(e=>_e(e)).join("|")})["'\x60]`,"u"),p=e=>{const{contextProperty:t,moduleSpecifier:o}=Q[e];return t===void 0?`${o} is imported`:`${o} is imported or ctx.${t} is read`},Nt="STRIPE_SECRET_KEY + STRIPE_WEBHOOK_SECRET (Stripe) or POLAR_ACCESS_TOKEN + POLAR_WEBHOOK_SECRET (Polar)",Tt=/\b(authBasePath|basePath):\s*(["'`])(\/[^"'`$\s]*)\2/gu,bt=/["']@lunora\/auth(?:\/[^"']*)?["']/u,Ct=/[Bb]asePath/u,At=e=>{const t=new Set;for(const o of e){const s=k(o,"utf8");if(!Ct.test(s))continue;const r=Je(s),a=bt.test(r);for(const[,i,,c]of r.matchAll(Tt)){const d=c?.endsWith("/")===!0?c.slice(0,-1):c??"";d!==""&&(i==="authBasePath"||a)&&t.add(d)}}return t.size===0?[Be]:[...t].toSorted((o,s)=>o.localeCompare(s))},Rt=(e,t,o,s)=>{const{error:r,value:a}=M(e,t,void 0,ye);if(r!==void 0)return;const i=o?[...At(s),Me,Ke].map(c=>`${c}/*`):[];return[...(a??[]).map(c=>c.path),...i]},It=/\bfrom\s+["']\.{1,2}\//u,ce=(e,t)=>{let o;try{o=ue(e,{withFileTypes:!0})}catch{return}for(const s of o){if(s.isDirectory()){ht.has(s.name)||ce(E(e,s.name),t);continue}const r=s.name.lastIndexOf(".");r!==-1&&gt.has(s.name.slice(r))&&t.push(E(e,s.name))}},Ot=(e,t,o)=>{const s=xe(e,t);return o?{...s,services:s.services.filter(r=>r.binding!==z)}:s},_t=(e,t,o)=>{const{info:s}=Le(e,t,o);return{jurisdiction:s?.jurisdiction,needsD1:s?.hasD1GlobalTable??!1}};let P;const wt=e=>{const t=ge(e);return P?.root!==t&&(P={project:new Z({compilerOptions:{allowJs:!0},skipAddingFilesFromTsConfig:!0}),root:t}),P.project},Dt=(e,t,o)=>{e.getSourceFile(t)?.getFullText()!==o&&e.createSourceFile(t,o,{overwrite:!0})},Lt=(e,t)=>{for(const o of e.getSourceFiles())t.has(o)||e.removeSourceFile(o)},Pt=(e,t,o)=>{const s=E(e,o),r=wt(e),a=[],i=new Set,c=[],d=[],l=Te();let u=!1,v=!1;for(const f of t){const S=E(e,f);if(!B(S)||!j(S).isDirectory())continue;const O=[];ce(S,O);for(const A of O){i.add(A);const x=k(A,"utf8"),T=te(A,s);u||=xt.test(x),v||=Et.test(x),(ae.test(x)||x.includes(h)||T&&(be(x)||It.test(x)))&&(Dt(r,A,x),a.push({file:A,inLunora:T}))}}Lt(r,new Set(a.map(({file:f})=>r.getSourceFileOrThrow(f))));for(const{file:f,inLunora:S}of a)(S?c:d).push(Ce(r.getSourceFileOrThrow(f),l));const g=V(c),C=V([g,...d]),I=new Set([...C.valueImports,...C.dynamicImports]),N=Ae({contextReads:g.contextReads,valueImports:I});return{...Object.fromEntries([...oe.map(f=>[re(f),N.has(f)]),...ne.map(([f,S])=>[f,I.has(S)])]),needsD1:v,usesEventLogClient:a.some(({file:f})=>se(r.getSourceFileOrThrow(f))),usesRequestSecretTool:g.requestSecretTool,usesAi:N.has("ai")||u,usesBrowser:N.has("browser")||g.sandboxTools.usesSandboxBrowser,usesWorkerLoader:g.sandboxTools.usesSandboxLoader,scannedFiles:i}},$t=(e,t,o)=>[...e.map(s=>s.exported?`${s.bindingName}/${s.className} (container "${s.exportName}" declared and exported)`:`hint: container "${s.exportName}" is declared but ${s.className} is not exported by the worker entry — add \`export * from "./lunora/_generated/containers"\``),...t.map(s=>s.exported?`exports.${s.className} (workflow "${s.exportName}" declared and exported)`:`hint: workflow "${s.exportName}" is declared but ${s.className} is not exported by the worker entry — add \`export * from "./lunora/_generated/workflows"\``),...o.map(s=>s.exported?`exports.${s.className} (agent "${s.exportName}" declared and exported)`:`hint: agent "${s.exportName}" is declared but ${s.className} is not exported by the worker entry — add \`export * from "./lunora/_generated/agents"\``)],Ft=(e,t,o)=>[[e.usesAi,`AI (${p("ai")}, env.AI is used, or an agent is declared)`],[e.usesAuth&&!t.has("SessionDO"),"hint: @lunora/auth is imported; its tables are D1-backed by default. For DO-backed auth (what @better-auth/scim needs), pass `namespace` to .auth() and export the generated auth DO class"],[e.usesScheduler&&!t.has("SchedulerDO"),`hint: ${p("scheduler")}, but no SchedulerDO is exported by the worker entry`],[e.usesStorage,`hint: ${p("storage")}; add an r2_buckets binding (bucket binding names are user-defined)`],[e.usesMail,`hint: ${p("mail")}; set RESEND_API_KEY in .dev.vars (obtain at https://resend.com/api-keys)`],[e.usesPayments,`hint: ${p("payments")}; set the provider secrets in .dev.vars — ${Nt}`],[e.usesBrowser,`browser (${p("browser")}, or a sandbox browserTool imported in lunora/) — self-describing { binding: BROWSER }`],[e.usesImages,`images (${p("images")}) — self-describing { binding: IMAGES }`],[e.usesAnalytics,`analytics_engine_datasets (${p("analytics")}) — self-describing { binding: ANALYTICS, dataset }`],[e.usesWorkerLoader,"worker_loaders (jsCodeTool imported in lunora/) — self-describing { binding: LOADER }"],[e.usesAiSearch,`ai_search_namespaces (${p("aiSearch")}) — self-describing { binding: AI_SEARCH, namespace: "default" }; remote-only, so \`lunora dev\` reaches the deployed AI Search service`],[e.usesAnalyticsSql,`analytics (${p("analyticsSql")}) — self-describing { binding: ANALYTICS_SQL }; needs wrangler >= 4.145.0, and is remote-only, so \`lunora dev\` queries the account's live analytics`],[e.usesKv,o.jurisdiction===void 0?`kv_namespaces (${p("kv")}) — { binding: KV } with no id; wrangler creates the namespace on the first deploy`:`hint: ${p("kv")} and the schema pins "${o.jurisdiction}"; create the namespace with --jurisdiction ${o.jurisdiction} and add a kv_namespaces binding ({ binding, id })`],[e.usesHyperdrive,`hyperdrive (${p("hyperdrive")}) — { binding: HYPERDRIVE } with a placeholder id; dev uses an embedded Postgres and \`lunora deploy\` creates the config`],[e.usesPipelines,`hint: ${p("pipelines")}; run 'wrangler pipelines create <name>' and add a 'pipelines' binding ({ binding, stream }) — the pipeline resource can't be auto-provisioned`],[e.usesArtifacts,o.jurisdiction===void 0?`artifacts (${p("artifacts")}) — { binding: ARTIFACTS, namespace }`:`hint: ${p("artifacts")}; the schema pins data to "${o.jurisdiction}", so create the namespace in that jurisdiction first and add { binding: ARTIFACTS, namespace } yourself — \`lunora deploy\` then checks it (a first create() in dev would make it unrestricted)`],[e.usesX402Charge,"hint: @lunora/x402/charge is imported; set the recipient wallet address as a [vars] entry (the var name is yours to choose) and pass it to the charge config — the x402 facilitator settles USDC to that address"],[e.usesX402,`hint: ${p("x402")} (ActionCtx-only, spends real funds); add a secrets_store_secrets[] binding for the agent wallet key (name it to match signer.secretName) and pair the pay rail with a spend policy — ctx.secrets reads a Secrets Store binding, not .dev.vars, so the key can't be auto-provisioned`]].filter(([r])=>r).map(([,r])=>r),jt=(e,t,o,s=[],r=[],a=[])=>{const i=new Set(e.map(d=>d.className)),c=e.map(d=>`${d.binding}/${d.className} (exported by worker entry)`);return t.needsD1&&c.push("DB (.global() table declared)"),c.push(...$t(s,r,a),...Ft(o,i,t)),c},kt=(e,t)=>e.some(o=>o.binding==="SHARD_REGISTRY")||ee(t)&&B(E(t,"shardRegistry.ts")),Bt=(e,t,o)=>{const s=new Z({compilerOptions:{allowJs:!0},skipAddingFilesFromTsConfig:!0}),r=[e],a=new Set;for(let i=r.pop();i!==void 0;i=r.pop()){if(a.has(i))continue;a.add(i);const c=K(i),d=c.text;if((ae.test(d)||d.includes(h))&&se(s.createSourceFile(i,d,{overwrite:!0})))return!0;for(const l of ft(c)){const u=G(i,l);u!==void 0&&!t.has(u)&&!te(u,o)&&r.push(u)}}return!1},Mt=e=>!e.composed&&e.path!==void 0&&U(e.path,"EventLogDO",void 0,new Set),Kt=e=>({usesNotifyFcm:e?.fcm==="env",usesNotifyFcmTokenSource:e?.fcm==="ownToken",usesNotifyWebPush:e?.hasWebPush??!1}),ss=async e=>{await Re;const t=e.schemaDir??"lunora",o=e.scanDirs??St,s=()=>Pt(e.projectRoot,o,t),{scannedFiles:r,...a}=e.cache===void 0?s():e.cache.memo(`capabilities:${e.projectRoot}:${t}:${o.join(",")}`,s),i=Pe(e.projectRoot);let c;i.composed?c=$e(E(e.projectRoot,t,_)).map(W=>({binding:Fe[W],className:W})):c=i.path===void 0?[]:je(i.path);const d=_t(e.projectRoot,t,e.cache),l={...d,needsD1:a.needsD1||d.needsD1},u=L(i,Oe(e.projectRoot,t,e.cache).containers,"containers"),v=L(i,ke(e.projectRoot,t).workflows,"workflows"),g=L(i,Ie(e.projectRoot,t).agents,"agents"),C={...a,usesAi:a.usesAi||g.length>0},I=[...De(e.projectRoot,t).queues],{flags:N}=Qe(e.projectRoot,t),D=M(e.projectRoot,t,Ne,ve),f=N?.provider==="flagship"&&N.mode==="binding"?N.bindingName:void 0,S=E(e.projectRoot,t,_),O=kt(c,S),A=Mt(i),x=!i.composed&&i.path!==void 0&&Bt(i.path,r,S),T=jt(c,l,C,u,v,g);!i.composed&&ee(E(e.projectRoot,t,_))&&!c.some(y=>y.className==="LunoraDO")&&T.push("hint: durableObjects.merge is set, but the worker entry exports no LunoraDO — export one built with mergeDurableObjects, or the classes stay separate"),f!==void 0&&T.push(`hint: lunora/flags.ts uses Flagship in binding mode; add a flagship binding ({ binding: "${f}", app_id }) — the app_id can't be auto-provisioned`);const R=Ot(e.projectRoot,t,e.skipCompanion===!0),de=R.error===void 0?R.services:void 0;R.error!==void 0&&T.push(`hint: lunora.config \`services\` not reconciled — ${R.error}`),T.push(...R.services.map(y=>y.binding===z?`${y.binding} → ${y.worker} (studio.companion)`:`${y.binding} → ${y.worker} (lunora.config services.${y.name})`));const le=Rt(e.projectRoot,t,C.usesAuth,r);return{...C,usesEventLogClient:C.usesEventLogClient||x,agents:g,containers:u,durableObjects:c,flagshipBinding:f,...l.jurisdiction===void 0?{}:{jurisdiction:l.jurisdiction},needsD1:l.needsD1,queues:I,services:de,signals:T,usesFlags:N!==void 0,...Kt(D.error===void 0?D.value:Ee),hostsEventLog:A,hostsShardRegistry:O,workerRoutes:le,workflows:v}},os=e=>[...ie,...yt].filter(([t,o])=>e[t]&&we[o]!==void 0).map(([,t])=>t);export{ss as inferLunoraBindings,os as secretSourcesFromBindings};
@@ -1 +1 @@
1
- import{isAbsolute as p,dirname as m,resolve as h}from"node:path";import{applyModify as l}from"./applyModify-DKP2l6S9.mjs";import{hasCloudflareCredentials as u}from"./hasCloudflareCredentials-Bak5w1_6.mjs";import{withheldBindings as g,writeDevConfig as w}from"./describeWithheld-CbyzZjZF.mjs";import{readWranglerJsonc as v}from"./WRANGLER_FILES-UNW-xY5u.mjs";const C=(e,n)=>{const{parsed:t,text:c}=v(e),o=t?.build,r=g(t,n.hasCredentials??(()=>u({projectRoot:n.projectRoot}))),s=typeof o?.command=="string"&&o.command!==""&&!(typeof o.cwd=="string"&&p(o.cwd));if(!s&&r.length===0)return{configPath:e,withheld:r};const d=m(e);let i=c;for(const{kind:f}of r)i=l(i,[f],void 0);s&&(i=l(i,["build","cwd"],h(d,typeof o.cwd=="string"?o.cwd:".")));const a=w(d,"service",i);return{cleanup:a.cleanup,configPath:a.configPath,withheld:r}},x=(e,n)=>{const t=e.map(o=>C(o,n)),c=t.flatMap(o=>o.cleanup===void 0?[]:[o.cleanup]);return{cleanup:()=>{for(const o of c)o()},configPaths:t.map(o=>o.configPath),withheld:t.flatMap(o=>o.withheld)}};export{x as materializeServiceDevConfigs};
1
+ import{isAbsolute as p,dirname as m,resolve as h}from"node:path";import{applyModify as l}from"./applyModify-DKP2l6S9.mjs";import{hasCloudflareCredentials as u}from"./hasCloudflareCredentials-ByCrwaLT.mjs";import{withheldBindings as g,writeDevConfig as w}from"./describeWithheld-CbyzZjZF.mjs";import{readWranglerJsonc as v}from"./WRANGLER_FILES-BF8PUjuo.mjs";const C=(e,n)=>{const{parsed:t,text:c}=v(e),o=t?.build,r=g(t,n.hasCredentials??(()=>u({projectRoot:n.projectRoot}))),s=typeof o?.command=="string"&&o.command!==""&&!(typeof o.cwd=="string"&&p(o.cwd));if(!s&&r.length===0)return{configPath:e,withheld:r};const d=m(e);let i=c;for(const{kind:f}of r)i=l(i,[f],void 0);s&&(i=l(i,["build","cwd"],h(d,typeof o.cwd=="string"?o.cwd:".")));const a=w(d,"service",i);return{cleanup:a.cleanup,configPath:a.configPath,withheld:r}},x=(e,n)=>{const t=e.map(o=>C(o,n)),c=t.flatMap(o=>o.cleanup===void 0?[]:[o.cleanup]);return{cleanup:()=>{for(const o of c)o()},configPaths:t.map(o=>o.configPath),withheld:t.flatMap(o=>o.withheld)}};export{x as materializeServiceDevConfigs};
@@ -0,0 +1 @@
1
+ import{basename as f}from"node:path";import{inferLunoraBindings as g}from"./inferLunoraBindings-Biq1OW9V.mjs";import{LUNORA_TAG as a}from"./LUNORA_TAG-DQTGPqcJ.mjs";import{applyWranglerBindings as $}from"./reconcileWranglerBindings-D7mXDfAe.mjs";import{planWranglerBindings as m}from"./collectExportGaps-BYo3bcXi.mjs";import{reconcileWranglerCompatibilityDate as w}from"./reconcileWranglerCompatibilityDate-Cj94osA-.mjs";import{reconcileWranglerCrons as h,describePreservedCrons as l}from"./describePreservedCrons-i5XT6rtl.mjs";const s=async e=>m(e.projectRoot,await g({cache:e.cache,projectRoot:e.projectRoot,schemaDir:e.schemaDir}),{target:e.target}),B=async(e,i,r)=>{try{const n=$(e.projectRoot,await s(e)),t=n.wranglerPath??"wrangler.jsonc";if(n.added.length>0&&i.info?.(`${a} inferred bindings → ${n.added.join(", ")} (written to ${t})`),n.updated.length>0&&i.info?.(`${a} updated bindings → ${n.updated.join(", ")} (written to ${t})`),n.devConfig!==void 0){const{added:o,path:c,updated:p}=n.devConfig;i.info?.(`${a} dev sidecar bindings → ${[...o,...p].join(", ")} (written to ${c})`)}for(const o of n.warnings)i.warn(`${a} ${o}`);n.exportGaps.length>0&&r?.(n.exportGaps)}catch(n){const t=n instanceof Error?n.message:String(n);i.warn(`${a} binding inference skipped: ${t}`)}},E=async e=>{try{const{added:i,devConfig:r,updated:n}=await s(e),t=r===void 0?[]:[...r.added,...r.updated].map(o=>`${f(r.path)} ${o}`);return[...new Set([...i,...n,...t])]}catch{return[]}},d=new Map,P=(e,i,r)=>{try{const n=h(e,i);n.changed&&r.info?.(`${a} synced ${i.length.toFixed(0)} cron trigger(s) into ${n.wranglerPath??"wrangler.jsonc"}`);for(const c of n.warnings)r.warn(`${a} ${c}`);const t=n.preserved.join("\0"),o=l(n.preserved);o!==void 0&&(n.changed||d.get(e)!==t)&&r.info?.(`${a} ${o}`),d.set(e,t)}catch(n){const t=n instanceof Error?n.message:String(n);r.warn(`${a} cron trigger sync skipped: ${t}`)}try{const n=w(e);n.changed&&r.info?.(`${a} bumped compatibility_date to ${n.date??"unknown"} (Workers Cache enabled) → ${n.wranglerPath??"wrangler.jsonc"}`)}catch(n){const t=n instanceof Error?n.message:String(n);r.warn(`${a} compatibility date sync skipped: ${t}`)}};export{E as pendingBindingChanges,B as reconcileBindingsSafely,P as reconcileWranglerExtras};
@@ -13,23 +13,6 @@ interface DiscoveryCache {
13
13
  memo: <T>(key: string, compute: () => T) => T;
14
14
  }
15
15
  declare const createDiscoveryCache: () => DiscoveryCache;
16
- /**
17
- * Placeholder `database_id` written for an auto-provisioned `DB` binding. It is
18
- * intentionally not a valid id so a deploy can't silently target the wrong
19
- * database; reconciliation warns the user to replace it (see the D1 warning in
20
- * `reconcileWranglerBindings`).
21
- *
22
- * Kept apart from `reconcile-bindings` so a module that only needs the string
23
- * (`celld-config`, reached from `@lunora/config/cli` through the driver
24
- * registry) does not pull codegen and ts-morph into every CLI start.
25
- */
26
- declare const D1_PLACEHOLDER_ID = "<replace-with-d1-create-id>";
27
- /**
28
- * The `id` reconcile writes on a Hyperdrive binding it adds, and the one the `hyperdrive`
29
- * registry item ships: wrangler requires a string, and `lunora dev` serves the binding from an
30
- * embedded Postgres whatever it is. `lunora deploy` swaps in a real id.
31
- */
32
- declare const HYPERDRIVE_PLACEHOLDER_ID = "<replace-with-hyperdrive-create-id>";
33
16
  /** One filterable Vectorize metadata property a schema declares. */
34
17
  interface VectorMetadataDeclaration {
35
18
  /** The vector index the property belongs to. */
@@ -335,4 +318,21 @@ declare const inferLunoraBindings: (options: InferOptions) => Promise<InferredBi
335
318
  * ({@link SECRET_SOURCE_FLAGS}), keeping only sources that carry secrets.
336
319
  */
337
320
  declare const secretSourcesFromBindings: (bindings: InferredBindings) => string[];
338
- export { COMPOSED_WORKER_ENTRY as C, DiscoveryCache as D, GENERATED_CLASS_MODULES as G, HYPERDRIVE_PLACEHOLDER_ID as H, InferOptions as I, MERGED_DURABLE_OBJECTS_MODULE as M, SchemaInfo as S, D1_PLACEHOLDER_ID as a, DURABLE_OBJECT_BINDINGS as b, DiscoverSchemaInfoResult as c, GENERATED_MODULE_DURABLE_OBJECTS as d, GeneratedClassModule as e, InferredAgent as f, InferredBindings as g, InferredContainer as h, InferredWorkflow as i, createDiscoveryCache as j, discoverSchemaInfo as k, inferLunoraBindings as l, isMergedProject as m, isMergedRoleModule as n, secretSourcesFromBindings as s };
321
+ /**
322
+ * Placeholder `database_id` written for an auto-provisioned `DB` binding. It is
323
+ * intentionally not a valid id so a deploy can't silently target the wrong
324
+ * database; reconciliation warns the user to replace it (see the D1 warning in
325
+ * `reconcileWranglerBindings`).
326
+ *
327
+ * Kept apart from `reconcile-bindings` so a module that only needs the string
328
+ * (`celld-config`, reached from `@lunora/config/cli` through the driver
329
+ * registry) does not pull codegen and ts-morph into every CLI start.
330
+ */
331
+ declare const D1_PLACEHOLDER_ID = "<replace-with-d1-create-id>";
332
+ /**
333
+ * The `id` reconcile writes on a Hyperdrive binding it adds, and the one the `hyperdrive`
334
+ * registry item ships: wrangler requires a string, and `lunora dev` serves the binding from an
335
+ * embedded Postgres whatever it is. `lunora deploy` swaps in a real id.
336
+ */
337
+ declare const HYPERDRIVE_PLACEHOLDER_ID = "<replace-with-hyperdrive-create-id>";
338
+ export { COMPOSED_WORKER_ENTRY as C, DiscoveryCache as D, GeneratedClassModule as G, HYPERDRIVE_PLACEHOLDER_ID as H, InferredBindings as I, MERGED_DURABLE_OBJECTS_MODULE as M, SchemaInfo as S, D1_PLACEHOLDER_ID as a, DURABLE_OBJECT_BINDINGS as b, DiscoverSchemaInfoResult as c, GENERATED_CLASS_MODULES as d, GENERATED_MODULE_DURABLE_OBJECTS as e, InferOptions as f, InferredAgent as g, InferredContainer as h, InferredWorkflow as i, createDiscoveryCache as j, discoverSchemaInfo as k, inferLunoraBindings as l, isMergedProject as m, isMergedRoleModule as n, secretSourcesFromBindings as s };