diff --git a/examples/auth-showcase/app/services/greeter-client.ts b/examples/auth-showcase/app/services/greeter-client.ts new file mode 100644 index 00000000..6816ac49 --- /dev/null +++ b/examples/auth-showcase/app/services/greeter-client.ts @@ -0,0 +1,7 @@ +import { httpTransport, serviceClient } from "@wrnexus/rpc"; +import { greeter } from "./greeter.ts"; + +/** A caller-side helper using the shared service contract. */ +export function greeterClient() { + return serviceClient(greeter, { app: "auth-showcase", transport: httpTransport() }); +} diff --git a/packages/cli/src/build.ts b/packages/cli/src/build.ts index 7f72ae3d..f4b73416 100644 --- a/packages/cli/src/build.ts +++ b/packages/cli/src/build.ts @@ -644,6 +644,17 @@ applyAuthzManifestEarly([${authzSetupEntries}]); .join(", "); if (router.layouts.length) console.log(`✓ Layouts: ${router.layouts.length}`); + // RPC services are server-only modules. Production statically imports them + // so the runtime can dispatch private calls without filesystem discovery. + const servicesLit = router.services + .map((service) => { + const v = `s${counter++}`; + imports.push(`import * as ${v} from ${JSON.stringify(fwd(service.file))};`); + return `{ name: ${JSON.stringify(service.name)}, mod: ${v} }`; + }) + .join(", "); + if (router.services.length) console.log(`✓ RPC services: ${router.services.length}`); + // Authorization declarations again, this time for ProdOptions.authz — a // SEPARATE set of static imports of the exact same files (harmless; ES // modules are evaluated once and shared across every importer), statically @@ -678,6 +689,7 @@ await createProductionServer( middleware: [${mwVars.join(", ")}], components: [${componentsLit}], layouts: [${layoutsLit}], + services: [${servicesLit}], }, { reactivePath: join(import.meta.dir, "reactive.js"), diff --git a/packages/dev-server/src/prod.ts b/packages/dev-server/src/prod.ts index b9fcd78e..4f7fdd97 100644 --- a/packages/dev-server/src/prod.ts +++ b/packages/dev-server/src/prod.ts @@ -73,6 +73,8 @@ export interface ProdManifest { components: { name: string; mod: RouteModule }[]; /** Named page layouts (from app/layouts/*.wrn). */ layouts: { name: string; mod: RouteModule }[]; + /** RPC service implementations (from app/services/*.ts). */ + services?: { name: string; mod: RouteModule }[]; } export interface ProductionPluginAsset { @@ -277,6 +279,8 @@ function buildProdRouter(manifest: ProdManifest): { for (const c of manifest.components) modules.set(c.name, c.mod); // Layouts share the module map under a `layout:` prefix (no name collisions). for (const l of manifest.layouts) modules.set(`layout:${l.name}`, l.mod); + for (const service of manifest.services ?? []) + modules.set(`service:${service.name}`, service.mod); const router: Router = { pages, @@ -288,7 +292,10 @@ function buildProdRouter(manifest: ProdManifest): { stores: [], schemas: [], // descriptors are pre-baked into schemasJs; not needed at runtime authz: [], // authz declarations are not needed at runtime in production - services: [], // RPC service modules are not yet emitted in production manifests + services: (manifest.services ?? []).map((service) => ({ + name: service.name, + file: `service:${service.name}`, + })), matchPage: optimizedMatcher(pages), matchApi: optimizedMatcher(api), matchRealtime: optimizedMatcher(realtime), diff --git a/packages/dev-server/test/rpc-endpoint.test.ts b/packages/dev-server/test/rpc-endpoint.test.ts index aee50bce..10bf04fa 100644 --- a/packages/dev-server/test/rpc-endpoint.test.ts +++ b/packages/dev-server/test/rpc-endpoint.test.ts @@ -2,6 +2,7 @@ import { describe, expect, test } from "bun:test"; import { defineService, implement, procedure } from "@wrnexus/rpc"; import { v } from "@wrnexus/validation"; import { handleRpcRequest, isInternalCaller, isRpcPath } from "../src/rpc-dispatch.ts"; +import { createProductionHandlers, type ProdManifest } from "../src/prod.ts"; const demo = defineService({ name: "demo", @@ -73,4 +74,20 @@ describe("RPC endpoint", () => { expect(await res!.json()).toMatchObject({ ok: false, code: "RPC_UNKNOWN" }); }); }); + + test("production manifests load and dispatch service implementations", async () => { + const manifest: ProdManifest = { + pages: [], + api: [], + realtime: [], + middleware: [], + components: [], + layouts: [], + services: [{ name: "demo", mod: { default: services.get("demo") } }], + }; + const handlers = createProductionHandlers(manifest, {}); + const req = request("/__wrnexus/rpc/demo/add", { "x-wrnexus-internal": "1" }); + const response = await handlers.fetch(req, {} as never); + expect(await response!.json()).toEqual({ ok: true, value: { a: 2 } }); + }); }); diff --git a/packages/rpc/test/client.test.ts b/packages/rpc/test/client.test.ts index 6aad19d3..0ea3412b 100644 --- a/packages/rpc/test/client.test.ts +++ b/packages/rpc/test/client.test.ts @@ -6,9 +6,13 @@ import { defineService, procedure } from "../src/contract.ts"; import { RPC_ERROR_CODES, ServiceError, failure, success } from "../src/errors.ts"; import type { RpcTarget } from "../src/transport.ts"; -const original = { ...process.env }; +const originalRpcSecret = process.env.WRNEXUS_RPC_SECRET; +const originalAppName = process.env.WRNEXUS_APP_NAME; afterEach(() => { - process.env = { ...original }; + if (originalRpcSecret === undefined) delete process.env.WRNEXUS_RPC_SECRET; + else process.env.WRNEXUS_RPC_SECRET = originalRpcSecret; + if (originalAppName === undefined) delete process.env.WRNEXUS_APP_NAME; + else process.env.WRNEXUS_APP_NAME = originalAppName; }); function configure(appName = "web") { diff --git a/packages/rpc/test/identity.test.ts b/packages/rpc/test/identity.test.ts index e439790b..cce68f32 100644 --- a/packages/rpc/test/identity.test.ts +++ b/packages/rpc/test/identity.test.ts @@ -4,10 +4,14 @@ import { signJwt } from "@wrnexus/jwt"; import { exportSubjectContext, importSubjectContext } from "../src/identity.ts"; const SECRET = "test-rpc-secret-at-least-32-chars-long"; -const original = { ...process.env }; +const originalRpcSecret = process.env.WRNEXUS_RPC_SECRET; +const originalAppName = process.env.WRNEXUS_APP_NAME; afterEach(() => { - process.env = { ...original }; + if (originalRpcSecret === undefined) delete process.env.WRNEXUS_RPC_SECRET; + else process.env.WRNEXUS_RPC_SECRET = originalRpcSecret; + if (originalAppName === undefined) delete process.env.WRNEXUS_APP_NAME; + else process.env.WRNEXUS_APP_NAME = originalAppName; }); function ctxFor(user: unknown, tenantId?: string): Context { diff --git a/packages/rpc/test/integration.test.ts b/packages/rpc/test/integration.test.ts index f858befe..a807809f 100644 --- a/packages/rpc/test/integration.test.ts +++ b/packages/rpc/test/integration.test.ts @@ -4,8 +4,10 @@ import { v } from "@wrnexus/validation"; import { serviceClient } from "../src/client.ts"; import { defineService, procedure } from "../src/contract.ts"; import { RPC_ERROR_CODES } from "../src/errors.ts"; +import { httpTransport } from "../src/http.ts"; import { implement } from "../src/server.ts"; import { inProcessTransport } from "../src/transport.ts"; +import { handleRpcRequest } from "../../dev-server/src/rpc-dispatch.ts"; const originalRpcSecret = process.env.WRNEXUS_RPC_SECRET; const originalAppName = process.env.WRNEXUS_APP_NAME; @@ -44,6 +46,30 @@ function wire(allowed: boolean) { }); } +function httpWire(allowed: boolean) { + const service = implement( + billing, + { + createInvoice: async ({ amountCents }, ctx) => ({ + invoiceId: `inv_${amountCents}`, + forSubject: ctx.subject?.subjectId ?? "anon", + }), + }, + { selfApp: "billing", checkPermission: async () => allowed }, + ); + return httpTransport({ + resolveOrigin: () => "http://billing.internal", + fetch: (async (input: RequestInfo | URL, init?: RequestInit) => { + const request = new Request(input, init); + return (await handleRpcRequest( + request, + new URL(request.url), + new Map([["billing", service]]), + ))!; + }) as typeof fetch, + }); +} + describe("RPC integration", () => { test("propagates identity and validates the callee permission", async () => { process.env.WRNEXUS_RPC_SECRET = "test-rpc-secret-at-least-32-chars-long"; @@ -71,4 +97,21 @@ describe("RPC integration", () => { code: RPC_ERROR_CODES.denied, }); }); + + test("uses the real HTTP transport and private dispatcher end to end", async () => { + process.env.WRNEXUS_RPC_SECRET = "test-rpc-secret-at-least-32-chars-long"; + process.env.WRNEXUS_APP_NAME = "web"; + const client = serviceClient(billing, { + app: "billing", + as: { user: { id: "u1" }, locals: {} } as unknown as Context, + transport: httpWire(true), + }); + expect(await client.createInvoice({ amountCents: 7 })).toEqual({ + invoiceId: "inv_7", + forSubject: "u1", + }); + await expect(client.createInvoice({ amountCents: "bad" } as never)).rejects.toMatchObject({ + code: RPC_ERROR_CODES.invalid, + }); + }); }); diff --git a/packages/rpc/test/server.test.ts b/packages/rpc/test/server.test.ts index dd23c67a..03bd8e03 100644 --- a/packages/rpc/test/server.test.ts +++ b/packages/rpc/test/server.test.ts @@ -5,9 +5,13 @@ import { RPC_ERROR_CODES } from "../src/errors.ts"; import { exportSubjectContext } from "../src/identity.ts"; import { implement } from "../src/server.ts"; -const original = { ...process.env }; +const originalRpcSecret = process.env.WRNEXUS_RPC_SECRET; +const originalAppName = process.env.WRNEXUS_APP_NAME; afterEach(() => { - process.env = { ...original }; + if (originalRpcSecret === undefined) delete process.env.WRNEXUS_RPC_SECRET; + else process.env.WRNEXUS_RPC_SECRET = originalRpcSecret; + if (originalAppName === undefined) delete process.env.WRNEXUS_APP_NAME; + else process.env.WRNEXUS_APP_NAME = originalAppName; }); function configure(appName = "web") {