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,423 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * scripts/create-function.ts
4
+ * ─────────────────────────────────────────────────────────────────────────────
5
+ * Scaffolds a new API function with constants, run, optional middlewares, and test files.
6
+ * Usage: pnpm create:function
7
+ */
8
+
9
+ import * as p from "@clack/prompts";
10
+ import fs from "node:fs";
11
+ import path from "node:path";
12
+ import { glob } from "tinyglobby";
13
+
14
+ const MAX_RETRIES = 5;
15
+ const ROOT = process.cwd();
16
+ const FUNCTIONS_DIR = path.join(ROOT, "src", "functions");
17
+ const MIDDLEWARES_DIR = path.join(ROOT, "src", "middlewares");
18
+
19
+ async function getExistingNamespaces(): Promise<string[]> {
20
+ if (!fs.existsSync(FUNCTIONS_DIR)) return [];
21
+
22
+ const runFiles = await glob("**/run.ts", {
23
+ cwd: FUNCTIONS_DIR,
24
+ absolute: false,
25
+ ignore: ["**/*.spec.ts", "**/__tests__/**"],
26
+ });
27
+
28
+ const namespaces = new Set<string>();
29
+ for (const f of runFiles) {
30
+ const parts = f.split("/");
31
+ if (parts.length < 3) continue;
32
+ const ns = parts.slice(0, parts.length - 2).join(".");
33
+ if (ns) namespaces.add(ns);
34
+ }
35
+
36
+ return Array.from(namespaces).sort();
37
+ }
38
+
39
+ function getAvailableMiddlewares(): string[] {
40
+ if (!fs.existsSync(MIDDLEWARES_DIR)) return [];
41
+ return fs
42
+ .readdirSync(MIDDLEWARES_DIR, { withFileTypes: true })
43
+ .filter((e) => e.isDirectory() && !e.name.startsWith("."))
44
+ .map((e) => e.name)
45
+ .sort();
46
+ }
47
+
48
+ const identifierRe = /^[a-zA-Z][a-zA-Z0-9]*$/;
49
+ const namespaceRe = /^[a-z][a-z0-9]*(\.[a-z][a-z0-9]*)*$/;
50
+
51
+ function tplConstants(ns: string, fn: string, isMultipart: boolean): string {
52
+ const nsPath = ns.replace(/\./g, "/");
53
+
54
+ if (isMultipart) {
55
+ return `/**
56
+ * functions/${nsPath}/${fn}/constants.ts
57
+ * ─────────────────────────────────────────────────────────────────────────────
58
+ * SCHEMA & CONTRACT DEFINITION
59
+ *
60
+ * WHAT TO TOUCH:
61
+ * - metadata: Human-readable description, tags, public status for API docs.
62
+ * - contentType: Strictly "multipart/form-data" for file uploads.
63
+ * - inputSchema: Define form fields and file attachments using File() or Files().
64
+ * - outputSchema: Define what this function returns.
65
+ */
66
+
67
+ import { Type } from "@sinclair/typebox";
68
+ import { File, Files } from "@cellsweb/rpc-core";
69
+
70
+ export const metadata = {
71
+ description: "TODO: describe ${fn}",
72
+ isPublic: ${ns.startsWith("public")},
73
+ deprecated: false,
74
+ tags: ["upload"] as string[],
75
+ };
76
+
77
+ export const contentType = "multipart/form-data" as const;
78
+
79
+ export const headersSchema = Type.Object({}, { additionalProperties: true });
80
+
81
+ export const inputSchema = Type.Object({
82
+ title: Type.String({ minLength: 1, description: "Title of the upload" }),
83
+ file: File({
84
+ maxSizeBytes: 5_000_000,
85
+ mimeTypes: ["image/png", "image/jpeg", "application/pdf"],
86
+ description: "Primary file attachment",
87
+ }),
88
+ files: Type.Optional(Files({
89
+ maxCount: 5,
90
+ maxSizeBytes: 10_000_000,
91
+ description: "Optional additional files",
92
+ })),
93
+ });
94
+
95
+ export const outputSchema = Type.Object({
96
+ fileName: Type.String(),
97
+ fileSize: Type.Number(),
98
+ extraFiles: Type.Number(),
99
+ });
100
+ `;
101
+ }
102
+
103
+ return `/**
104
+ * functions/${nsPath}/${fn}/constants.ts
105
+ * ─────────────────────────────────────────────────────────────────────────────
106
+ * SCHEMA & CONTRACT DEFINITION
107
+ *
108
+ * WHAT TO TOUCH:
109
+ * - metadata: Description, public access, tags.
110
+ * - contentType: "application/json" (default).
111
+ * - inputSchema: Define fields expected in req.body.data.
112
+ * - outputSchema: Define structure returned by run().
113
+ */
114
+
115
+ import { Type } from "@sinclair/typebox";
116
+
117
+ export const metadata = {
118
+ description: "TODO: describe ${fn}",
119
+ isPublic: ${ns.startsWith("public")},
120
+ deprecated: false,
121
+ tags: [] as string[],
122
+ };
123
+
124
+ export const contentType = "application/json" as const;
125
+
126
+ export const headersSchema = Type.Object({}, { additionalProperties: true });
127
+
128
+ export const inputSchema = Type.Object({
129
+ example: Type.String({ minLength: 1, description: "Example string input" }),
130
+ });
131
+
132
+ export const outputSchema = Type.Object({
133
+ result: Type.String(),
134
+ });
135
+ `;
136
+ }
137
+
138
+ function tplRun(ns: string, fn: string, isMultipart: boolean, mws: string[]): string {
139
+ const nsPath = ns.replace(/\./g, "/");
140
+ let contextTypeStr = "MiddlewareContext";
141
+ let importContextStr = 'import type { MiddlewareContext } from "@/context";';
142
+
143
+ if (mws.length > 0) {
144
+ importContextStr = 'import type { InferContext } from "@/registry";\nimport { middlewares } from "./middlewares";';
145
+ contextTypeStr = "InferContext<typeof middlewares>";
146
+ }
147
+
148
+ if (isMultipart) {
149
+ return `/**
150
+ * functions/${nsPath}/${fn}/run.ts
151
+ * ─────────────────────────────────────────────────────────────────────────────
152
+ * BUSINESS LOGIC HANDLER
153
+ *
154
+ * WHAT TO TOUCH:
155
+ * - Place core business operations here.
156
+ * - Access input fields: input.title, input.file.filename, input.file.toBuffer().
157
+ * - Access context variables provided by middlewares in _context.
158
+ *
159
+ * WHAT TO EXPECT:
160
+ * - input is guaranteed to be validated against inputSchema.
161
+ * - The return object MUST match outputSchema.
162
+ */
163
+
164
+ import type { Static } from "@sinclair/typebox";
165
+ ${importContextStr}
166
+ import { inputSchema, outputSchema } from "./constants";
167
+
168
+ type Input = Static<typeof inputSchema>;
169
+ type Output = Static<typeof outputSchema>;
170
+
171
+ export const run = async (
172
+ input: Input,
173
+ _context: ${contextTypeStr},
174
+ ): Promise<Output> => {
175
+ // Access uploaded file properties safely
176
+ const filename = input.file.filename;
177
+ const fileSize = input.file.byteLength;
178
+
179
+ return {
180
+ fileName: filename,
181
+ fileSize: fileSize,
182
+ extraFiles: input.files?.length ?? 0,
183
+ };
184
+ };
185
+ `;
186
+ }
187
+
188
+ return `/**
189
+ * functions/${nsPath}/${fn}/run.ts
190
+ * ─────────────────────────────────────────────────────────────────────────────
191
+ * BUSINESS LOGIC HANDLER
192
+ *
193
+ * WHAT TO TOUCH:
194
+ * - Implement function logic here.
195
+ * - Access input fields via input.*.
196
+ * - Access context values (e.g. auth user, ip, headers) via _context.
197
+ *
198
+ * WHAT TO EXPECT:
199
+ * - Input is pre-validated by TypeBox inputSchema.
200
+ * - Return value is validated against outputSchema before sending response.
201
+ */
202
+
203
+ import type { Static } from "@sinclair/typebox";
204
+ ${importContextStr}
205
+ import { inputSchema, outputSchema } from "./constants";
206
+
207
+ type Input = Static<typeof inputSchema>;
208
+ type Output = Static<typeof outputSchema>;
209
+
210
+ export const run = async (
211
+ input: Input,
212
+ _context: ${contextTypeStr},
213
+ ): Promise<Output> => {
214
+ return {
215
+ result: input.example,
216
+ };
217
+ };
218
+ `;
219
+ }
220
+
221
+ function tplMiddlewares(ns: string, fn: string, mws: string[]): string {
222
+ const nsPath = ns.replace(/\./g, "/");
223
+ const entries = mws
224
+ .map((mw) => {
225
+ if (mw === "rateLimit") {
226
+ return ` { name: "rateLimit", options: { windowSeconds: 60, maxRequests: 100 } },`;
227
+ }
228
+ if (mw === "auth") {
229
+ return ` { name: "auth", options: { roles: ["user", "admin", "vendor", "staff", "dev"] } },`;
230
+ }
231
+ return ` { name: "${mw}", options: {} },`;
232
+ })
233
+ .join("\n");
234
+
235
+ return `/**
236
+ * functions/${nsPath}/${fn}/middlewares.ts
237
+ * ─────────────────────────────────────────────────────────────────────────────
238
+ * FUNCTION MIDDLEWARE PIPELINE
239
+ *
240
+ * Declarative list of central middlewares executed in order before run().
241
+ */
242
+
243
+ import { defineMiddlewares } from "@cellsweb/rpc-core";
244
+
245
+ export const middlewares = defineMiddlewares([
246
+ ${entries}
247
+ ]);
248
+ `;
249
+ }
250
+
251
+ function tplTest(ns: string, fn: string, isMultipart: boolean): string {
252
+ const nsPath = ns.replace(/\./g, "/");
253
+
254
+ if (isMultipart) {
255
+ return `/**
256
+ * functions/${nsPath}/${fn}/test.ts
257
+ * ─────────────────────────────────────────────────────────────────────────────
258
+ * UNIT / INTEGRATION TEST FOR ${fn}
259
+ * Run with: pnpm test
260
+ */
261
+
262
+ import { describe, it, expect } from "vitest";
263
+ import { run } from "./run";
264
+ import { createUploadedFile } from "@/uploads/types";
265
+
266
+ describe("${ns}.${fn}", () => {
267
+ it("executes business logic with simulated upload", async () => {
268
+ const mockFile = createUploadedFile({
269
+ fieldName: "file",
270
+ filename: "test.png",
271
+ encoding: "7bit",
272
+ mimeType: "image/png",
273
+ byteLength: 1024,
274
+ tempFilePath: "/tmp/mock.png",
275
+ });
276
+
277
+ const result = await run(
278
+ {
279
+ title: "Test Upload",
280
+ file: mockFile,
281
+ },
282
+ {} as any,
283
+ );
284
+
285
+ expect(result.fileName).toBe("test.png");
286
+ expect(result.fileSize).toBe(1024);
287
+ });
288
+ });
289
+ `;
290
+ }
291
+
292
+ return `/**
293
+ * functions/${nsPath}/${fn}/test.ts
294
+ * ─────────────────────────────────────────────────────────────────────────────
295
+ * UNIT / INTEGRATION TEST FOR ${fn}
296
+ * Run with: pnpm test
297
+ */
298
+
299
+ import { describe, it, expect } from "vitest";
300
+ import { run } from "./run";
301
+
302
+ describe("${ns}.${fn}", () => {
303
+ it("executes successfully with valid input", async () => {
304
+ const result = await run({ example: "Hello World" }, {} as any);
305
+ expect(result.result).toBe("Hello World");
306
+ });
307
+ });
308
+ `;
309
+ }
310
+
311
+ async function main(): Promise<void> {
312
+ console.clear();
313
+ p.intro(" Create Function ");
314
+
315
+ const existingNs = await getExistingNamespaces();
316
+ const nsOptions = [
317
+ ...existingNs.map((ns) => ({ value: ns, label: ns })),
318
+ { value: "__new__", label: "+ Create new namespace" },
319
+ ];
320
+
321
+ const nsPick = await p.select({
322
+ message: "Select namespace",
323
+ options: nsOptions,
324
+ });
325
+ if (p.isCancel(nsPick)) { p.cancel("Cancelled."); process.exit(0); }
326
+
327
+ let namespace: string;
328
+ if (nsPick === "__new__") {
329
+ const custom = await p.text({
330
+ message: "New namespace",
331
+ placeholder: "public | admin | admin.users",
332
+ validate: (v) => {
333
+ if (!v?.trim()) return "Required";
334
+ if (!namespaceRe.test(v.trim())) return 'Lowercase, dot-separated (e.g. "admin.users")';
335
+ },
336
+ });
337
+ if (p.isCancel(custom)) { p.cancel("Cancelled."); process.exit(0); }
338
+ namespace = (custom as string).trim();
339
+ } else {
340
+ namespace = nsPick as string;
341
+ }
342
+
343
+ const nsDir = path.join(FUNCTIONS_DIR, namespace.replace(/\./g, path.sep));
344
+ let functionName = "";
345
+
346
+ for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
347
+ const label = attempt === 0 ? "Function name" : `Function name (${MAX_RETRIES - attempt} attempt(s) left)`;
348
+ const raw = await p.text({
349
+ message: label,
350
+ placeholder: "getUserID | uploadAvatar",
351
+ validate: (v) => {
352
+ if (!v?.trim()) return "Required";
353
+ if (!identifierRe.test(v.trim())) return "Letters and numbers only, starting with a letter";
354
+ },
355
+ });
356
+ if (p.isCancel(raw)) { p.cancel("Cancelled."); process.exit(0); }
357
+
358
+ const name = (raw as string).trim();
359
+ if (fs.existsSync(path.join(nsDir, name))) {
360
+ const remaining = MAX_RETRIES - attempt - 1;
361
+ if (remaining === 0) {
362
+ p.log.error(`"${name}" already exists. Aborting.`);
363
+ process.exit(1);
364
+ }
365
+ p.log.warn(`"${namespace}.${name}" already exists. (${remaining} left)`);
366
+ continue;
367
+ }
368
+
369
+ functionName = name;
370
+ break;
371
+ }
372
+
373
+ const contentTypePick = await p.select({
374
+ message: "Input Content-Type",
375
+ options: [
376
+ { value: "application/json", label: "application/json (default)" },
377
+ { value: "multipart/form-data", label: "multipart/form-data (file upload)" },
378
+ ],
379
+ });
380
+ if (p.isCancel(contentTypePick)) { p.cancel("Cancelled."); process.exit(0); }
381
+ const isMultipart = contentTypePick === "multipart/form-data";
382
+
383
+ const available = getAvailableMiddlewares();
384
+ let selectedMws: string[] = [];
385
+
386
+ if (available.length > 0) {
387
+ const pick = await p.multiselect({
388
+ message: "Select middlewares",
389
+ options: available.map((mw) => ({ value: mw, label: mw })),
390
+ required: false,
391
+ });
392
+ if (p.isCancel(pick)) { p.cancel("Cancelled."); process.exit(0); }
393
+ selectedMws = pick as string[];
394
+ }
395
+
396
+ const fnDir = path.join(nsDir, functionName);
397
+ const spin = p.spinner();
398
+ spin.start("Writing files…");
399
+
400
+ try {
401
+ fs.mkdirSync(fnDir, { recursive: true });
402
+ fs.writeFileSync(path.join(fnDir, "constants.ts"), tplConstants(namespace, functionName, isMultipart));
403
+ fs.writeFileSync(path.join(fnDir, "run.ts"), tplRun(namespace, functionName, isMultipart, selectedMws));
404
+ fs.writeFileSync(path.join(fnDir, "test.ts"), tplTest(namespace, functionName, isMultipart));
405
+ if (selectedMws.length > 0) {
406
+ fs.writeFileSync(
407
+ path.join(fnDir, "middlewares.ts"),
408
+ tplMiddlewares(namespace, functionName, selectedMws),
409
+ );
410
+ }
411
+ spin.stop("Done");
412
+ } catch (err) {
413
+ spin.stop("Failed");
414
+ p.log.error((err as Error).message);
415
+ process.exit(1);
416
+ }
417
+
418
+ const rel = path.relative(ROOT, fnDir);
419
+ p.note(`📁 ${rel}/\n constants.ts\n run.ts\n test.ts${selectedMws.length > 0 ? "\n middlewares.ts" : ""}`, "Created");
420
+ p.outro(`${namespace}.${functionName} ready.`);
421
+ }
422
+
423
+ main().catch((e) => { console.error(e); process.exit(1); });
@@ -0,0 +1,174 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * scripts/create-middleware.ts
4
+ * ─────────────────────────────────────────────────────────────────────────────
5
+ * Interactive CLI scaffolder for new central middlewares.
6
+ * Usage: pnpm create:middleware
7
+ */
8
+
9
+ import * as p from "@clack/prompts";
10
+ import fs from "node:fs";
11
+ import path from "node:path";
12
+
13
+ const MAX_RETRIES = 5;
14
+ const ROOT = process.cwd();
15
+ const MIDDLEWARES_DIR = path.join(ROOT, "src", "middlewares");
16
+
17
+ const identifierRe = /^[a-zA-Z][a-zA-Z0-9]*$/;
18
+
19
+ function tplConstants(name: string): string {
20
+ return `/**
21
+ * middlewares/${name}/constants.ts
22
+ * ─────────────────────────────────────────────────────────────────────────────
23
+ * MIDDLEWARE CONTRACT & METADATA
24
+ *
25
+ * WHAT TO TOUCH:
26
+ * - metadata: Description displayed in /docs.
27
+ * - headersSchema: Optional headers this middleware requires/reads.
28
+ * - optionsSchema: Config options passed in function middlewares.ts.
29
+ */
30
+
31
+ import { Type } from "@sinclair/typebox";
32
+
33
+ export const metadata = {
34
+ name: "${name}",
35
+ description: "TODO: describe what ${name} does",
36
+ };
37
+
38
+ export const headersSchema = Type.Object({}, { additionalProperties: true });
39
+
40
+ export const optionsSchema = Type.Object({}, { additionalProperties: false });
41
+ `;
42
+ }
43
+
44
+ function tplRun(name: string): string {
45
+ return `/**
46
+ * middlewares/${name}/run.ts
47
+ * ─────────────────────────────────────────────────────────────────────────────
48
+ * MIDDLEWARE IMPLEMENTATION
49
+ *
50
+ * MIDDLEWARE INPUT PARAMETERS:
51
+ * - params.headers: Incoming HTTP request headers (e.g. authorization, x-tenant-id)
52
+ * - params.options: Function-level options configured in function's middlewares.ts
53
+ * - params.function: Target function metadata ({ key, namespace, functionName, contentType })
54
+ * - context: Immutable request context ({ requestId, ip, requestStartTime, req })
55
+ *
56
+ * WHAT TO TOUCH:
57
+ * - Implement header checks, token verifications, or rate-limiting guards here.
58
+ * - Return augmented context object: return { ...context, ${name}: "value" }.
59
+ * - Throw AppError (e.g. ErrorCode.UNAUTHORIZED) to reject invalid requests.
60
+ */
61
+
62
+ import type { MiddlewareFn } from "@cellsweb/rpc-core";
63
+ import type { Static } from "@sinclair/typebox";
64
+ import { optionsSchema } from "./constants";
65
+
66
+ type Options = Static<typeof optionsSchema>;
67
+
68
+ export const run: MiddlewareFn<Options, { ${name}: string }> = async (
69
+ { headers, options, function: fn },
70
+ context,
71
+ ) => {
72
+ void headers;
73
+ void options;
74
+ void fn;
75
+
76
+ return {
77
+ ...context,
78
+ ${name}: "value",
79
+ };
80
+ };
81
+ `;
82
+ }
83
+
84
+ function tplTest(name: string): string {
85
+ return `/**
86
+ * middlewares/${name}/test.ts
87
+ * ─────────────────────────────────────────────────────────────────────────────
88
+ * UNIT TEST FOR ${name} MIDDLEWARE
89
+ * Run with: pnpm test
90
+ */
91
+
92
+ import { describe, it, expect } from "vitest";
93
+ import { run } from "./run";
94
+
95
+ describe("middleware: ${name}", () => {
96
+ it("augments context successfully", async () => {
97
+ const initialContext = { requestId: "test-id", ip: "127.0.0.1" } as any;
98
+ const result = await run(
99
+ {
100
+ headers: {},
101
+ options: {},
102
+ function: {
103
+ key: "test.fn",
104
+ namespace: "test",
105
+ functionName: "fn",
106
+ metadata: {} as any,
107
+ contentType: "application/json",
108
+ },
109
+ },
110
+ initialContext,
111
+ );
112
+
113
+ expect(result.${name}).toBe("value");
114
+ });
115
+ });
116
+ `;
117
+ }
118
+
119
+ async function main(): Promise<void> {
120
+ console.clear();
121
+ p.intro(" Create Middleware ");
122
+
123
+ let middlewareName = "";
124
+
125
+ for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
126
+ const label = attempt === 0 ? "Middleware name" : `Middleware name (${MAX_RETRIES - attempt} attempt(s) left)`;
127
+
128
+ const raw = await p.text({
129
+ message: label,
130
+ placeholder: "auth | rateLimit | tenantResolver",
131
+ validate: (v) => {
132
+ if (!v?.trim()) return "Required";
133
+ if (!identifierRe.test(v.trim())) return "Letters and numbers only, starting with a letter";
134
+ },
135
+ });
136
+ if (p.isCancel(raw)) { p.cancel("Cancelled."); process.exit(0); }
137
+
138
+ const name = (raw as string).trim();
139
+ if (fs.existsSync(path.join(MIDDLEWARES_DIR, name))) {
140
+ const remaining = MAX_RETRIES - attempt - 1;
141
+ if (remaining === 0) {
142
+ p.log.error(`"${name}" already exists. Aborting.`);
143
+ process.exit(1);
144
+ }
145
+ p.log.warn(`Middleware "${name}" already exists. (${remaining} left)`);
146
+ continue;
147
+ }
148
+
149
+ middlewareName = name;
150
+ break;
151
+ }
152
+
153
+ const mwDir = path.join(MIDDLEWARES_DIR, middlewareName);
154
+ const spin = p.spinner();
155
+ spin.start("Writing files…");
156
+
157
+ try {
158
+ fs.mkdirSync(mwDir, { recursive: true });
159
+ fs.writeFileSync(path.join(mwDir, "constants.ts"), tplConstants(middlewareName));
160
+ fs.writeFileSync(path.join(mwDir, "run.ts"), tplRun(middlewareName));
161
+ fs.writeFileSync(path.join(mwDir, "test.ts"), tplTest(middlewareName));
162
+ spin.stop("Done");
163
+ } catch (err) {
164
+ spin.stop("Failed");
165
+ p.log.error((err as Error).message);
166
+ process.exit(1);
167
+ }
168
+
169
+ const rel = path.relative(ROOT, mwDir);
170
+ p.note(`📁 ${rel}/\n constants.ts\n run.ts\n test.ts`, "Created");
171
+ p.outro(`"${middlewareName}" ready.`);
172
+ }
173
+
174
+ main().catch((e) => { console.error(e); process.exit(1); });
@@ -0,0 +1,18 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2023",
4
+ "module": "CommonJS",
5
+ "moduleResolution": "node",
6
+ "lib": ["ES2023"],
7
+ "strict": true,
8
+ "esModuleInterop": true,
9
+ "skipLibCheck": true,
10
+ "resolveJsonModule": true,
11
+ "noEmit": true,
12
+ "paths": {
13
+ "@/*": ["../src/*"]
14
+ }
15
+ },
16
+ "include": ["./**/*"],
17
+ "exclude": ["node_modules"]
18
+ }
@@ -0,0 +1,79 @@
1
+ import "dotenv/config";
2
+ import { Type, type Static } from "@sinclair/typebox";
3
+ import { Value } from "@sinclair/typebox/value";
4
+
5
+ export const EnvSchema = Type.Object({
6
+ NODE_ENV: Type.Optional(Type.Union([
7
+ Type.Literal("development"),
8
+ Type.Literal("test"),
9
+ Type.Literal("production"),
10
+ ], { default: "development" })),
11
+
12
+ API_PORT: Type.Optional(Type.Number({ default: 4000 })),
13
+ API_HOST: Type.Optional(Type.String({ default: "0.0.0.0" })),
14
+ API_REQUEST_TIMEOUT_MS: Type.Optional(Type.Number({ default: 30000 })),
15
+ API_LOG_LEVEL: Type.Optional(Type.String({ default: "info" })),
16
+
17
+ MAX_JSON_BODY_BYTES: Type.Optional(Type.Number({ default: 1_048_576 })),
18
+ MAX_MULTIPART_BYTES: Type.Optional(Type.Number({ default: 25_000_000 })),
19
+ MAX_UPLOAD_FILE_BYTES: Type.Optional(Type.Number({ default: 10_000_000 })),
20
+ UPLOAD_TMP_DIR: Type.Optional(Type.String()),
21
+
22
+ UPLOAD_MODE: Type.Optional(Type.Union([
23
+ Type.Literal("local"),
24
+ Type.Literal("s3"),
25
+ ], { default: "local" })),
26
+ UPLOAD_DIR: Type.Optional(Type.String({ default: "public/uploads" })),
27
+ SERVER_URL: Type.Optional(Type.String({ default: "http://localhost:4000" })),
28
+
29
+ S3_BUCKET: Type.Optional(Type.String()),
30
+ S3_REGION: Type.Optional(Type.String()),
31
+ S3_ACCESS_KEY: Type.Optional(Type.String()),
32
+ S3_SECRET_KEY: Type.Optional(Type.String()),
33
+ S3_ENDPOINT: Type.Optional(Type.String()),
34
+
35
+ SENTRY_DSN: Type.Optional(Type.String()),
36
+ TELEMETRY_ENABLED: Type.Optional(Type.Boolean({ default: true })),
37
+ });
38
+
39
+ export type Env = Static<typeof EnvSchema>;
40
+
41
+ function numberFromEnv(value: unknown, fallback: number): number {
42
+ if (value === undefined || value === "") return fallback;
43
+ const parsed = Number(value);
44
+ if (!Number.isFinite(parsed)) return NaN;
45
+ return parsed;
46
+ }
47
+
48
+ function parseEnv(): Env {
49
+ const raw: Record<string, unknown> = { ...process.env };
50
+ raw.NODE_ENV ??= "development";
51
+ raw.API_PORT = numberFromEnv(raw.API_PORT, 4000);
52
+ raw.API_HOST ??= "0.0.0.0";
53
+ raw.API_REQUEST_TIMEOUT_MS = numberFromEnv(raw.API_REQUEST_TIMEOUT_MS, 30000);
54
+ raw.MAX_JSON_BODY_BYTES = numberFromEnv(raw.MAX_JSON_BODY_BYTES, 1_048_576);
55
+ raw.MAX_MULTIPART_BYTES = numberFromEnv(raw.MAX_MULTIPART_BYTES, 25_000_000);
56
+ raw.MAX_UPLOAD_FILE_BYTES = numberFromEnv(raw.MAX_UPLOAD_FILE_BYTES, 10_000_000);
57
+ raw.UPLOAD_MODE ??= "local";
58
+ raw.UPLOAD_DIR ??= "public/uploads";
59
+ raw.SERVER_URL ??= "http://localhost:4000";
60
+
61
+ const withDefaults = Value.Default(EnvSchema, raw);
62
+
63
+ if (!Value.Check(EnvSchema, withDefaults)) {
64
+ const errors = [...Value.Errors(EnvSchema, withDefaults)];
65
+ const message = errors.map((e) => `${e.path || "/"}: ${e.message}`).join("\n");
66
+ throw new Error(`Environment validation failed:\n${message}`);
67
+ }
68
+
69
+ return withDefaults as Env;
70
+ }
71
+
72
+ export const env = parseEnv();
73
+
74
+ declare global {
75
+ // eslint-disable-next-line no-var
76
+ var env: Env;
77
+ }
78
+
79
+ globalThis.env = env;
File without changes