fix(plugins): guard legacy zod schemas without toJSONSchema
This commit is contained in:
committed by
Peter Steinberger
parent
dd145f1346
commit
9f4764cd41
17
src/channels/plugins/config-schema.test.ts
Normal file
17
src/channels/plugins/config-schema.test.ts
Normal 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 });
|
||||
});
|
||||
});
|
||||
@@ -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,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user