From d93e72b37fe4fcdd252bc99dda3fc652456ca805 Mon Sep 17 00:00:00 2001 From: jojo Date: Sat, 31 Oct 2026 14:21:54 +0800 Subject: [PATCH] fix: normalize nested arrays after filtering null values --- typescript/src/typechat.ts | 4 ++-- typescript/test/failure.test.ts | 26 ++++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/typescript/src/typechat.ts b/typescript/src/typechat.ts index af7a6a8b..68739ddd 100644 --- a/typescript/src/typechat.ts +++ b/typescript/src/typechat.ts @@ -189,14 +189,14 @@ export function createJsonTranslator(model: TypeChatLanguageMo function stripNulls(obj: any) { let keysToDelete: string[] | undefined; for (const k in obj) { - const value = obj[k]; + let value = obj[k]; if (value === null) { (keysToDelete ??= []).push(k); } else { if (Array.isArray(value)) { if (value.some(x => x === null)) { - obj[k] = value.filter(x => x !== null); + value = obj[k] = value.filter(x => x !== null); } } if (typeof value === "object") { diff --git a/typescript/test/failure.test.ts b/typescript/test/failure.test.ts index 5a5666d1..95c6b7d9 100644 --- a/typescript/test/failure.test.ts +++ b/typescript/test/failure.test.ts @@ -9,6 +9,32 @@ import { createModuleTextFromProgram, createTypeScriptJsonValidator } from "../d import { createZodJsonValidator } from "../dist/zod/index.js"; type Example = { value: number }; + +describe("stripNulls nested arrays", () => { + for (const { groups, expected } of [ + { groups: [null, [null, 1]], expected: [[1]] }, + { groups: [[null, 1], null, [null, null]], expected: [[1], []] } + ]) { + it(`normalizes nested arrays after filtering ${JSON.stringify(groups)}`, async () => { + const validator = createTypeScriptJsonValidator<{ groups: number[][] }>( + "export interface Data { groups: number[][]; }", "Data"); + try { + const model: TypeChatLanguageModel = { + complete: async () => success(JSON.stringify({ groups })) + }; + const translator = createJsonTranslator(model, validator); + translator.stripNulls = true; + translator.attemptRepair = false; + const result = await translator.translate("Return groups"); + assert.ok(result.success); + assert.deepEqual(result.data.groups, expected); + } + finally { + validator.close(); + } + }); + } +}); type IsUnknown = unknown extends T ? keyof T extends never ? true : false : false; class GetterFailure {