feat: close the browser boundary and add the generic UI host loader
Two gaps stood between the module UI contract and a host that could use
it. ADR 0023 recorded the first honestly but never diagnosed it: a module
UI file compiled with `"types": []` could still typecheck `process.env`.
The second was simply missing — nothing imported a compiled artifact,
checked its identity, mounted it, or tore it down.
The leak was one type-only import, bisected against the real type graph
rather than guessed. `@ekklesia/module-ui-sdk` imported
`type { EkklesiaPrincipal } from "@ekklesia/contracts"`. Importing
contracts/identity alone is clean and importing Zod alone is clean, but
contracts exposes a single barrel entry, so that one import reached
module-database, whose Drizzle types re-introduce Node's globals. The
runtime was never affected — the import was erased and host-context.js is
`export {}` — but a type-graph leak is still a real boundary failure,
because it silently permits code that cannot run in its target
environment.
The fix is not a narrower import path. The SDK now has no dependencies at
all, so there is no graph to leak through and no future contracts change
can reopen this. It owns `ModuleUiPrincipal`: the same shape ADR 0022
chose, with the Zod brand dropped. That brand encodes a server-side
parsing guarantee a browser cannot produce, and it is the same reason
`permissions.has` already took a plain string. An Ekklesia host still
passes its own `EkklesiaPrincipal` straight through — a branded string is
assignable to `string` — while a standalone host builds the literal.
Proven the way an author experiences it: two fixtures compiled under the
exact project a module uses, one supported and one deliberately reaching
for `process`, with the second required to fail on that specific name.
`@ekklesia/module-ui-host` is the generic loader, in its own package
because the SDK is bundled into every module artifact and host-only
loader code has no business shipping there. The boundary checker enforces
both directions: modules may not depend on the loader, and the loader may
depend only on the SDK plus dev-time tooling.
The distinction that shaped the design: Core resolves `entrypoints.ui` to
an absolute path on the server's disk, and a browser needs a URL. A
loader that accepted the path would test green on a server and fail in
every real host, and would quietly own asset publication. So the loader
takes a browser-loadable URL and knows nothing about how one is obtained.
Ekklesia has no route that publishes installed artifacts, so this is
precisely: loader complete, publication deferred. Nothing can mount an
installed module UI yet, and the docs say so rather than implying
otherwise.
Dynamic import is `(url) => import(url)` with a non-analyzable specifier,
kept as a runtime import so a host does not statically bundle every
installed module or need a hardcoded registry. It is injectable for
bundlers needing their own escape hatch, and deliberately not `eval` or
`new Function`, which would cost a host `unsafe-eval` in its CSP.
Identity is validated through the SDK's existing parser before `mount`
runs, so a stale or mismatched bundle never renders. Contract violations
propagate unwrapped; the loader adds only import and mount failure codes,
sanitized, with the cause attached. Unmount is idempotent, safe when a
module returned no cleanup, and marks an instance unmounted before
running cleanup so a throwing cleanup surfaces once and never re-runs. A
failed mount registers no cleanup. Each instance owns its own state, so
two mounts coexist. The loader never mutates the host's container — not
on success, failure, or unmount.
Tests prove all of it against real module URLs (`data:`, which both
browsers and Node import natively) rather than filesystem paths,
including one artifact built by the canonical Pass 2 pipeline and run
under both an Ekklesia-shaped and a standalone-shaped context. Core,
apps/api, and the contracts package are untouched; discovery remains
inert.
Co-Authored-By: Claude Opus 5 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5
parent
5d75d910fd
commit
44e676f0df
@@ -0,0 +1,121 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { readFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { buildModuleUi } from "@ekklesia/module-ui-build";
|
||||
import type { ModuleUiHostContext } from "@ekklesia/module-ui-sdk";
|
||||
import { beforeAll, describe, expect, it } from "vitest";
|
||||
import { loadModuleUi } from "../src/index.js";
|
||||
|
||||
const fixtureDirectory = path.join(
|
||||
path.dirname(fileURLToPath(import.meta.url)),
|
||||
"fixtures",
|
||||
"artifact-module",
|
||||
);
|
||||
|
||||
let artifactUrl: string;
|
||||
let artifactSource: string;
|
||||
|
||||
/** An Ekklesia-shaped host: module routes live under a Core-owned prefix. */
|
||||
function ekklesiaContext(requested: string[]): ModuleUiHostContext {
|
||||
return {
|
||||
moduleId: "example",
|
||||
api: {
|
||||
async request(pathname) {
|
||||
requested.push(`/api/v1/modules/example/${pathname.replace(/^\//u, "")}`);
|
||||
return new Response(null, { status: 200 });
|
||||
},
|
||||
},
|
||||
principal: { kind: "authenticated", userId: "user-123" },
|
||||
permissions: { has: () => true },
|
||||
};
|
||||
}
|
||||
|
||||
/** A standalone host: one module, a different origin, a completely different URL shape, no Core. */
|
||||
function standaloneContext(requested: string[]): ModuleUiHostContext {
|
||||
return {
|
||||
moduleId: "example",
|
||||
api: {
|
||||
async request(pathname) {
|
||||
requested.push(`https://example.test/api/${pathname.replace(/^\//u, "")}`);
|
||||
return new Response(null, { status: 200 });
|
||||
},
|
||||
},
|
||||
principal: { kind: "anonymous" },
|
||||
permissions: { has: () => false },
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Proves the loader consumes exactly the browser ESM artifact `@ekklesia/module-ui-build` produces
|
||||
* (ADR 0023) — no second output format, no checked-in build output. The artifact is rebuilt from
|
||||
* source each run and served through a `data:` URL, a real module URL rather than a filesystem path.
|
||||
*/
|
||||
describe("loading a real compiled artifact", () => {
|
||||
beforeAll(async () => {
|
||||
const result = await buildModuleUi({ moduleDirectory: fixtureDirectory });
|
||||
artifactSource = await readFile(result.outputFile, "utf8");
|
||||
artifactUrl = `data:text/javascript;base64,${Buffer.from(artifactSource, "utf8").toString("base64")}`;
|
||||
}, 60_000);
|
||||
|
||||
it("produces a self-contained artifact with no bare imports for a host to resolve", () => {
|
||||
expect(artifactSource).not.toMatch(/^import\s.*from\s*["'][^.]/mu);
|
||||
expect(artifactSource).toContain("export {");
|
||||
expect(artifactSource).not.toContain("/api/v1/modules");
|
||||
});
|
||||
|
||||
it("mounts the real artifact through the generic loader and unmounts it", async () => {
|
||||
const container = document.createElement("div");
|
||||
const requested: string[] = [];
|
||||
|
||||
const mounted = await loadModuleUi({
|
||||
source: { moduleId: "example", version: "0.1.0", url: artifactUrl },
|
||||
container,
|
||||
context: ekklesiaContext(requested),
|
||||
});
|
||||
|
||||
expect(container.textContent).toBe("example:200:user-123");
|
||||
await mounted.unmount();
|
||||
expect(container.textContent).toBe("");
|
||||
expect(mounted.mounted).toBe(false);
|
||||
});
|
||||
|
||||
it("still rejects the real artifact when the host expects a different version", async () => {
|
||||
await expect(
|
||||
loadModuleUi({
|
||||
source: { moduleId: "example", version: "0.2.0", url: artifactUrl },
|
||||
container: document.createElement("div"),
|
||||
context: ekklesiaContext([]),
|
||||
}),
|
||||
).rejects.toMatchObject({ code: "MODULE_UI_IDENTITY_MISMATCH" });
|
||||
});
|
||||
|
||||
it("runs the same artifact under an Ekklesia host and a standalone host", async () => {
|
||||
const ekklesiaRequests: string[] = [];
|
||||
const standaloneRequests: string[] = [];
|
||||
const ekklesiaContainer = document.createElement("div");
|
||||
const standaloneContainer = document.createElement("div");
|
||||
const source = { moduleId: "example", version: "0.1.0", url: artifactUrl };
|
||||
|
||||
const inEkklesia = await loadModuleUi({
|
||||
source,
|
||||
container: ekklesiaContainer,
|
||||
context: ekklesiaContext(ekklesiaRequests),
|
||||
});
|
||||
const inStandalone = await loadModuleUi({
|
||||
source,
|
||||
container: standaloneContainer,
|
||||
context: standaloneContext(standaloneRequests),
|
||||
});
|
||||
|
||||
// One artifact, one loader, two hosts. Every difference lives in the context the host supplied:
|
||||
// the module asked for "records" both times and resolved nothing itself.
|
||||
expect(ekklesiaRequests).toEqual(["/api/v1/modules/example/records"]);
|
||||
expect(standaloneRequests).toEqual(["https://example.test/api/records"]);
|
||||
expect(ekklesiaContainer.textContent).toBe("example:200:user-123");
|
||||
expect(standaloneContainer.textContent).toBe("example:200:guest");
|
||||
|
||||
await inEkklesia.unmount();
|
||||
await inStandalone.unmount();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user