burger-api 0.5.1 → 0.5.2

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.
@@ -1,25 +1,47 @@
1
+ // Import stuff from node
1
2
  import { readdirSync } from 'fs';
2
3
  import * as path from 'path';
4
+ // Import utils
3
5
  import { cleanPrefix, normalizePath, compareRoutes, ROUTE_CONSTANTS, } from '../utils/index';
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
+ */
4
11
  export class PageRouter {
5
12
  pagesDir;
6
13
  prefix;
14
+ /** Array of loaded page definitions */
7
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
+ */
8
21
  constructor(pagesDir, prefix = '') {
9
22
  this.pagesDir = pagesDir;
10
23
  this.prefix = prefix;
11
24
  if (!pagesDir) {
12
25
  throw new Error('Pages directory path must be provided');
13
26
  }
27
+ // Normalize the pagesDir path
14
28
  this.pagesDir = path.normalize(pagesDir);
29
+ // Normalize the prefix if provided
15
30
  if (prefix) {
16
31
  this.prefix = cleanPrefix(prefix);
17
32
  }
18
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
+ */
19
39
  async loadPages() {
40
+ // Clear the pages array
20
41
  this.pages = [];
21
42
  try {
22
43
  await this.scanDirectory(this.pagesDir);
44
+ // Sort pages to ensure static routes are matched before dynamic ones
23
45
  this.pages.sort((a, b) => compareRoutes(a, b));
24
46
  }
25
47
  catch (error) {
@@ -27,7 +49,13 @@ export class PageRouter {
27
49
  throw new Error(`Failed to load pages: ${error instanceof Error ? error.message : String(error)}`);
28
50
  }
29
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
+ */
30
57
  async scanDirectory(dir, basePath = '') {
58
+ // Track if a dynamic folder has been found at this directory level
31
59
  let dynamicFolderFound = false;
32
60
  try {
33
61
  const entries = readdirSync(dir, { withFileTypes: true });
@@ -35,6 +63,7 @@ export class PageRouter {
35
63
  const entryPath = path.join(dir, entry.name);
36
64
  const relativePath = path.join(basePath, entry.name);
37
65
  if (entry.isDirectory()) {
66
+ // Handle dynamic directories (e.g., [id])
38
67
  if (entry.name.startsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_START) &&
39
68
  entry.name.endsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_END)) {
40
69
  if (dynamicFolderFound) {
@@ -46,25 +75,33 @@ export class PageRouter {
46
75
  }
47
76
  else if (entry.isFile() &&
48
77
  ROUTE_CONSTANTS.SUPPORTED_PAGE_EXTENSIONS.some((ext) => entry.name.endsWith(ext))) {
78
+ // Convert file path to route path and load the module
49
79
  const routePath = this.convertFilePathToRoute(relativePath);
80
+ // Clean the route path
50
81
  const cleanedRoutePath = this.cleanRoutePath(routePath);
82
+ // Get the module path
51
83
  const modulePath = path.resolve(entryPath);
52
84
  try {
85
+ // Import the module
53
86
  const pageModule = await import(modulePath);
87
+ // Get the default export as the page handler
54
88
  if (entry.name.endsWith('.tsx') &&
55
89
  typeof pageModule.default !== 'function') {
56
90
  throw new Error(`Page at ${entryPath} must export a default function as its handler.`);
57
91
  }
92
+ // Create page definition
58
93
  const pageDefWithSlash = {
59
94
  path: cleanedRoutePath + '/',
60
95
  handler: pageModule.default,
61
96
  middleware: pageModule.middleware,
62
97
  };
98
+ // Create page definition
63
99
  const pageDef = {
64
100
  path: cleanedRoutePath,
65
101
  handler: pageModule.default,
66
102
  middleware: pageModule.middleware,
67
103
  };
104
+ // Add the page definition to the pages array
68
105
  this.pages.push(pageDefWithSlash, pageDef);
69
106
  }
70
107
  catch (importError) {
@@ -78,15 +115,24 @@ export class PageRouter {
78
115
  throw error;
79
116
  }
80
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
+ */
81
124
  convertFilePathToRoute(filePath) {
125
+ // Split path into segments
82
126
  const segments = filePath.split(path.sep);
83
127
  const resultSegments = [];
84
128
  for (let segment of segments) {
85
129
  if (!segment)
86
- continue;
130
+ continue; // Skip empty segments
131
+ // Skip grouping segments (e.g., (group))
87
132
  if (segment.startsWith(ROUTE_CONSTANTS.GROUPING_FOLDER_START) &&
88
133
  segment.endsWith(ROUTE_CONSTANTS.GROUPING_FOLDER_END))
89
134
  continue;
135
+ // Convert dynamic segments from [param] to :param
90
136
  if (segment.startsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_START) &&
91
137
  segment.endsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_END)) {
92
138
  const param = segment.slice(1, -1);
@@ -96,24 +142,37 @@ export class PageRouter {
96
142
  resultSegments.push(segment);
97
143
  }
98
144
  }
145
+ // Construct the route with leading slash
99
146
  let route = '/' + resultSegments.join('/');
147
+ // Apply prefix if provided
100
148
  if (this.prefix) {
101
149
  const cleanPrefixStr = cleanPrefix(this.prefix);
102
150
  route = '/' + cleanPrefixStr + route;
103
151
  }
152
+ // Remove trailing slash unless it's the root
104
153
  if (route !== '/' && route.endsWith('/')) {
105
154
  route = route.slice(0, -1);
106
155
  }
107
156
  return route;
108
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
+ */
109
163
  cleanRoutePath(routePath) {
164
+ // Break the route path into segments
110
165
  const pathSegments = routePath.split('/');
166
+ // Get the last segment
111
167
  if (pathSegments.length > 0) {
112
168
  const lastSegment = pathSegments[pathSegments.length - 1];
169
+ // Check if the last segment is an index file
113
170
  if (ROUTE_CONSTANTS.PAGE_INDEX_FILES.includes(lastSegment)) {
171
+ // Remove the last segment for index files
114
172
  pathSegments.pop();
115
173
  }
116
174
  else {
175
+ // Remove file extension for non-index files
117
176
  const extensionIndex = lastSegment.lastIndexOf('.');
118
177
  if (extensionIndex > 0) {
119
178
  pathSegments[pathSegments.length - 1] =
@@ -121,9 +180,15 @@ export class PageRouter {
121
180
  }
122
181
  }
123
182
  }
183
+ // Join the segments back together
124
184
  const finalPath = pathSegments.join('/') === '' ? '/' : pathSegments.join('/');
125
185
  return finalPath;
126
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
+ */
127
192
  resolve(request) {
128
193
  const url = new URL(request.url);
129
194
  const reqPath = normalizePath(url.pathname);
@@ -138,6 +203,12 @@ export class PageRouter {
138
203
  console.debug(`No matching route found for path: ${reqPath}`);
139
204
  return { params: {} };
140
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
+ */
141
212
  matchRoute(requestPath, pagePath) {
142
213
  const reqSegments = requestPath.split('/').filter(Boolean);
143
214
  const pageSegments = pagePath.split('/').filter(Boolean);
@@ -2,9 +2,19 @@ import type { ServerOptions, FetchHandler } from '../types/index';
2
2
  export declare class Server {
3
3
  private options;
4
4
  private server;
5
+ /**
6
+ * Initializes a new instance of the Server class with the given options.
7
+ * @param options - Configuration options for the server.
8
+ */
5
9
  constructor(options: ServerOptions);
6
10
  start(routes: {
7
11
  [key: string]: any;
8
12
  } | undefined, handler: FetchHandler, port: number, cb?: () => void): void;
13
+ /**
14
+ * Stops the server.
15
+ * If the server is currently running, this method will stop the server and
16
+ * log a message to the console indicating that the server has been stopped.
17
+ * If the server is not running, this method does nothing.
18
+ */
9
19
  stop(): void;
10
20
  }
@@ -1,22 +1,32 @@
1
+ // Import stuff from Bun
1
2
  import { serve } from 'bun';
3
+ // Import stuff from utils
2
4
  import { errorResponse } from '../utils/error';
3
5
  export class Server {
4
6
  options;
5
7
  server = null;
8
+ /**
9
+ * Initializes a new instance of the Server class with the given options.
10
+ * @param options - Configuration options for the server.
11
+ */
6
12
  constructor(options) {
7
13
  this.options = options;
8
14
  }
9
15
  start(routes, handler, port, cb) {
16
+ // Start Bun's native server using Bun.serve
10
17
  this.server = serve({
11
18
  routes,
19
+ // Bun's fetch handler
12
20
  fetch: async (request) => {
13
21
  try {
14
22
  return await handler(request);
15
23
  }
16
24
  catch (error) {
25
+ // Return a custom error response
17
26
  return errorResponse(error, request, this.options.debug ?? false);
18
27
  }
19
28
  },
29
+ // Global error handler
20
30
  error(error) {
21
31
  console.error(error);
22
32
  return new Response(`Internal Server Error: ${error.message}`, {
@@ -35,6 +45,12 @@ export class Server {
35
45
  console.log(`🍔 BurgerAPI is running at: http://${this.options.hostname || 'localhost'}:${port}`);
36
46
  }
37
47
  }
48
+ /**
49
+ * Stops the server.
50
+ * If the server is currently running, this method will stop the server and
51
+ * log a message to the console indicating that the server has been stopped.
52
+ * If the server is not running, this method does nothing.
53
+ */
38
54
  stop() {
39
55
  if (this.server) {
40
56
  this.server.stop();
@@ -1,19 +1,76 @@
1
1
  import type { ServerOptions } from './types/index';
2
2
  export declare class Burger {
3
3
  private options;
4
+ /**
5
+ * The server instance
6
+ */
4
7
  private server;
8
+ /**
9
+ * The API router instance
10
+ */
5
11
  private apiRouter?;
12
+ /**
13
+ * The page router instance
14
+ */
6
15
  private pageRouter?;
16
+ /**
17
+ * The global middleware
18
+ */
7
19
  private globalMiddleware;
20
+ /**
21
+ * The OpenAPI document
22
+ */
8
23
  private openApiDoc;
24
+ /**
25
+ * The routes object
26
+ */
9
27
  private routes;
28
+ /**
29
+ * Pre-computed responses for reuse
30
+ */
10
31
  private readonly METHOD_NOT_ALLOWED;
32
+ /**
33
+ * The not found response
34
+ */
11
35
  private readonly NOT_FOUND;
36
+ /**
37
+ * The OpenAPI error response
38
+ */
12
39
  private readonly OPENAPI_ERROR;
40
+ /**
41
+ * Constructor for the Burger class.
42
+ * @param options - The options for the server and router.
43
+ * The options object should contain the following properties:
44
+ * - port: The port number to listen on.
45
+ * - apiDir: The directory path to load API routes from.
46
+ * - pageDir: The directory path to load page routes from.
47
+ * - middleware: An array of global middleware functions.
48
+ */
13
49
  constructor(options: ServerOptions);
50
+ /**
51
+ * Process the page routes and add them to the routes object
52
+ * @returns A promise that resolves to a boolean
53
+ */
14
54
  private processPageRoutes;
55
+ /**
56
+ * Process the API routes and add them to the routes object
57
+ * @returns A promise that resolves to a boolean
58
+ */
15
59
  private processApiRoutes;
60
+ /**
61
+ * Process the middleware and handler
62
+ * @param request - The request object
63
+ * @param middlewares - The middleware array
64
+ * @param handler - The handler function
65
+ * @returns A promise that resolves to a response
66
+ */
16
67
  private processMiddleware;
68
+ /**
69
+ * Starts the server and begins listening for incoming requests.
70
+ * @param port - The port number to listen on. Defaults to `4000`.
71
+ * @param cb - An optional cb function to be executed when the server is listening.
72
+ * @returns A Promise that resolves when the server has started listening.
73
+ */
17
74
  serve(port?: number, cb?: () => void): Promise<void>;
18
75
  }
19
76
  export { setDir } from './utils/index';
package/dist/src/index.js CHANGED
@@ -1,75 +1,162 @@
1
+ // Import stuff from core
1
2
  import { Server } from './core/server';
2
3
  import { ApiRouter } from './core/api-router';
3
4
  import { PageRouter } from './core/page-router';
4
5
  import { generateOpenAPIDocument } from './core/openapi';
5
6
  import { swaggerHtml } from './core/swagger-ui';
7
+ // Import utils
6
8
  import { collectRoutes } from './utils/index';
7
9
  import { METHOD_NOT_ALLOWED, NOT_FOUND, OPENAPI_ERROR } from './utils/response';
8
10
  import { extractPathnameFromUrl, extractWildcardParams, } from './utils/wildcard';
11
+ // Import middleware
9
12
  import { createValidationMiddleware } from './middleware/validator';
10
13
  export class Burger {
11
14
  options;
15
+ /**
16
+ * The server instance
17
+ */
12
18
  server;
19
+ /**
20
+ * The API router instance
21
+ */
13
22
  apiRouter;
23
+ /**
24
+ * The page router instance
25
+ */
14
26
  pageRouter;
27
+ /**
28
+ * The global middleware
29
+ */
15
30
  globalMiddleware = [];
31
+ /**
32
+ * The OpenAPI document
33
+ */
16
34
  openApiDoc = null;
35
+ /**
36
+ * The routes object
37
+ */
17
38
  routes = {};
39
+ /**
40
+ * Pre-computed responses for reuse
41
+ */
18
42
  METHOD_NOT_ALLOWED = METHOD_NOT_ALLOWED;
43
+ /**
44
+ * The not found response
45
+ */
19
46
  NOT_FOUND = NOT_FOUND;
47
+ /**
48
+ * The OpenAPI error response
49
+ */
20
50
  OPENAPI_ERROR = OPENAPI_ERROR;
51
+ /**
52
+ * Constructor for the Burger class.
53
+ * @param options - The options for the server and router.
54
+ * The options object should contain the following properties:
55
+ * - port: The port number to listen on.
56
+ * - apiDir: The directory path to load API routes from.
57
+ * - pageDir: The directory path to load page routes from.
58
+ * - middleware: An array of global middleware functions.
59
+ */
21
60
  constructor(options) {
22
61
  this.options = options;
62
+ // Create server instance
23
63
  this.server = new Server(options);
64
+ // Fast initialization for routers with nullish coalescing
24
65
  const { apiDir, pageDir, apiPrefix, pagePrefix, globalMiddleware } = options;
66
+ // Initialize API router if apiDir is provided
25
67
  this.apiRouter = apiDir
26
68
  ? new ApiRouter(apiDir, apiPrefix || 'api')
27
69
  : undefined;
70
+ // Initialize page router if pageDir is provided
28
71
  this.pageRouter = pageDir
29
72
  ? new PageRouter(pageDir, pagePrefix || '')
30
73
  : undefined;
74
+ // Add global middleware if any
31
75
  this.globalMiddleware = globalMiddleware?.length
32
76
  ? globalMiddleware.slice()
33
77
  : [];
34
78
  }
79
+ /**
80
+ * Process the page routes and add them to the routes object
81
+ * @returns A promise that resolves to a boolean
82
+ */
35
83
  async processPageRoutes() {
84
+ // If no page router, return false
36
85
  if (!this.pageRouter)
37
86
  return false;
87
+ // Load pages routes
38
88
  await this.pageRouter.loadPages();
89
+ // If there are any page routes, add them to the routes object
39
90
  const pages = this.pageRouter.pages;
91
+ // Get the length of the pages routes
40
92
  const pageCount = pages.length;
93
+ // If no pages, return false
41
94
  if (pageCount === 0)
42
95
  return false;
96
+ // Loop through the pages
43
97
  for (let i = 0; i < pageCount; i++) {
98
+ // Get the current page
44
99
  const page = pages[i];
100
+ // Add the page to the routes
45
101
  this.routes[page.path] = page.handler;
46
102
  }
103
+ // Return true if there are any pages
47
104
  return true;
48
105
  }
106
+ /**
107
+ * Process the API routes and add them to the routes object
108
+ * @returns A promise that resolves to a boolean
109
+ */
49
110
  async processApiRoutes() {
111
+ // If no api router, return false
50
112
  if (!this.apiRouter)
51
113
  return false;
114
+ // Load API routes
52
115
  await this.apiRouter.loadRoutes();
116
+ // Collect API routes
53
117
  const apiRoutes = collectRoutes(this.apiRouter.routes);
118
+ // Get the length of the API routes
54
119
  const routeCount = apiRoutes.length;
120
+ // If there are no API routes, return false
55
121
  if (routeCount === 0)
56
122
  return false;
123
+ // Generate OpenAPI document and cache it
57
124
  this.openApiDoc = generateOpenAPIDocument(apiRoutes, this.options);
125
+ // Cache frequently accessed properties
58
126
  const routes = this.routes;
127
+ // Get the global middleware
59
128
  const globalMiddleware = this.globalMiddleware;
129
+ // Get the length of the global middleware
60
130
  const globalMiddlewareLen = globalMiddleware.length;
131
+ // Process each route with optimized handler creation
61
132
  for (let i = 0; i < routeCount; i++) {
133
+ /**
134
+ * ================================================
135
+ * Pre-compute the required functionality start
136
+ * ================================================
137
+ */
138
+ // Get the current route object
62
139
  const route = apiRoutes[i];
140
+ // Destructure the route object
63
141
  const { path, schema, middleware: routeMiddleware, handlers, } = route;
142
+ // Get length of route specific middleware
64
143
  const routeMiddlewareLen = routeMiddleware?.length || 0;
144
+ // Check if schema exists
65
145
  const hasSchema = !!schema;
146
+ // Optimize middleware array initialization by pre-allocating size
66
147
  const totalMiddlewareCount = globalMiddlewareLen + (hasSchema ? 1 : 0) + routeMiddlewareLen;
148
+ // Create optimized route handler
67
149
  if (totalMiddlewareCount === 0) {
150
+ // Ultra-fast path: no middleware
151
+ // Pre-compute wildcard segment count for faster extraction
68
152
  const isWildcard = route.isWildcard;
153
+ // Calculate how many segments come before the wildcard
154
+ // E.g., "/api/users/:userId/*" has 3 segments before wildcard (api, users, :userId)
69
155
  const baseSegmentCount = isWildcard
70
- ? path.split('/').filter(Boolean).length - 1
156
+ ? path.split('/').filter(Boolean).length - 1 // Subtract 1 for the * itself
71
157
  : 0;
72
158
  routes[path] = (request) => {
159
+ // Extract wildcard params if this is a wildcard route
73
160
  if (isWildcard) {
74
161
  const pathname = extractPathnameFromUrl(request.url);
75
162
  extractWildcardParams(request, pathname, baseSegmentCount);
@@ -79,24 +166,39 @@ export class Burger {
79
166
  };
80
167
  }
81
168
  else {
169
+ // Pre-compute middleware array with known size
82
170
  const middlewares = new Array(totalMiddlewareCount);
171
+ // Initialize index to track the current middleware
83
172
  let index = 0;
173
+ // Copy global middleware (most common case)
84
174
  for (let j = 0; j < globalMiddlewareLen; j++) {
85
175
  middlewares[index++] = globalMiddleware[j];
86
176
  }
177
+ // Add validation middleware if needed
87
178
  if (hasSchema) {
88
179
  middlewares[index++] = createValidationMiddleware(schema);
89
180
  }
181
+ // Add route-specific middlewares
90
182
  if (routeMiddleware) {
91
183
  for (let j = 0; j < routeMiddlewareLen; j++) {
92
184
  middlewares[index++] = routeMiddleware[j];
93
185
  }
94
186
  }
187
+ /**
188
+ * ================================================
189
+ * Pre-compute the required functionality end
190
+ * ================================================
191
+ */
192
+ // Pre-compute wildcard segment count for faster extraction
95
193
  const isWildcard = route.isWildcard;
194
+ // Calculate how many segments come before the wildcard
195
+ // E.g., "/api/users/:userId/*" has 3 segments before wildcard (api, users, :userId)
96
196
  const baseSegmentCount = isWildcard
97
- ? path.split('/').filter(Boolean).length - 1
197
+ ? path.split('/').filter(Boolean).length - 1 // Subtract 1 for the * itself
98
198
  : 0;
199
+ // Create handler with middleware
99
200
  routes[path] = (request) => {
201
+ // Extract wildcard params if this is a wildcard route
100
202
  if (isWildcard) {
101
203
  const pathname = extractPathnameFromUrl(request.url);
102
204
  extractWildcardParams(request, pathname, baseSegmentCount);
@@ -107,80 +209,129 @@ export class Burger {
107
209
  return this.processMiddleware(request, middlewares, handler);
108
210
  };
109
211
  }
212
+ // For wildcard routes, also register the base path
213
+ // Bun's /* wildcard may not match the base path itself, so we register both
110
214
  if (route.isWildcard && path.endsWith('/*')) {
111
- const basePath = path.slice(0, -2);
215
+ const basePath = path.slice(0, -2); // Remove "/*" to get base path
216
+ // Only register base path if no static route exists (preserve priority)
217
+ // Static routes have highest priority: Static > Dynamic > Wildcard
112
218
  if (!routes[basePath]) {
219
+ // No static route found, register wildcard for base path
113
220
  routes[basePath] = routes[path];
114
221
  }
222
+ // If static route exists, it takes priority (correct behavior)
115
223
  }
116
224
  }
225
+ // Add special routes for OpenAPI
117
226
  routes['/openapi.json'] = () => this.openApiDoc
118
227
  ? Response.json(this.openApiDoc)
119
228
  : this.OPENAPI_ERROR;
229
+ // Add special route for Swagger UI
120
230
  routes['/docs'] = () => new Response(swaggerHtml, {
121
231
  headers: { 'Content-Type': 'text/html' },
122
232
  });
123
233
  return true;
124
234
  }
235
+ /**
236
+ * Process the middleware and handler
237
+ * @param request - The request object
238
+ * @param middlewares - The middleware array
239
+ * @param handler - The handler function
240
+ * @returns A promise that resolves to a response
241
+ */
125
242
  async processMiddleware(request, middlewares, handler) {
243
+ // Get the length of the middleware array
126
244
  const middlewareLen = middlewares.length;
245
+ // Fast path: single middleware with no after functions
127
246
  if (middlewareLen === 1) {
247
+ // Get the first middleware
128
248
  const result = await middlewares[0](request);
249
+ // If the result is a response, return it
129
250
  if (result instanceof Response) {
130
251
  return result;
131
252
  }
253
+ // If the result is not a function, return the handler
132
254
  if (typeof result !== 'function') {
133
255
  return handler(request);
134
256
  }
257
+ // If the result is a function, return the result of the handler
135
258
  return result(await handler(request));
136
259
  }
260
+ // Stack to store "after" functions
261
+ // Regular path with pre-allocated afterStack
137
262
  const afterStack = new Array(middlewareLen);
263
+ // Initialize the after middleware counter
138
264
  let afterCount = 0;
265
+ // Process "before" logic
139
266
  for (let i = 0; i < middlewareLen; i++) {
267
+ // Get the current middleware
140
268
  const result = await middlewares[i](request);
269
+ // If the result is a response
141
270
  if (result instanceof Response) {
271
+ // Short-circuit with a response, but still run collected after middlewares (e.g., CORS)
142
272
  let response = result;
273
+ // Fast paths for after functions
143
274
  if (afterCount === 0) {
144
275
  return response;
145
276
  }
146
277
  if (afterCount === 1) {
147
278
  return afterStack[0](response);
148
279
  }
280
+ // Apply after middlewares in reverse order (LIFO)
149
281
  for (let j = afterCount - 1; j >= 0; j--) {
150
282
  response = await afterStack[j](response);
151
283
  }
152
284
  return response;
153
285
  }
286
+ // If the result is a function, save it to the afterStack
154
287
  else if (typeof result === 'function') {
155
288
  afterStack[afterCount++] = result;
156
289
  }
290
+ // If undefined, proceed to next middleware
157
291
  }
292
+ // Get response from handler
158
293
  let response = await handler(request);
294
+ // Fast path: no after functions
159
295
  if (afterCount === 0) {
160
296
  return response;
161
297
  }
298
+ // Fast path: single after function
162
299
  if (afterCount === 1) {
163
300
  return afterStack[0](response);
164
301
  }
302
+ // Process "after" logic in reverse order
165
303
  for (let i = afterCount - 1; i >= 0; i--) {
166
304
  response = await afterStack[i](response);
167
305
  }
306
+ // Return the response
168
307
  return response;
169
308
  }
309
+ /**
310
+ * Starts the server and begins listening for incoming requests.
311
+ * @param port - The port number to listen on. Defaults to `4000`.
312
+ * @param cb - An optional cb function to be executed when the server is listening.
313
+ * @returns A Promise that resolves when the server has started listening.
314
+ */
170
315
  async serve(port = 4000, cb) {
316
+ // Process routes in parallel if possible
171
317
  const [pagesConfigured, apiConfigured] = await Promise.all([
172
318
  this.processPageRoutes(),
173
319
  this.processApiRoutes(),
174
320
  ]);
321
+ // Flag to track if any routes were loaded
175
322
  const routesConfigured = pagesConfigured || apiConfigured;
323
+ // If routes were configured, start the server
176
324
  if (routesConfigured) {
325
+ // Start the server
177
326
  this.server.start(this.routes, async () => {
178
327
  return this.NOT_FOUND;
179
328
  }, port, cb);
180
329
  }
181
330
  else {
331
+ // If no routes were configured, log an error
182
332
  console.error('Error: No routes configured! Please provide either apiDir with route.ts files or pageDir with html files when initializing the Burger Class.');
183
333
  }
184
334
  }
185
335
  }
336
+ // Export utils
186
337
  export { setDir } from './utils/index';