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