@openplanr/protocol 0.6.1 → 0.7.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 (58) hide show
  1. package/README.md +10 -0
  2. package/lib/dashboard/closed-json-contract.mjs +99 -109
  3. package/lib/dashboard/operate-experience-audit-display-contract.d.mts +128 -153
  4. package/lib/dashboard/operate-experience-audit-display-contract.mjs +530 -585
  5. package/lib/dashboard/operate-experience-display-contract.d.mts +415 -437
  6. package/lib/dashboard/operate-experience-display-contract.mjs +777 -831
  7. package/lib/dashboard/operate-experience-surface-contract.d.mts +143 -148
  8. package/lib/dashboard/operate-experience-surface-contract.mjs +72 -73
  9. package/lib/dashboard/operate-review-contract.d.mts +7 -14
  10. package/lib/dashboard/operate-review-contract.mjs +46 -42
  11. package/lib/dashboard/operate-review-display-workspace-contract.d.mts +2 -5
  12. package/lib/dashboard/operate-review-display-workspace-contract.mjs +158 -104
  13. package/lib/dashboard/operate-review-payload-safety.mjs +4 -2
  14. package/lib/dashboard/operate-review-workspace-projection-v2.d.mts +47 -33
  15. package/lib/protocol/index.d.ts +2647 -543
  16. package/package.json +1 -1
  17. package/registries/artifact-theme.json +64 -0
  18. package/registries/commands.json +40 -40
  19. package/registries/skills.json +5 -5
  20. package/schemas/v1.14.0/artifact-theme.schema.json +316 -0
  21. package/src/browser-contracts.d.mts +4 -1
  22. package/src/browser-contracts.mjs +16 -5
  23. package/src/canonical-json.d.mts +6 -1
  24. package/src/canonical-json.mjs +100 -22
  25. package/src/compat/live-evidence-v2.mjs +1611 -485
  26. package/src/compat/operate-experience-live-patch.mjs +67 -15
  27. package/src/compat/operating-planning-contracts.mjs +183 -51
  28. package/src/contracts.d.mts +54 -13
  29. package/src/contracts.mjs +635 -343
  30. package/src/design-contracts.mjs +58 -21
  31. package/src/design-handoff-contracts.d.mts +67 -11
  32. package/src/design-handoff-contracts.mjs +236 -119
  33. package/src/design-publication-contracts.mjs +98 -33
  34. package/src/diagram-authoring-contracts.d.mts +422 -78
  35. package/src/diagram-authoring-contracts.mjs +1715 -335
  36. package/src/diagram-contracts.d.mts +4 -1
  37. package/src/diagram-contracts.mjs +16 -4
  38. package/src/enterprise-contracts.d.mts +211 -46
  39. package/src/enterprise-contracts.mjs +738 -184
  40. package/src/errors.mjs +4 -0
  41. package/src/generated/canonical-registries.mjs +45 -45
  42. package/src/index.d.mts +8 -8
  43. package/src/index.mjs +36 -20
  44. package/src/json-schema.d.mts +21 -6
  45. package/src/json-schema.mjs +66 -18
  46. package/src/planning-contracts.d.mts +8 -2
  47. package/src/planning-contracts.mjs +33 -7
  48. package/src/registries.d.mts +11 -3
  49. package/src/registries.mjs +369 -87
  50. package/src/review-experience-contracts.d.mts +7 -2
  51. package/src/review-experience-contracts.mjs +198 -49
  52. package/src/semver.mjs +5 -1
  53. package/src/skill-source-contracts.d.mts +36 -16
  54. package/src/skill-source-contracts.mjs +25 -6
  55. package/src/task-contracts.d.mts +13 -3
  56. package/src/task-contracts.mjs +181 -40
  57. package/src/workspace-contracts.d.mts +38 -10
  58. package/src/workspace-contracts.mjs +147 -33
@@ -1,59 +1,139 @@
1
- import { canonicalizeJson, sha256Jcs, sha256Hex } from './canonical-json.mjs';
2
- import { validateJson } from './json-schema.mjs';
1
+ // @ts-check
2
+ /**
3
+ * Diagram authoring contracts (Protocol 1.13.0): closed schemas for documents, presentations,
4
+ * bundles, edit transactions, source maps, fidelity reports, manifests, proposals and publication
5
+ * state, with accessor-safe inspection, digests, cross-reference checks and the capability catalog.
6
+ * Entry points: `validateDiagramAuthoringArtifact`, `assertDiagramAuthoringArtifact`,
7
+ * `DIAGRAM_AUTHORING_CAPABILITIES`, `inspectLegacyDiagramDocument`. Applying edits and rendering
8
+ * belong to the artifact package's `diagram/authoring` modules.
9
+ */
10
+
11
+ import { canonicalizeJson, deepFreeze, sha256Hex, sha256Jcs } from './canonical-json.mjs';
3
12
  import { DIAGRAM_REGISTRIES } from './generated/diagram-registries.mjs';
4
13
  import { LEGACY_DIAGRAM_DOCUMENT_SCHEMA } from './generated/legacy-diagram-schema.mjs';
14
+ import { validateJson } from './json-schema.mjs';
15
+
16
+ /** @typedef {import('./diagram-authoring-contracts.d.mts').DiagramAuthoringCapability} DiagramAuthoringCapability */
17
+ /** @typedef {import('./diagram-authoring-contracts.d.mts').DiagramAuthoringContractKind} DiagramAuthoringContractKind */
5
18
 
6
- /** Portable, inert data contracts. Validation confers no authorization or readiness. */
19
+ /**
20
+ * Portable, inert data contracts. Validation confers no authorization or readiness.
21
+ * @type {typeof import('./diagram-authoring-contracts.d.mts').DIAGRAM_AUTHORING_PROTOCOL_VERSION}
22
+ */
7
23
  export const DIAGRAM_AUTHORING_PROTOCOL_VERSION = '1.13.0';
24
+ /** @type {typeof import('./diagram-authoring-contracts.d.mts').DIAGRAM_AUTHORING_CONTRACT_VERSION} */
8
25
  export const DIAGRAM_AUTHORING_CONTRACT_VERSION = '1.0.0';
9
- const deepFreeze = (value) => {
10
- if (value && typeof value === 'object' && !Object.isFrozen(value)) {
11
- Object.values(value).forEach(deepFreeze);
12
- Object.freeze(value);
13
- }
14
- return value;
15
- };
26
+ /** @type {typeof import('./diagram-authoring-contracts.d.mts').DIAGRAM_EDIT_OPERATION_CLASSES} */
16
27
  export const DIAGRAM_EDIT_OPERATION_CLASSES = deepFreeze([
17
- 'insert-elements', 'update-semantics', 'remove-elements', 'set-membership-order',
18
- 'set-geometry', 'set-appearance-locks',
28
+ 'insert-elements',
29
+ 'update-semantics',
30
+ 'remove-elements',
31
+ 'set-membership-order',
32
+ 'set-geometry',
33
+ 'set-appearance-locks',
19
34
  ]);
35
+ /** @type {typeof import('./diagram-authoring-contracts.d.mts').DIAGRAM_AUTHORING_LIMITS} */
20
36
  export const DIAGRAM_AUTHORING_LIMITS = deepFreeze({
21
- depth: 48, values: 500000, textCodeUnits: 8388608, sourceBytes: 1048576,
22
- elements: 10000, operations: 256, coordinate: 1000000,
37
+ depth: 48,
38
+ values: 500000,
39
+ textCodeUnits: 8388608,
40
+ sourceBytes: 1048576,
41
+ elements: 10000,
42
+ operations: 256,
43
+ coordinate: 1000000,
23
44
  });
24
45
 
25
- const closed = (properties, required = Object.keys(properties)) => ({ type: 'object', additionalProperties: false, properties, required });
26
- const arr = (items, maxItems, minItems = 0, uniqueItems = false) => ({ type: 'array', items, minItems, maxItems, ...(uniqueItems ? { uniqueItems } : {}) });
46
+ const closed = (properties, required = Object.keys(properties)) => ({
47
+ type: 'object',
48
+ additionalProperties: false,
49
+ properties,
50
+ required,
51
+ });
52
+ const arr = (items, maxItems, minItems = 0, uniqueItems = false) => ({
53
+ type: 'array',
54
+ items,
55
+ minItems,
56
+ maxItems,
57
+ ...(uniqueItems ? { uniqueItems } : {}),
58
+ });
27
59
  const nullable = (schema) => ({ anyOf: [{ type: 'null' }, schema] });
28
60
  const str = (maxLength = 4096, minLength = 0) => ({ type: 'string', minLength, maxLength });
29
61
  const enumOf = (...values) => ({ enum: values });
30
- const id = { type: 'string', pattern: '^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$', minLength: 1, maxLength: 128 };
62
+ const id = {
63
+ type: 'string',
64
+ pattern: '^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$',
65
+ minLength: 1,
66
+ maxLength: 128,
67
+ };
31
68
  const digest = { type: 'string', pattern: '^sha256:[a-f0-9]{64}$' };
32
69
  const token = { type: 'string', pattern: '^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$', maxLength: 64 };
33
- const relativePath = { type: 'string', minLength: 1, maxLength: 1024, pattern: '^[A-Za-z0-9][A-Za-z0-9._/-]*$' };
70
+ const relativePath = {
71
+ type: 'string',
72
+ minLength: 1,
73
+ maxLength: 1024,
74
+ pattern: '^[A-Za-z0-9][A-Za-z0-9._/-]*$',
75
+ };
34
76
  const coordinate = { type: 'number', minimum: -1000000, maximum: 1000000 };
35
77
  const positiveSize = { type: 'number', minimum: 0.01, maximum: 1000000 };
36
78
  const index = { type: 'integer', minimum: 0, maximum: 10000 };
37
79
  const ids = arr(id, 10000, 0, true);
38
80
  const semanticKinds = ['process', 'start', 'end', 'decision', 'data-store', 'component'];
39
81
  const relationKinds = ['association', 'dependency', 'flow', 'message', 'transition'];
40
- const node = closed({ id, label: str(), kind: enumOf(...semanticKinds), description: nullable(str()) });
41
- const relation = closed({ id, from: id, to: id, kind: enumOf(...relationKinds), direction: enumOf('forward', 'both', 'none'), label: nullable(str()), weight: nullable({ type: 'number', minimum: 0, maximum: 1000000 }) });
82
+ const node = closed({
83
+ id,
84
+ label: str(),
85
+ kind: enumOf(...semanticKinds),
86
+ description: nullable(str()),
87
+ });
88
+ const relation = closed({
89
+ id,
90
+ from: id,
91
+ to: id,
92
+ kind: enumOf(...relationKinds),
93
+ direction: enumOf('forward', 'both', 'none'),
94
+ label: nullable(str()),
95
+ weight: nullable({ type: 'number', minimum: 0, maximum: 1000000 }),
96
+ });
42
97
  const container = closed({ id, label: str(), members: ids });
43
98
  const annotation = closed({ id, text: str(), targetId: nullable(id) });
44
99
  const emphasis = closed({ targetId: id, level: enumOf('primary', 'secondary', 'muted') });
45
100
  const semanticCollections = {
46
- nodes: arr(node, 4096), relations: arr(relation, 8192), groups: arr(container, 1024),
47
- lanes: arr(container, 256), events: arr(false, 0), series: arr(false, 0), axes: arr(false, 0),
48
- sets: arr(false, 0), annotations: arr(annotation, 1024), emphasis: arr(emphasis, 1024),
101
+ nodes: arr(node, 4096),
102
+ relations: arr(relation, 8192),
103
+ groups: arr(container, 1024),
104
+ lanes: arr(container, 256),
105
+ events: arr(false, 0),
106
+ series: arr(false, 0),
107
+ axes: arr(false, 0),
108
+ sets: arr(false, 0),
109
+ annotations: arr(annotation, 1024),
110
+ emphasis: arr(emphasis, 1024),
49
111
  };
50
112
  const bounds = closed({ x: coordinate, y: coordinate, width: positiveSize, height: positiveSize });
51
113
  const point = closed({ x: coordinate, y: coordinate });
52
- const attachment = closed({ side: enumOf('top', 'right', 'bottom', 'left'), offset: { type: 'number', minimum: 0, maximum: 1 } });
53
- const route = closed({ mode: enumOf('automatic', 'manual'), strategy: enumOf('straight', 'orthogonal'), from: attachment, to: attachment, points: arr(point, 256) });
114
+ const attachment = closed({
115
+ side: enumOf('top', 'right', 'bottom', 'left'),
116
+ offset: { type: 'number', minimum: 0, maximum: 1 },
117
+ });
118
+ const route = closed({
119
+ mode: enumOf('automatic', 'manual'),
120
+ strategy: enumOf('straight', 'orthogonal'),
121
+ from: attachment,
122
+ to: attachment,
123
+ points: arr(point, 256),
124
+ });
54
125
  const labelPlacement = closed({ x: coordinate, y: coordinate, width: positiveSize });
55
126
  const appearance = closed({
56
- shape: enumOf('rectangle', 'rounded-rectangle', 'ellipse', 'diamond', 'cylinder', 'text', 'container', 'connector'),
127
+ shape: enumOf(
128
+ 'rectangle',
129
+ 'rounded-rectangle',
130
+ 'ellipse',
131
+ 'diamond',
132
+ 'cylinder',
133
+ 'text',
134
+ 'container',
135
+ 'connector',
136
+ ),
57
137
  fill: enumOf('surface', 'accent', 'success', 'warning', 'danger', 'transparent'),
58
138
  stroke: enumOf('default', 'accent', 'muted', 'danger', 'none'),
59
139
  strokeWidth: { type: 'number', minimum: 0, maximum: 16 },
@@ -61,151 +141,501 @@ const appearance = closed({
61
141
  fontSize: { type: 'integer', minimum: 8, maximum: 72 },
62
142
  textAlign: enumOf('left', 'center', 'right'),
63
143
  });
64
- const locks = closed({ position: { type: 'boolean' }, size: { type: 'boolean' }, route: { type: 'boolean' } });
65
- const placement = closed({ elementId: id, bounds: nullable(bounds), route: nullable(route), label: nullable(labelPlacement), zIndex: index, appearance, locks });
66
- const snapshot = closed({ bundleDigest: digest, semanticDigest: digest, presentationDigest: digest });
144
+ const locks = closed({
145
+ position: { type: 'boolean' },
146
+ size: { type: 'boolean' },
147
+ route: { type: 'boolean' },
148
+ });
149
+ const placement = closed({
150
+ elementId: id,
151
+ bounds: nullable(bounds),
152
+ route: nullable(route),
153
+ label: nullable(labelPlacement),
154
+ zIndex: index,
155
+ appearance,
156
+ locks,
157
+ });
158
+ const snapshot = closed({
159
+ bundleDigest: digest,
160
+ semanticDigest: digest,
161
+ presentationDigest: digest,
162
+ });
67
163
  const schema = (name, kind, properties) => ({
68
164
  $schema: 'https://json-schema.org/draft/2020-12/schema',
69
165
  $id: `https://openplanr.dev/schemas/v1.13.0/${name}.schema.json`,
70
166
  'x-openplanr-contract': { id: name, version: '1.13.0' },
71
- ...closed({ kind: { const: kind }, schemaVersion: { const: '1.0.0' }, protocolVersion: { const: '1.13.0' }, ...properties }),
167
+ ...closed({
168
+ kind: { const: kind },
169
+ schemaVersion: { const: '1.0.0' },
170
+ protocolVersion: { const: '1.13.0' },
171
+ ...properties,
172
+ }),
72
173
  });
73
174
 
74
175
  const documentSchema = schema('diagram-document', 'planr-diagram', {
75
- diagramId: id, title: str(), summary: str(), audience: enumOf('engineer', 'executive', 'mixed'),
76
- grammar: closed({ id: enumOf('flowchart', 'process', 'swimlane', 'architecture'), version: { const: '1.0.0' } }),
77
- ...semanticCollections, laneOrder: ids,
176
+ diagramId: id,
177
+ title: str(),
178
+ summary: str(),
179
+ audience: enumOf('engineer', 'executive', 'mixed'),
180
+ grammar: closed({
181
+ id: enumOf('flowchart', 'process', 'swimlane', 'architecture'),
182
+ version: { const: '1.0.0' },
183
+ }),
184
+ ...semanticCollections,
185
+ laneOrder: ids,
78
186
  accessibility: closed({ title: str(), description: str(), readingOrder: ids }),
79
187
  documentDigest: digest,
80
188
  });
81
189
  const presentationSchema = schema('diagram-presentation', 'diagram-presentation', {
82
- diagramId: id, semanticDigest: digest, coordinateSystem: { const: 'global-canvas' },
83
- layout: closed({ direction: enumOf('top-down', 'left-right', 'right-left', 'bottom-up'), detailTier: enumOf('simplified', 'balanced', 'faithful') }),
84
- theme: closed({ themeId: enumOf('paper', 'slate', 'midnight'), mode: enumOf('light', 'dark', 'auto') }),
85
- elements: arr(placement, 10000), presentationDigest: digest,
190
+ diagramId: id,
191
+ semanticDigest: digest,
192
+ coordinateSystem: { const: 'global-canvas' },
193
+ layout: closed({
194
+ direction: enumOf('top-down', 'left-right', 'right-left', 'bottom-up'),
195
+ detailTier: enumOf('simplified', 'balanced', 'faithful'),
196
+ }),
197
+ theme: closed({
198
+ themeId: enumOf('paper', 'slate', 'midnight'),
199
+ mode: enumOf('light', 'dark', 'auto'),
200
+ }),
201
+ elements: arr(placement, 10000),
202
+ presentationDigest: digest,
203
+ });
204
+ const range = closed({
205
+ startByte: { type: 'integer', minimum: 0, maximum: 1048576 },
206
+ endByte: { type: 'integer', minimum: 0, maximum: 1048576 },
86
207
  });
87
- const range = closed({ startByte: { type: 'integer', minimum: 0, maximum: 1048576 }, endByte: { type: 'integer', minimum: 0, maximum: 1048576 } });
88
208
  const sourceMapSchema = schema('diagram-source-map', 'diagram-source-map', {
89
- diagramId: id, semanticDigest: digest, sourceDigest: digest,
209
+ diagramId: id,
210
+ semanticDigest: digest,
211
+ sourceDigest: digest,
90
212
  sourceByteLength: { type: 'integer', minimum: 0, maximum: 1048576 },
91
- encoding: { const: 'utf-8' }, parser: closed({ id: token, version: str(64, 1) }),
213
+ encoding: { const: 'utf-8' },
214
+ parser: closed({ id: token, version: str(64, 1) }),
92
215
  certificationVersion: { const: 'flowchart-copy-v1' },
93
- entries: arr(closed({ sourceId: nullable(str(128, 1)), elementIds: ids, range: nullable(range), construct: token, confidence: enumOf('exact', 'ambiguous'), losses: arr(str(512, 1), 64) }), 10000),
216
+ entries: arr(
217
+ closed({
218
+ sourceId: nullable(str(128, 1)),
219
+ elementIds: ids,
220
+ range: nullable(range),
221
+ construct: token,
222
+ confidence: enumOf('exact', 'ambiguous'),
223
+ losses: arr(str(512, 1), 64),
224
+ }),
225
+ 10000,
226
+ ),
94
227
  });
95
228
  const fidelityValue = enumOf('lossless', 'partial', 'unsupported');
96
229
  const fidelitySchema = schema('diagram-fidelity-report', 'diagram-fidelity-report', {
97
- diagramId: id, basis: snapshot, sourceDigest: nullable(digest),
98
- sourceFormat: enumOf('mermaid', 'planr-diagram-bundle'), targetFormat: enumOf('mermaid', 'planr-diagram-bundle', 'svg', 'html', 'png'),
99
- semantic: fidelityValue, presentation: fidelityValue, sourceText: fidelityValue,
100
- losses: arr(closed({ dimension: enumOf('semantic', 'presentation', 'sourceText'), code: token, elementIds: ids, message: str(512, 1) }), 1024),
230
+ diagramId: id,
231
+ basis: snapshot,
232
+ sourceDigest: nullable(digest),
233
+ sourceFormat: enumOf('mermaid', 'planr-diagram-bundle'),
234
+ targetFormat: enumOf('mermaid', 'planr-diagram-bundle', 'svg', 'html', 'png'),
235
+ semantic: fidelityValue,
236
+ presentation: fidelityValue,
237
+ sourceText: fidelityValue,
238
+ losses: arr(
239
+ closed({
240
+ dimension: enumOf('semantic', 'presentation', 'sourceText'),
241
+ code: token,
242
+ elementIds: ids,
243
+ message: str(512, 1),
244
+ }),
245
+ 1024,
246
+ ),
101
247
  });
102
248
  const bundleSchema = schema('diagram-authoring-bundle', 'diagram-authoring-bundle', {
103
- diagramId: id, document: documentSchema, presentation: presentationSchema,
104
- originalSource: nullable(closed({ format: { const: 'mermaid' }, text: str(1048576), sourceDigest: digest })),
105
- sourceMap: nullable(sourceMapSchema), bundleDigest: digest,
106
- });
107
- const semanticEntry = { oneOf: [
108
- closed({ collection: { const: 'nodes' }, value: node }), closed({ collection: { const: 'relations' }, value: relation }),
109
- closed({ collection: { const: 'groups' }, value: container }), closed({ collection: { const: 'lanes' }, value: container }),
110
- closed({ collection: { const: 'annotations' }, value: annotation }),
111
- ] };
112
- const editableSemanticValue = (collection, properties) => closed({
113
- type: { const: 'update-semantics' }, collection: { const: collection }, elementId: id,
114
- before: closed(properties), after: closed(properties),
249
+ diagramId: id,
250
+ document: documentSchema,
251
+ presentation: presentationSchema,
252
+ originalSource: nullable(
253
+ closed({ format: { const: 'mermaid' }, text: str(1048576), sourceDigest: digest }),
254
+ ),
255
+ sourceMap: nullable(sourceMapSchema),
256
+ bundleDigest: digest,
115
257
  });
258
+ const semanticEntry = {
259
+ oneOf: [
260
+ closed({ collection: { const: 'nodes' }, value: node }),
261
+ closed({ collection: { const: 'relations' }, value: relation }),
262
+ closed({ collection: { const: 'groups' }, value: container }),
263
+ closed({ collection: { const: 'lanes' }, value: container }),
264
+ closed({ collection: { const: 'annotations' }, value: annotation }),
265
+ ],
266
+ };
267
+ const editableSemanticValue = (collection, properties) =>
268
+ closed({
269
+ type: { const: 'update-semantics' },
270
+ collection: { const: collection },
271
+ elementId: id,
272
+ before: closed(properties),
273
+ after: closed(properties),
274
+ });
116
275
  const updateSchemas = [
117
- editableSemanticValue('nodes', { label: str(), kind: enumOf(...semanticKinds), description: nullable(str()) }),
118
- editableSemanticValue('relations', { from: id, to: id, kind: enumOf(...relationKinds), direction: enumOf('forward', 'both', 'none'), label: nullable(str()), weight: nullable({ type: 'number', minimum: 0, maximum: 1000000 }) }),
119
- editableSemanticValue('groups', { label: str() }), editableSemanticValue('lanes', { label: str() }),
276
+ editableSemanticValue('nodes', {
277
+ label: str(),
278
+ kind: enumOf(...semanticKinds),
279
+ description: nullable(str()),
280
+ }),
281
+ editableSemanticValue('relations', {
282
+ from: id,
283
+ to: id,
284
+ kind: enumOf(...relationKinds),
285
+ direction: enumOf('forward', 'both', 'none'),
286
+ label: nullable(str()),
287
+ weight: nullable({ type: 'number', minimum: 0, maximum: 1000000 }),
288
+ }),
289
+ editableSemanticValue('groups', { label: str() }),
290
+ editableSemanticValue('lanes', { label: str() }),
120
291
  editableSemanticValue('annotations', { text: str(), targetId: nullable(id) }),
121
- closed({ type: { const: 'update-semantics' }, collection: { const: 'emphasis' }, elementId: id, before: nullable(enumOf('primary', 'secondary', 'muted')), after: nullable(enumOf('primary', 'secondary', 'muted')), index: { type: 'integer', minimum: 0, maximum: 1024 } }, ['type', 'collection', 'elementId', 'before', 'after']),
122
- closed({ type: { const: 'update-semantics' }, collection: { const: 'document' }, before: closed({ title: str(), summary: str(), audience: enumOf('engineer', 'executive', 'mixed'), accessibility: documentSchema.properties.accessibility }), after: closed({ title: str(), summary: str(), audience: enumOf('engineer', 'executive', 'mixed'), accessibility: documentSchema.properties.accessibility }) }),
123
- closed({ type: { const: 'update-semantics' }, collection: { const: 'source-map' }, before: nullable(sourceMapSchema), after: nullable(sourceMapSchema) }),
292
+ closed(
293
+ {
294
+ type: { const: 'update-semantics' },
295
+ collection: { const: 'emphasis' },
296
+ elementId: id,
297
+ before: nullable(enumOf('primary', 'secondary', 'muted')),
298
+ after: nullable(enumOf('primary', 'secondary', 'muted')),
299
+ index: { type: 'integer', minimum: 0, maximum: 1024 },
300
+ },
301
+ ['type', 'collection', 'elementId', 'before', 'after'],
302
+ ),
303
+ closed({
304
+ type: { const: 'update-semantics' },
305
+ collection: { const: 'document' },
306
+ before: closed({
307
+ title: str(),
308
+ summary: str(),
309
+ audience: enumOf('engineer', 'executive', 'mixed'),
310
+ accessibility: documentSchema.properties.accessibility,
311
+ }),
312
+ after: closed({
313
+ title: str(),
314
+ summary: str(),
315
+ audience: enumOf('engineer', 'executive', 'mixed'),
316
+ accessibility: documentSchema.properties.accessibility,
317
+ }),
318
+ }),
319
+ closed({
320
+ type: { const: 'update-semantics' },
321
+ collection: { const: 'source-map' },
322
+ before: nullable(sourceMapSchema),
323
+ after: nullable(sourceMapSchema),
324
+ }),
124
325
  ];
125
- const membershipState = closed({ groups: arr(closed({ id, members: ids }), 1024), lanes: arr(closed({ id, members: ids }), 256), laneOrder: ids });
126
- const geometryValue = closed({ bounds: nullable(bounds), route: nullable(route), label: nullable(labelPlacement), zIndex: index });
326
+ const membershipState = closed({
327
+ groups: arr(closed({ id, members: ids }), 1024),
328
+ lanes: arr(closed({ id, members: ids }), 256),
329
+ laneOrder: ids,
330
+ });
331
+ const geometryValue = closed({
332
+ bounds: nullable(bounds),
333
+ route: nullable(route),
334
+ label: nullable(labelPlacement),
335
+ zIndex: index,
336
+ });
127
337
  const appearanceValue = closed({ appearance, locks });
128
- const operation = { oneOf: [
129
- closed({ type: { const: 'insert-elements' }, elements: arr(semanticEntry, 10000, 1), presentation: arr(placement, 10000, 1), positions: arr(closed({ elementId: id, semanticIndex: index, presentationIndex: index }), 10000, 1) }, ['type', 'elements', 'presentation']),
130
- ...updateSchemas,
131
- closed({ type: { const: 'remove-elements' }, elements: arr(semanticEntry, 10000, 1), presentation: arr(placement, 10000, 1) }),
132
- closed({ type: { const: 'set-membership-order' }, before: membershipState, after: membershipState }),
133
- closed({ type: { const: 'set-geometry' }, changes: arr(closed({ elementId: id, before: geometryValue, after: geometryValue }), 10000, 1) }),
134
- closed({ type: { const: 'set-appearance-locks' }, changes: arr(closed({ elementId: id, before: appearanceValue, after: appearanceValue }), 10000, 1) }),
135
- ] };
338
+ const operation = {
339
+ oneOf: [
340
+ closed(
341
+ {
342
+ type: { const: 'insert-elements' },
343
+ elements: arr(semanticEntry, 10000, 1),
344
+ presentation: arr(placement, 10000, 1),
345
+ positions: arr(
346
+ closed({ elementId: id, semanticIndex: index, presentationIndex: index }),
347
+ 10000,
348
+ 1,
349
+ ),
350
+ },
351
+ ['type', 'elements', 'presentation'],
352
+ ),
353
+ ...updateSchemas,
354
+ closed({
355
+ type: { const: 'remove-elements' },
356
+ elements: arr(semanticEntry, 10000, 1),
357
+ presentation: arr(placement, 10000, 1),
358
+ }),
359
+ closed({
360
+ type: { const: 'set-membership-order' },
361
+ before: membershipState,
362
+ after: membershipState,
363
+ }),
364
+ closed({
365
+ type: { const: 'set-geometry' },
366
+ changes: arr(
367
+ closed({ elementId: id, before: geometryValue, after: geometryValue }),
368
+ 10000,
369
+ 1,
370
+ ),
371
+ }),
372
+ closed({
373
+ type: { const: 'set-appearance-locks' },
374
+ changes: arr(
375
+ closed({ elementId: id, before: appearanceValue, after: appearanceValue }),
376
+ 10000,
377
+ 1,
378
+ ),
379
+ }),
380
+ ],
381
+ };
136
382
  const transactionSchema = schema('diagram-edit-transaction', 'diagram-edit-transaction', {
137
- transactionId: id, diagramId: id, base: snapshot, operations: arr(operation, 256, 1), undoOf: nullable(id),
383
+ transactionId: id,
384
+ diagramId: id,
385
+ base: snapshot,
386
+ operations: arr(operation, 256, 1),
387
+ undoOf: nullable(id),
138
388
  });
139
389
  const proposalSchema = schema('diagram-change-proposal', 'diagram-change-proposal', {
140
- proposalId: id, diagramId: id, base: snapshot, transaction: transactionSchema,
141
- summary: str(4096, 1), author: closed({ kind: enumOf('human', 'agent'), id }),
390
+ proposalId: id,
391
+ diagramId: id,
392
+ base: snapshot,
393
+ transaction: transactionSchema,
394
+ summary: str(4096, 1),
395
+ author: closed({ kind: enumOf('human', 'agent'), id }),
142
396
  status: enumOf('proposed', 'accepted', 'rejected', 'stale'),
143
397
  });
144
398
  const publicationSchema = schema('diagram-publication-state', 'diagram-publication-state', {
145
- diagramId: id, draft: nullable(snapshot), published: nullable(snapshot),
399
+ diagramId: id,
400
+ draft: nullable(snapshot),
401
+ published: nullable(snapshot),
146
402
  audience: enumOf('private', 'company', 'public'),
147
403
  capabilitySemantics: { const: 'descriptive-only-requires-host-authorization' },
148
404
  });
149
405
  const manifestSchema = schema('diagram-manifest', 'diagram-manifest', {
150
- diagramId: id, basis: snapshot, bundle: closed({ path: relativePath, transportDigest: digest }),
406
+ diagramId: id,
407
+ basis: snapshot,
408
+ bundle: closed({ path: relativePath, transportDigest: digest }),
151
409
  renderer: closed({ id: token, version: str(64, 1) }),
152
- outputs: arr(closed({ path: relativePath, mediaType: enumOf('image/svg+xml', 'text/html', 'image/png'), transportDigest: digest, fidelity: fidelitySchema }), 32, 1),
410
+ outputs: arr(
411
+ closed({
412
+ path: relativePath,
413
+ mediaType: enumOf('image/svg+xml', 'text/html', 'image/png'),
414
+ transportDigest: digest,
415
+ fidelity: fidelitySchema,
416
+ }),
417
+ 32,
418
+ 1,
419
+ ),
153
420
  });
154
421
  // Export consumers record the concrete palette version independently of renderer code.
155
422
  manifestSchema.properties.theme = closed({ id: token, version: str(64, 1) });
156
- const mermaidConstruct = closed({ construct: token, import: fidelityValue, export: fidelityValue, semanticRoundTrip: fidelityValue, mapping: str(512, 1) });
423
+ const mermaidConstruct = closed({
424
+ construct: token,
425
+ import: fidelityValue,
426
+ export: fidelityValue,
427
+ semanticRoundTrip: fidelityValue,
428
+ mapping: str(512, 1),
429
+ });
157
430
  const capabilityProfile = closed({
158
- grammarId: enumOf('flowchart', 'process', 'swimlane', 'architecture'), authoring: { const: true },
159
- primitives: arr(enumOf('node', 'relation', 'group', 'lane', 'annotation', 'emphasis'), 6, 1, true),
160
- nodeKinds: arr(enumOf(...semanticKinds), 6, 1, true), relationKinds: arr(enumOf(...relationKinds), 5, 1, true),
431
+ grammarId: enumOf('flowchart', 'process', 'swimlane', 'architecture'),
432
+ authoring: { const: true },
433
+ primitives: arr(
434
+ enumOf('node', 'relation', 'group', 'lane', 'annotation', 'emphasis'),
435
+ 6,
436
+ 1,
437
+ true,
438
+ ),
439
+ nodeKinds: arr(enumOf(...semanticKinds), 6, 1, true),
440
+ relationKinds: arr(enumOf(...relationKinds), 5, 1, true),
161
441
  operations: arr(enumOf(...DIAGRAM_EDIT_OPERATION_CLASSES), 6, 6, true),
162
- mermaid: closed({ mode: { const: 'copy' }, certificationVersion: { const: 'flowchart-copy-v1' }, constructs: arr(mermaidConstruct, 32, 1), linkedSource: { const: false } }),
163
- });
164
- const capabilitiesSchema = schema('diagram-authoring-capabilities', 'diagram-authoring-capabilities', {
165
- version: { const: '1.0.0' }, liveCollaboration: { const: false },
166
- profiles: arr(capabilityProfile, 4, 4),
167
- unsupportedGrammars: arr(token, 128, 0, true),
442
+ mermaid: closed({
443
+ mode: { const: 'copy' },
444
+ certificationVersion: { const: 'flowchart-copy-v1' },
445
+ constructs: arr(mermaidConstruct, 32, 1),
446
+ linkedSource: { const: false },
447
+ }),
168
448
  });
449
+ const capabilitiesSchema = schema(
450
+ 'diagram-authoring-capabilities',
451
+ 'diagram-authoring-capabilities',
452
+ {
453
+ version: { const: '1.0.0' },
454
+ liveCollaboration: { const: false },
455
+ profiles: arr(capabilityProfile, 4, 4),
456
+ unsupportedGrammars: arr(token, 128, 0, true),
457
+ },
458
+ );
169
459
  const schemas = {
170
- 'diagram-document': documentSchema, 'diagram-presentation': presentationSchema,
171
- 'diagram-authoring-bundle': bundleSchema, 'diagram-edit-transaction': transactionSchema,
172
- 'diagram-source-map': sourceMapSchema, 'diagram-fidelity-report': fidelitySchema,
173
- 'diagram-manifest': manifestSchema, 'diagram-change-proposal': proposalSchema,
174
- 'diagram-publication-state': publicationSchema, 'diagram-authoring-capabilities': capabilitiesSchema,
460
+ 'diagram-document': documentSchema,
461
+ 'diagram-presentation': presentationSchema,
462
+ 'diagram-authoring-bundle': bundleSchema,
463
+ 'diagram-edit-transaction': transactionSchema,
464
+ 'diagram-source-map': sourceMapSchema,
465
+ 'diagram-fidelity-report': fidelitySchema,
466
+ 'diagram-manifest': manifestSchema,
467
+ 'diagram-change-proposal': proposalSchema,
468
+ 'diagram-publication-state': publicationSchema,
469
+ 'diagram-authoring-capabilities': capabilitiesSchema,
175
470
  };
471
+ /** @type {typeof import('./diagram-authoring-contracts.d.mts').DIAGRAM_AUTHORING_SCHEMAS} */
176
472
  export const DIAGRAM_AUTHORING_SCHEMAS = deepFreeze(schemas);
177
- export const DIAGRAM_AUTHORING_CONTRACT_FILES = deepFreeze(Object.fromEntries(Object.keys(schemas).map((name) => [name, `${name}.schema.json`])));
473
+ /** @type {typeof import('./diagram-authoring-contracts.d.mts').DIAGRAM_AUTHORING_CONTRACT_FILES} */
474
+ export const DIAGRAM_AUTHORING_CONTRACT_FILES = deepFreeze(
475
+ /** @type {Record<DiagramAuthoringContractKind, string>} */ (
476
+ Object.fromEntries(Object.keys(schemas).map((name) => [name, `${name}.schema.json`]))
477
+ ),
478
+ );
178
479
  const mermaidConstructs = [
179
- ['flowchart-direction', 'lossless', 'lossless', 'lossless', 'flowchart TB/TD/LR/RL/BT maps to presentation layout direction'],
180
- ['explicit-node-id', 'lossless', 'lossless', 'lossless', 'Explicit source ID maps through source-map to stable semantic node ID; labels never establish identity'],
181
- ['plain-node-label', 'lossless', 'lossless', 'lossless', 'Escaped plain text maps to node label; HTML is inert text and is not executed'],
182
- ['rectangle-node', 'lossless', 'lossless', 'lossless', 'node.kind process and presentation shape rectangle'],
183
- ['rounded-node', 'lossless', 'lossless', 'lossless', 'node.kind process and presentation shape rounded-rectangle'],
184
- ['decision-node', 'lossless', 'lossless', 'lossless', 'node.kind decision and presentation shape diamond'],
185
- ['cylinder-node', 'lossless', 'lossless', 'lossless', 'node.kind data-store and presentation shape cylinder'],
186
- ['directed-edge', 'lossless', 'lossless', 'lossless', 'relation.kind flow and direction forward; source and target IDs are semantic endpoints'],
187
- ['bidirectional-edge', 'lossless', 'lossless', 'lossless', 'relation.kind flow and direction both'],
188
- ['undirected-edge', 'lossless', 'lossless', 'lossless', 'relation.kind association and direction none'],
189
- ['plain-edge-label', 'lossless', 'lossless', 'lossless', 'Escaped plain text maps to relation label'],
190
- ['subgraph', 'lossless', 'lossless', 'lossless', 'Explicit subgraph ID maps to one semantic group in an acyclic single-parent forest'],
191
- ['lane-semantics', 'unsupported', 'partial', 'partial', 'Mermaid subgraphs do not encode lane identity or explicit lane order'],
192
- ['manual-geometry', 'unsupported', 'partial', 'partial', 'Standard Mermaid does not preserve coordinates, routes, attachments, stacking or locks'],
193
- ['styles-and-directives', 'unsupported', 'unsupported', 'unsupported', 'CSS, classDef, init directives, links, callbacks and HTML labels are outside this certified subset'],
194
- ['unsupported-construct', 'unsupported', 'unsupported', 'unsupported', 'Unrecognized syntax is retained as original source with explicit loss diagnostics'],
195
- ].map(([construct, input, output, roundTrip, mapping]) => ({ construct, import: input, export: output, semanticRoundTrip: roundTrip, mapping }));
480
+ [
481
+ 'flowchart-direction',
482
+ 'lossless',
483
+ 'lossless',
484
+ 'lossless',
485
+ 'flowchart TB/TD/LR/RL/BT maps to presentation layout direction',
486
+ ],
487
+ [
488
+ 'explicit-node-id',
489
+ 'lossless',
490
+ 'lossless',
491
+ 'lossless',
492
+ 'Explicit source ID maps through source-map to stable semantic node ID; labels never establish identity',
493
+ ],
494
+ [
495
+ 'plain-node-label',
496
+ 'lossless',
497
+ 'lossless',
498
+ 'lossless',
499
+ 'Escaped plain text maps to node label; HTML is inert text and is not executed',
500
+ ],
501
+ [
502
+ 'rectangle-node',
503
+ 'lossless',
504
+ 'lossless',
505
+ 'lossless',
506
+ 'node.kind process and presentation shape rectangle',
507
+ ],
508
+ [
509
+ 'rounded-node',
510
+ 'lossless',
511
+ 'lossless',
512
+ 'lossless',
513
+ 'node.kind process and presentation shape rounded-rectangle',
514
+ ],
515
+ [
516
+ 'decision-node',
517
+ 'lossless',
518
+ 'lossless',
519
+ 'lossless',
520
+ 'node.kind decision and presentation shape diamond',
521
+ ],
522
+ [
523
+ 'cylinder-node',
524
+ 'lossless',
525
+ 'lossless',
526
+ 'lossless',
527
+ 'node.kind data-store and presentation shape cylinder',
528
+ ],
529
+ [
530
+ 'directed-edge',
531
+ 'lossless',
532
+ 'lossless',
533
+ 'lossless',
534
+ 'relation.kind flow and direction forward; source and target IDs are semantic endpoints',
535
+ ],
536
+ [
537
+ 'bidirectional-edge',
538
+ 'lossless',
539
+ 'lossless',
540
+ 'lossless',
541
+ 'relation.kind flow and direction both',
542
+ ],
543
+ [
544
+ 'undirected-edge',
545
+ 'lossless',
546
+ 'lossless',
547
+ 'lossless',
548
+ 'relation.kind association and direction none',
549
+ ],
550
+ [
551
+ 'plain-edge-label',
552
+ 'lossless',
553
+ 'lossless',
554
+ 'lossless',
555
+ 'Escaped plain text maps to relation label',
556
+ ],
557
+ [
558
+ 'subgraph',
559
+ 'lossless',
560
+ 'lossless',
561
+ 'lossless',
562
+ 'Explicit subgraph ID maps to one semantic group in an acyclic single-parent forest',
563
+ ],
564
+ [
565
+ 'lane-semantics',
566
+ 'unsupported',
567
+ 'partial',
568
+ 'partial',
569
+ 'Mermaid subgraphs do not encode lane identity or explicit lane order',
570
+ ],
571
+ [
572
+ 'manual-geometry',
573
+ 'unsupported',
574
+ 'partial',
575
+ 'partial',
576
+ 'Standard Mermaid does not preserve coordinates, routes, attachments, stacking or locks',
577
+ ],
578
+ [
579
+ 'styles-and-directives',
580
+ 'unsupported',
581
+ 'unsupported',
582
+ 'unsupported',
583
+ 'CSS, classDef, init directives, links, callbacks and HTML labels are outside this certified subset',
584
+ ],
585
+ [
586
+ 'unsupported-construct',
587
+ 'unsupported',
588
+ 'unsupported',
589
+ 'unsupported',
590
+ 'Unrecognized syntax is retained as original source with explicit loss diagnostics',
591
+ ],
592
+ ].map(([construct, input, output, roundTrip, mapping]) => ({
593
+ construct,
594
+ import: input,
595
+ export: output,
596
+ semanticRoundTrip: roundTrip,
597
+ mapping,
598
+ }));
196
599
  const profileIds = ['flowchart', 'process', 'swimlane', 'architecture'];
600
+ /** @type {typeof import('./diagram-authoring-contracts.d.mts').DIAGRAM_AUTHORING_CAPABILITIES} */
197
601
  export const DIAGRAM_AUTHORING_CAPABILITIES = deepFreeze({
198
- kind: 'diagram-authoring-capabilities', schemaVersion: '1.0.0', protocolVersion: '1.13.0',
199
- version: '1.0.0', liveCollaboration: false,
200
- profiles: profileIds.map((grammarId) => ({
201
- grammarId, authoring: true, primitives: ['node', 'relation', 'group', ...(grammarId === 'process' || grammarId === 'swimlane' ? ['lane'] : []), 'annotation', 'emphasis'],
202
- nodeKinds: [...semanticKinds], relationKinds: [...relationKinds], operations: [...DIAGRAM_EDIT_OPERATION_CLASSES],
203
- mermaid: { mode: 'copy', certificationVersion: 'flowchart-copy-v1', constructs: mermaidConstructs.map((entry) => ({ ...entry })), linkedSource: false },
204
- })),
205
- unsupportedGrammars: DIAGRAM_REGISTRIES['diagram-grammars.json'].grammars.map((entry) => entry.grammarId).filter((value) => !profileIds.includes(value)),
602
+ kind: 'diagram-authoring-capabilities',
603
+ schemaVersion: '1.0.0',
604
+ protocolVersion: '1.13.0',
605
+ version: '1.0.0',
606
+ liveCollaboration: false,
607
+ profiles: /** @type {DiagramAuthoringCapability[]} */ (
608
+ profileIds.map((grammarId) => ({
609
+ grammarId,
610
+ authoring: true,
611
+ primitives: [
612
+ 'node',
613
+ 'relation',
614
+ 'group',
615
+ ...(grammarId === 'process' || grammarId === 'swimlane' ? ['lane'] : []),
616
+ 'annotation',
617
+ 'emphasis',
618
+ ],
619
+ nodeKinds: [...semanticKinds],
620
+ relationKinds: [...relationKinds],
621
+ operations: [...DIAGRAM_EDIT_OPERATION_CLASSES],
622
+ mermaid: {
623
+ mode: 'copy',
624
+ certificationVersion: 'flowchart-copy-v1',
625
+ constructs: mermaidConstructs.map((entry) => ({ ...entry })),
626
+ linkedSource: false,
627
+ },
628
+ }))
629
+ ),
630
+ unsupportedGrammars: DIAGRAM_REGISTRIES['diagram-grammars.json'].grammars
631
+ .map((entry) => entry.grammarId)
632
+ .filter((value) => !profileIds.includes(value)),
206
633
  });
634
+ /** @type {typeof import('./diagram-authoring-contracts.d.mts').getDiagramAuthoringCapability} */
207
635
  export function getDiagramAuthoringCapability(grammarId) {
208
- return DIAGRAM_AUTHORING_CAPABILITIES.profiles.find((entry) => entry.grammarId === grammarId) ?? null;
636
+ return (
637
+ DIAGRAM_AUTHORING_CAPABILITIES.profiles.find((entry) => entry.grammarId === grammarId) ?? null
638
+ );
209
639
  }
210
640
 
211
641
  const error = (path, rule, detail) => ({ path, rule, detail });
@@ -218,41 +648,90 @@ function inspectData(value) {
218
648
  function visit(current, path, depth) {
219
649
  if (issues.length) return;
220
650
  if (++count > DIAGRAM_AUTHORING_LIMITS.values || depth > DIAGRAM_AUTHORING_LIMITS.depth) {
221
- issues.push(error(path, 'resource-limit', 'Data exceeds the portable value or nesting limit.')); return;
651
+ issues.push(
652
+ error(path, 'resource-limit', 'Data exceeds the portable value or nesting limit.'),
653
+ );
654
+ return;
222
655
  }
223
656
  if (typeof current === 'string') {
224
657
  textSize += current.length;
225
- if (textSize > DIAGRAM_AUTHORING_LIMITS.textCodeUnits) issues.push(error(path, 'resource-limit', 'Data exceeds the portable text limit.'));
226
- else if (/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(current)) issues.push(error(path, 'unicode', 'Unpaired Unicode surrogate is not portable UTF-8.'));
658
+ if (textSize > DIAGRAM_AUTHORING_LIMITS.textCodeUnits)
659
+ issues.push(error(path, 'resource-limit', 'Data exceeds the portable text limit.'));
660
+ else if (
661
+ /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(current)
662
+ )
663
+ issues.push(error(path, 'unicode', 'Unpaired Unicode surrogate is not portable UTF-8.'));
227
664
  return;
228
665
  }
229
666
  if (current === null || typeof current === 'boolean') return;
230
- if (typeof current === 'number') { if (!Number.isFinite(current)) issues.push(error(path, 'finite-number', 'Numbers must be finite.')); return; }
231
- if (typeof current !== 'object') { issues.push(error(path, 'plain-data', 'Only JSON data is accepted.')); return; }
667
+ if (typeof current === 'number') {
668
+ if (!Number.isFinite(current))
669
+ issues.push(error(path, 'finite-number', 'Numbers must be finite.'));
670
+ return;
671
+ }
672
+ if (typeof current !== 'object') {
673
+ issues.push(error(path, 'plain-data', 'Only JSON data is accepted.'));
674
+ return;
675
+ }
232
676
  const proto = Object.getPrototypeOf(current);
233
- if (Array.isArray(current) ? proto !== Array.prototype : proto !== Object.prototype && proto !== null) {
234
- issues.push(error(path, 'plain-data', 'Custom prototypes are not accepted.')); return;
677
+ if (
678
+ Array.isArray(current)
679
+ ? proto !== Array.prototype
680
+ : proto !== Object.prototype && proto !== null
681
+ ) {
682
+ issues.push(error(path, 'plain-data', 'Custom prototypes are not accepted.'));
683
+ return;
684
+ }
685
+ if (ancestors.has(current)) {
686
+ issues.push(error(path, 'cycle', 'Cyclic data is not accepted.'));
687
+ return;
235
688
  }
236
- if (ancestors.has(current)) { issues.push(error(path, 'cycle', 'Cyclic data is not accepted.')); return; }
237
689
  ancestors.add(current);
238
690
  const descriptors = Object.getOwnPropertyDescriptors(current);
239
691
  for (const key of Reflect.ownKeys(descriptors)) {
240
- if (typeof key !== 'string' || key === '__proto__' || key === 'constructor' || key === 'prototype') {
241
- issues.push(error(path, 'unsafe-key', 'Unsafe or symbolic object key.')); break;
692
+ if (
693
+ typeof key !== 'string' ||
694
+ key === '__proto__' ||
695
+ key === 'constructor' ||
696
+ key === 'prototype'
697
+ ) {
698
+ issues.push(error(path, 'unsafe-key', 'Unsafe or symbolic object key.'));
699
+ break;
242
700
  }
243
701
  const descriptor = descriptors[key];
244
- if (descriptor.get || descriptor.set || !('value' in descriptor)) { issues.push(error(path, 'accessor', 'Accessors are not accepted.')); break; }
702
+ if (descriptor.get || descriptor.set || !('value' in descriptor)) {
703
+ issues.push(error(path, 'accessor', 'Accessors are not accepted.'));
704
+ break;
705
+ }
245
706
  if (Array.isArray(current) && key === 'length') continue;
246
- if (!descriptor.enumerable || (Array.isArray(current) && (!/^(0|[1-9][0-9]*)$/u.test(key) || Number(key) >= current.length))) {
247
- issues.push(error(path, 'plain-data', 'Non-JSON properties are not accepted.')); break;
707
+ if (
708
+ !descriptor.enumerable ||
709
+ (Array.isArray(current) &&
710
+ (!/^(0|[1-9][0-9]*)$/u.test(key) || Number(key) >= current.length))
711
+ ) {
712
+ issues.push(error(path, 'plain-data', 'Non-JSON properties are not accepted.'));
713
+ break;
248
714
  }
249
- visit(descriptor.value, Array.isArray(current) ? `${path}[${key}]` : `${path}.${key}`, depth + 1);
715
+ visit(
716
+ descriptor.value,
717
+ Array.isArray(current) ? `${path}[${key}]` : `${path}.${key}`,
718
+ depth + 1,
719
+ );
250
720
  if (issues.length) break;
251
721
  }
252
- if (!issues.length && Array.isArray(current) && Object.keys(descriptors).length !== current.length + 1) issues.push(error(path, 'sparse-array', 'Sparse arrays are not accepted.'));
722
+ if (
723
+ !issues.length &&
724
+ Array.isArray(current) &&
725
+ Object.keys(descriptors).length !== current.length + 1
726
+ )
727
+ issues.push(error(path, 'sparse-array', 'Sparse arrays are not accepted.'));
253
728
  ancestors.delete(current);
254
729
  }
255
- try { visit(value, '$', 0); } catch { issues.push(error('$', 'plain-data', 'Data cannot be inspected safely.')); }
730
+ try {
731
+ visit(value, '$', 0);
732
+ } catch {
733
+ issues.push(error('$', 'plain-data', 'Data cannot be inspected safely.'));
734
+ }
256
735
  return issues;
257
736
  }
258
737
  function assertData(value) {
@@ -261,19 +740,37 @@ function assertData(value) {
261
740
  }
262
741
  function digestExcluding(value, field) {
263
742
  assertData(value);
264
- if (!value || typeof value !== 'object' || Array.isArray(value)) throw new TypeError('Digest input must be an object.');
743
+ if (!value || typeof value !== 'object' || Array.isArray(value))
744
+ throw new TypeError('Digest input must be an object.');
265
745
  const input = { ...value };
266
746
  delete input[field];
267
747
  return sha256Jcs(input);
268
748
  }
749
+ /** @type {typeof import('./diagram-authoring-contracts.d.mts').diagramDocumentDigest} */
269
750
  export const diagramDocumentDigest = (value) => digestExcluding(value, 'documentDigest');
751
+ /** @type {typeof import('./diagram-authoring-contracts.d.mts').diagramPresentationDigest} */
270
752
  export const diagramPresentationDigest = (value) => digestExcluding(value, 'presentationDigest');
753
+ /** @type {typeof import('./diagram-authoring-contracts.d.mts').diagramAuthoringBundleDigest} */
271
754
  export const diagramAuthoringBundleDigest = (value) => digestExcluding(value, 'bundleDigest');
272
755
  const same = (a, b) => canonicalizeJson(a) === canonicalizeJson(b);
273
756
  const sourceDigest = (text) => `sha256:${sha256Hex(text)}`;
274
- const semanticNames = ['nodes', 'relations', 'groups', 'lanes', 'events', 'series', 'axes', 'sets', 'annotations'];
757
+ const semanticNames = [
758
+ 'nodes',
759
+ 'relations',
760
+ 'groups',
761
+ 'lanes',
762
+ 'events',
763
+ 'series',
764
+ 'axes',
765
+ 'sets',
766
+ 'annotations',
767
+ ];
275
768
  const allElements = (doc) => semanticNames.flatMap((name) => doc[name]);
276
- const expectedSnapshot = (bundle) => ({ bundleDigest: bundle.bundleDigest, semanticDigest: bundle.document.documentDigest, presentationDigest: bundle.presentation.presentationDigest });
769
+ const expectedSnapshot = (bundle) => ({
770
+ bundleDigest: bundle.bundleDigest,
771
+ semanticDigest: bundle.document.documentDigest,
772
+ presentationDigest: bundle.presentation.presentationDigest,
773
+ });
277
774
  function hasContainmentCycle(parents) {
278
775
  const complete = new Set();
279
776
  for (const member of parents.keys()) {
@@ -281,7 +778,8 @@ function hasContainmentCycle(parents) {
281
778
  let current = member;
282
779
  while (current && !complete.has(current)) {
283
780
  if (visited.has(current)) return true;
284
- visited.add(current); current = parents.get(current);
781
+ visited.add(current);
782
+ current = parents.get(current);
285
783
  }
286
784
  for (const item of visited) complete.add(item);
287
785
  }
@@ -291,36 +789,105 @@ function hasContainmentCycle(parents) {
291
789
  function documentIssues(doc, path, issues) {
292
790
  const entries = allElements(doc);
293
791
  const byId = new Map();
294
- if (entries.length + doc.emphasis.length > 10000) issues.push(error(path, 'resource-limit', 'Too many semantic primitive entries.'));
295
- for (const collection of semanticNames) for (let i = 0; i < doc[collection].length; i += 1) {
296
- const entry = doc[collection][i];
297
- if (byId.has(entry.id)) issues.push(error(`${path}.${collection}[${i}].id`, 'duplicate-id', 'Semantic element IDs must be globally unique.'));
298
- byId.set(entry.id, { ...entry, collection });
299
- }
792
+ if (entries.length + doc.emphasis.length > 10000)
793
+ issues.push(error(path, 'resource-limit', 'Too many semantic primitive entries.'));
794
+ for (const collection of semanticNames)
795
+ for (let i = 0; i < doc[collection].length; i += 1) {
796
+ const entry = doc[collection][i];
797
+ if (byId.has(entry.id))
798
+ issues.push(
799
+ error(
800
+ `${path}.${collection}[${i}].id`,
801
+ 'duplicate-id',
802
+ 'Semantic element IDs must be globally unique.',
803
+ ),
804
+ );
805
+ byId.set(entry.id, { ...entry, collection });
806
+ }
300
807
  const capability = getDiagramAuthoringCapability(doc.grammar.id);
301
- if (!capability.primitives.includes('lane') && doc.lanes.length) issues.push(error(`${path}.lanes`, 'profile-primitive', 'This authoring profile does not support lanes.'));
302
- doc.relations.forEach((edge, i) => ['from', 'to'].forEach((key) => {
303
- if (byId.get(edge[key])?.collection !== 'nodes') issues.push(error(`${path}.relations[${i}].${key}`, 'endpoint', 'Relationship endpoints must reference semantic nodes.'));
304
- }));
808
+ if (capability && !capability.primitives.includes('lane') && doc.lanes.length)
809
+ issues.push(
810
+ error(`${path}.lanes`, 'profile-primitive', 'This authoring profile does not support lanes.'),
811
+ );
812
+ doc.relations.forEach((edge, i) =>
813
+ ['from', 'to'].forEach((key) => {
814
+ if (byId.get(edge[key])?.collection !== 'nodes')
815
+ issues.push(
816
+ error(
817
+ `${path}.relations[${i}].${key}`,
818
+ 'endpoint',
819
+ 'Relationship endpoints must reference semantic nodes.',
820
+ ),
821
+ );
822
+ }),
823
+ );
305
824
  const parent = new Map();
306
- for (const collection of ['groups', 'lanes']) doc[collection].forEach((group, i) => group.members.forEach((member, j) => {
307
- const child = byId.get(member);
308
- const memberPath = `${path}.${collection}[${i}].members[${j}]`;
309
- if (!child || !['nodes', 'groups', 'lanes', 'annotations'].includes(child.collection)) issues.push(error(memberPath, 'containment-reference', 'Container members must reference a placeable semantic element.'));
310
- if (parent.has(member)) issues.push(error(memberPath, 'multiple-parents', 'An element has more than one immediate container.'));
311
- parent.set(member, group.id);
312
- }));
313
- if (hasContainmentCycle(parent)) issues.push(error(path, 'containment-cycle', 'Container membership must form a forest.'));
314
- if (!same([...doc.laneOrder].sort(), doc.lanes.map((item) => item.id).sort())) issues.push(error(`${path}.laneOrder`, 'lane-order', 'Every lane must occur exactly once in laneOrder.'));
315
- doc.annotations.forEach((entry, i) => { if (entry.targetId !== null && !byId.has(entry.targetId)) issues.push(error(`${path}.annotations[${i}].targetId`, 'reference', 'Annotation target is missing.')); });
825
+ for (const collection of ['groups', 'lanes'])
826
+ doc[collection].forEach((group, i) =>
827
+ group.members.forEach((member, j) => {
828
+ const child = byId.get(member);
829
+ const memberPath = `${path}.${collection}[${i}].members[${j}]`;
830
+ if (!child || !['nodes', 'groups', 'lanes', 'annotations'].includes(child.collection))
831
+ issues.push(
832
+ error(
833
+ memberPath,
834
+ 'containment-reference',
835
+ 'Container members must reference a placeable semantic element.',
836
+ ),
837
+ );
838
+ if (parent.has(member))
839
+ issues.push(
840
+ error(
841
+ memberPath,
842
+ 'multiple-parents',
843
+ 'An element has more than one immediate container.',
844
+ ),
845
+ );
846
+ parent.set(member, group.id);
847
+ }),
848
+ );
849
+ if (hasContainmentCycle(parent))
850
+ issues.push(error(path, 'containment-cycle', 'Container membership must form a forest.'));
851
+ if (!same([...doc.laneOrder].sort(), doc.lanes.map((item) => item.id).sort()))
852
+ issues.push(
853
+ error(`${path}.laneOrder`, 'lane-order', 'Every lane must occur exactly once in laneOrder.'),
854
+ );
855
+ doc.annotations.forEach((entry, i) => {
856
+ if (entry.targetId !== null && !byId.has(entry.targetId))
857
+ issues.push(
858
+ error(`${path}.annotations[${i}].targetId`, 'reference', 'Annotation target is missing.'),
859
+ );
860
+ });
316
861
  const emphasisIds = new Set();
317
862
  doc.emphasis.forEach((entry, i) => {
318
- if (!byId.has(entry.targetId)) issues.push(error(`${path}.emphasis[${i}].targetId`, 'reference', 'Emphasis target is missing.'));
319
- if (emphasisIds.has(entry.targetId)) issues.push(error(`${path}.emphasis[${i}].targetId`, 'duplicate-id', 'Only one emphasis entry is allowed per target.'));
863
+ if (!byId.has(entry.targetId))
864
+ issues.push(
865
+ error(`${path}.emphasis[${i}].targetId`, 'reference', 'Emphasis target is missing.'),
866
+ );
867
+ if (emphasisIds.has(entry.targetId))
868
+ issues.push(
869
+ error(
870
+ `${path}.emphasis[${i}].targetId`,
871
+ 'duplicate-id',
872
+ 'Only one emphasis entry is allowed per target.',
873
+ ),
874
+ );
320
875
  emphasisIds.add(entry.targetId);
321
876
  });
322
- doc.accessibility.readingOrder.forEach((entry, i) => { if (!byId.has(entry)) issues.push(error(`${path}.accessibility.readingOrder[${i}]`, 'reference', 'Reading order target is missing.')); });
323
- if (doc.documentDigest !== diagramDocumentDigest(doc)) issues.push(error(`${path}.documentDigest`, 'digest', 'Semantic content digest does not match.'));
877
+ doc.accessibility.readingOrder.forEach((entry, i) => {
878
+ if (!byId.has(entry))
879
+ issues.push(
880
+ error(
881
+ `${path}.accessibility.readingOrder[${i}]`,
882
+ 'reference',
883
+ 'Reading order target is missing.',
884
+ ),
885
+ );
886
+ });
887
+ if (doc.documentDigest !== diagramDocumentDigest(doc))
888
+ issues.push(
889
+ error(`${path}.documentDigest`, 'digest', 'Semantic content digest does not match.'),
890
+ );
324
891
  }
325
892
  function presentationIssues(value, doc, path, issues) {
326
893
  const idsSeen = new Set();
@@ -328,36 +895,109 @@ function presentationIssues(value, doc, path, issues) {
328
895
  const nodes = doc ? new Set(doc.nodes.map((entry) => entry.id)) : null;
329
896
  const relations = doc ? new Map(doc.relations.map((entry) => [entry.id, entry])) : null;
330
897
  const containers = doc ? new Set([...doc.groups, ...doc.lanes].map((entry) => entry.id)) : null;
331
- if (doc && (value.diagramId !== doc.diagramId || value.semanticDigest !== doc.documentDigest)) issues.push(error(path, 'basis', 'Presentation does not reference the exact semantic document.'));
898
+ if (doc && (value.diagramId !== doc.diagramId || value.semanticDigest !== doc.documentDigest))
899
+ issues.push(
900
+ error(path, 'basis', 'Presentation does not reference the exact semantic document.'),
901
+ );
332
902
  value.elements.forEach((entry, i) => {
333
903
  const location = `${path}.elements[${i}]`;
334
904
  geometryIssues(entry, location, issues);
335
- if (idsSeen.has(entry.elementId)) issues.push(error(`${location}.elementId`, 'duplicate-id', 'Presentation element IDs must be unique.'));
905
+ if (idsSeen.has(entry.elementId))
906
+ issues.push(
907
+ error(`${location}.elementId`, 'duplicate-id', 'Presentation element IDs must be unique.'),
908
+ );
336
909
  idsSeen.add(entry.elementId);
337
- if (byId && !byId.has(entry.elementId)) issues.push(error(`${location}.elementId`, 'reference', 'Presentation element is not in the semantic document.'));
338
- if (entry.route !== null && entry.bounds !== null) issues.push(error(location, 'geometry-kind', 'A connector has a route; a shape has bounds.'));
339
- if (entry.route === null && entry.bounds === null) issues.push(error(location, 'geometry-kind', 'A placed element requires bounds or a route.'));
340
- if (entry.route?.mode === 'manual' && entry.route.points.length < 2) issues.push(error(`${location}.route.points`, 'manual-route', 'A manual route requires at least two global points.'));
341
- if (entry.route?.mode === 'automatic' && entry.route.points.length !== 0) issues.push(error(`${location}.route.points`, 'automatic-route', 'Automatic route geometry is derived and must not carry authored points.'));
342
- if (entry.route && entry.appearance.shape !== 'connector') issues.push(error(`${location}.appearance.shape`, 'shape-kind', 'Routes must use the connector shape.'));
343
- if (entry.bounds && entry.appearance.shape === 'connector') issues.push(error(`${location}.appearance.shape`, 'shape-kind', 'Bounded elements cannot use the connector shape.'));
344
- if (relations?.has(entry.elementId) && !entry.route) issues.push(error(location, 'geometry-kind', 'Semantic relations require route geometry.'));
345
- if (doc && !relations.has(entry.elementId) && !entry.bounds) issues.push(error(location, 'geometry-kind', 'Non-relation elements require bounds.'));
346
- if (containers?.has(entry.elementId) && entry.appearance.shape !== 'container') issues.push(error(`${location}.appearance.shape`, 'shape-kind', 'Containers require the container visual shape.'));
347
- if (nodes?.has(entry.elementId) && ['container', 'text'].includes(entry.appearance.shape)) issues.push(error(`${location}.appearance.shape`, 'shape-kind', 'Nodes require a node visual shape.'));
910
+ if (byId && !byId.has(entry.elementId))
911
+ issues.push(
912
+ error(
913
+ `${location}.elementId`,
914
+ 'reference',
915
+ 'Presentation element is not in the semantic document.',
916
+ ),
917
+ );
918
+ if (entry.route !== null && entry.bounds !== null)
919
+ issues.push(error(location, 'geometry-kind', 'A connector has a route; a shape has bounds.'));
920
+ if (entry.route === null && entry.bounds === null)
921
+ issues.push(error(location, 'geometry-kind', 'A placed element requires bounds or a route.'));
922
+ if (entry.route?.mode === 'manual' && entry.route.points.length < 2)
923
+ issues.push(
924
+ error(
925
+ `${location}.route.points`,
926
+ 'manual-route',
927
+ 'A manual route requires at least two global points.',
928
+ ),
929
+ );
930
+ if (entry.route?.mode === 'automatic' && entry.route.points.length !== 0)
931
+ issues.push(
932
+ error(
933
+ `${location}.route.points`,
934
+ 'automatic-route',
935
+ 'Automatic route geometry is derived and must not carry authored points.',
936
+ ),
937
+ );
938
+ if (entry.route && entry.appearance.shape !== 'connector')
939
+ issues.push(
940
+ error(`${location}.appearance.shape`, 'shape-kind', 'Routes must use the connector shape.'),
941
+ );
942
+ if (entry.bounds && entry.appearance.shape === 'connector')
943
+ issues.push(
944
+ error(
945
+ `${location}.appearance.shape`,
946
+ 'shape-kind',
947
+ 'Bounded elements cannot use the connector shape.',
948
+ ),
949
+ );
950
+ if (relations?.has(entry.elementId) && !entry.route)
951
+ issues.push(error(location, 'geometry-kind', 'Semantic relations require route geometry.'));
952
+ if (relations && !relations.has(entry.elementId) && !entry.bounds)
953
+ issues.push(error(location, 'geometry-kind', 'Non-relation elements require bounds.'));
954
+ if (containers?.has(entry.elementId) && entry.appearance.shape !== 'container')
955
+ issues.push(
956
+ error(
957
+ `${location}.appearance.shape`,
958
+ 'shape-kind',
959
+ 'Containers require the container visual shape.',
960
+ ),
961
+ );
962
+ if (nodes?.has(entry.elementId) && ['container', 'text'].includes(entry.appearance.shape))
963
+ issues.push(
964
+ error(`${location}.appearance.shape`, 'shape-kind', 'Nodes require a node visual shape.'),
965
+ );
348
966
  });
349
- if (byId && (idsSeen.size !== byId.size || [...byId.keys()].some((key) => !idsSeen.has(key)))) issues.push(error(`${path}.elements`, 'presentation-coverage', 'Every semantic element must have exactly one placement.'));
350
- if (value.presentationDigest !== diagramPresentationDigest(value)) issues.push(error(`${path}.presentationDigest`, 'digest', 'Presentation content digest does not match.'));
967
+ if (byId && (idsSeen.size !== byId.size || [...byId.keys()].some((key) => !idsSeen.has(key))))
968
+ issues.push(
969
+ error(
970
+ `${path}.elements`,
971
+ 'presentation-coverage',
972
+ 'Every semantic element must have exactly one placement.',
973
+ ),
974
+ );
975
+ if (value.presentationDigest !== diagramPresentationDigest(value))
976
+ issues.push(
977
+ error(`${path}.presentationDigest`, 'digest', 'Presentation content digest does not match.'),
978
+ );
351
979
  }
352
980
  function sourceMapIssues(value, doc, text, path, issues) {
353
- if (doc && (value.diagramId !== doc.diagramId || value.semanticDigest !== doc.documentDigest)) issues.push(error(path, 'basis', 'Source map does not reference the exact semantic document.'));
981
+ if (doc && (value.diagramId !== doc.diagramId || value.semanticDigest !== doc.documentDigest))
982
+ issues.push(error(path, 'basis', 'Source map does not reference the exact semantic document.'));
354
983
  const elementIds = doc ? new Set(allElements(doc).map((entry) => entry.id)) : null;
355
984
  const sourceIds = new Set();
356
985
  let boundaries = null;
357
986
  if (text !== undefined) {
358
987
  const byteLength = new TextEncoder().encode(text).length;
359
- if (value.sourceDigest !== sourceDigest(text) || value.sourceByteLength !== byteLength) issues.push(error(path, 'source-digest', 'Source digest and byte length must match exact UTF-8 source text.'));
360
- const requested = new Set(value.entries.flatMap((entry) => entry.range ? [entry.range.startByte, entry.range.endByte] : []));
988
+ if (value.sourceDigest !== sourceDigest(text) || value.sourceByteLength !== byteLength)
989
+ issues.push(
990
+ error(
991
+ path,
992
+ 'source-digest',
993
+ 'Source digest and byte length must match exact UTF-8 source text.',
994
+ ),
995
+ );
996
+ const requested = new Set(
997
+ value.entries.flatMap((entry) =>
998
+ entry.range ? [entry.range.startByte, entry.range.endByte] : [],
999
+ ),
1000
+ );
361
1001
  boundaries = new Set([0]);
362
1002
  let cursor = 0;
363
1003
  for (const character of text) {
@@ -368,60 +1008,197 @@ function sourceMapIssues(value, doc, text, path, issues) {
368
1008
  }
369
1009
  value.entries.forEach((entry, i) => {
370
1010
  const location = `${path}.entries[${i}]`;
371
- if (entry.sourceId !== null && sourceIds.has(entry.sourceId)) issues.push(error(`${location}.sourceId`, 'ambiguous-source-id', 'Duplicate explicit source IDs must be represented by one ambiguous entry.'));
1011
+ if (entry.sourceId !== null && sourceIds.has(entry.sourceId))
1012
+ issues.push(
1013
+ error(
1014
+ `${location}.sourceId`,
1015
+ 'ambiguous-source-id',
1016
+ 'Duplicate explicit source IDs must be represented by one ambiguous entry.',
1017
+ ),
1018
+ );
372
1019
  if (entry.sourceId !== null) sourceIds.add(entry.sourceId);
373
- if (entry.confidence === 'exact' && ((entry.sourceId === null && entry.range === null) || entry.elementIds.length !== 1)) issues.push(error(location, 'source-identity', 'Exact correspondence requires a source ID or exact range and one semantic element.'));
1020
+ if (
1021
+ entry.confidence === 'exact' &&
1022
+ ((entry.sourceId === null && entry.range === null) || entry.elementIds.length !== 1)
1023
+ )
1024
+ issues.push(
1025
+ error(
1026
+ location,
1027
+ 'source-identity',
1028
+ 'Exact correspondence requires a source ID or exact range and one semantic element.',
1029
+ ),
1030
+ );
374
1031
  const certification = mermaidConstructs.find((item) => item.construct === entry.construct);
375
- if (!certification || (certification.import === 'unsupported' && (entry.confidence === 'exact' || entry.losses.length === 0))) issues.push(error(`${location}.construct`, 'source-certification', 'Unsupported syntax requires the certified loss record and cannot claim exact correspondence.'));
376
- if (elementIds) entry.elementIds.forEach((item, j) => { if (!elementIds.has(item)) issues.push(error(`${location}.elementIds[${j}]`, 'reference', 'Source map semantic element is missing.')); });
377
- if (entry.range && (entry.range.startByte > entry.range.endByte || entry.range.endByte > value.sourceByteLength || (boundaries && (!boundaries.has(entry.range.startByte) || !boundaries.has(entry.range.endByte))))) issues.push(error(`${location}.range`, 'source-range', 'Source range must lie on UTF-8 boundaries within the original source.'));
1032
+ if (
1033
+ !certification ||
1034
+ (certification.import === 'unsupported' &&
1035
+ (entry.confidence === 'exact' || entry.losses.length === 0))
1036
+ )
1037
+ issues.push(
1038
+ error(
1039
+ `${location}.construct`,
1040
+ 'source-certification',
1041
+ 'Unsupported syntax requires the certified loss record and cannot claim exact correspondence.',
1042
+ ),
1043
+ );
1044
+ if (elementIds)
1045
+ entry.elementIds.forEach((item, j) => {
1046
+ if (!elementIds.has(item))
1047
+ issues.push(
1048
+ error(
1049
+ `${location}.elementIds[${j}]`,
1050
+ 'reference',
1051
+ 'Source map semantic element is missing.',
1052
+ ),
1053
+ );
1054
+ });
1055
+ if (
1056
+ entry.range &&
1057
+ (entry.range.startByte > entry.range.endByte ||
1058
+ entry.range.endByte > value.sourceByteLength ||
1059
+ (boundaries &&
1060
+ (!boundaries.has(entry.range.startByte) || !boundaries.has(entry.range.endByte))))
1061
+ )
1062
+ issues.push(
1063
+ error(
1064
+ `${location}.range`,
1065
+ 'source-range',
1066
+ 'Source range must lie on UTF-8 boundaries within the original source.',
1067
+ ),
1068
+ );
378
1069
  });
379
1070
  }
380
1071
  function bundleIssues(bundle, path, issues) {
381
1072
  documentIssues(bundle.document, `${path}.document`, issues);
382
1073
  presentationIssues(bundle.presentation, bundle.document, `${path}.presentation`, issues);
383
- if (bundle.diagramId !== bundle.document.diagramId || bundle.diagramId !== bundle.presentation.diagramId) issues.push(error(`${path}.diagramId`, 'diagram-id', 'Bundle members must identify one diagram.'));
384
- if ((bundle.originalSource === null) !== (bundle.sourceMap === null)) issues.push(error(path, 'source-pair', 'Original source and its correspondence map must be retained together.'));
1074
+ if (
1075
+ bundle.diagramId !== bundle.document.diagramId ||
1076
+ bundle.diagramId !== bundle.presentation.diagramId
1077
+ )
1078
+ issues.push(
1079
+ error(`${path}.diagramId`, 'diagram-id', 'Bundle members must identify one diagram.'),
1080
+ );
1081
+ if ((bundle.originalSource === null) !== (bundle.sourceMap === null))
1082
+ issues.push(
1083
+ error(
1084
+ path,
1085
+ 'source-pair',
1086
+ 'Original source and its correspondence map must be retained together.',
1087
+ ),
1088
+ );
385
1089
  if (bundle.originalSource) {
386
- if (new TextEncoder().encode(bundle.originalSource.text).length > DIAGRAM_AUTHORING_LIMITS.sourceBytes) issues.push(error(`${path}.originalSource.text`, 'resource-limit', 'Original source exceeds the UTF-8 byte limit.'));
387
- if (bundle.originalSource.sourceDigest !== sourceDigest(bundle.originalSource.text)) issues.push(error(`${path}.originalSource.sourceDigest`, 'source-digest', 'Source digest must match exact original UTF-8 bytes.'));
1090
+ if (
1091
+ new TextEncoder().encode(bundle.originalSource.text).length >
1092
+ DIAGRAM_AUTHORING_LIMITS.sourceBytes
1093
+ )
1094
+ issues.push(
1095
+ error(
1096
+ `${path}.originalSource.text`,
1097
+ 'resource-limit',
1098
+ 'Original source exceeds the UTF-8 byte limit.',
1099
+ ),
1100
+ );
1101
+ if (bundle.originalSource.sourceDigest !== sourceDigest(bundle.originalSource.text))
1102
+ issues.push(
1103
+ error(
1104
+ `${path}.originalSource.sourceDigest`,
1105
+ 'source-digest',
1106
+ 'Source digest must match exact original UTF-8 bytes.',
1107
+ ),
1108
+ );
388
1109
  }
389
- if (bundle.sourceMap) sourceMapIssues(bundle.sourceMap, bundle.document, bundle.originalSource?.text, `${path}.sourceMap`, issues);
390
- if (bundle.bundleDigest !== diagramAuthoringBundleDigest(bundle)) issues.push(error(`${path}.bundleDigest`, 'digest', 'Bundle content digest does not match.'));
1110
+ if (bundle.sourceMap)
1111
+ sourceMapIssues(
1112
+ bundle.sourceMap,
1113
+ bundle.document,
1114
+ bundle.originalSource?.text,
1115
+ `${path}.sourceMap`,
1116
+ issues,
1117
+ );
1118
+ if (bundle.bundleDigest !== diagramAuthoringBundleDigest(bundle))
1119
+ issues.push(error(`${path}.bundleDigest`, 'digest', 'Bundle content digest does not match.'));
391
1120
  }
392
1121
 
393
1122
  function basisIssues(value, bundle, path, issues) {
394
- if (bundle && (value.diagramId !== bundle.diagramId || !same(value.base ?? value.basis, expectedSnapshot(bundle)))) issues.push(error(path, 'basis', 'The artifact does not reference the exact supplied bundle snapshot.'));
1123
+ if (
1124
+ bundle &&
1125
+ (value.diagramId !== bundle.diagramId ||
1126
+ !same(value.base ?? value.basis, expectedSnapshot(bundle)))
1127
+ )
1128
+ issues.push(
1129
+ error(path, 'basis', 'The artifact does not reference the exact supplied bundle snapshot.'),
1130
+ );
395
1131
  }
396
1132
  function transactionIssues(value, bundle, path, issues) {
397
1133
  basisIssues(value, bundle, path, issues);
398
- if (value.undoOf === value.transactionId) issues.push(error(`${path}.undoOf`, 'undo-reference', 'An inverse cannot reference its own transaction.'));
1134
+ if (value.undoOf === value.transactionId)
1135
+ issues.push(
1136
+ error(`${path}.undoOf`, 'undo-reference', 'An inverse cannot reference its own transaction.'),
1137
+ );
399
1138
  const available = bundle ? new Set(allElements(bundle.document).map((entry) => entry.id)) : null;
400
- const collectionById = bundle ? new Map(semanticNames.flatMap((name) => bundle.document[name].map((entry) => [entry.id, name]))) : null;
1139
+ const collectionById = bundle
1140
+ ? new Map(
1141
+ semanticNames.flatMap((name) => bundle.document[name].map((entry) => [entry.id, name])),
1142
+ )
1143
+ : null;
401
1144
  const insertedCollections = new Map();
402
1145
  const inserted = new Set();
403
1146
  const removed = new Set();
404
1147
  const capability = bundle ? getDiagramAuthoringCapability(bundle.document.grammar.id) : null;
405
- const collectionOf = (elementId) => collectionById?.get(elementId) ?? insertedCollections.get(elementId);
1148
+ const collectionOf = (elementId) =>
1149
+ collectionById?.get(elementId) ?? insertedCollections.get(elementId);
406
1150
  const membershipReferences = (collection, item, location) => {
407
1151
  if (!collectionById) return;
408
1152
  const actualCollection = collectionOf(item.id);
409
- if (!actualCollection) issues.push(error(`${location}.id`, 'containment-reference', 'Membership container is not in the base or inserts.'));
410
- else if (actualCollection !== collection) issues.push(error(`${location}.id`, 'element-class', 'Membership container must match its semantic collection.'));
1153
+ if (!actualCollection)
1154
+ issues.push(
1155
+ error(
1156
+ `${location}.id`,
1157
+ 'containment-reference',
1158
+ 'Membership container is not in the base or inserts.',
1159
+ ),
1160
+ );
1161
+ else if (actualCollection !== collection)
1162
+ issues.push(
1163
+ error(
1164
+ `${location}.id`,
1165
+ 'element-class',
1166
+ 'Membership container must match its semantic collection.',
1167
+ ),
1168
+ );
411
1169
  item.members.forEach((member, j) => {
412
- if (!['nodes', 'groups', 'lanes', 'annotations'].includes(collectionOf(member))) issues.push(error(`${location}.members[${j}]`, 'containment-reference', 'Container members must reference placeable elements in the base or inserts.'));
1170
+ if (!['nodes', 'groups', 'lanes', 'annotations'].includes(collectionOf(member)))
1171
+ issues.push(
1172
+ error(
1173
+ `${location}.members[${j}]`,
1174
+ 'containment-reference',
1175
+ 'Container members must reference placeable elements in the base or inserts.',
1176
+ ),
1177
+ );
413
1178
  });
414
1179
  };
415
1180
  const semanticGeometry = (collection, geometry, location) => {
416
- if (collection && ((collection === 'relations') !== (geometry.route !== null))) issues.push(error(location, 'geometry-kind', 'Geometry must match the semantic element class.'));
1181
+ if (collection && (collection === 'relations') !== (geometry.route !== null))
1182
+ issues.push(
1183
+ error(location, 'geometry-kind', 'Geometry must match the semantic element class.'),
1184
+ );
417
1185
  };
418
1186
  const semanticAppearance = (collection, appearance, location) => {
419
1187
  if (!collection) return;
420
1188
  const shape = appearance.shape;
421
- if ((collection === 'relations' && shape !== 'connector')
422
- || (collection !== 'relations' && shape === 'connector')
423
- || (['groups', 'lanes'].includes(collection) && shape !== 'container')
424
- || (collection === 'nodes' && ['container', 'text'].includes(shape))) issues.push(error(`${location}.shape`, 'shape-kind', 'Appearance must match the semantic element class.'));
1189
+ if (
1190
+ (collection === 'relations' && shape !== 'connector') ||
1191
+ (collection !== 'relations' && shape === 'connector') ||
1192
+ (['groups', 'lanes'].includes(collection) && shape !== 'container') ||
1193
+ (collection === 'nodes' && ['container', 'text'].includes(shape))
1194
+ )
1195
+ issues.push(
1196
+ error(
1197
+ `${location}.shape`,
1198
+ 'shape-kind',
1199
+ 'Appearance must match the semantic element class.',
1200
+ ),
1201
+ );
425
1202
  };
426
1203
  // This inspects references only. Applying changes, checking before-values in sequence,
427
1204
  // computing inverse operations and committing revisions belong to the edit kernel.
@@ -430,197 +1207,700 @@ function transactionIssues(value, bundle, path, issues) {
430
1207
  if (op.type === 'insert-elements' || op.type === 'remove-elements') {
431
1208
  const entryIds = op.elements.map((entry) => entry.value.id);
432
1209
  const presentationIds = op.presentation.map((entry) => entry.elementId);
433
- if (new Set(entryIds).size !== entryIds.length) issues.push(error(`${location}.elements`, 'duplicate-id', 'Each operation must identify unique semantic elements.'));
434
- if (!same([...entryIds].sort(), [...presentationIds].sort())) issues.push(error(`${location}.presentation`, 'presentation-coverage', 'Inserted or removed semantic elements require matching presentation entries.'));
1210
+ if (new Set(entryIds).size !== entryIds.length)
1211
+ issues.push(
1212
+ error(
1213
+ `${location}.elements`,
1214
+ 'duplicate-id',
1215
+ 'Each operation must identify unique semantic elements.',
1216
+ ),
1217
+ );
1218
+ if (!same([...entryIds].sort(), [...presentationIds].sort()))
1219
+ issues.push(
1220
+ error(
1221
+ `${location}.presentation`,
1222
+ 'presentation-coverage',
1223
+ 'Inserted or removed semantic elements require matching presentation entries.',
1224
+ ),
1225
+ );
435
1226
  if (op.type === 'insert-elements' && op.positions) {
436
1227
  const positionedIds = op.positions.map((entry) => entry.elementId);
437
- if (new Set(positionedIds).size !== positionedIds.length) issues.push(error(`${location}.positions`, 'duplicate-id', 'Insertion positions must identify each element once.'));
438
- if (!same([...entryIds].sort(), [...positionedIds].sort())) issues.push(error(`${location}.positions`, 'position-coverage', 'Insertion positions must cover exactly the inserted elements.'));
1228
+ if (new Set(positionedIds).size !== positionedIds.length)
1229
+ issues.push(
1230
+ error(
1231
+ `${location}.positions`,
1232
+ 'duplicate-id',
1233
+ 'Insertion positions must identify each element once.',
1234
+ ),
1235
+ );
1236
+ if (!same([...entryIds].sort(), [...positionedIds].sort()))
1237
+ issues.push(
1238
+ error(
1239
+ `${location}.positions`,
1240
+ 'position-coverage',
1241
+ 'Insertion positions must cover exactly the inserted elements.',
1242
+ ),
1243
+ );
439
1244
  }
440
1245
  for (const entry of op.elements) {
441
1246
  if (op.type === 'insert-elements') {
442
- if (entry.collection === 'lanes' && capability && !capability.primitives.includes('lane')) issues.push(error(`${location}.elements`, 'profile-primitive', 'This authoring profile does not support lanes.'));
443
- if (inserted.has(entry.value.id) || available?.has(entry.value.id)) issues.push(error(`${location}.elements`, 'duplicate-id', 'An insert must allocate a new stable element ID.'));
1247
+ if (entry.collection === 'lanes' && capability && !capability.primitives.includes('lane'))
1248
+ issues.push(
1249
+ error(
1250
+ `${location}.elements`,
1251
+ 'profile-primitive',
1252
+ 'This authoring profile does not support lanes.',
1253
+ ),
1254
+ );
1255
+ if (inserted.has(entry.value.id) || available?.has(entry.value.id))
1256
+ issues.push(
1257
+ error(
1258
+ `${location}.elements`,
1259
+ 'duplicate-id',
1260
+ 'An insert must allocate a new stable element ID.',
1261
+ ),
1262
+ );
444
1263
  inserted.add(entry.value.id);
445
1264
  insertedCollections.set(entry.value.id, entry.collection);
446
1265
  } else {
447
- if (removed.has(entry.value.id)) issues.push(error(`${location}.elements`, 'duplicate-id', 'An element cannot be removed twice.'));
448
- if (available && !available.has(entry.value.id) && !inserted.has(entry.value.id)) issues.push(error(`${location}.elements`, 'reference', 'Removed element is not in the base or earlier inserts.'));
449
- if (collectionById && (collectionById.get(entry.value.id) ?? insertedCollections.get(entry.value.id)) !== entry.collection) issues.push(error(`${location}.elements`, 'element-class', 'Removed entry must identify the actual semantic element class.'));
1266
+ if (removed.has(entry.value.id))
1267
+ issues.push(
1268
+ error(`${location}.elements`, 'duplicate-id', 'An element cannot be removed twice.'),
1269
+ );
1270
+ if (available && !available.has(entry.value.id) && !inserted.has(entry.value.id))
1271
+ issues.push(
1272
+ error(
1273
+ `${location}.elements`,
1274
+ 'reference',
1275
+ 'Removed element is not in the base or earlier inserts.',
1276
+ ),
1277
+ );
1278
+ if (
1279
+ collectionById &&
1280
+ (collectionById.get(entry.value.id) ?? insertedCollections.get(entry.value.id)) !==
1281
+ entry.collection
1282
+ )
1283
+ issues.push(
1284
+ error(
1285
+ `${location}.elements`,
1286
+ 'element-class',
1287
+ 'Removed entry must identify the actual semantic element class.',
1288
+ ),
1289
+ );
450
1290
  removed.add(entry.value.id);
451
1291
  }
452
1292
  }
453
- if (op.type === 'insert-elements' && collectionById) op.elements.forEach((entry, j) => {
454
- if (entry.collection === 'relations') for (const endpoint of ['from', 'to']) {
455
- if ((collectionById.get(entry.value[endpoint]) ?? insertedCollections.get(entry.value[endpoint])) !== 'nodes') issues.push(error(`${location}.elements[${j}].value.${endpoint}`, 'endpoint', 'Relationship endpoints must identify nodes in the base or this insertion.'));
456
- }
457
- if (['groups', 'lanes'].includes(entry.collection)) membershipReferences(entry.collection, entry.value, `${location}.elements[${j}].value`);
458
- if (entry.collection === 'annotations' && entry.value.targetId !== null && !collectionOf(entry.value.targetId)) issues.push(error(`${location}.elements[${j}].value.targetId`, 'reference', 'Annotation target is not in the base or inserts.'));
459
- });
1293
+ if (op.type === 'insert-elements' && collectionById)
1294
+ op.elements.forEach((entry, j) => {
1295
+ if (entry.collection === 'relations')
1296
+ for (const endpoint of ['from', 'to']) {
1297
+ if (
1298
+ (collectionById.get(entry.value[endpoint]) ??
1299
+ insertedCollections.get(entry.value[endpoint])) !== 'nodes'
1300
+ )
1301
+ issues.push(
1302
+ error(
1303
+ `${location}.elements[${j}].value.${endpoint}`,
1304
+ 'endpoint',
1305
+ 'Relationship endpoints must identify nodes in the base or this insertion.',
1306
+ ),
1307
+ );
1308
+ }
1309
+ if (['groups', 'lanes'].includes(entry.collection))
1310
+ membershipReferences(entry.collection, entry.value, `${location}.elements[${j}].value`);
1311
+ if (
1312
+ entry.collection === 'annotations' &&
1313
+ entry.value.targetId !== null &&
1314
+ !collectionOf(entry.value.targetId)
1315
+ )
1316
+ issues.push(
1317
+ error(
1318
+ `${location}.elements[${j}].value.targetId`,
1319
+ 'reference',
1320
+ 'Annotation target is not in the base or inserts.',
1321
+ ),
1322
+ );
1323
+ });
460
1324
  // Validate geometry kind and routing even without a semantic context.
461
1325
  for (const [j, entry] of op.presentation.entries()) {
462
1326
  const semantic = op.elements.find((item) => item.value.id === entry.elementId);
463
1327
  geometryIssues(entry, `${location}.presentation[${j}]`, issues);
464
1328
  semanticGeometry(semantic?.collection, entry, `${location}.presentation[${j}]`);
465
- semanticAppearance(semantic?.collection, entry.appearance, `${location}.presentation[${j}].appearance`);
1329
+ semanticAppearance(
1330
+ semantic?.collection,
1331
+ entry.appearance,
1332
+ `${location}.presentation[${j}].appearance`,
1333
+ );
466
1334
  }
467
1335
  } else if (op.type === 'set-geometry' || op.type === 'set-appearance-locks') {
468
1336
  const touched = new Set();
469
1337
  op.changes.forEach((change, j) => {
470
- if (touched.has(change.elementId)) issues.push(error(`${location}.changes[${j}].elementId`, 'duplicate-id', 'An operation must list each affected element once.'));
1338
+ if (touched.has(change.elementId))
1339
+ issues.push(
1340
+ error(
1341
+ `${location}.changes[${j}].elementId`,
1342
+ 'duplicate-id',
1343
+ 'An operation must list each affected element once.',
1344
+ ),
1345
+ );
471
1346
  touched.add(change.elementId);
472
- if (available && !available.has(change.elementId) && !inserted.has(change.elementId)) issues.push(error(`${location}.changes[${j}].elementId`, 'reference', 'Affected element is not in the base or earlier inserts.'));
1347
+ if (available && !available.has(change.elementId) && !inserted.has(change.elementId))
1348
+ issues.push(
1349
+ error(
1350
+ `${location}.changes[${j}].elementId`,
1351
+ 'reference',
1352
+ 'Affected element is not in the base or earlier inserts.',
1353
+ ),
1354
+ );
473
1355
  for (const side of ['before', 'after']) {
474
1356
  const changePath = `${location}.changes[${j}].${side}`;
475
1357
  if (op.type === 'set-geometry') {
476
1358
  geometryIssues(change[side], changePath, issues);
477
- if (collectionById) semanticGeometry(collectionOf(change.elementId), change[side], changePath);
478
- } else if (collectionById) semanticAppearance(collectionOf(change.elementId), change[side].appearance, `${changePath}.appearance`);
1359
+ if (collectionById)
1360
+ semanticGeometry(collectionOf(change.elementId), change[side], changePath);
1361
+ } else if (collectionById)
1362
+ semanticAppearance(
1363
+ collectionOf(change.elementId),
1364
+ change[side].appearance,
1365
+ `${changePath}.appearance`,
1366
+ );
479
1367
  }
480
1368
  });
481
1369
  } else if (op.type === 'update-semantics') {
482
- if (op.collection === 'emphasis' && op.index !== undefined && (op.before !== null || op.after === null)) issues.push(error(`${location}.index`, 'insertion-position', 'An emphasis index is only valid when inserting an emphasis entry.'));
483
- if (!['document', 'source-map'].includes(op.collection) && available && !available.has(op.elementId) && !inserted.has(op.elementId)) issues.push(error(`${location}.elementId`, 'reference', 'Affected semantic element is not in the base or earlier inserts.'));
484
- if (!['document', 'source-map', 'emphasis'].includes(op.collection) && collectionById && (collectionById.get(op.elementId) ?? insertedCollections.get(op.elementId)) !== op.collection) issues.push(error(`${location}.collection`, 'element-class', 'An update cannot change the class of its semantic element.'));
485
- if (op.collection === 'relations') for (const side of ['before', 'after']) for (const end of ['from', 'to']) {
486
- if (collectionById && (collectionById.get(op[side][end]) ?? insertedCollections.get(op[side][end])) !== 'nodes') issues.push(error(`${location}.${side}.${end}`, 'endpoint', 'Relationship endpoints must identify nodes in the base or inserts.'));
487
- }
488
- if (collectionById && op.collection === 'annotations') for (const side of ['before', 'after']) {
489
- if (op[side].targetId !== null && !collectionOf(op[side].targetId)) issues.push(error(`${location}.${side}.targetId`, 'reference', 'Annotation target is not in the base or inserts.'));
490
- }
491
- if (collectionById && op.collection === 'document') for (const side of ['before', 'after']) op[side].accessibility.readingOrder.forEach((elementId, j) => {
492
- if (!collectionOf(elementId)) issues.push(error(`${location}.${side}.accessibility.readingOrder[${j}]`, 'reference', 'Reading order target is not in the base or inserts.'));
493
- });
1370
+ if (
1371
+ op.collection === 'emphasis' &&
1372
+ op.index !== undefined &&
1373
+ (op.before !== null || op.after === null)
1374
+ )
1375
+ issues.push(
1376
+ error(
1377
+ `${location}.index`,
1378
+ 'insertion-position',
1379
+ 'An emphasis index is only valid when inserting an emphasis entry.',
1380
+ ),
1381
+ );
1382
+ if (
1383
+ !['document', 'source-map'].includes(op.collection) &&
1384
+ available &&
1385
+ !available.has(op.elementId) &&
1386
+ !inserted.has(op.elementId)
1387
+ )
1388
+ issues.push(
1389
+ error(
1390
+ `${location}.elementId`,
1391
+ 'reference',
1392
+ 'Affected semantic element is not in the base or earlier inserts.',
1393
+ ),
1394
+ );
1395
+ if (
1396
+ !['document', 'source-map', 'emphasis'].includes(op.collection) &&
1397
+ collectionById &&
1398
+ (collectionById.get(op.elementId) ?? insertedCollections.get(op.elementId)) !==
1399
+ op.collection
1400
+ )
1401
+ issues.push(
1402
+ error(
1403
+ `${location}.collection`,
1404
+ 'element-class',
1405
+ 'An update cannot change the class of its semantic element.',
1406
+ ),
1407
+ );
1408
+ if (op.collection === 'relations')
1409
+ for (const side of ['before', 'after'])
1410
+ for (const end of ['from', 'to']) {
1411
+ if (
1412
+ collectionById &&
1413
+ (collectionById.get(op[side][end]) ?? insertedCollections.get(op[side][end])) !==
1414
+ 'nodes'
1415
+ )
1416
+ issues.push(
1417
+ error(
1418
+ `${location}.${side}.${end}`,
1419
+ 'endpoint',
1420
+ 'Relationship endpoints must identify nodes in the base or inserts.',
1421
+ ),
1422
+ );
1423
+ }
1424
+ if (collectionById && op.collection === 'annotations')
1425
+ for (const side of ['before', 'after']) {
1426
+ if (op[side].targetId !== null && !collectionOf(op[side].targetId))
1427
+ issues.push(
1428
+ error(
1429
+ `${location}.${side}.targetId`,
1430
+ 'reference',
1431
+ 'Annotation target is not in the base or inserts.',
1432
+ ),
1433
+ );
1434
+ }
1435
+ if (collectionById && op.collection === 'document')
1436
+ for (const side of ['before', 'after'])
1437
+ op[side].accessibility.readingOrder.forEach((elementId, j) => {
1438
+ if (!collectionOf(elementId))
1439
+ issues.push(
1440
+ error(
1441
+ `${location}.${side}.accessibility.readingOrder[${j}]`,
1442
+ 'reference',
1443
+ 'Reading order target is not in the base or inserts.',
1444
+ ),
1445
+ );
1446
+ });
494
1447
  } else if (op.type === 'set-membership-order') {
495
1448
  for (const side of ['before', 'after']) {
496
1449
  const state = op[side];
497
- if (state.lanes.length && capability && !capability.primitives.includes('lane')) issues.push(error(`${location}.${side}.lanes`, 'profile-primitive', 'This authoring profile does not support lanes.'));
498
- for (const collection of ['groups', 'lanes']) state[collection].forEach((item, j) => membershipReferences(collection, item, `${location}.${side}.${collection}[${j}]`));
1450
+ if (state.lanes.length && capability && !capability.primitives.includes('lane'))
1451
+ issues.push(
1452
+ error(
1453
+ `${location}.${side}.lanes`,
1454
+ 'profile-primitive',
1455
+ 'This authoring profile does not support lanes.',
1456
+ ),
1457
+ );
1458
+ for (const collection of ['groups', 'lanes'])
1459
+ state[collection].forEach((item, j) =>
1460
+ membershipReferences(collection, item, `${location}.${side}.${collection}[${j}]`),
1461
+ );
499
1462
  const parents = new Map();
500
1463
  const containers = [...state.groups, ...state.lanes];
501
- if (new Set(containers.map((item) => item.id)).size !== containers.length) issues.push(error(`${location}.${side}`, 'duplicate-id', 'Membership lists require distinct container IDs.'));
502
- for (const item of containers) for (const member of item.members) {
503
- if (parents.has(member)) issues.push(error(`${location}.${side}`, 'multiple-parents', 'Membership assigns more than one immediate parent.'));
504
- parents.set(member, item.id);
505
- }
506
- if (hasContainmentCycle(parents)) issues.push(error(`${location}.${side}`, 'containment-cycle', 'Membership must form a forest.'));
507
- if (!same([...state.laneOrder].sort(), state.lanes.map((item) => item.id).sort())) issues.push(error(`${location}.${side}.laneOrder`, 'lane-order', 'Membership includes every lane in explicit order.'));
1464
+ if (new Set(containers.map((item) => item.id)).size !== containers.length)
1465
+ issues.push(
1466
+ error(
1467
+ `${location}.${side}`,
1468
+ 'duplicate-id',
1469
+ 'Membership lists require distinct container IDs.',
1470
+ ),
1471
+ );
1472
+ for (const item of containers)
1473
+ for (const member of item.members) {
1474
+ if (parents.has(member))
1475
+ issues.push(
1476
+ error(
1477
+ `${location}.${side}`,
1478
+ 'multiple-parents',
1479
+ 'Membership assigns more than one immediate parent.',
1480
+ ),
1481
+ );
1482
+ parents.set(member, item.id);
1483
+ }
1484
+ if (hasContainmentCycle(parents))
1485
+ issues.push(
1486
+ error(`${location}.${side}`, 'containment-cycle', 'Membership must form a forest.'),
1487
+ );
1488
+ if (!same([...state.laneOrder].sort(), state.lanes.map((item) => item.id).sort()))
1489
+ issues.push(
1490
+ error(
1491
+ `${location}.${side}.laneOrder`,
1492
+ 'lane-order',
1493
+ 'Membership includes every lane in explicit order.',
1494
+ ),
1495
+ );
508
1496
  }
509
1497
  }
510
1498
  });
511
1499
  }
512
1500
  function geometryIssues(entry, path, issues) {
513
- if ((entry.bounds === null) === (entry.route === null)) issues.push(error(path, 'geometry-kind', 'Geometry requires exactly one of bounds or route.'));
514
- if (entry.route?.mode === 'manual' && entry.route.points.length < 2) issues.push(error(`${path}.route.points`, 'manual-route', 'Manual routes require at least two global points.'));
515
- if (entry.route?.mode === 'automatic' && entry.route.points.length !== 0) issues.push(error(`${path}.route.points`, 'automatic-route', 'Automatic route points are derived.'));
516
- if (entry.route?.mode === 'manual' && entry.route.strategy === 'straight' && entry.route.points.length !== 2) issues.push(error(`${path}.route.points`, 'route-strategy', 'A straight manual route has exactly two endpoint points.'));
517
- if (entry.route?.mode === 'manual' && entry.route.strategy === 'orthogonal' && entry.route.points.some((point, i, points) => i > 0 && point.x !== points[i - 1].x && point.y !== points[i - 1].y)) issues.push(error(`${path}.route.points`, 'route-strategy', 'Every orthogonal segment must be horizontal or vertical.'));
1501
+ if ((entry.bounds === null) === (entry.route === null))
1502
+ issues.push(error(path, 'geometry-kind', 'Geometry requires exactly one of bounds or route.'));
1503
+ if (entry.route?.mode === 'manual' && entry.route.points.length < 2)
1504
+ issues.push(
1505
+ error(
1506
+ `${path}.route.points`,
1507
+ 'manual-route',
1508
+ 'Manual routes require at least two global points.',
1509
+ ),
1510
+ );
1511
+ if (entry.route?.mode === 'automatic' && entry.route.points.length !== 0)
1512
+ issues.push(
1513
+ error(`${path}.route.points`, 'automatic-route', 'Automatic route points are derived.'),
1514
+ );
1515
+ if (
1516
+ entry.route?.mode === 'manual' &&
1517
+ entry.route.strategy === 'straight' &&
1518
+ entry.route.points.length !== 2
1519
+ )
1520
+ issues.push(
1521
+ error(
1522
+ `${path}.route.points`,
1523
+ 'route-strategy',
1524
+ 'A straight manual route has exactly two endpoint points.',
1525
+ ),
1526
+ );
1527
+ if (
1528
+ entry.route?.mode === 'manual' &&
1529
+ entry.route.strategy === 'orthogonal' &&
1530
+ entry.route.points.some(
1531
+ (point, i, points) => i > 0 && point.x !== points[i - 1].x && point.y !== points[i - 1].y,
1532
+ )
1533
+ )
1534
+ issues.push(
1535
+ error(
1536
+ `${path}.route.points`,
1537
+ 'route-strategy',
1538
+ 'Every orthogonal segment must be horizontal or vertical.',
1539
+ ),
1540
+ );
518
1541
  }
519
1542
  function fidelityIssues(value, bundle, path, issues) {
520
1543
  basisIssues(value, bundle, path, issues);
521
1544
  const idsKnown = bundle ? new Set(allElements(bundle.document).map((entry) => entry.id)) : null;
522
1545
  for (const [i, loss] of value.losses.entries()) {
523
- if (value[loss.dimension] === 'lossless') issues.push(error(`${path}.${loss.dimension}`, 'fidelity', 'A dimension with reported loss cannot claim lossless fidelity.'));
524
- if (idsKnown) loss.elementIds.forEach((entry, j) => { if (!idsKnown.has(entry)) issues.push(error(`${path}.losses[${i}].elementIds[${j}]`, 'reference', 'Fidelity loss refers to an unknown semantic element.')); });
1546
+ if (value[loss.dimension] === 'lossless')
1547
+ issues.push(
1548
+ error(
1549
+ `${path}.${loss.dimension}`,
1550
+ 'fidelity',
1551
+ 'A dimension with reported loss cannot claim lossless fidelity.',
1552
+ ),
1553
+ );
1554
+ if (idsKnown)
1555
+ loss.elementIds.forEach((entry, j) => {
1556
+ if (!idsKnown.has(entry))
1557
+ issues.push(
1558
+ error(
1559
+ `${path}.losses[${i}].elementIds[${j}]`,
1560
+ 'reference',
1561
+ 'Fidelity loss refers to an unknown semantic element.',
1562
+ ),
1563
+ );
1564
+ });
525
1565
  }
526
- if (bundle && value.sourceDigest !== (bundle.originalSource?.sourceDigest ?? null)) issues.push(error(`${path}.sourceDigest`, 'source-digest', 'Fidelity report must identify the retained source, if any.'));
527
- if (value.sourceFormat === 'mermaid' && value.sourceDigest === null) issues.push(error(`${path}.sourceDigest`, 'source-digest', 'A Mermaid import report must identify its exact source bytes.'));
1566
+ if (bundle && value.sourceDigest !== (bundle.originalSource?.sourceDigest ?? null))
1567
+ issues.push(
1568
+ error(
1569
+ `${path}.sourceDigest`,
1570
+ 'source-digest',
1571
+ 'Fidelity report must identify the retained source, if any.',
1572
+ ),
1573
+ );
1574
+ if (value.sourceFormat === 'mermaid' && value.sourceDigest === null)
1575
+ issues.push(
1576
+ error(
1577
+ `${path}.sourceDigest`,
1578
+ 'source-digest',
1579
+ 'A Mermaid import report must identify its exact source bytes.',
1580
+ ),
1581
+ );
528
1582
  if (bundle && value.sourceFormat === 'mermaid') {
529
- const uncertain = bundle.sourceMap?.entries.some((entry) => entry.confidence === 'ambiguous' || entry.losses.length || mermaidConstructs.find((item) => item.construct === entry.construct)?.import !== 'lossless');
530
- if (uncertain && value.semantic === 'lossless') issues.push(error(`${path}.semantic`, 'fidelity', 'Source correspondence records ambiguity or unsupported content; semantic fidelity cannot be lossless.'));
531
- const lostPresentation = bundle.sourceMap?.entries.some((entry) => ['styles-and-directives', 'manual-geometry', 'unsupported-construct'].includes(entry.construct));
532
- if (lostPresentation && value.presentation === 'lossless') issues.push(error(`${path}.presentation`, 'fidelity', 'Unsupported source presentation cannot be reported as retained without loss.'));
1583
+ const uncertain = bundle.sourceMap?.entries.some(
1584
+ (entry) =>
1585
+ entry.confidence === 'ambiguous' ||
1586
+ entry.losses.length ||
1587
+ mermaidConstructs.find((item) => item.construct === entry.construct)?.import !== 'lossless',
1588
+ );
1589
+ if (uncertain && value.semantic === 'lossless')
1590
+ issues.push(
1591
+ error(
1592
+ `${path}.semantic`,
1593
+ 'fidelity',
1594
+ 'Source correspondence records ambiguity or unsupported content; semantic fidelity cannot be lossless.',
1595
+ ),
1596
+ );
1597
+ const lostPresentation = bundle.sourceMap?.entries.some((entry) =>
1598
+ ['styles-and-directives', 'manual-geometry', 'unsupported-construct'].includes(
1599
+ entry.construct,
1600
+ ),
1601
+ );
1602
+ if (lostPresentation && value.presentation === 'lossless')
1603
+ issues.push(
1604
+ error(
1605
+ `${path}.presentation`,
1606
+ 'fidelity',
1607
+ 'Unsupported source presentation cannot be reported as retained without loss.',
1608
+ ),
1609
+ );
533
1610
  }
534
1611
  if (bundle && value.targetFormat === 'mermaid') {
535
- if (bundle.presentation.elements.length && value.presentation === 'lossless') issues.push(error(`${path}.presentation`, 'fidelity', 'Standard Mermaid does not retain authored global geometry, stacking, attachment offsets or locks.'));
536
- const appearances = new Map(bundle.presentation.elements.map((entry) => [entry.elementId, entry.appearance.shape]));
537
- const supportedNodes = bundle.document.nodes.every((entry) => (
538
- (entry.kind === 'process' && ['rectangle', 'rounded-rectangle'].includes(appearances.get(entry.id)))
539
- || (entry.kind === 'decision' && appearances.get(entry.id) === 'diamond')
540
- || (entry.kind === 'data-store' && appearances.get(entry.id) === 'cylinder')
541
- ));
542
- const supportedRelations = bundle.document.relations.every((entry) => (entry.kind === 'flow' && ['forward', 'both'].includes(entry.direction)) || (entry.kind === 'association' && entry.direction === 'none'));
543
- if ((!supportedNodes || !supportedRelations || bundle.document.lanes.length || bundle.document.annotations.length || bundle.document.emphasis.length) && value.semantic === 'lossless') issues.push(error(`${path}.semantic`, 'fidelity', 'The certified Mermaid subset cannot preserve all authored semantic roles or primitives.'));
1612
+ if (bundle.presentation.elements.length && value.presentation === 'lossless')
1613
+ issues.push(
1614
+ error(
1615
+ `${path}.presentation`,
1616
+ 'fidelity',
1617
+ 'Standard Mermaid does not retain authored global geometry, stacking, attachment offsets or locks.',
1618
+ ),
1619
+ );
1620
+ const appearances = new Map(
1621
+ bundle.presentation.elements.map((entry) => [entry.elementId, entry.appearance.shape]),
1622
+ );
1623
+ const supportedNodes = bundle.document.nodes.every(
1624
+ (entry) =>
1625
+ (entry.kind === 'process' &&
1626
+ ['rectangle', 'rounded-rectangle'].includes(appearances.get(entry.id))) ||
1627
+ (entry.kind === 'decision' && appearances.get(entry.id) === 'diamond') ||
1628
+ (entry.kind === 'data-store' && appearances.get(entry.id) === 'cylinder'),
1629
+ );
1630
+ const supportedRelations = bundle.document.relations.every(
1631
+ (entry) =>
1632
+ (entry.kind === 'flow' && ['forward', 'both'].includes(entry.direction)) ||
1633
+ (entry.kind === 'association' && entry.direction === 'none'),
1634
+ );
1635
+ if (
1636
+ (!supportedNodes ||
1637
+ !supportedRelations ||
1638
+ bundle.document.lanes.length ||
1639
+ bundle.document.annotations.length ||
1640
+ bundle.document.emphasis.length) &&
1641
+ value.semantic === 'lossless'
1642
+ )
1643
+ issues.push(
1644
+ error(
1645
+ `${path}.semantic`,
1646
+ 'fidelity',
1647
+ 'The certified Mermaid subset cannot preserve all authored semantic roles or primitives.',
1648
+ ),
1649
+ );
544
1650
  }
545
1651
  }
546
- const validRelativePath = (value) => !value.split('/').some((part) => part === '' || part === '.' || part === '..') && !/^[A-Za-z]:/u.test(value);
1652
+ const validRelativePath = (value) =>
1653
+ !value.split('/').some((part) => part === '' || part === '.' || part === '..') &&
1654
+ !/^[A-Za-z]:/u.test(value);
547
1655
 
548
- /** Returns located, value-redacted errors. No option bypasses shape, safety or digest checks. */
1656
+ /**
1657
+ * Returns located, value-redacted errors. No option bypasses shape, safety or digest checks.
1658
+ * @param {import('./diagram-authoring-contracts.d.mts').DiagramAuthoringValidationOptions} [options]
1659
+ * @returns {ReturnType<typeof import('./diagram-authoring-contracts.d.mts').validateDiagramAuthoringArtifact>}
1660
+ */
549
1661
  export function validateDiagramAuthoringArtifact(kind, value, options = {}) {
550
1662
  const issues = inspectData(value);
551
1663
  if (issues.length) return issues;
552
1664
  const optionIssues = inspectData(options);
553
- if (optionIssues.length) return optionIssues.map((entry) => ({ ...entry, path: entry.path.replace(/^\$/u, '$options') }));
554
- if (!options || Array.isArray(options) || typeof options !== 'object' || Object.keys(options).some((key) => !['document', 'bundle', 'baseBundle', 'sourceText'].includes(key))) return [error('$options', 'options', 'Only explicit document, bundle, baseBundle and sourceText contexts are accepted.')];
555
- if (options.sourceText !== undefined && typeof options.sourceText !== 'string') return [error('$options.sourceText', 'type', 'Source text context must be a string.')];
556
- if (typeof kind !== 'string' || !Object.hasOwn(DIAGRAM_AUTHORING_SCHEMAS, kind)) return [error('$', 'contract', 'Unknown diagram authoring contract.')];
1665
+ if (optionIssues.length)
1666
+ return optionIssues.map((entry) => ({
1667
+ ...entry,
1668
+ path: entry.path.replace(/^\$/u, '$options'),
1669
+ }));
1670
+ if (
1671
+ !options ||
1672
+ Array.isArray(options) ||
1673
+ typeof options !== 'object' ||
1674
+ Object.keys(options).some(
1675
+ (key) => !['document', 'bundle', 'baseBundle', 'sourceText'].includes(key),
1676
+ )
1677
+ )
1678
+ return [
1679
+ error(
1680
+ '$options',
1681
+ 'options',
1682
+ 'Only explicit document, bundle, baseBundle and sourceText contexts are accepted.',
1683
+ ),
1684
+ ];
1685
+ if (options.sourceText !== undefined && typeof options.sourceText !== 'string')
1686
+ return [error('$options.sourceText', 'type', 'Source text context must be a string.')];
1687
+ if (typeof kind !== 'string' || !Object.hasOwn(DIAGRAM_AUTHORING_SCHEMAS, kind))
1688
+ return [error('$', 'contract', 'Unknown diagram authoring contract.')];
557
1689
  const shapeIssues = validateJson(value, DIAGRAM_AUTHORING_SCHEMAS[kind]);
558
- if (shapeIssues.length) return shapeIssues.slice(0, 128).map(({ path, rule }) => error(path, rule, 'Value does not satisfy the diagram authoring contract.'));
1690
+ if (shapeIssues.length)
1691
+ return shapeIssues
1692
+ .slice(0, 128)
1693
+ .map(({ path, rule }) =>
1694
+ error(path, rule, 'Value does not satisfy the diagram authoring contract.'),
1695
+ );
559
1696
  // Context is untrusted too. Validate it before reading nested fields or using a digest.
560
- for (const name of ['document', 'bundle', 'baseBundle']) if (options[name] !== undefined) {
561
- const contextKind = name === 'document' ? 'diagram-document' : 'diagram-authoring-bundle';
562
- const failures = validateDiagramAuthoringArtifact(contextKind, options[name]);
563
- issues.push(...failures.map((entry) => ({ ...entry, path: entry.path.replace(/^\$/u, `$options.${name}`) })));
564
- }
1697
+ for (const name of ['document', 'bundle', 'baseBundle'])
1698
+ if (options[name] !== undefined) {
1699
+ const contextKind = name === 'document' ? 'diagram-document' : 'diagram-authoring-bundle';
1700
+ const failures = validateDiagramAuthoringArtifact(contextKind, options[name]);
1701
+ issues.push(
1702
+ ...failures.map((entry) => ({
1703
+ ...entry,
1704
+ path: entry.path.replace(/^\$/u, `$options.${name}`),
1705
+ })),
1706
+ );
1707
+ }
565
1708
  if (issues.length) return issues;
566
- if (options.bundle && options.baseBundle && !same(options.bundle, options.baseBundle)) return [error('$options', 'basis', 'Conflicting bundle contexts are not accepted.')];
1709
+ if (options.bundle && options.baseBundle && !same(options.bundle, options.baseBundle))
1710
+ return [error('$options', 'basis', 'Conflicting bundle contexts are not accepted.')];
567
1711
  const contextBundle = options.baseBundle ?? options.bundle;
568
1712
  const contextDoc = options.document ?? contextBundle?.document;
569
- if (options.document && contextBundle && !same(options.document, contextBundle.document)) return [error('$options.document', 'basis', 'Document context must match the supplied bundle.')];
570
- if (options.sourceText !== undefined && contextBundle?.originalSource && options.sourceText !== contextBundle.originalSource.text) return [error('$options.sourceText', 'source-digest', 'Source text context must match the supplied bundle.')];
1713
+ if (options.document && contextBundle && !same(options.document, contextBundle.document))
1714
+ return [
1715
+ error('$options.document', 'basis', 'Document context must match the supplied bundle.'),
1716
+ ];
1717
+ if (
1718
+ options.sourceText !== undefined &&
1719
+ contextBundle?.originalSource &&
1720
+ options.sourceText !== contextBundle.originalSource.text
1721
+ )
1722
+ return [
1723
+ error(
1724
+ '$options.sourceText',
1725
+ 'source-digest',
1726
+ 'Source text context must match the supplied bundle.',
1727
+ ),
1728
+ ];
571
1729
  switch (kind) {
572
- case 'diagram-document': documentIssues(value, '$', issues); break;
573
- case 'diagram-presentation': presentationIssues(value, contextDoc, '$', issues); break;
574
- case 'diagram-authoring-bundle': bundleIssues(value, '$', issues); break;
575
- case 'diagram-source-map': sourceMapIssues(value, contextDoc, options.sourceText ?? contextBundle?.originalSource?.text, '$', issues); break;
576
- case 'diagram-edit-transaction': transactionIssues(value, contextBundle, '$', issues); break;
1730
+ case 'diagram-document':
1731
+ documentIssues(value, '$', issues);
1732
+ break;
1733
+ case 'diagram-presentation':
1734
+ presentationIssues(value, contextDoc, '$', issues);
1735
+ break;
1736
+ case 'diagram-authoring-bundle':
1737
+ bundleIssues(value, '$', issues);
1738
+ break;
1739
+ case 'diagram-source-map':
1740
+ sourceMapIssues(
1741
+ value,
1742
+ contextDoc,
1743
+ options.sourceText ?? contextBundle?.originalSource?.text,
1744
+ '$',
1745
+ issues,
1746
+ );
1747
+ break;
1748
+ case 'diagram-edit-transaction':
1749
+ transactionIssues(value, contextBundle, '$', issues);
1750
+ break;
577
1751
  case 'diagram-change-proposal':
578
1752
  basisIssues(value, contextBundle, '$', issues);
579
1753
  transactionIssues(value.transaction, contextBundle, '$.transaction', issues);
580
- if (value.diagramId !== value.transaction.diagramId || !same(value.base, value.transaction.base)) issues.push(error('$.transaction', 'basis', 'Proposal and transaction must identify the same exact diagram snapshot.'));
1754
+ if (
1755
+ value.diagramId !== value.transaction.diagramId ||
1756
+ !same(value.base, value.transaction.base)
1757
+ )
1758
+ issues.push(
1759
+ error(
1760
+ '$.transaction',
1761
+ 'basis',
1762
+ 'Proposal and transaction must identify the same exact diagram snapshot.',
1763
+ ),
1764
+ );
1765
+ break;
1766
+ case 'diagram-fidelity-report':
1767
+ fidelityIssues(value, contextBundle, '$', issues);
581
1768
  break;
582
- case 'diagram-fidelity-report': fidelityIssues(value, contextBundle, '$', issues); break;
583
1769
  case 'diagram-manifest':
584
1770
  basisIssues(value, contextBundle, '$', issues);
585
- if (!validRelativePath(value.bundle.path)) issues.push(error('$.bundle.path', 'relative-path', 'Bundle path must remain within its artifact scope.'));
586
- if (!value.bundle.path.endsWith('.planr-diagram-bundle.json')) issues.push(error('$.bundle.path', 'bundle-path', 'The canonical bundle uses the planr-diagram-bundle.json extension.'));
1771
+ if (!validRelativePath(value.bundle.path))
1772
+ issues.push(
1773
+ error(
1774
+ '$.bundle.path',
1775
+ 'relative-path',
1776
+ 'Bundle path must remain within its artifact scope.',
1777
+ ),
1778
+ );
1779
+ if (!value.bundle.path.endsWith('.planr-diagram-bundle.json'))
1780
+ issues.push(
1781
+ error(
1782
+ '$.bundle.path',
1783
+ 'bundle-path',
1784
+ 'The canonical bundle uses the planr-diagram-bundle.json extension.',
1785
+ ),
1786
+ );
587
1787
  value.outputs.forEach((entry, i) => {
588
- if (!validRelativePath(entry.path)) issues.push(error(`$.outputs[${i}].path`, 'relative-path', 'Output path must remain within its artifact scope.'));
589
- if (entry.path === value.bundle.path) issues.push(error(`$.outputs[${i}].path`, 'canonical-output-collision', 'A derived output must not overwrite the canonical bundle.'));
590
- if (entry.fidelity.targetFormat !== ({ 'image/svg+xml': 'svg', 'text/html': 'html', 'image/png': 'png' })[entry.mediaType]) issues.push(error(`$.outputs[${i}].fidelity.targetFormat`, 'output-format', 'Output fidelity must describe the declared media type.'));
1788
+ if (!validRelativePath(entry.path))
1789
+ issues.push(
1790
+ error(
1791
+ `$.outputs[${i}].path`,
1792
+ 'relative-path',
1793
+ 'Output path must remain within its artifact scope.',
1794
+ ),
1795
+ );
1796
+ if (entry.path === value.bundle.path)
1797
+ issues.push(
1798
+ error(
1799
+ `$.outputs[${i}].path`,
1800
+ 'canonical-output-collision',
1801
+ 'A derived output must not overwrite the canonical bundle.',
1802
+ ),
1803
+ );
1804
+ if (
1805
+ entry.fidelity.targetFormat !==
1806
+ { 'image/svg+xml': 'svg', 'text/html': 'html', 'image/png': 'png' }[entry.mediaType]
1807
+ )
1808
+ issues.push(
1809
+ error(
1810
+ `$.outputs[${i}].fidelity.targetFormat`,
1811
+ 'output-format',
1812
+ 'Output fidelity must describe the declared media type.',
1813
+ ),
1814
+ );
591
1815
  fidelityIssues(entry.fidelity, contextBundle, `$.outputs[${i}].fidelity`, issues);
592
- if (entry.fidelity.diagramId !== value.diagramId || !same(entry.fidelity.basis, value.basis)) issues.push(error(`$.outputs[${i}].fidelity`, 'basis', 'Every output must identify the manifest snapshot.'));
1816
+ if (
1817
+ entry.fidelity.diagramId !== value.diagramId ||
1818
+ !same(entry.fidelity.basis, value.basis)
1819
+ )
1820
+ issues.push(
1821
+ error(
1822
+ `$.outputs[${i}].fidelity`,
1823
+ 'basis',
1824
+ 'Every output must identify the manifest snapshot.',
1825
+ ),
1826
+ );
593
1827
  });
594
- if (new Set(value.outputs.map((entry) => entry.path)).size !== value.outputs.length) issues.push(error('$.outputs', 'duplicate-path', 'Output paths must be unique.'));
1828
+ if (new Set(value.outputs.map((entry) => entry.path)).size !== value.outputs.length)
1829
+ issues.push(error('$.outputs', 'duplicate-path', 'Output paths must be unique.'));
595
1830
  break;
596
1831
  case 'diagram-publication-state':
597
- if (value.draft === null && value.published === null) issues.push(error('$', 'publication-reference', 'Publication metadata must identify at least one snapshot.'));
598
- if (contextBundle && (value.diagramId !== contextBundle.diagramId || ![value.draft, value.published].some((entry) => entry && same(entry, expectedSnapshot(contextBundle))))) issues.push(error('$', 'basis', 'Publication metadata does not reference the supplied snapshot.'));
1832
+ if (value.draft === null && value.published === null)
1833
+ issues.push(
1834
+ error(
1835
+ '$',
1836
+ 'publication-reference',
1837
+ 'Publication metadata must identify at least one snapshot.',
1838
+ ),
1839
+ );
1840
+ if (
1841
+ contextBundle &&
1842
+ (value.diagramId !== contextBundle.diagramId ||
1843
+ ![value.draft, value.published].some(
1844
+ (entry) => entry && same(entry, expectedSnapshot(contextBundle)),
1845
+ ))
1846
+ )
1847
+ issues.push(
1848
+ error('$', 'basis', 'Publication metadata does not reference the supplied snapshot.'),
1849
+ );
599
1850
  break;
600
1851
  case 'diagram-authoring-capabilities':
601
- if (!same(value, DIAGRAM_AUTHORING_CAPABILITIES)) issues.push(error('$', 'capability-certification', 'Capability claims must match the versioned certification catalog exactly.'));
1852
+ if (!same(value, DIAGRAM_AUTHORING_CAPABILITIES))
1853
+ issues.push(
1854
+ error(
1855
+ '$',
1856
+ 'capability-certification',
1857
+ 'Capability claims must match the versioned certification catalog exactly.',
1858
+ ),
1859
+ );
1860
+ break;
1861
+ default:
602
1862
  break;
603
- default: break;
604
1863
  }
605
1864
  return issues.slice(0, 128);
606
1865
  }
1866
+ /** @type {typeof import('./diagram-authoring-contracts.d.mts').assertDiagramAuthoringArtifact} */
607
1867
  export function assertDiagramAuthoringArtifact(kind, value, options) {
608
1868
  const errors = validateDiagramAuthoringArtifact(kind, value, options);
609
1869
  if (errors.length) {
610
- const failure = new TypeError(`Invalid ${kind}: ${errors.map((entry) => `${entry.path}: ${entry.rule}`).join('; ')}`);
611
- failure.errors = errors;
612
- throw failure;
1870
+ throw Object.assign(
1871
+ new TypeError(
1872
+ `Invalid ${kind}: ${errors.map((entry) => `${entry.path}: ${entry.rule}`).join('; ')}`,
1873
+ ),
1874
+ { errors },
1875
+ );
613
1876
  }
614
1877
  return value;
615
1878
  }
616
- export const validateDiagramDocument = (value, options) => validateDiagramAuthoringArtifact('diagram-document', value, options);
617
- export const assertDiagramDocument = (value, options) => assertDiagramAuthoringArtifact('diagram-document', value, options);
618
- export const validateDiagramPresentation = (value, options) => validateDiagramAuthoringArtifact('diagram-presentation', value, options);
619
- export const assertDiagramPresentation = (value, options) => assertDiagramAuthoringArtifact('diagram-presentation', value, options);
620
- export const validateDiagramAuthoringBundle = (value, options) => validateDiagramAuthoringArtifact('diagram-authoring-bundle', value, options);
621
- export const assertDiagramAuthoringBundle = (value, options) => assertDiagramAuthoringArtifact('diagram-authoring-bundle', value, options);
622
- export const validateDiagramEditTransaction = (value, options) => validateDiagramAuthoringArtifact('diagram-edit-transaction', value, options);
623
- export const assertDiagramEditTransaction = (value, options) => assertDiagramAuthoringArtifact('diagram-edit-transaction', value, options);
1879
+ /** @type {typeof import('./diagram-authoring-contracts.d.mts').validateDiagramDocument} */
1880
+ export const validateDiagramDocument = (value, options) =>
1881
+ validateDiagramAuthoringArtifact('diagram-document', value, options);
1882
+ /** @type {typeof import('./diagram-authoring-contracts.d.mts').assertDiagramDocument} */
1883
+ export const assertDiagramDocument = (value, options) =>
1884
+ assertDiagramAuthoringArtifact('diagram-document', value, options);
1885
+ /** @type {typeof import('./diagram-authoring-contracts.d.mts').validateDiagramPresentation} */
1886
+ export const validateDiagramPresentation = (value, options) =>
1887
+ validateDiagramAuthoringArtifact('diagram-presentation', value, options);
1888
+ /** @type {typeof import('./diagram-authoring-contracts.d.mts').assertDiagramPresentation} */
1889
+ export const assertDiagramPresentation = (value, options) =>
1890
+ assertDiagramAuthoringArtifact('diagram-presentation', value, options);
1891
+ /** @type {typeof import('./diagram-authoring-contracts.d.mts').validateDiagramAuthoringBundle} */
1892
+ export const validateDiagramAuthoringBundle = (value, options) =>
1893
+ validateDiagramAuthoringArtifact('diagram-authoring-bundle', value, options);
1894
+ /** @type {typeof import('./diagram-authoring-contracts.d.mts').assertDiagramAuthoringBundle} */
1895
+ export const assertDiagramAuthoringBundle = (value, options) =>
1896
+ assertDiagramAuthoringArtifact('diagram-authoring-bundle', value, options);
1897
+ /** @type {typeof import('./diagram-authoring-contracts.d.mts').validateDiagramEditTransaction} */
1898
+ export const validateDiagramEditTransaction = (value, options) =>
1899
+ validateDiagramAuthoringArtifact('diagram-edit-transaction', value, options);
1900
+ /** @type {typeof import('./diagram-authoring-contracts.d.mts').assertDiagramEditTransaction} */
1901
+ export const assertDiagramEditTransaction = (value, options) =>
1902
+ assertDiagramAuthoringArtifact('diagram-edit-transaction', value, options);
1903
+ /** @type {typeof import('./diagram-authoring-contracts.d.mts').summarizeDiagramAuthoringContent} */
624
1904
  export function summarizeDiagramAuthoringContent(bundle) {
625
1905
  assertDiagramAuthoringBundle(bundle);
626
1906
  const elementCount = allElements(bundle.document).length;
@@ -628,41 +1908,141 @@ export function summarizeDiagramAuthoringContent(bundle) {
628
1908
  }
629
1909
 
630
1910
  // Inspect the generated, exact frozen v1.6 descriptor without creating migrated data.
1911
+ /** @returns {ReturnType<typeof import('./diagram-authoring-contracts.d.mts').inspectLegacyDiagramDocument>} */
631
1912
  export function inspectLegacyDiagramDocument(value) {
632
1913
  let errors = inspectData(value);
633
- if (!errors.length && value && typeof value === 'object' && (value.protocolVersion !== '1.6.0' || value.schemaVersion !== '1.0.0')) errors.push(error('$', 'unsupported-version', 'This inspector accepts only the frozen v1.6 diagram contract.'));
634
- if (!errors.length) errors = validateJson(value, LEGACY_DIAGRAM_DOCUMENT_SCHEMA).slice(0, 128).map(({ path, rule }) => error(path, rule, 'Value does not satisfy the legacy diagram contract.'));
1914
+ if (
1915
+ !errors.length &&
1916
+ value &&
1917
+ typeof value === 'object' &&
1918
+ (value.protocolVersion !== '1.6.0' || value.schemaVersion !== '1.0.0')
1919
+ )
1920
+ errors.push(
1921
+ error(
1922
+ '$',
1923
+ 'unsupported-version',
1924
+ 'This inspector accepts only the frozen v1.6 diagram contract.',
1925
+ ),
1926
+ );
1927
+ if (!errors.length)
1928
+ errors = validateJson(value, LEGACY_DIAGRAM_DOCUMENT_SCHEMA)
1929
+ .slice(0, 128)
1930
+ .map(({ path, rule }) =>
1931
+ error(path, rule, 'Value does not satisfy the legacy diagram contract.'),
1932
+ );
635
1933
  let grammar = null;
636
1934
  if (!errors.length) {
637
- grammar = DIAGRAM_REGISTRIES['diagram-grammars.json'].grammars.find((entry) => entry.grammarId === value.grammar.id);
1935
+ grammar = DIAGRAM_REGISTRIES['diagram-grammars.json'].grammars.find(
1936
+ (entry) => entry.grammarId === value.grammar.id,
1937
+ );
638
1938
  if (!grammar) errors.push(error('$.grammar.id', 'grammar', 'Unknown legacy grammar.'));
639
- if (value.documentDigest !== diagramDocumentDigest(value)) errors.push(error('$.documentDigest', 'digest', 'Legacy semantic digest does not match.'));
1939
+ if (value.documentDigest !== diagramDocumentDigest(value))
1940
+ errors.push(error('$.documentDigest', 'digest', 'Legacy semantic digest does not match.'));
640
1941
  const elements = allElements(value);
641
- if (!elements.length && !value.emphasis.length) errors.push(error('$', 'visible-content', 'The legacy document contract requires content.'));
642
- if (elements.length + value.emphasis.length > 10000) errors.push(error('$', 'resource-limit', 'Too many legacy semantic primitive entries.'));
1942
+ if (!elements.length && !value.emphasis.length)
1943
+ errors.push(error('$', 'visible-content', 'The legacy document contract requires content.'));
1944
+ if (elements.length + value.emphasis.length > 10000)
1945
+ errors.push(error('$', 'resource-limit', 'Too many legacy semantic primitive entries.'));
643
1946
  const itemIds = new Set(elements.map((entry) => entry.id));
644
- if (itemIds.size !== elements.length) errors.push(error('$', 'duplicate-id', 'Legacy semantic IDs must be unique.'));
645
- for (const collection of ['relations', 'groups', 'lanes', 'sets', 'annotations', 'emphasis']) value[collection].forEach((entry, i) => {
646
- const refs = collection === 'relations' ? [entry.from, entry.to] : entry.members ?? (entry.targetId == null ? [] : [entry.targetId]);
647
- if (refs.some((ref) => !itemIds.has(ref))) errors.push(error(`$.${collection}[${i}]`, 'reference', 'Legacy semantic reference is missing.'));
1947
+ if (itemIds.size !== elements.length)
1948
+ errors.push(error('$', 'duplicate-id', 'Legacy semantic IDs must be unique.'));
1949
+ for (const collection of ['relations', 'groups', 'lanes', 'sets', 'annotations', 'emphasis'])
1950
+ value[collection].forEach((entry, i) => {
1951
+ const refs =
1952
+ collection === 'relations'
1953
+ ? [entry.from, entry.to]
1954
+ : (entry.members ?? (entry.targetId == null ? [] : [entry.targetId]));
1955
+ if (refs.some((ref) => !itemIds.has(ref)))
1956
+ errors.push(
1957
+ error(`$.${collection}[${i}]`, 'reference', 'Legacy semantic reference is missing.'),
1958
+ );
1959
+ });
1960
+ value.accessibility.readingOrder.forEach((entry, i) => {
1961
+ if (!itemIds.has(entry))
1962
+ errors.push(
1963
+ error(
1964
+ `$.accessibility.readingOrder[${i}]`,
1965
+ 'reference',
1966
+ 'Legacy reading order target is missing.',
1967
+ ),
1968
+ );
648
1969
  });
649
- value.accessibility.readingOrder.forEach((entry, i) => { if (!itemIds.has(entry)) errors.push(error(`$.accessibility.readingOrder[${i}]`, 'reference', 'Legacy reading order target is missing.')); });
650
1970
  if (grammar) {
651
- if (!grammar.directions.includes(value.layout.direction)) errors.push(error('$.layout.direction', 'profile-direction', 'Direction is not supported by the legacy grammar.'));
652
- if (!['quadrant', 'scatter', 'wardley'].includes(grammar.grammarId) && value.nodes.some((entry) => entry.semanticPosition != null)) errors.push(error('$.nodes', 'semantic-position', 'Semantic position is not supported by this legacy grammar.'));
653
- const plural = { node: 'nodes', relation: 'relations', group: 'groups', lane: 'lanes', event: 'events', series: 'series', axis: 'axes', set: 'sets', annotation: 'annotations', emphasis: 'emphasis' };
1971
+ if (!grammar.directions.includes(value.layout.direction))
1972
+ errors.push(
1973
+ error(
1974
+ '$.layout.direction',
1975
+ 'profile-direction',
1976
+ 'Direction is not supported by the legacy grammar.',
1977
+ ),
1978
+ );
1979
+ if (
1980
+ !['quadrant', 'scatter', 'wardley'].includes(grammar.grammarId) &&
1981
+ value.nodes.some((entry) => entry.semanticPosition != null)
1982
+ )
1983
+ errors.push(
1984
+ error(
1985
+ '$.nodes',
1986
+ 'semantic-position',
1987
+ 'Semantic position is not supported by this legacy grammar.',
1988
+ ),
1989
+ );
1990
+ const plural = {
1991
+ node: 'nodes',
1992
+ relation: 'relations',
1993
+ group: 'groups',
1994
+ lane: 'lanes',
1995
+ event: 'events',
1996
+ series: 'series',
1997
+ axis: 'axes',
1998
+ set: 'sets',
1999
+ annotation: 'annotations',
2000
+ emphasis: 'emphasis',
2001
+ };
654
2002
  for (const [primitive, collection] of Object.entries(plural)) {
655
- if (value[collection].length && !grammar.allowedPrimitives.includes(primitive)) errors.push(error(`$.${collection}`, 'profile-primitive', 'Primitive is not allowed by this legacy grammar.'));
656
- if (!value[collection].length && grammar.requiredPrimitives.includes(primitive)) errors.push(error(`$.${collection}`, 'required-primitive', 'Required legacy primitive is missing.'));
2003
+ if (value[collection].length && !grammar.allowedPrimitives.includes(primitive))
2004
+ errors.push(
2005
+ error(
2006
+ `$.${collection}`,
2007
+ 'profile-primitive',
2008
+ 'Primitive is not allowed by this legacy grammar.',
2009
+ ),
2010
+ );
2011
+ if (!value[collection].length && grammar.requiredPrimitives.includes(primitive))
2012
+ errors.push(
2013
+ error(`$.${collection}`, 'required-primitive', 'Required legacy primitive is missing.'),
2014
+ );
657
2015
  }
658
2016
  }
659
2017
  }
660
2018
  const valid = errors.length === 0;
661
- const unsupportedNodeKinds = valid ? [...new Set(value.nodes.filter((entry) => !semanticKinds.includes(entry.kind)).map((entry) => entry.kind))] : [];
662
- const authoringAvailable = valid && getDiagramAuthoringCapability(value.grammar.id) !== null && !unsupportedNodeKinds.length && !value.relations.some((entry) => entry.kind === 'containment') && !['events', 'series', 'axes', 'sets'].some((key) => value[key].length) && !(value.grammar.id === 'flowchart' || value.grammar.id === 'architecture' ? value.lanes.length : false);
2019
+ const unsupportedNodeKinds = valid
2020
+ ? [
2021
+ ...new Set(
2022
+ value.nodes
2023
+ .filter((entry) => !semanticKinds.includes(entry.kind))
2024
+ .map((entry) => entry.kind),
2025
+ ),
2026
+ ]
2027
+ : [];
2028
+ const authoringAvailable =
2029
+ valid &&
2030
+ getDiagramAuthoringCapability(value.grammar.id) !== null &&
2031
+ !unsupportedNodeKinds.length &&
2032
+ !value.relations.some((entry) => entry.kind === 'containment') &&
2033
+ !['events', 'series', 'axes', 'sets'].some((key) => value[key].length) &&
2034
+ !(value.grammar.id === 'flowchart' || value.grammar.id === 'architecture'
2035
+ ? value.lanes.length
2036
+ : false);
663
2037
  return {
664
- valid, errors, diagramId: valid ? value.diagramId : null, grammarId: valid ? value.grammar.id : null,
665
- authoringAvailable, requiresDerivedPresentation: valid, unsupportedNodeKinds,
666
- adoption: 'explicit-save-required', sourceModified: false,
2038
+ valid,
2039
+ errors,
2040
+ diagramId: valid ? value.diagramId : null,
2041
+ grammarId: valid ? value.grammar.id : null,
2042
+ authoringAvailable,
2043
+ requiresDerivedPresentation: valid,
2044
+ unsupportedNodeKinds,
2045
+ adoption: 'explicit-save-required',
2046
+ sourceModified: false,
667
2047
  };
668
2048
  }