@orkestrel/relation 0.0.15 → 0.0.17
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/dist/src/core/index.cjs +23 -34
- package/dist/src/core/index.cjs.map +1 -1
- package/dist/src/core/index.d.cts +1 -1
- package/dist/src/core/index.d.ts +1 -1
- package/dist/src/core/index.js +24 -35
- package/dist/src/core/index.js.map +1 -1
- package/package.json +16 -16
package/dist/src/core/index.cjs
CHANGED
|
@@ -2,7 +2,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
|
2
2
|
let _orkestrel_contract = require("@orkestrel/contract");
|
|
3
3
|
let _orkestrel_database = require("@orkestrel/database");
|
|
4
4
|
let _orkestrel_emitter = require("@orkestrel/emitter");
|
|
5
|
-
|
|
5
|
+
// src/core/errors.ts
|
|
6
6
|
/**
|
|
7
7
|
* Represents an error thrown by the relations layer, carrying a machine-readable
|
|
8
8
|
* {@link RelationErrorCode}.
|
|
@@ -19,6 +19,7 @@ var RelationError = class extends Error {
|
|
|
19
19
|
context;
|
|
20
20
|
constructor(code, message, context) {
|
|
21
21
|
super(message);
|
|
22
|
+
_orkestrel_contract.INTRINSICS.define(this, Symbol.for("@orkestrel/relation.RelationError"), { value: this });
|
|
22
23
|
this.name = "RelationError";
|
|
23
24
|
this.code = code;
|
|
24
25
|
if (context !== void 0) this.context = context;
|
|
@@ -28,13 +29,19 @@ var RelationError = class extends Error {
|
|
|
28
29
|
* Narrows an unknown caught value to a {@link RelationError}.
|
|
29
30
|
*
|
|
30
31
|
* @param value - The value to test (typically a `catch` binding)
|
|
31
|
-
* @returns True if
|
|
32
|
+
* @returns True if the error carries its own identity brand and declared members; false otherwise
|
|
32
33
|
*/
|
|
33
34
|
function isRelationError(value) {
|
|
34
|
-
return (0, _orkestrel_contract.
|
|
35
|
+
return (0, _orkestrel_contract.holds)(() => {
|
|
36
|
+
if (!(value instanceof Error) || _orkestrel_contract.INTRINSICS.prototype(value) === Error.prototype) return false;
|
|
37
|
+
if (_orkestrel_contract.INTRINSICS.describe(value, Symbol.for("@orkestrel/relation.RelationError"))?.value !== value) return false;
|
|
38
|
+
const code = _orkestrel_contract.INTRINSICS.reflect.read(value, "code");
|
|
39
|
+
if (code !== "INVALID" && code !== "UNKNOWN_RELATION" && code !== "NOT_THROUGH") return false;
|
|
40
|
+
const context = _orkestrel_contract.INTRINSICS.reflect.read(value, "context");
|
|
41
|
+
return context === void 0 || (0, _orkestrel_contract.isObject)(context) || (0, _orkestrel_contract.isFunction)(context);
|
|
42
|
+
});
|
|
35
43
|
}
|
|
36
|
-
|
|
37
|
-
//#region src/core/validators.ts
|
|
44
|
+
// src/core/validators.ts
|
|
38
45
|
/**
|
|
39
46
|
* Narrows a value to a {@link RelationDescriptor} (the object form of a relation).
|
|
40
47
|
*
|
|
@@ -73,8 +80,7 @@ function isRelationDescriptor(value) {
|
|
|
73
80
|
]) if (member in value && !(0, _orkestrel_contract.isString)(value[member])) return false;
|
|
74
81
|
return true;
|
|
75
82
|
}
|
|
76
|
-
|
|
77
|
-
//#region src/core/helpers.ts
|
|
83
|
+
// src/core/helpers.ts
|
|
78
84
|
/**
|
|
79
85
|
* Resolves one raw {@link Relation} value into a flat {@link ResolvedRelation}.
|
|
80
86
|
*
|
|
@@ -110,13 +116,8 @@ function resolveRelation(name, value) {
|
|
|
110
116
|
}
|
|
111
117
|
if (!isRelationDescriptor(value)) throw new RelationError("INVALID", `Relation '${name}': not a string, array, or descriptor`, { relation: name });
|
|
112
118
|
const model = value.model ?? name;
|
|
113
|
-
|
|
114
|
-
if (
|
|
115
|
-
else if ((0, _orkestrel_contract.isDefined)(value.through)) relationship = "through";
|
|
116
|
-
else if ((0, _orkestrel_contract.isDefined)(value.tag)) relationship = "morph";
|
|
117
|
-
else if ((0, _orkestrel_contract.isDefined)(value.column)) relationship = "belongs";
|
|
118
|
-
else if ((0, _orkestrel_contract.isDefined)(value.key)) relationship = "one";
|
|
119
|
-
else throw new RelationError("INVALID", `Relation '${name}': cannot infer relationship from descriptor`, { relation: name });
|
|
119
|
+
const relationship = value.relationship !== void 0 ? value.relationship : (0, _orkestrel_contract.isDefined)(value.through) ? "through" : (0, _orkestrel_contract.isDefined)(value.tag) ? "morph" : (0, _orkestrel_contract.isDefined)(value.column) ? "belongs" : (0, _orkestrel_contract.isDefined)(value.key) ? "one" : void 0;
|
|
120
|
+
if (relationship === void 0) throw new RelationError("INVALID", `Relation '${name}': cannot infer relationship from descriptor`, { relation: name });
|
|
120
121
|
switch (relationship) {
|
|
121
122
|
case "belongs": {
|
|
122
123
|
const column = value.column;
|
|
@@ -181,9 +182,7 @@ function resolveRelation(name, value) {
|
|
|
181
182
|
* @returns A map keyed by relation name
|
|
182
183
|
*/
|
|
183
184
|
function resolveRelationMap(relations) {
|
|
184
|
-
|
|
185
|
-
for (const [name, value] of Object.entries(relations)) resolved.set(name, resolveRelation(name, value));
|
|
186
|
-
return resolved;
|
|
185
|
+
return new Map(Object.entries(relations).map(([name, value]) => [name, resolveRelation(name, value)]));
|
|
187
186
|
}
|
|
188
187
|
/**
|
|
189
188
|
* Reads one column off any record, whatever its declared type.
|
|
@@ -222,10 +221,7 @@ function readColumn(record, column) {
|
|
|
222
221
|
* ```
|
|
223
222
|
*/
|
|
224
223
|
function countAttached(values) {
|
|
225
|
-
|
|
226
|
-
for (const value of values) if ((0, _orkestrel_contract.isArray)(value)) total += value.length;
|
|
227
|
-
else if (value !== void 0) total += 1;
|
|
228
|
-
return total;
|
|
224
|
+
return Iterator.from(values).reduce((total, value) => total + ((0, _orkestrel_contract.isArray)(value) ? value.length : value === void 0 ? 0 : 1), 0);
|
|
229
225
|
}
|
|
230
226
|
/**
|
|
231
227
|
* Indexes rows by the string form of one column, for keyed lookups.
|
|
@@ -247,9 +243,7 @@ function countAttached(values) {
|
|
|
247
243
|
* ```
|
|
248
244
|
*/
|
|
249
245
|
function indexRows(rows, column) {
|
|
250
|
-
|
|
251
|
-
for (const row of rows) index.set(String(readColumn(row, column)), row);
|
|
252
|
-
return index;
|
|
246
|
+
return new Map(Iterator.from(rows).map((row) => [String(readColumn(row, column)), row]));
|
|
253
247
|
}
|
|
254
248
|
/**
|
|
255
249
|
* Groups rows by the string form of one column, for one-to-many lookups.
|
|
@@ -376,8 +370,7 @@ function hasMorph(key, tag, label, model) {
|
|
|
376
370
|
...model !== void 0 ? { model } : {}
|
|
377
371
|
};
|
|
378
372
|
}
|
|
379
|
-
|
|
380
|
-
//#region src/core/Model.ts
|
|
373
|
+
// src/core/Model.ts
|
|
381
374
|
/**
|
|
382
375
|
* Pairs a typed table with relation-aware `load` / `find` and junction management.
|
|
383
376
|
*
|
|
@@ -468,9 +461,8 @@ var Model = class {
|
|
|
468
461
|
if ((0, _orkestrel_contract.isArray)(keys)) {
|
|
469
462
|
const bases = await this.#table.get(keys);
|
|
470
463
|
const present = bases.filter(_orkestrel_contract.isDefined);
|
|
471
|
-
const
|
|
472
|
-
|
|
473
|
-
return bases.map((base) => base === void 0 ? void 0 : Object.assign({}, base, props[next++]));
|
|
464
|
+
const attachments = (await this.#populate(present, include, this.#resolved, this.#table.primary, options)).values();
|
|
465
|
+
return bases.map((base) => base === void 0 ? void 0 : Object.assign({}, base, attachments.next().value));
|
|
474
466
|
}
|
|
475
467
|
const base = await this.#table.get(keys);
|
|
476
468
|
if (base === void 0) return void 0;
|
|
@@ -688,8 +680,7 @@ var Model = class {
|
|
|
688
680
|
return rows.map((row, index) => Object.assign({}, row, props[index]));
|
|
689
681
|
}
|
|
690
682
|
};
|
|
691
|
-
|
|
692
|
-
//#region src/core/RelationManager.ts
|
|
683
|
+
// src/core/RelationManager.ts
|
|
693
684
|
/**
|
|
694
685
|
* Resolves a {@link RelationsShape} once at construction and vends a typed
|
|
695
686
|
* {@link ModelInterface} per declared table.
|
|
@@ -780,8 +771,7 @@ var RelationManager = class {
|
|
|
780
771
|
};
|
|
781
772
|
}
|
|
782
773
|
};
|
|
783
|
-
|
|
784
|
-
//#region src/core/factories.ts
|
|
774
|
+
// src/core/factories.ts
|
|
785
775
|
/**
|
|
786
776
|
* Creates a {@link RelationManagerInterface} over a database and its relation map.
|
|
787
777
|
*
|
|
@@ -825,7 +815,6 @@ var RelationManager = class {
|
|
|
825
815
|
function createRelationManager(options) {
|
|
826
816
|
return new RelationManager(options);
|
|
827
817
|
}
|
|
828
|
-
//#endregion
|
|
829
818
|
exports.Model = Model;
|
|
830
819
|
exports.RelationError = RelationError;
|
|
831
820
|
exports.RelationManager = RelationManager;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["isInstance","isRecord","literalOf","isString","isString","isArray","isDefined","isObject","Emitter","isArray","isDefined","extractKey","isBoolean"],"sources":["../../../src/core/errors.ts","../../../src/core/validators.ts","../../../src/core/helpers.ts","../../../src/core/Model.ts","../../../src/core/RelationManager.ts","../../../src/core/factories.ts"],"sourcesContent":["import type { RelationErrorCode } from './types.js'\nimport { isInstance } from '@orkestrel/contract'\n\n// Invalid relation definitions and misuse `throw` a `RelationError` carrying a\n// machine-readable `code`, so a `catch` branches on `error.code`\n// (`.claude/rules/typescript.md` § Errors and outcomes).\n\n/**\n * Represents an error thrown by the relations layer, carrying a machine-readable\n * {@link RelationErrorCode}.\n *\n * @remarks\n * Thrown for: a relation value whose relationship cannot be inferred (`INVALID`), a\n * relation targeting a table or junction the database does not declare, raised when\n * the manager is created (`INVALID`), a reference to a relation a model does not\n * define (`UNKNOWN_RELATION`), and `link` / `unlink` / `links` on a relation that is\n * not a `through` (`NOT_THROUGH`).\n */\nexport class RelationError extends Error {\n\treadonly code: RelationErrorCode\n\treadonly context?: Readonly<Record<string, unknown>>\n\n\tconstructor(\n\t\tcode: RelationErrorCode,\n\t\tmessage: string,\n\t\tcontext?: Readonly<Record<string, unknown>>,\n\t) {\n\t\tsuper(message)\n\t\tthis.name = 'RelationError'\n\t\tthis.code = code\n\t\tif (context !== undefined) this.context = context\n\t}\n}\n\n/**\n * Narrows an unknown caught value to a {@link RelationError}.\n *\n * @param value - The value to test (typically a `catch` binding)\n * @returns True if `value` is a {@link RelationError}; false otherwise\n */\nexport function isRelationError(value: unknown): value is RelationError {\n\treturn isInstance(value, RelationError)\n}\n","import type { RelationDescriptor } from './types.js'\nimport { isRecord, isString, literalOf } from '@orkestrel/contract'\n\n// === Descriptor guard\n\n/**\n * Narrows a value to a {@link RelationDescriptor} (the object form of a relation).\n *\n * @remarks\n * A record satisfies the descriptor when every member it declares carries its declared\n * type: `relationship` is one of the `Relationship` values, and `column`, `key`,\n * `through`, `source`, `target`, `tag`, `label`, and `model` are strings. A member the\n * record omits is unconstrained, a member present with an `undefined` value is refused,\n * and a member the descriptor does not declare is carried without being checked. This\n * is what lets `resolveRelation` read each member after one narrow and report a\n * malformed definition as an `INVALID` `RelationError` instead of resolving a\n * wrong-typed column into an arm that declares it a string.\n *\n * @param value - The value to test\n * @returns True if `value` is a record whose every declared member holds its declared\n * type; false otherwise\n *\n * @example\n * ```ts\n * isRelationDescriptor(belongsTo('accountId')) // true\n * isRelationDescriptor({ column: 42 }) // false — `column` is declared a string\n * ```\n */\nexport function isRelationDescriptor(value: unknown): value is RelationDescriptor {\n\tif (!isRecord(value)) return false\n\tif (\n\t\t'relationship' in value &&\n\t\t!literalOf('belongs', 'many', 'one', 'through', 'morph')(value.relationship)\n\t) {\n\t\treturn false\n\t}\n\tfor (const member of ['column', 'key', 'through', 'source', 'target', 'tag', 'label', 'model']) {\n\t\tif (member in value && !isString(value[member])) return false\n\t}\n\treturn true\n}\n","import type {\n\tRelation,\n\tRelationDescriptor,\n\tRelationMap,\n\tRelationship,\n\tResolvedRelation,\n} from './types.js'\nimport type { Row } from '@orkestrel/database'\nimport { isArray, isDefined, isObject, isString } from '@orkestrel/contract'\nimport { isRelationDescriptor } from './validators.js'\nimport { RelationError } from './errors.js'\n\n// Resolve raw relation values into the flat `ResolvedRelation` form once, at\n// define-time, so no inference runs during loading. The builders in this file set\n// an explicit `relationship`; hand-written descriptors fall back to field inference.\n\n// === Resolution\n\n/**\n * Resolves one raw {@link Relation} value into a flat {@link ResolvedRelation}.\n *\n * @remarks\n * A `string` is a `belongs` (foreign-key column on this table); a `readonly string[]`\n * is a `many` (foreign-key column on the related table); a {@link RelationDescriptor}\n * uses its explicit `relationship`, or infers it from the fields present. The target\n * model defaults to the relation name. Every column the resolved arm declares is\n * validated here, which is what lets each arm declare its columns required.\n *\n * @param name - The relation name (its key in the {@link RelationMap})\n * @param value - The raw relation value\n * @returns The resolved relation, on the arm its `relationship` names\n * @throws An `INVALID` {@link RelationError} when the relationship cannot be resolved, or when a\n * column the resolved arm declares is missing\n */\nexport function resolveRelation(name: string, value: Relation): ResolvedRelation {\n\tif (isString(value)) {\n\t\treturn { relationship: 'belongs', name, model: name, column: value }\n\t}\n\tif (isArray(value)) {\n\t\tconst key = value[0]\n\t\tif (!isString(key)) {\n\t\t\tthrow new RelationError(\n\t\t\t\t'INVALID',\n\t\t\t\t`Relation '${name}': array form needs a string FK column`,\n\t\t\t\t{\n\t\t\t\t\trelation: name,\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t\treturn { relationship: 'many', name, model: name, key }\n\t}\n\tif (!isRelationDescriptor(value)) {\n\t\tthrow new RelationError('INVALID', `Relation '${name}': not a string, array, or descriptor`, {\n\t\t\trelation: name,\n\t\t})\n\t}\n\n\tconst model = value.model ?? name\n\t// Inferred from the fields present when no explicit `relationship` is set.\n\tlet relationship: Relationship\n\tif (value.relationship !== undefined) {\n\t\trelationship = value.relationship\n\t} else if (isDefined(value.through)) {\n\t\trelationship = 'through'\n\t} else if (isDefined(value.tag)) {\n\t\trelationship = 'morph'\n\t} else if (isDefined(value.column)) {\n\t\trelationship = 'belongs'\n\t} else if (isDefined(value.key)) {\n\t\trelationship = 'one'\n\t} else {\n\t\tthrow new RelationError(\n\t\t\t'INVALID',\n\t\t\t`Relation '${name}': cannot infer relationship from descriptor`,\n\t\t\t{ relation: name },\n\t\t)\n\t}\n\n\tswitch (relationship) {\n\t\tcase 'belongs': {\n\t\t\tconst column = value.column\n\t\t\tif (column === undefined) {\n\t\t\t\tthrow new RelationError('INVALID', `Relation '${name}': belongs needs 'column'`, {\n\t\t\t\t\trelation: name,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn { relationship, name, model, column }\n\t\t}\n\t\tcase 'many': {\n\t\t\tconst key = value.key\n\t\t\tif (key === undefined) {\n\t\t\t\tthrow new RelationError('INVALID', `Relation '${name}': many needs 'key'`, {\n\t\t\t\t\trelation: name,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn { relationship, name, model, key }\n\t\t}\n\t\tcase 'one': {\n\t\t\tconst key = value.key\n\t\t\tif (key === undefined) {\n\t\t\t\tthrow new RelationError('INVALID', `Relation '${name}': one needs 'key'`, {\n\t\t\t\t\trelation: name,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn { relationship, name, model, key }\n\t\t}\n\t\tcase 'through': {\n\t\t\tconst { through, source, target } = value\n\t\t\tif (through === undefined || source === undefined || target === undefined) {\n\t\t\t\tthrow new RelationError(\n\t\t\t\t\t'INVALID',\n\t\t\t\t\t`Relation '${name}': through needs 'through', 'source', and 'target'`,\n\t\t\t\t\t{ relation: name },\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn {\n\t\t\t\trelationship,\n\t\t\t\tname,\n\t\t\t\tmodel,\n\t\t\t\tthrough,\n\t\t\t\tsource,\n\t\t\t\ttarget,\n\t\t\t}\n\t\t}\n\t\tcase 'morph': {\n\t\t\tconst { key, tag, label } = value\n\t\t\tif (key === undefined || tag === undefined || label === undefined) {\n\t\t\t\tthrow new RelationError(\n\t\t\t\t\t'INVALID',\n\t\t\t\t\t`Relation '${name}': morph needs 'key', 'tag', and 'label'`,\n\t\t\t\t\t{ relation: name },\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn { relationship, name, model, key, tag, label }\n\t\t}\n\t}\n}\n\n/**\n * Resolves every entry of a {@link RelationMap} into a name → {@link ResolvedRelation} map.\n *\n * @param relations - The raw relation map\n * @returns A map keyed by relation name\n */\nexport function resolveRelationMap(relations: RelationMap): ReadonlyMap<string, ResolvedRelation> {\n\tconst resolved = new Map<string, ResolvedRelation>()\n\tfor (const [name, value] of Object.entries(relations)) {\n\t\tresolved.set(name, resolveRelation(name, value))\n\t}\n\treturn resolved\n}\n\n// === Row projection\n\n/**\n * Reads one column off any record, whatever its declared type.\n *\n * @remarks\n * A base row's type is closed, so the column is read with `Reflect.get` rather than\n * index access. Anything that is not an object reads as `undefined`.\n *\n * @param record - The record to read\n * @param column - The column name\n * @returns The column's value, or `undefined` when `record` is not an object\n *\n * @example\n * ```ts\n * readColumn({ accountId: 'acc1' }, 'accountId') // 'acc1'\n * ```\n */\nexport function readColumn(record: unknown, column: string): unknown {\n\tif (!isObject(record)) return undefined\n\treturn Reflect.get(record, column)\n}\n\n/**\n * Counts the related rows one relation attached across a record set.\n *\n * @remarks\n * An array-valued relation (`many` / `through` / `morph`) sums its lengths; a\n * single-valued one (`belongs` / `one`) counts each present row. This is the count a\n * `Model` carries on its `load` event.\n *\n * @param values - One relation's loaded value per record\n * @returns The total related rows attached across the set\n *\n * @example\n * ```ts\n * countAttached([[{ id: 'p1' }, { id: 'p2' }], undefined, { id: 'p3' }]) // 3\n * ```\n */\nexport function countAttached(values: ReadonlyArray<Row | readonly Row[] | undefined>): number {\n\tlet total = 0\n\tfor (const value of values) {\n\t\tif (isArray(value)) total += value.length\n\t\telse if (value !== undefined) total += 1\n\t}\n\treturn total\n}\n\n/**\n * Indexes rows by the string form of one column, for keyed lookups.\n *\n * @remarks\n * The column is read with {@link readColumn} and its value stringified, so a numeric\n * and a string foreign key meet at the same entry. A later row with a key an earlier\n * row already holds replaces it, and a row missing the column indexes under the string\n * `'undefined'`. This is the projection a `belongs` load and a `through` load use to\n * attach one related row per key.\n *\n * @param rows - The rows to index\n * @param column - The column to key on\n * @returns A read-only map from each key's string form to its row\n *\n * @example\n * ```ts\n * indexRows([{ id: 'r1' }, { id: 'r2' }], 'id').get('r1') // { id: 'r1' }\n * ```\n */\nexport function indexRows(rows: readonly Row[], column: string): ReadonlyMap<string, Row> {\n\tconst index = new Map<string, Row>()\n\tfor (const row of rows) index.set(String(readColumn(row, column)), row)\n\treturn index\n}\n\n/**\n * Groups rows by the string form of one column, for one-to-many lookups.\n *\n * @remarks\n * The column is read with {@link readColumn} and its value stringified, so a numeric\n * and a string foreign key meet at the same group. Rows keep their input order inside\n * a group, a key no row carries is absent rather than empty, and a row missing the\n * column groups under the string `'undefined'`. This is the projection a `many` load\n * and a `morph` load use to attach every related row per key.\n *\n * @param rows - The rows to group\n * @param column - The column to key on\n * @returns A read-only map from each key's string form to its rows, in input order\n *\n * @example\n * ```ts\n * groupRows([{ author: 'u1' }, { author: 'u1' }], 'author').get('u1')?.length // 2\n * ```\n */\nexport function groupRows(\n\trows: readonly Row[],\n\tcolumn: string,\n): ReadonlyMap<string, readonly Row[]> {\n\tconst groups = new Map<string, Row[]>()\n\tfor (const row of rows) {\n\t\tconst key = String(readColumn(row, column))\n\t\tconst group = groups.get(key)\n\t\tif (group !== undefined) group.push(row)\n\t\telse groups.set(key, [row])\n\t}\n\treturn groups\n}\n\n// === Builders\n\n/**\n * Builds a `belongs` relation — a foreign key on the owning table points at the related row\n * (single).\n *\n * @param column - The foreign-key column on this table\n * @param model - Target table name (defaults to the relation name)\n * @returns A {@link RelationDescriptor}\n *\n * @example\n * ```ts\n * { classification: belongsTo('classificationId', 'classifications') }\n * ```\n */\nexport function belongsTo(column: string, model?: string): RelationDescriptor {\n\treturn { relationship: 'belongs', column, ...(model !== undefined ? { model } : {}) }\n}\n\n/**\n * Builds a `many` relation — a foreign key on the related table points back at the owning row\n * (array).\n *\n * @param key - The foreign-key column on the related table\n * @param model - Target table name (defaults to the relation name)\n * @returns A {@link RelationDescriptor}\n */\nexport function hasMany(key: string, model?: string): RelationDescriptor {\n\treturn { relationship: 'many', key, ...(model !== undefined ? { model } : {}) }\n}\n\n/**\n * Builds a `one` relation — like {@link hasMany}, but a single related row.\n *\n * @param key - The foreign-key column on the related table\n * @param model - Target table name (defaults to the relation name)\n * @returns A {@link RelationDescriptor}\n */\nexport function hasOne(key: string, model?: string): RelationDescriptor {\n\treturn { relationship: 'one', key, ...(model !== undefined ? { model } : {}) }\n}\n\n/**\n * Builds a `through` relation — a junction table links the two sides (many-to-many).\n *\n * @param through - The junction table name\n * @param source - The junction foreign-key column pointing at the owning model\n * @param target - The junction foreign-key column pointing at the related model\n * @param model - Target table name (defaults to the relation name)\n * @returns A {@link RelationDescriptor}\n *\n * @example\n * ```ts\n * { reps: hasThrough('accountReps', 'accountId', 'repId', 'reps') }\n * ```\n */\nexport function hasThrough(\n\tthrough: string,\n\tsource: string,\n\ttarget: string,\n\tmodel?: string,\n): RelationDescriptor {\n\treturn {\n\t\trelationship: 'through',\n\t\tthrough,\n\t\tsource,\n\t\ttarget,\n\t\t...(model !== undefined ? { model } : {}),\n\t}\n}\n\n/**\n * Builds a `morph` relation — a polymorphic foreign key plus a discriminator column on the\n * related table (array).\n *\n * @param key - The foreign-key column on the related table\n * @param tag - The discriminator column on the related table\n * @param label - The discriminator value identifying the owning model\n * @param model - Target table name (defaults to the relation name)\n * @returns A {@link RelationDescriptor}\n *\n * @example\n * ```ts\n * { notes: hasMorph('entityId', 'entityType', 'account', 'notes') }\n * ```\n */\nexport function hasMorph(\n\tkey: string,\n\ttag: string,\n\tlabel: string,\n\tmodel?: string,\n): RelationDescriptor {\n\treturn { relationship: 'morph', key, tag, label, ...(model !== undefined ? { model } : {}) }\n}\n","import type {\n\tDatabaseInterface,\n\tKey,\n\tOperationOptions,\n\tRow,\n\tTableInterface,\n} from '@orkestrel/database'\nimport type { EmitterErrorHandler, EmitterHooks, EmitterInterface } from '@orkestrel/emitter'\nimport type {\n\tFindOptions,\n\tInclude,\n\tLoaded,\n\tLoadedMap,\n\tModelEventMap,\n\tModelInterface,\n\tRelationContext,\n\tRelationMap,\n\tResolvedBelongs,\n\tResolvedMany,\n\tResolvedMorph,\n\tResolvedOne,\n\tResolvedRelation,\n\tResolvedThrough,\n} from './types.js'\nimport { checkAbort, extractKey } from '@orkestrel/database'\nimport { Emitter } from '@orkestrel/emitter'\nimport { isArray, isBoolean, isDefined } from '@orkestrel/contract'\nimport { countAttached, groupRows, indexRows, readColumn } from './helpers.js'\nimport { RelationError } from './errors.js'\n\n/**\n * Pairs a typed table with relation-aware `load` / `find` and junction management.\n *\n * @remarks\n * The model's own table is fully typed (`table`); related tables are reached by\n * runtime name through the database at the broad `Row` type. Loading is batched:\n * a direct relation uses one query for the whole record set, while a `through`\n * relation uses two (junction then target); both counts remain constant regardless\n * of parent count. Nested includes recurse through the registry `lookup`, so each\n * nested level is batched again. Columns are read with `Reflect.get` (the base row's\n * type is closed) and relation properties merged with `Object.assign` — no `as`.\n *\n * @remarks\n * - **Observable.** The owned {@link emitter} ({@link ModelEventMap}) carries the\n * eager-load + junction moments — `load` (a relation resolved: its name + the count of\n * related rows attached across the whole record set), `link` / `unlink` (a junction row\n * written) — for fire-and-forget observers. Every event is emitted directly, strictly\n * after the load resolves and after the junction operation completes; the emitter\n * isolates a listener throw and routes it to its `error` handler (the `error` option),\n * so a buggy observer can never corrupt the batched eager-load (no N+1 in the events\n * either — one `load` per relation, not per record).\n *\n * @example\n * ```ts\n * import { Model, resolveRelationMap, hasMany } from '@orkestrel/relation'\n *\n * const relations = { posts: hasMany('author') }\n * const users = new Model(\n * \t'users',\n * \tdatabase.table('users'),\n * \tresolveRelationMap(relations),\n * \trelations,\n * \t() => undefined,\n * \tdatabase,\n * )\n * users.emitter.on('load', (name, count) => metrics.record(`relation.${name}`, count))\n * const ada = await users.load('u1', { posts: true })\n * ```\n */\nexport class Model<T = Row> implements ModelInterface<T> {\n\treadonly #name: string\n\treadonly #table: TableInterface<T>\n\treadonly #resolved: ReadonlyMap<string, ResolvedRelation>\n\treadonly #relations: RelationMap\n\treadonly #lookup: (model: string) => RelationContext | undefined\n\treadonly #database: DatabaseInterface\n\t// The push observation surface — owned, never inherited. The emitter isolates a\n\t// listener throw (routing it to the `error` handler), so it can never escape into the\n\t// batched eager-load.\n\treadonly #emitter: Emitter<ModelEventMap>\n\n\t/**\n\t * Constructs a model over one table and its resolved relations.\n\t *\n\t * @param name - The model's table name\n\t * @param table - The typed table this model's own reads and writes go through\n\t * @param resolved - The model's relations, resolved by `resolveRelationMap`\n\t * @param relations - The raw relation map the resolved relations came from\n\t * @param lookup - Reads a related model's {@link RelationContext} for a nested include,\n\t * and returns `undefined` for a model the registry does not hold\n\t * @param database - The broad database used to read related and junction tables by name\n\t * @param on - Initial {@link ModelEventMap} listeners\n\t * @param error - Receives a listener throw as `(error, event)`. Default: the throw is\n\t * swallowed.\n\t */\n\tconstructor(\n\t\tname: string,\n\t\ttable: TableInterface<T>,\n\t\tresolved: ReadonlyMap<string, ResolvedRelation>,\n\t\trelations: RelationMap,\n\t\tlookup: (model: string) => RelationContext | undefined,\n\t\tdatabase: DatabaseInterface,\n\t\ton?: EmitterHooks<ModelEventMap>,\n\t\terror?: EmitterErrorHandler,\n\t) {\n\t\tthis.#name = name\n\t\tthis.#table = table\n\t\tthis.#resolved = resolved\n\t\tthis.#relations = relations\n\t\tthis.#lookup = lookup\n\t\tthis.#database = database\n\t\tthis.#emitter = new Emitter<ModelEventMap>({\n\t\t\t...(on !== undefined ? { on } : {}),\n\t\t\t...(error !== undefined ? { error } : {}),\n\t\t})\n\t}\n\n\tget emitter(): EmitterInterface<ModelEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tget name(): string {\n\t\treturn this.#name\n\t}\n\n\tget table(): TableInterface<T> {\n\t\treturn this.#table\n\t}\n\n\tget relations(): RelationMap {\n\t\treturn this.#relations\n\t}\n\n\tload(key: Key, include: Include, options?: OperationOptions): Promise<Loaded<T> | undefined>\n\tload(\n\t\tkeys: readonly Key[],\n\t\tinclude: Include,\n\t\toptions?: OperationOptions,\n\t): Promise<ReadonlyArray<Loaded<T> | undefined>>\n\tasync load(\n\t\tkeys: Key | readonly Key[],\n\t\tinclude: Include,\n\t\toptions?: OperationOptions,\n\t): Promise<(Loaded<T> | undefined) | ReadonlyArray<Loaded<T> | undefined>> {\n\t\tcheckAbort(options?.signal)\n\t\tif (isArray(keys)) {\n\t\t\t// Batch: one `get`, then one populate over all present rows (no N+1).\n\t\t\tconst bases = await this.#table.get(keys)\n\t\t\tconst present = bases.filter(isDefined)\n\t\t\tconst props = await this.#populate(\n\t\t\t\tpresent,\n\t\t\t\tinclude,\n\t\t\t\tthis.#resolved,\n\t\t\t\tthis.#table.primary,\n\t\t\t\toptions,\n\t\t\t)\n\t\t\tlet next = 0\n\t\t\treturn bases.map((base) =>\n\t\t\t\tbase === undefined ? undefined : Object.assign({}, base, props[next++]),\n\t\t\t)\n\t\t}\n\t\tconst base = await this.#table.get(keys)\n\t\tif (base === undefined) return undefined\n\t\tconst [props] = await this.#populate(\n\t\t\t[base],\n\t\t\tinclude,\n\t\t\tthis.#resolved,\n\t\t\tthis.#table.primary,\n\t\t\toptions,\n\t\t)\n\t\treturn Object.assign({}, base, props)\n\t}\n\n\tasync find(include: Include, options?: FindOptions): Promise<ReadonlyArray<Loaded<T>>> {\n\t\tcheckAbort(options?.signal)\n\t\tconst records = await this.#table.records(\n\t\t\t{\n\t\t\t\t...(options?.sort !== undefined\n\t\t\t\t\t? {\n\t\t\t\t\t\t\torder: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tcolumn: options.sort,\n\t\t\t\t\t\t\t\t\tdirection: options.direction ?? 'ascending',\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t\t...(options?.offset !== undefined ? { offset: options.offset } : {}),\n\t\t\t\t...(options?.limit !== undefined ? { limit: options.limit } : {}),\n\t\t\t},\n\t\t\toptions,\n\t\t)\n\t\tconst props = await this.#populate(\n\t\t\trecords,\n\t\t\tinclude,\n\t\t\tthis.#resolved,\n\t\t\tthis.#table.primary,\n\t\t\toptions,\n\t\t)\n\t\treturn records.map((record, index) => Object.assign({}, record, props[index]))\n\t}\n\n\tasync link(key: Key, relation: string, target: Key, options?: OperationOptions): Promise<void> {\n\t\tcheckAbort(options?.signal)\n\t\tconst resolved = this.#through(relation)\n\t\tconst junction = this.#database.table(resolved.through)\n\t\tconst existing = await junction.count(\n\t\t\t{\n\t\t\t\tconditions: [\n\t\t\t\t\t{ column: resolved.source, operator: 'equals', values: [key], connector: 'and' },\n\t\t\t\t\t{ column: resolved.target, operator: 'equals', values: [target], connector: 'and' },\n\t\t\t\t],\n\t\t\t},\n\t\t\toptions,\n\t\t)\n\t\tif (existing > 0) return\n\t\tawait junction.set({ [resolved.source]: key, [resolved.target]: target }, options)\n\t\t// Observe the inserted junction row — strictly after the driver write, so a swallowed\n\t\t// listener throw can't perturb the link (carries the owning key + the relation name).\n\t\tthis.#emitter.emit('link', key, relation)\n\t}\n\n\tasync unlink(key: Key, relation: string, target: Key, options?: OperationOptions): Promise<void> {\n\t\tcheckAbort(options?.signal)\n\t\tconst resolved = this.#through(relation)\n\t\tconst junction = this.#database.table(resolved.through)\n\t\tconst rows = await junction.records(\n\t\t\t{\n\t\t\t\tconditions: [\n\t\t\t\t\t{\n\t\t\t\t\t\tcolumn: resolved.source,\n\t\t\t\t\t\toperator: 'equals',\n\t\t\t\t\t\tvalues: [key],\n\t\t\t\t\t\tconnector: 'and',\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tcolumn: resolved.target,\n\t\t\t\t\t\toperator: 'equals',\n\t\t\t\t\t\tvalues: [target],\n\t\t\t\t\t\tconnector: 'and',\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t\toptions,\n\t\t)\n\t\tawait this.#database.transaction(async (transaction) => {\n\t\t\tconst scoped = transaction.table(resolved.through)\n\t\t\tfor (const row of rows) {\n\t\t\t\tconst id = extractKey(row, junction.primary)\n\t\t\t\tif (id !== undefined) await scoped.remove(id, options)\n\t\t\t}\n\t\t}, options)\n\t\t// Observe the removal only after the transaction commits.\n\t\tthis.#emitter.emit('unlink', key, relation)\n\t}\n\n\tasync links(key: Key, relation: string, options?: OperationOptions): Promise<readonly Key[]> {\n\t\tcheckAbort(options?.signal)\n\t\tconst resolved = this.#through(relation)\n\t\tconst junction = this.#database.table(resolved.through)\n\t\tconst rows = await junction.records(\n\t\t\t{\n\t\t\t\tconditions: [\n\t\t\t\t\t{\n\t\t\t\t\t\tcolumn: resolved.source,\n\t\t\t\t\t\toperator: 'equals',\n\t\t\t\t\t\tvalues: [key],\n\t\t\t\t\t\tconnector: 'and',\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t\toptions,\n\t\t)\n\t\tconst target = resolved.target\n\t\tconst keys: Key[] = []\n\t\tfor (const row of rows) {\n\t\t\tconst value = extractKey(row, target)\n\t\t\tif (value !== undefined) keys.push(value)\n\t\t}\n\t\treturn keys\n\t}\n\n\t// === Private\n\n\t// Resolve a `through` relation by name to its own arm, or throw a descriptive error.\n\t#through(relation: string): ResolvedThrough {\n\t\tconst resolved = this.#resolved.get(relation)\n\t\tif (resolved === undefined) {\n\t\t\tthrow new RelationError(\n\t\t\t\t'UNKNOWN_RELATION',\n\t\t\t\t`Model '${this.#name}' has no relation '${relation}'`,\n\t\t\t\t{ model: this.#name, relation },\n\t\t\t)\n\t\t}\n\t\tif (resolved.relationship !== 'through') {\n\t\t\tthrow new RelationError(\n\t\t\t\t'NOT_THROUGH',\n\t\t\t\t`Relation '${relation}' on '${this.#name}' is not a through`,\n\t\t\t\t{ model: this.#name, relation },\n\t\t\t)\n\t\t}\n\t\treturn resolved\n\t}\n\n\t// Compute the relation properties for each record (parallel to `records`).\n\tasync #populate(\n\t\trecords: readonly unknown[],\n\t\tinclude: Include,\n\t\tresolvedMap: ReadonlyMap<string, ResolvedRelation>,\n\t\tprimary: string,\n\t\toptions?: OperationOptions,\n\t): Promise<LoadedMap[]> {\n\t\tcheckAbort(options?.signal)\n\t\tconst props: LoadedMap[] = records.map(() => ({}))\n\t\tfor (const [name, sub] of Object.entries(include)) {\n\t\t\tif (sub === false) continue\n\t\t\tcheckAbort(options?.signal)\n\t\t\tconst resolved = resolvedMap.get(name)\n\t\t\tif (resolved === undefined) continue\n\t\t\tconst values = await this.#load(records, resolved, sub, primary, options)\n\t\t\tvalues.forEach((value, index) => {\n\t\t\t\tconst target = props[index]\n\t\t\t\tif (target !== undefined) target[resolved.name] = value\n\t\t\t})\n\t\t\t// Observe this relation's eager-load — strictly after it resolved + was attached,\n\t\t\t// once per relation (not per record — the batched load has no N+1, nor do its\n\t\t\t// events), carrying the relation name + the count of rows attached across the set.\n\t\t\tthis.#emitter.emit('load', resolved.name, countAttached(values))\n\t\t}\n\t\treturn props\n\t}\n\n\t// Dispatch one relation to its loader, returning a value per record.\n\tasync #load(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedRelation,\n\t\tsub: boolean | Include,\n\t\tprimary: string,\n\t\toptions?: OperationOptions,\n\t): Promise<Array<Row | readonly Row[] | undefined>> {\n\t\tswitch (resolved.relationship) {\n\t\t\tcase 'belongs':\n\t\t\t\treturn this.#loadBelongs(records, resolved, sub, options)\n\t\t\tcase 'many':\n\t\t\t\treturn this.#loadMany(records, resolved, sub, primary, options)\n\t\t\tcase 'one':\n\t\t\t\treturn this.#loadOne(records, resolved, sub, primary, options)\n\t\t\tcase 'through':\n\t\t\t\treturn this.#loadThrough(records, resolved, sub, primary, options)\n\t\t\tcase 'morph':\n\t\t\t\treturn this.#loadMorph(records, resolved, sub, primary, options)\n\t\t}\n\t}\n\n\tasync #loadBelongs(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedBelongs,\n\t\tsub: boolean | Include,\n\t\toptions?: OperationOptions,\n\t): Promise<Array<Row | undefined>> {\n\t\tconst column = resolved.column\n\t\tconst keys = [...new Set(records.map((record) => readColumn(record, column)).filter(isDefined))]\n\t\tif (keys.length === 0) return records.map(() => undefined)\n\t\tconst related = this.#database.table(resolved.model)\n\t\tconst rows = await related.records(\n\t\t\t{\n\t\t\t\tconditions: [\n\t\t\t\t\t{\n\t\t\t\t\t\tcolumn: related.primary,\n\t\t\t\t\t\toperator: 'any',\n\t\t\t\t\t\tvalues: keys,\n\t\t\t\t\t\tconnector: 'and',\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t\toptions,\n\t\t)\n\t\tconst index = indexRows(await this.#nest(resolved.model, rows, sub, options), related.primary)\n\t\treturn records.map((record) => {\n\t\t\tconst fk = readColumn(record, column)\n\t\t\treturn isDefined(fk) ? index.get(String(fk)) : undefined\n\t\t})\n\t}\n\n\tasync #loadMany(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedMany | ResolvedOne,\n\t\tsub: boolean | Include,\n\t\tprimary: string,\n\t\toptions?: OperationOptions,\n\t): Promise<Array<readonly Row[]>> {\n\t\tconst foreign = resolved.key\n\t\tconst keys = [\n\t\t\t...new Set(records.map((record) => readColumn(record, primary)).filter(isDefined)),\n\t\t]\n\t\tif (keys.length === 0) return records.map(() => [])\n\t\tconst rows = await this.#database.table(resolved.model).records(\n\t\t\t{\n\t\t\t\tconditions: [{ column: foreign, operator: 'any', values: keys, connector: 'and' }],\n\t\t\t},\n\t\t\toptions,\n\t\t)\n\t\tconst groups = groupRows(await this.#nest(resolved.model, rows, sub, options), foreign)\n\t\treturn records.map((record) => groups.get(String(readColumn(record, primary))) ?? [])\n\t}\n\n\tasync #loadOne(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedOne,\n\t\tsub: boolean | Include,\n\t\tprimary: string,\n\t\toptions?: OperationOptions,\n\t): Promise<Array<Row | undefined>> {\n\t\tconst groups = await this.#loadMany(records, resolved, sub, primary, options)\n\t\treturn groups.map((group) => (group.length > 0 ? group[0] : undefined))\n\t}\n\n\tasync #loadThrough(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedThrough,\n\t\tsub: boolean | Include,\n\t\tprimary: string,\n\t\toptions?: OperationOptions,\n\t): Promise<Array<readonly Row[]>> {\n\t\tconst source = resolved.source\n\t\tconst target = resolved.target\n\t\tconst parents = [\n\t\t\t...new Set(records.map((record) => readColumn(record, primary)).filter(isDefined)),\n\t\t]\n\t\tif (parents.length === 0) return records.map(() => [])\n\n\t\tconst junctions = await this.#database.table(resolved.through).records(\n\t\t\t{\n\t\t\t\tconditions: [{ column: source, operator: 'any', values: parents, connector: 'and' }],\n\t\t\t},\n\t\t\toptions,\n\t\t)\n\t\tconst targetsBySource = new Map<string, unknown[]>()\n\t\tfor (const junction of junctions) {\n\t\t\tconst value = readColumn(junction, target)\n\t\t\tif (!isDefined(value)) continue\n\t\t\tconst owner = String(readColumn(junction, source))\n\t\t\tconst list = targetsBySource.get(owner)\n\t\t\tif (list !== undefined) list.push(value)\n\t\t\telse targetsBySource.set(owner, [value])\n\t\t}\n\n\t\tconst targets = [...new Set([...targetsBySource.values()].flat())]\n\t\tif (targets.length === 0) return records.map(() => [])\n\t\tconst related = this.#database.table(resolved.model)\n\t\tconst rows = await related.records(\n\t\t\t{\n\t\t\t\tconditions: [\n\t\t\t\t\t{\n\t\t\t\t\t\tcolumn: related.primary,\n\t\t\t\t\t\toperator: 'any',\n\t\t\t\t\t\tvalues: targets,\n\t\t\t\t\t\tconnector: 'and',\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t\toptions,\n\t\t)\n\t\tconst index = indexRows(await this.#nest(resolved.model, rows, sub, options), related.primary)\n\n\t\treturn records.map((record) => {\n\t\t\tconst out: Row[] = []\n\t\t\tfor (const value of targetsBySource.get(String(readColumn(record, primary))) ?? []) {\n\t\t\t\tconst row = index.get(String(value))\n\t\t\t\tif (row !== undefined) out.push(row)\n\t\t\t}\n\t\t\treturn out\n\t\t})\n\t}\n\n\tasync #loadMorph(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedMorph,\n\t\tsub: boolean | Include,\n\t\tprimary: string,\n\t\toptions?: OperationOptions,\n\t): Promise<Array<readonly Row[]>> {\n\t\tconst foreign = resolved.key\n\t\tconst keys = [\n\t\t\t...new Set(records.map((record) => readColumn(record, primary)).filter(isDefined)),\n\t\t]\n\t\tif (keys.length === 0) return records.map(() => [])\n\t\tconst rows = await this.#database.table(resolved.model).records(\n\t\t\t{\n\t\t\t\tconditions: [\n\t\t\t\t\t{ column: foreign, operator: 'any', values: keys, connector: 'and' },\n\t\t\t\t\t{\n\t\t\t\t\t\tcolumn: resolved.tag,\n\t\t\t\t\t\toperator: 'equals',\n\t\t\t\t\t\tvalues: [resolved.label],\n\t\t\t\t\t\tconnector: 'and',\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t\toptions,\n\t\t)\n\t\tconst groups = groupRows(await this.#nest(resolved.model, rows, sub, options), foreign)\n\t\treturn records.map((record) => groups.get(String(readColumn(record, primary))) ?? [])\n\t}\n\n\t// Recursively load a nested include onto related rows (when `sub` is an Include).\n\tasync #nest(\n\t\tmodel: string,\n\t\trows: readonly Row[],\n\t\tsub: boolean | Include,\n\t\toptions?: OperationOptions,\n\t): Promise<readonly Row[]> {\n\t\tif (isBoolean(sub) || rows.length === 0) return rows\n\t\tconst context = this.#lookup(model)\n\t\tif (context === undefined) return rows\n\t\tconst props = await this.#populate(rows, sub, context.resolved, context.primary, options)\n\t\treturn rows.map((row, index) => Object.assign({}, row, props[index]))\n\t}\n}\n","import type { DatabaseInterface, RowOf, TableInterface, TableMap } from '@orkestrel/database'\nimport type {\n\tModelInterface,\n\tRelationContext,\n\tRelationManagerInterface,\n\tRelationManagerOptions,\n\tRelationMap,\n\tRelationsShape,\n\tResolvedRelation,\n} from './types.js'\nimport { RelationError } from './errors.js'\nimport { resolveRelationMap } from './helpers.js'\nimport { Model } from './Model.js'\n\n/**\n * Resolves a {@link RelationsShape} once at construction and vends a typed\n * {@link ModelInterface} per declared table.\n *\n * @remarks\n * Holds the database both at its precise type (to type each model's own table)\n * and at the broad `DatabaseInterface` (to fetch related tables by runtime name\n * while loading). Construction validates every target and junction against the\n * database's declared tables, so invalid definitions fail before an operation runs.\n * The `model` option's `on` and `error` are threaded into every model vended, and\n * each `model(name)` call constructs a handle owning its own emitter, so retain the\n * handle a subscription is taken on.\n *\n * @example\n * ```ts\n * import { RelationManager, hasMany } from '@orkestrel/relation'\n *\n * const manager = new RelationManager({\n * \tdatabase,\n * \trelations: { users: { posts: hasMany('author') } },\n * \tmodel: { on: { load: (name, count) => metrics.record(`relation.${name}`, count) } },\n * })\n * const users = manager.model('users')\n * const ada = await users.load('u1', { posts: true })\n * ```\n */\nexport class RelationManager<T extends TableMap = TableMap> implements RelationManagerInterface<T> {\n\treadonly #database: DatabaseInterface<T>\n\treadonly #broad: DatabaseInterface\n\treadonly #relations: RelationsShape<T>\n\treadonly #model: RelationManagerOptions['model']\n\treadonly #resolved = new Map<string, ReadonlyMap<string, ResolvedRelation>>()\n\n\t/**\n\t * Constructs a registry over a database and its relation definitions.\n\t *\n\t * @param options - The `database`, an optional `relations` map, and the optional\n\t * `model` emitter settings threaded into every model vended\n\t * @throws An `INVALID` {@link RelationError} when a relation targets a table or a\n\t * junction the database does not declare\n\t */\n\tconstructor(options: RelationManagerOptions<T>) {\n\t\tthis.#database = options.database\n\t\tthis.#broad = options.database\n\t\tthis.#relations = options.relations ?? {}\n\t\tthis.#model = options.model\n\t\tconst declared = new Set(Object.keys(this.#broad.export()))\n\t\tfor (const [name, map] of Object.entries(this.#relations)) {\n\t\t\tif (map === undefined) continue\n\t\t\tconst resolved = resolveRelationMap(map)\n\t\t\tfor (const [relation, entry] of resolved) {\n\t\t\t\tif (!declared.has(entry.model)) {\n\t\t\t\t\tthrow new RelationError(\n\t\t\t\t\t\t'INVALID',\n\t\t\t\t\t\t`Model '${name}' relation '${relation}' targets undeclared table '${entry.model}'`,\n\t\t\t\t\t\t{ model: name, relation, table: entry.model },\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tif (entry.relationship === 'through' && !declared.has(entry.through)) {\n\t\t\t\t\tthrow new RelationError(\n\t\t\t\t\t\t'INVALID',\n\t\t\t\t\t\t`Model '${name}' relation '${relation}' uses undeclared junction '${entry.through}'`,\n\t\t\t\t\t\t{ model: name, relation, table: entry.through },\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis.#resolved.set(name, resolved)\n\t\t}\n\t}\n\n\tget count(): number {\n\t\treturn this.#resolved.size\n\t}\n\n\tmodel<K extends keyof T & string>(name: K): ModelInterface<RowOf<T[K]>> {\n\t\tconst resolved = this.#resolved.get(name) ?? new Map<string, ResolvedRelation>()\n\t\tconst relations = this.#relations[name] ?? {}\n\t\treturn this.#vend(name, this.#database.table(name), resolved, relations)\n\t}\n\n\tnames(): readonly string[] {\n\t\treturn [...this.#resolved.keys()]\n\t}\n\n\thas(name: string): boolean {\n\t\treturn this.#resolved.has(name)\n\t}\n\n\t// Construct a model over an opaque row type `R`, so `RowOf<T[K]>` is not\n\t// expanded structurally here (the instantiation-depth guard `db.table` sidesteps).\n\t// The `model` option's hooks and error handler reach each vended handle's own emitter.\n\t#vend<R>(\n\t\tname: string,\n\t\ttable: TableInterface<R>,\n\t\tresolved: ReadonlyMap<string, ResolvedRelation>,\n\t\trelations: RelationMap,\n\t): ModelInterface<R> {\n\t\treturn new Model(\n\t\t\tname,\n\t\t\ttable,\n\t\t\tresolved,\n\t\t\trelations,\n\t\t\t(model) => this.#context(model),\n\t\t\tthis.#broad,\n\t\t\tthis.#model?.on,\n\t\t\tthis.#model?.error,\n\t\t)\n\t}\n\n\t// Look up a related model's resolved relations + primary, for nested loading.\n\t#context(model: string): RelationContext | undefined {\n\t\tconst resolved = this.#resolved.get(model)\n\t\tif (resolved === undefined) return undefined\n\t\treturn { resolved, primary: this.#broad.table(model).primary }\n\t}\n}\n","import type { RelationManagerInterface, RelationManagerOptions } from './types.js'\nimport type { TableMap } from '@orkestrel/database'\nimport { RelationManager } from './RelationManager.js'\n\n/**\n * Creates a {@link RelationManagerInterface} over a database and its relation map.\n *\n * @remarks\n * `relations` maps table names (constrained to the database's tables) to their\n * relation maps; build entries with `belongsTo` / `hasMany` / `hasOne` /\n * `hasThrough` / `hasMorph`. `manager.model(name)` returns the typed model for a\n * table — its own table is fully typed, related rows load at the `Row` type.\n *\n * @param options - The `database` and an optional `relations` map\n * @returns A typed {@link RelationManagerInterface}\n *\n * @example Defining relations\n * ```ts\n * import {\n * \tcreateRelationManager,\n * \tbelongsTo,\n * \thasMany,\n * \thasOne,\n * \thasThrough,\n * \thasMorph,\n * } from '@orkestrel/relation'\n *\n * const manager = createRelationManager({\n * \tdatabase: db,\n * \trelations: {\n * \t\taccounts: {\n * \t\t\tclassification: belongsTo('classificationId', 'classifications'), // foreign key on accounts\n * \t\t\tcontacts: hasMany('accountId'), // foreign key on contacts → accounts\n * \t\t\tprofile: hasOne('accountId', 'profiles'), // single, foreign key on profiles\n * \t\t\trepresentatives: hasThrough('accountReps', 'accountId', 'repId', 'representatives'), // through a junction\n * \t\t\tnotes: hasMorph('entityId', 'entityType', 'account', 'notes'), // polymorphic\n * \t\t},\n * \t\tcontacts: { account: belongsTo('accountId', 'accounts') },\n * \t},\n * })\n *\n * const acme = await manager.model('accounts').load('acc1', { contacts: true, classification: true })\n * ```\n */\nexport function createRelationManager<T extends TableMap>(\n\toptions: RelationManagerOptions<T>,\n): RelationManagerInterface<T> {\n\treturn new RelationManager(options)\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAkBA,IAAa,gBAAb,cAAmC,MAAM;CACxC;CACA;CAEA,YACC,MACA,SACA,SACC;EACD,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,IAAI,YAAY,KAAA,GAAW,KAAK,UAAU;CAC3C;AACD;;;;;;;AAQA,SAAgB,gBAAgB,OAAwC;CACvE,QAAA,GAAOA,oBAAAA,WAAAA,CAAW,OAAO,aAAa;AACvC;;;;;;;;;;;;;;;;;;;;;;;;;;ACdA,SAAgB,qBAAqB,OAA6C;CACjF,IAAI,EAAA,GAACC,oBAAAA,SAAAA,CAAS,KAAK,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,UAAU,IAAI,KAAK;EACzC,IAAI,aAAa,KAAA,GAAW,OAAO,KAAA;EACnC,OAAO;GAAE;GAAU,SAAS,KAAK,OAAO,MAAM,KAAK,CAAC,CAAC;EAAQ;CAC9D;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACrFA,SAAgB,sBACf,SAC8B;CAC9B,OAAO,IAAI,gBAAgB,OAAO;AACnC"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["holds","INTRINSICS","isObject","isFunction","isRecord","literalOf","isString","isString","isArray","isDefined","isObject","Emitter","isArray","isDefined","extractKey","isBoolean"],"sources":["../../../src/core/errors.ts","../../../src/core/validators.ts","../../../src/core/helpers.ts","../../../src/core/Model.ts","../../../src/core/RelationManager.ts","../../../src/core/factories.ts"],"sourcesContent":["import type { RelationErrorCode } from './types.js'\nimport { holds, INTRINSICS, isFunction, isObject } from '@orkestrel/contract'\n\n// Invalid relation definitions and misuse `throw` a `RelationError` carrying a\n// machine-readable `code`, so a `catch` branches on `error.code`\n// (`.claude/rules/typescript.md` § Errors and outcomes).\n\n/**\n * Represents an error thrown by the relations layer, carrying a machine-readable\n * {@link RelationErrorCode}.\n *\n * @remarks\n * Thrown for: a relation value whose relationship cannot be inferred (`INVALID`), a\n * relation targeting a table or junction the database does not declare, raised when\n * the manager is created (`INVALID`), a reference to a relation a model does not\n * define (`UNKNOWN_RELATION`), and `link` / `unlink` / `links` on a relation that is\n * not a `through` (`NOT_THROUGH`).\n */\nexport class RelationError extends Error {\n\treadonly code: RelationErrorCode\n\treadonly context?: Readonly<Record<string, unknown>>\n\n\tconstructor(\n\t\tcode: RelationErrorCode,\n\t\tmessage: string,\n\t\tcontext?: Readonly<Record<string, unknown>>,\n\t) {\n\t\tsuper(message)\n\t\tINTRINSICS.define(this, Symbol.for('@orkestrel/relation.RelationError'), { value: this })\n\t\tthis.name = 'RelationError'\n\t\tthis.code = code\n\t\tif (context !== undefined) this.context = context\n\t}\n}\n\n/**\n * Narrows an unknown caught value to a {@link RelationError}.\n *\n * @param value - The value to test (typically a `catch` binding)\n * @returns True if the error carries its own identity brand and declared members; false otherwise\n */\nexport function isRelationError(value: unknown): value is RelationError {\n\treturn holds(() => {\n\t\tif (!(value instanceof Error) || INTRINSICS.prototype(value) === Error.prototype) return false\n\t\tconst brand = INTRINSICS.describe(value, Symbol.for('@orkestrel/relation.RelationError'))\n\t\tif (brand?.value !== value) return false\n\t\tconst code: unknown = INTRINSICS.reflect.read(value, 'code')\n\t\tif (code !== 'INVALID' && code !== 'UNKNOWN_RELATION' && code !== 'NOT_THROUGH') return false\n\t\tconst context: unknown = INTRINSICS.reflect.read(value, 'context')\n\t\treturn context === undefined || isObject(context) || isFunction(context)\n\t})\n}\n","import type { RelationDescriptor } from './types.js'\nimport { isRecord, isString, literalOf } from '@orkestrel/contract'\n\n// === Descriptor guard\n\n/**\n * Narrows a value to a {@link RelationDescriptor} (the object form of a relation).\n *\n * @remarks\n * A record satisfies the descriptor when every member it declares carries its declared\n * type: `relationship` is one of the `Relationship` values, and `column`, `key`,\n * `through`, `source`, `target`, `tag`, `label`, and `model` are strings. A member the\n * record omits is unconstrained, a member present with an `undefined` value is refused,\n * and a member the descriptor does not declare is carried without being checked. This\n * is what lets `resolveRelation` read each member after one narrow and report a\n * malformed definition as an `INVALID` `RelationError` instead of resolving a\n * wrong-typed column into an arm that declares it a string.\n *\n * @param value - The value to test\n * @returns True if `value` is a record whose every declared member holds its declared\n * type; false otherwise\n *\n * @example\n * ```ts\n * isRelationDescriptor(belongsTo('accountId')) // true\n * isRelationDescriptor({ column: 42 }) // false — `column` is declared a string\n * ```\n */\nexport function isRelationDescriptor(value: unknown): value is RelationDescriptor {\n\tif (!isRecord(value)) return false\n\tif (\n\t\t'relationship' in value &&\n\t\t!literalOf('belongs', 'many', 'one', 'through', 'morph')(value.relationship)\n\t) {\n\t\treturn false\n\t}\n\tfor (const member of ['column', 'key', 'through', 'source', 'target', 'tag', 'label', 'model']) {\n\t\tif (member in value && !isString(value[member])) return false\n\t}\n\treturn true\n}\n","import type {\n\tRelation,\n\tRelationDescriptor,\n\tRelationMap,\n\tRelationship,\n\tResolvedRelation,\n} from './types.js'\nimport type { Row } from '@orkestrel/database'\nimport { isArray, isDefined, isObject, isString } from '@orkestrel/contract'\nimport { isRelationDescriptor } from './validators.js'\nimport { RelationError } from './errors.js'\n\n// Resolve raw relation values into the flat `ResolvedRelation` form once, at\n// define-time, so no inference runs during loading. The builders in this file set\n// an explicit `relationship`; hand-written descriptors fall back to field inference.\n\n// === Resolution\n\n/**\n * Resolves one raw {@link Relation} value into a flat {@link ResolvedRelation}.\n *\n * @remarks\n * A `string` is a `belongs` (foreign-key column on this table); a `readonly string[]`\n * is a `many` (foreign-key column on the related table); a {@link RelationDescriptor}\n * uses its explicit `relationship`, or infers it from the fields present. The target\n * model defaults to the relation name. Every column the resolved arm declares is\n * validated here, which is what lets each arm declare its columns required.\n *\n * @param name - The relation name (its key in the {@link RelationMap})\n * @param value - The raw relation value\n * @returns The resolved relation, on the arm its `relationship` names\n * @throws An `INVALID` {@link RelationError} when the relationship cannot be resolved, or when a\n * column the resolved arm declares is missing\n */\nexport function resolveRelation(name: string, value: Relation): ResolvedRelation {\n\tif (isString(value)) {\n\t\treturn { relationship: 'belongs', name, model: name, column: value }\n\t}\n\tif (isArray(value)) {\n\t\tconst key = value[0]\n\t\tif (!isString(key)) {\n\t\t\tthrow new RelationError(\n\t\t\t\t'INVALID',\n\t\t\t\t`Relation '${name}': array form needs a string FK column`,\n\t\t\t\t{\n\t\t\t\t\trelation: name,\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t\treturn { relationship: 'many', name, model: name, key }\n\t}\n\tif (!isRelationDescriptor(value)) {\n\t\tthrow new RelationError('INVALID', `Relation '${name}': not a string, array, or descriptor`, {\n\t\t\trelation: name,\n\t\t})\n\t}\n\n\tconst model = value.model ?? name\n\t// Inferred from the fields present when no explicit `relationship` is set.\n\tconst relationship: Relationship | undefined =\n\t\tvalue.relationship !== undefined\n\t\t\t? value.relationship\n\t\t\t: isDefined(value.through)\n\t\t\t\t? 'through'\n\t\t\t\t: isDefined(value.tag)\n\t\t\t\t\t? 'morph'\n\t\t\t\t\t: isDefined(value.column)\n\t\t\t\t\t\t? 'belongs'\n\t\t\t\t\t\t: isDefined(value.key)\n\t\t\t\t\t\t\t? 'one'\n\t\t\t\t\t\t\t: undefined\n\tif (relationship === undefined) {\n\t\tthrow new RelationError(\n\t\t\t'INVALID',\n\t\t\t`Relation '${name}': cannot infer relationship from descriptor`,\n\t\t\t{ relation: name },\n\t\t)\n\t}\n\n\tswitch (relationship) {\n\t\tcase 'belongs': {\n\t\t\tconst column = value.column\n\t\t\tif (column === undefined) {\n\t\t\t\tthrow new RelationError('INVALID', `Relation '${name}': belongs needs 'column'`, {\n\t\t\t\t\trelation: name,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn { relationship, name, model, column }\n\t\t}\n\t\tcase 'many': {\n\t\t\tconst key = value.key\n\t\t\tif (key === undefined) {\n\t\t\t\tthrow new RelationError('INVALID', `Relation '${name}': many needs 'key'`, {\n\t\t\t\t\trelation: name,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn { relationship, name, model, key }\n\t\t}\n\t\tcase 'one': {\n\t\t\tconst key = value.key\n\t\t\tif (key === undefined) {\n\t\t\t\tthrow new RelationError('INVALID', `Relation '${name}': one needs 'key'`, {\n\t\t\t\t\trelation: name,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn { relationship, name, model, key }\n\t\t}\n\t\tcase 'through': {\n\t\t\tconst { through, source, target } = value\n\t\t\tif (through === undefined || source === undefined || target === undefined) {\n\t\t\t\tthrow new RelationError(\n\t\t\t\t\t'INVALID',\n\t\t\t\t\t`Relation '${name}': through needs 'through', 'source', and 'target'`,\n\t\t\t\t\t{ relation: name },\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn {\n\t\t\t\trelationship,\n\t\t\t\tname,\n\t\t\t\tmodel,\n\t\t\t\tthrough,\n\t\t\t\tsource,\n\t\t\t\ttarget,\n\t\t\t}\n\t\t}\n\t\tcase 'morph': {\n\t\t\tconst { key, tag, label } = value\n\t\t\tif (key === undefined || tag === undefined || label === undefined) {\n\t\t\t\tthrow new RelationError(\n\t\t\t\t\t'INVALID',\n\t\t\t\t\t`Relation '${name}': morph needs 'key', 'tag', and 'label'`,\n\t\t\t\t\t{ relation: name },\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn { relationship, name, model, key, tag, label }\n\t\t}\n\t}\n}\n\n/**\n * Resolves every entry of a {@link RelationMap} into a name → {@link ResolvedRelation} map.\n *\n * @param relations - The raw relation map\n * @returns A map keyed by relation name\n */\nexport function resolveRelationMap(relations: RelationMap): ReadonlyMap<string, ResolvedRelation> {\n\treturn new Map(\n\t\tObject.entries(relations).map(([name, value]) => [name, resolveRelation(name, value)]),\n\t)\n}\n\n// === Row projection\n\n/**\n * Reads one column off any record, whatever its declared type.\n *\n * @remarks\n * A base row's type is closed, so the column is read with `Reflect.get` rather than\n * index access. Anything that is not an object reads as `undefined`.\n *\n * @param record - The record to read\n * @param column - The column name\n * @returns The column's value, or `undefined` when `record` is not an object\n *\n * @example\n * ```ts\n * readColumn({ accountId: 'acc1' }, 'accountId') // 'acc1'\n * ```\n */\nexport function readColumn(record: unknown, column: string): unknown {\n\tif (!isObject(record)) return undefined\n\treturn Reflect.get(record, column)\n}\n\n/**\n * Counts the related rows one relation attached across a record set.\n *\n * @remarks\n * An array-valued relation (`many` / `through` / `morph`) sums its lengths; a\n * single-valued one (`belongs` / `one`) counts each present row. This is the count a\n * `Model` carries on its `load` event.\n *\n * @param values - One relation's loaded value per record\n * @returns The total related rows attached across the set\n *\n * @example\n * ```ts\n * countAttached([[{ id: 'p1' }, { id: 'p2' }], undefined, { id: 'p3' }]) // 3\n * ```\n */\nexport function countAttached(values: ReadonlyArray<Row | readonly Row[] | undefined>): number {\n\treturn Iterator.from(values).reduce(\n\t\t(total, value) => total + (isArray(value) ? value.length : value === undefined ? 0 : 1),\n\t\t0,\n\t)\n}\n\n/**\n * Indexes rows by the string form of one column, for keyed lookups.\n *\n * @remarks\n * The column is read with {@link readColumn} and its value stringified, so a numeric\n * and a string foreign key meet at the same entry. A later row with a key an earlier\n * row already holds replaces it, and a row missing the column indexes under the string\n * `'undefined'`. This is the projection a `belongs` load and a `through` load use to\n * attach one related row per key.\n *\n * @param rows - The rows to index\n * @param column - The column to key on\n * @returns A read-only map from each key's string form to its row\n *\n * @example\n * ```ts\n * indexRows([{ id: 'r1' }, { id: 'r2' }], 'id').get('r1') // { id: 'r1' }\n * ```\n */\nexport function indexRows(rows: readonly Row[], column: string): ReadonlyMap<string, Row> {\n\treturn new Map(Iterator.from(rows).map((row) => [String(readColumn(row, column)), row]))\n}\n\n/**\n * Groups rows by the string form of one column, for one-to-many lookups.\n *\n * @remarks\n * The column is read with {@link readColumn} and its value stringified, so a numeric\n * and a string foreign key meet at the same group. Rows keep their input order inside\n * a group, a key no row carries is absent rather than empty, and a row missing the\n * column groups under the string `'undefined'`. This is the projection a `many` load\n * and a `morph` load use to attach every related row per key.\n *\n * @param rows - The rows to group\n * @param column - The column to key on\n * @returns A read-only map from each key's string form to its rows, in input order\n *\n * @example\n * ```ts\n * groupRows([{ author: 'u1' }, { author: 'u1' }], 'author').get('u1')?.length // 2\n * ```\n */\nexport function groupRows(\n\trows: readonly Row[],\n\tcolumn: string,\n): ReadonlyMap<string, readonly Row[]> {\n\tconst groups = new Map<string, Row[]>()\n\tfor (const row of rows) {\n\t\tconst key = String(readColumn(row, column))\n\t\tconst group = groups.get(key)\n\t\tif (group !== undefined) group.push(row)\n\t\telse groups.set(key, [row])\n\t}\n\treturn groups\n}\n\n// === Builders\n\n/**\n * Builds a `belongs` relation — a foreign key on the owning table points at the related row\n * (single).\n *\n * @param column - The foreign-key column on this table\n * @param model - Target table name (defaults to the relation name)\n * @returns A {@link RelationDescriptor}\n *\n * @example\n * ```ts\n * { classification: belongsTo('classificationId', 'classifications') }\n * ```\n */\nexport function belongsTo(column: string, model?: string): RelationDescriptor {\n\treturn { relationship: 'belongs', column, ...(model !== undefined ? { model } : {}) }\n}\n\n/**\n * Builds a `many` relation — a foreign key on the related table points back at the owning row\n * (array).\n *\n * @param key - The foreign-key column on the related table\n * @param model - Target table name (defaults to the relation name)\n * @returns A {@link RelationDescriptor}\n */\nexport function hasMany(key: string, model?: string): RelationDescriptor {\n\treturn { relationship: 'many', key, ...(model !== undefined ? { model } : {}) }\n}\n\n/**\n * Builds a `one` relation — like {@link hasMany}, but a single related row.\n *\n * @param key - The foreign-key column on the related table\n * @param model - Target table name (defaults to the relation name)\n * @returns A {@link RelationDescriptor}\n */\nexport function hasOne(key: string, model?: string): RelationDescriptor {\n\treturn { relationship: 'one', key, ...(model !== undefined ? { model } : {}) }\n}\n\n/**\n * Builds a `through` relation — a junction table links the two sides (many-to-many).\n *\n * @param through - The junction table name\n * @param source - The junction foreign-key column pointing at the owning model\n * @param target - The junction foreign-key column pointing at the related model\n * @param model - Target table name (defaults to the relation name)\n * @returns A {@link RelationDescriptor}\n *\n * @example\n * ```ts\n * { reps: hasThrough('accountReps', 'accountId', 'repId', 'reps') }\n * ```\n */\nexport function hasThrough(\n\tthrough: string,\n\tsource: string,\n\ttarget: string,\n\tmodel?: string,\n): RelationDescriptor {\n\treturn {\n\t\trelationship: 'through',\n\t\tthrough,\n\t\tsource,\n\t\ttarget,\n\t\t...(model !== undefined ? { model } : {}),\n\t}\n}\n\n/**\n * Builds a `morph` relation — a polymorphic foreign key plus a discriminator column on the\n * related table (array).\n *\n * @param key - The foreign-key column on the related table\n * @param tag - The discriminator column on the related table\n * @param label - The discriminator value identifying the owning model\n * @param model - Target table name (defaults to the relation name)\n * @returns A {@link RelationDescriptor}\n *\n * @example\n * ```ts\n * { notes: hasMorph('entityId', 'entityType', 'account', 'notes') }\n * ```\n */\nexport function hasMorph(\n\tkey: string,\n\ttag: string,\n\tlabel: string,\n\tmodel?: string,\n): RelationDescriptor {\n\treturn { relationship: 'morph', key, tag, label, ...(model !== undefined ? { model } : {}) }\n}\n","import type {\n\tDatabaseInterface,\n\tKey,\n\tOperationOptions,\n\tRow,\n\tTableInterface,\n} from '@orkestrel/database'\nimport type { EmitterErrorHandler, EmitterHooks, EmitterInterface } from '@orkestrel/emitter'\nimport type {\n\tFindOptions,\n\tInclude,\n\tLoaded,\n\tLoadedMap,\n\tModelEventMap,\n\tModelInterface,\n\tRelationContext,\n\tRelationMap,\n\tResolvedBelongs,\n\tResolvedMany,\n\tResolvedMorph,\n\tResolvedOne,\n\tResolvedRelation,\n\tResolvedThrough,\n} from './types.js'\nimport { checkAbort, extractKey } from '@orkestrel/database'\nimport { Emitter } from '@orkestrel/emitter'\nimport { isArray, isBoolean, isDefined } from '@orkestrel/contract'\nimport { countAttached, groupRows, indexRows, readColumn } from './helpers.js'\nimport { RelationError } from './errors.js'\n\n/**\n * Pairs a typed table with relation-aware `load` / `find` and junction management.\n *\n * @remarks\n * The model's own table is fully typed (`table`); related tables are reached by\n * runtime name through the database at the broad `Row` type. Loading is batched:\n * a direct relation uses one query for the whole record set, while a `through`\n * relation uses two (junction then target); both counts remain constant regardless\n * of parent count. Nested includes recurse through the registry `lookup`, so each\n * nested level is batched again. Columns are read with `Reflect.get` (the base row's\n * type is closed) and relation properties merged with `Object.assign` — no `as`.\n *\n * @remarks\n * - **Observable.** The owned {@link emitter} ({@link ModelEventMap}) carries the\n * eager-load + junction moments — `load` (a relation resolved: its name + the count of\n * related rows attached across the whole record set), `link` / `unlink` (a junction row\n * written) — for fire-and-forget observers. Every event is emitted directly, strictly\n * after the load resolves and after the junction operation completes; the emitter\n * isolates a listener throw and routes it to its `error` handler (the `error` option),\n * so a buggy observer can never corrupt the batched eager-load (no N+1 in the events\n * either — one `load` per relation, not per record).\n *\n * @example\n * ```ts\n * import { Model, resolveRelationMap, hasMany } from '@orkestrel/relation'\n *\n * const relations = { posts: hasMany('author') }\n * const users = new Model(\n * \t'users',\n * \tdatabase.table('users'),\n * \tresolveRelationMap(relations),\n * \trelations,\n * \t() => undefined,\n * \tdatabase,\n * )\n * users.emitter.on('load', (name, count) => metrics.record(`relation.${name}`, count))\n * const ada = await users.load('u1', { posts: true })\n * ```\n */\nexport class Model<T = Row> implements ModelInterface<T> {\n\treadonly #name: string\n\treadonly #table: TableInterface<T>\n\treadonly #resolved: ReadonlyMap<string, ResolvedRelation>\n\treadonly #relations: RelationMap\n\treadonly #lookup: (model: string) => RelationContext | undefined\n\treadonly #database: DatabaseInterface\n\t// The push observation surface — owned, never inherited. The emitter isolates a\n\t// listener throw (routing it to the `error` handler), so it can never escape into the\n\t// batched eager-load.\n\treadonly #emitter: Emitter<ModelEventMap>\n\n\t/**\n\t * Constructs a model over one table and its resolved relations.\n\t *\n\t * @param name - The model's table name\n\t * @param table - The typed table this model's own reads and writes go through\n\t * @param resolved - The model's relations, resolved by `resolveRelationMap`\n\t * @param relations - The raw relation map the resolved relations came from\n\t * @param lookup - Reads a related model's {@link RelationContext} for a nested include,\n\t * and returns `undefined` for a model the registry does not hold\n\t * @param database - The broad database used to read related and junction tables by name\n\t * @param on - Initial {@link ModelEventMap} listeners\n\t * @param error - Receives a listener throw as `(error, event)`. Default: the throw is\n\t * swallowed.\n\t */\n\tconstructor(\n\t\tname: string,\n\t\ttable: TableInterface<T>,\n\t\tresolved: ReadonlyMap<string, ResolvedRelation>,\n\t\trelations: RelationMap,\n\t\tlookup: (model: string) => RelationContext | undefined,\n\t\tdatabase: DatabaseInterface,\n\t\ton?: EmitterHooks<ModelEventMap>,\n\t\terror?: EmitterErrorHandler,\n\t) {\n\t\tthis.#name = name\n\t\tthis.#table = table\n\t\tthis.#resolved = resolved\n\t\tthis.#relations = relations\n\t\tthis.#lookup = lookup\n\t\tthis.#database = database\n\t\tthis.#emitter = new Emitter<ModelEventMap>({\n\t\t\t...(on !== undefined ? { on } : {}),\n\t\t\t...(error !== undefined ? { error } : {}),\n\t\t})\n\t}\n\n\tget emitter(): EmitterInterface<ModelEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tget name(): string {\n\t\treturn this.#name\n\t}\n\n\tget table(): TableInterface<T> {\n\t\treturn this.#table\n\t}\n\n\tget relations(): RelationMap {\n\t\treturn this.#relations\n\t}\n\n\tload(key: Key, include: Include, options?: OperationOptions): Promise<Loaded<T> | undefined>\n\tload(\n\t\tkeys: readonly Key[],\n\t\tinclude: Include,\n\t\toptions?: OperationOptions,\n\t): Promise<ReadonlyArray<Loaded<T> | undefined>>\n\tasync load(\n\t\tkeys: Key | readonly Key[],\n\t\tinclude: Include,\n\t\toptions?: OperationOptions,\n\t): Promise<(Loaded<T> | undefined) | ReadonlyArray<Loaded<T> | undefined>> {\n\t\tcheckAbort(options?.signal)\n\t\tif (isArray(keys)) {\n\t\t\t// Batch: one `get`, then one populate over all present rows (no N+1).\n\t\t\tconst bases = await this.#table.get(keys)\n\t\t\tconst present = bases.filter(isDefined)\n\t\t\tconst props = await this.#populate(\n\t\t\t\tpresent,\n\t\t\t\tinclude,\n\t\t\t\tthis.#resolved,\n\t\t\t\tthis.#table.primary,\n\t\t\t\toptions,\n\t\t\t)\n\t\t\tconst attachments = props.values()\n\t\t\treturn bases.map((base) =>\n\t\t\t\tbase === undefined ? undefined : Object.assign({}, base, attachments.next().value),\n\t\t\t)\n\t\t}\n\t\tconst base = await this.#table.get(keys)\n\t\tif (base === undefined) return undefined\n\t\tconst [props] = await this.#populate(\n\t\t\t[base],\n\t\t\tinclude,\n\t\t\tthis.#resolved,\n\t\t\tthis.#table.primary,\n\t\t\toptions,\n\t\t)\n\t\treturn Object.assign({}, base, props)\n\t}\n\n\tasync find(include: Include, options?: FindOptions): Promise<ReadonlyArray<Loaded<T>>> {\n\t\tcheckAbort(options?.signal)\n\t\tconst records = await this.#table.records(\n\t\t\t{\n\t\t\t\t...(options?.sort !== undefined\n\t\t\t\t\t? {\n\t\t\t\t\t\t\torder: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tcolumn: options.sort,\n\t\t\t\t\t\t\t\t\tdirection: options.direction ?? 'ascending',\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t\t...(options?.offset !== undefined ? { offset: options.offset } : {}),\n\t\t\t\t...(options?.limit !== undefined ? { limit: options.limit } : {}),\n\t\t\t},\n\t\t\toptions,\n\t\t)\n\t\tconst props = await this.#populate(\n\t\t\trecords,\n\t\t\tinclude,\n\t\t\tthis.#resolved,\n\t\t\tthis.#table.primary,\n\t\t\toptions,\n\t\t)\n\t\treturn records.map((record, index) => Object.assign({}, record, props[index]))\n\t}\n\n\tasync link(key: Key, relation: string, target: Key, options?: OperationOptions): Promise<void> {\n\t\tcheckAbort(options?.signal)\n\t\tconst resolved = this.#through(relation)\n\t\tconst junction = this.#database.table(resolved.through)\n\t\tconst existing = await junction.count(\n\t\t\t{\n\t\t\t\tconditions: [\n\t\t\t\t\t{ column: resolved.source, operator: 'equals', values: [key], connector: 'and' },\n\t\t\t\t\t{ column: resolved.target, operator: 'equals', values: [target], connector: 'and' },\n\t\t\t\t],\n\t\t\t},\n\t\t\toptions,\n\t\t)\n\t\tif (existing > 0) return\n\t\tawait junction.set({ [resolved.source]: key, [resolved.target]: target }, options)\n\t\t// Observe the inserted junction row — strictly after the driver write, so a swallowed\n\t\t// listener throw can't perturb the link (carries the owning key + the relation name).\n\t\tthis.#emitter.emit('link', key, relation)\n\t}\n\n\tasync unlink(key: Key, relation: string, target: Key, options?: OperationOptions): Promise<void> {\n\t\tcheckAbort(options?.signal)\n\t\tconst resolved = this.#through(relation)\n\t\tconst junction = this.#database.table(resolved.through)\n\t\tconst rows = await junction.records(\n\t\t\t{\n\t\t\t\tconditions: [\n\t\t\t\t\t{\n\t\t\t\t\t\tcolumn: resolved.source,\n\t\t\t\t\t\toperator: 'equals',\n\t\t\t\t\t\tvalues: [key],\n\t\t\t\t\t\tconnector: 'and',\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tcolumn: resolved.target,\n\t\t\t\t\t\toperator: 'equals',\n\t\t\t\t\t\tvalues: [target],\n\t\t\t\t\t\tconnector: 'and',\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t\toptions,\n\t\t)\n\t\tawait this.#database.transaction(async (transaction) => {\n\t\t\tconst scoped = transaction.table(resolved.through)\n\t\t\tfor (const row of rows) {\n\t\t\t\tconst id = extractKey(row, junction.primary)\n\t\t\t\tif (id !== undefined) await scoped.remove(id, options)\n\t\t\t}\n\t\t}, options)\n\t\t// Observe the removal only after the transaction commits.\n\t\tthis.#emitter.emit('unlink', key, relation)\n\t}\n\n\tasync links(key: Key, relation: string, options?: OperationOptions): Promise<readonly Key[]> {\n\t\tcheckAbort(options?.signal)\n\t\tconst resolved = this.#through(relation)\n\t\tconst junction = this.#database.table(resolved.through)\n\t\tconst rows = await junction.records(\n\t\t\t{\n\t\t\t\tconditions: [\n\t\t\t\t\t{\n\t\t\t\t\t\tcolumn: resolved.source,\n\t\t\t\t\t\toperator: 'equals',\n\t\t\t\t\t\tvalues: [key],\n\t\t\t\t\t\tconnector: 'and',\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t\toptions,\n\t\t)\n\t\tconst target = resolved.target\n\t\tconst keys: Key[] = []\n\t\tfor (const row of rows) {\n\t\t\tconst value = extractKey(row, target)\n\t\t\tif (value !== undefined) keys.push(value)\n\t\t}\n\t\treturn keys\n\t}\n\n\t// === Private\n\n\t// Resolve a `through` relation by name to its own arm, or throw a descriptive error.\n\t#through(relation: string): ResolvedThrough {\n\t\tconst resolved = this.#resolved.get(relation)\n\t\tif (resolved === undefined) {\n\t\t\tthrow new RelationError(\n\t\t\t\t'UNKNOWN_RELATION',\n\t\t\t\t`Model '${this.#name}' has no relation '${relation}'`,\n\t\t\t\t{ model: this.#name, relation },\n\t\t\t)\n\t\t}\n\t\tif (resolved.relationship !== 'through') {\n\t\t\tthrow new RelationError(\n\t\t\t\t'NOT_THROUGH',\n\t\t\t\t`Relation '${relation}' on '${this.#name}' is not a through`,\n\t\t\t\t{ model: this.#name, relation },\n\t\t\t)\n\t\t}\n\t\treturn resolved\n\t}\n\n\t// Compute the relation properties for each record (parallel to `records`).\n\tasync #populate(\n\t\trecords: readonly unknown[],\n\t\tinclude: Include,\n\t\tresolvedMap: ReadonlyMap<string, ResolvedRelation>,\n\t\tprimary: string,\n\t\toptions?: OperationOptions,\n\t): Promise<LoadedMap[]> {\n\t\tcheckAbort(options?.signal)\n\t\tconst props: LoadedMap[] = records.map(() => ({}))\n\t\tfor (const [name, sub] of Object.entries(include)) {\n\t\t\tif (sub === false) continue\n\t\t\tcheckAbort(options?.signal)\n\t\t\tconst resolved = resolvedMap.get(name)\n\t\t\tif (resolved === undefined) continue\n\t\t\tconst values = await this.#load(records, resolved, sub, primary, options)\n\t\t\tvalues.forEach((value, index) => {\n\t\t\t\tconst target = props[index]\n\t\t\t\tif (target !== undefined) target[resolved.name] = value\n\t\t\t})\n\t\t\t// Observe this relation's eager-load — strictly after it resolved + was attached,\n\t\t\t// once per relation (not per record — the batched load has no N+1, nor do its\n\t\t\t// events), carrying the relation name + the count of rows attached across the set.\n\t\t\tthis.#emitter.emit('load', resolved.name, countAttached(values))\n\t\t}\n\t\treturn props\n\t}\n\n\t// Dispatch one relation to its loader, returning a value per record.\n\tasync #load(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedRelation,\n\t\tsub: boolean | Include,\n\t\tprimary: string,\n\t\toptions?: OperationOptions,\n\t): Promise<Array<Row | readonly Row[] | undefined>> {\n\t\tswitch (resolved.relationship) {\n\t\t\tcase 'belongs':\n\t\t\t\treturn this.#loadBelongs(records, resolved, sub, options)\n\t\t\tcase 'many':\n\t\t\t\treturn this.#loadMany(records, resolved, sub, primary, options)\n\t\t\tcase 'one':\n\t\t\t\treturn this.#loadOne(records, resolved, sub, primary, options)\n\t\t\tcase 'through':\n\t\t\t\treturn this.#loadThrough(records, resolved, sub, primary, options)\n\t\t\tcase 'morph':\n\t\t\t\treturn this.#loadMorph(records, resolved, sub, primary, options)\n\t\t}\n\t}\n\n\tasync #loadBelongs(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedBelongs,\n\t\tsub: boolean | Include,\n\t\toptions?: OperationOptions,\n\t): Promise<Array<Row | undefined>> {\n\t\tconst column = resolved.column\n\t\tconst keys = [...new Set(records.map((record) => readColumn(record, column)).filter(isDefined))]\n\t\tif (keys.length === 0) return records.map(() => undefined)\n\t\tconst related = this.#database.table(resolved.model)\n\t\tconst rows = await related.records(\n\t\t\t{\n\t\t\t\tconditions: [\n\t\t\t\t\t{\n\t\t\t\t\t\tcolumn: related.primary,\n\t\t\t\t\t\toperator: 'any',\n\t\t\t\t\t\tvalues: keys,\n\t\t\t\t\t\tconnector: 'and',\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t\toptions,\n\t\t)\n\t\tconst index = indexRows(await this.#nest(resolved.model, rows, sub, options), related.primary)\n\t\treturn records.map((record) => {\n\t\t\tconst fk = readColumn(record, column)\n\t\t\treturn isDefined(fk) ? index.get(String(fk)) : undefined\n\t\t})\n\t}\n\n\tasync #loadMany(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedMany | ResolvedOne,\n\t\tsub: boolean | Include,\n\t\tprimary: string,\n\t\toptions?: OperationOptions,\n\t): Promise<Array<readonly Row[]>> {\n\t\tconst foreign = resolved.key\n\t\tconst keys = [\n\t\t\t...new Set(records.map((record) => readColumn(record, primary)).filter(isDefined)),\n\t\t]\n\t\tif (keys.length === 0) return records.map(() => [])\n\t\tconst rows = await this.#database.table(resolved.model).records(\n\t\t\t{\n\t\t\t\tconditions: [{ column: foreign, operator: 'any', values: keys, connector: 'and' }],\n\t\t\t},\n\t\t\toptions,\n\t\t)\n\t\tconst groups = groupRows(await this.#nest(resolved.model, rows, sub, options), foreign)\n\t\treturn records.map((record) => groups.get(String(readColumn(record, primary))) ?? [])\n\t}\n\n\tasync #loadOne(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedOne,\n\t\tsub: boolean | Include,\n\t\tprimary: string,\n\t\toptions?: OperationOptions,\n\t): Promise<Array<Row | undefined>> {\n\t\tconst groups = await this.#loadMany(records, resolved, sub, primary, options)\n\t\treturn groups.map((group) => (group.length > 0 ? group[0] : undefined))\n\t}\n\n\tasync #loadThrough(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedThrough,\n\t\tsub: boolean | Include,\n\t\tprimary: string,\n\t\toptions?: OperationOptions,\n\t): Promise<Array<readonly Row[]>> {\n\t\tconst source = resolved.source\n\t\tconst target = resolved.target\n\t\tconst parents = [\n\t\t\t...new Set(records.map((record) => readColumn(record, primary)).filter(isDefined)),\n\t\t]\n\t\tif (parents.length === 0) return records.map(() => [])\n\n\t\tconst junctions = await this.#database.table(resolved.through).records(\n\t\t\t{\n\t\t\t\tconditions: [{ column: source, operator: 'any', values: parents, connector: 'and' }],\n\t\t\t},\n\t\t\toptions,\n\t\t)\n\t\tconst targetsBySource = new Map<string, unknown[]>()\n\t\tfor (const junction of junctions) {\n\t\t\tconst value = readColumn(junction, target)\n\t\t\tif (!isDefined(value)) continue\n\t\t\tconst owner = String(readColumn(junction, source))\n\t\t\tconst list = targetsBySource.get(owner)\n\t\t\tif (list !== undefined) list.push(value)\n\t\t\telse targetsBySource.set(owner, [value])\n\t\t}\n\n\t\tconst targets = [...new Set([...targetsBySource.values()].flat())]\n\t\tif (targets.length === 0) return records.map(() => [])\n\t\tconst related = this.#database.table(resolved.model)\n\t\tconst rows = await related.records(\n\t\t\t{\n\t\t\t\tconditions: [\n\t\t\t\t\t{\n\t\t\t\t\t\tcolumn: related.primary,\n\t\t\t\t\t\toperator: 'any',\n\t\t\t\t\t\tvalues: targets,\n\t\t\t\t\t\tconnector: 'and',\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t\toptions,\n\t\t)\n\t\tconst index = indexRows(await this.#nest(resolved.model, rows, sub, options), related.primary)\n\n\t\treturn records.map((record) => {\n\t\t\tconst out: Row[] = []\n\t\t\tfor (const value of targetsBySource.get(String(readColumn(record, primary))) ?? []) {\n\t\t\t\tconst row = index.get(String(value))\n\t\t\t\tif (row !== undefined) out.push(row)\n\t\t\t}\n\t\t\treturn out\n\t\t})\n\t}\n\n\tasync #loadMorph(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedMorph,\n\t\tsub: boolean | Include,\n\t\tprimary: string,\n\t\toptions?: OperationOptions,\n\t): Promise<Array<readonly Row[]>> {\n\t\tconst foreign = resolved.key\n\t\tconst keys = [\n\t\t\t...new Set(records.map((record) => readColumn(record, primary)).filter(isDefined)),\n\t\t]\n\t\tif (keys.length === 0) return records.map(() => [])\n\t\tconst rows = await this.#database.table(resolved.model).records(\n\t\t\t{\n\t\t\t\tconditions: [\n\t\t\t\t\t{ column: foreign, operator: 'any', values: keys, connector: 'and' },\n\t\t\t\t\t{\n\t\t\t\t\t\tcolumn: resolved.tag,\n\t\t\t\t\t\toperator: 'equals',\n\t\t\t\t\t\tvalues: [resolved.label],\n\t\t\t\t\t\tconnector: 'and',\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t\toptions,\n\t\t)\n\t\tconst groups = groupRows(await this.#nest(resolved.model, rows, sub, options), foreign)\n\t\treturn records.map((record) => groups.get(String(readColumn(record, primary))) ?? [])\n\t}\n\n\t// Recursively load a nested include onto related rows (when `sub` is an Include).\n\tasync #nest(\n\t\tmodel: string,\n\t\trows: readonly Row[],\n\t\tsub: boolean | Include,\n\t\toptions?: OperationOptions,\n\t): Promise<readonly Row[]> {\n\t\tif (isBoolean(sub) || rows.length === 0) return rows\n\t\tconst context = this.#lookup(model)\n\t\tif (context === undefined) return rows\n\t\tconst props = await this.#populate(rows, sub, context.resolved, context.primary, options)\n\t\treturn rows.map((row, index) => Object.assign({}, row, props[index]))\n\t}\n}\n","import type { DatabaseInterface, RowOf, TableInterface, TableMap } from '@orkestrel/database'\nimport type {\n\tModelInterface,\n\tRelationContext,\n\tRelationManagerInterface,\n\tRelationManagerOptions,\n\tRelationMap,\n\tRelationsShape,\n\tResolvedRelation,\n} from './types.js'\nimport { RelationError } from './errors.js'\nimport { resolveRelationMap } from './helpers.js'\nimport { Model } from './Model.js'\n\n/**\n * Resolves a {@link RelationsShape} once at construction and vends a typed\n * {@link ModelInterface} per declared table.\n *\n * @remarks\n * Holds the database both at its precise type (to type each model's own table)\n * and at the broad `DatabaseInterface` (to fetch related tables by runtime name\n * while loading). Construction validates every target and junction against the\n * database's declared tables, so invalid definitions fail before an operation runs.\n * The `model` option's `on` and `error` are threaded into every model vended, and\n * each `model(name)` call constructs a handle owning its own emitter, so retain the\n * handle a subscription is taken on.\n *\n * @example\n * ```ts\n * import { RelationManager, hasMany } from '@orkestrel/relation'\n *\n * const manager = new RelationManager({\n * \tdatabase,\n * \trelations: { users: { posts: hasMany('author') } },\n * \tmodel: { on: { load: (name, count) => metrics.record(`relation.${name}`, count) } },\n * })\n * const users = manager.model('users')\n * const ada = await users.load('u1', { posts: true })\n * ```\n */\nexport class RelationManager<T extends TableMap = TableMap> implements RelationManagerInterface<T> {\n\treadonly #database: DatabaseInterface<T>\n\treadonly #broad: DatabaseInterface\n\treadonly #relations: RelationsShape<T>\n\treadonly #model: RelationManagerOptions['model']\n\treadonly #resolved = new Map<string, ReadonlyMap<string, ResolvedRelation>>()\n\n\t/**\n\t * Constructs a registry over a database and its relation definitions.\n\t *\n\t * @param options - The `database`, an optional `relations` map, and the optional\n\t * `model` emitter settings threaded into every model vended\n\t * @throws An `INVALID` {@link RelationError} when a relation targets a table or a\n\t * junction the database does not declare\n\t */\n\tconstructor(options: RelationManagerOptions<T>) {\n\t\tthis.#database = options.database\n\t\tthis.#broad = options.database\n\t\tthis.#relations = options.relations ?? {}\n\t\tthis.#model = options.model\n\t\tconst declared = new Set(Object.keys(this.#broad.export()))\n\t\tfor (const [name, map] of Object.entries(this.#relations)) {\n\t\t\tif (map === undefined) continue\n\t\t\tconst resolved = resolveRelationMap(map)\n\t\t\tfor (const [relation, entry] of resolved) {\n\t\t\t\tif (!declared.has(entry.model)) {\n\t\t\t\t\tthrow new RelationError(\n\t\t\t\t\t\t'INVALID',\n\t\t\t\t\t\t`Model '${name}' relation '${relation}' targets undeclared table '${entry.model}'`,\n\t\t\t\t\t\t{ model: name, relation, table: entry.model },\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tif (entry.relationship === 'through' && !declared.has(entry.through)) {\n\t\t\t\t\tthrow new RelationError(\n\t\t\t\t\t\t'INVALID',\n\t\t\t\t\t\t`Model '${name}' relation '${relation}' uses undeclared junction '${entry.through}'`,\n\t\t\t\t\t\t{ model: name, relation, table: entry.through },\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis.#resolved.set(name, resolved)\n\t\t}\n\t}\n\n\tget count(): number {\n\t\treturn this.#resolved.size\n\t}\n\n\tmodel<K extends keyof T & string>(name: K): ModelInterface<RowOf<T[K]>> {\n\t\tconst resolved = this.#resolved.get(name) ?? new Map<string, ResolvedRelation>()\n\t\tconst relations = this.#relations[name] ?? {}\n\t\treturn this.#vend(name, this.#database.table(name), resolved, relations)\n\t}\n\n\tnames(): readonly string[] {\n\t\treturn [...this.#resolved.keys()]\n\t}\n\n\thas(name: string): boolean {\n\t\treturn this.#resolved.has(name)\n\t}\n\n\t// Construct a model over an opaque row type `R`, so `RowOf<T[K]>` is not\n\t// expanded structurally here (the instantiation-depth guard `db.table` sidesteps).\n\t// The `model` option's hooks and error handler reach each vended handle's own emitter.\n\t#vend<R>(\n\t\tname: string,\n\t\ttable: TableInterface<R>,\n\t\tresolved: ReadonlyMap<string, ResolvedRelation>,\n\t\trelations: RelationMap,\n\t): ModelInterface<R> {\n\t\treturn new Model(\n\t\t\tname,\n\t\t\ttable,\n\t\t\tresolved,\n\t\t\trelations,\n\t\t\t(model) => this.#context(model),\n\t\t\tthis.#broad,\n\t\t\tthis.#model?.on,\n\t\t\tthis.#model?.error,\n\t\t)\n\t}\n\n\t// Look up a related model's resolved relations + primary, for nested loading.\n\t#context(model: string): RelationContext | undefined {\n\t\tconst resolved = this.#resolved.get(model)\n\t\tif (resolved === undefined) return undefined\n\t\treturn { resolved, primary: this.#broad.table(model).primary }\n\t}\n}\n","import type { RelationManagerInterface, RelationManagerOptions } from './types.js'\nimport type { TableMap } from '@orkestrel/database'\nimport { RelationManager } from './RelationManager.js'\n\n/**\n * Creates a {@link RelationManagerInterface} over a database and its relation map.\n *\n * @remarks\n * `relations` maps table names (constrained to the database's tables) to their\n * relation maps; build entries with `belongsTo` / `hasMany` / `hasOne` /\n * `hasThrough` / `hasMorph`. `manager.model(name)` returns the typed model for a\n * table — its own table is fully typed, related rows load at the `Row` type.\n *\n * @param options - The `database` and an optional `relations` map\n * @returns A typed {@link RelationManagerInterface}\n *\n * @example Defining relations\n * ```ts\n * import {\n * \tcreateRelationManager,\n * \tbelongsTo,\n * \thasMany,\n * \thasOne,\n * \thasThrough,\n * \thasMorph,\n * } from '@orkestrel/relation'\n *\n * const manager = createRelationManager({\n * \tdatabase: db,\n * \trelations: {\n * \t\taccounts: {\n * \t\t\tclassification: belongsTo('classificationId', 'classifications'), // foreign key on accounts\n * \t\t\tcontacts: hasMany('accountId'), // foreign key on contacts → accounts\n * \t\t\tprofile: hasOne('accountId', 'profiles'), // single, foreign key on profiles\n * \t\t\trepresentatives: hasThrough('accountReps', 'accountId', 'repId', 'representatives'), // through a junction\n * \t\t\tnotes: hasMorph('entityId', 'entityType', 'account', 'notes'), // polymorphic\n * \t\t},\n * \t\tcontacts: { account: belongsTo('accountId', 'accounts') },\n * \t},\n * })\n *\n * const acme = await manager.model('accounts').load('acc1', { contacts: true, classification: true })\n * ```\n */\nexport function createRelationManager<T extends TableMap>(\n\toptions: RelationManagerOptions<T>,\n): RelationManagerInterface<T> {\n\treturn new RelationManager(options)\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAkBA,IAAa,gBAAb,cAAmC,MAAM;CAC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AO,MAAM;IAAM,CAC7C;IAED,IAAI,MAAM,iBAAiB,aAAa,CAAC,SAAS,IAAI,MAAM,OAAO,GAClE,MAAM,IAAI,cACT,WACA,UAAU,KAAK,cAAc,SAAS,8BAA8B,MAAM,QAAQ,IAClF;KAAE,OAAO;KAAM;KAAU,OAAO,MAAM;IAAQ,CAC/C;GAEF;GACA,KAAK,UAAU,IAAI,MAAM,QAAQ;EAClC;CACD;CAEA,IAAI,QAAgB;EACnB,OAAO,KAAK,UAAU;CACvB;CAEA,MAAkC,MAAsC;EACvE,MAAM,WAAW,KAAK,UAAU,IAAI,IAAI,qBAAK,IAAI,IAA8B;EAC/E,MAAM,YAAY,KAAK,WAAW,SAAS,CAAC;EAC5C,OAAO,KAAK,MAAM,MAAM,KAAK,UAAU,MAAM,IAAI,GAAG,UAAU,SAAS;CACxE;CAEA,QAA2B;EAC1B,OAAO,CAAC,GAAG,KAAK,UAAU,KAAK,CAAC;CACjC;CAEA,IAAI,MAAuB;EAC1B,OAAO,KAAK,UAAU,IAAI,IAAI;CAC/B;CAKA,MACC,MACA,OACA,UACA,WACoB;EACpB,OAAO,IAAI,MACV,MACA,OACA,UACA,YACC,UAAU,KAAK,SAAS,KAAK,GAC9B,KAAK,QACL,KAAK,QAAQ,IACb,KAAK,QAAQ,KACd;CACD;CAGA,SAAS,OAA4C;EACpD,MAAM,WAAW,KAAK,UAAU,IAAI,KAAK;EACzC,IAAI,aAAa,KAAA,GAAW,OAAO,KAAA;EACnC,OAAO;GAAE;GAAU,SAAS,KAAK,OAAO,MAAM,KAAK,CAAC,CAAC;EAAQ;CAC9D;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACrFA,SAAgB,sBACf,SAC8B;CAC9B,OAAO,IAAI,gBAAgB,OAAO;AACnC"}
|
|
@@ -233,7 +233,7 @@ export declare function isRelationDescriptor(value: unknown): value is RelationD
|
|
|
233
233
|
* Narrows an unknown caught value to a {@link RelationError}.
|
|
234
234
|
*
|
|
235
235
|
* @param value - The value to test (typically a `catch` binding)
|
|
236
|
-
* @returns True if
|
|
236
|
+
* @returns True if the error carries its own identity brand and declared members; false otherwise
|
|
237
237
|
*/
|
|
238
238
|
export declare function isRelationError(value: unknown): value is RelationError;
|
|
239
239
|
|
package/dist/src/core/index.d.ts
CHANGED
|
@@ -233,7 +233,7 @@ export declare function isRelationDescriptor(value: unknown): value is RelationD
|
|
|
233
233
|
* Narrows an unknown caught value to a {@link RelationError}.
|
|
234
234
|
*
|
|
235
235
|
* @param value - The value to test (typically a `catch` binding)
|
|
236
|
-
* @returns True if
|
|
236
|
+
* @returns True if the error carries its own identity brand and declared members; false otherwise
|
|
237
237
|
*/
|
|
238
238
|
export declare function isRelationError(value: unknown): value is RelationError;
|
|
239
239
|
|
package/dist/src/core/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { isArray, isBoolean, isDefined,
|
|
1
|
+
import { INTRINSICS, holds, isArray, isBoolean, isDefined, isFunction, isObject, isRecord, isString, literalOf } from "@orkestrel/contract";
|
|
2
2
|
import { checkAbort, extractKey } from "@orkestrel/database";
|
|
3
3
|
import { Emitter } from "@orkestrel/emitter";
|
|
4
|
-
|
|
4
|
+
// src/core/errors.ts
|
|
5
5
|
/**
|
|
6
6
|
* Represents an error thrown by the relations layer, carrying a machine-readable
|
|
7
7
|
* {@link RelationErrorCode}.
|
|
@@ -18,6 +18,7 @@ var RelationError = class extends Error {
|
|
|
18
18
|
context;
|
|
19
19
|
constructor(code, message, context) {
|
|
20
20
|
super(message);
|
|
21
|
+
INTRINSICS.define(this, Symbol.for("@orkestrel/relation.RelationError"), { value: this });
|
|
21
22
|
this.name = "RelationError";
|
|
22
23
|
this.code = code;
|
|
23
24
|
if (context !== void 0) this.context = context;
|
|
@@ -27,13 +28,19 @@ var RelationError = class extends Error {
|
|
|
27
28
|
* Narrows an unknown caught value to a {@link RelationError}.
|
|
28
29
|
*
|
|
29
30
|
* @param value - The value to test (typically a `catch` binding)
|
|
30
|
-
* @returns True if
|
|
31
|
+
* @returns True if the error carries its own identity brand and declared members; false otherwise
|
|
31
32
|
*/
|
|
32
33
|
function isRelationError(value) {
|
|
33
|
-
return
|
|
34
|
+
return holds(() => {
|
|
35
|
+
if (!(value instanceof Error) || INTRINSICS.prototype(value) === Error.prototype) return false;
|
|
36
|
+
if (INTRINSICS.describe(value, Symbol.for("@orkestrel/relation.RelationError"))?.value !== value) return false;
|
|
37
|
+
const code = INTRINSICS.reflect.read(value, "code");
|
|
38
|
+
if (code !== "INVALID" && code !== "UNKNOWN_RELATION" && code !== "NOT_THROUGH") return false;
|
|
39
|
+
const context = INTRINSICS.reflect.read(value, "context");
|
|
40
|
+
return context === void 0 || isObject(context) || isFunction(context);
|
|
41
|
+
});
|
|
34
42
|
}
|
|
35
|
-
|
|
36
|
-
//#region src/core/validators.ts
|
|
43
|
+
// src/core/validators.ts
|
|
37
44
|
/**
|
|
38
45
|
* Narrows a value to a {@link RelationDescriptor} (the object form of a relation).
|
|
39
46
|
*
|
|
@@ -72,8 +79,7 @@ function isRelationDescriptor(value) {
|
|
|
72
79
|
]) if (member in value && !isString(value[member])) return false;
|
|
73
80
|
return true;
|
|
74
81
|
}
|
|
75
|
-
|
|
76
|
-
//#region src/core/helpers.ts
|
|
82
|
+
// src/core/helpers.ts
|
|
77
83
|
/**
|
|
78
84
|
* Resolves one raw {@link Relation} value into a flat {@link ResolvedRelation}.
|
|
79
85
|
*
|
|
@@ -109,13 +115,8 @@ function resolveRelation(name, value) {
|
|
|
109
115
|
}
|
|
110
116
|
if (!isRelationDescriptor(value)) throw new RelationError("INVALID", `Relation '${name}': not a string, array, or descriptor`, { relation: name });
|
|
111
117
|
const model = value.model ?? name;
|
|
112
|
-
|
|
113
|
-
if (
|
|
114
|
-
else if (isDefined(value.through)) relationship = "through";
|
|
115
|
-
else if (isDefined(value.tag)) relationship = "morph";
|
|
116
|
-
else if (isDefined(value.column)) relationship = "belongs";
|
|
117
|
-
else if (isDefined(value.key)) relationship = "one";
|
|
118
|
-
else throw new RelationError("INVALID", `Relation '${name}': cannot infer relationship from descriptor`, { relation: name });
|
|
118
|
+
const relationship = value.relationship !== void 0 ? value.relationship : isDefined(value.through) ? "through" : isDefined(value.tag) ? "morph" : isDefined(value.column) ? "belongs" : isDefined(value.key) ? "one" : void 0;
|
|
119
|
+
if (relationship === void 0) throw new RelationError("INVALID", `Relation '${name}': cannot infer relationship from descriptor`, { relation: name });
|
|
119
120
|
switch (relationship) {
|
|
120
121
|
case "belongs": {
|
|
121
122
|
const column = value.column;
|
|
@@ -180,9 +181,7 @@ function resolveRelation(name, value) {
|
|
|
180
181
|
* @returns A map keyed by relation name
|
|
181
182
|
*/
|
|
182
183
|
function resolveRelationMap(relations) {
|
|
183
|
-
|
|
184
|
-
for (const [name, value] of Object.entries(relations)) resolved.set(name, resolveRelation(name, value));
|
|
185
|
-
return resolved;
|
|
184
|
+
return new Map(Object.entries(relations).map(([name, value]) => [name, resolveRelation(name, value)]));
|
|
186
185
|
}
|
|
187
186
|
/**
|
|
188
187
|
* Reads one column off any record, whatever its declared type.
|
|
@@ -221,10 +220,7 @@ function readColumn(record, column) {
|
|
|
221
220
|
* ```
|
|
222
221
|
*/
|
|
223
222
|
function countAttached(values) {
|
|
224
|
-
|
|
225
|
-
for (const value of values) if (isArray(value)) total += value.length;
|
|
226
|
-
else if (value !== void 0) total += 1;
|
|
227
|
-
return total;
|
|
223
|
+
return Iterator.from(values).reduce((total, value) => total + (isArray(value) ? value.length : value === void 0 ? 0 : 1), 0);
|
|
228
224
|
}
|
|
229
225
|
/**
|
|
230
226
|
* Indexes rows by the string form of one column, for keyed lookups.
|
|
@@ -246,9 +242,7 @@ function countAttached(values) {
|
|
|
246
242
|
* ```
|
|
247
243
|
*/
|
|
248
244
|
function indexRows(rows, column) {
|
|
249
|
-
|
|
250
|
-
for (const row of rows) index.set(String(readColumn(row, column)), row);
|
|
251
|
-
return index;
|
|
245
|
+
return new Map(Iterator.from(rows).map((row) => [String(readColumn(row, column)), row]));
|
|
252
246
|
}
|
|
253
247
|
/**
|
|
254
248
|
* Groups rows by the string form of one column, for one-to-many lookups.
|
|
@@ -375,8 +369,7 @@ function hasMorph(key, tag, label, model) {
|
|
|
375
369
|
...model !== void 0 ? { model } : {}
|
|
376
370
|
};
|
|
377
371
|
}
|
|
378
|
-
|
|
379
|
-
//#region src/core/Model.ts
|
|
372
|
+
// src/core/Model.ts
|
|
380
373
|
/**
|
|
381
374
|
* Pairs a typed table with relation-aware `load` / `find` and junction management.
|
|
382
375
|
*
|
|
@@ -467,9 +460,8 @@ var Model = class {
|
|
|
467
460
|
if (isArray(keys)) {
|
|
468
461
|
const bases = await this.#table.get(keys);
|
|
469
462
|
const present = bases.filter(isDefined);
|
|
470
|
-
const
|
|
471
|
-
|
|
472
|
-
return bases.map((base) => base === void 0 ? void 0 : Object.assign({}, base, props[next++]));
|
|
463
|
+
const attachments = (await this.#populate(present, include, this.#resolved, this.#table.primary, options)).values();
|
|
464
|
+
return bases.map((base) => base === void 0 ? void 0 : Object.assign({}, base, attachments.next().value));
|
|
473
465
|
}
|
|
474
466
|
const base = await this.#table.get(keys);
|
|
475
467
|
if (base === void 0) return void 0;
|
|
@@ -687,8 +679,7 @@ var Model = class {
|
|
|
687
679
|
return rows.map((row, index) => Object.assign({}, row, props[index]));
|
|
688
680
|
}
|
|
689
681
|
};
|
|
690
|
-
|
|
691
|
-
//#region src/core/RelationManager.ts
|
|
682
|
+
// src/core/RelationManager.ts
|
|
692
683
|
/**
|
|
693
684
|
* Resolves a {@link RelationsShape} once at construction and vends a typed
|
|
694
685
|
* {@link ModelInterface} per declared table.
|
|
@@ -779,8 +770,7 @@ var RelationManager = class {
|
|
|
779
770
|
};
|
|
780
771
|
}
|
|
781
772
|
};
|
|
782
|
-
|
|
783
|
-
//#region src/core/factories.ts
|
|
773
|
+
// src/core/factories.ts
|
|
784
774
|
/**
|
|
785
775
|
* Creates a {@link RelationManagerInterface} over a database and its relation map.
|
|
786
776
|
*
|
|
@@ -824,7 +814,6 @@ var RelationManager = class {
|
|
|
824
814
|
function createRelationManager(options) {
|
|
825
815
|
return new RelationManager(options);
|
|
826
816
|
}
|
|
827
|
-
//#endregion
|
|
828
817
|
export { Model, RelationError, RelationManager, belongsTo, countAttached, createRelationManager, groupRows, hasMany, hasMorph, hasOne, hasThrough, indexRows, isRelationDescriptor, isRelationError, readColumn, resolveRelation, resolveRelationMap };
|
|
829
818
|
|
|
830
819
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../src/core/errors.ts","../../../src/core/validators.ts","../../../src/core/helpers.ts","../../../src/core/Model.ts","../../../src/core/RelationManager.ts","../../../src/core/factories.ts"],"sourcesContent":["import type { RelationErrorCode } from './types.js'\nimport { isInstance } from '@orkestrel/contract'\n\n// Invalid relation definitions and misuse `throw` a `RelationError` carrying a\n// machine-readable `code`, so a `catch` branches on `error.code`\n// (`.claude/rules/typescript.md` § Errors and outcomes).\n\n/**\n * Represents an error thrown by the relations layer, carrying a machine-readable\n * {@link RelationErrorCode}.\n *\n * @remarks\n * Thrown for: a relation value whose relationship cannot be inferred (`INVALID`), a\n * relation targeting a table or junction the database does not declare, raised when\n * the manager is created (`INVALID`), a reference to a relation a model does not\n * define (`UNKNOWN_RELATION`), and `link` / `unlink` / `links` on a relation that is\n * not a `through` (`NOT_THROUGH`).\n */\nexport class RelationError extends Error {\n\treadonly code: RelationErrorCode\n\treadonly context?: Readonly<Record<string, unknown>>\n\n\tconstructor(\n\t\tcode: RelationErrorCode,\n\t\tmessage: string,\n\t\tcontext?: Readonly<Record<string, unknown>>,\n\t) {\n\t\tsuper(message)\n\t\tthis.name = 'RelationError'\n\t\tthis.code = code\n\t\tif (context !== undefined) this.context = context\n\t}\n}\n\n/**\n * Narrows an unknown caught value to a {@link RelationError}.\n *\n * @param value - The value to test (typically a `catch` binding)\n * @returns True if `value` is a {@link RelationError}; false otherwise\n */\nexport function isRelationError(value: unknown): value is RelationError {\n\treturn isInstance(value, RelationError)\n}\n","import type { RelationDescriptor } from './types.js'\nimport { isRecord, isString, literalOf } from '@orkestrel/contract'\n\n// === Descriptor guard\n\n/**\n * Narrows a value to a {@link RelationDescriptor} (the object form of a relation).\n *\n * @remarks\n * A record satisfies the descriptor when every member it declares carries its declared\n * type: `relationship` is one of the `Relationship` values, and `column`, `key`,\n * `through`, `source`, `target`, `tag`, `label`, and `model` are strings. A member the\n * record omits is unconstrained, a member present with an `undefined` value is refused,\n * and a member the descriptor does not declare is carried without being checked. This\n * is what lets `resolveRelation` read each member after one narrow and report a\n * malformed definition as an `INVALID` `RelationError` instead of resolving a\n * wrong-typed column into an arm that declares it a string.\n *\n * @param value - The value to test\n * @returns True if `value` is a record whose every declared member holds its declared\n * type; false otherwise\n *\n * @example\n * ```ts\n * isRelationDescriptor(belongsTo('accountId')) // true\n * isRelationDescriptor({ column: 42 }) // false — `column` is declared a string\n * ```\n */\nexport function isRelationDescriptor(value: unknown): value is RelationDescriptor {\n\tif (!isRecord(value)) return false\n\tif (\n\t\t'relationship' in value &&\n\t\t!literalOf('belongs', 'many', 'one', 'through', 'morph')(value.relationship)\n\t) {\n\t\treturn false\n\t}\n\tfor (const member of ['column', 'key', 'through', 'source', 'target', 'tag', 'label', 'model']) {\n\t\tif (member in value && !isString(value[member])) return false\n\t}\n\treturn true\n}\n","import type {\n\tRelation,\n\tRelationDescriptor,\n\tRelationMap,\n\tRelationship,\n\tResolvedRelation,\n} from './types.js'\nimport type { Row } from '@orkestrel/database'\nimport { isArray, isDefined, isObject, isString } from '@orkestrel/contract'\nimport { isRelationDescriptor } from './validators.js'\nimport { RelationError } from './errors.js'\n\n// Resolve raw relation values into the flat `ResolvedRelation` form once, at\n// define-time, so no inference runs during loading. The builders in this file set\n// an explicit `relationship`; hand-written descriptors fall back to field inference.\n\n// === Resolution\n\n/**\n * Resolves one raw {@link Relation} value into a flat {@link ResolvedRelation}.\n *\n * @remarks\n * A `string` is a `belongs` (foreign-key column on this table); a `readonly string[]`\n * is a `many` (foreign-key column on the related table); a {@link RelationDescriptor}\n * uses its explicit `relationship`, or infers it from the fields present. The target\n * model defaults to the relation name. Every column the resolved arm declares is\n * validated here, which is what lets each arm declare its columns required.\n *\n * @param name - The relation name (its key in the {@link RelationMap})\n * @param value - The raw relation value\n * @returns The resolved relation, on the arm its `relationship` names\n * @throws An `INVALID` {@link RelationError} when the relationship cannot be resolved, or when a\n * column the resolved arm declares is missing\n */\nexport function resolveRelation(name: string, value: Relation): ResolvedRelation {\n\tif (isString(value)) {\n\t\treturn { relationship: 'belongs', name, model: name, column: value }\n\t}\n\tif (isArray(value)) {\n\t\tconst key = value[0]\n\t\tif (!isString(key)) {\n\t\t\tthrow new RelationError(\n\t\t\t\t'INVALID',\n\t\t\t\t`Relation '${name}': array form needs a string FK column`,\n\t\t\t\t{\n\t\t\t\t\trelation: name,\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t\treturn { relationship: 'many', name, model: name, key }\n\t}\n\tif (!isRelationDescriptor(value)) {\n\t\tthrow new RelationError('INVALID', `Relation '${name}': not a string, array, or descriptor`, {\n\t\t\trelation: name,\n\t\t})\n\t}\n\n\tconst model = value.model ?? name\n\t// Inferred from the fields present when no explicit `relationship` is set.\n\tlet relationship: Relationship\n\tif (value.relationship !== undefined) {\n\t\trelationship = value.relationship\n\t} else if (isDefined(value.through)) {\n\t\trelationship = 'through'\n\t} else if (isDefined(value.tag)) {\n\t\trelationship = 'morph'\n\t} else if (isDefined(value.column)) {\n\t\trelationship = 'belongs'\n\t} else if (isDefined(value.key)) {\n\t\trelationship = 'one'\n\t} else {\n\t\tthrow new RelationError(\n\t\t\t'INVALID',\n\t\t\t`Relation '${name}': cannot infer relationship from descriptor`,\n\t\t\t{ relation: name },\n\t\t)\n\t}\n\n\tswitch (relationship) {\n\t\tcase 'belongs': {\n\t\t\tconst column = value.column\n\t\t\tif (column === undefined) {\n\t\t\t\tthrow new RelationError('INVALID', `Relation '${name}': belongs needs 'column'`, {\n\t\t\t\t\trelation: name,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn { relationship, name, model, column }\n\t\t}\n\t\tcase 'many': {\n\t\t\tconst key = value.key\n\t\t\tif (key === undefined) {\n\t\t\t\tthrow new RelationError('INVALID', `Relation '${name}': many needs 'key'`, {\n\t\t\t\t\trelation: name,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn { relationship, name, model, key }\n\t\t}\n\t\tcase 'one': {\n\t\t\tconst key = value.key\n\t\t\tif (key === undefined) {\n\t\t\t\tthrow new RelationError('INVALID', `Relation '${name}': one needs 'key'`, {\n\t\t\t\t\trelation: name,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn { relationship, name, model, key }\n\t\t}\n\t\tcase 'through': {\n\t\t\tconst { through, source, target } = value\n\t\t\tif (through === undefined || source === undefined || target === undefined) {\n\t\t\t\tthrow new RelationError(\n\t\t\t\t\t'INVALID',\n\t\t\t\t\t`Relation '${name}': through needs 'through', 'source', and 'target'`,\n\t\t\t\t\t{ relation: name },\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn {\n\t\t\t\trelationship,\n\t\t\t\tname,\n\t\t\t\tmodel,\n\t\t\t\tthrough,\n\t\t\t\tsource,\n\t\t\t\ttarget,\n\t\t\t}\n\t\t}\n\t\tcase 'morph': {\n\t\t\tconst { key, tag, label } = value\n\t\t\tif (key === undefined || tag === undefined || label === undefined) {\n\t\t\t\tthrow new RelationError(\n\t\t\t\t\t'INVALID',\n\t\t\t\t\t`Relation '${name}': morph needs 'key', 'tag', and 'label'`,\n\t\t\t\t\t{ relation: name },\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn { relationship, name, model, key, tag, label }\n\t\t}\n\t}\n}\n\n/**\n * Resolves every entry of a {@link RelationMap} into a name → {@link ResolvedRelation} map.\n *\n * @param relations - The raw relation map\n * @returns A map keyed by relation name\n */\nexport function resolveRelationMap(relations: RelationMap): ReadonlyMap<string, ResolvedRelation> {\n\tconst resolved = new Map<string, ResolvedRelation>()\n\tfor (const [name, value] of Object.entries(relations)) {\n\t\tresolved.set(name, resolveRelation(name, value))\n\t}\n\treturn resolved\n}\n\n// === Row projection\n\n/**\n * Reads one column off any record, whatever its declared type.\n *\n * @remarks\n * A base row's type is closed, so the column is read with `Reflect.get` rather than\n * index access. Anything that is not an object reads as `undefined`.\n *\n * @param record - The record to read\n * @param column - The column name\n * @returns The column's value, or `undefined` when `record` is not an object\n *\n * @example\n * ```ts\n * readColumn({ accountId: 'acc1' }, 'accountId') // 'acc1'\n * ```\n */\nexport function readColumn(record: unknown, column: string): unknown {\n\tif (!isObject(record)) return undefined\n\treturn Reflect.get(record, column)\n}\n\n/**\n * Counts the related rows one relation attached across a record set.\n *\n * @remarks\n * An array-valued relation (`many` / `through` / `morph`) sums its lengths; a\n * single-valued one (`belongs` / `one`) counts each present row. This is the count a\n * `Model` carries on its `load` event.\n *\n * @param values - One relation's loaded value per record\n * @returns The total related rows attached across the set\n *\n * @example\n * ```ts\n * countAttached([[{ id: 'p1' }, { id: 'p2' }], undefined, { id: 'p3' }]) // 3\n * ```\n */\nexport function countAttached(values: ReadonlyArray<Row | readonly Row[] | undefined>): number {\n\tlet total = 0\n\tfor (const value of values) {\n\t\tif (isArray(value)) total += value.length\n\t\telse if (value !== undefined) total += 1\n\t}\n\treturn total\n}\n\n/**\n * Indexes rows by the string form of one column, for keyed lookups.\n *\n * @remarks\n * The column is read with {@link readColumn} and its value stringified, so a numeric\n * and a string foreign key meet at the same entry. A later row with a key an earlier\n * row already holds replaces it, and a row missing the column indexes under the string\n * `'undefined'`. This is the projection a `belongs` load and a `through` load use to\n * attach one related row per key.\n *\n * @param rows - The rows to index\n * @param column - The column to key on\n * @returns A read-only map from each key's string form to its row\n *\n * @example\n * ```ts\n * indexRows([{ id: 'r1' }, { id: 'r2' }], 'id').get('r1') // { id: 'r1' }\n * ```\n */\nexport function indexRows(rows: readonly Row[], column: string): ReadonlyMap<string, Row> {\n\tconst index = new Map<string, Row>()\n\tfor (const row of rows) index.set(String(readColumn(row, column)), row)\n\treturn index\n}\n\n/**\n * Groups rows by the string form of one column, for one-to-many lookups.\n *\n * @remarks\n * The column is read with {@link readColumn} and its value stringified, so a numeric\n * and a string foreign key meet at the same group. Rows keep their input order inside\n * a group, a key no row carries is absent rather than empty, and a row missing the\n * column groups under the string `'undefined'`. This is the projection a `many` load\n * and a `morph` load use to attach every related row per key.\n *\n * @param rows - The rows to group\n * @param column - The column to key on\n * @returns A read-only map from each key's string form to its rows, in input order\n *\n * @example\n * ```ts\n * groupRows([{ author: 'u1' }, { author: 'u1' }], 'author').get('u1')?.length // 2\n * ```\n */\nexport function groupRows(\n\trows: readonly Row[],\n\tcolumn: string,\n): ReadonlyMap<string, readonly Row[]> {\n\tconst groups = new Map<string, Row[]>()\n\tfor (const row of rows) {\n\t\tconst key = String(readColumn(row, column))\n\t\tconst group = groups.get(key)\n\t\tif (group !== undefined) group.push(row)\n\t\telse groups.set(key, [row])\n\t}\n\treturn groups\n}\n\n// === Builders\n\n/**\n * Builds a `belongs` relation — a foreign key on the owning table points at the related row\n * (single).\n *\n * @param column - The foreign-key column on this table\n * @param model - Target table name (defaults to the relation name)\n * @returns A {@link RelationDescriptor}\n *\n * @example\n * ```ts\n * { classification: belongsTo('classificationId', 'classifications') }\n * ```\n */\nexport function belongsTo(column: string, model?: string): RelationDescriptor {\n\treturn { relationship: 'belongs', column, ...(model !== undefined ? { model } : {}) }\n}\n\n/**\n * Builds a `many` relation — a foreign key on the related table points back at the owning row\n * (array).\n *\n * @param key - The foreign-key column on the related table\n * @param model - Target table name (defaults to the relation name)\n * @returns A {@link RelationDescriptor}\n */\nexport function hasMany(key: string, model?: string): RelationDescriptor {\n\treturn { relationship: 'many', key, ...(model !== undefined ? { model } : {}) }\n}\n\n/**\n * Builds a `one` relation — like {@link hasMany}, but a single related row.\n *\n * @param key - The foreign-key column on the related table\n * @param model - Target table name (defaults to the relation name)\n * @returns A {@link RelationDescriptor}\n */\nexport function hasOne(key: string, model?: string): RelationDescriptor {\n\treturn { relationship: 'one', key, ...(model !== undefined ? { model } : {}) }\n}\n\n/**\n * Builds a `through` relation — a junction table links the two sides (many-to-many).\n *\n * @param through - The junction table name\n * @param source - The junction foreign-key column pointing at the owning model\n * @param target - The junction foreign-key column pointing at the related model\n * @param model - Target table name (defaults to the relation name)\n * @returns A {@link RelationDescriptor}\n *\n * @example\n * ```ts\n * { reps: hasThrough('accountReps', 'accountId', 'repId', 'reps') }\n * ```\n */\nexport function hasThrough(\n\tthrough: string,\n\tsource: string,\n\ttarget: string,\n\tmodel?: string,\n): RelationDescriptor {\n\treturn {\n\t\trelationship: 'through',\n\t\tthrough,\n\t\tsource,\n\t\ttarget,\n\t\t...(model !== undefined ? { model } : {}),\n\t}\n}\n\n/**\n * Builds a `morph` relation — a polymorphic foreign key plus a discriminator column on the\n * related table (array).\n *\n * @param key - The foreign-key column on the related table\n * @param tag - The discriminator column on the related table\n * @param label - The discriminator value identifying the owning model\n * @param model - Target table name (defaults to the relation name)\n * @returns A {@link RelationDescriptor}\n *\n * @example\n * ```ts\n * { notes: hasMorph('entityId', 'entityType', 'account', 'notes') }\n * ```\n */\nexport function hasMorph(\n\tkey: string,\n\ttag: string,\n\tlabel: string,\n\tmodel?: string,\n): RelationDescriptor {\n\treturn { relationship: 'morph', key, tag, label, ...(model !== undefined ? { model } : {}) }\n}\n","import type {\n\tDatabaseInterface,\n\tKey,\n\tOperationOptions,\n\tRow,\n\tTableInterface,\n} from '@orkestrel/database'\nimport type { EmitterErrorHandler, EmitterHooks, EmitterInterface } from '@orkestrel/emitter'\nimport type {\n\tFindOptions,\n\tInclude,\n\tLoaded,\n\tLoadedMap,\n\tModelEventMap,\n\tModelInterface,\n\tRelationContext,\n\tRelationMap,\n\tResolvedBelongs,\n\tResolvedMany,\n\tResolvedMorph,\n\tResolvedOne,\n\tResolvedRelation,\n\tResolvedThrough,\n} from './types.js'\nimport { checkAbort, extractKey } from '@orkestrel/database'\nimport { Emitter } from '@orkestrel/emitter'\nimport { isArray, isBoolean, isDefined } from '@orkestrel/contract'\nimport { countAttached, groupRows, indexRows, readColumn } from './helpers.js'\nimport { RelationError } from './errors.js'\n\n/**\n * Pairs a typed table with relation-aware `load` / `find` and junction management.\n *\n * @remarks\n * The model's own table is fully typed (`table`); related tables are reached by\n * runtime name through the database at the broad `Row` type. Loading is batched:\n * a direct relation uses one query for the whole record set, while a `through`\n * relation uses two (junction then target); both counts remain constant regardless\n * of parent count. Nested includes recurse through the registry `lookup`, so each\n * nested level is batched again. Columns are read with `Reflect.get` (the base row's\n * type is closed) and relation properties merged with `Object.assign` — no `as`.\n *\n * @remarks\n * - **Observable.** The owned {@link emitter} ({@link ModelEventMap}) carries the\n * eager-load + junction moments — `load` (a relation resolved: its name + the count of\n * related rows attached across the whole record set), `link` / `unlink` (a junction row\n * written) — for fire-and-forget observers. Every event is emitted directly, strictly\n * after the load resolves and after the junction operation completes; the emitter\n * isolates a listener throw and routes it to its `error` handler (the `error` option),\n * so a buggy observer can never corrupt the batched eager-load (no N+1 in the events\n * either — one `load` per relation, not per record).\n *\n * @example\n * ```ts\n * import { Model, resolveRelationMap, hasMany } from '@orkestrel/relation'\n *\n * const relations = { posts: hasMany('author') }\n * const users = new Model(\n * \t'users',\n * \tdatabase.table('users'),\n * \tresolveRelationMap(relations),\n * \trelations,\n * \t() => undefined,\n * \tdatabase,\n * )\n * users.emitter.on('load', (name, count) => metrics.record(`relation.${name}`, count))\n * const ada = await users.load('u1', { posts: true })\n * ```\n */\nexport class Model<T = Row> implements ModelInterface<T> {\n\treadonly #name: string\n\treadonly #table: TableInterface<T>\n\treadonly #resolved: ReadonlyMap<string, ResolvedRelation>\n\treadonly #relations: RelationMap\n\treadonly #lookup: (model: string) => RelationContext | undefined\n\treadonly #database: DatabaseInterface\n\t// The push observation surface — owned, never inherited. The emitter isolates a\n\t// listener throw (routing it to the `error` handler), so it can never escape into the\n\t// batched eager-load.\n\treadonly #emitter: Emitter<ModelEventMap>\n\n\t/**\n\t * Constructs a model over one table and its resolved relations.\n\t *\n\t * @param name - The model's table name\n\t * @param table - The typed table this model's own reads and writes go through\n\t * @param resolved - The model's relations, resolved by `resolveRelationMap`\n\t * @param relations - The raw relation map the resolved relations came from\n\t * @param lookup - Reads a related model's {@link RelationContext} for a nested include,\n\t * and returns `undefined` for a model the registry does not hold\n\t * @param database - The broad database used to read related and junction tables by name\n\t * @param on - Initial {@link ModelEventMap} listeners\n\t * @param error - Receives a listener throw as `(error, event)`. Default: the throw is\n\t * swallowed.\n\t */\n\tconstructor(\n\t\tname: string,\n\t\ttable: TableInterface<T>,\n\t\tresolved: ReadonlyMap<string, ResolvedRelation>,\n\t\trelations: RelationMap,\n\t\tlookup: (model: string) => RelationContext | undefined,\n\t\tdatabase: DatabaseInterface,\n\t\ton?: EmitterHooks<ModelEventMap>,\n\t\terror?: EmitterErrorHandler,\n\t) {\n\t\tthis.#name = name\n\t\tthis.#table = table\n\t\tthis.#resolved = resolved\n\t\tthis.#relations = relations\n\t\tthis.#lookup = lookup\n\t\tthis.#database = database\n\t\tthis.#emitter = new Emitter<ModelEventMap>({\n\t\t\t...(on !== undefined ? { on } : {}),\n\t\t\t...(error !== undefined ? { error } : {}),\n\t\t})\n\t}\n\n\tget emitter(): EmitterInterface<ModelEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tget name(): string {\n\t\treturn this.#name\n\t}\n\n\tget table(): TableInterface<T> {\n\t\treturn this.#table\n\t}\n\n\tget relations(): RelationMap {\n\t\treturn this.#relations\n\t}\n\n\tload(key: Key, include: Include, options?: OperationOptions): Promise<Loaded<T> | undefined>\n\tload(\n\t\tkeys: readonly Key[],\n\t\tinclude: Include,\n\t\toptions?: OperationOptions,\n\t): Promise<ReadonlyArray<Loaded<T> | undefined>>\n\tasync load(\n\t\tkeys: Key | readonly Key[],\n\t\tinclude: Include,\n\t\toptions?: OperationOptions,\n\t): Promise<(Loaded<T> | undefined) | ReadonlyArray<Loaded<T> | undefined>> {\n\t\tcheckAbort(options?.signal)\n\t\tif (isArray(keys)) {\n\t\t\t// Batch: one `get`, then one populate over all present rows (no N+1).\n\t\t\tconst bases = await this.#table.get(keys)\n\t\t\tconst present = bases.filter(isDefined)\n\t\t\tconst props = await this.#populate(\n\t\t\t\tpresent,\n\t\t\t\tinclude,\n\t\t\t\tthis.#resolved,\n\t\t\t\tthis.#table.primary,\n\t\t\t\toptions,\n\t\t\t)\n\t\t\tlet next = 0\n\t\t\treturn bases.map((base) =>\n\t\t\t\tbase === undefined ? undefined : Object.assign({}, base, props[next++]),\n\t\t\t)\n\t\t}\n\t\tconst base = await this.#table.get(keys)\n\t\tif (base === undefined) return undefined\n\t\tconst [props] = await this.#populate(\n\t\t\t[base],\n\t\t\tinclude,\n\t\t\tthis.#resolved,\n\t\t\tthis.#table.primary,\n\t\t\toptions,\n\t\t)\n\t\treturn Object.assign({}, base, props)\n\t}\n\n\tasync find(include: Include, options?: FindOptions): Promise<ReadonlyArray<Loaded<T>>> {\n\t\tcheckAbort(options?.signal)\n\t\tconst records = await this.#table.records(\n\t\t\t{\n\t\t\t\t...(options?.sort !== undefined\n\t\t\t\t\t? {\n\t\t\t\t\t\t\torder: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tcolumn: options.sort,\n\t\t\t\t\t\t\t\t\tdirection: options.direction ?? 'ascending',\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t\t...(options?.offset !== undefined ? { offset: options.offset } : {}),\n\t\t\t\t...(options?.limit !== undefined ? { limit: options.limit } : {}),\n\t\t\t},\n\t\t\toptions,\n\t\t)\n\t\tconst props = await this.#populate(\n\t\t\trecords,\n\t\t\tinclude,\n\t\t\tthis.#resolved,\n\t\t\tthis.#table.primary,\n\t\t\toptions,\n\t\t)\n\t\treturn records.map((record, index) => Object.assign({}, record, props[index]))\n\t}\n\n\tasync link(key: Key, relation: string, target: Key, options?: OperationOptions): Promise<void> {\n\t\tcheckAbort(options?.signal)\n\t\tconst resolved = this.#through(relation)\n\t\tconst junction = this.#database.table(resolved.through)\n\t\tconst existing = await junction.count(\n\t\t\t{\n\t\t\t\tconditions: [\n\t\t\t\t\t{ column: resolved.source, operator: 'equals', values: [key], connector: 'and' },\n\t\t\t\t\t{ column: resolved.target, operator: 'equals', values: [target], connector: 'and' },\n\t\t\t\t],\n\t\t\t},\n\t\t\toptions,\n\t\t)\n\t\tif (existing > 0) return\n\t\tawait junction.set({ [resolved.source]: key, [resolved.target]: target }, options)\n\t\t// Observe the inserted junction row — strictly after the driver write, so a swallowed\n\t\t// listener throw can't perturb the link (carries the owning key + the relation name).\n\t\tthis.#emitter.emit('link', key, relation)\n\t}\n\n\tasync unlink(key: Key, relation: string, target: Key, options?: OperationOptions): Promise<void> {\n\t\tcheckAbort(options?.signal)\n\t\tconst resolved = this.#through(relation)\n\t\tconst junction = this.#database.table(resolved.through)\n\t\tconst rows = await junction.records(\n\t\t\t{\n\t\t\t\tconditions: [\n\t\t\t\t\t{\n\t\t\t\t\t\tcolumn: resolved.source,\n\t\t\t\t\t\toperator: 'equals',\n\t\t\t\t\t\tvalues: [key],\n\t\t\t\t\t\tconnector: 'and',\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tcolumn: resolved.target,\n\t\t\t\t\t\toperator: 'equals',\n\t\t\t\t\t\tvalues: [target],\n\t\t\t\t\t\tconnector: 'and',\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t\toptions,\n\t\t)\n\t\tawait this.#database.transaction(async (transaction) => {\n\t\t\tconst scoped = transaction.table(resolved.through)\n\t\t\tfor (const row of rows) {\n\t\t\t\tconst id = extractKey(row, junction.primary)\n\t\t\t\tif (id !== undefined) await scoped.remove(id, options)\n\t\t\t}\n\t\t}, options)\n\t\t// Observe the removal only after the transaction commits.\n\t\tthis.#emitter.emit('unlink', key, relation)\n\t}\n\n\tasync links(key: Key, relation: string, options?: OperationOptions): Promise<readonly Key[]> {\n\t\tcheckAbort(options?.signal)\n\t\tconst resolved = this.#through(relation)\n\t\tconst junction = this.#database.table(resolved.through)\n\t\tconst rows = await junction.records(\n\t\t\t{\n\t\t\t\tconditions: [\n\t\t\t\t\t{\n\t\t\t\t\t\tcolumn: resolved.source,\n\t\t\t\t\t\toperator: 'equals',\n\t\t\t\t\t\tvalues: [key],\n\t\t\t\t\t\tconnector: 'and',\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t\toptions,\n\t\t)\n\t\tconst target = resolved.target\n\t\tconst keys: Key[] = []\n\t\tfor (const row of rows) {\n\t\t\tconst value = extractKey(row, target)\n\t\t\tif (value !== undefined) keys.push(value)\n\t\t}\n\t\treturn keys\n\t}\n\n\t// === Private\n\n\t// Resolve a `through` relation by name to its own arm, or throw a descriptive error.\n\t#through(relation: string): ResolvedThrough {\n\t\tconst resolved = this.#resolved.get(relation)\n\t\tif (resolved === undefined) {\n\t\t\tthrow new RelationError(\n\t\t\t\t'UNKNOWN_RELATION',\n\t\t\t\t`Model '${this.#name}' has no relation '${relation}'`,\n\t\t\t\t{ model: this.#name, relation },\n\t\t\t)\n\t\t}\n\t\tif (resolved.relationship !== 'through') {\n\t\t\tthrow new RelationError(\n\t\t\t\t'NOT_THROUGH',\n\t\t\t\t`Relation '${relation}' on '${this.#name}' is not a through`,\n\t\t\t\t{ model: this.#name, relation },\n\t\t\t)\n\t\t}\n\t\treturn resolved\n\t}\n\n\t// Compute the relation properties for each record (parallel to `records`).\n\tasync #populate(\n\t\trecords: readonly unknown[],\n\t\tinclude: Include,\n\t\tresolvedMap: ReadonlyMap<string, ResolvedRelation>,\n\t\tprimary: string,\n\t\toptions?: OperationOptions,\n\t): Promise<LoadedMap[]> {\n\t\tcheckAbort(options?.signal)\n\t\tconst props: LoadedMap[] = records.map(() => ({}))\n\t\tfor (const [name, sub] of Object.entries(include)) {\n\t\t\tif (sub === false) continue\n\t\t\tcheckAbort(options?.signal)\n\t\t\tconst resolved = resolvedMap.get(name)\n\t\t\tif (resolved === undefined) continue\n\t\t\tconst values = await this.#load(records, resolved, sub, primary, options)\n\t\t\tvalues.forEach((value, index) => {\n\t\t\t\tconst target = props[index]\n\t\t\t\tif (target !== undefined) target[resolved.name] = value\n\t\t\t})\n\t\t\t// Observe this relation's eager-load — strictly after it resolved + was attached,\n\t\t\t// once per relation (not per record — the batched load has no N+1, nor do its\n\t\t\t// events), carrying the relation name + the count of rows attached across the set.\n\t\t\tthis.#emitter.emit('load', resolved.name, countAttached(values))\n\t\t}\n\t\treturn props\n\t}\n\n\t// Dispatch one relation to its loader, returning a value per record.\n\tasync #load(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedRelation,\n\t\tsub: boolean | Include,\n\t\tprimary: string,\n\t\toptions?: OperationOptions,\n\t): Promise<Array<Row | readonly Row[] | undefined>> {\n\t\tswitch (resolved.relationship) {\n\t\t\tcase 'belongs':\n\t\t\t\treturn this.#loadBelongs(records, resolved, sub, options)\n\t\t\tcase 'many':\n\t\t\t\treturn this.#loadMany(records, resolved, sub, primary, options)\n\t\t\tcase 'one':\n\t\t\t\treturn this.#loadOne(records, resolved, sub, primary, options)\n\t\t\tcase 'through':\n\t\t\t\treturn this.#loadThrough(records, resolved, sub, primary, options)\n\t\t\tcase 'morph':\n\t\t\t\treturn this.#loadMorph(records, resolved, sub, primary, options)\n\t\t}\n\t}\n\n\tasync #loadBelongs(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedBelongs,\n\t\tsub: boolean | Include,\n\t\toptions?: OperationOptions,\n\t): Promise<Array<Row | undefined>> {\n\t\tconst column = resolved.column\n\t\tconst keys = [...new Set(records.map((record) => readColumn(record, column)).filter(isDefined))]\n\t\tif (keys.length === 0) return records.map(() => undefined)\n\t\tconst related = this.#database.table(resolved.model)\n\t\tconst rows = await related.records(\n\t\t\t{\n\t\t\t\tconditions: [\n\t\t\t\t\t{\n\t\t\t\t\t\tcolumn: related.primary,\n\t\t\t\t\t\toperator: 'any',\n\t\t\t\t\t\tvalues: keys,\n\t\t\t\t\t\tconnector: 'and',\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t\toptions,\n\t\t)\n\t\tconst index = indexRows(await this.#nest(resolved.model, rows, sub, options), related.primary)\n\t\treturn records.map((record) => {\n\t\t\tconst fk = readColumn(record, column)\n\t\t\treturn isDefined(fk) ? index.get(String(fk)) : undefined\n\t\t})\n\t}\n\n\tasync #loadMany(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedMany | ResolvedOne,\n\t\tsub: boolean | Include,\n\t\tprimary: string,\n\t\toptions?: OperationOptions,\n\t): Promise<Array<readonly Row[]>> {\n\t\tconst foreign = resolved.key\n\t\tconst keys = [\n\t\t\t...new Set(records.map((record) => readColumn(record, primary)).filter(isDefined)),\n\t\t]\n\t\tif (keys.length === 0) return records.map(() => [])\n\t\tconst rows = await this.#database.table(resolved.model).records(\n\t\t\t{\n\t\t\t\tconditions: [{ column: foreign, operator: 'any', values: keys, connector: 'and' }],\n\t\t\t},\n\t\t\toptions,\n\t\t)\n\t\tconst groups = groupRows(await this.#nest(resolved.model, rows, sub, options), foreign)\n\t\treturn records.map((record) => groups.get(String(readColumn(record, primary))) ?? [])\n\t}\n\n\tasync #loadOne(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedOne,\n\t\tsub: boolean | Include,\n\t\tprimary: string,\n\t\toptions?: OperationOptions,\n\t): Promise<Array<Row | undefined>> {\n\t\tconst groups = await this.#loadMany(records, resolved, sub, primary, options)\n\t\treturn groups.map((group) => (group.length > 0 ? group[0] : undefined))\n\t}\n\n\tasync #loadThrough(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedThrough,\n\t\tsub: boolean | Include,\n\t\tprimary: string,\n\t\toptions?: OperationOptions,\n\t): Promise<Array<readonly Row[]>> {\n\t\tconst source = resolved.source\n\t\tconst target = resolved.target\n\t\tconst parents = [\n\t\t\t...new Set(records.map((record) => readColumn(record, primary)).filter(isDefined)),\n\t\t]\n\t\tif (parents.length === 0) return records.map(() => [])\n\n\t\tconst junctions = await this.#database.table(resolved.through).records(\n\t\t\t{\n\t\t\t\tconditions: [{ column: source, operator: 'any', values: parents, connector: 'and' }],\n\t\t\t},\n\t\t\toptions,\n\t\t)\n\t\tconst targetsBySource = new Map<string, unknown[]>()\n\t\tfor (const junction of junctions) {\n\t\t\tconst value = readColumn(junction, target)\n\t\t\tif (!isDefined(value)) continue\n\t\t\tconst owner = String(readColumn(junction, source))\n\t\t\tconst list = targetsBySource.get(owner)\n\t\t\tif (list !== undefined) list.push(value)\n\t\t\telse targetsBySource.set(owner, [value])\n\t\t}\n\n\t\tconst targets = [...new Set([...targetsBySource.values()].flat())]\n\t\tif (targets.length === 0) return records.map(() => [])\n\t\tconst related = this.#database.table(resolved.model)\n\t\tconst rows = await related.records(\n\t\t\t{\n\t\t\t\tconditions: [\n\t\t\t\t\t{\n\t\t\t\t\t\tcolumn: related.primary,\n\t\t\t\t\t\toperator: 'any',\n\t\t\t\t\t\tvalues: targets,\n\t\t\t\t\t\tconnector: 'and',\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t\toptions,\n\t\t)\n\t\tconst index = indexRows(await this.#nest(resolved.model, rows, sub, options), related.primary)\n\n\t\treturn records.map((record) => {\n\t\t\tconst out: Row[] = []\n\t\t\tfor (const value of targetsBySource.get(String(readColumn(record, primary))) ?? []) {\n\t\t\t\tconst row = index.get(String(value))\n\t\t\t\tif (row !== undefined) out.push(row)\n\t\t\t}\n\t\t\treturn out\n\t\t})\n\t}\n\n\tasync #loadMorph(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedMorph,\n\t\tsub: boolean | Include,\n\t\tprimary: string,\n\t\toptions?: OperationOptions,\n\t): Promise<Array<readonly Row[]>> {\n\t\tconst foreign = resolved.key\n\t\tconst keys = [\n\t\t\t...new Set(records.map((record) => readColumn(record, primary)).filter(isDefined)),\n\t\t]\n\t\tif (keys.length === 0) return records.map(() => [])\n\t\tconst rows = await this.#database.table(resolved.model).records(\n\t\t\t{\n\t\t\t\tconditions: [\n\t\t\t\t\t{ column: foreign, operator: 'any', values: keys, connector: 'and' },\n\t\t\t\t\t{\n\t\t\t\t\t\tcolumn: resolved.tag,\n\t\t\t\t\t\toperator: 'equals',\n\t\t\t\t\t\tvalues: [resolved.label],\n\t\t\t\t\t\tconnector: 'and',\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t\toptions,\n\t\t)\n\t\tconst groups = groupRows(await this.#nest(resolved.model, rows, sub, options), foreign)\n\t\treturn records.map((record) => groups.get(String(readColumn(record, primary))) ?? [])\n\t}\n\n\t// Recursively load a nested include onto related rows (when `sub` is an Include).\n\tasync #nest(\n\t\tmodel: string,\n\t\trows: readonly Row[],\n\t\tsub: boolean | Include,\n\t\toptions?: OperationOptions,\n\t): Promise<readonly Row[]> {\n\t\tif (isBoolean(sub) || rows.length === 0) return rows\n\t\tconst context = this.#lookup(model)\n\t\tif (context === undefined) return rows\n\t\tconst props = await this.#populate(rows, sub, context.resolved, context.primary, options)\n\t\treturn rows.map((row, index) => Object.assign({}, row, props[index]))\n\t}\n}\n","import type { DatabaseInterface, RowOf, TableInterface, TableMap } from '@orkestrel/database'\nimport type {\n\tModelInterface,\n\tRelationContext,\n\tRelationManagerInterface,\n\tRelationManagerOptions,\n\tRelationMap,\n\tRelationsShape,\n\tResolvedRelation,\n} from './types.js'\nimport { RelationError } from './errors.js'\nimport { resolveRelationMap } from './helpers.js'\nimport { Model } from './Model.js'\n\n/**\n * Resolves a {@link RelationsShape} once at construction and vends a typed\n * {@link ModelInterface} per declared table.\n *\n * @remarks\n * Holds the database both at its precise type (to type each model's own table)\n * and at the broad `DatabaseInterface` (to fetch related tables by runtime name\n * while loading). Construction validates every target and junction against the\n * database's declared tables, so invalid definitions fail before an operation runs.\n * The `model` option's `on` and `error` are threaded into every model vended, and\n * each `model(name)` call constructs a handle owning its own emitter, so retain the\n * handle a subscription is taken on.\n *\n * @example\n * ```ts\n * import { RelationManager, hasMany } from '@orkestrel/relation'\n *\n * const manager = new RelationManager({\n * \tdatabase,\n * \trelations: { users: { posts: hasMany('author') } },\n * \tmodel: { on: { load: (name, count) => metrics.record(`relation.${name}`, count) } },\n * })\n * const users = manager.model('users')\n * const ada = await users.load('u1', { posts: true })\n * ```\n */\nexport class RelationManager<T extends TableMap = TableMap> implements RelationManagerInterface<T> {\n\treadonly #database: DatabaseInterface<T>\n\treadonly #broad: DatabaseInterface\n\treadonly #relations: RelationsShape<T>\n\treadonly #model: RelationManagerOptions['model']\n\treadonly #resolved = new Map<string, ReadonlyMap<string, ResolvedRelation>>()\n\n\t/**\n\t * Constructs a registry over a database and its relation definitions.\n\t *\n\t * @param options - The `database`, an optional `relations` map, and the optional\n\t * `model` emitter settings threaded into every model vended\n\t * @throws An `INVALID` {@link RelationError} when a relation targets a table or a\n\t * junction the database does not declare\n\t */\n\tconstructor(options: RelationManagerOptions<T>) {\n\t\tthis.#database = options.database\n\t\tthis.#broad = options.database\n\t\tthis.#relations = options.relations ?? {}\n\t\tthis.#model = options.model\n\t\tconst declared = new Set(Object.keys(this.#broad.export()))\n\t\tfor (const [name, map] of Object.entries(this.#relations)) {\n\t\t\tif (map === undefined) continue\n\t\t\tconst resolved = resolveRelationMap(map)\n\t\t\tfor (const [relation, entry] of resolved) {\n\t\t\t\tif (!declared.has(entry.model)) {\n\t\t\t\t\tthrow new RelationError(\n\t\t\t\t\t\t'INVALID',\n\t\t\t\t\t\t`Model '${name}' relation '${relation}' targets undeclared table '${entry.model}'`,\n\t\t\t\t\t\t{ model: name, relation, table: entry.model },\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tif (entry.relationship === 'through' && !declared.has(entry.through)) {\n\t\t\t\t\tthrow new RelationError(\n\t\t\t\t\t\t'INVALID',\n\t\t\t\t\t\t`Model '${name}' relation '${relation}' uses undeclared junction '${entry.through}'`,\n\t\t\t\t\t\t{ model: name, relation, table: entry.through },\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis.#resolved.set(name, resolved)\n\t\t}\n\t}\n\n\tget count(): number {\n\t\treturn this.#resolved.size\n\t}\n\n\tmodel<K extends keyof T & string>(name: K): ModelInterface<RowOf<T[K]>> {\n\t\tconst resolved = this.#resolved.get(name) ?? new Map<string, ResolvedRelation>()\n\t\tconst relations = this.#relations[name] ?? {}\n\t\treturn this.#vend(name, this.#database.table(name), resolved, relations)\n\t}\n\n\tnames(): readonly string[] {\n\t\treturn [...this.#resolved.keys()]\n\t}\n\n\thas(name: string): boolean {\n\t\treturn this.#resolved.has(name)\n\t}\n\n\t// Construct a model over an opaque row type `R`, so `RowOf<T[K]>` is not\n\t// expanded structurally here (the instantiation-depth guard `db.table` sidesteps).\n\t// The `model` option's hooks and error handler reach each vended handle's own emitter.\n\t#vend<R>(\n\t\tname: string,\n\t\ttable: TableInterface<R>,\n\t\tresolved: ReadonlyMap<string, ResolvedRelation>,\n\t\trelations: RelationMap,\n\t): ModelInterface<R> {\n\t\treturn new Model(\n\t\t\tname,\n\t\t\ttable,\n\t\t\tresolved,\n\t\t\trelations,\n\t\t\t(model) => this.#context(model),\n\t\t\tthis.#broad,\n\t\t\tthis.#model?.on,\n\t\t\tthis.#model?.error,\n\t\t)\n\t}\n\n\t// Look up a related model's resolved relations + primary, for nested loading.\n\t#context(model: string): RelationContext | undefined {\n\t\tconst resolved = this.#resolved.get(model)\n\t\tif (resolved === undefined) return undefined\n\t\treturn { resolved, primary: this.#broad.table(model).primary }\n\t}\n}\n","import type { RelationManagerInterface, RelationManagerOptions } from './types.js'\nimport type { TableMap } from '@orkestrel/database'\nimport { RelationManager } from './RelationManager.js'\n\n/**\n * Creates a {@link RelationManagerInterface} over a database and its relation map.\n *\n * @remarks\n * `relations` maps table names (constrained to the database's tables) to their\n * relation maps; build entries with `belongsTo` / `hasMany` / `hasOne` /\n * `hasThrough` / `hasMorph`. `manager.model(name)` returns the typed model for a\n * table — its own table is fully typed, related rows load at the `Row` type.\n *\n * @param options - The `database` and an optional `relations` map\n * @returns A typed {@link RelationManagerInterface}\n *\n * @example Defining relations\n * ```ts\n * import {\n * \tcreateRelationManager,\n * \tbelongsTo,\n * \thasMany,\n * \thasOne,\n * \thasThrough,\n * \thasMorph,\n * } from '@orkestrel/relation'\n *\n * const manager = createRelationManager({\n * \tdatabase: db,\n * \trelations: {\n * \t\taccounts: {\n * \t\t\tclassification: belongsTo('classificationId', 'classifications'), // foreign key on accounts\n * \t\t\tcontacts: hasMany('accountId'), // foreign key on contacts → accounts\n * \t\t\tprofile: hasOne('accountId', 'profiles'), // single, foreign key on profiles\n * \t\t\trepresentatives: hasThrough('accountReps', 'accountId', 'repId', 'representatives'), // through a junction\n * \t\t\tnotes: hasMorph('entityId', 'entityType', 'account', 'notes'), // polymorphic\n * \t\t},\n * \t\tcontacts: { account: belongsTo('accountId', 'accounts') },\n * \t},\n * })\n *\n * const acme = await manager.model('accounts').load('acc1', { contacts: true, classification: true })\n * ```\n */\nexport function createRelationManager<T extends TableMap>(\n\toptions: RelationManagerOptions<T>,\n): RelationManagerInterface<T> {\n\treturn new RelationManager(options)\n}\n"],"mappings":";;;;;;;;;;;;;;;AAkBA,IAAa,gBAAb,cAAmC,MAAM;CACxC;CACA;CAEA,YACC,MACA,SACA,SACC;EACD,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,IAAI,YAAY,KAAA,GAAW,KAAK,UAAU;CAC3C;AACD;;;;;;;AAQA,SAAgB,gBAAgB,OAAwC;CACvE,OAAO,WAAW,OAAO,aAAa;AACvC;;;;;;;;;;;;;;;;;;;;;;;;;;ACdA,SAAgB,qBAAqB,OAA6C;CACjF,IAAI,CAAC,SAAS,KAAK,GAAG,OAAO;CAC7B,IACC,kBAAkB,SAClB,CAAC,UAAU,WAAW,QAAQ,OAAO,WAAW,OAAO,CAAC,CAAC,MAAM,YAAY,GAE3E,OAAO;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AAK,UAAU,IAAI,IAAI,qBAAK,IAAI,IAA8B;EAC/E,MAAM,YAAY,KAAK,WAAW,SAAS,CAAC;EAC5C,OAAO,KAAK,MAAM,MAAM,KAAK,UAAU,MAAM,IAAI,GAAG,UAAU,SAAS;CACxE;CAEA,QAA2B;EAC1B,OAAO,CAAC,GAAG,KAAK,UAAU,KAAK,CAAC;CACjC;CAEA,IAAI,MAAuB;EAC1B,OAAO,KAAK,UAAU,IAAI,IAAI;CAC/B;CAKA,MACC,MACA,OACA,UACA,WACoB;EACpB,OAAO,IAAI,MACV,MACA,OACA,UACA,YACC,UAAU,KAAK,SAAS,KAAK,GAC9B,KAAK,QACL,KAAK,QAAQ,IACb,KAAK,QAAQ,KACd;CACD;CAGA,SAAS,OAA4C;EACpD,MAAM,WAAW,KAAK,UAAU,IAAI,KAAK;EACzC,IAAI,aAAa,KAAA,GAAW,OAAO,KAAA;EACnC,OAAO;GAAE;GAAU,SAAS,KAAK,OAAO,MAAM,KAAK,CAAC,CAAC;EAAQ;CAC9D;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACrFA,SAAgB,sBACf,SAC8B;CAC9B,OAAO,IAAI,gBAAgB,OAAO;AACnC"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../src/core/errors.ts","../../../src/core/validators.ts","../../../src/core/helpers.ts","../../../src/core/Model.ts","../../../src/core/RelationManager.ts","../../../src/core/factories.ts"],"sourcesContent":["import type { RelationErrorCode } from './types.js'\nimport { holds, INTRINSICS, isFunction, isObject } from '@orkestrel/contract'\n\n// Invalid relation definitions and misuse `throw` a `RelationError` carrying a\n// machine-readable `code`, so a `catch` branches on `error.code`\n// (`.claude/rules/typescript.md` § Errors and outcomes).\n\n/**\n * Represents an error thrown by the relations layer, carrying a machine-readable\n * {@link RelationErrorCode}.\n *\n * @remarks\n * Thrown for: a relation value whose relationship cannot be inferred (`INVALID`), a\n * relation targeting a table or junction the database does not declare, raised when\n * the manager is created (`INVALID`), a reference to a relation a model does not\n * define (`UNKNOWN_RELATION`), and `link` / `unlink` / `links` on a relation that is\n * not a `through` (`NOT_THROUGH`).\n */\nexport class RelationError extends Error {\n\treadonly code: RelationErrorCode\n\treadonly context?: Readonly<Record<string, unknown>>\n\n\tconstructor(\n\t\tcode: RelationErrorCode,\n\t\tmessage: string,\n\t\tcontext?: Readonly<Record<string, unknown>>,\n\t) {\n\t\tsuper(message)\n\t\tINTRINSICS.define(this, Symbol.for('@orkestrel/relation.RelationError'), { value: this })\n\t\tthis.name = 'RelationError'\n\t\tthis.code = code\n\t\tif (context !== undefined) this.context = context\n\t}\n}\n\n/**\n * Narrows an unknown caught value to a {@link RelationError}.\n *\n * @param value - The value to test (typically a `catch` binding)\n * @returns True if the error carries its own identity brand and declared members; false otherwise\n */\nexport function isRelationError(value: unknown): value is RelationError {\n\treturn holds(() => {\n\t\tif (!(value instanceof Error) || INTRINSICS.prototype(value) === Error.prototype) return false\n\t\tconst brand = INTRINSICS.describe(value, Symbol.for('@orkestrel/relation.RelationError'))\n\t\tif (brand?.value !== value) return false\n\t\tconst code: unknown = INTRINSICS.reflect.read(value, 'code')\n\t\tif (code !== 'INVALID' && code !== 'UNKNOWN_RELATION' && code !== 'NOT_THROUGH') return false\n\t\tconst context: unknown = INTRINSICS.reflect.read(value, 'context')\n\t\treturn context === undefined || isObject(context) || isFunction(context)\n\t})\n}\n","import type { RelationDescriptor } from './types.js'\nimport { isRecord, isString, literalOf } from '@orkestrel/contract'\n\n// === Descriptor guard\n\n/**\n * Narrows a value to a {@link RelationDescriptor} (the object form of a relation).\n *\n * @remarks\n * A record satisfies the descriptor when every member it declares carries its declared\n * type: `relationship` is one of the `Relationship` values, and `column`, `key`,\n * `through`, `source`, `target`, `tag`, `label`, and `model` are strings. A member the\n * record omits is unconstrained, a member present with an `undefined` value is refused,\n * and a member the descriptor does not declare is carried without being checked. This\n * is what lets `resolveRelation` read each member after one narrow and report a\n * malformed definition as an `INVALID` `RelationError` instead of resolving a\n * wrong-typed column into an arm that declares it a string.\n *\n * @param value - The value to test\n * @returns True if `value` is a record whose every declared member holds its declared\n * type; false otherwise\n *\n * @example\n * ```ts\n * isRelationDescriptor(belongsTo('accountId')) // true\n * isRelationDescriptor({ column: 42 }) // false — `column` is declared a string\n * ```\n */\nexport function isRelationDescriptor(value: unknown): value is RelationDescriptor {\n\tif (!isRecord(value)) return false\n\tif (\n\t\t'relationship' in value &&\n\t\t!literalOf('belongs', 'many', 'one', 'through', 'morph')(value.relationship)\n\t) {\n\t\treturn false\n\t}\n\tfor (const member of ['column', 'key', 'through', 'source', 'target', 'tag', 'label', 'model']) {\n\t\tif (member in value && !isString(value[member])) return false\n\t}\n\treturn true\n}\n","import type {\n\tRelation,\n\tRelationDescriptor,\n\tRelationMap,\n\tRelationship,\n\tResolvedRelation,\n} from './types.js'\nimport type { Row } from '@orkestrel/database'\nimport { isArray, isDefined, isObject, isString } from '@orkestrel/contract'\nimport { isRelationDescriptor } from './validators.js'\nimport { RelationError } from './errors.js'\n\n// Resolve raw relation values into the flat `ResolvedRelation` form once, at\n// define-time, so no inference runs during loading. The builders in this file set\n// an explicit `relationship`; hand-written descriptors fall back to field inference.\n\n// === Resolution\n\n/**\n * Resolves one raw {@link Relation} value into a flat {@link ResolvedRelation}.\n *\n * @remarks\n * A `string` is a `belongs` (foreign-key column on this table); a `readonly string[]`\n * is a `many` (foreign-key column on the related table); a {@link RelationDescriptor}\n * uses its explicit `relationship`, or infers it from the fields present. The target\n * model defaults to the relation name. Every column the resolved arm declares is\n * validated here, which is what lets each arm declare its columns required.\n *\n * @param name - The relation name (its key in the {@link RelationMap})\n * @param value - The raw relation value\n * @returns The resolved relation, on the arm its `relationship` names\n * @throws An `INVALID` {@link RelationError} when the relationship cannot be resolved, or when a\n * column the resolved arm declares is missing\n */\nexport function resolveRelation(name: string, value: Relation): ResolvedRelation {\n\tif (isString(value)) {\n\t\treturn { relationship: 'belongs', name, model: name, column: value }\n\t}\n\tif (isArray(value)) {\n\t\tconst key = value[0]\n\t\tif (!isString(key)) {\n\t\t\tthrow new RelationError(\n\t\t\t\t'INVALID',\n\t\t\t\t`Relation '${name}': array form needs a string FK column`,\n\t\t\t\t{\n\t\t\t\t\trelation: name,\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t\treturn { relationship: 'many', name, model: name, key }\n\t}\n\tif (!isRelationDescriptor(value)) {\n\t\tthrow new RelationError('INVALID', `Relation '${name}': not a string, array, or descriptor`, {\n\t\t\trelation: name,\n\t\t})\n\t}\n\n\tconst model = value.model ?? name\n\t// Inferred from the fields present when no explicit `relationship` is set.\n\tconst relationship: Relationship | undefined =\n\t\tvalue.relationship !== undefined\n\t\t\t? value.relationship\n\t\t\t: isDefined(value.through)\n\t\t\t\t? 'through'\n\t\t\t\t: isDefined(value.tag)\n\t\t\t\t\t? 'morph'\n\t\t\t\t\t: isDefined(value.column)\n\t\t\t\t\t\t? 'belongs'\n\t\t\t\t\t\t: isDefined(value.key)\n\t\t\t\t\t\t\t? 'one'\n\t\t\t\t\t\t\t: undefined\n\tif (relationship === undefined) {\n\t\tthrow new RelationError(\n\t\t\t'INVALID',\n\t\t\t`Relation '${name}': cannot infer relationship from descriptor`,\n\t\t\t{ relation: name },\n\t\t)\n\t}\n\n\tswitch (relationship) {\n\t\tcase 'belongs': {\n\t\t\tconst column = value.column\n\t\t\tif (column === undefined) {\n\t\t\t\tthrow new RelationError('INVALID', `Relation '${name}': belongs needs 'column'`, {\n\t\t\t\t\trelation: name,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn { relationship, name, model, column }\n\t\t}\n\t\tcase 'many': {\n\t\t\tconst key = value.key\n\t\t\tif (key === undefined) {\n\t\t\t\tthrow new RelationError('INVALID', `Relation '${name}': many needs 'key'`, {\n\t\t\t\t\trelation: name,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn { relationship, name, model, key }\n\t\t}\n\t\tcase 'one': {\n\t\t\tconst key = value.key\n\t\t\tif (key === undefined) {\n\t\t\t\tthrow new RelationError('INVALID', `Relation '${name}': one needs 'key'`, {\n\t\t\t\t\trelation: name,\n\t\t\t\t})\n\t\t\t}\n\t\t\treturn { relationship, name, model, key }\n\t\t}\n\t\tcase 'through': {\n\t\t\tconst { through, source, target } = value\n\t\t\tif (through === undefined || source === undefined || target === undefined) {\n\t\t\t\tthrow new RelationError(\n\t\t\t\t\t'INVALID',\n\t\t\t\t\t`Relation '${name}': through needs 'through', 'source', and 'target'`,\n\t\t\t\t\t{ relation: name },\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn {\n\t\t\t\trelationship,\n\t\t\t\tname,\n\t\t\t\tmodel,\n\t\t\t\tthrough,\n\t\t\t\tsource,\n\t\t\t\ttarget,\n\t\t\t}\n\t\t}\n\t\tcase 'morph': {\n\t\t\tconst { key, tag, label } = value\n\t\t\tif (key === undefined || tag === undefined || label === undefined) {\n\t\t\t\tthrow new RelationError(\n\t\t\t\t\t'INVALID',\n\t\t\t\t\t`Relation '${name}': morph needs 'key', 'tag', and 'label'`,\n\t\t\t\t\t{ relation: name },\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn { relationship, name, model, key, tag, label }\n\t\t}\n\t}\n}\n\n/**\n * Resolves every entry of a {@link RelationMap} into a name → {@link ResolvedRelation} map.\n *\n * @param relations - The raw relation map\n * @returns A map keyed by relation name\n */\nexport function resolveRelationMap(relations: RelationMap): ReadonlyMap<string, ResolvedRelation> {\n\treturn new Map(\n\t\tObject.entries(relations).map(([name, value]) => [name, resolveRelation(name, value)]),\n\t)\n}\n\n// === Row projection\n\n/**\n * Reads one column off any record, whatever its declared type.\n *\n * @remarks\n * A base row's type is closed, so the column is read with `Reflect.get` rather than\n * index access. Anything that is not an object reads as `undefined`.\n *\n * @param record - The record to read\n * @param column - The column name\n * @returns The column's value, or `undefined` when `record` is not an object\n *\n * @example\n * ```ts\n * readColumn({ accountId: 'acc1' }, 'accountId') // 'acc1'\n * ```\n */\nexport function readColumn(record: unknown, column: string): unknown {\n\tif (!isObject(record)) return undefined\n\treturn Reflect.get(record, column)\n}\n\n/**\n * Counts the related rows one relation attached across a record set.\n *\n * @remarks\n * An array-valued relation (`many` / `through` / `morph`) sums its lengths; a\n * single-valued one (`belongs` / `one`) counts each present row. This is the count a\n * `Model` carries on its `load` event.\n *\n * @param values - One relation's loaded value per record\n * @returns The total related rows attached across the set\n *\n * @example\n * ```ts\n * countAttached([[{ id: 'p1' }, { id: 'p2' }], undefined, { id: 'p3' }]) // 3\n * ```\n */\nexport function countAttached(values: ReadonlyArray<Row | readonly Row[] | undefined>): number {\n\treturn Iterator.from(values).reduce(\n\t\t(total, value) => total + (isArray(value) ? value.length : value === undefined ? 0 : 1),\n\t\t0,\n\t)\n}\n\n/**\n * Indexes rows by the string form of one column, for keyed lookups.\n *\n * @remarks\n * The column is read with {@link readColumn} and its value stringified, so a numeric\n * and a string foreign key meet at the same entry. A later row with a key an earlier\n * row already holds replaces it, and a row missing the column indexes under the string\n * `'undefined'`. This is the projection a `belongs` load and a `through` load use to\n * attach one related row per key.\n *\n * @param rows - The rows to index\n * @param column - The column to key on\n * @returns A read-only map from each key's string form to its row\n *\n * @example\n * ```ts\n * indexRows([{ id: 'r1' }, { id: 'r2' }], 'id').get('r1') // { id: 'r1' }\n * ```\n */\nexport function indexRows(rows: readonly Row[], column: string): ReadonlyMap<string, Row> {\n\treturn new Map(Iterator.from(rows).map((row) => [String(readColumn(row, column)), row]))\n}\n\n/**\n * Groups rows by the string form of one column, for one-to-many lookups.\n *\n * @remarks\n * The column is read with {@link readColumn} and its value stringified, so a numeric\n * and a string foreign key meet at the same group. Rows keep their input order inside\n * a group, a key no row carries is absent rather than empty, and a row missing the\n * column groups under the string `'undefined'`. This is the projection a `many` load\n * and a `morph` load use to attach every related row per key.\n *\n * @param rows - The rows to group\n * @param column - The column to key on\n * @returns A read-only map from each key's string form to its rows, in input order\n *\n * @example\n * ```ts\n * groupRows([{ author: 'u1' }, { author: 'u1' }], 'author').get('u1')?.length // 2\n * ```\n */\nexport function groupRows(\n\trows: readonly Row[],\n\tcolumn: string,\n): ReadonlyMap<string, readonly Row[]> {\n\tconst groups = new Map<string, Row[]>()\n\tfor (const row of rows) {\n\t\tconst key = String(readColumn(row, column))\n\t\tconst group = groups.get(key)\n\t\tif (group !== undefined) group.push(row)\n\t\telse groups.set(key, [row])\n\t}\n\treturn groups\n}\n\n// === Builders\n\n/**\n * Builds a `belongs` relation — a foreign key on the owning table points at the related row\n * (single).\n *\n * @param column - The foreign-key column on this table\n * @param model - Target table name (defaults to the relation name)\n * @returns A {@link RelationDescriptor}\n *\n * @example\n * ```ts\n * { classification: belongsTo('classificationId', 'classifications') }\n * ```\n */\nexport function belongsTo(column: string, model?: string): RelationDescriptor {\n\treturn { relationship: 'belongs', column, ...(model !== undefined ? { model } : {}) }\n}\n\n/**\n * Builds a `many` relation — a foreign key on the related table points back at the owning row\n * (array).\n *\n * @param key - The foreign-key column on the related table\n * @param model - Target table name (defaults to the relation name)\n * @returns A {@link RelationDescriptor}\n */\nexport function hasMany(key: string, model?: string): RelationDescriptor {\n\treturn { relationship: 'many', key, ...(model !== undefined ? { model } : {}) }\n}\n\n/**\n * Builds a `one` relation — like {@link hasMany}, but a single related row.\n *\n * @param key - The foreign-key column on the related table\n * @param model - Target table name (defaults to the relation name)\n * @returns A {@link RelationDescriptor}\n */\nexport function hasOne(key: string, model?: string): RelationDescriptor {\n\treturn { relationship: 'one', key, ...(model !== undefined ? { model } : {}) }\n}\n\n/**\n * Builds a `through` relation — a junction table links the two sides (many-to-many).\n *\n * @param through - The junction table name\n * @param source - The junction foreign-key column pointing at the owning model\n * @param target - The junction foreign-key column pointing at the related model\n * @param model - Target table name (defaults to the relation name)\n * @returns A {@link RelationDescriptor}\n *\n * @example\n * ```ts\n * { reps: hasThrough('accountReps', 'accountId', 'repId', 'reps') }\n * ```\n */\nexport function hasThrough(\n\tthrough: string,\n\tsource: string,\n\ttarget: string,\n\tmodel?: string,\n): RelationDescriptor {\n\treturn {\n\t\trelationship: 'through',\n\t\tthrough,\n\t\tsource,\n\t\ttarget,\n\t\t...(model !== undefined ? { model } : {}),\n\t}\n}\n\n/**\n * Builds a `morph` relation — a polymorphic foreign key plus a discriminator column on the\n * related table (array).\n *\n * @param key - The foreign-key column on the related table\n * @param tag - The discriminator column on the related table\n * @param label - The discriminator value identifying the owning model\n * @param model - Target table name (defaults to the relation name)\n * @returns A {@link RelationDescriptor}\n *\n * @example\n * ```ts\n * { notes: hasMorph('entityId', 'entityType', 'account', 'notes') }\n * ```\n */\nexport function hasMorph(\n\tkey: string,\n\ttag: string,\n\tlabel: string,\n\tmodel?: string,\n): RelationDescriptor {\n\treturn { relationship: 'morph', key, tag, label, ...(model !== undefined ? { model } : {}) }\n}\n","import type {\n\tDatabaseInterface,\n\tKey,\n\tOperationOptions,\n\tRow,\n\tTableInterface,\n} from '@orkestrel/database'\nimport type { EmitterErrorHandler, EmitterHooks, EmitterInterface } from '@orkestrel/emitter'\nimport type {\n\tFindOptions,\n\tInclude,\n\tLoaded,\n\tLoadedMap,\n\tModelEventMap,\n\tModelInterface,\n\tRelationContext,\n\tRelationMap,\n\tResolvedBelongs,\n\tResolvedMany,\n\tResolvedMorph,\n\tResolvedOne,\n\tResolvedRelation,\n\tResolvedThrough,\n} from './types.js'\nimport { checkAbort, extractKey } from '@orkestrel/database'\nimport { Emitter } from '@orkestrel/emitter'\nimport { isArray, isBoolean, isDefined } from '@orkestrel/contract'\nimport { countAttached, groupRows, indexRows, readColumn } from './helpers.js'\nimport { RelationError } from './errors.js'\n\n/**\n * Pairs a typed table with relation-aware `load` / `find` and junction management.\n *\n * @remarks\n * The model's own table is fully typed (`table`); related tables are reached by\n * runtime name through the database at the broad `Row` type. Loading is batched:\n * a direct relation uses one query for the whole record set, while a `through`\n * relation uses two (junction then target); both counts remain constant regardless\n * of parent count. Nested includes recurse through the registry `lookup`, so each\n * nested level is batched again. Columns are read with `Reflect.get` (the base row's\n * type is closed) and relation properties merged with `Object.assign` — no `as`.\n *\n * @remarks\n * - **Observable.** The owned {@link emitter} ({@link ModelEventMap}) carries the\n * eager-load + junction moments — `load` (a relation resolved: its name + the count of\n * related rows attached across the whole record set), `link` / `unlink` (a junction row\n * written) — for fire-and-forget observers. Every event is emitted directly, strictly\n * after the load resolves and after the junction operation completes; the emitter\n * isolates a listener throw and routes it to its `error` handler (the `error` option),\n * so a buggy observer can never corrupt the batched eager-load (no N+1 in the events\n * either — one `load` per relation, not per record).\n *\n * @example\n * ```ts\n * import { Model, resolveRelationMap, hasMany } from '@orkestrel/relation'\n *\n * const relations = { posts: hasMany('author') }\n * const users = new Model(\n * \t'users',\n * \tdatabase.table('users'),\n * \tresolveRelationMap(relations),\n * \trelations,\n * \t() => undefined,\n * \tdatabase,\n * )\n * users.emitter.on('load', (name, count) => metrics.record(`relation.${name}`, count))\n * const ada = await users.load('u1', { posts: true })\n * ```\n */\nexport class Model<T = Row> implements ModelInterface<T> {\n\treadonly #name: string\n\treadonly #table: TableInterface<T>\n\treadonly #resolved: ReadonlyMap<string, ResolvedRelation>\n\treadonly #relations: RelationMap\n\treadonly #lookup: (model: string) => RelationContext | undefined\n\treadonly #database: DatabaseInterface\n\t// The push observation surface — owned, never inherited. The emitter isolates a\n\t// listener throw (routing it to the `error` handler), so it can never escape into the\n\t// batched eager-load.\n\treadonly #emitter: Emitter<ModelEventMap>\n\n\t/**\n\t * Constructs a model over one table and its resolved relations.\n\t *\n\t * @param name - The model's table name\n\t * @param table - The typed table this model's own reads and writes go through\n\t * @param resolved - The model's relations, resolved by `resolveRelationMap`\n\t * @param relations - The raw relation map the resolved relations came from\n\t * @param lookup - Reads a related model's {@link RelationContext} for a nested include,\n\t * and returns `undefined` for a model the registry does not hold\n\t * @param database - The broad database used to read related and junction tables by name\n\t * @param on - Initial {@link ModelEventMap} listeners\n\t * @param error - Receives a listener throw as `(error, event)`. Default: the throw is\n\t * swallowed.\n\t */\n\tconstructor(\n\t\tname: string,\n\t\ttable: TableInterface<T>,\n\t\tresolved: ReadonlyMap<string, ResolvedRelation>,\n\t\trelations: RelationMap,\n\t\tlookup: (model: string) => RelationContext | undefined,\n\t\tdatabase: DatabaseInterface,\n\t\ton?: EmitterHooks<ModelEventMap>,\n\t\terror?: EmitterErrorHandler,\n\t) {\n\t\tthis.#name = name\n\t\tthis.#table = table\n\t\tthis.#resolved = resolved\n\t\tthis.#relations = relations\n\t\tthis.#lookup = lookup\n\t\tthis.#database = database\n\t\tthis.#emitter = new Emitter<ModelEventMap>({\n\t\t\t...(on !== undefined ? { on } : {}),\n\t\t\t...(error !== undefined ? { error } : {}),\n\t\t})\n\t}\n\n\tget emitter(): EmitterInterface<ModelEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tget name(): string {\n\t\treturn this.#name\n\t}\n\n\tget table(): TableInterface<T> {\n\t\treturn this.#table\n\t}\n\n\tget relations(): RelationMap {\n\t\treturn this.#relations\n\t}\n\n\tload(key: Key, include: Include, options?: OperationOptions): Promise<Loaded<T> | undefined>\n\tload(\n\t\tkeys: readonly Key[],\n\t\tinclude: Include,\n\t\toptions?: OperationOptions,\n\t): Promise<ReadonlyArray<Loaded<T> | undefined>>\n\tasync load(\n\t\tkeys: Key | readonly Key[],\n\t\tinclude: Include,\n\t\toptions?: OperationOptions,\n\t): Promise<(Loaded<T> | undefined) | ReadonlyArray<Loaded<T> | undefined>> {\n\t\tcheckAbort(options?.signal)\n\t\tif (isArray(keys)) {\n\t\t\t// Batch: one `get`, then one populate over all present rows (no N+1).\n\t\t\tconst bases = await this.#table.get(keys)\n\t\t\tconst present = bases.filter(isDefined)\n\t\t\tconst props = await this.#populate(\n\t\t\t\tpresent,\n\t\t\t\tinclude,\n\t\t\t\tthis.#resolved,\n\t\t\t\tthis.#table.primary,\n\t\t\t\toptions,\n\t\t\t)\n\t\t\tconst attachments = props.values()\n\t\t\treturn bases.map((base) =>\n\t\t\t\tbase === undefined ? undefined : Object.assign({}, base, attachments.next().value),\n\t\t\t)\n\t\t}\n\t\tconst base = await this.#table.get(keys)\n\t\tif (base === undefined) return undefined\n\t\tconst [props] = await this.#populate(\n\t\t\t[base],\n\t\t\tinclude,\n\t\t\tthis.#resolved,\n\t\t\tthis.#table.primary,\n\t\t\toptions,\n\t\t)\n\t\treturn Object.assign({}, base, props)\n\t}\n\n\tasync find(include: Include, options?: FindOptions): Promise<ReadonlyArray<Loaded<T>>> {\n\t\tcheckAbort(options?.signal)\n\t\tconst records = await this.#table.records(\n\t\t\t{\n\t\t\t\t...(options?.sort !== undefined\n\t\t\t\t\t? {\n\t\t\t\t\t\t\torder: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tcolumn: options.sort,\n\t\t\t\t\t\t\t\t\tdirection: options.direction ?? 'ascending',\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t\t...(options?.offset !== undefined ? { offset: options.offset } : {}),\n\t\t\t\t...(options?.limit !== undefined ? { limit: options.limit } : {}),\n\t\t\t},\n\t\t\toptions,\n\t\t)\n\t\tconst props = await this.#populate(\n\t\t\trecords,\n\t\t\tinclude,\n\t\t\tthis.#resolved,\n\t\t\tthis.#table.primary,\n\t\t\toptions,\n\t\t)\n\t\treturn records.map((record, index) => Object.assign({}, record, props[index]))\n\t}\n\n\tasync link(key: Key, relation: string, target: Key, options?: OperationOptions): Promise<void> {\n\t\tcheckAbort(options?.signal)\n\t\tconst resolved = this.#through(relation)\n\t\tconst junction = this.#database.table(resolved.through)\n\t\tconst existing = await junction.count(\n\t\t\t{\n\t\t\t\tconditions: [\n\t\t\t\t\t{ column: resolved.source, operator: 'equals', values: [key], connector: 'and' },\n\t\t\t\t\t{ column: resolved.target, operator: 'equals', values: [target], connector: 'and' },\n\t\t\t\t],\n\t\t\t},\n\t\t\toptions,\n\t\t)\n\t\tif (existing > 0) return\n\t\tawait junction.set({ [resolved.source]: key, [resolved.target]: target }, options)\n\t\t// Observe the inserted junction row — strictly after the driver write, so a swallowed\n\t\t// listener throw can't perturb the link (carries the owning key + the relation name).\n\t\tthis.#emitter.emit('link', key, relation)\n\t}\n\n\tasync unlink(key: Key, relation: string, target: Key, options?: OperationOptions): Promise<void> {\n\t\tcheckAbort(options?.signal)\n\t\tconst resolved = this.#through(relation)\n\t\tconst junction = this.#database.table(resolved.through)\n\t\tconst rows = await junction.records(\n\t\t\t{\n\t\t\t\tconditions: [\n\t\t\t\t\t{\n\t\t\t\t\t\tcolumn: resolved.source,\n\t\t\t\t\t\toperator: 'equals',\n\t\t\t\t\t\tvalues: [key],\n\t\t\t\t\t\tconnector: 'and',\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tcolumn: resolved.target,\n\t\t\t\t\t\toperator: 'equals',\n\t\t\t\t\t\tvalues: [target],\n\t\t\t\t\t\tconnector: 'and',\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t\toptions,\n\t\t)\n\t\tawait this.#database.transaction(async (transaction) => {\n\t\t\tconst scoped = transaction.table(resolved.through)\n\t\t\tfor (const row of rows) {\n\t\t\t\tconst id = extractKey(row, junction.primary)\n\t\t\t\tif (id !== undefined) await scoped.remove(id, options)\n\t\t\t}\n\t\t}, options)\n\t\t// Observe the removal only after the transaction commits.\n\t\tthis.#emitter.emit('unlink', key, relation)\n\t}\n\n\tasync links(key: Key, relation: string, options?: OperationOptions): Promise<readonly Key[]> {\n\t\tcheckAbort(options?.signal)\n\t\tconst resolved = this.#through(relation)\n\t\tconst junction = this.#database.table(resolved.through)\n\t\tconst rows = await junction.records(\n\t\t\t{\n\t\t\t\tconditions: [\n\t\t\t\t\t{\n\t\t\t\t\t\tcolumn: resolved.source,\n\t\t\t\t\t\toperator: 'equals',\n\t\t\t\t\t\tvalues: [key],\n\t\t\t\t\t\tconnector: 'and',\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t\toptions,\n\t\t)\n\t\tconst target = resolved.target\n\t\tconst keys: Key[] = []\n\t\tfor (const row of rows) {\n\t\t\tconst value = extractKey(row, target)\n\t\t\tif (value !== undefined) keys.push(value)\n\t\t}\n\t\treturn keys\n\t}\n\n\t// === Private\n\n\t// Resolve a `through` relation by name to its own arm, or throw a descriptive error.\n\t#through(relation: string): ResolvedThrough {\n\t\tconst resolved = this.#resolved.get(relation)\n\t\tif (resolved === undefined) {\n\t\t\tthrow new RelationError(\n\t\t\t\t'UNKNOWN_RELATION',\n\t\t\t\t`Model '${this.#name}' has no relation '${relation}'`,\n\t\t\t\t{ model: this.#name, relation },\n\t\t\t)\n\t\t}\n\t\tif (resolved.relationship !== 'through') {\n\t\t\tthrow new RelationError(\n\t\t\t\t'NOT_THROUGH',\n\t\t\t\t`Relation '${relation}' on '${this.#name}' is not a through`,\n\t\t\t\t{ model: this.#name, relation },\n\t\t\t)\n\t\t}\n\t\treturn resolved\n\t}\n\n\t// Compute the relation properties for each record (parallel to `records`).\n\tasync #populate(\n\t\trecords: readonly unknown[],\n\t\tinclude: Include,\n\t\tresolvedMap: ReadonlyMap<string, ResolvedRelation>,\n\t\tprimary: string,\n\t\toptions?: OperationOptions,\n\t): Promise<LoadedMap[]> {\n\t\tcheckAbort(options?.signal)\n\t\tconst props: LoadedMap[] = records.map(() => ({}))\n\t\tfor (const [name, sub] of Object.entries(include)) {\n\t\t\tif (sub === false) continue\n\t\t\tcheckAbort(options?.signal)\n\t\t\tconst resolved = resolvedMap.get(name)\n\t\t\tif (resolved === undefined) continue\n\t\t\tconst values = await this.#load(records, resolved, sub, primary, options)\n\t\t\tvalues.forEach((value, index) => {\n\t\t\t\tconst target = props[index]\n\t\t\t\tif (target !== undefined) target[resolved.name] = value\n\t\t\t})\n\t\t\t// Observe this relation's eager-load — strictly after it resolved + was attached,\n\t\t\t// once per relation (not per record — the batched load has no N+1, nor do its\n\t\t\t// events), carrying the relation name + the count of rows attached across the set.\n\t\t\tthis.#emitter.emit('load', resolved.name, countAttached(values))\n\t\t}\n\t\treturn props\n\t}\n\n\t// Dispatch one relation to its loader, returning a value per record.\n\tasync #load(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedRelation,\n\t\tsub: boolean | Include,\n\t\tprimary: string,\n\t\toptions?: OperationOptions,\n\t): Promise<Array<Row | readonly Row[] | undefined>> {\n\t\tswitch (resolved.relationship) {\n\t\t\tcase 'belongs':\n\t\t\t\treturn this.#loadBelongs(records, resolved, sub, options)\n\t\t\tcase 'many':\n\t\t\t\treturn this.#loadMany(records, resolved, sub, primary, options)\n\t\t\tcase 'one':\n\t\t\t\treturn this.#loadOne(records, resolved, sub, primary, options)\n\t\t\tcase 'through':\n\t\t\t\treturn this.#loadThrough(records, resolved, sub, primary, options)\n\t\t\tcase 'morph':\n\t\t\t\treturn this.#loadMorph(records, resolved, sub, primary, options)\n\t\t}\n\t}\n\n\tasync #loadBelongs(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedBelongs,\n\t\tsub: boolean | Include,\n\t\toptions?: OperationOptions,\n\t): Promise<Array<Row | undefined>> {\n\t\tconst column = resolved.column\n\t\tconst keys = [...new Set(records.map((record) => readColumn(record, column)).filter(isDefined))]\n\t\tif (keys.length === 0) return records.map(() => undefined)\n\t\tconst related = this.#database.table(resolved.model)\n\t\tconst rows = await related.records(\n\t\t\t{\n\t\t\t\tconditions: [\n\t\t\t\t\t{\n\t\t\t\t\t\tcolumn: related.primary,\n\t\t\t\t\t\toperator: 'any',\n\t\t\t\t\t\tvalues: keys,\n\t\t\t\t\t\tconnector: 'and',\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t\toptions,\n\t\t)\n\t\tconst index = indexRows(await this.#nest(resolved.model, rows, sub, options), related.primary)\n\t\treturn records.map((record) => {\n\t\t\tconst fk = readColumn(record, column)\n\t\t\treturn isDefined(fk) ? index.get(String(fk)) : undefined\n\t\t})\n\t}\n\n\tasync #loadMany(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedMany | ResolvedOne,\n\t\tsub: boolean | Include,\n\t\tprimary: string,\n\t\toptions?: OperationOptions,\n\t): Promise<Array<readonly Row[]>> {\n\t\tconst foreign = resolved.key\n\t\tconst keys = [\n\t\t\t...new Set(records.map((record) => readColumn(record, primary)).filter(isDefined)),\n\t\t]\n\t\tif (keys.length === 0) return records.map(() => [])\n\t\tconst rows = await this.#database.table(resolved.model).records(\n\t\t\t{\n\t\t\t\tconditions: [{ column: foreign, operator: 'any', values: keys, connector: 'and' }],\n\t\t\t},\n\t\t\toptions,\n\t\t)\n\t\tconst groups = groupRows(await this.#nest(resolved.model, rows, sub, options), foreign)\n\t\treturn records.map((record) => groups.get(String(readColumn(record, primary))) ?? [])\n\t}\n\n\tasync #loadOne(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedOne,\n\t\tsub: boolean | Include,\n\t\tprimary: string,\n\t\toptions?: OperationOptions,\n\t): Promise<Array<Row | undefined>> {\n\t\tconst groups = await this.#loadMany(records, resolved, sub, primary, options)\n\t\treturn groups.map((group) => (group.length > 0 ? group[0] : undefined))\n\t}\n\n\tasync #loadThrough(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedThrough,\n\t\tsub: boolean | Include,\n\t\tprimary: string,\n\t\toptions?: OperationOptions,\n\t): Promise<Array<readonly Row[]>> {\n\t\tconst source = resolved.source\n\t\tconst target = resolved.target\n\t\tconst parents = [\n\t\t\t...new Set(records.map((record) => readColumn(record, primary)).filter(isDefined)),\n\t\t]\n\t\tif (parents.length === 0) return records.map(() => [])\n\n\t\tconst junctions = await this.#database.table(resolved.through).records(\n\t\t\t{\n\t\t\t\tconditions: [{ column: source, operator: 'any', values: parents, connector: 'and' }],\n\t\t\t},\n\t\t\toptions,\n\t\t)\n\t\tconst targetsBySource = new Map<string, unknown[]>()\n\t\tfor (const junction of junctions) {\n\t\t\tconst value = readColumn(junction, target)\n\t\t\tif (!isDefined(value)) continue\n\t\t\tconst owner = String(readColumn(junction, source))\n\t\t\tconst list = targetsBySource.get(owner)\n\t\t\tif (list !== undefined) list.push(value)\n\t\t\telse targetsBySource.set(owner, [value])\n\t\t}\n\n\t\tconst targets = [...new Set([...targetsBySource.values()].flat())]\n\t\tif (targets.length === 0) return records.map(() => [])\n\t\tconst related = this.#database.table(resolved.model)\n\t\tconst rows = await related.records(\n\t\t\t{\n\t\t\t\tconditions: [\n\t\t\t\t\t{\n\t\t\t\t\t\tcolumn: related.primary,\n\t\t\t\t\t\toperator: 'any',\n\t\t\t\t\t\tvalues: targets,\n\t\t\t\t\t\tconnector: 'and',\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t\toptions,\n\t\t)\n\t\tconst index = indexRows(await this.#nest(resolved.model, rows, sub, options), related.primary)\n\n\t\treturn records.map((record) => {\n\t\t\tconst out: Row[] = []\n\t\t\tfor (const value of targetsBySource.get(String(readColumn(record, primary))) ?? []) {\n\t\t\t\tconst row = index.get(String(value))\n\t\t\t\tif (row !== undefined) out.push(row)\n\t\t\t}\n\t\t\treturn out\n\t\t})\n\t}\n\n\tasync #loadMorph(\n\t\trecords: readonly unknown[],\n\t\tresolved: ResolvedMorph,\n\t\tsub: boolean | Include,\n\t\tprimary: string,\n\t\toptions?: OperationOptions,\n\t): Promise<Array<readonly Row[]>> {\n\t\tconst foreign = resolved.key\n\t\tconst keys = [\n\t\t\t...new Set(records.map((record) => readColumn(record, primary)).filter(isDefined)),\n\t\t]\n\t\tif (keys.length === 0) return records.map(() => [])\n\t\tconst rows = await this.#database.table(resolved.model).records(\n\t\t\t{\n\t\t\t\tconditions: [\n\t\t\t\t\t{ column: foreign, operator: 'any', values: keys, connector: 'and' },\n\t\t\t\t\t{\n\t\t\t\t\t\tcolumn: resolved.tag,\n\t\t\t\t\t\toperator: 'equals',\n\t\t\t\t\t\tvalues: [resolved.label],\n\t\t\t\t\t\tconnector: 'and',\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t\toptions,\n\t\t)\n\t\tconst groups = groupRows(await this.#nest(resolved.model, rows, sub, options), foreign)\n\t\treturn records.map((record) => groups.get(String(readColumn(record, primary))) ?? [])\n\t}\n\n\t// Recursively load a nested include onto related rows (when `sub` is an Include).\n\tasync #nest(\n\t\tmodel: string,\n\t\trows: readonly Row[],\n\t\tsub: boolean | Include,\n\t\toptions?: OperationOptions,\n\t): Promise<readonly Row[]> {\n\t\tif (isBoolean(sub) || rows.length === 0) return rows\n\t\tconst context = this.#lookup(model)\n\t\tif (context === undefined) return rows\n\t\tconst props = await this.#populate(rows, sub, context.resolved, context.primary, options)\n\t\treturn rows.map((row, index) => Object.assign({}, row, props[index]))\n\t}\n}\n","import type { DatabaseInterface, RowOf, TableInterface, TableMap } from '@orkestrel/database'\nimport type {\n\tModelInterface,\n\tRelationContext,\n\tRelationManagerInterface,\n\tRelationManagerOptions,\n\tRelationMap,\n\tRelationsShape,\n\tResolvedRelation,\n} from './types.js'\nimport { RelationError } from './errors.js'\nimport { resolveRelationMap } from './helpers.js'\nimport { Model } from './Model.js'\n\n/**\n * Resolves a {@link RelationsShape} once at construction and vends a typed\n * {@link ModelInterface} per declared table.\n *\n * @remarks\n * Holds the database both at its precise type (to type each model's own table)\n * and at the broad `DatabaseInterface` (to fetch related tables by runtime name\n * while loading). Construction validates every target and junction against the\n * database's declared tables, so invalid definitions fail before an operation runs.\n * The `model` option's `on` and `error` are threaded into every model vended, and\n * each `model(name)` call constructs a handle owning its own emitter, so retain the\n * handle a subscription is taken on.\n *\n * @example\n * ```ts\n * import { RelationManager, hasMany } from '@orkestrel/relation'\n *\n * const manager = new RelationManager({\n * \tdatabase,\n * \trelations: { users: { posts: hasMany('author') } },\n * \tmodel: { on: { load: (name, count) => metrics.record(`relation.${name}`, count) } },\n * })\n * const users = manager.model('users')\n * const ada = await users.load('u1', { posts: true })\n * ```\n */\nexport class RelationManager<T extends TableMap = TableMap> implements RelationManagerInterface<T> {\n\treadonly #database: DatabaseInterface<T>\n\treadonly #broad: DatabaseInterface\n\treadonly #relations: RelationsShape<T>\n\treadonly #model: RelationManagerOptions['model']\n\treadonly #resolved = new Map<string, ReadonlyMap<string, ResolvedRelation>>()\n\n\t/**\n\t * Constructs a registry over a database and its relation definitions.\n\t *\n\t * @param options - The `database`, an optional `relations` map, and the optional\n\t * `model` emitter settings threaded into every model vended\n\t * @throws An `INVALID` {@link RelationError} when a relation targets a table or a\n\t * junction the database does not declare\n\t */\n\tconstructor(options: RelationManagerOptions<T>) {\n\t\tthis.#database = options.database\n\t\tthis.#broad = options.database\n\t\tthis.#relations = options.relations ?? {}\n\t\tthis.#model = options.model\n\t\tconst declared = new Set(Object.keys(this.#broad.export()))\n\t\tfor (const [name, map] of Object.entries(this.#relations)) {\n\t\t\tif (map === undefined) continue\n\t\t\tconst resolved = resolveRelationMap(map)\n\t\t\tfor (const [relation, entry] of resolved) {\n\t\t\t\tif (!declared.has(entry.model)) {\n\t\t\t\t\tthrow new RelationError(\n\t\t\t\t\t\t'INVALID',\n\t\t\t\t\t\t`Model '${name}' relation '${relation}' targets undeclared table '${entry.model}'`,\n\t\t\t\t\t\t{ model: name, relation, table: entry.model },\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tif (entry.relationship === 'through' && !declared.has(entry.through)) {\n\t\t\t\t\tthrow new RelationError(\n\t\t\t\t\t\t'INVALID',\n\t\t\t\t\t\t`Model '${name}' relation '${relation}' uses undeclared junction '${entry.through}'`,\n\t\t\t\t\t\t{ model: name, relation, table: entry.through },\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis.#resolved.set(name, resolved)\n\t\t}\n\t}\n\n\tget count(): number {\n\t\treturn this.#resolved.size\n\t}\n\n\tmodel<K extends keyof T & string>(name: K): ModelInterface<RowOf<T[K]>> {\n\t\tconst resolved = this.#resolved.get(name) ?? new Map<string, ResolvedRelation>()\n\t\tconst relations = this.#relations[name] ?? {}\n\t\treturn this.#vend(name, this.#database.table(name), resolved, relations)\n\t}\n\n\tnames(): readonly string[] {\n\t\treturn [...this.#resolved.keys()]\n\t}\n\n\thas(name: string): boolean {\n\t\treturn this.#resolved.has(name)\n\t}\n\n\t// Construct a model over an opaque row type `R`, so `RowOf<T[K]>` is not\n\t// expanded structurally here (the instantiation-depth guard `db.table` sidesteps).\n\t// The `model` option's hooks and error handler reach each vended handle's own emitter.\n\t#vend<R>(\n\t\tname: string,\n\t\ttable: TableInterface<R>,\n\t\tresolved: ReadonlyMap<string, ResolvedRelation>,\n\t\trelations: RelationMap,\n\t): ModelInterface<R> {\n\t\treturn new Model(\n\t\t\tname,\n\t\t\ttable,\n\t\t\tresolved,\n\t\t\trelations,\n\t\t\t(model) => this.#context(model),\n\t\t\tthis.#broad,\n\t\t\tthis.#model?.on,\n\t\t\tthis.#model?.error,\n\t\t)\n\t}\n\n\t// Look up a related model's resolved relations + primary, for nested loading.\n\t#context(model: string): RelationContext | undefined {\n\t\tconst resolved = this.#resolved.get(model)\n\t\tif (resolved === undefined) return undefined\n\t\treturn { resolved, primary: this.#broad.table(model).primary }\n\t}\n}\n","import type { RelationManagerInterface, RelationManagerOptions } from './types.js'\nimport type { TableMap } from '@orkestrel/database'\nimport { RelationManager } from './RelationManager.js'\n\n/**\n * Creates a {@link RelationManagerInterface} over a database and its relation map.\n *\n * @remarks\n * `relations` maps table names (constrained to the database's tables) to their\n * relation maps; build entries with `belongsTo` / `hasMany` / `hasOne` /\n * `hasThrough` / `hasMorph`. `manager.model(name)` returns the typed model for a\n * table — its own table is fully typed, related rows load at the `Row` type.\n *\n * @param options - The `database` and an optional `relations` map\n * @returns A typed {@link RelationManagerInterface}\n *\n * @example Defining relations\n * ```ts\n * import {\n * \tcreateRelationManager,\n * \tbelongsTo,\n * \thasMany,\n * \thasOne,\n * \thasThrough,\n * \thasMorph,\n * } from '@orkestrel/relation'\n *\n * const manager = createRelationManager({\n * \tdatabase: db,\n * \trelations: {\n * \t\taccounts: {\n * \t\t\tclassification: belongsTo('classificationId', 'classifications'), // foreign key on accounts\n * \t\t\tcontacts: hasMany('accountId'), // foreign key on contacts → accounts\n * \t\t\tprofile: hasOne('accountId', 'profiles'), // single, foreign key on profiles\n * \t\t\trepresentatives: hasThrough('accountReps', 'accountId', 'repId', 'representatives'), // through a junction\n * \t\t\tnotes: hasMorph('entityId', 'entityType', 'account', 'notes'), // polymorphic\n * \t\t},\n * \t\tcontacts: { account: belongsTo('accountId', 'accounts') },\n * \t},\n * })\n *\n * const acme = await manager.model('accounts').load('acc1', { contacts: true, classification: true })\n * ```\n */\nexport function createRelationManager<T extends TableMap>(\n\toptions: RelationManagerOptions<T>,\n): RelationManagerInterface<T> {\n\treturn new RelationManager(options)\n}\n"],"mappings":";;;;;;;;;;;;;;;AAkBA,IAAa,gBAAb,cAAmC,MAAM;CACxC;CACA;CAEA,YACC,MACA,SACA,SACC;EACD,MAAM,OAAO;EACb,WAAW,OAAO,MAAM,OAAO,IAAI,mCAAmC,GAAG,EAAE,OAAO,KAAK,CAAC;EACxF,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,IAAI,YAAY,KAAA,GAAW,KAAK,UAAU;CAC3C;AACD;;;;;;;AAQA,SAAgB,gBAAgB,OAAwC;CACvE,OAAO,YAAY;EAClB,IAAI,EAAE,iBAAiB,UAAU,WAAW,UAAU,KAAK,MAAM,MAAM,WAAW,OAAO;EAEzF,IADc,WAAW,SAAS,OAAO,OAAO,IAAI,mCAAmC,CACnF,CAAA,EAAO,UAAU,OAAO,OAAO;EACnC,MAAM,OAAgB,WAAW,QAAQ,KAAK,OAAO,MAAM;EAC3D,IAAI,SAAS,aAAa,SAAS,sBAAsB,SAAS,eAAe,OAAO;EACxF,MAAM,UAAmB,WAAW,QAAQ,KAAK,OAAO,SAAS;EACjE,OAAO,YAAY,KAAA,KAAa,SAAS,OAAO,KAAK,WAAW,OAAO;CACxE,CAAC;AACF;;;;;;;;;;;;;;;;;;;;;;;;;ACvBA,SAAgB,qBAAqB,OAA6C;CACjF,IAAI,CAAC,SAAS,KAAK,GAAG,OAAO;CAC7B,IACC,kBAAkB,SAClB,CAAC,UAAU,WAAW,QAAQ,OAAO,WAA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,WAAW,KAAK,UAAU,IAAI,IAAI,qBAAK,IAAI,IAA8B;EAC/E,MAAM,YAAY,KAAK,WAAW,SAAS,CAAC;EAC5C,OAAO,KAAK,MAAM,MAAM,KAAK,UAAU,MAAM,IAAI,GAAG,UAAU,SAAS;CACxE;CAEA,QAA2B;EAC1B,OAAO,CAAC,GAAG,KAAK,UAAU,KAAK,CAAC;CACjC;CAEA,IAAI,MAAuB;EAC1B,OAAO,KAAK,UAAU,IAAI,IAAI;CAC/B;CAKA,MACC,MACA,OACA,UACA,WACoB;EACpB,OAAO,IAAI,MACV,MACA,OACA,UACA,YACC,UAAU,KAAK,SAAS,KAAK,GAC9B,KAAK,QACL,KAAK,QAAQ,IACb,KAAK,QAAQ,KACd;CACD;CAGA,SAAS,OAA4C;EACpD,MAAM,WAAW,KAAK,UAAU,IAAI,KAAK;EACzC,IAAI,aAAa,KAAA,GAAW,OAAO,KAAA;EACnC,OAAO;GAAE;GAAU,SAAS,KAAK,OAAO,MAAM,KAAK,CAAC,CAAC;EAAQ;CAC9D;AACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACrFA,SAAgB,sBACf,SAC8B;CAC9B,OAAO,IAAI,gBAAgB,OAAO;AACnC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@orkestrel/relation",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.17",
|
|
4
4
|
"description": "A typed relation manager over database tables — batched eager loading and junction management, environment-agnostic. Part of the @orkestrel line.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"database",
|
|
@@ -65,27 +65,27 @@
|
|
|
65
65
|
"prepublishOnly": "npm run format:check && npm run lint:check && npm run check && npm run build && npm test && npm run test:distribution -- --mode release",
|
|
66
66
|
"test:distribution": "vitest run --config vite.config.ts --no-cache --reporter=dot --project distribution",
|
|
67
67
|
"test:probe": "vitest run --config vite.config.ts --no-cache --reporter=verbose --project probe",
|
|
68
|
-
"test:bench": "vitest bench --config vite.config.ts --no-cache --project probe",
|
|
68
|
+
"test:bench": "vitest bench --config vite.config.ts --no-cache --project \"probe (bench)\" --mode benchmark",
|
|
69
69
|
"prepack": "npm run build",
|
|
70
70
|
"test:setup": "vitest run --config vite.config.ts --no-cache --reporter=dot --project setup"
|
|
71
71
|
},
|
|
72
72
|
"dependencies": {
|
|
73
|
-
"@orkestrel/contract": "^0.0.
|
|
74
|
-
"@orkestrel/database": "^0.0.
|
|
75
|
-
"@orkestrel/emitter": "^0.0.
|
|
73
|
+
"@orkestrel/contract": "^0.0.20",
|
|
74
|
+
"@orkestrel/database": "^0.0.19",
|
|
75
|
+
"@orkestrel/emitter": "^0.0.13"
|
|
76
76
|
},
|
|
77
77
|
"devDependencies": {
|
|
78
|
-
"@microsoft/api-extractor": "^7.
|
|
79
|
-
"@orkestrel/guide": "^0.0.
|
|
80
|
-
"@orkestrel/probe": "^0.0.
|
|
81
|
-
"@orkestrel/scaffold": "^0.0.
|
|
82
|
-
"@orkestrel/test": "^0.0.
|
|
83
|
-
"@types/node": "^26.6.
|
|
84
|
-
"oxfmt": "^0.
|
|
85
|
-
"oxlint": "^1.
|
|
86
|
-
"typescript": "^
|
|
87
|
-
"vite": "^8.3.
|
|
88
|
-
"vitest": "^
|
|
78
|
+
"@microsoft/api-extractor": "^7.60.0",
|
|
79
|
+
"@orkestrel/guide": "^0.0.25",
|
|
80
|
+
"@orkestrel/probe": "^0.0.25",
|
|
81
|
+
"@orkestrel/scaffold": "^0.0.113",
|
|
82
|
+
"@orkestrel/test": "^0.0.31",
|
|
83
|
+
"@types/node": "^26.6.6",
|
|
84
|
+
"oxfmt": "^0.75.0",
|
|
85
|
+
"oxlint": "^1.90.0",
|
|
86
|
+
"typescript": "^7.0.2",
|
|
87
|
+
"vite": "^8.3.5",
|
|
88
|
+
"vitest": "^5.0.5"
|
|
89
89
|
},
|
|
90
90
|
"engines": {
|
|
91
91
|
"node": ">=22.12.0"
|