import type { FastifyReply } from "fastify"; import type { VextResponse } from "../../types/response.js"; /** * Fastify Reply → VextResponse 转换 * * 核心设计(与 Hono Adapter 的 response.ts 逻辑对齐): * * 1. 延迟绑定 requestId(getRequestId getter) * requestId 在 createVextResponse 调用时尚未生成(requestId 中间件还没执行), * 传入 getter 函数确保 json() 实际调用时才取值(此时 requestId 必然已由中间件生成)。 * * 2. 内建出口包装(_wrapEnabled 标志) * response-wrapper 中间件通过 _enableWrap() 开启包装标志。 * json() 根据标志决定是否将响应体包装为 { code: 0, data, requestId }。 * rawJson() 始终绕过包装——仅供框架内部错误处理使用。 * * 3. 重复发送保护(_sent 标志) * 防止 handler 中误调用多次 res.json(),dev 模式打印警告,生产模式静默忽略。 * * 4. 链式调用(status / setHeader 返回 this) * res.status(201).json(data) 正确设置 HTTP 201。 * * 5. 204 No Content 合规(RFC 9110 §15.3.5) * 无论包装是否开启,204 均发送无消息体的响应。 * * 6. 手动 JSON 序列化 * 使用 reply.send(JSON.stringify(...)) 而非 reply.send(object), * 避免 Fastify 内置的 fast-json-stringify 自动序列化, * 保证与 Hono Adapter 行为一致(跨 Adapter 行为一致性 > 单 Adapter 极限性能)。 * * 与 Hono Adapter 的差异: * - Hono: 通过 ResponseBox 容器捕获 c.json() 返回的 Web Response 对象 * - Fastify: 直接调用 reply.status().header().send() 发送响应(Node.js 原生模型) * - Fastify 无需 ResponseBox 机制,因为 Fastify 的 route handler 不需要返回 Response 对象 * * 时序保证: * createVextResponse(reply, () => req.requestId) * ↓ executeChain 开始 * [requestIdMiddleware] → req.requestId = 'a1b2c3d4...' * [responseWrapperMiddleware] → res._enableWrap() * ↓ * [handler] res.status(201).json(data) * → _wrapEnabled = true * → getRequestId() → 'a1b2c3d4...'(已设置) * → reply.send(JSON.stringify({ code: 0, data, requestId })) * → HTTP 201 ✅ * * @param reply Fastify Reply 对象 * @param getRequestId 延迟获取 requestId 的 getter 函数 * @returns VextResponse 实例(含内部方法 _enableWrap) * * @see 08a-fastify-adapter.md §5(响应转换) * @see adapters/hono/response.ts(Hono Adapter 对应实现) */ export declare function createVextResponse(reply: FastifyReply, getRequestId: () => string): VextResponse;