mcpField
C
contributing-to-z-schema

contributing-to-z-schema

github.com/zaggino开发349171 次安装5 天前更新
代码仓库

关于 contributing-to-z-schema

contributing-to-z-schema 是面向 z-schema 贡献者的开发指南,介绍这款 TypeScript JSON Schema 验证器。它梳理代码结构,并说明常见修改、测试流程和仓库规范。

主要功能

  1. 01梳理核心源码模块
  2. 02指导添加错误、格式、选项和关键字
  3. 03说明 Vitest 测试流程
  4. 04列出 TypeScript 与导入规范
  5. 05提供拉取请求检查清单

适用场景

  1. 01设置 z-schema 仓库
  2. 02添加验证选项或格式
  3. 03实现 JSON Schema 关键字
  4. 04运行指定测试或完整测试套件

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/zaggino/z-schema --skill contributing-to-z-schema

安装后在 Claude Code 中输入/contributing-to-z-schema确认已加载。

附带文件references/architecture-details.md

详细介绍

为 z-schema 做贡献

z-schema 是一个使用 TypeScript 编写的 JSON Schema 验证器(支持 draft-04 到 draft-2020-12)。本指南介绍开发工作流、代码库导航和常见贡献任务。

仓库设置

git clone --recursive https://github.com/zaggino/z-schema.git
cd z-schema
npm install

如果克隆时没有使用 --recursive(json-schema-spec/ 子模块需要此选项):

git submodule update --init --recursive

质量检查

推送前运行所有检查:

npm run check           # ultracite check (oxlint type-aware + oxfmt format check)
npm run build           # TypeScript + Rollup
npm run build:tests     # Type-check tests
npm test                # Vitest (node + browser)

Pre-commit 钩子会自动对暂存文件运行 lint 和格式化。Pre-push 钩子会运行构建和类型检查。

代码库概览

src/
  index.ts              → Public API (all exports)
  z-schema.ts           → Factory + ZSchema/ZSchemaSafe/ZSchemaAsync/ZSchemaAsyncSafe
  z-schema-base.ts      → Core validation orchestration
  schema-compiler.ts    → $ref resolution, id collection, schema compilation
  schema-validator.ts   → Schema-level validation against meta-schemas
  json-validation.ts    → Validation orchestration (validate, recurse*, collectEvaluated)
  validation/            → Keyword validators split by category
    shared.ts            → Shared types (JsonValidatorFn), vocab helpers, caching utilities
    type.ts              → type, enum, const validators
    numeric.ts           → multipleOf, minimum, maximum, exclusiveMin/Max validators
    string.ts            → minLength, maxLength, pattern, format, content* validators
    array.ts             → items, prefixItems, contains, min/maxItems, uniqueItems validators
    object.ts            → properties, patternProperties, additionalProperties, required, etc.
    combinators.ts       → allOf, anyOf, oneOf, not, if/then/else validators
    ref.ts               → $dynamicRef/$recursiveRef resolution helpers
  schema-cache.ts       → Schema caching by URI/id
  errors.ts             → Error codes (Errors object) + ValidateError class
  format-validators.ts  → Built-in + custom format validators
  report.ts             → Error accumulation (Report, SchemaErrorDetail)
  json-schema.ts        → Common JSON Schema definitions + helpers
  json-schema-versions.ts → Draft-specific type unions + version mappings
  z-schema-options.ts   → Options interface + defaults + normalizeOptions
  z-schema-reader.ts    → Schema reader type
  z-schema-versions.ts  → Registers bundled meta-schemas into cache
  utils/                → Pure utilities (array, clone, json, uri, etc.)
  schemas/              → Bundled meta-schemas (generated at build time)

验证流程

  1. Schema 编译(schema-compiler.ts):解析 $ref,收集 id/$id,并在缓存中注册
  2. Schema 验证(schema-validator.ts):根据其元 Schema 验证 Schema
  3. JSON 验证(json-validation.ts + validation/*.ts):根据已编译的 Schema 验证数据,包括类型检查、约束、组合器(allOf/anyOf/oneOf/not)、unevaluated* 跟踪和格式检查。关键字验证器按类别拆分到 validation/ 下的各个模块中
  4. 报告(report.ts):错误会累积在 Report 中,然后转换为 ValidateError

常见任务

添加新的错误代码
  1. 在 src/errors.ts 的 Errors 对象中添加错误:
    MY_NEW_ERROR: 'Description with {0} placeholder',
    
  2. 在验证逻辑中使用 report.addError('MY_NEW_ERROR', [param])。
  3. 编写测试,确认会生成该错误代码。
添加新的格式验证器
  1. 在 src/format-validators.ts 中编写验证器函数:
    const myFormatValidator: FormatValidatorFn = (input: unknown) => {
      if (typeof input !== 'string') return true;
      return /^pattern$/.test(input);
    };
    
  2. 在 inbuiltValidators 记录中注册它:
    const inbuiltValidators = {
      // ...existing
      'my-format': myFormatValidator,
    };
    
  3. 在 test/spec/format-validators.spec.ts 中添加测试。
添加新选项
  1. 在 src/z-schema-options.ts 中向 ZSchemaOptions 添加选项。
  2. 在 defaultOptions 中添加默认值。
  3. 如果该选项属于 strictMode,则将其添加到 normalizeOptions 中的 strictMode 块。
  4. 在 docs/options.md 中记录该选项。
  5. 编写测试。
实现新的 JSON Schema 关键字
  1. 在合适的 src/validation/*.ts 模块中添加验证逻辑(例如,数组关键字放在 array.ts 中,对象关键字放在 object.ts 中,应用器放在 combinators.ts 中),或者添加到 src/schema-validator.ts(用于 Schema 级验证)。src/json-validation.ts 中的编排层会调用这些模块。
  2. 如果该关键字仅适用于特定草案版本,则添加草案版本检查。
  3. 从 test/spec/json-schema-test-suite.common.ts 的 excludedFiles/excludedTests 中移除相关条目。
  4. 运行 JSON Schema 测试套件以确认符合规范:
    npx vitest run --silent=false --project node -t "draft2020-12/newKeyword"
    
  5. 通过 src/index.ts 导出任何新类型。
修改现有行为
  1. 使用上方的代码库概览找到相关模块。
  2. 按照代码规范进行修改(见下文)。
  3. 运行完整测试套件——回归问题往往会出现在其他草案版本中。

测试框架

  • 使用 Vitest,并启用 globals: true。
  • 两个项目:node 和 browser(Playwright:Chromium、Firefox、WebKit)。
  • 测试位于 test/spec/ 中。
文件命名
后缀运行环境
*.spec.tsnode 和 browser 均运行
*.node-spec.ts仅 node
*.browser-spec.ts仅 browser
运行测试
npm test                                                        # all
npm run test:node                                               # node only
npx vitest run --silent=false --project node -t "draft4/type"   # single test
npm run test:coverage                                           # coverage
测试模式
import { ZSchema } from '../../src/z-schema.ts';

describe('Feature Name', () => {
  it('should accept valid data', () => {
    const validator = ZSchema.create();
    expect(validator.validate('hello', { type: 'string' })).toBe(true);
  });

  it('should reject invalid data', () => {
    const validator = ZSchema.create();
    const { valid, err } = validator.validateSafe(42, { type: 'string' });
    expect(valid).toBe(false);
    expect(err?.details?.[0]?.code).toBe('INVALID_TYPE');
  });
});
JSON Schema 测试套件

官方测试用例通过 test/spec/json-schema-test-suite.common.ts 加载。要为新实现的功能启用测试,请从 excludedFiles/excludedTests 中移除相关条目,并确认测试通过。

代码规范

  • TypeScript 使用 strict: true,src/ 中使用 ESM,导入扩展名为 .js
  • test/ 中使用 .ts 导入扩展名(通过 allowImportingTsExtensions)
  • 仅用于类型的导入使用 import type(由 oxlint 强制执行)
  • 导入顺序:仅类型 → 副作用 → Node 内置模块 → 包 → 相对路径
  • oxfmt:120 个字符宽度、单引号、尾随逗号(es5)、分号
  • 类/类型:PascalCase — 函数/变量:camelCase — 错误:UPPER_SNAKE_CASE
  • 所有公共 API 均通过 src/index.ts 导出
  • 内部类型保持不导出
  • src/schemas/ 中的架构由 scripts/copy-schemas.mts 生成 — 请勿手动编辑
  • json-schema-spec/ 是一个 Git 子模块 — 请勿提交对其的更改

PR 检查清单

- [ ] Branch from `main`
- [ ] Changes follow code conventions
- [ ] npm run check passes (lint + format)
- [ ] npm run build passes
- [ ] npm run build:tests passes
- [ ] npm test passes (node + browser)
- [ ] New public types/values exported through src/index.ts
- [ ] New features have tests
- [ ] docs/ updated if public API changed
- [ ] JSON Schema Test Suite entries un-excluded if applicable

参考文件

评论

支持 Markdown