@collective-intelligence/schema-codegen

中文文档
0.3.2发布于 2026/11/15TypeScriptES Module零依赖近 30 天下载 1962

Pure generator from Draft 2020-12 JSON Schema documents to TypeScript, Zod and Effect Schema source.

原始使用文档
文档目录6 节
  1. Generate a module
  2. File header
  3. Authority and requirements
  4. Keywords
  5. Target limits
  6. Checks

@collective-intelligence/schema-codegen

Pure generator from Draft 2020-12 JSON Schema documents to TypeScript source. It has no runtime dependency. It does no file IO and has no CLI. Callers pass documents in and write the returned text. The ci package codegen command of @collective-intelligence/cli is the caller for package declarations; see the CLI README.

Targets:

  • types: plain TypeScript types.
  • zod: Zod schemas and inferred types.
  • effect: effect/Schema schemas and types.

Generate a module

The package exports generateSchemaModule and its types. The function is pure and never throws. It returns the source text of one file for one target.

import { generateSchemaModule } from "@collective-intelligence/schema-codegen"

const result = generateSchemaModule({
  target: "zod",
  header: { packageFqn: "acme.billing", packageVersion: "1.0.0" },
  schemas: [
    {
      name: "acme.billing.invoice#input",
      document: { type: "object", properties: { id: { type: "string" } } },
      fidelity: "exact"
    }
  ]
})

if (result.errors === undefined) {
  // Write result.source to <out>/acme.billing/zod.ts. result.warnings is data.
}
  • SchemaInput.name is <component fqn>#<slot label>. The generator builds the export name from it: the PascalCase component fqn without the package fqn, then the PascalCase slot label. Exports are sorted by component fqn, then slot label. A name without #<slot label>, an invalid identifier, a name that the target file already uses and two schemas with one export name are errors (reserved_name, invalid_name, name_clash). The zod file uses z, RegExp and Infinity; the effect file uses Schema, RegExp and Infinity. The types file reserves no name. This holds for the names of $defs entries too.
  • SchemaInput.fidelity is exact or structural. A structural schema can be stricter at runtime than its JSON Schema. Each structural schema gives a structural_fidelity warning.
  • GenerateResult is { source, warnings } or { errors }. One run collects every error, each with a code, the schema name, a JSON Pointer and the keyword (null when no single keyword is at fault).
  • Warning.kind is structural_fidelity, dropped_keyword, format_annotation_only or closed_object_unenforced.
  • The output is byte-stable. The same input gives the same text: no timestamp, tool version or hash. The library does not call a formatter.

File header

Every file starts with a // comment header. The header names the target, the package fqn and the package version, and says that the schemas are not runtime validation authority. A blank line follows it. The effect header has one more line about excess keys.

// @generated
// Target: zod
// Package: acme.billing
// Version: 1.0.0
// Generated schemas are a convenience and not runtime validation authority.
// The backend host validates.

The @generated marker in the leading comment is how the CLI recognizes a file that it may overwrite.

Authority and requirements

Generated schemas are a convenience. The backend host validates; generated files never replace it. The schemas describe the wire shape: the encoded JSON, not decoded runtime values.

  • zod output needs zod 4.4 or later. It uses z.xor for oneOf.
  • effect output needs Effect v4 and imports effect/Schema.
  • types output has no import.

Keywords

Supported keywords:

  • Types and values: type, enum, const.
  • String: minLength, maxLength, pattern, format.
  • Number: minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf.
  • Object: properties, required, additionalProperties, minProperties, maxProperties.
  • Array: items, prefixItems, minItems, maxItems, uniqueItems.
  • Composition: anyOf, oneOf, allOf.
  • References: local $ref to a $defs entry of the same document, and a root $defs. A $defs entry becomes a local declaration that is not exported.
  • Annotations: title, description, default, examples, deprecated, readOnly, writeOnly.
  • Ignored: $schema, $id, $anchor, $comment, $vocabulary and every keyword that starts with x-.

A constraint keyword needs type. minLength, pattern, format, the number bounds, properties, required, additionalProperties, minProperties, maxProperties, items, prefixItems, minItems, maxItems and uniqueItems only constrain values of their own type, so a schema without type also accepts every other value, and no target can say that. The generator does not guess a type: each such keyword fails the run with unsupported_keyword_combination, and keyword is the constraint. This holds in allOf, anyOf and oneOf members, and in $defs entries, too.

A name in required that properties does not declare is a property that additionalProperties describes: any value, or the additionalProperties schema. With additionalProperties: false no object can satisfy it, so it fails with unsupported_keyword_combination (required+additionalProperties) at the required entry.

prefixItems describes the positions that exist and does not make them exist. A position is required only below minItems; later positions are optional tuple elements ([A, B?]). A position at or beyond maxItems does not exist, and items after the last one is dropped.

These keywords fail the run, because the generator cannot express them: contains, dependentRequired, if, then, else, not, patternProperties, unevaluatedItems, unevaluatedProperties, $dynamicRef, $defs below the root, a remote $ref, a recursive $ref, and a $ref that does not point to a $defs entry. Any other keyword that does not start with x- is an unknown_keyword error. The generator never degrades a shape that changes what the schema accepts.

A validation-only keyword with no equivalent in a target is dropped. It stays as an annotation and gives a warning (dropped_keyword or format_annotation_only).

Target limits

  • types: a type cannot check values. Validation keywords (minLength, maxLength, pattern, format, the number bounds, the property and item counts, uniqueItems) become JSDoc tags and give dropped_keyword warnings.
  • zod: objects with additionalProperties: false are z.strictObject. An object with no properties and no additionalProperties is an open record, as in the other targets. format is checked for date-time, email, uuid and uri; any other format stays as .meta data and gives format_annotation_only. uniqueItems, minProperties and maxProperties stay as .meta data and give dropped_keyword.
  • effect: Schema.Struct has no closed object. additionalProperties: false is not enforced and gives one closed_object_unenforced warning per object; excess keys are rejected only with the decode option onExcessProperty: "error". Only format: uuid is a format check; any other format stays as an annotation and gives format_annotation_only. An object that has declared keys and no extra schema cannot count its keys, so minProperties and maxProperties stay as annotations and give dropped_keyword. allOf merges plain objects only; other members (allof_not_plain_objects, also for a $ref to one), and members that declare one property in different ways (allof_property_conflict), fail the run. Keywords of one schema object that do not merge, for example a $ref with a constraint or a type with oneOf, fail with unsupported_keyword_combination; its keyword lists them joined with +.

Checks

bun test tests/package-contract.test.ts
bun run type-check
bun run build
bun run test:pack

版本与发布记录

@collective-intelligence/schema-codegen 共发布 20 个版本,首次发布于 2026/10/28;过去 12 个月发布了 20 个版本。

版本发布日期距今
0.3.2latest2026/11/15今天
0.3.12026/11/15今天
0.3.02026/11/141 天前
0.2.322026/11/141 天前
0.1.312026/11/142 天前
0.1.302026/11/142 天前

关于 @collective-intelligence/schema-codegen 的常见问题

@collective-intelligence/schema-codegen 是什么?

Pure generator from Draft 2020-12 JSON Schema documents to TypeScript, Zod and Effect Schema source.

如何安装 @collective-intelligence/schema-codegen?

在项目目录运行 npm install @collective-intelligence/schema-codegen,或使用 pnpm add / yarn add / bun add。

@collective-intelligence/schema-codegen 支持 TypeScript 吗?

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

@collective-intelligence/schema-codegen 支持 ESM 还是 CommonJS?

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

@collective-intelligence/schema-codegen 可以商用吗?

@collective-intelligence/schema-codegen 使用 未声明 许可。package.json 没有声明许可证。没有许可证的代码默认保留全部权利,商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括,不构成法律意见,请以许可原文为准。

@collective-intelligence/schema-codegen 的下载量有多少?

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

@collective-intelligence/schema-codegen 还在维护吗?

最新版本 0.3.2 发布于 2026/11/15(今天);至今共发布 20 个版本,其中过去 12 个月发布了 20 个;首次发布于 2026/10/28。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。