archgraph-argo-beta 0.27.0-beta.2 → 0.27.0-beta.4

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.
@@ -259,8 +259,105 @@ function validateViewElementLimits(document, errors, options = {}) {
259
259
  }
260
260
  }
261
261
 
262
+ // Per-element-type attribute contract (issue #3): required attributes, a
263
+ // controlled vocabulary per attribute (enumByAttr) and uniqueness per attribute.
264
+ // Supplied by the active schema bundle's `attributesByElementType`; absent => no-op
265
+ // (fully backward compatible).
266
+ function attributeEntriesByName(element) {
267
+ const map = new Map();
268
+ const entries = Array.isArray(element && element.attributes) ? element.attributes : [];
269
+ for (const entry of entries) {
270
+ if (!entry || typeof entry !== 'object' || typeof entry.name !== 'string' || entry.name === '') {
271
+ continue;
272
+ }
273
+ if (!map.has(entry.name)) {
274
+ map.set(entry.name, []);
275
+ }
276
+ map.get(entry.name).push(entry);
277
+ }
278
+ return map;
279
+ }
280
+
281
+ function attributeValueOf(entry) {
282
+ if (entry.value !== undefined && entry.value !== null) {
283
+ return entry.value;
284
+ }
285
+ if (entry.content !== undefined && entry.content !== null) {
286
+ return entry.content;
287
+ }
288
+ return undefined;
289
+ }
290
+
291
+ function validateAttributeContracts(document, errors, ontology) {
292
+ const language = resolveOntology(ontology);
293
+ const contracts = language.attributesByElementType;
294
+ if (!contracts || typeof contracts !== 'object') {
295
+ return;
296
+ }
297
+ const uniqueTrackers = new Map();
298
+ for (const type of Object.keys(contracts)) {
299
+ uniqueTrackers.set(type, new Map());
300
+ }
301
+
302
+ for (const element of document.elements || []) {
303
+ if (!element || typeof element !== 'object') {
304
+ continue;
305
+ }
306
+ const contract = contracts[element.type];
307
+ if (!contract || typeof contract !== 'object') {
308
+ continue;
309
+ }
310
+ const byName = attributeEntriesByName(element);
311
+
312
+ for (const name of Array.isArray(contract.required) ? contract.required : []) {
313
+ const entries = byName.get(name);
314
+ const present = Array.isArray(entries) && entries.some((entry) => {
315
+ const value = attributeValueOf(entry);
316
+ return value !== undefined && value !== '';
317
+ });
318
+ if (!present) {
319
+ errors.push(`element '${element.id}' (type '${element.type}') is missing required attribute '${name}'`);
320
+ }
321
+ }
322
+
323
+ const enumByAttr = contract.enumByAttr && typeof contract.enumByAttr === 'object' ? contract.enumByAttr : {};
324
+ for (const [attr, allowed] of Object.entries(enumByAttr)) {
325
+ if (!Array.isArray(allowed)) {
326
+ continue;
327
+ }
328
+ for (const entry of byName.get(attr) || []) {
329
+ const value = attributeValueOf(entry);
330
+ if (value === undefined) {
331
+ continue;
332
+ }
333
+ const matches = allowed.some((option) => option === value || JSON.stringify(option) === JSON.stringify(value));
334
+ if (!matches) {
335
+ errors.push(`element '${element.id}' (type '${element.type}') attribute '${attr}' value ${JSON.stringify(value)} is not one of: ${allowed.map((option) => JSON.stringify(option)).join(', ')}`);
336
+ }
337
+ }
338
+ }
339
+
340
+ for (const attr of Array.isArray(contract.unique) ? contract.unique : []) {
341
+ const tracker = uniqueTrackers.get(element.type);
342
+ for (const entry of byName.get(attr) || []) {
343
+ const value = attributeValueOf(entry);
344
+ if (value === undefined) {
345
+ continue;
346
+ }
347
+ const key = JSON.stringify(value);
348
+ if (tracker.has(key) && tracker.get(key) !== element.id) {
349
+ errors.push(`element '${element.id}' (type '${element.type}') attribute '${attr}' value ${key} duplicates element '${tracker.get(key)}'`);
350
+ } else if (!tracker.has(key)) {
351
+ tracker.set(key, element.id);
352
+ }
353
+ }
354
+ }
355
+ }
356
+ }
357
+
262
358
  module.exports = {
263
359
  validateGraphSemantics,
264
360
  validateArchiMateEndpointMatrix,
265
361
  validateViewElementLimits,
362
+ validateAttributeContracts,
266
363
  };
@@ -99,7 +99,8 @@ function relativeLabel(workspaceRoot, absolutePath) {
99
99
 
100
100
  function buildBundle(kind, dir, workspaceRoot) {
101
101
  const schemaFile = path.join(dir, SCHEMA_BASENAME);
102
- const schema = readJsonFile(schemaFile);
102
+ const schemaExists = isFile(schemaFile);
103
+ const schema = schemaExists ? readJsonFile(schemaFile) : null;
103
104
 
104
105
  const configFile = path.join(dir, CONFIG_BASENAME);
105
106
  const fileConfig = isFile(configFile) ? readJsonFile(configFile) : {};
@@ -135,10 +136,9 @@ function buildBundle(kind, dir, workspaceRoot) {
135
136
  kind,
136
137
  dir,
137
138
  relativeDir: relativeLabel(workspaceRoot, dir),
138
- schema: {
139
- absolutePath: schemaFile,
140
- relativePath: relativeLabel(workspaceRoot, schemaFile),
141
- },
139
+ schema: schemaExists
140
+ ? { absolutePath: schemaFile, relativePath: relativeLabel(workspaceRoot, schemaFile) }
141
+ : null,
142
142
  schemaDocument: schema,
143
143
  config: {
144
144
  filePath: isFile(configFile) ? { absolutePath: configFile, relativePath: relativeLabel(workspaceRoot, configFile) } : null,
@@ -154,6 +154,145 @@ function buildBundle(kind, dir, workspaceRoot) {
154
154
  };
155
155
  }
156
156
 
157
+ // --- Bundle inheritance (issue #4) -----------------------------------------
158
+ // A bundle may declare `extends` to inherit a base bundle (the built-in default,
159
+ // or another bundle directory) and add/override on top of it instead of forking
160
+ // the whole rules file. `addElementTypes` / `addRelationships` / `overrideMatrix`
161
+ // are the delta; the effective element universe becomes base ∪ add (single
162
+ // source of truth), matrix/metadata merge by key.
163
+
164
+ function bundleConfig(dir) {
165
+ const configFile = path.join(dir, CONFIG_BASENAME);
166
+ if (!isFile(configFile)) {
167
+ return {};
168
+ }
169
+ try {
170
+ return readJsonFile(configFile);
171
+ } catch {
172
+ return {};
173
+ }
174
+ }
175
+
176
+ function hasExtendsConfig(dir) {
177
+ const config = bundleConfig(dir);
178
+ return typeof config.extends === 'string' && config.extends.trim() !== '';
179
+ }
180
+
181
+ function resolveBaseBundleDir(ext, childDir) {
182
+ const value = String(ext).trim();
183
+ // Reserved, language-neutral name for the built-in default bundle. Any other
184
+ // value is a path to another bundle directory — the framework never hardcodes a
185
+ // modeling-language name (ArchiMate or otherwise) into bundle resolution.
186
+ if (value === 'default') {
187
+ return path.join(getArgoRoot(), 'schema');
188
+ }
189
+ return path.resolve(childDir, value);
190
+ }
191
+
192
+ function deepCloneJson(value) {
193
+ return value === undefined ? undefined : JSON.parse(JSON.stringify(value));
194
+ }
195
+
196
+ function mergeMatrixInto(target, source) {
197
+ if (!source || typeof source !== 'object') {
198
+ return target;
199
+ }
200
+ for (const [relationshipType, bySource] of Object.entries(source)) {
201
+ if (!bySource || typeof bySource !== 'object') {
202
+ target[relationshipType] = deepCloneJson(bySource);
203
+ continue;
204
+ }
205
+ if (!target[relationshipType] || typeof target[relationshipType] !== 'object') {
206
+ target[relationshipType] = {};
207
+ }
208
+ for (const [sourceType, targets] of Object.entries(bySource)) {
209
+ target[relationshipType][sourceType] = deepCloneJson(targets);
210
+ }
211
+ }
212
+ return target;
213
+ }
214
+
215
+ function mergeExtendsBundle(base, child) {
216
+ const baseRules = base.rules || {};
217
+ const childRules = child.rules || {};
218
+ const config = { ...(base.config || {}), ...(child.config || {}) };
219
+
220
+ const elementTypeMetadata = { ...(baseRules.elementTypeMetadata || {}), ...(childRules.elementTypeMetadata || {}) };
221
+ const archimateClassByElementType = { ...(baseRules.archimateClassByElementType || {}), ...(childRules.archimateClassByElementType || {}) };
222
+ const relationshipCategoryByType = { ...(baseRules.relationshipCategoryByType || {}), ...(childRules.relationshipCategoryByType || {}) };
223
+
224
+ const addElementTypes = config.addElementTypes && typeof config.addElementTypes === 'object' ? config.addElementTypes : {};
225
+ for (const [type, meta] of Object.entries(addElementTypes)) {
226
+ if (!elementTypeMetadata[type]) {
227
+ elementTypeMetadata[type] = { layer: (meta && meta.layer) || null, aspect: (meta && meta.aspect) || null };
228
+ }
229
+ if (meta && typeof meta.class === 'string' && meta.class !== '') {
230
+ archimateClassByElementType[type] = meta.class;
231
+ }
232
+ }
233
+ const addRelationships = config.addRelationships && typeof config.addRelationships === 'object' ? config.addRelationships : {};
234
+ for (const [type, category] of Object.entries(addRelationships)) {
235
+ relationshipCategoryByType[type] = category;
236
+ }
237
+
238
+ // Guarantee base ∪ add for the element/relationship universe regardless of the
239
+ // base dialect (class-matrix derives types from rules metadata, type-matrix from
240
+ // schema enums) — an inheriting Profile must never silently drop a base type.
241
+ const baseOntology = buildOntology(base);
242
+ for (const type of baseOntology.elementTypes) {
243
+ if (!elementTypeMetadata[type]) {
244
+ elementTypeMetadata[type] = { layer: null, aspect: null };
245
+ }
246
+ }
247
+ for (const type of baseOntology.relationshipTypes) {
248
+ if (!relationshipCategoryByType[type]) {
249
+ relationshipCategoryByType[type] = 'Custom';
250
+ }
251
+ }
252
+
253
+ const relationshipTargetMatrix = deepCloneJson(baseRules.relationshipTargetMatrix || {}) || {};
254
+ mergeMatrixInto(relationshipTargetMatrix, childRules.relationshipTargetMatrix || {});
255
+ mergeMatrixInto(relationshipTargetMatrix, config.overrideMatrix || {});
256
+
257
+ const dialect = childRules.dialect || baseRules.dialect || 'archimate-class-matrix';
258
+ const rules = {
259
+ ...baseRules,
260
+ ...childRules,
261
+ dialect,
262
+ elementTypeMetadata,
263
+ archimateClassByElementType,
264
+ relationshipCategoryByType,
265
+ relationshipTargetMatrix,
266
+ };
267
+
268
+ return {
269
+ ...child,
270
+ schema: child.schema || base.schema,
271
+ schemaDocument: child.schemaDocument || base.schemaDocument,
272
+ rules,
273
+ config,
274
+ inheritedFrom: base.dir,
275
+ };
276
+ }
277
+
278
+ function applyExtends(bundle, workspaceRoot, seen = new Set()) {
279
+ const ext = bundle && bundle.config && typeof bundle.config.extends === 'string' ? bundle.config.extends.trim() : '';
280
+ if (!ext) {
281
+ return bundle;
282
+ }
283
+ seen.add(path.resolve(bundle.dir).toLowerCase());
284
+ const baseDir = resolveBaseBundleDir(ext, bundle.dir);
285
+ const baseKey = path.resolve(baseDir).toLowerCase();
286
+ if (seen.has(baseKey)) {
287
+ throw new Error(`schema bundle extends cycle detected at '${baseDir}'`);
288
+ }
289
+ if (!isFile(path.join(baseDir, SCHEMA_BASENAME)) && !hasExtendsConfig(baseDir)) {
290
+ throw new Error(`schema bundle extends '${ext}' could not be resolved: no schema bundle at '${baseDir}'`);
291
+ }
292
+ const baseBundle = applyExtends(buildBundle('extends', baseDir, workspaceRoot), workspaceRoot, seen);
293
+ return mergeExtendsBundle(baseBundle, bundle);
294
+ }
295
+
157
296
  function resolveSchemaBundle(workspaceRoot, options = {}) {
158
297
  const root = path.resolve(workspaceRoot || process.cwd());
159
298
  const candidates = [];
@@ -172,8 +311,8 @@ function resolveSchemaBundle(workspaceRoot, options = {}) {
172
311
  continue;
173
312
  }
174
313
  seen.add(key);
175
- if (isFile(path.join(candidate.dir, SCHEMA_BASENAME))) {
176
- return buildBundle(candidate.kind, candidate.dir, root);
314
+ if (isFile(path.join(candidate.dir, SCHEMA_BASENAME)) || hasExtendsConfig(candidate.dir)) {
315
+ return applyExtends(buildBundle(candidate.kind, candidate.dir, root), root);
177
316
  }
178
317
  }
179
318
 
@@ -258,7 +397,77 @@ function resolveActorElementType(config) {
258
397
  return DEFAULT_ACTOR_ELEMENT_TYPE;
259
398
  }
260
399
 
261
- function validateBundle({ language, dialect, elementTypes, relationshipTypes, actorElementType, matrix, deliveryDependencies }) {
400
+ // Per-element-type attribute contract (issue #3): declare that an element type
401
+ // must carry certain attributes, that some attribute values are a controlled
402
+ // vocabulary, and that some attribute values are unique within the type.
403
+ // { "Rule": { "required": ["ruleId","normativity"], "unique": ["ruleId"],
404
+ // "enumByAttr": { "normativity": ["MUST","SHOULD","MAY","MUST_NOT"] } } }
405
+ // Absent => no per-type attribute contract (backward compatible).
406
+ function resolveAttributeContracts(config) {
407
+ const raw = config && typeof config.attributesByElementType === 'object' && config.attributesByElementType !== null
408
+ ? config.attributesByElementType
409
+ : null;
410
+ if (!raw) {
411
+ return undefined;
412
+ }
413
+ const contracts = {};
414
+ for (const [type, contract] of Object.entries(raw)) {
415
+ if (!contract || typeof contract !== 'object') {
416
+ contracts[type] = {};
417
+ continue;
418
+ }
419
+ contracts[type] = {
420
+ required: Array.isArray(contract.required) ? contract.required.slice() : undefined,
421
+ unique: Array.isArray(contract.unique) ? contract.unique.slice() : undefined,
422
+ enumByAttr: contract.enumByAttr && typeof contract.enumByAttr === 'object' ? { ...contract.enumByAttr } : undefined,
423
+ };
424
+ }
425
+ return contracts;
426
+ }
427
+
428
+ function validateAttributeContracts(language, elementTypeList, contracts) {
429
+ const errors = [];
430
+ if (!contracts || typeof contracts !== 'object') {
431
+ return errors;
432
+ }
433
+ for (const [type, contract] of Object.entries(contracts)) {
434
+ if (!elementTypeList.includes(type)) {
435
+ errors.push(`schema bundle '${language}' attributesByElementType references unknown element type '${type}'`);
436
+ }
437
+ if (!contract || typeof contract !== 'object') {
438
+ continue;
439
+ }
440
+ for (const key of ['required', 'unique']) {
441
+ const list = contract[key];
442
+ if (list === undefined) {
443
+ continue;
444
+ }
445
+ if (!Array.isArray(list)) {
446
+ errors.push(`schema bundle '${language}' attributesByElementType['${type}'].${key} must be an array`);
447
+ continue;
448
+ }
449
+ for (const name of list) {
450
+ if (typeof name !== 'string' || name === '') {
451
+ errors.push(`schema bundle '${language}' attributesByElementType['${type}'].${key} entries must be non-empty strings`);
452
+ }
453
+ }
454
+ }
455
+ if (contract.enumByAttr !== undefined) {
456
+ if (!contract.enumByAttr || typeof contract.enumByAttr !== 'object') {
457
+ errors.push(`schema bundle '${language}' attributesByElementType['${type}'].enumByAttr must be an object`);
458
+ } else {
459
+ for (const [attr, allowed] of Object.entries(contract.enumByAttr)) {
460
+ if (!Array.isArray(allowed) || allowed.length === 0) {
461
+ errors.push(`schema bundle '${language}' attributesByElementType['${type}'].enumByAttr['${attr}'] must be a non-empty array`);
462
+ }
463
+ }
464
+ }
465
+ }
466
+ }
467
+ return errors;
468
+ }
469
+
470
+ function validateBundle({ language, dialect, elementTypes, relationshipTypes, actorElementType, matrix, deliveryDependencies, attributesByElementType }) {
262
471
  const errors = [];
263
472
  const elementTypeList = Array.isArray(elementTypes) ? elementTypes : [];
264
473
  const relationshipTypeList = Array.isArray(relationshipTypes) ? relationshipTypes : [];
@@ -304,6 +513,7 @@ function validateBundle({ language, dialect, elementTypes, relationshipTypes, ac
304
513
  }
305
514
 
306
515
  errors.push(...validateDeliveryDependencies(language, relationshipTypeList, deliveryDependencies));
516
+ errors.push(...validateAttributeContracts(language, elementTypeList, attributesByElementType));
307
517
 
308
518
  return { status: errors.length === 0 ? 'passed' : 'failed', errors };
309
519
  }
@@ -386,6 +596,7 @@ function buildClassMatrixOntology(bundle) {
386
596
  const relationshipTypes = Array.from(relationshipCategoryByType.keys());
387
597
  const actorElementType = resolveActorElementType(bundle.config);
388
598
  const deliveryDependencies = resolveDeliveryDependencies(bundle.config, 'archimate-class-matrix');
599
+ const attributesByElementType = resolveAttributeContracts(bundle.config);
389
600
  return finalizeOntology({
390
601
  kind: bundle.kind,
391
602
  dialect: 'archimate-class-matrix',
@@ -397,7 +608,8 @@ function buildClassMatrixOntology(bundle) {
397
608
  relationshipTypes,
398
609
  actorElementType,
399
610
  deliveryDependencies,
400
- bundleValidation: validateBundle({ language, dialect: 'archimate-class-matrix', elementTypes, relationshipTypes, actorElementType, matrix: null, deliveryDependencies }),
611
+ attributesByElementType,
612
+ bundleValidation: validateBundle({ language, dialect: 'archimate-class-matrix', elementTypes, relationshipTypes, actorElementType, matrix: null, deliveryDependencies, attributesByElementType }),
401
613
  elementTypeMetadata,
402
614
  relationshipCategoryByType,
403
615
  isSupportedElementType,
@@ -456,6 +668,7 @@ function buildTypeMatrixOntology(bundle) {
456
668
  const elementTypes = Array.from(elementTypeMetadata.keys());
457
669
  const relationshipTypes = Array.from(relationshipCategoryByType.keys());
458
670
  const deliveryDependencies = resolveDeliveryDependencies(config, 'type-matrix');
671
+ const attributesByElementType = resolveAttributeContracts(config);
459
672
  const getArchiMateClass = (elementOrType) => {
460
673
  const type = typeof elementOrType === 'string' ? elementOrType : elementOrType && elementOrType.type;
461
674
  return type;
@@ -494,7 +707,8 @@ function buildTypeMatrixOntology(bundle) {
494
707
  relationshipTypes,
495
708
  actorElementType,
496
709
  deliveryDependencies,
497
- bundleValidation: validateBundle({ language, dialect: 'type-matrix', elementTypes, relationshipTypes, actorElementType, matrix, deliveryDependencies }),
710
+ attributesByElementType,
711
+ bundleValidation: validateBundle({ language, dialect: 'type-matrix', elementTypes, relationshipTypes, actorElementType, matrix, deliveryDependencies, attributesByElementType }),
498
712
  elementTypeMetadata,
499
713
  relationshipCategoryByType,
500
714
  isSupportedElementType: (type) => elementTypeMetadata.has(type),
@@ -130,6 +130,7 @@ const {
130
130
  validateGraphSemantics,
131
131
  validateArchiMateEndpointMatrix,
132
132
  validateViewElementLimits,
133
+ validateAttributeContracts,
133
134
  } = require('./graph-semantics.js');
134
135
  const {
135
136
  loadSchemaBundleAndOntology,
@@ -616,6 +617,7 @@ function validateDocument(document, schema, options = {}) {
616
617
  }
617
618
  validateAgainstSchema(document, schema, '#', errors, schema);
618
619
  validateGraphSemantics(document, errors, ontology);
620
+ validateAttributeContracts(document, errors, ontology);
619
621
  validateArchiMateEndpointMatrix(document, errors, {
620
622
  ontology,
621
623
  touchedRelationshipIds: options.touchedRelationshipIds,
@@ -1389,6 +1391,207 @@ function resolveDuplicateConflict(options, candidates) {
1389
1391
  return { action: 'create', justification: options.justification };
1390
1392
  }
1391
1393
 
1394
+ function mutationNodeId(mutation) {
1395
+ if (!mutation || typeof mutation !== 'object') {
1396
+ return '(invalid)';
1397
+ }
1398
+ if (mutation.type === 'addElement') {
1399
+ return (mutation.element && mutation.element.id) || '(addElement)';
1400
+ }
1401
+ if (mutation.type === 'addRelationship') {
1402
+ return (mutation.relationship && mutation.relationship.id) || '(addRelationship)';
1403
+ }
1404
+ if (mutation.type === 'addView') {
1405
+ return (mutation.view && mutation.view.view_id) || '(addView)';
1406
+ }
1407
+ if (mutation.type === 'updateView') {
1408
+ return mutation.view_id || mutation.id || '(updateView)';
1409
+ }
1410
+ return mutation.id || mutation.view_id || `(${mutation.type})`;
1411
+ }
1412
+
1413
+ // Order a batch so it is order-independent: a mutation that references an object
1414
+ // created later in the SAME batch is applied after its producer. Dependencies:
1415
+ // addElement -> views it joins (view_ids)
1416
+ // addRelationship-> views it joins + its source/target elements
1417
+ // addView -> its parent element + included elements/relationships
1418
+ // update*/remove*-> the object they target (when that object is produced here)
1419
+ // A genuine cycle is reported with the id chain so the caller can split the batch.
1420
+ function orderMutationsForApplication(mutations) {
1421
+ const n = mutations.length;
1422
+ const producers = new Map();
1423
+ const addProducer = (key, index) => {
1424
+ if (!key) {
1425
+ return;
1426
+ }
1427
+ if (!producers.has(key)) {
1428
+ producers.set(key, []);
1429
+ }
1430
+ producers.get(key).push(index);
1431
+ };
1432
+
1433
+ mutations.forEach((mutation, index) => {
1434
+ if (!mutation || typeof mutation !== 'object') {
1435
+ return;
1436
+ }
1437
+ if (mutation.type === 'addElement' && mutation.element) {
1438
+ addProducer('element:' + mutation.element.id, index);
1439
+ }
1440
+ if (mutation.type === 'addRelationship' && mutation.relationship) {
1441
+ addProducer('relationship:' + mutation.relationship.id, index);
1442
+ }
1443
+ if (mutation.type === 'addView' && mutation.view) {
1444
+ addProducer('view:' + mutation.view.view_id, index);
1445
+ }
1446
+ });
1447
+
1448
+ const dependencies = mutations.map(() => new Set());
1449
+ mutations.forEach((mutation, index) => {
1450
+ if (!mutation || typeof mutation !== 'object') {
1451
+ return;
1452
+ }
1453
+ const requireKey = (key) => {
1454
+ const matches = producers.get(key);
1455
+ if (!matches) {
1456
+ return;
1457
+ }
1458
+ for (const producerIndex of matches) {
1459
+ if (producerIndex !== index) {
1460
+ dependencies[index].add(producerIndex);
1461
+ }
1462
+ }
1463
+ };
1464
+
1465
+ if (mutation.type === 'addElement') {
1466
+ for (const viewId of Array.isArray(mutation.view_ids) ? mutation.view_ids : []) {
1467
+ requireKey('view:' + viewId);
1468
+ }
1469
+ } else if (mutation.type === 'addRelationship') {
1470
+ for (const viewId of Array.isArray(mutation.view_ids) ? mutation.view_ids : []) {
1471
+ requireKey('view:' + viewId);
1472
+ }
1473
+ if (mutation.relationship) {
1474
+ requireKey('element:' + mutation.relationship.source_id);
1475
+ requireKey('element:' + mutation.relationship.target_id);
1476
+ }
1477
+ } else if (mutation.type === 'addView') {
1478
+ if (mutation.view) {
1479
+ requireKey('element:' + mutation.view.parent_element_id);
1480
+ for (const elementId of Array.isArray(mutation.view.included_elements) ? mutation.view.included_elements : []) {
1481
+ requireKey('element:' + elementId);
1482
+ }
1483
+ for (const relationshipId of Array.isArray(mutation.view.included_relationships) ? mutation.view.included_relationships : []) {
1484
+ requireKey('relationship:' + relationshipId);
1485
+ }
1486
+ }
1487
+ } else if (mutation.type === 'updateElement') {
1488
+ requireKey('element:' + mutation.id);
1489
+ } else if (mutation.type === 'updateRelationship') {
1490
+ requireKey('relationship:' + mutation.id);
1491
+ } else if (mutation.type === 'updateView') {
1492
+ requireKey('view:' + (mutation.view_id || mutation.id));
1493
+ } else if (mutation.type === 'removeView') {
1494
+ requireKey('view:' + mutation.view_id);
1495
+ } else if (mutation.type === 'removeElement') {
1496
+ requireKey('element:' + mutation.id);
1497
+ } else if (mutation.type === 'removeRelationship') {
1498
+ requireKey('relationship:' + mutation.id);
1499
+ }
1500
+ });
1501
+
1502
+ const indegree = mutations.map((_, index) => dependencies[index].size);
1503
+ const dependents = mutations.map(() => []);
1504
+ dependencies.forEach((set, index) => {
1505
+ for (const dependency of set) {
1506
+ dependents[dependency].push(index);
1507
+ }
1508
+ });
1509
+
1510
+ const remaining = new Set();
1511
+ for (let index = 0; index < n; index += 1) {
1512
+ remaining.add(index);
1513
+ }
1514
+ const ready = [];
1515
+ for (let index = 0; index < n; index += 1) {
1516
+ if (indegree[index] === 0) {
1517
+ ready.push(index);
1518
+ }
1519
+ }
1520
+ ready.sort((a, b) => a - b);
1521
+
1522
+ const ordered = [];
1523
+ while (ready.length > 0) {
1524
+ const index = ready.shift();
1525
+ if (!remaining.has(index)) {
1526
+ continue;
1527
+ }
1528
+ remaining.delete(index);
1529
+ ordered.push(mutations[index]);
1530
+ for (const dependent of dependents[index]) {
1531
+ indegree[dependent] -= 1;
1532
+ if (indegree[dependent] === 0) {
1533
+ ready.push(dependent);
1534
+ }
1535
+ }
1536
+ ready.sort((a, b) => a - b);
1537
+ }
1538
+
1539
+ if (ordered.length !== n) {
1540
+ const chain = findMutationCycle(mutations, dependencies, remaining);
1541
+ throw new Error(
1542
+ `Cyclic mutation dependencies in batch: ${chain.join(' -> ')}. `
1543
+ + 'Order the batch so each referenced object is created first, or split the mutually-dependent objects into separate calls.',
1544
+ );
1545
+ }
1546
+
1547
+ return ordered;
1548
+ }
1549
+
1550
+ function findMutationCycle(mutations, dependencies, remaining) {
1551
+ const visited = new Set();
1552
+ const inStack = new Set();
1553
+ const stack = [];
1554
+ let cycle = null;
1555
+
1556
+ const visit = (index) => {
1557
+ if (cycle) {
1558
+ return;
1559
+ }
1560
+ visited.add(index);
1561
+ inStack.add(index);
1562
+ stack.push(index);
1563
+ for (const dependency of dependencies[index]) {
1564
+ if (!remaining.has(dependency)) {
1565
+ continue;
1566
+ }
1567
+ if (inStack.has(dependency)) {
1568
+ cycle = stack.slice(stack.indexOf(dependency)).concat(dependency);
1569
+ return;
1570
+ }
1571
+ if (!visited.has(dependency)) {
1572
+ visit(dependency);
1573
+ }
1574
+ if (cycle) {
1575
+ return;
1576
+ }
1577
+ }
1578
+ inStack.delete(index);
1579
+ stack.pop();
1580
+ };
1581
+
1582
+ for (const index of remaining) {
1583
+ if (!visited.has(index)) {
1584
+ visit(index);
1585
+ }
1586
+ if (cycle) {
1587
+ break;
1588
+ }
1589
+ }
1590
+
1591
+ const chain = cycle || [...remaining];
1592
+ return chain.map((index) => mutationNodeId(mutations[index]));
1593
+ }
1594
+
1392
1595
  function applyMutations(document, mutations, options = {}) {
1393
1596
  const nextDocument = clone(document);
1394
1597
  const touchedElementIds = new Set();
@@ -1401,7 +1604,11 @@ function applyMutations(document, mutations, options = {}) {
1401
1604
  throw new Error('mutations must contain at least one mutation');
1402
1605
  }
1403
1606
 
1404
- for (const mutation of mutations) {
1607
+ // Apply in dependency order so a batch is order-independent (see
1608
+ // orderMutationsForApplication); a genuine cycle throws with the id chain.
1609
+ const orderedMutations = orderMutationsForApplication(mutations);
1610
+
1611
+ for (const mutation of orderedMutations) {
1405
1612
  if (!mutation || typeof mutation !== 'object' || !HANDLED_MUTATION_TYPES.has(mutation.type)) {
1406
1613
  throw new Error(`Unsupported mutation type: ${mutation && mutation.type}`);
1407
1614
  }
@@ -17,6 +17,7 @@ const {
17
17
  validateGraphSemantics,
18
18
  validateArchiMateEndpointMatrix,
19
19
  validateViewElementLimits,
20
+ validateAttributeContracts,
20
21
  } = require('./graph-semantics.js');
21
22
 
22
23
  function main() {
@@ -43,6 +44,7 @@ function main() {
43
44
  }
44
45
  validateAgainstSchema(document, schema, '#', errors, schema);
45
46
  validateGraphSemantics(document, errors, ontology);
47
+ validateAttributeContracts(document, errors, ontology);
46
48
  validateArchiMateEndpointMatrix(document, errors, { ontology });
47
49
  validateViewElementLimits(document, errors, { ontology });
48
50
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "archgraph-argo-beta",
3
- "version": "0.27.0-beta.2",
3
+ "version": "0.27.0-beta.4",
4
4
  "description": "Deploy the ArchGraph ARGO toolchain, skills, and rules (schema, scripts, argo-init skill, global rule) with one command.",
5
5
  "license": "MIT",
6
6
  "bin": {