okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-0213-guidata (final 1d5096beb) into f-0213-int85269ca15

main
3.3 KiB45 linesraw
1/** A stand-in for the host's /api/chats routes that is backed by the real chat store (server/chat-store.mjs), for tests of the page's side. */
2import { ChatStoreError, storeFailure } from '../../server/chat-store.mjs';
3
4/** A transport (the page's ChatTransport) straight over a chat store, with a way to make the host go away. */
5export function storeTransport(store, TransportError, state = { offline: false }) {
6  const guard = async (work) => {
7    if (state.offline) throw new TransportError('The host did not answer.', 0, 'offline', true);
8    try { return await work(); }
9    catch (e) { const f = e instanceof TransportError ? e : storeFailure(e); throw f instanceof TransportError ? f : new TransportError(f.message, f.status, f.code); }
10  };
11  return {
12    state,
13    list: () => guard(async () => store.list()),
14    get: (id) => guard(async () => { const text = await store.read(id); if (text === null) return null; const d = JSON.parse(text); return { rev: d.rev, session: d.session }; }),
15    put: (id, text, baseRev) => guard(() => store.save(id, text, { baseRev })),
16    remove: (id) => guard(async () => { await store.remove(id); }),
17    importMany: (sessions) => guard(() => store.importMany(sessions)),
18  };
19}
20
21/** Install a global fetch that answers /api/chats* from the store; every other path is refused like an unreachable host. */
22export function installFakeHostFetch(store, { events = [] } = {}) {
23  const calls = [];
24  const previous = globalThis.fetch;
25  globalThis.fetch = async (url, init = {}) => {
26    const path = String(url).replace(/^https?:\/\/[^/]+/, '');
27    const method = init.method ?? 'GET';
28    const headers = Object.fromEntries(Object.entries(init.headers ?? {}).map(([k, v]) => [k.toLowerCase(), v]));
29    calls.push({ method, path, headers });
30    const reply = (status, body) => ({ ok: status < 200 || status >= 300 ? false : true, status, json: async () => (typeof body === 'string' ? JSON.parse(body) : body), text: async () => (typeof body === 'string' ? body : JSON.stringify(body)) });
31    const m = /^\/api\/chats(?:\/([^/?]+))?/.exec(path);
32    if (!m) throw new TypeError('fetch failed');
33    if (!headers['x-strata-client']) return reply(403, { error: 'Not allowed.' });
34    const id = m[1] ? decodeURIComponent(m[1]) : null;
35    try {
36      if (!id && method === 'GET') return reply(200, store.list());
37      if (id === 'import' && method === 'POST') { const r = await store.importMany(JSON.parse(init.body).sessions); return reply(200, r); }
38      if (id && method === 'GET') { const t = await store.read(id); return t === null ? reply(404, { error: 'No such chat.', code: 'not-found' }) : reply(200, t); }
39      if (id && method === 'PUT') { const base = headers['x-strata-base-rev']; const r = await store.save(id, init.body, { baseRev: base !== undefined ? Number(base) : null }); events.push({ id, rev: r.rev, from: headers['x-strata-window'] }); return reply(200, r); }
40      if (id && method === 'DELETE') { const r = await store.remove(id); events.push({ id, deleted: true, from: headers['x-strata-window'] }); return reply(200, r); }
41    } catch (e) { const f = e instanceof ChatStoreError ? e : storeFailure(e); return reply(f.status, { error: f.message, code: f.code }); }
42    return reply(405, { error: 'Method not allowed.' });
43  };
44  return { calls, restore() { globalThis.fetch = previous; } };
45}