burger-api 0.1.0 → 0.2.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 +58 -465
- package/dist/src/core/api-router.d.ts +37 -29
- package/dist/src/core/api-router.js +96 -76
- package/dist/src/core/openapi.d.ts +2 -9
- package/dist/src/core/openapi.js +21 -27
- package/dist/src/core/page-router.d.ts +1 -1
- package/dist/src/core/page-router.js +20 -19
- package/dist/src/core/response.js +6 -6
- package/dist/src/core/server.d.ts +4 -9
- package/dist/src/core/server.js +18 -20
- package/dist/src/index.d.ts +51 -6
- package/dist/src/index.js +246 -112
- package/dist/src/middleware/validator.d.ts +1 -10
- package/dist/src/middleware/validator.js +60 -40
- package/dist/src/utils/error.js +9 -9
- package/dist/src/utils/index.d.ts +1 -1
- package/dist/src/utils/index.js +6 -6
- package/dist/src/utils/response.d.ts +12 -0
- package/dist/src/utils/response.js +17 -0
- package/dist/src/utils/routing.d.ts +9 -1
- package/dist/src/utils/routing.js +41 -15
- package/package.json +7 -6
- package/dist/src/types/index.d.ts +0 -251
- package/dist/src/types/index.js +0 -1
|
@@ -1,17 +1,8 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Creates a middleware function that validates request data according to the
|
|
3
|
-
* given schema for the current HTTP method.
|
|
4
|
-
*
|
|
5
|
-
* @param schema - The route schema to validate against.
|
|
6
|
-
* @returns A middleware function that validates request data and attaches the
|
|
7
|
-
* validated data to the request if successful, or returns a 400 response with
|
|
8
|
-
* error details if validation fails.
|
|
9
|
-
*/
|
|
10
1
|
export function createValidationMiddleware(schema) {
|
|
11
|
-
return async (req
|
|
2
|
+
return async (req) => {
|
|
12
3
|
// If the request has been validated, continue.
|
|
13
4
|
if (req.validated) {
|
|
14
|
-
return
|
|
5
|
+
return undefined; // Proceed to the next middleware or handler
|
|
15
6
|
}
|
|
16
7
|
// Determine the HTTP method (in lowercase) to match the schema.
|
|
17
8
|
const method = req.method.toLowerCase();
|
|
@@ -19,14 +10,19 @@ export function createValidationMiddleware(schema) {
|
|
|
19
10
|
const methodSchema = schema[method];
|
|
20
11
|
// If there's no schema for this method, continue.
|
|
21
12
|
if (!methodSchema) {
|
|
22
|
-
return
|
|
13
|
+
return undefined; // Proceed to the next middleware or handler
|
|
23
14
|
}
|
|
15
|
+
// Get the schemas for the current method.
|
|
16
|
+
const paramsSchema = methodSchema.params;
|
|
17
|
+
const querySchema = methodSchema.query;
|
|
18
|
+
const bodySchema = methodSchema.body;
|
|
24
19
|
/**
|
|
25
20
|
* Array to collect validation errors.
|
|
26
21
|
* Each error contains a `field` indicating the part of the request that failed validation,
|
|
27
22
|
* and an `error` providing details about the validation failure.
|
|
28
23
|
*/
|
|
29
|
-
const errors =
|
|
24
|
+
const errors = new Array(3); // Pre-allocate for params, query, body
|
|
25
|
+
let errorCount = 0;
|
|
30
26
|
/**
|
|
31
27
|
* Object to store validated request data. This will be attached to the
|
|
32
28
|
* request object if validation is successful. The object will contain
|
|
@@ -38,53 +34,77 @@ export function createValidationMiddleware(schema) {
|
|
|
38
34
|
*/
|
|
39
35
|
const validated = {};
|
|
40
36
|
// Validate URL parameters (if available and schema provided).
|
|
41
|
-
|
|
42
|
-
if (methodSchema.params && req.params) {
|
|
37
|
+
if (paramsSchema && req.params) {
|
|
43
38
|
try {
|
|
44
|
-
|
|
39
|
+
const result = paramsSchema.safeParse(req.params);
|
|
40
|
+
if (result.success) {
|
|
41
|
+
validated.params = result.data;
|
|
42
|
+
}
|
|
43
|
+
else {
|
|
44
|
+
errors[errorCount++] = {
|
|
45
|
+
field: 'params',
|
|
46
|
+
error: result.error,
|
|
47
|
+
};
|
|
48
|
+
}
|
|
45
49
|
}
|
|
46
50
|
catch (e) {
|
|
47
|
-
errors
|
|
51
|
+
errors[errorCount++] = { field: 'params', error: e.errors };
|
|
48
52
|
}
|
|
49
53
|
}
|
|
50
54
|
// Validate query parameters.
|
|
51
|
-
|
|
55
|
+
const url = new URL(req.url);
|
|
56
|
+
const queryParams = Object.fromEntries(url.searchParams.entries());
|
|
57
|
+
if (querySchema) {
|
|
52
58
|
try {
|
|
53
|
-
|
|
59
|
+
const result = querySchema.safeParse(queryParams);
|
|
60
|
+
if (result.success) {
|
|
61
|
+
validated.query = result.data;
|
|
62
|
+
}
|
|
63
|
+
else {
|
|
64
|
+
errors[errorCount++] = {
|
|
65
|
+
field: 'query',
|
|
66
|
+
error: result.error,
|
|
67
|
+
};
|
|
68
|
+
}
|
|
54
69
|
}
|
|
55
70
|
catch (e) {
|
|
56
|
-
errors
|
|
71
|
+
errors[errorCount++] = { field: 'query', error: e.errors };
|
|
57
72
|
}
|
|
58
73
|
}
|
|
59
74
|
// Validate request body.
|
|
60
|
-
if (
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
try {
|
|
72
|
-
// Attempt to parse the JSON body.
|
|
73
|
-
const bodyData = await req.json();
|
|
74
|
-
validated.body = methodSchema.body.parse(bodyData);
|
|
75
|
+
if (bodySchema &&
|
|
76
|
+
req.headers.get('Content-Type')?.includes('application/json')) {
|
|
77
|
+
try {
|
|
78
|
+
// Attempt to parse the JSON body.
|
|
79
|
+
const bodyData = await req.json();
|
|
80
|
+
const result = bodySchema.safeParse(bodyData);
|
|
81
|
+
if (result.success) {
|
|
82
|
+
// Set the validated body.
|
|
83
|
+
validated.body = result.data;
|
|
84
|
+
// Set the json method to return the validated body.
|
|
85
|
+
req.json = () => result.data;
|
|
75
86
|
}
|
|
76
|
-
|
|
77
|
-
errors
|
|
87
|
+
else {
|
|
88
|
+
errors[errorCount++] = {
|
|
89
|
+
field: 'body',
|
|
90
|
+
error: result.error,
|
|
91
|
+
};
|
|
78
92
|
}
|
|
79
93
|
}
|
|
94
|
+
catch (e) {
|
|
95
|
+
errors[errorCount++] = {
|
|
96
|
+
field: 'body',
|
|
97
|
+
error: e.errors || e.message,
|
|
98
|
+
};
|
|
99
|
+
}
|
|
80
100
|
}
|
|
81
|
-
if (
|
|
101
|
+
if (errorCount > 0) {
|
|
82
102
|
// If validation fails, return a 400 response with error details.
|
|
83
|
-
return
|
|
103
|
+
return Response.json({ errors }, { status: 400 });
|
|
84
104
|
}
|
|
85
105
|
// Attach validated data to the request.
|
|
86
106
|
req.validated = validated;
|
|
87
107
|
// Continue to the next middleware or handler.
|
|
88
|
-
return
|
|
108
|
+
return undefined; // Proceed
|
|
89
109
|
};
|
|
90
110
|
}
|
package/dist/src/utils/error.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { normalizePath } from
|
|
1
|
+
import { normalizePath } from './index.js';
|
|
2
2
|
/**
|
|
3
3
|
* Generates an HTTP error response based on the request's "Accept" header.
|
|
4
4
|
*
|
|
@@ -22,14 +22,14 @@ export function errorResponse(error, req, debug) {
|
|
|
22
22
|
const logPrefix = `[${method} ${url}]`;
|
|
23
23
|
// Log detailed error context
|
|
24
24
|
console.error(`${logPrefix} Error:`, error);
|
|
25
|
-
const acceptHeader = req.headers.get(
|
|
26
|
-
if (acceptHeader.includes(
|
|
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(
|
|
25
|
+
const acceptHeader = req.headers.get('accept') || '';
|
|
26
|
+
if (acceptHeader.includes('text/html') && debug) {
|
|
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>
|
|
28
28
|
`;
|
|
29
29
|
// Return the html response
|
|
30
30
|
return new Response(body, {
|
|
31
31
|
status: 500,
|
|
32
|
-
headers: {
|
|
32
|
+
headers: { 'Content-Type': 'text/html' },
|
|
33
33
|
});
|
|
34
34
|
}
|
|
35
35
|
else if (debug) {
|
|
@@ -38,19 +38,19 @@ export function errorResponse(error, req, debug) {
|
|
|
38
38
|
// Create a JSON response
|
|
39
39
|
const body = JSON.stringify({
|
|
40
40
|
request: `${method} ${url}`,
|
|
41
|
-
error: error instanceof Error ? error.message :
|
|
42
|
-
stack: error instanceof Error ? normalizePath(error.stack ||
|
|
41
|
+
error: error instanceof Error ? error.message : 'Unknown error',
|
|
42
|
+
stack: error instanceof Error ? normalizePath(error.stack || '') : '',
|
|
43
43
|
});
|
|
44
44
|
// Return the JSON response
|
|
45
45
|
return new Response(body, {
|
|
46
46
|
status: 500,
|
|
47
|
-
headers: {
|
|
47
|
+
headers: { 'Content-Type': 'application/json' },
|
|
48
48
|
});
|
|
49
49
|
}
|
|
50
50
|
else {
|
|
51
51
|
// Log detailed error context
|
|
52
52
|
console.error(`${logPrefix} Error:`, error);
|
|
53
53
|
// Return a plain text response
|
|
54
|
-
return new Response(
|
|
54
|
+
return new Response('Internal Server Error', { status: 500 });
|
|
55
55
|
}
|
|
56
56
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { ROUTE_CONSTANTS, HTTP_METHODS, compareRoutes, getRouteSpecificity, } from
|
|
1
|
+
export { ROUTE_CONSTANTS, HTTP_METHODS, compareRoutes, getRouteSpecificity, collectRoutes, } from './routing.js';
|
|
2
2
|
/**
|
|
3
3
|
* Resolves the given path to the specified directory.
|
|
4
4
|
* @param directory the directory to resolve to
|
package/dist/src/utils/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { resolve } from
|
|
1
|
+
import { resolve } from 'path';
|
|
2
2
|
// Export constants
|
|
3
|
-
export { ROUTE_CONSTANTS, HTTP_METHODS, compareRoutes, getRouteSpecificity, } from
|
|
3
|
+
export { ROUTE_CONSTANTS, HTTP_METHODS, compareRoutes, getRouteSpecificity, collectRoutes, } from './routing.js';
|
|
4
4
|
/**
|
|
5
5
|
* Resolves the given path to the specified directory.
|
|
6
6
|
* @param directory the directory to resolve to
|
|
@@ -17,11 +17,11 @@ export function setDir(directory, path) {
|
|
|
17
17
|
*/
|
|
18
18
|
export function cleanPrefix(prefix) {
|
|
19
19
|
// Remove all slashes from the beginning
|
|
20
|
-
while (prefix.startsWith(
|
|
20
|
+
while (prefix.startsWith('/')) {
|
|
21
21
|
prefix = prefix.slice(1);
|
|
22
22
|
}
|
|
23
23
|
// Remove all slashes from the end
|
|
24
|
-
while (prefix.endsWith(
|
|
24
|
+
while (prefix.endsWith('/')) {
|
|
25
25
|
prefix = prefix.slice(0, -1);
|
|
26
26
|
}
|
|
27
27
|
return prefix;
|
|
@@ -34,9 +34,9 @@ export function cleanPrefix(prefix) {
|
|
|
34
34
|
*/
|
|
35
35
|
export function normalizePath(path) {
|
|
36
36
|
// Replace multiple slashes with a single slash
|
|
37
|
-
let normalized = path.replace(/\/+/g,
|
|
37
|
+
let normalized = path.replace(/\/+/g, '/');
|
|
38
38
|
// Remove trailing slash if it's not the root
|
|
39
|
-
if (normalized.length > 1 && normalized.endsWith(
|
|
39
|
+
if (normalized.length > 1 && normalized.endsWith('/')) {
|
|
40
40
|
normalized = normalized.slice(0, -1);
|
|
41
41
|
}
|
|
42
42
|
return normalized;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The method not allowed response
|
|
3
|
+
*/
|
|
4
|
+
export declare const METHOD_NOT_ALLOWED: Response;
|
|
5
|
+
/**
|
|
6
|
+
* The not found response
|
|
7
|
+
*/
|
|
8
|
+
export declare const NOT_FOUND: Response;
|
|
9
|
+
/**
|
|
10
|
+
* The OpenAPI error response
|
|
11
|
+
*/
|
|
12
|
+
export declare const OPENAPI_ERROR: Response;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The method not allowed response
|
|
3
|
+
*/
|
|
4
|
+
export const METHOD_NOT_ALLOWED = new Response('Method Not Allowed', {
|
|
5
|
+
status: 405,
|
|
6
|
+
});
|
|
7
|
+
/**
|
|
8
|
+
* The not found response
|
|
9
|
+
*/
|
|
10
|
+
export const NOT_FOUND = new Response('Not Found', { status: 404 });
|
|
11
|
+
/**
|
|
12
|
+
* The OpenAPI error response
|
|
13
|
+
*/
|
|
14
|
+
export const OPENAPI_ERROR = Response.json({
|
|
15
|
+
error: 'API Router not configured',
|
|
16
|
+
message: 'Please provide an apiDir option when initializing the Burger instance to enable OpenAPI documentation.',
|
|
17
|
+
});
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { PageDefinition, RouteDefinition } from
|
|
1
|
+
import type { PageDefinition, RouteDefinition, TrieNode } from '@burgerTypes';
|
|
2
2
|
/**
|
|
3
3
|
* Constants for route handling.
|
|
4
4
|
*/
|
|
@@ -30,3 +30,11 @@ export declare const getRouteSpecificity: (path: string) => number;
|
|
|
30
30
|
* @returns Negative if a comes before b, positive if b comes before a, zero if equal.
|
|
31
31
|
*/
|
|
32
32
|
export declare const compareRoutes: (a: PageDefinition | RouteDefinition, b: PageDefinition | RouteDefinition) => number;
|
|
33
|
+
/**
|
|
34
|
+
* Collects all routes from the trie and returns them as an array of RouteDefinition objects.
|
|
35
|
+
* @param node The current node in the trie.
|
|
36
|
+
* @param currentPath The current path being traversed.
|
|
37
|
+
* @param routes The array of collected routes.
|
|
38
|
+
* @returns An array of RouteDefinition objects.
|
|
39
|
+
*/
|
|
40
|
+
export declare function collectRoutes(node: TrieNode, currentPath?: string, routes?: RouteDefinition[]): RouteDefinition[];
|
|
@@ -2,25 +2,25 @@
|
|
|
2
2
|
* Constants for route handling.
|
|
3
3
|
*/
|
|
4
4
|
export const ROUTE_CONSTANTS = {
|
|
5
|
-
SUPPORTED_PAGE_EXTENSIONS: [
|
|
6
|
-
PAGE_INDEX_FILES: [
|
|
7
|
-
DYNAMIC_SEGMENT_PREFIX:
|
|
8
|
-
DYNAMIC_FOLDER_START:
|
|
9
|
-
DYNAMIC_FOLDER_END:
|
|
10
|
-
GROUPING_FOLDER_START:
|
|
11
|
-
GROUPING_FOLDER_END:
|
|
5
|
+
SUPPORTED_PAGE_EXTENSIONS: ['.tsx', '.html'],
|
|
6
|
+
PAGE_INDEX_FILES: ['index.tsx', 'index.html'],
|
|
7
|
+
DYNAMIC_SEGMENT_PREFIX: ':',
|
|
8
|
+
DYNAMIC_FOLDER_START: '[',
|
|
9
|
+
DYNAMIC_FOLDER_END: ']',
|
|
10
|
+
GROUPING_FOLDER_START: '(',
|
|
11
|
+
GROUPING_FOLDER_END: ')',
|
|
12
12
|
};
|
|
13
13
|
/**
|
|
14
14
|
* Supported HTTP methods
|
|
15
15
|
*/
|
|
16
16
|
export const HTTP_METHODS = [
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
17
|
+
'GET',
|
|
18
|
+
'POST',
|
|
19
|
+
'PUT',
|
|
20
|
+
'DELETE',
|
|
21
|
+
'PATCH',
|
|
22
|
+
'HEAD',
|
|
23
|
+
'OPTIONS',
|
|
24
24
|
];
|
|
25
25
|
/**
|
|
26
26
|
* Calculates the specificity of a route path based on the number of static segments.
|
|
@@ -29,7 +29,7 @@ export const HTTP_METHODS = [
|
|
|
29
29
|
* @returns The specificity score (higher means more static segments).
|
|
30
30
|
*/
|
|
31
31
|
export const getRouteSpecificity = (path) => {
|
|
32
|
-
const segments = path.split(
|
|
32
|
+
const segments = path.split('/').filter(Boolean);
|
|
33
33
|
return segments.reduce((score, segment) => {
|
|
34
34
|
return segment.startsWith(ROUTE_CONSTANTS.DYNAMIC_SEGMENT_PREFIX)
|
|
35
35
|
? score
|
|
@@ -52,3 +52,29 @@ export const compareRoutes = (a, b) => {
|
|
|
52
52
|
return 1;
|
|
53
53
|
return a.path.localeCompare(b.path);
|
|
54
54
|
};
|
|
55
|
+
/**
|
|
56
|
+
* Collects all routes from the trie and returns them as an array of RouteDefinition objects.
|
|
57
|
+
* @param node The current node in the trie.
|
|
58
|
+
* @param currentPath The current path being traversed.
|
|
59
|
+
* @param routes The array of collected routes.
|
|
60
|
+
* @returns An array of RouteDefinition objects.
|
|
61
|
+
*/
|
|
62
|
+
export function collectRoutes(node, currentPath = '', routes = []) {
|
|
63
|
+
// If this node has a route definition, add it
|
|
64
|
+
if (node.route) {
|
|
65
|
+
routes.push({
|
|
66
|
+
...node.route,
|
|
67
|
+
path: currentPath,
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
// Traverse static children
|
|
71
|
+
node.children.forEach((child, segment) => {
|
|
72
|
+
collectRoutes(child, `${currentPath}/${segment}`, routes);
|
|
73
|
+
});
|
|
74
|
+
// Traverse dynamic child if exists
|
|
75
|
+
if (node.paramChild) {
|
|
76
|
+
const paramPath = `${currentPath}/:${node.paramChild.paramName}`;
|
|
77
|
+
collectRoutes(node.paramChild, paramPath, routes);
|
|
78
|
+
}
|
|
79
|
+
return routes;
|
|
80
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "burger-api",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"author": "Isfhan Ahmed",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"module": "dist/src/index.js",
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
],
|
|
11
11
|
"scripts": {
|
|
12
12
|
"typecheck": "tsc --noEmit",
|
|
13
|
-
"build": "tsc --project tsconfig.build.json",
|
|
13
|
+
"build": "tsc --project tsconfig.build.json && tsc-alias -p tsconfig.build.json",
|
|
14
14
|
"test": "bun test",
|
|
15
15
|
"dev": "bun run examples/file-base-static-page-routing-app/index.ts"
|
|
16
16
|
},
|
|
@@ -70,13 +70,14 @@
|
|
|
70
70
|
},
|
|
71
71
|
"homepage": "https://burger-api-docs.vercel.app",
|
|
72
72
|
"dependencies": {
|
|
73
|
-
"zod": "^3.24.
|
|
74
|
-
"zod-to-json-schema": "^3.24.
|
|
73
|
+
"zod": "^3.24.3",
|
|
74
|
+
"zod-to-json-schema": "^3.24.5"
|
|
75
75
|
},
|
|
76
76
|
"devDependencies": {
|
|
77
|
-
"@types/bun": "latest"
|
|
77
|
+
"@types/bun": "latest",
|
|
78
|
+
"tsc-alias": "^1.8.15"
|
|
78
79
|
},
|
|
79
80
|
"peerDependencies": {
|
|
80
81
|
"typescript": "^5.7.3"
|
|
81
82
|
}
|
|
82
|
-
}
|
|
83
|
+
}
|
|
@@ -1,251 +0,0 @@
|
|
|
1
|
-
import { z } from "zod";
|
|
2
|
-
export interface ServerOptions {
|
|
3
|
-
/**
|
|
4
|
-
* The title of the API. This is an optional property that can be used
|
|
5
|
-
* to specify a custom title for the API documentation.
|
|
6
|
-
*/
|
|
7
|
-
title?: string;
|
|
8
|
-
/**
|
|
9
|
-
* The description of the API. This is an optional property that can be used
|
|
10
|
-
* to provide a brief overview of the API.
|
|
11
|
-
*/
|
|
12
|
-
description?: string;
|
|
13
|
-
/**
|
|
14
|
-
* The directory path to load API routes from.
|
|
15
|
-
* If not specified, no API routes are loaded.
|
|
16
|
-
*/
|
|
17
|
-
apiDir?: string;
|
|
18
|
-
/**
|
|
19
|
-
* The directory path to load Page routes from.
|
|
20
|
-
* If not specified, no Page routes are loaded.
|
|
21
|
-
* Page routes are not yet supported, but will be supported in the future.
|
|
22
|
-
*/
|
|
23
|
-
pageDir?: string;
|
|
24
|
-
/**
|
|
25
|
-
* Global middleware to be executed before each request.
|
|
26
|
-
*/
|
|
27
|
-
globalMiddleware?: Middleware[];
|
|
28
|
-
/**
|
|
29
|
-
* The version of the API. This is an optional property that can be used
|
|
30
|
-
* to specify the version of the API.
|
|
31
|
-
*/
|
|
32
|
-
version?: string;
|
|
33
|
-
/**
|
|
34
|
-
* Enables or disables debug mode. This is an optional property
|
|
35
|
-
* that, when set to true, can be used to output additional debugging
|
|
36
|
-
* information to the console or logs to aid in development and troubleshooting.
|
|
37
|
-
*/
|
|
38
|
-
debug?: boolean;
|
|
39
|
-
}
|
|
40
|
-
export interface BurgerRequest extends Request {
|
|
41
|
-
/**
|
|
42
|
-
* Provides helper to access query parameters as URLSearchParams.
|
|
43
|
-
* This is a convenience property that allows you to access the query
|
|
44
|
-
* parameters of the request as a URLSearchParams object, which provides
|
|
45
|
-
* methods for working with the query parameters like `get(key)`,
|
|
46
|
-
* `getAll(key)`, `has(key)`, `keys()`, `values()`, `entries()`, and more.
|
|
47
|
-
*/
|
|
48
|
-
query: URLSearchParams;
|
|
49
|
-
/**
|
|
50
|
-
* Contains URL parameters extracted from the request path.
|
|
51
|
-
* This property is only present if the request path matches a route
|
|
52
|
-
* with dynamic parameters.
|
|
53
|
-
*
|
|
54
|
-
* For example, if the route is `/users/:id`, and the request path is
|
|
55
|
-
* `/users/123`, then the `params` property will be `{ id: '123' }`.
|
|
56
|
-
*/
|
|
57
|
-
params?: Record<string, string>;
|
|
58
|
-
/**
|
|
59
|
-
* Contains validated data for the request.
|
|
60
|
-
* This is an optional property that will only be present if
|
|
61
|
-
* a middleware has validated the request data and attached the
|
|
62
|
-
* validated data to the request.
|
|
63
|
-
*
|
|
64
|
-
* Properties:
|
|
65
|
-
* - `params`: Validated URL parameters.
|
|
66
|
-
* - `query`: Validated query string parameters.
|
|
67
|
-
* - `body`: Validated request body (if JSON).
|
|
68
|
-
*/
|
|
69
|
-
validated?: {
|
|
70
|
-
params?: unknown;
|
|
71
|
-
query?: unknown;
|
|
72
|
-
body?: unknown;
|
|
73
|
-
};
|
|
74
|
-
}
|
|
75
|
-
export interface BurgerResponse {
|
|
76
|
-
/**
|
|
77
|
-
* Sets a header value.
|
|
78
|
-
* @param name - The header name.
|
|
79
|
-
* @param value - The header value.
|
|
80
|
-
* @returns The current instance for chaining.
|
|
81
|
-
*/
|
|
82
|
-
header(name: string, value: string): this;
|
|
83
|
-
/**
|
|
84
|
-
* Removes a header.
|
|
85
|
-
* @param name - The header name to remove.
|
|
86
|
-
* @returns The current instance for chaining.
|
|
87
|
-
*/
|
|
88
|
-
removeHeader(name: string): this;
|
|
89
|
-
/**
|
|
90
|
-
* Sets the HTTP status code.
|
|
91
|
-
* @param status - The status code.
|
|
92
|
-
* @returns The current instance for chaining.
|
|
93
|
-
*/
|
|
94
|
-
status(status: number): this;
|
|
95
|
-
/**
|
|
96
|
-
* Sets the response body.
|
|
97
|
-
* @param body - The body content.
|
|
98
|
-
* @returns The current instance for chaining.
|
|
99
|
-
*/
|
|
100
|
-
body(body: BodyInit): this;
|
|
101
|
-
/**
|
|
102
|
-
* Builds and returns the final Response object using the current state.
|
|
103
|
-
* This should be called only once when the response is finalized.
|
|
104
|
-
* @returns The final Response object.
|
|
105
|
-
*/
|
|
106
|
-
build(): Response;
|
|
107
|
-
/**
|
|
108
|
-
* Convenience method to send a JSON response.
|
|
109
|
-
* Sets the "Content-Type" header and serializes the data to JSON.
|
|
110
|
-
* @param data - The data to send.
|
|
111
|
-
* @returns The final Response object.
|
|
112
|
-
*/
|
|
113
|
-
json(data: unknown): Response;
|
|
114
|
-
/**
|
|
115
|
-
* Convenience method to send a plain text response.
|
|
116
|
-
* Sets the "Content-Type" header and returns a text response.
|
|
117
|
-
* @param data - The text to send.
|
|
118
|
-
* @returns The final Response object.
|
|
119
|
-
*/
|
|
120
|
-
text(data: string): Response;
|
|
121
|
-
/**
|
|
122
|
-
* Convenience method to send an HTML response.
|
|
123
|
-
* Sets the "Content-Type" header and returns an HTML response.
|
|
124
|
-
* @param data - The HTML string to send.
|
|
125
|
-
* @returns The final Response object.
|
|
126
|
-
*/
|
|
127
|
-
html(data: string): Response;
|
|
128
|
-
/**
|
|
129
|
-
* Convenience method to send a redirect response.
|
|
130
|
-
* Sets the "Location" header and status code.
|
|
131
|
-
* @param url - The URL to redirect to.
|
|
132
|
-
* @param status - The HTTP status code (default 302).
|
|
133
|
-
* @returns The current instance for chaining.
|
|
134
|
-
*/
|
|
135
|
-
redirect(url: string, status?: number): this;
|
|
136
|
-
/**
|
|
137
|
-
* Convenience method to send a file response using Bun.file.
|
|
138
|
-
* @param filePath - The file path to serve.
|
|
139
|
-
* @returns The final Response object.
|
|
140
|
-
*/
|
|
141
|
-
file(filePath: string): Response;
|
|
142
|
-
/**
|
|
143
|
-
* Returns a Response directly using the provided body and init settings.
|
|
144
|
-
* This bypasses the mutable state.
|
|
145
|
-
* @param body - The response body.
|
|
146
|
-
* @param init - Optional ResponseInit settings.
|
|
147
|
-
* @returns A new Response object.
|
|
148
|
-
*/
|
|
149
|
-
original(body?: BodyInit | null, init?: ResponseInit): Response;
|
|
150
|
-
}
|
|
151
|
-
/**
|
|
152
|
-
* Represents a request handler function.
|
|
153
|
-
* Request handler functions receive a BurgerRequest and BurgerResponse as
|
|
154
|
-
* arguments. They must return a Response object, which can be either a Promise
|
|
155
|
-
* that resolves with a Response object or a Response object directly.
|
|
156
|
-
*
|
|
157
|
-
* @param request - The incoming BurgerRequest object.
|
|
158
|
-
* @param response - The outgoing BurgerResponse object.
|
|
159
|
-
* @returns A Response object or a Promise that resolves with a Response object.
|
|
160
|
-
*/
|
|
161
|
-
export type RequestHandler = (request: BurgerRequest, response: BurgerResponse) => Promise<Response> | Response;
|
|
162
|
-
/**
|
|
163
|
-
* Represents a middleware function in the request handling pipeline.
|
|
164
|
-
* Middleware functions have the ability to modify the request and response
|
|
165
|
-
* objects, end the request-response cycle, or call the next middleware function
|
|
166
|
-
* in the chain. They are executed in the order they are defined.
|
|
167
|
-
*
|
|
168
|
-
* @param request - The incoming BurgerRequest object.
|
|
169
|
-
* @param response - The outgoing BurgerResponse object.
|
|
170
|
-
* @param next - A function to call the next middleware in the chain.
|
|
171
|
-
* @returns A Promise that resolves with the response.
|
|
172
|
-
*/
|
|
173
|
-
export type Middleware = (request: BurgerRequest, response: BurgerResponse, next: () => Promise<Response>) => Promise<Response>;
|
|
174
|
-
export interface RouteDefinition {
|
|
175
|
-
/**
|
|
176
|
-
* The path of the route.
|
|
177
|
-
*/
|
|
178
|
-
path: string;
|
|
179
|
-
/**
|
|
180
|
-
* An object containing the request handlers for each HTTP method.
|
|
181
|
-
* The keys are the HTTP method names (e.g. "GET", "POST", etc.).
|
|
182
|
-
* The values are the request handlers for that method.
|
|
183
|
-
*/
|
|
184
|
-
handlers: {
|
|
185
|
-
[method: string]: RequestHandler;
|
|
186
|
-
};
|
|
187
|
-
/**
|
|
188
|
-
* An array of middleware functions to run before the request handler.
|
|
189
|
-
* The middleware functions will be run in the order they are specified.
|
|
190
|
-
*/
|
|
191
|
-
middleware?: Middleware[];
|
|
192
|
-
/**
|
|
193
|
-
* An optional route schema to validate the request data against.
|
|
194
|
-
* This property is set by the user when defining a route.
|
|
195
|
-
* The schema is used to validate the request data for each HTTP method.
|
|
196
|
-
* The keys are the HTTP method names (in lowercase) and the values are
|
|
197
|
-
* the Zod schema objects for that method.
|
|
198
|
-
*/
|
|
199
|
-
schema?: RouteSchema;
|
|
200
|
-
/**
|
|
201
|
-
* Optional OpenAPI metadata to generate documentation for the route.
|
|
202
|
-
* If provided, this property should define an object where each key
|
|
203
|
-
* is an HTTP method name (in lowercase), and the value is an object
|
|
204
|
-
* containing the OpenAPI metadata for that method.
|
|
205
|
-
*/
|
|
206
|
-
openapi?: openapi;
|
|
207
|
-
}
|
|
208
|
-
/**
|
|
209
|
-
* Define a type for the route schema.
|
|
210
|
-
* For each HTTP method (in lowercase), you can optionally define:
|
|
211
|
-
* - params: for URL parameters,
|
|
212
|
-
* - query: for query string parameters,
|
|
213
|
-
* - body: for the request body.
|
|
214
|
-
*/
|
|
215
|
-
export type RouteSchema = {
|
|
216
|
-
[method: string]: {
|
|
217
|
-
params?: z.ZodTypeAny;
|
|
218
|
-
query?: z.ZodTypeAny;
|
|
219
|
-
body?: z.ZodTypeAny;
|
|
220
|
-
};
|
|
221
|
-
};
|
|
222
|
-
/**
|
|
223
|
-
* Optional OpenAPI metadata to generate documentation for the route.
|
|
224
|
-
* Each key is an HTTP method name (in lowercase) and the value is an object
|
|
225
|
-
* containing the OpenAPI metadata for that method.
|
|
226
|
-
*
|
|
227
|
-
* If the `openapi` property is not defined, the route will not be included in
|
|
228
|
-
* the generated OpenAPI documentation.
|
|
229
|
-
*
|
|
230
|
-
* See the OpenAPI specification for the possible properties and their
|
|
231
|
-
* descriptions.
|
|
232
|
-
*/
|
|
233
|
-
export type openapi = {
|
|
234
|
-
[method: string]: {
|
|
235
|
-
summary?: string;
|
|
236
|
-
description?: string;
|
|
237
|
-
tags?: string[];
|
|
238
|
-
operationId?: string;
|
|
239
|
-
deprecated?: boolean;
|
|
240
|
-
responses?: Record<string, any>;
|
|
241
|
-
externalDocs?: {
|
|
242
|
-
description?: string;
|
|
243
|
-
url?: string;
|
|
244
|
-
};
|
|
245
|
-
};
|
|
246
|
-
};
|
|
247
|
-
export interface PageDefinition {
|
|
248
|
-
path: string;
|
|
249
|
-
handler: RequestHandler;
|
|
250
|
-
middleware?: RequestHandler[];
|
|
251
|
-
}
|
package/dist/src/types/index.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import { z } from "zod";
|