Cotton code
61 lines · 2.8 KB · TypeScriptRaw
/** * A contact, found or made, from one way of reaching somebody: * cotton-rules' `messages::resolve_contact` (crates/cotton-rules/src/messages/ * resolve_contact.rs), run as WASM over the object (`driver.ts`). ONE rule, * because two would eventually disagree, and a disagreement is two contact * rows for one human. The writes are returned as changes, never applied. * * The rule's `workspace_id` names the database to the phone's driver; here * one database is one object, so it is empty: no read is filtered by it and * the rows lose the column (`objectChanges`). */import { rule } from "../rules/index.ts";import { objectChanges, runEngine, type Change } from "./driver.ts";import type { Handle } from "./handles.ts";import type { ContactRow, Reader } from "./reader.ts";export { upsert, type Change } from "./driver.ts";export interface MatchedPerson {  id: string;  full_name: string | null;}/** The people the object holds, by the handles they carry; a handle two people claim resolves to neither. */export function peopleByHandle(db: Reader): Map<string, MatchedPerson> {  return new Map(Object.entries(runEngine<Record<string, MatchedPerson>>("people", { workspaceId: "" }, db)));}/** The contact this handle already belongs to: its handle row first, then — for a phone — the primary number. */export function findContactByHandle(db: Reader, handle: Handle): ContactRow | null {  return runEngine<ContactRow | null>("contact", { workspaceId: "", handle }, db);}/** The handle row, under its derived id; emitted every time (an upsert of what is there writes nothing). */export function contactHandleChanges(namespace: string, contactId: string, handle: Handle, now: string): Change[] {  return objectChanges(rule<Change[]>("contacts.handle_row", { workspaceId: "", namespace, contactId, handle, now }));}export interface ResolveArgs {  db: Reader;  namespace: string;  handle: Handle;  displayName: string | null;  personId: string | null;  now: string;  newId: () => string;  people: Map<string, MatchedPerson>;}/** * Find or create the ONE contact reachable at this handle: an existing contact * always wins; a name and a People link fill only where none is held; a new * contact's id is derived from its phone or its site handle (an email-only one * is minted); the handle row always. */export function resolveContact(args: ResolveArgs): { contactId: string; changes: Change[]; created: boolean } {  const { db, namespace, handle, displayName, personId, now, newId, people } = args;  const input = { workspaceId: "", namespace, handle, displayName, personId, now, people: Object.fromEntries(people) };  const resolved = runEngine<{ contactId: string; changes: Change[]; created: boolean }>("resolve", input, db, newId);  return { ...resolved, changes: objectChanges(resolved.changes) };}