Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(sdk): gate the request bodies every client sends
Yudhi Armyndharisf1d9fac1b397
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b1e782d2a..8b3e5f2a4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -32,6 +32,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- A session launch that fails on a locked database is retried. The classifier looked for `SQLITE_BUSY` in the error message while the driver carries it on `code`, so the session stayed down until a restart.- Meta-hosted ids (`@hosted`, `@hosted.lid`) normalize to the dialect they name. They parsed as unknown before, so a chat surfaced with kind `unknown` and the same id was then refused with a `400` on any write.+- 19 Python request types marked a field optional that the server requires, so a body missing `chatId` or `text` type-checked and then failed at the API. `UpdateWebhookRequest` no longer derives from the create type, whose `url` is required only on create.+- The Go client types six request enums that were plain strings and numbers, and the Java client three, so an invalid proxy scheme, call kind, membership method, chat state, pin window or status font fails to compile rather than returning a 400. Assigning a bare string or number to one of those fields no longer compiles.+- The webhook response declares the event vocabulary it returns instead of a bare string array, which is what every client already models.++### Tests++- The client shape gate covers request bodies on the Python, Go and Java clients, not only responses: 149 new pairs, and the per-client mapping floors rise with them.+- The gate reads vocabularies it previously skipped, so a wrong wire value fails instead of passing unread: numeric `Literal` and const-block enums, Java enum constants by their `@SerializedName`, enum members inside a list, and package-qualified generics.+### Documentation- The API reference and capability matrix record where the two engines differ on calls both support: read receipts, edit, pin and unpin, the profile writes, mute, and the channel lookup.diff --git a/openapi.json b/openapi.jsonindex fcbfc1e8c..3dc50b59a 100644--- a/openapi.json+++ b/openapi.json@@ -10714,7 +10714,33 @@"events": {"type": "array","items": {- "type": "string"+ "type": "string",+ "enum": [+ "message.received",+ "message.sent",+ "message.ack",+ "message.failed",+ "message.revoked",+ "message.reaction",+ "message.edited",+ "status.received",+ "session.status",+ "session.qr",+ "session.authenticated",+ "session.disconnected",+ "session.reconnect_loop",+ "session.restriction",+ "presence.update",+ "group.join",+ "group.leave",+ "group.update",+ "group.join_request",+ "call.received",+ "call.accepted",+ "call.rejected",+ "call.missed",+ "*"+ ]}},"filters": {diff --git a/scripts/check-contract-shapes.mjs b/scripts/check-contract-shapes.mjsindex 63fed0442..d6dc21c83 100644--- a/scripts/check-contract-shapes.mjs+++ b/scripts/check-contract-shapes.mjs@@ -1,7 +1,9 @@#!/usr/bin/env node/**- * Shape gate: the hand-written wire types of the two HTTP clients (the JavaScript SDK's types.ts- * and the dashboard's api.ts) against the DTO schemas of the committed openapi.json.+ * Shape gate: the hand-written wire types of all five clients (the JavaScript SDK's types.ts, the+ * dashboard's api.ts, the Python TypedDicts, the Go structs and the Java records) against the DTO+ * schemas of the committed openapi.json. Both directions of the traffic are mapped: response+ * payloads and request bodies alike.** This is the contract verification the repo previously had in name only: every existing gate* checks WHICH routes/events/methods exist, none checks request/response body SHAPES — the mocks@@ -14,9 +16,16 @@** Known blind spots, so nobody reads a green run as more than it is: TypeScript type-ALIASED* enums (e.g. `status: SessionStatus`) resolve to their alias name and are compared by presence- * and optionality only — the literal sets themselves are ungated on the TS clients; and Java- * enums (record components typed as enum classes) are likewise presence-only. Python Literals and- * Go const-block enums DO compare literally.+ * and optionality only, so the literal sets themselves are ungated on the TS clients. Everywhere+ * else the vocabulary IS compared member by member: Python Literals, Go const blocks and Java+ * enum constants (by their `@SerializedName`, or the constant's own name when it has none, which+ * is what Gson emits), whether the field carries one member or a list of them.+ *+ * One exception, in Java only: Gson serializes an enum constant by name, i.e. as a JSON string, so+ * a NUMERIC enum cannot be modelled as a Java enum without a custom adapter: the wire would carry+ * "86400" for a field the contract types as a number. Those components stay `Integer` and their+ * literal set is gated on the other four clients instead. Java also cannot express requiredness+ * through a record, which is why it alone runs with compareOptionality=false.** What one comparison covers, per mapped pair: field-name sets in both directions, required vs* optional (hand `?` vs the schema's `required` array), and — for fields whose both sides reduce@@ -160,14 +169,28 @@ const MAPPINGS = {const MINIMUM_MAPPED = {'sdk/javascript/src/types.ts': 78,'dashboard/src/services/api.ts': 20,- 'sdk/python/openwa/types.py': 23,- 'sdk/go': 25,- 'sdk/java': 25,+ 'sdk/python/openwa/types.py': 72,+ 'sdk/go': 73,+ 'sdk/java': 77,};/** Known drift, deliberately not gated yet — each line is a to-adjudicate follow-up. */const EXCLUDED = {+ 'sdk/go': {+ WebhookResponse:+ 'BY DESIGN: `WebhookEvent` is a type ALIAS for string so the Event* constants drop into a []string literal without a conversion, which means the events list resolves to array<string> and cannot carry the vocabulary. Un-excluding means making it a defined type and retyping the three Events fields, a source break for a published client',+ CreateWebhookRequest:+ 'BY DESIGN: `events` carries no omitempty so the key is always on the wire, which is what lets an empty slice mean "subscribe to nothing": the server keeps [] and only defaults when the key is absent. Adding omitempty would silently turn that into the default subscription',+ UpdateSessionConfigRequest:+ 'BY DESIGN: every component is `json:"-"` and MarshalJSON writes the body by hand, because the three fields need an explicit null to reset and Go cannot express "null" and "absent" through one pointer, so the harvester sees no wire fields at all',+ },+ 'sdk/java': {+ UpdateSessionConfigRequest:+ 'BY DESIGN: the three clear* components are client-side control flags consumed by UpdateSessionConfigRequestSerializer, which is what emits the explicit null; they never reach the wire',+ },'dashboard/src/services/api.ts': {+ Webhook:+ 'the events list models client state as much as the wire: it is rebuilt from checkbox toggles in Webhooks.tsx and re-guarded at runtime in queries.ts/useWebSocket.ts, so narrowing it to the event union would type those call sites rather than the payload. The vocabulary is gated on the JavaScript, Python and Java clients',Session:'BY DESIGN, not drift: the wire always carries engineLoaded, but this client clears it to "unknown" after a websocket status event so the action helpers fall back to the status set — the type models client state, not the wire',},@@ -176,33 +199,83 @@ const EXCLUDED = {/** Python client pairs (TypedDict classes in openwa/types.py). */const PYTHON_MAPPING = {AccountRestriction: 'AccountRestrictionDto',+ ArchiveChatRequest: 'ArchiveChatDto',BatchMessageResult: 'BatchMessageResultDto',BatchProgress: 'BatchProgressDto',BatchStatusResponse: 'BatchStatusResponseDto',+ BulkMediaRequest: 'BulkMediaDto',BulkMessageContent: 'BulkMessageContentDto',BulkMessageItem: 'BulkMessageItemDto',BulkMessageResponse: 'BulkMessageResponseDto',CallLinkResponse: 'CallLinkResponseDto',ChatSummary: 'ChatSummaryDto',+ CreateCallLinkRequest: 'CreateCallLinkDto',+ CreateChannelRequest: 'CreateChannelDto',+ CreateGroupRequest: 'CreateGroupDto',+ CreateSessionRequest: 'CreateSessionDto',+ CreateTemplateRequest: 'CreateTemplateDto',+ CreateWebhookRequest: 'CreateWebhookDto',+ DeleteChatRequest: 'DeleteChatDto',+ DeleteMessageRequest: 'DeleteMessageDto',+ DemoteChannelAdminRequest: 'DemoteChannelAdminDto',+ EditMessageRequest: 'EditMessageDto',+ ForwardMessageRequest: 'ForwardMessageDto',GroupInfo: 'GroupInfoDto',GroupJoinInfo: 'GroupJoinInfoDto',+ GroupMembershipRequest: 'GroupMembershipRequestDto',GroupParticipant: 'GroupParticipantDto',GroupSummary: 'GroupSummaryDto',+ JoinGroupRequest: 'JoinGroupDto',+ MarkChatRequest: 'MarkChatReadDto',MessageListResponse: 'MessageListResponseDto',MessageRecord: 'MessageListItemDto',MessageResponse: 'MessageResponseDto',+ MuteChannelRequest: 'MuteChannelDto',+ MuteChatRequest: 'MuteChatDto',PairingCodeResponse: 'PairingCodeResponseDto',ParticipantPresence: 'ParticipantPresenceDto',+ PinChatRequest: 'PinChatDto',+ PinMessageRequest: 'PinMessageDto',ProfilePictureResponse: 'ProfilePictureResponseDto',ProfilePicturesResponse: 'ProfilePicturesResponseDto',+ ReactMessageRequest: 'ReactMessageDto',+ ReplyMessageRequest: 'ReplyMessageDto',+ RequestPairingCodeRequest: 'RequestPairingCodeDto',+ SendAudioRequest: 'SendAudioMessageDto',+ SendBulkRequest: 'SendBulkMessageDto',+ SendChatStateRequest: 'SendChatStateDto',+ SendContactRequest: 'SendContactDto',+ SendImageStatusRequest: 'SendImageStatusDto',+ SendLocationRequest: 'SendLocationDto',+ SendMediaRequest: 'SendMediaMessageDto',+ SendPollRequest: 'SendPollDto',+ SendProductRequest: 'SendProductDto',+ SendTemplateRequest: 'SendTemplateMessageDto',+ SendTextRequest: 'SendTextMessageDto',+ SendTextStatusRequest: 'SendTextStatusDto',+ SendVideoStatusRequest: 'SendVideoStatusDto',+ SendVoiceStatusRequest: 'SendVoiceStatusDto',SessionResponse: 'SessionResponseDto',+ SetGroupPictureRequest: 'SetGroupPictureDto',+ SetOwnPresenceRequest: 'SetOwnPresenceDto',+ SetProfileNameRequest: 'SetProfileNameDto',+ SetProfilePictureRequest: 'SetProfilePictureDto',+ SetProfileStatusRequest: 'SetProfileStatusDto',+ StarMessageRequest: 'StarMessageDto',StatusResult: 'StatusResultDto',+ TransferChannelOwnershipRequest: 'TransferChannelOwnershipDto',+ UnpinMessageRequest: 'UnpinMessageDto',+ UpdateSessionConfigRequest: 'UpdateSessionConfigDto',+ UpsertContactRequest: 'UpsertContactDto',+ UpsertLabelRequest: 'UpsertLabelDto',+ VotePollRequest: 'VotePollDto',WebhookResponse: 'WebhookResponseDto',};/** Go client pairs (wire structs across types_*.go). */const GO_MAPPING = {AccountRestriction: 'AccountRestrictionDto',+ ArchiveChatRequest: 'ArchiveChatDto',BatchMessageResult: 'BatchMessageResultDto',BatchProgress: 'BatchProgressDto',BatchStatusResponse: 'BatchStatusResponseDto',@@ -212,49 +285,148 @@ const GO_MAPPING = {CallLinkResponse: 'CallLinkResponseDto',ChatHistoryMessage: 'ChatHistoryMessageDto',ChatSummary: 'ChatSummaryDto',+ CreateCallLinkRequest: 'CreateCallLinkDto',+ CreateChannelRequest: 'CreateChannelDto',+ CreateGroupRequest: 'CreateGroupDto',+ CreateSessionRequest: 'CreateSessionDto',+ CreateTemplateRequest: 'CreateTemplateDto',+ CreateWebhookRequest: 'CreateWebhookDto',+ DeleteChatRequest: 'DeleteChatDto',+ DeleteMessageRequest: 'DeleteMessageDto',+ DemoteChannelAdminRequest: 'DemoteChannelAdminDto',+ EditMessageRequest: 'EditMessageDto',+ ForwardMessageRequest: 'ForwardMessageDto',GroupInfo: 'GroupInfoDto',GroupJoinInfo: 'GroupJoinInfoDto',+ GroupMembershipRequest: 'GroupMembershipRequestDto',GroupParticipant: 'GroupParticipantDto',GroupSummary: 'GroupSummaryDto',+ JoinGroupRequest: 'JoinGroupDto',+ MarkChatRequest: 'MarkChatReadDto',MessageListResponse: 'MessageListResponseDto',MessageRecord: 'MessageListItemDto',MessageResponse: 'MessageResponseDto',+ MuteChannelRequest: 'MuteChannelDto',+ MuteChatRequest: 'MuteChatDto',PairingCodeResponse: 'PairingCodeResponseDto',ParticipantPresence: 'ParticipantPresenceDto',+ PinChatRequest: 'PinChatDto',+ PinMessageRequest: 'PinMessageDto',ProfilePictureResponse: 'ProfilePictureResponseDto',ProfilePicturesResponse: 'ProfilePicturesResponseDto',+ ReactMessageRequest: 'ReactMessageDto',+ ReplyMessageRequest: 'ReplyMessageDto',+ RequestPairingCodeRequest: 'RequestPairingCodeDto',SearchHit: 'SearchHitDto',+ SendAudioRequest: 'SendAudioMessageDto',+ SendBulkRequest: 'SendBulkMessageDto',+ SendChatStateRequest: 'SendChatStateDto',+ SendContactRequest: 'SendContactDto',+ SendImageStatusRequest: 'SendImageStatusDto',+ SendLocationRequest: 'SendLocationDto',+ SendMediaRequest: 'SendMediaMessageDto',+ SendPollRequest: 'SendPollDto',+ SendProductRequest: 'SendProductDto',+ SendTemplateRequest: 'SendTemplateMessageDto',+ SendTextRequest: 'SendTextMessageDto',+ SendTextStatusRequest: 'SendTextStatusDto',+ SendVideoStatusRequest: 'SendVideoStatusDto',+ SendVoiceStatusRequest: 'SendVoiceStatusDto',SessionResponse: 'SessionResponseDto',+ SetGroupPictureRequest: 'SetGroupPictureDto',+ SetOwnPresenceRequest: 'SetOwnPresenceDto',+ SetProfileNameRequest: 'SetProfileNameDto',+ SetProfilePictureRequest: 'SetProfilePictureDto',+ SetProfileStatusRequest: 'SetProfileStatusDto',+ StarMessageRequest: 'StarMessageDto',StatusResult: 'StatusResultDto',+ TransferChannelOwnershipRequest: 'TransferChannelOwnershipDto',+ UnpinMessageRequest: 'UnpinMessageDto',+ UpdateSessionConfigRequest: 'UpdateSessionConfigDto',+ UpsertContactRequest: 'UpsertContactDto',+ UpsertLabelRequest: 'UpsertLabelDto',+ VotePollRequest: 'VotePollDto',WebhookResponse: 'WebhookResponseDto',};/** Java client pairs (record components in model/*.java). */const JAVA_MAPPING = {AccountRestriction: 'AccountRestrictionDto',+ ArchiveChatRequest: 'ArchiveChatDto',BatchMessageResult: 'BatchMessageResultDto',BatchProgress: 'BatchProgressDto',BatchStatusResponse: 'BatchStatusResponseDto',+ BulkMediaRequest: 'BulkMediaDto',BulkMessageContent: 'BulkMessageContentDto',BulkMessageItem: 'BulkMessageItemDto',BulkMessageResponse: 'BulkMessageResponseDto',CallLinkResponse: 'CallLinkResponseDto',ChatHistoryMessage: 'ChatHistoryMessageDto',ChatSummary: 'ChatSummaryDto',+ CreateCallLinkRequest: 'CreateCallLinkDto',+ CreateChannelRequest: 'CreateChannelDto',+ CreateGroupRequest: 'CreateGroupDto',+ CreateSessionRequest: 'CreateSessionDto',+ CreateTemplateRequest: 'CreateTemplateDto',+ CreateWebhookRequest: 'CreateWebhookDto',+ DeleteChatRequest: 'DeleteChatDto',+ DeleteMessageRequest: 'DeleteMessageDto',+ DemoteChannelAdminRequest: 'DemoteChannelAdminDto',+ EditMessageRequest: 'EditMessageDto',+ ForwardMessageRequest: 'ForwardMessageDto',+ GroupDescriptionRequest: 'GroupDescriptionDto',GroupInfo: 'GroupInfoDto',GroupJoinInfo: 'GroupJoinInfoDto',+ GroupMembershipRequest: 'GroupMembershipRequestDto',GroupParticipant: 'GroupParticipantDto',+ GroupSubjectRequest: 'GroupSubjectDto',GroupSummary: 'GroupSummaryDto',+ JoinGroupRequest: 'JoinGroupDto',+ MarkChatRequest: 'MarkChatReadDto',MessageListResponse: 'MessageListResponseDto',MessageRecord: 'MessageListItemDto',MessageResponse: 'MessageResponseDto',+ MuteChannelRequest: 'MuteChannelDto',+ MuteChatRequest: 'MuteChatDto',PairingCodeResponse: 'PairingCodeResponseDto',ParticipantPresence: 'ParticipantPresenceDto',+ ParticipantsRequest: 'ParticipantsDto',+ PinChatRequest: 'PinChatDto',+ PinMessageRequest: 'PinMessageDto',ProfilePictureResponse: 'ProfilePictureResponseDto',ProfilePicturesResponse: 'ProfilePicturesResponseDto',+ ReactMessageRequest: 'ReactMessageDto',+ ReplyMessageRequest: 'ReplyMessageDto',+ RequestPairingCodeRequest: 'RequestPairingCodeDto',SearchHit: 'SearchHitDto',+ SendAudioRequest: 'SendAudioMessageDto',+ SendBulkRequest: 'SendBulkMessageDto',+ SendChatStateRequest: 'SendChatStateDto',+ SendContactRequest: 'SendContactDto',+ SendImageStatusRequest: 'SendImageStatusDto',+ SendLocationRequest: 'SendLocationDto',+ SendMediaRequest: 'SendMediaMessageDto',+ SendPollRequest: 'SendPollDto',+ SendProductRequest: 'SendProductDto',+ SendTemplateRequest: 'SendTemplateMessageDto',+ SendTextRequest: 'SendTextMessageDto',+ SendTextStatusRequest: 'SendTextStatusDto',+ SendVideoStatusRequest: 'SendVideoStatusDto',+ SendVoiceStatusRequest: 'SendVoiceStatusDto',SessionResponse: 'SessionResponseDto',+ SetGroupPictureRequest: 'SetGroupPictureDto',+ SetOwnPresenceRequest: 'SetOwnPresenceDto',+ SetProfileNameRequest: 'SetProfileNameDto',+ SetProfilePictureRequest: 'SetProfilePictureDto',+ SetProfileStatusRequest: 'SetProfileStatusDto',+ StarMessageRequest: 'StarMessageDto',StatusResult: 'StatusResultDto',+ TransferChannelOwnershipRequest: 'TransferChannelOwnershipDto',+ UnpinMessageRequest: 'UnpinMessageDto',+ UpdateSessionConfigRequest: 'UpdateSessionConfigDto',+ UpsertContactRequest: 'UpsertContactDto',+ UpsertLabelRequest: 'UpsertLabelDto',+ VotePollRequest: 'VotePollDto',WebhookResponse: 'WebhookResponseDto',};@@ -434,9 +606,12 @@ export function parseObjectToken(token) {return members;}-/** Fields whose both sides reduce to a primitive/enum/array/null-union get token-level diffing. */+/** Fields whose both sides reduce to a primitive/enum/array/null-union get token-level diffing.+ * `array<enum(...)>` counts: an array of enum members is exactly as comparable as a bare one, and+ * leaving it out silently ungated every vocabulary that travels as a list, the webhook event set+ * above all, on every client at once. */function isSimpleToken(token) {- return /^(string|number|boolean|unknown|any)(\|null)?$|^enum\([^)]*\)$|^array<(string|number|boolean)(\|null)?>$/.test(+ return /^(string|number|boolean|unknown|any)(\|null)?$|^enum\([^)]*\)$|^array<((string|number|boolean)(\|null)?|enum\([^)]*\))>$/.test(token,);}@@ -470,6 +645,14 @@ export function comparePair(handName, handMembers, schemaName, schema, schemas,// BOTH sides so nullability does not read as drift there; enums and kinds still compare.hand = hand.replace(/\|null$/, '');contract = contract.replace(/\|null$/, '');+ // Gson serializes an enum constant by its name, i.e. as a JSON string, so a NUMERIC enum+ // cannot be modelled as a Java enum without a custom adapter: the wire would carry+ // "86400" for a field the contract types as a number. Those components stay `Integer`+ // here; the literal set is gated on every other client. String enums ARE modelled as Java+ // enums and keep comparing by presence.+ if (/^enum\(-?\d+(?:\.\d+)?(?:,-?\d+(?:\.\d+)?)*\)$/.test(contract) && hand === 'number') {+ hand = contract;+ }}const absorbs = handInfo.absorbsNull && contract === `${hand}|null`;if (hand !== contract && !absorbs && isSimpleToken(hand)) {@@ -647,8 +830,13 @@ function pythonToken(text, resolve, depth = 0) {if (t === 'Any') return 'any';const lit = t.match(/^Literal\[(.+)\]$/s);if (lit) {- const vals = [...lit[1].matchAll(/["']([^"']+)["']/g)].map(m => m[1]);- if (vals.length) return `enum(${vals.slice().sort().join(',')})`;+ // Quoted members are string enums; bare members are the numeric ones (a status font, a pin+ // window). Both must reduce to the same enum token the schema side emits. A Literal whose+ // members went unread fell through to a non-simple token, which comparePair then skips, so+ // the field silently stopped being gated.+ const quoted = [...lit[1].matchAll(/["']([^"']+)["']/g)].map(m => m[1]);+ const vals = quoted.length ? quoted : [...lit[1].matchAll(/-?\d+(?:\.\d+)?/g)].map(m => m[0]);+ if (vals.length) return `enum(${sortEnumMembers(vals).join(',')})`;}const lst = t.match(/^(?:List|list)\[(.+)\]$/s);if (lst) return `array<${pythonToken(lst[1], resolve, depth + 1)}>`;@@ -703,15 +891,18 @@ export function parseGoTypes(sources) {for (const cblock of source.matchAll(/const \(([\s\S]*?)\n\)/g)) {for (const line of cblock[1].split('\n')) {// gofmt pads name/type with multiple spaces — \s+ on both sides of the type.- const m = line.match(/^\s*\w+\s+(\w+)\s+=\s+["']([^"']+)["']/);- if (m) (constGroups[m[1]] ??= []).push(m[2]);+ // A quoted value is a string enum, a bare one the numeric kind (pin windows, status+ // fonts). Reading only the quoted form left every numeric Go enum resolving to plain+ // `number`, which reports as drift against an enum schema and cannot be satisfied.+ const m = line.match(/^\s*\w+\s+(\w+)\s+=\s+(?:["']([^"']+)["']|(-?\d+(?:\.\d+)?))\s*(?:\/\/.*)?$/);+ if (m) (constGroups[m[1]] ??= []).push(m[2] ?? m[3]);}}}// defined scalar types whose consts exist become enumsfor (const [tname, vals] of Object.entries(constGroups)) {- if (scalarAliases[tname]) scalarAliases[tname] = `enum(${[...new Set(vals)].sort().join(',')})`;+ if (scalarAliases[tname]) scalarAliases[tname] = `enum(${sortEnumMembers([...new Set(vals)]).join(',')})`;}const expand = (typeText, depth = 0) => {@@ -765,6 +956,27 @@ export function parseJavaTypes(sources) {Instant: 'string',LocalDate: 'string',};+ const enums = {};+ for (const raw of sources) {+ const source = raw.replace(/\/\*[\s\S]*?\*\//g, '');+ for (const m of source.matchAll(/public enum (\w+)\s*\{([\s\S]*?)\n\}/g)) {+ // Constants end at the first `;` (anything after it is methods/fields). Gson emits the+ // @SerializedName value when present and the constant's own name otherwise, so that is the+ // wire member. Without this the whole enum resolved to its Java type name, which is not a+ // simple token, so comparePair skipped the field and a wrong wire value went unnoticed.+ const members = [];+ for (const part of m[2].split(';')[0].split(',')) {+ const serialized = part.match(/@SerializedName\("([^"]+)"\)/);+ if (serialized) {+ members.push(serialized[1]);+ continue;+ }+ const bare = part.replace(/@\w+\([^)]*\)/g, '').trim().match(/^([A-Z][A-Z0-9_]*)$/);+ if (bare) members.push(bare[1]);+ }+ if (members.length) enums[m[1]] = `enum(${sortEnumMembers([...new Set(members)]).join(',')})`;+ }+ }for (const raw of sources) {// Javadoc BETWEEN record components breaks comma-splitting — strip comments first.const source = raw.replace(/\/\*[\s\S]*?\*\//g, '');@@ -778,13 +990,20 @@ export function parseJavaTypes(sources) {records[m[1]] = members;}}- const expand = (t, depth = 0) => {+ const expand = (rawType, depth = 0) => {if (depth >= 4) return 'object';+ // Strip a package qualifier first: `java.util.List<String>` is the same shape as `List<String>`,+ // and records here use both spellings. Matching only the unqualified one left the qualified+ // components resolving to their raw text, which is not a simple token, so comparePair skipped+ // them, and `mentions` is carried by two request records with its type uncompared.+ const t = rawType.replace(/^(?:\w+\.)+(?=[A-Z])/, '');const lst = t.match(/^List<(.+)>$/);if (lst) return `array<${expand(lst[1], depth + 1)}>`;if (/^Map</.test(t)) return 'dict';if (primMap[t]) return primMap[t];+ if (enums[t]) return enums[t];const short = t.split('.').pop();+ if (enums[short]) return enums[short];if (records[short]) {const parts = Object.entries(records[short]).map(([f, v]) => `${f}:${expand(v.__java, depth + 1)}`);return `object(${parts.sort().join(',')})`;diff --git a/scripts/check-contract-shapes.spec.mjs b/scripts/check-contract-shapes.spec.mjsindex 7eb13ffac..dd7070848 100644--- a/scripts/check-contract-shapes.spec.mjs+++ b/scripts/check-contract-shapes.spec.mjs@@ -191,3 +191,71 @@ test('parseJavaTypes: javadoc between components must not drop fields', () => {assert.deepEqual(Object.keys(types.Sample), ['id', 'count']);assert.equal(types.Sample.count.token, 'number');});++test('parsePythonTypes: a Literal of bare numbers is an enum, not an unreadable token', () => {+ const src = [+ 'StatusFont = Literal[0, 1, 2, 6, 10]',+ '',+ 'class Post(TypedDict, total=False):',+ ' font: StatusFont',+ ].join('\n');+ // Members went unread before, so the field fell through to a non-simple token and comparePair+ // skipped it: the enum silently stopped being gated while the run stayed green.+ assert.equal(parsePythonTypes(src).Post.font.token, 'enum(0,1,2,6,10)', 'sorted numerically, not 0,1,10,2,6');+});++test('parseGoTypes: a const block of bare numbers is an enum', () => {+ const src = [+ 'type Window int',+ '',+ 'const (',+ '\tWindowDay Window = 86400',+ '\tWindowWeek Window = 604800',+ '\tWindowMonth Window = 2592000 // thirty days',+ ')',+ '',+ 'type Sample struct {',+ '\tWindow Window `json:"window"`',+ '}',+ ].join('\n');+ assert.equal(parseGoTypes([src]).Sample.window.token, 'enum(86400,604800,2592000)');+});++test('parseJavaTypes: enum constants resolve to their wire values, annotated or bare', () => {+ const src = [+ 'public enum Scheme {',+ ' @SerializedName("socks5")',+ ' SOCKS5,',+ ' @SerializedName("http")',+ ' HTTP',+ '}',+ 'public enum Plain {',+ ' RED,',+ ' BLUE',+ '}',+ 'public record Sample(Scheme scheme, List<Plain> shades) {}',+ ].join('\n');+ const s = parseJavaTypes([src]).Sample;+ // Gson emits @SerializedName when present and the constant name otherwise; without this the+ // component resolved to the Java type name, which comparePair skips as non-simple.+ assert.equal(s.scheme.token, 'enum(http,socks5)');+ assert.equal(s.shades.token, 'array<enum(BLUE,RED)>');+});++test('isSimpleToken-gated diffing reaches inside an array of enum members', () => {+ const hand = { events: { optional: false, token: 'array<enum(a,b)>' } };+ const schema = { type: 'object', required: ['events'], properties: { events: { type: 'array', items: { enum: ['a', 'c'] } } } };+ const diffs = comparePair('Hand', hand, 'Dto', schema, {});+ assert.equal(diffs.length, 1, 'a vocabulary that travels as a list must still be compared');+ assert.match(diffs[0], /events/);+});++test('parseJavaTypes: a package-qualified generic is the same shape as the bare one', () => {+ // Two request records spell the mentions list `java.util.List<String>`; matching only `List<...>`+ // left it resolving to its raw text, so its type went uncompared while the field still counted+ // as present.+ const src = 'public record Sample(java.util.List<String> mentions, List<String> tags) {}';+ const s = parseJavaTypes([src]).Sample;+ assert.equal(s.mentions.token, 'array<string>');+ assert.equal(s.tags.token, s.mentions.token);+});diff --git a/sdk/go/calls.go b/sdk/go/calls.goindex 0ad7cbbfb..2b9c69bc8 100644--- a/sdk/go/calls.go+++ b/sdk/go/calls.go@@ -6,11 +6,19 @@ import "context"// Backed by src/modules/call/call.controller.ts.type CallsService struct{ client *Client }+// CallLinkType is the kind of call a link opens.+type CallLinkType string++const (+ CallLinkAudio CallLinkType = "audio"+ CallLinkVideo CallLinkType = "video"+)+// CreateCallLinkRequest is the body for CallsService.CreateLink. Type is "audio" or "video";// WhatsApp's own URL path for audio is /voice/. StartTime is absolute epoch MILLISECONDS.type CreateCallLinkRequest struct {- Type string `json:"type"`- StartTime float64 `json:"startTime"`+ Type CallLinkType `json:"type"`+ StartTime float64 `json:"startTime"`}// CallLinkResponse carries the shareable WhatsApp call link.diff --git a/sdk/go/types_chat.go b/sdk/go/types_chat.goindex 69bc3767f..431452ecb 100644--- a/sdk/go/types_chat.go+++ b/sdk/go/types_chat.go@@ -24,10 +24,19 @@ type MarkChatRequest struct {ChatID string `json:"chatId"`}+// ChatState is the typing indicator a chat shows.+type ChatState string++const (+ ChatStateTyping ChatState = "typing"+ ChatStateRecording ChatState = "recording"+ ChatStatePaused ChatState = "paused"+)+// SendChatStateRequest sets typing state. State is one of: typing, recording, paused.type SendChatStateRequest struct {- ChatID string `json:"chatId"`- State string `json:"state"`+ ChatID string `json:"chatId"`+ State ChatState `json:"state"`}// DeleteChatRequest deletes a chat.diff --git a/sdk/go/types_group.go b/sdk/go/types_group.goindex 8429708b2..8dc82629d 100644--- a/sdk/go/types_group.go+++ b/sdk/go/types_group.go@@ -25,13 +25,22 @@ type GroupSummary struct {LinkedParentJID *string `json:"linkedParentJID,omitempty"`}+// MembershipRequestMethod is how a pending member asked to join.+type MembershipRequestMethod string++const (+ MembershipInviteLink MembershipRequestMethod = "invite_link"+ MembershipLinkedGroupJoin MembershipRequestMethod = "linked_group_join"+ MembershipNonAdminAdd MembershipRequestMethod = "non_admin_add"+)+// GroupMembershipRequest is a pending request to join a group. Only ParticipantID is always// present; the engine reports the rest when it has it.type GroupMembershipRequest struct {ParticipantID string `json:"participantId"`AddedByID string `json:"addedById,omitempty"`// Method is one of: invite_link, non_admin_add, linked_group_join.- Method string `json:"method,omitempty"`+ Method MembershipRequestMethod `json:"method,omitempty"`// RequestedAt is Unix seconds.RequestedAt float64 `json:"requestedAt,omitempty"`}diff --git a/sdk/go/types_message.go b/sdk/go/types_message.goindex 91538ef40..47a38d551 100644--- a/sdk/go/types_message.go+++ b/sdk/go/types_message.go@@ -487,12 +487,21 @@ type MessageMedia struct {ContentType string}+// PinDurationSeconds is one of the three windows WhatsApp accepts for a pinned message.+type PinDurationSeconds int++const (+ PinOneDay PinDurationSeconds = 86400+ PinSevenDays PinDurationSeconds = 604800+ PinThirtyDays PinDurationSeconds = 2592000+)+// PinMessageRequest pins a message in its chat. DurationSeconds must be 86400// (24h), 604800 (7d) or 2592000 (30d); omit it to take the server default of 24h.type PinMessageRequest struct {- ChatID string `json:"chatId"`- MessageID string `json:"messageId"`- DurationSeconds int `json:"durationSeconds,omitempty"`+ ChatID string `json:"chatId"`+ MessageID string `json:"messageId"`+ DurationSeconds PinDurationSeconds `json:"durationSeconds,omitempty"`}// UnpinMessageRequest removes a message's pin.diff --git a/sdk/go/types_session.go b/sdk/go/types_session.goindex 44565b68d..66abebe87 100644--- a/sdk/go/types_session.go+++ b/sdk/go/types_session.go@@ -165,13 +165,23 @@ type SessionResponse struct {EngineLoaded bool `json:"engineLoaded"`}+// ProxyType is the scheme of a session proxy.+type ProxyType string++const (+ ProxyHTTP ProxyType = "http"+ ProxyHTTPS ProxyType = "https"+ ProxySOCKS4 ProxyType = "socks4"+ ProxySOCKS5 ProxyType = "socks5"+)+// CreateSessionRequest is the body for creating a session. ProxyType is one of:// http, https, socks4, socks5.type CreateSessionRequest struct {Name string `json:"name"`Config map[string]any `json:"config,omitempty"`ProxyURL string `json:"proxyUrl,omitempty"`- ProxyType string `json:"proxyType,omitempty"`+ ProxyType ProxyType `json:"proxyType,omitempty"`}// QrCodeResponse carries the current QR code for a session awaiting scan.diff --git a/sdk/go/types_status.go b/sdk/go/types_status.goindex f9b964aac..9fcb496cf 100644--- a/sdk/go/types_status.go+++ b/sdk/go/types_status.go@@ -47,13 +47,27 @@ type StatusMedia struct {ContentType string}+// StatusFont is a WhatsApp status font family.+type StatusFont int++const (+ StatusFontDefault StatusFont = 0+ StatusFontSerif StatusFont = 1+ StatusFontNorican StatusFont = 2+ StatusFontBold StatusFont = 6+ StatusFontOswald StatusFont = 7+ StatusFontDamion StatusFont = 8+ StatusFontMorningbreeze StatusFont = 9+ StatusFontBryndan StatusFont = 10+)+// SendTextStatusRequest posts a text status. Recipients is required on the Baileys// engine only (absent/empty → 400 there); whatsapp-web.js ignores it — leave nil.type SendTextStatusRequest struct {- Text string `json:"text"`- Recipients []string `json:"recipients,omitempty"`- BackgroundColor string `json:"backgroundColor,omitempty"`- Font *int `json:"font,omitempty"`+ Text string `json:"text"`+ Recipients []string `json:"recipients,omitempty"`+ BackgroundColor string `json:"backgroundColor,omitempty"`+ Font *StatusFont `json:"font,omitempty"`}// StatusMediaInput is a status media payload: provide URL or Base64.diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/CallLinkType.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/CallLinkType.javanew file mode 100644index 000000000..d459be1e1--- /dev/null+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/CallLinkType.java@@ -0,0 +1,14 @@+package com.rmyndharis.openwa.model;++import com.google.gson.annotations.SerializedName;++/**+ * The kind of call a link opens. The wire values are lowercase, so each constant carries a+ * {@link SerializedName} mapping.+ */+public enum CallLinkType {+ @SerializedName("audio")+ AUDIO,+ @SerializedName("video")+ VIDEO+}diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/CreateCallLinkRequest.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/CreateCallLinkRequest.javaindex bec18d46a..203c6ef84 100644--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/CreateCallLinkRequest.java+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/CreateCallLinkRequest.java@@ -6,17 +6,17 @@ package com.rmyndharis.openwa.model;* @param type {@code "audio"} or {@code "video"}; WhatsApp's own URL path for audio is {@code /voice/}* @param startTime absolute epoch MILLISECONDS the call is scheduled to start at*/-public record CreateCallLinkRequest(String type, Double startTime) {+public record CreateCallLinkRequest(CallLinkType type, Double startTime) {public static Builder builder() {return new Builder();}public static final class Builder {- private String type;+ private CallLinkType type;private Double startTime;/** {@code "audio"} or {@code "video"}. */- public Builder type(String v) {+ public Builder type(CallLinkType v) {this.type = v;return this;}diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/CreateSessionRequest.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/CreateSessionRequest.javaindex 399833c63..34fb868fd 100644--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/CreateSessionRequest.java+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/CreateSessionRequest.java@@ -3,7 +3,7 @@ package com.rmyndharis.openwa.model;import java.util.Map;/** Request body for creating a session. Requires an OPERATOR-level key. */-public record CreateSessionRequest(String name, Map<String, Object> config, String proxyUrl, String proxyType) {+public record CreateSessionRequest(String name, Map<String, Object> config, String proxyUrl, ProxyType proxyType) {public static Builder builder() {return new Builder();}@@ -12,7 +12,7 @@ public record CreateSessionRequest(String name, Map<String, Object> config, Striprivate String name;private Map<String, Object> config;private String proxyUrl;- private String proxyType;+ private ProxyType proxyType;/** Alphanumeric + hyphens, 3–50 chars. */public Builder name(String v) {@@ -31,7 +31,7 @@ public record CreateSessionRequest(String name, Map<String, Object> config, Stri}/** One of {@code http}, {@code https}, {@code socks4}, {@code socks5}. */- public Builder proxyType(String v) {+ public Builder proxyType(ProxyType v) {this.proxyType = v;return this;}diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/GroupMembershipRequest.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/GroupMembershipRequest.javaindex 5f0f2a832..817a22eed 100644--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/GroupMembershipRequest.java+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/GroupMembershipRequest.java@@ -11,4 +11,5 @@ package com.rmyndharis.openwa.model;* @param method one of {@code invite_link}, {@code non_admin_add}, {@code linked_group_join}* @param requestedAt Unix seconds the request was created*/-public record GroupMembershipRequest(String participantId, String addedById, String method, Double requestedAt) {}+public record GroupMembershipRequest(+ String participantId, String addedById, MembershipRequestMethod method, Double requestedAt) {}diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/MembershipRequestMethod.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/MembershipRequestMethod.javanew file mode 100644index 000000000..83d5e1117--- /dev/null+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/MembershipRequestMethod.java@@ -0,0 +1,16 @@+package com.rmyndharis.openwa.model;++import com.google.gson.annotations.SerializedName;++/**+ * How a pending member asked to join a group. The wire values are snake_case, so each constant+ * carries a {@link SerializedName} mapping.+ */+public enum MembershipRequestMethod {+ @SerializedName("invite_link")+ INVITE_LINK,+ @SerializedName("linked_group_join")+ LINKED_GROUP_JOIN,+ @SerializedName("non_admin_add")+ NON_ADMIN_ADD+}diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/ProxyType.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ProxyType.javanew file mode 100644index 000000000..a99d1ed80--- /dev/null+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/ProxyType.java@@ -0,0 +1,18 @@+package com.rmyndharis.openwa.model;++import com.google.gson.annotations.SerializedName;++/**+ * The scheme of a session proxy. The wire values are lowercase, so each constant carries a+ * {@link SerializedName} mapping.+ */+public enum ProxyType {+ @SerializedName("http")+ HTTP,+ @SerializedName("https")+ HTTPS,+ @SerializedName("socks4")+ SOCKS4,+ @SerializedName("socks5")+ SOCKS5+}diff --git a/sdk/java/src/test/java/com/rmyndharis/openwa/resources/CallsResourceTest.java b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/CallsResourceTest.javaindex 042a8bf93..ba2a9f119 100644--- a/sdk/java/src/test/java/com/rmyndharis/openwa/resources/CallsResourceTest.java+++ b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/CallsResourceTest.java@@ -9,6 +9,7 @@ import com.rmyndharis.openwa.OpenWAClient;import com.rmyndharis.openwa.errors.OpenWANotFoundError;import com.rmyndharis.openwa.http.HttpMethod;import com.rmyndharis.openwa.support.MockTransport;+import com.rmyndharis.openwa.model.CallLinkType;import com.rmyndharis.openwa.model.CreateCallLinkRequest;import org.junit.jupiter.api.Test;@@ -47,10 +48,10 @@ class CallsResourceTest {void createLinkPostsToCallsLink() {tx.respond(200, "{\"link\":\"https://call.whatsapp.com/video/AbC\"}");var res = client.calls.createLink(- "s", CreateCallLinkRequest.builder().type("video").startTime(1800000000000.0).build());+ "s", CreateCallLinkRequest.builder().type(CallLinkType.VIDEO).startTime(1800000000000.0).build());assertEquals("http://h/api/sessions/s/calls/link", tx.lastRequest().url());assertEquals(HttpMethod.POST, tx.lastRequest().method());- assertTrue(tx.lastRequest().body().contains("video"));+ assertTrue(tx.lastRequest().body().contains("\"type\":\"video\""));assertTrue(res.link().contains("call.whatsapp.com"));}diff --git a/sdk/python/openwa/types.py b/sdk/python/openwa/types.pyindex cd66ac567..6216d872d 100644--- a/sdk/python/openwa/types.py+++ b/sdk/python/openwa/types.py@@ -38,6 +38,10 @@ SessionStatus = Literal[ChatState = Literal["typing", "recording", "paused"]MessageDirection = Literal["incoming", "outgoing"]DeliveryStatus = Literal["pending", "sent", "delivered", "read", "failed"]+# The three windows WhatsApp accepts for a pinned message: 24 hours, 7 days, 30 days.+PinDurationSeconds = Literal[86400, 604800, 2592000]+# WhatsApp status font family: 0 (default), 1, 2, 6 (bold), 7, 8, 9, 10.+StatusFont = Literal[0, 1, 2, 6, 7, 8, 9, 10]BulkMessageType = Literal["text", "image", "video", "audio", "document"]BatchMessageStatus = Literal["pending", "sent", "failed", "cancelled"]BatchLifecycleStatus = Literal["pending", "processing", "completed", "failed", "cancelled"]@@ -153,11 +157,11 @@ class UpsertLabelRequest(TypedDict, total=False):color: int-class CreateChannelRequest(TypedDict, total=False):+class CreateChannelRequest(TypedDict):"""Body for creating a channel."""name: str- description: str+ description: NotRequired[str]class MuteChannelRequest(TypedDict):@@ -254,11 +258,11 @@ class UpdateSessionConfigRequest(TypedDict, total=False):reconnectBaseDelay: int | None-class CreateSessionRequest(TypedDict, total=False):+class CreateSessionRequest(TypedDict):name: str- config: dict[str, Any]- proxyUrl: str- proxyType: Literal["http", "https", "socks4", "socks5"]+ config: NotRequired[dict[str, Any]]+ proxyUrl: NotRequired[str]+ proxyType: NotRequired[Literal['http', 'https', 'socks4', 'socks5']]class QrCodeResponse(TypedDict):@@ -298,41 +302,41 @@ class MessageResponse(TypedDict):timestamp: int-class SendTextRequest(TypedDict, total=False):+class SendTextRequest(TypedDict):# chatId/text required; mentions optional.chatId: Jidtext: str# WIDs to @mention (e.g. ["[email protected]"]). The text must also contain the @<number> token.- mentions: list[str]+ mentions: NotRequired[list[str]]# Controls the URL preview. False suppresses it on both engines. Otherwise the engines differ:# whatsapp-web.js builds one in-page by default, while on Baileys a preview is OPT-IN -- it needs# True, because generating one is a blocking outbound fetch per URL.- linkPreview: bool+ linkPreview: NotRequired[bool]# Attach a preview you supply yourself instead of one fetched from the URL. Nothing is fetched,# so this works even for a URL the gateway cannot reach. Baileys only -- whatsapp-web.js takes a# boolean and answers 501. Cannot be combined with linkPreview=False.- customLinkPreview: CustomLinkPreview+ customLinkPreview: NotRequired[CustomLinkPreview]# Quote an earlier message, turning this send into a reply. Engine-specific: whatsapp-web.js# matches the serialized message id, Baileys the raw key id of a message it has already stored.- quotedMessageId: str+ quotedMessageId: NotRequired[str]-class SendMediaRequest(TypedDict, total=False):+class SendMediaRequest(TypedDict):chatId: Jid- url: str- base64: str- mimetype: str- filename: str- caption: str+ url: NotRequired[str]+ base64: NotRequired[str]+ mimetype: NotRequired[str]+ filename: NotRequired[str]+ caption: NotRequired[str]# Quote an earlier message, turning this send into a reply. Engine-specific: whatsapp-web.js# matches the serialized message id, Baileys the raw key id of a message it has already stored.- quotedMessageId: str+ quotedMessageId: NotRequired[str]# WIDs to @mention; the caption must also contain the @<number> token.- mentions: list[str]+ mentions: NotRequired[list[str]]-class SendAudioRequest(SendMediaRequest, total=False):- ptt: bool # audio only: send as a WhatsApp voice note (PTT)+class SendAudioRequest(SendMediaRequest):+ ptt: NotRequired[bool]class BulkMediaRequest(TypedDict, total=False):@@ -345,16 +349,16 @@ class BulkMediaRequest(TypedDict, total=False):ptt: bool-class SendLocationRequest(TypedDict, total=False):+class SendLocationRequest(TypedDict):# chatId/latitude/longitude required; description/address optional.chatId: Jidlatitude: floatlongitude: float- description: str- address: str+ description: NotRequired[str]+ address: NotRequired[str]# Quote an earlier message, turning this send into a reply. Engine-specific: whatsapp-web.js# matches the serialized message id, Baileys the raw key id of a message it has already stored.- quotedMessageId: str+ quotedMessageId: NotRequired[str]class _SendContactRequired(TypedDict):@@ -365,10 +369,10 @@ class _SendContactRequired(TypedDict):# Split so the optional key can be added without loosening the three required ones — the same# inheritance shape SendAudioRequest already uses.-class SendContactRequest(_SendContactRequired, total=False):+class SendContactRequest(_SendContactRequired):# Quote an earlier message, turning this send into a reply. Engine-specific: whatsapp-web.js# matches the serialized message id, Baileys the raw key id of a message it has already stored.- quotedMessageId: str+ quotedMessageId: NotRequired[str]class ReplyMessageRequest(TypedDict):@@ -389,11 +393,11 @@ class ReactMessageRequest(TypedDict):emoji: str-class DeleteMessageRequest(TypedDict, total=False):+class DeleteMessageRequest(TypedDict):# chatId/messageId required; forEveryone optional (default true).chatId: JidmessageId: str- forEveryone: bool+ forEveryone: NotRequired[bool]class EditMessageRequest(TypedDict):@@ -403,26 +407,26 @@ class EditMessageRequest(TypedDict):body: str-class SendTemplateRequest(TypedDict, total=False):+class SendTemplateRequest(TypedDict):# chatId required; provide exactly one of templateId / templateName.# Modeled total=False (callers pass plain dicts); the backend validates.chatId: Jid- templateId: str- templateName: str- vars: dict[str, str]+ templateId: NotRequired[str]+ templateName: NotRequired[str]+ vars: NotRequired[dict[str, str]]-class SendPollRequest(TypedDict, total=False):+class SendPollRequest(TypedDict):# chatId/name/options required; allowMultipleAnswers optional (default single choice).chatId: Jid# Poll question / title (max 255 chars).name: str# Options to vote on (WhatsApp allows between 2 and 12).options: list[str]- allowMultipleAnswers: bool+ allowMultipleAnswers: NotRequired[bool]# Quote an earlier message, turning this send into a reply. Engine-specific: whatsapp-web.js# matches the serialized message id, Baileys the raw key id of a message it has already stored.- quotedMessageId: str+ quotedMessageId: NotRequired[str]# ``from`` is a Python keyword, so use the functional TypedDict form.@@ -599,10 +603,10 @@ class _SendBulkRequired(TypedDict):messages: list[BulkMessageItem]-class SendBulkRequest(_SendBulkRequired, total=False):+class SendBulkRequest(_SendBulkRequired):# `options` and `batchId` are optional; the backend applies defaults.- options: BulkOptions- batchId: str+ options: NotRequired[BulkOptions]+ batchId: NotRequired[str]class BulkMessageResponse(TypedDict):@@ -712,7 +716,7 @@ class GroupSummary(TypedDict):GroupMembershipRequestMethod = Literal["invite_link", "non_admin_add", "linked_group_join"]-class GroupMembershipRequest(TypedDict, total=False):+class GroupMembershipRequest(TypedDict):"""A pending request to join a group.Only ``participantId`` is always present; the engine reports the rest when it has it, so treat@@ -720,9 +724,9 @@ class GroupMembershipRequest(TypedDict, total=False):"""participantId: str- addedById: str- method: GroupMembershipRequestMethod- requestedAt: float+ addedById: NotRequired[str]+ method: NotRequired[GroupMembershipRequestMethod]+ requestedAt: NotRequired[float]class GroupInfo(TypedDict):@@ -818,17 +822,27 @@ class WebhookFilters(TypedDict):conditions: list[WebhookFilterCondition]-class CreateWebhookRequest(TypedDict, total=False):+class CreateWebhookRequest(TypedDict):+ url: str+ events: NotRequired[list[WebhookEvent]]+ secret: NotRequired[str]+ headers: NotRequired[dict[str, str]]+ filters: NotRequired[WebhookFilters | None]+ # Server DTO field is ``retryCount`` (0–5; default 3).+ retryCount: NotRequired[int]+++class UpdateWebhookRequest(TypedDict, total=False):+ # Deliberately NOT derived from CreateWebhookRequest: `url` is required to create a webhook and+ # optional to update one, and a TypedDict subclass cannot relax an inherited key back to+ # optional. Every field here is a partial update.url: strevents: list[WebhookEvent]secret: strheaders: dict[str, str]filters: WebhookFilters | None- # Server DTO field is ``retryCount`` (0–5; default 3).+ # Server DTO field is ``retryCount`` (0-5; default 3).retryCount: int---class UpdateWebhookRequest(CreateWebhookRequest, total=False):active: bool@@ -925,12 +939,12 @@ class StatusMedia(TypedDict):contentType: str | None-class PinMessageRequest(TypedDict, total=False):+class PinMessageRequest(TypedDict):"""Pin a message. ``durationSeconds`` is 86400 (24h), 604800 (7d) or 2592000 (30d)."""chatId: strmessageId: str- durationSeconds: int+ durationSeconds: NotRequired[PinDurationSeconds]class SetGroupPictureRequest(TypedDict, total=False):@@ -941,11 +955,11 @@ class SetGroupPictureRequest(TypedDict, total=False):mimetype: str-class UpsertContactRequest(TypedDict, total=False):+class UpsertContactRequest(TypedDict):"""Save or edit an addressbook contact. lastName is optional."""firstName: str- lastName: str+ lastName: NotRequired[str]class ArchiveChatRequest(TypedDict):@@ -1003,13 +1017,13 @@ class MessageMedia(TypedDict):contentType: str | None-class SendTextStatusRequest(TypedDict, total=False):+class SendTextStatusRequest(TypedDict):# text always required; recipients required on the Baileys engine only.text: str# Recipient JIDs. Required on the Baileys engine (absent/empty -> 400); omit on whatsapp-web.js.- recipients: list[str]- backgroundColor: str- font: int+ recipients: NotRequired[list[str]]+ backgroundColor: NotRequired[str]+ font: NotRequired[StatusFont]class StatusMediaInput(TypedDict, total=False):@@ -1020,25 +1034,25 @@ class StatusMediaInput(TypedDict, total=False):mimetype: str-class SendImageStatusRequest(TypedDict, total=False):+class SendImageStatusRequest(TypedDict):"""Server expects a nested ``{ image: { url|base64 } }`` body."""image: StatusMediaInput# Recipient JIDs. Required on the Baileys engine (absent/empty -> 400); omit on whatsapp-web.js.- recipients: list[str]- caption: str+ recipients: NotRequired[list[str]]+ caption: NotRequired[str]-class SendVideoStatusRequest(TypedDict, total=False):+class SendVideoStatusRequest(TypedDict):"""Server expects a nested ``{ video: { url|base64 } }`` body."""video: StatusMediaInput# Recipient JIDs. Required on the Baileys engine (absent/empty -> 400); omit on whatsapp-web.js.- recipients: list[str]- caption: str+ recipients: NotRequired[list[str]]+ caption: NotRequired[str]-class SendVoiceStatusRequest(TypedDict, total=False):+class SendVoiceStatusRequest(TypedDict):"""Post an audio status as a voice note.No caption: WhatsApp has nowhere to render one on a status voice note. ``audio.mimetype``@@ -1048,9 +1062,9 @@ class SendVoiceStatusRequest(TypedDict, total=False):audio: StatusMediaInput#: Required on the Baileys engine (absent/empty -> 400); omit on whatsapp-web.js.- recipients: list[str]+ recipients: NotRequired[list[str]]#: Background colour as "#RRGGBB", behind the voice-note bubble. Baileys only; wwjs ignores it.- backgroundColor: str+ backgroundColor: NotRequired[str]# ── Health ────────────────────────────────────────────────────────@@ -1089,13 +1103,13 @@ class TemplateRecord(TypedDict, total=False):updatedAt: str-class CreateTemplateRequest(TypedDict, total=False):+class CreateTemplateRequest(TypedDict):# name + body required; header/footer optional. Modeled total=False# (callers pass plain dicts); the backend validates the required fields.name: strbody: str- header: str- footer: str+ header: NotRequired[str]+ footer: NotRequired[str]class UpdateTemplateRequest(TypedDict, total=False):@@ -1213,10 +1227,10 @@ class ProductMessageResponse(TypedDict):# chatId + productId required; body optional. Modeled total=False for 3.9 compat# (callers pass plain dicts); the backend validates the required fields.-class SendProductRequest(TypedDict, total=False):+class SendProductRequest(TypedDict):chatId: JidproductId: str- body: str+ body: NotRequired[str]# ── Search ────────────────────────────────────────────────────────diff --git a/src/modules/webhook/dto/webhook.dto.ts b/src/modules/webhook/dto/webhook.dto.tsindex da34fed7b..f0b81bad7 100644--- a/src/modules/webhook/dto/webhook.dto.ts+++ b/src/modules/webhook/dto/webhook.dto.ts@@ -264,7 +264,10 @@ export class WebhookResponseDto {url!: string;@Expose()- @ApiProperty()+ // Same vocabulary the create and update bodies validate against: the stored list can only hold+ // values those routes accepted. Publishing a bare string[] understated the response, and left+ // every client's typed event list comparing against `array<string>` instead of the enum.+ @ApiProperty({ enum: [...WEBHOOK_EVENTS, '*'], type: String, isArray: true })events!: string[];@Expose()