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,8 +1,8 @@
|
|
|
1
1
|
// Import stuff from node
|
|
2
|
-
import {
|
|
3
|
-
import * as path from
|
|
2
|
+
import { readdir } from 'fs/promises';
|
|
3
|
+
import * as path from 'path';
|
|
4
4
|
// Import utils
|
|
5
|
-
import { cleanPrefix, normalizePath,
|
|
5
|
+
import { cleanPrefix, normalizePath, ROUTE_CONSTANTS, HTTP_METHODS, } from '../utils/index.js';
|
|
6
6
|
/**
|
|
7
7
|
* ApiRouter class for handling file-based routing.
|
|
8
8
|
* Loads routes from a directory structure and matches requests to the appropriate route handlers.
|
|
@@ -12,32 +12,36 @@ import { cleanPrefix, normalizePath, compareRoutes, ROUTE_CONSTANTS, HTTP_METHOD
|
|
|
12
12
|
export class ApiRouter {
|
|
13
13
|
routesDir;
|
|
14
14
|
prefix;
|
|
15
|
-
/**
|
|
16
|
-
|
|
15
|
+
/** The root of the trie where all routes will begin*/
|
|
16
|
+
root = { children: new Map() };
|
|
17
17
|
/**
|
|
18
18
|
* Constructor for the ApiRouter class.
|
|
19
19
|
* @param routesDir The directory path where route modules are located.
|
|
20
20
|
* @param prefix Optional prefix to prepend to all routes (e.g., "api" becomes "/api/...").
|
|
21
|
+
* @throws {Error} If the routes directory path is not provided.
|
|
21
22
|
*/
|
|
22
|
-
constructor(routesDir, prefix =
|
|
23
|
+
constructor(routesDir, prefix = '') {
|
|
23
24
|
this.routesDir = routesDir;
|
|
24
25
|
this.prefix = prefix;
|
|
25
26
|
if (!routesDir) {
|
|
26
|
-
throw new Error(
|
|
27
|
+
throw new Error('Routes directory path is required');
|
|
27
28
|
}
|
|
28
29
|
}
|
|
29
30
|
/**
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
|
|
33
|
-
|
|
31
|
+
* Getter for the routes trie.
|
|
32
|
+
* @returns The root of the trie.
|
|
33
|
+
*/
|
|
34
|
+
get routes() {
|
|
35
|
+
return this.root;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Loads all routes from the routes directory into the trie structure.
|
|
39
|
+
* @returns {Promise<void>} A promise that resolves when all routes are loaded.
|
|
40
|
+
* @throws {Error} If the routes directory is not found or if an error occurs during route loading.
|
|
34
41
|
*/
|
|
35
42
|
async loadRoutes() {
|
|
36
43
|
try {
|
|
37
|
-
this.routes = [];
|
|
38
44
|
await this.scanDirectory(this.routesDir);
|
|
39
|
-
// Sort routes to ensure static routes are matched before dynamic ones
|
|
40
|
-
this.routes.sort((a, b) => compareRoutes(a, b));
|
|
41
45
|
}
|
|
42
46
|
catch (error) {
|
|
43
47
|
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
@@ -45,16 +49,42 @@ export class ApiRouter {
|
|
|
45
49
|
}
|
|
46
50
|
}
|
|
47
51
|
/**
|
|
48
|
-
*
|
|
49
|
-
* @param
|
|
50
|
-
* @
|
|
51
|
-
|
|
52
|
+
* Inserts a route definition into the trie structure.
|
|
53
|
+
* @param routeDef The route definition to insert, containing path, handlers, middleware, schema, and OpenAPI metadata.
|
|
54
|
+
* @throws {Error} If the route definition is invalid or causes a conflict in the trie.
|
|
55
|
+
*/
|
|
56
|
+
insertRoute(routeDef) {
|
|
57
|
+
let node = this.root;
|
|
58
|
+
const segments = routeDef.path.split('/').filter(Boolean);
|
|
59
|
+
for (const segment of segments) {
|
|
60
|
+
if (segment.startsWith(':')) {
|
|
61
|
+
if (!node.paramChild) {
|
|
62
|
+
node.paramChild = { children: new Map() };
|
|
63
|
+
}
|
|
64
|
+
node = node.paramChild;
|
|
65
|
+
node.paramName = segment.slice(1);
|
|
66
|
+
}
|
|
67
|
+
else {
|
|
68
|
+
if (!node.children.has(segment)) {
|
|
69
|
+
node.children.set(segment, { children: new Map() });
|
|
70
|
+
}
|
|
71
|
+
node = node.children.get(segment);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
node.route = routeDef;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Recursively scans a directory for route modules (route.ts files) and loads them into the trie.
|
|
78
|
+
* @param dir The current directory path to scan.
|
|
79
|
+
* @param basePath The base path used to construct route paths from the directory structure.
|
|
80
|
+
* @returns {Promise<void>} A promise that resolves when the directory scan is complete.
|
|
81
|
+
* @throws {Error} If multiple dynamic folders are found at the same level or if directory access fails.
|
|
52
82
|
*/
|
|
53
|
-
async scanDirectory(dir, basePath =
|
|
83
|
+
async scanDirectory(dir, basePath = '') {
|
|
54
84
|
// Track if a dynamic folder has been found at this directory level
|
|
55
85
|
let dynamicFolderFound = false;
|
|
56
86
|
try {
|
|
57
|
-
const entries =
|
|
87
|
+
const entries = await readdir(dir, { withFileTypes: true });
|
|
58
88
|
for (const entry of entries) {
|
|
59
89
|
const entryPath = path.join(dir, entry.name);
|
|
60
90
|
const relativePath = path.join(basePath, entry.name);
|
|
@@ -69,7 +99,7 @@ export class ApiRouter {
|
|
|
69
99
|
}
|
|
70
100
|
await this.scanDirectory(entryPath, relativePath);
|
|
71
101
|
}
|
|
72
|
-
else if (entry.isFile() && entry.name ===
|
|
102
|
+
else if (entry.isFile() && entry.name === 'route.ts') {
|
|
73
103
|
await this.loadRouteModule(entryPath, relativePath);
|
|
74
104
|
}
|
|
75
105
|
}
|
|
@@ -82,24 +112,29 @@ export class ApiRouter {
|
|
|
82
112
|
}
|
|
83
113
|
}
|
|
84
114
|
/**
|
|
85
|
-
* Loads a route module and
|
|
86
|
-
* @param entryPath
|
|
87
|
-
* @param relativePath
|
|
115
|
+
* Loads a route module from a file and inserts it into the trie.
|
|
116
|
+
* @param entryPath The full file system path to the route module (route.ts).
|
|
117
|
+
* @param relativePath The relative path used to construct the route path.
|
|
118
|
+
* @returns {Promise<void>} A promise that resolves when the module is loaded and inserted.
|
|
119
|
+
* @throws {Error} If the route module fails to load or is invalid.
|
|
88
120
|
*/
|
|
89
121
|
async loadRouteModule(entryPath, relativePath) {
|
|
90
122
|
try {
|
|
91
|
-
// Convert file path to route path
|
|
123
|
+
// Convert the file path to a route path
|
|
92
124
|
const routePath = this.convertFilePathToRoute(relativePath);
|
|
125
|
+
console.info('Loading route:', routePath);
|
|
126
|
+
// Get the module path like "D:\\Projects\\src\\api\\users\\route.ts"
|
|
93
127
|
const modulePath = path.resolve(entryPath);
|
|
128
|
+
// Import the module
|
|
94
129
|
const routeModule = await import(modulePath);
|
|
95
|
-
//
|
|
130
|
+
// Variable to store the handlers for each method
|
|
96
131
|
const handlers = {};
|
|
132
|
+
// Loop through all the HTTP methods and add the handler to the handlers object
|
|
97
133
|
for (const method of HTTP_METHODS) {
|
|
98
|
-
if (typeof routeModule[method] ===
|
|
134
|
+
if (typeof routeModule[method] === 'function') {
|
|
99
135
|
handlers[method] = routeModule[method];
|
|
100
136
|
}
|
|
101
137
|
}
|
|
102
|
-
// Create route definition
|
|
103
138
|
const routeDef = {
|
|
104
139
|
path: routePath,
|
|
105
140
|
handlers,
|
|
@@ -107,22 +142,21 @@ export class ApiRouter {
|
|
|
107
142
|
schema: routeModule.schema,
|
|
108
143
|
openapi: routeModule.openapi,
|
|
109
144
|
};
|
|
110
|
-
this.
|
|
145
|
+
this.insertRoute(routeDef);
|
|
111
146
|
}
|
|
112
147
|
catch (error) {
|
|
113
148
|
throw new Error(`Failed to load route module '${entryPath}': ${String(error)}`);
|
|
114
149
|
}
|
|
115
150
|
}
|
|
116
151
|
/**
|
|
117
|
-
* Converts a file path to a route path by processing dynamic segments
|
|
118
|
-
*
|
|
119
|
-
* @
|
|
120
|
-
* @returns The converted route path string.
|
|
152
|
+
* Converts a file path to a route path by processing dynamic segments and applying the prefix.
|
|
153
|
+
* @param filePath The file path to convert (e.g., "users/[id]/route.ts").
|
|
154
|
+
* @returns {string} The converted route path (e.g., "/users/:id").
|
|
121
155
|
*/
|
|
122
156
|
convertFilePathToRoute(filePath) {
|
|
123
157
|
// Remove the "route.ts" suffix
|
|
124
|
-
if (filePath.endsWith(
|
|
125
|
-
filePath = filePath.slice(0, -
|
|
158
|
+
if (filePath.endsWith('route.ts')) {
|
|
159
|
+
filePath = filePath.slice(0, -'route.ts'.length);
|
|
126
160
|
}
|
|
127
161
|
// Split path into segments
|
|
128
162
|
const segments = filePath.split(path.sep);
|
|
@@ -145,65 +179,51 @@ export class ApiRouter {
|
|
|
145
179
|
}
|
|
146
180
|
}
|
|
147
181
|
// Construct the route with leading slash
|
|
148
|
-
let route =
|
|
182
|
+
let route = '/' + resultSegments.join('/');
|
|
149
183
|
// Apply prefix if provided
|
|
150
184
|
if (this.prefix) {
|
|
151
185
|
const cleanPrefixStr = cleanPrefix(this.prefix);
|
|
152
|
-
route =
|
|
186
|
+
route = '/' + cleanPrefixStr + route;
|
|
153
187
|
}
|
|
154
188
|
// Remove trailing slash unless it's the root
|
|
155
|
-
if (route !==
|
|
189
|
+
if (route !== '/' && route.endsWith('/')) {
|
|
156
190
|
route = route.slice(0, -1);
|
|
157
191
|
}
|
|
158
192
|
return route;
|
|
159
193
|
}
|
|
160
194
|
/**
|
|
161
|
-
* Resolves
|
|
162
|
-
* @param
|
|
163
|
-
* @
|
|
195
|
+
* Resolves a request to a route definition and its parameters.
|
|
196
|
+
* @param pathname The normalized request pathname.
|
|
197
|
+
* @param method The uppercase HTTP method.
|
|
198
|
+
* @returns {{ route?: RouteDefinition; params: Record<string, string> }} An object containing the matched route (if any) and extracted parameters.
|
|
199
|
+
* @throws {Error} If the request URL is malformed.
|
|
164
200
|
*/
|
|
165
|
-
resolve(
|
|
201
|
+
resolve(pathname, method) {
|
|
166
202
|
try {
|
|
167
|
-
const
|
|
168
|
-
|
|
169
|
-
const
|
|
170
|
-
for (const
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
203
|
+
const segments = pathname.split('/').filter(Boolean);
|
|
204
|
+
let node = this.root;
|
|
205
|
+
const params = {};
|
|
206
|
+
for (const segment of segments) {
|
|
207
|
+
if (node.children.has(segment)) {
|
|
208
|
+
node = node.children.get(segment);
|
|
209
|
+
}
|
|
210
|
+
else if (node.paramChild) {
|
|
211
|
+
node = node.paramChild;
|
|
212
|
+
params[node.paramName] = segment;
|
|
213
|
+
}
|
|
214
|
+
else {
|
|
215
|
+
return { params: {} };
|
|
174
216
|
}
|
|
175
217
|
}
|
|
218
|
+
if (node.route && node.route.handlers[method]) {
|
|
219
|
+
return { route: node.route, params };
|
|
220
|
+
}
|
|
176
221
|
return { params: {} };
|
|
177
222
|
}
|
|
178
223
|
catch (error) {
|
|
179
|
-
//
|
|
224
|
+
// Log the error for better debugging
|
|
225
|
+
console.error(`Error resolving API route for path "${pathname}":`, error);
|
|
180
226
|
return { params: {} };
|
|
181
227
|
}
|
|
182
228
|
}
|
|
183
|
-
/**
|
|
184
|
-
* Checks if the request path matches the route path, extracting dynamic parameters if matched.
|
|
185
|
-
* @param requestPath The request path to check.
|
|
186
|
-
* @param routePath The route path to match against.
|
|
187
|
-
* @returns A record of dynamic parameters if matched, otherwise null.
|
|
188
|
-
*/
|
|
189
|
-
matchRoute(requestPath, routePath) {
|
|
190
|
-
const reqSegments = requestPath.split("/").filter(Boolean);
|
|
191
|
-
const routeSegments = routePath.split("/").filter(Boolean);
|
|
192
|
-
if (reqSegments.length !== routeSegments.length) {
|
|
193
|
-
return null;
|
|
194
|
-
}
|
|
195
|
-
const params = {};
|
|
196
|
-
for (let i = 0; i < reqSegments.length; i++) {
|
|
197
|
-
const rSegment = routeSegments[i];
|
|
198
|
-
const reqSegment = reqSegments[i];
|
|
199
|
-
if (rSegment.startsWith(ROUTE_CONSTANTS.DYNAMIC_SEGMENT_PREFIX)) {
|
|
200
|
-
const paramName = rSegment.slice(1);
|
|
201
|
-
params[paramName] = decodeURIComponent(reqSegment);
|
|
202
|
-
}
|
|
203
|
-
else if (rSegment !== reqSegment) {
|
|
204
|
-
return null;
|
|
205
|
-
}
|
|
206
|
-
}
|
|
207
|
-
return params;
|
|
208
|
-
}
|
|
209
229
|
}
|
|
@@ -1,12 +1,5 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* Generates an OpenAPI 3.0 document from the router's routes and global options.
|
|
5
|
-
* @param router The router instance with loaded routes.
|
|
6
|
-
* @param options Global options, including OpenAPI metadata.
|
|
7
|
-
* @returns The OpenAPI document as a JavaScript object.
|
|
8
|
-
*/
|
|
9
|
-
export declare function generateOpenAPIDocument(router: ApiRouter, options: ServerOptions): {
|
|
1
|
+
import type { ServerOptions, RouteDefinition } from '@burgerTypes';
|
|
2
|
+
export declare function generateOpenAPIDocument(apiRoutes: RouteDefinition[], options: ServerOptions): {
|
|
10
3
|
openapi: string;
|
|
11
4
|
info: {
|
|
12
5
|
title: string;
|
package/dist/src/core/openapi.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { zodToJsonSchema } from
|
|
1
|
+
import { zodToJsonSchema } from 'zod-to-json-schema';
|
|
2
2
|
/**
|
|
3
3
|
* Builds an array of OpenAPI 3.0 parameters based on the Zod schema.
|
|
4
4
|
* For each property in the Zod schema, an OpenAPI parameter is constructed
|
|
@@ -12,14 +12,14 @@ function buildParameters(zodSchema, location) {
|
|
|
12
12
|
const parameters = [];
|
|
13
13
|
if (zodSchema &&
|
|
14
14
|
zodSchema._def &&
|
|
15
|
-
typeof zodSchema._def.shape ===
|
|
15
|
+
typeof zodSchema._def.shape === 'function') {
|
|
16
16
|
// Get the shape of the Zod schema
|
|
17
17
|
const shape = zodSchema._def.shape();
|
|
18
18
|
for (const key in shape) {
|
|
19
19
|
// Get the definition of the field
|
|
20
20
|
const fieldDef = shape[key];
|
|
21
21
|
// Determine if the field is optional
|
|
22
|
-
const isOptional = fieldDef._def.typeName ===
|
|
22
|
+
const isOptional = fieldDef._def.typeName === 'ZodOptional';
|
|
23
23
|
parameters.push({
|
|
24
24
|
// Set the name of the parameter
|
|
25
25
|
name: key,
|
|
@@ -28,7 +28,7 @@ function buildParameters(zodSchema, location) {
|
|
|
28
28
|
// Set the required flag
|
|
29
29
|
required: !isOptional,
|
|
30
30
|
// Set the schema type
|
|
31
|
-
schema: { type:
|
|
31
|
+
schema: { type: 'string' },
|
|
32
32
|
// Description of the parameter
|
|
33
33
|
description: `${location} parameter ${key}`,
|
|
34
34
|
});
|
|
@@ -49,11 +49,11 @@ function buildRequestBody(zodSchema) {
|
|
|
49
49
|
const jsonSchema = zodToJsonSchema(zodSchema);
|
|
50
50
|
return {
|
|
51
51
|
content: {
|
|
52
|
-
|
|
52
|
+
'application/json': {
|
|
53
53
|
schema: jsonSchema,
|
|
54
54
|
},
|
|
55
55
|
},
|
|
56
|
-
description:
|
|
56
|
+
description: 'Request body',
|
|
57
57
|
required: true,
|
|
58
58
|
};
|
|
59
59
|
}
|
|
@@ -65,27 +65,21 @@ function buildRequestBody(zodSchema) {
|
|
|
65
65
|
*/
|
|
66
66
|
function convertPathForOpenAPI(routePath) {
|
|
67
67
|
// Replace occurrences of :param with {param}
|
|
68
|
-
return routePath.replace(/:([a-zA-Z0-9_]+)/g,
|
|
68
|
+
return routePath.replace(/:([a-zA-Z0-9_]+)/g, '{$1}');
|
|
69
69
|
}
|
|
70
|
-
|
|
71
|
-
* Generates an OpenAPI 3.0 document from the router's routes and global options.
|
|
72
|
-
* @param router The router instance with loaded routes.
|
|
73
|
-
* @param options Global options, including OpenAPI metadata.
|
|
74
|
-
* @returns The OpenAPI document as a JavaScript object.
|
|
75
|
-
*/
|
|
76
|
-
export function generateOpenAPIDocument(router, options) {
|
|
70
|
+
export function generateOpenAPIDocument(apiRoutes, options) {
|
|
77
71
|
const openapiDoc = {
|
|
78
|
-
openapi:
|
|
72
|
+
openapi: '3.0.0',
|
|
79
73
|
info: {
|
|
80
|
-
title: options.title ||
|
|
81
|
-
description: options.description ||
|
|
82
|
-
version: options.version ||
|
|
74
|
+
title: options.title || 'Burger API',
|
|
75
|
+
description: options.description || 'Burger API documentation',
|
|
76
|
+
version: options.version || '1.0.0',
|
|
83
77
|
},
|
|
84
78
|
paths: {},
|
|
85
79
|
};
|
|
86
|
-
// Iterate over each route
|
|
87
|
-
for (const route of
|
|
88
|
-
// Convert colon-based dynamic segments to OpenAPI's {param} syntax
|
|
80
|
+
// Iterate over each route
|
|
81
|
+
for (const route of apiRoutes) {
|
|
82
|
+
// Convert colon-based dynamic segments to OpenAPI's {param} syntax
|
|
89
83
|
const openApiPath = convertPathForOpenAPI(route.path);
|
|
90
84
|
// Initialize path object if necessary
|
|
91
85
|
openapiDoc.paths[openApiPath] = openapiDoc.paths[openApiPath] || {};
|
|
@@ -97,14 +91,14 @@ export function generateOpenAPIDocument(router, options) {
|
|
|
97
91
|
const methodMeta = route.openapi?.[lowerMethod] || {};
|
|
98
92
|
// Generate an operationId: e.g., "get_api_product"
|
|
99
93
|
const operationId = methodMeta.operationId ||
|
|
100
|
-
`${lowerMethod}_${route.path.replace(/[\/:]/g,
|
|
94
|
+
`${lowerMethod}_${route.path.replace(/[\/:]/g, '_')}`;
|
|
101
95
|
// Build parameters for both path and query from the schema.
|
|
102
96
|
let parameters = [];
|
|
103
97
|
if (route.schema && route.schema[lowerMethod]) {
|
|
104
98
|
const schemaDef = route.schema[lowerMethod];
|
|
105
99
|
parameters = [
|
|
106
|
-
...buildParameters(schemaDef.params,
|
|
107
|
-
...buildParameters(schemaDef.query,
|
|
100
|
+
...buildParameters(schemaDef.params, 'path'),
|
|
101
|
+
...buildParameters(schemaDef.query, 'query'),
|
|
108
102
|
];
|
|
109
103
|
}
|
|
110
104
|
// Build requestBody if a body schema exists.
|
|
@@ -115,14 +109,14 @@ export function generateOpenAPIDocument(router, options) {
|
|
|
115
109
|
openapiDoc.paths[openApiPath][lowerMethod] = {
|
|
116
110
|
operationId,
|
|
117
111
|
summary: methodMeta.summary || `Summary for ${method} ${route.path}`,
|
|
118
|
-
description: methodMeta.description ||
|
|
112
|
+
description: methodMeta.description || '',
|
|
119
113
|
tags: methodMeta.tags || [],
|
|
120
114
|
deprecated: methodMeta.deprecated || false,
|
|
121
115
|
parameters: parameters,
|
|
122
116
|
requestBody: requestBody,
|
|
123
117
|
responses: methodMeta.responses || {
|
|
124
|
-
|
|
125
|
-
description:
|
|
118
|
+
'200': {
|
|
119
|
+
description: 'Successful response',
|
|
126
120
|
},
|
|
127
121
|
},
|
|
128
122
|
externalDocs: methodMeta.externalDocs || undefined,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { PageDefinition } from
|
|
1
|
+
import type { PageDefinition } from '@burgerTypes';
|
|
2
2
|
/**
|
|
3
3
|
* PageRouter class for handling file-based page routing.
|
|
4
4
|
* Loads pages from a directory structure and matches requests to the appropriate page handlers.
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
// Import stuff from node
|
|
2
|
-
import { readdirSync } from
|
|
3
|
-
import * as path from
|
|
2
|
+
import { readdirSync } from 'fs';
|
|
3
|
+
import * as path from 'path';
|
|
4
4
|
// Import utils
|
|
5
|
-
import { cleanPrefix, normalizePath, compareRoutes, ROUTE_CONSTANTS, } from
|
|
5
|
+
import { cleanPrefix, normalizePath, compareRoutes, ROUTE_CONSTANTS, } from '../utils/index.js';
|
|
6
6
|
/**
|
|
7
7
|
* PageRouter class for handling file-based page routing.
|
|
8
8
|
* Loads pages from a directory structure and matches requests to the appropriate page handlers.
|
|
@@ -18,11 +18,11 @@ export class PageRouter {
|
|
|
18
18
|
* @param pagesDir The directory path where page modules are located.
|
|
19
19
|
* @param prefix Optional prefix to prepend to all routes (e.g., "pages" becomes "/pages/...").
|
|
20
20
|
*/
|
|
21
|
-
constructor(pagesDir, prefix =
|
|
21
|
+
constructor(pagesDir, prefix = '') {
|
|
22
22
|
this.pagesDir = pagesDir;
|
|
23
23
|
this.prefix = prefix;
|
|
24
24
|
if (!pagesDir) {
|
|
25
|
-
throw new Error(
|
|
25
|
+
throw new Error('Pages directory path must be provided');
|
|
26
26
|
}
|
|
27
27
|
// Normalize the pagesDir path
|
|
28
28
|
this.pagesDir = path.normalize(pagesDir);
|
|
@@ -45,7 +45,7 @@ export class PageRouter {
|
|
|
45
45
|
this.pages.sort((a, b) => compareRoutes(a, b));
|
|
46
46
|
}
|
|
47
47
|
catch (error) {
|
|
48
|
-
console.error(
|
|
48
|
+
console.error('Failed to load pages:', error);
|
|
49
49
|
throw new Error(`Failed to load pages: ${error instanceof Error ? error.message : String(error)}`);
|
|
50
50
|
}
|
|
51
51
|
}
|
|
@@ -54,7 +54,7 @@ export class PageRouter {
|
|
|
54
54
|
* @param dir The current directory to scan.
|
|
55
55
|
* @param basePath The base path for constructing the route path.
|
|
56
56
|
*/
|
|
57
|
-
async scanDirectory(dir, basePath =
|
|
57
|
+
async scanDirectory(dir, basePath = '') {
|
|
58
58
|
// Track if a dynamic folder has been found at this directory level
|
|
59
59
|
let dynamicFolderFound = false;
|
|
60
60
|
try {
|
|
@@ -85,13 +85,13 @@ export class PageRouter {
|
|
|
85
85
|
// Import the module
|
|
86
86
|
const pageModule = await import(modulePath);
|
|
87
87
|
// Get the default export as the page handler
|
|
88
|
-
if (entry.name.endsWith(
|
|
89
|
-
typeof pageModule.default !==
|
|
88
|
+
if (entry.name.endsWith('.tsx') &&
|
|
89
|
+
typeof pageModule.default !== 'function') {
|
|
90
90
|
throw new Error(`Page at ${entryPath} must export a default function as its handler.`);
|
|
91
91
|
}
|
|
92
92
|
// Create page definition
|
|
93
93
|
const pageDefWithSlash = {
|
|
94
|
-
path: cleanedRoutePath +
|
|
94
|
+
path: cleanedRoutePath + '/',
|
|
95
95
|
handler: pageModule.default,
|
|
96
96
|
middleware: pageModule.middleware,
|
|
97
97
|
};
|
|
@@ -143,14 +143,14 @@ export class PageRouter {
|
|
|
143
143
|
}
|
|
144
144
|
}
|
|
145
145
|
// Construct the route with leading slash
|
|
146
|
-
let route =
|
|
146
|
+
let route = '/' + resultSegments.join('/');
|
|
147
147
|
// Apply prefix if provided
|
|
148
148
|
if (this.prefix) {
|
|
149
149
|
const cleanPrefixStr = cleanPrefix(this.prefix);
|
|
150
|
-
route =
|
|
150
|
+
route = '/' + cleanPrefixStr + route;
|
|
151
151
|
}
|
|
152
152
|
// Remove trailing slash unless it's the root
|
|
153
|
-
if (route !==
|
|
153
|
+
if (route !== '/' && route.endsWith('/')) {
|
|
154
154
|
route = route.slice(0, -1);
|
|
155
155
|
}
|
|
156
156
|
return route;
|
|
@@ -162,7 +162,7 @@ export class PageRouter {
|
|
|
162
162
|
*/
|
|
163
163
|
cleanRoutePath(routePath) {
|
|
164
164
|
// Break the route path into segments
|
|
165
|
-
const pathSegments = routePath.split(
|
|
165
|
+
const pathSegments = routePath.split('/');
|
|
166
166
|
// Get the last segment
|
|
167
167
|
if (pathSegments.length > 0) {
|
|
168
168
|
const lastSegment = pathSegments[pathSegments.length - 1];
|
|
@@ -173,14 +173,15 @@ export class PageRouter {
|
|
|
173
173
|
}
|
|
174
174
|
else {
|
|
175
175
|
// Remove file extension for non-index files
|
|
176
|
-
const extensionIndex = lastSegment.lastIndexOf(
|
|
176
|
+
const extensionIndex = lastSegment.lastIndexOf('.');
|
|
177
177
|
if (extensionIndex > 0) {
|
|
178
|
-
pathSegments[pathSegments.length - 1] =
|
|
178
|
+
pathSegments[pathSegments.length - 1] =
|
|
179
|
+
lastSegment.substring(0, extensionIndex);
|
|
179
180
|
}
|
|
180
181
|
}
|
|
181
182
|
}
|
|
182
183
|
// Join the segments back together
|
|
183
|
-
const finalPath = pathSegments.join(
|
|
184
|
+
const finalPath = pathSegments.join('/') === '' ? '/' : pathSegments.join('/');
|
|
184
185
|
return finalPath;
|
|
185
186
|
}
|
|
186
187
|
/**
|
|
@@ -209,8 +210,8 @@ export class PageRouter {
|
|
|
209
210
|
* @returns A record of dynamic parameters if matched, otherwise null.
|
|
210
211
|
*/
|
|
211
212
|
matchRoute(requestPath, pagePath) {
|
|
212
|
-
const reqSegments = requestPath.split(
|
|
213
|
-
const pageSegments = pagePath.split(
|
|
213
|
+
const reqSegments = requestPath.split('/').filter(Boolean);
|
|
214
|
+
const pageSegments = pagePath.split('/').filter(Boolean);
|
|
214
215
|
if (reqSegments.length !== pageSegments.length) {
|
|
215
216
|
return null;
|
|
216
217
|
}
|
|
@@ -58,7 +58,7 @@ export class HttpResponse {
|
|
|
58
58
|
* @returns The finalized Response object after building.
|
|
59
59
|
*/
|
|
60
60
|
json(data) {
|
|
61
|
-
this.header(
|
|
61
|
+
this.header('Content-Type', 'application/json');
|
|
62
62
|
this._body = JSON.stringify(data);
|
|
63
63
|
return this.build();
|
|
64
64
|
}
|
|
@@ -69,7 +69,7 @@ export class HttpResponse {
|
|
|
69
69
|
* @returns The finalized Response object after building.
|
|
70
70
|
*/
|
|
71
71
|
text(data) {
|
|
72
|
-
this.header(
|
|
72
|
+
this.header('Content-Type', 'text/plain');
|
|
73
73
|
this._body = data;
|
|
74
74
|
return this.build();
|
|
75
75
|
}
|
|
@@ -80,7 +80,7 @@ export class HttpResponse {
|
|
|
80
80
|
* @returns The finalized Response object after building.
|
|
81
81
|
*/
|
|
82
82
|
html(data) {
|
|
83
|
-
this.header(
|
|
83
|
+
this.header('Content-Type', 'text/html');
|
|
84
84
|
this._body = data;
|
|
85
85
|
return this.build();
|
|
86
86
|
}
|
|
@@ -92,7 +92,7 @@ export class HttpResponse {
|
|
|
92
92
|
*/
|
|
93
93
|
redirect(url, status = 302) {
|
|
94
94
|
this.status(status);
|
|
95
|
-
this.header(
|
|
95
|
+
this.header('Location', url);
|
|
96
96
|
this._body = null;
|
|
97
97
|
return this;
|
|
98
98
|
}
|
|
@@ -111,9 +111,9 @@ export class HttpResponse {
|
|
|
111
111
|
return this.build();
|
|
112
112
|
}
|
|
113
113
|
catch (error) {
|
|
114
|
-
console.error(
|
|
114
|
+
console.error('Error serving file:', error);
|
|
115
115
|
this.status(404);
|
|
116
|
-
this._body =
|
|
116
|
+
this._body = 'File not found';
|
|
117
117
|
return this.build();
|
|
118
118
|
}
|
|
119
119
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { ServerOptions,
|
|
1
|
+
import type { ServerOptions, FetchHandler } from '@burgerTypes';
|
|
2
2
|
export declare class Server {
|
|
3
3
|
private options;
|
|
4
4
|
private server;
|
|
@@ -7,14 +7,9 @@ export declare class Server {
|
|
|
7
7
|
* @param options - Configuration options for the server.
|
|
8
8
|
*/
|
|
9
9
|
constructor(options: ServerOptions);
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
* @param handler - The handler to be used by the server.
|
|
14
|
-
* @param port - The port to listen on.
|
|
15
|
-
* @param cb - An optional callback function to be called when the server starts.
|
|
16
|
-
*/
|
|
17
|
-
start(routes: any, handler: RequestHandler, port: number, cb?: () => void): void;
|
|
10
|
+
start(routes: {
|
|
11
|
+
[key: string]: any;
|
|
12
|
+
} | undefined, handler: FetchHandler, port: number, cb?: () => void): void;
|
|
18
13
|
/**
|
|
19
14
|
* Stops the server.
|
|
20
15
|
* If the server is currently running, this method will stop the server and
|