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
@@ -0,0 +1,137 @@
1
+ /**
2
+ * The validation error system — structured `ValidationError` + mode-gated
3
+ * renderers.
4
+ *
5
+ * `ValidationError` extends `HTTPError` (status 422) and carries structured
6
+ * `ValidationIssue[]` per slot. Renders RFC 9457 Problem Details by default;
7
+ * dev shows full issues, production strips internals. A custom
8
+ * `errorRenderer` overrides rendering. Production bodies never leak stacks or
9
+ * schema internals.
10
+ */
11
+ import { HTTPError, renderHTTPError } from '../errors/http-error.js';
12
+ /**
13
+ * A structured validation error thrown when request validation fails.
14
+ *
15
+ * Extends `HTTPError` with status 422. Carries the failing slot and
16
+ * normalized issues. Enters the `onError` pipeline; if no user hook
17
+ * handles it, the framework renders an RFC 9457 response.
18
+ */
19
+ export class ValidationError extends HTTPError {
20
+ name = 'ValidationError';
21
+ status;
22
+ /** The primary request slot that failed validation. */
23
+ slot;
24
+ /** Normalized field-level issues (all slots combined). */
25
+ issues;
26
+ /** Per-slot grouping of issues, when available. */
27
+ errorsBySlot;
28
+ constructor(slot, issues, options) {
29
+ const summary = issues.length === 1
30
+ ? issues[0].message
31
+ : `${issues.length} validation errors`;
32
+ const status = options?.status ?? 422;
33
+ super(status, `${slot}: ${summary}`, options);
34
+ this.status = status;
35
+ this.slot = slot;
36
+ this.issues = issues;
37
+ this.errorsBySlot = options?.errorsBySlot;
38
+ }
39
+ /**
40
+ * Creates a `ValidationError` from a failed `ValidationResult`.
41
+ */
42
+ static from(slot, result) {
43
+ if (result.success)
44
+ return null;
45
+ return new ValidationError(slot, result.issues);
46
+ }
47
+ /**
48
+ * Renders this error into an RFC 9457 Problem Details response.
49
+ *
50
+ * Dev mode includes full issue details; production strips internal path
51
+ * information. A custom `errorRenderer` takes precedence when provided.
52
+ */
53
+ toResponse(isDev, config = {}) {
54
+ if (config.errorRenderer) {
55
+ return config.errorRenderer({ success: false, issues: this.issues }, { slot: this.slot, status: this.status });
56
+ }
57
+ const format = config.errorFormat ?? 'problem+json';
58
+ // Use stored errorsBySlot if available, otherwise group by this.slot.
59
+ const grouped = this.errorsBySlot ?? { [this.slot]: this.issues };
60
+ if (format === 'problem+json') {
61
+ // Delegate to the single RFC 9457 renderer so ValidationError and
62
+ // HTTPError share one body shape (this adds the standard `detail`
63
+ // member alongside the per-slot `errors` grouping).
64
+ return renderHTTPError(this, isDev, {
65
+ title: 'Validation Error',
66
+ errors: grouped,
67
+ });
68
+ }
69
+ // Plain format fallback.
70
+ const body = { errors: grouped };
71
+ if (isDev) {
72
+ body.dev = true;
73
+ }
74
+ return new Response(JSON.stringify(body), {
75
+ status: this.status,
76
+ headers: { 'content-type': 'application/json' },
77
+ });
78
+ }
79
+ }
80
+ /** Flattens a `ValidationResult` failure into per-slot `ValidationError`s. */
81
+ export function toValidationErrors(result, slot) {
82
+ if (result.success)
83
+ return [];
84
+ return [new ValidationError(slot, result.issues)];
85
+ }
86
+ /**
87
+ * Renders a failed `ValidationResult` into a `Response`.
88
+ *
89
+ * A custom `errorRenderer` fully controls the body. `problem+json` emits the
90
+ * RFC 9457 shape (path/message only); `plain` emits `{ errors: { slot: issues } }`.
91
+ * Production emits only `path`/`message` (and `code`) — no stacks, source
92
+ * paths, or schema internals.
93
+ */
94
+ export function renderValidationError(result, ctx) {
95
+ if (result.success) {
96
+ throw new Error('[burger-api] renderValidationError called with a successful ' +
97
+ 'validation result; it only renders failures.');
98
+ }
99
+ if (ctx.config.errorRenderer) {
100
+ return ctx.config.errorRenderer(result, {
101
+ slot: ctx.slot,
102
+ status: ctx.status,
103
+ });
104
+ }
105
+ const issues = result.issues;
106
+ if (ctx.config.errorFormat === 'problem+json') {
107
+ return new Response(JSON.stringify({
108
+ type: 'about:blank',
109
+ title: 'Validation Error',
110
+ status: ctx.status,
111
+ detail: 'Request validation failed.',
112
+ errors: issues.map((i) => ({
113
+ path: i.path,
114
+ message: i.message,
115
+ })),
116
+ }), {
117
+ status: ctx.status,
118
+ headers: { 'content-type': 'application/problem+json' },
119
+ });
120
+ }
121
+ // Default plain format. Only normalized issue data
122
+ // (path/message/code) is emitted.
123
+ const body = {
124
+ errors: ctx.errorsBySlot
125
+ ? ctx.errorsBySlot
126
+ : ctx.slot
127
+ ? { [ctx.slot]: issues }
128
+ : { message: issues[0]?.message ?? 'Validation failed' },
129
+ };
130
+ if (ctx.isDev) {
131
+ body.dev = true;
132
+ }
133
+ return new Response(JSON.stringify(body), {
134
+ status: ctx.status,
135
+ headers: { 'content-type': 'application/json' },
136
+ });
137
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Validation module for BurgerAPI.
3
+ *
4
+ * Precompiled request validation (identity-cached per schema), opt-in
5
+ * coercion, and RFC 9457 error rendering.
6
+ */
7
+ export { compileRouteSchema, validatorCache, clearValidatorCache } from './compiler.js';
8
+ export { createValidationHook } from './validator.js';
9
+ export { ValidationError, renderValidationError, toValidationErrors, } from './error.js';
10
+ export type { RenderContext } from './error.js';
11
+ export { ValidatorCache } from './cache.js';
12
+ export { registerAdapter, detectAdapter, } from './adapter.js';
13
+ export type { MethodSchema, RouteSchema } from '../types/index.js';
14
+ export type { ValidatorAdapter } from './adapter.js';
15
+ export { buildPlan, apply } from './coerce.js';
16
+ export type { SchemaInput, ValidatorKind, ValidationSlot, ValidationIssue, ValidatorConfig, CompiledValidator, CompiledRouteValidators, CoercionOp, CoercionPlan, StandardSchemaV1, StandardSchemaV1Result, } from './types.js';
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Validation module for BurgerAPI.
3
+ *
4
+ * Precompiled request validation (identity-cached per schema), opt-in
5
+ * coercion, and RFC 9457 error rendering.
6
+ */
7
+ export { compileRouteSchema, validatorCache, clearValidatorCache } from './compiler.js';
8
+ export { createValidationHook } from './validator.js';
9
+ export { ValidationError, renderValidationError, toValidationErrors, } from './error.js';
10
+ export { ValidatorCache } from './cache.js';
11
+ export { registerAdapter, detectAdapter, } from './adapter.js';
12
+ export { buildPlan, apply } from './coerce.js';
@@ -0,0 +1,25 @@
1
+ /**
2
+ * The response validator — validates a handler's return against declared
3
+ * per-status schemas.
4
+ *
5
+ * Selects the schema by status (exact code, then class `2xx`), validates the
6
+ * body, and applies `dev` (observe/log) vs `enforce` (safe 500/422). Runs
7
+ * after the handler in the same request flow; invisible to apps that declare
8
+ * no `response` schema.
9
+ */
10
+ import type { CompiledRouteValidators, ValidatorConfig } from './types.js';
11
+ export interface ResponseValidationOutcome {
12
+ ok: boolean;
13
+ /** Safe error body (no internals) when enforce fails. */
14
+ errorResponse?: Response;
15
+ }
16
+ /**
17
+ * Validates a handler result against the `response` schema for `status`.
18
+ *
19
+ * @param validators - the route's compiled validators.
20
+ * @param status - the HTTP status of the handler response.
21
+ * @param value - the response body value to validate.
22
+ * @param config - the validator config (mode + enforce status).
23
+ * @param isDev - whether to run in dev mode (observe-only).
24
+ */
25
+ export declare function validateResponse(validators: CompiledRouteValidators, method: string, status: number, value: unknown, config: ValidatorConfig, isDev: boolean): ResponseValidationOutcome;
@@ -0,0 +1,85 @@
1
+ /**
2
+ * The response validator — validates a handler's return against declared
3
+ * per-status schemas.
4
+ *
5
+ * Selects the schema by status (exact code, then class `2xx`), validates the
6
+ * body, and applies `dev` (observe/log) vs `enforce` (safe 500/422). Runs
7
+ * after the handler in the same request flow; invisible to apps that declare
8
+ * no `response` schema.
9
+ */
10
+ import { renderValidationError } from './error.js';
11
+ import { HTTPError, renderHTTPError } from '../errors/http-error.js';
12
+ /** Resolves the response validator for a status (exact, then class). */
13
+ function selectResponseValidator(validators, method, status) {
14
+ // The response map only has lowercase-method keys; the caller's runtime
15
+ // method string may be any case, so index via the widened record.
16
+ const responses = validators.response;
17
+ if (!responses)
18
+ return undefined;
19
+ let methodResponses = responses[method];
20
+ // HEAD runs the GET handler, so it follows the GET contract.
21
+ if (!methodResponses && method === 'head')
22
+ methodResponses = responses.get;
23
+ if (!methodResponses)
24
+ return undefined;
25
+ if (methodResponses[String(status)])
26
+ return methodResponses[String(status)];
27
+ const cls = `${Math.floor(status / 100)}xx`;
28
+ if (methodResponses[cls])
29
+ return methodResponses[cls];
30
+ return undefined;
31
+ }
32
+ /**
33
+ * Validates a handler result against the `response` schema for `status`.
34
+ *
35
+ * @param validators - the route's compiled validators.
36
+ * @param status - the HTTP status of the handler response.
37
+ * @param value - the response body value to validate.
38
+ * @param config - the validator config (mode + enforce status).
39
+ * @param isDev - whether to run in dev mode (observe-only).
40
+ */
41
+ export function validateResponse(validators, method, status, value, config, isDev) {
42
+ const validator = selectResponseValidator(validators, method, status);
43
+ if (!validator) {
44
+ return { ok: true };
45
+ }
46
+ const result = validator.validate(value);
47
+ if (result.success) {
48
+ return { ok: true };
49
+ }
50
+ const mode = config.responseValidation ?? 'dev';
51
+ if (mode === 'off') {
52
+ return { ok: true };
53
+ }
54
+ if (mode === 'dev') {
55
+ // Observe only: log and pass the handler response through untouched.
56
+ if (isDev) {
57
+ console.warn(`[burger-api] Response validation mismatch (status ${status}):`, result.issues);
58
+ }
59
+ return { ok: true };
60
+ }
61
+ // enforce: the handler broke its own contract — a server bug. Always
62
+ // log it; answer with RFC 9457 Problem Details: issue details in dev,
63
+ // a generic 500 in production (never leak schema internals).
64
+ const enforceStatus = status === 422 ? 422 : 500;
65
+ console.error(`[burger-api] Response validation failed (status ${status}):`, result.issues);
66
+ if (config.errorRenderer) {
67
+ return {
68
+ ok: false,
69
+ errorResponse: renderValidationError(result, {
70
+ status: enforceStatus,
71
+ isDev,
72
+ slot: 'response',
73
+ config,
74
+ }),
75
+ };
76
+ }
77
+ // No stack: the synthetic error's trace is noise. Dev adds the issues.
78
+ const errorResponse = renderHTTPError(new HTTPError(enforceStatus, 'Response validation failed'), false, isDev
79
+ ? {
80
+ detail: 'Response validation failed',
81
+ errors: { response: result.issues },
82
+ }
83
+ : undefined);
84
+ return { ok: false, errorResponse };
85
+ }
@@ -0,0 +1,148 @@
1
+ /**
2
+ * Central type definitions for the validation subsystem.
3
+ *
4
+ * Types only — no runtime logic, no adapter implementations, no I/O.
5
+ */
6
+ import type { z } from 'zod';
7
+ import type { LowercaseHTTPMethod } from '../utils/routing.js';
8
+ /**
9
+ * Minimal structural type for a Standard Schema V1 validator — the common
10
+ * shape shared by libraries like Valibot and ArkType so they work with
11
+ * BurgerAPI. Only the stable `~standard` contract is used. `vendor` names the
12
+ * producing library (e.g. "valibot", "arktype", "zod").
13
+ */
14
+ export interface StandardSchemaV1 {
15
+ readonly '~standard': {
16
+ readonly version: 1;
17
+ readonly vendor: string;
18
+ readonly validate: (value: unknown) => StandardSchemaV1Result | Promise<StandardSchemaV1Result>;
19
+ /** True when the schema transforms (coerces) its input during validate. */
20
+ readonly coercible?: boolean;
21
+ readonly types?: {
22
+ readonly input?: unknown;
23
+ readonly output?: unknown;
24
+ };
25
+ };
26
+ }
27
+ export type StandardSchemaV1Result = StandardSchemaV1SuccessResult | StandardSchemaV1FailureResult;
28
+ export interface StandardSchemaV1SuccessResult {
29
+ readonly value: unknown;
30
+ readonly issues?: undefined;
31
+ }
32
+ export interface StandardSchemaV1FailureResult {
33
+ readonly issues: ReadonlyArray<StandardSchemaV1Issue>;
34
+ }
35
+ export interface StandardSchemaV1Issue {
36
+ readonly message: string;
37
+ readonly path?: ReadonlyArray<PropertyKey | {
38
+ readonly key: PropertyKey;
39
+ }>;
40
+ }
41
+ /**
42
+ * Any value accepted in a schema slot. Zod is the default provider; Standard
43
+ * Schema libraries are also accepted.
44
+ */
45
+ export type SchemaInput = z.ZodTypeAny | StandardSchemaV1;
46
+ /** The five request slots that can carry a schema. */
47
+ export type ValidationSlot = 'params' | 'query' | 'headers' | 'cookies' | 'body';
48
+ /** The kinds of validator providers known to the adapter layer. */
49
+ export type ValidatorKind = 'zod' | 'standard';
50
+ /**
51
+ * A common result shape shared by every adapter, so Zod and other libraries
52
+ * report success or failure the same way.
53
+ */
54
+ export type ValidationResult = {
55
+ success: true;
56
+ data: unknown;
57
+ } | {
58
+ success: false;
59
+ issues: ValidationIssue[];
60
+ };
61
+ /**
62
+ * A single field-level failure.
63
+ */
64
+ export interface ValidationIssue {
65
+ path: (string | number)[];
66
+ message: string;
67
+ code?: string;
68
+ }
69
+ /**
70
+ * The runtime unit produced when a schema is prepared: one reusable
71
+ * `validate` call plus metadata. Prepared once per unique identity before
72
+ * `serve()`.
73
+ */
74
+ export interface CompiledValidator {
75
+ kind: ValidatorKind;
76
+ slot: ValidationSlot;
77
+ identity: string;
78
+ validate: (value: unknown) => ValidationResult;
79
+ /**
80
+ * True when the schema transforms (coerces) its own input during
81
+ * `validate` (e.g. Zod `z.coerce.*`, Valibot `v.coerce`, or a
82
+ * `~standard.coercible` schema). Framework coercion is skipped for these —
83
+ * pre-coercing would double-apply type conversion.
84
+ */
85
+ coercible: boolean;
86
+ }
87
+ /** Coercion operations supported by the coercer. */
88
+ export type CoercionOp = 'number' | 'boolean' | 'date' | 'none';
89
+ /**
90
+ * A per-slot, per-field plan built when the route is set up. Applied at
91
+ * runtime with no extra checks on each request.
92
+ */
93
+ export interface CoercionPlan {
94
+ slot: 'query' | 'params' | 'headers' | 'cookies';
95
+ fields: Record<string, CoercionOp>;
96
+ /**
97
+ * Array fields (`z.array(...)`) → element op. A single value is wrapped
98
+ * into a one-element array; each element is coerced with the op.
99
+ */
100
+ arrays?: Record<string, CoercionOp>;
101
+ }
102
+ /**
103
+ * Per-status-code map of response validators.
104
+ */
105
+ export type ResponseSchema = Record<string, SchemaInput>;
106
+ /**
107
+ * Configuration surfaced from `ServerOptions` into the compilation step.
108
+ * Defaults: status 422, errorFormat 'problem+json' (RFC 9457),
109
+ * responseValidation 'dev'.
110
+ */
111
+ export interface ValidatorConfig {
112
+ /** Opt-in string→type coercion. Default false. */
113
+ coerce?: boolean;
114
+ /** Response validation mode. Default 'dev'. */
115
+ responseValidation?: 'off' | 'dev' | 'enforce';
116
+ /** Error body shape. Default 'problem+json' (RFC 9457). */
117
+ errorFormat?: 'plain' | 'problem+json';
118
+ /** Default HTTP status for validation errors. Default 422. */
119
+ status?: number;
120
+ /** Custom renderer that fully controls the error body. */
121
+ errorRenderer?: (result: ValidationResult, ctx: {
122
+ slot?: ValidationSlot | 'response';
123
+ status: number;
124
+ }) => Response;
125
+ }
126
+ /**
127
+ * The per-route bundle of prepared slot validators + conversion plans +
128
+ * response validators, attached to the route when it is prepared.
129
+ * Method keys are lowercase (the form the compiler emits and the validator
130
+ * looks up at request time).
131
+ */
132
+ export interface CompiledRouteValidators {
133
+ methods: Partial<Record<LowercaseHTTPMethod, {
134
+ params?: CompiledValidator;
135
+ query?: CompiledValidator;
136
+ headers?: CompiledValidator;
137
+ cookies?: CompiledValidator;
138
+ body?: CompiledValidator;
139
+ coercion?: {
140
+ query?: CoercionPlan;
141
+ params?: CoercionPlan;
142
+ headers?: CoercionPlan;
143
+ cookies?: CoercionPlan;
144
+ };
145
+ }>>;
146
+ /** Per-method, per-status-code map of response validators. */
147
+ response?: Partial<Record<LowercaseHTTPMethod, Record<string, CompiledValidator>>>;
148
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Central type definitions for the validation subsystem.
3
+ *
4
+ * Types only — no runtime logic, no adapter implementations, no I/O.
5
+ */
6
+ export {};
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The validation coordinator — builds the framework's validation hook from
3
+ * precompiled route validators.
4
+ *
5
+ * Runs `cv.validate(value)` once per slot — no walk over the raw schema, no
6
+ * adapter selection, no preparing at request time. Skips work when
7
+ * `ctx.validated` is already set and validates
8
+ * params/query/headers/cookies/body with the same checks.
9
+ *
10
+ * Throws `ValidationError` (422, RFC 9457 problem details) on failure, or
11
+ * `HTTPError(415)` when a body schema is declared but the request body is not
12
+ * JSON (never skips validation).
13
+ */
14
+ import type { LowercaseHTTPMethod } from '../utils/routing.js';
15
+ import type { ForwardHook } from '../lifecycle/types.js';
16
+ import type { CompiledRouteValidators, ValidatorConfig } from './types.js';
17
+ /** Parses a `Cookie` header value into a flat record (cookie slot). */
18
+ export declare function parseCookies(header: string | null | undefined): Record<string, string>;
19
+ /**
20
+ * True when a raw `Content-Type` header value is JSON (`application/json` or
21
+ * `application/…+json`). Shared by request-body and response validation.
22
+ */
23
+ export declare function isJsonContentType(raw: string): boolean;
24
+ /**
25
+ * Builds the validation hook from precompiled route validators.
26
+ *
27
+ * On failure, throws a `ValidationError` (status 422, or
28
+ * `ValidatorConfig.status` when set) into the `onError` pipeline. The
29
+ * framework's default onError handler renders the RFC 9457 response.
30
+ *
31
+ * @param validators - the compiled validators for this route (may be empty).
32
+ * @param config - validation configuration (custom status, error format).
33
+ * @param isDev - reserved for future use (dev diagnostics).
34
+ * @param method - when given, the hook is specialized for that lowercase
35
+ * method at compile time (no per-request method lookup).
36
+ * @param skipValidatedBag - when true, a method without validators does not
37
+ * allocate the empty `{}` bag (only legal with `method` given).
38
+ */
39
+ export declare function createValidationHook(validators: CompiledRouteValidators, config?: ValidatorConfig, isDev?: boolean, method?: LowercaseHTTPMethod, skipValidatedBag?: boolean): ForwardHook;