@alexsun-top/opencode-chat-room 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/queue.ts CHANGED
@@ -1,8 +1,11 @@
1
1
  import { createHash } from "node:crypto";
2
+ import { deletePendingAdmission, readPendingAdmission, savePendingAdmission } from "./receiver-state";
3
+ import { assertDeliveryLease } from "./session-delivery";
2
4
 
3
5
  export type QueueItem = {
4
6
  id?: string;
5
7
  senderId: string;
8
+ senderSessionID?: string;
6
9
  text: string;
7
10
  createdAt: number;
8
11
  };
@@ -10,7 +13,7 @@ export type QueueItem = {
10
13
  export type QueueBody = {
11
14
  id: string;
12
15
  prompt: { text: string };
13
- delivery: "queue";
16
+ delivery: "queue" | "steer";
14
17
  resume: true;
15
18
  };
16
19
 
@@ -21,53 +24,12 @@ export type PendingAdmission = {
21
24
  maxTs: number;
22
25
  capped: boolean;
23
26
  state: "pending" | "admitted";
27
+ items: QueueItem[];
24
28
  };
25
29
 
26
- type PendingEntry = {
27
- admission: PendingAdmission;
28
- expiresAt: number;
29
- };
30
-
31
- // ponytail: lazy expiry avoids one timer per admission; the hard cap keeps the
32
- // module-level map bounded even when no later queue activity triggers pruning.
33
30
  const PENDING_TTL_MS = 5 * 60_000;
34
- const MAX_PENDING_ADMISSIONS = 1024;
35
- const pending = new Map<string, PendingEntry>();
36
-
37
- function keyFor(sessionID: string, roomId: string): string {
38
- return `${sessionID}|${roomId}`;
39
- }
40
-
41
- function pruneExpired(now: number): void {
42
- for (const [key, entry] of pending) {
43
- if (entry.expiresAt <= now) {
44
- pending.delete(key);
45
- }
46
- }
47
- }
48
-
49
- function pendingEntry(key: string, now: number): PendingEntry | undefined {
50
- pruneExpired(now);
51
- return pending.get(key);
52
- }
53
-
54
- function rememberPending(
55
- key: string,
56
- admission: PendingAdmission,
57
- now: number,
58
- ): void {
59
- pending.delete(key);
60
- pending.set(key, {
61
- admission,
62
- expiresAt: now + PENDING_TTL_MS,
63
- });
64
- while (pending.size > MAX_PENDING_ADMISSIONS) {
65
- const oldest = pending.keys().next();
66
- if (oldest.done) {
67
- break;
68
- }
69
- pending.delete(oldest.value);
70
- }
31
+ function save(sessionID: string, roomID: string, admission: PendingAdmission, now: number): void {
32
+ savePendingAdmission(sessionID, roomID, admission, now + PENDING_TTL_MS, now);
71
33
  }
72
34
 
73
35
  export function queueAdmissionId(
@@ -94,7 +56,7 @@ export function pendingAdmission(
94
56
  sessionID: string,
95
57
  roomId: string,
96
58
  ): PendingAdmission | undefined {
97
- return pendingEntry(keyFor(sessionID, roomId), Date.now())?.admission;
59
+ return readPendingAdmission<PendingAdmission>(sessionID, roomId, Date.now());
98
60
  }
99
61
 
100
62
  export function getOrCreatePendingAdmission(
@@ -105,9 +67,8 @@ export function getOrCreatePendingAdmission(
105
67
  maxTs: number,
106
68
  capped: boolean,
107
69
  ): PendingAdmission {
108
- const key = keyFor(sessionID, roomId);
109
70
  const now = Date.now();
110
- const existing = pendingEntry(key, now)?.admission;
71
+ const existing = readPendingAdmission<PendingAdmission>(sessionID, roomId, now);
111
72
  if (
112
73
  existing &&
113
74
  (existing.state !== "admitted" || maxTs <= existing.maxTs)
@@ -121,9 +82,10 @@ export function getOrCreatePendingAdmission(
121
82
  maxTs,
122
83
  capped,
123
84
  state: "pending",
85
+ items: items.slice(-20).map((item) => ({ ...item })),
124
86
  };
125
87
  if (maxTs > 0) {
126
- rememberPending(key, admission, now);
88
+ save(sessionID, roomId, admission, now);
127
89
  }
128
90
  return admission;
129
91
  }
@@ -133,10 +95,10 @@ export function rejectPendingAdmission(
133
95
  roomId: string,
134
96
  admissionID: string,
135
97
  ): void {
136
- const key = keyFor(sessionID, roomId);
137
- const admission = pendingEntry(key, Date.now())?.admission;
98
+ assertDeliveryLease();
99
+ const admission = pendingAdmission(sessionID, roomId);
138
100
  if (admission?.state === "pending" && admission.id === admissionID) {
139
- pending.delete(key);
101
+ deletePendingAdmission(sessionID, roomId);
140
102
  }
141
103
  }
142
104
 
@@ -145,9 +107,12 @@ export function markPendingAdmissionAdmitted(
145
107
  roomId: string,
146
108
  admissionID?: string,
147
109
  ): PendingAdmission | undefined {
148
- const admission = pendingEntry(keyFor(sessionID, roomId), Date.now())?.admission;
110
+ assertDeliveryLease();
111
+ const now = Date.now();
112
+ const admission = pendingAdmission(sessionID, roomId);
149
113
  if (admission && (admissionID === undefined || admission.id === admissionID)) {
150
114
  admission.state = "admitted";
115
+ save(sessionID, roomId, admission, now);
151
116
  }
152
117
  return admission;
153
118
  }
@@ -157,12 +122,12 @@ export function clearPendingAdmission(
157
122
  roomId: string,
158
123
  confirmedTs: number,
159
124
  ): void {
160
- const key = keyFor(sessionID, roomId);
161
- const admission = pendingEntry(key, Date.now())?.admission;
125
+ assertDeliveryLease();
126
+ const admission = pendingAdmission(sessionID, roomId);
162
127
  if (!admission || confirmedTs < admission.maxTs) {
163
128
  return;
164
129
  }
165
- pending.delete(key);
130
+ deletePendingAdmission(sessionID, roomId);
166
131
  }
167
132
 
168
133
  export function admissionMatches(
@@ -177,7 +142,7 @@ export function admissionMatches(
177
142
  if (
178
143
  record.id === body.id &&
179
144
  record.sessionID === sessionID &&
180
- record.delivery === "queue"
145
+ (record.delivery === "queue" || record.delivery === "steer")
181
146
  ) {
182
147
  return true;
183
148
  }
@@ -0,0 +1,37 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { promises as fs } from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+
6
+ const validID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
7
+ export const isReceiverOwnerID = (value: unknown): value is string => typeof value === "string" && validID.test(value);
8
+
9
+ export async function receiverOwnerID(origin: string): Promise<string | undefined> {
10
+ const base = process.env.XDG_STATE_HOME || path.join(os.homedir(), ".local", "state");
11
+ const root = path.join(base, "opencode", "chat-room");
12
+ const dir = path.join(root, "owners");
13
+ const name = createHash("sha256").update(new URL(origin).origin).digest("hex") + ".json";
14
+ const file = path.join(dir, name);
15
+ try {
16
+ await fs.mkdir(root, { recursive: true, mode: 0o700 });
17
+ await fs.chmod(root, 0o700);
18
+ await fs.mkdir(dir, { recursive: true, mode: 0o700 });
19
+ await fs.chmod(dir, 0o700);
20
+ try {
21
+ const value = JSON.parse(await fs.readFile(file, "utf8")) as { ownerID?: string };
22
+ return typeof value.ownerID === "string" && validID.test(value.ownerID) ? value.ownerID : undefined;
23
+ } catch (error) {
24
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") return undefined;
25
+ }
26
+ const ownerID = randomUUID();
27
+ const temp = `${file}.${process.pid}.${randomUUID()}.tmp`;
28
+ await fs.writeFile(temp, JSON.stringify({ ownerID }), { flag: "wx", mode: 0o600 });
29
+ try { await fs.link(temp, file); } catch (error) {
30
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") return undefined;
31
+ } finally { await fs.unlink(temp).catch(() => {}); }
32
+ const value = JSON.parse(await fs.readFile(file, "utf8")) as { ownerID?: string };
33
+ return typeof value.ownerID === "string" && validID.test(value.ownerID) ? value.ownerID : undefined;
34
+ } catch {
35
+ return undefined;
36
+ }
37
+ }
@@ -0,0 +1,92 @@
1
+ import { Database } from "bun:sqlite";
2
+ import { chmodSync, mkdirSync } from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+
6
+ const databases = new Map<string, Database>();
7
+ const pause = (ms: number) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
8
+ export function receiverStateDirectory(): string {
9
+ const configured = process.env.XDG_STATE_HOME;
10
+ const base = configured && path.isAbsolute(configured) ? configured : path.join(os.homedir(), ".local", "state");
11
+ return path.join(base, "opencode", "chat-room");
12
+ }
13
+ function database(): Database {
14
+ const file = path.join(receiverStateDirectory(), "receiver.sqlite");
15
+ let db = databases.get(file);
16
+ if (db) return db;
17
+ mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
18
+ chmodSync(path.dirname(file), 0o700);
19
+ db = new Database(file, { create: true });
20
+ chmodSync(file, 0o600);
21
+ db.exec("PRAGMA journal_mode=WAL; PRAGMA busy_timeout=100; CREATE TABLE IF NOT EXISTS delivery_leases(session_id TEXT PRIMARY KEY,holder TEXT NOT NULL,expires_at INTEGER NOT NULL); CREATE TABLE IF NOT EXISTS pending_admissions(session_id TEXT NOT NULL,room_id TEXT NOT NULL,admission TEXT NOT NULL,expires_at INTEGER NOT NULL,updated_at INTEGER NOT NULL,PRIMARY KEY(session_id,room_id)); CREATE INDEX IF NOT EXISTS pending_admissions_expiry ON pending_admissions(expires_at); CREATE TABLE IF NOT EXISTS watcher_claims(identity TEXT PRIMARY KEY,instance_id TEXT NOT NULL,pid INTEGER NOT NULL);");
22
+ databases.set(file, db);
23
+ return db;
24
+ }
25
+ function immediate<T>(fn: (db: Database) => T): T {
26
+ const db = database();
27
+ for (let attempt = 0; ; attempt++) {
28
+ try { return db.transaction(() => fn(db)).immediate(); }
29
+ catch (error) {
30
+ const err = error as { code?: string };
31
+ if (!/SQLITE_(BUSY|LOCKED)/.test(err.code ?? "") || attempt >= 7) throw error;
32
+ pause(Math.min(20 * 2 ** attempt, 250));
33
+ }
34
+ }
35
+ }
36
+
37
+ export function readPendingAdmission<T>(sessionID: string, roomID: string, now: number): T | undefined {
38
+ return immediate((db) => {
39
+ db.query("DELETE FROM pending_admissions WHERE expires_at<=?").run(now);
40
+ const row = db.query("SELECT admission FROM pending_admissions WHERE session_id=? AND room_id=?").get(sessionID, roomID) as { admission: string } | null;
41
+ return row ? JSON.parse(row.admission) as T : undefined;
42
+ });
43
+ }
44
+ export function savePendingAdmission(sessionID: string, roomID: string, value: unknown, expiresAt: number, now: number): void {
45
+ immediate((db) => {
46
+ db.query("DELETE FROM pending_admissions WHERE expires_at<=?").run(now);
47
+ db.query("INSERT INTO pending_admissions VALUES(?,?,?,?,?) ON CONFLICT(session_id,room_id) DO UPDATE SET admission=excluded.admission,expires_at=excluded.expires_at,updated_at=excluded.updated_at")
48
+ .run(sessionID, roomID, JSON.stringify(value), expiresAt, now);
49
+ db.query("DELETE FROM pending_admissions WHERE rowid IN (SELECT rowid FROM pending_admissions ORDER BY updated_at DESC LIMIT -1 OFFSET 1024)").run();
50
+ });
51
+ }
52
+ export function deletePendingAdmission(sessionID: string, roomID: string): void {
53
+ immediate((db) => db.query("DELETE FROM pending_admissions WHERE session_id=? AND room_id=?").run(sessionID, roomID));
54
+ }
55
+
56
+ export function acquireDeliveryLease(sessionID: string, holder: string, now: number, expiresAt: number): boolean {
57
+ return immediate((db) => {
58
+ db.query("DELETE FROM delivery_leases WHERE expires_at<=?").run(now);
59
+ return db.query("INSERT INTO delivery_leases VALUES(?,?,?) ON CONFLICT(session_id) DO UPDATE SET holder=excluded.holder,expires_at=excluded.expires_at WHERE delivery_leases.expires_at<=?")
60
+ .run(sessionID, holder, expiresAt, now).changes === 1;
61
+ });
62
+ }
63
+ export function renewDeliveryLease(sessionID: string, holder: string, now: number, expiresAt: number): boolean {
64
+ return immediate((db) => db.query("UPDATE delivery_leases SET expires_at=? WHERE session_id=? AND holder=? AND expires_at>?")
65
+ .run(expiresAt, sessionID, holder, now).changes === 1);
66
+ }
67
+ export function ownsDeliveryLease(sessionID: string, holder: string, now: number): boolean {
68
+ const row = database().query("SELECT 1 AS owned FROM delivery_leases WHERE session_id=? AND holder=? AND expires_at>?").get(sessionID, holder, now);
69
+ return Boolean(row);
70
+ }
71
+ export function releaseDeliveryLease(sessionID: string, holder: string): void {
72
+ immediate((db) => db.query("DELETE FROM delivery_leases WHERE session_id=? AND holder=?").run(sessionID, holder));
73
+ }
74
+ export function watcherProcessMayExist(pid: number): boolean {
75
+ try { process.kill(pid, 0); return true; }
76
+ catch (error) { return (error as NodeJS.ErrnoException).code !== "ESRCH"; }
77
+ }
78
+ export function claimWatcher(identity: string, instanceID: string, pid: number): boolean {
79
+ return immediate((db) => {
80
+ const row = db.query("SELECT instance_id,pid FROM watcher_claims WHERE identity=?").get(identity) as { instance_id: string; pid: number } | null;
81
+ if (row && row.instance_id !== instanceID && watcherProcessMayExist(row.pid)) return false;
82
+ db.query("INSERT INTO watcher_claims VALUES(?,?,?) ON CONFLICT(identity) DO UPDATE SET instance_id=excluded.instance_id,pid=excluded.pid")
83
+ .run(identity, instanceID, pid);
84
+ return true;
85
+ });
86
+ }
87
+ export function releaseWatcherClaim(identity: string, instanceID: string): void {
88
+ immediate((db) => db.query("DELETE FROM watcher_claims WHERE identity=? AND instance_id=?").run(identity, instanceID));
89
+ }
90
+ export function closeReceiverState(): void {
91
+ for (const [file, db] of databases) { db.close(); databases.delete(file); }
92
+ }
@@ -42,14 +42,12 @@ export class RoomError extends Error {
42
42
  export default class RoomService {
43
43
  private rooms: Map<string, Room> = new Map();
44
44
 
45
- // ponytail: per-room history ceiling — everything above the watermark is
46
- // unreachable anyway; this bounds rooms.json and every serialized response
45
+ // Keep only a working window in memory; SQLite retains the full message history.
47
46
  static readonly MAX_MESSAGES = 500;
48
47
 
49
48
  hydrate(rooms: Room[]): void {
50
49
  for (const room of rooms) {
51
- // ponytail: cap pre-existing rooms.json files on load so an old
52
- // oversized file doesn't stay heavy until the next event
50
+ // Hydrated message arrays are only the in-memory working window.
53
51
  this.trimMessages(room);
54
52
  this.rooms.set(room.id, room);
55
53
  }
@@ -0,0 +1,51 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { randomUUID } from "node:crypto";
3
+ import { acquireDeliveryLease, ownsDeliveryLease, releaseDeliveryLease, renewDeliveryLease } from "./receiver-state";
4
+
5
+ const LEASE_MS = 15_000;
6
+ const active = new AsyncLocalStorage<{ sessionID: string; holder: string; lost: boolean }>();
7
+ const queues = new Map<string, Promise<unknown>>();
8
+
9
+ async function withLease<T>(sessionID: string, task: () => Promise<T>): Promise<T | undefined> {
10
+ const holder = randomUUID();
11
+ const now = Date.now();
12
+ if (!acquireDeliveryLease(sessionID, holder, now, now + LEASE_MS)) return undefined;
13
+ const lease = { sessionID, holder, lost: false };
14
+ const timer = setInterval(() => {
15
+ if (lease.lost) return;
16
+ const at = Date.now();
17
+ try {
18
+ if (!renewDeliveryLease(sessionID, holder, at, at + LEASE_MS)) lease.lost = true;
19
+ } catch {
20
+ lease.lost = true;
21
+ }
22
+ if (lease.lost) clearInterval(timer);
23
+ }, LEASE_MS / 3);
24
+ timer.unref?.();
25
+ try { return await active.run(lease, task); }
26
+ finally {
27
+ lease.lost = true;
28
+ clearInterval(timer);
29
+ try { releaseDeliveryLease(sessionID, holder); } catch { /* Expiry lets another process reclaim a locked row. */ }
30
+ }
31
+ }
32
+
33
+ export function assertDeliveryLease(): void {
34
+ const lease = active.getStore();
35
+ if (!lease) return;
36
+ if (lease.lost) throw new Error("session delivery lease was lost");
37
+ try {
38
+ if (ownsDeliveryLease(lease.sessionID, lease.holder, Date.now())) return;
39
+ } catch { lease.lost = true; }
40
+ lease.lost = true;
41
+ throw new Error("session delivery lease was lost");
42
+ }
43
+
44
+ export function serializeSessionPush<T>(sessionID: string, task: () => Promise<T>): Promise<T | undefined> {
45
+ const previous = queues.get(sessionID) ?? Promise.resolve();
46
+ const run = previous.catch(() => {}).then(() => withLease(sessionID, task));
47
+ let current: Promise<T | undefined>;
48
+ current = run.finally(() => { if (queues.get(sessionID) === current) queues.delete(sessionID); });
49
+ queues.set(sessionID, current);
50
+ return current;
51
+ }
@@ -0,0 +1,265 @@
1
+ import { Database } from "bun:sqlite";
2
+ import { chmodSync, mkdirSync, readFileSync } from "node:fs";
3
+ import path from "node:path";
4
+ import RoomService, { type Message, type Room, type Participant } from "./room-service";
5
+ import type { Registry, RegistryEntry } from "./store";
6
+
7
+ type State = { rooms: Room[]; registry: Registry };
8
+ type Page<T> = { items: T[]; hasMore: boolean };
9
+ const databases = new Map<string, Promise<Database>>();
10
+
11
+ function open(file: string): Promise<Database> {
12
+ const known = databases.get(file);
13
+ if (known) return known;
14
+ const pending = initialize(file);
15
+ databases.set(file, pending);
16
+ void pending.catch(() => databases.delete(file));
17
+ return pending;
18
+ }
19
+
20
+ async function initialize(file: string): Promise<Database> {
21
+ mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
22
+ chmodSync(path.dirname(file), 0o700);
23
+ const db = new Database(file, { create: true });
24
+ chmodSync(file, 0o600);
25
+ try {
26
+ for (let attempt = 0; ; attempt++) {
27
+ try {
28
+ db.exec("PRAGMA journal_mode=WAL; PRAGMA busy_timeout=50; PRAGMA foreign_keys=ON;");
29
+ db.exec(`CREATE TABLE IF NOT EXISTS meta(key TEXT PRIMARY KEY,value TEXT NOT NULL);
30
+ CREATE TABLE IF NOT EXISTS rooms(id TEXT PRIMARY KEY,name TEXT NOT NULL,owner_id TEXT NOT NULL,created_at INTEGER NOT NULL);
31
+ CREATE TABLE IF NOT EXISTS participants(room_id TEXT NOT NULL REFERENCES rooms(id) ON DELETE CASCADE,id TEXT NOT NULL,name TEXT NOT NULL,joined_at INTEGER NOT NULL,PRIMARY KEY(room_id,id));
32
+ CREATE TABLE IF NOT EXISTS messages(seq INTEGER PRIMARY KEY AUTOINCREMENT,id TEXT NOT NULL UNIQUE,room_id TEXT NOT NULL REFERENCES rooms(id) ON DELETE CASCADE,sender_id TEXT NOT NULL,sender_session_id TEXT,text TEXT NOT NULL,created_at INTEGER NOT NULL);
33
+ CREATE INDEX IF NOT EXISTS messages_room_seq ON messages(room_id,seq DESC);
34
+ CREATE INDEX IF NOT EXISTS messages_room_time ON messages(room_id,created_at,seq);
35
+ CREATE TABLE IF NOT EXISTS registry(room_id TEXT NOT NULL REFERENCES rooms(id) ON DELETE CASCADE,session_id TEXT NOT NULL,server_url TEXT NOT NULL,api_prefix TEXT NOT NULL,protocol TEXT,name TEXT NOT NULL,last_read_ts INTEGER,last_queued_ts INTEGER,directory TEXT,host TEXT,receiver_owner_id TEXT,PRIMARY KEY(room_id,session_id));`);
36
+ await migrate(db, file);
37
+ return db;
38
+ } catch (error) {
39
+ if (!isBusy(error) || attempt >= 7) throw error;
40
+ await pause(Math.min(20 * 2 ** attempt, 250));
41
+ }
42
+ }
43
+ } catch (error) { db.close(); throw error; }
44
+ }
45
+
46
+ function readLegacy(file: string): unknown | undefined {
47
+ try { return JSON.parse(readFileSync(file, "utf8")); }
48
+ catch (error) {
49
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
50
+ throw error;
51
+ }
52
+ }
53
+
54
+ const pause = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
55
+ function isBusy(error: unknown): boolean {
56
+ const err = error as { code?: string; message?: string };
57
+ return err.code === "SQLITE_BUSY" || err.code === "SQLITE_LOCKED" || /database is locked/i.test(err.message ?? "");
58
+ }
59
+
60
+ async function immediate<T>(db: Database, fn: () => T): Promise<T> {
61
+ for (let attempt = 0; ; attempt++) {
62
+ try { return db.transaction(fn).immediate(); }
63
+ catch (error) {
64
+ if (!isBusy(error) || attempt >= 7) throw error;
65
+ await pause(Math.min(20 * 2 ** attempt, 250));
66
+ }
67
+ }
68
+ }
69
+
70
+ async function migrate(db: Database, file: string): Promise<void> {
71
+ if (db.query("SELECT value FROM meta WHERE key='json-migration'").get()) return;
72
+ const oldRooms = readLegacy(path.join(path.dirname(file), "rooms.json"));
73
+ const oldRegistry = readLegacy(path.join(path.dirname(file), "registry.json"));
74
+ const rooms = validateRooms(oldRooms);
75
+ const registry = validateRegistry(oldRegistry);
76
+ await immediate(db, () => {
77
+ if (db.query("SELECT value FROM meta WHERE key='json-migration'").get()) return;
78
+ for (const room of rooms) insertRoom(db, room);
79
+ replaceRegistry(db, registry);
80
+ db.query("INSERT INTO meta(key,value) VALUES('json-migration','done')").run();
81
+ });
82
+ }
83
+
84
+ function record(value: unknown): value is Record<string, unknown> {
85
+ return typeof value === "object" && value !== null && !Array.isArray(value);
86
+ }
87
+ function timestamp(value: unknown): value is number { return typeof value === "number" && Number.isFinite(value) && value >= 0; }
88
+
89
+ function validateRooms(value: unknown): Room[] {
90
+ if (value === undefined) return [];
91
+ if (!Array.isArray(value)) throw new Error("Legacy rooms.json must contain an array");
92
+ return value.map((item) => {
93
+ if (!record(item) || typeof item.id !== "string" || !item.id || typeof item.name !== "string" ||
94
+ typeof item.ownerId !== "string" || !timestamp(item.createdAt) || !Array.isArray(item.participants) || !Array.isArray(item.messages)) {
95
+ throw new Error("Legacy rooms.json contains an invalid room");
96
+ }
97
+ const participants = new Map<string, Participant>();
98
+ for (const p of item.participants) {
99
+ if (!record(p) || typeof p.id !== "string" || typeof p.name !== "string" || !timestamp(p.joinedAt)) throw new Error("Legacy rooms.json contains an invalid participant");
100
+ participants.set(p.id, { id: p.id, name: p.name, joinedAt: p.joinedAt });
101
+ }
102
+ let previousTs = -1;
103
+ const messages = item.messages.map((m): Message => {
104
+ if (!record(m) || typeof m.id !== "string" || typeof m.roomId !== "string" || m.roomId !== item.id ||
105
+ typeof m.senderId !== "string" || typeof m.text !== "string" || !timestamp(m.createdAt) ||
106
+ m.createdAt <= previousTs || (m.senderSessionID !== undefined && typeof m.senderSessionID !== "string")) throw new Error("Legacy rooms.json contains an invalid message");
107
+ previousTs = m.createdAt;
108
+ return { id: m.id, roomId: m.roomId, senderId: m.senderId, text: m.text, createdAt: m.createdAt,
109
+ ...(m.senderSessionID !== undefined ? { senderSessionID: m.senderSessionID } : {}) };
110
+ });
111
+ return { id: item.id, name: item.name, ownerId: item.ownerId, createdAt: item.createdAt, participants, messages };
112
+ });
113
+ }
114
+
115
+ function validateRegistry(value: unknown): Registry {
116
+ if (value === undefined) return {};
117
+ if (!record(value)) throw new Error("Legacy registry.json must contain an object");
118
+ const result: Registry = Object.create(null);
119
+ for (const [roomId, members] of Object.entries(value)) {
120
+ if (!roomId || !record(members)) throw new Error("Legacy registry.json contains an invalid room");
121
+ result[roomId] = Object.create(null);
122
+ for (const [sessionID, raw] of Object.entries(members)) {
123
+ if (!sessionID || !record(raw) || typeof raw.serverUrl !== "string" || typeof raw.apiPrefix !== "string" ||
124
+ typeof raw.name !== "string" || (raw.protocol !== undefined && raw.protocol !== "v1" && raw.protocol !== "v2") ||
125
+ (["lastReadTs", "lastQueuedTs"].some((key) => raw[key] !== undefined && !timestamp(raw[key]))) ||
126
+ (["directory", "host", "receiverOwnerID"].some((key) => raw[key] !== undefined && typeof raw[key] !== "string"))) {
127
+ throw new Error("Legacy registry.json contains an invalid entry");
128
+ }
129
+ result[roomId]![sessionID] = { serverUrl: raw.serverUrl, apiPrefix: raw.apiPrefix, name: raw.name,
130
+ ...(raw.protocol ? { protocol: raw.protocol } : {}),
131
+ ...(timestamp(raw.lastReadTs) ? { lastReadTs: raw.lastReadTs } : {}),
132
+ ...(timestamp(raw.lastQueuedTs) ? { lastQueuedTs: raw.lastQueuedTs } : {}),
133
+ ...(typeof raw.directory === "string" ? { directory: raw.directory } : {}),
134
+ ...(typeof raw.host === "string" ? { host: raw.host } : {}),
135
+ ...(typeof raw.receiverOwnerID === "string" ? { receiverOwnerID: raw.receiverOwnerID } : {}) };
136
+ }
137
+ }
138
+ return result;
139
+ }
140
+
141
+ function insertRoom(db: Database, room: Room): void {
142
+ db.query("INSERT INTO rooms VALUES(?,?,?,?)").run(room.id, room.name, room.ownerId, room.createdAt);
143
+ const participant = db.query("INSERT INTO participants VALUES(?,?,?,?)");
144
+ for (const p of room.participants.values()) participant.run(room.id, p.id, p.name, p.joinedAt);
145
+ const message = db.query("INSERT INTO messages(id,room_id,sender_id,sender_session_id,text,created_at) VALUES(?,?,?,?,?,?)");
146
+ for (const m of room.messages) message.run(m.id, room.id, m.senderId, m.senderSessionID ?? null, m.text, m.createdAt);
147
+ }
148
+
149
+ function replaceRegistry(db: Database, registry: Registry): void {
150
+ db.exec("DELETE FROM registry");
151
+ const insert = db.query("INSERT INTO registry VALUES(?,?,?,?,?,?,?,?,?,?,?)");
152
+ for (const [roomID, members] of Object.entries(registry)) for (const [sessionID, r] of Object.entries(members)) {
153
+ insert.run(roomID, sessionID, r.serverUrl, r.apiPrefix, r.protocol ?? null, r.name,
154
+ r.lastReadTs ?? null, r.lastQueuedTs ?? null, r.directory ?? null, r.host ?? null, r.receiverOwnerID ?? null);
155
+ }
156
+ }
157
+
158
+ function persistState(db: Database, rooms: Room[], registry: Registry): void {
159
+ const roomRow = db.query("INSERT INTO rooms VALUES(?,?,?,?) ON CONFLICT(id) DO UPDATE SET name=excluded.name,owner_id=excluded.owner_id,created_at=excluded.created_at");
160
+ const participant = db.query("INSERT INTO participants VALUES(?,?,?,?)");
161
+ const message = db.query("INSERT OR IGNORE INTO messages(id,room_id,sender_id,sender_session_id,text,created_at) VALUES(?,?,?,?,?,?)");
162
+ const removeParticipants = db.query("DELETE FROM participants WHERE room_id=?");
163
+ for (const room of rooms) {
164
+ roomRow.run(room.id, room.name, room.ownerId, room.createdAt);
165
+ removeParticipants.run(room.id);
166
+ for (const p of room.participants.values()) participant.run(room.id, p.id, p.name, p.joinedAt);
167
+ for (const m of room.messages) message.run(m.id, room.id, m.senderId, m.senderSessionID ?? null, m.text, m.createdAt);
168
+ }
169
+ replaceRegistry(db, registry);
170
+ }
171
+
172
+ function readState(db: Database): State {
173
+ const roomRows = db.query("SELECT id,name,owner_id,created_at FROM rooms ORDER BY created_at,id").all() as Array<Record<string, string | number>>;
174
+ const rooms = roomRows.map((r): Room => {
175
+ const participants = new Map<string, Participant>();
176
+ for (const p of db.query("SELECT id,name,joined_at FROM participants WHERE room_id=?").all(String(r.id)) as Array<Record<string, string | number>>) {
177
+ participants.set(String(p.id), { id: String(p.id), name: String(p.name), joinedAt: Number(p.joined_at) });
178
+ }
179
+ const messages = db.query("SELECT id,room_id,sender_id,sender_session_id,text,created_at FROM messages WHERE room_id=? ORDER BY seq DESC LIMIT 500").all(String(r.id)) as Array<Record<string, string | number | null>>;
180
+ return { id: String(r.id), name: String(r.name), ownerId: String(r.owner_id), createdAt: Number(r.created_at), participants,
181
+ messages: messages.reverse().map((m) => ({ id: String(m.id), roomId: String(m.room_id), senderId: String(m.sender_id),
182
+ text: String(m.text), createdAt: Number(m.created_at), ...(m.sender_session_id ? { senderSessionID: String(m.sender_session_id) } : {}) })) };
183
+ });
184
+ const registry: Registry = Object.create(null);
185
+ const rows = db.query("SELECT * FROM registry").all() as Array<Record<string, string | number | null>>;
186
+ for (const r of rows) (registry[String(r.room_id)] ??= Object.create(null))[String(r.session_id)] = {
187
+ serverUrl: String(r.server_url), apiPrefix: String(r.api_prefix), name: String(r.name),
188
+ ...(r.protocol ? { protocol: r.protocol as "v1" | "v2" } : {}),
189
+ ...(r.last_read_ts !== null ? { lastReadTs: Number(r.last_read_ts) } : {}),
190
+ ...(r.last_queued_ts !== null ? { lastQueuedTs: Number(r.last_queued_ts) } : {}),
191
+ ...(r.directory !== null ? { directory: String(r.directory) } : {}), ...(r.host !== null ? { host: String(r.host) } : {}),
192
+ ...(r.receiver_owner_id !== null ? { receiverOwnerID: String(r.receiver_owner_id) } : {}),
193
+ };
194
+ return { rooms, registry };
195
+ }
196
+
197
+ export type HistoryMessage = Message & { seq: number };
198
+ export async function writeSqliteState<T>(file: string, callback: (service: RoomService, registry: Registry) => T): Promise<T> {
199
+ const db = await open(file);
200
+ return immediate(db, () => {
201
+ const state = readState(db);
202
+ const service = new RoomService();
203
+ service.hydrate(state.rooms);
204
+ const result = callback(service, state.registry);
205
+ if (result && typeof (result as { then?: unknown }).then === "function") throw new Error("writeState callback must be synchronous");
206
+ persistState(db, service.listRooms(), state.registry);
207
+ return result;
208
+ });
209
+ }
210
+
211
+ export async function readSqliteState(file: string): Promise<State> {
212
+ const db = await open(file);
213
+ return db.transaction(() => readState(db)).deferred();
214
+ }
215
+
216
+ export async function readUnreadPage(file: string, roomID: string, afterTs: number, limit = 100, sessionID?: string, senderName?: string, newest = false): Promise<Page<Message>> {
217
+ const db = await open(file);
218
+ const take = Math.min(200, Math.max(1, limit));
219
+ const rows = db.query(`SELECT id,room_id,sender_id,sender_session_id,text,created_at FROM messages WHERE room_id=? AND created_at>? AND
220
+ (? IS NULL OR (sender_session_id IS NOT NULL AND sender_session_id!=?) OR (sender_session_id IS NULL AND sender_id!=?))
221
+ ORDER BY created_at ${newest ? "DESC" : "ASC"},seq ${newest ? "DESC" : "ASC"} LIMIT ?`)
222
+ .all(roomID, afterTs, sessionID ?? null, sessionID ?? null, senderName ?? "", take + 1) as Array<Record<string, string | number | null>>;
223
+ const hasMore = rows.length > take;
224
+ const items = rows.slice(0, take).map(rowMessage);
225
+ return { items: newest ? items.reverse() : items, hasMore };
226
+ }
227
+
228
+ export async function readInboxPage(file: string, sessionID: string, roomFilter: string | null, excludeSelf: boolean, limit = 100) {
229
+ const db = await open(file);
230
+ return db.transaction(() => {
231
+ const take = Math.min(200, Math.max(1, limit));
232
+ const members = db.query("SELECT room_id,last_queued_ts FROM registry WHERE session_id=? AND (? IS NULL OR room_id=?)").all(sessionID, roomFilter, roomFilter) as Array<{ room_id: string; last_queued_ts: number | null }>;
233
+ const rows = db.query(`SELECT m.id,m.room_id,m.sender_id,m.sender_session_id,m.text,m.created_at,r.name AS room_name
234
+ FROM messages m JOIN registry g ON g.room_id=m.room_id JOIN rooms r ON r.id=m.room_id
235
+ WHERE g.session_id=? AND (? IS NULL OR m.room_id=?) AND
236
+ m.created_at > CASE WHEN ? THEN max(coalesce(g.last_read_ts,0),coalesce(g.last_queued_ts,0)) ELSE coalesce(g.last_read_ts,0) END AND
237
+ (?=0 OR (m.sender_session_id IS NOT NULL AND m.sender_session_id!=?) OR (m.sender_session_id IS NULL AND m.sender_id!=g.name))
238
+ ORDER BY m.created_at,m.seq LIMIT ?`).all(sessionID, roomFilter, roomFilter, excludeSelf ? 1 : 0,
239
+ excludeSelf ? 1 : 0, sessionID, take + 1) as Array<Record<string, string | number | null>>;
240
+ const hasMore = rows.length > take;
241
+ const items = rows.slice(0, take).map((row) => {
242
+ const { senderSessionID: _sessionID, ...message } = rowMessage(row);
243
+ return { ...message, roomName: String(row.room_name) };
244
+ });
245
+ const queuedTs = Object.fromEntries(members.map((member) => [member.room_id, member.last_queued_ts ?? 0]));
246
+ return { member: members.length > 0, items, queuedTs, hasMore };
247
+ }).deferred();
248
+ }
249
+
250
+ export async function readHistoryPage(file: string, roomID: string, beforeSeq?: number, limit = 100, excludeSessionID?: string, excludeName = ""): Promise<{ messages: HistoryMessage[]; nextBeforeSeq: number | null; hasMore: boolean }> {
251
+ const db = await open(file);
252
+ const take = Math.min(200, Math.max(1, limit));
253
+ const rows = db.query(`SELECT seq,id,room_id,sender_id,sender_session_id,text,created_at FROM messages WHERE room_id=? ${beforeSeq === undefined ? "" : "AND seq<? "}AND
254
+ (? IS NULL OR (sender_session_id IS NOT NULL AND sender_session_id!=?) OR (sender_session_id IS NULL AND sender_id!=?))
255
+ ORDER BY seq DESC LIMIT ?`).all(...(beforeSeq === undefined ? [roomID] : [roomID, beforeSeq]),
256
+ excludeSessionID ?? null, excludeSessionID ?? null, excludeName, take + 1) as Array<Record<string, string | number | null>>;
257
+ const hasMore = rows.length > take;
258
+ const messages = rows.slice(0, take).reverse().map((row) => ({ ...rowMessage(row), seq: Number(row.seq) }));
259
+ return { messages, nextBeforeSeq: hasMore ? messages[0]?.seq ?? null : null, hasMore };
260
+ }
261
+
262
+ function rowMessage(row: Record<string, string | number | null>): Message {
263
+ return { id: String(row.id), roomId: String(row.room_id), senderId: String(row.sender_id), text: String(row.text),
264
+ createdAt: Number(row.created_at), ...(row.sender_session_id !== null ? { senderSessionID: String(row.sender_session_id) } : {}) };
265
+ }