@vultro/test 0.0.0-stage → 0.0.1

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,121 @@
1
- # Temporary Holding Version
1
+ # @vultro/test
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` 的内存测试后端,API 设计参考 `@concavejs/test` 的
4
+ `createTestConcave`,但**不依赖任何 `@concavejs/*` 包**。
5
+
6
+ - 使用 `bun:sqlite` 内存数据库;
7
+ - 直接运行生产代码里的 `Runtime`、事务、查询引擎和 schema 校验;
8
+ - 不需要启动 server / workerd / Cloudflare;
9
+ - 适合 `bun test`、TDD 和函数级单元测试。
10
+
11
+ ## 快速开始
12
+
13
+ ```ts
14
+ import { describe, expect, test } from "bun:test";
15
+ import { createTestBackend } from "@vultro/test";
16
+ import { api } from "../convex/_generated/api";
17
+ import * as messages from "../convex/messages";
18
+ import schema from "../convex/schema";
19
+
20
+ describe("messages", () => {
21
+ test("send and list", async () => {
22
+ const t = createTestBackend({
23
+ modules: {
24
+ "messages.ts": messages,
25
+ "schema.ts": schema,
26
+ },
27
+ });
28
+
29
+ try {
30
+ await t.mutation(api.messages.send, { body: "hi" });
31
+ expect(await t.query(api.messages.list)).toHaveLength(1);
32
+ } finally {
33
+ await t.close();
34
+ }
35
+ });
36
+ });
37
+ ```
38
+
39
+ ## API
40
+
41
+ ### `createTestBackend(options)`
42
+
43
+ ```ts
44
+ const t = createTestBackend({
45
+ modules: Record<string, unknown>;
46
+ schema?: unknown;
47
+ identity?: TestIdentity;
48
+ onCommit?: (version: number) => void;
49
+ });
50
+ ```
51
+
52
+ - `modules`:与生产一致,key 可以是 `"messages.ts"`、`"../convex/messages.ts"`
53
+ 或 `"messages"`;
54
+ - `schema`:可选;不传时会自动从模块中查找 `schema.ts` / `schema`;
55
+ - `identity`:默认测试身份;
56
+ - `onCommit`:每次提交后的回调,用于断言版本号。
57
+
58
+ ### 运行函数
59
+
60
+ ```ts
61
+ await t.query(api.messages.list);
62
+ await t.mutation("messages:send", { body: "string path works too" });
63
+ await t.action(api.emails.send, { to: "ada@example.com" });
64
+ ```
65
+
66
+ 测试调用者受信,可以直接调用 `internalQuery` / `internalMutation` /
67
+ `internalAction`。
68
+
69
+ ### `t.run(handler)`
70
+
71
+ 在真实写事务里执行任意 handler:
72
+
73
+ ```ts
74
+ const id = await t.run(async (ctx) => {
75
+ return ctx.db.insert("messages", { body: "seeded" });
76
+ });
77
+ ```
78
+
79
+ 正常返回会提交;抛错会回滚整个事务。
80
+
81
+ ### `t.withIdentity(identity)`
82
+
83
+ 返回同一后端、不同身份的视图:
84
+
85
+ ```ts
86
+ const asAda = t.withIdentity({ subject: "ada", email: "ada@example.com" });
87
+ const identity = await asAda.query(api.users.me);
88
+ ```
89
+
90
+ 缺省字段会自动补全:
91
+
92
+ - `issuer`:`https://vultro-test.example`
93
+ - `subject`:`test-user-N`
94
+ - `tokenIdentifier`:`${issuer}|${subject}`
95
+
96
+ ### `t.close()`
97
+
98
+ 关闭内存数据库;每个测试结束都应调用,可重复调用。
99
+
100
+ ### 高级访问
101
+
102
+ - `t.runtime`:底层 `Runtime`;
103
+ - `t.db`:底层 `bun:sqlite` Database。
104
+
105
+ 普通测试优先使用 `query` / `mutation` / `action` / `run` / `withIdentity`。
106
+
107
+ ## 限制
108
+
109
+ 当前 `@vultro/core` 尚未实现以下能力,因此测试包也不提供:
110
+
111
+ - `ctx.scheduler`(计划任务)
112
+ - `ctx.storage`(文件存储)
113
+ - `httpRouter` / `httpAction` 的路由层
114
+
115
+ HTTP + WebSocket 的完整链路请使用 `apps/play/scripts/e2e.ts` 里的官方
116
+ Convex 客户端 E2E。
117
+
118
+ ## 为什么不是 `@concavejs/test`
119
+
120
+ 本项目要求 **0 依赖 `@concavejs/*`**。`@vultro/test` 复用我们自己的
121
+ `@vultro/core`,因此测试覆盖的是实际会部署的代码路径,而不是另一个模拟实现。
@@ -0,0 +1,12 @@
1
+ /**
2
+ * 测试环境的 Bun WASM 兼容层。
3
+ *
4
+ * `bun test` 直接由 Bun 加载源码,不经过 Vite;有些包(Convex Auth 依赖的
5
+ * `password-hash-wasm`)会 `import wasm from "./xxx_bg.wasm"`,Bun 把它解析
6
+ * 成绝对路径字符串,库随后 `fetch(path)` 会失败。这里把本地 `.wasm` 路径
7
+ * 交给 `Bun.file()` 读取,返回标准 `Response`。
8
+ *
9
+ * `createTestBackend()` 会自动调用它;单独使用 Runtime 的测试可以手动调用。
10
+ */
11
+ /** 幂等安装兼容层;多次调用只包一层 fetch。 */
12
+ export declare function installBunWasmFetch(): void;
@@ -0,0 +1,36 @@
1
+ // src/bun-wasm.ts
2
+ /**
3
+ * 测试环境的 Bun WASM 兼容层。
4
+ *
5
+ * `bun test` 直接由 Bun 加载源码,不经过 Vite;有些包(Convex Auth 依赖的
6
+ * `password-hash-wasm`)会 `import wasm from "./xxx_bg.wasm"`,Bun 把它解析
7
+ * 成绝对路径字符串,库随后 `fetch(path)` 会失败。这里把本地 `.wasm` 路径
8
+ * 交给 `Bun.file()` 读取,返回标准 `Response`。
9
+ *
10
+ * `createTestBackend()` 会自动调用它;单独使用 Runtime 的测试可以手动调用。
11
+ */
12
+ var installed = false;
13
+ /** 幂等安装兼容层;多次调用只包一层 fetch。 */
14
+ function installBunWasmFetch() {
15
+ if (installed) return;
16
+ if (typeof Bun === "undefined" || typeof globalThis.fetch !== "function") return;
17
+ installed = true;
18
+ const originalFetch = globalThis.fetch;
19
+ const wrappedFetch = (async (input, init) => {
20
+ const target = typeof input === "string" ? input : input instanceof URL ? input.href : void 0;
21
+ if (target && target.endsWith(".wasm") && (target.startsWith("file:") || target.startsWith("/"))) {
22
+ const file = Bun.file(target);
23
+ if (await file.exists()) return new Response(file);
24
+ }
25
+ return await originalFetch(input, init);
26
+ });
27
+ for (const key of Object.getOwnPropertyNames(originalFetch)) {
28
+ const descriptor = Object.getOwnPropertyDescriptor(originalFetch, key);
29
+ if (!descriptor) continue;
30
+ try {
31
+ Object.defineProperty(wrappedFetch, key, descriptor);
32
+ } catch {}
33
+ }
34
+ globalThis.fetch = wrappedFetch;
35
+ }
36
+ export { installBunWasmFetch };
@@ -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,100 @@
1
+ import { Database } from "bun:sqlite";
2
+ import { Runtime, type ComponentDefinitionInput, type RunResult, type QueryResult } from "@vultro/core";
3
+ import "@vultro/docstore-sqlite/runtime";
4
+ import { installBunWasmFetch } from "./bun-wasm.js";
5
+ /**
6
+ * ============================================================================
7
+ * @vultro/test
8
+ * ============================================================================
9
+ *
10
+ * 一个与 `@concavejs/test` 类似思路、但完全基于 `@vultro/core` 的测试包:
11
+ * - 使用 `bun:sqlite` 的内存数据库,不启动 server / workerd;
12
+ * - 直接复用生产代码的 DocumentStore、Transaction、QueryBuilder、Runtime;
13
+ * - 支持 query / mutation / action、internal 函数、`t.run()`、身份注入;
14
+ * - 每次 `createTestBackend()` 都是完全隔离的后端。
15
+ *
16
+ * 典型用法:
17
+ *
18
+ * ```ts
19
+ * import { describe, expect, test } from "bun:test";
20
+ * import { createTestBackend } from "@vultro/test";
21
+ * import { api } from "../convex/_generated/api";
22
+ * import * as messages from "../convex/messages";
23
+ *
24
+ * describe("messages", () => {
25
+ * test("send and list", async () => {
26
+ * const t = createTestBackend({ modules: { "messages.ts": messages } });
27
+ * try {
28
+ * await t.mutation(api.messages.send, { body: "hi" });
29
+ * expect(await t.query(api.messages.list)).toHaveLength(1);
30
+ * } finally {
31
+ * await t.close();
32
+ * }
33
+ * });
34
+ * });
35
+ * ```
36
+ */
37
+ export interface TestIdentity {
38
+ /** 默认 `test-user-N`。 */
39
+ subject?: string;
40
+ /** 默认 `https://vultro-test.example`。 */
41
+ issuer?: string;
42
+ /** 默认 `${issuer}|${subject}`。 */
43
+ tokenIdentifier?: string;
44
+ /** 其它任意 claims(email、name 等)。 */
45
+ [claim: string]: unknown;
46
+ }
47
+ export interface CreateTestBackendOptions {
48
+ /** 与生产一致:`{ "messages.ts": messages, "schema.ts": schema }`。 */
49
+ modules: Record<string, unknown>;
50
+ /**
51
+ * 可选 schema;不传时会自动从模块映射中寻找 `schema.ts` / `schema`。
52
+ */
53
+ schema?: unknown;
54
+ /** 默认身份;也可以用 `t.withIdentity()` 覆盖。 */
55
+ identity?: TestIdentity;
56
+ /** 每次提交后的回调,方便断言版本号。 */
57
+ onCommit?: (version: number) => void;
58
+ /** 挂载的 Convex components。 */
59
+ components?: Record<string, ComponentDefinitionInput>;
60
+ }
61
+ export interface TestBackend {
62
+ /** 执行 query;可以调用 internal query(测试调用者受信)。 */
63
+ query<T = unknown>(reference: unknown, args?: Record<string, unknown>): Promise<T>;
64
+ /** 执行 mutation;可以调用 internal mutation。 */
65
+ mutation<T = unknown>(reference: unknown, args?: Record<string, unknown>): Promise<T>;
66
+ /** 执行 action;可以调用 internal action。 */
67
+ action<T = unknown>(reference: unknown, args?: Record<string, unknown>): Promise<T>;
68
+ /** 在真实写事务里执行任意 handler;抛错会回滚。 */
69
+ run<T>(handler: (ctx: any) => T | Promise<T>): Promise<T>;
70
+ /** 返回同一后端、不同身份的视图。 */
71
+ withIdentity(identity: TestIdentity): TestBackend;
72
+ /** 关闭内存数据库;可重复调用。 */
73
+ close(): Promise<void>;
74
+ /** 高级用法:直接访问运行时。 */
75
+ readonly runtime: Runtime;
76
+ /** 高级用法:直接访问 bun:sqlite。 */
77
+ readonly db: Database;
78
+ }
79
+ /**
80
+ * 规范化测试身份。
81
+ *
82
+ * 与 Concave 的测试包思路一致:缺省 issuer/subject 会补默认值,
83
+ * `tokenIdentifier` 使用 `issuer|subject` 形式。
84
+ */
85
+ export declare function normalizeTestIdentity(identity?: TestIdentity): TestIdentity;
86
+ /**
87
+ * 创建一个独立的内存后端。
88
+ *
89
+ * 每个 backend 拥有自己的 `bun:sqlite` 内存数据库和 Runtime 实例,
90
+ * 因此测试之间不会互相污染。
91
+ */
92
+ export declare function createTestBackend(options: CreateTestBackendOptions): TestBackend;
93
+ /** `createTestBackend` 的别名,便于按产品名书写。 */
94
+ export declare const createTestVultro: typeof createTestBackend;
95
+ /** `createTestBackend` 的别名,便于从 Concave/Convex 测试迁移。 */
96
+ export declare const createTestRuntime: typeof createTestBackend;
97
+ /** 返回类型别名,方便在测试 helper 中标注。 */
98
+ export type { RunResult, QueryResult };
99
+ export { installBunWasmFetch };
100
+ export { componentsManifestPath, loadComponentsFromManifest, type ComponentManifestEntry, } from "./components.js";
package/dist/index.js ADDED
@@ -0,0 +1,119 @@
1
+ import { Database } from "bun:sqlite";
2
+ import { createRuntimeGraph, getFunctionName, setConsoleLogForwarding } from "@vultro/core";
3
+ import { sqliteStore } from "@vultro/docstore-sqlite";
4
+ import "@vultro/docstore-sqlite/runtime";
5
+ import { installBunWasmFetch } from "./bun-wasm.js";
6
+ import { componentsManifestPath, loadComponentsFromManifest } from "./components.js";
7
+ // src/index.ts
8
+ /** 自增测试身份编号,保证未显式提供 subject 时彼此不同。 */
9
+ var identityCounter = 0;
10
+ /**
11
+ * 规范化测试身份。
12
+ *
13
+ * 与 Concave 的测试包思路一致:缺省 issuer/subject 会补默认值,
14
+ * `tokenIdentifier` 使用 `issuer|subject` 形式。
15
+ */
16
+ function normalizeTestIdentity(identity = {}) {
17
+ const issuer = identity.issuer ?? "https://vultro-test.example";
18
+ const subject = identity.subject ?? `test-user-${++identityCounter}`;
19
+ return {
20
+ ...identity,
21
+ issuer,
22
+ subject,
23
+ tokenIdentifier: identity.tokenIdentifier ?? `${issuer}|${subject}`
24
+ };
25
+ }
26
+ /**
27
+ * 创建一个独立的内存后端。
28
+ *
29
+ * 每个 backend 拥有自己的 `bun:sqlite` 内存数据库和 Runtime 实例,
30
+ * 因此测试之间不会互相污染。
31
+ */
32
+ function createTestBackend(options) {
33
+ setConsoleLogForwarding({}.VULTRO_TEST_LOGS === "1");
34
+ installBunWasmFetch();
35
+ if (!options || typeof options.modules !== "object" || options.modules === null) throw new Error("createTestBackend requires a `modules` object");
36
+ const db = new Database(":memory:");
37
+ const runtime = createRuntimeGraph({
38
+ sql: createSqlExecutor(db),
39
+ schema: extractSchema(options.modules, options.schema),
40
+ modules: options.modules,
41
+ components: options.components,
42
+ docStore: sqliteStore(),
43
+ onCommit: options.onCommit
44
+ });
45
+ let closed = false;
46
+ const baseIdentity = options.identity ? normalizeTestIdentity(options.identity) : void 0;
47
+ const view = (identity) => {
48
+ const assertOpen = () => {
49
+ if (closed) throw new Error("Test backend is closed");
50
+ };
51
+ return {
52
+ async query(reference, args = {}) {
53
+ assertOpen();
54
+ return (await runtime.runQuery(getFunctionName(reference), args, { identity })).result;
55
+ },
56
+ async mutation(reference, args = {}) {
57
+ assertOpen();
58
+ return (await runtime.runMutation(getFunctionName(reference), args, { identity })).result;
59
+ },
60
+ async action(reference, args = {}) {
61
+ assertOpen();
62
+ return (await runtime.runAction(getFunctionName(reference), args, { identity })).result;
63
+ },
64
+ async run(handler) {
65
+ assertOpen();
66
+ return (await runtime.runDirect(handler, { identity })).result;
67
+ },
68
+ withIdentity(next) {
69
+ return view(normalizeTestIdentity(next));
70
+ },
71
+ async close() {
72
+ if (closed) return;
73
+ closed = true;
74
+ db.close();
75
+ },
76
+ runtime,
77
+ db
78
+ };
79
+ };
80
+ return view(baseIdentity);
81
+ }
82
+ /** `createTestBackend` 的别名,便于按产品名书写。 */
83
+ var createTestVultro = createTestBackend;
84
+ /** `createTestBackend` 的别名,便于从 Concave/Convex 测试迁移。 */
85
+ var createTestRuntime = createTestBackend;
86
+ /**
87
+ * 内存 SQLite 适配器。
88
+ *
89
+ * 与 `@vultro/core` 的 SqlExecutor 结构一致;这里不导入 core 的内部类型,
90
+ * 让测试包只依赖公共 API。
91
+ */
92
+ function createSqlExecutor(db) {
93
+ return { exec(sqlText, ...params) {
94
+ const head = sqlText.trimStart().slice(0, 10).toLowerCase();
95
+ if (head.startsWith("select") || head.startsWith("with") || head.startsWith("pragma")) return db.query(sqlText).all(...params);
96
+ db.run(sqlText, ...params);
97
+ return [];
98
+ } };
99
+ }
100
+ /**
101
+ * 从模块映射中提取 schema。
102
+ *
103
+ * 支持:
104
+ * - 显式 `schema` 参数;
105
+ * - `"schema.ts": schema`;
106
+ * - `"schema.ts": { default: schema }`;
107
+ * - `"../convex/schema.ts": schema`。
108
+ */
109
+ function extractSchema(modules, explicit) {
110
+ if (explicit !== void 0) return explicit;
111
+ for (const [key, value] of Object.entries(modules)) {
112
+ const file = key.replaceAll("\\", "/").split("/").pop() ?? "";
113
+ if (file !== "schema" && !/^schema\.(ts|tsx|js|jsx|mjs|mts)$/.test(file)) continue;
114
+ if (typeof value === "function") throw new Error(`Schema module "${key}" is a lazy loader; import it eagerly or pass the \`schema\` option.`);
115
+ if (value && typeof value === "object" && "default" in value) return value.default;
116
+ return value;
117
+ }
118
+ }
119
+ export { componentsManifestPath, createTestBackend, createTestRuntime, createTestVultro, installBunWasmFetch, loadComponentsFromManifest, normalizeTestIdentity };
package/package.json CHANGED
@@ -1,6 +1,21 @@
1
1
  {
2
2
  "name": "@vultro/test",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.1",
4
+ "type": "module",
5
+ "description": "In-memory bun:test harness for @vultro/core",
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/core": "0.0.1",
15
+ "@vultro/docstore-sqlite": "0.0.1"
16
+ },
17
+ "publishConfig": {
18
+ "access": "public"
19
+ },
20
+ "types": "./dist/index.d.ts"
21
+ }