// Plugin palette commands: a site tab tells the shell which commands its plugins registered, so the // command palette can list them under each plugin's name. Only `{ id, title, keywords }` strings // travel (capped in the registry and again natively, waybetter-host `plugins::commands`), only // about this tab, only when the list changes (`tab_report.commands`). Running one is the shell // asking native code to call `api.commands.run(id)` in this page; `run` never leaves it. // // Developer mode's start failures are reported here too: a toast in the page with file and line. import type { CommandInfo } from './commands.ts'; import { devErrorLocation, formatDevError } from './devErrors.ts'; export type Invoke = (command: string, args: Record) => Promise; type Commands = { list(): CommandInfo[]; onChange(callback: (list: CommandInfo[]) => void): () => void }; /** Reports the command list after it changes (batched, only real changes). Returns the disposer. */ export function installCommandReport(commands: Commands, invoke: Invoke | undefined, delay = 80): () => void { if (!invoke) return () => {}; let last = '[]'; let timer: ReturnType | undefined; const send = () => { timer = undefined; const list = commands.list(); const json = JSON.stringify(list); if (json === last) return; last = json; invoke('tab_report', { report: { commands: list } }).catch(() => {}); }; const off = commands.onChange(() => { if (timer === undefined) timer = setTimeout(send, delay); }); return () => { off(); if (timer !== undefined) clearTimeout(timer); }; } type Toast = (message: string, options: { tone: 'danger'; duration: number }) => void; /** * Developer mode (live reload): a plugin whose start failed shows `file:line — message` as a toast * in this page. The host evaluates reloaded plugins with a `sourceURL`, so the line is the file's. * `text` wraps the location in the app's words ("Plugin failed: {error}"). */ export function devErrorReporter(toast: () => Toast | undefined, text: (error: string) => string) { return (file: unknown, error: unknown) => { if (typeof file !== 'string') return; const location = formatDevError(devErrorLocation(error, file)); try { toast()?.(text(location), { tone: 'danger', duration: 12000 }); } catch { /* the page keeps working */ } }; }