create-cellsweb-rpc-api 1.0.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.
@@ -0,0 +1,265 @@
1
+ import { describe, it, expect, beforeAll, afterAll } from "vitest";
2
+ import http from "node:http";
3
+ import fs from "node:fs";
4
+ import path from "node:path";
5
+ import os from "node:os";
6
+ import { buildRegistry } from "./src/registry";
7
+ import { createRequestHandler } from "./src/server";
8
+
9
+ describe("CellsWeb RPC API Suite", () => {
10
+ let server: http.Server;
11
+ let baseUrl: string;
12
+ let tempDir: string;
13
+ let functionsDir: string;
14
+ let middlewaresDir: string;
15
+
16
+ beforeAll(async () => {
17
+ tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "rpc-test-"));
18
+ functionsDir = path.join(tempDir, "functions");
19
+ middlewaresDir = path.join(tempDir, "middlewares");
20
+
21
+ fs.mkdirSync(functionsDir, { recursive: true });
22
+ fs.mkdirSync(middlewaresDir, { recursive: true });
23
+
24
+ // ── Create Central Middlewares ──
25
+ const reqHeaderDir = path.join(middlewaresDir, "requireHeader");
26
+ fs.mkdirSync(reqHeaderDir, { recursive: true });
27
+ fs.writeFileSync(
28
+ path.join(reqHeaderDir, "constants.ts"),
29
+ `import { Type } from "@sinclair/typebox";
30
+ export const headersSchema = Type.Object({ "x-test-header": Type.String() });
31
+ export const optionsSchema = Type.Object({ tag: Type.String() });`,
32
+ );
33
+ fs.writeFileSync(
34
+ path.join(reqHeaderDir, "run.ts"),
35
+ `export const run = async ({ headers, options }, context) => {
36
+ if (!headers["x-test-header"]) throw new Error("Header missing");
37
+ return { ...context, testTag: options.tag };
38
+ };`,
39
+ );
40
+
41
+ const rateLimitDir = path.join(middlewaresDir, "rateLimit");
42
+ fs.mkdirSync(rateLimitDir, { recursive: true });
43
+ fs.writeFileSync(
44
+ path.join(rateLimitDir, "constants.ts"),
45
+ `import { Type } from "@sinclair/typebox";
46
+ export const optionsSchema = Type.Object({ windowSeconds: Type.Number(), maxRequests: Type.Number() });`,
47
+ );
48
+ fs.writeFileSync(
49
+ path.join(rateLimitDir, "run.ts"),
50
+ `import { AppError, ErrorCode } from "@/errors";
51
+ let callCount = 0;
52
+ export const run = async ({ options }) => {
53
+ callCount++;
54
+ if (callCount > options.maxRequests) {
55
+ throw new AppError(ErrorCode.RATE_LIMITED, "Rate limited in test");
56
+ }
57
+ };`,
58
+ );
59
+
60
+ // ── Create Functions ──
61
+ // 1. public.echoJson
62
+ const echoDir = path.join(functionsDir, "public", "echoJson");
63
+ fs.mkdirSync(echoDir, { recursive: true });
64
+ fs.writeFileSync(
65
+ path.join(echoDir, "constants.ts"),
66
+ `import { Type } from "@sinclair/typebox";
67
+ export const metadata = { description: "echo", isPublic: true };
68
+ export const contentType = "application/json";
69
+ export const inputSchema = Type.Object({ message: Type.String({ minLength: 2 }) });
70
+ export const outputSchema = Type.Object({ reply: Type.String() });`,
71
+ );
72
+ fs.writeFileSync(
73
+ path.join(echoDir, "run.ts"),
74
+ `export const run = async (input, context) => ({ reply: input.message + "_" + (context.testTag || "none") });`,
75
+ );
76
+ fs.writeFileSync(
77
+ path.join(echoDir, "middlewares.ts"),
78
+ `import { defineMiddlewares } from "@/registry";
79
+ export const middlewares = defineMiddlewares([
80
+ { name: "requireHeader", options: { tag: "echo-tag" } }
81
+ ]);`,
82
+ );
83
+
84
+ // 2. public.upload
85
+ const uploadDir = path.join(functionsDir, "public", "upload");
86
+ fs.mkdirSync(uploadDir, { recursive: true });
87
+ fs.writeFileSync(
88
+ path.join(uploadDir, "constants.ts"),
89
+ `import { Type } from "@sinclair/typebox";
90
+ import { File } from "@/utils/typebox";
91
+ export const metadata = { description: "upload", isPublic: true };
92
+ export const contentType = "multipart/form-data";
93
+ export const inputSchema = Type.Object({ title: Type.String(), file: File() });
94
+ export const outputSchema = Type.Object({ title: Type.String(), filename: Type.String() });`,
95
+ );
96
+ fs.writeFileSync(
97
+ path.join(uploadDir, "run.ts"),
98
+ `export const run = async (input) => ({ title: input.title, filename: input.file.filename });`,
99
+ );
100
+
101
+ // 3. public.badOutput
102
+ const badOutDir = path.join(functionsDir, "public", "badOutput");
103
+ fs.mkdirSync(badOutDir, { recursive: true });
104
+ fs.writeFileSync(
105
+ path.join(badOutDir, "constants.ts"),
106
+ `import { Type } from "@sinclair/typebox";
107
+ export const metadata = { description: "bad output", isPublic: true };
108
+ export const contentType = "application/json";
109
+ export const inputSchema = Type.Object({});
110
+ export const outputSchema = Type.Object({ num: Type.Number() });`,
111
+ );
112
+ fs.writeFileSync(
113
+ path.join(badOutDir, "run.ts"),
114
+ `export const run = async () => ({ num: "not-a-number" });`,
115
+ );
116
+
117
+ // 4. public.rateLimitedFn
118
+ const rlFnDir = path.join(functionsDir, "public", "rateLimitedFn");
119
+ fs.mkdirSync(rlFnDir, { recursive: true });
120
+ fs.writeFileSync(
121
+ path.join(rlFnDir, "constants.ts"),
122
+ `import { Type } from "@sinclair/typebox";
123
+ export const metadata = { description: "rl", isPublic: true };
124
+ export const contentType = "application/json";
125
+ export const inputSchema = Type.Object({});
126
+ export const outputSchema = Type.Object({ ok: Type.Boolean() });`,
127
+ );
128
+ fs.writeFileSync(
129
+ path.join(rlFnDir, "run.ts"),
130
+ `export const run = async () => ({ ok: true });`,
131
+ );
132
+ fs.writeFileSync(
133
+ path.join(rlFnDir, "middlewares.ts"),
134
+ `import { defineMiddlewares } from "@/registry";
135
+ export const middlewares = defineMiddlewares([
136
+ { name: "rateLimit", options: { windowSeconds: 60, maxRequests: 1 } }
137
+ ]);`,
138
+ );
139
+
140
+ await buildRegistry(functionsDir);
141
+
142
+ const handler = createRequestHandler();
143
+ server = http.createServer(handler);
144
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
145
+ const addr = server.address() as any;
146
+ baseUrl = `http://127.0.0.1:${addr.port}`;
147
+ });
148
+
149
+ afterAll(async () => {
150
+ await new Promise<void>((resolve) => server.close(() => resolve()));
151
+ fs.rmSync(tempDir, { recursive: true, force: true });
152
+ });
153
+
154
+ it("1. JSON function succeeds with correct headers and schema", async () => {
155
+ const res = await fetch(`${baseUrl}/api`, {
156
+ method: "POST",
157
+ headers: {
158
+ "content-type": "application/json",
159
+ "x-test-header": "valid",
160
+ },
161
+ body: JSON.stringify({
162
+ namespace: "public",
163
+ functionName: "echoJson",
164
+ data: { message: "hello" },
165
+ }),
166
+ });
167
+ const json = await res.json();
168
+ expect(json.status).toBe("ok");
169
+ expect(json.data.reply).toBe("hello_echo-tag");
170
+ });
171
+
172
+ it("2. JSON function rejects invalid input schema", async () => {
173
+ const res = await fetch(`${baseUrl}/api`, {
174
+ method: "POST",
175
+ headers: {
176
+ "content-type": "application/json",
177
+ "x-test-header": "valid",
178
+ },
179
+ body: JSON.stringify({
180
+ namespace: "public",
181
+ functionName: "echoJson",
182
+ data: { message: "a" },
183
+ }),
184
+ });
185
+ const json = await res.json();
186
+ expect(json.status).toBe("error");
187
+ expect(json.code).toBe("validation_error");
188
+ });
189
+
190
+ it("3. Multipart function succeeds and receives files under data", async () => {
191
+ const form = new FormData();
192
+ form.append("namespace", "public");
193
+ form.append("functionName", "upload");
194
+ form.append("title", "AvatarImage");
195
+ form.append("file", new Blob(["file-content"], { type: "text/plain" }), "avatar.txt");
196
+
197
+ const res = await fetch(`${baseUrl}/api`, {
198
+ method: "POST",
199
+ body: form,
200
+ });
201
+ const json = await res.json();
202
+ expect(json.status).toBe("ok");
203
+ expect(json.data.title).toBe("AvatarImage");
204
+ expect(json.data.filename).toBe("avatar.txt");
205
+ });
206
+
207
+ it("4. Multipart request to JSON function returns invalid_content_type", async () => {
208
+ const form = new FormData();
209
+ form.append("namespace", "public");
210
+ form.append("functionName", "echoJson");
211
+
212
+ const res = await fetch(`${baseUrl}/api`, {
213
+ method: "POST",
214
+ body: form,
215
+ });
216
+ const json = await res.json();
217
+ expect(json.status).toBe("error");
218
+ expect(json.code).toBe("invalid_content_type");
219
+ });
220
+
221
+ it("5. JSON request to multipart function returns invalid_content_type", async () => {
222
+ const res = await fetch(`${baseUrl}/api`, {
223
+ method: "POST",
224
+ headers: { "content-type": "application/json" },
225
+ body: JSON.stringify({
226
+ namespace: "public",
227
+ functionName: "upload",
228
+ data: {},
229
+ }),
230
+ });
231
+ const json = await res.json();
232
+ expect(json.status).toBe("error");
233
+ expect(json.code).toBe("invalid_content_type");
234
+ });
235
+
236
+ it("6. Rate limit options in middlewares.ts are enforced", async () => {
237
+ const res1 = await fetch(`${baseUrl}/api`, {
238
+ method: "POST",
239
+ headers: { "content-type": "application/json" },
240
+ body: JSON.stringify({ namespace: "public", functionName: "rateLimitedFn" }),
241
+ });
242
+ const json1 = await res1.json();
243
+ expect(json1.status).toBe("ok");
244
+
245
+ const res2 = await fetch(`${baseUrl}/api`, {
246
+ method: "POST",
247
+ headers: { "content-type": "application/json" },
248
+ body: JSON.stringify({ namespace: "public", functionName: "rateLimitedFn" }),
249
+ });
250
+ const json2 = await res2.json();
251
+ expect(json2.status).toBe("error");
252
+ expect(json2.code).toBe("rate_limited");
253
+ });
254
+
255
+ it("7. Output schema mismatch returns schema_mismatch", async () => {
256
+ const res = await fetch(`${baseUrl}/api`, {
257
+ method: "POST",
258
+ headers: { "content-type": "application/json" },
259
+ body: JSON.stringify({ namespace: "public", functionName: "badOutput" }),
260
+ });
261
+ const json = await res.json();
262
+ expect(json.status).toBe("error");
263
+ expect(json.code).toBe("schema_mismatch");
264
+ });
265
+ });
@@ -0,0 +1,14 @@
1
+ import { defineConfig } from "vitest/config";
2
+ import path from "node:path";
3
+
4
+ export default defineConfig({
5
+ test: {
6
+ include: ["test.ts", "src/**/test.ts", "**/*.test.ts", "**/*.spec.ts"],
7
+ globals: true,
8
+ },
9
+ resolve: {
10
+ alias: {
11
+ "@": path.resolve(__dirname, "./src"),
12
+ },
13
+ },
14
+ });