@type-bridge/node 1.5.0 → 1.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,395 +0,0 @@
1
- "use strict";
2
- /**
3
- * Render the `relations.ts` module text from a parsed TypeSchema.
4
- *
5
- * Mirrors `type_bridge/generator/render/relations.py` → `render_relations()`.
6
- *
7
- * Role-player derivation:
8
- * Scan ALL entity `plays[]` entries for `role_ref === "<relation>:<role>"`.
9
- * Remove ancestor types when a descendant is also present (minimal set).
10
- * This is the exact algorithm of `minimal_role_players()` in models.py.
11
- *
12
- * Cardinality sources:
13
- * Relates-side cardinality comes from the relation role definition
14
- * (`RoleSpec.cardinality`). Plays-side cardinality comes from the player's
15
- * `PlayedRole.cardinality` and renders as `playsCardinality` on `role(...)`.
16
- *
17
- * Field key = toFieldName(role.name) / toFieldName(attr.name).
18
- * Class names = toClassName(typeName) for all players / attr types.
19
- *
20
- * Build-time code generation; no runtime ORM logic.
21
- */
22
- Object.defineProperty(exports, "__esModule", { value: true });
23
- exports.renderRelations = renderRelations;
24
- const naming_js_1 = require("./naming.js");
25
- const cardinality_js_1 = require("./cardinality.js");
26
- // ---------------------------------------------------------------------------
27
- // Card() argument renderer — mirrors Python `_render_card_arg`
28
- //
29
- // Default (1,1) emits nothing — caller wraps with `{ cardinality: Card(...) }`.
30
- // We always emit cardinality for roles (the hand-authored parity file always
31
- // uses explicit Card()), but skip if it is the default single (1,1).
32
- // ---------------------------------------------------------------------------
33
- function renderCardArg(card, omitDefaultSingle = true) {
34
- if (card === null)
35
- return "";
36
- if (omitDefaultSingle && card.min === 1 && card.max === 1)
37
- return "";
38
- const maxStr = card.max === null ? "null" : String(card.max);
39
- return `Card(${card.min}, ${maxStr})`;
40
- }
41
- // ---------------------------------------------------------------------------
42
- // role() call renderer — mirrors `_render_role_field` in relations.py
43
- // ---------------------------------------------------------------------------
44
- function renderRoleCall(players, card, playsCardinality, overrides = null, isAbstract = false, ordered = false, distinct = false) {
45
- const cardArg = renderCardArg(card);
46
- const playsCardArg = renderCardArg(playsCardinality, false);
47
- const options = [];
48
- if (cardArg)
49
- options.push(`cardinality: ${cardArg}`);
50
- if (playsCardArg)
51
- options.push(`playsCardinality: ${playsCardArg}`);
52
- if (overrides != null)
53
- options.push(`overrides: "${overrides}"`);
54
- if (isAbstract)
55
- options.push(`abstract: true`);
56
- if (ordered)
57
- options.push(`ordered: true`);
58
- if (distinct)
59
- options.push(`distinct: true`);
60
- const cardOptions = options.length > 0 ? `{ ${options.join(", ")} }` : null;
61
- if (players.length === 1) {
62
- const args = cardOptions ? `${players[0]}, ${cardOptions}` : players[0];
63
- return `role(${args})`;
64
- }
65
- // Multi-player: role(A, B, ..., { cardinality: ... })
66
- const playerArgs = players.join(", ");
67
- const args = cardOptions ? `${playerArgs}, ${cardOptions}` : playerArgs;
68
- return `role(${args})`;
69
- }
70
- function playsCardinalityForRole(schema, relationName, roleName, players) {
71
- const roleToken = `${relationName}:${roleName}`;
72
- for (const player of players) {
73
- const entity = schema.entities[player];
74
- const played = entity?.plays.find((entry) => entry.role_ref === roleToken);
75
- if (played?.cardinality !== null && played?.cardinality !== undefined) {
76
- return played.cardinality;
77
- }
78
- }
79
- return null;
80
- }
81
- // ---------------------------------------------------------------------------
82
- // Minimal role players — mirrors `minimal_role_players` in models.py
83
- //
84
- // Scan entity plays[] for role_ref === "<relationName>:<roleName>".
85
- // Then remove ancestors when a descendant is also present.
86
- // ---------------------------------------------------------------------------
87
- function minimalRolePlayers(schema, relationName, roleName) {
88
- const roleToken = `${relationName}:${roleName}`;
89
- // Collect all entities that play this role
90
- const players = [];
91
- for (const [entityName, entity] of Object.entries(schema.entities)) {
92
- for (const played of entity.plays) {
93
- if (played.role_ref === roleToken) {
94
- players.push(entityName);
95
- break;
96
- }
97
- }
98
- }
99
- if (players.length === 0)
100
- return [];
101
- // Build parent map
102
- const parentMap = new Map();
103
- for (const [name, entity] of Object.entries(schema.entities)) {
104
- parentMap.set(name, entity.parent);
105
- }
106
- function isAncestor(candidate, target) {
107
- let current = parentMap.get(target) ?? null;
108
- while (current !== null) {
109
- if (current === candidate)
110
- return true;
111
- current = parentMap.get(current) ?? null;
112
- }
113
- return false;
114
- }
115
- // Remove ancestors when a descendant is also present
116
- const unique = new Set(players);
117
- const minimal = new Set(unique);
118
- for (const player of unique) {
119
- for (const other of unique) {
120
- if (player !== other && isAncestor(other, player) && minimal.has(player)) {
121
- minimal.delete(player);
122
- break;
123
- }
124
- }
125
- }
126
- return [...minimal].sort();
127
- }
128
- // ---------------------------------------------------------------------------
129
- // Topological sort — parents before children (mirrors `_topological_sort_relations`)
130
- // ---------------------------------------------------------------------------
131
- function topologicalSortRelations(schema) {
132
- const relations = schema.relations;
133
- const names = Object.keys(relations);
134
- const sorted = [];
135
- const visited = new Set();
136
- function visit(name) {
137
- if (visited.has(name))
138
- return;
139
- visited.add(name);
140
- const parent = relations[name]?.parent;
141
- if (parent && relations[parent]) {
142
- visit(parent);
143
- }
144
- sorted.push(name);
145
- }
146
- for (const name of names) {
147
- visit(name);
148
- }
149
- return sorted;
150
- }
151
- // ---------------------------------------------------------------------------
152
- // Import need detectors
153
- // ---------------------------------------------------------------------------
154
- function needsCardImport(schema) {
155
- for (const relation of Object.values(schema.relations)) {
156
- // Check role cardinalities
157
- for (const role of relation.roles) {
158
- if (role.cardinality !== null) {
159
- const c = role.cardinality;
160
- if (!(c.min === 1 && c.max === 1))
161
- return true;
162
- }
163
- const players = minimalRolePlayers(schema, relation.name, role.name);
164
- if (playsCardinalityForRole(schema, relation.name, role.name, players) !== null) {
165
- return true;
166
- }
167
- }
168
- // Check attribute cardinalities (multi-valued)
169
- for (const owned of relation.owns) {
170
- const c = owned.cardinality;
171
- if (c !== null && (0, cardinality_js_1.isCardMulti)(c))
172
- return true;
173
- }
174
- }
175
- return false;
176
- }
177
- function needsKeyImport(schema, options) {
178
- return Object.values(schema.relations).some((rel) => rel.owns.some((o) => (0, naming_js_1.isKeyAttribute)(o.name, o.is_key, options)));
179
- }
180
- function needsUniqueImport(schema) {
181
- return Object.values(schema.relations).some((rel) => rel.owns.some((o) => o.is_unique));
182
- }
183
- function needsTypeFlagsImport(schema) {
184
- return Object.values(schema.relations).some((rel) => rel.is_abstract);
185
- }
186
- function needsOrderedImport(schema) {
187
- return Object.values(schema.relations).some((rel) => rel.roles.some((r) => r.ordered) ||
188
- rel.owns.some((o) => o.ordered));
189
- }
190
- function needsDistinctImport(schema) {
191
- return Object.values(schema.relations).some((rel) => rel.roles.some((r) => r.distinct) ||
192
- rel.owns.some((o) => o.distinct));
193
- }
194
- // ---------------------------------------------------------------------------
195
- // Single-field renderer for owned attributes (mirrors renderEntities.ts logic)
196
- // ---------------------------------------------------------------------------
197
- function renderAttrFieldExpr(owned, attrClassName, isKey) {
198
- const card = owned.cardinality;
199
- if (isKey)
200
- return `field(${attrClassName}, Key)`;
201
- if (owned.is_unique)
202
- return `field(${attrClassName}, Unique)`;
203
- // Ordered list attribute: field(Attr).ordered() or field(Attr).ordered().distinct()
204
- if (owned.ordered) {
205
- const base = `field(${attrClassName}).ordered()`;
206
- return owned.distinct ? `${base}.distinct()` : base;
207
- }
208
- if (card === null || (0, cardinality_js_1.isCardOptionalSingle)(card))
209
- return `field(${attrClassName}).optional()`;
210
- if ((0, cardinality_js_1.isCardMulti)(card)) {
211
- const maxStr = card.max === null ? "null" : String(card.max);
212
- return `field(${attrClassName}).list(Card(${card.min}, ${maxStr}))`;
213
- }
214
- if ((0, cardinality_js_1.isCardRequired)(card) && (0, cardinality_js_1.isCardSingle)(card))
215
- return `field(${attrClassName})`;
216
- return `field(${attrClassName}).optional()`;
217
- }
218
- // ---------------------------------------------------------------------------
219
- // Main renderer
220
- // ---------------------------------------------------------------------------
221
- /**
222
- * Render the complete `relations.ts` source text from the parsed schema.
223
- *
224
- * Each relation emits:
225
- * export class <ClassName> extends Relation("<name>", { <fields> }) {}
226
- *
227
- * Role keys = toFieldName(role.name).
228
- * Attr keys = toFieldName(attr.name).
229
- * Player names = toClassName(entityName).
230
- *
231
- * Imports: `@type-bridge/node` for factory symbols; `./attributes.js` for
232
- * attribute classes; `./entities.js` for player entity classes.
233
- */
234
- function renderRelations(schema, options) {
235
- const sortedNames = topologicalSortRelations(schema);
236
- // Pre-compute class name maps
237
- const attrClassMap = new Map();
238
- for (const name of Object.keys(schema.attributes)) {
239
- attrClassMap.set(name, (0, naming_js_1.toClassName)(name));
240
- }
241
- const entityClassMap = new Map();
242
- for (const name of Object.keys(schema.entities)) {
243
- entityClassMap.set(name, (0, naming_js_1.toClassName)(name));
244
- }
245
- const relationClassMap = new Map();
246
- for (const name of Object.keys(schema.relations)) {
247
- relationClassMap.set(name, (0, naming_js_1.toClassName)(name));
248
- }
249
- // Determine which factory symbols are needed
250
- const needsCard = needsCardImport(schema);
251
- const needsKey = needsKeyImport(schema, options);
252
- const needsUnique = needsUniqueImport(schema);
253
- const needsTypeFlags = needsTypeFlagsImport(schema);
254
- const needsOrdered = needsOrderedImport(schema);
255
- const needsDistinct = needsDistinctImport(schema);
256
- const factoryImports = ["Relation", "role", "field"];
257
- if (needsCard)
258
- factoryImports.push("Card");
259
- if (needsKey)
260
- factoryImports.push("Key");
261
- if (needsUnique)
262
- factoryImports.push("Unique");
263
- if (needsTypeFlags)
264
- factoryImports.push("TypeFlags");
265
- if (needsOrdered)
266
- factoryImports.push("Ordered");
267
- if (needsDistinct)
268
- factoryImports.push("Distinct");
269
- factoryImports.sort();
270
- // Collect which attribute + entity class names are referenced (for imports)
271
- const referencedAttrClasses = new Set();
272
- const referencedEntityClasses = new Set();
273
- // Two-pass: collect all referenced classes first
274
- for (const relName of sortedNames) {
275
- const relation = schema.relations[relName];
276
- if (!relation)
277
- continue;
278
- // Parent-owned roles (skip inherited, same as Python)
279
- const parentRoleNames = new Set();
280
- if (relation.parent && schema.relations[relation.parent]) {
281
- for (const r of schema.relations[relation.parent].roles) {
282
- parentRoleNames.add(r.name);
283
- }
284
- }
285
- // Roles
286
- for (const role of relation.roles) {
287
- if (parentRoleNames.has(role.name) && !role.overrides)
288
- continue;
289
- const players = minimalRolePlayers(schema, relName, role.name);
290
- for (const p of players) {
291
- const cls = entityClassMap.get(p);
292
- if (cls)
293
- referencedEntityClasses.add(cls);
294
- }
295
- }
296
- // Attributes (only own, not inherited)
297
- const parentOwns = new Set();
298
- if (relation.parent && schema.relations[relation.parent]) {
299
- for (const o of schema.relations[relation.parent].owns) {
300
- parentOwns.add(o.name);
301
- }
302
- }
303
- for (const owned of relation.owns) {
304
- if (parentOwns.has(owned.name))
305
- continue;
306
- const cls = attrClassMap.get(owned.name);
307
- if (cls)
308
- referencedAttrClasses.add(cls);
309
- }
310
- }
311
- // Build import lines
312
- const lines = [
313
- `import { ${factoryImports.join(", ")} } from "@type-bridge/node";`,
314
- ];
315
- const sortedAttrImports = [...referencedAttrClasses].sort();
316
- if (sortedAttrImports.length > 0) {
317
- lines.push(`import { ${sortedAttrImports.join(", ")} } from "./attributes.js";`);
318
- }
319
- const sortedEntityImports = [...referencedEntityClasses].sort();
320
- if (sortedEntityImports.length > 0) {
321
- lines.push(`import { ${sortedEntityImports.join(", ")} } from "./entities.js";`);
322
- }
323
- lines.push(``);
324
- // Emit each relation class
325
- for (const relName of sortedNames) {
326
- const relation = schema.relations[relName];
327
- if (!relation)
328
- continue;
329
- const className = relationClassMap.get(relName) ?? (0, naming_js_1.toClassName)(relName);
330
- // First argument
331
- let firstArg;
332
- if (relation.is_abstract) {
333
- firstArg = `TypeFlags({ name: "${relName}", abstract: true })`;
334
- }
335
- else {
336
- firstArg = `"${relName}"`;
337
- }
338
- // Third argument: { parent: ParentClass }
339
- const parentClassName = relation.parent ? relationClassMap.get(relation.parent) : null;
340
- const thirdArg = parentClassName ? `, { parent: ${parentClassName} }` : "";
341
- // Collect parent-owned role names + attr names (skip inherited)
342
- const parentRoleNames = new Set();
343
- const parentOwns = new Set();
344
- if (relation.parent && schema.relations[relation.parent]) {
345
- const parentRel = schema.relations[relation.parent];
346
- for (const r of parentRel.roles) {
347
- parentRoleNames.add(r.name);
348
- }
349
- for (const o of parentRel.owns) {
350
- parentOwns.add(o.name);
351
- }
352
- }
353
- // Build field entries: roles first, then attrs (mirror Python relation template order)
354
- const fieldEntries = [];
355
- // Role fields
356
- for (const roleSpec of relation.roles) {
357
- if (parentRoleNames.has(roleSpec.name) && !roleSpec.overrides)
358
- continue;
359
- const players = minimalRolePlayers(schema, relName, roleSpec.name);
360
- if (players.length === 0)
361
- continue;
362
- const playerClassRefs = players.map((p) => entityClassMap.get(p) ?? (0, naming_js_1.toClassName)(p));
363
- const roleKey = (0, naming_js_1.toFieldName)(roleSpec.name);
364
- const playsCardinality = playsCardinalityForRole(schema, relName, roleSpec.name, players);
365
- const roleCall = renderRoleCall(playerClassRefs, roleSpec.cardinality, playsCardinality, roleSpec.overrides, roleSpec.is_abstract, roleSpec.ordered, roleSpec.distinct);
366
- fieldEntries.push(` ${roleKey}: ${roleCall},`);
367
- }
368
- // Attribute fields (own only, in owns_order)
369
- const ownLocalAttrs = relation.owns_order.filter((n) => !parentOwns.has(n));
370
- for (const attrName of ownLocalAttrs) {
371
- const owned = relation.owns.find((o) => o.name === attrName);
372
- if (!owned)
373
- continue;
374
- const attrClass = attrClassMap.get(attrName);
375
- if (!attrClass)
376
- continue;
377
- const fieldKey = (0, naming_js_1.toFieldName)(attrName);
378
- const isKey = (0, naming_js_1.isKeyAttribute)(attrName, owned.is_key, options);
379
- const fieldExpr = renderAttrFieldExpr(owned, attrClass, isKey);
380
- fieldEntries.push(` ${fieldKey}: ${fieldExpr},`);
381
- }
382
- if (fieldEntries.length === 0) {
383
- lines.push(`export class ${className} extends Relation(${firstArg}, {}${thirdArg}) {}`);
384
- }
385
- else {
386
- lines.push(`export class ${className} extends Relation(${firstArg}, {`);
387
- for (const entry of fieldEntries) {
388
- lines.push(entry);
389
- }
390
- lines.push(`}${thirdArg}) {}`);
391
- }
392
- lines.push(``);
393
- }
394
- return lines.join("\n");
395
- }
Binary file