Luigit
repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by admin

quickshell/nuguland/typed-state.test.mjs

Raw
// NL-PLAN-C4V7TQ2X step 6: in-process code binds typed service state. JSON
// stays at the edges: IPC handlers in shell.qml, diagnostics, and parsing
// subprocess output, files or the niri event stream.
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { productionFiles } from "./test-fixtures/sources.js";
import { test } from "node:test";

const root = new URL(".", import.meta.url).pathname;

// A line breaks the contract when it reads another object's JSON or snapshot,
// or parses what a service returned. Calls on objects the file declares itself
// (its own children) and the IPC edge in shell.qml are allowed.
export function violations(file, text) {
    if (file === "shell.qml")
        return [];
    const ids = new Set([...text.matchAll(/^\s*(?:id:|(?:readonly\s+)?property\s+[A-Z]\w*)\s+(\w+)/gm)].map(match => match[1]));
    const found = [];
    text.split("\n").forEach((line, index) => {
        for (const match of line.matchAll(/(\w+)\.(stateJson|stateObject)\(/g)) {
            if (match[1] !== "root" && !ids.has(match[1]))
                found.push(`${file}:${index + 1}: reads ${match[1]}.${match[2]}()`);
        }
        if (/(JSON\.parse|parseJson)\([^)]*\w+Service\.\w+\(/.test(line))
            found.push(`${file}:${index + 1}: parses a service's JSON return`);
        if (/(Panel|Surface|Host|Bar|BarControl)\.qml$|^(Registry|SurfaceManager)\.qml$/.test(file) && /JSON\.parse\(|parseJson\(/.test(line))
            found.push(`${file}:${index + 1}: presentation parses JSON`);
    });
    return found;
}

test("production QML binds typed service state; JSON stays at the IPC edge", () => {
    const found = productionFiles("*.qml", root).flatMap(file => violations(file, readFileSync(join(root, file), "utf8")));
    assert.deepEqual(found, []);
});

// Registry bar bindings read service properties; intents belong in handlers.
export function barCalls(text) {
    const lines = text.split("\n");
    const found = [];
    lines.forEach((line, index) => {
        const binding = /^\s*(bar\w+):/.exec(line);
        if (!binding)
            return;
        let body = line;
        for (let depth = (line.match(/\{/g) || []).length - (line.match(/\}/g) || []).length, next = index + 1; depth > 0 && next < lines.length; next++) {
            body += "\n" + lines[next];
            depth += (lines[next].match(/\{/g) || []).length - (lines[next].match(/\}/g) || []).length;
        }
        for (const call of body.matchAll(/root\.(\w+)\.(\w+)\(/g))
            found.push(`Registry.qml:${index + 1}: ${binding[1]} calls ${call[1]}.${call[2]}()`);
    });
    return found;
}

test("registry bar bindings read service properties, never call service functions", () => {
    assert.deepEqual(barCalls(readFileSync(join(root, "Registry.qml"), "utf8")), []);
    assert.notDeepEqual(barCalls("            barActive: root.audio.privacyActive()"), []);
    assert.notDeepEqual(barCalls("            barTitle: {\n                const privacy = root.audio.privacyLabel().toLowerCase();\n                return privacy;\n            }"), []);
    assert.deepEqual(barCalls("            barActive: root.audio.privacyActive\n            onDismissed: root.power.cancelAction()"), []);
});

test("the guard rejects the patterns step 6 removed", () => {
    for (const [file, line] of [
        ["features/audio/AudioPanel.qml", "    readonly property var panelState: audioService ? Util.parseJson(audioService.stateJson(), {}) : ({})"],
        ["features/media/Media.qml", "            return JSON.parse(osdService.trigger(\"media\", eventText));"],
        ["features/connectivity/ConnectivityPanel.qml", "        networkState = networkService.stateObject();"],
        ["PrivilegeSurface.qml", "            root.refreshFrom(root.privilegeService.stateJson());"]
    ])
        assert.notDeepEqual(violations(file, line), [], line);
    assert.deepEqual(violations("features/brightness/AmbientLight.qml", "    readonly property Settings originalSettings: Settings {}\n    x: originalSettings.stateObject()"), []);
    assert.deepEqual(violations("shell.qml", "            return featureRegistry.audio.stateJson();"), []);
    assert.deepEqual(violations("features/vault/Vault.qml", "            value = JSON.parse(cfgFile.text());"), []);
});