dsh-postbox 0.0.0-stage → 0.2.1

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.
@@ -0,0 +1,65 @@
1
+ // lib/backend-sqlite.js — 唯一接触 `node:sqlite` 的文件。
2
+ //
3
+ // 为什么要单独一层:`node:sqlite` 在 Node 24 仍是 **experimental**
4
+ // (会打印 ExperimentalWarning,API 可能变)。把它关在这一层,store.js 只依赖下面这三个
5
+ // 方法(exec / prepare / transaction),将来驱动换实现(或降级 JSON 后端)不用动业务代码。
6
+ //
7
+ // 已验证:DSH host 运行时 Node v24.21.0,node:sqlite + WAL + 中文往返均通过。
8
+
9
+ let modPromise = null;
10
+
11
+ /** 载入 node:sqlite,并吞掉它那一条 ExperimentalWarning(不污染 host 日志)。 */
12
+ async function loadSqlite() {
13
+ if (!modPromise) {
14
+ modPromise = (async () => {
15
+ const orig = process.emitWarning;
16
+ process.emitWarning = function (warning, ...rest) {
17
+ const msg = typeof warning === "string" ? warning : warning?.message;
18
+ if (/SQLite/i.test(String(msg ?? ""))) return; // 只吞这一条
19
+ return orig.call(this, warning, ...rest);
20
+ };
21
+ try {
22
+ return await import("node:sqlite");
23
+ } finally {
24
+ process.emitWarning = orig;
25
+ }
26
+ })();
27
+ }
28
+ return modPromise;
29
+ }
30
+
31
+ /** 打开 sqlite 后端。dir 由调用方保证已存在。 */
32
+ export async function openSqliteBackend(dbPath) {
33
+ const { DatabaseSync } = await loadSqlite();
34
+ const db = new DatabaseSync(dbPath);
35
+ db.exec("PRAGMA journal_mode=WAL");
36
+ db.exec("PRAGMA synchronous=NORMAL");
37
+ db.exec("PRAGMA foreign_keys=ON");
38
+
39
+ return {
40
+ kind: "sqlite",
41
+ path: dbPath,
42
+ exec(sql) { db.exec(sql); },
43
+ prepare(sql) {
44
+ const st = db.prepare(sql);
45
+ return {
46
+ run: (...p) => st.run(...p),
47
+ get: (...p) => st.get(...p),
48
+ all: (...p) => st.all(...p),
49
+ };
50
+ },
51
+ /** 事务:回调抛错则整体回滚。 */
52
+ transaction(fn) {
53
+ db.exec("BEGIN");
54
+ try {
55
+ const out = fn();
56
+ db.exec("COMMIT");
57
+ return out;
58
+ } catch (e) {
59
+ try { db.exec("ROLLBACK"); } catch { /* 回滚失败也不能掩盖原错 */ }
60
+ throw e;
61
+ }
62
+ },
63
+ close() { try { db.close(); } catch { /* 已关闭 */ } },
64
+ };
65
+ }