burger-api 0.9.6 → 1.0.0-beta

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.
Files changed (175) hide show
  1. package/README.md +84 -241
  2. package/dist/src/adapter/bun/index.d.ts +14 -0
  3. package/dist/src/adapter/bun/index.js +73 -0
  4. package/dist/src/adapter/bun/types.d.ts +15 -0
  5. package/dist/src/adapter/bun/types.js +1 -0
  6. package/dist/src/adapter/index.d.ts +1 -0
  7. package/dist/src/adapter/index.js +1 -0
  8. package/dist/src/adapter/types.d.ts +49 -0
  9. package/dist/src/adapter/types.js +1 -0
  10. package/dist/src/adapter/web-standard/fetch-handler.d.ts +39 -0
  11. package/dist/src/adapter/web-standard/fetch-handler.js +54 -0
  12. package/dist/src/adapter/web-standard/index.d.ts +8 -0
  13. package/dist/src/adapter/web-standard/index.js +7 -0
  14. package/dist/src/analysis/route-access-analyzer.d.ts +10 -0
  15. package/dist/src/analysis/route-access-analyzer.js +287 -0
  16. package/dist/src/chain/chain.d.ts +16 -0
  17. package/dist/src/chain/chain.js +17 -0
  18. package/dist/src/chain/flattener.d.ts +3 -0
  19. package/dist/src/chain/flattener.js +78 -0
  20. package/dist/src/chain/node.d.ts +25 -0
  21. package/dist/src/chain/node.js +1 -0
  22. package/dist/src/compiler/conventions.d.ts +67 -0
  23. package/dist/src/compiler/conventions.js +129 -0
  24. package/dist/src/compiler/index.d.ts +13 -0
  25. package/dist/src/compiler/index.js +11 -0
  26. package/dist/src/compiler/module-loader.d.ts +75 -0
  27. package/dist/src/compiler/module-loader.js +276 -0
  28. package/dist/src/compiler/route-module.d.ts +97 -0
  29. package/dist/src/compiler/route-module.js +1 -0
  30. package/dist/src/compiler/route-tree.d.ts +19 -0
  31. package/dist/src/compiler/route-tree.js +28 -0
  32. package/dist/src/compiler/scanner.d.ts +42 -0
  33. package/dist/src/compiler/scanner.js +201 -0
  34. package/dist/src/context/context-set.d.ts +26 -0
  35. package/dist/src/context/context-set.js +45 -0
  36. package/dist/src/context/context.d.ts +357 -0
  37. package/dist/src/context/context.js +401 -0
  38. package/dist/src/context/query-parser.d.ts +23 -0
  39. package/dist/src/context/query-parser.js +132 -0
  40. package/dist/src/context/route-access.d.ts +7 -0
  41. package/dist/src/context/route-access.js +18 -0
  42. package/dist/src/context/types.d.ts +62 -0
  43. package/dist/src/context/types.js +5 -0
  44. package/dist/src/core/asset-mime.d.ts +9 -0
  45. package/dist/src/core/asset-mime.js +35 -0
  46. package/dist/src/core/assets.d.ts +30 -0
  47. package/dist/src/core/assets.js +67 -0
  48. package/dist/src/core/docs-providers.d.ts +13 -0
  49. package/dist/src/core/docs-providers.js +89 -0
  50. package/dist/src/core/embedded-assets.d.ts +18 -0
  51. package/dist/src/core/embedded-assets.js +13 -0
  52. package/dist/src/core/openapi.d.ts +9 -10
  53. package/dist/src/core/openapi.js +333 -127
  54. package/dist/src/core/page-router.d.ts +13 -17
  55. package/dist/src/core/page-router.js +86 -55
  56. package/dist/src/core/server.d.ts +20 -11
  57. package/dist/src/core/server.js +41 -45
  58. package/dist/src/errors/forbidden.d.ts +14 -0
  59. package/dist/src/errors/forbidden.js +16 -0
  60. package/dist/src/errors/http-error.d.ts +47 -0
  61. package/dist/src/errors/http-error.js +146 -0
  62. package/dist/src/errors/method-not-allowed.d.ts +13 -0
  63. package/dist/src/errors/method-not-allowed.js +15 -0
  64. package/dist/src/errors/not-found.d.ts +14 -0
  65. package/dist/src/errors/not-found.js +16 -0
  66. package/dist/src/errors/unauthorized.d.ts +14 -0
  67. package/dist/src/errors/unauthorized.js +16 -0
  68. package/dist/src/index.d.ts +263 -50
  69. package/dist/src/index.js +919 -332
  70. package/dist/src/lifecycle/executor.d.ts +64 -0
  71. package/dist/src/lifecycle/executor.js +201 -0
  72. package/dist/src/lifecycle/hook-runner.d.ts +11 -0
  73. package/dist/src/lifecycle/hook-runner.js +156 -0
  74. package/dist/src/lifecycle/jit.d.ts +50 -0
  75. package/dist/src/lifecycle/jit.js +258 -0
  76. package/dist/src/lifecycle/transform.d.ts +26 -0
  77. package/dist/src/lifecycle/transform.js +99 -0
  78. package/dist/src/lifecycle/types.d.ts +135 -0
  79. package/dist/src/lifecycle/types.js +1 -0
  80. package/dist/src/plugin/composer.d.ts +3 -0
  81. package/dist/src/plugin/composer.js +28 -0
  82. package/dist/src/plugin/registry.d.ts +25 -0
  83. package/dist/src/plugin/registry.js +107 -0
  84. package/dist/src/plugin/types.d.ts +20 -0
  85. package/dist/src/plugin/types.js +1 -0
  86. package/dist/src/router/allow-cache.d.ts +20 -0
  87. package/dist/src/router/allow-cache.js +26 -0
  88. package/dist/src/router/compiler.d.ts +39 -0
  89. package/dist/src/router/compiler.js +817 -0
  90. package/dist/src/router/define.d.ts +67 -0
  91. package/dist/src/router/define.js +34 -0
  92. package/dist/src/router/index.d.ts +6 -0
  93. package/dist/src/router/index.js +5 -0
  94. package/dist/src/router/param-extract.d.ts +33 -0
  95. package/dist/src/router/param-extract.js +87 -0
  96. package/dist/src/router/regex-matcher.d.ts +42 -0
  97. package/dist/src/router/regex-matcher.js +216 -0
  98. package/dist/src/router/router.d.ts +201 -0
  99. package/dist/src/router/router.js +600 -0
  100. package/dist/src/router/static-map.d.ts +39 -0
  101. package/dist/src/router/static-map.js +48 -0
  102. package/dist/src/router/trie.d.ts +69 -0
  103. package/dist/src/router/trie.js +572 -0
  104. package/dist/src/router/types.d.ts +104 -0
  105. package/dist/src/router/types.js +1 -0
  106. package/dist/src/runtime/capabilities.d.ts +29 -0
  107. package/dist/src/runtime/capabilities.js +48 -0
  108. package/dist/src/types/index.d.ts +260 -109
  109. package/dist/src/types/index.js +1 -1
  110. package/dist/src/types/inference.d.ts +78 -0
  111. package/dist/src/types/inference.js +20 -0
  112. package/dist/src/types/openapi-config.d.ts +164 -0
  113. package/dist/src/types/openapi-config.js +8 -0
  114. package/dist/src/utils/env.d.ts +13 -0
  115. package/dist/src/utils/env.js +24 -0
  116. package/dist/src/utils/fs.d.ts +29 -0
  117. package/dist/src/utils/fs.js +75 -0
  118. package/dist/src/utils/index.d.ts +1 -1
  119. package/dist/src/utils/index.js +2 -2
  120. package/dist/src/utils/pathConversion.js +13 -7
  121. package/dist/src/utils/response.d.ts +42 -6
  122. package/dist/src/utils/response.js +172 -7
  123. package/dist/src/utils/routing.d.ts +32 -13
  124. package/dist/src/utils/routing.js +41 -18
  125. package/dist/src/utils/thenable.d.ts +8 -0
  126. package/dist/src/utils/thenable.js +12 -0
  127. package/dist/src/utils/timing-safe.d.ts +9 -0
  128. package/dist/src/utils/timing-safe.js +20 -0
  129. package/dist/src/utils/wildcard.d.ts +2 -9
  130. package/dist/src/utils/wildcard.js +20 -58
  131. package/dist/src/validation/adapter.d.ts +54 -0
  132. package/dist/src/validation/adapter.js +75 -0
  133. package/dist/src/validation/adapters/standard.d.ts +11 -0
  134. package/dist/src/validation/adapters/standard.js +110 -0
  135. package/dist/src/validation/adapters/zod.d.ts +9 -0
  136. package/dist/src/validation/adapters/zod.js +128 -0
  137. package/dist/src/validation/cache.d.ts +26 -0
  138. package/dist/src/validation/cache.js +35 -0
  139. package/dist/src/validation/coerce.d.ts +28 -0
  140. package/dist/src/validation/coerce.js +176 -0
  141. package/dist/src/validation/compiler.d.ts +27 -0
  142. package/dist/src/validation/compiler.js +191 -0
  143. package/dist/src/validation/error.d.ts +69 -0
  144. package/dist/src/validation/error.js +137 -0
  145. package/dist/src/validation/index.d.ts +16 -0
  146. package/dist/src/validation/index.js +12 -0
  147. package/dist/src/validation/response.d.ts +25 -0
  148. package/dist/src/validation/response.js +79 -0
  149. package/dist/src/validation/types.d.ts +148 -0
  150. package/dist/src/validation/types.js +6 -0
  151. package/dist/src/validation/validator.d.ts +39 -0
  152. package/dist/src/validation/validator.js +441 -0
  153. package/dist/src/ws/adapter.d.ts +219 -0
  154. package/dist/src/ws/adapter.js +623 -0
  155. package/dist/src/ws/compiler.d.ts +37 -0
  156. package/dist/src/ws/compiler.js +156 -0
  157. package/dist/src/ws/index.d.ts +11 -0
  158. package/dist/src/ws/index.js +8 -0
  159. package/dist/src/ws/platform.d.ts +81 -0
  160. package/dist/src/ws/platform.js +113 -0
  161. package/dist/src/ws/router.d.ts +48 -0
  162. package/dist/src/ws/router.js +174 -0
  163. package/dist/src/ws/scanner.d.ts +97 -0
  164. package/dist/src/ws/scanner.js +193 -0
  165. package/dist/src/ws/types.d.ts +380 -0
  166. package/dist/src/ws/types.js +213 -0
  167. package/package.json +72 -59
  168. package/dist/src/core/api-router.d.ts +0 -65
  169. package/dist/src/core/api-router.js +0 -264
  170. package/dist/src/core/swagger-ui.d.ts +0 -1
  171. package/dist/src/core/swagger-ui.js +0 -33
  172. package/dist/src/middleware/validator.d.ts +0 -14
  173. package/dist/src/middleware/validator.js +0 -133
  174. package/dist/src/utils/error.d.ts +0 -17
  175. package/dist/src/utils/error.js +0 -63
@@ -1,264 +0,0 @@
1
- // Import stuff from node
2
- import { readdir } from 'fs/promises';
3
- import * as path from 'path';
4
- // Import utils
5
- import { normalizePath, ROUTE_CONSTANTS, HTTP_METHODS } from '../utils/index';
6
- import { filePathToApiRoutePath } from '../utils/pathConversion';
7
- /**
8
- * ApiRouter class for handling file-based routing.
9
- * Loads routes from a directory structure and matches requests to the appropriate route handlers.
10
- * Supports dynamic segments (e.g., [id] ,(group),[...]) and HTTP method handlers.
11
- * Routes are sorted to prioritize static routes over dynamic and wildcard ones to prevent overlapping route issues.
12
- */
13
- export class ApiRouter {
14
- routesDir;
15
- prefix;
16
- /** The root of the trie where all routes will begin*/
17
- root = { children: new Map() };
18
- /**
19
- * Constructor for the ApiRouter class.
20
- * @param routesDir The directory path where route modules are located.
21
- * @param prefix Optional prefix to prepend to all routes (e.g., "api" becomes "/api/...").
22
- * @throws {Error} If the routes directory path is not provided.
23
- */
24
- constructor(routesDir, prefix = '') {
25
- this.routesDir = routesDir;
26
- this.prefix = prefix;
27
- if (!routesDir) {
28
- throw new Error('Routes directory path is required');
29
- }
30
- }
31
- /**
32
- * Getter for the routes trie.
33
- * @returns The root of the trie.
34
- */
35
- get routes() {
36
- return this.root;
37
- }
38
- /**
39
- * Loads all routes from the routes directory into the trie structure.
40
- * @returns {Promise<void>} A promise that resolves when all routes are loaded.
41
- * @throws {Error} If the routes directory is not found or if an error occurs during route loading.
42
- */
43
- async loadRoutes() {
44
- try {
45
- await this.scanDirectory(this.routesDir);
46
- }
47
- catch (error) {
48
- const errorMessage = error instanceof Error ? error.message : String(error);
49
- throw new Error(`Failed to load routes: ${errorMessage}`);
50
- }
51
- }
52
- /**
53
- * Inserts a route definition into the trie structure.
54
- * @param routeDef The route definition to insert, containing path, handlers, middleware, schema, and OpenAPI metadata.
55
- * @throws {Error} If the route definition is invalid or causes a conflict in the trie.
56
- */
57
- insertRoute(routeDef) {
58
- let node = this.root;
59
- const segments = routeDef.path.split('/').filter(Boolean);
60
- for (const segment of segments) {
61
- if (segment.startsWith(':')) {
62
- // Handle dynamic segments (:param)
63
- if (!node.paramChild) {
64
- node.paramChild = { children: new Map() };
65
- }
66
- node = node.paramChild;
67
- node.paramName = segment.slice(1);
68
- }
69
- else if (segment.startsWith('*')) {
70
- // Handle wildcard segments (*param)
71
- if (!node.wildcardChild) {
72
- node.wildcardChild = { children: new Map() };
73
- }
74
- node = node.wildcardChild;
75
- node.isWildcard = true; // Mark as wildcard route
76
- }
77
- else {
78
- // Handle static segments
79
- if (!node.children.has(segment)) {
80
- node.children.set(segment, { children: new Map() });
81
- }
82
- node = node.children.get(segment);
83
- }
84
- }
85
- node.route = routeDef;
86
- }
87
- /**
88
- * Recursively scans a directory for route modules (route.ts files) and loads them into the trie.
89
- * @param dir The current directory path to scan.
90
- * @param basePath The base path used to construct route paths from the directory structure.
91
- * @returns {Promise<void>} A promise that resolves when the directory scan is complete.
92
- * @throws {Error} If multiple dynamic folders are found at the same level or if directory access fails.
93
- */
94
- async scanDirectory(dir, basePath = '') {
95
- // Track route types at this directory level to prevent conflicts
96
- let dynamicFolderFound = false;
97
- let wildcardFolderFound = false;
98
- try {
99
- const entries = await readdir(dir, { withFileTypes: true });
100
- for (const entry of entries) {
101
- const entryPath = path.join(dir, entry.name);
102
- const relativePath = path.join(basePath, entry.name);
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
- }
109
- // Check if this is a dynamic or wildcard directory
110
- const isDynamic = entry.name.startsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_START) &&
111
- entry.name.endsWith(ROUTE_CONSTANTS.DYNAMIC_FOLDER_END) &&
112
- !entry.name.startsWith(ROUTE_CONSTANTS.WILDCARD_START);
113
- const isWildcard = entry.name === ROUTE_CONSTANTS.WILDCARD_SIMPLE;
114
- // Prevent conflicts between dynamic and wildcard routes
115
- if (isDynamic && wildcardFolderFound) {
116
- throw new Error(`Cannot mix dynamic and wildcard route folders in the same directory. ` +
117
- `Found dynamic folder '${entry.name}' but wildcard folder already exists in '${dir}'.`);
118
- }
119
- if (isWildcard && dynamicFolderFound) {
120
- throw new Error(`Cannot mix wildcard and dynamic route folders in the same directory. ` +
121
- `Found wildcard folder '${entry.name}' but dynamic folder already exists in '${dir}'.`);
122
- }
123
- if (isDynamic && dynamicFolderFound) {
124
- throw new Error(`Multiple dynamic route folders found in the same directory: ` +
125
- `'${entry.name}' conflicts with another dynamic folder in '${dir}'.`);
126
- }
127
- if (isWildcard && wildcardFolderFound) {
128
- throw new Error(`Multiple wildcard route folders found in the same directory: ` +
129
- `'${entry.name}' conflicts with another wildcard folder in '${dir}'.`);
130
- }
131
- // Update flags
132
- if (isDynamic)
133
- dynamicFolderFound = true;
134
- if (isWildcard)
135
- wildcardFolderFound = true;
136
- await this.scanDirectory(entryPath, relativePath);
137
- }
138
- else if (entry.isFile() && entry.name === 'route.ts') {
139
- await this.loadRouteModule(entryPath, relativePath);
140
- }
141
- }
142
- }
143
- catch (error) {
144
- if (error instanceof Error) {
145
- throw error; // Re-throw specific errors we created
146
- }
147
- throw new Error(`Failed to scan directory '${dir}': ${String(error)}`);
148
- }
149
- }
150
- /**
151
- * Loads a route module from a file and inserts it into the trie.
152
- * @param entryPath The full file system path to the route module (route.ts).
153
- * @param relativePath The relative path used to construct the route path.
154
- * @returns {Promise<void>} A promise that resolves when the module is loaded and inserted.
155
- * @throws {Error} If the route module fails to load or is invalid.
156
- */
157
- async loadRouteModule(entryPath, relativePath) {
158
- try {
159
- // Convert the file path to a route path
160
- const routePath = filePathToApiRoutePath(relativePath, this.prefix);
161
- console.info('Loading route:', routePath);
162
- // Get the module path like "D:\\Projects\\src\\api\\users\\route.ts"
163
- const modulePath = path.resolve(entryPath);
164
- // Import the module
165
- const routeModule = await import(modulePath);
166
- // Variable to store the handlers for each method
167
- const handlers = {};
168
- // Loop through all the HTTP methods and add the handler to the handlers object
169
- for (const method of HTTP_METHODS) {
170
- if (typeof routeModule[method] === 'function') {
171
- handlers[method] = routeModule[method];
172
- }
173
- }
174
- // Auto-inject minimal OPTIONS handler for CORS preflight when needed
175
- // Only if route defines any preflight-triggering methods and lacks an OPTIONS handler
176
- const PREFLIGHT_METHODS = [
177
- 'POST',
178
- 'PUT',
179
- 'DELETE',
180
- 'PATCH',
181
- ];
182
- let hasPreflightMethods = false;
183
- // Manual loop is slightly faster than Array.prototype.some in tight paths
184
- for (let i = 0; i < PREFLIGHT_METHODS.length; i++) {
185
- if (handlers[PREFLIGHT_METHODS[i]]) {
186
- hasPreflightMethods = true;
187
- break;
188
- }
189
- }
190
- // If the route defines any preflight-triggering methods and lacks an OPTIONS handler, auto-add an OPTIONS handler
191
- if (hasPreflightMethods && typeof handlers.OPTIONS !== 'function') {
192
- // if (process.env.NODE_ENV !== 'production') {
193
- // console.debug('Auto-added OPTIONS handler for route:', routePath);
194
- // }
195
- handlers.OPTIONS = () => new Response(null, { status: 204 });
196
- }
197
- const routeDef = {
198
- path: routePath,
199
- handlers,
200
- middleware: routeModule.middleware,
201
- schema: routeModule.schema,
202
- openapi: routeModule.openapi,
203
- isWildcard: routePath.includes(ROUTE_CONSTANTS.WILDCARD_SEGMENT_PREFIX),
204
- };
205
- this.insertRoute(routeDef);
206
- }
207
- catch (error) {
208
- throw new Error(`Failed to load route module '${entryPath}': ${String(error)}`);
209
- }
210
- }
211
- /**
212
- * Resolves a request to a route definition and its parameters.
213
- * @param pathname The normalized request pathname.
214
- * @param method The uppercase HTTP method.
215
- * @returns {{ route?: RouteDefinition; params: Record<string, string>; wildcardParams?: string[] }} An object containing the matched route (if any), extracted parameters, and wildcard segments (if applicable).
216
- * @throws {Error} If the request URL is malformed.
217
- */
218
- resolve(pathname, method) {
219
- try {
220
- const segments = pathname.split('/').filter(Boolean);
221
- let node = this.root;
222
- const params = {};
223
- let wildcardSegments = [];
224
- // Traverse the trie with proper prioritization
225
- for (let i = 0; i < segments.length; i++) {
226
- const segment = segments[i];
227
- // Priority 1: Exact static match (highest priority)
228
- if (node.children.has(segment)) {
229
- node = node.children.get(segment);
230
- }
231
- // Priority 2: Dynamic parameter match (medium priority)
232
- else if (node.paramChild) {
233
- node = node.paramChild;
234
- params[node.paramName] = segment;
235
- }
236
- // Priority 3: Collect remaining segments for wildcard (lowest priority)
237
- else {
238
- wildcardSegments = segments.slice(i);
239
- break;
240
- }
241
- }
242
- // Check if we have a route at the current node
243
- if (node.route?.handlers[method]) {
244
- return { route: node.route, params };
245
- }
246
- // If no route found but we have wildcard segments, check for wildcard route
247
- if (wildcardSegments.length > 0 &&
248
- node.wildcardChild?.route?.handlers[method]) {
249
- // Return wildcard segments so they can be added to req.wildcardParams
250
- return {
251
- route: node.wildcardChild.route,
252
- params,
253
- wildcardParams: wildcardSegments,
254
- };
255
- }
256
- return { params: {} };
257
- }
258
- catch (error) {
259
- // Log the error for better debugging
260
- console.error(`Error resolving API route for path "${pathname}":`, error);
261
- return { params: {} };
262
- }
263
- }
264
- }
@@ -1 +0,0 @@
1
- export declare const swaggerHtml = "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\">\n <title>API Documentation</title>\n <link rel=\"stylesheet\" href=\"https://unpkg.com/swagger-ui-dist/swagger-ui.css\" />\n <style>\n body {\n margin: 0;\n padding: 0;\n }\n </style>\n </head>\n <body>\n <div id=\"swagger-ui\"></div>\n <script src=\"https://unpkg.com/swagger-ui-dist/swagger-ui-bundle.js\"></script>\n <script>\n window.onload = function() {\n SwaggerUIBundle({\n url: '/openapi.json',\n dom_id: '#swagger-ui',\n presets: [\n SwaggerUIBundle.presets.apis,\n SwaggerUIBundle.SwaggerUIStandalonePreset\n ],\n layout: \"BaseLayout\",\n docExpansion: \"none\",\n filter: true,\n });\n };\n </script>\n </body>\n</html>";
@@ -1,33 +0,0 @@
1
- export const swaggerHtml = `<!DOCTYPE html>
2
- <html lang="en">
3
- <head>
4
- <meta charset="UTF-8">
5
- <title>API Documentation</title>
6
- <link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist/swagger-ui.css" />
7
- <style>
8
- body {
9
- margin: 0;
10
- padding: 0;
11
- }
12
- </style>
13
- </head>
14
- <body>
15
- <div id="swagger-ui"></div>
16
- <script src="https://unpkg.com/swagger-ui-dist/swagger-ui-bundle.js"></script>
17
- <script>
18
- window.onload = function() {
19
- SwaggerUIBundle({
20
- url: '/openapi.json',
21
- dom_id: '#swagger-ui',
22
- presets: [
23
- SwaggerUIBundle.presets.apis,
24
- SwaggerUIBundle.SwaggerUIStandalonePreset
25
- ],
26
- layout: "BaseLayout",
27
- docExpansion: "none",
28
- filter: true,
29
- });
30
- };
31
- </script>
32
- </body>
33
- </html>`;
@@ -1,14 +0,0 @@
1
- import type { RouteSchema, Middleware } from '../types/index';
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
- */
14
- export declare function createValidationMiddleware(schema: RouteSchema): Middleware;
@@ -1,133 +0,0 @@
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
- */
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
- */
39
- return async (req) => {
40
- // If the request has been validated, continue.
41
- if (req.validated) {
42
- return undefined; // Proceed to the next middleware or handler
43
- }
44
- // Determine the HTTP method (in lowercase) to match the schema.
45
- const method = (req.method || 'get').toLowerCase();
46
- // Get the schema for the current method.
47
- const methodSchema = methodMap[method];
48
- // If there's no schema for this method, continue.
49
- if (!methodSchema) {
50
- return undefined; // Proceed to the next middleware or handler
51
- }
52
- // Get the schemas for the current method.
53
- const { paramsSchema, querySchema, bodySchema, hasParams, hasQuery, hasBody, } = methodSchema;
54
- /**
55
- * Object to store validated request data. This will be attached to the
56
- * request object if validation is successful. The object will contain
57
- * validated data for the following fields:
58
- *
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).
62
- */
63
- const validated = {};
64
- // Lazy errors — create only if/when an error occurs
65
- let errors = null;
66
- // Validate URL parameters (if available and schema provided).
67
- if (hasParams && req.params && paramsSchema) {
68
- const result = paramsSchema.safeParse(req.params);
69
- if (result.success) {
70
- validated.params = result.data;
71
- }
72
- else {
73
- if (!errors)
74
- errors = {};
75
- errors.params = result.error.issues;
76
- }
77
- }
78
- // Validate query parameters if available and schema provided.
79
- if (hasQuery && querySchema) {
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;
85
- }
86
- else {
87
- if (!errors)
88
- errors = {};
89
- errors.query = result.error.issues;
90
- }
91
- }
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 &&
98
- contentType?.includes('application/json') &&
99
- bodySchema) {
100
- try {
101
- // Attempt to parse the JSON body.
102
- const bodyData = await req.json();
103
- const result = bodySchema.safeParse(bodyData);
104
- if (result.success) {
105
- // Set the validated body.
106
- validated.body = result.data;
107
- // Set the json method to return the validated body.
108
- req.json = async () => result.data;
109
- }
110
- else {
111
- if (!errors)
112
- errors = {};
113
- errors.body = result.error.issues;
114
- }
115
- }
116
- catch (error) {
117
- // Create a message from the error.
118
- const msg = error instanceof Error ? error.message : String(error);
119
- if (!errors)
120
- errors = {};
121
- errors.body = [{ message: msg }];
122
- }
123
- }
124
- if (errors) {
125
- // If validation fails, return a 400 response with error details.
126
- return Response.json({ errors }, { status: 400 });
127
- }
128
- // Attach validated data to the request.
129
- req.validated = validated;
130
- // Continue to the next middleware or handler.
131
- return undefined; // Proceed
132
- };
133
- }
@@ -1,17 +0,0 @@
1
- /**
2
- * Generates an HTTP error response based on the request's "Accept" header.
3
- *
4
- * If the "Accept" header includes "text/html" and debugging is enabled, it returns
5
- * an HTML response with the error message and stack trace.
6
- *
7
- * If the "Accept" header includes "application/json" or debugging is enabled, it
8
- * returns a JSON response with the error message and optionally the stack trace.
9
- *
10
- * Otherwise, it returns a plain text response indicating an internal server error.
11
- *
12
- * @param error - The error object or message to include in the response.
13
- * @param req - The incoming HTTP request object.
14
- * @param debug - A boolean indicating whether debugging information should be included.
15
- * @returns A Response object with the appropriate error details and status code.
16
- */
17
- export declare function errorResponse(error: unknown, req: Request, debug: boolean): Response;
@@ -1,63 +0,0 @@
1
- import { normalizePath } from './index';
2
- /**
3
- * Generates an HTTP error response based on the request's "Accept" header.
4
- *
5
- * If the "Accept" header includes "text/html" and debugging is enabled, it returns
6
- * an HTML response with the error message and stack trace.
7
- *
8
- * If the "Accept" header includes "application/json" or debugging is enabled, it
9
- * returns a JSON response with the error message and optionally the stack trace.
10
- *
11
- * Otherwise, it returns a plain text response indicating an internal server error.
12
- *
13
- * @param error - The error object or message to include in the response.
14
- * @param req - The incoming HTTP request object.
15
- * @param debug - A boolean indicating whether debugging information should be included.
16
- * @returns A Response object with the appropriate error details and status code.
17
- */
18
- export function errorResponse(error, req, debug) {
19
- // Extract request details
20
- const method = req.method;
21
- const url = req.url;
22
- const logPrefix = `[${method} ${url}]`;
23
- // Log detailed error context
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';
32
- const acceptHeader = req.headers.get('accept') || '';
33
- if (acceptHeader.includes('text/html') && debug) {
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>
35
- `;
36
- // Return the html response
37
- return new Response(body, {
38
- status: 500,
39
- headers: { 'Content-Type': 'text/html' },
40
- });
41
- }
42
- else if (debug) {
43
- // Log detailed error context
44
- console.error(`${logPrefix} Error:`, error);
45
- // Create a JSON response
46
- const body = JSON.stringify({
47
- request: `${method} ${url}`,
48
- error: error instanceof Error ? error.message : 'Unknown error',
49
- stack: error instanceof Error ? normalizePath(error.stack || '') : '',
50
- });
51
- // Return the JSON response
52
- return new Response(body, {
53
- status: 500,
54
- headers: { 'Content-Type': 'application/json' },
55
- });
56
- }
57
- else {
58
- // Log detailed error context
59
- console.error(`${logPrefix} Error:`, error);
60
- // Return a plain text response
61
- return new Response('Internal Server Error', { status: 500 });
62
- }
63
- }