Skip to content

Black Friday

Annual Pro is $90 for the first year, normally $120. Or start monthly at $6 for two months, then $12.

Ends Dec 4, 11:59 PM PT.

Create an account
← Public packages

@kentcdodds/google

Google helpers for Gmail, Calendar, Drive, People, YouTube (including upload), and Analytics.

FollowFork

Files

people-match.ts

278 lines · 11.3 KB · TypeScript
// Pure, dependency-free contact matching used by listConnections filtering and findContacts.

/** A small, size-bounded view of a Google People person. Empty fields are omitted. */
export type CompactContact = {
	resourceName: string
	name?: string
	names?: string[]
	nicknames?: string[]
	emails?: string[]
	phones?: string[]
	addresses?: string[]
	organizations?: string[]
	birthdays?: string[]
	urls?: string[]
	notes?: string
	/** Any other requested personFields, passed through unchanged. */
	extra?: Record<string, unknown>
}

export type ContactFilter = { name?: string; email?: string; phone?: string }

type PersonRecord = Record<string, unknown>

function list(value: unknown): PersonRecord[] {
	return Array.isArray(value) ? (value.filter((item) => item && typeof item === 'object') as PersonRecord[]) : []
}

function str(value: unknown): string | undefined {
	return typeof value === 'string' && value.trim() ? value.trim() : undefined
}

function uniq(values: Array<string | undefined>): string[] {
	return [...new Set(values.filter((value): value is string => Boolean(value)))]
}

function formatDate(value: unknown): string | undefined {
	if (!value || typeof value !== 'object') return undefined
	const date = value as { year?: number; month?: number; day?: number }
	if (!date.month || !date.day) return undefined
	const mm = String(date.month).padStart(2, '0')
	const dd = String(date.day).padStart(2, '0')
	return (date.year ? date.year + '-' : '--') + mm + '-' + dd
}

const KNOWN_FIELDS = new Set(['resourceName', 'etag', 'metadata', 'names', 'nicknames', 'emailAddresses', 'phoneNumbers', 'addresses', 'organizations', 'birthdays', 'urls', 'biographies'])

/** Project a raw People API person into a `CompactContact`. */
export function compactPerson(person: unknown): CompactContact {
	const record = (person && typeof person === 'object' ? person : {}) as PersonRecord
	const names = uniq(list(record.names).map((n) => str(n.displayName) ?? uniq([str(n.givenName), str(n.familyName)]).join(' ')))
	const out: CompactContact = { resourceName: str(record.resourceName) ?? '' }
	if (names.length) { out.name = names[0]; if (names.length > 1) out.names = names }
	const nicknames = uniq(list(record.nicknames).map((n) => str(n.value)))
	if (nicknames.length) out.nicknames = nicknames
	const emails = uniq(list(record.emailAddresses).map((e) => str(e.value)))
	if (emails.length) out.emails = emails
	const phones = uniq(list(record.phoneNumbers).map((p) => str(p.value) ?? str(p.canonicalForm)))
	if (phones.length) out.phones = phones
	const addresses = uniq(list(record.addresses).map((a) => str(a.formattedValue)?.replace(/\s*\n\s*/g, ', ') ?? uniq([str(a.streetAddress), str(a.city), str(a.region), str(a.postalCode), str(a.country)]).join(', ')))
	if (addresses.length) out.addresses = addresses
	const organizations = uniq(list(record.organizations).map((o) => uniq([str(o.title), str(o.name)]).join(', ')))
	if (organizations.length) out.organizations = organizations
	const birthdays = uniq(list(record.birthdays).map((b) => formatDate(b.date) ?? str(b.text)))
	if (birthdays.length) out.birthdays = birthdays
	const urls = uniq(list(record.urls).map((u) => str(u.value)))
	if (urls.length) out.urls = urls
	const notes = str(list(record.biographies)[0]?.value)
	if (notes) out.notes = notes.length > 280 ? notes.slice(0, 280) + '...' : notes
	const extra: Record<string, unknown> = {}
	for (const [key, value] of Object.entries(record)) if (!KNOWN_FIELDS.has(key)) extra[key] = value
	if (Object.keys(extra).length) out.extra = extra
	return out
}

/** Lowercase, strip diacritics and punctuation, collapse whitespace. */
export function normalizeText(value: string): string {
	return value.normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase().replace(/[^a-z0-9@.+]+/g, ' ').trim()
}

function tokens(value: string): string[] {
	return normalizeText(value).split(/[\s@.+]+/).filter(Boolean)
}

/** Common given-name groups. Any two names in a group are treated as a match. Generic, not tied to anyone. */
export const NICKNAME_GROUPS: string[][] = [
	['william', 'will', 'bill', 'billy', 'willie', 'liam'],
	['robert', 'rob', 'bob', 'bobby', 'robbie', 'bert'],
	['richard', 'rich', 'rick', 'ricky', 'dick'],
	['james', 'jim', 'jimmy', 'jamie'],
	['john', 'jon', 'johnny', 'jack'],
	['jonathan', 'jon', 'jonny', 'nathan'],
	['katherine', 'catherine', 'kathryn', 'kathleen', 'kate', 'katie', 'kathy', 'cathy', 'kat', 'kay', 'kitty'],
	['elizabeth', 'liz', 'lizzie', 'beth', 'betty', 'eliza', 'libby', 'betsy'],
	['margaret', 'maggie', 'meg', 'peggy', 'greta'],
	['michael', 'mike', 'mikey', 'mick'],
	['christopher', 'chris', 'kit'],
	['christina', 'christine', 'chris', 'tina', 'chrissy'],
	['jennifer', 'jen', 'jenny'],
	['joseph', 'joe', 'joey'],
	['josephine', 'jo', 'josie'],
	['thomas', 'tom', 'tommy'],
	['daniel', 'dan', 'danny'],
	['matthew', 'matt'],
	['anthony', 'tony'],
	['nicholas', 'nick', 'nicky'],
	['alexander', 'alex', 'xander', 'sasha'],
	['alexandra', 'alex', 'alexa', 'sandra', 'sasha'],
	['samuel', 'sam', 'sammy'],
	['samantha', 'sam', 'sammy'],
	['benjamin', 'ben', 'benny'],
	['andrew', 'andy', 'drew'],
	['edward', 'ed', 'eddie', 'ted', 'teddy', 'ned'],
	['steven', 'stephen', 'steve'],
	['patricia', 'pat', 'patty', 'trish', 'tricia'],
	['patrick', 'pat', 'paddy'],
	['susan', 'sue', 'susie', 'suzanne'],
	['deborah', 'debra', 'deb', 'debbie'],
	['rebecca', 'becky', 'becca'],
	['jessica', 'jess', 'jessie'],
	['victoria', 'vicky', 'tori'],
	['abigail', 'abby', 'gail'],
	['kimberly', 'kim'],
	['timothy', 'tim', 'timmy'],
	['gregory', 'greg'],
	['jacob', 'jake'],
	['zachary', 'zach', 'zack'],
	['kenneth', 'ken', 'kenny'],
	['charles', 'charlie', 'chuck', 'chas'],
	['charlotte', 'charlie', 'lottie'],
	['david', 'dave', 'davey'],
	['frederick', 'fred', 'freddie'],
	['henry', 'hank', 'harry'],
	['lawrence', 'larry'],
	['leonard', 'leo', 'len', 'lenny'],
	['ronald', 'ron', 'ronnie'],
	['donald', 'don', 'donnie'],
	['raymond', 'ray'],
	['gerald', 'gerry', 'jerry'],
	['peter', 'pete'],
	['philip', 'phillip', 'phil'],
	['douglas', 'doug'],
	['jeffrey', 'geoffrey', 'jeff', 'geoff'],
	['barbara', 'barb', 'barbie'],
	['dorothy', 'dot', 'dottie'],
	['theodore', 'theo', 'ted', 'teddy'],
	['madeline', 'madeleine', 'maddie', 'maddy'],
	['olivia', 'liv', 'livvy'],
	['emily', 'em', 'emmy'],
	['emma', 'em', 'emmy'],
	['sarah', 'sara', 'sally'],
	['ann', 'anne', 'anna', 'annie', 'nancy'],
	['mary', 'molly', 'polly', 'mae'],
	['jacqueline', 'jackie'],
	['judith', 'judy'],
	['cynthia', 'cindy'],
	['pamela', 'pam'],
	['kristen', 'kirsten', 'kristin', 'kris'],
	['natalie', 'nat'],
	['nathaniel', 'nate', 'nathan', 'nat'],
]

const NICKNAME_INDEX: Map<string, Set<number>> = (() => {
	const index = new Map<string, Set<number>>()
	NICKNAME_GROUPS.forEach((group, i) => { for (const name of group) { const set = index.get(name) ?? new Set<number>(); set.add(i); index.set(name, set) } })
	return index
})()

function sharesNicknameGroup(a: string, b: string): boolean {
	const groupsA = NICKNAME_INDEX.get(a)
	if (!groupsA) return false
	const groupsB = NICKNAME_INDEX.get(b)
	if (!groupsB) return false
	for (const group of groupsA) if (groupsB.has(group)) return true
	return false
}

/** Rough phonetic key so spelling variants (c/k, ph/f, y/i, doubled letters, silent h) compare equal. */
export function looseKey(token: string): string {
	return token
		.replace(/ph/g, 'f')
		.replace(/ck/g, 'k')
		.replace(/[cq]/g, 'k')
		.replace(/th/g, 't')
		.replace(/y/g, 'i')
		.replace(/z/g, 's')
		.replace(/(?<=.)h/g, '')
		.replace(/(.)\1+/g, '$1')
}

function editDistance(a: string, b: string, max: number): number {
	if (Math.abs(a.length - b.length) > max) return max + 1
	let prev = Array.from({ length: b.length + 1 }, (_, i) => i)
	for (let i = 1; i <= a.length; i++) {
		const row = [i]
		let best = i
		for (let j = 1; j <= b.length; j++) {
			row[j] = Math.min(prev[j] + 1, row[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1))
			if (row[j] < best) best = row[j]
		}
		if (best > max) return max + 1
		prev = row
	}
	return prev[b.length]
}

/** Score how well one query token matches one candidate token (0 = no match, 1 = exact). */
export function tokenScore(query: string, candidate: string): number {
	if (!query || !candidate) return 0
	if (query === candidate) return 1
	if (query.length >= 2 && candidate.startsWith(query)) return 0.9
	if (sharesNicknameGroup(query, candidate)) return 0.85
	const lq = looseKey(query)
	const lc = looseKey(candidate)
	if (lq === lc) return 0.8
	if (lq.length >= 3 && lc.startsWith(lq)) return 0.75
	if (query.length >= 4 && editDistance(query, candidate, 1) <= 1) return 0.7
	if (query.length >= 7 && editDistance(query, candidate, 2) <= 2) return 0.6
	return 0
}

function digits(value: string): string {
	return value.replace(/\D+/g, '')
}

function looksLikePhone(query: string): boolean {
	const d = digits(query)
	return d.length >= 4 && d.length >= query.replace(/[\s()+.-]/g, '').length * 0.8
}

function scoreName(query: string, contact: CompactContact): number {
	const queryTokens = tokens(query)
	if (!queryTokens.length) return 0
	const nameStrings = [...(contact.name ? [contact.name] : []), ...(contact.names ?? []), ...(contact.nicknames ?? [])]
	const normalizedQuery = normalizeText(query)
	if (nameStrings.some((name) => normalizeText(name) === normalizedQuery)) return 1
	const candidateTokens = uniq([...nameStrings.flatMap(tokens), ...(contact.emails ?? []).flatMap((email) => tokens(email.split('@')[0]))])
	let total = 0
	for (const queryToken of queryTokens) {
		let best = 0
		for (const candidate of candidateTokens) { const score = tokenScore(queryToken, candidate); if (score > best) best = score; if (best === 1) break }
		if (best === 0) return 0
		total += best
	}
	return total / queryTokens.length
}

/**
 * Score a compact contact against a free-text query (name, email, or phone).
 * Case-insensitive, diacritic-insensitive, tolerant of nicknames and small typos.
 * Returns 0 when it does not match, up to 1 for an exact match.
 */
export function scoreContact(query: string, contact: CompactContact): number {
	const trimmed = query.trim()
	if (!trimmed) return 0
	if (trimmed.includes('@')) {
		const needle = trimmed.toLowerCase()
		return (contact.emails ?? []).some((email) => email.toLowerCase() === needle) ? 1 : (contact.emails ?? []).some((email) => email.toLowerCase().includes(needle)) ? 0.9 : 0
	}
	if (looksLikePhone(trimmed)) {
		const needle = digits(trimmed)
		return (contact.phones ?? []).some((phone) => digits(phone).endsWith(needle) || digits(phone).includes(needle)) ? 1 : 0
	}
	const nameScore = scoreName(trimmed, contact)
	if (nameScore) return nameScore
	const needle = normalizeText(trimmed)
	if (needle.length >= 3 && (contact.organizations ?? []).some((org) => normalizeText(org).includes(needle))) return 0.6
	return 0
}

/** Score a contact against a structured filter; every provided field must match. */
export function scoreContactFilter(filter: ContactFilter, contact: CompactContact): number {
	const scores: number[] = []
	if (filter.name) scores.push(scoreName(filter.name, contact))
	if (filter.email) { const needle = filter.email.toLowerCase().trim(); scores.push((contact.emails ?? []).some((email) => email.toLowerCase().includes(needle)) ? 1 : 0) }
	if (filter.phone) { const needle = digits(filter.phone); scores.push(needle && (contact.phones ?? []).some((phone) => digits(phone).includes(needle)) ? 1 : 0) }
	if (!scores.length || scores.some((score) => score === 0)) return 0
	return Math.min(...scores)
}