@secret-momo/github-db 1.1.0 → 1.2.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 +14 -3
- package/docs/architecture.md +3 -1
- package/docs/requirements.md +2 -2
- package/docs/testing.md +3 -1
- package/lib/index.d.ts +1 -1
- package/lib/index.js +6 -6
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -28,7 +28,7 @@ const client = new GitHubDBClient({
|
|
|
28
28
|
owner: 'your-owner',
|
|
29
29
|
repo: 'your-repo',
|
|
30
30
|
// branch: 'main', // 省略时发现并缓存默认分支;空/全空白值非法
|
|
31
|
-
// timeout: 30_000, //
|
|
31
|
+
// timeout: 30_000, // 默认每个请求 30 秒,可覆盖
|
|
32
32
|
});
|
|
33
33
|
const db = client.getDB('workbench');
|
|
34
34
|
```
|
|
@@ -57,9 +57,9 @@ const proxied = new GitHubDBClient({
|
|
|
57
57
|
});
|
|
58
58
|
```
|
|
59
59
|
|
|
60
|
-
URL 保留 endpoint 路径前缀,例如 `/api/github/repos/your-owner/your-repo/git/...`。所有请求和 raw blob 下载均经过该地址;GitHub Bearer token 与代理 header 同时发送。自定义 header 不能覆盖 Authorization、Accept、Content-Type 或 X-GitHub-Api-Version。endpoint
|
|
60
|
+
URL 保留 endpoint 路径前缀,例如 `/api/github/repos/your-owner/your-repo/git/...`。所有请求和 raw blob 下载均经过该地址;GitHub Bearer token 与代理 header 同时发送。自定义 header 不能覆盖 Authorization、Accept、Content-Type 或 X-GitHub-Api-Version。endpoint 必须使用 HTTPS;仅 localhost、127.0.0.1 和 ::1 可使用 HTTP。URL 不得包含凭据、查询或 fragment,不跟随重定向。
|
|
61
61
|
|
|
62
|
-
还可注入 `fetch(url, init)`。timeout
|
|
62
|
+
还可注入 `fetch(url, init)`。timeout 是每个请求的超时,默认 30 秒,可配置为 1~2,147,483,647 毫秒;整个多请求操作的耗时可能超过单次超时。apiVersion 为日期字符串,默认 `2026-03-10`。
|
|
63
63
|
|
|
64
64
|
## 类型化 CRUD
|
|
65
65
|
|
|
@@ -156,6 +156,17 @@ const deletedBatch = await todos.deleteManyById([inserted[0]!.id, 'missing']);
|
|
|
156
156
|
|
|
157
157
|
首个检测到的元素错误携带从 0 开始的 details.itemIndex;批内重复指向后一次出现的位置,不收集全部错误、不回显业务内容。已有表损坏、容量和发布错误沿用原诊断,不添加 itemIndex。修改后的完整表仍不能超过 10,000,000 UTF-8 字节,不另设固定条数上限、不自动分块或重试。发布后 WRITE_RESULT_UNKNOWN 表示整批可能已经成功;自动 id 插入此时拿不到正常返回的 id 数组,需要可靠核验/重试的业务应自行提供稳定 id。SDK 不提供幂等键或导入恢复机制。
|
|
158
158
|
|
|
159
|
+
每次操作会重新读取 Git 快照。以下是默认分支已缓存、已有一张表时的典型 GitHub API 请求数;首次发现默认分支会多一次请求,目录状态也会影响实际次数:
|
|
160
|
+
|
|
161
|
+
| 操作 | 典型请求数 |
|
|
162
|
+
| ---------------------------- | ---------: |
|
|
163
|
+
| `insert` | 12 |
|
|
164
|
+
| `insertMany`(任意非空批次) | 12 |
|
|
165
|
+
| `findById` | 7 |
|
|
166
|
+
| `listTables`(一张表) | 5 |
|
|
167
|
+
|
|
168
|
+
批量写入用相近的请求数处理整批记录。需要写入多条记录时,优先使用 `insertMany`、`updateManyById` 或 `deleteManyById`。
|
|
169
|
+
|
|
159
170
|
## 底层字符串 API
|
|
160
171
|
|
|
161
172
|
底层只要求每行是 JSON 对象,不要求业务 id 或记录时间字段,也不解析为业务类型:
|
package/docs/architecture.md
CHANGED
|
@@ -57,6 +57,8 @@ src/
|
|
|
57
57
|
|
|
58
58
|
缓存仅包括默认分支缓存、首次发现请求合并和单次快照内 tree Promise 去重。跨操作读取重新获取快照和文件内容,不增加实例级 blob LRU、跨操作 SHA 缓存或 ETag/304 分支。若需求转向高频轮询,应先评估请求预算和存储定位,再以负载证据决定缓存策略。
|
|
59
59
|
|
|
60
|
+
默认分支已缓存且表已存在时,单次记录写入和非空批量写入通常各需约 12 次 GitHub API 请求,`findById` 约 7 次;`listTables` 在一张表时约 5 次,并将目录请求并发限制为 8。请求数随目录状态和快照内 tree 去重而变化,批量 API 可避免逐条重复支付整表读改写的请求成本。
|
|
61
|
+
|
|
60
62
|
TableStorage 在同一个快照定位 meta/data,解析 meta 并核对存在性。表目录已有内容而 meta 缺失、meta 存在但 data 缺失,均视为损坏。读取 raw blob 严格 UTF-8 解码,检查 dataSha、JSONL 与统计;不能以空表替代坏状态。getMeta 只加载元信息。
|
|
61
63
|
|
|
62
64
|
meta 的已知数值字段验证精确数学值与安全整数,拒绝负零;未知字段通过 JSON source/raw API 保留无法直接表示的原始数字。此能力依赖 Node.js 24+/Bun。
|
|
@@ -105,7 +107,7 @@ batchItems 检查普通密集数组与属性描述符,避免执行访问器,
|
|
|
105
107
|
|
|
106
108
|
HTTP 请求保留 endpoint 前缀和 GitHub path。GitHub 管理 header 与代理 header 同时发送,不跟随重定向。所有后续 URL/提交使用的 Git SHA 先验证为 40 位小写十六进制。
|
|
107
109
|
|
|
108
|
-
每次请求合并 caller signal
|
|
110
|
+
每次请求合并 caller signal 与默认 30 秒的可配置 timeout,原始数据按 UTF-8 fatal 解码。错误不回显上游正文,保留状态、requestId、retryAfter、dispatched。仅发布 PATCH 的 409/422 归类 CONFLICT/PUBLISH_REJECTED;其他阶段保留 HTTP_ERROR。发布后非确定响应归 WRITE_RESULT_UNKNOWN,并附 commitSha;发布 PATCH 未发送时 caller 取消为 ABORTED、超时为 TIMEOUT,已取得并验证的 commit SHA 可附带,未知 SHA 不保证;投递前取消保持已知 SHA 时的 BEFORE_PUBLICATION 语义。
|
|
109
111
|
|
|
110
112
|
创建 Git 对象或 tree 后,取消/超时可能留下未发布对象;SDK 不继续发布、不自动重试。发布 PATCH 已投递后的取消、超时或异常继续归 WRITE_RESULT_UNKNOWN,并携带尝试 commitSha。
|
|
111
113
|
|
package/docs/requirements.md
CHANGED
|
@@ -4,11 +4,11 @@
|
|
|
4
4
|
|
|
5
5
|
## 1. 环境与连接
|
|
6
6
|
|
|
7
|
-
TypeScript ESM npm SDK,支持 Node.js 24+ 与 Bun。运行与开发环境仅支持 macOS 和 Linux,不支持 Windows。client 配置 token、owner、repo,可选 branch、endpoint、headers、timeout、fetch、apiVersion。branch 省略时发现并缓存默认分支;显式 branch 必须是非空字符串,空字符串或全空白字符串报 INVALID_INPUT,分支值不做 trim 或 Unicode 归一化。仓库与目标分支必须人工保证已有至少一次提交,SDK 不初始化空仓库或创建分支。
|
|
7
|
+
TypeScript ESM npm SDK,支持 Node.js 24+ 与 Bun。运行与开发环境仅支持 macOS 和 Linux,不支持 Windows。client 配置 token、owner、repo,可选 branch、endpoint、headers、timeout、fetch、apiVersion。timeout 默认每个请求 30 秒,可配置为 1~2,147,483,647 毫秒;多请求操作没有整体 30 秒上限。branch 省略时发现并缓存默认分支;显式 branch 必须是非空字符串,空字符串或全空白字符串报 INVALID_INPUT,分支值不做 trim 或 Unicode 归一化。仓库与目标分支必须人工保证已有至少一次提交,SDK 不初始化空仓库或创建分支。
|
|
8
8
|
|
|
9
9
|
交付仅提供 ESM import 入口,不提供 CommonJS require/default 入口或 CJS 产物。支持从 npm registry 安装发布包,或在本地构建后使用;不支持直接安装 Git URL 依赖。
|
|
10
10
|
|
|
11
|
-
endpoint 保留路径前缀后拼接 GitHub API path。所有请求、包括 raw 下载都经过该地址;额外代理 header 与 GitHub Bearer token 同时发送,不允许覆盖 SDK 管理的鉴权、媒体类型或 API 版本 header
|
|
11
|
+
endpoint 保留路径前缀后拼接 GitHub API path。所有请求、包括 raw 下载都经过该地址;额外代理 header 与 GitHub Bearer token 同时发送,不允许覆盖 SDK 管理的鉴权、媒体类型或 API 版本 header。endpoint 必须使用 HTTPS,仅 loopback 地址 localhost、127.0.0.1、::1 可使用 HTTP;不跟随重定向,不接受凭据、查询或 fragment。API 日期版本默认 2026-03-10,可配置。
|
|
12
12
|
|
|
13
13
|
## 2. 存储单位
|
|
14
14
|
|
package/docs/testing.md
CHANGED
|
@@ -8,13 +8,15 @@
|
|
|
8
8
|
|
|
9
9
|
Bun LCOV 行/函数统计不能证明所有分支真实执行;已知插桩局限见 [KNOWN-ISSUES](../KNOWN-ISSUES.md)。关键错误及并发路径通过行为断言和 Node 原生 HTTP 测试补强,不以覆盖率数字代替行为验证。
|
|
10
10
|
|
|
11
|
+
默认请求超时由内部常量断言和请求信号测试覆盖;显式短超时的原生 HTTP 用例覆盖实际 TIMEOUT 与发布结果未知路径,不等待默认的 30 秒。
|
|
12
|
+
|
|
11
13
|
## 2. 本地场景
|
|
12
14
|
|
|
13
15
|
| 文件 | 验证范围 |
|
|
14
16
|
| --- | --- |
|
|
15
17
|
| client.test.ts | 单表布局、原子提交、meta/data、版本、表隔离、队列及完整性 |
|
|
16
18
|
| jsonl.test.ts | UTF-8/Unicode、JSONL、空文件、边界容量 |
|
|
17
|
-
| transport.test.ts | endpoint
|
|
19
|
+
| transport.test.ts | endpoint、双层鉴权、默认/显式请求超时、配置、HTTP、Git 响应、取消及发布确定性 |
|
|
18
20
|
| review-regressions.test.ts / round-two.test.ts | 元信息数字保真、安全整数、SHA、结构化错误、分支发现与历史回归 |
|
|
19
21
|
| records.test.ts | CRUD、AND 等值、系统字段、主键、队列、跨 client 竞争及两层共享 |
|
|
20
22
|
| batch-records.test.ts | 同表批量原子发布、单次 revision/请求流程、顺序、错误位置、重复/缺失 ID、空操作、输入复制、512 层包装边界、容量/旧表缩小、队列与未知发布 |
|
package/lib/index.d.ts
CHANGED
|
@@ -8,7 +8,7 @@ interface ClientOptions {
|
|
|
8
8
|
apiVersion?: string;
|
|
9
9
|
headers?: RequestInit['headers'];
|
|
10
10
|
fetch?: (url: string, init: RequestInit) => Promise<Response>;
|
|
11
|
-
/** Per-request milliseconds,
|
|
11
|
+
/** Per-request milliseconds; default 30,000, range 1 to 2,147,483,647. */
|
|
12
12
|
timeout?: number;
|
|
13
13
|
}
|
|
14
14
|
interface ReadOptions {
|
package/lib/index.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import{createHash as
|
|
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
|
|
1
|
+
import{createHash as M,randomUUID as H}from"node:crypto";import{isDeepStrictEqual as Q}from"node:util";import{Buffer as _}from"node:buffer";class c extends Error{constructor(t,e,n={}){super(e),this.code=t,this.details=n}code;details;name="GitHubDBError"}function T(a){return a!==null&&typeof a=="object"&&!Array.isArray(a)}function B(a){if(!T(a))throw new c("INVALID_INPUT","Options must be an object.")}function E(a){if(a!==void 0&&!(a instanceof AbortSignal))throw new c("INVALID_INPUT","signal must be an AbortSignal.")}function Z(a){if(typeof a!="string"||!a.isWellFormed())throw new c("INVALID_INPUT","Content must be a well-formed Unicode string.")}function $(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 D(a){if(!$(a))throw new c("INVALID_INPUT","Names must be nonempty, unambiguous path segments.");return a}function m(a){B(a);const t=a.signal;return E(t),t}const tt=1e7;function et(a){let t=!1,e=!1;for(let n=0;n<a.length;n++){const r=a[n];if(!t){r==='"'&&(t=!0);continue}if(r==="\\"){if(a[++n]==="u"){const s=Number.parseInt(a.slice(n+1,n+5),16);if(n+=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(r==='"'){if(e)return!0;t=!1}else if(e)return!0}return!1}function L(a,t=!0){Z(a);const e=_.byteLength(a,"utf8");if(t&&e>tt)throw new c("TABLE_TOO_LARGE","Table exceeds 10,000,000 UTF-8 bytes.");if(a==="")return{recordCount:0,byteLength:0};const n=a.split(`
|
|
2
|
+
`);n.at(-1)===""&&n.pop();for(const[r,s]of n.entries()){let i;try{i=JSON.parse(s)}catch{throw new c("INVALID_JSONL","Every record line must be valid JSON.",{lineNumber:r+1})}if(et(s))throw new c("INVALID_JSONL","JSONL contains invalid Unicode.",{lineNumber:r+1,reason:"INVALID_UNICODE"});if(!T(i))throw new c("INVALID_JSONL","Every record must be a JSON object.",{lineNumber:r+1})}return{recordCount:n.length,byteLength:e}}function O(a){if(!T(a))throw new c("INVALID_RESPONSE","Expected a GitHub response object.");return a}function w(a){if(typeof a!="string"||!/^[a-f0-9]{40}$/.test(a))throw new c("INVALID_RESPONSE","Expected a 40-character lowercase Git SHA.");return a}function P(a){if(typeof a!="string"||!a||!a.isWellFormed())throw new c("INVALID_RESPONSE","Expected a nonempty well-formed GitHub response field.");return a}function rt(a){if(typeof a!="string"||!a.trim()||!a.isWellFormed()||/[\p{Cc}\p{Cf}]/u.test(a))throw new c("INVALID_RESPONSE","Expected a valid well-formed GitHub branch name.");return a}const nt=3e4;function at(a,t){try{if(a===null||typeof a!="object")return;const e=a,n=e.status,r=e.ok,s=e.headers,i=e.json,o=e.arrayBuffer;if(typeof n!="number"||!Number.isInteger(n)||n<100||n>599||typeof r!="boolean"||r!==(n>=200&&n<300)||s===null||typeof s!="object")return;const d=s.get;if(typeof d!="function"||typeof i!="function"||typeof o!="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:r,json:i.bind(a),arrayBuffer:o.bind(a),details:{dispatched:t,status:n,requestId:u??void 0,retryAfter:h??void 0}}}catch{return}}function v(a,t,e){const n=Promise.resolve(a);return t?new Promise((r,s)=>{let i=!1;const o=()=>t.removeEventListener("abort",d),d=()=>{i||(i=!0,o(),s(e()))};t.addEventListener("abort",d,{once:!0}),n.then(u=>{i||(i=!0,o(),r(u))},u=>{i||(i=!0,o(),s(u))}),t.aborted&&d()}):n}function ot(a){const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(a);if(!t)return!1;const e=Number(t[1]),n=Number(t[2]),r=Number(t[3]);if(n<1||n>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 r>=1&&r<=s[n-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 c("INVALID_INPUT","token, owner and repo are required.");if(D(t.owner),D(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 c("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 c("INVALID_INPUT","endpoint must be an absolute HTTP(S) URL.")}const n=["localhost","127.0.0.1","[::1]"].includes(e.hostname);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&n))throw new c("INVALID_INPUT","endpoint must use HTTPS; plain HTTP is allowed only for localhost.");if(e.search||e.hash||e.username||e.password)throw new c("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 c("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 c("INVALID_INPUT","apiVersion must have YYYY-MM-DD format.");if(t.fetch!==void 0&&typeof t.fetch!="function")throw new c("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 c("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 c("INVALID_INPUT",`Custom headers cannot override ${r}.`);try{this.headers.set("Authorization",`Bearer ${t.token}`)}catch{throw new c("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??nt}async request(t,e,n,r,s){E(s);let i=!1;const o=new Headers(this.headers);o.set("Accept",r?"application/vnd.github.raw+json":"application/vnd.github+json"),n!==void 0&&o.set("Content-Type","application/json");const d=AbortSignal.timeout(this.timeout),u=s?AbortSignal.any([s,d]):d,h=e==="POST"&&t==="/git/commits",l=u,p=()=>h&&s?.aborted===!0,f=()=>new c(s?.aborted?"ABORTED":"TIMEOUT",s?.aborted?"Request was cancelled.":"Request timed out.",{dispatched:i});if(u?.aborted)throw f();let b;try{i=!0;const N=this.fetcher(`${this.endpoint}${this.prefix}${t}`,{method:e,headers:o,body:n===void 0?void 0:JSON.stringify(n),redirect:"manual",signal:u});b=await v(N,l,f)}catch{throw u?.aborted?f():new c("NETWORK_ERROR","GitHub request failed.",{dispatched:i})}if(u?.aborted&&!p())throw f();const g=at(b,i);if(!g)throw new c("INVALID_RESPONSE","fetch must return a valid Response.",{dispatched:i});const{details:y}=g;if(!g.ok)throw new c("HTTP_ERROR",`GitHub request returned HTTP ${y.status}.`,{...y,...y.status>=300&&y.status<400?{reason:"REDIRECT"}:{}});try{if(!r){const X=await v(g.json(),l,f);if(u?.aborted&&!p())throw f();return X}const N=await v(g.arrayBuffer(),l,f);let C;try{C=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(N)}catch{throw new c("INVALID_UTF8","File content is not valid UTF-8.",y)}if(u?.aborted)throw f();return C}catch(N){throw u?.aborted?f():N instanceof c?N:new c("INVALID_RESPONSE","Could not read the GitHub response.",y)}}async json(t,e="GET",n,r){return O(await this.request(t,e,n,!1,r))}scope(t){return JSON.stringify([this.endpoint,this.prefix,t])}}function it(a){const t=P(a);if(t.includes("/"))throw new c("INVALID_RESPONSE","GitHub returned an invalid tree entry path.");return t}class ct{constructor(t){this.transport=t}transport;tree(t,e,n){let r=t.trees.get(e);return r||(r=this.transport.json(`/git/trees/${e}`,"GET",void 0,n).then(s=>{if(s.truncated!==!1||!Array.isArray(s.tree))throw new c("INVALID_RESPONSE","GitHub returned an incomplete tree.");return s.tree.map(i=>{const o=O(i);return{path:it(o.path),sha:w(o.sha),type:P(o.type),mode:P(o.mode)}})}),t.trees.set(e,r)),r}async resolve(t,e,n){const r=e.split("/");let s=t.treeSha;for(let i=0;i<r.length;i++){const o=(await this.tree(t,s,n)).find(d=>d.path===r[i]);if(!o)return;if(i===r.length-1)return o;if(o.type!=="tree")throw new c("INVALID_METADATA","A parent path is not a directory.",{path:r.slice(0,i+1).join("/"),reason:"PATH_NOT_DIRECTORY"});s=o.sha}}async find(t,e,n){const r=await this.resolve(t,e,n);if(r&&(r.type!=="blob"||!["100644","100755"].includes(r.mode)))throw new c("INVALID_METADATA","Path must reference a regular file.",{path:e,reason:"NOT_REGULAR_FILE"});return r}async directory(t,e,n){const r=await this.resolve(t,e,n);if(r){if(r.type!=="tree")throw new c("INVALID_METADATA","Path must reference a directory.",{path:e,reason:"PATH_NOT_DIRECTORY"});return this.tree(t,r.sha,n)}}}function R(a){const t=_.from(a,"utf8");return M("sha1").update(`blob ${t.byteLength}\0`).update(t).digest("hex")}class ht{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 ct(this.transport),this.branchName=t.branch}async branch(t){if(t?.aborted)throw new c("ABORTED","Request was cancelled.",{dispatched:!1});if(this.branchName!==void 0)return this.branchName;if(this.branchLookup??=this.transport.json("").then(n=>(this.branchName=rt(n.default_branch),this.branchName)).finally(()=>{this.branchLookup=void 0}),!t)return this.branchLookup;const e=this.branchLookup;if(t.aborted)throw e.catch(()=>{}),new c("ABORTED","Request was cancelled.",{dispatched:!0});return new Promise((n,r)=>{const s=()=>r(new c("ABORTED","Request was cancelled.",{dispatched:!0}));t.addEventListener("abort",s,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",s))})}async snapshot(t){E(t);const e=await this.branch(t),n=await this.transport.json(`/git/ref/heads/${encodeURIComponent(e)}`,"GET",void 0,t),r=w(O(n.object).sha),s=await this.transport.json(`/git/commits/${r}`,"GET",void 0,t);return{commitSha:r,treeSha:w(O(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 n=await this.transport.json("/git/blobs","POST",{content:_.from(t,"utf8").toString("base64"),encoding:"base64"},e),r=w(n.sha);if(r!==R(t))throw new c("INVALID_RESPONSE","GitHub returned a blob SHA that does not match content.");return r}async commit(t,e,n,r){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,r)}))),i=await this.transport.json("/git/trees","POST",{base_tree:t.treeSha,tree:s},r),o=await this.transport.json("/git/commits","POST",{tree:w(i.sha),parents:[t.commitSha],message:n},r),d=w(o.sha),u=await this.branch();if(r?.aborted)throw new c("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},r);if(w(O(h.object).sha)!==d)throw new c("INVALID_RESPONSE","Unexpected published commit.")}catch(h){if(h instanceof c){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 c("CONFLICT","GitHub rejected publication; inspect the cause before retrying.",{...h.details,reason:"PUBLISH_REJECTED"}):h}throw new c("WRITE_RESULT_UNKNOWN","Publication may have succeeded; verify before retrying.",{dispatched:!0,...h instanceof c?h.details:{},commitSha:d})}return{commitSha:d}}}const dt=512;function J(a,t,e){if(a>dt)throw new c(t,"JSON nesting exceeds 512 object/array containers.",{...e,reason:"TOO_DEEP"})}function F(a,t,e){let n=0,r=!1;for(let s=0;s<a.length;s++){const i=a[s];r&&i==="\\"?s++:i==='"'?r=!r:r||(i==="{"||i==="["?J(++n,t,e):(i==="}"||i==="]")&&n--)}}function G(a){const t=/^(-?)(\d+)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/.exec(a),e=t[3]??"",n=(t[2]+e).replace(/^0+/,""),r=n.replace(/0+$/,"");return{sign:n?t[1]:"",digits:r,exponent:n?BigInt(t[4]??0)-BigInt(e.length)+BigInt(n.length-r.length):0n}}const S=JSON;function ut(a){const{digits:t,exponent:e}=G(a);return!t||e>=0n}function V(a,t,e){const n=a[t],r=S.isRawJSON(n)?Number(n.rawJSON):n;if(typeof r!="number"||!Number.isSafeInteger(r)||r<0||Object.is(r,-0)||S.isRawJSON(n)&&!ut(n.rawJSON))throw new c("INVALID_METADATA","Metadata field must be a nonnegative safe integer.",{...e,reason:"INVALID_FIELD",field:t});return a[t]=r,r}function lt(a,t){F(a,"INVALID_METADATA",t);let e;try{e=S.parse(a,(n,r,s)=>typeof r=="number"&&JSON.stringify(r)!==s.source?S.rawJSON(s.source):r)}catch{throw new c("INVALID_METADATA","meta.json must contain valid JSON.",{...t,reason:"INVALID_JSON"})}if(!T(e))throw new c("INVALID_METADATA","meta.json must contain an object.",{...t,reason:"INVALID_FIELD"});if(V(e,"version",t)!==1)throw new c("INVALID_METADATA","Unsupported metadata format version.",{...t,reason:"UNSUPPORTED_VERSION",field:"version"});for(const n of["createdAt","updatedAt","recordCount","byteLength"])V(e,n,t);if(V(e,"revision",t)===0||typeof e.dataSha!="string"||!/^[a-f0-9]{40}$/.test(e.dataSha))throw new c("INVALID_METADATA","Table revision or dataSha is invalid.",{...t,reason:"INVALID_FIELD",field:"revision/dataSha"});return e}function ft(a){return JSON.stringify(a,null,2)+`
|
|
3
|
+
`}class q{constructor(t,e,n){this.repository=t,this.name=n,D(e),D(n),this.root=`${e}/${n}`,this.metaPath=`${this.root}/meta.json`,this.dataPath=`${this.root}/data.jsonl`}repository;name;root;metaPath;dataPath;context(t=this.metaPath){return{path:t,table:this.name}}async metadata(t,e){const n=await this.repository.files.find(t,this.metaPath,e);if(!n){if((await this.repository.files.directory(t,this.root,e))?.length)throw new c("INVALID_METADATA","Existing table is missing meta.json.",{...this.context(),reason:"MISSING_METADATA"});return}const r=await this.repository.content(n,e);if(R(r)!==n.sha)throw new c("INVALID_METADATA","meta.json SHA does not match its content.",{...this.context(),reason:"META_SHA_MISMATCH"});return{meta:lt(r,this.context()),entry:n}}async state(t,e){const[n,r]=await Promise.all([this.metadata(t,e),this.repository.files.find(t,this.dataPath,e)]);if(!n)return{metadata:n,data:r};if(!r)throw new c("INVALID_METADATA","Table is missing data.jsonl.",{...this.context(),path:this.dataPath,reason:"MISSING_DATA"});return{metadata:n,data:r}}async validatedContent(t,e){if(!t.metadata)return"";const{meta:n}=t.metadata;if(n.dataSha!==t.data.sha)throw new c("INVALID_METADATA","dataSha does not match data.jsonl.",{...this.context(),path:this.dataPath,reason:"DATA_SHA_MISMATCH"});const r=await this.repository.content(t.data,e);if(R(r)!==t.data.sha)throw new c("INVALID_METADATA","dataSha does not match data.jsonl.",{...this.context(),path:this.dataPath,reason:"DATA_SHA_MISMATCH"});const s=L(r,!1);if(s.recordCount!==n.recordCount||s.byteLength!==n.byteLength)throw new c("INVALID_METADATA","Statistics do not match data.jsonl.",{...this.context(),path:this.dataPath,reason:"STATISTICS_MISMATCH"});return r}async write(t,e,n,r,s,i){const o=Date.now(),d=(e.metadata?.meta.revision??0)+1;if(!Number.isSafeInteger(d))throw new c("INVALID_METADATA","Table revision cannot be incremented safely.",{...this.context(),reason:"REVISION_OVERFLOW",field:"revision"});const u=await this.repository.createBlob(n,i),h={...e.metadata?.meta,version:1,createdAt:e.metadata?.meta.createdAt??o,updatedAt:o,...r,revision:d,dataSha:u},l=await this.repository.commit(t,[{path:this.dataPath,sha:u,mode:e.data?.mode},{path:this.metaPath,content:ft(h),mode:e.metadata?.entry.mode}],`github-db: ${s} ${JSON.stringify(this.root)}
|
|
4
4
|
|
|
5
5
|
client: @secret-momo/github-db
|
|
6
|
-
endpoint: ${this.repository.endpoint}`,
|
|
7
|
-
`);e.at(-1)===""&&e.pop();const
|
|
6
|
+
endpoint: ${this.repository.endpoint}`,i);return{meta:h,commitSha:l.commitSha}}}function I(a,t="INVALID_INPUT",e={},n=1){const r=()=>{throw new c(t,"Expected a plain JSON object with only serializable values.",{...e,reason:"NOT_JSON"})},s=new Set,i=(o,d,u)=>{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")return r();J(d,t,{...e,field:u});const h=Array.isArray(o),l=Object.getPrototypeOf(o);((h?l!==Array.prototype:l!==Object.prototype&&l!==null)||s.has(o))&&r(),s.add(o);const p=Reflect.ownKeys(o);h&&p.length!==o.length+1&&r();for(const f of p){if(h&&f==="length")continue;if(typeof f!="string"||!f.isWellFormed())return r();h&&(!/^(0|[1-9]\d*)$/.test(f)||Number(f)>=o.length)&&r();const b=Object.getOwnPropertyDescriptor(o,f);(!b.enumerable||!("value"in b))&&r(),i(b.value,d+1,`${u}.${f}`)}s.delete(o)};try{return T(a)?(i(a,n,"$"),JSON.parse(JSON.stringify(a))):r()}catch(o){if(o instanceof c)throw o;return r()}}function U(a,t){const e=n=>{throw new c("INVALID_INPUT","Expected a plain dense array of batch inputs.",{reason:"NOT_JSON",...n===void 0?{}:{itemIndex:n}})};try{if(!Array.isArray(a)||Object.getPrototypeOf(a)!==Array.prototype||Reflect.ownKeys(a).length!==a.length+1)return e();const n=[];for(let r=0;r<a.length;r++){const s=Object.getOwnPropertyDescriptor(a,String(r));(!s?.enumerable||!("value"in s))&&e(r),n.push(t(s.value,r))}return n}catch(n){if(n instanceof c)throw n;return e()}}function A(a,t="INVALID_INPUT",e={}){if(typeof a!="string"||!a.trim()||!a.isWellFormed())throw new c(t,"id must be a nonempty, well-formed string.",{...e,reason:"INVALID_ID",field:"id"})}function k(a){const{sign:t,digits:e,exponent:n}=G(a);return e?`${t}${e}e${n}`:"0"}const pt=JSON.parse;function W(a,t){if(!a)return[];const e=a.split(`
|
|
7
|
+
`);e.at(-1)===""&&e.pop();const n=new Set;return e.map((r,s)=>{const i={...t,lineNumber:s+1};F(r,"INVALID_RECORD",i);const o=pt(r,(u,h,l)=>{if(typeof h=="number"&&(!Number.isFinite(h)||k(l.source)!==k(JSON.stringify(h))))throw new c("INVALID_RECORD","Record number cannot round-trip without losing precision.",{...t,lineNumber:s+1,reason:"NUMERIC_PRECISION"});return h}),d=I(o,"INVALID_RECORD",i);A(d.id,"INVALID_RECORD",i);for(const u of["createdAt","updatedAt"]){const h=o[u];if(typeof h!="number"||!Number.isSafeInteger(h)||h<0||Object.is(h,-0))throw new c("INVALID_RECORD","Record timestamps must be nonnegative safe integers.",{...i,reason:"INVALID_TIMESTAMP",field:u})}if(n.has(d.id))throw new c("DUPLICATE_ID","Duplicate id in table data.",{...i,reason:"DUPLICATE_ID",field:"id"});return n.add(d.id),{record:d,source:r}})}function mt(a){return a.length?a.map(t=>t.source).join(`
|
|
8
8
|
`)+`
|
|
9
|
-
`:""}function j(a,t,e,
|
|
9
|
+
`:""}function j(a,t,e,n){if(A(a,"INVALID_INPUT",{itemIndex:e}),t.has(a))throw new c(n,"Batch inputs contain a duplicate id.",{reason:"DUPLICATE_ID",field:"id",itemIndex:e});return t.add(a),a}function x(a){const t=m(a);if(t?.aborted)throw new c("ABORTED","Request was cancelled.",{dispatched:!1});return t}class K{constructor(t,e,n){this.repository=t,this.dbName=e,this.name=n,this.storage=new q(t,e,n)}repository;dbName;name;storage;async findAll(t={},e={}){const n=m(e),r=I(t),s=await this.repository.snapshot(n),i=await this.storage.state(s,n);return W(await this.storage.validatedContent(i,n),this.storage.context(this.storage.dataPath)).filter(({record:o})=>Object.entries(r).every(([d,u])=>Object.hasOwn(o,d)&&Q(o[d],u))).map(({record:o})=>o)}async find(t={},e={}){return(await this.findAll(t,e))[0]??null}async findById(t,e={}){return A(t),this.find({id:t},e)}async insert(t,e={}){const n=I(t);if(Object.hasOwn(n,"createdAt")||Object.hasOwn(n,"updatedAt"))throw new c("INVALID_INPUT","Record timestamps are managed by the SDK.");const r=Object.hasOwn(n,"id")?n.id:H();return A(r),this.mutate("insert",s=>{if(s.some(({record:d})=>d.id===r))throw new c("DUPLICATE_ID","id already exists in this table.",{...this.storage.context(this.storage.dataPath),reason:"DUPLICATE_ID",field:"id"});const i=Date.now(),o={...n,id:r,createdAt:i,updatedAt:i};return s.push({record:o,source:JSON.stringify(o)}),{result:o,write:!0}},e)}async updateById(t,e,n={}){A(t);const r=I(e);if(!Object.keys(r).length||["id","createdAt","updatedAt"].some(s=>Object.hasOwn(r,s)))throw new c("INVALID_INPUT","Update requires business fields and cannot change system fields.");return this.mutate("update",s=>{const i=s.find(({record:d})=>d.id===t);if(!i)throw new c("NOT_FOUND","Record does not exist.",{...this.storage.context(this.storage.dataPath),reason:"RECORD_NOT_FOUND"});const o={...i.record,...r,updatedAt:Date.now()};return i.record=o,i.source=JSON.stringify(o),{result:o,write:!0}},n)}async insertMany(t,e={}){const n=x(e),r=new Set,s=U(t,(i,o)=>{const d=I(i,"INVALID_INPUT",{itemIndex:o});if(Object.hasOwn(d,"createdAt")||Object.hasOwn(d,"updatedAt"))throw new c("INVALID_INPUT","Record timestamps are managed by the SDK.",{itemIndex:o});const u=j(Object.hasOwn(d,"id")?d.id:H(),r,o,"DUPLICATE_ID");return{...d,id:u}});return s.length?this.mutate("insertMany",i=>{const o=new Set(i.map(({record:h})=>h.id));for(const[h,l]of s.entries())if(o.has(l.id))throw new c("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=s.map(h=>({...h,createdAt:d,updatedAt:d}));for(const h of u)i.push({record:h,source:JSON.stringify(h)});return{result:u,write:!0}},{signal:n}):[]}async updateManyById(t,e={}){const n=x(e),r=new Set,s=U(t,(i,o)=>{const d=I(i,"INVALID_INPUT",{itemIndex:o},0);if(Object.keys(d).length!==2||!Object.hasOwn(d,"id")||!Object.hasOwn(d,"patch"))throw new c("INVALID_INPUT","Update entries require only id and patch.",{itemIndex:o});const u=j(d.id,r,o,"INVALID_INPUT"),h=I(d.patch,"INVALID_INPUT",{itemIndex:o});if(!Object.keys(h).length||["id","createdAt","updatedAt"].some(l=>Object.hasOwn(h,l)))throw new c("INVALID_INPUT","Update requires business fields and cannot change system fields.",{itemIndex:o});return{id:u,patch:h}});return s.length?this.mutate("updateManyById",i=>{const o=new Map(i.map(u=>[u.record.id,u]));for(const[u,h]of s.entries())if(!o.has(h.id))throw new c("NOT_FOUND","Record does not exist.",{...this.storage.context(this.storage.dataPath),reason:"RECORD_NOT_FOUND",itemIndex:u});const d=Date.now();return{result:s.map(({id:u,patch:h})=>{const l=o.get(u),p={...l.record,...h,updatedAt:d};return l.record=p,l.source=JSON.stringify(p),p}),write:!0}},{signal:n}):[]}async deleteManyById(t,e={}){const n=x(e),r=new Set,s=U(t,(i,o)=>j(i,r,o,"INVALID_INPUT"));return s.length?this.mutate("deleteManyById",i=>{const o=new Set(i.map(({record:h})=>h.id)),d=s.map(h=>o.has(h));if(!d.some(Boolean))return{result:d,write:!1};let u=0;for(const h of i)r.has(h.record.id)||(i[u++]=h);return i.length=u,{result:d,write:!0}},{signal:n}):[]}async deleteById(t,e={}){return A(t),this.mutate("delete",n=>{const r=n.findIndex(({record:s})=>s.id===t);return r<0?{result:!1,write:!1}:(n.splice(r,1),{result:!0,write:!0})},e)}async mutate(t,e,n){const r=m(n);return this.repository.enqueue(async()=>{const s=await this.repository.snapshot(r),i=await this.storage.state(s,r),o=W(await this.storage.validatedContent(i,r),this.storage.context(this.storage.dataPath)),d=e(o);if(d.write){const u=mt(o);await this.storage.write(s,i,u,L(u),t,r)}return d.result})}}class Y{constructor(t,e,n){this.repository=t,this.dbName=e,this.name=n,this.storage=new q(t,e,n)}repository;dbName;name;storage;version(t,e){return M("sha256").update(JSON.stringify([this.repository.scope(),this.dbName,this.name,t.revision,e])).digest("hex")}async read(t={}){const e=m(t),n=await this.repository.snapshot(e),r=await this.storage.state(n,e);if(!r.metadata)throw new c("NOT_FOUND","Table does not exist.",{...this.storage.context(),path:this.storage.dataPath,reason:"TABLE_NOT_FOUND"});return{content:await this.storage.validatedContent(r,e),meta:r.metadata.meta,version:this.version(r.metadata.meta,r.data.sha),commitSha:n.commitSha}}async write(t,e={}){const n=m(e),r=e.expectedVersion;if(r!=null&&(typeof r!="string"||!/^[a-f0-9]{64}$/.test(r)))throw new c("INVALID_INPUT","expectedVersion must be an opaque table version or null.");const s=L(t);return this.repository.enqueue(async()=>{const i=await this.repository.snapshot(n),o=await this.storage.state(i,n),d=o.metadata?this.version(o.metadata.meta,o.data.sha):null;if(r!==void 0&&r!==d)throw new c("CONFLICT","Table version does not match expectedVersion.",{...this.storage.context(),path:this.storage.dataPath,reason:"VERSION_MISMATCH"});await this.storage.validatedContent(o,n);const u=await this.storage.write(i,o,t,s,"write",n);return{...u,version:this.version(u.meta,u.meta.dataSha)}})}async getMeta(t={}){const e=m(t),n=await this.repository.snapshot(e),r=await this.storage.metadata(n,e);if(!r)throw new c("NOT_FOUND","Table does not exist.",{...this.storage.context(),reason:"TABLE_NOT_FOUND"});return{meta:r.meta,commitSha:n.commitSha}}}class z{constructor(t,e){this.repository=t,this.name=e,D(e)}repository;name;async listTables(t={}){const e=m(t),n=await this.repository.snapshot(e),r=(await this.repository.files.directory(n,this.name,e)??[]).filter(o=>o.type==="tree"&&$(o.path)),s=new Array(r.length);let i=0;return await Promise.all(Array.from({length:Math.min(8,r.length)},async()=>{for(;i<r.length;){const o=i++,d=r[o],u=await this.repository.files.directory(n,`${this.name}/${d.path}`,e),h=new Set(u?.filter(l=>l.type==="blob"&&["100644","100755"].includes(l.mode)).map(l=>l.path));s[o]=h.has("meta.json")&&h.has("data.jsonl")?d.path:void 0}})),s.filter(o=>o!==void 0).sort()}getTable(t){return new Y(this.repository,this.name,t)}getRecordTable(t){return new K(this.repository,this.name,t)}}class wt{repository;constructor(t){this.repository=new ht(t)}getDB(t){return new z(this.repository,t)}}export{wt as GitHubDBClient,c as GitHubDBError,z as GitHubDatabase,K as GitHubRecordTable,Y as GitHubTable};
|