@moonwitness/ui 7.1.1 → 7.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,36 @@
1
+ /**
2
+ * T13 — Client pre-hydration init script for SSR skin parity.
3
+ *
4
+ * INV-013: Theme state is carried by request data.
5
+ * Generates a dependency-free IIFE that runs before React hydration.
6
+ * Precedence: explicit inline state > server data-* attrs > mw-theme cookie > legacy localStorage > defaults.
7
+ * Dev mismatch warning integrates T09 theme-mismatch-dev.ts when `dev: true`.
8
+ */
9
+ import type { ThemeRegistry, UserThemePreferences } from "../themes/types.js";
10
+ export interface SkinInitScriptOptionsSsr {
11
+ /** Explicit server-rendered state (inline data-* attributes win) */
12
+ serverState?: Partial<UserThemePreferences>;
13
+ /** Raw cookie value from the client (cookie wins over defaults) */
14
+ cookieValue?: string | null;
15
+ /** Development mode: emit console warning when server/client disagree */
16
+ dev?: boolean;
17
+ /** Theme registry to validate against */
18
+ registry?: ThemeRegistry;
19
+ /** Storage key for legacy localStorage fallback */
20
+ storageKey?: string;
21
+ }
22
+ /**
23
+ * Create a pre-hydration init script that applies theme state to documentElement
24
+ * before React hydrates. The generated IIFE has zero dependencies and runs
25
+ * synchronously in the <head> or at the top of <body>.
26
+ *
27
+ * Precedence (highest first):
28
+ * 1. `serverState` passed explicitly (inline data-* attrs from server render)
29
+ * 2. `cookieValue` from mw-theme cookie (passed from server, or read at runtime)
30
+ * 3. Legacy localStorage keys (mw-ui-theme, mw-board-preferences, mw-theme)
31
+ * 4. Registry defaults
32
+ *
33
+ * When `dev: true`, emits a console.warn if the resolved skin differs from what
34
+ * the server would have resolved from the same cookie (T09 parity check).
35
+ */
36
+ export declare function createSkinInitScript(options?: SkinInitScriptOptionsSsr): string;
@@ -0,0 +1,135 @@
1
+ /**
2
+ * T13 — Client pre-hydration init script for SSR skin parity.
3
+ *
4
+ * INV-013: Theme state is carried by request data.
5
+ * Generates a dependency-free IIFE that runs before React hydration.
6
+ * Precedence: explicit inline state > server data-* attrs > mw-theme cookie > legacy localStorage > defaults.
7
+ * Dev mismatch warning integrates T09 theme-mismatch-dev.ts when `dev: true`.
8
+ */
9
+ import { DEFAULT_SKIN_ID, themeRegistry, } from "../skin-catalog.js";
10
+ const VALID_MODES = new Set(["light", "dark"]);
11
+ const VALID_DENSITIES = new Set(["comfortable", "compact"]);
12
+ function isValidMode(value) {
13
+ return typeof value === "string" && VALID_MODES.has(value);
14
+ }
15
+ function isValidDensity(value) {
16
+ return typeof value === "string" && VALID_DENSITIES.has(value);
17
+ }
18
+ function isValidSkinId(value, registry) {
19
+ return typeof value === "string" && registry.has(value);
20
+ }
21
+ function resolveFromCookie(cookieValue, registry) {
22
+ if (!cookieValue)
23
+ return {};
24
+ let raw = cookieValue.trim();
25
+ try {
26
+ raw = decodeURIComponent(raw);
27
+ }
28
+ catch {
29
+ // keep raw
30
+ }
31
+ // Handle legacy bare mode like "dark"
32
+ if (isValidMode(raw))
33
+ return { theme_mode: raw };
34
+ const result = {};
35
+ for (const pair of raw.split(";")) {
36
+ const idx = pair.indexOf("=");
37
+ if (idx <= 0)
38
+ continue;
39
+ const key = pair.slice(0, idx).trim().toLowerCase();
40
+ const val = decodeURIComponent(pair.slice(idx + 1).trim());
41
+ if (key === "skin" && isValidSkinId(val, registry)) {
42
+ result.skin = val;
43
+ }
44
+ else if ((key === "mode" || key === "theme") && isValidMode(val)) {
45
+ result.theme_mode = val;
46
+ }
47
+ else if (key === "density" && isValidDensity(val)) {
48
+ result.density = val;
49
+ }
50
+ }
51
+ return result;
52
+ }
53
+ function normalizeState(partial, registry) {
54
+ const skinId = isValidSkinId(partial.skin, registry) ? partial.skin : registry.defaultSkinId;
55
+ const metadata = registry.resolve(skinId);
56
+ const mode = isValidMode(partial.theme_mode) ? partial.theme_mode : metadata.defaultMode;
57
+ const density = isValidDensity(partial.density) ? partial.density : metadata.defaultDensity;
58
+ return { skin: metadata.id, theme_mode: mode, density };
59
+ }
60
+ /**
61
+ * Create a pre-hydration init script that applies theme state to documentElement
62
+ * before React hydrates. The generated IIFE has zero dependencies and runs
63
+ * synchronously in the <head> or at the top of <body>.
64
+ *
65
+ * Precedence (highest first):
66
+ * 1. `serverState` passed explicitly (inline data-* attrs from server render)
67
+ * 2. `cookieValue` from mw-theme cookie (passed from server, or read at runtime)
68
+ * 3. Legacy localStorage keys (mw-ui-theme, mw-board-preferences, mw-theme)
69
+ * 4. Registry defaults
70
+ *
71
+ * When `dev: true`, emits a console.warn if the resolved skin differs from what
72
+ * the server would have resolved from the same cookie (T09 parity check).
73
+ */
74
+ export function createSkinInitScript(options = {}) {
75
+ const { serverState, cookieValue, dev = false, registry = themeRegistry, storageKey = "mw-ui-theme", } = options;
76
+ // Build the explicit server state if provided
77
+ const serverStatePayload = serverState
78
+ ? normalizeState(serverState, registry)
79
+ : null;
80
+ // Resolve what the cookie would produce (for dev parity check)
81
+ const cookieState = cookieValue
82
+ ? normalizeState(resolveFromCookie(cookieValue, registry), registry)
83
+ : null;
84
+ // Serialize registry skin IDs for client-side validation
85
+ const skinIdsJson = JSON.stringify(registry.list().map((s) => s.id));
86
+ const defaultSkinIdJson = JSON.stringify(DEFAULT_SKIN_ID);
87
+ const storageKeyJson = JSON.stringify(storageKey);
88
+ // Build the IIFE body as a template
89
+ const parts = [];
90
+ parts.push("(function(){");
91
+ parts.push("try{");
92
+ // 1. Apply explicit server state if provided (inline data-* wins)
93
+ if (serverStatePayload) {
94
+ parts.push(`var s=${JSON.stringify(serverStatePayload)};`, `document.documentElement.dataset.skin=s.skin;`, `document.documentElement.dataset.density=s.density;`, `document.documentElement.dataset.theme=s.theme_mode;`, `document.documentElement.classList.toggle('dark',s.theme_mode==='dark');`, `document.documentElement.classList.toggle('high-contrast',s.theme_mode==='high-contrast');`);
95
+ }
96
+ else if (cookieValue !== undefined && cookieValue !== null) {
97
+ // 2a. Explicit cookieValue passed from server - use it directly if valid
98
+ const cookieParsed = resolveFromCookie(cookieValue, registry);
99
+ if (Object.keys(cookieParsed).length > 0) {
100
+ parts.push(`var c=${JSON.stringify(normalizeState(cookieParsed, registry))};`, `document.documentElement.dataset.skin=c.skin;`, `document.documentElement.dataset.density=c.density;`, `document.documentElement.dataset.theme=c.theme_mode;`, `document.documentElement.classList.toggle('dark',c.theme_mode==='dark');`, `document.documentElement.classList.toggle('high-contrast',c.theme_mode==='high-contrast');`);
101
+ }
102
+ else {
103
+ // 2b. Explicit cookieValue but invalid - fall through to runtime cookie + localStorage
104
+ parts.push(`var cookieVal=null;`, `var cookieHeader=document.cookie||'';`, `for(var i=0;i<cookieHeader.split(';').length;i++){`, ` var part=cookieHeader.split(';')[i].trim();`, ` var eq=part.indexOf('=');`, ` var key=eq>=0?part.slice(0,eq):part;`, ` if(key==='mw-theme'){ cookieVal=eq>=0?decodeURIComponent(part.slice(eq+1)):''; break; }`, `}`, `if(cookieVal){`, ` var parsed={};`, ` try{ cookieVal=decodeURIComponent(cookieVal); }catch(e){}`, ` if(cookieVal==='dark'||cookieVal==='light'){ parsed.theme_mode=cookieVal; }`, ` else{ for(var j=0;j<cookieVal.split(';').length;j++){ var p=cookieVal.split(';')[j].trim(); var ei=p.indexOf('='); if(ei<=0) continue; var pk=p.slice(0,ei).trim().toLowerCase(); var pv=decodeURIComponent(p.slice(ei+1).trim()); if(pk==='skin') parsed.skin=pv; else if(pk==='mode'||pk==='theme') parsed.theme_mode=pv; else if(pk==='density') parsed.density=pv; } }`, ` var allowed=${skinIdsJson};`, ` var skin=(parsed.skin&&allowed.indexOf(parsed.skin)!==-1)?parsed.skin:${defaultSkinIdJson};`, ` var mode=(parsed.theme_mode==='dark'||parsed.theme_mode==='light')?parsed.theme_mode:'light';`, ` var density=(parsed.density==='compact')?'compact':'comfortable';`, ` document.documentElement.dataset.skin=skin;`, ` document.documentElement.dataset.density=density;`, ` document.documentElement.dataset.theme=mode;`, ` document.documentElement.classList.toggle('dark',mode==='dark');`, ` document.documentElement.classList.toggle('high-contrast',mode==='high-contrast');`, `} else {`,
105
+ // 3. Legacy localStorage fallback
106
+ `var raw=localStorage.getItem(${storageKeyJson})||localStorage.getItem('mw-board-preferences')||localStorage.getItem('mw-theme');`, `var p=raw?JSON.parse(raw):null;`, `var allowed=${skinIdsJson};`, `var k=p&&typeof p.skin==='string'&&allowed.indexOf(p.skin)!==-1?p.skin:${defaultSkinIdJson};`, `var d=p&&p.density==='compact'?'compact':'comfortable';`, `var rawMode=p&&(p.mode||p.theme);`, `var m=(rawMode==='dark'||rawMode==='light'||rawMode==='high-contrast')?rawMode:'light';`, `document.documentElement.dataset.skin=k;`, `document.documentElement.dataset.density=d;`, `document.documentElement.dataset.theme=m;`, `document.documentElement.classList.toggle('dark',m==='dark');`, `document.documentElement.classList.toggle('high-contrast',m==='high-contrast');`, `}`);
107
+ }
108
+ }
109
+ else {
110
+ // 2c. No explicit cookieValue - read mw-theme cookie at runtime, then localStorage
111
+ parts.push(`var cookieVal=null;`, `var cookieHeader=document.cookie||'';`, `for(var i=0;i<cookieHeader.split(';').length;i++){`, ` var part=cookieHeader.split(';')[i].trim();`, ` var eq=part.indexOf('=');`, ` var key=eq>=0?part.slice(0,eq):part;`, ` if(key==='mw-theme'){ cookieVal=eq>=0?decodeURIComponent(part.slice(eq+1)):''; break; }`, `}`, `if(cookieVal){`, ` var parsed={};`, ` try{ cookieVal=decodeURIComponent(cookieVal); }catch(e){}`, ` if(cookieVal==='dark'||cookieVal==='light'){ parsed.theme_mode=cookieVal; }`, ` else{ for(var j=0;j<cookieVal.split(';').length;j++){ var p=cookieVal.split(';')[j].trim(); var ei=p.indexOf('='); if(ei<=0) continue; var pk=p.slice(0,ei).trim().toLowerCase(); var pv=decodeURIComponent(p.slice(ei+1).trim()); if(pk==='skin') parsed.skin=pv; else if(pk==='mode'||pk==='theme') parsed.theme_mode=pv; else if(pk==='density') parsed.density=pv; } }`, ` var allowed=${skinIdsJson};`, ` var skin=(parsed.skin&&allowed.indexOf(parsed.skin)!==-1)?parsed.skin:${defaultSkinIdJson};`, ` var mode=(parsed.theme_mode==='dark'||parsed.theme_mode==='light')?parsed.theme_mode:'light';`, ` var density=(parsed.density==='compact')?'compact':'comfortable';`, ` document.documentElement.dataset.skin=skin;`, ` document.documentElement.dataset.density=density;`, ` document.documentElement.dataset.theme=mode;`, ` document.documentElement.classList.toggle('dark',mode==='dark');`, ` document.documentElement.classList.toggle('high-contrast',mode==='high-contrast');`, `} else {`,
112
+ // 3. Legacy localStorage fallback
113
+ `var raw=localStorage.getItem(${storageKeyJson})||localStorage.getItem('mw-board-preferences')||localStorage.getItem('mw-theme');`, `var p=raw?JSON.parse(raw):null;`, `var allowed=${skinIdsJson};`, `var k=p&&typeof p.skin==='string'&&allowed.indexOf(p.skin)!==-1?p.skin:${defaultSkinIdJson};`, `var d=p&&p.density==='compact'?'compact':'comfortable';`, `var rawMode=p&&(p.mode||p.theme);`, `var m=(rawMode==='dark'||rawMode==='light'||rawMode==='high-contrast')?rawMode:'light';`, `document.documentElement.dataset.skin=k;`, `document.documentElement.dataset.density=d;`, `document.documentElement.dataset.theme=m;`, `document.documentElement.classList.toggle('dark',m==='dark');`, `document.documentElement.classList.toggle('high-contrast',m==='high-contrast');`, `}`);
114
+ }
115
+ // Dev mismatch warning (T09 integration)
116
+ if (dev && serverStatePayload && cookieState) {
117
+ const serverSkin = serverStatePayload.skin;
118
+ const serverMode = serverStatePayload.theme_mode;
119
+ const serverDensity = serverStatePayload.density;
120
+ const cookieSkin = cookieState.skin;
121
+ const cookieMode = cookieState.theme_mode;
122
+ const cookieDensity = cookieState.density;
123
+ if (serverSkin !== cookieSkin ||
124
+ serverMode !== cookieMode ||
125
+ serverDensity !== cookieDensity) {
126
+ parts.push(`console.warn('[MoonWitness SSR] Theme mismatch: server={skin:"${serverSkin}",mode:"${serverMode}",density:"${serverDensity}"} cookie={skin:"${cookieSkin}",mode:"${cookieMode}",density:"${cookieDensity}"}. Inline state wins.');`);
127
+ }
128
+ }
129
+ parts.push("}catch(e){");
130
+ // Final safety net: apply defaults on any error
131
+ parts.push(`document.documentElement.dataset.skin=${defaultSkinIdJson};`, `document.documentElement.dataset.density='comfortable';`, `document.documentElement.dataset.theme='light';`, `document.documentElement.classList.remove('dark','high-contrast');`);
132
+ parts.push("}");
133
+ parts.push("})();");
134
+ return parts.join("");
135
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * T13 — SSR skin resolution from request data.
3
+ *
4
+ * INV-013: Theme state is carried by request data.
5
+ * No `localStorage`, `window`, or `document` access on this server path.
6
+ */
7
+ import type { ThemeRegistry, UserThemePreferences } from "../themes/types.js";
8
+ export declare const THEME_COOKIE_NAME = "mw-theme";
9
+ export declare const THEME_HEADER_NAME = "x-mw-theme";
10
+ export type ThemeSource = "cookie" | "header" | "default";
11
+ export interface ResolvedSkin extends UserThemePreferences {
12
+ readonly source: ThemeSource;
13
+ readonly valid: boolean;
14
+ }
15
+ export type CookieInput = string | null | undefined | Headers | Record<string, string | string[] | undefined> | Map<string, string>;
16
+ export interface ResolveSkinOptions {
17
+ readonly registry?: ThemeRegistry;
18
+ readonly cookieName?: string;
19
+ }
20
+ /**
21
+ * Resolve theme state from a cookie raw value, Cookie header, `Headers`,
22
+ * `x-mw-theme` header, or a plain header/cookie map.
23
+ *
24
+ * Precedence: mw-theme request data > x-mw-theme fallback > defaults.
25
+ */
26
+ export declare function resolveSkin(input: CookieInput, options?: ResolveSkinOptions): ResolvedSkin;
27
+ /** Serialize resolved state into the URL-safe mw-theme cookie value. */
28
+ export declare function serializeSkinCookie(state: UserThemePreferences): string;
29
+ type MutableUserThemePreferences = {
30
+ -readonly [K in keyof UserThemePreferences]: UserThemePreferences[K];
31
+ };
32
+ /** Parse a raw mw-theme cookie value without registry normalization. */
33
+ export declare function parseSkinCookie(value: string | undefined | null, registry?: ThemeRegistry): Partial<MutableUserThemePreferences>;
34
+ export {};
@@ -0,0 +1,168 @@
1
+ /**
2
+ * T13 — SSR skin resolution from request data.
3
+ *
4
+ * INV-013: Theme state is carried by request data.
5
+ * No `localStorage`, `window`, or `document` access on this server path.
6
+ */
7
+ import { DEFAULT_SKIN_ID, themeRegistry, } from "../skin-catalog.js";
8
+ export const THEME_COOKIE_NAME = "mw-theme";
9
+ export const THEME_HEADER_NAME = "x-mw-theme";
10
+ const THEME_VALUE_KEYS = new Set(["skin", "mode", "theme", "density"]);
11
+ const VALID_MODES = new Set(["light", "dark"]);
12
+ const VALID_DENSITIES = new Set(["comfortable", "compact"]);
13
+ function hasGet(input) {
14
+ return typeof input?.get === "function";
15
+ }
16
+ function headerValue(input, name) {
17
+ if (hasGet(input))
18
+ return input.get(name) ?? undefined;
19
+ if (input instanceof Map)
20
+ return input.get(name) ?? input.get(name.toLowerCase());
21
+ const direct = input[name] ?? input[name.toLowerCase()];
22
+ if (Array.isArray(direct))
23
+ return direct[0];
24
+ return direct;
25
+ }
26
+ function safeDecode(value) {
27
+ try {
28
+ return decodeURIComponent(value);
29
+ }
30
+ catch {
31
+ return value;
32
+ }
33
+ }
34
+ /** Parse a theme value: `skin=x;mode=dark;density=compact` or legacy `dark`. */
35
+ function parseThemeValue(rawValue) {
36
+ if (!rawValue)
37
+ return {};
38
+ let raw = rawValue.trim();
39
+ if (/%3d/i.test(raw))
40
+ raw = safeDecode(raw);
41
+ if (VALID_MODES.has(raw))
42
+ return { mode: raw };
43
+ const result = {};
44
+ for (const pair of raw.split(";")) {
45
+ const separator = pair.indexOf("=");
46
+ if (separator <= 0) {
47
+ const bare = pair.trim();
48
+ if (VALID_MODES.has(bare))
49
+ result.mode = bare;
50
+ continue;
51
+ }
52
+ const key = pair.slice(0, separator).trim().toLowerCase();
53
+ if (!THEME_VALUE_KEYS.has(key))
54
+ continue;
55
+ result[key] = safeDecode(pair.slice(separator + 1).trim());
56
+ }
57
+ return result;
58
+ }
59
+ /** Read a cookie value from a Cookie header, including semicolon-delimited theme pairs. */
60
+ function rawCookieFromHeader(cookieHeader, name) {
61
+ let active = false;
62
+ let value;
63
+ for (const segment of cookieHeader.split(";")) {
64
+ const part = segment.trim();
65
+ if (!part)
66
+ continue;
67
+ const separator = part.indexOf("=");
68
+ const key = (separator >= 0 ? part.slice(0, separator) : part).trim();
69
+ if (separator < 0 && active) {
70
+ value += `;${part}`;
71
+ continue;
72
+ }
73
+ if (THEME_VALUE_KEYS.has(key.toLowerCase()) && active) {
74
+ value += `;${part}`;
75
+ continue;
76
+ }
77
+ active = key === name;
78
+ if (active)
79
+ value = separator >= 0 ? part.slice(separator + 1).trim() : "";
80
+ }
81
+ return value;
82
+ }
83
+ function readThemeRaw(input, cookieName) {
84
+ if (typeof input === "string") {
85
+ if (!input.includes("="))
86
+ return VALID_MODES.has(input.trim()) ? input.trim() : undefined;
87
+ return rawCookieFromHeader(input, cookieName);
88
+ }
89
+ if (input === null || input === undefined)
90
+ return undefined;
91
+ const direct = headerValue(input, cookieName);
92
+ if (direct !== undefined)
93
+ return direct;
94
+ const cookieHeader = headerValue(input, "cookie");
95
+ return cookieHeader ? rawCookieFromHeader(cookieHeader, cookieName) : undefined;
96
+ }
97
+ function readHeaderRaw(input) {
98
+ if (typeof input === "string" || input === null || input === undefined)
99
+ return undefined;
100
+ return headerValue(input, THEME_HEADER_NAME);
101
+ }
102
+ function hasUsableTheme(value, registry) {
103
+ if (typeof value.skin === "string" && registry.has(value.skin))
104
+ return true;
105
+ // legacy bare mode (e.g., "dark" without skin) — treat as unusable so default applies
106
+ return false;
107
+ }
108
+ function normalize(value, registry) {
109
+ const skinId = typeof value.skin === "string" && registry.has(value.skin)
110
+ ? value.skin
111
+ : registry.defaultSkinId;
112
+ const metadata = registry.resolve(skinId);
113
+ const rawMode = value.mode ?? value.theme;
114
+ const mode = typeof rawMode === "string" && VALID_MODES.has(rawMode)
115
+ ? rawMode
116
+ : metadata.defaultMode;
117
+ const density = typeof value.density === "string" && VALID_DENSITIES.has(value.density)
118
+ ? value.density
119
+ : metadata.defaultDensity;
120
+ return { skin: metadata.id, theme_mode: mode, density };
121
+ }
122
+ function defaultState(registry) {
123
+ const fallback = registry.resolve(DEFAULT_SKIN_ID);
124
+ return {
125
+ skin: fallback.id,
126
+ theme_mode: fallback.defaultMode,
127
+ density: fallback.defaultDensity,
128
+ source: "default",
129
+ valid: false,
130
+ };
131
+ }
132
+ /**
133
+ * Resolve theme state from a cookie raw value, Cookie header, `Headers`,
134
+ * `x-mw-theme` header, or a plain header/cookie map.
135
+ *
136
+ * Precedence: mw-theme request data > x-mw-theme fallback > defaults.
137
+ */
138
+ export function resolveSkin(input, options = {}) {
139
+ const registry = options.registry ?? themeRegistry;
140
+ const cookieName = options.cookieName ?? THEME_COOKIE_NAME;
141
+ const fromCookie = parseThemeValue(readThemeRaw(input, cookieName));
142
+ if (hasUsableTheme(fromCookie, registry)) {
143
+ return { ...normalize(fromCookie, registry), source: "cookie", valid: true };
144
+ }
145
+ const fromHeader = parseThemeValue(readHeaderRaw(input));
146
+ if (hasUsableTheme(fromHeader, registry)) {
147
+ return { ...normalize(fromHeader, registry), source: "header", valid: true };
148
+ }
149
+ return defaultState(registry);
150
+ }
151
+ /** Serialize resolved state into the URL-safe mw-theme cookie value. */
152
+ export function serializeSkinCookie(state) {
153
+ return `skin=${encodeURIComponent(state.skin)};mode=${encodeURIComponent(state.theme_mode)};density=${encodeURIComponent(state.density)}`;
154
+ }
155
+ /** Parse a raw mw-theme cookie value without registry normalization. */
156
+ export function parseSkinCookie(value, registry) {
157
+ const parsed = parseThemeValue(value ?? undefined);
158
+ const result = {};
159
+ if (parsed.skin && (!registry || registry.has(parsed.skin)))
160
+ result.skin = parsed.skin;
161
+ const rawMode = parsed.mode ?? parsed.theme;
162
+ if (rawMode === "light" || rawMode === "dark")
163
+ result.theme_mode = rawMode;
164
+ if (parsed.density === "compact" || parsed.density === "comfortable") {
165
+ result.density = parsed.density;
166
+ }
167
+ return result;
168
+ }
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Dev-only SSR theme mismatch fixture for the W1/T09 smoke gate.
3
+ *
4
+ * INV-009: Theme state is visible to server and client.
5
+ *
6
+ * This module is intentionally small and dependency-free so the same
7
+ * deterministic logic can be exercised by:
8
+ * - the Playwright smoke spec (browser console hydration detection), and
9
+ * - a Node self-check when this file is executed directly (bunx fallback).
10
+ *
11
+ * Do not suppress hydration warnings. The gate must fail closed.
12
+ */
13
+ export declare const THEME_COOKIE_NAME = "mw-theme";
14
+ export declare const THEME_FIXTURES: readonly ["light", "dark"];
15
+ export type Theme = (typeof THEME_FIXTURES)[number];
16
+ export interface ThemeHtmlState {
17
+ theme: Theme;
18
+ attributes: Record<string, string>;
19
+ }
20
+ export interface HydrationCheck {
21
+ passed: boolean;
22
+ warning: string | null;
23
+ }
24
+ export interface SelfTestCheck {
25
+ name: string;
26
+ passed: boolean;
27
+ detail?: string;
28
+ }
29
+ export interface SelfTestResult {
30
+ passed: boolean;
31
+ checks: SelfTestCheck[];
32
+ }
33
+ /** Deterministic theme resolution: unknown/empty cookies fall back to light. */
34
+ export declare function resolveTheme(cookieValue: string | undefined | null): Theme;
35
+ /** Deterministic server-side theme state derived from the request cookie. */
36
+ export declare function serverRender(cookieValue: string | undefined | null): ThemeHtmlState;
37
+ /** Client hydration attributes derived from the same cookie. */
38
+ export declare function clientHydrationAttributes(cookieValue: string | undefined | null): Record<string, string>;
39
+ /** Stable serialization used on both sides so comparison is deterministic. */
40
+ export declare function serializeHtmlAttributes(attributes: Record<string, string>): string;
41
+ /** Full deterministic <html> open tag for a fixture cookie. */
42
+ export declare function renderServerHtml(cookieValue: string | undefined | null): string;
43
+ /**
44
+ * Negative fixture: simulate a client that ignores the cookie and hydrates
45
+ * with the light default while the server rendered dark.
46
+ */
47
+ export declare function mismatchedClientAttributes(_cookieValue: string | undefined | null): Record<string, string>;
48
+ /** True when a console message is a hydration warning. Fail closed on these. */
49
+ export declare function isHydrationWarning(message: string): boolean;
50
+ /** Gate predicate used by the smoke spec: any hydration warning fails. */
51
+ export declare function gateFailsOnWarnings(messages: string[]): boolean;
52
+ /** Compare server attributes with the attributes the client hydrates with. */
53
+ export declare function checkHydration(cookieValue: string | undefined | null, clientAttributes?: Record<string, string>): HydrationCheck;
54
+ /**
55
+ * Deterministic Node-side verification for the three T09 acceptance criteria.
56
+ * Used when the bun/bunx shim is unavailable.
57
+ */
58
+ export declare function runSelfTest(): SelfTestResult;
@@ -0,0 +1,133 @@
1
+ /**
2
+ * Dev-only SSR theme mismatch fixture for the W1/T09 smoke gate.
3
+ *
4
+ * INV-009: Theme state is visible to server and client.
5
+ *
6
+ * This module is intentionally small and dependency-free so the same
7
+ * deterministic logic can be exercised by:
8
+ * - the Playwright smoke spec (browser console hydration detection), and
9
+ * - a Node self-check when this file is executed directly (bunx fallback).
10
+ *
11
+ * Do not suppress hydration warnings. The gate must fail closed.
12
+ */
13
+ export const THEME_COOKIE_NAME = "mw-theme";
14
+ export const THEME_FIXTURES = ["light", "dark"];
15
+ /** Deterministic theme resolution: unknown/empty cookies fall back to light. */
16
+ export function resolveTheme(cookieValue) {
17
+ return cookieValue === "dark" ? "dark" : "light";
18
+ }
19
+ /** Deterministic server-side theme state derived from the request cookie. */
20
+ export function serverRender(cookieValue) {
21
+ const theme = resolveTheme(cookieValue);
22
+ return {
23
+ theme,
24
+ attributes: {
25
+ "data-theme": theme,
26
+ class: `theme-${theme}`,
27
+ },
28
+ };
29
+ }
30
+ /** Client hydration attributes derived from the same cookie. */
31
+ export function clientHydrationAttributes(cookieValue) {
32
+ const theme = resolveTheme(cookieValue);
33
+ return {
34
+ "data-theme": theme,
35
+ class: `theme-${theme}`,
36
+ };
37
+ }
38
+ /** Stable serialization used on both sides so comparison is deterministic. */
39
+ export function serializeHtmlAttributes(attributes) {
40
+ return Object.keys(attributes)
41
+ .sort()
42
+ .map((key) => `${key}="${attributes[key]}"`)
43
+ .join(" ");
44
+ }
45
+ /** Full deterministic <html> open tag for a fixture cookie. */
46
+ export function renderServerHtml(cookieValue) {
47
+ return `<html ${serializeHtmlAttributes(serverRender(cookieValue).attributes)}>`;
48
+ }
49
+ /**
50
+ * Negative fixture: simulate a client that ignores the cookie and hydrates
51
+ * with the light default while the server rendered dark.
52
+ */
53
+ export function mismatchedClientAttributes(_cookieValue) {
54
+ // Simulate a client that ignores the cookie and always hydrates light.
55
+ return {
56
+ "data-theme": "light",
57
+ class: "theme-light",
58
+ };
59
+ }
60
+ /** True when a console message is a hydration warning. Fail closed on these. */
61
+ export function isHydrationWarning(message) {
62
+ return /hydrat|did not match|text content does not match|server rendered html/i.test(message);
63
+ }
64
+ /** Gate predicate used by the smoke spec: any hydration warning fails. */
65
+ export function gateFailsOnWarnings(messages) {
66
+ return messages.some(isHydrationWarning);
67
+ }
68
+ /** Compare server attributes with the attributes the client hydrates with. */
69
+ export function checkHydration(cookieValue, clientAttributes = clientHydrationAttributes(cookieValue)) {
70
+ const server = serializeHtmlAttributes(serverRender(cookieValue).attributes);
71
+ const client = serializeHtmlAttributes(clientAttributes);
72
+ if (server !== client) {
73
+ return {
74
+ passed: false,
75
+ warning: `Hydration attribute mismatch: server="${server}" client="${client}"`,
76
+ };
77
+ }
78
+ return { passed: true, warning: null };
79
+ }
80
+ /**
81
+ * Deterministic Node-side verification for the three T09 acceptance criteria.
82
+ * Used when the bun/bunx shim is unavailable.
83
+ */
84
+ export function runSelfTest() {
85
+ const checks = [];
86
+ // AC2: server html attribute equals client html attribute for fixture cookie.
87
+ for (const cookie of THEME_FIXTURES) {
88
+ const result = checkHydration(cookie);
89
+ checks.push({
90
+ name: `server/client attribute parity for cookie=${cookie}`,
91
+ passed: result.passed,
92
+ detail: result.warning ?? undefined,
93
+ });
94
+ }
95
+ // AC3: two cookie values produce two deterministic server renders.
96
+ for (const cookie of THEME_FIXTURES) {
97
+ const first = renderServerHtml(cookie);
98
+ const second = renderServerHtml(cookie);
99
+ checks.push({
100
+ name: `deterministic server render for cookie=${cookie}`,
101
+ passed: first === second,
102
+ detail: first === second ? undefined : `"${first}" !== "${second}"`,
103
+ });
104
+ }
105
+ const lightHtml = renderServerHtml("light");
106
+ const darkHtml = renderServerHtml("dark");
107
+ checks.push({
108
+ name: "two cookie values produce distinct server renders",
109
+ passed: lightHtml !== darkHtml,
110
+ detail: lightHtml !== darkHtml ? undefined : `${lightHtml} === ${darkHtml}`,
111
+ });
112
+ // AC1: hydration warning fails the test (negative control).
113
+ const negative = checkHydration("dark", mismatchedClientAttributes("dark"));
114
+ const warningDetected = negative.passed === false && isHydrationWarning(negative.warning ?? "");
115
+ const gateFails = gateFailsOnWarnings([negative.warning ?? ""]);
116
+ checks.push({
117
+ name: "hydration warning fails the gate",
118
+ passed: warningDetected && gateFails,
119
+ detail: negative.warning ?? undefined,
120
+ });
121
+ return {
122
+ passed: checks.every((check) => check.passed),
123
+ checks,
124
+ };
125
+ }
126
+ // Direct-run CLI fallback (Node 24 can execute .ts directly).
127
+ if (typeof process !== "undefined" && process.argv?.[1]?.endsWith("theme-mismatch-dev.ts")) {
128
+ const result = runSelfTest();
129
+ console.log(JSON.stringify(result, null, 2));
130
+ if (!result.passed) {
131
+ process.exitCode = 1;
132
+ }
133
+ }
@@ -5,7 +5,9 @@
5
5
  * consumers can import it without pulling React in. Everything below re-exports
6
6
  * that catalogue unchanged, so `@moonwitness/ui/themes` keeps its public surface.
7
7
  */
8
- export { BUILTIN_SKINS, DEFAULT_SKIN_ID, createSkinInitScript, createThemeRegistry, themeRegistry, type SkinInitScriptOptions, } from "../skin-catalog.js";
8
+ export { BUILTIN_SKINS, DEFAULT_SKIN_ID, createSkinInitScript, createThemeRegistry, themeRegistry, validateSkinId, resolveValidSkin, type SkinInitScriptOptions, } from "../skin-catalog.js";
9
+ export { THEME_COOKIE_NAME, THEME_HEADER_NAME, resolveSkin, parseSkinCookie, serializeSkinCookie, type ResolvedSkin, type ResolveSkinOptions, type CookieInput, } from "../ssr/resolve-skin.js";
10
+ export { createSkinInitScript as createSkinInitScriptSsr, type SkinInitScriptOptionsSsr as SkinInitScriptOptionsSsr } from "../ssr/init-script.js";
9
11
  export type { BuiltinSkinId, ColorMode, SkinDensity, SkinId, SkinMetadata, SkinSwatchPreview, ThemeRegistry, UserThemePreferences, } from "./types.js";
10
12
  export { DEFAULT_THEME_STORAGE_KEY, ThemeProvider, useTheme, applyThemeState, type ThemeContextValue, type ThemeMode, type ThemeProviderProps, type ThemeState, } from "./provider.js";
11
13
  export { GENRE_DNA_PRESETS, getGenreDnaPresetById, applyGenreDnaAttribute, type GenreDnaPreset, type GenreDnaPresetId, } from "./dna-presets.js";
@@ -5,6 +5,8 @@
5
5
  * consumers can import it without pulling React in. Everything below re-exports
6
6
  * that catalogue unchanged, so `@moonwitness/ui/themes` keeps its public surface.
7
7
  */
8
- export { BUILTIN_SKINS, DEFAULT_SKIN_ID, createSkinInitScript, createThemeRegistry, themeRegistry, } from "../skin-catalog.js";
8
+ export { BUILTIN_SKINS, DEFAULT_SKIN_ID, createSkinInitScript, createThemeRegistry, themeRegistry, validateSkinId, resolveValidSkin, } from "../skin-catalog.js";
9
+ export { THEME_COOKIE_NAME, THEME_HEADER_NAME, resolveSkin, parseSkinCookie, serializeSkinCookie, } from "../ssr/resolve-skin.js";
10
+ export { createSkinInitScript as createSkinInitScriptSsr } from "../ssr/init-script.js";
9
11
  export { DEFAULT_THEME_STORAGE_KEY, ThemeProvider, useTheme, applyThemeState, } from "./provider.js";
10
12
  export { GENRE_DNA_PRESETS, getGenreDnaPresetById, applyGenreDnaAttribute, } from "./dna-presets.js";
@@ -1,12 +1,20 @@
1
1
  "use client";
2
2
  import { jsx as _jsx } from "react/jsx-runtime";
3
3
  import { createContext, useCallback, useContext, useEffect, useMemo, useState, } from "react";
4
+ import { themeRegistry } from "./index.js";
4
5
  export const DEFAULT_THEME_STORAGE_KEY = "mw-ui-theme";
5
6
  const DEFAULT_THEME_STATE = {
6
7
  mode: "light",
7
8
  skin: "moonwitness-ink",
8
9
  density: "comfortable",
9
10
  };
11
+ function validateSkinProp(skin) {
12
+ if (skin !== undefined && !themeRegistry.has(skin)) {
13
+ const available = themeRegistry.list().map((s) => s.id).join(", ");
14
+ throw new Error(`Unknown skin ID "${skin}". Available skins: ${available}`);
15
+ }
16
+ return skin ?? DEFAULT_THEME_STATE.skin;
17
+ }
10
18
  export function applyThemeState(state, root = typeof document !== "undefined"
11
19
  ? document.documentElement
12
20
  : null) {
@@ -45,9 +53,11 @@ function readStoredTheme(storageKey, fallback) {
45
53
  }
46
54
  }
47
55
  export function ThemeProvider({ children, defaultMode = DEFAULT_THEME_STATE.mode, defaultSkin = DEFAULT_THEME_STATE.skin, defaultDensity = DEFAULT_THEME_STATE.density, storageKey, targetElement, }) {
56
+ // Validate defaultSkin prop at provider creation time
57
+ const validatedDefaultSkin = validateSkinProp(defaultSkin);
48
58
  const [state, setState] = useState(() => readStoredTheme(storageKey, {
49
59
  mode: defaultMode,
50
- skin: defaultSkin,
60
+ skin: validatedDefaultSkin,
51
61
  density: defaultDensity,
52
62
  }));
53
63
  useEffect(() => {
@@ -67,6 +77,11 @@ export function ThemeProvider({ children, defaultMode = DEFAULT_THEME_STATE.mode
67
77
  setState((current) => ({ ...current, mode }));
68
78
  }, []);
69
79
  const setSkin = useCallback((skin) => {
80
+ // Validate skin at runtime when setting
81
+ if (!themeRegistry.has(skin)) {
82
+ const available = themeRegistry.list().map((s) => s.id).join(", ");
83
+ throw new Error(`Unknown skin ID "${skin}". Available skins: ${available}`);
84
+ }
70
85
  setState((current) => ({ ...current, skin }));
71
86
  }, []);
72
87
  const setDensity = useCallback((density) => {