barejs 0.1.45 → 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.
package/src/core/bare.ts CHANGED
@@ -1,286 +1,315 @@
1
- import { BareRouter } from './router';
2
- import { RadixNode } from './radix';
3
- import { Context } from './context';
4
- import { Type as typebox, Type as t } from '@sinclair/typebox';
5
- import { join } from "node:path";
6
- import { readFileSync } from "node:fs";
7
- import { bootstrapConfig } from "./loader";
8
-
9
- export interface NotFoundResponse {
10
- status: number;
11
- message: string;
12
- [key: string]: any;
13
- }
14
- export class BareJS extends BareRouter {
15
- private tree = new RadixNode();
16
- private pool: Context[] = [];
17
- private poolIdx = 0;
18
- private hotFetch?: (req: Request) => any;
19
- private compiled = false;
20
- private poolMask: number;
21
-
22
- constructor(poolSize: number = 1024) {
23
- super();
24
- bootstrapConfig();
25
- const size = Math.pow(2, Math.ceil(Math.log2(poolSize)));
26
- this.poolMask = size - 1;
27
- for (let i = 0; i < size; i++) {
28
- this.pool.push(new Context());
29
- }
30
- try {
31
- const pkgPath = join(process.cwd(), "package.json");
32
- const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
33
- if (pkg.name) {
34
- this.name = pkg.name
35
- .split(/[-_]/)
36
- .map((word: string) => word.charAt(0).toUpperCase() + word.slice(1))
37
- .join(" ");
38
- }
39
- } catch {
40
- this.name = "App";
41
- }
42
- }
43
-
44
- private notFoundHandler: () => NotFoundResponse = () => ({
45
- status: 404,
46
- message: "Route not found"
47
- });
48
- public setNotFound(handler: () => NotFoundResponse) {
49
- this.notFoundHandler = handler;
50
- }
51
-
52
-
53
- // inherited use() from BareRouter handles router merging now
54
-
55
- private compileHandler(pipeline: any[]): Function {
56
- const mws = pipeline;
57
- const len = pipeline.length;
58
-
59
- // Static ResponseInit for 200 OK (Zero Allocation)
60
- const json200 = { status: 200, headers: { "content-type": "application/json" } };
61
-
62
- // Inline Finalizer
63
- const finalizeCode = `
64
- if (res instanceof Response) return res;
65
- // Smart Finalizer: Handle String vs Object vs Null
66
- if (typeof res === 'string') {
67
- return new Response(res, {
68
- status: ctx._status,
69
- headers: ctx._headers || { "content-type": "text/plain" }
70
- });
71
- }
72
-
73
- // FASTEST PATH: 200 OK + No Custom Headers -> Use Cached Init
74
- if (ctx._status === 200 && !ctx._headers) {
75
- return Response.json(res ?? null, json200);
76
- }
77
-
78
- return Response.json(res ?? null, {
79
- status: ctx._status,
80
- headers: ctx._headers && ctx._headers["content-type"] ? ctx._headers : { "content-type": "application/json" }
81
- });
82
- `;
83
-
84
- if (len === 1) {
85
- // 🚀 Fast path: no middleware (just the handler)
86
- const fn0 = pipeline[0];
87
- return new Function('fn0', 'json200', `return function(ctx) {
88
- const res = fn0(ctx);
89
- if (res && res.then) return res.then(v => { const res = v; ${finalizeCode} });
90
- ${finalizeCode}
91
- }`)(fn0, json200);
92
- }
93
-
94
- // Check async
95
- const isAsync = pipeline.some(fn => fn.constructor.name === 'AsyncFunction');
96
- let code = '';
97
-
98
- // Middleware Hoisting: Pass functions as arguments to avoid array lookup
99
- const fnNames = pipeline.map((_, i) => `fn${i}`);
100
-
101
- if (isAsync) {
102
- // ASYNC MODE
103
- for (let i = 0; i < len - 1; i++) {
104
- // Smart Await: Optimistically assume sync execution
105
- code += `let r${i} = fn${i}(ctx, noop);\n`;
106
- code += `if (r${i}) {\n`;
107
- code += ` if (r${i}.then) r${i} = await r${i};\n`;
108
- code += ` if (r${i} instanceof Response) return r${i};\n`;
109
- code += `}\n`;
110
- }
111
- } else {
112
- // SYNC MODE
113
- for (let i = 0; i < len - 1; i++) {
114
- code += `const r${i} = fn${i}(ctx, noop);\n`;
115
- // Optim: Truthy check first
116
- code += `if (r${i} && r${i} instanceof Response) return r${i};\n`;
117
- }
118
- }
119
-
120
- // Final handler
121
- if (isAsync) {
122
- code += `
123
- let res = fn${len - 1}(ctx);
124
- if (res && res.then) res = await res;
125
- ${finalizeCode}
126
- `;
127
- } else {
128
- code += `
129
- const res = fn${len - 1}(ctx);
130
- if (res && res.then) return res.then(v => { const res = v; ${finalizeCode} });
131
- ${finalizeCode}
132
- `;
133
- }
134
-
135
- const noop = () => { };
136
-
137
- const fnHeader = isAsync ? 'return async function(ctx)' : 'return function(ctx)';
138
-
139
- // Construct Function: (...fns, noop, json200) -> return function(ctx) { ... }
140
- return new Function(...fnNames, 'noop', 'json200', `${fnHeader} { ${code} }`)(...pipeline, noop, json200);
141
- }
142
-
143
- public compile() {
144
- this.tree = new RadixNode();
145
- for (const route of this.routes) {
146
- this.tree.insert(route.path, route.method, this.compileHandler(route.handlers));
147
- }
148
-
149
- const tree = this.tree;
150
- const pool = this.pool;
151
- const mask = this.poolMask;
152
- let pIdx = 0;
153
- const hNotFound = this.notFoundHandler;
154
- const hError = (err: any) => ({
155
- status: 500,
156
- message: err.message || "Internal Server Error",
157
- stack: process.env.NODE_ENV === 'development' ? err.stack : undefined
158
- });
159
-
160
- // JIT Compiler: Create all Code instead of tree.lookup
161
- const hoistedHandlers: Function[] = [];
162
- const register = (h: Function) => {
163
- const name = `h${hoistedHandlers.length}`;
164
- hoistedHandlers.push(h);
165
- return name;
166
- };
167
-
168
- const routerCode = tree.jitCompile(register);
169
-
170
- // Create seamless Fetcher (JIT Edition)
171
- // We send nodes into the closure so the code can use them
172
- const EMPTY_PARAMS = Object.freeze({});
173
- const hNames = hoistedHandlers.map((_, i) => `h${i}`);
174
-
175
- const args = ['pool', 'pIdx', 'mask', 'hNotFound', 'hError', 'EMPTY_PARAMS', ...hNames];
176
- const values = [pool, pIdx, mask, hNotFound, hError, EMPTY_PARAMS, ...hoistedHandlers];
177
-
178
- const fnBody = `
179
- return function(req) {
180
- const url = req.url;
181
- // Start searching after "http://" (7) or "https://" (8)
182
- let s = url.indexOf('/', 8);
183
-
184
- // Handle root path or missing slash
185
- if (s === -1) {
186
- s = url.length;
187
- } else if (url.charCodeAt(s) === 47) {
188
- // Skip the leading slash to match split() behavior (['users'] not ['/users'])
189
- s++;
190
- }
191
-
192
- const method = req.method;
193
- const ctx = pool[(++pIdx) & mask];
194
- try {
195
- // INLINED Context.reset() for max speed (No function call overhead)
196
- ctx.req = req;
197
- ctx._status = 200;
198
- ctx._headers = undefined;
199
- if (ctx.store.size > 0) ctx.store.clear();
200
- ctx.params = EMPTY_PARAMS;
201
- ctx.body = undefined;
202
-
203
- // JIT Generated Code Start
204
- ${routerCode}
205
- // JIT Generated Code End
206
- const errorBody = hNotFound();
207
- return Response.json(errorBody, { status: errorBody.status || 404 });
208
- } catch (e) {
209
- const errorBody = hError(e);
210
- return Response.json(errorBody, { status: errorBody.status || 500 });
211
- }
212
- }
213
- `;
214
-
215
- this.hotFetch = new Function(...args, fnBody)(...values);
216
- this.compiled = true;
217
- // Auto-Optimize: Replace wrapper with direct JIT function
218
- this.fetch = this.hotFetch!;
219
- }
220
-
221
- public fetch = (req: Request): any => {
222
- if (!this.compiled) {
223
- this.compile();
224
- return this.hotFetch!(req);
225
- }
226
- return this.hotFetch!(req);
227
- };
228
- public name: string = "App";
229
-
230
- public listen(port?: number, hostname: string = '0.0.0.0', reusePort: boolean = true) {
231
- if (!this.compiled) this.compile();
232
-
233
- // ดึงค่า Config ล่าสุดมาใช้
234
- const { BARE_CONFIG } = require("./config");
235
-
236
- // ลำดับความสำคัญ: Parameter > Config File > Default (3000)
237
- const finalPort = port || BARE_CONFIG.port || 3000;
238
- const isProd = process.env.NODE_ENV === 'production';
239
-
240
- if (!isProd) {
241
- console.log(`
242
- \x1b[33m ____ _ _____ \x1b[0m
243
- \x1b[33m | __ ) __ _ _ __ ___ | | ____|\x1b[0m
244
- \x1b[33m | _ \\ / _\` | '__/ _ \\ _ | | _| \x1b[0m
245
- \x1b[33m | |_) | (_| | | | __/| |_| | |___ \x1b[0m
246
- \x1b[33m |____/ \\__,_|_| \\___| \\___/|_____|\x1b[0m
247
-
248
- \x1b[32m🚀 ${this.name} is running in development mode\x1b[0m
249
- \x1b[90m⚙️ Pool Size: ${this.pool.length} | JIT: Enabled | Port: ${finalPort}\x1b[0m
250
- \x1b[36m🛡️ Hash: ${BARE_CONFIG.hash.algorithm} (${BARE_CONFIG.hash.memoryCost / 1024}MB) | Iterations: ${BARE_CONFIG.hash.timeCost}\x1b[0m
251
- `);
252
- }
253
-
254
- const server = Bun.serve({
255
- port: finalPort,
256
- hostname,
257
- fetch: this.fetch,
258
- reusePort: reusePort,
259
- });
260
-
261
- const shutdown = () => {
262
- const isProd = process.env.NODE_ENV === 'production';
263
- const serverName = this.name;
264
- const supportsEmoji = process.stdout.isTTY;
265
-
266
- if (isProd) {
267
- console.log(`[${serverName}] INFO: Stopping server...`);
268
- } else {
269
-
270
- const stopIcon = supportsEmoji ? "🛑" : "!";
271
- const checkIcon = supportsEmoji ? "✅" : "v";
272
-
273
-
274
- process.stdout.write(`\n\x1b[31m${stopIcon} Stopping ${serverName}...\x1b[0m\n`);
275
- server.stop();
276
- process.stdout.write(`\x1b[32m${checkIcon} ${serverName} has been stopped.\x1b[0m\n`);
277
- }
278
- process.exit(0);
279
- };
280
-
281
- process.on("SIGINT", shutdown);
282
- process.on("SIGTERM", shutdown);
283
- }
284
- }
285
-
286
- export { Context, typebox, t };
1
+ import { BareRouter } from './router';
2
+ import { RadixNode } from './radix';
3
+ import { Context } from './context';
4
+ import { Type as typebox, Type as t } from '@sinclair/typebox';
5
+ import { join } from "node:path";
6
+ import { readFileSync } from "node:fs";
7
+ import { bootstrapConfig } from "./loader";
8
+
9
+ export interface NotFoundResponse {
10
+ status: number;
11
+ message: string;
12
+ [key: string]: any;
13
+ }
14
+ export class BareJS extends BareRouter {
15
+ private tree = new RadixNode();
16
+ private pool: Context[] = [];
17
+ // private poolIdx = 0;
18
+ private hotFetch?: (req: Request) => any;
19
+ private compiled = false;
20
+ private poolMask: number;
21
+ private _useLog: boolean = false;
22
+ public useLog(enabled: boolean = true): this {
23
+ this._useLog = enabled;
24
+ return this;
25
+ }
26
+ constructor(poolSize: number = 1024) {
27
+ super();
28
+ bootstrapConfig();
29
+ const size = Math.pow(2, Math.ceil(Math.log2(poolSize)));
30
+ this.poolMask = size - 1;
31
+ for (let i = 0; i < size; i++) {
32
+ this.pool.push(new Context());
33
+ }
34
+ try {
35
+ const pkgPath = join(process.cwd(), "package.json");
36
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
37
+ if (pkg.name) {
38
+ this.name = pkg.name
39
+ .split(/[-_]/)
40
+ .map((word: string) => word.charAt(0).toUpperCase() + word.slice(1))
41
+ .join(" ");
42
+ }
43
+ } catch {
44
+ this.name = "App";
45
+ }
46
+ }
47
+
48
+ private notFoundHandler: () => NotFoundResponse = () => ({
49
+ status: 404,
50
+ message: "Route not found"
51
+ });
52
+ public setNotFound(handler: () => NotFoundResponse) {
53
+ this.notFoundHandler = handler;
54
+ }
55
+
56
+
57
+ // inherited use() from BareRouter handles router merging now
58
+
59
+ private compileHandler(pipeline: any[], isLog: boolean): Function {
60
+ const len = pipeline.length;
61
+
62
+ // Static ResponseInit for 200 OK (Zero Allocation)
63
+ const json200 = { status: 200, headers: { "content-type": "application/json" } };
64
+ const text200 = { status: 200, headers: { "content-type": "text/plain" } };
65
+
66
+ const logResCode = isLog ? 'doLog(res.status);' : '';
67
+ const logStatusCode = isLog ? 'doLog(finalStatus);' : '';
68
+
69
+ // Inline Finalizer
70
+ const finalizeCode = `
71
+ if (res instanceof Response) {
72
+ ${logResCode}
73
+ return res;
74
+ }
75
+
76
+ const finalStatus = ctx._status || 200;
77
+ ${logStatusCode}
78
+
79
+ if (typeof res === 'string') {
80
+ if (finalStatus === 200 && !ctx._headers) return new Response(res, text200);
81
+ return new Response(res, {
82
+ status: finalStatus,
83
+ headers: ctx._headers || text200.headers
84
+ });
85
+ }
86
+
87
+ if (finalStatus === 200 && !ctx._headers) return Response.json(res ?? null, json200);
88
+ return Response.json(res ?? null, {
89
+ status: finalStatus,
90
+ headers: ctx._headers && ctx._headers["content-type"] ? ctx._headers : json200.headers
91
+ });
92
+ `;
93
+
94
+ const argSig = isLog ? 'ctx, doLog' : 'ctx';
95
+
96
+ if (len === 1) {
97
+ const fn0 = pipeline[0];
98
+ return new Function('fn0', 'json200', 'text200', `return function(${argSig}) {
99
+ const res = fn0(ctx);
100
+ if (res && res.then) return res.then(v => { const res = v; ${finalizeCode} });
101
+ ${finalizeCode}
102
+ }`)(fn0, json200, text200);
103
+ }
104
+
105
+ // Check async
106
+ const isAsync = pipeline.some(fn => fn.constructor.name === 'AsyncFunction');
107
+ let code = '';
108
+
109
+ // Middleware Hoisting: Pass functions as arguments to avoid array lookup
110
+ const fnNames = pipeline.map((_, i) => `fn${i}`);
111
+
112
+ if (isAsync) {
113
+ for (let i = 0; i < len - 1; i++) {
114
+ code += `let r${i} = fn${i}(ctx, noop);\n`;
115
+ code += `if (r${i}) {\n`;
116
+ code += ` if (r${i}.then) r${i} = await r${i};\n`;
117
+ code += ` if (r${i} instanceof Response) { ${isLog ? 'doLog(r' + i + '.status);' : ''} return r${i}; }\n`;
118
+ code += `}\n`;
119
+ }
120
+ code += `
121
+ let res = fn${len - 1}(ctx);
122
+ if (res && res.then) res = await res;
123
+ ${finalizeCode}
124
+ `;
125
+ } else {
126
+ for (let i = 0; i < len - 1; i++) {
127
+ code += `const r${i} = fn${i}(ctx, noop);\n`;
128
+ code += `if (r${i} && r${i} instanceof Response) { ${isLog ? 'doLog(r' + i + '.status);' : ''} return r${i}; }\n`;
129
+ }
130
+ code += `
131
+ const res = fn${len - 1}(ctx);
132
+ if (res && res.then) return res.then(v => { const res = v; ${finalizeCode} });
133
+ ${finalizeCode}
134
+ `;
135
+ }
136
+
137
+ const noop = () => { };
138
+ const fnHeader = isAsync
139
+ ? `return async function(${argSig})`
140
+ : `return function(${argSig})`;
141
+
142
+ return new Function(...fnNames, 'noop', 'json200', 'text200', `${fnHeader} { ${code} }`)(...pipeline, noop, json200, text200);
143
+ }
144
+
145
+ public compile() {
146
+ const isLog = this._useLog;
147
+ this.tree = new RadixNode();
148
+ for (const route of this.routes) {
149
+ this.tree.insert(route.path, route.method, this.compileHandler(route.handlers, isLog));
150
+ }
151
+
152
+ const tree = this.tree;
153
+ const pool = this.pool;
154
+ const maxPool = pool.length;
155
+ const hNotFound = this.notFoundHandler;
156
+ const hError = (err: any) => ({
157
+ status: 500,
158
+ message: process.env.NODE_ENV === 'development' ? (err?.message || "Internal Server Error") : "Internal Server Error",
159
+ stack: process.env.NODE_ENV === 'development' ? err?.stack : undefined
160
+ });
161
+
162
+ const hoistedHandlers: Function[] = [];
163
+ const register = (h: Function) => {
164
+ const name = `h${hoistedHandlers.length}`;
165
+ hoistedHandlers.push(h);
166
+ return name;
167
+ };
168
+
169
+ const rawRouterCode = tree.jitCompile(register);
170
+ const EMPTY_PARAMS = Object.freeze({});
171
+ const hNames = hoistedHandlers.map((_, i) => `h${i}`);
172
+
173
+ const releaseCode = `
174
+ if (ctx.store.size > 0) ctx.store.clear();
175
+ ctx.req = undefined;
176
+ ctx.body = undefined;
177
+ ctx._headers = undefined;
178
+ ctx.params = EMPTY_PARAMS;
179
+ if (poolTop < maxPool) pool[poolTop++] = ctx;
180
+ `;
181
+
182
+ const callSuffix = isLog ? '(ctx, doLog)' : '(ctx)';
183
+ const routerCode = rawRouterCode.replace(
184
+ /return (h\d+)\(ctx\);/g,
185
+ `const out = $1${callSuffix};
186
+ if (out && out.then) return out.then((v) => { ${releaseCode} return v; }, (e) => { ${releaseCode} ${isLog ? 'doLog(500);' : ''} return Response.json(hError(e), { status: 500 }); });
187
+ ${releaseCode}
188
+ return out;`
189
+ );
190
+
191
+ const args = ['pool', 'maxPool', 'Context', 'hNotFound', 'hError', 'EMPTY_PARAMS', ...hNames];
192
+ const values = [pool, maxPool, Context, hNotFound, hError, EMPTY_PARAMS, ...hoistedHandlers];
193
+
194
+ const logInit = isLog ? `
195
+ const start = performance.now();
196
+ const doLog = (status) => {
197
+ const duration = (performance.now() - start).toFixed(3);
198
+ console.log(
199
+ \` \\x1b[90m\${new Date().toLocaleTimeString()}\\x1b[0m \` +
200
+ \`\\x1b[1m\\x1b[38;5;117m\${method.padEnd(7)}\\x1b[0m \` +
201
+ \`\\x1b[38;5;250m\${url.substring(url.indexOf('/', 8))}\\x1b[0m \` +
202
+ \`\${status >= 400 ? '\\x1b[33m' : '\\x1b[32m'}\${status}\\x1b[0m \` +
203
+ \`\\x1b[90m(\${duration}ms)\\x1b[0m\`
204
+ );
205
+ };` : '';
206
+
207
+ const fnBody = `
208
+ let poolTop = maxPool;
209
+ return function(req) {
210
+ const url = req.url;
211
+ let s = url.indexOf('/', 8);
212
+ const q = s === -1 ? -1 : url.indexOf('?', s);
213
+ const urlLen = q === -1 ? url.length : q;
214
+ if (s !== -1) s++;
215
+ else s = urlLen;
216
+
217
+ const method = req.method;
218
+ const ctx = poolTop > 0 ? pool[--poolTop] : new Context();
219
+ ${logInit}
220
+
221
+ try {
222
+ ctx.req = req;
223
+ ctx._status = 200;
224
+ ctx._headers = undefined;
225
+ if (ctx.store.size > 0) ctx.store.clear();
226
+ ctx.params = EMPTY_PARAMS;
227
+ ctx.body = undefined;
228
+
229
+ ${routerCode}
230
+
231
+ const errorBody = hNotFound();
232
+ const status = errorBody.status || 404;
233
+ ${isLog ? 'doLog(status);' : ''}
234
+ ${releaseCode}
235
+ return Response.json(errorBody, { status });
236
+
237
+ } catch (e) {
238
+ ${isLog ? 'doLog(500);' : ''}
239
+ ${releaseCode}
240
+ return Response.json(hError(e), { status: 500 });
241
+ }
242
+ }
243
+ `;
244
+
245
+ this.hotFetch = new Function(...args, fnBody)(...values);
246
+ this.compiled = true;
247
+ this.fetch = this.hotFetch!;
248
+ }
249
+
250
+ public fetch = (req: Request): any => {
251
+ if (!this.compiled) {
252
+ this.compile();
253
+ return this.hotFetch!(req);
254
+ }
255
+ return this.hotFetch!(req);
256
+ };
257
+ public name: string = "App";
258
+
259
+ public listen(port?: number, hostname: string = '0.0.0.0', reusePort: boolean = true) {
260
+ if (!this.compiled) this.compile();
261
+
262
+
263
+ const { BARE_CONFIG } = require("./config");
264
+
265
+
266
+ const finalPort = port || BARE_CONFIG.port || 3000;
267
+ const isProd = process.env.NODE_ENV === 'production';
268
+
269
+ if (!isProd) {
270
+ console.log(`
271
+ \x1b[33m ____ _ _____ \x1b[0m
272
+ \x1b[33m | __ ) __ _ _ __ ___ | | ____|\x1b[0m
273
+ \x1b[33m | _ \\ / _\` | '__/ _ \\ _ | | _| \x1b[0m
274
+ \x1b[33m | |_) | (_| | | | __/| |_| | |___ \x1b[0m
275
+ \x1b[33m |____/ \\__,_|_| \\___| \\___/|_____|\x1b[0m
276
+
277
+ \x1b[32m🚀 ${this.name} is running in development mode\x1b[0m
278
+ \x1b[90m⚙️ Pool Size: ${this.pool.length} | JIT: Enabled | Port: ${finalPort}\x1b[0m
279
+ \x1b[36m🛡️ Hash: ${BARE_CONFIG.hash.algorithm} (${BARE_CONFIG.hash.memoryCost / 1024}MB) | Iterations: ${BARE_CONFIG.hash.timeCost}\x1b[0m
280
+ `);
281
+ }
282
+
283
+ const server = Bun.serve({
284
+ port: finalPort,
285
+ hostname,
286
+ fetch: this.fetch,
287
+ reusePort: reusePort,
288
+ });
289
+
290
+ const shutdown = () => {
291
+ const isProd = process.env.NODE_ENV === 'production';
292
+ const serverName = this.name;
293
+ const supportsEmoji = process.stdout.isTTY;
294
+
295
+ if (isProd) {
296
+ console.log(`[${serverName}] INFO: Stopping server...`);
297
+ } else {
298
+
299
+ const stopIcon = supportsEmoji ? "🛑" : "!";
300
+ const checkIcon = supportsEmoji ? "✅" : "v";
301
+
302
+
303
+ process.stdout.write(`\n\x1b[31m${stopIcon} Stopping ${serverName}...\x1b[0m\n`);
304
+ server.stop();
305
+ process.stdout.write(`\x1b[32m${checkIcon} ${serverName} has been stopped.\x1b[0m\n`);
306
+ }
307
+ process.exit(0);
308
+ };
309
+
310
+ process.on("SIGINT", shutdown);
311
+ process.on("SIGTERM", shutdown);
312
+ }
313
+ }
314
+
315
+ export { Context, typebox, t };