File size: 1,405 Bytes
4331e77 ec5d85c 6ee391c 4331e77 ec5d85c 6ee391c ec5d85c 6ee391c ec5d85c 6ee391c 659811e 6ee391c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
// Simple type to replace removed WebSearchSource
type SimpleSource = {
title?: string;
link: string;
};
import { processBlocks, type BlockToken } from "$lib/utils/marked";
export type IncomingMessage = {
type: "process";
content: string;
sources: SimpleSource[];
requestId: number;
};
export type OutgoingMessage = {
type: "processed";
blocks: BlockToken[];
requestId: number;
};
// Flag to track if the worker is currently processing a message
let isProcessing = false;
// Buffer to store the latest incoming message
let latestMessage: IncomingMessage | null = null;
// Helper function to safely handle the latest message
async function processMessage() {
if (latestMessage) {
const nextMessage = latestMessage;
latestMessage = null;
isProcessing = true;
try {
const { content, sources, requestId } = nextMessage;
const processedBlocks = await processBlocks(content, sources);
postMessage(
JSON.parse(JSON.stringify({ type: "processed", blocks: processedBlocks, requestId }))
);
} finally {
isProcessing = false;
// After processing, check if a new message was buffered
await new Promise((resolve) => setTimeout(resolve, 100));
processMessage();
}
}
}
onmessage = (event) => {
if (event.data.type !== "process") {
return;
}
latestMessage = event.data as IncomingMessage;
if (!isProcessing && latestMessage) {
processMessage();
}
};
|