@orkestrel/relation 0.0.26 → 0.0.28

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.
@@ -21,7 +21,7 @@ import type { TableMap } from '@orkestrel/database';
21
21
  * (single).
22
22
  *
23
23
  * @param column - The foreign-key column on this table
24
- * @param model - Target table name (defaults to the relation name)
24
+ * @param table - Target table name (defaults to the relation name)
25
25
  * @returns A {@link RelationDescriptor}
26
26
  *
27
27
  * @example
@@ -29,7 +29,7 @@ import type { TableMap } from '@orkestrel/database';
29
29
  * { classification: belongsTo('classificationId', 'classifications') }
30
30
  * ```
31
31
  */
32
- export declare function belongsTo(column: string, model?: string): RelationDescriptor;
32
+ export declare function belongsTo(column: string, table?: string): RelationDescriptor;
33
33
 
34
34
  /**
35
35
  * Computes the junction row's primary key for one pair of a `through` relation.
@@ -56,7 +56,7 @@ export declare function computeLinkKey(key: Key, target: Key): string;
56
56
  * @remarks
57
57
  * An array-valued relation (`many` / `through` / `morph`) sums its lengths; a
58
58
  * single-valued one (`belongs` / `one`) counts each present row. This is the count a
59
- * `Model` carries on its `load` event.
59
+ * `Repository` carries on its `load` event.
60
60
  *
61
61
  * @param values - One relation's loaded value per record
62
62
  * @returns The total related rows attached across the set
@@ -74,7 +74,7 @@ export declare function countAttached(values: ReadonlyArray<Row | readonly Row[]
74
74
  * @remarks
75
75
  * `relations` maps table names (constrained to the database's tables) to their
76
76
  * relation maps; build entries with `belongsTo` / `hasMany` / `hasOne` /
77
- * `hasThrough` / `hasMorph`. `manager.model(name)` returns the typed model for a
77
+ * `hasThrough` / `hasMorph`. `manager.repository(name)` returns the typed repository for a
78
78
  * table — its own table is fully typed, related rows load at the `Row` type.
79
79
  *
80
80
  * At a typed root, pass the table map as the type argument. Transaction storage infers it.
@@ -107,7 +107,9 @@ export declare function countAttached(values: ReadonlyArray<Row | readonly Row[]
107
107
  * },
108
108
  * })
109
109
  *
110
- * const acme = await manager.model('accounts').load('acc1', { contacts: true, classification: true })
110
+ * const acme = await manager
111
+ * .repository('accounts')
112
+ * .load('acc1', { contacts: true, classification: true })
111
113
  * ```
112
114
  */
113
115
  export declare function createRelationManager<T extends TableMap>(options: RelationManagerOptions<T>): RelationManagerInterface<T>;
@@ -149,10 +151,10 @@ export declare function groupRows(rows: readonly Row[], column: string, values?:
149
151
  * (array).
150
152
  *
151
153
  * @param key - The foreign-key column on the related table
152
- * @param model - Target table name (defaults to the relation name)
154
+ * @param table - Target table name (defaults to the relation name)
153
155
  * @returns A {@link RelationDescriptor}
154
156
  */
155
- export declare function hasMany(key: string, model?: string): RelationDescriptor;
157
+ export declare function hasMany(key: string, table?: string): RelationDescriptor;
156
158
 
157
159
  /**
158
160
  * Builds a `morph` relation — a polymorphic foreign key plus a discriminator column on the
@@ -160,8 +162,8 @@ export declare function hasMany(key: string, model?: string): RelationDescriptor
160
162
  *
161
163
  * @param key - The foreign-key column on the related table
162
164
  * @param tag - The discriminator column on the related table
163
- * @param label - The discriminator value identifying the owning model
164
- * @param model - Target table name (defaults to the relation name)
165
+ * @param label - The discriminator value identifying the owning repository
166
+ * @param table - Target table name (defaults to the relation name)
165
167
  * @returns A {@link RelationDescriptor}
166
168
  *
167
169
  * @example
@@ -169,24 +171,24 @@ export declare function hasMany(key: string, model?: string): RelationDescriptor
169
171
  * { notes: hasMorph('entityId', 'entityType', 'account', 'notes') }
170
172
  * ```
171
173
  */
172
- export declare function hasMorph(key: string, tag: string, label: string, model?: string): RelationDescriptor;
174
+ export declare function hasMorph(key: string, tag: string, label: string, table?: string): RelationDescriptor;
173
175
 
174
176
  /**
175
177
  * Builds a `one` relation — like {@link hasMany}, but a single related row.
176
178
  *
177
179
  * @param key - The foreign-key column on the related table
178
- * @param model - Target table name (defaults to the relation name)
180
+ * @param table - Target table name (defaults to the relation name)
179
181
  * @returns A {@link RelationDescriptor}
180
182
  */
181
- export declare function hasOne(key: string, model?: string): RelationDescriptor;
183
+ export declare function hasOne(key: string, table?: string): RelationDescriptor;
182
184
 
183
185
  /**
184
186
  * Builds a `through` relation — a junction table links the two sides (many-to-many).
185
187
  *
186
188
  * @param through - The junction table name
187
- * @param source - The junction foreign-key column pointing at the owning model
188
- * @param target - The junction foreign-key column pointing at the related model
189
- * @param model - Target table name (defaults to the relation name)
189
+ * @param source - The junction foreign-key column pointing at the owning table
190
+ * @param target - The junction foreign-key column pointing at the related table
191
+ * @param table - Target table name (defaults to the relation name)
190
192
  * @returns A {@link RelationDescriptor}
191
193
  *
192
194
  * @example
@@ -194,7 +196,7 @@ export declare function hasOne(key: string, model?: string): RelationDescriptor;
194
196
  * { reps: hasThrough('accountReps', 'accountId', 'repId', 'reps') }
195
197
  * ```
196
198
  */
197
- export declare function hasThrough(through: string, source: string, target: string, model?: string): RelationDescriptor;
199
+ export declare function hasThrough(through: string, source: string, target: string, table?: string): RelationDescriptor;
198
200
 
199
201
  /**
200
202
  * Selects which relations to populate when loading — and, recursively, their own.
@@ -241,7 +243,7 @@ export declare function indexRows(rows: readonly Row[], column: string, values?:
241
243
  * @remarks
242
244
  * The guard of the compiled `relationDescriptorContract`: a plain record whose every
243
245
  * member is optional, with `relationship` one of the `Relationship` values and `column`,
244
- * `key`, `through`, `source`, `target`, `tag`, `label`, and `model` strings. A member
246
+ * `key`, `through`, `source`, `target`, `tag`, `label`, and `table` strings. A member
245
247
  * present with an `undefined` value, a member holding another type, and an enumerable,
246
248
  * string-keyed member the descriptor does not declare each refuse it. That is what lets
247
249
  * `resolveRelation` read each member after one narrow and report a malformed definition
@@ -297,214 +299,11 @@ export declare type Loaded<T> = T & Readonly<LoadedMap>;
297
299
  *
298
300
  * @remarks
299
301
  * The broad value type (`Row | readonly Row[] | undefined`) is narrowed at the use
300
- * site. This is the mutable bag a `Model` fills while populating a record set;
302
+ * site. This is the mutable bag a `Repository` fills while populating a record set;
301
303
  * `Loaded<T>` is a base row intersected with its `Readonly` form.
302
304
  */
303
305
  export declare type LoadedMap = Record<string, Row | readonly Row[] | undefined>;
304
306
 
305
- /**
306
- * Pairs a typed table with relation-aware `load` / `find` and junction management.
307
- *
308
- * @remarks
309
- * The model's own table is fully typed (`table`); related tables are reached by
310
- * runtime name through the bound storage at the broad `Row` type. Loading is batched:
311
- * a direct relation uses one query for the whole record set, while a `through`
312
- * relation uses two (junction then target); both counts remain constant regardless
313
- * of parent count. Nested includes recurse through the registry `lookup`, so each
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`.
318
- *
319
- * @remarks
320
- * - **Observable.** The owned {@link emitter} ({@link ModelEventMap}) carries the
321
- * eager-load + junction moments — `load` (a relation resolved: its name + the count of
322
- * related rows attached across the whole record set), `link` / `unlink` (a junction row
323
- * written) — for fire-and-forget observers. Every event is emitted directly, strictly
324
- * after the load resolves and after the junction operation completes; the emitter
325
- * isolates a listener throw and routes it to its `error` handler (the `error` option),
326
- * so a buggy observer can never corrupt the batched eager-load (no N+1 in the events
327
- * either — one `load` per relation, not per record).
328
- *
329
- * @example
330
- * ```ts
331
- * import { Model, resolveRelationMap, hasMany } from '@orkestrel/relation'
332
- *
333
- * const relations = { posts: hasMany('author') }
334
- * const users = new Model(
335
- * 'users',
336
- * storage.table('users'),
337
- * resolveRelationMap(relations),
338
- * relations,
339
- * () => undefined,
340
- * storage,
341
- * )
342
- * users.emitter.on('load', (name, count) => metrics.record(`relation.${name}`, count))
343
- * const ada = await users.load('u1', { posts: true })
344
- * ```
345
- */
346
- export declare class Model<T = Row> implements ModelInterface<T> {
347
- #private;
348
- /**
349
- * Constructs a model over one table and its resolved relations.
350
- *
351
- * @param name - The model's table name
352
- * @param table - The typed table this model's own reads and writes go through; take it
353
- * from `storage` so both belong to one scope, as `RelationManager` does
354
- * (a root table read inside a transaction refuses with `CONFLICT`)
355
- * @param resolved - The model's relations, resolved by `resolveRelationMap`
356
- * @param relations - The raw relation map the resolved relations came from
357
- * @param lookup - Reads a related model's {@link RelationContext} for a nested include,
358
- * and returns `undefined` for a model the registry does not hold; its contexts must
359
- * resolve through the same `storage`
360
- * @param storage - The broad storage used to read related and junction tables by name
361
- * @param on - Initial {@link ModelEventMap} listeners
362
- * @param error - Receives a listener throw as `(error, event)`. Default: the throw is
363
- * swallowed.
364
- */
365
- constructor(name: string, table: TableInterface<T>, resolved: ReadonlyMap<string, ResolvedRelation>, relations: RelationMap, lookup: (model: string) => RelationContext | undefined, storage: DatabaseStorageInterface, on?: EmitterHooks<ModelEventMap>, error?: EmitterErrorHandler);
366
- get emitter(): EmitterInterface<ModelEventMap>;
367
- get name(): string;
368
- get table(): TableInterface<T>;
369
- get relations(): RelationMap;
370
- load(key: Key, include: Include, options?: OperationOptions): Promise<Loaded<T> | undefined>;
371
- load(keys: readonly Key[], include: Include, options?: OperationOptions): Promise<ReadonlyArray<Loaded<T> | undefined>>;
372
- find(include: Include, options?: FindOptions): Promise<ReadonlyArray<Loaded<T>>>;
373
- link(key: Key, relation: string, target: Key, options?: OperationOptions): Promise<void>;
374
- unlink(key: Key, relation: string, target: Key, options?: OperationOptions): Promise<void>;
375
- links(key: Key, relation: string, options?: OperationOptions): Promise<readonly Key[]>;
376
- }
377
-
378
- /**
379
- * Declares the push observation surface of a {@link ModelInterface} — the
380
- * eager-load + junction-management moments a fire-and-forget observer (logging, metrics,
381
- * a sync layer) subscribes to.
382
- *
383
- * @remarks
384
- * `load` fires once per relation that an eager-load resolves, carrying the relation name +
385
- * the count of related rows attached for the whole record set (it is the batched load
386
- * moment, not one event per record — there is no N+1 in the events either). `link` /
387
- * `unlink` fire after the junction operation completes within the bound scope and before
388
- * any outer commit, carrying the owning key + the relation name. Listener isolation is the emitter's: every event is emitted
389
- * directly and a listener throw is routed to the emitter's `error` handler (the `error`
390
- * option), never onto this map, and sits strictly after the load resolves / the junction op
391
- * completes — so a throwing observer can never corrupt the eager-load batching or a
392
- * junction write.
393
- * `RelationManager` is event-free by design (a stateless
394
- * registry that merely vends models — it has no observable lifecycle of its own); the
395
- * per-entity {@link ModelInterface} is where loading and linking happen, so the emitter
396
- * lives there. Subscribe through `model.emitter.on(...)`.
397
- */
398
- export declare type ModelEventMap = {
399
- /**
400
- * Fires when a relation is eager-loaded — the relation name + the count of related rows
401
- * attached.
402
- */
403
- readonly load: readonly [name: string, count: number];
404
- /**
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.
407
- */
408
- readonly link: readonly [key: Key, relation: string];
409
- /**
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.
412
- */
413
- readonly unlink: readonly [key: Key, relation: string];
414
- };
415
-
416
- /**
417
- * Represents a typed table paired with relation-aware loading and junction
418
- * management.
419
- *
420
- * @remarks
421
- * Table operations are reached through `table` (a fully typed
422
- * {@link TableInterface}); relation loading and through management are on the
423
- * model itself. `load` fetches one record with its relations populated; `find`
424
- * fetches many; both batch-load (one query per direct relation or two per
425
- * `through`, regardless of result size). `link` / `unlink` / `links` manage a
426
- * `through` relation's junction rows.
427
- * Exposes a typed {@link emitter} carrying the eager-load + junction
428
- * moments ({@link ModelEventMap}) for fire-and-forget observers — emitting is
429
- * observation-only (a swallowed listener throw can never corrupt the batched load).
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.
432
- */
433
- export declare interface ModelInterface<T = Row> {
434
- readonly emitter: EmitterInterface<ModelEventMap>;
435
- readonly name: string;
436
- readonly table: TableInterface<T>;
437
- readonly relations: RelationMap;
438
- /**
439
- * Loads one record by key with the chosen relations populated, or a positional array of
440
- * records for an array of keys.
441
- *
442
- * @remarks
443
- * A key the table does not hold reads as `undefined`, and an array of keys keeps one slot
444
- * per key in the order given. Either form batches the relation queries over the whole
445
- * record set.
446
- *
447
- * @param key - The primary key to read
448
- * @param include - The relations to populate, and recursively their own
449
- * @param options - The database package's abort option
450
- * @returns The loaded record, or `undefined` when the key holds none
451
- */
452
- load(key: Key, include: Include, options?: OperationOptions): Promise<Loaded<T> | undefined>;
453
- load(keys: readonly Key[], include: Include, options?: OperationOptions): Promise<ReadonlyArray<Loaded<T> | undefined>>;
454
- /**
455
- * Finds many records, paged and sorted through {@link FindOptions}, with the chosen
456
- * relations populated.
457
- *
458
- * @param include - The relations to populate, and recursively their own
459
- * @param options - Pagination, ordering, and the abort signal
460
- * @returns The page's records, each carrying its populated relations
461
- */
462
- find(include: Include, options?: FindOptions): Promise<ReadonlyArray<Loaded<T>>>;
463
- /**
464
- * Inserts the junction row for a pair through a `through` relation.
465
- *
466
- * @remarks
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.
471
- *
472
- * @param key - The owning record's primary key
473
- * @param relation - The `through` relation's name
474
- * @param target - The related record's primary key
475
- * @param options - The database package's abort option
476
- * @throws A `NOT_THROUGH` {@link RelationError} for any other relationship, and an
477
- * `UNKNOWN_RELATION` one for a relation the model never declared
478
- */
479
- link(key: Key, relation: string, target: Key, options?: OperationOptions): Promise<void>;
480
- /**
481
- * Removes the junction row for a pair through a `through` relation.
482
- *
483
- * @remarks
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.
486
- *
487
- * @param key - The owning record's primary key
488
- * @param relation - The `through` relation's name
489
- * @param target - The related record's primary key
490
- * @param options - The database package's abort option
491
- * @throws A `NOT_THROUGH` {@link RelationError} for any other relationship, and an
492
- * `UNKNOWN_RELATION` one for a relation the model never declared
493
- */
494
- unlink(key: Key, relation: string, target: Key, options?: OperationOptions): Promise<void>;
495
- /**
496
- * Lists the related keys reachable through a `through` relation.
497
- *
498
- * @param key - The owning record's primary key
499
- * @param relation - The `through` relation's name
500
- * @param options - The database package's abort option
501
- * @returns The related keys the junction holds for that record
502
- * @throws A `NOT_THROUGH` {@link RelationError} for any other relationship, and an
503
- * `UNKNOWN_RELATION` one for a relation the model never declared
504
- */
505
- links(key: Key, relation: string, options?: OperationOptions): Promise<readonly Key[]>;
506
- }
507
-
508
307
  /**
509
308
  * Reads one row a storage returned, refusing a value that is not a plain record.
510
309
  *
@@ -535,12 +334,12 @@ export declare function readRow<T>(table: string, row: T): T & Row;
535
334
  export declare type Relation = string | readonly string[] | RelationDescriptor;
536
335
 
537
336
  /**
538
- * Holds a related model's resolved relations and primary-key column, for nested loading.
337
+ * Holds a related repository's resolved relations and primary-key column, for nested loading.
539
338
  *
540
339
  * @remarks
541
- * The lookup result the relation registry hands a {@link ModelInterface} so it can
542
- * recurse into a related model's own relations. `RelationManager` produces it (one
543
- * per declared table); `Model` consumes it as its registry lookup's return. Shared
340
+ * The lookup result the relation registry hands a {@link RepositoryInterface} so it can
341
+ * recurse into a related repository's own relations. `RelationManager` produces it (one
342
+ * per declared table); `Repository` consumes it as its registry lookup's return. Shared
544
343
  * here so the producer and consumer stay in lockstep.
545
344
  */
546
345
  export declare interface RelationContext {
@@ -557,7 +356,7 @@ export declare interface RelationContext {
557
356
  * and `one` are otherwise indistinguishable by fields alone. When `relationship`
558
357
  * is omitted (a hand-written descriptor) it is inferred from the fields present:
559
358
  * `column` → `belongs`; `through` + `source` + `target` → `through`; `key` +
560
- * `tag` + `label` → `morph`; `key` alone → `one`. `model` overrides the target
359
+ * `tag` + `label` → `morph`; `key` alone → `one`. `table` overrides the target
561
360
  * table name (it defaults to the relation name).
562
361
  */
563
362
  export declare interface RelationDescriptor {
@@ -569,7 +368,7 @@ export declare interface RelationDescriptor {
569
368
  readonly target?: string;
570
369
  readonly tag?: string;
571
370
  readonly label?: string;
572
- readonly model?: string;
371
+ readonly table?: string;
573
372
  }
574
373
 
575
374
  /**
@@ -589,7 +388,7 @@ export declare const relationDescriptorContract: ContractInterface<RelationDescr
589
388
  *
590
389
  * @remarks
591
390
  * Every member is optional: `relationship` is one of the `Relationship` values, and
592
- * `column`, `key`, `through`, `source`, `target`, `tag`, `label`, and `model` are strings.
391
+ * `column`, `key`, `through`, `source`, `target`, `tag`, `label`, and `table` are strings.
593
392
  * The object is closed, so an enumerable, string-keyed member the descriptor does not declare
594
393
  * refuses it.
595
394
  *
@@ -610,7 +409,7 @@ source: OptionalShape<StringShape>;
610
409
  target: OptionalShape<StringShape>;
611
410
  tag: OptionalShape<StringShape>;
612
411
  label: OptionalShape<StringShape>;
613
- model: OptionalShape<StringShape>;
412
+ table: OptionalShape<StringShape>;
614
413
  }, false>;
615
414
 
616
415
  /**
@@ -622,7 +421,7 @@ model: OptionalShape<StringShape>;
622
421
  * relation targeting a table or junction the database does not declare, raised when
623
422
  * the manager is created (`INVALID`), a junction keyed by its relation's `source` or
624
423
  * `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
424
+ * (`INVALID`), a reference to a relation a repository does not
626
425
  * define (`UNKNOWN_RELATION`), and `link` / `unlink` / `links` on a relation that is
627
426
  * not a `through` (`NOT_THROUGH`).
628
427
  */
@@ -637,15 +436,15 @@ export declare type RelationErrorCode = 'INVALID' | 'UNKNOWN_RELATION' | 'NOT_TH
637
436
 
638
437
  /**
639
438
  * Resolves a {@link RelationSchema} once at construction and vends a typed
640
- * {@link ModelInterface} per declared table.
439
+ * {@link RepositoryInterface} per declared table.
641
440
  *
642
441
  * @remarks
643
- * Holds storage both at its precise type (to type each model's own table)
442
+ * Holds storage both at its precise type (to type each repository's own table)
644
443
  * and at the broad `DatabaseStorageInterface` (to fetch related tables by runtime name
645
444
  * while loading). Construction validates every target and junction against the
646
445
  * database's declared tables, so invalid definitions fail before an operation runs.
647
- * The `model` option's `on` and `error` are threaded into every model vended, and
648
- * each `model(name)` call constructs a handle owning its own emitter, so retain the
446
+ * The `repository` option's `on` and `error` are threaded into every repository vended, and
447
+ * each `repository(name)` call constructs a handle owning its own emitter, so retain the
649
448
  * handle a subscription is taken on.
650
449
  *
651
450
  * @example
@@ -655,9 +454,9 @@ export declare type RelationErrorCode = 'INVALID' | 'UNKNOWN_RELATION' | 'NOT_TH
655
454
  * const manager = new RelationManager<typeof TABLES>({
656
455
  * storage: database,
657
456
  * relations: { users: { posts: hasMany('author') } },
658
- * model: { on: { load: (name, count) => metrics.record(`relation.${name}`, count) } },
457
+ * repository: { on: { load: (name, count) => metrics.record(`relation.${name}`, count) } },
659
458
  * })
660
- * const users = manager.model('users')
459
+ * const users = manager.repository('users')
661
460
  * const ada = await users.load('u1', { posts: true })
662
461
  * ```
663
462
  */
@@ -667,48 +466,48 @@ export declare class RelationManager<T extends TableMap = TableMap> implements R
667
466
  * Constructs a registry over storage and its relation definitions.
668
467
  *
669
468
  * @param options - The `storage`, an optional `relations` map, and the optional
670
- * `model` emitter settings threaded into every model vended
469
+ * `repository` emitter settings threaded into every repository vended
671
470
  * @throws An `INVALID` {@link RelationError} when a relation targets a table or a
672
471
  * junction the database does not declare
673
472
  */
674
473
  constructor(options: RelationManagerOptions<T>);
675
474
  get count(): number;
676
- model<K extends keyof T & string>(name: K): ModelInterface<RowOf<T[K]>>;
475
+ repository<K extends keyof T & string>(name: K): RepositoryInterface<RowOf<T[K]>>;
677
476
  names(): readonly string[];
678
477
  has(name: string): boolean;
679
478
  }
680
479
 
681
480
  /**
682
- * Vends a typed {@link ModelInterface} per table.
481
+ * Vends a typed {@link RepositoryInterface} per table.
683
482
  *
684
483
  * @remarks
685
484
  * Built from a database and a {@link RelationSchema}; relations are resolved once
686
- * at construction. `model(name)` returns the model for a declared table, typed by
687
- * that table's row. Each call constructs a model, and the returned handle owns its
485
+ * at construction. `repository(name)` returns the repository for a declared table, typed by
486
+ * that table's row. Each call constructs a repository, and the returned handle owns its
688
487
  * own emitter, so retain the handle a subscription is taken on.
689
488
  */
690
489
  export declare interface RelationManagerInterface<T extends TableMap = TableMap> {
691
490
  readonly count: number;
692
491
  /**
693
- * Returns the typed model for a declared table.
492
+ * Returns the typed repository for a declared table.
694
493
  *
695
494
  * @remarks
696
495
  * `name` is checked against the database's declared tables, so a typo is a compile error.
697
- * A declared table with no relation entry yields a relation-less model, still fully usable
496
+ * A declared table with no relation entry yields a relation-less repository, still fully usable
698
497
  * for typed reads and writes through `table`.
699
498
  *
700
499
  * @param name - A declared table's name
701
- * @returns A model typed by that table's row
500
+ * @returns A repository typed by that table's row
702
501
  */
703
- model<K extends keyof T & string>(name: K): ModelInterface<RowOf<T[K]>>;
502
+ repository<K extends keyof T & string>(name: K): RepositoryInterface<RowOf<T[K]>>;
704
503
  /**
705
- * Lists the names of every model carrying resolved relations.
504
+ * Lists the names of every repository carrying resolved relations.
706
505
  *
707
506
  * @returns The table names the registry resolved a relation map for
708
507
  */
709
508
  names(): readonly string[];
710
509
  /**
711
- * Reports whether a model carries resolved relations.
510
+ * Reports whether a repository carries resolved relations.
712
511
  *
713
512
  * @param name - The table name to test
714
513
  * @returns True when the registry resolved a relation map for that table; false otherwise
@@ -720,10 +519,10 @@ export declare interface RelationManagerInterface<T extends TableMap = TableMap>
720
519
  * Configures `createRelationManager`.
721
520
  *
722
521
  * @remarks
723
- * `model` carries the emitter settings the manager threads into every model it
724
- * vends: `model.on` seeds each vended handle's initial {@link ModelEventMap}
725
- * listeners, and `model.error` receives a listener throw as `(error, event)`.
726
- * Each `model(name)` call constructs a handle with its own emitter, so these
522
+ * `repository` carries the emitter settings the manager threads into every repository it
523
+ * vends: `repository.on` seeds each vended handle's initial {@link RepositoryEventMap}
524
+ * listeners, and `repository.error` receives a listener throw as `(error, event)`.
525
+ * Each `repository(name)` call constructs a handle with its own emitter, so these
727
526
  * settings apply per handle rather than once for the manager.
728
527
  */
729
528
  export declare interface RelationManagerOptions<T extends TableMap = TableMap> {
@@ -731,21 +530,21 @@ export declare interface RelationManagerOptions<T extends TableMap = TableMap> {
731
530
  * Holds the storage the registry resolves tables through: a database, or the storage a transaction scope supplies.
732
531
  *
733
532
  * @remarks
734
- * Intersected with the broad `DatabaseStorageInterface` so `model()` types each
533
+ * Intersected with the broad `DatabaseStorageInterface` so `repository()` types each
735
534
  * declared table and loaders look related tables up by runtime name. A manager over
736
- * transaction storage belongs to that callback; its models and tables throw `CONFLICT`
535
+ * transaction storage belongs to that callback; its repositories and tables throw `CONFLICT`
737
536
  * after settlement. Construction resolves every relation target and junction through
738
537
  * `table()`; an undeclared one throws `INVALID`, and every other storage error propagates unchanged.
739
538
  */
740
539
  readonly storage: DatabaseStorageInterface<T> & DatabaseStorageInterface;
741
540
  readonly relations?: RelationSchema<T>;
742
- readonly model?: {
743
- readonly on?: EmitterHooks<ModelEventMap>;
541
+ readonly repository?: {
542
+ readonly on?: EmitterHooks<RepositoryEventMap>;
744
543
  readonly error?: EmitterErrorHandler;
745
544
  };
746
545
  }
747
546
 
748
- /** Holds a model's relations, keyed by relation name. */
547
+ /** Holds a repository's relations, keyed by relation name. */
749
548
  export declare type RelationMap = Readonly<Record<string, Relation>>;
750
549
 
751
550
  /**
@@ -771,18 +570,221 @@ export declare type RelationSchema<T extends TableMap = TableMap> = {
771
570
  */
772
571
  export declare type Relationship = 'belongs' | 'many' | 'one' | 'through' | 'morph';
773
572
 
573
+ /**
574
+ * Pairs a typed table with relation-aware `load` / `find` and junction management.
575
+ *
576
+ * @remarks
577
+ * The repository's own table is fully typed (`table`); related tables are reached by
578
+ * runtime name through the bound storage at the broad `Row` type. Loading is batched:
579
+ * a direct relation uses one query for the whole record set, while a `through`
580
+ * relation uses two (junction then target); both counts remain constant regardless
581
+ * of parent count. Nested includes recurse through the registry `lookup`, so each
582
+ * nested level is batched again. A load by primary key (`belongs`, a `through` target)
583
+ * reads through the table's keyed `get`; a load by foreign key reads through `records`
584
+ * with `any`. Columns are read with `resolveField` and relation properties merged with
585
+ * `Object.assign` — no `as`.
586
+ *
587
+ * @remarks
588
+ * - **Observable.** The owned {@link emitter} ({@link RepositoryEventMap}) carries the
589
+ * eager-load + junction moments — `load` (a relation resolved: its name + the count of
590
+ * related rows attached across the whole record set), `link` / `unlink` (a junction row
591
+ * written) — for fire-and-forget observers. Every event is emitted directly, strictly
592
+ * after the load resolves and after the junction operation completes; the emitter
593
+ * isolates a listener throw and routes it to its `error` handler (the `error` option),
594
+ * so a buggy observer can never corrupt the batched eager-load (no N+1 in the events
595
+ * either — one `load` per relation, not per record).
596
+ *
597
+ * @example
598
+ * ```ts
599
+ * import { Repository, resolveRelationMap, hasMany } from '@orkestrel/relation'
600
+ *
601
+ * const relations = { posts: hasMany('author') }
602
+ * const users = new Repository(
603
+ * 'users',
604
+ * storage.table('users'),
605
+ * resolveRelationMap(relations),
606
+ * relations,
607
+ * () => undefined,
608
+ * storage,
609
+ * )
610
+ * users.emitter.on('load', (name, count) => metrics.record(`relation.${name}`, count))
611
+ * const ada = await users.load('u1', { posts: true })
612
+ * ```
613
+ */
614
+ export declare class Repository<T = Row> implements RepositoryInterface<T> {
615
+ #private;
616
+ /**
617
+ * Constructs a repository over one table and its resolved relations.
618
+ *
619
+ * @param name - The repository's table name
620
+ * @param table - The typed table this repository's own reads and writes go through; take it
621
+ * from `storage` so both belong to one scope, as `RelationManager` does
622
+ * (a root table read inside a transaction refuses with `CONFLICT`)
623
+ * @param resolved - The repository's relations, resolved by `resolveRelationMap`
624
+ * @param relations - The raw relation map the resolved relations came from
625
+ * @param lookup - Reads a related table's {@link RelationContext} for a nested include,
626
+ * and returns `undefined` for a table the registry does not hold; its contexts must
627
+ * resolve through the same `storage`
628
+ * @param storage - The broad storage used to read related and junction tables by name
629
+ * @param on - Initial {@link RepositoryEventMap} listeners
630
+ * @param error - Receives a listener throw as `(error, event)`. Default: the throw is
631
+ * swallowed.
632
+ */
633
+ constructor(name: string, table: TableInterface<T>, resolved: ReadonlyMap<string, ResolvedRelation>, relations: RelationMap, lookup: (table: string) => RelationContext | undefined, storage: DatabaseStorageInterface, on?: EmitterHooks<RepositoryEventMap>, error?: EmitterErrorHandler);
634
+ get emitter(): EmitterInterface<RepositoryEventMap>;
635
+ get name(): string;
636
+ get table(): TableInterface<T>;
637
+ get relations(): RelationMap;
638
+ load(key: Key, include: Include, options?: OperationOptions): Promise<Loaded<T> | undefined>;
639
+ load(keys: readonly Key[], include: Include, options?: OperationOptions): Promise<ReadonlyArray<Loaded<T> | undefined>>;
640
+ find(include: Include, options?: FindOptions): Promise<ReadonlyArray<Loaded<T>>>;
641
+ link(key: Key, relation: string, target: Key, options?: OperationOptions): Promise<void>;
642
+ unlink(key: Key, relation: string, target: Key, options?: OperationOptions): Promise<void>;
643
+ links(key: Key, relation: string, options?: OperationOptions): Promise<readonly Key[]>;
644
+ }
645
+
646
+ /**
647
+ * Declares the push observation surface of a {@link RepositoryInterface} — the
648
+ * eager-load + junction-management moments a fire-and-forget observer (logging, metrics,
649
+ * a sync layer) subscribes to.
650
+ *
651
+ * @remarks
652
+ * `load` fires once per relation that an eager-load resolves, carrying the relation name +
653
+ * the count of related rows attached for the whole record set (it is the batched load
654
+ * moment, not one event per record — there is no N+1 in the events either). `link` /
655
+ * `unlink` fire after the junction operation completes within the bound scope and before
656
+ * any outer commit, carrying the owning key + the relation name. Listener isolation is the emitter's: every event is emitted
657
+ * directly and a listener throw is routed to the emitter's `error` handler (the `error`
658
+ * option), never onto this map, and sits strictly after the load resolves / the junction op
659
+ * completes — so a throwing observer can never corrupt the eager-load batching or a
660
+ * junction write.
661
+ * `RelationManager` is event-free by design (a stateless
662
+ * registry that merely vends repositories — it has no observable lifecycle of its own); the
663
+ * per-entity {@link RepositoryInterface} is where loading and linking happen, so the emitter
664
+ * lives there. Subscribe through `repository.emitter.on(...)`.
665
+ */
666
+ export declare type RepositoryEventMap = {
667
+ /**
668
+ * Fires when a relation is eager-loaded — the relation name + the count of related rows
669
+ * attached.
670
+ */
671
+ readonly load: readonly [name: string, count: number];
672
+ /**
673
+ * Fires after `link` inserts a junction row for a `through` relation — the owning key +
674
+ * relation name. A pair the junction already holds inserts nothing and fires nothing.
675
+ */
676
+ readonly link: readonly [key: Key, relation: string];
677
+ /**
678
+ * Fires after `unlink` removes a junction row for a `through` relation — the owning key +
679
+ * relation name. A pair the junction does not hold removes nothing and fires nothing.
680
+ */
681
+ readonly unlink: readonly [key: Key, relation: string];
682
+ };
683
+
684
+ /**
685
+ * Represents a typed table paired with relation-aware loading and junction
686
+ * management.
687
+ *
688
+ * @remarks
689
+ * Table operations are reached through `table` (a fully typed
690
+ * {@link TableInterface}); relation loading and through management are on the
691
+ * repository itself. `load` fetches one record with its relations populated; `find`
692
+ * fetches many; both batch-load (one query per direct relation or two per
693
+ * `through`, regardless of result size). `link` / `unlink` / `links` manage a
694
+ * `through` relation's junction rows.
695
+ * Exposes a typed {@link emitter} carrying the eager-load + junction
696
+ * moments ({@link RepositoryEventMap}) for fire-and-forget observers — emitting is
697
+ * observation-only (a swallowed listener throw can never corrupt the batched load).
698
+ * `link` is one insert under the pair's derived key, and `unlink` one remove of it,
699
+ * so a pair holds at most one junction row, concurrent calls included.
700
+ */
701
+ export declare interface RepositoryInterface<T = Row> {
702
+ readonly emitter: EmitterInterface<RepositoryEventMap>;
703
+ readonly name: string;
704
+ readonly table: TableInterface<T>;
705
+ readonly relations: RelationMap;
706
+ /**
707
+ * Loads one record by key with the chosen relations populated, or a positional array of
708
+ * records for an array of keys.
709
+ *
710
+ * @remarks
711
+ * A key the table does not hold reads as `undefined`, and an array of keys keeps one slot
712
+ * per key in the order given. Either form batches the relation queries over the whole
713
+ * record set.
714
+ *
715
+ * @param key - The primary key to read
716
+ * @param include - The relations to populate, and recursively their own
717
+ * @param options - The database package's abort option
718
+ * @returns The loaded record, or `undefined` when the key holds none
719
+ */
720
+ load(key: Key, include: Include, options?: OperationOptions): Promise<Loaded<T> | undefined>;
721
+ load(keys: readonly Key[], include: Include, options?: OperationOptions): Promise<ReadonlyArray<Loaded<T> | undefined>>;
722
+ /**
723
+ * Finds many records, paged and sorted through {@link FindOptions}, with the chosen
724
+ * relations populated.
725
+ *
726
+ * @param include - The relations to populate, and recursively their own
727
+ * @param options - Pagination, ordering, and the abort signal
728
+ * @returns The page's records, each carrying its populated relations
729
+ */
730
+ find(include: Include, options?: FindOptions): Promise<ReadonlyArray<Loaded<T>>>;
731
+ /**
732
+ * Inserts the junction row for a pair through a `through` relation.
733
+ *
734
+ * @remarks
735
+ * One insert keyed by the pair's derived key (see `computeLinkKey`) into the junction's
736
+ * primary column, which must store text. A pair the junction already holds writes
737
+ * nothing and emits nothing, so concurrent calls for one pair leave one row and one
738
+ * `link` event.
739
+ *
740
+ * @param key - The owning record's primary key
741
+ * @param relation - The `through` relation's name
742
+ * @param target - The related record's primary key
743
+ * @param options - The database package's abort option
744
+ * @throws A `NOT_THROUGH` {@link RelationError} for any other relationship, and an
745
+ * `UNKNOWN_RELATION` one for a relation the repository never declared
746
+ */
747
+ link(key: Key, relation: string, target: Key, options?: OperationOptions): Promise<void>;
748
+ /**
749
+ * Removes the junction row for a pair through a `through` relation.
750
+ *
751
+ * @remarks
752
+ * One remove of the pair's derived key through the bound storage. It emits `unlink` only
753
+ * when a row was removed; a pair the junction does not hold emits nothing.
754
+ *
755
+ * @param key - The owning record's primary key
756
+ * @param relation - The `through` relation's name
757
+ * @param target - The related record's primary key
758
+ * @param options - The database package's abort option
759
+ * @throws A `NOT_THROUGH` {@link RelationError} for any other relationship, and an
760
+ * `UNKNOWN_RELATION` one for a relation the repository never declared
761
+ */
762
+ unlink(key: Key, relation: string, target: Key, options?: OperationOptions): Promise<void>;
763
+ /**
764
+ * Lists the related keys reachable through a `through` relation.
765
+ *
766
+ * @param key - The owning record's primary key
767
+ * @param relation - The `through` relation's name
768
+ * @param options - The database package's abort option
769
+ * @returns The related keys the junction holds for that record
770
+ * @throws A `NOT_THROUGH` {@link RelationError} for any other relationship, and an
771
+ * `UNKNOWN_RELATION` one for a relation the repository never declared
772
+ */
773
+ links(key: Key, relation: string, options?: OperationOptions): Promise<readonly Key[]>;
774
+ }
775
+
774
776
  /**
775
777
  * Represents a `belongs` relation resolved at define-time — the foreign key sits on the owning
776
778
  * table.
777
779
  *
778
780
  * @remarks
779
781
  * `column` is that foreign key; the related row is the one whose primary key it holds.
780
- * `name` is the relation's key in its {@link RelationMap} and `model` the target table.
782
+ * `name` is the relation's key in its {@link RelationMap} and `table` the target table.
781
783
  */
782
784
  export declare interface ResolvedBelongs {
783
785
  readonly relationship: 'belongs';
784
786
  readonly name: string;
785
- readonly model: string;
787
+ readonly table: string;
786
788
  readonly column: string;
787
789
  }
788
790
 
@@ -797,7 +799,7 @@ export declare interface ResolvedBelongs {
797
799
  export declare interface ResolvedMany {
798
800
  readonly relationship: 'many';
799
801
  readonly name: string;
800
- readonly model: string;
802
+ readonly table: string;
801
803
  readonly key: string;
802
804
  }
803
805
 
@@ -807,12 +809,12 @@ export declare interface ResolvedMany {
807
809
  *
808
810
  * @remarks
809
811
  * `key` is the foreign key on the related table, `tag` the discriminator column beside
810
- * it, and `label` the discriminator value identifying the owning model.
812
+ * it, and `label` the discriminator value identifying the owning repository.
811
813
  */
812
814
  export declare interface ResolvedMorph {
813
815
  readonly relationship: 'morph';
814
816
  readonly name: string;
815
- readonly model: string;
817
+ readonly table: string;
816
818
  readonly key: string;
817
819
  readonly tag: string;
818
820
  readonly label: string;
@@ -829,7 +831,7 @@ export declare interface ResolvedMorph {
829
831
  export declare interface ResolvedOne {
830
832
  readonly relationship: 'one';
831
833
  readonly name: string;
832
- readonly model: string;
834
+ readonly table: string;
833
835
  readonly key: string;
834
836
  }
835
837
 
@@ -851,7 +853,7 @@ export declare type ResolvedRelation = ResolvedBelongs | ResolvedMany | Resolved
851
853
  *
852
854
  * @remarks
853
855
  * `through` is the junction table, `source` its foreign-key column pointing at the
854
- * owning model, and `target` its foreign-key column pointing at the related model.
856
+ * owning table, and `target` its foreign-key column pointing at the related table.
855
857
  * These are the columns `link` / `unlink` / `links` write and read. The junction's
856
858
  * primary column must store text: `link` writes the pair's derived key there, so a
857
859
  * numeric primary column refuses the row with the database's `VALIDATION` error.
@@ -859,7 +861,7 @@ export declare type ResolvedRelation = ResolvedBelongs | ResolvedMany | Resolved
859
861
  export declare interface ResolvedThrough {
860
862
  readonly relationship: 'through';
861
863
  readonly name: string;
862
- readonly model: string;
864
+ readonly table: string;
863
865
  readonly through: string;
864
866
  readonly source: string;
865
867
  readonly target: string;
@@ -872,7 +874,7 @@ export declare interface ResolvedThrough {
872
874
  * A `string` is a `belongs` (foreign-key column on this table); a `readonly string[]`
873
875
  * is a `many` (foreign-key column on the related table); a {@link RelationDescriptor}
874
876
  * uses its explicit `relationship`, or infers it from the fields present. The target
875
- * model defaults to the relation name. A descriptor must pass `relationDescriptorContract`'s
877
+ * table defaults to the relation name. A descriptor must pass `relationDescriptorContract`'s
876
878
  * strict guard: an undeclared member, enumerable or not, a member holding another type, and
877
879
  * a member present as `undefined` each refuse it, and no lossless repair admits it. The
878
880
  * refusal carries the contract's audit faults, described against its schema. Every column the resolved arm declares is validated here, which is
@@ -907,7 +909,7 @@ export declare function resolveRelationMap(relations: RelationMap): ReadonlyMap<
907
909
  * `link` writes the pair's `computeLinkKey` into the junction's primary column, so a junction
908
910
  * whose primary column is the relation's `source` or `target` column cannot hold that key.
909
911
  *
910
- * @param model - The owning model's name
912
+ * @param repository - The owning repository's name
911
913
  * @param resolved - The resolved `through` relation
912
914
  * @param primary - The junction table's primary-key column
913
915
  * @throws An `INVALID` {@link RelationError} when `primary` is the relation's `source` or
@@ -918,13 +920,13 @@ export declare function resolveRelationMap(relations: RelationMap): ReadonlyMap<
918
920
  * validateRelationJunction('accounts', resolved, 'id') // a junction keyed by `id` passes
919
921
  * ```
920
922
  */
921
- export declare function validateRelationJunction(model: string, resolved: ResolvedThrough, primary: string): void;
923
+ export declare function validateRelationJunction(repository: string, resolved: ResolvedThrough, primary: string): void;
922
924
 
923
925
  /**
924
926
  * Validates a relation table through its bound storage, translating only an undeclared table.
925
927
  *
926
928
  * @param storage - The storage that resolves the table
927
- * @param model - The owning model's name
929
+ * @param repository - The owning repository's name
928
930
  * @param relation - The relation's name
929
931
  * @param table - The target or junction table's name
930
932
  * @param junction - If `true`, reports an undeclared junction; if `false`, reports an undeclared target. Default: `false`.
@@ -935,6 +937,6 @@ export declare function validateRelationJunction(model: string, resolved: Resolv
935
937
  * validateRelationTable(storage, 'accounts', 'contacts', 'contacts')
936
938
  * ```
937
939
  */
938
- export declare function validateRelationTable(storage: DatabaseStorageInterface, model: string, relation: string, table: string, junction?: boolean): void;
940
+ export declare function validateRelationTable(storage: DatabaseStorageInterface, repository: string, relation: string, table: string, junction?: boolean): void;
939
941
 
940
942
  export { }