@open-wa/schema 5.5.1 → 5.6.1

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,59 @@
1
+ import { eventContracts, eventJsonSchema } from './contracts';
2
+
3
+ export interface AsyncApiOptions { origin?: string; basePath?: string; version?: string; mcpPath?: string; mcpEnabled?: boolean }
4
+
5
+ /** Build the same contract for the metadata endpoint and static documentation. */
6
+ export function createAsyncApiDocument(options: AsyncApiOptions = {}) {
7
+ const basePath = (options.basePath ?? '').replace(/\/$/, '');
8
+ const channels: Record<string, unknown> = {};
9
+ const operations: Record<string, unknown> = {};
10
+ const schemas: Record<string, unknown> = {};
11
+ const messages: Record<string, unknown> = {};
12
+ for (const contract of eventContracts) {
13
+ const key = contract.name.replace(/\./g, '_');
14
+ schemas[key] = eventJsonSchema(contract.payloadSchema);
15
+ for (const transport of contract.transports) {
16
+ const id = `${transport}_${key}`;
17
+ const isMcp = transport === 'mcp';
18
+ if (isMcp) schemas[`${key}_mcp`] = eventJsonSchema(contract.mcp!.payloadSchema);
19
+ const payloadRef = { $ref: `#/components/schemas/${key}${isMcp ? '_mcp' : ''}` };
20
+ const properties = transport === 'sse'
21
+ ? { id: { type: 'string' }, event: { const: contract.name }, payload: payloadRef, ts: { type: 'number' }, sessionId: { type: 'string' } }
22
+ : transport === 'webhook'
23
+ ? { webhookId: { type: 'string' }, sessionId: { type: 'string' }, event: { const: contract.name }, payload: payloadRef, timestamp: { type: 'number' }, idempotencyKey: { type: 'string' } }
24
+ : { eventId: { type: 'string' }, name: { const: contract.name }, timestamp: { type: 'string', format: 'date-time' }, data: payloadRef, cursor: { type: 'null' } };
25
+ messages[id] = {
26
+ name: contract.name, title: contract.name, summary: contract.description,
27
+ contentType: 'application/json',
28
+ payload: { type: 'object', properties, required: Object.keys(properties).filter(name => name !== 'idempotencyKey'), additionalProperties: false },
29
+ ...(isMcp ? { headers: { type: 'object', required: ['webhook-id', 'webhook-timestamp', 'webhook-signature', 'X-MCP-Subscription-Id'], properties: {
30
+ 'webhook-id': { type: 'string' }, 'webhook-timestamp': { type: 'string' }, 'webhook-signature': { type: 'string' }, 'X-MCP-Subscription-Id': { type: 'string' },
31
+ } } } : {}),
32
+ 'x-openwa-listener': contract.listener, 'x-openwa-aliases': contract.aliases,
33
+ 'x-openwa-optional-runtime-listener': contract.optionalRuntimeListener,
34
+ };
35
+ channels[id] = {
36
+ address: transport === 'sse' ? `${basePath}/api/events` : null,
37
+ description: transport === 'sse'
38
+ ? 'SSE event frame: id, event and JSON data; optional topics query filters exact runtime names. Keepalive every 20 seconds; reconnect hint 3000 ms. No history replay. API key in X-API-Key or api_key/key query.'
39
+ : transport === 'webhook'
40
+ ? 'Outbound HTTP POST to the configured destination. Public non-sensitive events pass through the plugin gateway. Optional event-name filter; default 3 retries with exponential delay from 1000 ms. Optional durable journal adds Idempotency-Key and retries pending deliveries after restart. No exactly-once guarantee.'
41
+ : `Verified subscriber-provided HTTPS callback. Subscribe through ${basePath}${options.mcpPath ?? '/mcp'} using MCP 2026-07-28. Standard Webhooks signatures, stable event IDs and bounded transient retries. No retry on 410/413; cursor:null means no historical replay.`,
42
+ messages: { event: { $ref: `#/components/messages/${id}` } },
43
+ 'x-openwa-transport': transport,
44
+ ...(transport === 'sse' ? { servers: [{ $ref: '#/servers/easyApi' }], 'x-openwa-sse': { event: contract.name, contentType: 'text/event-stream', topics: contract.name } } : {}),
45
+ ...(isMcp ? { 'x-openwa-subscription-schema': eventJsonSchema(contract.mcp!.inputSchema) } : {}),
46
+ };
47
+ operations[id] = { action: 'send', channel: { $ref: `#/channels/${id}` }, summary: `${contract.name} over ${transport}`, messages: [{ $ref: `#/channels/${id}/messages/event` }] };
48
+ }
49
+ }
50
+ const origin = new URL(options.origin ?? 'http://localhost:8080');
51
+ return {
52
+ asyncapi: '3.1.0',
53
+ info: { title: 'OpenWA events', version: options.version ?? '5.5.1', description: 'Initial public wire contracts for six runtime events. This is not an exhaustive list of internal lifecycle events. SSE and webhook policies differ; MCP provides compact summaries for three events.' },
54
+ servers: { easyApi: { host: origin.host, protocol: origin.protocol.slice(0, -1), security: [{ $ref: '#/components/securitySchemes/apiKey' }] } },
55
+ channels, operations,
56
+ components: { schemas, messages, securitySchemes: { apiKey: { type: 'httpApiKey', name: 'X-API-Key', in: 'header', description: 'Easy API instance API key. Callback signing secrets are per subscription and are never included in this document.' } } },
57
+ ...(options.mcpEnabled !== undefined ? { 'x-openwa-mcp-enabled': options.mcpEnabled } : {}),
58
+ };
59
+ }
@@ -0,0 +1,119 @@
1
+ import { z } from 'zod';
2
+ import { MessageSchema } from '../common-types';
3
+ import { eventRegistry } from './registry';
4
+ import './messaging';
5
+ import './state';
6
+ import './groups';
7
+
8
+ const context = z.object({ correlationId: z.string(), ts: z.number(), attempt: z.number().optional() });
9
+ // Runtime snapshots can be partial; the complete listener schema is not a wire guarantee.
10
+ const message = MessageSchema.partial().extend({ id: MessageSchema.shape.id }).passthrough();
11
+ const ack = MessageSchema.pick({ id: true, ack: true }).passthrough();
12
+ const step = (details: z.ZodType) => context.extend({
13
+ step: z.string(), details: details.optional(),
14
+ error: z.object({ name: z.string(), message: z.string(), stack: z.string().optional() }).optional(),
15
+ durationMs: z.number().optional(),
16
+ });
17
+ const conversationFilter = z.object({ chatId: z.string().min(1).optional() }).strict();
18
+ const noFilter = z.object({}).strict();
19
+ const messageSummary = z.object({
20
+ sessionId: z.string(), messageId: z.string(), chatId: z.string().optional(),
21
+ from: z.string().optional(), body: z.string().max(4000).optional(), truncated: z.boolean(),
22
+ });
23
+ const ackSummary = z.object({
24
+ sessionId: z.string(), messageId: z.string(), ack: z.number(), chatId: z.string().optional(),
25
+ });
26
+ const stateSummary = z.object({
27
+ sessionId: z.string(), previousState: z.string().optional(), state: z.string(),
28
+ });
29
+
30
+ export interface EventContract {
31
+ name: string;
32
+ listener: string;
33
+ aliases: string[];
34
+ description: string;
35
+ optionalRuntimeListener: boolean;
36
+ payloadSchema: z.ZodType;
37
+ transports: readonly ('sse' | 'webhook' | 'mcp')[];
38
+ mcp?: { inputSchema: z.ZodType; payloadSchema: z.ZodType; project(payload: unknown, sessionId: string): unknown };
39
+ }
40
+
41
+ const record = (value: unknown): Record<string, unknown> =>
42
+ value && typeof value === 'object' ? value as Record<string, unknown> : {};
43
+ const text = (value: unknown) => typeof value === 'string' ? value : undefined;
44
+
45
+ function defineContract(
46
+ listener: string,
47
+ definition: Omit<EventContract, 'listener' | 'aliases' | 'description'>,
48
+ ): EventContract {
49
+ const meta = eventRegistry.get(listener)!.meta;
50
+ return { ...definition, listener, aliases: [meta.legacyName, ...(meta.aliases ?? [])], description: meta.description ?? definition.name };
51
+ }
52
+
53
+ /** Canonical public wire contracts, shared by AsyncAPI, documentation and MCP. */
54
+ export const eventContracts: readonly EventContract[] = [
55
+ defineContract('message', {
56
+ name: 'message.received', optionalRuntimeListener: false, transports: ['sse', 'webhook', 'mcp'],
57
+ payloadSchema: z.object({ ctx: context, message }),
58
+ mcp: {
59
+ inputSchema: conversationFilter, payloadSchema: messageSummary,
60
+ project(payload, sessionId) {
61
+ const m = record(record(payload).message);
62
+ const body = text(m.body);
63
+ return { sessionId, messageId: m.id, chatId: text(m.chatId), from: text(m.from), body: body?.slice(0, 4000), truncated: (body?.length ?? 0) > 4000 };
64
+ },
65
+ },
66
+ }),
67
+ defineContract('anyMessage', {
68
+ name: 'message.any', optionalRuntimeListener: true, transports: ['sse', 'webhook'],
69
+ payloadSchema: z.object({ ctx: context, message }),
70
+ }),
71
+ defineContract('ack', {
72
+ name: 'ack.changed', optionalRuntimeListener: false, transports: ['sse', 'webhook', 'mcp'],
73
+ payloadSchema: z.object({ ctx: context, ack }),
74
+ mcp: {
75
+ inputSchema: conversationFilter, payloadSchema: ackSummary,
76
+ project(payload, sessionId) {
77
+ const a = record(record(payload).ack);
78
+ return { sessionId, messageId: a.id, ack: a.ack, chatId: text(a.chatId) };
79
+ },
80
+ },
81
+ }),
82
+ defineContract('stateChanged', {
83
+ name: 'session.state.changed', optionalRuntimeListener: false, transports: ['sse', 'webhook', 'mcp'],
84
+ payloadSchema: step(z.object({ prev: z.string(), next: z.string(), reason: z.string().optional() })),
85
+ mcp: {
86
+ inputSchema: noFilter, payloadSchema: stateSummary,
87
+ project(payload, sessionId) {
88
+ const details = record(record(payload).details);
89
+ return { sessionId, previousState: text(details.prev), state: details.next };
90
+ },
91
+ },
92
+ }),
93
+ defineContract('addedToGroup', {
94
+ name: 'group.addedToGroup', optionalRuntimeListener: true, transports: ['sse', 'webhook'],
95
+ payloadSchema: z.object({ ctx: context, groupId: z.string(), by: z.string().optional() }),
96
+ }),
97
+ defineContract('logout', {
98
+ name: 'session.logout', optionalRuntimeListener: false, transports: ['sse', 'webhook'],
99
+ payloadSchema: step(z.object({ reason: z.string().optional() })),
100
+ }),
101
+ ].sort((a, b) => a.name.localeCompare(b.name));
102
+
103
+ export function getEventContract(name: string): EventContract | undefined {
104
+ return eventContracts.find(contract => contract.name === name);
105
+ }
106
+
107
+ export function eventJsonSchema(schema: z.ZodType): Record<string, unknown> {
108
+ return z.toJSONSchema(schema, { target: 'draft-7', unrepresentable: 'any' });
109
+ }
110
+
111
+ export function getMcpEventDefinitions() {
112
+ return eventContracts.filter(contract => contract.mcp).map(contract => ({
113
+ name: contract.name,
114
+ description: `${contract.description}. Compact summary${contract.name === 'session.state.changed' ? '' : '; use messages.get with messageId to read a full message'}. No history replay.`,
115
+ delivery: ['webhook'] as 'webhook'[],
116
+ inputSchema: eventJsonSchema(contract.mcp!.inputSchema),
117
+ payloadSchema: eventJsonSchema(contract.mcp!.payloadSchema),
118
+ }));
119
+ }
@@ -6,3 +6,5 @@ export * from './calls';
6
6
  export * from './whatsapp-events';
7
7
 
8
8
  export * from './polls';
9
+ export * from './contracts';
10
+ export * from './asyncapi';