import { describe, expect, test, vi } from "vitest"; import { CatalogError, auditEvent, defineAdapter, defineFlag, featureFlag, getAdapter, notify, bundleNotifications, isNotificationEnabled, notifyMany, requirePermission, withAuditMiddleware, withIdempotency, withOwnerCheck, withTenantScope, type NotificationInput, } from "./index.js"; describe("@hivegrid/foundation", () => { test("writes audit events through the provided DB boundary", async () => { const client = { auditEvent: { create: vi.fn(async (args) => args.data) } }; await auditEvent({ action: "thing.changed", tenantId: "tenant_1" }, client); expect(client.auditEvent.create).toHaveBeenCalledWith({ data: expect.objectContaining({ action: "thing.changed", actorType: "system", tenantId: "tenant_1" }), }); }); test("adds audit middleware after successful handler execution", async () => { const client = { auditEvent: { create: vi.fn(async (args) => args.data) } }; const handler = withAuditMiddleware(async () => ({ id: "result_1" }), (result) => ({ action: "created", targetId: result.id }), client); await expect(handler()).resolves.toEqual({ id: "result_1" }); expect(client.auditEvent.create).toHaveBeenCalledWith({ data: expect.objectContaining({ action: "created", targetId: "result_1" }) }); }); test("returns 404-style catalog errors for missing permissions and owner checks", () => { expect(() => requirePermission({ permissions: [] }, "resource.view")).toThrow(CatalogError); expect(() => withOwnerCheck({ userId: "user_1" }, { ownerId: "user_2" })).toThrow(/foundation.not_found/); }); test("applies tenant scopes without mutating the input", () => { const value = { id: "row_1" }; expect(withTenantScope("tenant_1", value)).toEqual({ id: "row_1", tenantId: "tenant_1" }); expect(value).toEqual({ id: "row_1" }); }); test("resolves feature flags by override, user, tenant, global, and default precedence", () => { const flag = defineFlag({ key: "empty.flag", defaultEnabled: false }); const records = [ { scope: "global", enabled: false }, { tenantId: "tenant_1", enabled: true }, { userId: "user_1", enabled: false, key: "empty.flag" }, ]; expect(featureFlag({ ...flag, override: true, records, tenantId: "tenant_1", userId: "user_1" })).toBe(true); expect(featureFlag({ ...flag, records, tenantId: "tenant_1", userId: "user_1" })).toBe(false); expect(featureFlag({ ...flag, records, tenantId: "tenant_1" })).toBe(true); expect(featureFlag({ ...flag, records })).toBe(false); expect(featureFlag({ key: "new.flag", defaultEnabled: true })).toBe(true); }); test("does not apply tenant-scoped user flag overrides across tenants", () => { const flag = defineFlag({ key: "tenant.flag", defaultEnabled: false }); const records = [ { tenantId: "tenant_1", userId: "user_1", enabled: false, key: "tenant.flag" }, { tenantId: "tenant_2", enabled: true, key: "tenant.flag" }, ]; expect(featureFlag({ ...flag, records, tenantId: "tenant_2", userId: "user_1" })).toBe(true); expect(featureFlag({ ...flag, records, tenantId: "tenant_1", userId: "user_1" })).toBe(false); }); test("does not treat scoped feature flag records as global fallbacks", () => { const flag = defineFlag({ key: "scoped.flag", defaultEnabled: false }); const records = [ { scope: "tenant", tenantId: "tenant_1", enabled: true, key: "scoped.flag" }, { scope: "user", userId: "user_1", enabled: true, key: "scoped.flag" }, ]; expect(featureFlag({ ...flag, records, tenantId: "tenant_2", userId: "user_2" })).toBe(false); expect(featureFlag({ ...flag, records, tenantId: "tenant_1", userId: "user_2" })).toBe(true); expect(featureFlag({ ...flag, records, tenantId: "tenant_2", userId: "user_1" })).toBe(true); }); test("replays idempotent responses and rejects changed fingerprints", async () => { const rows = new Map(); const client = { idempotencyKey: { findUnique: vi.fn(async ({ where }) => { const key = where.idempotency_key_partition_scope_key; return rows.get(`${key.partitionKey}:${key.scope}:${key.key}`) ?? null; }), create: vi.fn(async ({ data }) => { const key = `${data.partitionKey}:${data.scope}:${data.key}`; if (rows.has(key)) throw Object.assign(new Error("unique"), { code: "P2002" }); rows.set(key, { requestHash: data.requestHash, responseStatus: data.responseStatus, responseBody: data.responseBody as { ok: boolean }, responseHeaders: null, }); }), update: vi.fn(async ({ where, data }) => { const unique = where.idempotency_key_partition_scope_key; const key = `${unique.partitionKey}:${unique.scope}:${unique.key}`; const existing = rows.get(key); if (!existing) throw new Error("missing reservation"); rows.set(key, { ...existing, responseStatus: data.responseStatus, responseBody: data.responseBody as { ok: boolean }, responseHeaders: null, }); }), deleteMany: vi.fn(async ({ where }) => { rows.delete(`${where.partitionKey}:${where.scope}:${where.key}`); }), }, }; const first = await withIdempotency({ tenantId: "tenant_1", key: "key_1", fingerprint: { body: "a" } }, client, async () => ({ status: 201, body: { ok: true } })); const replay = await withIdempotency({ tenantId: "tenant_1", key: "key_1", fingerprint: { body: "a" } }, client, async () => ({ status: 500 })); expect(first.replayed).toBe(false); expect(replay).toMatchObject({ replayed: true, status: 201, body: { ok: true } }); await expect(withIdempotency({ tenantId: "tenant_1", key: "key_1", fingerprint: { body: "b" } }, client, async () => ({ status: 200 }))).rejects.toThrow(CatalogError); }); test("serializes concurrent idempotent operations for the same scope and key", async () => { const rows = new Map(); let releaseOperation!: () => void; const operationGate = new Promise((resolve) => { releaseOperation = resolve; }); const operation = vi.fn(async () => { await operationGate; return { status: 201, body: { ok: true } }; }); const client = { idempotencyKey: { findUnique: vi.fn(async ({ where }) => { const key = where.idempotency_key_partition_scope_key; return rows.get(`${key.partitionKey}:${key.scope}:${key.key}`) ?? null; }), create: vi.fn(async ({ data }) => { const key = `${data.partitionKey}:${data.scope}:${data.key}`; if (rows.has(key)) throw Object.assign(new Error("unique"), { code: "P2002" }); rows.set(key, { requestHash: data.requestHash, responseStatus: data.responseStatus, responseBody: data.responseBody as { ok: boolean }, responseHeaders: null, }); }), update: vi.fn(async ({ where, data }) => { const unique = where.idempotency_key_partition_scope_key; const key = `${unique.partitionKey}:${unique.scope}:${unique.key}`; const existing = rows.get(key); if (!existing) throw new Error("missing reservation"); rows.set(key, { ...existing, responseStatus: data.responseStatus, responseBody: data.responseBody as { ok: boolean }, responseHeaders: null, }); }), deleteMany: vi.fn(async ({ where }) => { rows.delete(`${where.partitionKey}:${where.scope}:${where.key}`); }), }, }; const first = withIdempotency({ tenantId: "tenant_1", scope: "test", key: "key_concurrent", fingerprint: { body: "a" } }, client, operation); const second = withIdempotency({ tenantId: "tenant_1", scope: "test", key: "key_concurrent", fingerprint: { body: "a" } }, client, operation); releaseOperation(); await expect(Promise.all([first, second])).resolves.toEqual([ { status: 201, body: { ok: true }, replayed: false }, { status: 201, body: { ok: true }, replayed: true }, ]); expect(operation).toHaveBeenCalledTimes(1); }); test("tracks adapter five-state definitions and unknown adapters", () => { defineAdapter({ key: "empty.adapter", status: "healthy", adapter: { configured: true } }); expect(getAdapter("empty.adapter").status).toBe("healthy"); expect(getAdapter("missing.adapter").status).toBe("not_configured"); }); test("creates generic notification delivery records", async () => { const client = { notificationDelivery: { create: vi.fn(async (args) => args.data), update: vi.fn(), updateMany: vi.fn(), findMany: vi.fn(), }, }; await notify( { tenantId: "tenant_1", userId: "user_1", category: " Ops ", messageKey: "foundation.notifications.empty", payloadMetadata: { requestId: "req_1", apiKey: "secret" }, }, client, ); expect(client.notificationDelivery.create).toHaveBeenCalledWith({ data: expect.objectContaining({ tenantId: "tenant_1", userId: "user_1", channel: "IN_APP", category: "ops", status: "SENT", attemptsMade: 1, sentAt: expect.any(Date), payloadMetadata: { requestId: "req_1", apiKey: "[redacted]" }, }), }); await notify( { tenantId: "tenant_1", userId: "user_1", category: "ops", messageKey: "foundation.notifications.disabled", }, client, [{ tenantId: "tenant_1", userId: "user_1", channel: "IN_APP", category: "ops", enabled: false }], ); expect(client.notificationDelivery.create).toHaveBeenCalledTimes(2); expect(client.notificationDelivery.create).toHaveBeenLastCalledWith({ data: expect.objectContaining({ tenantId: "tenant_1", userId: "user_1", channel: "IN_APP", category: "ops", status: "SKIPPED", lastError: "preference_disabled", }), }); }); test("upserts notification deliveries with source keys through the Foundation contract", async () => { const client = { notificationDelivery: { create: vi.fn(async (args) => args.data), upsert: vi.fn(async (args) => args.create), }, }; await notify( { tenantId: "tenant_1", userId: "user_1", channel: "EMAIL", category: "billing", messageKey: "foundation.notifications.invoice", sourceKey: " invoice:invoice_1:user_1 ", }, client, ); expect(client.notificationDelivery.upsert).toHaveBeenCalledWith({ where: { notification_delivery_source_key: { tenantId: "tenant_1", userId: "user_1", channel: "EMAIL", sourceKey: "invoice:invoice_1:user_1", }, }, create: expect.objectContaining({ tenantId: "tenant_1", userId: "user_1", channel: "EMAIL", sourceKey: "invoice:invoice_1:user_1", status: "PENDING", attemptsMade: 0, }), update: expect.objectContaining({ messageKey: "foundation.notifications.invoice", status: "PENDING", }), }); expect(client.notificationDelivery.create).not.toHaveBeenCalled(); }); test("rejects notification delivery records without tenant scope", async () => { const client = { notificationDelivery: { create: vi.fn(async (args) => args.data), }, }; await expect( notify( { tenantId: " ", userId: "user_1", messageKey: "foundation.notifications.empty", }, client, ), ).rejects.toThrow("Notification delivery tenant scope is required."); expect(client.notificationDelivery.create).not.toHaveBeenCalled(); }); test("resolves notification preferences and records skipped batch diagnostics", async () => { const inputs: NotificationInput[] = [ { tenantId: "tenant_1", userId: "user_1", messageKey: "foundation.notifications.one", payloadMetadata: { count: 1 } }, { tenantId: "tenant_1", userId: "user_1", messageKey: "foundation.notifications.two", payloadMetadata: { source: "test", token: "secret-token" } }, { tenantId: "tenant_1", userId: "user_2", channel: "EMAIL" as const, category: "ops", messageKey: "foundation.notifications.three" }, ]; const preferences = [{ tenantId: "tenant_1", userId: "user_2", channel: "EMAIL" as const, category: "ops", enabled: false }]; const client = { notificationDelivery: { create: vi.fn(async (args) => args.data), update: vi.fn(), updateMany: vi.fn(), findMany: vi.fn(), }, }; expect(isNotificationEnabled(inputs[2], preferences)).toBe(false); expect(bundleNotifications(inputs)).toEqual([ { tenantId: "tenant_1", userId: "user_1", channel: "IN_APP", category: "default", messageKeys: ["foundation.notifications.one", "foundation.notifications.two"], payloadMetadata: { count: 1, source: "test", token: "[redacted]" }, }, { tenantId: "tenant_1", userId: "user_2", channel: "EMAIL", category: "ops", messageKeys: ["foundation.notifications.three"], payloadMetadata: {}, }, ]); await notifyMany(inputs, client, preferences); expect(client.notificationDelivery.create).toHaveBeenCalledTimes(3); expect(client.notificationDelivery.create).toHaveBeenLastCalledWith( expect.objectContaining({ data: expect.objectContaining({ tenantId: "tenant_1", userId: "user_2", channel: "EMAIL", category: "ops", messageKey: "foundation.notifications.three", status: "SKIPPED", lastError: "preference_disabled", }), }), ); }); test("falls back to default notification preferences when category-specific preferences are absent", () => { const input: NotificationInput = { tenantId: "tenant_1", userId: "user_1", channel: "IN_APP", category: "billing", messageKey: "foundation.notifications.billing", }; expect( isNotificationEnabled(input, [ { tenantId: "tenant_1", userId: "user_1", channel: "IN_APP", category: "default", enabled: false }, ]) ).toBe(false); expect( isNotificationEnabled(input, [ { tenantId: "tenant_1", userId: "user_1", channel: "IN_APP", category: "default", enabled: false }, { tenantId: "tenant_1", userId: "user_1", channel: "IN_APP", category: "billing", enabled: true }, ]) ).toBe(true); }); });