# @cypress/schema-tools 中文文档

规范地址：https://npmcn.com/package/%40cypress/schema-tools/

版本：4\.7\.10
npm 元数据更新时间：2025-10-27T19:14:20.448Z
中文译文更新时间：2026-11-11T07:21:41.732Z
软件包许可：MIT

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

原始 npm 页面：https://www.npmjs.com/package/%40cypress/schema-tools
原文对照：https://npmcn.com/package/%40cypress/schema-tools/?lang=original
项目主页：https://github.com/cypress-io/schema-tools#readme
源码仓库：https://github.com/cypress-io/schema-tools

弃用说明：Package no longer supported\. Contact Support at https://www\.npmjs\.com/support for more info\.

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

- 包体积（解压后）：97.3 kB，39 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- 运行依赖：9 个
- 首次发布：2018-04-18T15:54:22.703Z
- 最新版本发布：2023-04-12T20:14:57.991Z
- 近 30 天下载量：81826（2026-10-11 至 2026-11-09，npm 官方下载统计）
- 已发布版本数：65（近 12 个月 0 个）

## 中文简介

验证、消毒和记录 JSON 计划

## 安装

```sh
npm install @cypress/schema-tools
```

也可以使用：`pnpm add @cypress/schema-tools`、`yarn add @cypress/schema-tools`、`bun add @cypress/schema-tools`

## README

# @ cypress/schema- 工具 [![CircleCI](https://circleci.com/gh/cypress-io/schema-tools.svg?style=svg&circle-token=aa9b52bab9e9216699ba7258929f727b06b13afe)](https://circleci.com/gh/cypress-io/schema-tools) [![renovate-app badge](https://img.shields.io/badge/renovate-app-blue.svg)](https://renovateapp.com/)

> 验证、消毒和文档 [JSON 计划](http://json-schema.org/)

## 动机

明确 [JSON 计划](http://json-schema.org/) 描述在系统里传递的物体是好的!

-   他们是一个活的可测试文档,而不是人工Wiki编辑
-   为测试和整合提供实例
-   验证API呼吁的投入和产出

## 技选

-   [示马斯](https://npmcn.com/package/%40cypress/schema-tools/#readme-schemas)
-   [格式](https://npmcn.com/package/%40cypress/schema-tools/#readme-formats)
-   [API 密码](https://npmcn.com/package/%40cypress/schema-tools/#readme-api)
-   [调试](https://npmcn.com/package/%40cypress/schema-tools/#readme-debugging), (中文(简体) ), [测试](https://npmcn.com/package/%40cypress/schema-tools/#readme-testing) 财务报告和审定财务报表 [许可证](https://npmcn.com/package/%40cypress/schema-tools/#readme-license)

## 示马斯

每个单个计划对象应有3个部分:版本、实例和 [JSON 计划](http://json-schema.org/) 描述其属性。 见 [试验/示范计划](https://npmcn.com/package/%40cypress/schema-tools/test/example-schemas.ts)。从单一开始 `ObjectSchema` 描述一个对象的特定版本

```typescript
import { ObjectSchema } from '@cypress/schema-tools'
const person100: ObjectSchema = {
  // has semantic version numbers
  version: {
    major: 1,
    minor: 0,
    patch: 0,
  },
  // JSON schema
  schema: {
    type: 'object',
    title: 'Person',
    description: 'An example schema describing a person',
    properties: {
      name: {
        type: 'string',
        format: 'name',
        description: 'this person needs a name',
      },
      age: {
        type: 'integer',
        minimum: 0,
        description: 'Age in years',
      },
    },
    required: ['name', 'age'],
    // note: you can just use required: true to require all properties
  },
  // has typical example
  example: {
    name: 'Joe',
    age: 10,
  },
}
```

您可以有多个独立的版本的"Person" schema,然后将它们组合成单个对象.

```typescript
import {ObjectSchema, VersionedSchema, versionSchemas} from '@cypress/schema-tools'
const person100: ObjectSchema = { ... }
// maybe added another property
const person110: ObjectSchema = { ... }
// some big changes
const person200: ObjectSchema = { ... }
const personVersions: VersionedSchema = versionSchemas(person100, person110, person200)
```

最后,你大概有"Person"版本的"计划",也许还有"组织",也许还有其他的"计划". 所以把它们放入一个集合

```typescript
import { SchemaCollection, combineSchemas } from '@cypress/schema-tools'
export const schemas: SchemaCollection = combineSchemas(
  personVersions,
  organizationVersions,
)
```

现在你可以使用 `schemas` 对象以验证和消毒任何对象.

## 格式

计外 [包含有 JSON-schemas 的格式](https://spacetelescope.github.io/understanding-json-schema/reference/string.html#built-in-formats) 可以定义用于验证值的自定义格式。 以单一自定义格式开始描述例如 UUID

```typescript
// single custom format
import { CustomFormat, CustomFormats } from '@cypress/schema-tools'
const uuid: CustomFormat = {
  name: 'uuid', // the name
  description: 'GUID used through the system',
  // regular expression to use to validate value
  detect: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,
  // (optional) replace actual value with this default value
  // when using to sanitize an object
  defaultValue: 'ffffffff-ffff-ffff-ffff-ffffffffffff',
}
// export all custom formats, in our case just 1
export const formats: CustomFormats = { uuid }
```

现在,每当你使用你的计划时,也通过这些格式,这样验证器就能知道如何从自定义格式中检查值.

```typescript
// example JSON schema using uuid custom format
const employee100: ObjectSchema = {
  // has semantic version numbers
  version: {
    major: 1,
    minor: 0,
    patch: 0,
  },
  // JSON schema
  schema: {
    type: 'object',
    title: 'Employee',
    properties: {
      id: {
        type: 'string',
        format: 'uuid',
      },
    },
  },
  example: {
    id: 'a368dbfd-08e4-4698-b9a3-b2b660a11835',
  },
}
// employee100 goes into "schemas", then
assertSchema(schemas, formats)('Employee', '1.0.0')(someObject)
```

## API 密码

-   [有计划](https://npmcn.com/package/%40cypress/schema-tools/#readme-hasschema)
-   [文档计划](https://npmcn.com/package/%40cypress/schema-tools/#readme-documentschemas)
-   [验证](https://npmcn.com/package/%40cypress/schema-tools/#readme-validate)
-   [断言计划](https://npmcn.com/package/%40cypress/schema-tools/#readme-assertschema)
-   [修饰](https://npmcn.com/package/%40cypress/schema-tools/#readme-trim)
-   [填满](https://npmcn.com/package/%40cypress/schema-tools/#readme-fill)
-   [净化](https://npmcn.com/package/%40cypress/schema-tools/#readme-sanitize)
-   [绑定](https://npmcn.com/package/%40cypress/schema-tools/#readme-bind)
-   [斯克马厄尔](https://npmcn.com/package/%40cypress/schema-tools/#readme-schemaerror)
-   [添加财产](https://npmcn.com/package/%40cypress/schema-tools/#readme-addproperty)
-   [扩展](https://npmcn.com/package/%40cypress/schema-tools/#readme-extend)
-   [内存](https://npmcn.com/package/%40cypress/schema-tools/#readme-oneofregex)

### 有计划

回返 `true` 如果给定的策略存在于收藏中。 Curried 函数 .

```typescript
import { hasSchema } from '@cypress/schema-tools'
import { schemas } from './schemas'
hasSchema(schemas, 'Name', '1.0.0') // true
hasSchema(schemas)('FooBarBaz')('1.0.0') // false
```

### 文档计划

您可以使用提供的方法记录您的计划。 示例代码文件

```typescript
import { documentSchemas } from '@cypress/schema-tools'
import { schemas } from './schemas'
import { formats } from './formats'
console.log(documentSchemas(schemas, formats))
```

从国家防范机制的剧本中调用

```json
{
  "scripts": {
    "document": "ts-node ./document.ts > schemas.md"
  },
  "devDependencies": {
    "ts-node": "5.0.1",
    "typescript": "2.8.1"
  }
}
```

如果您想要告诉一个方案来自何处, 您可以设置软件包名称, 这将在输出 Markdown 中添加一个注释

```typescript
import { setPackageName, documentSchemas } from '@cypress/schema-tools'
import { schemas } from './schemas'
setPackageName(schemas, 'my-schemas')
console.log(documentSchemas(schemas, formats))
// each schema will have a note that it was defined in "my-schemas"
```

### 验证

对照一个方案检查给定对象,如果对象没有通过方案,则返回错误列表。 回返 `true` 如果对象通过方案,如果出现错误,则列出字符串(我知道,我们应该使用 [任一或验证](http://folktale.origamitower.com/api/v2.1.0/en/folktale.validation.html)) (中文(简体) ).

```ts
import { validate } from '@cypress/schema-tools'
// see example in ./test/example-schemas.ts
import { schemas } from './my-schemas'
import { formats } from './my-formats'
const validatePerson100 = validate(schemas, formats)('person', '1.0.0')
const result = validatePerson100(someObject)
if (result === true) {
  // all good
} else {
  const errorMessage = result.join('\n')
  console.error(errorMessage)
}
```

典型的验证信件是

```
data.createdAt is required
data.createdAt must be date-time format
```

要在发现初始错误后停止, 请通过 `greedy = false` 旗帜

```js
const validatePerson100 = validate(schemas, formats, false)('person', '1.0.0')
```

### 断言计划

对照方案(和格式)检查给定对象,并扔出一个 [斯克马厄尔](https://npmcn.com/package/%40cypress/schema-tools/#readme-schemaerror) 如果对象违反了给定的策略.

```js
try {
  assertSchema(schemas, formats)('Person', '1.0.0')(object)
} catch (e) {
  console.error(e.message)
  // can also inspect individual fields, see SchemaError
}
```

您可以从示例对象中替换一些字段来帮助动态数据。 例如,避免在无效时断开 `id` 值,我们可以看到 `assertSchema` 用于 `id` 来自示例对象的值.

```js
const o = {
  name: 'Mary',
  age: -1,
}
assertSchema(schemas, formats)('Person', '1.0.0', {
  substitutions: ['age'],
})(o)
// everything is good, because the actual object asserted was
// {name: 'Mary', age: 10}
```

也可以限制错误消息并省略一些属性. 通常情况下,错误消息包含错误列表、当前和示例对象,这可能会形成一堵文字墙。 省略 `object` 财务报告和审定财务报表 `example` 生成错误消息时留下其他字段

```js
const o = {
  name: 'Mary',
  age: -1,
}
assertSchema(schemas, formats)('Person', '1.0.0', {
  omit: {
    object: true,
    example: true,
  },
})(o)
// Error message is much much shorter, only "errors" and label will be there
```

默认json计划检查是 [贪心](https://github.com/mafintosh/is-my-json-valid#greedy-mode-tries-to-validate-as-much-as-possible) 但你可以通过一个选项来限制

```js
assertSchema(schemas, formats)('Person', '1.0.0', { greedy: false })
```

### 修饰

通常你有一个对象 _更多_ 属性比计划允许的属性。 例如,如果你有了新的结果,应该给“老人”客户,你可能想 `trim` 以结果对象为对象,然后确定方案.

```js
import { trim } from '@cypress/schema-tools'
const trimPerson = trim(schemas, 'Person', '1.0.0')
const person = ... // some result with lots of properties
const trimmed = trimPerson(person)
// trimmed should be valid Person 1.0.0 object
// if the values are actually matching Person@1.0.0
// all extra properties should have been removed
```

### 填满

反之则 `trim`。尝试用图中明确的默认值填充缺失对象属性。 见 [试验/填充试验.ts](https://npmcn.com/package/%40cypress/schema-tools/test/fill-test.ts) 举个例子.

### 净化

如果Schema有动态数据,比如时间戳或uuids,那么如果不先删除一些字段,打破了schema,就不可能比较对象. 要解决这个问题,您可以用格式标记一些属性,如果格式有默认值,您可以用默认值取代所有动态值.

下面的例子 `name` 属性已调用格式 `name` 像这样

```js
name: {
  type: 'string',
  format: 'name'
}
```

现在我们可以消毒 任何可以替换的物体 `name` 值为默认值,但将保持其他属性不变.

```js
import { sanitize, getDefaults } from '@cypress/schema-tools'
const name: CustomFormat = {
  name: 'name',
  description: 'Custom name format',
  detect: /^[A-Z][a-z]+$/,
  defaultValue: 'Buddy',
}
const exampleFormats: CustomFormats = {
  name,
}
const formatDefaults = getDefaults(exampleFormats)
const object = {
  name: 'joe',
  age: 21,
}
const sanitizePerson = sanitize(schemas, formatDefaults)('person', '1.0.0')
// now pass any object with dynamic "name" property
const result = sanitizePerson(object)
// result is {name: 'Buddy', age: 21}
```

另一个例子见 [测试/卫生化-测试.ts](https://npmcn.com/package/%40cypress/schema-tools/test/sanitize-test.ts)

### 绑定

有多种方法可以验证,断言或消毒一个物体对一个计划. 都采用计划和(可选)格式。 但是,一个使用schema工具的项目可能有一个单集的schemas,它想一次又一次地使用. 这个 `bind` 方法使每个函数中的第一个参数容易被绑定在一个 schema 集合上,而只是使用一个对象的调用方法.

```js
import { schemas } from './my-schemas'
import { formats } from './my-formats'
import { bind } from '@cypress/schema-tools'
const api = bind({ schemas, formats })
api.assertSchema('name', '1.0.0')(someObject)
```

见 [测试/测试](https://npmcn.com/package/%40cypress/schema-tools/test/bind-test.ts) 实例

### 斯克马厄尔

当对一个方案主张对象时,会抛出一个自定义错误。 这是一个实例 `Error`,有一个非常详细的信息。 它还拥有额外的属性.

-   `errors` 是带有单个验证错误的字符串列表
-   `object` 正在验证的对象
-   `example` 策略的示例对象
-   `schemaName` 是计划的名称,比如 `Person`
-   `schemaVersion` 版本喜欢 `1.0.0` 如果知道的话 计划被破坏.

### 添加财产

您可以使用包含的内容轻松扩展已有的策略 `addProperty` 函数。 见 [斜弧/动作](https://npmcn.com/package/%40cypress/schema-tools/src/actions.ts) 财务报告和审定财务报表 [测试/附加财产测试](https://npmcn.com/package/%40cypress/schema-tools/test/add-property-test.ts) 用于实例.

### 扩展

而不是一次添加一个属性,你可以简单地使用 `extend(existingSchema, newSchemaObj)`。 。 。 .

这个 `existingSchema` 将会被深克隆 并拥有 `newSchemaObj` 属性合并入.

若为 `newSchemaObj.version` 未提供,然后是前一个计划 `minor` 财产将被撞倒.

字段类 `required` 自动结合.

见 [斜弧/动作](https://npmcn.com/package/%40cypress/schema-tools/src/actions.ts) 财务报告和审定财务报表 [测试/扩展-schema-test.ts](https://npmcn.com/package/%40cypress/schema-tools/test/extend-schema-test.ts) 用于实例.

### 内存

创建正则表达式只匹配给定字符串的一点工具功能 .

```js
import { oneOfRegex } from '@cypress/schema-tools'
const r = oneOfRegex('foo', 'bar')
r.test('foo') // true
r.test('bar') // true
r.toString() // "/^(foo|bar)$/"
```

## 调试

要查看此模块中的日志消息, 请运行 `DEBUG=schema-tools`

## 测试

用途 [ava - ts (韩语)](https://github.com/andywer/ava-ts#readme) 以直接对照 TypeScript 测试文件运行 Ava 测试跑取器。 使用 `npm t` 建造和测试所有的东西 `test` 文件夹.

要运行单个测试文件, 请使用命令

```
npx ava-ts test/<file-name.ts>
```

更新快照并使用动词报告器(打印测试名称)

```
npx ava-ts test/<file-name.ts> --verbose -u
```

## 许可证

本项目的许可条件如下: [麻省理工学院许可证](https://npmcn.com/package/%40cypress/schema-tools/LICENSE.md)。 。 。 .

## 常见问题

### @cypress/schema-tools 是什么？

验证、消毒和记录 JSON 计划注意：该包已被作者标记为弃用——Package no longer supported\. Contact Support at https://www\.npmjs\.com/support for more info\.

### 如何安装 @cypress/schema-tools？

在项目目录运行 npm install @cypress/schema-tools，或使用 pnpm add / yarn add / bun add。

### @cypress/schema-tools 支持 TypeScript 吗？

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

### @cypress/schema-tools 支持 ESM 还是 CommonJS？

以 CommonJS 形式发布，可以直接 require\(\)；在 ES Module 项目中也可以用 import 引入（Node\.js 会把 module\.exports 作为默认导出）。

### @cypress/schema-tools 可以商用吗？

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

### @cypress/schema-tools 的下载量有多少？

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

### @cypress/schema-tools 还在维护吗？

最新版本 4\.7\.10 发布于 2023/04/13（3 年前）；至今共发布 65 个版本，其中过去 12 个月发布了 0 个；首次发布于 2018/04/18。作者已将其标记为弃用，新项目建议寻找替代方案。

