@faapi/faapi 6.24.0 → 6.26.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.
@@ -363,7 +363,11 @@ interface TaskWorkerOptions {
363
363
  /** signal 由执行器构造(abort/terminate 时触发),宿主只传 config 与 job 信息 */
364
364
  taskCtx: {
365
365
  config: unknown;
366
- /** 产物 resources 目录绝对路径(纯字符串可结构化克隆,worker 内挂到 taskCtx) */
366
+ /**
367
+ * 产物 resources 目录绝对路径(纯字符串可结构化克隆)——两处用途:经
368
+ * workerData 传给入口在任务模块求值前播种全局读取根 + 挂到 worker 内的
369
+ * taskCtx(业务方了解/拼接资源位置)
370
+ */
367
371
  resourcesDir?: string;
368
372
  job: {
369
373
  id: string;
@@ -1050,8 +1054,9 @@ interface FaapiContext {
1050
1054
  /**
1051
1055
  * 运行时资源根目录绝对路径(<rootDir>/<dist>/resources)
1052
1056
  *
1053
- * `src/resources/` 经 dev/build 复制进产物后的位置,handler 读静态文件用:
1054
- * `await fs.readFile(path.join(ctx.resourcesDir, 'prompts/foo.md'))`。
1057
+ * `src/resources/` 经 dev/build 复制进产物后的位置。数据字段——读取统一走
1058
+ * 免传参的 `readResource('prompts/foo.md')`(app 启动时绑定,见
1059
+ * src/utils/readResource.md),本字段供业务方了解/拼接资源位置。
1055
1060
  * HTTP/WS 请求链路恒有值;testing 直调(createTestContext)未传时为 undefined。
1056
1061
  */
1057
1062
  resourcesDir?: string;
@@ -1170,205 +1175,4 @@ interface FaapiContext {
1170
1175
  deleteCookie(name: string): void;
1171
1176
  }
1172
1177
 
1173
- /**
1174
- * faapi 中间件(洋葱模型)
1175
- *
1176
- * 单一 async 函数,通过 `await next()` 衔接前置/后置逻辑:
1177
- * - `await next()` 之前的代码:前置处理(鉴权、日志开始计时等)
1178
- * - `await next()` 之后的代码:后置处理(日志输出、响应修改等)
1179
- * - 不调用 `next()` 即拦截请求(如鉴权失败直接返回 Response)
1180
- * - `next()` 返回内层 Response,中间件可选择使用或替换
1181
- * - 返回 `Response`:作为响应返回(可用于拦截或错误处理)
1182
- * - 返回 `void`:使用 `await next()` 返回的内层响应
1183
- *
1184
- * 错误处理用 try/catch 包裹 `await next()`,而非独立的 error 钩子。
1185
- *
1186
- * 执行顺序(洋葱模型):
1187
- * ```
1188
- * mw1.before → mw2.before → handler → mw2.after → mw1.after
1189
- * ```
1190
- *
1191
- * 示例 middlewares.ts:
1192
- * ```ts
1193
- * import type { FaapiMiddleware } from '@faapi/faapi';
1194
- *
1195
- * export default [
1196
- * // 鉴权:不调 next() 即拦截
1197
- * async (ctx, next) => {
1198
- * const token = ctx.headers.get('authorization');
1199
- * if (!token) return new Response('Unauthorized', { status: 401 });
1200
- * ctx.user = await verifyToken(token);
1201
- * await next();
1202
- * },
1203
- * // 日志:before/after 一体,闭包共享状态
1204
- * async (ctx, next) => {
1205
- * const start = Date.now();
1206
- * await next();
1207
- * console.log(`${ctx.method} ${ctx.path} ${Date.now() - start}ms`);
1208
- * },
1209
- * // 错误处理:try/catch 语义
1210
- * async (ctx, next) => {
1211
- * try {
1212
- * await next();
1213
- * } catch (err) {
1214
- * return new Response(JSON.stringify({ error: String(err) }), { status: 500 });
1215
- * }
1216
- * },
1217
- * ] satisfies FaapiMiddleware[];
1218
- * ```
1219
- */
1220
- type FaapiMiddleware = (ctx: FaapiContext, next: () => Promise<Response>) => Promise<void | Response>;
1221
-
1222
- /**
1223
- * 注入器:按参数名匹配,提供 handler 所需的依赖
1224
- *
1225
- * 注入器是 faapi 的依赖注入扩展点,与中间件解耦:
1226
- * - 中间件只管请求流程(鉴权、日志、错误处理)
1227
- * - 注入器只管提供依赖(数据库连接、用户对象等)
1228
- *
1229
- * 注入器可以读取中间件塞进 ctx 的值(如鉴权中间件塞的 ctx.user),
1230
- * 也可以独立提供依赖(如数据库连接池)。
1231
- *
1232
- * 注入器按需执行:只对 handler 声明的参数执行对应的注入器,避免无谓计算。
1233
- *
1234
- * 在 middlewares.ts 中通过命名导出 `injectors` 注册:
1235
- * ```ts
1236
- * import type { InjectorMap } from '@faapi/faapi';
1237
- *
1238
- * export const injectors: InjectorMap = {
1239
- * db: () => getDbConnection(),
1240
- * user: (ctx) => ctx.user, // 取中间件塞的值
1241
- * };
1242
- * ```
1243
- */
1244
- type Injector = (ctx: FaapiContext) => unknown | Promise<unknown>;
1245
- /**
1246
- * 注入器映射表:参数名 → 注入器函数
1247
- *
1248
- * key 必须与 handler 参数名一致,运行时按参数名匹配执行。
1249
- */
1250
- type InjectorMap = Record<string, Injector>;
1251
-
1252
- interface CorsOptions {
1253
- origin?: string | string[] | true;
1254
- methods?: string[];
1255
- allowedHeaders?: string[];
1256
- exposeHeaders?: string[];
1257
- credentials?: boolean;
1258
- maxAge?: number;
1259
- }
1260
- /**
1261
- * 创建 CORS 中间件(洋葱模型)
1262
- *
1263
- * - origin=true: 允许所有来源(反射请求的 Origin)
1264
- * - origin=string: 允许指定来源
1265
- * - origin=string[]: 允许多个来源
1266
- *
1267
- * OPTIONS 预检请求直接返回 204,不调用 next()。
1268
- */
1269
- declare function cors(options?: CorsOptions): FaapiMiddleware;
1270
-
1271
- interface HelmetOptions {
1272
- contentSecurityPolicy?: string | false;
1273
- xFrameOptions?: 'DENY' | 'SAMEORIGIN' | false;
1274
- xContentTypeOptions?: boolean;
1275
- referrerPolicy?: string | false;
1276
- strictTransportSecurity?: string | false;
1277
- xDnsPrefetchControl?: boolean;
1278
- xDownloadOptions?: boolean;
1279
- xPermittedCrossDomainPolicies?: string | false;
1280
- crossOriginOpenerPolicy?: string | false;
1281
- crossOriginResourcePolicy?: string | false;
1282
- crossOriginEmbedderPolicy?: string | false;
1283
- originAgentCluster?: boolean;
1284
- xPoweredBy?: boolean;
1285
- }
1286
- declare function helmet(options?: HelmetOptions): FaapiMiddleware;
1287
-
1288
- declare const HTTP_METHODS: readonly ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"];
1289
- type HttpMethod = (typeof HTTP_METHODS)[number];
1290
-
1291
- interface RouteRecord {
1292
- method: HttpMethod;
1293
- urlPath: string;
1294
- filePath: string;
1295
- paramNames: string[];
1296
- isDynamic: boolean;
1297
- /** 是否为 catch-all 路由([...slug]) */
1298
- isCatchAll?: boolean;
1299
- /** 中间件文件绝对路径列表(根在前,路由目录在后;按需加载用) */
1300
- middlewarePaths?: string[];
1301
- /** 路由对应的中间件集合(从根到路由目录合并,按需加载后缓存) */
1302
- middlewares?: FaapiMiddleware[];
1303
- /** 路由对应的注入器映射表(从根到路由目录合并,按需加载后缓存) */
1304
- injectors?: InjectorMap;
1305
- }
1306
- /**
1307
- * WebSocket 路由记录
1308
- *
1309
- * 与 HTTP RouteRecord 类似,但不绑定 HTTP 方法(WS 是协议升级,不区分 GET/POST)。
1310
- * 一个 handler.ts 中导出 WS 即生成一条 WS 路由记录。
1311
- */
1312
- interface WsRouteRecord {
1313
- urlPath: string;
1314
- filePath: string;
1315
- paramNames: string[];
1316
- isDynamic: boolean;
1317
- /** 是否为 catch-all 路由([...slug]) */
1318
- isCatchAll?: boolean;
1319
- /** 中间件文件绝对路径列表(根在前,路由目录在后;按需加载用) */
1320
- middlewarePaths?: string[];
1321
- /** 路由对应的中间件集合(握手阶段执行,复用鉴权/CORS/日志;按需加载后缓存) */
1322
- middlewares?: FaapiMiddleware[];
1323
- /** 路由对应的注入器映射表 */
1324
- injectors?: InjectorMap;
1325
- }
1326
- type RouteManifest = RouteRecord[];
1327
- type WsRouteManifest = WsRouteRecord[];
1328
- /**
1329
- * 路由单个参数的 schema 描述
1330
- *
1331
- * 供 @faapi/schema 扩展包消费,通过 MCP 暴露给 LLM。
1332
- */
1333
- interface RouteParamSchema {
1334
- name: string;
1335
- type: string;
1336
- required: boolean;
1337
- }
1338
- /**
1339
- * 路由单个输入源的 schema 描述
1340
- */
1341
- interface RouteInputSchema {
1342
- source: 'query' | 'body' | 'params';
1343
- schemaName: string | null;
1344
- properties: RouteParamSchema[];
1345
- }
1346
- /**
1347
- * 路由响应类型的 schema 描述
1348
- *
1349
- * 由 @faapi/schema 扩展包的 buildRouteSchemas 生成。
1350
- * output 为 null 表示无显式返回类型注解、void/Promise<void>、或解析失败降级。
1351
- */
1352
- interface RouteOutputSchema {
1353
- /** 命名类型名(如 'UserResponse'),内联类型为 null */
1354
- schemaName: string | null;
1355
- /** 顶层属性列表 */
1356
- properties: RouteParamSchema[];
1357
- }
1358
- /**
1359
- * 路由的完整 schema 描述
1360
- *
1361
- * 由 @faapi/schema 扩展包的 buildRouteSchemas 生成。
1362
- * 主包只定义类型契约,逻辑实现在扩展包。
1363
- */
1364
- interface RouteInfo {
1365
- method: string;
1366
- path: string;
1367
- filePath: string;
1368
- isDynamic: boolean;
1369
- inputs: RouteInputSchema[];
1370
- /** 响应类型描述(null 表示无返回类型注解/void/解析失败) */
1371
- output: RouteOutputSchema | null;
1372
- }
1373
-
1374
- export { type ToolPathMeta as $, type AppRegistries as A, type RouteOutputSchema as B, type CorsOptions as C, type RouteParamSchema as D, type SseEvent as E, type FaapiMiddleware as F, type SseOptions as G, type HelmetOptions as H, type InjectorMap as I, type SseWriter as J, type TaskContext as K, type LogConfig as L, type TaskDriverJob as M, type TaskDriverProcess as N, type TaskDriverRecord as O, type TaskFailedInfo as P, type TaskJob as Q, type RouteManifest as R, type SkillRegistry as S, type TaskClient as T, type TaskJobStatus as U, type TaskMetadata as V, type WsRouteManifest as W, type TaskModule as X, type TaskRegistriesSnapshot as Y, type TaskRegistriesView as Z, type ToolCore as _, type FaapiContext as a, type ToolRegistry as a0, cors as a1, createAppRegistries as a2, createTaskRegistriesView as a3, createTaskRegistry as a4, helmet as a5, type TaskFailedHandler as b, type TaskQueueDeps as c, type TaskQueue as d, type TaskDriver as e, type TaskRegistry as f, type TaskManifest as g, type ToolMetadata as h, type AgentCore as i, type AgentMetadata as j, type CreateLoggerOptions as k, type Logger as l, type AgentHandleFactory as m, type AgentHandleStore as n, type AgentPathMeta as o, type AgentRegistry as p, type AgentToolDescriptor as q, type FaapiContextConfig as r, type FaapiTaskMeta as s, type FailOptions as t, type Injector as u, type LogEntry as v, type LogLevel as w, type LogSink as x, type RouteInfo as y, type RouteInputSchema as z };
1178
+ export { type AppRegistries as A, type TaskDriverProcess as B, type CreateLoggerOptions as C, type TaskDriverRecord as D, type TaskFailedInfo as E, type FaapiContext as F, type TaskJob as G, type TaskJobStatus as H, type TaskMetadata as I, type TaskModule as J, type TaskRegistriesSnapshot as K, type LogConfig as L, type TaskRegistriesView as M, type ToolCore as N, type ToolPathMeta as O, type ToolRegistry as P, createAppRegistries as Q, createTaskRegistriesView as R, type SkillRegistry as S, type TaskClient as T, createTaskRegistry as U, type TaskFailedHandler as a, type TaskQueueDeps as b, type TaskQueue as c, type TaskDriver as d, type TaskRegistry as e, type TaskManifest as f, type ToolMetadata as g, type AgentCore as h, type AgentMetadata as i, type Logger as j, type AgentHandleFactory as k, type AgentHandleStore as l, type AgentPathMeta as m, type AgentRegistry as n, type AgentToolDescriptor as o, type FaapiContextConfig as p, type FaapiTaskMeta as q, type FailOptions as r, type LogEntry as s, type LogLevel as t, type LogSink as u, type SseEvent as v, type SseOptions as w, type SseWriter as x, type TaskContext as y, type TaskDriverJob as z };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,7 @@
1
- import { F as FaapiMiddleware, A as AppRegistries, R as RouteManifest, a as FaapiContext, C as CorsOptions, T as TaskClient, H as HelmetOptions, L as LogConfig, I as InjectorMap, b as TaskFailedHandler, W as WsRouteManifest, c as TaskQueueDeps, d as TaskQueue, e as TaskDriver, f as TaskRegistry, g as TaskManifest, h as ToolMetadata, i as AgentCore, j as AgentMetadata, k as CreateLoggerOptions, l as Logger } from './routeTypes-D1swYDVC.js';
2
- export { m as AgentHandleFactory, n as AgentHandleStore, o as AgentPathMeta, p as AgentRegistry, q as AgentToolDescriptor, r as FaapiContextConfig, s as FaapiTaskMeta, t as FailOptions, u as Injector, v as LogEntry, w as LogLevel, x as LogSink, y as RouteInfo, z as RouteInputSchema, B as RouteOutputSchema, D as RouteParamSchema, S as SkillRegistry, E as SseEvent, G as SseOptions, J as SseWriter, K as TaskContext, M as TaskDriverJob, N as TaskDriverProcess, O as TaskDriverRecord, P as TaskFailedInfo, Q as TaskJob, U as TaskJobStatus, V as TaskMetadata, X as TaskModule, Y as TaskRegistriesSnapshot, Z as TaskRegistriesView, _ as ToolCore, $ as ToolPathMeta, a0 as ToolRegistry, a1 as cors, a2 as createAppRegistries, a3 as createTaskRegistriesView, a4 as createTaskRegistry, a5 as helmet } from './routeTypes-D1swYDVC.js';
1
+ import { A as AppRegistries, F as FaapiContext, T as TaskClient, L as LogConfig, a as TaskFailedHandler, b as TaskQueueDeps, c as TaskQueue, d as TaskDriver, e as TaskRegistry, f as TaskManifest, g as ToolMetadata, h as AgentCore, i as AgentMetadata, C as CreateLoggerOptions, j as Logger } from './contextTypes-gYf84EXF.js';
2
+ export { k as AgentHandleFactory, l as AgentHandleStore, m as AgentPathMeta, n as AgentRegistry, o as AgentToolDescriptor, p as FaapiContextConfig, q as FaapiTaskMeta, r as FailOptions, s as LogEntry, t as LogLevel, u as LogSink, S as SkillRegistry, v as SseEvent, w as SseOptions, x as SseWriter, y as TaskContext, z as TaskDriverJob, B as TaskDriverProcess, D as TaskDriverRecord, E as TaskFailedInfo, G as TaskJob, H as TaskJobStatus, I as TaskMetadata, J as TaskModule, K as TaskRegistriesSnapshot, M as TaskRegistriesView, N as ToolCore, O as ToolPathMeta, P as ToolRegistry, Q as createAppRegistries, R as createTaskRegistriesView, U as createTaskRegistry } from './contextTypes-gYf84EXF.js';
3
+ import { F as FaapiMiddleware, R as RouteManifest, C as CorsOptions, H as HelmetOptions, I as InjectorMap, W as WsRouteManifest } from './routeTypes-DlD6nnbT.js';
4
+ export { a as Injector, b as RouteInfo, c as RouteInputSchema, d as RouteOutputSchema, e as RouteParamSchema, f as cors, h as helmet } from './routeTypes-DlD6nnbT.js';
3
5
  import * as node_http from 'node:http';
4
6
  import { Server, IncomingMessage, ServerResponse } from 'node:http';
5
7
  import { Socket } from 'node:net';
@@ -1489,6 +1491,17 @@ declare function loadConfig(rootDir: string, dist: string): Promise<Partial<Faap
1489
1491
  */
1490
1492
  declare function loadEnv(rootDir: string): void;
1491
1493
 
1494
+ /**
1495
+ * 读取当前 app 的运行时资源内容(参数为相对路径,只能读 resources 内的文件)
1496
+ *
1497
+ * 唯一读取入口:HTTP/WS handler、任务、插件、lifecycle 钩子、编程式调用全部用
1498
+ * 本函数——resources 目录在 app 启动时绑定(createAppBase),调用方不传路径根。
1499
+ * 越界校验见 resolveResourceTarget——绝对路径、`..` 穿越、符号链接逃逸均显式抛错,
1500
+ * resources 内部的合法软链不误伤。
1501
+ */
1502
+ declare function readResource(relativePath: string): Promise<Buffer>;
1503
+ declare function readResource(relativePath: string, encoding: BufferEncoding): Promise<string>;
1504
+
1492
1505
  /**
1493
1506
  * 设置全局日志配置(进程级,`createAppBase` 启动时以 `config.log` 调用)
1494
1507
  *
@@ -1752,4 +1765,4 @@ type ProdApp = AppBase;
1752
1765
  */
1753
1766
  declare function createProdApp(options?: CreateAppOptions): Promise<ProdApp>;
1754
1767
 
1755
- export { type AgentConfig, AgentCore, AgentMetadata, type ProdApp as App, AppRegistries, CorsOptions, type CreateAppOptions, CreateLoggerOptions, type CronScheduler, type DevApp, type FaapiConfig, FaapiContext, FaapiError, FaapiMiddleware, type FaapiPlugin, type HandlerTypeInfo, HelmetOptions, type InjectOptions, type InjectResponse, InjectorMap, InternalError, type LifecycleContext, type LifecycleHooks, type LlmConfig, type LlmModelConfig, LogConfig, Logger, type LoggerOptions, MethodNotAllowedError, ModuleLoadError, type PluginContext, type PluginDeclaration, type ProdApp, type PropertyType, type RequestHandler, type ResponseConfig, RouteManifest, RouteNotFoundError, type RouteSchemaSource, type RuntimeType, SchemaExtractionError, TASK_PATTERNS, type TaskBullMqOptions, TaskClient, type TaskConfig, TaskDriver, TaskFailedHandler, TaskManifest, type TaskPgBossOptions, TaskQueue, TaskRegistry, ToolMetadata, type ToolModule, type ToolSchemaModule, type TypeConstraint, type UpgradeHandler, ValidationError, type ValidationErrorCode, type ValidationIssue, type WsContext, type WsEventHandlers, type WsHandler, type WsSocket, clearAgentHandleFactory, collectRouteSchemaSources, configureLogging, createProdApp as createApp, createCronScheduler, createDevApp, createLogger, createProdApp, createProgram, createPrograms, createTaskQueue, extractTypeInfo, flushLogging, getAgent, getAgentEntry, getApp, getInputTypeForMethod, getSkill, getTool, getToolSchemaPath, hydrateSkillRegistry, invalidateProgramCache, listSkills, loadConfig, loadEnv, loadTaskDriver, loadToolModule, loadToolSchema, logger, registerAgentHandleFactory, removeSkill, resolveAgentTools, resolveSubAgents, resolveTypeNode, scanTasks, upsertSkill };
1768
+ export { type AgentConfig, AgentCore, AgentMetadata, type ProdApp as App, AppRegistries, CorsOptions, type CreateAppOptions, CreateLoggerOptions, type CronScheduler, type DevApp, type FaapiConfig, FaapiContext, FaapiError, FaapiMiddleware, type FaapiPlugin, type HandlerTypeInfo, HelmetOptions, type InjectOptions, type InjectResponse, InjectorMap, InternalError, type LifecycleContext, type LifecycleHooks, type LlmConfig, type LlmModelConfig, LogConfig, Logger, type LoggerOptions, MethodNotAllowedError, ModuleLoadError, type PluginContext, type PluginDeclaration, type ProdApp, type PropertyType, type RequestHandler, type ResponseConfig, RouteManifest, RouteNotFoundError, type RouteSchemaSource, type RuntimeType, SchemaExtractionError, TASK_PATTERNS, type TaskBullMqOptions, TaskClient, type TaskConfig, TaskDriver, TaskFailedHandler, TaskManifest, type TaskPgBossOptions, TaskQueue, TaskRegistry, ToolMetadata, type ToolModule, type ToolSchemaModule, type TypeConstraint, type UpgradeHandler, ValidationError, type ValidationErrorCode, type ValidationIssue, type WsContext, type WsEventHandlers, type WsHandler, type WsSocket, clearAgentHandleFactory, collectRouteSchemaSources, configureLogging, createProdApp as createApp, createCronScheduler, createDevApp, createLogger, createProdApp, createProgram, createPrograms, createTaskQueue, extractTypeInfo, flushLogging, getAgent, getAgentEntry, getApp, getInputTypeForMethod, getSkill, getTool, getToolSchemaPath, hydrateSkillRegistry, invalidateProgramCache, listSkills, loadConfig, loadEnv, loadTaskDriver, loadToolModule, loadToolSchema, logger, readResource, registerAgentHandleFactory, removeSkill, resolveAgentTools, resolveSubAgents, resolveTypeNode, scanTasks, upsertSkill };