All files / src/core/server request-handler.ts

86.54% Statements 148/171
76.63% Branches 82/107
78.94% Functions 15/19
91.71% Lines 144/157

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311                                                                                                          3x     39x     39x       39x         8x               5x 15x         27x 27x 27x 27x 27x 27x 27x   27x 27x 26x 26x 1x     25x 25x 27x   27x 27x   27x 3x 3x 3x 1x 1x 1x       24x 24x 24x 27x   27x 24x   24x 1x 1x 1x 1x 1x 1x 1x     23x 23x   23x 23x 5x       5x       23x   23x 3x 3x 3x 3x 4x 2x 2x 1x 1x 1x 1x 1x     3x   3x 3x 3x       3x 3x   1x     3x 3x   1x 1x 1x 1x 1x 1x 1x 1x       3x     22x                   24x 22x 1x     22x 22x 22x 21x   17x 6x 6x 6x 6x 4x 5x     6x 4x 3x     6x 6x 1x 1x 5x 1x 1x 1x   1x 4x 1x 1x   3x 3x     11x 11x 11x 11x 11x       22x     27x                       24x   4x   4x 4x 1x 1x 1x 1x 1x             1x   3x 3x 2x 2x 1x 1x     2x 2x 2x 2x 2x           2x          
/**
 * Shared request handler for API routes
 * Used by both dev server and preview/production server
 */
 
import type { IncomingMessage, ServerResponse } from 'http';
import type { Connect } from 'vite';
import { matchRoute } from '../routing/route-matcher.js';
import { createContext, isVitekResponse, type VitekResponse } from '../context/create-context.js';
import { getApplicableMiddlewares } from '../middleware/get-applicable-middlewares.js';
import { compose } from '../middleware/compose.js';
import { API_BASE_PATH } from '../../shared/constants.js';
import { HttpError } from '../../shared/errors.js';
import type { Route } from '../routing/route-types.js';
import type { LoadedMiddleware } from '../middleware/get-applicable-middlewares.js';
import type { SocketEmitter } from '../shared/vitek-app.js';
import {
  normalizeCorsOptions,
  getCorsHeaders,
  type NormalizedCorsOptions,
} from './cors.js';
import { getEffectiveRequest } from './proxy.js';
 
/** Callback for beforeApiRequest hook. Call next() to continue, or send response and return without next() to short-circuit. */
export type BeforeApiRequestHook = (
  ctx: { req: IncomingMessage; res: ServerResponse; path: string; method: string },
  next: () => void
) => void | Promise<void>;
 
export interface RequestHandlerOptions {
  routes: Route[];
  middlewares: LoadedMiddleware[];
  /** Hooks called before each API request. Call next() to continue. */
  beforeApiRequest?: BeforeApiRequestHook[];
  /** Enable CORS. true or CorsOptions. When set, OPTIONS preflight and CORS headers on responses are handled. */
  cors?: boolean | import('./cors.js').CorsOptions;
  /** When true, trust X-Forwarded-* headers and set context.clientIp / effective url. */
  trustProxy?: boolean;
  logger?: {
    routeMatched?(pattern: string, method: string): void;
    requestStart?(method: string, path: string): void;
    request?(method: string, path: string, statusCode: number, duration?: number): void;
    warn?(message: string, data?: Record<string, unknown>): void;
    error?(message: string, data?: Record<string, unknown>): void;
  };
  /** When provided, context.sockets is set so route handlers can emit to WebSocket clients. */
  shared?: { sockets: SocketEmitter };
  /** Max request body size in bytes. When exceeded, responds with 413 Payload Too Large. Omit for no limit. */
  maxBodySize?: number;
  /** Called when a non-HttpError is thrown. May send a custom response; if res is not ended, default 500 JSON is sent. */
  onError?: (err: Error, req: IncomingMessage, res: ServerResponse) => void | Promise<void>;
}
 
const noop = () => {};
 
function sanitizeHeaderValue(value: string | number | string[]): string {
  const s = Array.isArray(value)
    ? value.map((v) => String(v).replace(/\r|\n/g, '')).join(', ')
    : String(value).replace(/\r|\n/g, '');
  return s;
}
 
function safeSetHeader(res: ServerResponse, key: string, value: string | number | string[]): void {
  res.setHeader(key, sanitizeHeaderValue(value));
}
 
/** True if value is a Node.js Readable stream (has .pipe). Used for streaming response body. */
function isReadableStream(value: unknown): value is NodeJS.ReadableStream {
  return (
    value != null &&
    typeof value === 'object' &&
    typeof (value as NodeJS.ReadableStream).pipe === 'function'
  );
}
 
function applyCorsHeaders(res: ServerResponse, corsHeaders: Record<string, string>): void {
  for (const [key, value] of Object.entries(corsHeaders)) {
    safeSetHeader(res, key, value);
  }
}
 
export function createRequestHandler(options: RequestHandlerOptions): (req: IncomingMessage, res: ServerResponse, next: Connect.NextFunction) => Promise<void> {
  const { routes, middlewares, beforeApiRequest = [], cors, trustProxy = false, logger, shared, maxBodySize, onError } = options;
  const corsOpts: NormalizedCorsOptions | null = cors != null ? normalizeCorsOptions(cors) : null;
  const logRouteMatched = logger?.routeMatched ?? noop;
  const logRequestStart = logger?.requestStart ?? noop;
  const logRequest = logger?.request ?? noop;
  const logWarn = logger?.warn ?? noop;
  const logError = logger?.error ?? noop;
 
  return async (req: IncomingMessage, res: ServerResponse, next: Connect.NextFunction) => {
    if (!req.url) return next();
    const pathname = req.url.split('?')[0];
    if (pathname !== API_BASE_PATH && !pathname.startsWith(API_BASE_PATH + '/')) {
      return next();
    }
 
    const startTime = Date.now();
    const requestMethod = req.method?.toLowerCase() || 'get';
    const requestPath = pathname;
 
    const effective = getEffectiveRequest(req, trustProxy);
    const requestUrl = effective.url || req.url;
 
    if (corsOpts) {
      const corsHeaders = getCorsHeaders(req, corsOpts);
      applyCorsHeaders(res, corsHeaders);
      if (req.method === 'OPTIONS') {
        res.statusCode = 204;
        res.end();
        return;
      }
    }
 
    try {
      const url = new URL(requestUrl, 'http://localhost');
      const routePath = url.pathname.replace(API_BASE_PATH, '') || '/';
      const method = requestMethod;
 
      const doHandleRequest = async () => {
      const match = matchRoute(routes, routePath, method);
 
      if (!match) {
        const duration = Date.now() - startTime;
        res.statusCode = 404;
        safeSetHeader(res, 'Content-Type', 'application/json');
        Iif (corsOpts) applyCorsHeaders(res, getCorsHeaders(req, corsOpts));
        res.end(JSON.stringify({ error: 'Route not found' }));
        logRequest(requestMethod, requestPath, 404, duration);
        return;
      }
 
      logRouteMatched(match.route.pattern, method);
      logRequestStart(requestMethod, requestPath);
 
      const query: Record<string, string | string[]> = {};
      url.searchParams.forEach((value, key) => {
        Iif (query[key]) {
          const existing = query[key];
          query[key] = Array.isArray(existing) ? [...existing, value] : [existing as string, value];
        } else {
          query[key] = value;
        }
      });
 
      const PAYLOAD_TOO_LARGE_SENTINEL = Symbol('PAYLOAD_TOO_LARGE');
      let body: unknown;
      if (['post', 'put', 'patch'].includes(method)) {
        body = await new Promise<unknown>((resolve, reject) => {
          const chunks: Buffer[] = [];
          let totalSize = 0;
          const onData = (chunk: Buffer) => {
            if (maxBodySize != null) {
              totalSize += chunk.length;
              if (totalSize > maxBodySize) {
                req.removeListener('data', onData);
                req.removeListener('end', onEnd);
                req.destroy();
                reject(new Error('PAYLOAD_TOO_LARGE'));
                return;
              }
            }
            chunks.push(chunk);
          };
          const onEnd = () => {
            const rawBody = Buffer.concat(chunks).toString();
            Iif (!rawBody) {
              resolve(undefined);
              return;
            }
            try {
              resolve(JSON.parse(rawBody));
            } catch {
              resolve(rawBody);
            }
          };
          req.on('data', onData);
          req.on('end', onEnd);
        }).catch((err) => {
          Eif (err?.message === 'PAYLOAD_TOO_LARGE') {
            const duration = Date.now() - startTime;
            res.statusCode = 413;
            safeSetHeader(res, 'Content-Type', 'application/json');
            Iif (corsOpts) applyCorsHeaders(res, getCorsHeaders(req, corsOpts));
            res.end(JSON.stringify({ error: 'Payload Too Large' }));
            logRequest(requestMethod, requestPath, 413, duration);
            return PAYLOAD_TOO_LARGE_SENTINEL;
          }
          throw err;
        });
        if (body === PAYLOAD_TOO_LARGE_SENTINEL) return;
      }
 
      const context = createContext(
        {
          url: requestUrl,
          method,
          headers: (req.headers || {}) as Record<string, string>,
          body,
        },
        match.params,
        query
      );
      if (effective.clientIp) context.clientIp = effective.clientIp;
      if (shared?.sockets) {
        context.sockets = shared.sockets;
      }
 
      const applicableMiddlewares = getApplicableMiddlewares(middlewares, match.route.pattern);
      const composed = compose(applicableMiddlewares);
      const handler = async () => {
        const result = await match.route.handler(context);
 
        if (isVitekResponse(result)) {
          const response = result as VitekResponse;
          const statusCode = response.status || 200;
          Iif (corsOpts) applyCorsHeaders(res, getCorsHeaders(req, corsOpts));
          if (response.headers) {
            for (const [key, value] of Object.entries(response.headers)) {
              safeSetHeader(res, key, value);
            }
          }
          if (!response.headers || !response.headers['Content-Type']) {
            if (response.body !== undefined && !isReadableStream(response.body)) {
              safeSetHeader(res, 'Content-Type', 'application/json');
            }
          }
          res.statusCode = statusCode;
          if (response.body === undefined) {
            res.end();
            logRequest(requestMethod, requestPath, statusCode, Date.now() - startTime);
          } else if (isReadableStream(response.body)) {
            const stream = response.body as NodeJS.ReadableStream;
            res.once('finish', () =>
              logRequest(requestMethod, requestPath, statusCode, Date.now() - startTime)
            );
            stream.pipe(res as NodeJS.WritableStream);
          } else if (typeof response.body === 'string') {
            res.end(response.body);
            logRequest(requestMethod, requestPath, statusCode, Date.now() - startTime);
          } else {
            res.end(JSON.stringify(response.body));
            logRequest(requestMethod, requestPath, statusCode, Date.now() - startTime);
          }
        } else {
          if (corsOpts) applyCorsHeaders(res, getCorsHeaders(req, corsOpts));
          safeSetHeader(res, 'Content-Type', 'application/json');
          res.statusCode = 200;
          res.end(JSON.stringify(result));
          logRequest(requestMethod, requestPath, 200, Date.now() - startTime);
        }
      };
 
      await composed(context, handler);
      };
 
      Iif (beforeApiRequest.length > 0) {
        for (const hook of beforeApiRequest) {
          await new Promise<void>((resolve, reject) => {
            let done = false;
            const next = () => { if (!done) { done = true; resolve(); } };
            Promise.resolve(hook({ req, res, path: routePath, method }, next))
              .then(() => { if (!done && res.writableEnded) { done = true; resolve(); } })
              .catch(reject);
          });
          if (res.writableEnded) return;
        }
      }
      await doHandleRequest();
    } catch (error) {
      const duration = Date.now() - startTime;
 
      Iif (corsOpts) applyCorsHeaders(res, getCorsHeaders(req, corsOpts));
      if (error instanceof HttpError) {
        const httpError = error as HttpError;
        logWarn(`HTTP Error ${httpError.statusCode}: ${httpError.message}`);
        res.statusCode = httpError.statusCode;
        safeSetHeader(res, 'Content-Type', 'application/json');
        res.end(
          JSON.stringify({
            error: httpError.name,
            message: httpError.message,
            code: httpError.code,
          })
        );
        logRequest(requestMethod, requestPath, httpError.statusCode, duration);
      } else {
        const err = error instanceof Error ? error : new Error(String(error));
        if (onError) {
          await Promise.resolve(onError(err, req, res));
          if (res.writableEnded) {
            logRequest(requestMethod, requestPath, res.statusCode, duration);
            return;
          }
        }
        const errorMessage = err.message;
        logError(`Error handling request: ${errorMessage}`);
        res.statusCode = 500;
        safeSetHeader(res, 'Content-Type', 'application/json');
        res.end(
          JSON.stringify({
            error: 'Internal server error',
            message: errorMessage,
          })
        );
        logRequest(requestMethod, requestPath, 500, duration);
      }
    }
  };
}