/** * Keyboard command handler — routing for summon-inline: * 1. Restricted URL (non-http/https) → open popup * 2. Ping content script (150ms timeout) → if alive, send SUMMON_AUTOFILL * with source:"shortcut"; content script handles inline (autofill selector * or search-mode palette). Always returns early — no popup fallback. * 3. Content script not ready → open popup fallback */ const PING_TIMEOUT_MS = 150; async function pingContentScript(tabId: number): Promise { return new Promise((resolve) => { const timer = setTimeout(() => resolve(false), PING_TIMEOUT_MS); try { chrome.tabs.sendMessage(tabId, { type: "PING" }, (response) => { clearTimeout(timer); if (chrome.runtime.lastError) { resolve(false); } else { resolve(response?.ok === true); } }); } catch { clearTimeout(timer); resolve(false); } }); } async function openPopup(): Promise { try { // chrome.action.openPopup() requires Chrome 127+ and user gesture context; // it may throw — that's acceptable, we degrade gracefully. await (chrome.action as { openPopup?: () => Promise }).openPopup?.(); } catch { // Silently ignore — user can click the toolbar icon instead } } export function setupCommands(): void { chrome.commands.onCommand.addListener(async (command) => { if (command !== "summon-inline") return; const [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); if (!tab?.id || !tab.url) return; // ── Step 1: restricted URL? ─────────────────────────────────── if (!/^https?:\/\//i.test(tab.url)) { await openPopup(); return; } const tabId = tab.id; // ── Step 2: ping existing content script ───────────────────── const alive = await pingContentScript(tabId); if (alive) { // Content script fully handles SUMMON_AUTOFILL with source:"shortcut": // shows the autofill selector when a form is present, or falls back to // a search-mode palette that copies to clipboard. No popup fallback needed. chrome.tabs.sendMessage(tabId, { type: "SUMMON_AUTOFILL", source: "shortcut" }).catch(() => {}); return; } // ── Step 3: content script unavailable ─────────────────────── await openPopup(); }); }