diff --git a/packages/core/schemas/registry-item.json b/packages/core/schemas/registry-item.json index a2051a5bf2..82a0da3e38 100644 --- a/packages/core/schemas/registry-item.json +++ b/packages/core/schemas/registry-item.json @@ -39,6 +39,10 @@ "type": "string", "format": "uri" }, + "sourceUrl": { + "type": "string", + "format": "uri" + }, "sourcePrompt": { "type": "string", "minLength": 1 diff --git a/packages/core/src/registry/index.ts b/packages/core/src/registry/index.ts index cf47b75a8c..744bf0da65 100644 --- a/packages/core/src/registry/index.ts +++ b/packages/core/src/registry/index.ts @@ -25,3 +25,6 @@ export { isBlockItem, isComponentItem, } from "./types.js"; + +export type { RegistryProvenanceSubject, RegistryProvenanceFinding } from "./provenance.js"; +export { checkProvenanceTags } from "./provenance.js"; diff --git a/packages/core/src/registry/provenance.test.ts b/packages/core/src/registry/provenance.test.ts new file mode 100644 index 0000000000..e303ba48ee --- /dev/null +++ b/packages/core/src/registry/provenance.test.ts @@ -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(); + }); +}); diff --git a/packages/core/src/registry/provenance.ts b/packages/core/src/registry/provenance.ts new file mode 100644 index 0000000000..b6827afce9 --- /dev/null +++ b/packages/core/src/registry/provenance.ts @@ -0,0 +1,32 @@ +import type { RegistryItem } from "./types.js"; + +export type RegistryProvenanceSubject = Pick; + +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.", + }; +} diff --git a/packages/core/src/registry/types.test.ts b/packages/core/src/registry/types.test.ts index 66cc11565d..8fd024083b 100644 --- a/packages/core/src/registry/types.test.ts +++ b/packages/core/src/registry/types.test.ts @@ -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."); }); }); diff --git a/packages/core/src/registry/types.ts b/packages/core/src/registry/types.ts index 94797a9aaa..8c6fbdf63e 100644 --- a/packages/core/src/registry/types.ts +++ b/packages/core/src/registry/types.ts @@ -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. */ diff --git a/packages/lint/src/hyperframeLinter.ts b/packages/lint/src/hyperframeLinter.ts index 1dc88067c6..65e6a8f40f 100644 --- a/packages/lint/src/hyperframeLinter.ts +++ b/packages/lint/src/hyperframeLinter.ts @@ -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( diff --git a/packages/lint/src/rules/composition.test.ts b/packages/lint/src/rules/composition.test.ts index 52f7892d0b..1ddd57e142 100644 --- a/packages/lint/src/rules/composition.test.ts +++ b/packages/lint/src/rules/composition.test.ts @@ -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) => diff --git a/packages/lint/src/rules/composition.ts b/packages/lint/src/rules/composition.ts index f34745c9ee..28cc15c39d 100644 --- a/packages/lint/src/rules/composition.ts +++ b/packages/lint/src/rules/composition.ts @@ -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 { diff --git a/packages/lint/src/rules/testSupport.ts b/packages/lint/src/rules/testSupport.ts new file mode 100644 index 0000000000..04429bc83d --- /dev/null +++ b/packages/lint/src/rules/testSupport.ts @@ -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); +} diff --git a/packages/lint/src/rules/theme.test.ts b/packages/lint/src/rules/theme.test.ts new file mode 100644 index 0000000000..1616a43451 --- /dev/null +++ b/packages/lint/src/rules/theme.test.ts @@ -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 = ` + + + + +
+`; + + 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 = ` + + + + +
+`; + + const findings = await findByCode(compliant, "theme_token_root_redeclare", { + filePath: REGISTRY_BLOCK_PATH, + }); + + expect(findings).toHaveLength(0); + }); + }); + + describe("theme_token_fallback_missing", () => { + const 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 = ` + + + + + +
+ +`; + + const findings = await findByCode(compliant, "theme_token_fallback_missing", { + filePath: REGISTRY_BLOCK_PATH, + }); + + expect(findings).toHaveLength(0); + }); + }); +}); diff --git a/packages/lint/src/rules/theme.ts b/packages/lint/src/rules/theme.ts new file mode 100644 index 0000000000..25c12bd737 --- /dev/null +++ b/packages/lint/src/rules/theme.ts @@ -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(); + const tokens = new Set(); + + 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, ) 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.", + }, + ]; + }, +]; diff --git a/packages/lint/src/rules/variables.test.ts b/packages/lint/src/rules/variables.test.ts new file mode 100644 index 0000000000..3686b369d4 --- /dev/null +++ b/packages/lint/src/rules/variables.test.ts @@ -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 = ` + + +
+ +
+ +`; + + 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 = ` + + +
+

Headline

+ +
+ +`; + + const findings = await findByCode(compliant, "composition_variable_unused", { + filePath: REGISTRY_BLOCK_PATH, + }); + + expect(findings).toHaveLength(0); + }); + }); +}); diff --git a/packages/lint/src/rules/variables.ts b/packages/lint/src/rules/variables.ts new file mode 100644 index 0000000000..f5756b7b9a --- /dev/null +++ b/packages/lint/src/rules/variables.ts @@ -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; + }, +]; diff --git a/packages/lint/src/types.ts b/packages/lint/src/types.ts index 8911566f93..ea8abed1d0 100644 --- a/packages/lint/src/types.ts +++ b/packages/lint/src/types.ts @@ -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.