@orkestrel/relation 0.0.10 → 0.0.12

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.
@@ -3,7 +3,8 @@ import { checkAbort, extractKey } from "@orkestrel/database";
3
3
  import { Emitter } from "@orkestrel/emitter";
4
4
  //#region src/core/errors.ts
5
5
  /**
6
- * An error thrown by the relations layer.
6
+ * Represents an error thrown by the relations layer, carrying a machine-readable
7
+ * {@link RelationErrorCode}.
7
8
  *
8
9
  * @remarks
9
10
  * Thrown for: a relation value whose relationship cannot be inferred (`INVALID`), a
@@ -23,38 +24,71 @@ var RelationError = class extends Error {
23
24
  }
24
25
  };
25
26
  /**
26
- * Narrow an unknown caught value to a {@link RelationError}.
27
+ * Narrows an unknown caught value to a {@link RelationError}.
27
28
  *
28
29
  * @param value - The value to test (typically a `catch` binding)
29
- * @returns `true` when `value` is a {@link RelationError}
30
+ * @returns True if `value` is a {@link RelationError}; false otherwise
30
31
  */
31
32
  function isRelationError(value) {
32
33
  return value instanceof RelationError;
33
34
  }
34
35
  //#endregion
35
- //#region src/core/helpers.ts
36
+ //#region src/core/validators.ts
36
37
  /**
37
- * 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.
38
49
  *
39
50
  * @param value - The value to test
40
- * @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
+ * ```
41
59
  */
42
60
  function isRelationDescriptor(value) {
43
- return isRecord(value);
61
+ if (!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 && !isString(value[member])) return false;
73
+ return true;
44
74
  }
75
+ //#endregion
76
+ //#region src/core/helpers.ts
45
77
  /**
46
- * Resolve one raw {@link Relation} value into a flat {@link ResolvedRelation}.
78
+ * Resolves one raw {@link Relation} value into a flat {@link ResolvedRelation}.
47
79
  *
48
80
  * @remarks
49
- * A `string` is a `belongs` (FK column on this table); a `readonly string[]` is a
50
- * `many` (FK column on the related table); a {@link RelationDescriptor} uses its
51
- * explicit `relationship`, or infers it from the fields present. The target model
52
- * defaults to the relation name. Throws `INVALID` when the relationship cannot be
53
- * resolved or a required field is missing.
81
+ * A `string` is a `belongs` (foreign-key column on this table); a `readonly string[]`
82
+ * is a `many` (foreign-key column on the related table); a {@link RelationDescriptor}
83
+ * uses its explicit `relationship`, or infers it from the fields present. The target
84
+ * model defaults to the relation name. Every column the resolved arm declares is
85
+ * validated here, which is what lets each arm declare its columns required.
54
86
  *
55
87
  * @param name - The relation name (its key in the {@link RelationMap})
56
88
  * @param value - The raw relation value
57
- * @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
58
92
  */
59
93
  function resolveRelation(name, value) {
60
94
  if (isString(value)) return {
@@ -140,7 +174,7 @@ function resolveRelation(name, value) {
140
174
  }
141
175
  }
142
176
  /**
143
- * 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.
144
178
  *
145
179
  * @param relations - The raw relation map
146
180
  * @returns A map keyed by relation name
@@ -151,9 +185,105 @@ function resolveRelationMap(relations) {
151
185
  return resolved;
152
186
  }
153
187
  /**
154
- * Build a `belongs` relation — a foreign key on THIS table points at the related row.
188
+ * Reads one column off any record, whatever its declared type.
155
189
  *
156
- * @param column - The FK column on this table
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 (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 the owning table points at the related row
284
+ * (single).
285
+ *
286
+ * @param column - The foreign-key column on this table
157
287
  * @param model - Target table name (defaults to the relation name)
158
288
  * @returns A {@link RelationDescriptor}
159
289
  *
@@ -170,9 +300,10 @@ function belongsTo(column, model) {
170
300
  };
171
301
  }
172
302
  /**
173
- * Build a `many` relation — a foreign key on the RELATED table points back here.
303
+ * Builds a `many` relation — a foreign key on the related table points back at the owning row
304
+ * (array).
174
305
  *
175
- * @param key - The FK column on the related table
306
+ * @param key - The foreign-key column on the related table
176
307
  * @param model - Target table name (defaults to the relation name)
177
308
  * @returns A {@link RelationDescriptor}
178
309
  */
@@ -184,9 +315,9 @@ function hasMany(key, model) {
184
315
  };
185
316
  }
186
317
  /**
187
- * Build a `one` relation — like {@link hasMany}, but a single related row.
318
+ * Builds a `one` relation — like {@link hasMany}, but a single related row.
188
319
  *
189
- * @param key - The FK column on the related table
320
+ * @param key - The foreign-key column on the related table
190
321
  * @param model - Target table name (defaults to the relation name)
191
322
  * @returns A {@link RelationDescriptor}
192
323
  */
@@ -198,11 +329,11 @@ function hasOne(key, model) {
198
329
  };
199
330
  }
200
331
  /**
201
- * Build a `through` relation — a junction table links the two sides (many-to-many).
332
+ * Builds a `through` relation — a junction table links the two sides (many-to-many).
202
333
  *
203
334
  * @param through - The junction table name
204
- * @param source - The junction FK column pointing at THIS model
205
- * @param target - The junction FK column pointing at the related model
335
+ * @param source - The junction foreign-key column pointing at the owning model
336
+ * @param target - The junction foreign-key column pointing at the related model
206
337
  * @param model - Target table name (defaults to the relation name)
207
338
  * @returns A {@link RelationDescriptor}
208
339
  *
@@ -221,11 +352,12 @@ function hasThrough(through, source, target, model) {
221
352
  };
222
353
  }
223
354
  /**
224
- * Build a `morph` relation — a polymorphic FK plus a discriminator on the RELATED table.
355
+ * Builds a `morph` relation — a polymorphic foreign key plus a discriminator column on the
356
+ * related table (array).
225
357
  *
226
- * @param key - The FK column on the related table
358
+ * @param key - The foreign-key column on the related table
227
359
  * @param tag - The discriminator column on the related table
228
- * @param label - The discriminator value identifying THIS model
360
+ * @param label - The discriminator value identifying the owning model
229
361
  * @param model - Target table name (defaults to the relation name)
230
362
  * @returns A {@link RelationDescriptor}
231
363
  *
@@ -246,7 +378,7 @@ function hasMorph(key, tag, label, model) {
246
378
  //#endregion
247
379
  //#region src/core/Model.ts
248
380
  /**
249
- * A model — a typed table paired with relation-aware loading.
381
+ * Pairs a typed table with relation-aware `load` / `find` and junction management.
250
382
  *
251
383
  * @remarks
252
384
  * The model's own table is fully typed (`table`); related tables are reached by
@@ -258,14 +390,31 @@ function hasMorph(key, tag, label, model) {
258
390
  * type is closed) and relation properties merged with `Object.assign` — no `as`.
259
391
  *
260
392
  * @remarks
261
- * - **Observable (§13).** The owned {@link emitter} ({@link ModelEventMap}) carries the
393
+ * - **Observable.** The owned {@link emitter} ({@link ModelEventMap}) carries the
262
394
  * eager-load + junction moments — `load` (a relation resolved: its name + the count of
263
395
  * related rows attached across the whole record set), `link` / `unlink` (a junction row
264
396
  * written) — for fire-and-forget observers. Every event is emitted directly, strictly
265
- * AFTER the load resolves / the junction op completes; the emitter isolates a listener
266
- * throw and routes it to its `error` handler (the `error` option), so a buggy observer can
267
- * never corrupt the batched eager-load (no N+1 in the events either — one `load` per
268
- * relation, not per record).
397
+ * after the load resolves and after the junction operation completes; the emitter
398
+ * isolates a listener throw and routes it to its `error` handler (the `error` option),
399
+ * so a buggy observer can never corrupt the batched eager-load (no N+1 in the events
400
+ * either — one `load` per relation, not per record).
401
+ *
402
+ * @example
403
+ * ```ts
404
+ * import { Model, resolveRelationMap, hasMany } from '@orkestrel/relation'
405
+ *
406
+ * const relations = { posts: hasMany('author') }
407
+ * const users = new Model(
408
+ * 'users',
409
+ * database.table('users'),
410
+ * resolveRelationMap(relations),
411
+ * relations,
412
+ * () => undefined,
413
+ * database,
414
+ * )
415
+ * users.emitter.on('load', (name, count) => metrics.record(`relation.${name}`, count))
416
+ * const ada = await users.load('u1', { posts: true })
417
+ * ```
269
418
  */
270
419
  var Model = class {
271
420
  #name;
@@ -275,6 +424,20 @@ var Model = class {
275
424
  #lookup;
276
425
  #database;
277
426
  #emitter;
427
+ /**
428
+ * Constructs a model over one table and its resolved relations.
429
+ *
430
+ * @param name - The model's table name
431
+ * @param table - The typed table this model's own reads and writes go through
432
+ * @param resolved - The model's relations, resolved by `resolveRelationMap`
433
+ * @param relations - The raw relation map the resolved relations came from
434
+ * @param lookup - Reads a related model's {@link RelationContext} for a nested include,
435
+ * and returns `undefined` for a model the registry does not hold
436
+ * @param database - The broad database used to read related and junction tables by name
437
+ * @param on - Initial {@link ModelEventMap} listeners
438
+ * @param error - Receives a listener throw as `(error, event)`. Default: the throw is
439
+ * swallowed.
440
+ */
278
441
  constructor(name, table, resolved, relations, lookup, database, on, error) {
279
442
  this.#name = name;
280
443
  this.#table = table;
@@ -329,43 +492,41 @@ var Model = class {
329
492
  async link(key, relation, target, options) {
330
493
  checkAbort(options?.signal);
331
494
  const resolved = this.#through(relation);
332
- const source = resolved.source ?? "";
333
- const column = resolved.target ?? "";
334
- const junction = this.#database.table(resolved.through ?? "");
495
+ const junction = this.#database.table(resolved.through);
335
496
  if (await junction.count({ conditions: [{
336
- column: source,
497
+ column: resolved.source,
337
498
  operator: "equals",
338
499
  values: [key],
339
500
  connector: "and"
340
501
  }, {
341
- column,
502
+ column: resolved.target,
342
503
  operator: "equals",
343
504
  values: [target],
344
505
  connector: "and"
345
506
  }] }, options) > 0) return;
346
507
  await junction.set({
347
- [source]: key,
348
- [column]: target
508
+ [resolved.source]: key,
509
+ [resolved.target]: target
349
510
  }, options);
350
511
  this.#emitter.emit("link", key, relation);
351
512
  }
352
513
  async unlink(key, relation, target, options) {
353
514
  checkAbort(options?.signal);
354
515
  const resolved = this.#through(relation);
355
- const junction = this.#database.table(resolved.through ?? "");
516
+ const junction = this.#database.table(resolved.through);
356
517
  const rows = await junction.records({ conditions: [{
357
- column: resolved.source ?? "",
518
+ column: resolved.source,
358
519
  operator: "equals",
359
520
  values: [key],
360
521
  connector: "and"
361
522
  }, {
362
- column: resolved.target ?? "",
523
+ column: resolved.target,
363
524
  operator: "equals",
364
525
  values: [target],
365
526
  connector: "and"
366
527
  }] }, options);
367
528
  await this.#database.transaction(async (transaction) => {
368
- const scoped = transaction.table(resolved.through ?? "");
529
+ const scoped = transaction.table(resolved.through);
369
530
  for (const row of rows) {
370
531
  const id = extractKey(row, junction.primary);
371
532
  if (id !== void 0) await scoped.remove(id, options);
@@ -376,13 +537,13 @@ var Model = class {
376
537
  async links(key, relation, options) {
377
538
  checkAbort(options?.signal);
378
539
  const resolved = this.#through(relation);
379
- const rows = await this.#database.table(resolved.through ?? "").records({ conditions: [{
380
- column: resolved.source ?? "",
540
+ const rows = await this.#database.table(resolved.through).records({ conditions: [{
541
+ column: resolved.source,
381
542
  operator: "equals",
382
543
  values: [key],
383
544
  connector: "and"
384
545
  }] }, options);
385
- const target = resolved.target ?? "";
546
+ const target = resolved.target;
386
547
  const keys = [];
387
548
  for (const row of rows) {
388
549
  const value = extractKey(row, target);
@@ -390,10 +551,6 @@ var Model = class {
390
551
  }
391
552
  return keys;
392
553
  }
393
- #field(record, column) {
394
- if (typeof record !== "object" || record === null) return void 0;
395
- return Reflect.get(record, column);
396
- }
397
554
  #through(relation) {
398
555
  const resolved = this.#resolved.get(relation);
399
556
  if (resolved === void 0) throw new RelationError("UNKNOWN_RELATION", `Model '${this.#name}' has no relation '${relation}'`, {
@@ -419,16 +576,10 @@ var Model = class {
419
576
  const target = props[index];
420
577
  if (target !== void 0) target[resolved.name] = value;
421
578
  });
422
- this.#emitter.emit("load", resolved.name, this.#attached(values));
579
+ this.#emitter.emit("load", resolved.name, countAttached(values));
423
580
  }
424
581
  return props;
425
582
  }
426
- #attached(values) {
427
- let total = 0;
428
- for (const value of values) if (isArray(value)) total += value.length;
429
- else if (value !== void 0) total += 1;
430
- return total;
431
- }
432
583
  async #load(records, resolved, sub, primary, options) {
433
584
  switch (resolved.relationship) {
434
585
  case "belongs": return this.#loadBelongs(records, resolved, sub, options);
@@ -439,8 +590,8 @@ var Model = class {
439
590
  }
440
591
  }
441
592
  async #loadBelongs(records, resolved, sub, options) {
442
- const column = resolved.column ?? "";
443
- const keys = [...new Set(records.map((record) => this.#field(record, column)).filter(isDefined))];
593
+ const column = resolved.column;
594
+ const keys = [...new Set(records.map((record) => readColumn(record, column)).filter(isDefined))];
444
595
  if (keys.length === 0) return records.map(() => void 0);
445
596
  const related = this.#database.table(resolved.model);
446
597
  const rows = await related.records({ conditions: [{
@@ -449,15 +600,15 @@ var Model = class {
449
600
  values: keys,
450
601
  connector: "and"
451
602
  }] }, options);
452
- const index = this.#index(await this.#nest(resolved.model, rows, sub, options), related.primary);
603
+ const index = indexRows(await this.#nest(resolved.model, rows, sub, options), related.primary);
453
604
  return records.map((record) => {
454
- const fk = this.#field(record, column);
605
+ const fk = readColumn(record, column);
455
606
  return isDefined(fk) ? index.get(String(fk)) : void 0;
456
607
  });
457
608
  }
458
609
  async #loadMany(records, resolved, sub, primary, options) {
459
- const foreign = resolved.key ?? "";
460
- const keys = [...new Set(records.map((record) => this.#field(record, primary)).filter(isDefined))];
610
+ const foreign = resolved.key;
611
+ const keys = [...new Set(records.map((record) => readColumn(record, primary)).filter(isDefined))];
461
612
  if (keys.length === 0) return records.map(() => []);
462
613
  const rows = await this.#database.table(resolved.model).records({ conditions: [{
463
614
  column: foreign,
@@ -465,18 +616,18 @@ var Model = class {
465
616
  values: keys,
466
617
  connector: "and"
467
618
  }] }, options);
468
- const groups = this.#group(await this.#nest(resolved.model, rows, sub, options), foreign);
469
- return records.map((record) => groups.get(String(this.#field(record, primary))) ?? []);
619
+ const groups = groupRows(await this.#nest(resolved.model, rows, sub, options), foreign);
620
+ return records.map((record) => groups.get(String(readColumn(record, primary))) ?? []);
470
621
  }
471
622
  async #loadOne(records, resolved, sub, primary, options) {
472
623
  return (await this.#loadMany(records, resolved, sub, primary, options)).map((group) => group.length > 0 ? group[0] : void 0);
473
624
  }
474
625
  async #loadThrough(records, resolved, sub, primary, options) {
475
- const source = resolved.source ?? "";
476
- const target = resolved.target ?? "";
477
- const parents = [...new Set(records.map((record) => this.#field(record, primary)).filter(isDefined))];
626
+ const source = resolved.source;
627
+ const target = resolved.target;
628
+ const parents = [...new Set(records.map((record) => readColumn(record, primary)).filter(isDefined))];
478
629
  if (parents.length === 0) return records.map(() => []);
479
- const junctions = await this.#database.table(resolved.through ?? "").records({ conditions: [{
630
+ const junctions = await this.#database.table(resolved.through).records({ conditions: [{
480
631
  column: source,
481
632
  operator: "any",
482
633
  values: parents,
@@ -484,9 +635,9 @@ var Model = class {
484
635
  }] }, options);
485
636
  const targetsBySource = /* @__PURE__ */ new Map();
486
637
  for (const junction of junctions) {
487
- const value = this.#field(junction, target);
638
+ const value = readColumn(junction, target);
488
639
  if (!isDefined(value)) continue;
489
- const owner = String(this.#field(junction, source));
640
+ const owner = String(readColumn(junction, source));
490
641
  const list = targetsBySource.get(owner);
491
642
  if (list !== void 0) list.push(value);
492
643
  else targetsBySource.set(owner, [value]);
@@ -500,10 +651,10 @@ var Model = class {
500
651
  values: targets,
501
652
  connector: "and"
502
653
  }] }, options);
503
- const index = this.#index(await this.#nest(resolved.model, rows, sub, options), related.primary);
654
+ const index = indexRows(await this.#nest(resolved.model, rows, sub, options), related.primary);
504
655
  return records.map((record) => {
505
656
  const out = [];
506
- for (const value of targetsBySource.get(String(this.#field(record, primary))) ?? []) {
657
+ for (const value of targetsBySource.get(String(readColumn(record, primary))) ?? []) {
507
658
  const row = index.get(String(value));
508
659
  if (row !== void 0) out.push(row);
509
660
  }
@@ -511,8 +662,8 @@ var Model = class {
511
662
  });
512
663
  }
513
664
  async #loadMorph(records, resolved, sub, primary, options) {
514
- const foreign = resolved.key ?? "";
515
- const keys = [...new Set(records.map((record) => this.#field(record, primary)).filter(isDefined))];
665
+ const foreign = resolved.key;
666
+ const keys = [...new Set(records.map((record) => readColumn(record, primary)).filter(isDefined))];
516
667
  if (keys.length === 0) return records.map(() => []);
517
668
  const rows = await this.#database.table(resolved.model).records({ conditions: [{
518
669
  column: foreign,
@@ -520,13 +671,13 @@ var Model = class {
520
671
  values: keys,
521
672
  connector: "and"
522
673
  }, {
523
- column: resolved.tag ?? "",
674
+ column: resolved.tag,
524
675
  operator: "equals",
525
- values: [resolved.label ?? ""],
676
+ values: [resolved.label],
526
677
  connector: "and"
527
678
  }] }, options);
528
- const groups = this.#group(await this.#nest(resolved.model, rows, sub, options), foreign);
529
- return records.map((record) => groups.get(String(this.#field(record, primary))) ?? []);
679
+ const groups = groupRows(await this.#nest(resolved.model, rows, sub, options), foreign);
680
+ return records.map((record) => groups.get(String(readColumn(record, primary))) ?? []);
530
681
  }
531
682
  async #nest(model, rows, sub, options) {
532
683
  if (typeof sub === "boolean" || rows.length === 0) return rows;
@@ -535,43 +686,54 @@ var Model = class {
535
686
  const props = await this.#populate(rows, sub, context.resolved, context.primary, options);
536
687
  return rows.map((row, index) => Object.assign({}, row, props[index]));
537
688
  }
538
- #index(rows, column) {
539
- const map = /* @__PURE__ */ new Map();
540
- for (const row of rows) map.set(String(this.#field(row, column)), row);
541
- return map;
542
- }
543
- #group(rows, column) {
544
- const map = /* @__PURE__ */ new Map();
545
- for (const row of rows) {
546
- const key = String(this.#field(row, column));
547
- const group = map.get(key);
548
- if (group !== void 0) group.push(row);
549
- else map.set(key, [row]);
550
- }
551
- return map;
552
- }
553
689
  };
554
690
  //#endregion
555
691
  //#region src/core/RelationManager.ts
556
692
  /**
557
- * The relation registry — resolves a {@link RelationsShape} once at construction
558
- * and vends a typed {@link ModelInterface} per declared table.
693
+ * Resolves a {@link RelationsShape} once at construction and vends a typed
694
+ * {@link ModelInterface} per declared table.
559
695
  *
560
696
  * @remarks
561
697
  * Holds the database both at its precise type (to type each model's own table)
562
698
  * and at the broad `DatabaseInterface` (to fetch related tables by runtime name
563
699
  * while loading). Construction validates every target and junction against the
564
700
  * database's declared tables, so invalid definitions fail before an operation runs.
701
+ * The `model` option's `on` and `error` are threaded into every model vended, and
702
+ * each `model(name)` call constructs a handle owning its own emitter, so retain the
703
+ * handle a subscription is taken on.
704
+ *
705
+ * @example
706
+ * ```ts
707
+ * import { RelationManager, hasMany } from '@orkestrel/relation'
708
+ *
709
+ * const manager = new RelationManager({
710
+ * database,
711
+ * relations: { users: { posts: hasMany('author') } },
712
+ * model: { on: { load: (name, count) => metrics.record(`relation.${name}`, count) } },
713
+ * })
714
+ * const users = manager.model('users')
715
+ * const ada = await users.load('u1', { posts: true })
716
+ * ```
565
717
  */
566
718
  var RelationManager = class {
567
719
  #database;
568
720
  #broad;
569
721
  #relations;
722
+ #model;
570
723
  #resolved = /* @__PURE__ */ new Map();
724
+ /**
725
+ * Constructs a registry over a database and its relation definitions.
726
+ *
727
+ * @param options - The `database`, an optional `relations` map, and the optional
728
+ * `model` emitter settings threaded into every model vended
729
+ * @throws An `INVALID` {@link RelationError} when a relation targets a table or a
730
+ * junction the database does not declare
731
+ */
571
732
  constructor(options) {
572
733
  this.#database = options.database;
573
734
  this.#broad = options.database;
574
735
  this.#relations = options.relations ?? {};
736
+ this.#model = options.model;
575
737
  const declared = new Set(Object.keys(this.#broad.export()));
576
738
  for (const [name, map] of Object.entries(this.#relations)) {
577
739
  if (map === void 0) continue;
@@ -582,7 +744,7 @@ var RelationManager = class {
582
744
  relation,
583
745
  table: entry.model
584
746
  });
585
- 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}'`, {
747
+ if (entry.relationship === "through" && !declared.has(entry.through)) throw new RelationError("INVALID", `Model '${name}' relation '${relation}' uses undeclared junction '${entry.through}'`, {
586
748
  model: name,
587
749
  relation,
588
750
  table: entry.through
@@ -599,14 +761,14 @@ var RelationManager = class {
599
761
  const relations = this.#relations[name] ?? {};
600
762
  return this.#vend(name, this.#database.table(name), resolved, relations);
601
763
  }
602
- models() {
764
+ names() {
603
765
  return [...this.#resolved.keys()];
604
766
  }
605
767
  has(name) {
606
768
  return this.#resolved.has(name);
607
769
  }
608
770
  #vend(name, table, resolved, relations) {
609
- return new Model(name, table, resolved, relations, (model) => this.#context(model), this.#broad);
771
+ return new Model(name, table, resolved, relations, (model) => this.#context(model), this.#broad, this.#model?.on, this.#model?.error);
610
772
  }
611
773
  #context(model) {
612
774
  const resolved = this.#resolved.get(model);
@@ -620,7 +782,7 @@ var RelationManager = class {
620
782
  //#endregion
621
783
  //#region src/core/factories.ts
622
784
  /**
623
- * Create a relation manager over a database and its relation definitions.
785
+ * Creates a {@link RelationManagerInterface} over a database and its relation map.
624
786
  *
625
787
  * @remarks
626
788
  * `relations` maps table names (constrained to the database's tables) to their
@@ -631,17 +793,31 @@ var RelationManager = class {
631
793
  * @param options - The `database` and an optional `relations` map
632
794
  * @returns A typed {@link RelationManagerInterface}
633
795
  *
634
- * @example
796
+ * @example Defining relations
635
797
  * ```ts
636
- * import { createRelationManager, belongsTo, hasMany } from '@src/core'
798
+ * import {
799
+ * createRelationManager,
800
+ * belongsTo,
801
+ * hasMany,
802
+ * hasOne,
803
+ * hasThrough,
804
+ * hasMorph,
805
+ * } from '@orkestrel/relation'
637
806
  *
638
807
  * const manager = createRelationManager({
639
808
  * database: db,
640
809
  * relations: {
641
- * accounts: { classification: belongsTo('classificationId', 'classifications'), contacts: hasMany('accountId') },
810
+ * accounts: {
811
+ * classification: belongsTo('classificationId', 'classifications'), // foreign key on accounts
812
+ * contacts: hasMany('accountId'), // foreign key on contacts → accounts
813
+ * profile: hasOne('accountId', 'profiles'), // single, foreign key on profiles
814
+ * representatives: hasThrough('accountReps', 'accountId', 'repId', 'representatives'), // through a junction
815
+ * notes: hasMorph('entityId', 'entityType', 'account', 'notes'), // polymorphic
816
+ * },
642
817
  * contacts: { account: belongsTo('accountId', 'accounts') },
643
818
  * },
644
819
  * })
820
+ *
645
821
  * const acme = await manager.model('accounts').load('acc1', { contacts: true, classification: true })
646
822
  * ```
647
823
  */
@@ -649,6 +825,6 @@ function createRelationManager(options) {
649
825
  return new RelationManager(options);
650
826
  }
651
827
  //#endregion
652
- export { Model, RelationError, RelationManager, belongsTo, createRelationManager, hasMany, hasMorph, hasOne, hasThrough, isRelationDescriptor, isRelationError, resolveRelation, resolveRelationMap };
828
+ export { Model, RelationError, RelationManager, belongsTo, countAttached, createRelationManager, groupRows, hasMany, hasMorph, hasOne, hasThrough, indexRows, isRelationDescriptor, isRelationError, readColumn, resolveRelation, resolveRelationMap };
653
829
 
654
830
  //# sourceMappingURL=index.js.map