@alexsun-top/opencode-chat-room 0.8.1 → 0.8.3

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.
Files changed (125) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +18 -62
  3. package/README.zh-CN.md +25 -69
  4. package/dist/cli.js +1008 -274
  5. package/package.json +10 -7
  6. package/packages/chat-room-channeld/README.md +42 -15
  7. package/packages/chat-room-channeld/dist/mock-adapter.js +5 -5
  8. package/packages/chat-room-channeld/src/adapter.ts +150 -7
  9. package/packages/chat-room-channeld/src/cli.ts +72 -5
  10. package/packages/chat-room-channeld/src/host.ts +41 -11
  11. package/packages/chat-room-channeld/src/inbound.ts +13 -4
  12. package/packages/chat-room-channeld/src/pg/database.ts +187 -0
  13. package/packages/chat-room-channeld/src/pg/migrate.ts +150 -0
  14. package/packages/chat-room-channeld/src/pg/schema.ts +60 -0
  15. package/packages/chat-room-channeld/src/pg/sql.mjs +175 -0
  16. package/packages/chat-room-channeld/src/pg/sqlite.ts +100 -0
  17. package/packages/chat-room-channeld/src/pg/worker.mjs +133 -0
  18. package/packages/chat-room-channeld/src/protocol.ts +53 -1
  19. package/packages/chat-room-channeld/src/rules.ts +7 -2
  20. package/packages/chat-room-channeld/src/state.ts +73 -97
  21. package/packages/chat-room-channeld/src/stats.ts +140 -109
  22. package/plugin.ts +1 -1
  23. package/server/assets/base.css +11 -3
  24. package/server/assets/chat/admin-badge.js +32 -30
  25. package/server/assets/chat/admin.js +198 -163
  26. package/server/assets/chat/announcements.js +295 -210
  27. package/server/assets/chat/attachment-store.js +106 -75
  28. package/server/assets/chat/attachments.js +686 -441
  29. package/server/assets/chat/chat-background.js +206 -0
  30. package/server/assets/chat/clipboard.js +44 -25
  31. package/server/assets/chat/confirm-dialog.js +36 -34
  32. package/server/assets/chat/copy-action.js +40 -40
  33. package/server/assets/chat/create-room-dialog.js +50 -48
  34. package/server/assets/chat/diagram-viewer.js +293 -228
  35. package/server/assets/chat/doc-preview.js +510 -388
  36. package/server/assets/chat/editor.js +423 -335
  37. package/server/assets/chat/events.js +637 -502
  38. package/server/assets/chat/files.js +476 -426
  39. package/server/assets/chat/history-loader.js +79 -73
  40. package/server/assets/chat/icons.js +9 -11
  41. package/server/assets/chat/image-zoom.js +239 -169
  42. package/server/assets/chat/index.js +6 -5
  43. package/server/assets/chat/install-prompt.js +86 -66
  44. package/server/assets/chat/integration-account-schema.js +101 -0
  45. package/server/assets/chat/integration-editor.js +162 -153
  46. package/server/assets/chat/integration-values.js +109 -100
  47. package/server/assets/chat/integrations.js +696 -479
  48. package/server/assets/chat/join-requests.js +408 -358
  49. package/server/assets/chat/locales/de.js +193 -194
  50. package/server/assets/chat/locales/es.js +193 -194
  51. package/server/assets/chat/locales/fr.js +193 -194
  52. package/server/assets/chat/locales/index.js +1 -2
  53. package/server/assets/chat/locales/it.js +193 -194
  54. package/server/assets/chat/locales/ja.js +193 -193
  55. package/server/assets/chat/locales/ko.js +193 -193
  56. package/server/assets/chat/markdown-footnotes.js +134 -102
  57. package/server/assets/chat/markdown.js +553 -386
  58. package/server/assets/chat/members.js +236 -197
  59. package/server/assets/chat/mentions.js +157 -133
  60. package/server/assets/chat/message-cache.js +40 -33
  61. package/server/assets/chat/message-polling.js +280 -227
  62. package/server/assets/chat/message-window.js +74 -55
  63. package/server/assets/chat/messages.js +552 -479
  64. package/server/assets/chat/office-preview.js +46 -45
  65. package/server/assets/chat/palette.js +450 -412
  66. package/server/assets/chat/panels.js +94 -58
  67. package/server/assets/chat/pwa.js +144 -73
  68. package/server/assets/chat/questions.js +372 -302
  69. package/server/assets/chat/recall.js +320 -273
  70. package/server/assets/chat/receipts.js +149 -122
  71. package/server/assets/chat/reminders.js +331 -216
  72. package/server/assets/chat/replies.js +165 -136
  73. package/server/assets/chat/resource-format.js +59 -62
  74. package/server/assets/chat/room-list.js +58 -55
  75. package/server/assets/chat/room-watcher.js +72 -50
  76. package/server/assets/chat/rooms.js +623 -505
  77. package/server/assets/chat/search.js +136 -114
  78. package/server/assets/chat/settings.js +229 -140
  79. package/server/assets/chat/shiki.js +61 -62
  80. package/server/assets/chat/shortcuts.js +212 -190
  81. package/server/assets/chat/side-pane.js +166 -131
  82. package/server/assets/chat/state.js +851 -707
  83. package/server/assets/chat/system-events.js +55 -27
  84. package/server/assets/chat/system-messages.js +59 -49
  85. package/server/assets/chat/task-form.js +178 -182
  86. package/server/assets/chat/task-row.js +158 -155
  87. package/server/assets/chat/tasks.js +653 -593
  88. package/server/assets/chat/viewport.js +32 -29
  89. package/server/assets/chat/window-controls.js +37 -0
  90. package/server/assets/code-highlight.css +22 -6
  91. package/server/assets/conversation.css +65 -16
  92. package/server/assets/doc-preview.css +6 -1
  93. package/server/assets/files.css +3 -0
  94. package/server/assets/monaco/integration-rules.css +1 -1
  95. package/server/assets/monaco/integration-rules.js +841 -533
  96. package/server/assets/responsive.css +32 -2
  97. package/server/assets/settings.css +117 -13
  98. package/server/assets/window-controls.css +36 -0
  99. package/server/channel-attachments.ts +133 -0
  100. package/server/channel-integration.ts +79 -26
  101. package/server/channels.ts +15 -5
  102. package/server/chat-server.ts +9 -1
  103. package/server/chat.html +73 -38
  104. package/server/manifest.webmanifest +1 -0
  105. package/server/routes/pages.ts +7 -5
  106. package/server/sw.js +346 -267
  107. package/src/center/center-client.ts +1 -1
  108. package/src/state/pg-database.ts +5 -5
  109. package/src/state/pg-migrate.ts +7 -7
  110. package/src/state/pg-worker.mjs +2 -17
  111. package/src/state/sqlite-database.ts +14 -5
  112. package/src/state/sqlite-rooms.ts +130 -23
  113. package/src/state/sqlite-state-store.ts +6 -5
  114. package/src/state/sqlite.ts +3 -3
  115. package/src/web/integration-rules-editor.ts +141 -5
  116. package/src/web/integration-rules.ts +6 -2
  117. package/src/web/integration-schema.ts +7 -6
  118. package/packages/chat-room-channeld/dist/feishu-adapter.js +0 -1262
  119. package/packages/chat-room-channeld/src/feishu-adapter.ts +0 -303
  120. package/packages/chat-room-channeld/src/feishu-card.ts +0 -27
  121. package/packages/chat-room-channeld/src/feishu-inbound.ts +0 -158
  122. package/packages/chat-room-channeld/src/feishu-live.ts +0 -355
  123. package/packages/chat-room-channeld/src/feishu-send.ts +0 -342
  124. package/packages/chat-room-channeld/src/feishu-ws-frames.ts +0 -173
  125. package/server/assets/chat/forward.js +0 -69
@@ -15,12 +15,21 @@ export function matchInboundRoutes(config: ChannelConfig, event: IngestEvent): I
15
15
 
16
16
  /**
17
17
  * Room-notification text. The native user id is opaque but stable; the account
18
- * label shows which Feishu bot and avoids exposing the chat id in room content.
18
+ * label shows which external bot and avoids exposing the chat id in room content.
19
19
  */
20
+ export function platformLabel(platform: string): string {
21
+ const value = platform.trim();
22
+ return value ? value[0]!.toUpperCase() + value.slice(1) : "Channel";
23
+ }
24
+
20
25
  export function inboundRoomText(event: IngestEvent, route: InboundRoute): string | undefined {
21
26
  const text = event.content?.text?.trim();
22
- if (!text) return undefined;
27
+ const attachments = event.content?.attachments ?? [];
28
+ if (!text && attachments.length === 0) return undefined;
23
29
  const actor = event.actor.nativeUserId || "unknown";
24
- const body = text.length > MAX_RELAY_TEXT ? `${text.slice(0, MAX_RELAY_TEXT)}…` : text;
25
- return `[Feishu ${route.from.account}] ${actor}: ${body}`;
30
+ const messageID = event.message?.nativeMessageId ?? event.providerEventId ?? "unknown";
31
+ const names = attachments.map((attachment) =>
32
+ attachment.kind === "image" ? "[image]" : `[file ${attachment.name}]`).join(", ");
33
+ const body = text ? (text.length > MAX_RELAY_TEXT ? `${text.slice(0, MAX_RELAY_TEXT)}…` : text) : names;
34
+ return `[${platformLabel(event.source.platform)} ${route.from.account}] message_id=${messageID} chat_id=${event.source.roomId} sender=${actor}: ${body}`;
26
35
  }
@@ -0,0 +1,187 @@
1
+ import { existsSync } from "node:fs";
2
+ import { MessageChannel, receiveMessageOnPort, Worker, type MessagePort } from "node:worker_threads";
3
+ import { fileURLToPath } from "node:url";
4
+ import type { QueryStatement, SQLQueryBindings, StateDatabase, Transaction } from "./sqlite.ts";
5
+
6
+ // Synchronous facade over a PostgreSQL connection. Every call blocks the
7
+ // calling thread on a SharedArrayBuffer while a worker thread performs the
8
+ // network I/O. The state layer is synchronous by design, so this preserves its
9
+ // transaction boundaries without turning 100+ call sites into async code.
10
+ //
11
+ // Channel D uses PostgreSQL as a single-instance durable backend selected by
12
+ // CHAT_ROOM_DATABASE_URL. Writers serialize per transaction with an advisory
13
+ // xact lock so a stray second process cannot interleave writes.
14
+
15
+ type Reply = {
16
+ id: number;
17
+ ok: boolean;
18
+ rows?: unknown[];
19
+ row?: unknown;
20
+ changes?: number;
21
+ lastInsertRowid?: number;
22
+ error?: Record<string, unknown>;
23
+ };
24
+
25
+ type ReadyMessage = { type: "ready" } | { type: "fatal"; error?: Record<string, unknown> };
26
+
27
+ function workerURL(): URL {
28
+ const candidates = [
29
+ new URL("./worker.mjs", import.meta.url), // dist/pg/database.js
30
+ new URL("../packages/chat-room-channeld/src/pg/worker.mjs", import.meta.url), // bundled dist/cli.js + npm package
31
+ new URL("../packages/chat-room-channeld/dist/pg/worker.mjs", import.meta.url), // container with built dist
32
+ new URL("../../src/pg/worker.mjs", import.meta.url), // package src layout
33
+ ];
34
+ for (const candidate of candidates) if (existsSync(fileURLToPath(candidate))) return candidate;
35
+ return candidates[0]!;
36
+ }
37
+
38
+ function databaseError(error: Record<string, unknown> | undefined): Error {
39
+ const result = new Error(String(error?.message ?? "PostgreSQL query failed"));
40
+ Object.assign(result, error);
41
+ return result;
42
+ }
43
+
44
+ export class PgDatabase implements StateDatabase {
45
+ readonly #worker: Worker;
46
+ readonly #port: MessagePort;
47
+ readonly #timeout: number;
48
+ readonly #lockTimeout: number;
49
+ #nextID = 1;
50
+ #depth = 0;
51
+ #savepoints = 0;
52
+ #broken: Error | undefined;
53
+ #closed = false;
54
+
55
+ constructor(connectionString: string, options: { timeout?: number } = {}) {
56
+ if (!connectionString) throw new Error("PostgreSQL connection string is empty");
57
+ this.#timeout = options.timeout ?? 5_000;
58
+ this.#lockTimeout = Math.max(1, this.#timeout - 1_000);
59
+ const ready = new SharedArrayBuffer(4);
60
+ const { port1, port2 } = new MessageChannel();
61
+ this.#port = port1;
62
+ this.#worker = new Worker(workerURL());
63
+ this.#worker.unref();
64
+ this.#port.unref();
65
+ try {
66
+ // No workerData: some Bun versions break `pg` when a worker starts with
67
+ // any workerData. The default worker channel carries one init message
68
+ // and transfers the request port.
69
+ this.#worker.postMessage({
70
+ type: "init",
71
+ connectionString,
72
+ ready,
73
+ statementTimeout: Math.max(1, this.#timeout - 500),
74
+ port: port2,
75
+ }, [port2]);
76
+ } catch (error) {
77
+ void this.#worker.terminate();
78
+ this.#port.close();
79
+ throw error;
80
+ }
81
+ const status = Atomics.wait(new Int32Array(ready), 0, 0, this.#timeout);
82
+ if (status === "timed-out") {
83
+ void this.#worker.terminate();
84
+ throw new Error(`PostgreSQL bridge did not become ready within ${this.#timeout}ms`);
85
+ }
86
+ const message = receiveMessageOnPort(this.#port)?.message as ReadyMessage | undefined;
87
+ if (message?.type === "fatal") {
88
+ void this.#worker.terminate();
89
+ throw databaseError(message.error);
90
+ }
91
+ }
92
+
93
+ query(sql: string): QueryStatement {
94
+ return {
95
+ all: (...params: SQLQueryBindings[]) => this.#request("all", sql, params).rows as unknown[],
96
+ get: (...params: SQLQueryBindings[]) => this.#request("get", sql, params).row as unknown,
97
+ run: (...params: SQLQueryBindings[]) => {
98
+ const result = this.#request("run", sql, params);
99
+ return { changes: result.changes ?? 0, lastInsertRowid: result.lastInsertRowid ?? 0 };
100
+ },
101
+ };
102
+ }
103
+
104
+ prepare(sql: string): QueryStatement { return this.query(sql); }
105
+
106
+ exec(sql: string): void { this.#request("exec", sql, []); }
107
+
108
+ transaction<T>(fn: () => T): Transaction<T> {
109
+ const run = (immediate: boolean) => this.#run(fn, immediate);
110
+ return Object.assign(() => run(false), {
111
+ deferred: () => run(false),
112
+ immediate: () => run(true),
113
+ });
114
+ }
115
+
116
+ close(): void {
117
+ if (this.#closed) return;
118
+ this.#closed = true;
119
+ const signal = new SharedArrayBuffer(4);
120
+ try {
121
+ this.#port.postMessage({ type: "close", signal });
122
+ // Give client.end() time to flush before a caller opens the next
123
+ // connection (migration and restart tests rely on it).
124
+ Atomics.wait(new Int32Array(signal), 0, 0, 2_000);
125
+ } catch { /* worker already gone */ }
126
+ this.#port.close();
127
+ void this.#worker.terminate();
128
+ }
129
+
130
+ #run<T>(fn: () => T, immediate: boolean): T {
131
+ const nested = this.#depth > 0;
132
+ const savepoint = `chat_room_savepoint_${this.#savepoints++}`;
133
+ if (nested) {
134
+ this.exec(`SAVEPOINT ${savepoint}`);
135
+ } else {
136
+ // Deferred reads need one stable snapshot; immediate writers are
137
+ // serialized by the transaction-level advisory lock.
138
+ this.exec(immediate ? "BEGIN" : "BEGIN ISOLATION LEVEL REPEATABLE READ");
139
+ if (immediate) {
140
+ try {
141
+ this.exec(`SET LOCAL lock_timeout = '${this.#lockTimeout}ms'; SELECT pg_advisory_xact_lock(hashtext('channeld-state')); SET LOCAL lock_timeout = 0`);
142
+ } catch (error) {
143
+ try { this.exec("ROLLBACK"); } catch { /* keep the original error */ }
144
+ throw error;
145
+ }
146
+ }
147
+ }
148
+ this.#depth++;
149
+ try {
150
+ const result = fn();
151
+ this.exec(nested ? `RELEASE ${savepoint}` : "COMMIT");
152
+ return result;
153
+ } catch (error) {
154
+ try {
155
+ this.exec(nested ? `ROLLBACK TO ${savepoint}; RELEASE ${savepoint}` : "ROLLBACK");
156
+ } catch { /* keep the original error */ }
157
+ throw error;
158
+ } finally {
159
+ this.#depth--;
160
+ }
161
+ }
162
+
163
+ #request(mode: "all" | "get" | "run" | "exec", sql: string, params: SQLQueryBindings[]): Reply {
164
+ if (this.#broken) throw this.#broken;
165
+ if (this.#closed) throw new Error("PostgreSQL database is closed");
166
+ const id = this.#nextID++;
167
+ const signal = new SharedArrayBuffer(4);
168
+ this.#port.postMessage({ id, mode, sql, params, signal });
169
+ const status = Atomics.wait(new Int32Array(signal), 0, 0, this.#timeout);
170
+ if (status === "timed-out") {
171
+ // The worker may still be inside the query. Its connection and queue are
172
+ // no longer trustworthy, so fail closed rather than desynchronize later calls.
173
+ this.#broken = Object.assign(
174
+ new Error(`PostgreSQL bridge timed out after ${this.#timeout}ms; the database connection must be reopened`),
175
+ { code: "PG_BRIDGE_TIMEOUT" },
176
+ );
177
+ throw this.#broken;
178
+ }
179
+ const message = receiveMessageOnPort(this.#port)?.message as Reply | undefined;
180
+ if (!message || message.id !== id) {
181
+ this.#broken = Object.assign(new Error("PostgreSQL bridge reply out of sequence"), { code: "PG_BRIDGE_SEQUENCE" });
182
+ throw this.#broken;
183
+ }
184
+ if (!message.ok) throw databaseError(message.error);
185
+ return message;
186
+ }
187
+ }
@@ -0,0 +1,150 @@
1
+ import { existsSync } from "node:fs";
2
+ import { PgDatabase } from "./database.ts";
3
+ import { initializeChannelSchema } from "./schema.ts";
4
+ import { Database, type SQLQueryBindings, type StateDatabase } from "./sqlite.ts";
5
+
6
+ // One-shot SQLite -> PostgreSQL copy for Channel D. Stop the relay host first:
7
+ // this takes a SQLite write lock, but nothing blocks a running PostgreSQL writer.
8
+ // Rollback is unsetting CHAT_ROOM_DATABASE_URL; the SQLite file is never modified.
9
+
10
+ export type MigrationReport = { tables: Array<{ table: string; rows: number }> };
11
+
12
+ const TABLES = ["channel_events", "channel_deliveries", "channel_receipts", "channel_echoes"] as const;
13
+
14
+ const COLUMNS: Record<(typeof TABLES)[number], string[]> = {
15
+ channel_events: ["event_id", "dedup_key", "payload", "ingress_seq", "committed_at"],
16
+ channel_deliveries: [
17
+ "delivery_id", "event_id", "rule_id", "rule_version", "target", "idempotency_key", "payload",
18
+ "state", "attempt_count", "next_attempt_at", "last_error", "provider_message", "created_at", "updated_at",
19
+ ],
20
+ channel_receipts: [
21
+ "receipt_id", "delivery_id", "attempt_id", "state", "provider_message", "detail", "observed_at",
22
+ ],
23
+ channel_echoes: ["endpoint", "native_message_id", "logical_message_id", "delivery_id", "created_at"],
24
+ };
25
+
26
+ const quote = (name: string) => `"${name.replace(/"/g, '""')}"`;
27
+
28
+ function rowCount(db: StateDatabase, table: string): number {
29
+ const row = db.query(`SELECT COUNT(*) AS count FROM ${quote(table)}`).get() as { count: unknown };
30
+ return Number(row.count);
31
+ }
32
+
33
+ function hasTable(db: StateDatabase, table: string): boolean {
34
+ return (db.query("SELECT name FROM sqlite_master WHERE type = 'table'").all() as Array<{ name: unknown }>)
35
+ .some((row) => String(row.name) === table);
36
+ }
37
+
38
+ function assertEmptyTarget(target: PgDatabase): void {
39
+ const tables = target.query(
40
+ "SELECT table_name FROM information_schema.tables WHERE table_schema = current_schema()",
41
+ ).all() as Array<{ table_name: string }>;
42
+ const nonEmpty: string[] = [];
43
+ for (const { table_name: table } of tables) {
44
+ const count = rowCount(target, table);
45
+ if (count > 0) nonEmpty.push(`${table} (${count})`);
46
+ }
47
+ if (nonEmpty.length > 0) {
48
+ throw new Error(`target database is not empty: ${nonEmpty.join(", ")}; migrate into a fresh database`);
49
+ }
50
+ }
51
+
52
+ function maxValue(db: StateDatabase, table: string, column: string, binary = false): unknown {
53
+ const expression = binary ? `${quote(column)} COLLATE "C"` : quote(column);
54
+ const row = db.query(`SELECT MAX(${expression}) AS value FROM ${quote(table)}`).get() as { value: unknown };
55
+ return row.value ?? null;
56
+ }
57
+
58
+ function assertMaxima(source: StateDatabase, target: StateDatabase): void {
59
+ const maxColumns: Record<(typeof TABLES)[number], string> = {
60
+ channel_events: "event_id",
61
+ channel_deliveries: "delivery_id",
62
+ channel_receipts: "receipt_id",
63
+ channel_echoes: "native_message_id",
64
+ };
65
+ for (const table of TABLES) {
66
+ const column = maxColumns[table];
67
+ const expected = maxValue(source, table, column);
68
+ const actual = maxValue(target, table, column, true);
69
+ if (String(expected) !== String(actual)) {
70
+ throw new Error(`max ${column} mismatch for ${table}: source ${String(expected)}, target ${String(actual)}`);
71
+ }
72
+ }
73
+ const sourceSeq = maxValue(source, "channel_events", "ingress_seq");
74
+ const targetSeq = maxValue(target, "channel_events", "ingress_seq");
75
+ if (String(sourceSeq) !== String(targetSeq)) {
76
+ throw new Error(`max ingress_seq mismatch: source ${String(sourceSeq)}, target ${String(targetSeq)}`);
77
+ }
78
+ }
79
+
80
+ function copyTable(
81
+ source: StateDatabase,
82
+ target: StateDatabase,
83
+ table: string,
84
+ columns: string[],
85
+ select: string,
86
+ ): number {
87
+ const rows = source.query(`SELECT ${select} FROM ${quote(table)}`).all() as Array<Record<string, unknown>>;
88
+ const insert = target.query(
89
+ `INSERT INTO ${quote(table)} (${columns.map(quote).join(",")}) VALUES (${columns.map(() => "?").join(",")})`,
90
+ );
91
+ for (const row of rows) {
92
+ insert.run(...(columns.map((column) => row[column]) as SQLQueryBindings[]));
93
+ }
94
+ return rows.length;
95
+ }
96
+
97
+ /**
98
+ * Copy the four channel tables into an empty PostgreSQL database, preserving
99
+ * ids and ingress_seq. Throws before writing if the target holds any rows.
100
+ */
101
+ export function migrateToPostgres(sqlitePath: string, url: string): MigrationReport {
102
+ if (!url.trim()) throw new Error("PostgreSQL URL is required");
103
+ if (!existsSync(sqlitePath)) throw new Error(`SQLite state database not found: ${sqlitePath}`);
104
+ const source = new Database(sqlitePath);
105
+ let target: PgDatabase | undefined;
106
+ try {
107
+ target = new PgDatabase(url);
108
+ const destination = target;
109
+ for (const table of TABLES) {
110
+ if (!hasTable(source, table)) throw new Error(`SQLite channel state not found: ${sqlitePath}`);
111
+ }
112
+ assertEmptyTarget(destination);
113
+ initializeChannelSchema(destination);
114
+
115
+ const echoHasCreatedAt = (source.query("PRAGMA table_info(channel_echoes)").all() as Array<{ name: unknown }>)
116
+ .some((column) => column.name === "created_at");
117
+ // Legacy rows predate created_at. rowid preserves their insertion order and
118
+ // stays below epoch timestamps written after the upgrade.
119
+ const echoTimestamp = echoHasCreatedAt
120
+ ? "CASE WHEN created_at IS NULL OR created_at = 0 THEN rowid ELSE created_at END"
121
+ : "rowid";
122
+ const echoColumns = COLUMNS.channel_echoes.filter((column) => column !== "created_at");
123
+ const copies: Array<{ table: string; rows: number }> = [];
124
+
125
+ source.transaction(() => {
126
+ destination.transaction(() => {
127
+ for (const table of TABLES) {
128
+ const columns = COLUMNS[table];
129
+ const select = table === "channel_echoes"
130
+ ? `${echoColumns.join(",")}, ${echoTimestamp} AS created_at`
131
+ : columns.join(",");
132
+ const expected = rowCount(source, table);
133
+ const rows = copyTable(source, destination, table, columns, select);
134
+ const actual = rowCount(destination, table);
135
+ if (rows !== expected || actual !== expected) {
136
+ throw new Error(`row count mismatch for ${table}: source ${expected}, copied ${rows}, target ${actual}`);
137
+ }
138
+ copies.push({ table, rows });
139
+ }
140
+ assertMaxima(source, destination);
141
+ return copies;
142
+ }).immediate();
143
+ }).immediate();
144
+
145
+ return { tables: copies };
146
+ } finally {
147
+ source.close();
148
+ target?.close();
149
+ }
150
+ }
@@ -0,0 +1,60 @@
1
+ import type { StateDatabase } from "./sqlite.ts";
2
+
3
+ export const SCHEMA = `
4
+ CREATE TABLE IF NOT EXISTS channel_events (
5
+ event_id TEXT PRIMARY KEY,
6
+ dedup_key TEXT NOT NULL UNIQUE,
7
+ payload TEXT NOT NULL,
8
+ ingress_seq INTEGER,
9
+ committed_at INTEGER NOT NULL
10
+ );
11
+ CREATE TABLE IF NOT EXISTS channel_deliveries (
12
+ delivery_id TEXT PRIMARY KEY,
13
+ event_id TEXT NOT NULL,
14
+ rule_id TEXT NOT NULL,
15
+ rule_version INTEGER NOT NULL,
16
+ target TEXT NOT NULL,
17
+ idempotency_key TEXT NOT NULL UNIQUE,
18
+ payload TEXT NOT NULL,
19
+ state TEXT NOT NULL,
20
+ attempt_count INTEGER NOT NULL DEFAULT 0,
21
+ next_attempt_at INTEGER,
22
+ last_error TEXT,
23
+ provider_message TEXT,
24
+ created_at INTEGER NOT NULL,
25
+ updated_at INTEGER NOT NULL
26
+ );
27
+ CREATE TABLE IF NOT EXISTS channel_receipts (
28
+ receipt_id TEXT PRIMARY KEY,
29
+ delivery_id TEXT NOT NULL,
30
+ attempt_id TEXT NOT NULL,
31
+ state TEXT NOT NULL,
32
+ provider_message TEXT,
33
+ detail TEXT,
34
+ observed_at INTEGER NOT NULL
35
+ );
36
+ CREATE TABLE IF NOT EXISTS channel_echoes (
37
+ endpoint TEXT NOT NULL,
38
+ native_message_id TEXT NOT NULL,
39
+ logical_message_id TEXT NOT NULL,
40
+ delivery_id TEXT,
41
+ created_at INTEGER NOT NULL DEFAULT 0,
42
+ PRIMARY KEY (endpoint, native_message_id)
43
+ );
44
+ `;
45
+
46
+ /** Create tables, add missing columns, and backfill legacy echo order from rowid. */
47
+ export function initializeChannelSchema(
48
+ db: StateDatabase,
49
+ options: { backfillEchoOrder?: boolean } = {},
50
+ ): void {
51
+ db.exec(SCHEMA);
52
+ const columns = db.query("PRAGMA table_info(channel_echoes)").all() as Array<{ name?: unknown }>;
53
+ if (!columns.some((column) => column.name === "created_at")) {
54
+ db.exec("ALTER TABLE channel_echoes ADD COLUMN created_at INTEGER NOT NULL DEFAULT 0");
55
+ }
56
+ if (options.backfillEchoOrder) {
57
+ // Legacy rows predate created_at; rowid keeps their original insertion order.
58
+ db.exec("UPDATE channel_echoes SET created_at = rowid WHERE created_at = 0");
59
+ }
60
+ }
@@ -0,0 +1,175 @@
1
+ // SQLite -> PostgreSQL translation for the chat-room state SQL. The app's SQL
2
+ // uses ? placeholders, SQLite DDL, a few pragmas and a handful of scalar
3
+ // functions; everything else is deliberately passed through unchanged.
4
+ //
5
+ // This is intentionally not a general SQLite translator. Keep the dialect
6
+ // narrow and add a test when the state layer starts using a new construct.
7
+
8
+ const PRAGMA_TABLE_INFO = /PRAGMA\s+table_info\s*\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\)/gi;
9
+
10
+ function pragmaTableInfo(table) {
11
+ const tableName = table.replace(/'/g, "''");
12
+ return `SELECT c.column_name AS name,c.data_type AS type,` +
13
+ `CASE WHEN c.is_nullable='NO' THEN 1 ELSE 0 END AS "notnull",` +
14
+ `c.column_default AS dflt_value,` +
15
+ `CASE WHEN EXISTS (SELECT 1 FROM pg_index i JOIN pg_attribute a ON a.attrelid=i.indrelid AND a.attnum=ANY(i.indkey) ` +
16
+ `WHERE i.indrelid=(quote_ident(c.table_schema)||'.'||quote_ident(c.table_name))::regclass AND i.indisprimary AND a.attname=c.column_name) ` +
17
+ `THEN 1 ELSE 0 END AS pk ` +
18
+ `FROM information_schema.columns c WHERE c.table_schema=current_schema() AND c.table_name='${tableName}' ORDER BY c.ordinal_position`;
19
+ }
20
+
21
+ const isIdentStart = (ch) => !!ch && /[A-Za-z_]/.test(ch);
22
+ const isIdentChar = (ch) => !!ch && /[A-Za-z0-9_$]/.test(ch);
23
+
24
+ function skipQuoted(sql, index) {
25
+ const quote = sql[index];
26
+ let i = index + 1;
27
+ while (i < sql.length) {
28
+ if (sql[i] === quote) {
29
+ if (sql[i + 1] === quote) { i += 2; continue; }
30
+ return i + 1;
31
+ }
32
+ i++;
33
+ }
34
+ return i;
35
+ }
36
+
37
+ function skipComment(sql, index) {
38
+ if (sql[index + 1] === "-") {
39
+ const end = sql.indexOf("\n", index + 2);
40
+ return end < 0 ? sql.length : end;
41
+ }
42
+ const end = sql.indexOf("*/", index + 2);
43
+ return end < 0 ? sql.length : end + 2;
44
+ }
45
+
46
+ function hasTopLevelComma(sql, openIndex) {
47
+ let depth = 0;
48
+ for (let i = openIndex; i < sql.length; i++) {
49
+ const ch = sql[i];
50
+ if (ch === "'" || ch === '"') { i = skipQuoted(sql, i) - 1; continue; }
51
+ if (ch === "-" && sql[i + 1] === "-") { i = skipComment(sql, i) - 1; continue; }
52
+ if (ch === "/" && sql[i + 1] === "*") { i = skipComment(sql, i) - 1; continue; }
53
+ if (ch === "(") depth++;
54
+ else if (ch === ")") { depth--; if (depth === 0) return false; }
55
+ else if (ch === "," && depth === 1) return true;
56
+ }
57
+ return false;
58
+ }
59
+
60
+ function wordBefore(sql, index) {
61
+ let i = index - 1;
62
+ while (i >= 0 && /\s/.test(sql[i])) i--;
63
+ const end = i + 1;
64
+ while (i >= 0 && isIdentChar(sql[i])) i--;
65
+ return sql.slice(i + 1, end).toLowerCase();
66
+ }
67
+
68
+ function wordAfter(sql, index) {
69
+ let i = index + 1;
70
+ while (i < sql.length && /\s/.test(sql[i])) i++;
71
+ const start = i;
72
+ while (i < sql.length && isIdentChar(sql[i])) i++;
73
+ return sql.slice(start, i).toLowerCase();
74
+ }
75
+
76
+ function scan(sql) {
77
+ let out = "";
78
+ let index = 0;
79
+ let parameter = 0;
80
+ while (index < sql.length) {
81
+ const ch = sql[index];
82
+ if (ch === "'" || ch === '"') {
83
+ const end = skipQuoted(sql, index);
84
+ out += sql.slice(index, end);
85
+ index = end;
86
+ continue;
87
+ }
88
+ if (ch === "-" && sql[index + 1] === "-") {
89
+ const end = skipComment(sql, index);
90
+ out += sql.slice(index, end);
91
+ index = end;
92
+ continue;
93
+ }
94
+ if (ch === "/" && sql[index + 1] === "*") {
95
+ const end = skipComment(sql, index);
96
+ out += sql.slice(index, end);
97
+ index = end;
98
+ continue;
99
+ }
100
+ if (ch === "?") {
101
+ // CASE WHEN ? needs a boolean; a bare `? IS NULL` has no type to infer.
102
+ const nextWord = wordAfter(sql, index);
103
+ const cast = (wordBefore(sql, index) === "when" && nextWord === "then") || nextWord === "is";
104
+ out += `$${++parameter}${cast ? (nextWord === "is" ? "::text" : "::boolean") : ""}`;
105
+ index++;
106
+ continue;
107
+ }
108
+ if (isIdentStart(ch)) {
109
+ let end = index + 1;
110
+ while (isIdentChar(sql[end])) end++;
111
+ const word = sql.slice(index, end);
112
+ const lower = word.toLowerCase();
113
+ // SQLite's scalar max(a,b)/min(a,b); the one-argument aggregate forms stay.
114
+ if (lower === "max" || lower === "min") {
115
+ let next = end;
116
+ while (next < sql.length && /\s/.test(sql[next])) next++;
117
+ if (sql[next] === "(" && hasTopLevelComma(sql, next)) {
118
+ out += lower === "max" ? "GREATEST" : "LEAST";
119
+ index = end;
120
+ continue;
121
+ }
122
+ }
123
+ // Preserve camelCase result aliases: PostgreSQL folds unquoted identifiers.
124
+ if (lower === "as") {
125
+ const previous = wordBefore(sql, index);
126
+ let next = end;
127
+ while (next < sql.length && /\s/.test(sql[next])) next++;
128
+ if (isIdentStart(sql[next])) {
129
+ let aliasEnd = next + 1;
130
+ while (isIdentChar(sql[aliasEnd])) aliasEnd++;
131
+ const alias = sql.slice(next, aliasEnd);
132
+ if (/[A-Z]/.test(alias) && previous !== "default" && alias.toLowerCase() !== "identity") {
133
+ out += `AS "${alias}"`;
134
+ index = aliasEnd;
135
+ continue;
136
+ }
137
+ }
138
+ }
139
+ out += word;
140
+ index = end;
141
+ continue;
142
+ }
143
+ out += ch;
144
+ index++;
145
+ }
146
+ return out;
147
+ }
148
+
149
+ function appendOnConflictDoNothing(sql) {
150
+ return `${sql.replace(/[\s;]+$/, "")} ON CONFLICT DO NOTHING`;
151
+ }
152
+
153
+ export function translate(sql) {
154
+ let text = String(sql);
155
+ // Connection tuning pragmas have no PostgreSQL equivalent; foreign keys are
156
+ // always enforced and concurrency is handled by advisory locks.
157
+ text = text.replace(/PRAGMA\s+(?:busy_timeout|journal_mode|foreign_keys)\s*(?:=\s*[^;]+)?\s*;?/gi, "");
158
+ text = text.replace(PRAGMA_TABLE_INFO, (_, table) => pragmaTableInfo(table));
159
+ // SQLite INTEGER is 64-bit; PostgreSQL INTEGER is 32-bit and epoch
160
+ // milliseconds overflow it.
161
+ text = text.replace(/\bINTEGER\b/gi, "BIGINT");
162
+ text = text.replace(/\bBIGINT\s+PRIMARY\s+KEY\s+AUTOINCREMENT\b/gi, "BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY");
163
+ // Manual `BEGIN IMMEDIATE` appears inside receiver-state's schema script.
164
+ text = text.replace(/\bBEGIN\s+(?:DEFERRED|IMMEDIATE|EXCLUSIVE)\b/gi, "BEGIN");
165
+ if (/\bINSERT\s+OR\s+IGNORE\b/i.test(text)) {
166
+ text = text.replace(/\bINSERT\s+OR\s+IGNORE\b/gi, "INSERT");
167
+ if (!/\bON\s+CONFLICT\b/i.test(text)) text = appendOnConflictDoNothing(text);
168
+ }
169
+ // SQLite treats 1/0 as booleans; PostgreSQL needs an explicit cast.
170
+ return scan(text).trim();
171
+ }
172
+
173
+ export function hasSql(text) {
174
+ return text.replace(/[;\s]/g, "").length > 0;
175
+ }