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,128 @@
1
+ /**
2
+ * The Zod adapter — the default schema provider for BurgerAPI.
3
+ *
4
+ * Computes a stable identity, compiles a Zod schema into a reusable
5
+ * `CompiledValidator`, and normalizes Zod `issues` into `ValidationIssue[]`.
6
+ * Delegates validation to `safeParse` and leaves coercion to the coercer.
7
+ */
8
+ import { z } from 'zod';
9
+ import { isZodSchema } from '../adapter.js';
10
+ /** Maps a Zod issue path to the normalized `(string | number)[]`. */
11
+ function normalizePath(path) {
12
+ return path.map((p) => (typeof p === 'bigint' ? Number(p) : p));
13
+ }
14
+ /** Bounded deep scan for function values inside a check descriptor. */
15
+ function hasFunctionValue(value, depth = 0) {
16
+ if (typeof value === 'function') {
17
+ return true;
18
+ }
19
+ if (depth >= 4 || typeof value !== 'object' || value === null) {
20
+ return false;
21
+ }
22
+ for (const v of Object.values(value)) {
23
+ if (hasFunctionValue(v, depth + 1)) {
24
+ return true;
25
+ }
26
+ }
27
+ return false;
28
+ }
29
+ /** Normalizes Zod's `ZodError.issues` into `ValidationIssue[]`. */
30
+ function normalizeIssues(error) {
31
+ return error.issues.map((issue) => ({
32
+ path: normalizePath(issue.path),
33
+ message: issue.message,
34
+ code: issue.code,
35
+ }));
36
+ }
37
+ /** Monotonic ids for schemas with no computable JSON Schema fingerprint. */
38
+ const uniqueSchemaIds = new WeakMap();
39
+ let nextUniqueSchemaId = 0;
40
+ /**
41
+ * Root-level wrappers whose validation semantics the JSON Schema fingerprint
42
+ * cannot capture. `z.string().optional()` and `z.string()` serialize
43
+ * identically, so sharing a cached validator would validate the wrong
44
+ * schema (e.g. `undefined` rejected for an optional body).
45
+ */
46
+ const LOSSY_ROOT_TYPES = new Set([
47
+ 'optional',
48
+ 'prefault',
49
+ 'nonoptional',
50
+ 'default',
51
+ 'catch',
52
+ 'pipe',
53
+ 'lazy',
54
+ ]);
55
+ export const ZodAdapter = {
56
+ identity(schema) {
57
+ // Zod v4's `toString()` is not stable for object schemas, so use a
58
+ // deterministic JSON Schema fingerprint as the structural identity.
59
+ // Prefix it to namespace under the Zod provider.
60
+ const zodSchema = schema;
61
+ let fingerprint;
62
+ try {
63
+ fingerprint = JSON.stringify(z.toJSONSchema(zodSchema));
64
+ }
65
+ catch {
66
+ // No computable fingerprint (transforms, dates, custom, bigint):
67
+ // key by object identity so distinct schemas can never share.
68
+ let id = uniqueSchemaIds.get(zodSchema);
69
+ if (id === undefined) {
70
+ id = ++nextUniqueSchemaId;
71
+ uniqueSchemaIds.set(zodSchema, id);
72
+ }
73
+ return 'zod:object:' + id;
74
+ }
75
+ return 'zod:' + fingerprint;
76
+ },
77
+ cacheable(schema) {
78
+ const zodSchema = schema;
79
+ const def = zodSchema._zod?.def;
80
+ // Self-coercing schemas (z.coerce.*) validate differently than their
81
+ // plain counterparts even though their JSON Schema fingerprints are
82
+ // identical — never let one route's coercion leak into another's.
83
+ if (def?.coerce === true) {
84
+ return false;
85
+ }
86
+ // Root wrappers invisible to the fingerprint (optional/default/pipe/
87
+ // …) change what counts as valid input — compile fresh.
88
+ if (def?.type !== undefined && LOSSY_ROOT_TYPES.has(def.type)) {
89
+ return false;
90
+ }
91
+ // Function-valued checks (refinements) are invisible to the JSON
92
+ // Schema fingerprint, so structurally identical refinements would
93
+ // collide in the cache. Compile them fresh instead.
94
+ const checks = def?.checks;
95
+ if (Array.isArray(checks) && checks.some((c) => hasFunctionValue(c))) {
96
+ return false;
97
+ }
98
+ return true;
99
+ },
100
+ supports(schema) {
101
+ return isZodSchema(schema);
102
+ },
103
+ compile(schema, slot) {
104
+ const zodSchema = schema;
105
+ const identity = this.identity(schema);
106
+ // Zod 4 marks self-coercing schemas (`z.coerce.*`) with
107
+ // `_zod.def.coerce === true`. Such schemas transform their input
108
+ // during validate, so framework coercion must not run on them.
109
+ const coercible = zodSchema
110
+ ?._zod?.def?.coerce === true;
111
+ const validate = (value) => {
112
+ const result = zodSchema.safeParse(value);
113
+ if (result.success) {
114
+ // Zod's success result already has the `{ success, data }` shape —
115
+ // return it directly instead of re-wrapping.
116
+ return result;
117
+ }
118
+ return { success: false, issues: normalizeIssues(result.error) };
119
+ };
120
+ return {
121
+ kind: 'zod',
122
+ slot,
123
+ identity,
124
+ validate,
125
+ coercible,
126
+ };
127
+ },
128
+ };
@@ -0,0 +1,26 @@
1
+ /**
2
+ * The validator cache — process-lifetime memoization of compiled validators
3
+ * keyed by schema identity.
4
+ *
5
+ * Lookup / insert / clear on dev hot reload (the next compile pass repopulates
6
+ * it wholesale). Must NOT retain build-time serialization artifacts at runtime
7
+ * and must NOT mutate during a production request. The storage mechanism
8
+ * (`Map`) is an implementation detail.
9
+ */
10
+ import type { CompiledValidator } from './types.js';
11
+ export declare class ValidatorCache {
12
+ private store;
13
+ /** Returns the cached validator for `identity`, or undefined on miss. */
14
+ get(identity: string): CompiledValidator | undefined;
15
+ /** Inserts a compiled validator keyed by its identity. */
16
+ set(identity: string, validator: CompiledValidator): void;
17
+ /** True when `identity` is already cached. */
18
+ has(identity: string): boolean;
19
+ /**
20
+ * Clears all cached validators. Called on dev hot reload; the next
21
+ * `compile()` pass repopulates it wholesale.
22
+ */
23
+ clear(): void;
24
+ /** Number of currently cached (unique) validators. */
25
+ get size(): number;
26
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * The validator cache — process-lifetime memoization of compiled validators
3
+ * keyed by schema identity.
4
+ *
5
+ * Lookup / insert / clear on dev hot reload (the next compile pass repopulates
6
+ * it wholesale). Must NOT retain build-time serialization artifacts at runtime
7
+ * and must NOT mutate during a production request. The storage mechanism
8
+ * (`Map`) is an implementation detail.
9
+ */
10
+ export class ValidatorCache {
11
+ store = new Map();
12
+ /** Returns the cached validator for `identity`, or undefined on miss. */
13
+ get(identity) {
14
+ return this.store.get(identity);
15
+ }
16
+ /** Inserts a compiled validator keyed by its identity. */
17
+ set(identity, validator) {
18
+ this.store.set(identity, validator);
19
+ }
20
+ /** True when `identity` is already cached. */
21
+ has(identity) {
22
+ return this.store.has(identity);
23
+ }
24
+ /**
25
+ * Clears all cached validators. Called on dev hot reload; the next
26
+ * `compile()` pass repopulates it wholesale.
27
+ */
28
+ clear() {
29
+ this.store.clear();
30
+ }
31
+ /** Number of currently cached (unique) validators. */
32
+ get size() {
33
+ return this.store.size;
34
+ }
35
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * The coercer — builds and applies precomputed value-conversion plans.
3
+ * "Coercion" means automatic type conversion: `"42"` → the number `42`,
4
+ * `"true"` → the boolean `true`.
5
+ *
6
+ * `buildPlan` records only the fields that need conversion
7
+ * (number/boolean/date) and returns undefined when there is nothing to
8
+ * convert. `apply` transforms a raw string record in a single linear pass;
9
+ * fields not in the plan are copied unchanged.
10
+ *
11
+ * Conversion is opt-in (default OFF, planned at startup and applied only when
12
+ * present). It never converts the body and never leaks `NaN` — a bad
13
+ * conversion stays a string so the validator reports the real input.
14
+ */
15
+ import type { CoercionPlan, SchemaInput } from './types.js';
16
+ /**
17
+ * Builds a coercion plan for a schema slot. Returns undefined when the slot
18
+ * has no coercible fields (so the orchestrator can skip coercion entirely).
19
+ *
20
+ * Currently inspects Zod object shapes (the default provider).
21
+ * Other adapters can be extended by detecting their intent here.
22
+ */
23
+ export declare function buildPlan(slotSchema: SchemaInput, slot: 'query' | 'params' | 'headers' | 'cookies'): CoercionPlan | undefined;
24
+ /**
25
+ * Applies a coercion plan to a raw record. Fields not in the plan are copied
26
+ * as-is. The output is a new record; the input is not mutated.
27
+ */
28
+ export declare function apply(plan: CoercionPlan, raw: Record<string, string | string[]>): Record<string, unknown>;
@@ -0,0 +1,176 @@
1
+ /**
2
+ * The coercer — builds and applies precomputed value-conversion plans.
3
+ * "Coercion" means automatic type conversion: `"42"` → the number `42`,
4
+ * `"true"` → the boolean `true`.
5
+ *
6
+ * `buildPlan` records only the fields that need conversion
7
+ * (number/boolean/date) and returns undefined when there is nothing to
8
+ * convert. `apply` transforms a raw string record in a single linear pass;
9
+ * fields not in the plan are copied unchanged.
10
+ *
11
+ * Conversion is opt-in (default OFF, planned at startup and applied only when
12
+ * present). It never converts the body and never leaks `NaN` — a bad
13
+ * conversion stays a string so the validator reports the real input.
14
+ */
15
+ import { isZodSchema } from './adapter.js';
16
+ /** Unwraps optional/nullable/default wrappers to reach the inner type. */
17
+ function unwrap(def) {
18
+ let current = def;
19
+ // Up to a few levels of wrapping (optional/nullable/default).
20
+ for (let i = 0; i < 4 && current; i++) {
21
+ const inner = current?._zod?.def?.innerType;
22
+ if (inner === undefined)
23
+ break;
24
+ current = inner;
25
+ }
26
+ return current;
27
+ }
28
+ /** Returns the coercion op for a Zod field def, or 'none'. */
29
+ function opForZodField(def) {
30
+ // Self-coercing fields (`z.coerce.*`, marked `_zod.def.coerce: true`)
31
+ // transform their input during validate — never pre-coerce them.
32
+ if (def?._zod?.def?.coerce === true)
33
+ return 'none';
34
+ const name = def?.constructor?.name;
35
+ if (name === 'ZodNumber')
36
+ return 'number';
37
+ if (name === 'ZodBoolean')
38
+ return 'boolean';
39
+ if (name === 'ZodDate')
40
+ return 'date';
41
+ // Try unwrapping optional/nullable/default.
42
+ const inner = unwrap(def);
43
+ if (inner && inner !== def)
44
+ return opForZodField(inner);
45
+ return 'none';
46
+ }
47
+ function coerceValue(op, raw) {
48
+ switch (op) {
49
+ case 'number': {
50
+ // Strict decimal form only: no empty/whitespace, hex, exponent,
51
+ // Infinity or NaN. Anything else stays a string.
52
+ if (!/^\s*[+-]?\d+(\.\d+)?\s*$/.test(raw)) {
53
+ return raw;
54
+ }
55
+ const n = Number(raw);
56
+ // Never leak NaN: keep the raw string so the validator reports
57
+ // the actual bad input.
58
+ return Number.isNaN(n) ? raw : n;
59
+ }
60
+ case 'boolean': {
61
+ if (raw === 'true' || raw === '1')
62
+ return true;
63
+ if (raw === 'false' || raw === '0')
64
+ return false;
65
+ // Unknown boolean string -> leave as-is; the validator will reject.
66
+ return raw;
67
+ }
68
+ case 'date': {
69
+ const d = tryParseDate(raw);
70
+ return d ?? raw;
71
+ }
72
+ default:
73
+ return raw;
74
+ }
75
+ }
76
+ /**
77
+ * Strict ISO-8601 date parse.
78
+ *
79
+ * Rejects numeric strings ("42"), non-ISO formats, and impossible calendar
80
+ * dates ("2026-02-30" rolls over in `new Date()` unless checked). Date-only
81
+ * values are validated against the calendar directly; full timestamps must
82
+ * carry a time and a zone.
83
+ */
84
+ function tryParseDate(raw) {
85
+ const dateOnly = /^(\d{4})-(\d{2})-(\d{2})$/.exec(raw);
86
+ if (dateOnly) {
87
+ const [, y, mo, da] = dateOnly;
88
+ const day = new Date(Date.UTC(Number(y), Number(mo) - 1, Number(da)));
89
+ if (day.toISOString().slice(0, 10) !== `${y}-${mo}-${da}`) {
90
+ return null;
91
+ }
92
+ return day;
93
+ }
94
+ if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,9})?(Z|[+-]\d{2}:\d{2})$/.test(raw)) {
95
+ return null;
96
+ }
97
+ // Full timestamp: verify the calendar day too (the parse alone would
98
+ // roll "2026-02-30T10:00:00Z" forward).
99
+ if (tryParseDate(raw.slice(0, 10)) === null) {
100
+ return null;
101
+ }
102
+ const d = new Date(raw);
103
+ return isNaN(d.getTime()) ? null : d;
104
+ }
105
+ /**
106
+ * Builds a coercion plan for a schema slot. Returns undefined when the slot
107
+ * has no coercible fields (so the orchestrator can skip coercion entirely).
108
+ *
109
+ * Currently inspects Zod object shapes (the default provider).
110
+ * Other adapters can be extended by detecting their intent here.
111
+ */
112
+ export function buildPlan(slotSchema, slot) {
113
+ if (!isZodSchema(slotSchema))
114
+ return undefined;
115
+ const shape = slotSchema.shape;
116
+ if (!shape || typeof shape !== 'object')
117
+ return undefined;
118
+ const fieldMap = shape;
119
+ const fields = {};
120
+ const arrays = {};
121
+ for (const key of Object.keys(fieldMap)) {
122
+ // `z.array(x)`: repeated keys (`?tag=a&tag=b`) already arrive as an
123
+ // array; a single occurrence is wrapped. Elements use x's op.
124
+ const inner = unwrap(fieldMap[key]);
125
+ if (inner?.constructor?.name === 'ZodArray') {
126
+ arrays[key] = opForZodField(inner._zod?.def?.element);
127
+ continue;
128
+ }
129
+ const op = opForZodField(fieldMap[key]);
130
+ if (op !== 'none')
131
+ fields[key] = op;
132
+ }
133
+ const hasArrays = Object.keys(arrays).length > 0;
134
+ if (Object.keys(fields).length === 0 && !hasArrays)
135
+ return undefined;
136
+ return hasArrays ? { slot, fields, arrays } : { slot, fields };
137
+ }
138
+ /**
139
+ * Applies a coercion plan to a raw record. Fields not in the plan are copied
140
+ * as-is. The output is a new record; the input is not mutated.
141
+ */
142
+ export function apply(plan, raw) {
143
+ // Null prototype: input keys are attacker-controlled.
144
+ const out = Object.create(null);
145
+ for (const key of Object.keys(raw)) {
146
+ const op = plan.fields[key];
147
+ const value = raw[key];
148
+ const elementOp = plan.arrays?.[key];
149
+ if (elementOp !== undefined) {
150
+ const list = Array.isArray(value) ? value : [value];
151
+ if (elementOp === 'none') {
152
+ out[key] = list;
153
+ continue;
154
+ }
155
+ // Plain loop: element coercion runs per request, no `map` closure.
156
+ const coerced = new Array(list.length);
157
+ for (let i = 0; i < list.length; i++) {
158
+ coerced[i] = coerceValue(elementOp, list[i]);
159
+ }
160
+ out[key] = coerced;
161
+ continue;
162
+ }
163
+ if (!op) {
164
+ out[key] = value;
165
+ continue;
166
+ }
167
+ // Arrays (duplicate keys) are not coerced field-by-field; pass through
168
+ // unchanged so the validator sees the same shape.
169
+ if (Array.isArray(value)) {
170
+ out[key] = value;
171
+ continue;
172
+ }
173
+ out[key] = coerceValue(op, value);
174
+ }
175
+ return out;
176
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * The schema preparation component — compiles a `RouteSchema` into
3
+ * `CompiledRouteValidators`.
4
+ *
5
+ * Walks each slot, detects its adapter, computes identity, and consults the
6
+ * cache; builds coercion plans and response validators when present. Runs
7
+ * ONCE per route when it is set up (before `serve()`), never per request.
8
+ * Identical schemas (by reference) share one cached validator.
9
+ */
10
+ import type { RouteSchema } from '../types/index.js';
11
+ import { ValidatorCache } from './cache.js';
12
+ import type { CompiledRouteValidators, ValidatorConfig } from './types.js';
13
+ /** The shared, process-lifetime validator cache. */
14
+ export declare const validatorCache: ValidatorCache;
15
+ /**
16
+ * Compiles a route's `schema` into `CompiledRouteValidators`.
17
+ *
18
+ * @param schema - the raw route schema.
19
+ * @param config - the validator configuration (coercion / response flags).
20
+ * @param cache - the validator cache (shared instance by default).
21
+ */
22
+ export declare function compileRouteSchema(schema: RouteSchema, config?: ValidatorConfig, cache?: ValidatorCache, route?: string): CompiledRouteValidators;
23
+ /**
24
+ * Clears the shared cache (dev hot reload). The next compile pass repopulates
25
+ * it wholesale.
26
+ */
27
+ export declare function clearValidatorCache(): void;
@@ -0,0 +1,191 @@
1
+ /**
2
+ * The schema preparation component — compiles a `RouteSchema` into
3
+ * `CompiledRouteValidators`.
4
+ *
5
+ * Walks each slot, detects its adapter, computes identity, and consults the
6
+ * cache; builds coercion plans and response validators when present. Runs
7
+ * ONCE per route when it is set up (before `serve()`), never per request.
8
+ * Identical schemas (by reference) share one cached validator.
9
+ */
10
+ import { ValidatorCache } from './cache.js';
11
+ import { detectAdapter, __setZodAdapter, __setStandardAdapter, } from './adapter.js';
12
+ // Explicit adapter registration — value imports (not side-effect imports) so
13
+ // registration survives tree-shaking under `sideEffects: false`.
14
+ import { ZodAdapter } from './adapters/zod.js';
15
+ import { StandardAdapter } from './adapters/standard.js';
16
+ __setZodAdapter(ZodAdapter);
17
+ __setStandardAdapter(StandardAdapter);
18
+ import { buildPlan as buildCoercionPlan } from './coerce.js';
19
+ /** The shared, process-lifetime validator cache. */
20
+ export const validatorCache = new ValidatorCache();
21
+ /** Request slots that can carry a schema in `RouteSchema`. */
22
+ const REQUEST_SLOTS = [
23
+ 'params',
24
+ 'query',
25
+ 'headers',
26
+ 'cookies',
27
+ 'body',
28
+ ];
29
+ /**
30
+ * Compiles a route's `schema` into `CompiledRouteValidators`.
31
+ *
32
+ * @param schema - the raw route schema.
33
+ * @param config - the validator configuration (coercion / response flags).
34
+ * @param cache - the validator cache (shared instance by default).
35
+ */
36
+ export function compileRouteSchema(schema, config = {}, cache = validatorCache, route) {
37
+ const methods = {};
38
+ // `export const coerce = true` in schema.ts enables coercion for every
39
+ // method in the file (a per-method `coerce` still works the same).
40
+ const topLevelCoerce = schema.coerce === true;
41
+ for (const rawMethod of Object.keys(schema)) {
42
+ const method = rawMethod.toLowerCase();
43
+ // The top-level `coerce` flag is not a method.
44
+ if (method === 'coerce')
45
+ continue;
46
+ // Schema keys are typed as the method union; a module export is still
47
+ // a runtime string, so index via the widened record.
48
+ const m = schema[rawMethod] ?? {};
49
+ const compiledMethod = {};
50
+ // Coercion is opt-in: app-level config.coerce, top-level schema
51
+ // `coerce`, OR per-route schema[method].coerce override.
52
+ const coerceEnabled = config.coerce === true || topLevelCoerce || m.coerce === true;
53
+ for (const slot of REQUEST_SLOTS) {
54
+ const raw = m[slot];
55
+ if (raw === undefined)
56
+ continue;
57
+ if (slot === 'headers') {
58
+ assertLowercaseHeaderKeys(raw, rawMethod.toUpperCase(), route);
59
+ }
60
+ compiledMethod[slot] = compileSlot(raw, slot, cache);
61
+ }
62
+ // Build coercion plans only when coercion is enabled.
63
+ if (coerceEnabled) {
64
+ const coercion = {};
65
+ for (const slot of [
66
+ 'query',
67
+ 'params',
68
+ 'headers',
69
+ 'cookies',
70
+ ]) {
71
+ const raw = m[slot];
72
+ if (raw === undefined)
73
+ continue;
74
+ // Self-coercing schemas (e.g. z.coerce.* / ~standard.coercible)
75
+ // transform their own input — framework coercion must not run.
76
+ if (compiledMethod[slot]?.coercible)
77
+ continue;
78
+ const plan = buildCoercionPlan(raw, slot);
79
+ if (plan)
80
+ coercion[slot] = plan;
81
+ }
82
+ if (Object.keys(coercion).length > 0) {
83
+ compiledMethod.coercion = coercion;
84
+ }
85
+ }
86
+ // Method keys are lowercased at runtime before storage; the compiled
87
+ // map is union-keyed, so write via the widened record.
88
+ methods[method] =
89
+ compiledMethod;
90
+ }
91
+ // Compile response schemas (per-status) when present.
92
+ const response = compileResponseSchemas(schema, cache, route);
93
+ const result = { methods };
94
+ if (response)
95
+ result.response = response;
96
+ return result;
97
+ }
98
+ /**
99
+ * Keys a schema exposes structurally (a Zod object's `.shape`, or a Standard
100
+ * Schema value carrying a `shape` record). Opaque schemas (`records`, maps)
101
+ * expose nothing, so they are skipped.
102
+ */
103
+ function exposedShapeKeys(schema) {
104
+ const shape = schema.shape;
105
+ if (shape === null || typeof shape !== 'object')
106
+ return undefined;
107
+ return Object.keys(shape);
108
+ }
109
+ /**
110
+ * Header names are lowercased at runtime (`x-api-key`), so a schema key with
111
+ * uppercase letters can never match. Fails startup naming the key and the
112
+ * lowercase form. Only enforced when the schema exposes its keys structurally.
113
+ */
114
+ function assertLowercaseHeaderKeys(schema, method, route) {
115
+ const keys = exposedShapeKeys(schema);
116
+ if (!keys)
117
+ return;
118
+ for (const key of keys) {
119
+ const lower = key.toLowerCase();
120
+ if (key !== lower) {
121
+ throw new Error(`Header schema key "${key}" for ` +
122
+ `${method}${route ? ` ${route}` : ''} can never match: ` +
123
+ `header names are lowercased at runtime. Use "${lower}" instead.`);
124
+ }
125
+ }
126
+ }
127
+ /** An exact status code (`200`) — the selected form. */
128
+ const STATUS_CODE_KEY = /^[1-5]\d\d$/;
129
+ /** A status class (`2xx`) — the fallback form, lowercase only. */
130
+ const STATUS_CLASS_KEY = /^[1-5]xx$/;
131
+ /**
132
+ * Compiles per-status `response` schemas into a map of `CompiledValidator`s.
133
+ * Returns undefined when no `response` schemas are declared.
134
+ *
135
+ * A key that is neither a status code nor a lowercase status class can never
136
+ * be selected at request time, so it fails startup naming the route, method
137
+ * and key instead of silently never running.
138
+ */
139
+ function compileResponseSchemas(schema, cache, route) {
140
+ const response = {};
141
+ let any = false;
142
+ for (const rawMethod of Object.keys(schema)) {
143
+ const method = rawMethod.toLowerCase();
144
+ if (method === 'coerce')
145
+ continue;
146
+ const m = schema[rawMethod] ?? {};
147
+ const responseSchemas = m.response;
148
+ if (!responseSchemas)
149
+ continue;
150
+ const byStatus = {};
151
+ for (const statusKey of Object.keys(responseSchemas)) {
152
+ if (!STATUS_CODE_KEY.test(statusKey) &&
153
+ !STATUS_CLASS_KEY.test(statusKey)) {
154
+ throw new Error(`Invalid response schema key "${statusKey}" for ` +
155
+ `${rawMethod.toUpperCase()}${route ? ` ${route}` : ''}: ` +
156
+ 'use a status code ("200") or a status class ("2xx").');
157
+ }
158
+ byStatus[statusKey] = compileSlot(responseSchemas[statusKey], 'body', cache);
159
+ any = true;
160
+ }
161
+ response[method] = byStatus;
162
+ }
163
+ return any ? response : undefined;
164
+ }
165
+ /**
166
+ * Compiles a single slot schema into a `CompiledValidator`, consulting the
167
+ * cache by identity first.
168
+ */
169
+ function compileSlot(slotSchema, slot, cache) {
170
+ const adapter = detectAdapter(slotSchema);
171
+ if (adapter.cacheable?.(slotSchema) === false) {
172
+ // Semantics that the structural identity cannot capture (refinements,
173
+ // self-coercion) — compile fresh so no other route can reuse this
174
+ // validator's behavior.
175
+ return adapter.compile(slotSchema, slot);
176
+ }
177
+ const identity = adapter.identity(slotSchema);
178
+ const cached = cache.get(identity);
179
+ if (cached)
180
+ return cached;
181
+ const compiled = adapter.compile(slotSchema, slot);
182
+ cache.set(identity, compiled);
183
+ return compiled;
184
+ }
185
+ /**
186
+ * Clears the shared cache (dev hot reload). The next compile pass repopulates
187
+ * it wholesale.
188
+ */
189
+ export function clearValidatorCache() {
190
+ validatorCache.clear();
191
+ }
@@ -0,0 +1,69 @@
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 } from '../errors/http-error.js';
12
+ import type { ValidationIssue, ValidationResult, ValidatorConfig, ValidationSlot } from './types.js';
13
+ /**
14
+ * A structured validation error thrown when request validation fails.
15
+ *
16
+ * Extends `HTTPError` with status 422. Carries the failing slot and
17
+ * normalized issues. Enters the `onError` pipeline; if no user hook
18
+ * handles it, the framework renders an RFC 9457 response.
19
+ */
20
+ export declare class ValidationError extends HTTPError {
21
+ readonly name = "ValidationError";
22
+ readonly status: number;
23
+ /** The primary request slot that failed validation. */
24
+ readonly slot: ValidationSlot | 'response';
25
+ /** Normalized field-level issues (all slots combined). */
26
+ readonly issues: ValidationIssue[];
27
+ /** Per-slot grouping of issues, when available. */
28
+ readonly errorsBySlot?: Record<string, ValidationIssue[]>;
29
+ constructor(slot: ValidationSlot | 'response', issues: ValidationIssue[], options?: ErrorOptions & {
30
+ errorsBySlot?: Record<string, ValidationIssue[]>;
31
+ /** Custom status code; defaults to 422 (ValidatorConfig.status). */
32
+ status?: number;
33
+ });
34
+ /**
35
+ * Creates a `ValidationError` from a failed `ValidationResult`.
36
+ */
37
+ static from(slot: ValidationSlot | 'response', result: ValidationResult): ValidationError | null;
38
+ /**
39
+ * Renders this error into an RFC 9457 Problem Details response.
40
+ *
41
+ * Dev mode includes full issue details; production strips internal path
42
+ * information. A custom `errorRenderer` takes precedence when provided.
43
+ */
44
+ toResponse(isDev: boolean, config?: ValidatorConfig): Response;
45
+ }
46
+ /** Flattens a `ValidationResult` failure into per-slot `ValidationError`s. */
47
+ export declare function toValidationErrors(result: ValidationResult, slot: string): ValidationError[];
48
+ export interface RenderContext {
49
+ status: number;
50
+ /** Whether to include dev diagnostics (stack/path detail). */
51
+ isDev: boolean;
52
+ /** The slot that produced the error (request) or 'response' (enforce). */
53
+ slot?: ValidationSlot | 'response';
54
+ /** Per-slot issues for request validation (all failing slots). When
55
+ * present, the plain renderer emits one key per slot instead of
56
+ * collapsing every issue under a single slot name. */
57
+ errorsBySlot?: Record<string, ValidationIssue[]>;
58
+ /** The validator config (mode + custom renderer). */
59
+ config: ValidatorConfig;
60
+ }
61
+ /**
62
+ * Renders a failed `ValidationResult` into a `Response`.
63
+ *
64
+ * A custom `errorRenderer` fully controls the body. `problem+json` emits the
65
+ * RFC 9457 shape (path/message only); `plain` emits `{ errors: { slot: issues } }`.
66
+ * Production emits only `path`/`message` (and `code`) — no stacks, source
67
+ * paths, or schema internals.
68
+ */
69
+ export declare function renderValidationError(result: ValidationResult, ctx: RenderContext): Response;