mirror of
https://github.com/multipleof4/sune.git
synced 2026-01-14 00:27:56 +00:00
Update sw.js
This commit is contained in:
376
public/sw.js
376
public/sw.js
@@ -1,66 +1,64 @@
|
|||||||
// /sw.js (drop in at root)
|
// sw.js (use this as your vite-plugin-pwa worker source)
|
||||||
// Debug service worker — tee & write to localforage and expose debug commands.
|
// - Tees streaming responses matching TARGET_SUBSTRING
|
||||||
|
// - Continuously overwrites "last thread" in localForage backing DB (key=threads_v1)
|
||||||
|
// - No importScripts required (uses native IndexedDB)
|
||||||
|
// - Exposes debug commands via postMessage: PING, PING_STATUS, TEST_WRITE, READ_KEY, LIST_SW_SAVED
|
||||||
|
|
||||||
const LF_CDN = 'https://cdn.jsdelivr.net/npm/localforage@1.10.0/dist/localforage.min.js';
|
const TARGET_SUBSTRING = 'openrouter.ai/api/v1/chat/completions'; // adjust if necessary
|
||||||
const THREADS_KEY = 'threads_v1';
|
const THREADS_KEY = 'threads_v1';
|
||||||
const TARGET_SUBSTRING = 'openrouter.ai/api/v1/chat/completions'; // adjust if needed
|
const SAVE_BYTES_THRESHOLD = 6 * 1024;
|
||||||
const SAVE_BYTES_THRESHOLD = 6 * 1024; // ~6KB
|
const SAVE_TIME_THRESHOLD = 800;
|
||||||
const SAVE_TIME_THRESHOLD = 800; // ms
|
|
||||||
const BROADCAST_THROTTLE_MS = 600;
|
const BROADCAST_THROTTLE_MS = 600;
|
||||||
|
|
||||||
|
const DB_NAME = 'localforage';
|
||||||
|
const STORE_NAME = 'keyvaluepairs';
|
||||||
|
|
||||||
const gid = () => Math.random().toString(36).slice(2,9) + '-' + Date.now().toString(36);
|
const gid = () => Math.random().toString(36).slice(2,9) + '-' + Date.now().toString(36);
|
||||||
const now = () => Date.now();
|
const now = () => Date.now();
|
||||||
|
|
||||||
let localforageAvailable = false;
|
function openLFDB() {
|
||||||
let lfLoadError = null;
|
return new Promise((resolve, reject) => {
|
||||||
|
const req = indexedDB.open(DB_NAME);
|
||||||
// Attempt to import localforage
|
req.onsuccess = (e) => resolve(e.target.result);
|
||||||
try {
|
req.onerror = (e) => reject(e.target.error || new Error('open error'));
|
||||||
importScripts(LF_CDN);
|
});
|
||||||
if (self.localforage) {
|
|
||||||
localforageAvailable = true;
|
|
||||||
// configure a name to avoid collisions (optional)
|
|
||||||
try {
|
|
||||||
localforage.config({ name: 'sw-localforage' });
|
|
||||||
} catch(e){}
|
|
||||||
} else {
|
|
||||||
lfLoadError = 'localforage not present after importScripts';
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
lfLoadError = String(e && e.message ? e.message : e);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// in-memory state for debug/status
|
async function idbGetRaw(key) {
|
||||||
const state = {
|
const db = await openLFDB();
|
||||||
totalIntercepted: 0,
|
const tx = db.transaction(STORE_NAME, 'readonly');
|
||||||
activeStreams: {}, // streamId -> meta
|
const store = tx.objectStore(STORE_NAME);
|
||||||
lastStreamSummary: null,
|
return await new Promise((res, rej) => {
|
||||||
debugWrites: [] // ids of test threads written by SW
|
const r = store.get(key);
|
||||||
};
|
r.onsuccess = ev => res(ev.target.result);
|
||||||
|
r.onerror = ev => rej(ev.target.error || new Error('get error'));
|
||||||
async function safeReadThreads() {
|
});
|
||||||
if (!localforageAvailable) throw new Error('localforage not available: ' + lfLoadError);
|
}
|
||||||
try {
|
|
||||||
const v = await localforage.getItem(THREADS_KEY);
|
async function idbPutRaw(key, value) {
|
||||||
return Array.isArray(v) ? v : [];
|
const db = await openLFDB();
|
||||||
} catch (err) {
|
const tx = db.transaction(STORE_NAME, 'readwrite');
|
||||||
throw err;
|
const store = tx.objectStore(STORE_NAME);
|
||||||
}
|
return await new Promise((res, rej) => {
|
||||||
}
|
const r = store.put({ key, value });
|
||||||
async function safeWriteThreads(arr) {
|
r.onsuccess = () => res(true);
|
||||||
if (!localforageAvailable) throw new Error('localforage not available: ' + lfLoadError);
|
r.onerror = ev => rej(ev.target.error || new Error('put error'));
|
||||||
try {
|
});
|
||||||
await localforage.setItem(THREADS_KEY, arr);
|
}
|
||||||
} catch (err) {
|
|
||||||
throw err;
|
async function idbGetThreads() {
|
||||||
}
|
const rec = await idbGetRaw(THREADS_KEY).catch(err => { throw err; });
|
||||||
|
if (!rec) return [];
|
||||||
|
return Array.isArray(rec.value) ? rec.value : [];
|
||||||
|
}
|
||||||
|
async function idbWriteThreads(arr) {
|
||||||
|
await idbPutRaw(THREADS_KEY, arr);
|
||||||
}
|
}
|
||||||
|
|
||||||
// pick last thread heuristic: newest updatedAt
|
|
||||||
function pickLastThread(threads) {
|
function pickLastThread(threads) {
|
||||||
if (!threads || threads.length === 0) return null;
|
if (!threads || threads.length === 0) return null;
|
||||||
const copy = [...threads].sort((a,b) => (b.updatedAt||0) - (a.updatedAt||0));
|
const sorted = [...threads].sort((a,b) => (b.updatedAt||0) - (a.updatedAt||0));
|
||||||
return copy[0] || null;
|
return sorted[0];
|
||||||
}
|
}
|
||||||
|
|
||||||
function upsertAssistantInThreadObj(threadObj, streamId, text) {
|
function upsertAssistantInThreadObj(threadObj, streamId, text) {
|
||||||
@@ -69,18 +67,17 @@ function upsertAssistantInThreadObj(threadObj, streamId, text) {
|
|||||||
const m = threadObj.messages[i];
|
const m = threadObj.messages[i];
|
||||||
if (m && m.sw_streamId === streamId) {
|
if (m && m.sw_streamId === streamId) {
|
||||||
m.content = text;
|
m.content = text;
|
||||||
m.contentParts = [{type:'text', text}];
|
m.contentParts = [{ type:'text', text }];
|
||||||
m.updatedAt = now();
|
m.updatedAt = now();
|
||||||
m._sw_savedAt = now();
|
m._sw_savedAt = now();
|
||||||
return threadObj;
|
return threadObj;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// append
|
|
||||||
const msg = {
|
const msg = {
|
||||||
id: 'swmsg-' + gid(),
|
id: 'swmsg-' + gid(),
|
||||||
role: 'assistant',
|
role: 'assistant',
|
||||||
content: text,
|
content: text,
|
||||||
contentParts: [{type:'text', text}],
|
contentParts: [{ type:'text', text }],
|
||||||
kind: 'assistant',
|
kind: 'assistant',
|
||||||
sw_saved: true,
|
sw_saved: true,
|
||||||
sw_streamId: streamId,
|
sw_streamId: streamId,
|
||||||
@@ -92,80 +89,68 @@ function upsertAssistantInThreadObj(threadObj, streamId, text) {
|
|||||||
return threadObj;
|
return threadObj;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function safeFlushLastThread(streamId, accumulated, meta = {}) {
|
||||||
|
const threads = await idbGetThreads();
|
||||||
|
let thread = pickLastThread(threads);
|
||||||
|
const ts = now();
|
||||||
|
if (!thread) {
|
||||||
|
thread = { id: 'sw-thread-' + gid(), title: 'Missed while backgrounded', pinned:false, updatedAt: ts, messages: [] };
|
||||||
|
threads.unshift(thread);
|
||||||
|
}
|
||||||
|
upsertAssistantInThreadObj(thread, streamId, accumulated);
|
||||||
|
await idbWriteThreads(threads);
|
||||||
|
return { ok:true, threadId: thread.id };
|
||||||
|
}
|
||||||
|
|
||||||
async function broadcast(msg) {
|
async function broadcast(msg) {
|
||||||
try {
|
try {
|
||||||
const cl = await self.clients.matchAll({ includeUncontrolled: true, type: 'window' });
|
const cl = await self.clients.matchAll({ includeUncontrolled: true, type: 'window' });
|
||||||
for (const c of cl) {
|
for (const c of cl) {
|
||||||
try { c.postMessage(msg); } catch(e) {}
|
try { c.postMessage(msg); } catch(_) {}
|
||||||
}
|
}
|
||||||
} catch(e) {}
|
} catch(_) {}
|
||||||
}
|
|
||||||
|
|
||||||
function logDebug(text) { // also broadcast small logs
|
|
||||||
console.log('[sw-debug]', text);
|
|
||||||
broadcast({ type: 'sw-debug-log', ts: now(), text: String(text) });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/* lifecycle */
|
/* lifecycle */
|
||||||
self.addEventListener('install', (ev) => { self.skipWaiting(); });
|
self.addEventListener('install', ev => self.skipWaiting());
|
||||||
self.addEventListener('activate', (ev) => { ev.waitUntil(self.clients.claim()); });
|
self.addEventListener('activate', ev => ev.waitUntil(self.clients.claim()));
|
||||||
|
|
||||||
/* fetch handler: tee, accumulate, and repeatedly overwrite last thread */
|
/* fetch handler: tee + continuous overwrite */
|
||||||
self.addEventListener('fetch', (event) => {
|
self.addEventListener('fetch', event => {
|
||||||
try {
|
try {
|
||||||
const url = String(event.request.url || '');
|
const url = String(event.request.url || '');
|
||||||
if (!url.includes(TARGET_SUBSTRING)) return; // not target
|
if (!url.includes(TARGET_SUBSTRING)) return;
|
||||||
|
|
||||||
event.respondWith((async () => {
|
event.respondWith((async () => {
|
||||||
const upstream = await fetch(event.request);
|
const upstream = await fetch(event.request);
|
||||||
|
|
||||||
if (!upstream || !upstream.body) return upstream;
|
if (!upstream || !upstream.body) return upstream;
|
||||||
|
|
||||||
const streamId = 'sw-' + gid();
|
const streamId = 'sw-' + gid();
|
||||||
const meta = { url, startedAt: now(), bytes: 0, status: 'started' };
|
const meta = { url, startedAt: now(), bytes: 0, status: 'started' };
|
||||||
state.totalIntercepted = (state.totalIntercepted || 0) + 1;
|
|
||||||
state.activeStreams[streamId] = meta;
|
|
||||||
broadcast({ type: 'sw-intercept-start', streamId, meta });
|
broadcast({ type: 'sw-intercept-start', streamId, meta });
|
||||||
|
|
||||||
const [clientStream, swStream] = upstream.body.tee();
|
const [clientStream, swStream] = upstream.body.tee();
|
||||||
|
|
||||||
// save task
|
|
||||||
const savePromise = (async () => {
|
const savePromise = (async () => {
|
||||||
const reader = swStream.getReader();
|
const reader = swStream.getReader();
|
||||||
const decoder = new TextDecoder('utf-8');
|
const decoder = new TextDecoder('utf-8');
|
||||||
let accumulated = '';
|
let accumulated = '';
|
||||||
let sinceLastSaveBytes = 0;
|
let sinceSaveBytes = 0;
|
||||||
let lastSaveAt = 0;
|
let lastSaveAt = 0;
|
||||||
let lastBroadcastAt = 0;
|
let lastBroadcastAt = 0;
|
||||||
|
|
||||||
async function flushToLastThread(force = false) {
|
async function maybeFlush(force=false) {
|
||||||
try {
|
try {
|
||||||
const nowMs = now();
|
const nowMs = now();
|
||||||
if (!force && sinceLastSaveBytes < SAVE_BYTES_THRESHOLD && (nowMs - lastSaveAt) < SAVE_TIME_THRESHOLD) return;
|
if (!force && sinceSaveBytes < SAVE_BYTES_THRESHOLD && (nowMs - lastSaveAt) < SAVE_TIME_THRESHOLD) return;
|
||||||
if (!localforageAvailable) {
|
await safeFlushLastThread(streamId, accumulated, { bytes: meta.bytes });
|
||||||
logDebug('flushToLastThread: localforage not available: ' + lfLoadError);
|
sinceSaveBytes = 0;
|
||||||
return;
|
|
||||||
}
|
|
||||||
const threads = await safeReadThreads();
|
|
||||||
let thread = pickLastThread(threads);
|
|
||||||
if (!thread) {
|
|
||||||
thread = { id: 'sw-thread-' + gid(), title: 'Missed while backgrounded', pinned:false, updatedAt: nowMs, messages: [] };
|
|
||||||
threads.unshift(thread);
|
|
||||||
logDebug('flush: created fallback thread ' + thread.id);
|
|
||||||
}
|
|
||||||
upsertAssistantInThreadObj(thread, streamId, accumulated);
|
|
||||||
// write back (overwrite entire array)
|
|
||||||
await safeWriteThreads(threads);
|
|
||||||
sinceLastSaveBytes = 0;
|
|
||||||
lastSaveAt = nowMs;
|
lastSaveAt = nowMs;
|
||||||
// throttle broadcasts
|
if (nowMs - lastBroadcastAt > BROADCAST_THROTTLE_MS) {
|
||||||
const now2 = Date.now();
|
lastBroadcastAt = nowMs;
|
||||||
if (now2 - lastBroadcastAt > BROADCAST_THROTTLE_MS) {
|
broadcast({ type: 'sw-intercept-progress', streamId, meta: { bytes: meta.bytes, savedAt: lastSaveAt, snippet: accumulated.slice(-1024) }});
|
||||||
lastBroadcastAt = now2;
|
|
||||||
broadcast({ type: 'sw-intercept-progress', streamId, meta: { bytes: meta.bytes, savedAt: lastSaveAt, snippet: accumulated.slice(-1024) } });
|
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
logDebug('flushToLastThread error: ' + (err && err.message ? err.message : String(err)));
|
broadcast({ type: 'sw-intercept-error', streamId, meta: { error: String(err && err.message ? err.message : err) }});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -173,188 +158,111 @@ self.addEventListener('fetch', (event) => {
|
|||||||
while (true) {
|
while (true) {
|
||||||
const { value, done } = await reader.read();
|
const { value, done } = await reader.read();
|
||||||
if (done) break;
|
if (done) break;
|
||||||
let chunkText = '';
|
let chunk = '';
|
||||||
try { chunkText = decoder.decode(value, { stream: true }); } catch(e) { try { chunkText = String(value); } catch(_) { chunkText = ''; } }
|
try { chunk = decoder.decode(value, { stream: true }); } catch (e) { chunk = ''; }
|
||||||
accumulated += chunkText;
|
accumulated += chunk;
|
||||||
const bytes = value ? (value.byteLength || 0) : chunkText.length;
|
const bytes = value ? (value.byteLength || 0) : chunk.length;
|
||||||
meta.bytes += bytes;
|
meta.bytes += bytes;
|
||||||
meta.lastProgressAt = now();
|
sinceSaveBytes += bytes;
|
||||||
sinceLastSaveBytes += bytes;
|
await maybeFlush(false);
|
||||||
// flush if thresholds met
|
|
||||||
await flushToLastThread(false);
|
|
||||||
}
|
}
|
||||||
|
await maybeFlush(true);
|
||||||
// final flush
|
|
||||||
await flushToLastThread(true);
|
|
||||||
|
|
||||||
// finalize
|
|
||||||
meta.status = 'finished';
|
meta.status = 'finished';
|
||||||
meta.endedAt = now();
|
meta.endedAt = now();
|
||||||
state.lastStreamSummary = { streamId, url: meta.url, startedAt: meta.startedAt, endedAt: meta.endedAt, totalBytes: meta.bytes };
|
broadcast({ type: 'sw-intercept-end', streamId, meta: { totalBytes: meta.bytes, endedAt: meta.endedAt }});
|
||||||
delete state.activeStreams[streamId];
|
|
||||||
broadcast({ type: 'sw-intercept-end', streamId, meta: { totalBytes: meta.bytes, endedAt: meta.endedAt } });
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
meta.status = 'error';
|
meta.status = 'error';
|
||||||
meta.error = String(err && err.message ? err.message : err);
|
meta.error = String(err && err.message ? err.message : err);
|
||||||
delete state.activeStreams[streamId];
|
broadcast({ type: 'sw-intercept-error', streamId, meta: { error: meta.error }});
|
||||||
broadcast({ type: 'sw-intercept-error', streamId, meta: { error: meta.error } });
|
|
||||||
logDebug('savePromise error: ' + meta.error);
|
|
||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
|
|
||||||
event.waitUntil(savePromise);
|
event.waitUntil(savePromise);
|
||||||
|
|
||||||
return new Response(clientStream, {
|
return new Response(clientStream, { status: upstream.status, statusText: upstream.statusText, headers: upstream.headers });
|
||||||
status: upstream.status,
|
|
||||||
statusText: upstream.statusText,
|
|
||||||
headers: upstream.headers
|
|
||||||
});
|
|
||||||
})());
|
})());
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
logDebug('fetch handler error: ' + (err && err.message ? err.message : String(err)));
|
broadcast({ type: 'sw-debug', text: 'fetch handler error: ' + String(err && err.message ? err.message : err) });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
/* Message handler: PING, PING_STATUS, TEST_WRITE, CHECK_LF, LIST_SW_SAVED, CLEAR_TESTS */
|
/* messages: PING, PING_STATUS, TEST_WRITE, READ_KEY, LIST_SW_SAVED */
|
||||||
self.addEventListener('message', (event) => {
|
self.addEventListener('message', (event) => {
|
||||||
const data = event.data || {};
|
const data = event.data || {};
|
||||||
try {
|
(async () => {
|
||||||
if (data && data.type === 'PING') {
|
try {
|
||||||
if (event.ports && event.ports[0]) {
|
if (data.type === 'PING') {
|
||||||
event.ports[0].postMessage({ type: 'PONG', ts: now(), ok: true });
|
if (event.ports && event.ports[0]) event.ports[0].postMessage({ type:'PONG', ts: now(), ok:true });
|
||||||
} else if (event.source && typeof event.source.postMessage === 'function') {
|
else broadcast({ type:'PONG', ts: now(), ok:true });
|
||||||
try { event.source.postMessage({ type: 'PONG', ts: now(), ok: true }); } catch(e) {}
|
return;
|
||||||
} else {
|
|
||||||
broadcast({ type: 'PONG', ts: now(), ok: true });
|
|
||||||
}
|
}
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (data && data.type === 'PING_STATUS') {
|
if (data.type === 'PING_STATUS') {
|
||||||
const reply = {
|
const reply = { type:'PONG_STATUS', ts: now() };
|
||||||
type: 'PONG_STATUS',
|
if (event.ports && event.ports[0]) event.ports[0].postMessage(reply);
|
||||||
ts: now(),
|
else broadcast(reply);
|
||||||
totalIntercepted: state.totalIntercepted || 0,
|
return;
|
||||||
activeStreams: Object.entries(state.activeStreams).map(([id,m]) => ({ streamId: id, url: m.url, bytes: m.bytes, status: m.status, startedAt: m.startedAt })),
|
}
|
||||||
lastStreamSummary: state.lastStreamSummary || null,
|
|
||||||
lfAvailable: localforageAvailable,
|
|
||||||
lfLoadError: lfLoadError
|
|
||||||
};
|
|
||||||
if (event.ports && event.ports[0]) event.ports[0].postMessage(reply);
|
|
||||||
else if (event.source && event.source.postMessage) event.source.postMessage(reply);
|
|
||||||
else broadcast(reply);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (data && data.type === 'TEST_WRITE') {
|
if (data.type === 'TEST_WRITE') {
|
||||||
(async () => {
|
|
||||||
if (!localforageAvailable) {
|
|
||||||
const res = { type:'TEST_WRITE_RESULT', ok:false, error: 'localforage not available: ' + lfLoadError };
|
|
||||||
if (event.ports && event.ports[0]) event.ports[0].postMessage(res); else (event.source && event.source.postMessage ? event.source.postMessage(res) : broadcast(res));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
try {
|
try {
|
||||||
const threads = await safeReadThreads();
|
const threads = await idbGetThreads();
|
||||||
const tid = 'sw-test-' + gid();
|
const tid = 'sw-test-' + gid();
|
||||||
const nowMs = now();
|
const nowMs = now();
|
||||||
const testThread = {
|
const testThread = { id: tid, title: 'SW test ' + new Date(nowMs).toISOString(), pinned:false, updatedAt: nowMs, messages: [ { id:'swtest-'+gid(),role:'assistant',content:'sw test write @'+new Date(nowMs).toISOString(), contentParts:[{type:'text',text:'sw test write'}], createdAt: nowMs, updatedAt: nowMs } ]};
|
||||||
id: tid,
|
|
||||||
title: 'SW test thread ' + nowMs,
|
|
||||||
pinned: false,
|
|
||||||
updatedAt: nowMs,
|
|
||||||
messages: [
|
|
||||||
{ id: 'swtestmsg-' + gid(), role: 'assistant', content: 'sw test write @' + new Date(nowMs).toISOString(), contentParts: [{type:'text',text:'sw test write @' + new Date(nowMs).toISOString()}], createdAt: nowMs, updatedAt: nowMs }
|
|
||||||
]
|
|
||||||
};
|
|
||||||
threads.unshift(testThread);
|
threads.unshift(testThread);
|
||||||
await safeWriteThreads(threads);
|
await idbWriteThreads(threads);
|
||||||
state.debugWrites = (state.debugWrites||[]).concat(tid);
|
const res = { type:'TEST_WRITE_RESULT', ok:true, tid };
|
||||||
const res = { type:'TEST_WRITE_RESULT', ok:true, tid, now: nowMs };
|
if (event.ports && event.ports[0]) event.ports[0].postMessage(res);
|
||||||
if (event.ports && event.ports[0]) event.ports[0].postMessage(res); else (event.source && event.source.postMessage ? event.source.postMessage(res) : broadcast(res));
|
else broadcast(res);
|
||||||
logDebug('TEST_WRITE created ' + tid);
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const res = { type:'TEST_WRITE_RESULT', ok:false, error: String(err && err.message ? err.message : err) };
|
const res = { type:'TEST_WRITE_RESULT', ok:false, error: String(err && err.message ? err.message : err) };
|
||||||
if (event.ports && event.ports[0]) event.ports[0].postMessage(res); else (event.source && event.source.postMessage ? event.source.postMessage(res) : broadcast(res));
|
if (event.ports && event.ports[0]) event.ports[0].postMessage(res);
|
||||||
logDebug('TEST_WRITE error: ' + res.error);
|
else broadcast(res);
|
||||||
}
|
}
|
||||||
})();
|
return;
|
||||||
return;
|
}
|
||||||
}
|
|
||||||
|
|
||||||
if (data && data.type === 'CHECK_LF') {
|
if (data.type === 'READ_KEY') {
|
||||||
(async () => {
|
const key = data.key || THREADS_KEY;
|
||||||
if (!localforageAvailable) {
|
|
||||||
const res = { type:'CHECK_LF_RESULT', ok:false, error: 'localforage not available: ' + lfLoadError };
|
|
||||||
if (event.ports && event.ports[0]) event.ports[0].postMessage(res); else (event.source && event.source.postMessage ? event.source.postMessage(res) : broadcast(res));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
try {
|
try {
|
||||||
const threads = await safeReadThreads();
|
const rec = await idbGetRaw(key);
|
||||||
const res = { type:'CHECK_LF_RESULT', ok:true, threadsCount: Array.isArray(threads)?threads.length:0, sample: (threads && threads[0]) ? threads[0] : null };
|
const val = rec ? rec.value : null;
|
||||||
if (event.ports && event.ports[0]) event.ports[0].postMessage(res); else (event.source && event.source.postMessage ? event.source.postMessage(res) : broadcast(res));
|
const res = { type:'READ_KEY_RESULT', ok:true, key, value: val };
|
||||||
logDebug('CHECK_LF returned ' + (Array.isArray(threads)?threads.length:'?') + ' threads');
|
if (event.ports && event.ports[0]) event.ports[0].postMessage(res);
|
||||||
|
else broadcast(res);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const res = { type:'CHECK_LF_RESULT', ok:false, error: String(err && err.message ? err.message : err) };
|
const res = { type:'READ_KEY_RESULT', ok:false, key, error: String(err && err.message ? err.message : err) };
|
||||||
if (event.ports && event.ports[0]) event.ports[0].postMessage(res); else (event.source && event.source.postMessage ? event.source.postMessage(res) : broadcast(res));
|
if (event.ports && event.ports[0]) event.ports[0].postMessage(res);
|
||||||
logDebug('CHECK_LF error: ' + res.error);
|
else broadcast(res);
|
||||||
}
|
}
|
||||||
})();
|
return;
|
||||||
return;
|
}
|
||||||
}
|
|
||||||
|
|
||||||
if (data && data.type === 'LIST_SW_SAVED') {
|
if (data.type === 'LIST_SW_SAVED') {
|
||||||
(async () => {
|
|
||||||
if (!localforageAvailable) {
|
|
||||||
const res = { type:'LIST_SW_SAVED_RESULT', ok:false, error: 'localforage not available: ' + lfLoadError };
|
|
||||||
if (event.ports && event.ports[0]) event.ports[0].postMessage(res); else (event.source && event.source.postMessage ? event.source.postMessage(res) : broadcast(res));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
try {
|
try {
|
||||||
const threads = await safeReadThreads();
|
const threads = await idbGetThreads();
|
||||||
const found = [];
|
const found = [];
|
||||||
for (const t of (threads || [])) {
|
for (const t of (threads||[])) {
|
||||||
for (const m of (t.messages || [])) {
|
for (const m of (t.messages||[])) {
|
||||||
if (m && m.sw_streamId) found.push({ threadId: t.id, threadTitle: t.title, messageId: m.id, sw_streamId: m.sw_streamId, snippet: (m.content||'').slice(0,200), updatedAt: m.updatedAt });
|
if (m && m.sw_streamId) found.push({ threadId: t.id, messageId: m.id, sw_streamId: m.sw_streamId, snippet: (m.content||'').slice(0,200) });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const res = { type:'LIST_SW_SAVED_RESULT', ok:true, found };
|
const res = { type:'LIST_SW_SAVED_RESULT', ok:true, found };
|
||||||
if (event.ports && event.ports[0]) event.ports[0].postMessage(res); else (event.source && event.source.postMessage ? event.source.postMessage(res) : broadcast(res));
|
if (event.ports && event.ports[0]) event.ports[0].postMessage(res);
|
||||||
logDebug('LIST_SW_SAVED returned ' + found.length + ' messages');
|
else broadcast(res);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const res = { type:'LIST_SW_SAVED_RESULT', ok:false, error: String(err && err.message ? err.message : err) };
|
const res = { type:'LIST_SW_SAVED_RESULT', ok:false, error: String(err && err.message ? err.message : err) };
|
||||||
if (event.ports && event.ports[0]) event.ports[0].postMessage(res); else (event.source && event.source.postMessage ? event.source.postMessage(res) : broadcast(res));
|
if (event.ports && event.ports[0]) event.ports[0].postMessage(res);
|
||||||
logDebug('LIST_SW_SAVED error: ' + res.error);
|
else broadcast(res);
|
||||||
}
|
}
|
||||||
})();
|
return;
|
||||||
return;
|
}
|
||||||
}
|
|
||||||
|
|
||||||
if (data && data.type === 'CLEAR_TESTS') {
|
} catch (err) {
|
||||||
(async () => {
|
const r = { type:'SW_ERROR', error: String(err && err.message ? err.message : err) };
|
||||||
if (!localforageAvailable) {
|
if (event.ports && event.ports[0]) event.ports[0].postMessage(r);
|
||||||
const res = { type:'CLEAR_TESTS_RESULT', ok:false, error: 'localforage not available: ' + lfLoadError };
|
else broadcast(r);
|
||||||
if (event.ports && event.ports[0]) event.ports[0].postMessage(res); else broadcast(res);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
const threads = await safeReadThreads();
|
|
||||||
const before = threads.length;
|
|
||||||
const cleaned = threads.filter(t => !(t.id && (String(t.id).startsWith('sw-test-') || String(t.id).startsWith('sw-thread-') || state.debugWrites.includes(t.id))));
|
|
||||||
await safeWriteThreads(cleaned);
|
|
||||||
const removed = before - cleaned.length;
|
|
||||||
state.debugWrites = [];
|
|
||||||
const res = { type:'CLEAR_TESTS_RESULT', ok:true, removed };
|
|
||||||
if (event.ports && event.ports[0]) event.ports[0].postMessage(res); else broadcast(res);
|
|
||||||
logDebug('CLEAR_TESTS removed ' + removed);
|
|
||||||
} catch (err) {
|
|
||||||
const res = { type:'CLEAR_TESTS_RESULT', ok:false, error: String(err && err.message ? err.message : err) };
|
|
||||||
if (event.ports && event.ports[0]) event.ports[0].postMessage(res); else broadcast(res);
|
|
||||||
}
|
|
||||||
})();
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
})();
|
||||||
} catch (err) {
|
|
||||||
logDebug('message handler error: ' + (err && err.message ? err.message : String(err)));
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user