diff --git a/packages/storage/src/index.ts b/packages/storage/src/index.ts index e0c368f..2bb3f9c 100644 --- a/packages/storage/src/index.ts +++ b/packages/storage/src/index.ts @@ -2,7 +2,7 @@ * The ONLY module that touches IndexedDB (CLAUDE.md §2). The database `rosea` and its * stores are listed in CLAUDE.md §4; each store arrives with the feature that writes * it. So far: `profile` (the sunset place, sunset-place.md), `events` (the rose's care - * log, rose.md) and `keys` (the identity, rose.md). + * log, rose.md, and her opened petals, day-sentence.md) and `keys` (the identity, rose.md). * * The database name changes together with the product name (CLAUDE.md preamble). * Everything written is a fresh plain copy that passed a shape check: a Svelte 5 @@ -10,9 +10,9 @@ * may enter a log that is never edited. */ import Dexie, { type DexieOptions, type Table } from 'dexie'; -import { newCare, type NamedPlace } from '@rosea/engine'; +import { newCare, newOpened, type NamedPlace } from '@rosea/engine'; import { isIdentity, type Identity } from '@rosea/identity'; -import { DATABASE_NAME, type CareEvent } from '@rosea/schema'; +import { DATABASE_NAME, type CareEvent, type SentenceOpened } from '@rosea/schema'; export { DATABASE_NAME }; @@ -37,14 +37,19 @@ const SUNSET_PLACE = 'sunsetPlace'; const SELF = 'self'; const PAST_KEYS = 'pastKeys'; -/** The file a rose is saved to and brought back from (keep-her-safe.md K4). Never the private key, never the town. */ +/** + * The file a rose is saved to and brought back from (keep-her-safe.md K4). Never the + * private key, never the town. Version 2 adds her opened petals (day-sentence.md P7); + * a version 1 file is still read, as one with none. + */ export const ROSE_FILE_FORMAT = 'rosea-rose'; export interface RoseFile { readonly format: typeof ROSE_FILE_FORMAT; - readonly version: 1; + readonly version: 2; /** The keys that have named her, the one she had when saved first. Public keys only. */ readonly keys: readonly string[]; readonly events: readonly CareEvent[]; + readonly opened: readonly SentenceOpened[]; } export interface Storage { @@ -55,6 +60,10 @@ export interface Storage { appendCare(event: CareEvent): Promise; /** The whole care log, in the order it was written. */ loadCare(): Promise; + /** Appends one opened petal (day-sentence.md P6). Never edited. */ + appendOpened(event: SentenceOpened): Promise; + /** Every opened petal, in the order written. */ + loadOpened(): Promise; /** * The player's identity: the one already kept, or `fresh` kept now. With two tabs * racing, both get the same one: the first write wins and the other is dropped. @@ -69,7 +78,7 @@ export interface Storage { * Brings a saved rose back: her keys join the past keys and every act not already * here is appended. Nothing is edited or removed. Rejects a file that is not a rose. */ - importRose(file: unknown, currentKey: string): Promise<{ readonly added: number }>; + importRose(file: unknown, currentKey: string): Promise<{ readonly added: number; readonly petals: number }>; close(): void; } @@ -118,21 +127,52 @@ export function asCareEvent(value: unknown): CareEvent | null { return isWater ? { ...base, amount: v['amount'] as number } : base; } +const OPENED_KEYS = new Set(['kind', 'ts', 'localDay', 'from', 'messageId', 'clientVersion']); + +/** The sentence-opened contract (sentence-opened.schema.json), checked by hand for the same reason as care. */ +export function asSentenceOpened(value: unknown): SentenceOpened | null { + if (typeof value !== 'object' || value === null) return null; + const v = value as Record; + if (Object.keys(v).some((k) => !OPENED_KEYS.has(k))) return null; + if (v['kind'] !== 'sentence-opened' || !Number.isSafeInteger(v['ts']) || (v['ts'] as number) < 0) return null; + if (!matches(v['localDay'], /^\d{4}-\d{2}-\d{2}$/) || !matches(v['from'], KEY)) return null; + const messageId = v['messageId']; + if (!(matches(messageId, /^[a-z0-9]+(-[a-z0-9]+)*$/) && messageId.length <= 64)) return null; + if (!matches(v['clientVersion'], /^\d+\.\d+\.\d+$/)) return null; + return { kind: 'sentence-opened', ts: v['ts'] as number, localDay: v['localDay'], from: v['from'], messageId, clientVersion: v['clientVersion'] }; +} + +/** Kinds the log holds besides care, each read by its own loader: not broken entries. */ +const OTHER_KINDS: ReadonlySet = new Set(['sentence-opened']); +const kindOf = (event: unknown): unknown => (typeof event === 'object' && event !== null ? (event as { kind?: unknown }).kind : undefined); + const isKeyList = (x: unknown): x is string[] => Array.isArray(x) && x.every((k) => matches(k, KEY)); -/** The shape check for a saved rose. Every act must pass the care event contract. */ +/** Every item through `check`, or null if any one fails it. */ +function every(items: unknown, check: (x: unknown) => T | null): T[] | null { + if (!Array.isArray(items)) return null; + const out: T[] = []; + for (const item of items as unknown[]) { + const plain = check(item); + if (plain === null) return null; + out.push(plain); + } + return out; +} + +/** + * The shape check for a saved rose, version 1 or 2. Every act must pass the care + * event contract and every petal the sentence-opened one. It answers as version 2. + */ export function asRoseFile(value: unknown): RoseFile | null { if (typeof value !== 'object' || value === null) return null; const v = value as Record; - if (v['format'] !== ROSE_FILE_FORMAT || v['version'] !== 1) return null; - if (!isKeyList(v['keys']) || v['keys'].length === 0 || !Array.isArray(v['events'])) return null; - const events: CareEvent[] = []; - for (const e of v['events'] as unknown[]) { - const plain = asCareEvent(e); - if (plain === null) return null; - events.push(plain); - } - return { format: ROSE_FILE_FORMAT, version: 1, keys: [...new Set(v['keys'])], events }; + if (v['format'] !== ROSE_FILE_FORMAT || (v['version'] !== 1 && v['version'] !== 2)) return null; + if (!isKeyList(v['keys']) || v['keys'].length === 0) return null; + const events = every(v['events'], asCareEvent); + const opened = v['version'] === 1 ? ('opened' in v ? null : []) : every(v['opened'], asSentenceOpened); + if (events === null || opened === null) return null; + return { format: ROSE_FILE_FORMAT, version: 2, keys: [...new Set(v['keys'])], events, opened }; } class RoseaDatabase extends Dexie { @@ -181,6 +221,7 @@ export function openStorage(options?: DexieOptions): Storage { const rows = await db.events.orderBy('id').toArray(); const events: CareEvent[] = []; for (const row of rows) { + if (OTHER_KINDS.has(kindOf(row.event))) continue; const e = asCareEvent(row.event); // A broken entry is said out loud and left in place: the log is never edited. if (e === null) console.warn('storage: a care event has an unknown shape; it is skipped, not removed', row); @@ -188,6 +229,22 @@ export function openStorage(options?: DexieOptions): Storage { } return events; }, + async appendOpened(event) { + const plain = asSentenceOpened(event); + if (plain === null) throw new TypeError('storage: refusing to append an opened petal of an unknown shape'); + await db.events.add({ event: plain }); + }, + async loadOpened() { + const rows = await db.events.orderBy('id').toArray(); + const opened: SentenceOpened[] = []; + for (const row of rows) { + if (kindOf(row.event) !== 'sentence-opened') continue; + const e = asSentenceOpened(row.event); + if (e === null) console.warn('storage: an opened petal has an unknown shape; it is skipped, not removed', row); + else opened.push(e); + } + return opened; + }, async keepIdentity(fresh) { if (!isIdentity(fresh)) throw new TypeError('storage: refusing to keep an identity of an unknown shape'); return db.transaction('rw', db.keys, async () => { @@ -211,7 +268,10 @@ export function openStorage(options?: DexieOptions): Storage { }, async exportRose(currentKey) { const past = await api.loadPastKeys(); - return { format: ROSE_FILE_FORMAT, version: 1, keys: [...new Set([currentKey, ...past])], events: await api.loadCare() }; + return { + format: ROSE_FILE_FORMAT, version: 2, keys: [...new Set([currentKey, ...past])], + events: await api.loadCare(), opened: await api.loadOpened() + }; }, async importRose(file, currentKey) { const rose = asRoseFile(file); @@ -221,10 +281,13 @@ export function openStorage(options?: DexieOptions): Storage { const past = isKeyList(row?.value) ? row.value : []; const keys = [...new Set([...past, ...rose.keys])].filter((k) => k !== currentKey); await db.profile.put({ key: PAST_KEYS, value: keys }); - const existing = (await db.events.orderBy('id').toArray()).map((r) => asCareEvent(r.event)).filter((e): e is CareEvent => e !== null); + const rows = (await db.events.orderBy('id').toArray()).map((r) => r.event); + const existing = rows.map(asCareEvent).filter((e): e is CareEvent => e !== null); + const existingOpened = rows.map(asSentenceOpened).filter((e): e is SentenceOpened => e !== null); const added = newCare(existing, rose.events); - await db.events.bulkAdd(added.map((event) => ({ event }))); - return { added: added.length }; + const petals = newOpened(existingOpened, rose.opened); + await db.events.bulkAdd([...added, ...petals].map((event) => ({ event }))); + return { added: added.length, petals: petals.length }; }); }, close() { diff --git a/packages/storage/test/opened.test.ts b/packages/storage/test/opened.test.ts new file mode 100644 index 0000000..4d5715f --- /dev/null +++ b/packages/storage/test/opened.test.ts @@ -0,0 +1,76 @@ +import type { CareEvent, SentenceOpened } from '@rosea/schema'; +import { validateSentenceOpened } from '@rosea/schema/validate'; +import Dexie from 'dexie'; +import { IDBFactory, IDBKeyRange } from 'fake-indexeddb'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { asSentenceOpened, openStorage, type Storage } from '../src/index.js'; + +const KEY = 'K'.repeat(87); +const petal: SentenceOpened = { kind: 'sentence-opened', ts: 1774944000000, localDay: '2026-03-31', from: KEY, messageId: 'ps-118-24', clientVersion: '0.1.0' }; +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 opened: Storage[] = []; +const open = (indexedDB: IDBFactory = new IDBFactory()): Storage => { + const s = openStorage({ indexedDB, IDBKeyRange }); + opened.push(s); + return s; +}; +afterEach(() => { + for (const s of opened.splice(0)) s.close(); + vi.restoreAllMocks(); +}); + +describe('opened petals (day-sentence.md P6)', () => { + it('are appended to the same log and come back in order, across a reopen', async () => { + const factory = new IDBFactory(); + const s = open(factory); + await s.appendOpened(petal); + await s.appendCare(weed); + await s.appendOpened(new Proxy({ ...petal, ts: petal.ts + 86_400_000, localDay: '2026-04-01' }, {})); + s.close(); + const again = open(factory); + expect(await again.loadOpened()).toEqual([petal, { ...petal, ts: petal.ts + 86_400_000, localDay: '2026-04-01' }]); + expect(await again.loadCare()).toEqual([weed]); + }); + + it('loading care passes over them quietly: they are not broken entries', async () => { + const s = open(); + await s.appendOpened(petal); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + expect(await s.loadCare()).toEqual([]); + expect(warn).not.toHaveBeenCalled(); + }); + + it('refuses text in place of an id, or anything else the contract refuses', async () => { + const s = open(); + for (const bad of [ + { ...petal, messageId: 'The LORD is my shepherd' }, + { ...petal, note: 'hello' }, + { ...petal, kind: 'care' }, + { ...petal, from: 'short' } + ]) { + await expect(s.appendOpened(bad as SentenceOpened)).rejects.toThrow(/unknown shape/); + } + expect(await s.loadOpened()).toEqual([]); + }); + + it('a broken one already in the log is skipped and said, never removed', async () => { + const factory = new IDBFactory(); + const s = open(factory); + await s.appendOpened(petal); + s.close(); + const raw = new Dexie('rosea', { indexedDB: factory, IDBKeyRange }); + raw.version(2).stores({ profile: 'key', events: '++id', keys: 'id' }); + await raw.table('events').add({ event: { kind: 'sentence-opened', messageId: 'Free words' } }); + raw.close(); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + expect(await open(factory).loadOpened()).toEqual([petal]); + expect(warn).toHaveBeenCalledOnce(); + }); + + it('the hand check agrees with the schema on every case above', () => { + for (const value of [petal, { ...petal, messageId: 'A sentence' }, { ...petal, note: 'x' }, { ...petal, ts: -1 }, { ...petal, ts: 1.5 }, { ...petal, localDay: '31.3.2026' }]) { + expect(asSentenceOpened(value) !== null, JSON.stringify(value)).toBe(validateSentenceOpened(value).ok); + } + }); +}); diff --git a/packages/storage/test/rose-file.test.ts b/packages/storage/test/rose-file.test.ts index e362664..9b80310 100644 --- a/packages/storage/test/rose-file.test.ts +++ b/packages/storage/test/rose-file.test.ts @@ -1,5 +1,5 @@ import { createIdentity } from '@rosea/identity'; -import type { CareEvent } from '@rosea/schema'; +import type { CareEvent, SentenceOpened } from '@rosea/schema'; import { IDBFactory, IDBKeyRange } from 'fake-indexeddb'; import { afterEach, describe, expect, it } from 'vitest'; import { asRoseFile, openStorage, ROSE_FILE_FORMAT, type Storage } from '../src/index.js'; @@ -11,6 +11,10 @@ const act = (to: string, ts: number): CareEvent => ({ trace: 'petal:rose', messageId: null, clientVersion: '0.1.0', amount: 0.5 }); +const petal = (from: string, ts: number): SentenceOpened => ({ + kind: 'sentence-opened', ts, localDay: '2026-03-01', from, messageId: 'ps-118-24', clientVersion: '0.1.0' +}); + const opened: Storage[] = []; const open = (indexedDB: IDBFactory = new IDBFactory()): Storage => { const s = openStorage({ indexedDB, IDBKeyRange }); @@ -28,14 +32,16 @@ describe('saving the rose to a file', () => { await s.keepIdentity(await createIdentity()); await s.saveSunsetPlace({ kind: 'town', town: { name: 'Brno', region: '', country: 'Czechia', lat: 49.2, lon: 16.61, timeZone: 'Europe/Prague' } }); await s.appendCare(act(OLD, 1)); + await s.appendOpened(petal(OLD, 2)); const file = await s.exportRose(OLD); - expect(file).toStrictEqual({ format: ROSE_FILE_FORMAT, version: 1, keys: [OLD], events: [act(OLD, 1)] }); + expect(file).toStrictEqual({ format: ROSE_FILE_FORMAT, version: 2, keys: [OLD], events: [act(OLD, 1)], opened: [petal(OLD, 2)] }); expect(JSON.stringify(file)).not.toMatch(/Brno|privateKey|CryptoKey/); }); it('survives a trip through JSON text unchanged', async () => { const s = open(); await s.appendCare(act(OLD, 1)); + await s.appendOpened(petal(OLD, 2)); const file = await s.exportRose(OLD); expect(asRoseFile(JSON.parse(JSON.stringify(file)))).toEqual(file); }); @@ -49,27 +55,48 @@ describe('bringing her back', () => { const file = JSON.parse(JSON.stringify(await old.exportRose(OLD))); const fresh = open(); - expect(await fresh.importRose(file, NEW)).toEqual({ added: 2 }); + expect(await fresh.importRose(file, NEW)).toEqual({ added: 2, petals: 0 }); expect(await fresh.loadPastKeys()).toEqual([OLD]); expect(await fresh.loadCare()).toEqual([act(OLD, 1), act(OLD, 2)]); }); + it('her opened petals come with her, so the next petal is the one she would have held (day-sentence.md P7)', async () => { + const old = open(); + await old.appendCare(act(OLD, 1)); + await old.appendOpened(petal(OLD, 2)); + const file = JSON.parse(JSON.stringify(await old.exportRose(OLD))); + const fresh = open(); + await fresh.appendOpened(petal(NEW, 9)); + expect(await fresh.importRose(file, NEW)).toEqual({ added: 1, petals: 1 }); + expect(await fresh.loadOpened()).toEqual([petal(NEW, 9), petal(OLD, 2)]); + }); + + it('a version 1 file, saved before petals existed, is still brought back', async () => { + const v1 = { format: ROSE_FILE_FORMAT, version: 1, keys: [OLD], events: [act(OLD, 1)] }; + const fresh = open(); + expect(await fresh.importRose(v1, NEW)).toEqual({ added: 1, petals: 0 }); + expect(await fresh.loadCare()).toEqual([act(OLD, 1)]); + }); + it('twice is the same as once, and the care given here meanwhile stays', async () => { const old = open(); await old.appendCare(act(OLD, 1)); + await old.appendOpened(petal(OLD, 2)); const file = await old.exportRose(OLD); const here = open(); await here.appendCare(act(NEW, 5)); await here.importRose(file, NEW); - expect(await here.importRose(file, NEW)).toEqual({ added: 0 }); + expect(await here.importRose(file, NEW)).toEqual({ added: 0, petals: 0 }); expect(await here.loadCare()).toEqual([act(NEW, 5), act(OLD, 1)]); + expect(await here.loadOpened()).toEqual([petal(OLD, 2)]); expect(await here.loadPastKeys()).toEqual([OLD]); }); it('a file saved on this very device adds nothing and does not list its own key as past', async () => { const s = open(); await s.appendCare(act(NEW, 1)); - expect(await s.importRose(await s.exportRose(NEW), NEW)).toEqual({ added: 0 }); + await s.appendOpened(petal(NEW, 2)); + expect(await s.importRose(await s.exportRose(NEW), NEW)).toEqual({ added: 0, petals: 0 }); expect(await s.loadPastKeys()).toEqual([]); }); @@ -79,6 +106,9 @@ describe('bringing her back', () => { for (const bad of [ null, 'rose', { format: 'other', version: 1, keys: [OLD], events: [] }, { format: ROSE_FILE_FORMAT, version: 2, keys: [OLD], events: [] }, + { format: ROSE_FILE_FORMAT, version: 3, keys: [OLD], events: [], opened: [] }, + { format: ROSE_FILE_FORMAT, version: 2, keys: [OLD], events: [], opened: [{ ...petal(OLD, 1), messageId: 'Free words' }] }, + { format: ROSE_FILE_FORMAT, version: 1, keys: [OLD], events: [], opened: [petal(OLD, 1)] }, { format: ROSE_FILE_FORMAT, version: 1, keys: [], events: [] }, { format: ROSE_FILE_FORMAT, version: 1, keys: ['short'], events: [] }, { format: ROSE_FILE_FORMAT, version: 1, keys: [OLD], events: [{ ...act(OLD, 1), note: 'hello' }] }