# @chubbyts/chubbyts-http-types 中文文档

规范地址：https://npmcn.com/package/%40chubbyts/chubbyts-http-types/

版本：4\.2\.2
npm 元数据更新时间：2026-11-03T21:36:44.438Z
中文译文更新时间：2026-11-09T15:38:51.579Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40chubbyts/chubbyts-http-types
原文对照：https://npmcn.com/package/%40chubbyts/chubbyts-http-types/?lang=original
源码仓库：https://github.com/chubbyts/chubbyts-http-types

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：37 kB，15 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- Node.js 要求：\>=22
- 运行依赖：0 个
- 首次发布：2022-05-26T09:48:17.986Z
- 最新版本发布：2026-11-03T21:36:44.272Z
- 近 30 天下载量：2347（2026-10-10 至 2026-11-08，npm 官方下载统计）
- 已发布版本数：19（近 12 个月 5 个）

## 中文简介

Http Request/Response types 有工厂,助手,中件和处理器,PSR-7,PSR-15和PSR-17启发.

## 安装

```sh
npm install @chubbyts/chubbyts-http-types
```

也可以使用：`pnpm add @chubbyts/chubbyts-http-types`、`yarn add @chubbyts/chubbyts-http-types`、`bun add @chubbyts/chubbyts-http-types`

## README

# 圆顶- http- 类型

[![CI](https://github.com/chubbyts/chubbyts-http-types/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/chubbyts/chubbyts-http-types/actions/workflows/ci.yml) [![Coverage Status](https://coveralls.io/repos/github/chubbyts/chubbyts-http-types/badge.svg?branch=master)](https://coveralls.io/github/chubbyts/chubbyts-http-types?branch=master) [![Mutation testing badge](https://img.shields.io/endpoint?style=flat&url=https%3A%2F%2Fbadge-api.stryker-mutator.io%2Fgithub.com%2Fchubbyts%2Fchubbyts-http-types%2Fmaster)](https://dashboard.stryker-mutator.io/reports/github.com/chubbyts/chubbyts-http-types/master) [![npm-version](https://img.shields.io/npm/v/@chubbyts/chubbyts-http-types.svg)](https://www.npmjs.com/package/@chubbyts/chubbyts-http-types)

[![bugs](https://sonarcloud.io/api/project_badges/measure?project=chubbyts_chubbyts-http-types&metric=bugs)](https://sonarcloud.io/dashboard?id=chubbyts_chubbyts-http-types) [![code\_smells](https://sonarcloud.io/api/project_badges/measure?project=chubbyts_chubbyts-http-types&metric=code_smells)](https://sonarcloud.io/dashboard?id=chubbyts_chubbyts-http-types) [![coverage](https://sonarcloud.io/api/project_badges/measure?project=chubbyts_chubbyts-http-types&metric=coverage)](https://sonarcloud.io/dashboard?id=chubbyts_chubbyts-http-types) [![duplicated\_lines\_density](https://sonarcloud.io/api/project_badges/measure?project=chubbyts_chubbyts-http-types&metric=duplicated_lines_density)](https://sonarcloud.io/dashboard?id=chubbyts_chubbyts-http-types) [![ncloc](https://sonarcloud.io/api/project_badges/measure?project=chubbyts_chubbyts-http-types&metric=ncloc)](https://sonarcloud.io/dashboard?id=chubbyts_chubbyts-http-types) [![sqale\_rating](https://sonarcloud.io/api/project_badges/measure?project=chubbyts_chubbyts-http-types&metric=sqale_rating)](https://sonarcloud.io/dashboard?id=chubbyts_chubbyts-http-types) [![alert\_status](https://sonarcloud.io/api/project_badges/measure?project=chubbyts_chubbyts-http-types&metric=alert_status)](https://sonarcloud.io/dashboard?id=chubbyts_chubbyts-http-types) [![reliability\_rating](https://sonarcloud.io/api/project_badges/measure?project=chubbyts_chubbyts-http-types&metric=reliability_rating)](https://sonarcloud.io/dashboard?id=chubbyts_chubbyts-http-types) [![security\_rating](https://sonarcloud.io/api/project_badges/measure?project=chubbyts_chubbyts-http-types&metric=security_rating)](https://sonarcloud.io/dashboard?id=chubbyts_chubbyts-http-types) [![sqale\_index](https://sonarcloud.io/api/project_badges/measure?project=chubbyts_chubbyts-http-types&metric=sqale_index)](https://sonarcloud.io/dashboard?id=chubbyts_chubbyts-http-types) [![vulnerabilities](https://sonarcloud.io/api/project_badges/measure?project=chubbyts_chubbyts-http-types&metric=vulnerabilities)](https://sonarcloud.io/dashboard?id=chubbyts_chubbyts-http-types)

## 说明

HTTP 信件、 处理器和中间软件的脚本类型, 灵感来自 [临 时 7](https://www.php-fig.org/psr/psr-7), (中文(简体) ), [临 时 15](https://www.php-fig.org/psr/psr-15) 财务报告和审定财务报表 [临 时 议 题](https://www.php-fig.org/psr/psr-17)。 。 。 .

仅合同:类型(加) `pipe`页:1 框架、路由器和中间软件取决于它和停留 可以互换,工厂和助手的任何执行都会创造和改变信息. 身体就是个 [`AsyncIterable<Uint8Array>`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncIterator),因此Node.js流和网络 `ReadableStream`不需要转换.

| 模块 | 出口 |
| --- | --- |
| `message` | `Uri`, (中文(简体) ), `Query`, (中文(简体) ), `Headers`, (中文(简体) ), `Body`, (中文(简体) ), `Message`, (中文(简体) ), `Method`, (中文(简体) ), `Request`, (中文(简体) ), `Attributes`, (中文(简体) ), `ServerRequest<A>`, (中文(简体) ), `Response` |
| `message-factory` | `UriFactory`, (中文(简体) ), `BodyFactory`, (中文(简体) ), `BodyFromFileFactory`, (中文(简体) ), `RequestFactory`, (中文(简体) ), `ServerRequestFactory`, (中文(简体) ), `ResponseFactory` |
| `message-helper` | `HeaderValue`, (中文(简体) ), `MessageHelpers`, (中文(简体) ), `RequestHelpers`, (中文(简体) ), `ServerRequestHelpers`, (中文(简体) ), `ResponseHelpers`, (中文(简体) ), `UriHelpers`, (中文(简体) ), `CookieOptions` |
| `handler` | `Handler<A>`数字 : `(request: ServerRequest<A>) => Promise<Response>` |
| `middleware` | `Middleware<I, O = I>`数字 : `(request: ServerRequest<I>, handler: Handler<O>) => Promise<Response>` |

`A`, (中文(简体) ), `I` 财务报告和审定财务报表 `O` 扩展和默认为 `Attributes` (单位:千美元)`Record<string, unknown>`) (中文(简体) ).

## 所需资源

-   节点: 22

## 安装

穿过 [国家预防机制](https://www.npmjs.com/) 作为 [@ hubbyts/ chubbyts- http- types](https://www.npmjs.com/package/@chubbyts/chubbyts-http-types)。 。 。 .

```sh
npm i @chubbyts/chubbyts-http-types@^4.2.2
```

## 使用量

### 信件

```ts
import { Readable } from 'node:stream';
import type { ServerRequest } from '@chubbyts/chubbyts-http-types/message';

// GET https://user:password@localhost:10443/api?key1=value1&key2[]=value2&key3[key31]=value3#fragment
const request: ServerRequest = {
  method: 'GET',
  uri: {
    scheme: 'https',
    userInfo: 'user:password',
    host: 'localhost',
    port: 10443,
    path: '/api',
    query: 'key1=value1&key2[]=value2&key3[key31]=value3',
    fragment: 'fragment',
  },
  protocolVersion: '1.1',
  headers: { accept: ['application/json'] },
  body: Readable.from([]),
  signal: new AbortController().signal,
  attributes: {},
};
```

-   `method`:已知方法自动完成,任何扩展方法(`PROPFIND`)被允许.
-   `uri.port`数字 : `undefined` 没有明确的端口. `uri.query`:原始和百分比编码,无 `?`。 。 。 .
-   `headers`: 小写名称,每个都有一个数值列表.
-   `body`:读取一次以延取(如. `text(body)` 从 `node:stream/consumers`,块是字节,从来没有 对象.
-   `signal`: 当不再需要请求时中止(例如客户端断开). 服务器桥拥有它, 处理者传递,例如. `fetch(url, { signal: request.signal })`。 。 。 .
-   `attributes`: 从请求中得出的值(路线参数,用户),参见 [输入属性](https://npmcn.com/package/%40chubbyts/chubbyts-http-types/#readme-typed-attributes)。 。 。 .

A 类 `Request` 没有 `attributes`页:1 `Response` 已经 `status`, (中文(简体) ), `reasonPhrase`, (中文(简体) ), `protocolVersion`, (中文(简体) ), `headers` 财务报告和审定财务报表 `body`。 。 。 .

### 工厂

| 类型 | 签署 |
| --- | --- |
| `UriFactory` | `(uri: string) => Uri` |
| `BodyFactory` | `(content: string) => Body` |
| `BodyFromFileFactory` | `(filename: string) => Body` |
| `RequestFactory` | `(method: Method, uri: string | Uri) => Request` |
| `ServerRequestFactory` | `(method: Method, uri: string | Uri) => ServerRequest` |
| `ResponseFactory` | `(status: number, reasonPhrase?: string) => Response` |

创建信件有协议版本 `1.1`,没有头和一空的尸体。 每个请求都有自己的信号 (一个会把听众堆积在一起) `Uri` 用于当前,服务器请求启动时没有属性。 这个 理由短语回到 [`STATUS_CODES`](https://nodejs.org/api/http.html#httpstatus_codes) (如果未知则为空字符串).

### 帮助者

帮助者读取并更改消息和尿液,像PSR-7接口一样分出. 每一个执行都必须遵循 这些规则,所以中间器件工作 任何注射:

-   标题名称是大小写不敏感并存储的小写,名称必须是符号([RFC 9110 5.1](https://www.rfc-editor.org/rfc/rfc9110#section-5.1)),一个值必须 不包含 CR、 LF 或 NUL, 否则 `with*` 帮助者投掷
-   页:1 `with*` 帮助者返回新信件或 uri, 给定的信件保持不变
-   用嵌入式解析查询( n)`key[sub]=value`, (中文(简体) ), `key[]=value`和重复键入对象和数组, `+` 财务报告和审定财务报表 百分数编码解码, `__proto__` 永远不要更改原型,限制(深度,阵列大小,参数)都在上升 执行进展情况
-   查询参数用索引键进行序列化(`key[sub]=value`, (中文(简体) ), `key[0]=value`),%编码(RFC 3986,空间为 `%20`),空阵列和对象被丢弃,所以重新解析它们返回
-   里端口为 `undefined` 如果它是其计划的标准之一(80对https, 443对https)

`MessageHelpers` (临7) `MessageInterface`:

| 帮助 | 签署 | 规则 |
| --- | --- | --- |
| `getHeader` | `(message, name) => ReadonlyArray<string>` | 如果缺少空阵列 |
| `getHeaderLine` | `(message, name) => string` | 加入的数值 `', '`,如果缺少空字符串,则丢弃用于 `set-cookie` |
| `hasHeader` | `(message, name) => boolean` |  |
| `withHeader` | `(message, name, value) => message` | 替换值 |
| `withAddedHeader` | `(message, name, value) => message` | 对现有值的附加 |
| `withoutHeader` | `(message, name) => message` |  |
| `withProtocolVersion` | `(message, protocolVersion) => message` | 抛出除 `1.0`, (中文(简体) ), `1.1`, (中文(简体) ), `2` 或者说 `3` |
| `withBody` | `(message, body) => message` |  |

`RequestHelpers` (临7) `RequestInterface`,包括: `MessageHelpers`数字 :

| 帮助 | 签署 | 规则 |
| --- | --- | --- |
| `withMethod` | `(request, method) => request` | 如果不是符号, 丢出大小写敏感度 |
| `getRequestTarget` | `(request) => string` | 来源窗体:路径(`/` 如果为空)和查询 |
| `withUri` | `(request, uri, preserveHost?) => request` | 设置 `host` 标题,除非小便没有或 `preserveHost` 并有一个存在 |
| `withSignal` | `(request, signal) => request` | 譬如说. `AbortSignal.any([request.signal, AbortSignal.timeout(ms)])` |
| `getQueryParams` | `(request) => Query` | 剖析 `uri.query` |
| `withQueryParams` | `(request, queryParams) => request` | 替换 `uri.query` |

`ServerRequestHelpers` (临7) `ServerRequestInterface`,包括: `RequestHelpers`数字 :

| 帮助 | 签署 | 规则 |
| --- | --- | --- |
| `withAttribute` | `(request, name, value) => request` | 添加或替换属性,包括其类型(\*) |
| `withoutAttribute` | `(request, name) => request` | 删除属性,包括其类型 |
| `getCookieParams` | `(request) => Record<string, string>` | 发送的值, 被删除的相邻引号, 第一次发生获胜 |

(\*) 名称仅在运行时知道(`string`),任何属性都可以被替换,因此其类型会被扩大以包括: 值的类型.

`ResponseHelpers` (临7) `ResponseInterface`,包括: `MessageHelpers`数字 :

| 帮助 | 签署 | 规则 |
| --- | --- | --- |
| `withStatus` | `(response, status, reasonPhrase?) => response` | 抛出100 -599之外, 理由短语回到 `STATUS_CODES` |
| `withCookie` | `(response, name, value, options?) => response` | 附录a `set-cookie` 标题 |
| `withoutCookie` | `(response, name, options?) => response` | 附录a `set-cookie` 标题已过期 cookie |

`UriHelpers` (临7) `UriInterface`:

| 帮助 | 签署 | 规则 |
| --- | --- | --- |
| `getAuthority` | `(uri) => string` | `[user-info@]host[:port]`,没有主机的空字符串 |
| `toString` | `(uri) => string` | `//` 只有主机才有权限 |
| `withScheme` | `(uri, scheme) => uri` | 小写, 如果无效丢出, 允许为空 |
| `withUserInfo` | `(uri, user, password?) => uri` | %- 编码, 与 `:` |
| `withHost` | `(uri, host) => uri` | 小写 |
| `withPort` | `(uri, port) => uri` | 在1 -65535外抛出, `undefined` 移除它 |
| `withPath` | `(uri, path) => uri` | %- encode 不允许字符, 保留已有的编码 |
| `withQuery` | `(uri, query) => uri` | 无 `?`,百分比编码类似 `withPath` |
| `withFragment` | `(uri, fragment) => uri` | 无 `#`,百分比编码类似 `withPath` |

饼干帮手跟着 [RFC 6265 (韩语)](https://www.rfc-editor.org/rfc/rfc6265) (PSR-7没有饼干支持):

-   一个名称必须是一个符号,一个值由 cookie-octets 组成,在双引号中可选,并且得到两个 编码或解码
-   路径和域不得包含 `;` 或控制字符,无效 `maxAge` 或者说 `expires` 掷出
-   `sameSite: 'None'` 财务报告和审定财务报表 `partitioned` 需求 `secure`页:1 `__Secure-` 前缀需要 `secure`页:1 `__Host-` 前缀 `secure`,路径 `/` 且无域
-   属性按顺序序列化 `Path`, (中文(简体) ), `Domain`, (中文(简体) ), `Max-Age`, (中文(简体) ), `Expires`, (中文(简体) ), `Secure`, (中文(简体) ), `HttpOnly`, (中文(简体) ), `SameSite`, (中文(简体) ), `Partitioned`
-   `withoutCookie` 设置空值, `Max-Age=0` 还有一个 `Expires` 1970年,路径和领域必须匹配 饼干被设定

### 处理器

处理器将服务器请求转换为响应,其依赖性被注入:

```ts
import type { Handler } from '@chubbyts/chubbyts-http-types/handler';
import type { BodyFactory, ResponseFactory } from '@chubbyts/chubbyts-http-types/message-factory';
import type { ResponseHelpers } from '@chubbyts/chubbyts-http-types/message-helper';

export const createPingHandler = (
  responseFactory: ResponseFactory,
  bodyFactory: BodyFactory,
  responseHelpers: ResponseHelpers,
): Handler => {
  return async () => {
    const response = responseHelpers.withBody(
      responseFactory(200),
      bodyFactory(JSON.stringify({ datetime: new Date().toISOString() })),
    );

    return responseHelpers.withHeader(response, 'content-type', 'application/json');
  };
};
```

### 中间软件

中间软件在下一个处理器之前和之后更改请求,或者自行回复:

```ts
import type { Attributes } from '@chubbyts/chubbyts-http-types/message';
import type { ResponseHelpers, ServerRequestHelpers } from '@chubbyts/chubbyts-http-types/message-helper';
import type { Middleware } from '@chubbyts/chubbyts-http-types/middleware';

export const createRequestIdMiddleware = (
  serverRequestHelpers: ServerRequestHelpers,
  responseHelpers: ResponseHelpers,
): Middleware<Attributes, { requestId: string }> => {
  return async (request, handler) => {
    const requestId = crypto.randomUUID();

    const response = await handler(serverRequestHelpers.withAttribute(request, 'requestId', requestId));

    return responseHelpers.withHeader(response, 'x-request-id', requestId);
  };
};
```

### 管道

`pipe` 将中间软件编成一个,第一个是最外层:

```ts
import type { Handler } from '@chubbyts/chubbyts-http-types/handler';
import type { Middleware } from '@chubbyts/chubbyts-http-types/middleware';
import { pipe } from '@chubbyts/chubbyts-http-types/pipe';

declare const handler: Handler;
declare const middlewares: Array<Middleware>;

const middleware: Middleware = pipe(middlewares);

export const app: Handler = (request) => middleware(request, handler);
```

### 输入属性

依赖先前(由路由器或认证)设定的属性的处理器或中间软件宣布这些属性,即 添加属性声明它接收的属性和传递的属性为 `Middleware<I, O>`数字 :

```ts
import type { Handler } from '@chubbyts/chubbyts-http-types/handler';
import type { ResponseFactory } from '@chubbyts/chubbyts-http-types/message-factory';
import type { ResponseHelpers, ServerRequestHelpers } from '@chubbyts/chubbyts-http-types/message-helper';
import type { Middleware } from '@chubbyts/chubbyts-http-types/middleware';

type RequestIdAttributes = { requestId: string };
type UserAttributes = RequestIdAttributes & { userId: string };

export const createAuthenticationMiddleware = (
  serverRequestHelpers: ServerRequestHelpers,
  resolveUserId: (authorization: string) => Promise<string>,
): Middleware<RequestIdAttributes, UserAttributes> => {
  return async (request, handler) => {
    const userId = await resolveUserId(serverRequestHelpers.getHeaderLine(request, 'authorization'));

    return handler(serverRequestHelpers.withAttribute(request, 'userId', userId));
  };
};

export const createUserHandler =
  (responseFactory: ResponseFactory, responseHelpers: ResponseHelpers): Handler<UserAttributes> =>
  async (request) =>
    responseHelpers.withHeader(responseFactory(204), 'x-user-id', request.attributes.userId);
```

`pipe` 只编写共享相同属性的中间软件(`Middleware<A>`) (中文(简体) ). 与 `m1: Middleware<RequestIdAttributes, UserAttributes>` 财务报告和审定财务报表 `m2: Middleware<UserAttributes, PingAttributes>`, (中文(简体) ), `pipe([m1, m2])` 编译为 a `Middleware<UserAttributes>`:它要求 `userId` 前面隐藏着 `ping`。 。 。 . 用手将这种中间软件链起来:

```ts
const app: Handler<RequestIdAttributes> = (request) => m1(request, (userRequest) => m2(userRequest, handler));
```

## 从3.x升级

| 3.x 运算 | 4.x (中文(简体) ) |
| --- | --- |
| 节点 qq 18 | 节点 22 |
| `import … from '@chubbyts/chubbyts-http-types/dist/message'` | `import … from '@chubbyts/chubbyts-http-types/message'` (无) `dist/`(中文(简体) ) |
| `uri.schema` | `uri.scheme` (与PSR-7一样) `getScheme()`(中文(简体) ) |
| `statusMap.get(status)` | `STATUS_CODES[status]` 从 `node:http` |
| 可变信息 | 所有属性 `readonly`,比如说. `withAttribute(request, 'userId', 'user-1')` 而不是转让 |
| `Method` 限于 `CONNECT`, (中文(简体) ), `DELETE`, (中文(简体) ), `GET`,, , , , , , , , `TRACE` | 任何方法,已知的 自动完成 |
| `Query` 数组只包含嵌入式查询 | `Query` 数组包含字符串和嵌入式查询( r)`key[]=value`(中文(简体) ) |
| `uri.query` 解析( e)`Query`(中文(简体) ) | `uri.query` 原始字符串, 使用 `requestHelpers.getQueryParams` 财务报告和审定财务报表 `withQueryParams` |
| `body` 是一个 `Duplex`,操作者写到 `response.body` | `body` 是一个 `AsyncIterable<Uint8Array>`,一个处理器设置它与 `withBody(response, bodyFactory(…))` |
| `StreamFromResourceFactory` | 删除时,一个节点.js流已经是一个 `Body` |
| `StreamFactory`, (中文(简体) ), `StreamFromFileFactory` | `BodyFactory`, (中文(简体) ), `BodyFromFileFactory` (旧名被去化名 |
| 无法注意到断开的客户端 | `request.signal`,当不再需要请求时中止 |
| `ServerRequest`, (中文(简体) ), `Handler`, (中文(简体) ), `Middleware` 无类型属性 | `ServerRequest<A>`, (中文(简体) ), `Handler<A>`, (中文(简体) ), `Middleware<I, O>` 带有已键入属性 |
| \- 说吧 | 新建 : `Headers`, (中文(简体) ), `Body`, (中文(简体) ), `Attributes`,帮助者类型和 `pipe` |

## 版权

2026 道米尼克·佐格(英语:

## 常见问题

### @chubbyts/chubbyts-http-types 是什么？

Http Request/Response types 有工厂,助手,中件和处理器,PSR-7,PSR-15和PSR-17启发\.

### 如何安装 @chubbyts/chubbyts-http-types？

在项目目录运行 npm install @chubbyts/chubbyts-http-types，或使用 pnpm add / yarn add / bun add。

### @chubbyts/chubbyts-http-types 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @chubbyts/chubbyts-http-types 支持 ESM 还是 CommonJS？

以 ES Module 形式发布，推荐使用 import 引入。在 CommonJS 项目中，Node\.js 20\.19\+ / 22\.12\+ 可以直接 require\(\) 不含顶层 await 的 ES Module，更早的版本需要改用动态 import\(\)。

### @chubbyts/chubbyts-http-types 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>=22。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @chubbyts/chubbyts-http-types 可以商用吗？

@chubbyts/chubbyts-http-types 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @chubbyts/chubbyts-http-types 的下载量有多少？

根据 npm 官方下载统计，@chubbyts/chubbyts-http-types 在 2026/10/10 – 2026/11/08 这 30 天内被下载 2,347 次，日均约 78 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @chubbyts/chubbyts-http-types 还在维护吗？

最新版本 4\.2\.2 发布于 2026/11/04（5 天前）；至今共发布 19 个版本，其中过去 12 个月发布了 5 个；首次发布于 2022/05/26。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

