@vultro/runtime-node 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.
@@ -0,0 +1,18 @@
1
+ /**
2
+ * ============================================================================
3
+ * @vultro/runtime-node
4
+ * ============================================================================
5
+ *
6
+ * `@vultro/core` 的 Node 适配层:
7
+ *
8
+ * - `createNodeRuntime()`:`node:sqlite` + 与 Bun 相同的内核组合;
9
+ * - `createNodeServer()`:`node:http` + `ws`,提供 Convex HTTP API、同步
10
+ * WebSocket 与 `dist/client` 静态托管。
11
+ *
12
+ * 与 `@vultro/runtime-cf` / `@vultro/runtime-bun` 共享同一份 core,业务函数不需要任何改动。
13
+ */
14
+ export { createNodeRuntime, type NodeRuntime, type NodeRuntimeOptions, } from "./runtime.js";
15
+ export { createNodeServer, type NodeServer, type NodeServerOptions } from "./server.js";
16
+ export { createNodeSql, type NodeSql } from "./sql.js";
17
+ export { createTimeoutSchedulerDriver } from "@vultro/runtime-bun/scheduler";
18
+ export { createNodeStorage, type NodeStorageOptions } from "./storage.js";
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ import { createNodeRuntime } from "./runtime.js";
2
+ import { createNodeServer } from "./server.js";
3
+ import { createNodeSql } from "./sql.js";
4
+ import { createTimeoutSchedulerDriver } from "@vultro/runtime-bun/scheduler";
5
+ import { createNodeStorage } from "./storage.js";
6
+ export { createNodeRuntime, createNodeServer, createNodeSql, createNodeStorage, createTimeoutSchedulerDriver };
@@ -0,0 +1,28 @@
1
+ import type { BunRuntimeOptions } from "@vultro/runtime-bun";
2
+ import "@vultro/docstore-sqlite/runtime";
3
+ import { type SqliteRuntime } from "@vultro/core/sqlite-runtime";
4
+ /**
5
+ * `@vultro/runtime-node` 的运行时组合。
6
+ *
7
+ * 与 Bun 适配层共享全部内核能力(事务 / 查询 / 同步 / 存储),差异只在:
8
+ * - SQL 驱动换成 `node:sqlite`(Node 22+ 内置);
9
+ * - HTTP / WebSocket 外壳在 `server.ts` 里用 `node:http` + `ws` 实现。
10
+ *
11
+ * 平台无关的装配在 `@vultro/core/sqlite-runtime`;这里只导入
12
+ * `@vultro/runtime-bun` 的 SQL 形状转换模块。文件存储默认值来自
13
+ * `@vultro/storage-local`(原生 SQLite + 本地文件夹),不再依赖 Bun 适配层,
14
+ * 不会把 `Bun.SQL` / `Bun.serve` 等实现带进 Node 产物。
15
+ */
16
+ export type NodeRuntime = SqliteRuntime;
17
+ /** `createNodeRuntime` 的选项。 */
18
+ export interface NodeRuntimeOptions extends Omit<BunRuntimeOptions, "database"> {
19
+ /**
20
+ * SQLite 文件路径。
21
+ *
22
+ * 不传时使用 `<dataDir>/data.sqlite`;`dataDir` 也不传时是
23
+ * `process.cwd()/.vultro`。
24
+ */
25
+ database?: string;
26
+ }
27
+ /** 创建 Node 运行时(`node:sqlite` + 共享的 SQLite 运行时组合)。 */
28
+ export declare function createNodeRuntime(options: NodeRuntimeOptions): Promise<NodeRuntime>;
@@ -0,0 +1,81 @@
1
+ import { mkdirSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { createBunSqlDatabase } from "@vultro/runtime-bun/sql";
4
+ import { sqliteStore } from "@vultro/docstore-sqlite";
5
+ import "@vultro/docstore-sqlite/runtime";
6
+ import { createTimeoutSchedulerDriver } from "@vultro/runtime-bun/scheduler";
7
+ import { createSqliteRuntime } from "@vultro/core/sqlite-runtime";
8
+ import { createNodeSql } from "./sql.js";
9
+ import { createNodeStorage } from "./storage.js";
10
+ // src/runtime.ts
11
+ /** 创建 Node 运行时(`node:sqlite` + 共享的 SQLite 运行时组合)。 */
12
+ async function createNodeRuntime(options) {
13
+ if ([
14
+ options.database,
15
+ options.postgres,
16
+ options.mysql
17
+ ].filter((value) => value !== void 0).length > 1) throw new Error("database / postgres / mysql 只能选一个");
18
+ const docStore = options.docStore ?? sqliteStore();
19
+ const storage = createNodeStorage({
20
+ dataDir: options.dataDir,
21
+ ...options.blobDir ? { blobDir: options.blobDir } : {},
22
+ ...options.blobs ? { blobs: options.blobs } : {}
23
+ });
24
+ if (options.mysql) {
25
+ const database = docStore.createDatabase?.("node", { mysql: options.mysql });
26
+ if (!database) throw new Error("mysql requires `docStore: mysqlStore()` from @vultro/docstore-mysql");
27
+ return createSqliteRuntime({
28
+ database,
29
+ schema: options.schema,
30
+ modules: options.modules,
31
+ components: options.components,
32
+ deploymentUrl: options.deploymentUrl,
33
+ prefix: options.prefix,
34
+ storage,
35
+ docStore,
36
+ ...options.mysql ? { mysql: options.mysql } : {},
37
+ scheduler: createTimeoutSchedulerDriver,
38
+ runtime: "node",
39
+ adminToken: options.adminToken,
40
+ trustLocalhost: options.trustLocalhost
41
+ });
42
+ }
43
+ if (options.postgres) {
44
+ const database = docStore.createDatabase?.("node", { postgres: options.postgres });
45
+ if (!database) throw new Error("postgres requires `docStore: pgStore()` from @vultro/docstore-postgres");
46
+ return createSqliteRuntime({
47
+ database,
48
+ schema: options.schema,
49
+ modules: options.modules,
50
+ components: options.components,
51
+ deploymentUrl: options.deploymentUrl,
52
+ prefix: options.prefix,
53
+ storage,
54
+ docStore,
55
+ ...options.postgres ? { postgres: options.postgres } : {},
56
+ scheduler: createTimeoutSchedulerDriver,
57
+ runtime: "node",
58
+ adminToken: options.adminToken,
59
+ trustLocalhost: options.trustLocalhost
60
+ });
61
+ }
62
+ const databasePath = options.database ?? join(options.dataDir ?? ".vultro", "data.sqlite");
63
+ mkdirSync(dirname(databasePath), { recursive: true });
64
+ const sql = createNodeSql(databasePath);
65
+ return createSqliteRuntime({
66
+ database: createBunSqlDatabase(sql),
67
+ schema: options.schema,
68
+ modules: options.modules,
69
+ components: options.components,
70
+ deploymentUrl: options.deploymentUrl,
71
+ prefix: options.prefix,
72
+ storage,
73
+ docStore,
74
+ scheduler: createTimeoutSchedulerDriver,
75
+ runtime: "node",
76
+ adminToken: options.adminToken,
77
+ trustLocalhost: options.trustLocalhost,
78
+ closeDatabase: () => sql.close()
79
+ });
80
+ }
81
+ export { createNodeRuntime };
@@ -0,0 +1,27 @@
1
+ import { createServer } from "node:http";
2
+ import type { NodeRuntime } from "./runtime.js";
3
+ /**
4
+ * Node HTTP / WebSocket 外壳。
5
+ *
6
+ * 与 Bun 版保持一致:`runtime.handle(request, { local })` 处理 HTTP API,
7
+ * `runtime.sync` 处理 `/api/<version>/sync` 的 WebSocket。页面静态资源由
8
+ * 构建产物 `dist/client` 提供(构建入口会把 staticDir 指过去)。
9
+ */
10
+ /** `createNodeServer` 的选项。 */
11
+ export interface NodeServerOptions {
12
+ /** TCP 端口;与 `unix` 二选一。 */
13
+ port?: number;
14
+ /** 监听地址,默认 `0.0.0.0`。 */
15
+ hostname?: string;
16
+ /** Unix socket 路径;dev 模式与 Vite 共用端口时使用。 */
17
+ unix?: string;
18
+ /** 静态资源目录(构建产物 dist/client);不传则只提供 API。 */
19
+ staticDir?: string;
20
+ }
21
+ /** 一个已启动的 Node 服务器。 */
22
+ export interface NodeServer {
23
+ server: ReturnType<typeof createServer>;
24
+ close(): Promise<void>;
25
+ }
26
+ /** 创建并启动 Node 服务器。 */
27
+ export declare function createNodeServer(runtime: NodeRuntime, options?: NodeServerOptions): Promise<NodeServer>;
package/dist/server.js ADDED
@@ -0,0 +1,155 @@
1
+ import { createReadStream, existsSync, statSync } from "node:fs";
2
+ import { createServer } from "node:http";
3
+ import { extname, join, resolve } from "node:path";
4
+ import { Readable } from "node:stream";
5
+ import { pipeline } from "node:stream/promises";
6
+ import { WebSocketServer } from "ws";
7
+ // src/server.ts
8
+ /** 创建并启动 Node 服务器。 */
9
+ async function createNodeServer(runtime, options = {}) {
10
+ const server = createServer((request, response) => {
11
+ handleHttp(runtime, options, request, response);
12
+ });
13
+ const webSockets = attachWebSockets(server, runtime);
14
+ await new Promise((resolveListen, rejectListen) => {
15
+ server.once("error", rejectListen);
16
+ if (options.unix) server.listen(options.unix, () => resolveListen());
17
+ else server.listen(options.port ?? 3e3, options.hostname ?? "0.0.0.0", () => resolveListen());
18
+ });
19
+ return {
20
+ server,
21
+ async close() {
22
+ webSockets.close();
23
+ await new Promise((resolveClose) => server.close(() => resolveClose()));
24
+ await runtime.close();
25
+ }
26
+ };
27
+ }
28
+ /** 处理普通 HTTP 请求:先交给运行时,再回退到静态资源。 */
29
+ async function handleHttp(runtime, options, request, response) {
30
+ try {
31
+ const fetchRequest = toFetchRequest(request, runtime.prefix);
32
+ if (!fetchRequest) {
33
+ if (options.staticDir && await serveStatic(request, response, options.staticDir)) return;
34
+ response.statusCode = 404;
35
+ response.end("Not found");
36
+ return;
37
+ }
38
+ const result = await runtime.handle(fetchRequest, { local: isLocalRequest(request) });
39
+ if (result.status === 404 && options.staticDir) {
40
+ if (await serveStatic(request, response, options.staticDir)) return;
41
+ }
42
+ response.statusCode = result.status;
43
+ result.headers.forEach((value, key) => response.setHeader(key, value));
44
+ if (!result.body) {
45
+ response.end();
46
+ return;
47
+ }
48
+ await pipeline(Readable.fromWeb(result.body), response);
49
+ } catch (error) {
50
+ if (!response.headersSent) {
51
+ response.statusCode = 500;
52
+ response.setHeader("content-type", "text/plain; charset=utf-8");
53
+ }
54
+ response.end(`Vultro node runtime error: ${error instanceof Error ? error.message : String(error)}`);
55
+ }
56
+ }
57
+ /** 把 Node WebSocket 升级请求交给 `SyncEngine`。 */
58
+ function attachWebSockets(server, runtime) {
59
+ const webSockets = new WebSocketServer({ noServer: true });
60
+ server.on("upgrade", (request, socket, head) => {
61
+ if (!new URL(request.url ?? "/", `http://${request.headers.host ?? "localhost"}`).pathname.endsWith("/sync")) {
62
+ socket.destroy();
63
+ return;
64
+ }
65
+ webSockets.handleUpgrade(request, socket, head, (ws) => {
66
+ const connection = runtime.sync.attach({
67
+ send: (data) => ws.send(data),
68
+ close: (code, reason) => ws.close(code, reason)
69
+ }, { local: isLocalRequest(request) });
70
+ ws.on("message", (data) => {
71
+ runtime.sync.receive(connection, data.toString());
72
+ });
73
+ ws.on("close", () => runtime.sync.detach(connection));
74
+ ws.on("error", () => runtime.sync.detach(connection));
75
+ });
76
+ });
77
+ return webSockets;
78
+ }
79
+ /** Node 请求 → Web 标准 Request。 */
80
+ function toFetchRequest(request, prefix) {
81
+ const url = new URL(request.url ?? "/", `http://${request.headers.host ?? "localhost"}`);
82
+ if (prefix) {
83
+ if (url.pathname !== prefix && !url.pathname.startsWith(`${prefix}/`)) return null;
84
+ url.pathname = url.pathname.slice(prefix.length) || "/";
85
+ }
86
+ const method = request.method ?? "GET";
87
+ const headers = new Headers();
88
+ for (const [key, value] of Object.entries(request.headers)) if (Array.isArray(value)) for (const item of value) headers.append(key, item);
89
+ else if (value !== void 0) headers.set(key, value);
90
+ const init = {
91
+ method,
92
+ headers
93
+ };
94
+ if (method !== "GET" && method !== "HEAD") {
95
+ init.body = Readable.toWeb(request);
96
+ init.duplex = "half";
97
+ }
98
+ return new Request(url, init);
99
+ }
100
+ /** 判断请求是否来自本机(与 Bun handler 的转发头规则一致)。 */
101
+ function isLocalRequest(request) {
102
+ if (request.headers["x-forwarded-for"] || request.headers["x-real-ip"] || request.headers.forwarded) return false;
103
+ const address = request.socket.remoteAddress ?? "";
104
+ if (!address) return true;
105
+ const normalized = address.replace(/^::ffff:/, "");
106
+ return normalized === "127.0.0.1" || normalized === "::1" || normalized === "localhost";
107
+ }
108
+ /** 静态文件 / SPA 回退;返回 false 表示没有命中。 */
109
+ async function serveStatic(request, response, staticDir) {
110
+ if (request.method !== "GET" && request.method !== "HEAD") return false;
111
+ const pathname = decodeURIComponent(new URL(request.url ?? "/", "http://localhost").pathname);
112
+ const relativePath = pathname === "/" ? "index.html" : pathname.replace(/^\/+/, "");
113
+ if (relativePath.includes("..")) return false;
114
+ const filePath = resolve(staticDir, relativePath);
115
+ if (isFile(filePath)) {
116
+ response.statusCode = 200;
117
+ response.setHeader("content-type", contentTypeOf(filePath));
118
+ if (request.method === "HEAD") response.end();
119
+ else await pipeline(createReadStream(filePath), response);
120
+ return true;
121
+ }
122
+ const indexFile = join(staticDir, "index.html");
123
+ if (!isFile(indexFile)) return false;
124
+ response.statusCode = 200;
125
+ response.setHeader("content-type", "text/html; charset=utf-8");
126
+ if (request.method === "HEAD") response.end();
127
+ else await pipeline(createReadStream(indexFile), response);
128
+ return true;
129
+ }
130
+ function isFile(path) {
131
+ try {
132
+ return existsSync(path) && statSync(path).isFile();
133
+ } catch {
134
+ return false;
135
+ }
136
+ }
137
+ /** 最小 MIME 表;覆盖 Vite 常见产物即可。 */
138
+ function contentTypeOf(filePath) {
139
+ switch (extname(filePath)) {
140
+ case ".html": return "text/html; charset=utf-8";
141
+ case ".js":
142
+ case ".mjs": return "text/javascript; charset=utf-8";
143
+ case ".css": return "text/css; charset=utf-8";
144
+ case ".json": return "application/json; charset=utf-8";
145
+ case ".svg": return "image/svg+xml";
146
+ case ".png": return "image/png";
147
+ case ".jpg":
148
+ case ".jpeg": return "image/jpeg";
149
+ case ".webp": return "image/webp";
150
+ case ".ico": return "image/x-icon";
151
+ case ".woff2": return "font/woff2";
152
+ default: return "application/octet-stream";
153
+ }
154
+ }
155
+ export { createNodeServer };
package/dist/sql.d.ts ADDED
@@ -0,0 +1,18 @@
1
+ /**
2
+ * `node:sqlite` → `@vultro/runtime-bun` 的 `BunSqlLike` 适配器。
3
+ *
4
+ * 内核的异步存储路径(`AsyncCachedDocumentStore` + `D1AsyncTransaction`)只依赖
5
+ * `unsafe(sql, params)` 这一个方法,所以 Node 运行时可以完全复用 Bun 适配层,
6
+ * 只需要把底层驱动从 `Bun.SQL` 换成 Node 内置的 `node:sqlite`。
7
+ */
8
+ export interface NodeSql {
9
+ unsafe(sql: string, params?: unknown[]): Promise<unknown>;
10
+ close(): Promise<void>;
11
+ }
12
+ /**
13
+ * 打开一个 SQLite 文件并返回最小异步接口。
14
+ *
15
+ * 判断读 / 写语句:`node:sqlite` 的 `StatementSync.columns()` 对 SELECT 返回
16
+ * 列信息,对 INSERT / UPDATE / DDL 返回空数组;读走 `all()`,写走 `run()`。
17
+ */
18
+ export declare function createNodeSql(databasePath: string): NodeSql;
package/dist/sql.js ADDED
@@ -0,0 +1,25 @@
1
+ import { mkdirSync } from "node:fs";
2
+ import { dirname } from "node:path";
3
+ import { DatabaseSync } from "node:sqlite";
4
+ // src/sql.ts
5
+ /**
6
+ * 打开一个 SQLite 文件并返回最小异步接口。
7
+ *
8
+ * 判断读 / 写语句:`node:sqlite` 的 `StatementSync.columns()` 对 SELECT 返回
9
+ * 列信息,对 INSERT / UPDATE / DDL 返回空数组;读走 `all()`,写走 `run()`。
10
+ */
11
+ function createNodeSql(databasePath) {
12
+ mkdirSync(dirname(databasePath), { recursive: true });
13
+ const database = new DatabaseSync(databasePath);
14
+ return {
15
+ async unsafe(sql, params = []) {
16
+ const statement = database.prepare(sql);
17
+ if (statement.columns().length > 0) return statement.all(...params);
18
+ return statement.run(...params);
19
+ },
20
+ async close() {
21
+ database.close();
22
+ }
23
+ };
24
+ }
25
+ export { createNodeSql };
@@ -0,0 +1,25 @@
1
+ import type { BlobStore, StorageFactory } from "@vultro/core/storage";
2
+ /**
3
+ * ============================================================================
4
+ * Node 默认 Storage
5
+ * ============================================================================
6
+ *
7
+ * Node 运行时的 `ctx.storage` 默认组合:
8
+ *
9
+ * - 元数据:`node:sqlite` 打开的原生 SQLite(Runtime 通过 `StorageContext.d1`
10
+ * 传入);
11
+ * - 字节:`<dataDir>/blobs` 本地文件夹。
12
+ *
13
+ * 与 Bun 版语义完全一致;差异只在 SQLite 驱动,因此共享
14
+ * `@vultro/storage-local` 的组合逻辑。
15
+ */
16
+ export interface NodeStorageOptions {
17
+ /** 数据目录,默认 `.vultro`。 */
18
+ dataDir?: string;
19
+ /** 本地字节目录;默认 `<dataDir>/blobs`。 */
20
+ blobDir?: string;
21
+ /** `"none"` 关闭本地文件夹;或传自定义 BlobStore。 */
22
+ blobs?: "none" | BlobStore;
23
+ }
24
+ /** 创建 Node 运行时的默认 Storage 工厂。 */
25
+ export declare function createNodeStorage(options?: NodeStorageOptions): StorageFactory;
@@ -0,0 +1,10 @@
1
+ import { createLocalStorage } from "@vultro/storage-local";
2
+ // src/storage.ts
3
+ /** 创建 Node 运行时的默认 Storage 工厂。 */
4
+ function createNodeStorage(options = {}) {
5
+ return createLocalStorage({
6
+ root: options.blobDir ?? `${options.dataDir ?? ".vultro"}/blobs`,
7
+ ...options.blobs ? { blobs: options.blobs } : {}
8
+ });
9
+ }
10
+ export { createNodeStorage };
package/package.json CHANGED
@@ -1,6 +1,24 @@
1
1
  {
2
2
  "name": "@vultro/runtime-node",
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": "Node runtime adapter for @vultro/core (node:sqlite + node:http + ws)",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./dist/index.d.ts",
9
+ "import": "./dist/index.js",
10
+ "default": "./dist/index.js"
11
+ }
12
+ },
13
+ "dependencies": {
14
+ "@vultro/runtime-bun": "0.0.2",
15
+ "@vultro/core": "0.0.2",
16
+ "@vultro/docstore-sqlite": "0.0.2",
17
+ "@vultro/storage-local": "0.0.2",
18
+ "ws": "^8.23.1"
19
+ },
20
+ "publishConfig": {
21
+ "access": "public"
22
+ },
23
+ "types": "./dist/index.d.ts"
24
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
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.