@haggholm/json-schema-merge-allof

中文文档
1.0.2发布于 2020/11/14MITTypeScriptCommonJS近 30 天下载 4652

Simplify your schema by combining allOf into the root schema, safely.

原始使用文档
文档目录14 节
  1. Features
  2. How
  3. not
  4. Options
  5. Combined resolvers
  6. Default resolver
  7. Resolvers
  8. Lossy vs lossless
  9. $ref
  10. Other libraries
  11. Restrictions
  12. Roadmap
  13. Contributing
  14. License

json-schema-merge-allof Build Status Coverage Status

Merge schemas combined using allOf into a more readable composed schema free from allOf.

npm install json-schema-merge-allof --save

Features

  • Real and safe merging of schemas combined with allOf
  • Takes away all allOf found in the whole schema
  • Lossless in terms of validation rules, merged schema does not validate more or less than the original schema
  • Results in a more readable root schema
  • Removes almost all logical impossibilities
  • Throws if no logical intersection is found (your schema would not validate anything from the start)
  • Validates in a way not possible by regular simple meta validators
  • Correctly considers additionalProperties, patternProperties and properties as a part of an whole when merging schemas containing those
  • Correctly considers items and additionalItems as a whole when merging schemas containing those
  • Supports merging schemas with items as array and direct schema
  • Supports merging dependencies when mixed array and schema
  • Supports all JSON schema core/validation keywords (v6, use custom resolvers to support other keywords)
  • Option to override common impossibility like adding properties when using additionalProperties: false
  • Pluggable keyword resolvers

How

Since allOf require ALL schemas provided (including the parent schema) to apply, we can iterate over all the schemas, extracting all the values for say, type, and find the intersection of valid values. Here is an example:

{
  type: ['object', 'null'],
  additionalProperties: {
    type: 'string',
    minLength: 5
  },
  allOf: [{
    type: ['array', 'object'],
    additionalProperties: {
      type: 'string',
      minLength: 10,
      maxLength: 20
    }
  }]
}

This result in the schema :

{
  type: 'object',
  additionalProperties: {
    type: 'string',
    minLength: 10,
    maxLength: 20
  }
}

Notice that type now excludes null and array since those are not logically possible. Also minLength is raised to 10. The other properties have no conflict and are merged into the root schema with no resolving needed.

For other keywords other methods are used, here are some simple examples:

  • minLength, minimum, minItems etc chooses the highest value of the conflicting values.
  • maxLength, maximum, maxItems etc chooses the lowest value of the conflicting values.
  • uniqueItems is true if any of the conflicting values are true

As you can see above the strategy is to choose the most restrictive of the set of values that conflict. For some keywords that is done by intersection, for others like required it is done by a union of all the values, since that is the most restrictive.

What you are left with is a schema completely free of allOf. Except for in a couple of values that are impossible to properly intersect/combine:

not

When multiple conflicting not values are found, we also use the approach that pattern use, but instead of allOf we use anyOf. When extraction of common rules from anyOf is in place this can be further simplified.

Options

ignoreAdditionalProperties default false

Allows you to combine schema properties even though some schemas have additionalProperties: false This is the most common issue people face when trying to expand schemas using allOf and a limitation of the json schema spec. Be aware though that the schema produced will allow more than the original schema. But this is useful if just want to combine schemas using allOf as if additionalProperties wasn't false during the merge process. The resulting schema will still get additionalProperties set to false.

resolvers Object Override any default resolver like this:

mergeAllOf(schema, {
  resolvers: {
    title: function(values, path, mergeSchemas, options) {
      // choose what title you want to be used based on the conflicting values
      // resolvers MUST return a value other than undefined
    }
  }
})

deep boolean, default true If false, resolves only the top-level allOf keyword in the schema.

If true, resolves all allOf keywords in the schema.

The function is passed:

  • values an array of the conflicting values that need to be resolved
  • path an array of strings containing the path to the position in the schema that caused the resolver to be called (useful if you use the same resolver for multiple keywords, or want to implement specific logic for custom paths)
  • mergeSchemas a function you can call that merges an array of schemas
  • options the options mergeAllOf was called with

Combined resolvers

No separate resolver is called for patternProperties and additionalProperties, only the properties resolver is called. Same for additionalItems, only items resolver is called. This is because those keywords need to be resolved together as they affect each other.

Those two resolvers are expected to return an object containing the resolved values of all the associated keywords. The keys must be the name of the keywords. So the properties resolver need to return an object like this containing the resolved values for each keyword:

{
    properties: ...,
    patternProperties: ...,
    additionalProperties: ...,
}

Also the resolve function is not passed mergeSchemas, but an object mergers that contains mergers for each of the related keywords. So properties get passed an object like this:

var mergers = {
    properties: function mergeSchemas(schemas, childSchemaName){...},
    patternProperties: function mergeSchemas(schemas, childSchemaName){...},
    additionalProperties: function mergeSchemas(schemas){...},
}

Some of the mergers requires you to supply a string of the name or index of the subschema you are currently merging. This is to make sure the path passed to child resolvers are correct.

Default resolver

You can set a default resolver that catches any unknown keyword. Let's say you want to use the same strategy as the ones for the meta keywords, to use the first value found. You can accomplish that like this:

mergeJsonSchema({
  ...
}, {
  resolvers: {
    defaultResolver: mergeJsonSchema.options.resolvers.title
  }
})

Resolvers

Resolvers are called whenever multiple conflicting values are found on the same position in the schemas.

You can override a resolver by supplying it in the options.

Lossy vs lossless

All built in reducers for validation keywords are lossless, meaning that they don't remove or add anything in terms of validation.

For meta keywords like title, description, $id, $schema, default the strategy is to use the first possible value if there are conflicting ones. So the root schema is prioritized. This process possibly removes some meta information from your schema. So it's lossy. Override this by providing custom resolvers.

$ref

If one of your schemas contain a $ref property you should resolve them using a ref resolver like json-schema-ref-parser to dereference your schema for you first. Resolving $refs is not the task of this library.

Other libraries

There exists some libraries that claim to merge schemas combined with allOf, but they just merge schemas using a very basic logic. Basically just the same as lodash merge. So you risk ending up with a schema that allows more or less than the original schema would allow.

Restrictions

We cannot merge schemas that are a logical impossibility, like:

{
  type: 'object',
  allOf: [{
    type: 'array'
  }]
}

The library will then throw an error reporting the values that had no valid intersection. But then again, your original schema wouldn't validate anything either.

Roadmap

  • Treat the interdependent validations like properties and additionalProperties as one resolver (and items additionalItems)
  • Extract repeating validators from anyOf/oneOf and merge them with parent schema
  • After extraction of validators from anyOf/oneOf, compare them and remove duplicates.
  • If left with only one in anyOf/oneOf then merge it to the parent schema.
  • Expose seperate tools for validation, extraction
  • Consider adding even more logical validation (like minLength <= maxLength)

Contributing

Create tests for new functionality and follow the eslint rules.

License

MIT © Martin Hansen

版本与发布记录

@haggholm/json-schema-merge-allof 共发布 3 个版本,首次发布于 2020/10/29;过去 12 个月发布了 0 个版本。

版本发布日期距今
1.0.2latest2020/11/146 年前
1.0.12020/11/146 年前
1.0.02020/10/296 年前

关于 @haggholm/json-schema-merge-allof 的常见问题

@haggholm/json-schema-merge-allof 是什么?

Simplify your schema by combining allOf into the root schema, safely.

如何安装 @haggholm/json-schema-merge-allof?

在项目目录运行 npm install @haggholm/json-schema-merge-allof,或使用 pnpm add / yarn add / bun add。

@haggholm/json-schema-merge-allof 支持 TypeScript 吗?

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

@haggholm/json-schema-merge-allof 支持 ESM 还是 CommonJS?

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

@haggholm/json-schema-merge-allof 可以商用吗?

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

@haggholm/json-schema-merge-allof 的下载量有多少?

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

@haggholm/json-schema-merge-allof 还在维护吗?

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