Open History to see the last commit
1/**
2 * AsyncAPI 3.x message-schema extraction. Bundles client (send) and
3 * server (receive) payloads as a `type`-discriminated `oneOf` via
4 * {@link bundleSchema}. FAL WMA is the only caller today.
5 */
6import type { CapabilityMap } from '#/lib/capabilities.ts'
7
8import { bundleSchema, findDanglingRefs } from './bundle.ts'
9import type { ExtractedEndpointSchemas, JsonValue } from './bundle.ts'
10
11function isObject(node: unknown): node is Record<string, unknown> {
12 return typeof node === 'object' && node !== null && !Array.isArray(node)
13}
14
15function isJsonValue(node: unknown): node is JsonValue {
16 if (node === null) return true
17 const t = typeof node
18 if (t === 'string' || t === 'number' || t === 'boolean') return true
19 if (Array.isArray(node)) return node.every(isJsonValue)
20 if (isObject(node)) {
21 return Object.values(node).every(isJsonValue)
22 }
23 return false
24}
25
26function jsonPointer(doc: unknown, ref: string): unknown {
27 if (!ref.startsWith('#/')) return undefined
28 const parts = ref
29 .slice(2)
30 .split('/')
31 .map((part) => part.replace(/~1/g, '/').replace(/~0/g, '~'))
32 let current: unknown = doc
33 for (const part of parts) {
34 if (Array.isArray(current)) {
35 const index = Number(part)
36 if (!Number.isInteger(index) || index < 0 || index >= current.length) {
37 return undefined
38 }
39 current = current[index]
40 continue
41 }
42 if (!isObject(current) || !(part in current)) return undefined
43 current = current[part]
44 }
45 return current
46}
47
48/** Follow `$ref` until a concrete node (cycle-capped). */
49function unwrap(doc: unknown, node: unknown, depth = 0): unknown {
50 if (depth > 20) return node
51 if (isObject(node) && typeof node.$ref === 'string') {
52 const target = jsonPointer(doc, node.$ref)
53 if (target === undefined) return node
54 return unwrap(doc, target, depth + 1)
55 }
56 return node
57}
58
59function schemaComponents(doc: unknown): Record<string, JsonValue> {
60 if (!isObject(doc)) return {}
61 const components = doc.components
62 if (!isObject(components) || !isObject(components.schemas)) return {}
63 const out: Record<string, JsonValue> = {}
64 for (const [name, schema] of Object.entries(components.schemas)) {
65 if (isJsonValue(schema)) out[name] = schema
66 }
67 return out
68}
69
70function messagePayload(doc: unknown, messageNode: unknown): JsonValue | null {
71 const message = unwrap(doc, messageNode)
72 if (!isObject(message)) return null
73 const payload = message.payload
74 if (payload === undefined) return null
75 if (!isJsonValue(payload)) return null
76 return payload
77}
78
79function collectFromOperations(
80 doc: unknown,
81 action: 'send' | 'receive',
82): Array<JsonValue> {
83 if (!isObject(doc) || !isObject(doc.operations)) return []
84 const payloads: Array<JsonValue> = []
85 for (const op of Object.values(doc.operations)) {
86 if (!isObject(op) || op.action !== action) continue
87 if (!Array.isArray(op.messages)) continue
88 for (const item of op.messages) {
89 const payload = messagePayload(doc, item)
90 if (payload !== null) payloads.push(payload)
91 }
92 }
93 return payloads
94}
95
96function collectFromComponentMessages(
97 doc: unknown,
98 prefix: 'client.' | 'server.',
99): Array<JsonValue> {
100 if (!isObject(doc) || !isObject(doc.components)) return []
101 const messages = doc.components.messages
102 if (!isObject(messages)) return []
103 const payloads: Array<JsonValue> = []
104 for (const name of Object.keys(messages).sort()) {
105 if (!name.startsWith(prefix)) continue
106 const payload = messagePayload(doc, messages[name])
107 if (payload !== null) payloads.push(payload)
108 }
109 return payloads
110}
111
112function payloadsFor(
113 doc: unknown,
114 action: 'send' | 'receive',
115 fallbackPrefix: 'client.' | 'server.',
116): Array<JsonValue> {
117 const fromOps = collectFromOperations(doc, action)
118 if (fromOps.length > 0) return fromOps
119 const hasOperations =
120 isObject(doc) &&
121 isObject(doc.operations) &&
122 Object.keys(doc.operations).length > 0
123 if (hasOperations) return fromOps
124 return collectFromComponentMessages(doc, fallbackPrefix)
125}
126
127function bundleOneOf(
128 payloads: Array<JsonValue>,
129 components: Record<string, JsonValue>,
130 title: string,
131 context: string,
132): { schema?: Record<string, JsonValue>; warnings: Array<string> } {
133 if (payloads.length === 0) return { warnings: [] }
134 const bundled = bundleSchema(
135 { title, oneOf: payloads },
136 components,
137 null,
138 context,
139 )
140 const dangling = findDanglingRefs(bundled.schema)
141 const warnings = [...bundled.warnings]
142 if (dangling.length > 0) {
143 warnings.push(`${context}: bundled schema has dangling refs`)
144 }
145 return { schema: bundled.schema, warnings }
146}
147
148function typeConstOf(schema: unknown): string {
149 if (!isObject(schema) || !isObject(schema.properties)) return ''
150 const type = schema.properties.type
151 if (!isObject(type) || typeof type.const !== 'string') return ''
152 return type.const
153}
154
155/** `type` consts on a bundled oneOf (follows `#/$defs/` refs). */
156export function asyncApiMessageTypes(schema: unknown): Array<string> {
157 if (!isObject(schema) || !Array.isArray(schema.oneOf)) return []
158 const defs = isObject(schema.$defs) ? schema.$defs : {}
159 return schema.oneOf.map((item) => {
160 if (
161 isObject(item) &&
162 typeof item.$ref === 'string' &&
163 item.$ref.startsWith('#/$defs/')
164 ) {
165 return typeConstOf(defs[item.$ref.slice('#/$defs/'.length)])
166 }
167 return typeConstOf(item)
168 })
169}
170
171/**
172 * Client-message payloads → `input` oneOf; server-message payloads →
173 * `output` oneOf. Each variant keeps its `type` const from the document.
174 */
175export function extractAsyncApiSchemas(
176 document: unknown,
177): ExtractedEndpointSchemas {
178 const warnings: Array<string> = []
179 if (!isObject(document) || typeof document.asyncapi !== 'string') {
180 return { warnings: ['asyncapi: document is missing an asyncapi version'] }
181 }
182 const components = schemaComponents(document)
183 const input = bundleOneOf(
184 payloadsFor(document, 'send', 'client.'),
185 components,
186 'Client messages',
187 'asyncapi input',
188 )
189 const output = bundleOneOf(
190 payloadsFor(document, 'receive', 'server.'),
191 components,
192 'Server messages',
193 'asyncapi output',
194 )
195 warnings.push(...input.warnings, ...output.warnings)
196 return { input: input.schema, output: output.schema, warnings }
197}
198
199export function hasAsyncApiFlag(capabilities: unknown): boolean {
200 return isObject(capabilities) && capabilities.asyncapi === true
201}
202
203/** Add or drop `asyncapi: true` on a flag map; keep its other flags. */
204export function withAsyncApiFlag(
205 capabilities: CapabilityMap | null,
206 enabled: boolean,
207): CapabilityMap | null {
208 if (enabled) return { ...capabilities, asyncapi: true }
209 if (capabilities?.asyncapi === undefined) return capabilities
210 const { asyncapi: _dropped, ...rest } = capabilities
211 return Object.keys(rest).length > 0 ? rest : null
212}
213
214/**
215 * Poll listings omit the AsyncAPI flag (they do not re-probe). Keep a
216 * previously persisted `asyncapi: true` unless the listing sets the key.
217 */
218export function preserveAsyncApiFlag(
219 existing: CapabilityMap | null,
220 listed: CapabilityMap | null,
221): CapabilityMap | null {
222 if (!hasAsyncApiFlag(existing) || listed?.asyncapi !== undefined) {
223 return listed
224 }
225 // A listing with no flags at all (null) still keeps the synced one.
226 return withAsyncApiFlag(listed, true)
227}