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
|
@@ -2,14 +2,51 @@ import type { BunRequest, Server } from 'bun';
|
|
|
2
2
|
import type { ServeOptions as BunServerOptions } from 'bun';
|
|
3
3
|
import { z } from 'zod';
|
|
4
4
|
export interface ServerOptions extends Omit<BunServerOptions, 'fetch' | 'port' | 'reusePort' | 'ipv6Only' | 'unix' | 'error' | 'id' | 'development'> {
|
|
5
|
+
/**
|
|
6
|
+
* The title of the API. This is an optional property that can be used
|
|
7
|
+
* to specify a custom title for the API documentation.
|
|
8
|
+
*/
|
|
5
9
|
title?: string;
|
|
10
|
+
/**
|
|
11
|
+
* The description of the API. This is an optional property that can be used
|
|
12
|
+
* to provide a brief overview of the API.
|
|
13
|
+
*/
|
|
6
14
|
description?: string;
|
|
15
|
+
/**
|
|
16
|
+
* The directory path to load API routes from.
|
|
17
|
+
* If not specified, no API routes are loaded.
|
|
18
|
+
*/
|
|
7
19
|
apiDir?: string;
|
|
20
|
+
/**
|
|
21
|
+
* The prefix for the API routes.
|
|
22
|
+
* If not specified, the default prefix is 'api'.
|
|
23
|
+
*/
|
|
8
24
|
apiPrefix?: string;
|
|
25
|
+
/**
|
|
26
|
+
* The directory path to load Page routes from.
|
|
27
|
+
* If not specified, no Page routes are loaded.
|
|
28
|
+
* Page routes are not yet supported, but will be supported in the future.
|
|
29
|
+
*/
|
|
9
30
|
pageDir?: string;
|
|
31
|
+
/**
|
|
32
|
+
* The prefix for the Page routes.
|
|
33
|
+
* If not specified, the default prefix is 'pages'.
|
|
34
|
+
*/
|
|
10
35
|
pagePrefix?: string;
|
|
36
|
+
/**
|
|
37
|
+
* Global middleware to be executed before each request.
|
|
38
|
+
*/
|
|
11
39
|
globalMiddleware?: Middleware[];
|
|
40
|
+
/**
|
|
41
|
+
* The version of the API. This is an optional property that can be used
|
|
42
|
+
* to specify the version of the API.
|
|
43
|
+
*/
|
|
12
44
|
version?: string;
|
|
45
|
+
/**
|
|
46
|
+
* Enables or disables debug mode. This is an optional property
|
|
47
|
+
* that, when set to true, can be used to output additional debugging
|
|
48
|
+
* information to the console or logs to aid in development and troubleshooting.
|
|
49
|
+
*/
|
|
13
50
|
debug?: boolean;
|
|
14
51
|
}
|
|
15
52
|
type DefaultRequestProperties = {
|
|
@@ -18,24 +55,118 @@ type DefaultRequestProperties = {
|
|
|
18
55
|
body?: Record<string, unknown>;
|
|
19
56
|
};
|
|
20
57
|
export interface BurgerRequest<RequestValidatedProperties extends DefaultRequestProperties = DefaultRequestProperties> extends Omit<BunRequest<string>, 'params'> {
|
|
58
|
+
/**
|
|
59
|
+
* Contains URL parameters extracted from the request path.
|
|
60
|
+
* This property is only present if the request path matches a route
|
|
61
|
+
* with dynamic parameters.
|
|
62
|
+
*
|
|
63
|
+
* For example, if the route is `/users/:id`, and the request path is
|
|
64
|
+
* `/users/123`, then the `params` property will be `{ id: '123' }`.
|
|
65
|
+
*/
|
|
21
66
|
params?: Record<string, string>;
|
|
67
|
+
/**
|
|
68
|
+
* Contains validated data for the request.
|
|
69
|
+
* This is an optional property that will only be present if
|
|
70
|
+
* a middleware has validated the request data and attached the
|
|
71
|
+
* validated data to the request.
|
|
72
|
+
*
|
|
73
|
+
* Properties:
|
|
74
|
+
* - `params`: Validated URL parameters.
|
|
75
|
+
* - `query`: Validated query string parameters.
|
|
76
|
+
* - `body`: Validated request body (if JSON).
|
|
77
|
+
*/
|
|
22
78
|
validated: RequestValidatedProperties;
|
|
79
|
+
/**
|
|
80
|
+
* Contains the wildcard parameters.
|
|
81
|
+
* This is an optional property that will only be present if
|
|
82
|
+
* the request path matches a route with a wildcard parameter.
|
|
83
|
+
* For example, if the route is `/users/[...]`, and the request path is
|
|
84
|
+
* `/users/123/456`, then the `wildcardParams` property will be `['123', '456']`.
|
|
85
|
+
*/
|
|
23
86
|
wildcardParams?: string[];
|
|
24
87
|
}
|
|
88
|
+
/**
|
|
89
|
+
* Represents what a middleware can return to control the request flow:
|
|
90
|
+
* - Response: Stop here, send this response back to the client
|
|
91
|
+
* - Function(Response): Continue processing, but transform the final response after handler runs
|
|
92
|
+
* - undefined: I'm done, continue to the next middleware or handler
|
|
93
|
+
*/
|
|
25
94
|
export type BurgerNext = Response | ((response: Response) => Promise<Response>) | undefined;
|
|
95
|
+
/**
|
|
96
|
+
* A middleware function that processes HTTP requests.
|
|
97
|
+
*
|
|
98
|
+
* What middleware can do:
|
|
99
|
+
* - Check if the request is valid (auth, validation, etc.)
|
|
100
|
+
* - Stop the request by returning a Response
|
|
101
|
+
* - Let the request continue by returning undefined
|
|
102
|
+
* - Transform the final response by returning a function
|
|
103
|
+
*
|
|
104
|
+
* @param request - The HTTP request with Burger framework enhancements
|
|
105
|
+
* @returns One of three things:
|
|
106
|
+
* - Response: Stop here, send this response back
|
|
107
|
+
* - Function: Transform the final response after handler runs
|
|
108
|
+
* - undefined: Continue to the next middleware or handler
|
|
109
|
+
*/
|
|
26
110
|
export type Middleware = ((request: BurgerRequest) => Promise<BurgerNext>) | ((request: BurgerRequest) => BurgerNext);
|
|
111
|
+
/**
|
|
112
|
+
* A request handler function that processes incoming HTTP requests.
|
|
113
|
+
* @param request - The BurgerRequest object containing request object.
|
|
114
|
+
* @returns A Response object or a Promise that resolves to a Response object.
|
|
115
|
+
*/
|
|
27
116
|
export type RequestHandler = (request: BurgerRequest) => Promise<Response> | Response;
|
|
28
|
-
|
|
117
|
+
/**
|
|
118
|
+
* A fetch handler function that can be used to handle a request.
|
|
119
|
+
* This can be a function that returns a Promise of a Response,
|
|
120
|
+
* or a function that returns a Response.
|
|
121
|
+
*/
|
|
122
|
+
export type FetchHandler = (request: Request, server?: Server<{}>) => Promise<Response> | Response;
|
|
29
123
|
export interface RouteDefinition {
|
|
124
|
+
/**
|
|
125
|
+
* The path of the route.
|
|
126
|
+
*/
|
|
30
127
|
path: string;
|
|
128
|
+
/**
|
|
129
|
+
* An object containing the request handlers for each HTTP method.
|
|
130
|
+
* The keys are the HTTP method names (e.g. "GET", "POST", etc.).
|
|
131
|
+
* The values are the request handlers for that method.
|
|
132
|
+
*/
|
|
31
133
|
handlers: {
|
|
32
134
|
[method: string]: RequestHandler;
|
|
33
135
|
};
|
|
136
|
+
/**
|
|
137
|
+
* An array of middleware functions to run before the request handler.
|
|
138
|
+
* The middleware functions will be run in the order they are specified.
|
|
139
|
+
*/
|
|
34
140
|
middleware?: Middleware[];
|
|
141
|
+
/**
|
|
142
|
+
* An optional route schema to validate the request data against.
|
|
143
|
+
* This property is set by the user when defining a route.
|
|
144
|
+
* The schema is used to validate the request data for each HTTP method.
|
|
145
|
+
* The keys are the HTTP method names (in lowercase) and the values are
|
|
146
|
+
* the Zod schema objects for that method.
|
|
147
|
+
*/
|
|
35
148
|
schema?: RouteSchema;
|
|
149
|
+
/**
|
|
150
|
+
* Optional OpenAPI metadata to generate documentation for the route.
|
|
151
|
+
* If provided, this property should define an object where each key
|
|
152
|
+
* is an HTTP method name (in lowercase), and the value is an object
|
|
153
|
+
* containing the OpenAPI metadata for that method.
|
|
154
|
+
*/
|
|
36
155
|
openapi?: openapi;
|
|
156
|
+
/**
|
|
157
|
+
* Indicates if this route is a wildcard route.
|
|
158
|
+
* True for routes using the `[...]` syntax.
|
|
159
|
+
* This property is used internally to identify wildcard routes.
|
|
160
|
+
*/
|
|
37
161
|
isWildcard?: boolean;
|
|
38
162
|
}
|
|
163
|
+
/**
|
|
164
|
+
* Define a type for the route schema.
|
|
165
|
+
* For each HTTP method (in lowercase), you can optionally define:
|
|
166
|
+
* - params: for URL parameters,
|
|
167
|
+
* - query: for query string parameters,
|
|
168
|
+
* - body: for the request body.
|
|
169
|
+
*/
|
|
39
170
|
export type RouteSchema = {
|
|
40
171
|
[method: string]: {
|
|
41
172
|
params?: z.ZodObject<any, any>;
|
|
@@ -43,6 +174,17 @@ export type RouteSchema = {
|
|
|
43
174
|
body?: z.ZodObject<any, any>;
|
|
44
175
|
};
|
|
45
176
|
};
|
|
177
|
+
/**
|
|
178
|
+
* Optional OpenAPI metadata to generate documentation for the route.
|
|
179
|
+
* Each key is an HTTP method name (in lowercase) and the value is an object
|
|
180
|
+
* containing the OpenAPI metadata for that method.
|
|
181
|
+
*
|
|
182
|
+
* If the `openapi` property is not defined, the route will not be included in
|
|
183
|
+
* the generated OpenAPI documentation.
|
|
184
|
+
*
|
|
185
|
+
* See the OpenAPI specification for the possible properties and their
|
|
186
|
+
* descriptions.
|
|
187
|
+
*/
|
|
46
188
|
export type openapi = {
|
|
47
189
|
[method: string]: {
|
|
48
190
|
summary?: string;
|
|
@@ -1 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generates an HTTP error response based on the request's "Accept" header.
|
|
3
|
+
*
|
|
4
|
+
* If the "Accept" header includes "text/html" and debugging is enabled, it returns
|
|
5
|
+
* an HTML response with the error message and stack trace.
|
|
6
|
+
*
|
|
7
|
+
* If the "Accept" header includes "application/json" or debugging is enabled, it
|
|
8
|
+
* returns a JSON response with the error message and optionally the stack trace.
|
|
9
|
+
*
|
|
10
|
+
* Otherwise, it returns a plain text response indicating an internal server error.
|
|
11
|
+
*
|
|
12
|
+
* @param error - The error object or message to include in the response.
|
|
13
|
+
* @param req - The incoming HTTP request object.
|
|
14
|
+
* @param debug - A boolean indicating whether debugging information should be included.
|
|
15
|
+
* @returns A Response object with the appropriate error details and status code.
|
|
16
|
+
*/
|
|
1
17
|
export declare function errorResponse(error: any, req: Request, debug: boolean): Response;
|
package/dist/src/utils/error.js
CHANGED
|
@@ -1,32 +1,56 @@
|
|
|
1
1
|
import { normalizePath } from './index';
|
|
2
|
+
/**
|
|
3
|
+
* Generates an HTTP error response based on the request's "Accept" header.
|
|
4
|
+
*
|
|
5
|
+
* If the "Accept" header includes "text/html" and debugging is enabled, it returns
|
|
6
|
+
* an HTML response with the error message and stack trace.
|
|
7
|
+
*
|
|
8
|
+
* If the "Accept" header includes "application/json" or debugging is enabled, it
|
|
9
|
+
* returns a JSON response with the error message and optionally the stack trace.
|
|
10
|
+
*
|
|
11
|
+
* Otherwise, it returns a plain text response indicating an internal server error.
|
|
12
|
+
*
|
|
13
|
+
* @param error - The error object or message to include in the response.
|
|
14
|
+
* @param req - The incoming HTTP request object.
|
|
15
|
+
* @param debug - A boolean indicating whether debugging information should be included.
|
|
16
|
+
* @returns A Response object with the appropriate error details and status code.
|
|
17
|
+
*/
|
|
2
18
|
export function errorResponse(error, req, debug) {
|
|
19
|
+
// Extract request details
|
|
3
20
|
const method = req.method;
|
|
4
21
|
const url = req.url;
|
|
5
22
|
const logPrefix = `[${method} ${url}]`;
|
|
23
|
+
// Log detailed error context
|
|
6
24
|
console.error(`${logPrefix} Error:`, error);
|
|
7
25
|
const acceptHeader = req.headers.get('accept') || '';
|
|
8
26
|
if (acceptHeader.includes('text/html') && debug) {
|
|
9
27
|
const body = `<!doctype html><html lang="en"><meta charset="UTF-8"><title>Error Occurred - BurgerAPI</title><style>body{margin:0;padding:0;background-color:#f4f4f4;font-family:Nunito,sans-serif;color:#333}.whoops-container{width:80%;margin:5% auto;background:#fff;border-radius:8px;box-shadow:0 4px 12px rgba(0,0,0,.15);overflow:hidden}.whoops-header{background-color:#e74c3c;color:#fff;padding:20px;display:flex;align-items:center;justify-content:space-between}.whoops-header .title-container{display:flex;align-items:center}.whoops-header .title{font-size:1.5em;margin-left:10px}.whoops-header .debug-mode{font-weight:600;display:flex;align-items:center;padding:10px;background-color:#fff;color:#e74c3c;box-shadow:0 4px 12px rgba(0,0,0,.15);border-radius:8px}.whoops-header .debug-mode .fa-check-circle{color:#28a745;margin-right:5px;font-size:1.2em}.whoops-content{padding:2em}.tag{font-weight:600;color:#4a5568;background-color:#edf2f7;padding:8px 15px;border-radius:6px;display:inline-block;font-size:14px}.error-message{font-size:1.25em;line-height:1.6;margin-bottom:1.5em;color:#2d3748}h2{color:#e3342f;font-size:1.5em;margin-bottom:.8em;border-bottom:1px solid #edf2f7;padding-bottom:.5em}pre{background:#f9fafc;border-left:4px solid #e3342f;padding:1.5em;border-radius:4px;font-family:"Source Code Pro",Menlo,Monaco,Consolas,"Courier New",monospace;font-size:1em;line-height:1.6;overflow-x:auto;color:#4a5568}.footer{text-align:center;padding-top:25px;font-size:.9em;color:#718096;border-top:1px solid #edf2f7}.error-icon{font-size:2em}.request-info{display:flex;justify-content:space-between;align-items:center}</style><link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css"rel="stylesheet"><div class="whoops-container"><div class="whoops-header"><div class="title-container"><i class="fas error-icon fa-exclamation-triangle"></i><div class="title">Whoops! Something went wrong</div></div><div class="debug-mode"><i class="fas fa-check-circle"></i> Debug Mode Enabled</div></div><div class="whoops-content"><div class="request-info"><div><strong>Request:</strong> ${method} ${url}</div><div class="tag">${error.stack?.split('\n')[0].split(':')[0]}</div></div><p class="error-message">${error.message}<h2>Stack Trace</h2><pre>${error.stack || 'No stack trace available'}</pre><div class="footer">“It’s not a bug, it’s an undocumented feature.” — Anonymous</div></div></div>
|
|
10
28
|
`;
|
|
29
|
+
// Return the html response
|
|
11
30
|
return new Response(body, {
|
|
12
31
|
status: 500,
|
|
13
32
|
headers: { 'Content-Type': 'text/html' },
|
|
14
33
|
});
|
|
15
34
|
}
|
|
16
35
|
else if (debug) {
|
|
36
|
+
// Log detailed error context
|
|
17
37
|
console.error(`${logPrefix} Error:`, error);
|
|
38
|
+
// Create a JSON response
|
|
18
39
|
const body = JSON.stringify({
|
|
19
40
|
request: `${method} ${url}`,
|
|
20
41
|
error: error instanceof Error ? error.message : 'Unknown error',
|
|
21
42
|
stack: error instanceof Error ? normalizePath(error.stack || '') : '',
|
|
22
43
|
});
|
|
44
|
+
// Return the JSON response
|
|
23
45
|
return new Response(body, {
|
|
24
46
|
status: 500,
|
|
25
47
|
headers: { 'Content-Type': 'application/json' },
|
|
26
48
|
});
|
|
27
49
|
}
|
|
28
50
|
else {
|
|
51
|
+
// Log detailed error context
|
|
29
52
|
console.error(`${logPrefix} Error:`, error);
|
|
53
|
+
// Return a plain text response
|
|
30
54
|
return new Response('Internal Server Error', { status: 500 });
|
|
31
55
|
}
|
|
32
56
|
}
|
|
@@ -1,4 +1,21 @@
|
|
|
1
1
|
export { ROUTE_CONSTANTS, HTTP_METHODS, compareRoutes, getRouteSpecificity, collectRoutes, } from './routing';
|
|
2
|
+
/**
|
|
3
|
+
* Resolves the given path to the specified directory.
|
|
4
|
+
* @param directory the directory to resolve to
|
|
5
|
+
* @param path the path to resolve
|
|
6
|
+
* @returns the resolved path
|
|
7
|
+
*/
|
|
2
8
|
export declare function setDir(directory: string, path: string): string;
|
|
9
|
+
/**
|
|
10
|
+
* Removes leading and trailing slashes from the given prefix.
|
|
11
|
+
* @param prefix the prefix to clean
|
|
12
|
+
* @returns the cleaned prefix
|
|
13
|
+
*/
|
|
3
14
|
export declare function cleanPrefix(prefix: string): string;
|
|
15
|
+
/**
|
|
16
|
+
* Normalizes a file path by replacing multiple slashes with a single slash
|
|
17
|
+
* and removing any trailing slash, unless the path is the root.
|
|
18
|
+
* @param path The file path to normalize.
|
|
19
|
+
* @returns The normalized file path.
|
|
20
|
+
*/
|
|
4
21
|
export declare function normalizePath(path: string): string;
|
package/dist/src/utils/index.js
CHANGED
|
@@ -1,19 +1,41 @@
|
|
|
1
1
|
import { resolve } from 'path';
|
|
2
|
+
// Export constants
|
|
2
3
|
export { ROUTE_CONSTANTS, HTTP_METHODS, compareRoutes, getRouteSpecificity, collectRoutes, } from './routing';
|
|
4
|
+
/**
|
|
5
|
+
* Resolves the given path to the specified directory.
|
|
6
|
+
* @param directory the directory to resolve to
|
|
7
|
+
* @param path the path to resolve
|
|
8
|
+
* @returns the resolved path
|
|
9
|
+
*/
|
|
3
10
|
export function setDir(directory, path) {
|
|
4
11
|
return resolve(directory, path);
|
|
5
12
|
}
|
|
13
|
+
/**
|
|
14
|
+
* Removes leading and trailing slashes from the given prefix.
|
|
15
|
+
* @param prefix the prefix to clean
|
|
16
|
+
* @returns the cleaned prefix
|
|
17
|
+
*/
|
|
6
18
|
export function cleanPrefix(prefix) {
|
|
19
|
+
// Remove all slashes from the beginning
|
|
7
20
|
while (prefix.startsWith('/')) {
|
|
8
21
|
prefix = prefix.slice(1);
|
|
9
22
|
}
|
|
23
|
+
// Remove all slashes from the end
|
|
10
24
|
while (prefix.endsWith('/')) {
|
|
11
25
|
prefix = prefix.slice(0, -1);
|
|
12
26
|
}
|
|
13
27
|
return prefix;
|
|
14
28
|
}
|
|
29
|
+
/**
|
|
30
|
+
* Normalizes a file path by replacing multiple slashes with a single slash
|
|
31
|
+
* and removing any trailing slash, unless the path is the root.
|
|
32
|
+
* @param path The file path to normalize.
|
|
33
|
+
* @returns The normalized file path.
|
|
34
|
+
*/
|
|
15
35
|
export function normalizePath(path) {
|
|
36
|
+
// Replace multiple slashes with a single slash
|
|
16
37
|
let normalized = path.replace(/\/+/g, '/');
|
|
38
|
+
// Remove trailing slash if it's not the root
|
|
17
39
|
if (normalized.length > 1 && normalized.endsWith('/')) {
|
|
18
40
|
normalized = normalized.slice(0, -1);
|
|
19
41
|
}
|
|
@@ -1,3 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The method not allowed response
|
|
3
|
+
*/
|
|
1
4
|
export declare const METHOD_NOT_ALLOWED: Response;
|
|
5
|
+
/**
|
|
6
|
+
* The not found response
|
|
7
|
+
*/
|
|
2
8
|
export declare const NOT_FOUND: Response;
|
|
9
|
+
/**
|
|
10
|
+
* The OpenAPI error response
|
|
11
|
+
*/
|
|
3
12
|
export declare const OPENAPI_ERROR: Response;
|
|
@@ -1,7 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The method not allowed response
|
|
3
|
+
*/
|
|
1
4
|
export const METHOD_NOT_ALLOWED = new Response('Method Not Allowed', {
|
|
2
5
|
status: 405,
|
|
3
6
|
});
|
|
7
|
+
/**
|
|
8
|
+
* The not found response
|
|
9
|
+
*/
|
|
4
10
|
export const NOT_FOUND = new Response('Not Found', { status: 404 });
|
|
11
|
+
/**
|
|
12
|
+
* The OpenAPI error response
|
|
13
|
+
*/
|
|
5
14
|
export const OPENAPI_ERROR = Response.json({
|
|
6
15
|
error: 'API Router not configured',
|
|
7
16
|
message: 'Please provide an apiDir option when initializing the Burger instance to enable OpenAPI documentation.',
|
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
import type { PageDefinition, RouteDefinition, TrieNode } from '../types/index';
|
|
2
|
+
/**
|
|
3
|
+
* Constants for route handling.
|
|
4
|
+
*/
|
|
2
5
|
export declare const ROUTE_CONSTANTS: {
|
|
3
6
|
SUPPORTED_PAGE_EXTENSIONS: string[];
|
|
4
7
|
PAGE_INDEX_FILES: string[];
|
|
@@ -11,7 +14,32 @@ export declare const ROUTE_CONSTANTS: {
|
|
|
11
14
|
WILDCARD_SIMPLE: string;
|
|
12
15
|
WILDCARD_START: string;
|
|
13
16
|
};
|
|
17
|
+
/**
|
|
18
|
+
* Supported HTTP methods
|
|
19
|
+
*/
|
|
14
20
|
export declare const HTTP_METHODS: string[];
|
|
21
|
+
/**
|
|
22
|
+
* Calculates the specificity of a route path based on the number of static segments.
|
|
23
|
+
* Static segments increase the score, while dynamic segments (:param) do not.
|
|
24
|
+
* Wildcard segments (*) have the lowest specificity (highest penalty).
|
|
25
|
+
* @param path The route path to evaluate.
|
|
26
|
+
* @returns The specificity score (higher means more static segments, lower priority for wildcard).
|
|
27
|
+
*/
|
|
15
28
|
export declare const getRouteSpecificity: (path: string) => number;
|
|
29
|
+
/**
|
|
30
|
+
* Compares two routes for sorting, prioritizing those with higher specificity (more static segments).
|
|
31
|
+
* Route prioritization: Static > Dynamic > Wildcard.
|
|
32
|
+
* If specificity is equal, sorts alphabetically by path.
|
|
33
|
+
* @param a The first route to compare.
|
|
34
|
+
* @param b The second route to compare.
|
|
35
|
+
* @returns Negative if a comes before b, positive if b comes before a, zero if equal.
|
|
36
|
+
*/
|
|
16
37
|
export declare const compareRoutes: (a: PageDefinition | RouteDefinition, b: PageDefinition | RouteDefinition) => number;
|
|
38
|
+
/**
|
|
39
|
+
* Collects all routes from the trie and returns them as an array of RouteDefinition objects.
|
|
40
|
+
* @param node The current node in the trie.
|
|
41
|
+
* @param currentPath The current path being traversed.
|
|
42
|
+
* @param routes The array of collected routes.
|
|
43
|
+
* @returns An array of RouteDefinition objects.
|
|
44
|
+
*/
|
|
17
45
|
export declare function collectRoutes(node: TrieNode, currentPath?: string, routes?: RouteDefinition[]): RouteDefinition[];
|
|
@@ -1,15 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Constants for route handling.
|
|
3
|
+
*/
|
|
1
4
|
export const ROUTE_CONSTANTS = {
|
|
5
|
+
// Supported page extensions
|
|
2
6
|
SUPPORTED_PAGE_EXTENSIONS: ['.tsx', '.html'],
|
|
7
|
+
// Page index files
|
|
3
8
|
PAGE_INDEX_FILES: ['index.tsx', 'index.html'],
|
|
9
|
+
// Dynamic route constants
|
|
4
10
|
DYNAMIC_SEGMENT_PREFIX: ':',
|
|
5
11
|
DYNAMIC_FOLDER_START: '[',
|
|
6
12
|
DYNAMIC_FOLDER_END: ']',
|
|
13
|
+
// Grouping folder constants
|
|
7
14
|
GROUPING_FOLDER_START: '(',
|
|
8
15
|
GROUPING_FOLDER_END: ')',
|
|
16
|
+
// Wildcard route constants
|
|
9
17
|
WILDCARD_SEGMENT_PREFIX: '*',
|
|
10
18
|
WILDCARD_SIMPLE: '[...]',
|
|
11
19
|
WILDCARD_START: '[...',
|
|
12
20
|
};
|
|
21
|
+
/**
|
|
22
|
+
* Supported HTTP methods
|
|
23
|
+
*/
|
|
13
24
|
export const HTTP_METHODS = [
|
|
14
25
|
'GET',
|
|
15
26
|
'POST',
|
|
@@ -19,17 +30,32 @@ export const HTTP_METHODS = [
|
|
|
19
30
|
'HEAD',
|
|
20
31
|
'OPTIONS',
|
|
21
32
|
];
|
|
33
|
+
/**
|
|
34
|
+
* Calculates the specificity of a route path based on the number of static segments.
|
|
35
|
+
* Static segments increase the score, while dynamic segments (:param) do not.
|
|
36
|
+
* Wildcard segments (*) have the lowest specificity (highest penalty).
|
|
37
|
+
* @param path The route path to evaluate.
|
|
38
|
+
* @returns The specificity score (higher means more static segments, lower priority for wildcard).
|
|
39
|
+
*/
|
|
22
40
|
export const getRouteSpecificity = (path) => {
|
|
23
41
|
const segments = path.split('/').filter(Boolean);
|
|
24
42
|
return segments.reduce((score, segment) => {
|
|
25
43
|
if (segment.startsWith(ROUTE_CONSTANTS.WILDCARD_SEGMENT_PREFIX)) {
|
|
26
|
-
return score + 1000;
|
|
44
|
+
return score + 1000; // Wildcard routes get highest penalty (lowest priority)
|
|
27
45
|
}
|
|
28
46
|
return segment.startsWith(ROUTE_CONSTANTS.DYNAMIC_SEGMENT_PREFIX)
|
|
29
|
-
? score + 100
|
|
30
|
-
: score + 1;
|
|
47
|
+
? score + 100 // Dynamic routes get medium penalty
|
|
48
|
+
: score + 1; // Static routes get minimal penalty
|
|
31
49
|
}, 0);
|
|
32
50
|
};
|
|
51
|
+
/**
|
|
52
|
+
* Compares two routes for sorting, prioritizing those with higher specificity (more static segments).
|
|
53
|
+
* Route prioritization: Static > Dynamic > Wildcard.
|
|
54
|
+
* If specificity is equal, sorts alphabetically by path.
|
|
55
|
+
* @param a The first route to compare.
|
|
56
|
+
* @param b The second route to compare.
|
|
57
|
+
* @returns Negative if a comes before b, positive if b comes before a, zero if equal.
|
|
58
|
+
*/
|
|
33
59
|
export const compareRoutes = (a, b) => {
|
|
34
60
|
const aSpecificity = getRouteSpecificity(a.path);
|
|
35
61
|
const bSpecificity = getRouteSpecificity(b.path);
|
|
@@ -39,21 +65,33 @@ export const compareRoutes = (a, b) => {
|
|
|
39
65
|
return 1;
|
|
40
66
|
return a.path.localeCompare(b.path);
|
|
41
67
|
};
|
|
68
|
+
/**
|
|
69
|
+
* Collects all routes from the trie and returns them as an array of RouteDefinition objects.
|
|
70
|
+
* @param node The current node in the trie.
|
|
71
|
+
* @param currentPath The current path being traversed.
|
|
72
|
+
* @param routes The array of collected routes.
|
|
73
|
+
* @returns An array of RouteDefinition objects.
|
|
74
|
+
*/
|
|
42
75
|
export function collectRoutes(node, currentPath = '', routes = []) {
|
|
76
|
+
// If this node has a route definition, add it
|
|
43
77
|
if (node.route) {
|
|
44
78
|
routes.push({
|
|
45
79
|
...node.route,
|
|
46
80
|
path: currentPath,
|
|
47
81
|
});
|
|
48
82
|
}
|
|
83
|
+
// Traverse static children
|
|
49
84
|
node.children.forEach((child, segment) => {
|
|
50
85
|
collectRoutes(child, `${currentPath}/${segment}`, routes);
|
|
51
86
|
});
|
|
87
|
+
// Traverse dynamic child if exists
|
|
52
88
|
if (node.paramChild) {
|
|
53
89
|
const paramPath = `${currentPath}/:${node.paramChild.paramName}`;
|
|
54
90
|
collectRoutes(node.paramChild, paramPath, routes);
|
|
55
91
|
}
|
|
92
|
+
// Traverse wildcard child if exists (lowest priority)
|
|
56
93
|
if (node.wildcardChild) {
|
|
94
|
+
// const wildcardPath = `${currentPath}/${node.wildcardChild.wildcardParamName}`;
|
|
57
95
|
const wildcardPath = `${currentPath}/${ROUTE_CONSTANTS.WILDCARD_SEGMENT_PREFIX}`;
|
|
58
96
|
collectRoutes(node.wildcardChild, wildcardPath, routes);
|
|
59
97
|
}
|
|
@@ -1,3 +1,14 @@
|
|
|
1
1
|
import type { BurgerRequest } from '../types/index';
|
|
2
|
+
/**
|
|
3
|
+
* Extracts the pathname from a full URL string, removing query parameters.
|
|
4
|
+
* @param url - The full URL string (e.g., "http://localhost:4000/api/users/123/profile?id=1")
|
|
5
|
+
* @returns The extracted pathname (e.g., "/api/users/123/profile")
|
|
6
|
+
*/
|
|
2
7
|
export declare function extractPathnameFromUrl(url: string): string;
|
|
8
|
+
/**
|
|
9
|
+
* Extracts wildcard parameters from a request pathname and sets them on the request object.
|
|
10
|
+
* @param request - The request object to modify
|
|
11
|
+
* @param pathname - The pathname extracted from the URL (e.g., "/api/users/123/profile")
|
|
12
|
+
* @param baseSegmentCount - Number of segments before the wildcard (e.g., 3 for "/api/users/:userId/*")
|
|
13
|
+
*/
|
|
3
14
|
export declare function extractWildcardParams(request: BurgerRequest, pathname: string, baseSegmentCount: number): void;
|
|
@@ -1,30 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Extracts the pathname from a full URL string, removing query parameters.
|
|
3
|
+
* @param url - The full URL string (e.g., "http://localhost:4000/api/users/123/profile?id=1")
|
|
4
|
+
* @returns The extracted pathname (e.g., "/api/users/123/profile")
|
|
5
|
+
*/
|
|
1
6
|
export function extractPathnameFromUrl(url) {
|
|
7
|
+
// Find where the path starts (after protocol and domain)
|
|
8
|
+
// Example: "http://localhost:4000/api/..." → protocolEnd = 4 (after "http")
|
|
2
9
|
const protocolEnd = url.indexOf('://');
|
|
10
|
+
// Find first "/" after the domain
|
|
11
|
+
// Example: "http://localhost:4000/api/..." → pathStart = 21 (the "/" before "api")
|
|
3
12
|
const pathStart = url.indexOf('/', protocolEnd + 3);
|
|
13
|
+
// Find where query parameters start (if any)
|
|
14
|
+
// Example: "/api/users/123?id=1" → pathEnd = 15 (at the "?")
|
|
4
15
|
const pathEnd = url.indexOf('?', pathStart);
|
|
16
|
+
// Extract just the pathname without query parameters
|
|
17
|
+
// Example: "/api/users/123/profile"
|
|
5
18
|
return pathEnd === -1
|
|
6
|
-
? url.substring(pathStart)
|
|
7
|
-
: url.substring(pathStart, pathEnd);
|
|
19
|
+
? url.substring(pathStart) // No query params
|
|
20
|
+
: url.substring(pathStart, pathEnd); // Has query params, stop at "?"
|
|
8
21
|
}
|
|
22
|
+
/**
|
|
23
|
+
* Extracts wildcard parameters from a request pathname and sets them on the request object.
|
|
24
|
+
* @param request - The request object to modify
|
|
25
|
+
* @param pathname - The pathname extracted from the URL (e.g., "/api/users/123/profile")
|
|
26
|
+
* @param baseSegmentCount - Number of segments before the wildcard (e.g., 3 for "/api/users/:userId/*")
|
|
27
|
+
*/
|
|
9
28
|
export function extractWildcardParams(request, pathname, baseSegmentCount) {
|
|
10
29
|
if (baseSegmentCount === 0) {
|
|
30
|
+
// Fast path: The entire path is wildcard
|
|
31
|
+
// Example: "/api/docs/*" where all segments after domain are wildcards
|
|
32
|
+
// Just split everything and we're done!
|
|
11
33
|
request.wildcardParams = pathname.split('/').filter(Boolean);
|
|
12
34
|
}
|
|
13
35
|
else {
|
|
36
|
+
// Optimized path: Skip base segments and only collect wildcard segments
|
|
37
|
+
// Example: "/api/users/123/settings/privacy"
|
|
38
|
+
// - We need to skip 3 segments (api, users, 123)
|
|
39
|
+
// - Only collect: ["settings", "privacy"]
|
|
14
40
|
const wildcardParams = [];
|
|
15
|
-
let segmentCount = 0;
|
|
16
|
-
let start = pathname[0] === '/' ? 1 : 0;
|
|
41
|
+
let segmentCount = 0; // Counts how many segments we've seen
|
|
42
|
+
let start = pathname[0] === '/' ? 1 : 0; // Start after leading "/" if present
|
|
43
|
+
// Loop through each character in the pathname
|
|
44
|
+
// When we hit "/" or end of string, we know we found a segment
|
|
17
45
|
for (let i = start; i <= pathname.length; i++) {
|
|
46
|
+
// Found end of a segment (either "/" or end of string)
|
|
18
47
|
if (i === pathname.length || pathname[i] === '/') {
|
|
48
|
+
// Make sure it's not an empty segment (from double slashes)
|
|
19
49
|
if (i > start) {
|
|
50
|
+
// Only save segments AFTER we've skipped the base segments
|
|
51
|
+
// Example: If baseSegmentCount=3, save segment 3, 4, 5, etc.
|
|
20
52
|
if (segmentCount >= baseSegmentCount) {
|
|
53
|
+
// Extract this segment from the pathname
|
|
54
|
+
// Example: pathname.substring(5, 13) might give "settings"
|
|
21
55
|
wildcardParams.push(pathname.substring(start, i));
|
|
22
56
|
}
|
|
23
|
-
segmentCount++;
|
|
57
|
+
segmentCount++; // Increment count for next segment
|
|
24
58
|
}
|
|
25
|
-
start = i + 1;
|
|
59
|
+
start = i + 1; // Move start position to character after "/"
|
|
26
60
|
}
|
|
27
61
|
}
|
|
62
|
+
// Done! wildcardParams now contains only the wildcard segments
|
|
63
|
+
// Example: ["settings", "privacy"] instead of ["api", "users", "123", "settings", "privacy"]
|
|
28
64
|
request.wildcardParams = wildcardParams;
|
|
29
65
|
}
|
|
30
66
|
}
|