/* KodyBridge v1 — shell-provided bridge adapter for stateful bundles. * * Phase 2, decided 2026-10-30: the bridge owns the store, one instance per * app section. The framework/renderer only renders from subscriptions. * Bundles never scrape spans for initial state when a JSON seed is present, * never invent their own fetch queue, and never talk to act() directly. * * Delivery: this file is plain ES2019 JavaScript, classic-script compatible * and module-importable (no import/export, no ?. , no ??, no replaceAll, * no .at, no arrow functions, no const/let, no template literals). The * shell client module imports it, so it runs before DOMContentLoaded, * which is when bundles init. It is also loadable directly in jsdom for * the harness, which is how it is tested. * * Store model (per section): * durable — mirrors the server, changed only via dispatch to act(). * ephemeral — local only, never sent or stored server-side (drafts, * selection, filters). Set with setEphemeral(). * derived — computed from durable + ephemeral, recomputed on change, * never stored. Registered with defineDerived(name, fn). * desired — the optimistic paint: durable, plus any pending dispatch. * * Dispatch model (single-flight queue, coalescing, rebase/rollback): * dispatch(action, args, optimistic, rebase) paints optimistic at once * and sends one fetch. A dispatch while one is in flight replaces the * pending dispatch (coalescing): the desired paint is the latest one. * When the in-flight response arrives: * - if a newer dispatch has superseded it, the response is stale: * discard it and send the latest pending dispatch instead; * - if the server state diverges from the sent optimistic state and * the pending dispatch has a rebase function, rebase returns * { args, optimistic } computed from the server state, or null to * drop the pending dispatch and accept the server state; * - without a rebase function, the pending dispatch is sent as-is. * On fetch failure or { ok: false }, the in-flight flag clears and the * desired paint is kept, so the next dispatch re-sends from the desired * state (the counter is not wedged). Durable truth remains server-side, * changed only via act(). * * Nested rebase rule (schemaVersion 5): rebase is per-dispatch, supplied * by the bundle, because only the bundle knows whether a pending write * is a delta or an absolute set. For a delta, rebase recomputes from the * server state (e.g. count: server + (pending - sent)). For an absolute * set, rebase returns null (server wins) or the absolute value (bundle * wins). The bridge never merges nested objects field-by-field on its * own: a nested field is replaced wholesale by the server state unless * the bundle's rebase function says otherwise. That is the whole nested * rebase rule, and it is deliberate — silent deep-merges lose writes. * * Span adoption (dual-channel migration): the bridge observes [data-field] * spans in its section. A span change that matches the durable state is * the bundle's own paint and is ignored. A span change from elsewhere * (a shell-form patch) while a dispatch is pending cannot lose the * pending desired paint: the bridge repaints the span to the desired * value. A span change with nothing pending is adopted as new durable * state (the shell form won, e.g. a Reset the bundle did not claim). * Span values are coerced with the fieldTypes the bundle passes at * create time (integer fields parse as integers, otherwise strings). */ (function (global) { 'use strict'; function isRecord(value) { return value !== null && typeof value === 'object' && !Array.isArray(value); } function clone(value) { if (value === undefined) return undefined; return JSON.parse(JSON.stringify(value)); } function keysOf(obj) { var out = []; for (var k in obj) { if (Object.prototype.hasOwnProperty.call(obj, k)) out.push(k); } return out; } function readSeedScript(section) { var appId = ''; if (section && section.getAttribute) appId = section.getAttribute('data-app-id') || ''; /* No app id to match against means a seed can only be trusted when * it is the ONLY seed on the page (a bundle-document harness, or a * single-app page). With several seeds, returning the first would * silently hand this store another app's state (the home-widget * bug, Oct 2026), so return null and let the caller fall back to * this section's own span readout instead. */ var scripts = document.querySelectorAll('script[data-kody-state-seed]'); var loneSeed = null; var seedCount = 0; for (var i = 0; i < scripts.length; i++) { var el = scripts[i]; if (appId !== '' && el.getAttribute('data-app-id') !== appId) continue; var text = el.textContent || ''; if (text === '') continue; try { var parsed = JSON.parse(text); if (!isRecord(parsed)) continue; if (appId !== '') return parsed; loneSeed = parsed; seedCount += 1; } catch (err) { if (appId !== '') return null; } } if (appId === '') return seedCount === 1 ? loneSeed : null; return null; } function readSpanState(section, fieldTypes) { var out = {}; if (!section || !section.querySelectorAll) return out; var rows = section.querySelectorAll('[data-field]'); for (var i = 0; i < rows.length; i++) { var row = rows[i]; var field = row.getAttribute('data-field') || ''; if (field === '') continue; var span = row.querySelector('span'); var text = span ? span.textContent : row.textContent; if (text === null || text === undefined) text = ''; if (fieldTypes && fieldTypes[field] === 'integer') { var n = parseInt(text, 10); out[field] = isNaN(n) ? 0 : n; } else if (fieldTypes && fieldTypes[field] === 'boolean') { out[field] = text === 'true'; } else { out[field] = text; } } return out; } function createStore(section, opts) { opts = opts || {}; /* Defensive: a seed