@sentropic/diagram-core 0.1.0 → 0.3.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.
Files changed (42) hide show
  1. package/README.md +164 -1
  2. package/dist/bindings.js +1 -0
  3. package/dist/chain-profile.d.ts +4 -0
  4. package/dist/chain-profile.js +85 -0
  5. package/dist/chain.d.ts +11 -0
  6. package/dist/chain.js +284 -0
  7. package/dist/commands.js +5 -3
  8. package/dist/diagnostics.d.ts +20 -4
  9. package/dist/erd-validate.d.ts +5 -0
  10. package/dist/erd-validate.js +33 -0
  11. package/dist/erd.d.ts +69 -0
  12. package/dist/erd.js +72 -0
  13. package/dist/flows.d.ts +36 -0
  14. package/dist/flows.js +144 -0
  15. package/dist/fold.d.ts +0 -9
  16. package/dist/fold.js +16 -19
  17. package/dist/index.d.ts +7 -2
  18. package/dist/index.js +7 -2
  19. package/dist/layout-hints.d.ts +158 -0
  20. package/dist/layout-hints.js +459 -0
  21. package/dist/notation.d.ts +121 -0
  22. package/dist/notation.js +225 -0
  23. package/dist/presentation-relations.d.ts +4 -0
  24. package/dist/presentation-relations.js +17 -0
  25. package/dist/profile.d.ts +39 -0
  26. package/dist/profile.js +2 -0
  27. package/dist/profiles/erd.d.ts +6 -0
  28. package/dist/profiles/erd.js +29 -0
  29. package/dist/profiles/index.d.ts +1 -0
  30. package/dist/profiles/index.js +5 -0
  31. package/dist/relation-types.d.ts +6 -0
  32. package/dist/relation-types.js +16 -0
  33. package/dist/validate.d.ts +0 -13
  34. package/dist/validate.js +63 -18
  35. package/dist/view-schema-pin.d.ts +9 -6
  36. package/dist/view-schema-pin.js +17 -7
  37. package/dist/view.d.ts +12 -3
  38. package/package.json +8 -3
  39. package/schemas/diagram-view-schema-3.json +1 -0
  40. package/schemas/diagram-view-schema-3.sha256 +1 -0
  41. package/schemas/ds-layout-hints-1.json +1 -0
  42. package/schemas/ds-layout-hints-1.sha256 +1 -0
@@ -9,9 +9,9 @@
9
9
  * fixture - the test asserts the CODE, not merely the failure.
10
10
  */
11
11
  /** Stable, machine-readable refusal codes. Additive; never renamed in place. */
12
- export type DiagnosticCode =
12
+ export type DiagnosticCode = "erd-missing-pk" | "erd-multiple-pk" | "erd-dangling-fk" | "erd-missing-end" | "erd-duplicate-field" | "erd-invalid-fk-target"
13
13
  /** A reference resolves to nothing in its namespace. */
14
- "dangling-reference"
14
+ | "dangling-reference"
15
15
  /** A well-formed reference of the wrong namespace (occurrence where entity was required, …). */
16
16
  | "reference-type-mismatch"
17
17
  /** A relation type declared `shape: "tree"` closes a cycle. */
@@ -27,9 +27,25 @@ export type DiagnosticCode =
27
27
  /** A command's `baseRevision` is not the state's revision. Carries expected and seen. */
28
28
  | "revision-conflict"
29
29
  /** An extension at validation level `unsupported`: preserved on import, never promoted. */
30
- | "extension-unsupported" | "malformed-ref" | "duplicate-id" | "record-key-mismatch" | "schema-version-malformed" | "schema-migration-required" | "document-not-an-object" | "unknown-profile" | "profile-not-declared" | "unknown-entity-type" | "unknown-relation-type" | "unknown-port-type" | "type-definition-conflict" | "attribute-type-mismatch" | "attribute-required-missing" | "enum-value-not-allowed" | "quantity-unit-not-allowed" | "text-too-long" | "date-not-iso8601" | "unique-attribute-violation" | "endpoint-role-unknown" | "endpoint-cardinality-violation" | "endpoint-target-not-allowed" | "hierarchy-multiple-parents" | "port-direction-not-allowed" | "port-owner-mismatch" | "view-document-mismatch" | "revision-divergence" | "occurrence-endpoint-mismatch" | "value-not-finite" | "value-not-serialisable" | "limit-exceeded"
30
+ | "extension-unsupported" | "malformed-ref" | "duplicate-id" | "record-key-mismatch" | "schema-version-malformed" | "schema-migration-required" | "document-not-an-object" | "unknown-profile" | "profile-not-declared" | "unknown-entity-type" | "unknown-relation-type" | "unknown-port-type" | "flow-types-conflict" | "flow-step-missing" | "flow-step-duplicate" | "flow-branch-overflow" | "flow-scenario-unknown" | "flow-scenario-misused" | "flow-step-end-invalid" | "flow-branch-without-sibling" | "flow-step-gap" | "type-definition-conflict" | "type-definition-reserved" | "type-definition-ambiguous" | "attribute-type-mismatch" | "attribute-required-missing" | "enum-value-not-allowed" | "quantity-unit-not-allowed" | "text-too-long" | "date-not-iso8601" | "unique-attribute-violation" | "endpoint-role-unknown" | "endpoint-cardinality-violation" | "endpoint-target-not-allowed" | "hierarchy-multiple-parents" | "port-direction-not-allowed" | "port-owner-mismatch" | "view-document-mismatch" | "revision-divergence" | "occurrence-endpoint-mismatch" | "value-not-finite" | "value-not-serialisable" | "limit-exceeded"
31
31
  /** A hierarchy endpoint targets a foreign-profile entity with no admitted semantic join (M3 §3.2.3). */
32
- | "endpoint-without-join" | "legend-key-parent-invalid" | "tone-category-unknown" | "text-pattern-mismatch" | "quantity-not-integer" | "quantity-below-min" | "quantity-above-max" | "relationship-matrix-violation" | "multiplicity-invalid" | "stereotype-application-invalid" | "reference-target-type" | "struct-type-unknown" | "struct-field-not-in-schema" | "struct-type-not-allowed" | "supertype-unknown" | "supertype-cycle" | "attribute-conflict" | "abstract-instantiated" | "unknown-command" | "target-already-exists" | "target-missing" | "delete-policy-required" | "delete-policy-refused" | "placement-kind-mismatch" | "inverse-budget-exceeded" | "extension-hash-mismatch" | "extension-source-not-retained" | "view-already-exists";
32
+ | "endpoint-without-join" | "legend-key-parent-invalid" | "tone-category-unknown" | "text-pattern-mismatch" | "quantity-not-integer" | "quantity-below-min" | "quantity-above-max" | "relationship-matrix-violation" | "multiplicity-invalid" | "stereotype-application-invalid" | "reference-target-type" | "struct-type-unknown" | "struct-field-not-in-schema" | "struct-type-not-allowed" | "supertype-unknown" | "supertype-cycle" | "attribute-conflict" | "abstract-instantiated" | "unknown-command" | "target-already-exists" | "target-missing" | "delete-policy-required" | "delete-policy-refused" | "placement-kind-mismatch" | "inverse-budget-exceeded" | "extension-hash-mismatch" | "extension-source-not-retained" | "view-already-exists"
33
+ /** `vocabulary` absent or not the pinned one: nothing else is read. */
34
+ | "layout-vocabulary-unknown"
35
+ /** Structural failure: wrong type, malformed reference, missing required member. */
36
+ | "layout-hints-invalid" | "layout-mode-unknown"
37
+ /** A mode specified for a later vocabulary: refused, never coerced. */
38
+ | "layout-mode-not-implemented"
39
+ /** A mode outside the views it is admitted on. */
40
+ | "layout-mode-out-of-scope" | "layout-hint-unknown"
41
+ /** A spacing override or a coordinate. */
42
+ | "layout-hint-forbidden"
43
+ /** A hint specified for a later vocabulary. */
44
+ | "layout-hint-not-implemented"
45
+ /** A hint the selected mode does not read. */
46
+ | "layout-hint-out-of-scope"
47
+ /** Two authored statements that cannot both hold. */
48
+ | "layout-hint-conflict";
33
49
  export type DiagnosticSeverity = "error" | "warning";
34
50
  export interface Diagnostic {
35
51
  readonly code: DiagnosticCode;
@@ -0,0 +1,5 @@
1
+ import { type Diagnostic } from './diagnostics.js';
2
+ import type { SemanticDocument } from './document.js';
3
+ import type { Profile } from './profile.js';
4
+ export declare function validateErdKeys(document: SemanticDocument, profile: Profile, maxFields: number): Diagnostic[];
5
+ //# sourceMappingURL=erd-validate.d.ts.map
@@ -0,0 +1,33 @@
1
+ import { diagnostic } from './diagnostics.js';
2
+ export function validateErdKeys(document, profile, maxFields) {
3
+ const out = [];
4
+ const report = (code, path, message) => out.push(diagnostic({ code, path, message }));
5
+ for (const entity of Object.values(document.entities).filter(e => e.profile === profile.id)) {
6
+ const fields = Object.values(document.ports).filter(p => p.owner === entity.id);
7
+ const path = 'entities.' + entity.id;
8
+ const keys = fields.filter(p => p.attributes.pk?.kind === 'boolean' && p.attributes.pk.value);
9
+ if (keys.length !== 1)
10
+ report(keys.length ? 'erd-multiple-pk' : 'erd-missing-pk', path, 'An entity requires exactly one primary key');
11
+ if (fields.length > maxFields)
12
+ report('limit-exceeded', path, 'Too many attribute rows: ' + fields.length);
13
+ if (new Set(fields.map(p => p.name)).size !== fields.length || new Set(fields.map(p => p.attributes.ordinal?.kind === 'quantity' ? p.attributes.ordinal.value : -1)).size !== fields.length)
14
+ report('erd-duplicate-field', path, 'Field names and ordinals must be distinct');
15
+ for (const field of fields) {
16
+ const fk = field.attributes.fk;
17
+ if (fk?.kind !== 'reference')
18
+ continue;
19
+ const target = document.ports[fk.value];
20
+ if (!target)
21
+ report('erd-dangling-fk', 'ports.' + field.id, 'Foreign key target is missing: ' + fk.value);
22
+ else if (target.profile !== profile.id || target.attributes.pk?.kind !== 'boolean' || !target.attributes.pk.value)
23
+ report('erd-invalid-fk-target', 'ports.' + field.id, 'Foreign key must target a primary key');
24
+ }
25
+ }
26
+ for (const relation of Object.values(document.relations).filter(r => r.profile === profile.id)) {
27
+ for (const role of ['from', 'to'])
28
+ if (!relation.endpoints.some(e => e.role === role))
29
+ report('erd-missing-end', 'relations.' + relation.id, 'Missing relationship end: ' + role);
30
+ }
31
+ return out;
32
+ }
33
+ //# sourceMappingURL=erd-validate.js.map
package/dist/erd.d.ts ADDED
@@ -0,0 +1,69 @@
1
+ import { type Entity, type SemanticPort, type Relation } from './document.js';
2
+ import { type EntityOccurrence, type PortOccurrence, type RelationOccurrence } from './view.js';
3
+ import { type DiagramPresentation } from './presentation.js';
4
+ import type { ErdCardinality } from './profiles/erd.js';
5
+ export interface EngramErdField {
6
+ readonly name: string;
7
+ readonly type: string;
8
+ readonly pk: boolean;
9
+ readonly fk: {
10
+ readonly class: string;
11
+ readonly field: string;
12
+ } | null;
13
+ readonly nullable: boolean;
14
+ }
15
+ export interface EngramErdScene {
16
+ readonly id: string;
17
+ readonly container: string;
18
+ readonly classes: readonly {
19
+ readonly name: string;
20
+ readonly fields: readonly EngramErdField[];
21
+ }[];
22
+ readonly relations: readonly {
23
+ readonly name: string;
24
+ readonly roleLabel: string;
25
+ readonly from: {
26
+ readonly class: string;
27
+ readonly cardinality: ErdCardinality;
28
+ readonly role?: string;
29
+ };
30
+ readonly to: {
31
+ readonly class: string;
32
+ readonly cardinality: ErdCardinality;
33
+ readonly role?: string;
34
+ };
35
+ }[];
36
+ }
37
+ /** Injective encoding into the narrow local-reference grammar, including punctuation and Unicode. */
38
+ export declare const erdLocalId: (name: string) => string;
39
+ export declare const erdEntityOccurrence: (entity: string) => import("./refs.js").OccurrenceRef;
40
+ export declare const erdPortOccurrence: (port: string, side?: "east" | "west") => import("./refs.js").OccurrenceRef;
41
+ /** One scene relation stays one semantic relation, including many-to-many and self references. */
42
+ export declare function convertEngramErdScene(scene: EngramErdScene): {
43
+ document: {
44
+ entities: Record<string, Entity>;
45
+ ports: Record<string, SemanticPort>;
46
+ relations: Record<string, Relation>;
47
+ documentId: import("./refs.js").DocumentRef;
48
+ schemaVersion: import("./document.js").SchemaVersion;
49
+ revision: number;
50
+ profileRefs: readonly import("./profile.js").ProfileId[];
51
+ typeDefinitions: Readonly<Record<string, import("./document.js").TypeDefinition>>;
52
+ resources: Readonly<Record<string, import("./document.js").ResourceDescriptor>>;
53
+ extensions: readonly import("./document.js").PreservedExtension[];
54
+ };
55
+ view: {
56
+ entityOccurrences: Record<string, EntityOccurrence>;
57
+ portOccurrences: Record<string, PortOccurrence>;
58
+ relationOccurrences: Record<string, RelationOccurrence>;
59
+ viewId: import("./refs.js").ViewRef;
60
+ semanticDocumentId: import("./refs.js").DocumentRef;
61
+ revision: number;
62
+ groups: Readonly<Record<string, import("./view.js").VisualGroup>>;
63
+ filters: readonly import("./view.js").ViewFilter[];
64
+ presentation: import("./view.js").PresentationState;
65
+ summaryLabels?: Readonly<Record<string, import("./view.js").SummaryDefinition>>;
66
+ };
67
+ presentation: DiagramPresentation;
68
+ };
69
+ //# sourceMappingURL=erd.d.ts.map
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
@@ -2,7 +2,7 @@
2
2
  * `@sentropic/diagram-core` - the typed semantic core.
3
3
  *
4
4
  * No runtime dependency, no DOM, no framework, no renderer. The package is
5
- * PRIVATE: no npm name is committed without an owner's gesture.
5
+ * public as `@sentropic/diagram-core`.
6
6
  *
7
7
  * Read `README.md` for the model, its limits and what is not covered yet.
8
8
  */
@@ -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,9 @@ 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";
35
+ export * from "./layout-hints.js";
36
+ export * from "./notation.js";
32
37
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@
2
2
  * `@sentropic/diagram-core` - the typed semantic core.
3
3
  *
4
4
  * No runtime dependency, no DOM, no framework, no renderer. The package is
5
- * PRIVATE: no npm name is committed without an owner's gesture.
5
+ * public as `@sentropic/diagram-core`.
6
6
  *
7
7
  * Read `README.md` for the model, its limits and what is not covered yet.
8
8
  */
@@ -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,9 @@ 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";
35
+ export * from "./layout-hints.js";
36
+ export * from "./notation.js";
32
37
  //# sourceMappingURL=index.js.map