@sentropic/diagram-core 0.2.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.
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
 
@@ -131,10 +131,8 @@ changing the presentation pin. The package includes
131
131
  [`schemas/diagram-view-schema-3.json`](schemas/diagram-view-schema-3.json) and its
132
132
  [canonical SHA-256](schemas/diagram-view-schema-3.sha256):
133
133
  `b415c05197692baa5f74ab35e3150ce58079cf9f06201df5e581d222a8d2c0df`.
134
- This branch includes the successor `@3` schema lot but defers the specification's
135
- `0.2.0` release lot: the current package version and downstream dependency pins
136
- remain `0.1.0`. The release conductor owns that version/pin/lockfile update and
137
- the owner-confirmed tag; schema inclusion does not certify downstream adoption.
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.
138
136
 
139
137
  ### Commands are transactions
140
138
 
@@ -188,6 +186,98 @@ so a migrated document may still be unwritable — for instance when a value tha
188
186
  failed to convert was a **required** attribute. The report names the element; the
189
187
  decision is the host's.
190
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
+
191
281
  ## What this package does not import
192
282
 
193
283
  Nothing. Not one specifier that is not a relative module of its own source, which
@@ -221,6 +311,10 @@ a test asserts by scanning every file. In particular:
221
311
  - **Codecs, source text, AST/CST and conversion reports**: GD-M4. Nothing here
222
312
  parses, fetches or executes imported content, a URI or markup.
223
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.
224
318
  - **A reference disposition in the delete policy.** The policy governs
225
319
  occurrences, relations and ports. An entity a typed reference attribute still
226
320
  points at cannot be deleted: the transaction refuses itself on the final state
@@ -253,6 +347,8 @@ src/hash.ts fnv1a64, dependency-free, non-cryptographic
253
347
  src/validate.ts every refusal, including the nine named rejected cases
254
348
  src/commands.ts 18 commands, transactions, effects, inverses
255
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)
256
352
  fixtures/ valid documents, a divergent-revision state, a command
257
353
  sequence, the nine rejected cases, a 1.0 stored document
258
354
  tests/ 10 suites; `refs-nominal.test.ts` is a COMPILER test
@@ -29,7 +29,23 @@ export type DiagnosticCode = "erd-missing-pk" | "erd-multiple-pk" | "erd-danglin
29
29
  /** An extension at validation level `unsupported`: preserved on import, never promoted. */
30
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;
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
  */
@@ -32,4 +32,6 @@ export * from "./migrate.js";
32
32
  export { relationBaseType, relationSchema } from "./relation-types.js";
33
33
  export { withFlowTypes, validateFlows, flowIndex, type FlowStep, type FlowScenario, type FlowIndex } from "./flows.js";
34
34
  export * from "./erd.js";
35
+ export * from "./layout-hints.js";
36
+ export * from "./notation.js";
35
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
  */
@@ -32,4 +32,6 @@ export * from "./migrate.js";
32
32
  export { relationBaseType, relationSchema } from "./relation-types.js";
33
33
  export { withFlowTypes, validateFlows, flowIndex } from "./flows.js";
34
34
  export * from "./erd.js";
35
+ export * from "./layout-hints.js";
36
+ export * from "./notation.js";
35
37
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,158 @@
1
+ /**
2
+ * `ds-layout-hints@1` — the closed layout-hint vocabulary of the Design System.
3
+ *
4
+ * A view declaration (engram `MetamodelViewDecl.layout`) names a layout by this
5
+ * vocabulary and never by a table of its own. The vocabulary is authored,
6
+ * versioned and pinned here, and nowhere else.
7
+ *
8
+ * Scope rule of `@1`: it admits only what the layout engine of
9
+ * `@sentropic/diagram-canvas` executes at this version.
10
+ * - `auto-pack` = `layoutMeasured` (measured, row-packed views);
11
+ * - `layered-flow` = `layoutDocument` (ranked flow), on `generic@1` views
12
+ * without a typed presentation only.
13
+ * A mode or a hint that is specified but not executed yet (`lane-stack`,
14
+ * `matrix-grid`, `tree`, `direction`, `rotate_labels`) is REFUSED with its own
15
+ * code, never coerced to another mode: a template that validates against `@1`
16
+ * must render. Spacing overrides and coordinates are forbidden outright.
17
+ *
18
+ * Three layers, one source:
19
+ * - `DS_LAYOUT_HINTS_SCHEMA` JSON Schema 2020-12, closed. Its `$defs` also
20
+ * carry the refusal classification, so the pinned bytes cover it.
21
+ * - `DS_LAYOUT_HINTS_RULES` frozen data read from the schema `$defs`.
22
+ * - `validateLayoutHints()` pure; structural and semantic; diagnostics.
23
+ *
24
+ * Any change to the schema is `ds-layout-hints@2`: the pin digest is the
25
+ * SHA-256 of the RFC 8785 bytes of the schema.
26
+ */
27
+ import { type Diagnostic, type DiagnosticCode } from "./diagnostics.js";
28
+ import type { PresentationPin } from "./presentation.js";
29
+ import type { EntityRef } from "./refs.js";
30
+ export declare const DS_LAYOUT_VOCABULARY: "ds-layout-hints@1";
31
+ export declare const DS_LAYOUT_HINTS_SCHEMA_ID: "https://sentropic.dev/schemas/diagram/layout-hints/v1";
32
+ /** Modes the layout engine executes at this version. */
33
+ export declare const DS_LAYOUT_MODES: readonly ["auto-pack", "layered-flow"];
34
+ /** Modes specified for a later vocabulary: refused in `@1`. */
35
+ export declare const DS_LAYOUT_FUTURE_MODES: readonly ["lane-stack", "matrix-grid", "tree"];
36
+ /** Hints specified for a later vocabulary: refused in `@1`. */
37
+ export declare const DS_LAYOUT_FUTURE_HINTS: readonly ["direction", "rotate_labels"];
38
+ /** Spacing overrides and coordinates: refused in every version (one gap law, no authored geometry). */
39
+ export declare const DS_LAYOUT_FORBIDDEN_HINTS: readonly ["cardGapX", "cardGapY", "density", "edge_label_orientation", "gapAfter", "height", "rankGap", "width", "x", "y", "zoneGapX", "zoneGapY"];
40
+ /** Hints read by the measured path only: refused under `layered-flow`. */
41
+ export declare const DS_LAYOUT_MEASURED_HINTS: readonly ["grouping", "grouping_axis", "ordering", "rootOrder", "stretch"];
42
+ export declare const DS_LAYOUT_AXES: readonly ["rows", "columns"];
43
+ export type DsLayoutMode = (typeof DS_LAYOUT_MODES)[number];
44
+ export type DsLayoutFutureMode = (typeof DS_LAYOUT_FUTURE_MODES)[number];
45
+ export type DsLayoutAxis = (typeof DS_LAYOUT_AXES)[number];
46
+ /** A recursive authored group: references and subgroups interleave in `items`. */
47
+ export interface DsLayoutGroup {
48
+ readonly id: string;
49
+ readonly direction: DsLayoutAxis;
50
+ readonly items: readonly (EntityRef | DsLayoutGroup)[];
51
+ readonly stretch?: boolean;
52
+ }
53
+ /** A valid `ds-layout-hints@1` payload. */
54
+ export interface DsLayoutHints {
55
+ readonly vocabulary: typeof DS_LAYOUT_VOCABULARY;
56
+ readonly mode: DsLayoutMode;
57
+ /** Sibling order per semantic parent. */
58
+ readonly ordering?: Readonly<Record<EntityRef, readonly EntityRef[]>>;
59
+ /** Declaration order of the root level. */
60
+ readonly rootOrder?: readonly EntityRef[];
61
+ /** Authored groups. Exclusive with `grouping_axis`. */
62
+ readonly grouping?: readonly DsLayoutGroup[];
63
+ /** Shorthand: one group over the root level, packed along this axis. Exclusive with `grouping`. */
64
+ readonly grouping_axis?: DsLayoutAxis;
65
+ readonly stretch?: boolean;
66
+ }
67
+ /**
68
+ * What the validator must know about the view to judge a mode. Absent facts
69
+ * never widen a scope: `layered-flow` without a context is refused.
70
+ */
71
+ export interface LayoutHintsContext {
72
+ /** Profile references of the view's document (`generic@1`, `archimate@2`, …). */
73
+ readonly profiles?: readonly string[];
74
+ /** True when the view carries a typed presentation (`presentation.diagram`). */
75
+ readonly diagramPresentation?: boolean;
76
+ /** The presentation vocabulary of the declaring profile, when it has one (`diagram-notation@1`). */
77
+ readonly presentationVocabulary?: string;
78
+ }
79
+ declare const LAYERED_FLOW_PROFILE = "generic@1";
80
+ /** The canonical JSON Schema of `ds-layout-hints@1`, deeply frozen. Also shipped as `schemas/ds-layout-hints-1.json`. */
81
+ export declare const DS_LAYOUT_HINTS_SCHEMA: Readonly<Record<string, unknown>>;
82
+ /** SHA-256 (64 lowercase hex) of the RFC 8785 bytes of the schema. */
83
+ export declare const DS_LAYOUT_HINTS_SCHEMA_DIGEST: string;
84
+ /** The pin a view declaration references. Equality is equality of the three fields. */
85
+ export declare const DS_LAYOUT_VOCABULARY_PIN: PresentationPin;
86
+ export type LayoutHintsDiagnosticCode = Extract<DiagnosticCode, `layout-${string}`>;
87
+ export interface DsLayoutHintsRules {
88
+ readonly vocabulary: typeof DS_LAYOUT_VOCABULARY;
89
+ /** Admitted modes, and the code raised for everything else. */
90
+ readonly modes: {
91
+ readonly implemented: readonly DsLayoutMode[];
92
+ /** Refused with `layout-mode-not-implemented`. */
93
+ readonly future: readonly DsLayoutFutureMode[];
94
+ /** The vocabulary a future mode waits for. */
95
+ readonly futureVocabulary: "ds-layout-hints@2";
96
+ };
97
+ /** `layered-flow` is admitted only on a view matching every fact below. */
98
+ readonly layeredFlowScope: {
99
+ readonly profiles: readonly [typeof LAYERED_FLOW_PROFILE];
100
+ readonly diagramPresentation: false;
101
+ readonly presentationVocabulary: "absent";
102
+ };
103
+ readonly hints: {
104
+ /** Read by the measured path; refused under `layered-flow` with `layout-hint-out-of-scope`. */
105
+ readonly measuredOnly: readonly string[];
106
+ /** Refused with `layout-hint-not-implemented`. */
107
+ readonly future: readonly string[];
108
+ /** Refused with `layout-hint-forbidden`. */
109
+ readonly forbidden: readonly string[];
110
+ /** Pairs that cannot be authored together (`layout-hint-conflict`). */
111
+ readonly exclusive: readonly (readonly [string, string])[];
112
+ };
113
+ /** Identity rules checked on a structurally valid payload (`layout-hint-conflict`). */
114
+ readonly identity: readonly ["group-id-unique", "group-leaf-once", "ordering-member-single-parent", "ordering-parent-not-member"];
115
+ }
116
+ /** The semantic rules of `ds-layout-hints@1`, as data. Every list equals the matching schema `$defs` enum. */
117
+ export declare const DS_LAYOUT_HINTS_RULES: DsLayoutHintsRules;
118
+ /**
119
+ * Validate a layout-hint payload against `ds-layout-hints@1`: structure and
120
+ * semantics, in one pass. Pure; never throws; an empty result means valid.
121
+ * Diagnostics are sorted by (path, code).
122
+ *
123
+ * What it cannot see: whether a reference exists in the document and whether
124
+ * the members of a group are siblings. Those need the document and stay with
125
+ * the layout engine (`validateHints` in `@sentropic/diagram-canvas`).
126
+ */
127
+ export declare function validateLayoutHints(value: unknown, context?: LayoutHintsContext): readonly Diagnostic[];
128
+ /** Type guard: true iff `validateLayoutHints` raises nothing. */
129
+ export declare function isLayoutHints(value: unknown, context?: LayoutHintsContext): value is DsLayoutHints;
130
+ /** The engine-side group shape (`LayoutGroup` of `@sentropic/diagram-canvas`), stated structurally. */
131
+ export interface LoweredLayoutGroup {
132
+ readonly id: string;
133
+ readonly direction: DsLayoutAxis;
134
+ readonly items: readonly (EntityRef | LoweredLayoutGroup)[];
135
+ readonly stretch?: boolean;
136
+ }
137
+ /** The engine-side hints (`LayoutHints` of `@sentropic/diagram-canvas`), stated structurally: no gap, no coordinate. */
138
+ export interface LoweredLayoutHints {
139
+ readonly ordering?: Readonly<Record<EntityRef, readonly EntityRef[]>>;
140
+ readonly rootOrder?: readonly EntityRef[];
141
+ readonly grouping?: readonly LoweredLayoutGroup[];
142
+ readonly stretch?: boolean;
143
+ }
144
+ /** The id of the root group `grouping_axis` lowers to. */
145
+ export declare const DS_LAYOUT_ROOT_GROUP_ID: "ds-layout-hints.root";
146
+ /**
147
+ * Lower a VALID payload to the hints the layout engine takes. `mode` selects
148
+ * the engine entry and is not part of the result; `layered-flow` lowers to no
149
+ * hint at all.
150
+ *
151
+ * `grouping_axis` is a shorthand for one group over the root level: it needs
152
+ * the visible root entities, which only the caller knows. Listed roots come
153
+ * first in `rootOrder`, the others after in UTF-16 order (the engine's own
154
+ * rule). Without roots the shorthand lowers to nothing.
155
+ */
156
+ export declare function lowerLayoutHints(hints: DsLayoutHints, roots?: readonly EntityRef[]): LoweredLayoutHints;
157
+ export {};
158
+ //# sourceMappingURL=layout-hints.d.ts.map
@@ -0,0 +1,459 @@
1
+ /**
2
+ * `ds-layout-hints@1` — the closed layout-hint vocabulary of the Design System.
3
+ *
4
+ * A view declaration (engram `MetamodelViewDecl.layout`) names a layout by this
5
+ * vocabulary and never by a table of its own. The vocabulary is authored,
6
+ * versioned and pinned here, and nowhere else.
7
+ *
8
+ * Scope rule of `@1`: it admits only what the layout engine of
9
+ * `@sentropic/diagram-canvas` executes at this version.
10
+ * - `auto-pack` = `layoutMeasured` (measured, row-packed views);
11
+ * - `layered-flow` = `layoutDocument` (ranked flow), on `generic@1` views
12
+ * without a typed presentation only.
13
+ * A mode or a hint that is specified but not executed yet (`lane-stack`,
14
+ * `matrix-grid`, `tree`, `direction`, `rotate_labels`) is REFUSED with its own
15
+ * code, never coerced to another mode: a template that validates against `@1`
16
+ * must render. Spacing overrides and coordinates are forbidden outright.
17
+ *
18
+ * Three layers, one source:
19
+ * - `DS_LAYOUT_HINTS_SCHEMA` JSON Schema 2020-12, closed. Its `$defs` also
20
+ * carry the refusal classification, so the pinned bytes cover it.
21
+ * - `DS_LAYOUT_HINTS_RULES` frozen data read from the schema `$defs`.
22
+ * - `validateLayoutHints()` pure; structural and semantic; diagnostics.
23
+ *
24
+ * Any change to the schema is `ds-layout-hints@2`: the pin digest is the
25
+ * SHA-256 of the RFC 8785 bytes of the schema.
26
+ */
27
+ import { diagnostic } from "./diagnostics.js";
28
+ import { canonicalBytes, sha256Hex } from "./sha256.js";
29
+ export const DS_LAYOUT_VOCABULARY = "ds-layout-hints@1";
30
+ export const DS_LAYOUT_HINTS_SCHEMA_ID = "https://sentropic.dev/schemas/diagram/layout-hints/v1";
31
+ /** Modes the layout engine executes at this version. */
32
+ export const DS_LAYOUT_MODES = ["auto-pack", "layered-flow"];
33
+ /** Modes specified for a later vocabulary: refused in `@1`. */
34
+ export const DS_LAYOUT_FUTURE_MODES = ["lane-stack", "matrix-grid", "tree"];
35
+ /** Hints specified for a later vocabulary: refused in `@1`. */
36
+ export const DS_LAYOUT_FUTURE_HINTS = ["direction", "rotate_labels"];
37
+ /** Spacing overrides and coordinates: refused in every version (one gap law, no authored geometry). */
38
+ export const DS_LAYOUT_FORBIDDEN_HINTS = [
39
+ "cardGapX",
40
+ "cardGapY",
41
+ "density",
42
+ "edge_label_orientation",
43
+ "gapAfter",
44
+ "height",
45
+ "rankGap",
46
+ "width",
47
+ "x",
48
+ "y",
49
+ "zoneGapX",
50
+ "zoneGapY",
51
+ ];
52
+ /** Hints read by the measured path only: refused under `layered-flow`. */
53
+ export const DS_LAYOUT_MEASURED_HINTS = ["grouping", "grouping_axis", "ordering", "rootOrder", "stretch"];
54
+ export const DS_LAYOUT_AXES = ["rows", "columns"];
55
+ const ENTITY_REF_PATTERN = "^entity:[A-Za-z0-9][A-Za-z0-9._-]*$";
56
+ const ENTITY_REF = new RegExp(ENTITY_REF_PATTERN);
57
+ const GROUP_ID_MAX = 80;
58
+ const LAYERED_FLOW_PROFILE = "generic@1";
59
+ const PRIVATE_SCHEMA = {
60
+ $schema: "https://json-schema.org/draft/2020-12/schema",
61
+ $id: DS_LAYOUT_HINTS_SCHEMA_ID,
62
+ title: "ds-layout-hints@1",
63
+ type: "object",
64
+ properties: {
65
+ vocabulary: { const: DS_LAYOUT_VOCABULARY },
66
+ mode: { $ref: "#/$defs/mode" },
67
+ ordering: {
68
+ type: "object",
69
+ propertyNames: { $ref: "#/$defs/entityRef" },
70
+ additionalProperties: { $ref: "#/$defs/entityRefList" },
71
+ },
72
+ rootOrder: { $ref: "#/$defs/entityRefList" },
73
+ grouping: { type: "array", items: { $ref: "#/$defs/group" } },
74
+ grouping_axis: { $ref: "#/$defs/axis" },
75
+ stretch: { type: "boolean" },
76
+ },
77
+ required: ["vocabulary", "mode"],
78
+ additionalProperties: false,
79
+ dependentSchemas: { grouping: { properties: { grouping_axis: false } } },
80
+ if: { properties: { mode: { const: "layered-flow" } }, required: ["mode"] },
81
+ then: {
82
+ properties: { grouping: false, grouping_axis: false, ordering: false, rootOrder: false, stretch: false },
83
+ },
84
+ $defs: {
85
+ mode: { enum: [...DS_LAYOUT_MODES] },
86
+ futureMode: { enum: [...DS_LAYOUT_FUTURE_MODES] },
87
+ futureHint: { enum: [...DS_LAYOUT_FUTURE_HINTS] },
88
+ forbiddenHint: { enum: [...DS_LAYOUT_FORBIDDEN_HINTS] },
89
+ measuredHint: { enum: [...DS_LAYOUT_MEASURED_HINTS] },
90
+ layeredFlowScope: {
91
+ type: "object",
92
+ properties: {
93
+ profiles: { type: "array", minItems: 1, items: { const: LAYERED_FLOW_PROFILE } },
94
+ diagramPresentation: { const: false },
95
+ presentationVocabulary: false,
96
+ },
97
+ required: ["profiles", "diagramPresentation"],
98
+ },
99
+ axis: { enum: [...DS_LAYOUT_AXES] },
100
+ entityRef: { type: "string", pattern: ENTITY_REF_PATTERN },
101
+ entityRefList: { type: "array", items: { $ref: "#/$defs/entityRef" }, uniqueItems: true },
102
+ group: {
103
+ type: "object",
104
+ properties: {
105
+ id: { type: "string", minLength: 1, maxLength: GROUP_ID_MAX },
106
+ direction: { $ref: "#/$defs/axis" },
107
+ items: {
108
+ type: "array",
109
+ minItems: 1,
110
+ items: { anyOf: [{ $ref: "#/$defs/entityRef" }, { $ref: "#/$defs/group" }] },
111
+ },
112
+ stretch: { type: "boolean" },
113
+ },
114
+ required: ["id", "direction", "items"],
115
+ additionalProperties: false,
116
+ },
117
+ },
118
+ };
119
+ function deepClone(value) {
120
+ if (value === null || typeof value !== "object")
121
+ return value;
122
+ if (Array.isArray(value))
123
+ return value.map((item) => deepClone(item));
124
+ const out = {};
125
+ for (const key of Object.keys(value)) {
126
+ out[key] = deepClone(value[key]);
127
+ }
128
+ return out;
129
+ }
130
+ function deepFreeze(value) {
131
+ if (value === null || typeof value !== "object" || Object.isFrozen(value))
132
+ return value;
133
+ for (const child of Object.values(value))
134
+ deepFreeze(child);
135
+ return Object.freeze(value);
136
+ }
137
+ deepFreeze(PRIVATE_SCHEMA);
138
+ /** The canonical JSON Schema of `ds-layout-hints@1`, deeply frozen. Also shipped as `schemas/ds-layout-hints-1.json`. */
139
+ export const DS_LAYOUT_HINTS_SCHEMA = deepFreeze(deepClone(PRIVATE_SCHEMA));
140
+ /** SHA-256 (64 lowercase hex) of the RFC 8785 bytes of the schema. */
141
+ export const DS_LAYOUT_HINTS_SCHEMA_DIGEST = sha256Hex(canonicalBytes(PRIVATE_SCHEMA));
142
+ /** The pin a view declaration references. Equality is equality of the three fields. */
143
+ export const DS_LAYOUT_VOCABULARY_PIN = deepFreeze({
144
+ id: DS_LAYOUT_HINTS_SCHEMA_ID,
145
+ version: DS_LAYOUT_VOCABULARY,
146
+ contentDigest: DS_LAYOUT_HINTS_SCHEMA_DIGEST,
147
+ });
148
+ /** The semantic rules of `ds-layout-hints@1`, as data. Every list equals the matching schema `$defs` enum. */
149
+ export const DS_LAYOUT_HINTS_RULES = deepFreeze({
150
+ vocabulary: DS_LAYOUT_VOCABULARY,
151
+ modes: {
152
+ implemented: [...DS_LAYOUT_MODES],
153
+ future: [...DS_LAYOUT_FUTURE_MODES],
154
+ futureVocabulary: "ds-layout-hints@2",
155
+ },
156
+ layeredFlowScope: {
157
+ profiles: [LAYERED_FLOW_PROFILE],
158
+ diagramPresentation: false,
159
+ presentationVocabulary: "absent",
160
+ },
161
+ hints: {
162
+ measuredOnly: [...DS_LAYOUT_MEASURED_HINTS],
163
+ future: [...DS_LAYOUT_FUTURE_HINTS],
164
+ forbidden: [...DS_LAYOUT_FORBIDDEN_HINTS],
165
+ exclusive: [["grouping", "grouping_axis"]],
166
+ },
167
+ identity: ["group-id-unique", "group-leaf-once", "ordering-member-single-parent", "ordering-parent-not-member"],
168
+ });
169
+ const ROOT_KEYS = ["vocabulary", "mode", "ordering", "rootOrder", "grouping", "grouping_axis", "stretch"];
170
+ const GROUP_KEYS = ["id", "direction", "items", "stretch"];
171
+ function isRecord(value) {
172
+ if (value === null || typeof value !== "object" || Array.isArray(value))
173
+ return false;
174
+ const proto = Object.getPrototypeOf(value);
175
+ return proto === Object.prototype || proto === null;
176
+ }
177
+ function includes(list, value) {
178
+ return typeof value === "string" && list.includes(value);
179
+ }
180
+ function describe(value) {
181
+ if (value === null)
182
+ return "null";
183
+ if (Array.isArray(value))
184
+ return "array";
185
+ return typeof value;
186
+ }
187
+ /** One property name outside the admitted set, classified. */
188
+ function refuseKey(key, path, push) {
189
+ if (includes(DS_LAYOUT_FORBIDDEN_HINTS, key)) {
190
+ push("layout-hint-forbidden", path, `${key} is a spacing or coordinate override: ${DS_LAYOUT_VOCABULARY} admits none`, {
191
+ details: { hint: key },
192
+ });
193
+ }
194
+ else if (includes(DS_LAYOUT_FUTURE_HINTS, key)) {
195
+ push("layout-hint-not-implemented", path, `${key} is not executed by the layout engine at ${DS_LAYOUT_VOCABULARY}`, {
196
+ details: { hint: key, vocabulary: DS_LAYOUT_HINTS_RULES.modes.futureVocabulary },
197
+ });
198
+ }
199
+ else {
200
+ push("layout-hint-unknown", path, `${key} is not a property of ${DS_LAYOUT_VOCABULARY}`, { details: { hint: key } });
201
+ }
202
+ }
203
+ function checkEntityRef(value, path, push) {
204
+ if (typeof value === "string" && ENTITY_REF.test(value))
205
+ return true;
206
+ push("layout-hints-invalid", path, `expected an entity reference, got ${typeof value === "string" ? JSON.stringify(value) : describe(value)}`);
207
+ return false;
208
+ }
209
+ function checkEntityRefList(value, path, push) {
210
+ if (!Array.isArray(value)) {
211
+ push("layout-hints-invalid", path, `expected an array of entity references, got ${describe(value)}`);
212
+ return [];
213
+ }
214
+ const out = [];
215
+ const seen = new Set();
216
+ value.forEach((member, index) => {
217
+ if (!checkEntityRef(member, `${path}.${index}`, push))
218
+ return;
219
+ if (seen.has(member)) {
220
+ push("layout-hint-conflict", `${path}.${index}`, `${member} is listed twice`, { refs: [member] });
221
+ return;
222
+ }
223
+ seen.add(member);
224
+ out.push(member);
225
+ });
226
+ return out;
227
+ }
228
+ function checkAxis(value, path, push) {
229
+ if (includes(DS_LAYOUT_AXES, value))
230
+ return true;
231
+ push("layout-hints-invalid", path, `expected "rows" or "columns", got ${typeof value === "string" ? JSON.stringify(value) : describe(value)}`);
232
+ return false;
233
+ }
234
+ function checkGroup(value, path, ledger, ancestors, push) {
235
+ if (!isRecord(value)) {
236
+ push("layout-hints-invalid", path, `expected a group object, got ${describe(value)}`);
237
+ return;
238
+ }
239
+ if (ancestors.has(value)) {
240
+ push("layout-hints-invalid", path, "a group cannot contain itself");
241
+ return;
242
+ }
243
+ for (const key of Object.keys(value)) {
244
+ if (!GROUP_KEYS.includes(key))
245
+ refuseKey(key, `${path}.${key}`, push);
246
+ }
247
+ const id = value["id"];
248
+ if (typeof id !== "string" || id.length < 1 || id.length > GROUP_ID_MAX) {
249
+ push("layout-hints-invalid", `${path}.id`, `a group id is a string of 1 to ${GROUP_ID_MAX} characters`);
250
+ }
251
+ else {
252
+ const first = ledger.ids.get(id);
253
+ if (first !== undefined) {
254
+ push("layout-hint-conflict", `${path}.id`, `group id ${JSON.stringify(id)} is already used at ${first}`, { details: { group: id } });
255
+ }
256
+ else {
257
+ ledger.ids.set(id, path);
258
+ }
259
+ }
260
+ checkAxis(value["direction"], `${path}.direction`, push);
261
+ if ("stretch" in value && typeof value["stretch"] !== "boolean") {
262
+ push("layout-hints-invalid", `${path}.stretch`, `expected a boolean, got ${describe(value["stretch"])}`);
263
+ }
264
+ const items = value["items"];
265
+ if (!Array.isArray(items) || items.length === 0) {
266
+ push("layout-hints-invalid", `${path}.items`, "a group lists at least one item");
267
+ return;
268
+ }
269
+ const nested = new Set(ancestors).add(value);
270
+ items.forEach((item, index) => {
271
+ const itemPath = `${path}.items.${index}`;
272
+ if (typeof item === "string") {
273
+ if (!checkEntityRef(item, itemPath, push))
274
+ return;
275
+ const owner = ledger.leaves.get(item);
276
+ if (owner !== undefined) {
277
+ push("layout-hint-conflict", itemPath, `${item} is already placed by ${owner}`, { refs: [item] });
278
+ }
279
+ else {
280
+ ledger.leaves.set(item, itemPath);
281
+ }
282
+ return;
283
+ }
284
+ checkGroup(item, itemPath, ledger, nested, push);
285
+ });
286
+ }
287
+ function checkLayeredFlowScope(context, push) {
288
+ const refuse = (message, details) => {
289
+ push("layout-mode-out-of-scope", "mode", `layered-flow is admitted on ${LAYERED_FLOW_PROFILE} views without a typed presentation only: ${message}`, {
290
+ details: { mode: "layered-flow", ...details },
291
+ });
292
+ };
293
+ const profiles = context?.profiles;
294
+ if (profiles === undefined || profiles.length === 0) {
295
+ refuse("the view's profiles are not stated", { reason: "profiles-unstated" });
296
+ return;
297
+ }
298
+ const foreign = profiles.filter((profile) => profile !== LAYERED_FLOW_PROFILE);
299
+ if (foreign.length > 0) {
300
+ refuse(`the view uses ${foreign.join(", ")}`, { reason: "profile", profile: foreign[0] });
301
+ }
302
+ if (context?.diagramPresentation !== false) {
303
+ refuse(context?.diagramPresentation === true ? "the view carries a typed presentation" : "the absence of a typed presentation is not stated", { reason: context?.diagramPresentation === true ? "diagram-presentation" : "diagram-presentation-unstated" });
304
+ }
305
+ if (context?.presentationVocabulary !== undefined) {
306
+ refuse(`the profile declares ${context.presentationVocabulary}`, {
307
+ reason: "presentation-vocabulary",
308
+ presentationVocabulary: context.presentationVocabulary,
309
+ });
310
+ }
311
+ }
312
+ /**
313
+ * Validate a layout-hint payload against `ds-layout-hints@1`: structure and
314
+ * semantics, in one pass. Pure; never throws; an empty result means valid.
315
+ * Diagnostics are sorted by (path, code).
316
+ *
317
+ * What it cannot see: whether a reference exists in the document and whether
318
+ * the members of a group are siblings. Those need the document and stay with
319
+ * the layout engine (`validateHints` in `@sentropic/diagram-canvas`).
320
+ */
321
+ export function validateLayoutHints(value, context) {
322
+ const found = [];
323
+ const push = (code, path, message, extra) => {
324
+ found.push(diagnostic({ code, path: path === "" ? "layout" : `layout.${path}`, message, ...extra }));
325
+ };
326
+ const done = () => found.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : a.code < b.code ? -1 : a.code > b.code ? 1 : 0));
327
+ if (!isRecord(value)) {
328
+ push("layout-hints-invalid", "", `expected a layout-hint object, got ${describe(value)}`);
329
+ return done();
330
+ }
331
+ const vocabulary = value["vocabulary"];
332
+ if (vocabulary !== DS_LAYOUT_VOCABULARY) {
333
+ // Fail closed: nothing else is read from a payload of another vocabulary.
334
+ push("layout-vocabulary-unknown", "vocabulary", vocabulary === undefined
335
+ ? `vocabulary is required and must be ${JSON.stringify(DS_LAYOUT_VOCABULARY)}`
336
+ : `vocabulary ${typeof vocabulary === "string" ? JSON.stringify(vocabulary) : describe(vocabulary)} is not ${JSON.stringify(DS_LAYOUT_VOCABULARY)}`, typeof vocabulary === "string" ? { details: { vocabulary } } : undefined);
337
+ return done();
338
+ }
339
+ for (const key of Object.keys(value)) {
340
+ if (!ROOT_KEYS.includes(key))
341
+ refuseKey(key, key, push);
342
+ }
343
+ const mode = value["mode"];
344
+ let admitted;
345
+ if (mode === undefined) {
346
+ push("layout-hints-invalid", "mode", "mode is required: an absent mode is never read as auto-pack");
347
+ }
348
+ else if (includes(DS_LAYOUT_MODES, mode)) {
349
+ admitted = mode;
350
+ }
351
+ else if (includes(DS_LAYOUT_FUTURE_MODES, mode)) {
352
+ push("layout-mode-not-implemented", "mode", `${String(mode)} is not executed by the layout engine at ${DS_LAYOUT_VOCABULARY}`, {
353
+ details: { mode: mode, vocabulary: DS_LAYOUT_HINTS_RULES.modes.futureVocabulary },
354
+ });
355
+ }
356
+ else {
357
+ push("layout-mode-unknown", "mode", `mode ${typeof mode === "string" ? JSON.stringify(mode) : describe(mode)} is not a mode of ${DS_LAYOUT_VOCABULARY}`, typeof mode === "string" ? { details: { mode } } : undefined);
358
+ }
359
+ if (admitted === "layered-flow") {
360
+ checkLayeredFlowScope(context, push);
361
+ for (const key of DS_LAYOUT_MEASURED_HINTS) {
362
+ if (key in value) {
363
+ push("layout-hint-out-of-scope", key, `${key} is read by auto-pack only; layered-flow takes no authored hint`, {
364
+ details: { hint: key, mode: "layered-flow" },
365
+ });
366
+ }
367
+ }
368
+ }
369
+ if ("stretch" in value && typeof value["stretch"] !== "boolean") {
370
+ push("layout-hints-invalid", "stretch", `expected a boolean, got ${describe(value["stretch"])}`);
371
+ }
372
+ if ("rootOrder" in value)
373
+ checkEntityRefList(value["rootOrder"], "rootOrder", push);
374
+ if ("ordering" in value) {
375
+ const ordering = value["ordering"];
376
+ if (!isRecord(ordering)) {
377
+ push("layout-hints-invalid", "ordering", `expected an object keyed by parent entity, got ${describe(ordering)}`);
378
+ }
379
+ else {
380
+ const parentOf = new Map();
381
+ for (const parent of Object.keys(ordering)) {
382
+ const path = `ordering.${parent}`;
383
+ const parentValid = checkEntityRef(parent, path, push);
384
+ for (const member of checkEntityRefList(ordering[parent], path, push)) {
385
+ if (parentValid && member === parent) {
386
+ push("layout-hint-conflict", path, `${member} cannot be ordered under itself`, { refs: [member] });
387
+ continue;
388
+ }
389
+ const first = parentOf.get(member);
390
+ if (first !== undefined && first !== parent) {
391
+ push("layout-hint-conflict", path, `${member} is already ordered under ${first}`, { refs: [member, first, parent] });
392
+ continue;
393
+ }
394
+ parentOf.set(member, parent);
395
+ }
396
+ }
397
+ }
398
+ }
399
+ if ("grouping" in value && "grouping_axis" in value) {
400
+ push("layout-hint-conflict", "grouping_axis", "grouping and grouping_axis cannot be authored together", {
401
+ details: { hint: "grouping_axis", other: "grouping" },
402
+ });
403
+ }
404
+ if ("grouping_axis" in value)
405
+ checkAxis(value["grouping_axis"], "grouping_axis", push);
406
+ if ("grouping" in value) {
407
+ const grouping = value["grouping"];
408
+ if (!Array.isArray(grouping)) {
409
+ push("layout-hints-invalid", "grouping", `expected an array of groups, got ${describe(grouping)}`);
410
+ }
411
+ else {
412
+ const ledger = { ids: new Map(), leaves: new Map() };
413
+ grouping.forEach((group, index) => checkGroup(group, `grouping.${index}`, ledger, new Set(), push));
414
+ }
415
+ }
416
+ return done();
417
+ }
418
+ /** Type guard: true iff `validateLayoutHints` raises nothing. */
419
+ export function isLayoutHints(value, context) {
420
+ return validateLayoutHints(value, context).length === 0;
421
+ }
422
+ /** The id of the root group `grouping_axis` lowers to. */
423
+ export const DS_LAYOUT_ROOT_GROUP_ID = "ds-layout-hints.root";
424
+ function lowerGroup(group) {
425
+ return {
426
+ id: group.id,
427
+ direction: group.direction,
428
+ items: group.items.map((item) => (typeof item === "string" ? item : lowerGroup(item))),
429
+ ...(group.stretch === undefined ? {} : { stretch: group.stretch }),
430
+ };
431
+ }
432
+ /**
433
+ * Lower a VALID payload to the hints the layout engine takes. `mode` selects
434
+ * the engine entry and is not part of the result; `layered-flow` lowers to no
435
+ * hint at all.
436
+ *
437
+ * `grouping_axis` is a shorthand for one group over the root level: it needs
438
+ * the visible root entities, which only the caller knows. Listed roots come
439
+ * first in `rootOrder`, the others after in UTF-16 order (the engine's own
440
+ * rule). Without roots the shorthand lowers to nothing.
441
+ */
442
+ export function lowerLayoutHints(hints, roots = []) {
443
+ if (hints.mode !== "auto-pack")
444
+ return {};
445
+ let grouping = hints.grouping?.map(lowerGroup);
446
+ if (hints.grouping_axis !== undefined && roots.length > 0) {
447
+ const members = new Set(roots);
448
+ const listed = (hints.rootOrder ?? []).filter((member) => members.has(member));
449
+ const rest = [...members].filter((member) => !listed.includes(member)).sort();
450
+ grouping = [{ id: DS_LAYOUT_ROOT_GROUP_ID, direction: hints.grouping_axis, items: [...listed, ...rest] }];
451
+ }
452
+ return {
453
+ ...(hints.ordering === undefined ? {} : { ordering: hints.ordering }),
454
+ ...(hints.rootOrder === undefined ? {} : { rootOrder: hints.rootOrder }),
455
+ ...(grouping === undefined ? {} : { grouping }),
456
+ ...(hints.stretch === undefined ? {} : { stretch: hints.stretch }),
457
+ };
458
+ }
459
+ //# sourceMappingURL=layout-hints.js.map
@@ -0,0 +1,121 @@
1
+ /**
2
+ * `diagram-notation@1` — the closed notation vocabulary and its pin.
3
+ *
4
+ * A profile maps its types onto this vocabulary (which role draws an entity
5
+ * type, which encoding draws a relation type). The vocabulary is DS-owned;
6
+ * the mapping is profile data and holds no place here.
7
+ *
8
+ * Two layers, both data, both pinned:
9
+ * - `DIAGRAM_NOTATION_SCHEMA` JSON Schema 2020-12, structural only: closed
10
+ * objects, enums, string bounds, required `role`, `nature`, `encoding`,
11
+ * slot shape.
12
+ * - `DIAGRAM_NOTATION_RULES` every conditional the schema does not state:
13
+ * the role table, the variants of each nature, the property list of each
14
+ * encoding, slot ownership.
15
+ *
16
+ * `DIAGRAM_NOTATION_PIN.contentDigest` is the SHA-256 of the RFC 8785 bytes of
17
+ * `{ schema, rules }`. Any change to either is `diagram-notation@2`.
18
+ *
19
+ * NOT here: `validateNotation`, `validateViewNotation` and `resolveNotation`.
20
+ * This module freezes the vocabulary a consumer pins; the executor that reads
21
+ * it is a later lot, and until it ships nothing in this package enforces the
22
+ * rules below.
23
+ */
24
+ import type { PresentationPin } from "./presentation.js";
25
+ export declare const DIAGRAM_NOTATION_VOCABULARY: "diagram-notation@1";
26
+ export declare const DIAGRAM_NOTATION_MODES: readonly ["strict", "metadata"];
27
+ export declare const DIAGRAM_NOTATION_ROLES: readonly ["card", "container", "lane", "entity-table", "flow-node"];
28
+ export declare const DIAGRAM_NOTATION_NATURES: readonly ["component", "responsibility", "data", "activity"];
29
+ export declare const DIAGRAM_NOTATION_VARIANTS: readonly ["task", "start", "end", "decision", "subprocess", "data", "document", "participant"];
30
+ export declare const DIAGRAM_NOTATION_ENCODINGS: readonly ["arrow", "containment", "detail", "footer"];
31
+ export declare const DIAGRAM_NOTATION_ENDS: readonly ["none", "arrow", "cardinality"];
32
+ export type NotationMode = (typeof DIAGRAM_NOTATION_MODES)[number];
33
+ export type NotationRole = (typeof DIAGRAM_NOTATION_ROLES)[number];
34
+ export type NotationNature = (typeof DIAGRAM_NOTATION_NATURES)[number];
35
+ export type NotationVariant = (typeof DIAGRAM_NOTATION_VARIANTS)[number];
36
+ export type NotationEncoding = (typeof DIAGRAM_NOTATION_ENCODINGS)[number];
37
+ export type NotationEnds = (typeof DIAGRAM_NOTATION_ENDS)[number];
38
+ /** A slot is a literal text, or a lookup on an attribute of the instance. */
39
+ export type NotationSlot = string | {
40
+ readonly attribute: string;
41
+ readonly values: Readonly<Record<string, string>>;
42
+ readonly default: string;
43
+ };
44
+ export interface NotationTypeRef {
45
+ readonly profile: string;
46
+ readonly type: string;
47
+ }
48
+ export interface NotationNode {
49
+ readonly role: NotationRole;
50
+ readonly nature: NotationNature;
51
+ readonly variant?: NotationSlot;
52
+ readonly icon?: NotationSlot;
53
+ readonly kicker?: NotationSlot;
54
+ /** Roles of DIRECT containment children. */
55
+ readonly holds?: readonly NotationRole[];
56
+ }
57
+ export interface NotationRelation {
58
+ readonly encoding: NotationEncoding;
59
+ readonly ends?: NotationEnds;
60
+ readonly provisional?: {
61
+ readonly attribute: string;
62
+ readonly equals: string;
63
+ };
64
+ readonly lift?: {
65
+ readonly via: NotationTypeRef;
66
+ readonly ancestors: readonly NotationTypeRef[];
67
+ };
68
+ readonly fallback?: {
69
+ readonly encoding: "detail" | "footer";
70
+ readonly on: string;
71
+ readonly label: string;
72
+ };
73
+ readonly on?: string;
74
+ readonly label?: string;
75
+ }
76
+ export interface NotationBlock {
77
+ readonly vocabulary: typeof DIAGRAM_NOTATION_VOCABULARY;
78
+ readonly mode?: NotationMode;
79
+ readonly entityTypes: Readonly<Record<string, NotationNode>>;
80
+ readonly relationTypes: Readonly<Record<string, NotationRelation>>;
81
+ }
82
+ /** How a role treats one slot. `participant-only`: admitted when the effective variant is `participant`. */
83
+ export type NotationSlotRule = "required" | "optional" | "refused" | "participant-only";
84
+ export interface NotationRoleRule {
85
+ readonly natures: readonly NotationNature[];
86
+ readonly icon: NotationSlotRule;
87
+ readonly kicker: NotationSlotRule;
88
+ /** `by-nature`: the variant is one of `variants[nature]`. */
89
+ readonly variant: "refused" | "by-nature";
90
+ /** Roles a type of this role may list in `holds`. */
91
+ readonly holds: readonly NotationRole[];
92
+ /** When set, `holds` counts only for this effective variant. */
93
+ readonly holdsEffectiveFor?: NotationVariant;
94
+ }
95
+ export interface DiagramNotationRules {
96
+ readonly vocabulary: typeof DIAGRAM_NOTATION_VOCABULARY;
97
+ readonly defaultMode: NotationMode;
98
+ readonly roles: Readonly<Record<NotationRole, NotationRoleRule>>;
99
+ readonly variants: Readonly<Record<NotationNature, readonly NotationVariant[]>>;
100
+ readonly iconPattern: string;
101
+ readonly encodings: Readonly<Record<NotationEncoding, {
102
+ readonly properties: readonly string[];
103
+ readonly required: readonly string[];
104
+ }>>;
105
+ readonly endsDefault: {
106
+ readonly directed: NotationEnds;
107
+ readonly undirected: NotationEnds;
108
+ };
109
+ readonly slotOwners: Readonly<Record<"detail" | "footer", readonly NotationRole[]>>;
110
+ readonly liftAncestorRoles: readonly NotationRole[];
111
+ readonly containmentHierarchyShape: "tree";
112
+ }
113
+ /** The structural JSON Schema of a `diagram-notation@1` block, deeply frozen. */
114
+ export declare const DIAGRAM_NOTATION_SCHEMA: Readonly<Record<string, unknown>>;
115
+ /** The semantic rules of `diagram-notation@1`, as data, deeply frozen. */
116
+ export declare const DIAGRAM_NOTATION_RULES: DiagramNotationRules;
117
+ /** SHA-256 (64 lowercase hex) of the RFC 8785 bytes of `{ schema, rules }`. */
118
+ export declare const DIAGRAM_NOTATION_DIGEST: string;
119
+ /** The pin of the notation vocabulary. Equality is equality of the three fields. */
120
+ export declare const DIAGRAM_NOTATION_PIN: PresentationPin;
121
+ //# sourceMappingURL=notation.d.ts.map
@@ -0,0 +1,225 @@
1
+ /**
2
+ * `diagram-notation@1` — the closed notation vocabulary and its pin.
3
+ *
4
+ * A profile maps its types onto this vocabulary (which role draws an entity
5
+ * type, which encoding draws a relation type). The vocabulary is DS-owned;
6
+ * the mapping is profile data and holds no place here.
7
+ *
8
+ * Two layers, both data, both pinned:
9
+ * - `DIAGRAM_NOTATION_SCHEMA` JSON Schema 2020-12, structural only: closed
10
+ * objects, enums, string bounds, required `role`, `nature`, `encoding`,
11
+ * slot shape.
12
+ * - `DIAGRAM_NOTATION_RULES` every conditional the schema does not state:
13
+ * the role table, the variants of each nature, the property list of each
14
+ * encoding, slot ownership.
15
+ *
16
+ * `DIAGRAM_NOTATION_PIN.contentDigest` is the SHA-256 of the RFC 8785 bytes of
17
+ * `{ schema, rules }`. Any change to either is `diagram-notation@2`.
18
+ *
19
+ * NOT here: `validateNotation`, `validateViewNotation` and `resolveNotation`.
20
+ * This module freezes the vocabulary a consumer pins; the executor that reads
21
+ * it is a later lot, and until it ships nothing in this package enforces the
22
+ * rules below.
23
+ */
24
+ import { canonicalBytes, sha256Hex } from "./sha256.js";
25
+ export const DIAGRAM_NOTATION_VOCABULARY = "diagram-notation@1";
26
+ export const DIAGRAM_NOTATION_MODES = ["strict", "metadata"];
27
+ export const DIAGRAM_NOTATION_ROLES = ["card", "container", "lane", "entity-table", "flow-node"];
28
+ export const DIAGRAM_NOTATION_NATURES = ["component", "responsibility", "data", "activity"];
29
+ export const DIAGRAM_NOTATION_VARIANTS = ["task", "start", "end", "decision", "subprocess", "data", "document", "participant"];
30
+ export const DIAGRAM_NOTATION_ENCODINGS = ["arrow", "containment", "detail", "footer"];
31
+ export const DIAGRAM_NOTATION_ENDS = ["none", "arrow", "cardinality"];
32
+ const TEXT = { type: "string", minLength: 1, maxLength: 40 };
33
+ const NAME = { type: "string", minLength: 1, maxLength: 80 };
34
+ const PRIVATE_SCHEMA = {
35
+ $schema: "https://json-schema.org/draft/2020-12/schema",
36
+ $id: "engram:diagram-notation-schema/1",
37
+ title: "diagram-notation@1 block",
38
+ type: "object",
39
+ properties: {
40
+ vocabulary: { const: DIAGRAM_NOTATION_VOCABULARY },
41
+ mode: { enum: [...DIAGRAM_NOTATION_MODES] },
42
+ entityTypes: { type: "object", additionalProperties: { $ref: "#/$defs/node" } },
43
+ relationTypes: { type: "object", additionalProperties: { $ref: "#/$defs/relation" } },
44
+ },
45
+ required: ["vocabulary", "entityTypes", "relationTypes"],
46
+ additionalProperties: false,
47
+ $defs: {
48
+ text: TEXT,
49
+ name: NAME,
50
+ role: { enum: [...DIAGRAM_NOTATION_ROLES] },
51
+ nature: { enum: [...DIAGRAM_NOTATION_NATURES] },
52
+ slot: {
53
+ anyOf: [
54
+ { $ref: "#/$defs/text" },
55
+ {
56
+ type: "object",
57
+ properties: {
58
+ attribute: { $ref: "#/$defs/name" },
59
+ values: { type: "object", maxProperties: 32, additionalProperties: { $ref: "#/$defs/text" } },
60
+ default: { $ref: "#/$defs/text" },
61
+ },
62
+ required: ["attribute", "values", "default"],
63
+ additionalProperties: false,
64
+ },
65
+ ],
66
+ },
67
+ typeRef: {
68
+ type: "object",
69
+ properties: { profile: { $ref: "#/$defs/name" }, type: { $ref: "#/$defs/name" } },
70
+ required: ["profile", "type"],
71
+ additionalProperties: false,
72
+ },
73
+ node: {
74
+ type: "object",
75
+ properties: {
76
+ role: { $ref: "#/$defs/role" },
77
+ nature: { $ref: "#/$defs/nature" },
78
+ variant: { $ref: "#/$defs/slot" },
79
+ icon: { $ref: "#/$defs/slot" },
80
+ kicker: { $ref: "#/$defs/slot" },
81
+ holds: { type: "array", items: { $ref: "#/$defs/role" }, uniqueItems: true },
82
+ },
83
+ required: ["role", "nature"],
84
+ additionalProperties: false,
85
+ },
86
+ relation: {
87
+ type: "object",
88
+ properties: {
89
+ encoding: { enum: [...DIAGRAM_NOTATION_ENCODINGS] },
90
+ ends: { enum: [...DIAGRAM_NOTATION_ENDS] },
91
+ provisional: {
92
+ type: "object",
93
+ properties: { attribute: { $ref: "#/$defs/name" }, equals: { $ref: "#/$defs/text" } },
94
+ required: ["attribute", "equals"],
95
+ additionalProperties: false,
96
+ },
97
+ lift: {
98
+ type: "object",
99
+ properties: {
100
+ via: { $ref: "#/$defs/typeRef" },
101
+ ancestors: { type: "array", minItems: 1, items: { $ref: "#/$defs/typeRef" } },
102
+ },
103
+ required: ["via", "ancestors"],
104
+ additionalProperties: false,
105
+ },
106
+ fallback: {
107
+ type: "object",
108
+ properties: {
109
+ encoding: { enum: ["detail", "footer"] },
110
+ on: { $ref: "#/$defs/name" },
111
+ label: { $ref: "#/$defs/text" },
112
+ },
113
+ required: ["encoding", "on", "label"],
114
+ additionalProperties: false,
115
+ },
116
+ on: { $ref: "#/$defs/name" },
117
+ label: { $ref: "#/$defs/text" },
118
+ },
119
+ required: ["encoding"],
120
+ additionalProperties: false,
121
+ },
122
+ },
123
+ };
124
+ const PRIVATE_RULES = {
125
+ vocabulary: DIAGRAM_NOTATION_VOCABULARY,
126
+ defaultMode: "strict",
127
+ roles: {
128
+ card: {
129
+ natures: ["component"],
130
+ icon: "required",
131
+ kicker: "optional",
132
+ variant: "refused",
133
+ holds: ["card", "entity-table", "flow-node"],
134
+ },
135
+ container: {
136
+ natures: ["component"],
137
+ icon: "required",
138
+ kicker: "optional",
139
+ variant: "refused",
140
+ holds: ["card", "container", "entity-table", "lane", "flow-node"],
141
+ },
142
+ lane: {
143
+ natures: ["responsibility"],
144
+ icon: "refused",
145
+ kicker: "refused",
146
+ variant: "refused",
147
+ holds: ["flow-node", "lane"],
148
+ },
149
+ "entity-table": {
150
+ natures: ["data"],
151
+ icon: "optional",
152
+ kicker: "refused",
153
+ variant: "refused",
154
+ holds: [],
155
+ },
156
+ "flow-node": {
157
+ natures: ["activity", "data", "responsibility"],
158
+ icon: "participant-only",
159
+ kicker: "refused",
160
+ variant: "by-nature",
161
+ holds: ["flow-node"],
162
+ holdsEffectiveFor: "subprocess",
163
+ },
164
+ },
165
+ /** Variants of each nature; the first is the default. `component` has none. */
166
+ variants: {
167
+ activity: ["task", "start", "end", "decision", "subprocess"],
168
+ data: ["data", "document"],
169
+ responsibility: ["participant"],
170
+ component: [],
171
+ },
172
+ /** Glyph id grammar of an `icon` text. The glyph inventory is not part of the pin. */
173
+ iconPattern: "^[a-z][a-z0-9-]{0,39}$",
174
+ /** The properties each encoding admits, `encoding` included; `required` among them. */
175
+ encodings: {
176
+ arrow: { properties: ["encoding", "ends", "provisional"], required: ["encoding"] },
177
+ containment: { properties: ["encoding", "lift", "fallback"], required: ["encoding"] },
178
+ detail: { properties: ["encoding", "on", "label"], required: ["encoding", "on", "label"] },
179
+ footer: { properties: ["encoding", "on", "label"], required: ["encoding", "on", "label"] },
180
+ },
181
+ /** `ends` when absent: `arrow` on a directed relation type, else `none`. */
182
+ endsDefault: { directed: "arrow", undirected: "none" },
183
+ /** Roles that own each text slot: every type allowed on the `on` endpoint must have one of them. */
184
+ slotOwners: {
185
+ detail: ["card", "container", "entity-table"],
186
+ footer: ["card", "container"],
187
+ },
188
+ /** Roles a `lift.ancestors` type must have. */
189
+ liftAncestorRoles: ["card", "container"],
190
+ /** `containment` needs a relation type whose hierarchy has this shape. */
191
+ containmentHierarchyShape: "tree",
192
+ };
193
+ function deepClone(value) {
194
+ if (value === null || typeof value !== "object")
195
+ return value;
196
+ if (Array.isArray(value))
197
+ return value.map((item) => deepClone(item));
198
+ const out = {};
199
+ for (const key of Object.keys(value)) {
200
+ out[key] = deepClone(value[key]);
201
+ }
202
+ return out;
203
+ }
204
+ function deepFreeze(value) {
205
+ if (value === null || typeof value !== "object" || Object.isFrozen(value))
206
+ return value;
207
+ for (const child of Object.values(value))
208
+ deepFreeze(child);
209
+ return Object.freeze(value);
210
+ }
211
+ deepFreeze(PRIVATE_SCHEMA);
212
+ deepFreeze(PRIVATE_RULES);
213
+ /** The structural JSON Schema of a `diagram-notation@1` block, deeply frozen. */
214
+ export const DIAGRAM_NOTATION_SCHEMA = deepFreeze(deepClone(PRIVATE_SCHEMA));
215
+ /** The semantic rules of `diagram-notation@1`, as data, deeply frozen. */
216
+ export const DIAGRAM_NOTATION_RULES = deepFreeze(deepClone(PRIVATE_RULES));
217
+ /** SHA-256 (64 lowercase hex) of the RFC 8785 bytes of `{ schema, rules }`. */
218
+ export const DIAGRAM_NOTATION_DIGEST = sha256Hex(canonicalBytes({ schema: PRIVATE_SCHEMA, rules: PRIVATE_RULES }));
219
+ /** The pin of the notation vocabulary. Equality is equality of the three fields. */
220
+ export const DIAGRAM_NOTATION_PIN = deepFreeze({
221
+ id: "diagram-notation",
222
+ version: "1",
223
+ contentDigest: DIAGRAM_NOTATION_DIGEST,
224
+ });
225
+ //# sourceMappingURL=notation.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sentropic/diagram-core",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Typed semantic core for diagrams: versioned documents and profiles, views with occurrences, transactional commands with logical inverses. No runtime dependency, no DOM, no framework.",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -24,7 +24,9 @@
24
24
  "import": "./dist/index.js"
25
25
  },
26
26
  "./schemas/diagram-view-schema-3.json": "./schemas/diagram-view-schema-3.json",
27
- "./schemas/diagram-view-schema-3.sha256": "./schemas/diagram-view-schema-3.sha256"
27
+ "./schemas/diagram-view-schema-3.sha256": "./schemas/diagram-view-schema-3.sha256",
28
+ "./schemas/ds-layout-hints-1.json": "./schemas/ds-layout-hints-1.json",
29
+ "./schemas/ds-layout-hints-1.sha256": "./schemas/ds-layout-hints-1.sha256"
28
30
  },
29
31
  "types": "./dist/index.d.ts",
30
32
  "main": "./dist/index.js",
@@ -0,0 +1 @@
1
+ {"$defs":{"axis":{"enum":["rows","columns"]},"entityRef":{"pattern":"^entity:[A-Za-z0-9][A-Za-z0-9._-]*$","type":"string"},"entityRefList":{"items":{"$ref":"#/$defs/entityRef"},"type":"array","uniqueItems":true},"forbiddenHint":{"enum":["cardGapX","cardGapY","density","edge_label_orientation","gapAfter","height","rankGap","width","x","y","zoneGapX","zoneGapY"]},"futureHint":{"enum":["direction","rotate_labels"]},"futureMode":{"enum":["lane-stack","matrix-grid","tree"]},"group":{"additionalProperties":false,"properties":{"direction":{"$ref":"#/$defs/axis"},"id":{"maxLength":80,"minLength":1,"type":"string"},"items":{"items":{"anyOf":[{"$ref":"#/$defs/entityRef"},{"$ref":"#/$defs/group"}]},"minItems":1,"type":"array"},"stretch":{"type":"boolean"}},"required":["id","direction","items"],"type":"object"},"layeredFlowScope":{"properties":{"diagramPresentation":{"const":false},"presentationVocabulary":false,"profiles":{"items":{"const":"generic@1"},"minItems":1,"type":"array"}},"required":["profiles","diagramPresentation"],"type":"object"},"measuredHint":{"enum":["grouping","grouping_axis","ordering","rootOrder","stretch"]},"mode":{"enum":["auto-pack","layered-flow"]}},"$id":"https://sentropic.dev/schemas/diagram/layout-hints/v1","$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"dependentSchemas":{"grouping":{"properties":{"grouping_axis":false}}},"if":{"properties":{"mode":{"const":"layered-flow"}},"required":["mode"]},"properties":{"grouping":{"items":{"$ref":"#/$defs/group"},"type":"array"},"grouping_axis":{"$ref":"#/$defs/axis"},"mode":{"$ref":"#/$defs/mode"},"ordering":{"additionalProperties":{"$ref":"#/$defs/entityRefList"},"propertyNames":{"$ref":"#/$defs/entityRef"},"type":"object"},"rootOrder":{"$ref":"#/$defs/entityRefList"},"stretch":{"type":"boolean"},"vocabulary":{"const":"ds-layout-hints@1"}},"required":["vocabulary","mode"],"then":{"properties":{"grouping":false,"grouping_axis":false,"ordering":false,"rootOrder":false,"stretch":false}},"title":"ds-layout-hints@1","type":"object"}
@@ -0,0 +1 @@
1
+ e72fd3f3446e19585b2992071f57c3777685f27087165c932806e12354ced42c