Skip to content

Commit 4e8fa91

Browse files
kevinccbsgclaude
andcommitted
fix: use actual schema branch count for best-match message
The totalBranches in "branch N of M" now comes from the schema's oneOf/anyOf array length, not just the count of branches with errors. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
1 parent 25a007f commit 4e8fa91

1 file changed

Lines changed: 24 additions & 2 deletions

File tree

src/validator.ts

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -345,11 +345,14 @@ function resolveCompositionErrors(
345345
branchErrors.get(branchIndex)!.push(err);
346346
}
347347

348-
const totalBranches = branchErrors.size;
349-
if (totalBranches === 0) {
348+
if (branchErrors.size === 0) {
350349
return filterNonSubErrors(errors, compositionError);
351350
}
352351

352+
// Get actual branch count from schema (not just branches with errors)
353+
const totalBranches = getSchemaCompositionBranchCount(schema, compositionError.schemaPath, keyword)
354+
?? branchErrors.size;
355+
353356
// Try discriminator resolution
354357
const discriminatorMsg = tryDiscriminatorResolution(
355358
keyword, schema, compositionError, branchErrors, payload,
@@ -469,6 +472,25 @@ function branchHasDiscriminatorValue(
469472
return false;
470473
}
471474

475+
function getSchemaCompositionBranchCount(
476+
schema: Record<string, unknown>,
477+
schemaPath: string,
478+
keyword: string,
479+
): number | null {
480+
const segments = schemaPath.replace(/^#\//, '').split('/');
481+
// Navigate to the parent, then read the keyword array length
482+
let current: unknown = schema;
483+
for (const seg of segments.slice(0, -1)) {
484+
if (current === null || current === undefined || typeof current !== 'object') return null;
485+
current = Array.isArray(current)
486+
? (current as unknown[])[parseInt(seg, 10)]
487+
: (current as Record<string, unknown>)[seg];
488+
}
489+
if (!current || typeof current !== 'object') return null;
490+
const branches = (current as Record<string, unknown>)[keyword];
491+
return Array.isArray(branches) ? branches.length : null;
492+
}
493+
472494
function filterNonSubErrors(
473495
errors: InternalError[],
474496
compositionError: InternalError,

0 commit comments

Comments
 (0)