Przeglądaj źródła

Split js/statum.js into core/document/markdown modules

Extract the 3,943-line single-file client into three IIFE modules with
an explicit load-order contract, preserving behaviour verbatim:

- js/statum-core.js: the slot protocol (persistence, X-Statum-Slot request
  machinery, directive application, the realtime SSE/SharedWorker channel),
  the alert/confirm/notify override mechanism, boot, the public API, and the
  new module seam. applyErrorClasses moved in from the render-walk section
  so reportFailure is self-contained. renderAll walks through an installed
  render driver instead of calling render() directly, so core is
  self-sufficient when loaded alone.
- js/statum-document.js: the render walk (loops, if-chains, stm-class.*,
  stm-attribute.*, stm-disabled, stm-text, stm-html, stm-action wiring).
  processInner iterates the seam's ordered handler registry; structural
  attributes stay hardcoded. Registers the five DOM bindings and installs
  the render driver.
- js/statum-markdown.js: the CommonMark 0.31.2 engine (moved verbatim, zero
  DOM references), stm-markdown and stm-h-demotion bindings (ordered after
  stm-html / stm-markdown), the statum.markdown.render/renderTo API sharing
  the binding's code path, and the __STATUM_TEST__ hatch.

The seam: statum.registerAttribute(name, fn, opts) is public; the internal
window.statum._bridge carries evalExpr/childScope/stateScope, renderAll,
loadEntrypoint/performAction, the trigger* handlers, applyErrorClasses and
the registry. after/before constraints resolve into the execution order;
unresolvable anchors warn and keep registration position; duplicate names
warn and are ignored. The resolved order with all three modules loaded is
identical to the previous hardcoded call order. Non-core modules are
guarded IIFEs that console.error and return when core is absent.

Build: src/meson.build now generates ClientCore/ClientDocument/ClientMarkdown
resources (statum-core.js, statum-document.js, statum-markdown.js) and
src/Statum.vala registers them at startup; the statum.js resource name is
gone. js/statum.js deleted. frontend-demo and example/main.html keep their
legacy references for now (a later task rewires demo delivery and the
mkpstm rewrite); mkpstm does not validate resource existence, so the
example still compiles.

Tests: tests/markdown loads core+markdown in order (regressions and the
CommonMark suite unchanged, still 96.4%). New tests/split suite: a fresh
qjs context per scenario covering core-alone, the exact resolved handler
order with and without markdown, the programmatic markdown API, the
core+markdown cherry-pick, the no-core guard, duplicate registration and
unresolvable-constraint warnings.
saddle-ClankerSaddle 3 tygodni temu
rodzic
commit
f1a415f9e8

+ 2 - 0
.gitignore

@@ -1 +1,3 @@
 builddir/
+builddir*/
+web-config.json

+ 1580 - 0
js/statum-core.js

@@ -0,0 +1,1580 @@
+/*!
+ * Statum - client-side state library (core module).
+ *
+ * An HTMX-inspired state layer. The library manages signed "snapshots" of
+ * application state (one per slot type), keeps them fresh via the server's
+ * `transmit_after` / `invalid_after` timestamps, and binds them to the DOM
+ * through `stm-*` attributes. See model.md for the full specification.
+ *
+ * The client ships as modules, each a plain IIFE with no dependencies and no
+ * build step, loaded in this order:
+ *
+ *   1. statum-core.js     - this file: the slot protocol (persistence, the
+ *                           X-Statum-Slot request machinery, directive
+ *                           application, the realtime channel), the
+ *                           alert/confirm/notify overrides, boot, and the
+ *                           module seam (`statum._bridge` /
+ *                           `statum.registerAttribute`). Self-sufficient;
+ *                           creates `window.statum`.
+ *   2. statum-document.js - the render walk and the structural/DOM bindings.
+ *   3. statum-markdown.js - the CommonMark engine and `stm-markdown`.
+ *
+ * Targets modern evergreen browsers (uses fetch, BroadcastChannel,
+ * queueMicrotask, URLSearchParams, FormData).
+ */
+(function () {
+  'use strict';
+
+
+  /** Content-Type used by every Statum directive response. */
+  var STATUM_CONTENT_TYPE = 'application/vnd.statum+json';
+  /** Request/response header carrying one slot's reference (or base64 frame). */
+  var SLOT_HEADER = 'X-Statum-Slot';
+  /** Request header carrying an action's opaque `private` blob. */
+  var PRIVATE_HEADER = 'X-Statum-Private';
+  /** Session-cookie marker used to detect a fresh browser session. */
+  var SESSION_COOKIE = '_statum_sdc';
+  /** BroadcastChannel name used to sync session/device state across tabs. */
+  var CHANNEL_NAME = 'statum';
+  /** localStorage / sessionStorage key prefix for persisted frames. */
+  var STORAGE_PREFIX = 'statum:';
+
+  // ---------------------------------------------------------------------------
+  // Configuration
+  // ---------------------------------------------------------------------------
+
+  /**
+   * Endpoint URLs. These defaults may be overridden per-page with the
+   * `stm-entrypoint` and `stm-slots` attributes on the `<body>` element.
+   *
+   * @type {{entrypointUrl: string, slotsUrl: string}}
+   */
+  var config = {
+    entrypointUrl: '/_statum/entrypoint',
+    slotsUrl: '/_statum/slots',
+    channelUrl: '/_statum/channel',
+    // The realtime worker is embedded in the library as a default resource
+    // (served at /_statum/resource/statum-worker.js); override with stm-worker.
+    workerUrl: '/_statum/resource/statum-worker.js'
+  };
+
+  // ---------------------------------------------------------------------------
+  // State store
+  // ---------------------------------------------------------------------------
+
+  /**
+   * In-memory store, keyed by slot type. Each value is `{frame, snapshot}`
+   * where `snapshot` is the parsed `frame.content`. This map is the single
+   * source of truth for rendering; persistent backends merely hydrate it.
+   *
+   * @type {Map<string, {frame: object, snapshot: object}>}
+   */
+  var store = new Map();
+
+  /** Listeners, keyed by type name. @type {Map<string, Set<Function>>} */
+  var listeners = new Map();
+
+  /**
+   * Idempotency tracking: slot key -> last-applied frame `signature`. Held in
+   * memory only (per tab), so a frame already persisted by another tab still
+   * re-draws a tab whose tracking lags. Entries are dropped on clear so a
+   * replayed frame re-applies.
+   * @type {Map<string, string>}
+   */
+  var signatures = new Map();
+
+  /** Optional UI handlers (set via `statum.on*Handler`). */
+  var handlers = { onConfirm: null, onNotify: null, onError: null };
+
+  /** @type {BroadcastChannel|null} */
+  var channel = null;
+
+  /** Whether {@link init} has already run. */
+  var initialized = false;
+
+  /** Whether the entrypoint has been fetched (guards without pre-entrypoint
+   *  only evaluate after this). */
+  var entrypointLoaded = false;
+
+  /** Set when a guard has triggered a redirect, so further work is skipped. */
+  var guardRedirected = false;
+
+  // ---------------------------------------------------------------------------
+  // Small utilities
+  // ---------------------------------------------------------------------------
+
+  /**
+   * Parse an ISO 8601 timestamp to epoch millis, or `undefined`.
+   * @param {string|undefined} s
+   * @returns {number|undefined}
+   */
+  function parseTime(s) {
+    if (!s) return undefined;
+    var t = new Date(s).getTime();
+    return isNaN(t) ? undefined : t;
+  }
+
+  /**
+   * Base64-encode a UTF-8 string (safe for frames containing non-Latin1 data).
+   * @param {string} str
+   * @returns {string}
+   */
+  function b64encode(str) {
+    var bytes = new TextEncoder().encode(str);
+    var bin = '';
+    var chunk = 0x8000;
+    for (var i = 0; i < bytes.length; i += chunk) {
+      bin += String.fromCharCode.apply(null, bytes.subarray(i, i + chunk));
+    }
+    return btoa(bin);
+  }
+
+  /** Read a cookie value, or `null` if absent. @param {string} name */
+  function getCookie(name) {
+    var escaped = name.replace(/([.$?*|{}()[\]\\/+^])/g, '\\$1');
+    var match = document.cookie.match(new RegExp('(?:^|; )' + escaped + '=([^;]*)'));
+    return match ? decodeURIComponent(match[1]) : null;
+  }
+
+  /** Set a session cookie (no expiry => cleared when the browser closes). */
+  function setCookie(name, value) {
+    document.cookie = name + '=' + encodeURIComponent(value) + '; path=/; SameSite=Lax';
+  }
+
+  // ---------------------------------------------------------------------------
+  // Expression evaluation
+  // ---------------------------------------------------------------------------
+
+  /**
+   * Compiled-expression cache. Expressions are evaluated as JavaScript against
+   * a scope object (the page's HTML is trusted, per the model).
+   * @type {Map<string, Function>}
+   */
+  var exprCache = new Map();
+
+  /**
+   * Wrap a scope for expression evaluation so bare identifiers resolve in a
+   * controlled order: names on the scope (slot types, loop variables,
+   * `stm-def-*` locals) win; names missing from the scope but present on
+   * `globalThis` (`Math`, `parseInt`, `String`, …) forward to that global;
+   * anything else resolves to `undefined` instead of throwing a
+   * `ReferenceError` or leaking an unintended global. The `has` trap claims
+   * every name so `with` never falls through around the proxy, and the inner
+   * try/catch of the compiled expression still turns property access on a
+   * resolved `undefined`/`null` into `undefined` for that expression alone.
+   * @param {object} scope
+   * @returns {Proxy<object>}
+   */
+  function evalScope(scope) {
+    return new Proxy(scope, {
+      has: function () { return true; },
+      get: function (target, name) {
+        if (name in target) return target[name];
+        if (typeof name === 'string' && name in globalThis) return globalThis[name];
+        return undefined;
+      }
+    });
+  }
+
+  /**
+   * Compile (and cache) an expression string into a function of `scope`.
+   * Uses `with` so that arbitrary type names and loop variables are resolved
+   * as bare identifiers. Returns a function that yields `undefined` on any
+   * runtime or compile error.
+   * @param {string} expr
+   * @returns {Function}
+   */
+  function compileExpr(expr) {
+    var cached = exprCache.get(expr);
+    if (cached !== undefined) return cached;
+    var fn;
+    try {
+      // Function-constructor bodies are non-strict by default, so `with` is
+      // permitted. The inner try/catch turns runtime errors (property access
+      // on an unset slot's `undefined`) into `undefined` so a missing path
+      // simply yields no value; missing identifiers already resolve to
+      // `undefined` via the evalScope proxy.
+      fn = new Function('scope', 'with(scope){try{return (' + expr + ');}catch(e){return undefined;}}');
+    } catch (e) {
+      fn = function () { return undefined; };
+    }
+    exprCache.set(expr, fn);
+    return fn;
+  }
+
+  /**
+   * Evaluate an expression against a scope.
+   * @param {string} expr
+   * @param {object} [scope]
+   * @returns {*} `undefined` if the expression is empty or fails.
+   */
+  function evalExpr(expr, scope) {
+    if (expr == null || expr === '') return undefined;
+    try {
+      return compileExpr(expr)(evalScope(scope || {}));
+    } catch (e) {
+      return undefined;
+    }
+  }
+
+  /**
+   * Build a child scope that inherits the parent (so type bindings remain
+   * visible) and adds one own loop variable.
+   * @param {object} parent
+   * @param {string} name
+   * @param {*} value
+   * @returns {object}
+   */
+  function childScope(parent, name, value) {
+    var scope = Object.create(parent || null);
+    scope[name] = value;
+    return scope;
+  }
+
+  // ---------------------------------------------------------------------------
+  // StatumError
+  // ---------------------------------------------------------------------------
+
+  /**
+   * Error type thrown for HTTP failures and `error` directives.
+   * @param {string} [message]
+   * @param {string} [code]
+   * @param {object} [data]
+   */
+  function StatumError(message, code, data) {
+    this.name = 'StatumError';
+    this.message = message || '';
+    this.code = code || undefined;
+    this.data = data || undefined;
+  }
+  StatumError.prototype = Object.create(Error.prototype);
+
+  // ---------------------------------------------------------------------------
+  // UI handlers (confirm / notify / error)
+  // ---------------------------------------------------------------------------
+
+  /**
+   * Run the `notify` directive's default behaviour or the custom
+   * `statum.onNotifyHandler`. The default surfaces the message via `alert()`.
+   * @param {string} [kind] Application-defined category (freeform).
+   * @param {string} [message]
+   */
+  function triggerNotify(kind, message) {
+    var fn = handlers.onNotify;
+    try {
+      if (fn) fn(kind, message);
+      else if (message != null) window.alert(message);
+    } catch (e) { console.error('[statum] notify handler error', e); }
+  }
+
+  /**
+   * Run the `stm-confirm` gate: the custom `statum.onConfirmHandler` if set,
+   * otherwise `window.confirm`. Supports async handlers (custom modals).
+   * @param {string} message
+   * @param {HTMLElement} element
+   * @returns {Promise<boolean>} truthy if the action should proceed.
+   */
+  async function triggerConfirm(message, element) {
+    var fn = handlers.onConfirm;
+    try {
+      if (fn) return !!(await fn(message, element));
+      return !!window.confirm(message);
+    } catch (e) {
+      console.error('[statum] confirm handler error', e);
+      return false;
+    }
+  }
+
+  /**
+   * Run the custom `statum.onErrorHandler`, if set. Returns whether the default
+   * behaviour (promise rejection + `stm-on-error` classes) should proceed: the
+   * handler suppresses the default by returning (or resolving) `false`.
+   * @param {StatumError} error
+   * @param {HTMLElement|null} element
+   * @returns {Promise<boolean>}
+   */
+  async function triggerError(error, element) {
+    var fn = handlers.onError;
+    if (!fn) return true;
+    try {
+      var suppress = await fn(error, element);
+      return suppress !== false;
+    } catch (e) {
+      console.error('[statum] error handler error', e);
+      return true;
+    }
+  }
+
+  /**
+   * Surface a failure: run `triggerError`, and if the default is not
+   * suppressed, apply `stm-on-error` classes (when an origin element exists)
+   * and re-throw so the originating promise rejects.
+   * @param {StatumError} error
+   * @param {HTMLElement|null} element
+   */
+  async function reportFailure(error, element) {
+    if (await triggerError(error, element)) {
+      if (element) applyErrorClasses(element, true);
+      throw error;
+    }
+  }
+
+  // ---------------------------------------------------------------------------
+  // Persistence
+  // ---------------------------------------------------------------------------
+
+  /**
+   * Pick the storage backend for a scope.
+   * @param {string} scope
+   * @returns {Storage|null} `null` for in-memory scopes.
+   */
+  function storageFor(scope) {
+    if (scope === 'device' || scope === 'session') return localStorage;
+    if (scope === 'flow') return sessionStorage;
+    return null; // page / transient
+  }
+
+  /**
+   * Persist a slot's frame to the backend matching its scope, removing any
+   * stale copy from the other backend first (in case the scope changed).
+   * @param {string} type
+   * @param {{frame: object, snapshot: object}} entry
+   */
+  function persistEntry(type, entry) {
+    var scope = entry.snapshot.slot && entry.snapshot.slot.scope;
+    removePersisted(type);
+    var storage = storageFor(scope);
+    if (!storage) return;
+    try {
+      storage.setItem(STORAGE_PREFIX + type, JSON.stringify(entry.frame));
+    } catch (e) {
+      /* storage full or unavailable; remain in-memory only */
+    }
+  }
+
+  /** Remove a persisted frame from both backends. @param {string} type */
+  function removePersisted(type) {
+    try { localStorage.removeItem(STORAGE_PREFIX + type); } catch (e) {}
+    try { sessionStorage.removeItem(STORAGE_PREFIX + type); } catch (e) {}
+  }
+
+  /** Load every persisted frame from a backend into the in-memory store. */
+  function loadFrom(storage) {
+    for (var i = 0; i < storage.length; i++) {
+      var key = storage.key(i);
+      if (!key || key.indexOf(STORAGE_PREFIX) !== 0) continue;
+      try {
+        var frame = JSON.parse(storage.getItem(key));
+        var snapshot = JSON.parse(frame.content);
+        var type = snapshot.slot && snapshot.slot.type;
+        if (type && !store.has(type)) store.set(type, { frame: frame, snapshot: snapshot });
+      } catch (e) {
+        /* corrupt entry: ignore */
+      }
+    }
+  }
+
+  /** Hydrate the store from localStorage and sessionStorage. */
+  function hydrate() {
+    try { loadFrom(localStorage); } catch (e) {}
+    try { loadFrom(sessionStorage); } catch (e) {}
+  }
+
+  // ---------------------------------------------------------------------------
+  // Session-cookie initialization
+  // ---------------------------------------------------------------------------
+
+  /**
+   * Detect a fresh browser session using the `_statum_sdc` session cookie.
+   * On a fresh session, clear all `session`-scoped persisted frames, then set
+   * the marker. Session cookies are shared across tabs, so a tab opened
+   * mid-session sees the marker and leaves session data intact.
+   */
+  function initSession() {
+    if (getCookie(SESSION_COOKIE) !== null) return;
+    clearSessionSlotsFromStorage();
+    setCookie(SESSION_COOKIE, '1');
+  }
+
+  /** Remove all `session`-scoped frames from localStorage. */
+  function clearSessionSlotsFromStorage() {
+    var toRemove = [];
+    for (var i = 0; i < localStorage.length; i++) {
+      var key = localStorage.key(i);
+      if (!key || key.indexOf(STORAGE_PREFIX) !== 0) continue;
+      try {
+        var frame = JSON.parse(localStorage.getItem(key));
+        var snapshot = JSON.parse(frame.content);
+        if (snapshot.slot && snapshot.slot.scope === 'session') toRemove.push(key);
+      } catch (e) {}
+    }
+    for (var j = 0; j < toRemove.length; j++) localStorage.removeItem(toRemove[j]);
+  }
+
+  // ---------------------------------------------------------------------------
+  // Listeners & cross-tab broadcast
+  // ---------------------------------------------------------------------------
+
+  /**
+   * Fire all listeners for a type. (Renamed from `notify` to avoid confusion
+   * with the `notify` directive.)
+   * @param {string} type
+   * @param {object|null} frame
+   * @param {object|null} snapshot
+   */
+  function fireListeners(type, frame, snapshot) {
+    var set = listeners.get(type);
+    if (!set) return;
+    var event = { type: type, frame: frame, snapshot: snapshot };
+    set.forEach(function (cb) {
+      try { cb(event); } catch (e) { console.error('[statum] listener error', e); }
+    });
+  }
+
+  /**
+   * Broadcast a state change to other tabs. Only `session`/`device` scopes are
+   * shared (flow/page/transient are per-tab).
+   * @param {object} message
+   * @param {string} [scope]
+   */
+  function broadcast(message, scope) {
+    if (!channel) return;
+    if (scope !== 'session' && scope !== 'device') return;
+    try { channel.postMessage(message); } catch (e) {}
+  }
+
+  /**
+   * Broadcast a message to other tabs regardless of slot scope. Used to relay
+   * realtime (live) events so they reach every tab, not just session/device
+   * ones.
+   */
+  function broadcastAlways(message) {
+    if (!channel) return;
+    try { channel.postMessage(message); } catch (e) {}
+  }
+
+  /** Open the BroadcastChannel and wire inbound messages. */
+  function setupChannel() {
+    if (typeof BroadcastChannel === 'undefined') return;
+    try {
+      channel = new BroadcastChannel(CHANNEL_NAME);
+    } catch (e) {
+      channel = null;
+      return;
+    }
+    channel.onmessage = function (ev) {
+      var msg = ev.data;
+      if (!msg) return;
+      if (msg.kind === 'set' && msg.frame) {
+        try {
+          var snapshot = JSON.parse(msg.frame.content);
+          var type = snapshot.slot && snapshot.slot.type;
+          if (type && commitSet(msg.frame, snapshot, type, false)) renderAll();
+        } catch (e) { /* ignore malformed */ }
+      } else if (msg.kind === 'clear') {
+        var t = msg.type;
+        if (!t && msg.key != null) {
+          store.forEach(function (entry, type) {
+            if (entry.snapshot.slot && entry.snapshot.slot.key === msg.key) t = type;
+          });
+        }
+        if (t) clearType(t, { broadcast: false });
+        else if (msg.key != null) signatures.delete(msg.key);
+        renderAll();
+      }
+    };
+  }
+
+  // ---------------------------------------------------------------------------
+  // State mutation
+  // ---------------------------------------------------------------------------
+
+  /**
+   * Remove a type from the store, un-persist it, drop its idempotency entry,
+   * fire listeners, and (optionally) broadcast the clear to other tabs.
+   * @param {string} type
+   * @param {{broadcast?: boolean}} [opts]
+   */
+  function clearType(type, opts) {
+    var entry = store.get(type);
+    if (!entry) return;
+    var scope = entry.snapshot.slot && entry.snapshot.slot.scope;
+    var key = entry.snapshot.slot && entry.snapshot.slot.key;
+    store.delete(type);
+    removePersisted(type);
+    if (key) signatures.delete(key);
+    fireListeners(type, null, null);
+    if (opts && opts.broadcast) broadcast({ kind: 'clear', key: key, type: type }, scope);
+  }
+
+  /**
+   * Resolve a slot key to its type and clear it. Used by the `clear` directive
+   * (keyed) and by live `clear` events.
+   * @param {string} key
+   * @param {boolean} [broadcast]
+   */
+  function clearByKey(key, broadcast) {
+    var typeToRemove = null;
+    store.forEach(function (entry, type) {
+      if (entry.snapshot.slot && entry.snapshot.slot.key === key) typeToRemove = type;
+    });
+    if (typeToRemove) clearType(typeToRemove, { broadcast: !!broadcast });
+    else if (key) signatures.delete(key);
+  }
+
+  /**
+   * Resolve a frame signature to its slot type and clear it. Used by the
+   * `invalidate` directive, which references a signature (not a key) because the
+   * server reports a bad signature without trusting the frame's content.
+   * @param {string} signature
+   * @param {boolean} [broadcast]
+   */
+  function clearBySignature(signature, broadcast) {
+    var typeToRemove = null;
+    store.forEach(function (entry, type) {
+      if (entry.frame && entry.frame.signature === signature) typeToRemove = type;
+    });
+    if (typeToRemove) clearType(typeToRemove, { broadcast: !!broadcast });
+    else if (signature) signatures.delete(signature);
+  }
+
+  /**
+   * Commit a `set` to the in-memory store, persist it, and fire listeners.
+   * Idempotent: if the frame's `signature` matches the last-applied signature
+   * for this slot (tracked in {@link signatures}), nothing happens and `false`
+   * is returned. When `doBroadcast` is true the set is forwarded to other tabs
+   * via the scope-gated broadcast (session/device only).
+   * @param {object} frame
+   * @param {object} snapshot
+   * @param {string} type
+   * @param {boolean} doBroadcast
+   * @returns {boolean} `true` if state changed.
+   */
+  function commitSet(frame, snapshot, type, doBroadcast) {
+    var key = snapshot.slot && snapshot.slot.key;
+    var sig = frame.signature;
+    if (key && sig !== undefined && signatures.get(key) === sig) return false;
+    var entry = { frame: frame, snapshot: snapshot };
+    store.set(type, entry);
+    persistEntry(type, entry);
+    fireListeners(type, frame, snapshot);
+    if (key && sig !== undefined) signatures.set(key, sig);
+    if (doBroadcast) {
+      var scope = snapshot.slot && snapshot.slot.scope;
+      broadcast({ kind: 'set', frame: frame }, scope);
+    }
+    return true;
+  }
+
+  /**
+   * Apply a `set` directive: store/refresh a slot's snapshot (idempotently),
+   * broadcasting to other tabs.
+   * @param {object} directive `{ snapshot_frame }`
+   */
+  function applySet(directive) {
+    var frame = directive.snapshot_frame;
+    if (!frame || !frame.content) return;
+    var snapshot;
+    try { snapshot = JSON.parse(frame.content); } catch (e) { return; }
+    var type = snapshot.slot && snapshot.slot.type;
+    if (!type) return;
+    commitSet(frame, snapshot, type, true);
+  }
+
+  /**
+   * Apply a `clear` directive. The directive carries a slot key, so the type
+   * holding that key is resolved and removed.
+   * @param {object} directive `{ key }`
+   */
+  function applyClear(directive) {
+    if (directive.key == null) return;
+    clearByKey(directive.key, true);
+  }
+
+  /**
+   * Apply a live `set` event received over the realtime channel. The frame is
+   * committed (idempotently) and, when new, broadcast to sibling tabs via the
+   * scope-agnostic {@link broadcastAlways} so every tab sees it regardless of
+   * which (or how many) tabs hold a subscription.
+   * @param {object} frame
+   */
+  function applyRemoteSet(frame) {
+    try {
+      var snapshot = JSON.parse(frame.content);
+      var type = snapshot.slot && snapshot.slot.type;
+      if (!type) return;
+      if (commitSet(frame, snapshot, type, false)) {
+        broadcastAlways({ kind: 'set', frame: frame });
+        renderAll();
+      }
+    } catch (e) { /* malformed frame */ }
+  }
+
+  /** Apply a live `clear` event received over the realtime channel. */
+  function applyRemoteClear(key) {
+    if (key == null) return;
+    signatures.delete(key);
+    clearByKey(key, false);
+    broadcastAlways({ kind: 'clear', key: key });
+    renderAll();
+  }
+
+  // ---------------------------------------------------------------------------
+  // Snapshot freshness & request headers
+  // ---------------------------------------------------------------------------
+
+  /**
+   * Categorize a held snapshot relative to the current time.
+   * @returns {'silent'|'always'|'invalid'|'stale'|'fresh'}
+   *   - `silent`: unidirectional (`transmit_after` undefined) - never sent.
+   *   - `always`: `transmit_after === as_at` - send the base64 frame each time.
+   *   - `invalid`: past `invalid_after` - drop and refetch.
+   *   - `stale`: past `transmit_after` but not yet invalid - pre-flight first.
+   *   - `fresh`: still cached server-side - send the `as_at` reference.
+   */
+  function entryCategory(entry) {
+    var snap = entry.snapshot;
+    var transmit = snap.transmit_after;
+    if (transmit === undefined || transmit === null) return 'silent';
+    if (transmit === snap.as_at) return 'always';
+    var now = Date.now();
+    var invalidAt = parseTime(snap.invalid_after);
+    var transmitAt = parseTime(transmit);
+    if (invalidAt !== undefined && now >= invalidAt) return 'invalid';
+    if (transmitAt !== undefined && now >= transmitAt) return 'stale';
+    return 'fresh';
+  }
+
+  /**
+   * Drop locally-invalid snapshots and pre-flight any stale ones. Pre-flighting
+   * posts the stale frames to the slot endpoint and applies the returned `set`
+   * directives, refreshing their `as_at` values before the real request runs.
+   *
+   * Single-flight: concurrent callers share one in-flight preparation.
+   * @returns {Promise<void>}
+   */
+  var preparePromise = null;
+  function prepareSlots() {
+    if (preparePromise) return preparePromise;
+    preparePromise = doPrepareSlots().then(function () {
+      preparePromise = null;
+    }, function () {
+      preparePromise = null;
+    });
+    return preparePromise;
+  }
+
+  async function doPrepareSlots() {
+    var stale = [];
+    store.forEach(function (entry, type) {
+      var cat = entryCategory(entry);
+      if (cat === 'invalid') {
+        clearType(type, { broadcast: false });
+      } else if (cat === 'stale') {
+        stale.push(entry.frame);
+      }
+    });
+    if (stale.length) {
+      var directives = await postSlots(stale);
+      var pfResult = applyDirectives(directives, { originElement: null });
+      executeTerminal(pfResult);
+    }
+  }
+
+  /**
+   * Build the `X-Statum-Slot` header values for every held slot, using the
+   * freshness rules. Assumes {@link prepareSlots} has just run.
+   * @returns {string[]}
+   */
+  function buildSlotHeaders() {
+    var headers = [];
+    store.forEach(function (entry) {
+      var snap = entry.snapshot;
+      var cat = entryCategory(entry);
+      if (cat === 'silent' || cat === 'invalid') return;
+      if (cat === 'always') {
+        headers.push(b64encode(JSON.stringify(entry.frame)));
+      } else {
+        headers.push('key=' + snap.slot.key + '; as_at=' + snap.as_at);
+      }
+    });
+    return headers;
+  }
+
+  /**
+   * Collect the current frames held for the given slot keys, in the order the
+   * keys are first supplied. Used by the `transmit` directive (which forces a
+   * slot's frame to be posted as if its `transmit_after` had elapsed). Keys the
+   * client does not currently hold are skipped.
+   * @param {string[]} keys
+   * @returns {object[]}
+   */
+  function collectFramesForKeys(keys) {
+    var keySet = Object.create(null);
+    for (var i = 0; i < keys.length; i++) keySet[keys[i]] = true;
+    var frames = [];
+    store.forEach(function (entry) {
+      var key = entry.snapshot.slot && entry.snapshot.slot.key;
+      if (key && keySet[key]) {
+        frames.push(entry.frame);
+        delete keySet[key];
+      }
+    });
+    return frames;
+  }
+
+  // ---------------------------------------------------------------------------
+  // HTTP helpers
+  // ---------------------------------------------------------------------------
+
+  /** True if a response is a Statum directive response. */
+  function isStatum(res) {
+    return (res.headers.get('Content-Type') || '').indexOf(STATUM_CONTENT_TYPE) !== -1;
+  }
+
+  /**
+   * POST an array of frames to the slot endpoint (the pre-flight target) and
+   * return its directive array. This request intentionally carries no slot
+   * headers (it is itself the refresh).
+   * @param {object[]} frames
+   * @returns {Promise<object[]>}
+   */
+  async function postSlots(frames) {
+    var headers = new Headers();
+    headers.set('Accept', STATUM_CONTENT_TYPE);
+    headers.set('Content-Type', 'application/json');
+    var res = await fetch(config.slotsUrl, {
+      method: 'POST',
+      headers: headers,
+      body: JSON.stringify(frames),
+      credentials: 'same-origin'
+    });
+    if (!isStatum(res)) return [];
+    try { return await res.json(); } catch (e) { return []; }
+  }
+
+  /**
+   * Apply the non-terminal directives from a response (set/clear/subscribe/
+   * unsubscribe/notify/transmit-collection), then `render`.
+   *
+   * Terminal directives (`navigate`, `post`), error directives, and any
+   * transmit/retry intent are collected on the returned result rather than
+   * executed here: {@link handleResponse} performs the asynchronous
+   * transmission (and optional retry) and then runs terminal navigation, so
+   * that a `transmit` with `retry` can re-issue the request before the page is
+   * navigated away.
+   * @param {object[]} directives
+   * @param {{originElement?: HTMLElement}} [ctx]
+   * @returns {{errors: StatumError[], transmitKeys: string[], retry: boolean, navigate: object|null, post: object|null}}
+   */
+  function applyDirectives(directives, ctx) {
+    var result = { errors: [], transmitKeys: [], retry: false, navigate: null, post: null, formSubmits: [], formResets: [] };
+    var list = Array.isArray(directives) ? directives : [];
+
+    for (var i = 0; i < list.length; i++) {
+      var d = list[i];
+      if (!d || typeof d !== 'object') continue;
+      switch (d.type) {
+        case 'set': applySet(d); break;
+        case 'clear': applyClear(d); break;
+        case 'invalidate':
+          if (d.signature != null) {
+            console.warn('[statum] server could not verify slot frame ' + d.signature + '; clearing it');
+            clearBySignature(d.signature, true);
+          }
+          break;
+        case 'subscribe': channelSubscribe(d.key); break;
+        case 'unsubscribe': channelUnsubscribe(d.key); break;
+        case 'notify': triggerNotify(d.kind, d.message); break;
+        case 'transmit':
+          if (d.key != null) {
+            if (result.transmitKeys.indexOf(d.key) === -1) result.transmitKeys.push(d.key);
+            if (d.retry) result.retry = true;
+          }
+          break;
+        case 'error':
+          {
+            var err = new StatumError(d.message, d.code, d.data);
+            var detail = d.code ? (d.message + ' [' + d.code + ']') : d.message;
+            console.error('[statum] error directive: ' + (detail || '(no message)'));
+            result.errors.push(err);
+          }
+          break;
+        case 'navigate': result.navigate = d; break;
+        case 'post': result.post = d; break;
+        case 'form-submit': result.formSubmits.push(d); break;
+        case 'form-reset': result.formResets.push(d); break;
+      }
+    }
+
+    renderAll();
+    return result;
+  }
+
+  /** Execute the terminal directives collected by {@link applyDirectives}. */
+  function executeTerminal(result) {
+    result.formResets.forEach(doFormReset);
+    result.formSubmits.forEach(doFormSubmit);
+    if (result.navigate) doNavigate(result.navigate);
+    if (result.post) doPost(result.post);
+  }
+
+  /** Execute a `form-submit` directive: optionally override action/method, then submit. */
+  function doFormSubmit(d) {
+    var form = document.getElementById(d.form);
+    if (form) {
+      if (d.action) form.setAttribute('action', d.action);
+      if (d.method) form.setAttribute('method', d.method);
+      form.submit();
+    }
+  }
+
+  /** Execute a `form-reset` directive. */
+  function doFormReset(d) {
+    var form = document.getElementById(d.form);
+    if (form) form.reset();
+  }
+
+  /** Execute a `navigate` directive as a full page load. */
+  function doNavigate(d) {
+    if (d.uri) window.location.href = d.uri;
+  }
+
+  /** Execute a `post` directive as a real (navigating) form POST. */
+  function doPost(d) {
+    if (!d.uri) return;
+    var form = document.createElement('form');
+    form.method = 'POST';
+    form.action = d.uri;
+    form.style.display = 'none';
+    var data = d.data || {};
+    Object.keys(data).forEach(function (name) {
+      var input = document.createElement('input');
+      input.type = 'hidden';
+      input.name = name;
+      input.value = data[name] == null ? '' : String(data[name]);
+      form.appendChild(input);
+    });
+    document.body.appendChild(form);
+    form.submit();
+  }
+
+  /**
+   * Handle a fetch response: if it is a Statum response, apply its directives;
+   * otherwise throw on HTTP errors and no-op on other successful responses.
+   *
+   * Directive ordering: non-terminal directives are applied and the page
+   * rendered; then any `transmit` directives force their slot frames to be
+   * posted (applying the directives the slot endpoint returns); then, if a
+   * transmit requested a retry, the originating request (`ctx.retry`) is
+   * re-issued and this response's terminal directives and errors are skipped.
+   * Otherwise terminal navigation runs, then error directives are surfaced.
+   * @param {Response} res
+   * @param {{originElement?: HTMLElement, retry?: Function}} [ctx]
+   */
+  async function handleResponse(res, ctx) {
+    var el = ctx && ctx.originElement;
+    if (!isStatum(res)) {
+      if (!res.ok) await reportFailure(new StatumError('HTTP ' + res.status), el);
+      return;
+    }
+    var directives;
+    try { directives = await res.json(); } catch (e) { directives = []; }
+    var result = applyDirectives(directives, ctx);
+
+    if (result.transmitKeys && result.transmitKeys.length) {
+      var frames = collectFramesForKeys(result.transmitKeys);
+      if (frames.length) {
+        var txDirectives = await postSlots(frames);
+        applyDirectives(txDirectives, { originElement: el });
+      }
+    }
+
+    if (result.retry && ctx && typeof ctx.retry === 'function') {
+      await ctx.retry();
+      return;
+    }
+
+    executeTerminal(result);
+
+    var errors = result.errors || [];
+    for (var i = 0; i < errors.length; i++) {
+      await reportFailure(errors[i], el);
+    }
+  }
+
+  // ---------------------------------------------------------------------------
+  // Entrypoint & action requests
+  // ---------------------------------------------------------------------------
+
+  /**
+   * Fetch the entrypoint for the current URL, applying its directives. Carries
+   * slot headers (and pre-flights) like any other request. The request is
+   * wrapped in an `attempt` closure passed as the response `retry` callback, so
+   * a `transmit` directive with `retry` can re-issue it after transmission.
+   * @returns {Promise<void>}
+   */
+  function loadEntrypoint() {
+    if (guardRedirected) return Promise.resolve();
+    // From this point on guards are "post-entrypoint" (all of them evaluate).
+    entrypointLoaded = true;
+    var attempt = async function () {
+      await prepareSlots();
+      var headers = new Headers();
+      headers.set('Accept', STATUM_CONTENT_TYPE);
+      buildSlotHeaders().forEach(function (v) { headers.append(SLOT_HEADER, v); });
+      var url = config.entrypointUrl + '?uri=' + encodeURIComponent(window.location.href);
+      var res = await fetch(url, { headers: headers, credentials: 'same-origin' });
+      await handleResponse(res, { originElement: null, retry: attempt });
+    };
+    return attempt();
+  }
+
+  /**
+   * Perform an action request.
+   *
+   * The request is wrapped in an `attempt` closure passed as the response
+   * `retry` callback, so a `transmit` directive with `retry` can re-issue the
+   * same action after the transmission (rebuilding headers from current state).
+   *
+   * @param {object} action `{ uri, method, private }`
+   * @param {object} [data] Key/value parameters. Encoded as query string for
+   *   GET/HEAD, otherwise as `application/x-www-form-urlencoded`.
+   * @param {HTMLElement} [originElement] Element that triggered the action, so
+   *   that `stm-on-error` classes can be applied on an `error` directive.
+   * @returns {Promise<void>} Resolves once the request completes and its
+   *   directives have run; rejects on HTTP failure or an `error` directive.
+   */
+  function performAction(action, data, originElement) {
+    var attempt = async function () {
+      await prepareSlots();
+      var headers = new Headers();
+      headers.set('Accept', STATUM_CONTENT_TYPE);
+      buildSlotHeaders().forEach(function (v) { headers.append(SLOT_HEADER, v); });
+      if (action.private) headers.set(PRIVATE_HEADER, action.private);
+
+      var method = (action.method || 'GET').toUpperCase();
+      var params = data || {};
+      var init = { method: method, headers: headers, credentials: 'same-origin' };
+      var url = action.uri;
+
+      if (method === 'GET' || method === 'HEAD') {
+        var qs = new URLSearchParams(params).toString();
+        if (qs) url += (url.indexOf('?') !== -1 ? '&' : '?') + qs;
+      } else {
+        init.body = new URLSearchParams(params).toString();
+        headers.set('Content-Type', 'application/x-www-form-urlencoded');
+      }
+
+      var res;
+      try {
+        res = await fetch(url, init);
+      } catch (networkErr) {
+        await reportFailure(new StatumError('Network error'), originElement);
+        return;
+      }
+      await handleResponse(res, { originElement: originElement, retry: attempt });
+    };
+    return attempt();
+  }
+
+  // ---------------------------------------------------------------------------
+  // Realtime channel (subscribe/unsubscribe directives)
+  // ---------------------------------------------------------------------------
+
+  /**
+   * Per-tab fallback engine, used when `SharedWorker` is unavailable. Owns an
+   * `EventSource`, reads the channel id from the first `event: channel`,
+   * reference-counts slot keys within this tab, PATCHes subscription changes,
+   * applies incoming set/clear events (broadcasting them to siblings), and
+   * closes the stream once it has no subscriptions.
+   */
+  function createFallbackEngine() {
+    var es = null;
+    var channelId = null;
+    var refs = new Map(); // slotKey -> count
+    var pending = { subscribe: [], unsubscribe: [] };
+    var patchScheduled = false;
+
+    function openStream() {
+      if (es) return;
+      try { es = new EventSource(config.channelUrl); }
+      catch (e) { es = null; return; }
+      es.addEventListener('channel', function (ev) { channelId = ev.data; flushPatch(); });
+      es.addEventListener('set', function (ev) {
+        try { applyRemoteSet(JSON.parse(ev.data)); } catch (e) {}
+      });
+      es.addEventListener('clear', function (ev) { applyRemoteClear(ev.data); });
+      es.onerror = function () { /* EventSource auto-reconnects */ };
+    }
+
+    function closeStream() {
+      if (es) { try { es.close(); } catch (e) {} es = null; }
+      channelId = null;
+    }
+
+    function schedulePatch() {
+      if (patchScheduled) return;
+      patchScheduled = true;
+      Promise.resolve().then(function () { patchScheduled = false; flushPatch(); });
+    }
+
+    function flushPatch() {
+      if (!channelId) return;
+      var sub = pending.subscribe, uns = pending.unsubscribe;
+      if (!sub.length && !uns.length) return;
+      pending = { subscribe: [], unsubscribe: [] };
+      var body = {};
+      if (sub.length) body.subscribe = sub;
+      if (uns.length) body.unsubscribe = uns;
+      try {
+        fetch(config.channelUrl + '/' + encodeURIComponent(channelId), {
+          method: 'PATCH',
+          headers: { 'Content-Type': 'application/json' },
+          credentials: 'same-origin',
+          body: JSON.stringify(body)
+        }).catch(function () {});
+      } catch (e) {}
+    }
+
+    return {
+      subscribe: function (key) {
+        var c = refs.get(key) || 0;
+        refs.set(key, c + 1);
+        if (c === 0) { openStream(); pending.subscribe.push(key); schedulePatch(); }
+      },
+      unsubscribe: function (key) {
+        var c = refs.get(key) || 0;
+        if (c <= 0) return;
+        if (c - 1 <= 0) {
+          refs.delete(key);
+          pending.unsubscribe.push(key);
+          schedulePatch();
+          if (refs.size === 0) setTimeout(function () { if (refs.size === 0) closeStream(); }, 0);
+        } else {
+          refs.set(key, c - 1);
+        }
+      }
+    };
+  }
+
+  /**
+   * Channel manager. Prefers a `SharedWorker` (which owns the single SSE
+   * connection, reference-counts subscriptions across tabs, and relays events
+   * through the cross-tab `BroadcastChannel`); falls back to a per-tab
+   * `EventSource` engine when `SharedWorker` is unavailable or the worker
+   * script fails to load. Tracks the true per-slot subscription count so it can
+   * replay active subscriptions into the fallback on a mid-session switch.
+   */
+  function createChannelManager() {
+    var port = null;
+    var workerObj = null;
+    var fallback = null;
+    var mode = null; // 'worker' | 'fallback' | null
+    var counts = new Map(); // slotKey -> count (true subscription state)
+
+    function switchToFallback() {
+      if (mode === 'fallback') return;
+      mode = 'fallback';
+      port = null;
+      workerObj = null;
+      fallback = createFallbackEngine();
+      counts.forEach(function (c, key) {
+        for (var i = 0; i < c; i++) fallback.subscribe(key);
+      });
+    }
+
+    function ensure() {
+      if (mode !== null) return;
+      if (typeof SharedWorker !== 'undefined') {
+        try {
+          workerObj = new SharedWorker(config.workerUrl);
+          port = workerObj.port;
+          port.start();
+          port.postMessage({ op: 'init', url: config.channelUrl });
+          // The worker delivers events via the BroadcastChannel, so nothing is
+          // required on this port beyond command messages.
+          port.onmessage = function () {};
+          workerObj.onerror = function () {
+            console.warn('[statum] realtime worker failed; falling back to per-tab channel');
+            switchToFallback();
+          };
+          window.addEventListener('pagehide', function () {
+            if (mode === 'worker' && port) {
+              try { port.postMessage({ op: 'disconnect' }); } catch (e) {}
+            }
+          });
+          mode = 'worker';
+          return;
+        } catch (e) { workerObj = null; port = null; }
+      }
+      switchToFallback();
+    }
+
+    return {
+      subscribe: function (key) {
+        if (key == null) return;
+        ensure();
+        counts.set(key, (counts.get(key) || 0) + 1);
+        if (mode === 'worker') { try { port.postMessage({ op: 'subscribe', key: key }); } catch (e) {} }
+        else fallback.subscribe(key);
+      },
+      unsubscribe: function (key) {
+        if (key == null) return;
+        var c = (counts.get(key) || 0) - 1;
+        if (c <= 0) counts.delete(key); else counts.set(key, c);
+        ensure();
+        if (mode === 'worker') { try { port.postMessage({ op: 'unsubscribe', key: key }); } catch (e) {} }
+        else fallback.unsubscribe(key);
+      }
+    };
+  }
+
+  var channelManager = createChannelManager();
+
+  function channelSubscribe(key) { channelManager.subscribe(key); }
+  function channelUnsubscribe(key) { channelManager.unsubscribe(key); }
+
+  // ---------------------------------------------------------------------------
+  // Error-state classes
+  // ---------------------------------------------------------------------------
+  // (Moved from the render-walk section in statum-document.js so that
+  // reportFailure above is self-contained without that module.)
+
+
+  /** Apply or remove `stm-on-error` classes on an action element. */
+  function applyErrorClasses(el, on) {
+    if (!el || !el.hasAttribute || !el.hasAttribute('stm-on-error')) return;
+    var classes = (el.getAttribute('stm-on-error') || '').split(/\s+/).filter(Boolean);
+    classes.forEach(function (c) { on ? el.classList.add(c) : el.classList.remove(c); });
+  }
+
+  // ---------------------------------------------------------------------------
+  // Module seam: attribute-handler registry + render driver
+  // ---------------------------------------------------------------------------
+  //
+  // statum-core.js is self-sufficient: it owns the slot protocol, the UI
+  // handler overrides and the boot sequence, and never references the other
+  // modules. statum-document.js (the render walk) and statum-markdown.js
+  // (the CommonMark engine) load AFTER core and register through this seam.
+  //
+  // `_bridge` (underscore = private by convention, like `_testMarkdown`) is
+  // the internal cross-module surface; `statum.registerAttribute` is the
+  // public entry point module authors use.
+
+  /**
+   * Resolved execution order of the per-element `stm-*` bindings: an ordered
+   * list of `{name, fn, prefix}`. The render walk (statum-document.js)
+   * iterates it for every element. A throwing handler aborts that render
+   * cycle through renderAll's try/catch, exactly as the previous hardcoded
+   * call chain did, so handlers get no per-handler try/catch here.
+   * @type {Array<{name: string, fn: Function, prefix: boolean}>}
+   */
+  var attributeHandlers = [];
+
+  /**
+   * Register a handler for an `stm-*` attribute.
+   *
+   * `name` is either an exact attribute name (`'stm-disabled'`) or, when it
+   * ends with a dot, a prefix matcher (`'stm-class.'` matches any
+   * `stm-class.{name}`). The handler is called once per element per render
+   * cycle when the element carries at least one matching attribute; it then
+   * iterates the element's attributes itself (several may match a prefix).
+   *
+   * `opts.after` / `opts.before` name another registered attribute and the
+   * handler is inserted directly after / before it. A constraint naming an
+   * unregistered attribute warns and keeps plain registration order, so
+   * loading a module early cannot break the page. Registering the same name
+   * twice warns and ignores the second handler.
+   *
+   * @param {string} name
+   * @param {Function} fn `fn(el, scope)`
+   * @param {{after?: string, before?: string}} [opts]
+   */
+  function registerAttribute(name, fn, opts) {
+    if (typeof name !== 'string' || !name || typeof fn !== 'function') {
+      console.warn('[statum] registerAttribute: expected an attribute name and a handler function');
+      return;
+    }
+    for (var i = 0; i < attributeHandlers.length; i++) {
+      if (attributeHandlers[i].name === name) {
+        console.warn('[statum] registerAttribute: "' + name + '" is already registered; ignoring');
+        return;
+      }
+    }
+    var entry = { name: name, fn: fn, prefix: name.charAt(name.length - 1) === '.' };
+    var anchor = opts && (opts.after || opts.before);
+    var at = anchor ? handlerIndex(anchor) : -1;
+    if (anchor && at === -1) {
+      console.warn('[statum] registerAttribute: "' + anchor +
+        '" is not registered; keeping registration order for "' + name + '"');
+    }
+    if (at !== -1 && opts.after) at += 1; // insert directly after the anchor
+    if (at === -1) attributeHandlers.push(entry);
+    else attributeHandlers.splice(at, 0, entry);
+  }
+
+  /** Position of a registered handler by name, or -1. */
+  function handlerIndex(name) {
+    for (var i = 0; i < attributeHandlers.length; i++) {
+      if (attributeHandlers[i].name === name) return i;
+    }
+    return -1;
+  }
+
+  /**
+   * The render driver: installed by statum-document.js at load time, called
+   * by renderAll to walk the document. When absent (core loaded alone)
+   * render cycles still run the evaluate hooks and guards but skip the DOM
+   * walk.
+   * @type {Function|null}
+   */
+  var renderDriver = null;
+
+  /** Install the render driver. @param {Function} fn `fn(scope)` */
+  function installRenderDriver(fn) {
+    if (typeof fn === 'function') renderDriver = fn;
+  }
+
+  /**
+   * The module bridge: everything the other modules need from core (and the
+   * one thing core needs from them, the render driver) crosses here. The
+   * evaluate hooks stay core-private on purpose — no other module needs
+   * them; modules register attribute handlers instead.
+   */
+  var bridge = {
+    /** Expression machinery (core-owned). */
+    evalExpr: evalExpr,
+    childScope: childScope,
+    stateScope: stateScope,
+    /** Render cycle + requests. */
+    renderAll: renderAll,
+    loadEntrypoint: loadEntrypoint,
+    performAction: performAction,
+    /** UI handler overrides (runElementAction gates on confirm). */
+    triggerConfirm: triggerConfirm,
+    triggerNotify: triggerNotify,
+    triggerError: triggerError,
+    handlers: handlers,
+    /** Error-state classes for action elements. */
+    applyErrorClasses: applyErrorClasses,
+    /** The seam itself. */
+    registerAttribute: registerAttribute,
+    attributeHandlers: attributeHandlers,
+    installRenderDriver: installRenderDriver
+  };
+
+
+  /**
+   * Evaluate every `<link rel="stm-guard">` in the document head. A guard whose
+   * `require` predicate is false redirects the page to its `href`.
+   *
+   * Guards marked `pre-entrypoint` are evaluated on every cycle (including the
+   * initial, pre-entrypoint render, which uses only hydrated state); guards
+   * without it are evaluated only once the entrypoint has loaded. On every later
+   * evaluate cycle (set/clear) all guards are re-checked, so logging out, for
+   * example, can bounce the user off a guarded page.
+   */
+  function evaluateGuards() {
+    if (guardRedirected) return;
+    var scope = stateScope();
+    var guards = document.querySelectorAll('link[rel~="stm-guard"]');
+    for (var i = 0; i < guards.length; i++) {
+      var g = guards[i];
+      var preEntrypoint = g.hasAttribute('pre-entrypoint');
+      if (!preEntrypoint && !entrypointLoaded) continue;
+      var require = g.getAttribute('require');
+      if (!require) continue;
+      if (!evalExpr(require, scope)) {
+        guardRedirected = true;
+        var href = g.getAttribute('href') || '/';
+        console.warn('[statum] guard failed (' + require + '); redirecting to ' + href);
+        window.location.href = href;
+        return;
+      }
+    }
+  }
+
+  // ---------------------------------------------------------------------------
+  // Evaluation hooks (no-arg callbacks before/after each render cycle)
+  // ---------------------------------------------------------------------------
+
+  var beforeHooks = [];
+  var afterHooks = [];
+
+  /** Re-render the whole document against the current state. */
+  function renderAll() {
+    if (guardRedirected) return;
+    beforeHooks.forEach(function (fn) { try { fn(); } catch (e) { console.error('[statum] beforeEvaluate hook error', e); } });
+    try {
+      // The DOM walk lives in statum-document.js and is installed through
+      // the seam; without it the cycle still runs hooks and guards.
+      if (renderDriver) renderDriver(stateScope());
+    }
+    catch (e) { console.error('[statum] render error', e); }
+    afterHooks.forEach(function (fn) { try { fn(); } catch (e) { console.error('[statum] afterEvaluate hook error', e); } });
+    evaluateGuards();
+  }
+
+
+  // ---------------------------------------------------------------------------
+  // Boot visibility (stm-preloader / stm-content)
+  // ---------------------------------------------------------------------------
+
+  /**
+   * Toggle pre/post-entrypoint visibility with the `hidden` attribute. While
+   * loading, `stm-preloader` elements are shown and `stm-content` elements
+   * hidden; once ready, the reverse.
+   *
+   * To avoid a flash of un-bound template before the script runs, authors may
+   * pre-set `hidden` directly on `stm-content` in the HTML (e.g.
+   * `<div stm-content hidden>`); the library removes it once ready. The library
+   * also sets `hidden` itself during loading as a fallback for authors who do
+   * not pre-set it.
+   * @param {boolean} ready
+   */
+  function setBootState(ready) {
+    var preloaders = document.querySelectorAll('[stm-preloader]');
+    var contents = document.querySelectorAll('[stm-content]');
+    for (var i = 0; i < preloaders.length; i++) {
+      ready ? preloaders[i].setAttribute('hidden', '') : preloaders[i].removeAttribute('hidden');
+    }
+    for (var j = 0; j < contents.length; j++) {
+      ready ? contents[j].removeAttribute('hidden') : contents[j].setAttribute('hidden', '');
+    }
+  }
+
+  // ---------------------------------------------------------------------------
+  // Public state accessors
+  // ---------------------------------------------------------------------------
+
+  /** Build the scope used for expression evaluation: `{ typeName: public }`. */
+  function stateScope() {
+    var scope = {};
+    store.forEach(function (entry, type) { scope[type] = entry.snapshot.public; });
+    return scope;
+  }
+
+  /** Read a type's `public` data (what the attributes bind to). */
+  function read(type) {
+    var entry = store.get(type);
+    return entry ? entry.snapshot.public : undefined;
+  }
+
+  /** Read a type's full snapshot object. */
+  function getSnapshot(type) {
+    var entry = store.get(type);
+    return entry ? entry.snapshot : undefined;
+  }
+
+  /** Read the frame wrapping a type's snapshot. */
+  function getFrame(type) {
+    var entry = store.get(type);
+    return entry ? entry.frame : undefined;
+  }
+
+  /** Build an object of `{ typeName: public }` for every held type. */
+  function state() {
+    var result = {};
+    store.forEach(function (entry, type) { result[type] = entry.snapshot.public; });
+    return result;
+  }
+
+  /**
+   * Clear state. With a type argument, clears that type only; without, clears
+   * all held state.
+   * @param {string} [type]
+   */
+  function clear(type) {
+    if (type === undefined) {
+      Array.from(store.keys()).forEach(function (t) { clearType(t, { broadcast: true }); });
+    } else {
+      clearType(type, { broadcast: true });
+    }
+    renderAll();
+  }
+
+  /**
+   * Perform an action. `action` may be an action object or a string path that
+   * resolves to an action object within the current state.
+   * @param {object|string} action
+   * @param {object} [data]
+   * @returns {Promise<void>}
+   */
+  function act(action, data) {
+    var resolved = action;
+    if (typeof action === 'string') resolved = evalExpr(action, stateScope());
+    if (!resolved || typeof resolved.uri !== 'string') {
+      return Promise.reject(new StatumError('Invalid action'));
+    }
+    return performAction(resolved, data, null);
+  }
+
+  /** Attach a state listener for a type. */
+  function addStateListener(type, callback) {
+    if (typeof callback !== 'function') return;
+    if (!listeners.has(type)) listeners.set(type, new Set());
+    listeners.get(type).add(callback);
+  }
+
+  /** Remove a previously-attached state listener. */
+  function removeStateListener(type, callback) {
+    var set = listeners.get(type);
+    if (!set) return;
+    set.delete(callback);
+    if (set.size === 0) listeners.delete(type);
+  }
+
+  // ---------------------------------------------------------------------------
+  // Initialization
+  // ---------------------------------------------------------------------------
+
+  /**
+   * Inject the stylesheet that makes the `hidden` attribute authoritative.
+   * Statum toggles `stm-if`/`stm-else` branches and loop holders via
+   * `hidden`, whose user-agent rule loses specificity battles to ordinary
+   * author CSS (a rule like `li { display: flex }` let hidden loop holders
+   * leak as phantom rows). Idempotent: skipped when the stylesheet is
+   * already present.
+   */
+  function injectHiddenStyle() {
+    var id = 'statum-hidden-style';
+    if (document.getElementById(id)) return;
+    var head = document.head;
+    if (!head) return;
+    var style = document.createElement('style');
+    style.id = id;
+    style.textContent = '[hidden]{display:none !important}';
+    head.appendChild(style);
+  }
+
+  /**
+   * Scan the document for `pstm-*` attributes and `<pstm-*>` elements, which
+   * are intended for server-side pre-rendering and should never reach the
+   * browser. Emits a single `console.warn` summarizing them.
+   */
+  function warnServerSideMarkup() {
+    var found = [];
+    var els = document.querySelectorAll('*');
+    for (var i = 0; i < els.length; i++) {
+      var el = els[i];
+      var tag = el.tagName.toLowerCase();
+      if (tag.indexOf('pstm-') === 0) found.push('<' + tag + '>');
+      var attrs = el.attributes;
+      for (var j = 0; j < attrs.length; j++) {
+        var name = attrs[j].name;
+        if (name.indexOf('pstm-') === 0) found.push('<' + tag + '> ' + name);
+      }
+    }
+    if (found.length) {
+      console.warn('[statum] ' + found.length + ' server-side pstm-* attribute/element(s) ' +
+        'found in the DOM; they should have been resolved during pre-rendering: ' +
+        found.slice(0, 10).join(', ') + (found.length > 10 ? ' …' : ''));
+    }
+  }
+
+  /**
+   * Initialize Statum: read URL overrides, run the session-cookie check,
+   * hydrate persisted state, open the cross-tab channel, fetch the entrypoint,
+   * and render. Safe to call multiple times.
+   * @returns {Promise<void>}
+   */
+  async function init() {
+    if (initialized) return;
+    initialized = true;
+
+    // Before the first render and the boot visibility toggling, so `hidden`
+    // wins over author CSS from the very first paint.
+    injectHiddenStyle();
+
+    var body = document.body;
+    if (body) {
+      if (body.hasAttribute('stm-entrypoint')) config.entrypointUrl = body.getAttribute('stm-entrypoint');
+      if (body.hasAttribute('stm-slots')) config.slotsUrl = body.getAttribute('stm-slots');
+      if (body.hasAttribute('stm-channel')) config.channelUrl = body.getAttribute('stm-channel');
+      if (body.hasAttribute('stm-worker')) config.workerUrl = body.getAttribute('stm-worker');
+    }
+
+    try { warnServerSideMarkup(); } catch (e) {}
+
+    try { initSession(); } catch (e) {}
+    try { hydrate(); } catch (e) {}
+    setupChannel();
+
+    setBootState(false);
+    renderAll(); // bind against any persisted/hydrated state immediately
+
+    try {
+      await loadEntrypoint();
+    } catch (err) {
+      console.error('[statum] entrypoint load failed', err);
+    } finally {
+      setBootState(true);
+    }
+  }
+
+  function autoInit() {
+    if (document.readyState === 'loading') {
+      document.addEventListener('DOMContentLoaded', init);
+    } else {
+      init();
+    }
+  }
+
+  // ---------------------------------------------------------------------------
+  // Public API
+  // ---------------------------------------------------------------------------
+
+  /** @namespace statum */
+  window.statum = {
+    /** Library version. */
+    version: '0.1.0',
+    /** Mutable endpoint configuration. */
+    config: config,
+    /** (Re)initialize the library. Usually runs automatically on load. */
+    init: init,
+    /** Read a type's `public` data. */
+    read: read,
+    /** Read a type's full snapshot object. */
+    getSnapshot: getSnapshot,
+    /** Read the frame wrapping a type's snapshot. */
+    getFrame: getFrame,
+    /** Build `{ typeName: public }` for every held type. */
+    state: state,
+    /** Clear one type (`clear("x")`) or all state (`clear()`). */
+    clear: clear,
+    /** Perform an action object or named action. */
+    act: act,
+    /** Attach a state-changed listener for a type. */
+    addStateListener: addStateListener,
+    /** Remove a previously-attached listener. */
+    removeStateListener: removeStateListener,
+    /**
+     * Register a handler for an `stm-*` attribute (module seam — see the
+     * registry in statum-core.js). `name` is an exact attribute name, or a
+     * prefix matcher when it ends with `.`; `opts.after` / `opts.before`
+     * order the handler against another registered attribute.
+     */
+    registerAttribute: registerAttribute,
+    /** Register a callback that runs before each render cycle (no arguments). */
+    beforeEvaluate: function (fn) { if (typeof fn === 'function') beforeHooks.push(fn); },
+    /** Register a callback that runs after each render cycle (no arguments). */
+    afterEvaluate: function (fn) { if (typeof fn === 'function') afterHooks.push(fn); },
+    /** The Statum error type (thrown by `act` and surfaced to handlers). */
+    Error: StatumError,
+    get onConfirmHandler() { return handlers.onConfirm; },
+    set onConfirmHandler(v) { handlers.onConfirm = typeof v === 'function' ? v : null; },
+    get onNotifyHandler() { return handlers.onNotify; },
+    set onNotifyHandler(v) { handlers.onNotify = typeof v === 'function' ? v : null; },
+    get onErrorHandler() { return handlers.onError; },
+    set onErrorHandler(v) { handlers.onError = typeof v === 'function' ? v : null; }
+  };
+
+  // The seam must be exposed before any other module loads. autoInit only
+  // ever runs on DOMContentLoaded (or immediately at load); both happen
+  // outside this script tag, so the later module tags always see the bridge.
+  window.statum._bridge = bridge;
+
+  autoInit();
+})();
+

+ 491 - 0
js/statum-document.js

@@ -0,0 +1,491 @@
+/*!
+ * Statum - client-side state library (document module).
+ *
+ * The render walk: expands `stm-for` loops and `stm-if` chains, applies the
+ * structural and DOM-level `stm-*` bindings (`stm-class.*`,
+ * `stm-attribute.*`, `stm-disabled`, `stm-text`, `stm-html`), wires
+ * `stm-action` elements, and recurses into child elements. The bindings
+ * register through core's attribute seam and this module installs core's
+ * render driver, so `renderAll` drives the walk defined here. The
+ * structural attributes (`stm-for`, `stm-if`/`stm-else-if`/`stm-else` and
+ * `stm-def-*`) stay hardcoded in the walk: they build the scope and the
+ * element list every handler receives.
+ *
+ * Load order: SECOND - requires statum-core.js, which creates `window.statum`
+ * and the `_bridge` this module registers through. Like core: an IIFE, no
+ * dependencies, no build step, plain script tag.
+ */
+(function () {
+  'use strict';
+
+  if (!window.statum || !window.statum._bridge) {
+    console.error('[statum] statum-document.js requires statum-core.js');
+    return;
+  }
+
+  // Core machinery shared through the module seam (see statum-core.js).
+  // Aliased so the moved code keeps its original call shapes.
+  var bridge = window.statum._bridge;
+  var evalExpr = bridge.evalExpr;
+  var childScope = bridge.childScope;
+  var stateScope = bridge.stateScope;
+  var triggerConfirm = bridge.triggerConfirm;
+  var performAction = bridge.performAction;
+  var applyErrorClasses = bridge.applyErrorClasses;
+
+
+  // ---------------------------------------------------------------------------
+  // Rendering: loops, conditionals, bindings
+  // ---------------------------------------------------------------------------
+
+  /** Templates captured from loop holders. @type {WeakMap<Element, Element>} */
+  var templates = new WeakMap();
+  /** Instance nodes managed by a loop holder. @type {WeakMap<Element, Element[]>} */
+  var instancesByHolder = new WeakMap();
+  /** Loop instance nodes; skipped by the render walk (owned by their holder). */
+  var instanceNodes = new WeakSet();
+  /** Elements whose `stm-action` has been wired, to avoid double-binding. */
+  var wired = new WeakSet();
+
+  /**
+   * Find a `stm-for-{name}-in` attribute on an element.
+   * @returns {{varName: string, expr: string}|null}
+   */
+  function getStmFor(el) {
+    var attrs = el.attributes;
+    for (var i = 0; i < attrs.length; i++) {
+      var match = attrs[i].name.match(/^stm-for-(.+)-in$/);
+      if (match) return { varName: match[1], expr: attrs[i].value };
+    }
+    return null;
+  }
+
+  /** Remove any `stm-for-*` and `stm-key` attributes from an element. */
+  function stripLoopAttrs(el) {
+    var toRemove = [];
+    for (var i = 0; i < el.attributes.length; i++) {
+      var name = el.attributes[i].name;
+      if (/^stm-for-(.+)-in$/.test(name) || name === 'stm-key') toRemove.push(name);
+    }
+    toRemove.forEach(function (n) { el.removeAttribute(n); });
+  }
+
+  /**
+   * Evaluate an `stm-if` / `stm-else-if` / `stm-else` chain beginning at `el`,
+   * showing the matching branch and hiding the rest.
+   *
+   * Branches are toggled with the `hidden` attribute rather than detached, so
+   * every branch stays in the DOM and is re-evaluated on each render. (Detaching
+   * the `stm-if` element would remove it from the render walk, leaving an
+   * already-attached `stm-else` branch skipped and never refreshed.)
+   * @returns {Element|null} The active branch element (or `null`).
+   */
+  function handleIfChain(el, scope) {
+    var branches = [{ el: el, expr: el.getAttribute('stm-if') }];
+    var cur = el.nextElementSibling;
+    while (cur) {
+      if (cur.hasAttribute('stm-else-if')) {
+        branches.push({ el: cur, expr: cur.getAttribute('stm-else-if') });
+        cur = cur.nextElementSibling;
+      } else if (cur.hasAttribute('stm-else')) {
+        branches.push({ el: cur, expr: null });
+        break;
+      } else {
+        break;
+      }
+    }
+    var activeEl = null;
+    for (var i = 0; i < branches.length; i++) {
+      var b = branches[i];
+      if (b.expr === null || !!evalExpr(b.expr, scope)) { activeEl = b.el; break; }
+    }
+    branches.forEach(function (b) {
+      if (b.el === activeEl) b.el.removeAttribute('hidden');
+      else b.el.setAttribute('hidden', '');
+    });
+    return activeEl;
+  }
+
+  /** Toggle `stm-class.{name}` classes from their predicate expressions. */
+  function handleClass(el, scope) {
+    var attrs = el.attributes;
+    for (var i = 0; i < attrs.length; i++) {
+      var attr = attrs[i];
+      if (attr.name.indexOf('stm-class.') === 0) {
+        var cls = attr.name.slice('stm-class.'.length);
+        if (cls && !!evalExpr(attr.value, scope)) el.classList.add(cls);
+        else el.classList.remove(cls);
+      }
+    }
+  }
+
+  /**
+   * Bind `stm-attribute.{name}`: a boolean result toggles the attribute, any
+   * other defined value sets it, and `undefined` removes it.
+   *
+   * For booleans, prefer the element's IDL property when one exists (e.g.
+   * `checked`, `disabled`, `hidden`) — setting the content attribute is
+   * unreliable for these once the control is "dirty".
+   */
+  function handleAttribute(el, scope) {
+    var attrs = el.attributes;
+    for (var i = 0; i < attrs.length; i++) {
+      var attr = attrs[i];
+      if (attr.name.indexOf('stm-attribute.') === 0) {
+        var name = attr.name.slice('stm-attribute.'.length);
+        if (!name) continue;
+        var value = evalExpr(attr.value, scope);
+        if (value === undefined) {
+          el.removeAttribute(name);
+        } else if (typeof value === 'boolean') {
+          if (name in el && typeof el[name] === 'boolean') el[name] = value;
+          else if (value) el.setAttribute(name, '');
+          else el.removeAttribute(name);
+        } else {
+          el.setAttribute(name, value === null ? '' : String(value));
+        }
+      }
+    }
+  }
+
+  /**
+   * Apply `stm-disabled`: when the predicate is truthy, disable the element and
+   * its descendant form controls; otherwise enable them.
+   */
+  function handleDisabled(el, scope) {
+    if (!el.hasAttribute('stm-disabled')) return;
+    setDisabledCascade(el, !!evalExpr(el.getAttribute('stm-disabled'), scope));
+  }
+
+  /** Set the `disabled` attribute on an element and its descendant controls. */
+  function setDisabledCascade(el, on) {
+    var nodes = [el].concat(Array.prototype.slice.call(
+      el.querySelectorAll('button,input,select,textarea,fieldset')));
+    nodes.forEach(function (n) {
+      if (on) n.setAttribute('disabled', ''); else n.removeAttribute('disabled');
+    });
+  }
+
+
+  // ---------------------------------------------------------------------------
+  // stm-text / stm-html
+  // ---------------------------------------------------------------------------
+  // (stm-markdown and stm-h-demotion moved to statum-markdown.js and register
+  // through the same seam, ordered after `stm-html`.)
+
+  /**
+   * Bind `stm-text`. Per the "leave original DOM content" policy, an
+   * unresolved value (`undefined`) leaves the element untouched; otherwise
+   * the value is stringified (`null` becomes empty).
+   */
+  function handleText(el, scope) {
+    if (el.hasAttribute('stm-text')) {
+      var text = evalExpr(el.getAttribute('stm-text'), scope);
+      if (text !== undefined) el.textContent = text === null ? '' : String(text);
+    }
+  }
+
+  /**
+   * Bind `stm-html`, with the same policy as `stm-text`.
+   */
+  function handleHtml(el, scope) {
+    if (el.hasAttribute('stm-html')) {
+      var html = evalExpr(el.getAttribute('stm-html'), scope);
+      if (html !== undefined) el.innerHTML = html === null ? '' : String(html);
+    }
+  }
+
+
+  /**
+   * Expand a loop holder: reconcile its instances against the current array.
+   * Keyed loops (`stm-key`) reuse DOM nodes for unchanged keys to preserve
+   * focus/selection/input state; unkeyed loops rebuild wholesale.
+   */
+  function handleLoop(el, scope) {
+    var info = getStmFor(el);
+    if (!info) return;
+
+    var template = templates.get(el);
+    if (!template) {
+      template = el.cloneNode(true);
+      stripLoopAttrs(template);
+      templates.set(el, template);
+    }
+
+    var raw = evalExpr(info.expr, scope);
+    if (raw === undefined) {
+      // No value for the source path yet: clear instances and restore the
+      // server-rendered holder content (progressive enhancement).
+      var prev = instancesByHolder.get(el) || [];
+      prev.forEach(function (n) { n.remove(); });
+      instancesByHolder.set(el, []);
+      if (el.getAttribute('data-stm-active') === '1') {
+        el.removeAttribute('data-stm-active');
+        el.removeAttribute('hidden');
+      }
+      return;
+    }
+    var arr = Array.isArray(raw) ? raw : [];
+
+    // Activate: hide the holder so only rendered instances are visible.
+    if (el.getAttribute('data-stm-active') !== '1') {
+      el.setAttribute('data-stm-active', '1');
+      el.setAttribute('hidden', '');
+    }
+
+    var keyExpr = el.getAttribute('stm-key');
+    var next = [];
+
+    if (keyExpr) {
+      var oldByKey = new Map();
+      (instancesByHolder.get(el) || []).forEach(function (n) {
+        if (n.__stmKey !== undefined) oldByKey.set(n.__stmKey, n);
+      });
+      var used = new Set();
+      arr.forEach(function (item) {
+        var child = childScope(scope, info.varName, item);
+        var key = evalExpr(keyExpr, child);
+        var node = (key !== undefined && !used.has(key)) ? oldByKey.get(key) : undefined;
+        if (node) {
+          used.add(key);
+          processElement(node, child);
+        } else {
+          node = template.cloneNode(true);
+          node.__stmKey = key;
+          instanceNodes.add(node);
+          processElement(node, child);
+        }
+        next.push(node);
+      });
+      oldByKey.forEach(function (n, key) { if (!used.has(key)) n.remove(); });
+    } else {
+      (instancesByHolder.get(el) || []).forEach(function (n) { n.remove(); });
+      arr.forEach(function (item) {
+        var child = childScope(scope, info.varName, item);
+        var node = template.cloneNode(true);
+        instanceNodes.add(node);
+        processElement(node, child);
+        next.push(node);
+      });
+    }
+
+    // Place instances in order, immediately after the holder.
+    var ref = el;
+    next.forEach(function (node) {
+      if (node !== ref.nextSibling) ref.parentNode.insertBefore(node, ref.nextSibling);
+      ref = node;
+    });
+    instancesByHolder.set(el, next);
+  }
+
+  /**
+   * Process one element's bindings (and recurse). Loop holders are handled by
+   * {@link handleLoop}; `stm-else-if` / `stm-else` are owned by their `stm-if`.
+   */
+  function processElement(el, scope) {
+    if (getStmFor(el)) { handleLoop(el, scope); return; }
+    if (el.hasAttribute('stm-else-if') || el.hasAttribute('stm-else')) return;
+    if (el.hasAttribute('stm-if')) {
+      var active = handleIfChain(el, scope);
+      if (active) processInner(active, scope);
+      return;
+    }
+    processInner(el, scope);
+  }
+
+  /**
+   * Collect `stm-def-{name}-as` attributes on an element into a child scope.
+   * Each expression is evaluated against the incoming scope (so the new
+   * variables cannot reference each other within the same element), and the
+   * results are added to a child scope visible to the element and its
+   * descendants. Multiple defs on one element are supported. If there are no
+   * defs, the original scope is returned unchanged.
+   * @param {Element} el
+   * @param {object} scope
+   * @returns {object}
+   */
+  function applyDefs(el, scope) {
+    var attrs = el.attributes;
+    var child = null;
+    for (var i = 0; i < attrs.length; i++) {
+      var name = attrs[i].name;
+      if (name.indexOf('stm-def-') === 0 && name.slice(-3) === '-as') {
+        var varName = name.slice(8, -3);
+        if (!varName) continue;
+        if (!child) child = Object.create(scope || null);
+        child[varName] = evalExpr(attrs[i].value, scope);
+      }
+    }
+    return child || scope;
+  }
+
+  /**
+   * Bind the non-control-flow attributes and recurse into children.
+   *
+   * Handlers run in the seam's resolved order (see registerAttribute in
+   * statum-core.js): once all modules have loaded it is stm-class.* ->
+   * stm-attribute.* -> stm-disabled -> stm-text -> stm-html ->
+   * stm-markdown -> stm-h-demotion, the order this walk used when it called
+   * the handlers directly. A throwing handler aborts the render cycle via
+   * renderAll's try/catch, as before.
+   */
+  function processInner(el, scope) {
+    var s = applyDefs(el, scope); // local definitions: element + descendants
+    el.__stmScope = s; // latest scope, used when an action fires
+    var registered = bridge.attributeHandlers;
+    for (var i = 0; i < registered.length; i++) {
+      var h = registered[i];
+      if (h.prefix ? hasAttrPrefix(el, h.name) : el.hasAttribute(h.name)) h.fn(el, s);
+    }
+    wireAction(el);
+    render(el, s);
+  }
+
+  /** Whether `el` carries any attribute starting with `prefix`. */
+  function hasAttrPrefix(el, prefix) {
+    var attrs = el.attributes;
+    for (var i = 0; i < attrs.length; i++) {
+      if (attrs[i].name.indexOf(prefix) === 0) return true;
+    }
+    return false;
+  }
+
+
+  /**
+   * Walk an element's children, processing each. Loop instance nodes are
+   * skipped here (they are owned and processed by their holder).
+   */
+  function render(root, scope) {
+    if (!root || !root.children) return;
+    // Snapshot the children: processing mutates the DOM (detaching branches,
+    // inserting loop instances) and a live HTMLCollection would shift indices.
+    var children = Array.prototype.slice.call(root.children);
+    for (var i = 0; i < children.length; i++) {
+      var el = children[i];
+      if (instanceNodes.has(el)) continue;
+      processElement(el, scope);
+    }
+  }
+
+  // ---------------------------------------------------------------------------
+  // HTML API: actions
+  // ---------------------------------------------------------------------------
+
+  /**
+   * Collect data for an action trigger: `stm-data-{key}` attributes plus, for a
+   * form, its named inputs.
+   * @param {HTMLElement} el
+   * @returns {object}
+   */
+  function collectData(el) {
+    var data = {};
+    var attrs = el.attributes;
+    for (var i = 0; i < attrs.length; i++) {
+      var name = attrs[i].name;
+      if (name.indexOf('stm-data-') === 0) data[name.slice('stm-data-'.length)] = attrs[i].value;
+    }
+    if (el.tagName === 'FORM') {
+      var fd = new FormData(el);
+      fd.forEach(function (value, key) {
+        data[key] = value instanceof File ? value.name : String(value);
+      });
+    }
+    return data;
+  }
+
+  /**
+   * Toggle the busy state of an action element: disables the element and its
+   * descendant form controls and applies `stm-busy-class` classes while busy.
+   *
+   * On un-busy the disabled state is not "restored" to a captured snapshot
+   * (that would clobber a `stm-disabled` value that `renderAll` applied during
+   * the response); instead the nodes are re-enabled and `stm-disabled` is
+   * re-evaluated, which re-disables any that should remain disabled.
+   */
+  function setBusyState(el, busy) {
+    var nodes = [el].concat(Array.prototype.slice.call(
+      el.querySelectorAll('button,input,select,textarea,fieldset')));
+    var busyClasses = (el.getAttribute('stm-busy-class') || '').split(/\s+/).filter(Boolean);
+    if (busy) {
+      nodes.forEach(function (n) { n.setAttribute('disabled', ''); });
+      busyClasses.forEach(function (c) { el.classList.add(c); });
+    } else {
+      nodes.forEach(function (n) { n.removeAttribute('disabled'); });
+      busyClasses.forEach(function (c) { el.classList.remove(c); });
+      reapplyDisabled(el);
+    }
+  }
+
+  /** Re-apply `stm-disabled` to an element and any descendants that carry it. */
+  function reapplyDisabled(el) {
+    var scope = el.__stmScope || stateScope();
+    if (el.hasAttribute('stm-disabled')) handleDisabled(el, scope);
+    var scoped = el.querySelectorAll('[stm-disabled]');
+    Array.prototype.forEach.call(scoped, function (n) {
+      handleDisabled(n, n.__stmScope || scope);
+    });
+  }
+
+  /**
+   * Wire an element's primary action once. The listener resolves the action
+   * object against the element's latest render scope, so loop instances bind to
+   * their own item.
+   */
+  function wireAction(el) {
+    if (!el.hasAttribute('stm-action') || wired.has(el)) return;
+    wired.add(el);
+    var eventName = el.tagName === 'FORM' ? 'submit' : 'click';
+    el.addEventListener(eventName, function (event) {
+      event.preventDefault();
+      runElementAction(el);
+    });
+  }
+
+  /**
+   * Resolve and perform the action attached to an element, managing busy and
+   * error-state classes around the request.
+   * @param {HTMLElement} el
+   */
+  async function runElementAction(el) {
+    var scope = el.__stmScope || stateScope();
+    var action = evalExpr(el.getAttribute('stm-action'), scope);
+    if (!action || typeof action.uri !== 'string') return;
+
+    // stm-confirm: gate the action behind the confirm handler (async-capable,
+    // so custom modals are supported).
+    if (el.hasAttribute('stm-confirm')) {
+      var confirmed = await triggerConfirm(el.getAttribute('stm-confirm'), el);
+      if (!confirmed) return;
+    }
+
+    applyErrorClasses(el, false); // clear error state on a new attempt
+    var data = collectData(el);
+    setBusyState(el, true);
+    try {
+      await performAction(action, data, el);
+    } catch (err) {
+      // Already handled: stm-on-error classes and the onErrorHandler run inside
+      // performAction/reportFailure. Swallow so an HTML-triggered action does
+      // not surface as an unhandled rejection.
+    } finally {
+      setBusyState(el, false);
+    }
+  }
+
+  // ---------------------------------------------------------------------------
+  // Registration (module seam)
+  // ---------------------------------------------------------------------------
+
+  // Registration order mirrors the order these handlers had when processInner
+  // called them directly; statum-markdown.js constrains its own handlers
+  // relative to `stm-html`.
+  bridge.registerAttribute('stm-class.', handleClass);
+  bridge.registerAttribute('stm-attribute.', handleAttribute);
+  bridge.registerAttribute('stm-disabled', handleDisabled);
+  bridge.registerAttribute('stm-text', handleText);
+  bridge.registerAttribute('stm-html', handleHtml);
+
+  // Core's renderAll drives the walk defined in this module.
+  bridge.installRenderDriver(function (scope) { render(document.body, scope); });
+})();
+

Plik diff jest za duży
+ 14 - 1245
js/statum-markdown.js


+ 7 - 4
src/Statum.vala

@@ -67,10 +67,13 @@ namespace Statum {
                 .with_metadata<EndpointRoute>(new EndpointRoute("/_statum/resource/{name}"));
 
             // Embed the Statum client scripts as default resources, served from
-            // /_statum/resource/statum.js and /_statum/resource/statum-worker.js
-            // (precompressed at build time). Apps get them for free and may add
-            // their own resources via StatumConfigurator.add_resource.
-            container.register_startup<ClientScript>().as<StatumResource>();
+            // /_statum/resource/statum-core.js, statum-document.js,
+            // statum-markdown.js and statum-worker.js (precompressed at build
+            // time). Apps get them for free and may add their own resources
+            // via StatumConfigurator.add_resource.
+            container.register_startup<ClientCore>().as<StatumResource>();
+            container.register_startup<ClientDocument>().as<StatumResource>();
+            container.register_startup<ClientMarkdown>().as<StatumResource>();
             container.register_startup<ClientWorker>().as<StatumResource>();
         }
 

+ 40 - 10
src/meson.build

@@ -1,14 +1,44 @@
-# Embed the Statum client scripts (js/statum.js and js/statum-worker.js) into the
-# library as precompressed ConstantStatumResource classes, served by default at
-# /_statum/resource/statum.js and /_statum/resource/statum-worker.js. Generated
-# at build time by the in-tree statum-mkres tool — no installed tool required.
-client_script = custom_target('statum-client-script',
-    input: files('../js/statum.js'),
-    output: 'ClientScript.vala',
+# Embed the Statum client scripts (js/statum-core.js, js/statum-document.js,
+# js/statum-markdown.js and js/statum-worker.js) into the library as
+# precompressed ConstantStatumResource classes, served by default at
+# /_statum/resource/<name>. Generated at build time by the in-tree
+# statum-mkres tool — no installed tool required.
+#
+# The three client modules are separate resources loaded in order by pages
+# (core creates window.statum and the module seam; document installs the
+# render walk; markdown adds the CommonMark engine). The former single-file
+# statum.js resource no longer exists.
+client_core = custom_target('statum-client-core',
+    input: files('../js/statum-core.js'),
+    output: 'ClientCore.vala',
     command: [statum_mkres,
               '-o', '@OUTPUT@',
-              '-n', 'statum.js',
-              '--class-name', 'ClientScript',
+              '-n', 'statum-core.js',
+              '--class-name', 'ClientCore',
+              '--ns', 'Statum',
+              '-c', 'application/javascript',
+              '@INPUT@']
+)
+
+client_document = custom_target('statum-client-document',
+    input: files('../js/statum-document.js'),
+    output: 'ClientDocument.vala',
+    command: [statum_mkres,
+              '-o', '@OUTPUT@',
+              '-n', 'statum-document.js',
+              '--class-name', 'ClientDocument',
+              '--ns', 'Statum',
+              '-c', 'application/javascript',
+              '@INPUT@']
+)
+
+client_markdown = custom_target('statum-client-markdown',
+    input: files('../js/statum-markdown.js'),
+    output: 'ClientMarkdown.vala',
+    command: [statum_mkres,
+              '-o', '@OUTPUT@',
+              '-n', 'statum-markdown.js',
+              '--class-name', 'ClientMarkdown',
               '--ns', 'Statum',
               '-c', 'application/javascript',
               '@INPUT@']
@@ -62,7 +92,7 @@ sources = files(
 
 library_version = meson.project_version()
 libstatum = shared_library('statum-@0@'.format(library_version),
-    sources, client_script, client_worker,
+    sources, client_core, client_document, client_markdown, client_worker,
     dependencies: [
         glib_dep,
         gobject_dep,

+ 2 - 1
tests/markdown/README.md

@@ -1,6 +1,7 @@
 # Markdown tests
 
-JS tests for the `stm-markdown` renderer in `js/statum.js`. These are the
+JS tests for the `stm-markdown` renderer in `js/statum-markdown.js` (loaded
+after `js/statum-core.js`, which it requires). These are the
 repository's first JavaScript tests; they run under
 [QuickJS](https://bellard.org/quickjs/) so **no Node.js is required**.
 

+ 5 - 1
tests/markdown/regressions.js

@@ -18,7 +18,11 @@ function fail(msg) {
 }
 
 installShim();
-(0, eval)(std.loadFile('js/statum.js'));
+// Load order matters: statum-core.js creates `window.statum` (and the module
+// seam), statum-markdown.js registers the engine + its bindings through it.
+// Loading exactly these two proves the core+markdown cherry-pick.
+(0, eval)(std.loadFile('js/statum-core.js'));
+(0, eval)(std.loadFile('js/statum-markdown.js'));
 
 var render = globalThis.statum._testMarkdown;
 if (typeof render !== 'function') fail('statum._testMarkdown is not exposed');

+ 8 - 7
tests/markdown/shim.js

@@ -1,13 +1,14 @@
 /**
- * Minimal DOM shim so js/statum.js can be loaded under QuickJS.
+ * Minimal DOM shim so the Statum module files can be loaded under QuickJS.
  *
- * statum.js is an IIFE that attaches `window.statum` and calls autoInit()
- * at load time. autoInit() only needs `document.readyState` (we report
- * 'loading' so it registers a DOMContentLoaded listener instead of running),
- * and the rest of the boot path is never exercised by the markdown tests.
+ * The modules are IIFEs; statum-core.js attaches `window.statum` and calls
+ * autoInit() at load time. autoInit() only needs `document.readyState` (we
+ * report 'loading' so it registers a DOMContentLoaded listener instead of
+ * running), and the rest of the boot path is never exercised by the markdown
+ * tests.
  *
- * Set `__STATUM_TEST__` before loading statum.js to expose
- * `statum._testMarkdown` (see the comment at the bottom of statum.js).
+ * Set `__STATUM_TEST__` before loading statum-markdown.js to expose
+ * `statum._testMarkdown` (see the comment at the bottom of that module).
  */
 export function installShim() {
   var listeners = {};

+ 5 - 1
tests/markdown/spec-test.js

@@ -20,7 +20,11 @@ function fail(msg) {
 }
 
 installShim();
-(0, eval)(std.loadFile('js/statum.js'));
+// Load order matters: statum-core.js creates `window.statum` (and the module
+// seam), statum-markdown.js registers the engine + its bindings through it.
+// Loading exactly these two proves the core+markdown cherry-pick.
+(0, eval)(std.loadFile('js/statum-core.js'));
+(0, eval)(std.loadFile('js/statum-markdown.js'));
 
 var render = globalThis.statum._testMarkdown;
 if (typeof render !== 'function') {

+ 29 - 0
tests/split/run.sh

@@ -0,0 +1,29 @@
+#!/bin/sh
+# Run the Statum module-split test scenarios.
+#
+# Builds the vendored QuickJS interpreter if no `qjs` is on PATH (same
+# bootstrap as tests/markdown/run.sh), then runs each scenario in a fresh
+# context. Exits non-zero when any scenario fails.
+#
+# Usage: tests/split/run.sh [scenario]   (default: all seven)
+set -e
+cd "$(dirname "$0")/../.."
+
+ROOT=$(pwd)
+QJS="$ROOT/tools/qjs/qjs"
+
+if ! command -v qjs >/dev/null 2>&1; then
+  echo "== building vendored QuickJS =="
+  "$ROOT/tools/qjs/build.sh"
+else
+  QJS=$(command -v qjs)
+fi
+
+SCENARIOS="${1:-1 2 3 4 5 6 7}"
+
+for n in $SCENARIOS; do
+  echo "== split scenario $n =="
+  "$QJS" "$ROOT/tests/split/scenarios.js" "$n"
+done
+
+echo "OK"

+ 198 - 0
tests/split/scenarios.js

@@ -0,0 +1,198 @@
+/**
+ * Module-split scenarios for the Statum client.
+ *
+ * Each scenario runs in a FRESH QuickJS context (run.sh invokes this script
+ * once per scenario) and loads a specific subset of the module files in a
+ * specific order, proving:
+ *
+ *   1  core-alone        - window.statum, seam, overrides, driver-less render
+ *   2  core+document     - render driver installed, handler order pinned
+ *   3  core+doc+markdown - full order, statum.markdown API, test hatch
+ *   4  core+markdown     - cherry-pick without the walk (crash-free)
+ *   5  document alone    - guarded IIFE: console.error, nothing attached
+ *   6  double register   - warns, order unchanged
+ *   7  unknown after     - warns, registration position kept
+ *
+ * Usage: qjs tests/split/scenarios.js <1|2|3|4|5|6|7>
+ */
+import * as std from 'std';
+import { installShim } from './shim.js';
+
+var ROOT = '/workspace/task-214/Statum';
+var scenario = scriptArgs.length > 1 ? scriptArgs[1] : '';
+
+function fail(msg) {
+  std.err.puts('FAIL [' + scenario + '] ' + msg + '\n');
+  std.exit(1);
+}
+
+function check(cond, msg) {
+  if (!cond) fail(msg);
+}
+
+function load(name) {
+  (0, eval)(std.loadFile(ROOT + '/js/' + name));
+}
+
+function handlerNames() {
+  return globalThis.statum._bridge.attributeHandlers.map(function (h) { return h.name; });
+}
+
+installShim();
+var log = globalThis.__shim.log;
+
+if (scenario === '1') {
+  load('statum-core.js');
+  var s = globalThis.statum;
+  check(s, 'window.statum is not defined');
+  check(s.version === '0.1.0', 'version missing');
+  check(typeof s.config === 'object' && s.config.entrypointUrl === '/_statum/entrypoint',
+    'config missing');
+  check(typeof s.registerAttribute === 'function', 'registerAttribute is not a function');
+  check(s._bridge, '_bridge is not present');
+  check(typeof s.Error === 'function', 'statum.Error missing');
+  check(log.errors.length === 0, 'unexpected console.error at load: ' + JSON.stringify(log.errors));
+  check(log.warns.length === 0, 'unexpected console.warn at load: ' + JSON.stringify(log.warns));
+
+  // The three override pairs round-trip a function and null out non-functions.
+  var fn = function () {};
+  var pairs = ['onConfirmHandler', 'onNotifyHandler', 'onErrorHandler'];
+  pairs.forEach(function (p) {
+    s[p] = fn;
+    check(s[p] === fn, p + ' did not round-trip the function');
+    s[p] = 42;
+    check(s[p] === null, p + ' did not null out a non-function');
+    s[p] = 'nope';
+    check(s[p] === null, p + ' did not null out a non-function (string)');
+  });
+
+  // No render driver installed: a render cycle must not crash.
+  check(s._bridge.attributeHandlers.length === 0, 'handlers registered without modules');
+  s._bridge.renderAll();
+  check(log.errors.length === 0, 'renderAll without a driver errored: ' + JSON.stringify(log.errors));
+
+} else if (scenario === '2') {
+  load('statum-core.js');
+  load('statum-document.js');
+  var s = globalThis.statum;
+  var names = handlerNames();
+  check(JSON.stringify(names) === JSON.stringify(
+    ['stm-class.', 'stm-attribute.', 'stm-disabled', 'stm-text', 'stm-html']),
+    'handler order is ' + JSON.stringify(names));
+
+  // The driver is installed: renderAll walks document.body and applies a
+  // binding. Scope comes from the (empty) store, so use a literal expression.
+  var el = globalThis.__shim.makeElement('p');
+  el.setAttribute('stm-text', "'driven'");
+  globalThis.__shim.body.appendChild(el);
+  s._bridge.renderAll();
+  check(el.textContent === 'driven',
+    'render driver did not apply stm-text (got ' + JSON.stringify(el.textContent) + ')');
+  check(log.errors.length === 0, 'unexpected console.error: ' + JSON.stringify(log.errors));
+
+} else if (scenario === '3') {
+  load('statum-core.js');
+  load('statum-document.js');
+  load('statum-markdown.js');
+  var s = globalThis.statum;
+  var names = handlerNames();
+  check(JSON.stringify(names) === JSON.stringify(
+    ['stm-class.', 'stm-attribute.', 'stm-disabled', 'stm-text', 'stm-html',
+     'stm-markdown', 'stm-h-demotion']),
+    'full handler order is ' + JSON.stringify(names));
+  // "directly after" from the ordered list above.
+  check(names.indexOf('stm-markdown') === names.indexOf('stm-html') + 1,
+    'stm-markdown is not directly after stm-html');
+  check(names.indexOf('stm-h-demotion') === names.indexOf('stm-markdown') + 1,
+    'stm-h-demotion is not directly after stm-markdown');
+
+  // Programmatic API shares the binding's engine. The engine renders blocks
+  // with a trailing newline (CommonMark serialisation), so '# x' -> '<h1>x</h1>\n'.
+  check(s.markdown, 'statum.markdown is not defined');
+  check(s.markdown.render('# x') === '<h1>x</h1>\n',
+    'markdown.render("# x") = ' + JSON.stringify(s.markdown.render('# x')));
+  check(typeof s.markdown.renderTo === 'function', 'markdown.renderTo is not a function');
+  var el = globalThis.__shim.makeElement('div');
+  s.markdown.renderTo(el, '# y');
+  check(el.innerHTML === '<h1>y</h1>\n',
+    'renderTo innerHTML = ' + JSON.stringify(el.innerHTML));
+  // The binding path and the programmatic path agree. (Attribute values are
+  // expressions, hence the quoted string; an unparseable value yields
+  // undefined and leaves the element untouched by design.)
+  el.innerHTML = '';
+  el.setAttribute('stm-markdown', "'# y'");
+  globalThis.__shim.body.appendChild(el);
+  // Drive the walk through the driver via a fresh render cycle.
+  var bridge = s._bridge;
+  bridge.renderAll();
+  check(el.innerHTML === '<h1>y</h1>\n',
+    'stm-markdown binding innerHTML = ' + JSON.stringify(el.innerHTML));
+
+  // Test hatch (the shim sets __STATUM_TEST__).
+  check(typeof s._testMarkdown === 'function', '_testMarkdown is not exposed');
+  check(log.errors.length === 0, 'unexpected console.error: ' + JSON.stringify(log.errors));
+
+} else if (scenario === '4') {
+  // Cherry-pick: markdown without the walk module. 'after: stm-html' cannot
+  // resolve (document is absent) so it warns and keeps registration order —
+  // that is the designed degradation, not a failure.
+  load('statum-core.js');
+  load('statum-markdown.js');
+  var s = globalThis.statum;
+  check(s.markdown.render('# x') === '<h1>x</h1>\n', 'markdown.render failed without statum-document.js');
+  var names = handlerNames();
+  check(names.indexOf('stm-markdown') !== -1 && names.indexOf('stm-h-demotion') !== -1,
+    'handlers not registered: ' + JSON.stringify(names));
+  check(names.indexOf('stm-h-demotion') === names.indexOf('stm-markdown') + 1,
+    'demotion constraint broke without the walk: ' + JSON.stringify(names));
+  check(log.errors.length === 0, 'unexpected console.error: ' + JSON.stringify(log.errors));
+  check(log.warns.length === 1 && log.warns[0].indexOf('stm-html') !== -1,
+    'expected one unresolvable-constraint warning, got ' + JSON.stringify(log.warns));
+  // A render cycle with no driver still runs.
+  s._bridge.renderAll();
+  check(log.errors.length === 0, 'renderAll errored without a driver: ' + JSON.stringify(log.errors));
+
+} else if (scenario === '5') {
+  // document without core: the guarded IIFE must record one console.error,
+  // not throw, and attach nothing.
+  load('statum-document.js');
+  check(log.errors.length === 1, 'expected exactly one console.error, got ' + JSON.stringify(log.errors));
+  check(log.errors[0].indexOf('statum-document.js requires statum-core.js') !== -1,
+    'error message: ' + JSON.stringify(log.errors[0]));
+  check(!globalThis.statum, 'document attached window.statum without core');
+  // Same for markdown.
+  log.errors.length = 0;
+  load('statum-markdown.js');
+  check(log.errors.length === 1, 'expected one console.error from markdown, got ' + JSON.stringify(log.errors));
+  check(log.errors[0].indexOf('statum-markdown.js requires statum-core.js') !== -1,
+    'error message: ' + JSON.stringify(log.errors[0]));
+  check(!globalThis.statum, 'markdown attached window.statum without core');
+
+} else if (scenario === '6') {
+  load('statum-core.js');
+  load('statum-document.js');
+  var before = handlerNames();
+  globalThis.statum.registerAttribute('stm-text', function () {});
+  check(log.warns.length === 1, 'double registration did not warn: ' + JSON.stringify(log.warns));
+  check(log.warns[0].indexOf('already registered') !== -1, 'warn text: ' + JSON.stringify(log.warns[0]));
+  var after = handlerNames();
+  check(JSON.stringify(before) === JSON.stringify(after),
+    'order changed on double registration: ' + JSON.stringify(after));
+
+} else if (scenario === '7') {
+  load('statum-core.js');
+  load('statum-document.js');
+  var before = handlerNames();
+  globalThis.statum.registerAttribute('stm-prefill', function () {}, { after: 'stm-nope' });
+  check(log.warns.length === 1, 'unresolvable constraint did not warn: ' + JSON.stringify(log.warns));
+  check(log.warns[0].indexOf('stm-nope') !== -1, 'warn names the missing anchor: ' + JSON.stringify(log.warns[0]));
+  var after = handlerNames();
+  check(after.length === before.length + 1, 'handler was not registered');
+  check(after[after.length - 1] === 'stm-prefill',
+    'handler did not keep registration position: ' + JSON.stringify(after));
+
+} else {
+  fail('unknown scenario: ' + scenario);
+}
+
+print('scenario ' + scenario + ': OK');

+ 93 - 0
tests/split/shim.js

@@ -0,0 +1,93 @@
+/**
+ * DOM shim for the module-split tests.
+ *
+ * Extends the markdown harness shim with a CAPTURING console (so scenarios
+ * can assert on the `[statum]` warnings/errors the seam emits) and a small
+ * element tree builder. Like tests/markdown/shim.js, `document.readyState`
+ * is 'loading' so statum-core.js only registers a DOMContentLoaded listener
+ * instead of booting.
+ */
+export function installShim() {
+  var listeners = {};
+  var log = { errors: [], warns: [], messages: [] };
+
+  function makeElement(tag) {
+    return {
+      tagName: (tag || 'div').toUpperCase(),
+      style: {}, dataset: {}, attributes: [],
+      children: [],
+      textContent: '', innerHTML: '',
+      get firstChild() { return this.children[0] || null; },
+      classList: { add: function () {}, remove: function () {}, contains: function () { return false; } },
+      contains: function () { return false; },
+      appendChild: function (c) { this.children.push(c); return c; },
+      removeChild: function (c) {
+        var i = this.children.indexOf(c);
+        if (i >= 0) this.children.splice(i, 1);
+        return c;
+      },
+      remove: function () {
+        if (this.parentNode) this.parentNode.removeChild(this);
+      },
+      replaceWith: function () {},
+      cloneNode: function () { return makeElement(this.tagName); },
+      nextElementSibling: null,
+      parentNode: null,
+      addEventListener: function () {}, removeEventListener: function () {},
+      setAttribute: function (n, v) {
+        this.attributes = this.attributes.filter(function (a) { return a.name !== n; });
+        this.attributes.push({ name: n, value: String(v) });
+      },
+      removeAttribute: function (n) {
+        this.attributes = this.attributes.filter(function (a) { return a.name !== n; });
+      },
+      hasAttribute: function (n) {
+        return this.attributes.some(function (a) { return a.name === n; });
+      },
+      getAttribute: function (n) {
+        var hit = this.attributes.filter(function (a) { return a.name === n; })[0];
+        return hit ? hit.value : null;
+      },
+      querySelectorAll: function () { return []; },
+      querySelector: function () { return null; }
+    };
+  }
+
+  globalThis.__shim = {
+    log: log,
+    makeElement: makeElement,
+    body: makeElement('body')
+  };
+
+  globalThis.console = {
+    log: function () { log.messages.push(['log', Array.prototype.slice.call(arguments)]); },
+    info: function () { log.messages.push(['info', Array.prototype.slice.call(arguments)]); },
+    debug: function () { log.messages.push(['debug', Array.prototype.slice.call(arguments)]); },
+    warn: function () {
+      log.warns.push(Array.prototype.slice.call(arguments).join(' '));
+      log.messages.push(['warn', Array.prototype.slice.call(arguments)]);
+    },
+    error: function () {
+      log.errors.push(Array.prototype.slice.call(arguments).join(' '));
+      log.messages.push(['error', Array.prototype.slice.call(arguments)]);
+    }
+  };
+  globalThis.document = {
+    readyState: 'loading', cookie: '',
+    head: makeElement('head'), body: globalThis.__shim.body,
+    documentElement: makeElement('html'),
+    addEventListener: function (t, f) { (listeners[t] = listeners[t] || []).push(f); },
+    removeEventListener: function () {},
+    getElementById: function () { return null; },
+    querySelectorAll: function () { return []; },
+    querySelector: function () { return null; },
+    createElement: function (tag) { return makeElement(tag); },
+    createTextNode: function (t) { return { nodeType: 3, textContent: t }; }
+  };
+  globalThis.window = globalThis;
+  globalThis.location = { href: 'http://localhost/', protocol: 'http:', addEventListener: function () {} };
+  globalThis.navigator = { userAgent: 'qjs' };
+  globalThis.addEventListener = function (t, f) { (listeners[t] = listeners[t] || []).push(f); };
+  globalThis.removeEventListener = function () {};
+  globalThis.__STATUM_TEST__ = true;
+}

Niektóre pliki nie zostały wyświetlone z powodu dużej ilości zmienionych plików