@mandujs/core 0.12.2 → 0.13.1

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.
@@ -1,569 +1,592 @@
1
- /**
2
- * Mandu Context - 만두 접시 🥟
3
- * Request/Response를 래핑하여 편리한 API 제공
4
- *
5
- * DNA-002: 의존성 주입 패턴 지원
6
- */
7
-
8
- import type { ZodSchema } from "zod";
9
- import type { ContractSchema, ContractMethod } from "../contract/schema";
10
- import type { InferBody, InferHeaders, InferParams, InferQuery, InferResponse } from "../contract/types";
11
- import { ContractValidator, type ContractValidatorOptions } from "../contract/validator";
12
- import { type FillingDeps, createDefaultDeps, globalDeps } from "./deps";
13
-
14
- type ContractInput<
15
- TContract extends ContractSchema,
16
- TMethod extends ContractMethod,
17
- > = {
18
- query: InferQuery<TContract, TMethod>;
19
- body: InferBody<TContract, TMethod>;
20
- params: InferParams<TContract, TMethod>;
21
- headers: InferHeaders<TContract, TMethod>;
22
- };
23
-
24
- // ========== Cookie Types ==========
25
-
26
- export interface CookieOptions {
27
- /** 쿠키 만료 시간 (Date 객체 또는 문자열) */
28
- expires?: Date | string;
29
- /** 쿠키 유효 기간 (초) */
30
- maxAge?: number;
31
- /** 쿠키 도메인 */
32
- domain?: string;
33
- /** 쿠키 경로 */
34
- path?: string;
35
- /** HTTPS에서만 전송 */
36
- secure?: boolean;
37
- /** JavaScript에서 접근 불가 */
38
- httpOnly?: boolean;
39
- /** Same-Site 정책 */
40
- sameSite?: "strict" | "lax" | "none";
41
- /** 파티션 (CHIPS) */
42
- partitioned?: boolean;
43
- }
44
-
45
- /**
46
- * Cookie Manager - 쿠키 읽기/쓰기 관리
47
- */
48
- export class CookieManager {
49
- private requestCookies: Map<string, string>;
50
- private responseCookies: Map<string, { value: string; options: CookieOptions }>;
51
- private deletedCookies: Set<string>;
52
-
53
- constructor(request: Request) {
54
- this.requestCookies = this.parseRequestCookies(request);
55
- this.responseCookies = new Map();
56
- this.deletedCookies = new Set();
57
- }
58
-
59
- private parseRequestCookies(request: Request): Map<string, string> {
60
- const cookies = new Map<string, string>();
61
- const cookieHeader = request.headers.get("cookie");
62
-
63
- if (cookieHeader) {
64
- const pairs = cookieHeader.split(";");
65
- for (const pair of pairs) {
66
- const [name, ...rest] = pair.trim().split("=");
67
- if (name) {
68
- const rawValue = rest.join("=");
69
- try {
70
- cookies.set(name, decodeURIComponent(rawValue));
71
- } catch {
72
- // 잘못된 URL 인코딩 시 원본 값 사용
73
- cookies.set(name, rawValue);
74
- }
75
- }
76
- }
77
- }
78
-
79
- return cookies;
80
- }
81
-
82
- /**
83
- * 쿠키 값 읽기
84
- * @example
85
- * const session = ctx.cookies.get('session');
86
- */
87
- get(name: string): string | undefined {
88
- return this.requestCookies.get(name);
89
- }
90
-
91
- /**
92
- * 쿠키 존재 여부 확인
93
- */
94
- has(name: string): boolean {
95
- return this.requestCookies.has(name);
96
- }
97
-
98
- /**
99
- * 모든 쿠키 가져오기
100
- */
101
- getAll(): Record<string, string> {
102
- return Object.fromEntries(this.requestCookies);
103
- }
104
-
105
- /**
106
- * 쿠키 설정
107
- * @example
108
- * ctx.cookies.set('session', 'abc123', { httpOnly: true, maxAge: 3600 });
109
- */
110
- set(name: string, value: string, options: CookieOptions = {}): void {
111
- this.responseCookies.set(name, { value, options });
112
- this.deletedCookies.delete(name);
113
- }
114
-
115
- /**
116
- * 쿠키 삭제
117
- * @example
118
- * ctx.cookies.delete('session');
119
- */
120
- delete(name: string, options: Pick<CookieOptions, "domain" | "path"> = {}): void {
121
- this.responseCookies.delete(name);
122
- this.deletedCookies.add(name);
123
- // 삭제용 쿠키 설정 (maxAge=0)
124
- this.responseCookies.set(name, {
125
- value: "",
126
- options: {
127
- ...options,
128
- maxAge: 0,
129
- expires: new Date(0),
130
- },
131
- });
132
- }
133
-
134
- /**
135
- * Set-Cookie 헤더 값들 생성
136
- */
137
- getSetCookieHeaders(): string[] {
138
- const headers: string[] = [];
139
-
140
- for (const [name, { value, options }] of this.responseCookies) {
141
- headers.push(this.serializeCookie(name, value, options));
142
- }
143
-
144
- return headers;
145
- }
146
-
147
- /**
148
- * 쿠키를 Set-Cookie 헤더 형식으로 직렬화
149
- */
150
- private serializeCookie(name: string, value: string, options: CookieOptions): string {
151
- const parts: string[] = [`${encodeURIComponent(name)}=${encodeURIComponent(value)}`];
152
-
153
- if (options.maxAge !== undefined) {
154
- parts.push(`Max-Age=${options.maxAge}`);
155
- }
156
-
157
- if (options.expires) {
158
- const expires =
159
- options.expires instanceof Date
160
- ? options.expires.toUTCString()
161
- : options.expires;
162
- parts.push(`Expires=${expires}`);
163
- }
164
-
165
- if (options.domain) {
166
- parts.push(`Domain=${options.domain}`);
167
- }
168
-
169
- if (options.path) {
170
- parts.push(`Path=${options.path}`);
171
- } else {
172
- parts.push("Path=/"); // 기본값
173
- }
174
-
175
- if (options.secure) {
176
- parts.push("Secure");
177
- }
178
-
179
- if (options.httpOnly) {
180
- parts.push("HttpOnly");
181
- }
182
-
183
- if (options.sameSite) {
184
- parts.push(`SameSite=${options.sameSite.charAt(0).toUpperCase() + options.sameSite.slice(1)}`);
185
- }
186
-
187
- if (options.partitioned) {
188
- parts.push("Partitioned");
189
- }
190
-
191
- return parts.join("; ");
192
- }
193
-
194
- /**
195
- * Response에 Set-Cookie 헤더들 적용
196
- */
197
- applyToResponse(response: Response): Response {
198
- const setCookieHeaders = this.getSetCookieHeaders();
199
-
200
- if (setCookieHeaders.length === 0) {
201
- return response;
202
- }
203
-
204
- // Headers를 복사하여 수정
205
- const newHeaders = new Headers(response.headers);
206
-
207
- for (const setCookie of setCookieHeaders) {
208
- newHeaders.append("Set-Cookie", setCookie);
209
- }
210
-
211
- return new Response(response.body, {
212
- status: response.status,
213
- statusText: response.statusText,
214
- headers: newHeaders,
215
- });
216
- }
217
-
218
- /**
219
- * 응답에 적용할 쿠키가 있는지 확인
220
- */
221
- hasPendingCookies(): boolean {
222
- return this.responseCookies.size > 0;
223
- }
224
- }
225
-
226
- // ========== ManduContext ==========
227
-
228
- export class ManduContext {
229
- private store: Map<string, unknown> = new Map();
230
- private _params: Record<string, string>;
231
- private _query: Record<string, string>;
232
- private _cookies: CookieManager;
233
- private _deps: FillingDeps;
234
-
235
- constructor(
236
- public readonly request: Request,
237
- params: Record<string, string> = {},
238
- deps?: FillingDeps
239
- ) {
240
- this._params = params;
241
- this._query = this.parseQuery();
242
- this._cookies = new CookieManager(request);
243
- this._deps = deps ?? globalDeps.get();
244
- }
245
-
246
- /**
247
- * DNA-002: 의존성 접근
248
- *
249
- * @example
250
- * ```ts
251
- * // 데이터베이스 쿼리
252
- * const users = await ctx.deps.db?.query("SELECT * FROM users");
253
- *
254
- * // 캐시 사용
255
- * const cached = await ctx.deps.cache?.get("user:123");
256
- *
257
- * // 로깅
258
- * ctx.deps.logger?.info("User logged in", { userId });
259
- *
260
- * // 현재 시간 (테스트에서 목킹 가능)
261
- * const now = ctx.deps.now?.() ?? new Date();
262
- * ```
263
- */
264
- get deps(): FillingDeps {
265
- return this._deps;
266
- }
267
-
268
- private parseQuery(): Record<string, string> {
269
- const url = new URL(this.request.url);
270
- const query: Record<string, string> = {};
271
- url.searchParams.forEach((value, key) => {
272
- query[key] = value;
273
- });
274
- return query;
275
- }
276
-
277
- // ============================================
278
- // 🥟 Request 읽기
279
- // ============================================
280
-
281
- /** Path parameters (e.g., /users/:id → { id: '123' }) */
282
- get params(): Record<string, string> {
283
- return this._params;
284
- }
285
-
286
- /** Query parameters (e.g., ?name=mandu → { name: 'mandu' }) */
287
- get query(): Record<string, string> {
288
- return this._query;
289
- }
290
-
291
- /** Request headers */
292
- get headers(): Headers {
293
- return this.request.headers;
294
- }
295
-
296
- /** HTTP method */
297
- get method(): string {
298
- return this.request.method;
299
- }
300
-
301
- /** Request URL */
302
- get url(): string {
303
- return this.request.url;
304
- }
305
-
306
- /** Shorthand for request */
307
- get req(): Request {
308
- return this.request;
309
- }
310
-
311
- /**
312
- * Cookie Manager
313
- * @example
314
- * // 쿠키 읽기
315
- * const session = ctx.cookies.get('session');
316
- *
317
- * // 쿠키 설정
318
- * ctx.cookies.set('session', 'abc123', { httpOnly: true, maxAge: 3600 });
319
- *
320
- * // 쿠키 삭제
321
- * ctx.cookies.delete('session');
322
- */
323
- get cookies(): CookieManager {
324
- return this._cookies;
325
- }
326
-
327
- /**
328
- * Parse request body with optional Zod validation
329
- * @example
330
- * const data = await ctx.body() // any
331
- * const data = await ctx.body(UserSchema) // typed & validated
332
- */
333
- async body<T = unknown>(schema?: ZodSchema<T>): Promise<T> {
334
- const contentType = this.request.headers.get("content-type") || "";
335
- let data: unknown;
336
-
337
- if (contentType.includes("application/json")) {
338
- data = await this.request.json();
339
- } else if (contentType.includes("application/x-www-form-urlencoded")) {
340
- const formData = await this.request.formData();
341
- data = Object.fromEntries(formData.entries());
342
- } else if (contentType.includes("multipart/form-data")) {
343
- const formData = await this.request.formData();
344
- data = Object.fromEntries(formData.entries());
345
- } else {
346
- data = await this.request.text();
347
- }
348
-
349
- if (schema) {
350
- const result = schema.safeParse(data);
351
- if (!result.success) {
352
- throw new ValidationError(result.error.errors);
353
- }
354
- return result.data;
355
- }
356
-
357
- return data as T;
358
- }
359
-
360
- /**
361
- * Parse and validate request input via Contract
362
- * @example
363
- * const input = await ctx.input(userContract, "POST", { id: "123" })
364
- */
365
- async input<
366
- TContract extends ContractSchema,
367
- TMethod extends ContractMethod,
368
- >(
369
- contract: TContract,
370
- method: TMethod,
371
- pathParams: Record<string, string> = {},
372
- options: ContractValidatorOptions = {}
373
- ): Promise<ContractInput<TContract, TMethod>> {
374
- const validator = new ContractValidator(contract, options);
375
- const result = await validator.validateAndNormalizeRequest(
376
- this.request,
377
- method,
378
- pathParams
379
- );
380
-
381
- if (!result.success) {
382
- throw new ValidationError(result.errors ?? []);
383
- }
384
-
385
- return (result.data ?? {}) as ContractInput<TContract, TMethod>;
386
- }
387
-
388
- // ============================================
389
- // 🥟 Response 보내기
390
- // ============================================
391
-
392
- /**
393
- * Response에 쿠키 헤더 적용 (내부 사용)
394
- */
395
- private withCookies(response: Response): Response {
396
- if (this._cookies.hasPendingCookies()) {
397
- return this._cookies.applyToResponse(response);
398
- }
399
- return response;
400
- }
401
-
402
- /** 200 OK */
403
- ok<T>(data: T): Response {
404
- return this.json(data, 200);
405
- }
406
-
407
- /** 201 Created */
408
- created<T>(data: T): Response {
409
- return this.json(data, 201);
410
- }
411
-
412
- /** 204 No Content */
413
- noContent(): Response {
414
- return this.withCookies(new Response(null, { status: 204 }));
415
- }
416
-
417
- /** 400 Bad Request */
418
- error(message: string, details?: unknown): Response {
419
- return this.json({ status: "error", message, details }, 400);
420
- }
421
-
422
- /** 401 Unauthorized */
423
- unauthorized(message: string = "Unauthorized"): Response {
424
- return this.json({ status: "error", message }, 401);
425
- }
426
-
427
- /** 403 Forbidden */
428
- forbidden(message: string = "Forbidden"): Response {
429
- return this.json({ status: "error", message }, 403);
430
- }
431
-
432
- /** 404 Not Found */
433
- notFound(message: string = "Not Found"): Response {
434
- return this.json({ status: "error", message }, 404);
435
- }
436
-
437
- /** 500 Internal Server Error */
438
- fail(message: string = "Internal Server Error"): Response {
439
- return this.json({ status: "error", message }, 500);
440
- }
441
-
442
- /** Custom JSON response */
443
- json<T>(data: T, status: number = 200): Response {
444
- const response = Response.json(data, { status });
445
- return this.withCookies(response);
446
- }
447
-
448
- /**
449
- * Validate and send response via Contract
450
- * @example
451
- * return ctx.output(userContract, 200, { data: users })
452
- */
453
- output<
454
- TContract extends ContractSchema,
455
- TStatus extends keyof TContract["response"],
456
- >(
457
- contract: TContract,
458
- status: TStatus,
459
- data: InferResponse<TContract, TStatus>,
460
- options: ContractValidatorOptions = {}
461
- ): Response {
462
- const validator = new ContractValidator(contract, options);
463
- const result = validator.validateResponse(data, Number(status));
464
-
465
- if (!result.success) {
466
- if (options.mode === "strict") {
467
- const errorResponse = Response.json(
468
- {
469
- errorType: "CONTRACT_VIOLATION",
470
- code: "MANDU_C001",
471
- message: "Response does not match contract schema",
472
- summary: "응답이 Contract 스키마와 일치하지 않습니다",
473
- statusCode: Number(status),
474
- violations: result.errors,
475
- timestamp: new Date().toISOString(),
476
- },
477
- { status: 500 }
478
- );
479
- return this.withCookies(errorResponse);
480
- }
481
-
482
- console.warn(
483
- "\x1b[33m[Mandu] Contract violation in response:\x1b[0m",
484
- result.errors
485
- );
486
- }
487
-
488
- const payload = result.success ? result.data : data;
489
- return this.json(payload as InferResponse<TContract, TStatus>, Number(status));
490
- }
491
-
492
- /** 200 OK with Contract validation */
493
- okContract<TContract extends ContractSchema>(
494
- contract: TContract,
495
- data: InferResponse<TContract, 200>,
496
- options: ContractValidatorOptions = {}
497
- ): Response {
498
- return this.output(contract, 200 as keyof TContract["response"], data, options);
499
- }
500
-
501
- /** 201 Created with Contract validation */
502
- createdContract<TContract extends ContractSchema>(
503
- contract: TContract,
504
- data: InferResponse<TContract, 201>,
505
- options: ContractValidatorOptions = {}
506
- ): Response {
507
- return this.output(contract, 201 as keyof TContract["response"], data, options);
508
- }
509
-
510
- /** Custom text response */
511
- text(data: string, status: number = 200): Response {
512
- const response = new Response(data, {
513
- status,
514
- headers: { "Content-Type": "text/plain" },
515
- });
516
- return this.withCookies(response);
517
- }
518
-
519
- /** Custom HTML response */
520
- html(data: string, status: number = 200): Response {
521
- const response = new Response(data, {
522
- status,
523
- headers: { "Content-Type": "text/html" },
524
- });
525
- return this.withCookies(response);
526
- }
527
-
528
- /** Redirect response */
529
- redirect(url: string, status: 301 | 302 | 307 | 308 = 302): Response {
530
- const response = Response.redirect(url, status);
531
- return this.withCookies(response);
532
- }
533
-
534
- // ============================================
535
- // 🥟 상태 저장 (Lifecycle → Handler 전달)
536
- // ============================================
537
-
538
- /** Store value for later use */
539
- set<T>(key: string, value: T): void {
540
- this.store.set(key, value);
541
- }
542
-
543
- /** Get stored value */
544
- get<T>(key: string): T | undefined {
545
- return this.store.get(key) as T | undefined;
546
- }
547
-
548
- /** Check if key exists */
549
- has(key: string): boolean {
550
- return this.store.has(key);
551
- }
552
- }
553
-
554
- /** Route context for error reporting */
555
- export interface ValidationRouteContext {
556
- routeId: string;
557
- pattern: string;
558
- }
559
-
560
- /** Validation error with details */
561
- export class ValidationError extends Error {
562
- constructor(
563
- public readonly errors: unknown[],
564
- public readonly routeContext?: ValidationRouteContext
565
- ) {
566
- super("Validation failed");
567
- this.name = "ValidationError";
568
- }
569
- }
1
+ /**
2
+ * Mandu Context - 만두 접시 🥟
3
+ * Request/Response를 래핑하여 편리한 API 제공
4
+ *
5
+ * DNA-002: 의존성 주입 패턴 지원
6
+ */
7
+
8
+ import type { ZodSchema } from "zod";
9
+ import type { ContractSchema, ContractMethod } from "../contract/schema";
10
+ import type { InferBody, InferHeaders, InferParams, InferQuery, InferResponse } from "../contract/types";
11
+ import { ContractValidator, type ContractValidatorOptions } from "../contract/validator";
12
+ import { type FillingDeps, globalDeps } from "./deps";
13
+ import { createSSEConnection, type SSEOptions, type SSEConnection } from "./sse";
14
+
15
+ type ContractInput<
16
+ TContract extends ContractSchema,
17
+ TMethod extends ContractMethod,
18
+ > = {
19
+ query: InferQuery<TContract, TMethod>;
20
+ body: InferBody<TContract, TMethod>;
21
+ params: InferParams<TContract, TMethod>;
22
+ headers: InferHeaders<TContract, TMethod>;
23
+ };
24
+
25
+ // ========== Cookie Types ==========
26
+
27
+ export interface CookieOptions {
28
+ /** 쿠키 만료 시간 (Date 객체 또는 문자열) */
29
+ expires?: Date | string;
30
+ /** 쿠키 유효 기간 (초) */
31
+ maxAge?: number;
32
+ /** 쿠키 도메인 */
33
+ domain?: string;
34
+ /** 쿠키 경로 */
35
+ path?: string;
36
+ /** HTTPS에서만 전송 */
37
+ secure?: boolean;
38
+ /** JavaScript에서 접근 불가 */
39
+ httpOnly?: boolean;
40
+ /** Same-Site 정책 */
41
+ sameSite?: "strict" | "lax" | "none";
42
+ /** 파티션 키 (CHIPS) */
43
+ partitioned?: boolean;
44
+ }
45
+
46
+ /**
47
+ * Cookie Manager - 쿠키 읽기/쓰기 관리
48
+ */
49
+ export class CookieManager {
50
+ private requestCookies: Map<string, string>;
51
+ private responseCookies: Map<string, { value: string; options: CookieOptions }>;
52
+ private deletedCookies: Set<string>;
53
+
54
+ constructor(request: Request) {
55
+ this.requestCookies = this.parseRequestCookies(request);
56
+ this.responseCookies = new Map();
57
+ this.deletedCookies = new Set();
58
+ }
59
+
60
+ private parseRequestCookies(request: Request): Map<string, string> {
61
+ const cookies = new Map<string, string>();
62
+ const cookieHeader = request.headers.get("cookie");
63
+
64
+ if (cookieHeader) {
65
+ const pairs = cookieHeader.split(";");
66
+ for (const pair of pairs) {
67
+ const [name, ...rest] = pair.trim().split("=");
68
+ if (name) {
69
+ const rawValue = rest.join("=");
70
+ try {
71
+ cookies.set(name, decodeURIComponent(rawValue));
72
+ } catch {
73
+ // 잘못된 URL 인코딩 시 원본 값 사용
74
+ cookies.set(name, rawValue);
75
+ }
76
+ }
77
+ }
78
+ }
79
+
80
+ return cookies;
81
+ }
82
+
83
+ /**
84
+ * 쿠키 값 읽기
85
+ * @example
86
+ * const session = ctx.cookies.get('session');
87
+ */
88
+ get(name: string): string | undefined {
89
+ return this.requestCookies.get(name);
90
+ }
91
+
92
+ /**
93
+ * 쿠키 존재 여부 확인
94
+ */
95
+ has(name: string): boolean {
96
+ return this.requestCookies.has(name);
97
+ }
98
+
99
+ /**
100
+ * 모든 쿠키 가져오기
101
+ */
102
+ getAll(): Record<string, string> {
103
+ return Object.fromEntries(this.requestCookies);
104
+ }
105
+
106
+ /**
107
+ * 쿠키 설정
108
+ * @example
109
+ * ctx.cookies.set('session', 'abc123', { httpOnly: true, maxAge: 3600 });
110
+ */
111
+ set(name: string, value: string, options: CookieOptions = {}): void {
112
+ this.responseCookies.set(name, { value, options });
113
+ this.deletedCookies.delete(name);
114
+ }
115
+
116
+ /**
117
+ * 쿠키 삭제
118
+ * @example
119
+ * ctx.cookies.delete('session');
120
+ */
121
+ delete(name: string, options: Pick<CookieOptions, "domain" | "path"> = {}): void {
122
+ this.responseCookies.delete(name);
123
+ this.deletedCookies.add(name);
124
+ // 삭제용 쿠키 설정 (maxAge=0)
125
+ this.responseCookies.set(name, {
126
+ value: "",
127
+ options: {
128
+ ...options,
129
+ maxAge: 0,
130
+ expires: new Date(0),
131
+ },
132
+ });
133
+ }
134
+
135
+ /**
136
+ * Set-Cookie 헤더 값들 생성
137
+ */
138
+ getSetCookieHeaders(): string[] {
139
+ const headers: string[] = [];
140
+
141
+ for (const [name, { value, options }] of this.responseCookies) {
142
+ headers.push(this.serializeCookie(name, value, options));
143
+ }
144
+
145
+ return headers;
146
+ }
147
+
148
+ /**
149
+ * 쿠키를 Set-Cookie 헤더 형식으로 직렬화
150
+ */
151
+ private serializeCookie(name: string, value: string, options: CookieOptions): string {
152
+ const parts: string[] = [`${encodeURIComponent(name)}=${encodeURIComponent(value)}`];
153
+
154
+ if (options.maxAge !== undefined) {
155
+ parts.push(`Max-Age=${options.maxAge}`);
156
+ }
157
+
158
+ if (options.expires) {
159
+ const expires =
160
+ options.expires instanceof Date
161
+ ? options.expires.toUTCString()
162
+ : options.expires;
163
+ parts.push(`Expires=${expires}`);
164
+ }
165
+
166
+ if (options.domain) {
167
+ parts.push(`Domain=${options.domain}`);
168
+ }
169
+
170
+ if (options.path) {
171
+ parts.push(`Path=${options.path}`);
172
+ } else {
173
+ parts.push("Path=/"); // 기본값
174
+ }
175
+
176
+ if (options.secure) {
177
+ parts.push("Secure");
178
+ }
179
+
180
+ if (options.httpOnly) {
181
+ parts.push("HttpOnly");
182
+ }
183
+
184
+ if (options.sameSite) {
185
+ parts.push(`SameSite=${options.sameSite.charAt(0).toUpperCase() + options.sameSite.slice(1)}`);
186
+ }
187
+
188
+ if (options.partitioned) {
189
+ parts.push("Partitioned");
190
+ }
191
+
192
+ return parts.join("; ");
193
+ }
194
+
195
+ /**
196
+ * Response에 Set-Cookie 헤더들 적용
197
+ */
198
+ applyToResponse(response: Response): Response {
199
+ const setCookieHeaders = this.getSetCookieHeaders();
200
+
201
+ if (setCookieHeaders.length === 0) {
202
+ return response;
203
+ }
204
+
205
+ // Headers를 복사하여 수정
206
+ const newHeaders = new Headers(response.headers);
207
+
208
+ for (const setCookie of setCookieHeaders) {
209
+ newHeaders.append("Set-Cookie", setCookie);
210
+ }
211
+
212
+ return new Response(response.body, {
213
+ status: response.status,
214
+ statusText: response.statusText,
215
+ headers: newHeaders,
216
+ });
217
+ }
218
+
219
+ /**
220
+ * 응답에 적용할 쿠키가 있는지 확인
221
+ */
222
+ hasPendingCookies(): boolean {
223
+ return this.responseCookies.size > 0;
224
+ }
225
+ }
226
+
227
+ // ========== ManduContext ==========
228
+
229
+ export class ManduContext {
230
+ private store: Map<string, unknown> = new Map();
231
+ private _params: Record<string, string>;
232
+ private _query: Record<string, string>;
233
+ private _cookies: CookieManager;
234
+ private _deps: FillingDeps;
235
+
236
+ constructor(
237
+ public readonly request: Request,
238
+ params: Record<string, string> = {},
239
+ deps?: FillingDeps
240
+ ) {
241
+ this._params = params;
242
+ this._query = this.parseQuery();
243
+ this._cookies = new CookieManager(request);
244
+ this._deps = deps ?? globalDeps.get();
245
+ }
246
+
247
+ /**
248
+ * DNA-002: 의존성 접근
249
+ *
250
+ * @example
251
+ * ```ts
252
+ * // 데이터베이스 쿼리
253
+ * const users = await ctx.deps.db?.query("SELECT * FROM users");
254
+ *
255
+ * // 캐시 사용
256
+ * const cached = await ctx.deps.cache?.get("user:123");
257
+ *
258
+ * // 로깅
259
+ * ctx.deps.logger?.info("User logged in", { userId });
260
+ *
261
+ * // 현재 시간 (테스트에서 목킹 가능)
262
+ * const now = ctx.deps.now?.() ?? new Date();
263
+ * ```
264
+ */
265
+ get deps(): FillingDeps {
266
+ return this._deps;
267
+ }
268
+
269
+ private parseQuery(): Record<string, string> {
270
+ const url = new URL(this.request.url);
271
+ const query: Record<string, string> = {};
272
+ url.searchParams.forEach((value, key) => {
273
+ query[key] = value;
274
+ });
275
+ return query;
276
+ }
277
+
278
+ // ============================================
279
+ // 🥟 Request 읽기
280
+ // ============================================
281
+
282
+ /** Path parameters (e.g., /users/:id → { id: '123' }) */
283
+ get params(): Record<string, string> {
284
+ return this._params;
285
+ }
286
+
287
+ /** Query parameters (e.g., ?name=mandu → { name: 'mandu' }) */
288
+ get query(): Record<string, string> {
289
+ return this._query;
290
+ }
291
+
292
+ /** Request headers */
293
+ get headers(): Headers {
294
+ return this.request.headers;
295
+ }
296
+
297
+ /** HTTP method */
298
+ get method(): string {
299
+ return this.request.method;
300
+ }
301
+
302
+ /** Request URL */
303
+ get url(): string {
304
+ return this.request.url;
305
+ }
306
+
307
+ /** Shorthand for request */
308
+ get req(): Request {
309
+ return this.request;
310
+ }
311
+
312
+ /**
313
+ * Cookie Manager
314
+ * @example
315
+ * // 쿠키 읽기
316
+ * const session = ctx.cookies.get('session');
317
+ *
318
+ * // 쿠키 설정
319
+ * ctx.cookies.set('session', 'abc123', { httpOnly: true, maxAge: 3600 });
320
+ *
321
+ * // 쿠키 삭제
322
+ * ctx.cookies.delete('session');
323
+ */
324
+ get cookies(): CookieManager {
325
+ return this._cookies;
326
+ }
327
+
328
+ /**
329
+ * Parse request body with optional Zod validation
330
+ * @example
331
+ * const data = await ctx.body() // any
332
+ * const data = await ctx.body(UserSchema) // typed & validated
333
+ */
334
+ async body<T = unknown>(schema?: ZodSchema<T>): Promise<T> {
335
+ const contentType = this.request.headers.get("content-type") || "";
336
+ let data: unknown;
337
+
338
+ if (contentType.includes("application/json")) {
339
+ data = await this.request.json();
340
+ } else if (contentType.includes("application/x-www-form-urlencoded")) {
341
+ const formData = await this.request.formData();
342
+ data = Object.fromEntries(formData.entries());
343
+ } else if (contentType.includes("multipart/form-data")) {
344
+ const formData = await this.request.formData();
345
+ data = Object.fromEntries(formData.entries());
346
+ } else {
347
+ data = await this.request.text();
348
+ }
349
+
350
+ if (schema) {
351
+ const result = schema.safeParse(data);
352
+ if (!result.success) {
353
+ throw new ValidationError(result.error.errors);
354
+ }
355
+ return result.data;
356
+ }
357
+
358
+ return data as T;
359
+ }
360
+
361
+ /**
362
+ * Parse and validate request input via Contract
363
+ * @example
364
+ * const input = await ctx.input(userContract, "POST", { id: "123" })
365
+ */
366
+ async input<
367
+ TContract extends ContractSchema,
368
+ TMethod extends ContractMethod,
369
+ >(
370
+ contract: TContract,
371
+ method: TMethod,
372
+ pathParams: Record<string, string> = {},
373
+ options: ContractValidatorOptions = {}
374
+ ): Promise<ContractInput<TContract, TMethod>> {
375
+ const validator = new ContractValidator(contract, options);
376
+ const result = await validator.validateAndNormalizeRequest(
377
+ this.request,
378
+ method,
379
+ pathParams
380
+ );
381
+
382
+ if (!result.success) {
383
+ throw new ValidationError(result.errors ?? []);
384
+ }
385
+
386
+ return (result.data ?? {}) as ContractInput<TContract, TMethod>;
387
+ }
388
+
389
+ // ============================================
390
+ // 🥟 Response 보내기
391
+ // ============================================
392
+
393
+ /**
394
+ * Response에 쿠키 헤더 적용 (내부 사용)
395
+ */
396
+ private withCookies(response: Response): Response {
397
+ if (this._cookies.hasPendingCookies()) {
398
+ return this._cookies.applyToResponse(response);
399
+ }
400
+ return response;
401
+ }
402
+
403
+ /** 200 OK */
404
+ ok<T>(data: T): Response {
405
+ return this.json(data, 200);
406
+ }
407
+
408
+ /** 201 Created */
409
+ created<T>(data: T): Response {
410
+ return this.json(data, 201);
411
+ }
412
+
413
+ /** 204 No Content */
414
+ noContent(): Response {
415
+ return this.withCookies(new Response(null, { status: 204 }));
416
+ }
417
+
418
+ /** 400 Bad Request */
419
+ error(message: string, details?: unknown): Response {
420
+ return this.json({ status: "error", message, details }, 400);
421
+ }
422
+
423
+ /** 401 Unauthorized */
424
+ unauthorized(message: string = "Unauthorized"): Response {
425
+ return this.json({ status: "error", message }, 401);
426
+ }
427
+
428
+ /** 403 Forbidden */
429
+ forbidden(message: string = "Forbidden"): Response {
430
+ return this.json({ status: "error", message }, 403);
431
+ }
432
+
433
+ /** 404 Not Found */
434
+ notFound(message: string = "Not Found"): Response {
435
+ return this.json({ status: "error", message }, 404);
436
+ }
437
+
438
+ /** 500 Internal Server Error */
439
+ fail(message: string = "Internal Server Error"): Response {
440
+ return this.json({ status: "error", message }, 500);
441
+ }
442
+
443
+ /** Custom JSON response */
444
+ json<T>(data: T, status: number = 200): Response {
445
+ const response = Response.json(data, { status });
446
+ return this.withCookies(response);
447
+ }
448
+
449
+ /**
450
+ * Validate and send response via Contract
451
+ * @example
452
+ * return ctx.output(userContract, 200, { data: users })
453
+ */
454
+ output<
455
+ TContract extends ContractSchema,
456
+ TStatus extends keyof TContract["response"],
457
+ >(
458
+ contract: TContract,
459
+ status: TStatus,
460
+ data: InferResponse<TContract, TStatus>,
461
+ options: ContractValidatorOptions = {}
462
+ ): Response {
463
+ const validator = new ContractValidator(contract, options);
464
+ const result = validator.validateResponse(data, Number(status));
465
+
466
+ if (!result.success) {
467
+ if (options.mode === "strict") {
468
+ const errorResponse = Response.json(
469
+ {
470
+ errorType: "CONTRACT_VIOLATION",
471
+ code: "MANDU_C001",
472
+ message: "Response does not match contract schema",
473
+ summary: "응답이 Contract 스키마와 일치하지 않습니다",
474
+ statusCode: Number(status),
475
+ violations: result.errors,
476
+ timestamp: new Date().toISOString(),
477
+ },
478
+ { status: 500 }
479
+ );
480
+ return this.withCookies(errorResponse);
481
+ }
482
+
483
+ console.warn(
484
+ "\x1b[33m[Mandu] Contract violation in response:\x1b[0m",
485
+ result.errors
486
+ );
487
+ }
488
+
489
+ const payload = result.success ? result.data : data;
490
+ return this.json(payload as InferResponse<TContract, TStatus>, Number(status));
491
+ }
492
+
493
+ /** 200 OK with Contract validation */
494
+ okContract<TContract extends ContractSchema>(
495
+ contract: TContract,
496
+ data: InferResponse<TContract, 200>,
497
+ options: ContractValidatorOptions = {}
498
+ ): Response {
499
+ return this.output(contract, 200 as keyof TContract["response"], data, options);
500
+ }
501
+
502
+ /** 201 Created with Contract validation */
503
+ createdContract<TContract extends ContractSchema>(
504
+ contract: TContract,
505
+ data: InferResponse<TContract, 201>,
506
+ options: ContractValidatorOptions = {}
507
+ ): Response {
508
+ return this.output(contract, 201 as keyof TContract["response"], data, options);
509
+ }
510
+
511
+ /** Custom text response */
512
+ text(data: string, status: number = 200): Response {
513
+ const response = new Response(data, {
514
+ status,
515
+ headers: { "Content-Type": "text/plain" },
516
+ });
517
+ return this.withCookies(response);
518
+ }
519
+
520
+ /** Custom HTML response */
521
+ html(data: string, status: number = 200): Response {
522
+ const response = new Response(data, {
523
+ status,
524
+ headers: { "Content-Type": "text/html" },
525
+ });
526
+ return this.withCookies(response);
527
+ }
528
+
529
+ /** Redirect response */
530
+ redirect(url: string, status: 301 | 302 | 307 | 308 = 302): Response {
531
+ const response = Response.redirect(url, status);
532
+ return this.withCookies(response);
533
+ }
534
+
535
+ /**
536
+ * Create a Server-Sent Events (SSE) response.
537
+ *
538
+ * @example
539
+ * return ctx.sse((sse) => {
540
+ * sse.event("ready", { ok: true });
541
+ * const stop = sse.heartbeat(15000);
542
+ * sse.onClose(() => stop());
543
+ * });
544
+ */
545
+ sse(setup?: (connection: SSEConnection) => void | Promise<void>, options: SSEOptions = {}): Response {
546
+ const connection = createSSEConnection(this.request.signal, options);
547
+
548
+ if (setup) {
549
+ Promise.resolve(setup(connection)).catch(() => {
550
+ void connection.close();
551
+ });
552
+ }
553
+
554
+ return this.withCookies(connection.response);
555
+ }
556
+
557
+ // ============================================
558
+ // 🥟 상태 저장 (Lifecycle → Handler 전달)
559
+ // ============================================
560
+
561
+ /** Store value for later use */
562
+ set<T>(key: string, value: T): void {
563
+ this.store.set(key, value);
564
+ }
565
+
566
+ /** Get stored value */
567
+ get<T>(key: string): T | undefined {
568
+ return this.store.get(key) as T | undefined;
569
+ }
570
+
571
+ /** Check if key exists */
572
+ has(key: string): boolean {
573
+ return this.store.has(key);
574
+ }
575
+ }
576
+
577
+ /** Route context for error reporting */
578
+ export interface ValidationRouteContext {
579
+ routeId: string;
580
+ pattern: string;
581
+ }
582
+
583
+ /** Validation error with details */
584
+ export class ValidationError extends Error {
585
+ constructor(
586
+ public readonly errors: unknown[],
587
+ public readonly routeContext?: ValidationRouteContext
588
+ ) {
589
+ super("Validation failed");
590
+ this.name = "ValidationError";
591
+ }
592
+ }