import { nativeSource } from "./native.ts"; export type Target = { recipient: string; chatId?: never } | { chatId: number; recipient?: never }; export type MessageService = "iMessage" | "SMS" | "RCS"; export type MessageDraft = { target: Target; text: string; service: MessageService; digest: string; }; export type ReadInput = { chatId: number; limit?: number; beforeMessageId?: number; after?: string; before?: string; }; export type SearchInput = { query: string; chatId?: number; limit?: number; scanLimit?: number; beforeMessageId?: number; after?: string; before?: string; service?: MessageService; fromMe?: boolean; }; export function object(raw: unknown, keys: string[]): Record { if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error("Pass an input object."); for (const key of Object.keys(raw)) if (!keys.includes(key)) throw new Error("Unknown input field: " + key); return raw as Record; } export function integer( value: unknown, label: string, fallback?: number, max = Number.MAX_SAFE_INTEGER, ): number { if (value === undefined && fallback !== undefined) return fallback; if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1 || value > max) throw new Error(label + " must be an integer from 1 to " + max + "."); return value; } export function text(value: unknown, label: string, max: number): string { if (typeof value !== "string" || !value.trim() || value.length > max || value.includes("\0")) throw new Error( label + " must be non-empty text of at most " + max + " characters, without null bytes.", ); return value; } export function target(raw: unknown): Target { const p = object(raw, ["recipient", "chatId"]); if ("recipient" in p === "chatId" in p) throw new Error("Choose exactly one target: recipient or chatId."); if ("chatId" in p) return { chatId: integer(p.chatId, "chatId") }; const recipient = text(p.recipient, "recipient", 254).trim(); if ( !/^\+[1-9]\d{6,14}$/.test(recipient) && !/^[^\s@<>,;"\\]+@[^\s@<>,;"\\]+\.[^\s@<>,;"\\]+$/.test(recipient) ) throw new Error( "Use an exact E.164 phone number or iMessage email address, not a contact name.", ); return { recipient }; } export function filters(raw: Record) { const result: Record = {}; for (const key of ["chatId", "beforeMessageId"]) if (raw[key] !== undefined) result[key] = integer(raw[key], key); for (const key of ["after", "before"]) if (raw[key] !== undefined) { const value = text(raw[key], key, 40); if ( !/^\d{4}-\d\d-\d\dT.*(?:Z|[+-]\d\d:\d\d)$/.test(value) || !Number.isFinite(Date.parse(value)) ) throw new Error(key + " must be an ISO date with a timezone."); result[key] = new Date(value).toISOString(); } if (result.after && result.before && String(result.after) >= String(result.before)) throw new Error("after must be earlier than before."); if (raw.service !== undefined) { if (typeof raw.service !== "string" || !["iMessage", "SMS", "RCS"].includes(raw.service)) throw new Error("service must be iMessage, SMS, or RCS."); result.service = raw.service; } if (raw.fromMe !== undefined) { if (typeof raw.fromMe !== "boolean") throw new Error("fromMe must be a boolean."); result.fromMe = raw.fromMe; } return result; } export async function digest( target: Target, body: string, service: MessageService = "iMessage", ): Promise { const bytes = new TextEncoder().encode(JSON.stringify({ target, text: body, service })); return Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)), (b) => b.toString(16).padStart(2, "0"), ).join(""); } export async function draft(raw: unknown): Promise { const p = object(raw, ["target", "text", "service"]); const to = target(p.target); const body = text(p.text, "text", 8000); const service = p.service ?? "iMessage"; if (typeof service !== "string" || !["iMessage", "SMS", "RCS"].includes(service)) throw new Error("service must be iMessage, SMS, or RCS."); if (service !== "iMessage" && !("chatId" in to)) throw new Error("SMS and RCS require an existing chatId with verified participants."); return { target: to, text: body, service: service as MessageService, digest: await digest(to, body, service as MessageService), }; } export async function validateDraft(raw: unknown): Promise { const p = object(raw, ["target", "text", "service", "digest"]); if (typeof p.service !== "string" || !["iMessage", "SMS", "RCS"].includes(p.service)) throw new Error("The reviewed draft must include its service."); const result = await draft({ target: p.target, text: p.text, service: p.service, }); if (p.digest !== result.digest) throw new Error("The draft changed. Prepare and review a new draft before sending."); return result; } export function nativeScript(input: Record): string { return ( nativeSource + "\nfunction run() { return JSON.stringify(nativeMain(" + JSON.stringify(input) .replace(/\u2028/g, "\\u2028") .replace(/\u2029/g, "\\u2029") + ")); }" ); } export async function native(input: Record): Promise { const { kody } = await import("kody:runtime"); // Host commands are a context-only namespace, not an ordinary Kody capability. const commands = kody.command; const run: unknown = commands ? Reflect.get(commands, "run") : undefined; if (typeof run !== "function") { throw new Error("Run on a Mac execution context with host commands enabled."); } let result: { exitCode: number | null; stdout: string; timedOut?: boolean; stdoutTruncated?: boolean; }; try { result = await Reflect.apply(run, commands, [ { file: "/usr/bin/osascript", args: ["-l", "JavaScript", "-"], stdin: nativeScript(input), timeoutMs: 45000, maxOutputBytes: 1048576, }, ]); } catch (error) { if (input.action === "send") return { status: "uncertain", retrySafe: false, issue: "The host connection failed. Inspect Messages before sending again.", } as T; throw error; } if (result.timedOut || result.stdoutTruncated || result.exitCode !== 0) { if (input.action === "send") return { status: "uncertain", retrySafe: false, issue: "The native command did not complete reliably. Inspect Messages before sending again.", } as T; throw new Error( "The macOS Messages helper failed or exceeded its bounded output. Run on a Mac context with host commands enabled and narrow the query.", ); } let response: { ok: boolean; result?: unknown; error?: string }; try { response = JSON.parse(result.stdout.trim()); } catch { if (input.action === "send") return { status: "uncertain", retrySafe: false, issue: "The send result was unreadable. Inspect Messages before retrying.", } as T; throw new Error("The macOS Messages helper returned invalid JSON."); } if (!response.ok) throw new Error(response.error ?? "Messages operation failed."); return response.result as T; }