From bddeb634b583cf4f7d5fa6cf3a1ee821e05d2923 Mon Sep 17 00:00:00 2001 From: Iwakurakaoru0822 Date: Tue, 6 Oct 2026 22:02:25 -0700 Subject: [PATCH] fix(errors): report union input issues at the union's path Zod reports union branch issues relative to the union, so a missing union-typed argument such as trace_application_feature's seed was reported at the request root, once per branch. Co-Authored-By: Claude Opus 5.5 --- src/domain/inputIssueProjection.test.ts | 23 +++++++++++++++++++++++ src/domain/inputIssueProjection.ts | 18 ++++++++++++++++-- 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/src/domain/inputIssueProjection.test.ts b/src/domain/inputIssueProjection.test.ts index 127679971..0abc83431 100644 --- a/src/domain/inputIssueProjection.test.ts +++ b/src/domain/inputIssueProjection.test.ts @@ -26,4 +26,27 @@ describe("input issue projection", () => { }, ]); }); + + it("reports union branch issues at the union's path once", () => { + const schema = z.object({ + seed: z.union([ + z.object({ value: z.string().min(1) }), + z.object({ value: z.literal(""), match: z.literal("exact") }), + ]), + }); + const missing = schema.safeParse({}); + if (missing.success) throw new Error("expected invalid input"); + expect(projectInputIssues(missing.error.issues, {})).toEqual([ + { path: ["seed"], reason: "missing_argument", expected: "object" }, + ]); + + const input = { seed: { value: 1 } }; + const nested = schema.safeParse(input); + if (nested.success) throw new Error("expected invalid input"); + expect(projectInputIssues(nested.error.issues, input)).toEqual( + expect.arrayContaining([ + { path: ["seed", "value"], reason: "invalid_type", expected: "string" }, + ]), + ); + }); }); diff --git a/src/domain/inputIssueProjection.ts b/src/domain/inputIssueProjection.ts index 1fff45e1c..08390df5a 100644 --- a/src/domain/inputIssueProjection.ts +++ b/src/domain/inputIssueProjection.ts @@ -15,9 +15,17 @@ const projectIssue = ( const path = issue.path.flatMap((part) => typeof part === "string" || typeof part === "number" ? [part] : [], ); + // Branch issue paths are relative to the union; branches often agree. if (issue.code === "invalid_union") - return issue.errors.flatMap((branch) => - branch.flatMap((branchIssue) => projectIssue(branchIssue, input)), + return uniqueIssues( + issue.errors.flatMap((branch) => + branch.flatMap((branchIssue) => + projectIssue( + { ...branchIssue, path: [...issue.path, ...branchIssue.path] }, + input, + ), + ), + ), ); if (issue.code === "unrecognized_keys") return issue.keys.map((key) => ({ @@ -58,6 +66,12 @@ const projectIssue = ( ]; }; +const uniqueIssues = ( + issues: readonly AnalysisInputIssue[], +): AnalysisInputIssue[] => [ + ...new Map(issues.map((issue) => [JSON.stringify(issue), issue])).values(), +]; + const valueAtPath = ( input: unknown, path: readonly (string | number)[],