burger-api 0.0.39 → 0.1.4

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.
@@ -0,0 +1,232 @@
1
+ // Import stuff from node
2
+ import { readdirSync } from 'fs';
3
+ import * as path from 'path';
4
+ // Import utils
5
+ import { cleanPrefix, normalizePath, compareRoutes, ROUTE_CONSTANTS, } from '../utils/index.js';
6
+ /**
7
+ * PageRouter class for handling file-based page routing.
8
+ * Loads pages from a directory structure and matches requests to the appropriate page handlers.
9
+ * Supports dynamic segments (e.g., [id]) and uses default exports as page handlers.
10
+ */
11
+ export class PageRouter {
12
+ pagesDir;
13
+ prefix;
14
+ /** Array of loaded page definitions */
15
+ pages = [];
16
+ /**
17
+ * Constructor for the PageRouter class.
18
+ * @param pagesDir The directory path where page modules are located.
19
+ * @param prefix Optional prefix to prepend to all routes (e.g., "pages" becomes "/pages/...").
20
+ */
21
+ constructor(pagesDir, prefix = '') {
22
+ this.pagesDir = pagesDir;
23
+ this.prefix = prefix;
24
+ if (!pagesDir) {
25
+ throw new Error('Pages directory path must be provided');
26
+ }
27
+ // Normalize the pagesDir path
28
+ this.pagesDir = path.normalize(pagesDir);
29
+ // Normalize the prefix if provided
30
+ if (prefix) {
31
+ this.prefix = cleanPrefix(prefix);
32
+ }
33
+ }
34
+ /**
35
+ * Loads page modules from the specified directory and adds them to the pages array.
36
+ * After loading, sorts the pages to prioritize static routes over dynamic ones based on specificity.
37
+ * @returns A promise that resolves when all page modules have been loaded and sorted.
38
+ */
39
+ async loadPages() {
40
+ // Clear the pages array
41
+ this.pages = [];
42
+ try {
43
+ await this.scanDirectory(this.pagesDir);
44
+ // Sort pages to ensure static routes are matched before dynamic ones
45
+ this.pages.sort((a, b) => compareRoutes(a, b));
46
+ }
47
+ catch (error) {
48
+ console.error('Failed to load pages:', error);
49
+ throw new Error(`Failed to load pages: ${error instanceof Error ? error.message : String(error)}`);
50
+ }
51
+ }
52
+ /**
53
+ * Recursively scans the directory for page modules and adds them to the pages array.
54
+ * @param dir The current directory to scan.
55
+ * @param basePath The base path for constructing the route path.
56
+ */
57
+ async scanDirectory(dir, basePath = '') {
58
+ // Track if a dynamic folder has been found at this directory level
59
+ let dynamicFolderFound = false;
60
+ try {
61
+ const entries = readdirSync(dir, { withFileTypes: true });
62
+ for (const entry of entries) {
63
+ const entryPath = path.join(dir, entry.name);
64
+ const relativePath = path.join(basePath, entry.name);
65
+ if (entry.isDirectory()) {
66
+ // Handle dynamic directories (e.g., [id])
67
+ if (entry.name.startsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_START) &&
68
+ entry.name.endsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_END)) {
69
+ if (dynamicFolderFound) {
70
+ throw new Error(`Multiple dynamic page folders found in the same directory: '${entry.name}' conflicts with another dynamic folder.`);
71
+ }
72
+ dynamicFolderFound = true;
73
+ }
74
+ await this.scanDirectory(entryPath, relativePath);
75
+ }
76
+ else if (entry.isFile() &&
77
+ ROUTE_CONSTANTS.SUPPORTED_PAGE_EXTENSIONS.some((ext) => entry.name.endsWith(ext))) {
78
+ // Convert file path to route path and load the module
79
+ const routePath = this.convertFilePathToRoute(relativePath);
80
+ // Clean the route path
81
+ const cleanedRoutePath = this.cleanRoutePath(routePath);
82
+ // Get the module path
83
+ const modulePath = path.resolve(entryPath);
84
+ try {
85
+ // Import the module
86
+ const pageModule = await import(modulePath);
87
+ // Get the default export as the page handler
88
+ if (entry.name.endsWith('.tsx') &&
89
+ typeof pageModule.default !== 'function') {
90
+ throw new Error(`Page at ${entryPath} must export a default function as its handler.`);
91
+ }
92
+ // Create page definition
93
+ const pageDefWithSlash = {
94
+ path: cleanedRoutePath + '/',
95
+ handler: pageModule.default,
96
+ middleware: pageModule.middleware,
97
+ };
98
+ // Create page definition
99
+ const pageDef = {
100
+ path: cleanedRoutePath,
101
+ handler: pageModule.default,
102
+ middleware: pageModule.middleware,
103
+ };
104
+ // Add the page definition to the pages array
105
+ this.pages.push(pageDefWithSlash, pageDef);
106
+ }
107
+ catch (importError) {
108
+ console.error(`Failed to import module at ${modulePath}:`, importError);
109
+ }
110
+ }
111
+ }
112
+ }
113
+ catch (error) {
114
+ console.error(`Error scanning directory ${dir}:`, error);
115
+ throw error;
116
+ }
117
+ }
118
+ /**
119
+ * Converts a file path to a route path by processing dynamic segments,
120
+ * removing certain directory indicators, and applying a prefix if specified.
121
+ * @param filePath The file path to convert into a route path.
122
+ * @returns The converted route path string (before extension cleaning).
123
+ */
124
+ convertFilePathToRoute(filePath) {
125
+ // Split path into segments
126
+ const segments = filePath.split(path.sep);
127
+ const resultSegments = [];
128
+ for (let segment of segments) {
129
+ if (!segment)
130
+ continue; // Skip empty segments
131
+ // Skip grouping segments (e.g., (group))
132
+ if (segment.startsWith(ROUTE_CONSTANTS.GROUPING_FOLDER_START) &&
133
+ segment.endsWith(ROUTE_CONSTANTS.GROUPING_FOLDER_END))
134
+ continue;
135
+ // Convert dynamic segments from [param] to :param
136
+ if (segment.startsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_START) &&
137
+ segment.endsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_END)) {
138
+ const param = segment.slice(1, -1);
139
+ resultSegments.push(ROUTE_CONSTANTS.DYNAMIC_SEGMENT_PREFIX + param);
140
+ }
141
+ else {
142
+ resultSegments.push(segment);
143
+ }
144
+ }
145
+ // Construct the route with leading slash
146
+ let route = '/' + resultSegments.join('/');
147
+ // Apply prefix if provided
148
+ if (this.prefix) {
149
+ const cleanPrefixStr = cleanPrefix(this.prefix);
150
+ route = '/' + cleanPrefixStr + route;
151
+ }
152
+ // Remove trailing slash unless it's the root
153
+ if (route !== '/' && route.endsWith('/')) {
154
+ route = route.slice(0, -1);
155
+ }
156
+ return route;
157
+ }
158
+ /**
159
+ * Cleans a route path by handling index files and removing extensions.
160
+ * @param routePath The route path to clean
161
+ * @returns The cleaned route path
162
+ */
163
+ cleanRoutePath(routePath) {
164
+ // Break the route path into segments
165
+ const pathSegments = routePath.split('/');
166
+ // Get the last segment
167
+ if (pathSegments.length > 0) {
168
+ const lastSegment = pathSegments[pathSegments.length - 1];
169
+ // Check if the last segment is an index file
170
+ if (ROUTE_CONSTANTS.PAGE_INDEX_FILES.includes(lastSegment)) {
171
+ // Remove the last segment for index files
172
+ pathSegments.pop();
173
+ }
174
+ else {
175
+ // Remove file extension for non-index files
176
+ const extensionIndex = lastSegment.lastIndexOf('.');
177
+ if (extensionIndex > 0) {
178
+ pathSegments[pathSegments.length - 1] =
179
+ lastSegment.substring(0, extensionIndex);
180
+ }
181
+ }
182
+ }
183
+ // Join the segments back together
184
+ const finalPath = pathSegments.join('/') === '' ? '/' : pathSegments.join('/');
185
+ return finalPath;
186
+ }
187
+ /**
188
+ * Resolves the given request by finding a matching page and extracting dynamic parameters.
189
+ * @param request The request to resolve.
190
+ * @returns An object containing the matched page and parameters, or an empty params object if no match.
191
+ */
192
+ resolve(request) {
193
+ const url = new URL(request.url);
194
+ const reqPath = normalizePath(url.pathname);
195
+ console.debug(`Resolving route for path: ${reqPath}`);
196
+ for (const page of this.pages) {
197
+ const match = this.matchRoute(reqPath, page.path);
198
+ if (match) {
199
+ console.debug(`Route matched: ${page.path} with params:`, match);
200
+ return { page, params: match };
201
+ }
202
+ }
203
+ console.debug(`No matching route found for path: ${reqPath}`);
204
+ return { params: {} };
205
+ }
206
+ /**
207
+ * Checks if the request path matches the page path, extracting dynamic parameters if matched.
208
+ * @param requestPath The request path to check.
209
+ * @param pagePath The page path to match against.
210
+ * @returns A record of dynamic parameters if matched, otherwise null.
211
+ */
212
+ matchRoute(requestPath, pagePath) {
213
+ const reqSegments = requestPath.split('/').filter(Boolean);
214
+ const pageSegments = pagePath.split('/').filter(Boolean);
215
+ if (reqSegments.length !== pageSegments.length) {
216
+ return null;
217
+ }
218
+ const params = {};
219
+ for (let i = 0; i < reqSegments.length; i++) {
220
+ const pSegment = pageSegments[i];
221
+ const reqSegment = reqSegments[i];
222
+ if (pSegment.startsWith(ROUTE_CONSTANTS.DYNAMIC_SEGMENT_PREFIX)) {
223
+ const paramName = pSegment.slice(ROUTE_CONSTANTS.DYNAMIC_SEGMENT_PREFIX.length);
224
+ params[paramName] = reqSegment;
225
+ }
226
+ else if (pSegment !== reqSegment) {
227
+ return null;
228
+ }
229
+ }
230
+ return params;
231
+ }
232
+ }
@@ -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("Content-Type", "application/json");
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("Content-Type", "text/plain");
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("Content-Type", "text/html");
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("Location", url);
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("Error serving file:", error);
114
+ console.error('Error serving file:', error);
115
115
  this.status(404);
116
- this._body = "File not found";
116
+ this._body = 'File not found';
117
117
  return this.build();
118
118
  }
119
119
  }
@@ -1,4 +1,4 @@
1
- import type { ServerOptions, RequestHandler } from "../types";
1
+ import type { ServerOptions, RequestHandler } from '../types/index.js';
2
2
  export declare class Server {
3
3
  private options;
4
4
  private server;
@@ -8,12 +8,15 @@ export declare class Server {
8
8
  */
9
9
  constructor(options: ServerOptions);
10
10
  /**
11
- * Starts the server with the given port, handler, and callback.
11
+ * Starts the server with the given routes, handler, port, and callback.
12
+ * @param routes - The routes to be used by the server.
13
+ * @param handler - The handler to be used by the server.
12
14
  * @param port - The port to listen on.
13
- * @param handler - The request handler function.
14
- * @param cb - The callback function to be called when the server starts.
15
+ * @param cb - An optional callback function to be called when the server starts.
15
16
  */
16
- start(port: number, handler: RequestHandler, cb?: () => void): void;
17
+ start(routes: {
18
+ [key: string]: any;
19
+ } | undefined, handler: RequestHandler, port: number, cb?: () => void): void;
17
20
  /**
18
21
  * Stops the server.
19
22
  * If the server is currently running, this method will stop the server and
@@ -1,8 +1,10 @@
1
+ // Import stuff from Bun
2
+ import { serve } from 'bun';
1
3
  // Import stuff from core
2
- import { HttpRequest } from "./request.js";
3
- import { HttpResponse } from "./response.js";
4
+ import { HttpRequest } from './request.js';
5
+ import { HttpResponse } from './response.js';
4
6
  // Import stuff from utils
5
- import { errorResponse } from "../utils/error.js";
7
+ import { errorResponse } from '../utils/error.js';
6
8
  export class Server {
7
9
  options;
8
10
  server = null;
@@ -14,15 +16,17 @@ export class Server {
14
16
  this.options = options;
15
17
  }
16
18
  /**
17
- * Starts the server with the given port, handler, and callback.
19
+ * Starts the server with the given routes, handler, port, and callback.
20
+ * @param routes - The routes to be used by the server.
21
+ * @param handler - The handler to be used by the server.
18
22
  * @param port - The port to listen on.
19
- * @param handler - The request handler function.
20
- * @param cb - The callback function to be called when the server starts.
23
+ * @param cb - An optional callback function to be called when the server starts.
21
24
  */
22
- start(port, handler, cb) {
25
+ start(routes, handler, port, cb) {
23
26
  // Start Bun's native server using Bun.serve
24
- this.server = Bun.serve({
25
- port,
27
+ this.server = serve({
28
+ routes,
29
+ // Burger's fetch handler
26
30
  fetch: async (request) => {
27
31
  try {
28
32
  // Wrap the native Request with HttpRequest to get a BurgerRequest
@@ -37,6 +41,7 @@ export class Server {
37
41
  return errorResponse(error, request, this.options.debug ?? false);
38
42
  }
39
43
  },
44
+ port,
40
45
  });
41
46
  if (cb) {
42
47
  cb();
@@ -54,7 +59,7 @@ export class Server {
54
59
  stop() {
55
60
  if (this.server) {
56
61
  this.server.stop();
57
- console.log("Server stopped.");
62
+ console.log('Server stopped.');
58
63
  }
59
64
  }
60
65
  }
@@ -1,8 +1,9 @@
1
- import type { ServerOptions, Middleware } from "./types";
1
+ import type { ServerOptions, Middleware } from './types/index.js';
2
2
  export declare class Burger {
3
3
  private options;
4
4
  private server;
5
- private router?;
5
+ private apiRouter?;
6
+ private pageRouter?;
6
7
  private globalMiddleware;
7
8
  /**
8
9
  * Constructor for the Burger class.
@@ -27,5 +28,5 @@ export declare class Burger {
27
28
  */
28
29
  serve(port?: number, cb?: () => void): Promise<void>;
29
30
  }
30
- export { setDir } from "./utils/index.js";
31
- export type { ServerOptions, RequestHandler, BurgerRequest, BurgerResponse, Middleware, } from "./types/index.js";
31
+ export { setDir } from './utils/index.js';
32
+ export type { ServerOptions, RequestHandler, BurgerRequest, BurgerResponse, BurgerNext, Middleware, openapi, } from './types/index.js';
package/dist/src/index.js CHANGED
@@ -1,16 +1,16 @@
1
1
  // Import stuff from core
2
- import { Server } from "./core/server.js";
3
- import { Router } from "./core/router.js";
4
- import { HttpRequest } from "./core/request.js";
5
- import { HttpResponse } from "./core/response.js";
6
- import { generateOpenAPIDocument } from "./core/openapi.js";
7
- import { swaggerHtml } from "./core/swagger-ui.js";
2
+ import { Server } from './core/server.js';
3
+ import { ApiRouter } from './core/api-router.js';
4
+ import { PageRouter } from './core/page-router.js';
5
+ import { generateOpenAPIDocument } from './core/openapi.js';
6
+ import { swaggerHtml } from './core/swagger-ui.js';
8
7
  // Import middleware
9
- import { createValidationMiddleware } from "./middleware/validator.js";
8
+ import { createValidationMiddleware } from './middleware/validator.js';
10
9
  export class Burger {
11
10
  options;
12
11
  server;
13
- router;
12
+ apiRouter;
13
+ pageRouter;
14
14
  globalMiddleware = [];
15
15
  /**
16
16
  * Constructor for the Burger class.
@@ -26,7 +26,11 @@ export class Burger {
26
26
  this.server = new Server(options);
27
27
  // Initialize API router
28
28
  if (options.apiDir) {
29
- this.router = new Router(options.apiDir, "api");
29
+ this.apiRouter = new ApiRouter(options.apiDir, 'api');
30
+ }
31
+ // Initialize page router
32
+ if (options.pageDir) {
33
+ this.pageRouter = new PageRouter(options.pageDir, '');
30
34
  }
31
35
  // Add global middleware
32
36
  if (options.globalMiddleware) {
@@ -48,48 +52,65 @@ export class Burger {
48
52
  */
49
53
  async serve(port = 4000, cb) {
50
54
  // File-based routing mode
51
- if (this.router) {
52
- await this.router.loadRoutes();
53
- this.server.start(port, async (req) => {
54
- // Wrap the native request with helper methods
55
- const request = new HttpRequest(req);
56
- // Create a new instance of BurgerResponse for the handler
57
- const response = new HttpResponse();
55
+ const routes = {};
56
+ // Handle page routes
57
+ if (this.pageRouter) {
58
+ // Load Page routes
59
+ await this.pageRouter.loadPages();
60
+ // If there are any page routes, add them to the routes object
61
+ if (this.pageRouter.pages.length > 0) {
62
+ this.pageRouter.pages.forEach((page) => {
63
+ routes[page.path] = page.handler;
64
+ });
65
+ }
66
+ }
67
+ if (this.apiRouter) {
68
+ // Load API routes
69
+ await this.apiRouter.loadRoutes();
70
+ // Start the server
71
+ this.server.start(routes, async (req, res) => {
58
72
  // Create URL object
59
- const url = new URL(request.url);
73
+ const url = new URL(req.url);
60
74
  // Check if the request is for /openapi.json
61
- if (url.pathname === "/openapi.json") {
62
- if (this.router) {
75
+ if (url.pathname === '/openapi.json') {
76
+ if (this.apiRouter) {
63
77
  // Generate OpenAPI document
64
- const doc = generateOpenAPIDocument(this.router, this.options);
78
+ const doc = generateOpenAPIDocument(this.apiRouter, this.options);
65
79
  // Return it as JSON
66
- return response.json(doc);
80
+ return res.json(doc);
67
81
  }
68
82
  else {
69
- // Return an error if router is not available
70
- return response
83
+ // Return a descriptive error if router is not available
84
+ return res
71
85
  .status(500)
72
- .json({ error: "Router not available" });
86
+ .json({
87
+ error: 'API Router not configured',
88
+ message: 'Please provide an apiDir option when initializing the Burger instance to enable OpenAPI documentation.'
89
+ });
73
90
  }
74
91
  }
75
92
  // Serve the Swagger UI at /docs
76
- if (url.pathname === "/docs") {
77
- return response.html(swaggerHtml);
93
+ if (url.pathname === '/docs') {
94
+ return res.html(swaggerHtml);
78
95
  }
79
96
  // Get the route and params for the current request
80
- const { route, params } = this.router.resolve(req);
97
+ const { route, params } = this.apiRouter.resolve(req);
81
98
  if (!route) {
82
99
  // Return a 404 if no route is found
83
- return response.status(404).json({ error: "Route not found" });
100
+ return res
101
+ .status(404)
102
+ .json({ error: 'Route not found' });
84
103
  }
85
104
  // Add params to the request
86
- request.params = params;
105
+ req.params = params;
87
106
  // Get the handler for the current HTTP method
88
107
  const method = req.method.toUpperCase();
89
108
  const handler = route.handlers[method];
90
109
  if (!handler) {
91
110
  // Return a 405 if no handler is found
92
- return response.status(405).json({ error: "Method Not Allowed" });
111
+ return res
112
+ .status(405)
113
+ .json({ error: 'Method Not Allowed' });
93
114
  }
94
115
  /**
95
116
  * Build the middleware composition chain.
@@ -99,39 +120,43 @@ export class Burger {
99
120
  * 4. Execute the handler
100
121
  */
101
122
  // 1. Compose the Route-Specific Chain
102
- let routeChain = async () => handler(request, response);
123
+ let routeChain = async () => handler(req, res);
103
124
  if (route.middleware && route.middleware.length > 0) {
104
125
  // Wrap route-specific middleware (in reverse order to preserve order of execution)
105
126
  for (const mw of route.middleware.slice().reverse()) {
106
127
  const next = routeChain;
107
- routeChain = async () => mw(request, response, next);
128
+ routeChain = async () => mw(req, res, next);
108
129
  }
109
130
  }
110
131
  // 2. Insert Validation Middleware (if a schema exists)
111
132
  let composedChain = routeChain;
112
133
  if (route.schema) {
113
134
  const validationMw = createValidationMiddleware(route.schema);
114
- composedChain = async () => validationMw(request, response, routeChain);
135
+ composedChain = async () => validationMw(req, res, routeChain);
115
136
  }
116
137
  // 3. Wrap Global Middleware (in reverse order so that the first-added runs first)
117
138
  let finalHandler = composedChain;
118
139
  if (this.globalMiddleware.length > 0) {
119
- for (const mw of this.globalMiddleware.slice().reverse()) {
140
+ for (const mw of this.globalMiddleware
141
+ .slice()
142
+ .reverse()) {
120
143
  const next = finalHandler;
121
- finalHandler = async () => mw(request, response, next);
144
+ finalHandler = async () => mw(req, res, next);
122
145
  }
123
146
  }
124
147
  // Execute the full chain
125
148
  return await finalHandler();
126
- }, cb);
149
+ }, port, cb);
127
150
  }
128
151
  else {
129
152
  // Fallback to default handler if no router is provided
130
- this.server.start(port, async (_) => new Response("Hello from burger-api!", {
131
- headers: { "Content-Type": "text/plain" },
132
- }), cb);
153
+ this.server.start(undefined, async (_, res) => {
154
+ return res
155
+ .status(200)
156
+ .json({ message: 'Hello from burger-api!' });
157
+ }, port, cb);
133
158
  }
134
159
  }
135
160
  }
136
161
  // Export utils
137
- export { setDir } from "./utils/index.js";
162
+ export { setDir } from './utils/index.js';
@@ -1,4 +1,4 @@
1
- import type { Middleware, RouteSchema } from "../types/index.js";
1
+ import type { RouteSchema, Middleware } from '../types/index.js';
2
2
  /**
3
3
  * Creates a middleware function that validates request data according to the
4
4
  * given schema for the current HTTP method.
@@ -44,7 +44,7 @@ export function createValidationMiddleware(schema) {
44
44
  validated.params = methodSchema.params.parse(req.params);
45
45
  }
46
46
  catch (e) {
47
- errors.push({ field: "params", error: e.errors });
47
+ errors.push({ field: 'params', error: e.errors });
48
48
  }
49
49
  }
50
50
  // Validate query parameters.
@@ -53,17 +53,17 @@ export function createValidationMiddleware(schema) {
53
53
  validated.query = methodSchema.query.parse(Object.fromEntries(req.query.entries()));
54
54
  }
55
55
  catch (e) {
56
- errors.push({ field: "query", error: e.errors });
56
+ errors.push({ field: 'query', error: e.errors });
57
57
  }
58
58
  }
59
59
  // Validate request body.
60
60
  if (methodSchema.body) {
61
61
  // Check the Content-Type header.
62
- const contentType = req.headers.get("Content-Type") || "";
63
- if (!contentType.includes("application/json")) {
62
+ const contentType = req.headers.get('Content-Type') || '';
63
+ if (!contentType.includes('application/json')) {
64
64
  // If not JSON, push an error indicating the expected content type.
65
65
  errors.push({
66
- field: "body",
66
+ field: 'body',
67
67
  error: "Invalid Content-Type. Expected 'application/json'.",
68
68
  });
69
69
  }
@@ -74,7 +74,10 @@ export function createValidationMiddleware(schema) {
74
74
  validated.body = methodSchema.body.parse(bodyData);
75
75
  }
76
76
  catch (e) {
77
- errors.push({ field: "body", error: e.errors || e.message });
77
+ errors.push({
78
+ field: 'body',
79
+ error: e.errors || e.message,
80
+ });
78
81
  }
79
82
  }
80
83
  }
@@ -1,4 +1,4 @@
1
- import { z } from "zod";
1
+ import { z } from 'zod';
2
2
  export interface ServerOptions {
3
3
  /**
4
4
  * The title of the API. This is an optional property that can be used
@@ -25,10 +25,6 @@ export interface ServerOptions {
25
25
  * Global middleware to be executed before each request.
26
26
  */
27
27
  globalMiddleware?: Middleware[];
28
- /**
29
- * The templating engine to use for rendering HTML templates.
30
- */
31
- templatingEngine?: TemplatingEngine;
32
28
  /**
33
29
  * The version of the API. This is an optional property that can be used
34
30
  * to specify the version of the API.
@@ -152,6 +148,12 @@ export interface BurgerResponse {
152
148
  */
153
149
  original(body?: BodyInit | null, init?: ResponseInit): Response;
154
150
  }
151
+ /**
152
+ * Represents a next function in the request handling pipeline.
153
+ * This function is used to call the next middleware in the chain.
154
+ * It returns a Promise that resolves with a Response object.
155
+ */
156
+ export type BurgerNext = () => Promise<Response>;
155
157
  /**
156
158
  * Represents a request handler function.
157
159
  * Request handler functions receive a BurgerRequest and BurgerResponse as
@@ -174,7 +176,7 @@ export type RequestHandler = (request: BurgerRequest, response: BurgerResponse)
174
176
  * @param next - A function to call the next middleware in the chain.
175
177
  * @returns A Promise that resolves with the response.
176
178
  */
177
- export type Middleware = (request: BurgerRequest, response: BurgerResponse, next: () => Promise<Response>) => Promise<Response>;
179
+ export type Middleware = (request: BurgerRequest, response: BurgerResponse, next: BurgerNext) => Promise<Response>;
178
180
  export interface RouteDefinition {
179
181
  /**
180
182
  * The path of the route.
@@ -248,4 +250,8 @@ export type openapi = {
248
250
  };
249
251
  };
250
252
  };
251
- export type TemplatingEngine = (templatePath: string, props?: Record<string, any>) => Promise<string>;
253
+ export interface PageDefinition {
254
+ path: string;
255
+ handler: RequestHandler;
256
+ middleware?: RequestHandler[];
257
+ }
@@ -1 +1 @@
1
- import { z } from "zod";
1
+ import { z } from 'zod';