burger-api 0.7.1 โ†’ 0.9.5

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
@@ -7,7 +7,7 @@
7
7
  [![Under Development](https://img.shields.io/badge/under%20development-red.svg)](https://github.com/isfhan/burger-api)
8
8
  [![License](https://img.shields.io/badge/license-MIT-blue.svg)](./packages/burger-api/LICENSE)
9
9
  [![Bun](https://img.shields.io/badge/Bun-1.2.20-black?logo=bun)](https://bun.sh)
10
- [![Version](https://img.shields.io/badge/version-0.6.2-green.svg)](https://github.com/isfhan/burger-api/releases)
10
+ [![Version](https://img.shields.io/badge/version-0.9.5-green.svg)](https://github.com/isfhan/burger-api/releases)
11
11
 
12
12
  **burger-api** is a modern, open source API framework built on
13
13
  [Bun.js](https://bun.sh). It combines the simplicity of file-based routing with
@@ -164,13 +164,16 @@ project. For more information, visit the
164
164
 
165
165
  ## ๐Ÿ“ฃ Changelog
166
166
 
167
- ### Latest Version: 0.7.0 (December 24, 2025)
167
+ ### Latest Version: 0.9.5 (March 18, 2026)
168
168
 
169
- - ๐Ÿ”ง **CLI & Release Improvements:**
170
- - Added CLI tool for creating new projects and managing middleware
171
- - Updated README.md
169
+ - ๐Ÿš€ Production builds work better and use the same route rules as
170
+ development.
171
+ - ๐Ÿ“ฆ You can pass route lists into the server so production does not scan
172
+ files.
173
+ - ๐Ÿงช Example tests and test scripts are improved; run framework and CLI
174
+ tests from the repo root.
172
175
 
173
- ### Latest Version: 0.6.2 (November 13, 2025)
176
+ ### Previous Version: 0.7.0 (November 13, 2025)
174
177
 
175
178
  - โšก **Major Performance Improvements:**
176
179
 
@@ -50,12 +50,6 @@ export declare class ApiRouter {
50
50
  * @throws {Error} If the route module fails to load or is invalid.
51
51
  */
52
52
  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
- private convertFilePathToRoute;
59
53
  /**
60
54
  * Resolves a request to a route definition and its parameters.
61
55
  * @param pathname The normalized request pathname.
@@ -2,7 +2,8 @@
2
2
  import { readdir } from 'fs/promises';
3
3
  import * as path from 'path';
4
4
  // Import utils
5
- import { cleanPrefix, normalizePath, ROUTE_CONSTANTS, HTTP_METHODS, } from '../utils/index';
5
+ import { normalizePath, ROUTE_CONSTANTS, HTTP_METHODS } from '../utils/index';
6
+ import { filePathToApiRoutePath } from '../utils/pathConversion';
6
7
  /**
7
8
  * ApiRouter class for handling file-based routing.
8
9
  * Loads routes from a directory structure and matches requests to the appropriate route handlers.
@@ -100,10 +101,15 @@ export class ApiRouter {
100
101
  const entryPath = path.join(dir, entry.name);
101
102
  const relativePath = path.join(basePath, entry.name);
102
103
  if (entry.isDirectory()) {
104
+ // Skip named wildcard folders
105
+ if (entry.name.startsWith(ROUTE_CONSTANTS.WILDCARD_START) &&
106
+ entry.name !== ROUTE_CONSTANTS.WILDCARD_SIMPLE) {
107
+ continue;
108
+ }
103
109
  // Check if this is a dynamic or wildcard directory
104
110
  const isDynamic = entry.name.startsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_START) &&
105
111
  entry.name.endsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_END) &&
106
- entry.name !== ROUTE_CONSTANTS.WILDCARD_SIMPLE;
112
+ !entry.name.startsWith(ROUTE_CONSTANTS.WILDCARD_START);
107
113
  const isWildcard = entry.name === ROUTE_CONSTANTS.WILDCARD_SIMPLE;
108
114
  // Prevent conflicts between dynamic and wildcard routes
109
115
  if (isDynamic && wildcardFolderFound) {
@@ -151,7 +157,7 @@ export class ApiRouter {
151
157
  async loadRouteModule(entryPath, relativePath) {
152
158
  try {
153
159
  // Convert the file path to a route path
154
- const routePath = this.convertFilePathToRoute(relativePath);
160
+ const routePath = filePathToApiRoutePath(relativePath, this.prefix);
155
161
  console.info('Loading route:', routePath);
156
162
  // Get the module path like "D:\\Projects\\src\\api\\users\\route.ts"
157
163
  const modulePath = path.resolve(entryPath);
@@ -167,7 +173,12 @@ export class ApiRouter {
167
173
  }
168
174
  // Auto-inject minimal OPTIONS handler for CORS preflight when needed
169
175
  // Only if route defines any preflight-triggering methods and lacks an OPTIONS handler
170
- const PREFLIGHT_METHODS = ['POST', 'PUT', 'DELETE', 'PATCH'];
176
+ const PREFLIGHT_METHODS = [
177
+ 'POST',
178
+ 'PUT',
179
+ 'DELETE',
180
+ 'PATCH',
181
+ ];
171
182
  let hasPreflightMethods = false;
172
183
  // Manual loop is slightly faster than Array.prototype.some in tight paths
173
184
  for (let i = 0; i < PREFLIGHT_METHODS.length; i++) {
@@ -197,55 +208,6 @@ export class ApiRouter {
197
208
  throw new Error(`Failed to load route module '${entryPath}': ${String(error)}`);
198
209
  }
199
210
  }
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
- convertFilePathToRoute(filePath) {
206
- // Remove the "route.ts" suffix
207
- if (filePath.endsWith('route.ts')) {
208
- filePath = filePath.slice(0, -'route.ts'.length);
209
- }
210
- // Split path into segments
211
- const segments = filePath.split(path.sep);
212
- const resultSegments = [];
213
- for (let segment of segments) {
214
- if (!segment)
215
- continue; // Skip empty segments
216
- // Skip grouping segments (e.g., (group))
217
- if (segment.startsWith(ROUTE_CONSTANTS.GROUPING_FOLDER_START) &&
218
- segment.endsWith(ROUTE_CONSTANTS.GROUPING_FOLDER_END)) {
219
- continue;
220
- }
221
- // Convert dynamic segments from [param] to :param
222
- if (segment.startsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_START) &&
223
- segment.endsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_END) &&
224
- !segment.startsWith(ROUTE_CONSTANTS.WILDCARD_START)) {
225
- const param = segment.slice(1, -1);
226
- resultSegments.push(ROUTE_CONSTANTS.DYNAMIC_SEGMENT_PREFIX + param);
227
- }
228
- // Convert wildcard segments from [...] to *
229
- else if (segment === ROUTE_CONSTANTS.WILDCARD_SIMPLE) {
230
- resultSegments.push(ROUTE_CONSTANTS.WILDCARD_SEGMENT_PREFIX);
231
- }
232
- else {
233
- resultSegments.push(segment);
234
- }
235
- }
236
- // Construct the route with leading slash
237
- let route = '/' + resultSegments.join('/');
238
- // Apply prefix if provided
239
- if (this.prefix) {
240
- const cleanPrefixStr = cleanPrefix(this.prefix);
241
- route = '/' + cleanPrefixStr + route;
242
- }
243
- // Remove trailing slash unless it's the root
244
- if (route !== '/' && route.endsWith('/')) {
245
- route = route.slice(0, -1);
246
- }
247
- return route;
248
- }
249
211
  /**
250
212
  * Resolves a request to a route definition and its parameters.
251
213
  * @param pathname The normalized request pathname.
@@ -32,7 +32,7 @@ function mapZodTypeToOpenAPIType(zodType) {
32
32
  */
33
33
  function buildParameters(zodSchema, location) {
34
34
  const parameters = [];
35
- if (zodSchema && typeof zodSchema.shape === 'object') {
35
+ if (isZodObjectSchema(zodSchema)) {
36
36
  // Get the shape of the Zod schema
37
37
  const shape = zodSchema.shape;
38
38
  for (const key in shape) {
@@ -58,6 +58,9 @@ function buildParameters(zodSchema, location) {
58
58
  }
59
59
  return parameters;
60
60
  }
61
+ function isZodObjectSchema(value) {
62
+ return value instanceof ZodObject;
63
+ }
61
64
  /**
62
65
  * Builds a request body object for OpenAPI based on a Zod schema.
63
66
  * Converts the Zod schema into JSON schema and constructs an OpenAPI
@@ -67,7 +70,7 @@ function buildParameters(zodSchema, location) {
67
70
  */
68
71
  function buildRequestBody(zodSchema) {
69
72
  // If no schema is provided, return undefined
70
- if (!zodSchema)
73
+ if (!(zodSchema instanceof ZodType))
71
74
  return undefined;
72
75
  // Convert the Zod schema to a JSON schema
73
76
  const jsonSchema = toJSONSchema(zodSchema);
@@ -121,6 +124,9 @@ export function generateOpenAPIDocument(apiRoutes, options) {
121
124
  openapiDoc.paths[openApiPath] = openapiDoc.paths[openApiPath] || {};
122
125
  // For each HTTP method in the route, add an OpenAPI operation.
123
126
  for (const method in route.handlers) {
127
+ // If the handler is not a function, skip
128
+ if (typeof route.handlers[method] !== 'function')
129
+ continue;
124
130
  // Convert HTTP method to lowercase
125
131
  const lowerMethod = method.toLowerCase();
126
132
  // Use provided openapi metadata if available; else, fallback to auto-generated values.
@@ -27,19 +27,6 @@ export declare class PageRouter {
27
27
  * @param basePath The base path for constructing the route path.
28
28
  */
29
29
  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
- 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
- private cleanRoutePath;
43
30
  /**
44
31
  * Resolves the given request by finding a matching page and extracting dynamic parameters.
45
32
  * @param request The request to resolve.
@@ -3,6 +3,7 @@ import { readdirSync } from 'fs';
3
3
  import * as path from 'path';
4
4
  // Import utils
5
5
  import { cleanPrefix, normalizePath, compareRoutes, ROUTE_CONSTANTS, } from '../utils/index';
6
+ import { filePathToPageRoutePath } from '../utils/pathConversion';
6
7
  /**
7
8
  * PageRouter class for handling file-based page routing.
8
9
  * Loads pages from a directory structure and matches requests to the appropriate page handlers.
@@ -63,6 +64,9 @@ export class PageRouter {
63
64
  const entryPath = path.join(dir, entry.name);
64
65
  const relativePath = path.join(basePath, entry.name);
65
66
  if (entry.isDirectory()) {
67
+ if (entry.name.startsWith(ROUTE_CONSTANTS.WILDCARD_START)) {
68
+ continue;
69
+ }
66
70
  // Handle dynamic directories (e.g., [id])
67
71
  if (entry.name.startsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_START) &&
68
72
  entry.name.endsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_END)) {
@@ -76,9 +80,7 @@ export class PageRouter {
76
80
  else if (entry.isFile() &&
77
81
  ROUTE_CONSTANTS.SUPPORTED_PAGE_EXTENSIONS.some((ext) => entry.name.endsWith(ext))) {
78
82
  // 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);
83
+ const cleanedRoutePath = filePathToPageRoutePath(relativePath, this.prefix);
82
84
  // Get the module path
83
85
  const modulePath = path.resolve(entryPath);
84
86
  try {
@@ -115,75 +117,6 @@ export class PageRouter {
115
117
  throw error;
116
118
  }
117
119
  }
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
120
  /**
188
121
  * Resolves the given request by finding a matching page and extracting dynamic parameters.
189
122
  * @param request The request to resolve.
@@ -1,4 +1,5 @@
1
- import type { ServerOptions, FetchHandler } from '../types/index';
1
+ import type { HTMLBundle } from 'bun';
2
+ import type { ServerOptions, FetchHandler, RequestHandler } from '../types/index';
2
3
  export declare class Server {
3
4
  private options;
4
5
  private server;
@@ -7,9 +8,7 @@ export declare class Server {
7
8
  * @param options - Configuration options for the server.
8
9
  */
9
10
  constructor(options: ServerOptions);
10
- start(routes: {
11
- [key: string]: any;
12
- } | undefined, handler: FetchHandler, port: number, cb?: () => void): void;
11
+ start(routes: Record<string, HTMLBundle | RequestHandler> | undefined, handler: FetchHandler, port: number, cb?: () => void): void;
13
12
  /**
14
13
  * Stops the server.
15
14
  * If the server is currently running, this method will stop the server and
@@ -14,19 +14,16 @@ export class Server {
14
14
  }
15
15
  start(routes, handler, port, cb) {
16
16
  // Start Bun's native server using Bun.serve
17
- this.server = serve({
17
+ const serveOptions = {
18
18
  routes,
19
- // Bun's fetch handler
20
19
  fetch: async (request) => {
21
20
  try {
22
21
  return await handler(request);
23
22
  }
24
23
  catch (error) {
25
- // Return a custom error response
26
24
  return errorResponse(error, request, this.options.debug ?? false);
27
25
  }
28
26
  },
29
- // Global error handler
30
27
  error(error) {
31
28
  console.error(error);
32
29
  return new Response(`Internal Server Error: ${error.message}`, {
@@ -37,7 +34,8 @@ export class Server {
37
34
  });
38
35
  },
39
36
  port,
40
- });
37
+ };
38
+ this.server = serve(serveOptions);
41
39
  if (cb) {
42
40
  cb();
43
41
  }
@@ -92,4 +92,4 @@ export declare class Burger {
92
92
  serve(port?: number, cb?: () => void): Promise<void>;
93
93
  }
94
94
  export { setDir } from './utils/index';
95
- export type { ServerOptions, RequestHandler, BurgerRequest, BurgerNext, Middleware, openapi, } from './types/index';
95
+ export type { ServerOptions, RequestHandler, BurgerRequest, BurgerNext, Middleware, openapi, RouteDefinition, PageDefinition, } from './types/index';
package/dist/src/index.js CHANGED
@@ -5,7 +5,7 @@ import { PageRouter } from './core/page-router';
5
5
  import { generateOpenAPIDocument } from './core/openapi';
6
6
  import { swaggerHtml } from './core/swagger-ui';
7
7
  // Import utils
8
- import { collectRoutes } from './utils/index';
8
+ import { collectRoutes, compareRoutes } from './utils/index';
9
9
  import { METHOD_NOT_ALLOWED, NOT_FOUND, OPENAPI_ERROR } from './utils/response';
10
10
  import { extractPathnameFromUrl, extractWildcardParams, } from './utils/wildcard';
11
11
  // Import middleware
@@ -63,14 +63,16 @@ export class Burger {
63
63
  this.server = new Server(options);
64
64
  // Fast initialization for routers with nullish coalescing
65
65
  const { apiDir, pageDir, apiPrefix, pagePrefix, globalMiddleware } = options;
66
- // Initialize API router if apiDir is provided
67
- this.apiRouter = apiDir
68
- ? new ApiRouter(apiDir, apiPrefix || 'api')
69
- : undefined;
70
- // Initialize page router if pageDir is provided
71
- this.pageRouter = pageDir
72
- ? new PageRouter(pageDir, pagePrefix || '')
73
- : undefined;
66
+ // Initialize API router only when using runtime scanning (no prebuilt apiRoutes)
67
+ this.apiRouter =
68
+ apiDir && !Array.isArray(options.apiRoutes)
69
+ ? new ApiRouter(apiDir, apiPrefix || 'api')
70
+ : undefined;
71
+ // Initialize page router only when using runtime scanning (no prebuilt pageRoutes)
72
+ this.pageRouter =
73
+ pageDir && !Array.isArray(options.pageRoutes)
74
+ ? new PageRouter(pageDir, pagePrefix || '')
75
+ : undefined;
74
76
  // Add global middleware if any
75
77
  this.globalMiddleware = globalMiddleware?.length
76
78
  ? globalMiddleware.slice()
@@ -81,7 +83,18 @@ export class Burger {
81
83
  * @returns A promise that resolves to a boolean
82
84
  */
83
85
  async processPageRoutes() {
84
- // If no page router, return false
86
+ // Production path: use pre-built page routes (no filesystem scan)
87
+ const prebuiltPages = this.options.pageRoutes;
88
+ if (Array.isArray(prebuiltPages)) {
89
+ // Sort the prebuilt pages
90
+ const sorted = [...prebuiltPages].sort((a, b) => compareRoutes(a, b));
91
+ for (let i = 0; i < sorted.length; i++) {
92
+ const page = sorted[i];
93
+ this.routes[page.path] = page.handler;
94
+ }
95
+ return sorted.length > 0;
96
+ }
97
+ // Dev path: load from filesystem via PageRouter
85
98
  if (!this.pageRouter)
86
99
  return false;
87
100
  // Load pages routes
@@ -108,13 +121,18 @@ export class Burger {
108
121
  * @returns A promise that resolves to a boolean
109
122
  */
110
123
  async processApiRoutes() {
111
- // If no api router, return false
112
- if (!this.apiRouter)
113
- return false;
114
- // Load API routes
115
- await this.apiRouter.loadRoutes();
116
- // Collect API routes
117
- const apiRoutes = collectRoutes(this.apiRouter.routes);
124
+ // Production path: use pre-built API routes (no filesystem scan)
125
+ let apiRoutes;
126
+ if (Array.isArray(this.options.apiRoutes)) {
127
+ apiRoutes = [...this.options.apiRoutes].sort((a, b) => compareRoutes(a, b));
128
+ }
129
+ else {
130
+ // Dev path: load from filesystem via ApiRouter
131
+ if (!this.apiRouter)
132
+ return false;
133
+ await this.apiRouter.loadRoutes();
134
+ apiRoutes = collectRoutes(this.apiRouter.routes);
135
+ }
118
136
  // Get the length of the API routes
119
137
  const routeCount = apiRoutes.length;
120
138
  // If there are no API routes, return false
@@ -395,7 +413,7 @@ export class Burger {
395
413
  }
396
414
  else {
397
415
  // If no routes were configured, log an error
398
- console.error('Error: No routes configured! Please provide either apiDir with route.ts files or pageDir with html files when initializing the Burger Class.');
416
+ console.error('Error: No routes configured! Please provide apiDir/pageDir (for dev) or apiRoutes/pageRoutes (for production builds) when initializing the Burger class.');
399
417
  }
400
418
  }
401
419
  }
@@ -64,7 +64,7 @@ export function createValidationMiddleware(schema) {
64
64
  // Lazy errors โ€” create only if/when an error occurs
65
65
  let errors = null;
66
66
  // Validate URL parameters (if available and schema provided).
67
- if (hasParams && req.params) {
67
+ if (hasParams && req.params && paramsSchema) {
68
68
  const result = paramsSchema.safeParse(req.params);
69
69
  if (result.success) {
70
70
  validated.params = result.data;
@@ -76,7 +76,7 @@ export function createValidationMiddleware(schema) {
76
76
  }
77
77
  }
78
78
  // Validate query parameters if available and schema provided.
79
- if (hasQuery) {
79
+ if (hasQuery && querySchema) {
80
80
  const url = new URL(req.url);
81
81
  const queryParams = Object.fromEntries(url.searchParams.entries());
82
82
  const result = querySchema.safeParse(queryParams);
@@ -94,7 +94,9 @@ export function createValidationMiddleware(schema) {
94
94
  req.headers.get('Content-Type') ??
95
95
  '';
96
96
  // Validate request body if it's JSON
97
- if (hasBody && contentType?.includes('application/json')) {
97
+ if (hasBody &&
98
+ contentType?.includes('application/json') &&
99
+ bodySchema) {
98
100
  try {
99
101
  // Attempt to parse the JSON body.
100
102
  const bodyData = await req.json();
@@ -113,9 +115,7 @@ export function createValidationMiddleware(schema) {
113
115
  }
114
116
  catch (error) {
115
117
  // Create a message from the error.
116
- const msg = error && typeof error.message === 'string'
117
- ? error.message
118
- : String(error);
118
+ const msg = error instanceof Error ? error.message : String(error);
119
119
  if (!errors)
120
120
  errors = {};
121
121
  errors.body = [{ message: msg }];
@@ -1,5 +1,7 @@
1
1
  import type { BunRequest, Server } from 'bun';
2
- import type { ServeOptions as BunServerOptions } from 'bun';
2
+ import type { serve } from 'bun';
3
+ /** Options type for Bun.serve(); use this instead of deprecated ServeOptions. */
4
+ type BunServerOptions = Parameters<typeof serve>[0];
3
5
  import { z } from 'zod';
4
6
  export interface ServerOptions extends Omit<BunServerOptions, 'fetch' | 'port' | 'reusePort' | 'ipv6Only' | 'unix' | 'error' | 'id' | 'development'> {
5
7
  /**
@@ -48,6 +50,16 @@ export interface ServerOptions extends Omit<BunServerOptions, 'fetch' | 'port' |
48
50
  * information to the console or logs to aid in development and troubleshooting.
49
51
  */
50
52
  debug?: boolean;
53
+ /**
54
+ * Pre-built API routes (e.g. from CLI build). When provided, apiDir is ignored
55
+ * and no runtime filesystem scanning is performed. Used for bundled/executable builds.
56
+ */
57
+ apiRoutes?: RouteDefinition[];
58
+ /**
59
+ * Pre-built page routes (e.g. from CLI build). When provided, pageDir is ignored
60
+ * and no runtime filesystem scanning is performed. Used for bundled/executable builds.
61
+ */
62
+ pageRoutes?: PageDefinition[];
51
63
  }
52
64
  type DefaultRequestProperties = {
53
65
  params?: Record<string, unknown>;
@@ -169,9 +181,9 @@ export interface RouteDefinition {
169
181
  */
170
182
  export type RouteSchema = {
171
183
  [method: string]: {
172
- params?: z.ZodObject<any, any>;
173
- query?: z.ZodObject<any, any>;
174
- body?: z.ZodObject<any, any>;
184
+ params?: z.ZodTypeAny;
185
+ query?: z.ZodTypeAny;
186
+ body?: z.ZodTypeAny;
175
187
  };
176
188
  };
177
189
  /**
@@ -14,4 +14,4 @@
14
14
  * @param debug - A boolean indicating whether debugging information should be included.
15
15
  * @returns A Response object with the appropriate error details and status code.
16
16
  */
17
- export declare function errorResponse(error: any, req: Request, debug: boolean): Response;
17
+ export declare function errorResponse(error: unknown, req: Request, debug: boolean): Response;
@@ -22,9 +22,16 @@ export function errorResponse(error, req, debug) {
22
22
  const logPrefix = `[${method} ${url}]`;
23
23
  // Log detailed error context
24
24
  console.error(`${logPrefix} Error:`, error);
25
+ const message = error instanceof Error
26
+ ? error.message
27
+ : String(error ?? 'Unknown error');
28
+ const stack = error instanceof Error
29
+ ? (error.stack ?? 'No stack trace available')
30
+ : '';
31
+ const tagLabel = stack ? stack.split('\n')[0].split(':')[0] : 'Error';
25
32
  const acceptHeader = req.headers.get('accept') || '';
26
33
  if (acceptHeader.includes('text/html') && debug) {
27
- const body = `<!doctype html><html lang="en"><meta charset="UTF-8"><title>Error Occurred - BurgerAPI</title><style>body{margin:0;padding:0;background-color:#f4f4f4;font-family:Nunito,sans-serif;color:#333}.whoops-container{width:80%;margin:5% auto;background:#fff;border-radius:8px;box-shadow:0 4px 12px rgba(0,0,0,.15);overflow:hidden}.whoops-header{background-color:#e74c3c;color:#fff;padding:20px;display:flex;align-items:center;justify-content:space-between}.whoops-header .title-container{display:flex;align-items:center}.whoops-header .title{font-size:1.5em;margin-left:10px}.whoops-header .debug-mode{font-weight:600;display:flex;align-items:center;padding:10px;background-color:#fff;color:#e74c3c;box-shadow:0 4px 12px rgba(0,0,0,.15);border-radius:8px}.whoops-header .debug-mode .fa-check-circle{color:#28a745;margin-right:5px;font-size:1.2em}.whoops-content{padding:2em}.tag{font-weight:600;color:#4a5568;background-color:#edf2f7;padding:8px 15px;border-radius:6px;display:inline-block;font-size:14px}.error-message{font-size:1.25em;line-height:1.6;margin-bottom:1.5em;color:#2d3748}h2{color:#e3342f;font-size:1.5em;margin-bottom:.8em;border-bottom:1px solid #edf2f7;padding-bottom:.5em}pre{background:#f9fafc;border-left:4px solid #e3342f;padding:1.5em;border-radius:4px;font-family:"Source Code Pro",Menlo,Monaco,Consolas,"Courier New",monospace;font-size:1em;line-height:1.6;overflow-x:auto;color:#4a5568}.footer{text-align:center;padding-top:25px;font-size:.9em;color:#718096;border-top:1px solid #edf2f7}.error-icon{font-size:2em}.request-info{display:flex;justify-content:space-between;align-items:center}</style><link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css"rel="stylesheet"><div class="whoops-container"><div class="whoops-header"><div class="title-container"><i class="fas error-icon fa-exclamation-triangle"></i><div class="title">Whoops! Something went wrong</div></div><div class="debug-mode"><i class="fas fa-check-circle"></i> Debug Mode Enabled</div></div><div class="whoops-content"><div class="request-info"><div><strong>Request:</strong> ${method} ${url}</div><div class="tag">${error.stack?.split('\n')[0].split(':')[0]}</div></div><p class="error-message">${error.message}<h2>Stack Trace</h2><pre>${error.stack || 'No stack trace available'}</pre><div class="footer">โ€œItโ€™s not a bug, itโ€™s an undocumented feature.โ€ โ€” Anonymous</div></div></div>
34
+ const body = `<!doctype html><html lang="en"><meta charset="UTF-8"><title>Error Occurred - BurgerAPI</title><style>body{margin:0;padding:0;background-color:#f4f4f4;font-family:Nunito,sans-serif;color:#333}.whoops-container{width:80%;margin:5% auto;background:#fff;border-radius:8px;box-shadow:0 4px 12px rgba(0,0,0,.15);overflow:hidden}.whoops-header{background-color:#e74c3c;color:#fff;padding:20px;display:flex;align-items:center;justify-content:space-between}.whoops-header .title-container{display:flex;align-items:center}.whoops-header .title{font-size:1.5em;margin-left:10px}.whoops-header .debug-mode{font-weight:600;display:flex;align-items:center;padding:10px;background-color:#fff;color:#e74c3c;box-shadow:0 4px 12px rgba(0,0,0,.15);border-radius:8px}.whoops-header .debug-mode .fa-check-circle{color:#28a745;margin-right:5px;font-size:1.2em}.whoops-content{padding:2em}.tag{font-weight:600;color:#4a5568;background-color:#edf2f7;padding:8px 15px;border-radius:6px;display:inline-block;font-size:14px}.error-message{font-size:1.25em;line-height:1.6;margin-bottom:1.5em;color:#2d3748}h2{color:#e3342f;font-size:1.5em;margin-bottom:.8em;border-bottom:1px solid #edf2f7;padding-bottom:.5em}pre{background:#f9fafc;border-left:4px solid #e3342f;padding:1.5em;border-radius:4px;font-family:"Source Code Pro",Menlo,Monaco,Consolas,"Courier New",monospace;font-size:1em;line-height:1.6;overflow-x:auto;color:#4a5568}.footer{text-align:center;padding-top:25px;font-size:.9em;color:#718096;border-top:1px solid #edf2f7}.error-icon{font-size:2em}.request-info{display:flex;justify-content:space-between;align-items:center}</style><link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css"rel="stylesheet"><div class="whoops-container"><div class="whoops-header"><div class="title-container"><i class="fas error-icon fa-exclamation-triangle"></i><div class="title">Whoops! Something went wrong</div></div><div class="debug-mode"><i class="fas fa-check-circle"></i> Debug Mode Enabled</div></div><div class="whoops-content"><div class="request-info"><div><strong>Request:</strong> ${method} ${url}</div><div class="tag">${tagLabel}</div></div><p class="error-message">${message}</p><h2>Stack Trace</h2><pre>${stack}</pre><div class="footer">โ€œItโ€™s not a bug, itโ€™s an undocumented feature.โ€ โ€” Anonymous</div></div></div>
28
35
  `;
29
36
  // Return the html response
30
37
  return new Response(body, {
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Converts a file path to an API route path.
3
+ * @param filePath The file path to convert.
4
+ * @param prefix The prefix to prepend to the route path.
5
+ * @returns The API route path.
6
+ */
7
+ export declare function filePathToApiRoutePath(filePath: string, prefix: string): string;
8
+ /**
9
+ * Converts a file path to a page route path.
10
+ * @param filePath The file path to convert.
11
+ * @param prefix The prefix to prepend to the route path.
12
+ * @returns The page route path.
13
+ */
14
+ export declare function filePathToPageRoutePath(filePath: string, prefix: string): string;
@@ -0,0 +1,91 @@
1
+ import * as path from 'path';
2
+ import { cleanPrefix } from './index';
3
+ import { ROUTE_CONSTANTS } from './routing';
4
+ /**
5
+ * Converts a file path to an API route path.
6
+ * @param filePath The file path to convert.
7
+ * @param prefix The prefix to prepend to the route path.
8
+ * @returns The API route path.
9
+ */
10
+ export function filePathToApiRoutePath(filePath, prefix) {
11
+ if (filePath.endsWith('route.ts')) {
12
+ filePath = filePath.slice(0, -'route.ts'.length);
13
+ }
14
+ const segments = filePath.split(path.sep);
15
+ const resultSegments = [];
16
+ for (const segment of segments) {
17
+ if (!segment)
18
+ continue;
19
+ if (segment.startsWith(ROUTE_CONSTANTS.GROUPING_FOLDER_START) &&
20
+ segment.endsWith(ROUTE_CONSTANTS.GROUPING_FOLDER_END)) {
21
+ continue;
22
+ }
23
+ if (segment.startsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_START) &&
24
+ segment.endsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_END) &&
25
+ !segment.startsWith(ROUTE_CONSTANTS.WILDCARD_START)) {
26
+ resultSegments.push(ROUTE_CONSTANTS.DYNAMIC_SEGMENT_PREFIX + segment.slice(1, -1));
27
+ }
28
+ else if (segment === ROUTE_CONSTANTS.WILDCARD_SIMPLE) {
29
+ resultSegments.push(ROUTE_CONSTANTS.WILDCARD_SEGMENT_PREFIX);
30
+ }
31
+ else {
32
+ resultSegments.push(segment);
33
+ }
34
+ }
35
+ let route = '/' + resultSegments.join('/');
36
+ const clean = cleanPrefix(prefix);
37
+ if (clean) {
38
+ route = '/' + clean + route;
39
+ }
40
+ if (route !== '/' && route.endsWith('/')) {
41
+ route = route.slice(0, -1);
42
+ }
43
+ return route;
44
+ }
45
+ /**
46
+ * Converts a file path to a page route path.
47
+ * @param filePath The file path to convert.
48
+ * @param prefix The prefix to prepend to the route path.
49
+ * @returns The page route path.
50
+ */
51
+ export function filePathToPageRoutePath(filePath, prefix) {
52
+ const segments = filePath.split(path.sep);
53
+ const resultSegments = [];
54
+ for (const segment of segments) {
55
+ if (!segment)
56
+ continue;
57
+ if (segment.startsWith(ROUTE_CONSTANTS.GROUPING_FOLDER_START) &&
58
+ segment.endsWith(ROUTE_CONSTANTS.GROUPING_FOLDER_END)) {
59
+ continue;
60
+ }
61
+ if (segment.startsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_START) &&
62
+ segment.endsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_END)) {
63
+ resultSegments.push(ROUTE_CONSTANTS.DYNAMIC_SEGMENT_PREFIX + segment.slice(1, -1));
64
+ }
65
+ else {
66
+ resultSegments.push(segment);
67
+ }
68
+ }
69
+ let route = '/' + resultSegments.join('/');
70
+ const clean = cleanPrefix(prefix);
71
+ if (clean) {
72
+ route = '/' + clean + route;
73
+ }
74
+ if (route !== '/' && route.endsWith('/')) {
75
+ route = route.slice(0, -1);
76
+ }
77
+ const pathSegments = route.split('/');
78
+ const lastSegment = pathSegments.at(-1);
79
+ if (typeof lastSegment === 'string') {
80
+ if (ROUTE_CONSTANTS.PAGE_INDEX_FILES.includes(lastSegment)) {
81
+ pathSegments.pop();
82
+ }
83
+ else {
84
+ const extensionIndex = lastSegment.lastIndexOf('.');
85
+ if (extensionIndex > 0) {
86
+ pathSegments[pathSegments.length - 1] = lastSegment.slice(0, extensionIndex);
87
+ }
88
+ }
89
+ }
90
+ return pathSegments.join('/') === '' ? '/' : pathSegments.join('/');
91
+ }
package/package.json CHANGED
@@ -1,10 +1,16 @@
1
1
  {
2
2
  "name": "burger-api",
3
- "version": "0.7.1",
3
+ "version": "0.9.5",
4
4
  "author": "Isfhan Ahmed",
5
5
  "type": "module",
6
6
  "module": "dist/src/index.js",
7
7
  "types": "dist/src/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "import": "./dist/src/index.js",
11
+ "types": "./dist/src/index.d.ts"
12
+ }
13
+ },
8
14
  "files": [
9
15
  "dist"
10
16
  ],
@@ -12,7 +18,8 @@
12
18
  "typecheck": "tsc --noEmit",
13
19
  "build": "tsc --project tsconfig.build.json",
14
20
  "prepare": "bun run build",
15
- "test": "bun test",
21
+ "test": "bun run test:examples",
22
+ "test:examples": "bun test --timeout 30000 --max-concurrency 1 examples/**/*.test.ts",
16
23
  "dev": "bun run examples/file-base-static-page-routing-app/index.ts"
17
24
  },
18
25
  "keywords": [
@@ -77,6 +84,9 @@
77
84
  "url": "https://github.com/isfhan/burger-api/issues"
78
85
  },
79
86
  "homepage": "https://burger-api.com",
87
+ "engines": {
88
+ "bun": ">=1.3.0"
89
+ },
80
90
  "dependencies": {
81
91
  "zod": "^4.0.17"
82
92
  },
@@ -84,6 +94,6 @@
84
94
  "@types/bun": "latest"
85
95
  },
86
96
  "peerDependencies": {
87
- "typescript": "^5.7.3"
97
+ "typescript": "^5"
88
98
  }
89
99
  }