contributing-to-z-schema
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseContributing to z-schema
为z-schema做贡献
z-schema is a JSON Schema validator (draft-04 through draft-2020-12) written in TypeScript. This skill covers the development workflow, codebase navigation, and common contribution tasks.
z-schema是一款用TypeScript编写的JSON Schema验证器(支持draft-04到draft-2020-12版本)。本指南涵盖开发工作流、代码库导航和常见贡献任务。
Repository setup
仓库设置
bash
git clone --recursive https://github.com/zaggino/z-schema.git
cd z-schema
npm installIf already cloned without (needed for the submodule):
--recursivejson-schema-spec/bash
git submodule update --init --recursivebash
git clone --recursive https://github.com/zaggino/z-schema.git
cd z-schema
npm install如果克隆时未添加参数(拉取子模块需要该参数),请执行以下命令:
--recursivejson-schema-spec/bash
git submodule update --init --recursiveQuality checks
质量检查
Run all checks before pushing:
bash
npm run lint:check # ESLint
npm run format:check # Prettier
npm run build # TypeScript + Rollup
npm run build:tests # Type-check tests
npm test # Vitest (node + browser)Pre-commit hooks auto-run lint + format on staged files. Pre-push hooks run build + type-check.
推送代码前请运行所有检查:
bash
npm run lint:check # ESLint
npm run format:check # Prettier
npm run build # TypeScript + Rollup
npm run build:tests # 测试用例类型检查
npm test # Vitest (node + browser)预提交钩子会自动对暂存文件执行lint和格式检查。预推送钩子会执行构建和类型检查。
Codebase map
代码库结构
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 → Instance validation (type, constraints, combiners)
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)src/
index.ts → 公共API(所有导出内容)
z-schema.ts → 工厂函数 + ZSchema/ZSchemaSafe/ZSchemaAsync/ZSchemaAsyncSafe类
z-schema-base.ts → 核心验证编排逻辑
schema-compiler.ts → $ref解析、id收集、Schema编译
schema-validator.ts → 基于元Schema的Schema层级验证
json-validation.ts → 实例验证(类型、约束、组合器)
schema-cache.ts → 按URI/id缓存Schema
errors.ts → 错误码(Errors对象) + ValidateError类
format-validators.ts → 内置 + 自定义格式验证器
report.ts → 错误归集(Report, SchemaErrorDetail)
json-schema.ts → 通用JSON Schema定义 + 工具函数
json-schema-versions.ts → 版本专属类型联合 + 版本映射
z-schema-options.ts → 配置项接口 + 默认值 + normalizeOptions方法
z-schema-reader.ts → Schema读取器类型
z-schema-versions.ts → 将打包的元Schema注册到缓存中
utils/ → 纯工具函数(数组、克隆、json、uri等)
schemas/ → 打包的元Schema(构建时生成)Validation pipeline
验证流水线
- Schema compilation (): resolves
schema-compiler.ts, collects$ref/id, registers in cache$id - Schema validation (): validates schema against its meta-schema
schema-validator.ts - JSON validation (): validates data against compiled schema — type checks, constraints, combiners (
json-validation.ts/allOf/anyOf/oneOf),nottracking, format checksunevaluated* - Report (): errors accumulate in a
report.ts, then convert toReportValidateError
- Schema编译():解析
schema-compiler.ts、收集$ref/id、注册到缓存$id - Schema验证():基于对应元Schema验证Schema本身合法性
schema-validator.ts - JSON验证():基于编译后的Schema验证数据 — 类型检查、约束校验、组合器(
json-validation.ts/allOf/anyOf/oneOf)逻辑、not追踪、格式校验unevaluated* - 报告生成():错误归集到
report.ts对象,之后转换为ReportValidateError
Common tasks
常见任务
Adding a new error code
新增错误码
- Add the error to the object in
Errors:src/errors.tstypescriptMY_NEW_ERROR: 'Description with {0} placeholder', - Use in the validation logic.
report.addError('MY_NEW_ERROR', [param]) - Write tests verifying the error code is produced.
- 在的
src/errors.ts对象中添加新错误:ErrorstypescriptMY_NEW_ERROR: 'Description with {0} placeholder', - 在验证逻辑中使用抛出该错误。
report.addError('MY_NEW_ERROR', [param]) - 编写测试用例验证错误码可以正常触发。
Adding a new format validator
新增格式验证器
- Write the validator function in :
src/format-validators.tstypescriptconst myFormatValidator: FormatValidatorFn = (input: unknown) => { if (typeof input !== 'string') return true; return /^pattern$/.test(input); }; - Register it in the record:
inbuiltValidatorstypescriptconst inbuiltValidators = { // ...existing 'my-format': myFormatValidator, }; - Add tests in .
test/spec/format-validators.spec.ts
- 在中编写验证函数:
src/format-validators.tstypescriptconst myFormatValidator: FormatValidatorFn = (input: unknown) => { if (typeof input !== 'string') return true; return /^pattern$/.test(input); }; - 在对象中注册该验证器:
inbuiltValidatorstypescriptconst inbuiltValidators = { // ...现有验证器 'my-format': myFormatValidator, }; - 在中添加测试用例。
test/spec/format-validators.spec.ts
Adding a new option
新增配置项
- Add the option to in
ZSchemaOptions.src/z-schema-options.ts - Add a default value in .
defaultOptions - If the option is part of , add it to the
strictModeblock instrictMode.normalizeOptions - Document it in .
docs/options.md - Write tests.
- 在的
src/z-schema-options.ts接口中添加新配置项。ZSchemaOptions - 在中添加默认值。
defaultOptions - 如果该配置项属于的一部分,在
strictMode的normalizeOptions代码块中添加对应逻辑。strictMode - 在中添加配置项说明。
docs/options.md - 编写测试用例。
Implementing a new JSON Schema keyword
实现新的JSON Schema关键字
- Add validation logic in (for data validation) or
src/json-validation.ts(for schema-level validation).src/schema-validator.ts - Guard with a draft version check if the keyword is draft-specific.
- Remove relevant entries from /
excludedFilesinexcludedTests.test/spec/json-schema-test-suite.common.ts - Run the JSON Schema Test Suite to confirm compliance:
bash
npx vitest run --silent=false --project node -t "draft2020-12/newKeyword" - Export any new types through .
src/index.ts
- 在(数据验证逻辑)或
src/json-validation.ts(Schema层级验证逻辑)中添加验证逻辑。src/schema-validator.ts - 如果关键字是特定draft版本专属,添加版本检查逻辑。
- 从的
test/spec/json-schema-test-suite.common.ts/excludedFiles中移除相关条目。excludedTests - 运行JSON Schema测试套件验证合规性:
bash
npx vitest run --silent=false --project node -t "draft2020-12/newKeyword" - 通过导出所有新增类型。
src/index.ts
Modifying existing behavior
修改现有行为
- Find the relevant module using the codebase map above.
- Make changes following code conventions (see below).
- Run the full test suite — regressions often appear in other drafts.
- 参考上方的代码库结构找到对应模块。
- 遵循代码规范进行修改(见下文)。
- 运行完整测试套件 — 经常会在其他版本的draft中出现回归问题。
Test framework
测试框架
- Vitest with .
globals: true - Two projects: node and browser (Playwright: Chromium, Firefox, WebKit).
- Tests live in .
test/spec/
- 采用Vitest,开启配置
globals: true - 包含两个测试项目:node和browser(Playwright驱动:Chromium、Firefox、WebKit)
- 测试用例存放于目录
test/spec/
File naming
文件命名规则
| Suffix | Runs in |
|---|---|
| Both node and browser |
| Node only |
| Browser only |
| 后缀 | 运行环境 |
|---|---|
| Node和浏览器环境都运行 |
| 仅Node环境运行 |
| 仅浏览器环境运行 |
Running tests
运行测试
bash
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 # coveragebash
npm test # 运行所有测试
npm run test:node # 仅运行Node端测试
npx vitest run --silent=false --project node -t "draft4/type" # 运行单个测试用例
npm run test:coverage # 生成测试覆盖率报告Test pattern
测试写法示例
typescript
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');
});
});typescript
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 Suite
JSON Schema测试套件
Official test cases loaded via . To enable tests for a newly implemented feature, remove entries from / and confirm they pass.
test/spec/json-schema-test-suite.common.tsexcludedFilesexcludedTests官方测试用例通过加载。如果要为新实现的功能启用测试,请从/中移除对应条目并确认测试通过。
test/spec/json-schema-test-suite.common.tsexcludedFilesexcludedTestsCode conventions
代码约定
- TypeScript , ESM with
strict: trueimport extensions in.jssrc/ - import extensions in
.ts(viatest/)allowImportingTsExtensions - for type-only imports (enforced by ESLint)
import type - Import order: type-only → side-effect → node builtins → packages → relative
- Prettier: 120 char width, single quotes, trailing commas (es5), semicolons
- Classes/types: — functions/variables:
PascalCase— errors:camelCaseUPPER_SNAKE_CASE - All public API exported through
src/index.ts - Internal types stay unexported
- Schemas in are generated by
src/schemas/— do not edit manuallyscripts/copy-schemas.mts - is a git submodule — do not commit changes to it
json-schema-spec/
- TypeScript开启,
strict: true目录下ESM导入使用src/扩展名.js - 目录下导入使用
test/扩展名(通过.ts配置支持)allowImportingTsExtensions - 类型导入使用(由ESLint强制校验)
import type - 导入顺序:类型导入 → 副作用导入 → Node内置模块 → 第三方依赖 → 相对路径导入
- Prettier配置:120字符宽度、单引号、尾逗号(es5规则)、分号
- 类/类型命名:— 函数/变量命名:
PascalCase— 错误码命名:camelCaseUPPER_SNAKE_CASE - 所有公共API通过导出
src/index.ts - 内部类型不对外导出
- 下的Schema由
src/schemas/生成 — 请勿手动编辑scripts/copy-schemas.mts - 是git子模块 — 请勿提交对它的修改
json-schema-spec/
PR checklist
PR检查清单
- [ ] Branch from `main`
- [ ] Changes follow code conventions
- [ ] npm run lint:check passes
- [ ] npm run format:check passes
- [ ] 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- [ ] 从`main`分支创建开发分支
- [ ] 修改符合代码规范
- [ ] npm run lint:check 检查通过
- [ ] npm run format:check 检查通过
- [ ] npm run build 构建通过
- [ ] npm run build:tests 测试类型检查通过
- [ ] npm test 全部测试通过(Node + 浏览器端)
- [ ] 新增的公共类型/变量已通过src/index.ts导出
- [ ] 新功能已添加测试用例
- [ ] 若修改了公共API,已更新docs/目录下的文档
- [ ] 若适用,已取消对应JSON Schema测试套件条目的排除配置Reference files
参考文件
- references/architecture-details.md — Full module dependency diagram, factory pattern, build outputs, and internal types
- references/architecture-details.md — 完整模块依赖图、工厂模式、构建输出和内部类型说明