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
|
@@ -2,51 +2,14 @@ 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
|
-
*/
|
|
9
5
|
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
|
-
*/
|
|
14
6
|
description?: string;
|
|
15
|
-
/**
|
|
16
|
-
* The directory path to load API routes from.
|
|
17
|
-
* If not specified, no API routes are loaded.
|
|
18
|
-
*/
|
|
19
7
|
apiDir?: string;
|
|
20
|
-
/**
|
|
21
|
-
* The prefix for the API routes.
|
|
22
|
-
* If not specified, the default prefix is 'api'.
|
|
23
|
-
*/
|
|
24
8
|
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
|
-
*/
|
|
30
9
|
pageDir?: string;
|
|
31
|
-
/**
|
|
32
|
-
* The prefix for the Page routes.
|
|
33
|
-
* If not specified, the default prefix is 'pages'.
|
|
34
|
-
*/
|
|
35
10
|
pagePrefix?: string;
|
|
36
|
-
/**
|
|
37
|
-
* Global middleware to be executed before each request.
|
|
38
|
-
*/
|
|
39
11
|
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
|
-
*/
|
|
44
12
|
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
|
-
*/
|
|
50
13
|
debug?: boolean;
|
|
51
14
|
}
|
|
52
15
|
type DefaultRequestProperties = {
|
|
@@ -55,119 +18,24 @@ type DefaultRequestProperties = {
|
|
|
55
18
|
body?: Record<string, unknown>;
|
|
56
19
|
};
|
|
57
20
|
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
|
-
*/
|
|
66
21
|
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
|
-
*/
|
|
78
22
|
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
|
-
*/
|
|
86
23
|
wildcardParams?: string[];
|
|
87
24
|
}
|
|
88
|
-
/**
|
|
89
|
-
* Represents what a middleware can return to control the request flow:
|
|
90
|
-
* - Response: Immediately send this response back to the client
|
|
91
|
-
* - Function: Continue processing, but transform the final response
|
|
92
|
-
* - undefined: Continue to the next middleware or handler
|
|
93
|
-
*/
|
|
94
25
|
export type BurgerNext = Response | ((response: Response) => Promise<Response>) | undefined;
|
|
95
|
-
/**
|
|
96
|
-
* A middleware function that processes HTTP requests before they reach the final handler.
|
|
97
|
-
*
|
|
98
|
-
* What middleware can do:
|
|
99
|
-
* - Change the request (add data, modify headers, etc.)
|
|
100
|
-
* - Check if the request is valid
|
|
101
|
-
* - Stop the request by returning a Response
|
|
102
|
-
* - Let the request continue by returning undefined
|
|
103
|
-
* - Transform the final response by returning a function
|
|
104
|
-
*
|
|
105
|
-
* @param request - The HTTP request with Burger framework enhancements
|
|
106
|
-
* @returns One of three things:
|
|
107
|
-
* - Response: Stop here, send this response back
|
|
108
|
-
* - Function: Continue processing, but transform the final response
|
|
109
|
-
* - undefined: I'm done, continue to the next step
|
|
110
|
-
*/
|
|
111
26
|
export type Middleware = ((request: BurgerRequest) => Promise<BurgerNext>) | ((request: BurgerRequest) => BurgerNext);
|
|
112
|
-
/**
|
|
113
|
-
* A request handler function that processes incoming HTTP requests.
|
|
114
|
-
* @param request - The BurgerRequest object containing request object.
|
|
115
|
-
* @returns A Response object or a Promise that resolves to a Response object.
|
|
116
|
-
*/
|
|
117
27
|
export type RequestHandler = (request: BurgerRequest) => Promise<Response> | Response;
|
|
118
|
-
/**
|
|
119
|
-
* A fetch handler function that can be used to handle a request.
|
|
120
|
-
* This can be a function that returns a Promise of a Response,
|
|
121
|
-
* or a function that returns a Response.
|
|
122
|
-
*/
|
|
123
28
|
export type FetchHandler = (request: Request, server?: Server) => Promise<Response> | Response;
|
|
124
29
|
export interface RouteDefinition {
|
|
125
|
-
/**
|
|
126
|
-
* The path of the route.
|
|
127
|
-
*/
|
|
128
30
|
path: string;
|
|
129
|
-
/**
|
|
130
|
-
* An object containing the request handlers for each HTTP method.
|
|
131
|
-
* The keys are the HTTP method names (e.g. "GET", "POST", etc.).
|
|
132
|
-
* The values are the request handlers for that method.
|
|
133
|
-
*/
|
|
134
31
|
handlers: {
|
|
135
32
|
[method: string]: RequestHandler;
|
|
136
33
|
};
|
|
137
|
-
/**
|
|
138
|
-
* An array of middleware functions to run before the request handler.
|
|
139
|
-
* The middleware functions will be run in the order they are specified.
|
|
140
|
-
*/
|
|
141
34
|
middleware?: Middleware[];
|
|
142
|
-
/**
|
|
143
|
-
* An optional route schema to validate the request data against.
|
|
144
|
-
* This property is set by the user when defining a route.
|
|
145
|
-
* The schema is used to validate the request data for each HTTP method.
|
|
146
|
-
* The keys are the HTTP method names (in lowercase) and the values are
|
|
147
|
-
* the Zod schema objects for that method.
|
|
148
|
-
*/
|
|
149
35
|
schema?: RouteSchema;
|
|
150
|
-
/**
|
|
151
|
-
* Optional OpenAPI metadata to generate documentation for the route.
|
|
152
|
-
* If provided, this property should define an object where each key
|
|
153
|
-
* is an HTTP method name (in lowercase), and the value is an object
|
|
154
|
-
* containing the OpenAPI metadata for that method.
|
|
155
|
-
*/
|
|
156
36
|
openapi?: openapi;
|
|
157
|
-
/**
|
|
158
|
-
* Indicates if this route is a wildcard route.
|
|
159
|
-
* True for routes using the `[...]` syntax.
|
|
160
|
-
* This property is used internally to identify wildcard routes.
|
|
161
|
-
*/
|
|
162
37
|
isWildcard?: boolean;
|
|
163
38
|
}
|
|
164
|
-
/**
|
|
165
|
-
* Define a type for the route schema.
|
|
166
|
-
* For each HTTP method (in lowercase), you can optionally define:
|
|
167
|
-
* - params: for URL parameters,
|
|
168
|
-
* - query: for query string parameters,
|
|
169
|
-
* - body: for the request body.
|
|
170
|
-
*/
|
|
171
39
|
export type RouteSchema = {
|
|
172
40
|
[method: string]: {
|
|
173
41
|
params?: z.ZodObject<any, any>;
|
|
@@ -175,17 +43,6 @@ export type RouteSchema = {
|
|
|
175
43
|
body?: z.ZodObject<any, any>;
|
|
176
44
|
};
|
|
177
45
|
};
|
|
178
|
-
/**
|
|
179
|
-
* Optional OpenAPI metadata to generate documentation for the route.
|
|
180
|
-
* Each key is an HTTP method name (in lowercase) and the value is an object
|
|
181
|
-
* containing the OpenAPI metadata for that method.
|
|
182
|
-
*
|
|
183
|
-
* If the `openapi` property is not defined, the route will not be included in
|
|
184
|
-
* the generated OpenAPI documentation.
|
|
185
|
-
*
|
|
186
|
-
* See the OpenAPI specification for the possible properties and their
|
|
187
|
-
* descriptions.
|
|
188
|
-
*/
|
|
189
46
|
export type openapi = {
|
|
190
47
|
[method: string]: {
|
|
191
48
|
summary?: string;
|
|
@@ -1,17 +1 @@
|
|
|
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
|
-
*/
|
|
17
1
|
export declare function errorResponse(error: any, req: Request, debug: boolean): Response;
|
package/dist/src/utils/error.js
CHANGED
|
@@ -1,56 +1,32 @@
|
|
|
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
|
-
*/
|
|
18
2
|
export function errorResponse(error, req, debug) {
|
|
19
|
-
// Extract request details
|
|
20
3
|
const method = req.method;
|
|
21
4
|
const url = req.url;
|
|
22
5
|
const logPrefix = `[${method} ${url}]`;
|
|
23
|
-
// Log detailed error context
|
|
24
6
|
console.error(`${logPrefix} Error:`, error);
|
|
25
7
|
const acceptHeader = req.headers.get('accept') || '';
|
|
26
8
|
if (acceptHeader.includes('text/html') && debug) {
|
|
27
9
|
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>
|
|
28
10
|
`;
|
|
29
|
-
// Return the html response
|
|
30
11
|
return new Response(body, {
|
|
31
12
|
status: 500,
|
|
32
13
|
headers: { 'Content-Type': 'text/html' },
|
|
33
14
|
});
|
|
34
15
|
}
|
|
35
16
|
else if (debug) {
|
|
36
|
-
// Log detailed error context
|
|
37
17
|
console.error(`${logPrefix} Error:`, error);
|
|
38
|
-
// Create a JSON response
|
|
39
18
|
const body = JSON.stringify({
|
|
40
19
|
request: `${method} ${url}`,
|
|
41
20
|
error: error instanceof Error ? error.message : 'Unknown error',
|
|
42
21
|
stack: error instanceof Error ? normalizePath(error.stack || '') : '',
|
|
43
22
|
});
|
|
44
|
-
// Return the JSON response
|
|
45
23
|
return new Response(body, {
|
|
46
24
|
status: 500,
|
|
47
25
|
headers: { 'Content-Type': 'application/json' },
|
|
48
26
|
});
|
|
49
27
|
}
|
|
50
28
|
else {
|
|
51
|
-
// Log detailed error context
|
|
52
29
|
console.error(`${logPrefix} Error:`, error);
|
|
53
|
-
// Return a plain text response
|
|
54
30
|
return new Response('Internal Server Error', { status: 500 });
|
|
55
31
|
}
|
|
56
32
|
}
|
|
@@ -1,21 +1,4 @@
|
|
|
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
|
-
*/
|
|
8
2
|
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
|
-
*/
|
|
14
3
|
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
|
-
*/
|
|
21
4
|
export declare function normalizePath(path: string): string;
|
package/dist/src/utils/index.js
CHANGED
|
@@ -1,41 +1,19 @@
|
|
|
1
1
|
import { resolve } from 'path';
|
|
2
|
-
// Export constants
|
|
3
2
|
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
|
-
*/
|
|
10
3
|
export function setDir(directory, path) {
|
|
11
4
|
return resolve(directory, path);
|
|
12
5
|
}
|
|
13
|
-
/**
|
|
14
|
-
* Removes leading and trailing slashes from the given prefix.
|
|
15
|
-
* @param prefix the prefix to clean
|
|
16
|
-
* @returns the cleaned prefix
|
|
17
|
-
*/
|
|
18
6
|
export function cleanPrefix(prefix) {
|
|
19
|
-
// Remove all slashes from the beginning
|
|
20
7
|
while (prefix.startsWith('/')) {
|
|
21
8
|
prefix = prefix.slice(1);
|
|
22
9
|
}
|
|
23
|
-
// Remove all slashes from the end
|
|
24
10
|
while (prefix.endsWith('/')) {
|
|
25
11
|
prefix = prefix.slice(0, -1);
|
|
26
12
|
}
|
|
27
13
|
return prefix;
|
|
28
14
|
}
|
|
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
|
-
*/
|
|
35
15
|
export function normalizePath(path) {
|
|
36
|
-
// Replace multiple slashes with a single slash
|
|
37
16
|
let normalized = path.replace(/\/+/g, '/');
|
|
38
|
-
// Remove trailing slash if it's not the root
|
|
39
17
|
if (normalized.length > 1 && normalized.endsWith('/')) {
|
|
40
18
|
normalized = normalized.slice(0, -1);
|
|
41
19
|
}
|
|
@@ -1,12 +1,3 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* The method not allowed response
|
|
3
|
-
*/
|
|
4
1
|
export declare const METHOD_NOT_ALLOWED: Response;
|
|
5
|
-
/**
|
|
6
|
-
* The not found response
|
|
7
|
-
*/
|
|
8
2
|
export declare const NOT_FOUND: Response;
|
|
9
|
-
/**
|
|
10
|
-
* The OpenAPI error response
|
|
11
|
-
*/
|
|
12
3
|
export declare const OPENAPI_ERROR: Response;
|
|
@@ -1,16 +1,7 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* The method not allowed response
|
|
3
|
-
*/
|
|
4
1
|
export const METHOD_NOT_ALLOWED = new Response('Method Not Allowed', {
|
|
5
2
|
status: 405,
|
|
6
3
|
});
|
|
7
|
-
/**
|
|
8
|
-
* The not found response
|
|
9
|
-
*/
|
|
10
4
|
export const NOT_FOUND = new Response('Not Found', { status: 404 });
|
|
11
|
-
/**
|
|
12
|
-
* The OpenAPI error response
|
|
13
|
-
*/
|
|
14
5
|
export const OPENAPI_ERROR = Response.json({
|
|
15
6
|
error: 'API Router not configured',
|
|
16
7
|
message: 'Please provide an apiDir option when initializing the Burger instance to enable OpenAPI documentation.',
|
|
@@ -1,7 +1,4 @@
|
|
|
1
1
|
import type { PageDefinition, RouteDefinition, TrieNode } from '../types/index';
|
|
2
|
-
/**
|
|
3
|
-
* Constants for route handling.
|
|
4
|
-
*/
|
|
5
2
|
export declare const ROUTE_CONSTANTS: {
|
|
6
3
|
SUPPORTED_PAGE_EXTENSIONS: string[];
|
|
7
4
|
PAGE_INDEX_FILES: string[];
|
|
@@ -14,32 +11,7 @@ export declare const ROUTE_CONSTANTS: {
|
|
|
14
11
|
WILDCARD_SIMPLE: string;
|
|
15
12
|
WILDCARD_START: string;
|
|
16
13
|
};
|
|
17
|
-
/**
|
|
18
|
-
* Supported HTTP methods
|
|
19
|
-
*/
|
|
20
14
|
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
|
-
*/
|
|
28
15
|
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
|
-
*/
|
|
37
16
|
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
|
-
*/
|
|
45
17
|
export declare function collectRoutes(node: TrieNode, currentPath?: string, routes?: RouteDefinition[]): RouteDefinition[];
|
|
@@ -1,26 +1,15 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Constants for route handling.
|
|
3
|
-
*/
|
|
4
1
|
export const ROUTE_CONSTANTS = {
|
|
5
|
-
// Supported page extensions
|
|
6
2
|
SUPPORTED_PAGE_EXTENSIONS: ['.tsx', '.html'],
|
|
7
|
-
// Page index files
|
|
8
3
|
PAGE_INDEX_FILES: ['index.tsx', 'index.html'],
|
|
9
|
-
// Dynamic route constants
|
|
10
4
|
DYNAMIC_SEGMENT_PREFIX: ':',
|
|
11
5
|
DYNAMIC_FOLDER_START: '[',
|
|
12
6
|
DYNAMIC_FOLDER_END: ']',
|
|
13
|
-
// Grouping folder constants
|
|
14
7
|
GROUPING_FOLDER_START: '(',
|
|
15
8
|
GROUPING_FOLDER_END: ')',
|
|
16
|
-
// Wildcard route constants
|
|
17
9
|
WILDCARD_SEGMENT_PREFIX: '*',
|
|
18
10
|
WILDCARD_SIMPLE: '[...]',
|
|
19
11
|
WILDCARD_START: '[...',
|
|
20
12
|
};
|
|
21
|
-
/**
|
|
22
|
-
* Supported HTTP methods
|
|
23
|
-
*/
|
|
24
13
|
export const HTTP_METHODS = [
|
|
25
14
|
'GET',
|
|
26
15
|
'POST',
|
|
@@ -30,32 +19,17 @@ export const HTTP_METHODS = [
|
|
|
30
19
|
'HEAD',
|
|
31
20
|
'OPTIONS',
|
|
32
21
|
];
|
|
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
|
-
*/
|
|
40
22
|
export const getRouteSpecificity = (path) => {
|
|
41
23
|
const segments = path.split('/').filter(Boolean);
|
|
42
24
|
return segments.reduce((score, segment) => {
|
|
43
25
|
if (segment.startsWith(ROUTE_CONSTANTS.WILDCARD_SEGMENT_PREFIX)) {
|
|
44
|
-
return score + 1000;
|
|
26
|
+
return score + 1000;
|
|
45
27
|
}
|
|
46
28
|
return segment.startsWith(ROUTE_CONSTANTS.DYNAMIC_SEGMENT_PREFIX)
|
|
47
|
-
? score + 100
|
|
48
|
-
: score + 1;
|
|
29
|
+
? score + 100
|
|
30
|
+
: score + 1;
|
|
49
31
|
}, 0);
|
|
50
32
|
};
|
|
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
|
-
*/
|
|
59
33
|
export const compareRoutes = (a, b) => {
|
|
60
34
|
const aSpecificity = getRouteSpecificity(a.path);
|
|
61
35
|
const bSpecificity = getRouteSpecificity(b.path);
|
|
@@ -65,33 +39,21 @@ export const compareRoutes = (a, b) => {
|
|
|
65
39
|
return 1;
|
|
66
40
|
return a.path.localeCompare(b.path);
|
|
67
41
|
};
|
|
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
|
-
*/
|
|
75
42
|
export function collectRoutes(node, currentPath = '', routes = []) {
|
|
76
|
-
// If this node has a route definition, add it
|
|
77
43
|
if (node.route) {
|
|
78
44
|
routes.push({
|
|
79
45
|
...node.route,
|
|
80
46
|
path: currentPath,
|
|
81
47
|
});
|
|
82
48
|
}
|
|
83
|
-
// Traverse static children
|
|
84
49
|
node.children.forEach((child, segment) => {
|
|
85
50
|
collectRoutes(child, `${currentPath}/${segment}`, routes);
|
|
86
51
|
});
|
|
87
|
-
// Traverse dynamic child if exists
|
|
88
52
|
if (node.paramChild) {
|
|
89
53
|
const paramPath = `${currentPath}/:${node.paramChild.paramName}`;
|
|
90
54
|
collectRoutes(node.paramChild, paramPath, routes);
|
|
91
55
|
}
|
|
92
|
-
// Traverse wildcard child if exists (lowest priority)
|
|
93
56
|
if (node.wildcardChild) {
|
|
94
|
-
// const wildcardPath = `${currentPath}/${node.wildcardChild.wildcardParamName}`;
|
|
95
57
|
const wildcardPath = `${currentPath}/${ROUTE_CONSTANTS.WILDCARD_SEGMENT_PREFIX}`;
|
|
96
58
|
collectRoutes(node.wildcardChild, wildcardPath, routes);
|
|
97
59
|
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
export function extractPathnameFromUrl(url) {
|
|
2
|
+
const protocolEnd = url.indexOf('://');
|
|
3
|
+
const pathStart = url.indexOf('/', protocolEnd + 3);
|
|
4
|
+
const pathEnd = url.indexOf('?', pathStart);
|
|
5
|
+
return pathEnd === -1
|
|
6
|
+
? url.substring(pathStart)
|
|
7
|
+
: url.substring(pathStart, pathEnd);
|
|
8
|
+
}
|
|
9
|
+
export function extractWildcardParams(request, pathname, baseSegmentCount) {
|
|
10
|
+
if (baseSegmentCount === 0) {
|
|
11
|
+
request.wildcardParams = pathname.split('/').filter(Boolean);
|
|
12
|
+
}
|
|
13
|
+
else {
|
|
14
|
+
const wildcardParams = [];
|
|
15
|
+
let segmentCount = 0;
|
|
16
|
+
let start = pathname[0] === '/' ? 1 : 0;
|
|
17
|
+
for (let i = start; i <= pathname.length; i++) {
|
|
18
|
+
if (i === pathname.length || pathname[i] === '/') {
|
|
19
|
+
if (i > start) {
|
|
20
|
+
if (segmentCount >= baseSegmentCount) {
|
|
21
|
+
wildcardParams.push(pathname.substring(start, i));
|
|
22
|
+
}
|
|
23
|
+
segmentCount++;
|
|
24
|
+
}
|
|
25
|
+
start = i + 1;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
request.wildcardParams = wildcardParams;
|
|
29
|
+
}
|
|
30
|
+
}
|