@cleverbrush/schema 4.4.3 → 5.0.0

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 (110) hide show
  1. package/LICENSE +28 -0
  2. package/README.md +176 -19
  3. package/dist/builders/AnySchemaBuilder.d.ts +11 -2
  4. package/dist/builders/AnySchemaBuilder.js +1 -1
  5. package/dist/builders/ArraySchemaBuilder.d.ts +15 -4
  6. package/dist/builders/ArraySchemaBuilder.js +1 -1
  7. package/dist/builders/BooleanSchemaBuilder.d.ts +21 -6
  8. package/dist/builders/BooleanSchemaBuilder.js +1 -1
  9. package/dist/builders/DateSchemaBuilder.d.ts +24 -10
  10. package/dist/builders/DateSchemaBuilder.js +1 -1
  11. package/dist/builders/ExternSchemaBuilder.d.ts +3 -2
  12. package/dist/builders/ExternSchemaBuilder.js +1 -1
  13. package/dist/builders/FunctionSchemaBuilder.d.ts +14 -2
  14. package/dist/builders/FunctionSchemaBuilder.js +1 -1
  15. package/dist/builders/GenericSchemaBuilder.d.ts +14 -3
  16. package/dist/builders/IntersectionSchemaBuilder.d.ts +1 -0
  17. package/dist/builders/LazySchemaBuilder.d.ts +1 -0
  18. package/dist/builders/NullSchemaBuilder.d.ts +2 -4
  19. package/dist/builders/NumberSchemaBuilder.d.ts +21 -7
  20. package/dist/builders/NumberSchemaBuilder.js +1 -1
  21. package/dist/builders/ObjectSchemaBuilder.d.ts +15 -4
  22. package/dist/builders/ObjectSchemaBuilder.js +1 -1
  23. package/dist/builders/ParseStringSchemaBuilder.d.ts +1 -0
  24. package/dist/builders/ParseStringSchemaBuilder.js +1 -1
  25. package/dist/builders/PromiseSchemaBuilder.d.ts +13 -2
  26. package/dist/builders/PromiseSchemaBuilder.js +1 -1
  27. package/dist/builders/RecordSchemaBuilder.d.ts +12 -0
  28. package/dist/builders/RecordSchemaBuilder.js +1 -1
  29. package/dist/builders/SchemaBuilder.d.ts +59 -10
  30. package/dist/builders/StringSchemaBuilder.d.ts +23 -8
  31. package/dist/builders/StringSchemaBuilder.js +1 -1
  32. package/dist/builders/TupleSchemaBuilder.d.ts +16 -4
  33. package/dist/builders/TupleSchemaBuilder.js +1 -1
  34. package/dist/builders/UnionSchemaBuilder.d.ts +12 -2
  35. package/dist/builders/UnionSchemaBuilder.js +1 -1
  36. package/dist/chunk-25KL2NBJ.js +2 -0
  37. package/dist/chunk-25KL2NBJ.js.map +1 -0
  38. package/dist/chunk-2BKBVVZ3.js +2 -0
  39. package/dist/chunk-2BKBVVZ3.js.map +1 -0
  40. package/dist/chunk-3E5M6GRR.js +2 -0
  41. package/dist/chunk-3E5M6GRR.js.map +1 -0
  42. package/dist/chunk-66U6MMJ2.js +2 -0
  43. package/dist/chunk-66U6MMJ2.js.map +1 -0
  44. package/dist/chunk-BMA2X7LI.js +2 -0
  45. package/dist/chunk-BMA2X7LI.js.map +1 -0
  46. package/dist/chunk-BTR3ZGES.js +2 -0
  47. package/dist/chunk-BTR3ZGES.js.map +1 -0
  48. package/dist/chunk-CR2QIV5I.js +2 -0
  49. package/dist/chunk-CR2QIV5I.js.map +1 -0
  50. package/dist/chunk-D7RXO2FA.js +2 -0
  51. package/dist/chunk-D7RXO2FA.js.map +1 -0
  52. package/dist/chunk-JEBLDVKG.js +2 -0
  53. package/dist/chunk-JEBLDVKG.js.map +1 -0
  54. package/dist/chunk-JH7VLA6C.js +2 -0
  55. package/dist/chunk-JH7VLA6C.js.map +1 -0
  56. package/dist/chunk-K7TDPKGQ.js +2 -0
  57. package/dist/chunk-K7TDPKGQ.js.map +1 -0
  58. package/dist/chunk-NDESVCWI.js +2 -0
  59. package/dist/chunk-NDESVCWI.js.map +1 -0
  60. package/dist/chunk-VBPZRO7L.js +2 -0
  61. package/dist/chunk-VBPZRO7L.js.map +1 -0
  62. package/dist/chunk-W5D22D4P.js +2 -0
  63. package/dist/chunk-W5D22D4P.js.map +1 -0
  64. package/dist/{chunk-XHSBY2QK.js → chunk-X6CT6I2V.js} +2 -2
  65. package/dist/{chunk-XHSBY2QK.js.map → chunk-X6CT6I2V.js.map} +1 -1
  66. package/dist/chunk-XASMTNON.js +2 -0
  67. package/dist/chunk-XASMTNON.js.map +1 -0
  68. package/dist/chunk-ZYWDTLNL.js +2 -0
  69. package/dist/chunk-ZYWDTLNL.js.map +1 -0
  70. package/dist/core.d.ts +3 -3
  71. package/dist/core.js +1 -1
  72. package/dist/extension.d.ts +4 -1
  73. package/dist/extension.js +1 -1
  74. package/dist/extensions/string.d.ts +2 -4
  75. package/dist/index.js +1 -1
  76. package/dist/index.js.map +1 -1
  77. package/dist/metadata-extension.d.ts +196 -0
  78. package/package.json +6 -3
  79. package/dist/chunk-54RHS4F4.js +0 -2
  80. package/dist/chunk-54RHS4F4.js.map +0 -1
  81. package/dist/chunk-6LSN7NXQ.js +0 -2
  82. package/dist/chunk-6LSN7NXQ.js.map +0 -1
  83. package/dist/chunk-C6YQOKWB.js +0 -2
  84. package/dist/chunk-C6YQOKWB.js.map +0 -1
  85. package/dist/chunk-ELPPAHNO.js +0 -2
  86. package/dist/chunk-ELPPAHNO.js.map +0 -1
  87. package/dist/chunk-G424M7GI.js +0 -2
  88. package/dist/chunk-G424M7GI.js.map +0 -1
  89. package/dist/chunk-JUFZ7PLO.js +0 -2
  90. package/dist/chunk-JUFZ7PLO.js.map +0 -1
  91. package/dist/chunk-K4ZLXLE2.js +0 -2
  92. package/dist/chunk-K4ZLXLE2.js.map +0 -1
  93. package/dist/chunk-KC45JEFL.js +0 -2
  94. package/dist/chunk-KC45JEFL.js.map +0 -1
  95. package/dist/chunk-NF4CRFMN.js +0 -2
  96. package/dist/chunk-NF4CRFMN.js.map +0 -1
  97. package/dist/chunk-ORV2G6ZL.js +0 -2
  98. package/dist/chunk-ORV2G6ZL.js.map +0 -1
  99. package/dist/chunk-PQINUGZW.js +0 -2
  100. package/dist/chunk-PQINUGZW.js.map +0 -1
  101. package/dist/chunk-REYZ7G7J.js +0 -2
  102. package/dist/chunk-REYZ7G7J.js.map +0 -1
  103. package/dist/chunk-VSU5GILY.js +0 -2
  104. package/dist/chunk-VSU5GILY.js.map +0 -1
  105. package/dist/chunk-XL723XFL.js +0 -2
  106. package/dist/chunk-XL723XFL.js.map +0 -1
  107. package/dist/chunk-XPLTW5DI.js +0 -2
  108. package/dist/chunk-XPLTW5DI.js.map +0 -1
  109. package/dist/chunk-YAOZEA2R.js +0 -2
  110. package/dist/chunk-YAOZEA2R.js.map +0 -1
@@ -0,0 +1,196 @@
1
+ import type { AnySchemaBuilder } from './builders/AnySchemaBuilder.js';
2
+ import type { ArraySchemaBuilder } from './builders/ArraySchemaBuilder.js';
3
+ import type { BooleanSchemaBuilder } from './builders/BooleanSchemaBuilder.js';
4
+ import type { DateSchemaBuilder } from './builders/DateSchemaBuilder.js';
5
+ import type { FunctionSchemaBuilder } from './builders/FunctionSchemaBuilder.js';
6
+ import type { GenericSchemaBuilder } from './builders/GenericSchemaBuilder.js';
7
+ import type { NumberSchemaBuilder } from './builders/NumberSchemaBuilder.js';
8
+ import type { ObjectSchemaBuilder } from './builders/ObjectSchemaBuilder.js';
9
+ import type { PromiseSchemaBuilder } from './builders/PromiseSchemaBuilder.js';
10
+ import type { RecordSchemaBuilder } from './builders/RecordSchemaBuilder.js';
11
+ import type { PropertyDescriptorTree, SchemaBuilder } from './builders/SchemaBuilder.js';
12
+ import type { StringSchemaBuilder } from './builders/StringSchemaBuilder.js';
13
+ import type { TupleSchemaBuilder } from './builders/TupleSchemaBuilder.js';
14
+ import type { UnionSchemaBuilder } from './builders/UnionSchemaBuilder.js';
15
+ import type { EXTRA_TYPE_BRAND, HiddenExtensionMethods, METHOD_LITERAL_BRAND } from './extension.js';
16
+ /** @internal Metadata helpers own their key, including explicitly undefined values. */
17
+ export declare function isMetadataMethod(method: Function): boolean;
18
+ /** Metadata recorded by typed extension methods; unannotated builders yield `{}`. */
19
+ export type InferExtensionMetadata<S> = S extends {
20
+ readonly __cleverbrush_extension_metadata__: infer M;
21
+ } ? M : {};
22
+ /** @internal Description carried on a metadata method's type, not on schemas. */
23
+ export type MetadataMethod<K extends string, A extends any[], V, Mode> = ((this: SchemaBuilder<any, any, any, any, any>, ...args: A) => SchemaBuilder<any, any, any, any, any>) & {
24
+ readonly __cleverbrush_metadata_method__: {
25
+ key: K;
26
+ value: V;
27
+ mode: Mode;
28
+ };
29
+ };
30
+ /** Defines the source of a typed metadata value for an extension method. */
31
+ export interface MetadataMethodBuilder<K extends string> {
32
+ /** Store the caller's argument, retaining its literal type. */
33
+ argument<TValue = unknown>(): MetadataMethod<K, [
34
+ value: TValue
35
+ ], TValue, 'argument'>;
36
+ /** Create a zero-argument method that stores a fixed value. */
37
+ value<const TValue>(value: TValue): MetadataMethod<K, [], TValue, 'value'>;
38
+ /** Compute metadata from typed arguments; inference uses the callback's return type. */
39
+ compute<TArgs extends any[], TValue>(compute: (...args: TArgs) => TValue): MetadataMethod<K, TArgs, TValue, 'computed'>;
40
+ }
41
+ /**
42
+ * Define an immutable metadata-only method for use inside `defineExtension()`.
43
+ *
44
+ * Unlike ordinary extension methods, its stored value is also available through
45
+ * `InferExtensionMetadata<S>`. Repeated writes replace the value for that key.
46
+ * The method does not validate input or change the schema's inferred value type.
47
+ * Methods are installed only on factories returned by `withExtensions()`.
48
+ *
49
+ * @param key - Runtime introspection key, independent of the fluent method name.
50
+ * @example
51
+ * ```ts
52
+ * const labels = defineExtension({
53
+ * string: {
54
+ * label: defineMetadataMethod('label').argument<string>(),
55
+ * internal: defineMetadataMethod('visibility').value('internal')
56
+ * }
57
+ * });
58
+ * const s = withExtensions(labels).string().label('Title').optional();
59
+ * type Label = InferExtensionMetadata<typeof s>['label']; // 'Title'
60
+ * ```
61
+ */
62
+ export declare function defineMetadataMethod<const K extends string>(key: K): MetadataMethodBuilder<K>;
63
+ /** @internal Rebuild a native builder with new extension state, preserving its value flags. */
64
+ type WithExtensions<S, E> = S extends {
65
+ readonly __cleverbrush_builder_type__: infer P;
66
+ } ? P extends readonly [
67
+ 'number',
68
+ infer T,
69
+ infer R extends boolean,
70
+ infer N extends boolean,
71
+ infer D extends boolean
72
+ ] ? NumberSchemaBuilder<T, R, N, D, E> : P extends readonly [
73
+ 'string',
74
+ infer T,
75
+ infer R extends boolean,
76
+ infer N extends boolean,
77
+ infer D extends boolean
78
+ ] ? StringSchemaBuilder<T, R, N, D, E> : P extends readonly [
79
+ 'date',
80
+ infer T,
81
+ infer R extends boolean,
82
+ infer N extends boolean,
83
+ infer D extends boolean
84
+ ] ? DateSchemaBuilder<T, R, N, D, E> : P extends readonly [
85
+ 'object',
86
+ infer P extends Record<string, SchemaBuilder<any, any, any, any, any>>,
87
+ infer R extends boolean,
88
+ infer N extends boolean,
89
+ infer T,
90
+ infer D extends boolean,
91
+ infer C extends SchemaBuilder<any, any, any, any, any>[]
92
+ ] ? ObjectSchemaBuilder<P, R, N, T, D, E, C> : P extends readonly [
93
+ 'array',
94
+ infer P extends SchemaBuilder<any, any, any, any, any>,
95
+ infer R extends boolean,
96
+ infer N extends boolean,
97
+ infer T,
98
+ infer D extends boolean,
99
+ infer V
100
+ ] ? ArraySchemaBuilder<P, R, N, T, D, E, V> : P extends readonly [
101
+ 'boolean',
102
+ infer T,
103
+ infer R extends boolean,
104
+ infer N extends boolean,
105
+ infer X,
106
+ infer D extends boolean,
107
+ infer V
108
+ ] ? BooleanSchemaBuilder<T, R, N, X, D, E, V> : P extends readonly [
109
+ 'tuple',
110
+ infer P extends readonly SchemaBuilder<any, any, any, any, any>[],
111
+ infer R extends boolean,
112
+ infer N extends boolean,
113
+ infer T,
114
+ infer D extends boolean,
115
+ infer Rest extends SchemaBuilder<any, any, any, any, any> | undefined,
116
+ infer V
117
+ ] ? TupleSchemaBuilder<P, R, N, T, D, E, Rest, V> : P extends readonly [
118
+ 'record',
119
+ infer K extends StringSchemaBuilder<any, any, any, any>,
120
+ infer P extends SchemaBuilder<any, any, any, any, any>,
121
+ infer R extends boolean,
122
+ infer N extends boolean,
123
+ infer T,
124
+ infer D extends boolean,
125
+ infer V
126
+ ] ? RecordSchemaBuilder<K, P, R, N, T, D, E, V> : P extends readonly [
127
+ 'union',
128
+ infer P extends readonly SchemaBuilder<any, any, any, any, any>[],
129
+ infer R extends boolean,
130
+ infer N extends boolean,
131
+ infer T,
132
+ infer D extends boolean
133
+ ] ? UnionSchemaBuilder<P, R, N, T, D, E> : P extends readonly [
134
+ 'func',
135
+ infer R extends boolean,
136
+ infer N extends boolean,
137
+ infer T,
138
+ infer D extends boolean,
139
+ infer P extends SchemaBuilder<any, any, any, any, any>[],
140
+ infer Return extends SchemaBuilder<any, any, any, any, any> | undefined,
141
+ infer V
142
+ ] ? FunctionSchemaBuilder<R, N, T, D, E, P, Return, V> : P extends readonly [
143
+ 'promise',
144
+ infer R extends boolean,
145
+ infer N extends boolean,
146
+ infer T,
147
+ infer D extends boolean,
148
+ infer P extends SchemaBuilder<any, any, any, any, any> | undefined,
149
+ infer V
150
+ ] ? PromiseSchemaBuilder<R, N, T, D, E, P, V> : P extends readonly [
151
+ 'generic',
152
+ infer F extends (...args: any[]) => SchemaBuilder<any, any, any, any, any>,
153
+ infer R extends boolean,
154
+ infer N extends boolean,
155
+ infer T,
156
+ infer D extends boolean,
157
+ infer V
158
+ ] ? GenericSchemaBuilder<F, R, N, T, D, E, V> : P extends readonly [
159
+ 'any',
160
+ infer R extends boolean,
161
+ infer N extends boolean,
162
+ infer T,
163
+ infer D extends boolean,
164
+ infer V
165
+ ] ? AnySchemaBuilder<R, N, T, D, E, V> : never : never;
166
+ /** @internal Named declaration support for metadata-aware fluent builders. */
167
+ export type MetadataState<Methods, Metadata, Extras> = MetadataMethods<Methods> & HiddenExtensionMethods & Extras & {
168
+ readonly __cleverbrush_extension_metadata__: Metadata;
169
+ };
170
+ /** @internal A metadata-aware factory result; state survives native builder modifiers. */
171
+ export type MetadataExtended<S, Methods, Metadata = {}, Extras = ExtraProperties<S, Methods>> = WithExtensions<S, MetadataState<Methods, Metadata, Extras>> & MetadataState<Methods, Metadata, Extras>;
172
+ /** @internal Preserve author-defined type brands without intersecting stale metadata or methods. */
173
+ export type ExtraProperties<S, Methods> = Pick<S, Exclude<keyof S, keyof WithExtensions<S, {}> | keyof Methods | '__cleverbrush_extension_metadata__'>>;
174
+ type ExtraTypes<S> = S extends {
175
+ readonly [EXTRA_TYPE_BRAND]?: infer T;
176
+ } ? T : {};
177
+ type LiteralNames<S> = S extends {
178
+ readonly [METHOD_LITERAL_BRAND]?: infer T;
179
+ } ? T : never;
180
+ type WithBrand<S, Methods, K extends PropertyKey, V> = MetadataExtended<S, Methods, InferExtensionMetadata<S>, Omit<ExtraProperties<S, Methods>, K> & {
181
+ readonly [P in K]?: V;
182
+ }>;
183
+ type SetMetadata<S, Methods, K extends string, V> = MetadataExtended<S, Methods, Omit<InferExtensionMetadata<S>, K> & Record<K, V>>;
184
+ /** Describe fields without recursively inspecting the receiver's fluent methods. */
185
+ type MetadataPropertyTree<S> = S extends {
186
+ readonly __cleverbrush_builder_type__: readonly [
187
+ 'object',
188
+ infer P extends Record<string, SchemaBuilder<any, any, any, any, any>>,
189
+ ...unknown[]
190
+ ];
191
+ } ? PropertyDescriptorTree<ObjectSchemaBuilder<P>, ObjectSchemaBuilder<P>> : never;
192
+ /** @internal Named declaration support for extension method signatures. */
193
+ export type MetadataMethods<Methods> = {
194
+ [M in keyof Methods]: Methods[M] extends MetadataMethod<infer K, infer A, infer V, infer Mode> ? Mode extends 'argument' ? <S, const Value extends A[0]>(this: S, value: Value) => SetMetadata<S, Methods, K, Value> : <S>(this: S, ...args: A) => SetMetadata<S, Methods, K, V> : Methods[M] extends (this: any, ...args: infer A) => infer R ? typeof EXTRA_TYPE_BRAND extends keyof R ? <S, const Name extends string & A[0], const Key extends string>(this: S, name: Name, ...columns: ReadonlyArray<Key | ((t: MetadataPropertyTree<S>) => any)>) => WithBrand<S, Methods, typeof EXTRA_TYPE_BRAND, ExtraTypes<S> & Record<Name, readonly Key[]>> : typeof METHOD_LITERAL_BRAND extends keyof R ? <S, const Name extends string & A[0]>(this: S, name: Name, ...rest: A extends [any, ...infer Rest] ? Rest : []) => WithBrand<S, Methods, typeof METHOD_LITERAL_BRAND, LiteralNames<S> | Name> : <S>(this: S, ...args: A) => S : Methods[M];
195
+ };
196
+ export {};
package/package.json CHANGED
@@ -20,7 +20,7 @@
20
20
  "standard-schema",
21
21
  "cleverbrush"
22
22
  ],
23
- "license": "BSD 3-Clause",
23
+ "license": "BSD-3-Clause",
24
24
  "main": "./dist/index.js",
25
25
  "exports": {
26
26
  ".": {
@@ -94,6 +94,9 @@
94
94
  },
95
95
  "sideEffects": false,
96
96
  "name": "@cleverbrush/schema",
97
+ "engines": {
98
+ "node": ">=24"
99
+ },
97
100
  "readme": "https://github.com/cleverbrush/framework/tree/master/libs/schema#readme",
98
101
  "repository": {
99
102
  "type": "git",
@@ -106,9 +109,9 @@
106
109
  },
107
110
  "type": "module",
108
111
  "types": "./dist/index.d.ts",
109
- "version": "4.4.3",
112
+ "version": "5.0.0",
110
113
  "devDependencies": {
111
- "@cleverbrush/deep": "^4.4.3"
114
+ "@cleverbrush/deep": "^5.0.0"
112
115
  },
113
116
  "peerDependencies": {
114
117
  "@standard-schema/spec": "^1.1.0"
@@ -1,2 +0,0 @@
1
- import{a as P,b as w}from"./chunk-C6YQOKWB.js";import{a as B,b as R}from"./chunk-K4ZLXLE2.js";import{a as S,b}from"./chunk-ELPPAHNO.js";import{a as g,b as F}from"./chunk-6LSN7NXQ.js";import{a as M,b as A}from"./chunk-JUFZ7PLO.js";import{a as N,b as D}from"./chunk-XL723XFL.js";import{a as _,b as v}from"./chunk-ORV2G6ZL.js";import{a as V,b as C}from"./chunk-G424M7GI.js";import{a as c,b as T}from"./chunk-XPLTW5DI.js";import{a as x,b as p}from"./chunk-KC45JEFL.js";import{a as m,b as E}from"./chunk-PQINUGZW.js";import{a as h,b as f}from"./chunk-NF4CRFMN.js";import{f as u}from"./chunk-REYZ7G7J.js";var d=class o extends u{#e;#n;#t;static create(e){return new o({type:"generic",...e})}constructor(e){super(e),this.#e=e.templateFn,this.#n=e.defaults,this.apply=(...n)=>{if(!this.#e)throw new Error("GenericSchemaBuilder: no template function defined");return this.#e(...n)}}introspect(){return{...super.introspect(),templateFn:this.#e,defaults:this.#n}}#a(){if(!(!this.#e||!this.#n))return this.#t||(this.#t=this.#e(...this.#n)),this.#t}#r(e,n){let{valid:r,transaction:s,errors:i}=e;if(!r)return{valid:r,errors:i};let{object:{validatedObject:a}}=s;if(typeof a>"u"&&!this.isRequired||a===null&&(!this.isRequired||this.isNullable))return{valid:!0,object:a};let t=this.#a();return t?t.validate(a,n):{valid:!1,errors:[{message:"This is a generic schema template. Call .apply() with concrete schemas to get a validatable schema, or provide default arguments to generic()."}]}}async#s(e,n){let{valid:r,transaction:s,errors:i}=e;if(!r)return{valid:r,errors:i};let{object:{validatedObject:a}}=s;if(typeof a>"u"&&!this.isRequired||a===null&&(!this.isRequired||this.isNullable))return{valid:!0,object:a};let t=this.#a();return t?await t.validateAsync(a,n):{valid:!1,errors:[{message:"This is a generic schema template. Call .apply() with concrete schemas to get a validatable schema, or provide default arguments to generic()."}]}}validate(e,n){return super.validate(e,n)}async validateAsync(e,n){return super.validateAsync(e,n)}_validate(e,n){return this.#r(this.preValidateSync(e,n),n)}async _validateAsync(e,n){return this.#s(await super.preValidateAsync(e,n),n)}createFromProps(e){return o.create(e)}hasType(e){return this.createFromProps({...this.introspect()})}clearHasType(){return this.createFromProps({...this.introspect()})}required(e){return super.required(e)}optional(){return super.optional()}nullable(){return super.nullable()}notNullable(){return super.notNullable()}default(e){return super.default(e)}clearDefault(){return super.clearDefault()}brand(e){return super.brand(e)}readonly(){return super.readonly()}};function j(o,e){let n=e!==void 0?e:o,r=e!==void 0?o:void 0;return d.create({isRequired:!0,templateFn:n,defaults:r})}var y={string:_,number:S,boolean:m,date:h,object:g,array:x,tuple:V,record:N,union:P,func:B,any:c,promise:M,generic:d},q={string:v,number:b,boolean:E,date:f,object:F,array:p,tuple:C,record:D,union:w,func:R,any:T,promise:A,generic:j},ee="__cleverbrush_method_literal_brand__";var ne="__cleverbrush_extra_type_brand__";var G=new Set(["validate","validateAsync","parse","parseAsync","safeParse","safeParseAsync","introspect","optional","required","addPreprocessor","clearPreprocessors","addValidator","clearValidators","hasType","clearHasType","createFromProps","preValidate","preValidateSync","preValidateAsync","getValidationErrorMessage","getValidationErrorMessageSync","assureValidationErrorMessageProvider","withExtension","getExtension"]);function te(o){let e={};for(let n of Object.keys(o)){if(!(n in y))throw new Error(`Unknown builder type "${n}". Valid types: ${Object.keys(y).join(", ")}`);let r=o[n];if(!r||typeof r!="object")throw new Error(`Extension config for "${n}" must be an object of methods`);e[n]={};for(let s of Object.keys(r)){if(G.has(s))throw new Error(`Cannot override reserved method "${s}" on "${n}"`);let i=r[s];if(typeof i!="function")throw new Error(`Extension method "${n}.${s}" must be a function`);e[n][s]=function(...a){let t=i.apply(this,a);return t&&typeof t=="object"&&typeof t.withExtension=="function"&&(typeof t.getExtension!="function"||t.getExtension(s)===void 0)?t.withExtension(s,a.length===1?a[0]:a.length===0?!0:a):t}}}return{config:e}}function ae(...o){let e=new Map;for(let r of o)for(let s of Object.keys(r.config)){e.has(s)||e.set(s,new Map);let i=e.get(s),a=r.config[s];for(let t of Object.keys(a)){if(i.has(t))throw new Error(`Extension method collision: "${t}" is defined by multiple extensions for "${s}"`);i.set(t,a[t])}}let n={};for(let r of Object.keys(y)){let s=e.get(r);if(!s||s.size===0){n[r]=q[r];continue}let i=y[r],a=class extends i{constructor(...t){super(...t)}static create(t){return new a({...t})}createFromProps(t){return a.create(t)}};for(let[t,l]of s)Object.defineProperty(a.prototype,t,{value:l,writable:!0,configurable:!0,enumerable:!1});n[r]=(...t)=>{let l=q[r](...t);return Object.setPrototypeOf(l,a.prototype),l}}return n}export{d as a,j as b,ee as c,ne as d,te as e,ae as f};
2
- //# sourceMappingURL=chunk-54RHS4F4.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/builders/GenericSchemaBuilder.ts","../src/extension.ts"],"sourcesContent":["import {\n type BRAND,\n SchemaBuilder,\n type ValidationContext,\n type ValidationErrorMessageProvider,\n type ValidationResult\n} from './SchemaBuilder.js';\n\ntype GenericSchemaBuilderCreateProps<TRequired extends boolean = true> =\n Partial<ReturnType<GenericSchemaBuilder<any, TRequired>['introspect']>>;\n\n/**\n * Schema builder that wraps a generic template function, enabling reusable\n * parameterized schemas. Call {@link GenericSchemaBuilder.apply | `.apply()`}\n * with concrete schema arguments to obtain a fully typed concrete schema\n * builder whose TypeScript type is inferred from the template function's\n * generic signature.\n *\n * **NOTE** this class is exported only to give opportunity to extend it\n * by inheriting. It is not recommended to create an instance of this class\n * directly. Use {@link generic | generic()} function instead.\n *\n * @example Single type parameter\n * ```ts\n * import { generic, object, array, number, string, InferType } from '@cleverbrush/schema';\n *\n * const PaginatedList = generic(\n * <T extends SchemaBuilder<any, any, any, any, any>>(itemSchema: T) =>\n * object({\n * items: array(itemSchema),\n * total: number(),\n * page: number(),\n * })\n * );\n *\n * const userSchema = object({ name: string(), age: number() });\n * const PaginatedUsers = PaginatedList.apply(userSchema);\n *\n * type PaginatedUsersType = InferType<typeof PaginatedUsers>;\n * // → { items: { name: string; age: number }[]; total: number; page: number }\n * ```\n *\n * @example Multiple type parameters\n * ```ts\n * const Result = generic(\n * <T extends SchemaBuilder<any, any, any, any, any>,\n * E extends SchemaBuilder<any, any, any, any, any>>(\n * valueSchema: T,\n * errorSchema: E\n * ) =>\n * object({\n * ok: boolean(),\n * value: valueSchema.optional(),\n * error: errorSchema.optional(),\n * })\n * );\n *\n * const StringResult = Result.apply(string(), number());\n * // InferType → { ok: boolean; value?: string; error?: number }\n * ```\n *\n * @example With default arguments (enables direct `.validate()` on the template)\n * ```ts\n * const AnyList = generic(\n * [any()], // default args — one per template parameter\n * <T extends SchemaBuilder<any, any, any, any, any>>(itemSchema: T) =>\n * object({ items: array(itemSchema), total: number() })\n * );\n *\n * // Validate directly using defaults:\n * AnyList.validate({ items: [1, 'two', true], total: 3 }); // valid\n *\n * // Or apply concrete schemas first:\n * AnyList.apply(string()).validate({ items: ['a', 'b'], total: 2 }); // valid\n * ```\n *\n * @see {@link generic}\n *\n * @typeParam TFn - The generic template function type. Its return type\n * determines `TResult` (the validated value type) when no explicit type\n * override has been applied via `.hasType<T>()`.\n * @typeParam TRequired - `true` when the schema is required (default),\n * `false` after calling `.optional()`. Governs whether `undefined` is a\n * valid value.\n * @typeParam TNullable - `true` after calling `.nullable()`. Governs whether\n * `null` is a valid value.\n * @typeParam TExplicitType - Type override set via `.hasType<T>()`. When\n * `undefined` (the default), `TResult` is derived from `TFn`'s return type.\n * @typeParam THasDefault - `true` after calling `.default(value)`. Governs\n * whether `InferType` emits `T` instead of `T | undefined` for optional\n * schemas with a default.\n * @typeParam TExtensions - Object type carrying extension methods added via\n * `withExtensions()`. Defaults to `{}`.\n * @typeParam TResult - The inferred result type: `TExplicitType` when set,\n * otherwise the value type inferred from `ReturnType<TFn>`.\n */\nexport class GenericSchemaBuilder<\n TFn extends (...args: any[]) => SchemaBuilder<any, any, any, any, any>,\n TRequired extends boolean = true,\n TNullable extends boolean = false,\n TExplicitType = undefined,\n THasDefault extends boolean = false,\n TExtensions = {},\n TResult = TExplicitType extends undefined\n ? ReturnType<TFn> extends SchemaBuilder<infer R, any, any, any, any>\n ? R\n : any\n : TExplicitType\n> extends SchemaBuilder<\n TResult,\n TRequired,\n TNullable,\n THasDefault,\n TExtensions\n> {\n #templateFn?: (...args: any[]) => SchemaBuilder<any, any, any, any, any>;\n #defaults?: readonly any[];\n #cachedDefaultSchema?: SchemaBuilder<any, any, any, any, any>;\n\n /**\n * Applies the template function with concrete schema arguments, returning\n * a fully typed concrete schema builder. TypeScript infers the result type\n * from the template function's own generic signature.\n *\n * The returned builder is independent of this `GenericSchemaBuilder` and\n * can be used like any other schema: `.validate()`, `.optional()`, etc.\n *\n * @example\n * ```ts\n * const Wrapper = generic(\n * <T extends SchemaBuilder<any, any, any, any, any>>(schema: T) =>\n * object({ data: schema })\n * );\n *\n * const s = Wrapper.apply(string());\n * // InferType<typeof s> → { data: string }\n * s.validate({ data: 'hello' }); // { valid: true }\n * ```\n */\n // Set to the actual function in the constructor; declared here for TypeScript.\n public declare readonly apply: TFn;\n\n /**\n * @hidden\n */\n public static create(props: GenericSchemaBuilderCreateProps<any>) {\n return new GenericSchemaBuilder({\n type: 'generic',\n ...props\n });\n }\n\n protected constructor(props: GenericSchemaBuilderCreateProps<TRequired>) {\n super(props as any);\n this.#templateFn = (props as any).templateFn;\n this.#defaults = (props as any).defaults;\n\n // Own property: typed as TFn so generic inference works at call sites.\n (this as any).apply = (...args: any[]) => {\n if (!this.#templateFn) {\n throw new Error(\n 'GenericSchemaBuilder: no template function defined'\n );\n }\n return this.#templateFn(...args);\n };\n }\n\n /**\n * Returns an object describing the current schema configuration.\n *\n * In addition to the base fields exposed by {@link SchemaBuilder.introspect},\n * the following fields are included:\n *\n * - `templateFn` — the template function passed to {@link generic}.\n * - `defaults` — the default argument list passed to the two-argument\n * form of {@link generic}, or `undefined` when no defaults were provided.\n *\n * @example\n * ```ts\n * const schema = generic([string()], <T>(s: T) => object({ data: s }));\n *\n * const info = schema.introspect();\n * // info.type → 'generic'\n * // info.templateFn → [Function]\n * // info.defaults → [StringSchemaBuilder]\n * ```\n */\n public introspect() {\n return {\n ...super.introspect(),\n /** Template function passed to {@link generic}. */\n templateFn: this.#templateFn,\n /** Default positional arguments for the template function, or `undefined`. */\n defaults: this.#defaults\n };\n }\n\n #getOrCreateDefaultSchema():\n | SchemaBuilder<any, any, any, any, any>\n | undefined {\n if (!this.#templateFn || !this.#defaults) {\n return undefined;\n }\n if (!this.#cachedDefaultSchema) {\n this.#cachedDefaultSchema = this.#templateFn(...this.#defaults);\n }\n return this.#cachedDefaultSchema;\n }\n\n #buildResult(\n superResult: ReturnType<\n GenericSchemaBuilder<TFn, TRequired>['preValidateSync']\n >,\n context?: ValidationContext\n ): ValidationResult<TResult> {\n const {\n valid,\n transaction: preValidationTransaction,\n errors\n } = superResult;\n\n if (!valid) {\n return { valid, errors };\n }\n\n const {\n object: { validatedObject: objToValidate }\n } = preValidationTransaction!;\n\n if (\n (typeof objToValidate === 'undefined' && !this.isRequired) ||\n (objToValidate === null && (!this.isRequired || this.isNullable))\n ) {\n return { valid: true, object: objToValidate };\n }\n\n const defaultSchema = this.#getOrCreateDefaultSchema();\n if (!defaultSchema) {\n return {\n valid: false,\n errors: [\n {\n message:\n 'This is a generic schema template. Call .apply() with concrete schemas to get a validatable schema, or provide default arguments to generic().'\n }\n ]\n };\n }\n\n return defaultSchema.validate(\n objToValidate,\n context\n ) as ValidationResult<TResult>;\n }\n\n async #buildAsyncResult(\n superResult: Awaited<\n ReturnType<GenericSchemaBuilder<TFn, TRequired>['preValidateAsync']>\n >,\n context?: ValidationContext\n ): Promise<ValidationResult<TResult>> {\n const {\n valid,\n transaction: preValidationTransaction,\n errors\n } = superResult;\n\n if (!valid) {\n return { valid, errors };\n }\n\n const {\n object: { validatedObject: objToValidate }\n } = preValidationTransaction!;\n\n if (\n (typeof objToValidate === 'undefined' && !this.isRequired) ||\n (objToValidate === null && (!this.isRequired || this.isNullable))\n ) {\n return { valid: true, object: objToValidate };\n }\n\n const defaultSchema = this.#getOrCreateDefaultSchema();\n if (!defaultSchema) {\n return {\n valid: false,\n errors: [\n {\n message:\n 'This is a generic schema template. Call .apply() with concrete schemas to get a validatable schema, or provide default arguments to generic().'\n }\n ]\n };\n }\n\n return (await defaultSchema.validateAsync(\n objToValidate,\n context\n )) as ValidationResult<TResult>;\n }\n\n /** {@inheritDoc SchemaBuilder.validate} */\n public validate(\n object: TResult,\n context?: ValidationContext\n ): ValidationResult<TResult> {\n return super.validate(object, context) as ValidationResult<TResult>;\n }\n\n /** {@inheritDoc SchemaBuilder.validateAsync} */\n public async validateAsync(\n object: TResult,\n context?: ValidationContext\n ): Promise<ValidationResult<TResult>> {\n return super.validateAsync(object, context) as Promise<\n ValidationResult<TResult>\n >;\n }\n\n /**\n * Performs synchronous validation of the schema over `object`.\n * Throws if any preprocessor, validator, or error message provider returns a Promise.\n * @param context Optional `ValidationContext` settings.\n */\n protected _validate(\n object: TResult,\n context?: ValidationContext\n ): ValidationResult<TResult> {\n return this.#buildResult(\n this.preValidateSync(object, context),\n context\n );\n }\n\n /**\n * Performs async validation of the schema over `object`.\n * Supports async preprocessors, validators, and error message providers.\n * @param context Optional `ValidationContext` settings.\n */\n protected async _validateAsync(\n object: TResult,\n context?: ValidationContext\n ): Promise<ValidationResult<TResult>> {\n return this.#buildAsyncResult(\n await super.preValidateAsync(object, context),\n context\n );\n }\n\n protected createFromProps<TReq extends boolean>(\n props: GenericSchemaBuilderCreateProps<TReq>\n ): this {\n return GenericSchemaBuilder.create(props as any) as any;\n }\n\n /**\n * @hidden\n */\n public hasType<T>(\n _notUsed?: T\n ): GenericSchemaBuilder<TFn, true, TNullable, T, THasDefault, TExtensions> &\n TExtensions {\n return this.createFromProps({\n ...this.introspect()\n } as any) as any;\n }\n\n /**\n * @hidden\n */\n public clearHasType(): GenericSchemaBuilder<\n TFn,\n TRequired,\n TNullable,\n undefined,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return this.createFromProps({\n ...this.introspect()\n } as any) as any;\n }\n\n /**\n * @hidden\n */\n public required(\n errorMessage?: ValidationErrorMessageProvider\n ): GenericSchemaBuilder<\n TFn,\n true,\n TNullable,\n TExplicitType,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return super.required(errorMessage);\n }\n\n /**\n * @hidden\n */\n public optional(): GenericSchemaBuilder<\n TFn,\n false,\n TNullable,\n TExplicitType,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return super.optional();\n }\n\n /**\n * @hidden\n */\n public nullable(): GenericSchemaBuilder<\n TFn,\n TRequired,\n true,\n TExplicitType,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return super.nullable() as any;\n }\n\n /**\n * @hidden\n */\n public notNullable(): GenericSchemaBuilder<\n TFn,\n TRequired,\n false,\n TExplicitType,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return super.notNullable() as any;\n }\n\n /**\n * @hidden\n */\n public default(\n value: TResult | (() => TResult)\n ): GenericSchemaBuilder<\n TFn,\n true,\n TNullable,\n TExplicitType,\n true,\n TExtensions\n > &\n TExtensions {\n return super.default(value) as any;\n }\n\n /**\n * @hidden\n */\n public clearDefault(): GenericSchemaBuilder<\n TFn,\n TRequired,\n TNullable,\n TExplicitType,\n false,\n TExtensions\n > &\n TExtensions {\n return super.clearDefault() as any;\n }\n\n /**\n * @hidden\n */\n public brand<TBrand extends string | symbol>(\n _name?: TBrand\n ): GenericSchemaBuilder<\n TFn,\n TRequired,\n TNullable,\n TResult & { readonly [K in BRAND]: TBrand },\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return super.brand(_name);\n }\n\n /**\n * @hidden\n */\n public readonly(): GenericSchemaBuilder<\n TFn,\n TRequired,\n TNullable,\n Readonly<TResult>,\n THasDefault,\n TExtensions\n > &\n TExtensions {\n return super.readonly();\n }\n}\n\n/**\n * Creates a generic schema template — a reusable, parameterized schema factory\n * whose TypeScript type is inferred from the template function's generic\n * signature.\n *\n * Call {@link GenericSchemaBuilder.apply | `.apply()`} on the returned builder\n * to instantiate the template with concrete schema arguments and receive a\n * fully typed concrete schema.\n *\n * There are two overloads:\n *\n * 1. **`generic(templateFn)`** — Provide only the template function. The\n * template must be called via `.apply()` before validation.\n * 2. **`generic(defaults, templateFn)`** — Provide positional default arguments\n * followed by the template function. The template can be validated directly\n * using those defaults (without calling `.apply()` first).\n *\n * @param templateFn - A (generic) function that accepts schema arguments and\n * returns a concrete schema. TypeScript infers the result type from this\n * function's generic signature when `.apply()` is called.\n *\n * @returns A new {@link GenericSchemaBuilder} with `isRequired` set to `true`.\n *\n * @example Single type parameter\n * ```ts\n * import { generic, object, array, number, string, any, InferType } from '@cleverbrush/schema';\n *\n * const PaginatedList = generic(\n * <T extends SchemaBuilder<any, any, any, any, any>>(itemSchema: T) =>\n * object({ items: array(itemSchema), total: number(), page: number() })\n * );\n *\n * const UserList = PaginatedList.apply(object({ name: string() }));\n * type UserListType = InferType<typeof UserList>;\n * // → { items: { name: string }[]; total: number; page: number }\n *\n * UserList.validate({ items: [{ name: 'Alice' }], total: 1, page: 1 }); // valid\n * ```\n *\n * @example Multiple type parameters\n * ```ts\n * const Result = generic(\n * <T extends SchemaBuilder<any, any, any, any, any>,\n * E extends SchemaBuilder<any, any, any, any, any>>(\n * valueSchema: T,\n * errorSchema: E\n * ) =>\n * union(\n * object({ ok: boolean().equalsTo(true), value: valueSchema }),\n * object({ ok: boolean().equalsTo(false), error: errorSchema })\n * )\n * );\n *\n * const StringResult = Result.apply(string(), number());\n * ```\n *\n * @example With defaults (enables direct validation on the template)\n * ```ts\n * const AnyList = generic(\n * [any()], // default args — positional, one per template parameter\n * <T extends SchemaBuilder<any, any, any, any, any>>(itemSchema: T) =>\n * object({ items: array(itemSchema), total: number() })\n * );\n *\n * // Validate directly — uses the default any() schema:\n * AnyList.validate({ items: [1, 'two'], total: 2 }); // valid\n *\n * // Or apply concrete schemas first:\n * AnyList.apply(string()).validate({ items: ['x'], total: 1 }); // valid\n * ```\n *\n * @see {@link GenericSchemaBuilder}\n */\nexport function generic<\n TFn extends (...args: any[]) => SchemaBuilder<any, any, any, any, any>\n>(\n templateFn: TFn\n): GenericSchemaBuilder<TFn, true, false, undefined, false, {}>;\nexport function generic<\n TFn extends (...args: any[]) => SchemaBuilder<any, any, any, any, any>\n>(\n defaults: readonly any[],\n templateFn: TFn\n): GenericSchemaBuilder<TFn, true, false, undefined, false, {}>;\nexport function generic<\n TFn extends (...args: any[]) => SchemaBuilder<any, any, any, any, any>\n>(\n fnOrDefaults: TFn | readonly any[],\n templateFn?: TFn\n): GenericSchemaBuilder<TFn, true, false, undefined, false, {}> {\n const fn = templateFn !== undefined ? templateFn : (fnOrDefaults as TFn);\n const defaults =\n templateFn !== undefined ? (fnOrDefaults as readonly any[]) : undefined;\n return GenericSchemaBuilder.create({\n isRequired: true,\n templateFn: fn,\n defaults\n }) as any;\n}\n","/**\n * @module extension\n *\n * The **extension system** for `@cleverbrush/schema` allows third-party and\n * first-party code to add custom methods to any schema builder type\n * (`string`, `number`, `date`, `object`, …) without modifying the core\n * library.\n *\n * ## Overview\n *\n * Extensions follow a two-step workflow:\n *\n * 1. **Define** an extension with {@link defineExtension} — declare which\n * builder types it targets and what methods it adds.\n * 2. **Apply** one or more extensions with {@link withExtensions} — get back\n * augmented factory functions (`string()`, `number()`, …) whose return\n * types include the new methods.\n *\n * ## Ergonomic authoring\n *\n * Extension methods do **not** need to call `withExtension()` manually.\n * The system automatically attaches metadata using the method name as the\n * extension key and the method arguments as the value. This keeps extension\n * definitions concise:\n *\n * ```ts\n * const slugExt = defineExtension({\n * string: {\n * slug(this: StringSchemaBuilder) {\n * return this.addValidator((val) => {\n * const valid = /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(val);\n * return { valid, errors: valid ? [] : [{ message: 'must be a valid URL slug' }] };\n * });\n * }\n * }\n * });\n * ```\n *\n * If you need **custom metadata** (e.g. a different key or a transformed\n * value), call `this.withExtension(key, value)` explicitly — the auto-infer\n * logic will detect the existing key and skip the automatic attachment.\n *\n * ## Stacking and composition\n *\n * Multiple extensions can target the same builder type. Pass them all to\n * `withExtensions()` and the methods are merged. A runtime error is thrown\n * if two extensions define the same method name on the same builder type.\n *\n * ```ts\n * const s = withExtensions(emailExt, slugExt, rangeExt);\n * const schema = s.string().email().slug(); // both methods available\n * ```\n *\n * ## Introspection\n *\n * Extension metadata is accessible via `schema.introspect().extensions`.\n * Each key corresponds to an extension method name and its value is whatever\n * was passed (or auto-inferred) as the extension data.\n *\n * @see {@link defineExtension} — define an extension\n * @see {@link withExtensions} — apply extensions to builder factories\n * @see {@link ExtensionConfig} — shape of the configuration object\n * @see {@link ExtensionDescriptor} — branded descriptor returned by `defineExtension`\n */\nimport { AnySchemaBuilder, any } from './builders/AnySchemaBuilder.js';\nimport { ArraySchemaBuilder, array } from './builders/ArraySchemaBuilder.js';\nimport {\n BooleanSchemaBuilder,\n boolean\n} from './builders/BooleanSchemaBuilder.js';\nimport { DateSchemaBuilder, date } from './builders/DateSchemaBuilder.js';\nimport {\n FunctionSchemaBuilder,\n func\n} from './builders/FunctionSchemaBuilder.js';\nimport {\n GenericSchemaBuilder,\n generic\n} from './builders/GenericSchemaBuilder.js';\nimport { NumberSchemaBuilder, number } from './builders/NumberSchemaBuilder.js';\nimport { ObjectSchemaBuilder, object } from './builders/ObjectSchemaBuilder.js';\nimport {\n PromiseSchemaBuilder,\n promise\n} from './builders/PromiseSchemaBuilder.js';\nimport { RecordSchemaBuilder, record } from './builders/RecordSchemaBuilder.js';\nimport type {\n PropertyDescriptorTree,\n SchemaBuilder\n} from './builders/SchemaBuilder.js';\nimport { StringSchemaBuilder, string } from './builders/StringSchemaBuilder.js';\nimport { TupleSchemaBuilder, tuple } from './builders/TupleSchemaBuilder.js';\nimport { UnionSchemaBuilder, union } from './builders/UnionSchemaBuilder.js';\n\n// ---------------------------------------------------------------------------\n// Builder type name mapping\n// ---------------------------------------------------------------------------\n\n/**\n * Maps each builder type name to the corresponding generic builder class.\n *\n * Used internally to type-check extension method `this` bindings — for\n * example, an extension targeting `\"string\"` receives `this: StringSchemaBuilder`.\n *\n * @internal Not exported — used only by the extension type machinery.\n */\ntype BuilderMap = {\n string: StringSchemaBuilder<any, any, any, any, any>;\n number: NumberSchemaBuilder<any, any, any, any, any>;\n boolean: BooleanSchemaBuilder<any, any, any, any, any, any, any>;\n date: DateSchemaBuilder<any, any, any, any, any>;\n object: ObjectSchemaBuilder<any, any, any, any, any, any, any>;\n array: ArraySchemaBuilder<any, any, any, any, any, any, any>;\n tuple: TupleSchemaBuilder<any, any, any, any, any, any, any>;\n record: RecordSchemaBuilder<any, any, any, any, any, any, any>;\n union: UnionSchemaBuilder<any, any, any, any, any, any>;\n func: FunctionSchemaBuilder<any, any, any, any, any>;\n any: AnySchemaBuilder<any, any, any, any, any, any>;\n promise: PromiseSchemaBuilder<any, any, any, any, any>;\n generic: GenericSchemaBuilder<any, any, any, any, any, any>;\n};\n\ntype BuilderTypeName = keyof BuilderMap;\n\n// Runtime mapping from type name to the actual class constructor\nconst builderClasses: Record<BuilderTypeName, typeof SchemaBuilder> = {\n string: StringSchemaBuilder as any,\n number: NumberSchemaBuilder as any,\n boolean: BooleanSchemaBuilder as any,\n date: DateSchemaBuilder as any,\n object: ObjectSchemaBuilder as any,\n array: ArraySchemaBuilder as any,\n tuple: TupleSchemaBuilder as any,\n record: RecordSchemaBuilder as any,\n union: UnionSchemaBuilder as any,\n func: FunctionSchemaBuilder as any,\n any: AnySchemaBuilder as any,\n promise: PromiseSchemaBuilder as any,\n generic: GenericSchemaBuilder as any\n};\n\n// Runtime mapping from type name to factory function\nconst builderFactories: Record<BuilderTypeName, (...args: any[]) => any> = {\n string,\n number,\n boolean,\n date,\n object,\n array,\n tuple,\n record,\n union,\n func,\n any,\n promise,\n generic\n};\n\n// ---------------------------------------------------------------------------\n// Extension configuration types\n// ---------------------------------------------------------------------------\n\n/**\n * Defines the shape of an extension configuration object passed to\n * {@link defineExtension}.\n *\n * Each key is a **builder type name** — one of `\"string\"`, `\"number\"`,\n * `\"boolean\"`, `\"date\"`, `\"object\"`, `\"array\"`, `\"union\"`, `\"func\"`, or\n * `\"any\"`. The value is a record of **method implementations** to add to\n * that builder type.\n *\n * Method implementations receive `this` bound to the target builder instance\n * (e.g. `StringSchemaBuilder` for the `\"string\"` key) and **must** return a\n * builder of the same type to support fluent chaining.\n *\n * @remarks\n * Extension methods that only add validators/preprocessors do not need to\n * call `this.withExtension()` — the system will auto-attach metadata using\n * the method name as the key and the arguments as the value. Call\n * `this.withExtension(key, value)` explicitly only when you need custom\n * metadata (e.g. a transformed value or a different key).\n *\n * @example\n * ```ts\n * // Minimal extension config — auto-inferred metadata\n * const config: ExtensionConfig = {\n * string: {\n * slug(this: StringSchemaBuilder) {\n * return this.addValidator((v) => ({ valid: /^[a-z0-9-]+$/.test(v), errors: [] }));\n * }\n * },\n * number: {\n * port(this: NumberSchemaBuilder) {\n * return this.isInteger().min(1).max(65535);\n * }\n * }\n * };\n * ```\n *\n * @see {@link defineExtension}\n */\nexport type ExtensionConfig = {\n [K in BuilderTypeName]?: Record<\n string,\n (this: BuilderMap[K], ...args: any[]) => any\n >;\n};\n\n/**\n * A branded descriptor returned by {@link defineExtension}.\n *\n * The descriptor captures the extension's method signatures at the **type\n * level** so that {@link withExtensions} can produce correctly-typed factory\n * functions. At runtime it holds the (possibly wrapped) configuration object.\n *\n * Extension descriptors are intentionally **opaque** — consumers should not\n * access `config` directly. Instead, pass descriptors to\n * {@link withExtensions} to obtain augmented builder factories.\n *\n * @typeParam T - The concrete {@link ExtensionConfig} shape. Inferred\n * automatically by `defineExtension`; you rarely need to specify it.\n *\n * @example\n * ```ts\n * // The type is inferred — no need to annotate\n * const myExt: ExtensionDescriptor<{ string: { slug: ... } }> = defineExtension({ ... });\n * ```\n *\n * @see {@link defineExtension}\n * @see {@link withExtensions}\n */\nexport type ExtensionDescriptor<T extends ExtensionConfig = ExtensionConfig> = {\n readonly __brand: unique symbol;\n readonly config: T;\n};\n\n// ---------------------------------------------------------------------------\n// Type-level extraction of extension methods per builder type\n// ---------------------------------------------------------------------------\n\n/** Extracts the method signatures an extension adds to a given builder type. */\ntype ExtractMethods<\n TExt extends ExtensionConfig,\n TType extends BuilderTypeName\n> =\n TExt[TType] extends Record<string, (...args: any[]) => any>\n ? TExt[TType]\n : {};\n\n/** Merges the methods from multiple extensions for a given builder type. */\ntype MergeExtensionMethods<\n TExts extends readonly ExtensionDescriptor<any>[],\n TType extends BuilderTypeName\n> = TExts extends readonly [\n ExtensionDescriptor<infer TFirst>,\n ...infer TRest extends readonly ExtensionDescriptor<any>[]\n]\n ? ExtractMethods<TFirst, TType> & MergeExtensionMethods<TRest, TType>\n : {};\n\n// ---------------------------------------------------------------------------\n// Return types for withExtensions()\n// ---------------------------------------------------------------------------\n\n/**\n * Unique string-literal brand key used by {@link FixedMethods} to detect\n * extension methods whose first-argument literal should be accumulated in the\n * return type.\n *\n * Declare the return type of any extension method as\n * `this & { readonly [METHOD_LITERAL_BRAND]?: N }` (where `N extends string`)\n * and `FixedMethods` will automatically make it generic so the literal name\n * flows through the type system and accumulates across multiple calls.\n *\n * This powers scope-name autocomplete in `SchemaQueryBuilder.scoped()`.\n */\nconst METHOD_LITERAL_BRAND = '__cleverbrush_method_literal_brand__' as const;\n\nexport { METHOD_LITERAL_BRAND };\nexport type MethodLiteralBrandSymbol = typeof METHOD_LITERAL_BRAND;\n\n/**\n * Generic accumulator brand for extension methods that want to thread\n * a `Record<name, readonly string[]>` map through the builder chain.\n *\n * Extension authors can declare a method's return type as\n * `this & { readonly [EXTRA_TYPE_BRAND]?: { [name]: TKeys } }`\n * and {@link FixedMethods} will automatically:\n * - Make the first argument const-generic (to capture the literal name).\n * - Make the second argument const-generic when it is a `readonly string[]`\n * tuple (to capture the literal key list).\n * - Accumulate both into the 4th `TExtraTypes` parameter of `FixedMethods`\n * so the information survives subsequent method calls on the same builder.\n *\n * This is deliberately projection-agnostic — any extension that follows the\n * `(name: string, data: readonly string[] | function)` signature convention\n * can use it. Projection-specific semantics (e.g. `PROJECTION_BRAND`) live\n * in the consuming library, not here.\n *\n * @see {@link FixedMethods} for how the accumulation works.\n */\nconst EXTRA_TYPE_BRAND = '__cleverbrush_extra_type_brand__' as const;\n\nexport { EXTRA_TYPE_BRAND };\nexport type ExtraTypeBrandSymbol = typeof EXTRA_TYPE_BRAND;\n\n/** @internal Drops the first element of a tuple type. */\ntype TailArgs<T> = T extends readonly [unknown, ...infer R] ? R : [];\n\n/**\n * Intersected onto consumer-facing builder types to make `withExtension`\n * and `getExtension` uncallable (`never`). Using an intersection instead\n * of `Omit` preserves the class identity so extended builders remain\n * assignable to `SchemaBuilder<any, any, any, any, any>`.\n */\nexport type HiddenExtensionMethods = {\n /** @internal Extension-author only — use inside `defineExtension()`. */\n withExtension: never;\n /** @internal Extension-author only — use inside `defineExtension()`. */\n getExtension: never;\n};\n\n/**\n * Overrides extension method return types so they always return the full\n * extended builder type. This ensures extension methods preserve all other\n * extension methods through chaining (e.g. `s.string().email().slug()`).\n *\n * The self-reference (`FixedMethods` appears in its own mapped return\n * types) is resolved lazily by TypeScript because the recursion sits\n * inside a function-return position within a conditional mapped type.\n *\n * The optional third parameter `TAccum` accumulates literal string names\n * registered by methods whose raw return type includes\n * `{ readonly [METHOD_LITERAL_BRAND]?: any }`. Those methods are rewritten\n * as `const`-generic so the literal flows through; all other methods thread\n * the accumulator unchanged.\n *\n * The optional fourth parameter `TExtraTypes` accumulates a\n * `Record<name, readonly string[]>` map contributed by methods whose raw\n * return type includes `{ readonly [EXTRA_TYPE_BRAND]?: any }`. Those\n * methods are rewritten as const-generic for both the name and the keys\n * tuple so the mapping flows through; all other methods thread it unchanged.\n *\n * For object-schema methods the accessor-form callback parameter is\n * automatically typed as `PropertyDescriptorTree<TBase, TBase>` when\n * `TBase` is an `ObjectSchemaBuilder`, giving callers IDE autocomplete over\n * the schema's own properties.\n */\nexport type FixedMethods<\n TRawMethods,\n TBase,\n TAccum extends string = never,\n TExtraTypes extends Record<string, readonly string[]> = Record<never, never>\n> = {\n [K in keyof TRawMethods]: TRawMethods[K] extends (\n this: any,\n ...args: infer A\n ) => infer R\n ? R extends { readonly [EXTRA_TYPE_BRAND]?: any }\n ? // Extra-type-brand method: rest-param shape `(name, ...columns)`.\n // Each column is a property-name string or an accessor callback.\n // The string-literal union accumulates into `TKey` and lands in\n // the `EXTRA_TYPE_BRAND` under `TName` as `readonly TKey[]`.\n // When `TBase` is an `ObjectSchemaBuilder` the callback `t` is\n // typed as `PropertyDescriptorTree<TBase, TBase>` so callers get\n // IDE autocomplete over the schema's own properties.\n <const TName extends string & A[0], const TKey extends string>(\n name: TName,\n ...columns: ReadonlyArray<\n | TKey\n | (TBase extends ObjectSchemaBuilder<\n any,\n any,\n any,\n any,\n any\n >\n ? (t: PropertyDescriptorTree<TBase, TBase>) => any\n : (t: any) => any)\n >\n ) => TBase &\n FixedMethods<\n TRawMethods,\n TBase,\n TAccum,\n TExtraTypes & Record<TName, readonly TKey[]>\n > &\n HiddenExtensionMethods & {\n readonly [EXTRA_TYPE_BRAND]?: TExtraTypes &\n Record<TName, readonly TKey[]>;\n } & ([TAccum] extends [never]\n ? {}\n : { readonly [METHOD_LITERAL_BRAND]?: TAccum })\n : R extends { readonly [METHOD_LITERAL_BRAND]?: any }\n ? // Literal-brand method: becomes const-generic so the first-arg\n // literal accumulates in TAccum and in the [METHOD_LITERAL_BRAND]\n // property of the return type.\n <const TName extends string & A[0]>(\n name: TName,\n ...rest: TailArgs<A>\n ) => TBase &\n FixedMethods<\n TRawMethods,\n TBase,\n TAccum | TName,\n TExtraTypes\n > &\n HiddenExtensionMethods & {\n readonly [METHOD_LITERAL_BRAND]?: TAccum | TName;\n } & ([keyof TExtraTypes] extends [never]\n ? {}\n : { readonly [EXTRA_TYPE_BRAND]?: TExtraTypes })\n : // Regular method: threads both accumulators through so literals\n // defined earlier in the chain are not lost.\n (\n ...args: A\n ) => TBase &\n FixedMethods<TRawMethods, TBase, TAccum, TExtraTypes> &\n HiddenExtensionMethods &\n ([TAccum] extends [never]\n ? {}\n : { readonly [METHOD_LITERAL_BRAND]?: TAccum }) &\n ([keyof TExtraTypes] extends [never]\n ? {}\n : { readonly [EXTRA_TYPE_BRAND]?: TExtraTypes })\n : TRawMethods[K];\n};\n\n/**\n * Produces the consumer-facing type for an extended builder: the base\n * builder intersected with its fixed extension methods, with\n * `withExtension` / `getExtension` overridden to `never` so they\n * don't appear as callable in consumer code.\n */\nexport type CleanExtended<TBuilder, TExt> = TBuilder &\n FixedMethods<TExt, TBuilder> &\n HiddenExtensionMethods;\n\n// -- Factory types that return builders with corrected extension methods ------\n\ntype ExtendedStringFactory<TExt> = {\n (): CleanExtended<\n StringSchemaBuilder<string, true, false, false, TExt>,\n TExt\n >;\n <T extends string>(\n equals: T\n ): CleanExtended<StringSchemaBuilder<T, true, false, false, TExt>, TExt>;\n};\n\ntype ExtendedNumberFactory<TExt> = {\n (): CleanExtended<\n NumberSchemaBuilder<number, true, false, false, TExt>,\n TExt\n >;\n <T extends number>(\n equals: T\n ): CleanExtended<NumberSchemaBuilder<T, true, false, false, TExt>, TExt>;\n};\n\ntype ExtendedBooleanFactory<TExt> = () => CleanExtended<\n BooleanSchemaBuilder<boolean, true, false, undefined, false, TExt>,\n TExt\n>;\n\ntype ExtendedDateFactory<TExt> = () => CleanExtended<\n DateSchemaBuilder<Date, true, false, false, TExt>,\n TExt\n>;\n\ntype ExtendedObjectFactory<TExt> = <\n P extends Record<string, SchemaBuilder<any, any, any, any, any>>\n>(\n properties?: P\n) => CleanExtended<\n ObjectSchemaBuilder<P, true, false, undefined, false, TExt, []>,\n TExt\n>;\n\ntype ExtendedArrayFactory<TExt> = <\n TElementSchema extends SchemaBuilder<any, any, any, any, any>\n>(\n elementSchema?: TElementSchema\n) => CleanExtended<\n ArraySchemaBuilder<TElementSchema, true, false, undefined, false, TExt>,\n TExt\n>;\n\ntype ExtendedUnionFactory<TExt> = <\n T extends SchemaBuilder<any, any, any, any, any>\n>(\n schema: T\n) => CleanExtended<\n UnionSchemaBuilder<[T], true, false, undefined, false, TExt>,\n TExt\n>;\n\ntype ExtendedFuncFactory<TExt> = () => CleanExtended<\n FunctionSchemaBuilder<true, false, undefined, false, TExt>,\n TExt\n>;\n\ntype ExtendedAnyFactory<TExt> = () => CleanExtended<\n AnySchemaBuilder<true, false, undefined, false, TExt>,\n TExt\n>;\n\ntype ExtendedTupleFactory<TExt> = <\n const TElements extends readonly SchemaBuilder<any, any, any, any, any>[]\n>(\n elements: [...TElements]\n) => CleanExtended<\n TupleSchemaBuilder<TElements, true, false, undefined, false, TExt>,\n TExt\n>;\n\ntype ExtendedRecordFactory<TExt> = <\n TKeySchema extends StringSchemaBuilder<any, any, any, any>,\n TValueSchema extends SchemaBuilder<any, any, any, any, any>\n>(\n keySchema: TKeySchema,\n valueSchema: TValueSchema\n) => CleanExtended<\n RecordSchemaBuilder<\n TKeySchema,\n TValueSchema,\n true,\n false,\n undefined,\n false,\n TExt\n >,\n TExt\n>;\n\ntype ExtendedPromiseFactory<TExt> = <\n TSchema extends SchemaBuilder<any, any, any, any, any>\n>(\n resolvedTypeSchema?: TSchema\n) => CleanExtended<\n PromiseSchemaBuilder<true, false, undefined, false, TExt, TSchema>,\n TExt\n>;\n\ntype ExtendedGenericFactory<TExt> = <\n TFn extends (...args: any[]) => SchemaBuilder<any, any, any, any, any>\n>(\n templateFn: TFn\n) => CleanExtended<\n GenericSchemaBuilder<TFn, true, false, undefined, false, TExt>,\n TExt\n>;\n\n/**\n * The return type of {@link withExtensions}.\n *\n * Contains a factory function for every builder type (`string`, `number`,\n * `boolean`, `date`, `object`, `array`, `union`, `func`, `any`). Each\n * factory returns a builder whose type includes the methods contributed\n * by all provided extension descriptors.\n *\n * @typeParam TExts - Tuple of extension descriptors passed to `withExtensions`.\n *\n * @see {@link withExtensions}\n */\ntype WithExtensionsResult<TExts extends readonly ExtensionDescriptor<any>[]> = {\n string: ExtendedStringFactory<MergeExtensionMethods<TExts, 'string'>>;\n number: ExtendedNumberFactory<MergeExtensionMethods<TExts, 'number'>>;\n boolean: ExtendedBooleanFactory<MergeExtensionMethods<TExts, 'boolean'>>;\n date: ExtendedDateFactory<MergeExtensionMethods<TExts, 'date'>>;\n object: ExtendedObjectFactory<MergeExtensionMethods<TExts, 'object'>>;\n array: ExtendedArrayFactory<MergeExtensionMethods<TExts, 'array'>>;\n tuple: ExtendedTupleFactory<MergeExtensionMethods<TExts, 'tuple'>>;\n record: ExtendedRecordFactory<MergeExtensionMethods<TExts, 'record'>>;\n union: ExtendedUnionFactory<MergeExtensionMethods<TExts, 'union'>>;\n func: ExtendedFuncFactory<MergeExtensionMethods<TExts, 'func'>>;\n any: ExtendedAnyFactory<MergeExtensionMethods<TExts, 'any'>>;\n promise: ExtendedPromiseFactory<MergeExtensionMethods<TExts, 'promise'>>;\n generic: ExtendedGenericFactory<MergeExtensionMethods<TExts, 'generic'>>;\n};\n\n// ---------------------------------------------------------------------------\n// Reserved method names — cannot be overridden by extensions\n// ---------------------------------------------------------------------------\n\n/**\n * Method names on `SchemaBuilder` that extensions are **not** allowed to\n * override. An error is thrown at definition time if an extension tries\n * to use any of these names.\n *\n * @internal\n */\nconst RESERVED_METHODS = new Set([\n 'validate',\n 'validateAsync',\n 'parse',\n 'parseAsync',\n 'safeParse',\n 'safeParseAsync',\n 'introspect',\n 'optional',\n 'required',\n 'addPreprocessor',\n 'clearPreprocessors',\n 'addValidator',\n 'clearValidators',\n 'hasType',\n 'clearHasType',\n 'createFromProps',\n 'preValidate',\n 'preValidateSync',\n 'preValidateAsync',\n 'getValidationErrorMessage',\n 'getValidationErrorMessageSync',\n 'assureValidationErrorMessageProvider',\n 'withExtension',\n 'getExtension'\n]);\n\n// ---------------------------------------------------------------------------\n// defineExtension()\n// ---------------------------------------------------------------------------\n\n/**\n * Defines an extension targeting one or more schema builder types.\n *\n * Each extension is a plain object keyed by builder type name (`\"string\"`,\n * `\"number\"`, `\"date\"`, …) whose values are method implementations.\n * Methods receive `this` bound to the builder instance and must return a\n * builder to support fluent chaining.\n *\n * ## Ergonomic metadata (auto-infer)\n *\n * Extension methods **do not** have to call `this.withExtension()`. The\n * system wraps each method and automatically attaches\n * `withExtension(methodName, args)` to the returned builder when the key\n * is not already present. This eliminates the most common source of\n * duplication in extension code.\n *\n * - **Zero-arg methods** → metadata value is `true`\n * - **Single-arg methods** → metadata value is the argument itself\n * - **Multi-arg methods** → metadata value is the arguments array\n *\n * If you need **custom metadata** (e.g. a different key, a transformed\n * value, or a structured object), call `this.withExtension(key, value)`\n * explicitly inside the method — the auto-infer logic detects the existing\n * key and skips automatic attachment.\n *\n * ## Validation\n *\n * `defineExtension` validates the configuration eagerly:\n * - Unknown builder type names throw immediately.\n * - {@link RESERVED_METHODS | Reserved method names} (e.g. `validate`,\n * `introspect`) cannot be overridden.\n * - Non-function values in the method record are rejected.\n *\n * @param config - An {@link ExtensionConfig} object mapping builder type\n * names to method records.\n * @returns A branded {@link ExtensionDescriptor} ready to pass to\n * {@link withExtensions}.\n *\n * @example Simple extension (auto-inferred metadata)\n * ```ts\n * const slugExt = defineExtension({\n * string: {\n * slug(this: StringSchemaBuilder) {\n * return this.addValidator((val) => {\n * const valid = /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(val);\n * return { valid, errors: valid ? [] : [{ message: 'invalid slug' }] };\n * });\n * }\n * }\n * });\n *\n * // Usage:\n * const s = withExtensions(slugExt);\n * const schema = s.string().slug();\n * schema.introspect().extensions.slug; // true\n * ```\n *\n * @example Extension with custom metadata\n * ```ts\n * const currencyExt = defineExtension({\n * number: {\n * currency(this: NumberSchemaBuilder, opts?: { maxDecimals?: number }) {\n * const maxDec = opts?.maxDecimals ?? 2;\n * return this.withExtension('currency', { maxDecimals: maxDec })\n * .min(0)\n * .addValidator((val) => {\n * const decimals = (String(val).split('.')[1] ?? '').length;\n * const valid = decimals <= maxDec;\n * return { valid, errors: valid ? [] : [{ message: `max ${maxDec} decimals` }] };\n * });\n * }\n * }\n * });\n * ```\n *\n * @example Multi-builder extension\n * ```ts\n * const myExt = defineExtension({\n * string: {\n * email(this: StringSchemaBuilder) { return this.addValidator(...); }\n * },\n * number: {\n * port(this: NumberSchemaBuilder) { return this.isInteger().min(1).max(65535); }\n * }\n * });\n * ```\n *\n * @throws {Error} If a builder type name is unknown.\n * @throws {Error} If a method name is reserved.\n * @throws {Error} If a method value is not a function.\n *\n * @see {@link withExtensions} — apply the defined extension\n * @see {@link ExtensionConfig} — configuration shape\n */\nexport function defineExtension<T extends ExtensionConfig>(\n config: T\n): ExtensionDescriptor<T> {\n // Validate at definition time and wrap methods for auto-infer extension key\n const wrappedConfig: any = {};\n for (const builderName of Object.keys(config) as BuilderTypeName[]) {\n if (!(builderName in builderClasses)) {\n throw new Error(\n `Unknown builder type \"${builderName}\". Valid types: ${Object.keys(builderClasses).join(', ')}`\n );\n }\n\n const methods = config[builderName];\n if (!methods || typeof methods !== 'object') {\n throw new Error(\n `Extension config for \"${builderName}\" must be an object of methods`\n );\n }\n\n wrappedConfig[builderName] = {};\n for (const methodName of Object.keys(methods)) {\n if (RESERVED_METHODS.has(methodName)) {\n throw new Error(\n `Cannot override reserved method \"${methodName}\" on \"${builderName}\"`\n );\n }\n const origMethod = methods[methodName];\n if (typeof origMethod !== 'function') {\n throw new Error(\n `Extension method \"${builderName}.${methodName}\" must be a function`\n );\n }\n // Wrap the method to auto-infer extension key if not already set\n wrappedConfig[builderName][methodName] = function (\n this: any,\n ...args: any[]\n ) {\n const result = (origMethod as any).apply(this, args);\n // If result is a builder and does not have the extension key, auto-apply withExtension\n if (\n result &&\n typeof result === 'object' &&\n typeof result.withExtension === 'function' &&\n // Only auto-apply if the extension key is not already present\n (typeof result.getExtension !== 'function' ||\n result.getExtension(methodName) === undefined)\n ) {\n // Only auto-apply if the original method did not call withExtension\n return result.withExtension(\n methodName,\n args.length === 1\n ? args[0]\n : args.length === 0\n ? true\n : args\n );\n }\n return result;\n };\n }\n }\n\n return { config: wrappedConfig } as ExtensionDescriptor<T>;\n}\n\n// ---------------------------------------------------------------------------\n// withExtensions()\n// ---------------------------------------------------------------------------\n\n/**\n * Creates a set of schema factory functions with the provided extensions\n * applied.\n *\n * Each factory function (`string()`, `number()`, `date()`, …) returned by\n * `withExtensions` produces builder instances whose prototypes include the\n * extension methods. All built-in builder methods remain available and\n * fully chainable alongside the new ones.\n *\n * ## Stacking multiple extensions\n *\n * Pass any number of {@link ExtensionDescriptor}s — their methods are\n * merged per builder type. If two extensions define the **same** method\n * name on the same builder type, a runtime error is thrown to prevent\n * silent conflicts.\n *\n * ## Type safety\n *\n * The return type is fully inferred: TypeScript knows exactly which\n * extension methods are available on each builder factory. Extension\n * methods return the full extended builder type, so chaining like\n * `s.string().email().slug().minLength(3)` is fully typed.\n *\n * ## Builder types without extensions\n *\n * Builders that have no methods from any of the provided extensions\n * use the standard (unextended) factory, so there is zero overhead.\n *\n * @param extensions - One or more {@link ExtensionDescriptor}s created\n * by {@link defineExtension}.\n * @returns An object with factory functions for all builder types\n * (`string`, `number`, `boolean`, `date`, `object`, `array`, `union`,\n * `func`, `any`), each returning augmented builders.\n *\n * @example Basic usage\n * ```ts\n * const s = withExtensions(emailExt, rangeExt);\n *\n * // string() now has .email()\n * const emailSchema = s.string().email().minLength(5);\n *\n * // number() now has .range()\n * const rangeSchema = s.number().range(0, 100);\n *\n * // builders without targeted extensions work as normal\n * const dateSchema = s.date();\n * ```\n *\n * @example Stacking extensions on the same builder\n * ```ts\n * const s = withExtensions(emailExt, slugExt, trimmedExt);\n * const schema = s.string().email().slug().trimmed();\n * ```\n *\n * @example Using extensions in object schemas\n * ```ts\n * const s = withExtensions(emailExt, portExt);\n * const ServerConfig = s.object({\n * host: s.string().email(),\n * port: s.number().port()\n * });\n * ```\n *\n * @throws {Error} If two extensions define the same method name on the\n * same builder type.\n *\n * @see {@link defineExtension} — create extension descriptors\n * @see {@link ExtensionDescriptor}\n */\nexport function withExtensions<\n const TExts extends readonly ExtensionDescriptor<any>[]\n>(...extensions: TExts): WithExtensionsResult<TExts> {\n // Collect all methods per builder type and check for collisions\n const methodsByBuilder = new Map<BuilderTypeName, Map<string, Function>>();\n\n for (const ext of extensions) {\n for (const builderName of Object.keys(\n ext.config\n ) as BuilderTypeName[]) {\n if (!methodsByBuilder.has(builderName)) {\n methodsByBuilder.set(builderName, new Map());\n }\n const methods = methodsByBuilder.get(builderName)!;\n const extMethods = ext.config[builderName]!;\n\n for (const methodName of Object.keys(extMethods)) {\n if (methods.has(methodName)) {\n throw new Error(\n `Extension method collision: \"${methodName}\" is defined by multiple extensions for \"${builderName}\"`\n );\n }\n methods.set(methodName, extMethods[methodName]);\n }\n }\n }\n\n // For each builder type, create a dynamic subclass if there are extension methods\n const factories: Record<string, (...args: any[]) => any> = {};\n\n for (const builderName of Object.keys(\n builderClasses\n ) as BuilderTypeName[]) {\n const methods = methodsByBuilder.get(builderName);\n\n if (!methods || methods.size === 0) {\n // No extensions for this builder type — use the standard factory\n factories[builderName] = builderFactories[builderName];\n continue;\n }\n\n const BaseClass = builderClasses[builderName] as any;\n\n // Create a dynamic subclass\n const ExtendedClass = class extends BaseClass {\n // biome-ignore lint/complexity/noUselessConstructor: required\n constructor(...args: any[]) {\n super(...args);\n }\n\n static create(props: any) {\n return new ExtendedClass({\n ...props\n });\n }\n\n protected createFromProps(props: any): any {\n return ExtendedClass.create(props);\n }\n };\n\n // Add extension methods to the subclass prototype\n for (const [methodName, methodFn] of methods) {\n Object.defineProperty(ExtendedClass.prototype, methodName, {\n value: methodFn,\n writable: true,\n configurable: true,\n enumerable: false\n });\n }\n\n // Create a factory that uses the extended class\n factories[builderName] = (...args: any[]) => {\n // Delegate to the original factory to get an initialized instance,\n // then upgrade its prototype so it gains the extension methods.\n // Note: Object.setPrototypeOf can cause V8 hidden-class deoptimization\n // on the mutated object, but avoids the double allocation and\n // introspect() round-trip of the previous approach.\n const original = builderFactories[builderName](...args);\n Object.setPrototypeOf(original, ExtendedClass.prototype);\n return original;\n };\n }\n\n return factories as WithExtensionsResult<TExts>;\n}\n"],"mappings":"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","names":["GenericSchemaBuilder","_GenericSchemaBuilder","SchemaBuilder","#templateFn","#defaults","#cachedDefaultSchema","props","args","#getOrCreateDefaultSchema","#buildResult","superResult","context","valid","preValidationTransaction","errors","objToValidate","defaultSchema","#buildAsyncResult","object","_notUsed","errorMessage","value","_name","generic","fnOrDefaults","templateFn","fn","defaults","builderClasses","StringSchemaBuilder","NumberSchemaBuilder","BooleanSchemaBuilder","DateSchemaBuilder","ObjectSchemaBuilder","ArraySchemaBuilder","TupleSchemaBuilder","RecordSchemaBuilder","UnionSchemaBuilder","FunctionSchemaBuilder","AnySchemaBuilder","PromiseSchemaBuilder","GenericSchemaBuilder","builderFactories","string","number","boolean","date","object","array","tuple","record","union","func","any","promise","generic","METHOD_LITERAL_BRAND","EXTRA_TYPE_BRAND","RESERVED_METHODS","defineExtension","config","wrappedConfig","builderName","builderClasses","methods","methodName","origMethod","args","result","withExtensions","extensions","methodsByBuilder","ext","extMethods","factories","builderFactories","BaseClass","ExtendedClass","props","methodFn","original"]}
@@ -1,2 +0,0 @@
1
- import{c as f,d as k,f as S}from"./chunk-REYZ7G7J.js";var O=class{#e;#t;#n=[];#a=[];get seenValue(){let e=this.#e[f].getValue(this.#t);return e.success?e.value:void 0}get errors(){return this.#n}get isValid(){return this.#n.length===0&&this.getChildErrors().length===0}getChildErrors(){return this.#a}get descriptor(){return this.#e[f]}constructor(e,r,t){if(!b.isValidPropertyDescriptor(e))throw new Error("Invalid property descriptor");this.#e=e,this.#n=Array.isArray(t)?[...t]:[],this.#t=r}addError(e){this.#n.push(e)}addChildError(e){this.#a.push(e)}toJSON(){return{isValid:this.isValid,errors:this.errors}}};var V="must be an object",b=class p extends S{#e={};#t=!1;#n=[];#a=[];[k]=!0;#s=new WeakMap;static create(e){return new p({type:"object",...e})}createFromProps(e){return p.create(e)}constructor(e){super(e),typeof e.properties=="object"&&e.properties&&(this.#e=e.properties,this.#n=Object.keys(e.properties)),typeof e.acceptUnknownProps=="boolean"&&(this.#t=e.acceptUnknownProps),Array.isArray(e.constructorSchemas)&&(this.#a=e.constructorSchemas.filter(r=>r instanceof S))}introspect(){return{...super.introspect(),properties:{...this.#e},acceptUnknownProps:this.#t,constructorSchemas:[...this.#a]}}required(e){return super.required(e)}optional(){return super.optional()}default(e){return super.default(e)}clearDefault(){return super.clearDefault()}brand(e){return super.brand(e)}readonly(){return super.readonly()}#i(e){p.isValidPropertyDescriptor(e?.context?.rootPropertyDescriptor)||(e.context.rootPropertyDescriptor=p.getPropertiesFor(this)),p.isValidPropertyDescriptor(e.context.currentPropertyDescriptor)||(e.context.currentPropertyDescriptor=e.context.rootPropertyDescriptor),!e.context.rootValidationObject&&e.transaction?.object?.validatedObject&&(e.context.rootValidationObject=e.transaction.object.validatedObject)}preValidateSync(e,r){let t=super.preValidateSync(e,r);return this.#i(t),t}async preValidateAsync(e,r){let t=await super.preValidateAsync(e,r);return this.#i(t),t}#o(e){let{valid:r,context:t,transaction:n,errors:a}=e,s=new WeakMap,y=new Set,{doNotStopOnFirstError:o,rootValidationObject:i}=t,l=t.rootPropertyDescriptor,u=t.currentPropertyDescriptor,P=(h,m,R)=>{if(!p.isValidPropertyDescriptor(h))throw new Error("invalid property descriptor");let g=s.has(h)?s.get(h):null;if(g||(g=new O(h,i),s.set(h,g)),g.addError(m),y.add(g),R&&p.isValidPropertyDescriptor(R)){let j=s.has(R)?s.get(R):null;j||(j=new O(R,i),s.set(R,j)),j.addChildError(g)}},d=(h=>{let m=typeof h=="function"?h(u):u;if(!p.isValidPropertyDescriptor(m))throw new Error("invalid property descriptor");return s.has(m)||s.set(m,new O(m,i)),s.get(m)}),c=()=>[...y].filter(h=>h.errors.length>0),T=e.errors||[],E=h=>{if(typeof h.property=="function"&&p.isValidPropertyDescriptor(u)){let m=h.property(u);if(p.isValidPropertyDescriptor(m)){P(m,h.message,u);return}}p.isValidPropertyDescriptor(u)&&P(u,h.message)};if(!r&&!o&&a){for(let h of a)E(h);return{earlyReturn:!0,result:{valid:r,errors:a,getErrorsFor:d,getInvalidProperties:c}}}if(o&&a)for(let h of a)E(h);let{object:{validatedObject:x}}=n;if(typeof x>"u"&&!this.isRequired||x===null&&(!this.isRequired||this.isNullable))return{earlyReturn:!0,result:{valid:!0,object:n.commit().validatedObject,getErrorsFor:d,getInvalidProperties:c}};if(typeof x!="object"||x===null)return T.length===0&&(T.push({message:V}),P(u,V)),n&&n.rollback(),{earlyReturn:!0,result:{valid:!1,errors:o?T:[T[0]],getErrorsFor:d,getInvalidProperties:c}};let w=this.#n,D=Object.keys(x);if(w.length===0){if(D.length===0)return o&&T.length>0?{earlyReturn:!0,result:{valid:!1,errors:T,getErrorsFor:d,getInvalidProperties:c}}:(n&&n.commit().validatedObject,{earlyReturn:!0,result:{valid:!0,object:{},getErrorsFor:d,getInvalidProperties:c}});if(!this.#t){for(let h=0;h<D.length;h++){let m=`unknown property '${D[h]}'`;if(T.push({message:m}),!o)break}return n&&n.rollback(),{earlyReturn:!0,result:{valid:!1,errors:o?T:[T[0]],getErrorsFor:d,getInvalidProperties:c}}}return n&&n.commit(),{earlyReturn:!0,result:{valid:!0,object:{...x},getErrorsFor:d,getInvalidProperties:c}}}return{earlyReturn:!1,errors:T,objToValidate:x,propKeys:w,objKeys:D,addErrorFor:P,getErrorsFor:d,getInvalidProperties:c,doNotStopOnFirstError:!!o,rootPropertyDescriptor:l,currentPropertyDescriptor:u,validationTransaction:n}}#p(e,r){let{objToValidate:t,objKeys:n,addErrorFor:a,getErrorsFor:s,getInvalidProperties:y,doNotStopOnFirstError:o,currentPropertyDescriptor:i,validationTransaction:l}=e,u=e.errors,P=!1;for(let{result:d}of r)if(!d.valid&&(P=!0,Array.isArray(d.errors)))for(let c of d.errors)u.push(c);for(let d=0;d<n.length;d++){let c=n[d];if(!(c in this.#e)&&!this.#t){let T=`unknown property '${c}'`;if(u.push({message:T}),a(i,T),!o)return l&&l.rollback(),{valid:!1,errors:[u[0]],getErrorsFor:s,getInvalidProperties:y}}}if(!P&&u.length===0){let d={};for(let{key:c,result:T}of r)d[c]=T.object;if(this.#t)for(let c of n)c in this.#e||(d[c]=t[c]);return{valid:!0,object:d,getErrorsFor:s,getInvalidProperties:y}}for(let{key:d,result:c}of r)if(!c.valid){let T=i[d];if(typeof c.getErrorsFor=="function"&&p.isValidPropertyDescriptor(T)){if(p.#c(c,T,a),Array.isArray(c.__externErrorPropertyNames)&&Array.isArray(c.errors))for(let E of c.errors)a(T,E.message,i)}else if(Array.isArray(c.errors)&&p.isValidPropertyDescriptor(T))for(let E of c.errors)a(T,E.message)}return l.rollback(),{valid:!1,errors:o?u:u[0]?[u[0]]:[],getErrorsFor:s,getInvalidProperties:y}}addValidator(e,r){return super.addValidator(e,r)}validate(e,r){return super.validate(e,r)}async validateAsync(e,r){return super.validateAsync(e,r)}_validate(e,r){if(this.canSkipPreValidation&&!r?.doNotStopOnFirstError&&!r?.rootPropertyDescriptor){if(typeof e>"u"||e===null)if(typeof e>"u"&&this.hasDefault)e=this.resolveDefaultValue();else if(!this.isRequired||e===null&&this.isNullable){let t=this;return{valid:!0,object:e,getErrorsFor(n){return t.#r(e,r).getErrorsFor(n)},getInvalidProperties(){return t.#r(e,r).getInvalidProperties()}}}else{let t=this;return{valid:!1,errors:[{message:this.getValidationErrorMessageSync(this.requiredErrorMessage,e)}],getErrorsFor(n){return t.#r(e,r).getErrorsFor(n)},getInvalidProperties(){return t.#r(e,r).getInvalidProperties()}}}else if(typeof e=="object"){let t=this.#n;if(!this.#t){let s=Object.keys(e);for(let y=0;y<s.length;y++)if(!(s[y]in this.#e)){let o=this;return{valid:!1,errors:[{message:`unknown property '${s[y]}'`}],getErrorsFor(i){return o.#r(e,r).getErrorsFor(i)},getInvalidProperties(){return o.#r(e,r).getInvalidProperties()}}}}let n={};for(let s=0;s<t.length;s++){let y=t[s],o=this.#e[y].validate(e[y]);if(!o.valid){let i=this;return{valid:!1,errors:o.errors&&o.errors.length>0?[o.errors[0]]:[],getErrorsFor(l){return i.#r(e,r).getErrorsFor(l)},getInvalidProperties(){return i.#r(e,r).getInvalidProperties()}}}n[y]=o.object}if(this.#t){let s=Object.keys(e);for(let y=0;y<s.length;y++)s[y]in this.#e||(n[s[y]]=e[s[y]])}let a=this;return{valid:!0,object:n,getErrorsFor(s){return a.#r(e,r).getErrorsFor(s)},getInvalidProperties(){return a.#r(e,r).getInvalidProperties()}}}}return this.#r(e,r)}#r(e,r){let t=this.#o(this.preValidateSync(e,r));if(t.earlyReturn)return t.result;let{propKeys:n,objToValidate:a,doNotStopOnFirstError:s,rootPropertyDescriptor:y,currentPropertyDescriptor:o}=t,i=[];for(let l of n){let u=this.#e[l].validate(a[l],{...r,rootPropertyDescriptor:y,currentPropertyDescriptor:o[l]});if(i.push({key:l,result:u}),!u.valid&&!s)break}return this.#p(t,i)}async _validateAsync(e,r){let t=this.#o(await this.preValidateAsync(e,r));if(t.earlyReturn)return t.result;let{propKeys:n,objToValidate:a,doNotStopOnFirstError:s,rootPropertyDescriptor:y,currentPropertyDescriptor:o}=t,i=[];if(s){let l=await Promise.all(n.map(async u=>{let P=await this.#e[u].validateAsync(a[u],{...r,rootPropertyDescriptor:y,currentPropertyDescriptor:o[u]});return{key:u,result:P}}));i.push(...l)}else for(let l of n){let u=await this.#e[l].validateAsync(a[l],{...r,rootPropertyDescriptor:y,currentPropertyDescriptor:o[l]});if(i.push({key:l,result:u}),!u.valid)break}return this.#p(t,i)}acceptUnknownProps(){return this.createFromProps({...this.introspect(),acceptUnknownProps:!0})}notAcceptUnknownProps(){return this.createFromProps({...this.introspect(),acceptUnknownProps:!1})}hasType(e){return this.createFromProps({...this.introspect()})}clearHasType(){return this.createFromProps({...this.introspect()})}addConstructor(e){if(!(e instanceof S))throw new Error("schema must be an instance of the SchemaBuilder class");return this.createFromProps({...this.introspect(),constructorSchemas:[...this.#a,e]})}clearConstructors(){return this.createFromProps({...this.introspect(),constructorSchemas:[]})}addProp(e,r){if(typeof e!="string"||!e)throw new Error("propName must be a non empty string");if(e in this.#e)throw new Error(`Property ${e} already exists`);if(!(r instanceof S))throw new Error("schema must be an instance of the SchemaBuilder class");return this.createFromProps({...this.introspect(),properties:{...this.introspect().properties,[e]:r}})}optimize(){return this.createFromProps({...this.introspect()})}addProps(e){if(e instanceof p)return this.addProps(e.introspect().properties);if(typeof e!="object")throw new Error("props should be an object");if(e===null)throw new Error("props should not be null");let r={...this.#e};for(let t in e){if(t in this.#e)throw new Error(`property '${t}' already exists`);if(!(e[t]instanceof S))throw new Error(`${t} is not a SchemaBuilder`);r[t]=e[t]}return this.createFromProps({...this.introspect(),properties:r})}omit(e){if(typeof e=="string"){let r=e;if(!r||!(r in this.#e))throw new Error(`property ${r.toString()} does not exists in the schema`);return this.createFromProps({...this.introspect(),properties:(()=>{let t={...this.#e};return delete t[r],t})()})}else if(Array.isArray(e)){let r=e,t=new Map;if(r.forEach(a=>{if(typeof a!="string"||!a)throw new Error("property name must be a string");if(!(a in this.#e))throw new Error(`property ${a.toString()} does not exists in the schema`);t.set(a.toString(),!0)}),t.size===0)throw new Error("please provide at least one property to omit");let n={...this.introspect()};for(let a of t.keys())delete n.properties[a];return this.createFromProps(n)}else if(e instanceof p){let r={...e.introspect().properties},t={...this.introspect()};for(let n in r)n in t.properties&&delete t.properties[n];return this.createFromProps(t)}throw new Error("this parameter type is not supported")}intersect(e){if(!(e instanceof p))throw new Error("schema must be an instance of the ObjectSchemaBuilder class");let r=e.introspect().properties,t=this.introspect(),n=Object.keys(t.properties).reduce((a,s)=>(a[s]=s in r?r[s]:t.properties[s],a),{});return this.createFromProps({...this.introspect(),properties:n})}partial(e){if(typeof e>"u"||e===null)return this.createFromProps({...this.introspect(),properties:Object.keys(this.#e).reduce((r,t)=>(r[t]=this.#e[t].optional(),r),{})});if(Array.isArray(e)){let r=e;if(r.length===0)throw new Error("properties cannot be empty");let t={...this.introspect()};return r.forEach(n=>{if(typeof n!="string")throw new Error("each propery in property list must be as string value");if(!(n in t.properties))throw new Error(`property ${n} does not exists`);t.properties[n]=t.properties[n].optional()}),this.createFromProps(t)}if(typeof e=="string")return this.modifyPropSchema(e,r=>r.optional());throw new Error("expecting string or string[] parameter")}deepPartial(){let e={};for(let r of Object.keys(this.#e)){let t=this.#e[r];t instanceof p?e[r]=t.deepPartial().optional():e[r]=t.optional()}return this.createFromProps({...this.introspect(),properties:e})}pick(e){if(typeof e=="string"){let r=e;if(!r)throw new Error("property cannot be empty");if(!(r in this.#e))throw new Error(`property ${r} does not exists`);return this.createFromProps({...this.introspect(),properties:{[r]:this.#e[r]}})}if(Array.isArray(e)){if(e.length===0)throw new Error("properties must be a non empty erray");let r=e.reduce((t,n)=>{if(typeof n!="string"||!n)throw new Error("each property name must be a non empty string");if(!(n in this.#e))throw new Error(`property ${n} does not exists`);return t[n]=this.#e[n],t},{});return this.createFromProps({...this.introspect(),properties:r})}if(e instanceof p){let t=Object.keys(e.introspect().properties).filter(n=>typeof this.#e[n]<"u");if(t.length===0)throw new Error("there are no common properties in provided schemas");return this.pick(t)}throw new Error("string, array or ObjectSchemaBuilder is expected")}modifyPropSchema(e,r){if(typeof e!="string"||!e)throw new Error("propName must be a non empty string");if(!(e in this.#e))throw new Error(`property ${e} does not exists in the schema`);if(typeof r!="function")throw new Error("callback must be a function");let t=r(this.#e[e]);if(!(t instanceof S))throw new Error("callback must return a SchemaBuilder object");let n={...this.introspect()};return n.properties={...n.properties,[e]:t},this.createFromProps(n)}makePropOptional(e){return this.modifyPropSchema(e,r=>r.optional())}makePropRequired(e){return this.modifyPropSchema(e,r=>r.required())}makeAllPropsOptional(){return this.createFromProps({...this.introspect(),properties:Object.keys(this.#e).reduce((e,r)=>(e[r]=this.#e[r].optional(),e),{})})}makeAllPropsRequired(){return this.createFromProps({...this.introspect(),properties:Object.keys(this.#e).reduce((e,r)=>(e[r]=this.#e[r].required(),e),{})})}static#y(e,r,t,n,a){let s=e.introspect();if(!s.properties)return{};let y=Object.keys(s.properties);if(y.length===0)return{};typeof r!="function"&&(r=i=>i);let o=B((i,l)=>(t||r)(i,l),n,e,a);for(let i of y){let l=s.properties[i];if(l instanceof p){let u=l.introspect().properties;u&&typeof u=="object"&&Object.keys(u).length>0?o[i]=p.#y(l,(P,d)=>{let c=r(P,d);return c?(d&&!c[i]&&(c[i]={}),c[i]):null},r,i,o[f]):o[i]=B(r,i,l,o[f])}else if(l[k]===!0){let u=B(r,i,l,o[f]),P=(d,c)=>{let T=r(d,c);return T?(c&&!T[i]&&(T[i]={}),T[i]):null};o[i]=q(u,P)}else o[i]=B(r,i,l,o[f])}return o}static getPropertiesFor(e){if(!(e instanceof p))throw new Error("schema must be an instance of the ObjectSchemaBuilder class");if(e.#s.has(e))return e.#s.get(e);let r=p.#y(e);return e.#s.set(e,r),r}static isValidPropertyDescriptor(e){return typeof e=="object"&&e!==null&&typeof e[f]=="object"}static#c(e,r,t){let a=p.#l(r).introspect().properties,s;if(a)s=Object.keys(a);else if(Array.isArray(e.__externErrorPropertyNames))s=e.__externErrorPropertyNames;else return;for(let y of s){let o=r[y];if(!p.isValidPropertyDescriptor(o))continue;let i=e.getErrorsFor(()=>o);if(!i.isValid)for(let l of i.errors)t(o,l,r);if(a){let l=a[y];(l instanceof p||l[k]===!0)&&typeof e.getErrorsFor=="function"&&p.isValidPropertyDescriptor(o)&&p.#c(e,o,t)}}}static#l(e){if(!p.isValidPropertyDescriptor(e))throw new Error("descriptor is not a valid property descriptor");return e[f].getSchema()}nullable(){return super.nullable()}notNullable(){return super.notNullable()}},v=(p=>b.create({isRequired:!0,properties:p})),B=(p,e,r,t)=>({[f]:{setValue:(n,a,s)=>{let y=p(n,!!s?.createMissingStructure);return y?(typeof e=="string"&&(y[e]=a),!0):!1},getValue:n=>{let a=p(n,!1);return a?typeof e!="string"?{success:!0,value:a}:Object.hasOwn(a,e)?{success:!0,value:a[e]}:{success:!1}:{success:!1}},getSchema:()=>r,parent:t,propertyName:e,toJsonPointer:()=>{let n=[];typeof e=="string"&&n.push(e.replace(/~/g,"~0").replace(/\//g,"~1"));let a=t;for(;a;)typeof a.propertyName=="string"&&n.push(a.propertyName.replace(/~/g,"~0").replace(/\//g,"~1")),a=a.parent;return n.reverse(),n.length>0?"/"+n.join("/"):""}}}),q=(p,e)=>new Proxy(p,{get(r,t,n){if(t===f)return r[f];if(typeof t=="string"&&!(t in r)){let a=B(e,t,void 0,r[f]),s=(y,o)=>{let i=e(y,o);return i!=null&&typeof i=="object"?(o&&!(t in i)&&(i[t]={}),i[t]):null};r[t]=q(a,s)}return Reflect.get(r,t,n)}});v.getPropertiesFor=p=>b.getPropertiesFor(p);v.isValidPropertyDescriptor=b.isValidPropertyDescriptor;export{b as a,v as b};
2
- //# sourceMappingURL=chunk-6LSN7NXQ.js.map