@sentropic/diagram-core 0.1.0 → 0.2.0

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/erd.js ADDED
@@ -0,0 +1,72 @@
1
+ import { createDocument } from './document.js';
2
+ import { createView } from './view.js';
3
+ import { documentRef, entityRef, portRef, relationRef, occurrenceRef, viewRef } from './refs.js';
4
+ import { DIAGRAM_PRESENTATION_CONTRACT_PIN } from './presentation.js';
5
+ /** Injective encoding into the narrow local-reference grammar, including punctuation and Unicode. */
6
+ export const erdLocalId = (name) => 'x' + Array.from(name).map(c => c.codePointAt(0).toString(16)).join('-');
7
+ export const erdEntityOccurrence = (entity) => occurrenceRef('e.' + entity.slice(7));
8
+ export const erdPortOccurrence = (port, side = 'east') => occurrenceRef('p.' + side + '.' + port.slice(5));
9
+ const text = (value) => ({ kind: 'text', value });
10
+ /** One scene relation stays one semantic relation, including many-to-many and self references. */
11
+ export function convertEngramErdScene(scene) {
12
+ const entities = {}, ports = {}, relations = {};
13
+ const entityOccurrences = {}, portOccurrences = {}, relationOccurrences = {};
14
+ const forms = {};
15
+ const entityId = (name) => entityRef(erdLocalId(name));
16
+ const fieldId = (owner, field) => portRef(erdLocalId(owner) + '.' + erdLocalId(field));
17
+ for (const cls of scene.classes) {
18
+ const id = entityId(cls.name), occurrence = erdEntityOccurrence(id);
19
+ if (entities[id])
20
+ throw new Error('Duplicate ERD class: ' + cls.name);
21
+ entities[id] = { id, profile: 'erd@1', type: 'entity', attributes: { name: text(cls.name), schema: text(scene.container) } };
22
+ entityOccurrences[occurrence] = { id: occurrence, entity: id, geometry: { x: 0, y: 0, width: 1, height: 1 } };
23
+ forms[occurrence] = { form: 'card', text: { title: cls.name } };
24
+ cls.fields.forEach((field, index) => {
25
+ const port = fieldId(cls.name, field.name), po = erdPortOccurrence(port);
26
+ if (ports[port])
27
+ throw new Error('Duplicate ERD field: ' + cls.name + '.' + field.name);
28
+ ports[port] = { id: port, profile: 'erd@1', type: 'field', owner: id, name: field.name, direction: 'inout', attributes: {
29
+ dataType: text(field.type), pk: { kind: 'boolean', value: field.pk }, nullable: { kind: 'boolean', value: field.nullable },
30
+ ordinal: { kind: 'quantity', unit: 'index', value: index },
31
+ ...(field.fk === null ? {} : { fk: { kind: 'reference', value: fieldId(field.fk.class, field.fk.field) } }),
32
+ } };
33
+ portOccurrences[po] = { id: po, port, ownerOccurrence: occurrence, side: 'east', order: index, anchor: (index + 0.5) / cls.fields.length };
34
+ });
35
+ }
36
+ scene.relations.forEach((relation, index) => {
37
+ const id = relationRef('r.' + String(index).padStart(4, '0') + '.' + erdLocalId(relation.name)), occurrence = occurrenceRef(id.slice(9));
38
+ const stem = (value) => value.toLowerCase().replace(/id$/, '').replace('owned', 'owner');
39
+ const relationStem = stem(relation.name);
40
+ const words = (value) => value.replace(/([a-z])([A-Z])/g, '$1 $2').toLowerCase().replace('owned', 'owner').split(' ');
41
+ const score = (field) => {
42
+ if (relation.name === 'partOf' && field.name.startsWith('parent'))
43
+ return 100;
44
+ if (stem(field.name).startsWith(relationStem))
45
+ return 100;
46
+ return words(relation.name).filter(w => !['by', 'of', 'to'].includes(w) && words(field.name).includes(w)).length;
47
+ };
48
+ const pickFk = (owner, target) => scene.classes.find(c => c.name === owner)?.fields
49
+ .filter(f => f.fk?.class === target).sort((a, b) => score(b) - score(a))[0];
50
+ const forward = pickFk(relation.from.class, relation.to.class);
51
+ const reverse = forward ? undefined : pickFk(relation.to.class, relation.from.class);
52
+ const targets = forward?.fk
53
+ ? [fieldId(relation.from.class, forward.name), fieldId(forward.fk.class, forward.fk.field)]
54
+ : reverse?.fk
55
+ ? [fieldId(reverse.fk.class, reverse.fk.field), fieldId(relation.to.class, reverse.name)]
56
+ : [entityId(relation.from.class), entityId(relation.to.class)];
57
+ const endpoints = ['from', 'to'].map((role, i) => ({ role, target: targets[i] }));
58
+ relations[id] = { id, profile: 'erd@1', type: 'relationship', endpoints, attributes: {
59
+ name: text(relation.name), label: text(relation.roleLabel),
60
+ fromCardinality: { kind: 'enum', value: relation.from.cardinality }, toCardinality: { kind: 'enum', value: relation.to.cardinality },
61
+ fromRole: text(relation.from.role ?? ''), toRole: text(relation.to.role ?? relation.roleLabel),
62
+ } };
63
+ relationOccurrences[occurrence] = { id: occurrence, relation: id, endpoints: endpoints.map(e => ({ role: e.role,
64
+ occurrence: e.target.startsWith('port:') ? erdPortOccurrence(e.target) : erdEntityOccurrence(e.target),
65
+ })) };
66
+ });
67
+ const document = { ...createDocument({ documentId: documentRef(erdLocalId(scene.id)), profileRefs: ['erd@1'] }), entities, ports, relations };
68
+ const presentation = { contractPin: DIAGRAM_PRESENTATION_CONTRACT_PIN, entities: forms, legends: {}, categoryTokens: [] };
69
+ const view = { ...createView({ viewId: viewRef('erd'), semanticDocumentId: document.documentId }), entityOccurrences, portOccurrences, relationOccurrences };
70
+ return { document, view, presentation };
71
+ }
72
+ //# sourceMappingURL=erd.js.map
@@ -0,0 +1,36 @@
1
+ import { type Diagnostic } from "./diagnostics.js";
2
+ import type { SemanticDocument } from "./document.js";
3
+ import type { EntityRef, RelationRef } from "./refs.js";
4
+ export interface FlowStep {
5
+ readonly relation: RelationRef;
6
+ readonly scenario: string;
7
+ readonly step: number;
8
+ readonly branch?: string;
9
+ readonly ordinal: number;
10
+ readonly badge: string;
11
+ readonly source: EntityRef;
12
+ readonly target: EntityRef;
13
+ readonly self: boolean;
14
+ readonly label?: string;
15
+ readonly kind?: "sync" | "async" | "reply";
16
+ readonly realises?: string;
17
+ }
18
+ export interface FlowScenario {
19
+ readonly id: string;
20
+ readonly label: string;
21
+ readonly order?: number;
22
+ readonly steps: readonly FlowStep[];
23
+ }
24
+ export interface FlowIndex {
25
+ readonly scenarios: readonly FlowScenario[];
26
+ readonly byRelation: Readonly<Record<string, FlowStep>>;
27
+ readonly byEntity: Readonly<Record<string, readonly RelationRef[]>>;
28
+ }
29
+ export declare function withFlowTypes(document: SemanticDocument): {
30
+ document: SemanticDocument;
31
+ diagnostics: readonly Diagnostic[];
32
+ };
33
+ export declare function flowIndex(document: SemanticDocument): FlowIndex;
34
+ /** Run after document validation; this pass only owns the flow semantics. */
35
+ export declare function validateFlows(document: SemanticDocument): readonly Diagnostic[];
36
+ //# sourceMappingURL=flows.d.ts.map
package/dist/flows.js ADDED
@@ -0,0 +1,144 @@
1
+ /** Numbered flows are authored relations, independent of any process notation. */
2
+ import { stableStringify } from "./bindings.js";
3
+ import { diagnostic } from "./diagnostics.js";
4
+ const cmp = (a, b) => a < b ? -1 : a > b ? 1 : 0;
5
+ export function withFlowTypes(document) {
6
+ const profile = document.profileRefs.includes("generic@2") ? "generic@2" : "generic@1";
7
+ const definitions = [
8
+ { id: "flow-step", profile, baseType: "link", attributes: [
9
+ { name: "step", kind: "quantity", units: ["unit"], integer: true, min: 1, max: 999 },
10
+ { name: "branch", kind: "text", pattern: "^[a-z]$", patternName: "flow-branch" },
11
+ { name: "scenario", kind: "reference", refKind: "entity", targetTypes: ["flow-scenario"] },
12
+ { name: "kind", kind: "enum", values: ["sync", "async", "reply"] },
13
+ { name: "realises", kind: "text", maxLength: 200, pattern: "^bpmn:[\\w.-]+#[\\w.-]+$", patternName: "bpmn-task" },
14
+ ] },
15
+ { id: "flow-scenario", profile, baseType: "node", attributes: [
16
+ { name: "order", kind: "quantity", units: ["unit"], integer: true, min: 1 },
17
+ ] },
18
+ ];
19
+ const diagnostics = [];
20
+ for (const definition of definitions) {
21
+ const existing = document.typeDefinitions[definition.id];
22
+ if (existing !== undefined && stableStringify(existing) !== stableStringify(definition)) {
23
+ diagnostics.push(diagnostic({ code: "flow-types-conflict", path: "typeDefinitions." + definition.id, message: "a different flow definition already exists" }));
24
+ }
25
+ }
26
+ if (diagnostics.length > 0)
27
+ return { document, diagnostics };
28
+ if (definitions.every((definition) => document.typeDefinitions[definition.id] !== undefined))
29
+ return { document, diagnostics };
30
+ return { document: { ...document, typeDefinitions: { ...document.typeDefinitions, ...Object.fromEntries(definitions.map((d) => [d.id, d])) } }, diagnostics };
31
+ }
32
+ export function flowIndex(document) {
33
+ const scenarios = new Map();
34
+ const scenarioEntities = Object.values(document.entities).filter((e) => e.type === "flow-scenario").sort((a, b) => cmp(a.id, b.id));
35
+ for (const entity of scenarioEntities) {
36
+ const name = entity.attributes["name"];
37
+ const order = entity.attributes["order"];
38
+ scenarios.set(entity.id, { id: entity.id, label: name?.kind === "text" ? name.value : entity.id, ...(order?.kind === "quantity" ? { order: order.value } : {}), steps: [] });
39
+ }
40
+ const byRelation = {};
41
+ const byEntity = {};
42
+ for (const relation of Object.values(document.relations).filter((r) => r.type === "flow-step").sort((a, b) => cmp(a.id, b.id))) {
43
+ const attrs = relation.attributes;
44
+ const step = attrs["step"];
45
+ if (step?.kind !== "quantity" || !Number.isInteger(step.value) || step.value < 1 || step.value > 999)
46
+ continue;
47
+ const owner = (role) => {
48
+ const end = relation.endpoints.find((e) => e.role === role)?.target;
49
+ return end?.startsWith("port:") ? document.ports[end]?.owner : end?.startsWith("entity:") ? end : undefined;
50
+ };
51
+ const source = owner("source"), target = owner("target");
52
+ if (source === undefined || target === undefined)
53
+ continue;
54
+ const scenario = attrs["scenario"]?.kind === "reference" ? attrs["scenario"].value : "";
55
+ if (scenario === "" && !scenarios.has(""))
56
+ scenarios.set("", { id: "", label: "", steps: [] });
57
+ const group = scenarios.get(scenario);
58
+ if (group === undefined)
59
+ continue;
60
+ const branch = attrs["branch"]?.kind === "text" ? attrs["branch"].value : undefined;
61
+ const label = attrs["label"]?.kind === "text" ? attrs["label"].value : undefined;
62
+ const kind = attrs["kind"]?.kind === "enum" ? attrs["kind"].value : undefined;
63
+ const realises = attrs["realises"]?.kind === "text" ? attrs["realises"].value : undefined;
64
+ group.steps.push({ relation: relation.id, scenario, step: step.value, ...(branch === undefined ? {} : { branch }), ordinal: 0,
65
+ badge: String(step.value) + (branch ?? ""), source, target, self: source === target,
66
+ ...(label === undefined ? {} : { label }), ...(kind === undefined ? {} : { kind }), ...(realises === undefined ? {} : { realises }) });
67
+ }
68
+ const ordered = [...scenarios.values()].sort((a, b) => a.id === "" ? -1 : b.id === "" ? 1 : (a.order ?? Infinity) - (b.order ?? Infinity) || cmp(a.id, b.id));
69
+ for (const scenario of ordered) {
70
+ scenario.steps.sort((a, b) => a.step - b.step || cmp(a.branch ?? "", b.branch ?? "") || cmp(a.relation, b.relation));
71
+ scenario.steps = scenario.steps.map((step, ordinal) => ({ ...step, ordinal }));
72
+ for (const step of scenario.steps) {
73
+ byRelation[step.relation] = step;
74
+ for (const entity of new Set([step.source, step.target]))
75
+ (byEntity[entity] ??= []).push(step.relation);
76
+ }
77
+ }
78
+ return { scenarios: ordered, byRelation, byEntity };
79
+ }
80
+ /** Run after document validation; this pass only owns the flow semantics. */
81
+ export function validateFlows(document) {
82
+ const diagnostics = [];
83
+ const groups = new Map();
84
+ const seen = new Set();
85
+ const scenarios = new Set(Object.values(document.entities).filter((e) => e.type === "flow-scenario").map((e) => e.id));
86
+ const add = (code, relation, severity = "error") => {
87
+ diagnostics.push(diagnostic({ code, path: "relations." + relation, refs: [relation], severity, message: code }));
88
+ };
89
+ for (const relation of Object.values(document.relations).sort((a, b) => cmp(a.id, b.id))) {
90
+ for (const end of relation.endpoints) {
91
+ const owner = end.target.startsWith("port:") ? document.ports[end.target]?.owner : end.target;
92
+ if (owner !== undefined && scenarios.has(owner)) {
93
+ add("flow-scenario-misused", relation.id);
94
+ if (relation.type === "flow-step")
95
+ add("flow-step-end-invalid", relation.id);
96
+ }
97
+ }
98
+ if (relation.type !== "flow-step")
99
+ continue;
100
+ const step = relation.attributes["step"];
101
+ if (step === undefined) {
102
+ add("flow-step-missing", relation.id);
103
+ continue;
104
+ }
105
+ if (step.kind !== "quantity")
106
+ continue;
107
+ const scenarioAttr = relation.attributes["scenario"];
108
+ const scenario = scenarioAttr?.kind === "reference" ? scenarioAttr.value : "";
109
+ if (scenario !== "" && !scenarios.has(scenario))
110
+ add("flow-scenario-unknown", relation.id);
111
+ const branch = relation.attributes["branch"];
112
+ const key = JSON.stringify([scenario, step.value, branch?.kind === "text" ? branch.value : ""]);
113
+ if (seen.has(key))
114
+ add("flow-step-duplicate", relation.id);
115
+ seen.add(key);
116
+ const groupKey = JSON.stringify([scenario, step.value]);
117
+ const group = groups.get(groupKey) ?? [];
118
+ group.push(relation);
119
+ groups.set(groupKey, group);
120
+ }
121
+ for (const group of groups.values()) {
122
+ if (group.length > 26)
123
+ add("flow-branch-overflow", group[0].id);
124
+ for (const relation of group) {
125
+ if ((group.length === 1) === (relation.attributes["branch"] !== undefined))
126
+ add("flow-branch-without-sibling", relation.id, "warning");
127
+ }
128
+ }
129
+ const numbers = new Map();
130
+ for (const group of groups.values()) {
131
+ const first = group[0];
132
+ const attr = first.attributes["scenario"];
133
+ const scenario = attr?.kind === "reference" ? attr.value : "";
134
+ const step = first.attributes["step"];
135
+ if (step?.kind === "quantity")
136
+ (numbers.get(scenario) ?? numbers.set(scenario, new Set()).get(scenario)).add(step.value);
137
+ }
138
+ for (const [scenario, values] of numbers) {
139
+ if ([...values].sort((a, b) => a - b).some((value, i) => value !== i + 1))
140
+ diagnostics.push(diagnostic({ code: "flow-step-gap", severity: "warning", path: "flows." + scenario, message: "step numbers are not consecutive from 1" }));
141
+ }
142
+ return diagnostics;
143
+ }
144
+ //# sourceMappingURL=flows.js.map
package/dist/fold.d.ts CHANGED
@@ -1,12 +1,3 @@
1
- /**
2
- * Fold binding, folded-edge projection and authored summary labels (M3 §4).
3
- *
4
- * `projectView` is the only folded projection: a pure function from a
5
- * retained source view to a projected `ViewDocument`, recomputed from the
6
- * retained source on every transition and never patched from a previous
7
- * projection (§4.4.3). Views without the §4.1/§4.4.2/§4.5.1 fields behave
8
- * exactly as before; `validateView` owns every refusal.
9
- */
10
1
  import type { SemanticDocument } from "./document.js";
11
2
  import type { ProfileRegistry } from "./profile.js";
12
3
  import type { RelationOccurrence, ViewDocument } from "./view.js";
package/dist/fold.js CHANGED
@@ -1,12 +1,4 @@
1
- /**
2
- * Fold binding, folded-edge projection and authored summary labels (M3 §4).
3
- *
4
- * `projectView` is the only folded projection: a pure function from a
5
- * retained source view to a projected `ViewDocument`, recomputed from the
6
- * retained source on every transition and never patched from a previous
7
- * projection (§4.4.3). Views without the §4.1/§4.4.2/§4.5.1 fields behave
8
- * exactly as before; `validateView` owns every refusal.
9
- */
1
+ import { relationSchema } from "./relation-types.js";
10
2
  import { relationTypeOf } from "./profile.js";
11
3
  import { canonicalise } from "./canonical.js";
12
4
  /** The parent entity occurrence containing an occurrence in this view, if any. */
@@ -59,6 +51,8 @@ export function portRepresentativeOf(view, document, collapsed, id) {
59
51
  if (port === undefined)
60
52
  return id;
61
53
  const ownerRep = representativeOf(view, collapsed, port.ownerOccurrence);
54
+ if (port.ownerOccurrence === ownerRep && collapsed.has(ownerRep) && document.ports[port.port]?.profile === "erd@1")
55
+ return ownerRep;
62
56
  const ownerEntity = view.entityOccurrences[ownerRep]?.entity;
63
57
  const original = document.ports[port.port];
64
58
  const candidates = Object.values(view.portOccurrences).filter((candidate) => {
@@ -204,10 +198,9 @@ export function projectRelationOccurrences(sourceView, document, collapsed) {
204
198
  relationOccurrences[key] = {
205
199
  id: occurrence.id,
206
200
  relation: occurrence.relation,
207
- endpoints: occurrence.endpoints.map((endpoint) => ({
208
- role: endpoint.role,
209
- occurrence: endpoint.occurrence,
210
- })),
201
+ endpoints: occurrence.endpoints.map((endpoint) => endpoint.chainProvenance !== undefined
202
+ ? endpoint
203
+ : { role: endpoint.role, occurrence: endpoint.occurrence }),
211
204
  ...(occurrence.waypoints === undefined
212
205
  ? {}
213
206
  : { waypoints: occurrence.waypoints.map((point) => ({ ...point })) }),
@@ -216,6 +209,8 @@ export function projectRelationOccurrences(sourceView, document, collapsed) {
216
209
  continue;
217
210
  }
218
211
  const endpoints = occurrence.endpoints.map((endpoint) => {
212
+ if (endpoint.chainProvenance !== undefined)
213
+ return endpoint;
219
214
  const original = endpoint.occurrence;
220
215
  const isRelation = sourceView.relationOccurrences[original] !== undefined;
221
216
  const hidden = isRelation ? internal.has(original) : hiddenByFold(sourceView, collapsed, original);
@@ -252,7 +247,7 @@ export function projectRelationOccurrences(sourceView, document, collapsed) {
252
247
  export function projectView(document, sourceView, collapsedOccurrenceIds) {
253
248
  for (const key of Object.keys(sourceView.relationOccurrences).sort()) {
254
249
  const occurrence = sourceView.relationOccurrences[key];
255
- const index = occurrence.endpoints.findIndex((endpoint) => endpoint.semanticTarget !== undefined);
250
+ const index = occurrence.endpoints.findIndex((endpoint) => endpoint.semanticTarget !== undefined && endpoint.chainProvenance === undefined);
256
251
  if (index !== -1) {
257
252
  const endpoint = occurrence.endpoints[index];
258
253
  const refusal = {
@@ -315,9 +310,11 @@ export function reprojectRetained(view, document) {
315
310
  const occurrence = view.relationOccurrences[key];
316
311
  stripped[key] = {
317
312
  ...occurrence,
318
- endpoints: occurrence.endpoints.map((endpoint) => endpoint.sourceOccurrence === undefined
319
- ? { role: endpoint.role, occurrence: endpoint.occurrence }
320
- : { role: endpoint.role, occurrence: endpoint.sourceOccurrence }),
313
+ endpoints: occurrence.endpoints.map((endpoint) => endpoint.chainProvenance !== undefined
314
+ ? endpoint
315
+ : endpoint.sourceOccurrence === undefined
316
+ ? { role: endpoint.role, occurrence: endpoint.occurrence }
317
+ : { role: endpoint.role, occurrence: endpoint.sourceOccurrence }),
321
318
  };
322
319
  }
323
320
  const fresh = projectRelationOccurrences({ ...view, relationOccurrences: stripped }, document, collapsedOf(view));
@@ -430,7 +427,7 @@ function isUndirectedRelation(document, registry, relationId) {
430
427
  if (relation === undefined)
431
428
  return false;
432
429
  const profile = registry.get(relation.profile);
433
- const declared = profile === undefined ? undefined : relationTypeOf(profile, relation.type);
430
+ const declared = profile === undefined ? undefined : relationSchema(document, profile, relation);
434
431
  if (declared === undefined)
435
432
  return false;
436
433
  return declared.direction === "undirected";
@@ -441,7 +438,7 @@ function declaredRoleOrder(document, registry, relationId) {
441
438
  if (relation === undefined)
442
439
  return undefined;
443
440
  const profile = registry.get(relation.profile);
444
- const declared = profile === undefined ? undefined : relationTypeOf(profile, relation.type);
441
+ const declared = profile === undefined ? undefined : relationSchema(document, profile, relation);
445
442
  if (declared === undefined)
446
443
  return undefined;
447
444
  return declared.roles.map((role) => role.role);
package/dist/index.d.ts CHANGED
@@ -15,7 +15,7 @@ export * from "./multiplicity.js";
15
15
  export * from "./archimate-cases.js";
16
16
  export * from "./profile-migrations.js";
17
17
  export * from "./presentation.js";
18
- export * from "./presentation-validate.js";
18
+ export * from "./presentation-relations.js";
19
19
  export * from "./presentation-apply.js";
20
20
  export * from "./resolver.js";
21
21
  export * from "./profiles/index.js";
@@ -29,4 +29,7 @@ export * from "./canonical.js";
29
29
  export * from "./validate.js";
30
30
  export * from "./commands.js";
31
31
  export * from "./migrate.js";
32
+ export { relationBaseType, relationSchema } from "./relation-types.js";
33
+ export { withFlowTypes, validateFlows, flowIndex, type FlowStep, type FlowScenario, type FlowIndex } from "./flows.js";
34
+ export * from "./erd.js";
32
35
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -15,7 +15,7 @@ export * from "./multiplicity.js";
15
15
  export * from "./archimate-cases.js";
16
16
  export * from "./profile-migrations.js";
17
17
  export * from "./presentation.js";
18
- export * from "./presentation-validate.js";
18
+ export * from "./presentation-relations.js";
19
19
  export * from "./presentation-apply.js";
20
20
  export * from "./resolver.js";
21
21
  export * from "./profiles/index.js";
@@ -29,4 +29,7 @@ export * from "./canonical.js";
29
29
  export * from "./validate.js";
30
30
  export * from "./commands.js";
31
31
  export * from "./migrate.js";
32
+ export { relationBaseType, relationSchema } from "./relation-types.js";
33
+ export { withFlowTypes, validateFlows, flowIndex } from "./flows.js";
34
+ export * from "./erd.js";
32
35
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,4 @@
1
+ /** Resolve document relation refinements at the boundary of the frozen presentation adapter. */
2
+ import { validateDiagramPresentation as validatePinnedPresentation } from "./presentation-validate.js";
3
+ export declare function validateDiagramPresentation(...args: Parameters<typeof validatePinnedPresentation>): ReturnType<typeof validatePinnedPresentation>;
4
+ //# sourceMappingURL=presentation-relations.d.ts.map
@@ -0,0 +1,17 @@
1
+ /** Resolve document relation refinements at the boundary of the frozen presentation adapter. */
2
+ import { validateDiagramPresentation as validatePinnedPresentation } from "./presentation-validate.js";
3
+ import { relationBaseType } from "./relation-types.js";
4
+ export function validateDiagramPresentation(...args) {
5
+ const [document, view, options] = args;
6
+ let changed = false;
7
+ const relations = Object.fromEntries(Object.entries(document.relations).map(([id, relation]) => {
8
+ const profile = options.registry.get(relation.profile);
9
+ const type = profile === undefined ? relation.type : relationBaseType(document, profile, relation);
10
+ if (type === relation.type)
11
+ return [id, relation];
12
+ changed = true;
13
+ return [id, { ...relation, type }];
14
+ }));
15
+ return validatePinnedPresentation(changed ? { ...document, relations } : document, view, options);
16
+ }
17
+ //# sourceMappingURL=presentation-relations.js.map
package/dist/profile.d.ts CHANGED
@@ -32,6 +32,7 @@ export interface EntityTypeDeclaration {
32
32
  * or token field is added here: those live in the view/presentation contract.
33
33
  */
34
34
  readonly container?: boolean;
35
+ readonly foldable?: boolean;
35
36
  /** K1 base types, in declaration order (depth-first, left-to-right). */
36
37
  readonly supertypes?: readonly string[];
37
38
  }
@@ -156,6 +157,9 @@ export type AddedConstraint = {
156
157
  readonly attribute: string;
157
158
  };
158
159
  export type ProfileConstraint = {
160
+ readonly kind: "erd-keys";
161
+ readonly maxFields: number;
162
+ } | {
159
163
  readonly kind: "acyclic-hierarchy";
160
164
  readonly hierarchyId: string;
161
165
  } | {
@@ -174,6 +178,40 @@ export interface ProfileLimits {
174
178
  readonly maxRelations?: number;
175
179
  readonly maxEndpointsPerRelation?: number;
176
180
  }
181
+ /** Pure DATA consumed by the document-only endpoint provenance evaluator. */
182
+ export interface ChainConstraint {
183
+ readonly attribute: string;
184
+ readonly equals: string | boolean;
185
+ }
186
+ export interface ChainStep {
187
+ readonly relationTypes: readonly string[];
188
+ readonly direction: "forward" | "inverse";
189
+ readonly repeat: "one" | "zeroOrMore" | "oneOrMore";
190
+ }
191
+ export interface ChainPath {
192
+ readonly steps: readonly ChainStep[];
193
+ readonly endTypes: readonly string[];
194
+ readonly endConstraints?: readonly ChainConstraint[];
195
+ }
196
+ export interface ChainAggregation {
197
+ readonly memberRelationTypes: readonly string[];
198
+ readonly memberTargetChain: ChainPath;
199
+ readonly memberSourceChain: ChainPath;
200
+ /** Fixed UTF-16 tuple order; never a locale-dependent comparator. */
201
+ readonly sort?: "sourceId,targetId,relationId";
202
+ }
203
+ export interface ChainPredicate {
204
+ readonly id: string;
205
+ readonly appliesTo: {
206
+ readonly relationTypes: readonly string[];
207
+ readonly roles: readonly string[];
208
+ readonly startTypes: readonly string[];
209
+ };
210
+ readonly startConstraints?: readonly ChainConstraint[];
211
+ readonly alternatives: readonly ChainPath[];
212
+ readonly selection: "unique" | "ordered" | "first-drawn" | "aggregate";
213
+ readonly aggregation?: ChainAggregation;
214
+ }
177
215
  export interface Profile {
178
216
  readonly id: ProfileId;
179
217
  readonly name: string;
@@ -184,6 +222,7 @@ export interface Profile {
184
222
  readonly relationTypes: readonly RelationTypeDeclaration[];
185
223
  readonly constraints: readonly ProfileConstraint[];
186
224
  readonly limits: ProfileLimits;
225
+ readonly chainPredicates?: readonly ChainPredicate[];
187
226
  /** Declared limits, in prose, for a human reading a skeleton profile. */
188
227
  readonly notes: readonly string[];
189
228
  }
package/dist/profile.js CHANGED
@@ -16,6 +16,7 @@
16
16
  */
17
17
  import { stableStringify } from "./bindings.js";
18
18
  import { diagnostic } from "./diagnostics.js";
19
+ import { validateChainPredicates } from "./chain-profile.js";
19
20
  export function createProfileRegistry(profiles) {
20
21
  const byId = new Map();
21
22
  for (const profile of profiles) {
@@ -119,6 +120,7 @@ export function validateProfile(profile, adapter = "legacy-constraints@1") {
119
120
  // checks below; the retained native run ignores them exactly as before.
120
121
  }
121
122
  diagnostics.push(...validateM3Declarations(profile, seenEntityTypes, adapter));
123
+ diagnostics.push(...validateChainPredicates(profile));
122
124
  return diagnostics;
123
125
  }
124
126
  /**
@@ -0,0 +1,6 @@
1
+ import type { Profile } from '../profile.js';
2
+ export declare const ERD_PROFILE_ID: "erd@1";
3
+ export declare const ERD_CARDINALITIES: readonly ["1", "0..1", "1..n", "0..n"];
4
+ export type ErdCardinality = typeof ERD_CARDINALITIES[number];
5
+ export declare const erdProfile: Profile;
6
+ //# sourceMappingURL=erd.d.ts.map
@@ -0,0 +1,29 @@
1
+ export const ERD_PROFILE_ID = 'erd@1';
2
+ export const ERD_CARDINALITIES = ['1', '0..1', '1..n', '0..n'];
3
+ export const erdProfile = {
4
+ id: ERD_PROFILE_ID, name: 'ERD', version: 1, completeness: 'complete',
5
+ entityTypes: [{ id: 'entity', label: 'Entity', foldable: true, attributes: [
6
+ { name: 'name', kind: 'text', required: true }, { name: 'schema', kind: 'text' },
7
+ ] }],
8
+ portTypes: [{ id: 'field', label: 'Attribute row', directions: ['inout'], attributes: [
9
+ { name: 'dataType', kind: 'text', required: true },
10
+ { name: 'pk', kind: 'boolean', required: true },
11
+ { name: 'fk', kind: 'reference', refKind: 'port' },
12
+ { name: 'nullable', kind: 'boolean', required: true },
13
+ { name: 'ordinal', kind: 'quantity', units: ['index'], integer: true, min: 0, required: true },
14
+ ] }],
15
+ relationTypes: [{ id: 'relationship', label: 'Relationship', direction: 'undirected',
16
+ roles: ['from', 'to'].map(role => ({ role, cardinality: { min: 1, max: 1 }, targets: ['entity', 'port'] })),
17
+ attributes: [
18
+ { name: 'name', kind: 'text', required: true }, { name: 'label', kind: 'text' },
19
+ ...['from', 'to'].flatMap(end => [
20
+ { name: end + 'Cardinality', kind: 'enum', values: ERD_CARDINALITIES, required: true },
21
+ { name: end + 'Role', kind: 'text', required: true },
22
+ ]),
23
+ ],
24
+ }],
25
+ constraints: [{ kind: 'erd-keys', maxFields: 17 }],
26
+ limits: { maxEntities: 1000, maxRelations: 10000, maxEndpointsPerRelation: 2 },
27
+ notes: ['Exactly one primary key per entity; no composite keys. Many-to-many remains one relationship.'],
28
+ };
29
+ //# sourceMappingURL=erd.js.map
@@ -8,6 +8,7 @@
8
8
  */
9
9
  import { type ExecutorProfileBindings } from "../bindings.js";
10
10
  import { type Profile, type ProfileRegistry } from "../profile.js";
11
+ export * from "./erd.js";
11
12
  export * from "./generic.js";
12
13
  export * from "./generic2.js";
13
14
  export * from "./skeletons.js";
@@ -8,11 +8,13 @@
8
8
  */
9
9
  import { embeddedExecutorBindings } from "../bindings.js";
10
10
  import { createProfileRegistry } from "../profile.js";
11
+ import { erdProfile } from "./erd.js";
11
12
  import { genericProfile } from "./generic.js";
12
13
  import { generic2Profile } from "./generic2.js";
13
14
  import { archimateSkeletonProfile, bpmnSkeletonProfile, umlSkeletonProfile } from "./skeletons.js";
14
15
  import { archimate2Profile } from "./archimate2.js";
15
16
  import { uml2Profile } from "./uml2.js";
17
+ export * from "./erd.js";
16
18
  export * from "./generic.js";
17
19
  export * from "./generic2.js";
18
20
  export * from "./skeletons.js";
@@ -37,6 +39,7 @@ export const m3ProfileRegistry = createProfileRegistry([
37
39
  generic2Profile,
38
40
  archimate2Profile,
39
41
  uml2Profile,
42
+ erdProfile,
40
43
  ]);
41
44
  /** All six @1/@2 ids for coexistence and reload witnesses (§3.13.2). */
42
45
  export const allProfilesRegistry = createProfileRegistry([
@@ -45,6 +48,7 @@ export const allProfilesRegistry = createProfileRegistry([
45
48
  generic2Profile,
46
49
  archimate2Profile,
47
50
  uml2Profile,
51
+ erdProfile,
48
52
  ]);
49
53
  /**
50
54
  * The shipped `executor-profile-bindings@1` table (M3 §5.3.1): one verifying
@@ -72,6 +76,7 @@ export const shippedExecutorBindings = lazyBindings([
72
76
  generic2Profile,
73
77
  archimate2Profile,
74
78
  uml2Profile,
79
+ erdProfile,
75
80
  ]);
76
81
  /**
77
82
  * The packaged verified default rows for exactly the four retained @1
@@ -0,0 +1,6 @@
1
+ /** Document-local relation refinements inherit the complete relation declaration. */
2
+ import type { Relation, SemanticDocument } from "./document.js";
3
+ import { type Profile, type RelationTypeDeclaration } from "./profile.js";
4
+ export declare function relationBaseType(document: SemanticDocument, profile: Profile, relation: Relation): string;
5
+ export declare function relationSchema(document: SemanticDocument, profile: Profile, relation: Relation): RelationTypeDeclaration | undefined;
6
+ //# sourceMappingURL=relation-types.d.ts.map
@@ -0,0 +1,16 @@
1
+ import { relationTypeOf } from "./profile.js";
2
+ export function relationBaseType(document, profile, relation) {
3
+ if (relationTypeOf(profile, relation.type) !== undefined)
4
+ return relation.type;
5
+ const definition = document.typeDefinitions[relation.type];
6
+ return definition?.profile === profile.id ? definition.baseType : relation.type;
7
+ }
8
+ export function relationSchema(document, profile, relation) {
9
+ const base = relationTypeOf(profile, relationBaseType(document, profile, relation));
10
+ if (base === undefined)
11
+ return undefined;
12
+ const definition = document.typeDefinitions[relation.type];
13
+ return relation.type === base.id || definition?.profile !== profile.id
14
+ ? base : { ...base, attributes: [...(base.attributes ?? []), ...definition.attributes] };
15
+ }
16
+ //# sourceMappingURL=relation-types.js.map
@@ -1,16 +1,3 @@
1
- /**
2
- * Validation: the only place that decides whether a document or a view is
3
- * writable, and the only producer of the nine named rejected cases.
4
- *
5
- * Three rules it follows without exception:
6
- * 1. It never repairs. A document is refused with diagnostics, never
7
- * "cleaned up" - a silently dropped dangling edge is what study invariant 1
8
- * forbids at the semantic level.
9
- * 2. It reads nothing ambient. Types, roles, cardinalities, constraints and
10
- * limits come from the profile registry handed to it.
11
- * 3. It collects. A caller gets every diagnostic of a run, not the first, so a
12
- * refused transaction can be explained in one pass.
13
- */
14
1
  import { type AttributeSchema } from "./attributes.js";
15
2
  import { type ExecutorProfileBindings } from "./bindings.js";
16
3
  import { type Diagnostic } from "./diagnostics.js";