@reinsjs/store-sqlite 0.1.0
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 +22 -0
- package/LICENSE +21 -0
- package/README.md +45 -0
- package/dist/driver-CLJG7byg.d.ts +21 -0
- package/dist/index.d.ts +99 -0
- package/dist/index.js +265 -0
- package/dist/index.js.map +1 -0
- package/dist/node.d.ts +19 -0
- package/dist/node.js +15 -0
- package/dist/node.js.map +1 -0
- package/package.json +49 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# @reinsjs/store-sqlite
|
|
2
|
+
|
|
3
|
+
## 0.1.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- First public release.
|
|
8
|
+
|
|
9
|
+
- **Timeline first.** Append-only event log with `schemaVersion` on every event and fail-closed upcast on read; projection decides what the model sees each turn; replay and fork from the log alone.
|
|
10
|
+
- **A loop you can copy.** `runLoop` as an exported async generator: pause/resume is a return value with a small signed state, bounded retry on transient failures only while nothing has been written, tool pipeline `beforeTool → validate → approval → execute → afterTool`, sub-agent pause bubbling (`Interruption { kind: "subagent" }`).
|
|
11
|
+
- **Brain modules** (`@reinsjs/brain`): perception, compact (with folded-result manifest and `recall`; recommended on after measuring 100% recall at lower token cost on two model families), pins, spill, handoff, memory (`memory_20250818` shape, namespace isolation), approval (deny → ask → allow, fail-closed), budget (five limits, sub-agent usage included).
|
|
12
|
+
- **Lowering** (`@reinsjs/lowering-pi`): Anthropic Messages and OpenAI Responses via pi-ai with a declared loss matrix, trust markers on untrusted content, cache-breakpoint handling.
|
|
13
|
+
- **Serving** (`@reinsjs/server`, `@reinsjs/ui-agui`): Web-standard handler with SSE replay from `lastSeq`, per-session run lock, `authorizeSession` (only `true` allows), AG-UI as the first-class UI protocol.
|
|
14
|
+
- **Stores**: SQLite (`node:sqlite` / `bun:sqlite`) and Postgres (`pg` / PGlite), conformance-tested; configurable memory table for per-role isolation.
|
|
15
|
+
- **Tools**: MCP servers as one socket (`@reinsjs/tools-mcp`, tools bound per run, annotations as defaults not permissions); `asTool(agent)` in `reins`.
|
|
16
|
+
- **TanStack AI** middleware (`@reinsjs/adapter-tanstack-ai`): the brain on TanStack's loop with the log as the single source of truth; idempotent client-message import; runtime check for the approval interrupt.
|
|
17
|
+
- **Eval harness** (`@reinsjs/eval`): fixtures from real recordings, recorded tools, arm-vs-arm runner, metrics, the four-rule gate.
|
|
18
|
+
|
|
19
|
+
### Patch Changes
|
|
20
|
+
|
|
21
|
+
- Updated dependencies
|
|
22
|
+
- @reinsjs/core@0.1.0
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 NewRate Limited
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
# @reinsjs/store-sqlite
|
|
2
|
+
|
|
3
|
+
SQLite-backed `EventLog`, `BlobStore` and `MemoryStore` for [reins](../../README.md). One SQL layer, driver supplied by the runtime: Node 22.13+ ships `node:sqlite`, Bun ships `bun:sqlite`. The main entry has no `node:*` import and only needs an object with `exec(sql)` and `prepare(sql)`.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
pnpm add @reinsjs/store-sqlite
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
// Node
|
|
11
|
+
import { sqliteStores } from "@reinsjs/store-sqlite"
|
|
12
|
+
import { openSqlite } from "@reinsjs/store-sqlite/node"
|
|
13
|
+
|
|
14
|
+
const store = sqliteStores(openSqlite("./agent.db")) // WAL on by default; ":memory:" for tests
|
|
15
|
+
|
|
16
|
+
// Bun
|
|
17
|
+
import { Database } from "bun:sqlite"
|
|
18
|
+
const store = sqliteStores(new Database("./agent.db"))
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
`sqliteStores(db, { memoryTable })` creates the tables if missing and returns `{ log, blobs, memory }`, ready for `createAgent({ store })`.
|
|
22
|
+
|
|
23
|
+
## Layout
|
|
24
|
+
|
|
25
|
+
| table | keyed by | notes |
|
|
26
|
+
| --- | --- | --- |
|
|
27
|
+
| `reins_events` | `session_id, seq` | append-only; `seq` must be contiguous per session (the store enforces it and throws `seq_conflict`) |
|
|
28
|
+
| `reins_blobs` | `session_id, id` | spilled tool results and other large payloads |
|
|
29
|
+
| `reins_memory` (configurable) | `path` | the model's memory files; `memoryTable` lets each role or tenant have its own table |
|
|
30
|
+
|
|
31
|
+
Table names are validated against `^[A-Za-z_][A-Za-z0-9_]{0,62}$` before any SQL is assembled — identifiers cannot be bound as parameters, so this whitelist is the injection guard. Only the memory table is renamable; events and blobs are isolated by `session_id` on purpose.
|
|
32
|
+
|
|
33
|
+
`fork(from, atSeq, to)` copies a session prefix verbatim (ids and `seq` preserved) into an empty session in one statement.
|
|
34
|
+
|
|
35
|
+
## Verified
|
|
36
|
+
|
|
37
|
+
Passes the conformance suite in `@reinsjs/core/testing`. The published `dist` keeps the `node:sqlite` protocol prefix (tsup's default would strip it to a bare `sqlite`, which only fails at runtime — `pnpm check:dist` guards this).
|
|
38
|
+
|
|
39
|
+
Cloudflare Workers are not a target of this package; Durable Objects SQLite would be a separate store.
|
|
40
|
+
|
|
41
|
+
## Documentation
|
|
42
|
+
|
|
43
|
+
`docs/模块盘点/store.md` and `docs/技术方案.md` §5 — in Chinese, at the repository root.
|
|
44
|
+
|
|
45
|
+
MIT © 2026 NewRate Limited.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SQLite 驱动的最小形状。`node:sqlite` 的 `DatabaseSync` 与 `bun:sqlite` 的 `Database` 都天然满足:
|
|
3
|
+
* 同步 API,`exec` 跑无参 SQL,`prepare(sql)` 得到能 `run / all / get` 的语句。
|
|
4
|
+
* 本包只依赖这几个方法,SQL 层一份,驱动由运行时决定(技术方案 S3)。
|
|
5
|
+
*/
|
|
6
|
+
type SqliteValue = null | number | bigint | string | Uint8Array;
|
|
7
|
+
interface SqliteStatement {
|
|
8
|
+
run(...params: SqliteValue[]): unknown;
|
|
9
|
+
all(...params: SqliteValue[]): unknown[];
|
|
10
|
+
get(...params: SqliteValue[]): unknown;
|
|
11
|
+
}
|
|
12
|
+
interface SqliteDatabase {
|
|
13
|
+
exec(sql: string): void;
|
|
14
|
+
prepare(sql: string): SqliteStatement;
|
|
15
|
+
}
|
|
16
|
+
/** 同步事务:抛错即回滚并原样抛出 */
|
|
17
|
+
declare function transaction<T>(db: SqliteDatabase, fn: () => T): T;
|
|
18
|
+
/** node:sqlite / bun:sqlite 的唯一约束错误:两者都把 SQLite 的 errcode 放在不同字段,只认消息更稳 */
|
|
19
|
+
declare function isUniqueViolation(err: unknown): boolean;
|
|
20
|
+
|
|
21
|
+
export { type SqliteDatabase as S, type SqliteStatement as a, type SqliteValue as b, isUniqueViolation as i, transaction as t };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { BlobStore, BlobMeta, EventLog, Event, ReadOptions, MemoryStore, Stores } from '@reinsjs/core';
|
|
2
|
+
import { S as SqliteDatabase } from './driver-CLJG7byg.js';
|
|
3
|
+
export { a as SqliteStatement, b as SqliteValue, i as isUniqueViolation, t as transaction } from './driver-CLJG7byg.js';
|
|
4
|
+
|
|
5
|
+
/** SQLite 大对象存储:字节进 BLOB 列,`slice` 用 substr 在库内切,不把整个 blob 读出来 */
|
|
6
|
+
declare class SqliteBlobStore implements BlobStore {
|
|
7
|
+
private readonly now;
|
|
8
|
+
private readonly stmts;
|
|
9
|
+
constructor(db: SqliteDatabase, now?: () => number);
|
|
10
|
+
put(bytes: Uint8Array | string, meta: {
|
|
11
|
+
mime: string;
|
|
12
|
+
sessionId: string;
|
|
13
|
+
}): Promise<{
|
|
14
|
+
id: string;
|
|
15
|
+
}>;
|
|
16
|
+
get(id: string): Promise<{
|
|
17
|
+
bytes: Uint8Array;
|
|
18
|
+
meta: BlobMeta;
|
|
19
|
+
}>;
|
|
20
|
+
slice(id: string, range: {
|
|
21
|
+
start: number;
|
|
22
|
+
end: number;
|
|
23
|
+
}): Promise<Uint8Array>;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* SQLite 事件日志。契约与内存实现一致(技术方案 §5):
|
|
28
|
+
* append 先整批校验(同会话、从末尾 +1 连续)再在一个事务里写入;读出的事件由 JSON 重新解析,天然是副本。
|
|
29
|
+
*/
|
|
30
|
+
declare class SqliteEventLog implements EventLog {
|
|
31
|
+
private readonly db;
|
|
32
|
+
private readonly stmts;
|
|
33
|
+
constructor(db: SqliteDatabase);
|
|
34
|
+
private lastSeqOf;
|
|
35
|
+
append(events: readonly Event[]): Promise<void>;
|
|
36
|
+
read(sessionId: string, opts?: ReadOptions): AsyncIterable<Event>;
|
|
37
|
+
tail(sessionId: string, n: number): Promise<Event[]>;
|
|
38
|
+
fork(fromSessionId: string, atSeq: number, toSessionId: string): Promise<void>;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
interface SqliteMemoryStoreOptions {
|
|
42
|
+
/** 表名。缺省 `reins_memory`;表必须已存在(构造期就预编译语句,没有表立刻抛) */
|
|
43
|
+
table?: string;
|
|
44
|
+
/** 测试注入时间 */
|
|
45
|
+
now?: () => number;
|
|
46
|
+
}
|
|
47
|
+
/** SQLite 记忆后端:路径 → 文本的 KV。前缀匹配用 substr 而不是 LIKE,免得转义 % 与 _ */
|
|
48
|
+
declare class SqliteMemoryStore implements MemoryStore {
|
|
49
|
+
private readonly stmts;
|
|
50
|
+
private readonly now;
|
|
51
|
+
constructor(db: SqliteDatabase, opts?: SqliteMemoryStoreOptions);
|
|
52
|
+
list(prefix: string): Promise<string[]>;
|
|
53
|
+
read(path: string): Promise<string | null>;
|
|
54
|
+
write(path: string, content: string): Promise<void>;
|
|
55
|
+
delete(path: string): Promise<void>;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** 记忆表缺省名。事件表与 blob 表不可配:它们由 EventLog / BlobStore 的契约唯一确定,隔离靠 session_id */
|
|
59
|
+
declare const DEFAULT_MEMORY_TABLE = "reins_memory";
|
|
60
|
+
/**
|
|
61
|
+
* 表名只认 `字母 / 下划线开头 + 字母数字下划线`,长度 ≤ 63(与 Postgres 的标识符上限对齐,两包同一规则)。
|
|
62
|
+
* 表名会被字面拼进 SQL(SQL 参数绑定不了标识符),这个白名单就是防注入的唯一一道闸;不合规直接抛,不碰数据库。
|
|
63
|
+
*/
|
|
64
|
+
declare function assertTableName(name: string, what?: string): string;
|
|
65
|
+
interface SqliteSchemaOptions {
|
|
66
|
+
/** 记忆表名。缺省 `reins_memory`;多套记忆共用一个库时按表隔离(技术方案 §9.6 隔离第一层) */
|
|
67
|
+
memoryTable?: string;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* 三张表。事件整条存 JSON(`data`),几列壳字段抽出来做主键与查询:
|
|
71
|
+
* - 主键 (session_id, seq):seq 连续由 append 校验,唯一约束是并发写入者的最后一道闸
|
|
72
|
+
* - 不加 STRICT,兼容更老的 SQLite 版本;类型由本包写入端保证
|
|
73
|
+
*/
|
|
74
|
+
declare function sqliteSchemaSql(opts?: SqliteSchemaOptions): string;
|
|
75
|
+
/** 缺省表名的整段 DDL(给自己管迁移的宿主直接执行) */
|
|
76
|
+
declare const SQLITE_SCHEMA_SQL: string;
|
|
77
|
+
/** 建表(幂等)。sqliteStores() 缺省会调;自己管迁移的宿主也可以直接执行 SQLITE_SCHEMA_SQL / sqliteSchemaSql(opts) */
|
|
78
|
+
declare function migrateSqlite(db: {
|
|
79
|
+
exec(sql: string): void;
|
|
80
|
+
}, opts?: SqliteSchemaOptions): void;
|
|
81
|
+
|
|
82
|
+
interface SqliteStoresOptions {
|
|
83
|
+
/** 起步时建表(幂等)。缺省 true;自己管迁移的宿主传 false */
|
|
84
|
+
migrate?: boolean;
|
|
85
|
+
/**
|
|
86
|
+
* 记忆表名,缺省 `reins_memory`。多个 agent 共用一个库、各自一套记忆时,每个传不同的表名;
|
|
87
|
+
* 事件表与 blob 表始终共用(按 session_id 隔离),建表语句随表名同步。
|
|
88
|
+
*/
|
|
89
|
+
memoryTable?: string;
|
|
90
|
+
/** 测试注入时间 */
|
|
91
|
+
now?: () => number;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* 一套 SQLite 存储:`createAgent({ store: sqliteStores(db) })`。
|
|
95
|
+
* db 是 node:sqlite 的 DatabaseSync 或 bun:sqlite 的 Database(Node 下可用 `@reinsjs/store-sqlite/node` 的 openSqlite 打开)。
|
|
96
|
+
*/
|
|
97
|
+
declare function sqliteStores(db: SqliteDatabase, opts?: SqliteStoresOptions): Stores;
|
|
98
|
+
|
|
99
|
+
export { DEFAULT_MEMORY_TABLE, SQLITE_SCHEMA_SQL, SqliteBlobStore, SqliteDatabase, SqliteEventLog, SqliteMemoryStore, type SqliteMemoryStoreOptions, type SqliteSchemaOptions, type SqliteStoresOptions, assertTableName, migrateSqlite, sqliteSchemaSql, sqliteStores };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
// src/blob-store.ts
|
|
2
|
+
import { StoreError, uuidv7 } from "@reinsjs/core";
|
|
3
|
+
var SqliteBlobStore = class {
|
|
4
|
+
constructor(db, now = () => Date.now()) {
|
|
5
|
+
this.now = now;
|
|
6
|
+
this.stmts = {
|
|
7
|
+
insert: db.prepare(
|
|
8
|
+
"INSERT INTO reins_blobs (id, session_id, mime, size, created_at, bytes) VALUES (?, ?, ?, ?, ?, ?)"
|
|
9
|
+
),
|
|
10
|
+
get: db.prepare("SELECT session_id, mime, size, created_at, bytes FROM reins_blobs WHERE id = ?"),
|
|
11
|
+
// substr 对 BLOB 按字节计,起点从 1 起
|
|
12
|
+
slice: db.prepare("SELECT substr(bytes, ?, ?) AS part FROM reins_blobs WHERE id = ?")
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
now;
|
|
16
|
+
stmts;
|
|
17
|
+
async put(bytes, meta) {
|
|
18
|
+
const data = typeof bytes === "string" ? new TextEncoder().encode(bytes) : bytes;
|
|
19
|
+
const id = uuidv7();
|
|
20
|
+
this.stmts.insert.run(id, meta.sessionId, meta.mime, data.byteLength, this.now(), data);
|
|
21
|
+
return { id };
|
|
22
|
+
}
|
|
23
|
+
async get(id) {
|
|
24
|
+
const row = this.stmts.get.get(id);
|
|
25
|
+
if (!row) throw new StoreError("not_found", `blob \u4E0D\u5B58\u5728\uFF1A${id}`, { id });
|
|
26
|
+
return { bytes: new Uint8Array(row.bytes), meta: metaOf(row) };
|
|
27
|
+
}
|
|
28
|
+
async slice(id, range) {
|
|
29
|
+
const start = Math.max(0, Math.floor(range.start));
|
|
30
|
+
const length = Math.max(0, Math.floor(range.end) - start);
|
|
31
|
+
const row = this.stmts.slice.get(start + 1, length, id);
|
|
32
|
+
if (!row) throw new StoreError("not_found", `blob \u4E0D\u5B58\u5728\uFF1A${id}`, { id });
|
|
33
|
+
return row.part ? new Uint8Array(row.part) : new Uint8Array(0);
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
function metaOf(row) {
|
|
37
|
+
return {
|
|
38
|
+
mime: row.mime,
|
|
39
|
+
sessionId: row.session_id,
|
|
40
|
+
size: Number(row.size),
|
|
41
|
+
createdAt: Number(row.created_at)
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// src/driver.ts
|
|
46
|
+
function transaction(db, fn) {
|
|
47
|
+
db.exec("BEGIN IMMEDIATE");
|
|
48
|
+
try {
|
|
49
|
+
const out = fn();
|
|
50
|
+
db.exec("COMMIT");
|
|
51
|
+
return out;
|
|
52
|
+
} catch (err) {
|
|
53
|
+
db.exec("ROLLBACK");
|
|
54
|
+
throw err;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
function isUniqueViolation(err) {
|
|
58
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
59
|
+
return /UNIQUE constraint failed/i.test(message);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// src/event-log.ts
|
|
63
|
+
import { StoreError as StoreError2 } from "@reinsjs/core";
|
|
64
|
+
var READ_PAGE = 500;
|
|
65
|
+
var SqliteEventLog = class {
|
|
66
|
+
constructor(db) {
|
|
67
|
+
this.db = db;
|
|
68
|
+
this.stmts = {
|
|
69
|
+
lastSeq: db.prepare("SELECT COALESCE(MAX(seq), 0) AS last FROM reins_events WHERE session_id = ?"),
|
|
70
|
+
insert: db.prepare(
|
|
71
|
+
"INSERT INTO reins_events (session_id, seq, id, type, at, data) VALUES (?, ?, ?, ?, ?, ?)"
|
|
72
|
+
),
|
|
73
|
+
page: db.prepare(
|
|
74
|
+
"SELECT data FROM reins_events WHERE session_id = ? AND seq >= ? AND seq <= ? ORDER BY seq LIMIT ?"
|
|
75
|
+
),
|
|
76
|
+
tail: db.prepare("SELECT data FROM reins_events WHERE session_id = ? ORDER BY seq DESC LIMIT ?"),
|
|
77
|
+
// fork:原样复制壳字段,只把 JSON 里的 sessionId 换掉
|
|
78
|
+
fork: db.prepare(
|
|
79
|
+
"INSERT INTO reins_events (session_id, seq, id, type, at, data) SELECT ?, seq, id, type, at, json_set(data, '$.sessionId', ?) FROM reins_events WHERE session_id = ? AND seq <= ? ORDER BY seq"
|
|
80
|
+
)
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
db;
|
|
84
|
+
stmts;
|
|
85
|
+
lastSeqOf(sessionId) {
|
|
86
|
+
const row = this.stmts.lastSeq.get(sessionId);
|
|
87
|
+
return Number(row.last);
|
|
88
|
+
}
|
|
89
|
+
async append(events) {
|
|
90
|
+
if (events.length === 0) throw new StoreError2("empty_batch", "append \u7684\u4E8B\u4EF6\u6570\u7EC4\u4E3A\u7A7A");
|
|
91
|
+
const sessionId = events[0].sessionId;
|
|
92
|
+
for (const e of events) {
|
|
93
|
+
if (e.sessionId !== sessionId) {
|
|
94
|
+
throw new StoreError2("session_mismatch", "\u540C\u4E00\u6279 append \u5FC5\u987B\u5C5E\u4E8E\u540C\u4E00\u4E2A\u4F1A\u8BDD", {
|
|
95
|
+
expected: sessionId,
|
|
96
|
+
got: e.sessionId
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
try {
|
|
101
|
+
transaction(this.db, () => {
|
|
102
|
+
let expected = this.lastSeqOf(sessionId) + 1;
|
|
103
|
+
for (const e of events) {
|
|
104
|
+
if (e.seq !== expected) {
|
|
105
|
+
throw new StoreError2("seq_conflict", `\u4F1A\u8BDD ${sessionId} \u671F\u671B seq=${expected}\uFF0C\u6536\u5230 ${e.seq}`, {
|
|
106
|
+
sessionId,
|
|
107
|
+
expected,
|
|
108
|
+
got: e.seq
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
expected++;
|
|
112
|
+
}
|
|
113
|
+
for (const e of events) this.stmts.insert.run(sessionId, e.seq, e.id, e.type, e.at, JSON.stringify(e));
|
|
114
|
+
});
|
|
115
|
+
} catch (err) {
|
|
116
|
+
if (isUniqueViolation(err)) {
|
|
117
|
+
throw new StoreError2("seq_conflict", `\u4F1A\u8BDD ${sessionId} \u7684 seq \u5DF2\u88AB\u522B\u7684\u5199\u5165\u8005\u5360\u7528`, { sessionId });
|
|
118
|
+
}
|
|
119
|
+
throw err;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
async *read(sessionId, opts = {}) {
|
|
123
|
+
let from = Math.max(opts.fromSeq ?? 1, 1);
|
|
124
|
+
const to = opts.toSeq ?? Number.MAX_SAFE_INTEGER;
|
|
125
|
+
while (from <= to) {
|
|
126
|
+
const rows = this.stmts.page.all(sessionId, from, to, READ_PAGE);
|
|
127
|
+
for (const row of rows) yield JSON.parse(row.data);
|
|
128
|
+
if (rows.length < READ_PAGE) return;
|
|
129
|
+
from += rows.length;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
async tail(sessionId, n) {
|
|
133
|
+
if (!Number.isInteger(n) || n < 0)
|
|
134
|
+
throw new StoreError2("invalid_argument", `tail \u7684 n \u5FC5\u987B\u662F\u975E\u8D1F\u6574\u6570\uFF1A${n}`);
|
|
135
|
+
if (n === 0) return [];
|
|
136
|
+
const rows = this.stmts.tail.all(sessionId, n);
|
|
137
|
+
return rows.reverse().map((r) => JSON.parse(r.data));
|
|
138
|
+
}
|
|
139
|
+
async fork(fromSessionId, atSeq, toSessionId) {
|
|
140
|
+
transaction(this.db, () => {
|
|
141
|
+
const lastSeq = this.lastSeqOf(fromSessionId);
|
|
142
|
+
if (!Number.isInteger(atSeq) || atSeq < 1 || atSeq > lastSeq) {
|
|
143
|
+
throw new StoreError2(
|
|
144
|
+
"out_of_range",
|
|
145
|
+
`fork \u70B9 ${atSeq} \u8D85\u51FA\u4F1A\u8BDD ${fromSessionId} \u7684\u8303\u56F4 [1, ${lastSeq}]`,
|
|
146
|
+
{
|
|
147
|
+
fromSessionId,
|
|
148
|
+
atSeq,
|
|
149
|
+
lastSeq
|
|
150
|
+
}
|
|
151
|
+
);
|
|
152
|
+
}
|
|
153
|
+
if (this.lastSeqOf(toSessionId) > 0) {
|
|
154
|
+
throw new StoreError2("target_not_empty", `\u76EE\u6807\u4F1A\u8BDD ${toSessionId} \u5DF2\u6709\u4E8B\u4EF6`, { toSessionId });
|
|
155
|
+
}
|
|
156
|
+
this.stmts.fork.run(toSessionId, toSessionId, fromSessionId, atSeq);
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
|
|
161
|
+
// src/schema.ts
|
|
162
|
+
import { StoreError as StoreError3 } from "@reinsjs/core";
|
|
163
|
+
var DEFAULT_MEMORY_TABLE = "reins_memory";
|
|
164
|
+
function assertTableName(name, what = "memoryTable") {
|
|
165
|
+
if (typeof name !== "string" || !/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(name)) {
|
|
166
|
+
throw new StoreError3("invalid_argument", `${what} \u4E0D\u662F\u5408\u6CD5\u8868\u540D\uFF08^[A-Za-z_][A-Za-z0-9_]{0,62}$\uFF09`, {
|
|
167
|
+
[what]: name
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
return name;
|
|
171
|
+
}
|
|
172
|
+
function sqliteSchemaSql(opts = {}) {
|
|
173
|
+
const memoryTable = assertTableName(opts.memoryTable ?? DEFAULT_MEMORY_TABLE);
|
|
174
|
+
return `
|
|
175
|
+
CREATE TABLE IF NOT EXISTS reins_events (
|
|
176
|
+
session_id TEXT NOT NULL,
|
|
177
|
+
seq INTEGER NOT NULL,
|
|
178
|
+
id TEXT NOT NULL,
|
|
179
|
+
type TEXT NOT NULL,
|
|
180
|
+
at INTEGER NOT NULL,
|
|
181
|
+
data TEXT NOT NULL,
|
|
182
|
+
PRIMARY KEY (session_id, seq)
|
|
183
|
+
);
|
|
184
|
+
CREATE TABLE IF NOT EXISTS reins_blobs (
|
|
185
|
+
id TEXT PRIMARY KEY,
|
|
186
|
+
session_id TEXT NOT NULL,
|
|
187
|
+
mime TEXT NOT NULL,
|
|
188
|
+
size INTEGER NOT NULL,
|
|
189
|
+
created_at INTEGER NOT NULL,
|
|
190
|
+
bytes BLOB NOT NULL
|
|
191
|
+
);
|
|
192
|
+
CREATE TABLE IF NOT EXISTS ${memoryTable} (
|
|
193
|
+
path TEXT PRIMARY KEY,
|
|
194
|
+
content TEXT NOT NULL,
|
|
195
|
+
updated_at INTEGER NOT NULL
|
|
196
|
+
);
|
|
197
|
+
`;
|
|
198
|
+
}
|
|
199
|
+
var SQLITE_SCHEMA_SQL = sqliteSchemaSql();
|
|
200
|
+
function migrateSqlite(db, opts = {}) {
|
|
201
|
+
db.exec(sqliteSchemaSql(opts));
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// src/memory-store.ts
|
|
205
|
+
var SqliteMemoryStore = class {
|
|
206
|
+
stmts;
|
|
207
|
+
now;
|
|
208
|
+
constructor(db, opts = {}) {
|
|
209
|
+
const table = assertTableName(opts.table ?? DEFAULT_MEMORY_TABLE, "table");
|
|
210
|
+
this.now = opts.now ?? (() => Date.now());
|
|
211
|
+
this.stmts = {
|
|
212
|
+
list: db.prepare(`SELECT path FROM ${table} WHERE substr(path, 1, ?) = ? ORDER BY path`),
|
|
213
|
+
read: db.prepare(`SELECT content FROM ${table} WHERE path = ?`),
|
|
214
|
+
write: db.prepare(
|
|
215
|
+
`INSERT INTO ${table} (path, content, updated_at) VALUES (?, ?, ?) ON CONFLICT(path) DO UPDATE SET content = excluded.content, updated_at = excluded.updated_at`
|
|
216
|
+
),
|
|
217
|
+
delete: db.prepare(`DELETE FROM ${table} WHERE path = ?`)
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
async list(prefix) {
|
|
221
|
+
const rows = this.stmts.list.all(prefix.length, prefix);
|
|
222
|
+
return rows.map((r) => r.path);
|
|
223
|
+
}
|
|
224
|
+
async read(path) {
|
|
225
|
+
const row = this.stmts.read.get(path);
|
|
226
|
+
return row ? row.content : null;
|
|
227
|
+
}
|
|
228
|
+
async write(path, content) {
|
|
229
|
+
this.stmts.write.run(path, content, this.now());
|
|
230
|
+
}
|
|
231
|
+
async delete(path) {
|
|
232
|
+
this.stmts.delete.run(path);
|
|
233
|
+
}
|
|
234
|
+
};
|
|
235
|
+
|
|
236
|
+
// src/stores.ts
|
|
237
|
+
function sqliteStores(db, opts = {}) {
|
|
238
|
+
const schema = {};
|
|
239
|
+
const memoryOpts = {};
|
|
240
|
+
if (opts.memoryTable !== void 0) {
|
|
241
|
+
schema.memoryTable = opts.memoryTable;
|
|
242
|
+
memoryOpts.table = opts.memoryTable;
|
|
243
|
+
}
|
|
244
|
+
if (opts.now !== void 0) memoryOpts.now = opts.now;
|
|
245
|
+
if (opts.migrate !== false) migrateSqlite(db, schema);
|
|
246
|
+
return {
|
|
247
|
+
log: new SqliteEventLog(db),
|
|
248
|
+
blobs: new SqliteBlobStore(db, opts.now),
|
|
249
|
+
memory: new SqliteMemoryStore(db, memoryOpts)
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
export {
|
|
253
|
+
DEFAULT_MEMORY_TABLE,
|
|
254
|
+
SQLITE_SCHEMA_SQL,
|
|
255
|
+
SqliteBlobStore,
|
|
256
|
+
SqliteEventLog,
|
|
257
|
+
SqliteMemoryStore,
|
|
258
|
+
assertTableName,
|
|
259
|
+
isUniqueViolation,
|
|
260
|
+
migrateSqlite,
|
|
261
|
+
sqliteSchemaSql,
|
|
262
|
+
sqliteStores,
|
|
263
|
+
transaction
|
|
264
|
+
};
|
|
265
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/blob-store.ts","../src/driver.ts","../src/event-log.ts","../src/schema.ts","../src/memory-store.ts","../src/stores.ts"],"sourcesContent":["import { type BlobMeta, type BlobStore, StoreError, uuidv7 } from \"@reinsjs/core\"\nimport type { SqliteDatabase } from \"./driver.js\"\n\ninterface MetaRow {\n session_id: string\n mime: string\n size: number | bigint\n created_at: number | bigint\n}\n\n/** SQLite 大对象存储:字节进 BLOB 列,`slice` 用 substr 在库内切,不把整个 blob 读出来 */\nexport class SqliteBlobStore implements BlobStore {\n private readonly stmts\n\n constructor(\n db: SqliteDatabase,\n private readonly now: () => number = () => Date.now(),\n ) {\n this.stmts = {\n insert: db.prepare(\n \"INSERT INTO reins_blobs (id, session_id, mime, size, created_at, bytes) VALUES (?, ?, ?, ?, ?, ?)\",\n ),\n get: db.prepare(\"SELECT session_id, mime, size, created_at, bytes FROM reins_blobs WHERE id = ?\"),\n // substr 对 BLOB 按字节计,起点从 1 起\n slice: db.prepare(\"SELECT substr(bytes, ?, ?) AS part FROM reins_blobs WHERE id = ?\"),\n }\n }\n\n async put(bytes: Uint8Array | string, meta: { mime: string; sessionId: string }): Promise<{ id: string }> {\n const data = typeof bytes === \"string\" ? new TextEncoder().encode(bytes) : bytes\n const id = uuidv7()\n this.stmts.insert.run(id, meta.sessionId, meta.mime, data.byteLength, this.now(), data)\n return { id }\n }\n\n async get(id: string): Promise<{ bytes: Uint8Array; meta: BlobMeta }> {\n const row = this.stmts.get.get(id) as (MetaRow & { bytes: Uint8Array }) | undefined\n if (!row) throw new StoreError(\"not_found\", `blob 不存在:${id}`, { id })\n return { bytes: new Uint8Array(row.bytes), meta: metaOf(row) }\n }\n\n async slice(id: string, range: { start: number; end: number }): Promise<Uint8Array> {\n const start = Math.max(0, Math.floor(range.start))\n const length = Math.max(0, Math.floor(range.end) - start)\n const row = this.stmts.slice.get(start + 1, length, id) as { part: Uint8Array | null } | undefined\n if (!row) throw new StoreError(\"not_found\", `blob 不存在:${id}`, { id })\n return row.part ? new Uint8Array(row.part) : new Uint8Array(0)\n }\n}\n\nfunction metaOf(row: MetaRow): BlobMeta {\n return {\n mime: row.mime,\n sessionId: row.session_id,\n size: Number(row.size),\n createdAt: Number(row.created_at),\n }\n}\n","/**\n * SQLite 驱动的最小形状。`node:sqlite` 的 `DatabaseSync` 与 `bun:sqlite` 的 `Database` 都天然满足:\n * 同步 API,`exec` 跑无参 SQL,`prepare(sql)` 得到能 `run / all / get` 的语句。\n * 本包只依赖这几个方法,SQL 层一份,驱动由运行时决定(技术方案 S3)。\n */\nexport type SqliteValue = null | number | bigint | string | Uint8Array\n\nexport interface SqliteStatement {\n run(...params: SqliteValue[]): unknown\n all(...params: SqliteValue[]): unknown[]\n get(...params: SqliteValue[]): unknown\n}\n\nexport interface SqliteDatabase {\n exec(sql: string): void\n prepare(sql: string): SqliteStatement\n}\n\n/** 同步事务:抛错即回滚并原样抛出 */\nexport function transaction<T>(db: SqliteDatabase, fn: () => T): T {\n db.exec(\"BEGIN IMMEDIATE\")\n try {\n const out = fn()\n db.exec(\"COMMIT\")\n return out\n } catch (err) {\n db.exec(\"ROLLBACK\")\n throw err\n }\n}\n\n/** node:sqlite / bun:sqlite 的唯一约束错误:两者都把 SQLite 的 errcode 放在不同字段,只认消息更稳 */\nexport function isUniqueViolation(err: unknown): boolean {\n const message = err instanceof Error ? err.message : String(err)\n return /UNIQUE constraint failed/i.test(message)\n}\n","import { type Event, type EventLog, type ReadOptions, StoreError } from \"@reinsjs/core\"\nimport { isUniqueViolation, type SqliteDatabase, transaction } from \"./driver.js\"\n\n/** 每次分页读取的条数:既不把整条长会话一次拉进内存,也不至于一条一查 */\nconst READ_PAGE = 500\n\ninterface Row {\n data: string\n}\n\n/**\n * SQLite 事件日志。契约与内存实现一致(技术方案 §5):\n * append 先整批校验(同会话、从末尾 +1 连续)再在一个事务里写入;读出的事件由 JSON 重新解析,天然是副本。\n */\nexport class SqliteEventLog implements EventLog {\n private readonly stmts\n\n constructor(private readonly db: SqliteDatabase) {\n this.stmts = {\n lastSeq: db.prepare(\"SELECT COALESCE(MAX(seq), 0) AS last FROM reins_events WHERE session_id = ?\"),\n insert: db.prepare(\n \"INSERT INTO reins_events (session_id, seq, id, type, at, data) VALUES (?, ?, ?, ?, ?, ?)\",\n ),\n page: db.prepare(\n \"SELECT data FROM reins_events WHERE session_id = ? AND seq >= ? AND seq <= ? ORDER BY seq LIMIT ?\",\n ),\n tail: db.prepare(\"SELECT data FROM reins_events WHERE session_id = ? ORDER BY seq DESC LIMIT ?\"),\n // fork:原样复制壳字段,只把 JSON 里的 sessionId 换掉\n fork: db.prepare(\n \"INSERT INTO reins_events (session_id, seq, id, type, at, data) \" +\n \"SELECT ?, seq, id, type, at, json_set(data, '$.sessionId', ?) FROM reins_events \" +\n \"WHERE session_id = ? AND seq <= ? ORDER BY seq\",\n ),\n }\n }\n\n private lastSeqOf(sessionId: string): number {\n const row = this.stmts.lastSeq.get(sessionId) as { last: number | bigint }\n return Number(row.last)\n }\n\n async append(events: readonly Event[]): Promise<void> {\n if (events.length === 0) throw new StoreError(\"empty_batch\", \"append 的事件数组为空\")\n const sessionId = (events[0] as Event).sessionId\n for (const e of events) {\n if (e.sessionId !== sessionId) {\n throw new StoreError(\"session_mismatch\", \"同一批 append 必须属于同一个会话\", {\n expected: sessionId,\n got: e.sessionId,\n })\n }\n }\n try {\n transaction(this.db, () => {\n let expected = this.lastSeqOf(sessionId) + 1\n for (const e of events) {\n if (e.seq !== expected) {\n throw new StoreError(\"seq_conflict\", `会话 ${sessionId} 期望 seq=${expected},收到 ${e.seq}`, {\n sessionId,\n expected,\n got: e.seq,\n })\n }\n expected++\n }\n for (const e of events) this.stmts.insert.run(sessionId, e.seq, e.id, e.type, e.at, JSON.stringify(e))\n })\n } catch (err) {\n // BEGIN IMMEDIATE 下同进程不会撞到,这里兜的是多进程写同一个文件\n if (isUniqueViolation(err)) {\n throw new StoreError(\"seq_conflict\", `会话 ${sessionId} 的 seq 已被别的写入者占用`, { sessionId })\n }\n throw err\n }\n }\n\n async *read(sessionId: string, opts: ReadOptions = {}): AsyncIterable<Event> {\n let from = Math.max(opts.fromSeq ?? 1, 1)\n const to = opts.toSeq ?? Number.MAX_SAFE_INTEGER\n while (from <= to) {\n const rows = this.stmts.page.all(sessionId, from, to, READ_PAGE) as Row[]\n for (const row of rows) yield JSON.parse(row.data) as Event\n if (rows.length < READ_PAGE) return\n from += rows.length\n }\n }\n\n async tail(sessionId: string, n: number): Promise<Event[]> {\n if (!Number.isInteger(n) || n < 0)\n throw new StoreError(\"invalid_argument\", `tail 的 n 必须是非负整数:${n}`)\n if (n === 0) return []\n const rows = this.stmts.tail.all(sessionId, n) as Row[]\n return rows.reverse().map((r) => JSON.parse(r.data) as Event)\n }\n\n async fork(fromSessionId: string, atSeq: number, toSessionId: string): Promise<void> {\n transaction(this.db, () => {\n const lastSeq = this.lastSeqOf(fromSessionId)\n if (!Number.isInteger(atSeq) || atSeq < 1 || atSeq > lastSeq) {\n throw new StoreError(\n \"out_of_range\",\n `fork 点 ${atSeq} 超出会话 ${fromSessionId} 的范围 [1, ${lastSeq}]`,\n {\n fromSessionId,\n atSeq,\n lastSeq,\n },\n )\n }\n if (this.lastSeqOf(toSessionId) > 0) {\n throw new StoreError(\"target_not_empty\", `目标会话 ${toSessionId} 已有事件`, { toSessionId })\n }\n this.stmts.fork.run(toSessionId, toSessionId, fromSessionId, atSeq)\n })\n }\n}\n","import { StoreError } from \"@reinsjs/core\"\n\n/** 记忆表缺省名。事件表与 blob 表不可配:它们由 EventLog / BlobStore 的契约唯一确定,隔离靠 session_id */\nexport const DEFAULT_MEMORY_TABLE = \"reins_memory\"\n\n/**\n * 表名只认 `字母 / 下划线开头 + 字母数字下划线`,长度 ≤ 63(与 Postgres 的标识符上限对齐,两包同一规则)。\n * 表名会被字面拼进 SQL(SQL 参数绑定不了标识符),这个白名单就是防注入的唯一一道闸;不合规直接抛,不碰数据库。\n */\nexport function assertTableName(name: string, what = \"memoryTable\"): string {\n if (typeof name !== \"string\" || !/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(name)) {\n throw new StoreError(\"invalid_argument\", `${what} 不是合法表名(^[A-Za-z_][A-Za-z0-9_]{0,62}$)`, {\n [what]: name,\n })\n }\n return name\n}\n\nexport interface SqliteSchemaOptions {\n /** 记忆表名。缺省 `reins_memory`;多套记忆共用一个库时按表隔离(技术方案 §9.6 隔离第一层) */\n memoryTable?: string\n}\n\n/**\n * 三张表。事件整条存 JSON(`data`),几列壳字段抽出来做主键与查询:\n * - 主键 (session_id, seq):seq 连续由 append 校验,唯一约束是并发写入者的最后一道闸\n * - 不加 STRICT,兼容更老的 SQLite 版本;类型由本包写入端保证\n */\nexport function sqliteSchemaSql(opts: SqliteSchemaOptions = {}): string {\n const memoryTable = assertTableName(opts.memoryTable ?? DEFAULT_MEMORY_TABLE)\n return `\nCREATE TABLE IF NOT EXISTS reins_events (\n session_id TEXT NOT NULL,\n seq INTEGER NOT NULL,\n id TEXT NOT NULL,\n type TEXT NOT NULL,\n at INTEGER NOT NULL,\n data TEXT NOT NULL,\n PRIMARY KEY (session_id, seq)\n);\nCREATE TABLE IF NOT EXISTS reins_blobs (\n id TEXT PRIMARY KEY,\n session_id TEXT NOT NULL,\n mime TEXT NOT NULL,\n size INTEGER NOT NULL,\n created_at INTEGER NOT NULL,\n bytes BLOB NOT NULL\n);\nCREATE TABLE IF NOT EXISTS ${memoryTable} (\n path TEXT PRIMARY KEY,\n content TEXT NOT NULL,\n updated_at INTEGER NOT NULL\n);\n`\n}\n\n/** 缺省表名的整段 DDL(给自己管迁移的宿主直接执行) */\nexport const SQLITE_SCHEMA_SQL = sqliteSchemaSql()\n\n/** 建表(幂等)。sqliteStores() 缺省会调;自己管迁移的宿主也可以直接执行 SQLITE_SCHEMA_SQL / sqliteSchemaSql(opts) */\nexport function migrateSqlite(db: { exec(sql: string): void }, opts: SqliteSchemaOptions = {}): void {\n db.exec(sqliteSchemaSql(opts))\n}\n","import type { MemoryStore } from \"@reinsjs/core\"\nimport type { SqliteDatabase } from \"./driver.js\"\nimport { assertTableName, DEFAULT_MEMORY_TABLE } from \"./schema.js\"\n\nexport interface SqliteMemoryStoreOptions {\n /** 表名。缺省 `reins_memory`;表必须已存在(构造期就预编译语句,没有表立刻抛) */\n table?: string\n /** 测试注入时间 */\n now?: () => number\n}\n\n/** SQLite 记忆后端:路径 → 文本的 KV。前缀匹配用 substr 而不是 LIKE,免得转义 % 与 _ */\nexport class SqliteMemoryStore implements MemoryStore {\n private readonly stmts\n private readonly now: () => number\n\n constructor(db: SqliteDatabase, opts: SqliteMemoryStoreOptions = {}) {\n // 表名字面拼进 SQL,先过白名单(schema.ts 同一条规则)\n const table = assertTableName(opts.table ?? DEFAULT_MEMORY_TABLE, \"table\")\n this.now = opts.now ?? (() => Date.now())\n this.stmts = {\n list: db.prepare(`SELECT path FROM ${table} WHERE substr(path, 1, ?) = ? ORDER BY path`),\n read: db.prepare(`SELECT content FROM ${table} WHERE path = ?`),\n write: db.prepare(\n `INSERT INTO ${table} (path, content, updated_at) VALUES (?, ?, ?) ` +\n \"ON CONFLICT(path) DO UPDATE SET content = excluded.content, updated_at = excluded.updated_at\",\n ),\n delete: db.prepare(`DELETE FROM ${table} WHERE path = ?`),\n }\n }\n\n async list(prefix: string): Promise<string[]> {\n const rows = this.stmts.list.all(prefix.length, prefix) as { path: string }[]\n return rows.map((r) => r.path)\n }\n\n async read(path: string): Promise<string | null> {\n const row = this.stmts.read.get(path) as { content: string } | undefined\n return row ? row.content : null\n }\n\n async write(path: string, content: string): Promise<void> {\n this.stmts.write.run(path, content, this.now())\n }\n\n async delete(path: string): Promise<void> {\n this.stmts.delete.run(path)\n }\n}\n","import type { Stores } from \"@reinsjs/core\"\nimport { SqliteBlobStore } from \"./blob-store.js\"\nimport type { SqliteDatabase } from \"./driver.js\"\nimport { SqliteEventLog } from \"./event-log.js\"\nimport { SqliteMemoryStore, type SqliteMemoryStoreOptions } from \"./memory-store.js\"\nimport { migrateSqlite, type SqliteSchemaOptions } from \"./schema.js\"\n\nexport interface SqliteStoresOptions {\n /** 起步时建表(幂等)。缺省 true;自己管迁移的宿主传 false */\n migrate?: boolean\n /**\n * 记忆表名,缺省 `reins_memory`。多个 agent 共用一个库、各自一套记忆时,每个传不同的表名;\n * 事件表与 blob 表始终共用(按 session_id 隔离),建表语句随表名同步。\n */\n memoryTable?: string\n /** 测试注入时间 */\n now?: () => number\n}\n\n/**\n * 一套 SQLite 存储:`createAgent({ store: sqliteStores(db) })`。\n * db 是 node:sqlite 的 DatabaseSync 或 bun:sqlite 的 Database(Node 下可用 `@reinsjs/store-sqlite/node` 的 openSqlite 打开)。\n */\nexport function sqliteStores(db: SqliteDatabase, opts: SqliteStoresOptions = {}): Stores {\n const schema: SqliteSchemaOptions = {}\n const memoryOpts: SqliteMemoryStoreOptions = {}\n if (opts.memoryTable !== undefined) {\n schema.memoryTable = opts.memoryTable\n memoryOpts.table = opts.memoryTable\n }\n if (opts.now !== undefined) memoryOpts.now = opts.now\n if (opts.migrate !== false) migrateSqlite(db, schema)\n return {\n log: new SqliteEventLog(db),\n blobs: new SqliteBlobStore(db, opts.now),\n memory: new SqliteMemoryStore(db, memoryOpts),\n }\n}\n"],"mappings":";AAAA,SAAwC,YAAY,cAAc;AAW3D,IAAM,kBAAN,MAA2C;AAAA,EAGhD,YACE,IACiB,MAAoB,MAAM,KAAK,IAAI,GACpD;AADiB;AAEjB,SAAK,QAAQ;AAAA,MACX,QAAQ,GAAG;AAAA,QACT;AAAA,MACF;AAAA,MACA,KAAK,GAAG,QAAQ,gFAAgF;AAAA;AAAA,MAEhG,OAAO,GAAG,QAAQ,kEAAkE;AAAA,IACtF;AAAA,EACF;AAAA,EAVmB;AAAA,EAJF;AAAA,EAgBjB,MAAM,IAAI,OAA4B,MAAoE;AACxG,UAAM,OAAO,OAAO,UAAU,WAAW,IAAI,YAAY,EAAE,OAAO,KAAK,IAAI;AAC3E,UAAM,KAAK,OAAO;AAClB,SAAK,MAAM,OAAO,IAAI,IAAI,KAAK,WAAW,KAAK,MAAM,KAAK,YAAY,KAAK,IAAI,GAAG,IAAI;AACtF,WAAO,EAAE,GA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AAG;AAAA,QACR,eAAe,KAAK;AAAA,MAEtB;AAAA,MACA,QAAQ,GAAG,QAAQ,eAAe,KAAK,iBAAiB;AAAA,IAC1D;AAAA,EACF;AAAA,EAEA,MAAM,KAAK,QAAmC;AAC5C,UAAM,OAAO,KAAK,MAAM,KAAK,IAAI,OAAO,QAAQ,MAAM;AACtD,WAAO,KAAK,IAAI,CAAC,MAAM,EAAE,IAAI;AAAA,EAC/B;AAAA,EAEA,MAAM,KAAK,MAAsC;AAC/C,UAAM,MAAM,KAAK,MAAM,KAAK,IAAI,IAAI;AACpC,WAAO,MAAM,IAAI,UAAU;AAAA,EAC7B;AAAA,EAEA,MAAM,MAAM,MAAc,SAAgC;AACxD,SAAK,MAAM,MAAM,IAAI,MAAM,SAAS,KAAK,IAAI,CAAC;AAAA,EAChD;AAAA,EAEA,MAAM,OAAO,MAA6B;AACxC,SAAK,MAAM,OAAO,IAAI,IAAI;AAAA,EAC5B;AACF;;;ACzBO,SAAS,aAAa,IAAoB,OAA4B,CAAC,GAAW;AACvF,QAAM,SAA8B,CAAC;AACrC,QAAM,aAAuC,CAAC;AAC9C,MAAI,KAAK,gBAAgB,QAAW;AAClC,WAAO,cAAc,KAAK;AAC1B,eAAW,QAAQ,KAAK;AAAA,EAC1B;AACA,MAAI,KAAK,QAAQ,OAAW,YAAW,MAAM,KAAK;AAClD,MAAI,KAAK,YAAY,MAAO,eAAc,IAAI,MAAM;AACpD,SAAO;AAAA,IACL,KAAK,IAAI,eAAe,EAAE;AAAA,IAC1B,OAAO,IAAI,gBAAgB,IAAI,KAAK,GAAG;AAAA,IACvC,QAAQ,IAAI,kBAAkB,IAAI,UAAU;AAAA,EAC9C;AACF;","names":["StoreError","StoreError","StoreError"]}
|
package/dist/node.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
2
|
+
import { S as SqliteDatabase } from './driver-CLJG7byg.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* @reinsjs/store-sqlite/node —— 用 Node 22.13+ 内置的 node:sqlite 打开数据库。只有这个子路径出现 `node:*`。
|
|
6
|
+
*
|
|
7
|
+
* 文件库缺省开 WAL 与 5 秒 busy_timeout:多进程(如 server 的多个 worker)写同一个文件时排队而不是立刻报 SQLITE_BUSY。
|
|
8
|
+
* node:sqlite 在 22.x 仍会打一条 ExperimentalWarning,属 Node 行为,本包不吞(宿主可用 --no-warnings)。
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
interface OpenSqliteOptions {
|
|
12
|
+
/** 文件库缺省 true;":memory:" 不适用 */
|
|
13
|
+
wal?: boolean;
|
|
14
|
+
/** 毫秒,缺省 5000 */
|
|
15
|
+
busyTimeoutMs?: number;
|
|
16
|
+
}
|
|
17
|
+
declare function openSqlite(path: string, opts?: OpenSqliteOptions): SqliteDatabase & DatabaseSync;
|
|
18
|
+
|
|
19
|
+
export { type OpenSqliteOptions, openSqlite };
|
package/dist/node.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// src/node.ts
|
|
2
|
+
import { DatabaseSync } from "node:sqlite";
|
|
3
|
+
function openSqlite(path, opts = {}) {
|
|
4
|
+
const db = new DatabaseSync(path);
|
|
5
|
+
if (path !== ":memory:") {
|
|
6
|
+
if (opts.wal !== false) db.exec("PRAGMA journal_mode = WAL");
|
|
7
|
+
db.exec(`PRAGMA busy_timeout = ${Math.max(0, Math.floor(opts.busyTimeoutMs ?? 5e3))}`);
|
|
8
|
+
}
|
|
9
|
+
db.exec("PRAGMA foreign_keys = ON");
|
|
10
|
+
return db;
|
|
11
|
+
}
|
|
12
|
+
export {
|
|
13
|
+
openSqlite
|
|
14
|
+
};
|
|
15
|
+
//# sourceMappingURL=node.js.map
|
package/dist/node.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/node.ts"],"sourcesContent":["/**\n * @reinsjs/store-sqlite/node —— 用 Node 22.13+ 内置的 node:sqlite 打开数据库。只有这个子路径出现 `node:*`。\n *\n * 文件库缺省开 WAL 与 5 秒 busy_timeout:多进程(如 server 的多个 worker)写同一个文件时排队而不是立刻报 SQLITE_BUSY。\n * node:sqlite 在 22.x 仍会打一条 ExperimentalWarning,属 Node 行为,本包不吞(宿主可用 --no-warnings)。\n */\nimport { DatabaseSync } from \"node:sqlite\"\nimport type { SqliteDatabase } from \"./driver.js\"\n\nexport interface OpenSqliteOptions {\n /** 文件库缺省 true;\":memory:\" 不适用 */\n wal?: boolean\n /** 毫秒,缺省 5000 */\n busyTimeoutMs?: number\n}\n\nexport function openSqlite(path: string, opts: OpenSqliteOptions = {}): SqliteDatabase & DatabaseSync {\n const db = new DatabaseSync(path)\n if (path !== \":memory:\") {\n if (opts.wal !== false) db.exec(\"PRAGMA journal_mode = WAL\")\n db.exec(`PRAGMA busy_timeout = ${Math.max(0, Math.floor(opts.busyTimeoutMs ?? 5000))}`)\n }\n db.exec(\"PRAGMA foreign_keys = ON\")\n return db\n}\n"],"mappings":";AAMA,SAAS,oBAAoB;AAUtB,SAAS,WAAW,MAAc,OAA0B,CAAC,GAAkC;AACpG,QAAM,KAAK,IAAI,aAAa,IAAI;AAChC,MAAI,SAAS,YAAY;AACvB,QAAI,KAAK,QAAQ,MAAO,IAAG,KAAK,2BAA2B;AAC3D,OAAG,KAAK,yBAAyB,KAAK,IAAI,GAAG,KAAK,MAAM,KAAK,iBAAiB,GAAI,CAAC,CAAC,EAAE;AAAA,EACxF;AACA,KAAG,KAAK,0BAA0B;AAClC,SAAO;AACT;","names":[]}
|
package/package.json
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@reinsjs/store-sqlite",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "reins — SQLite-backed EventLog / BlobStore / MemoryStore. One SQL layer, driver supplied by the runtime (node:sqlite, bun:sqlite)",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"agent",
|
|
7
|
+
"event-log",
|
|
8
|
+
"sqlite",
|
|
9
|
+
"node-sqlite",
|
|
10
|
+
"bun-sqlite"
|
|
11
|
+
],
|
|
12
|
+
"license": "MIT",
|
|
13
|
+
"author": "NewRate Limited (https://www.adrate.io)",
|
|
14
|
+
"repository": {
|
|
15
|
+
"type": "git",
|
|
16
|
+
"url": "git+https://github.com/AdRate-io/reins.git",
|
|
17
|
+
"directory": "packages/store-sqlite"
|
|
18
|
+
},
|
|
19
|
+
"homepage": "https://github.com/AdRate-io/reins/tree/main/packages/store-sqlite#readme",
|
|
20
|
+
"bugs": "https://github.com/AdRate-io/reins/issues",
|
|
21
|
+
"type": "module",
|
|
22
|
+
"sideEffects": false,
|
|
23
|
+
"exports": {
|
|
24
|
+
".": {
|
|
25
|
+
"types": "./dist/index.d.ts",
|
|
26
|
+
"import": "./dist/index.js"
|
|
27
|
+
},
|
|
28
|
+
"./node": {
|
|
29
|
+
"types": "./dist/node.d.ts",
|
|
30
|
+
"import": "./dist/node.js"
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
"files": [
|
|
34
|
+
"dist",
|
|
35
|
+
"CHANGELOG.md"
|
|
36
|
+
],
|
|
37
|
+
"dependencies": {
|
|
38
|
+
"@reinsjs/core": "0.1.0"
|
|
39
|
+
},
|
|
40
|
+
"devDependencies": {
|
|
41
|
+
"@types/node": "^22.0.0"
|
|
42
|
+
},
|
|
43
|
+
"engines": {
|
|
44
|
+
"node": ">=22.13"
|
|
45
|
+
},
|
|
46
|
+
"scripts": {
|
|
47
|
+
"build": "tsup"
|
|
48
|
+
}
|
|
49
|
+
}
|