Skip to content

Resolved FIXME #2147

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions packages/core/src/v3/zodMessageHandler.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { describe, it, expect, vi } from "vitest";
import { EventEmitter } from "node:events";
import { ZodMessageHandler } from "./zodMessageHandler.js";
import { z } from "zod";

describe("ZodMessageHandler.registerHandlers", () => {
const schema = { TEST: z.object({ foo: z.string() }) } as const;

it("handles messages with an explicit payload field", async () => {
const handler = vi.fn(async (payload: { foo: string }) => payload);
const messageHandler = new ZodMessageHandler({ schema, messages: { TEST: handler } });
const emitter = new EventEmitter();
messageHandler.registerHandlers(emitter);

const ack = await new Promise((resolve) => {
emitter.emit("TEST", { payload: { foo: "bar" }, version: "v1" }, resolve);
});

expect(handler).toHaveBeenCalledWith({ foo: "bar" });
expect(ack).toEqual({ foo: "bar" });
});

it("handles messages without a payload field", async () => {
const handler = vi.fn(async (payload: { foo: string }) => payload);
const messageHandler = new ZodMessageHandler({ schema, messages: { TEST: handler } });
const emitter = new EventEmitter();
messageHandler.registerHandlers(emitter);

const ack = await new Promise((resolve) => {
emitter.emit("TEST", { foo: "baz", version: "v1" }, resolve);
});

expect(handler).toHaveBeenCalledWith({ foo: "baz" });
expect(ack).toEqual({ foo: "baz" });
});
});
15 changes: 11 additions & 4 deletions packages/core/src/v3/zodMessageHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,12 +179,19 @@ export class ZodMessageHandler<TMessageCatalog extends ZodMessageCatalogSchema>

let ack: Awaited<ReturnType<ZodMessageHandler<TMessageCatalog>["handleMessage"]>>;

// FIXME: this only works if the message doesn't have genuine payload prop
if ("payload" in message) {
ack = await this.handleMessage({ type: eventName, ...message });
// Use runtime validation to detect payload presence
const hasPayload =
typeof message === "object" &&
message !== null &&
z.object({ payload: z.unknown() }).passthrough().safeParse(message).success;

if (hasPayload) {
ack = await this.handleMessage({ type: eventName, ...(message as any) });
} else {
// Handle messages not sent by ZodMessageSender
const { version, ...payload } = message;
const messageObj =
typeof message === "object" && message !== null ? (message as any) : {};
const { version, ...payload } = messageObj;
ack = await this.handleMessage({ type: eventName, version, payload });
}

Expand Down
20 changes: 18 additions & 2 deletions packages/core/src/v3/zodNamespace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,19 @@ import {
ZodSocketMessageCatalogSchema,
ZodSocketMessageHandler,
ZodSocketMessageHandlers,
GetSocketMessagesWithCallback,
} from "./zodSocket.js";
// @ts-ignore
import type { DefaultEventsMap, EventsMap } from "socket.io/dist/typed-events";
import { z } from "zod";
import { SimpleStructuredLogger, StructuredLogger } from "./utils/structuredLogger.js";

type AssertNoCallbackSchemas<T extends ZodSocketMessageCatalogSchema> = [
GetSocketMessagesWithCallback<T>,
] extends [never]
? Record<string, never>
: { __error__: GetSocketMessagesWithCallback<T> };

interface ExtendedError extends Error {
data?: any;
}
Expand All @@ -32,7 +39,7 @@ interface ZodNamespaceOptions<
TServerMessages extends ZodSocketMessageCatalogSchema,
TServerSideEvents extends EventsMap = DefaultEventsMap,
TSocketData extends z.ZodObject<any, any, any> = any,
> {
> extends AssertNoCallbackSchemas<TServerMessages> {
io: Server;
name: string;
clientMessages: TClientMessages;
Expand Down Expand Up @@ -108,7 +115,16 @@ export class ZodNamespace<

this.namespace = this.io.of(opts.name);

// FIXME: There's a bug here, this sender should not accept Socket schemas with callbacks
const invalidMessages = Object.entries(opts.serverMessages)
.filter(([, value]) => "callback" in value && value.callback)
.map(([key]) => key);

if (invalidMessages.length > 0) {
throw new Error(
`serverMessages with callbacks are not supported: ${invalidMessages.join(", ")}`
);
}

this.sender = new ZodMessageSender({
schema: opts.serverMessages,
sender: async (message) => {
Expand Down
38 changes: 38 additions & 0 deletions packages/core/test/zodNamespace.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { describe, it, expect } from "vitest";
import { ZodNamespace } from "../src/v3/zodNamespace.js";
import type { Server } from "socket.io";
import { z } from "zod";

const createStubServer = (): Server => {
const namespace = {
use: () => namespace,
on: () => namespace,
emit: () => {},
fetchSockets: async () => [],
} as any;
return { of: () => namespace } as any;
};

describe("ZodNamespace", () => {
it("throws when serverMessages include callbacks", () => {
const io = createStubServer();

const clientMessages = {} as const;
const serverMessages = {
TEST: {
message: z.object({ version: z.literal("v1").default("v1") }),
callback: z.void(),
},
} as const;

expect(
() =>
new ZodNamespace({
io,
name: "test",
clientMessages,
serverMessages,
})
).toThrowError(/callbacks are not supported/);
});
});