From be653f03552cbc8d862d2c6850f6d6515b8c404f Mon Sep 17 00:00:00 2001 From: "borja (aider)" Date: Mon, 5 May 2025 15:06:02 +0200 Subject: [PATCH] feat: add WhatsApp ID normalization utility --- src/utils/whatsapp.ts | 61 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 src/utils/whatsapp.ts diff --git a/src/utils/whatsapp.ts b/src/utils/whatsapp.ts new file mode 100644 index 0000000..3422955 --- /dev/null +++ b/src/utils/whatsapp.ts @@ -0,0 +1,61 @@ +/** + * Normalizes a WhatsApp ID by removing the domain part (@s.whatsapp.net, @g.us) + * and any participant identifier (:12). + * Handles potential variations like participant IDs in group messages. + * + * Examples: + * - '1234567890@s.whatsapp.net' -> '1234567890' + * - '1234567890-1234567890@g.us' -> '1234567890-1234567890' + * - '1234567890:12@s.whatsapp.net' -> '1234567890' (handles participant format) + * - 'status_me@broadcast' -> 'status_me' (handles status broadcast) + * + * @param id The raw WhatsApp ID string. Can be null or undefined. + * @returns The normalized ID string, or null if the input is null/undefined or invalid after normalization. + */ +export function normalizeWhatsAppId(id: string | null | undefined): string | null { + if (!id) { + return null; + } + + // Remove domain part (@s.whatsapp.net, @g.us, @broadcast etc.) + let normalized = id.split('@')[0]; + + // Handle potential participant format like '1234567890:12' by taking the part before ':' + normalized = normalized.split(':')[0]; + + // Basic validation: should contain alphanumeric characters, possibly hyphens for group IDs + // Allows simple numbers, group IDs with hyphens, and potentially status_me + if (!/^[a-zA-Z0-9_-]+$/.test(normalized)) { + console.warn(`[normalizeWhatsAppId] Invalid characters found in WhatsApp ID after normalization: ${id} -> ${normalized}`); + // Return null for clearly invalid IDs after normalization + return null; + } + + // Prevent empty strings after normalization + if (normalized.length === 0) { + console.warn(`[normalizeWhatsAppId] Empty string resulted from normalization: ${id}`); + return null; + } + + return normalized; +} + +/** + * Checks if a given raw JID represents a group chat. + * + * @param jid The raw JID string (e.g., '123-456@g.us'). + * @returns True if the JID ends with '@g.us', false otherwise. + */ +export function isGroupId(jid: string | null | undefined): boolean { + return !!jid && jid.endsWith('@g.us'); +} + +/** + * Checks if a given raw JID represents a standard user chat. + * + * @param jid The raw JID string (e.g., '123456@s.whatsapp.net'). + * @returns True if the JID ends with '@s.whatsapp.net', false otherwise. + */ +export function isUserJid(jid: string | null | undefined): boolean { + return !!jid && jid.endsWith('@s.whatsapp.net'); +}