@mandujs/core 0.2.2 → 0.3.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mandujs/core",
3
- "version": "0.2.2",
3
+ "version": "0.3.0",
4
4
  "description": "Mandu Framework Core - Spec, Generator, Guard, Runtime",
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
@@ -0,0 +1,219 @@
1
+ /**
2
+ * Mandu Context - 만두 접시 🥟
3
+ * Request/Response를 래핑하여 편리한 API 제공
4
+ */
5
+
6
+ import type { ZodSchema } from "zod";
7
+
8
+ export class ManduContext {
9
+ private store: Map<string, unknown> = new Map();
10
+ private _params: Record<string, string>;
11
+ private _query: Record<string, string>;
12
+ private _shouldContinue: boolean = true;
13
+ private _response: Response | null = null;
14
+
15
+ constructor(
16
+ public readonly request: Request,
17
+ params: Record<string, string> = {}
18
+ ) {
19
+ this._params = params;
20
+ this._query = this.parseQuery();
21
+ }
22
+
23
+ private parseQuery(): Record<string, string> {
24
+ const url = new URL(this.request.url);
25
+ const query: Record<string, string> = {};
26
+ url.searchParams.forEach((value, key) => {
27
+ query[key] = value;
28
+ });
29
+ return query;
30
+ }
31
+
32
+ // ============================================
33
+ // 🥟 Request 읽기
34
+ // ============================================
35
+
36
+ /** Path parameters (e.g., /users/:id → { id: '123' }) */
37
+ get params(): Record<string, string> {
38
+ return this._params;
39
+ }
40
+
41
+ /** Query parameters (e.g., ?name=mandu → { name: 'mandu' }) */
42
+ get query(): Record<string, string> {
43
+ return this._query;
44
+ }
45
+
46
+ /** Request headers */
47
+ get headers(): Headers {
48
+ return this.request.headers;
49
+ }
50
+
51
+ /** HTTP method */
52
+ get method(): string {
53
+ return this.request.method;
54
+ }
55
+
56
+ /** Request URL */
57
+ get url(): string {
58
+ return this.request.url;
59
+ }
60
+
61
+ /**
62
+ * Parse request body with optional Zod validation
63
+ * @example
64
+ * const data = await ctx.body() // any
65
+ * const data = await ctx.body(UserSchema) // typed & validated
66
+ */
67
+ async body<T = unknown>(schema?: ZodSchema<T>): Promise<T> {
68
+ const contentType = this.request.headers.get("content-type") || "";
69
+ let data: unknown;
70
+
71
+ if (contentType.includes("application/json")) {
72
+ data = await this.request.json();
73
+ } else if (contentType.includes("application/x-www-form-urlencoded")) {
74
+ const formData = await this.request.formData();
75
+ data = Object.fromEntries(formData.entries());
76
+ } else if (contentType.includes("multipart/form-data")) {
77
+ const formData = await this.request.formData();
78
+ data = Object.fromEntries(formData.entries());
79
+ } else {
80
+ data = await this.request.text();
81
+ }
82
+
83
+ if (schema) {
84
+ const result = schema.safeParse(data);
85
+ if (!result.success) {
86
+ throw new ValidationError(result.error.errors);
87
+ }
88
+ return result.data;
89
+ }
90
+
91
+ return data as T;
92
+ }
93
+
94
+ // ============================================
95
+ // 🥟 Response 보내기
96
+ // ============================================
97
+
98
+ /** 200 OK */
99
+ ok<T>(data: T): Response {
100
+ return this.json(data, 200);
101
+ }
102
+
103
+ /** 201 Created */
104
+ created<T>(data: T): Response {
105
+ return this.json(data, 201);
106
+ }
107
+
108
+ /** 204 No Content */
109
+ noContent(): Response {
110
+ return new Response(null, { status: 204 });
111
+ }
112
+
113
+ /** 400 Bad Request */
114
+ error(message: string, details?: unknown): Response {
115
+ return this.json({ status: "error", message, details }, 400);
116
+ }
117
+
118
+ /** 401 Unauthorized */
119
+ unauthorized(message: string = "Unauthorized"): Response {
120
+ return this.json({ status: "error", message }, 401);
121
+ }
122
+
123
+ /** 403 Forbidden */
124
+ forbidden(message: string = "Forbidden"): Response {
125
+ return this.json({ status: "error", message }, 403);
126
+ }
127
+
128
+ /** 404 Not Found */
129
+ notFound(message: string = "Not Found"): Response {
130
+ return this.json({ status: "error", message }, 404);
131
+ }
132
+
133
+ /** 500 Internal Server Error */
134
+ fail(message: string = "Internal Server Error"): Response {
135
+ return this.json({ status: "error", message }, 500);
136
+ }
137
+
138
+ /** Custom JSON response */
139
+ json<T>(data: T, status: number = 200): Response {
140
+ return Response.json(data, { status });
141
+ }
142
+
143
+ /** Custom text response */
144
+ text(data: string, status: number = 200): Response {
145
+ return new Response(data, {
146
+ status,
147
+ headers: { "Content-Type": "text/plain" },
148
+ });
149
+ }
150
+
151
+ /** Custom HTML response */
152
+ html(data: string, status: number = 200): Response {
153
+ return new Response(data, {
154
+ status,
155
+ headers: { "Content-Type": "text/html" },
156
+ });
157
+ }
158
+
159
+ /** Redirect response */
160
+ redirect(url: string, status: 301 | 302 | 307 | 308 = 302): Response {
161
+ return Response.redirect(url, status);
162
+ }
163
+
164
+ // ============================================
165
+ // 🥟 상태 저장 (Guard → Handler 전달)
166
+ // ============================================
167
+
168
+ /** Store value for later use */
169
+ set<T>(key: string, value: T): void {
170
+ this.store.set(key, value);
171
+ }
172
+
173
+ /** Get stored value */
174
+ get<T>(key: string): T | undefined {
175
+ return this.store.get(key) as T | undefined;
176
+ }
177
+
178
+ /** Check if key exists */
179
+ has(key: string): boolean {
180
+ return this.store.has(key);
181
+ }
182
+
183
+ // ============================================
184
+ // 🥟 Guard 제어
185
+ // ============================================
186
+
187
+ /** Continue to next guard/handler */
188
+ next(): symbol {
189
+ this._shouldContinue = true;
190
+ return NEXT_SYMBOL;
191
+ }
192
+
193
+ /** Check if should continue */
194
+ get shouldContinue(): boolean {
195
+ return this._shouldContinue;
196
+ }
197
+
198
+ /** Set early response (from guard) */
199
+ setResponse(response: Response): void {
200
+ this._shouldContinue = false;
201
+ this._response = response;
202
+ }
203
+
204
+ /** Get early response */
205
+ getResponse(): Response | null {
206
+ return this._response;
207
+ }
208
+ }
209
+
210
+ /** Symbol to indicate continue to next */
211
+ export const NEXT_SYMBOL = Symbol("mandu:next");
212
+
213
+ /** Validation error with details */
214
+ export class ValidationError extends Error {
215
+ constructor(public readonly errors: unknown[]) {
216
+ super("Validation failed");
217
+ this.name = "ValidationError";
218
+ }
219
+ }
@@ -0,0 +1,234 @@
1
+ /**
2
+ * Mandu Filling - 만두소 🥟
3
+ * 체이닝 API로 비즈니스 로직 정의
4
+ */
5
+
6
+ import { ManduContext, NEXT_SYMBOL, ValidationError } from "./context";
7
+
8
+ /** Handler function type */
9
+ export type Handler = (ctx: ManduContext) => Response | Promise<Response>;
10
+
11
+ /** Guard function type - returns next() or Response */
12
+ export type Guard = (ctx: ManduContext) => symbol | Response | Promise<symbol | Response>;
13
+
14
+ /** HTTP methods */
15
+ export type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS";
16
+
17
+ interface FillingConfig {
18
+ handlers: Map<HttpMethod, Handler>;
19
+ guards: Guard[];
20
+ methodGuards: Map<HttpMethod, Guard[]>;
21
+ }
22
+
23
+ /**
24
+ * Mandu Filling Builder
25
+ * @example
26
+ * ```typescript
27
+ * export default Mandu.filling()
28
+ * .guard(authCheck)
29
+ * .get(ctx => ctx.ok({ message: 'Hello!' }))
30
+ * .post(ctx => ctx.created({ id: 1 }))
31
+ * ```
32
+ */
33
+ export class ManduFilling {
34
+ private config: FillingConfig = {
35
+ handlers: new Map(),
36
+ guards: [],
37
+ methodGuards: new Map(),
38
+ };
39
+
40
+ // ============================================
41
+ // 🥟 HTTP Method Handlers
42
+ // ============================================
43
+
44
+ /** Handle GET requests */
45
+ get(handler: Handler): this {
46
+ this.config.handlers.set("GET", handler);
47
+ return this;
48
+ }
49
+
50
+ /** Handle POST requests */
51
+ post(handler: Handler): this {
52
+ this.config.handlers.set("POST", handler);
53
+ return this;
54
+ }
55
+
56
+ /** Handle PUT requests */
57
+ put(handler: Handler): this {
58
+ this.config.handlers.set("PUT", handler);
59
+ return this;
60
+ }
61
+
62
+ /** Handle PATCH requests */
63
+ patch(handler: Handler): this {
64
+ this.config.handlers.set("PATCH", handler);
65
+ return this;
66
+ }
67
+
68
+ /** Handle DELETE requests */
69
+ delete(handler: Handler): this {
70
+ this.config.handlers.set("DELETE", handler);
71
+ return this;
72
+ }
73
+
74
+ /** Handle HEAD requests */
75
+ head(handler: Handler): this {
76
+ this.config.handlers.set("HEAD", handler);
77
+ return this;
78
+ }
79
+
80
+ /** Handle OPTIONS requests */
81
+ options(handler: Handler): this {
82
+ this.config.handlers.set("OPTIONS", handler);
83
+ return this;
84
+ }
85
+
86
+ /** Handle all methods with single handler */
87
+ all(handler: Handler): this {
88
+ const methods: HttpMethod[] = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"];
89
+ methods.forEach((method) => this.config.handlers.set(method, handler));
90
+ return this;
91
+ }
92
+
93
+ // ============================================
94
+ // 🥟 Guards (만두 찜기)
95
+ // ============================================
96
+
97
+ /**
98
+ * Add guard for all methods or specific methods
99
+ * @example
100
+ * .guard(authCheck) // all methods
101
+ * .guard(authCheck, 'POST', 'PUT') // specific methods
102
+ */
103
+ guard(guardFn: Guard, ...methods: HttpMethod[]): this {
104
+ if (methods.length === 0) {
105
+ // Apply to all methods
106
+ this.config.guards.push(guardFn);
107
+ } else {
108
+ // Apply to specific methods
109
+ methods.forEach((method) => {
110
+ const guards = this.config.methodGuards.get(method) || [];
111
+ guards.push(guardFn);
112
+ this.config.methodGuards.set(method, guards);
113
+ });
114
+ }
115
+ return this;
116
+ }
117
+
118
+ /** Alias for guard - more semantic for middleware */
119
+ use(guardFn: Guard, ...methods: HttpMethod[]): this {
120
+ return this.guard(guardFn, ...methods);
121
+ }
122
+
123
+ // ============================================
124
+ // 🥟 Execution
125
+ // ============================================
126
+
127
+ /**
128
+ * Handle incoming request
129
+ * Called by generated route handler
130
+ */
131
+ async handle(request: Request, params: Record<string, string> = {}): Promise<Response> {
132
+ const ctx = new ManduContext(request, params);
133
+ const method = request.method.toUpperCase() as HttpMethod;
134
+
135
+ try {
136
+ // Run global guards
137
+ for (const guard of this.config.guards) {
138
+ const result = await guard(ctx);
139
+ if (result !== NEXT_SYMBOL) {
140
+ return result as Response;
141
+ }
142
+ if (!ctx.shouldContinue) {
143
+ return ctx.getResponse()!;
144
+ }
145
+ }
146
+
147
+ // Run method-specific guards
148
+ const methodGuards = this.config.methodGuards.get(method) || [];
149
+ for (const guard of methodGuards) {
150
+ const result = await guard(ctx);
151
+ if (result !== NEXT_SYMBOL) {
152
+ return result as Response;
153
+ }
154
+ if (!ctx.shouldContinue) {
155
+ return ctx.getResponse()!;
156
+ }
157
+ }
158
+
159
+ // Get handler for method
160
+ const handler = this.config.handlers.get(method);
161
+ if (!handler) {
162
+ return ctx.json(
163
+ {
164
+ status: "error",
165
+ message: `Method ${method} not allowed`,
166
+ allowed: Array.from(this.config.handlers.keys()),
167
+ },
168
+ 405
169
+ );
170
+ }
171
+
172
+ // Execute handler
173
+ return await handler(ctx);
174
+ } catch (error) {
175
+ // Handle validation errors
176
+ if (error instanceof ValidationError) {
177
+ return ctx.json(
178
+ {
179
+ status: "error",
180
+ message: "Validation failed",
181
+ errors: error.errors,
182
+ },
183
+ 400
184
+ );
185
+ }
186
+
187
+ // Handle other errors
188
+ console.error(`[Mandu] Handler error:`, error);
189
+ return ctx.fail(
190
+ error instanceof Error ? error.message : "Internal Server Error"
191
+ );
192
+ }
193
+ }
194
+
195
+ /**
196
+ * Get list of registered methods
197
+ */
198
+ getMethods(): HttpMethod[] {
199
+ return Array.from(this.config.handlers.keys());
200
+ }
201
+
202
+ /**
203
+ * Check if method is registered
204
+ */
205
+ hasMethod(method: HttpMethod): boolean {
206
+ return this.config.handlers.has(method);
207
+ }
208
+ }
209
+
210
+ /**
211
+ * Mandu namespace with factory methods
212
+ */
213
+ export const Mandu = {
214
+ /**
215
+ * Create a new filling (slot logic builder)
216
+ * @example
217
+ * ```typescript
218
+ * import { Mandu } from '@mandujs/core'
219
+ *
220
+ * export default Mandu.filling()
221
+ * .get(ctx => ctx.ok({ message: 'Hello!' }))
222
+ * ```
223
+ */
224
+ filling(): ManduFilling {
225
+ return new ManduFilling();
226
+ },
227
+
228
+ /**
229
+ * Create context manually (for testing)
230
+ */
231
+ context(request: Request, params?: Record<string, string>): ManduContext {
232
+ return new ManduContext(request, params);
233
+ },
234
+ };
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Mandu Filling Module - 만두소 🥟
3
+ */
4
+
5
+ export { ManduContext, NEXT_SYMBOL, ValidationError } from "./context";
6
+ export { ManduFilling, Mandu } from "./filling";
7
+ export type { Handler, Guard, HttpMethod } from "./filling";
@@ -25,7 +25,6 @@ export default function handler(req: Request, params: Record<string, string>): R
25
25
 
26
26
  export function generateApiHandlerWithSlot(route: RouteSpec): string {
27
27
  const slotImportPath = computeSlotImportPath(route.slotModule!, "apps/server/generated/routes");
28
- const logicFunctionName = `${route.id}Logic`;
29
28
 
30
29
  return `// Generated by Mandu - DO NOT EDIT DIRECTLY
31
30
  // Route ID: ${route.id}
@@ -33,69 +32,61 @@ export function generateApiHandlerWithSlot(route: RouteSpec): string {
33
32
  // Slot Module: ${route.slotModule}
34
33
 
35
34
  import type { Request } from "bun";
36
- import { ${logicFunctionName} } from "${slotImportPath}";
35
+ import filling from "${slotImportPath}";
37
36
 
38
37
  export default async function handler(
39
38
  req: Request,
40
39
  params: Record<string, string>
41
40
  ): Promise<Response> {
42
- try {
43
- const result = await ${logicFunctionName}(req, params);
44
- return Response.json(result);
45
- } catch (error) {
46
- console.error(\`[${route.id}] Handler error:\`, error);
47
- return Response.json(
48
- { status: "error", message: "Internal server error" },
49
- { status: 500 }
50
- );
51
- }
41
+ return filling.handle(req, params);
52
42
  }
53
43
  `;
54
44
  }
55
45
 
56
46
  export function generateSlotLogic(route: RouteSpec): string {
57
- const logicFunctionName = `${route.id}Logic`;
58
- const resultTypeName = `${capitalize(route.id)}Result`;
59
-
60
- return `// Slot logic for route: ${route.id}
47
+ return `// 🥟 Mandu Filling - ${route.id}
61
48
  // Pattern: ${route.pattern}
62
49
  // 이 파일에서 비즈니스 로직을 구현하세요.
63
50
 
64
- import type { Request } from "bun";
65
-
66
- export interface ${resultTypeName} {
67
- status: "ok" | "error";
68
- data?: unknown;
69
- message?: string;
70
- }
51
+ import { Mandu } from "@mandujs/core";
52
+
53
+ export default Mandu.filling()
54
+ // 📋 GET ${route.pattern}
55
+ .get((ctx) => {
56
+ return ctx.ok({
57
+ message: "Hello from ${route.id}!",
58
+ timestamp: new Date().toISOString(),
59
+ });
60
+ })
61
+
62
+ // ➕ POST ${route.pattern}
63
+ .post(async (ctx) => {
64
+ const body = await ctx.body();
65
+ return ctx.created({
66
+ message: "Created!",
67
+ received: body,
68
+ });
69
+ });
71
70
 
72
- export async function ${logicFunctionName}(
73
- req: Request,
74
- params: Record<string, string>
75
- ): Promise<${resultTypeName}> {
76
- const method = req.method;
77
-
78
- // TODO: 비즈니스 로직 구현
79
- switch (method) {
80
- case "GET":
81
- return {
82
- status: "ok",
83
- data: { routeId: "${route.id}", message: "GET 로직 미구현" },
84
- };
85
-
86
- case "POST":
87
- return {
88
- status: "ok",
89
- data: { routeId: "${route.id}", message: "POST 로직 미구현" },
90
- };
91
-
92
- default:
93
- return {
94
- status: "error",
95
- message: \`Method \${method} not allowed\`,
96
- };
97
- }
98
- }
71
+ // 💡 사용 가능한 메서드:
72
+ // .get(ctx => ...) - GET 요청 처리
73
+ // .post(ctx => ...) - POST 요청 처리
74
+ // .put(ctx => ...) - PUT 요청 처리
75
+ // .delete(ctx => ...) - DELETE 요청 처리
76
+ // .guard(ctx => ...) - 인증/검증 미들웨어
77
+ //
78
+ // 💡 Context (ctx) API:
79
+ // ctx.query - Query parameters { name: 'value' }
80
+ // ctx.params - Path parameters { id: '123' }
81
+ // ctx.body() - Request body (자동 파싱)
82
+ // ctx.body(zodSchema) - Body with validation
83
+ // ctx.headers - Request headers
84
+ // ctx.ok(data) - 200 OK
85
+ // ctx.created(data) - 201 Created
86
+ // ctx.error(msg) - 400 Bad Request
87
+ // ctx.notFound(msg) - 404 Not Found
88
+ // ctx.set(key, value) - Guard에서 Handler로 데이터 전달
89
+ // ctx.get(key) - Guard에서 설정한 데이터 읽기
99
90
  `;
100
91
  }
101
92
 
package/src/index.ts CHANGED
@@ -3,3 +3,4 @@ export * from "./runtime";
3
3
  export * from "./generator";
4
4
  export * from "./guard";
5
5
  export * from "./report";
6
+ export * from "./filling";