@lunora/vite 1.0.0-alpha.7 → 1.0.0-alpha.70

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.
@@ -1,9 +1,13 @@
1
1
  import { existsSync, readFileSync } from 'node:fs';
2
2
  import { resolve, join } from 'node:path';
3
+ import { LunoraError } from '@lunora/errors';
3
4
 
4
5
  const LUNORA_WORKER_VIRTUAL_ID = "virtual:lunora/worker";
5
6
  const RESOLVED_VIRTUAL_PREFIX = "\0";
6
7
  const RESOLVED_LUNORA_WORKER_ID = `${RESOLVED_VIRTUAL_PREFIX}${LUNORA_WORKER_VIRTUAL_ID}`;
8
+ const CLIENT_WORKER_STUB = `// @lunora/vite — the composed worker entry is worker-only and unavailable in the client environment.
9
+ export default {};
10
+ `;
7
11
  const TRAILING_SLASH = /\/$/;
8
12
  const CLASS_A_WIRING = {
9
13
  "react-router": {
@@ -44,23 +48,24 @@ const projectUsesUmbrella = (projectRoot) => {
44
48
  return false;
45
49
  }
46
50
  };
47
- const buildWorkerEntrySource = (framework, generatedImportBase, hasContainers = false, useUmbrella = false) => {
51
+ const buildWorkerEntrySource = (framework, generatedImportBase, hasContainers = false, useUmbrella = false, allowUnauthenticatedShardAccess = false) => {
48
52
  const wiring = CLASS_A_WIRING[framework];
49
53
  if (wiring === void 0) {
50
- throw new Error(`[lunora] no class-A worker wiring for framework "${framework}"`);
54
+ throw new LunoraError("INTERNAL", `[lunora] no class-A worker wiring for framework "${framework}"`);
51
55
  }
56
+ const base = generatedImportBase.replaceAll("\\", "/");
52
57
  const runtimeModule = useUmbrella ? "lunorash/runtime" : "@lunora/runtime";
53
58
  const containersReexport = hasContainers ? `
54
- export * from "${generatedImportBase}/containers";
59
+ export * from "${base}/containers";
55
60
  ` : "";
56
61
  return `// Generated by @lunora/vite — class-A worker composition (PLAN4 M2).
57
62
  // Do not edit: emitted from the detected framework (${framework}). Point your
58
63
  // wrangler \`main\` here (or re-export it) instead of hand-wiring createWorker.
59
64
  import { composeWorker } from "${runtimeModule}";
60
65
  ${wiring.imports}
61
- import { LUNORA_FUNCTIONS } from "${generatedImportBase}/functions";
62
- import { openApiSpec } from "${generatedImportBase}/openapi";
63
- import { createShardDO } from "${generatedImportBase}/shard";
66
+ import { LUNORA_FUNCTIONS } from "${base}/functions";
67
+ import { openApiSpec } from "${base}/openapi";
68
+ import { createShardDO } from "${base}/shard";
64
69
 
65
70
  export const ShardDO = createShardDO();
66
71
  ${containersReexport}
@@ -69,7 +74,7 @@ let worker;
69
74
 
70
75
  export default {
71
76
  async fetch(request, env, context) {
72
- worker ??= composeWorker({
77
+ worker ??= composeWorker({${allowUnauthenticatedShardAccess ? "\n allowUnauthenticatedShardAccess: true," : ""}
73
78
  functions: LUNORA_FUNCTIONS,
74
79
  httpRouter: ${wiring.handler},
75
80
  openApiSpec,
@@ -88,8 +93,17 @@ const frameworkComposePlugin = (options, context) => {
88
93
  return {
89
94
  load(id) {
90
95
  if (id === RESOLVED_LUNORA_WORKER_ID && isWorkerVirtualActive(context) && context.framework !== void 0) {
96
+ if (this.environment.name === "client") {
97
+ return CLIENT_WORKER_STUB;
98
+ }
91
99
  const hasContainers = existsSync(join(generatedImportBase, "containers.ts"));
92
- return buildWorkerEntrySource(context.framework.framework, generatedImportBase, hasContainers, useUmbrella);
100
+ return buildWorkerEntrySource(
101
+ context.framework.framework,
102
+ generatedImportBase,
103
+ hasContainers,
104
+ useUmbrella,
105
+ options.allowUnauthenticatedShardAccess
106
+ );
93
107
  }
94
108
  return void 0;
95
109
  },
@@ -0,0 +1,3 @@
1
+ const LUNORA_API_UPDATED_EVENT = "lunora:api-updated";
2
+
3
+ export { LUNORA_API_UPDATED_EVENT as default };
@@ -1,5 +1,5 @@
1
1
  import { detectAgentRules } from '@lunora/config';
2
- import { handleSeedRequest, handleSchemaEditRequest, handlePolicyScaffoldRequest, SEED_ENDPOINT, SCHEMA_EDIT_ENDPOINT, POLICY_SCAFFOLD_ENDPOINT, serveJsonHandler, renderStudioHtml, resolveAdminToken, studioAssetsStamp, loadStudioAssets } from '@lunora/config/studio-host';
2
+ import { handleSeedRequest, handleSchemaEditRequest, handlePolicyScaffoldRequest, SEED_ENDPOINT, SCHEMA_EDIT_ENDPOINT, POLICY_SCAFFOLD_ENDPOINT, serveJsonHandler, isStandaloneModulePath, renderStudioHtml, resolveAdminToken, studioAssetsStamp, loadStudioAssets, readStandaloneAsset, assetContentType } from '@lunora/config/studio-host';
3
3
 
4
4
  const STUDIO_PATH = "/__lunora";
5
5
  const STUDIO_SCRIPT_PATH = `${STUDIO_PATH}/studio.js`;
@@ -47,6 +47,10 @@ const transportRejectionReason = (request) => {
47
47
  if (host !== void 0 && !LOOPBACK_HOSTS.has(host)) {
48
48
  return "Lunora studio rejects a non-localhost Host header in dev.";
49
49
  }
50
+ const FORWARDING_HEADERS = ["x-forwarded-for", "x-forwarded-host", "x-forwarded-proto", "forwarded"];
51
+ if (FORWARDING_HEADERS.some((name) => request.headers?.[name] !== void 0)) {
52
+ return "Lunora studio refuses a proxied (X-Forwarded-*) request in dev.";
53
+ }
50
54
  return void 0;
51
55
  };
52
56
  const originRejectionReason = (headers) => {
@@ -113,7 +117,7 @@ const createStudioHandler = (server, isNonLoopbackBind) => {
113
117
  let assetsStamp;
114
118
  let html;
115
119
  const projectRoot = server.config.root ?? process.cwd();
116
- const serveStaticAsset = (pathname, response) => {
120
+ const serveStaticAsset = (pathname, request, response) => {
117
121
  const stamp = studioAssetsStamp();
118
122
  if (assets === void 0 || stamp !== assetsStamp) {
119
123
  assets = loadStudioAssets(server.config.logger);
@@ -125,8 +129,30 @@ const createStudioHandler = (server, isNonLoopbackBind) => {
125
129
  response.end("Lunora studio assets not found — install and build @lunora/studio.");
126
130
  return;
127
131
  }
128
- const isScript = pathname === STUDIO_SCRIPT_PATH;
129
- sendOk(response, isScript ? assets.script : assets.styles, isScript ? "text/javascript; charset=utf-8" : "text/css; charset=utf-8");
132
+ const isStyle = pathname === STUDIO_STYLE_PATH;
133
+ const fileName = pathname.slice(pathname.lastIndexOf("/") + 1);
134
+ const etag = stamp === void 0 ? void 0 : `W/"${fileName}-${String(stamp)}"`;
135
+ response.setHeader("Cache-Control", "no-cache");
136
+ if (etag !== void 0) {
137
+ response.setHeader("ETag", etag);
138
+ if (headerValue(request.headers?.["if-none-match"]) === etag.toLowerCase()) {
139
+ response.statusCode = 304;
140
+ response.end();
141
+ return;
142
+ }
143
+ }
144
+ if (isStyle) {
145
+ sendOk(response, assets.styles, "text/css; charset=utf-8");
146
+ return;
147
+ }
148
+ const bytes = readStandaloneAsset(fileName);
149
+ if (bytes === void 0) {
150
+ response.statusCode = 404;
151
+ response.setHeader("Content-Type", "text/plain");
152
+ response.end("Not found");
153
+ return;
154
+ }
155
+ sendOk(response, bytes, assetContentType(fileName));
130
156
  };
131
157
  return (request, response, next) => {
132
158
  const pathname = pathnameOf(request.url ?? "");
@@ -154,8 +180,8 @@ const createStudioHandler = (server, isNonLoopbackBind) => {
154
180
  serveJsonHandler(request, response, jsonHandler, projectRoot);
155
181
  return;
156
182
  }
157
- if (pathname === STUDIO_SCRIPT_PATH || pathname === STUDIO_STYLE_PATH) {
158
- serveStaticAsset(pathname, response);
183
+ if (pathname === STUDIO_STYLE_PATH || isStandaloneModulePath(pathname)) {
184
+ serveStaticAsset(pathname, request, response);
159
185
  return;
160
186
  }
161
187
  html ??= renderStudioHtml({
@@ -0,0 +1,347 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { join, resolve, sep, basename } from 'node:path';
3
+ import { createCodegenProject, refreshCodegenProject, runCodegen, CodegenDiagnosticError } from '@lunora/codegen';
4
+ import { findWranglerFile, LUNORA_CONFIG_FILE, readWranglerJsonc, WRANGLER_FILES, collectWranglerSecretVariables, inferLunoraBindings, reconcileWranglerBindings, reconcileWranglerCrons, reconcileWranglerCompatibilityDate } from '@lunora/config';
5
+ import { isRunnableDevEnvironment } from 'vite';
6
+ import LUNORA_API_UPDATED_EVENT from './LUNORA_API_UPDATED_EVENT-BrkWk3rr.mjs';
7
+ import { L as LUNORA_TAG, a as advisoryLine } from './log-BjO9EWah.mjs';
8
+ import { r as runPendingClose, a as registerDevServerClose } from './server-close-DKDp7YTU.mjs';
9
+
10
+ const fingerprintJsonc = (filePath, normalize) => {
11
+ try {
12
+ const { parsed, text } = readWranglerJsonc(filePath);
13
+ if (parsed === void 0) {
14
+ return `raw:${text}`;
15
+ }
16
+ return JSON.stringify(normalize ? normalize(parsed) : parsed);
17
+ } catch {
18
+ return "unreadable";
19
+ }
20
+ };
21
+ const stripCodegenOwnedCrons = (parsed) => {
22
+ const clone = { ...parsed };
23
+ const { triggers } = clone;
24
+ if (triggers !== null && typeof triggers === "object") {
25
+ const restTriggers = { ...triggers };
26
+ delete restTriggers.crons;
27
+ if (Object.keys(restTriggers).length > 0) {
28
+ clone.triggers = restTriggers;
29
+ } else {
30
+ delete clone.triggers;
31
+ }
32
+ }
33
+ return clone;
34
+ };
35
+ const computeConfigFingerprint = (projectRoot) => {
36
+ const wranglerFile = findWranglerFile(projectRoot);
37
+ const wranglerPart = wranglerFile === void 0 ? "absent" : fingerprintJsonc(wranglerFile, stripCodegenOwnedCrons);
38
+ const lunoraConfigPath = join(projectRoot, LUNORA_CONFIG_FILE);
39
+ const lunoraPart = existsSync(lunoraConfigPath) ? fingerprintJsonc(lunoraConfigPath) : "absent";
40
+ return `${wranglerPart}\0${lunoraPart}`;
41
+ };
42
+
43
+ const DEBOUNCE_MS = 100;
44
+ const TSCONFIG_VARIANT_RE = /[/\\]tsconfig\..+\.json$/u;
45
+ const formatExportGapOverlay = (gaps) => {
46
+ const lines = gaps.map((gap) => ` • ${gap.kind} "${gap.exportName}" — class ${gap.className} is not exported by your worker entry.`);
47
+ const hints = [...new Set(gaps.map((gap) => gap.module))].map((module) => ` export * from "./lunora/_generated/${module}";`);
48
+ return [
49
+ `[lunora] ${String(gaps.length)} declared ${gaps.length === 1 ? "binding is" : "bindings are"} not exported by your worker entry — \`wrangler deploy\` will fail.`,
50
+ ...lines,
51
+ "",
52
+ "Add to your worker entry:",
53
+ ...hints
54
+ ].join("\n");
55
+ };
56
+ const reconcileBindingsSafely = async (options, logger, onExportGaps) => {
57
+ try {
58
+ const inferred = await inferLunoraBindings({ projectRoot: options.projectRoot, schemaDir: options.schemaDir });
59
+ const reconciled = reconcileWranglerBindings(options.projectRoot, inferred);
60
+ if (reconciled.changed) {
61
+ logger.info?.(`${LUNORA_TAG} inferred bindings → ${reconciled.added.join(", ")} (written to ${reconciled.wranglerPath ?? "wrangler.jsonc"})`);
62
+ }
63
+ for (const warning of reconciled.warnings) {
64
+ logger.warn(`${LUNORA_TAG} ${warning}`);
65
+ }
66
+ if (reconciled.exportGaps.length > 0) {
67
+ onExportGaps?.(reconciled.exportGaps);
68
+ }
69
+ } catch (error) {
70
+ const message = error instanceof Error ? error.message : String(error);
71
+ logger.warn(`${LUNORA_TAG} binding inference skipped: ${message}`);
72
+ }
73
+ };
74
+ const reconcileWranglerExtras = (projectRoot, cronTriggers, logger) => {
75
+ try {
76
+ const reconciled = reconcileWranglerCrons(projectRoot, cronTriggers);
77
+ if (reconciled.changed) {
78
+ logger.info?.(`${LUNORA_TAG} synced ${cronTriggers.length.toFixed(0)} cron trigger(s) into ${reconciled.wranglerPath ?? "wrangler.jsonc"}`);
79
+ }
80
+ } catch (cronError) {
81
+ const message = cronError instanceof Error ? cronError.message : String(cronError);
82
+ logger.warn(`${LUNORA_TAG} cron trigger sync skipped: ${message}`);
83
+ }
84
+ try {
85
+ const reconciled = reconcileWranglerCompatibilityDate(projectRoot);
86
+ if (reconciled.changed) {
87
+ logger.info?.(
88
+ `${LUNORA_TAG} bumped compatibility_date to ${reconciled.date ?? "unknown"} (Workers Cache enabled) → ${reconciled.wranglerPath ?? "wrangler.jsonc"}`
89
+ );
90
+ }
91
+ } catch (dateError) {
92
+ const message = dateError instanceof Error ? dateError.message : String(dateError);
93
+ logger.warn(`${LUNORA_TAG} compatibility date sync skipped: ${message}`);
94
+ }
95
+ };
96
+ const runCodegenSafely = (options, logger, overlay, project) => {
97
+ const schemaPath = join(options.projectRoot, options.schemaDir, "schema.ts");
98
+ if (!existsSync(schemaPath)) {
99
+ logger.warn(`${LUNORA_TAG} schema.ts not found at ${schemaPath} — codegen skipped`);
100
+ return void 0;
101
+ }
102
+ try {
103
+ const result = runCodegen({
104
+ apiSpec: options.apiSpec,
105
+ lunoraDirectory: options.schemaDir,
106
+ project,
107
+ projectRoot: options.projectRoot,
108
+ wranglerVariables: collectWranglerSecretVariables(options.projectRoot)
109
+ });
110
+ reconcileWranglerExtras(options.projectRoot, result.cronTriggers, logger);
111
+ for (const advisory of result.advisories) {
112
+ const line = advisoryLine(advisory.level, advisory.name, advisory.detail, advisory.remediation);
113
+ if (advisory.level === "ERROR") {
114
+ logger.error(line);
115
+ } else {
116
+ logger.warn(line);
117
+ }
118
+ }
119
+ return resolve(result.outputDirectory);
120
+ } catch (error) {
121
+ const message = error instanceof Error ? error.message : String(error);
122
+ logger.error(`${LUNORA_TAG} codegen failed: ${message}`);
123
+ overlay?.onError(error, message);
124
+ return void 0;
125
+ }
126
+ };
127
+ const notifyEnvironmentsAfterCodegen = (server, changedFile, clearErrorOverlay) => {
128
+ let clientEnvironment;
129
+ for (const [name, environment] of Object.entries(server.environments)) {
130
+ if (name === "client") {
131
+ clientEnvironment = environment;
132
+ continue;
133
+ }
134
+ if (isRunnableDevEnvironment(environment)) {
135
+ continue;
136
+ }
137
+ environment.hot.send({ path: "*", triggeredBy: changedFile, type: "full-reload" });
138
+ }
139
+ if (clientEnvironment === void 0) {
140
+ server.hot.send({ type: "full-reload" });
141
+ return;
142
+ }
143
+ if (clearErrorOverlay) {
144
+ clientEnvironment.hot.send({ type: "full-reload" });
145
+ return;
146
+ }
147
+ clientEnvironment.hot.send({ event: LUNORA_API_UPDATED_EVENT, type: "custom" });
148
+ };
149
+ const codegenPlugin = (options) => {
150
+ const absoluteSchemaDirectory = resolve(options.projectRoot, options.schemaDir);
151
+ let absoluteGeneratedDirectory = resolve(options.projectRoot, options.generatedDir);
152
+ let devServer;
153
+ const pendingMiddlewareTeardowns = /* @__PURE__ */ new Map();
154
+ let configFingerprint;
155
+ let configBaselineSettled = false;
156
+ let restartInFlight = false;
157
+ return {
158
+ async buildStart() {
159
+ const logger = {
160
+ error: (message) => {
161
+ console.error(message);
162
+ },
163
+ info: (message) => {
164
+ console.info(message);
165
+ },
166
+ warn: (message) => {
167
+ console.warn(message);
168
+ }
169
+ };
170
+ const outputDirectory = runCodegenSafely(options, logger);
171
+ if (outputDirectory !== void 0) {
172
+ absoluteGeneratedDirectory = outputDirectory;
173
+ }
174
+ await reconcileBindingsSafely(options, logger, (gaps) => {
175
+ devServer?.hot.send({
176
+ err: { loc: void 0, message: formatExportGapOverlay(gaps), stack: "" },
177
+ type: "error"
178
+ });
179
+ });
180
+ if (devServer !== void 0) {
181
+ configFingerprint = computeConfigFingerprint(options.projectRoot);
182
+ configBaselineSettled = true;
183
+ }
184
+ },
185
+ configureServer(server) {
186
+ devServer = server;
187
+ server.watcher.add(absoluteSchemaDirectory);
188
+ configFingerprint = computeConfigFingerprint(options.projectRoot);
189
+ configBaselineSettled = false;
190
+ const serverLogger = {
191
+ error: (message) => {
192
+ server.config.logger.error(message);
193
+ },
194
+ info: (message) => {
195
+ server.config.logger.info(message);
196
+ },
197
+ warn: (message) => {
198
+ server.config.logger.warn(message);
199
+ }
200
+ };
201
+ let hadErrorOverlay = false;
202
+ const overlay = {
203
+ onError(error, message) {
204
+ hadErrorOverlay = true;
205
+ const loc = error instanceof CodegenDiagnosticError ? { column: error.column, file: error.file, line: error.line } : void 0;
206
+ const overlayMessage = loc === void 0 ? `[lunora] codegen failed: ${message}
207
+ (see terminal for full stack trace and file location)` : `[lunora] codegen failed: ${message}`;
208
+ devServer?.hot.send({
209
+ err: {
210
+ loc,
211
+ message: overlayMessage,
212
+ stack: error instanceof Error ? error.stack ?? "" : ""
213
+ },
214
+ type: "error"
215
+ });
216
+ }
217
+ };
218
+ const isInside = (path, directory) => path === directory || path.startsWith(directory + sep);
219
+ let closed = false;
220
+ let debounceTimer;
221
+ let cachedProject;
222
+ const invalidateGenerated = () => {
223
+ for (const environment of Object.values(server.environments)) {
224
+ const graph = environment.moduleGraph;
225
+ for (const moduleEntry of graph.idToModuleMap.values()) {
226
+ if (moduleEntry.id && isInside(moduleEntry.id, absoluteGeneratedDirectory)) {
227
+ graph.invalidateModule(moduleEntry);
228
+ }
229
+ }
230
+ }
231
+ };
232
+ const onChange = (file) => {
233
+ const normalized = resolve(file);
234
+ if (!isInside(normalized, absoluteSchemaDirectory)) {
235
+ return;
236
+ }
237
+ if (isInside(normalized, absoluteGeneratedDirectory)) {
238
+ return;
239
+ }
240
+ if (normalized.endsWith(`${sep}tsconfig.json`) || TSCONFIG_VARIANT_RE.test(normalized)) {
241
+ cachedProject = void 0;
242
+ return;
243
+ }
244
+ if (!normalized.endsWith(".ts")) {
245
+ return;
246
+ }
247
+ if (normalized.includes(`${sep}__tests__${sep}`) || normalized.endsWith(".test.ts") || normalized.endsWith(".spec.ts")) {
248
+ return;
249
+ }
250
+ if (debounceTimer) {
251
+ clearTimeout(debounceTimer);
252
+ }
253
+ debounceTimer = setTimeout(() => {
254
+ debounceTimer = void 0;
255
+ if (closed) {
256
+ return;
257
+ }
258
+ if (cachedProject === void 0) {
259
+ cachedProject = createCodegenProject(absoluteSchemaDirectory);
260
+ } else {
261
+ refreshCodegenProject(cachedProject, absoluteSchemaDirectory);
262
+ }
263
+ const outputDirectory = runCodegenSafely(options, serverLogger, overlay, cachedProject);
264
+ if (outputDirectory === void 0) {
265
+ cachedProject = void 0;
266
+ return;
267
+ }
268
+ absoluteGeneratedDirectory = outputDirectory;
269
+ invalidateGenerated();
270
+ notifyEnvironmentsAfterCodegen(server, normalized, hadErrorOverlay);
271
+ hadErrorOverlay = false;
272
+ }, DEBOUNCE_MS);
273
+ };
274
+ server.watcher.on("add", onChange);
275
+ server.watcher.on("change", onChange);
276
+ server.watcher.on("unlink", onChange);
277
+ const configWatchPaths = /* @__PURE__ */ new Set([
278
+ ...WRANGLER_FILES.map((name) => resolve(options.projectRoot, name)),
279
+ resolve(options.projectRoot, LUNORA_CONFIG_FILE)
280
+ ]);
281
+ for (const configPath of configWatchPaths) {
282
+ server.watcher.add(configPath);
283
+ }
284
+ const onConfigChange = (file) => {
285
+ if (!configWatchPaths.has(resolve(file))) {
286
+ return;
287
+ }
288
+ if (restartInFlight) {
289
+ return;
290
+ }
291
+ const nextFingerprint = computeConfigFingerprint(options.projectRoot);
292
+ if (!configBaselineSettled) {
293
+ configFingerprint = nextFingerprint;
294
+ return;
295
+ }
296
+ if (configFingerprint === void 0) {
297
+ configFingerprint = nextFingerprint;
298
+ return;
299
+ }
300
+ if (nextFingerprint === configFingerprint) {
301
+ return;
302
+ }
303
+ configFingerprint = nextFingerprint;
304
+ restartInFlight = true;
305
+ server.config.logger.info(`${LUNORA_TAG} ${basename(resolve(file))} changed — restarting dev server`);
306
+ Promise.resolve(server.restart()).finally(() => {
307
+ restartInFlight = false;
308
+ }).catch((error) => {
309
+ const message = error instanceof Error ? error.message : String(error);
310
+ server.config.logger.error(
311
+ `${LUNORA_TAG} dev server restart failed: ${message} — keeping the running server; re-save your config to retry.`
312
+ );
313
+ server.hot.send({ err: { loc: void 0, message: `[lunora] dev server restart failed: ${message}`, stack: "" }, type: "error" });
314
+ });
315
+ };
316
+ server.watcher.on("add", onConfigChange);
317
+ server.watcher.on("change", onConfigChange);
318
+ server.watcher.on("unlink", onConfigChange);
319
+ const teardown = () => {
320
+ if (closed) {
321
+ return;
322
+ }
323
+ closed = true;
324
+ cachedProject = void 0;
325
+ if (debounceTimer) {
326
+ clearTimeout(debounceTimer);
327
+ debounceTimer = void 0;
328
+ }
329
+ server.watcher.off("add", onChange);
330
+ server.watcher.off("change", onChange);
331
+ server.watcher.off("unlink", onChange);
332
+ server.watcher.off("add", onConfigChange);
333
+ server.watcher.off("change", onConfigChange);
334
+ server.watcher.off("unlink", onConfigChange);
335
+ };
336
+ return () => {
337
+ registerDevServerClose(server, pendingMiddlewareTeardowns, teardown);
338
+ };
339
+ },
340
+ buildEnd() {
341
+ runPendingClose(pendingMiddlewareTeardowns, this.environment);
342
+ },
343
+ name: "lunora:codegen"
344
+ };
345
+ };
346
+
347
+ export { codegenPlugin as default };
@@ -0,0 +1,50 @@
1
+ import { discoverContainerInfo, streamContainerLogs } from '@lunora/config';
2
+ import { l as lunoraLine } from './log-BjO9EWah.mjs';
3
+
4
+ const containerLogsPlugin = (options) => {
5
+ let handle;
6
+ const closeHandle = () => {
7
+ handle?.close();
8
+ handle = void 0;
9
+ };
10
+ return {
11
+ apply: "serve",
12
+ // Fires on `server.close()` for both the normal and middleware-mode dev
13
+ // servers, so the Docker poll loop is torn down even when there is no
14
+ // `httpServer` to listen on (middleware mode).
15
+ buildEnd() {
16
+ closeHandle();
17
+ },
18
+ configureServer(server) {
19
+ if (handle || process.env.LUNORA_CONTAINER_LOGS === "0") {
20
+ return;
21
+ }
22
+ const discovery = discoverContainerInfo(options.projectRoot, options.schemaDir);
23
+ const containers = discovery.containers.map((container) => {
24
+ return { className: container.className, exportName: container.exportName };
25
+ });
26
+ if (containers.length === 0) {
27
+ return;
28
+ }
29
+ const { logger } = server.config;
30
+ handle = streamContainerLogs({
31
+ containers,
32
+ onLine: (line) => {
33
+ const text = lunoraLine(`container:${line.name} ${line.text}`);
34
+ if (line.level === "error") {
35
+ logger.warn(text);
36
+ } else {
37
+ logger.info(text);
38
+ }
39
+ },
40
+ onUnavailable: (message) => {
41
+ logger.warn(lunoraLine(`container: Docker engine unreachable — container logs unavailable (${message})`));
42
+ }
43
+ });
44
+ server.httpServer?.once("close", closeHandle);
45
+ },
46
+ name: "lunora:container-logs"
47
+ };
48
+ };
49
+
50
+ export { containerLogsPlugin as default };
@@ -0,0 +1,84 @@
1
+ import { claimDevServerState, DEV_LOG_FILE_ENV, DEV_DAEMON_ENV, DEV_HANDOFF_ENV, clearDevServerState } from '@lunora/config';
2
+ import { l as lunoraLine } from './log-BjO9EWah.mjs';
3
+ import { r as runPendingClose, a as registerDevServerClose } from './server-close-DKDp7YTU.mjs';
4
+
5
+ const TRAILING_SLASH = /\/$/;
6
+ const resolveLocalUrl = (server) => {
7
+ const resolved = server.resolvedUrls?.local[0];
8
+ if (resolved !== void 0) {
9
+ return resolved.replace(TRAILING_SLASH, "");
10
+ }
11
+ const address = server.httpServer?.address();
12
+ if (address !== null && typeof address === "object") {
13
+ return `http://localhost:${String(address.port)}`;
14
+ }
15
+ return void 0;
16
+ };
17
+ const devStatePlugin = (options) => {
18
+ let recorded = false;
19
+ const pendingMiddlewareClears = /* @__PURE__ */ new Map();
20
+ return {
21
+ apply: "serve",
22
+ configureServer(server) {
23
+ const root = options.projectRoot;
24
+ const record = () => {
25
+ if (recorded) {
26
+ return;
27
+ }
28
+ const url = resolveLocalUrl(server);
29
+ if (url === void 0) {
30
+ return;
31
+ }
32
+ const handoffPid = Number(process.env[DEV_HANDOFF_ENV]);
33
+ const claim = claimDevServerState(
34
+ root,
35
+ {
36
+ background: process.env[DEV_DAEMON_ENV] === "1",
37
+ logFile: process.env[DEV_LOG_FILE_ENV],
38
+ mode: "vite",
39
+ pid: process.pid,
40
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
41
+ url
42
+ },
43
+ Number.isInteger(handoffPid) && handoffPid > 0 ? { supersedePid: handoffPid } : void 0
44
+ );
45
+ if (!claim.ok) {
46
+ if (claim.existing !== void 0) {
47
+ server.config.logger.warn(
48
+ lunoraLine(
49
+ `another dev server is already recorded at ${claim.existing.url} (pid ${String(claim.existing.pid)}) — leaving .lunora/dev.json untouched`
50
+ )
51
+ );
52
+ }
53
+ return;
54
+ }
55
+ recorded = true;
56
+ };
57
+ const clearOnClose = () => {
58
+ if (recorded) {
59
+ clearDevServerState(root, process.pid);
60
+ recorded = false;
61
+ }
62
+ };
63
+ registerDevServerClose(server, pendingMiddlewareClears, clearOnClose);
64
+ return () => {
65
+ if (typeof server.printUrls === "function") {
66
+ const printUrls = server.printUrls.bind(server);
67
+ server.printUrls = () => {
68
+ printUrls();
69
+ record();
70
+ };
71
+ }
72
+ server.httpServer?.once("listening", () => {
73
+ setTimeout(record, 0);
74
+ });
75
+ };
76
+ },
77
+ buildEnd() {
78
+ runPendingClose(pendingMiddlewareClears, this.environment);
79
+ },
80
+ name: "lunora:dev-state"
81
+ };
82
+ };
83
+
84
+ export { devStatePlugin as default };
@@ -0,0 +1,19 @@
1
+ import { ensureDevVariables, createConfirm, fillDevSecrets } from '@lunora/config';
2
+ import { l as lunoraLine } from './log-BjO9EWah.mjs';
3
+
4
+ const devVariablesPlugin = (options) => {
5
+ return {
6
+ apply: "serve",
7
+ async configResolved() {
8
+ const info = (message) => {
9
+ console.info(lunoraLine(message));
10
+ };
11
+ await ensureDevVariables({ confirm: createConfirm("[lunora] "), cwd: options.projectRoot, info });
12
+ fillDevSecrets({ cwd: options.projectRoot, info });
13
+ },
14
+ enforce: "pre",
15
+ name: "lunora:dev-vars"
16
+ };
17
+ };
18
+
19
+ export { devVariablesPlugin as default };