@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.
@@ -10,7 +10,51 @@ import type { TranslationLoader } from '../i18n/index.js';
10
10
  import { type SecurityHeadersOptions } from './middleware/security-headers.js';
11
11
  import { type HostAuthorizationOptions } from './middleware/host-authorization.js';
12
12
  import { type DevBannerOptions } from './dev-banner.js';
13
- import { type StartViteDevServerOptions } from './vite-dev-server.js';
13
+ import { startViteDevServer, type StartViteDevServerOptions } from './vite-dev-server.js';
14
+ type BunServer = {
15
+ stop?: (closeConnections?: boolean) => void | Promise<void>;
16
+ requestIP?: (request: Request) => {
17
+ address?: string;
18
+ } | null;
19
+ port?: number;
20
+ hostname?: string;
21
+ };
22
+ type ViteServer = Awaited<ReturnType<typeof startViteDevServer>>['server'];
23
+ /**
24
+ * The one managed Vite dev server this process runs, and who owns it.
25
+ *
26
+ * The owner matters because a dev server outlives the `listen()` that started
27
+ * it: on a `bun --hot` reload the next `listen()` adopts the running server
28
+ * rather than restarting it, and both applications then hold the same object.
29
+ * Instance identity cannot tell those two apart — it is the same server — so
30
+ * "may I close this?" is answered here instead, by the slot naming exactly one
31
+ * owner at a time.
32
+ */
33
+ export interface ActiveViteDevServer {
34
+ readonly server: ViteServer;
35
+ readonly localUrl: string;
36
+ readonly owner: Application;
37
+ /**
38
+ * Detaches the owner's process teardown handlers. Whoever replaces this
39
+ * record calls it, because the outgoing owner is only reachable from here —
40
+ * and a set of handlers left attached would still close this server, and run
41
+ * its own `process.exit()`, on the next signal.
42
+ */
43
+ readonly disposeTeardown: () => void;
44
+ }
45
+ /**
46
+ * The ambient slots `listen()` plants on `globalThis` so a `bun --hot` reload,
47
+ * which re-runs the entrypoint but keeps `globalThis`, can find what the
48
+ * previous run left running.
49
+ *
50
+ * Exported so the tests that plant stand-ins in these slots can name them
51
+ * against this declaration instead of restating it. Not part of the public
52
+ * API: `src/index.ts` re-exports by name and does not list it.
53
+ */
54
+ export interface GurenGlobalSlots {
55
+ __gurenActiveServer?: BunServer;
56
+ __gurenActiveViteDevServer?: ActiveViteDevServer;
57
+ }
14
58
  export type BootCallback = (app: Hono) => void | Promise<void>;
15
59
  /**
16
60
  * Service provider class constructor type.
@@ -105,12 +149,51 @@ export interface ApplicationListenOptions {
105
149
  hostname?: string;
106
150
  assetsUrl?: string;
107
151
  vite?: StartViteDevServerOptions | false;
152
+ /**
153
+ * What to do when the requested port is already taken.
154
+ *
155
+ * `true` walks forward through the next 20 ports; `false` fails fast with
156
+ * the original EADDRINUSE. Unset walks outside production, matching the loop
157
+ * this option replaces.
158
+ *
159
+ * `GUREN_STRICT_PORT=1` forces fail-fast regardless, and `port: 0` never
160
+ * walks — the OS is already picking a free port.
161
+ */
162
+ portFallback?: boolean;
163
+ }
164
+ /**
165
+ * Where the server actually ended up listening.
166
+ *
167
+ * Returned by {@link Application.listen} so callers never have to infer the
168
+ * port from the port they asked for — with a port walk or `PORT=0` in play,
169
+ * those are different numbers, and scraping the human-readable dev banner is
170
+ * the only alternative.
171
+ *
172
+ * Read-only because {@link Application.address} hands back the very object
173
+ * `listen()` returned: a caller that adjusted its own copy would change what
174
+ * every later reader sees.
175
+ */
176
+ export interface ListenAddress {
177
+ /**
178
+ * The port the socket is bound to — what the runtime reports, falling back
179
+ * to the port the successful `Bun.serve` call was made with.
180
+ */
181
+ readonly port: number;
182
+ /** The hostname the socket is bound to. */
183
+ readonly hostname: string;
184
+ /** A URL that reaches the server, with a wildcard bind resolved to localhost. */
185
+ readonly url: string;
108
186
  }
109
187
  /**
110
188
  * Application wires an app-local router into a running Hono instance.
111
189
  *
112
190
  * It embeds a DI Container as the backbone of the framework, binding core
113
191
  * services and managing providers through the container's ProviderManager.
192
+ *
193
+ * Lifecycle rule for `listen()`/`stop()` and their helpers: re-check ownership
194
+ * after every `await`. Any server or slot they remembered can have been
195
+ * superseded by a concurrent call while they waited, and only the current
196
+ * owner may clear shared state.
114
197
  */
115
198
  export declare class Application {
116
199
  private readonly options;
@@ -119,10 +202,20 @@ export declare class Application {
119
202
  readonly router: Router;
120
203
  private readonly providerManager;
121
204
  private readonly authManager;
122
- private viteDevServer?;
123
205
  private bunServer?;
124
- private viteTeardownRegistered;
125
- private bunTeardownRegistered;
206
+ private boundAddress?;
207
+ /**
208
+ * Detaches the Bun half's process teardown handlers, and doubles as the "are
209
+ * they attached?" memo. One field rather than a separate boolean: a memo and
210
+ * an undo that can disagree is how handlers end up attached while a flag says
211
+ * otherwise — see {@link registerProcessTeardown}.
212
+ *
213
+ * The Vite half's disposer lives in {@link ActiveViteDevServer} instead,
214
+ * because the application that detaches those handlers is not always the one
215
+ * that attached them: adoption moves the server to a new owner, and the
216
+ * outgoing owner is only reachable through the slot.
217
+ */
218
+ private disposeBunTeardown?;
126
219
  private autoSessionAttached;
127
220
  private routesRegistered;
128
221
  private bootPromise?;
@@ -178,7 +271,54 @@ export declare class Application {
178
271
  /**
179
272
  * Convenience helper to start a Bun server when available.
180
273
  */
181
- listen(options?: ApplicationListenOptions): Promise<void>;
274
+ listen(options?: ApplicationListenOptions): Promise<ListenAddress>;
275
+ /**
276
+ * The address {@link Application.listen} bound, or `undefined` before it has
277
+ * been called and once this app's server has been superseded or torn down.
278
+ *
279
+ * The same object `listen()` returned, so callers that need the address
280
+ * later — an OpenAPI `servers` entry, an absolute URL, a health report —
281
+ * read it here instead of threading it out of the entrypoint.
282
+ *
283
+ * The stored value is preferred over re-reading the live server, because
284
+ * `listen()` resolves the port through a fallback the socket no longer
285
+ * carries.
286
+ *
287
+ * Liveness is only as good as the signal available: a server stopped through
288
+ * the framework — {@link Application.stop}, a later `listen()`, the
289
+ * process-exit teardown — clears what this reads, but one stopped by reaching
290
+ * past the framework to the Bun server's own `stop()` does not, and this keeps
291
+ * reporting its address. Treat it as "where `listen()` put this app", not as a
292
+ * health check.
293
+ */
294
+ get address(): ListenAddress | undefined;
295
+ /**
296
+ * Stops the server {@link listen} started, undoing that call.
297
+ *
298
+ * Safe to call when nothing is listening, and safe to call twice — both are
299
+ * no-ops. A later `listen()` starts cleanly, so an app may be stopped and
300
+ * restarted in one process.
301
+ *
302
+ * `closeActiveConnections` forces in-flight requests closed instead of
303
+ * waiting for them, matching Bun's own `stop()` parameter. It defaults to
304
+ * `false` (graceful) because a caller reaching for a public stop is usually
305
+ * shutting down deliberately; the hot-reload path inside `listen()` forces
306
+ * the close, since a reload must not wait on the server it is replacing.
307
+ *
308
+ * The managed Vite dev server is taken down too. `listen()` is what started
309
+ * it, and `listen()`'s own bind-failure path already closes the one it
310
+ * started — leaving it running here would strand an asset server, and its
311
+ * published env vars, in a process with no application server. That close is
312
+ * best-effort on the same terms as every other path: it is bounded by
313
+ * {@link viteCloseTimeoutMs}, and a Vite server that overruns the bound is
314
+ * warned about and abandoned rather than holding this call open. A dev server
315
+ * a later `listen()` has adopted is left alone — it belongs to that call now.
316
+ *
317
+ * The stop itself is bounded by {@link bunStopTimeoutMs}: a graceful stop
318
+ * waits on in-flight requests, and one that never finishes would otherwise
319
+ * hold this call open forever.
320
+ */
321
+ stop(closeActiveConnections?: boolean): Promise<void>;
182
322
  /**
183
323
  * Register a service provider.
184
324
  */
@@ -191,7 +331,25 @@ export declare class Application {
191
331
  * Logs the rich development server banner to the console.
192
332
  */
193
333
  logDevServerBanner(options: DevBannerOptions): void;
334
+ /**
335
+ * Closes the managed Vite dev server, but only while this application still
336
+ * owns it.
337
+ *
338
+ * Ownership is the whole check. A `listen()` elsewhere in the process may
339
+ * have adopted the running server — same object, new owner — and closing it
340
+ * then would take the asset server, and its published env vars, out from
341
+ * under an application that is actively serving from it. The record in the
342
+ * slot is the one place that distinction exists, so it is read here rather
343
+ * than mirrored on the instance.
344
+ */
194
345
  private closeViteDevServer;
346
+ /**
347
+ * Attaches this application's Vite teardown handlers and returns the disposer
348
+ * that detaches them. The disposer is stored in the active-record slot rather
349
+ * than on this instance, because whoever takes ownership next is the one that
350
+ * has to call it — and a disposer another app could spend would leave this
351
+ * instance believing its handlers are attached when they are not.
352
+ */
195
353
  private registerViteTeardown;
196
354
  private registerBunTeardown;
197
355
  }
@@ -24,17 +24,16 @@ import type { ValidationRule } from './validation/types.js';
24
24
  * }
25
25
  * }
26
26
  *
27
- * authorize() {
28
- * return this.user() !== null
27
+ * async authorize() {
28
+ * return (await this.user()) !== null
29
29
  * }
30
30
  * }
31
31
  *
32
32
  * // In controller:
33
- * const data = await this.validate(StorePostRequest)
33
+ * const data = await new StorePostRequest().handle(this.ctx)
34
34
  * // data is typed as StorePostData
35
35
  * ```
36
- */
37
- /**
36
+ *
38
37
  * @deprecated Legacy compatibility layer — prefer schema-first validation
39
38
  * via `this.validateBody()` / `validateQuery()` / `validateParams()`.
40
39
  */
@@ -62,11 +61,15 @@ export declare abstract class FormRequest<T = Record<string, unknown>> {
62
61
  attributes(): Record<string, string>;
63
62
  /**
64
63
  * Get the authenticated user from the request context.
64
+ *
65
+ * Awaiting is load-bearing: `this.user() !== null` compiles and is always
66
+ * true, because an unawaited call is a pending promise.
65
67
  */
66
- protected user(): unknown;
68
+ protected user<TUser = unknown>(): Promise<TUser | null>;
67
69
  /**
68
70
  * Handle the form request: authorize, parse body, validate, return typed data.
69
- * @internal Called by Controller.validate()
71
+ * Call it from a controller with the request context:
72
+ * `const data = await new StorePostRequest().handle(this.ctx)`.
70
73
  */
71
74
  handle(ctx: Context): Promise<T>;
72
75
  private parseBody;
@@ -4,4 +4,15 @@ export interface DevBannerOptions {
4
4
  port: number;
5
5
  assetsUrl?: string;
6
6
  }
7
+ /**
8
+ * A wildcard bind answers on every interface but is not itself dialable on
9
+ * every platform.
10
+ *
11
+ * Lives here rather than beside its other caller because the banner and
12
+ * `Application.listen()`'s returned address are two renderings of one fact,
13
+ * and a platform caveat added to only one of them is the drift this replaces.
14
+ */
15
+ export declare function isWildcardHost(hostname: string): boolean;
16
+ /** `host:port`, bracketing an IPv6 literal so the result is dialable. */
17
+ export declare function formatHostPort(hostname: string, port: number): string;
7
18
  export declare function logDevServerBanner({ hostname, port, assetsUrl, }: DevBannerOptions): void;
@@ -7,7 +7,7 @@ export interface CorsOptions {
7
7
  * - A function: dynamic origin evaluation
8
8
  */
9
9
  origin?: string | string[] | ((origin: string, ctx: unknown) => string | undefined | null);
10
- /** Allowed HTTP methods. Default: ['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH'] */
10
+ /** Allowed HTTP methods. Default: ['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH', 'QUERY'] */
11
11
  allowMethods?: string[];
12
12
  /** Allowed request headers. */
13
13
  allowHeaders?: string[];
@@ -0,0 +1,31 @@
1
+ import type { Context, MiddlewareHandler } from 'hono';
2
+ /**
3
+ * Cookie flash for Inertia validation errors on apps with no session.
4
+ *
5
+ * The Laravel-style flow flashes errors to the session and redirects back,
6
+ * but sessions are only mounted when `createApp({ auth })` is configured — a
7
+ * fresh scaffold has none yet. Dropping the errors silently turns every
8
+ * validation failure into "the form did nothing", so without a session the
9
+ * flattened errors ride across the one redirect in a short-lived HttpOnly
10
+ * cookie instead: display-only data, no store required, working on every
11
+ * runtime (Bun, Workers, Lambda).
12
+ */
13
+ export declare const VALIDATION_ERRORS_COOKIE = "guren_validation_errors";
14
+ /**
15
+ * The `Set-Cookie` value that flashes `errors` across the next redirect.
16
+ */
17
+ export declare function validationErrorsSetCookie(errors: Record<string, string>): string;
18
+ /**
19
+ * The flashed errors carried by the current request, if any. Reading consumes
20
+ * the flash: the cleanup middleware expires the cookie on this response.
21
+ */
22
+ export declare function readValidationErrorsCookie(ctx: Context): Record<string, string> | undefined;
23
+ /**
24
+ * Expires the flash cookie on the response whose render consumed it,
25
+ * restoring the show-once semantics a session flash has. Runs post-`next()`,
26
+ * so a thrown `ValidationException` (whose renderer may be *setting* a fresh
27
+ * cookie on its 303) never reaches the deletion — and the `getSetCookie`
28
+ * guard covers any other path that just wrote the cookie on this same
29
+ * response.
30
+ */
31
+ export declare function createValidationErrorsCookieCleanup(): MiddlewareHandler;
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export { Application, createApp } from './http/Application.js';
2
- export type { Context, ApplicationListenOptions, ServiceProviderConstructor } from './http/Application.js';
2
+ export type { Context, ApplicationListenOptions, ListenAddress, ServiceProviderConstructor, } from './http/Application.js';
3
3
  export { parseRequestPayload, formatValidationErrors } from './http/request.js';
4
4
  export { Controller } from './mvc/Controller.js';
5
5
  export type { InertiaResponse, InferInertiaProps, ControllerInertiaProps, AuthPayload } from './mvc/Controller.js';
@@ -52,7 +52,7 @@ export type { ErrorResponse, ExceptionHandlerOptions, ExceptionReporter, Excepti
52
52
  export { Command, Input, Output, BufferedOutput, ConsoleKernel, createConsoleKernel, parseSignature, } from './console/index.js';
53
53
  export type { ArgumentDefinition, OptionDefinition, ParsedSignature, CommandClass, CommandInstance, ConsoleKernelOptions, OutputInterface, InputInterface, ScheduledCommand, PromptInterface, ProgressInterface, } from './console/index.js';
54
54
  export { Gate, Response as AuthResponse, createGate, setGate, getGate, defineGate, can, cannot, authorize as authorizeAbility, Policy, definePolicy, authorizeMiddleware, authorizeAllMiddleware, authorizeResourceMiddleware, withAuthorization, } from './authorization/index.js';
55
- export type { AuthUser, GateCallback, GateDefinition, PolicyMethod, PolicyInterface, PolicyClass, AuthorizationResponse, GateOptions, AuthorizeOptions, PolicyRegistration, ResourceAction, ResponseBuilder, AuthorizedContext, } from './authorization/index.js';
55
+ export type { AuthUser, GateCallback, GateDefinition, PolicyMethod, PolicyInterface, PolicyClass, AuthorizationResponse, GateOptions, AuthorizeOptions, AuthorizeResourceOptions, PolicyRegistration, ResourceAction, ResponseBuilder, AuthorizedContext, } from './authorization/index.js';
56
56
  export { Encrypter, generateKey, generateAppKey, normalizeAppKey, parseAppKey, parsePreviousAppKeys, getAppKeyringFromEnv, deriveAppKey, deriveAppKeyring, createEncrypter, setEncrypter, getEncrypter, encrypt, decrypt, MessageSigner, signUrl, verifySignedUrl, hash, hmac, verifyHmac, sha256, sha512, md5, hashPassword, verifyPassword, needsRehash, secureCompare, check as checkHash, randomString, random, randomHex, randomBase64, randomBase64Url, uuid, randomInt, urlSafeToken, generatePassword, generateOtp, generateSlug, shuffle, pick, sample, } from './encryption/index.js';
57
57
  export type { AppKeyring, EncryptOptions, DecryptOptions, EncrypterConfig, EncryptedPayload, SignedMessageClaims, SignMessageOptions, VerifySignedMessageOptions, HashAlgorithm, HmacOptions, PasswordHashOptions, RandomStringOptions, SignedUrlOptions, VerifySignedUrlOptions, } from './encryption/index.js';
58
58
  export { createFacade, createFacades } from './facades/index.js';