@kravc/schema 2.8.0-alpha.6 → 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 +2 -58
- 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 +3 -59
- 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
|
@@ -1,170 +1,10 @@
|
|
|
1
1
|
import { isUndefined } from 'lodash';
|
|
2
2
|
|
|
3
|
-
import type {
|
|
4
|
-
JsonSchema,
|
|
5
|
-
EnumSchema,
|
|
6
|
-
ObjectSchema,
|
|
7
|
-
ArrayPropertySchema,
|
|
8
|
-
ObjectPropertySchema,
|
|
9
|
-
ReferencePropertySchema,
|
|
10
|
-
} from './JsonSchema';
|
|
11
|
-
|
|
12
3
|
/**
|
|
13
4
|
* Normalizes required field declarations in JSON schemas by converting property-level
|
|
14
5
|
* `required` flags to schema-level `required` arrays and `x-required` metadata flags.
|
|
15
|
-
*
|
|
16
|
-
* **Intent:**
|
|
17
|
-
* This function transforms JSON schemas from a property-centric required field model
|
|
18
|
-
* (where each property has its own `required: true/false` flag) to the standard JSON Schema
|
|
19
|
-
* format (where required fields are listed in a top-level `required` array). This normalization
|
|
20
|
-
* ensures compatibility with JSON Schema validators while preserving the original required
|
|
21
|
-
* field information through the `x-required` extension attribute.
|
|
22
|
-
*
|
|
23
|
-
* **Use Cases:**
|
|
24
|
-
* 1. **Schema Standardization**: Convert custom schema formats to standard JSON Schema format
|
|
25
|
-
* for validator compatibility
|
|
26
|
-
* 2. **Schema Transformation**: Prepare schemas for validation libraries that expect
|
|
27
|
-
* required fields in array format
|
|
28
|
-
* 3. **Metadata Preservation**: Maintain required field information in both standard format
|
|
29
|
-
* (`required` array) and extension format (`x-required` flag) for different use cases
|
|
30
|
-
* 4. **Schema Processing Pipeline**: Normalize schemas before validation, credential generation,
|
|
31
|
-
* or API documentation generation
|
|
32
|
-
*
|
|
33
|
-
* **Behavior:**
|
|
34
|
-
* - Mutates the input schema in-place
|
|
35
|
-
* - Moves `required: true` from property level to schema-level `required` array
|
|
36
|
-
* - Sets `x-required: true` on properties that were marked as required
|
|
37
|
-
* - Deletes the `required` property from individual property schemas
|
|
38
|
-
* - Recursively processes nested object properties
|
|
39
|
-
* - Recursively processes array items (including nested objects within arrays)
|
|
40
|
-
* - Skips reference properties (`$ref`) as they are resolved elsewhere
|
|
41
|
-
* - Skips EnumSchema (returns early)
|
|
42
|
-
* - Only sets `required` array if at least one field is required
|
|
43
|
-
*
|
|
44
|
-
* **Examples:**
|
|
45
|
-
*
|
|
46
|
-
* ```typescript
|
|
47
|
-
* // Example 1: Simple object schema
|
|
48
|
-
* const schema = {
|
|
49
|
-
* id: 'User',
|
|
50
|
-
* properties: {
|
|
51
|
-
* name: { type: 'string', required: true },
|
|
52
|
-
* email: { type: 'string', required: true },
|
|
53
|
-
* age: { type: 'number', required: false }
|
|
54
|
-
* }
|
|
55
|
-
* };
|
|
56
|
-
*
|
|
57
|
-
* normalizeRequired(schema);
|
|
58
|
-
* // Result:
|
|
59
|
-
* // schema.required = ['name', 'email']
|
|
60
|
-
* // schema.properties.name['x-required'] = true
|
|
61
|
-
* // schema.properties.email['x-required'] = true
|
|
62
|
-
* // schema.properties.name.required = undefined (deleted)
|
|
63
|
-
* // schema.properties.email.required = undefined (deleted)
|
|
64
|
-
* ```
|
|
65
|
-
*
|
|
66
|
-
* ```typescript
|
|
67
|
-
* // Example 2: Nested objects
|
|
68
|
-
* const schema = {
|
|
69
|
-
* id: 'Order',
|
|
70
|
-
* properties: {
|
|
71
|
-
* user: {
|
|
72
|
-
* type: 'object',
|
|
73
|
-
* required: true,
|
|
74
|
-
* properties: {
|
|
75
|
-
* name: { type: 'string', required: true },
|
|
76
|
-
* address: {
|
|
77
|
-
* type: 'object',
|
|
78
|
-
* properties: {
|
|
79
|
-
* street: { type: 'string', required: true }
|
|
80
|
-
* }
|
|
81
|
-
* }
|
|
82
|
-
* }
|
|
83
|
-
* }
|
|
84
|
-
* }
|
|
85
|
-
* };
|
|
86
|
-
*
|
|
87
|
-
* normalizeRequired(schema);
|
|
88
|
-
* // Result:
|
|
89
|
-
* // schema.required = ['user']
|
|
90
|
-
* // schema.properties.user['x-required'] = true
|
|
91
|
-
* // schema.properties.user.required = ['name']
|
|
92
|
-
* // schema.properties.user.properties.name['x-required'] = true
|
|
93
|
-
* // schema.properties.user.properties.address.required = ['street']
|
|
94
|
-
* // schema.properties.user.properties.address.properties.street['x-required'] = true
|
|
95
|
-
* ```
|
|
96
|
-
*
|
|
97
|
-
* ```typescript
|
|
98
|
-
* // Example 3: Arrays with object items
|
|
99
|
-
* const schema = {
|
|
100
|
-
* id: 'Order',
|
|
101
|
-
* properties: {
|
|
102
|
-
* items: {
|
|
103
|
-
* type: 'array',
|
|
104
|
-
* required: true,
|
|
105
|
-
* items: {
|
|
106
|
-
* type: 'object',
|
|
107
|
-
* properties: {
|
|
108
|
-
* productId: { type: 'string', required: true },
|
|
109
|
-
* quantity: { type: 'number', required: true }
|
|
110
|
-
* }
|
|
111
|
-
* }
|
|
112
|
-
* }
|
|
113
|
-
* }
|
|
114
|
-
* };
|
|
115
|
-
*
|
|
116
|
-
* normalizeRequired(schema);
|
|
117
|
-
* // Result:
|
|
118
|
-
* // schema.required = ['items']
|
|
119
|
-
* // schema.properties.items['x-required'] = true
|
|
120
|
-
* // schema.properties.items.items.required = ['productId', 'quantity']
|
|
121
|
-
* // schema.properties.items.items.properties.productId['x-required'] = true
|
|
122
|
-
* // schema.properties.items.items.properties.quantity['x-required'] = true
|
|
123
|
-
* ```
|
|
124
|
-
*
|
|
125
|
-
* ```typescript
|
|
126
|
-
* // Example 4: Mixed structure
|
|
127
|
-
* const schema = {
|
|
128
|
-
* id: 'Profile',
|
|
129
|
-
* properties: {
|
|
130
|
-
* name: { type: 'string', required: true },
|
|
131
|
-
* address: {
|
|
132
|
-
* type: 'object',
|
|
133
|
-
* required: true,
|
|
134
|
-
* properties: {
|
|
135
|
-
* street: { type: 'string', required: true },
|
|
136
|
-
* city: { type: 'string' }
|
|
137
|
-
* }
|
|
138
|
-
* },
|
|
139
|
-
* tags: {
|
|
140
|
-
* type: 'array',
|
|
141
|
-
* items: {
|
|
142
|
-
* type: 'object',
|
|
143
|
-
* properties: {
|
|
144
|
-
* label: { type: 'string', required: true }
|
|
145
|
-
* }
|
|
146
|
-
* }
|
|
147
|
-
* }
|
|
148
|
-
* }
|
|
149
|
-
* };
|
|
150
|
-
*
|
|
151
|
-
* normalizeRequired(schema);
|
|
152
|
-
* // Result:
|
|
153
|
-
* // schema.required = ['name', 'address']
|
|
154
|
-
* // All nested required fields are normalized recursively
|
|
155
|
-
* ```
|
|
156
|
-
*
|
|
157
|
-
* **Limitations:**
|
|
158
|
-
* - Only processes schemas with a `properties` field (ObjectSchema or ObjectPropertySchema)
|
|
159
|
-
* - EnumSchema is accepted but returns early without processing
|
|
160
|
-
* - Reference properties (`$ref`) are skipped and not processed
|
|
161
|
-
* - The function mutates the input schema object
|
|
162
|
-
* - Does not resolve `$ref` references (they must be resolved separately)
|
|
163
|
-
*
|
|
164
|
-
* @param jsonSchema - The JSON schema to normalize (ObjectSchema, ObjectPropertySchema, or ReferencePropertySchema)
|
|
165
|
-
* @returns void (mutates the input schema in-place)
|
|
166
6
|
*/
|
|
167
|
-
const normalizeRequired = (jsonSchema:
|
|
7
|
+
const normalizeRequired = (jsonSchema: EnumSchema | ObjectSchema | ObjectPropertySchema | ReferencePropertySchema) => {
|
|
168
8
|
const { enum: enumItems } = (jsonSchema as EnumSchema);
|
|
169
9
|
|
|
170
10
|
const isEnum = !!enumItems;
|
|
@@ -3,169 +3,41 @@ type ValueType = 'number' | 'integer' | 'boolean' | 'string' | 'object' | 'array
|
|
|
3
3
|
const BOOLEAN_STRING_TRUE_VALUES = ['yes', 'true', '1'];
|
|
4
4
|
const BOOLEAN_STRING_FALSE_VALUES = ['no', 'false', '0'];
|
|
5
5
|
|
|
6
|
-
/**
|
|
7
|
-
* Checks if a value is null or undefined.
|
|
8
|
-
*
|
|
9
|
-
* @param value - The value to check
|
|
10
|
-
* @returns True if the value is null or undefined, false otherwise
|
|
11
|
-
*/
|
|
6
|
+
/** Checks if a value is null or undefined. */
|
|
12
7
|
const isNullOrUndefined = (value: unknown): value is null | undefined =>
|
|
13
8
|
value === null || value === undefined;
|
|
14
9
|
|
|
15
|
-
/**
|
|
16
|
-
* Checks if a JSON Schema type is numeric (number or integer).
|
|
17
|
-
*
|
|
18
|
-
* @param type - The JSON Schema type to check
|
|
19
|
-
* @returns True if the type is 'number' or 'integer', false otherwise
|
|
20
|
-
*/
|
|
10
|
+
/** Checks if a JSON Schema type is numeric (number or integer). */
|
|
21
11
|
const isNumericType = (type: ValueType): boolean => type === 'number' || type === 'integer';
|
|
22
12
|
|
|
23
|
-
/**
|
|
24
|
-
* Checks if a JSON Schema type is boolean.
|
|
25
|
-
*
|
|
26
|
-
* @param type - The JSON Schema type to check
|
|
27
|
-
* @returns True if the type is 'boolean', false otherwise
|
|
28
|
-
*/
|
|
13
|
+
/** Checks if a JSON Schema type is boolean. */
|
|
29
14
|
const isBooleanType = (type: ValueType): boolean => type === 'boolean';
|
|
30
15
|
|
|
31
|
-
/**
|
|
32
|
-
* Type guard that checks if a value is a number.
|
|
33
|
-
*
|
|
34
|
-
* @param value - The value to check
|
|
35
|
-
* @returns True if the value is a number, false otherwise
|
|
36
|
-
*/
|
|
16
|
+
/** Type guard that checks if a value is a number. */
|
|
37
17
|
const isNumberValue = (value: unknown): value is number => typeof value === 'number';
|
|
38
18
|
|
|
39
|
-
/**
|
|
40
|
-
* Type guard that checks if a value is a boolean.
|
|
41
|
-
*
|
|
42
|
-
* @param value - The value to check
|
|
43
|
-
* @returns True if the value is a boolean, false otherwise
|
|
44
|
-
*/
|
|
19
|
+
/** Type guard that checks if a value is a boolean. */
|
|
45
20
|
const isBooleanValue = (value: unknown): value is boolean => typeof value === 'boolean';
|
|
46
21
|
|
|
47
|
-
/**
|
|
48
|
-
* Type guard that checks if a value is a string.
|
|
49
|
-
*
|
|
50
|
-
* @param value - The value to check
|
|
51
|
-
* @returns True if the value is a string, false otherwise
|
|
52
|
-
*/
|
|
22
|
+
/** Type guard that checks if a value is a string. */
|
|
53
23
|
const isStringValue = (value: unknown): value is string => typeof value === 'string';
|
|
54
24
|
|
|
55
|
-
/**
|
|
56
|
-
* Checks if a string is empty or contains only whitespace characters.
|
|
57
|
-
*
|
|
58
|
-
* @param value - The string to check
|
|
59
|
-
* @returns True if the string is empty or whitespace-only, false otherwise
|
|
60
|
-
*/
|
|
25
|
+
/** Checks if a string is empty or contains only whitespace characters. */
|
|
61
26
|
const isEmptyOrWhitespaceString = (value: string): boolean =>
|
|
62
27
|
value === '' || value.trim() === '';
|
|
63
28
|
|
|
64
|
-
/**
|
|
65
|
-
* Checks if a number is valid (not NaN).
|
|
66
|
-
*
|
|
67
|
-
* @param value - The number to check
|
|
68
|
-
* @returns True if the number is valid (not NaN), false otherwise
|
|
69
|
-
*/
|
|
29
|
+
/** Checks if a number is valid (not NaN). */
|
|
70
30
|
const isValidNumber = (value: number): boolean => !isNaN(value);
|
|
71
31
|
|
|
72
|
-
/**
|
|
73
|
-
* Checks if a string represents a boolean true value.
|
|
74
|
-
* Recognized values (case-insensitive): 'yes', 'true', '1'.
|
|
75
|
-
*
|
|
76
|
-
* @param value - The string to check
|
|
77
|
-
* @returns True if the string represents a boolean true value, false otherwise
|
|
78
|
-
*/
|
|
32
|
+
/** Checks if a string represents a boolean true value. */
|
|
79
33
|
const isBooleanTrueString = (value: string): boolean =>
|
|
80
34
|
BOOLEAN_STRING_TRUE_VALUES.includes(value.toLowerCase());
|
|
81
35
|
|
|
82
|
-
/**
|
|
83
|
-
* Checks if a string represents a boolean false value.
|
|
84
|
-
* Recognized values (case-insensitive): 'no', 'false', '0'.
|
|
85
|
-
*
|
|
86
|
-
* @param value - The string to check
|
|
87
|
-
* @returns True if the string represents a boolean false value, false otherwise
|
|
88
|
-
*/
|
|
36
|
+
/** Checks if a string represents a boolean false value. */
|
|
89
37
|
const isBooleanFalseString = (value: string): boolean =>
|
|
90
38
|
BOOLEAN_STRING_FALSE_VALUES.includes(value.toLowerCase());
|
|
91
39
|
|
|
92
|
-
/**
|
|
93
|
-
* Normalizes a value to match a specified JSON Schema type.
|
|
94
|
-
*
|
|
95
|
-
* ## Intent
|
|
96
|
-
*
|
|
97
|
-
* This function is designed to coerce values into their expected types based on JSON Schema
|
|
98
|
-
* type definitions. It's particularly useful when processing data from external sources (like
|
|
99
|
-
* form inputs, query parameters, or API responses) where values may arrive as strings but
|
|
100
|
-
* need to be converted to their proper types according to a schema definition.
|
|
101
|
-
*
|
|
102
|
-
* The function performs type coercion where appropriate, but preserves the original value
|
|
103
|
-
* when conversion is not possible or when the value is already of the correct type. This
|
|
104
|
-
* makes it safe to use in data normalization pipelines without losing information.
|
|
105
|
-
*
|
|
106
|
-
* ## Use Cases
|
|
107
|
-
*
|
|
108
|
-
* 1. **Schema-based data normalization**: When processing objects against JSON Schema
|
|
109
|
-
* definitions, ensuring property values match their declared types.
|
|
110
|
-
*
|
|
111
|
-
* 2. **Form data processing**: Converting string values from HTML forms (which are always
|
|
112
|
-
* strings) to their expected types (numbers, booleans) based on schema definitions.
|
|
113
|
-
*
|
|
114
|
-
* 3. **API response normalization**: Normalizing API responses where types may be ambiguous
|
|
115
|
-
* or incorrectly serialized (e.g., numbers as strings, booleans as strings).
|
|
116
|
-
*
|
|
117
|
-
* 4. **Configuration parsing**: Parsing configuration values from environment variables or
|
|
118
|
-
* config files where everything is initially a string but needs type coercion.
|
|
119
|
-
*
|
|
120
|
-
* ## Behavior by Type
|
|
121
|
-
*
|
|
122
|
-
* - **number/integer**: Attempts to convert strings and booleans to numbers. Preserves
|
|
123
|
-
* original value if conversion fails or value is already a number.
|
|
124
|
-
*
|
|
125
|
-
* - **boolean**: Converts numbers (0 → false, non-zero → true) and recognized string
|
|
126
|
-
* values ('yes', 'true', '1' → true; 'no', 'false', '0' → false). Preserves original
|
|
127
|
-
* value for unrecognized strings or non-convertible types.
|
|
128
|
-
*
|
|
129
|
-
* - **string/object/array**: Returns the value as-is (no conversion performed).
|
|
130
|
-
*
|
|
131
|
-
* - **null/undefined**: Always preserved regardless of target type.
|
|
132
|
-
*
|
|
133
|
-
* ## Examples
|
|
134
|
-
*
|
|
135
|
-
* ### Number Conversion
|
|
136
|
-
* ```typescript
|
|
137
|
-
* normalizeType('number', '123') // → 123
|
|
138
|
-
* normalizeType('number', '45.67') // → 45.67
|
|
139
|
-
* normalizeType('number', '0') // → 0
|
|
140
|
-
* normalizeType('number', true) // → 1
|
|
141
|
-
* normalizeType('number', 'abc') // → 'abc' (conversion failed, original preserved)
|
|
142
|
-
* ```
|
|
143
|
-
*
|
|
144
|
-
* ### Boolean Conversion
|
|
145
|
-
* ```typescript
|
|
146
|
-
* normalizeType('boolean', 0) // → false
|
|
147
|
-
* normalizeType('boolean', 1) // → true
|
|
148
|
-
* normalizeType('boolean', 'yes') // → true
|
|
149
|
-
* normalizeType('boolean', 'true') // → true
|
|
150
|
-
* normalizeType('boolean', '1') // → true
|
|
151
|
-
* normalizeType('boolean', 'no') // → false
|
|
152
|
-
* normalizeType('boolean', 'false') // → false
|
|
153
|
-
* normalizeType('boolean', 'maybe') // → 'maybe' (unrecognized, original preserved)
|
|
154
|
-
* ```
|
|
155
|
-
*
|
|
156
|
-
* ### Type Preservation
|
|
157
|
-
* ```typescript
|
|
158
|
-
* normalizeType('string', 'hello') // → 'hello'
|
|
159
|
-
* normalizeType('string', 123) // → 123 (no conversion for string type)
|
|
160
|
-
* normalizeType('object', { a: 1 }) // → { a: 1 }
|
|
161
|
-
* normalizeType('array', [1, 2, 3]) // → [1, 2, 3]
|
|
162
|
-
* normalizeType('number', null) // → null (null always preserved)
|
|
163
|
-
* ```
|
|
164
|
-
*
|
|
165
|
-
* @param type - The target JSON Schema type ('number', 'integer', 'boolean', 'string', 'object', 'array')
|
|
166
|
-
* @param value - The value to normalize (can be any type)
|
|
167
|
-
* @returns The normalized value, or the original value if normalization is not applicable
|
|
168
|
-
*/
|
|
40
|
+
/** Normalizes a value to match a specified JSON Schema type. */
|
|
169
41
|
const normalizeType = (type: ValueType, value: unknown): string | number | boolean | unknown => {
|
|
170
42
|
// Preserve null and undefined values regardless of target type
|
|
171
43
|
if (isNullOrUndefined(value)) {
|
|
@@ -1,7 +1,5 @@
|
|
|
1
1
|
import { get, set } from 'lodash';
|
|
2
|
-
import
|
|
3
|
-
|
|
4
|
-
import type { TargetObject } from './JsonSchema';
|
|
2
|
+
import ZSchema, { type SchemaErrorDetail } from 'z-schema';
|
|
5
3
|
|
|
6
4
|
/**
|
|
7
5
|
* Format error codes that indicate validation failures due to format mismatches.
|
|
@@ -13,145 +11,10 @@ const FORMAT_ERROR_CODES = [
|
|
|
13
11
|
'INVALID_FORMAT'
|
|
14
12
|
] as const;
|
|
15
13
|
|
|
16
|
-
/**
|
|
17
|
-
* Values that are considered "empty" and can be safely converted to null.
|
|
18
|
-
*/
|
|
14
|
+
/** Values that are considered "empty" and can be safely converted to null. */
|
|
19
15
|
const EMPTY_VALUES = [''] as const;
|
|
20
16
|
|
|
21
|
-
/**
|
|
22
|
-
* Converts empty string values to null for specific format validation errors.
|
|
23
|
-
*
|
|
24
|
-
* **Intent:**
|
|
25
|
-
* This function provides a post-validation normalization strategy that attempts to
|
|
26
|
-
* resolve format validation errors by converting empty strings to null. This is
|
|
27
|
-
* particularly useful when dealing with optional fields where an empty string
|
|
28
|
-
* represents "no value provided" rather than an invalid format. By converting
|
|
29
|
-
* empty strings to null, the validation may pass if the schema allows null values
|
|
30
|
-
* for optional fields.
|
|
31
|
-
*
|
|
32
|
-
* **Use Cases:**
|
|
33
|
-
* - **Optional field normalization**: When optional string fields receive empty
|
|
34
|
-
* strings from user input or API responses, converting them to null allows
|
|
35
|
-
* validation to succeed if the schema permits null values for optional fields.
|
|
36
|
-
* This is especially common with form inputs that submit empty strings instead
|
|
37
|
-
* of omitting fields entirely.
|
|
38
|
-
* - **Format error recovery**: After schema validation fails with format errors
|
|
39
|
-
* (pattern mismatch, enum mismatch, invalid format), this function attempts to
|
|
40
|
-
* resolve errors by nullifying empty strings. This enables graceful handling
|
|
41
|
-
* of optional fields that failed format validation due to empty values.
|
|
42
|
-
* - **API integration**: When integrating with external APIs or services that
|
|
43
|
-
* send empty strings for optional fields, this function normalizes the data
|
|
44
|
-
* to use null instead, which is often more semantically correct for optional
|
|
45
|
-
* fields in JSON schemas.
|
|
46
|
-
* - **Data transformation pipeline**: As part of a validation and normalization
|
|
47
|
-
* pipeline, this function can be used to clean and normalize data before
|
|
48
|
-
* further processing or storage, ensuring consistent representation of
|
|
49
|
-
* "missing" values.
|
|
50
|
-
* - **User input handling**: When processing user-submitted forms or data where
|
|
51
|
-
* empty string inputs should be treated as "not provided" rather than invalid,
|
|
52
|
-
* this function converts them to null for proper schema validation.
|
|
53
|
-
*
|
|
54
|
-
* **Behavior:**
|
|
55
|
-
* - Returns a deep clone of the input object (does not mutate the original)
|
|
56
|
-
* - Only processes format-related errors (PATTERN, ENUM_MISMATCH, INVALID_FORMAT)
|
|
57
|
-
* - Skips required attributes (marked with `x-required: true`)
|
|
58
|
-
* - Only converts empty strings (`''`) to null, preserving other values
|
|
59
|
-
* - Supports nested paths and array indices
|
|
60
|
-
* - Returns both the modified object and remaining validation errors that
|
|
61
|
-
* couldn't be resolved
|
|
62
|
-
*
|
|
63
|
-
* **Examples:**
|
|
64
|
-
*
|
|
65
|
-
* ```typescript
|
|
66
|
-
* // Example 1: Basic usage with pattern error
|
|
67
|
-
* const object = { email: '' };
|
|
68
|
-
* const error = {
|
|
69
|
-
* code: 'PATTERN',
|
|
70
|
-
* path: '#/email',
|
|
71
|
-
* // ... other error properties
|
|
72
|
-
* };
|
|
73
|
-
* const [result, remainingErrors] = nullifyEmptyValues(object, [error]);
|
|
74
|
-
* // result: { email: null }
|
|
75
|
-
* // remainingErrors: []
|
|
76
|
-
* ```
|
|
77
|
-
*
|
|
78
|
-
* ```typescript
|
|
79
|
-
* // Example 2: Required fields are not nullified
|
|
80
|
-
* const object = { requiredField: '', optionalField: '' };
|
|
81
|
-
* const requiredError = {
|
|
82
|
-
* code: 'PATTERN',
|
|
83
|
-
* path: '#/requiredField',
|
|
84
|
-
* // schema has x-required: true
|
|
85
|
-
* };
|
|
86
|
-
* const optionalError = {
|
|
87
|
-
* code: 'PATTERN',
|
|
88
|
-
* path: '#/optionalField',
|
|
89
|
-
* // schema has no x-required or x-required: false
|
|
90
|
-
* };
|
|
91
|
-
* const [result, remainingErrors] = nullifyEmptyValues(
|
|
92
|
-
* object,
|
|
93
|
-
* [requiredError, optionalError]
|
|
94
|
-
* );
|
|
95
|
-
* // result: { requiredField: '', optionalField: null }
|
|
96
|
-
* // remainingErrors: [requiredError] // required field error remains
|
|
97
|
-
* ```
|
|
98
|
-
*
|
|
99
|
-
* ```typescript
|
|
100
|
-
* // Example 3: Nested paths and arrays
|
|
101
|
-
* const object = {
|
|
102
|
-
* user: {
|
|
103
|
-
* profile: {
|
|
104
|
-
* bio: '',
|
|
105
|
-
* tags: ['', 'tag1', '']
|
|
106
|
-
* }
|
|
107
|
-
* }
|
|
108
|
-
* };
|
|
109
|
-
* const errors = [
|
|
110
|
-
* { code: 'PATTERN', path: '#/user/profile/bio' },
|
|
111
|
-
* { code: 'INVALID_FORMAT', path: '#/user/profile/tags/0' },
|
|
112
|
-
* { code: 'ENUM_MISMATCH', path: '#/user/profile/tags/2' }
|
|
113
|
-
* ];
|
|
114
|
-
* const [result, remainingErrors] = nullifyEmptyValues(object, errors);
|
|
115
|
-
* // result: {
|
|
116
|
-
* // user: {
|
|
117
|
-
* // profile: {
|
|
118
|
-
* // bio: null,
|
|
119
|
-
* // tags: [null, 'tag1', null]
|
|
120
|
-
* // }
|
|
121
|
-
* // }
|
|
122
|
-
* // }
|
|
123
|
-
* // remainingErrors: []
|
|
124
|
-
* ```
|
|
125
|
-
*
|
|
126
|
-
* ```typescript
|
|
127
|
-
* // Example 4: Non-format errors are not processed
|
|
128
|
-
* const object = { field: '' };
|
|
129
|
-
* const formatError = { code: 'PATTERN', path: '#/field' };
|
|
130
|
-
* const typeError = { code: 'INVALID_TYPE', path: '#/field' };
|
|
131
|
-
* const [result, remainingErrors] = nullifyEmptyValues(
|
|
132
|
-
* object,
|
|
133
|
-
* [formatError, typeError]
|
|
134
|
-
* );
|
|
135
|
-
* // result: { field: null }
|
|
136
|
-
* // remainingErrors: [typeError] // type error remains
|
|
137
|
-
* ```
|
|
138
|
-
*
|
|
139
|
-
* ```typescript
|
|
140
|
-
* // Example 5: Non-empty values are preserved
|
|
141
|
-
* const object = { field: 'invalid-value' };
|
|
142
|
-
* const error = { code: 'PATTERN', path: '#/field' };
|
|
143
|
-
* const [result, remainingErrors] = nullifyEmptyValues(object, [error]);
|
|
144
|
-
* // result: { field: 'invalid-value' } // unchanged
|
|
145
|
-
* // remainingErrors: [error] // error remains
|
|
146
|
-
* ```
|
|
147
|
-
*
|
|
148
|
-
* @param object - The target object to process (will be deep cloned, not mutated)
|
|
149
|
-
* @param validationErrors - Array of schema validation errors from z-schema
|
|
150
|
-
* @returns A tuple containing:
|
|
151
|
-
* - `[0]`: Deep clone of the object with empty strings converted to null where applicable
|
|
152
|
-
* - `[1]`: Array of validation errors that couldn't be resolved (required fields,
|
|
153
|
-
* non-format errors, or errors for non-empty values)
|
|
154
|
-
*/
|
|
17
|
+
/** Converts empty string values to null for specific format validation errors. */
|
|
155
18
|
const nullifyEmptyValues = (
|
|
156
19
|
object: TargetObject,
|
|
157
20
|
validationErrors: SchemaErrorDetail[]
|
|
@@ -162,7 +25,7 @@ const nullifyEmptyValues = (
|
|
|
162
25
|
|
|
163
26
|
for (const error of validationErrors) {
|
|
164
27
|
const { code, path: pathString } = error;
|
|
165
|
-
const schema = get(error, schemaSymbol) as Record<string, unknown> | undefined;
|
|
28
|
+
const schema = get(error, ZSchema.schemaSymbol) as Record<string, unknown> | undefined;
|
|
166
29
|
const isAttributeRequired = schema?.['x-required'] === true;
|
|
167
30
|
const isFormatError = FORMAT_ERROR_CODES.includes(code as typeof FORMAT_ERROR_CODES[number]);
|
|
168
31
|
|
|
@@ -182,11 +45,13 @@ const nullifyEmptyValues = (
|
|
|
182
45
|
}
|
|
183
46
|
|
|
184
47
|
// Parse the JSON path (e.g., '#/user/profile/field' -> ['user', 'profile', 'field'])
|
|
185
|
-
const path = pathString
|
|
48
|
+
const path = typeof pathString === 'string'
|
|
49
|
+
? pathString.replace(/^#\//, '').split('/').filter(Boolean)
|
|
50
|
+
: pathString;
|
|
186
51
|
|
|
187
|
-
// Get the actual value from the error's JSON context
|
|
188
|
-
const json = get(error, jsonSymbol) as TargetObject;
|
|
189
|
-
const value = get(json, path);
|
|
52
|
+
// Get the actual value from the error's JSON context, or fall back to the object
|
|
53
|
+
const json = get(error, ZSchema.jsonSymbol) as TargetObject | undefined;
|
|
54
|
+
const value = get(json ?? result, path);
|
|
190
55
|
|
|
191
56
|
const isEmptyValue = EMPTY_VALUES.includes(value as typeof EMPTY_VALUES[number]);
|
|
192
57
|
const shouldSkipNonEmptyValue = !isEmptyValue;
|
|
@@ -1,110 +1,5 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
EnumSchema,
|
|
3
|
-
PropertySchema,
|
|
4
|
-
ArrayPropertySchema,
|
|
5
|
-
ObjectPropertySchema,
|
|
6
|
-
} from './JsonSchema';
|
|
7
1
|
|
|
8
|
-
/**
|
|
9
|
-
* Recursively removes `required` and `default` attributes from a JSON schema.
|
|
10
|
-
*
|
|
11
|
-
* **Intent:**
|
|
12
|
-
* This function is designed to transform JSON schemas by stripping out validation
|
|
13
|
-
* constraints (`required`) and default values (`default`) from all properties,
|
|
14
|
-
* including nested objects and array items. This is useful for creating "pure"
|
|
15
|
-
* or "update-friendly" versions of schemas where all fields become optional and
|
|
16
|
-
* no defaults are applied.
|
|
17
|
-
*
|
|
18
|
-
* **Use Cases:**
|
|
19
|
-
* 1. **Update Schemas**: Create schemas for partial updates where all fields are optional
|
|
20
|
-
* 2. **Schema Transformation**: Prepare schemas for contexts where required/default
|
|
21
|
-
* constraints are not needed (e.g., credential generation, API transformations)
|
|
22
|
-
* 3. **Schema Normalization**: Remove validation metadata before further processing
|
|
23
|
-
*
|
|
24
|
-
* **Behavior:**
|
|
25
|
-
* - Mutates the input schema in-place by deleting `required` and `default` properties
|
|
26
|
-
* - Recursively processes nested object properties
|
|
27
|
-
* - Recursively processes array items (including nested objects within arrays)
|
|
28
|
-
* - Preserves all other schema properties (type, description, pattern, etc.)
|
|
29
|
-
* - Returns an object containing only the `properties` field
|
|
30
|
-
*
|
|
31
|
-
* **Examples:**
|
|
32
|
-
*
|
|
33
|
-
* ```typescript
|
|
34
|
-
* // Example 1: Simple object schema
|
|
35
|
-
* const schema = {
|
|
36
|
-
* type: 'object',
|
|
37
|
-
* properties: {
|
|
38
|
-
* name: { type: 'string', required: true, default: 'John' },
|
|
39
|
-
* age: { type: 'number', required: false, default: 0 }
|
|
40
|
-
* }
|
|
41
|
-
* };
|
|
42
|
-
*
|
|
43
|
-
* const result = removeRequiredAndDefault(schema);
|
|
44
|
-
* // result.properties.name: { type: 'string' } (required and default removed)
|
|
45
|
-
* // result.properties.age: { type: 'number' } (required and default removed)
|
|
46
|
-
* ```
|
|
47
|
-
*
|
|
48
|
-
* ```typescript
|
|
49
|
-
* // Example 2: Nested objects
|
|
50
|
-
* const schema = {
|
|
51
|
-
* type: 'object',
|
|
52
|
-
* properties: {
|
|
53
|
-
* user: {
|
|
54
|
-
* type: 'object',
|
|
55
|
-
* required: true,
|
|
56
|
-
* default: {},
|
|
57
|
-
* properties: {
|
|
58
|
-
* name: { type: 'string', required: true, default: 'John' },
|
|
59
|
-
* address: {
|
|
60
|
-
* type: 'object',
|
|
61
|
-
* properties: {
|
|
62
|
-
* street: { type: 'string', required: true, default: '' }
|
|
63
|
-
* }
|
|
64
|
-
* }
|
|
65
|
-
* }
|
|
66
|
-
* }
|
|
67
|
-
* }
|
|
68
|
-
* };
|
|
69
|
-
*
|
|
70
|
-
* const result = removeRequiredAndDefault(schema);
|
|
71
|
-
* // All required and default attributes are removed at all nesting levels
|
|
72
|
-
* ```
|
|
73
|
-
*
|
|
74
|
-
* ```typescript
|
|
75
|
-
* // Example 3: Arrays with object items
|
|
76
|
-
* const schema = {
|
|
77
|
-
* type: 'object',
|
|
78
|
-
* properties: {
|
|
79
|
-
* users: {
|
|
80
|
-
* type: 'array',
|
|
81
|
-
* required: true,
|
|
82
|
-
* default: [],
|
|
83
|
-
* items: {
|
|
84
|
-
* type: 'object',
|
|
85
|
-
* properties: {
|
|
86
|
-
* name: { type: 'string', required: true, default: 'John' }
|
|
87
|
-
* }
|
|
88
|
-
* }
|
|
89
|
-
* }
|
|
90
|
-
* }
|
|
91
|
-
* };
|
|
92
|
-
*
|
|
93
|
-
* const result = removeRequiredAndDefault(schema);
|
|
94
|
-
* // Removes required/default from array property and nested object properties
|
|
95
|
-
* ```
|
|
96
|
-
*
|
|
97
|
-
* **Limitations:**
|
|
98
|
-
* - Only processes schemas with a `properties` field (ObjectPropertySchema)
|
|
99
|
-
* - EnumSchema is accepted as a parameter but not processed (will return empty properties)
|
|
100
|
-
* - The function mutates the input schema object
|
|
101
|
-
* - Array items that are primitives (string, number, etc.) are processed but
|
|
102
|
-
* their return values are discarded (this is intentional)
|
|
103
|
-
*
|
|
104
|
-
* @param jsonSchema - The JSON schema to process (must have a `properties` field)
|
|
105
|
-
* @returns An object containing only the `properties` field with all `required`
|
|
106
|
-
* and `default` attributes removed recursively
|
|
107
|
-
*/
|
|
2
|
+
/** Recursively removes `required` and `default` attributes from a JSON schema. */
|
|
108
3
|
const removeRequiredAndDefault = (jsonSchema: PropertySchema | EnumSchema) => {
|
|
109
4
|
const { properties } = (jsonSchema as ObjectPropertySchema);
|
|
110
5
|
|
|
@@ -1,41 +1,6 @@
|
|
|
1
1
|
import { isURL } from 'validator';
|
|
2
2
|
|
|
3
|
-
/**
|
|
4
|
-
* Validates that a value is a URL or a DID (Decentralized Identifier).
|
|
5
|
-
* Throws if the value is missing, null, undefined, or not a valid URL/DID.
|
|
6
|
-
*
|
|
7
|
-
* **Intent**
|
|
8
|
-
* Enforce that identifier-style parameters (schema IDs, credential IDs, subject
|
|
9
|
-
* references, etc.) are either resolvable URLs or W3C DIDs before they are used
|
|
10
|
-
* in Linked Data or verification flows. This prevents malformed or arbitrary
|
|
11
|
-
* strings from propagating into storage, APIs, or cryptographic operations.
|
|
12
|
-
*
|
|
13
|
-
* **Use cases**
|
|
14
|
-
* - Validating `schemaId`, `credentialId`, or similar parameters in credential
|
|
15
|
-
* and schema factories before creating or resolving documents.
|
|
16
|
-
* - Input validation for APIs that accept URI identifiers (e.g. fetch by ID).
|
|
17
|
-
* - Guarding helpers that resolve or dereference IDs (e.g. document loaders,
|
|
18
|
-
* schema registries) from invalid input.
|
|
19
|
-
*
|
|
20
|
-
* **Examples**
|
|
21
|
-
*
|
|
22
|
-
* Valid — URLs:
|
|
23
|
-
* validateId('schemaId', 'https://example.com/schemas/v1');
|
|
24
|
-
* validateId('id', 'http://example.com:8080/path?q=1');
|
|
25
|
-
*
|
|
26
|
-
* Valid — DIDs (case-insensitive `did:` prefix):
|
|
27
|
-
* validateId('subject', 'did:example:123456789');
|
|
28
|
-
* validateId('subject', 'did:key:z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK');
|
|
29
|
-
*
|
|
30
|
-
* Throws — missing or invalid:
|
|
31
|
-
* validateId('id', ''); // Error: Parameter "id" is required
|
|
32
|
-
* validateId('id', null); // Error: Parameter "id" is required
|
|
33
|
-
* validateId('id', 'not-a-uri'); // Error: Parameter "id" must be a URL, received: "not-a-uri"
|
|
34
|
-
*
|
|
35
|
-
* @param name - Parameter name used in error messages (e.g. `"schemaId"`, `"credentialId"`).
|
|
36
|
-
* @param value - The value to validate (`string`, `null`, or `undefined`).
|
|
37
|
-
* @throws {Error} When `value` is falsy, or when it is not a URL and does not start with `did:`.
|
|
38
|
-
*/
|
|
3
|
+
/** Validates that a value is a URL or a DID (Decentralized Identifier). */
|
|
39
4
|
const validateId = (name: string, value: string | null | undefined) => {
|
|
40
5
|
if (!value) {
|
|
41
6
|
throw new Error(`Parameter "${name}" is required`);
|