@faapi/faapi 0.0.0-canary.4ab8d97 → 0.0.0-canary.4e89b9b
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.md +7 -1
- package/dist/cli/index.js +6056 -5253
- package/dist/cli/index.js.map +1 -1
- package/dist/index.d.ts +423 -66
- package/dist/index.js +2828 -168
- package/dist/index.js.map +1 -1
- package/package.json +7 -5
package/dist/index.d.ts
CHANGED
|
@@ -99,6 +99,14 @@ interface FaapiContext {
|
|
|
99
99
|
headers: Headers;
|
|
100
100
|
method: string;
|
|
101
101
|
path: string;
|
|
102
|
+
/**
|
|
103
|
+
* 客户端 IP
|
|
104
|
+
*
|
|
105
|
+
* 优先 `x-forwarded-for` 第一个 IP(反向代理场景),回退到 socket.remoteAddress。
|
|
106
|
+
* IPv6 形式 `::ffff:1.2.3.4` 会被规整为 IPv4 形式 `1.2.3.4`。
|
|
107
|
+
* 无法获取时为空字符串。
|
|
108
|
+
*/
|
|
109
|
+
ip: string;
|
|
102
110
|
/** 解析后的所有 cookie 键值对 */
|
|
103
111
|
cookies: Record<string, string>;
|
|
104
112
|
/** 配置文件中的自定义业务配置(类型可通过 declare module '@faapi/faapi' 增强 FaapiContextConfig) */
|
|
@@ -111,6 +119,19 @@ interface FaapiContext {
|
|
|
111
119
|
* 设置响应头
|
|
112
120
|
*/
|
|
113
121
|
setHeader(key: string, value: string): void;
|
|
122
|
+
/**
|
|
123
|
+
* 设置 ETag 响应头
|
|
124
|
+
*
|
|
125
|
+
* handler 中基于业务数据(如 updatedAt / version / contentHash)设置 ETag:
|
|
126
|
+
* ```ts
|
|
127
|
+
* export function GET(ctx) {
|
|
128
|
+
* const data = await fetchData();
|
|
129
|
+
* ctx.setETag(`"${data.version}-${data.updatedAt}"`);
|
|
130
|
+
* return data;
|
|
131
|
+
* }
|
|
132
|
+
* ```
|
|
133
|
+
*/
|
|
134
|
+
setETag(value: string): void;
|
|
114
135
|
/**
|
|
115
136
|
* 返回 JSON 响应(handler 直接 return)
|
|
116
137
|
*
|
|
@@ -264,22 +285,50 @@ interface CorsOptions {
|
|
|
264
285
|
*/
|
|
265
286
|
declare function cors(options?: CorsOptions): FaapiMiddleware;
|
|
266
287
|
|
|
288
|
+
type LoggerFn = (messageOrObj: string | Record<string, unknown>, message?: string) => void;
|
|
267
289
|
interface LoggerOptions {
|
|
268
|
-
/**
|
|
269
|
-
|
|
290
|
+
/**
|
|
291
|
+
* 自定义日志函数
|
|
292
|
+
*
|
|
293
|
+
* - 传入 `console.log`(默认):纯文本格式 `GET /api/users 200 12ms`
|
|
294
|
+
* - 传入 pino logger:结构化日志 `logger.info({ method, path, status, durationMs }, 'request completed')`
|
|
295
|
+
* - 传入 winston logger:`logger.info('GET /api/users 200 12ms', { method, path })`
|
|
296
|
+
*/
|
|
297
|
+
log?: LoggerFn;
|
|
270
298
|
}
|
|
271
299
|
/**
|
|
272
300
|
* 创建请求日志中间件(洋葱模型)
|
|
273
301
|
*
|
|
274
|
-
*
|
|
275
|
-
*
|
|
302
|
+
* 日志格式(文本模式):GET /api/users 200 12ms
|
|
303
|
+
* 错误格式(文本模式):POST /api/users 400 45ms - Error: ...
|
|
304
|
+
*
|
|
305
|
+
* 结构化模式:传入 pino/winston 等 logger 实例时,会自动传递结构化字段。
|
|
276
306
|
*
|
|
277
307
|
* before/after 一体,闭包变量共享开始时间,无需污染 ctx。
|
|
278
308
|
* 错误用 try/catch 捕获,记录后重新抛出(让上层处理)。
|
|
279
309
|
* 成功时从 next() 返回的 Response 读取状态码。
|
|
310
|
+
*
|
|
311
|
+
* log 函数每次请求时读取(options.log ?? console.log),运行时替换 console.log 会生效。
|
|
280
312
|
*/
|
|
281
313
|
declare function logger(options?: LoggerOptions): FaapiMiddleware;
|
|
282
314
|
|
|
315
|
+
interface HelmetOptions {
|
|
316
|
+
contentSecurityPolicy?: string | false;
|
|
317
|
+
xFrameOptions?: 'DENY' | 'SAMEORIGIN' | false;
|
|
318
|
+
xContentTypeOptions?: boolean;
|
|
319
|
+
referrerPolicy?: string | false;
|
|
320
|
+
strictTransportSecurity?: string | false;
|
|
321
|
+
xDnsPrefetchControl?: boolean;
|
|
322
|
+
xDownloadOptions?: boolean;
|
|
323
|
+
xPermittedCrossDomainPolicies?: string | false;
|
|
324
|
+
crossOriginOpenerPolicy?: string | false;
|
|
325
|
+
crossOriginResourcePolicy?: string | false;
|
|
326
|
+
crossOriginEmbedderPolicy?: string | false;
|
|
327
|
+
originAgentCluster?: boolean;
|
|
328
|
+
xPoweredBy?: boolean;
|
|
329
|
+
}
|
|
330
|
+
declare function helmet(options?: HelmetOptions): FaapiMiddleware;
|
|
331
|
+
|
|
283
332
|
declare const HTTP_METHODS: readonly ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"];
|
|
284
333
|
type HttpMethod = (typeof HTTP_METHODS)[number];
|
|
285
334
|
|
|
@@ -296,7 +345,26 @@ interface RouteRecord {
|
|
|
296
345
|
/** 路由对应的注入器映射表(从根到路由目录合并,构建时加载) */
|
|
297
346
|
injectors?: InjectorMap;
|
|
298
347
|
}
|
|
348
|
+
/**
|
|
349
|
+
* WebSocket 路由记录
|
|
350
|
+
*
|
|
351
|
+
* 与 HTTP RouteRecord 类似,但不绑定 HTTP 方法(WS 是协议升级,不区分 GET/POST)。
|
|
352
|
+
* 一个 handler.ts 中导出 WS 即生成一条 WS 路由记录。
|
|
353
|
+
*/
|
|
354
|
+
interface WsRouteRecord {
|
|
355
|
+
urlPath: string;
|
|
356
|
+
filePath: string;
|
|
357
|
+
paramNames: string[];
|
|
358
|
+
isDynamic: boolean;
|
|
359
|
+
/** 是否为 catch-all 路由([...slug]) */
|
|
360
|
+
isCatchAll?: boolean;
|
|
361
|
+
/** 路由对应的中间件集合(握手阶段执行,复用鉴权/CORS/日志) */
|
|
362
|
+
middlewares?: FaapiMiddleware[];
|
|
363
|
+
/** 路由对应的注入器映射表 */
|
|
364
|
+
injectors?: InjectorMap;
|
|
365
|
+
}
|
|
299
366
|
type RouteManifest = RouteRecord[];
|
|
367
|
+
type WsRouteManifest = WsRouteRecord[];
|
|
300
368
|
/**
|
|
301
369
|
* 路由单个参数的 schema 描述
|
|
302
370
|
*
|
|
@@ -315,6 +383,18 @@ interface RouteInputSchema {
|
|
|
315
383
|
schemaName: string | null;
|
|
316
384
|
properties: RouteParamSchema[];
|
|
317
385
|
}
|
|
386
|
+
/**
|
|
387
|
+
* 路由响应类型的 schema 描述
|
|
388
|
+
*
|
|
389
|
+
* 由 @faapi/schema 扩展包的 buildRouteSchemas 生成。
|
|
390
|
+
* output 为 null 表示无显式返回类型注解、void/Promise<void>、或解析失败降级。
|
|
391
|
+
*/
|
|
392
|
+
interface RouteOutputSchema {
|
|
393
|
+
/** 命名类型名(如 'UserResponse'),内联类型为 null */
|
|
394
|
+
schemaName: string | null;
|
|
395
|
+
/** 顶层属性列表 */
|
|
396
|
+
properties: RouteParamSchema[];
|
|
397
|
+
}
|
|
318
398
|
/**
|
|
319
399
|
* 路由的完整 schema 描述
|
|
320
400
|
*
|
|
@@ -327,6 +407,8 @@ interface RouteInfo {
|
|
|
327
407
|
filePath: string;
|
|
328
408
|
isDynamic: boolean;
|
|
329
409
|
inputs: RouteInputSchema[];
|
|
410
|
+
/** 响应类型描述(null 表示无返回类型注解/void/解析失败) */
|
|
411
|
+
output: RouteOutputSchema | null;
|
|
330
412
|
}
|
|
331
413
|
|
|
332
414
|
/** HTTP 请求 handler 类型 */
|
|
@@ -344,8 +426,10 @@ type UpgradeHandler = (req: IncomingMessage, socket: Socket, head: Buffer) => vo
|
|
|
344
426
|
interface PluginContext {
|
|
345
427
|
/** 项目根目录 */
|
|
346
428
|
rootDir: string;
|
|
347
|
-
/**
|
|
429
|
+
/** 当前路由清单(setup 时的快照,reloadRoutes 后不会更新;需最新路由用 getRoutes()) */
|
|
348
430
|
routes: RouteManifest;
|
|
431
|
+
/** 获取最新路由清单(reloadRoutes 后返回更新后的数组) */
|
|
432
|
+
getRoutes: () => RouteManifest;
|
|
349
433
|
/** HTTP 服务器实例(未 listen) */
|
|
350
434
|
server: Server;
|
|
351
435
|
/** 自定义业务配置(faapi.config.ts 中的自定义 key) */
|
|
@@ -416,40 +500,31 @@ type PluginDeclaration = string | [string, unknown] | {
|
|
|
416
500
|
options?: unknown;
|
|
417
501
|
};
|
|
418
502
|
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
*/
|
|
425
|
-
type ResponseFormatFn = (data: unknown, ctx: FaapiContext) => unknown;
|
|
426
|
-
/**
|
|
427
|
-
* 错误响应格式化函数
|
|
428
|
-
*
|
|
429
|
-
* 优先于内置 formatErrorResponse 处理错误。返回 Response 表示已处理;
|
|
430
|
-
* 返回 null/undefined 表示不处理,由内置 formatErrorResponse 兜底。
|
|
431
|
-
*/
|
|
432
|
-
type ErrorFormatFn = (error: unknown, ctx?: FaapiContext) => Response | null | undefined;
|
|
503
|
+
interface Http2Options {
|
|
504
|
+
key?: string;
|
|
505
|
+
cert?: string;
|
|
506
|
+
}
|
|
507
|
+
|
|
433
508
|
/**
|
|
434
509
|
* 生命周期钩子
|
|
435
510
|
*/
|
|
436
511
|
interface LifecycleHooks {
|
|
437
|
-
/**
|
|
512
|
+
/** 服务器启动后调用(适合初始化数据库连接等) */
|
|
438
513
|
onReady?: (ctx: LifecycleContext) => Promise<void> | void;
|
|
439
514
|
/** 服务器关闭时调用(适合清理资源、优雅关闭) */
|
|
440
515
|
onClose?: (ctx: LifecycleContext) => Promise<void> | void;
|
|
441
516
|
/**
|
|
442
|
-
*
|
|
517
|
+
* 请求错误已被处理为响应后调用(参考 Fastify onError 语义)
|
|
443
518
|
*
|
|
444
|
-
*
|
|
519
|
+
* 时机:handler 抛错 → 全局中间件 try/catch(若有) → 框架内置 formatErrorResponse 兜底
|
|
445
520
|
* → 响应发出后 → onError 触发副作用
|
|
446
521
|
*
|
|
447
|
-
*
|
|
448
|
-
*
|
|
522
|
+
* 职责:日志上报、告警、链路追踪等副作用。**不修改、不替换已生成的响应**。
|
|
523
|
+
* 自身抛错会被捕获并忽略,不影响响应已发送的事实。
|
|
449
524
|
*
|
|
450
|
-
*
|
|
451
|
-
* -
|
|
452
|
-
* - onError
|
|
525
|
+
* 与全局错误中间件的区别:
|
|
526
|
+
* - 全局错误中间件:把 error 翻译成 Response(主入口,决定响应内容)
|
|
527
|
+
* - onError:响应发出后的副作用(不能改响应)
|
|
453
528
|
*/
|
|
454
529
|
onError?: (error: unknown, ctx: FaapiContext) => Promise<void> | void;
|
|
455
530
|
}
|
|
@@ -471,7 +546,6 @@ interface LifecycleContext {
|
|
|
471
546
|
* ```ts
|
|
472
547
|
* import type { FaapiConfig } from '@faapi/faapi';
|
|
473
548
|
* export default {
|
|
474
|
-
* port: 3000,
|
|
475
549
|
* cors: { origin: '*' },
|
|
476
550
|
* } satisfies FaapiConfig;
|
|
477
551
|
* ```
|
|
@@ -480,7 +554,6 @@ interface LifecycleContext {
|
|
|
480
554
|
* ```ts
|
|
481
555
|
* import type { FaapiConfig } from '@faapi/faapi';
|
|
482
556
|
* export default {
|
|
483
|
-
* port: 3000,
|
|
484
557
|
* cors: { origin: '*' },
|
|
485
558
|
* // 自定义业务配置(任意 key)
|
|
486
559
|
* db: { host: 'localhost', port: 5432 },
|
|
@@ -488,20 +561,24 @@ interface LifecycleContext {
|
|
|
488
561
|
* ```
|
|
489
562
|
*
|
|
490
563
|
* 环境覆盖通过 faapi.config.{NODE_ENV}.ts 实现(如 faapi.config.production.ts)
|
|
564
|
+
*
|
|
565
|
+
* 框架元信息通过环境变量配置(不放在 config 内):
|
|
566
|
+
* - `PORT`:服务端口,默认 3000
|
|
567
|
+
* - `FAAPI_DIST`:产物输出目录,dev 固定为 `.faapi`(不可修改),prod 默认为 `dist`(可通过 `--dist` 修改)
|
|
491
568
|
*/
|
|
492
569
|
interface FaapiConfig {
|
|
493
|
-
/** 服务端口,默认 3000(可被 --port / PORT 环境变量覆盖) */
|
|
494
|
-
port?: number;
|
|
495
|
-
/** 静态文件目录 */
|
|
496
|
-
staticDir?: string;
|
|
497
570
|
/** CORS 配置,false 禁用 */
|
|
498
571
|
cors?: CorsOptions | boolean;
|
|
499
|
-
/** 统一响应格式化函数 */
|
|
500
|
-
responseFormat?: ResponseFormatFn;
|
|
501
|
-
/** 错误响应格式化函数 */
|
|
502
|
-
errorFormat?: ErrorFormatFn;
|
|
503
572
|
/** 生命周期钩子 */
|
|
504
573
|
lifecycle?: LifecycleHooks;
|
|
574
|
+
/** 安全头配置,false 禁用 */
|
|
575
|
+
helmet?: HelmetOptions | boolean;
|
|
576
|
+
/** 请求体大小限制(字节),默认 10MB(10 * 1024 * 1024) */
|
|
577
|
+
bodyLimit?: number;
|
|
578
|
+
/** 日志中间件配置 */
|
|
579
|
+
logger?: LoggerOptions | boolean;
|
|
580
|
+
/** HTTP/2 配置,false 禁用(默认 http/1.1) */
|
|
581
|
+
http2?: Http2Options | boolean;
|
|
505
582
|
/**
|
|
506
583
|
* 全局中间件:对所有路由(HTTP + WebSocket 握手)生效
|
|
507
584
|
*
|
|
@@ -664,6 +741,15 @@ interface WsContext {
|
|
|
664
741
|
*/
|
|
665
742
|
type WsHandler = (ctx: WsContext) => WsEventHandlers | void;
|
|
666
743
|
|
|
744
|
+
/**
|
|
745
|
+
* 清理所有 Program 缓存(watch 模式下文件变化时调用)
|
|
746
|
+
*
|
|
747
|
+
* 全量清理而非增量清理,理由:
|
|
748
|
+
* - 简单可靠,无状态一致性问题
|
|
749
|
+
* - 跨文件类型引用需要所有文件的 Program 同步更新
|
|
750
|
+
* - dev 模式文件量有限,全量重建在百毫秒级
|
|
751
|
+
*/
|
|
752
|
+
declare function invalidateProgramCache(): void;
|
|
667
753
|
/**
|
|
668
754
|
* 为指定文件创建 TypeScript Program(带缓存)
|
|
669
755
|
*
|
|
@@ -725,6 +811,13 @@ type RuntimeType = {
|
|
|
725
811
|
kind: 'record';
|
|
726
812
|
key: RuntimeType;
|
|
727
813
|
value: RuntimeType;
|
|
814
|
+
} | {
|
|
815
|
+
kind: 'map';
|
|
816
|
+
key: RuntimeType;
|
|
817
|
+
value: RuntimeType;
|
|
818
|
+
} | {
|
|
819
|
+
kind: 'set';
|
|
820
|
+
element: RuntimeType;
|
|
728
821
|
} | {
|
|
729
822
|
kind: 'ref';
|
|
730
823
|
name: string;
|
|
@@ -744,7 +837,79 @@ interface PropertyType {
|
|
|
744
837
|
name: string;
|
|
745
838
|
type: RuntimeType;
|
|
746
839
|
optional: boolean;
|
|
840
|
+
/**
|
|
841
|
+
* 字段级 JSDoc 约束标签(@max/@min/@maxLength 等)
|
|
842
|
+
*
|
|
843
|
+
* 来自字段 JSDoc 注释,由 generateZodSchema 转为 zod 链式调用。
|
|
844
|
+
* 约束与字段类型不匹配时在提取阶段抛 SchemaExtractionError。
|
|
845
|
+
*/
|
|
846
|
+
constraints?: TypeConstraint[];
|
|
747
847
|
}
|
|
848
|
+
/**
|
|
849
|
+
* JSDoc 约束标签的运行时描述
|
|
850
|
+
*
|
|
851
|
+
* 由字段 JSDoc 注释提取,对应 zod schema 的链式约束方法。
|
|
852
|
+
* 仅在 PropertyType.constraints 中出现,不挂在嵌套类型(array 元素、tuple 元素等)上。
|
|
853
|
+
*/
|
|
854
|
+
type TypeConstraint = {
|
|
855
|
+
kind: 'max';
|
|
856
|
+
value: number;
|
|
857
|
+
} | {
|
|
858
|
+
kind: 'min';
|
|
859
|
+
value: number;
|
|
860
|
+
} | {
|
|
861
|
+
kind: 'int';
|
|
862
|
+
} | {
|
|
863
|
+
kind: 'positive';
|
|
864
|
+
} | {
|
|
865
|
+
kind: 'negative';
|
|
866
|
+
} | {
|
|
867
|
+
kind: 'nonnegative';
|
|
868
|
+
} | {
|
|
869
|
+
kind: 'nonpositive';
|
|
870
|
+
} | {
|
|
871
|
+
kind: 'maxLength';
|
|
872
|
+
value: number;
|
|
873
|
+
} | {
|
|
874
|
+
kind: 'minLength';
|
|
875
|
+
value: number;
|
|
876
|
+
} | {
|
|
877
|
+
kind: 'length';
|
|
878
|
+
value: number;
|
|
879
|
+
} | {
|
|
880
|
+
kind: 'regex';
|
|
881
|
+
pattern: string;
|
|
882
|
+
flags?: string;
|
|
883
|
+
} | {
|
|
884
|
+
kind: 'email';
|
|
885
|
+
} | {
|
|
886
|
+
kind: 'url';
|
|
887
|
+
} | {
|
|
888
|
+
kind: 'uuid';
|
|
889
|
+
};
|
|
890
|
+
/**
|
|
891
|
+
* 将 TypeScript 类型节点解析为运行时类型描述
|
|
892
|
+
*
|
|
893
|
+
* 支持的类型:
|
|
894
|
+
* - 基础类型:string / number / boolean / null / undefined / any / unknown / void
|
|
895
|
+
* - bigint:不支持(HTTP/JSON 不能传输),AST 提取阶段抛 SchemaExtractionError
|
|
896
|
+
* - 字面量类型:'foo' / 42 / true
|
|
897
|
+
* - 数组类型:T[] / Array<T> / ReadonlyArray<T> / readonly T[]
|
|
898
|
+
* - 元组类型:[string, number] / [string, number?] / [string, ...number[]] / readonly [T, U](按位置校验)
|
|
899
|
+
* - 对象类型:{ name: string; age?: number }(含 readonly 字段修饰符,忽略 readonly)
|
|
900
|
+
* - 联合类型:string | null
|
|
901
|
+
* - 交叉类型:A & B(按对象合并处理)
|
|
902
|
+
* - 引用类型:Date / 其他 interface(递归解析)
|
|
903
|
+
* - 工具类型:Record<K, V> / Partial<T> / Readonly<T>(best effort)
|
|
904
|
+
* - Pick<T, K> / Omit<T, K>:K 支持字面量联合、类型别名、keyof T
|
|
905
|
+
*
|
|
906
|
+
* readonly 是编译期约束,运行时不产生校验语义,所有 readonly 修饰符统一忽略。
|
|
907
|
+
*
|
|
908
|
+
* @param typeNode TypeScript 类型节点
|
|
909
|
+
* @param checker 类型 checker(用于解析引用类型)
|
|
910
|
+
* @param visited 防止递归循环
|
|
911
|
+
*/
|
|
912
|
+
declare function resolveTypeNode(typeNode: ts.TypeNode, checker?: ts.TypeChecker, visited?: Set<string>): RuntimeType;
|
|
748
913
|
|
|
749
914
|
interface HandlerTypeInfo {
|
|
750
915
|
name: string;
|
|
@@ -780,48 +945,240 @@ declare function extractTypeInfo(program: ts.Program, filePath: string, typeName
|
|
|
780
945
|
declare function getInputTypeForMethod(method: string): 'query' | 'body';
|
|
781
946
|
|
|
782
947
|
/**
|
|
783
|
-
*
|
|
948
|
+
* 单个路由的 schema 提取结果
|
|
949
|
+
*
|
|
950
|
+
* key 使用 urlPath(如 '/api/hello')而非 filePath,因为 urlPath 在 dev/prod 完全一致,
|
|
951
|
+
* 无需 remapManifestKeys 桥接 .ts/.js 路径差异。
|
|
784
952
|
*/
|
|
785
|
-
interface
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
953
|
+
interface RouteSchemaSource {
|
|
954
|
+
/** 路由 URL 路径(如 '/api/hello'),作为 schema key */
|
|
955
|
+
urlPath: string;
|
|
956
|
+
/** 源文件绝对路径(用于 generateSchemaFiles 按文件分组生成 zod.js) */
|
|
957
|
+
filePath: string;
|
|
958
|
+
schemaName: string;
|
|
959
|
+
typeInfo: HandlerTypeInfo | null;
|
|
960
|
+
/**
|
|
961
|
+
* 是否对 number/boolean 字段生成 z.preprocess 字符串转换(coerce)。
|
|
962
|
+
*
|
|
963
|
+
* - query/params:始终 coerce=true(URL 来源均为 string)
|
|
964
|
+
* - body:始终 coerce=false(JSON 解析已是天然 JS 类型)
|
|
965
|
+
* - form:coerce=true(form-urlencoded 来源均为 string),由本函数在提取时
|
|
966
|
+
* 检测到 handler 声明 `form` 参数时显式设置。schema 名仍为 `POSTBody`
|
|
967
|
+
* (与 body 共享运行时 schema key),运行时 validateInput 无需感知 form/body 差异。
|
|
968
|
+
*
|
|
969
|
+
* 未设置时由 generateSchemaFileSource 回退到 schemaName 后缀正则推断(Query/Params → true)。
|
|
970
|
+
*/
|
|
971
|
+
coerce?: boolean;
|
|
789
972
|
}
|
|
790
973
|
/**
|
|
791
|
-
*
|
|
974
|
+
* 从路由清单收集 schema 提取所需的原始数据
|
|
975
|
+
*
|
|
976
|
+
* dev 和 prd 共享的核心提取流程:
|
|
977
|
+
* 1. 按文件分组遍历路由
|
|
978
|
+
* 2. 对每个文件 createProgram + extractAllTypes 收集所有类型
|
|
979
|
+
* 3. 用 analyzeInjection + extractTypeInfo 提取每个路由的 schema 类型
|
|
980
|
+
* 4. 同时返回按文件分组的 allTypesMap 和合并后的全局 allTypes
|
|
981
|
+
*
|
|
982
|
+
* 调用方基于返回的 sources 和 allTypes 各自做最终转换:
|
|
983
|
+
* - dev:生成 JS 模块文件 → import 加载(用 allTypesByFile)
|
|
984
|
+
* - prd:生成 JS 模块代码 → SchemaModuleEntry[](用 allTypesByFile)
|
|
792
985
|
*/
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
986
|
+
declare function collectRouteSchemaSources(routes: RouteManifest, rootDir?: string): {
|
|
987
|
+
sources: RouteSchemaSource[];
|
|
988
|
+
/** 按文件分组的类型映射(prd writeSchemaModule 用) */
|
|
989
|
+
allTypesByFile: Map<string, Map<string, HandlerTypeInfo>>;
|
|
990
|
+
/** 合并后的全局类型映射(兼容旧调用方保留,新路径使用 allTypesByFile) */
|
|
991
|
+
mergedAllTypes: Map<string, HandlerTypeInfo>;
|
|
992
|
+
};
|
|
993
|
+
|
|
994
|
+
/**
|
|
995
|
+
* 加载 faapi 配置文件
|
|
996
|
+
*
|
|
997
|
+
* 统一读取 `<dist>/faapi-config.js` 产物:
|
|
998
|
+
* - dev 模式:`faapi dev` 启动时由 `compileConfig` 生成 `.faapi/faapi-config.js`
|
|
999
|
+
* - prod 模式:`faapi build` 时由 `compileConfig` 生成 `dist/faapi-config.js`
|
|
1000
|
+
*
|
|
1001
|
+
* 产物由 `compileConfig` 在构建阶段合并 env 后固化,运行时不读源码、不现场编译、不按 env 合并。
|
|
1002
|
+
*
|
|
1003
|
+
* - 产物存在 → import 并返回 default
|
|
1004
|
+
* - 产物不存在但源码有配置文件 → 抛错(强制 rebuild)
|
|
1005
|
+
* - 源码也无配置文件 → 返回 `null`(配置可选)
|
|
1006
|
+
*
|
|
1007
|
+
* @param rootDir 项目根目录
|
|
1008
|
+
* @param dist 产物目录(如 'dist' 或 '.faapi')
|
|
1009
|
+
* @returns 配置对象,无配置文件时返回 null
|
|
1010
|
+
*/
|
|
1011
|
+
declare function loadConfig(rootDir: string, dist: string): Promise<Partial<FaapiConfig> | null>;
|
|
1012
|
+
|
|
1013
|
+
declare const VALIDATION_ERROR = "VALIDATION_ERROR";
|
|
1014
|
+
declare const ROUTE_NOT_FOUND = "ROUTE_NOT_FOUND";
|
|
1015
|
+
declare const METHOD_NOT_ALLOWED = "METHOD_NOT_ALLOWED";
|
|
1016
|
+
declare const INTERNAL_ERROR = "INTERNAL_ERROR";
|
|
1017
|
+
declare const MODULE_LOAD_ERROR = "MODULE_LOAD_ERROR";
|
|
1018
|
+
type ErrorCode = typeof VALIDATION_ERROR | typeof ROUTE_NOT_FOUND | typeof METHOD_NOT_ALLOWED | typeof INTERNAL_ERROR | typeof MODULE_LOAD_ERROR;
|
|
1019
|
+
|
|
1020
|
+
declare class FaapiError extends Error {
|
|
1021
|
+
readonly code: ErrorCode;
|
|
1022
|
+
readonly statusCode: number;
|
|
1023
|
+
constructor(code: ErrorCode, message: string, statusCode: number);
|
|
1024
|
+
}
|
|
1025
|
+
|
|
1026
|
+
declare class ValidationError extends FaapiError {
|
|
1027
|
+
readonly issues: ValidationIssue[];
|
|
1028
|
+
constructor(message: string, issues: ValidationIssue[]);
|
|
1029
|
+
}
|
|
1030
|
+
declare class RouteNotFoundError extends FaapiError {
|
|
1031
|
+
constructor(path: string);
|
|
1032
|
+
}
|
|
1033
|
+
declare class MethodNotAllowedError extends FaapiError {
|
|
1034
|
+
readonly allowedMethods: string[];
|
|
1035
|
+
constructor(method: string, path: string, allowedMethods: string[]);
|
|
1036
|
+
}
|
|
1037
|
+
declare class InternalError extends FaapiError {
|
|
1038
|
+
constructor(message: string);
|
|
1039
|
+
}
|
|
1040
|
+
declare class ModuleLoadError extends FaapiError {
|
|
1041
|
+
constructor(filePath: string, reason: string);
|
|
798
1042
|
}
|
|
799
1043
|
/**
|
|
800
|
-
*
|
|
1044
|
+
* 校验问题类型
|
|
801
1045
|
*
|
|
802
|
-
*
|
|
803
|
-
*
|
|
1046
|
+
* 结构化错误信息,便于上层(全局错误中间件/前端)按 code 做不同处理,
|
|
1047
|
+
* 不依赖字符串解析。message 仅为人类可读的兜底描述。
|
|
804
1048
|
*
|
|
805
|
-
*
|
|
806
|
-
*
|
|
807
|
-
*
|
|
1049
|
+
* code 与 HTTP 状态码的映射(由 ValidationError 推导):
|
|
1050
|
+
* - INVALID_FORMAT / MISSING_FIELD → 400 Bad Request
|
|
1051
|
+
* - TYPE_MISMATCH / INVALID_VALUE / COERCE_FAILED → 422 Unprocessable Entity
|
|
808
1052
|
*/
|
|
809
|
-
|
|
1053
|
+
interface ValidationIssue {
|
|
1054
|
+
/** 字段路径,如 'user.address.city' */
|
|
1055
|
+
path: string;
|
|
1056
|
+
/** 错误码,机器可读的契约 */
|
|
1057
|
+
code: ValidationErrorCode;
|
|
1058
|
+
/** 期望类型/值,如 'number' / '"admin" | "user"' */
|
|
1059
|
+
expected: string;
|
|
1060
|
+
/** 实际类型/值,如 'string' / 'undefined' */
|
|
1061
|
+
received: string;
|
|
1062
|
+
/** 人类可读的本地化消息(兜底,不保证稳定) */
|
|
1063
|
+
message: string;
|
|
1064
|
+
}
|
|
1065
|
+
type ValidationErrorCode = 'TYPE_MISMATCH' | 'MISSING_FIELD' | 'INVALID_FORMAT' | 'INVALID_VALUE' | 'COERCE_FAILED';
|
|
810
1066
|
|
|
811
1067
|
/**
|
|
812
|
-
*
|
|
1068
|
+
* 从 Request 对象创建 FaapiContext
|
|
1069
|
+
* @param request Web Request 对象
|
|
1070
|
+
* @param params 动态路由参数
|
|
1071
|
+
* @param config 自定义业务配置(来自 faapi.config.ts)
|
|
1072
|
+
* @param ip 客户端 IP(由调用方从 IncomingMessage 提取,HTTP/WS 握手均通过 utils/getClientIp)
|
|
1073
|
+
*/
|
|
1074
|
+
declare function createContext(request: Request, params: Record<string, string>, config?: Record<string, unknown>, ip?: string): FaapiContext;
|
|
1075
|
+
|
|
1076
|
+
/**
|
|
1077
|
+
* 调用路由 handler 并将返回值转为 Response
|
|
813
1078
|
*
|
|
814
|
-
*
|
|
815
|
-
* 1.
|
|
816
|
-
* 2.
|
|
817
|
-
* 3.
|
|
1079
|
+
* 流程(洋葱模型):
|
|
1080
|
+
* 1. 中间件按洋葱模型执行:mw1.before → mw2.before → ... → handler → ... → mw2.after → mw1.after
|
|
1081
|
+
* 2. 中间件不调用 next() 即拦截请求(必须返回 Response)
|
|
1082
|
+
* 3. 中间件可用 try/catch 捕获内层错误
|
|
1083
|
+
* 4. 最内层执行注入器(按需)→ handler
|
|
818
1084
|
*
|
|
819
|
-
*
|
|
1085
|
+
* 注入器与中间件解耦:
|
|
1086
|
+
* - 注入器按 handler 参数名匹配,只执行需要的
|
|
1087
|
+
* - 注入器可读取中间件塞进 ctx 的值
|
|
1088
|
+
*/
|
|
1089
|
+
declare function invokeHandler(handler: (...args: unknown[]) => unknown, ctx: FaapiContext, body?: unknown, middlewares?: FaapiMiddleware[], injectors?: InjectorMap): Promise<Response>;
|
|
1090
|
+
|
|
1091
|
+
interface InjectOptions {
|
|
1092
|
+
method?: string;
|
|
1093
|
+
path?: string;
|
|
1094
|
+
headers?: Record<string, string>;
|
|
1095
|
+
query?: Record<string, string>;
|
|
1096
|
+
body?: unknown;
|
|
1097
|
+
}
|
|
1098
|
+
interface InjectResponse {
|
|
1099
|
+
status: number;
|
|
1100
|
+
headers: Headers;
|
|
1101
|
+
body: unknown;
|
|
1102
|
+
}
|
|
1103
|
+
interface CreateAppOptions {
|
|
1104
|
+
/** 项目根目录,默认 process.cwd() */
|
|
1105
|
+
rootDir?: string;
|
|
1106
|
+
/** 产物输出目录(如 dist 或 .faapi),覆盖环境变量 FAAPI_DIST,默认 'dist' */
|
|
1107
|
+
dist?: string;
|
|
1108
|
+
/** 端口号,也可在 listen() 时传入;默认环境变量 PORT 或 3000 */
|
|
1109
|
+
port?: number;
|
|
1110
|
+
}
|
|
1111
|
+
/** 应用基础接口(dev/prod 共用,不含 reloadRoutes) */
|
|
1112
|
+
interface AppBase {
|
|
1113
|
+
/** Node.js Server 实例(listen 后可用,close 后置 null) */
|
|
1114
|
+
server: Server | null;
|
|
1115
|
+
/** 排序后的路由清单 */
|
|
1116
|
+
routes: RouteManifest;
|
|
1117
|
+
/** WebSocket 路由清单 */
|
|
1118
|
+
wsRoutes: WsRouteManifest;
|
|
1119
|
+
/** 项目根目录 */
|
|
1120
|
+
rootDir: string;
|
|
1121
|
+
/** 启动 HTTP server,打印路由表,执行 onReady 钩子 */
|
|
1122
|
+
listen(port?: number): Promise<Server>;
|
|
1123
|
+
/** 关闭 server,执行 onClose 钩子 */
|
|
1124
|
+
close(): Promise<void>;
|
|
1125
|
+
/**
|
|
1126
|
+
* 无服务器测试注入
|
|
1127
|
+
*
|
|
1128
|
+
* 构建一个模拟请求直接走完整请求链路,不绑定端口。
|
|
1129
|
+
* 需要在 listen() 之前调用(server 未启动时)。
|
|
1130
|
+
*/
|
|
1131
|
+
inject(options?: InjectOptions): Promise<InjectResponse>;
|
|
1132
|
+
}
|
|
1133
|
+
|
|
1134
|
+
/** dev 应用接口(AppBase + reloadRoutes 热替换) */
|
|
1135
|
+
interface DevApp extends AppBase {
|
|
1136
|
+
/** 重新水合路由清单 + 清 schema 缓存 + 更新 server 路由引用(dev 热替换用) */
|
|
1137
|
+
reloadRoutes(): Promise<void>;
|
|
1138
|
+
}
|
|
1139
|
+
/**
|
|
1140
|
+
* dev 模式应用启动 API
|
|
820
1141
|
*
|
|
821
|
-
*
|
|
822
|
-
*
|
|
823
|
-
*
|
|
1142
|
+
* 在 createAppBase(共享逻辑)基础上增加 `reloadRoutes` 热替换能力,供 `faapi dev` watcher 调用。
|
|
1143
|
+
*
|
|
1144
|
+
* 与 createProdApp 的区别:
|
|
1145
|
+
* - dev:含 reloadRoutes(重新扫描路由 + 重新生成 schema + 清缓存 + 更新 server 路由引用)
|
|
1146
|
+
* - prod:精简,无 reloadRoutes(产物已固化,运行时不重建)
|
|
1147
|
+
*
|
|
1148
|
+
* 由 `devCommand` 直接调用,devCommand 持有 app 引用并传给 watcher。
|
|
1149
|
+
*
|
|
1150
|
+
* @example
|
|
1151
|
+
* ```ts
|
|
1152
|
+
* // devCommand 内部
|
|
1153
|
+
* const app = await createDevApp();
|
|
1154
|
+
* await app.listen();
|
|
1155
|
+
* startWatcher({ rootDir, app, devDist });
|
|
1156
|
+
* ```
|
|
1157
|
+
*/
|
|
1158
|
+
declare function createDevApp(options?: CreateAppOptions): Promise<DevApp>;
|
|
1159
|
+
|
|
1160
|
+
/** prod 应用接口(AppBase,无 reloadRoutes) */
|
|
1161
|
+
type ProdApp = AppBase;
|
|
1162
|
+
|
|
1163
|
+
/**
|
|
1164
|
+
* prod 模式应用启动 API
|
|
1165
|
+
*
|
|
1166
|
+
* 直接返回 createAppBase 结果(共享逻辑),不含 dev 专用能力(reloadRoutes、缓存失效)。
|
|
1167
|
+
* 产物在 `faapi build` 阶段已固化,运行时不重建。
|
|
1168
|
+
*
|
|
1169
|
+
* 框架采用零入口设计——用户无需编写 main.ts:
|
|
1170
|
+
* - `faapi build` 自动生成 `dist/main.js` 启动入口,内部调用 `createProdApp()` + `listen()` 启动生产服务器
|
|
1171
|
+
* - 用户自定义启动逻辑通过 `faapi.config.ts` 的 `lifecycle.onReady` / `onClose` 钩子实现
|
|
1172
|
+
*
|
|
1173
|
+
* 编程式调用场景(如自定义 CLI 启动器)也可直接调用:
|
|
1174
|
+
*
|
|
1175
|
+
* @example
|
|
1176
|
+
* ```ts
|
|
1177
|
+
* import { createProdApp } from '@faapi/faapi';
|
|
1178
|
+
* const app = await createProdApp();
|
|
1179
|
+
* await app.listen();
|
|
1180
|
+
* ```
|
|
824
1181
|
*/
|
|
825
|
-
declare function
|
|
1182
|
+
declare function createProdApp(options?: CreateAppOptions): Promise<ProdApp>;
|
|
826
1183
|
|
|
827
|
-
export { type CorsOptions, type
|
|
1184
|
+
export { type ProdApp as App, type CorsOptions, type CreateAppOptions, type DevApp, type FaapiConfig, type FaapiContext, type FaapiContextConfig, FaapiError, type FaapiMiddleware, type FaapiPlugin, type HandlerTypeInfo, type HelmetOptions, type InjectOptions, type InjectResponse, type Injector, type InjectorMap, InternalError, type LifecycleContext, type LifecycleHooks, type LoggerOptions, MethodNotAllowedError, ModuleLoadError, type PluginContext, type PluginDeclaration, type ProdApp, type PropertyType, type RequestHandler, type RouteInfo, type RouteInputSchema, type RouteManifest, RouteNotFoundError, type RouteOutputSchema, type RouteParamSchema, type RouteSchemaSource, type RuntimeType, SchemaExtractionError, type SseEvent, type SseWriter, type TypeConstraint, type UpgradeHandler, ValidationError, type ValidationErrorCode, type ValidationIssue, type WsContext, type WsEventHandlers, type WsHandler, type WsSocket, collectRouteSchemaSources, cors, createProdApp as createApp, createContext, createDevApp, createProdApp, createProgram, extractTypeInfo, getInputTypeForMethod, helmet, invalidateProgramCache, invokeHandler, loadConfig, logger, resolveTypeNode };
|