HyperFlow / extension /src /worker.ts
Gaurav711's picture
Deploy 35b1393
64b0986 verified
Raw History Blame Contribute Delete
3.56 kB
// Extension service worker: validates page messages, keeps state in extension storage and answers
// the popup. All analysis runs here; nothing is sent over the network.
import highsLoader, { type Highs } from 'highs';
import { analyze } from './analyze';
import { pairKey, findMatches } from './match';
import { parseMsg } from './messages';
import { serialize } from './serial';
import type { OkCart, ParsedCart, Store } from './model';
import { storeForUrl } from './parsers';
import { freshSeen, recordSeen, type KeyValue } from './seen';
const kv: KeyValue = {
get: async (key) => (await chrome.storage.local.get(key))[key],
set: (key, value) => chrome.storage.local.set({ [key]: value }),
};
interface State { carts: Partial<Record<Store, OkCart>>; latest: ParsedCart | null; location: Partial<Record<Store, string>>; confirmations: string[] }
const load = async (): Promise<State> => ({ carts: {}, latest: null, location: {}, confirmations: [], ...((await kv.get('state')) as Partial<State> | undefined) });
const save = (state: State) => kv.set('state', state);
let solver: Promise<Highs> | null = null;
const highs = () => (solver ??= highsLoader({ locateFile: (file) => chrome.runtime.getURL(file) }));
function fromOwnContentScript(sender: chrome.runtime.MessageSender): Store | null {
if (sender.id !== chrome.runtime.id || !sender.tab || !sender.url) return null;
return storeForUrl(new URL(sender.url));
}
const fromOwnPopup = (sender: chrome.runtime.MessageSender) =>
sender.id === chrome.runtime.id && !sender.tab && sender.url?.startsWith(chrome.runtime.getURL('popup.html'));
async function handle(raw: unknown, sender: chrome.runtime.MessageSender): Promise<unknown> {
const msg = parseMsg(raw);
if (!msg) return { error: 'invalid message' };
const state = await load();
if (msg.type === 'cart' || msg.type === 'seen') {
const store = fromOwnContentScript(sender);
if (!store) return { error: 'untrusted sender' };
if (msg.type === 'seen') {
if (msg.prices.some((p) => p.store !== store)) return { error: 'store mismatch' };
state.location[store] = msg.prices[0]!.locationKey;
await recordSeen(kv, msg.prices);
} else {
if (msg.cart.store !== store) return { error: 'store mismatch' };
state.location[store] = msg.locationKey;
state.latest = msg.cart;
if (msg.cart.status === 'ok') state.carts[store] = msg.cart;
}
await save(state);
return { ok: true };
}
if (!fromOwnPopup(sender)) return { error: 'untrusted sender' };
const cart = state.latest;
if (!cart) return { empty: true };
if (cart.status !== 'ok') return { unsupported: cart };
const seen = await freshSeen(kv, state.location);
if (msg.type === 'confirm') {
const line = cart.lines[msg.lineIndex];
const match = line && findMatches(line, seen).find((m) => m.seen.store === msg.store);
if (!match) return { error: 'no such match' };
state.confirmations = [...new Set([...state.confirmations, pairKey(line, match.seen)])];
await save(state);
}
return { report: analyze(await highs(), cart, state.carts, seen, new Set(state.confirmations)) };
}
// Handlers read, modify and write extension storage; running them one at a time prevents
// lost updates when several store tabs report at once.
const inOrder = serialize();
chrome.runtime.onMessage.addListener((raw, sender, respond) => {
inOrder(() => handle(raw, sender)).then(respond, (error) => respond({ error: String(error) }));
return true; // keep the channel open for the async response
});