Files

121 lines
4.4 KiB
TypeScript

import type { CareEvent, SentenceOpened } from '@rosea/schema';
import { IDBFactory, IDBKeyRange } from 'fake-indexeddb';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { openStorage, ROSE_FILE_FORMAT, type Change, type Storage } from '../src/index.js';
const KEY = 'K'.repeat(87);
const OLD = 'O'.repeat(87);
const weed: CareEvent = { kind: 'care', ts: 1774944060000, localDay: '2026-03-31', from: KEY, to: KEY, act: 'weed', trace: 'petal:rose', messageId: null, clientVersion: '0.1.0' };
const petal: SentenceOpened = { kind: 'sentence-opened', ts: 1774944000000, localDay: '2026-03-31', from: KEY, messageId: 'ps-118-24', clientVersion: '0.1.0' };
const brno = { kind: 'town', town: { name: 'Brno', region: '', country: 'Czechia', lat: 49.2, lon: 16.61, timeZone: 'Europe/Prague' } } as const;
let channels = 0;
const opened: Storage[] = [];
/** Two tabs of one garden: one database, one channel, their own for this test. */
function twoTabs(): [Storage, Storage] {
const indexedDB = new IDBFactory();
const channel = `rosea-test-${++channels}`;
const tabs = [openStorage({ indexedDB, IDBKeyRange }, { channel }), openStorage({ indexedDB, IDBKeyRange }, { channel })] as [Storage, Storage];
opened.push(...tabs);
return tabs;
}
afterEach(() => {
for (const s of opened.splice(0)) s.close();
vi.unstubAllGlobals();
vi.restoreAllMocks();
});
/** Everything `tab` hears in the next `ms`. */
function hears(tab: Storage, ms = 150): Promise<Change[]> {
const heard: Change[] = [];
const stop = tab.onChange((what) => heard.push(what));
return new Promise((resolve) =>
setTimeout(() => {
stop();
resolve(heard);
}, ms)
);
}
describe('a write is announced to the other tabs (two-tabs.md W1)', () => {
it('care: the other tab hears "log", and reading then finds it', async () => {
const [a, b] = twoTabs();
let found: CareEvent[] = [];
const read = new Promise<void>((resolve) =>
b.onChange(async () => {
found = await b.loadCare();
resolve();
})
);
await a.appendCare(weed);
await read;
expect(found).toEqual([weed]);
});
it('a petal and a rose brought back are "log"; a town is "place"', async () => {
const [a, b] = twoTabs();
const heard = hears(b);
await a.appendOpened(petal);
await a.importRose({ format: ROSE_FILE_FORMAT, version: 2, keys: [OLD], events: [], opened: [] }, KEY);
await a.saveSunsetPlace(brno);
expect(await heard).toEqual(['log', 'log', 'place']);
});
it('a tab does not hear itself (W3)', async () => {
const [a] = twoTabs();
const heard = hears(a);
await a.appendCare(weed);
expect(await heard).toEqual([]);
});
it('a refused write announces nothing', async () => {
const [a, b] = twoTabs();
const heard = hears(b);
await expect(a.appendCare({ ...weed, note: 'x' } as CareEvent)).rejects.toThrow();
await expect(a.importRose('not a rose', KEY)).rejects.toThrow();
expect(await heard).toEqual([]);
});
it('a malformed message is ignored; a listener that throws does not stop the others', async () => {
const [, b] = twoTabs();
const raw = new BroadcastChannel(`rosea-test-${channels}`);
const error = vi.spyOn(console, 'error').mockImplementation(() => undefined);
b.onChange(() => {
throw new Error('a broken listener');
});
const heard = hears(b);
raw.postMessage({ what: 'log', data: 'anything' });
raw.postMessage('care');
raw.postMessage('place');
expect(await heard).toEqual(['place']);
expect(error).toHaveBeenCalledOnce();
raw.close();
});
it('after unsubscribing, or after close, nothing more is heard', async () => {
const [a, b] = twoTabs();
const calls: Change[] = [];
const stop = b.onChange((w) => calls.push(w));
stop();
await a.appendCare(weed);
b.close();
await a.appendCare({ ...weed, ts: weed.ts + 1 });
await new Promise((r) => setTimeout(r, 100));
expect(calls).toEqual([]);
});
});
describe('without a channel (W5)', () => {
it('storage works as before, and simply hears nothing', async () => {
vi.stubGlobal('BroadcastChannel', undefined);
const indexedDB = new IDBFactory();
const a = openStorage({ indexedDB, IDBKeyRange });
const b = openStorage({ indexedDB, IDBKeyRange });
opened.push(a, b);
const heard = hears(b);
await a.appendCare(weed);
expect(await b.loadCare()).toEqual([weed]);
expect(await heard).toEqual([]);
});
});