burger-api 0.9.7 → 1.0.0-beta.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.
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 +240 -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 +49 -0
  61. package/dist/src/errors/http-error.js +155 -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 +275 -50
  69. package/dist/src/index.js +974 -333
  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 +867 -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 +214 -0
  99. package/dist/src/router/router.js +670 -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 +189 -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 +6 -7
  130. package/dist/src/utils/wildcard.js +38 -55
  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 +85 -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 +230 -0
  154. package/dist/src/ws/adapter.js +660 -0
  155. package/dist/src/ws/compiler.d.ts +37 -0
  156. package/dist/src/ws/compiler.js +178 -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 +82 -0
  160. package/dist/src/ws/platform.js +122 -0
  161. package/dist/src/ws/router.d.ts +47 -0
  162. package/dist/src/ws/router.js +183 -0
  163. package/dist/src/ws/scanner.d.ts +97 -0
  164. package/dist/src/ws/scanner.js +253 -0
  165. package/dist/src/ws/types.d.ts +381 -0
  166. package/dist/src/ws/types.js +213 -0
  167. package/package.json +72 -60
  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,80 +1,136 @@
1
1
  // Import stuff from Zod 4.x
2
- import { toJSONSchema, ZodArray, ZodBoolean, ZodNumber, ZodObject, ZodOptional, ZodString, ZodType, } from 'zod';
2
+ import { toJSONSchema, ZodType } from 'zod';
3
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.
4
+ * Builds OpenAPI parameters from an object schema, using the input side so
5
+ * `.default()` / `.optional()` fields are not required and each parameter
6
+ * keeps its enum / format / default / min / max.
7
+ *
8
+ * Zod objects and configured Standard Schema converters yield real JSON
9
+ * Schema. A Standard Schema with no JSON Schema falls back to its field map
10
+ * (`shape` / `entries`) and emits each name with `schema: {}` — never a
11
+ * silent omission.
7
12
  */
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
13
+ function buildParameters(schema, location, mapJsonSchema) {
14
+ const json = schemaToJsonSchema(schema, mapJsonSchema, 'input');
15
+ const properties = json?.properties;
16
+ if (properties && typeof properties === 'object') {
17
+ const required = new Set(json?.required ?? []);
18
+ return Object.entries(properties).map(([name, propertySchema]) => {
19
+ const source = typeof propertySchema === 'object' && propertySchema !== null
20
+ ? propertySchema
21
+ : {};
22
+ const { description, ...rest } = source;
23
+ return {
24
+ name,
25
+ in: location,
26
+ // OpenAPI requires path parameters to be marked required.
27
+ required: location === 'path' || required.has(name),
28
+ schema: rest,
29
+ description: typeof description === 'string'
30
+ ? description
31
+ : `${location} parameter ${name}`,
32
+ };
33
+ });
34
+ }
35
+ // No JSON Schema available: use the schema's structural field map.
36
+ const fields = structuralFieldNames(schema);
37
+ if (!fields)
38
+ return [];
39
+ return fields.map((name) => ({
40
+ name,
41
+ in: location,
42
+ required: location === 'path',
43
+ schema: {},
44
+ description: `${location} parameter ${name}`,
45
+ }));
23
46
  }
24
47
  /**
25
- * Builds an array of OpenAPI 3.0 parameters based on the Zod schema.
26
- * For each property in the Zod schema, an OpenAPI parameter is constructed
27
- * with the same name and required flag. The schema of the parameter is set
28
- * to a string type.
29
- * @param zodSchema - The Zod schema to construct parameters from. Can be undefined.
30
- * @param location - The location of the parameter. Must be either "path" or "query".
31
- * @returns An array of OpenAPI 3.0 parameter objects or an empty array if the Zod schema is undefined.
48
+ * Field names from common structural maps: zod's `shape`, valibot's
49
+ * `entries`. Returns undefined when the schema exposes no field map.
32
50
  */
33
- function buildParameters(zodSchema, location) {
34
- const parameters = [];
35
- if (isZodObjectSchema(zodSchema)) {
36
- // Get the shape of the Zod schema
37
- const shape = zodSchema.shape;
38
- for (const key in shape) {
39
- // Get the definition of the field
40
- const fieldDef = shape[key];
41
- // Determine if the field is optional
42
- const isOptional = fieldDef instanceof ZodOptional;
43
- // Map the Zod type to an OpenAPI schema type
44
- const type = mapZodTypeToOpenAPIType(fieldDef);
45
- parameters.push({
46
- // Set the name of the parameter
47
- name: key,
48
- // Type of the parameter path or query
49
- in: location,
50
- // Set the required flag
51
- required: !isOptional,
52
- // Set the schema type
53
- schema: { type },
54
- // Description of the parameter
55
- description: `${location} parameter ${key}`,
56
- });
51
+ function structuralFieldNames(schema) {
52
+ if (typeof schema !== 'object' || schema === null)
53
+ return undefined;
54
+ const candidate = schema;
55
+ const map = candidate.shape ?? candidate.entries;
56
+ if (map && typeof map === 'object' && !Array.isArray(map)) {
57
+ return Object.keys(map);
58
+ }
59
+ return undefined;
60
+ }
61
+ /**
62
+ * Whether the body schema accepts `undefined` (so the request body is not
63
+ * required). Runs once at document generation, never per request.
64
+ */
65
+ function acceptsUndefined(schema) {
66
+ const zod = schema;
67
+ if (typeof zod.safeParse === 'function') {
68
+ try {
69
+ const result = zod.safeParse(undefined);
70
+ return result?.success === true;
71
+ }
72
+ catch {
73
+ return false;
57
74
  }
58
75
  }
59
- return parameters;
76
+ const standard = schema;
77
+ try {
78
+ const result = standard['~standard']?.validate?.(undefined);
79
+ if (result === undefined || result instanceof Promise)
80
+ return false;
81
+ return !('issues' in result && result.issues);
82
+ }
83
+ catch {
84
+ return false;
85
+ }
60
86
  }
61
- function isZodObjectSchema(value) {
62
- return value instanceof ZodObject;
87
+ /**
88
+ * Converts a SchemaInput to JSON Schema: configured converter first, Zod's
89
+ * `toJSONSchema` as fallback.
90
+ *
91
+ * `io` selects the request side (`'input'`, where `.default()` fields are
92
+ * optional) or the response side (`'output'`).
93
+ */
94
+ function schemaToJsonSchema(schema, mapJsonSchema, io = 'output') {
95
+ if (schema instanceof ZodType) {
96
+ const jsonSchema = toJSONSchema(schema, {
97
+ io,
98
+ unrepresentable: 'any',
99
+ });
100
+ // Zod emits `$schema`, which is illegal inside an OpenAPI `schema`
101
+ // object (OAS defines its own dialect) — drop it.
102
+ delete jsonSchema.$schema;
103
+ return jsonSchema;
104
+ }
105
+ // Standard Schema: try configured converters
106
+ if (mapJsonSchema &&
107
+ (typeof schema === 'object' || typeof schema === 'function') &&
108
+ schema !== null) {
109
+ const stdSchema = schema;
110
+ const vendor = stdSchema['~standard']?.vendor ??
111
+ stdSchema.__vendor;
112
+ if (typeof vendor === 'string' && mapJsonSchema[vendor]) {
113
+ return mapJsonSchema[vendor](schema);
114
+ }
115
+ }
116
+ // Standard JSON Schema: validators that can describe themselves.
117
+ const converter = schema?.['~standard']?.jsonSchema;
118
+ if (converter && typeof converter[io] === 'function') {
119
+ const jsonSchema = converter[io]({ target: 'draft-2020-12' });
120
+ delete jsonSchema.$schema;
121
+ return jsonSchema;
122
+ }
123
+ return undefined;
63
124
  }
64
125
  /**
65
- * Builds a request body object for OpenAPI based on a Zod schema.
66
- * Converts the Zod schema into JSON schema and constructs an OpenAPI
67
- * requestBody object with content type "application/json".
68
- * @param zodSchema - The Zod schema to convert into JSON schema.
69
- * @returns An OpenAPI requestBody object, or undefined if no schema is provided.
126
+ * Builds a request body object for OpenAPI based on a SchemaInput.
70
127
  */
71
- function buildRequestBody(zodSchema) {
72
- // If no schema is provided, return undefined
73
- if (!(zodSchema instanceof ZodType))
128
+ function buildRequestBody(zodSchema, mapJsonSchema) {
129
+ if (!(zodSchema instanceof ZodType) && !isStandardSchema(zodSchema))
130
+ return undefined;
131
+ const jsonSchema = schemaToJsonSchema(zodSchema, mapJsonSchema, 'input');
132
+ if (!jsonSchema)
74
133
  return undefined;
75
- // Convert the Zod schema to a JSON schema
76
- const jsonSchema = toJSONSchema(zodSchema);
77
- // Return the OpenAPI requestBody object
78
134
  return {
79
135
  content: {
80
136
  'application/json': {
@@ -82,88 +138,238 @@ function buildRequestBody(zodSchema) {
82
138
  },
83
139
  },
84
140
  description: 'Request body',
85
- required: true,
141
+ // Required unless the schema itself accepts `undefined`.
142
+ required: !acceptsUndefined(zodSchema),
86
143
  };
87
144
  }
88
145
  /**
89
- * Converts a route path from colon-based dynamic segments to OpenAPI's curly brace syntax.
90
- * Also handles wildcard routes.
91
- *
92
- * @param routePath The original route path with colon-based dynamic segments (e.g., "/user/:id") or wildcards (e.g., "/files/*").
93
- * @returns The converted route path with curly brace syntax (e.g., "/user/{id}") or wildcard format (e.g., "/files/*").
146
+ * Type guard for Standard Schema objects (has ~standard property).
147
+ */
148
+ function isStandardSchema(value) {
149
+ return ((typeof value === 'object' || typeof value === 'function') &&
150
+ value !== null &&
151
+ '~standard' in value);
152
+ }
153
+ /**
154
+ * Builds OpenAPI responses from a route's response schema, converting each
155
+ * status code's schema to JSON Schema.
156
+ */
157
+ function buildResponses(responseSchema, openapiMetaResponses, mapJsonSchema) {
158
+ // Auto-generate from schema.response
159
+ const autoGenerated = {};
160
+ if (responseSchema) {
161
+ for (const [statusCode, schema] of Object.entries(responseSchema)) {
162
+ const jsonSchema = schemaToJsonSchema(schema, mapJsonSchema);
163
+ autoGenerated[statusCode] = {
164
+ description: statusCode.startsWith('2')
165
+ ? 'Successful response'
166
+ : statusCode.startsWith('4')
167
+ ? 'Client error'
168
+ : statusCode.startsWith('5')
169
+ ? 'Server error'
170
+ : `Response ${statusCode}`,
171
+ content: jsonSchema
172
+ ? {
173
+ 'application/json': {
174
+ schema: jsonSchema,
175
+ },
176
+ }
177
+ : undefined,
178
+ };
179
+ }
180
+ }
181
+ // User-provided responses override auto-generated ones.
182
+ if (openapiMetaResponses) {
183
+ return { ...autoGenerated, ...openapiMetaResponses };
184
+ }
185
+ return Object.keys(autoGenerated).length > 0
186
+ ? autoGenerated
187
+ : { '200': { description: 'Successful response' } };
188
+ }
189
+ /**
190
+ * Converts `:param` and `*` route segments to OpenAPI's curly brace syntax.
191
+ * Param names may carry `-` and `_`; wildcards document as `{wildcard}`.
94
192
  */
95
193
  function convertPathForOpenAPI(routePath) {
96
- // Fast path: if no special chars, return as-is
97
194
  if (routePath.indexOf(':') === -1 && routePath.indexOf('*') === -1) {
98
195
  return routePath;
99
196
  }
100
- // Replace occurrences of :param with {param}
101
- let converted = routePath.replace(/:([a-zA-Z0-9_]+)/g, '{$1}');
102
- // Handle wildcard routes
103
- // OpenAPI 3.0 doesn't have official wildcard syntax, so we keep /* as-is
104
- // This will display in Swagger as /api/files/* which is intuitive and common
105
- // Alternative: convert to {path*} format if preferred
106
- // converted = converted.replace(/\/\*$/g, '/{path*}');
107
- return converted;
197
+ return routePath
198
+ .replace(/:([a-zA-Z0-9_-]+)/g, '{$1}')
199
+ .replace(/\*+/g, '{wildcard}');
108
200
  }
109
- export function generateOpenAPIDocument(apiRoutes, options) {
110
- const openapiDoc = {
111
- openapi: '3.0.0',
112
- info: {
113
- title: options.title || 'Burger API',
114
- description: options.description || 'Burger API documentation',
115
- version: options.version || '1.0.0',
116
- },
201
+ /**
202
+ * Generates a full OpenAPI 3.1 document from API routes.
203
+ *
204
+ * @param apiRoutes Compiled route definitions.
205
+ * @param options Server options (fallback metadata source).
206
+ * @param config OpenAPI config from `openapi.config.ts` (primary metadata source).
207
+ */
208
+ export function generateOpenAPIDocument(apiRoutes, options, config) {
209
+ // Build info block: config overrides ServerOptions
210
+ const info = {
211
+ title: config?.title || options.title || 'Burger API',
212
+ description: config?.description ||
213
+ options.description ||
214
+ 'Burger API documentation',
215
+ version: config?.version || options.version || '1.0.0',
216
+ };
217
+ if (config?.contact)
218
+ info.contact = config.contact;
219
+ if (config?.license)
220
+ info.license = config.license;
221
+ if (config?.termsOfService)
222
+ info.termsOfService = config.termsOfService;
223
+ const doc = {
224
+ // Zod emits JSON Schema draft 2020-12, which OpenAPI 3.1 matches.
225
+ openapi: '3.1.0',
226
+ info,
117
227
  paths: {},
118
228
  };
119
- // Iterate over each route
229
+ // Servers
230
+ if (config?.servers && config.servers.length > 0) {
231
+ doc.servers = config.servers;
232
+ }
233
+ // External docs
234
+ if (config?.externalDocs) {
235
+ doc.externalDocs = config.externalDocs;
236
+ }
237
+ // Root security defaults to `[]` (no auth required): core is auth-agnostic,
238
+ // and omitting it makes strict linters flag every operation.
239
+ doc.security =
240
+ config?.security && config.security.length > 0
241
+ ? config.security
242
+ : [];
243
+ // Collect tags used across operations
244
+ const tagSet = new Set();
245
+ // OperationIds must be unique and sanitized for OpenAPI
246
+ // (`^[a-zA-Z0-9_.-]+$`); collisions get a numeric suffix.
247
+ const usedOperationIds = new Set();
120
248
  for (const route of apiRoutes) {
121
- // Convert colon-based dynamic segments to OpenAPI's {param} syntax
122
249
  const openApiPath = convertPathForOpenAPI(route.path);
123
- // Initialize path object if necessary
124
- openapiDoc.paths[openApiPath] = openapiDoc.paths[openApiPath] || {};
125
- // For each HTTP method in the route, add an OpenAPI operation.
250
+ doc.paths[openApiPath] = doc.paths[openApiPath] || {};
126
251
  for (const method in route.handlers) {
127
- // If the handler is not a function, skip
128
- if (typeof route.handlers[method] !== 'function')
252
+ // Handler/schema/openapi maps are union-keyed at the type level,
253
+ // so widen per map for runtime lookups.
254
+ const handlers = route.handlers;
255
+ const openapiMeta = (route.openapi ?? {});
256
+ const schema = (route.schema ?? {});
257
+ if (typeof handlers[method] !== 'function')
129
258
  continue;
130
- // Convert HTTP method to lowercase
259
+ // Auto-generated OPTIONS (CORS preflight) is not a documented
260
+ // operation.
261
+ if (handlers[method].isAutoOptions) {
262
+ continue;
263
+ }
131
264
  const lowerMethod = method.toLowerCase();
132
- // Use provided openapi metadata if available; else, fallback to auto-generated values.
133
- const methodMeta = route.openapi?.[lowerMethod] || {};
134
- // Generate an operationId: e.g., "get_api_product"
135
- const operationId = methodMeta.operationId ||
136
- `${lowerMethod}_${route.path.replace(/[\/:]/g, '_')}`;
137
- // Build parameters for both path and query from the schema.
138
- let parameters = [];
139
- if (route.schema && route.schema[lowerMethod]) {
140
- const schemaDef = route.schema[lowerMethod];
141
- parameters = [
142
- ...buildParameters(schemaDef.params, 'path'),
143
- ...buildParameters(schemaDef.query, 'query'),
144
- ];
265
+ try {
266
+ const methodMeta = openapiMeta[lowerMethod] || {};
267
+ // Sanitize the operationId to OpenAPI-legal characters and
268
+ // dedupe collisions.
269
+ let operationId = methodMeta.operationId ||
270
+ `${lowerMethod}_${route.path.replace(/[^a-zA-Z0-9_.-]+/g, '_')}`;
271
+ if (usedOperationIds.has(operationId)) {
272
+ let suffix = 2;
273
+ let candidate = `${operationId}_${suffix}`;
274
+ while (usedOperationIds.has(candidate)) {
275
+ suffix += 1;
276
+ candidate = `${operationId}_${suffix}`;
277
+ }
278
+ operationId = candidate;
279
+ }
280
+ usedOperationIds.add(operationId);
281
+ let parameters = [];
282
+ if (schema[lowerMethod]) {
283
+ const schemaDef = schema[lowerMethod];
284
+ const mapJsonSchema = config?.mapJsonSchema;
285
+ parameters = [
286
+ ...buildParameters(schemaDef.params, 'path', mapJsonSchema),
287
+ ...buildParameters(schemaDef.query, 'query', mapJsonSchema),
288
+ ...buildParameters(schemaDef.headers, 'header', mapJsonSchema),
289
+ ...buildParameters(schemaDef.cookies, 'cookie', mapJsonSchema),
290
+ ];
291
+ }
292
+ // Every operation on a templated path must define its path
293
+ // parameters (OAS `path-parameters-defined`), even with no
294
+ // schema.
295
+ for (const match of openApiPath.matchAll(/\{([^}]+)\}/g)) {
296
+ const name = match[1];
297
+ if (!parameters.some((p) => p.in === 'path' && p.name === name)) {
298
+ parameters.unshift({
299
+ name,
300
+ in: 'path',
301
+ required: true,
302
+ schema: { type: 'string' },
303
+ description: name === 'wildcard'
304
+ ? 'Wildcard path segments (may contain slashes)'
305
+ : `Path parameter ${name}`,
306
+ });
307
+ }
308
+ }
309
+ let requestBody = undefined;
310
+ if (schema[lowerMethod]?.body) {
311
+ requestBody = buildRequestBody(schema[lowerMethod].body, config?.mapJsonSchema);
312
+ }
313
+ const responses = buildResponses(schema[lowerMethod]?.response, methodMeta.responses, config?.mapJsonSchema);
314
+ // Collect tags
315
+ const tags = methodMeta.tags || [];
316
+ for (const tag of tags) {
317
+ tagSet.add(tag);
318
+ }
319
+ doc.paths[openApiPath][lowerMethod] = {
320
+ operationId,
321
+ summary: methodMeta.summary ||
322
+ `Summary for ${method} ${route.path}`,
323
+ description: methodMeta.description || '',
324
+ tags,
325
+ deprecated: methodMeta.deprecated || false,
326
+ parameters,
327
+ requestBody,
328
+ responses,
329
+ externalDocs: methodMeta.externalDocs || undefined,
330
+ };
145
331
  }
146
- // Build requestBody if a body schema exists.
147
- let requestBody = undefined;
148
- if (route.schema && route.schema[lowerMethod]?.body) {
149
- requestBody = buildRequestBody(route.schema[lowerMethod].body);
332
+ catch (error) {
333
+ // A schema the converter still cannot express must not take
334
+ // the whole document (or startup) down — document the
335
+ // operation with an empty object and warn once.
336
+ console.warn(`[burger-api] OpenAPI: could not build ${method.toUpperCase()} ${route.path} — documenting it without schema details:`, error);
337
+ doc.paths[openApiPath][lowerMethod] = {};
150
338
  }
151
- openapiDoc.paths[openApiPath][lowerMethod] = {
152
- operationId,
153
- summary: methodMeta.summary || `Summary for ${method} ${route.path}`,
154
- description: methodMeta.description || '',
155
- tags: methodMeta.tags || [],
156
- deprecated: methodMeta.deprecated || false,
157
- parameters: parameters,
158
- requestBody: requestBody,
159
- responses: methodMeta.responses || {
160
- '200': {
161
- description: 'Successful response',
339
+ }
340
+ }
341
+ // Emit the top-level tags array.
342
+ if (tagSet.size > 0) {
343
+ doc.tags = Array.from(tagSet).map((name) => ({ name }));
344
+ }
345
+ // Add components.schemas.ProblemDetail (RFC 9457) when the doc has paths.
346
+ if (Object.keys(doc.paths).length > 0) {
347
+ doc.components = {
348
+ schemas: {
349
+ ProblemDetail: {
350
+ type: 'object',
351
+ properties: {
352
+ type: {
353
+ type: 'string',
354
+ description: 'URI reference identifying the problem type',
355
+ },
356
+ title: {
357
+ type: 'string',
358
+ description: 'Short human-readable summary',
359
+ },
360
+ status: {
361
+ type: 'integer',
362
+ description: 'HTTP status code',
363
+ },
364
+ detail: {
365
+ type: 'string',
366
+ description: 'Human-readable explanation',
367
+ },
162
368
  },
369
+ required: ['type', 'title', 'status'],
163
370
  },
164
- externalDocs: methodMeta.externalDocs || undefined,
165
- };
166
- }
371
+ },
372
+ };
167
373
  }
168
- return openapiDoc;
374
+ return doc;
169
375
  }
@@ -1,8 +1,7 @@
1
- import type { PageDefinition } from '../types/index';
1
+ import type { PageDefinition } from '../types/index.js';
2
2
  /**
3
- * PageRouter class for handling file-based page routing.
4
- * Loads pages from a directory structure and matches requests to the appropriate page handlers.
5
- * Supports dynamic segments (e.g., [id]) and uses default exports as page handlers.
3
+ * File-based page router: loads pages from a directory tree, matches requests,
4
+ * and supports dynamic segments (e.g. `[id]`). Default exports are handlers.
6
5
  */
7
6
  export declare class PageRouter {
8
7
  private pagesDir;
@@ -10,37 +9,34 @@ export declare class PageRouter {
10
9
  /** Array of loaded page definitions */
11
10
  pages: PageDefinition[];
12
11
  /**
13
- * Constructor for the PageRouter class.
14
- * @param pagesDir The directory path where page modules are located.
15
- * @param prefix Optional prefix to prepend to all routes (e.g., "pages" becomes "/pages/...").
12
+ * @param pagesDir Directory containing page modules.
13
+ * @param prefix Optional prefix for every route (e.g. "pages" → "/pages/...").
16
14
  */
17
15
  constructor(pagesDir: string, prefix?: string);
18
16
  /**
19
- * Loads page modules from the specified directory and adds them to the pages array.
20
- * After loading, sorts the pages to prioritize static routes over dynamic ones based on specificity.
21
- * @returns A promise that resolves when all page modules have been loaded and sorted.
17
+ * Loads and sorts page modules (static routes before dynamic ones).
22
18
  */
23
19
  loadPages(): Promise<void>;
24
20
  /**
25
- * Recursively scans the directory for page modules and adds them to the pages array.
26
- * @param dir The current directory to scan.
27
- * @param basePath The base path for constructing the route path.
21
+ * Recursively scans `dir` for page modules.
22
+ * @param dir Directory to scan.
23
+ * @param basePath Base path used to build route paths.
28
24
  */
29
25
  private scanDirectory;
30
26
  /**
31
- * Resolves the given request by finding a matching page and extracting dynamic parameters.
27
+ * Finds the page matching the request and extracts dynamic params.
32
28
  * @param request The request to resolve.
33
- * @returns An object containing the matched page and parameters, or an empty params object if no match.
29
+ * @returns The matched page + params, or empty params when nothing matches.
34
30
  */
35
31
  resolve(request: Request): {
36
32
  page?: PageDefinition;
37
33
  params: Record<string, string>;
38
34
  };
39
35
  /**
40
- * Checks if the request path matches the page path, extracting dynamic parameters if matched.
36
+ * Matches a request path against a page path.
41
37
  * @param requestPath The request path to check.
42
38
  * @param pagePath The page path to match against.
43
- * @returns A record of dynamic parameters if matched, otherwise null.
39
+ * @returns Captured params when matched, otherwise null.
44
40
  */
45
41
  private matchRoute;
46
42
  }