@guren/server 2.28.1 → 2.29.0

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.
@@ -0,0 +1,59 @@
1
+ import type { Context } from 'hono';
2
+ import type { RuntimeErrorCollector } from './runtime-error-capture.js';
3
+ export { RUNTIME_ERRORS_BINDING, RUNTIME_ERRORS_PATH } from './runtime-error-capture.js';
4
+ export interface RuntimeErrorQuery {
5
+ sessionId?: string;
6
+ after?: number;
7
+ limit?: number;
8
+ }
9
+ export interface RuntimeErrorEvent {
10
+ sessionId: string;
11
+ sequence: number;
12
+ occurredAt: string;
13
+ method: string;
14
+ route?: {
15
+ method: string;
16
+ pattern: string;
17
+ name?: string;
18
+ };
19
+ correlation: 'matched' | 'ambiguous' | 'unavailable';
20
+ status: number;
21
+ category: 'server-error';
22
+ frames: Array<{
23
+ file: string;
24
+ line?: number;
25
+ column?: number;
26
+ }>;
27
+ }
28
+ export interface RuntimeErrorResult {
29
+ schemaVersion: 1;
30
+ status: 'available';
31
+ sessionId: string;
32
+ startedAt: string;
33
+ events: RuntimeErrorEvent[];
34
+ nextCursor: {
35
+ sessionId: string;
36
+ after: number;
37
+ };
38
+ dropped: number;
39
+ cursorExpired: boolean;
40
+ }
41
+ export declare class RuntimeErrorBuffer implements RuntimeErrorCollector {
42
+ private readonly root;
43
+ private readonly now;
44
+ private sessionId;
45
+ private startedAt;
46
+ private sequence;
47
+ private dropped;
48
+ private bytes;
49
+ private events;
50
+ constructor(root: string, now?: () => number);
51
+ reset(): void;
52
+ /** Called through `captureRuntimeError()`, which has already checked the status and guards the call. */
53
+ capture(error: Error, ctx: Context, status: number): void;
54
+ record(error: Error, detail: Pick<RuntimeErrorEvent, 'method' | 'route' | 'correlation' | 'status'>): void;
55
+ read(query?: RuntimeErrorQuery): RuntimeErrorResult;
56
+ private evict;
57
+ private expire;
58
+ private frames;
59
+ }
@@ -295,6 +295,8 @@ export declare class Router<in M extends string = never> {
295
295
  controller?: ControllerConstructor;
296
296
  action?: string;
297
297
  }>;
298
+ /** Model identities behind the serialized binding names, indexed like definitions (RFC 0032). */
299
+ registeredModelBindings(): ReadonlyArray<Record<string, BindableModel>>;
298
300
  /**
299
301
  * Every alias and group resolved, and each route's chain in `mount()` order,
300
302
  * index-aligned with {@link definitions} (RFC 0026 §3). Like `definitions()`,
@@ -0,0 +1,25 @@
1
+ //#region src/http/request-container.ts
2
+ /**
3
+ * Context variable the serving Application's container is stamped under
4
+ * (RFC 0023 §2). The stamp is the first middleware `Application` mounts, so
5
+ * nothing an app registers runs ahead of it. The one place a middleware
6
+ * reaches its app's container without holding the app.
7
+ */
8
+ const CONTAINER_CONTEXT_KEY = "guren.container";
9
+ /**
10
+ * The container of the Application serving `ctx`, or undefined off an
11
+ * Application (bare Hono). Judged by shape rather than `instanceof`: a test
12
+ * double answering every key must not pass as a container.
13
+ */
14
+ function tryGetRequestContainer(ctx) {
15
+ const container = ctx.get(CONTAINER_CONTEXT_KEY);
16
+ return typeof container?.makeOptional === "function" ? container : void 0;
17
+ }
18
+ /** The container of the Application serving `ctx`; throws off an Application (bare Hono). */
19
+ function getRequestContainer(ctx) {
20
+ const container = tryGetRequestContainer(ctx);
21
+ if (!container) throw new Error("No Application container on this request. The container is stamped by Application; a bare Hono app has none — pass the service explicitly there.");
22
+ return container;
23
+ }
24
+ //#endregion
25
+ export { getRequestContainer as n, tryGetRequestContainer as r, CONTAINER_CONTEXT_KEY as t };
@@ -1,8 +1,8 @@
1
1
  import { a as trimTrailingSlashes, n as isRealPathWithin, t as isPathWithin } from "../contained-path-BkNSBljW.js";
2
2
  import { n as parseImportMap } from "../inertia-defaults-BjrcT7za.js";
3
3
  import { n as hash } from "../Hash-D2DFd8xX.js";
4
- import { a as getManifestCss, c as isViteProduction, d as startViteDevServer, i as clientManifestCandidates, l as loadViteManifest, o as getManifestFile, r as PUBLIC_ASSETS_URL_PREFIX, u as normalizeDevServerUrl } from "../vite-manifest-wPxfAzjW.js";
5
- import { r as logDevServerBanner, t as GUREN_ASCII_ART } from "../dev-banner-DnaL8Ku6.js";
4
+ import { a as getManifestCss, c as isViteProduction, d as startViteDevServer, i as clientManifestCandidates, l as loadViteManifest, o as getManifestFile, r as PUBLIC_ASSETS_URL_PREFIX, u as normalizeDevServerUrl } from "../vite-manifest-DO0pU1vm.js";
5
+ import { r as logDevServerBanner, t as GUREN_ASCII_ART } from "../dev-banner-BAXzolUl.js";
6
6
  import { createRequire } from "node:module";
7
7
  import { dirname, extname, join, resolve } from "node:path";
8
8
  import { fileURLToPath } from "node:url";
@@ -0,0 +1,48 @@
1
+ import { t as createLoopbackGuard } from "./loopback-guard-CG8xB4v0.js";
2
+ import { r as tryGetRequestContainer } from "./request-container-BbuH0JJy.js";
3
+ //#region src/mcp/endpoint.ts
4
+ const MCP_ENDPOINT_PATH = "/_guren/mcp";
5
+ /**
6
+ * Whether the MCP endpoint is mounted: opt-in via `GUREN_MCP=1`, never in
7
+ * production (it exposes project introspection and code generation). The env
8
+ * reads are plain member access on purpose: the deploy plugins settle NODE_ENV
9
+ * with `--define`, which matches one exact expression, so an optional chain
10
+ * leaves a runtime read that reopens the gate on workerd; `tests/mcp/endpoint.test.ts` pins the form.
11
+ */
12
+ function isMcpEndpointEnabled() {
13
+ if (typeof process === "undefined") return false;
14
+ if (process.env.NODE_ENV === "production") return false;
15
+ return process.env.GUREN_MCP === "1";
16
+ }
17
+ /**
18
+ * Restricts the MCP endpoint to the developer's own machine. The endpoint is
19
+ * CSRF-exempt (agent clients carry no token), so this guard takes over: a web
20
+ * page is rejected unless its `Origin` is loopback, and every caller unless its
21
+ * socket peer is. It fails closed when the runtime reports no peer at all.
22
+ */
23
+ function createMcpAccessGuard() {
24
+ return createLoopbackGuard("the MCP endpoint");
25
+ }
26
+ //#endregion
27
+ //#region src/mcp/runtime-error-capture.ts
28
+ const RUNTIME_ERRORS_BINDING = "dev.runtimeErrors";
29
+ const RUNTIME_ERRORS_PATH = "/_guren/runtime/errors";
30
+ let loading;
31
+ /**
32
+ * The buffer module while the collector is enabled, else undefined. The NODE_ENV
33
+ * read is plain member access so a deploy build's `--define` settles the branch
34
+ * and the bundler drops the `import()` with it; `isMcpEndpointEnabled()` alone is
35
+ * a call no define can settle. `tests/mcp/runtime-errors.test.ts` pins the form.
36
+ */
37
+ function loadRuntimeErrorsModule() {
38
+ if (typeof process !== "undefined" && process.env.NODE_ENV !== "production" && isMcpEndpointEnabled()) return loading ??= import("./runtime-errors-DOPBX0Ox.js");
39
+ }
40
+ /** Only ExceptionHandler calls this, after applying its dontReport policy. */
41
+ function captureRuntimeError(error, ctx, status) {
42
+ if (!isMcpEndpointEnabled() || status < 500 || status > 599 || !Number.isInteger(status)) return;
43
+ try {
44
+ tryGetRequestContainer(ctx)?.makeOptional(RUNTIME_ERRORS_BINDING)?.capture(error, ctx, status);
45
+ } catch {}
46
+ }
47
+ //#endregion
48
+ export { MCP_ENDPOINT_PATH as a, loadRuntimeErrorsModule as i, RUNTIME_ERRORS_PATH as n, createMcpAccessGuard as o, captureRuntimeError as r, isMcpEndpointEnabled as s, RUNTIME_ERRORS_BINDING as t };
@@ -0,0 +1,135 @@
1
+ import { n as RUNTIME_ERRORS_PATH, t as RUNTIME_ERRORS_BINDING } from "./runtime-error-capture-BclelWhA.js";
2
+ import { r as tryGetRequestContainer } from "./request-container-BbuH0JJy.js";
3
+ import { realpathSync, statSync } from "node:fs";
4
+ import { routePath } from "hono/route";
5
+ //#region src/mcp/runtime-errors.ts
6
+ var RuntimeErrorBuffer = class {
7
+ root;
8
+ now;
9
+ sessionId = crypto.randomUUID();
10
+ startedAt;
11
+ sequence = 0;
12
+ dropped = 0;
13
+ bytes = 0;
14
+ events = [];
15
+ constructor(root, now = Date.now) {
16
+ this.root = root;
17
+ this.now = now;
18
+ this.startedAt = new Date(now()).toISOString();
19
+ }
20
+ reset() {
21
+ this.sessionId = crypto.randomUUID();
22
+ this.startedAt = new Date(this.now()).toISOString();
23
+ this.sequence = this.dropped = this.bytes = 0;
24
+ this.events = [];
25
+ }
26
+ /** Called through `captureRuntimeError()`, which has already checked the status and guards the call. */
27
+ capture(error, ctx, status) {
28
+ const pattern = routePath(ctx);
29
+ const matches = (tryGetRequestContainer(ctx)?.makeOptional("router")?.definitions() ?? []).filter((entry) => entry.path === pattern && (entry.method === ctx.req.method || entry.method === "ALL"));
30
+ const route = matches.length === 1 ? matches[0] : void 0;
31
+ this.record(error, {
32
+ method: ctx.req.method,
33
+ status,
34
+ correlation: matches.length === 1 ? "matched" : matches.length > 1 ? "ambiguous" : "unavailable",
35
+ ...route ? { route: {
36
+ method: route.method,
37
+ pattern: route.path,
38
+ ...route.name ? { name: route.name } : {}
39
+ } } : {}
40
+ });
41
+ }
42
+ record(error, detail) {
43
+ const at = this.now();
44
+ this.expire(at);
45
+ const event = {
46
+ sessionId: this.sessionId,
47
+ sequence: ++this.sequence,
48
+ occurredAt: new Date(at).toISOString(),
49
+ method: /^(GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS|CONNECT|TRACE|QUERY)$/.test(detail.method) ? detail.method : "UNKNOWN",
50
+ ...detail.route ? { route: detail.route } : {},
51
+ correlation: detail.correlation,
52
+ status: detail.status,
53
+ category: "server-error",
54
+ frames: this.frames(error.stack)
55
+ };
56
+ const bytes = new TextEncoder().encode(JSON.stringify(event)).length;
57
+ if (bytes > 8192) {
58
+ this.dropped++;
59
+ return;
60
+ }
61
+ this.events.push({
62
+ event,
63
+ at,
64
+ bytes
65
+ });
66
+ this.bytes += bytes;
67
+ while (this.events.length > 100 || this.bytes > 262144) this.evict();
68
+ }
69
+ read(query = {}) {
70
+ const after = query.after ?? 0;
71
+ const limit = query.limit ?? 20;
72
+ if (!Number.isSafeInteger(after) || after < 0 || !Number.isSafeInteger(limit) || limit < 1 || limit > 100 || query.sessionId !== void 0 && typeof query.sessionId !== "string") throw new Error("Invalid runtime error cursor or limit.");
73
+ this.expire(this.now());
74
+ const different = query.sessionId !== void 0 && query.sessionId !== this.sessionId;
75
+ const start = different ? 0 : after;
76
+ const events = this.events.filter(({ event }) => event.sequence > start).slice(0, limit).map(({ event }) => structuredClone(event));
77
+ const earliest = this.events[0]?.event.sequence ?? this.sequence + 1;
78
+ return {
79
+ schemaVersion: 1,
80
+ status: "available",
81
+ sessionId: this.sessionId,
82
+ startedAt: this.startedAt,
83
+ events,
84
+ nextCursor: {
85
+ sessionId: this.sessionId,
86
+ after: events.at(-1)?.sequence ?? this.sequence
87
+ },
88
+ dropped: this.dropped,
89
+ cursorExpired: different || start < earliest - 1 || start > this.sequence
90
+ };
91
+ }
92
+ evict() {
93
+ const removed = this.events.shift();
94
+ if (removed) {
95
+ this.bytes -= removed.bytes;
96
+ this.dropped++;
97
+ }
98
+ }
99
+ expire(at) {
100
+ while (this.events[0] && at - this.events[0].at >= 9e5) this.evict();
101
+ }
102
+ frames(stack) {
103
+ const root = this.root.replace(/\\/g, "/").replace(/\/$/, "") + "/";
104
+ const frames = [];
105
+ let actualRoot;
106
+ try {
107
+ actualRoot = realpathSync(this.root).replace(/\\/g, "/").replace(/\/$/, "") + "/";
108
+ } catch {
109
+ return frames;
110
+ }
111
+ for (const line of (stack ?? "").slice(0, 32768).split("\n").slice(1, 41)) {
112
+ const match = line.match(/(?:\(|\s)((?:file:\/\/)?(?:\/|[A-Za-z]:[\\/])[^\n]*):([0-9]+):([0-9]+)\)?$/);
113
+ if (!match) continue;
114
+ const path = match[1].replace(/^file:\/\//, "").replace(/\\/g, "/");
115
+ if (!path.startsWith(root)) continue;
116
+ const file = path.slice(root.length);
117
+ if (!/^[\w./@ -]+\.(?:[cm]?[jt]sx?)$/.test(file) || file.split("/").some((part) => part === ".." || part === "node_modules" || part.startsWith("."))) continue;
118
+ try {
119
+ const actual = realpathSync(path).replace(/\\/g, "/");
120
+ if (!actual.startsWith(actualRoot) || !statSync(actual).isFile()) continue;
121
+ } catch {
122
+ continue;
123
+ }
124
+ frames.push({
125
+ file,
126
+ line: Number(match[2]),
127
+ column: Number(match[3])
128
+ });
129
+ if (frames.length === 10) break;
130
+ }
131
+ return frames;
132
+ }
133
+ };
134
+ //#endregion
135
+ export { RUNTIME_ERRORS_BINDING, RUNTIME_ERRORS_PATH, RuntimeErrorBuffer };
@@ -0,0 +1,391 @@
1
+ import { a as trimTrailingSlashes } from "./contained-path-BkNSBljW.js";
2
+ import { resolve } from "node:path";
3
+ import { readFileSync } from "node:fs";
4
+ //#region src/http/server-lifecycle.ts
5
+ const MANAGED_VITE_ENV_FLAG = "GUREN_MANAGED_VITE_DEV_SERVER";
6
+ const DEFAULT_DEV_ENTRY_PATH = "/resources/js/dev-entry.ts";
7
+ function clearManagedViteEnv() {
8
+ if (typeof process === "undefined") return;
9
+ if (process.env["GUREN_MANAGED_VITE_DEV_SERVER"] === "1") {
10
+ delete process.env.VITE_DEV_SERVER_URL;
11
+ if (process.env.GUREN_INERTIA_ENTRY?.endsWith(DEFAULT_DEV_ENTRY_PATH)) delete process.env.GUREN_INERTIA_ENTRY;
12
+ }
13
+ delete process.env[MANAGED_VITE_ENV_FLAG];
14
+ }
15
+ function normalizeDevEntryUrl(baseUrl) {
16
+ return `${baseUrl.replace(/\/$/u, "")}${DEFAULT_DEV_ENTRY_PATH}`;
17
+ }
18
+ function syncManagedInertiaDevEntry(devServerUrl) {
19
+ if (typeof process === "undefined") return;
20
+ const nextEntry = normalizeDevEntryUrl(devServerUrl);
21
+ const currentEntry = process.env.GUREN_INERTIA_ENTRY;
22
+ if (!currentEntry || currentEntry.endsWith(DEFAULT_DEV_ENTRY_PATH)) process.env.GUREN_INERTIA_ENTRY = nextEntry;
23
+ }
24
+ function getGlobalState() {
25
+ return globalThis;
26
+ }
27
+ /**
28
+ * How long a server `stop()` may take before shutdown stops waiting. Abandoning
29
+ * this wait is safe in a way abandoning a Vite close is not: the socket has
30
+ * already stopped accepting connections, so what is left is a drain.
31
+ */
32
+ function bunStopTimeoutMs() {
33
+ return shutdownTimeoutMs("GUREN_BUN_STOP_TIMEOUT_MS");
34
+ }
35
+ /**
36
+ * How long a `bun --hot` reload waits on the server it replaces. That stop is
37
+ * forced, and the hot-reload teardown has already server-closed every broadcast
38
+ * WebSocket, so nothing is draining; on Bun 1.3.x `stop()` then never resolves
39
+ * (1.4.0 resolves at once). Quoted in docs/{en,ja}/guides/architecture.md.
40
+ */
41
+ const HOT_RELOAD_STOP_TIMEOUT_MS = 250;
42
+ function defaultStopBound() {
43
+ return {
44
+ timeoutMs: bunStopTimeoutMs(),
45
+ warn: true
46
+ };
47
+ }
48
+ /**
49
+ * Silent: on Bun 1.3.x it is hit on every reload, and there is nothing to
50
+ * report. `GUREN_BUN_STOP_TIMEOUT_MS` can only shorten it: it is set for a
51
+ * production drain, which a reload never is.
52
+ */
53
+ function hotReloadStopBound() {
54
+ return {
55
+ timeoutMs: Math.min(bunStopTimeoutMs(), HOT_RELOAD_STOP_TIMEOUT_MS),
56
+ warn: false
57
+ };
58
+ }
59
+ /**
60
+ * A positive integer of milliseconds, or 5000 when unset or unparseable. One
61
+ * parse for both bounds, so they cannot drift apart.
62
+ */
63
+ function shutdownTimeoutMs(envName) {
64
+ const parsed = typeof process !== "undefined" ? Number.parseInt(process.env[envName] ?? "", 10) : NaN;
65
+ return Number.isInteger(parsed) && parsed > 0 ? parsed : 5e3;
66
+ }
67
+ /**
68
+ * Awaits `work`, giving up after `timeoutMs`. Resolves either way: every caller
69
+ * is a shutdown path, and one that hangs is worse than one that gives up.
70
+ */
71
+ async function awaitBounded(work, timeoutMs, onTimeout) {
72
+ let timer;
73
+ try {
74
+ if (await Promise.race([work.then(() => false), new Promise((resolve) => {
75
+ timer = setTimeout(() => resolve(true), timeoutMs);
76
+ })])) onTimeout(timeoutMs);
77
+ } finally {
78
+ clearTimeout(timer);
79
+ }
80
+ }
81
+ /** `stop()` bounded by `bound` ({@link bunStopTimeoutMs} by default), warning rather than throwing. */
82
+ async function stopBunServerBounded(server, closeActiveConnections, bound = defaultStopBound()) {
83
+ await awaitBounded((async () => {
84
+ try {
85
+ await server.stop?.(closeActiveConnections);
86
+ } catch (error) {
87
+ console.warn("Failed to stop Bun server:", error);
88
+ }
89
+ })(), bound.timeoutMs, (timeoutMs) => {
90
+ if (!bound.warn) return;
91
+ console.warn(`Bun server did not stop within ${timeoutMs}ms — no longer waiting on it. In-flight requests may still be draining.`);
92
+ });
93
+ }
94
+ async function stopActiveBunServer(closeActiveConnections = false, bound) {
95
+ const state = getGlobalState();
96
+ const previous = state.__gurenActiveServer;
97
+ if (!previous?.stop) {
98
+ state.__gurenActiveServer = void 0;
99
+ return;
100
+ }
101
+ try {
102
+ await stopBunServerBounded(previous, closeActiveConnections, bound);
103
+ } finally {
104
+ releaseActiveBunServer(previous);
105
+ }
106
+ }
107
+ function setActiveBunServer(server) {
108
+ getGlobalState().__gurenActiveServer = server;
109
+ }
110
+ /**
111
+ * Gives up the process-wide slot, but only while it still holds `server`: a
112
+ * `listen()` that completed inside the caller's await has repointed it at a
113
+ * live server, which clearing would strip of its exit teardown.
114
+ */
115
+ function releaseActiveBunServer(server) {
116
+ if (getGlobalState().__gurenActiveServer === server) setActiveBunServer();
117
+ }
118
+ /**
119
+ * Attaches one SIGINT/SIGTERM/exit trio and returns the disposer for it. A
120
+ * boolean-guarded registrar would leave handlers attached and let the next
121
+ * `listen()` stack a second set on top — and `process.once` fires in
122
+ * registration order, so a stale handler's `process.exit()` can end the process
123
+ * ahead of the live set's shutdown.
124
+ */
125
+ function registerProcessTeardown(onSignal, onExit) {
126
+ process.once("SIGINT", onSignal);
127
+ process.once("SIGTERM", onSignal);
128
+ process.on("exit", onExit);
129
+ return () => {
130
+ process.off("SIGINT", onSignal);
131
+ process.off("SIGTERM", onSignal);
132
+ process.off("exit", onExit);
133
+ };
134
+ }
135
+ /**
136
+ * How long a Vite `close()` may take before shutdown abandons it — a browser tab
137
+ * holding its HMR socket can keep that wait alive indefinitely. A stranded asset
138
+ * server is recoverable noise; a `listen()` that never returns is not.
139
+ */
140
+ function viteCloseTimeoutMs() {
141
+ return shutdownTimeoutMs("GUREN_VITE_CLOSE_TIMEOUT_MS");
142
+ }
143
+ /**
144
+ * `close()` bounded by {@link viteCloseTimeoutMs}: resolves once the server
145
+ * closed, failed (warned), or ran out the clock (warned, abandoned).
146
+ */
147
+ async function closeViteDevServerBounded(server) {
148
+ await awaitBounded((async () => {
149
+ try {
150
+ await server.close();
151
+ } catch (error) {
152
+ console.warn("Failed to stop Vite dev server:", error);
153
+ }
154
+ })(), viteCloseTimeoutMs(), (timeoutMs) => {
155
+ console.warn(`Vite dev server did not close within ${timeoutMs}ms — abandoning it. A stale asset server may still hold its port.`);
156
+ });
157
+ }
158
+ /**
159
+ * Closes the managed Vite dev server whoever owns it. Only `listen()`'s restart
160
+ * path calls this — the one case where an owner's claim does not survive.
161
+ */
162
+ async function stopActiveViteDevServer() {
163
+ const previous = getGlobalState().__gurenActiveViteDevServer;
164
+ try {
165
+ if (previous) await closeViteDevServerBounded(previous.server);
166
+ } finally {
167
+ previous?.disposeTeardown();
168
+ if (getGlobalState().__gurenActiveViteDevServer === previous) setActiveViteDevServer();
169
+ }
170
+ }
171
+ function publishManagedViteEnv(localUrl) {
172
+ if (typeof process === "undefined") return;
173
+ process.env.VITE_DEV_SERVER_URL = localUrl;
174
+ process.env[MANAGED_VITE_ENV_FLAG] = "1";
175
+ syncManagedInertiaDevEntry(localUrl);
176
+ }
177
+ /**
178
+ * The one write point for the active-record slot. `VITE_DEV_SERVER_URL` and the
179
+ * managed flag travel with it, so a stale close cannot unpublish an adopter's
180
+ * URL while its record stays live, or the reverse.
181
+ */
182
+ function setActiveViteDevServer(active) {
183
+ getGlobalState().__gurenActiveViteDevServer = active;
184
+ if (active) publishManagedViteEnv(active.localUrl);
185
+ else clearManagedViteEnv();
186
+ }
187
+ /**
188
+ * The managed Vite dev server a previous `listen()` left running. Reusing it
189
+ * keeps the browser's HMR socket connected and skips the
190
+ * {@link viteCloseTimeoutMs} wait. Explicit `vite` options veto reuse: the
191
+ * running server was built from the *previous* call's options.
192
+ */
193
+ function reusableActiveViteDevServer(viteOption) {
194
+ if (typeof viteOption === "object") return;
195
+ const active = getGlobalState().__gurenActiveViteDevServer;
196
+ if (!active || !active.server.httpServer?.listening) return;
197
+ return active;
198
+ }
199
+ /**
200
+ * Closes the managed Vite dev server, but only while this application still
201
+ * owns it: another `listen()` may have adopted the same object, and closing it
202
+ * then would take the asset server out from under an app serving from it. The
203
+ * slot's record is the one place that distinction exists.
204
+ */
205
+ async function closeOwnedViteDevServer(owner) {
206
+ const active = getGlobalState().__gurenActiveViteDevServer;
207
+ if (active?.owner !== owner) return;
208
+ try {
209
+ await closeViteDevServerBounded(active.server);
210
+ } finally {
211
+ active.disposeTeardown();
212
+ if (getGlobalState().__gurenActiveViteDevServer === active) setActiveViteDevServer();
213
+ }
214
+ }
215
+ function registerViteTeardown(owner) {
216
+ if (typeof process === "undefined") return () => {};
217
+ return registerProcessTeardown(() => {
218
+ closeOwnedViteDevServer(owner).then(() => process.exit(0)).catch(() => process.exit(1));
219
+ }, () => {
220
+ const active = getGlobalState().__gurenActiveViteDevServer;
221
+ if (active?.owner === owner) active.server.close();
222
+ });
223
+ }
224
+ function registerBunTeardown() {
225
+ if (typeof process === "undefined") return () => {};
226
+ return registerProcessTeardown(() => {
227
+ stopActiveBunServer().then(() => process.exit(0)).catch(() => process.exit(1));
228
+ }, () => {
229
+ stopActiveBunServer();
230
+ });
231
+ }
232
+ function adoptViteDevServer(owner, viteServer, localUrl) {
233
+ const displaced = getGlobalState().__gurenActiveViteDevServer;
234
+ displaced?.disposeTeardown();
235
+ if (displaced && displaced.server !== viteServer) closeViteDevServerBounded(displaced.server);
236
+ setActiveViteDevServer({
237
+ server: viteServer,
238
+ localUrl,
239
+ owner,
240
+ disposeTeardown: registerViteTeardown(owner)
241
+ });
242
+ }
243
+ //#endregion
244
+ //#region src/http/vite-dev-server.ts
245
+ /**
246
+ * Build the inline config the managed dev server starts with. `server.host` is
247
+ * left undefined unless asked for, so Vite's config merge drops it and the
248
+ * project's own `vite.config.ts` decides.
249
+ */
250
+ function resolveViteDevServerConfig(options = {}) {
251
+ const { root = process.cwd(), config = {}, host, port } = options;
252
+ return {
253
+ clearScreen: false,
254
+ ...config,
255
+ root: config.root ?? root,
256
+ server: {
257
+ host,
258
+ port,
259
+ ...config.server
260
+ }
261
+ };
262
+ }
263
+ async function startViteDevServer(options = {}) {
264
+ const { host, port } = options;
265
+ const { createServer } = await import("vite");
266
+ const server = await createServer(resolveViteDevServerConfig(options));
267
+ try {
268
+ await server.listen();
269
+ const resolved = server.resolvedUrls;
270
+ const localUrls = resolved?.local?.length ? resolved.local : [`http://${typeof host === "string" ? host : "localhost"}:${server.config.server.port ?? port ?? 5173}`];
271
+ const networkUrls = resolved?.network ?? [];
272
+ return {
273
+ server,
274
+ localUrl: localUrls[0],
275
+ networkUrls
276
+ };
277
+ } catch (error) {
278
+ await closeViteDevServerBounded(server);
279
+ throw error;
280
+ }
281
+ }
282
+ //#endregion
283
+ //#region src/http/vite-manifest.ts
284
+ /**
285
+ * The one rule for how Vite build output is found and addressed, shared by the
286
+ * Inertia asset wiring (`inertia-assets.ts`) and `viteAsset()` (`vite-assets.ts`,
287
+ * RFC 0014) so the two cannot drift: what counts as a manifest, where one may
288
+ * live, which URL prefix serves the hashed files, and what "the dev server is
289
+ * on" means.
290
+ */
291
+ /**
292
+ * Where `configureInertiaAssets` serves hashed build output from. The deploy
293
+ * builds restate it as `CLIENT_ASSETS_URL_PREFIX` in @guren/core's
294
+ * internal/deploy-build.ts; tests/http/vite-manifest.test.ts pins the two equal.
295
+ */
296
+ const PUBLIC_ASSETS_URL_PREFIX = "/public/assets/";
297
+ /** The Vite default the framework assumes when no dev-server URL is set. */
298
+ const DEFAULT_DEV_SERVER_URL = "http://localhost:5173";
299
+ /**
300
+ * Production for *asset* purposes: `NODE_ENV` says so and no dev server is
301
+ * configured — a configured dev server means dev asset serving even when
302
+ * `NODE_ENV` is `production` (E2E runs do exactly this).
303
+ */
304
+ function isViteProduction(devServerUrl = process.env.VITE_DEV_SERVER_URL) {
305
+ return process.env.NODE_ENV === "production" && typeof devServerUrl !== "string";
306
+ }
307
+ function normalizeDevServerUrl(value) {
308
+ if (!value) return value;
309
+ const trimmed = value.trim();
310
+ if (!trimmed) return trimmed;
311
+ const stripped = trimTrailingSlashes(trimmed);
312
+ return stripped.length > 0 ? stripped : "/";
313
+ }
314
+ /**
315
+ * Candidate client-manifest locations, `.vite/manifest.json` first: Vite >= 5
316
+ * writes it there, so a flat `manifest.json` is likely a stale leftover. The
317
+ * deploy plugins order the same pair through `@guren/core`'s deploy-build
318
+ * helpers and must agree, or an app with both layouts resolves different asset
319
+ * versions after a serverless deploy; `tests/http/vite-manifest.test.ts` pins it.
320
+ */
321
+ function clientManifestCandidates(baseDir) {
322
+ const root = baseDir ?? process.cwd();
323
+ return [resolve(root, "public/assets/.vite/manifest.json"), resolve(root, "public/assets/manifest.json")];
324
+ }
325
+ /**
326
+ * `__path__` label for an injected manifest, so "entry not in the manifest"
327
+ * errors name the real source rather than a path that was never read.
328
+ */
329
+ const INJECTED_CLIENT_MANIFEST_SOURCE = "GUREN_VITE_MANIFEST (injected by the deploy build)";
330
+ const INJECTED_MANIFEST_HINT = "It must hold the Vite client manifest text (deploy plugins inject it at build time), not a path.";
331
+ /**
332
+ * Attach one of the manifest's bookkeeping fields. `enumerable: false` is the
333
+ * invariant: a stamped field must never leak into `Object.keys` or a
334
+ * re-serialization of the manifest.
335
+ */
336
+ function defineHidden(manifest, key, value) {
337
+ Object.defineProperty(manifest, key, {
338
+ value,
339
+ enumerable: false
340
+ });
341
+ }
342
+ /**
343
+ * The client manifest a deploy build injected for runtimes that do not ship
344
+ * `public/assets/manifest.json`: `GUREN_VITE_MANIFEST` holds the manifest *JSON
345
+ * text*, not a path. Fails loudly on a value that is set but not a manifest,
346
+ * because falling through to the filesystem would end in "run `bunx vite build`"
347
+ * — a diagnosis pointing away from the variable that is actually broken.
348
+ */
349
+ function injectedClientManifest() {
350
+ const raw = process.env.GUREN_VITE_MANIFEST;
351
+ if (typeof raw !== "string" || raw.length === 0) return;
352
+ let parsed;
353
+ try {
354
+ parsed = JSON.parse(raw);
355
+ } catch (error) {
356
+ throw new Error(`GUREN_VITE_MANIFEST is set but is not valid JSON. ${INJECTED_MANIFEST_HINT}`, { cause: error });
357
+ }
358
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error(`GUREN_VITE_MANIFEST is set but does not hold a manifest object. ${INJECTED_MANIFEST_HINT}`);
359
+ const manifest = parsed;
360
+ defineHidden(manifest, "__path__", INJECTED_CLIENT_MANIFEST_SOURCE);
361
+ return manifest;
362
+ }
363
+ function loadViteManifest(candidatePaths, label, options = {}) {
364
+ const warnOnMissing = options.warnOnMissing ?? true;
365
+ const command = label === "SSR" ? "bunx vite build --ssr" : "bunx vite build";
366
+ for (const manifestPath of candidatePaths) try {
367
+ const raw = readFileSync(manifestPath, "utf8");
368
+ const manifest = JSON.parse(raw);
369
+ defineHidden(manifest, "__path__", manifestPath);
370
+ if (options.includeRaw) defineHidden(manifest, "__raw__", raw);
371
+ return manifest;
372
+ } catch (error) {
373
+ if (error.code !== "ENOENT") {
374
+ console.warn(`Unable to load ${label} Vite manifest at ${manifestPath}.`, error);
375
+ return;
376
+ }
377
+ }
378
+ if (warnOnMissing && candidatePaths.length) console.warn(`Unable to load ${label} Vite manifest. Checked paths:\n${candidatePaths.map((p) => ` - ${p}`).join("\n")}\nRun \`${command}\` before starting in production.`);
379
+ }
380
+ function getManifestFile(entry) {
381
+ if (!entry) return;
382
+ if (Array.isArray(entry)) return entry[0];
383
+ if (typeof entry === "string") return entry;
384
+ if ("file" in entry && typeof entry.file === "string") return entry.file;
385
+ }
386
+ function getManifestCss(entry) {
387
+ if (!entry || Array.isArray(entry) || typeof entry === "string") return;
388
+ return entry.css;
389
+ }
390
+ //#endregion
391
+ export { stopBunServerBounded as C, stopActiveViteDevServer as S, registerBunTeardown as _, getManifestCss as a, setActiveBunServer as b, isViteProduction as c, startViteDevServer as d, MANAGED_VITE_ENV_FLAG as f, hotReloadStopBound as g, getGlobalState as h, clientManifestCandidates as i, loadViteManifest as l, closeOwnedViteDevServer as m, INJECTED_CLIENT_MANIFEST_SOURCE as n, getManifestFile as o, adoptViteDevServer as p, PUBLIC_ASSETS_URL_PREFIX as r, injectedClientManifest as s, DEFAULT_DEV_SERVER_URL as t, normalizeDevServerUrl as u, releaseActiveBunServer as v, stopActiveBunServer as x, reusableActiveViteDevServer as y };