@orkestrel/relation 0.0.22 → 0.0.23

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.
@@ -1,12 +1,18 @@
1
+ import type { ContractInterface } from '@orkestrel/contract';
1
2
  import type { DatabaseStorageInterface } from '@orkestrel/database';
2
3
  import type { EmitterErrorHandler } from '@orkestrel/emitter';
3
4
  import type { EmitterHooks } from '@orkestrel/emitter';
4
5
  import type { EmitterInterface } from '@orkestrel/emitter';
6
+ import type { Guard } from '@orkestrel/contract';
5
7
  import type { Key } from '@orkestrel/database';
8
+ import { LiteralShape } from '@orkestrel/contract';
9
+ import { ObjectShape } from '@orkestrel/contract';
6
10
  import type { OperationOptions } from '@orkestrel/database';
11
+ import { OptionalShape } from '@orkestrel/contract';
7
12
  import type { OrderDirection } from '@orkestrel/database';
8
13
  import type { Row } from '@orkestrel/database';
9
14
  import type { RowOf } from '@orkestrel/database';
15
+ import { StringShape } from '@orkestrel/contract';
10
16
  import type { TableInterface } from '@orkestrel/database';
11
17
  import type { TableMap } from '@orkestrel/database';
12
18
 
@@ -25,6 +31,25 @@ import type { TableMap } from '@orkestrel/database';
25
31
  */
26
32
  export declare function belongsTo(column: string, model?: string): RelationDescriptor;
27
33
 
34
+ /**
35
+ * Computes the junction row's primary key for one pair of a `through` relation.
36
+ *
37
+ * @remarks
38
+ * The key is the JSON text of `[key, target]`, so each pair has one key and a string key
39
+ * stays apart from the number it spells. `link` inserts under this key and `unlink` removes
40
+ * it, which is why a junction's primary column must store text.
41
+ *
42
+ * @param key - The owning record's primary key
43
+ * @param target - The related record's primary key
44
+ * @returns The pair's junction key
45
+ *
46
+ * @example
47
+ * ```ts
48
+ * computeLinkKey('acc1', 'rep1') // '["acc1","rep1"]'
49
+ * ```
50
+ */
51
+ export declare function computeLinkKey(key: Key, target: Key): string;
52
+
28
53
  /**
29
54
  * Counts the related rows one relation attached across a record set.
30
55
  *
@@ -100,7 +125,7 @@ export declare interface FindOptions extends OperationOptions {
100
125
  * Groups rows by the string form of one column, for one-to-many lookups.
101
126
  *
102
127
  * @remarks
103
- * The column is read with {@link readColumn} and its value stringified, so a numeric
128
+ * The column is read with `resolveField` and its value stringified, so a numeric
104
129
  * and a string foreign key meet at the same group. Rows keep their input order inside
105
130
  * a group, a key no row carries is absent rather than empty, and a row missing the
106
131
  * column groups under the string `'undefined'`. This is the projection a `many` load
@@ -191,7 +216,7 @@ export declare interface Include {
191
216
  * Indexes rows by the string form of one column, for keyed lookups.
192
217
  *
193
218
  * @remarks
194
- * The column is read with {@link readColumn} and its value stringified, so a numeric
219
+ * The column is read with `resolveField` and its value stringified, so a numeric
195
220
  * and a string foreign key meet at the same entry. A later row with a key an earlier
196
221
  * row already holds replaces it, and a row missing the column indexes under the string
197
222
  * `'undefined'`. This is the projection a `belongs` load and a `through` load use to
@@ -214,32 +239,43 @@ export declare function indexRows(rows: readonly Row[], column: string, values?:
214
239
  * Narrows a value to a {@link RelationDescriptor} (the object form of a relation).
215
240
  *
216
241
  * @remarks
217
- * A record satisfies the descriptor when every member it declares carries its declared
218
- * type: `relationship` is one of the `Relationship` values, and `column`, `key`,
219
- * `through`, `source`, `target`, `tag`, `label`, and `model` are strings. A member the
220
- * record omits is unconstrained, a member present with an `undefined` value is refused,
221
- * and a member the descriptor does not declare is carried without being checked. This
222
- * is what lets `resolveRelation` read each member after one narrow and report a
223
- * malformed definition as an `INVALID` `RelationError` instead of resolving a
224
- * wrong-typed column into an arm that declares it a string.
225
- *
226
- * @param value - The value to test
227
- * @returns True if `value` is a record whose every declared member holds its declared
228
- * type; false otherwise
242
+ * The guard of the compiled `relationDescriptorContract`: a plain record whose every
243
+ * member is optional, with `relationship` one of the `Relationship` values and `column`,
244
+ * `key`, `through`, `source`, `target`, `tag`, `label`, and `model` strings. A member
245
+ * present with an `undefined` value, a member holding another type, and an enumerable,
246
+ * string-keyed member the descriptor does not declare each refuse it. That is what lets
247
+ * `resolveRelation` read each member after one narrow and report a malformed definition
248
+ * as an `INVALID` `RelationError`.
229
249
  *
230
250
  * @example
231
251
  * ```ts
232
252
  * isRelationDescriptor(belongsTo('accountId')) // true
233
253
  * isRelationDescriptor({ column: 42 }) // false — `column` is declared a string
254
+ * isRelationDescriptor({ column: 'accountId', comment: 'x' }) // false — `comment` is undeclared
234
255
  * ```
235
256
  */
236
- export declare function isRelationDescriptor(value: unknown): value is RelationDescriptor;
257
+ export declare const isRelationDescriptor: Guard<RelationDescriptor>;
237
258
 
238
259
  /**
239
260
  * Narrows an unknown caught value to a {@link RelationError}.
240
261
  *
262
+ * @remarks
263
+ * Accepts branded instances and subclasses across package copies and module formats.
264
+ * Requires a declared {@link RelationErrorCode} and a `context` that is absent, an object,
265
+ * or a callable object. Refuses look-alikes, transparent proxies, and plain branded objects
266
+ * without requiring an exact `name`.
267
+ *
241
268
  * @param value - The value to test (typically a `catch` binding)
242
- * @returns True if the error carries its own identity brand and declared members; false otherwise
269
+ * @returns True if `value` is a {@link RelationError}; false otherwise
270
+ *
271
+ * @example
272
+ * ```ts
273
+ * try {
274
+ * resolveRelation('ghost', {})
275
+ * } catch (error) {
276
+ * if (isRelationError(error) && error.code === 'INVALID') report(error.message)
277
+ * }
278
+ * ```
243
279
  */
244
280
  export declare function isRelationError(value: unknown): value is RelationError;
245
281
 
@@ -248,9 +284,9 @@ export declare function isRelationError(value: unknown): value is RelationError;
248
284
  *
249
285
  * @remarks
250
286
  * The base row is fully typed (the table's row type); the relation properties
251
- * ({@link LoadedMap}) are broad — narrow them at the use site. Typing each
252
- * relation property to its target row is a deliberate (documented) deferral, like
253
- * the database guide's deferred pieces.
287
+ * ({@link LoadedMap}) are broad — narrow them at the use site. A relation property
288
+ * typed to its target row is refused until a consumer narrows a loaded relation
289
+ * property by hand.
254
290
  */
255
291
  export declare type Loaded<T> = T & Readonly<LoadedMap>;
256
292
 
@@ -275,8 +311,10 @@ export declare type LoadedMap = Record<string, Row | readonly Row[] | undefined>
275
311
  * a direct relation uses one query for the whole record set, while a `through`
276
312
  * relation uses two (junction then target); both counts remain constant regardless
277
313
  * of parent count. Nested includes recurse through the registry `lookup`, so each
278
- * nested level is batched again. Columns are read with `Reflect.get` (the base row's
279
- * type is closed) and relation properties merged with `Object.assign` — no `as`.
314
+ * nested level is batched again. A load by primary key (`belongs`, a `through` target)
315
+ * reads through the table's keyed `get`; a load by foreign key reads through `records`
316
+ * with `any`. Columns are read with `resolveField` and relation properties merged with
317
+ * `Object.assign` — no `as`.
280
318
  *
281
319
  * @remarks
282
320
  * - **Observable.** The owned {@link emitter} ({@link ModelEventMap}) carries the
@@ -364,13 +402,13 @@ export declare type ModelEventMap = {
364
402
  */
365
403
  readonly load: readonly [name: string, count: number];
366
404
  /**
367
- * Fires after a junction row is inserted for a `through` relation — the owning key +
368
- * relation name.
405
+ * Fires after `link` inserts a junction row for a `through` relation — the owning key +
406
+ * relation name. A pair the junction already holds inserts nothing and fires nothing.
369
407
  */
370
408
  readonly link: readonly [key: Key, relation: string];
371
409
  /**
372
- * Fires after a junction row is removed for a `through` relation — the owning key +
373
- * relation name.
410
+ * Fires after `unlink` removes a junction row for a `through` relation — the owning key +
411
+ * relation name. A pair the junction does not hold removes nothing and fires nothing.
374
412
  */
375
413
  readonly unlink: readonly [key: Key, relation: string];
376
414
  };
@@ -389,8 +427,8 @@ export declare type ModelEventMap = {
389
427
  * Exposes a typed {@link emitter} carrying the eager-load + junction
390
428
  * moments ({@link ModelEventMap}) for fire-and-forget observers — emitting is
391
429
  * observation-only (a swallowed listener throw can never corrupt the batched load).
392
- * `link` is idempotent for sequential calls: an existing pair writes nothing and
393
- * emits nothing. `unlink` shares the atomicity of the bound storage's scope.
430
+ * `link` is one insert under the pair's derived key, and `unlink` one remove of it,
431
+ * so a pair holds at most one junction row, concurrent calls included.
394
432
  */
395
433
  export declare interface ModelInterface<T = Row> {
396
434
  readonly emitter: EmitterInterface<ModelEventMap>;
@@ -423,11 +461,13 @@ export declare interface ModelInterface<T = Row> {
423
461
  */
424
462
  find(include: Include, options?: FindOptions): Promise<ReadonlyArray<Loaded<T>>>;
425
463
  /**
426
- * Inserts a missing junction row for a `through` relation.
464
+ * Inserts the junction row for a pair through a `through` relation.
427
465
  *
428
466
  * @remarks
429
- * Idempotent for sequential calls: a pair the junction already holds writes nothing and
430
- * emits nothing. Concurrent calls for one pair may each insert.
467
+ * One insert keyed by the pair's derived key (see `computeLinkKey`) into the junction's
468
+ * primary column, which must store text. A pair the junction already holds writes
469
+ * nothing and emits nothing, so concurrent calls for one pair leave one row and one
470
+ * `link` event.
431
471
  *
432
472
  * @param key - The owning record's primary key
433
473
  * @param relation - The `through` relation's name
@@ -438,11 +478,11 @@ export declare interface ModelInterface<T = Row> {
438
478
  */
439
479
  link(key: Key, relation: string, target: Key, options?: OperationOptions): Promise<void>;
440
480
  /**
441
- * Removes every matching junction row for a `through` relation through the bound storage.
481
+ * Removes the junction row for a pair through a `through` relation.
442
482
  *
443
483
  * @remarks
444
- * Atomicity is the enclosing scope's: enclose the call in `database.transaction()` for
445
- * all-or-nothing removal; outside one, a fault leaves the removals made before it.
484
+ * One remove of the pair's derived key through the bound storage. It emits `unlink` only
485
+ * when a row was removed; a pair the junction does not hold emits nothing.
446
486
  *
447
487
  * @param key - The owning record's primary key
448
488
  * @param relation - The `through` relation's name
@@ -466,22 +506,23 @@ export declare interface ModelInterface<T = Row> {
466
506
  }
467
507
 
468
508
  /**
469
- * Reads one column off any record, whatever its declared type.
509
+ * Reads one row a storage returned, refusing a value that is not a plain record.
470
510
  *
471
511
  * @remarks
472
- * A base row's type is closed, so the column is read with `Reflect.get` rather than
473
- * index access. Anything that is not an object reads as `undefined`.
512
+ * Contract's `isRecord` decides, so a class instance, an array, or a primitive that a custom
513
+ * `DatabaseStorageInterface` returns raises rather than reading as a miss or dropping.
474
514
  *
475
- * @param record - The record to read
476
- * @param column - The column name
477
- * @returns The column's value, or `undefined` when `record` is not an object
515
+ * @param table - The table the row came from
516
+ * @param row - The row as the storage returned it
517
+ * @returns The row, narrowed to a record
518
+ * @throws An `INVALID` {@link RelationError} naming `table` when `row` is not a plain record
478
519
  *
479
520
  * @example
480
521
  * ```ts
481
- * readColumn({ accountId: 'acc1' }, 'accountId') // 'acc1'
522
+ * readRow('accounts', { id: 'acc1' }) // { id: 'acc1' }
482
523
  * ```
483
524
  */
484
- export declare function readColumn(record: unknown, column: string): unknown;
525
+ export declare function readRow<T>(table: string, row: T): T & Row;
485
526
 
486
527
  /**
487
528
  * Represents a single relation definition.
@@ -531,6 +572,47 @@ export declare interface RelationDescriptor {
531
572
  readonly model?: string;
532
573
  }
533
574
 
575
+ /**
576
+ * Holds the compiled contract of a relation descriptor, which `resolveRelation` admits through.
577
+ *
578
+ * @example
579
+ * ```ts
580
+ * import { relationDescriptorContract } from '@orkestrel/relation'
581
+ *
582
+ * relationDescriptorContract.audit({ column: 'accountId', comment: 'x' }) // [{ reason: 'extra', path: ['comment'] }]
583
+ * ```
584
+ */
585
+ export declare const relationDescriptorContract: ContractInterface<RelationDescriptor>;
586
+
587
+ /**
588
+ * Declares the object form of a relation as a closed contract shape.
589
+ *
590
+ * @remarks
591
+ * Every member is optional: `relationship` is one of the `Relationship` values, and
592
+ * `column`, `key`, `through`, `source`, `target`, `tag`, `label`, and `model` are strings.
593
+ * The object is closed, so an enumerable, string-keyed member the descriptor does not declare
594
+ * refuses it.
595
+ *
596
+ * @example
597
+ * ```ts
598
+ * import { createContract } from '@orkestrel/contract'
599
+ * import { relationDescriptorShape } from '@orkestrel/relation'
600
+ *
601
+ * createContract(relationDescriptorShape).is({ column: 'accountId', comment: 'x' }) // false
602
+ * ```
603
+ */
604
+ export declare const relationDescriptorShape: ObjectShape< {
605
+ relationship: OptionalShape<LiteralShape<readonly ["belongs", "many", "one", "through", "morph"]>>;
606
+ column: OptionalShape<StringShape>;
607
+ key: OptionalShape<StringShape>;
608
+ through: OptionalShape<StringShape>;
609
+ source: OptionalShape<StringShape>;
610
+ target: OptionalShape<StringShape>;
611
+ tag: OptionalShape<StringShape>;
612
+ label: OptionalShape<StringShape>;
613
+ model: OptionalShape<StringShape>;
614
+ }, false>;
615
+
534
616
  /**
535
617
  * Represents an error thrown by the relations layer, carrying a machine-readable
536
618
  * {@link RelationErrorCode}.
@@ -538,7 +620,9 @@ export declare interface RelationDescriptor {
538
620
  * @remarks
539
621
  * Thrown for: a relation value whose relationship cannot be inferred (`INVALID`), a
540
622
  * relation targeting a table or junction the database does not declare, raised when
541
- * the manager is created (`INVALID`), a reference to a relation a model does not
623
+ * the manager is created (`INVALID`), a junction keyed by its relation's `source` or
624
+ * `target` column (`INVALID`), a row a storage returns that is not a plain record
625
+ * (`INVALID`), a reference to a relation a model does not
542
626
  * define (`UNKNOWN_RELATION`), and `link` / `unlink` / `links` on a relation that is
543
627
  * not a `through` (`NOT_THROUGH`).
544
628
  */
@@ -552,7 +636,7 @@ export declare class RelationError extends Error {
552
636
  export declare type RelationErrorCode = 'INVALID' | 'UNKNOWN_RELATION' | 'NOT_THROUGH';
553
637
 
554
638
  /**
555
- * Resolves a {@link RelationsShape} once at construction and vends a typed
639
+ * Resolves a {@link RelationSchema} once at construction and vends a typed
556
640
  * {@link ModelInterface} per declared table.
557
641
  *
558
642
  * @remarks
@@ -598,7 +682,7 @@ export declare class RelationManager<T extends TableMap = TableMap> implements R
598
682
  * Vends a typed {@link ModelInterface} per table.
599
683
  *
600
684
  * @remarks
601
- * Built from a database and a {@link RelationsShape}; relations are resolved once
685
+ * Built from a database and a {@link RelationSchema}; relations are resolved once
602
686
  * at construction. `model(name)` returns the model for a declared table, typed by
603
687
  * that table's row. Each call constructs a model, and the returned handle owns its
604
688
  * own emitter, so retain the handle a subscription is taken on.
@@ -654,7 +738,7 @@ export declare interface RelationManagerOptions<T extends TableMap = TableMap> {
654
738
  * `table()`; an undeclared one throws `INVALID`, and every other storage error propagates unchanged.
655
739
  */
656
740
  readonly storage: DatabaseStorageInterface<T> & DatabaseStorageInterface;
657
- readonly relations?: RelationsShape<T>;
741
+ readonly relations?: RelationSchema<T>;
658
742
  readonly model?: {
659
743
  readonly on?: EmitterHooks<ModelEventMap>;
660
744
  readonly error?: EmitterErrorHandler;
@@ -664,6 +748,17 @@ export declare interface RelationManagerOptions<T extends TableMap = TableMap> {
664
748
  /** Holds a model's relations, keyed by relation name. */
665
749
  export declare type RelationMap = Readonly<Record<string, Relation>>;
666
750
 
751
+ /**
752
+ * Holds per-table relation maps — the declarative input to `createRelationManager`.
753
+ *
754
+ * @remarks
755
+ * Keys are constrained to the database's declared table names, so relations can
756
+ * only be defined for tables that exist. A table may be omitted (no relations).
757
+ */
758
+ export declare type RelationSchema<T extends TableMap = TableMap> = {
759
+ readonly [K in keyof T]?: RelationMap;
760
+ };
761
+
667
762
  /**
668
763
  * Enumerates the relationships a relation can declare.
669
764
  *
@@ -676,17 +771,6 @@ export declare type RelationMap = Readonly<Record<string, Relation>>;
676
771
  */
677
772
  export declare type Relationship = 'belongs' | 'many' | 'one' | 'through' | 'morph';
678
773
 
679
- /**
680
- * Holds per-table relation maps — the declarative input to `createRelationManager`.
681
- *
682
- * @remarks
683
- * Keys are constrained to the database's declared table names, so relations can
684
- * only be defined for tables that exist. A table may be omitted (no relations).
685
- */
686
- export declare type RelationsShape<T extends TableMap = TableMap> = {
687
- readonly [K in keyof T]?: RelationMap;
688
- };
689
-
690
774
  /**
691
775
  * Represents a `belongs` relation resolved at define-time — the foreign key sits on the owning
692
776
  * table.
@@ -768,7 +852,9 @@ export declare type ResolvedRelation = ResolvedBelongs | ResolvedMany | Resolved
768
852
  * @remarks
769
853
  * `through` is the junction table, `source` its foreign-key column pointing at the
770
854
  * owning model, and `target` its foreign-key column pointing at the related model.
771
- * These are the columns `link` / `unlink` / `links` write and read.
855
+ * These are the columns `link` / `unlink` / `links` write and read. The junction's
856
+ * primary column must store text: `link` writes the pair's derived key there, so a
857
+ * numeric primary column refuses the row with the database's `VALIDATION` error.
772
858
  */
773
859
  export declare interface ResolvedThrough {
774
860
  readonly relationship: 'through';
@@ -786,14 +872,23 @@ export declare interface ResolvedThrough {
786
872
  * A `string` is a `belongs` (foreign-key column on this table); a `readonly string[]`
787
873
  * is a `many` (foreign-key column on the related table); a {@link RelationDescriptor}
788
874
  * uses its explicit `relationship`, or infers it from the fields present. The target
789
- * model defaults to the relation name. Every column the resolved arm declares is
790
- * validated here, which is what lets each arm declare its columns required.
875
+ * model defaults to the relation name. A descriptor must pass `relationDescriptorContract`'s
876
+ * strict guard: an undeclared member, enumerable or not, a member holding another type, and
877
+ * a member present as `undefined` each refuse it, and no lossless repair admits it. The
878
+ * refusal carries the contract's audit faults, described against its schema. Every column the resolved arm declares is validated here, which is
879
+ * what lets each arm declare its columns required.
791
880
  *
792
881
  * @param name - The relation name (its key in the {@link RelationMap})
793
882
  * @param value - The raw relation value
794
883
  * @returns The resolved relation, on the arm its `relationship` names
795
- * @throws An `INVALID` {@link RelationError} when the relationship cannot be resolved, or when a
796
- * column the resolved arm declares is missing
884
+ * @throws An `INVALID` {@link RelationError} when the relationship cannot be resolved, when the
885
+ * descriptor fails its contract (the faults ride on `context.faults`), or when a column the
886
+ * resolved arm declares is missing
887
+ *
888
+ * @example
889
+ * ```ts
890
+ * resolveRelation('classification', belongsTo('classificationId', 'classifications')).relationship // 'belongs'
891
+ * ```
797
892
  */
798
893
  export declare function resolveRelation(name: string, value: Relation): ResolvedRelation;
799
894
 
@@ -805,6 +900,26 @@ export declare function resolveRelation(name: string, value: Relation): Resolved
805
900
  */
806
901
  export declare function resolveRelationMap(relations: RelationMap): ReadonlyMap<string, ResolvedRelation>;
807
902
 
903
+ /**
904
+ * Validates that a `through` relation's junction keys its rows by a column of its own.
905
+ *
906
+ * @remarks
907
+ * `link` writes the pair's `computeLinkKey` into the junction's primary column, so a junction
908
+ * whose primary column is the relation's `source` or `target` column cannot hold that key.
909
+ *
910
+ * @param model - The owning model's name
911
+ * @param resolved - The resolved `through` relation
912
+ * @param primary - The junction table's primary-key column
913
+ * @throws An `INVALID` {@link RelationError} when `primary` is the relation's `source` or
914
+ * `target` column
915
+ *
916
+ * @example
917
+ * ```ts
918
+ * validateRelationJunction('accounts', resolved, 'id') // a junction keyed by `id` passes
919
+ * ```
920
+ */
921
+ export declare function validateRelationJunction(model: string, resolved: ResolvedThrough, primary: string): void;
922
+
808
923
  /**
809
924
  * Validates a relation table through its bound storage, translating only an undeclared table.
810
925
  *