burger-api 0.5.0 → 0.5.1
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/README.md +9 -2
- package/dist/src/core/api-router.d.ts +0 -53
- package/dist/src/core/api-router.js +3 -93
- package/dist/src/core/openapi.js +1 -58
- package/dist/src/core/page-router.d.ts +0 -43
- package/dist/src/core/page-router.js +1 -72
- package/dist/src/core/server.d.ts +0 -10
- package/dist/src/core/server.js +0 -16
- package/dist/src/index.d.ts +0 -57
- package/dist/src/index.js +8 -280
- package/dist/src/middleware/validator.d.ts +0 -12
- package/dist/src/middleware/validator.js +9 -59
- package/dist/src/types/index.d.ts +0 -143
- package/dist/src/utils/error.d.ts +0 -16
- package/dist/src/utils/error.js +0 -24
- package/dist/src/utils/index.d.ts +0 -17
- package/dist/src/utils/index.js +0 -22
- package/dist/src/utils/response.d.ts +0 -9
- package/dist/src/utils/response.js +0 -9
- package/dist/src/utils/routing.d.ts +0 -28
- package/dist/src/utils/routing.js +3 -41
- package/dist/src/utils/wildcard.d.ts +3 -0
- package/dist/src/utils/wildcard.js +30 -0
- package/package.json +88 -88
package/dist/src/index.js
CHANGED
|
@@ -1,328 +1,105 @@
|
|
|
1
|
-
// Import stuff from core
|
|
2
1
|
import { Server } from './core/server';
|
|
3
2
|
import { ApiRouter } from './core/api-router';
|
|
4
3
|
import { PageRouter } from './core/page-router';
|
|
5
4
|
import { generateOpenAPIDocument } from './core/openapi';
|
|
6
5
|
import { swaggerHtml } from './core/swagger-ui';
|
|
7
|
-
// Import utils
|
|
8
6
|
import { collectRoutes } from './utils/index';
|
|
9
7
|
import { METHOD_NOT_ALLOWED, NOT_FOUND, OPENAPI_ERROR } from './utils/response';
|
|
10
|
-
|
|
8
|
+
import { extractPathnameFromUrl, extractWildcardParams, } from './utils/wildcard';
|
|
11
9
|
import { createValidationMiddleware } from './middleware/validator';
|
|
12
10
|
export class Burger {
|
|
13
11
|
options;
|
|
14
|
-
/**
|
|
15
|
-
* The server instance
|
|
16
|
-
*/
|
|
17
12
|
server;
|
|
18
|
-
/**
|
|
19
|
-
* The API router instance
|
|
20
|
-
*/
|
|
21
13
|
apiRouter;
|
|
22
|
-
/**
|
|
23
|
-
* The page router instance
|
|
24
|
-
*/
|
|
25
14
|
pageRouter;
|
|
26
|
-
/**
|
|
27
|
-
* The global middleware
|
|
28
|
-
*/
|
|
29
15
|
globalMiddleware = [];
|
|
30
|
-
/**
|
|
31
|
-
* The OpenAPI document
|
|
32
|
-
*/
|
|
33
16
|
openApiDoc = null;
|
|
34
|
-
/**
|
|
35
|
-
* The routes object
|
|
36
|
-
*/
|
|
37
17
|
routes = {};
|
|
38
|
-
/**
|
|
39
|
-
* Pre-computed responses for reuse
|
|
40
|
-
*/
|
|
41
18
|
METHOD_NOT_ALLOWED = METHOD_NOT_ALLOWED;
|
|
42
|
-
/**
|
|
43
|
-
* The not found response
|
|
44
|
-
*/
|
|
45
19
|
NOT_FOUND = NOT_FOUND;
|
|
46
|
-
/**
|
|
47
|
-
* The OpenAPI error response
|
|
48
|
-
*/
|
|
49
20
|
OPENAPI_ERROR = OPENAPI_ERROR;
|
|
50
|
-
/**
|
|
51
|
-
* Constructor for the Burger class.
|
|
52
|
-
* @param options - The options for the server and router.
|
|
53
|
-
* The options object should contain the following properties:
|
|
54
|
-
* - port: The port number to listen on.
|
|
55
|
-
* - apiDir: The directory path to load API routes from.
|
|
56
|
-
* - pageDir: The directory path to load page routes from.
|
|
57
|
-
* - middleware: An array of global middleware functions.
|
|
58
|
-
*/
|
|
59
21
|
constructor(options) {
|
|
60
22
|
this.options = options;
|
|
61
|
-
// Create server instance
|
|
62
23
|
this.server = new Server(options);
|
|
63
|
-
// Fast initialization for routers with nullish coalescing
|
|
64
24
|
const { apiDir, pageDir, apiPrefix, pagePrefix, globalMiddleware } = options;
|
|
65
|
-
// Initialize API router if apiDir is provided
|
|
66
25
|
this.apiRouter = apiDir
|
|
67
26
|
? new ApiRouter(apiDir, apiPrefix || 'api')
|
|
68
27
|
: undefined;
|
|
69
|
-
// Initialize page router if pageDir is provided
|
|
70
28
|
this.pageRouter = pageDir
|
|
71
29
|
? new PageRouter(pageDir, pagePrefix || '')
|
|
72
30
|
: undefined;
|
|
73
|
-
// Add global middleware if any
|
|
74
31
|
this.globalMiddleware = globalMiddleware?.length
|
|
75
32
|
? globalMiddleware.slice()
|
|
76
33
|
: [];
|
|
77
34
|
}
|
|
78
|
-
/**
|
|
79
|
-
* Process the page routes and add them to the routes object
|
|
80
|
-
* @returns A promise that resolves to a boolean
|
|
81
|
-
*/
|
|
82
35
|
async processPageRoutes() {
|
|
83
|
-
// If no page router, return false
|
|
84
36
|
if (!this.pageRouter)
|
|
85
37
|
return false;
|
|
86
|
-
// Load pages routes
|
|
87
38
|
await this.pageRouter.loadPages();
|
|
88
|
-
// If there are any page routes, add them to the routes object
|
|
89
39
|
const pages = this.pageRouter.pages;
|
|
90
|
-
// Get the length of the pages routes
|
|
91
40
|
const pageCount = pages.length;
|
|
92
|
-
// If no pages, return false
|
|
93
41
|
if (pageCount === 0)
|
|
94
42
|
return false;
|
|
95
|
-
// Loop through the pages
|
|
96
43
|
for (let i = 0; i < pageCount; i++) {
|
|
97
|
-
// Get the current page
|
|
98
44
|
const page = pages[i];
|
|
99
|
-
// Add the page to the routes
|
|
100
45
|
this.routes[page.path] = page.handler;
|
|
101
46
|
}
|
|
102
|
-
// Return true if there are any pages
|
|
103
47
|
return true;
|
|
104
48
|
}
|
|
105
|
-
/**
|
|
106
|
-
* Process the API routes and add them to the routes object
|
|
107
|
-
* @returns A promise that resolves to a boolean
|
|
108
|
-
*/
|
|
109
49
|
async processApiRoutes() {
|
|
110
|
-
// If no api router, return false
|
|
111
50
|
if (!this.apiRouter)
|
|
112
51
|
return false;
|
|
113
|
-
// Load API routes
|
|
114
52
|
await this.apiRouter.loadRoutes();
|
|
115
|
-
// Collect API routes
|
|
116
53
|
const apiRoutes = collectRoutes(this.apiRouter.routes);
|
|
117
|
-
// Get the length of the API routes
|
|
118
54
|
const routeCount = apiRoutes.length;
|
|
119
|
-
// If there are no API routes, return false
|
|
120
55
|
if (routeCount === 0)
|
|
121
56
|
return false;
|
|
122
|
-
// Generate OpenAPI document and cache it
|
|
123
57
|
this.openApiDoc = generateOpenAPIDocument(apiRoutes, this.options);
|
|
124
|
-
// Cache frequently accessed properties
|
|
125
58
|
const routes = this.routes;
|
|
126
|
-
// Get the global middleware
|
|
127
59
|
const globalMiddleware = this.globalMiddleware;
|
|
128
|
-
// Get the length of the global middleware
|
|
129
60
|
const globalMiddlewareLen = globalMiddleware.length;
|
|
130
|
-
// Process each route with optimized handler creation
|
|
131
61
|
for (let i = 0; i < routeCount; i++) {
|
|
132
|
-
/**
|
|
133
|
-
* ================================================
|
|
134
|
-
* Pre-compute the required functionality start
|
|
135
|
-
* ================================================
|
|
136
|
-
*/
|
|
137
|
-
// Get the current route object
|
|
138
62
|
const route = apiRoutes[i];
|
|
139
|
-
// Destructure the route object
|
|
140
63
|
const { path, schema, middleware: routeMiddleware, handlers, } = route;
|
|
141
|
-
// Get length of route specific middleware
|
|
142
64
|
const routeMiddlewareLen = routeMiddleware?.length || 0;
|
|
143
|
-
// Check if schema exists
|
|
144
65
|
const hasSchema = !!schema;
|
|
145
|
-
// Optimize middleware array initialization by pre-allocating size
|
|
146
66
|
const totalMiddlewareCount = globalMiddlewareLen + (hasSchema ? 1 : 0) + routeMiddlewareLen;
|
|
147
|
-
// Create optimized route handler
|
|
148
67
|
if (totalMiddlewareCount === 0) {
|
|
149
|
-
// Ultra-fast path: no middleware
|
|
150
|
-
// Pre-compute wildcard segment count for faster extraction
|
|
151
68
|
const isWildcard = route.isWildcard;
|
|
152
|
-
// Calculate how many segments come before the wildcard
|
|
153
|
-
// E.g., "/api/users/:userId/*" has 3 segments before wildcard (api, users, :userId)
|
|
154
69
|
const baseSegmentCount = isWildcard
|
|
155
|
-
? path.split('/').filter(Boolean).length - 1
|
|
70
|
+
? path.split('/').filter(Boolean).length - 1
|
|
156
71
|
: 0;
|
|
157
72
|
routes[path] = (request) => {
|
|
158
|
-
// Extract wildcard params if this is a wildcard route
|
|
159
73
|
if (isWildcard) {
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
const url = request.url;
|
|
163
|
-
// Find where the path starts (after protocol and domain)
|
|
164
|
-
// Example: "http://localhost:4000/api/..." → protocolEnd = 4 (after "http")
|
|
165
|
-
const protocolEnd = url.indexOf('://');
|
|
166
|
-
// Find first "/" after the domain
|
|
167
|
-
// Example: "http://localhost:4000/api/..." → pathStart = 21 (the "/" before "api")
|
|
168
|
-
const pathStart = url.indexOf('/', protocolEnd + 3);
|
|
169
|
-
// Find where query parameters start (if any)
|
|
170
|
-
// Example: "/api/users/123?id=1" → pathEnd = 15 (at the "?")
|
|
171
|
-
const pathEnd = url.indexOf('?', pathStart);
|
|
172
|
-
// Extract just the pathname without query parameters
|
|
173
|
-
// Example: "/api/users/123/profile"
|
|
174
|
-
const pathname = pathEnd === -1
|
|
175
|
-
? url.substring(pathStart) // No query params
|
|
176
|
-
: url.substring(pathStart, pathEnd); // Has query params, stop at "?"
|
|
177
|
-
// Step 2: Extract wildcard segments efficiently
|
|
178
|
-
// Example route: "/api/users/:userId/*" has baseSegmentCount = 3
|
|
179
|
-
// - Segment 0: "api"
|
|
180
|
-
// - Segment 1: "users"
|
|
181
|
-
// - Segment 2: ":userId" (or "123" in actual URL)
|
|
182
|
-
// - Segment 3+: wildcard segments we want!
|
|
183
|
-
if (baseSegmentCount === 0) {
|
|
184
|
-
// Fast path: The entire path is wildcard
|
|
185
|
-
// Example: "/api/docs/*" where all segments after domain are wildcards
|
|
186
|
-
// Just split everything and we're done!
|
|
187
|
-
request.wildcardParams = pathname
|
|
188
|
-
.split('/')
|
|
189
|
-
.filter(Boolean);
|
|
190
|
-
}
|
|
191
|
-
else {
|
|
192
|
-
// Optimized path: Skip base segments and only collect wildcard segments
|
|
193
|
-
// Example: "/api/users/123/settings/privacy"
|
|
194
|
-
// - We need to skip 3 segments (api, users, 123)
|
|
195
|
-
// - Only collect: ["settings", "privacy"]
|
|
196
|
-
const wildcardParams = [];
|
|
197
|
-
let segmentCount = 0; // Counts how many segments we've seen
|
|
198
|
-
let start = pathname[0] === '/' ? 1 : 0; // Start after leading "/" if present
|
|
199
|
-
// Loop through each character in the pathname
|
|
200
|
-
// When we hit "/" or end of string, we know we found a segment
|
|
201
|
-
for (let i = start; i <= pathname.length; i++) {
|
|
202
|
-
// Found end of a segment (either "/" or end of string)
|
|
203
|
-
if (i === pathname.length ||
|
|
204
|
-
pathname[i] === '/') {
|
|
205
|
-
// Make sure it's not an empty segment (from double slashes)
|
|
206
|
-
if (i > start) {
|
|
207
|
-
// Only save segments AFTER we've skipped the base segments
|
|
208
|
-
// Example: If baseSegmentCount=3, save segment 3, 4, 5, etc.
|
|
209
|
-
if (segmentCount >= baseSegmentCount) {
|
|
210
|
-
// Extract this segment from the pathname
|
|
211
|
-
// Example: pathname.substring(5, 13) might give "settings"
|
|
212
|
-
wildcardParams.push(pathname.substring(start, i));
|
|
213
|
-
}
|
|
214
|
-
segmentCount++; // Increment count for next segment
|
|
215
|
-
}
|
|
216
|
-
start = i + 1; // Move start position to character after "/"
|
|
217
|
-
}
|
|
218
|
-
}
|
|
219
|
-
// Done! wildcardParams now contains only the wildcard segments
|
|
220
|
-
// Example: ["settings", "privacy"] instead of ["api", "users", "123", "settings", "privacy"]
|
|
221
|
-
request.wildcardParams = wildcardParams;
|
|
222
|
-
}
|
|
74
|
+
const pathname = extractPathnameFromUrl(request.url);
|
|
75
|
+
extractWildcardParams(request, pathname, baseSegmentCount);
|
|
223
76
|
}
|
|
224
77
|
const handler = handlers[request.method];
|
|
225
78
|
return handler ? handler(request) : this.METHOD_NOT_ALLOWED;
|
|
226
79
|
};
|
|
227
80
|
}
|
|
228
81
|
else {
|
|
229
|
-
// Pre-compute middleware array with known size
|
|
230
82
|
const middlewares = new Array(totalMiddlewareCount);
|
|
231
|
-
// Initialize index to track the current middleware
|
|
232
83
|
let index = 0;
|
|
233
|
-
// Copy global middleware (most common case)
|
|
234
84
|
for (let j = 0; j < globalMiddlewareLen; j++) {
|
|
235
85
|
middlewares[index++] = globalMiddleware[j];
|
|
236
86
|
}
|
|
237
|
-
// Add validation middleware if needed
|
|
238
87
|
if (hasSchema) {
|
|
239
88
|
middlewares[index++] = createValidationMiddleware(schema);
|
|
240
89
|
}
|
|
241
|
-
// Add route-specific middlewares
|
|
242
90
|
if (routeMiddleware) {
|
|
243
91
|
for (let j = 0; j < routeMiddlewareLen; j++) {
|
|
244
92
|
middlewares[index++] = routeMiddleware[j];
|
|
245
93
|
}
|
|
246
94
|
}
|
|
247
|
-
/**
|
|
248
|
-
* ================================================
|
|
249
|
-
* Pre-compute the required functionality end
|
|
250
|
-
* ================================================
|
|
251
|
-
*/
|
|
252
|
-
// Pre-compute wildcard segment count for faster extraction
|
|
253
95
|
const isWildcard = route.isWildcard;
|
|
254
|
-
// Calculate how many segments come before the wildcard
|
|
255
|
-
// E.g., "/api/users/:userId/*" has 3 segments before wildcard (api, users, :userId)
|
|
256
96
|
const baseSegmentCount = isWildcard
|
|
257
|
-
? path.split('/').filter(Boolean).length - 1
|
|
97
|
+
? path.split('/').filter(Boolean).length - 1
|
|
258
98
|
: 0;
|
|
259
|
-
// Create handler with middleware
|
|
260
99
|
routes[path] = (request) => {
|
|
261
|
-
// Extract wildcard params if this is a wildcard route
|
|
262
100
|
if (isWildcard) {
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
const url = request.url;
|
|
266
|
-
// Find where the path starts (after protocol and domain)
|
|
267
|
-
// Example: "http://localhost:4000/api/..." → protocolEnd = 4 (after "http")
|
|
268
|
-
const protocolEnd = url.indexOf('://');
|
|
269
|
-
// Find first "/" after the domain
|
|
270
|
-
// Example: "http://localhost:4000/api/..." → pathStart = 21 (the "/" before "api")
|
|
271
|
-
const pathStart = url.indexOf('/', protocolEnd + 3);
|
|
272
|
-
// Find where query parameters start (if any)
|
|
273
|
-
// Example: "/api/users/123?id=1" → pathEnd = 15 (at the "?")
|
|
274
|
-
const pathEnd = url.indexOf('?', pathStart);
|
|
275
|
-
// Extract just the pathname without query parameters
|
|
276
|
-
// Example: "/api/users/123/profile"
|
|
277
|
-
const pathname = pathEnd === -1
|
|
278
|
-
? url.substring(pathStart) // No query params
|
|
279
|
-
: url.substring(pathStart, pathEnd); // Has query params, stop at "?"
|
|
280
|
-
// Step 2: Extract wildcard segments efficiently
|
|
281
|
-
// Example route: "/api/users/:userId/*" has baseSegmentCount = 3
|
|
282
|
-
// - Segment 0: "api"
|
|
283
|
-
// - Segment 1: "users"
|
|
284
|
-
// - Segment 2: ":userId" (or "123" in actual URL)
|
|
285
|
-
// - Segment 3+: wildcard segments we want!
|
|
286
|
-
if (baseSegmentCount === 0) {
|
|
287
|
-
// Fast path: The entire path is wildcard
|
|
288
|
-
// Example: "/api/docs/*" where all segments after domain are wildcards
|
|
289
|
-
// Just split everything and we're done!
|
|
290
|
-
request.wildcardParams = pathname
|
|
291
|
-
.split('/')
|
|
292
|
-
.filter(Boolean);
|
|
293
|
-
}
|
|
294
|
-
else {
|
|
295
|
-
// Optimized path: Skip base segments and only collect wildcard segments
|
|
296
|
-
// Example: "/api/users/123/settings/privacy"
|
|
297
|
-
// - We need to skip 3 segments (api, users, 123)
|
|
298
|
-
// - Only collect: ["settings", "privacy"]
|
|
299
|
-
const wildcardParams = [];
|
|
300
|
-
let segmentCount = 0; // Counts how many segments we've seen
|
|
301
|
-
let start = pathname[0] === '/' ? 1 : 0; // Start after leading "/" if present
|
|
302
|
-
// Loop through each character in the pathname
|
|
303
|
-
// When we hit "/" or end of string, we know we found a segment
|
|
304
|
-
for (let i = start; i <= pathname.length; i++) {
|
|
305
|
-
// Found end of a segment (either "/" or end of string)
|
|
306
|
-
if (i === pathname.length ||
|
|
307
|
-
pathname[i] === '/') {
|
|
308
|
-
// Make sure it's not an empty segment (from double slashes)
|
|
309
|
-
if (i > start) {
|
|
310
|
-
// Only save segments AFTER we've skipped the base segments
|
|
311
|
-
// Example: If baseSegmentCount=3, save segment 3, 4, 5, etc.
|
|
312
|
-
if (segmentCount >= baseSegmentCount) {
|
|
313
|
-
// Extract this segment from the pathname
|
|
314
|
-
// Example: pathname.substring(5, 13) might give "settings"
|
|
315
|
-
wildcardParams.push(pathname.substring(start, i));
|
|
316
|
-
}
|
|
317
|
-
segmentCount++; // Increment count for next segment
|
|
318
|
-
}
|
|
319
|
-
start = i + 1; // Move start position to character after "/"
|
|
320
|
-
}
|
|
321
|
-
}
|
|
322
|
-
// Done! wildcardParams now contains only the wildcard segments
|
|
323
|
-
// Example: ["settings", "privacy"] instead of ["api", "users", "123", "settings", "privacy"]
|
|
324
|
-
request.wildcardParams = wildcardParams;
|
|
325
|
-
}
|
|
101
|
+
const pathname = extractPathnameFromUrl(request.url);
|
|
102
|
+
extractWildcardParams(request, pathname, baseSegmentCount);
|
|
326
103
|
}
|
|
327
104
|
const handler = handlers[request.method];
|
|
328
105
|
if (!handler)
|
|
@@ -330,129 +107,80 @@ export class Burger {
|
|
|
330
107
|
return this.processMiddleware(request, middlewares, handler);
|
|
331
108
|
};
|
|
332
109
|
}
|
|
333
|
-
// For wildcard routes, also register the base path
|
|
334
|
-
// Bun's /* wildcard may not match the base path itself, so we register both
|
|
335
110
|
if (route.isWildcard && path.endsWith('/*')) {
|
|
336
|
-
const basePath = path.slice(0, -2);
|
|
337
|
-
// Only register base path if no static route exists (preserve priority)
|
|
338
|
-
// Static routes have highest priority: Static > Dynamic > Wildcard
|
|
111
|
+
const basePath = path.slice(0, -2);
|
|
339
112
|
if (!routes[basePath]) {
|
|
340
|
-
// No static route found, register wildcard for base path
|
|
341
113
|
routes[basePath] = routes[path];
|
|
342
114
|
}
|
|
343
|
-
// If static route exists, it takes priority (correct behavior)
|
|
344
115
|
}
|
|
345
116
|
}
|
|
346
|
-
// Add special routes for OpenAPI
|
|
347
117
|
routes['/openapi.json'] = () => this.openApiDoc
|
|
348
118
|
? Response.json(this.openApiDoc)
|
|
349
119
|
: this.OPENAPI_ERROR;
|
|
350
|
-
// Add special route for Swagger UI
|
|
351
120
|
routes['/docs'] = () => new Response(swaggerHtml, {
|
|
352
121
|
headers: { 'Content-Type': 'text/html' },
|
|
353
122
|
});
|
|
354
123
|
return true;
|
|
355
124
|
}
|
|
356
|
-
/**
|
|
357
|
-
* Process the middleware and handler
|
|
358
|
-
* @param request - The request object
|
|
359
|
-
* @param middlewares - The middleware array
|
|
360
|
-
* @param handler - The handler function
|
|
361
|
-
* @returns A promise that resolves to a response
|
|
362
|
-
*/
|
|
363
125
|
async processMiddleware(request, middlewares, handler) {
|
|
364
|
-
// Get the length of the middleware array
|
|
365
126
|
const middlewareLen = middlewares.length;
|
|
366
|
-
// Fast path: single middleware with no after functions
|
|
367
127
|
if (middlewareLen === 1) {
|
|
368
|
-
// Get the first middleware
|
|
369
128
|
const result = await middlewares[0](request);
|
|
370
|
-
// If the result is a response, return it
|
|
371
129
|
if (result instanceof Response) {
|
|
372
130
|
return result;
|
|
373
131
|
}
|
|
374
|
-
// If the result is not a function, return the handler
|
|
375
132
|
if (typeof result !== 'function') {
|
|
376
133
|
return handler(request);
|
|
377
134
|
}
|
|
378
|
-
// If the result is a function, return the result of the handler
|
|
379
135
|
return result(await handler(request));
|
|
380
136
|
}
|
|
381
|
-
// Stack to store "after" functions
|
|
382
|
-
// Regular path with pre-allocated afterStack
|
|
383
137
|
const afterStack = new Array(middlewareLen);
|
|
384
|
-
// Initialize the after middleware counter
|
|
385
138
|
let afterCount = 0;
|
|
386
|
-
// Process "before" logic
|
|
387
139
|
for (let i = 0; i < middlewareLen; i++) {
|
|
388
|
-
// Get the current middleware
|
|
389
140
|
const result = await middlewares[i](request);
|
|
390
|
-
// If the result is a response
|
|
391
141
|
if (result instanceof Response) {
|
|
392
|
-
// Short-circuit with a response, but still run collected after middlewares (e.g., CORS)
|
|
393
142
|
let response = result;
|
|
394
|
-
// Fast paths for after functions
|
|
395
143
|
if (afterCount === 0) {
|
|
396
144
|
return response;
|
|
397
145
|
}
|
|
398
146
|
if (afterCount === 1) {
|
|
399
147
|
return afterStack[0](response);
|
|
400
148
|
}
|
|
401
|
-
// Apply after middlewares in reverse order (LIFO)
|
|
402
149
|
for (let j = afterCount - 1; j >= 0; j--) {
|
|
403
150
|
response = await afterStack[j](response);
|
|
404
151
|
}
|
|
405
152
|
return response;
|
|
406
153
|
}
|
|
407
|
-
// If the result is a function, save it to the afterStack
|
|
408
154
|
else if (typeof result === 'function') {
|
|
409
155
|
afterStack[afterCount++] = result;
|
|
410
156
|
}
|
|
411
|
-
// If undefined, proceed to next middleware
|
|
412
157
|
}
|
|
413
|
-
// Get response from handler
|
|
414
158
|
let response = await handler(request);
|
|
415
|
-
// Fast path: no after functions
|
|
416
159
|
if (afterCount === 0) {
|
|
417
160
|
return response;
|
|
418
161
|
}
|
|
419
|
-
// Fast path: single after function
|
|
420
162
|
if (afterCount === 1) {
|
|
421
163
|
return afterStack[0](response);
|
|
422
164
|
}
|
|
423
|
-
// Process "after" logic in reverse order
|
|
424
165
|
for (let i = afterCount - 1; i >= 0; i--) {
|
|
425
166
|
response = await afterStack[i](response);
|
|
426
167
|
}
|
|
427
|
-
// Return the response
|
|
428
168
|
return response;
|
|
429
169
|
}
|
|
430
|
-
/**
|
|
431
|
-
* Starts the server and begins listening for incoming requests.
|
|
432
|
-
* @param port - The port number to listen on. Defaults to `4000`.
|
|
433
|
-
* @param cb - An optional cb function to be executed when the server is listening.
|
|
434
|
-
* @returns A Promise that resolves when the server has started listening.
|
|
435
|
-
*/
|
|
436
170
|
async serve(port = 4000, cb) {
|
|
437
|
-
// Process routes in parallel if possible
|
|
438
171
|
const [pagesConfigured, apiConfigured] = await Promise.all([
|
|
439
172
|
this.processPageRoutes(),
|
|
440
173
|
this.processApiRoutes(),
|
|
441
174
|
]);
|
|
442
|
-
// Flag to track if any routes were loaded
|
|
443
175
|
const routesConfigured = pagesConfigured || apiConfigured;
|
|
444
|
-
// If routes were configured, start the server
|
|
445
176
|
if (routesConfigured) {
|
|
446
|
-
// Start the server
|
|
447
177
|
this.server.start(this.routes, async () => {
|
|
448
178
|
return this.NOT_FOUND;
|
|
449
179
|
}, port, cb);
|
|
450
180
|
}
|
|
451
181
|
else {
|
|
452
|
-
// If no routes were configured, log an error
|
|
453
182
|
console.error('Error: No routes configured! Please provide either apiDir with route.ts files or pageDir with html files when initializing the Burger Class.');
|
|
454
183
|
}
|
|
455
184
|
}
|
|
456
185
|
}
|
|
457
|
-
// Export utils
|
|
458
186
|
export { setDir } from './utils/index';
|
|
@@ -1,14 +1,2 @@
|
|
|
1
1
|
import type { RouteSchema, Middleware } from '../types/index';
|
|
2
|
-
/**
|
|
3
|
-
* createValidationMiddleware:
|
|
4
|
-
* - Precompute a smaller runtime descriptor per method to avoid
|
|
5
|
-
* repeatedly touching the full schema object on every request.
|
|
6
|
-
* - Uses safeParse (sync) for Zod schemas (no try/catch around safeParse).
|
|
7
|
-
* - Parses querystring manually (no URL constructor, no throw).
|
|
8
|
-
* - Lazily allocates the errors container only when needed.
|
|
9
|
-
* - Avoids unnecessary object allocations for successful paths.
|
|
10
|
-
*
|
|
11
|
-
* @param schema - The route schema to validate the request against.
|
|
12
|
-
* @returns The middleware function that validates the request.
|
|
13
|
-
*/
|
|
14
2
|
export declare function createValidationMiddleware(schema: RouteSchema): Middleware;
|
|
@@ -1,69 +1,29 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* createValidationMiddleware:
|
|
3
|
-
* - Precompute a smaller runtime descriptor per method to avoid
|
|
4
|
-
* repeatedly touching the full schema object on every request.
|
|
5
|
-
* - Uses safeParse (sync) for Zod schemas (no try/catch around safeParse).
|
|
6
|
-
* - Parses querystring manually (no URL constructor, no throw).
|
|
7
|
-
* - Lazily allocates the errors container only when needed.
|
|
8
|
-
* - Avoids unnecessary object allocations for successful paths.
|
|
9
|
-
*
|
|
10
|
-
* @param schema - The route schema to validate the request against.
|
|
11
|
-
* @returns The middleware function that validates the request.
|
|
12
|
-
*/
|
|
13
1
|
export function createValidationMiddleware(schema) {
|
|
14
|
-
// Precompute a minimal descriptor per HTTP method (lowercased)
|
|
15
|
-
// This work runs once at middleware creation time (fast startup cost, zero cost on each request for those computations).
|
|
16
2
|
const methodMap = {};
|
|
17
|
-
// Loop through the schema and create a method map
|
|
18
3
|
for (const rawMethod of Object.keys(schema)) {
|
|
19
|
-
// Convert the method to lowercase
|
|
20
4
|
const key = rawMethod.toLowerCase();
|
|
21
|
-
// Get the method schema
|
|
22
5
|
const m = schema[rawMethod] || {};
|
|
23
|
-
// Create a method map
|
|
24
6
|
methodMap[key] = {
|
|
25
|
-
paramsSchema: m.params,
|
|
26
|
-
querySchema: m.query,
|
|
27
|
-
bodySchema: m.body,
|
|
28
|
-
hasParams: !!m.params,
|
|
29
|
-
hasQuery: !!m.query,
|
|
30
|
-
hasBody: !!m.body,
|
|
7
|
+
paramsSchema: m.params,
|
|
8
|
+
querySchema: m.query,
|
|
9
|
+
bodySchema: m.body,
|
|
10
|
+
hasParams: !!m.params,
|
|
11
|
+
hasQuery: !!m.query,
|
|
12
|
+
hasBody: !!m.body,
|
|
31
13
|
};
|
|
32
14
|
}
|
|
33
|
-
/**
|
|
34
|
-
* The middleware function that validates the request.
|
|
35
|
-
*
|
|
36
|
-
* @param req - The request object.
|
|
37
|
-
* @returns The next middleware or handler.
|
|
38
|
-
*/
|
|
39
15
|
return async (req) => {
|
|
40
|
-
// If the request has been validated, continue.
|
|
41
16
|
if (req.validated) {
|
|
42
|
-
return undefined;
|
|
17
|
+
return undefined;
|
|
43
18
|
}
|
|
44
|
-
// Determine the HTTP method (in lowercase) to match the schema.
|
|
45
19
|
const method = (req.method || 'get').toLowerCase();
|
|
46
|
-
// Get the schema for the current method.
|
|
47
20
|
const methodSchema = methodMap[method];
|
|
48
|
-
// If there's no schema for this method, continue.
|
|
49
21
|
if (!methodSchema) {
|
|
50
|
-
return undefined;
|
|
22
|
+
return undefined;
|
|
51
23
|
}
|
|
52
|
-
// Get the schemas for the current method.
|
|
53
24
|
const { paramsSchema, querySchema, bodySchema, hasParams, hasQuery, hasBody, } = methodSchema;
|
|
54
|
-
/**
|
|
55
|
-
* Object to store validated request data. This will be attached to the
|
|
56
|
-
* request object if validation is successful. The object will contain
|
|
57
|
-
* validated data for the following fields:
|
|
58
|
-
*
|
|
59
|
-
* - `params`: Validated URL parameters (if available and schema provided).
|
|
60
|
-
* - `query`: Validated query parameters (if available and schema provided).
|
|
61
|
-
* - `body`: Validated request body (if JSON and schema provided).
|
|
62
|
-
*/
|
|
63
25
|
const validated = {};
|
|
64
|
-
// Lazy errors — create only if/when an error occurs
|
|
65
26
|
let errors = null;
|
|
66
|
-
// Validate URL parameters (if available and schema provided).
|
|
67
27
|
if (hasParams && req.params) {
|
|
68
28
|
const result = paramsSchema.safeParse(req.params);
|
|
69
29
|
if (result.success) {
|
|
@@ -75,7 +35,6 @@ export function createValidationMiddleware(schema) {
|
|
|
75
35
|
errors.params = result.error.issues;
|
|
76
36
|
}
|
|
77
37
|
}
|
|
78
|
-
// Validate query parameters if available and schema provided.
|
|
79
38
|
if (hasQuery) {
|
|
80
39
|
const url = new URL(req.url);
|
|
81
40
|
const queryParams = Object.fromEntries(url.searchParams.entries());
|
|
@@ -89,20 +48,15 @@ export function createValidationMiddleware(schema) {
|
|
|
89
48
|
errors.query = result.error.issues;
|
|
90
49
|
}
|
|
91
50
|
}
|
|
92
|
-
// Get the content type header
|
|
93
51
|
const contentType = req.headers.get('content-type') ??
|
|
94
52
|
req.headers.get('Content-Type') ??
|
|
95
53
|
'';
|
|
96
|
-
// Validate request body if it's JSON
|
|
97
54
|
if (hasBody && contentType?.includes('application/json')) {
|
|
98
55
|
try {
|
|
99
|
-
// Attempt to parse the JSON body.
|
|
100
56
|
const bodyData = await req.json();
|
|
101
57
|
const result = bodySchema.safeParse(bodyData);
|
|
102
58
|
if (result.success) {
|
|
103
|
-
// Set the validated body.
|
|
104
59
|
validated.body = result.data;
|
|
105
|
-
// Set the json method to return the validated body.
|
|
106
60
|
req.json = async () => result.data;
|
|
107
61
|
}
|
|
108
62
|
else {
|
|
@@ -112,7 +66,6 @@ export function createValidationMiddleware(schema) {
|
|
|
112
66
|
}
|
|
113
67
|
}
|
|
114
68
|
catch (error) {
|
|
115
|
-
// Create a message from the error.
|
|
116
69
|
const msg = error && typeof error.message === 'string'
|
|
117
70
|
? error.message
|
|
118
71
|
: String(error);
|
|
@@ -122,12 +75,9 @@ export function createValidationMiddleware(schema) {
|
|
|
122
75
|
}
|
|
123
76
|
}
|
|
124
77
|
if (errors) {
|
|
125
|
-
// If validation fails, return a 400 response with error details.
|
|
126
78
|
return Response.json({ errors }, { status: 400 });
|
|
127
79
|
}
|
|
128
|
-
// Attach validated data to the request.
|
|
129
80
|
req.validated = validated;
|
|
130
|
-
|
|
131
|
-
return undefined; // Proceed
|
|
81
|
+
return undefined;
|
|
132
82
|
};
|
|
133
83
|
}
|