refactor(schema): share compact schema field checks (#17392)

This commit is contained in:
Vincent Koc
2026-12-06 13:07:00 +08:00
committed by GitHub
parent 1a8b783331
commit db54e1eca0
+20 -37
View File
@@ -121,6 +121,14 @@ class BudgetedSchemaSerializer {
return true;
}
private isStrippedAnnotation(key: string, isRoot: boolean): boolean {
return (
this.strip &&
annotationKeys.has(key) &&
!(isRoot && key === "description")
);
}
private isSkippedKey(
key: string,
position: SchemaPosition,
@@ -137,50 +145,25 @@ class BudgetedSchemaSerializer {
)
return true;
const isRoot = mode === "root" || mode === "root-siblings";
return (
this.strip &&
annotationKeys.has(key) &&
!(isRoot && key === "description")
);
return this.isStrippedAnnotation(key, isRoot);
}
private isEffectivelyEmpty(
private hasSchemaField(
value: Record<string, unknown>,
isRoot: boolean,
mode: "all" | "siblings",
): boolean {
for (const key in value) {
if (!Object.hasOwn(value, key) || value[key] === undefined) continue;
if (
this.strip &&
annotationKeys.has(key) &&
!(isRoot && key === "description")
mode === "siblings" &&
(key === "$ref" ||
key === "$id" ||
key === "$anchor" ||
key === "$schema")
)
continue;
return false;
}
return true;
}
private hasSiblings(
value: Record<string, unknown>,
isRoot: boolean,
): boolean {
for (const key in value) {
if (!Object.hasOwn(value, key) || value[key] === undefined) continue;
if (
key === "$ref" ||
key === "$id" ||
key === "$anchor" ||
key === "$schema"
)
continue;
if (
this.strip &&
annotationKeys.has(key) &&
!(isRoot && key === "description")
)
continue;
return true;
if (!this.isStrippedAnnotation(key, isRoot)) return true;
}
return false;
}
@@ -242,7 +225,7 @@ class BudgetedSchemaSerializer {
this.resolved = false;
return false;
}
if (this.isEffectivelyEmpty(value, isRoot))
if (!this.hasSchemaField(value, isRoot, "all"))
return this.emitAscii(EMPTY_SCHEMA_JSON);
if (Object.hasOwn(value, "$ref") && typeof value.$ref === "string")
return this.visitReference(value, value.$ref, currentScope, isRoot);
@@ -273,7 +256,7 @@ class BudgetedSchemaSerializer {
this.resolved = false;
return false;
}
const siblings = this.hasSiblings(value, isRoot);
const siblings = this.hasSchemaField(value, isRoot, "siblings");
// Draft 7 ignores siblings, while clients such as Ajv also apply them.
// Do not label either interpretation an equivalent inline advertisement.
if (currentScope.dialect === "draft-07" && siblings) {
@@ -325,7 +308,7 @@ class BudgetedSchemaSerializer {
position === "schema" &&
key === "not" &&
isSchemaObject(child) &&
this.isEffectivelyEmpty(child, false)
!this.hasSchemaField(child, false, "all")
) {
if (!this.emitAscii("{}")) return false;
continue;