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,5 +1,6 @@
import { defineBackground } from 'wxt/utils/define-background';
import nacl from 'tweetnacl';
import type { AnalyzePayload, LexAIConfig, LexAIResponse } from '@lib/types';
// ─── Fetch with timeout ───────────────────────────────────────────────────────
@@ -13,27 +14,6 @@ async function fetchWithTimeout(url: string, options: RequestInit, timeoutMs = 3
}
}
// ─── Types ────────────────────────────────────────────────────────────────────
interface AnalyzePayload {
text: string;
action: string;
style?: string;
}
interface LexAIConfig {
provider?: string;
apiKey?: string;
apiKeyEnc?: string;
encKey?: string;
model?: string;
}
interface LexAIResponse {
result?: string;
error?: string;
}
// ─── System prompts ───────────────────────────────────────────────────────────
function getSystemPrompt(action: string, style?: string): string {

View File

@@ -1,4 +1,5 @@
import { defineContentScript } from 'wxt/utils/define-content-script';
import { isExtensionValid, safeSendMessage } from '@lib/messaging';
export default defineContentScript({
matches: ['<all_urls>'],
@@ -362,15 +363,7 @@ export default defineContentScript({
}
}
// ─── Extension context guard ──────────────────────────────────────────────
function isExtensionValid(): boolean {
try {
return typeof chrome !== 'undefined' && !!chrome.runtime?.id;
} catch {
return false;
}
}
// Extension context guard: isExtensionValid is imported from ~/lib/messaging.
function showErrorToast(msg: string) {
const toast = document.createElement('div');
@@ -528,7 +521,7 @@ export default defineContentScript({
grid.style.display = 'none';
spinnerSlot.style.display = 'flex';
const response = await safeSendMessage({
const response = await sendToBackground({
type: 'COPY_AS',
text,
format: fmt,
@@ -563,22 +556,13 @@ export default defineContentScript({
}
// ─── Safe chrome.runtime.sendMessage wrapper ──────────────────────────────
// Shared implementation; on a stale extension context we toast and clean up.
async function safeSendMessage(payload: Record<string, unknown>): Promise<unknown> {
if (!isExtensionValid()) {
async function sendToBackground(payload: Record<string, unknown>): Promise<unknown> {
return safeSendMessage(payload, () => {
showErrorToast('LexAI was updated — please refresh this page.');
return null;
}
try {
return await chrome.runtime.sendMessage(payload);
} catch (err) {
if (String(err).includes('Extension context invalidated') ||
String(err).includes('message channel closed')) {
showErrorToast('LexAI was updated — please refresh this page.');
hideToolbar();
}
return null;
}
hideToolbar();
});
}
// ─── LLM call ─────────────────────────────────────────────────────────────
@@ -628,14 +612,14 @@ export default defineContentScript({
}
try {
const response = await safeSendMessage({
const response = await sendToBackground({
type: 'ANALYZE_TEXT',
payload: { text: textToProcess, action, style: currentStyle },
}) as { error?: string; result?: string } | null;
hideToolbar();
if (response === null) return; // safeSendMessage already handled the error
if (response === null) return; // sendToBackground already handled the error
if (response?.error) {
showModal(`${response.error}`, null, snapStart, snapEnd, snapElement, snapRange, action, textToProcess);
@@ -832,7 +816,7 @@ export default defineContentScript({
regenBtn.disabled = true;
styleSelect.disabled = true;
const response = await safeSendMessage({
const response = await sendToBackground({
type: 'ANALYZE_TEXT',
payload: { text: textForRegenerate, action, style: chosenStyle },
}) as { error?: string; result?: string } | null;

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() {

View File

@@ -1,41 +1,6 @@
import React, { useEffect, useRef, useState } from 'react';
import { createRoot } from 'react-dom/client';
// ─── Safe chrome storage wrapper ─────────────────────────────────────────────
function safeStorageGet(
storage: chrome.storage.StorageArea,
keys: string[],
callback: (result: Record<string, string>) => void,
) {
try {
if (typeof chrome === 'undefined' || !chrome.runtime?.id) return;
storage.get(keys, callback);
} catch (err) {
console.warn('LexAI: Extension context invalidated', err);
}
}
function safeStorageSet(storage: chrome.storage.StorageArea, data: Record<string, string>) {
try {
if (typeof chrome === 'undefined' || !chrome.runtime?.id) return;
storage.set(data);
} catch (err) {
console.warn('LexAI: Extension context invalidated', err);
}
}
async function safeSendMessage(
message: Record<string, unknown>,
): Promise<Record<string, string> | null> {
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;
}
}
import { safeSendMessage, safeStorageGet, safeStorageSet } from '@lib/messaging';
// ─── Constants ───────────────────────────────────────────────────────────────
@@ -222,7 +187,7 @@ function Popup() {
// Load config + restore session input + load writing style
useEffect(() => {
safeStorageGet(chrome.storage.local, ['provider', 'apiKey', 'apiKeyEnc', 'model', 'writingStyle'], (result) => {
safeStorageGet(['provider', 'apiKey', 'apiKeyEnc', 'model', 'writingStyle'], (result) => {
if (result.apiKey || result.apiKeyEnc) {
setConfigured(true);
setProvider(result.provider || 'openai');
@@ -235,11 +200,11 @@ function Popup() {
if (!sessionRestored.current) {
sessionRestored.current = true;
safeStorageGet(chrome.storage.session, ['lexai_popup_input'], (res) => {
safeStorageGet(['lexai_popup_input'], (res) => {
if (res.lexai_popup_input) {
setInputText(res.lexai_popup_input);
}
});
}, chrome.storage.session);
}
}, []);
@@ -247,14 +212,14 @@ function Popup() {
const handleInputChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
const val = e.target.value;
setInputText(val);
safeStorageSet(chrome.storage.session, { lexai_popup_input: val });
safeStorageSet({ lexai_popup_input: val }, undefined, chrome.storage.session);
};
// Save writing style on change
const handleStyleChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
const val = e.target.value;
setWritingStyle(val);
safeStorageSet(chrome.storage.local, { writingStyle: val });
safeStorageSet({ writingStyle: val });
};
const openSettings = () => {