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.
package/README.md ADDED
@@ -0,0 +1,33 @@
1
+ # `create-cellsweb-rpc-api`
2
+
3
+ > Official CLI scaffolder for **CellsWeb RPC API** service projects.
4
+
5
+ ---
6
+
7
+ ## Usage
8
+
9
+ ```bash
10
+ # Using npm
11
+ npm create cellsweb-rpc-api@latest my-app
12
+
13
+ # Using npx
14
+ npx create-cellsweb-rpc-api@latest my-app
15
+
16
+ # Using pnpm
17
+ pnpm create cellsweb-rpc-api@latest my-app
18
+ ```
19
+
20
+ ---
21
+
22
+ ## Features
23
+
24
+ - **Pre-wired `@cellsweb/rpc-core`**: High performance $O(1)$ dispatching engine.
25
+ - **Interactive Scaffolding**: Built-in CLI scripts for adding new functions (`pnpm run create:function`) and middlewares (`pnpm run create:middleware`).
26
+ - **Pre-scaffolded Common Middlewares**: Includes `auth` (JWT verification stub) and `rateLimit` (in-memory rate limiting) with rich step-by-step instructions.
27
+ - **Pluggable Extensions**: Modular application-level `env.ts` (TypeBox), `telemetry.ts` (Sentry), and `storage.ts` (Local/S3 uploads).
28
+
29
+ ---
30
+
31
+ ## License
32
+
33
+ MIT © Minhazur Rahman
package/bin/create.js ADDED
@@ -0,0 +1,232 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * create-cellsweb-rpc-api
5
+ * ─────────────────────────────────────────────────────────────────────────────
6
+ * CLI scaffolder — copies the CellsWeb RPC API boilerplate into a target dir.
7
+ *
8
+ * Usage:
9
+ * npm create cellsweb-rpc-api@latest
10
+ * npx create-cellsweb-rpc-api@latest
11
+ */
12
+
13
+ "use strict";
14
+
15
+ const fs = require("fs");
16
+ const path = require("path");
17
+ const { execSync } = require("child_process");
18
+ const readline = require("readline");
19
+
20
+ // ─── Colours ──────────────────────────────────────────────────────────────────
21
+ const c = {
22
+ reset: "\x1b[0m",
23
+ bold: "\x1b[1m",
24
+ dim: "\x1b[2m",
25
+ cyan: "\x1b[36m",
26
+ green: "\x1b[32m",
27
+ yellow: "\x1b[33m",
28
+ red: "\x1b[31m",
29
+ white: "\x1b[37m",
30
+ };
31
+
32
+ const bold = (s) => `${c.bold}${s}${c.reset}`;
33
+ const cyan = (s) => `${c.cyan}${s}${c.reset}`;
34
+ const green = (s) => `${c.green}${s}${c.reset}`;
35
+ const yellow = (s) => `${c.yellow}${s}${c.reset}`;
36
+ const dim = (s) => `${c.dim}${s}${c.reset}`;
37
+
38
+ // ─── Banner ───────────────────────────────────────────────────────────────────
39
+ console.log(`
40
+ ${cyan("╔═══════════════════════════════════════════════════════╗")}
41
+ ${cyan("║")} ${bold("CellsWeb RPC API")} — production-ready boilerplate ${cyan("║")}
42
+ ${cyan("║")} Custom RPC server · TypeBox · pino · Rate limiting ${cyan("║")}
43
+ ${cyan("╚═══════════════════════════════════════════════════════╝")}
44
+ `);
45
+
46
+ // ─── Prompt helper ────────────────────────────────────────────────────────────
47
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
48
+ const ask = (question, defaultVal) =>
49
+ new Promise((resolve) => {
50
+ const hint = defaultVal ? dim(` (${defaultVal})`) : "";
51
+ rl.question(` ${question}${hint}: `, (answer) => {
52
+ resolve(answer.trim() || defaultVal || "");
53
+ });
54
+ });
55
+
56
+ // ─── Copy helper (recursive) ──────────────────────────────────────────────────
57
+ function copyDir(src, dest) {
58
+ fs.mkdirSync(dest, { recursive: true });
59
+ for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
60
+ const srcPath = path.join(src, entry.name);
61
+ const destPath = path.join(dest, entry.name);
62
+ if (entry.isDirectory()) {
63
+ copyDir(srcPath, destPath);
64
+ } else {
65
+ fs.copyFileSync(srcPath, destPath);
66
+ }
67
+ }
68
+ }
69
+
70
+ // ─── Main ─────────────────────────────────────────────────────────────────────
71
+ async function main() {
72
+ // ── 1. Inputs ──────────────────────────────────────────────────────────────
73
+ const targetArg = process.argv[2];
74
+ const isTTY = Boolean(process.stdin.isTTY);
75
+
76
+ let targetDir;
77
+ let projectName;
78
+ let pm;
79
+
80
+ if (targetArg && !isTTY) {
81
+ targetDir = path.resolve(process.cwd(), targetArg);
82
+ projectName = path.basename(targetDir);
83
+ pm = "pnpm";
84
+ rl.close();
85
+ } else {
86
+ targetDir = targetArg
87
+ ? path.resolve(process.cwd(), targetArg)
88
+ : path.resolve(process.cwd(), await ask("Target directory", "./api"));
89
+
90
+ const defaultName = path.basename(targetDir);
91
+ projectName = await ask("Package name", defaultName);
92
+
93
+ const pmAnswer = await ask("Package manager [npm / pnpm / yarn]", "pnpm");
94
+ pm = ["npm", "pnpm", "yarn"].includes(pmAnswer) ? pmAnswer : "pnpm";
95
+ rl.close();
96
+ }
97
+
98
+ // ── 2. Guard ───────────────────────────────────────────────────────────────
99
+ if (fs.existsSync(targetDir) && fs.readdirSync(targetDir).length > 0) {
100
+ console.log(`\n ${yellow("⚠")} ${bold(targetDir)} already exists and is not empty.`);
101
+ console.log(` Files will be merged — existing files will NOT be overwritten.\n`);
102
+ }
103
+
104
+ // ── 3. Copy template ───────────────────────────────────────────────────────
105
+ const templateDir = path.join(__dirname, "..", "template");
106
+ console.log(`\n ${dim("Scaffolding into")} ${cyan(targetDir)} ...\n`);
107
+ copyDir(templateDir, targetDir);
108
+
109
+ // ── 4. Write package.json ──────────────────────────────────────────────────
110
+ const pkg = {
111
+ name: projectName,
112
+ version: "0.1.0",
113
+ type: "module",
114
+ private: true,
115
+ scripts: {
116
+ dev: "tsx watch --clear-screen=false src/server.ts",
117
+ build: "tsc && tsc-alias",
118
+ start: "node dist/server.js",
119
+ typecheck: "tsc --noEmit",
120
+ test: "vitest run test.ts",
121
+ "test:watch": "vitest test test.ts",
122
+ "create:function": "tsx scripts/create-function.ts",
123
+ "create:middleware": "tsx scripts/create-middleware.ts",
124
+ },
125
+ dependencies: {
126
+ "@cellsweb/rpc-core": "^1.0.0",
127
+ "@aws-sdk/client-s3": "^3.700.0",
128
+ "@paralleldrive/cuid2": "^2.2.2",
129
+ "@sentry/node": "^8.40.0",
130
+ "@sinclair/typebox": "^0.34.52",
131
+ "busboy": "^1.6.0",
132
+ "dotenv": "^17.4.2",
133
+ "lru-cache": "^11.1.0",
134
+ "mime-types": "^3.0.2",
135
+ "pino": "^9.7.0",
136
+ "rate-limiter-flexible": "^7.1.0",
137
+ "safe-stable-stringify": "^2.5.0",
138
+ "tinyglobby": "^0.2.12",
139
+ },
140
+ devDependencies: {
141
+ "@clack/prompts": "^1.4.0",
142
+ "@types/busboy": "^1.5.4",
143
+ "@types/mime-types": "^3.0.1",
144
+ "@types/node": "^22.15.18",
145
+ "pino-pretty": "^13.0.0",
146
+ "tsc-alias": "^1.8.17",
147
+ "tsx": "^4.22.0",
148
+ "typescript": "^7.0.2",
149
+ "vitest": "^3.2.4",
150
+ },
151
+ };
152
+ fs.writeFileSync(path.join(targetDir, "package.json"), JSON.stringify(pkg, null, 2) + "\n");
153
+
154
+ // ── 5. Write tsconfig.json ─────────────────────────────────────────────────
155
+ const tsconfig = {
156
+ compilerOptions: {
157
+ outDir: "./dist",
158
+ rootDir: "./src",
159
+ module: "NodeNext",
160
+ moduleResolution: "NodeNext",
161
+ target: "ES2023",
162
+ lib: ["ES2023", "DOM"],
163
+ strict: true,
164
+ esModuleInterop: true,
165
+ skipLibCheck: true,
166
+ resolveJsonModule: true,
167
+ declaration: true,
168
+ declarationMap: true,
169
+ sourceMap: true,
170
+ paths: { "@/*": ["./src/*"] },
171
+ },
172
+ include: ["src/**/*"],
173
+ exclude: ["node_modules", "dist"],
174
+ };
175
+ fs.writeFileSync(path.join(targetDir, "tsconfig.json"), JSON.stringify(tsconfig, null, 2) + "\n");
176
+
177
+ // ── 6. Write scripts/tsconfig.json ────────────────────────────────────────
178
+ const scriptsTsconfig = {
179
+ compilerOptions: {
180
+ target: "ES2022",
181
+ module: "CommonJS",
182
+ moduleResolution: "node",
183
+ lib: ["ES2022"],
184
+ strict: true,
185
+ esModuleInterop: true,
186
+ skipLibCheck: true,
187
+ resolveJsonModule: true,
188
+ noEmit: true,
189
+ paths: { "@/*": ["../src/*"] },
190
+ },
191
+ include: ["./**/*"],
192
+ exclude: ["node_modules"],
193
+ };
194
+ const scriptsDir = path.join(targetDir, "scripts");
195
+ fs.mkdirSync(scriptsDir, { recursive: true });
196
+ fs.writeFileSync(path.join(scriptsDir, "tsconfig.json"), JSON.stringify(scriptsTsconfig, null, 2) + "\n");
197
+
198
+ // ── 7. Write .gitignore ───────────────────────────────────────────────────
199
+ const gitignore = ["node_modules", "dist", ".env", "*.log", ".DS_Store"].join("\n") + "\n";
200
+ const giPath = path.join(targetDir, ".gitignore");
201
+ if (!fs.existsSync(giPath)) fs.writeFileSync(giPath, gitignore);
202
+
203
+ // ── 8. Install ────────────────────────────────────────────────────────────
204
+ console.log(` ${dim("Installing dependencies with")} ${bold(pm)} ...\n`);
205
+ try {
206
+ execSync(`${pm} install`, { cwd: targetDir, stdio: "inherit" });
207
+ } catch {
208
+ console.log(` ${yellow("⚠")} Install failed — run ${bold(`${pm} install`)} manually.\n`);
209
+ }
210
+
211
+ // ── 9. Done ───────────────────────────────────────────────────────────────
212
+ console.log(`
213
+ ${green("✔")} ${bold("Done!")} Your RPC API is ready.
214
+
215
+ ${dim("Next steps:")}
216
+ ${cyan(`cd ${path.relative(process.cwd(), targetDir) || "."}`)}
217
+ ${cyan(`${pm} run dev`)} ${dim("→ start dev server (hot-reload)")}
218
+ ${cyan(`${pm} run create:function`)} ${dim("→ scaffold a new API function")}
219
+ ${cyan(`${pm} run create:middleware`)} ${dim("→ scaffold a new middleware")}
220
+
221
+ ${dim("Add your JWT logic in:")}
222
+ ${cyan("src/middlewares/auth/run.ts")} ${dim("→ verifyToken()")}
223
+
224
+ ${dim("API endpoint:")} POST ${cyan("http://localhost:4000/api")}
225
+ ${dim("Docs:")} GET ${cyan("http://localhost:4000/docs")}
226
+ `);
227
+ }
228
+
229
+ main().catch((err) => {
230
+ console.error(`\n ${c.red}✖${c.reset} ${err.message}\n`);
231
+ process.exit(1);
232
+ });
package/package.json ADDED
@@ -0,0 +1,30 @@
1
+ {
2
+ "name": "create-cellsweb-rpc-api",
3
+ "version": "1.0.0",
4
+ "publishConfig": {
5
+ "access": "public"
6
+ },
7
+ "description": "Scaffold a production-ready CellsWeb RPC API service with @cellsweb/rpc-core",
8
+ "bin": {
9
+ "create-cellsweb-rpc-api": "./bin/create.js"
10
+ },
11
+ "files": [
12
+ "bin",
13
+ "template"
14
+ ],
15
+ "scripts": {
16
+ "test": "echo \"CLI scaffolder test suite\""
17
+ },
18
+ "keywords": [
19
+ "rpc",
20
+ "create-app",
21
+ "scaffolder",
22
+ "boilerplate",
23
+ "cellsweb"
24
+ ],
25
+ "author": "Minhazur Rahman",
26
+ "license": "MIT",
27
+ "dependencies": {
28
+ "@clack/prompts": "^1.7.0"
29
+ }
30
+ }
@@ -0,0 +1,25 @@
1
+ NODE_ENV=development
2
+ API_PORT=4000
3
+ API_HOST=0.0.0.0
4
+ API_REQUEST_TIMEOUT_MS=30000
5
+ API_LOG_LEVEL=info
6
+
7
+ MAX_JSON_BODY_BYTES=1048576
8
+ MAX_MULTIPART_BYTES=25000000
9
+ MAX_UPLOAD_FILE_BYTES=10000000
10
+ # UPLOAD_TMP_DIR=
11
+
12
+ UPLOAD_MODE=local
13
+ UPLOAD_DIR=public/uploads
14
+ SERVER_URL=http://localhost:4000
15
+
16
+ # S3 Upload Mode Credentials (Optional - required only when UPLOAD_MODE=s3)
17
+ # S3_BUCKET=my-bucket
18
+ # S3_REGION=us-east-1
19
+ # S3_ACCESS_KEY=your-access-key
20
+ # S3_SECRET_KEY=your-secret-key
21
+ # S3_ENDPOINT=https://s3.us-east-1.amazonaws.com
22
+
23
+ # Optional Sentry & Telemetry (Only initialized if SENTRY_DSN is provided)
24
+ # SENTRY_DSN=https://examplePublicKey@o0.ingest.sentry.io/0
25
+ TELEMETRY_ENABLED=true
@@ -0,0 +1,116 @@
1
+ # CellsWeb RPC API Service
2
+
3
+ Welcome to your production-ready **CellsWeb RPC API** service!
4
+
5
+ Powered by `@cellsweb/rpc-core` — zero framework overhead, TypeBox schema validation, $O(1)$ in-memory function dispatching, and built-in interactive CLI generators.
6
+
7
+ ---
8
+
9
+ ## Quick Start Commands
10
+
11
+ ```bash
12
+ pnpm run dev # Start dev server with hot-reload (http://localhost:4000)
13
+ pnpm run typecheck # Check TypeScript types
14
+ pnpm test # Run Vitest test suite
15
+ pnpm run create:function # Interactively scaffold a new API function + test
16
+ pnpm run create:middleware # Interactively scaffold a new central middleware + test
17
+ pnpm run build # Compile TypeScript to dist/ for production
18
+ pnpm start # Run compiled server (node dist/server.js)
19
+ ```
20
+
21
+ ---
22
+
23
+ ## Architecture Overview
24
+
25
+ ```txt
26
+ src/
27
+ ├── server.ts — Entrypoint initializing CoreRPC
28
+ ├── env.ts — TypeBox environment configuration
29
+ ├── telemetry.ts — Optional Sentry error tracking hook
30
+ ├── utils/
31
+ │ └── storage.ts — Dual Local & AWS S3 file storage utility
32
+ ├── middlewares/
33
+ │ ├── auth/ — Pre-scaffolded JWT auth stub with instructions
34
+ │ └── rateLimit/ — Pre-scaffolded rate limit stub with instructions
35
+ └── functions/
36
+ └── public/
37
+ └── hello/ — Sample JSON RPC function
38
+ ```
39
+
40
+ ---
41
+
42
+ ## Single API Endpoint (`POST /rpc` or `POST /api`)
43
+
44
+ ### JSON Request Example
45
+ ```json
46
+ {
47
+ "namespace": "public",
48
+ "functionName": "hello",
49
+ "data": {
50
+ "name": "Alice"
51
+ }
52
+ }
53
+ ```
54
+
55
+ ### Multipart Request Example (`Content-Type: multipart/form-data`)
56
+ Pass form-data fields:
57
+ - `namespace`: `"public"`
58
+ - `functionName`: `"uploadAvatar"`
59
+ - `title`: `"My Avatar"`
60
+ - `avatar`: `<file attachment>`
61
+
62
+ ---
63
+
64
+ ## Creating Functions & Middlewares
65
+
66
+ ### Scaffold a New Function
67
+ ```bash
68
+ pnpm run create:function
69
+ ```
70
+
71
+ Generates:
72
+ ```txt
73
+ src/functions/{namespace}/{functionName}/
74
+ ├── constants.ts — Metadata, accepted Content-Type, and TypeBox schemas
75
+ ├── run.ts — Business logic handler
76
+ ├── middlewares.ts — Declarative middleware pipeline ({ name, options })
77
+ └── test.ts — Vitest unit test
78
+ ```
79
+
80
+ ### Scaffold a New Middleware
81
+ ```bash
82
+ pnpm run create:middleware
83
+ ```
84
+
85
+ Generates:
86
+ ```txt
87
+ src/middlewares/{middlewareName}/
88
+ ├── constants.ts — Metadata, headersSchema, and optionsSchema
89
+ ├── run.ts — Middleware logic (receives headers, options, function, context)
90
+ └── test.ts — Vitest unit test
91
+ ```
92
+
93
+ ---
94
+
95
+ ## Storage & File Uploads
96
+
97
+ Use `storage.upload()` inside function `run.ts`:
98
+
99
+ ```ts
100
+ import { storage } from "@/utils/storage";
101
+
102
+ export const run = async (input, _context) => {
103
+ const fileBuffer = await input.avatar.toBuffer();
104
+ const saved = await storage.upload(fileBuffer, input.avatar.filename, "avatars");
105
+ return { url: saved.url };
106
+ };
107
+ ```
108
+
109
+ Set `UPLOAD_MODE=s3` in `.env` along with `S3_BUCKET`, `S3_REGION`, `S3_ACCESS_KEY`, `S3_SECRET_KEY` to switch to S3 mode seamlessly.
110
+
111
+ ---
112
+
113
+ ## Interactive Documentation & Health
114
+
115
+ - **Interactive API Docs**: Visit `http://localhost:4000/docs` in your browser.
116
+ - **Health Check**: `GET http://localhost:4000/health`.
@@ -0,0 +1,7 @@
1
+ {
2
+ "watch": ["src"],
3
+ "ext": "ts,json",
4
+ "ignore": ["node_modules", "dist", "src/**/*.spec.ts"],
5
+ "delay": 1500,
6
+ "exec": "tsc && tsc-alias && exec node dist/server.js"
7
+ }