@open-wa/schema 5.0.0 → 5.2.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.
Files changed (74) hide show
  1. package/dist/generated/index.cjs +8 -2
  2. package/dist/generated/index.cjs.map +1 -1
  3. package/dist/generated/index.d.cts +7868 -994
  4. package/dist/generated/index.d.cts.map +1 -1
  5. package/dist/generated/index.d.mts +7868 -994
  6. package/dist/generated/index.d.mts.map +1 -1
  7. package/dist/generated/index.mjs +8 -2
  8. package/dist/generated/index.mjs.map +1 -1
  9. package/dist/index-C9Ad0lEr.d.cts +4729 -0
  10. package/dist/index-C9Ad0lEr.d.cts.map +1 -0
  11. package/dist/index-D0QN2PaW.d.mts +4729 -0
  12. package/dist/index-D0QN2PaW.d.mts.map +1 -0
  13. package/dist/index.cjs +109 -1
  14. package/dist/index.cjs.map +1 -1
  15. package/dist/index.d.cts +2 -2
  16. package/dist/index.d.mts +2 -2
  17. package/dist/index.mjs +53 -2
  18. package/dist/index.mjs.map +1 -1
  19. package/dist/methods/index.cjs +6 -1
  20. package/dist/methods/index.d.cts +2 -2
  21. package/dist/methods/index.d.mts +2 -2
  22. package/dist/methods/index.mjs +2 -2
  23. package/dist/{methods-Dizm7Fn9.cjs → methods-BGmdzjd3.cjs} +904 -76
  24. package/dist/methods-BGmdzjd3.cjs.map +1 -0
  25. package/dist/{methods-CZqeUhKy.mjs → methods-BhLsQNtL.mjs} +587 -77
  26. package/dist/methods-BhLsQNtL.mjs.map +1 -0
  27. package/package.json +4 -3
  28. package/src/__tests__/generators.contract.test.ts +181 -0
  29. package/src/__tests__/registry.contract.test.ts +81 -0
  30. package/src/client-config.ts +30 -0
  31. package/src/codecs.test.ts +41 -0
  32. package/src/codecs.ts +191 -0
  33. package/src/common-types.ts +287 -0
  34. package/src/config.ts +47 -0
  35. package/src/enums.ts +63 -0
  36. package/src/events/groups.ts +33 -0
  37. package/src/events/index.ts +4 -0
  38. package/src/events/messaging.ts +86 -0
  39. package/src/events/registry.ts +124 -0
  40. package/src/events/state.ts +59 -0
  41. package/src/generated/AliasMap.ts +216 -0
  42. package/src/generated/BaseClient.ts +878 -0
  43. package/src/generated/BaseNamespacedClient.ts +214 -0
  44. package/src/generated/index.ts +5 -0
  45. package/src/generated/openapi.json +30049 -0
  46. package/src/generated/types.ts +383 -0
  47. package/src/http-manifest.ts +97 -0
  48. package/src/implementor.test.ts +88 -0
  49. package/src/implementor.ts +75 -0
  50. package/src/index.ts +46 -0
  51. package/src/interactive.ts +151 -0
  52. package/src/methods/business.ts +52 -0
  53. package/src/methods/chats.ts +264 -0
  54. package/src/methods/communities.ts +121 -0
  55. package/src/methods/contacts.ts +160 -0
  56. package/src/methods/groups.ts +378 -0
  57. package/src/methods/index.ts +34 -0
  58. package/src/methods/interactive.ts +21 -0
  59. package/src/methods/labels.ts +88 -0
  60. package/src/methods/media.ts +36 -0
  61. package/src/methods/messaging.ts +836 -0
  62. package/src/methods/session.ts +262 -0
  63. package/src/methods/status.ts +122 -0
  64. package/src/output-json-schema.ts +27 -0
  65. package/src/parameters.ts +237 -0
  66. package/src/registry.test.ts +30 -0
  67. package/src/registry.ts +601 -0
  68. package/src/return-types.ts +125 -0
  69. package/dist/index-BHcd0h7x.d.mts +0 -1265
  70. package/dist/index-BHcd0h7x.d.mts.map +0 -1
  71. package/dist/index-ChYFQM1K.d.cts +0 -1265
  72. package/dist/index-ChYFQM1K.d.cts.map +0 -1
  73. package/dist/methods-CZqeUhKy.mjs.map +0 -1
  74. package/dist/methods-Dizm7Fn9.cjs.map +0 -1
@@ -0,0 +1,287 @@
1
+ import { z } from 'zod';
2
+
3
+ // Aliases
4
+ export const ContactIdSchema = z.string().brand('ContactId').describe('Opaque WhatsApp contact identifier. Preserve the exact value returned by the API.');
5
+ export type ContactId = z.infer<typeof ContactIdSchema>;
6
+
7
+ export const ChatIdSchema = z.string().brand('ChatId').describe('Opaque conversation identifier. Use the exact value returned by a message event or chat lookup.');
8
+ export type ChatId = z.infer<typeof ChatIdSchema>;
9
+
10
+ export const MessageIdSchema = z.string().brand('MessageId').describe('Message identifier returned by a send method or message event.');
11
+ export type MessageId = z.infer<typeof MessageIdSchema>;
12
+
13
+ export const GroupChatIdSchema = z.string().brand('GroupChatId').describe('Opaque group conversation identifier returned by a group lookup or join method.');
14
+ export type GroupChatId = z.infer<typeof GroupChatIdSchema>;
15
+
16
+ export const GroupIdSchema = z.string().brand('GroupId').describe('Identifier for a WhatsApp group. Use the value returned by the API.');
17
+ export type GroupId = z.infer<typeof GroupIdSchema>;
18
+
19
+ export const DataURLSchema = z.templateLiteral(['data:', z.string(), ';base64,', z.string()]);
20
+ export type DataURL = z.infer<typeof DataURLSchema>;
21
+ export type Base64 = string;
22
+ export type Content = string | DataURL | Base64 | Buffer;
23
+
24
+ export const GroupMetadataSchema = z.object({
25
+ id: GroupIdSchema,
26
+ subject: z.string(),
27
+ creation: z.number(),
28
+ owner: ContactIdSchema.optional(),
29
+ desc: z.string().optional(),
30
+ descTime: z.number().optional(),
31
+ descOwner: ContactIdSchema.optional(),
32
+ restrict: z.boolean().optional(),
33
+ announce: z.boolean().optional(),
34
+ participants: z.array(z.object({
35
+ id: ContactIdSchema,
36
+ isAdmin: z.boolean(),
37
+ isSuperAdmin: z.boolean().optional(),
38
+ })),
39
+ }).passthrough().describe('Serialized group metadata returned by group lookups. Additional WhatsApp Web fields may be present.');
40
+ export type GroupMetadata = z.infer<typeof GroupMetadataSchema>;
41
+
42
+ // Id
43
+ export const IdSchema = z.object({
44
+ server: z.string(),
45
+ user: z.string(),
46
+ _serialized: z.string(),
47
+ });
48
+ export type Id = z.infer<typeof IdSchema>;
49
+
50
+ // Enums
51
+ export enum MessageTypes {
52
+ TEXT = 'chat',
53
+ AUDIO = 'audio',
54
+ VOICE = 'ptt',
55
+ IMAGE = 'image',
56
+ VIDEO = 'video',
57
+ DOCUMENT = 'document',
58
+ STICKER = 'sticker',
59
+ LOCATION = 'location',
60
+ CONTACT_CARD = 'vcard',
61
+ CONTACT_CARD_MULTI = 'multi_vcard',
62
+ REVOKED = 'revoked',
63
+ ORDER = 'order',
64
+ BUTTONS_RESPONSE = 'buttons_response',
65
+ LIST_RESPONSE = "list_response",
66
+ UNKNOWN = 'unknown'
67
+ }
68
+
69
+ export enum MessageAck {
70
+ ACK_ERROR = -1,
71
+ ACK_PENDING = 0,
72
+ ACK_SERVER = 1,
73
+ ACK_DEVICE = 2,
74
+ ACK_READ = 3,
75
+ ACK_PLAYED = 4,
76
+ }
77
+
78
+ /**
79
+ * An enum of all the "simple listeners". A simple listener is a listener that just takes one parameter which is the callback function to handle the event.
80
+ */
81
+ export enum SimpleListener {
82
+ /**
83
+ * Represents [[onMessage]]
84
+ */
85
+ Message = 'onMessage',
86
+ /**
87
+ * Represents [[onAnyMessage]]
88
+ */
89
+ AnyMessage = 'onAnyMessage',
90
+ /**
91
+ * Represents [[onMessageDeleted]]
92
+ */
93
+ MessageDeleted = 'onMessageDeleted',
94
+ /**
95
+ * Represents [[onAck]]
96
+ */
97
+ Ack = 'onAck',
98
+ /**
99
+ * Represents [[onAddedToGroup]]
100
+ */
101
+ AddedToGroup = 'onAddedToGroup',
102
+ /**
103
+ * Represents [[onChatDeleted]]
104
+ */
105
+ ChatDeleted = 'onChatDeleted',
106
+ /**
107
+ * Represents [[onBattery]]
108
+ */
109
+ Battery = 'onBattery',
110
+ /**
111
+ * Represents [[onChatOpened]]
112
+ */
113
+ ChatOpened = 'onChatOpened',
114
+ /**
115
+ * Represents [[onIncomingCall]]
116
+ */
117
+ IncomingCall = 'onIncomingCall',
118
+ /**
119
+ * Represents [[onGlobalParticipantsChanged]]
120
+ */
121
+ GlobalParticipantsChanged = 'onGlobalParticipantsChanged',
122
+ /**
123
+ * Represents [[onChatState]]
124
+ */
125
+ ChatState = 'onChatState',
126
+ /**
127
+ * Represents [[onLogout]]
128
+ */
129
+ Logout = 'onLogout',
130
+ /**
131
+ * Represents [[onPlugged]]
132
+ */
133
+ Plugged = 'onPlugged',
134
+ /**
135
+ * Represents [[onStateChanged]]
136
+ */
137
+ StateChanged = 'onStateChanged',
138
+ /**
139
+ * Represents [[onButton]]
140
+ */
141
+ Button = 'onButton',
142
+ /**
143
+ * Requires licence
144
+ * Represents [[onStory]]
145
+ */
146
+ Story = 'onStory',
147
+ /**
148
+ * Requires licence
149
+ * Represents [[onRemovedFromGroup]]
150
+ */
151
+ RemovedFromGroup = 'onRemovedFromGroup',
152
+ /**
153
+ * Requires licence
154
+ * Represents [[onContactAdded]]
155
+ */
156
+ ContactAdded = 'onContactAdded',
157
+ /**
158
+ * Represents [[onOrder]]
159
+ */
160
+ Order = 'onOrder',
161
+ }
162
+
163
+ // Forward declarations
164
+ const MessageSchemaBase = z.object({
165
+ id: MessageIdSchema,
166
+ body: z.string(),
167
+ type: z.nativeEnum(MessageTypes),
168
+ t: z.number(),
169
+ notifyName: z.string().optional(),
170
+ from: ChatIdSchema,
171
+ to: ChatIdSchema,
172
+ self: z.enum(['in', 'out']),
173
+ ack: z.nativeEnum(MessageAck),
174
+ invis: z.boolean().optional(),
175
+ isNewMsg: z.boolean().optional(),
176
+ star: z.boolean().optional(),
177
+ recvFresh: z.boolean().optional(),
178
+ broadcast: z.boolean().optional(),
179
+ isForwarded: z.boolean().optional(),
180
+ labels: z.array(z.string()).optional(),
181
+ mentionedJidList: z.array(ContactIdSchema).optional(),
182
+ caption: z.string().optional(),
183
+ sender: z.any(), // Circular reference handled later/lazy
184
+ timestamp: z.number(),
185
+ content: z.string(),
186
+ isGroupMsg: z.boolean(),
187
+ isMMS: z.boolean().optional(),
188
+ isMedia: z.boolean(),
189
+ isNotification: z.boolean(),
190
+ isPSA: z.boolean().optional(),
191
+ fromMe: z.boolean(),
192
+ chat: z.any(), // Circular reference handled later/lazy
193
+ chatId: ChatIdSchema,
194
+ author: z.string().optional(),
195
+ clientUrl: z.string().optional(),
196
+ deprecatedMms3Url: z.string().optional(),
197
+ isQuotedMsgAvailable: z.boolean(),
198
+ quotedMsg: z.any().optional(), // z.lazy(() => MessageSchema.optional()),
199
+ quotedMsgObj: z.any().optional(), // z.lazy(() => MessageSchema.optional()),
200
+ senderId: z.string().optional(),
201
+ }).passthrough();
202
+
203
+
204
+ // Contact
205
+ export const ContactSchema = z.object({
206
+ id: ContactIdSchema,
207
+ name: z.string().optional(),
208
+ shortName: z.string().optional(),
209
+ pushname: z.string().optional(),
210
+ formattedName: z.string().optional(),
211
+ isBusiness: z.boolean().optional(),
212
+ isEnterprise: z.boolean().optional(),
213
+ isMe: z.boolean().optional(),
214
+ isMyContact: z.boolean().optional(),
215
+ isPSA: z.boolean().optional(),
216
+ isUser: z.boolean().optional(),
217
+ isWAContact: z.boolean().optional(),
218
+ labels: z.array(z.string()).optional(),
219
+ msgs: z.array(z.unknown()).nullable().optional(), // Raw nested messages avoid recursive serialization
220
+ profilePicThumbObj: z.object({
221
+ eurl: z.string().optional(),
222
+ id: IdSchema.optional(),
223
+ img: z.string().optional(),
224
+ imgFull: z.string().optional(),
225
+ tag: z.string().optional(),
226
+ }).optional(),
227
+ statusMute: z.boolean().optional(),
228
+ type: z.string().optional(),
229
+ verifiedLevel: z.number().optional(),
230
+ verifiedName: z.string().optional(),
231
+ isOnline: z.boolean().optional(),
232
+ lastSeen: z.number().optional(),
233
+ }).passthrough();
234
+
235
+ export type Contact = z.infer<typeof ContactSchema>;
236
+
237
+ // Location
238
+ export const LocationSchema = z.object({
239
+ lat: z.number().describe('Latitude coordinate'),
240
+ lng: z.number().describe('Longitude coordinate'),
241
+ name: z.string().optional().describe('Location name'),
242
+ address: z.string().optional().describe('Formatted address'),
243
+ url: z.string().optional().describe('WhatsApp location URL'),
244
+ }).passthrough();
245
+
246
+ export type Location = z.infer<typeof LocationSchema>;
247
+
248
+ // Chat
249
+ export const ChatSchema = z.object({
250
+ id: ChatIdSchema,
251
+ name: z.string().optional(),
252
+ formattedTitle: z.string().optional(),
253
+ isGroup: z.boolean(),
254
+ contact: ContactSchema.nullable(),
255
+ groupMetadata: GroupMetadataSchema.nullable().optional(),
256
+ presence: z.record(z.string(), z.unknown()).nullable().optional(),
257
+ t: z.number().optional(),
258
+ unreadCount: z.number().optional(),
259
+ lastReceivedKey: z.any().optional(),
260
+ msgs: z.array(z.unknown()).nullable().optional(), // Raw nested messages avoid recursive serialization
261
+ isReadOnly: z.boolean().optional(),
262
+ muteExpiration: z.number().optional(),
263
+ notSpam: z.boolean().optional(),
264
+ pin: z.number().optional(),
265
+ ack: z.any().optional(),
266
+ }).passthrough().describe('Serialized chat returned by chat lookups and listings. Its id is an opaque ChatId; additional WhatsApp Web fields may be present.');
267
+
268
+ export type Chat = z.infer<typeof ChatSchema>;
269
+
270
+ // Full Message Schema with implementations
271
+ export const MessageSchema = MessageSchemaBase.extend({
272
+ sender: ContactSchema,
273
+ chat: ChatSchema,
274
+ });
275
+
276
+ export type Message = z.infer<typeof MessageSchema>;
277
+
278
+ // Additional return types
279
+ export const SerializedMessageIdSchema = z.object({
280
+ _serialized: z.string(),
281
+ }).passthrough();
282
+
283
+ export const MessageIdReturnSchema = z.union([MessageIdSchema, SerializedMessageIdSchema])
284
+ .describe('A message ID as a string or an object containing the serialized ID. Validate it before passing it to another method.');
285
+ export type MessageIdReturn = z.infer<typeof MessageIdReturnSchema>;
286
+
287
+ export type SerializedMessageId = z.infer<typeof SerializedMessageIdSchema>;
package/src/config.ts ADDED
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Configuration schema and types - re-exported from @open-wa/config
3
+ *
4
+ * This file provides backward compatibility for code that imports from @open-wa/schema.
5
+ * New code should import directly from @open-wa/config.
6
+ *
7
+ * @deprecated Import from '@open-wa/config' instead
8
+ */
9
+
10
+ // Re-export everything from @open-wa/config
11
+ export {
12
+ // Enums
13
+ QRFormat,
14
+ CLOUD_PROVIDERS,
15
+ DIRECTORY_STRATEGY,
16
+ NotificationLanguage,
17
+ OnError,
18
+ LicenseType,
19
+ // Sub-schemas
20
+ SessionDataSchema,
21
+ DevToolsSchema,
22
+ ProxyServerCredentialsSchema,
23
+ CloudUploadOptionsSchema,
24
+ ViewportSchema,
25
+ S3SyncSchema,
26
+ LoggingTransportSchema,
27
+ // Main schema
28
+ ConfigSchema,
29
+ PartialConfigSchema,
30
+ StrictConfigSchema,
31
+ // Types
32
+ type Config,
33
+ type PartialConfig,
34
+ type DeepPartialConfig,
35
+ type StrictConfig,
36
+ type SessionData,
37
+ type DevTools,
38
+ type ProxyServerCredentials,
39
+ type CloudUploadOptions,
40
+ type Viewport,
41
+ type S3Sync,
42
+ type LoggingTransport,
43
+ // Validation helpers
44
+ validateConfig,
45
+ parseConfig,
46
+ getDefaultConfig,
47
+ } from '@open-wa/config';
package/src/enums.ts ADDED
@@ -0,0 +1,63 @@
1
+ import { z } from 'zod';
2
+
3
+ /**
4
+ * Action types for RBAC permissions
5
+ * - read: Retrieve data (e.g., get contact, chat object)
6
+ * - send: Create/send new content (e.g., send message, image, story)
7
+ * - update: Modify existing data (e.g., update message, chat metadata, promote admin)
8
+ * - delete: Remove data (e.g., delete chat, story, remove contact, demote admin)
9
+ */
10
+ export const ActionEnum = z.enum([
11
+ 'read',
12
+ 'send',
13
+ 'update',
14
+ 'delete'
15
+ ]);
16
+
17
+ export type ActionType = z.infer<typeof ActionEnum>;
18
+
19
+ /**
20
+ * License tiers for feature gating
21
+ * - none: Available to all users
22
+ * - insiders: Requires insiders license
23
+ * - restricted: Requires special/restricted license
24
+ */
25
+ export const LicenseEnum = z.enum([
26
+ 'none',
27
+ 'insiders',
28
+ 'restricted'
29
+ ]);
30
+
31
+ export type LicenseTier = z.infer<typeof LicenseEnum>;
32
+
33
+ /**
34
+ * Functionality scope for WhatsApp account types
35
+ * - both: Works on both business and personal accounts
36
+ * - business-only: Only works on business accounts
37
+ * - personal-only: Only works on personal accounts
38
+ */
39
+ export const FunctionalityEnum = z.enum([
40
+ 'both',
41
+ 'business-only',
42
+ 'personal-only'
43
+ ]);
44
+
45
+ export type FunctionalityScope = z.infer<typeof FunctionalityEnum>;
46
+
47
+ /**
48
+ * HTTP methods for API mapping
49
+ * - AUTO: Automatically inferred from action type or defaults to POST
50
+ * - GET, POST, PUT, DELETE, PATCH, OPTIONS, HEAD: Standard HTTP methods
51
+ */
52
+ export const HttpMethodEnum = z.enum([
53
+ 'AUTO',
54
+ 'GET',
55
+ 'POST',
56
+ 'PUT',
57
+ 'DELETE',
58
+ 'PATCH',
59
+ 'OPTIONS',
60
+ 'HEAD'
61
+ ]);
62
+
63
+ export type HttpMethod = z.infer<typeof HttpMethodEnum>;
@@ -0,0 +1,33 @@
1
+ import { z } from 'zod';
2
+ import { defineListenerV2 } from './registry';
3
+
4
+ export const participantsChangedEvent = defineListenerV2('participantsChanged', {
5
+ legacyName: 'onParticipantsChanged',
6
+ meta: {
7
+ description: 'Fired when group participants change',
8
+ namespace: 'groups',
9
+ status: 'stable',
10
+ license: 'none',
11
+ },
12
+ payload: z.object({
13
+ groupId: z.string(),
14
+ action: z.enum(['add', 'remove', 'promote', 'demote']),
15
+ participantIds: z.array(z.string()),
16
+ by: z.string().optional(),
17
+ }),
18
+ });
19
+
20
+ export const addedToGroupEvent = defineListenerV2('addedToGroup', {
21
+ legacyName: 'onAddedToGroup',
22
+ meta: {
23
+ description: 'Fired when you are added to a group',
24
+ namespace: 'groups',
25
+ status: 'stable',
26
+ license: 'none',
27
+ },
28
+ payload: z.object({
29
+ groupId: z.string(),
30
+ groupName: z.string(),
31
+ addedBy: z.string().optional(),
32
+ }),
33
+ });
@@ -0,0 +1,4 @@
1
+ export * from './registry';
2
+ export * from './messaging';
3
+ export * from './state';
4
+ export * from './groups';
@@ -0,0 +1,86 @@
1
+ import { InteractiveResponseSchema, FormResponseSchema } from '../interactive';
2
+ import { z } from 'zod';
3
+ import { defineListenerV2 } from './registry';
4
+ import { MessageSchema, MessageAck } from '../common-types';
5
+
6
+ const AckSchema = z.object({
7
+ id: z.string(),
8
+ chatId: z.string(),
9
+ ack: z.nativeEnum(MessageAck),
10
+ timestamp: z.number().optional(),
11
+ });
12
+
13
+ export const messageEvent = defineListenerV2('message', {
14
+ legacyName: 'onMessage',
15
+ meta: {
16
+ description: 'Fired when a new message is received (excluding own messages)',
17
+ namespace: 'messages',
18
+ status: 'stable',
19
+ license: 'none',
20
+ },
21
+ payload: MessageSchema,
22
+ defaultQueueOptions: { concurrency: 1 },
23
+ });
24
+
25
+ export const anyMessageEvent = defineListenerV2('anyMessage', {
26
+ legacyName: 'onAnyMessage',
27
+ meta: {
28
+ description: 'Fired for any message including own messages',
29
+ namespace: 'messages',
30
+ status: 'stable',
31
+ license: 'none',
32
+ },
33
+ payload: MessageSchema,
34
+ defaultQueueOptions: { concurrency: 1 },
35
+ });
36
+
37
+ export const messageDeletedEvent = defineListenerV2('messageDeleted', {
38
+ legacyName: 'onMessageDeleted',
39
+ meta: {
40
+ description: 'Fired when a message is deleted',
41
+ namespace: 'messages',
42
+ status: 'stable',
43
+ license: 'none',
44
+ },
45
+ payload: MessageSchema,
46
+ });
47
+
48
+ export const ackEvent = defineListenerV2('ack', {
49
+ legacyName: 'onAck',
50
+ meta: {
51
+ description: 'Fired when a message acknowledgment is received',
52
+ namespace: 'messages',
53
+ status: 'stable',
54
+ license: 'none',
55
+ },
56
+ payload: AckSchema,
57
+ });
58
+
59
+ export const reactionEvent = defineListenerV2('reaction', {
60
+ legacyName: 'onReaction',
61
+ meta: {
62
+ description: 'Fired when a reaction is added to a message',
63
+ namespace: 'messages',
64
+ status: 'stable',
65
+ license: 'none',
66
+ },
67
+ payload: z.object({
68
+ messageId: z.string(),
69
+ reaction: z.string(),
70
+ senderId: z.string(),
71
+ timestamp: z.number(),
72
+ }),
73
+ });
74
+
75
+ export const interactiveResponseEvent = defineListenerV2('interactiveResponse', {
76
+ legacyName: 'onInteractiveResponse',
77
+ meta: { description: 'Structured reply, list, form or native interactive response', namespace: 'messages', status: 'stable', license: 'insiders' },
78
+ payload: InteractiveResponseSchema,
79
+ defaultQueueOptions: { concurrency: 1 },
80
+ });
81
+ export const formResponseEvent = defineListenerV2('formResponse', {
82
+ legacyName: 'onFormResponse',
83
+ meta: { description: 'A form submission with question IDs and chosen option IDs', namespace: 'messages', status: 'stable', license: 'insiders' },
84
+ payload: FormResponseSchema,
85
+ defaultQueueOptions: { concurrency: 1 },
86
+ });
@@ -0,0 +1,124 @@
1
+ import { z } from 'zod';
2
+ import { LicenseTier } from '../enums';
3
+
4
+ export type QueueOverloadStrategy = 'backpressure' | 'dropping';
5
+
6
+ export interface QueueOptions {
7
+ concurrency?: number;
8
+ capacity?: number;
9
+ overload?: QueueOverloadStrategy;
10
+ ordering?: 'fifo';
11
+ intervalCap?: number;
12
+ interval?: number;
13
+ timeout?: number;
14
+ }
15
+
16
+ export type EventStatus = 'stable' | 'beta' | 'deprecated' | 'experimental';
17
+
18
+ export interface EventMetadata {
19
+ eventName: string;
20
+ legacyName: string;
21
+ description?: string;
22
+ namespace?: string;
23
+ status?: EventStatus;
24
+ deprecated?: string;
25
+ license?: LicenseTier;
26
+ since?: string;
27
+ payloadSchema: z.ZodTypeAny;
28
+ defaultQueueOptions?: QueueOptions;
29
+ }
30
+
31
+ export interface EventDefinition {
32
+ callbackSchema: z.ZodFunction<any, any>;
33
+ meta: EventMetadata;
34
+ }
35
+
36
+ const eventsByName = new Map<string, EventDefinition>();
37
+ const nameByCallback = new WeakMap<z.ZodFunction<any, any>, string>();
38
+
39
+ export const eventRegistry = {
40
+ register(def: EventDefinition): z.ZodFunction<any, any> {
41
+ const name = def.meta.eventName;
42
+
43
+ if (eventsByName.has(name)) {
44
+ throw new Error(`Event "${name}" already registered`);
45
+ }
46
+
47
+ eventsByName.set(name, def);
48
+ nameByCallback.set(def.callbackSchema, name);
49
+
50
+ return def.callbackSchema;
51
+ },
52
+
53
+ get(name: string): EventDefinition | undefined {
54
+ return eventsByName.get(name);
55
+ },
56
+
57
+ getByLegacyName(legacyName: string): EventDefinition | undefined {
58
+ for (const def of eventsByName.values()) {
59
+ if (def.meta.legacyName === legacyName) return def;
60
+ }
61
+ return undefined;
62
+ },
63
+
64
+ has(name: string): boolean {
65
+ return eventsByName.has(name);
66
+ },
67
+
68
+ getAll(): EventDefinition[] {
69
+ return Array.from(eventsByName.values());
70
+ },
71
+
72
+ getByNamespace(namespace: string): EventDefinition[] {
73
+ return this.getAll().filter(def => def.meta.namespace === namespace);
74
+ },
75
+
76
+ clear(): void {
77
+ eventsByName.clear();
78
+ }
79
+ };
80
+
81
+ export const QueueOptionsSchema = z.object({
82
+ concurrency: z.number().int().positive().optional(),
83
+ capacity: z.number().int().positive().optional(),
84
+ overload: z.enum(['backpressure', 'dropping']).optional(),
85
+ ordering: z.literal('fifo').optional(),
86
+ intervalCap: z.number().int().positive().optional(),
87
+ interval: z.number().positive().optional(),
88
+ timeout: z.number().positive().optional(),
89
+ }).optional();
90
+
91
+ export function defineListenerV2<T extends z.ZodTypeAny>(
92
+ name: string,
93
+ params: {
94
+ legacyName?: string;
95
+ meta: Omit<EventMetadata, 'eventName' | 'legacyName' | 'payloadSchema'>;
96
+ payload: T;
97
+ defaultQueueOptions?: QueueOptions;
98
+ }
99
+ ): z.ZodFunction<any, any> {
100
+
101
+ const legacyName = params.legacyName || `on${name.charAt(0).toUpperCase()}${name.slice(1)}`;
102
+
103
+ const callbackSchema = z.function({
104
+ input: z.tuple([params.payload, QueueOptionsSchema]),
105
+ output: z.union([
106
+ z.boolean(),
107
+ z.promise(z.boolean()),
108
+ z.function({ input: z.tuple([]), output: z.void() }),
109
+ ])
110
+ });
111
+
112
+ eventRegistry.register({
113
+ callbackSchema,
114
+ meta: {
115
+ eventName: name,
116
+ legacyName,
117
+ payloadSchema: params.payload,
118
+ defaultQueueOptions: params.defaultQueueOptions,
119
+ ...params.meta
120
+ }
121
+ });
122
+
123
+ return callbackSchema as any;
124
+ }