Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
import { parseWaId } from './wa-id';
/**
* Engine-neutral expansion of a WhatsApp JID into every form of the same entity (shared by the
* message chat filter and the API-key chat scope, so the two cannot disagree about identity).
*
* - a `<phone>@c.us` / `@s.whatsapp.net` input yields the literal, both user dialects, and every lid
* the directory maps to that phone;
* - a `<lid>@lid` input yields the literal and the phone it resolves to (in both user dialects). It
* deliberately does NOT mint `<lid-digits>@c.us`: a lid's digits are not a phone number, and
* treating them as one would let `555000111@lid` match a `[email protected]` chat.
* - a group / status / newsletter / broadcast id has exactly one stored form, so it yields only the
* literal (expanding a group's digits into the user dialects could match an unrelated person), and
* so does an id under an unrecognised domain; only a bare number is qualified as a phone.
*
* The last rule is why a non-user kind returns just the input: it fails closed on the literal id.
*/
export interface ContactDirectory {
/** The phone digits a lid's user-part resolves to, or null/undefined when unmapped. */
resolveLid(lid: string): string | null | undefined | Promise<string | null | undefined>;
/** The lid user-parts currently mapped to a phone's digits. */
lidsForPhone(phone: string): string[] | Promise<string[]>;
}
export async function resolveJidCandidates(value: string, directory?: ContactDirectory): Promise<string[]> {
const parsed = parseWaId(value);
// Group ids are stored in the neutral `<id>@g.us` form, so normalize rather than echo the input:
// an upper-case domain must not make the guard's answer disagree with the list filter's.
if (parsed.kind === 'group') return [`${parsed.userPart}@g.us`];
// Only a bare number is qualified into the user dialects; an unrecognised domain is not a phone.
if (parsed.kind !== 'user' && parsed.kind !== 'lid' && (parsed.kind !== 'unknown' || value.includes('@'))) {
return [value];
}
if (parsed.kind === 'lid') {
// Start from the neutral `<lid>@lid`, not the raw input, for the same reason (an upper-case
// domain or a `:device` suffix must still match the stored form).
const candidates = new Set<string>([`${parsed.userPart}@lid`]);
const resolved = await directory?.resolveLid(parsed.userPart);
if (resolved) {
candidates.add(`${resolved}@c.us`);
candidates.add(`${resolved}@s.whatsapp.net`);
}
return [...candidates];
}
const phone = parsed.userPart;
const candidates = new Set<string>([value, `${phone}@c.us`, `${phone}@s.whatsapp.net`]);
for (const lid of (await directory?.lidsForPhone(phone)) ?? []) {
candidates.add(`${lid}@lid`);
}
return [...candidates];
}