barejs 0.1.48 → 0.1.50

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.
@@ -30,10 +30,10 @@ const errorJSON = (data: any, status = 400) =>
30
30
  export const typebox = (schema: any): Middleware => {
31
31
  const check = Compiler.TypeCompiler.Compile(schema);
32
32
 
33
- return async (ctx: Context, next?: Next) => {
33
+ const mw: Middleware = async (ctx: any, next?: Next) => {
34
34
  try {
35
- // const body = await ctx.req.json();
36
- const body = await ctx.jsonBody();
35
+ const isCtx = ctx instanceof Object && 'req' in ctx;
36
+ const body = isCtx ? await ctx.jsonBody() : await ctx.json();
37
37
 
38
38
  if (!check.Check(body)) {
39
39
  const error = check.Errors(body).First();
@@ -45,13 +45,14 @@ export const typebox = (schema: any): Middleware => {
45
45
  });
46
46
  }
47
47
 
48
- // ✅ FIX TS18046: Cast to 'any' to allow assignment to 'unknown' body
49
- (ctx as any).body = body;
48
+ if (isCtx) (ctx as any).body = body;
50
49
  return next ? next() : undefined;
51
50
  } catch {
52
51
  return errorJSON({ status: 'error', message: 'Malformed JSON payload' });
53
52
  }
54
53
  };
54
+ (mw as any).__schema = schema;
55
+ return mw;
55
56
  };
56
57
 
57
58
  /**
@@ -61,8 +62,9 @@ export const native = (schema: any): Middleware => {
61
62
  const props = schema.properties || {};
62
63
  const keys = Object.keys(props);
63
64
  const kLen = keys.length;
65
+ const reqSet = Array.isArray(schema.required) ? new Set<string>(schema.required) : null;
64
66
 
65
- return async (ctx: any, next?: any) => {
67
+ const mw: Middleware = async (ctx: any, next?: any) => {
66
68
  try {
67
69
  const isCtx = ctx instanceof Object && 'req' in ctx;
68
70
  const body = isCtx ? await ctx.jsonBody() : await ctx.json();
@@ -73,7 +75,19 @@ export const native = (schema: any): Middleware => {
73
75
 
74
76
  for (let i = 0; i < kLen; i++) {
75
77
  const k = keys[i]!;
76
- if (!Object.hasOwn(body, k) || typeof body[k] !== props[k]?.type) {
78
+ const hasKey = Object.hasOwn(body, k) && body[k] !== undefined;
79
+ if (!hasKey) {
80
+ if (!reqSet || reqSet.has(k)) {
81
+ return errorJSON({
82
+ status: 'error',
83
+ code: 'TYPE_MISMATCH',
84
+ message: `Field '${k}' must be of type ${props[k]?.type}`,
85
+ field: k
86
+ });
87
+ }
88
+ continue;
89
+ }
90
+ if (typeof body[k] !== props[k]?.type) {
77
91
  return errorJSON({
78
92
  status: 'error',
79
93
  code: 'TYPE_MISMATCH',
@@ -90,13 +104,15 @@ export const native = (schema: any): Middleware => {
90
104
  return errorJSON({ status: 'error', message: 'Invalid JSON payload' });
91
105
  }
92
106
  };
107
+ (mw as any).__schema = schema;
108
+ return mw;
93
109
  };
94
110
 
95
111
  /**
96
112
  * Zod Engine (z)
97
113
  */
98
114
  export const zod = (schema: z.ZodSchema): Middleware => {
99
- return async (ctx: any, next?: any) => {
115
+ const mw: Middleware = async (ctx: any, next?: any) => {
100
116
  try {
101
117
  const isCtx = ctx instanceof Object && 'req' in ctx;
102
118
  const body = isCtx ? await ctx.jsonBody() : await ctx.json();
@@ -118,6 +134,8 @@ export const zod = (schema: z.ZodSchema): Middleware => {
118
134
  return errorJSON({ status: 'error', message: 'Invalid JSON payload' });
119
135
  }
120
136
  };
137
+ (mw as any).__schema = schema;
138
+ return mw;
121
139
  };
122
140
 
123
141
  /**
@@ -131,4 +149,183 @@ export const validate = (schema: any): Middleware => {
131
149
  return native(schema);
132
150
  };
133
151
 
134
- export { typebox as t, zod as z, native as n, validate as v };
152
+ export { typebox as t, zod as z, native as n, validate as v };
153
+
154
+ export interface RouteDetail {
155
+ summary?: string;
156
+ description?: string;
157
+ tags?: string[];
158
+ }
159
+
160
+ export interface RouteSchemas {
161
+ body?: any;
162
+ query?: any;
163
+ params?: any;
164
+ headers?: any;
165
+ response?: any;
166
+ detail?: RouteDetail;
167
+ maxBodySize?: number;
168
+ }
169
+
170
+ const compileSingleSchema = (schema: any): ((val: any) => { ok: boolean; data?: any; error?: any }) => {
171
+ if (schema && '_def' in schema) {
172
+ return (val: any) => {
173
+ const r = schema.safeParse(val);
174
+ return r.success ? { ok: true, data: r.data } : { ok: false, error: r.error.flatten() };
175
+ };
176
+ }
177
+ const check = Compiler.TypeCompiler.Compile(schema);
178
+ return (val: any) => {
179
+ if (check.Check(val)) return { ok: true, data: val };
180
+ const first = check.Errors(val).First();
181
+ return { ok: false, error: { message: first?.message || 'Invalid input', path: first?.path } };
182
+ };
183
+ };
184
+
185
+ const buildProjectorExpr = (schema: any, accessor: string): string | null => {
186
+ const props = schema?.properties;
187
+ if (!props || typeof props !== 'object') return null;
188
+ const entries: string[] = [];
189
+ for (const [k, subSchema] of Object.entries<any>(props)) {
190
+ const keyLit = JSON.stringify(k);
191
+ const propAccess = `${accessor}[${keyLit}]`;
192
+ const nestedExpr = buildProjectorExpr(subSchema, propAccess);
193
+ if (nestedExpr) {
194
+ entries.push(`${keyLit}: (${propAccess} && typeof ${propAccess} === 'object' && !Array.isArray(${propAccess})) ? ${nestedExpr} : ${propAccess}`);
195
+ } else {
196
+ entries.push(`${keyLit}: ${propAccess}`);
197
+ }
198
+ }
199
+ return `{ ${entries.join(', ')} }`;
200
+ };
201
+
202
+ const compileProjector = (schema: any): ((val: any) => any) | null => {
203
+ if (!schema || '_def' in schema) return null; // Zod safeParse strips unknown keys natively
204
+ if (schema.type === 'array' && schema.items) {
205
+ const itemExpr = buildProjectorExpr(schema.items, 'item');
206
+ if (!itemExpr) return null;
207
+ return new Function(
208
+ `return function(arr) {
209
+ if (!Array.isArray(arr)) return arr;
210
+ const len = arr.length;
211
+ const out = new Array(len);
212
+ for (let i = 0; i < len; i++) {
213
+ const item = arr[i];
214
+ out[i] = (item && typeof item === 'object' && !Array.isArray(item)) ? ${itemExpr} : item;
215
+ }
216
+ return out;
217
+ }`
218
+ )();
219
+ }
220
+ const objExpr = buildProjectorExpr(schema, 'o');
221
+ if (!objExpr) return null;
222
+ return new Function(
223
+ `return function(o) {
224
+ if (!o || typeof o !== 'object' || Array.isArray(o)) return o;
225
+ return ${objExpr};
226
+ }`
227
+ )();
228
+ };
229
+
230
+ export const createResponseFilter = (schema: any): ((val: any) => any) => {
231
+ const check = compileSingleSchema(schema);
232
+ const project = compileProjector(schema);
233
+
234
+ return (val: any) => {
235
+ if (val instanceof Response) return val;
236
+ const filtered = project ? project(val) : val;
237
+ const r = check(filtered);
238
+ if (!r.ok) {
239
+ return errorJSON({ status: 'error', code: 'RESPONSE_VALIDATION_FAILED', error: r.error }, 500);
240
+ }
241
+ return r.data;
242
+ };
243
+ };
244
+
245
+ const coerceFields = (obj: Record<string, any>, schema: any): Record<string, any> => {
246
+ const props = schema?.properties || (schema?._def?.shape ? (typeof schema._def.shape === 'function' ? schema._def.shape() : schema._def.shape) : null);
247
+ if (!props) return obj;
248
+ const out: Record<string, any> = { ...obj };
249
+ for (const [k, propSchema] of Object.entries<any>(props)) {
250
+ if (!Object.hasOwn(out, k)) continue;
251
+ const val = out[k];
252
+ if (typeof val !== 'string') continue;
253
+ const tType = propSchema?.type || propSchema?._def?.typeName;
254
+ if (tType === 'number' || tType === 'integer' || tType === 'ZodNumber') {
255
+ if (val.trim() !== '') {
256
+ const n = Number(val);
257
+ if (!Number.isNaN(n)) out[k] = n;
258
+ }
259
+ } else if (tType === 'boolean' || tType === 'ZodBoolean') {
260
+ if (val === 'true') out[k] = true;
261
+ else if (val === 'false') out[k] = false;
262
+ }
263
+ }
264
+ return out;
265
+ };
266
+
267
+ export const schemaValidator = (schemas: RouteSchemas): Middleware => {
268
+ const bodyCheck = schemas.body ? compileSingleSchema(schemas.body) : null;
269
+ const queryCheck = schemas.query ? compileSingleSchema(schemas.query) : null;
270
+ const paramsCheck = schemas.params ? compileSingleSchema(schemas.params) : null;
271
+ const headersCheck = schemas.headers ? compileSingleSchema(schemas.headers) : null;
272
+ const responseFilter = schemas.response ? createResponseFilter(schemas.response) : null;
273
+ const maxBodySize = schemas.maxBodySize ?? 1048576;
274
+
275
+ const validateSyncParts = (ctx: Context): Response | undefined => {
276
+ if (paramsCheck) {
277
+ const coerced = coerceFields(ctx.params, schemas.params);
278
+ const r = paramsCheck(coerced);
279
+ if (!r.ok) return errorJSON({ status: 'error', code: 'PARAMS_INVALID', error: r.error });
280
+ ctx.params = r.data;
281
+ }
282
+ if (queryCheck) {
283
+ const coerced = coerceFields(ctx.query, schemas.query);
284
+ const r = queryCheck(coerced);
285
+ if (!r.ok) return errorJSON({ status: 'error', code: 'QUERY_INVALID', error: r.error });
286
+ ctx._query = r.data;
287
+ }
288
+ if (headersCheck) {
289
+ const hdrObj: Record<string, string> = {};
290
+ ctx.req.headers.forEach((v, k) => { hdrObj[k.toLowerCase()] = v; });
291
+ const r = headersCheck(hdrObj);
292
+ if (!r.ok) return errorJSON({ status: 'error', code: 'HEADERS_INVALID', error: r.error });
293
+ }
294
+ return undefined;
295
+ };
296
+
297
+ if (!bodyCheck) {
298
+ const syncMw: Middleware = (ctx: Context, next?: Next) => {
299
+ const errRes = validateSyncParts(ctx);
300
+ if (errRes) return errRes;
301
+ return next ? next() : undefined;
302
+ };
303
+ (syncMw as any).__routeSchemas = schemas;
304
+ if (responseFilter) (syncMw as any).__responseFilter = responseFilter;
305
+ return syncMw;
306
+ }
307
+
308
+ const mw: Middleware = async (ctx: Context, next?: Next) => {
309
+ const errRes = validateSyncParts(ctx);
310
+ if (errRes) return errRes;
311
+
312
+ let body: any;
313
+ try {
314
+ body = await ctx.jsonBody(maxBodySize);
315
+ } catch (e: any) {
316
+ if (e?.status === 413) {
317
+ return errorJSON({ status: 'error', code: 'PAYLOAD_TOO_LARGE', message: 'Payload Too Large' }, 413);
318
+ }
319
+ return errorJSON({ status: 'error', message: 'Malformed JSON payload' });
320
+ }
321
+ const r = bodyCheck(body);
322
+ if (!r.ok) return errorJSON({ status: 'error', code: 'VALIDATION_FAILED', error: r.error });
323
+ ctx.body = r.data;
324
+
325
+ return next ? next() : undefined;
326
+ };
327
+ (mw as any).__schema = schemas.body;
328
+ (mw as any).__routeSchemas = schemas;
329
+ if (responseFilter) (mw as any).__responseFilter = responseFilter;
330
+ return mw;
331
+ };
@@ -0,0 +1,151 @@
1
+ export interface OpenAPIOptions {
2
+ title?: string;
3
+ version?: string;
4
+ description?: string;
5
+ }
6
+
7
+ const zodToJsonSchema = (schema: any): Record<string, any> => {
8
+ if (!schema || !schema._def) return { type: 'object' };
9
+ const def = schema._def;
10
+ const typeName = def.typeName;
11
+
12
+ if (typeName === 'ZodObject') {
13
+ const shape = typeof def.shape === 'function' ? def.shape() : def.shape;
14
+ const properties: Record<string, any> = {};
15
+ const required: string[] = [];
16
+ for (const [k, v] of Object.entries(shape || {})) {
17
+ const child = v as any;
18
+ properties[k] = zodToJsonSchema(child);
19
+ if (child?._def?.typeName !== 'ZodOptional' && child?._def?.typeName !== 'ZodDefault') {
20
+ required.push(k);
21
+ }
22
+ }
23
+ return { type: 'object', properties, ...(required.length ? { required } : {}) };
24
+ }
25
+ if (typeName === 'ZodString') return { type: 'string' };
26
+ if (typeName === 'ZodNumber') return { type: 'number' };
27
+ if (typeName === 'ZodBoolean') return { type: 'boolean' };
28
+ if (typeName === 'ZodArray') return { type: 'array', items: zodToJsonSchema(def.type) };
29
+ if (typeName === 'ZodOptional' || typeName === 'ZodDefault') return zodToJsonSchema(def.innerType);
30
+ if (typeName === 'ZodEnum') return { type: 'string', enum: def.values };
31
+ return { type: 'object' };
32
+ };
33
+
34
+ const extractSchema = (schema: any): Record<string, any> => {
35
+ if (!schema) return { type: 'object' };
36
+ if ('_def' in schema) return zodToJsonSchema(schema);
37
+ // TypeBox or plain JSON Schema
38
+ return JSON.parse(JSON.stringify(schema));
39
+ };
40
+
41
+ export const generateOpenAPISpec = (routes: any[], options: OpenAPIOptions = {}) => {
42
+ const paths: Record<string, Record<string, any>> = {};
43
+
44
+ for (const route of routes) {
45
+ if (route.path === '/docs' || route.path === '/docs/json') continue;
46
+
47
+ const openApiPath = ('/' + route.path)
48
+ .replace(/\/+/g, '/')
49
+ .replace(/:([a-zA-Z0-9_]+)/g, '{$1}');
50
+
51
+ if (!paths[openApiPath]) paths[openApiPath] = {};
52
+
53
+ const method = route.method.toLowerCase();
54
+ const params: any[] = [];
55
+ let requestBody: any = undefined;
56
+ let responseSchema: any = undefined;
57
+ let detail: any = undefined;
58
+ let paramSchemaObj: Record<string, any> | null = null;
59
+
60
+ for (const h of route.handlers) {
61
+ if (!h) continue;
62
+ const rs = (h as any).__routeSchemas;
63
+ if (rs) {
64
+ if (rs.detail) detail = rs.detail;
65
+ if (rs.params) paramSchemaObj = extractSchema(rs.params);
66
+ if (rs.query) {
67
+ const qSchema = extractSchema(rs.query);
68
+ const qReq = new Set<string>(qSchema.required || []);
69
+ for (const [k, prop] of Object.entries(qSchema.properties || {})) {
70
+ params.push({ name: k, in: 'query', required: qReq.has(k), schema: prop });
71
+ }
72
+ }
73
+ if (rs.headers) {
74
+ const hSchema = extractSchema(rs.headers);
75
+ const hReq = new Set<string>(hSchema.required || []);
76
+ for (const [k, prop] of Object.entries(hSchema.properties || {})) {
77
+ params.push({ name: k, in: 'header', required: hReq.has(k), schema: prop });
78
+ }
79
+ }
80
+ if (rs.response) {
81
+ responseSchema = extractSchema(rs.response);
82
+ }
83
+ }
84
+ if ((h as any).__schema && !requestBody) {
85
+ requestBody = {
86
+ required: true,
87
+ content: {
88
+ 'application/json': {
89
+ schema: extractSchema((h as any).__schema)
90
+ }
91
+ }
92
+ };
93
+ }
94
+ }
95
+
96
+ const paramMatches = route.path.matchAll(/:([a-zA-Z0-9_]+)/g);
97
+ for (const m of paramMatches) {
98
+ const pName = m[1]!;
99
+ const pProp = paramSchemaObj?.properties?.[pName] || { type: 'string' };
100
+ params.unshift({
101
+ name: pName,
102
+ in: 'path',
103
+ required: true,
104
+ schema: pProp
105
+ });
106
+ }
107
+
108
+ paths[openApiPath][method] = {
109
+ summary: detail?.summary || `${route.method} ${openApiPath}`,
110
+ ...(detail?.description ? { description: detail.description } : {}),
111
+ ...(detail?.tags ? { tags: detail.tags } : {}),
112
+ ...(params.length ? { parameters: params } : {}),
113
+ ...(requestBody ? { requestBody } : {}),
114
+ responses: {
115
+ '200': {
116
+ description: 'Success',
117
+ ...(responseSchema
118
+ ? { content: { 'application/json': { schema: responseSchema } } }
119
+ : {})
120
+ }
121
+ }
122
+ };
123
+ }
124
+
125
+ return {
126
+ openapi: '3.1.0',
127
+ info: {
128
+ title: options.title || 'BareJS API',
129
+ version: options.version || '1.0.0',
130
+ ...(options.description ? { description: options.description } : {})
131
+ },
132
+ paths
133
+ };
134
+ };
135
+
136
+ export const renderDocsHTML = (specUrl: string, title: string = 'BareJS API Docs'): string => {
137
+ const safeTitle = title.replace(/[<>&"]/g, '');
138
+ const safeSpecUrl = JSON.stringify(specUrl);
139
+ return `<!doctype html>
140
+ <html>
141
+ <head>
142
+ <title>${safeTitle}</title>
143
+ <meta charset="utf-8" />
144
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
145
+ </head>
146
+ <body>
147
+ <script id="api-reference" data-url=${safeSpecUrl}></script>
148
+ <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
149
+ </body>
150
+ </html>`;
151
+ };
@@ -1,10 +1,18 @@
1
1
  import { resolve, sep } from 'node:path';
2
+ import { stat } from 'node:fs/promises';
2
3
 
3
- export const staticFile = (root: string = 'public') => {
4
+ export interface StaticOptions {
5
+ maxAge?: number;
6
+ etag?: boolean;
7
+ }
8
+
9
+ export const staticFile = (root: string = 'public', options: StaticOptions = {}) => {
4
10
  const rootDir = resolve(process.cwd(), root);
5
11
  const rootPrefix = rootDir.endsWith(sep) ? rootDir : rootDir + sep;
12
+ const maxAge = options.maxAge ?? 3600;
13
+ const enableEtag = options.etag !== false;
6
14
 
7
- return async (ctx: any, next: any) => {
15
+ const mw = async (ctx: any, next: any) => {
8
16
  const method = ctx.req.method;
9
17
  if (method !== 'GET' && method !== 'HEAD') return next();
10
18
 
@@ -33,11 +41,60 @@ export const staticFile = (root: string = 'public') => {
33
41
  return ctx.status(403).send('Forbidden');
34
42
  }
35
43
 
44
+ let fileSize = 0;
45
+ let mtimeMs = 0;
46
+ try {
47
+ const st = await stat(filePath);
48
+ if (st.isDirectory()) return next();
49
+ fileSize = st.size;
50
+ mtimeMs = Math.floor(st.mtimeMs);
51
+ } catch {
52
+ return next();
53
+ }
36
54
  const file = Bun.file(filePath);
37
- if (await file.exists()) {
38
- return new Response(file);
55
+
56
+ const headers: Record<string, string> = {
57
+ 'Cache-Control': `public, max-age=${maxAge}`,
58
+ 'Accept-Ranges': 'bytes'
59
+ };
60
+
61
+ if (enableEtag) {
62
+ const etag = `W/"${fileSize.toString(16)}-${mtimeMs.toString(16)}"`;
63
+ headers['ETag'] = etag;
64
+ const ifNoneMatch = ctx.req.headers?.get?.('if-none-match');
65
+ if (ifNoneMatch && ifNoneMatch === etag) {
66
+ return new Response(null, { status: 304, headers });
67
+ }
68
+ }
69
+
70
+ const rangeHeader = ctx.req.headers?.get?.('range');
71
+ if (rangeHeader && rangeHeader.startsWith('bytes=') && fileSize > 0) {
72
+ const [startStr, endStr] = rangeHeader.slice(6).split('-');
73
+ let start = startStr ? Number(startStr) : 0;
74
+ let end = endStr ? Number(endStr) : fileSize - 1;
75
+ if (!startStr && endStr) {
76
+ start = Math.max(0, fileSize - Number(endStr));
77
+ end = fileSize - 1;
78
+ }
79
+ if (!Number.isInteger(start) || !Number.isInteger(end) || start < 0 || end >= fileSize || start > end) {
80
+ return new Response(null, {
81
+ status: 416,
82
+ headers: { ...headers, 'Content-Range': `bytes */${fileSize}` }
83
+ });
84
+ }
85
+ headers['Content-Range'] = `bytes ${start}-${end}/${fileSize}`;
86
+ headers['Content-Length'] = String(end - start + 1);
87
+ if (file.type) headers['Content-Type'] = file.type;
88
+ return new Response(method === 'HEAD' ? null : file.slice(start, end + 1), {
89
+ status: 206,
90
+ headers
91
+ });
39
92
  }
40
93
 
41
- return next();
94
+ if (file.type) headers['Content-Type'] = file.type;
95
+ headers['Content-Length'] = String(fileSize);
96
+ return new Response(method === 'HEAD' ? null : file, { status: 200, headers });
42
97
  };
98
+ (mw as any).__isStatic = true;
99
+ return mw;
43
100
  };