@secret-momo/github-db 1.0.1 → 1.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/README.md CHANGED
@@ -113,6 +113,9 @@ const deleted = await todos.deleteById('task-2'); // boolean
113
113
  | `findAll(where?, options?)` | 返回所有匹配记录,不传条件时列出全表。 |
114
114
  | `updateById(id, patch, options?)` | 顶层合并业务字段、更新 updatedAt;不存在时报 NOT_FOUND。 |
115
115
  | `deleteById(id, options?)` | 删除成功返回 true,不存在返回 false,不创建表、不提交。 |
116
+ | `insertMany(records, options?)` | 同表批量追加,返回完整记录数组,首次自动建表。 |
117
+ | `updateManyById(updates, options?)` | 接收 `{ id, patch }` 数组,返回完整记录数组;任意目标不存在则整批失败。 |
118
+ | `deleteManyById(ids, options?)` | 返回逐项对应的 boolean 数组;不存在为 false,全部不存在时不提交。 |
116
119
 
117
120
  查询仅支持顶层字段等值,多字段按 AND 组合;对象按结构比较且忽略键顺序,数组按元素顺序比较,null 与不存在的字段不同。结果遵循文件中的记录顺序,find 基于 findAll 实现。不支持比较操作符、SQL、排序、分页或 JOIN。
118
121
 
@@ -128,6 +131,31 @@ DB、表名和记录 id 都按原始字符串精确匹配,不自动做 Unicode
128
131
 
129
132
  CRUD 写操作自动处理并发检查。每次在同一个队列和 Git 快照内读取全表、执行修改并发布,不需要调用方手工处理 JSONL 或版本令牌。查询下载完整表并在内存中过滤,写操作替换完整文件,因此适用于低频、小规模数据。
130
133
 
134
+ ### 批量写入
135
+
136
+ ```ts
137
+ const inserted = await todos.insertMany([
138
+ { id: 'batch-a', title: '任务 A', status: 'pending' },
139
+ { title: '任务 B', status: 'pending' }, // 也可自动生成 id
140
+ ]); // Todo[],与输入顺序一致
141
+
142
+ const updatedBatch = await todos.updateManyById([
143
+ { id: inserted[1]!.id, patch: { status: 'done' } },
144
+ { id: inserted[0]!.id, patch: { priority: 2 } },
145
+ ]); // Todo[],与更新输入顺序一致,表内顺序保持原样
146
+
147
+ const deletedBatch = await todos.deleteManyById([inserted[0]!.id, 'missing']);
148
+ // [true, false]
149
+ ```
150
+
151
+ 一次批量调用只操作一张表、执行一种操作,输入支持只读数组。需要写入时只执行一套全表读改写流程,用一个 Git commit 原子发布全部修改,表 revision 只增加一次;不会循环调用单条 API。插入按输入顺序追加,同批插入或更新统一使用一次毫秒时间。没有跨表事务、混合操作或条件批量更新。
152
+
153
+ 插入的批内重复 id 或已有 id 冲突使整批报 DUPLICATE_ID;更新、删除的批内重复 id 报 INVALID_INPUT/DUPLICATE_ID,不跳过、覆盖或合并。更新任意目标不存在使整批报 NOT_FOUND/RECORD_NOT_FOUND;删除不存在属于正常结果,全部不存在时不提交、不创建表。删除最后一条记录仍保留空表。
154
+
155
+ 空数组返回 [],不请求 GitHub、不创建表、不提交,但仍校验选项,已取消的请求报 ABORTED。数组必须普通、密集且无额外属性、访问器或隐藏元素;更新项仅包含 id 和 patch。数组、元素和选项在调用时捕获,排队后修改不影响本次操作。批次数组和更新包装层不计入单条记录/patch 的 512 层深度额度。
156
+
157
+ 首个检测到的元素错误携带从 0 开始的 details.itemIndex;批内重复指向后一次出现的位置,不收集全部错误、不回显业务内容。已有表损坏、容量和发布错误沿用原诊断,不添加 itemIndex。修改后的完整表仍不能超过 10,000,000 UTF-8 字节,不另设固定条数上限、不自动分块或重试。发布后 WRITE_RESULT_UNKNOWN 表示整批可能已经成功;自动 id 插入此时拿不到正常返回的 id 数组,需要可靠核验/重试的业务应自行提供稳定 id。SDK 不提供幂等键或导入恢复机制。
158
+
131
159
  ## 底层字符串 API
132
160
 
133
161
  底层只要求每行是 JSON 对象,不要求业务 id 或记录时间字段,也不解析为业务类型:
@@ -189,9 +217,9 @@ await todos.insert(
189
217
  await todos.findAll({ status: 'pending' }, { signal: controller.signal });
190
218
  ```
191
219
 
192
- 提交信息由 SDK 自动生成,不接受调用方指定,固定为 `github-db: <operation> "<db>/<table>"`。操作为 `write`、`insert`、`update` 或 `delete`,表路径使用 JSON 字符串转义。例如 `github-db: insert "app/todos"`。首次建表沿用调用操作;删除不存在的记录不产生提交。消息不包含记录内容、ID、时间戳或 SHA。
220
+ 提交信息由 SDK 自动生成,不接受调用方指定,固定为 `github-db: <operation> "<db>/<table>"`。操作为 `write`、`insert`、`update`、`delete`、`insertMany`、`updateManyById` 或 `deleteManyById`,表路径使用 JSON 字符串转义。例如 `github-db: insert "app/todos"`。首次建表沿用调用操作;删除不存在的记录不产生提交。消息不包含记录内容、ID、时间戳或 SHA。
193
221
 
194
- 错误为 GitHubDBError,提供 code 与 details,包括 reason、path、table、field、lineNumber 和可用的 HTTP 诊断字段。dispatched 仅表示调用了 fetch,不证明服务器已收到请求。
222
+ 错误为 GitHubDBError,提供 code 与 details,包括 reason、path、table、field、lineNumber、itemIndex 和可用的 HTTP 诊断字段。dispatched 仅表示调用了 fetch,不证明服务器已收到请求。
195
223
 
196
224
  写入在发布 PATCH 尚未发送时被取消返回 ABORTED,超时返回 TIMEOUT;SDK 已取得并验证 commitSha 时会附带该 SHA,SHA 尚未取得时不保证该字段。reason 为 BEFORE_PUBLICATION 的已知 commit 取消不会发送 PATCH;取消或超时可能留下未发布的 Git 对象。发布 PATCH 已投递后若结果不确定,返回 WRITE_RESULT_UNKNOWN 并携带尝试 commitSha。
197
225
 
@@ -69,7 +69,7 @@ JSONL 读取和校验在内存持有完整字符串,CRUD 下载全表后查询
69
69
 
70
70
  底层 write 先校验输入 JSONL、容量、取消与令牌格式,在 repository 队列内读取最新表快照,比较令牌后校验旧数据完整性。版本由 SHA-256 生成,输入包含连接作用域、DB、表、revision、实际 data SHA。
71
71
 
72
- 输入校验返回的 recordCount/byteLength 直接传入 TableStorage.write,避免对同一新内容重复扫描。高层对修改后的 JSONL 计算一次统计后使用同一持久化入口。
72
+ 输入校验返回的 recordCount/byteLength 直接传入 TableStorage.write,避免对同一新内容重复扫描。高层对修改后的 JSONL 计算一次统计后使用同一持久化入口。批量操作复用该入口,不增加每条记录的远端写入。
73
73
 
74
74
  底层 write 和高层 CRUD 在内部传递固定操作类型,TableStorage.write 统一生成提交信息:subject 为 `github-db: <operation> "<db>/<table>"`,使用 JSON.stringify 转义表路径;body 包含包名与 GitRepository 配置的 endpoint 原文。GitRepository 只接收生成后的消息,不推断业务操作。
75
75
 
@@ -93,6 +93,12 @@ insert/update/delete 都在 repository 队列内固定快照、验证全表、
93
93
 
94
94
  跨 client 操作没有共享内存锁;相同旧快照产生的两个提交不能都快进发布,失败者返回 CONFLICT。未知发布结果不自动重试,避免自动 id 插入重复。
95
95
 
96
+ 同表批量 insertMany/updateManyById/deleteManyById 也复用 mutate,在同一队列和快照中完成整批变化,一次编码、统计和 TableStorage.write,revision 只增加一次。插入用 Set 检查已有 id;更新用 Map 定位并先确认全部目标存在;删除用 Set 筛选并保留原顺序。记录匹配按 O(N+K) 处理,不逐项扫描全表,不循环调用单条方法,不自动拆批。
97
+
98
+ batchItems 检查普通密集数组与属性描述符,避免执行访问器,再逐项验证并复制。更新项仅含 id/patch,JSON 校验从包装层深度 0 开始,patch 根仍为第一层;批次数组不计入记录深度。批内重复和元素输入错误在请求前失败;已有 id 冲突和目标缺失在快照内检查。元素错误携带零起算 itemIndex,旧表校验/容量/发布错误保持原诊断。空数组校验选项与预取消后直接返回 [],不入队或请求。
99
+
100
+ 批量操作名原样传给 TableStorage.write 生成提交信息。发布未知、竞争和取消沿用 repository 的整批语义;未发布对象可能留存,但没有可见的部分记录更新。自动 id 发布未知时不额外返回 id 数组,也不增加幂等或恢复协议。
101
+
96
102
  ## 6. 传输与错误
97
103
 
98
104
  内部 request 方法统一处理请求发送、HTTP 分类、取消和响应读取,使用 raw 布尔参数区分 JSON 与原始文本,保留现有位置参数,不为这两种读取方式另拆 send/body 抽象。该组织方式不改变取消、投递状态、编码及发布确定性分类的正确性要求。
@@ -3,10 +3,12 @@
3
3
  一个 DB 下可以有多张独立表,每张表保存一份 meta.json 和一份 data.jsonl,不提供表分区或可变当前范围。
4
4
 
5
5
  - `db.getTable(name)`:底层 UTF-8 JSONL 字符串接口,支持 read/write/getMeta。
6
- - `db.getRecordTable<T>(name)`:高层记录接口,支持 insert/find/findById/findAll/updateById/deleteById,必须显式指定包含 RecordBase 的完整业务类型。
6
+ - `db.getRecordTable<T>(name)`:高层记录接口,支持 insert/find/findById/findAll/updateById/deleteById,以及 insertMany/updateManyById/deleteManyById,必须显式指定包含 RecordBase 的完整业务类型。
7
7
 
8
8
  两个入口使用相同表布局及共享写队列,便于不同调用需求;底层写入的数据只有满足记录约束时才能由高层消费。系统字段由 SDK 管理,业务字段编译期类型由调用方提供。
9
9
 
10
+ 批量写入接收同表、同类的只读数组,用一个提交原子发布,返回与输入对齐;不支持混合操作或自动分块。空数组无网络返回 [];删除缺失目标返回 false,更新缺失目标整批失败。详细错误及容量边界见记录 API。
11
+
10
12
  主键只要求表内唯一,另一张表可以复用 id。获取句柄无网络请求。两种 API 都查询整张目标表,表名固定,不支持跨表聚合或事务。
11
13
 
12
14
  示例见 [README](../README.md),详细契约见 [需求](requirements.md) 和 [记录 API](record-api-design.md),实现分层见 [架构](architecture.md)。
@@ -1,6 +1,6 @@
1
1
  # 类型化记录 API 设计
2
2
 
3
- 已确认并实现:单表 CRUD、自动/调用方 id、毫秒时间戳、字段等值 AND 查询及运行时记录约束。不提供分区。
3
+ 已确认并实现:单表 CRUD 与同类批量写入、自动/调用方 id、毫秒时间戳、字段等值 AND 查询及运行时记录约束。不提供分区。
4
4
 
5
5
  ## 1. 类型与入口
6
6
 
@@ -14,7 +14,7 @@ const todos = db.getRecordTable<Todo>('todolist');
14
14
 
15
15
  T 是完整落盘/返回记录的类型,必须包含字符串 id 与数字 createdAt/updatedAt。工厂不允许省略泛型,系统字段必须能承载 SDK 生成的普通 string/number,不能限定为某个字面量或品牌值。
16
16
 
17
- RecordInsert<T> 为业务字段加可选字符串 id,禁止时间字段;RecordUpdate<T> 为业务字段的 Partial,禁止全部系统字段;RecordWhere<T> 为记录字段的 Partial。返回值保持 T、T | null、T[] 或 boolean,不退化成 any。
17
+ RecordInsert<T> 为业务字段加可选字符串 id,禁止时间字段;RecordUpdate<T> 为业务字段的 Partial,禁止全部系统字段;RecordWhere<T> 为记录字段的 Partial。返回值保持 T、T | null、T[]、boolean 或 boolean[],不退化成 any。
18
18
 
19
19
  ## 2. CRUD 契约
20
20
 
@@ -26,7 +26,36 @@ updateById 顶层合并业务字段,嵌套值整体替换,只更新 updatedA
26
26
 
27
27
  deleteById 存在返回 true,不存在返回 false 且不提交。删除最后一条记录后保留空表,不删除目录。删除后的 id 可再次使用。不同表的主键集合相互独立。
28
28
 
29
- 读不到表时查询返回 null/[];update 报不存在,delete 返回 false,只有 insert 建表。
29
+ 读不到表时查询返回 null/[];单条 update 报不存在,单条 delete 返回 false,只有插入操作建表。批量返回和空操作见下节。
30
+
31
+ ### 同表批量写入
32
+
33
+ ```ts
34
+ declare class GitHubRecordTable<T extends RecordBase> {
35
+ insertMany(
36
+ inputs: readonly RecordInsert<T>[],
37
+ options?: RecordWriteOptions,
38
+ ): Promise<T[]>;
39
+ updateManyById(
40
+ inputs: readonly { id: string; patch: RecordUpdate<T> }[],
41
+ options?: RecordWriteOptions,
42
+ ): Promise<T[]>;
43
+ deleteManyById(
44
+ inputs: readonly string[],
45
+ options?: RecordWriteOptions,
46
+ ): Promise<boolean[]>;
47
+ }
48
+ ```
49
+
50
+ - insertMany:接收只读 RecordInsert<T> 数组,批量追加并返回 T[];非空批次首次自动建表。批内重复 id 或与已有 id 冲突,整批报 DUPLICATE_ID,自动生成 id 也参与唯一性校验。
51
+ - updateManyById:接收只读 `{ id: string; patch: RecordUpdate<T> }` 数组,返回 T[];每项仅包含 id 和 patch,patch 沿用单条更新规则。任意目标不存在报 NOT_FOUND/RECORD_NOT_FOUND,整批不更新。
52
+ - deleteManyById:接收只读字符串 id 数组,返回与输入对应的 boolean[];存在为 true,不存在为 false。全部不存在时不提交、不创建表;删除最后一条记录保留空表。
53
+
54
+ 批量接口每次只支持同表、同类操作,不支持混合操作、跨表事务、条件批量更新、文件/流式导入。更新、删除的批内重复 id 报 INVALID_INPUT/DUPLICATE_ID,不跳过或合并;批内重复错误指向后一次出现的位置。返回与输入顺序一致,插入按输入顺序追加,更新保留存储顺序;同批插入/更新取一次毫秒时间,沿用系统字段保护规则。
55
+
56
+ 一批修改只执行一套全表读改写,用一个提交原子发布,revision 只增加一次,不循环调用单条 API。首个检测到的错误使整批失败,不收集全部错误;元素错误包含从 0 开始的 itemIndex,表损坏、容量和发布错误不添加该字段,不回显业务内容。发布未知不代表回滚,沿用 WRITE_RESULT_UNKNOWN 与尝试 commitSha,不自动重试、不增加幂等键或恢复机制;需要核验/重试的业务应提供稳定 id,自动 id 插入发布未知时不会返回正常的 id 数组。
57
+
58
+ 批次输入必须普通密集数组,无额外属性、访问器、隐藏元素或 symbol 属性。调用时捕获并复制数组及元素。空数组返回 [],不请求、不建表、不提交,但仍验证选项,已取消时返回 ABORTED。批次数组/更新包装层不计入单条记录及 patch 的 512 层额度。最终完整表沿用 10,000,000 UTF-8 字节上限,不另设条数上限,不自动分块。
30
59
 
31
60
  ## 3. 校验边界
32
61
 
@@ -44,9 +73,9 @@ JSON 数据模型允许普通对象、密集数组、合法 Unicode 字符串、
44
73
 
45
74
  高层变更复用内部 TableStorage,在 repository 队列内固定快照、验证全表、检查主键、计算修改,并用同一个快照原子发布 data/meta。实例内不同句柄与两层写入共用队列;跨 client 竞争通过非强制分支更新拒绝,无自动重试。
46
75
 
47
- 发布响应不明确时保留 WRITE_RESULT_UNKNOWN 和尝试 commitSha。自动生成 id 的 insert 同样不能盲目重试,否则可能产生第二条记录。外部 force reset 的严格 CAS 与历史清除不在承诺内。
76
+ 发布响应不明确时保留 WRITE_RESULT_UNKNOWN 和尝试 commitSha。自动生成 id 的 insert/insertMany 同样不能盲目重试,否则可能产生第二条记录。外部 force reset 的严格 CAS 与历史清除不在承诺内。
48
77
 
49
- 查询和变更都读取完整表;每次写入替换完整 data。没有远端行级索引、分页、SQL、JOIN、batch 或跨表事务。定位为低频、小规模数据,写入容量继承 10,000,000 UTF-8 字节限制。
78
+ 查询和变更都读取完整表;每次写入替换完整 data。没有远端行级索引、分页、SQL、JOIN、混合 batch 或跨表事务。定位为低频、小规模数据,写入容量继承 10,000,000 UTF-8 字节限制。
50
79
 
51
80
  ## 5. 验收
52
81
 
@@ -53,10 +53,19 @@ getRecordTable<T>(name) 获取高层句柄,必须显式指定包含 RecordBase
53
53
  - findAll:返回全部匹配记录数组,不传条件时查询全表。
54
54
  - updateById:输入排除系统字段后的部分业务字段,顶层合并、嵌套字段整体替换,返回完整记录。空 patch 不合法,不存在时报 NOT_FOUND/RECORD_NOT_FOUND。
55
55
  - deleteById:存在时删除并返回 true,不存在返回 false,无提交,也不创建空表。
56
+ - insertMany:接收只读 RecordInsert<T> 数组,批量追加并返回 T[];非空批次首次自动建表。批内重复 id 或与已有 id 冲突,整批报 DUPLICATE_ID,自动生成 id 也参与唯一性校验。
57
+ - updateManyById:接收只读 `{ id: string; patch: RecordUpdate<T> }` 数组,返回 T[];每项仅包含 id 和 patch,patch 沿用单条更新规则。任意目标不存在报 NOT_FOUND/RECORD_NOT_FOUND,整批不更新。
58
+ - deleteManyById:接收只读字符串 id 数组,返回与输入对应的 boolean[];存在为 true,不存在为 false。全部不存在时不提交、不创建表;删除最后一条记录保留空表。
59
+
60
+ 批量接口每次只支持同表、同类操作,不支持混合操作、跨表事务、条件批量更新、文件/流式导入。更新、删除的批内重复 id 报 INVALID_INPUT/DUPLICATE_ID,不跳过或合并;批内重复错误指向后一次出现的位置。返回与输入顺序一致,插入按输入顺序追加,更新保留存储顺序;同批插入/更新取一次毫秒时间,沿用系统字段保护规则。
61
+
62
+ 一批修改只执行一套全表读改写,用一个提交原子发布,revision 只增加一次,不循环调用单条 API。首个检测到的错误使整批失败,不收集全部错误;元素错误包含从 0 开始的 itemIndex,表损坏、容量和发布错误不添加该字段,不回显业务内容。发布未知不代表回滚,沿用 WRITE_RESULT_UNKNOWN 与尝试 commitSha,不自动重试、不增加幂等键或恢复机制;需要核验/重试的业务应提供稳定 id,自动 id 插入发布未知时不会返回正常的 id 数组。
63
+
64
+ 批次输入必须普通密集数组,无额外属性、访问器、隐藏元素或 symbol 属性。调用时捕获并复制数组及元素。空数组返回 [],不请求、不建表、不提交,但仍验证选项,已取消时返回 ABORTED。批次数组/更新包装层不计入单条记录及 patch 的 512 层额度。最终完整表沿用 10,000,000 UTF-8 字节上限,不另设条数上限,不自动分块。
56
65
 
57
66
  id 是非空合法 Unicode 字符串;唯一性范围为一张表,不同表允许复用。SDK 生成数字毫秒 createdAt/updatedAt,更新保留 id 和 createdAt。相同毫秒或系统时钟变化不保证更新时间严格递增。删除最后一条记录后保留表及零字节数据文件。
58
67
 
59
- 对象等值按结构比较,忽略对象键顺序;数组顺序敏感,null 与缺字段不同。无 SQL、比较操作符、排序、分页、JOIN、跨表事务或 batch API。
68
+ 对象等值按结构比较,忽略对象键顺序;数组顺序敏感,null 与缺字段不同。无 SQL、比较操作符、排序、分页、JOIN、跨表事务或混合 batch API。
60
69
 
61
70
  TS 负责业务类型的编译期校验。运行时验证普通 JSON 对象、系统字段及全表重复 id,不从泛型推导业务 schema。拒绝会丢失的 undefined、函数、symbol、非有限数字、BigInt、循环引用、非普通对象、稀疏/额外属性数组、隐藏属性、访问器及非法 Unicode。读取不能按 JS number 精确往返的原始数字字面量也拒绝;高精度数值应存字符串。
62
71
 
@@ -70,7 +79,7 @@ TS 负责业务类型的编译期校验。运行时验证普通 JSON 对象、
70
79
 
71
80
  force=false 发布拒绝竞争提交,不强制覆盖、不自动重试。外部 force reset/ABA 不在严格 CAS 保证内,不增加针对外部强制历史操作的锁或协调服务;正常非强制并发下仍必须防止丢记录、漏检重复及覆盖其他表。提交前失败不产生可见半更新;发布后网络、取消、超时、5xx 或异常响应可能已经成功,报 WRITE_RESULT_UNKNOWN,携带尝试 commitSha。
72
81
 
73
- 所有操作支持 AbortSignal。提交信息由 SDK 自动生成,不接受调用方指定;subject 固定为 `github-db: <operation> "<db>/<table>"`,表路径使用 JSON 字符串转义。body 包含 `client: @secret-momo/github-db` 与 `endpoint: <configured endpoint>`,原样保留调用方指定的 endpoint;未配置 endpoint 时使用 `https://api.github.com`。operation 对应公开 API,为 write、insert、update 或 delete;首次建表沿用调用操作,删除最后一条记录仍为 delete。消息不包含记录内容、ID、时间戳或 SHA。调用入口复制选项与 CRUD 输入,排队期间调用方修改不影响本次操作。错误包含 code 与结构化诊断,不回显上游秘密正文;dispatched 仅表示调用 fetch。
82
+ 所有操作支持 AbortSignal。提交信息由 SDK 自动生成,不接受调用方指定;subject 固定为 `github-db: <operation> "<db>/<table>"`,表路径使用 JSON 字符串转义。body 包含 `client: @secret-momo/github-db` 与 `endpoint: <configured endpoint>`,原样保留调用方指定的 endpoint;未配置 endpoint 时使用 `https://api.github.com`。operation 对应公开 API,为 write、insert、update、delete、insertMany、updateManyById 或 deleteManyById;首次建表沿用调用操作,单条删除最后一条记录仍为 delete,批量删除为 deleteManyById。消息不包含记录内容、ID、时间戳或 SHA。调用入口复制选项与 CRUD 输入,排队期间调用方修改不影响本次操作。错误包含 code 与结构化诊断,不回显上游秘密正文;dispatched 仅表示调用 fetch。
74
83
 
75
84
  发布 PATCH 尚未发送时,caller 取消返回 ABORTED,超时返回 TIMEOUT;SDK 已取得并验证 commit SHA 时可附带该 SHA,其中已知 commit 的发布前 caller 取消包含 reason=BEFORE_PUBLICATION 和 commitSha,SHA 尚未取得时不保证该字段。取消或超时可能留下未发布的 Git 对象,但 SDK 不继续发布。发布 PATCH 已投递后的取消、超时或异常返回 WRITE_RESULT_UNKNOWN,并携带尝试 commitSha。
76
85
 
package/docs/testing.md CHANGED
@@ -17,12 +17,13 @@ Bun LCOV 行/函数统计不能证明所有分支真实执行;已知插桩局
17
17
  | transport.test.ts | endpoint、双层鉴权、配置、HTTP、Git 响应、取消及发布确定性 |
18
18
  | review-regressions.test.ts / round-two.test.ts | 元信息数字保真、安全整数、SHA、结构化错误、分支发现与历史回归 |
19
19
  | records.test.ts | CRUD、AND 等值、系统字段、主键、队列、跨 client 竞争及两层共享 |
20
+ | batch-records.test.ts | 同表批量原子发布、单次 revision/请求流程、顺序、错误位置、重复/缺失 ID、空操作、输入复制、512 层包装边界、容量/旧表缩小、队列与未知发布 |
20
21
  | records-validation.test.ts | JSON 可存储性、坏记录、输入复制、数字精度与容量 |
21
22
  | review-latest.test.ts | 512 层边界、深层旧数据结构化错误、发布前取消状态及 Unicode 键隔离 |
22
- | bun-runtime.test.mjs | Bun 原生 HTTP/fetch 的 UTF-8、大文件、CRUD、双层鉴权、重定向、取消、超时及 socket/发布异常 |
23
+ | bun-runtime.test.mjs | Bun 原生 HTTP/fetch 的 UTF-8、大文件、单条/批量 CRUD、双层鉴权、重定向、取消、超时及 socket/发布异常 |
23
24
  | coverage.test.mjs | 覆盖率清单、嵌套源码、缺失报告与门槛拒绝 |
24
- | node-runtime.mjs | 构建后的 ESM 在原生 HTTP/fetch 上的读写、CRUD、并发、超时、取消及丢失发布响应 |
25
- | package-consumer.mjs | 真正打包、Node/Bun 包名导入、单 JS/d.ts 无 map、NodeNext 正反类型用例 |
25
+ | node-runtime.mjs | 构建后的 ESM 在原生 HTTP/fetch 上的读写、单条/批量 CRUD、深度包装边界、并发、超时、取消及丢失发布响应 |
26
+ | package-consumer.mjs | 真正打包、Node/Bun 包名导入、单 JS/d.ts 无 map、NodeNext 单条/批量及只读数组的正反类型用例 |
26
27
 
27
28
  FakeGitHub 用真实 Git blob SHA、不可变 commit/tree、分支 head 以及非强制更新模拟 Git 对象协议。Bun 单元使用注入 fetch;Bun/Node 原生场景通过本地 HTTP,并保留独立预期。Bun 原生 suite 在默认 bun test 中执行,无需额外脚本;夹具逐测试管理连接,避免 Bun 1.4 的 closeAllConnections 同时停止监听导致二次 close 错误。Node 构建产物另验证 512 层可写可读、超限输入无 HTTP、深层旧行结构化报错。构建产物的公开类型不得因 skipLibCheck=true 而退化。
28
29
 
@@ -32,7 +33,7 @@ FakeGitHub 用真实 Git blob SHA、不可变 commit/tree、分支 head 以及
32
33
 
33
34
  第三方 relay 验收同时配置 `GITHUB_RELAY_ENDPOINT` 和 `GITHUB_RELAY_TOKEN`,缺少任意一项时立即失败。SDK、独立 Git Data 核验及清理请求均通过该 endpoint,并在 GitHub Bearer 鉴权之外发送 `x-cfgr-token`。两项均未配置时直连 GitHub。
34
35
 
35
- 每次生成唯一表名前缀,独立 Git Data 请求核验初始不存在、同次提交的 meta/data 和最新单表布局。覆盖底层单表、多个独立表、条件版本、零字节文件、大于 1 MB 的 raw blob,以及高层自动/指定 id、重复拒绝、AND 查询、更新、删除、并发新增与跨表隔离。
36
+ 每次生成唯一表名前缀,独立 Git Data 请求核验初始不存在、同次提交的 meta/data 和最新单表布局。覆盖底层单表、多个独立表、条件版本、零字节文件、大于 1 MB 的 raw blob,以及高层自动/指定 id、重复拒绝、AND 查询、更新、删除、并发新增、同表批量增改删的单次提交/revision、失败原子性与跨表隔离。
36
37
 
37
38
  结束时仅移除本次生成的表目录,核验清理成功;不会清理其他数据或重写 Git 历史。明确的清理发布竞争可在新快照重新计算,未知发布结果/网络失败不盲目重试;清理失败指出本轮表名并保留原因。
38
39
 
package/lib/index.d.ts CHANGED
@@ -144,6 +144,12 @@ declare class GitHubRecordTable<T extends RecordBase> {
144
144
  findById(id: string, options?: ReadOptions): Promise<T | null>;
145
145
  insert(input: RecordInsert<T>, options?: RecordWriteOptions): Promise<T>;
146
146
  updateById(id: string, patch: RecordUpdate<T>, options?: RecordWriteOptions): Promise<T>;
147
+ insertMany(inputs: readonly RecordInsert<T>[], options?: RecordWriteOptions): Promise<T[]>;
148
+ updateManyById(inputs: readonly {
149
+ id: string;
150
+ patch: RecordUpdate<T>;
151
+ }[], options?: RecordWriteOptions): Promise<T[]>;
152
+ deleteManyById(inputs: readonly string[], options?: RecordWriteOptions): Promise<boolean[]>;
147
153
  deleteById(id: string, options?: RecordWriteOptions): Promise<boolean>;
148
154
  private mutate;
149
155
  }
@@ -197,6 +203,8 @@ interface ErrorDetails {
197
203
  /** True once fetch is invoked; does not prove that the server received a request. */
198
204
  dispatched?: boolean;
199
205
  lineNumber?: number;
206
+ /** Zero-based position of a failing batch input; omitted for table/publication errors. */
207
+ itemIndex?: number;
200
208
  status?: number;
201
209
  requestId?: string;
202
210
  retryAfter?: string;
package/lib/index.js CHANGED
@@ -1,9 +1,9 @@
1
- import{createHash as C,randomUUID as z}from"node:crypto";import{isDeepStrictEqual as K}from"node:util";import{Buffer as E}from"node:buffer";class i extends Error{constructor(t,e,r={}){super(e),this.code=t,this.details=r}code;details;name="GitHubDBError"}function g(a){return a!==null&&typeof a=="object"&&!Array.isArray(a)}function x(a){if(!g(a))throw new i("INVALID_INPUT","Options must be an object.")}function _(a){if(a!==void 0&&!(a instanceof AbortSignal))throw new i("INVALID_INPUT","signal must be an AbortSignal.")}function X(a){if(typeof a!="string"||!a.isWellFormed())throw new i("INVALID_INPUT","Content must be a well-formed Unicode string.")}function H(a){return typeof a=="string"&&!!a.trim()&&a.isWellFormed()&&a!=="."&&a!==".."&&a.toLowerCase()!==".git"&&!/[/\\\p{Cc}\p{Cf}\u115F\u1160\u3164\u2800\uFFA0]/u.test(a)}function N(a){if(!H(a))throw new i("INVALID_INPUT","Names must be nonempty, unambiguous path segments.");return a}function A(a){x(a);const t=a.signal;return _(t),t}const Q=1e7;function Z(a){let t=!1,e=!1;for(let r=0;r<a.length;r++){const n=a[r];if(!t){n==='"'&&(t=!0);continue}if(n==="\\"){if(a[++r]==="u"&&/^[0-9a-fA-F]{4}$/.test(a.slice(r+1,r+5))){const s=Number.parseInt(a.slice(r+1,r+5),16);if(r+=4,s>=55296&&s<=56319){if(e)return!0;e=!0}else if(s>=56320&&s<=57343){if(!e)return!0;e=!1}else if(e)return!0}else if(e)return!0}else if(n==='"'){if(e)return!0;t=!1}else if(e)return!0}return e}function L(a,t=!0){X(a);const e=E.byteLength(a,"utf8");if(t&&e>Q)throw new i("TABLE_TOO_LARGE","Table exceeds 10,000,000 UTF-8 bytes.");if(a==="")return{recordCount:0,byteLength:0};const r=a.split(`
2
- `);r.at(-1)===""&&r.pop();for(const[n,s]of r.entries()){let o;try{o=JSON.parse(s)}catch{throw new i("INVALID_JSONL","Every record line must be valid JSON.",{lineNumber:n+1})}if(Z(s))throw new i("INVALID_JSONL","JSONL contains invalid Unicode.",{lineNumber:n+1,reason:"INVALID_UNICODE"});if(!g(o))throw new i("INVALID_JSONL","Every record must be a JSON object.",{lineNumber:n+1})}return{recordCount:r.length,byteLength:e}}function T(a){if(!g(a))throw new i("INVALID_RESPONSE","Expected a GitHub response object.");return a}function w(a){if(typeof a!="string"||!/^[a-f0-9]{40}$/.test(a))throw new i("INVALID_RESPONSE","Expected a 40-character lowercase Git SHA.");return a}function v(a){if(typeof a!="string"||!a||!a.isWellFormed())throw new i("INVALID_RESPONSE","Expected a nonempty well-formed GitHub response field.");return a}function tt(a){if(typeof a!="string"||!a.trim()||!a.isWellFormed()||/[\p{Cc}\p{Cf}]/u.test(a))throw new i("INVALID_RESPONSE","Expected a valid well-formed GitHub branch name.");return a}function et(a,t){try{if(a===null||typeof a!="object")return;const e=a,r=e.status,n=e.ok,s=e.headers,o=e.json,c=e.arrayBuffer;if(typeof r!="number"||!Number.isInteger(r)||r<100||r>599||typeof n!="boolean"||n!==(r>=200&&r<300)||s===null||typeof s!="object")return;const d=s.get;if(typeof d!="function"||typeof o!="function"||typeof c!="function")return;const u=d.call(s,"x-github-request-id"),h=d.call(s,"retry-after");return u!==null&&typeof u!="string"||h!==null&&typeof h!="string"?void 0:{ok:n,json:o.bind(a),arrayBuffer:c.bind(a),details:{dispatched:t,status:r,requestId:u??void 0,retryAfter:h??void 0}}}catch{return}}function P(a,t,e){const r=Promise.resolve(a);return t?new Promise((n,s)=>{let o=!1;const c=()=>t.removeEventListener("abort",d),d=()=>{o||(o=!0,c(),s(e()))};t.addEventListener("abort",d,{once:!0}),r.then(u=>{o||(o=!0,c(),n(u))},u=>{o||(o=!0,c(),s(u))}),t.aborted&&d()}):r}function rt(a){const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(a);if(!t)return!1;const e=Number(t[1]),r=Number(t[2]),n=Number(t[3]);if(r<1||r>12)return!1;const s=[31,e%4===0&&(e%100!==0||e%400===0)?29:28,31,30,31,30,31,31,30,31,30,31];return n>=1&&n<=s[r-1]}class nt{endpoint;prefix;headers;fetcher;timeout;constructor(t){x(t);for(const r of[t.token,t.owner,t.repo])if(typeof r!="string"||!r.trim())throw new i("INVALID_INPUT","token, owner and repo are required.");if(N(t.owner),N(t.repo),t.branch!==void 0&&(typeof t.branch!="string"||!t.branch.trim()||!t.branch.isWellFormed()||/[\p{Cc}\p{Cf}]/u.test(t.branch)))throw new i("INVALID_INPUT","branch must be nonempty, well-formed Unicode without control or format characters.");let e;try{e=new URL(t.endpoint??"https://api.github.com")}catch{throw new i("INVALID_INPUT","endpoint must be an absolute HTTP(S) URL.")}if(!["https:","http:"].includes(e.protocol)||e.search||e.hash||e.username||e.password)throw new i("INVALID_INPUT","endpoint cannot contain credentials, query or fragment.");if(t.timeout!==void 0&&(!Number.isSafeInteger(t.timeout)||t.timeout<=0||t.timeout>2147483647))throw new i("INVALID_INPUT","timeout must be between 1 and 2,147,483,647 milliseconds.");if(t.apiVersion!==void 0&&(typeof t.apiVersion!="string"||!rt(t.apiVersion)))throw new i("INVALID_INPUT","apiVersion must have YYYY-MM-DD format.");if(t.fetch!==void 0&&typeof t.fetch!="function")throw new i("INVALID_INPUT","fetch must be a function.");this.endpoint=e.href.replace(/\/+$/,""),this.prefix=`/repos/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repo)}`;try{this.headers=new Headers(t.headers)}catch{throw new i("INVALID_INPUT","Custom headers are not valid HTTP header values.")}for(const r of["authorization","accept","content-type","x-github-api-version"])if(this.headers.has(r))throw new i("INVALID_INPUT",`Custom headers cannot override ${r}.`);try{this.headers.set("Authorization",`Bearer ${t.token}`)}catch{throw new i("INVALID_INPUT","token is not a valid HTTP header value.")}this.headers.set("X-GitHub-Api-Version",t.apiVersion??"2026-03-10"),this.fetcher=t.fetch??globalThis.fetch,this.timeout=t.timeout}async request(t,e,r,n,s){_(s);let o=!1;const c=new Headers(this.headers);c.set("Accept",n?"application/vnd.github.raw+json":"application/vnd.github+json"),r!==void 0&&c.set("Content-Type","application/json");const d=s?[s]:[],u=this.timeout===void 0?void 0:AbortSignal.timeout(this.timeout);u&&d.push(u);const h=d.length?AbortSignal.any(d):void 0,p=e==="POST"&&t==="/git/commits",l=h,m=()=>p&&s?.aborted===!0,f=()=>new i(s?.aborted?"ABORTED":"TIMEOUT",s?.aborted?"Request was cancelled.":"Request timed out.",{dispatched:o});if(h?.aborted)throw f();let U;try{o=!0;const I=this.fetcher(`${this.endpoint}${this.prefix}${t}`,{method:e,headers:c,body:r===void 0?void 0:JSON.stringify(r),redirect:"manual",signal:h});U=await P(I,l,f)}catch{throw h?.aborted?f():new i("NETWORK_ERROR","GitHub request failed.",{dispatched:o})}if(h?.aborted&&!m())throw f();const y=et(U,o);if(!y)throw new i("INVALID_RESPONSE","fetch must return a valid Response.",{dispatched:o});const{details:b}=y;if(!y.ok)throw new i("HTTP_ERROR",`GitHub request returned HTTP ${b.status}.`,{...b,...b.status>=300&&b.status<400?{reason:"REDIRECT"}:{}});try{if(!n){const Y=await P(y.json(),l,f);if(h?.aborted&&!m())throw f();return Y}const I=await P(y.arrayBuffer(),l,f);let j;try{j=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(I)}catch{throw new i("INVALID_UTF8","File content is not valid UTF-8.",b)}if(h?.aborted&&!m())throw f();return j}catch(I){throw h?.aborted?f():I instanceof i?I:new i("INVALID_RESPONSE","Could not read the GitHub response.",b)}}async json(t,e="GET",r,n){return T(await this.request(t,e,r,!1,n))}scope(t){return JSON.stringify([this.endpoint,this.prefix,t])}}function at(a){if(typeof a!="string")throw new i("INVALID_INPUT","Path must be a string.");return a.split("/").forEach(N),a}function ot(a){const t=v(a);if(t.includes("/"))throw new i("INVALID_RESPONSE","GitHub returned an invalid tree entry path.");return t}class st{constructor(t){this.transport=t}transport;tree(t,e,r){let n=t.trees.get(e);return n||(n=this.transport.json(`/git/trees/${e}`,"GET",void 0,r).then(s=>{if(s.truncated!==!1||!Array.isArray(s.tree))throw new i("INVALID_RESPONSE","GitHub returned an incomplete tree.");return s.tree.map(o=>{const c=T(o);return{path:ot(c.path),sha:w(c.sha),type:v(c.type),mode:v(c.mode)}})}),t.trees.set(e,n)),n}async resolve(t,e,r){const n=at(e).split("/");let s=t.treeSha;for(let o=0;o<n.length;o++){const c=(await this.tree(t,s,r)).find(d=>d.path===n[o]);if(!c)return;if(o===n.length-1)return c;if(c.type!=="tree")throw new i("INVALID_METADATA","A parent path is not a directory.",{path:n.slice(0,o+1).join("/"),reason:"PATH_NOT_DIRECTORY"});s=c.sha}}async find(t,e,r){const n=await this.resolve(t,e,r);if(n&&(n.type!=="blob"||!["100644","100755"].includes(n.mode)))throw new i("INVALID_METADATA","Path must reference a regular file.",{path:e,reason:"NOT_REGULAR_FILE"});return n}async directory(t,e,r){const n=await this.resolve(t,e,r);if(n){if(n.type!=="tree")throw new i("INVALID_METADATA","Path must reference a directory.",{path:e,reason:"PATH_NOT_DIRECTORY"});return this.tree(t,n.sha,r)}}}function R(a){const t=E.from(a,"utf8");return C("sha1").update(`blob ${t.byteLength}\0`).update(t).digest("hex")}class it{transport;endpoint;files;branchName;branchLookup;queue=Promise.resolve();constructor(t){this.transport=new nt(t),this.endpoint=t.endpoint??"https://api.github.com",this.files=new st(this.transport),this.branchName=t.branch}async branch(t){if(t?.aborted)throw new i("ABORTED","Request was cancelled.",{dispatched:!1});if(this.branchName!==void 0)return this.branchName;if(this.branchLookup??=this.transport.json("").then(r=>(this.branchName=tt(r.default_branch),this.branchName)).finally(()=>{this.branchLookup=void 0}),!t)return this.branchLookup;const e=this.branchLookup;if(t.aborted)throw e.catch(()=>{}),new i("ABORTED","Request was cancelled.",{dispatched:!0});return new Promise((r,n)=>{const s=()=>n(new i("ABORTED","Request was cancelled.",{dispatched:!0}));t.addEventListener("abort",s,{once:!0}),e.then(r,n).finally(()=>t.removeEventListener("abort",s))})}async snapshot(t){_(t);const e=await this.branch(t),r=await this.transport.json(`/git/ref/heads/${encodeURIComponent(e)}`,"GET",void 0,t),n=w(T(r.object).sha),s=await this.transport.json(`/git/commits/${n}`,"GET",void 0,t);return{commitSha:n,treeSha:w(T(s.tree).sha),trees:new Map}}scope(){return this.transport.scope(this.branchName)}async content(t,e){return await this.transport.request(`/git/blobs/${t.sha}`,"GET",void 0,!0,e)}enqueue(t){const e=this.queue.then(t);return this.queue=e.then(()=>{},()=>{}),e}async createBlob(t,e){const r=await this.transport.json("/git/blobs","POST",{content:E.from(t,"utf8").toString("base64"),encoding:"base64"},e),n=w(r.sha);if(n!==R(t))throw new i("INVALID_RESPONSE","GitHub returned a blob SHA that does not match content.");return n}async commit(t,e,r,n){const s=await Promise.all(e.map(async h=>({path:h.path,mode:h.mode??"100644",type:"blob",sha:"sha"in h?h.sha:await this.createBlob(h.content,n)}))),o=await this.transport.json("/git/trees","POST",{base_tree:t.treeSha,tree:s},n),c=await this.transport.json("/git/commits","POST",{tree:w(o.sha),parents:[t.commitSha],message:r},n),d=w(c.sha),u=await this.branch();if(n?.aborted)throw new i("ABORTED","Write was cancelled before publication.",{dispatched:!0,reason:"BEFORE_PUBLICATION",commitSha:d});try{const h=await this.transport.json(`/git/refs/heads/${encodeURIComponent(u)}`,"PATCH",{sha:d,force:!1},n);if(w(T(h.object).sha)!==d)throw new i("INVALID_RESPONSE","Unexpected published commit.")}catch(h){if(h instanceof i){if(h.details.dispatched===!1)throw h;if(h.code==="HTTP_ERROR"&&h.details.status!==void 0&&h.details.status<500)throw h.details.status===409||h.details.status===422?new i("CONFLICT","GitHub rejected publication; inspect the cause before retrying.",{...h.details,reason:"PUBLISH_REJECTED"}):h}throw new i("WRITE_RESULT_UNKNOWN","Publication may have succeeded; verify before retrying.",{dispatched:!0,...h instanceof i?h.details:{},commitSha:d})}return{commitSha:d}}}const ct=512;function M(a,t,e){if(a>ct)throw new i(t,"JSON nesting exceeds 512 object/array containers.",{...e,reason:"TOO_DEEP"})}function $(a,t,e){let r=0,n=!1;for(let s=0;s<a.length;s++){const o=a[s];n&&o==="\\"?s++:o==='"'?n=!n:n||(o==="{"||o==="["?M(++r,t,e):(o==="}"||o==="]")&&r--)}}function J(a){const t=/^(-?)(\d+)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/.exec(a),e=t[3]??"",r=(t[2]+e).replace(/^0+/,""),n=r.replace(/0+$/,"");return{sign:r?t[1]:"",digits:n,exponent:r?BigInt(t[4]??0)-BigInt(e.length)+BigInt(r.length-n.length):0n}}const S=JSON;function ht(a){const{digits:t,exponent:e}=J(a);return!t||e>=0n}function V(a,t,e){const r=a[t],n=S.isRawJSON(r)?Number(r.rawJSON):r;if(typeof n!="number"||!Number.isSafeInteger(n)||n<0||Object.is(n,-0)||S.isRawJSON(r)&&!ht(r.rawJSON))throw new i("INVALID_METADATA","Metadata field must be a nonnegative safe integer.",{...e,reason:"INVALID_FIELD",field:t});return a[t]=n,n}function dt(a,t){$(a,"INVALID_METADATA",t);let e;try{e=S.parse(a,(r,n,s)=>typeof n=="number"&&JSON.stringify(n)!==s.source?S.rawJSON(s.source):n)}catch{throw new i("INVALID_METADATA","meta.json must contain valid JSON.",{...t,reason:"INVALID_JSON"})}if(!g(e))throw new i("INVALID_METADATA","meta.json must contain an object.",{...t,reason:"INVALID_FIELD"});if(V(e,"version",t)!==1)throw new i("INVALID_METADATA","Unsupported metadata format version.",{...t,reason:"UNSUPPORTED_VERSION",field:"version"});for(const r of["createdAt","updatedAt","recordCount","byteLength"])V(e,r,t);if(V(e,"revision",t)===0||typeof e.dataSha!="string"||!/^[a-f0-9]{40}$/.test(e.dataSha))throw new i("INVALID_METADATA","Table revision or dataSha is invalid.",{...t,reason:"INVALID_FIELD",field:"revision/dataSha"});return e}function ut(a){return JSON.stringify(a,null,2)+`
3
- `}class B{constructor(t,e,r){this.repository=t,this.dbName=e,this.name=r,N(e),N(r),this.root=`${e}/${r}`,this.metaPath=`${this.root}/meta.json`,this.dataPath=`${this.root}/data.jsonl`}repository;dbName;name;root;metaPath;dataPath;context(t=this.metaPath){return{path:t,table:this.name}}async metadata(t,e){const r=await this.repository.files.find(t,this.metaPath,e);if(!r){if((await this.repository.files.directory(t,this.root,e))?.length)throw new i("INVALID_METADATA","Existing table is missing meta.json.",{...this.context(),reason:"MISSING_METADATA"});return}const n=await this.repository.content(r,e);if(R(n)!==r.sha)throw new i("INVALID_METADATA","meta.json SHA does not match its content.",{...this.context(),reason:"META_SHA_MISMATCH"});return{meta:dt(n,this.context()),entry:r}}async state(t,e){const[r,n]=await Promise.all([this.metadata(t,e),this.repository.files.find(t,this.dataPath,e)]);if(r&&!n)throw new i("INVALID_METADATA","Table is missing data.jsonl.",{...this.context(),path:this.dataPath,reason:"MISSING_DATA"});return{metadata:r,data:n}}async validatedContent(t,e){if(!t.metadata||!t.data)return"";const{meta:r}=t.metadata;if(r.dataSha!==t.data.sha)throw new i("INVALID_METADATA","dataSha does not match data.jsonl.",{...this.context(),path:this.dataPath,reason:"DATA_SHA_MISMATCH"});const n=await this.repository.content(t.data,e);if(R(n)!==t.data.sha)throw new i("INVALID_METADATA","dataSha does not match data.jsonl.",{...this.context(),path:this.dataPath,reason:"DATA_SHA_MISMATCH"});const s=L(n,!1);if(s.recordCount!==r.recordCount||s.byteLength!==r.byteLength)throw new i("INVALID_METADATA","Statistics do not match data.jsonl.",{...this.context(),path:this.dataPath,reason:"STATISTICS_MISMATCH"});return n}async write(t,e,r,n,s,o){const c=Date.now(),d=(e.metadata?.meta.revision??0)+1;if(!Number.isSafeInteger(d))throw new i("INVALID_METADATA","Table revision cannot be incremented safely.",{...this.context(),reason:"REVISION_OVERFLOW",field:"revision"});const u=await this.repository.createBlob(r,o),h={...e.metadata?.meta,version:1,createdAt:e.metadata?.meta.createdAt??c,updatedAt:c,...n,revision:d,dataSha:u},p=await this.repository.commit(t,[{path:this.dataPath,sha:u,mode:e.data?.mode},{path:this.metaPath,content:ut(h),mode:e.metadata?.entry.mode}],`github-db: ${s} ${JSON.stringify(this.root)}
1
+ import{createHash as H,randomUUID as $}from"node:crypto";import{isDeepStrictEqual as Z}from"node:util";import{Buffer as _}from"node:buffer";class i extends Error{constructor(t,e,r={}){super(e),this.code=t,this.details=r}code;details;name="GitHubDBError"}function D(a){return a!==null&&typeof a=="object"&&!Array.isArray(a)}function B(a){if(!D(a))throw new i("INVALID_INPUT","Options must be an object.")}function E(a){if(a!==void 0&&!(a instanceof AbortSignal))throw new i("INVALID_INPUT","signal must be an AbortSignal.")}function tt(a){if(typeof a!="string"||!a.isWellFormed())throw new i("INVALID_INPUT","Content must be a well-formed Unicode string.")}function J(a){return typeof a=="string"&&!!a.trim()&&a.isWellFormed()&&a!=="."&&a!==".."&&a.toLowerCase()!==".git"&&!/[/\\\p{Cc}\p{Cf}\u115F\u1160\u3164\u2800\uFFA0]/u.test(a)}function A(a){if(!J(a))throw new i("INVALID_INPUT","Names must be nonempty, unambiguous path segments.");return a}function w(a){B(a);const t=a.signal;return E(t),t}const et=1e7;function rt(a){let t=!1,e=!1;for(let r=0;r<a.length;r++){const n=a[r];if(!t){n==='"'&&(t=!0);continue}if(n==="\\"){if(a[++r]==="u"&&/^[0-9a-fA-F]{4}$/.test(a.slice(r+1,r+5))){const o=Number.parseInt(a.slice(r+1,r+5),16);if(r+=4,o>=55296&&o<=56319){if(e)return!0;e=!0}else if(o>=56320&&o<=57343){if(!e)return!0;e=!1}else if(e)return!0}else if(e)return!0}else if(n==='"'){if(e)return!0;t=!1}else if(e)return!0}return e}function L(a,t=!0){tt(a);const e=_.byteLength(a,"utf8");if(t&&e>et)throw new i("TABLE_TOO_LARGE","Table exceeds 10,000,000 UTF-8 bytes.");if(a==="")return{recordCount:0,byteLength:0};const r=a.split(`
2
+ `);r.at(-1)===""&&r.pop();for(const[n,o]of r.entries()){let c;try{c=JSON.parse(o)}catch{throw new i("INVALID_JSONL","Every record line must be valid JSON.",{lineNumber:n+1})}if(rt(o))throw new i("INVALID_JSONL","JSONL contains invalid Unicode.",{lineNumber:n+1,reason:"INVALID_UNICODE"});if(!D(c))throw new i("INVALID_JSONL","Every record must be a JSON object.",{lineNumber:n+1})}return{recordCount:r.length,byteLength:e}}function O(a){if(!D(a))throw new i("INVALID_RESPONSE","Expected a GitHub response object.");return a}function I(a){if(typeof a!="string"||!/^[a-f0-9]{40}$/.test(a))throw new i("INVALID_RESPONSE","Expected a 40-character lowercase Git SHA.");return a}function P(a){if(typeof a!="string"||!a||!a.isWellFormed())throw new i("INVALID_RESPONSE","Expected a nonempty well-formed GitHub response field.");return a}function nt(a){if(typeof a!="string"||!a.trim()||!a.isWellFormed()||/[\p{Cc}\p{Cf}]/u.test(a))throw new i("INVALID_RESPONSE","Expected a valid well-formed GitHub branch name.");return a}function at(a,t){try{if(a===null||typeof a!="object")return;const e=a,r=e.status,n=e.ok,o=e.headers,c=e.json,s=e.arrayBuffer;if(typeof r!="number"||!Number.isInteger(r)||r<100||r>599||typeof n!="boolean"||n!==(r>=200&&r<300)||o===null||typeof o!="object")return;const d=o.get;if(typeof d!="function"||typeof c!="function"||typeof s!="function")return;const u=d.call(o,"x-github-request-id"),h=d.call(o,"retry-after");return u!==null&&typeof u!="string"||h!==null&&typeof h!="string"?void 0:{ok:n,json:c.bind(a),arrayBuffer:s.bind(a),details:{dispatched:t,status:r,requestId:u??void 0,retryAfter:h??void 0}}}catch{return}}function v(a,t,e){const r=Promise.resolve(a);return t?new Promise((n,o)=>{let c=!1;const s=()=>t.removeEventListener("abort",d),d=()=>{c||(c=!0,s(),o(e()))};t.addEventListener("abort",d,{once:!0}),r.then(u=>{c||(c=!0,s(),n(u))},u=>{c||(c=!0,s(),o(u))}),t.aborted&&d()}):r}function ot(a){const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(a);if(!t)return!1;const e=Number(t[1]),r=Number(t[2]),n=Number(t[3]);if(r<1||r>12)return!1;const o=[31,e%4===0&&(e%100!==0||e%400===0)?29:28,31,30,31,30,31,31,30,31,30,31];return n>=1&&n<=o[r-1]}class st{endpoint;prefix;headers;fetcher;timeout;constructor(t){B(t);for(const r of[t.token,t.owner,t.repo])if(typeof r!="string"||!r.trim())throw new i("INVALID_INPUT","token, owner and repo are required.");if(A(t.owner),A(t.repo),t.branch!==void 0&&(typeof t.branch!="string"||!t.branch.trim()||!t.branch.isWellFormed()||/[\p{Cc}\p{Cf}]/u.test(t.branch)))throw new i("INVALID_INPUT","branch must be nonempty, well-formed Unicode without control or format characters.");let e;try{e=new URL(t.endpoint??"https://api.github.com")}catch{throw new i("INVALID_INPUT","endpoint must be an absolute HTTP(S) URL.")}if(!["https:","http:"].includes(e.protocol)||e.search||e.hash||e.username||e.password)throw new i("INVALID_INPUT","endpoint cannot contain credentials, query or fragment.");if(t.timeout!==void 0&&(!Number.isSafeInteger(t.timeout)||t.timeout<=0||t.timeout>2147483647))throw new i("INVALID_INPUT","timeout must be between 1 and 2,147,483,647 milliseconds.");if(t.apiVersion!==void 0&&(typeof t.apiVersion!="string"||!ot(t.apiVersion)))throw new i("INVALID_INPUT","apiVersion must have YYYY-MM-DD format.");if(t.fetch!==void 0&&typeof t.fetch!="function")throw new i("INVALID_INPUT","fetch must be a function.");this.endpoint=e.href.replace(/\/+$/,""),this.prefix=`/repos/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repo)}`;try{this.headers=new Headers(t.headers)}catch{throw new i("INVALID_INPUT","Custom headers are not valid HTTP header values.")}for(const r of["authorization","accept","content-type","x-github-api-version"])if(this.headers.has(r))throw new i("INVALID_INPUT",`Custom headers cannot override ${r}.`);try{this.headers.set("Authorization",`Bearer ${t.token}`)}catch{throw new i("INVALID_INPUT","token is not a valid HTTP header value.")}this.headers.set("X-GitHub-Api-Version",t.apiVersion??"2026-03-10"),this.fetcher=t.fetch??globalThis.fetch,this.timeout=t.timeout}async request(t,e,r,n,o){E(o);let c=!1;const s=new Headers(this.headers);s.set("Accept",n?"application/vnd.github.raw+json":"application/vnd.github+json"),r!==void 0&&s.set("Content-Type","application/json");const d=o?[o]:[],u=this.timeout===void 0?void 0:AbortSignal.timeout(this.timeout);u&&d.push(u);const h=d.length?AbortSignal.any(d):void 0,l=e==="POST"&&t==="/git/commits",m=h,p=()=>l&&o?.aborted===!0,f=()=>new i(o?.aborted?"ABORTED":"TIMEOUT",o?.aborted?"Request was cancelled.":"Request timed out.",{dispatched:c});if(h?.aborted)throw f();let C;try{c=!0;const y=this.fetcher(`${this.endpoint}${this.prefix}${t}`,{method:e,headers:s,body:r===void 0?void 0:JSON.stringify(r),redirect:"manual",signal:h});C=await v(y,m,f)}catch{throw h?.aborted?f():new i("NETWORK_ERROR","GitHub request failed.",{dispatched:c})}if(h?.aborted&&!p())throw f();const T=at(C,c);if(!T)throw new i("INVALID_RESPONSE","fetch must return a valid Response.",{dispatched:c});const{details:N}=T;if(!T.ok)throw new i("HTTP_ERROR",`GitHub request returned HTTP ${N.status}.`,{...N,...N.status>=300&&N.status<400?{reason:"REDIRECT"}:{}});try{if(!n){const Q=await v(T.json(),m,f);if(h?.aborted&&!p())throw f();return Q}const y=await v(T.arrayBuffer(),m,f);let M;try{M=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(y)}catch{throw new i("INVALID_UTF8","File content is not valid UTF-8.",N)}if(h?.aborted&&!p())throw f();return M}catch(y){throw h?.aborted?f():y instanceof i?y:new i("INVALID_RESPONSE","Could not read the GitHub response.",N)}}async json(t,e="GET",r,n){return O(await this.request(t,e,r,!1,n))}scope(t){return JSON.stringify([this.endpoint,this.prefix,t])}}function it(a){if(typeof a!="string")throw new i("INVALID_INPUT","Path must be a string.");return a.split("/").forEach(A),a}function ct(a){const t=P(a);if(t.includes("/"))throw new i("INVALID_RESPONSE","GitHub returned an invalid tree entry path.");return t}class ht{constructor(t){this.transport=t}transport;tree(t,e,r){let n=t.trees.get(e);return n||(n=this.transport.json(`/git/trees/${e}`,"GET",void 0,r).then(o=>{if(o.truncated!==!1||!Array.isArray(o.tree))throw new i("INVALID_RESPONSE","GitHub returned an incomplete tree.");return o.tree.map(c=>{const s=O(c);return{path:ct(s.path),sha:I(s.sha),type:P(s.type),mode:P(s.mode)}})}),t.trees.set(e,n)),n}async resolve(t,e,r){const n=it(e).split("/");let o=t.treeSha;for(let c=0;c<n.length;c++){const s=(await this.tree(t,o,r)).find(d=>d.path===n[c]);if(!s)return;if(c===n.length-1)return s;if(s.type!=="tree")throw new i("INVALID_METADATA","A parent path is not a directory.",{path:n.slice(0,c+1).join("/"),reason:"PATH_NOT_DIRECTORY"});o=s.sha}}async find(t,e,r){const n=await this.resolve(t,e,r);if(n&&(n.type!=="blob"||!["100644","100755"].includes(n.mode)))throw new i("INVALID_METADATA","Path must reference a regular file.",{path:e,reason:"NOT_REGULAR_FILE"});return n}async directory(t,e,r){const n=await this.resolve(t,e,r);if(n){if(n.type!=="tree")throw new i("INVALID_METADATA","Path must reference a directory.",{path:e,reason:"PATH_NOT_DIRECTORY"});return this.tree(t,n.sha,r)}}}function R(a){const t=_.from(a,"utf8");return H("sha1").update(`blob ${t.byteLength}\0`).update(t).digest("hex")}class dt{transport;endpoint;files;branchName;branchLookup;queue=Promise.resolve();constructor(t){this.transport=new st(t),this.endpoint=t.endpoint??"https://api.github.com",this.files=new ht(this.transport),this.branchName=t.branch}async branch(t){if(t?.aborted)throw new i("ABORTED","Request was cancelled.",{dispatched:!1});if(this.branchName!==void 0)return this.branchName;if(this.branchLookup??=this.transport.json("").then(r=>(this.branchName=nt(r.default_branch),this.branchName)).finally(()=>{this.branchLookup=void 0}),!t)return this.branchLookup;const e=this.branchLookup;if(t.aborted)throw e.catch(()=>{}),new i("ABORTED","Request was cancelled.",{dispatched:!0});return new Promise((r,n)=>{const o=()=>n(new i("ABORTED","Request was cancelled.",{dispatched:!0}));t.addEventListener("abort",o,{once:!0}),e.then(r,n).finally(()=>t.removeEventListener("abort",o))})}async snapshot(t){E(t);const e=await this.branch(t),r=await this.transport.json(`/git/ref/heads/${encodeURIComponent(e)}`,"GET",void 0,t),n=I(O(r.object).sha),o=await this.transport.json(`/git/commits/${n}`,"GET",void 0,t);return{commitSha:n,treeSha:I(O(o.tree).sha),trees:new Map}}scope(){return this.transport.scope(this.branchName)}async content(t,e){return await this.transport.request(`/git/blobs/${t.sha}`,"GET",void 0,!0,e)}enqueue(t){const e=this.queue.then(t);return this.queue=e.then(()=>{},()=>{}),e}async createBlob(t,e){const r=await this.transport.json("/git/blobs","POST",{content:_.from(t,"utf8").toString("base64"),encoding:"base64"},e),n=I(r.sha);if(n!==R(t))throw new i("INVALID_RESPONSE","GitHub returned a blob SHA that does not match content.");return n}async commit(t,e,r,n){const o=await Promise.all(e.map(async h=>({path:h.path,mode:h.mode??"100644",type:"blob",sha:"sha"in h?h.sha:await this.createBlob(h.content,n)}))),c=await this.transport.json("/git/trees","POST",{base_tree:t.treeSha,tree:o},n),s=await this.transport.json("/git/commits","POST",{tree:I(c.sha),parents:[t.commitSha],message:r},n),d=I(s.sha),u=await this.branch();if(n?.aborted)throw new i("ABORTED","Write was cancelled before publication.",{dispatched:!0,reason:"BEFORE_PUBLICATION",commitSha:d});try{const h=await this.transport.json(`/git/refs/heads/${encodeURIComponent(u)}`,"PATCH",{sha:d,force:!1},n);if(I(O(h.object).sha)!==d)throw new i("INVALID_RESPONSE","Unexpected published commit.")}catch(h){if(h instanceof i){if(h.details.dispatched===!1)throw h;if(h.code==="HTTP_ERROR"&&h.details.status!==void 0&&h.details.status<500)throw h.details.status===409||h.details.status===422?new i("CONFLICT","GitHub rejected publication; inspect the cause before retrying.",{...h.details,reason:"PUBLISH_REJECTED"}):h}throw new i("WRITE_RESULT_UNKNOWN","Publication may have succeeded; verify before retrying.",{dispatched:!0,...h instanceof i?h.details:{},commitSha:d})}return{commitSha:d}}}const ut=512;function F(a,t,e){if(a>ut)throw new i(t,"JSON nesting exceeds 512 object/array containers.",{...e,reason:"TOO_DEEP"})}function G(a,t,e){let r=0,n=!1;for(let o=0;o<a.length;o++){const c=a[o];n&&c==="\\"?o++:c==='"'?n=!n:n||(c==="{"||c==="["?F(++r,t,e):(c==="}"||c==="]")&&r--)}}function q(a){const t=/^(-?)(\d+)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/.exec(a),e=t[3]??"",r=(t[2]+e).replace(/^0+/,""),n=r.replace(/0+$/,"");return{sign:r?t[1]:"",digits:n,exponent:r?BigInt(t[4]??0)-BigInt(e.length)+BigInt(r.length-n.length):0n}}const S=JSON;function lt(a){const{digits:t,exponent:e}=q(a);return!t||e>=0n}function V(a,t,e){const r=a[t],n=S.isRawJSON(r)?Number(r.rawJSON):r;if(typeof n!="number"||!Number.isSafeInteger(n)||n<0||Object.is(n,-0)||S.isRawJSON(r)&&!lt(r.rawJSON))throw new i("INVALID_METADATA","Metadata field must be a nonnegative safe integer.",{...e,reason:"INVALID_FIELD",field:t});return a[t]=n,n}function ft(a,t){G(a,"INVALID_METADATA",t);let e;try{e=S.parse(a,(r,n,o)=>typeof n=="number"&&JSON.stringify(n)!==o.source?S.rawJSON(o.source):n)}catch{throw new i("INVALID_METADATA","meta.json must contain valid JSON.",{...t,reason:"INVALID_JSON"})}if(!D(e))throw new i("INVALID_METADATA","meta.json must contain an object.",{...t,reason:"INVALID_FIELD"});if(V(e,"version",t)!==1)throw new i("INVALID_METADATA","Unsupported metadata format version.",{...t,reason:"UNSUPPORTED_VERSION",field:"version"});for(const r of["createdAt","updatedAt","recordCount","byteLength"])V(e,r,t);if(V(e,"revision",t)===0||typeof e.dataSha!="string"||!/^[a-f0-9]{40}$/.test(e.dataSha))throw new i("INVALID_METADATA","Table revision or dataSha is invalid.",{...t,reason:"INVALID_FIELD",field:"revision/dataSha"});return e}function pt(a){return JSON.stringify(a,null,2)+`
3
+ `}class k{constructor(t,e,r){this.repository=t,this.dbName=e,this.name=r,A(e),A(r),this.root=`${e}/${r}`,this.metaPath=`${this.root}/meta.json`,this.dataPath=`${this.root}/data.jsonl`}repository;dbName;name;root;metaPath;dataPath;context(t=this.metaPath){return{path:t,table:this.name}}async metadata(t,e){const r=await this.repository.files.find(t,this.metaPath,e);if(!r){if((await this.repository.files.directory(t,this.root,e))?.length)throw new i("INVALID_METADATA","Existing table is missing meta.json.",{...this.context(),reason:"MISSING_METADATA"});return}const n=await this.repository.content(r,e);if(R(n)!==r.sha)throw new i("INVALID_METADATA","meta.json SHA does not match its content.",{...this.context(),reason:"META_SHA_MISMATCH"});return{meta:ft(n,this.context()),entry:r}}async state(t,e){const[r,n]=await Promise.all([this.metadata(t,e),this.repository.files.find(t,this.dataPath,e)]);if(r&&!n)throw new i("INVALID_METADATA","Table is missing data.jsonl.",{...this.context(),path:this.dataPath,reason:"MISSING_DATA"});return{metadata:r,data:n}}async validatedContent(t,e){if(!t.metadata||!t.data)return"";const{meta:r}=t.metadata;if(r.dataSha!==t.data.sha)throw new i("INVALID_METADATA","dataSha does not match data.jsonl.",{...this.context(),path:this.dataPath,reason:"DATA_SHA_MISMATCH"});const n=await this.repository.content(t.data,e);if(R(n)!==t.data.sha)throw new i("INVALID_METADATA","dataSha does not match data.jsonl.",{...this.context(),path:this.dataPath,reason:"DATA_SHA_MISMATCH"});const o=L(n,!1);if(o.recordCount!==r.recordCount||o.byteLength!==r.byteLength)throw new i("INVALID_METADATA","Statistics do not match data.jsonl.",{...this.context(),path:this.dataPath,reason:"STATISTICS_MISMATCH"});return n}async write(t,e,r,n,o,c){const s=Date.now(),d=(e.metadata?.meta.revision??0)+1;if(!Number.isSafeInteger(d))throw new i("INVALID_METADATA","Table revision cannot be incremented safely.",{...this.context(),reason:"REVISION_OVERFLOW",field:"revision"});const u=await this.repository.createBlob(r,c),h={...e.metadata?.meta,version:1,createdAt:e.metadata?.meta.createdAt??s,updatedAt:s,...n,revision:d,dataSha:u},l=await this.repository.commit(t,[{path:this.dataPath,sha:u,mode:e.data?.mode},{path:this.metaPath,content:pt(h),mode:e.metadata?.entry.mode}],`github-db: ${o} ${JSON.stringify(this.root)}
4
4
 
5
5
  client: @secret-momo/github-db
6
- endpoint: ${this.repository.endpoint}`,o);return{meta:h,commitSha:p.commitSha}}}function O(a,t="INVALID_INPUT",e={}){const r=()=>{throw new i(t,"Expected a plain JSON object with only serializable values.",{...e,reason:"NOT_JSON"})},n=new Set,s=(o,c,d)=>{if(o===null||typeof o=="boolean")return;if(typeof o=="string"){o.isWellFormed()||r();return}if(typeof o=="number"){Number.isFinite(o)||r();return}if(typeof o!="object"||o===null)return r();M(c,t,{...e,field:d});const u=Array.isArray(o),h=Object.getPrototypeOf(o);((u?h!==Array.prototype:h!==Object.prototype&&h!==null)||n.has(o))&&r(),n.add(o);const p=Reflect.ownKeys(o);u&&p.length!==o.length+1&&r();for(const l of p){if(u&&l==="length")continue;if(typeof l!="string"||!l.isWellFormed())return r();u&&(!/^(0|[1-9]\d*)$/.test(l)||Number(l)>=o.length)&&r();const m=Object.getOwnPropertyDescriptor(o,l);(!m.enumerable||!("value"in m))&&r(),s(m.value,c+1,`${d}.${l}`)}n.delete(o)};try{return g(a)?(s(a,1,"$"),JSON.parse(JSON.stringify(a))):r()}catch(o){if(o instanceof i)throw o;return r()}}function D(a,t="INVALID_INPUT",e={}){if(typeof a!="string"||!a.trim()||!a.isWellFormed())throw new i(t,"id must be a nonempty, well-formed string.",{...e,reason:"INVALID_ID",field:"id"})}function F(a){const{sign:t,digits:e,exponent:r}=J(a);return e?`${t}${e}e${r}`:"0"}const lt=JSON.parse;function G(a,t){if(!a)return[];const e=a.split(`
7
- `);e.at(-1)===""&&e.pop();const r=new Set;return e.map((n,s)=>{const o={...t,lineNumber:s+1};$(n,"INVALID_RECORD",o);let c;try{c=lt(n,(u,h,p)=>{if(typeof h=="number"&&(!Number.isFinite(h)||F(p.source)!==F(JSON.stringify(h))))throw new i("INVALID_RECORD","Record number cannot round-trip without losing precision.",{...t,lineNumber:s+1,reason:"NUMERIC_PRECISION"});return h})}catch(u){throw u instanceof i?u:new i("INVALID_RECORD","Record line could not be parsed.",{...o,reason:"UNPARSABLE"})}const d=O(c,"INVALID_RECORD",o);D(d.id,"INVALID_RECORD",o);for(const u of["createdAt","updatedAt"]){const h=c[u];if(typeof h!="number"||!Number.isSafeInteger(h)||h<0||Object.is(h,-0))throw new i("INVALID_RECORD","Record timestamps must be nonnegative safe integers.",{...o,reason:"INVALID_TIMESTAMP",field:u})}if(r.has(d.id))throw new i("DUPLICATE_ID","Duplicate id in table data.",{...o,reason:"DUPLICATE_ID",field:"id"});return r.add(d.id),{record:d,source:n}})}function ft(a){return a.length?a.map(t=>t.source).join(`
6
+ endpoint: ${this.repository.endpoint}`,c);return{meta:h,commitSha:l.commitSha}}}function b(a,t="INVALID_INPUT",e={},r=1){const n=()=>{throw new i(t,"Expected a plain JSON object with only serializable values.",{...e,reason:"NOT_JSON"})},o=new Set,c=(s,d,u)=>{if(s===null||typeof s=="boolean")return;if(typeof s=="string"){s.isWellFormed()||n();return}if(typeof s=="number"){Number.isFinite(s)||n();return}if(typeof s!="object"||s===null)return n();F(d,t,{...e,field:u});const h=Array.isArray(s),l=Object.getPrototypeOf(s);((h?l!==Array.prototype:l!==Object.prototype&&l!==null)||o.has(s))&&n(),o.add(s);const m=Reflect.ownKeys(s);h&&m.length!==s.length+1&&n();for(const p of m){if(h&&p==="length")continue;if(typeof p!="string"||!p.isWellFormed())return n();h&&(!/^(0|[1-9]\d*)$/.test(p)||Number(p)>=s.length)&&n();const f=Object.getOwnPropertyDescriptor(s,p);(!f.enumerable||!("value"in f))&&n(),c(f.value,d+1,`${u}.${p}`)}o.delete(s)};try{return D(a)?(c(a,r,"$"),JSON.parse(JSON.stringify(a))):n()}catch(s){if(s instanceof i)throw s;return n()}}function U(a,t){const e=r=>{throw new i("INVALID_INPUT","Expected a plain dense array of batch inputs.",{reason:"NOT_JSON",...r===void 0?{}:{itemIndex:r}})};try{if(!Array.isArray(a)||Object.getPrototypeOf(a)!==Array.prototype||Reflect.ownKeys(a).length!==a.length+1)return e();const r=[];for(let n=0;n<a.length;n++){const o=Object.getOwnPropertyDescriptor(a,String(n));(!o?.enumerable||!("value"in o))&&e(n),r.push(t(o.value,n))}return r}catch(r){if(r instanceof i)throw r;return e()}}function g(a,t="INVALID_INPUT",e={}){if(typeof a!="string"||!a.trim()||!a.isWellFormed())throw new i(t,"id must be a nonempty, well-formed string.",{...e,reason:"INVALID_ID",field:"id"})}function W(a){const{sign:t,digits:e,exponent:r}=q(a);return e?`${t}${e}e${r}`:"0"}const mt=JSON.parse;function K(a,t){if(!a)return[];const e=a.split(`
7
+ `);e.at(-1)===""&&e.pop();const r=new Set;return e.map((n,o)=>{const c={...t,lineNumber:o+1};G(n,"INVALID_RECORD",c);let s;try{s=mt(n,(u,h,l)=>{if(typeof h=="number"&&(!Number.isFinite(h)||W(l.source)!==W(JSON.stringify(h))))throw new i("INVALID_RECORD","Record number cannot round-trip without losing precision.",{...t,lineNumber:o+1,reason:"NUMERIC_PRECISION"});return h})}catch(u){throw u instanceof i?u:new i("INVALID_RECORD","Record line could not be parsed.",{...c,reason:"UNPARSABLE"})}const d=b(s,"INVALID_RECORD",c);g(d.id,"INVALID_RECORD",c);for(const u of["createdAt","updatedAt"]){const h=s[u];if(typeof h!="number"||!Number.isSafeInteger(h)||h<0||Object.is(h,-0))throw new i("INVALID_RECORD","Record timestamps must be nonnegative safe integers.",{...c,reason:"INVALID_TIMESTAMP",field:u})}if(r.has(d.id))throw new i("DUPLICATE_ID","Duplicate id in table data.",{...c,reason:"DUPLICATE_ID",field:"id"});return r.add(d.id),{record:d,source:n}})}function wt(a){return a.length?a.map(t=>t.source).join(`
8
8
  `)+`
9
- `:""}class q{constructor(t,e,r){this.repository=t,this.dbName=e,this.name=r,this.storage=new B(t,e,r)}repository;dbName;name;storage;async findAll(t={},e={}){const r=A(e),n=O(t),s=await this.repository.snapshot(r),o=await this.storage.state(s,r);return G(await this.storage.validatedContent(o,r),this.storage.context(this.storage.dataPath)).filter(({record:c})=>Object.entries(n).every(([d,u])=>Object.hasOwn(c,d)&&K(c[d],u))).map(({record:c})=>c)}async find(t={},e={}){return(await this.findAll(t,e))[0]??null}async findById(t,e={}){return D(t),this.find({id:t},e)}async insert(t,e={}){const r=O(t);if(Object.hasOwn(r,"createdAt")||Object.hasOwn(r,"updatedAt"))throw new i("INVALID_INPUT","Record timestamps are managed by the SDK.");const n=Object.hasOwn(r,"id")?r.id:z();return D(n),this.mutate("insert",s=>{if(s.some(({record:d})=>d.id===n))throw new i("DUPLICATE_ID","id already exists in this table.",{...this.storage.context(this.storage.dataPath),reason:"DUPLICATE_ID",field:"id"});const o=Date.now(),c={...r,id:n,createdAt:o,updatedAt:o};return s.push({record:c,source:JSON.stringify(c)}),{result:c,write:!0}},e)}async updateById(t,e,r={}){D(t);const n=O(e);if(!Object.keys(n).length||["id","createdAt","updatedAt"].some(s=>Object.hasOwn(n,s)))throw new i("INVALID_INPUT","Update requires business fields and cannot change system fields.");return this.mutate("update",s=>{const o=s.find(({record:d})=>d.id===t);if(!o)throw new i("NOT_FOUND","Record does not exist.",{...this.storage.context(this.storage.dataPath),reason:"RECORD_NOT_FOUND"});const c={...o.record,...n,updatedAt:Date.now()};return o.record=c,o.source=JSON.stringify(c),{result:c,write:!0}},r)}async deleteById(t,e={}){return D(t),this.mutate("delete",r=>{const n=r.findIndex(({record:s})=>s.id===t);return n<0?{result:!1,write:!1}:(r.splice(n,1),{result:!0,write:!0})},e)}async mutate(t,e,r){const n=A(r);return this.repository.enqueue(async()=>{const s=await this.repository.snapshot(n),o=await this.storage.state(s,n),c=G(await this.storage.validatedContent(o,n),this.storage.context(this.storage.dataPath)),d=e(c);if(d.write){const u=ft(c);await this.storage.write(s,o,u,L(u),t,n)}return d.result})}}class k{constructor(t,e,r){this.repository=t,this.dbName=e,this.name=r,this.storage=new B(t,e,r)}repository;dbName;name;storage;version(t,e){return C("sha256").update(JSON.stringify([this.repository.scope(),this.dbName,this.name,t.revision,e])).digest("hex")}async read(t={}){const e=A(t),r=await this.repository.snapshot(e),n=await this.storage.state(r,e);if(!n.metadata||!n.data)throw new i("NOT_FOUND","Table does not exist.",{...this.storage.context(),path:this.storage.dataPath,reason:"TABLE_NOT_FOUND"});return{content:await this.storage.validatedContent(n,e),meta:n.metadata.meta,version:this.version(n.metadata.meta,n.data.sha),commitSha:r.commitSha}}async write(t,e={}){const r=A(e),n=e.expectedVersion;if(n!=null&&(typeof n!="string"||!/^[a-f0-9]{64}$/.test(n)))throw new i("INVALID_INPUT","expectedVersion must be an opaque table version or null.");const s=L(t);return this.repository.enqueue(async()=>{const o=await this.repository.snapshot(r),c=await this.storage.state(o,r),d=c.metadata&&c.data?this.version(c.metadata.meta,c.data.sha):null;if(n!==void 0&&n!==d)throw new i("CONFLICT","Table version does not match expectedVersion.",{...this.storage.context(),path:this.storage.dataPath,reason:"VERSION_MISMATCH"});await this.storage.validatedContent(c,r);const u=await this.storage.write(o,c,t,s,"write",r);return{...u,version:this.version(u.meta,u.meta.dataSha)}})}async getMeta(t={}){const e=A(t),r=await this.repository.snapshot(e),n=await this.storage.metadata(r,e);if(!n)throw new i("NOT_FOUND","Table does not exist.",{...this.storage.context(),reason:"TABLE_NOT_FOUND"});return{meta:n.meta,commitSha:r.commitSha}}}class W{constructor(t,e){this.repository=t,this.name=e,N(e)}repository;name;async listTables(t={}){const e=A(t),r=await this.repository.snapshot(e),n=await this.repository.files.directory(r,this.name,e);return(await Promise.all((n??[]).filter(s=>s.type==="tree"&&H(s.path)).map(async s=>{const o=await this.repository.files.directory(r,`${this.name}/${s.path}`,e),c=new Set(o?.filter(d=>d.type==="blob"&&["100644","100755"].includes(d.mode)).map(d=>d.path));return c.has("meta.json")&&c.has("data.jsonl")?s.path:void 0}))).filter(s=>s!==void 0).sort()}getTable(t){return new k(this.repository,this.name,t)}getRecordTable(t){return new q(this.repository,this.name,t)}}class pt{repository;constructor(t){this.repository=new it(t)}getDB(t){return new W(this.repository,t)}}export{pt as GitHubDBClient,i as GitHubDBError,W as GitHubDatabase,q as GitHubRecordTable,k as GitHubTable};
9
+ `:""}function j(a,t,e,r){if(g(a,"INVALID_INPUT",{itemIndex:e}),t.has(a))throw new i(r,"Batch inputs contain a duplicate id.",{reason:"DUPLICATE_ID",field:"id",itemIndex:e});return t.add(a),a}function x(a){const t=w(a);if(t?.aborted)throw new i("ABORTED","Request was cancelled.",{dispatched:!1});return t}class Y{constructor(t,e,r){this.repository=t,this.dbName=e,this.name=r,this.storage=new k(t,e,r)}repository;dbName;name;storage;async findAll(t={},e={}){const r=w(e),n=b(t),o=await this.repository.snapshot(r),c=await this.storage.state(o,r);return K(await this.storage.validatedContent(c,r),this.storage.context(this.storage.dataPath)).filter(({record:s})=>Object.entries(n).every(([d,u])=>Object.hasOwn(s,d)&&Z(s[d],u))).map(({record:s})=>s)}async find(t={},e={}){return(await this.findAll(t,e))[0]??null}async findById(t,e={}){return g(t),this.find({id:t},e)}async insert(t,e={}){const r=b(t);if(Object.hasOwn(r,"createdAt")||Object.hasOwn(r,"updatedAt"))throw new i("INVALID_INPUT","Record timestamps are managed by the SDK.");const n=Object.hasOwn(r,"id")?r.id:$();return g(n),this.mutate("insert",o=>{if(o.some(({record:d})=>d.id===n))throw new i("DUPLICATE_ID","id already exists in this table.",{...this.storage.context(this.storage.dataPath),reason:"DUPLICATE_ID",field:"id"});const c=Date.now(),s={...r,id:n,createdAt:c,updatedAt:c};return o.push({record:s,source:JSON.stringify(s)}),{result:s,write:!0}},e)}async updateById(t,e,r={}){g(t);const n=b(e);if(!Object.keys(n).length||["id","createdAt","updatedAt"].some(o=>Object.hasOwn(n,o)))throw new i("INVALID_INPUT","Update requires business fields and cannot change system fields.");return this.mutate("update",o=>{const c=o.find(({record:d})=>d.id===t);if(!c)throw new i("NOT_FOUND","Record does not exist.",{...this.storage.context(this.storage.dataPath),reason:"RECORD_NOT_FOUND"});const s={...c.record,...n,updatedAt:Date.now()};return c.record=s,c.source=JSON.stringify(s),{result:s,write:!0}},r)}async insertMany(t,e={}){const r=x(e),n=new Set,o=U(t,(c,s)=>{const d=b(c,"INVALID_INPUT",{itemIndex:s});if(Object.hasOwn(d,"createdAt")||Object.hasOwn(d,"updatedAt"))throw new i("INVALID_INPUT","Record timestamps are managed by the SDK.",{itemIndex:s});const u=j(Object.hasOwn(d,"id")?d.id:$(),n,s,"DUPLICATE_ID");return{...d,id:u}});return o.length?this.mutate("insertMany",c=>{const s=new Set(c.map(({record:h})=>h.id));for(const[h,l]of o.entries())if(s.has(l.id))throw new i("DUPLICATE_ID","id already exists in this table.",{...this.storage.context(this.storage.dataPath),reason:"DUPLICATE_ID",field:"id",itemIndex:h});const d=Date.now(),u=o.map(h=>({...h,createdAt:d,updatedAt:d}));for(const h of u)c.push({record:h,source:JSON.stringify(h)});return{result:u,write:!0}},{signal:r}):[]}async updateManyById(t,e={}){const r=x(e),n=new Set,o=U(t,(c,s)=>{const d=b(c,"INVALID_INPUT",{itemIndex:s},0);if(Object.keys(d).length!==2||!Object.hasOwn(d,"id")||!Object.hasOwn(d,"patch"))throw new i("INVALID_INPUT","Update entries require only id and patch.",{itemIndex:s});const u=j(d.id,n,s,"INVALID_INPUT"),h=b(d.patch,"INVALID_INPUT",{itemIndex:s});if(!Object.keys(h).length||["id","createdAt","updatedAt"].some(l=>Object.hasOwn(h,l)))throw new i("INVALID_INPUT","Update requires business fields and cannot change system fields.",{itemIndex:s});return{id:u,patch:h}});return o.length?this.mutate("updateManyById",c=>{const s=new Map(c.map(u=>[u.record.id,u]));for(const[u,h]of o.entries())if(!s.has(h.id))throw new i("NOT_FOUND","Record does not exist.",{...this.storage.context(this.storage.dataPath),reason:"RECORD_NOT_FOUND",itemIndex:u});const d=Date.now();return{result:o.map(({id:u,patch:h})=>{const l=s.get(u),m={...l.record,...h,updatedAt:d};return l.record=m,l.source=JSON.stringify(m),m}),write:!0}},{signal:r}):[]}async deleteManyById(t,e={}){const r=x(e),n=new Set,o=U(t,(c,s)=>j(c,n,s,"INVALID_INPUT"));return o.length?this.mutate("deleteManyById",c=>{const s=new Set(c.map(({record:h})=>h.id)),d=o.map(h=>s.has(h));if(!d.some(Boolean))return{result:d,write:!1};let u=0;for(const h of c)n.has(h.record.id)||(c[u++]=h);return c.length=u,{result:d,write:!0}},{signal:r}):[]}async deleteById(t,e={}){return g(t),this.mutate("delete",r=>{const n=r.findIndex(({record:o})=>o.id===t);return n<0?{result:!1,write:!1}:(r.splice(n,1),{result:!0,write:!0})},e)}async mutate(t,e,r){const n=w(r);return this.repository.enqueue(async()=>{const o=await this.repository.snapshot(n),c=await this.storage.state(o,n),s=K(await this.storage.validatedContent(c,n),this.storage.context(this.storage.dataPath)),d=e(s);if(d.write){const u=wt(s);await this.storage.write(o,c,u,L(u),t,n)}return d.result})}}class z{constructor(t,e,r){this.repository=t,this.dbName=e,this.name=r,this.storage=new k(t,e,r)}repository;dbName;name;storage;version(t,e){return H("sha256").update(JSON.stringify([this.repository.scope(),this.dbName,this.name,t.revision,e])).digest("hex")}async read(t={}){const e=w(t),r=await this.repository.snapshot(e),n=await this.storage.state(r,e);if(!n.metadata||!n.data)throw new i("NOT_FOUND","Table does not exist.",{...this.storage.context(),path:this.storage.dataPath,reason:"TABLE_NOT_FOUND"});return{content:await this.storage.validatedContent(n,e),meta:n.metadata.meta,version:this.version(n.metadata.meta,n.data.sha),commitSha:r.commitSha}}async write(t,e={}){const r=w(e),n=e.expectedVersion;if(n!=null&&(typeof n!="string"||!/^[a-f0-9]{64}$/.test(n)))throw new i("INVALID_INPUT","expectedVersion must be an opaque table version or null.");const o=L(t);return this.repository.enqueue(async()=>{const c=await this.repository.snapshot(r),s=await this.storage.state(c,r),d=s.metadata&&s.data?this.version(s.metadata.meta,s.data.sha):null;if(n!==void 0&&n!==d)throw new i("CONFLICT","Table version does not match expectedVersion.",{...this.storage.context(),path:this.storage.dataPath,reason:"VERSION_MISMATCH"});await this.storage.validatedContent(s,r);const u=await this.storage.write(c,s,t,o,"write",r);return{...u,version:this.version(u.meta,u.meta.dataSha)}})}async getMeta(t={}){const e=w(t),r=await this.repository.snapshot(e),n=await this.storage.metadata(r,e);if(!n)throw new i("NOT_FOUND","Table does not exist.",{...this.storage.context(),reason:"TABLE_NOT_FOUND"});return{meta:n.meta,commitSha:r.commitSha}}}class X{constructor(t,e){this.repository=t,this.name=e,A(e)}repository;name;async listTables(t={}){const e=w(t),r=await this.repository.snapshot(e),n=await this.repository.files.directory(r,this.name,e);return(await Promise.all((n??[]).filter(o=>o.type==="tree"&&J(o.path)).map(async o=>{const c=await this.repository.files.directory(r,`${this.name}/${o.path}`,e),s=new Set(c?.filter(d=>d.type==="blob"&&["100644","100755"].includes(d.mode)).map(d=>d.path));return s.has("meta.json")&&s.has("data.jsonl")?o.path:void 0}))).filter(o=>o!==void 0).sort()}getTable(t){return new z(this.repository,this.name,t)}getRecordTable(t){return new Y(this.repository,this.name,t)}}class It{repository;constructor(t){this.repository=new dt(t)}getDB(t){return new X(this.repository,t)}}export{It as GitHubDBClient,i as GitHubDBError,X as GitHubDatabase,Y as GitHubRecordTable,z as GitHubTable};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@secret-momo/github-db",
3
- "version": "1.0.1",
3
+ "version": "1.1.0",
4
4
  "description": "A lightweight wrapper that turns a GitHub repository into a simple database.",
5
5
  "type": "module",
6
6
  "packageManager": "bun@1.4.2",
@@ -64,18 +64,18 @@
64
64
  "devDependencies": {
65
65
  "@eslint/js": "10.0.1",
66
66
  "@types/bun": "1.4.2",
67
- "eslint": "10.11.0",
67
+ "eslint": "10.12.0",
68
68
  "eslint-plugin-import-x": "4.17.1",
69
69
  "eslint-plugin-unused-imports": "4.4.1",
70
70
  "husky": "9.1.7",
71
71
  "jiti": "2.7.0",
72
- "lint-staged": "17.5.1",
73
- "prettier": "3.9.8",
74
- "rollup": "4.63.4",
72
+ "lint-staged": "17.6.0",
73
+ "prettier": "3.9.9",
74
+ "rollup": "4.64.1",
75
75
  "rollup-plugin-dts": "6.5.1",
76
76
  "rollup-plugin-esbuild": "6.2.1",
77
77
  "typescript": "6.0.3",
78
- "typescript-eslint": "8.70.0"
78
+ "typescript-eslint": "8.71.1"
79
79
  },
80
80
  "license": "MIT"
81
81
  }