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
@@ -23,6 +23,8 @@ export type ModuleUiBuildErrorCode =
|
||||
| "MODULE_UI_ENTRYPOINT_UNSAFE"
|
||||
| "MODULE_UI_ENTRYPOINT_COLLISION"
|
||||
| "MODULE_UI_SOURCE_MISSING"
|
||||
| "MODULE_UI_STYLESHEET_INVALID"
|
||||
| "MODULE_UI_STYLESHEET_UNDECLARED"
|
||||
| "MODULE_UI_BUILD_FAILED";
|
||||
|
||||
export type ModuleUiArtifactKind = "ui" | "display";
|
||||
@@ -34,6 +36,10 @@ const errorMessages: Readonly<Record<ModuleUiBuildErrorCode, string>> = Object.f
|
||||
MODULE_UI_ENTRYPOINT_COLLISION:
|
||||
"A display UI entrypoint must not overwrite another declared artifact.",
|
||||
MODULE_UI_SOURCE_MISSING: "A declared module UI source entrypoint was not found.",
|
||||
MODULE_UI_STYLESHEET_INVALID:
|
||||
"A module stylesheet may not define a global Ekklesia theme variable or keep an unresolved @import.",
|
||||
MODULE_UI_STYLESHEET_UNDECLARED:
|
||||
"A module UI build produced a stylesheet beside its artifact. Every style must be compiled into the declared artifact.",
|
||||
MODULE_UI_BUILD_FAILED: "A module UI bundle could not be produced.",
|
||||
});
|
||||
|
||||
@@ -58,32 +64,97 @@ export class ModuleUiBuildError extends Error {
|
||||
}
|
||||
|
||||
/**
|
||||
* Rejects a stylesheet import instead of quietly emitting one.
|
||||
*
|
||||
* esbuild would happily bundle `import "./styles.css"` into a sidecar `index.css` next to the
|
||||
* artifact. Nothing declares that file, no host loads it, and the manifest has no field for it — so
|
||||
* it would work in a local test and silently do nothing in a real host. Module styling has no
|
||||
* public loading contract yet (ADR 0023), so the build fails loudly rather than producing an
|
||||
* undeclared asset. `scripts/check-boundaries.ts` rejects a `.css` file authored *inside* a module;
|
||||
* this additionally covers a stylesheet reached through a dependency.
|
||||
* A CSS custom property in Ekklesia's own global theme namespace, being **declared** rather than
|
||||
* referenced. `var(--ekklesia-x)` and `var(--ekklesia-x, fallback)` are reads and are fine; only a
|
||||
* `--ekklesia-x:` declaration matches, because that is what would invent a global theme variable
|
||||
* outside the registry a future theme editor enumerates (ADR 0039).
|
||||
*/
|
||||
function rejectStylesheetImports(): Plugin {
|
||||
const GLOBAL_THEME_DECLARATION = /--ekklesia-[a-z0-9-]*\s*:/iu;
|
||||
|
||||
/** An `@import` that survived compilation — a remote or otherwise unresolvable one. A local import
|
||||
* is inlined by the nested bundle below and leaves nothing behind, so anything still here would make
|
||||
* the artifact fetch a stylesheet at run time, which is exactly what "self-contained" excludes. */
|
||||
const SURVIVING_IMPORT = /@import\s/iu;
|
||||
|
||||
/**
|
||||
* Compiles each imported stylesheet into the artifact instead of emitting a sidecar.
|
||||
*
|
||||
* esbuild's default for `import "./styles.css"` from JavaScript is to collect every such stylesheet
|
||||
* into an `index.css` output beside the artifact. Nothing declares that file, no host fetches it,
|
||||
* and the manifest has no field for it — it would work in a local test and silently do nothing in a
|
||||
* real host. ADR 0023 therefore rejected the import outright; ADR 0040 compiles it instead.
|
||||
*
|
||||
* Each `.css` import becomes a JavaScript module whose default export is that stylesheet's compiled
|
||||
* text, produced by a nested esbuild run so local `@import`s are resolved and the result is one
|
||||
* self-contained string. The author passes that string to `defineModuleUi({ styles })` and the host
|
||||
* installs it into the artifact's isolated root. The declared `.js` artifact therefore remains the
|
||||
* only file the platform publishes, exactly as before stylesheets existed.
|
||||
*
|
||||
* Other stylesheet dialects stay rejected. Adding one is a language and toolchain decision, not a
|
||||
* detail of this pass, and would need its own ADR.
|
||||
*/
|
||||
const STYLESHEET_PLUGIN_NAME = "ekklesia-compile-stylesheet-imports";
|
||||
|
||||
function compileStylesheetImports(): Plugin {
|
||||
const decoder = new TextDecoder();
|
||||
return {
|
||||
name: "ekklesia-reject-stylesheet-imports",
|
||||
name: STYLESHEET_PLUGIN_NAME,
|
||||
setup(pluginBuild) {
|
||||
// No `u` flag, deliberately: esbuild compiles a plugin filter to a Go RE2 expression, which
|
||||
// rejects `(?iu)` outright ("filter is not a valid Go regular expression"). This pattern is
|
||||
// rejects `(?iu)` outright ("filter is not a valid Go regular expression"). These patterns are
|
||||
// pure ASCII, so the flag would change nothing anyway.
|
||||
pluginBuild.onResolve({ filter: /\.(css|s[ac]ss|less|styl|pcss|postcss)$/i }, (args) => ({
|
||||
pluginBuild.onResolve({ filter: /\.(s[ac]ss|less|styl|pcss|postcss)$/i }, (args) => ({
|
||||
errors: [
|
||||
{
|
||||
text:
|
||||
"Module UI cannot import a stylesheet yet: there is no declared way for a host to " +
|
||||
"load one. Use React inline style objects for now (ADR 0023).",
|
||||
"Module UI supports plain .css only. Other stylesheet dialects have no compilation " +
|
||||
"contract in this platform (ADR 0040).",
|
||||
location: { file: args.importer },
|
||||
},
|
||||
],
|
||||
}));
|
||||
|
||||
pluginBuild.onLoad({ filter: /\.css$/i }, async (args) => {
|
||||
const compiled = await build({
|
||||
bundle: true,
|
||||
entryPoints: [args.path],
|
||||
logLevel: "silent",
|
||||
minify: false,
|
||||
target: MODULE_UI_BUILD_TARGET,
|
||||
write: false,
|
||||
});
|
||||
const stylesheet = compiled.outputFiles
|
||||
.map((outputFile) => decoder.decode(outputFile.contents))
|
||||
.join("\n");
|
||||
|
||||
if (GLOBAL_THEME_DECLARATION.test(stylesheet)) {
|
||||
return {
|
||||
errors: [
|
||||
{
|
||||
text:
|
||||
"A module stylesheet may reference Ekklesia's global theme variables but must " +
|
||||
"never declare one. Derive a private alias under your own prefix instead " +
|
||||
"(ADR 0039).",
|
||||
location: { file: args.path },
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
if (SURVIVING_IMPORT.test(stylesheet)) {
|
||||
return {
|
||||
errors: [
|
||||
{
|
||||
text:
|
||||
"A module stylesheet left an unresolved @import. A declared artifact must be " +
|
||||
"self-contained, so every import has to resolve to a local file (ADR 0040).",
|
||||
location: { file: args.path },
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
return { contents: `export default ${JSON.stringify(stylesheet)};`, loader: "js" };
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -237,7 +308,7 @@ export async function buildModuleUi(options: BuildModuleUiOptions): Promise<Modu
|
||||
minify: false,
|
||||
outfile: artifact.outputFile,
|
||||
platform: "browser",
|
||||
plugins: [rejectStylesheetImports()],
|
||||
plugins: [compileStylesheetImports()],
|
||||
sourcemap: true,
|
||||
target: MODULE_UI_BUILD_TARGET,
|
||||
// Fail rather than silently shipping a partial bundle.
|
||||
@@ -246,6 +317,17 @@ export async function buildModuleUi(options: BuildModuleUiOptions): Promise<Modu
|
||||
// atomic with respect to parse/resolve/bundle failures rather than leaving a stale partial set.
|
||||
write: false,
|
||||
});
|
||||
// Belt and braces on the stylesheet contract. The plugin above turns every `.css` import into
|
||||
// JavaScript, so esbuild has nothing left to emit a stylesheet from — but a future option or
|
||||
// loader change could reintroduce a sidecar, and a sidecar is precisely the failure this
|
||||
// design exists to make impossible: a file nothing declares, no host fetches, and every local
|
||||
// test silently passes without. Producing one fails the build rather than shipping it.
|
||||
const sidecar = result.outputFiles.find(
|
||||
(outputFile) => path.extname(outputFile.path).toLowerCase() === ".css",
|
||||
);
|
||||
if (sidecar) {
|
||||
throw new ModuleUiBuildError("MODULE_UI_STYLESHEET_UNDECLARED", artifact.kind);
|
||||
}
|
||||
pendingWrites.push(
|
||||
result.outputFiles.map((outputFile) => ({
|
||||
contents: outputFile.contents,
|
||||
@@ -253,10 +335,21 @@ export async function buildModuleUi(options: BuildModuleUiOptions): Promise<Modu
|
||||
})),
|
||||
);
|
||||
} catch (error) {
|
||||
if (error instanceof ModuleUiBuildError) {
|
||||
throw error;
|
||||
}
|
||||
// esbuild's structured diagnostics are surfaced by the CLI; rethrow a sanitized error so a
|
||||
// programmatic caller never receives raw paths or internals.
|
||||
if (isRecord(error) && Array.isArray(error.errors)) {
|
||||
throw Object.assign(new ModuleUiBuildError("MODULE_UI_BUILD_FAILED", artifact.kind), {
|
||||
// A stylesheet the module authored broke one of this platform's own rules, rather than
|
||||
// failing to compile. Reported with its own code so a caller can tell "your CSS is not
|
||||
// allowed to do that" from "your TSX does not compile".
|
||||
const code = error.errors.some(
|
||||
(diagnostic) => isRecord(diagnostic) && diagnostic.pluginName === STYLESHEET_PLUGIN_NAME,
|
||||
)
|
||||
? "MODULE_UI_STYLESHEET_INVALID"
|
||||
: "MODULE_UI_BUILD_FAILED";
|
||||
throw Object.assign(new ModuleUiBuildError(code, artifact.kind), {
|
||||
diagnostics: error.errors,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -342,10 +342,10 @@ describe("module UI build", () => {
|
||||
});
|
||||
|
||||
it.each([
|
||||
"styles.css",
|
||||
"theme.scss",
|
||||
"layout.less",
|
||||
])("rejects a %s import rather than emitting an undeclared sidecar asset", async (stylesheet) => {
|
||||
"tokens.styl",
|
||||
])("rejects a %s import: only plain CSS has a compilation contract", async (stylesheet) => {
|
||||
const directory = await createModule({
|
||||
ui: "./dist/ui/index.js",
|
||||
files: {
|
||||
@@ -358,47 +358,131 @@ describe("module UI build", () => {
|
||||
await buildModuleUi({ moduleDirectory: directory });
|
||||
expect.unreachable("expected the stylesheet import to be rejected");
|
||||
} catch (error) {
|
||||
expect((error as ModuleUiBuildError).code).toBe("MODULE_UI_BUILD_FAILED");
|
||||
expect((error as ModuleUiBuildError).code).toBe("MODULE_UI_STYLESHEET_INVALID");
|
||||
const diagnostics = (error as { diagnostics?: { text?: string }[] }).diagnostics ?? [];
|
||||
expect(diagnostics.some((entry) => entry.text?.includes("cannot import a stylesheet"))).toBe(
|
||||
true,
|
||||
);
|
||||
expect(diagnostics.some((entry) => entry.text?.includes("plain .css only"))).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("never leaves a stylesheet sidecar next to the artifact", async () => {
|
||||
it("compiles a plain stylesheet into the artifact instead of emitting a sidecar", async () => {
|
||||
const directory = await createModule({
|
||||
ui: "./dist/ui/index.js",
|
||||
files: {
|
||||
"src/ui/index.tsx": 'import "./styles.css";\nexport default {};',
|
||||
"src/ui/styles.css": ".example { color: red; }",
|
||||
"src/ui/index.tsx": `
|
||||
import styles from "./styles.css";
|
||||
export default { id: "example", version: "0.1.0", styles, mount: () => undefined };`,
|
||||
"src/ui/styles.css": ".example { color: var(--ekklesia-text-primary); }",
|
||||
},
|
||||
});
|
||||
|
||||
await expect(buildModuleUi({ moduleDirectory: directory })).rejects.toBeInstanceOf(
|
||||
ModuleUiBuildError,
|
||||
);
|
||||
const result = await buildModuleUi({ moduleDirectory: directory });
|
||||
const artifact = await readFile(result.artifacts[0]?.outputFile ?? "", "utf8");
|
||||
|
||||
// The whole stylesheet travels inside the one declared artifact.
|
||||
expect(artifact).toContain(".example");
|
||||
expect(artifact).toContain("--ekklesia-text-primary");
|
||||
// And nothing was emitted beside it. A sidecar is the exact failure this design prevents: a
|
||||
// file nothing declares, no host fetches, and every local test silently passes without.
|
||||
await expect(
|
||||
readFile(path.join(directory, "dist", "ui", "index.css"), "utf8"),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("enforces the stylesheet boundary for display UI too", async () => {
|
||||
it("resolves a local @import so the compiled stylesheet is self-contained", async () => {
|
||||
const directory = await createModule({
|
||||
ui: "./dist/ui/index.js",
|
||||
files: {
|
||||
"src/ui/index.tsx": `
|
||||
import styles from "./styles.css";
|
||||
export default { id: "example", version: "0.1.0", styles, mount: () => undefined };`,
|
||||
"src/ui/styles.css": '@import "./base.css";\n.example { color: red; }',
|
||||
"src/ui/base.css": ".base { display: grid; }",
|
||||
},
|
||||
});
|
||||
|
||||
const result = await buildModuleUi({ moduleDirectory: directory });
|
||||
const artifact = await readFile(result.artifacts[0]?.outputFile ?? "", "utf8");
|
||||
|
||||
expect(artifact).toContain(".base");
|
||||
expect(artifact).toContain(".example");
|
||||
});
|
||||
|
||||
it("rejects a stylesheet that keeps an unresolved @import, so the artifact stays self-contained", async () => {
|
||||
const directory = await createModule({
|
||||
ui: "./dist/ui/index.js",
|
||||
files: {
|
||||
"src/ui/index.tsx": `
|
||||
import styles from "./styles.css";
|
||||
export default { id: "example", version: "0.1.0", styles, mount: () => undefined };`,
|
||||
"src/ui/styles.css": '@import url("https://fonts.example.invalid/family.css");',
|
||||
},
|
||||
});
|
||||
|
||||
await expect(buildModuleUi({ moduleDirectory: directory })).rejects.toMatchObject({
|
||||
code: "MODULE_UI_STYLESHEET_INVALID",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects a stylesheet that declares a global Ekklesia theme variable", async () => {
|
||||
const directory = await createModule({
|
||||
ui: "./dist/ui/index.js",
|
||||
files: {
|
||||
"src/ui/index.tsx": `
|
||||
import styles from "./styles.css";
|
||||
export default { id: "example", version: "0.1.0", styles, mount: () => undefined };`,
|
||||
// Referencing a token is the contract; *declaring* one would invent a global theme variable
|
||||
// outside the registry a future theme editor enumerates (ADR 0039).
|
||||
"src/ui/styles.css": ":host { --ekklesia-text-primary: hotpink; }",
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
await buildModuleUi({ moduleDirectory: directory });
|
||||
expect.unreachable("expected the stylesheet to be rejected");
|
||||
} catch (error) {
|
||||
expect((error as ModuleUiBuildError).code).toBe("MODULE_UI_STYLESHEET_INVALID");
|
||||
const diagnostics = (error as { diagnostics?: { text?: string }[] }).diagnostics ?? [];
|
||||
expect(diagnostics.some((entry) => entry.text?.includes("never declare one"))).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("accepts a private alias derived from a registered token", async () => {
|
||||
const directory = await createModule({
|
||||
ui: "./dist/ui/index.js",
|
||||
files: {
|
||||
"src/ui/index.tsx": `
|
||||
import styles from "./styles.css";
|
||||
export default { id: "example", version: "0.1.0", styles, mount: () => undefined };`,
|
||||
"src/ui/styles.css":
|
||||
":host { --example-gap: var(--ekklesia-spacing-sm); }\n.example { gap: var(--example-gap); }",
|
||||
},
|
||||
});
|
||||
|
||||
const artifact = await readFile(
|
||||
(await buildModuleUi({ moduleDirectory: directory })).artifacts[0]?.outputFile ?? "",
|
||||
"utf8",
|
||||
);
|
||||
expect(artifact).toContain("--example-gap");
|
||||
});
|
||||
|
||||
it("compiles a display artifact's stylesheet the same way", async () => {
|
||||
const directory = await createModule({
|
||||
display: {
|
||||
artifact: "./dist/display/index.js",
|
||||
permission: "example.display.view",
|
||||
},
|
||||
files: {
|
||||
"src/display/index.tsx": 'import "./styles.css";\nexport default {};',
|
||||
"src/display/index.tsx": `
|
||||
import styles from "./styles.css";
|
||||
export default { id: "example", version: "0.1.0", styles, mount: () => undefined };`,
|
||||
"src/display/styles.css": ".display { position: fixed; }",
|
||||
},
|
||||
});
|
||||
|
||||
await expect(buildModuleUi({ moduleDirectory: directory })).rejects.toMatchObject({
|
||||
code: "MODULE_UI_BUILD_FAILED",
|
||||
kind: "display",
|
||||
});
|
||||
const result = await buildModuleUi({ moduleDirectory: directory });
|
||||
const artifact = await readFile(result.artifacts[0]?.outputFile ?? "", "utf8");
|
||||
|
||||
expect(artifact).toContain(".display");
|
||||
await expect(readFile(path.join(directory, "dist/display/index.css"))).rejects.toThrow();
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user