context.ts
2.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import type { IncomingMessage, ServerResponse } from 'node:http';
import type { JobStore } from '../jobStore';
import type { JobQueue } from '../queue';
import type { PreviewManager } from '../preview';
import type { ProjectRunner } from '../project-runner';
import type { resolveServerOptions, loadServerModelConfig } from '../config';
import type { SystemStatus, LogEntry } from '../types';
/**
* 注入到所有路由 handler 的共享上下文。
* 等价于原 server.ts 闭包内共享的依赖与辅助函数,集中到一个对象里传递,
* 避免每个 handler 各自携带一长串参数。
*/
export interface ServerCtx {
store: JobStore;
queue: JobQueue;
preview: PreviewManager;
projectRunner: ProjectRunner;
opts: ReturnType<typeof resolveServerOptions>;
startTime: number;
serverVersion: string;
coderioVersion: string;
admin: { restart: () => void; shutdown: () => void };
model: ReturnType<typeof loadServerModelConfig>;
sseClients: Set<ServerResponse>;
recentLogs: LogEntry[];
broadcast: (event: string, data: unknown) => void;
sendJson: (res: ServerResponse, code: number, obj: unknown) => void;
readJsonBody: <T = Record<string, unknown>>(req: IncomingMessage) => Promise<T>;
/** 读取请求体并按 zod schema 校验;失败抛 `ValidationError`(全局映射为 400)。 */
parseJsonBody: <S extends import('zod').ZodTypeAny>(
req: IncomingMessage,
schema: S,
) => Promise<import('zod').z.infer<S>>;
computeStatus: () => SystemStatus;
/** 是否由后端托管 UI(COD_SERVE_WEB !== '0')。 */
SERVE_WEB: boolean;
/** Phase 2 前端构建产物目录;仅 SERVE_WEB 时有效。 */
WEB_DIST: string | undefined;
}
/** 一次请求 + 匹配出的路径参数,统一传给 handler。 */
export interface RouteContext {
ctx: ServerCtx;
req: IncomingMessage;
res: ServerResponse;
url: URL;
params: Record<string, string>;
}
/**
* 单条路由定义。
* handle 返回值语义:返回 `false` 表示“未处理,继续尝试下一条路由”;
* 返回 `true` / `undefined` / `void` 表示已处理(无论响应内容是什么)。
* 这用于实现 SPA fallback 等“条件命中”的路由。
*/
export interface Route {
method: string;
/** 精确路径,或含 `:param`(单段)与 `*`(`/assets/*` 等通配)的模式。 */
path: string;
handle: (rc: RouteContext) => Promise<boolean | void> | boolean | void;
}