@atolis-hq/corum 0.1.17 → 0.1.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -131,6 +131,25 @@ Options:
131
131
  --graph <path> Override the graph directory
132
132
  ```
133
133
 
134
+ #### `corum import asyncapi <spec>`
135
+
136
+ Import an AsyncAPI spec directly.
137
+
138
+ ```bash
139
+ corum import asyncapi <spec> [options]
140
+
141
+ Options:
142
+ --component-strategy <strategy> Component mapping: channel-segment (default), channel-pattern,
143
+ name-segment, name-pattern, tag, hardcoded
144
+ --separator <char> Separator for segment strategies (default: .)
145
+ --segment <n> Segment index (negative counts from end)
146
+ --pattern <regex> Regex pattern for pattern strategies
147
+ --component <name> Component name (hardcoded strategy)
148
+ --event-classification <mode> always-integration (default) or always-domain
149
+ --include-consumed Also import receive (consumed) operations
150
+ --graph <path> Override the graph directory
151
+ ```
152
+
134
153
  ## Configuration
135
154
 
136
155
  Run `corum init` to generate a `.corum/config.yaml` with all available options. Corum walks up from the current directory to find it, so you can place it at your project root.
@@ -0,0 +1,12 @@
1
+ import { parseSpec } from './parser.js';
2
+ import { mapDocument } from './mapper.js';
3
+ export class AsyncAPIAdapter {
4
+ adapterId = 'asyncapi';
5
+ async import(entry, context) {
6
+ const { document, diagnostics } = await parseSpec(entry.spec);
7
+ if (!document)
8
+ return { nodes: [], edges: [], diagnostics };
9
+ const { nodes, edges, diagnostics: mapDiagnostics } = mapDocument(document, entry, context.packConfig);
10
+ return { nodes, edges, diagnostics: [...diagnostics, ...mapDiagnostics] };
11
+ }
12
+ }
@@ -0,0 +1,507 @@
1
+ export function extractValue(strategy, operation, message) {
2
+ switch (strategy.strategy) {
3
+ case 'channel-segment': {
4
+ const address = operation.channels().all()[0]?.address() ?? '';
5
+ const parts = address.split(strategy.separator).filter(s => s.length > 0);
6
+ const idx = strategy.segment < 0 ? parts.length + strategy.segment : strategy.segment;
7
+ return parts[idx];
8
+ }
9
+ case 'channel-pattern': {
10
+ const address = operation.channels().all()[0]?.address() ?? '';
11
+ const match = address.match(strategy.pattern);
12
+ return match?.[1] ?? match?.[0];
13
+ }
14
+ case 'name-segment': {
15
+ const source = message.name() ?? message.id();
16
+ if (!source)
17
+ return undefined;
18
+ const parts = source.split(strategy.separator).filter(s => s.length > 0);
19
+ const idx = strategy.segment < 0 ? parts.length + strategy.segment : strategy.segment;
20
+ return parts[idx];
21
+ }
22
+ case 'name-pattern': {
23
+ const source = message.name() ?? message.id();
24
+ if (!source)
25
+ return undefined;
26
+ const match = source.match(strategy.pattern);
27
+ return match?.[1] ?? match?.[0];
28
+ }
29
+ case 'tag': {
30
+ const msgTags = message.tags().all();
31
+ if (msgTags.length > 0)
32
+ return msgTags[0].name();
33
+ const opTagsFn = operation.tags;
34
+ const opTags = opTagsFn?.()?.all?.() ?? [];
35
+ return opTags[0]?.name();
36
+ }
37
+ case 'hardcoded':
38
+ return strategy.value;
39
+ }
40
+ }
41
+ function unwrapPayload(payload) {
42
+ if (!payload || typeof payload !== 'object')
43
+ return payload;
44
+ const p = payload;
45
+ if (p.schemaFormat !== undefined && p.schema !== undefined && typeof p.schema === 'object')
46
+ return p.schema;
47
+ return payload;
48
+ }
49
+ export function deriveScalarType(type, format, scalarTypes) {
50
+ if (format && scalarTypes[`${type}/${format}`])
51
+ return scalarTypes[`${type}/${format}`];
52
+ return scalarTypes[type];
53
+ }
54
+ export function deriveMessageName(message, namingCtx, _specPath) {
55
+ const rawName = message.name();
56
+ const rawId = message.id();
57
+ if (!rawName && (!rawId || rawId.startsWith('<anonymous')))
58
+ return null;
59
+ if (!rawName && !namingCtx)
60
+ return null;
61
+ const extracted = namingCtx
62
+ ? extractValue(namingCtx.strategy, namingCtx.operation, message)
63
+ : rawName;
64
+ if (!extracted)
65
+ return null;
66
+ return { name: extracted };
67
+ }
68
+ export function classifyEvent(classification, operation, message) {
69
+ if (!classification)
70
+ return 'IntegrationEvent';
71
+ if (!('from' in classification)) {
72
+ return classification.strategy === 'always-domain' ? 'DomainEvent' : 'IntegrationEvent';
73
+ }
74
+ const value = extractValue(classification.from, operation, message);
75
+ return value === classification.domainValue ? 'DomainEvent' : 'IntegrationEvent';
76
+ }
77
+ export function deriveNodeId(kind, component, name, opts) {
78
+ if (kind === 'event')
79
+ return `${component}.${opts?.template ?? 'IntegrationEvent'}.${name}`;
80
+ return `${opts.parentId}.${opts.section}.${name}`;
81
+ }
82
+ // Extract the original component schema name from a resolved schema object.
83
+ // @asyncapi/parser resolves $refs inline but tags each resolved object with
84
+ // x-parser-schema-id equal to the component schema name (non-anonymous schemas
85
+ // have a plain name; anonymous ones get "<anonymous-schema-N>").
86
+ // Falls back to parsing a literal $ref string for test mocks that don't resolve.
87
+ function componentSchemaIdOf(obj) {
88
+ if (!obj || typeof obj !== 'object')
89
+ return undefined;
90
+ const o = obj;
91
+ const xId = o['x-parser-schema-id'];
92
+ if (typeof xId === 'string' && !xId.startsWith('<'))
93
+ return xId;
94
+ const ref = o['$ref'];
95
+ if (typeof ref === 'string' && ref.startsWith('#/components/schemas/'))
96
+ return ref.slice('#/components/schemas/'.length);
97
+ return undefined;
98
+ }
99
+ export function countMessageSchemaUsage(document) {
100
+ const rawDoc = document.json();
101
+ const componentSchemaNames = new Set(Object.keys(rawDoc.components?.schemas ?? {}));
102
+ const schemaToMessages = new Map();
103
+ function register(schemaName, msgName) {
104
+ if (!componentSchemaNames.has(schemaName))
105
+ return;
106
+ if (!schemaToMessages.has(schemaName))
107
+ schemaToMessages.set(schemaName, new Set());
108
+ schemaToMessages.get(schemaName).add(msgName);
109
+ }
110
+ function collectRefs(obj, msgName) {
111
+ if (!obj || typeof obj !== 'object')
112
+ return;
113
+ const id = componentSchemaIdOf(obj);
114
+ if (id)
115
+ register(id, msgName);
116
+ const o = obj;
117
+ if (o.properties)
118
+ for (const v of Object.values(o.properties))
119
+ collectRefs(v, msgName);
120
+ if (o.items)
121
+ collectRefs(o.items, msgName);
122
+ }
123
+ for (const operation of document.allOperations()) {
124
+ for (const message of operation.messages().all()) {
125
+ const msgName = message.name() ?? message.id();
126
+ if (!msgName)
127
+ continue;
128
+ const msgJson = message.json();
129
+ if (msgJson.payload)
130
+ collectRefs(unwrapPayload(msgJson.payload), msgName);
131
+ }
132
+ }
133
+ const counts = new Map();
134
+ for (const [name, names] of schemaToMessages)
135
+ counts.set(name, names.size);
136
+ return counts;
137
+ }
138
+ export function collectSharedSchemaNames(document, counts) {
139
+ const rawDoc = document.json();
140
+ const shared = new Set();
141
+ for (const [name, count] of counts) {
142
+ if (count >= 2)
143
+ shared.add(name);
144
+ }
145
+ function schemaReferences(schema, names) {
146
+ const refs = new Set();
147
+ function walk(obj) {
148
+ if (!obj || typeof obj !== 'object')
149
+ return;
150
+ const id = componentSchemaIdOf(obj);
151
+ if (id && names.has(id))
152
+ refs.add(id);
153
+ const o = obj;
154
+ if (o.properties)
155
+ for (const v of Object.values(o.properties))
156
+ walk(v);
157
+ if (o.items)
158
+ walk(o.items);
159
+ }
160
+ walk(schema);
161
+ return refs;
162
+ }
163
+ const candidateNames = new Set(Object.keys(rawDoc.components?.schemas ?? {}));
164
+ let changed = true;
165
+ while (changed) {
166
+ changed = false;
167
+ for (const [candidateName] of Object.entries(rawDoc.components?.schemas ?? {})) {
168
+ if (shared.has(candidateName))
169
+ continue;
170
+ for (const sharedName of shared) {
171
+ const sharedSchema = rawDoc.components?.schemas?.[sharedName];
172
+ const refs = schemaReferences(sharedSchema, candidateNames);
173
+ if (refs.has(candidateName)) {
174
+ shared.add(candidateName);
175
+ changed = true;
176
+ break;
177
+ }
178
+ }
179
+ }
180
+ }
181
+ return shared;
182
+ }
183
+ export function extractHeaders(rawHeaders, scalarTypes, specPath) {
184
+ if (!rawHeaders || typeof rawHeaders !== 'object')
185
+ return null;
186
+ const h = rawHeaders;
187
+ if (!h.properties || Object.keys(h.properties).length === 0)
188
+ return null;
189
+ const headers = {};
190
+ const diagnostics = [];
191
+ for (const [name, rawDef] of Object.entries(h.properties)) {
192
+ const def = rawDef;
193
+ const rawType = Array.isArray(def.type) ? (def.type.find(t => t !== 'null') ?? 'string') : (def.type ?? 'string');
194
+ if (rawType === 'object') {
195
+ diagnostics.push({ severity: 'warning', file: specPath, message: `Header "${name}" is a nested object — skipping` });
196
+ continue;
197
+ }
198
+ const scalarType = deriveScalarType(rawType, def.format, scalarTypes) ?? 'string';
199
+ const required = Array.isArray(h.required) && h.required.includes(name);
200
+ const entry = { type: scalarType, required };
201
+ if (def.description)
202
+ entry.description = def.description;
203
+ headers[name] = entry;
204
+ }
205
+ return { headers, diagnostics };
206
+ }
207
+ export function mapDocument(document, entry, packConfig) {
208
+ const nodes = [];
209
+ const edges = [];
210
+ const diagnostics = [];
211
+ const sharedSchemas = new Map();
212
+ const sourceSchemas = new Map();
213
+ const rawDoc = document.json();
214
+ for (const [name, schema] of Object.entries(rawDoc.components?.schemas ?? {})) {
215
+ sourceSchemas.set(name, schema);
216
+ }
217
+ const schemaCounts = countMessageSchemaUsage(document);
218
+ const sharedSchemaNames = collectSharedSchemaNames(document, schemaCounts);
219
+ const schemaComponents = new Map();
220
+ for (const operation of document.allOperations()) {
221
+ for (const message of operation.messages().all()) {
222
+ const component = extractValue(entry.componentMapping, operation, message);
223
+ if (!component)
224
+ continue;
225
+ const msgName = message.name() ?? message.id();
226
+ if (!msgName)
227
+ continue;
228
+ const msgJson = message.json();
229
+ const resolvedComponent = component;
230
+ function walkForComponent(obj) {
231
+ if (!obj || typeof obj !== 'object')
232
+ return;
233
+ const id = componentSchemaIdOf(obj);
234
+ if (id && sourceSchemas.has(id)) {
235
+ const existing = schemaComponents.get(id);
236
+ if (!existing)
237
+ schemaComponents.set(id, resolvedComponent);
238
+ else if (existing !== resolvedComponent)
239
+ schemaComponents.set(id, 'shared');
240
+ }
241
+ const o = obj;
242
+ if (o.properties)
243
+ for (const v of Object.values(o.properties))
244
+ walkForComponent(v);
245
+ if (o.items)
246
+ walkForComponent(o.items);
247
+ }
248
+ if (msgJson.payload)
249
+ walkForComponent(unwrapPayload(msgJson.payload));
250
+ }
251
+ }
252
+ for (const [name, schema] of Object.entries(rawDoc.components?.schemas ?? {})) {
253
+ const s = schema;
254
+ const component = schemaComponents.get(name) ?? 'shared';
255
+ if (s.enum) {
256
+ sharedSchemas.set(name, `${component}.EnumDefinition.${name}`);
257
+ }
258
+ else if (sharedSchemaNames.has(name)) {
259
+ sharedSchemas.set(name, `${component}.Schema.${name}`);
260
+ }
261
+ }
262
+ for (const [name, schema] of Object.entries(rawDoc.components?.schemas ?? {})) {
263
+ const s = schema;
264
+ const registeredId = sharedSchemas.get(name);
265
+ if (!registeredId)
266
+ continue;
267
+ if (s.enum) {
268
+ const [component] = registeredId.split('.');
269
+ nodes.push(makeNode(packConfig.constructs['enumDefinition']?.template ?? 'EnumDefinition', component, entry.spec, registeredId));
270
+ for (const value of s.enum) {
271
+ const valueId = deriveNodeId('enumValue', component, String(value), { parentId: registeredId, section: 'values' });
272
+ const valueNode = makeNode(packConfig.constructs['enumValue']?.template ?? 'EnumValue', component, entry.spec, valueId);
273
+ valueNode.properties = { name: String(value) };
274
+ nodes.push(valueNode);
275
+ edges.push({ id: `${registeredId}__has-value__${valueId}`, from: registeredId, to: valueId, type: 'has-value', state: 'implemented', stability: 'unstable' });
276
+ }
277
+ continue;
278
+ }
279
+ if (!sharedSchemaNames.has(name))
280
+ continue;
281
+ const [component] = registeredId.split('.');
282
+ nodes.push(makeNode(packConfig.constructs['payloadSchema']?.template ?? 'Schema', component, entry.spec, registeredId));
283
+ emitFields(s, registeredId, 'fields', undefined, packConfig, entry.spec, nodes, edges, diagnostics, sharedSchemas, sourceSchemas, new Map());
284
+ }
285
+ const seenMessages = new Map();
286
+ const allOperations = document.allOperations().all();
287
+ const operations = entry.includeConsumed ? allOperations : allOperations.filter(op => op.action() === 'send');
288
+ for (const operation of operations) {
289
+ const channelAddress = operation.channels().all()[0]?.address() ?? '';
290
+ for (const message of operation.messages().all()) {
291
+ const component = extractValue(entry.componentMapping, operation, message);
292
+ if (!component) {
293
+ diagnostics.push({ severity: 'warning', file: entry.spec, message: `Cannot derive component for message on channel "${channelAddress}" — skipping` });
294
+ continue;
295
+ }
296
+ const namingCtx = entry.messageNaming ? { strategy: entry.messageNaming, operation } : undefined;
297
+ const nameResult = deriveMessageName(message, namingCtx, entry.spec);
298
+ if (!nameResult) {
299
+ const hasId = message.id() && !message.id().startsWith('<anonymous');
300
+ diagnostics.push({
301
+ severity: hasId ? 'warning' : 'error',
302
+ file: entry.spec,
303
+ message: hasId
304
+ ? `Cannot derive name for message on channel "${channelAddress}" — skipping. Set message.name or configure messageNaming.`
305
+ : `Anonymous message on channel "${channelAddress}" — skipping (no name or id)`,
306
+ });
307
+ continue;
308
+ }
309
+ const messageName = nameResult.name;
310
+ if (seenMessages.has(messageName)) {
311
+ diagnostics.push({ severity: 'warning', file: entry.spec, message: `[INFO] Message "${messageName}" also on channel "${channelAddress}" — using first channel "${seenMessages.get(messageName)}"` });
312
+ continue;
313
+ }
314
+ seenMessages.set(messageName, channelAddress);
315
+ const eventTemplate = classifyEvent(entry.eventClassification, operation, message);
316
+ const eventId = deriveNodeId('event', component, messageName, { template: eventTemplate });
317
+ const eventNode = makeNode(eventTemplate, component, entry.spec, eventId);
318
+ const msgRaw = message.json();
319
+ const properties = { topic: channelAddress };
320
+ if (msgRaw.description)
321
+ properties.description = String(msgRaw.description);
322
+ const rawPayload = unwrapPayload(msgRaw.payload);
323
+ if (rawPayload) {
324
+ const payloadSchemaName = componentSchemaIdOf(rawPayload);
325
+ if (payloadSchemaName) {
326
+ const globalId = sharedSchemas.get(payloadSchemaName);
327
+ if (globalId) {
328
+ emitReadsEdge(eventId, globalId, edges);
329
+ properties.payload = globalId;
330
+ }
331
+ else {
332
+ const sourceSchema = sourceSchemas.get(payloadSchemaName);
333
+ if (sourceSchema) {
334
+ const schemaKey = payloadSchemaName;
335
+ const schemaId = deriveNodeId('schema', component, schemaKey, { parentId: eventId, section: 'schemas' });
336
+ nodes.push(makeNode(packConfig.constructs['payloadSchema']?.template ?? 'Schema', component, entry.spec, schemaId));
337
+ edges.push({ id: `${eventId}__has-field__${schemaId}`, from: eventId, to: schemaId, type: 'has-field', state: 'implemented', stability: 'unstable' });
338
+ emitFields(sourceSchema, schemaId, 'fields', eventId, packConfig, entry.spec, nodes, edges, diagnostics, sharedSchemas, sourceSchemas, new Map());
339
+ properties.payload = `#/schemas/${schemaKey}`;
340
+ }
341
+ }
342
+ }
343
+ else if (rawPayload.type === 'object' && rawPayload.properties) {
344
+ const schemaId = deriveNodeId('schema', component, messageName, { parentId: eventId, section: 'schemas' });
345
+ nodes.push(makeNode(packConfig.constructs['payloadSchema']?.template ?? 'Schema', component, entry.spec, schemaId));
346
+ edges.push({ id: `${eventId}__has-field__${schemaId}`, from: eventId, to: schemaId, type: 'has-field', state: 'implemented', stability: 'unstable' });
347
+ emitFields(rawPayload, schemaId, 'fields', eventId, packConfig, entry.spec, nodes, edges, diagnostics, sharedSchemas, sourceSchemas, new Map());
348
+ properties.payload = `#/schemas/${messageName}`;
349
+ }
350
+ else {
351
+ const primitiveType = Array.isArray(rawPayload.type) ? rawPayload.type.find(t => t !== 'null') : rawPayload.type;
352
+ if (primitiveType && primitiveType !== 'object') {
353
+ diagnostics.push({ severity: 'warning', file: entry.spec, message: `Message "${messageName}" has scalar payload (type: ${primitiveType}) — Event created with no schemas section` });
354
+ }
355
+ }
356
+ }
357
+ if (message.hasHeaders()) {
358
+ const rawHeaders = msgRaw.headers ?? null;
359
+ const headerResult = extractHeaders(rawHeaders, packConfig.scalarTypes, entry.spec);
360
+ if (headerResult) {
361
+ diagnostics.push(...headerResult.diagnostics);
362
+ if (Object.keys(headerResult.headers).length > 0)
363
+ properties.headers = headerResult.headers;
364
+ }
365
+ }
366
+ eventNode.properties = properties;
367
+ nodes.push(eventNode);
368
+ }
369
+ }
370
+ return { nodes, edges, diagnostics };
371
+ }
372
+ function makeNode(template, component, specPath, id) {
373
+ return {
374
+ id,
375
+ template,
376
+ component,
377
+ state: 'implemented',
378
+ stability: 'unstable',
379
+ schemaVersion: '1',
380
+ lastModifiedAt: new Date().toISOString().split('T')[0],
381
+ extractedFrom: specPath,
382
+ derivation: 'determined',
383
+ derivedBy: 'adapter:asyncapi',
384
+ properties: {},
385
+ };
386
+ }
387
+ function emitReadsEdge(from, to, edges) {
388
+ const id = `${from}__reads__${to}`;
389
+ if (!edges.some(e => e.id === id)) {
390
+ edges.push({ id, from, to, type: 'reads', state: 'implemented', stability: 'unstable' });
391
+ }
392
+ }
393
+ function refName(ref) {
394
+ return ref.split('/').pop() ?? ref;
395
+ }
396
+ function isRefSchema(schema) {
397
+ return typeof schema === 'object' && schema !== null && '$ref' in schema;
398
+ }
399
+ function resolveAllOfRef(schema) {
400
+ if (isRefSchema(schema))
401
+ return schema;
402
+ const s = schema;
403
+ if (Array.isArray(s.allOf) && s.allOf.length === 1 && isRefSchema(s.allOf[0]))
404
+ return s.allOf[0];
405
+ return schema;
406
+ }
407
+ function resolveSchemaRef(schemaName, nullable, collection, readsSource, rootId, component, packConfig, specPath, nodes, edges, diagnostics, sharedSchemas, sourceSchemas, localSchemas) {
408
+ const extra = { nullable };
409
+ if (collection)
410
+ extra.collection = collection;
411
+ const globalId = sharedSchemas.get(schemaName);
412
+ if (globalId) {
413
+ emitReadsEdge(readsSource, globalId, edges);
414
+ return { $ref: globalId, ...extra };
415
+ }
416
+ if (localSchemas.has(schemaName))
417
+ return { $ref: localSchemas.get(schemaName), ...extra };
418
+ if (rootId) {
419
+ const src = sourceSchemas.get(schemaName);
420
+ if (src) {
421
+ const inlineId = deriveNodeId('schema', component, schemaName, { parentId: rootId, section: 'schemas' });
422
+ if (!nodes.some(n => n.id === inlineId)) {
423
+ nodes.push(makeNode(packConfig.constructs['payloadSchema']?.template ?? 'Schema', component, specPath, inlineId));
424
+ edges.push({ id: `${rootId}__has-field__${inlineId}`, from: rootId, to: inlineId, type: 'has-field', state: 'implemented', stability: 'unstable' });
425
+ const localRef = `#/schemas/${schemaName}`;
426
+ localSchemas.set(schemaName, localRef);
427
+ emitFields(src, inlineId, 'fields', rootId, packConfig, specPath, nodes, edges, diagnostics, sharedSchemas, sourceSchemas, localSchemas);
428
+ }
429
+ return { $ref: localSchemas.get(schemaName) ?? `#/schemas/${schemaName}`, ...extra };
430
+ }
431
+ }
432
+ return { $ref: schemaName, ...extra };
433
+ }
434
+ function emitFields(schema, parentId, section, rootId, packConfig, specPath, nodes, edges, diagnostics, sharedSchemas, sourceSchemas, localSchemas) {
435
+ const readsSource = rootId ?? parentId;
436
+ const [component] = parentId.split('.');
437
+ for (const [fieldName, rawFieldSchema] of Object.entries(schema.properties ?? {})) {
438
+ const resolvedSchemaId = componentSchemaIdOf(rawFieldSchema);
439
+ const fieldSchema = resolveAllOfRef(rawFieldSchema);
440
+ const fieldId = deriveNodeId('field', component, fieldName, { parentId, section });
441
+ const fieldNode = makeNode(packConfig.constructs['payloadField']?.template ?? 'Field', component, specPath, fieldId);
442
+ const required = Array.isArray(schema.required) && schema.required.includes(fieldName);
443
+ // Resolve reference: prefer x-parser-schema-id (resolved by @asyncapi/parser), fall back to literal $ref
444
+ const schemaName = (resolvedSchemaId !== undefined && (sharedSchemas.has(resolvedSchemaId) || sourceSchemas.has(resolvedSchemaId)))
445
+ ? resolvedSchemaId
446
+ : (isRefSchema(fieldSchema) ? refName(fieldSchema.$ref) : undefined);
447
+ if (schemaName !== undefined) {
448
+ fieldNode.properties = resolveSchemaRef(schemaName, !required, undefined, readsSource, rootId, component, packConfig, specPath, nodes, edges, diagnostics, sharedSchemas, sourceSchemas, localSchemas);
449
+ }
450
+ else {
451
+ const fs = fieldSchema;
452
+ const rawType = Array.isArray(fs.type) ? (fs.type.find(t => t !== 'null') ?? 'string') : (fs.type ?? 'string');
453
+ const isNullableArray = Array.isArray(fs.type) && fs.type.includes('null');
454
+ const nullable = !required || isNullableArray;
455
+ if (fs.enum) {
456
+ const enumRef = sharedSchemas.get(fieldName);
457
+ fieldNode.properties = enumRef ? { $ref: enumRef, nullable } : { type: 'string', nullable };
458
+ if (!enumRef)
459
+ diagnostics.push({ severity: 'warning', file: specPath, message: `Inline enum for field "${fieldId}" — treating as string` });
460
+ }
461
+ else if (rawType === 'array') {
462
+ const items = fs.items ? resolveAllOfRef(fs.items) : undefined;
463
+ if (!items) {
464
+ fieldNode.properties = { type: 'string', nullable, collection: 'array' };
465
+ }
466
+ else if (isRefSchema(items)) {
467
+ fieldNode.properties = resolveSchemaRef(refName(items.$ref), nullable, 'array', readsSource, rootId, component, packConfig, specPath, nodes, edges, diagnostics, sharedSchemas, sourceSchemas, localSchemas);
468
+ if (!fieldNode.properties.$ref)
469
+ fieldNode.properties = { type: 'string', nullable, collection: 'array' };
470
+ }
471
+ else {
472
+ const it = items;
473
+ fieldNode.properties = { type: deriveScalarType(it.type ?? 'string', it.format, packConfig.scalarTypes) ?? 'string', nullable, collection: 'array' };
474
+ }
475
+ }
476
+ else if (rawType === 'object' && fs.properties) {
477
+ if (rootId) {
478
+ const inlineId = deriveNodeId('schema', component, fieldName, { parentId: rootId, section: 'schemas' });
479
+ if (!nodes.some(n => n.id === inlineId)) {
480
+ nodes.push(makeNode(packConfig.constructs['payloadSchema']?.template ?? 'Schema', component, specPath, inlineId));
481
+ edges.push({ id: `${rootId}__has-field__${inlineId}`, from: rootId, to: inlineId, type: 'has-field', state: 'implemented', stability: 'unstable' });
482
+ const localRef = `#/schemas/${fieldName}`;
483
+ localSchemas.set(fieldName, localRef);
484
+ emitFields(fs, inlineId, 'fields', rootId, packConfig, specPath, nodes, edges, diagnostics, sharedSchemas, sourceSchemas, localSchemas);
485
+ }
486
+ fieldNode.properties = { $ref: localSchemas.get(fieldName) ?? `#/schemas/${fieldName}`, nullable };
487
+ }
488
+ else {
489
+ diagnostics.push({ severity: 'warning', file: specPath, message: `Inline object field "${fieldId}" has no event context — treating as string` });
490
+ fieldNode.properties = { type: 'string', nullable };
491
+ }
492
+ }
493
+ else {
494
+ const scalarType = deriveScalarType(rawType, fs.format, packConfig.scalarTypes);
495
+ if (scalarType) {
496
+ fieldNode.properties = { type: scalarType, nullable };
497
+ }
498
+ else {
499
+ diagnostics.push({ severity: 'warning', file: specPath, message: `Unknown type for field "${fieldId}": ${rawType}/${fs.format} — defaulting to string` });
500
+ fieldNode.properties = { type: 'string', nullable };
501
+ }
502
+ }
503
+ }
504
+ nodes.push(fieldNode);
505
+ edges.push({ id: `${parentId}__has-field__${fieldId}`, from: parentId, to: fieldId, type: 'has-field', state: 'implemented', stability: 'unstable' });
506
+ }
507
+ }
@@ -0,0 +1,35 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { Parser } from '@asyncapi/parser';
4
+ const parser = new Parser();
5
+ export async function parseSpec(specPath) {
6
+ const diagnostics = [];
7
+ try {
8
+ const content = readFileSync(specPath, 'utf-8');
9
+ const source = `file://${path.resolve(specPath)}`;
10
+ const result = await parser.parse(content, { source });
11
+ for (const d of result.diagnostics) {
12
+ if (d.severity === 0) {
13
+ diagnostics.push({ severity: 'error', file: specPath, message: d.message });
14
+ }
15
+ else if (d.severity === 1) {
16
+ diagnostics.push({ severity: 'warning', file: specPath, message: d.message });
17
+ }
18
+ }
19
+ if (!result.document) {
20
+ if (!diagnostics.some(d => d.severity === 'error')) {
21
+ diagnostics.push({ severity: 'error', file: specPath, message: 'AsyncAPI parser returned no document' });
22
+ }
23
+ return { document: null, diagnostics };
24
+ }
25
+ return { document: result.document, diagnostics };
26
+ }
27
+ catch (err) {
28
+ diagnostics.push({
29
+ severity: 'error',
30
+ file: specPath,
31
+ message: `Failed to parse AsyncAPI spec: ${err instanceof Error ? err.message : String(err)}`,
32
+ });
33
+ return { document: null, diagnostics };
34
+ }
35
+ }
@@ -10,3 +10,5 @@ export function getAdapter(adapterId) {
10
10
  }
11
11
  import { OpenAPIAdapter } from './openapi/index.js';
12
12
  registerAdapter(new OpenAPIAdapter());
13
+ import { AsyncAPIAdapter } from './asyncapi/index.js';
14
+ registerAdapter(new AsyncAPIAdapter());
@@ -5,7 +5,7 @@ import { readFile as fsReadFile } from 'node:fs/promises';
5
5
  import { createRequire } from 'node:module';
6
6
  import path from 'node:path';
7
7
  import { parse as parseYaml } from 'yaml';
8
- import { buildOpenAPIConfig, loadImportConfig } from '../import/config.js';
8
+ import { buildAsyncAPIConfig, buildOpenAPIConfig, loadImportConfig } from '../import/config.js';
9
9
  import { runImport } from '../import/runner.js';
10
10
  import { loadGraph } from '../loader/index.js';
11
11
  import { startMcpServer } from '../mcp/index.js';
@@ -185,6 +185,42 @@ importCmd
185
185
  process.exit(2);
186
186
  }
187
187
  });
188
+ importCmd
189
+ .command('asyncapi <spec>')
190
+ .description('Import an AsyncAPI spec into the graph')
191
+ .option('--component-strategy <strategy>', 'Component mapping: channel-segment, channel-pattern, name-segment, name-pattern, tag, hardcoded', 'channel-segment')
192
+ .option('--separator <char>', 'Separator for segment strategies', '.')
193
+ .option('--segment <n>', 'Segment index for segment strategies', parseInt)
194
+ .option('--pattern <regex>', 'Regex pattern for pattern strategies')
195
+ .option('--component <name>', 'Component name (hardcoded strategy)')
196
+ .option('--event-classification <mode>', 'Event classification: always-integration, always-domain', 'always-integration')
197
+ .option('--include-consumed', 'Also import receive (consumed) operations', false)
198
+ .option('--graph <path>', 'Override CORUM_GRAPH_PATH')
199
+ .action(async (spec, opts) => {
200
+ try {
201
+ const runtimeConfig = buildRuntimeConfig(opts.graph);
202
+ const entry = buildAsyncAPIConfig(spec, opts.componentStrategy, {
203
+ separator: opts.separator,
204
+ segment: opts.segment,
205
+ pattern: opts.pattern,
206
+ value: opts.component,
207
+ });
208
+ if (opts.eventClassification === 'always-domain') {
209
+ entry.eventClassification = { strategy: 'always-domain' };
210
+ }
211
+ if (opts.includeConsumed) {
212
+ entry.includeConsumed = true;
213
+ }
214
+ const result = await runImport({ imports: [entry] }, runtimeConfig);
215
+ reportDiagnostics(result.diagnostics);
216
+ if (result.diagnostics.some(d => d.severity === 'error'))
217
+ process.exit(1);
218
+ }
219
+ catch (err) {
220
+ process.stderr.write(`[ERROR] ${err instanceof Error ? err.message : String(err)}\n`);
221
+ process.exit(2);
222
+ }
223
+ });
188
224
  const packCmd = program.command('pack').description('Manage template packs');
189
225
  packCmd
190
226
  .command('install <name>')
@@ -37,3 +37,27 @@ export function buildOpenAPIConfig(spec, strategy, segment, pattern, component)
37
37
  }
38
38
  return { adapter: 'openapi', spec, componentMapping };
39
39
  }
40
+ export function buildAsyncAPIConfig(spec, strategy, opts = {}) {
41
+ let componentMapping;
42
+ if (strategy === 'hardcoded') {
43
+ if (!opts.value)
44
+ throw new Error('--component required for hardcoded strategy');
45
+ componentMapping = { strategy: 'hardcoded', value: opts.value };
46
+ }
47
+ else if (strategy === 'tag') {
48
+ componentMapping = { strategy: 'tag' };
49
+ }
50
+ else if (strategy === 'channel-pattern') {
51
+ componentMapping = { strategy: 'channel-pattern', pattern: opts.pattern ?? '' };
52
+ }
53
+ else if (strategy === 'name-pattern') {
54
+ componentMapping = { strategy: 'name-pattern', pattern: opts.pattern ?? '' };
55
+ }
56
+ else if (strategy === 'name-segment') {
57
+ componentMapping = { strategy: 'name-segment', separator: opts.separator ?? '.', segment: opts.segment ?? 0 };
58
+ }
59
+ else {
60
+ componentMapping = { strategy: 'channel-segment', separator: opts.separator ?? '.', segment: opts.segment ?? 0 };
61
+ }
62
+ return { adapter: 'asyncapi', spec, componentMapping };
63
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atolis-hq/corum",
3
- "version": "0.1.17",
3
+ "version": "0.1.18",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -23,6 +23,7 @@
23
23
  },
24
24
  "dependencies": {
25
25
  "@apidevtools/swagger-parser": "^12.1.0",
26
+ "@asyncapi/parser": "^3.6.0",
26
27
  "@modelcontextprotocol/sdk": "^1.0.0",
27
28
  "@toon-format/toon": "^2.1.0",
28
29
  "commander": "^14.0.3",