feat(skin): connect v4 runtime prototype to WebClient

This commit is contained in:
illusia committed 2026-10-10 15:53:50 +08:00
1 parent 7993b38eee
commit 7650bd650b
14 files changed
+683 -49

No files matched your search

+46 -1
View File
@@ -385,7 +385,9 @@ test("schema version 4 validates and caches isolated plugin package files withou
assert.equal(await skin.runtimePluginFiles?.[entry].text(), "export const render = () => document.createElement('button');");
assert.equal(await skin.runtimePluginFiles?.[style].text(), ".toolbar { color: teal; }");
assert.equal(skin.runtimePluginFiles?.[icon].type, "image/png");
assert.equal(skin.assets[icon], undefined, "plugin assets stay in the isolated plugin file set");
assert.equal(skin.assets[icon]?.type, "image/png", "declared plugin media is available only by its package path for scoped CSS and host remapping");
assert.match(skin.runtimePluginStyles?.["voice-toolbar"] ?? "", /data-ws-runtime-plugin="voice-toolbar".*?\.toolbar/s);
assert.match(skin.runtimePluginStyles?.["voice-toolbar"] ?? "", /color: teal/);
assert.match(skin.css, /position: fixed/);
await assert.rejects(
@@ -402,6 +404,49 @@ test("schema version 4 validates and caches isolated plugin package files withou
);
});
test("a v4 surface cannot compete with a v3 surface on the same public page", async () => {
const components = {
schemaVersion: 2,
components: [{
id: "voice-v3-surface",
name: "Voice v3 surface",
page: "voice",
mode: "surface",
accessibleName: "Voice workspace",
permissions: ["ui.surface.replace"],
actions: {},
root: { tag: "main", children: [{ tag: "p", children: [{ text: "replacement UI" }] }] },
}],
};
const plugins = {
schemaVersion: 1,
plugins: [{
id: "voice-v4-surface",
name: "Voice v4 surface",
version: "1.0.0",
apiVersion: 1,
runtime: "wasm",
page: "voice",
mode: "surface",
entry: "plugins/voice-v4-surface/index.wasm",
assets: [],
permissions: ["ui.surface.replace"],
}],
};
const files = {
"manifest.json": strToU8(JSON.stringify({ ...manifest, schemaVersion: 4, packageType: "open-skin", components: "components.json", plugins: "plugins.json" })),
"skin.css": strToU8('[data-ws-part="app"] { color: teal; }'),
"components.json": strToU8(JSON.stringify(components)),
"plugins.json": strToU8(JSON.stringify(plugins)),
"plugins/voice-v4-surface/index.wasm": createSkinExtensionWasmPrefixByteImmediateProbe(),
};
const archive = zipSync(files);
await assert.rejects(
importSkinPack(new File([archive.slice().buffer as ArrayBuffer], "competing-surfaces.wskin")),
(error: unknown) => error instanceof SkinPackError && error.code === "SKIN_PLUGIN_SURFACE_DUPLICATE",
);
});
test("the distributable KAAK v3 package validates end to end", async () => {
const archive = await readFile(new URL("../../../docs/examples/kaak-voice.wskin", import.meta.url));
const file = new File([archive], "kaak-voice.wskin", { type: "application/octet-stream" });
+47 -8
View File
@@ -109,6 +109,7 @@ export interface InstalledSkin extends SkinManifest {
pluginData?: SkinPluginDocument;
runtimePlugins?: SkinRuntimePluginDocument;
runtimePluginFiles?: Record<string, Blob>;
runtimePluginStyles?: Record<string, string>;
previewBlob?: Blob;
warnings: string[];
installedAt: number;
@@ -177,6 +178,7 @@ export async function importSkinPack(file: File): Promise<InstalledSkin> {
}
const runtimePluginFiles: Record<string, Blob> = Object.create(null) as Record<string, Blob>;
const assets: Record<string, Blob> = Object.create(null) as Record<string, Blob>;
const runtimePluginPaths = runtimePlugins ? listSkinRuntimePluginFilePaths(runtimePlugins) : [];
const runtimePluginPathSet = new Set(runtimePluginPaths.map((path) => path.toLowerCase()));
const manifestPathSet = ["manifest.json", manifest.entry, manifest.layout, manifest.content, manifest.components, manifest.plugins, manifest.preview]
@@ -213,10 +215,10 @@ export async function importSkinPack(file: File): Promise<InstalledSkin> {
if (mimeType.startsWith("font/") && bytes.byteLength > MAX_FONT_BYTES) throw new SkinPackError("Plugin fonts must be smaller than 4 MiB.", "SKIN_FONT_SIZE");
if (mimeType.startsWith("image/") && bytes.byteLength > MAX_IMAGE_BYTES) throw new SkinPackError("Plugin images must be smaller than 16 MiB.", "SKIN_IMAGE_SIZE");
runtimePluginFiles[pluginPath] = new Blob([bytes], { type: mimeType });
assets[pluginPath] = runtimePluginFiles[pluginPath];
}
}
const assets: Record<string, Blob> = Object.create(null) as Record<string, Blob>;
for (const [path, bytes] of files) {
if (["manifest.json", manifest.entry, manifest.layout, manifest.content, manifest.components, manifest.plugins].includes(path)
|| runtimePluginPathSet.has(path.toLowerCase())) continue;
@@ -227,6 +229,20 @@ export async function importSkinPack(file: File): Promise<InstalledSkin> {
assets[path] = new Blob([bytes], { type: mimeType });
}
const runtimePluginStyles: Record<string, string> = Object.create(null) as Record<string, string>;
const runtimePluginWarnings: string[] = [];
for (const plugin of runtimePlugins?.plugins ?? []) {
if (!plugin.style) continue;
const style = runtimePluginFiles[plugin.style];
if (!style) throw new SkinPackError(`A declared plugin style is missing: ${plugin.style}`, "SKIN_RUNTIME_PLUGIN_FILE_MISSING");
const pluginAssetPrefix = `plugins/${plugin.id}/assets/`;
const pluginAssets = Object.fromEntries(Object.entries(assets).filter(([path]) =>
path.startsWith("assets/") || path.startsWith(pluginAssetPrefix)));
const compiledStyle = compileSkinCss(await style.text(), manifest.id, pluginAssets, manifest.schemaVersion, plugin.id);
runtimePluginStyles[plugin.id] = compiledStyle.css;
runtimePluginWarnings.push(...compiledStyle.warnings);
}
let contentData: SkinContent | undefined;
if (manifest.content) {
const contentBytes = files.get(manifest.content);
@@ -264,7 +280,24 @@ export async function importSkinPack(file: File): Promise<InstalledSkin> {
}
const compiled = compileSkinCss(decoder.decode(cssBytes), manifest.id, assets, manifest.schemaVersion);
return { ...manifest, css: compiled.css, assets, contentData, layoutData, pluginData, runtimePlugins, runtimePluginFiles, previewBlob, warnings: compiled.warnings, installedAt: Date.now() };
const hasConflictingSurface = (pluginData?.components ?? []).some((component) => component.mode === "surface"
&& runtimePlugins?.plugins.some((plugin) => plugin.mode === "surface" && plugin.page === component.page));
if (hasConflictingSurface) throw new SkinPackError("A page cannot declare both a v3 and v4 surface.", "SKIN_PLUGIN_SURFACE_DUPLICATE");
return {
...manifest,
css: compiled.css,
assets,
contentData,
layoutData,
pluginData,
runtimePlugins,
runtimePluginFiles,
runtimePluginStyles,
previewBlob,
warnings: [...compiled.warnings, ...runtimePluginWarnings],
installedAt: Date.now(),
};
}
export function resolveSkinCssAssets(css: string, assets: Record<string, Blob>): { css: string; objectUrls: string[] } {
@@ -527,15 +560,18 @@ function parseContent(bytes: Uint8Array): SkinContent {
return { defaultLocale: root.defaultLocale, locales };
}
function compileSkinCss(source: string, id: string, assets: Record<string, Blob>, schemaVersion: SkinManifest["schemaVersion"]): { css: string; warnings: string[] } {
function compileSkinCss(source: string, id: string, assets: Record<string, Blob>, schemaVersion: SkinManifest["schemaVersion"], pluginId?: string): { css: string; warnings: string[] } {
const size = new TextEncoder().encode(source).byteLength;
if (!size || size > MAX_CSS_BYTES) throw new SkinPackError("The CSS entry must be between 1 byte and 512 KiB.", "SKIN_CSS_SIZE");
let root: postcss.Root;
try { root = postcss.parse(source, { from: undefined }); }
catch (error) { throw new SkinPackError(`The CSS file could not be parsed: ${(error as Error).message}`, "SKIN_CSS_INVALID"); }
const scope = `.ws-skin-root[data-ws-skin="${id}"]`;
const namespace = `ws-${id.replace(/[^a-z0-9_-]/gi, "-")}`;
const skinScope = `.ws-skin-root[data-ws-skin="${id}"]`;
const scope = pluginId
? `${skinScope} .ws-plugin-component[data-ws-runtime-plugin="${pluginId}"]`
: skinScope;
const namespace = `ws-${id.replace(/[^a-z0-9_-]/gi, "-")}${pluginId ? `-${pluginId}` : ""}`;
const scopeNodes = selectorParser().astSync(scope).first!.nodes.map((node) => node.clone());
const warnings = new Set<string>();
const keyframeNames = new Map<string, string>();
@@ -575,7 +611,7 @@ function compileSkinCss(source: string, id: string, assets: Record<string, Blob>
root.walkRules((rule: Rule) => {
if (hasKeyframesAncestor(rule)) return;
if (rule.parent?.type === "rule") throw rule.error("Nested style rules are not supported; use flat selectors.");
if (!selectorUsesPublicHook(rule.selector, schemaVersion >= 3)) throw rule.error("Skin selectors must use :root, [data-ws-page], [data-ws-part], or [data-ws-plugin-part] so they stay attached to WebSpeak's stable visual interface.");
if (!pluginId && !selectorUsesPublicHook(rule.selector, schemaVersion >= 3)) throw rule.error("Skin selectors must use :root, [data-ws-page], [data-ws-part], or [data-ws-plugin-part] so they stay attached to WebSpeak's stable visual interface.");
if (targetsOnlyOptionalVisualParts(rule.selector)) hideableRules.add(rule);
try {
rule.selector = selectorParser((selectors) => {
@@ -629,8 +665,11 @@ function compileSkinCss(source: string, id: string, assets: Record<string, Blob>
const canHideTarget = owningRule
? hideableRules.has(owningRule) || Boolean(keyframesRule && optionalOnlyKeyframes.has(keyframesRule.params.trim()))
: false;
if (property.startsWith("--") && !/^--skin-[a-z0-9_-]+$/i.test(property)) {
throw declaration.error("Custom skin variables must use the --skin- prefix so they cannot replace WebSpeak's structural tokens.");
if (property.startsWith("--") && !/^--skin-[a-z0-9_-]+$/i.test(property)
&& !(pluginId && property.startsWith(`--plugin-${pluginId}-`))) {
throw declaration.error(pluginId
? `Custom plugin variables must use --plugin-${pluginId}- or --skin- prefixes.`
: "Custom skin variables must use the --skin- prefix so they cannot replace WebSpeak's structural tokens.");
}
if (schemaVersion < 3 && isLayoutAffectingProperty(property)) {
throw declaration.error("Skin CSS may change component artwork and appearance, but must not change layout, positioning, sizing, text flow, or interaction geometry.");
@@ -0,0 +1,69 @@
import assert from "node:assert/strict";
import test from "node:test";
import { parseSkinRuntimePluginDocument } from "../../../src/shared/skin-runtime-plugins.js";
import { createSkinRuntimePluginSession, SkinRuntimePluginSessionError } from "./skin-runtime-plugin-session.js";
const plugin = parseSkinRuntimePluginDocument({
schemaVersion: 1,
plugins: [{
id: "voice-surface",
name: "Voice surface",
version: "1.0.0",
apiVersion: 1,
runtime: "wasm",
page: "voice",
mode: "surface",
entry: "plugins/voice-surface/index.wasm",
assets: [],
permissions: ["ui.surface.replace"],
}],
}).plugins[0];
function output(page = "voice", count = 1): string {
return JSON.stringify({
schemaVersion: 5,
components: Array.from({ length: count }, (_, index) => ({
id: `surface-${index}`,
name: "Voice surface",
page,
accessibleName: "Voice workspace",
state: {},
root: { tag: "main", children: [{ text: "custom voice UI" }] },
})),
});
}
function sessionWithOutput(value: string, onError: (error: Error) => void = () => undefined) {
return createSkinRuntimePluginSession({
plugin,
createRun: () => ({ result: Promise.resolve({ uiOutput: value }), close: () => undefined }),
onError,
});
}
test("runtime plugin session accepts one generated root for its declared surface", async () => {
const session = sessionWithOutput(output());
assert.equal(await session.start(), true);
assert.equal(session.output, output());
assert.equal(session.closed, false);
session.close();
assert.equal(session.closed, true);
});
test("runtime plugin session rejects output targeting a different page", async () => {
const errors: Error[] = [];
const session = sessionWithOutput(output("home"), (error) => errors.push(error));
assert.equal(await session.start(), false);
assert.equal(errors[0] instanceof SkinRuntimePluginSessionError, true);
assert.equal((errors[0] as SkinRuntimePluginSessionError).code, "SKIN_RUNTIME_PLUGIN_PAGE_MISMATCH");
assert.equal(session.output, null);
});
test("runtime surface plugins cannot emit competing roots", async () => {
const errors: Error[] = [];
const session = sessionWithOutput(output("voice", 2), (error) => errors.push(error));
assert.equal(await session.start(), false);
assert.ok(errors[0] instanceof SkinRuntimePluginSessionError);
assert.equal((errors[0] as SkinRuntimePluginSessionError).code, "SKIN_RUNTIME_PLUGIN_SURFACE_OUTPUT_INVALID");
assert.equal(session.output, null);
});
@@ -0,0 +1,49 @@
import type { SkinRuntimePlugin } from "../../../src/shared/skin-runtime-plugins.js";
import type { SkinExtensionUiInput } from "../../../src/shared/skin-extension-ui-input.js";
import type { SkinPluginDocument } from "../../../src/shared/skin-plugin.js";
import {
createSkinExtensionWasmUiLoopPrototype,
type SkinExtensionWasmUiLoopRunHandle,
} from "./skin-extension-wasm-ui-loop.js";
export class SkinRuntimePluginSessionError extends Error {
constructor(readonly code: string, message: string) {
super(message);
this.name = "SkinRuntimePluginSessionError";
}
}
export interface SkinRuntimePluginSessionOptions {
plugin: SkinRuntimePlugin;
createRun(input: SkinExtensionUiInput): SkinExtensionWasmUiLoopRunHandle;
onOutput?(output: string, document: SkinPluginDocument): void | Promise<void>;
onError?(error: Error): void;
}
/** Binds one authorized v4 descriptor to its page and surface contract. */
export function createSkinRuntimePluginSession(options: SkinRuntimePluginSessionOptions) {
let output: string | null = null;
const loop = createSkinExtensionWasmUiLoopPrototype({
createRun: options.createRun,
onOutput: async (nextOutput, document) => {
if (document.components.some((component) => component.page !== options.plugin.page)) {
throw new SkinRuntimePluginSessionError("SKIN_RUNTIME_PLUGIN_PAGE_MISMATCH", "Generated UI must stay on the page declared by its plugin.");
}
if (options.plugin.mode === "surface" && document.components.length !== 1) {
throw new SkinRuntimePluginSessionError("SKIN_RUNTIME_PLUGIN_SURFACE_OUTPUT_INVALID", "A surface plugin must generate exactly one root component.");
}
output = nextOutput;
await options.onOutput?.(nextOutput, document);
},
onError: options.onError,
});
return {
get output() { return output; },
get closed() { return loop.closed; },
get running() { return loop.running; },
start: () => loop.start(),
dispatch: (input: unknown) => loop.dispatch(input),
close: (reason?: string) => loop.close(reason),
};
}
@@ -1,5 +1,6 @@
import assert from "node:assert/strict";
import test from "node:test";
import "./skin-runtime-plugin-session.test.js";
import {
computeSkinRuntimePluginDigest,
createSkinRuntimePluginApproval,
+2 -2
View File
@@ -33,7 +33,7 @@ export interface SkinRuntimePluginWasmOptions {
prototypeOnly: true;
}
const WASM_PROTOTYPE_PERMISSIONS = new Set(["session.status.read"]);
const WASM_PROTOTYPE_PERMISSIONS = new Set(["session.status.read", "ui.surface.replace"]);
/** Starts a Wasm entry only after rechecking the exact package digest and local approval. */
export async function createSkinRuntimePluginWasmSandboxPrototype(
@@ -66,7 +66,7 @@ export async function createSkinRuntimePluginWasmSandboxPrototype(
name: plugin.name,
version: plugin.version,
apiVersion: plugin.apiVersion,
permissions: [...plugin.permissions],
permissions: plugin.permissions.filter((permission) => permission === "session.status.read"),
});
// This legacy approval object is created only after the v4 digest-bound host approval above.