@orkestrel/relation 0.0.9 → 0.0.11

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.
package/README.md CHANGED
@@ -5,7 +5,7 @@ tables — name a table's relations once, then `load` / `find` records with thei
5
5
  related rows already attached. Loading is **batched** — a direct relation uses
6
6
  one query across the whole record set, while a `through` relation uses two
7
7
  (junction then target); either count stays constant as the parent count grows.
8
- Five relation kinds
8
+ The relationships
9
9
  (`belongs` / `many` / `one` / `through` / `morph`) cover the FK shapes; nested
10
10
  includes recurse through the registry; `link` / `unlink` / `links` manage a
11
11
  many-to-many junction without hand-writing join rows. Environment-agnostic —
@@ -19,8 +19,8 @@ npm install @orkestrel/relation
19
19
 
20
20
  ## Requirements
21
21
 
22
- - Node.js >= 24
23
- - ESM-only (no CommonJS build)
22
+ - Node.js >= 22.12.0, matching the `engines` field in `package.json`
23
+ - ESM (`import`) and CommonJS (`require`) through the `exports` field
24
24
 
25
25
  ## Usage
26
26
 
@@ -4,7 +4,7 @@ let _orkestrel_database = require("@orkestrel/database");
4
4
  let _orkestrel_emitter = require("@orkestrel/emitter");
5
5
  //#region src/core/errors.ts
6
6
  /**
7
- * An error thrown by the relations layer.
7
+ * Represents an error thrown by the relations layer.
8
8
  *
9
9
  * @remarks
10
10
  * Thrown for: a relation value whose relationship cannot be inferred (`INVALID`), a
@@ -24,38 +24,71 @@ var RelationError = class extends Error {
24
24
  }
25
25
  };
26
26
  /**
27
- * Narrow an unknown caught value to a {@link RelationError}.
27
+ * Narrows an unknown caught value to a {@link RelationError}.
28
28
  *
29
29
  * @param value - The value to test (typically a `catch` binding)
30
- * @returns `true` when `value` is a {@link RelationError}
30
+ * @returns True if `value` is a {@link RelationError}; false otherwise
31
31
  */
32
32
  function isRelationError(value) {
33
33
  return value instanceof RelationError;
34
34
  }
35
35
  //#endregion
36
- //#region src/core/helpers.ts
36
+ //#region src/core/validators.ts
37
37
  /**
38
- * Narrow a value to a {@link RelationDescriptor} (the object form of a relation).
38
+ * Narrows a value to a {@link RelationDescriptor} (the object form of a relation).
39
+ *
40
+ * @remarks
41
+ * A record satisfies the descriptor when every member it declares carries its declared
42
+ * type: `relationship` is one of the `Relationship` values, and `column`, `key`,
43
+ * `through`, `source`, `target`, `tag`, `label`, and `model` are strings. A member the
44
+ * record omits is unconstrained, a member present with an `undefined` value is refused,
45
+ * and a member the descriptor does not declare is carried without being checked. This
46
+ * is what lets `resolveRelation` read each member after one narrow and report a
47
+ * malformed definition as an `INVALID` `RelationError` instead of resolving a
48
+ * wrong-typed column into an arm that declares it a string.
39
49
  *
40
50
  * @param value - The value to test
41
- * @returns `true` when `value` is a plain record
51
+ * @returns True if `value` is a record whose every declared member holds its declared
52
+ * type; false otherwise
53
+ *
54
+ * @example
55
+ * ```ts
56
+ * isRelationDescriptor(belongsTo('accountId')) // true
57
+ * isRelationDescriptor({ column: 42 }) // false — `column` is declared a string
58
+ * ```
42
59
  */
43
60
  function isRelationDescriptor(value) {
44
- return (0, _orkestrel_contract.isRecord)(value);
61
+ if (!(0, _orkestrel_contract.isRecord)(value)) return false;
62
+ if ("relationship" in value && value.relationship !== "belongs" && value.relationship !== "many" && value.relationship !== "one" && value.relationship !== "through" && value.relationship !== "morph") return false;
63
+ for (const member of [
64
+ "column",
65
+ "key",
66
+ "through",
67
+ "source",
68
+ "target",
69
+ "tag",
70
+ "label",
71
+ "model"
72
+ ]) if (member in value && !(0, _orkestrel_contract.isString)(value[member])) return false;
73
+ return true;
45
74
  }
75
+ //#endregion
76
+ //#region src/core/helpers.ts
46
77
  /**
47
- * Resolve one raw {@link Relation} value into a flat {@link ResolvedRelation}.
78
+ * Resolves one raw {@link Relation} value into a flat {@link ResolvedRelation}.
48
79
  *
49
80
  * @remarks
50
81
  * A `string` is a `belongs` (FK column on this table); a `readonly string[]` is a
51
82
  * `many` (FK column on the related table); a {@link RelationDescriptor} uses its
52
83
  * explicit `relationship`, or infers it from the fields present. The target model
53
- * defaults to the relation name. Throws `INVALID` when the relationship cannot be
54
- * resolved or a required field is missing.
84
+ * defaults to the relation name. Every column the resolved arm declares is validated
85
+ * here, which is what lets each arm declare its columns required.
55
86
  *
56
87
  * @param name - The relation name (its key in the {@link RelationMap})
57
88
  * @param value - The raw relation value
58
- * @returns The resolved relation
89
+ * @returns The resolved relation, on the arm its `relationship` names
90
+ * @throws An `INVALID` {@link RelationError} when the relationship cannot be resolved, or when a
91
+ * column the resolved arm declares is missing
59
92
  */
60
93
  function resolveRelation(name, value) {
61
94
  if ((0, _orkestrel_contract.isString)(value)) return {
@@ -141,7 +174,7 @@ function resolveRelation(name, value) {
141
174
  }
142
175
  }
143
176
  /**
144
- * Resolve every entry of a {@link RelationMap} into a name → {@link ResolvedRelation} map.
177
+ * Resolves every entry of a {@link RelationMap} into a name → {@link ResolvedRelation} map.
145
178
  *
146
179
  * @param relations - The raw relation map
147
180
  * @returns A map keyed by relation name
@@ -152,7 +185,102 @@ function resolveRelationMap(relations) {
152
185
  return resolved;
153
186
  }
154
187
  /**
155
- * Build a `belongs` relation — a foreign key on THIS table points at the related row.
188
+ * Reads one column off any record.
189
+ *
190
+ * @remarks
191
+ * A base row's type is closed, so the column is read with `Reflect.get` rather than
192
+ * index access. Anything that is not an object reads as `undefined`.
193
+ *
194
+ * @param record - The record to read
195
+ * @param column - The column name
196
+ * @returns The column's value, or `undefined` when `record` is not an object
197
+ *
198
+ * @example
199
+ * ```ts
200
+ * readColumn({ accountId: 'acc1' }, 'accountId') // 'acc1'
201
+ * ```
202
+ */
203
+ function readColumn(record, column) {
204
+ if (typeof record !== "object" || record === null) return void 0;
205
+ return Reflect.get(record, column);
206
+ }
207
+ /**
208
+ * Counts the related rows one relation attached across a record set.
209
+ *
210
+ * @remarks
211
+ * An array-valued relation (`many` / `through` / `morph`) sums its lengths; a
212
+ * single-valued one (`belongs` / `one`) counts each present row. This is the count a
213
+ * `Model` carries on its `load` event.
214
+ *
215
+ * @param values - One relation's loaded value per record
216
+ * @returns The total related rows attached across the set
217
+ *
218
+ * @example
219
+ * ```ts
220
+ * countAttached([[{ id: 'p1' }, { id: 'p2' }], undefined, { id: 'p3' }]) // 3
221
+ * ```
222
+ */
223
+ function countAttached(values) {
224
+ let total = 0;
225
+ for (const value of values) if ((0, _orkestrel_contract.isArray)(value)) total += value.length;
226
+ else if (value !== void 0) total += 1;
227
+ return total;
228
+ }
229
+ /**
230
+ * Indexes rows by the string form of one column, for keyed lookups.
231
+ *
232
+ * @remarks
233
+ * The column is read with {@link readColumn} and its value stringified, so a numeric
234
+ * and a string foreign key meet at the same entry. A later row with a key an earlier
235
+ * row already holds replaces it, and a row missing the column indexes under the string
236
+ * `'undefined'`. This is the projection a `belongs` load and a `through` load use to
237
+ * attach one related row per key.
238
+ *
239
+ * @param rows - The rows to index
240
+ * @param column - The column to key on
241
+ * @returns A read-only map from each key's string form to its row
242
+ *
243
+ * @example
244
+ * ```ts
245
+ * indexRows([{ id: 'r1' }, { id: 'r2' }], 'id').get('r1') // { id: 'r1' }
246
+ * ```
247
+ */
248
+ function indexRows(rows, column) {
249
+ const index = /* @__PURE__ */ new Map();
250
+ for (const row of rows) index.set(String(readColumn(row, column)), row);
251
+ return index;
252
+ }
253
+ /**
254
+ * Groups rows by the string form of one column, for one-to-many lookups.
255
+ *
256
+ * @remarks
257
+ * The column is read with {@link readColumn} and its value stringified, so a numeric
258
+ * and a string foreign key meet at the same group. Rows keep their input order inside
259
+ * a group, a key no row carries is absent rather than empty, and a row missing the
260
+ * column groups under the string `'undefined'`. This is the projection a `many` load
261
+ * and a `morph` load use to attach every related row per key.
262
+ *
263
+ * @param rows - The rows to group
264
+ * @param column - The column to key on
265
+ * @returns A read-only map from each key's string form to its rows, in input order
266
+ *
267
+ * @example
268
+ * ```ts
269
+ * groupRows([{ author: 'u1' }, { author: 'u1' }], 'author').get('u1')?.length // 2
270
+ * ```
271
+ */
272
+ function groupRows(rows, column) {
273
+ const groups = /* @__PURE__ */ new Map();
274
+ for (const row of rows) {
275
+ const key = String(readColumn(row, column));
276
+ const group = groups.get(key);
277
+ if (group !== void 0) group.push(row);
278
+ else groups.set(key, [row]);
279
+ }
280
+ return groups;
281
+ }
282
+ /**
283
+ * Builds a `belongs` relation — a foreign key on THIS table points at the related row.
156
284
  *
157
285
  * @param column - The FK column on this table
158
286
  * @param model - Target table name (defaults to the relation name)
@@ -171,7 +299,7 @@ function belongsTo(column, model) {
171
299
  };
172
300
  }
173
301
  /**
174
- * Build a `many` relation — a foreign key on the RELATED table points back here.
302
+ * Builds a `many` relation — a foreign key on the RELATED table points back here.
175
303
  *
176
304
  * @param key - The FK column on the related table
177
305
  * @param model - Target table name (defaults to the relation name)
@@ -185,7 +313,7 @@ function hasMany(key, model) {
185
313
  };
186
314
  }
187
315
  /**
188
- * Build a `one` relation — like {@link hasMany}, but a single related row.
316
+ * Builds a `one` relation — like {@link hasMany}, but a single related row.
189
317
  *
190
318
  * @param key - The FK column on the related table
191
319
  * @param model - Target table name (defaults to the relation name)
@@ -199,7 +327,7 @@ function hasOne(key, model) {
199
327
  };
200
328
  }
201
329
  /**
202
- * Build a `through` relation — a junction table links the two sides (many-to-many).
330
+ * Builds a `through` relation — a junction table links the two sides (many-to-many).
203
331
  *
204
332
  * @param through - The junction table name
205
333
  * @param source - The junction FK column pointing at THIS model
@@ -222,7 +350,7 @@ function hasThrough(through, source, target, model) {
222
350
  };
223
351
  }
224
352
  /**
225
- * Build a `morph` relation — a polymorphic FK plus a discriminator on the RELATED table.
353
+ * Builds a `morph` relation — a polymorphic FK plus a discriminator on the RELATED table.
226
354
  *
227
355
  * @param key - The FK column on the related table
228
356
  * @param tag - The discriminator column on the related table
@@ -247,7 +375,7 @@ function hasMorph(key, tag, label, model) {
247
375
  //#endregion
248
376
  //#region src/core/Model.ts
249
377
  /**
250
- * A model — a typed table paired with relation-aware loading.
378
+ * Pairs a typed table with relation-aware loading.
251
379
  *
252
380
  * @remarks
253
381
  * The model's own table is fully typed (`table`); related tables are reached by
@@ -259,7 +387,7 @@ function hasMorph(key, tag, label, model) {
259
387
  * type is closed) and relation properties merged with `Object.assign` — no `as`.
260
388
  *
261
389
  * @remarks
262
- * - **Observable (§13).** The owned {@link emitter} ({@link ModelEventMap}) carries the
390
+ * - **Observable.** The owned {@link emitter} ({@link ModelEventMap}) carries the
263
391
  * eager-load + junction moments — `load` (a relation resolved: its name + the count of
264
392
  * related rows attached across the whole record set), `link` / `unlink` (a junction row
265
393
  * written) — for fire-and-forget observers. Every event is emitted directly, strictly
@@ -267,6 +395,23 @@ function hasMorph(key, tag, label, model) {
267
395
  * throw and routes it to its `error` handler (the `error` option), so a buggy observer can
268
396
  * never corrupt the batched eager-load (no N+1 in the events either — one `load` per
269
397
  * relation, not per record).
398
+ *
399
+ * @example
400
+ * ```ts
401
+ * import { Model, resolveRelationMap, hasMany } from '@orkestrel/relation'
402
+ *
403
+ * const relations = { posts: hasMany('author') }
404
+ * const users = new Model(
405
+ * 'users',
406
+ * database.table('users'),
407
+ * resolveRelationMap(relations),
408
+ * relations,
409
+ * () => undefined,
410
+ * database,
411
+ * )
412
+ * users.emitter.on('load', (name, count) => metrics.record(`relation.${name}`, count))
413
+ * const ada = await users.load('u1', { posts: true })
414
+ * ```
270
415
  */
271
416
  var Model = class {
272
417
  #name;
@@ -276,6 +421,20 @@ var Model = class {
276
421
  #lookup;
277
422
  #database;
278
423
  #emitter;
424
+ /**
425
+ * Constructs a model over one table and its resolved relations.
426
+ *
427
+ * @param name - The model's table name
428
+ * @param table - The typed table this model's own reads and writes go through
429
+ * @param resolved - The model's relations, resolved by `resolveRelationMap`
430
+ * @param relations - The raw relation map the resolved relations came from
431
+ * @param lookup - Reads a related model's {@link RelationContext} for a nested include,
432
+ * and returns `undefined` for a model the registry does not hold
433
+ * @param database - The broad database used to read related and junction tables by name
434
+ * @param on - Initial {@link ModelEventMap} listeners
435
+ * @param error - Receives a listener throw as `(error, event)`. Default: the throw is
436
+ * swallowed.
437
+ */
279
438
  constructor(name, table, resolved, relations, lookup, database, on, error) {
280
439
  this.#name = name;
281
440
  this.#table = table;
@@ -330,43 +489,41 @@ var Model = class {
330
489
  async link(key, relation, target, options) {
331
490
  (0, _orkestrel_database.checkAbort)(options?.signal);
332
491
  const resolved = this.#through(relation);
333
- const source = resolved.source ?? "";
334
- const column = resolved.target ?? "";
335
- const junction = this.#database.table(resolved.through ?? "");
492
+ const junction = this.#database.table(resolved.through);
336
493
  if (await junction.count({ conditions: [{
337
- column: source,
494
+ column: resolved.source,
338
495
  operator: "equals",
339
496
  values: [key],
340
497
  connector: "and"
341
498
  }, {
342
- column,
499
+ column: resolved.target,
343
500
  operator: "equals",
344
501
  values: [target],
345
502
  connector: "and"
346
503
  }] }, options) > 0) return;
347
504
  await junction.set({
348
- [source]: key,
349
- [column]: target
505
+ [resolved.source]: key,
506
+ [resolved.target]: target
350
507
  }, options);
351
508
  this.#emitter.emit("link", key, relation);
352
509
  }
353
510
  async unlink(key, relation, target, options) {
354
511
  (0, _orkestrel_database.checkAbort)(options?.signal);
355
512
  const resolved = this.#through(relation);
356
- const junction = this.#database.table(resolved.through ?? "");
513
+ const junction = this.#database.table(resolved.through);
357
514
  const rows = await junction.records({ conditions: [{
358
- column: resolved.source ?? "",
515
+ column: resolved.source,
359
516
  operator: "equals",
360
517
  values: [key],
361
518
  connector: "and"
362
519
  }, {
363
- column: resolved.target ?? "",
520
+ column: resolved.target,
364
521
  operator: "equals",
365
522
  values: [target],
366
523
  connector: "and"
367
524
  }] }, options);
368
525
  await this.#database.transaction(async (transaction) => {
369
- const scoped = transaction.table(resolved.through ?? "");
526
+ const scoped = transaction.table(resolved.through);
370
527
  for (const row of rows) {
371
528
  const id = (0, _orkestrel_database.extractKey)(row, junction.primary);
372
529
  if (id !== void 0) await scoped.remove(id, options);
@@ -377,13 +534,13 @@ var Model = class {
377
534
  async links(key, relation, options) {
378
535
  (0, _orkestrel_database.checkAbort)(options?.signal);
379
536
  const resolved = this.#through(relation);
380
- const rows = await this.#database.table(resolved.through ?? "").records({ conditions: [{
381
- column: resolved.source ?? "",
537
+ const rows = await this.#database.table(resolved.through).records({ conditions: [{
538
+ column: resolved.source,
382
539
  operator: "equals",
383
540
  values: [key],
384
541
  connector: "and"
385
542
  }] }, options);
386
- const target = resolved.target ?? "";
543
+ const target = resolved.target;
387
544
  const keys = [];
388
545
  for (const row of rows) {
389
546
  const value = (0, _orkestrel_database.extractKey)(row, target);
@@ -391,10 +548,6 @@ var Model = class {
391
548
  }
392
549
  return keys;
393
550
  }
394
- #field(record, column) {
395
- if (typeof record !== "object" || record === null) return void 0;
396
- return Reflect.get(record, column);
397
- }
398
551
  #through(relation) {
399
552
  const resolved = this.#resolved.get(relation);
400
553
  if (resolved === void 0) throw new RelationError("UNKNOWN_RELATION", `Model '${this.#name}' has no relation '${relation}'`, {
@@ -420,16 +573,10 @@ var Model = class {
420
573
  const target = props[index];
421
574
  if (target !== void 0) target[resolved.name] = value;
422
575
  });
423
- this.#emitter.emit("load", resolved.name, this.#attached(values));
576
+ this.#emitter.emit("load", resolved.name, countAttached(values));
424
577
  }
425
578
  return props;
426
579
  }
427
- #attached(values) {
428
- let total = 0;
429
- for (const value of values) if ((0, _orkestrel_contract.isArray)(value)) total += value.length;
430
- else if (value !== void 0) total += 1;
431
- return total;
432
- }
433
580
  async #load(records, resolved, sub, primary, options) {
434
581
  switch (resolved.relationship) {
435
582
  case "belongs": return this.#loadBelongs(records, resolved, sub, options);
@@ -440,8 +587,8 @@ var Model = class {
440
587
  }
441
588
  }
442
589
  async #loadBelongs(records, resolved, sub, options) {
443
- const column = resolved.column ?? "";
444
- const keys = [...new Set(records.map((record) => this.#field(record, column)).filter(_orkestrel_contract.isDefined))];
590
+ const column = resolved.column;
591
+ const keys = [...new Set(records.map((record) => readColumn(record, column)).filter(_orkestrel_contract.isDefined))];
445
592
  if (keys.length === 0) return records.map(() => void 0);
446
593
  const related = this.#database.table(resolved.model);
447
594
  const rows = await related.records({ conditions: [{
@@ -450,15 +597,15 @@ var Model = class {
450
597
  values: keys,
451
598
  connector: "and"
452
599
  }] }, options);
453
- const index = this.#index(await this.#nest(resolved.model, rows, sub, options), related.primary);
600
+ const index = indexRows(await this.#nest(resolved.model, rows, sub, options), related.primary);
454
601
  return records.map((record) => {
455
- const fk = this.#field(record, column);
602
+ const fk = readColumn(record, column);
456
603
  return (0, _orkestrel_contract.isDefined)(fk) ? index.get(String(fk)) : void 0;
457
604
  });
458
605
  }
459
606
  async #loadMany(records, resolved, sub, primary, options) {
460
- const foreign = resolved.key ?? "";
461
- const keys = [...new Set(records.map((record) => this.#field(record, primary)).filter(_orkestrel_contract.isDefined))];
607
+ const foreign = resolved.key;
608
+ const keys = [...new Set(records.map((record) => readColumn(record, primary)).filter(_orkestrel_contract.isDefined))];
462
609
  if (keys.length === 0) return records.map(() => []);
463
610
  const rows = await this.#database.table(resolved.model).records({ conditions: [{
464
611
  column: foreign,
@@ -466,18 +613,18 @@ var Model = class {
466
613
  values: keys,
467
614
  connector: "and"
468
615
  }] }, options);
469
- const groups = this.#group(await this.#nest(resolved.model, rows, sub, options), foreign);
470
- return records.map((record) => groups.get(String(this.#field(record, primary))) ?? []);
616
+ const groups = groupRows(await this.#nest(resolved.model, rows, sub, options), foreign);
617
+ return records.map((record) => groups.get(String(readColumn(record, primary))) ?? []);
471
618
  }
472
619
  async #loadOne(records, resolved, sub, primary, options) {
473
620
  return (await this.#loadMany(records, resolved, sub, primary, options)).map((group) => group.length > 0 ? group[0] : void 0);
474
621
  }
475
622
  async #loadThrough(records, resolved, sub, primary, options) {
476
- const source = resolved.source ?? "";
477
- const target = resolved.target ?? "";
478
- const parents = [...new Set(records.map((record) => this.#field(record, primary)).filter(_orkestrel_contract.isDefined))];
623
+ const source = resolved.source;
624
+ const target = resolved.target;
625
+ const parents = [...new Set(records.map((record) => readColumn(record, primary)).filter(_orkestrel_contract.isDefined))];
479
626
  if (parents.length === 0) return records.map(() => []);
480
- const junctions = await this.#database.table(resolved.through ?? "").records({ conditions: [{
627
+ const junctions = await this.#database.table(resolved.through).records({ conditions: [{
481
628
  column: source,
482
629
  operator: "any",
483
630
  values: parents,
@@ -485,9 +632,9 @@ var Model = class {
485
632
  }] }, options);
486
633
  const targetsBySource = /* @__PURE__ */ new Map();
487
634
  for (const junction of junctions) {
488
- const value = this.#field(junction, target);
635
+ const value = readColumn(junction, target);
489
636
  if (!(0, _orkestrel_contract.isDefined)(value)) continue;
490
- const owner = String(this.#field(junction, source));
637
+ const owner = String(readColumn(junction, source));
491
638
  const list = targetsBySource.get(owner);
492
639
  if (list !== void 0) list.push(value);
493
640
  else targetsBySource.set(owner, [value]);
@@ -501,10 +648,10 @@ var Model = class {
501
648
  values: targets,
502
649
  connector: "and"
503
650
  }] }, options);
504
- const index = this.#index(await this.#nest(resolved.model, rows, sub, options), related.primary);
651
+ const index = indexRows(await this.#nest(resolved.model, rows, sub, options), related.primary);
505
652
  return records.map((record) => {
506
653
  const out = [];
507
- for (const value of targetsBySource.get(String(this.#field(record, primary))) ?? []) {
654
+ for (const value of targetsBySource.get(String(readColumn(record, primary))) ?? []) {
508
655
  const row = index.get(String(value));
509
656
  if (row !== void 0) out.push(row);
510
657
  }
@@ -512,8 +659,8 @@ var Model = class {
512
659
  });
513
660
  }
514
661
  async #loadMorph(records, resolved, sub, primary, options) {
515
- const foreign = resolved.key ?? "";
516
- const keys = [...new Set(records.map((record) => this.#field(record, primary)).filter(_orkestrel_contract.isDefined))];
662
+ const foreign = resolved.key;
663
+ const keys = [...new Set(records.map((record) => readColumn(record, primary)).filter(_orkestrel_contract.isDefined))];
517
664
  if (keys.length === 0) return records.map(() => []);
518
665
  const rows = await this.#database.table(resolved.model).records({ conditions: [{
519
666
  column: foreign,
@@ -521,13 +668,13 @@ var Model = class {
521
668
  values: keys,
522
669
  connector: "and"
523
670
  }, {
524
- column: resolved.tag ?? "",
671
+ column: resolved.tag,
525
672
  operator: "equals",
526
- values: [resolved.label ?? ""],
673
+ values: [resolved.label],
527
674
  connector: "and"
528
675
  }] }, options);
529
- const groups = this.#group(await this.#nest(resolved.model, rows, sub, options), foreign);
530
- return records.map((record) => groups.get(String(this.#field(record, primary))) ?? []);
676
+ const groups = groupRows(await this.#nest(resolved.model, rows, sub, options), foreign);
677
+ return records.map((record) => groups.get(String(readColumn(record, primary))) ?? []);
531
678
  }
532
679
  async #nest(model, rows, sub, options) {
533
680
  if (typeof sub === "boolean" || rows.length === 0) return rows;
@@ -536,43 +683,54 @@ var Model = class {
536
683
  const props = await this.#populate(rows, sub, context.resolved, context.primary, options);
537
684
  return rows.map((row, index) => Object.assign({}, row, props[index]));
538
685
  }
539
- #index(rows, column) {
540
- const map = /* @__PURE__ */ new Map();
541
- for (const row of rows) map.set(String(this.#field(row, column)), row);
542
- return map;
543
- }
544
- #group(rows, column) {
545
- const map = /* @__PURE__ */ new Map();
546
- for (const row of rows) {
547
- const key = String(this.#field(row, column));
548
- const group = map.get(key);
549
- if (group !== void 0) group.push(row);
550
- else map.set(key, [row]);
551
- }
552
- return map;
553
- }
554
686
  };
555
687
  //#endregion
556
688
  //#region src/core/RelationManager.ts
557
689
  /**
558
- * The relation registry — resolves a {@link RelationsShape} once at construction
559
- * and vends a typed {@link ModelInterface} per declared table.
690
+ * Resolves a {@link RelationsShape} once at construction and vends a typed
691
+ * {@link ModelInterface} per declared table.
560
692
  *
561
693
  * @remarks
562
694
  * Holds the database both at its precise type (to type each model's own table)
563
695
  * and at the broad `DatabaseInterface` (to fetch related tables by runtime name
564
696
  * while loading). Construction validates every target and junction against the
565
697
  * database's declared tables, so invalid definitions fail before an operation runs.
698
+ * The `model` option's `on` and `error` are threaded into every model vended, and
699
+ * each `model(name)` call constructs a handle owning its own emitter, so retain the
700
+ * handle a subscription is taken on.
701
+ *
702
+ * @example
703
+ * ```ts
704
+ * import { RelationManager, hasMany } from '@orkestrel/relation'
705
+ *
706
+ * const manager = new RelationManager({
707
+ * database,
708
+ * relations: { users: { posts: hasMany('author') } },
709
+ * model: { on: { load: (name, count) => metrics.record(`relation.${name}`, count) } },
710
+ * })
711
+ * const users = manager.model('users')
712
+ * const ada = await users.load('u1', { posts: true })
713
+ * ```
566
714
  */
567
715
  var RelationManager = class {
568
716
  #database;
569
717
  #broad;
570
718
  #relations;
719
+ #model;
571
720
  #resolved = /* @__PURE__ */ new Map();
721
+ /**
722
+ * Constructs a registry over a database and its relation definitions.
723
+ *
724
+ * @param options - The `database`, an optional `relations` map, and the optional
725
+ * `model` emitter settings threaded into every model vended
726
+ * @throws An `INVALID` {@link RelationError} when a relation targets a table or a
727
+ * junction the database does not declare
728
+ */
572
729
  constructor(options) {
573
730
  this.#database = options.database;
574
731
  this.#broad = options.database;
575
732
  this.#relations = options.relations ?? {};
733
+ this.#model = options.model;
576
734
  const declared = new Set(Object.keys(this.#broad.export()));
577
735
  for (const [name, map] of Object.entries(this.#relations)) {
578
736
  if (map === void 0) continue;
@@ -583,7 +741,7 @@ var RelationManager = class {
583
741
  relation,
584
742
  table: entry.model
585
743
  });
586
- if (entry.relationship === "through" && entry.through !== void 0 && !declared.has(entry.through)) throw new RelationError("INVALID", `Model '${name}' relation '${relation}' uses undeclared junction '${entry.through}'`, {
744
+ if (entry.relationship === "through" && !declared.has(entry.through)) throw new RelationError("INVALID", `Model '${name}' relation '${relation}' uses undeclared junction '${entry.through}'`, {
587
745
  model: name,
588
746
  relation,
589
747
  table: entry.through
@@ -600,14 +758,14 @@ var RelationManager = class {
600
758
  const relations = this.#relations[name] ?? {};
601
759
  return this.#vend(name, this.#database.table(name), resolved, relations);
602
760
  }
603
- models() {
761
+ names() {
604
762
  return [...this.#resolved.keys()];
605
763
  }
606
764
  has(name) {
607
765
  return this.#resolved.has(name);
608
766
  }
609
767
  #vend(name, table, resolved, relations) {
610
- return new Model(name, table, resolved, relations, (model) => this.#context(model), this.#broad);
768
+ return new Model(name, table, resolved, relations, (model) => this.#context(model), this.#broad, this.#model?.on, this.#model?.error);
611
769
  }
612
770
  #context(model) {
613
771
  const resolved = this.#resolved.get(model);
@@ -621,7 +779,7 @@ var RelationManager = class {
621
779
  //#endregion
622
780
  //#region src/core/factories.ts
623
781
  /**
624
- * Create a relation manager over a database and its relation definitions.
782
+ * Creates a relation manager over a database and its relation definitions.
625
783
  *
626
784
  * @remarks
627
785
  * `relations` maps table names (constrained to the database's tables) to their
@@ -654,13 +812,17 @@ exports.Model = Model;
654
812
  exports.RelationError = RelationError;
655
813
  exports.RelationManager = RelationManager;
656
814
  exports.belongsTo = belongsTo;
815
+ exports.countAttached = countAttached;
657
816
  exports.createRelationManager = createRelationManager;
817
+ exports.groupRows = groupRows;
658
818
  exports.hasMany = hasMany;
659
819
  exports.hasMorph = hasMorph;
660
820
  exports.hasOne = hasOne;
661
821
  exports.hasThrough = hasThrough;
822
+ exports.indexRows = indexRows;
662
823
  exports.isRelationDescriptor = isRelationDescriptor;
663
824
  exports.isRelationError = isRelationError;
825
+ exports.readColumn = readColumn;
664
826
  exports.resolveRelation = resolveRelation;
665
827
  exports.resolveRelationMap = resolveRelationMap;
666
828