feat: let one module contribute a browser renderer to another's capability

The platform has had a complete story for one module using another's
*backend* since ADR 0006 — capabilities, versioned ranges, provider
registration. It has had none at all for one module using another's *browser*
code, and every workaround is wrong in a way that matters: a consumer cannot
import a peer module, it cannot re-implement a renderer for a domain it does
not own, and a second `entrypoints` role would put the platform in charge of
deciding when a slot inside someone else's screen should be filled.

Add a generic browser contribution. `manifestVersion: 7` declares one:
namespaced id, its own version, a target capability, a compatible range, and
one artifact. That is the complete list, and the omissions are the decision —
no payload schema, slot, ordering, or rendering hint exists anywhere, so Core
cannot learn what a slide is because the declaration cannot express it.

Discovery resolves a contribution artifact through the *identical* loop every
other compiled entrypoint uses, inheriting the path, containment, symlink,
extension, and file-kind checks rather than getting a weaker copy of them. The
registry publishes one only when another eligible module provides the target
capability within the declared range; otherwise it is absent rather than
mounted and broken. `apps/api` serves it as a sibling of the artifact and
display routes, with the same policy: three lookup keys, one exact match, one
already-validated path, and one indistinguishable 404 for unknown, undeclared,
stale, and incompatible alike.

A consumer discovers through the host, never through a URL. Its descriptor
carries identity, version, and capability; the URL stays server-side and is
resolved exactly as `api.request("records")` is. A module can only ever see
contributions aimed at a capability it itself provides, and cannot name its
way to anything else — a mount for a withheld id fails without fetching.

The consumer owns the domain contract entirely. Input is opaque JSON, checked
structurally so a Date, a function, a cycle, or `undefined` fails at the
boundary rather than vanishing somewhere far from the mistake, and checked for
nothing else. A contributed renderer receives its own id and that input: no
API client, realtime, principal, configuration, database, storage, or
credential. Loading one grants its module nothing.

The contribution ABI is versioned separately from the module UI ABI, because
the two have different shapes and lifecycles and coupling them would force
every module to rebuild whenever either moved. It supports asynchronous
readiness, update-without-remount (a screen that remounted per tick would
restart animations and reload media), deterministic cleanup in a `finally`,
and sanitized failure that never carries the consumer's domain data. Each
renderer mounts in its own isolated root with its own stylesheet.

The template now declares a contribution, so `pnpm build` exercises the whole
authoring path, and the shell suite drives the full relationship — one module
discovering, mounting, updating, and unmounting another's React renderer with
neither importing the other.

Co-Authored-By: Claude Opus 5 <[email protected]>
This commit is contained in:
ekklesia
2026-08-27 07:47:10 -05:00
co-authored by Claude Opus 5
parent 07835b7b56
commit c444ff570b
79 changed files with 3317 additions and 137 deletions
+1
View File
@@ -1,2 +1,3 @@
export * from "./isolated-root.js";
export * from "./load-module-contribution.js";
export * from "./load-module-ui.js";
@@ -0,0 +1,142 @@
import {
isModuleContributionInput,
type ModuleContributionDefinition,
ModuleContributionError,
type ModuleContributionInput,
type ModuleContributionInstance,
type MountedModuleContribution,
parseModuleContributionExport,
} from "@ekklesia/module-ui-sdk";
import { createIsolatedArtifactRoot, type IsolatedArtifactRoot } from "./isolated-root.js";
import { type ModuleUiImporter, ModuleUiHostError } from "./load-module-ui.js";
/**
* How a host obtains one contribution artifact.
*
* `url` is a **browser-loadable module URL** the host produced, never a path a module composed. The
* consuming module names a contribution id; turning that into a URL is asset publication, which this
* generic package deliberately does not own — exactly as it does not own it for a module UI artifact
* (ADR 0024, ADR 0025). Ekklesia implements it at its API edge (ADR 0041).
*
* `contributionId` and `version` are the identity the host already read from the contributing
* module's validated manifest, and are checked against the artifact before anything is mounted.
*/
export interface ModuleContributionSource {
readonly contributionId: string;
readonly version: string;
readonly url: string;
}
export interface LoadModuleContributionOptions {
readonly source: ModuleContributionSource;
/** A container the **consuming module** owns. The loader builds the contribution's isolated root
* inside it and never reaches outside it. */
readonly container: Element;
/** The consumer's own versioned input, validated as JSON before it crosses the boundary. */
readonly input: ModuleContributionInput;
readonly importModule?: ModuleUiImporter;
}
const defaultImporter: ModuleUiImporter = (url) => import(url);
/**
* Imports a published contribution artifact, verifies it is the contribution the host expected, and
* mounts it into an isolated root inside the consumer's container (ADR 0040, ADR 0041).
*
* **This executes trusted first-party code in the host's own page**, exactly like a module UI
* artifact. The isolated root keeps the renderer's *styles* to itself; it is not a sandbox, and
* mounting a contribution grants its module no authority whatsoever. Server-side authorization is
* untouched: the consumer was already authorized to obtain the data it passes as input, and the
* contribution receives nothing else.
*
* The consumer's `input` is validated as genuinely JSON-serializable **before** the artifact is even
* imported. A `Date`, a function, a cyclic object, or `undefined` would either vanish or throw
* somewhere far from the mistake, so it fails here, at the boundary, with a sanitized code that
* never echoes the domain data itself.
*/
export async function loadModuleContribution(
options: LoadModuleContributionOptions,
): Promise<MountedModuleContribution> {
const { container, input, source } = options;
if (!isModuleContributionInput(input)) {
throw new ModuleContributionError("MODULE_CONTRIBUTION_INPUT_INVALID");
}
const importModule = options.importModule ?? defaultImporter;
let namespace: unknown;
try {
namespace = await importModule(source.url);
} catch (error) {
throw new ModuleUiHostError("MODULE_UI_IMPORT_FAILED", { cause: error });
}
// The one contract parser, reused rather than reimplemented: it validates the default export's
// shape, its ABI marker, and that its id/version match what the host expected. A mismatched or
// stale artifact fails before it can render.
const definition: ModuleContributionDefinition = parseModuleContributionExport(namespace, {
id: source.contributionId,
version: source.version,
});
let isolated: IsolatedArtifactRoot;
try {
isolated = createIsolatedArtifactRoot(container, definition.styles);
} catch (error) {
throw new ModuleUiHostError("MODULE_UI_ISOLATION_UNAVAILABLE", { cause: error });
}
let instance: ModuleContributionInstance | undefined;
try {
const result = await definition.mount(isolated.mountTarget, {
contributionId: definition.id,
input,
});
if (result && typeof result === "object") {
instance = result;
}
} catch (error) {
isolated.dispose();
throw new ModuleUiHostError("MODULE_UI_MOUNT_FAILED", { cause: error });
}
let mounted = true;
return {
contributionId: definition.id,
version: definition.version,
get mounted() {
return mounted;
},
async update(next: ModuleContributionInput): Promise<void> {
if (!mounted) {
throw new ModuleContributionError("MODULE_CONTRIBUTION_UNKNOWN");
}
if (!isModuleContributionInput(next)) {
throw new ModuleContributionError("MODULE_CONTRIBUTION_INPUT_INVALID");
}
// A renderer that cannot update in place says so by returning no `update`, and the consumer is
// told to remount rather than left rendering stale content behind a silently ignored call.
if (!instance?.update) {
throw new ModuleContributionError("MODULE_CONTRIBUTION_NOT_UPDATABLE");
}
try {
await instance.update(next);
} catch (error) {
throw new ModuleUiHostError("MODULE_CONTRIBUTION_UPDATE_FAILED", { cause: error });
}
},
async unmount(): Promise<void> {
if (!mounted) {
return;
}
// Marked unmounted before cleanup runs, so a throwing cleanup surfaces once and a second call
// never re-runs it. The isolated root goes in a `finally`, so a renderer that fails to clean
// up still has its styles taken out of the consumer's page.
mounted = false;
try {
await instance?.unmount?.();
} finally {
isolated.dispose();
}
},
};
}
@@ -82,13 +82,15 @@ export interface MountedModuleUi {
export type ModuleUiHostErrorCode =
| "MODULE_UI_IMPORT_FAILED"
| "MODULE_UI_ISOLATION_UNAVAILABLE"
| "MODULE_UI_MOUNT_FAILED";
| "MODULE_UI_MOUNT_FAILED"
| "MODULE_CONTRIBUTION_UPDATE_FAILED";
const errorMessages: Readonly<Record<ModuleUiHostErrorCode, string>> = Object.freeze({
MODULE_UI_IMPORT_FAILED: "A module UI artifact could not be imported from its published URL.",
MODULE_UI_ISOLATION_UNAVAILABLE:
"A module UI artifact could not be given an isolated root in this environment.",
MODULE_UI_MOUNT_FAILED: "A module UI artifact failed while mounting.",
MODULE_CONTRIBUTION_UPDATE_FAILED: "A contributed renderer failed while applying new input.",
});
/**
@@ -1,5 +1,5 @@
{
"manifestVersion": 6,
"manifestVersion": 7,
"id": "example",
"name": "Example",
"version": "0.1.0",
@@ -0,0 +1,350 @@
// @vitest-environment happy-dom
import { MODULE_CONTRIBUTION_ABI_VERSION, ModuleContributionError } from "@ekklesia/module-ui-sdk";
import { describe, expect, it } from "vitest";
import {
loadModuleContribution,
MODULE_UI_ISOLATION_ATTRIBUTE,
MODULE_UI_ISOLATION_ROOT_ATTRIBUTE,
MODULE_UI_ISOLATION_STYLE_ATTRIBUTE,
ModuleUiHostError,
} from "../src/index.js";
function moduleUrl(source: string): string {
return `data:text/javascript;base64,${Buffer.from(source, "utf8").toString("base64")}`;
}
const contributionArtifact = (
options: {
id?: string;
version?: string;
styles?: string;
updatable?: boolean;
cleanup?: boolean;
mountThrows?: boolean;
updateThrows?: boolean;
} = {},
) => `
export default {
abi: ${MODULE_CONTRIBUTION_ABI_VERSION},
id: ${JSON.stringify(options.id ?? "announcements.signage-slide")},
version: ${JSON.stringify(options.version ?? "1.0.0")},
${options.styles === undefined ? "" : `styles: ${JSON.stringify(options.styles)},`}
mount(container, context) {
${options.mountThrows ? 'throw new Error("mount exploded");' : ""}
globalThis.__contributionMounts ??= [];
globalThis.__contributionMounts.push({ container, contributionId: context.contributionId });
container.textContent = "slide:" + JSON.stringify(context.input);
return {
${
options.updatable === false
? ""
: `update(input) {
${options.updateThrows ? 'throw new Error("update exploded");' : ""}
container.textContent = "slide:" + JSON.stringify(input);
},`
}
${
options.cleanup === false
? ""
: `unmount() {
globalThis.__contributionUnmounts = (globalThis.__contributionUnmounts ?? 0) + 1;
container.textContent = "";
},`
}
};
},
};
`;
function container(): Element {
const element = document.createElement("div");
document.body.append(element);
return element;
}
function renderedText(element: Element): string {
const shadowHost = element.querySelector(`[${MODULE_UI_ISOLATION_ATTRIBUTE}]`);
return (
shadowHost?.shadowRoot?.querySelector(`[${MODULE_UI_ISOLATION_ROOT_ATTRIBUTE}]`)?.textContent ??
""
);
}
const source = { contributionId: "announcements.signage-slide", version: "1.0.0" };
describe("generic contribution loader", () => {
it("mounts a contribution with the consumer's input, in its own isolated root", async () => {
const element = container();
const mounted = await loadModuleContribution({
container: element,
input: { slide: 1 },
source: { ...source, url: moduleUrl(contributionArtifact({ styles: ".slide{color:red}" })) },
});
expect(mounted.contributionId).toBe("announcements.signage-slide");
expect(mounted.version).toBe("1.0.0");
expect(mounted.mounted).toBe(true);
expect(renderedText(element)).toBe('slide:{"slide":1}');
// Same isolation as every other browser artifact (ADR 0040): the renderer's styles cannot reach
// the consuming module's own screen around it.
const shadowRoot = element.querySelector(`[${MODULE_UI_ISOLATION_ATTRIBUTE}]`)?.shadowRoot;
expect(
shadowRoot?.querySelector(`style[${MODULE_UI_ISOLATION_STYLE_ATTRIBUTE}]`)?.textContent,
).toContain(".slide{color:red}");
expect(element.textContent).toBe("");
});
it("gives the renderer its own id and nothing else from the platform", async () => {
const element = container();
await loadModuleContribution({
container: element,
input: null,
source: { ...source, url: moduleUrl(contributionArtifact()) },
});
const mounts = (
globalThis as { __contributionMounts?: { contributionId: string; container: Element }[] }
).__contributionMounts;
expect(mounts?.at(-1)?.contributionId).toBe("announcements.signage-slide");
// The isolated root, never the consumer's own element.
expect(mounts?.at(-1)?.container).not.toBe(element);
});
it("updates in place without remounting", async () => {
const element = container();
const before = (globalThis as { __contributionMounts?: unknown[] }).__contributionMounts
?.length;
const mounted = await loadModuleContribution({
container: element,
input: { slide: 1 },
source: { ...source, url: moduleUrl(contributionArtifact()) },
});
await mounted.update({ slide: 2 });
expect(renderedText(element)).toBe('slide:{"slide":2}');
// One mount, two renders: exactly the property a long-running screen needs.
expect(
((globalThis as { __contributionMounts?: unknown[] }).__contributionMounts?.length ?? 0) -
(before ?? 0),
).toBe(1);
});
it("tells a consumer to remount when the renderer cannot update in place", async () => {
const element = container();
const mounted = await loadModuleContribution({
container: element,
input: { slide: 1 },
source: { ...source, url: moduleUrl(contributionArtifact({ updatable: false })) },
});
await expect(mounted.update({ slide: 2 })).rejects.toMatchObject({
code: "MODULE_CONTRIBUTION_NOT_UPDATABLE",
});
});
it("reports a throwing update as a sanitized failure", async () => {
const element = container();
const mounted = await loadModuleContribution({
container: element,
input: { slide: 1 },
source: { ...source, url: moduleUrl(contributionArtifact({ updateThrows: true })) },
});
try {
await mounted.update({ slide: 2 });
expect.unreachable("expected the update to fail");
} catch (error) {
expect(error).toBeInstanceOf(ModuleUiHostError);
expect((error as ModuleUiHostError).code).toBe("MODULE_CONTRIBUTION_UPDATE_FAILED");
expect((error as ModuleUiHostError).message).not.toContain("exploded");
expect((error as { cause?: Error }).cause?.message).toBe("update exploded");
}
});
it("unmounts deterministically, idempotently, and removes the isolated root", async () => {
const element = container();
const before = (globalThis as { __contributionUnmounts?: number }).__contributionUnmounts ?? 0;
const mounted = await loadModuleContribution({
container: element,
input: { slide: 1 },
source: { ...source, url: moduleUrl(contributionArtifact({ styles: ".slide{}" })) },
});
await mounted.unmount();
await mounted.unmount();
expect(mounted.mounted).toBe(false);
expect(element.children).toHaveLength(0);
expect(
((globalThis as { __contributionUnmounts?: number }).__contributionUnmounts ?? 0) - before,
).toBe(1);
await expect(mounted.update({ slide: 2 })).rejects.toMatchObject({
code: "MODULE_CONTRIBUTION_UNKNOWN",
});
});
it("unmounts safely when the renderer registered no cleanup", async () => {
const element = container();
const mounted = await loadModuleContribution({
container: element,
input: null,
source: { ...source, url: moduleUrl(contributionArtifact({ cleanup: false })) },
});
await expect(mounted.unmount()).resolves.toBeUndefined();
expect(element.children).toHaveLength(0);
});
it("refuses input that is not genuinely JSON, before importing anything", async () => {
const element = container();
let imported = false;
for (const input of [
new Date() as unknown as null,
(() => undefined) as unknown as null,
Number.NaN as unknown as null,
{ nested: undefined } as unknown as null,
]) {
await expect(
loadModuleContribution({
container: element,
input,
importModule: async () => {
imported = true;
return {};
},
source: { ...source, url: "unused" },
}),
).rejects.toMatchObject({ code: "MODULE_CONTRIBUTION_INPUT_INVALID" });
}
const cyclic: Record<string, unknown> = {};
cyclic.self = cyclic;
await expect(
loadModuleContribution({
container: element,
input: cyclic as never,
source: { ...source, url: "unused" },
}),
).rejects.toMatchObject({ code: "MODULE_CONTRIBUTION_INPUT_INVALID" });
expect(imported).toBe(false);
expect(element.children).toHaveLength(0);
});
it("never echoes the consumer's domain data in a failure", async () => {
const element = container();
try {
await loadModuleContribution({
container: element,
input: { secretHeading: new Date() } as unknown as null,
source: { ...source, url: "unused" },
});
expect.unreachable("expected the input to be refused");
} catch (error) {
expect(error).toBeInstanceOf(ModuleContributionError);
expect(String((error as Error).message)).not.toContain("secretHeading");
expect(String((error as Error).stack)).not.toContain("secretHeading");
}
});
it.each([
[
"a different contribution id",
contributionArtifact({ id: "calendar.week" }),
"MODULE_CONTRIBUTION_IDENTITY_MISMATCH",
],
[
"a different version",
contributionArtifact({ version: "2.0.0" }),
"MODULE_CONTRIBUTION_IDENTITY_MISMATCH",
],
[
"a different contribution ABI",
'export default { abi: 99, id: "announcements.signage-slide", version: "1.0.0", mount() {} };',
"MODULE_CONTRIBUTION_ABI_UNSUPPORTED",
],
["no default export", "export const contribution = {};", "MODULE_CONTRIBUTION_EXPORT_MISSING"],
[
"a malformed definition",
`export default { abi: ${MODULE_CONTRIBUTION_ABI_VERSION}, id: "announcements.signage-slide" };`,
"MODULE_CONTRIBUTION_DEFINITION_INVALID",
],
])("refuses %s before mounting", async (_label, artifact, code) => {
const element = container();
await expect(
loadModuleContribution({
container: element,
input: null,
source: { ...source, url: moduleUrl(artifact) },
}),
).rejects.toMatchObject({ code });
expect(element.children).toHaveLength(0);
});
it("reports a throwing mount as a sanitized failure and leaves nothing behind", async () => {
const element = container();
try {
await loadModuleContribution({
container: element,
input: null,
source: { ...source, url: moduleUrl(contributionArtifact({ mountThrows: true })) },
});
expect.unreachable("expected the mount to fail");
} catch (error) {
expect(error).toBeInstanceOf(ModuleUiHostError);
expect((error as ModuleUiHostError).code).toBe("MODULE_UI_MOUNT_FAILED");
expect((error as ModuleUiHostError).message).not.toContain("exploded");
}
expect(element.children).toHaveLength(0);
});
it("reports an unreachable artifact as an import failure with no URL in the message", async () => {
const element = container();
try {
await loadModuleContribution({
container: element,
input: null,
source: { ...source, url: "data:text/javascript,this is not(valid javascript" },
});
expect.unreachable("expected the import to fail");
} catch (error) {
expect((error as ModuleUiHostError).code).toBe("MODULE_UI_IMPORT_FAILED");
expect((error as ModuleUiHostError).message).not.toContain("data:");
}
});
it("keeps two mounted contributions independent", async () => {
const first = container();
const second = container();
const url = moduleUrl(contributionArtifact());
const a = await loadModuleContribution({
container: first,
input: { slide: "a" },
source: { ...source, url },
});
const b = await loadModuleContribution({
container: second,
input: { slide: "b" },
source: { ...source, url },
});
await a.unmount();
expect(a.mounted).toBe(false);
expect(b.mounted).toBe(true);
expect(first.children).toHaveLength(0);
expect(renderedText(second)).toBe('slide:{"slide":"b"}');
});
});
@@ -3,6 +3,7 @@ import {
MODULE_UI_ABI_VERSION,
ModuleUiContractError,
type ModuleUiHostContext,
NO_MODULE_UI_CONTRIBUTIONS,
} from "@ekklesia/module-ui-sdk";
import { describe, expect, it } from "vitest";
import {
@@ -50,6 +51,7 @@ export default {
function hostContext(requested: string[], moduleId = "announcements"): ModuleUiHostContext {
return {
contributions: NO_MODULE_UI_CONTRIBUTIONS,
moduleId,
api: {
async request(path) {
@@ -3,7 +3,7 @@ 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 { type ModuleUiHostContext, NO_MODULE_UI_CONTRIBUTIONS } from "@ekklesia/module-ui-sdk";
import { beforeAll, describe, expect, it } from "vitest";
import {
loadModuleUi,
@@ -32,6 +32,7 @@ let artifactSource: string;
/** An Ekklesia-shaped host: module routes live under a Core-owned prefix. */
function ekklesiaContext(requested: string[]): ModuleUiHostContext {
return {
contributions: NO_MODULE_UI_CONTRIBUTIONS,
moduleId: "example",
api: {
async request(pathname) {
@@ -48,6 +49,7 @@ function ekklesiaContext(requested: string[]): ModuleUiHostContext {
/** A standalone host: one module, a different origin, a completely different URL shape, no Core. */
function standaloneContext(requested: string[]): ModuleUiHostContext {
return {
contributions: NO_MODULE_UI_CONTRIBUTIONS,
moduleId: "example",
api: {
async request(pathname) {