@openplanr/protocol 0.13.0 → 0.14.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.
@@ -0,0 +1,266 @@
1
+ import { canonicalizeJson, sha256Hex } from './canonical-json.mjs';
2
+ import { assertDiagramData } from './diagram-authoring-contracts.mjs';
3
+ import { validateJson } from './json-schema.mjs';
4
+
5
+ const closed = (properties) => ({
6
+ type: 'object',
7
+ additionalProperties: false,
8
+ required: Object.keys(properties),
9
+ properties,
10
+ });
11
+ const unit = { type: 'number', minimum: 0, maximum: 1 };
12
+ const extent = { type: 'number', exclusiveMinimum: 0, maximum: 1 };
13
+ const point = closed({ x: unit, y: unit });
14
+ const identifier = { type: 'string', pattern: '^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$', maxLength: 128 };
15
+ const version = { type: 'string', pattern: '^[0-9]+\\.[0-9]+\\.[0-9]+$', maxLength: 32 };
16
+ const digest = { type: 'string', pattern: '^sha256:[a-f0-9]{64}$' };
17
+ const rect = {
18
+ type: { const: 'rect' },
19
+ x: unit,
20
+ y: unit,
21
+ width: extent,
22
+ height: extent,
23
+ radius: unit,
24
+ };
25
+ const ellipse = { type: { const: 'ellipse' }, cx: unit, cy: unit, rx: extent, ry: extent };
26
+ const polygon = {
27
+ type: { const: 'polygon' },
28
+ points: { type: 'array', minItems: 3, maxItems: 32, items: point },
29
+ };
30
+ const paint = { fill: { enum: ['fill', 'none'] }, stroke: { enum: ['stroke', 'none'] } };
31
+ const pixels = { type: 'number', minimum: 1, maximum: 10000 };
32
+
33
+ export const SHAPE_REFERENCE_SCHEMA = closed({
34
+ packId: identifier,
35
+ packVersion: version,
36
+ shapeId: identifier,
37
+ definitionDigest: digest,
38
+ });
39
+ export const SHAPE_DEFINITION_SCHEMA = {
40
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
41
+ $id: 'https://openplanr.dev/schemas/v1.21.0/diagram-shape-definition.schema.json',
42
+ 'x-openplanr-contract': { id: 'diagram-shape-definition', version: '1.21.0' },
43
+ ...closed({
44
+ ...SHAPE_REFERENCE_SCHEMA.properties,
45
+ name: { type: 'string', minLength: 1, maxLength: 128 },
46
+ description: { type: 'string', maxLength: 1024 },
47
+ tags: {
48
+ type: 'array',
49
+ maxItems: 16,
50
+ uniqueItems: true,
51
+ items: { type: 'string', minLength: 1, maxLength: 64 },
52
+ },
53
+ primitives: {
54
+ type: 'array',
55
+ minItems: 1,
56
+ maxItems: 32,
57
+ items: {
58
+ oneOf: [
59
+ closed({ ...rect, ...paint }),
60
+ closed({ ...ellipse, ...paint }),
61
+ closed({ ...polygon, ...paint }),
62
+ closed({
63
+ type: { const: 'line' },
64
+ x1: unit,
65
+ y1: unit,
66
+ x2: unit,
67
+ y2: unit,
68
+ stroke: paint.stroke,
69
+ }),
70
+ ],
71
+ },
72
+ },
73
+ attachment: { oneOf: [closed(rect), closed(ellipse), closed(polygon)] },
74
+ textRegion: closed({ x: unit, y: unit, width: extent, height: extent }),
75
+ sizing: closed({ width: pixels, height: pixels, minWidth: pixels, minHeight: pixels }),
76
+ }),
77
+ };
78
+ export const SHAPE_LIBRARY_SCHEMA = {
79
+ type: 'array',
80
+ maxItems: 512,
81
+ items: SHAPE_DEFINITION_SCHEMA,
82
+ };
83
+
84
+ export function shapeReferenceKey(value) {
85
+ return `${value.packId}@${value.packVersion}/${value.shapeId}`;
86
+ }
87
+
88
+ export function shapeDefinitionDigest(value) {
89
+ assertDiagramData(value);
90
+ const { definitionDigest: _digest, ...definition } = value;
91
+ return `sha256:${sha256Hex(canonicalizeJson(definition))}`;
92
+ }
93
+
94
+ function assertConvexPolygon(points, label) {
95
+ let orientation = 0;
96
+ for (let index = 0; index < points.length; index += 1) {
97
+ const a = points[index];
98
+ const b = points[(index + 1) % points.length];
99
+ const c = points[(index + 2) % points.length];
100
+ const cross = (b.x - a.x) * (c.y - b.y) - (b.y - a.y) * (c.x - b.x);
101
+ if (a.x === b.x && a.y === b.y)
102
+ throw new TypeError(`${label}: polygon has duplicate adjacent points.`);
103
+ if (cross !== 0) {
104
+ if (orientation !== 0 && Math.sign(cross) !== orientation)
105
+ throw new TypeError(`${label}: polygon must be convex.`);
106
+ orientation = Math.sign(cross);
107
+ }
108
+ }
109
+ if (orientation === 0) throw new TypeError(`${label}: polygon has no area.`);
110
+ // Every other vertex must lie on the same side of each edge, excluding self intersections.
111
+ for (let index = 0; index < points.length; index += 1) {
112
+ const a = points[index];
113
+ const b = points[(index + 1) % points.length];
114
+ for (const c of points) {
115
+ const cross = (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);
116
+ if (cross * orientation < -1e-10)
117
+ throw new TypeError(`${label}: polygon must be simple and convex.`);
118
+ }
119
+ }
120
+ }
121
+
122
+ function assertGeometry(value, label) {
123
+ if (value.type === 'ellipse') {
124
+ if (
125
+ value.cx - value.rx < 0 ||
126
+ value.cy - value.ry < 0 ||
127
+ value.cx + value.rx > 1 ||
128
+ value.cy + value.ry > 1
129
+ )
130
+ throw new TypeError(`${label}: ellipse exceeds normalized bounds.`);
131
+ } else if (value.type === 'polygon') {
132
+ assertConvexPolygon(value.points, label);
133
+ } else if (value.type !== 'line') {
134
+ if (
135
+ value.x + value.width > 1 ||
136
+ value.y + value.height > 1 ||
137
+ (value.radius ?? 0) > Math.min(value.width, value.height) / 2
138
+ )
139
+ throw new TypeError(`${label}: rectangle exceeds normalized bounds or radius.`);
140
+ }
141
+ }
142
+
143
+ // Normalized geometry only needs allowance for floating-point roundoff.
144
+ const GEOMETRY_ROUNDOFF = Number.EPSILON * 32;
145
+ function primitiveVertices(primitive) {
146
+ if (primitive.type === 'polygon') return primitive.points;
147
+ if (primitive.type === 'line')
148
+ return [
149
+ { x: primitive.x1, y: primitive.y1 },
150
+ { x: primitive.x2, y: primitive.y2 },
151
+ ];
152
+ const x = primitive.type === 'ellipse' ? primitive.cx - primitive.rx : primitive.x;
153
+ const y = primitive.type === 'ellipse' ? primitive.cy - primitive.ry : primitive.y;
154
+ const width = primitive.type === 'ellipse' ? primitive.rx * 2 : primitive.width;
155
+ const height = primitive.type === 'ellipse' ? primitive.ry * 2 : primitive.height;
156
+ return [
157
+ { x, y },
158
+ { x: x + width, y },
159
+ { x: x + width, y: y + height },
160
+ { x, y: y + height },
161
+ ];
162
+ }
163
+ function primitiveSupport(primitive, nx, ny) {
164
+ if (primitive.type === 'ellipse')
165
+ return primitive.cx * nx + primitive.cy * ny + Math.hypot(primitive.rx * nx, primitive.ry * ny);
166
+ // Rounded corners scale uniformly, so only the rectangle envelope survives every aspect ratio.
167
+ return Math.max(...primitiveVertices(primitive).map(({ x, y }) => x * nx + y * ny));
168
+ }
169
+ function containsPoint(outline, point) {
170
+ if (outline.type === 'ellipse')
171
+ return (
172
+ Math.hypot((point.x - outline.cx) / outline.rx, (point.y - outline.cy) / outline.ry) <=
173
+ 1 + GEOMETRY_ROUNDOFF
174
+ );
175
+ const dx = Math.max(
176
+ outline.x + outline.radius - point.x,
177
+ point.x - (outline.x + outline.width - outline.radius),
178
+ 0,
179
+ );
180
+ const dy = Math.max(
181
+ outline.y + outline.radius - point.y,
182
+ point.y - (outline.y + outline.height - outline.radius),
183
+ 0,
184
+ );
185
+ return Math.hypot(dx, dy) <= outline.radius + GEOMETRY_ROUNDOFF;
186
+ }
187
+ function assertPrimitiveContainment(primitive, outline, label) {
188
+ const { fill: _fill, stroke: _stroke, ...geometry } = primitive;
189
+ if (canonicalizeJson(geometry) === canonicalizeJson(outline)) return;
190
+ if (outline.type === 'polygon') {
191
+ const points = outline.points;
192
+ let sign = 0;
193
+ for (let index = 0; index < points.length && sign === 0; index += 1) {
194
+ const a = points[index],
195
+ b = points[(index + 1) % points.length],
196
+ c = points[(index + 2) % points.length];
197
+ sign = Math.sign((b.x - a.x) * (c.y - b.y) - (b.y - a.y) * (c.x - b.x));
198
+ }
199
+ for (let index = 0; index < points.length; index += 1) {
200
+ const a = points[index],
201
+ b = points[(index + 1) % points.length];
202
+ const length = Math.hypot(b.x - a.x, b.y - a.y);
203
+ const nx = (sign * (b.y - a.y)) / length,
204
+ ny = (sign * (a.x - b.x)) / length;
205
+ if (primitiveSupport(primitive, nx, ny) > a.x * nx + a.y * ny + GEOMETRY_ROUNDOFF)
206
+ throw new TypeError(
207
+ `${label}: primitive exceeds its attachment outline; keep decoration geometry and rounded-rectangle bounds inside the declared boundary.`,
208
+ );
209
+ }
210
+ return;
211
+ }
212
+ if (!primitiveVertices(primitive).every((point) => containsPoint(outline, point)))
213
+ throw new TypeError(
214
+ `${label}: primitive envelope exceeds its attachment outline; curved decorations require their axis-aligned bounds inside the declared boundary.`,
215
+ );
216
+ }
217
+
218
+ export function assertShapeDefinition(value) {
219
+ assertDiagramData(value);
220
+ const failures = validateJson(value, SHAPE_DEFINITION_SCHEMA);
221
+ if (failures.length)
222
+ throw new TypeError(
223
+ `Invalid shape definition: ${failures[0].path} ${failures[0].detail ?? failures[0].rule}.`,
224
+ );
225
+ const key = shapeReferenceKey(value);
226
+ if (shapeDefinitionDigest(value) !== value.definitionDigest)
227
+ throw new TypeError(`Shape ${key}: definition digest does not match.`);
228
+ for (const primitive of value.primitives) assertGeometry(primitive, `Shape ${key}`);
229
+ assertGeometry(value.attachment, `Shape ${key} attachment`);
230
+ const { fill: _fill, stroke: _stroke, ...outline } = value.primitives[0];
231
+ if (canonicalizeJson(outline) !== canonicalizeJson(value.attachment))
232
+ throw new TypeError(`Shape ${key}: first primitive must match its attachment outline.`);
233
+ for (const [index, primitive] of value.primitives.entries())
234
+ assertPrimitiveContainment(primitive, value.attachment, `Shape ${key} primitive ${index}`);
235
+ assertGeometry(value.textRegion, `Shape ${key} text region`);
236
+ if (value.sizing.width < value.sizing.minWidth || value.sizing.height < value.sizing.minHeight)
237
+ throw new TypeError(`Shape ${key}: default size is below its minimum size.`);
238
+ return value;
239
+ }
240
+
241
+ export function assertShapeLibrary(value) {
242
+ assertDiagramData(value);
243
+ if (validateJson(value, SHAPE_LIBRARY_SCHEMA).length)
244
+ throw new TypeError('Invalid shape library: expected at most 512 inert shape definitions.');
245
+ const keys = new Set();
246
+ for (const definition of value) {
247
+ assertShapeDefinition(definition);
248
+ const key = shapeReferenceKey(definition);
249
+ if (keys.has(key)) throw new TypeError(`Shape library contains duplicate identity ${key}.`);
250
+ keys.add(key);
251
+ }
252
+ return value;
253
+ }
254
+
255
+ export function assertShapeReference(value, library) {
256
+ assertDiagramData(value);
257
+ if (validateJson(value, SHAPE_REFERENCE_SCHEMA).length)
258
+ throw new TypeError('Invalid shape reference.');
259
+ const key = shapeReferenceKey(value);
260
+ const definition = library?.find((entry) => shapeReferenceKey(entry) === key);
261
+ if (!definition)
262
+ throw new TypeError(`Shape ${key}: definition is missing from the document library.`);
263
+ if (definition.definitionDigest !== value.definitionDigest)
264
+ throw new TypeError(`Shape ${key}: reference digest does not match its definition.`);
265
+ return definition;
266
+ }
@@ -4,6 +4,7 @@ import type {
4
4
  DiagramEditTransaction,
5
5
  } from './diagram-authoring-contracts.mjs';
6
6
  import type { DiagramReviewBundle } from './diagram-review-contracts.mjs';
7
+ import type { ShapeDefinition } from './shape-library-contracts.mjs';
7
8
  export interface DiagramPresentation {
8
9
  kind: 'openplanr-diagram-presentation';
9
10
  schemaVersion: '2.0.0';
@@ -53,7 +54,19 @@ export type DiagramAuthoringBundleV11 = Omit<
53
54
  DiagramAuthoringBundle,
54
55
  'schemaVersion' | 'protocolVersion'
55
56
  > & { schemaVersion: '1.1.0'; protocolVersion: '1.17.0'; studioPresentation: DiagramPresentation };
56
- export type VersionedDiagramAuthoringBundle = DiagramAuthoringBundle | DiagramAuthoringBundleV11;
57
+ export type DiagramAuthoringBundleV12 = Omit<
58
+ DiagramAuthoringBundle,
59
+ 'schemaVersion' | 'protocolVersion'
60
+ > & {
61
+ schemaVersion: '1.2.0';
62
+ protocolVersion: '1.21.0';
63
+ shapeLibrary: ShapeDefinition[];
64
+ studioPresentation?: DiagramPresentation;
65
+ };
66
+ export type VersionedDiagramAuthoringBundle =
67
+ | (DiagramAuthoringBundle & { studioPresentation?: never; shapeLibrary?: never })
68
+ | (DiagramAuthoringBundleV11 & { shapeLibrary?: never })
69
+ | DiagramAuthoringBundleV12;
57
70
  export interface SetStudioPresentationOperation {
58
71
  type: 'set-studio-presentation';
59
72
  before: DiagramPresentation | null;
@@ -67,7 +80,42 @@ export type DiagramEditTransactionV11 = Omit<
67
80
  protocolVersion: '1.17.0';
68
81
  operations: Array<DiagramEditOperation | SetStudioPresentationOperation>;
69
82
  };
70
- export type VersionedDiagramEditTransaction = DiagramEditTransaction | DiagramEditTransactionV11;
83
+ export interface SetShapeLibraryOperation {
84
+ type: 'set-shape-library';
85
+ before: ShapeDefinition[] | null;
86
+ after: ShapeDefinition[] | null;
87
+ }
88
+ export type DiagramEditTransactionV12 = Omit<
89
+ DiagramEditTransaction,
90
+ 'schemaVersion' | 'protocolVersion' | 'operations'
91
+ > & {
92
+ schemaVersion: '1.2.0';
93
+ protocolVersion: '1.21.0';
94
+ operations: Array<
95
+ DiagramEditOperation | SetStudioPresentationOperation | SetShapeLibraryOperation
96
+ >;
97
+ };
98
+ export type VersionedDiagramEditTransaction =
99
+ | DiagramEditTransaction
100
+ | DiagramEditTransactionV11
101
+ | DiagramEditTransactionV12;
102
+ export declare const DIAGRAM_AUTHORING_BUNDLE_V12_SCHEMA: Record<string, unknown>;
103
+ export declare const DIAGRAM_EDIT_TRANSACTION_V12_SCHEMA: Record<string, unknown>;
104
+ export declare const DIAGRAM_REVIEW_BUNDLE_V12_SCHEMA: Record<string, unknown>;
105
+ export type DiagramReviewBundleV12 = Omit<DiagramReviewBundle, 'schemaVersion' | 'authored'> & {
106
+ schemaVersion: '1.2.0';
107
+ presentation?: DiagramPresentation;
108
+ authored?: VersionedDiagramAuthoringBundle;
109
+ };
110
+ export declare function supportsDiagramShapeLibrary(value: unknown): boolean;
111
+ export declare function supportsDiagramStudioPresentation(value: unknown): boolean;
112
+ export declare function diagramAuthoringVersionFields(value: {
113
+ shapeLibrary?: ShapeDefinition[];
114
+ studioPresentation?: DiagramPresentation | null;
115
+ }):
116
+ | { schemaVersion: '1.2.0'; protocolVersion: '1.21.0' }
117
+ | { schemaVersion: '1.1.0'; protocolVersion: '1.17.0' }
118
+ | { schemaVersion: '1.0.0'; protocolVersion: '1.13.0' };
71
119
 
72
120
  export declare function validateVersionedDiagramAuthoringArtifact(
73
121
  kind: string,
@@ -6,6 +6,7 @@ import {
6
6
  copyImmutableDiagramData,
7
7
  DIAGRAM_AUTHORING_SCHEMAS,
8
8
  diagramAuthoringBundleDigest,
9
+ diagramPresentationDigest,
9
10
  sealImmutableDiagramData,
10
11
  validateDiagramAuthoringArtifact,
11
12
  } from './diagram-authoring-contracts.mjs';
@@ -15,6 +16,34 @@ import {
15
16
  DIAGRAM_REVIEW_BUNDLE_SCHEMA,
16
17
  } from './diagram-review-contracts.mjs';
17
18
  import { validateJson } from './json-schema.mjs';
19
+ import {
20
+ assertShapeLibrary,
21
+ assertShapeReference,
22
+ SHAPE_LIBRARY_SCHEMA,
23
+ SHAPE_REFERENCE_SCHEMA,
24
+ shapeReferenceKey,
25
+ } from './shape-library-contracts.mjs';
26
+
27
+ export function supportsDiagramShapeLibrary(value) {
28
+ return (
29
+ value !== null &&
30
+ typeof value === 'object' &&
31
+ Object.getOwnPropertyDescriptor(value, 'schemaVersion')?.value === '1.2.0'
32
+ );
33
+ }
34
+ export function supportsDiagramStudioPresentation(value) {
35
+ if (value === null || typeof value !== 'object') return false;
36
+ const version = Object.getOwnPropertyDescriptor(value, 'schemaVersion')?.value;
37
+ return version === '1.1.0' || version === '1.2.0';
38
+ }
39
+ export function diagramAuthoringVersionFields(value) {
40
+ return Object.hasOwn(value, 'shapeLibrary')
41
+ ? { schemaVersion: '1.2.0', protocolVersion: '1.21.0' }
42
+ : value.studioPresentation
43
+ ? { schemaVersion: '1.1.0', protocolVersion: '1.17.0' }
44
+ : { schemaVersion: '1.0.0', protocolVersion: '1.13.0' };
45
+ }
46
+
18
47
  export const DIAGRAM_PRESENTATION_SCHEMA = {
19
48
  $schema: 'https://json-schema.org/draft/2020-12/schema',
20
49
  $id: 'https://openplanr.dev/schemas/v1.17.0/diagram-presentation.schema.json',
@@ -72,6 +101,7 @@ export function assertDiagramReviewBundleV11(value) {
72
101
  }
73
102
  export function assertVersionedDiagramReviewBundle(value) {
74
103
  assertDiagramData(value);
104
+ if (value?.schemaVersion === '1.2.0') return assertDiagramReviewBundleV12(value);
75
105
  return value?.schemaVersion === '1.1.0'
76
106
  ? assertDiagramReviewBundleV11(value)
77
107
  : assertDiagramReviewBundle(value);
@@ -118,14 +148,21 @@ DIAGRAM_EDIT_TRANSACTION_V11_SCHEMA.properties.operations.items.oneOf.push({
118
148
  });
119
149
  export function legacyDiagramAuthoringProjection(value) {
120
150
  assertDiagramData(value);
121
- const { studioPresentation: _studio, ...legacy } = value;
151
+ if (supportsDiagramShapeLibrary(value)) assertShapeLibraryReferences(value);
152
+ const { studioPresentation: _studio, shapeLibrary: _library, ...legacy } = value;
122
153
  legacy.schemaVersion = '1.0.0';
123
154
  legacy.protocolVersion = '1.13.0';
155
+ if (supportsDiagramShapeLibrary(value)) {
156
+ legacy.presentation = structuredClone(value.presentation);
157
+ for (const placement of legacy.presentation.elements) delete placement.appearance.shapeRef;
158
+ legacy.presentation.presentationDigest = diagramPresentationDigest(legacy.presentation);
159
+ }
124
160
  legacy.bundleDigest = diagramAuthoringBundleDigest(legacy);
125
161
  return legacy;
126
162
  }
127
163
  export function assertVersionedDiagramAuthoringBundle(value) {
128
164
  assertDiagramData(value);
165
+ if (supportsDiagramShapeLibrary(value)) return assertDiagramAuthoringBundleV12(value);
129
166
  if (value?.schemaVersion !== '1.1.0') return assertDiagramAuthoringBundle(value);
130
167
  if (
131
168
  validateJson(value, DIAGRAM_AUTHORING_BUNDLE_V11_SCHEMA).length ||
@@ -139,6 +176,7 @@ export function assertVersionedDiagramAuthoringBundle(value) {
139
176
  export function assertVersionedDiagramEditTransaction(value, options = {}) {
140
177
  assertDiagramData(value);
141
178
  assertDiagramData(options);
179
+ if (supportsDiagramShapeLibrary(value)) return assertDiagramEditTransactionV12(value, options);
142
180
  if (value?.schemaVersion !== '1.1.0') return assertDiagramEditTransaction(value, options);
143
181
  if (validateJson(value, DIAGRAM_EDIT_TRANSACTION_V11_SCHEMA).length)
144
182
  throw new TypeError('Invalid diagram transaction 1.1.0.');
@@ -216,10 +254,10 @@ export function validateVersionedDiagramAuthoringArtifact(kind, value, options =
216
254
  return [{ path: '$', rule: 'diagram-authoring-contract', detail: error.message }];
217
255
  }
218
256
  if (kind === 'diagram-authoring-bundle') return validateVersionedDiagramAuthoringBundle(value);
219
- if (kind === 'diagram-edit-transaction' && value?.schemaVersion === '1.1.0')
257
+ if (kind === 'diagram-edit-transaction' && supportsDiagramStudioPresentation(value))
220
258
  return validateVersionedDiagramEditTransaction(value, options);
221
259
  const context = options.baseBundle ?? options.bundle;
222
- if (context?.schemaVersion !== '1.1.0')
260
+ if (!supportsDiagramStudioPresentation(context))
223
261
  return validateDiagramAuthoringArtifact(kind, value, options);
224
262
  const failures = validateVersionedDiagramAuthoringBundle(context);
225
263
  if (failures.length) return failures.map((entry) => ({ ...entry, path: '$options.bundle' }));
@@ -246,7 +284,10 @@ export function validateVersionedDiagramAuthoringArtifact(kind, value, options =
246
284
  Object.hasOwn(item, 'presentationDigest')
247
285
  ) {
248
286
  if (canonicalizeJson(item) === canonicalizeJson(fullSnapshot))
249
- item.bundleDigest = legacy.bundleDigest;
287
+ Object.assign(item, {
288
+ bundleDigest: legacy.bundleDigest,
289
+ presentationDigest: legacy.presentation.presentationDigest,
290
+ });
250
291
  else if (item.bundleDigest === legacy.bundleDigest) invalidBasis = true;
251
292
  }
252
293
  for (const child of Object.values(item)) project(child);
@@ -285,3 +326,243 @@ export function sealVersionedDiagramAuthoringSnapshot(value, previous = null) {
285
326
  assertVersionedDiagramAuthoringBundle(copy);
286
327
  return copy;
287
328
  }
329
+
330
+ function withShapeReferences(schema) {
331
+ const copy = structuredClone(schema);
332
+ function visit(value) {
333
+ if (!value || typeof value !== 'object') return;
334
+ if (value.properties?.shape && value.properties?.strokeWidth && value.properties?.fontSize)
335
+ value.properties.shapeRef = SHAPE_REFERENCE_SCHEMA;
336
+ for (const child of Object.values(value)) visit(child);
337
+ }
338
+ visit(copy);
339
+ return copy;
340
+ }
341
+ function versionSchema(schema, name) {
342
+ return {
343
+ ...schema,
344
+ $id: `https://openplanr.dev/schemas/v1.21.0/${name}.schema.json`,
345
+ 'x-openplanr-contract': { id: name, version: '1.21.0' },
346
+ };
347
+ }
348
+ export const DIAGRAM_AUTHORING_BUNDLE_V12_SCHEMA = versionSchema(
349
+ withShapeReferences(DIAGRAM_AUTHORING_BUNDLE_V11_SCHEMA),
350
+ 'diagram-authoring-bundle',
351
+ );
352
+ Object.assign(DIAGRAM_AUTHORING_BUNDLE_V12_SCHEMA.properties, {
353
+ schemaVersion: { const: '1.2.0' },
354
+ protocolVersion: { const: '1.21.0' },
355
+ shapeLibrary: SHAPE_LIBRARY_SCHEMA,
356
+ });
357
+ DIAGRAM_AUTHORING_BUNDLE_V12_SCHEMA.required = DIAGRAM_AUTHORING_BUNDLE_V12_SCHEMA.required
358
+ .filter((key) => key !== 'studioPresentation')
359
+ .concat('shapeLibrary');
360
+ export const DIAGRAM_EDIT_TRANSACTION_V12_SCHEMA = versionSchema(
361
+ withShapeReferences(DIAGRAM_EDIT_TRANSACTION_V11_SCHEMA),
362
+ 'diagram-edit-transaction',
363
+ );
364
+ Object.assign(DIAGRAM_EDIT_TRANSACTION_V12_SCHEMA.properties, {
365
+ schemaVersion: { const: '1.2.0' },
366
+ protocolVersion: { const: '1.21.0' },
367
+ });
368
+ DIAGRAM_EDIT_TRANSACTION_V12_SCHEMA.properties.operations.items.oneOf.push({
369
+ type: 'object',
370
+ additionalProperties: false,
371
+ required: ['type', 'before', 'after'],
372
+ properties: {
373
+ type: { const: 'set-shape-library' },
374
+ before: { anyOf: [SHAPE_LIBRARY_SCHEMA, { type: 'null' }] },
375
+ after: { anyOf: [SHAPE_LIBRARY_SCHEMA, { type: 'null' }] },
376
+ },
377
+ });
378
+ export const DIAGRAM_REVIEW_BUNDLE_V12_SCHEMA = versionSchema(
379
+ structuredClone(DIAGRAM_REVIEW_BUNDLE_SCHEMA),
380
+ 'diagram-review-bundle',
381
+ );
382
+ Object.assign(DIAGRAM_REVIEW_BUNDLE_V12_SCHEMA.properties, {
383
+ schemaVersion: { const: '1.2.0' },
384
+ presentation: DIAGRAM_PRESENTATION_SCHEMA,
385
+ authored: {
386
+ oneOf: [
387
+ DIAGRAM_AUTHORING_SCHEMAS['diagram-authoring-bundle'],
388
+ DIAGRAM_AUTHORING_BUNDLE_V11_SCHEMA,
389
+ DIAGRAM_AUTHORING_BUNDLE_V12_SCHEMA,
390
+ ],
391
+ },
392
+ });
393
+
394
+ function assertShapeLibraryReferences(value) {
395
+ assertShapeLibrary(value.shapeLibrary);
396
+ for (const entry of value.presentation.elements)
397
+ assertPlacementShape(entry, value.shapeLibrary, true);
398
+ }
399
+ function assertDiagramAuthoringBundleV12(value) {
400
+ if (validateJson(value, DIAGRAM_AUTHORING_BUNDLE_V12_SCHEMA).length)
401
+ throw new TypeError('Invalid diagram authoring bundle 1.2.0.');
402
+ if (
403
+ value.bundleDigest !== diagramAuthoringBundleDigest(value) ||
404
+ value.presentation.presentationDigest !== diagramPresentationDigest(value.presentation)
405
+ )
406
+ throw new TypeError('Diagram authoring bundle 1.2.0 content digest does not match.');
407
+ assertShapeLibraryReferences(value);
408
+ if (value.studioPresentation) assertDiagramPresentation(value.studioPresentation);
409
+ assertDiagramAuthoringBundle(legacyDiagramAuthoringProjection(value));
410
+ return value;
411
+ }
412
+ function assertDiagramReviewBundleV12(value) {
413
+ if (validateJson(value, DIAGRAM_REVIEW_BUNDLE_V12_SCHEMA).length)
414
+ throw new TypeError('Invalid diagram review bundle 1.2.0.');
415
+ const { presentation, ...legacy } = value;
416
+ if (presentation) assertDiagramPresentation(presentation);
417
+ if (value.authored) {
418
+ assertVersionedDiagramAuthoringBundle(value.authored);
419
+ if (
420
+ canonicalizeJson(value.authored.studioPresentation ?? null) !==
421
+ canonicalizeJson(presentation ?? null)
422
+ )
423
+ throw new TypeError('Review and authored presentations differ.');
424
+ legacy.authored = legacyDiagramAuthoringProjection(value.authored);
425
+ }
426
+ assertDiagramReviewBundle({ ...legacy, schemaVersion: '1.0.0' });
427
+ return value;
428
+ }
429
+ function assertLibraryOperation(operation) {
430
+ if (operation.before !== null) assertShapeLibrary(operation.before);
431
+ if (operation.after !== null) assertShapeLibrary(operation.after);
432
+ const previous = new Map(
433
+ (operation.before ?? []).map((entry) => [shapeReferenceKey(entry), entry.definitionDigest]),
434
+ );
435
+ for (const definition of operation.after ?? []) {
436
+ const digest = previous.get(shapeReferenceKey(definition));
437
+ if (digest && digest !== definition.definitionDigest)
438
+ throw new TypeError(
439
+ `Shape ${shapeReferenceKey(definition)}: immutable library definition changed.`,
440
+ );
441
+ }
442
+ }
443
+ function assertChangedValue(operation, current, label) {
444
+ if (
445
+ canonicalizeJson(operation.before) !== canonicalizeJson(current) ||
446
+ canonicalizeJson(operation.after) === canonicalizeJson(current)
447
+ )
448
+ throw new TypeError(`${label} operation before/after differs.`);
449
+ }
450
+ function assertPlacementShape(entry, library, validateGeometry = false) {
451
+ if (!entry.appearance.shapeRef) return;
452
+ const definition = assertShapeReference(entry.appearance.shapeRef, library);
453
+ if (!validateGeometry) return;
454
+ if (entry.route || !entry.bounds)
455
+ throw new TypeError(`Element ${entry.elementId}: connectors cannot reference library shapes.`);
456
+ if (
457
+ entry.bounds.width < definition.sizing.minWidth ||
458
+ entry.bounds.height < definition.sizing.minHeight
459
+ )
460
+ throw new TypeError(
461
+ `Element ${entry.elementId}: saved size is below shape minimum ${definition.sizing.minWidth} by ${definition.sizing.minHeight}.`,
462
+ );
463
+ }
464
+ function updateReferencedPlacements(operation, placements, library) {
465
+ if (operation.type === 'insert-elements' || operation.type === 'remove-elements') {
466
+ for (const entry of operation.presentation) {
467
+ assertPlacementShape(entry, library);
468
+ if (operation.type === 'insert-elements') placements.set(entry.elementId, entry);
469
+ else placements.delete(entry.elementId);
470
+ }
471
+ return;
472
+ }
473
+ if (!['set-geometry', 'set-appearance-locks'].includes(operation.type)) return;
474
+ for (const change of operation.changes) {
475
+ const appearance = operation.type === 'set-appearance-locks';
476
+ if (appearance) {
477
+ assertPlacementShape(change.before, library);
478
+ assertPlacementShape(change.after, library);
479
+ }
480
+ const previous = placements.get(change.elementId);
481
+ if (previous)
482
+ placements.set(change.elementId, {
483
+ ...previous,
484
+ ...(appearance ? { appearance: change.after.appearance } : change.after),
485
+ });
486
+ }
487
+ }
488
+
489
+ function stripShapeReferences(item) {
490
+ if (!item || typeof item !== 'object') return;
491
+ if (item.appearance) delete item.appearance.shapeRef;
492
+ for (const child of Object.values(item)) stripShapeReferences(child);
493
+ }
494
+ function projectLibraryOperations(operations, basis) {
495
+ let library = basis.shapeLibrary ?? null;
496
+ let studio = basis.studioPresentation ?? null;
497
+ const placements = new Map(basis.presentation.elements.map((entry) => [entry.elementId, entry]));
498
+ const ordinary = [];
499
+ for (const operation of operations) {
500
+ if (operation.type === 'set-shape-library') {
501
+ assertChangedValue(operation, library, 'Shape library');
502
+ library = operation.after;
503
+ } else if (operation.type === 'set-studio-presentation') {
504
+ assertChangedValue(operation, studio, 'Studio presentation');
505
+ studio = operation.after;
506
+ } else {
507
+ updateReferencedPlacements(operation, placements, library);
508
+ const projected = structuredClone(operation);
509
+ stripShapeReferences(projected);
510
+ ordinary.push(projected);
511
+ }
512
+ }
513
+ for (const placement of placements.values()) assertPlacementShape(placement, library, true);
514
+ return ordinary;
515
+ }
516
+ function assertDiagramEditTransactionV12(value, options) {
517
+ if (validateJson(value, DIAGRAM_EDIT_TRANSACTION_V12_SCHEMA).length)
518
+ throw new TypeError('Invalid diagram transaction 1.2.0.');
519
+ const basis = options.baseBundle ?? options.bundle;
520
+ if (
521
+ options.baseBundle &&
522
+ options.bundle &&
523
+ canonicalizeJson(options.baseBundle) !== canonicalizeJson(options.bundle)
524
+ )
525
+ throw new TypeError('Conflicting transaction bundle contexts.');
526
+ const seenDefinitions = new Map();
527
+ for (const operation of value.operations) {
528
+ if (operation.type !== 'set-shape-library') continue;
529
+ assertLibraryOperation(operation);
530
+ for (const definition of [...(operation.before ?? []), ...(operation.after ?? [])]) {
531
+ const key = shapeReferenceKey(definition);
532
+ const previous = seenDefinitions.get(key);
533
+ if (previous && previous !== definition.definitionDigest)
534
+ throw new TypeError(
535
+ `Shape ${key}: immutable library definition changed within transaction.`,
536
+ );
537
+ seenDefinitions.set(key, definition.definitionDigest);
538
+ }
539
+ }
540
+ if (!basis) return value;
541
+ assertVersionedDiagramAuthoringBundle(basis);
542
+ if (
543
+ value.diagramId !== basis.diagramId ||
544
+ value.base.bundleDigest !== basis.bundleDigest ||
545
+ value.base.semanticDigest !== basis.document.documentDigest ||
546
+ value.base.presentationDigest !== basis.presentation.presentationDigest
547
+ )
548
+ throw new TypeError('Shape library transaction basis differs.');
549
+ const ordinary = projectLibraryOperations(value.operations, basis);
550
+ if (ordinary.length) {
551
+ const legacy = legacyDiagramAuthoringProjection(basis);
552
+ assertDiagramEditTransaction(
553
+ {
554
+ ...value,
555
+ schemaVersion: '1.0.0',
556
+ protocolVersion: '1.13.0',
557
+ base: {
558
+ ...value.base,
559
+ bundleDigest: legacy.bundleDigest,
560
+ presentationDigest: legacy.presentation.presentationDigest,
561
+ },
562
+ operations: ordinary,
563
+ },
564
+ { baseBundle: legacy },
565
+ );
566
+ }
567
+ return value;
568
+ }