feat: give module UI real stylesheets, and every artifact its own root
ADR 0023 refused stylesheet imports for a good reason: esbuild would emit a
`.css` sidecar beside the artifact, nothing would declare it, no host would
fetch it, and it would work in a local test and silently do nothing in a real
host. Inline style objects were the whole story. They cannot express
`:hover`, `:focus-visible`, `:disabled`, `@media`, or `@keyframes` — so an
accessible focus treatment was not expressible, and the shared elements added
in the previous commit are built from real CSS for exactly that reason.
Compile the stylesheet into the artifact instead of beside it. A module
imports plain `.css`; the canonical builder resolves local `@import`s through
a nested bundle and turns each file into its compiled text, which the author
declares as `defineModuleUi({ styles })`. One declared file still contains
everything: nothing extra to publish, nothing to fetch, and no way for CSS to
become an asset nobody serves. The build additionally fails if a CSS output
ever appears beside an artifact, so a future loader change cannot bring the
sidecar back. Two rules are enforced with their own codes: a module stylesheet
may reference `--ekklesia-*` and never declare one, and every `@import` must
resolve locally or the artifact would fetch styles at run time. Plain `.css`
only; other dialects are a toolchain decision needing their own ADR.
Then make the isolation real. The generic loader mounts every browser artifact
— primary, display, and later a contributed renderer — inside an open Shadow
DOM root it creates, installs the artifact's stylesheet there, and hands the
artifact an element inside it. Shadow DOM is the one mechanism a browser
actually enforces; a class prefix or a "scope your selectors" instruction is a
convention one mistake defeats, and the failure mode is a module silently
restyling the Dashboard. It applies unconditionally, including to artifacts
with no stylesheet, because a conditional boundary is one a module can fall
out of by editing a source file. Both wrappers are `display: contents` through
base rules installed before the artifact's own, so layout is unchanged and a
full-viewport display can still override `:host`. Unmount removes the whole
root in a `finally`, so a cleanup that throws cannot leave styles behind, and
remounting cannot accumulate a second copy.
This is a correctness boundary for styles and is not described as a sandbox:
the root is `open` precisely because module code is trusted, same-realm code
that could reach `document` anyway.
An artifact's DOM is no longer a direct child of the host's element, so the
mount ABI is versioned explicitly. `defineModuleUi` stamps
`MODULE_UI_ABI_VERSION` so it can never drift from the SDK the artifact
compiled against, and a version-1 artifact fails with its own code — "rebuild
your module", not a typo hunt. No dual acceptance, matching every manifest
cutover here. Migration is one `pnpm build`.
`pnpm boundaries` allows `.css` only under `src/ui/` and `src/display/`: a
stylesheet anywhere else in a module is the undeclared sidecar again, just
relocated.
Co-Authored-By: Claude Opus 5 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5
parent
e03d38fcab
commit
07835b7b56
@@ -1,12 +1,18 @@
|
||||
import { type ModuleUiDefinition, parseModuleUiDefinition } from "./module-ui.js";
|
||||
import {
|
||||
MODULE_UI_ABI_VERSION,
|
||||
type ModuleUiDefinition,
|
||||
type ModuleUiDefinitionInput,
|
||||
parseModuleUiDefinition,
|
||||
} from "./module-ui.js";
|
||||
|
||||
/**
|
||||
* The module author's entry point, mirroring `defineModuleRuntime` (ADR 0006): validate at authoring
|
||||
* time, freeze, and preserve the literal type. A malformed definition fails where it was written
|
||||
* rather than in a host, at mount time, in a browser.
|
||||
* time, freeze, and stamp the browser mount ABI this artifact was built against. A malformed
|
||||
* definition fails where it was written rather than in a host, at mount time, in a browser.
|
||||
*
|
||||
* The ABI marker is added here rather than written by the author, so it can never drift from the SDK
|
||||
* the artifact actually compiled against — which is the whole point of having one (ADR 0040).
|
||||
*/
|
||||
export function defineModuleUi<const Definition extends ModuleUiDefinition>(
|
||||
definition: Definition,
|
||||
): Readonly<Definition> {
|
||||
return parseModuleUiDefinition(definition) as Readonly<Definition>;
|
||||
export function defineModuleUi(definition: ModuleUiDefinitionInput): ModuleUiDefinition {
|
||||
return parseModuleUiDefinition({ ...definition, abi: MODULE_UI_ABI_VERSION });
|
||||
}
|
||||
|
||||
@@ -2,17 +2,38 @@ import type { ModuleUiHostContext } from "./host-context.js";
|
||||
|
||||
export type Awaitable<Value> = Value | PromiseLike<Value>;
|
||||
|
||||
/**
|
||||
* The version of the browser mount ABI this package defines, and the only one a host accepts.
|
||||
*
|
||||
* Version 1 was `{ id, version, mount }` mounted straight into the host's own container. Version 2
|
||||
* adds a declared `styles` stylesheet and makes every artifact mount inside an **isolated root** the
|
||||
* host creates (ADR 0040). That is a behavioural change an artifact can observe — its DOM is no
|
||||
* longer a direct child of the host's element — so it is versioned explicitly rather than
|
||||
* introduced silently.
|
||||
*
|
||||
* There is deliberately no dual acceptance, exactly as there is none for a manifest version
|
||||
* (ADR 0006, ADR 0014, ADR 0021, ADR 0033): an artifact built against version 1 fails to mount with
|
||||
* `MODULE_UI_ABI_UNSUPPORTED` rather than being mounted under guessed semantics. Migration is to
|
||||
* rebuild the module, which is one `pnpm build` — the canonical builder owns every option, and a
|
||||
* module that declares no stylesheet needs no source change at all.
|
||||
*
|
||||
* `defineModuleUi` stamps this for the author. A module never writes it.
|
||||
*/
|
||||
export const MODULE_UI_ABI_VERSION = 2;
|
||||
|
||||
/**
|
||||
* Released by a host when the module UI should be torn down. A module that acquires anything during
|
||||
* `mount` — a framework root, a subscription, a timer, an event listener — must return one of these
|
||||
* and release that work here, exactly as a backend module releases resources in its `stop` hook
|
||||
* (ADR 0006). Returning nothing declares that the mount acquired nothing to release.
|
||||
*
|
||||
* A module never has to remove its declared `styles`: the host installed them into the isolated root
|
||||
* it owns, and it removes that whole root after this runs.
|
||||
*/
|
||||
export type ModuleUiUnmount = () => Awaitable<void>;
|
||||
|
||||
/**
|
||||
* What either compiled browser artifact (`entrypoints.ui` or `entrypoints.display.artifact`)
|
||||
* default-exports (ADR 0021, ADR 0022, ADR 0033).
|
||||
* What a module author passes to {@link defineModuleUi}.
|
||||
*
|
||||
* `id` and `version` are build-artifact identity markers, mirroring `ModuleRuntimeDefinition`
|
||||
* exactly (ADR 0006): they let a host prove the UI bundle it imported was built from the module it
|
||||
@@ -23,19 +44,38 @@ export type ModuleUiUnmount = () => Awaitable<void>;
|
||||
* write that (ADR 0022), but React appears nowhere in this type — the contract is a mount function,
|
||||
* so a module's internal framework choice, and a host's, can each change without renegotiating the
|
||||
* platform boundary.
|
||||
*
|
||||
* `styles` is the artifact's own compiled CSS **text**, not a URL, a filename, or a sidecar
|
||||
* (ADR 0040). A module imports its local `.css` files and the canonical builder compiles them into
|
||||
* this string, so the declared JavaScript artifact stays exactly as self-contained as it was before
|
||||
* stylesheets existed: there is no second file to publish, nothing for a host to fetch, and no way
|
||||
* for a stylesheet to become an asset nothing serves. The host installs it into the artifact's
|
||||
* isolated root at mount and removes it at unmount.
|
||||
*/
|
||||
export interface ModuleUiDefinition {
|
||||
export interface ModuleUiDefinitionInput {
|
||||
readonly id: string;
|
||||
readonly version: string;
|
||||
readonly styles?: string;
|
||||
readonly mount: (
|
||||
container: Element,
|
||||
context: ModuleUiHostContext,
|
||||
) => Awaitable<ModuleUiUnmount | void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* What either compiled browser artifact (`entrypoints.ui` or `entrypoints.display.artifact`)
|
||||
* default-exports (ADR 0021, ADR 0022, ADR 0033, ADR 0040): the author's declaration plus the ABI
|
||||
* marker `defineModuleUi` stamped on it.
|
||||
*/
|
||||
export interface ModuleUiDefinition extends ModuleUiDefinitionInput {
|
||||
readonly abi: number;
|
||||
}
|
||||
|
||||
export type ModuleUiContractErrorCode =
|
||||
| "MODULE_UI_EXPORT_MISSING"
|
||||
| "MODULE_UI_DEFINITION_INVALID"
|
||||
| "MODULE_UI_ABI_UNSUPPORTED"
|
||||
| "MODULE_UI_STYLES_INVALID"
|
||||
| "MODULE_UI_IDENTITY_MISMATCH";
|
||||
|
||||
const errorMessages: Readonly<Record<ModuleUiContractErrorCode, string>> = Object.freeze({
|
||||
@@ -43,6 +83,10 @@ const errorMessages: Readonly<Record<ModuleUiContractErrorCode, string>> = Objec
|
||||
"A module UI entrypoint must have a default export produced by defineModuleUi.",
|
||||
MODULE_UI_DEFINITION_INVALID:
|
||||
"A module UI definition must declare a non-empty id and version and a mount function, and nothing else.",
|
||||
MODULE_UI_ABI_UNSUPPORTED:
|
||||
"This module UI artifact was built for a different browser mount ABI. Rebuild the module against the current module UI SDK.",
|
||||
MODULE_UI_STYLES_INVALID:
|
||||
"A module UI definition's styles must be the artifact's compiled CSS text, as a non-empty string.",
|
||||
MODULE_UI_IDENTITY_MISMATCH:
|
||||
"The module UI artifact's id and version do not match the module it was loaded for.",
|
||||
});
|
||||
@@ -64,7 +108,7 @@ export class ModuleUiContractError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
const definitionKeys = new Set(["id", "mount", "version"]);
|
||||
const definitionKeys = new Set(["abi", "id", "mount", "styles", "version"]);
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
@@ -80,12 +124,15 @@ function isNonEmptyString(value: unknown): value is string {
|
||||
* grammar — there is exactly one place each of those is defined, and it is not here.
|
||||
*/
|
||||
export function isModuleUiDefinition(value: unknown): value is ModuleUiDefinition {
|
||||
if (!isRecord(value)) {
|
||||
if (!isRecord(value) || value.abi !== MODULE_UI_ABI_VERSION) {
|
||||
return false;
|
||||
}
|
||||
if (Object.keys(value).some((key) => !definitionKeys.has(key))) {
|
||||
return false;
|
||||
}
|
||||
if (value.styles !== undefined && !isNonEmptyString(value.styles)) {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
isNonEmptyString(value.id) &&
|
||||
isNonEmptyString(value.version) &&
|
||||
@@ -93,13 +140,31 @@ export function isModuleUiDefinition(value: unknown): value is ModuleUiDefinitio
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses an artifact's default export.
|
||||
*
|
||||
* The ABI marker is checked **first and on its own**, so an artifact built against the previous
|
||||
* mount ABI is reported as exactly that rather than as a malformed definition — the difference
|
||||
* between "rebuild your module" and a developer hunting for a typo.
|
||||
*/
|
||||
export function parseModuleUiDefinition(value: unknown): ModuleUiDefinition {
|
||||
if (!isRecord(value)) {
|
||||
throw new ModuleUiContractError("MODULE_UI_DEFINITION_INVALID");
|
||||
}
|
||||
if (value.abi !== MODULE_UI_ABI_VERSION) {
|
||||
throw new ModuleUiContractError("MODULE_UI_ABI_UNSUPPORTED");
|
||||
}
|
||||
if (value.styles !== undefined && !isNonEmptyString(value.styles)) {
|
||||
throw new ModuleUiContractError("MODULE_UI_STYLES_INVALID");
|
||||
}
|
||||
if (!isModuleUiDefinition(value)) {
|
||||
throw new ModuleUiContractError("MODULE_UI_DEFINITION_INVALID");
|
||||
}
|
||||
return Object.freeze({
|
||||
abi: MODULE_UI_ABI_VERSION,
|
||||
id: value.id,
|
||||
mount: value.mount,
|
||||
...(value.styles === undefined ? {} : { styles: value.styles }),
|
||||
version: value.version,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -2,23 +2,32 @@ import { beforeEach, describe, expect, it } from "vitest";
|
||||
import {
|
||||
defineModuleUi,
|
||||
isModuleUiDefinition,
|
||||
MODULE_UI_ABI_VERSION,
|
||||
ModuleUiContractError,
|
||||
type ModuleUiApiClient,
|
||||
type ModuleUiDefinition,
|
||||
type ModuleUiDefinitionInput,
|
||||
type ModuleUiHostContext,
|
||||
type ModuleUiRealtimeClient,
|
||||
parseModuleUiDefinition,
|
||||
parseModuleUiExport,
|
||||
} from "../src/index.js";
|
||||
|
||||
function validDefinition(): ModuleUiDefinition {
|
||||
function definitionInput(): ModuleUiDefinitionInput {
|
||||
return { id: "announcements", version: "0.1.0", mount: (): void => undefined };
|
||||
}
|
||||
|
||||
/** What a compiled artifact actually default-exports: the author's declaration plus the ABI marker
|
||||
* `defineModuleUi` stamps on it (ADR 0040). */
|
||||
function validDefinition(): ModuleUiDefinition {
|
||||
return { abi: MODULE_UI_ABI_VERSION, ...definitionInput() };
|
||||
}
|
||||
|
||||
/** The contract treats the container as an opaque host-supplied mount target, so a plain object
|
||||
* with the one property the fixture touches is a faithful stand-in. No DOM is required to prove the
|
||||
* contract, and this package deliberately does not take a DOM dependency to obtain one. */
|
||||
const noop = (): void => undefined;
|
||||
const abi = MODULE_UI_ABI_VERSION;
|
||||
|
||||
const noopRealtime: ModuleUiRealtimeClient = Object.freeze({
|
||||
subscribe: () => Object.freeze({ close: noop }),
|
||||
@@ -29,23 +38,66 @@ function fakeContainer(): Element & { textContent: string } {
|
||||
}
|
||||
|
||||
describe("module UI definition contract", () => {
|
||||
it("accepts and freezes a valid definition", () => {
|
||||
const definition = defineModuleUi(validDefinition());
|
||||
it("accepts, stamps the ABI on, and freezes a valid definition", () => {
|
||||
const definition = defineModuleUi(definitionInput());
|
||||
|
||||
expect(definition.id).toBe("announcements");
|
||||
expect(definition.version).toBe("0.1.0");
|
||||
// Stamped by the SDK the artifact compiled against, never written by the author, so it can
|
||||
// never drift from the contract the artifact was actually built for.
|
||||
expect(definition.abi).toBe(MODULE_UI_ABI_VERSION);
|
||||
expect(definition.styles).toBeUndefined();
|
||||
expect(Object.isFrozen(definition)).toBe(true);
|
||||
});
|
||||
|
||||
it("carries a declared stylesheet through as the artifact's own compiled CSS text", () => {
|
||||
const definition = defineModuleUi({ ...definitionInput(), styles: ".a{color:red}" });
|
||||
|
||||
expect(definition.styles).toBe(".a{color:red}");
|
||||
});
|
||||
|
||||
it("rejects an artifact built against a different mount ABI, with its own code", () => {
|
||||
// The whole point of the marker: a version-1 artifact is reported as "rebuild your module",
|
||||
// not as a malformed definition a developer would hunt for a typo in.
|
||||
const versionOne = { id: "announcements", version: "0.1.0", mount: noop };
|
||||
|
||||
expect(isModuleUiDefinition(versionOne)).toBe(false);
|
||||
try {
|
||||
parseModuleUiDefinition(versionOne);
|
||||
expect.unreachable("expected a contract error");
|
||||
} catch (error) {
|
||||
expect((error as ModuleUiContractError).code).toBe("MODULE_UI_ABI_UNSUPPORTED");
|
||||
}
|
||||
expect(() =>
|
||||
parseModuleUiDefinition({ ...versionOne, abi: MODULE_UI_ABI_VERSION + 1 }),
|
||||
).toThrowError(expect.objectContaining({ code: "MODULE_UI_ABI_UNSUPPORTED" }));
|
||||
});
|
||||
|
||||
it.each<[string, unknown]>([
|
||||
["a missing id", { version: "0.1.0", mount: noop }],
|
||||
["a blank id", { id: " ", version: "0.1.0", mount: noop }],
|
||||
["a non-string id", { id: 7, version: "0.1.0", mount: noop }],
|
||||
["a missing version", { id: "announcements", mount: noop }],
|
||||
["a blank version", { id: "announcements", version: "", mount: noop }],
|
||||
["a missing mount", { id: "announcements", version: "0.1.0" }],
|
||||
["a non-function mount", { id: "announcements", version: "0.1.0", mount: "render" }],
|
||||
["an unknown property", { id: "announcements", version: "0.1.0", mount: noop, routes: [] }],
|
||||
["a blank stylesheet", " "],
|
||||
["a non-string stylesheet", 7],
|
||||
["an array of stylesheets", [".a{}"]],
|
||||
])("rejects %s", (_label, styles) => {
|
||||
const candidate = { ...validDefinition(), styles };
|
||||
|
||||
expect(isModuleUiDefinition(candidate)).toBe(false);
|
||||
expect(() => parseModuleUiDefinition(candidate)).toThrowError(
|
||||
expect.objectContaining({ code: "MODULE_UI_STYLES_INVALID" }),
|
||||
);
|
||||
});
|
||||
|
||||
it.each<[string, unknown]>([
|
||||
["a missing id", { abi, version: "0.1.0", mount: noop }],
|
||||
["a blank id", { abi, id: " ", version: "0.1.0", mount: noop }],
|
||||
["a non-string id", { abi, id: 7, version: "0.1.0", mount: noop }],
|
||||
["a missing version", { abi, id: "announcements", mount: noop }],
|
||||
["a blank version", { abi, id: "announcements", version: "", mount: noop }],
|
||||
["a missing mount", { abi, id: "announcements", version: "0.1.0" }],
|
||||
["a non-function mount", { abi, id: "announcements", version: "0.1.0", mount: "render" }],
|
||||
[
|
||||
"an unknown property",
|
||||
{ abi, id: "announcements", version: "0.1.0", mount: noop, routes: [] },
|
||||
],
|
||||
])("rejects a definition with %s", (_label, candidate) => {
|
||||
expect(isModuleUiDefinition(candidate)).toBe(false);
|
||||
expect(() => parseModuleUiDefinition(candidate)).toThrowError(ModuleUiContractError);
|
||||
@@ -64,7 +116,7 @@ describe("module UI definition contract", () => {
|
||||
|
||||
it("reports a malformed definition with a stable, sanitized code", () => {
|
||||
try {
|
||||
parseModuleUiDefinition({ id: "announcements" });
|
||||
parseModuleUiDefinition({ abi, id: "announcements" });
|
||||
expect.unreachable("expected a contract error");
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(ModuleUiContractError);
|
||||
|
||||
Reference in New Issue
Block a user