barejs 0.1.47 → 0.1.48

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,32 +1,32 @@
1
- // src/core/config.ts
2
-
3
- export interface BareConfig {
4
- hash: {
5
- algorithm: "argon2id" | "bcrypt";
6
- memoryCost: number;
7
- timeCost: number;
8
- };
9
- port: number;
10
-
11
- }
12
-
13
- export const DEFAULT_CONFIG: BareConfig = {
14
- hash: {
15
- algorithm: "argon2id",
16
- memoryCost: 65536, // 64MB
17
- timeCost: 2
18
- },
19
- port: 3000
20
- };
21
-
22
- export let BARE_CONFIG = DEFAULT_CONFIG;
23
-
24
-
25
- export const initConfig = (userConfig: Partial<BareConfig> = {}) => {
26
- BARE_CONFIG = {
27
- ...DEFAULT_CONFIG,
28
- ...userConfig,
29
- hash: { ...DEFAULT_CONFIG.hash, ...userConfig.hash }
30
- };
31
- return BARE_CONFIG;
1
+ // src/core/config.ts
2
+
3
+ export interface BareConfig {
4
+ hash: {
5
+ algorithm: "argon2id" | "bcrypt";
6
+ memoryCost: number;
7
+ timeCost: number;
8
+ };
9
+ port: number;
10
+
11
+ }
12
+
13
+ export const DEFAULT_CONFIG: BareConfig = {
14
+ hash: {
15
+ algorithm: "argon2id",
16
+ memoryCost: 65536, // 64MB
17
+ timeCost: 2
18
+ },
19
+ port: 3000
20
+ };
21
+
22
+ export let BARE_CONFIG = DEFAULT_CONFIG;
23
+
24
+
25
+ export const initConfig = (userConfig: Partial<BareConfig> = {}) => {
26
+ BARE_CONFIG = {
27
+ ...DEFAULT_CONFIG,
28
+ ...userConfig,
29
+ hash: { ...DEFAULT_CONFIG.hash, ...userConfig.hash }
30
+ };
31
+ return BARE_CONFIG;
32
32
  };
@@ -1,112 +1,112 @@
1
- export type Params = Record<string, string>;
2
- export type Next = () => Promise<any> | any;
3
- export type Middleware = (ctx: Context, next: Next) => Promise<any> | any;
4
- export type Handler = (ctx: Context) => Promise<any> | any;
5
- export type GroupCallback = (router: any) => void;
6
- export type AuthUser = Record<string, any>;
7
-
8
- export class Context {
9
- public req!: Request;
10
- public params: Params = {};
11
- public _status = 200;
12
- public _headers?: Record<string, string> | undefined = undefined;
13
- public store = new Map<string, any>();
14
- public body: any = undefined;
15
- public query: Record<string, string> = {};
16
- constructor() { }
17
-
18
-
19
- public async jsonBody(): Promise<any> {
20
-
21
- if (this.body !== undefined) return this.body;
22
-
23
-
24
- const contentType = this.req.headers.get("content-type");
25
- if (contentType && contentType.includes("application/json")) {
26
- try {
27
-
28
- return this.body = await this.req.json();
29
- } catch {
30
- return this.body = null;
31
- }
32
- }
33
- return this.body = null;
34
- }
35
-
36
-
37
- public reset(req: Request): this {
38
- this.req = req;
39
- this._status = 200;
40
- this._headers = undefined;
41
- if (this.store.size > 0) this.store.clear();
42
- this.params = {};
43
- this.query = {};
44
- this.body = undefined;
45
- return this;
46
- }
47
-
48
- public status(code: number): this {
49
- this._status = code;
50
- return this;
51
- }
52
-
53
- // public json(data: any): Response {
54
- // if (this._headers !== undefined) {
55
- // if (this._headers["content-type"] === undefined) {
56
- // this._headers["content-type"] = "application/json";
57
- // }
58
- // return Response.json(data, {
59
- // status: this._status,
60
- // headers: this._headers
61
- // });
62
- // }
63
- // if (this._status === 200) {
64
- // return Response.json(data);
65
- // }
66
- // return Response.json(data, { status: this._status });
67
- // }
68
- public json(data: any): Response {
69
- const status = this._status || 200;
70
-
71
- // No custom headers
72
- if (!this._headers) {
73
- return Response.json(data, { status });
74
- }
75
-
76
- // Ensure Content-Type is set to application/json
77
- if (this._headers["content-type"] === undefined) {
78
- this._headers["content-type"] = "application/json";
79
- }
80
-
81
- return Response.json(data, {
82
- status,
83
- headers: this._headers as any // ⚠️ FIX TS18046: Cast to 'any' to allow assignment to 'unknown' headers
84
- });
85
- }
86
-
87
- public set(key: string, value: any): this {
88
- this.store.set(key, value);
89
- return this;
90
- }
91
-
92
- public get(key: string): any {
93
- return this.store.get(key);
94
- }
95
-
96
- public setHeader(name: string, value: string): this {
97
- if (!this._headers) this._headers = {};
98
- this._headers[name.toLowerCase()] = value;
99
- return this;
100
- }
101
-
102
-
103
- public send(message: string, extra: Record<string, any> = {}): Response {
104
- const isError = this._status >= 400;
105
-
106
- return this.json({
107
- status: isError ? "error" : "success",
108
- msg: message,
109
- ...extra
110
- });
111
- }
1
+ export type Params = Record<string, string>;
2
+ export type Next = () => Promise<any> | any;
3
+ export type Middleware = (ctx: Context, next: Next) => Promise<any> | any;
4
+ export type Handler = (ctx: Context) => Promise<any> | any;
5
+ export type GroupCallback = (router: any) => void;
6
+ export type AuthUser = Record<string, any>;
7
+
8
+ export class Context {
9
+ public req!: Request;
10
+ public params: Params = {};
11
+ public _status = 200;
12
+ public _headers?: Record<string, string> | undefined = undefined;
13
+ public store = new Map<string, any>();
14
+ public body: any = undefined;
15
+ public query: Record<string, string> = {};
16
+ constructor() { }
17
+
18
+
19
+ public async jsonBody(): Promise<any> {
20
+
21
+ if (this.body !== undefined) return this.body;
22
+
23
+
24
+ const contentType = this.req.headers.get("content-type");
25
+ if (contentType && contentType.includes("application/json")) {
26
+ try {
27
+
28
+ return this.body = await this.req.json();
29
+ } catch {
30
+ return this.body = null;
31
+ }
32
+ }
33
+ return this.body = null;
34
+ }
35
+
36
+
37
+ public reset(req: Request): this {
38
+ this.req = req;
39
+ this._status = 200;
40
+ this._headers = undefined;
41
+ if (this.store.size > 0) this.store.clear();
42
+ this.params = {};
43
+ this.query = {};
44
+ this.body = undefined;
45
+ return this;
46
+ }
47
+
48
+ public status(code: number): this {
49
+ this._status = code;
50
+ return this;
51
+ }
52
+
53
+ // public json(data: any): Response {
54
+ // if (this._headers !== undefined) {
55
+ // if (this._headers["content-type"] === undefined) {
56
+ // this._headers["content-type"] = "application/json";
57
+ // }
58
+ // return Response.json(data, {
59
+ // status: this._status,
60
+ // headers: this._headers
61
+ // });
62
+ // }
63
+ // if (this._status === 200) {
64
+ // return Response.json(data);
65
+ // }
66
+ // return Response.json(data, { status: this._status });
67
+ // }
68
+ public json(data: any): Response {
69
+ const status = this._status || 200;
70
+
71
+ // No custom headers
72
+ if (!this._headers) {
73
+ return Response.json(data, { status });
74
+ }
75
+
76
+ // Ensure Content-Type is set to application/json
77
+ if (this._headers["content-type"] === undefined) {
78
+ this._headers["content-type"] = "application/json";
79
+ }
80
+
81
+ return Response.json(data, {
82
+ status,
83
+ headers: this._headers as any // ⚠️ FIX TS18046: Cast to 'any' to allow assignment to 'unknown' headers
84
+ });
85
+ }
86
+
87
+ public set(key: string, value: any): this {
88
+ this.store.set(key, value);
89
+ return this;
90
+ }
91
+
92
+ public get(key: string): any {
93
+ return this.store.get(key);
94
+ }
95
+
96
+ public setHeader(name: string, value: string): this {
97
+ if (!this._headers) this._headers = {};
98
+ this._headers[name.toLowerCase()] = value;
99
+ return this;
100
+ }
101
+
102
+
103
+ public send(message: string, extra: Record<string, any> = {}): Response {
104
+ const isError = this._status >= 400;
105
+
106
+ return this.json({
107
+ status: isError ? "error" : "success",
108
+ msg: message,
109
+ ...extra
110
+ });
111
+ }
112
112
  }
@@ -1,13 +1,13 @@
1
- // src/core/loader.ts
2
- import { join } from "node:path";
3
- import { initConfig } from "./config";
4
-
5
- export async function bootstrapConfig() {
6
- const configPath = join(process.cwd(), "bare.config.ts");
7
- try {
8
- const userModule = await import(configPath);
9
- return initConfig(userModule.default);
10
- } catch {
11
- return initConfig();
12
- }
1
+ // src/core/loader.ts
2
+ import { join } from "node:path";
3
+ import { initConfig } from "./config";
4
+
5
+ export async function bootstrapConfig() {
6
+ const configPath = join(process.cwd(), "bare.config.ts");
7
+ try {
8
+ const userModule = await import(configPath);
9
+ return initConfig(userModule.default);
10
+ } catch {
11
+ return initConfig();
12
+ }
13
13
  }
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
+ }