feat(lint): add theme-token contract and provenance lint rules

Enforce the video-primitive theme-token contract (W2f): registry blocks and
components must not redeclare contract tokens at :root/html/body (they bypass
composition scoping), must supply var() fallbacks, and must consume every
declared composition variable. Adds a provenance check for registry items
whose tags claim an external port with no recorded source.
This commit is contained in:
Miguel Angel Simon Sierra
2026-07-09 11:40:51 -04:00
parent 8e04d01969
commit d7865585e2
15 changed files with 569 additions and 1 deletions
+4
View File
@@ -39,6 +39,10 @@
"type": "string",
"format": "uri"
},
"sourceUrl": {
"type": "string",
"format": "uri"
},
"sourcePrompt": {
"type": "string",
"minLength": 1
+3
View File
@@ -25,3 +25,6 @@ export {
isBlockItem,
isComponentItem,
} from "./types.js";
export type { RegistryProvenanceSubject, RegistryProvenanceFinding } from "./provenance.js";
export { checkProvenanceTags } from "./provenance.js";
@@ -0,0 +1,40 @@
import { describe, expect, it } from "vitest";
import { checkProvenanceTags } from "./provenance.js";
describe("checkProvenanceTags", () => {
it("warns when a -port tag has no recorded source", () => {
const finding = checkProvenanceTags({
tags: ["remocn-port", "data"],
});
expect(finding).toBeDefined();
expect(finding?.severity).toBe("warning");
expect(finding?.message).toContain("remocn-port");
});
it("does not warn when a -port tag has sourceUrl", () => {
const finding = checkProvenanceTags({
tags: ["remocn-port"],
sourceUrl: "https://example.com/source",
});
expect(finding).toBeNull();
});
it("does not warn when a -port tag has sourcePrompt", () => {
const finding = checkProvenanceTags({
tags: ["remocn-port"],
sourcePrompt: "Port the source component faithfully.",
});
expect(finding).toBeNull();
});
it("does not warn when no tag ends in -port", () => {
const finding = checkProvenanceTags({
tags: ["data", "chart"],
});
expect(finding).toBeNull();
});
});
+32
View File
@@ -0,0 +1,32 @@
import type { RegistryItem } from "./types.js";
export type RegistryProvenanceSubject = Pick<RegistryItem, "tags" | "sourceUrl" | "sourcePrompt">;
export type RegistryProvenanceFinding = {
code: "provenance_port_tag_missing_source";
severity: "warning";
message: string;
fixHint: string;
};
function hasText(value: string | undefined): boolean {
return typeof value === "string" && value.trim().length > 0;
}
export function checkProvenanceTags(
item: RegistryProvenanceSubject,
): RegistryProvenanceFinding | null {
const portTags = (item.tags ?? []).filter((tag) => tag.toLowerCase().endsWith("-port"));
if (portTags.length === 0) return null;
if (hasText(item.sourceUrl) || hasText(item.sourcePrompt)) return null;
return {
code: "provenance_port_tag_missing_source",
severity: "warning",
message:
`Registry item tag(s) ${portTags.join(", ")} claim this item was ported from an external source, ` +
"but neither sourceUrl nor sourcePrompt is recorded, so the claim is unverifiable.",
fixHint:
"Add sourceUrl for the external source, add sourcePrompt for prompt-derived provenance, or remove the -port tag.",
};
}
+2
View File
@@ -220,6 +220,7 @@ describe("registry types", () => {
description: "d",
author: "heygen",
authorUrl: "https://example.com/heygen",
sourceUrl: "https://example.com/source",
sourcePrompt: "Create a shader wipe.",
license: "Apache-2.0",
minCliVersion: "0.4.0",
@@ -234,6 +235,7 @@ describe("registry types", () => {
};
expect(item.author).toBe("heygen");
expect(item.authorUrl).toBe("https://example.com/heygen");
expect(item.sourceUrl).toBe("https://example.com/source");
expect(item.sourcePrompt).toBe("Create a shader wipe.");
});
});
+2
View File
@@ -50,6 +50,8 @@ interface RegistryItemBase {
author?: string;
/** URL for the author / creator credit. */
authorUrl?: string;
/** URL for the external source used to create or inspire the item. */
sourceUrl?: string;
/** Original prompt used to create or inspire the item. */
sourcePrompt?: string;
/** SPDX license identifier. */
+4
View File
@@ -10,6 +10,8 @@ import { adapterRules } from "./rules/adapters";
import { textureRules } from "./rules/textures";
import { fontRules } from "./rules/fonts";
import { slideshowRules } from "./rules/slideshow";
import { themeRules } from "./rules/theme";
import { variableRules } from "./rules/variables";
const ALL_RULES = [
...coreRules,
@@ -21,6 +23,8 @@ const ALL_RULES = [
...textureRules,
...fontRules,
...slideshowRules,
...themeRules,
...variableRules,
];
export async function lintHyperframeHtml(
@@ -1,8 +1,17 @@
// fallow-ignore-file code-duplication
import { describe, it, expect } from "vitest";
import { lintHyperframeHtml } from "../hyperframeLinter.js";
import { isRegistrySourceFile } from "./composition.js";
describe("composition rules", () => {
describe("isRegistrySourceFile", () => {
it("matches canonical registry component source HTML files", () => {
expect(
isRegistrySourceFile("/project/registry/components/cursor-trail/cursor-trail.html"),
).toBe(true);
});
});
describe("subcomposition guidance", () => {
it("warns when any HTML composition file is over 300 lines", async () => {
const html = Array.from({ length: 301 }, (_, i) =>
+1 -1
View File
@@ -39,7 +39,7 @@ export function isRegistrySourceFile(filePath?: string): boolean {
if (!filePath) return false;
const normalized = filePath.replace(/\\/g, "/");
return /(?:^|\/)registry\/blocks\/([^/]+)\/\1\.html$/i.test(normalized);
return /(?:^|\/)registry\/(?:blocks|components)\/([^/]+)\/\1\.html$/i.test(normalized);
}
export function isRegistryInstalledFile(rawSource: string): boolean {
+11
View File
@@ -0,0 +1,11 @@
import { lintHyperframeHtml } from "../hyperframeLinter.js";
import type { HyperframeLinterOptions } from "../types.js";
export async function findByCode(
html: string,
code: string,
options: HyperframeLinterOptions = {},
) {
const result = await lintHyperframeHtml(html, options);
return result.findings.filter((f) => f.code === code);
}
+137
View File
@@ -0,0 +1,137 @@
import { describe, expect, it } from "vitest";
import { findByCode } from "./testSupport.js";
const REGISTRY_BLOCK_PATH = "/project/registry/blocks/theme-card/theme-card.html";
describe("theme rules", () => {
describe("theme_token_root_redeclare", () => {
const html = `<!doctype html>
<html>
<head>
<style>
:root, .local { --bg: #050505; }
body { --brand: #ff00aa; }
.card { color: var(--fg, #fff); }
</style>
</head>
<body><div data-composition-id="theme-card"></div></body>
</html>`;
it("errors for contract tokens redeclared on root selectors in registry sources", async () => {
const findings = await findByCode(html, "theme_token_root_redeclare", {
filePath: REGISTRY_BLOCK_PATH,
});
expect(findings).toHaveLength(1);
expect(findings[0]!.severity).toBe("error");
expect(findings[0]!.message).toContain("--bg");
expect(findings[0]!.message).toContain("--brand");
expect(findings[0]!.message).toContain(":root");
expect(findings[0]!.message).toContain("body");
});
it("errors when explicitly opted in without a registry source path", async () => {
const findings = await findByCode(html, "theme_token_root_redeclare", {
enforceThemeTokenContract: true,
});
expect(findings).toHaveLength(1);
});
it("does not run for normal project compositions by default", async () => {
const findings = await findByCode(html, "theme_token_root_redeclare", {
filePath: "/project/index.html",
});
expect(findings).toHaveLength(0);
});
it("does not error when contract tokens are used with fallbacks at point of use", async () => {
const compliant = `<!doctype html>
<html>
<head>
<style>
.card {
background: var(--bg, #050505);
color: var(--fg, #ffffff);
}
</style>
</head>
<body><div data-composition-id="theme-card" class="card"></div></body>
</html>`;
const findings = await findByCode(compliant, "theme_token_root_redeclare", {
filePath: REGISTRY_BLOCK_PATH,
});
expect(findings).toHaveLength(0);
});
});
describe("theme_token_fallback_missing", () => {
const html = `<!doctype html>
<html>
<head>
<style>
.card {
color: var(--fg);
background: var(--bg, #050505);
}
</style>
</head>
<body>
<div data-composition-id="theme-card" style="border-color: var(--border)"></div>
</body>
</html>`;
it("warns for contract token var() calls without fallbacks in registry sources", async () => {
const findings = await findByCode(html, "theme_token_fallback_missing", {
filePath: REGISTRY_BLOCK_PATH,
});
expect(findings).toHaveLength(1);
expect(findings[0]!.severity).toBe("warning");
expect(findings[0]!.message).toContain("--fg");
expect(findings[0]!.message).toContain("--border");
});
it("warns when explicitly opted in without a registry source path", async () => {
const findings = await findByCode(html, "theme_token_fallback_missing", {
enforceThemeTokenContract: true,
});
expect(findings).toHaveLength(1);
});
it("does not run for normal project compositions by default", async () => {
const findings = await findByCode(html, "theme_token_fallback_missing", {
filePath: "/project/index.html",
});
expect(findings).toHaveLength(0);
});
it("does not warn when every contract token var() call has a fallback", async () => {
const compliant = `<!doctype html>
<html>
<head>
<style>
.card {
color: var(--fg, #ffffff);
background: var(--bg, #050505);
}
</style>
</head>
<body>
<div data-composition-id="theme-card" style="border-color: var(--border, #222222)"></div>
</body>
</html>`;
const findings = await findByCode(compliant, "theme_token_fallback_missing", {
filePath: REGISTRY_BLOCK_PATH,
});
expect(findings).toHaveLength(0);
});
});
});
+170
View File
@@ -0,0 +1,170 @@
import type { LintContext, HyperframeLintFinding } from "../context";
import { readJsonAttr } from "../utils";
import { isRegistrySourceFile } from "./composition";
const CONTRACT_TOKENS = [
"--bg",
"--fg",
"--muted",
"--surface",
"--border",
"--brand",
"--accent",
"--font-display",
"--font-body",
"--font-mono",
"--radius",
"--space-1",
"--space-2",
"--space-3",
"--dur-beat",
"--ease-standard",
"--ease-emphasis",
];
const CONTRACT_TOKEN_SET = new Set(CONTRACT_TOKENS);
const ROOT_SELECTORS = new Set([":root", "html", "body"]);
function shouldEnforceThemeTokenContract(ctx: LintContext): boolean {
return (
ctx.options.enforceThemeTokenContract === true || isRegistrySourceFile(ctx.options.filePath)
);
}
function stripCssComments(css: string): string {
return css.replace(/\/\*[\s\S]*?\*\//g, " ");
}
function rootSelectorsFromHeader(header: string): string[] {
const selectors: string[] = [];
for (const selector of header.split(",")) {
const normalized = selector.trim().toLowerCase();
if (ROOT_SELECTORS.has(normalized) && !selectors.includes(normalized)) {
selectors.push(normalized);
}
}
return selectors;
}
function contractDeclarations(block: string): string[] {
const tokens: string[] = [];
const declarationPattern = /(--[A-Za-z0-9-]+)\s*:/g;
let match: RegExpExecArray | null;
while ((match = declarationPattern.exec(block)) !== null) {
const token = match[1] ?? "";
if (CONTRACT_TOKEN_SET.has(token) && !tokens.includes(token)) tokens.push(token);
}
return tokens;
}
type RootRedeclaration = {
selectors: string[];
tokens: string[];
};
function collectRootRedeclarationsFromCss(cssText: string): RootRedeclaration[] {
const redeclarations: RootRedeclaration[] = [];
const css = stripCssComments(cssText);
const ruleHeader = /([^{}]+)\{/g;
let match: RegExpExecArray | null;
while ((match = ruleHeader.exec(css)) !== null) {
const header = (match[1] ?? "").trim();
if (!header || header.startsWith("@")) continue;
const selectors = rootSelectorsFromHeader(header);
if (selectors.length === 0) continue;
const blockEnd = css.indexOf("}", ruleHeader.lastIndex);
if (blockEnd === -1) continue;
const tokens = contractDeclarations(css.slice(ruleHeader.lastIndex, blockEnd));
if (tokens.length > 0) {
redeclarations.push({ selectors, tokens });
}
}
return redeclarations;
}
function collectRootRedeclarations(styles: Array<{ content: string }>): RootRedeclaration {
const selectors = new Set<string>();
const tokens = new Set<string>();
for (const style of styles) {
for (const redeclaration of collectRootRedeclarationsFromCss(style.content)) {
redeclaration.selectors.forEach((selector) => selectors.add(selector));
redeclaration.tokens.forEach((token) => tokens.add(token));
}
}
return { selectors: [...selectors], tokens: [...tokens] };
}
function collectInlineStyles(ctx: LintContext): string[] {
const values: string[] = [];
for (const tag of ctx.tags) {
const style = readJsonAttr(tag.raw, "style");
if (style) values.push(style);
}
return values;
}
function collectVarCallsWithoutFallback(cssTexts: string[]): string[] {
const tokens: string[] = [];
const varPattern = /\bvar\(\s*(--[A-Za-z0-9-]+)\s*([,)])/g;
for (const cssText of cssTexts) {
const css = stripCssComments(cssText);
let match: RegExpExecArray | null;
while ((match = varPattern.exec(css)) !== null) {
const token = match[1] ?? "";
const delimiter = match[2] ?? "";
if (delimiter !== ")" || !CONTRACT_TOKEN_SET.has(token)) continue;
if (!tokens.includes(token)) tokens.push(token);
}
}
return tokens;
}
export const themeRules: Array<(ctx: LintContext) => HyperframeLintFinding[]> = [
// theme_token_root_redeclare
(ctx) => {
if (!shouldEnforceThemeTokenContract(ctx)) return [];
const { selectors, tokens } = collectRootRedeclarations(ctx.styles);
if (tokens.length === 0) return [];
return [
{
code: "theme_token_root_redeclare",
severity: "error",
message:
`Contract theme token(s) ${tokens.join(", ")} are redeclared on ${selectors.join(", ")}. ` +
"The composition scoper passes html/body/:root selectors through unscoped " +
"(packages/core/src/compiler/compositionScoping.ts:115), so these declarations bypass per-composition scoping and leak document-global values.",
selector: selectors.join(", "),
fixHint:
"Declare the token at point of use with var(--token, <fallback>) instead of redeclaring it at the document root; contract tokens are supplied by the host page, not owned by the primitive.",
},
];
},
// theme_token_fallback_missing
(ctx) => {
if (!shouldEnforceThemeTokenContract(ctx)) return [];
const cssTexts = [...ctx.styles.map((style) => style.content), ...collectInlineStyles(ctx)];
const tokens = collectVarCallsWithoutFallback(cssTexts);
if (tokens.length === 0) return [];
return [
{
code: "theme_token_fallback_missing",
severity: "warning",
message: `Contract theme token var() usage is missing fallback value(s): ${tokens.join(", ")}.`,
fixHint:
"Always supply a fallback, e.g. var(--bg, #fff) - primitives must render acceptably even when a host page doesn't define the contract tokens.",
},
];
},
];
+72
View File
@@ -0,0 +1,72 @@
import { describe, expect, it } from "vitest";
import { findByCode } from "./testSupport.js";
const REGISTRY_BLOCK_PATH = "/project/registry/blocks/data-card/data-card.html";
describe("variable rules", () => {
describe("composition_variable_unused", () => {
const html = `<!doctype html>
<html data-composition-variables='[
{"id":"headline","type":"string","label":"Headline","default":"Hello"},
{"id":"accent","type":"color","label":"Accent","default":"#ff00aa"}
]'>
<body>
<div data-composition-id="data-card" style="color: var(--fg, #fff)">
<script>const accent = getVariables().accent;</script>
</div>
</body>
</html>`;
it("warns for declared variables that are not consumed in registry sources", async () => {
const [finding, extraFinding] = await findByCode(html, "composition_variable_unused", {
filePath: REGISTRY_BLOCK_PATH,
});
expect(extraFinding).toBeUndefined();
expect(finding?.severity).toBe("warning");
expect(finding?.message).toContain("headline");
expect(finding?.message).not.toContain("accent");
});
it("warns when explicitly opted in without a registry source path", async () => {
const findings = await findByCode(html, "composition_variable_unused", {
enforceThemeTokenContract: true,
});
expect(findings).toHaveLength(1);
});
it("does not run for normal project compositions by default", async () => {
const findings = await findByCode(html, "composition_variable_unused", {
filePath: "/project/index.html",
});
expect(findings).toHaveLength(0);
});
it("does not warn when every declared variable id appears elsewhere", async () => {
const compliant = `<!doctype html>
<html data-composition-variables='[
{"id":"headline","type":"string","label":"Headline","default":"Hello"},
{"id":"accent","type":"color","label":"Accent","default":"#ff00aa"}
]'>
<body>
<div data-composition-id="data-card">
<h1 data-headline-target="true">Headline</h1>
<script>
const vars = getVariables();
title.textContent = vars.headline;
root.style.setProperty("--local-accent", vars.accent);
</script>
</div>
</body>
</html>`;
const findings = await findByCode(compliant, "composition_variable_unused", {
filePath: REGISTRY_BLOCK_PATH,
});
expect(findings).toHaveLength(0);
});
});
});
+77
View File
@@ -0,0 +1,77 @@
import type { LintContext, HyperframeLintFinding } from "../context";
import { findHtmlTag, readJsonAttr } from "../utils";
import { isRegistrySourceFile } from "./composition";
function shouldEnforceVariableContract(ctx: LintContext): boolean {
return (
ctx.options.enforceThemeTokenContract === true || isRegistrySourceFile(ctx.options.filePath)
);
}
function escapeRegExp(value: string): string {
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function getStringProperty(value: unknown, key: string): string | null {
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
const candidate = Reflect.get(value, key);
return typeof candidate === "string" ? candidate : null;
}
function removeFirst(haystack: string, needle: string): string {
const index = haystack.indexOf(needle);
if (index === -1) return haystack;
return `${haystack.slice(0, index)} ${haystack.slice(index + needle.length)}`;
}
function readDeclaredVariableIds(source: string): { attrValue: string; ids: string[] } | null {
const htmlTag = findHtmlTag(source);
if (!htmlTag) return null;
const attrValue = readJsonAttr(htmlTag.raw, "data-composition-variables");
if (!attrValue) return null;
let parsed: unknown;
try {
parsed = JSON.parse(attrValue);
} catch {
return null;
}
if (!Array.isArray(parsed)) return null;
const ids: string[] = [];
for (const entry of parsed) {
const id = getStringProperty(entry, "id");
if (id && !ids.includes(id)) ids.push(id);
}
return { attrValue, ids };
}
export const variableRules: Array<(ctx: LintContext) => HyperframeLintFinding[]> = [
// composition_variable_unused
(ctx) => {
if (!shouldEnforceVariableContract(ctx)) return [];
const declared = readDeclaredVariableIds(ctx.source);
if (!declared || declared.ids.length === 0) return [];
const sourceWithoutDeclaration = removeFirst(ctx.rawSource, declared.attrValue);
const findings: HyperframeLintFinding[] = [];
for (const id of declared.ids) {
const idPattern = new RegExp(`\\b${escapeRegExp(id)}\\b`);
if (idPattern.test(sourceWithoutDeclaration)) continue;
findings.push({
code: "composition_variable_unused",
severity: "warning",
message:
`Composition variable "${id}" is declared but never consumed outside data-composition-variables. ` +
"This creates metadata/implementation drift: changing the variable has no visible effect.",
fixHint:
"Wire the variable into the script/CSS that should use it, or remove the unused declaration.",
});
}
return findings;
},
];
+5
View File
@@ -31,6 +31,11 @@ export type HyperframeLinterOptions = {
* render time — the font will silently fall back to whatever the OS provides.
*/
distributed?: boolean;
/**
* Enforce the video-primitive theme-token/variable contract outside canonical
* registry source files. This is opt-in for project compositions.
*/
enforceThemeTokenContract?: boolean;
};
// A rule is a function: receives parsed context, returns zero or more findings.