@cleverbrush/schema 0.0.0-beta-20260410073748

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 (85) hide show
  1. package/README.md +1409 -0
  2. package/dist/builders/AnySchemaBuilder.d.ts +116 -0
  3. package/dist/builders/AnySchemaBuilder.js +2 -0
  4. package/dist/builders/AnySchemaBuilder.js.map +1 -0
  5. package/dist/builders/ArraySchemaBuilder.d.ts +214 -0
  6. package/dist/builders/ArraySchemaBuilder.js +2 -0
  7. package/dist/builders/ArraySchemaBuilder.js.map +1 -0
  8. package/dist/builders/BooleanSchemaBuilder.d.ts +146 -0
  9. package/dist/builders/BooleanSchemaBuilder.js +2 -0
  10. package/dist/builders/BooleanSchemaBuilder.js.map +1 -0
  11. package/dist/builders/DateSchemaBuilder.d.ts +277 -0
  12. package/dist/builders/DateSchemaBuilder.js +2 -0
  13. package/dist/builders/DateSchemaBuilder.js.map +1 -0
  14. package/dist/builders/ExternSchemaBuilder.d.ts +200 -0
  15. package/dist/builders/ExternSchemaBuilder.js +2 -0
  16. package/dist/builders/ExternSchemaBuilder.js.map +1 -0
  17. package/dist/builders/FunctionSchemaBuilder.d.ts +246 -0
  18. package/dist/builders/FunctionSchemaBuilder.js +2 -0
  19. package/dist/builders/FunctionSchemaBuilder.js.map +1 -0
  20. package/dist/builders/LazySchemaBuilder.d.ts +167 -0
  21. package/dist/builders/NullSchemaBuilder.d.ts +162 -0
  22. package/dist/builders/NumberSchemaBuilder.d.ts +273 -0
  23. package/dist/builders/NumberSchemaBuilder.js +2 -0
  24. package/dist/builders/NumberSchemaBuilder.js.map +1 -0
  25. package/dist/builders/ObjectSchemaBuilder.d.ts +517 -0
  26. package/dist/builders/ObjectSchemaBuilder.js +2 -0
  27. package/dist/builders/ObjectSchemaBuilder.js.map +1 -0
  28. package/dist/builders/PropertyValidationResult.d.ts +68 -0
  29. package/dist/builders/RecordSchemaBuilder.d.ts +341 -0
  30. package/dist/builders/RecordSchemaBuilder.js +2 -0
  31. package/dist/builders/RecordSchemaBuilder.js.map +1 -0
  32. package/dist/builders/SchemaBuilder.d.ts +947 -0
  33. package/dist/builders/StringSchemaBuilder.d.ts +291 -0
  34. package/dist/builders/StringSchemaBuilder.js +2 -0
  35. package/dist/builders/StringSchemaBuilder.js.map +1 -0
  36. package/dist/builders/TupleSchemaBuilder.d.ts +248 -0
  37. package/dist/builders/TupleSchemaBuilder.js +2 -0
  38. package/dist/builders/TupleSchemaBuilder.js.map +1 -0
  39. package/dist/builders/UnionSchemaBuilder.d.ts +227 -0
  40. package/dist/builders/UnionSchemaBuilder.js +2 -0
  41. package/dist/builders/UnionSchemaBuilder.js.map +1 -0
  42. package/dist/chunk-CTP4RHDG.js +2 -0
  43. package/dist/chunk-CTP4RHDG.js.map +1 -0
  44. package/dist/chunk-FWUEUW2N.js +2 -0
  45. package/dist/chunk-FWUEUW2N.js.map +1 -0
  46. package/dist/chunk-IJ6FO37G.js +2 -0
  47. package/dist/chunk-IJ6FO37G.js.map +1 -0
  48. package/dist/chunk-KESLT5EE.js +2 -0
  49. package/dist/chunk-KESLT5EE.js.map +1 -0
  50. package/dist/chunk-KFTO7TMB.js +2 -0
  51. package/dist/chunk-KFTO7TMB.js.map +1 -0
  52. package/dist/chunk-MKAYFPAR.js +2 -0
  53. package/dist/chunk-MKAYFPAR.js.map +1 -0
  54. package/dist/chunk-NXPH3ZUW.js +2 -0
  55. package/dist/chunk-NXPH3ZUW.js.map +1 -0
  56. package/dist/chunk-OOPF7RXS.js +2 -0
  57. package/dist/chunk-OOPF7RXS.js.map +1 -0
  58. package/dist/chunk-S5TC6NSU.js +2 -0
  59. package/dist/chunk-S5TC6NSU.js.map +1 -0
  60. package/dist/chunk-YWBNVHR6.js +2 -0
  61. package/dist/chunk-YWBNVHR6.js.map +1 -0
  62. package/dist/chunk-Z72HXYKX.js +2 -0
  63. package/dist/chunk-Z72HXYKX.js.map +1 -0
  64. package/dist/chunk-Z7QZ7IXT.js +2 -0
  65. package/dist/chunk-Z7QZ7IXT.js.map +1 -0
  66. package/dist/chunk-ZAN4ZHCJ.js +2 -0
  67. package/dist/chunk-ZAN4ZHCJ.js.map +1 -0
  68. package/dist/chunk-ZUPYV5TI.js +2 -0
  69. package/dist/chunk-ZUPYV5TI.js.map +1 -0
  70. package/dist/core.d.ts +23 -0
  71. package/dist/core.js +2 -0
  72. package/dist/core.js.map +1 -0
  73. package/dist/extension.d.ts +413 -0
  74. package/dist/extensions/array.d.ts +112 -0
  75. package/dist/extensions/enum.d.ts +190 -0
  76. package/dist/extensions/index.d.ts +108 -0
  77. package/dist/extensions/nullable.d.ts +26 -0
  78. package/dist/extensions/number.d.ts +228 -0
  79. package/dist/extensions/string.d.ts +332 -0
  80. package/dist/extensions/util.d.ts +45 -0
  81. package/dist/index.d.ts +7 -0
  82. package/dist/index.js +2 -0
  83. package/dist/index.js.map +1 -0
  84. package/dist/utils/transaction.d.ts +69 -0
  85. package/package.json +104 -0
package/README.md ADDED
@@ -0,0 +1,1409 @@
1
+ # @cleverbrush/schema
2
+
3
+ [![CI](https://github.com/cleverbrush/framework/actions/workflows/ci.yml/badge.svg)](https://github.com/cleverbrush/framework/actions/workflows/ci.yml)
4
+ [![Standard Schema v1](https://img.shields.io/badge/Standard%20Schema-v1-blue)](https://standardschema.dev/)
5
+ <!-- bundle-badge-start -->
6
+ [![Bundle size](https://img.shields.io/badge/bundle-17.5%20KB%20gzip-green)](https://github.com/cleverbrush/framework/blob/master/libs/schema)
7
+ <!-- bundle-badge-end -->
8
+ [![License: BSD-3-Clause](https://img.shields.io/badge/license-BSD--3--Clause-blue.svg)](../../LICENSE)
9
+ <!-- coverage-badge-start -->
10
+ ![Coverage](https://img.shields.io/badge/coverage-98.7%25-brightgreen)
11
+ <!-- coverage-badge-end -->
12
+
13
+ A schema definition and validation library for TypeScript — faster than Zod in 14/15 benchmarks (up to 204× faster on invalid input), 3× smaller than Zod v4, and compatible with 50+ ecosystem tools via [Standard Schema v1](https://standardschema.dev/).
14
+
15
+ Define a schema **once** and get TypeScript type inference, runtime validation, object mapping ([`@cleverbrush/mapper`](../mapper)), auto-generated React forms ([`@cleverbrush/react-form`](../react-form)), and bidirectional JSON Schema conversion ([`@cleverbrush/schema-json`](../schema-json)) — all from the same immutable, fluent API.
16
+
17
+ ## Why @cleverbrush/schema?
18
+
19
+ **The problem:** In a typical TypeScript project, types and runtime validation are separate concerns. You define a `User` type in one file, then write Joi / Yup / Zod schemas (or manual `if` checks) in another. Over time these drift apart — the type says a field is required, but the validation allows it to be `undefined`. Tests pass, but production data breaks because the validation didn't match the type.
20
+
21
+ **The solution:** `@cleverbrush/schema` lets you define a schema **once** and derive both the TypeScript type (via `InferType`) and runtime validation from the same source. Because every method returns a **new builder instance** (immutability), you can safely compose and extend schemas without accidentally mutating shared definitions.
22
+
23
+ **What makes it different from Zod / Yup / Joi:**
24
+
25
+ - **PropertyDescriptors** — a runtime descriptor tree that every tool in the ecosystem can introspect. The [`@cleverbrush/mapper`](../mapper) uses it for type-safe property selectors. The [`@cleverbrush/react-form`](../react-form) uses it to auto-generate form fields with correct validation. This makes the schema library a **foundation** for an entire ecosystem — not just a standalone validation tool. No other popular schema library exposes this level of runtime metadata.
26
+ - **Standard Schema v1** — the `['~standard']` getter is implemented on every builder. That means your schema works as-is with tRPC, TanStack Form, React Hook Form, T3 Env, Hono, Elysia, next-safe-action, and every other [Standard Schema consumer](https://standardschema.dev/).
27
+ - **Extension system** — add custom methods to any builder type (`string`, `number`, `date`, …) via `defineExtension()` + `withExtensions()`. Extensions are fully typed, chainable, composable, and appear in `introspect()`. No other popular schema library offers a comparable type-safe plugin system.
28
+ - **Built-in extension pack** — common validators like `email()`, `url()`, `uuid()`, `ip()`, `trim()`, `positive()`, `negative()`, `nonempty()`, `unique()`, and more are included out of the box. The default import has them pre-applied; import from `@cleverbrush/schema/core` to get bare builders without extensions.
29
+ - **14 KB gzipped (full) — 3× smaller than Zod v4** — sub-path imports (`@cleverbrush/schema/string`, `/number`, `/object`, `/array`) drop individual builders to ~4 KB.
30
+ - **First-class nullable support** — `.nullable()` and `.notNullable()` are native methods on every builder. The inferred type automatically includes or excludes `null`, and `introspect()` exposes `isNullable` for runtime metadata.
31
+ - **JSDoc comment preservation** — JSDoc comments on schema properties carry through to the inferred TypeScript type, so IDE tooltips and autocomplete descriptions come from the schema definition itself.
32
+ - **Zero runtime dependencies.**
33
+
34
+ | Feature | @cleverbrush/schema | Zod | Yup | Joi |
35
+ | --- | --- | --- | --- | --- |
36
+ | TypeScript type inference | ✓ | ✓ | ~ | ✗ |
37
+ | [Standard Schema v1](https://standardschema.dev/) | ✓ | ✓ | ✗ | ✗ |
38
+ | **PropertyDescriptors** (runtime introspection) | ✓ | ✗ | ✗ | ✗ |
39
+ | **Type-safe extension system** | ✓ | ✗ | ✗ | ✗ |
40
+ | **Built-in object mapper** | ✓ | ✗ | ✗ | ✗ |
41
+ | **Built-in form generation** | ✓ | ✗ | ✗ | ✗ |
42
+ | Bidirectional JSON Schema | ✓ | ~ (output only) | ✗ | ✗ |
43
+ | **External schema interop** (`extern()`) | ✓ | ✗ | ✗ | ✗ |
44
+ | JSDoc preservation | ✓ | ✗ | ✗ | ✗ |
45
+ | Immutable schemas | ✓ | ✓ | ✗ | ✗ |
46
+ | Zero dependencies | ✓ | ✓ | ✗ | ✗ |
47
+ | Sync + async validation | ✓ | ✓ | ✓ | ✓ |
48
+ | Per-property error inspection | ✓ | ~ | ~ | ~ |
49
+ | Default values | ✓ | ✓ | ✓ | ✓ |
50
+ | Bundle size (full, gzipped) | **14 KB** | 41 KB (v4) | ~19 KB | ~26 KB |
51
+
52
+ ## Installation
53
+
54
+ ```bash
55
+ npm install @cleverbrush/schema
56
+ ```
57
+
58
+ ## Quick Start
59
+
60
+ [▶ Open in Playground](https://docs.cleverbrush.com/playground/quick-start)
61
+
62
+ ```typescript
63
+ import {
64
+ object,
65
+ string,
66
+ number,
67
+ boolean,
68
+ InferType
69
+ } from '@cleverbrush/schema';
70
+
71
+ // 1. Define a schema with fluent constraints
72
+ const UserSchema = object({
73
+ name: string().nonempty('Name is required').minLength(2, 'Name must be at least 2 characters'),
74
+ email: string().email('Please enter a valid email'),
75
+ age: number().min(0, 'Age cannot be negative').max(150).positive(),
76
+ isActive: boolean()
77
+ });
78
+
79
+ // 2. TypeScript type is inferred automatically — no duplication!
80
+ type User = InferType<typeof UserSchema>;
81
+ // Equivalent to: { name: string; email: string; age: number; isActive: boolean }
82
+
83
+ // 3. Validate data at runtime — synchronous by default
84
+ const result = UserSchema.validate({
85
+ name: 'Alice',
86
+ email: 'alice@example.com',
87
+ age: 30,
88
+ isActive: true
89
+ });
90
+
91
+ // Or use validateAsync() when you have async validators/preprocessors
92
+ // const result = await UserSchema.validateAsync({ ... });
93
+
94
+ if (result.valid) {
95
+ console.log('Validated:', result.object); // typed as User
96
+ } else {
97
+ // For object schemas, prefer getErrorsFor() for per-property error inspection:
98
+ const nameErrors = result.getErrorsFor((p) => p.name);
99
+ console.log(nameErrors.isValid); // false
100
+ console.log(nameErrors.errors); // ['Name must be at least 2 characters']
101
+
102
+ // result.errors on object schemas is deprecated — use getErrorsFor() instead
103
+ console.log('Errors:', result.errors);
104
+ // Array of { message: string }
105
+ }
106
+ ```
107
+
108
+ Type inference works in plain JavaScript too, using JSDoc:
109
+
110
+ ```javascript
111
+ /**
112
+ * @type {import('@cleverbrush/schema').InferType<typeof UserSchema>}
113
+ */
114
+ const user = {
115
+ // type is inferred as { name: string; email: string; age: number; isActive: boolean }
116
+ };
117
+ ```
118
+
119
+ ## Schema Types
120
+
121
+ [▶ Open in Playground](https://docs.cleverbrush.com/playground/schema-types)
122
+
123
+ The following builder functions are available:
124
+
125
+ | Function | Description | Key Methods |
126
+ | --------------- | ------------------------------------------------- | --------------------------------------------------------------- |
127
+ | `any()` | Any value. Similar to TypeScript's `any` type. | `.optional()`, `.nullable()`, `.notNullable()`, `.default(value)`, `.addValidator(fn)` |
128
+ | `string()` | String value with constraints. | `.minLength(n)`, `.maxLength(n)`, `.matches(re)`, `.email()`, `.url()`, `.uuid()`, `.ip()`, `.trim()`, `.toLowerCase()`, `.nonempty()`, `.oneOf(...values)`, `.nullable()`, `.notNullable()`, `.default(value)` |
129
+ | `number()` | Numeric value with constraints. | `.min(n)`, `.max(n)`, `.integer()`, `.positive()`, `.negative()`, `.finite()`, `.multipleOf(n)`, `.oneOf(...values)`, `.nullable()`, `.notNullable()`, `.default(value)` |
130
+ | `boolean()` | Boolean value. | `.optional()`, `.nullable()`, `.notNullable()`, `.default(value)` |
131
+ | `date()` | JavaScript `Date` instance. | `.optional()`, `.nullable()`, `.notNullable()`, `.default(value)` |
132
+ | `func()` | Function value. Supports typed parameter and return-type schemas. | `.addParameter(schema)`, `.hasReturnType(schema)`, `.optional()`, `.nullable()`, `.notNullable()`, `.default(value)` |
133
+ | `nul()` | Exactly `null`. Useful in nullable unions. | `.optional()`, `.default(value)` |
134
+ | `object(props)` | Object with typed properties. Supports nesting. | `.validate(data)`, `.addProps({...})`, `.optional()`, `.nullable()`, `.notNullable()`, `.default(value)` |
135
+ | `array()` | Array with optional element schema (via `.of()`). | `.minLength(n)`, `.maxLength(n)`, `.of(schema)`, `.nonempty()`, `.unique()`, `.nullable()`, `.notNullable()`, `.default(value)` |
136
+ | `tuple([...schemas])` | Fixed-length array with per-position types. Each index validated against its own schema — mirrors TypeScript tuple types. | `.rest(schema)`, `.optional()`, `.nullable()`, `.notNullable()`, `.default(value)` |
137
+ | `record(keySchema, valSchema)` | Object with dynamic string keys. Every key must satisfy `keySchema` (a string schema) and every value must satisfy `valSchema` — mirrors TypeScript's `Record<K, V>`. | `.optional()`, `.nullable()`, `.notNullable()`, `.default(value)`, `.addValidator(fn)` |
138
+ | `union(schema)` | Union of schemas — e.g. `string \| number`. | `.or(schema)`, `.validate(data)`, `.optional()`, `.nullable()`, `.notNullable()`, `.default(value)` |
139
+ | `enumOf(...values)` | String enum — sugar for `string().oneOf(...)`. | `.optional()`, `.nullable()`, `.notNullable()`, `.default(value)` |
140
+ | `lazy(getter)` | Recursive/self-referential schema. The getter is called once and its result is cached. Enables tree structures, linked lists, and other recursive types. | `.resolve()`, `.optional()`, `.addValidator(fn)`, `.default(value)` |
141
+
142
+ ## Immutability
143
+
144
+ [▶ Open in Playground](https://docs.cleverbrush.com/playground/immutability)
145
+
146
+ All schema builders are immutable. Every method call returns a **new** schema builder instance, so existing schemas are never modified:
147
+
148
+ ```typescript
149
+ const base = string().minLength(1);
150
+ const strict = base.maxLength(50); // new instance — base is unchanged
151
+ const loose = base.optional(); // another new instance
152
+
153
+ // base still only has minLength(1)
154
+ // strict has minLength(1) + maxLength(50)
155
+ // loose has minLength(1) + optional
156
+ ```
157
+
158
+ This is especially powerful when building a library of reusable schema fragments:
159
+
160
+ ```typescript
161
+ const Email = string().minLength(5).maxLength(255);
162
+ const Name = string().minLength(1).maxLength(100);
163
+
164
+ const CreateUser = object({ name: Name, email: Email });
165
+ const UpdateUser = object({ name: Name.optional(), email: Email.optional() });
166
+ // Both schemas share the same base constraints but differ in optionality
167
+ ```
168
+
169
+ ## Composing Schemas
170
+
171
+ [▶ Open in Playground](https://docs.cleverbrush.com/playground/composing-schemas)
172
+
173
+ Schemas can be extended with additional properties, combined with unions, or nested inside arrays and objects:
174
+
175
+ ```typescript
176
+ import { object, string, number, array, union } from '@cleverbrush/schema';
177
+
178
+ // Extend an existing schema with new properties
179
+ const BaseEntity = object({
180
+ id: string(),
181
+ createdAt: string()
182
+ });
183
+
184
+ const UserEntity = BaseEntity.addProps({
185
+ name: string().minLength(2),
186
+ email: string().minLength(5)
187
+ });
188
+
189
+ // Nest objects inside arrays
190
+ const TeamSchema = object({
191
+ name: string().minLength(1),
192
+ members: array().of(UserEntity).minLength(1).maxLength(50)
193
+ });
194
+
195
+ // Union types
196
+ const IdOrEmail = union(string().minLength(1)).or(
197
+ string().matches(/^[^@]+@[^@]+$/)
198
+ );
199
+ ```
200
+
201
+ ## Function Schemas
202
+
203
+ [▶ Open in Playground](https://docs.cleverbrush.com/playground/function-schema)
204
+
205
+ Use `func()` to validate that a value is a function. Two fluent methods let you annotate the expected signature — the inferred TypeScript type reflects both the parameter types and the return type:
206
+
207
+ - **`.addParameter(schema)`** — appends a parameter schema. Each call extends the inferred tuple of parameter types. The schemas are accessible at runtime via `introspect().parameters`.
208
+ - **`.hasReturnType(schema)`** — sets the return type schema. The inferred function type gains a concrete return type instead of `any`. Accessible via `introspect().returnType`.
209
+
210
+ ```typescript
211
+ import { func, string, number, boolean, InferType } from '@cleverbrush/schema';
212
+
213
+ // Plain function validator — accepts any () => any
214
+ const anyFn = func();
215
+ anyFn.validate(() => 42); // { valid: true }
216
+ anyFn.validate('not a fn'); // { valid: false }
217
+
218
+ // Typed parameter and return type
219
+ const greet = func()
220
+ .addParameter(string()) // first param: string
221
+ .addParameter(number().optional()) // second param: number | undefined
222
+ .hasReturnType(string()); // return type: string
223
+
224
+ // InferType preserves the declared parameter types and return type.
225
+ // Function schemas also remain compatible with callbacks of any arity.
226
+ type Greet = InferType<typeof greet>;
227
+ // → (param0: string, param1: number | undefined, ...args: any[]) => string
228
+
229
+ // Introspect at runtime
230
+ const info = greet.introspect();
231
+ // info.parameters → [StringSchemaBuilder, NumberSchemaBuilder]
232
+ // info.returnType → StringSchemaBuilder
233
+
234
+ // Optional function schemas infer a union with undefined
235
+ const optionalHandler = func()
236
+ .addParameter(string())
237
+ .addParameter(boolean())
238
+ .hasReturnType(boolean())
239
+ .optional();
240
+
241
+ type OptionalHandler = InferType<typeof optionalHandler>;
242
+ // → ((param0: string, param1: boolean, ...args: any[]) => boolean) | undefined
243
+ ```
244
+
245
+ ## Record Schemas
246
+
247
+ [▶ Open in Playground](https://docs.cleverbrush.com/playground/record-basics)
248
+
249
+ Use `record(keySchema, valueSchema)` to validate objects with **dynamic string keys** — lookup tables, i18n bundles, caches, or any `Record<string, V>` shape. Unlike `object()`, which requires a fixed set of known property names, `record()` validates objects whose keys are not known at schema-definition time.
250
+
251
+ Both the key and the value schema are enforced at runtime, and the inferred TypeScript type mirrors `Record<K, V>`.
252
+
253
+ ```typescript
254
+ import { record, string, number, object, InferType } from '@cleverbrush/schema';
255
+
256
+ // ── Basic: string keys → number values ──────────────────────────────────────
257
+ const scores = record(string(), number().min(0).max(100));
258
+ // InferType<typeof scores> → Record<string, number>
259
+
260
+ scores.validate({ alice: 95, bob: 87 }); // { valid: true }
261
+ scores.validate({ alice: 95, bob: -1 }); // { valid: false } — negative score
262
+
263
+ // ── Key constraint — only locale-style keys allowed ──────────────────────────
264
+ const i18n = record(
265
+ string().matches(/^[a-z]{2}(-[A-Z]{2})?$/),
266
+ string().nonempty()
267
+ );
268
+
269
+ i18n.validate({ en: 'Hello', 'fr-FR': 'Bonjour' }); // { valid: true }
270
+ i18n.validate({ '123': 'oops' }); // { valid: false } — bad key
271
+
272
+ // ── Nested: values are objects ───────────────────────────────────────────────
273
+ const userMap = record(
274
+ string(),
275
+ object({ name: string(), age: number() })
276
+ );
277
+ // InferType<typeof userMap> → Record<string, { name: string; age: number }>
278
+
279
+ // ── Optional with factory default ────────────────────────────────────────────
280
+ const cache = record(string(), number()).optional().default(() => ({}));
281
+
282
+ // ── getErrorsFor(key) — rich per-key result with descriptor ────────────────────
283
+ const schema = record(string(), number().min(0));
284
+ const result = schema.validate(
285
+ { a: 1, b: -2, c: -3 },
286
+ { doNotStopOnFirstError: true }
287
+ );
288
+
289
+ if (!result.valid) {
290
+ // Root-level errors (e.g. 'object expected')
291
+ const root = result.getErrorsFor();
292
+ console.log(root.isValid); // false if the container itself is invalid
293
+
294
+ // Per-key errors
295
+ const bResult = result.getErrorsFor('b');
296
+ console.log(bResult.isValid); // false
297
+ console.log(bResult.errors[0]); // 'the value must be >= 0'
298
+ console.log(bResult.seenValue); // -2
299
+
300
+ // Descriptor: read/write the entry on the original object
301
+ const descriptor = bResult.descriptor;
302
+ console.log(descriptor.key); // 'b'
303
+ descriptor.getSchema(); // → NumberSchemaBuilder
304
+ descriptor.getValue(result.object); // → { success: true, value: -2 }
305
+ descriptor.setValue(result.object, 0); // fixes the value in-place
306
+ }
307
+ ```
308
+
309
+ ## Recursive Schemas
310
+
311
+ [▶ Open in Playground](https://docs.cleverbrush.com/playground/recursive-schemas)
312
+
313
+ Use `lazy(() => schema)` to define recursive or self-referential schemas — tree structures, comment threads, nested menus, org charts, and any other type that refers to itself.
314
+
315
+ The getter function is called **once** on first validation, and the resolved schema is cached. Every subsequent call reuses the cache.
316
+
317
+ > **TypeScript limitation:** TypeScript cannot infer recursive types automatically. You must provide an explicit type annotation on the variable holding the schema.
318
+
319
+ ```typescript
320
+ import {
321
+ object,
322
+ string,
323
+ number,
324
+ array,
325
+ lazy,
326
+ type SchemaBuilder
327
+ } from '@cleverbrush/schema';
328
+
329
+ // ── Tree structure ───────────────────────────────────────────────
330
+ type TreeNode = { value: number; children: TreeNode[] };
331
+
332
+ // Explicit annotation required — TypeScript can't infer recursive types
333
+ const treeNode: SchemaBuilder<TreeNode, true> = object({
334
+ value: number(),
335
+ children: array(lazy(() => treeNode))
336
+ });
337
+
338
+ treeNode.validate({
339
+ value: 1,
340
+ children: [
341
+ { value: 2, children: [] },
342
+ { value: 3, children: [{ value: 4, children: [] }] }
343
+ ]
344
+ });
345
+ // { valid: true, object: { value: 1, children: [...] } }
346
+
347
+ // ── Comment thread ───────────────────────────────────────────────
348
+ type Comment = { text: string; replies: Comment[] };
349
+
350
+ const commentSchema: SchemaBuilder<Comment, true> = object({
351
+ text: string(),
352
+ replies: array(lazy(() => commentSchema))
353
+ });
354
+
355
+ // ── Navigation menu with optional sub-levels ─────────────────────
356
+ type MenuItem = { label: string; submenu?: MenuItem[] };
357
+
358
+ const menuItem: SchemaBuilder<MenuItem, true> = object({
359
+ label: string(),
360
+ submenu: array(lazy(() => menuItem)).optional()
361
+ });
362
+ ```
363
+
364
+ `lazy()` is fully compatible with `.optional()`, `.addPreprocessor()`, `.addValidator()`, and all other fluent methods. The wrapper's own preprocessors and validators run before delegating to the resolved schema.
365
+
366
+ ```typescript
367
+ // Preprocessors and validators work on the lazy wrapper itself
368
+ const schema = lazy(() => string())
369
+ .addPreprocessor((v) => (typeof v === 'number' ? String(v) : v))
370
+ .addValidator((v) => ({ valid: v !== 'forbidden' }));
371
+ ```
372
+
373
+ ## Discriminated Unions
374
+
375
+ [▶ Open in Playground](https://docs.cleverbrush.com/playground/discriminated-unions)
376
+
377
+ Some libraries ship a dedicated `.discriminator()` API for tagged unions. With `@cleverbrush/schema` you don't need one — `union()` combined with **string-literal schemas** gives you the same pattern naturally, with full type inference.
378
+
379
+ Use `string('literal')` for the discriminator field. Each branch of the union gets its own object schema whose discriminator can only match one exact value. TypeScript narrows the inferred type automatically:
380
+
381
+ ```typescript
382
+ import { object, string, number, union, type InferType } from '@cleverbrush/schema';
383
+
384
+ // Each variant has a literal "type" field acting as the discriminator
385
+ const Circle = object({
386
+ type: string('circle'),
387
+ radius: number().min(0)
388
+ });
389
+
390
+ const Rectangle = object({
391
+ type: string('rectangle'),
392
+ width: number().min(0),
393
+ height: number().min(0)
394
+ });
395
+
396
+ const Triangle = object({
397
+ type: string('triangle'),
398
+ base: number().min(0),
399
+ height: number().min(0)
400
+ });
401
+
402
+ // Combine with union() — no special .discriminator() call needed
403
+ const ShapeSchema = union(Circle).or(Rectangle).or(Triangle);
404
+
405
+ type Shape = InferType<typeof ShapeSchema>;
406
+ // Shape is automatically:
407
+ // | { type: 'circle'; radius: number }
408
+ // | { type: 'rectangle'; width: number; height: number }
409
+ // | { type: 'triangle'; base: number; height: number }
410
+
411
+ // Validation picks the matching branch by the literal field
412
+ const result = ShapeSchema.validate({ type: 'circle', radius: 5 });
413
+ ```
414
+
415
+ ### Real-World Example: Job Scheduler
416
+
417
+ The `@cleverbrush/scheduler` library uses this exact pattern to validate job schedules. The `every` field acts as the discriminator, and each variant adds its own set of allowed properties:
418
+
419
+ ```typescript
420
+ import { object, string, number, array, date, union, type InferType } from '@cleverbrush/schema';
421
+
422
+ // Shared base with common schedule fields
423
+ const ScheduleBase = object({
424
+ interval: number().min(1).max(356),
425
+ hour: number().min(0).max(23).optional(),
426
+ minute: number().min(0).max(59).optional(),
427
+ startsOn: date().acceptJsonString().optional(),
428
+ endsOn: date().acceptJsonString().optional()
429
+ });
430
+
431
+ // Minute schedule — omit hour/minute (they don't apply)
432
+ const EveryMinute = ScheduleBase
433
+ .omit('hour').omit('minute')
434
+ .addProps({ every: string('minute') });
435
+
436
+ // Day schedule
437
+ const EveryDay = ScheduleBase
438
+ .addProps({ every: string('day') });
439
+
440
+ // Week schedule — adds dayOfWeek array
441
+ const EveryWeek = ScheduleBase.addProps({
442
+ every: string('week'),
443
+ dayOfWeek: array().of(number().min(1).max(7)).minLength(1).maxLength(7)
444
+ });
445
+
446
+ // Month schedule — adds day (number or 'last')
447
+ const EveryMonth = ScheduleBase.addProps({
448
+ every: string('month'),
449
+ day: union(string('last')).or(number().min(1).max(28))
450
+ });
451
+
452
+ // Combine all variants in a single union
453
+ const ScheduleSchema = union(EveryMinute)
454
+ .or(EveryDay)
455
+ .or(EveryWeek)
456
+ .or(EveryMonth);
457
+
458
+ type Schedule = InferType<typeof ScheduleSchema>;
459
+ // TypeScript infers a proper discriminated union on "every"
460
+ ```
461
+
462
+ Because each branch uses a string literal (`string('minute')`, `string('day')`, etc.) for the `every` field, TypeScript can narrow the full union based on that single property — exactly like zod's `z.discriminatedUnion()`, but without any extra API surface.
463
+
464
+ ## JSDoc Comment Preservation
465
+
466
+ When you define an object schema, JSDoc comments on properties are preserved in the inferred TypeScript type. This means your IDE tooltips, hover documentation, and autocomplete descriptions all carry through from the schema definition — no need to maintain separate documentation:
467
+
468
+ ```typescript
469
+ const UserSchema = object({
470
+ /** Full display name of the user */
471
+ name: string().minLength(1).maxLength(200),
472
+ /** Contact email — must be unique across all users */
473
+ email: string().minLength(5),
474
+ /** Age in years. Must be a positive integer. */
475
+ age: number().min(0).max(150)
476
+ });
477
+
478
+ type User = InferType<typeof UserSchema>;
479
+ // Hovering over User.name in your IDE shows:
480
+ // "Full display name of the user"
481
+ // Hovering over User.email shows:
482
+ // "Contact email — must be unique across all users"
483
+ ```
484
+
485
+ ## Deep Partial
486
+
487
+ [▶ Open in Playground](https://docs.cleverbrush.com/playground/deep-partial)
488
+
489
+ `.deepPartial()` recursively marks **all properties at every nesting level** as optional. It is the deep-object equivalent of a common `DeepPartial<T>` helper type in TypeScript, and is the recommended way to build PATCH API bodies or partial form state.
490
+
491
+ | Schema type | Effect |
492
+ |-------------|--------|
493
+ | `object(…).deepPartial()` | All top-level and nested object properties become optional |
494
+ | Nested `object(…)` inside an object | Recursed — its properties are made optional too |
495
+ | `array(…)`, `union(…)`, primitives | The property itself is made optional; internals are **not** modified |
496
+
497
+ ```typescript
498
+ import { object, string, number, array, type InferType } from '@cleverbrush/schema';
499
+
500
+ const CreateUser = object({
501
+ name: string(),
502
+ address: object({
503
+ street: string(),
504
+ city: string()
505
+ })
506
+ });
507
+
508
+ const PatchUser = CreateUser.deepPartial();
509
+
510
+ type PatchUserPayload = InferType<typeof PatchUser>;
511
+ // {
512
+ // name?: string;
513
+ // address?: { street?: string; city?: string };
514
+ // }
515
+
516
+ // All three are valid:
517
+ PatchUser.validate({}); // { valid: true }
518
+ PatchUser.validate({ address: {} }); // { valid: true }
519
+ PatchUser.validate({ address: { city: 'Paris' } }); // { valid: true }
520
+ ```
521
+
522
+ Contrast with `.partial()`, which only affects the top level:
523
+
524
+ ```typescript
525
+ const ShallowPartial = CreateUser.partial();
526
+ // { name?: string; address?: { street: string; city: string } }
527
+ // ↑ still required inside
528
+
529
+ ShallowPartial.validate({ address: {} });
530
+ // { valid: false } — street and city are still required
531
+ ```
532
+
533
+ Chains naturally with other modifiers:
534
+
535
+ ```typescript
536
+ const Schema = CreateUser.deepPartial().readonly();
537
+ type T = InferType<typeof Schema>;
538
+ // Readonly<{ name?: string; address?: { street?: string; city?: string } }>
539
+ ```
540
+
541
+ > **Note:** `.deepPartial()` recurses only into nested `object()` schemas. Array element schemas and union option schemas are not modified — `array(object({…}))` becomes an optional array but its element shape is unchanged. If you need deep-partialed array elements, apply `.deepPartial()` to the element schema before passing it to `array()`:
542
+ > ```typescript
543
+ > array(InnerSchema.deepPartial()).optional()
544
+ > ```
545
+
546
+ ## Validation
547
+
548
+ [▶ Open in Playground](https://docs.cleverbrush.com/playground/validation-errors)
549
+
550
+ Every schema builder has two validation methods:
551
+
552
+ - **`validate(data)`** — synchronous. Returns a `ValidationResult` directly. Throws if any preprocessor, validator, or error message provider returns a Promise.
553
+ - **`validateAsync(data)`** — asynchronous. Returns a `Promise<ValidationResult>`. Supports async preprocessors, validators, and error message providers.
554
+
555
+ Use `validate()` by default for the best performance. Switch to `validateAsync()` only when your schema includes async operations (e.g. database lookups, API calls in validators).
556
+
557
+ ```typescript
558
+ // Synchronous validation (default — use when all validators are sync)
559
+ const result = UserSchema.validate(someObject);
560
+
561
+ if (result.valid) {
562
+ console.log(result.object); // typed as InferType<typeof UserSchema>
563
+ } else {
564
+ // For object schemas, prefer getErrorsFor() for per-property error inspection (see below)
565
+ console.log(result.errors); // deprecated for object schemas — Array of { message: string }
566
+ }
567
+
568
+ // Async validation (use when validators/preprocessors are async)
569
+ const asyncResult = await UserSchema.validateAsync(someObject);
570
+ ```
571
+
572
+ ### Collecting All Errors
573
+
574
+ By default, validation stops at the first error. Pass `{ doNotStopOnFirstError: true }` to collect all errors at once:
575
+
576
+ ```typescript
577
+ const result = UserSchema.validate(
578
+ { name: 'A', email: '', age: -5, isActive: true },
579
+ { doNotStopOnFirstError: true }
580
+ );
581
+
582
+ console.log(result.errors);
583
+ // [
584
+ // { message: 'Name must be at least 2 characters' },
585
+ // { message: 'Please enter a valid email' },
586
+ // { message: 'Age cannot be negative' }
587
+ // ]
588
+ ```
589
+
590
+ ### Custom Error Messages
591
+
592
+ [▶ Open in Playground](https://docs.cleverbrush.com/playground/custom-error-messages)
593
+
594
+ Every constraint accepts an optional error message — either a plain string or a function:
595
+
596
+ ```typescript
597
+ const Name = string()
598
+ .minLength(2, 'Name is too short')
599
+ .maxLength(50, (seen) => `"${seen}" exceeds 50 characters`);
600
+
601
+ const Age = number()
602
+ .min(0, 'Age cannot be negative')
603
+ .max(150, 'Age seems unrealistic');
604
+ ```
605
+
606
+ ### Custom Validators
607
+
608
+ [▶ Open in Playground](https://docs.cleverbrush.com/playground/custom-validators)
609
+
610
+ Add custom synchronous or asynchronous validators to any schema:
611
+
612
+ ```typescript
613
+ const EmailSchema = string()
614
+ .minLength(5, 'Email is too short')
615
+ .addValidator(async (value) => {
616
+ if (value === 'taken@example.com') {
617
+ return {
618
+ valid: false,
619
+ errors: [{ message: 'This email is already registered' }]
620
+ };
621
+ }
622
+ return { valid: true };
623
+ });
624
+ ```
625
+
626
+ Object-level validators can validate cross-field constraints:
627
+
628
+ ```typescript
629
+ const SignupSchema = object({
630
+ password: string().minLength(8),
631
+ confirmPassword: string().minLength(8)
632
+ }).addValidator(async (value) => {
633
+ if (value.password !== value.confirmPassword) {
634
+ return {
635
+ valid: false,
636
+ errors: [{ message: 'Passwords do not match' }]
637
+ };
638
+ }
639
+ return { valid: true };
640
+ });
641
+ ```
642
+
643
+ ### Per-Property Errors with `getErrorsFor()` (Recommended)
644
+
645
+ `ObjectSchemaBuilder.validate()` returns an extended result with a `getErrorsFor()` method for inspecting errors on individual properties — perfect for showing inline form errors. **This is the recommended way to inspect validation errors on object schemas** and replaces the deprecated `errors` array on `ObjectSchemaValidationResult`:
646
+
647
+ ```typescript
648
+ const PersonSchema = object({
649
+ name: string().minLength(1),
650
+ address: object({
651
+ city: string(),
652
+ zip: number()
653
+ })
654
+ });
655
+
656
+ const result = PersonSchema.validate(person, {
657
+ doNotStopOnFirstError: true
658
+ });
659
+
660
+ if (!result.valid) {
661
+ // Get errors for a single property
662
+ const nameErrors = result.getErrorsFor((p) => p.name);
663
+ console.log(nameErrors.isValid); // false
664
+ console.log(nameErrors.errors); // ['must be at least 1 character']
665
+ console.log(nameErrors.seenValue); // the value that was validated
666
+
667
+ // Works with nested properties too
668
+ const cityErrors = result.getErrorsFor((p) => p.address.city);
669
+ console.log(cityErrors.errors);
670
+ }
671
+ ```
672
+
673
+ ## PropertyDescriptors
674
+
675
+ PropertyDescriptors are a runtime metadata tree attached to each property in an object schema. They provide type-safe access to property values, schema builders, and parent descriptors. This is what makes the entire Cleverbrush ecosystem work:
676
+
677
+ - [`@cleverbrush/mapper`](../mapper) uses them as **selectors** (like C# expression trees) to point at source and target properties type-safely.
678
+ - [`@cleverbrush/react-form`](../react-form) uses them to bind form fields to schema properties and read their validation constraints automatically.
679
+
680
+ ```typescript
681
+ import {
682
+ object,
683
+ string,
684
+ number,
685
+ ObjectSchemaBuilder
686
+ } from '@cleverbrush/schema';
687
+
688
+ const UserSchema = object({
689
+ name: string().minLength(2),
690
+ address: object({
691
+ city: string(),
692
+ zip: number()
693
+ })
694
+ });
695
+
696
+ // Get the PropertyDescriptor tree
697
+ const tree = ObjectSchemaBuilder.getPropertiesFor(UserSchema);
698
+
699
+ // Use descriptors as selectors in mapper and react-form:
700
+ // mapper: .for((t) => t.name).from((s) => s.name)
701
+ // react-form: <Field selector={(t) => t.address.city} form={form} />
702
+ ```
703
+
704
+ ## Default Values
705
+
706
+ Every schema builder supports `.default(value)`. When the input is `undefined`, the default value is used instead — and the result is still validated against the schema's constraints.
707
+
708
+ ```typescript
709
+ import { string, number, array, object, InferType } from '@cleverbrush/schema';
710
+
711
+ // Static default
712
+ const Name = string().default('Anonymous');
713
+ Name.validate(undefined); // { valid: true, object: 'Anonymous' }
714
+ Name.validate('Alice'); // { valid: true, object: 'Alice' }
715
+
716
+ // Factory function — useful for mutable defaults
717
+ const Tags = array(string()).default(() => []);
718
+
719
+ // Works with .optional() — removes undefined from the type
720
+ const Port = number().optional().default(3000);
721
+ type Port = InferType<typeof Port>; // number (not number | undefined)
722
+ ```
723
+
724
+ Use a factory function for mutable values (arrays, objects) to avoid shared references:
725
+
726
+ ```typescript
727
+ const Config = object({
728
+ host: string().default('localhost'),
729
+ port: number().default(8080),
730
+ tags: array(string()).default(() => [])
731
+ });
732
+
733
+ type Config = InferType<typeof Config>;
734
+ // { host: string; port: number; tags: string[] }
735
+ // All fields are non-optional — defaults fill in missing values
736
+ ```
737
+
738
+ Default values are exposed via `.introspect()`:
739
+
740
+ ```typescript
741
+ const schema = string().default('hello');
742
+ const info = schema.introspect();
743
+ console.log(info.hasDefault); // true
744
+ console.log(info.defaultValue); // 'hello'
745
+ ```
746
+
747
+ ## Catch / Fallback
748
+
749
+ Every schema builder supports `.catch(value)`. When validation **fails for any reason** — wrong type, constraint violation, missing required value — the fallback is returned as a successful result instead of errors.
750
+
751
+ Unlike `.default()`, which only fires when the input is `undefined`, `.catch()` fires on **any** validation failure.
752
+
753
+ ```typescript
754
+ import { string, number, array, object } from '@cleverbrush/schema';
755
+
756
+ // Static fallback
757
+ const Name = string().catch('unknown');
758
+ Name.validate(42); // { valid: true, object: 'unknown' }
759
+ Name.validate(null); // { valid: true, object: 'unknown' }
760
+ Name.validate('Alice'); // { valid: true, object: 'Alice' }
761
+
762
+ // Constraint violation also triggers catch
763
+ const Age = number().min(0).catch(-1);
764
+ Age.validate(-5); // { valid: true, object: -1 }
765
+
766
+ // .parse() and .parseAsync() never throw when .catch() is set
767
+ Name.parse(42); // 'unknown' (no SchemaValidationError thrown)
768
+ ```
769
+
770
+ Use a factory function for mutable fallback values to avoid shared references:
771
+
772
+ ```typescript
773
+ const Tags = array(string()).catch(() => []);
774
+
775
+ const r1 = Tags.validate(null); // { valid: true, object: [] }
776
+ const r2 = Tags.validate(null); // { valid: true, object: [] }
777
+ // r1.object !== r2.object — separate array instances each time
778
+ ```
779
+
780
+ The fallback state is exposed via `.introspect()`:
781
+
782
+ ```typescript
783
+ const schema = string().catch('unknown');
784
+ const info = schema.introspect();
785
+ console.log(info.hasCatch); // true
786
+ console.log(info.catchValue); // 'unknown'
787
+ ```
788
+
789
+ ## Readonly Modifier
790
+
791
+ Every schema builder supports `.readonly()`. This is a **type-level-only** modifier — it marks the inferred TypeScript type as immutable, but does not alter validation behaviour or freeze the validated value at runtime.
792
+
793
+ | Builder | Effect on `InferType<T>` |
794
+ |---------|--------------------------|
795
+ | `object(…).readonly()` | `Readonly<{ … }>` — all top-level properties become `readonly` |
796
+ | `array(…).readonly()` | `ReadonlyArray<T>` — no `push`, `pop`, etc. at the type level |
797
+ | `string().readonly()` | `string` (identity — primitives are already immutable) |
798
+ | `number().readonly()` | `number` (identity) |
799
+ | `boolean().readonly()` | `boolean` (identity) |
800
+ | `date().readonly()` | `Readonly<Date>` |
801
+
802
+ ```typescript
803
+ import { object, array, string, number, InferType } from '@cleverbrush/schema';
804
+
805
+ // Readonly object
806
+ const UserSchema = object({ name: string(), age: number() }).readonly();
807
+ type User = InferType<typeof UserSchema>;
808
+ // Readonly<{ name: string; age: number }>
809
+
810
+ // Readonly array
811
+ const TagsSchema = array(string()).readonly();
812
+ type Tags = InferType<typeof TagsSchema>;
813
+ // ReadonlyArray<string>
814
+
815
+ // Validation behaviour is unchanged
816
+ const result = UserSchema.validate({ name: 'Alice', age: 30 });
817
+ // { valid: true, object: { name: 'Alice', age: 30 } }
818
+ ```
819
+
820
+ Chains naturally with `.optional()` and `.default()`:
821
+
822
+ ```typescript
823
+ const Schema = object({ id: number() }).readonly().optional();
824
+ type T = InferType<typeof Schema>;
825
+ // Readonly<{ id: number }> | undefined
826
+ ```
827
+
828
+ The `isReadonly` flag is exposed via `.introspect()` for tooling:
829
+
830
+ ```typescript
831
+ const schema = object({ name: string() }).readonly();
832
+ console.log(schema.introspect().isReadonly); // true
833
+ ```
834
+
835
+ > **Note:** `.readonly()` is **shallow** — only top-level object properties or the array itself are marked readonly. For deeply nested immutability consider applying `.readonly()` at each level, or use a `DeepReadonly` utility type post-validation.
836
+
837
+ ## Describe
838
+
839
+ Every schema builder supports `.describe(text)`. This is a **metadata-only** modifier — it stores a human-readable description on the schema at runtime with no effect on validation.
840
+
841
+ ```typescript
842
+ const UserSchema = object({
843
+ name: string().describe("The user's full name"),
844
+ age: number().optional().describe('Age in years'),
845
+ }).describe('A user object');
846
+
847
+ // Read the description back at runtime
848
+ UserSchema.introspect().description; // 'A user object'
849
+ ```
850
+
851
+ The description is accessible via `.introspect().description` and chains naturally with all other modifiers:
852
+
853
+ ```typescript
854
+ string().describe('A name').optional().readonly()
855
+ // ^ InferType is string | undefined, isReadonly: true, description: 'A name'
856
+ ```
857
+
858
+ When using `@cleverbrush/schema-json`, descriptions round-trip through JSON Schema's standard `description` field:
859
+
860
+ ```typescript
861
+ import { toJsonSchema, fromJsonSchema } from '@cleverbrush/schema-json';
862
+
863
+ const spec = toJsonSchema(string().describe('A name'), { $schema: false });
864
+ // { type: 'string', description: 'A name' }
865
+
866
+ const schema = fromJsonSchema({ type: 'string', description: 'A name' } as const);
867
+ schema.introspect().description; // 'A name'
868
+ ```
869
+
870
+ ## Extensions
871
+
872
+ [▶ Open in Playground](https://docs.cleverbrush.com/playground/custom-extensions)
873
+
874
+ The extension system lets you add **custom methods** to any schema builder type without modifying the core library. Define an extension once, apply it with `withExtensions()`, and every builder produced by the returned factories includes your new methods — fully typed and chainable.
875
+
876
+ ### Defining an Extension
877
+
878
+ Use `defineExtension()` to declare which builder types your extension targets and what methods it adds. Extension methods receive `this` bound to the builder instance and must return a builder to support fluent chaining:
879
+
880
+ ```typescript
881
+ import {
882
+ defineExtension,
883
+ withExtensions,
884
+ StringSchemaBuilder,
885
+ NumberSchemaBuilder,
886
+ DateSchemaBuilder
887
+ } from '@cleverbrush/schema';
888
+
889
+ // Email extension — adds .email() to string builders
890
+ const emailExt = defineExtension({
891
+ string: {
892
+ email(this: StringSchemaBuilder) {
893
+ return this.addValidator((val) => {
894
+ const valid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(val as string);
895
+ return {
896
+ valid,
897
+ errors: valid
898
+ ? []
899
+ : [{ message: 'Invalid email address' }]
900
+ };
901
+ });
902
+ }
903
+ }
904
+ });
905
+
906
+ // Port extension — adds .port() to number builders
907
+ const portExt = defineExtension({
908
+ number: {
909
+ port(this: NumberSchemaBuilder) {
910
+ return this.isInteger().min(1).max(65535);
911
+ }
912
+ }
913
+ });
914
+
915
+ // Slug extension — adds .slug() to string builders
916
+ const slugExt = defineExtension({
917
+ string: {
918
+ slug(this: StringSchemaBuilder) {
919
+ return this.addValidator((val) => {
920
+ const valid = /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(val as string);
921
+ return {
922
+ valid,
923
+ errors: valid
924
+ ? []
925
+ : [{ message: 'Must be a valid URL slug' }]
926
+ };
927
+ });
928
+ }
929
+ }
930
+ });
931
+ ```
932
+
933
+ ### Using Extensions
934
+
935
+ Pass one or more extension descriptors to `withExtensions()` to get augmented factory functions. All original builder methods remain available and fully chainable alongside the new ones:
936
+
937
+ ```typescript
938
+ const s = withExtensions(emailExt, portExt, slugExt);
939
+
940
+ // .email() and .slug() are now available on string builders
941
+ const EmailSchema = s.string().email().minLength(5);
942
+ const SlugSchema = s.string().slug().minLength(1).maxLength(200);
943
+
944
+ // .port() is now available on number builders
945
+ const PortSchema = s.number().port();
946
+
947
+ // Use in object schemas — just like normal builders
948
+ const ServerConfig = s.object({
949
+ adminEmail: s.string().email(),
950
+ port: s.number().port(),
951
+ slug: s.string().slug(),
952
+ name: s.string().minLength(1)
953
+ });
954
+
955
+ // Validate as usual
956
+ const result = ServerConfig.validate({
957
+ adminEmail: 'admin@example.com',
958
+ port: 8080,
959
+ slug: 'my-server',
960
+ name: 'Production'
961
+ });
962
+ ```
963
+
964
+ ### Multi-Builder Extensions
965
+
966
+ A single extension can target multiple builder types:
967
+
968
+ ```typescript
969
+ const timestampsExt = defineExtension({
970
+ string: {
971
+ /** Marks this string property as an ISO timestamp */
972
+ isoTimestamp(this: StringSchemaBuilder) {
973
+ return this.addValidator((val) => {
974
+ const valid = !isNaN(Date.parse(val as string));
975
+ return {
976
+ valid,
977
+ errors: valid
978
+ ? []
979
+ : [{ message: 'Must be a valid ISO timestamp' }]
980
+ };
981
+ });
982
+ }
983
+ },
984
+ date: {
985
+ /** Adds a validator that rejects dates in the future */
986
+ pastOnly(this: DateSchemaBuilder) {
987
+ return this.addValidator((val) => {
988
+ const valid = (val as Date) <= new Date();
989
+ return {
990
+ valid,
991
+ errors: valid ? [] : [{ message: 'Date must be in the past' }]
992
+ };
993
+ });
994
+ }
995
+ }
996
+ });
997
+ ```
998
+
999
+ ### Extension Metadata & Introspection
1000
+
1001
+ Extension methods automatically record metadata that can be inspected at runtime via `.introspect().extensions`. The system auto-infers the metadata value based on the arguments passed to the extension method:
1002
+
1003
+ - **Zero-arg methods** → metadata value is `true`
1004
+ - **Single-arg methods** → metadata value is the argument itself
1005
+ - **Multi-arg methods** → metadata value is the arguments array
1006
+
1007
+ ```typescript
1008
+ const s = withExtensions(emailExt, portExt);
1009
+
1010
+ // Zero-arg method — metadata is `true`
1011
+ const emailSchema = s.string().email();
1012
+ console.log(emailSchema.introspect().extensions.email); // true
1013
+
1014
+ // Single-arg method — metadata is the argument
1015
+ const rangeExt = defineExtension({
1016
+ number: {
1017
+ percentage(this: NumberSchemaBuilder) {
1018
+ return this.min(0).max(100);
1019
+ }
1020
+ }
1021
+ });
1022
+ const s2 = withExtensions(rangeExt);
1023
+ const pctSchema = s2.number().percentage();
1024
+ console.log(pctSchema.introspect().extensions.percentage); // true
1025
+
1026
+ // Multi-arg method — metadata is the arguments array
1027
+ const rangeExt2 = defineExtension({
1028
+ number: {
1029
+ range(this: NumberSchemaBuilder, min: number, max: number) {
1030
+ return this.min(min).max(max);
1031
+ }
1032
+ }
1033
+ });
1034
+ const s3 = withExtensions(rangeExt2);
1035
+ const rangeSchema = s3.number().range(0, 100);
1036
+ console.log(rangeSchema.introspect().extensions.range); // [0, 100]
1037
+ ```
1038
+
1039
+ ### Custom Metadata
1040
+
1041
+ If you need structured metadata (e.g. an object with named fields rather than the raw arguments), call `this.withExtension(key, value)` explicitly inside the method. The auto-infer logic detects the existing key and skips automatic attachment:
1042
+
1043
+ ```typescript
1044
+ const currencyExt = defineExtension({
1045
+ number: {
1046
+ currency(this: NumberSchemaBuilder, opts?: { maxDecimals?: number }) {
1047
+ const maxDec = opts?.maxDecimals ?? 2;
1048
+ // Explicit withExtension() call — auto-infer is skipped
1049
+ return this
1050
+ .withExtension('currency', { maxDecimals: maxDec })
1051
+ .min(0)
1052
+ .addValidator((val) => {
1053
+ const decimals = (String(val).split('.')[1] ?? '').length;
1054
+ const valid = decimals <= maxDec;
1055
+ return {
1056
+ valid,
1057
+ errors: valid
1058
+ ? []
1059
+ : [{ message: `Max ${maxDec} decimal places` }]
1060
+ };
1061
+ });
1062
+ }
1063
+ }
1064
+ });
1065
+
1066
+ const s = withExtensions(currencyExt);
1067
+ const priceSchema = s.number().currency({ maxDecimals: 4 });
1068
+ console.log(priceSchema.introspect().extensions.currency);
1069
+ // { maxDecimals: 4 } — structured metadata, not the raw args
1070
+ ```
1071
+
1072
+ ### Stacking Extensions
1073
+
1074
+ Multiple extensions can be stacked — their methods are merged per builder type. A runtime error is thrown if two extensions define the same method name on the same builder type:
1075
+
1076
+ ```typescript
1077
+ // All three extensions target StringSchemaBuilder
1078
+ const s = withExtensions(emailExt, slugExt, trimmedExt);
1079
+
1080
+ // All methods are available and chainable
1081
+ const schema = s.string().email().slug().trimmed().minLength(5);
1082
+ ```
1083
+
1084
+ ### Validation
1085
+
1086
+ `defineExtension()` validates the configuration eagerly:
1087
+
1088
+ - **Unknown builder type names** throw immediately (e.g. `{ str: { ... } }` instead of `{ string: { ... } }`)
1089
+ - **Reserved method names** cannot be overridden — `validate`, `introspect`, `optional`, `required`, `addValidator`, `addPreprocessor`, `withExtension`, `getExtension`, etc.
1090
+ - **Non-function values** in the method record are rejected
1091
+
1092
+ ```typescript
1093
+ // ❌ Throws: Unknown builder type "str"
1094
+ defineExtension({ str: { foo() { return this; } } });
1095
+
1096
+ // ❌ Throws: Cannot override reserved method "validate"
1097
+ defineExtension({ string: { validate() { return this; } } });
1098
+ ```
1099
+
1100
+ ### Extension API Reference
1101
+
1102
+ | Function / Type | Description |
1103
+ | ------------------------------ | -------------------------------------------------------------------------------------------------------- |
1104
+ | `defineExtension(config)` | Defines an extension. `config` is an `ExtensionConfig` keyed by builder type name. Returns an `ExtensionDescriptor`. |
1105
+ | `withExtensions(...exts)` | Accepts one or more `ExtensionDescriptor`s. Returns an object with augmented factory functions (`string`, `number`, `boolean`, `date`, `object`, `array`, `union`, `func`, `any`). |
1106
+ | `ExtensionConfig` | Type for the configuration object passed to `defineExtension`. Maps builder type names to method records. |
1107
+ | `ExtensionDescriptor` | Branded type returned by `defineExtension`. Pass to `withExtensions()` to apply. |
1108
+
1109
+ ## Built-in Extensions
1110
+
1111
+ [▶ Open in Playground](https://docs.cleverbrush.com/playground/builtin-extensions)
1112
+
1113
+ The default import from `@cleverbrush/schema` includes a pre-applied extension pack with common validators. You get these methods automatically — no extra setup required:
1114
+
1115
+ ### String Extensions
1116
+
1117
+ | Method | Description | Metadata |
1118
+ | --- | --- | --- |
1119
+ | `.email(errorMessage?)` | Validates email format | `true` |
1120
+ | `.url(opts?, errorMessage?)` | Validates URL format. `opts.protocols` narrows allowed schemes (default: `http`, `https`) | `true` or `{ protocols }` |
1121
+ | `.uuid(errorMessage?)` | Validates RFC 4122 UUID format (versions 1–5) | `true` |
1122
+ | `.ip(opts?, errorMessage?)` | Validates IPv4 or IPv6 address. `opts.version` narrows to `'v4'` or `'v6'` | `true` or `{ version }` |
1123
+ | `.trim()` | Preprocessor — trims whitespace before validation | `true` |
1124
+ | `.toLowerCase()` | Preprocessor — lowercases value before validation | `true` |
1125
+ | `.nonempty(errorMessage?)` | Rejects empty strings | `true` |
1126
+
1127
+ ### Number Extensions
1128
+
1129
+ | Method | Description | Metadata |
1130
+ | --- | --- | --- |
1131
+ | `.positive(errorMessage?)` | Value must be > 0 | `true` |
1132
+ | `.negative(errorMessage?)` | Value must be < 0 | `true` |
1133
+ | `.finite(errorMessage?)` | Value must be finite (not `Infinity` / `-Infinity`) | `true` |
1134
+ | `.multipleOf(n, errorMessage?)` | Value must be an exact multiple of `n` (float-safe) | `n` |
1135
+
1136
+ ### Array Extensions
1137
+
1138
+ | Method | Description | Metadata |
1139
+ | --- | --- | --- |
1140
+ | `.nonempty(errorMessage?)` | Array must have at least one element | `true` |
1141
+ | `.unique(keyFn?, errorMessage?)` | All elements must be unique. Optional `keyFn` extracts comparison key for objects | `true` or `keyFn` |
1142
+
1143
+ ### Nullable / Not Nullable
1144
+
1145
+ `.nullable()` and `.notNullable()` are **native methods** available on every builder — no extension required.
1146
+
1147
+ | Method | Available on | Description |
1148
+ | --- | --- | --- |
1149
+ | `.nullable()` | all builders | Marks the schema as nullable — `null` is accepted as a valid value. The inferred type changes from `T` to `T \| null`. |
1150
+ | `.notNullable()` | all builders | Removes the nullable mark — `null` is no longer accepted. The inferred type changes from `T \| null` back to `T`. |
1151
+
1152
+ ```typescript
1153
+ import { string, number, object, InferType } from '@cleverbrush/schema';
1154
+
1155
+ const name = string().nullable();
1156
+ type Name = InferType<typeof name>; // string | null
1157
+
1158
+ // Works with any builder
1159
+ const score = number().positive().nullable(); // number | null
1160
+
1161
+ // Chaining: validators before .nullable()
1162
+ const email = string().email().nullable(); // string | null
1163
+
1164
+ // Optional + nullable: accepts string | null | undefined
1165
+ const bio = string().optional().nullable();
1166
+
1167
+ // Nested inside objects
1168
+ const User = object({
1169
+ name: string().nonempty(),
1170
+ bio: string().nullable(), // string | null
1171
+ age: number().nullable(), // number | null
1172
+ });
1173
+
1174
+ User.validate({ name: 'Alice', bio: null, age: null }); // valid
1175
+
1176
+ // Toggle back with .notNullable()
1177
+ const strictName = string().nullable().notNullable();
1178
+ type StrictName = InferType<typeof strictName>; // string (not string | null)
1179
+
1180
+ strictName.validate(null); // invalid
1181
+ strictName.validate('Alice'); // valid
1182
+
1183
+ // Introspect at runtime
1184
+ string().nullable().introspect().isNullable; // true
1185
+ string().nullable().notNullable().introspect().isNullable; // false
1186
+ ```
1187
+
1188
+ ### Enum / oneOf Extension
1189
+
1190
+ | Method | Available on | Description |
1191
+ | --- | --- | --- |
1192
+ | `.oneOf(...values)` | `string`, `number` | Constrains the value to one of the given literals and **narrows the inferred type** to the literal union. |
1193
+ | `.oneOf(valuesArray, errorMessage?)` | `string`, `number` | Array-form with an optional custom error message (string or factory). |
1194
+ | `enumOf(...values)` | top-level factory | Sugar for `string().oneOf(...)`. Mirrors Zod's `z.enum()`. |
1195
+ | `enumOf(valuesArray, errorMessage?)` | top-level factory | Array-form with an optional custom error message. |
1196
+
1197
+ ```typescript
1198
+ import { string, number, enumOf, InferType } from '@cleverbrush/schema';
1199
+
1200
+ // String enum — infers 'admin' | 'user' | 'guest'
1201
+ const Role = enumOf('admin', 'user', 'guest');
1202
+ type Role = InferType<typeof Role>;
1203
+
1204
+ Role.validate('admin'); // valid
1205
+ Role.validate('other'); // invalid — "must be one of: admin, user, guest"
1206
+
1207
+ // Equivalent long-form
1208
+ const Role2 = string().oneOf('admin', 'user', 'guest');
1209
+
1210
+ // Number enum — infers 1 | 2 | 3
1211
+ const Priority = number().oneOf(1, 2, 3);
1212
+ type Priority = InferType<typeof Priority>;
1213
+
1214
+ // Chains with nullable / optional
1215
+ const OptionalRole = enumOf('admin', 'user').nullable(); // 'admin' | 'user' | null
1216
+
1217
+ // Runtime access to allowed values via introspect
1218
+ Role.introspect().extensions?.oneOf; // ['admin', 'user', 'guest']
1219
+ ```
1220
+
1221
+ #### Custom error messages for `.oneOf()`
1222
+
1223
+ `.oneOf()` accepts a custom error message via the **array form**, where the allowed values are passed as an array and the error message is the second argument:
1224
+
1225
+ ```typescript
1226
+ import { string, number, enumOf } from '@cleverbrush/schema';
1227
+
1228
+ // String — array form with custom string error message
1229
+ const role = string().oneOf(['admin', 'user', 'guest'], 'Invalid role');
1230
+ role.validate('other'); // invalid — "Invalid role"
1231
+
1232
+ // String — array form with factory function
1233
+ const role2 = string().oneOf(
1234
+ ['admin', 'user'],
1235
+ (val) => `"${val}" is not a valid role`
1236
+ );
1237
+
1238
+ // enumOf — array form with custom error message
1239
+ const Role = enumOf(['admin', 'user', 'guest'], 'Invalid role');
1240
+
1241
+ // Number — trailing error message (unambiguous since values are numbers)
1242
+ const priority = number().oneOf(1, 2, 3, 'Priority must be 1, 2, or 3');
1243
+ priority.validate(99); // invalid — "Priority must be 1, 2, or 3"
1244
+
1245
+ // Number — array form
1246
+ const priority2 = number().oneOf([1, 2, 3], 'Invalid priority');
1247
+
1248
+ // Number — factory function
1249
+ const priority3 = number().oneOf(
1250
+ 1, 2, 3,
1251
+ (val) => `${val} is not a valid priority`
1252
+ );
1253
+ ```
1254
+
1255
+ > **Note on string `.oneOf()` error messages:** Because `.oneOf()` accepts a variadic list of string values, a trailing string argument is treated as another allowed value (not an error message). To provide a string error message for a string enum, use the **array form** — `string().oneOf(['a', 'b'], 'error message')`. A trailing *function* is always unambiguously treated as an error message factory in the rest-params form.
1256
+
1257
+ All validator extensions accept an optional error message as the last parameter — either a string or a function (matching the same `ValidationErrorMessageProvider` pattern used by built-in constraints like `.minLength()`):
1258
+
1259
+ ```typescript
1260
+ import { string, number, array } from '@cleverbrush/schema';
1261
+
1262
+ // String error messages
1263
+ const email = string().email('Please enter a valid email');
1264
+ const age = number().positive('Age must be positive');
1265
+ const tags = array().of(string()).nonempty('At least one tag required');
1266
+
1267
+ // Function error messages — receive the invalid value
1268
+ const name = string().nonempty((val) => `"${val}" is not allowed`);
1269
+ const score = number().multipleOf(5, (val) => `${val} is not a multiple of 5`);
1270
+ ```
1271
+
1272
+ ### The `/core` Sub-path
1273
+
1274
+ If you need bare builders **without** the built-in extensions (e.g. to apply only your own custom extensions), import from the `/core` sub-path:
1275
+
1276
+ ```typescript
1277
+ // Bare builders — no built-in extensions
1278
+ import { string, number, array, withExtensions } from '@cleverbrush/schema/core';
1279
+
1280
+ // Apply only your own extensions
1281
+ const s = withExtensions(myCustomExtension);
1282
+ ```
1283
+
1284
+ The default import (`@cleverbrush/schema`) re-exports everything from `/core` and overrides the nine factory functions (`string`, `number`, `boolean`, `date`, `object`, `array`, `union`, `func`, `any`) with pre-extended versions. The extension descriptors themselves are also exported (`stringExtensions`, `numberExtensions`, `arrayExtensions`, `nullableExtension`) so you can compose them with your own.
1285
+
1286
+ ## Part of the Cleverbrush Ecosystem
1287
+
1288
+ `@cleverbrush/schema` is the foundation of a three-library ecosystem:
1289
+
1290
+ ```
1291
+ @cleverbrush/schema → Define once
1292
+ ↓ ↓ ↓
1293
+ Validate data Map between schemas Render React forms
1294
+ ↓ ↓ ↓
1295
+ .validate() @cleverbrush/mapper @cleverbrush/react-form
1296
+ ```
1297
+
1298
+ Define a schema once and use it for runtime validation, object mapping between different shapes, and type-safe React forms — all from a single source of truth.
1299
+
1300
+ ## Exports
1301
+
1302
+ **Builder functions:** `any`, `lazy`, `string`, `number`, `boolean`, `func`, `object`, `date`, `array`, `union`
1303
+
1304
+ **Builder classes** (for extending): `SchemaBuilder`, `AnySchemaBuilder`, `ArraySchemaBuilder`, `BooleanSchemaBuilder`, `DateSchemaBuilder`, `FunctionSchemaBuilder`, `LazySchemaBuilder`, `NumberSchemaBuilder`, `ObjectSchemaBuilder`, `StringSchemaBuilder`, `UnionSchemaBuilder`
1305
+
1306
+ **Extension system:** `defineExtension`, `withExtensions`, `stringExtensions`, `numberExtensions`, `arrayExtensions`, `nullableExtension`
1307
+
1308
+ **Sub-path exports:** `@cleverbrush/schema/core` — bare builders without built-in extensions
1309
+
1310
+ **Types:** `InferType`, `ValidationResult`, `ValidationError`, `MakeOptional`, `SchemaPropertySelector`, `PropertyDescriptor`, `PropertyDescriptorTree`, `ExtensionConfig`, `ExtensionDescriptor`
1311
+
1312
+ See [API documentation](https://docs.cleverbrush.com/) for the full reference.
1313
+
1314
+ ## Performance
1315
+
1316
+ Benchmarked against Zod v4 with [Vitest bench](https://vitest.dev/guide/features.html#benchmarking). Run the benchmarks yourself from the repo root: `npm run bench`.
1317
+
1318
+ | Benchmark | @cleverbrush/schema | Zod | Ratio |
1319
+ | --- | --- | --- | --- |
1320
+ | Array 100 objects — valid | 35,228 ops/s | 13,277 ops/s | **2.65× faster** |
1321
+ | Array 100 objects — invalid | 899,329 ops/s | 4,396 ops/s | **204× faster** |
1322
+ | Complex order — valid | 198,988 ops/s | 136,090 ops/s | **1.46× faster** |
1323
+ | Complex order — invalid | 884,706 ops/s | 26,106 ops/s | **33.9× faster** |
1324
+ | Flat object — valid | 1,001,194 ops/s | 840,725 ops/s | **1.19× faster** |
1325
+ | Flat object — invalid | 2,653,630 ops/s | 176,222 ops/s | **15.1× faster** |
1326
+ | Nested object — valid | 690,556 ops/s | 368,893 ops/s | **1.87× faster** |
1327
+ | Nested object — invalid | 2,739,319 ops/s | 87,245 ops/s | **31.4× faster** |
1328
+ | String — valid | 5,348,564 ops/s | 3,533,945 ops/s | **1.51× faster** |
1329
+ | String — invalid | 5,749,087 ops/s | 482,961 ops/s | **11.9× faster** |
1330
+ | Number — valid | 7,911,266 ops/s | 4,806,511 ops/s | **1.65× faster** |
1331
+ | Number — invalid | 5,387,475 ops/s | 637,513 ops/s | **8.45× faster** |
1332
+ | Union first branch | 1,925,508 ops/s | 1,529,547 ops/s | **1.26× faster** |
1333
+ | Union last branch | 676,107 ops/s | 732,682 ops/s | 0.92× |
1334
+ | Union no match — invalid | 5,873,118 ops/s | 385,453 ops/s | **15.2× faster** |
1335
+
1336
+ The large gains on invalid data come from the early-exit optimization: validation stops at the first failing constraint in each field and skips the rest of the object. For APIs and form handlers where invalid submissions are common, this translates directly to measurable throughput improvements.
1337
+
1338
+ ## External Schema Interop (`extern()`)
1339
+
1340
+ Already using Zod, Valibot, or ArkType? The `extern()` factory wraps any [Standard Schema v1](https://standardschema.dev/) compatible schema into a `@cleverbrush/schema` builder — so you can mix external schemas with native ones inside an `object()` without rewriting anything.
1341
+
1342
+ ```ts
1343
+ import { z } from 'zod';
1344
+ import { object, number, extern, InferType } from '@cleverbrush/schema';
1345
+
1346
+ // Existing Zod schema — keep as-is
1347
+ const ZodAddress = z.object({
1348
+ street: z.string().min(1),
1349
+ city: z.string(),
1350
+ zip: z.string().length(5),
1351
+ });
1352
+
1353
+ // Compose with @cleverbrush/schema
1354
+ const OrderSchema = object({
1355
+ address: extern(ZodAddress),
1356
+ totalCents: number().min(1),
1357
+ });
1358
+
1359
+ // Type is inferred from *both* libraries:
1360
+ type Order = InferType<typeof OrderSchema>;
1361
+ // { address: { street: string; city: string; zip: string }; totalCents: number }
1362
+
1363
+ const result = OrderSchema.validate({
1364
+ address: { street: '5th Ave', city: 'NYC', zip: '10001' },
1365
+ totalCents: 4999,
1366
+ });
1367
+
1368
+ if (!result.valid) {
1369
+ // Navigate into the extern property — no type annotation needed
1370
+ const zipErrors = result.getErrorsFor(t => t.address.zip);
1371
+ console.log(zipErrors.errors);
1372
+ }
1373
+ ```
1374
+
1375
+ Key points:
1376
+ - **One parameter:** `extern(standardSchema)` — types and property descriptors are derived automatically.
1377
+ - **getErrorsFor()** works through extern boundaries: `t => t.address.city` navigates into the Zod schema.
1378
+ - **Validation** is delegated to the external schema’s `['~standard'].validate()` — @cleverbrush/schema never re-implements the external library’s validation logic.
1379
+ - Works with any library that implements Standard Schema v1 (Zod ≥ 3.24, Valibot ≥ 1.0, ArkType, etc.).
1380
+
1381
+ ## Standard Schema Interoperability
1382
+
1383
+ `@cleverbrush/schema` implements [Standard Schema v1](https://standardschema.dev/). Every builder exposes a `['~standard']` getter, which means schemas work as-is with any Standard Schema consumer — no adapters, no wrappers, no configuration:
1384
+
1385
+ ```ts
1386
+ import { object, string, number } from '@cleverbrush/schema';
1387
+
1388
+ const UserSchema = object({
1389
+ name: string().nonempty(),
1390
+ age: number().min(18),
1391
+ });
1392
+
1393
+ // Works with tRPC, TanStack Form, React Hook Form, T3 Env, Hono, Elysia, …
1394
+ const standardSchema = UserSchema['~standard'];
1395
+ ```
1396
+
1397
+ Confirmed integrations: **tRPC**, **TanStack Form**, **React Hook Form**, **T3 Env**, **Hono**, **Elysia**, **next-safe-action**, and 50+ others listed on [standardschema.dev](https://standardschema.dev/).
1398
+
1399
+ ## Code Quality
1400
+
1401
+ - **Linting:** [Biome](https://biomejs.dev/) — strict rules enforced on every PR via CI
1402
+ - **Type checking:** TypeScript strict mode (`strictNullChecks`, `noImplicitAny`, full coverage)
1403
+ - **Unit tests:** [Vitest](https://vitest.dev/) — runtime tests + type-level tests (`expectTypeOf`) covering all builders, extensions, edge cases, and error paths
1404
+ - **Type-level tests:** `expectTypeOf` assertions validate that inferred types are exactly correct, not just assignable
1405
+ - **CI:** Every pull request must pass lint + build + test before merge — see [`.github/workflows/ci.yml`](../../.github/workflows/ci.yml)
1406
+
1407
+ ## License
1408
+
1409
+ BSD-3-Clause