barejs 0.2.5 → 0.2.7

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.
@@ -15,6 +15,37 @@ export type InferSchema<S> =
15
15
  : S extends { _output: infer T } ? T
16
16
  : any;
17
17
 
18
+ type SuccessStatusKey = 200 | 201 | 202 | 203 | 204 | '200' | '201' | '202' | '203' | '204';
19
+ type ErrorStatusKey =
20
+ | 400 | 401 | 403 | 404 | 409 | 413 | 415 | 422 | 429 | 500 | 502 | 503
21
+ | '400' | '401' | '403' | '404' | '409' | '413' | '415' | '422' | '429' | '500' | '502' | '503';
22
+
23
+ type IsSingleSchema<S> =
24
+ S extends { '~standard': any } ? true
25
+ : S extends { static: any } ? true
26
+ : S extends { _output: any } ? true
27
+ : S extends { type: string } ? true
28
+ : S extends { properties: Record<string, any> } ? true
29
+ : false;
30
+
31
+ export type InferResponseSuccess<R> =
32
+ IsSingleSchema<R> extends true
33
+ ? InferSchema<R>
34
+ : R extends Record<string | number, any>
35
+ ? ([Extract<keyof R, SuccessStatusKey>] extends [never]
36
+ ? InferSchema<R[keyof R]>
37
+ : InferSchema<R[Extract<keyof R, SuccessStatusKey>]>)
38
+ : InferSchema<R>;
39
+
40
+ export type InferResponseError<R> =
41
+ IsSingleSchema<R> extends true
42
+ ? any
43
+ : R extends Record<string | number, any>
44
+ ? ([Extract<keyof R, ErrorStatusKey>] extends [never]
45
+ ? any
46
+ : InferSchema<R[Extract<keyof R, ErrorStatusKey>]>)
47
+ : any;
48
+
18
49
  type StripLeadingSlash<S extends string> = S extends `/${infer Rest}` ? StripLeadingSlash<Rest> : S;
19
50
  type StripTrailingSlash<S extends string> = S extends `${infer Rest}/` ? StripTrailingSlash<Rest> : S;
20
51
  type NormalizePrefix<P extends string> = StripTrailingSlash<StripLeadingSlash<P>> extends ''
@@ -45,11 +76,12 @@ type TypedRouterHandler<S extends RouteSchemas, Res> = (
45
76
  body: S extends { body: infer B } ? InferSchema<B> : any;
46
77
  query: S extends { query: infer Q } ? InferSchema<Q> : Record<string, string>;
47
78
  params: S extends { params: infer Pa } ? InferSchema<Pa> : Record<string, any>;
79
+ cookies: S extends { cookies: infer C } ? InferSchema<C> : Record<string, string>;
48
80
  }
49
81
  ) => Res | Promise<Res>;
50
82
 
51
83
  type AddRouterRoute<Routes extends RouteSchema, M extends string> = {
52
- <P extends string, S extends RouteSchemas, Res = S extends { response: infer R } ? InferSchema<R> : any>(
84
+ <P extends string, S extends RouteSchemas, Res = S extends { response: infer R } ? (InferResponseSuccess<R> | InferResponseError<R>) : any>(
53
85
  path: P,
54
86
  schemas: S,
55
87
  handler: TypedRouterHandler<S, Res>
@@ -60,12 +92,13 @@ type AddRouterRoute<Routes extends RouteSchema, M extends string> = {
60
92
  query: S extends { query: infer Q } ? InferSchema<Q> : Record<string, any>;
61
93
  headers: S extends { headers: infer H } ? InferSchema<H> : Record<string, string>;
62
94
  body: S extends { body: infer B } ? InferSchema<B> : any;
63
- response: S extends { response: infer R } ? InferSchema<R> : Awaited<Res>;
95
+ response: S extends { response: infer R } ? InferResponseSuccess<R> : Awaited<Res>;
96
+ error: S extends { response: infer R } ? InferResponseError<R> : any;
64
97
  }>>;
65
98
  <P extends string, Res = any>(
66
99
  path: P,
67
100
  ...handlers: any[]
68
- ): BareRouter<Routes & Record<`${M} ${P}`, { method: M; path: P; response: Awaited<Res> }>>;
101
+ ): BareRouter<Routes & Record<`${M} ${P}`, { method: M; path: P; response: Awaited<Res>; error: any }>>;
69
102
  };
70
103
 
71
104
  export class BareRouter<Routes extends RouteSchema = {}> {
@@ -1,8 +1,23 @@
1
- export interface WebSocketRouteHandler {
1
+ export interface WebSocketRouteHandler<Body = string | Buffer, Query = any, Headers = any, Res = any> {
2
+ /** Optional schema (Standard Schema v1 / TypeBox / Zod / Native) for incoming JSON messages */
3
+ body?: any;
4
+ /** Optional schema for WebSocket upgrade query parameters */
5
+ query?: any;
6
+ /** Optional schema for WebSocket upgrade request headers */
7
+ headers?: any;
8
+ /** Optional schema describing outgoing server messages (for typed bareTreaty/bareClient) */
9
+ response?: any;
10
+ /** Optional error callback when an incoming WS message fails `body` validation */
11
+ onValidationError?: (ws: any, error: { code: string; error: any; raw: any }) => void;
2
12
  open?: (ws: any) => void;
3
- message?: (ws: any, message: string | Buffer) => void;
13
+ message?: (ws: any, message: Body) => void | Promise<void>;
4
14
  close?: (ws: any, code: number, reason: string) => void;
5
15
  drain?: (ws: any) => void;
16
+ /** @internal Pre-compiled fail-closed upgrade validator (only present when query/headers schema is set) */
17
+ __validateUpgrade?: (urlOrReq: string | Request, headers?: Record<string, string> | Headers) =>
18
+ | { ok: true; query?: Query; headers?: Headers }
19
+ | { ok: false; code: string; error: any }
20
+ | Promise<{ ok: true; query?: Query; headers?: Headers } | { ok: false; code: string; error: any }>;
6
21
  }
7
22
 
8
23
  export interface WsMatchResult {
package/src/edge.ts CHANGED
@@ -468,6 +468,8 @@ export function createSingleflight() {
468
468
  };
469
469
  }
470
470
 
471
+ export { tracing, serverTiming, type TracingOptions, type TracingSpan } from './utils/tracing';
472
+
471
473
  export {
472
474
  BareEdge as BareJS,
473
475
  BareRouter,
package/src/index.ts CHANGED
@@ -6,8 +6,8 @@
6
6
  */
7
7
 
8
8
  // --- 1. Core Engine ---
9
- export { BareJS, normalizePoolSize, type WebSocketRouteHandler, type CronOptions, type NotFoundResponse } from './core/bare';
10
- export { BareRouter, type InferSchema, type PrefixRoutes } from './core/router';
9
+ export { BareJS, normalizePoolSize, type MacroDefinition, type WebSocketRouteHandler, type CronOptions, type NotFoundResponse } from './core/bare';
10
+ export { BareRouter, type InferSchema, type InferResponseSuccess, type InferResponseError, type PrefixRoutes } from './core/router';
11
11
 
12
12
  /**
13
13
  * Plugin Interface for BareJS
@@ -37,7 +37,7 @@ import { Type } from "@sinclair/typebox";
37
37
  export { Type, Type as T, Type as TypeBox };
38
38
 
39
39
  // --- 4. The Validation Suite (Engines - สำหรับเป็น Middleware) ---
40
- import { typebox, zod, native, standard, validate, schemaValidator, createResponseFilter, Z, type RouteSchemas, type RouteDetail, type StandardSchemaV1 } from './security/validators';
40
+ import { typebox, zod, native, standard, validate, schemaValidator, createResponseFilter, isStatusResponseMap, Z, type RouteSchemas, type RouteDetail, type StandardSchemaV1 } from './security/validators';
41
41
  export {
42
42
  // TypeBox Engine
43
43
  typebox,
@@ -58,6 +58,7 @@ export {
58
58
  // Unified Route Schema Engine (body, query, params, headers, response, detail, maxBodySize)
59
59
  schemaValidator,
60
60
  createResponseFilter,
61
+ isStatusResponseMap,
61
62
  type RouteSchemas,
62
63
  type RouteDetail,
63
64
  type StandardSchemaV1
@@ -83,8 +84,10 @@ export {
83
84
  export { circuitBreaker, type CircuitBreakerOptions, type CircuitState } from './security/resilience';
84
85
  export { securityHeaders, type SecurityHeadersOptions } from './security/headers';
85
86
  export { staticFile, type StaticOptions, type StaticMetadataCacheOptions } from './utils/static';
87
+ export { file, type FileResponseOptions } from './utils/file';
86
88
  export { compress, type CompressOptions, type CompressionEncoding } from './utils/compress';
87
89
  export { generateOpenAPISpec, renderDocsHTML, type OpenAPIOptions } from './utils/openapi';
90
+ export { tracing, serverTiming, type TracingOptions, type TracingSpan } from './utils/tracing';
88
91
 
89
92
  // --- 6. Authentication (Bun Native) ---
90
93
  // Always deploy using process.env [2026-01-06]
@@ -99,6 +102,7 @@ export {
99
102
  type BareClient,
100
103
  type BareSafeClient,
101
104
  type BareTreatyNode,
105
+ type TreatyTree,
102
106
  type BareClientResult,
103
107
  type BareWsClient,
104
108
  type BareClientOptions,
@@ -34,13 +34,33 @@ export const bunDriver: RuntimeDriver = {
34
34
  fetch(req: Request, srv: any) {
35
35
  if (req.headers.get('upgrade')?.toLowerCase() === 'websocket') {
36
36
  const matched = matchWsRoute(wsCfg.routes, req.url);
37
- if (
38
- matched &&
39
- srv.upgrade(req, {
40
- data: matched.params ? { ...matched.handler, params: matched.params } : matched.handler
41
- })
42
- ) {
43
- return undefined as any;
37
+ if (matched) {
38
+ const doUpgrade = (extra?: { query?: any; headers?: any }) => {
39
+ const data =
40
+ matched.params || extra
41
+ ? { ...matched.handler, ...(matched.params ? { params: matched.params } : {}), ...(extra || {}) }
42
+ : matched.handler;
43
+ return srv.upgrade(req, { data }) ? (undefined as any) : new Response('Upgrade failed', { status: 400 });
44
+ };
45
+ const validate = matched.handler.__validateUpgrade;
46
+ if (validate) {
47
+ const vr = validate(req);
48
+ if (vr && typeof (vr as any).then === 'function') {
49
+ return (vr as Promise<any>).then((r) =>
50
+ r?.ok
51
+ ? doUpgrade({ query: r.query, headers: r.headers })
52
+ : Response.json({ status: 'error', code: r?.code || 'WS_UPGRADE_INVALID', error: r?.error }, { status: 400 })
53
+ );
54
+ }
55
+ if (!(vr as any)?.ok) {
56
+ return Response.json(
57
+ { status: 'error', code: (vr as any)?.code || 'WS_UPGRADE_INVALID', error: (vr as any)?.error },
58
+ { status: 400 }
59
+ );
60
+ }
61
+ return doUpgrade({ query: (vr as any).query, headers: (vr as any).headers });
62
+ }
63
+ if (doUpgrade() === undefined) return undefined as any;
44
64
  }
45
65
  }
46
66
  return opts.fetch(req, srv?.requestIP?.(req)?.address);
@@ -446,8 +446,23 @@ export const nodeDriver: RuntimeDriver = {
446
446
  return;
447
447
  }
448
448
  try {
449
+ let extra: { query?: any; headers?: any } | undefined;
450
+ if (matched.handler.__validateUpgrade) {
451
+ const vr = await matched.handler.__validateUpgrade(req.url || '/', req.headers as Record<string, string>);
452
+ if (!vr?.ok) {
453
+ try {
454
+ socket.write('HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n');
455
+ } catch {}
456
+ socket.destroy();
457
+ return;
458
+ }
459
+ extra = { query: vr.query, headers: vr.headers };
460
+ }
449
461
  const wss = await getWss();
450
- const data = matched.params ? { ...matched.handler, params: matched.params } : matched.handler;
462
+ const data =
463
+ matched.params || extra
464
+ ? { ...matched.handler, ...(matched.params ? { params: matched.params } : {}), ...(extra || {}) }
465
+ : matched.handler;
451
466
  if (!wss) {
452
467
  handleNativeWsUpgrade(req, socket, head, data);
453
468
  return;
@@ -581,16 +581,56 @@ export function serveUws(
581
581
  res.writeStatus('404 Not Found').end();
582
582
  return;
583
583
  }
584
- const handler: any = matched.params
585
- ? { ...matched.handler, params: matched.params }
586
- : matched.handler;
587
- res.upgrade(
588
- { handler, wrapped: null },
589
- req.getHeader('sec-websocket-key'),
590
- req.getHeader('sec-websocket-protocol'),
591
- req.getHeader('sec-websocket-extensions'),
592
- context
593
- );
584
+ const wsKey = req.getHeader('sec-websocket-key');
585
+ const wsProto = req.getHeader('sec-websocket-protocol');
586
+ const wsExt = req.getHeader('sec-websocket-extensions');
587
+ const validate = matched.handler.__validateUpgrade;
588
+ if (!validate) {
589
+ const handler: any = matched.params
590
+ ? { ...matched.handler, params: matched.params }
591
+ : matched.handler;
592
+ res.upgrade({ handler, wrapped: null }, wsKey, wsProto, wsExt, context);
593
+ return;
594
+ }
595
+
596
+ const hdrs: Record<string, string> = {};
597
+ req.forEach((k: string, v: string) => {
598
+ const lower = k.toLowerCase();
599
+ if (lower !== '__proto__' && lower !== 'constructor' && lower !== 'prototype') hdrs[lower] = v;
600
+ });
601
+
602
+ const finishUpgrade = (vr: any, isAsync: boolean) => {
603
+ if (!vr?.ok) {
604
+ const body = JSON.stringify({ status: 'error', code: vr?.code || 'WS_UPGRADE_INVALID', error: vr?.error });
605
+ const sendErr = () => {
606
+ res.writeStatus('400 Bad Request').writeHeader('content-type', 'application/json').end(body);
607
+ };
608
+ if (isAsync) res.cork(sendErr);
609
+ else sendErr();
610
+ return;
611
+ }
612
+ const handler: any = {
613
+ ...matched.handler,
614
+ ...(matched.params ? { params: matched.params } : {}),
615
+ ...(vr.query !== undefined ? { query: vr.query } : {}),
616
+ ...(vr.headers !== undefined ? { headers: vr.headers } : {})
617
+ };
618
+ const doUp = () => res.upgrade({ handler, wrapped: null }, wsKey, wsProto, wsExt, context);
619
+ if (isAsync) res.cork(doUp);
620
+ else doUp();
621
+ };
622
+
623
+ const vr = validate(fullUrl, hdrs);
624
+ if (vr && typeof (vr as any).then === 'function') {
625
+ let aborted = false;
626
+ res.onAborted(() => { aborted = true; });
627
+ (vr as Promise<any>).then(
628
+ (resolved) => { if (!aborted) finishUpgrade(resolved, true); },
629
+ () => { if (!aborted) finishUpgrade({ ok: false, code: 'WS_UPGRADE_INVALID' }, true); }
630
+ );
631
+ return;
632
+ }
633
+ finishUpgrade(vr, false);
594
634
  },
595
635
  open(ws: any) {
596
636
  wsCfg.adapter.open(getWrapped(ws));
@@ -244,6 +244,7 @@ export interface RouteSchemas {
244
244
  query?: any;
245
245
  params?: any;
246
246
  headers?: any;
247
+ cookies?: any;
247
248
  response?: any;
248
249
  /** Strip undeclared properties from validated body using JIT projector (prevents Mass Assignment) */
249
250
  stripUnknown?: boolean;
@@ -527,7 +528,7 @@ const compileNativeCheck = (schema: any): ((val: any) => { ok: boolean; data?: a
527
528
  type CheckResult = { ok: boolean; data?: any; error?: any };
528
529
  type SchemaChecker = (val: any) => CheckResult | Promise<CheckResult>;
529
530
 
530
- const compileSingleSchema = (schema: any): SchemaChecker => {
531
+ export const compileSingleSchema = (schema: any): SchemaChecker => {
531
532
  if (schema && '_def' in schema) {
532
533
  return (val: any) => {
533
534
  const r = schema.safeParse(val);
@@ -794,7 +795,52 @@ const compileProjector = (schema: any): ((val: any) => any) | null => {
794
795
  )();
795
796
  };
796
797
 
797
- export const createResponseFilter = (schema: any): ((val: any) => any) => {
798
+ const STATUS_CODE_RE = /^[1-5]\d\d$/;
799
+
800
+ /**
801
+ * Detects whether a `response` option is a per-status schema map
802
+ * (e.g. `{ 200: UserSchema, 404: NotFoundSchema }`) rather than a single schema.
803
+ */
804
+ export const isStatusResponseMap = (schema: any): boolean => {
805
+ if (!schema || typeof schema !== 'object' || Array.isArray(schema)) return false;
806
+ if (
807
+ '~standard' in schema ||
808
+ '_def' in schema ||
809
+ typeof schema.parse === 'function' ||
810
+ 'type' in schema ||
811
+ 'properties' in schema ||
812
+ 'anyOf' in schema ||
813
+ 'oneOf' in schema ||
814
+ 'allOf' in schema ||
815
+ '$ref' in schema ||
816
+ Symbol.for('TypeBox.Kind') in schema
817
+ ) {
818
+ return false;
819
+ }
820
+ const keys = Object.keys(schema);
821
+ if (keys.length === 0) return false;
822
+ for (let i = 0; i < keys.length; i++) {
823
+ if (!STATUS_CODE_RE.test(keys[i]!)) return false;
824
+ }
825
+ return true;
826
+ };
827
+
828
+ export const createResponseFilter = (schema: any): ((val: any, status?: number) => any) => {
829
+ if (isStatusResponseMap(schema)) {
830
+ const byStatus = new Map<number, (val: any, status?: number) => any>();
831
+ for (const [codeStr, subSchema] of Object.entries(schema)) {
832
+ const code = Number(codeStr);
833
+ if (Number.isInteger(code) && code >= 100 && code <= 599) {
834
+ byStatus.set(code, createResponseFilter(subSchema));
835
+ }
836
+ }
837
+ return (val: any, status?: number) => {
838
+ const code = status ?? (val instanceof Response ? val.status : 200);
839
+ const filter = byStatus.get(code);
840
+ return filter ? filter(val, code) : val;
841
+ };
842
+ }
843
+
798
844
  const check = compileSingleSchema(schema);
799
845
  const project = compileProjector(schema);
800
846
 
@@ -864,9 +910,11 @@ export const schemaValidator = (schemas: RouteSchemas): Middleware => {
864
910
  const queryCheck = schemas.query ? compileSingleSchema(schemas.query) : null;
865
911
  const paramsCheck = schemas.params ? compileSingleSchema(schemas.params) : null;
866
912
  const headersCheck = schemas.headers ? compileSingleSchema(schemas.headers) : null;
913
+ const cookiesCheck = schemas.cookies ? compileSingleSchema(schemas.cookies) : null;
867
914
  const bodyProjector = schemas.stripUnknown && schemas.body ? compileProjector(schemas.body) : null;
868
915
  const queryProjector = schemas.stripUnknown && schemas.query ? compileProjector(schemas.query) : null;
869
916
  const paramsProjector = schemas.stripUnknown && schemas.params ? compileProjector(schemas.params) : null;
917
+ const cookiesProjector = schemas.stripUnknown && schemas.cookies ? compileProjector(schemas.cookies) : null;
870
918
  const responseFilter = schemas.response ? createResponseFilter(schemas.response) : null;
871
919
  const maxBodySize = schemas.maxBodySize ?? 1048576;
872
920
  const queryArrayKeys: string[] = [];
@@ -897,11 +945,28 @@ export const schemaValidator = (schemas: RouteSchemas): Middleware => {
897
945
  }
898
946
  }
899
947
  }
900
- const hasSyncParts = Boolean(paramsCheck || queryCheck || headersCheck);
948
+ const hasSyncParts = Boolean(paramsCheck || queryCheck || headersCheck || cookiesCheck);
901
949
 
902
950
  const validateSyncParts = (ctx: Context): Response | undefined | Promise<Response | undefined> => {
951
+ const runCookies = (): Response | undefined | Promise<Response | undefined> => {
952
+ if (!cookiesCheck) return undefined;
953
+ const coerced = coerceFields(ctx.cookies, schemas.cookies);
954
+ const r = cookiesCheck(coerced);
955
+ if (r && typeof (r as any).then === 'function') {
956
+ return (r as Promise<CheckResult>).then((res) => {
957
+ if (!res.ok) return errorJSON({ status: 'error', code: 'COOKIES_INVALID', error: res.error });
958
+ ctx._cookies = cookiesProjector ? cookiesProjector(res.data) : res.data;
959
+ return undefined;
960
+ });
961
+ }
962
+ const syncR = r as CheckResult;
963
+ if (!syncR.ok) return errorJSON({ status: 'error', code: 'COOKIES_INVALID', error: syncR.error });
964
+ ctx._cookies = cookiesProjector ? cookiesProjector(syncR.data) : syncR.data;
965
+ return undefined;
966
+ };
967
+
903
968
  const runHeaders = (): Response | undefined | Promise<Response | undefined> => {
904
- if (!headersCheck) return undefined;
969
+ if (!headersCheck) return runCookies();
905
970
  const hdrObj: Record<string, string> = {};
906
971
  ctx.req.headers.forEach((v, k) => {
907
972
  const lower = k.toLowerCase();
@@ -912,12 +977,12 @@ export const schemaValidator = (schemas: RouteSchemas): Middleware => {
912
977
  const r = headersCheck(hdrObj);
913
978
  if (r && typeof (r as any).then === 'function') {
914
979
  return (r as Promise<CheckResult>).then((res) =>
915
- res.ok ? undefined : errorJSON({ status: 'error', code: 'HEADERS_INVALID', error: res.error })
980
+ res.ok ? runCookies() : errorJSON({ status: 'error', code: 'HEADERS_INVALID', error: res.error })
916
981
  );
917
982
  }
918
983
  const syncR = r as CheckResult;
919
984
  if (!syncR.ok) return errorJSON({ status: 'error', code: 'HEADERS_INVALID', error: syncR.error });
920
- return undefined;
985
+ return runCookies();
921
986
  };
922
987
 
923
988
  const runQuery = (): Response | undefined | Promise<Response | undefined> => {
@@ -0,0 +1,111 @@
1
+ import { existsSync, realpathSync, statSync } from 'node:fs';
2
+ import { basename, resolve, sep } from 'node:path';
3
+ import { runtime } from '../runtime';
4
+
5
+ export interface FileResponseOptions {
6
+ /** Optional root directory jail — blocks path traversal and symlinks escaping `root` (403) */
7
+ root?: string;
8
+ /** Override Content-Type header */
9
+ type?: string;
10
+ /** Set Content-Disposition: attachment (pass `true` for basename or a custom filename) */
11
+ download?: boolean | string;
12
+ /** Optional Cache-Control header value */
13
+ cacheControl?: string;
14
+ /** Additional custom response headers */
15
+ headers?: Record<string, string>;
16
+ /** HTTP status code (default: 200) */
17
+ status?: number;
18
+ }
19
+
20
+ const sanitizeHeaderVal = (v: string): string => v.replace(/[\r\n]+/g, '');
21
+
22
+ /**
23
+ * Ergonomic 1-liner file response helper:
24
+ * `app.get('/logo', () => file('public/logo.png'))`
25
+ * `app.get('/dl/:name', (ctx) => file(ctx.params.name, { root: './uploads', download: true }))`
26
+ *
27
+ * Uses zero-copy `Bun.file` on Bun and streaming `fs.createReadStream` on Node.js.
28
+ * Enforces null-byte rejection and optional `root` directory/symlink containment.
29
+ */
30
+ export const file = (filePath: string, options: FileResponseOptions = {}): Response => {
31
+ if (typeof filePath !== 'string' || filePath.length === 0 || filePath.includes('\0')) {
32
+ return new Response('Bad Request', { status: 400 });
33
+ }
34
+
35
+ let resolved: string;
36
+ if (options.root) {
37
+ let decodedPath = filePath;
38
+ if (decodedPath.includes('%')) {
39
+ try {
40
+ decodedPath = decodeURIComponent(decodedPath);
41
+ } catch {
42
+ return new Response('Bad Request', { status: 400 });
43
+ }
44
+ if (decodedPath.includes('\0')) {
45
+ return new Response('Bad Request', { status: 400 });
46
+ }
47
+ }
48
+ const rootAbs = resolve(options.root);
49
+ let realRoot: string;
50
+ try {
51
+ realRoot = realpathSync(rootAbs);
52
+ } catch {
53
+ return new Response('Not Found', { status: 404 });
54
+ }
55
+ const cleanRel = decodedPath.replace(/^[/\\]+/, '');
56
+ const candidate = resolve(realRoot, cleanRel);
57
+ if (candidate !== realRoot && !candidate.startsWith(realRoot + sep)) {
58
+ return new Response('Forbidden', { status: 403 });
59
+ }
60
+ if (!existsSync(candidate)) {
61
+ return new Response('Not Found', { status: 404 });
62
+ }
63
+ try {
64
+ resolved = realpathSync(candidate);
65
+ } catch {
66
+ return new Response('Not Found', { status: 404 });
67
+ }
68
+ if (resolved !== realRoot && !resolved.startsWith(realRoot + sep)) {
69
+ return new Response('Forbidden', { status: 403 });
70
+ }
71
+ } else {
72
+ resolved = resolve(filePath);
73
+ if (!existsSync(resolved)) {
74
+ return new Response('Not Found', { status: 404 });
75
+ }
76
+ }
77
+
78
+ let st;
79
+ try {
80
+ st = statSync(resolved);
81
+ } catch {
82
+ return new Response('Not Found', { status: 404 });
83
+ }
84
+ if (!st.isFile()) {
85
+ return new Response('Not Found', { status: 404 });
86
+ }
87
+
88
+ const handle = runtime.openFile(resolved);
89
+ const headers: Record<string, string> = {
90
+ 'content-type': sanitizeHeaderVal(options.type || handle.type || 'application/octet-stream'),
91
+ 'content-length': String(st.size)
92
+ };
93
+ if (options.cacheControl) {
94
+ headers['cache-control'] = sanitizeHeaderVal(options.cacheControl);
95
+ }
96
+ if (options.download) {
97
+ const rawName = typeof options.download === 'string' ? options.download : basename(resolved);
98
+ const safeName = sanitizeHeaderVal(rawName).replace(/["\\]/g, '_');
99
+ headers['content-disposition'] = `attachment; filename="${safeName}"`;
100
+ }
101
+ if (options.headers) {
102
+ for (const [k, v] of Object.entries(options.headers)) {
103
+ headers[k] = sanitizeHeaderVal(String(v));
104
+ }
105
+ }
106
+
107
+ return new Response(handle.full(), {
108
+ status: options.status ?? 200,
109
+ headers
110
+ });
111
+ };
@@ -1,3 +1,5 @@
1
+ import { isStatusResponseMap } from '../security/validators';
2
+
1
3
  export interface OpenAPIOptions {
2
4
  title?: string;
3
5
  version?: string;
@@ -118,8 +120,15 @@ export const generateOpenAPISpec = (routes: any[], options: OpenAPIOptions = {})
118
120
  params.push({ name: k, in: 'header', required: hReq.has(k), schema: prop });
119
121
  }
120
122
  }
123
+ if (rs.cookies) {
124
+ const cSchema = extractSchema(rs.cookies);
125
+ const cReq = new Set<string>(cSchema.required || []);
126
+ for (const [k, prop] of Object.entries(cSchema.properties || {})) {
127
+ params.push({ name: k, in: 'cookie', required: cReq.has(k), schema: prop });
128
+ }
129
+ }
121
130
  if (rs.response) {
122
- responseSchema = extractSchema(rs.response);
131
+ responseSchema = rs.response;
123
132
  }
124
133
  }
125
134
  if ((h as any).__schema && !requestBody) {
@@ -151,6 +160,41 @@ export const generateOpenAPISpec = (routes: any[], options: OpenAPIOptions = {})
151
160
  }
152
161
  const allParams = [...pathParams, ...params];
153
162
 
163
+ const STATUS_DESCRIPTIONS: Record<string, string> = {
164
+ '200': 'Success',
165
+ '201': 'Created',
166
+ '202': 'Accepted',
167
+ '204': 'No Content',
168
+ '400': 'Bad Request',
169
+ '401': 'Unauthorized',
170
+ '403': 'Forbidden',
171
+ '404': 'Not Found',
172
+ '409': 'Conflict',
173
+ '413': 'Payload Too Large',
174
+ '415': 'Unsupported Media Type',
175
+ '422': 'Unprocessable Entity',
176
+ '429': 'Too Many Requests',
177
+ '500': 'Internal Server Error',
178
+ '503': 'Service Unavailable'
179
+ };
180
+
181
+ const responses: Record<string, any> = {};
182
+ if (responseSchema && isStatusResponseMap(responseSchema)) {
183
+ for (const [code, subSchema] of Object.entries(responseSchema)) {
184
+ responses[code] = {
185
+ description: STATUS_DESCRIPTIONS[code] || `Response ${code}`,
186
+ content: { 'application/json': { schema: extractSchema(subSchema) } }
187
+ };
188
+ }
189
+ } else {
190
+ responses['200'] = {
191
+ description: 'Success',
192
+ ...(responseSchema
193
+ ? { content: { 'application/json': { schema: extractSchema(responseSchema) } } }
194
+ : {})
195
+ };
196
+ }
197
+
154
198
  paths[openApiPath][method] = {
155
199
  summary: detail?.summary || `${route.method} ${openApiPath}`,
156
200
  ...(detail?.description ? { description: detail.description } : {}),
@@ -158,14 +202,7 @@ export const generateOpenAPISpec = (routes: any[], options: OpenAPIOptions = {})
158
202
  ...(routeSecurity.length ? { security: routeSecurity } : {}),
159
203
  ...(allParams.length ? { parameters: allParams } : {}),
160
204
  ...(requestBody ? { requestBody } : {}),
161
- responses: {
162
- '200': {
163
- description: 'Success',
164
- ...(responseSchema
165
- ? { content: { 'application/json': { schema: responseSchema } } }
166
- : {})
167
- }
168
- }
205
+ responses
169
206
  };
170
207
  }
171
208