burger-api 0.5.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -5,7 +5,7 @@
5
5
  [![Under Development](https://img.shields.io/badge/under%20development-red.svg)](https://github.com/isfhan/burger-api)
6
6
  [![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
7
7
  [![Bun](https://img.shields.io/badge/Bun-1.2.20-black?logo=bun)](https://bun.sh)
8
- [![Version](https://img.shields.io/badge/version-0.5.0-green.svg)](https://github.com/isfhan/burger-api/releases)
8
+ [![Version](https://img.shields.io/badge/version-0.5.1-green.svg)](https://github.com/isfhan/burger-api/releases)
9
9
 
10
10
  **burger-api** is a modern, open source API framework built on
11
11
  [Bun.js](https://bun.sh). It combines the simplicity of file-based routing with
@@ -66,7 +66,14 @@ burger-api is built to offer a robust developer experience through:
66
66
 
67
67
  ## 📣 Changelog
68
68
 
69
- ### Latest Version: 0.5.0 (November 1, 2025)
69
+ ### Latest Version: 0.5.1 (December 2025)
70
+
71
+ - 🔧 **Internal Improvements:**
72
+ - Refactored wildcard parameter extraction logic into reusable utility functions
73
+ - Enabled `removeComments` in build configuration to reduce bundle size
74
+ - Added test suites and README files for all example projects
75
+
76
+ ### Previous Version: 0.5.0 (November 1, 2025)
70
77
 
71
78
  - 🌟 **Feature:** Auto-injected OPTIONS handler for CORS preflight:
72
79
 
@@ -1,68 +1,15 @@
1
1
  import type { RouteDefinition, TrieNode } from '../types/index';
2
- /**
3
- * ApiRouter class for handling file-based routing.
4
- * Loads routes from a directory structure and matches requests to the appropriate route handlers.
5
- * Supports dynamic segments (e.g., [id] ,(group),[...]) and HTTP method handlers.
6
- * Routes are sorted to prioritize static routes over dynamic and wildcard ones to prevent overlapping route issues.
7
- */
8
2
  export declare class ApiRouter {
9
3
  private routesDir;
10
4
  private prefix;
11
- /** The root of the trie where all routes will begin*/
12
5
  private root;
13
- /**
14
- * Constructor for the ApiRouter class.
15
- * @param routesDir The directory path where route modules are located.
16
- * @param prefix Optional prefix to prepend to all routes (e.g., "api" becomes "/api/...").
17
- * @throws {Error} If the routes directory path is not provided.
18
- */
19
6
  constructor(routesDir: string, prefix?: string);
20
- /**
21
- * Getter for the routes trie.
22
- * @returns The root of the trie.
23
- */
24
7
  get routes(): TrieNode;
25
- /**
26
- * Loads all routes from the routes directory into the trie structure.
27
- * @returns {Promise<void>} A promise that resolves when all routes are loaded.
28
- * @throws {Error} If the routes directory is not found or if an error occurs during route loading.
29
- */
30
8
  loadRoutes(): Promise<void>;
31
- /**
32
- * Inserts a route definition into the trie structure.
33
- * @param routeDef The route definition to insert, containing path, handlers, middleware, schema, and OpenAPI metadata.
34
- * @throws {Error} If the route definition is invalid or causes a conflict in the trie.
35
- */
36
9
  private insertRoute;
37
- /**
38
- * Recursively scans a directory for route modules (route.ts files) and loads them into the trie.
39
- * @param dir The current directory path to scan.
40
- * @param basePath The base path used to construct route paths from the directory structure.
41
- * @returns {Promise<void>} A promise that resolves when the directory scan is complete.
42
- * @throws {Error} If multiple dynamic folders are found at the same level or if directory access fails.
43
- */
44
10
  private scanDirectory;
45
- /**
46
- * Loads a route module from a file and inserts it into the trie.
47
- * @param entryPath The full file system path to the route module (route.ts).
48
- * @param relativePath The relative path used to construct the route path.
49
- * @returns {Promise<void>} A promise that resolves when the module is loaded and inserted.
50
- * @throws {Error} If the route module fails to load or is invalid.
51
- */
52
11
  private loadRouteModule;
53
- /**
54
- * Converts a file path to a route path by processing dynamic segments and wildcard segments applying the prefix.
55
- * @param filePath The file path to convert (e.g., "users/[id]/route.ts" , "users/[...slug]/route.ts").
56
- * @returns {string} The converted route path (e.g., "/users/:id" , "/users/*slug").
57
- */
58
12
  private convertFilePathToRoute;
59
- /**
60
- * Resolves a request to a route definition and its parameters.
61
- * @param pathname The normalized request pathname.
62
- * @param method The uppercase HTTP method.
63
- * @returns {{ route?: RouteDefinition; params: Record<string, string>; wildcardParams?: string[] }} An object containing the matched route (if any), extracted parameters, and wildcard segments (if applicable).
64
- * @throws {Error} If the request URL is malformed.
65
- */
66
13
  resolve(pathname: string, method: string): {
67
14
  route?: RouteDefinition;
68
15
  params: Record<string, string>;
@@ -1,25 +1,10 @@
1
- // Import stuff from node
2
1
  import { readdir } from 'fs/promises';
3
2
  import * as path from 'path';
4
- // Import utils
5
3
  import { cleanPrefix, normalizePath, ROUTE_CONSTANTS, HTTP_METHODS, } from '../utils/index';
6
- /**
7
- * ApiRouter class for handling file-based routing.
8
- * Loads routes from a directory structure and matches requests to the appropriate route handlers.
9
- * Supports dynamic segments (e.g., [id] ,(group),[...]) and HTTP method handlers.
10
- * Routes are sorted to prioritize static routes over dynamic and wildcard ones to prevent overlapping route issues.
11
- */
12
4
  export class ApiRouter {
13
5
  routesDir;
14
6
  prefix;
15
- /** The root of the trie where all routes will begin*/
16
7
  root = { children: new Map() };
17
- /**
18
- * Constructor for the ApiRouter class.
19
- * @param routesDir The directory path where route modules are located.
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.
22
- */
23
8
  constructor(routesDir, prefix = '') {
24
9
  this.routesDir = routesDir;
25
10
  this.prefix = prefix;
@@ -27,18 +12,9 @@ export class ApiRouter {
27
12
  throw new Error('Routes directory path is required');
28
13
  }
29
14
  }
30
- /**
31
- * Getter for the routes trie.
32
- * @returns The root of the trie.
33
- */
34
15
  get routes() {
35
16
  return this.root;
36
17
  }
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.
41
- */
42
18
  async loadRoutes() {
43
19
  try {
44
20
  await this.scanDirectory(this.routesDir);
@@ -48,17 +24,11 @@ export class ApiRouter {
48
24
  throw new Error(`Failed to load routes: ${errorMessage}`);
49
25
  }
50
26
  }
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
27
  insertRoute(routeDef) {
57
28
  let node = this.root;
58
29
  const segments = routeDef.path.split('/').filter(Boolean);
59
30
  for (const segment of segments) {
60
31
  if (segment.startsWith(':')) {
61
- // Handle dynamic segments (:param)
62
32
  if (!node.paramChild) {
63
33
  node.paramChild = { children: new Map() };
64
34
  }
@@ -66,15 +36,13 @@ export class ApiRouter {
66
36
  node.paramName = segment.slice(1);
67
37
  }
68
38
  else if (segment.startsWith('*')) {
69
- // Handle wildcard segments (*param)
70
39
  if (!node.wildcardChild) {
71
40
  node.wildcardChild = { children: new Map() };
72
41
  }
73
42
  node = node.wildcardChild;
74
- node.isWildcard = true; // Mark as wildcard route
43
+ node.isWildcard = true;
75
44
  }
76
45
  else {
77
- // Handle static segments
78
46
  if (!node.children.has(segment)) {
79
47
  node.children.set(segment, { children: new Map() });
80
48
  }
@@ -83,15 +51,7 @@ export class ApiRouter {
83
51
  }
84
52
  node.route = routeDef;
85
53
  }
86
- /**
87
- * Recursively scans a directory for route modules (route.ts files) and loads them into the trie.
88
- * @param dir The current directory path to scan.
89
- * @param basePath The base path used to construct route paths from the directory structure.
90
- * @returns {Promise<void>} A promise that resolves when the directory scan is complete.
91
- * @throws {Error} If multiple dynamic folders are found at the same level or if directory access fails.
92
- */
93
54
  async scanDirectory(dir, basePath = '') {
94
- // Track route types at this directory level to prevent conflicts
95
55
  let dynamicFolderFound = false;
96
56
  let wildcardFolderFound = false;
97
57
  try {
@@ -100,12 +60,10 @@ export class ApiRouter {
100
60
  const entryPath = path.join(dir, entry.name);
101
61
  const relativePath = path.join(basePath, entry.name);
102
62
  if (entry.isDirectory()) {
103
- // Check if this is a dynamic or wildcard directory
104
63
  const isDynamic = entry.name.startsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_START) &&
105
64
  entry.name.endsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_END) &&
106
65
  entry.name !== ROUTE_CONSTANTS.WILDCARD_SIMPLE;
107
66
  const isWildcard = entry.name === ROUTE_CONSTANTS.WILDCARD_SIMPLE;
108
- // Prevent conflicts between dynamic and wildcard routes
109
67
  if (isDynamic && wildcardFolderFound) {
110
68
  throw new Error(`Cannot mix dynamic and wildcard route folders in the same directory. ` +
111
69
  `Found dynamic folder '${entry.name}' but wildcard folder already exists in '${dir}'.`);
@@ -122,7 +80,6 @@ export class ApiRouter {
122
80
  throw new Error(`Multiple wildcard route folders found in the same directory: ` +
123
81
  `'${entry.name}' conflicts with another wildcard folder in '${dir}'.`);
124
82
  }
125
- // Update flags
126
83
  if (isDynamic)
127
84
  dynamicFolderFound = true;
128
85
  if (isWildcard)
@@ -136,51 +93,32 @@ export class ApiRouter {
136
93
  }
137
94
  catch (error) {
138
95
  if (error instanceof Error) {
139
- throw error; // Re-throw specific errors we created
96
+ throw error;
140
97
  }
141
98
  throw new Error(`Failed to scan directory '${dir}': ${String(error)}`);
142
99
  }
143
100
  }
144
- /**
145
- * Loads a route module from a file and inserts it into the trie.
146
- * @param entryPath The full file system path to the route module (route.ts).
147
- * @param relativePath The relative path used to construct the route path.
148
- * @returns {Promise<void>} A promise that resolves when the module is loaded and inserted.
149
- * @throws {Error} If the route module fails to load or is invalid.
150
- */
151
101
  async loadRouteModule(entryPath, relativePath) {
152
102
  try {
153
- // Convert the file path to a route path
154
103
  const routePath = this.convertFilePathToRoute(relativePath);
155
104
  console.info('Loading route:', routePath);
156
- // Get the module path like "D:\\Projects\\src\\api\\users\\route.ts"
157
105
  const modulePath = path.resolve(entryPath);
158
- // Import the module
159
106
  const routeModule = await import(modulePath);
160
- // Variable to store the handlers for each method
161
107
  const handlers = {};
162
- // Loop through all the HTTP methods and add the handler to the handlers object
163
108
  for (const method of HTTP_METHODS) {
164
109
  if (typeof routeModule[method] === 'function') {
165
110
  handlers[method] = routeModule[method];
166
111
  }
167
112
  }
168
- // Auto-inject minimal OPTIONS handler for CORS preflight when needed
169
- // Only if route defines any preflight-triggering methods and lacks an OPTIONS handler
170
113
  const PREFLIGHT_METHODS = ['POST', 'PUT', 'DELETE', 'PATCH'];
171
114
  let hasPreflightMethods = false;
172
- // Manual loop is slightly faster than Array.prototype.some in tight paths
173
115
  for (let i = 0; i < PREFLIGHT_METHODS.length; i++) {
174
116
  if (handlers[PREFLIGHT_METHODS[i]]) {
175
117
  hasPreflightMethods = true;
176
118
  break;
177
119
  }
178
120
  }
179
- // If the route defines any preflight-triggering methods and lacks an OPTIONS handler, auto-add an OPTIONS handler
180
121
  if (hasPreflightMethods && typeof handlers.OPTIONS !== 'function') {
181
- // if (process.env.NODE_ENV !== 'production') {
182
- // console.debug('Auto-added OPTIONS handler for route:', routePath);
183
- // }
184
122
  handlers.OPTIONS = () => new Response(null, { status: 204 });
185
123
  }
186
124
  const routeDef = {
@@ -197,35 +135,25 @@ export class ApiRouter {
197
135
  throw new Error(`Failed to load route module '${entryPath}': ${String(error)}`);
198
136
  }
199
137
  }
200
- /**
201
- * Converts a file path to a route path by processing dynamic segments and wildcard segments applying the prefix.
202
- * @param filePath The file path to convert (e.g., "users/[id]/route.ts" , "users/[...slug]/route.ts").
203
- * @returns {string} The converted route path (e.g., "/users/:id" , "/users/*slug").
204
- */
205
138
  convertFilePathToRoute(filePath) {
206
- // Remove the "route.ts" suffix
207
139
  if (filePath.endsWith('route.ts')) {
208
140
  filePath = filePath.slice(0, -'route.ts'.length);
209
141
  }
210
- // Split path into segments
211
142
  const segments = filePath.split(path.sep);
212
143
  const resultSegments = [];
213
144
  for (let segment of segments) {
214
145
  if (!segment)
215
- continue; // Skip empty segments
216
- // Skip grouping segments (e.g., (group))
146
+ continue;
217
147
  if (segment.startsWith(ROUTE_CONSTANTS.GROUPING_FOLDER_START) &&
218
148
  segment.endsWith(ROUTE_CONSTANTS.GROUPING_FOLDER_END)) {
219
149
  continue;
220
150
  }
221
- // Convert dynamic segments from [param] to :param
222
151
  if (segment.startsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_START) &&
223
152
  segment.endsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_END) &&
224
153
  !segment.startsWith(ROUTE_CONSTANTS.WILDCARD_START)) {
225
154
  const param = segment.slice(1, -1);
226
155
  resultSegments.push(ROUTE_CONSTANTS.DYNAMIC_SEGMENT_PREFIX + param);
227
156
  }
228
- // Convert wildcard segments from [...] to *
229
157
  else if (segment === ROUTE_CONSTANTS.WILDCARD_SIMPLE) {
230
158
  resultSegments.push(ROUTE_CONSTANTS.WILDCARD_SEGMENT_PREFIX);
231
159
  }
@@ -233,58 +161,41 @@ export class ApiRouter {
233
161
  resultSegments.push(segment);
234
162
  }
235
163
  }
236
- // Construct the route with leading slash
237
164
  let route = '/' + resultSegments.join('/');
238
- // Apply prefix if provided
239
165
  if (this.prefix) {
240
166
  const cleanPrefixStr = cleanPrefix(this.prefix);
241
167
  route = '/' + cleanPrefixStr + route;
242
168
  }
243
- // Remove trailing slash unless it's the root
244
169
  if (route !== '/' && route.endsWith('/')) {
245
170
  route = route.slice(0, -1);
246
171
  }
247
172
  return route;
248
173
  }
249
- /**
250
- * Resolves a request to a route definition and its parameters.
251
- * @param pathname The normalized request pathname.
252
- * @param method The uppercase HTTP method.
253
- * @returns {{ route?: RouteDefinition; params: Record<string, string>; wildcardParams?: string[] }} An object containing the matched route (if any), extracted parameters, and wildcard segments (if applicable).
254
- * @throws {Error} If the request URL is malformed.
255
- */
256
174
  resolve(pathname, method) {
257
175
  try {
258
176
  const segments = pathname.split('/').filter(Boolean);
259
177
  let node = this.root;
260
178
  const params = {};
261
179
  let wildcardSegments = [];
262
- // Traverse the trie with proper prioritization
263
180
  for (let i = 0; i < segments.length; i++) {
264
181
  const segment = segments[i];
265
- // Priority 1: Exact static match (highest priority)
266
182
  if (node.children.has(segment)) {
267
183
  node = node.children.get(segment);
268
184
  }
269
- // Priority 2: Dynamic parameter match (medium priority)
270
185
  else if (node.paramChild) {
271
186
  node = node.paramChild;
272
187
  params[node.paramName] = segment;
273
188
  }
274
- // Priority 3: Collect remaining segments for wildcard (lowest priority)
275
189
  else {
276
190
  wildcardSegments = segments.slice(i);
277
191
  break;
278
192
  }
279
193
  }
280
- // Check if we have a route at the current node
281
194
  if (node.route?.handlers[method]) {
282
195
  return { route: node.route, params };
283
196
  }
284
- // If no route found but we have wildcard segments, check for wildcard route
285
197
  if (wildcardSegments.length > 0 &&
286
198
  node.wildcardChild?.route?.handlers[method]) {
287
- // Return wildcard segments so they can be added to req.wildcardParams
288
199
  return {
289
200
  route: node.wildcardChild.route,
290
201
  params,
@@ -294,7 +205,6 @@ export class ApiRouter {
294
205
  return { params: {} };
295
206
  }
296
207
  catch (error) {
297
- // Log the error for better debugging
298
208
  console.error(`Error resolving API route for path "${pathname}":`, error);
299
209
  return { params: {} };
300
210
  }
@@ -1,10 +1,4 @@
1
- // Import stuff from Zod 4.x
2
1
  import { toJSONSchema, ZodArray, ZodBoolean, ZodNumber, ZodObject, ZodOptional, ZodString, ZodType, } from 'zod';
3
- /**
4
- * Maps a Zod type to an OpenAPI schema type.
5
- * @param zodType - The Zod type to map.
6
- * @returns The OpenAPI schema type.
7
- */
8
2
  function mapZodTypeToOpenAPIType(zodType) {
9
3
  if (zodType instanceof ZodOptional) {
10
4
  return mapZodTypeToOpenAPIType(zodType.unwrap());
@@ -19,59 +13,31 @@ function mapZodTypeToOpenAPIType(zodType) {
19
13
  return 'array';
20
14
  if (zodType instanceof ZodObject)
21
15
  return 'object';
22
- return 'string'; // fallback
16
+ return 'string';
23
17
  }
24
- /**
25
- * Builds an array of OpenAPI 3.0 parameters based on the Zod schema.
26
- * For each property in the Zod schema, an OpenAPI parameter is constructed
27
- * with the same name and required flag. The schema of the parameter is set
28
- * to a string type.
29
- * @param zodSchema - The Zod schema to construct parameters from. Can be undefined.
30
- * @param location - The location of the parameter. Must be either "path" or "query".
31
- * @returns An array of OpenAPI 3.0 parameter objects or an empty array if the Zod schema is undefined.
32
- */
33
18
  function buildParameters(zodSchema, location) {
34
19
  const parameters = [];
35
20
  if (zodSchema && typeof zodSchema.shape === 'object') {
36
- // Get the shape of the Zod schema
37
21
  const shape = zodSchema.shape;
38
22
  for (const key in shape) {
39
- // Get the definition of the field
40
23
  const fieldDef = shape[key];
41
- // Determine if the field is optional
42
24
  const isOptional = fieldDef instanceof ZodOptional;
43
- // Map the Zod type to an OpenAPI schema type
44
25
  const type = mapZodTypeToOpenAPIType(fieldDef);
45
26
  parameters.push({
46
- // Set the name of the parameter
47
27
  name: key,
48
- // Type of the parameter path or query
49
28
  in: location,
50
- // Set the required flag
51
29
  required: !isOptional,
52
- // Set the schema type
53
30
  schema: { type },
54
- // Description of the parameter
55
31
  description: `${location} parameter ${key}`,
56
32
  });
57
33
  }
58
34
  }
59
35
  return parameters;
60
36
  }
61
- /**
62
- * Builds a request body object for OpenAPI based on a Zod schema.
63
- * Converts the Zod schema into JSON schema and constructs an OpenAPI
64
- * requestBody object with content type "application/json".
65
- * @param zodSchema - The Zod schema to convert into JSON schema.
66
- * @returns An OpenAPI requestBody object, or undefined if no schema is provided.
67
- */
68
37
  function buildRequestBody(zodSchema) {
69
- // If no schema is provided, return undefined
70
38
  if (!zodSchema)
71
39
  return undefined;
72
- // Convert the Zod schema to a JSON schema
73
40
  const jsonSchema = toJSONSchema(zodSchema);
74
- // Return the OpenAPI requestBody object
75
41
  return {
76
42
  content: {
77
43
  'application/json': {
@@ -82,25 +48,11 @@ function buildRequestBody(zodSchema) {
82
48
  required: true,
83
49
  };
84
50
  }
85
- /**
86
- * Converts a route path from colon-based dynamic segments to OpenAPI's curly brace syntax.
87
- * Also handles wildcard routes.
88
- *
89
- * @param routePath The original route path with colon-based dynamic segments (e.g., "/user/:id") or wildcards (e.g., "/files/*").
90
- * @returns The converted route path with curly brace syntax (e.g., "/user/{id}") or wildcard format (e.g., "/files/*").
91
- */
92
51
  function convertPathForOpenAPI(routePath) {
93
- // Fast path: if no special chars, return as-is
94
52
  if (routePath.indexOf(':') === -1 && routePath.indexOf('*') === -1) {
95
53
  return routePath;
96
54
  }
97
- // Replace occurrences of :param with {param}
98
55
  let converted = routePath.replace(/:([a-zA-Z0-9_]+)/g, '{$1}');
99
- // Handle wildcard routes
100
- // OpenAPI 3.0 doesn't have official wildcard syntax, so we keep /* as-is
101
- // This will display in Swagger as /api/files/* which is intuitive and common
102
- // Alternative: convert to {path*} format if preferred
103
- // converted = converted.replace(/\/\*$/g, '/{path*}');
104
56
  return converted;
105
57
  }
106
58
  export function generateOpenAPIDocument(apiRoutes, options) {
@@ -113,22 +65,14 @@ export function generateOpenAPIDocument(apiRoutes, options) {
113
65
  },
114
66
  paths: {},
115
67
  };
116
- // Iterate over each route
117
68
  for (const route of apiRoutes) {
118
- // Convert colon-based dynamic segments to OpenAPI's {param} syntax
119
69
  const openApiPath = convertPathForOpenAPI(route.path);
120
- // Initialize path object if necessary
121
70
  openapiDoc.paths[openApiPath] = openapiDoc.paths[openApiPath] || {};
122
- // For each HTTP method in the route, add an OpenAPI operation.
123
71
  for (const method in route.handlers) {
124
- // Convert HTTP method to lowercase
125
72
  const lowerMethod = method.toLowerCase();
126
- // Use provided openapi metadata if available; else, fallback to auto-generated values.
127
73
  const methodMeta = route.openapi?.[lowerMethod] || {};
128
- // Generate an operationId: e.g., "get_api_product"
129
74
  const operationId = methodMeta.operationId ||
130
75
  `${lowerMethod}_${route.path.replace(/[\/:]/g, '_')}`;
131
- // Build parameters for both path and query from the schema.
132
76
  let parameters = [];
133
77
  if (route.schema && route.schema[lowerMethod]) {
134
78
  const schemaDef = route.schema[lowerMethod];
@@ -137,7 +81,6 @@ export function generateOpenAPIDocument(apiRoutes, options) {
137
81
  ...buildParameters(schemaDef.query, 'query'),
138
82
  ];
139
83
  }
140
- // Build requestBody if a body schema exists.
141
84
  let requestBody = undefined;
142
85
  if (route.schema && route.schema[lowerMethod]?.body) {
143
86
  requestBody = buildRequestBody(route.schema[lowerMethod].body);
@@ -1,59 +1,16 @@
1
1
  import type { PageDefinition } from '../types/index';
2
- /**
3
- * PageRouter class for handling file-based page routing.
4
- * Loads pages from a directory structure and matches requests to the appropriate page handlers.
5
- * Supports dynamic segments (e.g., [id]) and uses default exports as page handlers.
6
- */
7
2
  export declare class PageRouter {
8
3
  private pagesDir;
9
4
  private prefix;
10
- /** Array of loaded page definitions */
11
5
  pages: PageDefinition[];
12
- /**
13
- * Constructor for the PageRouter class.
14
- * @param pagesDir The directory path where page modules are located.
15
- * @param prefix Optional prefix to prepend to all routes (e.g., "pages" becomes "/pages/...").
16
- */
17
6
  constructor(pagesDir: string, prefix?: string);
18
- /**
19
- * Loads page modules from the specified directory and adds them to the pages array.
20
- * After loading, sorts the pages to prioritize static routes over dynamic ones based on specificity.
21
- * @returns A promise that resolves when all page modules have been loaded and sorted.
22
- */
23
7
  loadPages(): Promise<void>;
24
- /**
25
- * Recursively scans the directory for page modules and adds them to the pages array.
26
- * @param dir The current directory to scan.
27
- * @param basePath The base path for constructing the route path.
28
- */
29
8
  private scanDirectory;
30
- /**
31
- * Converts a file path to a route path by processing dynamic segments,
32
- * removing certain directory indicators, and applying a prefix if specified.
33
- * @param filePath The file path to convert into a route path.
34
- * @returns The converted route path string (before extension cleaning).
35
- */
36
9
  private convertFilePathToRoute;
37
- /**
38
- * Cleans a route path by handling index files and removing extensions.
39
- * @param routePath The route path to clean
40
- * @returns The cleaned route path
41
- */
42
10
  private cleanRoutePath;
43
- /**
44
- * Resolves the given request by finding a matching page and extracting dynamic parameters.
45
- * @param request The request to resolve.
46
- * @returns An object containing the matched page and parameters, or an empty params object if no match.
47
- */
48
11
  resolve(request: Request): {
49
12
  page?: PageDefinition;
50
13
  params: Record<string, string>;
51
14
  };
52
- /**
53
- * Checks if the request path matches the page path, extracting dynamic parameters if matched.
54
- * @param requestPath The request path to check.
55
- * @param pagePath The page path to match against.
56
- * @returns A record of dynamic parameters if matched, otherwise null.
57
- */
58
15
  private matchRoute;
59
16
  }