export type Profile = { name: string; email?: string; phone?: string };/** * A missing key (or `undefined`) means keep, `null` means clear, a string means set. * `name` cannot be cleared. */export type ProfilePatch = { name?: string; email?: string | null; phone?: string | null };export class ProfileError extends Error { constructor(public readonly kind: "invalid_name" | "invalid_email" | "invalid_phone") { super(kind); }}const validEmail = (s: string): boolean => { const parts = s.split("@"); return parts.length === 2 && parts[0] !== "" && parts[1] !== "";};const validPhone = (s: string): boolean => { if (!/^\+?[0-9 -]*$/.test(s)) return false; const digits = s.replace(/[^0-9]/g, "").length; return digits >= 7 && digits <= 15;};const nextField = ( current: string | undefined, change: string | null | undefined, valid: (s: string) => boolean, kind: ProfileError["kind"],): string | undefined => { if (change === undefined) return current; if (change === null) return undefined; const t = change.trim(); if (!valid(t)) throw new ProfileError(kind); return t;};/** Throws ProfileError when a value being set is invalid. */export function applyPatch(profile: Profile, patch: ProfilePatch): Profile { let name = profile.name; if (patch.name !== undefined) { name = patch.name.trim(); if (name === "") throw new ProfileError("invalid_name"); } const email = nextField(profile.email, patch.email, validEmail, "invalid_email"); const phone = nextField(profile.phone, patch.phone, validPhone, "invalid_phone"); const out: Profile = { name }; if (email !== undefined) out.email = email; if (phone !== undefined) out.phone = phone; return out;}