Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: merge compatible definitions in union types #722

Draft
wants to merge 7 commits into
base: next
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
13 changes: 13 additions & 0 deletions src/TypeFormatter/UnionTypeFormatter.ts
Expand Up @@ -4,6 +4,7 @@ import { SubTypeFormatter } from "../SubTypeFormatter";
import { BaseType } from "../Type/BaseType";
import { UnionType } from "../Type/UnionType";
import { TypeFormatter } from "../TypeFormatter";
import { mergeDefinitions } from "../Utils/mergeDefinitions";
import { uniqueArray } from "../Utils/uniqueArray";

export class UnionTypeFormatter implements SubTypeFormatter {
Expand Down Expand Up @@ -45,6 +46,18 @@ export class UnionTypeFormatter implements SubTypeFormatter {
}
}

for (let idx = 0; idx < flattenedDefinitions.length - 1; idx++) {
for (let comp = idx + 1; comp < flattenedDefinitions.length; ) {
const merged = mergeDefinitions(flattenedDefinitions[idx], flattenedDefinitions[comp]);
if (merged) {
flattenedDefinitions[idx] = merged;
flattenedDefinitions.splice(comp, 1);
} else {
comp++;
}
}
}

return flattenedDefinitions.length > 1
? {
anyOf: flattenedDefinitions,
Expand Down
25 changes: 25 additions & 0 deletions src/Utils/mergeDefinitions.ts
@@ -0,0 +1,25 @@
import { Definition } from "../Schema/Definition";
import { uniqueArray } from "./uniqueArray";

/**
* Attempt to merge two disjoint definitions into one. Definitions are disjoint
* (and therefore mergeable) if all of the following are true:
* 1) Each has a 'type' property, and they share no types in common,
* 2) The cross-type validation properties 'enum' and 'const' are not on either definition, and
* 3) The two definitions have no properties besides 'type' in common.
*
* Returns the merged definition, or null if the two defs were not disjoint.
*/
export function mergeDefinitions(def1: Definition, def2: Definition): Definition | null {
const { type: type1, ...props1 } = def1;
const { type: type2, ...props2 } = def2;
const types = [type1!, type2!].flat();
if (!type1 || !type2 || uniqueArray(types).length !== types.length) {
return null;
}
const keys = [Object.keys(props1), Object.keys(props2)].flat();
dmchurch marked this conversation as resolved.
Show resolved Hide resolved
if (keys.includes("enum") || keys.includes("const") || uniqueArray(keys).length !== keys.length) {
return null;
}
return { type: types, ...props1, ...props2 };
}