@atproto/lex-schema 0.0.11 → 0.0.13

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 (261) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/dist/core/$type.d.ts +149 -0
  3. package/dist/core/$type.d.ts.map +1 -1
  4. package/dist/core/$type.js +44 -0
  5. package/dist/core/$type.js.map +1 -1
  6. package/dist/core/record-key.d.ts +44 -0
  7. package/dist/core/record-key.d.ts.map +1 -1
  8. package/dist/core/record-key.js +30 -0
  9. package/dist/core/record-key.js.map +1 -1
  10. package/dist/core/result.d.ts +85 -4
  11. package/dist/core/result.d.ts.map +1 -1
  12. package/dist/core/result.js +60 -4
  13. package/dist/core/result.js.map +1 -1
  14. package/dist/core/schema.d.ts +232 -5
  15. package/dist/core/schema.d.ts.map +1 -1
  16. package/dist/core/schema.js +197 -4
  17. package/dist/core/schema.js.map +1 -1
  18. package/dist/core/string-format.d.ts +244 -11
  19. package/dist/core/string-format.d.ts.map +1 -1
  20. package/dist/core/string-format.js +150 -0
  21. package/dist/core/string-format.js.map +1 -1
  22. package/dist/core/types.d.ts +90 -3
  23. package/dist/core/types.d.ts.map +1 -1
  24. package/dist/core/types.js.map +1 -1
  25. package/dist/core/validation-error.d.ts +60 -0
  26. package/dist/core/validation-error.d.ts.map +1 -1
  27. package/dist/core/validation-error.js +60 -0
  28. package/dist/core/validation-error.js.map +1 -1
  29. package/dist/core/validation-issue.d.ts +61 -0
  30. package/dist/core/validation-issue.d.ts.map +1 -1
  31. package/dist/core/validation-issue.js +54 -1
  32. package/dist/core/validation-issue.js.map +1 -1
  33. package/dist/core/validator.d.ts +356 -11
  34. package/dist/core/validator.d.ts.map +1 -1
  35. package/dist/core/validator.js +203 -4
  36. package/dist/core/validator.js.map +1 -1
  37. package/dist/helpers.d.ts +12 -28
  38. package/dist/helpers.d.ts.map +1 -1
  39. package/dist/helpers.js.map +1 -1
  40. package/dist/schema/array.d.ts +46 -0
  41. package/dist/schema/array.d.ts.map +1 -1
  42. package/dist/schema/array.js +16 -1
  43. package/dist/schema/array.js.map +1 -1
  44. package/dist/schema/blob.d.ts +50 -2
  45. package/dist/schema/blob.d.ts.map +1 -1
  46. package/dist/schema/blob.js +44 -2
  47. package/dist/schema/blob.js.map +1 -1
  48. package/dist/schema/boolean.d.ts +29 -0
  49. package/dist/schema/boolean.d.ts.map +1 -1
  50. package/dist/schema/boolean.js +30 -1
  51. package/dist/schema/boolean.js.map +1 -1
  52. package/dist/schema/bytes.d.ts +39 -0
  53. package/dist/schema/bytes.d.ts.map +1 -1
  54. package/dist/schema/bytes.js +34 -1
  55. package/dist/schema/bytes.js.map +1 -1
  56. package/dist/schema/cid.d.ts +39 -0
  57. package/dist/schema/cid.d.ts.map +1 -1
  58. package/dist/schema/cid.js +35 -1
  59. package/dist/schema/cid.js.map +1 -1
  60. package/dist/schema/custom.d.ts +67 -1
  61. package/dist/schema/custom.d.ts.map +1 -1
  62. package/dist/schema/custom.js +55 -0
  63. package/dist/schema/custom.js.map +1 -1
  64. package/dist/schema/dict.d.ts +45 -0
  65. package/dist/schema/dict.d.ts.map +1 -1
  66. package/dist/schema/dict.js +46 -1
  67. package/dist/schema/dict.js.map +1 -1
  68. package/dist/schema/discriminated-union.d.ts +59 -0
  69. package/dist/schema/discriminated-union.d.ts.map +1 -1
  70. package/dist/schema/discriminated-union.js +47 -1
  71. package/dist/schema/discriminated-union.js.map +1 -1
  72. package/dist/schema/enum.d.ts +49 -0
  73. package/dist/schema/enum.d.ts.map +1 -1
  74. package/dist/schema/enum.js +49 -0
  75. package/dist/schema/enum.js.map +1 -1
  76. package/dist/schema/integer.d.ts +43 -0
  77. package/dist/schema/integer.d.ts.map +1 -1
  78. package/dist/schema/integer.js +38 -1
  79. package/dist/schema/integer.js.map +1 -1
  80. package/dist/schema/intersection.d.ts +55 -0
  81. package/dist/schema/intersection.d.ts.map +1 -1
  82. package/dist/schema/intersection.js +50 -0
  83. package/dist/schema/intersection.js.map +1 -1
  84. package/dist/schema/lex-map.d.ts +37 -0
  85. package/dist/schema/lex-map.d.ts.map +1 -0
  86. package/dist/schema/lex-map.js +60 -0
  87. package/dist/schema/lex-map.js.map +1 -0
  88. package/dist/schema/lex-value.d.ts +35 -0
  89. package/dist/schema/lex-value.d.ts.map +1 -0
  90. package/dist/schema/lex-value.js +87 -0
  91. package/dist/schema/lex-value.js.map +1 -0
  92. package/dist/schema/literal.d.ts +45 -0
  93. package/dist/schema/literal.d.ts.map +1 -1
  94. package/dist/schema/literal.js +45 -0
  95. package/dist/schema/literal.js.map +1 -1
  96. package/dist/schema/never.d.ts +43 -0
  97. package/dist/schema/never.d.ts.map +1 -1
  98. package/dist/schema/never.js +44 -1
  99. package/dist/schema/never.js.map +1 -1
  100. package/dist/schema/null.d.ts +30 -0
  101. package/dist/schema/null.d.ts.map +1 -1
  102. package/dist/schema/null.js +31 -1
  103. package/dist/schema/null.js.map +1 -1
  104. package/dist/schema/nullable.d.ts +42 -0
  105. package/dist/schema/nullable.d.ts.map +1 -1
  106. package/dist/schema/nullable.js +42 -0
  107. package/dist/schema/nullable.js.map +1 -1
  108. package/dist/schema/object.d.ts +57 -0
  109. package/dist/schema/object.d.ts.map +1 -1
  110. package/dist/schema/object.js +53 -1
  111. package/dist/schema/object.js.map +1 -1
  112. package/dist/schema/optional.d.ts +43 -0
  113. package/dist/schema/optional.d.ts.map +1 -1
  114. package/dist/schema/optional.js +43 -0
  115. package/dist/schema/optional.js.map +1 -1
  116. package/dist/schema/params.d.ts +96 -12
  117. package/dist/schema/params.d.ts.map +1 -1
  118. package/dist/schema/params.js +155 -21
  119. package/dist/schema/params.js.map +1 -1
  120. package/dist/schema/payload.d.ts +111 -15
  121. package/dist/schema/payload.d.ts.map +1 -1
  122. package/dist/schema/payload.js +73 -3
  123. package/dist/schema/payload.js.map +1 -1
  124. package/dist/schema/permission-set.d.ts +58 -0
  125. package/dist/schema/permission-set.d.ts.map +1 -1
  126. package/dist/schema/permission-set.js +50 -0
  127. package/dist/schema/permission-set.js.map +1 -1
  128. package/dist/schema/permission.d.ts +42 -0
  129. package/dist/schema/permission.d.ts.map +1 -1
  130. package/dist/schema/permission.js +39 -0
  131. package/dist/schema/permission.js.map +1 -1
  132. package/dist/schema/procedure.d.ts +64 -0
  133. package/dist/schema/procedure.d.ts.map +1 -1
  134. package/dist/schema/procedure.js +64 -0
  135. package/dist/schema/procedure.js.map +1 -1
  136. package/dist/schema/query.d.ts +55 -0
  137. package/dist/schema/query.d.ts.map +1 -1
  138. package/dist/schema/query.js +55 -0
  139. package/dist/schema/query.js.map +1 -1
  140. package/dist/schema/record.d.ts +76 -25
  141. package/dist/schema/record.d.ts.map +1 -1
  142. package/dist/schema/record.js +21 -0
  143. package/dist/schema/record.js.map +1 -1
  144. package/dist/schema/ref.d.ts +51 -0
  145. package/dist/schema/ref.d.ts.map +1 -1
  146. package/dist/schema/ref.js +18 -0
  147. package/dist/schema/ref.js.map +1 -1
  148. package/dist/schema/refine.d.ts +58 -9
  149. package/dist/schema/refine.d.ts.map +1 -1
  150. package/dist/schema/refine.js.map +1 -1
  151. package/dist/schema/regexp.d.ts +45 -0
  152. package/dist/schema/regexp.d.ts.map +1 -1
  153. package/dist/schema/regexp.js +46 -1
  154. package/dist/schema/regexp.js.map +1 -1
  155. package/dist/schema/string.d.ts +72 -6
  156. package/dist/schema/string.d.ts.map +1 -1
  157. package/dist/schema/string.js +56 -8
  158. package/dist/schema/string.js.map +1 -1
  159. package/dist/schema/subscription.d.ts +72 -2
  160. package/dist/schema/subscription.d.ts.map +1 -1
  161. package/dist/schema/subscription.js +59 -0
  162. package/dist/schema/subscription.js.map +1 -1
  163. package/dist/schema/token.d.ts +48 -0
  164. package/dist/schema/token.d.ts.map +1 -1
  165. package/dist/schema/token.js +49 -1
  166. package/dist/schema/token.js.map +1 -1
  167. package/dist/schema/typed-object.d.ts +73 -23
  168. package/dist/schema/typed-object.d.ts.map +1 -1
  169. package/dist/schema/typed-object.js +20 -1
  170. package/dist/schema/typed-object.js.map +1 -1
  171. package/dist/schema/typed-ref.d.ts +54 -0
  172. package/dist/schema/typed-ref.d.ts.map +1 -1
  173. package/dist/schema/typed-ref.js +16 -0
  174. package/dist/schema/typed-ref.js.map +1 -1
  175. package/dist/schema/typed-union.d.ts +51 -1
  176. package/dist/schema/typed-union.d.ts.map +1 -1
  177. package/dist/schema/typed-union.js +52 -2
  178. package/dist/schema/typed-union.js.map +1 -1
  179. package/dist/schema/union.d.ts +46 -0
  180. package/dist/schema/union.d.ts.map +1 -1
  181. package/dist/schema/union.js +41 -0
  182. package/dist/schema/union.js.map +1 -1
  183. package/dist/schema/unknown.d.ts +34 -0
  184. package/dist/schema/unknown.d.ts.map +1 -1
  185. package/dist/schema/unknown.js +34 -0
  186. package/dist/schema/unknown.js.map +1 -1
  187. package/dist/schema/with-default.d.ts +45 -0
  188. package/dist/schema/with-default.d.ts.map +1 -1
  189. package/dist/schema/with-default.js +45 -0
  190. package/dist/schema/with-default.js.map +1 -1
  191. package/dist/schema.d.ts +2 -1
  192. package/dist/schema.d.ts.map +1 -1
  193. package/dist/schema.js +2 -1
  194. package/dist/schema.js.map +1 -1
  195. package/dist/util/if-any.d.ts +2 -0
  196. package/dist/util/if-any.d.ts.map +1 -0
  197. package/dist/util/if-any.js +3 -0
  198. package/dist/util/if-any.js.map +1 -0
  199. package/package.json +3 -3
  200. package/src/core/$type.ts +150 -18
  201. package/src/core/record-key.ts +44 -0
  202. package/src/core/result.ts +86 -4
  203. package/src/core/schema.ts +244 -9
  204. package/src/core/string-format.ts +259 -13
  205. package/src/core/types.ts +91 -3
  206. package/src/core/validation-error.ts +60 -0
  207. package/src/core/validation-issue.ts +68 -2
  208. package/src/core/validator.ts +373 -12
  209. package/src/helpers.test.ts +110 -29
  210. package/src/helpers.ts +54 -25
  211. package/src/schema/array.test.ts +94 -79
  212. package/src/schema/array.ts +48 -1
  213. package/src/schema/blob.ts +50 -1
  214. package/src/schema/boolean.ts +31 -1
  215. package/src/schema/bytes.ts +41 -1
  216. package/src/schema/cid.ts +41 -1
  217. package/src/schema/custom.ts +68 -1
  218. package/src/schema/dict.ts +47 -1
  219. package/src/schema/discriminated-union.ts +61 -1
  220. package/src/schema/enum.ts +50 -0
  221. package/src/schema/integer.ts +45 -1
  222. package/src/schema/intersection.ts +56 -0
  223. package/src/schema/{unknown-object.test.ts → lex-map.test.ts} +9 -9
  224. package/src/schema/lex-map.ts +63 -0
  225. package/src/schema/lex-value.test.ts +81 -0
  226. package/src/schema/lex-value.ts +86 -0
  227. package/src/schema/literal.ts +46 -0
  228. package/src/schema/never.ts +45 -1
  229. package/src/schema/null.ts +32 -1
  230. package/src/schema/nullable.ts +43 -0
  231. package/src/schema/object.ts +59 -1
  232. package/src/schema/optional.ts +44 -0
  233. package/src/schema/params.test.ts +133 -38
  234. package/src/schema/params.ts +237 -37
  235. package/src/schema/payload.test.ts +3 -3
  236. package/src/schema/payload.ts +145 -42
  237. package/src/schema/permission-set.ts +58 -0
  238. package/src/schema/permission.ts +42 -0
  239. package/src/schema/procedure.ts +64 -0
  240. package/src/schema/query.ts +55 -0
  241. package/src/schema/record.ts +82 -16
  242. package/src/schema/ref.ts +52 -0
  243. package/src/schema/refine.ts +58 -9
  244. package/src/schema/regexp.ts +47 -1
  245. package/src/schema/string.test.ts +99 -2
  246. package/src/schema/string.ts +108 -15
  247. package/src/schema/subscription.ts +72 -2
  248. package/src/schema/token.ts +50 -1
  249. package/src/schema/typed-object.ts +81 -16
  250. package/src/schema/typed-ref.ts +55 -0
  251. package/src/schema/typed-union.ts +58 -3
  252. package/src/schema/union.ts +47 -0
  253. package/src/schema/unknown.ts +35 -0
  254. package/src/schema/with-default.ts +46 -0
  255. package/src/schema.ts +2 -1
  256. package/src/util/if-any.ts +3 -0
  257. package/dist/schema/unknown-object.d.ts +0 -8
  258. package/dist/schema/unknown-object.d.ts.map +0 -1
  259. package/dist/schema/unknown-object.js +0 -19
  260. package/dist/schema/unknown-object.js.map +0 -1
  261. package/src/schema/unknown-object.ts +0 -19
@@ -4,6 +4,34 @@ exports.ValidationContext = void 0;
4
4
  const result_js_1 = require("./result.js");
5
5
  const validation_error_js_1 = require("./validation-error.js");
6
6
  const validation_issue_js_1 = require("./validation-issue.js");
7
+ /**
8
+ * Manages the state and context for validation operations.
9
+ *
10
+ * The `ValidationContext` class is responsible for:
11
+ * - Tracking the current path in nested structures for error reporting
12
+ * - Collecting validation issues during traversal
13
+ * - Enforcing validation mode (validate vs parse)
14
+ * - Providing factory methods for creating validation results
15
+ *
16
+ * Use the static {@link ValidationContext.validate} method as the primary entry point
17
+ * for validation. This ensures proper mode enforcement and issue aggregation.
18
+ *
19
+ * @example
20
+ * ```typescript
21
+ * // Primary usage via static method
22
+ * const result = ValidationContext.validate(data, schema, { mode: 'parse' })
23
+ *
24
+ * // Within a custom validator implementation
25
+ * class MyValidator implements Validator {
26
+ * validateInContext(input: unknown, ctx: ValidationContext): ValidationResult {
27
+ * if (typeof input !== 'string') {
28
+ * return ctx.issueUnexpectedType(input, 'string')
29
+ * }
30
+ * return ctx.success(input)
31
+ * }
32
+ * }
33
+ * ```
34
+ */
7
35
  class ValidationContext {
8
36
  options;
9
37
  static validate(input, validator, options) {
@@ -13,25 +41,55 @@ class ValidationContext {
13
41
  });
14
42
  return context.validate(input, validator);
15
43
  }
44
+ /**
45
+ * The current path being validated, used for error reporting.
46
+ */
16
47
  currentPath;
48
+ /**
49
+ * Accumulated validation issues collected during traversal.
50
+ */
17
51
  issues = [];
52
+ /**
53
+ * Creates a new validation context with the specified options.
54
+ *
55
+ * @param options - The validation options (path and mode are required)
56
+ */
18
57
  constructor(options) {
19
58
  this.options = options;
20
59
  // Create a copy because we will be mutating the array during validation.
21
60
  this.currentPath = Array.from(options.path);
22
61
  }
62
+ /**
63
+ * Returns a copy of the current validation path.
64
+ *
65
+ * The path represents the location in the data structure being validated,
66
+ * used for constructing meaningful error messages.
67
+ */
23
68
  get path() {
24
69
  return Array.from(this.currentPath);
25
70
  }
71
+ /**
72
+ * Creates a new path by appending segments to the current path.
73
+ *
74
+ * @param path - Optional path segment(s) to append
75
+ * @returns A new path array with the segment(s) appended
76
+ */
26
77
  concatPath(path) {
27
78
  if (path == null)
28
79
  return this.path;
29
80
  return this.currentPath.concat(path);
30
81
  }
31
82
  /**
32
- * This is basically the entry point for validation within a context. Use this
33
- * method instead of using {@link Validator.validateInContext} directly,
34
- * because this method ensures the proper use of {@link ValidationOptions}.
83
+ * Validates input against a validator within this context.
84
+ *
85
+ * This is the primary entry point for validation within a context. Always use
86
+ * this method instead of calling {@link Validator.validateInContext} directly,
87
+ * as this method enforces validation mode rules and handles transformation detection.
88
+ *
89
+ * @typeParam V - The validator type
90
+ * @param input - The value to validate
91
+ * @param validator - The validator to use
92
+ * @returns A validation result with the validated value or error
35
93
  */
36
94
  validate(input, validator) {
37
95
  // This is the only place where validateInContext should be called.
@@ -59,7 +117,37 @@ class ValidationContext {
59
117
  }
60
118
  return result;
61
119
  }
120
+ /**
121
+ * Validates a child property of an object within this context.
122
+ *
123
+ * This method automatically manages the path stack, pushing the property key
124
+ * before validation and popping it afterward. Use this for validating object
125
+ * properties to ensure proper path tracking in error messages.
126
+ *
127
+ * @typeParam I - The input object type
128
+ * @typeParam K - The property key type
129
+ * @typeParam V - The validator type
130
+ * @param input - The parent object containing the property
131
+ * @param key - The property key to validate
132
+ * @param validator - The validator to use for the property value
133
+ * @returns A validation result for the property value
134
+ *
135
+ * @example
136
+ * ```typescript
137
+ * // In a custom object validator
138
+ * const result = ctx.validateChild(input, 'name', stringSchema)
139
+ * // If validation fails, error path will include 'name'
140
+ * ```
141
+ */
62
142
  validateChild(input, key, validator) {
143
+ // @NOTE we could add support for recursive schemas by keeping track of
144
+ // "parent" objects in the context and checking for circular references
145
+ // here. This would allow us to validate recursive structures without
146
+ // hitting maximum call stack errors, and would also allow us to provide
147
+ // better error messages for circular reference issues. However, this is not
148
+ // a priority at the moment as recursive structures are not supported in
149
+ // the context of AT Protocol lexicons, and we can always add this in the
150
+ // future if needed.
63
151
  // Instead of creating a new context, we just push/pop the path segment.
64
152
  this.currentPath.push(key);
65
153
  try {
@@ -69,41 +157,152 @@ class ValidationContext {
69
157
  this.currentPath.length--;
70
158
  }
71
159
  }
160
+ /**
161
+ * Adds a validation issue to the context without immediately failing.
162
+ *
163
+ * Use this method to collect multiple issues during validation before
164
+ * determining the final result. Issues added this way will be included
165
+ * in the final error if validation fails.
166
+ *
167
+ * @param issue - The validation issue to add
168
+ */
72
169
  addIssue(issue) {
73
170
  this.issues.push(issue);
74
171
  }
172
+ /**
173
+ * Creates a successful validation result with the given value.
174
+ *
175
+ * @typeParam V - The value type
176
+ * @param value - The validated value
177
+ * @returns A successful validation result
178
+ */
75
179
  success(value) {
76
180
  return (0, result_js_1.success)(value);
77
181
  }
182
+ /**
183
+ * Creates a failed validation result with the given error.
184
+ *
185
+ * @param reason - The validation error
186
+ * @returns A failed validation result
187
+ */
78
188
  failure(reason) {
79
189
  return (0, result_js_1.failure)(reason);
80
190
  }
191
+ /**
192
+ * Creates a failed validation result from a single issue.
193
+ *
194
+ * Any previously accumulated issues in the context are included in the error.
195
+ *
196
+ * @param issue - The validation issue that caused the failure
197
+ * @returns A failed validation result
198
+ */
81
199
  issue(issue) {
82
200
  return this.failure(new validation_error_js_1.ValidationError([...this.issues, issue]));
83
201
  }
202
+ /**
203
+ * Creates a failure for an invalid value that doesn't match expected values.
204
+ *
205
+ * @param input - The actual value that was received
206
+ * @param values - The expected valid values
207
+ * @returns A failed validation result with an invalid value issue
208
+ */
84
209
  issueInvalidValue(input, values) {
85
210
  return this.issue(new validation_issue_js_1.IssueInvalidValue(this.path, input, values));
86
211
  }
212
+ /**
213
+ * Creates a failure for an invalid type.
214
+ *
215
+ * @param input - The actual value that was received
216
+ * @param expected - An array of expected type names
217
+ * @returns A failed validation result with an invalid type issue
218
+ */
87
219
  issueInvalidType(input, expected) {
88
- return this.issue(new validation_issue_js_1.IssueInvalidType(this.path, input, [expected]));
220
+ return this.issue(new validation_issue_js_1.IssueInvalidType(this.path, input, expected));
221
+ }
222
+ /**
223
+ * Creates a failure for an invalid type.
224
+ *
225
+ * @param input - The actual value that was received
226
+ * @param expected - The expected type name
227
+ * @returns A failed validation result with an invalid type issue
228
+ */
229
+ issueUnexpectedType(input, expected) {
230
+ return this.issueInvalidType(input, [expected]);
89
231
  }
232
+ /**
233
+ * Creates a failure for a missing required key in an object.
234
+ *
235
+ * @param input - The object missing the required key
236
+ * @param key - The name of the required key
237
+ * @returns A failed validation result with a required key issue
238
+ */
90
239
  issueRequiredKey(input, key) {
91
240
  return this.issue(new validation_issue_js_1.IssueRequiredKey(this.path, input, key));
92
241
  }
242
+ /**
243
+ * Creates a failure for an invalid string format.
244
+ *
245
+ * @param input - The actual value that was received
246
+ * @param format - The expected format name (e.g., 'did', 'handle', 'uri')
247
+ * @param msg - Optional additional message describing the format error
248
+ * @returns A failed validation result with an invalid format issue
249
+ */
93
250
  issueInvalidFormat(input, format, msg) {
94
251
  return this.issue(new validation_issue_js_1.IssueInvalidFormat(this.path, input, format, msg));
95
252
  }
253
+ /**
254
+ * Creates a failure for a value that exceeds a maximum constraint.
255
+ *
256
+ * @param input - The actual value that was received
257
+ * @param type - The type of measurement (e.g., 'string', 'array', 'bytes')
258
+ * @param max - The maximum allowed value
259
+ * @param actual - The actual measured value
260
+ * @returns A failed validation result with a too big issue
261
+ */
96
262
  issueTooBig(input, type, max, actual) {
97
263
  return this.issue(new validation_issue_js_1.IssueTooBig(this.path, input, max, type, actual));
98
264
  }
265
+ /**
266
+ * Creates a failure for a value that is below a minimum constraint.
267
+ *
268
+ * @param input - The actual value that was received
269
+ * @param type - The type of measurement (e.g., 'string', 'array', 'bytes')
270
+ * @param min - The minimum required value
271
+ * @param actual - The actual measured value
272
+ * @returns A failed validation result with a too small issue
273
+ */
99
274
  issueTooSmall(input, type, min, actual) {
100
275
  return this.issue(new validation_issue_js_1.IssueTooSmall(this.path, input, min, type, actual));
101
276
  }
277
+ /**
278
+ * Creates a failure for an invalid property value within an object.
279
+ *
280
+ * This is a convenience method that automatically extracts the property value
281
+ * and constructs the appropriate path.
282
+ *
283
+ * @typeParam I - The input object type
284
+ * @param input - The object containing the invalid property
285
+ * @param property - The property key with the invalid value
286
+ * @param values - The expected valid values
287
+ * @returns A failed validation result with an invalid value issue at the property path
288
+ */
102
289
  issueInvalidPropertyValue(input, property, values) {
103
290
  const value = input[property];
104
291
  const path = this.concatPath(property);
105
292
  return this.issue(new validation_issue_js_1.IssueInvalidValue(path, value, values));
106
293
  }
294
+ /**
295
+ * Creates a failure for an invalid property type within an object.
296
+ *
297
+ * This is a convenience method that automatically extracts the property value
298
+ * and constructs the appropriate path.
299
+ *
300
+ * @typeParam I - The input object type
301
+ * @param input - The object containing the invalid property
302
+ * @param property - The property key with the invalid type
303
+ * @param expected - The expected type name
304
+ * @returns A failed validation result with an invalid type issue at the property path
305
+ */
107
306
  issueInvalidPropertyType(input, property, expected) {
108
307
  const value = input[property];
109
308
  const path = this.concatPath(property);
@@ -1 +1 @@
1
- {"version":3,"file":"validator.js","sourceRoot":"","sources":["../../src/core/validator.ts"],"names":[],"mappings":";;;AACA,2CAA4E;AAC5E,+DAAuD;AACvD,+DAS8B;AAuE9B,MAAa,iBAAiB;IAmCP;IAfrB,MAAM,CAAC,QAAQ,CACb,KAAc,EACd,SAAY,EACZ,OAA2B;QAE3B,MAAM,OAAO,GAAG,IAAI,iBAAiB,CAAC;YACpC,IAAI,EAAE,OAAO,EAAE,IAAI,IAAI,EAAE;YACzB,IAAI,EAAE,OAAO,EAAE,IAAI,IAAI,UAAU;SAClC,CAAC,CAAA;QACF,OAAO,OAAO,CAAC,QAAQ,CAAC,KAAK,EAAE,SAAS,CAAC,CAAA;IAC3C,CAAC;IAEkB,WAAW,CAAe;IAC1B,MAAM,GAAY,EAAE,CAAA;IAEvC,YAAqB,OAAoC;QAApC,YAAO,GAAP,OAAO,CAA6B;QACvD,yEAAyE;QACzE,IAAI,CAAC,WAAW,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C;CACF;AA5KD,8CA4KC","sourcesContent":["import { PropertyKey } from './property-key.js'\nimport { ResultFailure, ResultSuccess, failure, success } from './result.js'\nimport { ValidationError } from './validation-error.js'\nimport {\n Issue,\n IssueInvalidFormat,\n IssueInvalidType,\n IssueInvalidValue,\n IssueRequiredKey,\n IssueTooBig,\n IssueTooSmall,\n MeasurableType,\n} from './validation-issue.js'\n\nexport type ValidationSuccess<Value = unknown> = ResultSuccess<Value>\nexport type ValidationFailure = ResultFailure<ValidationError>\nexport type ValidationResult<Value = unknown> =\n | ValidationSuccess<Value>\n | ValidationFailure\n\nexport type InferInput<V extends Validator> = V['__lex']['input']\nexport type InferOutput<V extends Validator> = V['__lex']['output']\n\nexport type { InferInput as Infer }\n\nexport interface Validator<TInput = unknown, TOutput = TInput> {\n /**\n * This property is used for type inference purposes and does not actually\n * exist at runtime.\n *\n * @deprecated **INTERNAL API, DO NOT USE**.\n */\n readonly ['__lex']: {\n /** @internal The inferred validation type */\n input: TInput\n /** @internal The inferred parse type */\n output: TOutput\n }\n\n /**\n * @internal **INTERNAL API**: use {@link ValidationContext.validate} instead\n *\n * This method is implemented by subclasses to perform transformation and\n * validation of the input value. Do not call this method directly; as the\n * {@link ValidationContext.options.mode} option will **not** be enforced. See\n * {@link ValidationContext.validate} for details. When delegating validation\n * from one validator sub-class implementation to another schema,\n * {@link ValidationContext.validate} must be used instead of calling\n * {@link Validator.validateInContext}. This will allow to stop the validation\n * process if the value was transformed (by the other schema) but\n * transformations are not allowed.\n *\n * By convention, the {@link ValidationResult} must return the original input\n * value if validation was successful and no transformation was applied (i.e.\n * the input already conformed to the schema). If a default value, or any\n * other transformation was applied, the returned value can be different from\n * the input.\n *\n * This convention allows the {@link Validator.check check} and\n * {@link Validator.assert assert} methods to check whether the input value\n * exactly matches the schema (without defaults or transformations), by\n * checking if the returned value is strictly equal to the input.\n *\n * @see {@link ValidationContext.validate}\n */\n validateInContext(input: unknown, ctx: ValidationContext): ValidationResult\n}\n\nexport type ValidationOptions = {\n /**\n * When set to `\"validate\"` (default), the result of validation must be\n * strictly equal to the input value (i.e. no transformation, such as applying\n * default values, is allowed).\n */\n mode?: 'validate' | 'parse'\n\n /**\n * The path to the value being validated. This is used to provide more\n * context in validation issues.\n */\n path?: readonly PropertyKey[]\n}\n\nexport class ValidationContext {\n static validate<V extends Validator>(\n input: unknown,\n validator: V,\n options: ValidationOptions & {\n mode: 'parse'\n },\n ): ValidationResult<InferOutput<V>>\n static validate<V extends Validator, I = unknown>(\n input: I,\n validator: V,\n options?: ValidationOptions & {\n mode?: 'validate'\n },\n ): ValidationResult<I & InferInput<V>>\n static validate<V extends Validator>(\n input: unknown,\n validator: V,\n options?: ValidationOptions,\n ): ValidationResult<InferOutput<V> | InferInput<V>>\n static validate<V extends Validator>(\n input: unknown,\n validator: V,\n options?: ValidationOptions,\n ): ValidationResult<InferOutput<V> | InferInput<V>> {\n const context = new ValidationContext({\n path: options?.path ?? [],\n mode: options?.mode ?? 'validate',\n })\n return context.validate(input, validator)\n }\n\n protected readonly currentPath: PropertyKey[]\n protected readonly issues: Issue[] = []\n\n constructor(readonly options: Required<ValidationOptions>) {\n // Create a copy because we will be mutating the array during validation.\n this.currentPath = Array.from(options.path)\n }\n\n get path() {\n return Array.from(this.currentPath)\n }\n\n concatPath(path?: PropertyKey | readonly PropertyKey[]) {\n if (path == null) return this.path\n return this.currentPath.concat(path)\n }\n\n /**\n * This is basically the entry point for validation within a context. Use this\n * method instead of using {@link Validator.validateInContext} directly,\n * because this method ensures the proper use of {@link ValidationOptions}.\n */\n validate<V extends Validator>(\n input: unknown,\n validator: V,\n ): ValidationResult<InferInput<V>> {\n // This is the only place where validateInContext should be called.\n const result = validator.validateInContext(input, this)\n\n if (result.success) {\n if (this.issues.length > 0) {\n // Validator returned a success but issues were added via the context.\n // This means the overall validation failed.\n return failure(new ValidationError(Array.from(this.issues)))\n }\n\n if (this.options.mode !== 'parse' && !Object.is(result.value, input)) {\n // If the value changed, it means that a default (or some other\n // transformation) was applied, meaning that the original value did\n // *not* match the (output) schema. When not in \"parse\" mode, we\n // consider this a failure.\n\n // This check is the reason why Validator.validateInContext should not\n // be used directly, and ValidatorContext.validate should be used\n // instead, even when delegating validation from one validator to\n // another.\n\n // This if block comes before the next one because 'this.issues' will\n // end-up being appended to the returned ValidationError (see the\n // \"failure\" method below), resulting in a more complete error report.\n return this.issueInvalidValue(input, [result.value])\n }\n }\n\n return result as ValidationResult<InferInput<V>>\n }\n\n validateChild<\n I extends object,\n K extends PropertyKey & keyof I,\n V extends Validator,\n >(input: I, key: K, validator: V): ValidationResult<InferInput<V>> {\n // Instead of creating a new context, we just push/pop the path segment.\n this.currentPath.push(key)\n try {\n return this.validate(input[key], validator)\n } finally {\n this.currentPath.length--\n }\n }\n\n addIssue(issue: Issue): void {\n this.issues.push(issue)\n }\n\n success<V>(value: V): ValidationResult<V> {\n return success(value)\n }\n\n failure(reason: ValidationError): ValidationFailure {\n return failure(reason)\n }\n\n issue(issue: Issue) {\n return this.failure(new ValidationError([...this.issues, issue]))\n }\n\n issueInvalidValue(input: unknown, values: readonly unknown[]) {\n return this.issue(new IssueInvalidValue(this.path, input, values))\n }\n\n issueInvalidType(input: unknown, expected: string) {\n return this.issue(new IssueInvalidType(this.path, input, [expected]))\n }\n\n issueRequiredKey(input: object, key: PropertyKey) {\n return this.issue(new IssueRequiredKey(this.path, input, key))\n }\n\n issueInvalidFormat(input: unknown, format: string, msg?: string) {\n return this.issue(new IssueInvalidFormat(this.path, input, format, msg))\n }\n\n issueTooBig(\n input: unknown,\n type: MeasurableType,\n max: number,\n actual: number,\n ) {\n return this.issue(new IssueTooBig(this.path, input, max, type, actual))\n }\n\n issueTooSmall(\n input: unknown,\n type: MeasurableType,\n min: number,\n actual: number,\n ) {\n return this.issue(new IssueTooSmall(this.path, input, min, type, actual))\n }\n\n issueInvalidPropertyValue<I>(\n input: I,\n property: keyof I & PropertyKey,\n values: readonly unknown[],\n ) {\n const value = input[property]\n const path = this.concatPath(property)\n return this.issue(new IssueInvalidValue(path, value, values))\n }\n\n issueInvalidPropertyType<I>(\n input: I,\n property: keyof I & PropertyKey,\n expected: string,\n ) {\n const value = input[property]\n const path = this.concatPath(property)\n return this.issue(new IssueInvalidType(path, value, [expected]))\n }\n}\n\nexport type UnwrapValidator<T extends Validator> = T extends {\n unwrap(): infer U extends Validator\n}\n ? UnwrapValidator<U>\n : T\n\nexport interface WrappedValidator<out Validator> {\n unwrap(): Validator\n}\n"]}
1
+ {"version":3,"file":"validator.js","sourceRoot":"","sources":["../../src/core/validator.ts"],"names":[],"mappings":";;;AACA,2CAA4E;AAC5E,+DAAuD;AACvD,+DAS8B;AAiK9B;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,MAAa,iBAAiB;IA8EP;IA3BrB,MAAM,CAAC,QAAQ,CACb,KAAc,EACd,SAAY,EACZ,OAA2B;QAE3B,MAAM,OAAO,GAAG,IAAI,iBAAiB,CAAC;YACpC,IAAI,EAAE,OAAO,EAAE,IAAI,IAAI,EAAE;YACzB,IAAI,EAAE,OAAO,EAAE,IAAI,IAAI,UAAU;SAClC,CAAC,CAAA;QACF,OAAO,OAAO,CAAC,QAAQ,CAAC,KAAK,EAAE,SAAS,CAAC,CAAA;IAC3C,CAAC;IAED;;OAEG;IACgB,WAAW,CAAe;IAE7C;;OAEG;IACgB,MAAM,GAAY,EAAE,CAAA;IAEvC;;;;OAIG;IACH,YAAqB,OAAoC;QAApC,YAAO,GAAP,OAAO,CAA6B;QACvD,yEAAyE;QACzE,IAAI,CAAC,WAAW,GAAG,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAA;IAC7C,CAAC;IAED;;;;;OAKG;IACH,IAAI,IAAI;QACN,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,CAAA;IACrC,CAAC;IAED;;;;;OAKG;IACH,UAAU,CAAC,IAA2C;QACpD,IAAI,IAAI,IAAI,IAAI;YAAE,OAAO,IAAI,C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,EACR,QAA+B,EAC/B,QAAgB;QAEhB,MAAM,KAAK,GAAG,KAAK,CAAC,QAAQ,CAAC,CAAA;QAC7B,MAAM,IAAI,GAAG,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAA;QACtC,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,sCAAgB,CAAC,IAAI,EAAE,KAAK,EAAE,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAA;IAClE,CAAC;CACF;AAzXD,8CAyXC","sourcesContent":["import { PropertyKey } from './property-key.js'\nimport { ResultFailure, ResultSuccess, failure, success } from './result.js'\nimport { ValidationError } from './validation-error.js'\nimport {\n Issue,\n IssueInvalidFormat,\n IssueInvalidType,\n IssueInvalidValue,\n IssueRequiredKey,\n IssueTooBig,\n IssueTooSmall,\n MeasurableType,\n} from './validation-issue.js'\n\n/**\n * Represents a successful validation result.\n *\n * @typeParam Value - The type of the validated value\n */\nexport type ValidationSuccess<Value = unknown> = ResultSuccess<Value>\n\n/**\n * Represents a failed validation result containing a {@link ValidationError}.\n */\nexport type ValidationFailure = ResultFailure<ValidationError>\n\n/**\n * Discriminated union representing the outcome of a validation operation.\n *\n * Check the `success` property to determine if validation passed or failed:\n * - If `success` is `true`, the `value` property contains the validated data\n * - If `success` is `false`, the `reason` property contains the {@link ValidationError}\n *\n * @typeParam Value - The type of the validated value on success\n *\n * @example\n * ```typescript\n * const result: ValidationResult<string> = schema.safeParse(data)\n * if (result.success) {\n * // result.value is string\n * } else {\n * // result.reason is ValidationError\n * }\n * ```\n */\nexport type ValidationResult<Value = unknown> =\n | ValidationSuccess<Value>\n | ValidationFailure\n\n/**\n * Extracts the input type that a validator accepts.\n *\n * Use this utility type to infer what type a schema will accept during validation.\n *\n * @typeParam V - A validator type\n *\n * @example\n * ```typescript\n * const userSchema = new ObjectSchema({ name: stringSchema, age: numberSchema })\n * type UserInput = InferInput<typeof userSchema>\n * // { name: string; age: number }\n * ```\n */\nexport type InferInput<V extends Validator> = V['__lex']['input']\n\n/**\n * Extracts the output type that a validator produces after parsing.\n *\n * The output type may differ from the input type when the schema applies\n * transformations such as default values or type coercion during parsing.\n *\n * @typeParam V - A validator type\n *\n * @example\n * ```typescript\n * const schema = new StringSchema().default('hello')\n * type Input = InferInput<typeof schema> // string | undefined\n * type Output = InferOutput<typeof schema> // string\n * ```\n */\nexport type InferOutput<V extends Validator> = V['__lex']['output']\n\n/**\n * Alias for {@link InferInput} for convenient type inference.\n *\n * @typeParam V - A validator type\n */\nexport type { InferInput as Infer }\n\nexport interface Validator<TInput = unknown, TOutput = TInput> {\n /**\n * This property is used for type inference purposes and does not actually\n * exist at runtime.\n *\n * @internal\n * @deprecated **INTERNAL API, DO NOT USE**.\n */\n readonly ['__lex']: {\n input: TInput\n output: TOutput\n }\n\n /**\n * @internal **INTERNAL API**: use {@link ValidationContext.validate} instead\n *\n * This method is implemented by subclasses to perform transformation and\n * validation of the input value. Do not call this method directly; as the\n * {@link ValidationContext.options.mode} option will **not** be enforced. See\n * {@link ValidationContext.validate} for details. When delegating validation\n * from one validator sub-class implementation to another schema,\n * {@link ValidationContext.validate} must be used instead of calling\n * {@link Validator.validateInContext}. This will allow to stop the validation\n * process if the value was transformed (by the other schema) but\n * transformations are not allowed.\n *\n * By convention, the {@link ValidationResult} must return the original input\n * value if validation was successful and no transformation was applied (i.e.\n * the input already conformed to the schema). If a default value, or any\n * other transformation was applied, the returned value can be different from\n * the input.\n *\n * This convention allows the {@link Validator.check check} and\n * {@link Validator.assert assert} methods to check whether the input value\n * exactly matches the schema (without defaults or transformations), by\n * checking if the returned value is strictly equal to the input.\n *\n * @see {@link ValidationContext.validate}\n */\n validateInContext(input: unknown, ctx: ValidationContext): ValidationResult\n}\n\n/**\n * Configuration options for validation and parsing operations.\n *\n * @example\n * ```typescript\n * // Validate mode (strict, no transformations)\n * ValidationContext.validate(data, schema, { mode: 'validate' })\n *\n * // Parse mode (allows transformations like defaults)\n * ValidationContext.validate(data, schema, { mode: 'parse' })\n *\n * // With initial path for nested validation\n * ValidationContext.validate(data, schema, { path: ['user', 'profile'] })\n * ```\n */\nexport type ValidationOptions = {\n /**\n * The validation mode determining how transformations are handled.\n *\n * - `\"validate\"` (default): Strict validation where the result must be\n * strictly equal to the input value. No transformations such as applying\n * default values are allowed.\n * - `\"parse\"`: Allows the schema to transform the input value, such as\n * applying default values or performing type coercion.\n */\n mode?: 'validate' | 'parse'\n\n /**\n * The initial path to the value being validated.\n *\n * This is used to provide context in validation issues when validating\n * nested structures. The path is prepended to all issue paths.\n *\n * @example\n * ```typescript\n * // Issues will be reported at paths like \"user.name\" instead of just \"name\"\n * ValidationContext.validate(data, schema, { path: ['user'] })\n * ```\n */\n path?: readonly PropertyKey[]\n}\n\n/**\n * Manages the state and context for validation operations.\n *\n * The `ValidationContext` class is responsible for:\n * - Tracking the current path in nested structures for error reporting\n * - Collecting validation issues during traversal\n * - Enforcing validation mode (validate vs parse)\n * - Providing factory methods for creating validation results\n *\n * Use the static {@link ValidationContext.validate} method as the primary entry point\n * for validation. This ensures proper mode enforcement and issue aggregation.\n *\n * @example\n * ```typescript\n * // Primary usage via static method\n * const result = ValidationContext.validate(data, schema, { mode: 'parse' })\n *\n * // Within a custom validator implementation\n * class MyValidator implements Validator {\n * validateInContext(input: unknown, ctx: ValidationContext): ValidationResult {\n * if (typeof input !== 'string') {\n * return ctx.issueUnexpectedType(input, 'string')\n * }\n * return ctx.success(input)\n * }\n * }\n * ```\n */\nexport class ValidationContext {\n /**\n * Validates input against a validator in parse mode.\n *\n * In parse mode, the schema may transform the input (e.g., apply defaults).\n *\n * @param input - The value to validate\n * @param validator - The validator to use\n * @param options - Validation options with mode set to 'parse'\n * @returns A validation result with the parsed output type\n */\n static validate<V extends Validator>(\n input: unknown,\n validator: V,\n options: ValidationOptions & {\n mode: 'parse'\n },\n ): ValidationResult<InferOutput<V>>\n /**\n * Validates input against a validator in validate mode (default).\n *\n * In validate mode, the result must be strictly equal to the input.\n * No transformations are allowed.\n *\n * @typeParam V - The validator type\n * @typeParam I - The input type\n * @param input - The value to validate\n * @param validator - The validator to use\n * @param options - Optional validation options (defaults to validate mode)\n * @returns A validation result preserving the input type intersected with the schema type\n */\n static validate<V extends Validator, I = unknown>(\n input: I,\n validator: V,\n options?: ValidationOptions & {\n mode?: 'validate'\n },\n ): ValidationResult<I & InferInput<V>>\n /**\n * Validates input against a validator with configurable options.\n *\n * @param input - The value to validate\n * @param validator - The validator to use\n * @param options - Optional validation options\n * @returns A validation result with either the input or output type\n */\n static validate<V extends Validator>(\n input: unknown,\n validator: V,\n options?: ValidationOptions,\n ): ValidationResult<InferOutput<V> | InferInput<V>>\n static validate<V extends Validator>(\n input: unknown,\n validator: V,\n options?: ValidationOptions,\n ): ValidationResult<InferOutput<V> | InferInput<V>> {\n const context = new ValidationContext({\n path: options?.path ?? [],\n mode: options?.mode ?? 'validate',\n })\n return context.validate(input, validator)\n }\n\n /**\n * The current path being validated, used for error reporting.\n */\n protected readonly currentPath: PropertyKey[]\n\n /**\n * Accumulated validation issues collected during traversal.\n */\n protected readonly issues: Issue[] = []\n\n /**\n * Creates a new validation context with the specified options.\n *\n * @param options - The validation options (path and mode are required)\n */\n constructor(readonly options: Required<ValidationOptions>) {\n // Create a copy because we will be mutating the array during validation.\n this.currentPath = Array.from(options.path)\n }\n\n /**\n * Returns a copy of the current validation path.\n *\n * The path represents the location in the data structure being validated,\n * used for constructing meaningful error messages.\n */\n get path() {\n return Array.from(this.currentPath)\n }\n\n /**\n * Creates a new path by appending segments to the current path.\n *\n * @param path - Optional path segment(s) to append\n * @returns A new path array with the segment(s) appended\n */\n concatPath(path?: PropertyKey | readonly PropertyKey[]) {\n if (path == null) return this.path\n return this.currentPath.concat(path)\n }\n\n /**\n * Validates input against a validator within this context.\n *\n * This is the primary entry point for validation within a context. Always use\n * this method instead of calling {@link Validator.validateInContext} directly,\n * as this method enforces validation mode rules and handles transformation detection.\n *\n * @typeParam V - The validator type\n * @param input - The value to validate\n * @param validator - The validator to use\n * @returns A validation result with the validated value or error\n */\n validate<V extends Validator>(\n input: unknown,\n validator: V,\n ): ValidationResult<InferInput<V>> {\n // This is the only place where validateInContext should be called.\n const result = validator.validateInContext(input, this)\n\n if (result.success) {\n if (this.issues.length > 0) {\n // Validator returned a success but issues were added via the context.\n // This means the overall validation failed.\n return failure(new ValidationError(Array.from(this.issues)))\n }\n\n if (this.options.mode !== 'parse' && !Object.is(result.value, input)) {\n // If the value changed, it means that a default (or some other\n // transformation) was applied, meaning that the original value did\n // *not* match the (output) schema. When not in \"parse\" mode, we\n // consider this a failure.\n\n // This check is the reason why Validator.validateInContext should not\n // be used directly, and ValidatorContext.validate should be used\n // instead, even when delegating validation from one validator to\n // another.\n\n // This if block comes before the next one because 'this.issues' will\n // end-up being appended to the returned ValidationError (see the\n // \"failure\" method below), resulting in a more complete error report.\n return this.issueInvalidValue(input, [result.value])\n }\n }\n\n return result as ValidationResult<InferInput<V>>\n }\n\n /**\n * Validates a child property of an object within this context.\n *\n * This method automatically manages the path stack, pushing the property key\n * before validation and popping it afterward. Use this for validating object\n * properties to ensure proper path tracking in error messages.\n *\n * @typeParam I - The input object type\n * @typeParam K - The property key type\n * @typeParam V - The validator type\n * @param input - The parent object containing the property\n * @param key - The property key to validate\n * @param validator - The validator to use for the property value\n * @returns A validation result for the property value\n *\n * @example\n * ```typescript\n * // In a custom object validator\n * const result = ctx.validateChild(input, 'name', stringSchema)\n * // If validation fails, error path will include 'name'\n * ```\n */\n validateChild<\n I extends object,\n K extends PropertyKey & keyof I,\n V extends Validator,\n >(input: I, key: K, validator: V): ValidationResult<InferInput<V>> {\n // @NOTE we could add support for recursive schemas by keeping track of\n // \"parent\" objects in the context and checking for circular references\n // here. This would allow us to validate recursive structures without\n // hitting maximum call stack errors, and would also allow us to provide\n // better error messages for circular reference issues. However, this is not\n // a priority at the moment as recursive structures are not supported in\n // the context of AT Protocol lexicons, and we can always add this in the\n // future if needed.\n\n // Instead of creating a new context, we just push/pop the path segment.\n this.currentPath.push(key)\n try {\n return this.validate(input[key], validator)\n } finally {\n this.currentPath.length--\n }\n }\n\n /**\n * Adds a validation issue to the context without immediately failing.\n *\n * Use this method to collect multiple issues during validation before\n * determining the final result. Issues added this way will be included\n * in the final error if validation fails.\n *\n * @param issue - The validation issue to add\n */\n addIssue(issue: Issue): void {\n this.issues.push(issue)\n }\n\n /**\n * Creates a successful validation result with the given value.\n *\n * @typeParam V - The value type\n * @param value - The validated value\n * @returns A successful validation result\n */\n success<V>(value: V): ValidationResult<V> {\n return success(value)\n }\n\n /**\n * Creates a failed validation result with the given error.\n *\n * @param reason - The validation error\n * @returns A failed validation result\n */\n failure(reason: ValidationError): ValidationFailure {\n return failure(reason)\n }\n\n /**\n * Creates a failed validation result from a single issue.\n *\n * Any previously accumulated issues in the context are included in the error.\n *\n * @param issue - The validation issue that caused the failure\n * @returns A failed validation result\n */\n issue(issue: Issue) {\n return this.failure(new ValidationError([...this.issues, issue]))\n }\n\n /**\n * Creates a failure for an invalid value that doesn't match expected values.\n *\n * @param input - The actual value that was received\n * @param values - The expected valid values\n * @returns A failed validation result with an invalid value issue\n */\n issueInvalidValue(input: unknown, values: readonly unknown[]) {\n return this.issue(new IssueInvalidValue(this.path, input, values))\n }\n\n /**\n * Creates a failure for an invalid type.\n *\n * @param input - The actual value that was received\n * @param expected - An array of expected type names\n * @returns A failed validation result with an invalid type issue\n */\n issueInvalidType(input: unknown, expected: readonly string[]) {\n return this.issue(new IssueInvalidType(this.path, input, expected))\n }\n\n /**\n * Creates a failure for an invalid type.\n *\n * @param input - The actual value that was received\n * @param expected - The expected type name\n * @returns A failed validation result with an invalid type issue\n */\n issueUnexpectedType(input: unknown, expected: string) {\n return this.issueInvalidType(input, [expected])\n }\n\n /**\n * Creates a failure for a missing required key in an object.\n *\n * @param input - The object missing the required key\n * @param key - The name of the required key\n * @returns A failed validation result with a required key issue\n */\n issueRequiredKey(input: object, key: PropertyKey) {\n return this.issue(new IssueRequiredKey(this.path, input, key))\n }\n\n /**\n * Creates a failure for an invalid string format.\n *\n * @param input - The actual value that was received\n * @param format - The expected format name (e.g., 'did', 'handle', 'uri')\n * @param msg - Optional additional message describing the format error\n * @returns A failed validation result with an invalid format issue\n */\n issueInvalidFormat(input: unknown, format: string, msg?: string) {\n return this.issue(new IssueInvalidFormat(this.path, input, format, msg))\n }\n\n /**\n * Creates a failure for a value that exceeds a maximum constraint.\n *\n * @param input - The actual value that was received\n * @param type - The type of measurement (e.g., 'string', 'array', 'bytes')\n * @param max - The maximum allowed value\n * @param actual - The actual measured value\n * @returns A failed validation result with a too big issue\n */\n issueTooBig(\n input: unknown,\n type: MeasurableType,\n max: number,\n actual: number,\n ) {\n return this.issue(new IssueTooBig(this.path, input, max, type, actual))\n }\n\n /**\n * Creates a failure for a value that is below a minimum constraint.\n *\n * @param input - The actual value that was received\n * @param type - The type of measurement (e.g., 'string', 'array', 'bytes')\n * @param min - The minimum required value\n * @param actual - The actual measured value\n * @returns A failed validation result with a too small issue\n */\n issueTooSmall(\n input: unknown,\n type: MeasurableType,\n min: number,\n actual: number,\n ) {\n return this.issue(new IssueTooSmall(this.path, input, min, type, actual))\n }\n\n /**\n * Creates a failure for an invalid property value within an object.\n *\n * This is a convenience method that automatically extracts the property value\n * and constructs the appropriate path.\n *\n * @typeParam I - The input object type\n * @param input - The object containing the invalid property\n * @param property - The property key with the invalid value\n * @param values - The expected valid values\n * @returns A failed validation result with an invalid value issue at the property path\n */\n issueInvalidPropertyValue<I>(\n input: I,\n property: keyof I & PropertyKey,\n values: readonly unknown[],\n ) {\n const value = input[property]\n const path = this.concatPath(property)\n return this.issue(new IssueInvalidValue(path, value, values))\n }\n\n /**\n * Creates a failure for an invalid property type within an object.\n *\n * This is a convenience method that automatically extracts the property value\n * and constructs the appropriate path.\n *\n * @typeParam I - The input object type\n * @param input - The object containing the invalid property\n * @param property - The property key with the invalid type\n * @param expected - The expected type name\n * @returns A failed validation result with an invalid type issue at the property path\n */\n issueInvalidPropertyType<I>(\n input: I,\n property: keyof I & PropertyKey,\n expected: string,\n ) {\n const value = input[property]\n const path = this.concatPath(property)\n return this.issue(new IssueInvalidType(path, value, [expected]))\n }\n}\n\n/**\n * Recursively unwraps a wrapped validator to its innermost validator type.\n *\n * Some validators wrap other validators (e.g., optional, nullable). This type\n * utility recursively unwraps such wrappers to reveal the core validator.\n *\n * @typeParam T - A validator type, possibly wrapped\n *\n * @example\n * ```typescript\n * type Inner = UnwrapValidator<OptionalValidator<NullableValidator<StringSchema>>>\n * // Result: StringSchema\n * ```\n */\nexport type UnwrapValidator<T extends Validator> = T extends {\n unwrap(): infer U extends Validator\n}\n ? UnwrapValidator<U>\n : T\n\n/**\n * Interface for validators that wrap another validator.\n *\n * Implement this interface when creating validators that wrap or modify\n * the behavior of another validator (e.g., optional, nullable, transform).\n *\n * @typeParam Validator - The type of the wrapped validator\n *\n * @example\n * ```typescript\n * class OptionalSchema<V extends Validator> implements WrappedValidator<V> {\n * constructor(private inner: V) {}\n *\n * unwrap(): V {\n * return this.inner\n * }\n * }\n * ```\n */\nexport interface WrappedValidator<out Validator> {\n /**\n * Returns the inner wrapped validator.\n *\n * @returns The wrapped validator\n */\n unwrap(): Validator\n}\n"]}
package/dist/helpers.d.ts CHANGED
@@ -1,6 +1,5 @@
1
- import { LexValue } from '@atproto/lex-data';
2
- import { InferOutput, Restricted, Schema } from './core.js';
3
- import { InferPayload, InferPayloadBody, InferPayloadEncoding, Payload, Procedure, Query, Subscription } from './schema.js';
1
+ import { InferOutput, Restricted } from './core.js';
2
+ import { InferPayload, InferPayloadBody, InferPayloadEncoding, Procedure, Query, Subscription } from './schema.js';
4
3
  export type Main<T> = T | {
5
4
  main: T;
6
5
  };
@@ -13,30 +12,16 @@ export declare function getMain<T extends object>(ns: Main<T>): T;
13
12
  * `ReadableStream`, etc.). This type is a placeholder to represent binary data
14
13
  * when not explicitly provided.
15
14
  */
16
- type BinaryData = Restricted<'Binary data'>;
17
- export type InferMethodParams<M extends Procedure | Query | Subscription> = InferOutput<M['parameters']>;
18
- export type InferMethodInput<M extends Procedure | Query | Subscription, B = BinaryData> = M extends {
19
- input: Payload;
20
- } ? InferPayload<M['input'], B> : undefined;
21
- export type InferMethodInputBody<M extends Procedure | Query | Subscription, B = BinaryData> = M extends {
22
- input: Payload;
23
- } ? InferPayloadBody<M['input'], B> : undefined;
24
- export type InferMethodInputEncoding<M extends Procedure | Query | Subscription> = M extends {
25
- input: Payload;
26
- } ? InferPayloadEncoding<M['input']> : undefined;
27
- export type InferMethodOutput<M extends Procedure | Query | Subscription, B = BinaryData> = M extends {
28
- output: Payload;
29
- } ? InferPayload<M['output'], B> : undefined;
30
- export type InferMethodOutputBody<M extends Procedure | Query | Subscription, B = BinaryData> = M extends {
31
- output: Payload;
32
- } ? InferPayloadBody<M['output'], B> : undefined;
33
- export type InferMethodOutputEncoding<M extends Procedure | Query | Subscription> = M extends {
34
- output: Payload;
35
- } ? InferPayloadEncoding<M['output']> : undefined;
36
- export type InferMethodMessage<M extends Procedure | Query | Subscription> = M extends {
37
- message: Schema;
38
- } ? LexValue & InferOutput<M['message']> : undefined;
39
- export type InferMethodError<M extends Procedure | Query | Subscription> = M extends {
15
+ export type BinaryData = Restricted<'Binary data'>;
16
+ export type InferMethodParams<M extends Procedure | Query | Subscription = Procedure | Query | Subscription> = M extends Procedure<any, infer TParams, any, any, any> ? InferOutput<TParams> : M extends Query<any, infer TParams, any, any> ? InferOutput<TParams> : M extends Subscription<any, infer TParams, any, any> ? InferOutput<TParams> : never;
17
+ export type InferMethodInput<M extends Procedure | Query | Subscription = Procedure | Query | Subscription, B = BinaryData> = M extends Procedure<any, any, infer TInput, any, any> ? InferPayload<TInput, B> : undefined;
18
+ export type InferMethodInputBody<M extends Procedure | Query | Subscription = Procedure | Query | Subscription, B = BinaryData> = M extends Procedure<any, any, infer TInput, any, any> ? InferPayloadBody<TInput, B> : undefined;
19
+ export type InferMethodInputEncoding<M extends Procedure | Query | Subscription = Procedure | Query | Subscription> = M extends Procedure<any, any, infer TInput, any, any> ? InferPayloadEncoding<TInput> : undefined;
20
+ export type InferMethodOutput<M extends Procedure | Query | Subscription = Procedure | Query | Subscription, B = BinaryData> = M extends Procedure<any, any, any, infer TOutput, any> ? InferPayload<TOutput, B> : M extends Query<any, any, infer TOutput, any> ? InferPayload<TOutput, B> : undefined;
21
+ export type InferMethodOutputBody<M extends Procedure | Query | Subscription = Procedure | Query | Subscription, B = BinaryData> = M extends Procedure<any, any, any, infer TOutput, any> ? InferPayloadBody<TOutput, B> : M extends Query<any, any, infer TOutput, any> ? InferPayloadBody<TOutput, B> : undefined;
22
+ export type InferMethodOutputEncoding<M extends Procedure | Query | Subscription = Procedure | Query | Subscription> = M extends Procedure<any, any, any, infer TOutput, any> ? InferPayloadEncoding<TOutput> : M extends Query<any, any, infer TOutput, any> ? InferPayloadEncoding<TOutput> : undefined;
23
+ export type InferMethodMessage<M extends Procedure | Query | Subscription = Procedure | Query | Subscription> = M extends Subscription<any, any, infer TMessage, any> ? InferOutput<TMessage> : undefined;
24
+ export type InferMethodError<M extends Procedure | Query | Subscription = Procedure | Query | Subscription> = M extends {
40
25
  errors: readonly (infer E extends string)[];
41
26
  } ? E : never;
42
27
  export declare const lexErrorDataSchema: import("./schema.js").ObjectSchema<{
@@ -45,5 +30,4 @@ export declare const lexErrorDataSchema: import("./schema.js").ObjectSchema<{
45
30
  }>;
46
31
  readonly message: import("./schema.js").OptionalSchema<import("./schema.js").StringSchema<{}>>;
47
32
  }>;
48
- export {};
49
33
  //# sourceMappingURL=helpers.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../src/helpers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,QAAQ,EAAE,MAAM,mBAAmB,CAAA;AAC1D,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,WAAW,CAAA;AAC3D,OAAO,EACL,YAAY,EACZ,gBAAgB,EAChB,oBAAoB,EACpB,OAAO,EACP,SAAS,EACT,KA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AM,EAAC;IACvC,KAAK,EAAE,IAAA,kBAAM,EAAC,EAAE,SAAS,EAAE,CAAC,EAAE,CAAC;IAC/B,OAAO,EAAE,IAAA,oBAAQ,EAAC,IAAA,kBAAM,GAAE,CAAC;CAC5B,CAAgC,CAAA","sourcesContent":["import { LexErrorData, LexValue } from '@atproto/lex-data'\nimport { InferOutput, Restricted, Schema } from './core.js'\nimport {\n InferPayload,\n InferPayloadBody,\n InferPayloadEncoding,\n Payload,\n Procedure,\n Query,\n Subscription,\n object,\n optional,\n string,\n} from './schema.js'\n\nexport type Main<T> = T | { main: T }\n\nexport function getMain<T extends object>(ns: Main<T>): T {\n return 'main' in ns ? ns.main : ns\n}\n\n/**\n * Every XRPC implementation should translate `application/json` and `text/*`\n * payloads into their native equivalent ({@link LexValue} or string). Binary\n * data payloads, however, can be represented differently depending on the\n * environment and use case (e.g. `Uint8Array`, `Blob`, `Buffer`,\n * `ReadableStream`, etc.). This type is a placeholder to represent binary data\n * when not explicitly provided.\n */\ntype BinaryData = Restricted<'Binary data'>\n\nexport type InferMethodParams<M extends Procedure | Query | Subscription> =\n InferOutput<M['parameters']>\n\nexport type InferMethodInput<\n M extends Procedure | Query | Subscription,\n B = BinaryData,\n> = M extends { input: Payload } ? InferPayload<M['input'], B> : undefined\n\nexport type InferMethodInputBody<\n M extends Procedure | Query | Subscription,\n B = BinaryData,\n> = M extends { input: Payload } ? InferPayloadBody<M['input'], B> : undefined\n\nexport type InferMethodInputEncoding<\n M extends Procedure | Query | Subscription,\n> = M extends { input: Payload } ? InferPayloadEncoding<M['input']> : undefined\n\nexport type InferMethodOutput<\n M extends Procedure | Query | Subscription,\n B = BinaryData,\n> = M extends { output: Payload } ? InferPayload<M['output'], B> : undefined\n\nexport type InferMethodOutputBody<\n M extends Procedure | Query | Subscription,\n B = BinaryData,\n> = M extends { output: Payload } ? InferPayloadBody<M['output'], B> : undefined\n\nexport type InferMethodOutputEncoding<\n M extends Procedure | Query | Subscription,\n> = M extends { output: Payload }\n ? InferPayloadEncoding<M['output']>\n : undefined\n\nexport type InferMethodMessage<\n //\n M extends Procedure | Query | Subscription,\n> = M extends { message: Schema }\n ? LexValue & InferOutput<M['message']>\n : undefined\n\nexport type InferMethodError<\n //\n M extends Procedure | Query | Subscription,\n> = M extends { errors: readonly (infer E extends string)[] } ? E : never\n\nexport const lexErrorDataSchema = object({\n error: string({ minLength: 1 }),\n message: optional(string()),\n}) satisfies Schema<LexErrorData>\n"]}
1
+ {"version":3,"file":"helpers.js","sourceRoot":"","sources":["../src/helpers.ts"],"names":[],"mappings":";;;AAgBA,0BAEC;AAhBD,2CAUoB;AAIpB,SAAgB,OAAO,CAAmB,EAAW;IACnD,OAAO,MAAM,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAA;AACpC,CAAC;AAuFY,QAAA,kBAAkB,GAAG,IAAA,kBAAM,EAAC;IACvC,KAAK,EAAE,IAAA,kBAAM,EAAC,EAAE,SAAS,EAAE,CAAC,EAAE,CAAC;IAC/B,OAAO,EAAE,IAAA,oBAAQ,EAAC,IAAA,kBAAM,GAAE,CAAC;CAC5B,CAAgC,CAAA","sourcesContent":["import { LexErrorData } from '@atproto/lex-data'\nimport { InferOutput, Restricted, Schema } from './core.js'\nimport {\n InferPayload,\n InferPayloadBody,\n InferPayloadEncoding,\n Procedure,\n Query,\n Subscription,\n object,\n optional,\n string,\n} from './schema.js'\n\nexport type Main<T> = T | { main: T }\n\nexport function getMain<T extends object>(ns: Main<T>): T {\n return 'main' in ns ? ns.main : ns\n}\n\n/**\n * Every XRPC implementation should translate `application/json` and `text/*`\n * payloads into their native equivalent ({@link LexValue} or string). Binary\n * data payloads, however, can be represented differently depending on the\n * environment and use case (e.g. `Uint8Array`, `Blob`, `Buffer`,\n * `ReadableStream`, etc.). This type is a placeholder to represent binary data\n * when not explicitly provided.\n */\nexport type BinaryData = Restricted<'Binary data'>\n\nexport type InferMethodParams<\n M extends Procedure | Query | Subscription = Procedure | Query | Subscription,\n> =\n M extends Procedure<any, infer TParams, any, any, any>\n ? InferOutput<TParams>\n : M extends Query<any, infer TParams, any, any>\n ? InferOutput<TParams>\n : M extends Subscription<any, infer TParams, any, any>\n ? InferOutput<TParams>\n : never\n\nexport type InferMethodInput<\n M extends Procedure | Query | Subscription = Procedure | Query | Subscription,\n B = BinaryData,\n> =\n M extends Procedure<any, any, infer TInput, any, any>\n ? InferPayload<TInput, B>\n : undefined\n\nexport type InferMethodInputBody<\n M extends Procedure | Query | Subscription = Procedure | Query | Subscription,\n B = BinaryData,\n> =\n M extends Procedure<any, any, infer TInput, any, any>\n ? InferPayloadBody<TInput, B>\n : undefined\n\nexport type InferMethodInputEncoding<\n M extends Procedure | Query | Subscription = Procedure | Query | Subscription,\n> =\n M extends Procedure<any, any, infer TInput, any, any>\n ? InferPayloadEncoding<TInput>\n : undefined\n\nexport type InferMethodOutput<\n M extends Procedure | Query | Subscription = Procedure | Query | Subscription,\n B = BinaryData,\n> =\n M extends Procedure<any, any, any, infer TOutput, any>\n ? InferPayload<TOutput, B>\n : M extends Query<any, any, infer TOutput, any>\n ? InferPayload<TOutput, B>\n : undefined\n\nexport type InferMethodOutputBody<\n M extends Procedure | Query | Subscription = Procedure | Query | Subscription,\n B = BinaryData,\n> =\n M extends Procedure<any, any, any, infer TOutput, any>\n ? InferPayloadBody<TOutput, B>\n : M extends Query<any, any, infer TOutput, any>\n ? InferPayloadBody<TOutput, B>\n : undefined\n\nexport type InferMethodOutputEncoding<\n M extends Procedure | Query | Subscription = Procedure | Query | Subscription,\n> =\n M extends Procedure<any, any, any, infer TOutput, any>\n ? InferPayloadEncoding<TOutput>\n : M extends Query<any, any, infer TOutput, any>\n ? InferPayloadEncoding<TOutput>\n : undefined\n\nexport type InferMethodMessage<\n M extends Procedure | Query | Subscription = Procedure | Query | Subscription,\n> =\n M extends Subscription<any, any, infer TMessage, any>\n ? InferOutput<TMessage>\n : undefined\n\nexport type InferMethodError<\n //\n M extends Procedure | Query | Subscription = Procedure | Query | Subscription,\n> = M extends { errors: readonly (infer E extends string)[] } ? E : never\n\nexport const lexErrorDataSchema = object({\n error: string({ minLength: 1 }),\n message: optional(string()),\n}) satisfies Schema<LexErrorData>\n"]}
@@ -1,14 +1,60 @@
1
1
  import { InferInput, InferOutput, Schema, ValidationContext, Validator } from '../core.js';
2
+ /**
3
+ * Configuration options for array schema validation.
4
+ *
5
+ * @property minLength - Minimum number of items in the array
6
+ * @property maxLength - Maximum number of items in the array
7
+ */
2
8
  export type ArraySchemaOptions = {
3
9
  minLength?: number;
4
10
  maxLength?: number;
5
11
  };
12
+ /**
13
+ * Schema for validating arrays where all items match a given schema.
14
+ *
15
+ * Validates that the input is an array, checks length constraints, and
16
+ * validates each item against the provided item schema.
17
+ *
18
+ * @template TItem - The validator type for array items
19
+ *
20
+ * @example
21
+ * ```ts
22
+ * const schema = new ArraySchema(l.string(), { maxLength: 10 })
23
+ * const result = schema.validate(['a', 'b', 'c'])
24
+ * ```
25
+ */
6
26
  export declare class ArraySchema<const TItem extends Validator> extends Schema<Array<InferInput<TItem>>, Array<InferOutput<TItem>>> {
7
27
  readonly validator: TItem;
8
28
  readonly options: ArraySchemaOptions;
29
+ readonly type: "array";
9
30
  constructor(validator: TItem, options?: ArraySchemaOptions);
10
31
  validateInContext(input: unknown, ctx: ValidationContext): import("../core.js").ValidationResult<any[]>;
11
32
  }
33
+ /**
34
+ * Creates an array schema that validates each item against the provided schema.
35
+ *
36
+ * @param items - Schema to validate each array item against
37
+ * @param options - Optional length constraints
38
+ * @returns A new {@link ArraySchema} instance
39
+ *
40
+ * @example
41
+ * ```ts
42
+ * // Array of strings
43
+ * const tagsSchema = l.array(l.string())
44
+ *
45
+ * // Array with length constraints
46
+ * const limitedSchema = l.array(l.integer(), { maxLength: 100 })
47
+ *
48
+ * // Array of objects
49
+ * const usersSchema = l.array(l.object({
50
+ * name: l.string(),
51
+ * age: l.integer(),
52
+ * }))
53
+ *
54
+ * // Non-empty array
55
+ * const nonEmptySchema = l.array(l.string(), { minLength: 1 })
56
+ * ```
57
+ */
12
58
  declare function arraySchema<const TValidator extends Validator>(items: TValidator, options?: ArraySchemaOptions): ArraySchema<TValidator>;
13
59
  declare function arraySchema<const TValue, const TValidator extends Validator<TValue> = Validator<TValue>>(items: TValidator, options?: ArraySchemaOptions): ArraySchema<TValidator>;
14
60
  export declare const array: typeof arraySchema;
@@ -1 +1 @@
1
- {"version":3,"file":"array.d.ts","sourceRoot":"","sources":["../../src/schema/array.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,UAAU,EACV,WAAW,EACX,MAAM,EACN,iBAAiB,EACjB,SAAS,EACV,MAAM,YAAY,CAAA;AAGnB,MAAM,MAAM,kBAAkB,GAAG;IAC/B,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,SAAS,CAAC,EAAE,MAAM,CAAA;CACnB,CAAA;AAED,qBAAa,WAAW,CAAC,KAAK,CAAC,KAAK,SAAS,SAAS,CAAE,SAAQ,MAAM,CACpE,KAAK,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,EACxB,KAAK,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC,CAC1B;IAEG,QAAQ,CAAC,SAAS,EAAE,KAAK;IACzB,QAAQ,CAAC,OAAO,EAAE,kBAAkB;gBAD3B,SAAS,EAAE,KAAK,EAChB,OAAO,GAAE,kBAAuB;IAK3C,iBAAiB,CAAC,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,iBAAiB;CAmCzD;AAGD,iBAAS,WAAW,CAAC,KAAK,CAAC,UAAU,SAAS,SAAS,EACrD,KAAK,EAAE,UAAU,EACjB,OAAO,CAAC,EAAE,kBAAkB,GAC3B,WAAW,CAAC,UAAU,CAAC,CAAA;AAC1B,iBAAS,WAAW,CAClB,KAAK,CAAC,MAAM,EACZ,KAAK,CAAC,UAAU,SAAS,SAAS,CAAC,MAAM,CAAC,GAAG,SAAS,CAAC,MAAM,CAAC,EAC9D,KAAK,EAAE,U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kBAAkB,GAAG,WAAW,CAAC,UAAU,CAAC,CAAA;AAQ3E,eAAO,MAAM,KAAK,oBAAiD,CAAA"}
@@ -3,9 +3,24 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.array = exports.ArraySchema = void 0;
4
4
  const core_js_1 = require("../core.js");
5
5
  const memoize_js_1 = require("../util/memoize.js");
6
+ /**
7
+ * Schema for validating arrays where all items match a given schema.
8
+ *
9
+ * Validates that the input is an array, checks length constraints, and
10
+ * validates each item against the provided item schema.
11
+ *
12
+ * @template TItem - The validator type for array items
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * const schema = new ArraySchema(l.string(), { maxLength: 10 })
17
+ * const result = schema.validate(['a', 'b', 'c'])
18
+ * ```
19
+ */
6
20
  class ArraySchema extends core_js_1.Schema {
7
21
  validator;
8
22
  options;
23
+ type = 'array';
9
24
  constructor(validator, options = {}) {
10
25
  super();
11
26
  this.validator = validator;
@@ -13,7 +28,7 @@ class ArraySchema extends core_js_1.Schema {
13
28
  }
14
29
  validateInContext(input, ctx) {
15
30
  if (!Array.isArray(input)) {
16
- return ctx.issueInvalidType(input, 'array');
31
+ return ctx.issueUnexpectedType(input, 'array');
17
32
  }
18
33
  const { minLength, maxLength } = this.options;
19
34
  if (minLength != null && input.length < minLength) {
@@ -1 +1 @@
1
- {"version":3,"file":"array.js","sourceRoot":"","sources":["../../src/schema/array.ts"],"names":[],"mappings":";;;AAAA,wCAMmB;AACnB,mDAAwD;AAOxD,MAAa,WAA2C,SAAQ,gBAG/D;IAEY;IACA;IAFX,YACW,SAAgB,EAChB,UAA8B,EAAE;QAEzC,KAAK,EAAE,CAAA;QAHE,cAAS,GAAT,SAAS,CAAO;QAChB,YAAO,GAAP,OAAO,CAAyB;IAG3C,CAAC;IAED,iBAAiB,CAAC,KAAc,EAAE,GAAsB;QACtD,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;YAC1B,OAAO,GAAG,CAAC,gBAAgB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AAC;QAED,OAAO,GAAG,CAAC,OAAO,CAAC,IAAI,IAAI,KAAK,CAAC,CAAA;IACnC,CAAC;CACF;AA9CD,kCA8CC;AAWD,SAAS,WAAW,CAClB,KAAiB,EACjB,OAA4B;IAE5B,OAAO,IAAI,WAAW,CAAa,KAAK,EAAE,OAAO,CAAC,CAAA;AACpD,CAAC;AAEY,QAAA,KAAK,GAAiB,IAAA,gCAAmB,EAAC,WAAW,CAAC,CAAA","sourcesContent":["import {\n InferInput,\n InferOutput,\n Schema,\n ValidationContext,\n Validator,\n} from '../core.js'\nimport { memoizedTransformer } from '../util/memoize.js'\n\nexport type ArraySchemaOptions = {\n minLength?: number\n maxLength?: number\n}\n\nexport class ArraySchema<const TItem extends Validator> extends Schema<\n Array<InferInput<TItem>>,\n Array<InferOutput<TItem>>\n> {\n constructor(\n readonly validator: TItem,\n readonly options: ArraySchemaOptions = {},\n ) {\n super()\n }\n\n validateInContext(input: unknown, ctx: ValidationContext) {\n if (!Array.isArray(input)) {\n return ctx.issueInvalidType(input, 'array')\n }\n\n const { minLength, maxLength } = this.options\n\n if (minLength != null && input.length < minLength) {\n return ctx.issueTooSmall(input, 'array', minLength, input.length)\n }\n\n if (maxLength != null && input.length > maxLength) {\n return ctx.issueTooBig(input, 'array', maxLength, input.length)\n }\n\n let copy: undefined | unknown[]\n\n for (let i = 0; i < input.length; i++) {\n const result = ctx.validateChild(input, i, this.validator)\n if (!result.success) return result\n\n if (result.value !== input[i]) {\n if (ctx.options.mode === 'validate') {\n // In \"validate\" mode, we can't modify the input, so we issue an error\n return ctx.issueInvalidPropertyValue(input, i, [result.value])\n }\n\n // Copy on write (but only if we did not already make a copy)\n copy ??= Array.from(input)\n copy[i] = result.value\n }\n }\n\n return ctx.success(copy ?? input)\n }\n}\n\n/*@__NO_SIDE_EFFECTS__*/\nfunction arraySchema<const TValidator extends Validator>(\n items: TValidator,\n options?: ArraySchemaOptions,\n): ArraySchema<TValidator>\nfunction arraySchema<\n const TValue,\n const TValidator extends Validator<TValue> = Validator<TValue>,\n>(items: TValidator, options?: ArraySchemaOptions): ArraySchema<TValidator>\nfunction arraySchema<const TValidator extends Validator>(\n items: TValidator,\n options?: ArraySchemaOptions,\n) {\n return new ArraySchema<TValidator>(items, options)\n}\n\nexport const array = /*#__PURE__*/ memoizedTransformer(arraySchema)\n"]}
1
+ {"version":3,"file":"array.js","sourceRoot":"","sources":["../../src/schema/array.ts"],"names":[],"mappings":";;;AAAA,wCAMmB;AACnB,mDAAwD;AAaxD;;;;;;;;;;;;;GAaG;AACH,MAAa,WAA2C,SAAQ,gBAG/D;IAIY;IACA;IAJF,IAAI,GAAG,OAAgB,CAAA;IAEhC,YACW,SAAgB,EAChB,UAA8B,EAAE;QAEzC,KAAK,EAAE,CAAA;QAHE,cAAS,GAAT,SAAS,CAAO;QAChB,YAAO,GAAP,OAAO,CAAyB;IAG3C,CAAC;IAED,iBAAiB,CAAC,KAAc,EAAE,GAAsB;QACtD,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;YAC1B,OAAO,GAAG,CAAC,mBAAmB,CAAC,KAAK,EAAE,OAAO,CAAC,CAAA;QAChD,CAAC;QAED,MAAM,EAAE,SAAS,EAAE,SAAS,EAAE,GAAG,IAAI,CAAC,OAAO,CAAA;QAE7C,IAAI,SAAS,IAAI,IAAI,IAAI,KAAK,CAAC,MAAM,GAAG,SAAS,EAAE,CAAC;YAClD,OAAO,GAAG,CAAC,aAAa,CAAC,KAAK,EAAE,OAAO,EAAE,SAAS,EAAE,KAAK,CAAC,MAAM,CAAC,CAAA;QACnE,CAAC;QAED,IAAI,SAAS,IAAI,IAAI,IAAI,KAAK,CAAC,MAAM,GAAG,SAAS,EAAE,CAAC;YAClD,OAAO,GAAG,CAAC,WAAW,CAAC,KAAK,EAAE,OAAO,EAAE,SAAS,EAAE,KAAK,CAAC,MAAM,CAAC,CAAA;QACjE,CAAC;QAED,IAAI,IAA2B,CAAA;QAE/B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YACtC,MAAM,MAAM,GAAG,GAAG,CAAC,aAAa,CAAC,KAAK,EAAE,CAAC,EAAE,IAAI,CAAC,SAAS,CAAC,CAAA;YAC1D,IAAI,CAAC,MAAM,CAAC,OAAO;gBAAE,OAAO,MAAM,CAAA;YAElC,IAAI,MAAM,CAAC,KAAK,KAAK,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC;gBAC9B,IAAI,GAAG,CAAC,OAAO,CAAC,IAAI,KAAK,UAAU,EAAE,CAAC;oBACpC,sEAAsE;oBACtE,OAAO,GAAG,CAAC,yBAAyB,CAAC,KAAK,EAAE,CAAC,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAA;gBAChE,CAAC;gBAED,6DAA6D;gBAC7D,IAAI,KAAK,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAA;gBAC1B,IAAI,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC,KAAK,CAAA;YACxB,CAAC;QACH,CAAC;QAED,OAAO,GAAG,CAAC,OAAO,CAAC,IAAI,IAAI,KAAK,CAAC,CAAA;IACnC,CAAC;CACF;AAhDD,kCAgDC;AAoCD,SAAS,WAAW,CAClB,KAAiB,EACjB,OAA4B;IAE5B,OAAO,IAAI,WAAW,CAAa,KAAK,EAAE,OAAO,CAAC,CAAA;AACpD,CAAC;AAEY,QAAA,KAAK,GAAiB,IAAA,gCAAmB,EAAC,WAAW,CAAC,CAAA","sourcesContent":["import {\n InferInput,\n InferOutput,\n Schema,\n ValidationContext,\n Validator,\n} from '../core.js'\nimport { memoizedTransformer } from '../util/memoize.js'\n\n/**\n * Configuration options for array schema validation.\n *\n * @property minLength - Minimum number of items in the array\n * @property maxLength - Maximum number of items in the array\n */\nexport type ArraySchemaOptions = {\n minLength?: number\n maxLength?: number\n}\n\n/**\n * Schema for validating arrays where all items match a given schema.\n *\n * Validates that the input is an array, checks length constraints, and\n * validates each item against the provided item schema.\n *\n * @template TItem - The validator type for array items\n *\n * @example\n * ```ts\n * const schema = new ArraySchema(l.string(), { maxLength: 10 })\n * const result = schema.validate(['a', 'b', 'c'])\n * ```\n */\nexport class ArraySchema<const TItem extends Validator> extends Schema<\n Array<InferInput<TItem>>,\n Array<InferOutput<TItem>>\n> {\n readonly type = 'array' as const\n\n constructor(\n readonly validator: TItem,\n readonly options: ArraySchemaOptions = {},\n ) {\n super()\n }\n\n validateInContext(input: unknown, ctx: ValidationContext) {\n if (!Array.isArray(input)) {\n return ctx.issueUnexpectedType(input, 'array')\n }\n\n const { minLength, maxLength } = this.options\n\n if (minLength != null && input.length < minLength) {\n return ctx.issueTooSmall(input, 'array', minLength, input.length)\n }\n\n if (maxLength != null && input.length > maxLength) {\n return ctx.issueTooBig(input, 'array', maxLength, input.length)\n }\n\n let copy: undefined | unknown[]\n\n for (let i = 0; i < input.length; i++) {\n const result = ctx.validateChild(input, i, this.validator)\n if (!result.success) return result\n\n if (result.value !== input[i]) {\n if (ctx.options.mode === 'validate') {\n // In \"validate\" mode, we can't modify the input, so we issue an error\n return ctx.issueInvalidPropertyValue(input, i, [result.value])\n }\n\n // Copy on write (but only if we did not already make a copy)\n copy ??= Array.from(input)\n copy[i] = result.value\n }\n }\n\n return ctx.success(copy ?? input)\n }\n}\n\n/**\n * Creates an array schema that validates each item against the provided schema.\n *\n * @param items - Schema to validate each array item against\n * @param options - Optional length constraints\n * @returns A new {@link ArraySchema} instance\n *\n * @example\n * ```ts\n * // Array of strings\n * const tagsSchema = l.array(l.string())\n *\n * // Array with length constraints\n * const limitedSchema = l.array(l.integer(), { maxLength: 100 })\n *\n * // Array of objects\n * const usersSchema = l.array(l.object({\n * name: l.string(),\n * age: l.integer(),\n * }))\n *\n * // Non-empty array\n * const nonEmptySchema = l.array(l.string(), { minLength: 1 })\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction arraySchema<const TValidator extends Validator>(\n items: TValidator,\n options?: ArraySchemaOptions,\n): ArraySchema<TValidator>\nfunction arraySchema<\n const TValue,\n const TValidator extends Validator<TValue> = Validator<TValue>,\n>(items: TValidator, options?: ArraySchemaOptions): ArraySchema<TValidator>\nfunction arraySchema<const TValidator extends Validator>(\n items: TValidator,\n options?: ArraySchemaOptions,\n) {\n return new ArraySchema<TValidator>(items, options)\n}\n\nexport const array = /*#__PURE__*/ memoizedTransformer(arraySchema)\n"]}