burger-api 0.3.0 → 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/dist/src/core/api-router.js +1 -1
- package/dist/src/core/openapi.js +35 -11
- package/dist/src/core/page-router.js +1 -1
- package/dist/src/core/server.js +1 -1
- package/dist/src/index.d.ts +1 -1
- package/dist/src/index.js +9 -9
- package/dist/src/middleware/validator.d.ts +12 -0
- package/dist/src/middleware/validator.js +83 -60
- package/dist/src/utils/error.js +1 -1
- package/dist/src/utils/index.d.ts +1 -1
- package/dist/src/utils/index.js +1 -1
- package/package.json +1 -1
|
@@ -2,7 +2,7 @@
|
|
|
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 '
|
|
5
|
+
import { cleanPrefix, normalizePath, ROUTE_CONSTANTS, HTTP_METHODS, } from '../utils/index.js';
|
|
6
6
|
/**
|
|
7
7
|
* ApiRouter class for handling file-based routing.
|
|
8
8
|
* Loads routes from a directory structure and matches requests to the appropriate route handlers.
|
package/dist/src/core/openapi.js
CHANGED
|
@@ -1,25 +1,47 @@
|
|
|
1
|
-
|
|
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.
|
|
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
|
|
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
|
|
53
|
+
schema: { type },
|
|
32
54
|
// Description of the parameter
|
|
33
55
|
description: `${location} parameter ${key}`,
|
|
34
56
|
});
|
|
@@ -44,10 +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
|
-
//
|
|
50
|
-
const jsonSchema =
|
|
72
|
+
// Convert the Zod schema to a JSON schema
|
|
73
|
+
const jsonSchema = toJSONSchema(zodSchema);
|
|
74
|
+
// Return the OpenAPI requestBody object
|
|
51
75
|
return {
|
|
52
76
|
content: {
|
|
53
77
|
'application/json': {
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { readdirSync } from 'fs';
|
|
3
3
|
import * as path from 'path';
|
|
4
4
|
// Import utils
|
|
5
|
-
import { cleanPrefix, normalizePath, compareRoutes, ROUTE_CONSTANTS, } from '
|
|
5
|
+
import { cleanPrefix, normalizePath, compareRoutes, ROUTE_CONSTANTS, } from '../utils/index.js';
|
|
6
6
|
/**
|
|
7
7
|
* PageRouter class for handling file-based page routing.
|
|
8
8
|
* Loads pages from a directory structure and matches requests to the appropriate page handlers.
|
package/dist/src/core/server.js
CHANGED
package/dist/src/index.d.ts
CHANGED
|
@@ -73,5 +73,5 @@ export declare class Burger {
|
|
|
73
73
|
*/
|
|
74
74
|
serve(port?: number, cb?: () => void): Promise<void>;
|
|
75
75
|
}
|
|
76
|
-
export { setDir } from '
|
|
76
|
+
export { setDir } from './utils/index.js';
|
|
77
77
|
export type { ServerOptions, RequestHandler, BurgerRequest, BurgerNext, Middleware, openapi, } from '@burgerTypes';
|
package/dist/src/index.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
// Import stuff from core
|
|
2
|
-
import { Server } from '
|
|
3
|
-
import { ApiRouter } from '
|
|
4
|
-
import { PageRouter } from '
|
|
5
|
-
import { generateOpenAPIDocument } from '
|
|
6
|
-
import { swaggerHtml } from '
|
|
2
|
+
import { Server } from './core/server.js';
|
|
3
|
+
import { ApiRouter } from './core/api-router.js';
|
|
4
|
+
import { PageRouter } from './core/page-router.js';
|
|
5
|
+
import { generateOpenAPIDocument } from './core/openapi.js';
|
|
6
|
+
import { swaggerHtml } from './core/swagger-ui.js';
|
|
7
7
|
// Import utils
|
|
8
|
-
import { collectRoutes } from '
|
|
9
|
-
import { METHOD_NOT_ALLOWED, NOT_FOUND, OPENAPI_ERROR } from '
|
|
8
|
+
import { collectRoutes } from './utils/index.js';
|
|
9
|
+
import { METHOD_NOT_ALLOWED, NOT_FOUND, OPENAPI_ERROR } from './utils/response';
|
|
10
10
|
// Import middleware
|
|
11
|
-
import { createValidationMiddleware } from '
|
|
11
|
+
import { createValidationMiddleware } from './middleware/validator.js';
|
|
12
12
|
export class Burger {
|
|
13
13
|
options;
|
|
14
14
|
/**
|
|
@@ -284,4 +284,4 @@ export class Burger {
|
|
|
284
284
|
}
|
|
285
285
|
}
|
|
286
286
|
// Export utils
|
|
287
|
-
export { setDir } from '
|
|
287
|
+
export { setDir } from './utils/index.js';
|
|
@@ -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 =
|
|
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
|
|
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 (
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
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
|
-
|
|
51
|
-
|
|
72
|
+
else {
|
|
73
|
+
if (!errors)
|
|
74
|
+
errors = {};
|
|
75
|
+
errors.params = result.error.issues;
|
|
52
76
|
}
|
|
53
77
|
}
|
|
54
|
-
// Validate query parameters.
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
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
|
-
|
|
71
|
-
|
|
86
|
+
else {
|
|
87
|
+
if (!errors)
|
|
88
|
+
errors = {};
|
|
89
|
+
errors.query = result.error.issues;
|
|
72
90
|
}
|
|
73
91
|
}
|
|
74
|
-
//
|
|
75
|
-
|
|
76
|
-
req.headers.get('Content-Type')
|
|
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
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
};
|
|
109
|
+
if (!errors)
|
|
110
|
+
errors = {};
|
|
111
|
+
errors.body = result.error.issues;
|
|
92
112
|
}
|
|
93
113
|
}
|
|
94
|
-
catch (
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
error
|
|
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 (
|
|
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
|
}
|
package/dist/src/utils/error.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { ROUTE_CONSTANTS, HTTP_METHODS, compareRoutes, getRouteSpecificity, collectRoutes, } from '
|
|
1
|
+
export { ROUTE_CONSTANTS, HTTP_METHODS, compareRoutes, getRouteSpecificity, collectRoutes, } from './routing.js';
|
|
2
2
|
/**
|
|
3
3
|
* Resolves the given path to the specified directory.
|
|
4
4
|
* @param directory the directory to resolve to
|
package/dist/src/utils/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { resolve } from 'path';
|
|
2
2
|
// Export constants
|
|
3
|
-
export { ROUTE_CONSTANTS, HTTP_METHODS, compareRoutes, getRouteSpecificity, collectRoutes, } from '
|
|
3
|
+
export { ROUTE_CONSTANTS, HTTP_METHODS, compareRoutes, getRouteSpecificity, collectRoutes, } from './routing.js';
|
|
4
4
|
/**
|
|
5
5
|
* Resolves the given path to the specified directory.
|
|
6
6
|
* @param directory the directory to resolve to
|