@mandujs/core 0.2.1 → 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/README.ko.md +191 -0
- package/README.md +52 -50
- package/package.json +1 -1
- package/src/filling/context.ts +219 -0
- package/src/filling/filling.ts +234 -0
- package/src/filling/index.ts +7 -0
- package/src/generator/templates.ts +41 -50
- package/src/index.ts +1 -0
package/README.ko.md
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
# @mandujs/core
|
|
2
|
+
|
|
3
|
+
> **[English](./README.md)** | 한국어
|
|
4
|
+
|
|
5
|
+
Mandu Framework Core - Spec, Generator, Guard, Runtime
|
|
6
|
+
|
|
7
|
+
## 설치
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
bun add @mandujs/core
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
> 일반적으로 `@mandujs/cli`를 통해 사용합니다. 직접 사용은 고급 사용 사례입니다.
|
|
14
|
+
|
|
15
|
+
## 모듈 구조
|
|
16
|
+
|
|
17
|
+
```
|
|
18
|
+
@mandujs/core
|
|
19
|
+
├── spec/ # Spec 스키마 및 로딩
|
|
20
|
+
├── generator/ # 코드 생성
|
|
21
|
+
├── guard/ # 아키텍처 검사 및 자동 수정
|
|
22
|
+
├── runtime/ # 서버 및 라우터
|
|
23
|
+
└── report/ # Guard 리포트 생성
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
## Spec 모듈
|
|
27
|
+
|
|
28
|
+
라우트 manifest 스키마 정의 및 로딩.
|
|
29
|
+
|
|
30
|
+
```typescript
|
|
31
|
+
import { loadManifest, RoutesManifest, RouteSpec } from "@mandujs/core";
|
|
32
|
+
|
|
33
|
+
// manifest 로드 및 검증
|
|
34
|
+
const result = await loadManifest("spec/routes.manifest.json");
|
|
35
|
+
|
|
36
|
+
if (result.success && result.data) {
|
|
37
|
+
const manifest: RoutesManifest = result.data;
|
|
38
|
+
manifest.routes.forEach((route: RouteSpec) => {
|
|
39
|
+
console.log(route.id, route.pattern, route.kind);
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
### Lock 파일
|
|
45
|
+
|
|
46
|
+
```typescript
|
|
47
|
+
import { writeLock, readLock } from "@mandujs/core";
|
|
48
|
+
|
|
49
|
+
// lock 파일 쓰기
|
|
50
|
+
const lock = await writeLock("spec/spec.lock.json", manifest);
|
|
51
|
+
console.log(lock.routesHash);
|
|
52
|
+
|
|
53
|
+
// lock 파일 읽기
|
|
54
|
+
const existing = await readLock("spec/spec.lock.json");
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Generator 모듈
|
|
58
|
+
|
|
59
|
+
Spec 기반 코드 생성.
|
|
60
|
+
|
|
61
|
+
```typescript
|
|
62
|
+
import { generateRoutes, GenerateResult } from "@mandujs/core";
|
|
63
|
+
|
|
64
|
+
const result: GenerateResult = await generateRoutes(manifest, "./");
|
|
65
|
+
|
|
66
|
+
console.log("생성됨:", result.created);
|
|
67
|
+
console.log("건너뜀:", result.skipped); // 이미 존재하는 slot 파일
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
### 템플릿 함수
|
|
71
|
+
|
|
72
|
+
```typescript
|
|
73
|
+
import {
|
|
74
|
+
generateApiHandler,
|
|
75
|
+
generateApiHandlerWithSlot,
|
|
76
|
+
generateSlotLogic,
|
|
77
|
+
generatePageComponent
|
|
78
|
+
} from "@mandujs/core";
|
|
79
|
+
|
|
80
|
+
// API 핸들러 생성
|
|
81
|
+
const code = generateApiHandler(route);
|
|
82
|
+
|
|
83
|
+
// Slot이 있는 API 핸들러
|
|
84
|
+
const codeWithSlot = generateApiHandlerWithSlot(route);
|
|
85
|
+
|
|
86
|
+
// Slot 로직 파일
|
|
87
|
+
const slotCode = generateSlotLogic(route);
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
## Guard 모듈
|
|
91
|
+
|
|
92
|
+
아키텍처 규칙 검사 및 자동 수정.
|
|
93
|
+
|
|
94
|
+
```typescript
|
|
95
|
+
import {
|
|
96
|
+
runGuardCheck,
|
|
97
|
+
runAutoCorrect,
|
|
98
|
+
GuardResult,
|
|
99
|
+
GuardViolation
|
|
100
|
+
} from "@mandujs/core";
|
|
101
|
+
|
|
102
|
+
// 검사 실행
|
|
103
|
+
const result: GuardResult = await runGuardCheck(manifest, "./");
|
|
104
|
+
|
|
105
|
+
if (!result.passed) {
|
|
106
|
+
result.violations.forEach((v: GuardViolation) => {
|
|
107
|
+
console.log(`${v.rule}: ${v.message}`);
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
// 자동 수정 실행
|
|
111
|
+
const corrected = await runAutoCorrect(result.violations, manifest, "./");
|
|
112
|
+
console.log("수정됨:", corrected.steps);
|
|
113
|
+
console.log("남은 위반:", corrected.remainingViolations);
|
|
114
|
+
}
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
### Guard 규칙
|
|
118
|
+
|
|
119
|
+
| 규칙 ID | 설명 | 자동 수정 |
|
|
120
|
+
|---------|------|----------|
|
|
121
|
+
| `SPEC_HASH_MISMATCH` | spec과 lock 해시 불일치 | ✅ |
|
|
122
|
+
| `GENERATED_MANUAL_EDIT` | generated 파일 수동 수정 | ✅ |
|
|
123
|
+
| `HANDLER_NOT_FOUND` | 핸들러 파일 없음 | ❌ |
|
|
124
|
+
| `COMPONENT_NOT_FOUND` | 컴포넌트 파일 없음 | ❌ |
|
|
125
|
+
| `SLOT_NOT_FOUND` | slot 파일 없음 | ✅ |
|
|
126
|
+
|
|
127
|
+
## Runtime 모듈
|
|
128
|
+
|
|
129
|
+
서버 시작 및 라우팅.
|
|
130
|
+
|
|
131
|
+
```typescript
|
|
132
|
+
import {
|
|
133
|
+
startServer,
|
|
134
|
+
registerApiHandler,
|
|
135
|
+
registerPageLoader
|
|
136
|
+
} from "@mandujs/core";
|
|
137
|
+
|
|
138
|
+
// API 핸들러 등록
|
|
139
|
+
registerApiHandler("getUsers", async (req) => {
|
|
140
|
+
return { users: [] };
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
// 페이지 로더 등록
|
|
144
|
+
registerPageLoader("homePage", () => import("./pages/Home"));
|
|
145
|
+
|
|
146
|
+
// 서버 시작
|
|
147
|
+
const server = startServer(manifest, { port: 3000 });
|
|
148
|
+
|
|
149
|
+
// 종료
|
|
150
|
+
server.stop();
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
## Report 모듈
|
|
154
|
+
|
|
155
|
+
Guard 결과 리포트 생성.
|
|
156
|
+
|
|
157
|
+
```typescript
|
|
158
|
+
import { buildGuardReport } from "@mandujs/core";
|
|
159
|
+
|
|
160
|
+
const report = buildGuardReport(guardResult, lockPath);
|
|
161
|
+
console.log(report); // 포맷된 텍스트 리포트
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
## 타입
|
|
165
|
+
|
|
166
|
+
```typescript
|
|
167
|
+
import type {
|
|
168
|
+
RoutesManifest,
|
|
169
|
+
RouteSpec,
|
|
170
|
+
RouteKind,
|
|
171
|
+
SpecLock,
|
|
172
|
+
GuardResult,
|
|
173
|
+
GuardViolation,
|
|
174
|
+
GenerateResult,
|
|
175
|
+
AutoCorrectResult,
|
|
176
|
+
} from "@mandujs/core";
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
## 요구 사항
|
|
180
|
+
|
|
181
|
+
- Bun >= 1.0.0
|
|
182
|
+
- React >= 18.0.0
|
|
183
|
+
- Zod >= 3.0.0
|
|
184
|
+
|
|
185
|
+
## 관련 패키지
|
|
186
|
+
|
|
187
|
+
- [@mandujs/cli](https://www.npmjs.com/package/@mandujs/cli) - CLI 도구
|
|
188
|
+
|
|
189
|
+
## 라이선스
|
|
190
|
+
|
|
191
|
+
MIT
|
package/README.md
CHANGED
|
@@ -1,34 +1,36 @@
|
|
|
1
1
|
# @mandujs/core
|
|
2
2
|
|
|
3
|
+
> English | **[한국어](./README.ko.md)**
|
|
4
|
+
|
|
3
5
|
Mandu Framework Core - Spec, Generator, Guard, Runtime
|
|
4
6
|
|
|
5
|
-
##
|
|
7
|
+
## Installation
|
|
6
8
|
|
|
7
9
|
```bash
|
|
8
10
|
bun add @mandujs/core
|
|
9
11
|
```
|
|
10
12
|
|
|
11
|
-
>
|
|
13
|
+
> Typically used through `@mandujs/cli`. Direct usage is for advanced use cases.
|
|
12
14
|
|
|
13
|
-
##
|
|
15
|
+
## Module Structure
|
|
14
16
|
|
|
15
17
|
```
|
|
16
18
|
@mandujs/core
|
|
17
|
-
├── spec/ # Spec
|
|
18
|
-
├── generator/ #
|
|
19
|
-
├── guard/ #
|
|
20
|
-
├── runtime/ #
|
|
21
|
-
└── report/ # Guard
|
|
19
|
+
├── spec/ # Spec schema and loading
|
|
20
|
+
├── generator/ # Code generation
|
|
21
|
+
├── guard/ # Architecture checking and auto-correction
|
|
22
|
+
├── runtime/ # Server and router
|
|
23
|
+
└── report/ # Guard report generation
|
|
22
24
|
```
|
|
23
25
|
|
|
24
|
-
## Spec
|
|
26
|
+
## Spec Module
|
|
25
27
|
|
|
26
|
-
|
|
28
|
+
Route manifest schema definition and loading.
|
|
27
29
|
|
|
28
30
|
```typescript
|
|
29
31
|
import { loadManifest, RoutesManifest, RouteSpec } from "@mandujs/core";
|
|
30
32
|
|
|
31
|
-
//
|
|
33
|
+
// Load and validate manifest
|
|
32
34
|
const result = await loadManifest("spec/routes.manifest.json");
|
|
33
35
|
|
|
34
36
|
if (result.success && result.data) {
|
|
@@ -39,33 +41,33 @@ if (result.success && result.data) {
|
|
|
39
41
|
}
|
|
40
42
|
```
|
|
41
43
|
|
|
42
|
-
### Lock
|
|
44
|
+
### Lock File
|
|
43
45
|
|
|
44
46
|
```typescript
|
|
45
47
|
import { writeLock, readLock } from "@mandujs/core";
|
|
46
48
|
|
|
47
|
-
// lock
|
|
49
|
+
// Write lock file
|
|
48
50
|
const lock = await writeLock("spec/spec.lock.json", manifest);
|
|
49
51
|
console.log(lock.routesHash);
|
|
50
52
|
|
|
51
|
-
// lock
|
|
53
|
+
// Read lock file
|
|
52
54
|
const existing = await readLock("spec/spec.lock.json");
|
|
53
55
|
```
|
|
54
56
|
|
|
55
|
-
## Generator
|
|
57
|
+
## Generator Module
|
|
56
58
|
|
|
57
|
-
Spec
|
|
59
|
+
Spec-based code generation.
|
|
58
60
|
|
|
59
61
|
```typescript
|
|
60
62
|
import { generateRoutes, GenerateResult } from "@mandujs/core";
|
|
61
63
|
|
|
62
64
|
const result: GenerateResult = await generateRoutes(manifest, "./");
|
|
63
65
|
|
|
64
|
-
console.log("
|
|
65
|
-
console.log("
|
|
66
|
+
console.log("Created:", result.created);
|
|
67
|
+
console.log("Skipped:", result.skipped); // Existing slot files
|
|
66
68
|
```
|
|
67
69
|
|
|
68
|
-
###
|
|
70
|
+
### Template Functions
|
|
69
71
|
|
|
70
72
|
```typescript
|
|
71
73
|
import {
|
|
@@ -75,19 +77,19 @@ import {
|
|
|
75
77
|
generatePageComponent
|
|
76
78
|
} from "@mandujs/core";
|
|
77
79
|
|
|
78
|
-
// API
|
|
80
|
+
// Generate API handler
|
|
79
81
|
const code = generateApiHandler(route);
|
|
80
82
|
|
|
81
|
-
//
|
|
83
|
+
// API handler with slot
|
|
82
84
|
const codeWithSlot = generateApiHandlerWithSlot(route);
|
|
83
85
|
|
|
84
|
-
// Slot
|
|
86
|
+
// Slot logic file
|
|
85
87
|
const slotCode = generateSlotLogic(route);
|
|
86
88
|
```
|
|
87
89
|
|
|
88
|
-
## Guard
|
|
90
|
+
## Guard Module
|
|
89
91
|
|
|
90
|
-
|
|
92
|
+
Architecture rule checking and auto-correction.
|
|
91
93
|
|
|
92
94
|
```typescript
|
|
93
95
|
import {
|
|
@@ -97,7 +99,7 @@ import {
|
|
|
97
99
|
GuardViolation
|
|
98
100
|
} from "@mandujs/core";
|
|
99
101
|
|
|
100
|
-
//
|
|
102
|
+
// Run check
|
|
101
103
|
const result: GuardResult = await runGuardCheck(manifest, "./");
|
|
102
104
|
|
|
103
105
|
if (!result.passed) {
|
|
@@ -105,26 +107,26 @@ if (!result.passed) {
|
|
|
105
107
|
console.log(`${v.rule}: ${v.message}`);
|
|
106
108
|
});
|
|
107
109
|
|
|
108
|
-
//
|
|
110
|
+
// Run auto-correction
|
|
109
111
|
const corrected = await runAutoCorrect(result.violations, manifest, "./");
|
|
110
|
-
console.log("
|
|
111
|
-
console.log("
|
|
112
|
+
console.log("Fixed:", corrected.steps);
|
|
113
|
+
console.log("Remaining violations:", corrected.remainingViolations);
|
|
112
114
|
}
|
|
113
115
|
```
|
|
114
116
|
|
|
115
|
-
### Guard
|
|
117
|
+
### Guard Rules
|
|
116
118
|
|
|
117
|
-
|
|
|
118
|
-
|
|
119
|
-
| `SPEC_HASH_MISMATCH` |
|
|
120
|
-
| `GENERATED_MANUAL_EDIT` |
|
|
121
|
-
| `HANDLER_NOT_FOUND` |
|
|
122
|
-
| `COMPONENT_NOT_FOUND` |
|
|
123
|
-
| `SLOT_NOT_FOUND` |
|
|
119
|
+
| Rule ID | Description | Auto-correctable |
|
|
120
|
+
|---------|-------------|------------------|
|
|
121
|
+
| `SPEC_HASH_MISMATCH` | Spec and lock hash mismatch | ✅ |
|
|
122
|
+
| `GENERATED_MANUAL_EDIT` | Manual edit to generated file | ✅ |
|
|
123
|
+
| `HANDLER_NOT_FOUND` | Handler file not found | ❌ |
|
|
124
|
+
| `COMPONENT_NOT_FOUND` | Component file not found | ❌ |
|
|
125
|
+
| `SLOT_NOT_FOUND` | Slot file not found | ✅ |
|
|
124
126
|
|
|
125
|
-
## Runtime
|
|
127
|
+
## Runtime Module
|
|
126
128
|
|
|
127
|
-
|
|
129
|
+
Server startup and routing.
|
|
128
130
|
|
|
129
131
|
```typescript
|
|
130
132
|
import {
|
|
@@ -133,33 +135,33 @@ import {
|
|
|
133
135
|
registerPageLoader
|
|
134
136
|
} from "@mandujs/core";
|
|
135
137
|
|
|
136
|
-
// API
|
|
138
|
+
// Register API handler
|
|
137
139
|
registerApiHandler("getUsers", async (req) => {
|
|
138
140
|
return { users: [] };
|
|
139
141
|
});
|
|
140
142
|
|
|
141
|
-
//
|
|
143
|
+
// Register page loader
|
|
142
144
|
registerPageLoader("homePage", () => import("./pages/Home"));
|
|
143
145
|
|
|
144
|
-
//
|
|
146
|
+
// Start server
|
|
145
147
|
const server = startServer(manifest, { port: 3000 });
|
|
146
148
|
|
|
147
|
-
//
|
|
149
|
+
// Stop
|
|
148
150
|
server.stop();
|
|
149
151
|
```
|
|
150
152
|
|
|
151
|
-
## Report
|
|
153
|
+
## Report Module
|
|
152
154
|
|
|
153
|
-
Guard
|
|
155
|
+
Guard result report generation.
|
|
154
156
|
|
|
155
157
|
```typescript
|
|
156
158
|
import { buildGuardReport } from "@mandujs/core";
|
|
157
159
|
|
|
158
160
|
const report = buildGuardReport(guardResult, lockPath);
|
|
159
|
-
console.log(report); //
|
|
161
|
+
console.log(report); // Formatted text report
|
|
160
162
|
```
|
|
161
163
|
|
|
162
|
-
##
|
|
164
|
+
## Types
|
|
163
165
|
|
|
164
166
|
```typescript
|
|
165
167
|
import type {
|
|
@@ -174,16 +176,16 @@ import type {
|
|
|
174
176
|
} from "@mandujs/core";
|
|
175
177
|
```
|
|
176
178
|
|
|
177
|
-
##
|
|
179
|
+
## Requirements
|
|
178
180
|
|
|
179
181
|
- Bun >= 1.0.0
|
|
180
182
|
- React >= 18.0.0
|
|
181
183
|
- Zod >= 3.0.0
|
|
182
184
|
|
|
183
|
-
##
|
|
185
|
+
## Related Packages
|
|
184
186
|
|
|
185
|
-
- [@mandujs/cli](https://www.npmjs.com/package/@mandujs/cli) - CLI
|
|
187
|
+
- [@mandujs/cli](https://www.npmjs.com/package/@mandujs/cli) - CLI tool
|
|
186
188
|
|
|
187
|
-
##
|
|
189
|
+
## License
|
|
188
190
|
|
|
189
191
|
MIT
|
package/package.json
CHANGED
|
@@ -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
|
+
};
|
|
@@ -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
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
65
|
-
|
|
66
|
-
export
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
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
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
)
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
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