@kravc/schema 2.8.0-alpha.7 → 2.8.0-alpha.8
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/dist/CredentialFactory.d.ts +5 -318
- package/dist/CredentialFactory.d.ts.map +1 -1
- package/dist/CredentialFactory.js +5 -317
- package/dist/CredentialFactory.js.map +1 -1
- package/dist/Schema.d.ts +15 -420
- package/dist/Schema.d.ts.map +1 -1
- package/dist/Schema.js +13 -384
- package/dist/Schema.js.map +1 -1
- package/dist/ValidationError.d.ts +3 -49
- package/dist/ValidationError.d.ts.map +1 -1
- package/dist/ValidationError.js +3 -48
- package/dist/ValidationError.js.map +1 -1
- package/dist/Validator.d.ts +6 -470
- package/dist/Validator.d.ts.map +1 -1
- package/dist/Validator.js +50 -478
- package/dist/Validator.js.map +1 -1
- package/dist/helpers/cleanupAttributes.d.ts +3 -32
- package/dist/helpers/cleanupAttributes.d.ts.map +1 -1
- package/dist/helpers/cleanupAttributes.js +1 -30
- package/dist/helpers/cleanupAttributes.js.map +1 -1
- package/dist/helpers/cleanupNulls.d.ts +1 -25
- package/dist/helpers/cleanupNulls.d.ts.map +1 -1
- package/dist/helpers/cleanupNulls.js +2 -61
- package/dist/helpers/cleanupNulls.js.map +1 -1
- package/dist/helpers/createSchemasMap.d.ts +2 -93
- package/dist/helpers/createSchemasMap.d.ts.map +1 -1
- package/dist/helpers/createSchemasMap.js +4 -162
- package/dist/helpers/createSchemasMap.js.map +1 -1
- package/dist/helpers/getReferenceIds.d.ts +1 -165
- package/dist/helpers/getReferenceIds.d.ts.map +1 -1
- package/dist/helpers/getReferenceIds.js +2 -166
- package/dist/helpers/getReferenceIds.js.map +1 -1
- package/dist/helpers/got.d.ts +1 -57
- package/dist/helpers/got.d.ts.map +1 -1
- package/dist/helpers/got.js +1 -57
- package/dist/helpers/got.js.map +1 -1
- package/dist/helpers/mapObjectProperties.d.ts +2 -144
- package/dist/helpers/mapObjectProperties.d.ts.map +1 -1
- package/dist/helpers/mapObjectProperties.js +1 -142
- package/dist/helpers/mapObjectProperties.js.map +1 -1
- package/dist/helpers/normalizeAttributes.d.ts +3 -211
- package/dist/helpers/normalizeAttributes.d.ts.map +1 -1
- package/dist/helpers/normalizeAttributes.js +1 -209
- package/dist/helpers/normalizeAttributes.js.map +1 -1
- package/dist/helpers/normalizeProperties.d.ts +1 -165
- package/dist/helpers/normalizeProperties.d.ts.map +1 -1
- package/dist/helpers/normalizeProperties.js +1 -164
- package/dist/helpers/normalizeProperties.js.map +1 -1
- package/dist/helpers/normalizeRequired.d.ts +1 -153
- package/dist/helpers/normalizeRequired.d.ts.map +1 -1
- package/dist/helpers/normalizeRequired.js +0 -151
- package/dist/helpers/normalizeRequired.js.map +1 -1
- package/dist/helpers/normalizeType.d.ts +1 -77
- package/dist/helpers/normalizeType.d.ts.map +1 -1
- package/dist/helpers/normalizeType.js +11 -139
- package/dist/helpers/normalizeType.js.map +1 -1
- package/dist/helpers/nullifyEmptyValues.d.ts +1 -135
- package/dist/helpers/nullifyEmptyValues.d.ts.map +1 -1
- package/dist/helpers/nullifyEmptyValues.js +13 -143
- package/dist/helpers/nullifyEmptyValues.js.map +1 -1
- package/dist/helpers/removeRequiredAndDefault.d.ts +2 -102
- package/dist/helpers/removeRequiredAndDefault.d.ts.map +1 -1
- package/dist/helpers/removeRequiredAndDefault.js +1 -100
- package/dist/helpers/removeRequiredAndDefault.js.map +1 -1
- package/dist/helpers/validateId.d.ts +1 -36
- package/dist/helpers/validateId.d.ts.map +1 -1
- package/dist/helpers/validateId.js +1 -36
- package/dist/helpers/validateId.js.map +1 -1
- package/dist/ld/documentLoader.d.ts +1 -1
- package/dist/ld/documentLoader.d.ts.map +1 -1
- package/dist/ld/documentLoader.js +1 -1
- package/dist/ld/documentLoader.js.map +1 -1
- package/dist/ld/getLinkedDataAttributeType.d.ts +1 -1
- package/dist/ld/getLinkedDataAttributeType.d.ts.map +1 -1
- package/dist/ld/getLinkedDataAttributeType.js +1 -1
- package/dist/ld/getLinkedDataAttributeType.js.map +1 -1
- package/dist/ld/getLinkedDataContext.d.ts +1 -1
- package/dist/ld/getLinkedDataContext.d.ts.map +1 -1
- package/dist/ld/getLinkedDataContext.js +1 -1
- package/dist/ld/getLinkedDataContext.js.map +1 -1
- package/package.json +2 -2
- package/src/CredentialFactory.ts +5 -318
- package/src/Schema.ts +17 -427
- package/src/ValidationError.ts +5 -52
- package/src/Validator.ts +19 -483
- package/src/__tests__/CredentialFactory.test.ts +1 -1
- package/src/__tests__/Schema.test.ts +3 -8
- package/src/__tests__/ValidationError.test.ts +4 -2
- package/src/__tests__/Validator.test.ts +21 -4
- package/src/helpers/__tests__/cleanupAttributes.test.ts +3 -1
- package/src/helpers/__tests__/createSchemasMap.test.ts +1 -1
- package/src/helpers/__tests__/mapObjectProperties.test.ts +2 -1
- package/src/helpers/__tests__/normalizeAttributes.test.ts +4 -2
- package/src/helpers/__tests__/normalizeProperties.test.ts +3 -1
- package/src/helpers/__tests__/normalizeRequired.test.ts +4 -9
- package/src/helpers/__tests__/nullifyEmptyValues.test.ts +43 -12
- package/src/helpers/__tests__/removeRequiredAndDefault.test.ts +3 -10
- package/src/helpers/cleanupAttributes.ts +6 -44
- package/src/helpers/cleanupNulls.ts +2 -63
- package/src/helpers/createSchemasMap.ts +4 -163
- package/src/helpers/getReferenceIds.ts +2 -173
- package/src/helpers/got.ts +1 -57
- package/src/helpers/mapObjectProperties.ts +4 -156
- package/src/helpers/normalizeAttributes.ts +7 -211
- package/src/helpers/normalizeProperties.ts +1 -172
- package/src/helpers/normalizeRequired.ts +1 -161
- package/src/helpers/normalizeType.ts +11 -139
- package/src/helpers/nullifyEmptyValues.ts +10 -145
- package/src/helpers/removeRequiredAndDefault.ts +1 -106
- package/src/helpers/validateId.ts +1 -36
- package/src/ld/documentLoader.ts +1 -1
- package/src/ld/getLinkedDataAttributeType.ts +1 -1
- package/src/ld/getLinkedDataContext.ts +1 -1
- package/src/{helpers/JsonSchema.ts → types.d.ts} +12 -16
- package/dist/helpers/JsonSchema.d.ts +0 -99
- package/dist/helpers/JsonSchema.d.ts.map +0 -1
- package/dist/helpers/JsonSchema.js +0 -3
- package/dist/helpers/JsonSchema.js.map +0 -1
package/dist/Validator.js
CHANGED
|
@@ -1,10 +1,43 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
2
35
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
36
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
37
|
};
|
|
5
38
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
const z_schema_1 = __importDefault(require("z-schema"));
|
|
7
39
|
const lodash_1 = require("lodash");
|
|
40
|
+
const z_schema_1 = __importStar(require("z-schema"));
|
|
8
41
|
const got_1 = __importDefault(require("./helpers/got"));
|
|
9
42
|
const cleanupNulls_1 = __importDefault(require("./helpers/cleanupNulls"));
|
|
10
43
|
const getReferenceIds_1 = __importDefault(require("./helpers/getReferenceIds"));
|
|
@@ -12,245 +45,12 @@ const ValidationError_1 = __importDefault(require("./ValidationError"));
|
|
|
12
45
|
const cleanupAttributes_1 = __importDefault(require("./helpers/cleanupAttributes"));
|
|
13
46
|
const nullifyEmptyValues_1 = __importDefault(require("./helpers/nullifyEmptyValues"));
|
|
14
47
|
const normalizeAttributes_1 = __importDefault(require("./helpers/normalizeAttributes"));
|
|
15
|
-
/**
|
|
16
|
-
* Validator for validating and normalizing objects against JSON schemas.
|
|
17
|
-
*
|
|
18
|
-
* **Intent:**
|
|
19
|
-
* The Validator class provides a comprehensive solution for validating objects against JSON schemas
|
|
20
|
-
* with built-in normalization, cleanup, and error handling capabilities. It serves as the primary
|
|
21
|
-
* interface for ensuring data integrity and consistency in applications that work with structured
|
|
22
|
-
* data, particularly in API endpoints, data transformation pipelines, and credential systems.
|
|
23
|
-
*
|
|
24
|
-
* The validator performs several key operations:
|
|
25
|
-
* - Validates objects against registered schemas using JSON Schema validation
|
|
26
|
-
* - Removes attributes not defined in the schema (cleanup)
|
|
27
|
-
* - Normalizes attribute types (e.g., string '1' → boolean true, string '180' → number 180)
|
|
28
|
-
* - Handles empty values by optionally nullifying them for non-required fields
|
|
29
|
-
* - Provides detailed validation errors with structured error information
|
|
30
|
-
*
|
|
31
|
-
* **Use Cases:**
|
|
32
|
-
*
|
|
33
|
-
* 1. **API Request/Response Validation:**
|
|
34
|
-
* - Validate incoming API requests against defined schemas
|
|
35
|
-
* - Ensure API responses conform to expected structure
|
|
36
|
-
* - Clean up extra fields sent by clients
|
|
37
|
-
* - Normalize data from query parameters or form submissions
|
|
38
|
-
*
|
|
39
|
-
* 2. **Data Integration & Third-Party Services:**
|
|
40
|
-
* - Integrate with external APIs that send loosely-typed data
|
|
41
|
-
* - Normalize data from URLs where types are strings (e.g., 'true', '1', '180')
|
|
42
|
-
* - Clean up payloads before sending to third-party services (e.g., Telegram, webhooks)
|
|
43
|
-
* - Handle data from systems that don't enforce strict typing
|
|
44
|
-
*
|
|
45
|
-
* 3. **Credential & Identity Systems:**
|
|
46
|
-
* - Validate verifiable credentials against schema definitions
|
|
47
|
-
* - Ensure credential subjects conform to expected schemas
|
|
48
|
-
* - Normalize credential data from various sources
|
|
49
|
-
*
|
|
50
|
-
* 4. **Data Transformation Pipelines:**
|
|
51
|
-
* - Normalize data types without full validation
|
|
52
|
-
* - Clean up data structures before processing
|
|
53
|
-
* - Transform data between different formats while maintaining schema compliance
|
|
54
|
-
*
|
|
55
|
-
* 5. **Form & User Input Processing:**
|
|
56
|
-
* - Validate and normalize form submissions
|
|
57
|
-
* - Handle empty values gracefully (nullify empty strings for optional fields)
|
|
58
|
-
* - Clean up null values from nested objects
|
|
59
|
-
*
|
|
60
|
-
* **Example - Basic Validation:**
|
|
61
|
-
* ```typescript
|
|
62
|
-
* const userSchema = new Schema({
|
|
63
|
-
* name: { type: 'string', required: true },
|
|
64
|
-
* email: { type: 'string', format: 'email', required: true },
|
|
65
|
-
* age: { type: 'number', minimum: 0 }
|
|
66
|
-
* }, 'User');
|
|
67
|
-
*
|
|
68
|
-
* const validator = new Validator([userSchema]);
|
|
69
|
-
*
|
|
70
|
-
* const validUser = validator.validate({
|
|
71
|
-
* name: 'John Doe',
|
|
72
|
-
* email: 'john@example.com',
|
|
73
|
-
* age: 30
|
|
74
|
-
* }, 'User');
|
|
75
|
-
* // Returns: { name: 'John Doe', email: 'john@example.com', age: 30 }
|
|
76
|
-
* ```
|
|
77
|
-
*
|
|
78
|
-
* **Example - Normalization (String to Type Conversion):**
|
|
79
|
-
* ```typescript
|
|
80
|
-
* // Useful when receiving data from URLs or forms where types are strings
|
|
81
|
-
* const preferencesSchema = new Schema({
|
|
82
|
-
* height: { type: 'number' },
|
|
83
|
-
* isNotificationEnabled: { type: 'boolean' }
|
|
84
|
-
* }, 'Preferences');
|
|
85
|
-
*
|
|
86
|
-
* const validator = new Validator([preferencesSchema]);
|
|
87
|
-
*
|
|
88
|
-
* const normalized = validator.validate({
|
|
89
|
-
* height: '180', // String '180' → number 180
|
|
90
|
-
* isNotificationEnabled: '1' // String '1' → boolean true
|
|
91
|
-
* }, 'Preferences');
|
|
92
|
-
* // Returns: { height: 180, isNotificationEnabled: true }
|
|
93
|
-
* ```
|
|
94
|
-
*
|
|
95
|
-
* **Example - Cleanup (Remove Extra Attributes):**
|
|
96
|
-
* ```typescript
|
|
97
|
-
* const profileSchema = new Schema({
|
|
98
|
-
* name: { type: 'string', required: true },
|
|
99
|
-
* email: { type: 'string', required: true }
|
|
100
|
-
* }, 'Profile');
|
|
101
|
-
*
|
|
102
|
-
* const validator = new Validator([profileSchema]);
|
|
103
|
-
*
|
|
104
|
-
* const cleaned = validator.validate({
|
|
105
|
-
* name: 'John',
|
|
106
|
-
* email: 'john@example.com',
|
|
107
|
-
* extraField: 'should be removed',
|
|
108
|
-
* _internalId: 'should be removed'
|
|
109
|
-
* }, 'Profile', false, true);
|
|
110
|
-
* // Returns: { name: 'John', email: 'john@example.com' }
|
|
111
|
-
* // extraField and _internalId are removed
|
|
112
|
-
* ```
|
|
113
|
-
*
|
|
114
|
-
* **Example - Nullify Empty Values:**
|
|
115
|
-
* ```typescript
|
|
116
|
-
* const profileSchema = new Schema({
|
|
117
|
-
* name: { type: 'string', required: true },
|
|
118
|
-
* gender: { enum: ['Male', 'Female', 'Other'] }, // Optional
|
|
119
|
-
* mobileNumber: { type: 'string', pattern: '^\\d+$' } // Optional
|
|
120
|
-
* }, 'Profile');
|
|
121
|
-
*
|
|
122
|
-
* const validator = new Validator([profileSchema]);
|
|
123
|
-
*
|
|
124
|
-
* const result = validator.validate({
|
|
125
|
-
* name: 'John',
|
|
126
|
-
* gender: '', // Empty string for optional enum
|
|
127
|
-
* mobileNumber: '' // Empty string for optional pattern field
|
|
128
|
-
* }, 'Profile', true); // shouldNullifyEmptyValues = true
|
|
129
|
-
* // Returns: { name: 'John', gender: null, mobileNumber: null }
|
|
130
|
-
* // Empty values are converted to null for non-required fields
|
|
131
|
-
* ```
|
|
132
|
-
*
|
|
133
|
-
* **Example - Normalization Only (Without Validation):**
|
|
134
|
-
* ```typescript
|
|
135
|
-
* const preferencesSchema = new Schema({
|
|
136
|
-
* height: { type: 'number' },
|
|
137
|
-
* isNotificationEnabled: { type: 'boolean', default: false }
|
|
138
|
-
* }, 'Preferences');
|
|
139
|
-
*
|
|
140
|
-
* const validator = new Validator([preferencesSchema]);
|
|
141
|
-
*
|
|
142
|
-
* // Normalize without validation - useful for partial data
|
|
143
|
-
* const normalized = validator.normalize({
|
|
144
|
-
* height: '180'
|
|
145
|
-
* }, 'Preferences');
|
|
146
|
-
* // Returns: { height: 180, isNotificationEnabled: false }
|
|
147
|
-
* // Applies normalization and defaults without validation
|
|
148
|
-
* ```
|
|
149
|
-
*
|
|
150
|
-
* **Example - Error Handling:**
|
|
151
|
-
* ```typescript
|
|
152
|
-
* const validator = new Validator([userSchema]);
|
|
153
|
-
*
|
|
154
|
-
* try {
|
|
155
|
-
* validator.validate({
|
|
156
|
-
* name: '', // Empty required field
|
|
157
|
-
* email: 'invalid-email' // Invalid format
|
|
158
|
-
* }, 'User');
|
|
159
|
-
* } catch (error) {
|
|
160
|
-
* if (error instanceof ValidationError) {
|
|
161
|
-
* const errorDetails = error.toJSON();
|
|
162
|
-
* console.error(errorDetails.schemaId); // 'User'
|
|
163
|
-
* console.error(errorDetails.validationErrors);
|
|
164
|
-
* // [
|
|
165
|
-
* // { path: '#/name', code: 'MIN_LENGTH', message: '...' },
|
|
166
|
-
* // { path: '#/email', code: 'INVALID_FORMAT', message: '...' }
|
|
167
|
-
* // ]
|
|
168
|
-
* }
|
|
169
|
-
* }
|
|
170
|
-
* ```
|
|
171
|
-
*
|
|
172
|
-
* **Example - Schema References:**
|
|
173
|
-
* ```typescript
|
|
174
|
-
* const addressSchema = new Schema({
|
|
175
|
-
* street: { type: 'string', required: true },
|
|
176
|
-
* city: { type: 'string', required: true }
|
|
177
|
-
* }, 'Address');
|
|
178
|
-
*
|
|
179
|
-
* const userSchema = new Schema({
|
|
180
|
-
* name: { type: 'string', required: true },
|
|
181
|
-
* address: { $ref: 'Address' }
|
|
182
|
-
* }, 'User');
|
|
183
|
-
*
|
|
184
|
-
* const validator = new Validator([addressSchema, userSchema]);
|
|
185
|
-
*
|
|
186
|
-
* // Get all schemas referenced by User schema
|
|
187
|
-
* const referencedIds = validator.getReferenceIds('User');
|
|
188
|
-
* // Returns: ['Address']
|
|
189
|
-
* ```
|
|
190
|
-
*
|
|
191
|
-
* **Example - Multiple Schemas:**
|
|
192
|
-
* ```typescript
|
|
193
|
-
* const statusSchema = new Schema({ enum: ['ACTIVE', 'INACTIVE'] }, 'Status');
|
|
194
|
-
* const profileSchema = new Schema({
|
|
195
|
-
* name: { type: 'string', required: true },
|
|
196
|
-
* status: { $ref: 'Status' }
|
|
197
|
-
* }, 'Profile');
|
|
198
|
-
*
|
|
199
|
-
* const validator = new Validator([statusSchema, profileSchema]);
|
|
200
|
-
*
|
|
201
|
-
* const result = validator.validate({
|
|
202
|
-
* name: 'John',
|
|
203
|
-
* status: 'ACTIVE'
|
|
204
|
-
* }, 'Profile');
|
|
205
|
-
* ```
|
|
206
|
-
*/
|
|
48
|
+
/** Validator for validating and normalizing objects against JSON schemas. */
|
|
207
49
|
class Validator {
|
|
208
50
|
_engine;
|
|
209
51
|
_schemasMap;
|
|
210
52
|
_jsonSchemasMap;
|
|
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
|
-
*/
|
|
53
|
+
/** Creates a validator instance for a collection of schemas. */
|
|
254
54
|
constructor(schemas) {
|
|
255
55
|
if (!schemas) {
|
|
256
56
|
throw new Error('No schemas provided');
|
|
@@ -263,108 +63,23 @@ class Validator {
|
|
|
263
63
|
throw new Error(`Multiple schemas provided for ID: ${id}`);
|
|
264
64
|
}
|
|
265
65
|
}
|
|
266
|
-
this._engine =
|
|
66
|
+
this._engine = z_schema_1.default.create({
|
|
267
67
|
reportPathAsArray: false,
|
|
268
68
|
ignoreUnknownFormats: true,
|
|
269
69
|
});
|
|
270
70
|
const jsonSchemas = schemas.map(({ jsonSchema }) => jsonSchema);
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
71
|
+
try {
|
|
72
|
+
this._engine.validateSchema(jsonSchemas);
|
|
73
|
+
}
|
|
74
|
+
catch (error) {
|
|
75
|
+
const details = error instanceof z_schema_1.ValidateError && error.details ? error.details : [];
|
|
76
|
+
const errorsJson = JSON.stringify(details, null, 2);
|
|
275
77
|
throw new Error(`Schemas validation failed, errors: ${errorsJson}`);
|
|
276
78
|
}
|
|
277
79
|
this._schemasMap = (0, lodash_1.keyBy)(schemas, 'id');
|
|
278
80
|
this._jsonSchemasMap = (0, lodash_1.keyBy)(jsonSchemas, 'id');
|
|
279
81
|
}
|
|
280
|
-
/**
|
|
281
|
-
* Validates, cleans, and normalizes an object against a registered schema.
|
|
282
|
-
*
|
|
283
|
-
* **Intent:** Perform comprehensive validation and transformation of objects to ensure they
|
|
284
|
-
* conform to schema definitions. This method combines validation, attribute cleanup, type
|
|
285
|
-
* normalization, and optional empty value handling in a single operation.
|
|
286
|
-
*
|
|
287
|
-
* **Use Cases:**
|
|
288
|
-
* - Validate API request payloads before processing
|
|
289
|
-
* - Clean up objects by removing undefined attributes
|
|
290
|
-
* - Normalize data types from loosely-typed sources (URLs, forms, external APIs)
|
|
291
|
-
* - Handle empty values gracefully for optional fields
|
|
292
|
-
* - Prepare data for storage or transmission
|
|
293
|
-
*
|
|
294
|
-
* **Processing Pipeline:**
|
|
295
|
-
* 1. Deep clones the input object
|
|
296
|
-
* 2. Optionally removes null values (if `shouldCleanupNulls` is true)
|
|
297
|
-
* 3. Removes attributes not defined in the schema
|
|
298
|
-
* 4. Normalizes attribute types (string → number/boolean, etc.)
|
|
299
|
-
* 5. Validates against JSON Schema
|
|
300
|
-
* 6. Optionally nullifies empty values for non-required fields
|
|
301
|
-
* 7. Returns validated and normalized object, or throws ValidationError
|
|
302
|
-
*
|
|
303
|
-
* @param object - The object to validate and normalize
|
|
304
|
-
* @param schemaId - The ID of the schema to validate against (must be registered in constructor)
|
|
305
|
-
* @param shouldNullifyEmptyValues - If true, converts empty strings to null for non-required
|
|
306
|
-
* fields that fail format/pattern/enum validation. Useful for
|
|
307
|
-
* handling form submissions where empty fields are sent as ''.
|
|
308
|
-
* @param shouldCleanupNulls - If true, removes null values from the object before processing.
|
|
309
|
-
* Useful for cleaning up data structures.
|
|
310
|
-
*
|
|
311
|
-
* @returns The validated, cleaned, and normalized object
|
|
312
|
-
*
|
|
313
|
-
* @throws Error if schema with `schemaId` is not found
|
|
314
|
-
* @throws ValidationError if validation fails (contains detailed error information)
|
|
315
|
-
*
|
|
316
|
-
* **Example - Basic Validation:**
|
|
317
|
-
* ```typescript
|
|
318
|
-
* const validator = new Validator([userSchema]);
|
|
319
|
-
*
|
|
320
|
-
* const result = validator.validate({
|
|
321
|
-
* name: 'John',
|
|
322
|
-
* email: 'john@example.com'
|
|
323
|
-
* }, 'User');
|
|
324
|
-
* ```
|
|
325
|
-
*
|
|
326
|
-
* **Example - With Cleanup:**
|
|
327
|
-
* ```typescript
|
|
328
|
-
* const result = validator.validate({
|
|
329
|
-
* name: 'John',
|
|
330
|
-
* extraField: 'removed',
|
|
331
|
-
* nullField: null
|
|
332
|
-
* }, 'User', false, true);
|
|
333
|
-
* // extraField and nullField are removed
|
|
334
|
-
* ```
|
|
335
|
-
*
|
|
336
|
-
* **Example - With Normalization:**
|
|
337
|
-
* ```typescript
|
|
338
|
-
* const result = validator.validate({
|
|
339
|
-
* name: 'John',
|
|
340
|
-
* age: '30', // String → number
|
|
341
|
-
* isActive: 'true' // String → boolean
|
|
342
|
-
* }, 'User');
|
|
343
|
-
* // age becomes 30, isActive becomes true
|
|
344
|
-
* ```
|
|
345
|
-
*
|
|
346
|
-
* **Example - Nullify Empty Values:**
|
|
347
|
-
* ```typescript
|
|
348
|
-
* const result = validator.validate({
|
|
349
|
-
* name: 'John',
|
|
350
|
-
* optionalEmail: '', // Empty string
|
|
351
|
-
* optionalPhone: '' // Empty string
|
|
352
|
-
* }, 'User', true);
|
|
353
|
-
* // optionalEmail and optionalPhone become null (if not required)
|
|
354
|
-
* ```
|
|
355
|
-
*
|
|
356
|
-
* **Example - Error Handling:**
|
|
357
|
-
* ```typescript
|
|
358
|
-
* try {
|
|
359
|
-
* validator.validate({ name: '' }, 'User');
|
|
360
|
-
* } catch (error) {
|
|
361
|
-
* if (error instanceof ValidationError) {
|
|
362
|
-
* const details = error.toJSON();
|
|
363
|
-
* // Access error.schemaId, error.validationErrors, etc.
|
|
364
|
-
* }
|
|
365
|
-
* }
|
|
366
|
-
* ```
|
|
367
|
-
*/
|
|
82
|
+
/** Validates, cleans, and normalizes an object against a registered schema. */
|
|
368
83
|
validate(object, schemaId, shouldNullifyEmptyValues = false, shouldCleanupNulls = false) {
|
|
369
84
|
const jsonSchema = (0, got_1.default)(this._jsonSchemasMap, schemaId, 'Schema "$PATH" not found');
|
|
370
85
|
const objectJson = JSON.stringify(object);
|
|
@@ -391,11 +106,11 @@ class Validator {
|
|
|
391
106
|
// NOTE: Skip errors in cleanup and normalize attributes methods.
|
|
392
107
|
// Validation would fail below for objects with invalid value types.
|
|
393
108
|
}
|
|
394
|
-
const
|
|
395
|
-
if (
|
|
109
|
+
const validationResult = this._engine.validateSafe(result, jsonSchema);
|
|
110
|
+
if (validationResult.valid) {
|
|
396
111
|
return result;
|
|
397
112
|
}
|
|
398
|
-
const validationErrors =
|
|
113
|
+
const validationErrors = validationResult.err?.details ?? [];
|
|
399
114
|
if (!shouldNullifyEmptyValues) {
|
|
400
115
|
throw new ValidationError_1.default(schemaId, result, validationErrors);
|
|
401
116
|
}
|
|
@@ -406,161 +121,18 @@ class Validator {
|
|
|
406
121
|
}
|
|
407
122
|
return nullifiedResult;
|
|
408
123
|
}
|
|
409
|
-
/**
|
|
410
|
-
* Normalizes object attributes using a schema without performing validation.
|
|
411
|
-
*
|
|
412
|
-
* **Intent:** Apply type normalization and default values to an object without the strictness
|
|
413
|
-
* of full validation. This is useful when you want to transform data types but don't need
|
|
414
|
-
* complete schema compliance, or when working with partial/incomplete data.
|
|
415
|
-
*
|
|
416
|
-
* **Use Cases:**
|
|
417
|
-
* - Normalize data types from loosely-typed sources (URLs, query parameters, forms)
|
|
418
|
-
* - Apply default values from schemas to partial objects
|
|
419
|
-
* - Transform data before validation in a separate step
|
|
420
|
-
* - Prepare data for display or processing without strict validation
|
|
421
|
-
* - Handle partial updates where not all fields are present
|
|
422
|
-
*
|
|
423
|
-
* **What It Does:**
|
|
424
|
-
* - Deep clones the input object
|
|
425
|
-
* - Normalizes attribute types (string '1' → boolean true, string '180' → number 180)
|
|
426
|
-
* - Applies default values from schema definitions
|
|
427
|
-
* - Does NOT validate required fields, formats, patterns, or enums
|
|
428
|
-
* - Does NOT remove undefined attributes
|
|
429
|
-
*
|
|
430
|
-
* @param object - The object to normalize
|
|
431
|
-
* @param schemaId - The ID of the schema to use for normalization (must be registered)
|
|
432
|
-
*
|
|
433
|
-
* @returns A new object with normalized types and applied defaults
|
|
434
|
-
*
|
|
435
|
-
* @throws Error if schema with `schemaId` is not found
|
|
436
|
-
*
|
|
437
|
-
* **Example - Type Normalization:**
|
|
438
|
-
* ```typescript
|
|
439
|
-
* const preferencesSchema = new Schema({
|
|
440
|
-
* height: { type: 'number' },
|
|
441
|
-
* isNotificationEnabled: { type: 'boolean', default: false }
|
|
442
|
-
* }, 'Preferences');
|
|
443
|
-
*
|
|
444
|
-
* const validator = new Validator([preferencesSchema]);
|
|
445
|
-
*
|
|
446
|
-
* const normalized = validator.normalize({
|
|
447
|
-
* height: '180', // String → number
|
|
448
|
-
* isNotificationEnabled: '1' // String '1' → boolean true
|
|
449
|
-
* }, 'Preferences');
|
|
450
|
-
* // Returns: { height: 180, isNotificationEnabled: true }
|
|
451
|
-
* ```
|
|
452
|
-
*
|
|
453
|
-
* **Example - Apply Defaults:**
|
|
454
|
-
* ```typescript
|
|
455
|
-
* const userSchema = new Schema({
|
|
456
|
-
* name: { type: 'string', required: true },
|
|
457
|
-
* status: { enum: ['ACTIVE', 'INACTIVE'], default: 'ACTIVE' },
|
|
458
|
-
* role: { enum: ['USER', 'ADMIN'], default: 'USER' }
|
|
459
|
-
* }, 'User');
|
|
460
|
-
*
|
|
461
|
-
* const validator = new Validator([userSchema]);
|
|
462
|
-
*
|
|
463
|
-
* const normalized = validator.normalize({
|
|
464
|
-
* name: 'John'
|
|
465
|
-
* // status and role are not provided
|
|
466
|
-
* }, 'User');
|
|
467
|
-
* // Returns: { name: 'John', status: 'ACTIVE', role: 'USER' }
|
|
468
|
-
* ```
|
|
469
|
-
*
|
|
470
|
-
* **Example - Partial Data:**
|
|
471
|
-
* ```typescript
|
|
472
|
-
* // Useful for partial updates where validation might fail
|
|
473
|
-
* const partial = validator.normalize({
|
|
474
|
-
* age: '25' // Only updating age, other fields missing
|
|
475
|
-
* }, 'User');
|
|
476
|
-
* // Normalizes age to number without requiring other fields
|
|
477
|
-
* ```
|
|
478
|
-
*/
|
|
124
|
+
/** Normalizes object attributes using a schema without performing validation. */
|
|
479
125
|
normalize(object, schemaId) {
|
|
480
126
|
const jsonSchema = (0, got_1.default)(this._jsonSchemasMap, schemaId, 'Schema "$PATH" not found');
|
|
481
127
|
const result = JSON.parse(JSON.stringify(object));
|
|
482
128
|
(0, normalizeAttributes_1.default)(result, jsonSchema, this._jsonSchemasMap);
|
|
483
129
|
return result;
|
|
484
130
|
}
|
|
485
|
-
/**
|
|
486
|
-
* Returns a map of all registered schemas by their IDs.
|
|
487
|
-
*
|
|
488
|
-
* **Intent:** Provide access to all schemas registered with this validator, enabling
|
|
489
|
-
* inspection, iteration, or programmatic access to schema definitions.
|
|
490
|
-
*
|
|
491
|
-
* **Use Cases:**
|
|
492
|
-
* - Inspect all available schemas
|
|
493
|
-
* - Iterate over schemas for bulk operations
|
|
494
|
-
* - Access schema metadata or properties
|
|
495
|
-
* - Build UI components that list available schemas
|
|
496
|
-
* - Debug schema registration
|
|
497
|
-
*
|
|
498
|
-
* @returns A record mapping schema IDs to Schema instances
|
|
499
|
-
*
|
|
500
|
-
* **Example:**
|
|
501
|
-
* ```typescript
|
|
502
|
-
* const validator = new Validator([userSchema, statusSchema]);
|
|
503
|
-
*
|
|
504
|
-
* const schemas = validator.schemasMap;
|
|
505
|
-
* // { 'User': Schema instance, 'Status': Schema instance }
|
|
506
|
-
*
|
|
507
|
-
* // Access a specific schema
|
|
508
|
-
* const userSchema = schemas['User'];
|
|
509
|
-
*
|
|
510
|
-
* // Iterate over all schemas
|
|
511
|
-
* Object.keys(schemas).forEach(id => {
|
|
512
|
-
* console.log(`Schema ${id} is registered`);
|
|
513
|
-
* });
|
|
514
|
-
* ```
|
|
515
|
-
*/
|
|
131
|
+
/** Returns a map of all registered schemas by their IDs. */
|
|
516
132
|
get schemasMap() {
|
|
517
133
|
return this._schemasMap;
|
|
518
134
|
}
|
|
519
|
-
/**
|
|
520
|
-
* Returns the IDs of all schemas referenced by the specified schema.
|
|
521
|
-
*
|
|
522
|
-
* **Intent:** Discover schema dependencies by finding all schemas referenced via `$ref`
|
|
523
|
-
* in a given schema. This is useful for understanding schema relationships and building
|
|
524
|
-
* dependency graphs.
|
|
525
|
-
*
|
|
526
|
-
* **Use Cases:**
|
|
527
|
-
* - Build schema dependency graphs
|
|
528
|
-
* - Validate that all referenced schemas are available
|
|
529
|
-
* - Generate documentation showing schema relationships
|
|
530
|
-
* - Determine which schemas need to be loaded together
|
|
531
|
-
* - Debug schema reference issues
|
|
532
|
-
*
|
|
533
|
-
* @param schemaId - The ID of the schema to analyze for references
|
|
534
|
-
*
|
|
535
|
-
* @returns An array of schema IDs that are referenced by the specified schema
|
|
536
|
-
*
|
|
537
|
-
* @throws Error if schema with `schemaId` is not found
|
|
538
|
-
*
|
|
539
|
-
* **Example:**
|
|
540
|
-
* ```typescript
|
|
541
|
-
* const addressSchema = new Schema({
|
|
542
|
-
* street: { type: 'string' }
|
|
543
|
-
* }, 'Address');
|
|
544
|
-
*
|
|
545
|
-
* const userSchema = new Schema({
|
|
546
|
-
* name: { type: 'string' },
|
|
547
|
-
* address: { $ref: 'Address' },
|
|
548
|
-
* status: { $ref: 'Status' }
|
|
549
|
-
* }, 'User');
|
|
550
|
-
*
|
|
551
|
-
* const validator = new Validator([addressSchema, statusSchema, userSchema]);
|
|
552
|
-
*
|
|
553
|
-
* const references = validator.getReferenceIds('User');
|
|
554
|
-
* // Returns: ['Address', 'Status']
|
|
555
|
-
* ```
|
|
556
|
-
*
|
|
557
|
-
* **Example - Nested References:**
|
|
558
|
-
* ```typescript
|
|
559
|
-
* // If Address schema also references Country schema
|
|
560
|
-
* const references = validator.getReferenceIds('User');
|
|
561
|
-
* // Returns: ['Address', 'Status', 'Country'] (includes nested references)
|
|
562
|
-
* ```
|
|
563
|
-
*/
|
|
135
|
+
/** Returns the IDs of all schemas referenced by the specified schema. */
|
|
564
136
|
getReferenceIds(schemaId) {
|
|
565
137
|
const schema = (0, got_1.default)(this.schemasMap, schemaId, 'Schema "$PATH" not found');
|
|
566
138
|
return (0, getReferenceIds_1.default)(schema, this._schemasMap);
|
package/dist/Validator.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Validator.js","sourceRoot":"","sources":["../src/Validator.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"Validator.js","sourceRoot":"","sources":["../src/Validator.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;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AAE,0BAA0B,CAAC,CAAC;QAE1E,OAAO,IAAA,yBAAe,EAAC,MAAM,EAAE,IAAI,CAAC,WAAW,CAAC,CAAC;IACnD,CAAC;CACF;AAED,kBAAe,SAAS,CAAC"}
|
|
@@ -1,34 +1,5 @@
|
|
|
1
|
-
import type
|
|
2
|
-
/**
|
|
3
|
-
|
|
4
|
-
*
|
|
5
|
-
* **Intent:**
|
|
6
|
-
* This function ensures that objects conform to their schema definition by removing
|
|
7
|
-
* any properties that are not explicitly defined in the schema. It performs a deep
|
|
8
|
-
* cleanup, recursively processing nested objects, arrays, and schema references.
|
|
9
|
-
*
|
|
10
|
-
* **Use Cases:**
|
|
11
|
-
* - **Third-party API integrations**: When integrating with external services (e.g., Telegram)
|
|
12
|
-
* that may send additional fields you don't want to process, this function allows you
|
|
13
|
-
* to define a minimal schema and automatically strip unwanted properties.
|
|
14
|
-
* - **Data sanitization**: Clean up objects received from external sources or user input
|
|
15
|
-
* before validation or processing, ensuring only expected fields are present.
|
|
16
|
-
* - **Schema enforcement**: Enforce strict schema compliance by removing any properties
|
|
17
|
-
* that don't match the defined schema structure.
|
|
18
|
-
* - **Pre-validation cleanup**: Remove extraneous properties before schema validation to
|
|
19
|
-
* prevent validation errors from unexpected fields.
|
|
20
|
-
*
|
|
21
|
-
* **Behavior:**
|
|
22
|
-
* - Mutates the input object in-place (does not return a new object)
|
|
23
|
-
* - Recursively processes nested objects, arrays, and schema references ($ref)
|
|
24
|
-
* - Skips enum schemas (returns early without modification)
|
|
25
|
-
* - Only processes object values (skips null, undefined, and primitive values)
|
|
26
|
-
* - Handles array items by cleaning each object item according to the array's item schema
|
|
27
|
-
*
|
|
28
|
-
* @param object - The target object to clean up (mutated in-place)
|
|
29
|
-
* @param jsonSchema - The JSON schema defining allowed properties
|
|
30
|
-
* @param schemasMap - Optional map of schema IDs to schema definitions for resolving $ref references
|
|
31
|
-
*/
|
|
32
|
-
declare const cleanupAttributes: (object: TargetObject, jsonSchema: JsonSchema, schemasMap?: JsonSchemasMap) => void;
|
|
1
|
+
import { type JsonSchema } from 'z-schema';
|
|
2
|
+
/** Removes properties from an object that are not defined in the JSON schema. */
|
|
3
|
+
declare const cleanupAttributes: (object: TargetObject, jsonSchema: JsonSchema, schemasMap?: Record<string, JsonSchema>) => void;
|
|
33
4
|
export default cleanupAttributes;
|
|
34
5
|
//# sourceMappingURL=cleanupAttributes.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cleanupAttributes.d.ts","sourceRoot":"","sources":["../../src/helpers/cleanupAttributes.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"cleanupAttributes.d.ts","sourceRoot":"","sources":["../../src/helpers/cleanupAttributes.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,UAAU,EAAE,MAAM,UAAU,CAAC;AAI3C,iFAAiF;AACjF,QAAA,MAAM,iBAAiB,GACrB,QAAQ,YAAY,EACpB,YAAY,UAAU,EACtB,aAAY,MAAM,CAAC,MAAM,EAAE,UAAU,CAAM,SAqG5C,CAAC;AAEF,eAAe,iBAAiB,CAAC"}
|