refactor: extract shared types + safe chrome wrappers into src/lib

- src/lib/types.ts: message contract (both ANALYZE_TEXT shapes preserved),
  config/response types, storage-key constants.
- src/lib/messaging.ts: single safeStorageGet/safeStorageSet/safeSendMessage/
  isExtensionValid implementation replacing the three divergent copies in
  Options, Popup, and content. Content script keeps its refresh-toast
  behavior via an onContextInvalidated callback.
- New '@lib' import alias (wxt force-overwrites '~' and '@' to srcDir, so
  those cannot point at ./src); wired in wxt.config, tsconfig, vitest.
- tests/unit/messaging.test.ts: 14 unit tests over the wrappers.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
john kevin asprec
2026-07-14 21:33:56 +08:00
parent 04a4a2dc99
commit 324cfcc486
10 changed files with 303 additions and 124 deletions

View File

@@ -1,6 +1,7 @@
import React, { useEffect, useRef, useState } from 'react';
import { createRoot } from 'react-dom/client';
import nacl from 'tweetnacl';
import { safeSendMessage, safeStorageGet, safeStorageSet } from '@lib/messaging';
// ─── Provider config ──────────────────────────────────────────────────────────
@@ -166,40 +167,6 @@ const styles = {
} as React.CSSProperties,
};
// ─── Safe chrome storage wrappers ────────────────────────────────────────────
function safeStorageGet(keys: string[], callback: (result: Record<string, string>) => void) {
try {
if (typeof chrome === 'undefined' || !chrome.runtime?.id) return;
chrome.storage.local.get(keys, callback);
} catch (err) {
console.warn('LexAI: Extension context invalidated', err);
}
}
function safeStorageSet(data: Record<string, string>, callback?: () => void) {
try {
if (typeof chrome === 'undefined' || !chrome.runtime?.id) return;
if (callback) {
chrome.storage.local.set(data, callback);
} else {
chrome.storage.local.set(data);
}
} catch (err) {
console.warn('LexAI: Extension context invalidated', err);
}
}
async function safeSendMessage(message: Record<string, unknown>): Promise<any> {
try {
if (typeof chrome === 'undefined' || !chrome.runtime?.id) return null;
return await chrome.runtime.sendMessage(message);
} catch (err) {
console.warn('LexAI: sendMessage failed', err);
return null;
}
}
// ─── Component ────────────────────────────────────────────────────────────────
function OptionsPage() {