@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.
Files changed (118) hide show
  1. package/dist/CredentialFactory.d.ts +5 -318
  2. package/dist/CredentialFactory.d.ts.map +1 -1
  3. package/dist/CredentialFactory.js +5 -317
  4. package/dist/CredentialFactory.js.map +1 -1
  5. package/dist/Schema.d.ts +15 -420
  6. package/dist/Schema.d.ts.map +1 -1
  7. package/dist/Schema.js +13 -384
  8. package/dist/Schema.js.map +1 -1
  9. package/dist/ValidationError.d.ts +3 -49
  10. package/dist/ValidationError.d.ts.map +1 -1
  11. package/dist/ValidationError.js +3 -48
  12. package/dist/ValidationError.js.map +1 -1
  13. package/dist/Validator.d.ts +6 -470
  14. package/dist/Validator.d.ts.map +1 -1
  15. package/dist/Validator.js +50 -478
  16. package/dist/Validator.js.map +1 -1
  17. package/dist/helpers/cleanupAttributes.d.ts +3 -32
  18. package/dist/helpers/cleanupAttributes.d.ts.map +1 -1
  19. package/dist/helpers/cleanupAttributes.js +1 -30
  20. package/dist/helpers/cleanupAttributes.js.map +1 -1
  21. package/dist/helpers/cleanupNulls.d.ts +1 -25
  22. package/dist/helpers/cleanupNulls.d.ts.map +1 -1
  23. package/dist/helpers/cleanupNulls.js +2 -61
  24. package/dist/helpers/cleanupNulls.js.map +1 -1
  25. package/dist/helpers/createSchemasMap.d.ts +2 -93
  26. package/dist/helpers/createSchemasMap.d.ts.map +1 -1
  27. package/dist/helpers/createSchemasMap.js +4 -162
  28. package/dist/helpers/createSchemasMap.js.map +1 -1
  29. package/dist/helpers/getReferenceIds.d.ts +1 -165
  30. package/dist/helpers/getReferenceIds.d.ts.map +1 -1
  31. package/dist/helpers/getReferenceIds.js +2 -166
  32. package/dist/helpers/getReferenceIds.js.map +1 -1
  33. package/dist/helpers/got.d.ts +2 -58
  34. package/dist/helpers/got.d.ts.map +1 -1
  35. package/dist/helpers/got.js +1 -57
  36. package/dist/helpers/got.js.map +1 -1
  37. package/dist/helpers/mapObjectProperties.d.ts +2 -144
  38. package/dist/helpers/mapObjectProperties.d.ts.map +1 -1
  39. package/dist/helpers/mapObjectProperties.js +1 -142
  40. package/dist/helpers/mapObjectProperties.js.map +1 -1
  41. package/dist/helpers/normalizeAttributes.d.ts +3 -211
  42. package/dist/helpers/normalizeAttributes.d.ts.map +1 -1
  43. package/dist/helpers/normalizeAttributes.js +1 -209
  44. package/dist/helpers/normalizeAttributes.js.map +1 -1
  45. package/dist/helpers/normalizeProperties.d.ts +1 -165
  46. package/dist/helpers/normalizeProperties.d.ts.map +1 -1
  47. package/dist/helpers/normalizeProperties.js +1 -164
  48. package/dist/helpers/normalizeProperties.js.map +1 -1
  49. package/dist/helpers/normalizeRequired.d.ts +1 -153
  50. package/dist/helpers/normalizeRequired.d.ts.map +1 -1
  51. package/dist/helpers/normalizeRequired.js +0 -151
  52. package/dist/helpers/normalizeRequired.js.map +1 -1
  53. package/dist/helpers/normalizeType.d.ts +1 -77
  54. package/dist/helpers/normalizeType.d.ts.map +1 -1
  55. package/dist/helpers/normalizeType.js +11 -139
  56. package/dist/helpers/normalizeType.js.map +1 -1
  57. package/dist/helpers/nullifyEmptyValues.d.ts +1 -135
  58. package/dist/helpers/nullifyEmptyValues.d.ts.map +1 -1
  59. package/dist/helpers/nullifyEmptyValues.js +13 -143
  60. package/dist/helpers/nullifyEmptyValues.js.map +1 -1
  61. package/dist/helpers/removeRequiredAndDefault.d.ts +2 -102
  62. package/dist/helpers/removeRequiredAndDefault.d.ts.map +1 -1
  63. package/dist/helpers/removeRequiredAndDefault.js +1 -100
  64. package/dist/helpers/removeRequiredAndDefault.js.map +1 -1
  65. package/dist/helpers/validateId.d.ts +1 -36
  66. package/dist/helpers/validateId.d.ts.map +1 -1
  67. package/dist/helpers/validateId.js +1 -36
  68. package/dist/helpers/validateId.js.map +1 -1
  69. package/dist/ld/documentLoader.d.ts +1 -1
  70. package/dist/ld/documentLoader.d.ts.map +1 -1
  71. package/dist/ld/documentLoader.js +1 -1
  72. package/dist/ld/documentLoader.js.map +1 -1
  73. package/dist/ld/getLinkedDataAttributeType.d.ts +1 -1
  74. package/dist/ld/getLinkedDataAttributeType.d.ts.map +1 -1
  75. package/dist/ld/getLinkedDataAttributeType.js +1 -1
  76. package/dist/ld/getLinkedDataAttributeType.js.map +1 -1
  77. package/dist/ld/getLinkedDataContext.d.ts +1 -1
  78. package/dist/ld/getLinkedDataContext.d.ts.map +1 -1
  79. package/dist/ld/getLinkedDataContext.js +1 -1
  80. package/dist/ld/getLinkedDataContext.js.map +1 -1
  81. package/package.json +2 -2
  82. package/src/CredentialFactory.ts +5 -318
  83. package/src/Schema.ts +17 -427
  84. package/src/ValidationError.ts +5 -52
  85. package/src/Validator.ts +19 -483
  86. package/src/__tests__/CredentialFactory.test.ts +1 -1
  87. package/src/__tests__/Schema.test.ts +3 -8
  88. package/src/__tests__/ValidationError.test.ts +4 -2
  89. package/src/__tests__/Validator.test.ts +21 -4
  90. package/src/helpers/__tests__/cleanupAttributes.test.ts +3 -1
  91. package/src/helpers/__tests__/createSchemasMap.test.ts +1 -1
  92. package/src/helpers/__tests__/mapObjectProperties.test.ts +2 -1
  93. package/src/helpers/__tests__/normalizeAttributes.test.ts +4 -2
  94. package/src/helpers/__tests__/normalizeProperties.test.ts +3 -1
  95. package/src/helpers/__tests__/normalizeRequired.test.ts +4 -9
  96. package/src/helpers/__tests__/nullifyEmptyValues.test.ts +43 -12
  97. package/src/helpers/__tests__/removeRequiredAndDefault.test.ts +3 -10
  98. package/src/helpers/cleanupAttributes.ts +6 -44
  99. package/src/helpers/cleanupNulls.ts +2 -63
  100. package/src/helpers/createSchemasMap.ts +4 -163
  101. package/src/helpers/getReferenceIds.ts +2 -173
  102. package/src/helpers/got.ts +3 -59
  103. package/src/helpers/mapObjectProperties.ts +4 -156
  104. package/src/helpers/normalizeAttributes.ts +7 -211
  105. package/src/helpers/normalizeProperties.ts +1 -172
  106. package/src/helpers/normalizeRequired.ts +1 -161
  107. package/src/helpers/normalizeType.ts +11 -139
  108. package/src/helpers/nullifyEmptyValues.ts +10 -145
  109. package/src/helpers/removeRequiredAndDefault.ts +1 -106
  110. package/src/helpers/validateId.ts +1 -36
  111. package/src/ld/documentLoader.ts +1 -1
  112. package/src/ld/getLinkedDataAttributeType.ts +1 -1
  113. package/src/ld/getLinkedDataContext.ts +1 -1
  114. package/src/{helpers/JsonSchema.ts → types.d.ts} +12 -16
  115. package/dist/helpers/JsonSchema.d.ts +0 -99
  116. package/dist/helpers/JsonSchema.d.ts.map +0 -1
  117. package/dist/helpers/JsonSchema.js +0 -3
  118. package/dist/helpers/JsonSchema.js.map +0 -1
package/src/Schema.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { JsonSchema } from 'z-schema';
1
2
  import { pick, cloneDeep } from 'lodash';
2
3
 
3
4
  import validateId from './helpers/validateId';
@@ -6,50 +7,10 @@ import normalizeProperties from './helpers/normalizeProperties';
6
7
  import getLinkedDataContext from './ld/getLinkedDataContext';
7
8
  import removeRequiredAndDefault from './helpers/removeRequiredAndDefault';
8
9
  import type { LinkedDataContext } from './ld/getLinkedDataContext';
9
- import type {
10
- JsonSchema,
11
- EnumSchema,
12
- PropertiesSchema,
13
- ObjectSchema
14
- } from './helpers/JsonSchema';
15
10
 
16
11
  const UNDEFINED_SCHEMA_ID = 'UNDEFINED_SCHEMA_ID';
17
12
 
18
- /**
19
- * JSON-LD linked data type structure for semantic web integration.
20
- *
21
- * **Intent:** Provide a standardized format for representing schemas in the
22
- * semantic web, enabling integration with Linked Data and Verifiable Credentials.
23
- *
24
- * **Use Cases:**
25
- * - Generate Verifiable Credentials with proper semantic context
26
- * - Create JSON-LD documents compatible with schema.org and other vocabularies
27
- * - Enable semantic interoperability between different systems
28
- * - Support decentralized identity and credential systems
29
- *
30
- * **Structure:**
31
- * - `@id`: The unique identifier (URI) for the schema type
32
- * - `@context`: The JSON-LD context mapping properties to semantic types
33
- *
34
- * **Example:**
35
- * ```typescript
36
- * const schema = new Schema(
37
- * { name: { type: 'string' }, email: { type: 'string', format: 'email' } },
38
- * 'Person',
39
- * 'https://schema.org/'
40
- * );
41
- *
42
- * const linkedData = schema.linkedDataType;
43
- * // {
44
- * // '@id': 'https://schema.org/Person',
45
- * // '@context': {
46
- * // '@vocab': 'https://schema.org/',
47
- * // 'name': 'https://schema.org/name',
48
- * // 'email': 'https://schema.org/email'
49
- * // }
50
- * // }
51
- * ```
52
- */
13
+ /** JSON-LD linked data type structure for semantic web integration. */
53
14
  export type LinkedDataType = {
54
15
  '@id': string;
55
16
  '@context': LinkedDataContext;
@@ -59,94 +20,14 @@ export type SchemaSource = EnumSchema | PropertiesSchema;
59
20
 
60
21
  export type PropertiesSchemaSource = PropertiesSchema;
61
22
 
62
- /**
63
- * Schema class for defining and manipulating JSON schemas for object validation.
64
- *
65
- * This class provides a flexible API for creating, transforming, and composing JSON schemas.
66
- * It supports both property-based schemas (for objects) and enum schemas (for value sets).
67
- *
68
- * **Use Cases:**
69
- * - Define validation schemas for API request/response objects
70
- * - Create reusable schema components that can be extended or composed
71
- * - Generate JSON-LD linked data types for semantic web applications
72
- * - Transform schemas for different use cases (e.g., create update schemas from create schemas)
73
- *
74
- * **Example - Basic Usage:**
75
- * ```typescript
76
- * const userSchema = new Schema({
77
- * firstName: { type: 'string', required: true },
78
- * lastName: { type: 'string', required: true },
79
- * email: { type: 'string', format: 'email', required: true }
80
- * }, 'User');
81
- * ```
82
- *
83
- * **Example - Schema Composition:**
84
- * ```typescript
85
- * const baseSchema = new Schema({ name: { required: true } }, 'Base');
86
- * const extendedSchema = baseSchema.extend({ status: { enum: ['Active', 'Inactive'] } }, 'Extended');
87
- * ```
88
- *
89
- * **Example - Linked Data Types:**
90
- * ```typescript
91
- * const schema = new Schema(
92
- * { id: { type: 'string' }, name: { type: 'string' } },
93
- * 'Person',
94
- * 'https://schema.org/'
95
- * );
96
- * // schema.linkedDataType will contain JSON-LD context
97
- * ```
98
- */
23
+ /** Schema class for defining and manipulating JSON schemas for object validation. */
99
24
  class Schema {
100
25
  private _id: string;
101
26
  private _url?: string;
102
27
  private _source: PropertiesSchema | EnumSchema;
103
28
  private _linkedDataType?: LinkedDataType;
104
29
 
105
- /**
106
- * Creates a new Schema instance.
107
- *
108
- * **Intent:** Initialize a schema with properties, enum values, or clone from another schema.
109
- * Automatically normalizes properties, infers types, and optionally creates JSON-LD linked data types.
110
- *
111
- * **Use Cases:**
112
- * - Create a new schema from scratch with property definitions
113
- * - Create an enum schema for value validation
114
- * - Clone an existing schema with a new ID
115
- * - Create a schema with JSON-LD context for semantic web applications
116
- *
117
- * @param propertiesOrSchema - Property definitions, enum schema, or existing Schema instance to clone
118
- * @param id - Unique identifier for the schema (defaults to 'UNDEFINED_SCHEMA_ID' if not provided)
119
- * @param url - Optional URL for generating JSON-LD linked data types (only for property schemas, not enums)
120
- *
121
- * **Example - Property Schema:**
122
- * ```typescript
123
- * const schema = new Schema({
124
- * name: { type: 'string', required: true },
125
- * age: { type: 'number', minimum: 0 }
126
- * }, 'Person');
127
- * ```
128
- *
129
- * **Example - Enum Schema:**
130
- * ```typescript
131
- * const sizeSchema = new Schema({ enum: ['S', 'M', 'L'], type: 'string' }, 'Size');
132
- * ```
133
- *
134
- * **Example - Clone Schema:**
135
- * ```typescript
136
- * const original = new Schema({ name: { type: 'string' } }, 'Original');
137
- * const cloned = new Schema(original, 'Cloned');
138
- * ```
139
- *
140
- * **Example - With Linked Data URL:**
141
- * ```typescript
142
- * const schema = new Schema(
143
- * { name: { type: 'string' } },
144
- * 'Person',
145
- * 'https://schema.org/'
146
- * );
147
- * // Automatically creates linkedDataType with @id and @context
148
- * ```
149
- */
30
+ /** Creates a new Schema instance. */
150
31
  constructor(propertiesOrSchema: Schema | SchemaSource, id?: string, url?: string) {
151
32
  this._id = id || UNDEFINED_SCHEMA_ID;
152
33
 
@@ -192,142 +73,33 @@ class Schema {
192
73
  normalizeProperties(this._source);
193
74
  }
194
75
 
195
- /**
196
- * Returns the unique identifier for this schema.
197
- *
198
- * **Intent:** Provide a way to reference and identify schemas in collections or validators.
199
- *
200
- * **Use Cases:**
201
- * - Reference schemas in Validator instances
202
- * - Track schema lineage when cloning/extending
203
- * - Generate schema identifiers for JSON Schema output
204
- *
205
- * @returns The schema ID, or 'UNDEFINED_SCHEMA_ID' if not specified during construction
206
- *
207
- * **Example:**
208
- * ```typescript
209
- * const schema = new Schema({ name: { type: 'string' } }, 'User');
210
- * console.log(schema.id); // 'User'
211
- * ```
212
- */
76
+ /** Returns the unique identifier for this schema. */
213
77
  get id() {
214
78
  return this._id;
215
79
  }
216
80
 
217
- /**
218
- * Returns the URL associated with this schema for JSON-LD linked data generation.
219
- *
220
- * **Intent:** Provide access to the base URL used for generating semantic web identifiers.
221
- *
222
- * **Use Cases:**
223
- * - Check if a schema has linked data support
224
- * - Access the base URL for constructing related URIs
225
- * - Debug linked data type generation
226
- *
227
- * @returns The schema URL if provided during construction, undefined otherwise
228
- *
229
- * **Example:**
230
- * ```typescript
231
- * const schema = new Schema({ name: { type: 'string' } }, 'Person', 'https://schema.org/');
232
- * console.log(schema.url); // 'https://schema.org/'
233
- * ```
234
- */
81
+ /** Returns the URL associated with this schema for JSON-LD linked data generation. */
235
82
  get url() {
236
83
  return this._url;
237
84
  }
238
85
 
239
- /**
240
- * Returns a deep clone of the schema's source properties or enum definition.
241
- *
242
- * **Intent:** Provide immutable access to schema definitions to prevent accidental mutations.
243
- *
244
- * **Use Cases:**
245
- * - Inspect schema structure without modifying the original
246
- * - Clone schemas manually for custom transformations
247
- * - Debug schema definitions
248
- * - Pass schema definitions to other functions safely
249
- *
250
- * @returns A deep copy of the schema source (PropertiesSchema or EnumSchema)
251
- *
252
- * **Example:**
253
- * ```typescript
254
- * const schema = new Schema({ name: { type: 'string', required: true } }, 'User');
255
- * const source = schema.source;
256
- * // source is a clone, modifying it won't affect the original schema
257
- * ```
258
- */
86
+ /** Returns a deep clone of the schema's source properties or enum definition. */
259
87
  get source() {
260
88
  return cloneDeep(this._source);
261
89
  }
262
90
 
263
- /**
264
- * Checks if this schema is an enum schema (defines a set of allowed values).
265
- *
266
- * **Intent:** Enable type-safe branching logic based on schema type.
267
- *
268
- * **Use Cases:**
269
- * - Conditionally apply methods that only work on property schemas
270
- * - Validate schema type before operations
271
- * - Implement different serialization logic for enums vs objects
272
- *
273
- * @returns true if the schema is an enum schema, false if it's a properties schema
274
- *
275
- * **Example:**
276
- * ```typescript
277
- * const enumSchema = new Schema({ enum: ['A', 'B', 'C'] }, 'Letters');
278
- * const propSchema = new Schema({ name: { type: 'string' } }, 'Person');
279
- *
280
- * console.log(enumSchema.isEnum); // true
281
- * console.log(propSchema.isEnum); // false
282
- * ```
283
- */
91
+ /** Checks if this schema is an enum schema (defines a set of allowed values). */
284
92
  get isEnum() {
285
93
  return !!this._source.enum;
286
94
  }
287
95
 
288
- /**
289
- * Returns a normalized JSON Schema representation of this schema.
290
- *
291
- * **Intent:** Convert the internal schema representation to standard JSON Schema format
292
- * with normalized required arrays and proper structure for validation libraries.
293
- *
294
- * **Use Cases:**
295
- * - Export schemas for use with JSON Schema validators (e.g., z-schema)
296
- * - Generate API documentation from schemas
297
- * - Serialize schemas to JSON for storage or transmission
298
- * - Integrate with tools that expect standard JSON Schema format
299
- *
300
- * @returns A JsonSchema object (ObjectSchema for property schemas, EnumSchema for enum schemas)
301
- *
302
- * **Example - Property Schema:**
303
- * ```typescript
304
- * const schema = new Schema({
305
- * name: { type: 'string', required: true },
306
- * age: { type: 'number' }
307
- * }, 'Person');
308
- *
309
- * const jsonSchema = schema.jsonSchema;
310
- * // {
311
- * // id: 'Person',
312
- * // type: 'object',
313
- * // properties: { name: {...}, age: {...} },
314
- * // required: ['name']
315
- * // }
316
- * ```
317
- *
318
- * **Example - Enum Schema:**
319
- * ```typescript
320
- * const enumSchema = new Schema({ enum: ['S', 'M', 'L'], type: 'string' }, 'Size');
321
- * const jsonSchema = enumSchema.jsonSchema;
322
- * // { id: 'Size', enum: ['S', 'M', 'L'], type: 'string' }
323
- * ```
324
- */
96
+ /** Returns a normalized JSON Schema representation of this schema. */
325
97
  get jsonSchema(): JsonSchema {
326
98
  if (this.isEnum) {
327
99
  return {
328
100
  id: this._id,
329
101
  ...this.source
330
- } as EnumSchema;
102
+ } as JsonSchema;
331
103
  }
332
104
 
333
105
  const jsonSchema = {
@@ -338,98 +110,20 @@ class Schema {
338
110
 
339
111
  normalizeRequired(jsonSchema);
340
112
 
341
- return jsonSchema;
113
+ return jsonSchema as JsonSchema;
342
114
  }
343
115
 
344
- /**
345
- * Returns the JSON-LD linked data type if a URL was provided during construction.
346
- *
347
- * **Intent:** Provide semantic web identifiers and context for schemas, enabling
348
- * integration with Linked Data and Verifiable Credentials standards.
349
- *
350
- * **Use Cases:**
351
- * - Generate Verifiable Credentials with proper semantic context
352
- * - Create JSON-LD documents with schema.org or custom vocabularies
353
- * - Enable semantic interoperability between systems
354
- * - Support decentralized identity and credential systems
355
- *
356
- * @returns LinkedDataType object with @id and @context, or undefined if no URL was provided
357
- *
358
- * **Example:**
359
- * ```typescript
360
- * const schema = new Schema(
361
- * { name: { type: 'string' }, email: { type: 'string', format: 'email' } },
362
- * 'Person',
363
- * 'https://schema.org/'
364
- * );
365
- *
366
- * const linkedData = schema.linkedDataType;
367
- * // {
368
- * // '@id': 'https://schema.org/Person',
369
- * // '@context': { ... } // Generated context mapping types to schema.org
370
- * // }
371
- * ```
372
- *
373
- * **Note:** Linked data types are only generated for property schemas, not enum schemas.
374
- */
116
+ /** Returns the JSON-LD linked data type if a URL was provided during construction. */
375
117
  get linkedDataType() {
376
118
  return this._linkedDataType;
377
119
  }
378
120
 
379
- /**
380
- * Creates a complete clone of the schema with a new identifier.
381
- *
382
- * **Intent:** Duplicate a schema while maintaining all properties and structure,
383
- * useful for creating variations or versioning schemas.
384
- *
385
- * **Use Cases:**
386
- * - Create schema versions (e.g., 'UserV1', 'UserV2')
387
- * - Duplicate schemas for different contexts
388
- * - Create base schemas that can be independently extended
389
- * - Maintain schema history or branching
390
- *
391
- * @param id - The new unique identifier for the cloned schema
392
- * @returns A new Schema instance with identical structure but different ID
393
- *
394
- * **Example:**
395
- * ```typescript
396
- * const userSchema = new Schema({ name: { type: 'string' } }, 'User');
397
- * const userV2Schema = userSchema.clone('UserV2');
398
- * // Both schemas have identical properties but different IDs
399
- * ```
400
- */
121
+ /** Creates a complete clone of the schema with a new identifier. */
401
122
  clone(id?: string) {
402
123
  return new Schema(this.source, id);
403
124
  }
404
125
 
405
- /**
406
- * Creates a schema clone without required constraints and default values.
407
- *
408
- * **Intent:** Generate update/patch schemas from create schemas by removing
409
- * validation constraints that make sense for creation but not for updates.
410
- *
411
- * **Use Cases:**
412
- * - Create update schemas where all fields are optional
413
- * - Generate PATCH endpoint schemas from POST endpoint schemas
414
- * - Allow partial updates without requiring all original fields
415
- * - Create flexible input schemas for editing operations
416
- *
417
- * @param id - The new unique identifier for the pure schema
418
- * @returns A new Schema instance with all required flags and defaults removed
419
- * @throws Error if called on an enum schema
420
- *
421
- * **Example:**
422
- * ```typescript
423
- * const createSchema = new Schema({
424
- * name: { type: 'string', required: true },
425
- * email: { type: 'string', required: true, default: 'user@example.com' }
426
- * }, 'CreateUser');
427
- *
428
- * const updateSchema = createSchema.pure('UpdateUser');
429
- * // updateSchema has no required fields and no defaults
430
- * // All fields are optional for updates
431
- * ```
432
- */
126
+ /** Creates a schema clone without required constraints and default values. */
433
127
  pure(id?: string) {
434
128
  if (this.isEnum) {
435
129
  throw new Error('The "pure" method is not supported for enum schemas.');
@@ -443,37 +137,7 @@ class Schema {
443
137
  return new Schema(source, id);
444
138
  }
445
139
 
446
- /**
447
- * Creates a schema clone containing only the specified properties.
448
- *
449
- * **Intent:** Create focused schemas that expose only a subset of properties,
450
- * useful for different API views or security contexts.
451
- *
452
- * **Use Cases:**
453
- * - Create public-facing schemas that hide sensitive fields
454
- * - Generate response schemas with only necessary fields
455
- * - Create view-specific schemas (e.g., 'UserSummary', 'UserDetail')
456
- * - Implement field-level access control in schemas
457
- * - Create lightweight schemas for list views
458
- *
459
- * @param propertyNames - Array of property names to include in the new schema
460
- * @param id - The new unique identifier for the filtered schema
461
- * @returns A new Schema instance containing only the specified properties
462
- * @throws Error if called on an enum schema
463
- *
464
- * **Example:**
465
- * ```typescript
466
- * const fullSchema = new Schema({
467
- * name: { type: 'string' },
468
- * email: { type: 'string' },
469
- * password: { type: 'string' },
470
- * ssn: { type: 'string' }
471
- * }, 'User');
472
- *
473
- * const publicSchema = fullSchema.only(['name', 'email'], 'PublicUser');
474
- * // publicSchema only contains name and email, hiding sensitive fields
475
- * ```
476
- */
140
+ /** Creates a schema clone containing only the specified properties. */
477
141
  only(propertyNames: string[], id?: string) {
478
142
  if (this.isEnum) {
479
143
  throw new Error('The "only" method is not supported for enum schemas.');
@@ -483,39 +147,7 @@ class Schema {
483
147
  return new Schema(source as PropertiesSchema, id);
484
148
  }
485
149
 
486
- /**
487
- * Creates a schema clone extended with additional properties.
488
- *
489
- * **Intent:** Build complex schemas incrementally by composing base schemas
490
- * with additional fields, enabling schema inheritance and composition patterns.
491
- *
492
- * **Use Cases:**
493
- * - Extend base schemas with domain-specific fields
494
- * - Create schema hierarchies (e.g., BaseEntity -> User -> AdminUser)
495
- * - Add computed or derived fields to existing schemas
496
- * - Compose schemas from multiple sources
497
- * - Build versioned schemas that add new fields
498
- *
499
- * @param properties - Additional properties to merge into the schema
500
- * @param id - The new unique identifier for the extended schema
501
- * @returns A new Schema instance with merged properties (new properties override existing ones)
502
- * @throws Error if called on an enum schema
503
- *
504
- * **Example:**
505
- * ```typescript
506
- * const baseSchema = new Schema({
507
- * id: { type: 'string', required: true },
508
- * createdAt: { type: 'string', format: 'date-time', required: true }
509
- * }, 'BaseEntity');
510
- *
511
- * const userSchema = baseSchema.extend({
512
- * name: { type: 'string', required: true },
513
- * email: { type: 'string', format: 'email', required: true }
514
- * }, 'User');
515
- *
516
- * // userSchema contains id, createdAt, name, and email
517
- * ```
518
- */
150
+ /** Creates a schema clone extended with additional properties. */
519
151
  extend(properties: PropertiesSchema, id?: string) {
520
152
  if (this.isEnum) {
521
153
  throw new Error('The "extend" method is not supported for enum schemas.');
@@ -524,49 +156,7 @@ class Schema {
524
156
  return new Schema({ ...this.source, ...properties }, id);
525
157
  }
526
158
 
527
- /**
528
- * Creates a new schema that wraps the current schema as a nested property.
529
- *
530
- * **Intent:** Transform a flat schema into a nested structure, useful for
531
- * API response formatting or when data needs to be wrapped in a container object.
532
- *
533
- * **Use Cases:**
534
- * - Wrap schemas for API responses (e.g., { data: { ...schema } })
535
- * - Create nested data structures from flat schemas
536
- * - Format schemas for specific API conventions
537
- * - Generate wrapper schemas for pagination or metadata containers
538
- * - Transform schemas for different API versions or formats
539
- *
540
- * @param propertyName - The name of the property that will contain the wrapped schema
541
- * @param attributes - Optional attributes for the wrapper property (default: { required: true })
542
- * @param id - The new unique identifier for the wrapped schema
543
- * @returns A new Schema instance where the original schema is nested under the specified property
544
- * @throws Error if called on an enum schema
545
- *
546
- * **Example:**
547
- * ```typescript
548
- * const userSchema = new Schema({
549
- * name: { type: 'string', required: true },
550
- * email: { type: 'string', required: true }
551
- * }, 'User');
552
- *
553
- * const wrappedSchema = userSchema.wrap('data', { required: true }, 'UserResponse');
554
- * // Resulting schema structure:
555
- * // {
556
- * // data: {
557
- * // type: 'object',
558
- * // properties: { name: {...}, email: {...} },
559
- * // required: true
560
- * // }
561
- * // }
562
- * ```
563
- *
564
- * **Example - With Default Value:**
565
- * ```typescript
566
- * const wrappedSchema = userSchema.wrap('data', { default: '{}' }, 'OptionalUserResponse');
567
- * // The 'data' property has a default value and is not required
568
- * ```
569
- */
159
+ /** Creates a new schema that wraps the current schema as a nested property. */
570
160
  wrap(propertyName: string, attributes: { default?: string; required?: boolean; }, id?: string) {
571
161
  if (this.isEnum) {
572
162
  throw new Error('The "wrap" method is not supported for enum schemas.');
@@ -1,7 +1,5 @@
1
1
  import type { SchemaErrorDetail } from 'z-schema';
2
2
 
3
- import { TargetObject } from './helpers/JsonSchema';
4
-
5
3
  export type ValidationErrorOutput = {
6
4
  path: string;
7
5
  code: string;
@@ -9,40 +7,13 @@ export type ValidationErrorOutput = {
9
7
  message: string;
10
8
  }
11
9
 
12
- /**
13
- * Normalized validation error thrown when object validation fails against a schema.
14
- *
15
- * This error is thrown by the Validator when an object does not conform to its schema.
16
- * It extends the standard Error class and provides structured access to validation
17
- * failure details, including the schema ID, the invalid object, and normalized error
18
- * information for each validation failure.
19
- *
20
- * @example
21
- * ```typescript
22
- * try {
23
- * validator.validate(userData, 'UserSchema');
24
- * } catch (error) {
25
- * if (error instanceof ValidationError) {
26
- * const errorDetails = error.toJSON();
27
- * console.error(errorDetails.schemaId); // 'UserSchema'
28
- * console.error(errorDetails.validationErrors); // Array of validation failures
29
- * }
30
- * }
31
- * ```
32
- */
10
+ /** Normalized validation error thrown when object validation fails against a schema. */
33
11
  class ValidationError extends Error {
34
12
  private _object: TargetObject;
35
13
  private _schemaId: string;
36
14
  private _validationErrors: ValidationErrorOutput[];
37
15
 
38
- /**
39
- * Creates a validation error instance.
40
- *
41
- * @param schemaId - The identifier of the schema that failed validation
42
- * @param invalidObject - The object that failed validation (may be partially processed)
43
- * @param validationErrors - Array of validation error details from z-schema, which will be
44
- * normalized to extract only path, code, params, and message
45
- */
16
+ /** Creates a validation error instance. */
46
17
  constructor(schemaId: string, invalidObject: TargetObject, validationErrors: SchemaErrorDetail[]) {
47
18
  super(`"${schemaId}" validation failed`);
48
19
 
@@ -52,32 +23,14 @@ class ValidationError extends Error {
52
23
 
53
24
  this._validationErrors = validationErrors
54
25
  .map(error => ({
55
- path: error.path,
26
+ path: error.path as string,
56
27
  code: error.code,
57
- params: error.params,
28
+ params: error.params as string[],
58
29
  message: error.message,
59
30
  }));
60
31
  }
61
32
 
62
- /**
63
- * Returns a JSON serializable representation of the validation error.
64
- *
65
- * This method is useful for:
66
- * - API error responses (can be directly serialized and sent to clients)
67
- * - Logging validation failures in a structured format
68
- * - Error reporting and debugging
69
- *
70
- * @returns An object containing:
71
- * - `code`: The error class name ('ValidationError')
72
- * - `object`: The invalid object that failed validation
73
- * - `message`: The error message (e.g., '"SchemaId" validation failed')
74
- * - `schemaId`: The identifier of the schema that failed validation
75
- * - `validationErrors`: Array of normalized validation errors, each containing:
76
- * - `path`: JSON path to the invalid field (e.g., '#/user/email')
77
- * - `code`: Error code from z-schema (e.g., 'INVALID_TYPE', 'REQUIRED')
78
- * - `params`: Array of error-specific parameters
79
- * - `message`: Human-readable error message
80
- */
33
+ /** Returns a JSON serializable representation of the validation error. */
81
34
  toJSON() {
82
35
  return {
83
36
  code: this.constructor.name,