chore: import upstream snapshot with attribution
regression / regression-shards (style-16-prod style-9-prod style-17-prod iframe-render-compat variables-prod mp4-h265-sdr, shard-4) (push) Has been cancelled
regression / regression-shards (style-4-prod style-11-prod style-2-prod animejs-adapter typegpu-adapter parallel-capture-regression, shard-5) (push) Has been cancelled
regression / regression-shards (style-7-prod style-8-prod style-10-prod css-spinner-render-compat webm-transparency mp4-h264-sdr webm-vp9, shard-3) (push) Has been cancelled
regression / regression-shards (sub-composition-video style-18-prod raf-ball-render-compat font-variant-numeric sub-comp-t0 sub-comp-id-selector, shard-7) (push) Has been cancelled
Windows render verification / Detect changes (push) Has been cancelled
Windows render verification / Preflight (lint + format) (push) Has been cancelled
Windows render verification / Render on windows-latest (push) Has been cancelled
Windows render verification / Tests on windows-latest (push) Has been cancelled
CI / Detect changes (push) Has been cancelled
CI / Build (push) Has been cancelled
CI / Lint (push) Has been cancelled
CI / Fallow audit (push) Has been cancelled
CI / Format (push) Has been cancelled
CI / Typecheck (push) Has been cancelled
CI / Test (push) Has been cancelled
CI / Producer: integration tests (push) Has been cancelled
CI / Producer: unit tests (push) Has been cancelled
CI / File size check (push) Has been cancelled
CI / Test: skills (push) Has been cancelled
CI / Skills: manifest in sync (push) Has been cancelled
CI / CLI: npx shim (macos-latest) (push) Has been cancelled
CI / CLI: npx shim (ubuntu-latest) (push) Has been cancelled
CI / CLI: npx shim (windows-latest) (push) Has been cancelled
CI / SDK: unit + contract + smoke (push) Has been cancelled
CI / Test: runtime contract (push) Has been cancelled
CI / Studio: load smoke (push) Has been cancelled
CI / Smoke: global install (push) Has been cancelled
CI / CLI smoke (required) (push) Has been cancelled
CI / Semantic PR title (push) Has been cancelled
Player perf / Detect changes (push) Has been cancelled
Player perf / Preflight (lint + format) (push) Has been cancelled
Player perf / player-perf (push) Has been cancelled
Player perf / Perf: drift (push) Has been cancelled
Player perf / Perf: fps (push) Has been cancelled
Player perf / Perf: parity (push) Has been cancelled
Player perf / Perf: scrub (push) Has been cancelled
Player perf / Perf: load (push) Has been cancelled
preview-regression / Detect changes (push) Has been cancelled
preview-regression / Preflight (lint + format) (push) Has been cancelled
preview-regression / Preview parity (push) Has been cancelled
preview-regression / preview-regression (push) Has been cancelled
regression / regression (push) Has been cancelled
regression / Detect changes (push) Has been cancelled
regression / Preflight (lint + format) (push) Has been cancelled
regression / regression-shards (hdr-regression style-5-prod style-3-prod mov-prores, shard-1) (push) Has been cancelled
regression / regression-shards (overlay-montage-prod style-12-prod chat missing-host-comp-id png-sequence portrait-edge-bleed, shard-6) (push) Has been cancelled
regression / regression-shards (style-13-prod style-6-prod vignelli-stacking gsap-letters-render-compat audio-mux-parity, shard-8) (push) Has been cancelled
regression / regression-shards (style-15-prod hdr-hlg-regression style-1-prod many-cuts vfr-screen-recording render-symlinked-assets, shard-2) (push) Has been cancelled
CodeQL / Analyze (actions) (push) Has been cancelled
CodeQL / Analyze (javascript-typescript) (push) Has been cancelled
CodeQL / Analyze (python) (push) Has been cancelled
Docs / Validate docs (push) Has been cancelled
Sync skills to ClawHub / Publish changed skills (push) Has been cancelled

This commit is contained in:
wehub-resource-sync
2026-07-13 12:58:35 +08:00
commit 85453da49f
4031 changed files with 710987 additions and 0 deletions
@@ -0,0 +1,55 @@
// assets.mjs — stage frame-named capture assets into assets/.
// Shared by stage-assets.mjs (Step 4 close, BEFORE the frame workers run) and
// assemble-index.mjs (Step 5, idempotent backstop). Only assets a frame names
// in `asset_candidates` are staged; unnamed assets never reach the project.
// asset_candidates value form: "assets/<basename> — desc; assets/… — …".
import { copyFileSync, existsSync, mkdirSync } from "node:fs";
import { basename, join } from "node:path";
export function basenamesFromCandidates(value) {
if (typeof value !== "string") return [];
return value
.split(";")
.map((seg) => seg.split(/\s+[—–-]\s+/)[0].trim()) // strip the " — description"
.filter(Boolean)
.map((p) => basename(p.replace(/^assets\//, "")));
}
// Copy each frame's asset_candidates from capture/{assets,assets/videos,
// screenshots} into assets/. Already-staged files are left as is (first-wins),
// so calling this twice is safe. Returns { staged, wanted, anomalies }.
export function stageAssets({ hyperframesDir, frames }) {
const wanted = new Set();
for (const f of frames) {
for (const b of basenamesFromCandidates(f.extra?.asset_candidates)) wanted.add(b);
}
const captureDirs = [
join(hyperframesDir, "capture/assets"),
join(hyperframesDir, "capture/assets/videos"), // videos download into a subdir
join(hyperframesDir, "capture/screenshots"),
];
const assetsDir = join(hyperframesDir, "assets");
const anomalies = [];
let staged = 0;
if (wanted.size > 0) {
mkdirSync(assetsDir, { recursive: true });
for (const b of wanted) {
const dest = join(assetsDir, b);
if (existsSync(dest)) {
staged++;
continue;
} // first-wins / already staged
const src = captureDirs.map((d) => join(d, b)).find((p) => existsSync(p));
if (src) {
copyFileSync(src, dest);
staged++;
} else {
anomalies.push(
`asset "${b}" named by a frame but not found under capture/ — frame will 404 it`,
);
}
}
}
return { staged, wanted, anomalies };
}
@@ -0,0 +1,45 @@
// dimensions.mjs — canvas size + caption-band geometry for the video
// pipeline. Single source of truth = the STORYBOARD frontmatter `format` global
// ("1920x1080" / "1080x1920" / "1080x1080", or a named orientation). Every
// script and the index assembler reads the size from here; none hardcodes it.
// Named orientation presets. Square/portrait are 1080-based so they share the
// long-edge pixel budget with landscape (same render-cost ballpark).
export const ORIENTATION_PRESETS = {
landscape: { width: 1920, height: 1080 }, // 16:9 — default
portrait: { width: 1080, height: 1920 }, // 9:16 — reels / shorts / TikTok
square: { width: 1080, height: 1080 }, // 1:1 — feed
};
export const DEFAULT_DIMENSIONS = ORIENTATION_PRESETS.landscape;
function sane(w, h) {
return Number.isFinite(w) && Number.isFinite(h) && w >= 240 && h >= 240 && w <= 8192 && h <= 8192;
}
// Parse a STORYBOARD `format` global into { width, height, source }. Accepts
// "WxH" (e.g. "1920x1080"; `x` or `×`, any inner spacing) or a named orientation;
// falls back to landscape so a storyboard with a missing/garbled format still
// renders (no behavior change vs the old landscape lock).
export function parseFormat(format) {
const s = typeof format === "string" ? format.trim().toLowerCase() : "";
if (ORIENTATION_PRESETS[s]) return { ...ORIENTATION_PRESETS[s], source: `orientation=${s}` };
const m = s.match(/^(\d+)\s*[x×]\s*(\d+)$/);
if (m) {
const w = parseInt(m[1] ?? "", 10);
const h = parseInt(m[2] ?? "", 10);
if (sane(w, h)) return { width: w, height: h, source: "format" };
}
return { ...DEFAULT_DIMENSIONS, source: "default(landscape)" };
}
// Caption band geometry, derived from canvas height: the bottom ~16.67% (180px
// at h=1080). Frame content must end `safetyPx` above the band top. Holds even
// when captions are disabled (bottom-edge consistency).
export const CAPTION_BAND_FRACTION = 0.1667;
export function captionBand(height, safetyPx = 20) {
const h = Number.isFinite(height) ? height : DEFAULT_DIMENSIONS.height;
const bandHeight = Math.round(h * CAPTION_BAND_FRACTION);
const bandTopY = h - bandHeight; // foreground must end at/above this y
return { bandHeight, bandTopY, foregroundMaxY: bandTopY - safetyPx };
}
@@ -0,0 +1,36 @@
// pad-frame-duration.mjs — keeps a frame's own #root/clip data-duration in
// sync with the padded index.html wrapper duration transitions.mjs computes.
//
// The frame's OWN internal file declares its #root/clip data-duration to the
// STORYBOARD's content-only length (frame-worker.md: duration is "fixed
// upstream"). When an outgoing transition pads the index.html WRAPPER's
// data-duration to cover the transition tail, the frame's own internal
// duration is left short — the render engine clip-gates the sub-composition's
// visible content at that shorter value, so content vanishes abruptly at
// content-end instead of fading gracefully through the wrapper's extended
// fade-out tween. Pad the frame's own file to match so both durations agree.
import { readFileSync, writeFileSync } from "node:fs";
import { resolve } from "node:path";
export function padFrameInternalDuration(hyperframesDir, frameSrc, frameId, newDuration) {
const framePath = resolve(hyperframesDir, frameSrc);
let html;
try {
html = readFileSync(framePath, "utf8");
} catch (err) {
if (err?.code === "ENOENT") return;
throw err;
}
const tagRe = /<[a-z][\w:-]*\s[^<>]*?>/gi;
let m;
while ((m = tagRe.exec(html)) !== null) {
const tag = m[0];
if (!tag.includes(`data-composition-id="${frameId}"`)) continue;
if (!/data-duration="[\d.]+"/.test(tag)) continue;
const newTag = tag.replace(/data-duration="[\d.]+"/, `data-duration="${newDuration}"`);
if (newTag === tag) return;
writeFileSync(framePath, html.slice(0, m.index) + newTag + html.slice(m.index + tag.length));
return;
}
}
@@ -0,0 +1,249 @@
// storyboard.mjs — vendored lenient parser for STORYBOARD.md.
//
// Faithful plain-JS port of @hyperframes/core/storyboard
// (packages/core/src/storyboard/parseStoryboard.ts). Vendored because skills
// ship standalone: installed via `npx skills add`, a skill's scripts can't reach
// the monorepo's core package, and the core export points at .ts source that
// `node` (which runs these scripts) can't load. CANONICAL contract = the core
// parser + skills/hyperframes-core/references/storyboard-format.md; keep this in
// lockstep. Behavior: never throws, accepts freeform narrative, recognizes
// Frame/Beat/Scene headings at H2/H3, preserves unknown keys verbatim under
// `extra` (keys lowercased). Pure node — no deps.
export const FRAME_STATUSES = ["outline", "built", "animated"];
export const DEFAULT_FRAME_STATUS = "outline";
// Detection-only frame heading (ends at the keyword); ReDoS-hardened — keep as-is.
const FRAME_HEADING_RE = /^(#{2,3})[ \t]+(?:frame|beat|scene)\b/i;
const FRAME_TITLE_SEP_RE = /^[\s.:—-]+/;
const HEADING_LEVEL_RE = /^(#{1,6})\s+/;
const META_RE = /^\s*[-*]\s+([A-Za-z_][\w-]*)\s*:\s*(.+?)\s*$/;
const LEADING_INT_RE = /^(\d+)/;
const DURATION_NUM_RE = /(\d+(?:\.\d+)?)/;
const TRANSITION_KEYS = new Set(["transition_in", "transitionin", "transition"]);
const SCENE_KEYS = new Set(["scene", "description", "summary", "caption"]);
export const VOICEOVER_ALIASES = ["voiceover", "vo", "voice_over", "narration"];
const VOICEOVER_KEYS = new Set(VOICEOVER_ALIASES);
export function parseStoryboard(source) {
const warnings = [];
const { globals, bodyStartLine, body } = parseFrontmatter(source, warnings);
const frames = parseFrames(body, bodyStartLine, warnings);
return { globals, frames, warnings };
}
function emptyGlobals() {
return { extra: {} };
}
function isFrameStatus(value) {
return FRAME_STATUSES.includes(value);
}
// ── Frontmatter ─────────────────────────────────────────────────────────────
function findFrontmatterRange(lines, warnings) {
let start = 0;
while (start < lines.length && (lines[start] ?? "").trim() === "") start++;
if ((lines[start] ?? "").trim() !== "---") return null;
for (let i = start + 1; i < lines.length; i++) {
if ((lines[i] ?? "").trim() === "---") return { start, end: i };
}
warnings.push({
message: "Frontmatter opening '---' has no closing '---'; treating whole file as body.",
line: start + 1,
});
return null;
}
function parseFrontmatterEntries(lines, start, end, warnings) {
const globals = emptyGlobals();
for (let i = start + 1; i < end; i++) {
const raw = lines[i] ?? "";
if (raw.trim() === "") continue;
const colon = raw.indexOf(":");
if (colon === -1) {
warnings.push({
message: `Ignored non key:value frontmatter line: "${raw.trim()}"`,
line: i + 1,
});
continue;
}
const key = raw.slice(0, colon).trim().toLowerCase();
assignGlobal(globals, key, stripQuotes(raw.slice(colon + 1).trim()));
}
return globals;
}
function parseFrontmatter(source, warnings) {
const lines = source.split(/\r?\n/);
const range = findFrontmatterRange(lines, warnings);
if (!range) return { globals: emptyGlobals(), bodyStartLine: 1, body: source };
const globals = parseFrontmatterEntries(lines, range.start, range.end, warnings);
const body = lines.slice(range.end + 1).join("\n");
return { globals, bodyStartLine: range.end + 2, body };
}
function assignGlobal(globals, key, value) {
switch (key) {
case "format":
globals.format = value;
break;
case "message":
globals.message = value;
break;
case "arc":
globals.arc = value;
break;
case "audience":
globals.audience = value;
break;
default:
globals.extra[key] = value;
}
}
// ── Frames ──────────────────────────────────────────────────────────────────
function openFrameSection(line, headingLine) {
const match = FRAME_HEADING_RE.exec(line);
if (!match) return null;
const headingText = line.slice(match[0].length).replace(FRAME_TITLE_SEP_RE, "").trim();
return { headingText, headingLine, level: (match[1] ?? "##").length, lines: [] };
}
function endsFrameSection(line, current) {
if (!current) return false;
const heading = HEADING_LEVEL_RE.exec(line);
return heading !== null && (heading[1] ?? "").length <= current.level;
}
function parseFrames(body, bodyStartLine, warnings) {
const lines = body.split(/\r?\n/);
const sections = [];
let current = null;
for (let i = 0; i < lines.length; i++) {
const line = lines[i] ?? "";
const opened = openFrameSection(line, bodyStartLine + i);
if (opened) {
sections.push(opened);
current = opened;
} else if (endsFrameSection(line, current)) {
current = null;
} else if (current) {
current.lines.push(line);
}
}
return sections.map((section, idx) => buildFrame(section, idx + 1, warnings));
}
function buildFrame(section, index, warnings) {
const frame = { index, status: DEFAULT_FRAME_STATUS, narrative: "", extra: {} };
const { number, title } = parseHeading(section.headingText);
if (number !== undefined) frame.number = number;
if (title) frame.title = title;
const narrativeLines = [];
for (const line of section.lines) {
const meta = META_RE.exec(line);
if (meta) {
applyMeta(
frame,
(meta[1] ?? "").toLowerCase(),
(meta[2] ?? "").trim(),
section.headingLine,
warnings,
);
} else {
narrativeLines.push(line);
}
}
frame.narrative = narrativeLines.join("\n").trim();
return frame;
}
function parseHeading(text) {
if (!text) return {};
const intMatch = LEADING_INT_RE.exec(text);
if (!intMatch) return { title: text };
const number = Number.parseInt(intMatch[1] ?? "", 10);
const rest = text
.slice((intMatch[0] ?? "").length)
.replace(/^[\s.:—-]+/, "")
.trim();
return { number, title: rest || undefined };
}
// Dispatch a recognized metadata key to its field, else stash under `extra`.
// Mirrors core's META_SETTERS map exactly (direct keys + alias sets).
function applyMeta(frame, key, value, headingLine, warnings) {
switch (key) {
case "duration":
applyDuration(frame, value, headingLine, warnings);
return;
case "status":
applyStatus(frame, value, headingLine, warnings);
return;
case "poster":
applyPoster(frame, value);
return;
case "src":
frame.src = value;
return;
}
if (TRANSITION_KEYS.has(key)) {
frame.transitionIn = value;
return;
}
if (SCENE_KEYS.has(key)) {
frame.scene = value;
return;
}
if (VOICEOVER_KEYS.has(key)) {
frame.voiceover = stripQuotes(value);
return;
}
frame.extra[key] = value;
}
function applyPoster(frame, value) {
const num = DURATION_NUM_RE.exec(value);
if (num) frame.poster = Number.parseFloat(num[1] ?? "");
}
function applyDuration(frame, value, headingLine, warnings) {
frame.duration = value;
const num = DURATION_NUM_RE.exec(value);
if (num) {
frame.durationSeconds = Number.parseFloat(num[1] ?? "");
return;
}
warnings.push({
message: `Frame ${frame.index}: could not parse duration "${value}".`,
line: headingLine,
frameIndex: frame.index,
});
}
function applyStatus(frame, value, headingLine, warnings) {
const normalized = value.toLowerCase();
if (isFrameStatus(normalized)) {
frame.status = normalized;
return;
}
frame.extra.status = value;
warnings.push({
message: `Frame ${frame.index}: unknown status "${value}"; defaulting to "${DEFAULT_FRAME_STATUS}".`,
line: headingLine,
frameIndex: frame.index,
});
}
function stripQuotes(value) {
if (value.length >= 2) {
const first = value[0];
const last = value[value.length - 1];
if ((first === '"' && last === '"') || (first === "'" && last === "'")) {
return value.slice(1, -1);
}
}
return value;
}
@@ -0,0 +1,219 @@
// tokens.mjs — shared brand-token parsing + semantic role mapping for frame.md /
// FRAME.md. Used by build-frame.mjs (remix a preset onto brand tokens) and
// captions.mjs (derive caption colors from frame.md). One mapping → frames and
// captions stay consistent. Pure node.
// Collect `key: value` pairs under the top-level `colors:` block (until dedent).
export function parseColors(md) {
const out = [];
let inBlock = false;
for (const line of md.split(/\r?\n/)) {
if (/^colors:\s*$/.test(line)) {
inBlock = true;
continue;
}
if (!inBlock) continue;
if (/^\S/.test(line)) break; // dedent to a top-level key → end of block
const m = line.match(
/^\s+([\w-]+):\s*(?:"([^"]+)"|'([^']+)'|(#[0-9a-fA-F]{3,8}|rgba?\([^)]*\)|[^#\s][^#\n]*?))\s*(?:#.*)?$/,
);
if (m) out.push([m[1], (m[2] ?? m[3] ?? m[4]).trim()]);
}
return out;
}
// relative luminance of a #rrggbb (null for non-hex like rgba()).
export function lum(v) {
const m = /^#?([0-9a-fA-F]{6})$/.exec(String(v).trim());
if (!m) return null;
const n = parseInt(m[1], 16);
return 0.2126 * ((n >> 16) & 255) + 0.7152 * ((n >> 8) & 255) + 0.0722 * (n & 255);
}
// chroma (maxmin channel) of a #rrggbb — a cheap "how colorful" proxy; 1 for non-hex.
export function chroma(v) {
const m = /^#?([0-9a-fA-F]{6})$/.exec(String(v).trim());
if (!m) return -1;
const n = parseInt(m[1], 16);
const r = (n >> 16) & 255,
g = (n >> 8) & 255,
b = n & 255;
return Math.max(r, g, b) - Math.min(r, g, b);
}
// Browser user-agent default colors for links / visited links. These leak into a
// capture from any UNSTYLED <a> and are NOT brand colors — but being pure & saturated
// they beat a real accent on chroma alone. Never let one become the accent.
export const UA_DEFAULT_COLORS = new Set(
["#0000EE", "#0000FF", "#0000CC", "#1A0DAB", "#551A8B", "#EE0000"].map((c) => c.toUpperCase()),
);
// Semantic STATUS roles (green "positive", red "negative"/"error", amber "warning" …). Their HUE
// carries the meaning, so they are never a brand ACCENT — a status red is frequently the most
// chromatic color in a palette (e.g. #dc2626 chroma 182 beats a deep-blue accent #1E40AF chroma
// 145) and would otherwise win a pure chroma ranking, painting captions/highlights the error red.
// build-frame.mjs uses this same key set to protect status colors during the preset→brand remix.
export const STATUS_ROLE_KEY =
/(?:^|[-_])(?:positive|negative|success|error|warning|danger|good|bad|up|down|info|neutral|alert|caution|critical)(?:[-_]|$)/i;
// Pick the brand ACCENT — never by raw chroma alone, never a UA-default link color.
// Priority:
// 1) with capture colorStats → the colorful color that RECURS across the UI. The brand
// accent shows up in MANY roles (link text + icon + button + badge), whereas a one-off
// CTA fill appears in just one. So rank chromatic (chroma>40) candidates by role
// diversity first, then total prevalence, then interactive use, then chroma. This keeps
// a pervasive brand color (e.g. an indigo used everywhere) ahead of a single bright
// button fill (e.g. a lime used once) — the old "top interactiveBg" rule picked the
// latter. Requiring interactiveBg>0 is dropped so a text/icon-only accent can still win.
// 2) no stats → most chromatic color AFTER removing UA defaults + `exclude`.
// A stray default link color (e.g. #0000EE) can win under neither path.
export function pickAccent(stats, colors, exclude = []) {
const ban = new Set([...exclude, ...UA_DEFAULT_COLORS].map((c) => String(c).toUpperCase()));
const ok = (h) => /^#[0-9a-fA-F]{6}$/.test(String(h)) && !ban.has(String(h).toUpperCase());
// Prominence rank from the (frequency-ordered) `colors` palette: index 0 = most used.
// A saturated color sitting at the TAIL is almost always a one-off (a single CTA fill),
// not the brand accent — capture colorStats counts are too sparse to tell these apart
// (e.g. Linear's indigo and a lime CTA both register count≈1), but palette ORDER does.
const rank = new Map((colors ?? []).map((h, i) => [String(h).toUpperCase(), i]));
const prom = (h) => (rank.has(String(h).toUpperCase()) ? rank.get(String(h).toUpperCase()) : 1e9);
if (Array.isArray(stats) && stats.length) {
const roles = (s) =>
((s.interactiveBg || 0) > 0 ? 1 : 0) +
((s.textCount || 0) > 0 ? 1 : 0) +
((s.bgCount || 0) > 0 ? 1 : 0);
const a = stats
.filter((s) => ok(s?.hex) && chroma(s.hex) > 40)
.sort(
(x, y) =>
roles(y) - roles(x) || // used in MORE roles (link+icon+button) = the brand accent
prom(x.hex) - prom(y.hex) || // earlier in the palette = more prominent
(y.count || 0) - (x.count || 0) ||
(y.interactiveBg || 0) - (x.interactiveBg || 0) ||
chroma(y.hex) - chroma(x.hex),
);
if (a.length) return a[0].hex;
}
const c = (colors ?? [])
.map(String)
.filter(ok)
.sort((x, y) => chroma(y) - chroma(x));
return c[0];
}
// Derive brand roles from rich capture colorStats (areaBg / interactiveBg / textCount /
// maxArea) — by semantic FUNCTION, not luminance/chroma proxies. Returns null when stats
// are unusable, so the caller can fall back. canvas = the color painting the most real
// background area (the page ground, dark or light); ink = the dominant text color that
// actually contrasts with the canvas; accent via pickAccent.
export function brandRolesFromStats(stats, colorsInOrder) {
if (!Array.isArray(stats) || !stats.length) return null;
const v = stats.filter((s) => /^#[0-9a-fA-F]{6}$/.test(s?.hex || ""));
if (!v.length) return null;
const canvas = [...v].sort(
(a, b) =>
(b.areaBg || 0) - (a.areaBg || 0) ||
(b.maxArea || 0) - (a.maxArea || 0) ||
(b.bgCount || 0) - (a.bgCount || 0),
)[0]?.hex;
// pass the frequency-ordered palette (tokens.colors) so pickAccent can use palette
// PROMINENCE — colorStats counts alone are too sparse to rank rare accents.
const accent = pickAccent(v, colorsInOrder ?? v.map((s) => s.hex), [canvas]);
if (!canvas || !accent) return null;
const cl = lum(canvas) ?? 0;
const ink =
[...v]
.filter((s) => s.hex !== canvas && s.hex !== accent)
.sort((a, b) => (b.textCount || 0) - (a.textCount || 0))
.find((s) => Math.abs((lum(s.hex) ?? 0) - cl) > 64)?.hex ??
(cl > 128 ? "#000000" : "#FFFFFF");
const accent2 =
v
.filter(
(s) =>
![canvas, ink, accent].includes(s.hex) &&
(s.interactiveBg || 0) > 0 &&
chroma(s.hex) > 40 &&
!UA_DEFAULT_COLORS.has(s.hex.toUpperCase()),
)
.sort((a, b) => (b.interactiveBg || 0) - (a.interactiveBg || 0))[0]?.hex ?? accent;
return { ink, canvas, accent, accent2 };
}
// Map a list of [key, value] colors to semantic roles. ink = a dark/ink-named
// color (else darkest); canvas = a paper/cream/white-named color (else lightest);
// accents = whatever's left, ranked by chroma (the loudest color is almost always
// the brand accent) — UA-default link colors AND semantic status colors (positive/
// negative/error…) excluded so neither a stray <a> color nor a status red ever wins.
// For an unkeyed brand list, pass synthetic keys — name matching simply no-ops and it
// falls back to luminance/chroma, which is what we want. NOTE: when capture colorStats
// exist, prefer brandRolesFromStats() — it picks by function, not these proxies.
export function semanticColors(colors) {
if (!colors.length) return {};
const named = (re) => colors.find(([k]) => re.test(k));
const hexes = colors.filter(([, v]) => lum(v) != null);
const byLum = [...hexes].sort((a, b) => (lum(a[1]) ?? 1e9) - (lum(b[1]) ?? 1e9));
const pick = (m, fallback) => (m ? m[1] : fallback ? fallback[1] : undefined);
// "ink" must be a whole word-segment so "soft-pink"/"pink" don't match it.
const ink = pick(
named(/(?:^|[-_])ink(?:[-_]|$)|black|charcoal|^text(?:-dark)?$|outline|noir/i),
byLum[0] ?? colors[0],
);
const canvas = pick(
named(/cream|paper|canvas|white|bg|ground|surface|base|sand|parchment|off-?white|bone/i),
byLum[byLum.length - 1] ?? colors[colors.length - 1],
);
const accents = colors
.filter(
([k, v]) =>
v !== ink &&
v !== canvas &&
!UA_DEFAULT_COLORS.has(String(v).toUpperCase()) &&
!STATUS_ROLE_KEY.test(k), // a status red/green carries meaning by hue — never an accent
)
.sort((a, b) => chroma(b[1]) - chroma(a[1]))
.map(([, v]) => v);
return { ink, canvas, accent: accents[0] ?? ink, accent2: accents[1] ?? accents[0] ?? ink };
}
// Collect role→fontFamily under the top-level `typography:` block; pick a display
// + body family from the usual role names. Returns quoted families (or null).
export function parseFonts(md) {
const roles = {};
let inBlock = false;
for (const line of md.split(/\r?\n/)) {
if (/^typography:\s*$/.test(line)) {
inBlock = true;
continue;
}
if (!inBlock) continue;
if (/^\S/.test(line)) break;
const m = line.match(/^\s+([\w-]+):\s*\{[^}]*fontFamily:\s*"([^"]+)"/);
if (m) roles[m[1]] = m[2];
}
const q = (s) => (s ? `"${s}"` : null);
const body = roles.body ?? roles.subtitle ?? Object.values(roles)[0];
const display =
roles.display ??
roles.headline ??
roles["card-headline"] ??
roles["section-headline"] ??
roles["quote-display"] ??
roles.h1 ??
roles.h2 ??
roles.title ??
roles.hero ??
body;
// the monospace / chrome family (code, tags, ticks, page numbers) — so the remix can
// route a captured brand mono (Berkeley Mono, JetBrains Mono…) onto this role instead
// of the reading body. null when the preset has no distinct mono role.
const mono =
roles.mono ??
roles["mono-tag"] ??
roles["mono-chrome"] ??
roles["mono-tick"] ??
roles.code ??
roles.data ??
roles.pagenum ??
null;
return { display: q(display), body: q(body), mono: q(mono) };
}
@@ -0,0 +1,38 @@
// transition-registry.mjs — loader for this skill's vendored transition registry
// (./transitions.json). The registry is the curated Tier-B subset (transform /
// opacity / filter on the two frame clip wrappers `#el-<id>`, no overlay DOM) +
// each type's GSAP template. Vendored into the skill so it ships standalone; the
// recipes originate from the shared catalog skills/hyperframes-animation/
// transitions/ (css-*.md) — keep them in step if those shared recipes change.
import { readFileSync } from "node:fs";
import { resolve, dirname } from "node:path";
import { fileURLToPath } from "node:url";
const here = dirname(fileURLToPath(import.meta.url));
export const DEFAULT_REGISTRY_PATH = resolve(here, "./transitions.json");
let _cache = null;
export function loadTransitionRegistry(registryPath = DEFAULT_REGISTRY_PATH) {
if (_cache && _cache.path === registryPath) return _cache.data;
let data;
try {
data = JSON.parse(readFileSync(registryPath, "utf8"));
} catch (e) {
throw new Error(`transition registry not loadable at ${registryPath}: ${e.message}`);
}
if (!Array.isArray(data.transitions) || data.transitions.length === 0) {
throw new Error(`transition registry ${registryPath} has no transitions[]`);
}
_cache = { path: registryPath, data };
return data;
}
// Convenience: a Map name -> transition record.
export function transitionsByName(registryPath = DEFAULT_REGISTRY_PATH) {
const data = loadTransitionRegistry(registryPath);
const map = new Map();
for (const t of data.transitions) map.set(t.name, t);
return map;
}
@@ -0,0 +1,71 @@
{
"_comment": "Vendored transition registry for the product-launch workflow — the curated Tier-B subset (transform/opacity/filter on the two frame clip wrappers #el-<id>, no overlay DOM, no per-frame cooperation). Each type carries its GSAP template; the transitions.mjs injector stamps it onto window.__timelines[\"main\"]. Recipes originate from the shared catalog skills/hyperframes-animation/transitions/ (css-*.md) — keep in step if those change. Token placeholders the injector substitutes: __OLD__ (#el-<from>), __NEW__ (#el-<to>), __T__ (overlap-start s), __DUR__ (this boundary's duration), __DX__/__DXIN__ (horizontal travel + incoming offset), __DY__/__DYIN__ (vertical).",
"transitions": [
{
"name": "crossfade",
"energy": "any",
"default_duration_s": 0.5,
"directions": [],
"source": "css-dissolve.md",
"gsap_template": [
"tl.to(__OLD__, { opacity: 0, duration: __DUR__, ease: \"power2.inOut\" }, __T__);",
"tl.fromTo(__NEW__, { opacity: 0 }, { opacity: 1, duration: __DUR__, ease: \"power2.inOut\" }, __T__);"
]
},
{
"name": "blur-crossfade",
"energy": "calm",
"default_duration_s": 0.6,
"directions": [],
"source": "css-dissolve.md",
"note": "Default when the two frames' #root backgrounds differ a lot — the blur masks the background-color clash a plain crossfade would expose.",
"gsap_template": [
"tl.to(__OLD__, { filter: \"blur(10px)\", scale: 1.03, opacity: 0, duration: __DUR__, ease: \"power2.inOut\" }, __T__);",
"tl.fromTo(__NEW__, { filter: \"blur(10px)\", scale: 0.97, opacity: 0 }, { filter: \"blur(0px)\", scale: 1, opacity: 1, duration: __DUR__, ease: \"power2.inOut\" }, __T__);"
]
},
{
"name": "push-slide",
"energy": "medium",
"default_duration_s": 0.5,
"directions": ["LEFT", "RIGHT", "UP", "DOWN"],
"default_direction": "LEFT",
"source": "css-push.md",
"note": "Directional. The injector picks __DX__/__DY__ from the direction and emits the horizontal OR vertical pair (not both).",
"gsap_template_horizontal": [
"tl.to(__OLD__, { x: __DX__, duration: __DUR__, ease: \"power3.inOut\" }, __T__);",
"tl.fromTo(__NEW__, { x: __DXIN__, opacity: 1 }, { x: 0, duration: __DUR__, ease: \"power3.inOut\" }, __T__);"
],
"gsap_template_vertical": [
"tl.to(__OLD__, { y: __DY__, duration: __DUR__, ease: \"power3.inOut\" }, __T__);",
"tl.fromTo(__NEW__, { y: __DYIN__, opacity: 1 }, { y: 0, duration: __DUR__, ease: \"power3.inOut\" }, __T__);"
]
},
{
"name": "zoom-through",
"energy": "high",
"default_duration_s": 0.4,
"directions": [],
"source": "css-scale.md",
"gsap_template": [
"tl.to(__OLD__, { scale: 2.5, opacity: 0, filter: \"blur(8px)\", duration: __DUR__, ease: \"power3.in\" }, __T__);",
"tl.fromTo(__NEW__, { scale: 0.5, opacity: 0, filter: \"blur(8px)\" }, { scale: 1, opacity: 1, filter: \"blur(0px)\", duration: __DUR__, ease: \"power3.out\" }, __T__);"
]
},
{
"name": "squeeze",
"energy": "medium",
"default_duration_s": 0.4,
"directions": [],
"source": "css-push.md",
"note": "Old compresses to a vertical line on the left edge; new expands from the right edge. Incoming starts off (scaleX 0) so its higher-track stacking is harmless.",
"gsap_template": [
"tl.to(__OLD__, { scaleX: 0, transformOrigin: \"left center\", duration: __DUR__, ease: \"power3.inOut\" }, __T__);",
"tl.fromTo(__NEW__, { scaleX: 0, transformOrigin: \"right center\", opacity: 1 }, { scaleX: 1, transformOrigin: \"right center\", duration: __DUR__, ease: \"power3.inOut\" }, __T__);"
]
}
],
"default_high_energy": "zoom-through",
"default_calm": "blur-crossfade",
"max_duration_s": 2.0
}