@vultro/runtime-bun 0.0.0-stage → 0.0.2

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
@@ -1,3 +1,197 @@
1
- # Temporary Holding Version
1
+ # @vultro/runtime-bun
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `@vultro/core` 的 **Bun 运行时适配层**:`Bun.serve` + `Bun.SQL`(SQLite 文件)。
4
+
5
+ ## 用法
6
+
7
+ 本包只提供 **handler**,`Bun.serve` 由应用自己启动:
8
+
9
+ ```ts
10
+ import { createBunHandler, createBunRuntime } from "@vultro/runtime-bun";
11
+ import index from "./index.html";
12
+
13
+ const runtime = await createBunRuntime({
14
+ schema,
15
+ modules: { messages },
16
+ // 数据目录:SQLite 与文件字节都放这里,备份一个目录就够
17
+ dataDir: ".vultro",
18
+ });
19
+
20
+ const handler = createBunHandler(runtime);
21
+
22
+ Bun.serve({
23
+ port: 3000,
24
+ // 只把首页注册成 HTML 路由,其余路径都落到 fetch
25
+ routes: { "/": index },
26
+ // 必须传 server:WebSocket 升级要用 server.upgrade()
27
+ fetch(req, server) {
28
+ return handler.fetch(req, server);
29
+ },
30
+ websocket: handler.websocket,
31
+ });
32
+ ```
33
+
34
+ ### 为什么只给 handler,不给 server
35
+
36
+ - **路由编排属于应用层**:前端怎么挂(HTML 导入 / 静态目录 / 完全不要页面)、
37
+ 要不要加自己的路由,不该被库锁死;
38
+ - `Bun.HTMLBundle` 只能作为 `routes` 的值使用,塞进 `new Response()` 只会得到
39
+ `"[object HTMLBundle]"`,所以 `Bun.serve` 必须在应用侧调用;
40
+ - handler 是纯对象(`{ fetch, websocket }`),可以展开进任意 `Bun.serve`
41
+ 配置,也能被测试直接调用。
42
+
43
+ ### 注意 `routes` 的优先级
44
+
45
+ `routes` 的优先级**高于** handler 的 `fetch`。所以只注册 `"/": index`:
46
+ 如果写成 `"/*": index`,`/health`、`/api/*` 会被 HTML 通配符吞掉,
47
+ 全部返回页面而不是 JSON。
48
+
49
+ ### 注意必须把 `server` 传给 handler
50
+
51
+ ```ts
52
+ fetch(req, server) { return handler.fetch(req, server); }
53
+ ```
54
+
55
+ WebSocket 升级依赖 `server.upgrade()`。写成 `fetch(req)` 会导致
56
+ `WS /api/<version>/sync` 直接 500,实时订阅完全不可用。
57
+
58
+ ## 两个运行时的对应关系
59
+
60
+ | 能力 | Cloudflare(`@vultro/runtime-cf`) | Bun(本包) |
61
+ | ---------- | ---------------------------------- | ----------------------- |
62
+ | HTTP | Worker `fetch` | `Bun.serve` |
63
+ | 存储 | DO SQLite / D1 | `Bun.SQL` + SQLite 文件 |
64
+ | 事务串行化 | 单 DO 实例 | 进程内 Mutex(单进程) |
65
+ | WebSocket | `WebSocketPair` | `server.upgrade` |
66
+ | 定时任务 | DO `alarm` | `setTimeout` |
67
+ | 同步协议 | core 的 `SyncEngine` | 同一个 `SyncEngine` |
68
+
69
+ ## 关键设计:复用 D1 异步存储路径
70
+
71
+ `Bun.SQL` 是异步 API,而 core 的同步 `DocumentStore` 需要同步 `exec()`。
72
+ 本包没有重写一套存储,而是复用 core 已有的 `D1CachedDocumentStore`:
73
+ 它用内存 Map 做读写缓存、把提交异步落到 SQL,接口与同步 store 完全一致。
74
+ `sql.ts` 只负责把 `Bun.SQL` 的返回形状(带 `count` / `command` 属性的数组)
75
+ 转换成 D1 的 `{ results }` 形状。
76
+
77
+ 好处是事务、索引、查询构建器、schema 校验全部与 Cloudflare 版走同一份代码。
78
+
79
+ ## 实时订阅
80
+
81
+ `createBunRuntime` 会通过 `runtime.setCommitListener()` 把每次提交转给
82
+ `SyncEngine`。这是实时订阅的关键:Cloudflare 版由 `VultroDO` 的 `onCommit`
83
+ 通知 `SyncDO`,Bun 版没有独立 DO,必须在同一进程内完成这次转发。
84
+
85
+ ## 文件存储(ctx.storage)
86
+
87
+ 文件分两层存:**元数据**(id / size / sha256 / contentType)在 SQLite,
88
+ **字节**交给 `BlobStore` 适配器。元数据必须同步可读(`getMetadata` /
89
+ `list` 都是同步方法),字节体积大,适合放对象存储或磁盘。
90
+
91
+ ### 默认:本地磁盘
92
+
93
+ 只传 `dataDir` 就够了:不传 `blobs` 时默认写本地磁盘,字节落在数据目录下的
94
+ `blobs/`:
95
+
96
+ ```text
97
+ .vultro/
98
+ data.sqlite
99
+ blobs/
100
+ objects/<storageId> # 字节
101
+ objects/<storageId>.meta.json # contentType / size
102
+ ```
103
+
104
+ 备份数据目录即可同时备份文档和文件,不需要运维记两个路径。
105
+
106
+ ### 选择后端
107
+
108
+ ```ts
109
+ import { createLocalBlobStore } from "@vultro/storage-local";
110
+ import { createS3BlobStore } from "@vultro/storage-s3";
111
+
112
+ // 1. 不传 blobs:默认本地磁盘(内部调用 createLocalBlobStore)
113
+ await createBunRuntime({ modules, dataDir: ".vultro" });
114
+
115
+ // 2. 只存 SQLite 的 base64 副本(文件很小、想少一个目录)
116
+ await createBunRuntime({ modules, dataDir, blobs: "none" });
117
+
118
+ // 3. 本地磁盘换目录
119
+ await createBunRuntime({
120
+ modules,
121
+ dataDir,
122
+ blobs: createLocalBlobStore({ root: "/data/blobs" }),
123
+ });
124
+
125
+ // 4. S3(AWS 或 MinIO 等兼容实现)
126
+ await createBunRuntime({
127
+ modules,
128
+ dataDir,
129
+ blobs: createS3BlobStore({
130
+ bucket: "my-bucket",
131
+ region: "us-east-1",
132
+ accessKeyId: process.env.S3_ACCESS_KEY_ID!,
133
+ secretAccessKey: process.env.S3_SECRET_ACCESS_KEY!,
134
+ // MinIO / 私有部署需要显式 endpoint
135
+ endpoint: process.env.S3_ENDPOINT,
136
+ prefix: "my-app", // 同一 bucket 放多个 deployment
137
+ }),
138
+ });
139
+ ```
140
+
141
+ `blobs` 只接受 `"none"` 或一个已经构造好的 `BlobStore`;不传就用默认的
142
+ 本地磁盘后端。这样 runtime 不需要知道各种后端的配置形状,新增后端只要
143
+ 实现 `BlobStore` 接口即可。
144
+
145
+ ### 对象 key
146
+
147
+ 逻辑 key 是 `<namespace>/objects/<storageId>`,**不含前缀**——前缀由各
148
+ 适配器自己的 `prefix` / `root` 配置决定。这样同一份元数据可以在不同后端
149
+ 之间迁移,只要前缀配置对齐即可。
150
+
151
+ ### S3 走 Bun 原生实现
152
+
153
+ `createS3BlobStore` 直接用 Bun 内置的 `Bun.S3Client`,**不引 AWS SDK**:
154
+
155
+ - 签名(SigV4)、重试、分片、并发都由 Bun 原生实现负责;
156
+ - 支持 AWS S3,以及 MinIO / R2 的 S3 网关等兼容服务;
157
+ - 兼容对象存储的 `x-amz-content-sha256: UNSIGNED-PAYLOAD` 也是合法的。
158
+
159
+ 适配器本身只做两件事:给逻辑 key 加 `prefix`,把 `S3File` 适配成
160
+ `{ bytes, contentType }`。
161
+
162
+ > 注意:`S3File.type` 是惰性属性,永远返回空字符串(不会发请求),所以
163
+ > MIME 类型必须从 `stat()` 的响应头里读——适配器已经这样处理。
164
+
165
+ ### 切换后端的注意事项
166
+
167
+ 元数据留在 SQLite,所以切换后端不影响已登记的文件列表。但**旧文件不会
168
+ 自动迁移**:换后端后旧文件的字节读不到,会回退到 SQLite 副本;如果之前
169
+ 没开双写,下载会返回 404。
170
+
171
+ ## 系统接口与「本机」信任
172
+
173
+ `_system/frontend/*`、`/api/json_schemas`、`/api/shapes2`、`/api/app_metrics/*`
174
+ 这些系统接口只允许两类请求:
175
+
176
+ 1. 携带正确 `adminToken`(`Authorization: Convex <token>`);
177
+ 2. 来自**本机**的连接(默认开启,方便本地开发)。
178
+
179
+ 「是否本机」由 `server.requestIP()` 的真实 socket 地址判定,**不是** Host 头
180
+ (`Host` 客户端可伪造,用它会直接绕过鉴权)。
181
+
182
+ ### 部署在反向代理后面时
183
+
184
+ 同机 nginx / Caddy 转发后,socket 地址一律是 `127.0.0.1`,公网请求会被
185
+ 误判成本机。为此只要请求带转发头(`x-forwarded-for` / `x-real-ip` /
186
+ `forwarded`),就**不再**认本机——真实来源只有代理知道,而这些头客户端
187
+ 也能伪造,与其猜不如不信任。
188
+
189
+ 这类部署请二选一:
190
+
191
+ ```ts
192
+ // 1. 配 adminToken,系统接口只认 token
193
+ await createBunRuntime({ ..., adminToken: process.env.VULTRO_ADMIN_TOKEN });
194
+
195
+ // 2. 彻底关闭本机免 token
196
+ await createBunRuntime({ ..., trustLocalhost: false });
197
+ ```
@@ -0,0 +1,7 @@
1
+ /**
2
+ * 兼容入口:本地磁盘 BlobStore 已移到 `@vultro/storage-local`。
3
+ *
4
+ * 保留 `@vultro/runtime-bun/blob-store` 这个子路径,避免已有应用改 import;
5
+ * 新代码建议直接从 `@vultro/storage-local` 引入。
6
+ */
7
+ export { createLocalBlobStore, localBlobPath, type LocalBlobStoreOptions, } from "@vultro/storage-local";
@@ -0,0 +1 @@
1
+ export { createLocalBlobStore, localBlobPath } from "@vultro/storage-local";
@@ -0,0 +1,23 @@
1
+ import type { ComponentDefinitionInput } from "@vultro/core";
2
+ /**
3
+ * 从 codegen 生成的 `components.manifest.json`(`node_modules/.vultro/`)加载组件注册对象。
4
+ *
5
+ * 参考 `@concavejs/cli`:_generated 里只保存组件清单,运行时按清单动态
6
+ * import 组件模块并组装成 `createRuntime({ components })` 需要的结构。
7
+ * 这个函数用于不经过 Vite 插件的 Bun 入口(例如 apps/custom)。
8
+ */
9
+ export interface ComponentManifestEntry {
10
+ componentPath: string;
11
+ parentPath: string;
12
+ name: string;
13
+ schemaPath?: string;
14
+ schemaExportName?: "default" | "schema";
15
+ modules: Array<{
16
+ name: string;
17
+ filePath: string;
18
+ }>;
19
+ }
20
+ /** 组件 manifest 位置:convex 项目根目录的 `node_modules/.vultro/`。 */
21
+ export declare function componentsManifestPath(convexDir: string): string;
22
+ /** 加载 manifest 并返回 `createRuntime({ components })` 可直接使用的对象。 */
23
+ export declare function loadComponentsFromManifest(convexDir: string): Promise<Record<string, ComponentDefinitionInput>>;
@@ -0,0 +1,40 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { join, resolve } from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+ // src/components.ts
5
+ /** 组件 manifest 位置:convex 项目根目录的 `node_modules/.vultro/`。 */
6
+ function componentsManifestPath(convexDir) {
7
+ return join(resolve(convexDir, ".."), "node_modules", ".vultro", "components.manifest.json");
8
+ }
9
+ /** 加载 manifest 并返回 `createRuntime({ components })` 可直接使用的对象。 */
10
+ async function loadComponentsFromManifest(convexDir) {
11
+ const manifestPath = componentsManifestPath(convexDir);
12
+ if (!existsSync(manifestPath)) throw new Error(`组件 manifest 不存在:${manifestPath}。请先运行 \`vultro codegen\`(或 \`bun run codegen\`)生成。`);
13
+ const manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
14
+ const baseDir = join(convexDir, "_generated");
15
+ const nodes = /* @__PURE__ */ new Map();
16
+ const importModule = async (filePath) => {
17
+ return await import(pathToFileURL(resolve(baseDir, filePath)).href);
18
+ };
19
+ for (const entry of manifest.entries) {
20
+ const node = {
21
+ schema: void 0,
22
+ modules: {},
23
+ components: {}
24
+ };
25
+ if (entry.schemaPath) node.schema = (await importModule(entry.schemaPath))[entry.schemaExportName ?? "default"];
26
+ const modules = node.modules;
27
+ for (const module of entry.modules) modules[module.name] = await importModule(module.filePath);
28
+ nodes.set(entry.componentPath, node);
29
+ }
30
+ const roots = {};
31
+ for (const entry of manifest.entries) {
32
+ const node = nodes.get(entry.componentPath);
33
+ if (entry.parentPath) {
34
+ const parent = nodes.get(entry.parentPath);
35
+ if (parent) parent.components[entry.name] = node;
36
+ } else roots[entry.name] = node;
37
+ }
38
+ return roots;
39
+ }
40
+ export { componentsManifestPath, loadComponentsFromManifest };
@@ -0,0 +1,120 @@
1
+ /**
2
+ * ============================================================================
3
+ * Bun handler
4
+ * ============================================================================
5
+ *
6
+ * 生成一个可直接交给 `Bun.serve()` 的 handler 对象:
7
+ *
8
+ * ```ts
9
+ * const handler = createBunHandler(runtime);
10
+ * Bun.serve({ port: 3000, routes: { "/*": index }, ...handler });
11
+ * ```
12
+ *
13
+ * 为什么返回 handler 而不是自己调用 `Bun.serve`:
14
+ *
15
+ * - **路由编排属于应用层**。应用要决定前端页面怎么挂(HTML 导入、静态目录、
16
+ * 还是完全不要页面)、要不要加自己的路由,这些不该被库锁死;
17
+ * - handler 是纯对象(`{ fetch, websocket }`),可以直接展开到任意
18
+ * `Bun.serve` 配置里,也可以被测试单独调用;
19
+ * - 前端页面由应用以 `routes: { "/*": htmlBundle }` 挂载——`Bun.HTMLBundle`
20
+ * 只能作为 route 值使用,塞进 `new Response()` 只会得到
21
+ * `"[object HTMLBundle]"`,所以这一步必须由调用方在 `Bun.serve` 里完成。
22
+ *
23
+ * 关于路由优先级(已实测):`routes` 里更具体的模式优先于通配符,所以
24
+ * 应用如果同时注册 `/api/*` 和 `/*`,API 不会被 SPA 回退吞掉。
25
+ *
26
+ * 关于 WebSocket 生命周期:Bun 的 `server.upgrade()` 只负责握手,真正的
27
+ * `ServerWebSocket` 要等 `websocket.open(ws)` 才拿到。所以 `attach` 必须在
28
+ * `open` 里做——`fetch` 阶段只有 `request`,没有可发送的连接对象。
29
+ */
30
+ import type { BunRuntime } from "./runtime.js";
31
+ import { attachBunSocket } from "./runtime.js";
32
+ /**
33
+ * WebSocket 连接上挂的会话数据。
34
+ *
35
+ * `Bun.serve` 的 `server.upgrade(request, { data })` 会把它带到
36
+ * `websocket.open(ws)` 的 `ws.data` 上。
37
+ */
38
+ export interface BunSocketData {
39
+ /**
40
+ * 这次连接是否来自本机(受信)。
41
+ *
42
+ * 用 `server.requestIP()` 的真实远端地址判定,**不是** hostname——
43
+ * hostname 来自 Host 头,客户端可以伪造。
44
+ */
45
+ local: boolean;
46
+ /** `open` 之后由 `SyncEngine` 创建的连接状态。 */
47
+ connection?: ReturnType<typeof attachBunSocket>;
48
+ }
49
+ /**
50
+ * `Bun.serve` 传给 fetch / route handler 的 server 句柄中我们用到的那部分。
51
+ *
52
+ * 只声明 `upgrade`:WebSocket 握手需要它,其余能力本封装不依赖,
53
+ * 保持最小接口可以避免绑定 Bun 的具体版本类型。
54
+ */
55
+ interface BunServerHandle {
56
+ upgrade(request: Request, options?: {
57
+ data: BunSocketData;
58
+ }): boolean;
59
+ /** 真实远端地址;用于判断连接是否来自本机。 */
60
+ requestIP?(request: Request): {
61
+ address: string;
62
+ } | null;
63
+ }
64
+ /**
65
+ * 可直接展开进 `Bun.serve({ ...handler })` 的 handler。
66
+ *
67
+ * 用 `Bun.ServerWebSocket` 而不是自定义结构:`Bun.serve` 对 `websocket`
68
+ * 字段做严格类型匹配,自定义的「最小结构」会因缺少 `data` 之外的方法
69
+ * 而无法赋值。
70
+ */
71
+ export interface BunHandler {
72
+ fetch(request: Request, server: BunServerHandle): Promise<Response | undefined>;
73
+ websocket: {
74
+ open(ws: Bun.ServerWebSocket<BunSocketData>): void;
75
+ message(ws: Bun.ServerWebSocket<BunSocketData>, message: string | Buffer): void;
76
+ close(ws: Bun.ServerWebSocket<BunSocketData>): void;
77
+ };
78
+ }
79
+ /** `createBunHandler` 的选项。 */
80
+ export interface BunHandlerOptions {
81
+ /**
82
+ * 覆盖 runtime 的路由前缀。
83
+ *
84
+ * **通常不需要传**:`createBunRuntime({ prefix })` 已经处理好了
85
+ * handler 剥离前缀和 `deploymentUrl` 拼接。这里只用于测试或特殊场景。
86
+ */
87
+ prefix?: string;
88
+ /**
89
+ * 传输方式;默认 `"tcp"`。
90
+ *
91
+ * `Bun.serve({ unix })` 的 `server.requestIP()` 会返回 `null`,此时无法用
92
+ * socket 地址判断来源。Unix socket 只能被本机进程访问(例如 Vite dev
93
+ * proxy),所以显式传 `"unix"` 时把「拿不到 peer 地址」视为本机连接。
94
+ */
95
+ transport?: "tcp" | "unix";
96
+ }
97
+ /**
98
+ * 创建一个 Bun handler。
99
+ *
100
+ * 处理三类请求:
101
+ * 1. `WS /api/<version>/sync`:升级为 WebSocket,交给 `SyncEngine`;
102
+ * 2. `/api/*`、`/_storage/*`、`/health` 等:交给 Convex HTTP API;
103
+ * 3. 其余:返回 404(页面由调用方的 `routes` 处理)。
104
+ */
105
+ export declare function createBunHandler(runtime: BunRuntime, options?: BunHandlerOptions): BunHandler;
106
+ /**
107
+ * 判断连接是否来自本机。
108
+ *
109
+ * 用 `server.requestIP()` 拿真实远端地址,**不能**用 hostname:hostname
110
+ * 来自请求的 Host 头,客户端伪造 `Host: localhost` 就能绕过鉴权。
111
+ *
112
+ * **反向代理**:同机 nginx / Caddy 转发后 socket 地址一律是 `127.0.0.1`,
113
+ * 公网请求会被误判为本机。所以只要请求带转发头,就**不**认本机——
114
+ * 真实来源只有代理知道,而 `X-Forwarded-For` 本身又可被客户端伪造,
115
+ * 与其猜,不如直接不信任。这类部署应当配 `adminToken`。
116
+ *
117
+ * 拿不到远端地址时同样按「不受信」处理(安全默认)。
118
+ */
119
+ export declare function isLocalPeer(server: Pick<BunServerHandle, "requestIP">, request: Request, transport?: "tcp" | "unix"): boolean;
120
+ export {};
@@ -0,0 +1,109 @@
1
+ import { attachBunSocket, isLocalHost, syncSocketDataToString } from "./runtime.js";
2
+ // src/handler.ts
3
+ /**
4
+ * 创建一个 Bun handler。
5
+ *
6
+ * 处理三类请求:
7
+ * 1. `WS /api/<version>/sync`:升级为 WebSocket,交给 `SyncEngine`;
8
+ * 2. `/api/*`、`/_storage/*`、`/health` 等:交给 Convex HTTP API;
9
+ * 3. 其余:返回 404(页面由调用方的 `routes` 处理)。
10
+ */
11
+ function createBunHandler(runtime, options = {}) {
12
+ const { trustLocalhost } = runtime;
13
+ const routePrefix = options.prefix ? normalizePrefix(options.prefix) : runtime.prefix;
14
+ const fetchHandler = async (request, server) => {
15
+ const local = trustLocalhost && isLocalPeer(server, request, options.transport);
16
+ const originalRequest = request;
17
+ if (routePrefix) {
18
+ const stripped = stripPrefix(request, routePrefix);
19
+ if (!stripped) return new Response("Not found", { status: 404 });
20
+ request = stripped;
21
+ }
22
+ {
23
+ const probe = new URL(request.url);
24
+ if (probe.pathname.startsWith("//")) {
25
+ probe.pathname = probe.pathname.replace(/^\/{2,}/, "/");
26
+ request = new Request(probe, request);
27
+ }
28
+ }
29
+ const url = new URL(request.url);
30
+ if (url.pathname === "/sync" || url.pathname.endsWith("/sync")) return server.upgrade(originalRequest, { data: { local } }) ? void 0 : new Response("WebSocket upgrade failed", { status: 400 });
31
+ if (isApiPath(url.pathname)) return runtime.handle(request, { local });
32
+ return new Response("Not found", { status: 404 });
33
+ };
34
+ return {
35
+ fetch: fetchHandler,
36
+ websocket: {
37
+ open(ws) {
38
+ ws.data.connection = attachBunSocket(runtime.sync, {
39
+ send: (data) => ws.send(data),
40
+ close: (code, reason) => ws.close(code, reason)
41
+ }, { local: ws.data.local });
42
+ },
43
+ message(ws, message) {
44
+ const connection = ws.data.connection;
45
+ if (!connection) return;
46
+ runtime.sync.receive(connection, syncSocketDataToString(message));
47
+ },
48
+ close(ws) {
49
+ const connection = ws.data.connection;
50
+ if (connection) runtime.sync.detach(connection);
51
+ }
52
+ }
53
+ };
54
+ }
55
+ /**
56
+ * 判断连接是否来自本机。
57
+ *
58
+ * 用 `server.requestIP()` 拿真实远端地址,**不能**用 hostname:hostname
59
+ * 来自请求的 Host 头,客户端伪造 `Host: localhost` 就能绕过鉴权。
60
+ *
61
+ * **反向代理**:同机 nginx / Caddy 转发后 socket 地址一律是 `127.0.0.1`,
62
+ * 公网请求会被误判为本机。所以只要请求带转发头,就**不**认本机——
63
+ * 真实来源只有代理知道,而 `X-Forwarded-For` 本身又可被客户端伪造,
64
+ * 与其猜,不如直接不信任。这类部署应当配 `adminToken`。
65
+ *
66
+ * 拿不到远端地址时同样按「不受信」处理(安全默认)。
67
+ */
68
+ function isLocalPeer(server, request, transport = "tcp") {
69
+ const peer = server.requestIP?.(request);
70
+ if (!peer) return transport === "unix";
71
+ if (hasForwardingHeaders(request)) return false;
72
+ if (!peer.address) return false;
73
+ const address = peer.address.replace(/^::ffff:/, "");
74
+ return isLocalHost(address);
75
+ }
76
+ /**
77
+ * 请求是否经过反向代理(带任一标准转发头)。
78
+ *
79
+ * 只用来**否定**本机判定,不用来推导真实来源——这些头客户端也能伪造。
80
+ */
81
+ function hasForwardingHeaders(request) {
82
+ return request.headers.has("x-forwarded-for") || request.headers.has("x-real-ip") || request.headers.has("forwarded");
83
+ }
84
+ /**
85
+ * 把前缀规范成 `/xxx` 形式。
86
+ *
87
+ * 接受 `"v"` / `"/v"` / `"/v/"` 三种写法,统一成 `/v`;空串原样返回。
88
+ */
89
+ function normalizePrefix(prefix) {
90
+ const trimmed = prefix.trim().replace(/^\/+|\/+$/g, "");
91
+ return trimmed ? `/${trimmed}` : "";
92
+ }
93
+ /**
94
+ * 从请求路径里剥掉前缀,返回新路径的 Request。
95
+ *
96
+ * 前缀不匹配时返回 `null`。只改 pathname,保留 method / headers / body,
97
+ * 内核看到的与直接访问原始路径完全一致。
98
+ */
99
+ function stripPrefix(request, prefix) {
100
+ const url = new URL(request.url);
101
+ if (url.pathname !== prefix && !url.pathname.startsWith(`${prefix}/`)) return null;
102
+ url.pathname = url.pathname.slice(prefix.length) || "/";
103
+ return new Request(url, request);
104
+ }
105
+ /** 与 Cloudflare 版 `worker.ts` 一致的 API 路由前缀。 */
106
+ function isApiPath(pathname) {
107
+ return pathname.startsWith("/api/") || pathname.startsWith("/_storage/") || pathname.startsWith("/_http/") || pathname === "/_http" || pathname === "/_dashboard" || pathname.startsWith("/_dashboard/") || pathname === "/health";
108
+ }
109
+ export { createBunHandler, isLocalPeer };
@@ -0,0 +1,46 @@
1
+ /**
2
+ * ============================================================================
3
+ * @vultro/runtime-bun
4
+ * ============================================================================
5
+ *
6
+ * `@vultro/core` 的 Bun 运行时适配层:`Bun.serve` + `Bun.SQL`(SQLite 文件)。
7
+ *
8
+ * 典型用法(handler 由库提供,`Bun.serve` 由应用自己启动):
9
+ *
10
+ * ```ts
11
+ * import { createBunRuntime, createBunHandler } from "@vultro/runtime-bun";
12
+ * import index from "./index.html";
13
+ *
14
+ * const runtime = await createBunRuntime({
15
+ * schema,
16
+ * modules: { messages },
17
+ * dataDir: ".vultro",
18
+ * });
19
+ *
20
+ * const handler = createBunHandler(runtime);
21
+ *
22
+ * Bun.serve({
23
+ * port: 3000,
24
+ * // 前端页面:Bun 内置打包器会按需编译 HTML 引用的 TSX / CSS。
25
+ * routes: { "/": index },
26
+ * // 必须传 server:WebSocket 升级要用 server.upgrade()。
27
+ * fetch(req, server) {
28
+ * return handler.fetch(req, server);
29
+ * },
30
+ * websocket: handler.websocket,
31
+ * });
32
+ * ```
33
+ *
34
+ * 为什么库只给 handler 不给 server:路由编排(前端怎么挂、要不要额外路由)
35
+ * 属于应用层决定;`Bun.HTMLBundle` 也只能作为 `routes` 的值使用,无法塞进
36
+ * `Response`,所以 `Bun.serve` 必须在应用侧调用。
37
+ */
38
+ export { createBunRuntime, attachBunSocket, type BunRuntime, type BunRuntimeOptions, type BunSocketLike, } from "./runtime.js";
39
+ export { createBunHandler, isLocalPeer, type BunHandler, type BunHandlerOptions, type BunSocketData, } from "./handler.js";
40
+ export { createBunSqlDatabase, type BunSqlLike } from "./sql.js";
41
+ export { createTimeoutSchedulerDriver } from "./scheduler.js";
42
+ export { createBunStorage, type BunStorageOptions } from "./storage.js";
43
+ export { createLocalBlobStore, localBlobPath, type LocalBlobStoreOptions, } from "@vultro/storage-local";
44
+ export type { BlobStore, BlobStoreObject, BlobStorePutOptions, StorageFactory, } from "@vultro/core/storage";
45
+ export { isLocalHost, syncSocketDataToString } from "@vultro/core";
46
+ export { componentsManifestPath, loadComponentsFromManifest, type ComponentManifestEntry, } from "./components.js";
package/dist/index.js ADDED
@@ -0,0 +1,9 @@
1
+ import { attachBunSocket, createBunRuntime } from "./runtime.js";
2
+ import { createBunHandler, isLocalPeer } from "./handler.js";
3
+ import { createBunSqlDatabase } from "./sql.js";
4
+ import { createTimeoutSchedulerDriver } from "./scheduler.js";
5
+ import { createBunStorage } from "./storage.js";
6
+ import { createLocalBlobStore, localBlobPath } from "@vultro/storage-local";
7
+ import { isLocalHost, syncSocketDataToString } from "@vultro/core";
8
+ import { componentsManifestPath, loadComponentsFromManifest } from "./components.js";
9
+ export { attachBunSocket, componentsManifestPath, createBunHandler, createBunRuntime, createBunSqlDatabase, createBunStorage, createLocalBlobStore, createTimeoutSchedulerDriver, isLocalHost, isLocalPeer, loadComponentsFromManifest, localBlobPath, syncSocketDataToString };
@@ -0,0 +1,202 @@
1
+ /**
2
+ * ============================================================================
3
+ * @vultro/runtime-bun
4
+ * ============================================================================
5
+ *
6
+ * `@vultro/core` 的 Bun 运行时适配层。
7
+ *
8
+ * 与 `@vultro/runtime-cf` 的差异只在「平台外壳」,内核完全一致:
9
+ *
10
+ * | 能力 | Cloudflare | Bun |
11
+ * | ---------- | ----------------------- | -------------------------- |
12
+ * | HTTP | Worker `fetch` | `Bun.serve` |
13
+ * | 存储 | DO SQLite / D1 | `Bun.SQL` + SQLite 文件 |
14
+ * | 事务串行化 | 单 DO 实例 | 进程内 Mutex(单进程) |
15
+ * | WebSocket | `WebSocketPair` | `server.upgrade` |
16
+ * | 定时任务 | DO `alarm` | `setTimeout`(SchedulerDriver) |
17
+ * | 同步引擎 | `SyncEngine`(core) | 同一个 `SyncEngine` |
18
+ *
19
+ * 因为同步协议、事务、查询引擎都在 core 里,这里只做三件事:
20
+ * 1. 把 `Bun.SQL` 适配成 core 的异步存储后端;
21
+ * 2. 把 HTTP 请求交给 core 的 `createHttpApi`;
22
+ * 3. 把 WebSocket 连接交给 core 的 `SyncEngine`。
23
+ *
24
+ * 单进程天然等价于「一个 shard」,所以不需要 CF 那套 shard / 区域路由。
25
+ */
26
+ import { SyncEngine, isLocalHost, syncSocketDataToString, type BlobStore, type D1DatabaseLike, type DocStoreBackend, type PostgresClientLike, type MysqlClientLike, type SyncConnection } from "@vultro/core";
27
+ import type { StorageFactory } from "@vultro/core/storage";
28
+ import "@vultro/docstore-sqlite/runtime";
29
+ import { type SqliteRuntime } from "@vultro/core/sqlite-runtime";
30
+ import { type BunSqlLike } from "./sql.js";
31
+ /** 一个 Bun WebSocket 连接需要的最小能力。 */
32
+ export interface BunSocketLike {
33
+ send(data: string): void;
34
+ close(code?: number, reason?: string): void;
35
+ }
36
+ /** `createBunRuntime` 的选项。 */
37
+ export interface BunRuntimeOptions {
38
+ /** 用户 schema(`defineSchema()` 的返回值)。 */
39
+ schema?: unknown;
40
+ /** 函数模块映射:`{ messages: import * as messages }`。 */
41
+ modules: Record<string, unknown>;
42
+ /** 挂载的 Convex components。 */
43
+ components?: Record<string, unknown>;
44
+ /**
45
+ * 数据目录。**推荐用法**:整个应用的数据(SQLite、文件字节)都放这里,
46
+ * 备份一个目录就等于备份全部数据。
47
+ *
48
+ * 目录布局(使用默认的本地磁盘后端时):
49
+ *
50
+ * ```text
51
+ * <dataDir>/
52
+ * data.sqlite # 文档、元数据、执行日志
53
+ * blobs/
54
+ * objects/<storageId> # 文件字节
55
+ * objects/<storageId>.meta.json
56
+ * ```
57
+ *
58
+ * 目录不存在会自动创建。与 `database` 二选一,不能同时传。
59
+ */
60
+ dataDir?: string;
61
+ /**
62
+ * SQLite 数据库。
63
+ *
64
+ * 传 `Bun.SQL` 实例,或直接传文件路径(内部会用 `Bun.SQL` 打开)。
65
+ *
66
+ * 传**目录**(推荐)时会自动在其下创建 `data.sqlite`;传文件路径则只
67
+ * 影响数据库本身,文件字节的默认目录退化为 `<文件所在目录>/blobs`。
68
+ * 与 `dataDir` 二选一。
69
+ */
70
+ database?: BunSqlLike | string;
71
+ /**
72
+ * 使用 Postgres(Neon)作为文档存储。
73
+ *
74
+ * 与 `database` 二选一;提供后不再创建本地 SQLite。`pg` / `postgres`
75
+ * 的 client 都满足 `PostgresClientLike`,由调用方负责连接生命周期。
76
+ */
77
+ postgres?: PostgresClientLike;
78
+ /**
79
+ * 使用 MySQL / TiDB 作为文档存储。
80
+ *
81
+ * 与 `database` / `postgres` 三选一;提供后不再创建本地 SQLite。
82
+ * `mysql2/promise` 的 connection 满足 `MysqlClientLike`,由调用方负责
83
+ * 连接生命周期。
84
+ */
85
+ mysql?: MysqlClientLike;
86
+ /**
87
+ * 自定义文件存储工厂;省略时使用 Bun 默认值(原生 SQLite + 本地文件夹)。
88
+ *
89
+ * 生成的入口会从 `vultro.config.ts` 的 `storage: s3Storage()` 等选择器
90
+ * 注入;嵌入式调用也可以直接传工厂。
91
+ */
92
+ storage?: StorageFactory;
93
+ /** 文档存储后端包选择器;省略时使用本地 SQLite 适配路径。 */
94
+ docStore?: DocStoreBackend;
95
+ /** deployment 的公开地址,用于 `ctx.storage.getUrl()` 返回绝对 URL。 */
96
+ deploymentUrl?: string;
97
+ /**
98
+ * API 路由前缀,例如 `"/v"`。空串表示不加前缀。
99
+ *
100
+ * 配了之后 runtime 会自动处理两件事,应用**不需要**再手动拼:
101
+ *
102
+ * 1. `ctx.storage.getUrl()` / `generateUploadUrl()` 返回的地址带上前缀;
103
+ * 2. `createBunHandler` 从传入路径里剥掉前缀再交给内核。
104
+ *
105
+ * 内核看到的仍是 `/api/...` 原始路径,所以 `convex/` 下的代码不用改。
106
+ */
107
+ prefix?: string;
108
+ /**
109
+ * 文件字节存哪里。**默认使用本地磁盘**(内部调用
110
+ * `createLocalBlobStore`,目录是 `<dataDir>/blobs`),开箱就有真正的
111
+ * 文件存储,不必先配对象存储。
112
+ *
113
+ * 只接受两种值:
114
+ *
115
+ * - 不传(默认):`createLocalBlobStore({ root: <dataDir>/blobs })`;
116
+ * - `"none"`:字节只存 SQLite 的 base64 副本(与 Cloudflare 无 R2 时一致),
117
+ * 适合「文件很小、想少一个目录」的场景;
118
+ * - `BlobStore` 实例:任意后端。用 `createS3BlobStore({...})` 接 S3 /
119
+ * MinIO,或用 `createLocalBlobStore({ root })` 换目录。
120
+ *
121
+ * 元数据始终留在 SQLite,所以切换后端不影响已登记的文件列表;
122
+ * 但**旧文件不会自动迁移**,换后端后旧文件的字节读不到(会回退到
123
+ * SQLite 副本,如果之前没开双写则返回 404)。
124
+ *
125
+ * ```ts
126
+ * import { createS3BlobStore } from "@vultro/runtime-bun";
127
+ *
128
+ * // 默认:本地磁盘,SQLite 与文件字节都在 dataDir 下
129
+ * await createBunRuntime({ modules, dataDir: ".vultro" });
130
+ *
131
+ * // S3(AWS 或 MinIO):显式构造适配器
132
+ * await createBunRuntime({
133
+ * modules,
134
+ * dataDir: ".vultro",
135
+ * blobs: createS3BlobStore({
136
+ * bucket: "my-bucket",
137
+ * region: "us-east-1",
138
+ * accessKeyId: process.env.S3_KEY!,
139
+ * secretAccessKey: process.env.S3_SECRET!,
140
+ * }),
141
+ * });
142
+ *
143
+ * // 本地磁盘换目录
144
+ * await createBunRuntime({
145
+ * modules,
146
+ * dataDir: ".vultro",
147
+ * blobs: createLocalBlobStore({ root: "/data/blobs" }),
148
+ * });
149
+ * ```
150
+ */
151
+ blobs?: "none" | BlobStore;
152
+ /**
153
+ * 默认本地磁盘后端的根目录。默认 `<dataDir>/blobs`。
154
+ *
155
+ * 已由 `blobs: createLocalBlobStore({ root })` 取代;保留是为了向后兼容。
156
+ */
157
+ blobDir?: string;
158
+ /**
159
+ * 系统 UDF 的 admin token。
160
+ *
161
+ * 未设置时**不会**按 localhost 自动放行:请求 hostname 来自可伪造的
162
+ * Host 头,用它判断来源是安全漏洞。本机开发靠 `handle()` 的
163
+ * `context.local`(`createBunHandler` 已用 `server.requestIP()` 判定)。
164
+ */
165
+ adminToken?: string;
166
+ /**
167
+ * 是否允许「本机连接」免 token 访问系统接口。默认 `true`。
168
+ *
169
+ * 默认放开是因为直连场景下 `server.requestIP()` 给出的就是真实远端
170
+ * 地址,公网客户端不会被判成本机。
171
+ *
172
+ * **反向代理场景**:nginx / Caddy 等同机代理转发后,socket 地址一律是
173
+ * `127.0.0.1`,公网请求会被误判为本机。为此 `isLocalPeer()` 只要看到
174
+ * 转发头(`x-forwarded-for` / `x-real-ip` / `forwarded`)就直接拒绝本机
175
+ * 判定,不再依赖 socket 地址。
176
+ *
177
+ * 如果代理不写转发头、或者部署方希望**彻底**关掉本机免 token,把它设为
178
+ * `false`——此时系统接口只能靠 `adminToken` 访问。
179
+ */
180
+ trustLocalhost?: boolean;
181
+ }
182
+ /**
183
+ * 运行时组合结果。
184
+ *
185
+ * 与 Node 共享 `SqliteRuntime` 结构(见 `@vultro/core/sqlite-runtime`);
186
+ * 差异只在创建时使用的 SQL 驱动。
187
+ */
188
+ export type BunRuntime = SqliteRuntime;
189
+ /**
190
+ * 创建一个 Bun 运行时。
191
+ *
192
+ * 平台无关的装配(文档存储 / HTTP API / 同步引擎)在
193
+ * `@vultro/core/sqlite-runtime`;这里只负责把 `Bun.SQL` 和本地磁盘
194
+ * BlobStore 解析成 core 需要的接口。
195
+ */
196
+ export declare function createBunRuntime(options: BunRuntimeOptions): Promise<BunRuntime>;
197
+ /** 把 Bun 的 WebSocket 连接接到同步引擎上。 */
198
+ export declare function attachBunSocket(sync: SyncEngine, ws: BunSocketLike, options?: {
199
+ local?: boolean;
200
+ }): SyncConnection;
201
+ export { syncSocketDataToString, isLocalHost };
202
+ export type { D1DatabaseLike };
@@ -0,0 +1,192 @@
1
+ import { existsSync, mkdirSync, statSync } from "node:fs";
2
+ import { dirname, join, resolve } from "node:path";
3
+ import { isLocalHost, syncSocketDataToString } from "@vultro/core";
4
+ import { sqliteStore } from "@vultro/docstore-sqlite";
5
+ import "@vultro/docstore-sqlite/runtime";
6
+ import { createSqliteRuntime } from "@vultro/core/sqlite-runtime";
7
+ import { createBunSqlDatabase } from "./sql.js";
8
+ import { createTimeoutSchedulerDriver } from "./scheduler.js";
9
+ import { createBunStorage } from "./storage.js";
10
+ import { installBunWasmFetch } from "./wasm-fetch.js";
11
+ // src/runtime.ts
12
+ /**
13
+ * ============================================================================
14
+ * @vultro/runtime-bun
15
+ * ============================================================================
16
+ *
17
+ * `@vultro/core` 的 Bun 运行时适配层。
18
+ *
19
+ * 与 `@vultro/runtime-cf` 的差异只在「平台外壳」,内核完全一致:
20
+ *
21
+ * | 能力 | Cloudflare | Bun |
22
+ * | ---------- | ----------------------- | -------------------------- |
23
+ * | HTTP | Worker `fetch` | `Bun.serve` |
24
+ * | 存储 | DO SQLite / D1 | `Bun.SQL` + SQLite 文件 |
25
+ * | 事务串行化 | 单 DO 实例 | 进程内 Mutex(单进程) |
26
+ * | WebSocket | `WebSocketPair` | `server.upgrade` |
27
+ * | 定时任务 | DO `alarm` | `setTimeout`(SchedulerDriver) |
28
+ * | 同步引擎 | `SyncEngine`(core) | 同一个 `SyncEngine` |
29
+ *
30
+ * 因为同步协议、事务、查询引擎都在 core 里,这里只做三件事:
31
+ * 1. 把 `Bun.SQL` 适配成 core 的异步存储后端;
32
+ * 2. 把 HTTP 请求交给 core 的 `createHttpApi`;
33
+ * 3. 把 WebSocket 连接交给 core 的 `SyncEngine`。
34
+ *
35
+ * 单进程天然等价于「一个 shard」,所以不需要 CF 那套 shard / 区域路由。
36
+ */
37
+ /**
38
+ * 创建一个 Bun 运行时。
39
+ *
40
+ * 平台无关的装配(文档存储 / HTTP API / 同步引擎)在
41
+ * `@vultro/core/sqlite-runtime`;这里只负责把 `Bun.SQL` 和本地磁盘
42
+ * BlobStore 解析成 core 需要的接口。
43
+ */
44
+ async function createBunRuntime(options) {
45
+ installBunWasmFetch();
46
+ if ([
47
+ options.database,
48
+ options.postgres,
49
+ options.mysql
50
+ ].filter((value) => value !== void 0).length > 1) throw new Error("database / postgres / mysql 只能选一个");
51
+ const resolved = resolveDataDir(options);
52
+ const docStore = options.docStore ?? sqliteStore();
53
+ const storage = options.storage ?? createBunStorage({
54
+ dataDir: resolved.dir,
55
+ ...options.blobDir ? { blobDir: options.blobDir } : {},
56
+ ...options.blobs ? { blobs: options.blobs } : {}
57
+ });
58
+ if (options.mysql) {
59
+ const database = docStore.createDatabase?.("bun", { mysql: options.mysql });
60
+ if (!database) throw new Error("mysql requires `docStore: mysqlStore()` from @vultro/docstore-mysql");
61
+ return createSqliteRuntime({
62
+ database,
63
+ schema: options.schema,
64
+ modules: options.modules,
65
+ components: options.components,
66
+ deploymentUrl: options.deploymentUrl,
67
+ prefix: options.prefix,
68
+ storage,
69
+ docStore,
70
+ mysql: options.mysql,
71
+ scheduler: createTimeoutSchedulerDriver,
72
+ runtime: "bun",
73
+ adminToken: options.adminToken,
74
+ trustLocalhost: options.trustLocalhost
75
+ });
76
+ }
77
+ if (options.postgres) {
78
+ const database = docStore.createDatabase?.("bun", { postgres: options.postgres });
79
+ if (!database) throw new Error("postgres requires `docStore: pgStore()` from @vultro/docstore-postgres");
80
+ return createSqliteRuntime({
81
+ database,
82
+ schema: options.schema,
83
+ modules: options.modules,
84
+ components: options.components,
85
+ deploymentUrl: options.deploymentUrl,
86
+ prefix: options.prefix,
87
+ storage,
88
+ docStore,
89
+ postgres: options.postgres,
90
+ scheduler: createTimeoutSchedulerDriver,
91
+ runtime: "bun",
92
+ adminToken: options.adminToken,
93
+ trustLocalhost: options.trustLocalhost
94
+ });
95
+ }
96
+ const sql = resolveSql(resolved.database);
97
+ return createSqliteRuntime({
98
+ database: createBunSqlDatabase(sql),
99
+ schema: options.schema,
100
+ modules: options.modules,
101
+ components: options.components,
102
+ deploymentUrl: options.deploymentUrl,
103
+ prefix: options.prefix,
104
+ storage,
105
+ docStore,
106
+ scheduler: createTimeoutSchedulerDriver,
107
+ runtime: "bun",
108
+ adminToken: options.adminToken,
109
+ trustLocalhost: options.trustLocalhost,
110
+ closeDatabase: () => sql.close()
111
+ });
112
+ }
113
+ /**
114
+ * 把 `dataDir` / `database` 归一成「数据目录 + 数据库文件」。
115
+ *
116
+ * 支持的输入:
117
+ *
118
+ * - `dataDir: ".vultro"` → 目录 `.vultro`,数据库 `.vultro/data.sqlite`;
119
+ * - `database: ".vultro"`(目录,不存在)→ 同上;
120
+ * - `database: ".vultro/data.sqlite"`(文件)→ 目录 `.vultro`;
121
+ * - `database: ":memory:"` → 内存库,没有目录;
122
+ * - 都不传 → 默认 `.vultro/data.sqlite`(相对 cwd)。
123
+ *
124
+ * 判断「目录还是文件」不能只看后缀:用户可能用 `.sqlite3` / `.db3` 甚至
125
+ * 没有后缀的数据库文件名。这里的规则是——**已存在的路径一律当文件**,
126
+ * 只有不存在且没有数据库后缀的路径才按目录处理。
127
+ */
128
+ function resolveDataDir(options) {
129
+ if (options.dataDir) {
130
+ if (typeof options.database === "string") throw new Error("传 dataDir 时不要再传 database 文件路径,两者只能选一个");
131
+ return {
132
+ database: options.database ?? join(options.dataDir, "data.sqlite"),
133
+ dir: options.dataDir
134
+ };
135
+ }
136
+ const database = options.database;
137
+ if (database === void 0) {
138
+ const dir = join(process.cwd(), ".vultro");
139
+ return {
140
+ database: join(dir, "data.sqlite"),
141
+ dir
142
+ };
143
+ }
144
+ if (typeof database !== "string") return {
145
+ database,
146
+ dir: void 0
147
+ };
148
+ const path = database.startsWith("file://") ? database.slice(7) : database;
149
+ if (path === ":memory:") return {
150
+ database,
151
+ dir: void 0
152
+ };
153
+ if (existsSync(path) && statSync(path).isFile()) return {
154
+ database,
155
+ dir: dirname(resolve(path))
156
+ };
157
+ if (/\.(sqlite3?|db3?)$/i.test(path)) return {
158
+ database,
159
+ dir: dirname(resolve(path))
160
+ };
161
+ return {
162
+ database: join(path, "data.sqlite"),
163
+ dir: path
164
+ };
165
+ }
166
+ /** 把 `Bun.SQL` 实例或文件路径统一成实例。 */
167
+ function resolveSql(database) {
168
+ if (typeof database !== "string") return database;
169
+ const path = database.startsWith("file://") ? database.slice(7) : database;
170
+ if (path === ":memory:") {
171
+ const BunSql = globalThis.Bun?.SQL;
172
+ if (!BunSql) throw new Error("Bun.SQL is not available in this runtime");
173
+ return new BunSql({
174
+ url: "sqlite://:memory:",
175
+ adapter: "sqlite"
176
+ });
177
+ }
178
+ const dir = dirname(resolve(path));
179
+ if (dir) mkdirSync(dir, { recursive: true });
180
+ const url = `sqlite://${path}`;
181
+ const BunSql = globalThis.Bun?.SQL;
182
+ if (!BunSql) throw new Error("Bun.SQL is not available in this runtime");
183
+ return new BunSql({
184
+ url,
185
+ adapter: "sqlite"
186
+ });
187
+ }
188
+ /** 把 Bun 的 WebSocket 连接接到同步引擎上。 */
189
+ function attachBunSocket(sync, ws, options = {}) {
190
+ return sync.attach(ws, options);
191
+ }
192
+ export { attachBunSocket, createBunRuntime, isLocalHost, syncSocketDataToString };
@@ -0,0 +1,25 @@
1
+ import type { SchedulerDriver, SchedulerDriverContext } from "@vultro/core";
2
+ /**
3
+ * ============================================================================
4
+ * 进程内定时任务驱动器(Bun / Node)
5
+ * ============================================================================
6
+ *
7
+ * Bun 与 Node 都没有 Durable Object alarm,进程内 `setTimeout` 就是最直接的
8
+ * 定时器。Node 运行时已经依赖 `@vultro/runtime-bun` 的 SQL 形状适配器,因此
9
+ * 这里复用同一份实现,避免两个包各写一套定时器状态机。
10
+ *
11
+ * 关键语义:
12
+ *
13
+ * - `start()` 从数据库恢复下一个待执行时间;
14
+ * - `schedule()` 只允许提前,不允许把已排好的唤醒推后;
15
+ * - 定时器 `unref()`,不会阻止 CLI / 测试进程退出;
16
+ * - `dispose()` 会等待正在执行的 `fire()`,避免关闭数据库时还有任务在跑;
17
+ * - `runDue()` 抛错时 1 秒后重试,避免一次数据库异常让 pending 任务永久停摆。
18
+ */
19
+ /**
20
+ * 基于 `setTimeout` 的驱动器。
21
+ *
22
+ * 由 `@vultro/runtime-bun` / `@vultro/runtime-node` 在创建运行时显式注入;
23
+ * core 只保留接口,不把这段实现带进 Cloudflare 构建。
24
+ */
25
+ export declare function createTimeoutSchedulerDriver(context: SchedulerDriverContext): SchedulerDriver;
@@ -0,0 +1,82 @@
1
+ // src/scheduler.ts
2
+ /**
3
+ * ============================================================================
4
+ * 进程内定时任务驱动器(Bun / Node)
5
+ * ============================================================================
6
+ *
7
+ * Bun 与 Node 都没有 Durable Object alarm,进程内 `setTimeout` 就是最直接的
8
+ * 定时器。Node 运行时已经依赖 `@vultro/runtime-bun` 的 SQL 形状适配器,因此
9
+ * 这里复用同一份实现,避免两个包各写一套定时器状态机。
10
+ *
11
+ * 关键语义:
12
+ *
13
+ * - `start()` 从数据库恢复下一个待执行时间;
14
+ * - `schedule()` 只允许提前,不允许把已排好的唤醒推后;
15
+ * - 定时器 `unref()`,不会阻止 CLI / 测试进程退出;
16
+ * - `dispose()` 会等待正在执行的 `fire()`,避免关闭数据库时还有任务在跑;
17
+ * - `runDue()` 抛错时 1 秒后重试,避免一次数据库异常让 pending 任务永久停摆。
18
+ */
19
+ /**
20
+ * 基于 `setTimeout` 的驱动器。
21
+ *
22
+ * 由 `@vultro/runtime-bun` / `@vultro/runtime-node` 在创建运行时显式注入;
23
+ * core 只保留接口,不把这段实现带进 Cloudflare 构建。
24
+ */
25
+ function createTimeoutSchedulerDriver(context) {
26
+ let timer;
27
+ let scheduledAt;
28
+ let disposed = false;
29
+ /** 正在进行中的 fire;dispose 等它结束,避免关闭数据库时还有任务在跑。 */
30
+ let inFlight;
31
+ function clearTimer() {
32
+ if (timer !== void 0) {
33
+ clearTimeout(timer);
34
+ timer = void 0;
35
+ }
36
+ scheduledAt = void 0;
37
+ }
38
+ async function fire() {
39
+ if (disposed) return;
40
+ const task = (async () => {
41
+ try {
42
+ await context.runDue();
43
+ } catch (error) {
44
+ console.error("[vultro] scheduled job runner failed:", error);
45
+ schedule(Date.now() + 1e3);
46
+ }
47
+ })();
48
+ inFlight = task;
49
+ try {
50
+ await task;
51
+ } finally {
52
+ if (inFlight === task) inFlight = void 0;
53
+ }
54
+ }
55
+ function schedule(runAt) {
56
+ if (disposed) return;
57
+ if (scheduledAt !== void 0 && scheduledAt <= runAt) return;
58
+ clearTimer();
59
+ scheduledAt = runAt;
60
+ const delay = Math.max(0, runAt - Date.now());
61
+ timer = setTimeout(() => {
62
+ timer = void 0;
63
+ scheduledAt = void 0;
64
+ fire();
65
+ }, delay);
66
+ timer.unref?.();
67
+ }
68
+ return {
69
+ start() {
70
+ const next = context.nextRun();
71
+ if (next !== null) schedule(next);
72
+ },
73
+ schedule,
74
+ fire,
75
+ dispose() {
76
+ disposed = true;
77
+ clearTimer();
78
+ return inFlight;
79
+ }
80
+ };
81
+ }
82
+ export { createTimeoutSchedulerDriver };
package/dist/sql.d.ts ADDED
@@ -0,0 +1,37 @@
1
+ /**
2
+ * ============================================================================
3
+ * Bun.SQL → D1DatabaseLike 适配器
4
+ * ============================================================================
5
+ *
6
+ * 为什么要适配成 D1 的接口形状,而不是新写一套存储:
7
+ *
8
+ * `@vultro/core` 已经有一条成熟的「异步 SQL 后端」路径
9
+ * (`AsyncCachedDocumentStore` + `D1AsyncTransaction`):它用内存 Map 做读写
10
+ * 缓存、把提交异步落到 SQL,接口与同步 `DocumentStore` 完全一致。这条路径
11
+ * 原本是为 Cloudflare D1 写的,但它只依赖 `prepare/bind/all/run` 这四个
12
+ * 方法——`Bun.SQL` 完全能满足。
13
+ *
14
+ * 因此 Bun 运行时直接复用这条路径,而不是再写一个 SQLite 存储实现:
15
+ * 事务、索引、查询构建器、schema 校验全部走同一份代码,两个运行时的行为
16
+ * 不会漂移。
17
+ *
18
+ * 与 D1 的差异(这里必须转换,否则 `AsyncCachedDocumentStore` 会读到 undefined):
19
+ *
20
+ * - D1 的 `all()` 返回 `{ results: T[] }`,`Bun.SQL` 直接返回数组本身;
21
+ * - D1 的 `first()` 返回首行或 `null`,`Bun.SQL` 没有对应方法;
22
+ * - D1 的 `bind()` 是链式惰性绑定,`Bun.SQL` 是立即执行。
23
+ */
24
+ import type { D1DatabaseLike } from "@vultro/core";
25
+ /** `Bun.SQL` 实例的最小结构类型(避免依赖 Bun 的完整类型定义)。 */
26
+ export interface BunSqlLike {
27
+ /** 用位置参数执行一条 SQL。 */
28
+ unsafe(sql: string, params?: unknown[]): Promise<unknown>;
29
+ close(): Promise<void>;
30
+ }
31
+ /**
32
+ * 把 `Bun.SQL` 包装成 D1 风格的数据库接口。
33
+ *
34
+ * 每次 `prepare` 产出一个惰性语句对象:`bind()` 记录参数,`all()` / `run()`
35
+ * 才真正执行。这与 D1 的调用习惯一致(`db.prepare(...).bind(...).all()`)。
36
+ */
37
+ export declare function createBunSqlDatabase(sql: BunSqlLike): D1DatabaseLike;
package/dist/sql.js ADDED
@@ -0,0 +1,70 @@
1
+ // src/sql.ts
2
+ /**
3
+ * 把 `Bun.SQL` 包装成 D1 风格的数据库接口。
4
+ *
5
+ * 每次 `prepare` 产出一个惰性语句对象:`bind()` 记录参数,`all()` / `run()`
6
+ * 才真正执行。这与 D1 的调用习惯一致(`db.prepare(...).bind(...).all()`)。
7
+ */
8
+ function createBunSqlDatabase(sql) {
9
+ return {
10
+ prepare(query) {
11
+ let bound = [];
12
+ const statement = {
13
+ bind(...values) {
14
+ bound = values;
15
+ return statement;
16
+ },
17
+ async first() {
18
+ return normalizeRows(await sql.unsafe(query, bound))[0] ?? null;
19
+ },
20
+ async all() {
21
+ return {
22
+ results: normalizeRows(await sql.unsafe(query, bound)),
23
+ success: true
24
+ };
25
+ },
26
+ async run() {
27
+ return {
28
+ success: true,
29
+ meta: metaOf(await sql.unsafe(query, bound))
30
+ };
31
+ }
32
+ };
33
+ return statement;
34
+ },
35
+ async exec(query) {
36
+ await sql.unsafe(query);
37
+ return { success: true };
38
+ },
39
+ async batch(statements) {
40
+ const results = [];
41
+ for (const statement of statements) results.push(await statement.run());
42
+ return results;
43
+ }
44
+ };
45
+ }
46
+ /**
47
+ * `Bun.SQL` 返回的是「带附加属性的数组」:
48
+ *
49
+ * ```ts
50
+ * [ { id: 1, name: "a" }, count: 1, command: "SELECT", affectedRows: 0 ]
51
+ * ```
52
+ *
53
+ * 数组本身是行数据,附加属性是元信息。这里只取行数据,把 `ArrayLike`
54
+ * 之外的部分丢掉,避免它们被当成某一行参与后续遍历。
55
+ */
56
+ function normalizeRows(value) {
57
+ if (!Array.isArray(value)) return [];
58
+ return value;
59
+ }
60
+ /** 从 `Bun.SQL` 的结果里提取 D1 风格的 meta 信息。 */
61
+ function metaOf(value) {
62
+ if (!Array.isArray(value)) return {};
63
+ const rows = value;
64
+ return {
65
+ changes: typeof rows.affectedRows === "number" ? rows.affectedRows : 0,
66
+ last_row_id: typeof rows.lastInsertRowid === "number" ? rows.lastInsertRowid : null,
67
+ rows_written: typeof rows.count === "number" ? rows.count : 0
68
+ };
69
+ }
70
+ export { createBunSqlDatabase };
@@ -0,0 +1,25 @@
1
+ import type { BlobStore, StorageFactory } from "@vultro/core/storage";
2
+ /**
3
+ * ============================================================================
4
+ * Bun 默认 Storage
5
+ * ============================================================================
6
+ *
7
+ * Bun 运行时的 `ctx.storage` 默认组合:
8
+ *
9
+ * - 元数据:`Bun.SQL` 打开的原生 SQLite(Runtime 通过 `StorageContext.d1`
10
+ * 传入);
11
+ * - 字节:`<dataDir>/blobs` 本地文件夹。
12
+ *
13
+ * 需要换成 S3 / 自定义目录时,传 `blobs` / `blobDir`;传 `"none"` 则只保留
14
+ * SQLite 里的 base64 副本。
15
+ */
16
+ export interface BunStorageOptions {
17
+ /** 数据目录,默认 `.vultro`。 */
18
+ dataDir?: string;
19
+ /** 本地字节目录;默认 `<dataDir>/blobs`。 */
20
+ blobDir?: string;
21
+ /** `"none"` 关闭本地文件夹;或传自定义 BlobStore。 */
22
+ blobs?: "none" | BlobStore;
23
+ }
24
+ /** 创建 Bun 运行时的默认 Storage 工厂。 */
25
+ export declare function createBunStorage(options?: BunStorageOptions): StorageFactory;
@@ -0,0 +1,10 @@
1
+ import { createLocalStorage } from "@vultro/storage-local";
2
+ // src/storage.ts
3
+ /** 创建 Bun 运行时的默认 Storage 工厂。 */
4
+ function createBunStorage(options = {}) {
5
+ return createLocalStorage({
6
+ root: options.blobDir ?? `${options.dataDir ?? ".vultro"}/blobs`,
7
+ ...options.blobs ? { blobs: options.blobs } : {}
8
+ });
9
+ }
10
+ export { createBunStorage };
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Bun 的 `fetch(file://)` 兼容层。
3
+ *
4
+ * 为什么需要:有些 npm 包(例如 `password-hash-wasm`,Convex Auth 依赖它)
5
+ * 会 `import wasm from "./xxx_bg.wasm"`,Bun 把这种 import 解析成**绝对路径
6
+ * 字符串**,库随后把它交给 `fetch()` 加载。Bun 的 fetch 不支持 file:// 或
7
+ * 绝对路径,于是 WASM 初始化直接失败。
8
+ *
9
+ * 这里只拦截「file: URL 或绝对路径的 .wasm」,用 `Bun.file()` 读成
10
+ * `Response` 交给库;其它请求原样交还给原生 fetch,不影响业务代码。
11
+ *
12
+ * 用 Vite 构建时 `@vultro/vite-plugin` 会把 `.wasm` 内嵌成
13
+ * `WebAssembly.Module`,因此这个兼容层主要服务 `bun test`、`apps/custom`
14
+ * 这类不经过 Vite 的 Bun 进程。
15
+ */
16
+ /** 幂等安装;多次调用只包一层 fetch。 */
17
+ export declare function installBunWasmFetch(): void;
@@ -0,0 +1,46 @@
1
+ // src/wasm-fetch.ts
2
+ /**
3
+ * Bun 的 `fetch(file://)` 兼容层。
4
+ *
5
+ * 为什么需要:有些 npm 包(例如 `password-hash-wasm`,Convex Auth 依赖它)
6
+ * 会 `import wasm from "./xxx_bg.wasm"`,Bun 把这种 import 解析成**绝对路径
7
+ * 字符串**,库随后把它交给 `fetch()` 加载。Bun 的 fetch 不支持 file:// 或
8
+ * 绝对路径,于是 WASM 初始化直接失败。
9
+ *
10
+ * 这里只拦截「file: URL 或绝对路径的 .wasm」,用 `Bun.file()` 读成
11
+ * `Response` 交给库;其它请求原样交还给原生 fetch,不影响业务代码。
12
+ *
13
+ * 用 Vite 构建时 `@vultro/vite-plugin` 会把 `.wasm` 内嵌成
14
+ * `WebAssembly.Module`,因此这个兼容层主要服务 `bun test`、`apps/custom`
15
+ * 这类不经过 Vite 的 Bun 进程。
16
+ */
17
+ var installed = false;
18
+ /** 幂等安装;多次调用只包一层 fetch。 */
19
+ function installBunWasmFetch() {
20
+ if (installed) return;
21
+ if (typeof Bun === "undefined" || typeof globalThis.fetch !== "function") return;
22
+ installed = true;
23
+ const originalFetch = globalThis.fetch;
24
+ const wrappedFetch = (async (input, init) => {
25
+ const target = typeof input === "string" ? input : input instanceof URL ? input.href : void 0;
26
+ if (target && isLocalWasmTarget(target)) {
27
+ const file = Bun.file(target);
28
+ if (await file.exists()) return new Response(file);
29
+ }
30
+ return await originalFetch(input, init);
31
+ });
32
+ for (const key of Object.getOwnPropertyNames(originalFetch)) {
33
+ const descriptor = Object.getOwnPropertyDescriptor(originalFetch, key);
34
+ if (!descriptor) continue;
35
+ try {
36
+ Object.defineProperty(wrappedFetch, key, descriptor);
37
+ } catch {}
38
+ }
39
+ globalThis.fetch = wrappedFetch;
40
+ }
41
+ /** 只处理本地 WASM 文件,避免影响普通请求。 */
42
+ function isLocalWasmTarget(target) {
43
+ if (!target.endsWith(".wasm")) return false;
44
+ return target.startsWith("file:") || target.startsWith("/") || /^[A-Za-z]:[\\/]/.test(target);
45
+ }
46
+ export { installBunWasmFetch };
package/package.json CHANGED
@@ -1,6 +1,37 @@
1
1
  {
2
2
  "name": "@vultro/runtime-bun",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.2",
4
+ "type": "module",
5
+ "description": "Bun runtime adapter for @vultro/core (Bun.serve + Bun.SQL SQLite)",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./dist/index.d.ts",
9
+ "import": "./dist/index.js",
10
+ "default": "./dist/index.js"
11
+ },
12
+ "./blob-store": {
13
+ "types": "./dist/blob-store.d.ts",
14
+ "import": "./dist/blob-store.js",
15
+ "default": "./dist/blob-store.js"
16
+ },
17
+ "./scheduler": {
18
+ "types": "./dist/scheduler.d.ts",
19
+ "import": "./dist/scheduler.js",
20
+ "default": "./dist/scheduler.js"
21
+ },
22
+ "./sql": {
23
+ "types": "./dist/sql.d.ts",
24
+ "import": "./dist/sql.js",
25
+ "default": "./dist/sql.js"
26
+ }
27
+ },
28
+ "dependencies": {
29
+ "@vultro/core": "0.0.2",
30
+ "@vultro/docstore-sqlite": "0.0.2",
31
+ "@vultro/storage-local": "0.0.2"
32
+ },
33
+ "publishConfig": {
34
+ "access": "public"
35
+ },
36
+ "types": "./dist/index.d.ts"
37
+ }