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.
package/src/core/radix.ts CHANGED
@@ -1,171 +1,184 @@
1
- import { Context } from "./context";
2
-
3
- export class RadixNode {
4
- public children: Record<string, RadixNode> = {};
5
- public staticKeys: string[] = [];
6
- public paramNode: RadixNode | null = null;
7
- public paramName: string | null = null;
8
- public handlers: Record<string, Function> = {};
9
-
10
- public insert(path: string, method: string, handler: Function) {
11
- let node: RadixNode = this;
12
- const parts = path.split('/').filter(Boolean);
13
- for (const part of parts) {
14
- if (part.startsWith(':')) {
15
- if (!node.paramNode) node.paramNode = new RadixNode();
16
- node.paramName = part.slice(1);
17
- node = node.paramNode;
18
- } else {
19
- if (!node.children[part]) {
20
- node.children[part] = new RadixNode();
21
- node.staticKeys.push(part);
22
- }
23
- node = node.children[part]!;
24
- }
25
- }
26
- node.handlers[method] = handler;
27
- }
28
-
29
- public lookup(method: string, url: string, start: number, ctx: Context) {
30
- let node: RadixNode = this;
31
- let i = start === -1 ? 0 : start;
32
- const len = url.length;
33
- if (url[i] === '/') i++;
34
-
35
- for (const k in ctx.params) delete ctx.params[k];
36
-
37
- while (i < len) {
38
- let j = url.indexOf('/', i);
39
- if (j === -1) j = len;
40
- const segmentLen = j - i;
41
- let found = false;
42
-
43
- const keys = node.staticKeys;
44
- const kLen = keys.length;
45
-
46
- if (kLen === 1) {
47
- const key = keys[0]!;
48
- if (key.length === segmentLen) {
49
- let match = true;
50
- for (let m = 0; m < segmentLen; m++) {
51
- if (key[m] !== url[i + m]) { match = false; break; }
52
- }
53
- if (match) { node = node.children[key]!; found = true; }
54
- }
55
- } else {
56
- for (let k = 0; k < kLen; k++) {
57
- const key = keys[k]!;
58
- if (key.length === segmentLen) {
59
- let match = true;
60
- for (let m = 0; m < segmentLen; m++) {
61
- if (key[m] !== url[i + m]) { match = false; break; }
62
- }
63
- if (match) { node = node.children[key]!; found = true; break; }
64
- }
65
- }
66
- }
67
-
68
- if (!found) {
69
- if (node.paramNode) {
70
- ctx.params[node.paramName!] = url.slice(i, j);
71
- node = node.paramNode;
72
- } else return null;
73
- }
74
- i = j + 1;
75
- }
76
- return node.handlers[method] || null;
77
- }
78
-
79
- public jitCompile(
80
- register: (h: Function) => string,
81
- level = 0,
82
- pathPrefix = 'url',
83
- idxPrefix = 's',
84
- paramAccumulator: { name: string, varName: string }[] = []
85
- ): string {
86
- let code = '';
87
- const indent = ' '.repeat(level);
88
-
89
- // ⚡ [CORE] Handler Matcher: ส่วนนี้จะเช็คว่า path สิ้นสุดที่ Node นี้หรือไม่
90
- if (Object.keys(this.handlers).length > 0) {
91
- code += `${indent}if (${idxPrefix} >= urlLen) {\n`;
92
-
93
- // ฉีด Params เข้า Context เมื่อยืนยันว่า Match แล้ว
94
- if (paramAccumulator.length > 0) {
95
- const props = paramAccumulator.map((p: any) => `"${p.name}": ${p.varName}`).join(', ');
96
- code += `${indent} ctx.params = { ${props} };\n`;
97
- }
98
-
99
- code += `${indent} switch(method) {\n`;
100
- for (const [m, h] of Object.entries(this.handlers)) {
101
- const hName = register(h as Function);
102
- code += `${indent} case "${m}": return ${hName}(ctx);\n`;
103
- }
104
- code += `${indent} }\n`;
105
- code += `${indent}}\n`;
106
- }
107
-
108
- // 1. Static Keys Logic
109
- if (this.staticKeys.length > 0) {
110
- if (this.staticKeys.length === 1) {
111
- const key = this.staticKeys[0]!;
112
- const kLen = key.length;
113
-
114
- code += `${indent}if (${pathPrefix}.startsWith("${key}", ${idxPrefix})) {\n`;
115
- code += `${indent} const nextChar = ${pathPrefix}.charCodeAt(${idxPrefix} + ${kLen});\n`;
116
- code += `${indent} if (isNaN(nextChar) || nextChar === 47) {\n`;
117
-
118
- const child = this.children[key]!;
119
- const newIdxVar = `newIdxL${level}`;
120
- code += `${indent} const ${newIdxVar} = isNaN(nextChar) ? ${pathPrefix}.length : (${idxPrefix} + ${kLen} + 1);\n`;
121
-
122
- code += child.jitCompile(register, level + 1, pathPrefix, newIdxVar, paramAccumulator);
123
-
124
- code += `${indent} }\n`;
125
- code += `${indent}}\n`;
126
-
127
- } else {
128
- // 🔥 แก้ไขตรงนี้: ใส่วงเล็บครอบ idxPrefix เพื่อให้คำนวณถูกต้อง
129
- code += `${indent}let slash${level} = ${pathPrefix}.indexOf('/', ${idxPrefix});\n`;
130
- code += `${indent}if (slash${level} === -1) slash${level} = ${pathPrefix}.length;\n`;
131
- code += `${indent}const len${level} = slash${level} - (${idxPrefix});\n\n`; // ✅ ใส่วงเล็บ
132
-
133
- code += `${indent}switch(len${level}) {\n`;
134
- for (const key of this.staticKeys) {
135
- code += `${indent} case ${key.length}: // "${key}"\n`;
136
- if (key.length === 1) {
137
- code += `${indent} if (${pathPrefix}.charCodeAt(${idxPrefix}) === ${key.charCodeAt(0)}) {\n`;
138
- } else {
139
- code += `${indent} if (${pathPrefix}.startsWith("${key}", ${idxPrefix})) {\n`;
140
- }
141
-
142
- const child = this.children[key]!;
143
- code += child.jitCompile(register, level + 1, pathPrefix, `slash${level} + 1`, paramAccumulator);
144
-
145
- code += `${indent} }\n`;
146
- code += `${indent} break;\n`;
147
- }
148
- code += `${indent}}\n`;
149
- }
150
- }
151
-
152
- // 2. Param Node Logic (Fallback)
153
- if (this.paramNode) {
154
- const pNode = this.paramNode;
155
- if (this.staticKeys.length === 0) {
156
- code += `${indent}let slash${level} = ${pathPrefix}.indexOf('/', ${idxPrefix});\n`;
157
- code += `${indent}if (slash${level} === -1) slash${level} = ${pathPrefix}.length;\n`;
158
- }
159
-
160
- const pVar = `pL${level}`;
161
- code += `${indent}const ${pVar} = ${pathPrefix}.slice(${idxPrefix}, slash${level});\n`;
162
-
163
- const newAccumulator = [...paramAccumulator, { name: this.paramName!, varName: pVar }];
164
- code += pNode.jitCompile(register, level + 1, pathPrefix, `slash${level} + 1`, newAccumulator);
165
- }
166
-
167
- return code;
168
- }
169
-
170
- public id = Math.random().toString(36).slice(2);
171
- }
1
+ import { Context } from "./context";
2
+
3
+ export class RadixNode {
4
+ public children: Record<string, RadixNode> = {};
5
+ public staticKeys: string[] = [];
6
+ public paramNode: RadixNode | null = null;
7
+ public paramName: string | null = null;
8
+ public handlers: Record<string, Function> = {};
9
+
10
+ public insert(path: string, method: string, handler: Function) {
11
+ let node: RadixNode = this;
12
+ const parts = path.split('/').filter(Boolean);
13
+ for (const part of parts) {
14
+ if (part.startsWith(':')) {
15
+ if (!node.paramNode) node.paramNode = new RadixNode();
16
+ node.paramName = part.slice(1);
17
+ node = node.paramNode;
18
+ } else {
19
+ if (!node.children[part]) {
20
+ node.children[part] = new RadixNode();
21
+ node.staticKeys.push(part);
22
+ }
23
+ node = node.children[part]!;
24
+ }
25
+ }
26
+ node.handlers[method] = handler;
27
+ }
28
+
29
+ public lookup(method: string, url: string, start: number, ctx: Context) {
30
+ let node: RadixNode = this;
31
+ let i = start === -1 ? 0 : start;
32
+ const len = url.length;
33
+ if (url[i] === '/') i++;
34
+
35
+ for (const k in ctx.params) delete ctx.params[k];
36
+
37
+ while (i < len) {
38
+ let j = url.indexOf('/', i);
39
+ if (j === -1) j = len;
40
+ const segmentLen = j - i;
41
+ let found = false;
42
+
43
+ const keys = node.staticKeys;
44
+ const kLen = keys.length;
45
+
46
+ if (kLen === 1) {
47
+ const key = keys[0]!;
48
+ if (key.length === segmentLen) {
49
+ let match = true;
50
+ for (let m = 0; m < segmentLen; m++) {
51
+ if (key[m] !== url[i + m]) { match = false; break; }
52
+ }
53
+ if (match) { node = node.children[key]!; found = true; }
54
+ }
55
+ } else {
56
+ for (let k = 0; k < kLen; k++) {
57
+ const key = keys[k]!;
58
+ if (key.length === segmentLen) {
59
+ let match = true;
60
+ for (let m = 0; m < segmentLen; m++) {
61
+ if (key[m] !== url[i + m]) { match = false; break; }
62
+ }
63
+ if (match) { node = node.children[key]!; found = true; break; }
64
+ }
65
+ }
66
+ }
67
+
68
+ if (!found) {
69
+ if (node.paramNode) {
70
+ ctx.params[node.paramName!] = url.slice(i, j);
71
+ node = node.paramNode;
72
+ } else return null;
73
+ }
74
+ i = j + 1;
75
+ }
76
+ return node.handlers[method] || null;
77
+ }
78
+
79
+ public jitCompile(
80
+ register: (h: Function) => string,
81
+ level = 0,
82
+ pathPrefix = 'url',
83
+ idxPrefix = 's',
84
+ paramAccumulator: { name: string, varName: string }[] = []
85
+ ): string {
86
+ let code = '';
87
+ const indent = ' '.repeat(level);
88
+
89
+
90
+ if (Object.keys(this.handlers).length > 0) {
91
+ code += `${indent}if (${idxPrefix} >= urlLen) {\n`;
92
+
93
+
94
+ if (paramAccumulator.length > 0) {
95
+ const props = paramAccumulator.map((p: any) => `${JSON.stringify(p.name)}: ${p.varName}`).join(', ');
96
+ code += `${indent} ctx.params = { ${props} };\n`;
97
+ }
98
+
99
+ code += `${indent} switch(method) {\n`;
100
+ for (const [m, h] of Object.entries(this.handlers)) {
101
+ const hName = register(h as Function);
102
+ code += `${indent} case ${JSON.stringify(m)}: return ${hName}(ctx);\n`;
103
+ }
104
+ code += `${indent} }\n`;
105
+ code += `${indent}}\n`;
106
+ }
107
+
108
+ // 1. Static Keys Logic
109
+ if (this.staticKeys.length > 0) {
110
+ if (this.staticKeys.length === 1) {
111
+ const key = this.staticKeys[0]!;
112
+ const kLen = key.length;
113
+ const nextIdxVar = `nextIdxL${level}`;
114
+
115
+ code += `${indent}if (${pathPrefix}.startsWith(${JSON.stringify(key)}, ${idxPrefix})) {\n`;
116
+ code += `${indent} const ${nextIdxVar} = ${idxPrefix} + ${kLen};\n`;
117
+ code += `${indent} if (${nextIdxVar} === urlLen || ${pathPrefix}.charCodeAt(${nextIdxVar}) === 47) {\n`;
118
+
119
+ const child = this.children[key]!;
120
+ const newIdxVar = `newIdxL${level}`;
121
+ code += `${indent} const ${newIdxVar} = ${nextIdxVar} === urlLen ? urlLen : (${nextIdxVar} + 1);\n`;
122
+
123
+ code += child.jitCompile(register, level + 1, pathPrefix, newIdxVar, paramAccumulator);
124
+
125
+ code += `${indent} }\n`;
126
+ code += `${indent}}\n`;
127
+
128
+ } else {
129
+
130
+ code += `${indent}let slash${level} = ${pathPrefix}.indexOf('/', ${idxPrefix});\n`;
131
+ code += `${indent}if (slash${level} === -1 || slash${level} > urlLen) slash${level} = urlLen;\n`;
132
+ code += `${indent}const len${level} = slash${level} - (${idxPrefix});\n\n`;
133
+
134
+ const byLen = new Map<number, string[]>();
135
+ for (const key of this.staticKeys) {
136
+ let list = byLen.get(key.length);
137
+ if (!list) {
138
+ list = [];
139
+ byLen.set(key.length, list);
140
+ }
141
+ list.push(key);
142
+ }
143
+
144
+ code += `${indent}switch(len${level}) {\n`;
145
+ for (const [kLen, keysForLen] of byLen) {
146
+ code += `${indent} case ${kLen}:\n`;
147
+ for (const key of keysForLen) {
148
+ if (kLen === 1) {
149
+ code += `${indent} if (${pathPrefix}.charCodeAt(${idxPrefix}) === ${key.charCodeAt(0)}) {\n`;
150
+ } else {
151
+ code += `${indent} if (${pathPrefix}.startsWith(${JSON.stringify(key)}, ${idxPrefix})) {\n`;
152
+ }
153
+
154
+ const child = this.children[key]!;
155
+ code += child.jitCompile(register, level + 1, pathPrefix, `slash${level} + 1`, paramAccumulator);
156
+
157
+ code += `${indent} }\n`;
158
+ }
159
+ code += `${indent} break;\n`;
160
+ }
161
+ code += `${indent}}\n`;
162
+ }
163
+ }
164
+
165
+ // 2. Param Node Logic (Fallback)
166
+ if (this.paramNode) {
167
+ const pNode = this.paramNode;
168
+ if (this.staticKeys.length === 0) {
169
+ code += `${indent}let slash${level} = ${pathPrefix}.indexOf('/', ${idxPrefix});\n`;
170
+ code += `${indent}if (slash${level} === -1 || slash${level} > urlLen) slash${level} = urlLen;\n`;
171
+ }
172
+
173
+ const pVar = `pL${level}`;
174
+ code += `${indent}const ${pVar} = ${pathPrefix}.slice(${idxPrefix}, slash${level});\n`;
175
+
176
+ const newAccumulator = [...paramAccumulator, { name: this.paramName!, varName: pVar }];
177
+ code += pNode.jitCompile(register, level + 1, pathPrefix, `slash${level} + 1`, newAccumulator);
178
+ }
179
+
180
+ return code;
181
+ }
182
+
183
+ public id = Math.random().toString(36).slice(2);
184
+ }
@@ -1,62 +1,61 @@
1
- import {
2
- type Middleware,
3
- type Handler,
4
- type GroupCallback
5
- } from '../core/context';
6
-
7
- type HandlersChain = (Middleware | Handler)[];
8
-
9
- export class BareRouter {
10
- public routes: any[] = [];
11
-
12
- constructor(
13
- public prefix: string = "",
14
- public groupMiddleware: any[] = []
15
- ) { }
16
-
17
- private _add(method: string, path: string, handlers: HandlersChain) {
18
- // ⚡️ แก้ไข: ไม่ต้องเติม / นำหน้า และกำจัด // ออกให้หมด
19
- let fullPath = (this.prefix + "/" + path)
20
- .replace(/\/+/g, "/") // ยุบ // ให้เหลือ /
21
- // .replace(/^\//, ""); // 🚩 ลบ / ตัวหน้าสุดออก (เช่น /api -> api)
22
-
23
- // ลบ / ตัวท้ายออกถ้ามี
24
- if (fullPath.endsWith("/")) fullPath = fullPath.slice(0, -1);
25
-
26
- this.routes.push({
27
- method: method.toUpperCase(),
28
- path: fullPath || "", // หน้าแรกจะเป็นค่าว่าง "" แทน "/"
29
- handlers: [...this.groupMiddleware, ...handlers]
30
- });
31
- return this;
32
- }
33
-
34
- public get = (path: string, ...h: HandlersChain) => this._add("GET", path, h);
35
- public post = (path: string, ...h: HandlersChain) => this._add("POST", path, h);
36
- public put = (path: string, ...h: HandlersChain) => this._add("PUT", path, h);
37
- public patch = (path: string, ...h: HandlersChain) => this._add("PATCH", path, h);
38
- public delete = (path: string, ...h: HandlersChain) => this._add("DELETE", path, h);
39
-
40
- public group = (path: string, ...args: any[]) => {
41
- const callback = args.pop();
42
- const middleware = args;
43
-
44
- // ส่ง prefix ต่อไปโดยคงรูปแบบเดิม
45
- const newPrefix = (this.prefix + "/" + path).replace(/\/+/g, "/");
46
- const subRouter = new BareRouter(newPrefix, [...this.groupMiddleware, ...middleware]);
47
-
48
- callback(subRouter);
49
- this.routes.push(...subRouter.routes);
50
- return this;
51
- };
52
-
53
- public use(mw: any) {
54
- if (mw instanceof BareRouter || (mw && mw.routes)) {
55
- // ดึงมาตรงๆ ไม่ต้องบวก prefix ซ้ำ เพราะใน subRouter มันคำนวณมาแล้ว
56
- this.routes.push(...mw.routes);
57
- } else {
58
- this.groupMiddleware.push(mw);
59
- }
60
- return this;
61
- }
62
- }
1
+ import {
2
+ type Middleware,
3
+ type Handler,
4
+ type GroupCallback
5
+ } from '../core/context';
6
+
7
+ type HandlersChain = (Middleware | Handler)[];
8
+
9
+ export class BareRouter {
10
+ public routes: any[] = [];
11
+
12
+ constructor(
13
+ public prefix: string = "",
14
+ public groupMiddleware: any[] = []
15
+ ) { }
16
+
17
+ private _add(method: string, path: string, handlers: HandlersChain) {
18
+ let fullPath = (this.prefix + "/" + path)
19
+ .replace(/\/+/g, "/")
20
+
21
+
22
+
23
+ if (fullPath.endsWith("/")) fullPath = fullPath.slice(0, -1);
24
+
25
+ this.routes.push({
26
+ method: method.toUpperCase(),
27
+ path: fullPath || "",
28
+ handlers: [...this.groupMiddleware, ...handlers]
29
+ });
30
+ return this;
31
+ }
32
+
33
+ public get = (path: string, ...h: HandlersChain) => this._add("GET", path, h);
34
+ public post = (path: string, ...h: HandlersChain) => this._add("POST", path, h);
35
+ public put = (path: string, ...h: HandlersChain) => this._add("PUT", path, h);
36
+ public patch = (path: string, ...h: HandlersChain) => this._add("PATCH", path, h);
37
+ public delete = (path: string, ...h: HandlersChain) => this._add("DELETE", path, h);
38
+ public options = (path: string, ...h: HandlersChain) => this._add("OPTIONS", path, h);
39
+
40
+ public group = (path: string, ...args: any[]) => {
41
+ const callback = args.pop();
42
+ const middleware = args;
43
+
44
+
45
+ const newPrefix = (this.prefix + "/" + path).replace(/\/+/g, "/");
46
+ const subRouter = new BareRouter(newPrefix, [...this.groupMiddleware, ...middleware]);
47
+
48
+ callback(subRouter);
49
+ this.routes.push(...subRouter.routes);
50
+ return this;
51
+ };
52
+
53
+ public use(mw: any) {
54
+ if (mw instanceof BareRouter || (mw && mw.routes)) {
55
+ this.routes.push(...mw.routes);
56
+ } else {
57
+ this.groupMiddleware.push(mw);
58
+ }
59
+ return this;
60
+ }
61
+ }
package/src/index.ts CHANGED
@@ -1,61 +1,73 @@
1
- /**
2
- * BareJS: The Metal of Web Frameworks
3
- * All comments must be in English [2026-01-06]
4
- * Built for Bun with Mechanical Sympathy
5
- * Optimized to outperform competitors by 55% [2026-01-05]
6
- */
7
-
8
- // --- 1. Core Engine ---
9
- export { BareJS } from './core/bare';
10
-
11
- /**
12
- * Plugin Interface for BareJS
13
- */
14
- export interface BarePlugin {
15
- install: (app: any) => void;
16
- }
17
-
18
- // --- 2. Context & Types ---
19
- export type {
20
- Middleware,
21
- Handler,
22
- Next,
23
- Context,
24
- Params,
25
- AuthUser
26
- } from './core/context';
27
-
28
- // --- 3. The Validation Suite (Builders - สำหรับสร้าง Schema) ---
29
- import { Type } from "@sinclair/typebox";
30
- export { Type, Type as T, Type as TypeBox };
31
-
32
- // --- 4. The Validation Suite (Engines - สำหรับเป็น Middleware) ---
33
- import { typebox, zod, native, validate, Z } from './security/validators';
34
- export {
35
- // TypeBox Engine
36
- typebox,
37
- typebox as t,
38
- // Zod Engine & Builder
39
- zod,
40
- zod as z,
41
- Z,
42
- Z as Zod,
43
- // Native Engine
44
- native,
45
- native as n,
46
- // Auto-Detect Engine
47
- validate,
48
- validate as v
49
- };
50
-
51
- // --- 5. Middlewares & Utilities ---
52
- // export { logger } from './utils/logger';
53
- export { cors } from './security/cors';
54
- export { staticFile } from './utils/static';
55
- export { BareRouter } from './core/router';
56
-
57
- // --- 6. Authentication (Bun Native) ---
58
- // Always deploy using process.env [2026-01-06]
59
- export { bareAuth, createToken } from './security/auth';
60
- // --- 7. Hashing ---
61
- export{Hash as Password, Hash} from './security/hash';
1
+ /**
2
+ * BareJS: The Metal of Web Frameworks
3
+ * All comments must be in English [2026-01-06]
4
+ * Built for Bun with Mechanical Sympathy
5
+ * Optimized to outperform competitors by 55% [2026-01-05]
6
+ */
7
+
8
+ // --- 1. Core Engine ---
9
+ export { BareJS, type WebSocketRouteHandler } from './core/bare';
10
+
11
+ /**
12
+ * Plugin Interface for BareJS
13
+ */
14
+ export interface BarePlugin {
15
+ install: (app: any) => void;
16
+ }
17
+
18
+ // --- 2. Context & Types ---
19
+ export type {
20
+ Middleware,
21
+ Handler,
22
+ Next,
23
+ Context,
24
+ Params,
25
+ AuthUser
26
+ } from './core/context';
27
+
28
+ // --- 3. The Validation Suite (Builders - สำหรับสร้าง Schema) ---
29
+ import { Type } from "@sinclair/typebox";
30
+ export { Type, Type as T, Type as TypeBox };
31
+
32
+ // --- 4. The Validation Suite (Engines - สำหรับเป็น Middleware) ---
33
+ import { typebox, zod, native, validate, Z } from './security/validators';
34
+ export {
35
+ // TypeBox Engine
36
+ typebox,
37
+ typebox as t,
38
+ // Zod Engine & Builder
39
+ zod,
40
+ zod as z,
41
+ Z,
42
+ Z as Zod,
43
+ // Native Engine
44
+ native,
45
+ native as n,
46
+ // Auto-Detect Engine
47
+ validate,
48
+ validate as v
49
+ };
50
+
51
+ // --- 5. Middlewares & Utilities ---
52
+ // export { logger } from './utils/logger';
53
+ export { cors } from './security/cors';
54
+ export { rateLimit, type RateLimitOptions } from './security/rateLimit';
55
+ export { securityHeaders, type SecurityHeadersOptions } from './security/headers';
56
+ export { staticFile } from './utils/static';
57
+ export { generateOpenAPISpec, renderDocsHTML, type OpenAPIOptions } from './utils/openapi';
58
+ export { BareRouter } from './core/router';
59
+
60
+ // --- 6. Authentication (Bun Native) ---
61
+ // Always deploy using process.env [2026-01-06]
62
+ export { bareAuth, createToken, basicAuth, hasRole } from './security/auth';
63
+ // --- 7. Hashing ---
64
+ export { Hash as Password, Hash } from './security/hash';
65
+
66
+ // --- 8. Type-Safe RPC Client ---
67
+ export {
68
+ bareClient,
69
+ type BareClient,
70
+ type BareClientOptions,
71
+ type ClientRequestOptions,
72
+ type RouteSchema
73
+ } from './client/index';