Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
refactor(identity): inline the single-consumer WaId wrapper into the filter evaluator (#517)
Yudhi Armyndharisa300f53d0b8b
diff --git a/src/engine/identity/wa-id.value.spec.ts b/src/engine/identity/wa-id.value.spec.tsdeleted file mode 100644index 52ce2a397..000000000--- a/src/engine/identity/wa-id.value.spec.ts+++ /dev/null@@ -1,109 +0,0 @@-import { WaId } from './wa-id.value';-import { toNeutralJid } from './wa-id';--describe('WaId', () => {- describe('fromEngineJid', () => {- it('parses a phone user and folds @s.whatsapp.net to @c.us', () => {- const id = WaId.fromEngineJid('[email protected]');- expect(id.kind).toBe('user');- expect(id.phone).toBe('628111');- expect(id.toNeutral()).toBe('[email protected]');- });-- it('strips a :device suffix from the phone', () => {- expect(WaId.fromEngineJid('628111:[email protected]').phone).toBe('628111');- expect(WaId.fromEngineJid('628111:[email protected]').toNeutral()).toBe('[email protected]');- });-- it('keeps an unresolved lid first-class (phone undefined, stays @lid)', () => {- const id = WaId.fromEngineJid('111@lid');- expect(id.kind).toBe('lid');- expect(id.lid).toBe('111');- expect(id.phone).toBeUndefined();- expect(id.toNeutral()).toBe('111@lid');- });-- it('resolves a lid to its phone when the resolver knows it', () => {- const id = WaId.fromEngineJid('111@lid', () => '628999');- expect(id.kind).toBe('lid');- expect(id.lid).toBe('111');- expect(id.phone).toBe('628999');- expect(id.toNeutral()).toBe('[email protected]');- });-- it('parses groups, status, newsletter and broadcast', () => {- expect(WaId.fromEngineJid('[email protected]').groupId).toBe('123-456');- expect(WaId.fromEngineJid('[email protected]').toNeutral()).toBe('[email protected]');- expect(WaId.fromEngineJid('status@broadcast').toNeutral()).toBe('status@broadcast');- expect(WaId.fromEngineJid('123@newsletter').toNeutral()).toBe('123@newsletter');- expect(WaId.fromEngineJid('123@broadcast').toNeutral()).toBe('123@broadcast');- });- });-- describe('fromUserInput', () => {- it('treats bare digits as a phone-addressed user', () => {- expect(WaId.fromUserInput('628111').toNeutral()).toBe('[email protected]');- });-- it('strips non-digits from a formatted phone', () => {- expect(WaId.fromUserInput('+62 811').phone).toBe('62811');- });-- it('parses a full jid like an engine id', () => {- expect(WaId.fromUserInput('[email protected]').kind).toBe('user');- expect(WaId.fromUserInput('111@lid').kind).toBe('lid');- });- });-- describe('toJSON / serialization byte-identity', () => {- // The wire format must not change: WaId serializes to exactly today's neutral string. Embedding a- // WaId in a DTO and JSON.stringify-ing it yields the same string a raw id would have.- it('serializes transparently inside a DTO', () => {- const payload = { from: WaId.fromEngineJid('[email protected]'), chatId: WaId.fromEngineJid('[email protected]') };- expect(JSON.stringify(payload)).toBe('{"from":"[email protected]","chatId":"[email protected]"}');- });-- // Guard: WaId.toNeutral() is defined in terms of the adapters' toNeutralJid, so a representative- // message.received payload (from/to/chatId/author) + group payload (owner/participants) stay- // byte-identical to what the engine emits today.- it('matches toNeutralJid for every representative id', () => {- const resolve = (jid: string) => (jid.startsWith('111@') ? '628999' : null);- const ids = [- '[email protected]',- '628111:[email protected]',- '[email protected]',- '111@lid', // resolves to 628999- '222@lid', // stays @lid- '[email protected]',- 'status@broadcast',- '999@newsletter',- '888@broadcast',- ];- for (const jid of ids) {- expect(WaId.fromEngineJid(jid, resolve).toNeutral()).toBe(toNeutralJid(jid, resolve));- }- });- });-- describe('refersToSamePerson (three-valued)', () => {- it('true when phones match, false when they differ', () => {- expect(WaId.fromEngineJid('[email protected]').refersToSamePerson(WaId.fromEngineJid('[email protected]'))).toBe(- true,- );- expect(WaId.fromEngineJid('[email protected]').refersToSamePerson(WaId.fromEngineJid('[email protected]'))).toBe(false);- });-- it('true when both carry the same lid', () => {- expect(WaId.fromEngineJid('111@lid').refersToSamePerson(WaId.fromEngineJid('111@lid'))).toBe(true);- });-- it("null ('couldn't tell') for a known phone vs an unresolved lid", () => {- expect(WaId.fromEngineJid('[email protected]').refersToSamePerson(WaId.fromEngineJid('111@lid'))).toBeNull();- });-- it('matches a resolved lid to the phone it resolved to', () => {- const resolvedLid = WaId.fromEngineJid('111@lid', () => '628999');- expect(resolvedLid.refersToSamePerson(WaId.fromEngineJid('[email protected]'))).toBe(true);- });- });-});diff --git a/src/engine/identity/wa-id.value.ts b/src/engine/identity/wa-id.value.tsdeleted file mode 100644index 9a8ab8e20..000000000--- a/src/engine/identity/wa-id.value.ts+++ /dev/null@@ -1,103 +0,0 @@-import { parseWaId, userPart, WaIdKind } from './wa-id';--/**- * Typed WhatsApp identity. A thin, in-memory value object over the {@link parseWaId} primitives that- * makes the kind and the (maybe-unknown) phone first-class, so a lid whose phone we don't know is- * visible in the type instead of re-derived by every caller.- *- * `WaId` is never persisted and never crosses the wire: the boundary format stays the neutral string- * ({@link toNeutral}). It carries no behaviour the engine didn't already have - `toNeutral()` delegates- * to the same {@link toNeutralJid} the adapters use, so the serialized string is byte-identical.- */-export class WaId {- private constructor(- readonly kind: WaIdKind,- /** The original engine JID, verbatim. Debug/provenance only - excluded from matching. */- readonly raw: string,- /** E.164 phone digits, when known (a resolved lid carries this; an unresolved one does not). */- readonly phone?: string,- /** The lid number, when this id is or carries a lid. */- readonly lid?: string,- /** The group id, for groups. */- readonly groupId?: string,- ) {}-- /** Build from an engine JID, resolving a lid to its phone when the engine knows the mapping. */- static fromEngineJid(jid: string, resolvePhone?: (jid: string) => string | null): WaId {- const parsed = parseWaId(jid);- switch (parsed.kind) {- case 'user':- return new WaId('user', jid, parsed.userPart);- case 'group':- return new WaId('group', jid, undefined, undefined, parsed.userPart);- case 'lid': {- const phone = resolvePhone?.(jid) ?? undefined;- return new WaId('lid', jid, phone, parsed.userPart);- }- default:- return new WaId(parsed.kind, jid);- }- }-- /** Build from API/user input: bare digits are a phone-addressed user; anything else parses as a JID. */- static fromUserInput(value: string): WaId {- const trimmed = value.trim();- if (trimmed && !trimmed.includes('@')) {- const digits = trimmed.replace(/\D/g, '');- return new WaId('user', trimmed, digits || trimmed);- }- return WaId.fromEngineJid(trimmed);- }-- /**- * The neutral boundary string, built from the resolved fields. Kept in lock-step with the adapters'- * {@link toNeutralJid} (a spec asserts byte-identity for every engine id), so the emitted string is- * identical to today's wire format - WaId changes nothing observable.- */- toNeutral(): string {- switch (this.kind) {- case 'user':- return `${this.phone}@c.us`;- case 'group':- return `${this.groupId}@g.us`;- case 'lid':- return this.phone ? `${this.phone}@c.us` : `${this.lid}@lid`;- case 'status':- return 'status@broadcast';- case 'newsletter':- return `${userPart(this.raw)}@newsletter`;- case 'broadcast':- return `${userPart(this.raw)}@broadcast`;- default:- return this.raw;- }- }-- toString(): string {- return this.toNeutral();- }-- toJSON(): string {- return this.toNeutral();- }-- /**- * Relational same-person test, deliberately three-valued: `true` when they share a lid or a known- * phone, `false` when both phones are known and differ, and `null` ("couldn't tell") when one side is- * a phone and the other only an unresolved lid. `raw` is excluded so the same person seen via two- * engines doesn't split. This is NOT a hashable key - matching is relational while lids are unresolved.- */- refersToSamePerson(other: WaId): boolean | null {- if (this.lid && other.lid) {- return this.lid === other.lid;- }- if (this.phone && other.phone) {- return this.phone === other.phone;- }- return null;- }-}--/** Re-exported for callers that only need the kind union without importing the primitives module. */-export type { WaIdKind };-export { userPart };diff --git a/src/modules/webhook/filters/filter-evaluator.spec.ts b/src/modules/webhook/filters/filter-evaluator.spec.tsindex 1ea005fa4..a48d12d7f 100644--- a/src/modules/webhook/filters/filter-evaluator.spec.ts+++ b/src/modules/webhook/filters/filter-evaluator.spec.ts@@ -26,6 +26,19 @@ describe('evaluateFilters', () => {expect(evaluateFilters(f, 'message.received', msg({ from: '[email protected]' }))).toBe(false);});+ it('matches a bare-digit phone filter against the engine JID across dialects (user-input canonicalization)', () => {+ // A user-typed phone (bare digits, optionally formatted) collapses to <digits>@c.us and matches the+ // sender whether the engine emitted @c.us or @s.whatsapp.net.+ const f = filters({ field: 'sender', operator: 'is', value: ['111'] });+ expect(evaluateFilters(f, 'message.received', msg({ from: '[email protected]' }))).toBe(true);+ expect(evaluateFilters(f, 'message.received', msg({ from: '[email protected]' }))).toBe(true);+ expect(evaluateFilters(f, 'message.received', msg({ from: '[email protected]' }))).toBe(false);++ // Formatting characters are stripped to digits before canonicalization.+ const formatted = filters({ field: 'sender', operator: 'is', value: ['+1 (11)'] });+ expect(evaluateFilters(formatted, 'message.received', msg({ from: '[email protected]' }))).toBe(true);+ });+it('resolves sender to author in group messages', () => {const f = filters({ field: 'sender', operator: 'is', value: ['[email protected]'] });const groupMsg = msg({ from: '[email protected]', author: '[email protected]', isGroup: true });diff --git a/src/modules/webhook/filters/filter-evaluator.ts b/src/modules/webhook/filters/filter-evaluator.tsindex 10b57052f..e2371dda2 100644--- a/src/modules/webhook/filters/filter-evaluator.ts+++ b/src/modules/webhook/filters/filter-evaluator.ts@@ -5,7 +5,7 @@ import {eventFamily,getFieldDefinition,} from './filter-types';-import { WaId } from '../../../engine/identity/wa-id.value';+import { toNeutralJid } from '../../../engine/identity/wa-id';/*** Resolves a lid JID to its phone user-part when the mapping is known (mirrors the engine adapter's@@ -19,9 +19,16 @@ export type LidResolver = (jid: string) => string | null;// table resolves to its phone) and a user-typed filter value (bare digits or a JID) both collapse to// the same neutral string (`<phone>@c.us` / `<id>@g.us` / `<lid>@lid`). So a phone filter now matches// the person across user dialects AND any lid resolving to that phone - previously a silent miss.-const canonicalActor = (jid: string, resolve?: LidResolver): string =>- WaId.fromEngineJid(jid, resolve).toNeutral().toLowerCase();-const canonicalInput = (value: string): string => WaId.fromUserInput(value).toNeutral().toLowerCase();+const canonicalActor = (jid: string, resolve?: LidResolver): string => toNeutralJid(jid, resolve).toLowerCase();+const canonicalInput = (value: string): string => {+ // Bare digits are a phone-addressed user; anything else parses as a JID. Mirrors the engine's+ // user-input canonicalization (byte-identical to the former WaId.fromUserInput().toNeutral()).+ const trimmed = value.trim();+ if (trimmed && !trimmed.includes('@')) {+ return `${trimmed.replace(/\D/g, '') || trimmed}@c.us`.toLowerCase();+ }+ return toNeutralJid(trimmed).toLowerCase();+};const toStringArray = (value: unknown): string[] =>Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string') : [];