@lunora/vite 1.0.0-alpha.245 → 1.0.0-alpha.247

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,3 +1,3 @@
1
- import{createRequire as i}from"node:module";import{cloudflare as l}from"@cloudflare/vite-plugin";import{detectAgentRules as s,claimAgentRulesHint as u,AGENT_RULES_HINT as c,detectFramework as f,resolveTargetOrThrow as d,isRunnableTarget as m,runnableTargetIds as p}from"@lunora/config";import{GENERATED_CLASS_MODULES as ar,detectFramework as ir}from"@lunora/config";import g from"@visulima/vite-overlay";import{l as a}from"./packem_shared/log-DE48L4Oz.mjs";import{r as S,c as v}from"./packem_shared/codegen-plugin-CnF5a3-x.mjs";import w from"./packem_shared/containerLogsPlugin-CWkqSCL3.mjs";import R from"./packem_shared/devStatePlugin-CcFV-eBl.mjs";import h from"./packem_shared/devVariablesPlugin-DY_bJXsX.mjs";import{frameworkComposePlugin as k}from"./packem_shared/CLASS_A_WIRING-B4-x5Aws.mjs";import{CLASS_A_WIRING as sr,LUNORA_WORKER_VIRTUAL_ID as ur,buildWorkerEntrySource as cr,isAutoComposable as fr}from"./packem_shared/CLASS_A_WIRING-B4-x5Aws.mjs";import P from"./packem_shared/logStreamPlugin-DtOu5VX8.mjs";import{proxyCheckPlugin as A}from"./packem_shared/checkLunoraProxy-C9M8c5eS.mjs";import{checkLunoraProxy as mr}from"./packem_shared/checkLunoraProxy-C9M8c5eS.mjs";import{remoteBindingsPlugin as E}from"./packem_shared/planViteRemoteBindings-E3GdC6pY.mjs";import{planViteRemoteBindings as gr,withRemoteBindings as Sr}from"./packem_shared/planViteRemoteBindings-E3GdC6pY.mjs";import{lunoraSolutionFinders as T}from"./packem_shared/lunoraSolutionFinder--J0x2mAM.mjs";import{lunoraSolutionFinder as wr}from"./packem_shared/lunoraSolutionFinder--J0x2mAM.mjs";import{studioPlugin as _}from"./packem_shared/STUDIO_PATH-UztnV2ca.mjs";import{STUDIO_PATH as hr,buildStudioUrl as kr}from"./packem_shared/STUDIO_PATH-UztnV2ca.mjs";import{withWorkerStartupHint as x}from"./packem_shared/WORKER_STARTUP_HINT-COlRTY32.mjs";import{WORKER_STARTUP_HINT as Ar,augmentWorkerStartupError as Er,isWorkerEntryEvalError as Tr}from"./packem_shared/WORKER_STARTUP_HINT-COlRTY32.mjs";import{wranglerValidatorPlugin as O}from"./packem_shared/wranglerValidatorPlugin-BdKLAEoq.mjs";import{default as xr}from"./packem_shared/LUNORA_API_UPDATED_EVENT-CO2Rv2re.mjs";import{reconcileWranglerCrons as br}from"@lunora/config/cloudflare";const b=o=>({apply:"serve",configureServer(r){return()=>{s(o.projectRoot).installed||!u()||r.config.logger.warn(`
1
+ import{createRequire as i}from"node:module";import{cloudflare as l}from"@cloudflare/vite-plugin";import{detectAgentRules as s,claimAgentRulesHint as u,AGENT_RULES_HINT as c,detectFramework as f,resolveTargetOrThrow as d,isRunnableTarget as m,runnableTargetIds as p}from"@lunora/config";import{GENERATED_CLASS_MODULES as ar,detectFramework as ir}from"@lunora/config";import g from"@visulima/vite-overlay";import{l as a}from"./packem_shared/log-DE48L4Oz.mjs";import{r as S,c as v}from"./packem_shared/codegen-plugin-BqoP2XfZ.mjs";import w from"./packem_shared/containerLogsPlugin-CWkqSCL3.mjs";import R from"./packem_shared/devStatePlugin-CcFV-eBl.mjs";import h from"./packem_shared/devVariablesPlugin-DY_bJXsX.mjs";import{frameworkComposePlugin as k}from"./packem_shared/CLASS_A_WIRING-B4-x5Aws.mjs";import{CLASS_A_WIRING as sr,LUNORA_WORKER_VIRTUAL_ID as ur,buildWorkerEntrySource as cr,isAutoComposable as fr}from"./packem_shared/CLASS_A_WIRING-B4-x5Aws.mjs";import P from"./packem_shared/logStreamPlugin-DtOu5VX8.mjs";import{proxyCheckPlugin as A}from"./packem_shared/checkLunoraProxy-C9M8c5eS.mjs";import{checkLunoraProxy as mr}from"./packem_shared/checkLunoraProxy-C9M8c5eS.mjs";import{remoteBindingsPlugin as E}from"./packem_shared/planViteRemoteBindings-E3GdC6pY.mjs";import{planViteRemoteBindings as gr,withRemoteBindings as Sr}from"./packem_shared/planViteRemoteBindings-E3GdC6pY.mjs";import{lunoraSolutionFinders as T}from"./packem_shared/lunoraSolutionFinder--J0x2mAM.mjs";import{lunoraSolutionFinder as wr}from"./packem_shared/lunoraSolutionFinder--J0x2mAM.mjs";import{studioPlugin as _}from"./packem_shared/STUDIO_PATH-UztnV2ca.mjs";import{STUDIO_PATH as hr,buildStudioUrl as kr}from"./packem_shared/STUDIO_PATH-UztnV2ca.mjs";import{withWorkerStartupHint as x}from"./packem_shared/WORKER_STARTUP_HINT-COlRTY32.mjs";import{WORKER_STARTUP_HINT as Ar,augmentWorkerStartupError as Er,isWorkerEntryEvalError as Tr}from"./packem_shared/WORKER_STARTUP_HINT-COlRTY32.mjs";import{wranglerValidatorPlugin as O}from"./packem_shared/wranglerValidatorPlugin-BdKLAEoq.mjs";import{default as xr}from"./packem_shared/LUNORA_API_UPDATED_EVENT-CO2Rv2re.mjs";import{reconcileWranglerCrons as br}from"@lunora/config/cloudflare";const b=o=>({apply:"serve",configureServer(r){return()=>{s(o.projectRoot).installed||!u()||r.config.logger.warn(`
2
2
  ${a(c)}
3
3
  `)}},name:"lunora:agent-rules-hint"}),y=o=>({async config(r,t){t.isPreview!==!0&&await S(o,{info:e=>{console.info(e)},warn:e=>{console.warn(e)}})},enforce:"pre",name:"lunora:bindings-provision"}),L=()=>({}),W={astro:"Astro",none:"standalone (SPA / SSR-less)",nuxt:"Nuxt","react-router":"React Router","solid-start":"SolidStart",sveltekit:"SvelteKit","tanstack-start":"TanStack Start","tanstack-start-solid":"TanStack Start (Solid)",vinext:"Next.js on Vite (vinext)"},D=o=>{const r=W[o.framework];return o.framework==="none"?a("no meta-framework detected — running standalone."):o.class==="B"?a(`detected ${r} — composition is handled by the framework adapter.`):a(`detected ${r} — composing the Lunora worker into one Cloudflare Worker.`)},C=(o,r)=>{let t=!1;const e=()=>{r.framework??=f(o.projectRoot)};return{config(){e()},configResolved(){e()},configureServer(){e(),!t&&r.framework!==void 0&&(t=!0,console.info(D(r.framework)))},name:"lunora:framework-detect"}},N=o=>{if(o===!1)return!1;const r=o===!0||o===void 0?{}:o;return{...r,forwardedConsoleMethods:r.forwardedConsoleMethods??["error","warn"],solutionFinders:[...T,...r.solutionFinders??[]]}},U=(o,r)=>{const t=d(o,r);if(!m(t)){const e=p();throw new Error(`target "${t}" has no command-line toolchain, so the Lunora Vite plugin cannot build or serve it — it can only generate for it (\`lunora codegen --target ${t}\`). Buildable targets: ${e.join(", ")}`)}return t},I=o=>{const r=o??{},t=r.schemaDir??"lunora";let e;r.cloudflare===!1?e=!1:r.cloudflare===!0||r.cloudflare===void 0?e={}:e=r.cloudflare;const n=r.projectRoot??process.cwd();return{allowUnauthenticatedShardAccess:r.allowUnauthenticatedShardAccess??!1,apiSpec:r.apiSpec??"openapi",cloudflare:e,studio:r.studio??!0,generatedDir:`${t}/_generated`,overlay:N(r.overlay),projectRoot:n,schemaDir:t,shard:r.shard??{},target:U(n,r.target),validateWrangler:r.validateWrangler??!0}},er=o=>{const r=I(o),t=L(),e=[C(r,t),k(r,t),h(r),y(r),v(r),P(),R(r),b(r),A()];r.studio&&e.push(_(r)),r.validateWrangler&&e.push(O(r)),r.overlay!==!1&&e.push(g(r.overlay)),e.push(w(r));const n=r.cloudflare===!1?void 0:{...r.cloudflare};return e.push(E(n,{projectRoot:r.projectRoot})),n!==void 0&&e.push(...x(l(n))),e},or=i(import.meta.url)("../package.json").version;export{sr as CLASS_A_WIRING,ar as GENERATED_CLASS_MODULES,xr as LUNORA_API_UPDATED_EVENT,ur as LUNORA_WORKER_VIRTUAL_ID,hr as STUDIO_PATH,or as VERSION,Ar as WORKER_STARTUP_HINT,Er as augmentWorkerStartupError,kr as buildStudioUrl,cr as buildWorkerEntrySource,mr as checkLunoraProxy,v as codegenPlugin,w as containerLogsPlugin,ir as detectFramework,R as devStatePlugin,h as devVariablesPlugin,k as frameworkComposePlugin,fr as isAutoComposable,Tr as isWorkerEntryEvalError,P as logStreamPlugin,er as lunora,wr as lunoraSolutionFinder,T as lunoraSolutionFinders,gr as planViteRemoteBindings,A as proxyCheckPlugin,br as reconcileWranglerCrons,E as remoteBindingsPlugin,N as resolveOverlayOption,_ as studioPlugin,Sr as withRemoteBindings,x as withWorkerStartupHint,O as wranglerValidatorPlugin};
@@ -0,0 +1,3 @@
1
+ import{readFileSync as V,existsSync as W}from"node:fs";import{join as J,resolve as w,sep as E,basename as Q}from"node:path";import{findProjectConfigFile as Y,listLunoraSourceFiles as Z,PROJECT_CONFIG_FILENAMES as ee,findTsconfig as ne,runCodegen as re,describeErrorLevelFindings as te,createCodegenProject as oe,refreshCodegenProject as ie,CodegenDiagnosticError as ae}from"@lunora/codegen";import{inferLunoraBindings as ce,isCodegenDisabled as se,CODEGEN_ENV as F,runPostCodegenHook as A}from"@lunora/config";import{findWranglerFile as de,readWranglerJsonc as le,reconcileWranglerBindings as fe,reconcileWranglerCrons as ge,describePreservedCrons as ue,reconcileWranglerCompatibilityDate as he,WRANGLER_FILES as me,collectWranglerSecretVariables as pe}from"@lunora/config/cloudflare";import{isRunnableDevEnvironment as we}from"vite";import{createHash as H}from"node:crypto";import ye from"./LUNORA_API_UPDATED_EVENT-CO2Rv2re.mjs";import{L as l,a as L}from"./log-DE48L4Oz.mjs";import{r as $e,a as ve}from"./server-close-Qoh4i6Ay.mjs";const Se=(e,r)=>{try{const{parsed:t,text:n}=le(e);return t===void 0?`raw:${n}`:JSON.stringify(r?r(t):t)}catch{return"unreadable"}},be=e=>{const r={...e},{triggers:t}=r;if(t!==null&&typeof t=="object"){const n={...t};delete n.crons,Object.keys(n).length>0?r.triggers=n:delete r.triggers}return r},N=e=>{const r=de(e),t=r===void 0?"absent":Se(r,be),n=Y(e);let o="absent";try{n!==void 0&&(o=H("sha256").update(V(n)).digest("hex"))}catch{}return`${t}\0${o}`},Ee=async(e,r,t)=>{try{const n=await ce({projectRoot:e.projectRoot,schemaDir:e.schemaDir}),o=fe(e.projectRoot,n),a=o.wranglerPath??"wrangler.jsonc";o.added.length>0&&r.info?.(`${l} inferred bindings → ${o.added.join(", ")} (written to ${a})`),o.updated.length>0&&r.info?.(`${l} updated bindings → ${o.updated.join(", ")} (written to ${a})`);for(const c of o.warnings)r.warn(`${l} ${c}`);o.exportGaps.length>0&&t?.(o.exportGaps)}catch(n){const o=n instanceof Error?n.message:String(n);r.warn(`${l} binding inference skipped: ${o}`)}},G=new Map,Re=(e,r,t)=>{try{const n=ge(e,r);n.changed&&t.info?.(`${l} synced ${r.length.toFixed(0)} cron trigger(s) into ${n.wranglerPath??"wrangler.jsonc"}`);for(const c of n.warnings)t.warn(`${l} ${c}`);const o=n.preserved.join("\0"),a=ue(n.preserved);a!==void 0&&(n.changed||G.get(e)!==o)&&t.info?.(`${l} ${a}`),G.set(e,o)}catch(n){const o=n instanceof Error?n.message:String(n);t.warn(`${l} cron trigger sync skipped: ${o}`)}try{const n=he(e);n.changed&&t.info?.(`${l} bumped compatibility_date to ${n.date??"unknown"} (Workers Cache enabled) → ${n.wranglerPath??"wrangler.jsonc"}`)}catch(n){const o=n instanceof Error?n.message:String(n);t.warn(`${l} compatibility date sync skipped: ${o}`)}},ke=100,z=300,I=2,je=e=>{let r,t,n=0;const o=()=>{r&&(clearTimeout(r),r=void 0)},a=(g,u)=>{t&&clearTimeout(t),t=setTimeout(()=>{if(t=void 0,e.fingerprint()!==g){if(n+=1,n>I){e.logger.warn(`${l} \`postcodegen\` keeps rewriting the schema sources — stopping after ${String(I)} reruns. Make the hook idempotent or move it off the schema directory.`);return}e.logger.info(`${l} schema changed while \`postcodegen\` was running — regenerating`),u()}},z)},c=g=>{e.regenerate(g,u=>{a(u,()=>{c(g)})})};return{cancelPending:o,dispose:()=>{o(),t&&(clearTimeout(t),t=void 0)},onSave:g=>{o(),n=0,r=setTimeout(()=>{r=void 0,c(g)},ke)}}},B=e=>{if(!W(e))return"unreadable";const r=Z(e),t=J(e,"schema.ts");W(t)&&r.push(t);const n=H("sha256");for(const o of r.toSorted((a,c)=>a.localeCompare(c)))try{n.update(o).update("\0").update(V(o))}catch{}return n.digest("hex")},U=/[/\\]tsconfig\..+\.json$/u,Ce=e=>{const r=e.map(n=>` • ${n.kind} "${n.exportName}" — class ${n.className} is not exported by your worker entry.`),t=[...new Set(e.map(n=>n.module))].map(n=>` export * from "./lunora/_generated/${n}";`);return[`[lunora] ${String(e.length)} declared ${e.length===1?"binding is":"bindings are"} not exported by your worker entry — \`wrangler deploy\` will fail.`,...r,"","Add to your worker entry:",...t].join(`
2
+ `)},De=e=>{const{advisoryNames:r,platformDiagnosticNames:t}=te(e),n=[...new Set([...r,...t])].toSorted((a,c)=>a.localeCompare(c));if(n.length===0)return;const o=n.length===1?"advisory/platform diagnostic":"advisories/platform diagnostics";return`${l} ${String(n.length)} ERROR-level ${o} (${n.join(", ")}) — see the log above for detail.`},Pe=(e,r,t)=>{if(r.warn(`${l} schema.ts not found at ${e} — codegen skipped`),t!==void 0){const n=`schema.ts not found at ${e} — generated output is now stale`;t.onError(new Error(n),n)}},O=(e,r,t,n)=>{const o=J(e.projectRoot,e.schemaDir,"schema.ts");if(!W(o))return Pe(o,r,t),{};try{const a=re({apiSpec:e.apiSpec,lunoraDirectory:e.schemaDir,project:n,projectRoot:e.projectRoot,target:e.target,wranglerVariables:pe(e.projectRoot)});Re(e.projectRoot,a.cronTriggers,r);for(const c of a.advisories){const g=L(c.level,c.name,c.detail,c.remediation);c.level==="ERROR"?r.error(g):r.warn(g)}for(const c of a.platformDiagnostics){const g=L(c.level==="error"?"ERROR":"WARN",c.name,c.message,c.remediation);c.level==="error"?r.error(g):r.warn(g)}return{blockingMessage:De(a),outputDirectory:w(a.outputDirectory)}}catch(a){const c=a instanceof Error?a.message:String(a);return r.error(`${l} codegen failed: ${c}`),t?.onError(a,c),{failure:`${l} codegen failed: ${c}`}}},_e=(e,r,t)=>{let n;for(const[o,a]of Object.entries(e.environments)){if(o==="client"){n=a;continue}we(a)||a.hot.send({path:"*",triggeredBy:r,type:"full-reload"})}if(n===void 0){e.hot.send({type:"full-reload"});return}if(t){n.hot.send({type:"full-reload"});return}n.hot.send({event:ye,type:"custom"})},k={error:e=>{console.error(e)},info:e=>{console.info(e)},warn:e=>{console.warn(e)}},Ie=e=>{const r=w(e.projectRoot,e.schemaDir),t=se(process.env[F]);let n=w(e.projectRoot,e.generatedDir),o=0,a=!1,c;const g=new Map;let u,j=!1,C=!1,y,D;return{config(s,m){y=m.command},configResolved(){y!=="build"&&t||(D=O(e,k))},async buildStart(){const s=y!=="build"&&t,{blockingMessage:m,failure:$,outputDirectory:R}=D??(s?{}:O(e,k));if(D=void 0,y==="build"&&$!==void 0&&this.error($),R!==void 0){n=R,a=!0;let h;try{h=await A({cwd:e.projectRoot,logger:k})}finally{a=!1}h.ran&&(o=Date.now()),y==="build"&&h.error!==void 0&&this.error(h.error)}y==="build"&&m!==void 0&&this.error(m),await Ee(e,k,h=>{c?.hot.send({err:{loc:void 0,message:Ce(h),stack:""},type:"error"})}),c!==void 0&&(u=N(e.projectRoot),j=!0)},configureServer(s){c=s,s.watcher.add(r),u=N(e.projectRoot),j=!1;const m={error:i=>{s.config.logger.error(i)},info:i=>{s.config.logger.info(i)},warn:i=>{s.config.logger.warn(i)}};let $=!1;const R={onError(i,d){$=!0;const f=i instanceof ae?{column:i.column,file:i.file,line:i.line}:void 0,b=f===void 0?`[lunora] codegen failed: ${d}
3
+ (see terminal for full stack trace and file location)`:`[lunora] codegen failed: ${d}`;c?.hot.send({err:{loc:f,message:b,stack:i instanceof Error?i.stack??"":""},type:"error"})}},h=(i,d)=>i===d||i.startsWith(d+E);let P=!1,p;const K=()=>{for(const i of Object.values(s.environments)){const d=i.moduleGraph;for(const f of d.idToModuleMap.values())f.id&&h(f.id,n)&&d.invalidateModule(f)}},X=async(i,d)=>{try{if(P)return;p===void 0?p=oe(r):ie(p,r);const{outputDirectory:f}=O(e,m,R,p);if(f===void 0){p=void 0;return}n=f;const b=B(r);a=!0;let T;try{T=await A({cwd:e.projectRoot,logger:m})}finally{a=!1}if(T.ran&&(o=Date.now(),d(b)),T.error!==void 0)return;K(),_e(s,i,$),$=!1}catch(f){m.error(`${l} codegen watch: ${f instanceof Error?f.message:String(f)}`)}},_=je({fingerprint:()=>B(r),logger:m,regenerate:(i,d)=>{X(i,d)}}),v=i=>{const d=w(i);if(U.test(d)){p=void 0;return}if(d.endsWith(`${E}tsconfig.json`)&&d===ne(r)){p=void 0;return}if(h(d,r)&&!h(d,n)&&d.endsWith(".ts")&&!(d.includes(`${E}__tests__${E}`)||d.endsWith(".test.ts")||d.endsWith(".spec.ts"))){if(a||Date.now()-o<z){_.cancelPending();return}_.onSave(d)}},x=i=>{const d=w(i);(d.endsWith(`${E}tsconfig.json`)||U.test(d))&&(p=void 0)};t?s.config.logger.info(`${l} codegen watch disabled (${F}) — _generated/ is written only by an explicit \`lunora codegen\``):(s.watcher.on("add",v),s.watcher.on("change",v),s.watcher.on("unlink",v),s.watcher.on("unlink",x));const M=new Set([...me.map(i=>w(e.projectRoot,i)),...ee.map(i=>w(e.projectRoot,i))]);for(const i of M)s.watcher.add(i);const S=i=>{if(!M.has(w(i))||C)return;const d=N(e.projectRoot);if(!j){u=d;return}if(u===void 0){u=d;return}d!==u&&(u=d,C=!0,s.config.logger.info(`${l} ${Q(w(i))} changed — restarting dev server`),Promise.resolve(s.restart()).finally(()=>{C=!1}).catch(f=>{const b=f instanceof Error?f.message:String(f);s.config.logger.error(`${l} dev server restart failed: ${b} — keeping the running server; re-save your config to retry.`),s.hot.send({err:{loc:void 0,message:`[lunora] dev server restart failed: ${b}`,stack:""},type:"error"})}))};s.watcher.on("add",S),s.watcher.on("change",S),s.watcher.on("unlink",S);const q=()=>{P||(P=!0,p=void 0,_.dispose(),s.watcher.off("add",v),s.watcher.off("change",v),s.watcher.off("unlink",v),s.watcher.off("unlink",x),s.watcher.off("add",S),s.watcher.off("change",S),s.watcher.off("unlink",S))};return()=>{ve(s,g,q)}},buildEnd(){$e(g,this.environment)},name:"lunora:codegen"}};export{Ie as c,Ee as r};
@@ -1 +1 @@
1
- import{c as i}from"./codegen-plugin-CnF5a3-x.mjs";import"./LUNORA_API_UPDATED_EVENT-CO2Rv2re.mjs";import"./log-DE48L4Oz.mjs";import"./server-close-Qoh4i6Ay.mjs";export{i as default};
1
+ import{c as i}from"./codegen-plugin-BqoP2XfZ.mjs";import"./LUNORA_API_UPDATED_EVENT-CO2Rv2re.mjs";import"./log-DE48L4Oz.mjs";import"./server-close-Qoh4i6Ay.mjs";export{i as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/vite",
3
- "version": "1.0.0-alpha.245",
3
+ "version": "1.0.0-alpha.247",
4
4
  "description": "The Lunora Vite plugin: codegen, type sync, wrangler validation, and an error overlay over @cloudflare/vite-plugin",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -46,8 +46,8 @@
46
46
  },
47
47
  "dependencies": {
48
48
  "@cloudflare/vite-plugin": "1.54.4",
49
- "@lunora/codegen": "1.0.0-alpha.208",
50
- "@lunora/config": "1.0.0-alpha.245",
49
+ "@lunora/codegen": "1.0.0-alpha.210",
50
+ "@lunora/config": "1.0.0-alpha.247",
51
51
  "@lunora/errors": "1.0.0-alpha.41",
52
52
  "@visulima/vite-overlay": "2.0.20"
53
53
  },
@@ -1,3 +0,0 @@
1
- import{readFileSync as V,existsSync as W}from"node:fs";import{join as J,resolve as w,sep as b,basename as Q}from"node:path";import{findProjectConfigFile as Y,listLunoraSourceFiles as Z,PROJECT_CONFIG_FILENAMES as ee,findTsconfig as ne,runCodegen as re,describeErrorLevelFindings as te,createCodegenProject as oe,refreshCodegenProject as ie,CodegenDiagnosticError as ae}from"@lunora/codegen";import{inferLunoraBindings as ce,isCodegenDisabled as se,CODEGEN_ENV as F,runPostCodegenHook as A}from"@lunora/config";import{findWranglerFile as le,readWranglerJsonc as de,reconcileWranglerBindings as fe,reconcileWranglerCrons as ge,describePreservedCrons as ue,reconcileWranglerCompatibilityDate as he,WRANGLER_FILES as me,collectWranglerSecretVariables as pe}from"@lunora/config/cloudflare";import{isRunnableDevEnvironment as we}from"vite";import{createHash as H}from"node:crypto";import ye from"./LUNORA_API_UPDATED_EVENT-CO2Rv2re.mjs";import{L as d,a as L}from"./log-DE48L4Oz.mjs";import{r as $e,a as ve}from"./server-close-Qoh4i6Ay.mjs";const Se=(e,r)=>{try{const{parsed:t,text:n}=de(e);return t===void 0?`raw:${n}`:JSON.stringify(r?r(t):t)}catch{return"unreadable"}},Ee=e=>{const r={...e},{triggers:t}=r;if(t!==null&&typeof t=="object"){const n={...t};delete n.crons,Object.keys(n).length>0?r.triggers=n:delete r.triggers}return r},N=e=>{const r=le(e),t=r===void 0?"absent":Se(r,Ee),n=Y(e);let o="absent";try{n!==void 0&&(o=H("sha256").update(V(n)).digest("hex"))}catch{}return`${t}\0${o}`},be=async(e,r,t)=>{try{const n=await ce({projectRoot:e.projectRoot,schemaDir:e.schemaDir}),o=fe(e.projectRoot,n);o.changed&&r.info?.(`${d} inferred bindings → ${o.added.join(", ")} (written to ${o.wranglerPath??"wrangler.jsonc"})`);for(const a of o.warnings)r.warn(`${d} ${a}`);o.exportGaps.length>0&&t?.(o.exportGaps)}catch(n){const o=n instanceof Error?n.message:String(n);r.warn(`${d} binding inference skipped: ${o}`)}},G=new Map,Re=(e,r,t)=>{try{const n=ge(e,r);n.changed&&t.info?.(`${d} synced ${r.length.toFixed(0)} cron trigger(s) into ${n.wranglerPath??"wrangler.jsonc"}`);for(const l of n.warnings)t.warn(`${d} ${l}`);const o=n.preserved.join("\0"),a=ue(n.preserved);a!==void 0&&(n.changed||G.get(e)!==o)&&t.info?.(`${d} ${a}`),G.set(e,o)}catch(n){const o=n instanceof Error?n.message:String(n);t.warn(`${d} cron trigger sync skipped: ${o}`)}try{const n=he(e);n.changed&&t.info?.(`${d} bumped compatibility_date to ${n.date??"unknown"} (Workers Cache enabled) → ${n.wranglerPath??"wrangler.jsonc"}`)}catch(n){const o=n instanceof Error?n.message:String(n);t.warn(`${d} compatibility date sync skipped: ${o}`)}},ke=100,z=300,I=2,Ce=e=>{let r,t,n=0;const o=()=>{r&&(clearTimeout(r),r=void 0)},a=(g,u)=>{t&&clearTimeout(t),t=setTimeout(()=>{if(t=void 0,e.fingerprint()!==g){if(n+=1,n>I){e.logger.warn(`${d} \`postcodegen\` keeps rewriting the schema sources — stopping after ${String(I)} reruns. Make the hook idempotent or move it off the schema directory.`);return}e.logger.info(`${d} schema changed while \`postcodegen\` was running — regenerating`),u()}},z)},l=g=>{e.regenerate(g,u=>{a(u,()=>{l(g)})})};return{cancelPending:o,dispose:()=>{o(),t&&(clearTimeout(t),t=void 0)},onSave:g=>{o(),n=0,r=setTimeout(()=>{r=void 0,l(g)},ke)}}},B=e=>{if(!W(e))return"unreadable";const r=Z(e),t=J(e,"schema.ts");W(t)&&r.push(t);const n=H("sha256");for(const o of r.toSorted((a,l)=>a.localeCompare(l)))try{n.update(o).update("\0").update(V(o))}catch{}return n.digest("hex")},U=/[/\\]tsconfig\..+\.json$/u,je=e=>{const r=e.map(n=>` • ${n.kind} "${n.exportName}" — class ${n.className} is not exported by your worker entry.`),t=[...new Set(e.map(n=>n.module))].map(n=>` export * from "./lunora/_generated/${n}";`);return[`[lunora] ${String(e.length)} declared ${e.length===1?"binding is":"bindings are"} not exported by your worker entry — \`wrangler deploy\` will fail.`,...r,"","Add to your worker entry:",...t].join(`
2
- `)},De=e=>{const{advisoryNames:r,platformDiagnosticNames:t}=te(e),n=[...new Set([...r,...t])].toSorted((a,l)=>a.localeCompare(l));if(n.length===0)return;const o=n.length===1?"advisory/platform diagnostic":"advisories/platform diagnostics";return`${d} ${String(n.length)} ERROR-level ${o} (${n.join(", ")}) — see the log above for detail.`},Pe=(e,r,t)=>{if(r.warn(`${d} schema.ts not found at ${e} — codegen skipped`),t!==void 0){const n=`schema.ts not found at ${e} — generated output is now stale`;t.onError(new Error(n),n)}},O=(e,r,t,n)=>{const o=J(e.projectRoot,e.schemaDir,"schema.ts");if(!W(o))return Pe(o,r,t),{};try{const a=re({apiSpec:e.apiSpec,lunoraDirectory:e.schemaDir,project:n,projectRoot:e.projectRoot,target:e.target,wranglerVariables:pe(e.projectRoot)});Re(e.projectRoot,a.cronTriggers,r);for(const l of a.advisories){const g=L(l.level,l.name,l.detail,l.remediation);l.level==="ERROR"?r.error(g):r.warn(g)}for(const l of a.platformDiagnostics){const g=L(l.level==="error"?"ERROR":"WARN",l.name,l.message,l.remediation);l.level==="error"?r.error(g):r.warn(g)}return{blockingMessage:De(a),outputDirectory:w(a.outputDirectory)}}catch(a){const l=a instanceof Error?a.message:String(a);return r.error(`${d} codegen failed: ${l}`),t?.onError(a,l),{failure:`${d} codegen failed: ${l}`}}},_e=(e,r,t)=>{let n;for(const[o,a]of Object.entries(e.environments)){if(o==="client"){n=a;continue}we(a)||a.hot.send({path:"*",triggeredBy:r,type:"full-reload"})}if(n===void 0){e.hot.send({type:"full-reload"});return}if(t){n.hot.send({type:"full-reload"});return}n.hot.send({event:ye,type:"custom"})},k={error:e=>{console.error(e)},info:e=>{console.info(e)},warn:e=>{console.warn(e)}},Ie=e=>{const r=w(e.projectRoot,e.schemaDir),t=se(process.env[F]);let n=w(e.projectRoot,e.generatedDir),o=0,a=!1,l;const g=new Map;let u,C=!1,j=!1,y,D;return{config(c,m){y=m.command},configResolved(){y!=="build"&&t||(D=O(e,k))},async buildStart(){const c=y!=="build"&&t,{blockingMessage:m,failure:$,outputDirectory:R}=D??(c?{}:O(e,k));if(D=void 0,y==="build"&&$!==void 0&&this.error($),R!==void 0){n=R,a=!0;let h;try{h=await A({cwd:e.projectRoot,logger:k})}finally{a=!1}h.ran&&(o=Date.now()),y==="build"&&h.error!==void 0&&this.error(h.error)}y==="build"&&m!==void 0&&this.error(m),await be(e,k,h=>{l?.hot.send({err:{loc:void 0,message:je(h),stack:""},type:"error"})}),l!==void 0&&(u=N(e.projectRoot),C=!0)},configureServer(c){l=c,c.watcher.add(r),u=N(e.projectRoot),C=!1;const m={error:i=>{c.config.logger.error(i)},info:i=>{c.config.logger.info(i)},warn:i=>{c.config.logger.warn(i)}};let $=!1;const R={onError(i,s){$=!0;const f=i instanceof ae?{column:i.column,file:i.file,line:i.line}:void 0,E=f===void 0?`[lunora] codegen failed: ${s}
3
- (see terminal for full stack trace and file location)`:`[lunora] codegen failed: ${s}`;l?.hot.send({err:{loc:f,message:E,stack:i instanceof Error?i.stack??"":""},type:"error"})}},h=(i,s)=>i===s||i.startsWith(s+b);let P=!1,p;const K=()=>{for(const i of Object.values(c.environments)){const s=i.moduleGraph;for(const f of s.idToModuleMap.values())f.id&&h(f.id,n)&&s.invalidateModule(f)}},X=async(i,s)=>{try{if(P)return;p===void 0?p=oe(r):ie(p,r);const{outputDirectory:f}=O(e,m,R,p);if(f===void 0){p=void 0;return}n=f;const E=B(r);a=!0;let T;try{T=await A({cwd:e.projectRoot,logger:m})}finally{a=!1}if(T.ran&&(o=Date.now(),s(E)),T.error!==void 0)return;K(),_e(c,i,$),$=!1}catch(f){m.error(`${d} codegen watch: ${f instanceof Error?f.message:String(f)}`)}},_=Ce({fingerprint:()=>B(r),logger:m,regenerate:(i,s)=>{X(i,s)}}),v=i=>{const s=w(i);if(U.test(s)){p=void 0;return}if(s.endsWith(`${b}tsconfig.json`)&&s===ne(r)){p=void 0;return}if(h(s,r)&&!h(s,n)&&s.endsWith(".ts")&&!(s.includes(`${b}__tests__${b}`)||s.endsWith(".test.ts")||s.endsWith(".spec.ts"))){if(a||Date.now()-o<z){_.cancelPending();return}_.onSave(s)}},x=i=>{const s=w(i);(s.endsWith(`${b}tsconfig.json`)||U.test(s))&&(p=void 0)};t?c.config.logger.info(`${d} codegen watch disabled (${F}) — _generated/ is written only by an explicit \`lunora codegen\``):(c.watcher.on("add",v),c.watcher.on("change",v),c.watcher.on("unlink",v),c.watcher.on("unlink",x));const M=new Set([...me.map(i=>w(e.projectRoot,i)),...ee.map(i=>w(e.projectRoot,i))]);for(const i of M)c.watcher.add(i);const S=i=>{if(!M.has(w(i))||j)return;const s=N(e.projectRoot);if(!C){u=s;return}if(u===void 0){u=s;return}s!==u&&(u=s,j=!0,c.config.logger.info(`${d} ${Q(w(i))} changed — restarting dev server`),Promise.resolve(c.restart()).finally(()=>{j=!1}).catch(f=>{const E=f instanceof Error?f.message:String(f);c.config.logger.error(`${d} dev server restart failed: ${E} — keeping the running server; re-save your config to retry.`),c.hot.send({err:{loc:void 0,message:`[lunora] dev server restart failed: ${E}`,stack:""},type:"error"})}))};c.watcher.on("add",S),c.watcher.on("change",S),c.watcher.on("unlink",S);const q=()=>{P||(P=!0,p=void 0,_.dispose(),c.watcher.off("add",v),c.watcher.off("change",v),c.watcher.off("unlink",v),c.watcher.off("unlink",x),c.watcher.off("add",S),c.watcher.off("change",S),c.watcher.off("unlink",S))};return()=>{ve(c,g,q)}},buildEnd(){$e(g,this.environment)},name:"lunora:codegen"}};export{Ie as c,be as r};