@open-wa/schema 5.9.7 → 5.11.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 (67) hide show
  1. package/dist/generated/index.cjs +1 -1
  2. package/dist/generated/index.cjs.map +1 -1
  3. package/dist/generated/index.d.cts +141 -583
  4. package/dist/generated/index.d.cts.map +1 -1
  5. package/dist/generated/index.d.mts +141 -583
  6. package/dist/generated/index.d.mts.map +1 -1
  7. package/dist/generated/index.mjs +1 -1
  8. package/dist/generated/index.mjs.map +1 -1
  9. package/dist/{index-j2GMQzWY.d.mts → index-DlfSVhzo.d.mts} +53 -234
  10. package/dist/index-DlfSVhzo.d.mts.map +1 -0
  11. package/dist/{index-BR61SSKs.d.cts → index-JLPIa9s-.d.cts} +53 -234
  12. package/dist/index-JLPIa9s-.d.cts.map +1 -0
  13. package/dist/index.cjs +20 -11
  14. package/dist/index.cjs.map +1 -1
  15. package/dist/index.d.cts +3 -3
  16. package/dist/index.d.mts +3 -3
  17. package/dist/index.mjs +16 -10
  18. package/dist/index.mjs.map +1 -1
  19. package/dist/{interactive-DxUwKpzK.d.cts → interactive-BE_M4nur.d.cts} +14 -6
  20. package/dist/interactive-BE_M4nur.d.cts.map +1 -0
  21. package/dist/{interactive-DxUwKpzK.d.mts → interactive-BE_M4nur.d.mts} +14 -6
  22. package/dist/interactive-BE_M4nur.d.mts.map +1 -0
  23. package/dist/interactive-ClvvgmVP.cjs +630 -0
  24. package/dist/interactive-ClvvgmVP.cjs.map +1 -0
  25. package/dist/interactive-Dec4HB2U.mjs +475 -0
  26. package/dist/interactive-Dec4HB2U.mjs.map +1 -0
  27. package/dist/interactive.cjs +26 -304
  28. package/dist/interactive.d.cts +2 -2
  29. package/dist/interactive.d.mts +2 -2
  30. package/dist/interactive.mjs +2 -283
  31. package/dist/methods/index.cjs +1 -1
  32. package/dist/methods/index.d.cts +1 -1
  33. package/dist/methods/index.d.mts +1 -1
  34. package/dist/methods/index.mjs +1 -1
  35. package/dist/{methods-D4XLSUxh.cjs → methods-CILSsPyT.cjs} +27 -93
  36. package/dist/methods-CILSsPyT.cjs.map +1 -0
  37. package/dist/{methods-CpeSpB2P.mjs → methods-L7ijqbZM.mjs} +19 -79
  38. package/dist/methods-L7ijqbZM.mjs.map +1 -0
  39. package/package.json +3 -3
  40. package/src/__tests__/booking-time.contract.test.ts +88 -0
  41. package/src/__tests__/generators.contract.test.ts +82 -45
  42. package/src/booking-time.ts +39 -0
  43. package/src/common-types.ts +1 -1
  44. package/src/effect-projection.ts +90 -47
  45. package/src/events/asyncapi.ts +2 -2
  46. package/src/events/contracts.ts +10 -3
  47. package/src/events/polls.ts +1 -1
  48. package/src/generated/BaseClient.ts +12 -12
  49. package/src/generated/asyncapi.json +206 -95
  50. package/src/generated/openapi.json +1702 -1337
  51. package/src/interactive.ts +12 -1
  52. package/src/methods/calls.ts +4 -4
  53. package/src/methods/contacts.ts +1 -1
  54. package/src/methods/groups.ts +2 -2
  55. package/src/methods/messaging.ts +7 -7
  56. package/src/methods/session.ts +1 -1
  57. package/src/methods/whatsapp-events.ts +1 -1
  58. package/src/parameters.ts +2 -2
  59. package/src/return-types.ts +1 -1
  60. package/dist/index-BR61SSKs.d.cts.map +0 -1
  61. package/dist/index-j2GMQzWY.d.mts.map +0 -1
  62. package/dist/interactive-DxUwKpzK.d.cts.map +0 -1
  63. package/dist/interactive-DxUwKpzK.d.mts.map +0 -1
  64. package/dist/interactive.cjs.map +0 -1
  65. package/dist/interactive.mjs.map +0 -1
  66. package/dist/methods-CpeSpB2P.mjs.map +0 -1
  67. package/dist/methods-D4XLSUxh.cjs.map +0 -1
@@ -0,0 +1,88 @@
1
+ import { expect, test } from 'vitest';
2
+ import { Schema, SchemaGetter } from 'effect';
3
+ import { z } from 'zod';
4
+ import { BookingTimestampSchema, normalizeBookingTimestamp, type BookingTimestamp } from '../booking-time';
5
+ import { BookingTimestampRegistrySchema, InteractiveContentSchema, defineInteractiveMessage, type DecodedInteractiveContent } from '../interactive';
6
+ import { projectEffectSchema } from '../effect-projection';
7
+ import { CallSnapshotSchema } from '../calling';
8
+ import { EventInputRegistrySchema } from '../whatsapp-event-registry';
9
+
10
+ type Assert<T extends true> = T;
11
+ type Equal<A, B> = [A, B] extends [B, A] ? true : false;
12
+ export type RegistryAcceptsTimestampStrings = Assert<Equal<z.input<typeof BookingTimestampRegistrySchema>, string>>;
13
+ export type RegistryReturnsEffectBrand = Assert<Equal<z.output<typeof BookingTimestampRegistrySchema>, BookingTimestamp>>;
14
+ export type DecoderReturnsEffectBrand = Assert<Equal<ReturnType<typeof normalizeBookingTimestamp>, BookingTimestamp>>;
15
+ type ParsedBooking = Extract<DecodedInteractiveContent, { type: 'booking' }>;
16
+ export type ParsedBookingRequiresBrand = Assert<Equal<ParsedBooking['booking']['startAt'], BookingTimestamp>>;
17
+ export type RawStringsCannotBeParsedTimestamps = Assert<string extends BookingTimestamp ? false : true>;
18
+
19
+ test('Effect and the serving projection decode offsets and fractions and encode canonical UTC seconds', () => {
20
+ const input = '2026-07-26T00:00:00.987+01:00';
21
+ const expected = '2026-07-25T23:00:00Z';
22
+ const decoded = normalizeBookingTimestamp(input);
23
+ expect(decoded).toBe(expected);
24
+ expect(Schema.encodeSync(BookingTimestampSchema)(decoded)).toBe(expected);
25
+ expect(BookingTimestampRegistrySchema.parse(input)).toBe(expected);
26
+ expect(z.encode(BookingTimestampRegistrySchema, decoded)).toBe(expected);
27
+ expect(z.safeEncode(BookingTimestampRegistrySchema, input as BookingTimestamp).success).toBe(false);
28
+ });
29
+
30
+ test('invalid calendar dates and ambiguous timestamps fail in both Effect and the projection', () => {
31
+ const invalid = ['2026-02-29T14:00:00Z', '2026-04-31T14:00:00Z', '2026-13-01T14:00:00Z',
32
+ '2026-10-26T24:00:00Z', '2026-10-26T14:00:00+24:00', '2026-10-26T14:00:00', '2026-10-26', 'not a date'];
33
+ for (const input of invalid) {
34
+ expect(() => normalizeBookingTimestamp(input)).toThrow();
35
+ expect(BookingTimestampRegistrySchema.safeParse(input).success).toBe(false);
36
+ }
37
+ expect(normalizeBookingTimestamp('2028-02-29T14:00:00Z')).toBe('2028-02-29T14:00:00Z');
38
+ });
39
+
40
+ test('builders normalize automatically and reject ranges collapsed by whole-second precision', () => {
41
+ const content = { type: 'booking' as const, body: 'Booking', booking: {
42
+ startAt: '2026-07-26T14:00:00.100+01:00', endAt: '2026-07-26T14:30:00.900+01:00', location: 'Office',
43
+ } };
44
+ const parsed = defineInteractiveMessage(content);
45
+ expect(parsed.booking).toEqual({ startAt: '2026-07-26T13:00:00Z', endAt: '2026-07-26T13:30:00Z', location: 'Office' });
46
+ expect(content.booking.startAt).toBe('2026-07-26T14:00:00.100+01:00');
47
+ expect(() => InteractiveContentSchema.parse({ ...content, booking: {
48
+ ...content.booking, endAt: '2026-07-26T14:00:00.500+01:00',
49
+ } })).toThrow('after');
50
+ });
51
+
52
+ test('input and output JSON Schema retain their distinct patterns and Effect metadata', () => {
53
+ const input = z.toJSONSchema(BookingTimestampRegistrySchema, { io: 'input' });
54
+ const output = z.toJSONSchema(BookingTimestampRegistrySchema, { io: 'output' });
55
+ expect(input).toMatchObject({ type: 'string', format: 'date-time', examples: ['2026-10-26T14:00:00Z', '2026-07-26T14:00:00.000+01:00'] });
56
+ expect(input.description).toContain('Decoding converts');
57
+ expect(output).toMatchObject({ type: 'string', format: 'date-time', title: 'BookingTimestamp', examples: ['2026-10-26T14:00:00Z'] });
58
+ expect(output.description).toContain('whole seconds');
59
+ expect(new RegExp(input.pattern!).test('2026-07-26T14:00:00.123+01:00')).toBe(true);
60
+ expect(new RegExp(output.pattern!).test('2026-07-26T14:00:00.123Z')).toBe(false);
61
+ expect(new RegExp(output.pattern!).test('2026-07-26T14:00:00Z')).toBe(true);
62
+ });
63
+
64
+ test('the bridge executes nested Effect transformations, refinements and encoders while retaining Struct.shape', () => {
65
+ const count = Schema.String.pipe(Schema.decodeTo(Schema.Number, {
66
+ decode: SchemaGetter.transform(Number), encode: SchemaGetter.transform(String),
67
+ }));
68
+ const effect = Schema.Struct({ count, until: Schema.optional(count) }).check(Schema.makeFilter(value =>
69
+ value.until === undefined || value.until > value.count || 'until must follow count'));
70
+ const projected = projectEffectSchema(effect);
71
+ expect('shape' in projected).toBe(true);
72
+ expect(projected.parse({ count: '2', until: '3' })).toEqual({ count: 2, until: 3 });
73
+ expect(projected.parse({ count: '2' })).toEqual({ count: 2 });
74
+ expect(z.encode(projected, { count: 2, until: 3 })).toEqual({ count: '2', until: '3' });
75
+ expect(projected.safeParse({ count: '2', until: '1' }).success).toBe(false);
76
+ expect(z.safeEncode(projected, { count: 2, until: 1 }).success).toBe(false);
77
+ });
78
+
79
+ test('existing call and event projections retain optional fields and validation', () => {
80
+ const call = { id: 'id', sessionId: 'session', generation: 'generation', peer: 'peer', state: 'active', direction: 'incoming',
81
+ video: false, terminal: false, observedAt: 1 };
82
+ const projected = projectEffectSchema(CallSnapshotSchema);
83
+ expect(projected.parse(call)).toEqual(call);
84
+ expect(projected.safeParse({ ...call, direction: 'sideways' }).success).toBe(false);
85
+ expect(EventInputRegistrySchema.parse({ name: 'Meetup', startTime: 100 })).toEqual({ name: 'Meetup', startTime: 100 });
86
+ expect(EventInputRegistrySchema.safeParse({ name: 'Meetup', startTime: 1.5 }).success).toBe(false);
87
+ expect(EventInputRegistrySchema.safeParse({ name: 'Meetup', startTime: 100, endTime: 99 }).success).toBe(false);
88
+ });
@@ -97,24 +97,26 @@ describe('generator outputs', () => {
97
97
 
98
98
  describe('Client API reference docs', () => {
99
99
  const indexPath = path.join(clientDocsDir, 'index.mdx');
100
- const metaPath = path.join(clientDocsDir, 'meta.json');
100
+ const referenceMetaPath = path.join(clientDocsDir, '../meta.json');
101
101
  const messagesPath = path.join(clientDocsDir, 'messages.mdx');
102
102
 
103
- it('should create client docs index and navigation metadata', () => {
103
+ it('should create the overview page and list namespaces first in the sidebar', () => {
104
104
  expect(fs.existsSync(indexPath)).toBe(true);
105
- expect(fs.existsSync(metaPath)).toBe(true);
105
+ expect(fs.existsSync(referenceMetaPath)).toBe(true);
106
106
 
107
107
  const indexContent = fs.readFileSync(indexPath, 'utf-8');
108
- const meta = JSON.parse(fs.readFileSync(metaPath, 'utf-8'));
108
+ const meta = JSON.parse(fs.readFileSync(referenceMetaPath, 'utf-8'));
109
109
 
110
- expect(indexContent).toContain('Generated file warning');
111
- expect(indexContent).toContain('packages/schema/scripts/gen-client-reference-docs.ts');
110
+ expect(indexContent).toContain('title: "Overview"');
112
111
  expect(indexContent).toContain('<Cards>');
113
- expect(indexContent).toContain('<Card title="Messages" href="./messages">');
114
- expect(indexContent).toContain('client methods');
115
- expect(meta.title).toBe('Client API');
116
- expect(meta.icon).toBe('BookOpen');
117
- expect(meta.pages).toContain('messages');
112
+ expect(indexContent).toContain('<Card title="Messages" href="/docs/reference/client/messages">');
113
+ expect(indexContent).not.toContain('gen-client-reference-docs');
114
+ expect(indexContent).not.toMatch(/schema[- ]registry/i);
115
+ expect(meta.title).toBe('API reference');
116
+ expect(meta.pages.slice(0, 3)).toEqual(['!index', 'client/index', 'client/messages']);
117
+ expect(meta.pages.indexOf('client/messages')).toBeLessThan(meta.pages.indexOf('create'));
118
+ expect(meta.pages.at(-1)).toBe('client/send-text-worked-example');
119
+ expect(meta.pages).not.toContain('workspaces');
118
120
  });
119
121
 
120
122
  it('should create a generated MDX page for every namespace', () => {
@@ -124,58 +126,93 @@ describe('generator outputs', () => {
124
126
  .filter((fileName) => fileName.endsWith('.mdx') && fileName !== 'index.mdx' && fileName !== 'client.mdx')
125
127
  .sort();
126
128
 
127
- expect(mdxFiles).toEqual(expect.arrayContaining(namespaces.map((namespace) => `${namespace.toLowerCase()}.mdx`)));
129
+ expect(mdxFiles).toEqual(expect.arrayContaining(namespaces.map((namespace) => `${namespace === 'events' ? 'whatsapp-events' : namespace.toLowerCase()}.mdx`)));
128
130
  });
129
131
 
130
- it('should include sendText method details from the schema registry', () => {
132
+ it('should order methods by use and render sendText details', () => {
131
133
  expect(fs.existsSync(messagesPath)).toBe(true);
132
134
  const content = fs.readFileSync(messagesPath, 'utf-8');
133
135
 
134
- expect(content).toContain('Generated file warning');
135
- expect(content).toContain('packages/schema/scripts/gen-client-reference-docs.ts');
136
- expect(content).toContain('## `sendText`');
137
- expect(content).toContain('### Overview');
138
- expect(content).toContain('| Prop | Value |');
139
- expect(content).toContain('| Namespace | `messages` |');
140
- expect(content).toContain('| Action | `send` |');
141
- expect(content).toContain('| Positional parameter order | `to`, `content`, `options` |');
142
- expect(content).toContain('| Aliases | `messages.sendText` |');
143
- expect(content).toContain('### Routes');
144
- expect(content).toContain('| Type | Method | Path | Name | Status |');
145
- expect(content).toContain('| Primary | `POST` | `/api/messages/sendText` | `sendText` | Active |');
146
- expect(content).toContain('| Alias | `POST` | `/api/sendText` | `sendText` | Active |');
147
- expect(content).toContain('### Usage');
148
- expect(content).toContain('<InterfaceTabs>');
149
- expect(content).toContain('<InterfaceTab value="Embedded">');
150
- expect(content).toContain('const result = await client.sendText({');
151
- expect(content).toContain('// namespaced form: client.messages.sendText(...)');
136
+ expect(content).toContain('title: "Messages"');
137
+ expect(content.indexOf('## `sendText`')).toBeGreaterThan(-1);
138
+ expect(content.indexOf('## `sendText`')).toBeLessThan(content.indexOf('## `sendImage`'));
139
+ expect(content.indexOf('## `sendImage`')).toBeLessThan(content.indexOf('## `deleteMessage`'));
140
+ expect(content).toContain('```ts\nclient.sendText(to: string, content: string, options?: unknown): Promise<MessageId>\n```');
141
+ // Sub-headings are literal <h3> elements: out of the TOC, with no copy-link button.
142
+ expect(content).toContain('<h3 id="sendtext-usage" className="scroll-m-28">Usage</h3>');
143
+ expect(content).not.toContain('[!toc]');
144
+ expect(content).toContain('<InterfaceTab value="SDK">');
152
145
  expect(content).toContain('<InterfaceTab value="SocketClient">');
153
- expect(content).toContain('<InterfaceTab value="Easy API">');
146
+ expect(content).toContain('<InterfaceTab value="HTTP">');
154
147
  expect(content).toContain('curl -X POST "http://localhost:8080/api/messages/sendText"');
155
- expect(content).toContain('### Parameters');
156
- expect(content).toContain('<AutoTypeTable path="./generated-method-params.ts" name="SendTextParams" />');
157
- expect(content).toContain('### Output');
158
- expect(content).toContain('| Return type | `object &#123; _serialized &#125; \\| boolean \\| string` |');
159
- expect(content).not.toContain('Returns: `');
148
+ expect(content).toContain('<h3 id="sendtext-parameters" className="scroll-m-28">Parameters</h3>');
149
+ expect(content).toContain('| `to` | `string` | Recipient chat ID. The target chat for a send operation. Also accepts `chatId`. |');
150
+ expect(content).not.toContain('AutoTypeTable');
151
+ expect(content).toContain('<h3 id="sendtext-returns" className="scroll-m-28">Returns</h3>');
152
+ expect(content).toContain('Resolves to [`MessageId`](/docs/reference/client/return-types#messageid).');
153
+ expect(content).toContain('**HTTP:** `POST /api/messages/sendText`, or `/api/sendText`. **Also named:** `messages.sendText`.');
154
+ expect(content).not.toContain('<details>');
155
+ expect(content).not.toContain('"options": {}');
156
+ expect(content).not.toContain('**Signature**');
157
+ });
158
+
159
+ it('should render licensed methods inside the tier treatment with a license sentence', () => {
160
+ expect(fs.existsSync(messagesPath)).toBe(true);
161
+ const content = fs.readFileSync(messagesPath, 'utf-8');
162
+
163
+ expect(content).toContain('<LicensedMethodSection tier="insiders">');
164
+ expect(content).toContain('## `sendButtons`');
165
+ expect(content).toContain('Needs an Insiders license.');
160
166
  });
161
167
 
162
- it('should render licensed methods with callouts and visible heading indicators', () => {
163
- expect(fs.existsSync(messagesPath)).toBe(true);
168
+ it('should link documented parameter types to Return types instead of expanding them', () => {
164
169
  const content = fs.readFileSync(messagesPath, 'utf-8');
165
170
 
166
- expect(content).toContain('## `sendButtons` - insiders');
167
- expect(content).toContain('<LicensedFeatureCallout tier="insiders" />');
168
- expect(content).toContain('| License | `insiders` |');
171
+ expect(content).toContain('client.sendInteractive(to: string, content: InteractiveContent): Promise<string>');
172
+ expect(content).toContain('| `content` | [`InteractiveContent`](/docs/reference/client/return-types#interactivecontent) |');
173
+ expect(fs.readFileSync(path.join(clientDocsDir, 'media.mdx'), 'utf-8')).toContain('client.decryptMedia(message: Message): Promise<DataURL>');
174
+ });
175
+
176
+ it('should make the A–Z page a lookup that links to namespace anchors', () => {
177
+ const content = fs.readFileSync(path.join(clientDocsDir, 'client.mdx'), 'utf-8');
178
+ const count = clientRegistry.getAll().length;
179
+
180
+ expect(content).toContain(`<ClientReference total={${count}}>`);
181
+ expect(content).toContain('| [`sendText`](/docs/reference/client/messages#sendtext) | Messages |');
182
+ expect(content.match(/^\| \[`/gm)).toHaveLength(count);
183
+ expect(content).not.toContain('<details>');
184
+ expect(content).not.toContain('```');
185
+ });
186
+
187
+ it('should keep Return types declarations without repeating shared fields', () => {
188
+ const content = fs.readFileSync(path.join(clientDocsDir, 'return-types.mdx'), 'utf-8');
189
+ const story = content.slice(content.indexOf('## Story'), content.indexOf('\n## ', content.indexOf('## Story') + 1));
190
+
191
+ expect(content).toContain('<TypeDeclaration name="Message" code={"type Message = {');
192
+ expect(story).toContain('Story has the same fields as [Message](/docs/reference/client/return-types#message), apart from these.');
193
+ expect(story).not.toContain('| `body` |');
194
+ });
195
+
196
+ it('should title the media method page apart from the media guide', () => {
197
+ expect(fs.readFileSync(path.join(clientDocsDir, 'media.mdx'), 'utf-8')).toContain('title: "Media methods"');
198
+ });
199
+
200
+ it('should keep implementation mechanisms out of the generated pages', () => {
201
+ const pages = fs.readdirSync(clientDocsDir).filter((fileName) => fileName.endsWith('.mdx'));
202
+ for (const page of pages) {
203
+ const content = fs.readFileSync(path.join(clientDocsDir, page), 'utf-8');
204
+ expect(content, page).not.toMatch(/private patch|installed patch|\bwapi|webpack|inject|donor|schema-registry|Client API/i);
205
+ }
169
206
  });
170
207
 
171
- it('should visibly label deprecated alias routes in route tables', () => {
208
+ it('should visibly label deprecated alias routes', () => {
172
209
  const contactsPath = path.join(clientDocsDir, 'contacts.mdx');
173
210
  expect(fs.existsSync(contactsPath)).toBe(true);
174
211
  const content = fs.readFileSync(contactsPath, 'utf-8');
175
212
 
176
213
  expect(content).toContain('## `blockContact`');
177
- expect(content).toContain('| Deprecated alias | `PUT` | `/api/contactBlock` | `contactBlock` | **Deprecated** |');
178
- expect(content).toContain('| Deprecated alias | `PUT` | `/api/contacts/contactBlock` | `contacts.contactBlock` | **Deprecated** |');
214
+ expect(content).toContain('Deprecated routes: `/api/contactBlock`, `/api/contacts/contactBlock`.');
215
+ expect(content).toContain('Deprecated names: `contactBlock`, `contacts.contactBlock`.');
179
216
  });
180
217
  });
181
218
  });
@@ -0,0 +1,39 @@
1
+ import { Schema, SchemaGetter } from 'effect';
2
+
3
+ const isoTimestamp = /^\d{4}-\d{2}-\d{2}T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/u;
4
+ const utcSeconds = /^\d{4}-\d{2}-\d{2}T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\dZ$/u;
5
+ const calendarDate = Schema.makeFilter<string>((value) => {
6
+ const year = Number(value.slice(0, 4));
7
+ const month = Number(value.slice(5, 7));
8
+ const day = Number(value.slice(8, 10));
9
+ const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
10
+ const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
11
+ return month >= 1 && month <= 12 && day >= 1 && day <= days[month - 1] && Number.isFinite(Date.parse(value))
12
+ || 'Use a real calendar date and an explicit UTC or numeric timezone';
13
+ }, {
14
+ // Calendar arithmetic has no exact JSON Schema equivalent; retain the other
15
+ // constraints and let the Effect decoder enforce the complete calendar rule.
16
+ toJsonSchema: () => [{}, true],
17
+ });
18
+
19
+ const canonicalTimestamp = Schema.String.check(Schema.isPattern(utcSeconds), calendarDate).annotate({
20
+ title: 'BookingTimestamp',
21
+ description: 'Validated native booking timestamp, encoded as UTC ISO 8601 with whole seconds and no fractional seconds.',
22
+ format: 'date-time',
23
+ examples: ['2026-10-26T14:00:00Z'],
24
+ }).pipe(Schema.brand('BookingTimestamp'));
25
+
26
+ /** Effect owns validation, normalization and encoding for native booking dates. */
27
+ export const BookingTimestampSchema = Schema.String.check(Schema.isPattern(isoTimestamp), calendarDate).annotate({
28
+ description: 'ISO 8601 booking timestamp with an explicit timezone. Decoding converts offsets and fractional seconds to UTC whole seconds for WhatsApp.',
29
+ format: 'date-time',
30
+ examples: ['2026-10-26T14:00:00Z', '2026-07-26T14:00:00.000+01:00'],
31
+ }).pipe(Schema.decodeTo(canonicalTimestamp, {
32
+ decode: SchemaGetter.transform((value) => new Date(value).toISOString().replace(/\.\d{3}Z$/, 'Z')),
33
+ encode: SchemaGetter.transform((value) => value),
34
+ }));
35
+
36
+ export type BookingTimestamp = typeof BookingTimestampSchema.Type;
37
+
38
+ /** Validate and normalize an external timestamp before constructing typed booking data. */
39
+ export const normalizeBookingTimestamp = Schema.decodeUnknownSync(BookingTimestampSchema);
@@ -235,7 +235,7 @@ export const ContactSchema = z.object({
235
235
  msgs: z.array(z.unknown()).nullable().optional(), // Raw nested messages avoid recursive serialization
236
236
  profilePicThumbObj: z.object({
237
237
  eurl: z.string().optional(),
238
- id: IdSchema.optional(),
238
+ id: ContactIdSchema.optional().describe('Serialized contact ID returned by the profile-picture serializer'),
239
239
  img: z.string().optional(),
240
240
  imgFull: z.string().optional(),
241
241
  tag: z.string().optional(),
@@ -1,67 +1,110 @@
1
1
  import { Schema } from 'effect';
2
2
  import { z } from 'zod';
3
3
 
4
- type JsonSchema = { $ref?: string; type?: string; const?: unknown; enum?: unknown[]; anyOf?: JsonSchema[]; oneOf?: JsonSchema[]; properties?: Record<string, JsonSchema>; required?: string[]; items?: JsonSchema; additionalProperties?: boolean | JsonSchema; minimum?: number; maximum?: number; exclusiveMinimum?: number; exclusiveMaximum?: number; minLength?: number; maxLength?: number };
4
+ type JsonSchema = { $ref?: string; type?: string; const?: unknown; enum?: unknown[]; anyOf?: JsonSchema[]; oneOf?: JsonSchema[]; allOf?: JsonSchema[]; properties?: Record<string, JsonSchema>; required?: string[]; items?: JsonSchema; additionalProperties?: boolean | JsonSchema; minimum?: number; maximum?: number; exclusiveMinimum?: number; exclusiveMaximum?: number; minLength?: number; maxLength?: number; pattern?: string; format?: string; title?: string; description?: string; examples?: unknown[] };
5
+ export type SyncEffectSchema = Schema.Top & Schema.ConstraintCodec<unknown, unknown>;
5
6
 
6
- /** Project Effect contracts into the serving method and listener registry. */
7
- export function projectEffectSchema<S extends Schema.Top>(schema: S): z.ZodType<S['Type'], S['Encoded']> {
8
- // JSON codec generation maps undefined to null. Project Struct fields from
9
- // their original schemas so optional properties retain their JS semantics.
10
- if ('fields' in schema) {
11
- const fields = schema.fields as Record<string, Schema.Top>;
12
- const shape = Object.fromEntries(Object.entries(fields).map(([name, field]) => {
13
- const optional = field.ast.context?.isOptional === true;
14
- const hasUndefined = field.ast._tag === 'Union' && field.ast.types.some(member => member._tag === 'Undefined');
15
- const valueSchema = !optional ? field : hasUndefined
16
- ? Schema.required(field as Schema.optional<Schema.Top>)
17
- : Schema.requiredKey(field as Schema.optionalKey<Schema.Top>);
18
- const value = projectEffectSchema(valueSchema);
19
- return [name, optional ? value.optional() : value];
20
- }));
21
- return z.object(shape) as z.ZodType<S['Type'], S['Encoded']>;
22
- }
23
- const document = Schema.toJsonSchemaDocument(schema);
7
+ /** JSON Schema is presentation metadata; Effect remains the validation/codec authority. */
8
+ function projectDocument(document: ReturnType<typeof Schema.toJsonSchemaDocument>): z.ZodType {
24
9
  const project = (node: JsonSchema): z.ZodType => {
25
- if (node.$ref) {
10
+ let value: z.ZodType;
11
+ if (node.allOf) {
12
+ const { allOf, ...base } = node;
13
+ value = project(base);
14
+ for (const clause of allOf) {
15
+ const metadataOnly = Object.keys(clause).every(key => ['title', 'description', 'examples', 'format'].includes(key));
16
+ value = metadataOnly ? value.meta(clause) : z.intersection(value, project({ type: node.type, ...clause }));
17
+ }
18
+ } else if (node.$ref) {
26
19
  const key = node.$ref.split('/').at(-1)!;
27
- return project(document.definitions[key] as JsonSchema);
28
- }
29
- if ('const' in node) return z.literal(node.const as string | number | boolean | null);
30
- if (node.enum) return z.union(node.enum.map(value => z.literal(value as string | number | boolean | null)));
31
- const members = node.anyOf ?? node.oneOf;
32
- if (members) return z.union(members.map(project));
33
- switch (node.type) {
20
+ value = project(document.definitions[key] as JsonSchema);
21
+ } else if ('const' in node) value = z.literal(node.const as string | number | boolean | null);
22
+ else if (node.enum) value = z.union(node.enum.map(item => z.literal(item as string | number | boolean | null)));
23
+ else if (node.anyOf ?? node.oneOf) value = z.union((node.anyOf ?? node.oneOf)!.map(project));
24
+ else switch (node.type) {
34
25
  case 'string': {
35
- let value = z.string();
36
- if (node.minLength !== undefined) value = value.min(node.minLength);
37
- if (node.maxLength !== undefined) value = value.max(node.maxLength);
38
- return value;
26
+ let string = z.string();
27
+ if (node.minLength !== undefined) string = string.min(node.minLength);
28
+ if (node.maxLength !== undefined) string = string.max(node.maxLength);
29
+ if (node.pattern !== undefined) string = string.regex(new RegExp(node.pattern));
30
+ value = string;
31
+ break;
39
32
  }
40
33
  case 'number':
41
34
  case 'integer': {
42
- let value = node.type === 'integer' ? z.number().int() : z.number();
43
- if (node.minimum !== undefined) value = value.min(node.minimum);
44
- if (node.maximum !== undefined) value = value.max(node.maximum);
45
- if (node.exclusiveMinimum !== undefined) value = value.gt(node.exclusiveMinimum);
46
- if (node.exclusiveMaximum !== undefined) value = value.lt(node.exclusiveMaximum);
47
- return value;
35
+ let number = node.type === 'integer' ? z.number().int() : z.number();
36
+ if (node.minimum !== undefined) number = number.min(node.minimum);
37
+ if (node.maximum !== undefined) number = number.max(node.maximum);
38
+ if (node.exclusiveMinimum !== undefined) number = number.gt(node.exclusiveMinimum);
39
+ if (node.exclusiveMaximum !== undefined) number = number.lt(node.exclusiveMaximum);
40
+ value = number;
41
+ break;
48
42
  }
49
- case 'boolean': return z.boolean();
50
- case 'null': return z.null();
51
- case 'array': return z.array(project(node.items ?? {}));
43
+ case 'boolean': value = z.boolean(); break;
44
+ case 'null': value = z.null(); break;
45
+ case 'array': value = z.array(project(node.items ?? {})); break;
52
46
  case 'object': {
53
47
  const properties = node.properties ?? {};
54
48
  const values = typeof node.additionalProperties === 'object' ? project(node.additionalProperties) : node.additionalProperties ? z.unknown() : undefined;
55
- if (!Object.keys(properties).length && values) return z.record(z.string(), values);
49
+ if (!Object.keys(properties).length && values) { value = z.record(z.string(), values); break; }
56
50
  const required = new Set(node.required ?? []);
57
- const object = z.object(Object.fromEntries(Object.entries(properties).map(([key, value]) => {
58
- const field = project(value);
59
- return [key, required.has(key) ? field : field.optional()];
51
+ const object = z.object(Object.fromEntries(Object.entries(properties).map(([key, field]) => {
52
+ const property = project(field);
53
+ return [key, required.has(key) ? property : property.optional()];
60
54
  })));
61
- return values ? object.catchall(values) : object;
55
+ value = values ? object.catchall(values) : object;
56
+ break;
62
57
  }
63
- default: return z.unknown();
58
+ default: value = z.unknown();
64
59
  }
60
+ const { title, description, examples, format } = node;
61
+ return value.meta({ ...(title ? { title } : {}), ...(description ? { description } : {}), ...(examples ? { examples } : {}), ...(format ? { format } : {}) });
65
62
  };
66
- return project(document.schema as JsonSchema) as z.ZodType<S['Type'], S['Encoded']>;
63
+ return project(document.schema as JsonSchema);
64
+ }
65
+
66
+ /** Project synchronous Effect contracts into the method/listener/OpenUI registry. */
67
+ export function projectEffectSchema<S extends SyncEffectSchema>(schema: S): z.ZodType<S['Type'], S['Encoded']> {
68
+ const decoded = Schema.toType(schema);
69
+ const encoded = Schema.toEncoded(schema);
70
+ // Keep Struct.shape for the serving registry, while field codecs perform their
71
+ // real transformations and decoded Struct checks remain authoritative.
72
+ if ('fields' in schema) {
73
+ const fields = schema.fields as Record<string, SyncEffectSchema>;
74
+ const shape = Object.fromEntries(Object.entries(fields).map(([name, field]) => {
75
+ const optional = field.ast.context?.isOptional === true;
76
+ const hasUndefined = field.ast._tag === 'Union' && field.ast.types.some(member => member._tag === 'Undefined');
77
+ const valueSchema = !optional ? field : hasUndefined
78
+ ? Schema.required(field as Schema.optional<SyncEffectSchema>)
79
+ : Schema.requiredKey(field as Schema.optionalKey<SyncEffectSchema>);
80
+ const value = projectEffectSchema(valueSchema);
81
+ return [name, optional ? value.optional() : value];
82
+ }));
83
+ return z.object(shape).superRefine((value, ctx) => {
84
+ try { Schema.decodeUnknownSync(decoded)(value); }
85
+ catch (error) { ctx.addIssue({ code: 'custom', message: String(error) }); }
86
+ }).meta(Schema.resolveAnnotations(schema) ?? {}) as z.ZodType<S['Type'], S['Encoded']>;
87
+ }
88
+ // Identity schemas need Effect's checks but no transformation wrapper. This
89
+ // retains native Zod kinds and input examples for registry documentation.
90
+ if (encoded.ast === decoded.ast) {
91
+ return projectDocument(Schema.toJsonSchemaDocument(schema)).superRefine((value, ctx) => {
92
+ try { Schema.decodeUnknownSync(schema)(value); }
93
+ catch (error) { ctx.addIssue({ code: 'custom', message: String(error) }); }
94
+ }).meta(Schema.resolveAnnotations(schema) ?? {}) as z.ZodType<S['Type'], S['Encoded']>;
95
+ }
96
+ return z.codec(
97
+ projectDocument(Schema.toJsonSchemaDocument(encoded)),
98
+ projectDocument(Schema.toJsonSchemaDocument(decoded)),
99
+ {
100
+ decode: (value, ctx) => {
101
+ try { return Schema.decodeUnknownSync(schema)(value); }
102
+ catch (error) { ctx.issues.push({ code: 'custom', input: value, message: String(error) }); return z.NEVER; }
103
+ },
104
+ encode: (value, ctx) => {
105
+ try { return Schema.encodeSync(schema)(Schema.decodeUnknownSync(decoded)(value)); }
106
+ catch (error) { ctx.issues.push({ code: 'custom', input: value, message: String(error) }); return z.NEVER; }
107
+ },
108
+ },
109
+ ) as z.ZodType<S['Type'], S['Encoded']>;
67
110
  }
@@ -21,7 +21,7 @@ export function createAsyncApiDocument(options: AsyncApiOptions = {}) {
21
21
  ? { id: { type: 'string' }, event: { const: contract.name }, payload: payloadRef, ts: { type: 'number' }, sessionId: { type: 'string' } }
22
22
  : transport === 'webhook'
23
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' } };
24
+ : { eventId: { type: 'string' }, name: { const: contract.name }, timestamp: { type: 'string', format: 'date-time' }, data: payloadRef, cursor: { type: ['string', 'null'] } };
25
25
  messages[id] = {
26
26
  name: contract.name, title: contract.name, summary: contract.description,
27
27
  contentType: 'application/json',
@@ -38,7 +38,7 @@ export function createAsyncApiDocument(options: AsyncApiOptions = {}) {
38
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
39
  : transport === 'webhook'
40
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.`,
41
+ : `Verified subscriber-provided HTTPS callback. Subscribe through ${basePath}${options.mcpPath ?? '/mcp'} using MCP 2026-07-28. Standard Webhooks signatures, stable event IDs and transient retries for up to 15 minutes. No retry on 410/413. The same events are available through events/poll and events/stream; cursors replay events retained on the server (15 minutes by default).`,
42
42
  messages: { event: { $ref: `#/components/messages/${id}` } },
43
43
  'x-openwa-transport': transport,
44
44
  ...(transport === 'sse' ? { servers: [{ $ref: '#/servers/easyApi' }], 'x-openwa-sse': { event: contract.name, contentType: 'text/event-stream', topics: contract.name } } : {}),
@@ -35,7 +35,12 @@ export interface EventContract {
35
35
  optionalRuntimeListener: boolean;
36
36
  payloadSchema: z.ZodType;
37
37
  transports: readonly ('sse' | 'webhook' | 'mcp')[];
38
- mcp?: { inputSchema: z.ZodType; payloadSchema: z.ZodType; project(payload: unknown, sessionId: string): unknown };
38
+ mcp?: {
39
+ inputSchema: z.ZodType; payloadSchema: z.ZodType;
40
+ project(payload: unknown, sessionId: string): unknown;
41
+ /** Stable upstream identity, so the same WhatsApp event deduplicates across delivery paths. */
42
+ eventId?(data: Record<string, unknown>): string | undefined;
43
+ };
39
44
  }
40
45
 
41
46
  const record = (value: unknown): Record<string, unknown> =>
@@ -62,6 +67,7 @@ export const eventContracts: readonly EventContract[] = [
62
67
  const body = text(m.body);
63
68
  return { sessionId, messageId: m.id, chatId: text(m.chatId), from: text(m.from), body: body?.slice(0, 4000), truncated: (body?.length ?? 0) > 4000 };
64
69
  },
70
+ eventId: data => text(data.messageId),
65
71
  },
66
72
  }),
67
73
  defineContract('anyMessage', {
@@ -77,6 +83,7 @@ export const eventContracts: readonly EventContract[] = [
77
83
  const a = record(record(payload).ack);
78
84
  return { sessionId, messageId: a.id, ack: a.ack, chatId: text(a.chatId) };
79
85
  },
86
+ eventId: data => typeof data.messageId === 'string' ? `${data.messageId}:${String(data.ack)}` : undefined,
80
87
  },
81
88
  }),
82
89
  defineContract('stateChanged', {
@@ -111,8 +118,8 @@ export function eventJsonSchema(schema: z.ZodType): Record<string, unknown> {
111
118
  export function getMcpEventDefinitions() {
112
119
  return eventContracts.filter(contract => contract.mcp).map(contract => ({
113
120
  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'[],
121
+ description: `${contract.description}. Compact summary${contract.name === 'session.state.changed' ? '' : '; use messages.get with messageId to read a full message'}. Cursors replay recent events within the server's retention window.`,
122
+ delivery: ['poll', 'push', 'webhook'] as ('poll' | 'push' | 'webhook')[],
116
123
  inputSchema: eventJsonSchema(contract.mcp!.inputSchema),
117
124
  payloadSchema: eventJsonSchema(contract.mcp!.payloadSchema),
118
125
  }));
@@ -5,7 +5,7 @@ export const pollVoteEvent = defineListenerV2('pollVote', {
5
5
  legacyName: 'onPollVote',
6
6
  meta: {
7
7
  namespace: 'messages', license: 'none', status: 'beta',
8
- description: 'A decrypted poll vote added or changed in the synced store. Hydration can emit old votes. Hidden-voter polls omit sender and message identifiers. Deduplicate ordinary votes by id and timestamp; refresh getPollResults for current totals.',
8
+ description: 'Someone voted on a poll or changed their vote. Older votes can arrive again after the session starts, so deduplicate by id and timestamp and call getPollResults for current totals. Polls with hidden voters leave out sender and message IDs.',
9
9
  },
10
10
  payload: PollVoteSchema, defaultQueueOptions: { concurrency: 1 },
11
11
  });