@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
@@ -1,334 +1,21 @@
1
- import type { TargetObject } from './helpers/JsonSchema';
2
1
  import Schema, { type LinkedDataType } from './Schema';
3
- /**
4
- * Factory class for creating Verifiable Credentials with embedded JSON-LD linked data context.
5
- *
6
- * **Intent:** Provide a standardized way to generate W3C Verifiable Credentials that are
7
- * compatible with JSON-LD and semantic web standards. The factory automatically validates
8
- * credential subjects against provided schemas, generates appropriate JSON-LD contexts, and
9
- * structures credentials according to the Verifiable Credentials data model.
10
- *
11
- * **Use Cases:**
12
- * - Generate Verifiable Credentials for decentralized identity systems
13
- * - Create credentials with automatic schema validation and type checking
14
- * - Build credentials with embedded semantic context (schema.org, custom vocabularies)
15
- * - Support multi-schema credentials with nested object references
16
- * - Enable credential interoperability through standardized JSON-LD contexts
17
- * - Integrate with credential issuance systems (e.g., DID-based identity providers)
18
- *
19
- * **Key Features:**
20
- * - Automatic validation of credential subjects against schema definitions
21
- * - JSON-LD context generation for semantic web compatibility
22
- * - Support for multiple schemas with cross-references (`$ref`)
23
- * - Type-safe credential generation with TypeScript support
24
- * - Schema.org type mapping for common data formats (date-time, date, etc.)
25
- *
26
- * **Example - Simple Credential:**
27
- * ```typescript
28
- * import { Schema, CredentialFactory } from '@kravc/schema';
29
- *
30
- * // Define credential subject schema
31
- * const accountSchema = new Schema({
32
- * id: {},
33
- * username: { required: true },
34
- * createdAt: { format: 'date-time', required: true },
35
- * dateOfBirth: { format: 'date' }
36
- * }, 'Account');
37
- *
38
- * // Create factory with credential URI and schemas
39
- * const factory = new CredentialFactory(
40
- * 'https://example.com/schema/AccountV1',
41
- * [accountSchema]
42
- * );
43
- *
44
- * // Generate credential
45
- * const credential = factory.createCredential(
46
- * 'https://example.com/credentials/123',
47
- * 'did:holder:123',
48
- * {
49
- * id: 'did:holder:123',
50
- * username: 'alice',
51
- * createdAt: new Date().toISOString()
52
- * }
53
- * );
54
- * ```
55
- *
56
- * **Example - Multi-Schema Credential with References:**
57
- * ```typescript
58
- * import { Schema, CredentialFactory } from '@kravc/schema';
59
- *
60
- * // Define multiple related schemas
61
- * const playerSchema = new Schema({
62
- * id: {},
63
- * hasVideoGameScore: { $ref: 'VideoGameScore', required: true }
64
- * }, 'Player');
65
- *
66
- * const videoGameSchema = new Schema({
67
- * id: {},
68
- * name: { type: 'string', required: true },
69
- * version: { type: 'string', required: true }
70
- * }, 'VideoGame', 'https://schema.org/');
71
- *
72
- * const scoreSchema = new Schema({
73
- * game: { $ref: 'VideoGame', required: true },
74
- * wins: { type: 'integer', required: true },
75
- * bestScore: { type: 'integer', required: true }
76
- * }, 'VideoGameScore');
77
- *
78
- * // Create factory with multiple schemas
79
- * const factory = new CredentialFactory(
80
- * 'https://example.com/schema/GameScoreV1',
81
- * [playerSchema, videoGameSchema, scoreSchema]
82
- * );
83
- *
84
- * // Generate credential with nested data
85
- * const credential = factory.createCredential(
86
- * 'https://example.com/credentials/score-456',
87
- * 'did:player:789',
88
- * {
89
- * id: 'did:player:789',
90
- * hasVideoGameScore: {
91
- * game: { id: 'did:game:001', name: 'MineSweeper', version: '1.0' },
92
- * wins: 10,
93
- * bestScore: 5000
94
- * }
95
- * }
96
- * );
97
- * ```
98
- *
99
- * **Example - Accessing Credential Context:**
100
- * ```typescript
101
- * const factory = new CredentialFactory(uri, schemas);
102
- *
103
- * // Get credential type (extracted from URI)
104
- * const type = factory.credentialType; // e.g., 'AccountV1'
105
- *
106
- * // Get JSON-LD context for embedding
107
- * const context = factory.context;
108
- * // {
109
- * // AccountV1: { '@id': 'https://example.com/schema/AccountV1' },
110
- * // Account: { '@id': '...', '@context': {...} }
111
- * // }
112
- * ```
113
- */
2
+ /** Factory class for creating Verifiable Credentials with embedded JSON-LD linked data context. */
114
3
  declare class CredentialFactory {
115
4
  private _uri;
116
5
  private _types;
117
6
  private _context;
118
7
  private _validator;
119
- /**
120
- * Creates a new CredentialFactory instance.
121
- *
122
- * **Intent:** Initialize a factory with credential schemas and URI, enabling credential
123
- * generation with automatic validation and JSON-LD context generation.
124
- *
125
- * **Use Cases:**
126
- * - Set up credential factories for different credential types
127
- * - Configure factories with single or multiple related schemas
128
- * - Prepare factories for batch credential generation
129
- *
130
- * **Behavior:**
131
- * - Validates that the provided URI is a valid URL
132
- * - Processes schemas: if a schema doesn't have a URL, creates a new Schema instance
133
- * with the factory URI as the base URL
134
- * - Validates all schemas using the Validator
135
- * - Builds JSON-LD context from schema linked data types
136
- *
137
- * @param uri - The base URI for the credential type (e.g., 'https://example.com/schema/AccountV1')
138
- * Must be a valid URL. The last segment will be used as the credential type name.
139
- * @param schemas - Array of Schema instances defining the credential subject structure.
140
- * The first schema is considered the root schema for validation.
141
- * Schemas can reference each other using `$ref`.
142
- *
143
- * @throws Error if the URI is not a valid URL
144
- * @throws Error if schema validation fails (e.g., invalid JSON Schema structure)
145
- *
146
- * **Example:**
147
- * ```typescript
148
- * const accountSchema = new Schema({
149
- * username: { required: true },
150
- * email: { format: 'email', required: true }
151
- * }, 'Account');
152
- *
153
- * const factory = new CredentialFactory(
154
- * 'https://example.com/schema/AccountV1',
155
- * [accountSchema]
156
- * );
157
- * ```
158
- */
8
+ /** Creates a new CredentialFactory instance. */
159
9
  constructor(uri: string, schemas: Schema[]);
160
- /**
161
- * Returns the credential type name extracted from the factory URI.
162
- *
163
- * **Intent:** Provide a convenient way to access the credential type identifier
164
- * without manually parsing the URI.
165
- *
166
- * **Use Cases:**
167
- * - Access credential type for logging or debugging
168
- * - Use type name in credential processing logic
169
- * - Generate type-specific identifiers or filenames
170
- *
171
- * **Behavior:**
172
- * - Extracts the last segment from the URI path
173
- * - Example: 'https://example.com/schema/AccountV1' → 'AccountV1'
174
- *
175
- * @returns The credential type name (last segment of the URI path)
176
- *
177
- * **Example:**
178
- * ```typescript
179
- * const factory = new CredentialFactory(
180
- * 'https://example.com/schema/AccountV1',
181
- * [schema]
182
- * );
183
- *
184
- * console.log(factory.credentialType); // 'AccountV1'
185
- * ```
186
- */
10
+ /** Returns the credential type name extracted from the factory URI. */
187
11
  get credentialType(): string;
188
- /**
189
- * Returns the JSON-LD context object for the credential.
190
- *
191
- * **Intent:** Provide the complete JSON-LD context mapping that should be included
192
- * in the credential's `@context` array for semantic web compatibility.
193
- *
194
- * **Use Cases:**
195
- * - Access context for credential serialization
196
- * - Inspect context mappings for debugging
197
- * - Use context in custom credential processing
198
- * - Embed context in other JSON-LD documents
199
- *
200
- * **Structure:**
201
- * - Contains the credential type mapping (`{ credentialType: { '@id': uri } }`)
202
- * - Includes all schema-linked data types from the factory's schemas
203
- * - Each schema's `linkedDataType` is included if the schema was created with a URL
204
- *
205
- * @returns Object containing credential type and schema type mappings for JSON-LD context
206
- *
207
- * **Example:**
208
- * ```typescript
209
- * const factory = new CredentialFactory(uri, schemas);
210
- * const context = factory.context;
211
- *
212
- * // Result structure:
213
- * // {
214
- * // AccountV1: { '@id': 'https://example.com/schema/AccountV1' },
215
- * // Account: {
216
- * // '@id': 'https://example.com/schema/AccountV1#Account',
217
- * // '@context': { ... }
218
- * // }
219
- * // }
220
- * ```
221
- */
12
+ /** Returns the JSON-LD context object for the credential. */
222
13
  get context(): {
223
14
  [x: string]: LinkedDataType | {
224
15
  '@id': string;
225
16
  };
226
17
  };
227
- /**
228
- * Creates a Verifiable Credential for the specified subject.
229
- *
230
- * **Intent:** Generate a W3C-compliant Verifiable Credential with validated subject data,
231
- * proper JSON-LD context, and standardized structure ready for issuance and verification.
232
- *
233
- * **Use Cases:**
234
- * - Issue credentials for user accounts, achievements, certifications
235
- * - Generate credentials with automatic schema validation
236
- * - Create credentials with embedded semantic context for interoperability
237
- * - Build credentials for decentralized identity systems
238
- * - Generate credentials that can be verified using JSON-LD processors
239
- *
240
- * **Behavior:**
241
- * - Validates that `id` and `holder` are valid URLs/URIs
242
- * - Validates the subject against the root schema (first schema in the factory)
243
- * - Applies schema defaults and normalizes data according to schema rules
244
- * - Generates credential with proper `@context`, `type`, `id`, `holder`, and `credentialSubject`
245
- * - Returns credential ready for signing (issuer, issuanceDate, proof to be added separately)
246
- *
247
- * **Credential Structure:**
248
- * ```typescript
249
- * {
250
- * '@context': [
251
- * 'https://www.w3.org/2018/credentials/v1',
252
- * factory.context // JSON-LD context from factory
253
- * ],
254
- * id: string, // Credential identifier
255
- * type: ['VerifiableCredential', credentialType],
256
- * holder: string, // DID or identifier of credential holder
257
- * credentialSubject: { // Validated and normalized subject data
258
- * id: string,
259
- * type: string, // Root schema ID
260
- * // ... additional subject properties
261
- * }
262
- * }
263
- * ```
264
- *
265
- * @param id - Unique identifier for the credential (must be a valid URL/URI)
266
- * @param holder - DID or identifier of the credential holder (must be a valid URL/URI)
267
- * @param subject - Object containing the credential subject data to be validated against
268
- * the root schema. Properties are validated, defaults are applied,
269
- * and nested objects are validated against referenced schemas.
270
- *
271
- * @returns Verifiable Credential object with validated subject and JSON-LD context
272
- *
273
- * @throws Error if `id` is not a valid URL/URI
274
- * @throws Error if `holder` is not a valid URL/URI
275
- * @throws ValidationError if subject data doesn't match the schema requirements
276
- *
277
- * **Example - Basic Credential:**
278
- * ```typescript
279
- * const factory = new CredentialFactory(uri, [accountSchema]);
280
- *
281
- * const credential = factory.createCredential(
282
- * 'https://example.com/credentials/123',
283
- * 'did:holder:456',
284
- * {
285
- * id: 'did:holder:456',
286
- * username: 'alice',
287
- * createdAt: '2024-01-01T00:00:00Z'
288
- * }
289
- * );
290
- *
291
- * // Result:
292
- * // {
293
- * // '@context': ['https://www.w3.org/2018/credentials/v1', {...}],
294
- * // id: 'https://example.com/credentials/123',
295
- * // type: ['VerifiableCredential', 'AccountV1'],
296
- * // holder: 'did:holder:456',
297
- * // credentialSubject: {
298
- * // id: 'did:holder:456',
299
- * // username: 'alice',
300
- * // createdAt: '2024-01-01T00:00:00Z',
301
- * // type: 'Account'
302
- * // }
303
- * // }
304
- * ```
305
- *
306
- * **Example - Credential with Nested Objects:**
307
- * ```typescript
308
- * const factory = new CredentialFactory(uri, [playerSchema, gameSchema, scoreSchema]);
309
- *
310
- * const credential = factory.createCredential(
311
- * 'https://example.com/credentials/score-789',
312
- * 'did:player:123',
313
- * {
314
- * id: 'did:player:123',
315
- * hasVideoGameScore: {
316
- * game: {
317
- * id: 'did:game:001',
318
- * name: 'MineSweeper',
319
- * version: '1.0'
320
- * },
321
- * wins: 10,
322
- * bestScore: 5000
323
- * }
324
- * }
325
- * );
326
- * ```
327
- *
328
- * **Note:** The returned credential does not include `issuer`, `issuanceDate`, or `proof`
329
- * fields. These should be added by the credential issuance system (e.g., using
330
- * [@kravc/identity](http://github.com/alexkravets/identity) or similar libraries).
331
- */
18
+ /** Creates a Verifiable Credential for the specified subject. */
332
19
  createCredential(id: string, holder: string, subject?: TargetObject): {
333
20
  '@context': (string | {
334
21
  [x: string]: LinkedDataType | {
@@ -1 +1 @@
1
- {"version":3,"file":"CredentialFactory.d.ts","sourceRoot":"","sources":["../src/CredentialFactory.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,MAAM,EAAE,EAAE,KAAK,cAAc,EAAE,MAAM,UAAU,CAAC;AAIvD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8GG;AACH,cAAM,iBAAiB;IACrB,OAAO,CAAC,IAAI,CAAS;IACrB,OAAO,CAAC,MAAM,CAAW;IACzB,OAAO,CAAC,QAAQ,CAAiC;IACjD,OAAO,CAAC,UAAU,CAAY;IAE9B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAuCG;gBACS,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE;IAqB1C;;;;;;;;;;;;;;;;;;;;;;;;;;OA0BG;IACH,IAAI,cAAc,WAIjB;IAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAiCG;IACH,IAAI,OAAO;;;;MAKV;IAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAwGG;IACH,gBAAgB,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,GAAE,YAAiB;;;;;;;;;;;CAuBxE;AAED,eAAe,iBAAiB,CAAC"}
1
+ {"version":3,"file":"CredentialFactory.d.ts","sourceRoot":"","sources":["../src/CredentialFactory.ts"],"names":[],"mappings":"AAIA,OAAO,MAAM,EAAE,EAAE,KAAK,cAAc,EAAE,MAAM,UAAU,CAAC;AAIvD,mGAAmG;AACnG,cAAM,iBAAiB;IACrB,OAAO,CAAC,IAAI,CAAS;IACrB,OAAO,CAAC,MAAM,CAAW;IACzB,OAAO,CAAC,QAAQ,CAAiC;IACjD,OAAO,CAAC,UAAU,CAAY;IAE9B,gDAAgD;gBACpC,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE;IAqB1C,uEAAuE;IACvE,IAAI,cAAc,WAIjB;IAED,6DAA6D;IAC7D,IAAI,OAAO;;;;MAKV;IAED,iEAAiE;IACjE,gBAAgB,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,GAAE,YAAiB;;;;;;;;;;;CAuBxE;AAED,eAAe,iBAAiB,CAAC"}
@@ -8,162 +8,13 @@ const Validator_1 = __importDefault(require("./Validator"));
8
8
  const validateId_1 = __importDefault(require("./helpers/validateId"));
9
9
  const Schema_1 = __importDefault(require("./Schema"));
10
10
  const { CREDENTIALS_CONTEXT_V1_URL } = credentials_context_1.constants;
11
- /**
12
- * Factory class for creating Verifiable Credentials with embedded JSON-LD linked data context.
13
- *
14
- * **Intent:** Provide a standardized way to generate W3C Verifiable Credentials that are
15
- * compatible with JSON-LD and semantic web standards. The factory automatically validates
16
- * credential subjects against provided schemas, generates appropriate JSON-LD contexts, and
17
- * structures credentials according to the Verifiable Credentials data model.
18
- *
19
- * **Use Cases:**
20
- * - Generate Verifiable Credentials for decentralized identity systems
21
- * - Create credentials with automatic schema validation and type checking
22
- * - Build credentials with embedded semantic context (schema.org, custom vocabularies)
23
- * - Support multi-schema credentials with nested object references
24
- * - Enable credential interoperability through standardized JSON-LD contexts
25
- * - Integrate with credential issuance systems (e.g., DID-based identity providers)
26
- *
27
- * **Key Features:**
28
- * - Automatic validation of credential subjects against schema definitions
29
- * - JSON-LD context generation for semantic web compatibility
30
- * - Support for multiple schemas with cross-references (`$ref`)
31
- * - Type-safe credential generation with TypeScript support
32
- * - Schema.org type mapping for common data formats (date-time, date, etc.)
33
- *
34
- * **Example - Simple Credential:**
35
- * ```typescript
36
- * import { Schema, CredentialFactory } from '@kravc/schema';
37
- *
38
- * // Define credential subject schema
39
- * const accountSchema = new Schema({
40
- * id: {},
41
- * username: { required: true },
42
- * createdAt: { format: 'date-time', required: true },
43
- * dateOfBirth: { format: 'date' }
44
- * }, 'Account');
45
- *
46
- * // Create factory with credential URI and schemas
47
- * const factory = new CredentialFactory(
48
- * 'https://example.com/schema/AccountV1',
49
- * [accountSchema]
50
- * );
51
- *
52
- * // Generate credential
53
- * const credential = factory.createCredential(
54
- * 'https://example.com/credentials/123',
55
- * 'did:holder:123',
56
- * {
57
- * id: 'did:holder:123',
58
- * username: 'alice',
59
- * createdAt: new Date().toISOString()
60
- * }
61
- * );
62
- * ```
63
- *
64
- * **Example - Multi-Schema Credential with References:**
65
- * ```typescript
66
- * import { Schema, CredentialFactory } from '@kravc/schema';
67
- *
68
- * // Define multiple related schemas
69
- * const playerSchema = new Schema({
70
- * id: {},
71
- * hasVideoGameScore: { $ref: 'VideoGameScore', required: true }
72
- * }, 'Player');
73
- *
74
- * const videoGameSchema = new Schema({
75
- * id: {},
76
- * name: { type: 'string', required: true },
77
- * version: { type: 'string', required: true }
78
- * }, 'VideoGame', 'https://schema.org/');
79
- *
80
- * const scoreSchema = new Schema({
81
- * game: { $ref: 'VideoGame', required: true },
82
- * wins: { type: 'integer', required: true },
83
- * bestScore: { type: 'integer', required: true }
84
- * }, 'VideoGameScore');
85
- *
86
- * // Create factory with multiple schemas
87
- * const factory = new CredentialFactory(
88
- * 'https://example.com/schema/GameScoreV1',
89
- * [playerSchema, videoGameSchema, scoreSchema]
90
- * );
91
- *
92
- * // Generate credential with nested data
93
- * const credential = factory.createCredential(
94
- * 'https://example.com/credentials/score-456',
95
- * 'did:player:789',
96
- * {
97
- * id: 'did:player:789',
98
- * hasVideoGameScore: {
99
- * game: { id: 'did:game:001', name: 'MineSweeper', version: '1.0' },
100
- * wins: 10,
101
- * bestScore: 5000
102
- * }
103
- * }
104
- * );
105
- * ```
106
- *
107
- * **Example - Accessing Credential Context:**
108
- * ```typescript
109
- * const factory = new CredentialFactory(uri, schemas);
110
- *
111
- * // Get credential type (extracted from URI)
112
- * const type = factory.credentialType; // e.g., 'AccountV1'
113
- *
114
- * // Get JSON-LD context for embedding
115
- * const context = factory.context;
116
- * // {
117
- * // AccountV1: { '@id': 'https://example.com/schema/AccountV1' },
118
- * // Account: { '@id': '...', '@context': {...} }
119
- * // }
120
- * ```
121
- */
11
+ /** Factory class for creating Verifiable Credentials with embedded JSON-LD linked data context. */
122
12
  class CredentialFactory {
123
13
  _uri;
124
14
  _types;
125
15
  _context;
126
16
  _validator;
127
- /**
128
- * Creates a new CredentialFactory instance.
129
- *
130
- * **Intent:** Initialize a factory with credential schemas and URI, enabling credential
131
- * generation with automatic validation and JSON-LD context generation.
132
- *
133
- * **Use Cases:**
134
- * - Set up credential factories for different credential types
135
- * - Configure factories with single or multiple related schemas
136
- * - Prepare factories for batch credential generation
137
- *
138
- * **Behavior:**
139
- * - Validates that the provided URI is a valid URL
140
- * - Processes schemas: if a schema doesn't have a URL, creates a new Schema instance
141
- * with the factory URI as the base URL
142
- * - Validates all schemas using the Validator
143
- * - Builds JSON-LD context from schema linked data types
144
- *
145
- * @param uri - The base URI for the credential type (e.g., 'https://example.com/schema/AccountV1')
146
- * Must be a valid URL. The last segment will be used as the credential type name.
147
- * @param schemas - Array of Schema instances defining the credential subject structure.
148
- * The first schema is considered the root schema for validation.
149
- * Schemas can reference each other using `$ref`.
150
- *
151
- * @throws Error if the URI is not a valid URL
152
- * @throws Error if schema validation fails (e.g., invalid JSON Schema structure)
153
- *
154
- * **Example:**
155
- * ```typescript
156
- * const accountSchema = new Schema({
157
- * username: { required: true },
158
- * email: { format: 'email', required: true }
159
- * }, 'Account');
160
- *
161
- * const factory = new CredentialFactory(
162
- * 'https://example.com/schema/AccountV1',
163
- * [accountSchema]
164
- * );
165
- * ```
166
- */
17
+ /** Creates a new CredentialFactory instance. */
167
18
  constructor(uri, schemas) {
168
19
  (0, validateId_1.default)('uri', uri);
169
20
  this._types = schemas
@@ -180,182 +31,19 @@ class CredentialFactory {
180
31
  this._context[id] = linkedDataType;
181
32
  }
182
33
  }
183
- /**
184
- * Returns the credential type name extracted from the factory URI.
185
- *
186
- * **Intent:** Provide a convenient way to access the credential type identifier
187
- * without manually parsing the URI.
188
- *
189
- * **Use Cases:**
190
- * - Access credential type for logging or debugging
191
- * - Use type name in credential processing logic
192
- * - Generate type-specific identifiers or filenames
193
- *
194
- * **Behavior:**
195
- * - Extracts the last segment from the URI path
196
- * - Example: 'https://example.com/schema/AccountV1' → 'AccountV1'
197
- *
198
- * @returns The credential type name (last segment of the URI path)
199
- *
200
- * **Example:**
201
- * ```typescript
202
- * const factory = new CredentialFactory(
203
- * 'https://example.com/schema/AccountV1',
204
- * [schema]
205
- * );
206
- *
207
- * console.log(factory.credentialType); // 'AccountV1'
208
- * ```
209
- */
34
+ /** Returns the credential type name extracted from the factory URI. */
210
35
  get credentialType() {
211
36
  const [credentialType] = this._uri.split('/').reverse();
212
37
  return credentialType;
213
38
  }
214
- /**
215
- * Returns the JSON-LD context object for the credential.
216
- *
217
- * **Intent:** Provide the complete JSON-LD context mapping that should be included
218
- * in the credential's `@context` array for semantic web compatibility.
219
- *
220
- * **Use Cases:**
221
- * - Access context for credential serialization
222
- * - Inspect context mappings for debugging
223
- * - Use context in custom credential processing
224
- * - Embed context in other JSON-LD documents
225
- *
226
- * **Structure:**
227
- * - Contains the credential type mapping (`{ credentialType: { '@id': uri } }`)
228
- * - Includes all schema-linked data types from the factory's schemas
229
- * - Each schema's `linkedDataType` is included if the schema was created with a URL
230
- *
231
- * @returns Object containing credential type and schema type mappings for JSON-LD context
232
- *
233
- * **Example:**
234
- * ```typescript
235
- * const factory = new CredentialFactory(uri, schemas);
236
- * const context = factory.context;
237
- *
238
- * // Result structure:
239
- * // {
240
- * // AccountV1: { '@id': 'https://example.com/schema/AccountV1' },
241
- * // Account: {
242
- * // '@id': 'https://example.com/schema/AccountV1#Account',
243
- * // '@context': { ... }
244
- * // }
245
- * // }
246
- * ```
247
- */
39
+ /** Returns the JSON-LD context object for the credential. */
248
40
  get context() {
249
41
  return {
250
42
  [this.credentialType]: { '@id': this._uri },
251
43
  ...this._context
252
44
  };
253
45
  }
254
- /**
255
- * Creates a Verifiable Credential for the specified subject.
256
- *
257
- * **Intent:** Generate a W3C-compliant Verifiable Credential with validated subject data,
258
- * proper JSON-LD context, and standardized structure ready for issuance and verification.
259
- *
260
- * **Use Cases:**
261
- * - Issue credentials for user accounts, achievements, certifications
262
- * - Generate credentials with automatic schema validation
263
- * - Create credentials with embedded semantic context for interoperability
264
- * - Build credentials for decentralized identity systems
265
- * - Generate credentials that can be verified using JSON-LD processors
266
- *
267
- * **Behavior:**
268
- * - Validates that `id` and `holder` are valid URLs/URIs
269
- * - Validates the subject against the root schema (first schema in the factory)
270
- * - Applies schema defaults and normalizes data according to schema rules
271
- * - Generates credential with proper `@context`, `type`, `id`, `holder`, and `credentialSubject`
272
- * - Returns credential ready for signing (issuer, issuanceDate, proof to be added separately)
273
- *
274
- * **Credential Structure:**
275
- * ```typescript
276
- * {
277
- * '@context': [
278
- * 'https://www.w3.org/2018/credentials/v1',
279
- * factory.context // JSON-LD context from factory
280
- * ],
281
- * id: string, // Credential identifier
282
- * type: ['VerifiableCredential', credentialType],
283
- * holder: string, // DID or identifier of credential holder
284
- * credentialSubject: { // Validated and normalized subject data
285
- * id: string,
286
- * type: string, // Root schema ID
287
- * // ... additional subject properties
288
- * }
289
- * }
290
- * ```
291
- *
292
- * @param id - Unique identifier for the credential (must be a valid URL/URI)
293
- * @param holder - DID or identifier of the credential holder (must be a valid URL/URI)
294
- * @param subject - Object containing the credential subject data to be validated against
295
- * the root schema. Properties are validated, defaults are applied,
296
- * and nested objects are validated against referenced schemas.
297
- *
298
- * @returns Verifiable Credential object with validated subject and JSON-LD context
299
- *
300
- * @throws Error if `id` is not a valid URL/URI
301
- * @throws Error if `holder` is not a valid URL/URI
302
- * @throws ValidationError if subject data doesn't match the schema requirements
303
- *
304
- * **Example - Basic Credential:**
305
- * ```typescript
306
- * const factory = new CredentialFactory(uri, [accountSchema]);
307
- *
308
- * const credential = factory.createCredential(
309
- * 'https://example.com/credentials/123',
310
- * 'did:holder:456',
311
- * {
312
- * id: 'did:holder:456',
313
- * username: 'alice',
314
- * createdAt: '2024-01-01T00:00:00Z'
315
- * }
316
- * );
317
- *
318
- * // Result:
319
- * // {
320
- * // '@context': ['https://www.w3.org/2018/credentials/v1', {...}],
321
- * // id: 'https://example.com/credentials/123',
322
- * // type: ['VerifiableCredential', 'AccountV1'],
323
- * // holder: 'did:holder:456',
324
- * // credentialSubject: {
325
- * // id: 'did:holder:456',
326
- * // username: 'alice',
327
- * // createdAt: '2024-01-01T00:00:00Z',
328
- * // type: 'Account'
329
- * // }
330
- * // }
331
- * ```
332
- *
333
- * **Example - Credential with Nested Objects:**
334
- * ```typescript
335
- * const factory = new CredentialFactory(uri, [playerSchema, gameSchema, scoreSchema]);
336
- *
337
- * const credential = factory.createCredential(
338
- * 'https://example.com/credentials/score-789',
339
- * 'did:player:123',
340
- * {
341
- * id: 'did:player:123',
342
- * hasVideoGameScore: {
343
- * game: {
344
- * id: 'did:game:001',
345
- * name: 'MineSweeper',
346
- * version: '1.0'
347
- * },
348
- * wins: 10,
349
- * bestScore: 5000
350
- * }
351
- * }
352
- * );
353
- * ```
354
- *
355
- * **Note:** The returned credential does not include `issuer`, `issuanceDate`, or `proof`
356
- * fields. These should be added by the credential issuance system (e.g., using
357
- * [@kravc/identity](http://github.com/alexkravets/identity) or similar libraries).
358
- */
46
+ /** Creates a Verifiable Credential for the specified subject. */
359
47
  createCredential(id, holder, subject = {}) {
360
48
  (0, validateId_1.default)('id', id);
361
49
  (0, validateId_1.default)('holder', holder);