@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
package/README.md CHANGED
@@ -4,7 +4,7 @@ The typed semantic core of the diagram programme: versioned documents and
4
4
  profiles, views with occurrences, and transactional commands that return their
5
5
  logical inverse. No runtime dependency, no DOM, no framework, no renderer.
6
6
 
7
- This package is public as `@sentropic/diagram-core` (0.1.0, first publication).
7
+ This package is public as `@sentropic/diagram-core`, at version `0.3.0`.
8
8
  Pin the exact version — never a range, never `latest`. Publication is CI-only
9
9
  through `.github/workflows/diagram-core-publish.yml` on tags `diagram-core-v<version>`.
10
10
 
@@ -78,6 +78,62 @@ optional grid. It is stored here, and deliberately not imported from a renderer
78
78
  package: a migration-versioned persisted schema must not be hostage to another
79
79
  package's type evolution.
80
80
 
81
+ ### Endpoint provenance: fold and chain
82
+
83
+ Endpoints attach a relation role to a drawn occurrence. When the drawing differs
84
+ from its semantic target, exactly one provenance arm supplies the witness:
85
+
86
+ | Form | Fields beyond `role`, `occurrence` |
87
+ | --- | --- |
88
+ | Plain | None; the occurrence draws the role target directly. |
89
+ | Fold | `semanticTarget` and `sourceOccurrence`; the current fold proves the representative. |
90
+ | Chain | `semanticTarget` and `chainProvenance`; `sourceOccurrence` is absent. |
91
+
92
+ `chainProvenance` contains a profile-declared `predicateId`, ordered relation
93
+ `hops` from the semantic target to the drawn entity, and aggregate-only `members`.
94
+ Profiles declare `chainPredicates` as serialisable DATA: typed directed steps,
95
+ repeat modes, strict string/boolean attribute constraints, alternatives and
96
+ `unique`, `ordered`, `first-drawn` or `aggregate` selection. Types include resolved
97
+ ancestry in their own profile. Walks see only that profile's semantic entities,
98
+ relations and attributes; the sole view input is whether an occurrence exists
99
+ for an entity. Geometry, groups, collapsed state and filters cannot prove a chain.
100
+ A drawn port is tested through its owner entity.
101
+
102
+ Walks stop at the first admitted end and close cycles with an iterative branch
103
+ stack. Completed suffixes are reused while their cycle-pruning ancestors remain
104
+ on the branch, preserving the first witness in candidate order. `first-drawn`
105
+ accepts a drawn completed single-step prefix (the exposer in an external-API
106
+ chain) without requiring the remaining suffix. A drawn non-admitted intermediate
107
+ blocks further lifting.
108
+ Aggregates recompute the complete member set, test each member's target and source
109
+ chains, sort by UTF-16 `(sourceId, targetId, relationId)`, and require the smallest
110
+ member as carrier. Any occurrence of the same repo entity is an equivalent end.
111
+
112
+ `validateView` reports `occurrence-endpoint-mismatch` with one of
113
+ `chain-not-declared`, `chain-hop-mismatch`, `chain-not-proven`, `chain-ambiguous`
114
+ or `chain-aggregation-mismatch` in `details.check`. Candidate lists are in `refs`;
115
+ details remain scalar. Pairing failures retain the fold `provenance-missing`
116
+ template, and dangling witness refs precede chain checks. `validateProfile` uses
117
+ `type-definition-conflict` with `chain-duplicate-id`, `chain-unknown-type`,
118
+ `chain-invalid-direction`, `chain-invalid-repeat` or `chain-members-not-aggregate`;
119
+ functions fail serialisation with `value-not-serialisable`.
120
+
121
+ Selection owns its cardinality outcome: several distinct ends under `unique`
122
+ give `chain-not-proven` with `cause: "cardinality"`; several drawn ends in the
123
+ chosen `ordered` alternative give `chain-ambiguous`. Semantic cardinality remains
124
+ profile-side; `validateView` never calls `validateDocument`.
125
+
126
+ Projection, removal repair and replacement inverses carry chain endpoints
127
+ verbatim, including hop/member order, and leave validation to `validateView`.
128
+ Old views keep their canonical bytes. Frozen schemas `@1/@2` refuse chain fields;
129
+ `@3` adds the exclusive pairing forms and resolves by exact pin only, without
130
+ changing the presentation pin. The package includes
131
+ [`schemas/diagram-view-schema-3.json`](schemas/diagram-view-schema-3.json) and its
132
+ [canonical SHA-256](schemas/diagram-view-schema-3.sha256):
133
+ `b415c05197692baa5f74ab35e3150ce58079cf9f06201df5e581d222a8d2c0df`.
134
+ The `@3` schema shipped with `0.2.0`. `@sentropic/diagram-canvas` pins this
135
+ package by exact version; schema inclusion does not certify downstream adoption.
136
+
81
137
  ### Commands are transactions
82
138
 
83
139
  `applyTransaction(state, transaction, { registry })` returns either
@@ -130,6 +186,98 @@ so a migrated document may still be unwritable — for instance when a value tha
130
186
  failed to convert was a **required** attribute. The report names the element; the
131
187
  decision is the host's.
132
188
 
189
+ ## Layout-hint vocabulary (`ds-layout-hints@1`)
190
+
191
+ A view declaration names its layout through one closed vocabulary, authored,
192
+ versioned and pinned here. A consumer (engram's view mechanism) references the
193
+ pin and calls the validator; it never keeps a mode table of its own.
194
+
195
+ ```ts
196
+ import { DS_LAYOUT_VOCABULARY_PIN, validateLayoutHints, lowerLayoutHints } from "@sentropic/diagram-core";
197
+
198
+ const layout = { vocabulary: "ds-layout-hints@1", mode: "auto-pack", grouping_axis: "rows" };
199
+ const diagnostics = validateLayoutHints(layout); // [] means valid
200
+ ```
201
+
202
+ | Export | What it is |
203
+ |---|---|
204
+ | `DS_LAYOUT_HINTS_SCHEMA` | JSON Schema 2020-12, closed, deeply frozen. Also shipped as [`schemas/ds-layout-hints-1.json`](schemas/ds-layout-hints-1.json) (canonical bytes) with its [SHA-256](schemas/ds-layout-hints-1.sha256). |
205
+ | `DS_LAYOUT_HINTS_RULES` | The semantic rules as frozen data. Every list equals an enum of the schema's `$defs`. |
206
+ | `validateLayoutHints(value, context?)` | Pure, never throws. Structure and semantics in one pass; diagnostics sorted by (path, code). |
207
+ | `DS_LAYOUT_VOCABULARY_PIN` | `PresentationPin` `{ id, version, contentDigest }`. |
208
+ | `lowerLayoutHints(hints, roots?)` | A valid payload lowered to the hints the layout engine takes. |
209
+
210
+ The pin:
211
+
212
+ ```
213
+ id https://sentropic.dev/schemas/diagram/layout-hints/v1
214
+ version ds-layout-hints@1
215
+ contentDigest e72fd3f3446e19585b2992071f57c3777685f27087165c932806e12354ced42c
216
+ ```
217
+
218
+ `contentDigest` is the SHA-256 (bare 64 lowercase hex) of the RFC 8785 bytes of
219
+ the schema: `sha256Hex(canonicalBytes(DS_LAYOUT_HINTS_SCHEMA))`. The refusal
220
+ classification lives in the schema's `$defs`, so the digest covers it. Any
221
+ change to the schema is `ds-layout-hints@2`; `tests/layout-hints.test.ts`
222
+ recomputes the digest and fails on an edit in place.
223
+
224
+ **Scope rule of `@1`: a payload that validates must render.** The vocabulary
225
+ admits only what the layout engine of `@sentropic/diagram-canvas` executes at
226
+ this version.
227
+
228
+ | `mode` | Engine entry | Admitted on |
229
+ |---|---|---|
230
+ | `auto-pack` | `layoutMeasured` | every view |
231
+ | `layered-flow` | `layoutDocument` | `generic@1` views without a typed presentation, stated through `context` |
232
+
233
+ Hints, read by `auto-pack` only: `ordering`, `rootOrder`, `grouping`
234
+ (recursive groups `{ id, direction, items, stretch? }`), `grouping_axis`
235
+ (`"rows" | "columns"`, a shorthand for one group over the root level, exclusive
236
+ with `grouping`) and `stretch`. `mode` is required: an absent mode is never
237
+ read as `auto-pack`.
238
+
239
+ Refusals are typed, and nothing is coerced to another mode:
240
+
241
+ | Code | Raised when |
242
+ |---|---|
243
+ | `layout-vocabulary-unknown` | `vocabulary` is absent or is not `ds-layout-hints@1`. Nothing else is read. |
244
+ | `layout-hints-invalid` | Structural failure: wrong type, malformed entity reference, missing member. |
245
+ | `layout-mode-not-implemented` | `lane-stack`, `matrix-grid`, `tree`: specified, not executed yet. `details.vocabulary` names `ds-layout-hints@2`. |
246
+ | `layout-mode-unknown` | Any other mode. |
247
+ | `layout-mode-out-of-scope` | `layered-flow` on a view that is not `generic@1`, that carries a typed presentation, that declares a presentation vocabulary, or whose `context` is not stated. |
248
+ | `layout-hint-forbidden` | A spacing override or a coordinate: `density`, `cardGapX`, `cardGapY`, `zoneGapX`, `zoneGapY`, `rankGap`, `gapAfter`, `x`, `y`, `width`, `height`, `edge_label_orientation`. |
249
+ | `layout-hint-not-implemented` | `direction`, `rotate_labels`: specified, not executed yet. |
250
+ | `layout-hint-out-of-scope` | A hint under `layered-flow`, which takes none. |
251
+ | `layout-hint-unknown` | Any other property. |
252
+ | `layout-hint-conflict` | `grouping` with `grouping_axis`; a group id used twice; a leaf placed twice; a member listed twice, ordered under two parents or under itself. |
253
+
254
+ What the validator cannot see: whether a reference exists in the document and
255
+ whether the members of a group are siblings. Both need the document and stay
256
+ with the layout engine (`validateHints` in `@sentropic/diagram-canvas`).
257
+ Whether a view kind takes a layout at all is the declaring grammar's rule.
258
+
259
+ ## Notation pin (`diagram-notation@1`)
260
+
261
+ `DIAGRAM_NOTATION_PIN` is exported beside the layout pin:
262
+
263
+ ```
264
+ id diagram-notation
265
+ version 1
266
+ contentDigest b4bfa7174a7a53ec23b8a8d7580d6bdfc3bab7f29deb1204aa2e4ce12424909f
267
+ ```
268
+
269
+ `contentDigest` is the SHA-256 of the RFC 8785 bytes of
270
+ `{ schema: DIAGRAM_NOTATION_SCHEMA, rules: DIAGRAM_NOTATION_RULES }`. The schema
271
+ (`$id` `engram:diagram-notation-schema/1`) is structural only: closed objects,
272
+ enums, string bounds, required `role`, `nature` and `encoding`, slot shape. The
273
+ rules are frozen data: the role table (nature, `icon`, `kicker`, `variant`,
274
+ `holds`), the variants of each nature, the property list of each encoding,
275
+ slot ownership. Any change to either is `diagram-notation@2`.
276
+
277
+ Not covered: `validateNotation`, `validateViewNotation` and `resolveNotation`.
278
+ This version freezes the vocabulary a consumer pins and ships no executor for
279
+ it; `Profile` has no `notation` member yet.
280
+
133
281
  ## What this package does not import
134
282
 
135
283
  Nothing. Not one specifier that is not a relative module of its own source, which
@@ -163,6 +311,10 @@ a test asserts by scanning every file. In particular:
163
311
  - **Codecs, source text, AST/CST and conversion reports**: GD-M4. Nothing here
164
312
  parses, fetches or executes imported content, a URI or markup.
165
313
  - **Native BPMN / ArchiMate / UML profiles**: GD-M3. See the skeletons' `notes`.
314
+ - **The notation executor**: `diagram-notation@1` is pinned as data only.
315
+ - **Layout modes `lane-stack`, `matrix-grid`, `tree` and the hints `direction`,
316
+ `rotate_labels`**: refused by `ds-layout-hints@1` until the layout engine
317
+ executes them.
166
318
  - **A reference disposition in the delete policy.** The policy governs
167
319
  occurrences, relations and ports. An entity a typed reference attribute still
168
320
  points at cannot be deleted: the transaction refuses itself on the final state
@@ -184,6 +336,8 @@ src/refs.ts the seven nominal reference types, their guards and diagnos
184
336
  src/diagnostics.ts one code per refusal; nothing returns a boolean validity
185
337
  src/attributes.ts typed attribute values and their schemas
186
338
  src/profile.ts profile declarations, registry, and profile self-validation
339
+ src/chain-profile.ts chain predicate DATA declaration checks
340
+ src/chain.ts indexed document-only chain walks, selection and aggregate witnesses
187
341
  src/profiles/ generic@1 (complete), bpmn@1 / archimate@1 / uml@1 (skeletons)
188
342
  src/document.ts SemanticDocument, entities, relations, ports, resources, extensions
189
343
  src/view.ts ViewDocument, the three occurrence kinds, groups, filters, presentation
@@ -193,6 +347,8 @@ src/hash.ts fnv1a64, dependency-free, non-cryptographic
193
347
  src/validate.ts every refusal, including the nine named rejected cases
194
348
  src/commands.ts 18 commands, transactions, effects, inverses
195
349
  src/migrate.ts registered migrations and their reports
350
+ src/layout-hints.ts ds-layout-hints@1: schema, rules, validator, pin, lowering
351
+ src/notation.ts diagram-notation@1: schema, rules, pin (no executor)
196
352
  fixtures/ valid documents, a divergent-revision state, a command
197
353
  sequence, the nine rejected cases, a 1.0 stored document
198
354
  tests/ 10 suites; `refs-nominal.test.ts` is a COMPILER test
@@ -211,3 +367,10 @@ reference types are not interchangeable with one `@ts-expect-error` per
211
367
  illegitimate assignment (42 ordered pairs). Those assertions only mean something
212
368
  if a compiler reads them. Remove the brand from `Ref<K>` and `check` reports 42
213
369
  × TS2578 ("Unused '@ts-expect-error' directive") — measured, not assumed.
370
+
371
+ ## Numbered flows (DC-2c.1)
372
+
373
+ `withFlowTypes`, `validateFlows` and `flowIndex` provide authored flow relations
374
+ and scenarios. Relation refinements resolve through `relationBaseType` and
375
+ `relationSchema`, preserving inherited roles and constraints. See
376
+ [the authoring contract and mapping examples](../../docs/DC2C_NUMBERED_FLOWS.md).
package/dist/bindings.js CHANGED
@@ -28,6 +28,7 @@ const IMPOSED_ADAPTERS = {
28
28
  "archimate@1": LEGACY_CONSTRAINTS_ADAPTER,
29
29
  "bpmn@1": LEGACY_CONSTRAINTS_ADAPTER,
30
30
  "uml@1": LEGACY_CONSTRAINTS_ADAPTER,
31
+ "erd@1": SCOPED_CONSTRAINTS_ADAPTER,
31
32
  "generic@2": SCOPED_CONSTRAINTS_ADAPTER,
32
33
  "archimate@2": SCOPED_CONSTRAINTS_ADAPTER,
33
34
  "uml@2": SCOPED_CONSTRAINTS_ADAPTER,
@@ -0,0 +1,4 @@
1
+ import { type Diagnostic } from "./diagnostics.js";
2
+ import type { Profile } from "./profile.js";
3
+ export declare function validateChainPredicates(profile: Profile): readonly Diagnostic[];
4
+ //# sourceMappingURL=chain-profile.d.ts.map
@@ -0,0 +1,85 @@
1
+ /** Declaration checks for the optional, serialisable chain DATA vocabulary. */
2
+ import { tryCanonicalise } from "./canonical.js";
3
+ import { diagnostic } from "./diagnostics.js";
4
+ export function validateChainPredicates(profile) {
5
+ if (profile.chainPredicates === undefined)
6
+ return [];
7
+ const root = `profiles.${profile.id}.chainPredicates`;
8
+ const serialised = tryCanonicalise(profile.chainPredicates, root);
9
+ if (!serialised.ok)
10
+ return serialised.diagnostics;
11
+ const diagnostics = [];
12
+ const entities = new Set(profile.entityTypes.map((type) => type.id));
13
+ const relations = new Set(profile.relationTypes.map((type) => type.id));
14
+ const attributes = new Set(profile.entityTypes.flatMap((type) => type.attributes.map((field) => field.name)));
15
+ const seen = new Set();
16
+ for (const [index, predicate] of profile.chainPredicates.entries()) {
17
+ const path = `${root}[${index}]`;
18
+ const fail = (check, field) => {
19
+ diagnostics.push(diagnostic({
20
+ code: "type-definition-conflict", path: `${path}${field}`,
21
+ message: `chain predicate ${predicate.id} fails check ${check}`,
22
+ details: { check },
23
+ }));
24
+ };
25
+ const types = (values, known, field) => {
26
+ if (values.length === 0 || values.some((value) => !known.has(value)))
27
+ fail("chain-unknown-type", field);
28
+ };
29
+ const constraints = (values, field) => {
30
+ for (const [i, constraint] of (values ?? []).entries()) {
31
+ if (!attributes.has(constraint.attribute))
32
+ fail("chain-unknown-type", `${field}[${i}].attribute`);
33
+ }
34
+ };
35
+ const walk = (value, field) => {
36
+ types(value.endTypes, entities, `${field}.endTypes`);
37
+ constraints(value.endConstraints, `${field}.endConstraints`);
38
+ if (value.steps.length === 0)
39
+ fail("chain-unknown-type", `${field}.steps`);
40
+ for (const [i, step] of value.steps.entries()) {
41
+ types(step.relationTypes, relations, `${field}.steps[${i}].relationTypes`);
42
+ if (step.direction !== "forward" && step.direction !== "inverse") {
43
+ fail("chain-invalid-direction", `${field}.steps[${i}].direction`);
44
+ }
45
+ if (!["one", "zeroOrMore", "oneOrMore"].includes(step.repeat)) {
46
+ fail("chain-invalid-repeat", `${field}.steps[${i}].repeat`);
47
+ }
48
+ }
49
+ };
50
+ if (predicate.id.length === 0 || seen.has(predicate.id))
51
+ fail("chain-duplicate-id", ".id");
52
+ seen.add(predicate.id);
53
+ types(predicate.appliesTo.relationTypes, relations, ".appliesTo.relationTypes");
54
+ types(predicate.appliesTo.startTypes, entities, ".appliesTo.startTypes");
55
+ const roles = new Set(profile.relationTypes
56
+ .filter((type) => predicate.appliesTo.relationTypes.includes(type.id))
57
+ .flatMap((type) => type.roles.map((role) => role.role)));
58
+ types(predicate.appliesTo.roles, roles, ".appliesTo.roles");
59
+ constraints(predicate.startConstraints, ".startConstraints");
60
+ if (predicate.alternatives.length === 0)
61
+ fail("chain-unknown-type", ".alternatives");
62
+ predicate.alternatives.forEach((alternative, i) => walk(alternative, `.alternatives[${i}]`));
63
+ const aggregation = predicate.aggregation;
64
+ const raw = predicate;
65
+ if (predicate.selection !== "aggregate") {
66
+ if (aggregation !== undefined || raw["sort"] !== undefined || raw["members"] !== undefined) {
67
+ fail("chain-members-not-aggregate", ".aggregation");
68
+ }
69
+ }
70
+ else if (aggregation?.memberRelationTypes === undefined || aggregation.memberTargetChain === undefined ||
71
+ aggregation.memberSourceChain === undefined) {
72
+ fail("chain-members-not-aggregate", ".aggregation");
73
+ }
74
+ else {
75
+ types(aggregation.memberRelationTypes, relations, ".aggregation.memberRelationTypes");
76
+ walk(aggregation.memberTargetChain, ".aggregation.memberTargetChain");
77
+ walk(aggregation.memberSourceChain, ".aggregation.memberSourceChain");
78
+ if (aggregation.sort !== undefined && aggregation.sort !== "sourceId,targetId,relationId") {
79
+ fail("chain-members-not-aggregate", ".aggregation.sort");
80
+ }
81
+ }
82
+ }
83
+ return diagnostics;
84
+ }
85
+ //# sourceMappingURL=chain-profile.js.map
@@ -0,0 +1,11 @@
1
+ /** Document-only chain evaluation. The sole view input is the drawn-target index. */
2
+ import { type Diagnostic } from "./diagnostics.js";
3
+ import type { Relation, SemanticDocument } from "./document.js";
4
+ import type { ProfileRegistry } from "./profile.js";
5
+ import type { EntityRef, OccurrenceRef, PortRef, RelationRef } from "./refs.js";
6
+ import type { TypeResolver } from "./resolver.js";
7
+ import type { RelationOccurrenceEndpoint } from "./view.js";
8
+ type Target = EntityRef | PortRef | RelationRef;
9
+ export declare function createChainValidator(document: SemanticDocument, registry: ProfileRegistry, resolver: TypeResolver, drawnTargets: ReadonlyMap<OccurrenceRef, Target>): (relation: Relation, occurrence: OccurrenceRef, endpoint: RelationOccurrenceEndpoint, path: string, scoped: boolean) => Diagnostic | undefined;
10
+ export {};
11
+ //# sourceMappingURL=chain.d.ts.map
package/dist/chain.js ADDED
@@ -0,0 +1,284 @@
1
+ /** Document-only chain evaluation. The sole view input is the drawn-target index. */
2
+ import { diagnostic } from "./diagnostics.js";
3
+ const compare = (a, b) => a < b ? -1 : a > b ? 1 : 0;
4
+ export function createChainValidator(document, registry, resolver, drawnTargets) {
5
+ const indexes = new Map();
6
+ const entityOf = (target) => {
7
+ if (document.entities[target] !== undefined)
8
+ return target;
9
+ return document.ports[target]?.owner;
10
+ };
11
+ const drawnEntities = new Set([...drawnTargets.values()].map(entityOf).filter((id) => id !== undefined));
12
+ const ancestries = new Map();
13
+ // Once per validateView: type -> source/target adjacency, sorted by relation id.
14
+ for (const relation of Object.values(document.relations).sort((a, b) => compare(a.id, b.id))) {
15
+ let index = indexes.get(relation.profile);
16
+ if (index === undefined) {
17
+ index = { types: new Map(), relations: [] };
18
+ indexes.set(relation.profile, index);
19
+ }
20
+ index.relations.push(relation);
21
+ let adjacency = index.types.get(relation.type);
22
+ if (adjacency === undefined) {
23
+ adjacency = { forward: new Map(), inverse: new Map() };
24
+ index.types.set(relation.type, adjacency);
25
+ }
26
+ const sources = relation.endpoints.filter((e) => e.role === "source").map((e) => entityOf(e.target));
27
+ const targets = relation.endpoints.filter((e) => e.role === "target").map((e) => entityOf(e.target));
28
+ for (const source of sources)
29
+ for (const target of targets) {
30
+ if (source === undefined || target === undefined || document.entities[source]?.profile !== relation.profile ||
31
+ document.entities[target]?.profile !== relation.profile)
32
+ continue;
33
+ const append = (map, from, end) => {
34
+ const edges = map.get(from) ?? [];
35
+ edges.push({ relation: relation.id, end });
36
+ map.set(from, edges);
37
+ };
38
+ append(adjacency.forward, source, target);
39
+ append(adjacency.inverse, target, source);
40
+ }
41
+ }
42
+ const matches = (profile, id, types, constraints = []) => {
43
+ const entity = document.entities[id];
44
+ if (entity?.profile !== profile.id)
45
+ return false;
46
+ let byType = ancestries.get(profile);
47
+ if (byType === undefined) {
48
+ byType = new Map();
49
+ ancestries.set(profile, byType);
50
+ }
51
+ if (!byType.has(entity.type)) {
52
+ const resolution = resolver.resolve(profile, entity.type);
53
+ byType.set(entity.type, resolution.ok ? resolution.resolved.ancestry : undefined);
54
+ }
55
+ const ancestry = byType.get(entity.type);
56
+ if (ancestry === undefined || !types.some((type) => ancestry.includes(type)))
57
+ return false;
58
+ return constraints.every(({ attribute, equals }) => {
59
+ const value = entity.attributes[attribute];
60
+ return typeof equals === "boolean"
61
+ ? value?.kind === "boolean" && value.value === equals
62
+ : (value?.kind === "text" || value?.kind === "enum") && value.value === equals;
63
+ });
64
+ };
65
+ function* candidates(profile, node, step, excluded) {
66
+ for (const type of step.relationTypes) {
67
+ for (const edge of indexes.get(profile.id)?.types.get(type)?.[step.direction].get(node) ?? []) {
68
+ if (edge.relation !== excluded)
69
+ yield edge;
70
+ }
71
+ }
72
+ }
73
+ /** Iterative DFS with branch-local (entity, step) visits and shared path trails. */
74
+ function* walk(profile, start, path, excluded, drawnPrefix = false) {
75
+ if (document.entities[start]?.profile !== profile.id || path.steps.length === 0)
76
+ return;
77
+ const frames = [{ node: start, step: 0, used: false, prefixEnd: false, entered: false }];
78
+ const visiting = new Set();
79
+ const completed = new Map();
80
+ const hops = [];
81
+ const nodes = [{ entity: start, prefixEnd: false }];
82
+ const pop = () => {
83
+ const frame = frames.pop();
84
+ if (frame.key !== undefined) {
85
+ visiting.delete(frame.key);
86
+ // A cycle back into this suffix is internal, not an external
87
+ // ancestor dependency of the completed suffix.
88
+ frame.blockers?.delete(frame.key);
89
+ completed.set(frame.memoKey, frame.blockers ?? new Set());
90
+ }
91
+ const parent = frames[frames.length - 1];
92
+ if (parent !== undefined && frame.blockers !== undefined) {
93
+ parent.blockers ??= new Set();
94
+ for (const key of frame.blockers)
95
+ if (key !== parent.key)
96
+ parent.blockers.add(key);
97
+ }
98
+ if (frame.edge !== undefined) {
99
+ hops.pop();
100
+ nodes.pop();
101
+ }
102
+ };
103
+ function* moves(frame, step) {
104
+ const mayStop = frame.used || step.repeat === "zeroOrMore";
105
+ if (mayStop && frame.step + 1 < path.steps.length) {
106
+ yield { node: frame.node, step: frame.step + 1, used: false, prefixEnd: false };
107
+ }
108
+ if (step.repeat === "one" && frame.used)
109
+ return;
110
+ for (const edge of candidates(profile, frame.node, step, excluded)) {
111
+ yield { node: edge.end, step: frame.step, used: true, edge,
112
+ prefixEnd: step.repeat === "one" && frame.step + 1 < path.steps.length };
113
+ }
114
+ }
115
+ while (frames.length > 0) {
116
+ const frame = frames[frames.length - 1];
117
+ const step = path.steps[frame.step];
118
+ if (!frame.entered) {
119
+ frame.entered = true;
120
+ const key = `${frame.step}:${frame.node}`;
121
+ if (visiting.has(key)) {
122
+ frame.blockers = new Set([key]);
123
+ pop();
124
+ continue;
125
+ }
126
+ const memoKey = `${frame.used}:${key}`;
127
+ const blockers = completed.get(memoKey);
128
+ // All ends of this suffix were already emitted in canonical order.
129
+ // Reuse only if the ancestors that pruned it are still on this branch;
130
+ // otherwise another context may permit a previously blocked route.
131
+ if (blockers !== undefined && [...blockers].every((blocked) => visiting.has(blocked))) {
132
+ frame.blockers = new Set(blockers);
133
+ pop();
134
+ continue;
135
+ }
136
+ frame.memoKey = memoKey;
137
+ visiting.add(key);
138
+ frame.key = key;
139
+ const mayStop = frame.used || step.repeat === "zeroOrMore";
140
+ if ((drawnPrefix && frame.prefixEnd && drawnEntities.has(frame.node)) ||
141
+ (mayStop && frame.step === path.steps.length - 1 && matches(profile, frame.node, path.endTypes, path.endConstraints))) {
142
+ yield { end: frame.node, hops: [...hops], nodes: [...nodes] };
143
+ pop();
144
+ continue;
145
+ }
146
+ frame.moves = moves(frame, step);
147
+ }
148
+ const next = frame.moves.next();
149
+ if (next.done) {
150
+ pop();
151
+ continue;
152
+ }
153
+ if (next.value.edge !== undefined) {
154
+ hops.push(next.value.edge.relation);
155
+ nodes.push({ entity: next.value.node, prefixEnd: next.value.prefixEnd });
156
+ }
157
+ frames.push({ ...next.value, entered: false });
158
+ }
159
+ }
160
+ return (relation, occurrence, endpoint, path, scoped) => {
161
+ const provenance = endpoint.chainProvenance;
162
+ const semantic = endpoint.semanticTarget;
163
+ const foldFailure = (check) => diagnostic({
164
+ code: "occurrence-endpoint-mismatch", path: `${path}.occurrence`,
165
+ message: `projected endpoint for role ${endpoint.role} fails check ${check}`,
166
+ refs: [occurrence, endpoint.occurrence], details: { role: endpoint.role, check },
167
+ });
168
+ const refs = [occurrence, endpoint.occurrence, semantic];
169
+ const fail = (check, details = {}, extra = []) => diagnostic({
170
+ code: "occurrence-endpoint-mismatch", path: `${path}.occurrence`,
171
+ message: `chain endpoint for role ${endpoint.role} fails check ${check} (predicate ${provenance.predicateId})`,
172
+ refs: [...refs, ...extra], details: { role: endpoint.role, check, predicateId: provenance.predicateId, ...details },
173
+ });
174
+ for (const ref of [...provenance.hops, ...(provenance.members ?? [])]) {
175
+ if (document.relations[ref] === undefined)
176
+ return diagnostic({
177
+ code: "dangling-reference", path: `${path}.occurrence`, message: `${ref} is no relation of this document`, refs: [ref],
178
+ });
179
+ }
180
+ if (!relation.endpoints.some((e) => e.role === endpoint.role && e.target === semantic))
181
+ return foldFailure("provenance-mismatch");
182
+ const drawn = drawnTargets.get(endpoint.occurrence);
183
+ if (drawn === undefined)
184
+ return diagnostic({
185
+ code: "dangling-reference", path: `${path}.occurrence`,
186
+ message: scoped ? `${endpoint.occurrence} is no entity, port or relation occurrence of this view`
187
+ : `${endpoint.occurrence} is no entity or port occurrence of this view`, refs: [endpoint.occurrence],
188
+ });
189
+ const profile = registry.get(relation.profile);
190
+ const predicate = profile?.chainPredicates?.find((p) => p.id === provenance.predicateId);
191
+ if (profile === undefined || predicate === undefined)
192
+ return fail("chain-not-declared");
193
+ const start = entityOf(semantic);
194
+ const end = entityOf(drawn);
195
+ if (!predicate.appliesTo.relationTypes.includes(relation.type) || !predicate.appliesTo.roles.includes(endpoint.role) ||
196
+ start === undefined || !matches(profile, start, predicate.appliesTo.startTypes, predicate.startConstraints))
197
+ return fail("chain-hop-mismatch");
198
+ if ((predicate.selection === "aggregate") !== (provenance.members !== undefined))
199
+ return fail("chain-hop-mismatch");
200
+ let expected;
201
+ if (predicate.selection === "aggregate") {
202
+ const aggregation = predicate.aggregation;
203
+ if (aggregation === undefined)
204
+ return fail("chain-hop-mismatch");
205
+ const members = [];
206
+ for (const member of indexes.get(profile.id)?.relations ?? []) {
207
+ if (!aggregation.memberRelationTypes.includes(member.type))
208
+ continue;
209
+ const source = member.endpoints.find((e) => e.role === "source")?.target;
210
+ const target = member.endpoints.find((e) => e.role === "target")?.target;
211
+ const s = source === undefined ? undefined : entityOf(source);
212
+ const t = target === undefined ? undefined : entityOf(target);
213
+ if (s === undefined || t === undefined || walk(profile, t, aggregation.memberTargetChain, relation.id).next().done)
214
+ continue;
215
+ for (const route of walk(profile, s, aggregation.memberSourceChain, relation.id)) {
216
+ if (route.end === end) {
217
+ members.push({ relation: member, source: s, target: t, route });
218
+ break;
219
+ }
220
+ }
221
+ }
222
+ members.sort((a, b) => compare(a.source, b.source) || compare(a.target, b.target) || compare(a.relation.id, b.relation.id));
223
+ const declared = provenance.members;
224
+ const firstDifference = members.findIndex((m, i) => m.relation.id !== declared[i]);
225
+ if (members.length === 0 || members.length !== declared.length || firstDifference !== -1 || members[0].relation.id !== relation.id) {
226
+ const differing = firstDifference === -1 ? declared[members.length] : declared[firstDifference] ?? members[firstDifference]?.relation.id;
227
+ const carrier = members[0]?.relation.id;
228
+ return fail("chain-aggregation-mismatch", { expectedCount: members.length, declaredCount: declared.length }, carrier !== relation.id && carrier !== undefined ? [carrier] : differing === undefined ? [] : [differing]);
229
+ }
230
+ expected = members[0].route;
231
+ }
232
+ else if (predicate.selection === "first-drawn") {
233
+ search: for (const alternative of predicate.alternatives) {
234
+ for (const route of walk(profile, start, alternative, relation.id, true)) {
235
+ const index = route.nodes.findIndex((node) => drawnEntities.has(node.entity));
236
+ if (index === -1)
237
+ return fail("chain-not-proven");
238
+ const node = route.nodes[index];
239
+ // A completed one-step prefix is an admitted lift (e.g. the exposer).
240
+ // Nodes inside a repeating step must satisfy that path's end test.
241
+ if (!node.prefixEnd && index !== route.nodes.length - 1)
242
+ return fail("chain-not-proven", { blockingDrawn: node.entity });
243
+ if (node.entity !== end)
244
+ return fail("chain-not-proven", { earlierDrawn: node.entity });
245
+ expected = { ...route, end: node.entity, hops: route.hops.slice(0, index) };
246
+ break search;
247
+ }
248
+ }
249
+ }
250
+ else {
251
+ const ends = new Map();
252
+ for (const alternative of predicate.alternatives) {
253
+ for (const route of walk(profile, start, alternative, relation.id)) {
254
+ if (predicate.selection === "ordered" && !drawnEntities.has(route.end))
255
+ continue;
256
+ if (!ends.has(route.end))
257
+ ends.set(route.end, route);
258
+ }
259
+ if (predicate.selection === "ordered" && ends.size > 0)
260
+ break;
261
+ }
262
+ if (ends.size > 1) {
263
+ return predicate.selection === "unique" ? fail("chain-not-proven", { cause: "cardinality" })
264
+ : fail("chain-ambiguous", { candidateCount: ends.size }, [...ends.keys()].sort(compare));
265
+ }
266
+ expected = ends.values().next().value;
267
+ }
268
+ if (expected === undefined)
269
+ return fail("chain-not-proven");
270
+ if (expected.end !== end)
271
+ return fail("chain-not-proven", { expectedEnd: expected.end });
272
+ if (provenance.hops.length === 0)
273
+ return fail("chain-not-proven");
274
+ const length = Math.max(provenance.hops.length, expected.hops.length);
275
+ for (let i = 0; i < length; i++) {
276
+ if (provenance.hops[i] !== expected.hops[i]) {
277
+ const hop = provenance.hops[i] ?? expected.hops[i];
278
+ return fail("chain-hop-mismatch", { hopIndex: i, hop }, [hop]);
279
+ }
280
+ }
281
+ return undefined;
282
+ };
283
+ }
284
+ //# sourceMappingURL=chain.js.map
package/dist/commands.js CHANGED
@@ -181,9 +181,11 @@ function stripProvenance(view) {
181
181
  continue;
182
182
  const stripped = {
183
183
  ...occurrence,
184
- endpoints: occurrence.endpoints.map((endpoint) => endpoint.sourceOccurrence === undefined
185
- ? { role: endpoint.role, occurrence: endpoint.occurrence }
186
- : { role: endpoint.role, occurrence: endpoint.sourceOccurrence }),
184
+ endpoints: occurrence.endpoints.map((endpoint) => endpoint.chainProvenance !== undefined
185
+ ? endpoint
186
+ : endpoint.sourceOccurrence === undefined
187
+ ? { role: endpoint.role, occurrence: endpoint.occurrence }
188
+ : { role: endpoint.role, occurrence: endpoint.sourceOccurrence }),
187
189
  };
188
190
  relationOccurrences = withKey(relationOccurrences, key, stripped);
189
191
  changed = true;