Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/packages/chat/src/message-discovery.server.test.ts
T

144 lines
5.9 KiB
TypeScript

import { beforeEach, describe, expect, it, vi } from "vitest";
import { CHAT_PERMISSIONS } from "./permissions.js";
const mocks = vi.hoisted(() => ({
runTransaction: vi.fn(),
tx: { $queryRaw: vi.fn() },
}));
vi.mock("./repository.server.js", () => ({
runChatRepositoryTransaction: (...args: unknown[]) => mocks.runTransaction(...args),
}));
import { listChatMessageDiscovery } from "./message-discovery.server.js";
const context = {
tenantId: "tenant_1",
userId: "viewer_1",
permissions: [CHAT_PERMISSIONS.readOwnChannels],
} as const;
function row(id: string, createdAt: string, overrides: Record<string, unknown> = {}) {
return {
id,
chatId: "chat_1",
channelKind: "group",
channelName: " Montage Nord ",
projectId: null,
authorUserId: "author_1",
body: ` Nachricht ${id} `,
parentMessageId: null,
createdAt: new Date(createdAt),
...overrides,
};
}
describe("chat message discovery repository", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.runTransaction.mockImplementation(
async (_context: unknown, _permission: string, operation: (tx: typeof mocks.tx, permissions: readonly string[]) => Promise<unknown>) =>
operation(mocks.tx, [CHAT_PERMISSIONS.readOwnChannels])
);
mocks.tx.$queryRaw.mockResolvedValue([]);
});
it("searches only through the shared repository gate and returns a filter-bound cursor", async () => {
mocks.tx.$queryRaw
.mockResolvedValueOnce([
row("message_3", "2026-07-16T10:03:00.000Z"),
row("message_2", "2026-07-16T10:02:00.000Z"),
row("message_1", "2026-07-16T10:01:00.000Z"),
])
.mockResolvedValueOnce([
{ chatId: "chat_1", userId: "author_1", displayName: "Ada Lovelace", avatarUrl: "/avatars/ada" },
{ chatId: "chat_1", userId: "viewer_1", displayName: "Raffael Sheikh", avatarUrl: null },
]);
const result = await listChatMessageDiscovery({ ...context, mode: "search", query: " heat%pump ", limit: 2 });
expect(mocks.runTransaction).toHaveBeenCalledWith(
{ ...context, mode: "search", query: " heat%pump ", limit: 2 },
CHAT_PERMISSIONS.readOwnChannels,
expect.any(Function)
);
expect(result.messages).toEqual([
{
id: "message_3",
chatId: "chat_1",
channelKind: "group",
channelName: "Montage Nord",
projectId: null,
authorUserId: "author_1",
body: "Nachricht message_3",
parentMessageId: null,
createdAtIso: "2026-07-16T10:03:00.000Z",
participants: [
{ userId: "author_1", displayName: "Ada Lovelace", avatarUrl: "/avatars/ada" },
{ userId: "viewer_1", displayName: "Raffael Sheikh", avatarUrl: null },
],
},
expect.objectContaining({ id: "message_2" }),
]);
expect(result.nextCursor).toEqual(expect.any(String));
const searchSql = queryText(mocks.tx.$queryRaw.mock.calls[0]);
expect(searchSql).toContain('INNER JOIN "TeamChatMember" AS viewer_member');
expect(searchSql).toContain('viewer_member."leftAt" IS NULL');
expect(searchSql).toContain('channel_row."archivedAt" IS NULL');
expect(searchSql).toContain('message_row."body" ILIKE');
expect(mocks.tx.$queryRaw.mock.calls[0]?.slice(1)).toEqual(expect.arrayContaining(["tenant_1", "viewer_1", "%heat!%pump%", 3]));
mocks.tx.$queryRaw.mockResolvedValueOnce([]);
await listChatMessageDiscovery({ ...context, mode: "search", query: "heat%pump", limit: 2, beforeCursor: result.nextCursor! });
expect(mocks.tx.$queryRaw.mock.calls.at(-1)?.slice(1)).toEqual(
expect.arrayContaining([new Date("2026-07-16T10:02:00.000Z"), "message_2"])
);
});
it("aggregates every visible user mention and keeps the mention predicate server-side", async () => {
mocks.tx.$queryRaw.mockResolvedValueOnce([row("mention_1", "2026-07-16T11:00:00.000Z")]).mockResolvedValueOnce([]);
const result = await listChatMessageDiscovery({ ...context, mode: "mentions" });
expect(result.messages).toHaveLength(1);
const mentionSql = queryText(mocks.tx.$queryRaw.mock.calls[0]);
expect(mentionSql).toContain('message_row."mentions" @> jsonb_build_array');
expect(mentionSql).toContain('viewer_member."userId" =');
expect(mocks.tx.$queryRaw.mock.calls[0]?.slice(1)).toEqual(expect.arrayContaining(["tenant_1", "viewer_1"]));
});
it("still checks current permission and module access for an empty search", async () => {
const result = await listChatMessageDiscovery({ ...context, mode: "search", query: " " });
expect(result).toEqual({ messages: [], nextCursor: null });
expect(mocks.runTransaction).toHaveBeenCalledWith(expect.any(Object), CHAT_PERMISSIONS.readOwnChannels, expect.any(Function));
expect(mocks.tx.$queryRaw).not.toHaveBeenCalled();
});
it("rejects malformed input and a cursor from another filter before querying", async () => {
await expect(listChatMessageDiscovery({ ...context, mode: "search", query: "x".repeat(201) })).rejects.toMatchObject({
code: "chat.invalid_input",
});
await expect(listChatMessageDiscovery({ ...context, mode: "mentions", query: "unexpected" })).rejects.toMatchObject({
code: "chat.invalid_input",
});
await expect(listChatMessageDiscovery({ ...context, mode: "search", beforeCursor: "broken" })).rejects.toMatchObject({
code: "chat.invalid_input",
});
expect(mocks.runTransaction).not.toHaveBeenCalled();
});
it("fails closed on malformed persisted records", async () => {
mocks.tx.$queryRaw.mockResolvedValueOnce([row("bad", "2026-07-16T10:00:00.000Z", { authorUserId: null })]).mockResolvedValueOnce([]);
await expect(listChatMessageDiscovery({ ...context, mode: "mentions" })).rejects.toMatchObject({ code: "chat.integrity_failure" });
});
});
function queryText(call: unknown[] | undefined): string {
const strings = call?.[0];
return Array.isArray(strings) ? strings.join("?") : "";
}