@asaidimu/anansi 1.6.0 → 1.6.2

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 (5) hide show
  1. package/index.cjs +33 -48
  2. package/index.d.cts +250 -27
  3. package/index.d.ts +250 -27
  4. package/index.js +42 -57
  5. package/package.json +1 -1
package/index.d.cts CHANGED
@@ -175,6 +175,16 @@ type FieldType = "string" | "number" | "boolean" | "array" | "set" | "enum" | "o
175
175
  type IndexType = "normal" | "unique" | "btree" | "hash" | "spatial" | "fulltext" | "gi" | "expression" | "composite";
176
176
  /**
177
177
  * Defines a predicate function for data validation, mapped to a PredicateMap at runtime.
178
+ *
179
+ * @example
180
+ * ```typescript
181
+ * const isEmail: Predicate = ({ data, field, arguments: regex }) => {
182
+ * if (field && typeof data[field] === 'string') {
183
+ * return regex.test(data[field]);
184
+ * }
185
+ * return false;
186
+ * };
187
+ * ```
178
188
  */
179
189
  type Predicate = <T, K extends FieldType = any>(params: {
180
190
  data: T;
@@ -183,20 +193,53 @@ type Predicate = <T, K extends FieldType = any>(params: {
183
193
  }) => boolean;
184
194
  /**
185
195
  * A map of predicate names to their validation functions, implemented by the runtime environment.
196
+ *
197
+ * @example
198
+ * ```typescript
199
+ * const predicateMap: PredicateMap = {
200
+ * isEmail: isEmail,
201
+ * isPositive: ({ data, field, arguments: min }) => {
202
+ * if (field && typeof data[field] === 'number'){
203
+ * return data[field] > min;
204
+ * }
205
+ * return false;
206
+ * }
207
+ * };
208
+ * ```
186
209
  */
187
210
  type PredicateMap = Record<string, Predicate>;
188
211
  /**
189
212
  * A map of function names to generic functions, used elsewhere in the system.
213
+ *
214
+ * @example
215
+ * ```typescript
216
+ * const functionMap: FunctionMap = {
217
+ * calculateTotal: (items: { price: number; quantity: number }[]) => {
218
+ * return items.reduce((acc, item) => acc + item.price * item.quantity, 0);
219
+ * }
220
+ * };
221
+ * ```
190
222
  */
191
223
  type FunctionMap = Record<string, Function>;
192
224
  /** @deprecated Use PredicateMap instead. */
193
225
  type ConstraintsMap = Record<string, Predicate>;
194
226
  /**
195
227
  * Names of supported predicates, derived from a PredicateMap.
228
+ *
229
+ * @example
230
+ * ```typescript
231
+ * type AvailablePredicates = PredicateName<typeof predicateMap>; // "isEmail" | "isPositive"
232
+ * ```
196
233
  */
197
234
  type PredicateName<T extends PredicateMap = any> = keyof T;
198
235
  /**
199
236
  * Parameters for predicates, tailored to each field type.
237
+ *
238
+ * @example
239
+ * ```typescript
240
+ * type StringParams = PredicateParameters<"string">; // string | string[] | RegExp | { field: string }
241
+ * type NumberParams = PredicateParameters<"number">; // number | number[] | { precision: number; scale?: number } | { field: string }
242
+ * ```
200
243
  */
201
244
  type PredicateParameters<T extends FieldType> = T extends "string" ? string | string[] | RegExp | {
202
245
  field: string;
@@ -217,6 +260,16 @@ type PredicateParameters<T extends FieldType> = T extends "string" ? string | st
217
260
  type ConstraintParameters<T extends FieldType> = PredicateParameters<T>;
218
261
  /**
219
262
  * Defines a constraint on a field or schema, using a predicate for validation.
263
+ *
264
+ * @example
265
+ * ```typescript
266
+ * const emailConstraint: Constraint<"string"> = {
267
+ * name: "email",
268
+ * predicate: "isEmail",
269
+ * parameters: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
270
+ * errorMessage: "Must be a valid email address."
271
+ * };
272
+ * ```
220
273
  */
221
274
  type Constraint<T extends FieldType> = {
222
275
  type?: "schema";
@@ -229,6 +282,18 @@ type Constraint<T extends FieldType> = {
229
282
  };
230
283
  /**
231
284
  * Groups multiple constraints with a logical operator for complex validation logic.
285
+ *
286
+ * @example
287
+ * ```typescript
288
+ * const compositeConstraint: ConstraintGroup<"number"> = {
289
+ * name: "positiveAndLessThan100",
290
+ * operator: "and",
291
+ * rules: [
292
+ * { name: "positive", predicate: "isPositive", parameters: 0 },
293
+ * { name: "lessThan100", predicate: "isLessThan", parameters: 100 }
294
+ * ]
295
+ * };
296
+ * ```
232
297
  */
233
298
  interface ConstraintGroup<T extends FieldType> {
234
299
  name: string;
@@ -237,6 +302,14 @@ interface ConstraintGroup<T extends FieldType> {
237
302
  }
238
303
  /**
239
304
  * Collection of constraints or groups applied at the schema or nested level.
305
+ *
306
+ * @example
307
+ * ```typescript
308
+ * const schemaConstraints: SchemaConstraint<"number"> = [
309
+ * { name: "positive", predicate: "isPositive", parameters: 0 },
310
+ * compositeConstraint
311
+ * ];
312
+ * ```
240
313
  */
241
314
  type SchemaConstraint<T extends FieldType> = Array<Constraint<T> | ConstraintGroup<T>>;
242
315
  /** Reference to a nested schema (mini-SchemaDefinition) with optional overrides. */
@@ -247,6 +320,23 @@ interface FieldSchema {
247
320
  }
248
321
  /**
249
322
  * Defines a field within a schema, including its type, constraints, and nesting.
323
+ *
324
+ * @example
325
+ * ```typescript
326
+ * const ageField: FieldDefinition<number> = {
327
+ * name: "age",
328
+ * type: "number",
329
+ * required: true,
330
+ * constraints: [{ name: "positive", predicate: "isPositive", parameters: 0 }],
331
+ * default: 25,
332
+ * hint: {
333
+ * input: {
334
+ * min : 0,
335
+ * max : 100
336
+ * }
337
+ * }
338
+ * };
339
+ * ```
250
340
  */
251
341
  interface FieldDefinition<T> {
252
342
  name: string;
@@ -257,7 +347,7 @@ interface FieldDefinition<T> {
257
347
  /** For type 'enum', specifies the allowed values. */
258
348
  values?: Array<string | number>;
259
349
  /** For type 'union', specifies the array of allowed schemas.
260
- * For type 'object' specifies the schema of the object
350
+ * For type 'object' specifies the schema of the object
261
351
  * */
262
352
  schema?: FieldSchema | Array<FieldSchema>;
263
353
  itemsType?: FieldType;
@@ -275,6 +365,15 @@ interface FieldDefinition<T> {
275
365
  }
276
366
  /**
277
367
  * Condition for partial indexes, allowing conditional indexing based on field values.
368
+ *
369
+ * @example
370
+ * ```typescript
371
+ * const activeCondition: PartialIndexCondition = {
372
+ * operator: "and",
373
+ * field: "isActive",
374
+ * value: true
375
+ * };
376
+ * ```
278
377
  */
279
378
  interface PartialIndexCondition {
280
379
  operator: LogicalOperator;
@@ -284,6 +383,16 @@ interface PartialIndexCondition {
284
383
  }
285
384
  /**
286
385
  * Defines an index for optimizing queries or enforcing uniqueness.
386
+ *
387
+ * @example
388
+ * ```typescript
389
+ * const nameIndex: IndexDefinition = {
390
+ * name: "nameIndex",
391
+ * fields: ["firstName", "lastName"],
392
+ * type: "composite",
393
+ * unique: true
394
+ * };
395
+ * ```
287
396
  */
288
397
  interface IndexDefinition {
289
398
  fields: string[];
@@ -300,6 +409,27 @@ interface IndexDefinition {
300
409
  * but only when concrete is false. This restriction avoids complexity in RDBMS implementations,
301
410
  * where concrete schemas map directly to tables with fixed columns. Non-concrete schemas, as embedded
302
411
  * structures, can leverage this flexibility without affecting physical table design.
412
+ *
413
+ * @example
414
+ * ```typescript
415
+ * const addressSchema: NestedSchemaDefinition = {
416
+ * name: "address",
417
+ * fields: {
418
+ * street: { name: "street", type: "string" },
419
+ * city: { name: "city", type: "string" },
420
+ * zip: { name: "zip", type: "string" }
421
+ * },
422
+ * concrete: true
423
+ * };
424
+ *
425
+ * const contactSchema: NestedSchemaDefinition = {
426
+ * name: "contact",
427
+ * fields: [
428
+ * { fields: { email: { name: "email", type: "string" } }, when: { field: "type", value: "email" } },
429
+ * { fields: { phone: { name: "phone", type: "string" } }, when: { field: "type", value: "phone" } }
430
+ * ]
431
+ * };
432
+ * ```
303
433
  */
304
434
  interface NestedSchemaDefinition {
305
435
  /**
@@ -321,8 +451,8 @@ interface NestedSchemaDefinition {
321
451
  * Defines the fields of the nested schema.
322
452
  * - If concrete is true, must be a Record<string, FieldDefinition<any>> for a fixed field set.
323
453
  * - If concrete is false, can be either a Record<string, FieldDefinition<any>> or an
324
- * Array<{ fields: Record<string, FieldDefinition<any>>; when?: { field: string; value: any } }>,
325
- * allowing discriminated field sets based on a field value (e.g., 'type').
454
+ * Array<{ fields: Record<string, FieldDefinition<any>>; when?: { field: string; value: any } }>,
455
+ * allowing discriminated field sets based on a field value (e.g., 'type').
326
456
  * The array form enables variant-specific fields without constraints, but is not supported for
327
457
  * concrete schemas to maintain simplicity in RDBMS table mappings.
328
458
  */
@@ -343,6 +473,34 @@ interface NestedSchemaDefinition {
343
473
  }
344
474
  /**
345
475
  * Defines a complete schema, intended as an atomic unit within a larger domain model.
476
+ *
477
+ * @example
478
+ * ```typescript
479
+ * const userSchema: SchemaDefinition = {
480
+ * name: "user",
481
+ * version: "1.0.0",
482
+ * fields: {
483
+ * id: { name: "id", type: "string", required: true },
484
+ * name: { name: "name", type: "string" },
485
+ * address: { name: "address", type: "object", schema: { id: "address" } }
486
+ * },
487
+ * nestedSchemas: {
488
+ * address: addressSchema
489
+ * },
490
+ * indexes: [{ name: "nameIndex", fields: ["name"], type: "normal" }],
491
+ * mock: (faker) => {
492
+ * return {
493
+ * id: faker.string.uuid(),
494
+ * name: faker.person.fullName(),
495
+ * address: {
496
+ * street: faker.location.streetAddress(),
497
+ * city: faker.location.city(),
498
+ * zip: faker.location.zipCode()
499
+ * }
500
+ * };
501
+ * }
502
+ * };
503
+ * ```
346
504
  */
347
505
  interface SchemaDefinition {
348
506
  name: string;
@@ -363,6 +521,25 @@ interface SchemaDefinition {
363
521
  /**
364
522
  * Defines a change that can be made to a schema during migration.
365
523
  * Updated to support the new NestedSchemaDefinition structure.
524
+ *
525
+ * @example
526
+ * ```typescript
527
+ * const addEmailField: SchemaChange<string> = {
528
+ * type: "addField",
529
+ * id: "email",
530
+ * definition: { name: "email", type: "string" }
531
+ * };
532
+ *
533
+ * const modifyAddressSchema: SchemaChange<any> = {
534
+ * type: "modifyNestedSchema",
535
+ * id: "address",
536
+ * changes: {
537
+ * fields: {
538
+ * country: {name: "country", type: "string"}
539
+ * }
540
+ * }
541
+ * }
542
+ * ```
366
543
  */
367
544
  type SchemaChange<T> = {
368
545
  type: "modifyProperty";
@@ -421,10 +598,25 @@ type SchemaChange<T> = {
421
598
  };
422
599
  /**
423
600
  * Defines a transform function for data migration between schema versions.
601
+ *
602
+ * @example
603
+ * ```typescript
604
+ * const transformEmail: TransformFunction<{ oldEmail: string }, { email: string }> = (data) => {
605
+ * return { email: data.oldEmail };
606
+ * };
607
+ * ```
424
608
  */
425
609
  type TransformFunction<Initial, Next> = (data: Initial) => Next | Promise<Next>;
426
610
  /**
427
611
  * Represents a pair of transformations for bidirectional data migration.
612
+ *
613
+ * @example
614
+ * ```typescript
615
+ * const emailMigration: DataTransform<{ oldEmail: string }, { email: string }> = {
616
+ * forward: transformEmail,
617
+ * backward: (data) => ({ oldEmail: data.email })
618
+ * };
619
+ * ```
428
620
  */
429
621
  interface DataTransform<Initial, Next> {
430
622
  forward: TransformFunction<Initial, Next>;
@@ -432,6 +624,20 @@ interface DataTransform<Initial, Next> {
432
624
  }
433
625
  /**
434
626
  * Defines a migration, consisting of schema changes and data transforms.
627
+ *
628
+ * @example
629
+ * ```typescript
630
+ * const emailMigration: Migration<string> = {
631
+ * id: "emailMigration",
632
+ * schemaVersion: "2.0.0",
633
+ * changes: [addEmailField],
634
+ * description: "Adds email field",
635
+ * status: "pending",
636
+ * transform: emailMigration,
637
+ * createdAt: new Date().toISOString(),
638
+ * checksum: "someChecksum"
639
+ * };
640
+ * ```
435
641
  */
436
642
  interface Migration<T> {
437
643
  id: string;
@@ -448,6 +654,13 @@ interface Migration<T> {
448
654
  }
449
655
  /**
450
656
  * Generator type for mock data functions (used with Faker).
657
+ *
658
+ * @example
659
+ * ```typescript
660
+ * const mockGenerator: Generator<{ name: string }, void, unknown> = function* (faker) {
661
+ * yield { name: faker.person.fullName() };
662
+ * };
663
+ * ```
451
664
  */
452
665
  type Generator<T, TReturn, TNext> = Iterator<T, TReturn, TNext>;
453
666
 
@@ -1536,6 +1749,37 @@ declare function validateSchemaDefinition(schema: unknown): schema is SchemaDefi
1536
1749
  */
1537
1750
  declare const validate: typeof validateSchemaDefinition;
1538
1751
 
1752
+ /**
1753
+ * Represents a group of field definitions with optional metadata.
1754
+ */
1755
+ interface FieldGroup {
1756
+ name: string;
1757
+ label: string;
1758
+ description?: string;
1759
+ fields: FieldDefinition<any>[];
1760
+ }
1761
+ /**
1762
+ * Extracts all field definitions from a schema, organized into groups based on hint.input.group,
1763
+ * including those in nested schemas, with proper path prefixing to represent the field hierarchy.
1764
+ *
1765
+ * @param schema - The schema definition to extract fields from
1766
+ * @returns Array of field groups, each containing grouped field definitions
1767
+ */
1768
+ declare function extractInputFieldGroups(schema: SchemaDefinition): FieldGroup[];
1769
+ /**
1770
+ * Generates a default data object from a schema definition, ensuring all fields have values.
1771
+ * Fields with explicit defaults use those values; otherwise, type-based defaults are applied.
1772
+ * An optional resolver can override type-based defaults for fields without explicit defaults.
1773
+ *
1774
+ * @param schema - The schema definition to generate defaults from
1775
+ * @param options - Optional configuration for custom defaults and discriminators
1776
+ * @returns A fully populated default object conforming to the schema's structure
1777
+ */
1778
+ declare function schemaDefaults<T>(schema: SchemaDefinition, options?: {
1779
+ resolver?: (field: FieldDefinition<any>) => any;
1780
+ discriminator?: Record<string, any>;
1781
+ }): T;
1782
+
1539
1783
  /**
1540
1784
  * Generates a SHA-256 hash of the input string.
1541
1785
  *
@@ -1559,7 +1803,8 @@ declare function deepMerge<T extends object>(target: T, update: Partial<T>): T;
1559
1803
  * nested schemas, and union types for enum fields and constraints. Uses field.name as-is for field names,
1560
1804
  * capitalized nestedSchema.name for type names, and handles required/optional fields, new types (enum,
1561
1805
  * record, union), discriminated unions with common fields, primitives, arrays, sets, references, and nested
1562
- * structures with strict type safety. Introduces unique generics for each record field.
1806
+ * structures with strict type safety. Introduces unique generics for each record field and adjusts object
1807
+ * fields referencing concrete schemas to use a string | NestedType union.
1563
1808
  *
1564
1809
  * @param schema - The schema definition to convert
1565
1810
  * @param includeComments - Whether to include JSDoc comments (default: true)
@@ -1567,10 +1812,6 @@ declare function deepMerge<T extends object>(target: T, update: Partial<T>): T;
1567
1812
  * @returns TypeScript type definitions as a string
1568
1813
  */
1569
1814
  declare function schemaToTypes(schema: SchemaDefinition, includeComments?: boolean, exportTypes?: boolean): string;
1570
- /**
1571
- * Generates a TypeScript interface for validating schema data
1572
- */
1573
- declare function generateValidationInterface(schema: SchemaDefinition, exportType?: boolean): string;
1574
1815
 
1575
1816
  /**
1576
1817
  * Serializes constraint parameters for error messages, handling special types like RegExp.
@@ -1615,22 +1856,4 @@ declare function docgen(schema: SchemaDefinition, options?: {
1615
1856
  faker?: Faker;
1616
1857
  }): string;
1617
1858
 
1618
- /**
1619
- * Represents a group of field definitions with optional metadata.
1620
- */
1621
- interface FieldGroup {
1622
- name: string;
1623
- label: string;
1624
- description?: string;
1625
- fields: FieldDefinition<any>[];
1626
- }
1627
- /**
1628
- * Extracts all field definitions from a schema, organized into groups based on hint.input.group,
1629
- * including those in nested schemas, with proper path prefixing to represent the field hierarchy.
1630
- *
1631
- * @param schema - The schema definition to extract fields from
1632
- * @returns Array of field groups, each containing grouped field definitions
1633
- */
1634
- declare function extractInputFieldGroups(schema: SchemaDefinition): FieldGroup[];
1635
-
1636
- export { type ArrayHint, type BooleanHint, type Constraint, type ConstraintGroup, type ConstraintParameters, type ConstraintsMap, type DataTransform, type DateHint, type DynamicHint, type EnumHint, type FieldDefinition, type FieldGroup, type FieldSchema, type FieldType, type FileHint, type FunctionMap, type GroupDefinition, type IndexDefinition, type IndexType, type InputHint, JsonPatchError, type LogicalOperator, type Migration, MigrationEngine, type MigrationEngineInterface, MigrationError, MigrationErrorCode, type MigrationMetadata, type NestedSchemaDefinition, type NumberHint, type ObjectHint, type PartialIndexCondition, type PatchOperation, type Persistence, type PersistenceCollection, type PersistenceEvent, type PersistenceEventType, type PersistenceTransaction, type Predicate, type PredicateMap, type PredicateName, type PredicateParameters, type RegistryLock, type RegistryMetadata, type RemoteRepository, type Schema, type SchemaChange, type SchemaConstraint, type SchemaDefinition, type SchemaEvent, type SchemaEventType, type SchemaHint, type SchemaIndex, type SchemaMetadata, type SchemaMigrationHelper, SchemaRegistry, type SchemaRegistryInterface, type SchemaVersion, type SecretHint, type SetHint, type TextHint, type TransformFunction, applyPatch, calculateNextVersion, compareSemanticVersions, createGitSchemaRegistry, createPatch, createSchemaMigrationHelper, createStandardSchemaValidator, deepMerge, docgen, extractInputFieldGroups, formResolver, generateSHA256Hash, generateValidationInterface, normalizePath, schemaChangeToPatch, schemaToTypes, serializeParams, sortSemanticVars, validate, validateMigration, validateSchemaChange, validateSchemaDefinition };
1859
+ export { type ArrayHint, type BooleanHint, type Constraint, type ConstraintGroup, type ConstraintParameters, type ConstraintsMap, type DataTransform, type DateHint, type DynamicHint, type EnumHint, type FieldDefinition, type FieldGroup, type FieldSchema, type FieldType, type FileHint, type FunctionMap, type GroupDefinition, type IndexDefinition, type IndexType, type InputHint, JsonPatchError, type LogicalOperator, type Migration, MigrationEngine, type MigrationEngineInterface, MigrationError, MigrationErrorCode, type MigrationMetadata, type NestedSchemaDefinition, type NumberHint, type ObjectHint, type PartialIndexCondition, type PatchOperation, type Persistence, type PersistenceCollection, type PersistenceEvent, type PersistenceEventType, type PersistenceTransaction, type Predicate, type PredicateMap, type PredicateName, type PredicateParameters, type RegistryLock, type RegistryMetadata, type RemoteRepository, type Schema, type SchemaChange, type SchemaConstraint, type SchemaDefinition, type SchemaEvent, type SchemaEventType, type SchemaHint, type SchemaIndex, type SchemaMetadata, type SchemaMigrationHelper, SchemaRegistry, type SchemaRegistryInterface, type SchemaVersion, type SecretHint, type SetHint, type TextHint, type TransformFunction, applyPatch, calculateNextVersion, compareSemanticVersions, createGitSchemaRegistry, createPatch, createSchemaMigrationHelper, createStandardSchemaValidator, deepMerge, docgen, extractInputFieldGroups, formResolver, generateSHA256Hash, normalizePath, schemaChangeToPatch, schemaDefaults, schemaToTypes, serializeParams, sortSemanticVars, validate, validateMigration, validateSchemaChange, validateSchemaDefinition };