@guren/server 2.3.0 → 2.5.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.
package/dist/index.js CHANGED
@@ -1,8 +1,11 @@
1
1
  import {
2
+ DEFAULT_DEV_STYLES_ENTRY,
3
+ formatHostPort,
4
+ isWildcardHost,
2
5
  logDevServerBanner,
3
6
  parseImportMap,
4
7
  startViteDevServer
5
- } from "./chunk-6IGN233M.js";
8
+ } from "./chunk-62AB24ZU.js";
6
9
  import {
7
10
  PendingSchedule,
8
11
  Schedule,
@@ -198,7 +201,7 @@ import {
198
201
  getGate,
199
202
  setGate,
200
203
  withAuthorization
201
- } from "./chunk-7OB2YXRE.js";
204
+ } from "./chunk-T2FFUU6J.js";
202
205
  import {
203
206
  AuthorizationException,
204
207
  ExceptionHandler,
@@ -231,7 +234,7 @@ import {
231
234
  getBroadcastManager,
232
235
  parseRequestPayload,
233
236
  setBroadcastManager
234
- } from "./chunk-4VE3LYOM.js";
237
+ } from "./chunk-DRNPVBAA.js";
235
238
  import {
236
239
  CacheManager,
237
240
  FileStore,
@@ -251,25 +254,11 @@ import {
251
254
  decrypt,
252
255
  encrypt,
253
256
  generateKey,
254
- generateOtp,
255
- generatePassword,
256
- generateSlug,
257
257
  getEncrypter,
258
- pick,
259
- random,
260
- randomBase64,
261
- randomBase64Url,
262
- randomHex,
263
- randomInt,
264
- randomString,
265
- sample,
266
258
  setEncrypter,
267
- shuffle,
268
259
  signUrl,
269
- urlSafeToken,
270
- uuid,
271
260
  verifySignedUrl
272
- } from "./chunk-LVJCZCAV.js";
261
+ } from "./chunk-H3B23O6T.js";
273
262
  import {
274
263
  MessageSigner,
275
264
  deriveAppKey,
@@ -294,6 +283,22 @@ import {
294
283
  verifyHmac,
295
284
  verifyPassword
296
285
  } from "./chunk-QQKTH5KX.js";
286
+ import {
287
+ generateOtp,
288
+ generatePassword,
289
+ generateSlug,
290
+ pick,
291
+ random,
292
+ randomBase64,
293
+ randomBase64Url,
294
+ randomHex,
295
+ randomInt,
296
+ randomString,
297
+ sample,
298
+ shuffle,
299
+ urlSafeToken,
300
+ uuid
301
+ } from "./chunk-V4DNC2ER.js";
297
302
  import {
298
303
  ApplicationShutdown,
299
304
  ApplicationStarted,
@@ -319,7 +324,7 @@ import {
319
324
  StorageCheck,
320
325
  createHealthManager,
321
326
  customCheck
322
- } from "./chunk-SIP34GBE.js";
327
+ } from "./chunk-2SC566CD.js";
323
328
 
324
329
  // src/support/error-polyfill.ts
325
330
  var patched = false;
@@ -487,6 +492,9 @@ var Router = class {
487
492
  delete(path, handlerOrOptions, ...rest) {
488
493
  return this.register("DELETE", path, handlerOrOptions, rest);
489
494
  }
495
+ query(path, handlerOrOptions, ...rest) {
496
+ return this.register("QUERY", path, handlerOrOptions, rest);
497
+ }
490
498
  group(prefix, callback) {
491
499
  this.prefixStack.push(prefix);
492
500
  try {
@@ -706,6 +714,12 @@ var RouterMiddlewareGroupBuilder = class {
706
714
  delete(path, handlerOrOptions, ...rest) {
707
715
  return this.router.applyMiddlewareScope(this.items, () => this.router.delete(path, handlerOrOptions, ...rest));
708
716
  }
717
+ query(path, handlerOrOptions, ...rest) {
718
+ return this.router.applyMiddlewareScope(this.items, () => this.router.query(path, handlerOrOptions, ...rest));
719
+ }
720
+ on(method, path, handlerOrOptions, ...rest) {
721
+ return this.router.applyMiddlewareScope(this.items, () => this.router.on(method, path, handlerOrOptions, ...rest));
722
+ }
709
723
  };
710
724
  function createRouteBuilder(route, namedRoutes) {
711
725
  return {
@@ -1664,6 +1678,7 @@ function isExcluded2(path, patterns) {
1664
1678
 
1665
1679
  // src/http/middleware/cors.ts
1666
1680
  import { cors } from "hono/cors";
1681
+ var DEFAULT_ALLOW_METHODS = ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH", "QUERY"];
1667
1682
  function createCorsMiddleware(options = {}) {
1668
1683
  if (options.credentials && !options.origin) {
1669
1684
  throw new Error(
@@ -1673,11 +1688,11 @@ function createCorsMiddleware(options = {}) {
1673
1688
  const origin = options.origin ?? (() => "");
1674
1689
  return cors({
1675
1690
  origin,
1676
- allowMethods: options.allowMethods,
1677
- allowHeaders: options.allowHeaders,
1678
- exposeHeaders: options.exposeHeaders,
1679
- maxAge: options.maxAge,
1680
- credentials: options.credentials
1691
+ allowMethods: options.allowMethods ?? DEFAULT_ALLOW_METHODS,
1692
+ ...options.allowHeaders !== void 0 && { allowHeaders: options.allowHeaders },
1693
+ ...options.exposeHeaders !== void 0 && { exposeHeaders: options.exposeHeaders },
1694
+ ...options.maxAge !== void 0 && { maxAge: options.maxAge },
1695
+ ...options.credentials !== void 0 && { credentials: options.credentials }
1681
1696
  });
1682
1697
  }
1683
1698
 
@@ -2232,7 +2247,7 @@ async function inertia(component, props, options = {}) {
2232
2247
  const page = {
2233
2248
  component,
2234
2249
  props,
2235
- url: options.url ?? "",
2250
+ url: options.url ?? inertiaPageUrl(options.request) ?? "",
2236
2251
  version: resolvedVersion
2237
2252
  };
2238
2253
  const request = options.request;
@@ -2275,15 +2290,23 @@ async function inertia(component, props, options = {}) {
2275
2290
  }
2276
2291
  });
2277
2292
  }
2293
+ function inertiaPageUrl(request) {
2294
+ if (!request) {
2295
+ return void 0;
2296
+ }
2297
+ const { pathname, search } = new URL(request.url);
2298
+ return `${pathname}${search}`;
2299
+ }
2278
2300
  async function renderDocument(page, options) {
2279
2301
  const defaultEntry = process.env.GUREN_INERTIA_ENTRY ?? "/resources/js/app.tsx";
2280
2302
  const entry = options.entry ?? defaultEntry;
2281
2303
  const title = escapeHtml(options.title ?? DEFAULT_TITLE);
2282
- const styles = options.styles ?? parseStylesEnv(process.env.GUREN_INERTIA_STYLES);
2304
+ const isProduction = process.env.NODE_ENV === "production";
2305
+ const configuredStyles = options.styles ?? parseStylesEnv(process.env.GUREN_INERTIA_STYLES);
2306
+ const styles = !isProduction && options.styles === void 0 && isDevServerEntry(entry) ? configuredStyles.filter((href) => href !== DEFAULT_DEV_STYLES_ENTRY) : configuredStyles;
2283
2307
  const envImportMap = parseImportMap(process.env.GUREN_INERTIA_IMPORT_MAP, {
2284
2308
  context: "GUREN_INERTIA_IMPORT_MAP"
2285
2309
  });
2286
- const isProduction = process.env.NODE_ENV === "production";
2287
2310
  const importMapEntries = {
2288
2311
  ...isProduction ? {} : DEV_FALLBACK_IMPORT_MAP,
2289
2312
  ...envImportMap,
@@ -2417,6 +2440,9 @@ function normalizeSsrSpecifier(specifier) {
2417
2440
  function isUrlLike(specifier) {
2418
2441
  return /^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(specifier);
2419
2442
  }
2443
+ function isDevServerEntry(entry) {
2444
+ return /^https?:\/\//iu.test(entry);
2445
+ }
2420
2446
  function renderStyles(styles) {
2421
2447
  if (!styles.length) {
2422
2448
  return "";
@@ -2514,12 +2540,79 @@ var ViewEngine = class {
2514
2540
  }
2515
2541
  };
2516
2542
 
2543
+ // src/http/middleware/validation-errors-cookie.ts
2544
+ import { deleteCookie, getCookie as getCookie3 } from "hono/cookie";
2545
+ import { serialize } from "hono/utils/cookie";
2546
+ var VALIDATION_ERRORS_COOKIE = "guren_validation_errors";
2547
+ var COOKIE_MAX_AGE_SECONDS = 60;
2548
+ var MAX_COOKIE_VALUE_LENGTH = 3800;
2549
+ var CONSUMED_CONTEXT_KEY = "gurenValidationErrorsCookieConsumed";
2550
+ function validationErrorsSetCookie(errors) {
2551
+ const kept = {};
2552
+ for (const [field, message] of Object.entries(errors)) {
2553
+ const next = encodeURIComponent(JSON.stringify({ ...kept, [field]: message }));
2554
+ if (next.length > MAX_COOKIE_VALUE_LENGTH) {
2555
+ continue;
2556
+ }
2557
+ kept[field] = message;
2558
+ }
2559
+ return serialize(VALIDATION_ERRORS_COOKIE, JSON.stringify(kept), {
2560
+ path: "/",
2561
+ httpOnly: true,
2562
+ sameSite: "Lax",
2563
+ maxAge: COOKIE_MAX_AGE_SECONDS
2564
+ });
2565
+ }
2566
+ function readValidationErrorsCookie(ctx) {
2567
+ const raw = getCookie3(ctx, VALIDATION_ERRORS_COOKIE);
2568
+ if (!raw) {
2569
+ return void 0;
2570
+ }
2571
+ ctx.set(CONSUMED_CONTEXT_KEY, true);
2572
+ let parsed;
2573
+ try {
2574
+ parsed = JSON.parse(raw);
2575
+ } catch {
2576
+ return void 0;
2577
+ }
2578
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
2579
+ return void 0;
2580
+ }
2581
+ const errors = {};
2582
+ for (const [field, message] of Object.entries(parsed)) {
2583
+ if (typeof message === "string") {
2584
+ errors[field] = message;
2585
+ }
2586
+ }
2587
+ return Object.keys(errors).length > 0 ? errors : void 0;
2588
+ }
2589
+ function createValidationErrorsCookieCleanup() {
2590
+ return async (ctx, next) => {
2591
+ await next();
2592
+ if (!ctx.get(CONSUMED_CONTEXT_KEY)) {
2593
+ return;
2594
+ }
2595
+ const setCookies = ctx.res.headers.getSetCookie?.() ?? [];
2596
+ if (setCookies.some((header) => header.startsWith(`${VALIDATION_ERRORS_COOKIE}=`))) {
2597
+ return;
2598
+ }
2599
+ deleteCookie(ctx, VALIDATION_ERRORS_COOKIE, { path: "/" });
2600
+ };
2601
+ }
2602
+
2517
2603
  // src/providers/InertiaServiceProvider.ts
2518
2604
  var InertiaServiceProvider = class extends ServiceProvider {
2519
2605
  register() {
2520
2606
  if (!ViewEngine.has("inertia")) {
2521
2607
  ViewEngine.register("inertia", inertia);
2522
2608
  }
2609
+ let hono;
2610
+ try {
2611
+ hono = this.container.make("hono");
2612
+ } catch {
2613
+ return;
2614
+ }
2615
+ hono.use("*", createValidationErrorsCookieCleanup());
2523
2616
  }
2524
2617
  boot() {
2525
2618
  this.registerValidationRenderer();
@@ -2547,18 +2640,21 @@ var InertiaServiceProvider = class extends ServiceProvider {
2547
2640
  422
2548
2641
  );
2549
2642
  }
2643
+ const flattened = {};
2644
+ for (const [key, messages] of Object.entries(error.errors ?? {})) {
2645
+ flattened[key] = messages[0] ?? "";
2646
+ }
2647
+ const referer = ctx.req.header("Referer") ?? "/";
2648
+ const headers = { Location: referer };
2550
2649
  const session = getSessionFromContext(ctx);
2551
2650
  if (session) {
2552
- const flattened = {};
2553
- for (const [key, messages] of Object.entries(error.errors ?? {})) {
2554
- flattened[key] = messages[0] ?? "";
2555
- }
2556
2651
  session.flash("errors", flattened);
2652
+ } else {
2653
+ headers["Set-Cookie"] = validationErrorsSetCookie(flattened);
2557
2654
  }
2558
- const referer = ctx.req.header("Referer") ?? "/";
2559
2655
  return new Response(null, {
2560
2656
  status: 303,
2561
- headers: { Location: referer }
2657
+ headers
2562
2658
  });
2563
2659
  });
2564
2660
  }
@@ -2570,8 +2666,12 @@ var InertiaServiceProvider = class extends ServiceProvider {
2570
2666
  registerSharedErrors() {
2571
2667
  shareInertiaProps(async (ctx) => {
2572
2668
  const session = getSessionFromContext(ctx);
2573
- const errors = session?.getFlash("errors");
2574
- return errors && Object.keys(errors).length > 0 ? { errors } : {};
2669
+ if (session) {
2670
+ const errors2 = session.getFlash("errors");
2671
+ return errors2 && Object.keys(errors2).length > 0 ? { errors: errors2 } : {};
2672
+ }
2673
+ const errors = readValidationErrorsCookie(ctx);
2674
+ return errors ? { errors } : {};
2575
2675
  }, this.container);
2576
2676
  }
2577
2677
  };
@@ -2579,12 +2679,38 @@ var InertiaServiceProvider = class extends ServiceProvider {
2579
2679
  // src/http/Application.ts
2580
2680
  var MANAGED_VITE_ENV_FLAG = "GUREN_MANAGED_VITE_DEV_SERVER";
2581
2681
  var DEFAULT_DEV_ENTRY_PATH = "/resources/js/dev-entry.ts";
2682
+ var STRICT_PORT_ENV_FLAG = "GUREN_STRICT_PORT";
2683
+ var DEFAULT_PORT_WALK_ATTEMPTS = 20;
2684
+ function isAddressInUse(error) {
2685
+ return Boolean(
2686
+ error && typeof error === "object" && "code" in error && error.code === "EADDRINUSE"
2687
+ );
2688
+ }
2689
+ function resolvePortAttempts(option, port) {
2690
+ if (port === 0) {
2691
+ return 1;
2692
+ }
2693
+ if (typeof process !== "undefined" && process.env?.[STRICT_PORT_ENV_FLAG] === "1") {
2694
+ return 1;
2695
+ }
2696
+ if (typeof option === "boolean") {
2697
+ return option ? DEFAULT_PORT_WALK_ATTEMPTS : 1;
2698
+ }
2699
+ return typeof process !== "undefined" && process.env.NODE_ENV === "production" ? 1 : DEFAULT_PORT_WALK_ATTEMPTS;
2700
+ }
2701
+ function toConnectableUrl(hostname, port) {
2702
+ const host = isWildcardHost(hostname) ? hostname === "::" ? "::1" : "127.0.0.1" : hostname;
2703
+ return `http://${formatHostPort(host, port)}`;
2704
+ }
2582
2705
  function clearManagedViteEnv() {
2583
2706
  if (typeof process === "undefined") {
2584
2707
  return;
2585
2708
  }
2586
2709
  if (process.env[MANAGED_VITE_ENV_FLAG] === "1") {
2587
2710
  delete process.env.VITE_DEV_SERVER_URL;
2711
+ if (process.env.GUREN_INERTIA_ENTRY?.endsWith(DEFAULT_DEV_ENTRY_PATH)) {
2712
+ delete process.env.GUREN_INERTIA_ENTRY;
2713
+ }
2588
2714
  }
2589
2715
  delete process.env[MANAGED_VITE_ENV_FLAG];
2590
2716
  }
@@ -2604,7 +2730,44 @@ function syncManagedInertiaDevEntry(devServerUrl) {
2604
2730
  function getGlobalState() {
2605
2731
  return globalThis;
2606
2732
  }
2607
- async function stopActiveBunServer() {
2733
+ function bunStopTimeoutMs() {
2734
+ return shutdownTimeoutMs("GUREN_BUN_STOP_TIMEOUT_MS");
2735
+ }
2736
+ function shutdownTimeoutMs(envName) {
2737
+ const parsed = typeof process !== "undefined" ? Number.parseInt(process.env[envName] ?? "", 10) : Number.NaN;
2738
+ return Number.isInteger(parsed) && parsed > 0 ? parsed : 5e3;
2739
+ }
2740
+ async function awaitBounded(work, timeoutMs, onTimeout) {
2741
+ let timer;
2742
+ try {
2743
+ const timedOut = await Promise.race([
2744
+ work.then(() => false),
2745
+ new Promise((resolve2) => {
2746
+ timer = setTimeout(() => resolve2(true), timeoutMs);
2747
+ })
2748
+ ]);
2749
+ if (timedOut) {
2750
+ onTimeout(timeoutMs);
2751
+ }
2752
+ } finally {
2753
+ clearTimeout(timer);
2754
+ }
2755
+ }
2756
+ async function stopBunServerBounded(server, closeActiveConnections) {
2757
+ const stopped = (async () => {
2758
+ try {
2759
+ await server.stop?.(closeActiveConnections);
2760
+ } catch (error) {
2761
+ console.warn("Failed to stop Bun server:", error);
2762
+ }
2763
+ })();
2764
+ await awaitBounded(stopped, bunStopTimeoutMs(), (timeoutMs) => {
2765
+ console.warn(
2766
+ `Bun server did not stop within ${timeoutMs}ms \u2014 no longer waiting on it. In-flight requests may still be draining.`
2767
+ );
2768
+ });
2769
+ }
2770
+ async function stopActiveBunServer(closeActiveConnections = false) {
2608
2771
  const state = getGlobalState();
2609
2772
  const previous = state.__gurenActiveServer;
2610
2773
  if (!previous?.stop) {
@@ -2612,35 +2775,84 @@ async function stopActiveBunServer() {
2612
2775
  return;
2613
2776
  }
2614
2777
  try {
2615
- await Promise.resolve(previous.stop());
2616
- } catch (error) {
2617
- console.warn("Failed to stop previous Bun server:", error);
2778
+ await stopBunServerBounded(previous, closeActiveConnections);
2618
2779
  } finally {
2619
- state.__gurenActiveServer = void 0;
2780
+ releaseActiveBunServer(previous);
2620
2781
  }
2621
2782
  }
2622
2783
  function setActiveBunServer(server) {
2623
2784
  getGlobalState().__gurenActiveServer = server;
2624
2785
  }
2625
- async function stopActiveViteDevServer() {
2626
- const state = getGlobalState();
2627
- const previous = state.__gurenActiveViteDevServer;
2628
- if (!previous) {
2629
- state.__gurenActiveViteDevServer = void 0;
2630
- clearManagedViteEnv();
2631
- return;
2786
+ function releaseActiveBunServer(server) {
2787
+ if (getGlobalState().__gurenActiveServer === server) {
2788
+ setActiveBunServer();
2632
2789
  }
2790
+ }
2791
+ function registerProcessTeardown(onSignal, onExit) {
2792
+ process.once("SIGINT", onSignal);
2793
+ process.once("SIGTERM", onSignal);
2794
+ process.on("exit", onExit);
2795
+ return () => {
2796
+ process.off("SIGINT", onSignal);
2797
+ process.off("SIGTERM", onSignal);
2798
+ process.off("exit", onExit);
2799
+ };
2800
+ }
2801
+ function viteCloseTimeoutMs() {
2802
+ return shutdownTimeoutMs("GUREN_VITE_CLOSE_TIMEOUT_MS");
2803
+ }
2804
+ async function closeViteDevServerBounded(server) {
2805
+ const close = (async () => {
2806
+ try {
2807
+ await server.close();
2808
+ } catch (error) {
2809
+ console.warn("Failed to stop Vite dev server:", error);
2810
+ }
2811
+ })();
2812
+ await awaitBounded(close, viteCloseTimeoutMs(), (timeoutMs) => {
2813
+ console.warn(
2814
+ `Vite dev server did not close within ${timeoutMs}ms \u2014 abandoning it. A stale asset server may still hold its port.`
2815
+ );
2816
+ });
2817
+ }
2818
+ async function stopActiveViteDevServer() {
2819
+ const previous = getGlobalState().__gurenActiveViteDevServer;
2633
2820
  try {
2634
- await previous.close();
2635
- } catch (error) {
2636
- console.warn("Failed to stop previous Vite dev server:", error);
2821
+ if (previous) {
2822
+ await closeViteDevServerBounded(previous.server);
2823
+ }
2637
2824
  } finally {
2638
- state.__gurenActiveViteDevServer = void 0;
2825
+ previous?.disposeTeardown();
2826
+ if (getGlobalState().__gurenActiveViteDevServer === previous) {
2827
+ setActiveViteDevServer();
2828
+ }
2829
+ }
2830
+ }
2831
+ function publishManagedViteEnv(localUrl) {
2832
+ if (typeof process === "undefined") {
2833
+ return;
2834
+ }
2835
+ process.env.VITE_DEV_SERVER_URL = localUrl;
2836
+ process.env[MANAGED_VITE_ENV_FLAG] = "1";
2837
+ syncManagedInertiaDevEntry(localUrl);
2838
+ }
2839
+ function setActiveViteDevServer(active) {
2840
+ getGlobalState().__gurenActiveViteDevServer = active;
2841
+ if (active) {
2842
+ publishManagedViteEnv(active.localUrl);
2843
+ } else {
2639
2844
  clearManagedViteEnv();
2640
2845
  }
2641
2846
  }
2642
- function setActiveViteDevServer(server) {
2643
- getGlobalState().__gurenActiveViteDevServer = server;
2847
+ function reusableActiveViteDevServer(viteOption) {
2848
+ if (typeof viteOption === "object") {
2849
+ return void 0;
2850
+ }
2851
+ const active = getGlobalState().__gurenActiveViteDevServer;
2852
+ if (!active || !active.server.httpServer?.listening) {
2853
+ return void 0;
2854
+ }
2855
+ return active;
2644
2856
  }
2645
2857
  var Application = class {
2646
2858
  constructor(options = {}) {
@@ -2698,10 +2910,20 @@ var Application = class {
2698
2910
  router;
2699
2911
  providerManager;
2700
2912
  authManager;
2701
- viteDevServer;
2702
2913
  bunServer;
2703
- viteTeardownRegistered = false;
2704
- bunTeardownRegistered = false;
2914
+ boundAddress;
2915
+ /**
2916
+ * Detaches the Bun half's process teardown handlers, and doubles as the "are
2917
+ * they attached?" memo. One field rather than a separate boolean: a memo and
2918
+ * an undo that can disagree is how handlers end up attached while a flag says
2919
+ * otherwise — see {@link registerProcessTeardown}.
2920
+ *
2921
+ * The Vite half's disposer lives in {@link ActiveViteDevServer} instead,
2922
+ * because the application that detaches those handlers is not always the one
2923
+ * that attached them: adoption moves the server to a new owner, and the
2924
+ * outgoing owner is only reachable through the slot.
2925
+ */
2926
+ disposeBunTeardown;
2705
2927
  autoSessionAttached = false;
2706
2928
  routesRegistered = false;
2707
2929
  bootPromise;
@@ -2830,55 +3052,179 @@ var Application = class {
2830
3052
  if (!Bun) {
2831
3053
  throw new Error("Bun runtime is required to call Application.listen");
2832
3054
  }
2833
- await stopActiveBunServer();
2834
- await stopActiveViteDevServer();
2835
- const { port = 3e3, hostname = "0.0.0.0", assetsUrl, vite } = options;
3055
+ const supersededServer = getGlobalState().__gurenActiveServer;
3056
+ await stopActiveBunServer(true);
3057
+ const { port = 3e3, hostname = "0.0.0.0", assetsUrl, vite, portFallback } = options;
2836
3058
  const externalAssetsUrl = typeof process !== "undefined" && process.env?.[MANAGED_VITE_ENV_FLAG] !== "1" ? process.env?.VITE_DEV_SERVER_URL : void 0;
2837
3059
  let resolvedAssetsUrl = assetsUrl ?? externalAssetsUrl;
2838
- const shouldStartVite = vite !== false && typeof process !== "undefined" && process.env?.NODE_ENV !== "production" && !resolvedAssetsUrl && process.env?.GUREN_DEV_VITE !== "0";
2839
- if (shouldStartVite) {
3060
+ const shouldStartVite = vite !== false && typeof process !== "undefined" && process.env.NODE_ENV !== "production" && !resolvedAssetsUrl && process.env?.GUREN_DEV_VITE !== "0";
3061
+ const adoptViteDevServer = (viteServer, localUrl) => {
3062
+ const displaced2 = getGlobalState().__gurenActiveViteDevServer;
3063
+ displaced2?.disposeTeardown();
3064
+ if (displaced2 && displaced2.server !== viteServer) {
3065
+ void closeViteDevServerBounded(displaced2.server);
3066
+ }
3067
+ setActiveViteDevServer({
3068
+ server: viteServer,
3069
+ localUrl,
3070
+ owner: this,
3071
+ disposeTeardown: this.registerViteTeardown()
3072
+ });
3073
+ resolvedAssetsUrl = localUrl;
3074
+ };
3075
+ const reusableVite = shouldStartVite ? reusableActiveViteDevServer(vite) : void 0;
3076
+ let startedViteHere = false;
3077
+ if (reusableVite) {
3078
+ adoptViteDevServer(reusableVite.server, reusableVite.localUrl);
3079
+ } else {
3080
+ await stopActiveViteDevServer();
3081
+ }
3082
+ if (shouldStartVite && !reusableVite) {
2840
3083
  const viteOptions = typeof vite === "object" ? vite : void 0;
2841
3084
  try {
2842
- await this.closeViteDevServer();
2843
3085
  const { server: server2, localUrl } = await startViteDevServer({
2844
3086
  root: viteOptions?.root ?? process.cwd(),
2845
3087
  config: viteOptions?.config,
2846
3088
  host: viteOptions?.host,
2847
3089
  port: viteOptions?.port
2848
3090
  });
2849
- this.viteDevServer = server2;
2850
- setActiveViteDevServer(server2);
2851
- resolvedAssetsUrl = localUrl;
2852
- if (typeof process !== "undefined") {
2853
- process.env.VITE_DEV_SERVER_URL = resolvedAssetsUrl;
2854
- process.env[MANAGED_VITE_ENV_FLAG] = "1";
2855
- }
2856
- syncManagedInertiaDevEntry(resolvedAssetsUrl);
2857
- this.registerViteTeardown();
3091
+ adoptViteDevServer(server2, localUrl);
3092
+ startedViteHere = true;
2858
3093
  } catch (error) {
2859
3094
  console.error("Failed to start Vite dev server:", error);
2860
3095
  process.exit(1);
2861
3096
  }
2862
3097
  }
2863
- const server = Bun.serve({
2864
- port,
2865
- hostname,
2866
- // `{ server }` is Bun's convention for reaching the live server from a
2867
- // handler; middleware reads `ctx.env.server.requestIP()` through it to
2868
- // learn the socket peer (the MCP access guard, the rate limiter).
2869
- fetch: (request, server2) => this.fetch(request, { server: server2 })
2870
- });
3098
+ const attempts = resolvePortAttempts(portFallback, port);
3099
+ let server;
3100
+ let attemptPort = port;
3101
+ for (let offset = 0; offset < attempts; offset += 1) {
3102
+ attemptPort = port + offset;
3103
+ try {
3104
+ server = Bun.serve({
3105
+ port: attemptPort,
3106
+ hostname,
3107
+ // `{ server }` is Bun's convention for reaching the live server from a
3108
+ // handler; middleware reads `ctx.env.server.requestIP()` through it to
3109
+ // learn the socket peer (the MCP access guard, the rate limiter).
3110
+ fetch: (request, server2) => this.fetch(request, { server: server2 })
3111
+ });
3112
+ break;
3113
+ } catch (error) {
3114
+ if (offset === attempts - 1 || !isAddressInUse(error)) {
3115
+ if (startedViteHere) {
3116
+ await this.closeViteDevServer();
3117
+ }
3118
+ throw error;
3119
+ }
3120
+ console.warn(`[guren] Port ${attemptPort} is in use, trying ${attemptPort + 1}...`);
3121
+ }
3122
+ }
3123
+ if (!server) {
3124
+ throw new Error("Bun.serve did not return a server instance");
3125
+ }
3126
+ let boundPort = server.port;
3127
+ if (typeof boundPort !== "number") {
3128
+ if (port === 0) {
3129
+ await server.stop?.(true);
3130
+ throw new Error(
3131
+ "Bun.serve did not report a bound port for `port: 0`. Application.listen cannot report the address it is serving on."
3132
+ );
3133
+ }
3134
+ boundPort = attemptPort;
3135
+ }
3136
+ const boundHostname = server.hostname ?? hostname;
3137
+ const address = {
3138
+ port: boundPort,
3139
+ hostname: boundHostname,
3140
+ url: toConnectableUrl(boundHostname, boundPort)
3141
+ };
3142
+ const displaced = this.bunServer;
3143
+ if (displaced && displaced !== server && displaced !== supersededServer) {
3144
+ await stopBunServerBounded(displaced, true);
3145
+ }
2871
3146
  this.bunServer = server;
3147
+ this.boundAddress = address;
2872
3148
  setActiveBunServer(server);
2873
3149
  this.registerBunTeardown();
2874
- const shouldLogBanner = typeof process === "undefined" || process.env?.NODE_ENV !== "production" && process.env?.GUREN_DEV_BANNER !== "0";
3150
+ const shouldLogBanner = typeof process === "undefined" || process.env.NODE_ENV !== "production" && process.env?.GUREN_DEV_BANNER !== "0";
2875
3151
  if (shouldLogBanner) {
2876
3152
  this.logDevServerBanner({
2877
- hostname,
2878
- port,
3153
+ hostname: boundHostname,
3154
+ port: boundPort,
2879
3155
  assetsUrl: resolvedAssetsUrl ?? "http://localhost:5173"
2880
3156
  });
2881
3157
  }
3158
+ return address;
3159
+ }
3160
+ /**
3161
+ * The address {@link Application.listen} bound, or `undefined` before it has
3162
+ * been called and once this app's server has been superseded or torn down.
3163
+ *
3164
+ * The same object `listen()` returned, so callers that need the address
3165
+ * later — an OpenAPI `servers` entry, an absolute URL, a health report —
3166
+ * read it here instead of threading it out of the entrypoint.
3167
+ *
3168
+ * The stored value is preferred over re-reading the live server, because
3169
+ * `listen()` resolves the port through a fallback the socket no longer
3170
+ * carries.
3171
+ *
3172
+ * Liveness is only as good as the signal available: a server stopped through
3173
+ * the framework — {@link Application.stop}, a later `listen()`, the
3174
+ * process-exit teardown — clears what this reads, but one stopped by reaching
3175
+ * past the framework to the Bun server's own `stop()` does not, and this keeps
3176
+ * reporting its address. Treat it as "where `listen()` put this app", not as a
3177
+ * health check.
3178
+ */
3179
+ get address() {
3180
+ if (!this.bunServer || getGlobalState().__gurenActiveServer !== this.bunServer) {
3181
+ return void 0;
3182
+ }
3183
+ return this.boundAddress;
3184
+ }
3185
+ /**
3186
+ * Stops the server {@link listen} started, undoing that call.
3187
+ *
3188
+ * Safe to call when nothing is listening, and safe to call twice — both are
3189
+ * no-ops. A later `listen()` starts cleanly, so an app may be stopped and
3190
+ * restarted in one process.
3191
+ *
3192
+ * `closeActiveConnections` forces in-flight requests closed instead of
3193
+ * waiting for them, matching Bun's own `stop()` parameter. It defaults to
3194
+ * `false` (graceful) because a caller reaching for a public stop is usually
3195
+ * shutting down deliberately; the hot-reload path inside `listen()` forces
3196
+ * the close, since a reload must not wait on the server it is replacing.
3197
+ *
3198
+ * The managed Vite dev server is taken down too. `listen()` is what started
3199
+ * it, and `listen()`'s own bind-failure path already closes the one it
3200
+ * started — leaving it running here would strand an asset server, and its
3201
+ * published env vars, in a process with no application server. That close is
3202
+ * best-effort on the same terms as every other path: it is bounded by
3203
+ * {@link viteCloseTimeoutMs}, and a Vite server that overruns the bound is
3204
+ * warned about and abandoned rather than holding this call open. A dev server
3205
+ * a later `listen()` has adopted is left alone — it belongs to that call now.
3206
+ *
3207
+ * The stop itself is bounded by {@link bunStopTimeoutMs}: a graceful stop
3208
+ * waits on in-flight requests, and one that never finishes would otherwise
3209
+ * hold this call open forever.
3210
+ */
3211
+ async stop(closeActiveConnections = false) {
3212
+ const server = this.bunServer;
3213
+ if (server) {
3214
+ try {
3215
+ await stopBunServerBounded(server, closeActiveConnections);
3216
+ } finally {
3217
+ releaseActiveBunServer(server);
3218
+ }
3219
+ }
3220
+ if (this.bunServer !== server) {
3221
+ return;
3222
+ }
3223
+ this.bunServer = void 0;
3224
+ this.boundAddress = void 0;
3225
+ this.disposeBunTeardown?.();
3226
+ this.disposeBunTeardown = void 0;
3227
+ await this.closeViteDevServer();
2882
3228
  }
2883
3229
  /**
2884
3230
  * Register a service provider.
@@ -2900,52 +3246,67 @@ var Application = class {
2900
3246
  logDevServerBanner(options) {
2901
3247
  logDevServerBanner(options);
2902
3248
  }
3249
+ /**
3250
+ * Closes the managed Vite dev server, but only while this application still
3251
+ * owns it.
3252
+ *
3253
+ * Ownership is the whole check. A `listen()` elsewhere in the process may
3254
+ * have adopted the running server — same object, new owner — and closing it
3255
+ * then would take the asset server, and its published env vars, out from
3256
+ * under an application that is actively serving from it. The record in the
3257
+ * slot is the one place that distinction exists, so it is read here rather
3258
+ * than mirrored on the instance.
3259
+ */
2903
3260
  async closeViteDevServer() {
2904
- if (!this.viteDevServer) {
3261
+ const active = getGlobalState().__gurenActiveViteDevServer;
3262
+ if (active?.owner !== this) {
2905
3263
  return;
2906
3264
  }
2907
3265
  try {
2908
- await this.viteDevServer.close();
2909
- } catch (error) {
2910
- console.error("Error while shutting down Vite dev server:", error);
3266
+ await closeViteDevServerBounded(active.server);
2911
3267
  } finally {
2912
- if (getGlobalState().__gurenActiveViteDevServer === this.viteDevServer) {
3268
+ active.disposeTeardown();
3269
+ if (getGlobalState().__gurenActiveViteDevServer === active) {
2913
3270
  setActiveViteDevServer();
2914
3271
  }
2915
- this.viteDevServer = void 0;
2916
- this.viteTeardownRegistered = false;
2917
- clearManagedViteEnv();
2918
3272
  }
2919
3273
  }
3274
+ /**
3275
+ * Attaches this application's Vite teardown handlers and returns the disposer
3276
+ * that detaches them. The disposer is stored in the active-record slot rather
3277
+ * than on this instance, because whoever takes ownership next is the one that
3278
+ * has to call it — and a disposer another app could spend would leave this
3279
+ * instance believing its handlers are attached when they are not.
3280
+ */
2920
3281
  registerViteTeardown() {
2921
- if (this.viteTeardownRegistered || !this.viteDevServer || typeof process === "undefined") {
2922
- return;
3282
+ if (typeof process === "undefined") {
3283
+ return () => {
3284
+ };
2923
3285
  }
2924
- this.viteTeardownRegistered = true;
2925
- const exitHandler = () => {
2926
- this.closeViteDevServer().then(() => process.exit(0)).catch(() => process.exit(1));
2927
- };
2928
- process.once("SIGINT", exitHandler);
2929
- process.once("SIGTERM", exitHandler);
2930
- process.on("exit", () => {
2931
- if (this.viteDevServer) {
2932
- void this.viteDevServer.close();
3286
+ return registerProcessTeardown(
3287
+ () => {
3288
+ this.closeViteDevServer().then(() => process.exit(0)).catch(() => process.exit(1));
3289
+ },
3290
+ () => {
3291
+ const active = getGlobalState().__gurenActiveViteDevServer;
3292
+ if (active?.owner === this) {
3293
+ void active.server.close();
3294
+ }
2933
3295
  }
2934
- });
3296
+ );
2935
3297
  }
2936
3298
  registerBunTeardown() {
2937
- if (this.bunTeardownRegistered || typeof process === "undefined") {
3299
+ if (this.disposeBunTeardown || typeof process === "undefined") {
2938
3300
  return;
2939
3301
  }
2940
- this.bunTeardownRegistered = true;
2941
- const exitHandler = () => {
2942
- stopActiveBunServer().then(() => process.exit(0)).catch(() => process.exit(1));
2943
- };
2944
- process.once("SIGINT", exitHandler);
2945
- process.once("SIGTERM", exitHandler);
2946
- process.on("exit", () => {
2947
- void stopActiveBunServer();
2948
- });
3302
+ this.disposeBunTeardown = registerProcessTeardown(
3303
+ () => {
3304
+ stopActiveBunServer().then(() => process.exit(0)).catch(() => process.exit(1));
3305
+ },
3306
+ () => {
3307
+ void stopActiveBunServer();
3308
+ }
3309
+ );
2949
3310
  }
2950
3311
  };
2951
3312
  function createApp(options = {}) {
@@ -3117,17 +3478,14 @@ var Controller = class {
3117
3478
  }
3118
3479
  async inertia(componentOrPage, props, options = {}) {
3119
3480
  const ctx = this.ctx;
3120
- const { url: overrideUrl, ...rest } = options;
3121
- const url2 = overrideUrl ?? ctx.req.path ?? ctx.req.url ?? "";
3122
3481
  const component = typeof componentOrPage === "string" ? componentOrPage : componentOrPage.component ?? componentOrPage.id;
3123
3482
  const sharedProps = await resolveSharedInertiaProps(ctx, this._container);
3124
3483
  const propsWithShared = { ...sharedProps, ...props };
3125
3484
  const response = await inertia(component, propsWithShared, {
3126
- ...rest,
3485
+ ...options,
3127
3486
  // No 'en' fallback here (unlike the locale getter): unconfigured apps
3128
3487
  // keep the Inertia engine's own default lang.
3129
- lang: rest.lang ?? this.#resolveLocale(),
3130
- url: url2,
3488
+ lang: options.lang ?? this.#resolveLocale(),
3131
3489
  request: ctx.req.raw
3132
3490
  });
3133
3491
  response.__gurenInertia = {
@@ -3772,14 +4130,18 @@ var FormRequest = class {
3772
4130
  }
3773
4131
  /**
3774
4132
  * Get the authenticated user from the request context.
4133
+ *
4134
+ * Awaiting is load-bearing: `this.user() !== null` compiles and is always
4135
+ * true, because an unawaited call is a pending promise.
3775
4136
  */
3776
- user() {
4137
+ async user() {
3777
4138
  const auth = this.ctx.get(AUTH_CONTEXT_KEY);
3778
- return auth?.user?.() ?? null;
4139
+ return await auth?.user() ?? null;
3779
4140
  }
3780
4141
  /**
3781
4142
  * Handle the form request: authorize, parse body, validate, return typed data.
3782
- * @internal Called by Controller.validate()
4143
+ * Call it from a controller with the request context:
4144
+ * `const data = await new StorePostRequest().handle(this.ctx)`.
3783
4145
  */
3784
4146
  async handle(ctx) {
3785
4147
  this.ctx = ctx;
@@ -6795,7 +7157,7 @@ function debugErrorMiddleware() {
6795
7157
  try {
6796
7158
  await next();
6797
7159
  } catch (err) {
6798
- const isProduction = typeof process !== "undefined" && process.env?.NODE_ENV === "production";
7160
+ const isProduction = typeof process !== "undefined" && process.env.NODE_ENV === "production";
6799
7161
  if (isProduction) {
6800
7162
  throw err;
6801
7163
  }
@@ -6917,7 +7279,7 @@ function renderRequestSection(request) {
6917
7279
  </section>`;
6918
7280
  }
6919
7281
  function renderEnvironmentSection() {
6920
- const nodeEnv = typeof process !== "undefined" ? process.env?.NODE_ENV ?? "undefined" : "undefined";
7282
+ const nodeEnv = typeof process !== "undefined" ? process.env.NODE_ENV ?? "undefined" : "undefined";
6921
7283
  const bunVersion = typeof process !== "undefined" ? process.versions?.bun ?? "N/A" : "N/A";
6922
7284
  const platform = typeof process !== "undefined" ? process.platform ?? "unknown" : "unknown";
6923
7285
  return `