burger-api 0.5.1 → 0.6.0
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 +43 -16
- package/dist/src/core/api-router.d.ts +53 -0
- package/dist/src/core/api-router.js +93 -3
- package/dist/src/core/openapi.js +58 -1
- package/dist/src/core/page-router.d.ts +43 -0
- package/dist/src/core/page-router.js +72 -1
- package/dist/src/core/server.d.ts +10 -0
- package/dist/src/core/server.js +16 -0
- package/dist/src/index.d.ts +75 -0
- package/dist/src/index.js +264 -47
- package/dist/src/middleware/validator.d.ts +12 -0
- package/dist/src/middleware/validator.js +59 -9
- package/dist/src/types/index.d.ts +143 -1
- package/dist/src/utils/error.d.ts +16 -0
- package/dist/src/utils/error.js +24 -0
- package/dist/src/utils/index.d.ts +17 -0
- package/dist/src/utils/index.js +22 -0
- package/dist/src/utils/response.d.ts +9 -0
- package/dist/src/utils/response.js +9 -0
- package/dist/src/utils/routing.d.ts +28 -0
- package/dist/src/utils/routing.js +41 -3
- package/dist/src/utils/wildcard.d.ts +11 -0
- package/dist/src/utils/wildcard.js +42 -6
- package/package.json +1 -1
|
@@ -1,25 +1,47 @@
|
|
|
1
|
+
// Import stuff from node
|
|
1
2
|
import { readdirSync } from 'fs';
|
|
2
3
|
import * as path from 'path';
|
|
4
|
+
// Import utils
|
|
3
5
|
import { cleanPrefix, normalizePath, compareRoutes, ROUTE_CONSTANTS, } from '../utils/index';
|
|
6
|
+
/**
|
|
7
|
+
* PageRouter class for handling file-based page routing.
|
|
8
|
+
* Loads pages from a directory structure and matches requests to the appropriate page handlers.
|
|
9
|
+
* Supports dynamic segments (e.g., [id]) and uses default exports as page handlers.
|
|
10
|
+
*/
|
|
4
11
|
export class PageRouter {
|
|
5
12
|
pagesDir;
|
|
6
13
|
prefix;
|
|
14
|
+
/** Array of loaded page definitions */
|
|
7
15
|
pages = [];
|
|
16
|
+
/**
|
|
17
|
+
* Constructor for the PageRouter class.
|
|
18
|
+
* @param pagesDir The directory path where page modules are located.
|
|
19
|
+
* @param prefix Optional prefix to prepend to all routes (e.g., "pages" becomes "/pages/...").
|
|
20
|
+
*/
|
|
8
21
|
constructor(pagesDir, prefix = '') {
|
|
9
22
|
this.pagesDir = pagesDir;
|
|
10
23
|
this.prefix = prefix;
|
|
11
24
|
if (!pagesDir) {
|
|
12
25
|
throw new Error('Pages directory path must be provided');
|
|
13
26
|
}
|
|
27
|
+
// Normalize the pagesDir path
|
|
14
28
|
this.pagesDir = path.normalize(pagesDir);
|
|
29
|
+
// Normalize the prefix if provided
|
|
15
30
|
if (prefix) {
|
|
16
31
|
this.prefix = cleanPrefix(prefix);
|
|
17
32
|
}
|
|
18
33
|
}
|
|
34
|
+
/**
|
|
35
|
+
* Loads page modules from the specified directory and adds them to the pages array.
|
|
36
|
+
* After loading, sorts the pages to prioritize static routes over dynamic ones based on specificity.
|
|
37
|
+
* @returns A promise that resolves when all page modules have been loaded and sorted.
|
|
38
|
+
*/
|
|
19
39
|
async loadPages() {
|
|
40
|
+
// Clear the pages array
|
|
20
41
|
this.pages = [];
|
|
21
42
|
try {
|
|
22
43
|
await this.scanDirectory(this.pagesDir);
|
|
44
|
+
// Sort pages to ensure static routes are matched before dynamic ones
|
|
23
45
|
this.pages.sort((a, b) => compareRoutes(a, b));
|
|
24
46
|
}
|
|
25
47
|
catch (error) {
|
|
@@ -27,7 +49,13 @@ export class PageRouter {
|
|
|
27
49
|
throw new Error(`Failed to load pages: ${error instanceof Error ? error.message : String(error)}`);
|
|
28
50
|
}
|
|
29
51
|
}
|
|
52
|
+
/**
|
|
53
|
+
* Recursively scans the directory for page modules and adds them to the pages array.
|
|
54
|
+
* @param dir The current directory to scan.
|
|
55
|
+
* @param basePath The base path for constructing the route path.
|
|
56
|
+
*/
|
|
30
57
|
async scanDirectory(dir, basePath = '') {
|
|
58
|
+
// Track if a dynamic folder has been found at this directory level
|
|
31
59
|
let dynamicFolderFound = false;
|
|
32
60
|
try {
|
|
33
61
|
const entries = readdirSync(dir, { withFileTypes: true });
|
|
@@ -35,6 +63,7 @@ export class PageRouter {
|
|
|
35
63
|
const entryPath = path.join(dir, entry.name);
|
|
36
64
|
const relativePath = path.join(basePath, entry.name);
|
|
37
65
|
if (entry.isDirectory()) {
|
|
66
|
+
// Handle dynamic directories (e.g., [id])
|
|
38
67
|
if (entry.name.startsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_START) &&
|
|
39
68
|
entry.name.endsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_END)) {
|
|
40
69
|
if (dynamicFolderFound) {
|
|
@@ -46,25 +75,33 @@ export class PageRouter {
|
|
|
46
75
|
}
|
|
47
76
|
else if (entry.isFile() &&
|
|
48
77
|
ROUTE_CONSTANTS.SUPPORTED_PAGE_EXTENSIONS.some((ext) => entry.name.endsWith(ext))) {
|
|
78
|
+
// Convert file path to route path and load the module
|
|
49
79
|
const routePath = this.convertFilePathToRoute(relativePath);
|
|
80
|
+
// Clean the route path
|
|
50
81
|
const cleanedRoutePath = this.cleanRoutePath(routePath);
|
|
82
|
+
// Get the module path
|
|
51
83
|
const modulePath = path.resolve(entryPath);
|
|
52
84
|
try {
|
|
85
|
+
// Import the module
|
|
53
86
|
const pageModule = await import(modulePath);
|
|
87
|
+
// Get the default export as the page handler
|
|
54
88
|
if (entry.name.endsWith('.tsx') &&
|
|
55
89
|
typeof pageModule.default !== 'function') {
|
|
56
90
|
throw new Error(`Page at ${entryPath} must export a default function as its handler.`);
|
|
57
91
|
}
|
|
92
|
+
// Create page definition
|
|
58
93
|
const pageDefWithSlash = {
|
|
59
94
|
path: cleanedRoutePath + '/',
|
|
60
95
|
handler: pageModule.default,
|
|
61
96
|
middleware: pageModule.middleware,
|
|
62
97
|
};
|
|
98
|
+
// Create page definition
|
|
63
99
|
const pageDef = {
|
|
64
100
|
path: cleanedRoutePath,
|
|
65
101
|
handler: pageModule.default,
|
|
66
102
|
middleware: pageModule.middleware,
|
|
67
103
|
};
|
|
104
|
+
// Add the page definition to the pages array
|
|
68
105
|
this.pages.push(pageDefWithSlash, pageDef);
|
|
69
106
|
}
|
|
70
107
|
catch (importError) {
|
|
@@ -78,15 +115,24 @@ export class PageRouter {
|
|
|
78
115
|
throw error;
|
|
79
116
|
}
|
|
80
117
|
}
|
|
118
|
+
/**
|
|
119
|
+
* Converts a file path to a route path by processing dynamic segments,
|
|
120
|
+
* removing certain directory indicators, and applying a prefix if specified.
|
|
121
|
+
* @param filePath The file path to convert into a route path.
|
|
122
|
+
* @returns The converted route path string (before extension cleaning).
|
|
123
|
+
*/
|
|
81
124
|
convertFilePathToRoute(filePath) {
|
|
125
|
+
// Split path into segments
|
|
82
126
|
const segments = filePath.split(path.sep);
|
|
83
127
|
const resultSegments = [];
|
|
84
128
|
for (let segment of segments) {
|
|
85
129
|
if (!segment)
|
|
86
|
-
continue;
|
|
130
|
+
continue; // Skip empty segments
|
|
131
|
+
// Skip grouping segments (e.g., (group))
|
|
87
132
|
if (segment.startsWith(ROUTE_CONSTANTS.GROUPING_FOLDER_START) &&
|
|
88
133
|
segment.endsWith(ROUTE_CONSTANTS.GROUPING_FOLDER_END))
|
|
89
134
|
continue;
|
|
135
|
+
// Convert dynamic segments from [param] to :param
|
|
90
136
|
if (segment.startsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_START) &&
|
|
91
137
|
segment.endsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_END)) {
|
|
92
138
|
const param = segment.slice(1, -1);
|
|
@@ -96,24 +142,37 @@ export class PageRouter {
|
|
|
96
142
|
resultSegments.push(segment);
|
|
97
143
|
}
|
|
98
144
|
}
|
|
145
|
+
// Construct the route with leading slash
|
|
99
146
|
let route = '/' + resultSegments.join('/');
|
|
147
|
+
// Apply prefix if provided
|
|
100
148
|
if (this.prefix) {
|
|
101
149
|
const cleanPrefixStr = cleanPrefix(this.prefix);
|
|
102
150
|
route = '/' + cleanPrefixStr + route;
|
|
103
151
|
}
|
|
152
|
+
// Remove trailing slash unless it's the root
|
|
104
153
|
if (route !== '/' && route.endsWith('/')) {
|
|
105
154
|
route = route.slice(0, -1);
|
|
106
155
|
}
|
|
107
156
|
return route;
|
|
108
157
|
}
|
|
158
|
+
/**
|
|
159
|
+
* Cleans a route path by handling index files and removing extensions.
|
|
160
|
+
* @param routePath The route path to clean
|
|
161
|
+
* @returns The cleaned route path
|
|
162
|
+
*/
|
|
109
163
|
cleanRoutePath(routePath) {
|
|
164
|
+
// Break the route path into segments
|
|
110
165
|
const pathSegments = routePath.split('/');
|
|
166
|
+
// Get the last segment
|
|
111
167
|
if (pathSegments.length > 0) {
|
|
112
168
|
const lastSegment = pathSegments[pathSegments.length - 1];
|
|
169
|
+
// Check if the last segment is an index file
|
|
113
170
|
if (ROUTE_CONSTANTS.PAGE_INDEX_FILES.includes(lastSegment)) {
|
|
171
|
+
// Remove the last segment for index files
|
|
114
172
|
pathSegments.pop();
|
|
115
173
|
}
|
|
116
174
|
else {
|
|
175
|
+
// Remove file extension for non-index files
|
|
117
176
|
const extensionIndex = lastSegment.lastIndexOf('.');
|
|
118
177
|
if (extensionIndex > 0) {
|
|
119
178
|
pathSegments[pathSegments.length - 1] =
|
|
@@ -121,9 +180,15 @@ export class PageRouter {
|
|
|
121
180
|
}
|
|
122
181
|
}
|
|
123
182
|
}
|
|
183
|
+
// Join the segments back together
|
|
124
184
|
const finalPath = pathSegments.join('/') === '' ? '/' : pathSegments.join('/');
|
|
125
185
|
return finalPath;
|
|
126
186
|
}
|
|
187
|
+
/**
|
|
188
|
+
* Resolves the given request by finding a matching page and extracting dynamic parameters.
|
|
189
|
+
* @param request The request to resolve.
|
|
190
|
+
* @returns An object containing the matched page and parameters, or an empty params object if no match.
|
|
191
|
+
*/
|
|
127
192
|
resolve(request) {
|
|
128
193
|
const url = new URL(request.url);
|
|
129
194
|
const reqPath = normalizePath(url.pathname);
|
|
@@ -138,6 +203,12 @@ export class PageRouter {
|
|
|
138
203
|
console.debug(`No matching route found for path: ${reqPath}`);
|
|
139
204
|
return { params: {} };
|
|
140
205
|
}
|
|
206
|
+
/**
|
|
207
|
+
* Checks if the request path matches the page path, extracting dynamic parameters if matched.
|
|
208
|
+
* @param requestPath The request path to check.
|
|
209
|
+
* @param pagePath The page path to match against.
|
|
210
|
+
* @returns A record of dynamic parameters if matched, otherwise null.
|
|
211
|
+
*/
|
|
141
212
|
matchRoute(requestPath, pagePath) {
|
|
142
213
|
const reqSegments = requestPath.split('/').filter(Boolean);
|
|
143
214
|
const pageSegments = pagePath.split('/').filter(Boolean);
|
|
@@ -2,9 +2,19 @@ import type { ServerOptions, FetchHandler } from '../types/index';
|
|
|
2
2
|
export declare class Server {
|
|
3
3
|
private options;
|
|
4
4
|
private server;
|
|
5
|
+
/**
|
|
6
|
+
* Initializes a new instance of the Server class with the given options.
|
|
7
|
+
* @param options - Configuration options for the server.
|
|
8
|
+
*/
|
|
5
9
|
constructor(options: ServerOptions);
|
|
6
10
|
start(routes: {
|
|
7
11
|
[key: string]: any;
|
|
8
12
|
} | undefined, handler: FetchHandler, port: number, cb?: () => void): void;
|
|
13
|
+
/**
|
|
14
|
+
* Stops the server.
|
|
15
|
+
* If the server is currently running, this method will stop the server and
|
|
16
|
+
* log a message to the console indicating that the server has been stopped.
|
|
17
|
+
* If the server is not running, this method does nothing.
|
|
18
|
+
*/
|
|
9
19
|
stop(): void;
|
|
10
20
|
}
|
package/dist/src/core/server.js
CHANGED
|
@@ -1,22 +1,32 @@
|
|
|
1
|
+
// Import stuff from Bun
|
|
1
2
|
import { serve } from 'bun';
|
|
3
|
+
// Import stuff from utils
|
|
2
4
|
import { errorResponse } from '../utils/error';
|
|
3
5
|
export class Server {
|
|
4
6
|
options;
|
|
5
7
|
server = null;
|
|
8
|
+
/**
|
|
9
|
+
* Initializes a new instance of the Server class with the given options.
|
|
10
|
+
* @param options - Configuration options for the server.
|
|
11
|
+
*/
|
|
6
12
|
constructor(options) {
|
|
7
13
|
this.options = options;
|
|
8
14
|
}
|
|
9
15
|
start(routes, handler, port, cb) {
|
|
16
|
+
// Start Bun's native server using Bun.serve
|
|
10
17
|
this.server = serve({
|
|
11
18
|
routes,
|
|
19
|
+
// Bun's fetch handler
|
|
12
20
|
fetch: async (request) => {
|
|
13
21
|
try {
|
|
14
22
|
return await handler(request);
|
|
15
23
|
}
|
|
16
24
|
catch (error) {
|
|
25
|
+
// Return a custom error response
|
|
17
26
|
return errorResponse(error, request, this.options.debug ?? false);
|
|
18
27
|
}
|
|
19
28
|
},
|
|
29
|
+
// Global error handler
|
|
20
30
|
error(error) {
|
|
21
31
|
console.error(error);
|
|
22
32
|
return new Response(`Internal Server Error: ${error.message}`, {
|
|
@@ -35,6 +45,12 @@ export class Server {
|
|
|
35
45
|
console.log(`🍔 BurgerAPI is running at: http://${this.options.hostname || 'localhost'}:${port}`);
|
|
36
46
|
}
|
|
37
47
|
}
|
|
48
|
+
/**
|
|
49
|
+
* Stops the server.
|
|
50
|
+
* If the server is currently running, this method will stop the server and
|
|
51
|
+
* log a message to the console indicating that the server has been stopped.
|
|
52
|
+
* If the server is not running, this method does nothing.
|
|
53
|
+
*/
|
|
38
54
|
stop() {
|
|
39
55
|
if (this.server) {
|
|
40
56
|
this.server.stop();
|
package/dist/src/index.d.ts
CHANGED
|
@@ -1,19 +1,94 @@
|
|
|
1
1
|
import type { ServerOptions } from './types/index';
|
|
2
2
|
export declare class Burger {
|
|
3
3
|
private options;
|
|
4
|
+
/**
|
|
5
|
+
* The server instance
|
|
6
|
+
*/
|
|
4
7
|
private server;
|
|
8
|
+
/**
|
|
9
|
+
* The API router instance
|
|
10
|
+
*/
|
|
5
11
|
private apiRouter?;
|
|
12
|
+
/**
|
|
13
|
+
* The page router instance
|
|
14
|
+
*/
|
|
6
15
|
private pageRouter?;
|
|
16
|
+
/**
|
|
17
|
+
* The global middleware
|
|
18
|
+
*/
|
|
7
19
|
private globalMiddleware;
|
|
20
|
+
/**
|
|
21
|
+
* The OpenAPI document
|
|
22
|
+
*/
|
|
8
23
|
private openApiDoc;
|
|
24
|
+
/**
|
|
25
|
+
* The routes object
|
|
26
|
+
*/
|
|
9
27
|
private routes;
|
|
28
|
+
/**
|
|
29
|
+
* Pre-computed responses for reuse
|
|
30
|
+
*/
|
|
10
31
|
private readonly METHOD_NOT_ALLOWED;
|
|
32
|
+
/**
|
|
33
|
+
* The not found response
|
|
34
|
+
*/
|
|
11
35
|
private readonly NOT_FOUND;
|
|
36
|
+
/**
|
|
37
|
+
* The OpenAPI error response
|
|
38
|
+
*/
|
|
12
39
|
private readonly OPENAPI_ERROR;
|
|
40
|
+
/**
|
|
41
|
+
* Constructor for the Burger class.
|
|
42
|
+
* @param options - The options for the server and router.
|
|
43
|
+
* The options object should contain the following properties:
|
|
44
|
+
* - port: The port number to listen on.
|
|
45
|
+
* - apiDir: The directory path to load API routes from.
|
|
46
|
+
* - pageDir: The directory path to load page routes from.
|
|
47
|
+
* - middleware: An array of global middleware functions.
|
|
48
|
+
*/
|
|
13
49
|
constructor(options: ServerOptions);
|
|
50
|
+
/**
|
|
51
|
+
* Process the page routes and add them to the routes object
|
|
52
|
+
* @returns A promise that resolves to a boolean
|
|
53
|
+
*/
|
|
14
54
|
private processPageRoutes;
|
|
55
|
+
/**
|
|
56
|
+
* Process the API routes and add them to the routes object
|
|
57
|
+
* @returns A promise that resolves to a boolean
|
|
58
|
+
*/
|
|
15
59
|
private processApiRoutes;
|
|
60
|
+
/**
|
|
61
|
+
* Process single middleware
|
|
62
|
+
* @param request - The request object
|
|
63
|
+
* @param middleware - The middleware function
|
|
64
|
+
* @param handler - The handler function
|
|
65
|
+
* @returns A promise that resolves to a response
|
|
66
|
+
*/
|
|
67
|
+
private processSingleMiddleware;
|
|
68
|
+
/**
|
|
69
|
+
* Process middleware and handler
|
|
70
|
+
*
|
|
71
|
+
* How it works:
|
|
72
|
+
* 1. Run each middleware in order
|
|
73
|
+
* 2. If middleware returns Response → stop and send that response (but still apply "after" functions)
|
|
74
|
+
* 3. If middleware returns undefined → continue to next middleware
|
|
75
|
+
* 4. If middleware returns function → save it to transform the final response later
|
|
76
|
+
* 5. After all middlewares, run the handler
|
|
77
|
+
* 6. Apply all saved "after" functions to the response (in reverse order)
|
|
78
|
+
*
|
|
79
|
+
* Performance optimizations:
|
|
80
|
+
* - Pre-allocated array for "after" functions (avoids dynamic resizing)
|
|
81
|
+
* - Fast paths for 0, 1, and 2 middlewares (most common cases)
|
|
82
|
+
* - Manual loop unrolling for small counts
|
|
83
|
+
* - Minimal branching in hot path
|
|
84
|
+
*/
|
|
16
85
|
private processMiddleware;
|
|
86
|
+
/**
|
|
87
|
+
* Starts the server and begins listening for incoming requests.
|
|
88
|
+
* @param port - The port number to listen on. Defaults to `4000`.
|
|
89
|
+
* @param cb - An optional cb function to be executed when the server is listening.
|
|
90
|
+
* @returns A Promise that resolves when the server has started listening.
|
|
91
|
+
*/
|
|
17
92
|
serve(port?: number, cb?: () => void): Promise<void>;
|
|
18
93
|
}
|
|
19
94
|
export { setDir } from './utils/index';
|