fix(plugins): guard legacy zod schemas without toJSONSchema

This commit is contained in:
pandego
2026-02-24 02:28:34 +01:00
committed by Peter Steinberger
parent dd145f1346
commit 9f4764cd41
2 changed files with 37 additions and 4 deletions

View File

@@ -0,0 +1,17 @@
import { describe, expect, it } from "vitest";
import { z } from "zod";
import { buildChannelConfigSchema } from "./config-schema.js";
describe("buildChannelConfigSchema", () => {
it("builds json schema when toJSONSchema is available", () => {
const schema = z.object({ enabled: z.boolean().default(true) });
const result = buildChannelConfigSchema(schema);
expect(result.schema).toMatchObject({ type: "object" });
});
it("falls back when toJSONSchema is missing (zod v3 plugin compatibility)", () => {
const legacySchema = {} as unknown as Parameters<typeof buildChannelConfigSchema>[0];
const result = buildChannelConfigSchema(legacySchema);
expect(result.schema).toEqual({ type: "object", additionalProperties: true });
});
});

View File

@@ -1,11 +1,27 @@
import type { ZodTypeAny } from "zod";
import type { ChannelConfigSchema } from "./types.plugin.js";
type ZodSchemaWithToJsonSchema = ZodTypeAny & {
toJSONSchema?: (params?: Record<string, unknown>) => unknown;
};
export function buildChannelConfigSchema(schema: ZodTypeAny): ChannelConfigSchema {
const schemaWithJson = schema as ZodSchemaWithToJsonSchema;
if (typeof schemaWithJson.toJSONSchema === "function") {
return {
schema: schemaWithJson.toJSONSchema({
target: "draft-07",
unrepresentable: "any",
}) as Record<string, unknown>,
};
}
// Compatibility fallback for plugins built against Zod v3 schemas,
// where `.toJSONSchema()` is unavailable.
return {
schema: schema.toJSONSchema({
target: "draft-07",
unrepresentable: "any",
}) as Record<string, unknown>,
schema: {
type: "object",
additionalProperties: true,
},
};
}