@kravc/schema 2.7.6 → 2.8.0-alpha.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 (170) hide show
  1. package/README.md +19 -14
  2. package/dist/CredentialFactory.d.ts +345 -0
  3. package/dist/CredentialFactory.d.ts.map +1 -0
  4. package/dist/CredentialFactory.js +381 -0
  5. package/dist/CredentialFactory.js.map +1 -0
  6. package/dist/Schema.d.ts +448 -0
  7. package/dist/Schema.d.ts.map +1 -0
  8. package/dist/Schema.js +506 -0
  9. package/dist/Schema.js.map +1 -0
  10. package/dist/ValidationError.d.ts +70 -0
  11. package/dist/ValidationError.d.ts.map +1 -0
  12. package/dist/ValidationError.js +78 -0
  13. package/dist/ValidationError.js.map +1 -0
  14. package/dist/Validator.d.ts +483 -0
  15. package/dist/Validator.d.ts.map +1 -0
  16. package/dist/Validator.js +570 -0
  17. package/dist/Validator.js.map +1 -0
  18. package/dist/helpers/JsonSchema.d.ts +99 -0
  19. package/dist/helpers/JsonSchema.d.ts.map +1 -0
  20. package/dist/helpers/JsonSchema.js +3 -0
  21. package/dist/helpers/JsonSchema.js.map +1 -0
  22. package/dist/helpers/cleanupAttributes.d.ts +34 -0
  23. package/dist/helpers/cleanupAttributes.d.ts.map +1 -0
  24. package/dist/helpers/cleanupAttributes.js +113 -0
  25. package/dist/helpers/cleanupAttributes.js.map +1 -0
  26. package/dist/helpers/cleanupNulls.d.ts +27 -0
  27. package/dist/helpers/cleanupNulls.d.ts.map +1 -0
  28. package/dist/helpers/cleanupNulls.js +96 -0
  29. package/dist/helpers/cleanupNulls.js.map +1 -0
  30. package/dist/helpers/getReferenceIds.d.ts +169 -0
  31. package/dist/helpers/getReferenceIds.d.ts.map +1 -0
  32. package/dist/helpers/getReferenceIds.js +241 -0
  33. package/dist/helpers/getReferenceIds.js.map +1 -0
  34. package/dist/helpers/got.d.ts +60 -0
  35. package/dist/helpers/got.d.ts.map +1 -0
  36. package/dist/helpers/got.js +72 -0
  37. package/dist/helpers/got.js.map +1 -0
  38. package/dist/helpers/mapObjectProperties.d.ts +150 -0
  39. package/dist/helpers/mapObjectProperties.d.ts.map +1 -0
  40. package/dist/helpers/mapObjectProperties.js +229 -0
  41. package/dist/helpers/mapObjectProperties.js.map +1 -0
  42. package/dist/helpers/normalizeAttributes.d.ts +213 -0
  43. package/dist/helpers/normalizeAttributes.d.ts.map +1 -0
  44. package/dist/helpers/normalizeAttributes.js +243 -0
  45. package/dist/helpers/normalizeAttributes.js.map +1 -0
  46. package/dist/helpers/normalizeProperties.d.ts +168 -0
  47. package/dist/helpers/normalizeProperties.d.ts.map +1 -0
  48. package/dist/helpers/normalizeProperties.js +223 -0
  49. package/dist/helpers/normalizeProperties.js.map +1 -0
  50. package/dist/helpers/normalizeRequired.d.ts +159 -0
  51. package/dist/helpers/normalizeRequired.d.ts.map +1 -0
  52. package/dist/helpers/normalizeRequired.js +206 -0
  53. package/dist/helpers/normalizeRequired.js.map +1 -0
  54. package/dist/helpers/normalizeType.d.ts +81 -0
  55. package/dist/helpers/normalizeType.d.ts.map +1 -0
  56. package/dist/helpers/normalizeType.js +210 -0
  57. package/dist/helpers/normalizeType.js.map +1 -0
  58. package/dist/helpers/nullifyEmptyValues.d.ts +139 -0
  59. package/dist/helpers/nullifyEmptyValues.d.ts.map +1 -0
  60. package/dist/helpers/nullifyEmptyValues.js +191 -0
  61. package/dist/helpers/nullifyEmptyValues.js.map +1 -0
  62. package/dist/helpers/removeRequiredAndDefault.d.ts +106 -0
  63. package/dist/helpers/removeRequiredAndDefault.d.ts.map +1 -0
  64. package/dist/helpers/removeRequiredAndDefault.js +138 -0
  65. package/dist/helpers/removeRequiredAndDefault.js.map +1 -0
  66. package/dist/helpers/validateId.d.ts +39 -0
  67. package/dist/helpers/validateId.d.ts.map +1 -0
  68. package/dist/helpers/validateId.js +51 -0
  69. package/dist/helpers/validateId.js.map +1 -0
  70. package/dist/index.d.ts +7 -0
  71. package/dist/index.d.ts.map +1 -0
  72. package/dist/index.js +17 -0
  73. package/dist/index.js.map +1 -0
  74. package/dist/ld/documentLoader.d.ts +8 -0
  75. package/dist/ld/documentLoader.d.ts.map +1 -0
  76. package/dist/ld/documentLoader.js +24 -0
  77. package/dist/ld/documentLoader.js.map +1 -0
  78. package/dist/ld/getLinkedDataAttributeType.d.ts +10 -0
  79. package/dist/ld/getLinkedDataAttributeType.d.ts.map +1 -0
  80. package/dist/ld/getLinkedDataAttributeType.js +32 -0
  81. package/dist/ld/getLinkedDataAttributeType.js.map +1 -0
  82. package/dist/ld/getLinkedDataContext.d.ts +19 -0
  83. package/dist/ld/getLinkedDataContext.d.ts.map +1 -0
  84. package/dist/ld/getLinkedDataContext.js +50 -0
  85. package/dist/ld/getLinkedDataContext.js.map +1 -0
  86. package/eslint.config.mjs +32 -52
  87. package/examples/credentials/createAccountCredential.ts +27 -0
  88. package/examples/credentials/createMineSweeperScoreCredential.ts +115 -0
  89. package/examples/index.ts +7 -0
  90. package/examples/schemas/FavoriteItemSchema.ts +27 -0
  91. package/examples/{Preferences.yaml → schemas/Preferences.yaml} +2 -0
  92. package/examples/schemas/PreferencesSchema.ts +29 -0
  93. package/examples/schemas/ProfileSchema.ts +91 -0
  94. package/examples/schemas/Status.yaml +3 -0
  95. package/examples/schemas/StatusSchema.ts +12 -0
  96. package/jest.config.mjs +5 -0
  97. package/package.json +27 -20
  98. package/src/CredentialFactory.ts +392 -0
  99. package/src/Schema.ts +583 -0
  100. package/src/ValidationError.ts +90 -0
  101. package/src/Validator.ts +603 -0
  102. package/src/__tests__/CredentialFactory.test.ts +588 -0
  103. package/src/__tests__/Schema.test.ts +371 -0
  104. package/src/__tests__/ValidationError.test.ts +235 -0
  105. package/src/__tests__/Validator.test.ts +787 -0
  106. package/src/helpers/JsonSchema.ts +119 -0
  107. package/src/helpers/__tests__/cleanupAttributes.test.ts +943 -0
  108. package/src/helpers/__tests__/cleanupNulls.test.ts +772 -0
  109. package/src/helpers/__tests__/getReferenceIds.test.ts +975 -0
  110. package/src/helpers/__tests__/got.test.ts +193 -0
  111. package/src/helpers/__tests__/mapObjectProperties.test.ts +1126 -0
  112. package/src/helpers/__tests__/normalizeAttributes.test.ts +1435 -0
  113. package/src/helpers/__tests__/normalizeProperties.test.ts +727 -0
  114. package/src/helpers/__tests__/normalizeRequired.test.ts +669 -0
  115. package/src/helpers/__tests__/normalizeType.test.ts +772 -0
  116. package/src/helpers/__tests__/nullifyEmptyValues.test.ts +735 -0
  117. package/src/helpers/__tests__/removeRequiredAndDefault.test.ts +734 -0
  118. package/src/helpers/__tests__/validateId.test.ts +118 -0
  119. package/src/helpers/cleanupAttributes.ts +151 -0
  120. package/src/helpers/cleanupNulls.ts +106 -0
  121. package/src/helpers/getReferenceIds.ts +273 -0
  122. package/src/helpers/got.ts +73 -0
  123. package/src/helpers/mapObjectProperties.ts +272 -0
  124. package/src/helpers/normalizeAttributes.ts +247 -0
  125. package/src/helpers/normalizeProperties.ts +249 -0
  126. package/src/helpers/normalizeRequired.ts +233 -0
  127. package/src/helpers/normalizeType.ts +235 -0
  128. package/src/helpers/nullifyEmptyValues.ts +207 -0
  129. package/src/helpers/removeRequiredAndDefault.ts +151 -0
  130. package/src/helpers/validateId.ts +53 -0
  131. package/src/index.ts +13 -0
  132. package/src/ld/__tests__/documentLoader.test.ts +57 -0
  133. package/src/ld/__tests__/getLinkedDataAttributeType.test.ts +212 -0
  134. package/src/ld/__tests__/getLinkedDataContext.test.ts +378 -0
  135. package/src/ld/documentLoader.ts +28 -0
  136. package/src/ld/getLinkedDataAttributeType.ts +46 -0
  137. package/src/ld/getLinkedDataContext.ts +80 -0
  138. package/tsconfig.json +27 -0
  139. package/types/credentials-context.d.ts +14 -0
  140. package/types/security-context.d.ts +6 -0
  141. package/examples/Status.yaml +0 -3
  142. package/examples/createAccountCredential.js +0 -27
  143. package/examples/createMineSweeperScoreCredential.js +0 -63
  144. package/examples/index.js +0 -9
  145. package/src/CredentialFactory.js +0 -67
  146. package/src/CredentialFactory.spec.js +0 -131
  147. package/src/Schema.js +0 -104
  148. package/src/Schema.spec.js +0 -172
  149. package/src/ValidationError.js +0 -31
  150. package/src/Validator.js +0 -128
  151. package/src/Validator.spec.js +0 -355
  152. package/src/helpers/cleanupAttributes.js +0 -71
  153. package/src/helpers/cleanupNulls.js +0 -42
  154. package/src/helpers/getReferenceIds.js +0 -71
  155. package/src/helpers/mapObject.js +0 -65
  156. package/src/helpers/normalizeAttributes.js +0 -28
  157. package/src/helpers/normalizeProperties.js +0 -61
  158. package/src/helpers/normalizeRequired.js +0 -37
  159. package/src/helpers/normalizeType.js +0 -41
  160. package/src/helpers/nullifyEmptyValues.js +0 -57
  161. package/src/helpers/removeRequiredAndDefault.js +0 -30
  162. package/src/helpers/validateId.js +0 -19
  163. package/src/index.d.ts +0 -25
  164. package/src/index.js +0 -8
  165. package/src/ld/documentLoader.js +0 -25
  166. package/src/ld/documentLoader.spec.js +0 -12
  167. package/src/ld/getLinkedDataContext.js +0 -63
  168. package/src/ld/getLinkedDataType.js +0 -38
  169. /package/examples/{FavoriteItem.yaml → schemas/FavoriteItem.yaml} +0 -0
  170. /package/examples/{Profile.yaml → schemas/Profile.yaml} +0 -0
@@ -0,0 +1,603 @@
1
+ import ZSchema from 'z-schema';
2
+ import { keyBy, groupBy } from 'lodash';
3
+
4
+ import got from './helpers/got';
5
+ import Schema from './Schema';
6
+ import cleanupNulls from './helpers/cleanupNulls';
7
+ import getReferenceIds from './helpers/getReferenceIds';
8
+ import ValidationError from './ValidationError';
9
+ import cleanupAttributes from './helpers/cleanupAttributes';
10
+ import nullifyEmptyValues from './helpers/nullifyEmptyValues';
11
+ import normalizeAttributes from './helpers/normalizeAttributes';
12
+ import type { TargetObject, JsonSchemasMap } from './helpers/JsonSchema';
13
+
14
+ /**
15
+ * Validator for validating and normalizing objects against JSON schemas.
16
+ *
17
+ * **Intent:**
18
+ * The Validator class provides a comprehensive solution for validating objects against JSON schemas
19
+ * with built-in normalization, cleanup, and error handling capabilities. It serves as the primary
20
+ * interface for ensuring data integrity and consistency in applications that work with structured
21
+ * data, particularly in API endpoints, data transformation pipelines, and credential systems.
22
+ *
23
+ * The validator performs several key operations:
24
+ * - Validates objects against registered schemas using JSON Schema validation
25
+ * - Removes attributes not defined in the schema (cleanup)
26
+ * - Normalizes attribute types (e.g., string '1' → boolean true, string '180' → number 180)
27
+ * - Handles empty values by optionally nullifying them for non-required fields
28
+ * - Provides detailed validation errors with structured error information
29
+ *
30
+ * **Use Cases:**
31
+ *
32
+ * 1. **API Request/Response Validation:**
33
+ * - Validate incoming API requests against defined schemas
34
+ * - Ensure API responses conform to expected structure
35
+ * - Clean up extra fields sent by clients
36
+ * - Normalize data from query parameters or form submissions
37
+ *
38
+ * 2. **Data Integration & Third-Party Services:**
39
+ * - Integrate with external APIs that send loosely-typed data
40
+ * - Normalize data from URLs where types are strings (e.g., 'true', '1', '180')
41
+ * - Clean up payloads before sending to third-party services (e.g., Telegram, webhooks)
42
+ * - Handle data from systems that don't enforce strict typing
43
+ *
44
+ * 3. **Credential & Identity Systems:**
45
+ * - Validate verifiable credentials against schema definitions
46
+ * - Ensure credential subjects conform to expected schemas
47
+ * - Normalize credential data from various sources
48
+ *
49
+ * 4. **Data Transformation Pipelines:**
50
+ * - Normalize data types without full validation
51
+ * - Clean up data structures before processing
52
+ * - Transform data between different formats while maintaining schema compliance
53
+ *
54
+ * 5. **Form & User Input Processing:**
55
+ * - Validate and normalize form submissions
56
+ * - Handle empty values gracefully (nullify empty strings for optional fields)
57
+ * - Clean up null values from nested objects
58
+ *
59
+ * **Example - Basic Validation:**
60
+ * ```typescript
61
+ * const userSchema = new Schema({
62
+ * name: { type: 'string', required: true },
63
+ * email: { type: 'string', format: 'email', required: true },
64
+ * age: { type: 'number', minimum: 0 }
65
+ * }, 'User');
66
+ *
67
+ * const validator = new Validator([userSchema]);
68
+ *
69
+ * const validUser = validator.validate({
70
+ * name: 'John Doe',
71
+ * email: 'john@example.com',
72
+ * age: 30
73
+ * }, 'User');
74
+ * // Returns: { name: 'John Doe', email: 'john@example.com', age: 30 }
75
+ * ```
76
+ *
77
+ * **Example - Normalization (String to Type Conversion):**
78
+ * ```typescript
79
+ * // Useful when receiving data from URLs or forms where types are strings
80
+ * const preferencesSchema = new Schema({
81
+ * height: { type: 'number' },
82
+ * isNotificationEnabled: { type: 'boolean' }
83
+ * }, 'Preferences');
84
+ *
85
+ * const validator = new Validator([preferencesSchema]);
86
+ *
87
+ * const normalized = validator.validate({
88
+ * height: '180', // String '180' → number 180
89
+ * isNotificationEnabled: '1' // String '1' → boolean true
90
+ * }, 'Preferences');
91
+ * // Returns: { height: 180, isNotificationEnabled: true }
92
+ * ```
93
+ *
94
+ * **Example - Cleanup (Remove Extra Attributes):**
95
+ * ```typescript
96
+ * const profileSchema = new Schema({
97
+ * name: { type: 'string', required: true },
98
+ * email: { type: 'string', required: true }
99
+ * }, 'Profile');
100
+ *
101
+ * const validator = new Validator([profileSchema]);
102
+ *
103
+ * const cleaned = validator.validate({
104
+ * name: 'John',
105
+ * email: 'john@example.com',
106
+ * extraField: 'should be removed',
107
+ * _internalId: 'should be removed'
108
+ * }, 'Profile', false, true);
109
+ * // Returns: { name: 'John', email: 'john@example.com' }
110
+ * // extraField and _internalId are removed
111
+ * ```
112
+ *
113
+ * **Example - Nullify Empty Values:**
114
+ * ```typescript
115
+ * const profileSchema = new Schema({
116
+ * name: { type: 'string', required: true },
117
+ * gender: { enum: ['Male', 'Female', 'Other'] }, // Optional
118
+ * mobileNumber: { type: 'string', pattern: '^\\d+$' } // Optional
119
+ * }, 'Profile');
120
+ *
121
+ * const validator = new Validator([profileSchema]);
122
+ *
123
+ * const result = validator.validate({
124
+ * name: 'John',
125
+ * gender: '', // Empty string for optional enum
126
+ * mobileNumber: '' // Empty string for optional pattern field
127
+ * }, 'Profile', true); // shouldNullifyEmptyValues = true
128
+ * // Returns: { name: 'John', gender: null, mobileNumber: null }
129
+ * // Empty values are converted to null for non-required fields
130
+ * ```
131
+ *
132
+ * **Example - Normalization Only (Without Validation):**
133
+ * ```typescript
134
+ * const preferencesSchema = new Schema({
135
+ * height: { type: 'number' },
136
+ * isNotificationEnabled: { type: 'boolean', default: false }
137
+ * }, 'Preferences');
138
+ *
139
+ * const validator = new Validator([preferencesSchema]);
140
+ *
141
+ * // Normalize without validation - useful for partial data
142
+ * const normalized = validator.normalize({
143
+ * height: '180'
144
+ * }, 'Preferences');
145
+ * // Returns: { height: 180, isNotificationEnabled: false }
146
+ * // Applies normalization and defaults without validation
147
+ * ```
148
+ *
149
+ * **Example - Error Handling:**
150
+ * ```typescript
151
+ * const validator = new Validator([userSchema]);
152
+ *
153
+ * try {
154
+ * validator.validate({
155
+ * name: '', // Empty required field
156
+ * email: 'invalid-email' // Invalid format
157
+ * }, 'User');
158
+ * } catch (error) {
159
+ * if (error instanceof ValidationError) {
160
+ * const errorDetails = error.toJSON();
161
+ * console.error(errorDetails.schemaId); // 'User'
162
+ * console.error(errorDetails.validationErrors);
163
+ * // [
164
+ * // { path: '#/name', code: 'MIN_LENGTH', message: '...' },
165
+ * // { path: '#/email', code: 'INVALID_FORMAT', message: '...' }
166
+ * // ]
167
+ * }
168
+ * }
169
+ * ```
170
+ *
171
+ * **Example - Schema References:**
172
+ * ```typescript
173
+ * const addressSchema = new Schema({
174
+ * street: { type: 'string', required: true },
175
+ * city: { type: 'string', required: true }
176
+ * }, 'Address');
177
+ *
178
+ * const userSchema = new Schema({
179
+ * name: { type: 'string', required: true },
180
+ * address: { $ref: 'Address' }
181
+ * }, 'User');
182
+ *
183
+ * const validator = new Validator([addressSchema, userSchema]);
184
+ *
185
+ * // Get all schemas referenced by User schema
186
+ * const referencedIds = validator.getReferenceIds('User');
187
+ * // Returns: ['Address']
188
+ * ```
189
+ *
190
+ * **Example - Multiple Schemas:**
191
+ * ```typescript
192
+ * const statusSchema = new Schema({ enum: ['ACTIVE', 'INACTIVE'] }, 'Status');
193
+ * const profileSchema = new Schema({
194
+ * name: { type: 'string', required: true },
195
+ * status: { $ref: 'Status' }
196
+ * }, 'Profile');
197
+ *
198
+ * const validator = new Validator([statusSchema, profileSchema]);
199
+ *
200
+ * const result = validator.validate({
201
+ * name: 'John',
202
+ * status: 'ACTIVE'
203
+ * }, 'Profile');
204
+ * ```
205
+ */
206
+ class Validator {
207
+ private _engine: ZSchema;
208
+ private _schemasMap: Record<string, Schema>;
209
+ private _jsonSchemasMap: JsonSchemasMap;
210
+
211
+ /**
212
+ * Creates a validator instance for a collection of schemas.
213
+ *
214
+ * **Intent:** Initialize a validator with a set of schemas that can be used for validation
215
+ * and normalization. The constructor validates that all schemas are valid JSON schemas and
216
+ * that there are no duplicate schema IDs.
217
+ *
218
+ * **Use Cases:**
219
+ * - Initialize a validator with all schemas needed for an application
220
+ * - Set up a validator for a specific domain or module
221
+ * - Create validators for different environments (dev, staging, production)
222
+ *
223
+ * @param schemas - Array of Schema instances to register with this validator.
224
+ * All schemas must have unique IDs and valid JSON Schema structure.
225
+ * Referenced schemas (via $ref) must be included in this array.
226
+ *
227
+ * @throws Error if no schemas are provided
228
+ * @throws Error if multiple schemas have the same ID
229
+ * @throws Error if any schema has invalid JSON Schema structure or missing references
230
+ *
231
+ * **Example:**
232
+ * ```typescript
233
+ * const userSchema = new Schema({ name: { type: 'string' } }, 'User');
234
+ * const statusSchema = new Schema({ enum: ['ACTIVE', 'INACTIVE'] }, 'Status');
235
+ *
236
+ * const validator = new Validator([userSchema, statusSchema]);
237
+ * ```
238
+ *
239
+ * **Example - With Schema References:**
240
+ * ```typescript
241
+ * const addressSchema = new Schema({
242
+ * street: { type: 'string' }
243
+ * }, 'Address');
244
+ *
245
+ * const userSchema = new Schema({
246
+ * name: { type: 'string' },
247
+ * address: { $ref: 'Address' } // References Address schema
248
+ * }, 'User');
249
+ *
250
+ * // Both schemas must be provided
251
+ * const validator = new Validator([addressSchema, userSchema]);
252
+ * ```
253
+ */
254
+ constructor(schemas: Schema[] | undefined) {
255
+ if (!schemas) {
256
+ throw new Error('No schemas provided');
257
+ }
258
+
259
+ const groupsById = groupBy(schemas, 'id');
260
+
261
+ for (const id in groupsById) {
262
+ const schemas = groupsById[id];
263
+ const hasDuplicates = schemas.length > 1;
264
+
265
+ if (hasDuplicates) {
266
+ throw new Error(`Multiple schemas provided for ID: ${id}`);
267
+ }
268
+ }
269
+
270
+ this._engine = new ZSchema({
271
+ reportPathAsArray: false,
272
+ ignoreUnknownFormats: true,
273
+ });
274
+
275
+ const jsonSchemas = schemas.map(({ jsonSchema }) => jsonSchema);
276
+ const isValid = this._engine.validateSchema(jsonSchemas);
277
+
278
+ if (!isValid) {
279
+ const { errors } = this._engine.lastReport!;
280
+ const errorsJson = JSON.stringify(errors, null, 2);
281
+
282
+ throw new Error(`Schemas validation failed, errors: ${errorsJson}`);
283
+ }
284
+
285
+ this._schemasMap = keyBy(schemas, 'id');
286
+ this._jsonSchemasMap = keyBy(jsonSchemas, 'id');
287
+ }
288
+
289
+ /**
290
+ * Validates, cleans, and normalizes an object against a registered schema.
291
+ *
292
+ * **Intent:** Perform comprehensive validation and transformation of objects to ensure they
293
+ * conform to schema definitions. This method combines validation, attribute cleanup, type
294
+ * normalization, and optional empty value handling in a single operation.
295
+ *
296
+ * **Use Cases:**
297
+ * - Validate API request payloads before processing
298
+ * - Clean up objects by removing undefined attributes
299
+ * - Normalize data types from loosely-typed sources (URLs, forms, external APIs)
300
+ * - Handle empty values gracefully for optional fields
301
+ * - Prepare data for storage or transmission
302
+ *
303
+ * **Processing Pipeline:**
304
+ * 1. Deep clones the input object
305
+ * 2. Optionally removes null values (if `shouldCleanupNulls` is true)
306
+ * 3. Removes attributes not defined in the schema
307
+ * 4. Normalizes attribute types (string → number/boolean, etc.)
308
+ * 5. Validates against JSON Schema
309
+ * 6. Optionally nullifies empty values for non-required fields
310
+ * 7. Returns validated and normalized object, or throws ValidationError
311
+ *
312
+ * @param object - The object to validate and normalize
313
+ * @param schemaId - The ID of the schema to validate against (must be registered in constructor)
314
+ * @param shouldNullifyEmptyValues - If true, converts empty strings to null for non-required
315
+ * fields that fail format/pattern/enum validation. Useful for
316
+ * handling form submissions where empty fields are sent as ''.
317
+ * @param shouldCleanupNulls - If true, removes null values from the object before processing.
318
+ * Useful for cleaning up data structures.
319
+ *
320
+ * @returns The validated, cleaned, and normalized object
321
+ *
322
+ * @throws Error if schema with `schemaId` is not found
323
+ * @throws ValidationError if validation fails (contains detailed error information)
324
+ *
325
+ * **Example - Basic Validation:**
326
+ * ```typescript
327
+ * const validator = new Validator([userSchema]);
328
+ *
329
+ * const result = validator.validate({
330
+ * name: 'John',
331
+ * email: 'john@example.com'
332
+ * }, 'User');
333
+ * ```
334
+ *
335
+ * **Example - With Cleanup:**
336
+ * ```typescript
337
+ * const result = validator.validate({
338
+ * name: 'John',
339
+ * extraField: 'removed',
340
+ * nullField: null
341
+ * }, 'User', false, true);
342
+ * // extraField and nullField are removed
343
+ * ```
344
+ *
345
+ * **Example - With Normalization:**
346
+ * ```typescript
347
+ * const result = validator.validate({
348
+ * name: 'John',
349
+ * age: '30', // String → number
350
+ * isActive: 'true' // String → boolean
351
+ * }, 'User');
352
+ * // age becomes 30, isActive becomes true
353
+ * ```
354
+ *
355
+ * **Example - Nullify Empty Values:**
356
+ * ```typescript
357
+ * const result = validator.validate({
358
+ * name: 'John',
359
+ * optionalEmail: '', // Empty string
360
+ * optionalPhone: '' // Empty string
361
+ * }, 'User', true);
362
+ * // optionalEmail and optionalPhone become null (if not required)
363
+ * ```
364
+ *
365
+ * **Example - Error Handling:**
366
+ * ```typescript
367
+ * try {
368
+ * validator.validate({ name: '' }, 'User');
369
+ * } catch (error) {
370
+ * if (error instanceof ValidationError) {
371
+ * const details = error.toJSON();
372
+ * // Access error.schemaId, error.validationErrors, etc.
373
+ * }
374
+ * }
375
+ * ```
376
+ */
377
+ validate(
378
+ object: TargetObject,
379
+ schemaId: string,
380
+ shouldNullifyEmptyValues = false,
381
+ shouldCleanupNulls = false
382
+ ) {
383
+ const jsonSchema = got(this._jsonSchemasMap, schemaId, 'Schema "$PATH" not found');
384
+
385
+ const objectJson = JSON.stringify(object);
386
+ let result = JSON.parse(objectJson);
387
+
388
+ if (shouldCleanupNulls) {
389
+ result = cleanupNulls(result);
390
+ }
391
+
392
+ try {
393
+ // NOTE: Drop attributes from objects that are not defined in schema.
394
+ // This is bad for FE developers, as they continue to send some
395
+ // trash to endpoints, but good for integrations with third party
396
+ // services, e.g. Telegram, when you do not want to define schema
397
+ // for the full payload. This method currently fails for cases when
398
+ // attribute is defined as object or array in schema, but value is
399
+ // a string. In this case validation method below would catch that.
400
+ cleanupAttributes(result, jsonSchema, this._jsonSchemasMap);
401
+
402
+ // NOTE: Normalize method helps to integrate objects built from URLs,
403
+ // where types are not defined, e.g. booleans are '1', 'yes' string
404
+ // or numbers are '1', '2'... strings.
405
+ normalizeAttributes(result, jsonSchema, this._jsonSchemasMap);
406
+
407
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
408
+ } catch (error) {
409
+ // NOTE: Skip errors in cleanup and normalize attributes methods.
410
+ // Validation would fail below for objects with invalid value types.
411
+
412
+ }
413
+
414
+ const isValid = this._engine.validate(result, jsonSchema);
415
+
416
+ if (isValid) {
417
+ return result;
418
+ }
419
+
420
+ const validationErrors = this._engine.getLastErrors();
421
+
422
+ if (!shouldNullifyEmptyValues) {
423
+ throw new ValidationError(schemaId, result, validationErrors);
424
+ }
425
+
426
+ const [ nullifiedResult, updatedValidationErrors ] = nullifyEmptyValues(result, validationErrors);
427
+
428
+ const hasValidationErrors = updatedValidationErrors.length > 0;
429
+
430
+ if (hasValidationErrors) {
431
+ throw new ValidationError(schemaId, result, updatedValidationErrors);
432
+ }
433
+
434
+ return nullifiedResult;
435
+ }
436
+
437
+ /**
438
+ * Normalizes object attributes using a schema without performing validation.
439
+ *
440
+ * **Intent:** Apply type normalization and default values to an object without the strictness
441
+ * of full validation. This is useful when you want to transform data types but don't need
442
+ * complete schema compliance, or when working with partial/incomplete data.
443
+ *
444
+ * **Use Cases:**
445
+ * - Normalize data types from loosely-typed sources (URLs, query parameters, forms)
446
+ * - Apply default values from schemas to partial objects
447
+ * - Transform data before validation in a separate step
448
+ * - Prepare data for display or processing without strict validation
449
+ * - Handle partial updates where not all fields are present
450
+ *
451
+ * **What It Does:**
452
+ * - Deep clones the input object
453
+ * - Normalizes attribute types (string '1' → boolean true, string '180' → number 180)
454
+ * - Applies default values from schema definitions
455
+ * - Does NOT validate required fields, formats, patterns, or enums
456
+ * - Does NOT remove undefined attributes
457
+ *
458
+ * @param object - The object to normalize
459
+ * @param schemaId - The ID of the schema to use for normalization (must be registered)
460
+ *
461
+ * @returns A new object with normalized types and applied defaults
462
+ *
463
+ * @throws Error if schema with `schemaId` is not found
464
+ *
465
+ * **Example - Type Normalization:**
466
+ * ```typescript
467
+ * const preferencesSchema = new Schema({
468
+ * height: { type: 'number' },
469
+ * isNotificationEnabled: { type: 'boolean', default: false }
470
+ * }, 'Preferences');
471
+ *
472
+ * const validator = new Validator([preferencesSchema]);
473
+ *
474
+ * const normalized = validator.normalize({
475
+ * height: '180', // String → number
476
+ * isNotificationEnabled: '1' // String '1' → boolean true
477
+ * }, 'Preferences');
478
+ * // Returns: { height: 180, isNotificationEnabled: true }
479
+ * ```
480
+ *
481
+ * **Example - Apply Defaults:**
482
+ * ```typescript
483
+ * const userSchema = new Schema({
484
+ * name: { type: 'string', required: true },
485
+ * status: { enum: ['ACTIVE', 'INACTIVE'], default: 'ACTIVE' },
486
+ * role: { enum: ['USER', 'ADMIN'], default: 'USER' }
487
+ * }, 'User');
488
+ *
489
+ * const validator = new Validator([userSchema]);
490
+ *
491
+ * const normalized = validator.normalize({
492
+ * name: 'John'
493
+ * // status and role are not provided
494
+ * }, 'User');
495
+ * // Returns: { name: 'John', status: 'ACTIVE', role: 'USER' }
496
+ * ```
497
+ *
498
+ * **Example - Partial Data:**
499
+ * ```typescript
500
+ * // Useful for partial updates where validation might fail
501
+ * const partial = validator.normalize({
502
+ * age: '25' // Only updating age, other fields missing
503
+ * }, 'User');
504
+ * // Normalizes age to number without requiring other fields
505
+ * ```
506
+ */
507
+ normalize(object: TargetObject, schemaId: string) {
508
+ const jsonSchema = got(this._jsonSchemasMap, schemaId, 'Schema "$PATH" not found');
509
+ const result = JSON.parse(JSON.stringify(object));
510
+
511
+ normalizeAttributes(result, jsonSchema, this._jsonSchemasMap);
512
+
513
+ return result;
514
+ }
515
+
516
+ /**
517
+ * Returns a map of all registered schemas by their IDs.
518
+ *
519
+ * **Intent:** Provide access to all schemas registered with this validator, enabling
520
+ * inspection, iteration, or programmatic access to schema definitions.
521
+ *
522
+ * **Use Cases:**
523
+ * - Inspect all available schemas
524
+ * - Iterate over schemas for bulk operations
525
+ * - Access schema metadata or properties
526
+ * - Build UI components that list available schemas
527
+ * - Debug schema registration
528
+ *
529
+ * @returns A record mapping schema IDs to Schema instances
530
+ *
531
+ * **Example:**
532
+ * ```typescript
533
+ * const validator = new Validator([userSchema, statusSchema]);
534
+ *
535
+ * const schemas = validator.schemasMap;
536
+ * // { 'User': Schema instance, 'Status': Schema instance }
537
+ *
538
+ * // Access a specific schema
539
+ * const userSchema = schemas['User'];
540
+ *
541
+ * // Iterate over all schemas
542
+ * Object.keys(schemas).forEach(id => {
543
+ * console.log(`Schema ${id} is registered`);
544
+ * });
545
+ * ```
546
+ */
547
+ get schemasMap() {
548
+ return this._schemasMap;
549
+ }
550
+
551
+ /**
552
+ * Returns the IDs of all schemas referenced by the specified schema.
553
+ *
554
+ * **Intent:** Discover schema dependencies by finding all schemas referenced via `$ref`
555
+ * in a given schema. This is useful for understanding schema relationships and building
556
+ * dependency graphs.
557
+ *
558
+ * **Use Cases:**
559
+ * - Build schema dependency graphs
560
+ * - Validate that all referenced schemas are available
561
+ * - Generate documentation showing schema relationships
562
+ * - Determine which schemas need to be loaded together
563
+ * - Debug schema reference issues
564
+ *
565
+ * @param schemaId - The ID of the schema to analyze for references
566
+ *
567
+ * @returns An array of schema IDs that are referenced by the specified schema
568
+ *
569
+ * @throws Error if schema with `schemaId` is not found
570
+ *
571
+ * **Example:**
572
+ * ```typescript
573
+ * const addressSchema = new Schema({
574
+ * street: { type: 'string' }
575
+ * }, 'Address');
576
+ *
577
+ * const userSchema = new Schema({
578
+ * name: { type: 'string' },
579
+ * address: { $ref: 'Address' },
580
+ * status: { $ref: 'Status' }
581
+ * }, 'User');
582
+ *
583
+ * const validator = new Validator([addressSchema, statusSchema, userSchema]);
584
+ *
585
+ * const references = validator.getReferenceIds('User');
586
+ * // Returns: ['Address', 'Status']
587
+ * ```
588
+ *
589
+ * **Example - Nested References:**
590
+ * ```typescript
591
+ * // If Address schema also references Country schema
592
+ * const references = validator.getReferenceIds('User');
593
+ * // Returns: ['Address', 'Status', 'Country'] (includes nested references)
594
+ * ```
595
+ */
596
+ getReferenceIds(schemaId: string) {
597
+ const schema = got(this.schemasMap, schemaId, 'Schema "$PATH" not found');
598
+
599
+ return getReferenceIds(schema, this._schemasMap);
600
+ }
601
+ }
602
+
603
+ export default Validator;