import { afterEach, expect, test } from "bun:test"; import { implement } from "@wrnexus/rpc"; import { handleRpcRequest } from "../../../packages/dev-server/src/rpc-dispatch.ts"; import { GET } from "./api/product-summary.ts"; import { auditService, catalogService } from "./lib/contracts.ts"; const savedFetch = globalThis.fetch; const savedSecret = process.env.WRNEXUS_RPC_SECRET; const savedApp = process.env.WRNEXUS_APP_NAME; const savedOrigins = process.env.WRNEXUS_INTERNAL_ORIGINS; afterEach(() => { globalThis.fetch = savedFetch; if (savedSecret === undefined) delete process.env.WRNEXUS_RPC_SECRET; else process.env.WRNEXUS_RPC_SECRET = savedSecret; if (savedApp === undefined) delete process.env.WRNEXUS_APP_NAME; else process.env.WRNEXUS_APP_NAME = savedApp; if (savedOrigins === undefined) delete process.env.WRNEXUS_INTERNAL_ORIGINS; else process.env.WRNEXUS_INTERNAL_ORIGINS = savedOrigins; }); test("coordinator reaches two peer-app listeners and an external API", async () => { process.env.WRNEXUS_RPC_SECRET = "test-rpc-secret-at-least-32-chars-long"; process.env.WRNEXUS_APP_NAME = "product-summary"; const catalog = implement( catalogService, { getProduct: ({ sku }) => ({ sku, displayName: "Starter", enabled: true }), }, { selfApp: "catalog" }, ); const audit = implement( auditService, { recordLookup: () => ({ eventId: "audit_1" }), }, { selfApp: "audit" }, ); const catalogServer = Bun.serve({ port: 0, hostname: "127.0.0.1", async fetch(request) { return ( (await handleRpcRequest(request, new URL(request.url), new Map([["catalog", catalog]]))) ?? new Response("Not found", { status: 404 }) ); }, }); const auditServer = Bun.serve({ port: 0, hostname: "127.0.0.1", async fetch(request) { return ( (await handleRpcRequest(request, new URL(request.url), new Map([["audit", audit]]))) ?? new Response("Not found", { status: 404 }) ); }, }); process.env.WRNEXUS_INTERNAL_ORIGINS = JSON.stringify({ catalog: `http://127.0.0.1:${catalogServer.port}`, audit: `http://127.0.0.1:${auditServer.port}`, }); globalThis.fetch = ((input: RequestInfo | URL, init?: RequestInit) => { if (String(input) === "https://api.github.com/repos/octocat/Hello-World") { return Promise.resolve( Response.json({ full_name: "octocat/Hello-World", stargazers_count: 7 }), ); } return savedFetch(input, init); }) as typeof fetch; try { const response = await GET({ req: new Request("http://coordinator.test/api/product-summary?sku=starter"), user: { id: "u1" }, locals: {}, } as never); expect(response.status).toBe(200); expect(await response.json()).toEqual({ product: { sku: "starter", displayName: "Starter", enabled: true }, external: { repository: "octocat/Hello-World", stars: 7 }, audit: { eventId: "audit_1" }, }); } finally { catalogServer.stop(true); auditServer.stop(true); } });