barejs 0.1.47 → 0.1.49

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,134 +1,138 @@
1
- /**
2
- * BareJS Ultimate Validation Engines
3
- * All comments must be in English [2026-01-06]
4
- * Optimized for Bun Runtime & Mechanical Sympathy [2026-01-05]
5
- */
6
-
7
- import * as Compiler from '@sinclair/typebox/compiler';
8
- import { z } from 'zod';
9
- import type { Context, Middleware, Next } from '../core/context';
10
-
11
- // --- Types & Constants ---
12
- export const Z = z;
13
-
14
- /**
15
- * Standardized High-Performance Error Response
16
- * Uses Bun's native Response.json for speed.
17
- */
18
- const errorJSON = (data: any, status = 400) =>
19
- Response.json(data, {
20
- status,
21
- headers: { 'Content-Type': 'application/json' }
22
- });
23
-
24
- // --- Engines ---
25
-
26
- /**
27
- * TypeBox JIT Engine (t)
28
- * Pre-compiled JIT validation to outperform competitors by 55% [2026-01-05].
29
- */
30
- export const typebox = (schema: any): Middleware => {
31
- const check = Compiler.TypeCompiler.Compile(schema);
32
-
33
- return async (ctx: Context, next?: Next) => {
34
- try {
35
- // const body = await ctx.req.json();
36
- const body = await ctx.jsonBody();
37
-
38
- if (!check.Check(body)) {
39
- const error = check.Errors(body).First();
40
- return errorJSON({
41
- status: 'error',
42
- code: 'VALIDATION_FAILED',
43
- message: error?.message || 'Invalid input',
44
- path: error?.path || 'body'
45
- });
46
- }
47
-
48
- // ✅ FIX TS18046: Cast to 'any' to allow assignment to 'unknown' body
49
- (ctx as any).body = body;
50
- return next ? next() : undefined;
51
- } catch {
52
- return errorJSON({ status: 'error', message: 'Malformed JSON payload' });
53
- }
54
- };
55
- };
56
-
57
- /**
58
- * Native Engine (n)
59
- */
60
- export const native = (schema: any): Middleware => {
61
- const props = schema.properties || {};
62
- const keys = Object.keys(props);
63
- const kLen = keys.length;
64
-
65
- return async (ctx: any, next?: any) => {
66
- try {
67
- const isCtx = ctx instanceof Object && 'req' in ctx;
68
- const req = isCtx ? ctx.req : ctx;
69
-
70
- const body = await req.json() as any;
71
- for (let i = 0; i < kLen; i++) {
72
- const k = keys[i]!;
73
- if (typeof body[k] !== props[k]?.type) {
74
- return errorJSON({
75
- status: 'error',
76
- code: 'TYPE_MISMATCH',
77
- message: `Field '${k}' must be of type ${props[k]?.type}`,
78
- field: k
79
- });
80
- }
81
- }
82
-
83
- // ✅ FIX TS18046: Ensure body assignment is allowed
84
- if (isCtx) (ctx as any).body = body;
85
-
86
- return next ? next() : undefined;
87
- } catch {
88
- return errorJSON({ status: 'error', message: 'Invalid JSON payload' });
89
- }
90
- };
91
- };
92
-
93
- /**
94
- * Zod Engine (z)
95
- */
96
- export const zod = (schema: z.ZodSchema): Middleware => {
97
- return async (ctx: any, next?: any) => {
98
- try {
99
- const isCtx = ctx instanceof Object && 'req' in ctx;
100
- const req = isCtx ? ctx.req : ctx;
101
-
102
- const body = await req.json();
103
- const result = await schema.safeParseAsync(body);
104
-
105
- if (!result.success) {
106
- return errorJSON({
107
- status: 'error',
108
- code: 'ZOD_ERROR',
109
- errors: result.error.flatten()
110
- });
111
- }
112
-
113
- // ✅ FIX TS18046: Line 68/74 area fix
114
- if (isCtx) (ctx as any).body = result.data;
115
-
116
- return next ? next() : undefined;
117
- } catch {
118
- return errorJSON({ status: 'error', message: 'Invalid JSON payload' });
119
- }
120
- };
121
- };
122
-
123
- /**
124
- * Smart Dispatcher (v)
125
- */
126
- export const validate = (schema: any): Middleware => {
127
- if (schema && '_def' in schema) return zod(schema);
128
- if (schema && (schema.kind || schema.type || schema[Symbol.for('TypeBox.Kind')])) {
129
- return typebox(schema);
130
- }
131
- return native(schema);
132
- };
133
-
1
+ /**
2
+ * BareJS Ultimate Validation Engines
3
+ * All comments must be in English [2026-01-06]
4
+ * Optimized for Bun Runtime & Mechanical Sympathy [2026-01-05]
5
+ */
6
+
7
+ import * as Compiler from '@sinclair/typebox/compiler';
8
+ import { z } from 'zod';
9
+ import type { Context, Middleware, Next } from '../core/context';
10
+
11
+ // --- Types & Constants ---
12
+ export const Z = z;
13
+
14
+ /**
15
+ * Standardized High-Performance Error Response
16
+ * Uses Bun's native Response.json for speed.
17
+ */
18
+ const errorJSON = (data: any, status = 400) =>
19
+ Response.json(data, {
20
+ status,
21
+ headers: { 'Content-Type': 'application/json' }
22
+ });
23
+
24
+ // --- Engines ---
25
+
26
+ /**
27
+ * TypeBox JIT Engine (t)
28
+ * Pre-compiled JIT validation to outperform competitors by 55% [2026-01-05].
29
+ */
30
+ export const typebox = (schema: any): Middleware => {
31
+ const check = Compiler.TypeCompiler.Compile(schema);
32
+
33
+ const mw: Middleware = async (ctx: Context, next?: Next) => {
34
+ try {
35
+ const body = await ctx.jsonBody();
36
+
37
+ if (!check.Check(body)) {
38
+ const error = check.Errors(body).First();
39
+ return errorJSON({
40
+ status: 'error',
41
+ code: 'VALIDATION_FAILED',
42
+ message: error?.message || 'Invalid input',
43
+ path: error?.path || 'body'
44
+ });
45
+ }
46
+
47
+ (ctx as any).body = body;
48
+ return next ? next() : undefined;
49
+ } catch {
50
+ return errorJSON({ status: 'error', message: 'Malformed JSON payload' });
51
+ }
52
+ };
53
+ (mw as any).__schema = schema;
54
+ return mw;
55
+ };
56
+
57
+ /**
58
+ * Native Engine (n)
59
+ */
60
+ export const native = (schema: any): Middleware => {
61
+ const props = schema.properties || {};
62
+ const keys = Object.keys(props);
63
+ const kLen = keys.length;
64
+
65
+ const mw: Middleware = async (ctx: any, next?: any) => {
66
+ try {
67
+ const isCtx = ctx instanceof Object && 'req' in ctx;
68
+ const body = isCtx ? await ctx.jsonBody() : await ctx.json();
69
+
70
+ if (!body || typeof body !== 'object' || Array.isArray(body)) {
71
+ return errorJSON({ status: 'error', message: 'Invalid JSON object payload' });
72
+ }
73
+
74
+ for (let i = 0; i < kLen; i++) {
75
+ const k = keys[i]!;
76
+ if (!Object.hasOwn(body, k) || typeof body[k] !== props[k]?.type) {
77
+ return errorJSON({
78
+ status: 'error',
79
+ code: 'TYPE_MISMATCH',
80
+ message: `Field '${k}' must be of type ${props[k]?.type}`,
81
+ field: k
82
+ });
83
+ }
84
+ }
85
+
86
+ if (isCtx) (ctx as any).body = body;
87
+
88
+ return next ? next() : undefined;
89
+ } catch {
90
+ return errorJSON({ status: 'error', message: 'Invalid JSON payload' });
91
+ }
92
+ };
93
+ (mw as any).__schema = schema;
94
+ return mw;
95
+ };
96
+
97
+ /**
98
+ * Zod Engine (z)
99
+ */
100
+ export const zod = (schema: z.ZodSchema): Middleware => {
101
+ const mw: Middleware = async (ctx: any, next?: any) => {
102
+ try {
103
+ const isCtx = ctx instanceof Object && 'req' in ctx;
104
+ const body = isCtx ? await ctx.jsonBody() : await ctx.json();
105
+
106
+ const result = await schema.safeParseAsync(body);
107
+
108
+ if (!result.success) {
109
+ return errorJSON({
110
+ status: 'error',
111
+ code: 'ZOD_ERROR',
112
+ errors: result.error.flatten()
113
+ });
114
+ }
115
+
116
+ if (isCtx) (ctx as any).body = result.data;
117
+
118
+ return next ? next() : undefined;
119
+ } catch {
120
+ return errorJSON({ status: 'error', message: 'Invalid JSON payload' });
121
+ }
122
+ };
123
+ (mw as any).__schema = schema;
124
+ return mw;
125
+ };
126
+
127
+ /**
128
+ * Smart Dispatcher (v)
129
+ */
130
+ export const validate = (schema: any): Middleware => {
131
+ if (schema && '_def' in schema) return zod(schema);
132
+ if (schema && (schema.kind || schema.type || schema[Symbol.for('TypeBox.Kind')])) {
133
+ return typebox(schema);
134
+ }
135
+ return native(schema);
136
+ };
137
+
134
138
  export { typebox as t, zod as z, native as n, validate as v };
@@ -0,0 +1,116 @@
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
+ const paramMatches = route.path.matchAll(/:([a-zA-Z0-9_]+)/g);
56
+ for (const m of paramMatches) {
57
+ params.push({
58
+ name: m[1],
59
+ in: 'path',
60
+ required: true,
61
+ schema: { type: 'string' }
62
+ });
63
+ }
64
+
65
+ let requestBody: any = undefined;
66
+ for (const h of route.handlers) {
67
+ if (h && (h as any).__schema) {
68
+ requestBody = {
69
+ required: true,
70
+ content: {
71
+ 'application/json': {
72
+ schema: extractSchema((h as any).__schema)
73
+ }
74
+ }
75
+ };
76
+ break;
77
+ }
78
+ }
79
+
80
+ paths[openApiPath][method] = {
81
+ summary: `${route.method} ${openApiPath}`,
82
+ ...(params.length ? { parameters: params } : {}),
83
+ ...(requestBody ? { requestBody } : {}),
84
+ responses: {
85
+ '200': { description: 'Success' }
86
+ }
87
+ };
88
+ }
89
+
90
+ return {
91
+ openapi: '3.1.0',
92
+ info: {
93
+ title: options.title || 'BareJS API',
94
+ version: options.version || '1.0.0',
95
+ ...(options.description ? { description: options.description } : {})
96
+ },
97
+ paths
98
+ };
99
+ };
100
+
101
+ export const renderDocsHTML = (specUrl: string, title: string = 'BareJS API Docs'): string => {
102
+ const safeTitle = title.replace(/[<>&"]/g, '');
103
+ const safeSpecUrl = JSON.stringify(specUrl);
104
+ return `<!doctype html>
105
+ <html>
106
+ <head>
107
+ <title>${safeTitle}</title>
108
+ <meta charset="utf-8" />
109
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
110
+ </head>
111
+ <body>
112
+ <script id="api-reference" data-url=${safeSpecUrl}></script>
113
+ <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
114
+ </body>
115
+ </html>`;
116
+ };
@@ -1,26 +1,43 @@
1
- import { join, normalize } from 'node:path';
2
-
3
- export const staticFile = (root: string = 'public') => {
4
- return async (ctx: any, next: any) => {
5
- // 1. Log that the middleware actually started
6
- // console.log(`📡 [Static] Checking disk for: ${ctx.req.url}`);
7
-
8
- if (ctx.req.method !== 'GET' && ctx.req.method !== 'HEAD') return next();
9
-
10
- const url = new URL(ctx.req.url);
11
- const pathName = decodeURIComponent(url.pathname).replace(/^\//, '');
12
-
13
- // Resolve path (Windows compatible)
14
- const filePath = join(process.cwd(), root, pathName);
15
- const file = Bun.file(filePath);
16
-
17
- if (await file.exists()) {
18
- // console.log(`✅ [Static] Found file: ${filePath}`);
19
- return new Response(file);
20
- }
21
-
22
- // 2. Log if the file was NOT found before moving to 404
23
- // console.log(`❌ [Static] Not found on disk: ${filePath}`);
24
- return next();
25
- };
1
+ import { resolve, sep } from 'node:path';
2
+
3
+ export const staticFile = (root: string = 'public') => {
4
+ const rootDir = resolve(process.cwd(), root);
5
+ const rootPrefix = rootDir.endsWith(sep) ? rootDir : rootDir + sep;
6
+
7
+ return async (ctx: any, next: any) => {
8
+ const method = ctx.req.method;
9
+ if (method !== 'GET' && method !== 'HEAD') return next();
10
+
11
+ const rawUrl: string = ctx.req.url;
12
+ const pathStart = rawUrl.indexOf('/', 8);
13
+ const queryStart = pathStart === -1 ? -1 : rawUrl.indexOf('?', pathStart);
14
+ const rawPath = pathStart === -1
15
+ ? ''
16
+ : (queryStart === -1 ? rawUrl.slice(pathStart) : rawUrl.slice(pathStart, queryStart));
17
+
18
+ let decodedPath: string;
19
+ try {
20
+ decodedPath = decodeURIComponent(rawPath);
21
+ } catch {
22
+ return ctx.status(400).send('Bad Request');
23
+ }
24
+
25
+ if (decodedPath.includes('\0')) {
26
+ return ctx.status(400).send('Bad Request');
27
+ }
28
+
29
+ const relativePath = decodedPath.replace(/^\/+/, '');
30
+ const filePath = resolve(rootDir, relativePath);
31
+
32
+ if (filePath !== rootDir && !filePath.startsWith(rootPrefix)) {
33
+ return ctx.status(403).send('Forbidden');
34
+ }
35
+
36
+ const file = Bun.file(filePath);
37
+ if (await file.exists()) {
38
+ return new Response(file);
39
+ }
40
+
41
+ return next();
42
+ };
26
43
  };