@alexsun-top/opencode-chat-room 0.7.3 → 0.7.5
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/CHANGELOG.md +24 -0
- package/README.md +12 -5
- package/README.zh-CN.md +12 -5
- package/cli.ts +26 -6
- package/dist/cli.js +7804 -0
- package/package.json +19 -6
- package/plugin.ts +7 -4
- package/server/admin-auth.ts +1 -1
- package/server/admin-routes.ts +2 -2
- package/server/admin-state.ts +2 -1
- package/server/assets/FLUENT-ICONS-LICENSE +25 -0
- package/server/assets/NOTICE.txt +2 -1
- package/server/assets/attachments.css +1 -1
- package/server/assets/base.css +29 -7
- package/server/assets/chat/admin.js +43 -3
- package/server/assets/chat/announcements.js +5 -3
- package/server/assets/chat/confirm-dialog.js +12 -2
- package/server/assets/chat/create-room-dialog.js +5 -3
- package/server/assets/chat/events.js +32 -7
- package/server/assets/chat/files.js +369 -0
- package/server/assets/chat/history-loader.js +36 -26
- package/server/assets/chat/icons.js +15 -0
- package/server/assets/chat/index.js +7 -1
- package/server/assets/chat/locales/de.js +19 -2
- package/server/assets/chat/locales/es.js +19 -2
- package/server/assets/chat/locales/fr.js +19 -2
- package/server/assets/chat/locales/it.js +19 -2
- package/server/assets/chat/locales/ja.js +19 -2
- package/server/assets/chat/locales/ko.js +19 -2
- package/server/assets/chat/markdown.js +5 -33
- package/server/assets/chat/message-polling.js +61 -6
- package/server/assets/chat/message-window.js +28 -0
- package/server/assets/chat/messages.js +32 -12
- package/server/assets/chat/palette.js +396 -0
- package/server/assets/chat/pwa.js +67 -9
- package/server/assets/chat/recall.js +3 -2
- package/server/assets/chat/replies.js +2 -1
- package/server/assets/chat/rooms.js +20 -7
- package/server/assets/chat/search.js +137 -0
- package/server/assets/chat/settings.js +11 -5
- package/server/assets/chat/shortcuts.js +1 -1
- package/server/assets/chat/state.js +38 -4
- package/server/assets/code-highlight.css +0 -5
- package/server/assets/conversation.css +5 -4
- package/server/assets/edit-room.css +77 -0
- package/server/assets/files.css +222 -0
- package/server/assets/fluent-icons.svg +42 -0
- package/server/assets/icons.css +9 -0
- package/server/assets/palette.css +263 -0
- package/server/assets/recall.css +2 -2
- package/server/assets/responsive.css +6 -5
- package/server/assets/room-create.css +1 -1
- package/server/assets/settings.css +10 -7
- package/server/chat-server.ts +46 -29
- package/server/chat.html +175 -61
- package/server/http-server.ts +182 -0
- package/server/join-requests.ts +4 -4
- package/server/manifest.webmanifest +1 -1
- package/server/member-routes.ts +3 -3
- package/server/message-recall-routes.ts +1 -1
- package/server/newrooms.ts +4 -4
- package/server/resource-routes.ts +19 -4
- package/server/room-join.ts +1 -1
- package/server/room-payload.ts +1 -1
- package/server/sw.js +12 -1
- package/server/wake.ts +1 -1
- package/src/README.md +4 -2
- package/src/config/file-config.ts +294 -0
- package/src/rooms/resource-read.ts +2 -1
- package/src/rooms/resource-upload.ts +6 -3
- package/src/rooms/resources.ts +7 -2
- package/src/runtime/watch.ts +13 -8
- package/src/state/receiver-state.ts +3 -5
- package/src/state/sqlite-state.ts +11 -7
- package/src/state/sqlite.ts +80 -0
- package/src/state/store.ts +1 -0
- package/src/tui/app.mjs +417 -0
- package/src/tui/config.mjs +194 -0
- package/src/tui/http.mjs +103 -0
- package/src/tui/main.mjs +176 -0
- package/src/tui/messages.mjs +67 -0
- package/src/tui/palette-app.mjs +265 -0
- package/src/tui/palette.mjs +101 -0
- package/src/tui/session.mjs +40 -0
- package/src/tui/ui-content.mjs +426 -0
- package/src/tui/ui-theme.mjs +60 -0
- package/src/tui/ui-view.mjs +452 -0
- package/src/tui/ui.mjs +262 -0
- package/src/tests/announcement-board.ts +0 -186
|
@@ -9,7 +9,8 @@ const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-
|
|
|
9
9
|
const limit = 512 * 1024 * 1024;
|
|
10
10
|
|
|
11
11
|
export class ResourceReadError extends Error {
|
|
12
|
-
|
|
12
|
+
readonly code: "invalid" | "permission_denied" | "size_limit" | "not_found" | "aborted" | "network" | "save_failed";
|
|
13
|
+
constructor(code: "invalid" | "permission_denied" | "size_limit" | "not_found" | "aborted" | "network" | "save_failed", message: string) { super(message); this.code = code; }
|
|
13
14
|
}
|
|
14
15
|
export function resourceReadFailure(error: unknown): string {
|
|
15
16
|
return error instanceof ResourceReadError ? error.message : "resource read failed; verify roomId and resourceId, check the server connection, then retry";
|
|
@@ -1,5 +1,7 @@
|
|
|
1
|
+
import { createReadStream } from "node:fs";
|
|
1
2
|
import { realpath, stat } from "node:fs/promises";
|
|
2
3
|
import path from "node:path";
|
|
4
|
+
import { Readable } from "node:stream";
|
|
3
5
|
import type { Resource } from "./resources.ts";
|
|
4
6
|
|
|
5
7
|
type PermissionContext = { directory: string; worktree?: string; ask(input: { permission: string; patterns: string[]; always: string[]; metadata: Record<string, unknown> }): Promise<void> };
|
|
@@ -32,13 +34,14 @@ export async function uploadAgentResource(opts: UploadOptions, roomID: string, f
|
|
|
32
34
|
};
|
|
33
35
|
if (opts.token) headers.Authorization = `Bearer ${opts.token}`;
|
|
34
36
|
const response = await fetch(`${opts.center}/rooms/${encodeURIComponent(roomID)}/resources`, {
|
|
35
|
-
method: "POST", headers,
|
|
37
|
+
method: "POST", headers,
|
|
38
|
+
body: Readable.toWeb(createReadStream(actual)) as unknown as BodyInit,
|
|
36
39
|
redirect: "error",
|
|
37
40
|
// Large transfers need more than the JSON client's ten-second deadline.
|
|
38
41
|
signal: AbortSignal.timeout(30 * 60_000),
|
|
39
|
-
//
|
|
42
|
+
// Streaming request bodies require half-duplex framing in fetch.
|
|
40
43
|
duplex: "half",
|
|
41
|
-
});
|
|
44
|
+
} as RequestInit & { duplex: "half" });
|
|
42
45
|
const data = await response.json().catch(() => ({})) as { resource?: Resource; error?: string };
|
|
43
46
|
if (!response.ok || !data.resource) throw new Error(data.error ?? `upload failed (${response.status})`);
|
|
44
47
|
return `${JSON.stringify(data.resource)}\n[[resource:${data.resource.id}]]\nThe upload alone is invisible. To display this attachment, include the marker above unchanged in a send message, outside backticks or code blocks.`;
|
package/src/rooms/resources.ts
CHANGED
|
@@ -2,11 +2,12 @@ import { randomUUID } from "node:crypto";
|
|
|
2
2
|
import { promises as fs } from "node:fs";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { databasePath, readState } from "../state/store.ts";
|
|
5
|
-
import { getResource, putResource, removeResource, type StoredResource } from "../state/sqlite-state.ts";
|
|
5
|
+
import { getResource, listResources, putResource, removeResource, type StoredResource } from "../state/sqlite-state.ts";
|
|
6
6
|
|
|
7
7
|
export type Resource = StoredResource;
|
|
8
8
|
export class ResourceError extends Error {
|
|
9
|
-
|
|
9
|
+
readonly status: number;
|
|
10
|
+
constructor(status: number, message: string) { super(message); this.status = status; }
|
|
10
11
|
}
|
|
11
12
|
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
12
13
|
const storageDir = () => path.join(path.dirname(databasePath()), "resources");
|
|
@@ -133,6 +134,10 @@ export function resourcePath(resource: Pick<Resource, "id" | "roomID">): string
|
|
|
133
134
|
if (!uuid.test(resource.roomID) || !uuid.test(resource.id)) throw new ResourceError(404, "resource not found");
|
|
134
135
|
return path.join(roomDirectory(resource.roomID), resource.id);
|
|
135
136
|
}
|
|
137
|
+
export async function listRoomResources(roomID: string, limit = 500, offset = 0): Promise<{ items: Resource[]; total: number }> {
|
|
138
|
+
if (!uuid.test(roomID)) throw new ResourceError(404, "room not found");
|
|
139
|
+
return listResources(databasePath(), roomID, limit, offset);
|
|
140
|
+
}
|
|
136
141
|
export async function findResource(roomID: string, id: string): Promise<Resource | undefined> {
|
|
137
142
|
if (!uuid.test(id)) return undefined;
|
|
138
143
|
return getResource(databasePath(), roomID, id);
|
package/src/runtime/watch.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { Buffer } from "node:buffer";
|
|
1
2
|
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
|
2
3
|
import { realpathSync } from "node:fs";
|
|
3
4
|
import { appendFile, chmod, link, mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
|
|
@@ -10,12 +11,14 @@ import { receiverOwnerID } from "../state/receiver-owner.ts";
|
|
|
10
11
|
import { claimWatcher, closeReceiverState, releaseWatcherClaim, receiverStateDirectory, watcherProcessMayExist } from "../state/receiver-state.ts";
|
|
11
12
|
import { databasePath, loadRegistry } from "../state/store.ts";
|
|
12
13
|
import { request, type CenterOpts } from "../center/center-client.ts";
|
|
14
|
+
import { loadRoomConfig, resolveClientSettings } from "../config/file-config.ts";
|
|
13
15
|
import { assertDeliveryLease } from "../center/session-delivery.ts";
|
|
14
16
|
import type { QueueTransport } from "../center/queue-transport.ts";
|
|
15
17
|
import { pollOwnedSessions } from "./v2-receiver.ts";
|
|
16
|
-
import { pollKnownSessions } from "../../plugin";
|
|
18
|
+
import { pollKnownSessions } from "../../plugin.ts";
|
|
17
19
|
import { locallyOwnedSessions, reportAgentPresence } from "../agent/agent-presence.ts";
|
|
18
20
|
import { flushReceiptCandidates, receiptDestination } from "../agent/agent-receipts.ts";
|
|
21
|
+
import { startServer } from "../../server/http-server.ts";
|
|
19
22
|
|
|
20
23
|
type WatchRecord = { phase: "starting" | "running"; token: string; nonce: string; instanceID: string; pid: number; port?: number; createdAt?: number };
|
|
21
24
|
function canonicalPath(value: string): string {
|
|
@@ -33,8 +36,9 @@ function canonicalPath(value: string): string {
|
|
|
33
36
|
}
|
|
34
37
|
}
|
|
35
38
|
}
|
|
39
|
+
const clientSettings = () => resolveClientSettings(loadRoomConfig());
|
|
36
40
|
const profile = () => {
|
|
37
|
-
const center =
|
|
41
|
+
const center = clientSettings().url;
|
|
38
42
|
const home = process.env.HOME || os.homedir();
|
|
39
43
|
let target = `standalone:${canonicalPath(databasePath())}`;
|
|
40
44
|
if (center) { try { const url = new URL(center); target = `${url.origin}${url.pathname}`; } catch { target = "invalid-center"; } }
|
|
@@ -136,9 +140,10 @@ export async function watcherSweep(deps: WatchSweepDeps = defaultSweepDeps()): P
|
|
|
136
140
|
}
|
|
137
141
|
|
|
138
142
|
function defaultSweepDeps(): WatchSweepDeps {
|
|
143
|
+
const settings = clientSettings();
|
|
139
144
|
const center: CenterOpts = {
|
|
140
|
-
center:
|
|
141
|
-
token:
|
|
145
|
+
center: settings.url,
|
|
146
|
+
token: settings.token,
|
|
142
147
|
};
|
|
143
148
|
return {
|
|
144
149
|
discover: discoverCompatibleRegisteredHost,
|
|
@@ -308,7 +313,7 @@ export async function runWatcher(): Promise<void> {
|
|
|
308
313
|
let shuttingDown = false;
|
|
309
314
|
let interval: ReturnType<typeof setInterval> | undefined;
|
|
310
315
|
let activeSweep: Promise<unknown> | undefined;
|
|
311
|
-
let server: ReturnType<typeof
|
|
316
|
+
let server: Awaited<ReturnType<typeof startServer>> | undefined;
|
|
312
317
|
let finish!: () => void;
|
|
313
318
|
const done = new Promise<void>((resolve) => { finish = resolve; });
|
|
314
319
|
const stop = async () => {
|
|
@@ -319,14 +324,14 @@ export async function runWatcher(): Promise<void> {
|
|
|
319
324
|
process.off("SIGTERM", onSignal);
|
|
320
325
|
await activeSweep?.catch(() => {});
|
|
321
326
|
await logEvent("stopped");
|
|
322
|
-
server?.
|
|
327
|
+
await server?.close();
|
|
323
328
|
await removeRecord(token!, nonce!);
|
|
324
329
|
try { releaseWatcherClaim(profile(), instanceID!); } catch { /* Dead process detection reclaims the row next time. */ }
|
|
325
330
|
closeReceiverState();
|
|
326
331
|
finish();
|
|
327
332
|
};
|
|
328
333
|
const onSignal = () => { void stop(); };
|
|
329
|
-
const controlServer =
|
|
334
|
+
const controlServer = await startServer({
|
|
330
335
|
hostname: "127.0.0.1", port: 0,
|
|
331
336
|
fetch(request) {
|
|
332
337
|
const url = new URL(request.url);
|
|
@@ -349,7 +354,7 @@ export async function runWatcher(): Promise<void> {
|
|
|
349
354
|
try {
|
|
350
355
|
await saveRecord({ phase: "running", token, nonce, instanceID: instanceID!, pid: process.pid, port: controlServer.port, createdAt });
|
|
351
356
|
} catch (error) {
|
|
352
|
-
controlServer.
|
|
357
|
+
await controlServer.close();
|
|
353
358
|
await removeRecord(token, nonce);
|
|
354
359
|
releaseWatcherClaim(profile(), instanceID!);
|
|
355
360
|
throw error;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { Database } from "bun:sqlite";
|
|
2
1
|
import { chmodSync, mkdirSync } from "node:fs";
|
|
3
2
|
import os from "node:os";
|
|
4
3
|
import path from "node:path";
|
|
4
|
+
import { Database, isBusyError } from "./sqlite.ts";
|
|
5
5
|
|
|
6
6
|
const databases = new Map<string, Database>();
|
|
7
7
|
const pause = (ms: number) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
@@ -14,8 +14,7 @@ function initialize(db: Database): void {
|
|
|
14
14
|
return;
|
|
15
15
|
} catch (error) {
|
|
16
16
|
try { db.exec("ROLLBACK"); } catch { /* No transaction remained open. */ }
|
|
17
|
-
|
|
18
|
-
if (!/SQLITE_(BUSY|LOCKED)/.test(err.code ?? "") || attempt >= 7) throw error;
|
|
17
|
+
if (!isBusyError(error) || attempt >= 7) throw error;
|
|
19
18
|
pause(Math.min(20 * 2 ** attempt, 250));
|
|
20
19
|
}
|
|
21
20
|
}
|
|
@@ -78,8 +77,7 @@ function immediate<T>(fn: (db: Database) => T): T {
|
|
|
78
77
|
for (let attempt = 0; ; attempt++) {
|
|
79
78
|
try { return db.transaction(() => fn(db)).immediate(); }
|
|
80
79
|
catch (error) {
|
|
81
|
-
|
|
82
|
-
if (!/SQLITE_(BUSY|LOCKED)/.test(err.code ?? "") || attempt >= 7) throw error;
|
|
80
|
+
if (!isBusyError(error) || attempt >= 7) throw error;
|
|
83
81
|
pause(Math.min(20 * 2 ** attempt, 250));
|
|
84
82
|
}
|
|
85
83
|
}
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { Database } from "bun:sqlite";
|
|
2
1
|
import { randomUUID } from "node:crypto";
|
|
3
2
|
import { chmodSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
4
3
|
import path from "node:path";
|
|
@@ -6,6 +5,7 @@ import RoomService, { type Message, type Room, type Participant } from "../rooms
|
|
|
6
5
|
import type { MessageReceipt, PresenceReport, ReceiptEvidence, ReceiptIdentity, ReceiptWriteResult, Registry, RegistryEntry } from "./store.ts";
|
|
7
6
|
import { presenceOwnerMatches, receiptOwnerMatches } from "./member-state.ts";
|
|
8
7
|
import { isRoomAdmin } from "./roles.ts";
|
|
8
|
+
import { Database, isBusyError } from "./sqlite.ts";
|
|
9
9
|
|
|
10
10
|
type State = { rooms: Room[]; registry: Registry };
|
|
11
11
|
type Page<T> = { items: T[]; hasMore: boolean };
|
|
@@ -91,7 +91,7 @@ async function initialize(file: string): Promise<Database> {
|
|
|
91
91
|
db.exec("PRAGMA busy_timeout=50;");
|
|
92
92
|
return db;
|
|
93
93
|
} catch (error) {
|
|
94
|
-
if (!
|
|
94
|
+
if (!isBusyError(error) || attempt >= 7) throw error;
|
|
95
95
|
await pause(Math.min(20 * 2 ** attempt, 250));
|
|
96
96
|
}
|
|
97
97
|
}
|
|
@@ -131,6 +131,14 @@ export async function putResource(file: string, resource: StoredResource): Promi
|
|
|
131
131
|
return true;
|
|
132
132
|
});
|
|
133
133
|
}
|
|
134
|
+
export async function listResources(file: string, roomID: string, limit = 500, offset = 0): Promise<{ items: StoredResource[]; total: number }> {
|
|
135
|
+
const db = await initialize(file);
|
|
136
|
+
const items = db.query("SELECT id,room_id AS roomID,name,mime_type AS mimeType,size,created_at AS createdAt,uploader_session_id AS uploaderSessionID,uploader_name AS uploaderName FROM resources WHERE room_id=? ORDER BY created_at DESC, id DESC LIMIT ? OFFSET ?")
|
|
137
|
+
.all(roomID, limit, offset) as StoredResource[];
|
|
138
|
+
const total = Number((db.query("SELECT COUNT(*) AS count FROM resources WHERE room_id=?").get(roomID) as { count: number } | null)?.count ?? 0);
|
|
139
|
+
return { items, total };
|
|
140
|
+
}
|
|
141
|
+
|
|
134
142
|
export async function getResource(file: string, roomID: string, id: string): Promise<StoredResource | undefined> {
|
|
135
143
|
const db = await openStateDatabase(file);
|
|
136
144
|
const row = db.query("SELECT id,room_id AS roomID,name,mime_type AS mimeType,size,created_at AS createdAt,uploader_session_id AS uploaderSessionID,uploader_name AS uploaderName FROM resources WHERE room_id=? AND id=?")
|
|
@@ -203,16 +211,12 @@ function readLegacy(file: string): unknown | undefined {
|
|
|
203
211
|
}
|
|
204
212
|
|
|
205
213
|
const pause = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
206
|
-
function isBusy(error: unknown): boolean {
|
|
207
|
-
const err = error as { code?: string; message?: string };
|
|
208
|
-
return err.code === "SQLITE_BUSY" || err.code === "SQLITE_LOCKED" || /database is locked/i.test(err.message ?? "");
|
|
209
|
-
}
|
|
210
214
|
|
|
211
215
|
async function immediate<T>(db: Database, fn: () => T): Promise<T> {
|
|
212
216
|
for (let attempt = 0; ; attempt++) {
|
|
213
217
|
try { return db.transaction(fn).immediate(); }
|
|
214
218
|
catch (error) {
|
|
215
|
-
if (!
|
|
219
|
+
if (!isBusyError(error) || attempt >= 7) throw error;
|
|
216
220
|
await pause(Math.min(20 * 2 ** attempt, 250));
|
|
217
221
|
}
|
|
218
222
|
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { DatabaseSync, type StatementSync } from "node:sqlite";
|
|
2
|
+
|
|
3
|
+
// The subset of bun:sqlite that this codebase uses, backed by node:sqlite so the
|
|
4
|
+
// same synchronous driver runs on Node, Bun and Deno.
|
|
5
|
+
export type SQLQueryBindings = null | number | bigint | string | boolean | Uint8Array | undefined;
|
|
6
|
+
export type RunResult = { changes: number; lastInsertRowid: number };
|
|
7
|
+
type RawBindings = Array<null | number | bigint | string | Uint8Array>;
|
|
8
|
+
|
|
9
|
+
// bun:sqlite binds booleans as 1/0 and undefined as NULL; node:sqlite rejects both.
|
|
10
|
+
function bindings(params: SQLQueryBindings[]): RawBindings {
|
|
11
|
+
let values: SQLQueryBindings[] | undefined;
|
|
12
|
+
for (let index = 0; index < params.length; index++) {
|
|
13
|
+
const value = params[index];
|
|
14
|
+
if (value === undefined || typeof value === "boolean") {
|
|
15
|
+
values ??= params.slice();
|
|
16
|
+
values[index] = value === undefined ? null : value ? 1 : 0;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
return (values ?? params) as RawBindings;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export class Statement {
|
|
23
|
+
readonly #statement: StatementSync;
|
|
24
|
+
constructor(statement: StatementSync) { this.#statement = statement; }
|
|
25
|
+
all(...params: SQLQueryBindings[]): unknown[] {
|
|
26
|
+
return this.#statement.all(...bindings(params));
|
|
27
|
+
}
|
|
28
|
+
// bun:sqlite returns null for a missing row, node:sqlite returns undefined.
|
|
29
|
+
get(...params: SQLQueryBindings[]): unknown {
|
|
30
|
+
return this.#statement.get(...bindings(params)) ?? null;
|
|
31
|
+
}
|
|
32
|
+
run(...params: SQLQueryBindings[]): RunResult {
|
|
33
|
+
const result = this.#statement.run(...bindings(params));
|
|
34
|
+
return { changes: Number(result.changes), lastInsertRowid: Number(result.lastInsertRowid) };
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export type Transaction<T> = (() => T) & { deferred(): T; immediate(): T };
|
|
39
|
+
|
|
40
|
+
export class Database {
|
|
41
|
+
readonly #db: DatabaseSync;
|
|
42
|
+
#savepoints = 0;
|
|
43
|
+
|
|
44
|
+
// node:sqlite always creates a missing file, matching the default Bun options.
|
|
45
|
+
constructor(file: string, _options?: { create?: boolean }) {
|
|
46
|
+
this.#db = new DatabaseSync(file);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
query(sql: string): Statement { return new Statement(this.#db.prepare(sql)); }
|
|
50
|
+
exec(sql: string): void { this.#db.exec(sql); }
|
|
51
|
+
|
|
52
|
+
transaction<T>(fn: () => T): Transaction<T> {
|
|
53
|
+
const run = (begin: string) => this.#run(begin, fn);
|
|
54
|
+
return Object.assign(() => run("BEGIN"), { deferred: () => run("BEGIN"), immediate: () => run("BEGIN IMMEDIATE") });
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
close(): void { this.#db.close(); }
|
|
58
|
+
|
|
59
|
+
#run<T>(begin: string, fn: () => T): T {
|
|
60
|
+
// Nested calls become savepoints, like bun:sqlite transactions.
|
|
61
|
+
const nested = this.#db.isTransaction;
|
|
62
|
+
const savepoint = `chat_room_savepoint_${this.#savepoints++}`;
|
|
63
|
+
this.#db.exec(nested ? `SAVEPOINT ${savepoint}` : begin);
|
|
64
|
+
try {
|
|
65
|
+
const result = fn();
|
|
66
|
+
this.#db.exec(nested ? `RELEASE ${savepoint}` : "COMMIT");
|
|
67
|
+
return result;
|
|
68
|
+
} catch (error) {
|
|
69
|
+
try { this.#db.exec(nested ? `ROLLBACK TO ${savepoint}; RELEASE ${savepoint}` : "ROLLBACK"); } catch { /* keep the original error */ }
|
|
70
|
+
throw error;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function isBusyError(error: unknown): boolean {
|
|
76
|
+
const err = error as { code?: string; errcode?: number; message?: string } | null;
|
|
77
|
+
if (!err) return false;
|
|
78
|
+
if (typeof err.errcode === "number" && ((err.errcode & 0xff) === 5 || (err.errcode & 0xff) === 6)) return true;
|
|
79
|
+
return /SQLITE_(BUSY|LOCKED)/.test(err.code ?? "") || /database (?:is|table is) locked/i.test(err.message ?? "");
|
|
80
|
+
}
|
package/src/state/store.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// Shared state facade for the standalone SQLite database.
|
|
2
2
|
// (rooms + registry), identity, and formatting. Used by plugin.ts (standalone
|
|
3
3
|
// mode) and server/chat-server.ts (central mode).
|
|
4
|
+
import { Buffer } from "node:buffer";
|
|
4
5
|
import path from "node:path";
|
|
5
6
|
import os from "node:os";
|
|
6
7
|
import RoomService, { type Message, type Room } from "../rooms/room-service.ts";
|