@asenajs/ergenecore 1.5.0 → 2.0.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.
@@ -1,13 +1,11 @@
1
- import { AsenaAdapter, VALIDATOR_METHODS, } from '@asenajs/asena/adapter';
1
+ import { AsenaAdapter, isHttpException, VALIDATOR_METHODS, } from '@asenajs/asena/adapter';
2
2
  import { blue, green, red, yellow } from '@asenajs/asena/logger';
3
3
  import { ErgenecoreWebsocketAdapter } from './ErgenecoreWebsocketAdapter';
4
4
  import { ErgenecoreContextWrapper } from './ErgenecoreContextWrapper';
5
5
  import * as Bun from 'bun';
6
6
  import * as path from 'path';
7
- import { flattenError } from 'zod';
8
7
  import { HttpException, MiddlewareResponseError, ValidationError } from './errors';
9
8
  import { shouldApplyMiddleware } from '@asenajs/asena/utils';
10
- import { isValidationError } from '@asenajs/asena/adapter';
11
9
  /**
12
10
  * Static response headers for performance
13
11
  *
@@ -59,6 +57,15 @@ export class Ergenecore extends AsenaAdapter {
59
57
  * Error handler function
60
58
  */
61
59
  errorHandler;
60
+ /**
61
+ * Handler for requests that matched no route
62
+ */
63
+ notFoundHandler;
64
+ /**
65
+ * Whether the adapter logs errors before handing them to the application.
66
+ * Set false when your own handler already logs with a correlation id.
67
+ */
68
+ logErrors = true;
62
69
  /**
63
70
  * Global middlewares with route configuration
64
71
  * Structure: Array<{ middleware, config }>
@@ -81,9 +88,10 @@ export class Ergenecore extends AsenaAdapter {
81
88
  * @param logger - Server logger instance
82
89
  * @param websocketAdapter - WebSocket adapter instance (optional)
83
90
  */
84
- constructor(logger, websocketAdapter) {
91
+ constructor(logger, websocketAdapter, logErrors = true) {
85
92
  // Call parent constructor with logger and websocketAdapter
86
93
  super(logger, websocketAdapter || new ErgenecoreWebsocketAdapter(logger));
94
+ this.logErrors = logErrors;
87
95
  }
88
96
  /**
89
97
  * Registers a WebSocket route (deferred registration)
@@ -279,6 +287,14 @@ export class Ergenecore extends AsenaAdapter {
279
287
  onError(errorHandler) {
280
288
  this.errorHandler = errorHandler;
281
289
  }
290
+ /**
291
+ * Registers the handler for requests that match no route.
292
+ *
293
+ * Separate from {@link onError}: a missing route is a routing outcome, not a thrown error.
294
+ */
295
+ onNotFound(notFoundHandler) {
296
+ this.notFoundHandler = notFoundHandler;
297
+ }
282
298
  /**
283
299
  * Sets serve options
284
300
  *
@@ -312,59 +328,52 @@ export class Ergenecore extends AsenaAdapter {
312
328
  */
313
329
  buildBunRoutes() {
314
330
  const routes = {};
315
- // Group routes by base path for optimization
316
- const routeGroups = this.groupRoutesByBasePath(this.routeQueue);
317
- // Process each base path group
318
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
319
- for (const [_, groupRoutes] of routeGroups) {
320
- // Extract common middlewares for this group
321
- const commonMiddlewares = this.extractCommonMiddlewares(groupRoutes);
322
- // Group routes by exact path (same as before)
323
- const routesByPath = new Map();
324
- for (const route of groupRoutes) {
325
- if (!routesByPath.has(route.path)) {
326
- routesByPath.set(route.path, []);
327
- }
328
- routesByPath.get(route.path).push(route);
331
+ // Group routes by exact path. There used to be an outer grouping by *base* path too, but
332
+ // its only product was a `commonMiddlewares` array that createRouteHandler ignored - and
333
+ // the comparison behind it was broken anyway (see the removed extractCommonMiddlewares in
334
+ // HonoAdapter, where the same code was live and swapped guards between sibling routes).
335
+ const routesByPath = new Map();
336
+ for (const route of this.routeQueue) {
337
+ if (!routesByPath.has(route.path)) {
338
+ routesByPath.set(route.path, []);
329
339
  }
330
- // Build Bun router object for each path
331
- for (const [path, pathRoutes] of routesByPath) {
332
- // Normalize trailing slash to support both variants
333
- // This ensures /users and /users/ both work with query params
334
- const normalizedPath = path.endsWith('/') && path !== '/' ? path.slice(0, -1) : path;
335
- const pathWithSlash = normalizedPath === '/' ? '/' : `${normalizedPath}/`;
336
- // Initialize both path variants (skip duplicate for root path)
337
- routes[normalizedPath] = routes[normalizedPath] || {};
338
- if (normalizedPath !== '/') {
339
- routes[pathWithSlash] = routes[pathWithSlash] || {};
340
- }
341
- for (const route of pathRoutes) {
342
- const method = route.method.toUpperCase();
343
- // Fast Path Optimization with Pattern Matching
344
- // ✅ Check if this route has any applicable global middlewares
345
- const applicableGlobalMiddlewares = this.getGlobalMiddlewaresForPath(route.path);
346
- // Check if route is simple (no middleware, validation, or static serve)
347
- const isSimpleRoute = applicableGlobalMiddlewares.length === 0 &&
348
- (!route.middlewares || route.middlewares.length === 0) &&
349
- !route.validator &&
350
- !route.staticServe;
351
- // Create handler based on route complexity
352
- const handler = isSimpleRoute
353
- ? this.createFastPathHandler(route)
354
- : this.createRouteHandler(route, commonMiddlewares);
355
- // Register handler to both path variants for trailing slash support
356
- if (method === 'ALL') {
357
- // Bun native: direct handler function matches all HTTP methods
358
- routes[normalizedPath] = handler;
359
- if (normalizedPath !== '/') {
360
- routes[pathWithSlash] = handler;
361
- }
340
+ routesByPath.get(route.path).push(route);
341
+ }
342
+ // Build Bun router object for each path
343
+ for (const [path, pathRoutes] of routesByPath) {
344
+ // Normalize trailing slash to support both variants
345
+ // This ensures /users and /users/ both work with query params
346
+ const normalizedPath = path.endsWith('/') && path !== '/' ? path.slice(0, -1) : path;
347
+ const pathWithSlash = normalizedPath === '/' ? '/' : `${normalizedPath}/`;
348
+ // Initialize both path variants (skip duplicate for root path)
349
+ routes[normalizedPath] = routes[normalizedPath] || {};
350
+ if (normalizedPath !== '/') {
351
+ routes[pathWithSlash] = routes[pathWithSlash] || {};
352
+ }
353
+ for (const route of pathRoutes) {
354
+ const method = route.method.toUpperCase();
355
+ // Fast Path Optimization with Pattern Matching
356
+ // ✅ Check if this route has any applicable global middlewares
357
+ const applicableGlobalMiddlewares = this.getGlobalMiddlewaresForPath(route.path);
358
+ // Check if route is simple (no middleware, validation, or static serve)
359
+ const isSimpleRoute = applicableGlobalMiddlewares.length === 0 &&
360
+ (!route.middlewares || route.middlewares.length === 0) &&
361
+ !route.validator &&
362
+ !route.staticServe;
363
+ // Create handler based on route complexity
364
+ const handler = isSimpleRoute ? this.createFastPathHandler(route) : this.createRouteHandler(route);
365
+ // Register handler to both path variants for trailing slash support
366
+ if (method === 'ALL') {
367
+ // Bun native: direct handler function matches all HTTP methods
368
+ routes[normalizedPath] = handler;
369
+ if (normalizedPath !== '/') {
370
+ routes[pathWithSlash] = handler;
362
371
  }
363
- else {
364
- routes[normalizedPath][method] = handler;
365
- if (normalizedPath !== '/') {
366
- routes[pathWithSlash][method] = handler;
367
- }
372
+ }
373
+ else {
374
+ routes[normalizedPath][method] = handler;
375
+ if (normalizedPath !== '/') {
376
+ routes[pathWithSlash][method] = handler;
368
377
  }
369
378
  }
370
379
  }
@@ -374,26 +383,35 @@ export class Ergenecore extends AsenaAdapter {
374
383
  routes['/*'] = async (req) => {
375
384
  const context = new ErgenecoreContextWrapper(req, this.server);
376
385
  const requestPath = new URL(req.url).pathname;
377
- // Filter and run applicable global middlewares
378
- const applicableMiddlewares = this.globalMiddlewares
379
- .filter(({ config }) => shouldApplyMiddleware(requestPath, config))
380
- .map(({ middleware }) => middleware);
381
- if (applicableMiddlewares.length > 0) {
382
- const result = await this.executeMiddlewares(context, applicableMiddlewares);
383
- if (result instanceof Response)
384
- return result;
385
- if (result === false) {
386
- return new Response('Forbidden', { status: 403 });
386
+ // Wrapped like every other request path. Without this a global middleware throwing on an
387
+ // unmatched route - an auth middleware raising HttpException(401), or getBody() rejecting a
388
+ // malformed payload - escaped the handler entirely: onError never saw it, nothing was
389
+ // logged, and the caller got Bun's own 500 page instead of the adapter's envelope.
390
+ try {
391
+ // Filter and run applicable global middlewares
392
+ const applicableMiddlewares = this.globalMiddlewares
393
+ .filter(({ config }) => shouldApplyMiddleware(requestPath, config))
394
+ .map(({ middleware }) => middleware);
395
+ if (applicableMiddlewares.length > 0) {
396
+ // The 404 is produced as the chain's *terminal step*, the same way a matched route runs
397
+ // its handler. Producing it after the chain had already unwound meant a global
398
+ // middleware's post-`next()` code observed the request before any status existed -
399
+ // `@asenajs/asena-otel` reads `context.res.status` there, so every unmatched route was
400
+ // recorded with no `http.response.status_code`.
401
+ const result = await this.executeMiddlewares(context, applicableMiddlewares, 0, () => this.respondToUnmatched(context, requestPath, req.method));
402
+ if (result instanceof Response)
403
+ return result;
404
+ if (result === false) {
405
+ return new Response('Forbidden', { status: 403 });
406
+ }
387
407
  }
408
+ // Reached when no global middleware applies, or when one short-circuited without calling
409
+ // next(). The application's onNotFound, or the default 404.
410
+ return await this.respondToUnmatched(context, requestPath, req.method);
388
411
  }
389
- // No middleware handled the request → error handler or 404
390
- if (this.errorHandler) {
391
- return this.errorHandler(new Error('Not Found'), context);
412
+ catch (error) {
413
+ return await this.respondToError(error, context);
392
414
  }
393
- return new Response(JSON.stringify({ error: 'Not Found' }), {
394
- status: 404,
395
- headers: STATIC_JSON_HEADERS,
396
- });
397
415
  };
398
416
  return routes;
399
417
  }
@@ -428,6 +446,143 @@ export class Ergenecore extends AsenaAdapter {
428
446
  }
429
447
  return routes;
430
448
  }
449
+ /**
450
+ * Answers a request nothing served: an unmatched route, or a static file that does not exist.
451
+ *
452
+ * Both go through the application's `onNotFound` so an app has one place to shape its 404,
453
+ * and both fall back to the same JSON envelope the hono adapter uses.
454
+ *
455
+ * Deliberately NOT routed to `onError` - that hook is for errors the application threw.
456
+ */
457
+ async respondToUnmatched(context, path, method) {
458
+ const response = await this.resolveUnmatchedResponse(context, path, method);
459
+ // Record the status on the context before answering. An unmatched request never reaches a
460
+ // route handler, so nothing else writes it - and `OtelTracingMiddleware` reads
461
+ // `context.res.status` to attribute both the span and the request metrics. Without this every
462
+ // 404 was recorded with no `http.response.status_code` at all, which is exactly the traffic
463
+ // (bots, probes, typo'd paths) an operator most wants to count.
464
+ context.res.status = response.status;
465
+ return response;
466
+ }
467
+ async resolveUnmatchedResponse(context, path, method) {
468
+ if (this.notFoundHandler) {
469
+ try {
470
+ const response = await this.notFoundHandler(context, { path, method });
471
+ if (response instanceof Response) {
472
+ return response;
473
+ }
474
+ }
475
+ catch (error) {
476
+ // onNotFound must not be able to take the server down.
477
+ this.logger.error('onNotFound threw an error, using the default response:', error);
478
+ }
479
+ }
480
+ this.logUnmatched(path, method);
481
+ return new Response(JSON.stringify({ error: 'Not Found' }), {
482
+ status: 404,
483
+ headers: STATIC_JSON_HEADERS,
484
+ });
485
+ }
486
+ /**
487
+ * Records a request the framework itself answered with a 404.
488
+ *
489
+ * Only reached when the application has no `onNotFound`, or when its hook declined or threw -
490
+ * an application that answered its own 404 already knows about the request. Without this an
491
+ * unmatched route was the one outcome that produced no output at any level, which is exactly
492
+ * the traffic (bots, probes, a typo in a deployed client) an operator needs to see.
493
+ *
494
+ * `info`, not `warn`: a scanner walking /wp-admin, /.env and /phpmyadmin must not be able to
495
+ * fill the warning stream. Not `debug` either - a 404 nobody can see is how a mistyped route
496
+ * survives to production.
497
+ */
498
+ logUnmatched(path, method) {
499
+ if (this.logErrors === false)
500
+ return;
501
+ this.logger.info('Route not found:', { path, method, status: 404 });
502
+ }
503
+ /**
504
+ * Logs an error before the application's handler sees it, at a level that matches the
505
+ * response the caller will get.
506
+ *
507
+ * This adapter used to log only when NO error handler was registered - which is to say,
508
+ * never in a real application, since every app configures `onError`. A 500 answered
509
+ * nothing to stdout and the stack was gone. The level split mirrors the hono adapter:
510
+ * 5xx is ours to fix and gets a stack, 4xx is the caller's and would otherwise let a bot
511
+ * scanning for /wp-admin flood the error stream.
512
+ */
513
+ logHandledError(error, context) {
514
+ if (this.logErrors === false)
515
+ return;
516
+ // Brand check, not `instanceof` - `respondToError` below uses `isHttpException` to decide the
517
+ // *response*, and with two resolved copies of this package `instanceof` disagrees with it: the
518
+ // client would get a correct 401 while this line computed 500 and wrote an error-level entry
519
+ // with a full stack. That is precisely the log flooding the level split exists to prevent.
520
+ const status = isHttpException(error) ? error.status : 500;
521
+ const isServerError = status >= 500;
522
+ const meta = {
523
+ // A thrown non-Error is rare but legal, and `String(value)` on a plain object yields
524
+ // "[object Object]" - which tells an operator nothing. Serialise it instead.
525
+ message: error instanceof Error ? error.message : JSON.stringify(error),
526
+ path: new URL(context.req.url).pathname,
527
+ method: context.req.method,
528
+ status,
529
+ ...(isServerError && error instanceof Error ? { stack: error.stack } : {}),
530
+ };
531
+ if (isServerError) {
532
+ this.logger.error('Application error occurred:', meta);
533
+ return;
534
+ }
535
+ // `debug` is optional on ServerLogger - read it structurally and fall back to info.
536
+ const debug = this.logger.debug;
537
+ (debug ?? this.logger.info).call(this.logger, 'Request rejected:', meta);
538
+ }
539
+ /**
540
+ * Produces the response for a thrown error, in the same order the hono adapter uses.
541
+ *
542
+ * The application's handler gets first refusal on *every* error, `HttpException` included.
543
+ * Previously each catch block answered an `HttpException` straight from `getResponse()` and
544
+ * only consulted `errorHandler` for everything else, so an app could not reshape its own
545
+ * 401/403/404 envelopes. Worse, only one of the five catch blocks carried the
546
+ * `!isValidationError` exemption, so a `ValidationError` thrown on the fast path never
547
+ * reached `onError` at all - the exact opposite of why ValidationError exists.
548
+ *
549
+ * Falls back to the exception's own response (or a 500) when there is no handler, when the
550
+ * handler returns nothing, or when the handler itself throws.
551
+ */
552
+ async respondToError(error, context) {
553
+ if (this.errorHandler) {
554
+ try {
555
+ const response = await this.errorHandler(error, context);
556
+ if (response instanceof Response) {
557
+ // The application answered. Its handler is where this error gets recorded, with
558
+ // whatever correlation id the application carries - a second line from here would
559
+ // only duplicate it.
560
+ return response;
561
+ }
562
+ }
563
+ catch (handlerError) {
564
+ this.logger.error('Error handler threw an error, using the default response:', handlerError);
565
+ }
566
+ }
567
+ // Reached when there is no handler, when it declined, or when it threw - in every one of
568
+ // those the framework is answering, so it is the framework's job to say what happened.
569
+ // Without this, an `onError` that returns nothing swallows a 500 with no trace anywhere.
570
+ this.logHandledError(error, context);
571
+ // Branded check, not `instanceof`: with two resolved copies of this package `instanceof`
572
+ // answers false and every deliberate 401/403/404 would fall through to the generic 500
573
+ // below - silently, because the API still responds.
574
+ if (isHttpException(error)) {
575
+ return error.getResponse();
576
+ }
577
+ // Never echo the thrown message. An unhandled 500 is by definition something the application
578
+ // did not anticipate, and its message routinely carries a connection string, a file path or a
579
+ // driver's raw complaint. The message is not lost - `logHandledError` above wrote it with a
580
+ // stack. An application that wants to say more declares `onError`.
581
+ return new Response(JSON.stringify({ error: 'Internal Server Error' }), {
582
+ status: 500,
583
+ headers: STATIC_JSON_HEADERS,
584
+ });
585
+ }
431
586
  /**
432
587
  * Executes middleware chain with recursive next() pattern
433
588
  *
@@ -500,10 +655,9 @@ export class Ergenecore extends AsenaAdapter {
500
655
  return true;
501
656
  }
502
657
  catch (error) {
503
- // If middleware threw HttpException, convert to Response
504
- if (error instanceof HttpException) {
505
- return error.getResponse();
506
- }
658
+ // HttpException is deliberately NOT answered here. Converting it to a Response inside the
659
+ // middleware chain short-circuits the application's error handler; rethrowing lets the
660
+ // caller's terminal catch run it through respondToError like every other error.
507
661
  // If a downstream middleware returned a Response, propagate it
508
662
  if (error instanceof MiddlewareResponseError) {
509
663
  return error.response;
@@ -544,9 +698,10 @@ export class Ergenecore extends AsenaAdapter {
544
698
  // This happens at server startup, NOT on every request → zero runtime overhead
545
699
  const applicableGlobalMiddlewares = this.getGlobalMiddlewaresForPath(wsRoute.path);
546
700
  return async (req) => {
701
+ // Built outside the try so the catch can hand it to the application's error handler,
702
+ // the same way createRouteHandler does.
703
+ const context = new ErgenecoreContextWrapper(req, this.server);
547
704
  try {
548
- // Create context wrapper
549
- const context = new ErgenecoreContextWrapper(req, this.server);
550
705
  // Execute filtered global middlewares with real next() chain
551
706
  if (applicableGlobalMiddlewares.length > 0) {
552
707
  const result = await this.executeMiddlewares(context, applicableGlobalMiddlewares);
@@ -587,18 +742,7 @@ export class Ergenecore extends AsenaAdapter {
587
742
  return new Response('WebSocket upgrade failed', { status: 500 });
588
743
  }
589
744
  catch (error) {
590
- // If HttpException was thrown, convert to Response
591
- if (error instanceof HttpException) {
592
- return error.getResponse();
593
- }
594
- // Log and handle other errors
595
- this.logger.error('WebSocket upgrade handler error:', error);
596
- return new Response(JSON.stringify({
597
- error: error instanceof Error ? error.message : 'WebSocket upgrade failed',
598
- }), {
599
- status: 500,
600
- headers: { 'Content-Type': 'application/json' },
601
- });
745
+ return await this.respondToError(error, context);
602
746
  }
603
747
  };
604
748
  }
@@ -684,50 +828,10 @@ export class Ergenecore extends AsenaAdapter {
684
828
  * @returns Bun-compatible fast path handler
685
829
  */
686
830
  createFastPathHandler(route) {
687
- // If no error handler is set, use ultra-minimal version with default error handling
688
- if (!this.errorHandler) {
689
- return async (req) => {
690
- const context = new ErgenecoreContextWrapper(req, this.server);
691
- context.routePattern = route.path;
692
- try {
693
- // Inject Bun's native route params if present
694
- // @ts-expect-error - Bun adds params to Request
695
- if (req.params) {
696
- // @ts-expect-error - Bun adds params to Request
697
- const params = req.params;
698
- for (const key in params) {
699
- context.setValue(`param:${key}`, params[key]);
700
- }
701
- }
702
- // Execute handler directly
703
- const response = await route.handler(context);
704
- // Return response (check if already a Response object)
705
- if (response instanceof Response) {
706
- return response;
707
- }
708
- // Wrap in Response with static headers
709
- return new Response(JSON.stringify(response), {
710
- status: 200,
711
- headers: STATIC_JSON_HEADERS,
712
- });
713
- }
714
- catch (error) {
715
- // If handler threw HttpException, convert to Response
716
- if (error instanceof HttpException) {
717
- return error.getResponse();
718
- }
719
- // Default error handling when no custom error handler is registered
720
- this.logger.error('Route handler error:', error);
721
- return new Response(JSON.stringify({
722
- error: error instanceof Error ? error.message : 'Internal Server Error',
723
- }), {
724
- status: 500,
725
- headers: STATIC_JSON_HEADERS,
726
- });
727
- }
728
- };
729
- }
730
- // With error handler (minimal try-catch)
831
+ // Deliberately one closure. There used to be a second, picked here by `if (!this.errorHandler)`
832
+ // - and once both were routed through `respondToError` the two bodies were identical. It was
833
+ // also the only place the adapter read `errorHandler` at *build* time rather than per request,
834
+ // so a handler registered after start() would have selected the wrong closure.
731
835
  return async (req) => {
732
836
  const context = new ErgenecoreContextWrapper(req, this.server);
733
837
  context.routePattern = route.path;
@@ -754,12 +858,7 @@ export class Ergenecore extends AsenaAdapter {
754
858
  });
755
859
  }
756
860
  catch (error) {
757
- // If handler threw HttpException, convert to Response
758
- if (error instanceof HttpException) {
759
- return error.getResponse();
760
- }
761
- // Handle other errors with custom error handler
762
- return this.errorHandler(error, context);
861
+ return await this.respondToError(error, context);
763
862
  }
764
863
  };
765
864
  }
@@ -773,10 +872,9 @@ export class Ergenecore extends AsenaAdapter {
773
872
  * - Error handling
774
873
  *
775
874
  * @param route - Route parameters
776
- * @param _commonMiddlewares - Common middlewares for this route group (for future optimization)
777
875
  * @returns Bun-compatible route handler
778
876
  */
779
- createRouteHandler(route, _commonMiddlewares = []) {
877
+ createRouteHandler(route) {
780
878
  // ✅ Filter global middlewares by path pattern (ONCE during route building)
781
879
  // This happens at server startup, NOT on every request → zero runtime overhead
782
880
  const applicableGlobalMiddlewares = this.getGlobalMiddlewaresForPath(route.path);
@@ -835,25 +933,8 @@ export class Ergenecore extends AsenaAdapter {
835
933
  return new Response(null, { status: 204 });
836
934
  }
837
935
  catch (error) {
838
- // Validation errors are HttpExceptions too, but the whole point of throwing
839
- // them is to let the application reshape them - so they take the handler
840
- // branch rather than being answered from getResponse() here
841
- if (error instanceof HttpException && !isValidationError(error)) {
842
- return error.getResponse();
843
- }
844
- // Handle other errors with custom error handler if available
845
- if (this.errorHandler) {
846
- // Pass the original context with params already injected
847
- return this.errorHandler(error, context);
848
- }
849
- // Default error response
850
- this.logger.error('Route handler error:', error);
851
- return new Response(JSON.stringify({
852
- error: error instanceof Error ? error.message : 'Internal Server Error',
853
- }), {
854
- status: 500,
855
- headers: { 'Content-Type': 'application/json' },
856
- });
936
+ // The context here already has params injected, so pass it through unchanged.
937
+ return await this.respondToError(error, context);
857
938
  }
858
939
  };
859
940
  }
@@ -924,19 +1005,12 @@ export class Ergenecore extends AsenaAdapter {
924
1005
  if (hookResponse)
925
1006
  return hookResponse;
926
1007
  }
927
- // Reported through the application's error handler so validation shares the
928
- // same response envelope as every other error. With no handler configured
929
- // the thrown error would surface as a bare 500, so the adapter's own 400
930
- // envelope stays as the fallback.
931
- if (!this.errorHandler) {
932
- return new Response(JSON.stringify({
933
- error: 'Validation failed',
934
- details: flattenError(result.error),
935
- }), {
936
- status: 400,
937
- headers: { 'Content-Type': 'application/json' },
938
- });
939
- }
1008
+ // Reported through the application's error handler so validation shares the same
1009
+ // response envelope as every other error. The adapter used to answer its own 400 here
1010
+ // when no handler was configured, which meant a validation failure was the one 4xx
1011
+ // that reached neither `onError` nor the log. The envelope did not disappear with that
1012
+ // branch - it moved onto `ValidationError.getResponse()`, which `respondToError`
1013
+ // falls back to.
940
1014
  throw new ValidationError(result.error, key);
941
1015
  }
942
1016
  }
@@ -1015,84 +1089,82 @@ export class Ergenecore extends AsenaAdapter {
1015
1089
  * ```
1016
1090
  */
1017
1091
  async serveStaticFile(req, context, staticServe) {
1018
- try {
1019
- // 1. Extract request path from URL
1020
- const url = new URL(req.url);
1021
- const requestPath = decodeURIComponent(url.pathname); // Decode URL encoding
1022
- // 2. Apply path rewriting if provided
1023
- const rewrittenPath = staticServe.rewriteRequestPath ? staticServe.rewriteRequestPath(requestPath) : requestPath;
1024
- // 3. Build absolute file path
1025
- const filePath = path.join(staticServe.root, rewrittenPath);
1026
- // 4. Security: Resolve and validate path to prevent traversal attacks
1027
- // Resolve both paths to absolute canonical paths
1028
- const resolvedFilePath = path.resolve(filePath);
1029
- const resolvedRoot = path.resolve(staticServe.root);
1030
- // Check if resolved file path is within root directory
1031
- if (!resolvedFilePath.startsWith(resolvedRoot)) {
1032
- this.logger.warn(`Path traversal attempt detected: ${requestPath} -> ${resolvedFilePath}`);
1033
- return new Response('Forbidden', { status: 403 });
1034
- }
1035
- // 5. Create Bun.file() instance
1036
- const file = Bun.file(resolvedFilePath);
1037
- // 5. Check if file exists
1038
- const fileExists = await file.exists();
1039
- // 6. File not found → trigger onNotFound hook
1040
- if (!fileExists) {
1041
- if (staticServe.onNotFound) {
1042
- await staticServe.onNotFound.handler(rewrittenPath, context);
1043
- // If hook overrides, return null (let handler continue)
1044
- if (staticServe.onNotFound.override) {
1045
- return null;
1046
- }
1047
- }
1048
- // Default 404 response
1049
- return new Response('Not Found', { status: 404 });
1050
- }
1051
- // 7. File found → trigger onFound hook
1052
- if (staticServe.onFound) {
1053
- await staticServe.onFound.handler(rewrittenPath, context);
1092
+ // Deliberately no try/catch. Anything thrown here - a rewriteRequestPath that raises, a
1093
+ // path.resolve or Bun.file failure - travels up to createRouteHandler's catch and through
1094
+ // `respondToError`, like every other failure. Answering it here meant the body was
1095
+ // `{"error": error.message}`, and a message thrown out of the filesystem layer is
1096
+ // specifically a deployment path; and the application's `onError` never saw it at all.
1097
+ // 1. Extract request path from URL
1098
+ const url = new URL(req.url);
1099
+ const requestPath = decodeURIComponent(url.pathname); // Decode URL encoding
1100
+ // 2. Apply path rewriting if provided
1101
+ const rewrittenPath = staticServe.rewriteRequestPath ? staticServe.rewriteRequestPath(requestPath) : requestPath;
1102
+ // 3. Build absolute file path
1103
+ const filePath = path.join(staticServe.root, rewrittenPath);
1104
+ // 4. Security: Resolve and validate path to prevent traversal attacks
1105
+ // Resolve both paths to absolute canonical paths
1106
+ const resolvedFilePath = path.resolve(filePath);
1107
+ const resolvedRoot = path.resolve(staticServe.root);
1108
+ // Check if resolved file path is within root directory
1109
+ if (!resolvedFilePath.startsWith(resolvedRoot)) {
1110
+ this.logger.warn(`Path traversal attempt detected: ${requestPath} -> ${resolvedFilePath}`);
1111
+ return new Response('Forbidden', { status: 403 });
1112
+ }
1113
+ // 5. Create Bun.file() instance
1114
+ const file = Bun.file(resolvedFilePath);
1115
+ // 5. Check if file exists
1116
+ const fileExists = await file.exists();
1117
+ // 6. File not found → trigger onNotFound hook
1118
+ if (!fileExists) {
1119
+ if (staticServe.onNotFound) {
1120
+ await staticServe.onNotFound.handler(rewrittenPath, context);
1054
1121
  // If hook overrides, return null (let handler continue)
1055
- if (staticServe.onFound.override) {
1122
+ if (staticServe.onNotFound.override) {
1056
1123
  return null;
1057
1124
  }
1058
1125
  }
1059
- // 8. Create Bun file response with automatic Content-Type detection
1060
- const fileResponse = new Response(file);
1061
- // 9. Build response headers starting with Bun's Content-Type
1062
- const finalHeaders = new Headers(fileResponse.headers);
1063
- // 10. Add cache validation headers (ETag and Last-Modified)
1064
- // ETag format: W/"<size>-<lastModified>" (weak validator)
1065
- const etag = `W/"${file.size}-${file.lastModified}"`;
1066
- finalHeaders.set('ETag', etag);
1067
- // Last-Modified: HTTP date format (RFC 7231)
1068
- const lastModified = new Date(file.lastModified).toUTCString();
1069
- finalHeaders.set('Last-Modified', lastModified);
1070
- // 11. Add custom headers (can override defaults)
1071
- const customHeaders = this.buildStaticFileHeaders(resolvedFilePath, staticServe.extra);
1072
- for (const [key, value] of Object.entries(customHeaders)) {
1073
- finalHeaders.set(key, value);
1074
- }
1075
- // 12. Add default Cache-Control if not provided
1076
- // Using 'public, max-age=0' allows caching but requires revalidation
1077
- if (!finalHeaders.has('Cache-Control')) {
1078
- finalHeaders.set('Cache-Control', 'public, max-age=0');
1126
+ // No hook, or a hook that did not take over: fall through to the application's
1127
+ // onNotFound, exactly as an unmatched route does. This used to answer a hard-coded
1128
+ // `text/plain` 404 and never consult the config hook - so the same app produced a
1129
+ // different 404 body here than on the hono adapter, where serveStatic calls next()
1130
+ // and the request lands in app.notFound.
1131
+ return await this.respondToUnmatched(context, new URL(req.url).pathname, req.method);
1132
+ }
1133
+ // 7. File found → trigger onFound hook
1134
+ if (staticServe.onFound) {
1135
+ await staticServe.onFound.handler(rewrittenPath, context);
1136
+ // If hook overrides, return null (let handler continue)
1137
+ if (staticServe.onFound.override) {
1138
+ return null;
1079
1139
  }
1080
- // 13. Return response with all headers
1081
- // This preserves Bun's zero-copy file serving while adding cache headers
1082
- return new Response(fileResponse.body, {
1083
- status: fileResponse.status,
1084
- headers: finalHeaders,
1085
- });
1086
1140
  }
1087
- catch (error) {
1088
- this.logger.error('Static file serving error:', error);
1089
- return new Response(JSON.stringify({
1090
- error: error instanceof Error ? error.message : 'Static file serving failed',
1091
- }), {
1092
- status: 500,
1093
- headers: { 'Content-Type': 'application/json' },
1094
- });
1141
+ // 8. Create Bun file response with automatic Content-Type detection
1142
+ const fileResponse = new Response(file);
1143
+ // 9. Build response headers starting with Bun's Content-Type
1144
+ const finalHeaders = new Headers(fileResponse.headers);
1145
+ // 10. Add cache validation headers (ETag and Last-Modified)
1146
+ // ETag format: W/"<size>-<lastModified>" (weak validator)
1147
+ const etag = `W/"${file.size}-${file.lastModified}"`;
1148
+ finalHeaders.set('ETag', etag);
1149
+ // Last-Modified: HTTP date format (RFC 7231)
1150
+ const lastModified = new Date(file.lastModified).toUTCString();
1151
+ finalHeaders.set('Last-Modified', lastModified);
1152
+ // 11. Add custom headers (can override defaults)
1153
+ const customHeaders = this.buildStaticFileHeaders(resolvedFilePath, staticServe.extra);
1154
+ for (const [key, value] of Object.entries(customHeaders)) {
1155
+ finalHeaders.set(key, value);
1095
1156
  }
1157
+ // 12. Add default Cache-Control if not provided
1158
+ // Using 'public, max-age=0' allows caching but requires revalidation
1159
+ if (!finalHeaders.has('Cache-Control')) {
1160
+ finalHeaders.set('Cache-Control', 'public, max-age=0');
1161
+ }
1162
+ // 13. Return response with all headers
1163
+ // This preserves Bun's zero-copy file serving while adding cache headers
1164
+ return new Response(fileResponse.body, {
1165
+ status: fileResponse.status,
1166
+ headers: finalHeaders,
1167
+ });
1096
1168
  }
1097
1169
  /**
1098
1170
  * Builds response headers for static file serving
@@ -1142,108 +1214,6 @@ export class Ergenecore extends AsenaAdapter {
1142
1214
  }
1143
1215
  return headers;
1144
1216
  }
1145
- /**
1146
- * Extracts base path from a route path
1147
- *
1148
- * Removes dynamic segments (parameters and wildcards) from the path
1149
- * to find the static base path for grouping routes.
1150
- *
1151
- * @param path - Route path (e.g., "/api/users/:id")
1152
- * @returns Base path without dynamic segments (e.g., "/api/users")
1153
- *
1154
- * @example
1155
- * ```typescript
1156
- * extractBasePath('/api/users/:id') // => '/api/users'
1157
- * extractBasePath('/api/users/:id/posts/:postId') // => '/api/users'
1158
- * extractBasePath('/static/*') // => '/static'
1159
- * extractBasePath('/') // => '/'
1160
- * ```
1161
- */
1162
- extractBasePath(path) {
1163
- // Remove trailing slash (except for root)
1164
- const normalized = path.endsWith('/') && path !== '/' ? path.slice(0, -1) : path;
1165
- // Split path into segments
1166
- const segments = normalized.split('/');
1167
- const baseSegments = [];
1168
- // Keep segments until we hit a parameter or wildcard
1169
- for (const segment of segments) {
1170
- // Stop if segment is a parameter (:param) or wildcard (*)
1171
- if (segment.startsWith(':') || segment.includes('*')) {
1172
- break;
1173
- }
1174
- baseSegments.push(segment);
1175
- }
1176
- // Join back into path, handle root case
1177
- return baseSegments.join('/') || '/';
1178
- }
1179
- /**
1180
- * Extracts common middlewares across multiple routes
1181
- *
1182
- * Identifies middlewares that are present in ALL routes and can be
1183
- * moved to group level for optimization.
1184
- *
1185
- * @param routes - Array of routes to analyze
1186
- * @returns Array of common middleware instances
1187
- *
1188
- * @example
1189
- * ```typescript
1190
- * extractCommonMiddlewares([
1191
- * { middlewares: [auth, log, rate] },
1192
- * { middlewares: [auth, log] },
1193
- * { middlewares: [auth, log] }
1194
- * ]) // => [auth, log]
1195
- * ```
1196
- */
1197
- extractCommonMiddlewares(routes) {
1198
- // Need at least 2 routes to have common middlewares
1199
- if (routes.length === 0 || routes.length === 1) {
1200
- return [];
1201
- }
1202
- // Get middlewares from first route as baseline
1203
- const firstRouteMiddlewares = routes[0].middlewares || [];
1204
- // Filter to only middlewares present in ALL routes
1205
- return firstRouteMiddlewares.filter((middleware) => {
1206
- return routes.every((route) => {
1207
- return (route.middlewares || []).some((mw) => {
1208
- // Compare by constructor name (class identity)
1209
- return mw.constructor.name === middleware.constructor.name;
1210
- });
1211
- });
1212
- });
1213
- }
1214
- /**
1215
- * Groups routes by their base path
1216
- *
1217
- * Creates a map of base paths to routes for optimization.
1218
- * Routes with the same base path will share common middlewares.
1219
- *
1220
- * @param routes - Array of routes to group
1221
- * @returns Map of base paths to route arrays
1222
- *
1223
- * @example
1224
- * ```typescript
1225
- * groupRoutesByBasePath([
1226
- * { path: '/api/users' },
1227
- * { path: '/api/users/:id' },
1228
- * { path: '/api/posts' }
1229
- * ])
1230
- * // => Map {
1231
- * // '/api/users' => [route1, route2],
1232
- * // '/api/posts' => [route3]
1233
- * // }
1234
- * ```
1235
- */
1236
- groupRoutesByBasePath(routes) {
1237
- const groups = new Map();
1238
- for (const route of routes) {
1239
- const basePath = this.extractBasePath(route.path);
1240
- if (!groups.has(basePath)) {
1241
- groups.set(basePath, []);
1242
- }
1243
- groups.get(basePath).push(route);
1244
- }
1245
- return groups;
1246
- }
1247
1217
  get hostname() {
1248
1218
  return this._hostname;
1249
1219
  }