burger-api 0.2.3 → 0.3.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
@@ -4,8 +4,8 @@
4
4
 
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
- [![Bun](https://img.shields.io/badge/Bun-1.2.4-black?logo=bun)](https://bun.sh)
8
- [![Version](https://img.shields.io/badge/version-0.2.0-green.svg)](https://github.com/isfhan/burger-api/releases)
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.3.0-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
@@ -59,13 +59,13 @@ burger-api is built to offer a robust developer experience through:
59
59
 
60
60
  ## 📣 Changelog
61
61
 
62
- ### Latest Version: 0.2.0 (April 26, 2025)
62
+ ### Latest Version: 0.3.0 (August 15, 2025)
63
63
 
64
- - ⚡ **Performance & Core Improvements:**
65
- - Optimized framework core and improved middleware handling
66
- - Enhanced OpenAPI documentation and route tracking
67
- - Updated ID preprocessing logic in schema validation
68
- - Improved type definitions across the framework
64
+ - 🔧 **Updated Zod to version 4:**
65
+ - Updated Zod version from 3.x to 4.x
66
+ - Updated built-in request validation middleware to use Zod 4
67
+ - Updated and better request validation middleware error handling
68
+ - Removed Zod-to-json-schema dependency and use Zod 4 directly
69
69
 
70
70
  For a complete list of changes, please check the [Changelog](CHANGELOG.md) file.
71
71
 
@@ -1,25 +1,47 @@
1
- import { zodToJsonSchema } from 'zod-to-json-schema';
1
+ // Import stuff from Zod 4.x
2
+ 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
+ function mapZodTypeToOpenAPIType(zodType) {
9
+ if (zodType instanceof ZodOptional) {
10
+ return mapZodTypeToOpenAPIType(zodType.unwrap());
11
+ }
12
+ if (zodType instanceof ZodString)
13
+ return 'string';
14
+ if (zodType instanceof ZodNumber)
15
+ return 'number';
16
+ if (zodType instanceof ZodBoolean)
17
+ return 'boolean';
18
+ if (zodType instanceof ZodArray)
19
+ return 'array';
20
+ if (zodType instanceof ZodObject)
21
+ return 'object';
22
+ return 'string'; // fallback
23
+ }
2
24
  /**
3
25
  * Builds an array of OpenAPI 3.0 parameters based on the Zod schema.
4
26
  * For each property in the Zod schema, an OpenAPI parameter is constructed
5
27
  * with the same name and required flag. The schema of the parameter is set
6
28
  * to a string type.
7
- * @param zodSchema - The Zod schema to construct parameters from.
29
+ * @param zodSchema - The Zod schema to construct parameters from. Can be undefined.
8
30
  * @param location - The location of the parameter. Must be either "path" or "query".
9
- * @returns An array of OpenAPI 3.0 parameter objects.
31
+ * @returns An array of OpenAPI 3.0 parameter objects or an empty array if the Zod schema is undefined.
10
32
  */
11
33
  function buildParameters(zodSchema, location) {
12
34
  const parameters = [];
13
- if (zodSchema &&
14
- zodSchema._def &&
15
- typeof zodSchema._def.shape === 'function') {
35
+ if (zodSchema && typeof zodSchema.shape === 'object') {
16
36
  // Get the shape of the Zod schema
17
- const shape = zodSchema._def.shape();
37
+ const shape = zodSchema.shape;
18
38
  for (const key in shape) {
19
39
  // Get the definition of the field
20
40
  const fieldDef = shape[key];
21
41
  // Determine if the field is optional
22
- const isOptional = fieldDef._def.typeName === 'ZodOptional';
42
+ const isOptional = fieldDef instanceof ZodOptional;
43
+ // Map the Zod type to an OpenAPI schema type
44
+ const type = mapZodTypeToOpenAPIType(fieldDef);
23
45
  parameters.push({
24
46
  // Set the name of the parameter
25
47
  name: key,
@@ -28,7 +50,7 @@ function buildParameters(zodSchema, location) {
28
50
  // Set the required flag
29
51
  required: !isOptional,
30
52
  // Set the schema type
31
- schema: { type: 'string' },
53
+ schema: { type },
32
54
  // Description of the parameter
33
55
  description: `${location} parameter ${key}`,
34
56
  });
@@ -44,9 +66,12 @@ function buildParameters(zodSchema, location) {
44
66
  * @returns An OpenAPI requestBody object, or undefined if no schema is provided.
45
67
  */
46
68
  function buildRequestBody(zodSchema) {
69
+ // If no schema is provided, return undefined
47
70
  if (!zodSchema)
48
71
  return undefined;
49
- const jsonSchema = zodToJsonSchema(zodSchema);
72
+ // Convert the Zod schema to a JSON schema
73
+ const jsonSchema = toJSONSchema(zodSchema);
74
+ // Return the OpenAPI requestBody object
50
75
  return {
51
76
  content: {
52
77
  'application/json': {
@@ -1,2 +1,14 @@
1
1
  import type { RouteSchema, Middleware } from '@burgerTypes';
2
+ /**
3
+ * createValidationMiddleware:
4
+ * - Precompute a smaller runtime descriptor per method to avoid
5
+ * repeatedly touching the full schema object on every request.
6
+ * - Uses safeParse (sync) for Zod schemas (no try/catch around safeParse).
7
+ * - Parses querystring manually (no URL constructor, no throw).
8
+ * - Lazily allocates the errors container only when needed.
9
+ * - Avoids unnecessary object allocations for successful paths.
10
+ *
11
+ * @param schema - The route schema to validate the request against.
12
+ * @returns The middleware function that validates the request.
13
+ */
2
14
  export declare function createValidationMiddleware(schema: RouteSchema): Middleware;
@@ -1,79 +1,100 @@
1
+ /**
2
+ * createValidationMiddleware:
3
+ * - Precompute a smaller runtime descriptor per method to avoid
4
+ * repeatedly touching the full schema object on every request.
5
+ * - Uses safeParse (sync) for Zod schemas (no try/catch around safeParse).
6
+ * - Parses querystring manually (no URL constructor, no throw).
7
+ * - Lazily allocates the errors container only when needed.
8
+ * - Avoids unnecessary object allocations for successful paths.
9
+ *
10
+ * @param schema - The route schema to validate the request against.
11
+ * @returns The middleware function that validates the request.
12
+ */
1
13
  export function createValidationMiddleware(schema) {
14
+ // Precompute a minimal descriptor per HTTP method (lowercased)
15
+ // This work runs once at middleware creation time (fast startup cost, zero cost on each request for those computations).
16
+ const methodMap = {};
17
+ // Loop through the schema and create a method map
18
+ for (const rawMethod of Object.keys(schema)) {
19
+ // Convert the method to lowercase
20
+ const key = rawMethod.toLowerCase();
21
+ // Get the method schema
22
+ const m = schema[rawMethod] || {};
23
+ // Create a method map
24
+ methodMap[key] = {
25
+ paramsSchema: m.params, // URL parameters schema
26
+ querySchema: m.query, // Query parameters schema
27
+ bodySchema: m.body, // Request body schema
28
+ hasParams: !!m.params, // Whether the method has URL parameters
29
+ hasQuery: !!m.query, // Whether the method has query parameters
30
+ hasBody: !!m.body, // Whether the method has a request body
31
+ };
32
+ }
33
+ /**
34
+ * The middleware function that validates the request.
35
+ *
36
+ * @param req - The request object.
37
+ * @returns The next middleware or handler.
38
+ */
2
39
  return async (req) => {
3
40
  // If the request has been validated, continue.
4
41
  if (req.validated) {
5
42
  return undefined; // Proceed to the next middleware or handler
6
43
  }
7
44
  // Determine the HTTP method (in lowercase) to match the schema.
8
- const method = req.method.toLowerCase();
45
+ const method = (req.method || 'get').toLowerCase();
9
46
  // Get the schema for the current method.
10
- const methodSchema = schema[method];
47
+ const methodSchema = methodMap[method];
11
48
  // If there's no schema for this method, continue.
12
49
  if (!methodSchema) {
13
50
  return undefined; // Proceed to the next middleware or handler
14
51
  }
15
52
  // Get the schemas for the current method.
16
- const paramsSchema = methodSchema.params;
17
- const querySchema = methodSchema.query;
18
- const bodySchema = methodSchema.body;
19
- /**
20
- * Array to collect validation errors.
21
- * Each error contains a `field` indicating the part of the request that failed validation,
22
- * and an `error` providing details about the validation failure.
23
- */
24
- const errors = new Array(3); // Pre-allocate for params, query, body
25
- let errorCount = 0;
53
+ const { paramsSchema, querySchema, bodySchema, hasParams, hasQuery, hasBody, } = methodSchema;
26
54
  /**
27
55
  * Object to store validated request data. This will be attached to the
28
56
  * request object if validation is successful. The object will contain
29
57
  * validated data for the following fields:
30
58
  *
31
- * - `params`: Validated URL parameters.
32
- * - `query`: Validated query parameters.
33
- * - `body`: Validated request body (if JSON).
59
+ * - `params`: Validated URL parameters (if available and schema provided).
60
+ * - `query`: Validated query parameters (if available and schema provided).
61
+ * - `body`: Validated request body (if JSON and schema provided).
34
62
  */
35
63
  const validated = {};
64
+ // Lazy errors — create only if/when an error occurs
65
+ let errors = null;
36
66
  // Validate URL parameters (if available and schema provided).
37
- if (paramsSchema && req.params) {
38
- try {
39
- const result = paramsSchema.safeParse(req.params);
40
- if (result.success) {
41
- validated.params = result.data;
42
- }
43
- else {
44
- errors[errorCount++] = {
45
- field: 'params',
46
- error: result.error,
47
- };
48
- }
67
+ if (hasParams && req.params) {
68
+ const result = paramsSchema.safeParse(req.params);
69
+ if (result.success) {
70
+ validated.params = result.data;
49
71
  }
50
- catch (e) {
51
- errors[errorCount++] = { field: 'params', error: e.errors };
72
+ else {
73
+ if (!errors)
74
+ errors = {};
75
+ errors.params = result.error.issues;
52
76
  }
53
77
  }
54
- // Validate query parameters.
55
- const url = new URL(req.url);
56
- const queryParams = Object.fromEntries(url.searchParams.entries());
57
- if (querySchema) {
58
- try {
59
- const result = querySchema.safeParse(queryParams);
60
- if (result.success) {
61
- validated.query = result.data;
62
- }
63
- else {
64
- errors[errorCount++] = {
65
- field: 'query',
66
- error: result.error,
67
- };
68
- }
78
+ // Validate query parameters if available and schema provided.
79
+ if (hasQuery) {
80
+ const url = new URL(req.url);
81
+ const queryParams = Object.fromEntries(url.searchParams.entries());
82
+ const result = querySchema.safeParse(queryParams);
83
+ if (result.success) {
84
+ validated.query = result.data;
69
85
  }
70
- catch (e) {
71
- errors[errorCount++] = { field: 'query', error: e.errors };
86
+ else {
87
+ if (!errors)
88
+ errors = {};
89
+ errors.query = result.error.issues;
72
90
  }
73
91
  }
74
- // Validate request body.
75
- if (bodySchema &&
76
- req.headers.get('Content-Type')?.includes('application/json')) {
92
+ // Get the content type header
93
+ const contentType = req.headers.get('content-type') ??
94
+ req.headers.get('Content-Type') ??
95
+ '';
96
+ // Validate request body if it's JSON
97
+ if (hasBody && contentType?.includes('application/json')) {
77
98
  try {
78
99
  // Attempt to parse the JSON body.
79
100
  const bodyData = await req.json();
@@ -82,23 +103,25 @@ export function createValidationMiddleware(schema) {
82
103
  // Set the validated body.
83
104
  validated.body = result.data;
84
105
  // Set the json method to return the validated body.
85
- req.json = () => result.data;
106
+ req.json = async () => result.data;
86
107
  }
87
108
  else {
88
- errors[errorCount++] = {
89
- field: 'body',
90
- error: result.error,
91
- };
109
+ if (!errors)
110
+ errors = {};
111
+ errors.body = result.error.issues;
92
112
  }
93
113
  }
94
- catch (e) {
95
- errors[errorCount++] = {
96
- field: 'body',
97
- error: e.errors || e.message,
98
- };
114
+ catch (error) {
115
+ // Create a message from the error.
116
+ const msg = error && typeof error.message === 'string'
117
+ ? error.message
118
+ : String(error);
119
+ if (!errors)
120
+ errors = {};
121
+ errors.body = [{ message: msg }];
99
122
  }
100
123
  }
101
- if (errorCount > 0) {
124
+ if (errors) {
102
125
  // If validation fails, return a 400 response with error details.
103
126
  return Response.json({ errors }, { status: 400 });
104
127
  }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Simple Zod to JSON Schema converter for Zod 4.x
3
+ * This utility converts Zod schemas to JSON Schema format
4
+ * for use in OpenAPI documentation generation
5
+ */
6
+ /**
7
+ * Converts a Zod schema to JSON Schema format
8
+ * @param schema - The Zod schema to convert
9
+ * @returns JSON Schema object
10
+ */
11
+ export declare function zodToJsonSchema(schema: any): any;
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Simple Zod to JSON Schema converter for Zod 4.x
3
+ * This utility converts Zod schemas to JSON Schema format
4
+ * for use in OpenAPI documentation generation
5
+ */
6
+ /**
7
+ * Converts a Zod schema to JSON Schema format
8
+ * @param schema - The Zod schema to convert
9
+ * @returns JSON Schema object
10
+ */
11
+ export function zodToJsonSchema(schema) {
12
+ if (!schema) {
13
+ return { type: 'string' };
14
+ }
15
+ // Simple type detection based on schema properties
16
+ try {
17
+ // Check if it's a string schema
18
+ if (schema._def?.typeName === 'ZodString') {
19
+ return { type: 'string' };
20
+ }
21
+ // Check if it's a number schema
22
+ if (schema._def?.typeName === 'ZodNumber') {
23
+ return { type: 'number' };
24
+ }
25
+ // Check if it's a boolean schema
26
+ if (schema._def?.typeName === 'ZodBoolean') {
27
+ return { type: 'boolean' };
28
+ }
29
+ // Check if it's an array schema
30
+ if (schema._def?.typeName === 'ZodArray') {
31
+ return {
32
+ type: 'array',
33
+ items: { type: 'string' } // Default to string items
34
+ };
35
+ }
36
+ // Check if it's an object schema
37
+ if (schema._def?.typeName === 'ZodObject') {
38
+ const objectSchema = {
39
+ type: 'object',
40
+ properties: {},
41
+ required: []
42
+ };
43
+ // Try to get the shape
44
+ let shape = {};
45
+ if (schema.shape) {
46
+ shape = typeof schema.shape === 'function' ? schema.shape() : schema.shape;
47
+ }
48
+ for (const [key, value] of Object.entries(shape)) {
49
+ const fieldDef = value;
50
+ objectSchema.properties[key] = { type: 'string' }; // Default to string
51
+ // Check if field is optional
52
+ if (fieldDef._def?.typeName !== 'ZodOptional') {
53
+ objectSchema.required.push(key);
54
+ }
55
+ }
56
+ return objectSchema;
57
+ }
58
+ // Check if it's an optional schema
59
+ if (schema._def?.typeName === 'ZodOptional') {
60
+ return { type: 'string' };
61
+ }
62
+ // Check if it's a nullable schema
63
+ if (schema._def?.typeName === 'ZodNullable') {
64
+ return {
65
+ oneOf: [
66
+ { type: 'string' },
67
+ { type: 'null' }
68
+ ]
69
+ };
70
+ }
71
+ // Check if it's a union schema
72
+ if (schema._def?.typeName === 'ZodUnion') {
73
+ return {
74
+ oneOf: [
75
+ { type: 'string' },
76
+ { type: 'number' }
77
+ ]
78
+ };
79
+ }
80
+ // Check if it's an enum schema
81
+ if (schema._def?.typeName === 'ZodEnum') {
82
+ try {
83
+ const values = schema._def.values || [];
84
+ return {
85
+ type: 'string',
86
+ enum: values
87
+ };
88
+ }
89
+ catch {
90
+ return { type: 'string' };
91
+ }
92
+ }
93
+ // Check if it's a literal schema
94
+ if (schema._def?.typeName === 'ZodLiteral') {
95
+ try {
96
+ const value = schema._def.value;
97
+ return {
98
+ type: typeof value,
99
+ const: value
100
+ };
101
+ }
102
+ catch {
103
+ return { type: 'string' };
104
+ }
105
+ }
106
+ // Check if it's a default schema
107
+ if (schema._def?.typeName === 'ZodDefault') {
108
+ return { type: 'string' };
109
+ }
110
+ }
111
+ catch (error) {
112
+ // If any error occurs, fall back to string type
113
+ console.warn('Error processing Zod schema:', error);
114
+ }
115
+ // Fallback for unknown types
116
+ return { type: 'string' };
117
+ }
package/package.json CHANGED
@@ -1,90 +1,89 @@
1
- {
2
- "name": "burger-api",
3
- "version": "0.2.3",
4
- "author": "Isfhan Ahmed",
5
- "type": "module",
6
- "module": "dist/src/index.js",
7
- "types": "dist/src/index.d.ts",
8
- "files": [
9
- "dist"
10
- ],
11
- "scripts": {
12
- "typecheck": "tsc --noEmit",
13
- "build": "tsc --project tsconfig.build.json && tsc-alias -p tsconfig.build.json",
14
- "test": "bun test",
15
- "dev": "bun run examples/file-base-static-page-routing-app/index.ts"
16
- },
17
- "keywords": [
18
- "burger-api",
19
- "burger-api-framework",
20
- "bun",
21
- "bunjs",
22
- "bun-framework",
23
- "fast-backend",
24
- "javascript-backend",
25
- "high-performance",
26
- "esm",
27
- "typescript",
28
- "openapi",
29
- "swagger-ui",
30
- "declarative-routing",
31
- "api-framework",
32
- "modern-backend",
33
- "backend-framework",
34
- "server",
35
- "bun-native",
36
- "js-backend",
37
- "fast-api",
38
- "scalable-backend",
39
- "backend-development",
40
- "modern-api",
41
- "api-development",
42
- "backend-engine",
43
- "efficient",
44
- "minimalist-backend",
45
- "bun-powered",
46
- "open-source",
47
- "typescript-backend",
48
- "performance",
49
- "rapid-development",
50
- "web-framework",
51
- "api-server",
52
- "dynamic-routing",
53
- "backend-routing",
54
- "extensible",
55
- "modular",
56
- "declarative-api",
57
- "lightweight",
58
- "contemporary-backend",
59
- "fast-javascript",
60
- "bun-js-framework",
61
- "bun-backend",
62
- "bun-api-framework",
63
- "pakistan-backend",
64
- "pakistan-api-framework",
65
- "pakistan-api-server",
66
- "pakistan-backend-framework",
67
- "pakistan-bunjs-framework",
68
- "pakistan-javascript-framework"
69
- ],
70
- "license": "MIT",
71
- "repository": {
72
- "type": "git",
73
- "url": "git+https://github.com/isfhan/burger-api.git"
74
- },
75
- "bugs": {
76
- "url": "https://github.com/isfhan/burger-api/issues"
77
- },
78
- "homepage": "https://burger-api.com",
79
- "dependencies": {
80
- "zod": "^3.24.3",
81
- "zod-to-json-schema": "^3.24.5"
82
- },
83
- "devDependencies": {
84
- "@types/bun": "latest",
85
- "tsc-alias": "^1.8.15"
86
- },
87
- "peerDependencies": {
88
- "typescript": "^5.7.3"
89
- }
1
+ {
2
+ "name": "burger-api",
3
+ "version": "0.3.1",
4
+ "author": "Isfhan Ahmed",
5
+ "type": "module",
6
+ "module": "dist/src/index.js",
7
+ "types": "dist/src/index.d.ts",
8
+ "files": [
9
+ "dist"
10
+ ],
11
+ "scripts": {
12
+ "typecheck": "tsc --noEmit",
13
+ "build": "tsc --project tsconfig.build.json && tsc-alias -p tsconfig.build.json",
14
+ "test": "bun test",
15
+ "dev": "bun run examples/file-base-static-page-routing-app/index.ts"
16
+ },
17
+ "keywords": [
18
+ "burger-api",
19
+ "burger-api-framework",
20
+ "bun",
21
+ "bunjs",
22
+ "bun-framework",
23
+ "fast-backend",
24
+ "javascript-backend",
25
+ "high-performance",
26
+ "esm",
27
+ "typescript",
28
+ "openapi",
29
+ "swagger-ui",
30
+ "declarative-routing",
31
+ "api-framework",
32
+ "modern-backend",
33
+ "backend-framework",
34
+ "server",
35
+ "bun-native",
36
+ "js-backend",
37
+ "fast-api",
38
+ "scalable-backend",
39
+ "backend-development",
40
+ "modern-api",
41
+ "api-development",
42
+ "backend-engine",
43
+ "efficient",
44
+ "minimalist-backend",
45
+ "bun-powered",
46
+ "open-source",
47
+ "typescript-backend",
48
+ "performance",
49
+ "rapid-development",
50
+ "web-framework",
51
+ "api-server",
52
+ "dynamic-routing",
53
+ "backend-routing",
54
+ "extensible",
55
+ "modular",
56
+ "declarative-api",
57
+ "lightweight",
58
+ "contemporary-backend",
59
+ "fast-javascript",
60
+ "bun-js-framework",
61
+ "bun-backend",
62
+ "bun-api-framework",
63
+ "pakistan-backend",
64
+ "pakistan-api-framework",
65
+ "pakistan-api-server",
66
+ "pakistan-backend-framework",
67
+ "pakistan-bunjs-framework",
68
+ "pakistan-javascript-framework"
69
+ ],
70
+ "license": "MIT",
71
+ "repository": {
72
+ "type": "git",
73
+ "url": "git+https://github.com/isfhan/burger-api.git"
74
+ },
75
+ "bugs": {
76
+ "url": "https://github.com/isfhan/burger-api/issues"
77
+ },
78
+ "homepage": "https://burger-api.com",
79
+ "dependencies": {
80
+ "zod": "^4.0.17"
81
+ },
82
+ "devDependencies": {
83
+ "@types/bun": "latest",
84
+ "tsc-alias": "^1.8.16"
85
+ },
86
+ "peerDependencies": {
87
+ "typescript": "^5.7.3"
88
+ }
90
89
  }