statum-core.js 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580
  1. /*!
  2. * Statum - client-side state library (core module).
  3. *
  4. * An HTMX-inspired state layer. The library manages signed "snapshots" of
  5. * application state (one per slot type), keeps them fresh via the server's
  6. * `transmit_after` / `invalid_after` timestamps, and binds them to the DOM
  7. * through `stm-*` attributes. See model.md for the full specification.
  8. *
  9. * The client ships as modules, each a plain IIFE with no dependencies and no
  10. * build step, loaded in this order:
  11. *
  12. * 1. statum-core.js - this file: the slot protocol (persistence, the
  13. * X-Statum-Slot request machinery, directive
  14. * application, the realtime channel), the
  15. * alert/confirm/notify overrides, boot, and the
  16. * module seam (`statum._bridge` /
  17. * `statum.registerAttribute`). Self-sufficient;
  18. * creates `window.statum`.
  19. * 2. statum-document.js - the render walk and the structural/DOM bindings.
  20. * 3. statum-markdown.js - the CommonMark engine and `stm-markdown`.
  21. *
  22. * Targets modern evergreen browsers (uses fetch, BroadcastChannel,
  23. * queueMicrotask, URLSearchParams, FormData).
  24. */
  25. (function () {
  26. 'use strict';
  27. /** Content-Type used by every Statum directive response. */
  28. var STATUM_CONTENT_TYPE = 'application/vnd.statum+json';
  29. /** Request/response header carrying one slot's reference (or base64 frame). */
  30. var SLOT_HEADER = 'X-Statum-Slot';
  31. /** Request header carrying an action's opaque `private` blob. */
  32. var PRIVATE_HEADER = 'X-Statum-Private';
  33. /** Session-cookie marker used to detect a fresh browser session. */
  34. var SESSION_COOKIE = '_statum_sdc';
  35. /** BroadcastChannel name used to sync session/device state across tabs. */
  36. var CHANNEL_NAME = 'statum';
  37. /** localStorage / sessionStorage key prefix for persisted frames. */
  38. var STORAGE_PREFIX = 'statum:';
  39. // ---------------------------------------------------------------------------
  40. // Configuration
  41. // ---------------------------------------------------------------------------
  42. /**
  43. * Endpoint URLs. These defaults may be overridden per-page with the
  44. * `stm-entrypoint` and `stm-slots` attributes on the `<body>` element.
  45. *
  46. * @type {{entrypointUrl: string, slotsUrl: string}}
  47. */
  48. var config = {
  49. entrypointUrl: '/_statum/entrypoint',
  50. slotsUrl: '/_statum/slots',
  51. channelUrl: '/_statum/channel',
  52. // The realtime worker is embedded in the library as a default resource
  53. // (served at /_statum/resource/statum-worker.js); override with stm-worker.
  54. workerUrl: '/_statum/resource/statum-worker.js'
  55. };
  56. // ---------------------------------------------------------------------------
  57. // State store
  58. // ---------------------------------------------------------------------------
  59. /**
  60. * In-memory store, keyed by slot type. Each value is `{frame, snapshot}`
  61. * where `snapshot` is the parsed `frame.content`. This map is the single
  62. * source of truth for rendering; persistent backends merely hydrate it.
  63. *
  64. * @type {Map<string, {frame: object, snapshot: object}>}
  65. */
  66. var store = new Map();
  67. /** Listeners, keyed by type name. @type {Map<string, Set<Function>>} */
  68. var listeners = new Map();
  69. /**
  70. * Idempotency tracking: slot key -> last-applied frame `signature`. Held in
  71. * memory only (per tab), so a frame already persisted by another tab still
  72. * re-draws a tab whose tracking lags. Entries are dropped on clear so a
  73. * replayed frame re-applies.
  74. * @type {Map<string, string>}
  75. */
  76. var signatures = new Map();
  77. /** Optional UI handlers (set via `statum.on*Handler`). */
  78. var handlers = { onConfirm: null, onNotify: null, onError: null };
  79. /** @type {BroadcastChannel|null} */
  80. var channel = null;
  81. /** Whether {@link init} has already run. */
  82. var initialized = false;
  83. /** Whether the entrypoint has been fetched (guards without pre-entrypoint
  84. * only evaluate after this). */
  85. var entrypointLoaded = false;
  86. /** Set when a guard has triggered a redirect, so further work is skipped. */
  87. var guardRedirected = false;
  88. // ---------------------------------------------------------------------------
  89. // Small utilities
  90. // ---------------------------------------------------------------------------
  91. /**
  92. * Parse an ISO 8601 timestamp to epoch millis, or `undefined`.
  93. * @param {string|undefined} s
  94. * @returns {number|undefined}
  95. */
  96. function parseTime(s) {
  97. if (!s) return undefined;
  98. var t = new Date(s).getTime();
  99. return isNaN(t) ? undefined : t;
  100. }
  101. /**
  102. * Base64-encode a UTF-8 string (safe for frames containing non-Latin1 data).
  103. * @param {string} str
  104. * @returns {string}
  105. */
  106. function b64encode(str) {
  107. var bytes = new TextEncoder().encode(str);
  108. var bin = '';
  109. var chunk = 0x8000;
  110. for (var i = 0; i < bytes.length; i += chunk) {
  111. bin += String.fromCharCode.apply(null, bytes.subarray(i, i + chunk));
  112. }
  113. return btoa(bin);
  114. }
  115. /** Read a cookie value, or `null` if absent. @param {string} name */
  116. function getCookie(name) {
  117. var escaped = name.replace(/([.$?*|{}()[\]\\/+^])/g, '\\$1');
  118. var match = document.cookie.match(new RegExp('(?:^|; )' + escaped + '=([^;]*)'));
  119. return match ? decodeURIComponent(match[1]) : null;
  120. }
  121. /** Set a session cookie (no expiry => cleared when the browser closes). */
  122. function setCookie(name, value) {
  123. document.cookie = name + '=' + encodeURIComponent(value) + '; path=/; SameSite=Lax';
  124. }
  125. // ---------------------------------------------------------------------------
  126. // Expression evaluation
  127. // ---------------------------------------------------------------------------
  128. /**
  129. * Compiled-expression cache. Expressions are evaluated as JavaScript against
  130. * a scope object (the page's HTML is trusted, per the model).
  131. * @type {Map<string, Function>}
  132. */
  133. var exprCache = new Map();
  134. /**
  135. * Wrap a scope for expression evaluation so bare identifiers resolve in a
  136. * controlled order: names on the scope (slot types, loop variables,
  137. * `stm-def-*` locals) win; names missing from the scope but present on
  138. * `globalThis` (`Math`, `parseInt`, `String`, …) forward to that global;
  139. * anything else resolves to `undefined` instead of throwing a
  140. * `ReferenceError` or leaking an unintended global. The `has` trap claims
  141. * every name so `with` never falls through around the proxy, and the inner
  142. * try/catch of the compiled expression still turns property access on a
  143. * resolved `undefined`/`null` into `undefined` for that expression alone.
  144. * @param {object} scope
  145. * @returns {Proxy<object>}
  146. */
  147. function evalScope(scope) {
  148. return new Proxy(scope, {
  149. has: function () { return true; },
  150. get: function (target, name) {
  151. if (name in target) return target[name];
  152. if (typeof name === 'string' && name in globalThis) return globalThis[name];
  153. return undefined;
  154. }
  155. });
  156. }
  157. /**
  158. * Compile (and cache) an expression string into a function of `scope`.
  159. * Uses `with` so that arbitrary type names and loop variables are resolved
  160. * as bare identifiers. Returns a function that yields `undefined` on any
  161. * runtime or compile error.
  162. * @param {string} expr
  163. * @returns {Function}
  164. */
  165. function compileExpr(expr) {
  166. var cached = exprCache.get(expr);
  167. if (cached !== undefined) return cached;
  168. var fn;
  169. try {
  170. // Function-constructor bodies are non-strict by default, so `with` is
  171. // permitted. The inner try/catch turns runtime errors (property access
  172. // on an unset slot's `undefined`) into `undefined` so a missing path
  173. // simply yields no value; missing identifiers already resolve to
  174. // `undefined` via the evalScope proxy.
  175. fn = new Function('scope', 'with(scope){try{return (' + expr + ');}catch(e){return undefined;}}');
  176. } catch (e) {
  177. fn = function () { return undefined; };
  178. }
  179. exprCache.set(expr, fn);
  180. return fn;
  181. }
  182. /**
  183. * Evaluate an expression against a scope.
  184. * @param {string} expr
  185. * @param {object} [scope]
  186. * @returns {*} `undefined` if the expression is empty or fails.
  187. */
  188. function evalExpr(expr, scope) {
  189. if (expr == null || expr === '') return undefined;
  190. try {
  191. return compileExpr(expr)(evalScope(scope || {}));
  192. } catch (e) {
  193. return undefined;
  194. }
  195. }
  196. /**
  197. * Build a child scope that inherits the parent (so type bindings remain
  198. * visible) and adds one own loop variable.
  199. * @param {object} parent
  200. * @param {string} name
  201. * @param {*} value
  202. * @returns {object}
  203. */
  204. function childScope(parent, name, value) {
  205. var scope = Object.create(parent || null);
  206. scope[name] = value;
  207. return scope;
  208. }
  209. // ---------------------------------------------------------------------------
  210. // StatumError
  211. // ---------------------------------------------------------------------------
  212. /**
  213. * Error type thrown for HTTP failures and `error` directives.
  214. * @param {string} [message]
  215. * @param {string} [code]
  216. * @param {object} [data]
  217. */
  218. function StatumError(message, code, data) {
  219. this.name = 'StatumError';
  220. this.message = message || '';
  221. this.code = code || undefined;
  222. this.data = data || undefined;
  223. }
  224. StatumError.prototype = Object.create(Error.prototype);
  225. // ---------------------------------------------------------------------------
  226. // UI handlers (confirm / notify / error)
  227. // ---------------------------------------------------------------------------
  228. /**
  229. * Run the `notify` directive's default behaviour or the custom
  230. * `statum.onNotifyHandler`. The default surfaces the message via `alert()`.
  231. * @param {string} [kind] Application-defined category (freeform).
  232. * @param {string} [message]
  233. */
  234. function triggerNotify(kind, message) {
  235. var fn = handlers.onNotify;
  236. try {
  237. if (fn) fn(kind, message);
  238. else if (message != null) window.alert(message);
  239. } catch (e) { console.error('[statum] notify handler error', e); }
  240. }
  241. /**
  242. * Run the `stm-confirm` gate: the custom `statum.onConfirmHandler` if set,
  243. * otherwise `window.confirm`. Supports async handlers (custom modals).
  244. * @param {string} message
  245. * @param {HTMLElement} element
  246. * @returns {Promise<boolean>} truthy if the action should proceed.
  247. */
  248. async function triggerConfirm(message, element) {
  249. var fn = handlers.onConfirm;
  250. try {
  251. if (fn) return !!(await fn(message, element));
  252. return !!window.confirm(message);
  253. } catch (e) {
  254. console.error('[statum] confirm handler error', e);
  255. return false;
  256. }
  257. }
  258. /**
  259. * Run the custom `statum.onErrorHandler`, if set. Returns whether the default
  260. * behaviour (promise rejection + `stm-on-error` classes) should proceed: the
  261. * handler suppresses the default by returning (or resolving) `false`.
  262. * @param {StatumError} error
  263. * @param {HTMLElement|null} element
  264. * @returns {Promise<boolean>}
  265. */
  266. async function triggerError(error, element) {
  267. var fn = handlers.onError;
  268. if (!fn) return true;
  269. try {
  270. var suppress = await fn(error, element);
  271. return suppress !== false;
  272. } catch (e) {
  273. console.error('[statum] error handler error', e);
  274. return true;
  275. }
  276. }
  277. /**
  278. * Surface a failure: run `triggerError`, and if the default is not
  279. * suppressed, apply `stm-on-error` classes (when an origin element exists)
  280. * and re-throw so the originating promise rejects.
  281. * @param {StatumError} error
  282. * @param {HTMLElement|null} element
  283. */
  284. async function reportFailure(error, element) {
  285. if (await triggerError(error, element)) {
  286. if (element) applyErrorClasses(element, true);
  287. throw error;
  288. }
  289. }
  290. // ---------------------------------------------------------------------------
  291. // Persistence
  292. // ---------------------------------------------------------------------------
  293. /**
  294. * Pick the storage backend for a scope.
  295. * @param {string} scope
  296. * @returns {Storage|null} `null` for in-memory scopes.
  297. */
  298. function storageFor(scope) {
  299. if (scope === 'device' || scope === 'session') return localStorage;
  300. if (scope === 'flow') return sessionStorage;
  301. return null; // page / transient
  302. }
  303. /**
  304. * Persist a slot's frame to the backend matching its scope, removing any
  305. * stale copy from the other backend first (in case the scope changed).
  306. * @param {string} type
  307. * @param {{frame: object, snapshot: object}} entry
  308. */
  309. function persistEntry(type, entry) {
  310. var scope = entry.snapshot.slot && entry.snapshot.slot.scope;
  311. removePersisted(type);
  312. var storage = storageFor(scope);
  313. if (!storage) return;
  314. try {
  315. storage.setItem(STORAGE_PREFIX + type, JSON.stringify(entry.frame));
  316. } catch (e) {
  317. /* storage full or unavailable; remain in-memory only */
  318. }
  319. }
  320. /** Remove a persisted frame from both backends. @param {string} type */
  321. function removePersisted(type) {
  322. try { localStorage.removeItem(STORAGE_PREFIX + type); } catch (e) {}
  323. try { sessionStorage.removeItem(STORAGE_PREFIX + type); } catch (e) {}
  324. }
  325. /** Load every persisted frame from a backend into the in-memory store. */
  326. function loadFrom(storage) {
  327. for (var i = 0; i < storage.length; i++) {
  328. var key = storage.key(i);
  329. if (!key || key.indexOf(STORAGE_PREFIX) !== 0) continue;
  330. try {
  331. var frame = JSON.parse(storage.getItem(key));
  332. var snapshot = JSON.parse(frame.content);
  333. var type = snapshot.slot && snapshot.slot.type;
  334. if (type && !store.has(type)) store.set(type, { frame: frame, snapshot: snapshot });
  335. } catch (e) {
  336. /* corrupt entry: ignore */
  337. }
  338. }
  339. }
  340. /** Hydrate the store from localStorage and sessionStorage. */
  341. function hydrate() {
  342. try { loadFrom(localStorage); } catch (e) {}
  343. try { loadFrom(sessionStorage); } catch (e) {}
  344. }
  345. // ---------------------------------------------------------------------------
  346. // Session-cookie initialization
  347. // ---------------------------------------------------------------------------
  348. /**
  349. * Detect a fresh browser session using the `_statum_sdc` session cookie.
  350. * On a fresh session, clear all `session`-scoped persisted frames, then set
  351. * the marker. Session cookies are shared across tabs, so a tab opened
  352. * mid-session sees the marker and leaves session data intact.
  353. */
  354. function initSession() {
  355. if (getCookie(SESSION_COOKIE) !== null) return;
  356. clearSessionSlotsFromStorage();
  357. setCookie(SESSION_COOKIE, '1');
  358. }
  359. /** Remove all `session`-scoped frames from localStorage. */
  360. function clearSessionSlotsFromStorage() {
  361. var toRemove = [];
  362. for (var i = 0; i < localStorage.length; i++) {
  363. var key = localStorage.key(i);
  364. if (!key || key.indexOf(STORAGE_PREFIX) !== 0) continue;
  365. try {
  366. var frame = JSON.parse(localStorage.getItem(key));
  367. var snapshot = JSON.parse(frame.content);
  368. if (snapshot.slot && snapshot.slot.scope === 'session') toRemove.push(key);
  369. } catch (e) {}
  370. }
  371. for (var j = 0; j < toRemove.length; j++) localStorage.removeItem(toRemove[j]);
  372. }
  373. // ---------------------------------------------------------------------------
  374. // Listeners & cross-tab broadcast
  375. // ---------------------------------------------------------------------------
  376. /**
  377. * Fire all listeners for a type. (Renamed from `notify` to avoid confusion
  378. * with the `notify` directive.)
  379. * @param {string} type
  380. * @param {object|null} frame
  381. * @param {object|null} snapshot
  382. */
  383. function fireListeners(type, frame, snapshot) {
  384. var set = listeners.get(type);
  385. if (!set) return;
  386. var event = { type: type, frame: frame, snapshot: snapshot };
  387. set.forEach(function (cb) {
  388. try { cb(event); } catch (e) { console.error('[statum] listener error', e); }
  389. });
  390. }
  391. /**
  392. * Broadcast a state change to other tabs. Only `session`/`device` scopes are
  393. * shared (flow/page/transient are per-tab).
  394. * @param {object} message
  395. * @param {string} [scope]
  396. */
  397. function broadcast(message, scope) {
  398. if (!channel) return;
  399. if (scope !== 'session' && scope !== 'device') return;
  400. try { channel.postMessage(message); } catch (e) {}
  401. }
  402. /**
  403. * Broadcast a message to other tabs regardless of slot scope. Used to relay
  404. * realtime (live) events so they reach every tab, not just session/device
  405. * ones.
  406. */
  407. function broadcastAlways(message) {
  408. if (!channel) return;
  409. try { channel.postMessage(message); } catch (e) {}
  410. }
  411. /** Open the BroadcastChannel and wire inbound messages. */
  412. function setupChannel() {
  413. if (typeof BroadcastChannel === 'undefined') return;
  414. try {
  415. channel = new BroadcastChannel(CHANNEL_NAME);
  416. } catch (e) {
  417. channel = null;
  418. return;
  419. }
  420. channel.onmessage = function (ev) {
  421. var msg = ev.data;
  422. if (!msg) return;
  423. if (msg.kind === 'set' && msg.frame) {
  424. try {
  425. var snapshot = JSON.parse(msg.frame.content);
  426. var type = snapshot.slot && snapshot.slot.type;
  427. if (type && commitSet(msg.frame, snapshot, type, false)) renderAll();
  428. } catch (e) { /* ignore malformed */ }
  429. } else if (msg.kind === 'clear') {
  430. var t = msg.type;
  431. if (!t && msg.key != null) {
  432. store.forEach(function (entry, type) {
  433. if (entry.snapshot.slot && entry.snapshot.slot.key === msg.key) t = type;
  434. });
  435. }
  436. if (t) clearType(t, { broadcast: false });
  437. else if (msg.key != null) signatures.delete(msg.key);
  438. renderAll();
  439. }
  440. };
  441. }
  442. // ---------------------------------------------------------------------------
  443. // State mutation
  444. // ---------------------------------------------------------------------------
  445. /**
  446. * Remove a type from the store, un-persist it, drop its idempotency entry,
  447. * fire listeners, and (optionally) broadcast the clear to other tabs.
  448. * @param {string} type
  449. * @param {{broadcast?: boolean}} [opts]
  450. */
  451. function clearType(type, opts) {
  452. var entry = store.get(type);
  453. if (!entry) return;
  454. var scope = entry.snapshot.slot && entry.snapshot.slot.scope;
  455. var key = entry.snapshot.slot && entry.snapshot.slot.key;
  456. store.delete(type);
  457. removePersisted(type);
  458. if (key) signatures.delete(key);
  459. fireListeners(type, null, null);
  460. if (opts && opts.broadcast) broadcast({ kind: 'clear', key: key, type: type }, scope);
  461. }
  462. /**
  463. * Resolve a slot key to its type and clear it. Used by the `clear` directive
  464. * (keyed) and by live `clear` events.
  465. * @param {string} key
  466. * @param {boolean} [broadcast]
  467. */
  468. function clearByKey(key, broadcast) {
  469. var typeToRemove = null;
  470. store.forEach(function (entry, type) {
  471. if (entry.snapshot.slot && entry.snapshot.slot.key === key) typeToRemove = type;
  472. });
  473. if (typeToRemove) clearType(typeToRemove, { broadcast: !!broadcast });
  474. else if (key) signatures.delete(key);
  475. }
  476. /**
  477. * Resolve a frame signature to its slot type and clear it. Used by the
  478. * `invalidate` directive, which references a signature (not a key) because the
  479. * server reports a bad signature without trusting the frame's content.
  480. * @param {string} signature
  481. * @param {boolean} [broadcast]
  482. */
  483. function clearBySignature(signature, broadcast) {
  484. var typeToRemove = null;
  485. store.forEach(function (entry, type) {
  486. if (entry.frame && entry.frame.signature === signature) typeToRemove = type;
  487. });
  488. if (typeToRemove) clearType(typeToRemove, { broadcast: !!broadcast });
  489. else if (signature) signatures.delete(signature);
  490. }
  491. /**
  492. * Commit a `set` to the in-memory store, persist it, and fire listeners.
  493. * Idempotent: if the frame's `signature` matches the last-applied signature
  494. * for this slot (tracked in {@link signatures}), nothing happens and `false`
  495. * is returned. When `doBroadcast` is true the set is forwarded to other tabs
  496. * via the scope-gated broadcast (session/device only).
  497. * @param {object} frame
  498. * @param {object} snapshot
  499. * @param {string} type
  500. * @param {boolean} doBroadcast
  501. * @returns {boolean} `true` if state changed.
  502. */
  503. function commitSet(frame, snapshot, type, doBroadcast) {
  504. var key = snapshot.slot && snapshot.slot.key;
  505. var sig = frame.signature;
  506. if (key && sig !== undefined && signatures.get(key) === sig) return false;
  507. var entry = { frame: frame, snapshot: snapshot };
  508. store.set(type, entry);
  509. persistEntry(type, entry);
  510. fireListeners(type, frame, snapshot);
  511. if (key && sig !== undefined) signatures.set(key, sig);
  512. if (doBroadcast) {
  513. var scope = snapshot.slot && snapshot.slot.scope;
  514. broadcast({ kind: 'set', frame: frame }, scope);
  515. }
  516. return true;
  517. }
  518. /**
  519. * Apply a `set` directive: store/refresh a slot's snapshot (idempotently),
  520. * broadcasting to other tabs.
  521. * @param {object} directive `{ snapshot_frame }`
  522. */
  523. function applySet(directive) {
  524. var frame = directive.snapshot_frame;
  525. if (!frame || !frame.content) return;
  526. var snapshot;
  527. try { snapshot = JSON.parse(frame.content); } catch (e) { return; }
  528. var type = snapshot.slot && snapshot.slot.type;
  529. if (!type) return;
  530. commitSet(frame, snapshot, type, true);
  531. }
  532. /**
  533. * Apply a `clear` directive. The directive carries a slot key, so the type
  534. * holding that key is resolved and removed.
  535. * @param {object} directive `{ key }`
  536. */
  537. function applyClear(directive) {
  538. if (directive.key == null) return;
  539. clearByKey(directive.key, true);
  540. }
  541. /**
  542. * Apply a live `set` event received over the realtime channel. The frame is
  543. * committed (idempotently) and, when new, broadcast to sibling tabs via the
  544. * scope-agnostic {@link broadcastAlways} so every tab sees it regardless of
  545. * which (or how many) tabs hold a subscription.
  546. * @param {object} frame
  547. */
  548. function applyRemoteSet(frame) {
  549. try {
  550. var snapshot = JSON.parse(frame.content);
  551. var type = snapshot.slot && snapshot.slot.type;
  552. if (!type) return;
  553. if (commitSet(frame, snapshot, type, false)) {
  554. broadcastAlways({ kind: 'set', frame: frame });
  555. renderAll();
  556. }
  557. } catch (e) { /* malformed frame */ }
  558. }
  559. /** Apply a live `clear` event received over the realtime channel. */
  560. function applyRemoteClear(key) {
  561. if (key == null) return;
  562. signatures.delete(key);
  563. clearByKey(key, false);
  564. broadcastAlways({ kind: 'clear', key: key });
  565. renderAll();
  566. }
  567. // ---------------------------------------------------------------------------
  568. // Snapshot freshness & request headers
  569. // ---------------------------------------------------------------------------
  570. /**
  571. * Categorize a held snapshot relative to the current time.
  572. * @returns {'silent'|'always'|'invalid'|'stale'|'fresh'}
  573. * - `silent`: unidirectional (`transmit_after` undefined) - never sent.
  574. * - `always`: `transmit_after === as_at` - send the base64 frame each time.
  575. * - `invalid`: past `invalid_after` - drop and refetch.
  576. * - `stale`: past `transmit_after` but not yet invalid - pre-flight first.
  577. * - `fresh`: still cached server-side - send the `as_at` reference.
  578. */
  579. function entryCategory(entry) {
  580. var snap = entry.snapshot;
  581. var transmit = snap.transmit_after;
  582. if (transmit === undefined || transmit === null) return 'silent';
  583. if (transmit === snap.as_at) return 'always';
  584. var now = Date.now();
  585. var invalidAt = parseTime(snap.invalid_after);
  586. var transmitAt = parseTime(transmit);
  587. if (invalidAt !== undefined && now >= invalidAt) return 'invalid';
  588. if (transmitAt !== undefined && now >= transmitAt) return 'stale';
  589. return 'fresh';
  590. }
  591. /**
  592. * Drop locally-invalid snapshots and pre-flight any stale ones. Pre-flighting
  593. * posts the stale frames to the slot endpoint and applies the returned `set`
  594. * directives, refreshing their `as_at` values before the real request runs.
  595. *
  596. * Single-flight: concurrent callers share one in-flight preparation.
  597. * @returns {Promise<void>}
  598. */
  599. var preparePromise = null;
  600. function prepareSlots() {
  601. if (preparePromise) return preparePromise;
  602. preparePromise = doPrepareSlots().then(function () {
  603. preparePromise = null;
  604. }, function () {
  605. preparePromise = null;
  606. });
  607. return preparePromise;
  608. }
  609. async function doPrepareSlots() {
  610. var stale = [];
  611. store.forEach(function (entry, type) {
  612. var cat = entryCategory(entry);
  613. if (cat === 'invalid') {
  614. clearType(type, { broadcast: false });
  615. } else if (cat === 'stale') {
  616. stale.push(entry.frame);
  617. }
  618. });
  619. if (stale.length) {
  620. var directives = await postSlots(stale);
  621. var pfResult = applyDirectives(directives, { originElement: null });
  622. executeTerminal(pfResult);
  623. }
  624. }
  625. /**
  626. * Build the `X-Statum-Slot` header values for every held slot, using the
  627. * freshness rules. Assumes {@link prepareSlots} has just run.
  628. * @returns {string[]}
  629. */
  630. function buildSlotHeaders() {
  631. var headers = [];
  632. store.forEach(function (entry) {
  633. var snap = entry.snapshot;
  634. var cat = entryCategory(entry);
  635. if (cat === 'silent' || cat === 'invalid') return;
  636. if (cat === 'always') {
  637. headers.push(b64encode(JSON.stringify(entry.frame)));
  638. } else {
  639. headers.push('key=' + snap.slot.key + '; as_at=' + snap.as_at);
  640. }
  641. });
  642. return headers;
  643. }
  644. /**
  645. * Collect the current frames held for the given slot keys, in the order the
  646. * keys are first supplied. Used by the `transmit` directive (which forces a
  647. * slot's frame to be posted as if its `transmit_after` had elapsed). Keys the
  648. * client does not currently hold are skipped.
  649. * @param {string[]} keys
  650. * @returns {object[]}
  651. */
  652. function collectFramesForKeys(keys) {
  653. var keySet = Object.create(null);
  654. for (var i = 0; i < keys.length; i++) keySet[keys[i]] = true;
  655. var frames = [];
  656. store.forEach(function (entry) {
  657. var key = entry.snapshot.slot && entry.snapshot.slot.key;
  658. if (key && keySet[key]) {
  659. frames.push(entry.frame);
  660. delete keySet[key];
  661. }
  662. });
  663. return frames;
  664. }
  665. // ---------------------------------------------------------------------------
  666. // HTTP helpers
  667. // ---------------------------------------------------------------------------
  668. /** True if a response is a Statum directive response. */
  669. function isStatum(res) {
  670. return (res.headers.get('Content-Type') || '').indexOf(STATUM_CONTENT_TYPE) !== -1;
  671. }
  672. /**
  673. * POST an array of frames to the slot endpoint (the pre-flight target) and
  674. * return its directive array. This request intentionally carries no slot
  675. * headers (it is itself the refresh).
  676. * @param {object[]} frames
  677. * @returns {Promise<object[]>}
  678. */
  679. async function postSlots(frames) {
  680. var headers = new Headers();
  681. headers.set('Accept', STATUM_CONTENT_TYPE);
  682. headers.set('Content-Type', 'application/json');
  683. var res = await fetch(config.slotsUrl, {
  684. method: 'POST',
  685. headers: headers,
  686. body: JSON.stringify(frames),
  687. credentials: 'same-origin'
  688. });
  689. if (!isStatum(res)) return [];
  690. try { return await res.json(); } catch (e) { return []; }
  691. }
  692. /**
  693. * Apply the non-terminal directives from a response (set/clear/subscribe/
  694. * unsubscribe/notify/transmit-collection), then `render`.
  695. *
  696. * Terminal directives (`navigate`, `post`), error directives, and any
  697. * transmit/retry intent are collected on the returned result rather than
  698. * executed here: {@link handleResponse} performs the asynchronous
  699. * transmission (and optional retry) and then runs terminal navigation, so
  700. * that a `transmit` with `retry` can re-issue the request before the page is
  701. * navigated away.
  702. * @param {object[]} directives
  703. * @param {{originElement?: HTMLElement}} [ctx]
  704. * @returns {{errors: StatumError[], transmitKeys: string[], retry: boolean, navigate: object|null, post: object|null}}
  705. */
  706. function applyDirectives(directives, ctx) {
  707. var result = { errors: [], transmitKeys: [], retry: false, navigate: null, post: null, formSubmits: [], formResets: [] };
  708. var list = Array.isArray(directives) ? directives : [];
  709. for (var i = 0; i < list.length; i++) {
  710. var d = list[i];
  711. if (!d || typeof d !== 'object') continue;
  712. switch (d.type) {
  713. case 'set': applySet(d); break;
  714. case 'clear': applyClear(d); break;
  715. case 'invalidate':
  716. if (d.signature != null) {
  717. console.warn('[statum] server could not verify slot frame ' + d.signature + '; clearing it');
  718. clearBySignature(d.signature, true);
  719. }
  720. break;
  721. case 'subscribe': channelSubscribe(d.key); break;
  722. case 'unsubscribe': channelUnsubscribe(d.key); break;
  723. case 'notify': triggerNotify(d.kind, d.message); break;
  724. case 'transmit':
  725. if (d.key != null) {
  726. if (result.transmitKeys.indexOf(d.key) === -1) result.transmitKeys.push(d.key);
  727. if (d.retry) result.retry = true;
  728. }
  729. break;
  730. case 'error':
  731. {
  732. var err = new StatumError(d.message, d.code, d.data);
  733. var detail = d.code ? (d.message + ' [' + d.code + ']') : d.message;
  734. console.error('[statum] error directive: ' + (detail || '(no message)'));
  735. result.errors.push(err);
  736. }
  737. break;
  738. case 'navigate': result.navigate = d; break;
  739. case 'post': result.post = d; break;
  740. case 'form-submit': result.formSubmits.push(d); break;
  741. case 'form-reset': result.formResets.push(d); break;
  742. }
  743. }
  744. renderAll();
  745. return result;
  746. }
  747. /** Execute the terminal directives collected by {@link applyDirectives}. */
  748. function executeTerminal(result) {
  749. result.formResets.forEach(doFormReset);
  750. result.formSubmits.forEach(doFormSubmit);
  751. if (result.navigate) doNavigate(result.navigate);
  752. if (result.post) doPost(result.post);
  753. }
  754. /** Execute a `form-submit` directive: optionally override action/method, then submit. */
  755. function doFormSubmit(d) {
  756. var form = document.getElementById(d.form);
  757. if (form) {
  758. if (d.action) form.setAttribute('action', d.action);
  759. if (d.method) form.setAttribute('method', d.method);
  760. form.submit();
  761. }
  762. }
  763. /** Execute a `form-reset` directive. */
  764. function doFormReset(d) {
  765. var form = document.getElementById(d.form);
  766. if (form) form.reset();
  767. }
  768. /** Execute a `navigate` directive as a full page load. */
  769. function doNavigate(d) {
  770. if (d.uri) window.location.href = d.uri;
  771. }
  772. /** Execute a `post` directive as a real (navigating) form POST. */
  773. function doPost(d) {
  774. if (!d.uri) return;
  775. var form = document.createElement('form');
  776. form.method = 'POST';
  777. form.action = d.uri;
  778. form.style.display = 'none';
  779. var data = d.data || {};
  780. Object.keys(data).forEach(function (name) {
  781. var input = document.createElement('input');
  782. input.type = 'hidden';
  783. input.name = name;
  784. input.value = data[name] == null ? '' : String(data[name]);
  785. form.appendChild(input);
  786. });
  787. document.body.appendChild(form);
  788. form.submit();
  789. }
  790. /**
  791. * Handle a fetch response: if it is a Statum response, apply its directives;
  792. * otherwise throw on HTTP errors and no-op on other successful responses.
  793. *
  794. * Directive ordering: non-terminal directives are applied and the page
  795. * rendered; then any `transmit` directives force their slot frames to be
  796. * posted (applying the directives the slot endpoint returns); then, if a
  797. * transmit requested a retry, the originating request (`ctx.retry`) is
  798. * re-issued and this response's terminal directives and errors are skipped.
  799. * Otherwise terminal navigation runs, then error directives are surfaced.
  800. * @param {Response} res
  801. * @param {{originElement?: HTMLElement, retry?: Function}} [ctx]
  802. */
  803. async function handleResponse(res, ctx) {
  804. var el = ctx && ctx.originElement;
  805. if (!isStatum(res)) {
  806. if (!res.ok) await reportFailure(new StatumError('HTTP ' + res.status), el);
  807. return;
  808. }
  809. var directives;
  810. try { directives = await res.json(); } catch (e) { directives = []; }
  811. var result = applyDirectives(directives, ctx);
  812. if (result.transmitKeys && result.transmitKeys.length) {
  813. var frames = collectFramesForKeys(result.transmitKeys);
  814. if (frames.length) {
  815. var txDirectives = await postSlots(frames);
  816. applyDirectives(txDirectives, { originElement: el });
  817. }
  818. }
  819. if (result.retry && ctx && typeof ctx.retry === 'function') {
  820. await ctx.retry();
  821. return;
  822. }
  823. executeTerminal(result);
  824. var errors = result.errors || [];
  825. for (var i = 0; i < errors.length; i++) {
  826. await reportFailure(errors[i], el);
  827. }
  828. }
  829. // ---------------------------------------------------------------------------
  830. // Entrypoint & action requests
  831. // ---------------------------------------------------------------------------
  832. /**
  833. * Fetch the entrypoint for the current URL, applying its directives. Carries
  834. * slot headers (and pre-flights) like any other request. The request is
  835. * wrapped in an `attempt` closure passed as the response `retry` callback, so
  836. * a `transmit` directive with `retry` can re-issue it after transmission.
  837. * @returns {Promise<void>}
  838. */
  839. function loadEntrypoint() {
  840. if (guardRedirected) return Promise.resolve();
  841. // From this point on guards are "post-entrypoint" (all of them evaluate).
  842. entrypointLoaded = true;
  843. var attempt = async function () {
  844. await prepareSlots();
  845. var headers = new Headers();
  846. headers.set('Accept', STATUM_CONTENT_TYPE);
  847. buildSlotHeaders().forEach(function (v) { headers.append(SLOT_HEADER, v); });
  848. var url = config.entrypointUrl + '?uri=' + encodeURIComponent(window.location.href);
  849. var res = await fetch(url, { headers: headers, credentials: 'same-origin' });
  850. await handleResponse(res, { originElement: null, retry: attempt });
  851. };
  852. return attempt();
  853. }
  854. /**
  855. * Perform an action request.
  856. *
  857. * The request is wrapped in an `attempt` closure passed as the response
  858. * `retry` callback, so a `transmit` directive with `retry` can re-issue the
  859. * same action after the transmission (rebuilding headers from current state).
  860. *
  861. * @param {object} action `{ uri, method, private }`
  862. * @param {object} [data] Key/value parameters. Encoded as query string for
  863. * GET/HEAD, otherwise as `application/x-www-form-urlencoded`.
  864. * @param {HTMLElement} [originElement] Element that triggered the action, so
  865. * that `stm-on-error` classes can be applied on an `error` directive.
  866. * @returns {Promise<void>} Resolves once the request completes and its
  867. * directives have run; rejects on HTTP failure or an `error` directive.
  868. */
  869. function performAction(action, data, originElement) {
  870. var attempt = async function () {
  871. await prepareSlots();
  872. var headers = new Headers();
  873. headers.set('Accept', STATUM_CONTENT_TYPE);
  874. buildSlotHeaders().forEach(function (v) { headers.append(SLOT_HEADER, v); });
  875. if (action.private) headers.set(PRIVATE_HEADER, action.private);
  876. var method = (action.method || 'GET').toUpperCase();
  877. var params = data || {};
  878. var init = { method: method, headers: headers, credentials: 'same-origin' };
  879. var url = action.uri;
  880. if (method === 'GET' || method === 'HEAD') {
  881. var qs = new URLSearchParams(params).toString();
  882. if (qs) url += (url.indexOf('?') !== -1 ? '&' : '?') + qs;
  883. } else {
  884. init.body = new URLSearchParams(params).toString();
  885. headers.set('Content-Type', 'application/x-www-form-urlencoded');
  886. }
  887. var res;
  888. try {
  889. res = await fetch(url, init);
  890. } catch (networkErr) {
  891. await reportFailure(new StatumError('Network error'), originElement);
  892. return;
  893. }
  894. await handleResponse(res, { originElement: originElement, retry: attempt });
  895. };
  896. return attempt();
  897. }
  898. // ---------------------------------------------------------------------------
  899. // Realtime channel (subscribe/unsubscribe directives)
  900. // ---------------------------------------------------------------------------
  901. /**
  902. * Per-tab fallback engine, used when `SharedWorker` is unavailable. Owns an
  903. * `EventSource`, reads the channel id from the first `event: channel`,
  904. * reference-counts slot keys within this tab, PATCHes subscription changes,
  905. * applies incoming set/clear events (broadcasting them to siblings), and
  906. * closes the stream once it has no subscriptions.
  907. */
  908. function createFallbackEngine() {
  909. var es = null;
  910. var channelId = null;
  911. var refs = new Map(); // slotKey -> count
  912. var pending = { subscribe: [], unsubscribe: [] };
  913. var patchScheduled = false;
  914. function openStream() {
  915. if (es) return;
  916. try { es = new EventSource(config.channelUrl); }
  917. catch (e) { es = null; return; }
  918. es.addEventListener('channel', function (ev) { channelId = ev.data; flushPatch(); });
  919. es.addEventListener('set', function (ev) {
  920. try { applyRemoteSet(JSON.parse(ev.data)); } catch (e) {}
  921. });
  922. es.addEventListener('clear', function (ev) { applyRemoteClear(ev.data); });
  923. es.onerror = function () { /* EventSource auto-reconnects */ };
  924. }
  925. function closeStream() {
  926. if (es) { try { es.close(); } catch (e) {} es = null; }
  927. channelId = null;
  928. }
  929. function schedulePatch() {
  930. if (patchScheduled) return;
  931. patchScheduled = true;
  932. Promise.resolve().then(function () { patchScheduled = false; flushPatch(); });
  933. }
  934. function flushPatch() {
  935. if (!channelId) return;
  936. var sub = pending.subscribe, uns = pending.unsubscribe;
  937. if (!sub.length && !uns.length) return;
  938. pending = { subscribe: [], unsubscribe: [] };
  939. var body = {};
  940. if (sub.length) body.subscribe = sub;
  941. if (uns.length) body.unsubscribe = uns;
  942. try {
  943. fetch(config.channelUrl + '/' + encodeURIComponent(channelId), {
  944. method: 'PATCH',
  945. headers: { 'Content-Type': 'application/json' },
  946. credentials: 'same-origin',
  947. body: JSON.stringify(body)
  948. }).catch(function () {});
  949. } catch (e) {}
  950. }
  951. return {
  952. subscribe: function (key) {
  953. var c = refs.get(key) || 0;
  954. refs.set(key, c + 1);
  955. if (c === 0) { openStream(); pending.subscribe.push(key); schedulePatch(); }
  956. },
  957. unsubscribe: function (key) {
  958. var c = refs.get(key) || 0;
  959. if (c <= 0) return;
  960. if (c - 1 <= 0) {
  961. refs.delete(key);
  962. pending.unsubscribe.push(key);
  963. schedulePatch();
  964. if (refs.size === 0) setTimeout(function () { if (refs.size === 0) closeStream(); }, 0);
  965. } else {
  966. refs.set(key, c - 1);
  967. }
  968. }
  969. };
  970. }
  971. /**
  972. * Channel manager. Prefers a `SharedWorker` (which owns the single SSE
  973. * connection, reference-counts subscriptions across tabs, and relays events
  974. * through the cross-tab `BroadcastChannel`); falls back to a per-tab
  975. * `EventSource` engine when `SharedWorker` is unavailable or the worker
  976. * script fails to load. Tracks the true per-slot subscription count so it can
  977. * replay active subscriptions into the fallback on a mid-session switch.
  978. */
  979. function createChannelManager() {
  980. var port = null;
  981. var workerObj = null;
  982. var fallback = null;
  983. var mode = null; // 'worker' | 'fallback' | null
  984. var counts = new Map(); // slotKey -> count (true subscription state)
  985. function switchToFallback() {
  986. if (mode === 'fallback') return;
  987. mode = 'fallback';
  988. port = null;
  989. workerObj = null;
  990. fallback = createFallbackEngine();
  991. counts.forEach(function (c, key) {
  992. for (var i = 0; i < c; i++) fallback.subscribe(key);
  993. });
  994. }
  995. function ensure() {
  996. if (mode !== null) return;
  997. if (typeof SharedWorker !== 'undefined') {
  998. try {
  999. workerObj = new SharedWorker(config.workerUrl);
  1000. port = workerObj.port;
  1001. port.start();
  1002. port.postMessage({ op: 'init', url: config.channelUrl });
  1003. // The worker delivers events via the BroadcastChannel, so nothing is
  1004. // required on this port beyond command messages.
  1005. port.onmessage = function () {};
  1006. workerObj.onerror = function () {
  1007. console.warn('[statum] realtime worker failed; falling back to per-tab channel');
  1008. switchToFallback();
  1009. };
  1010. window.addEventListener('pagehide', function () {
  1011. if (mode === 'worker' && port) {
  1012. try { port.postMessage({ op: 'disconnect' }); } catch (e) {}
  1013. }
  1014. });
  1015. mode = 'worker';
  1016. return;
  1017. } catch (e) { workerObj = null; port = null; }
  1018. }
  1019. switchToFallback();
  1020. }
  1021. return {
  1022. subscribe: function (key) {
  1023. if (key == null) return;
  1024. ensure();
  1025. counts.set(key, (counts.get(key) || 0) + 1);
  1026. if (mode === 'worker') { try { port.postMessage({ op: 'subscribe', key: key }); } catch (e) {} }
  1027. else fallback.subscribe(key);
  1028. },
  1029. unsubscribe: function (key) {
  1030. if (key == null) return;
  1031. var c = (counts.get(key) || 0) - 1;
  1032. if (c <= 0) counts.delete(key); else counts.set(key, c);
  1033. ensure();
  1034. if (mode === 'worker') { try { port.postMessage({ op: 'unsubscribe', key: key }); } catch (e) {} }
  1035. else fallback.unsubscribe(key);
  1036. }
  1037. };
  1038. }
  1039. var channelManager = createChannelManager();
  1040. function channelSubscribe(key) { channelManager.subscribe(key); }
  1041. function channelUnsubscribe(key) { channelManager.unsubscribe(key); }
  1042. // ---------------------------------------------------------------------------
  1043. // Error-state classes
  1044. // ---------------------------------------------------------------------------
  1045. // (Moved from the render-walk section in statum-document.js so that
  1046. // reportFailure above is self-contained without that module.)
  1047. /** Apply or remove `stm-on-error` classes on an action element. */
  1048. function applyErrorClasses(el, on) {
  1049. if (!el || !el.hasAttribute || !el.hasAttribute('stm-on-error')) return;
  1050. var classes = (el.getAttribute('stm-on-error') || '').split(/\s+/).filter(Boolean);
  1051. classes.forEach(function (c) { on ? el.classList.add(c) : el.classList.remove(c); });
  1052. }
  1053. // ---------------------------------------------------------------------------
  1054. // Module seam: attribute-handler registry + render driver
  1055. // ---------------------------------------------------------------------------
  1056. //
  1057. // statum-core.js is self-sufficient: it owns the slot protocol, the UI
  1058. // handler overrides and the boot sequence, and never references the other
  1059. // modules. statum-document.js (the render walk) and statum-markdown.js
  1060. // (the CommonMark engine) load AFTER core and register through this seam.
  1061. //
  1062. // `_bridge` (underscore = private by convention, like `_testMarkdown`) is
  1063. // the internal cross-module surface; `statum.registerAttribute` is the
  1064. // public entry point module authors use.
  1065. /**
  1066. * Resolved execution order of the per-element `stm-*` bindings: an ordered
  1067. * list of `{name, fn, prefix}`. The render walk (statum-document.js)
  1068. * iterates it for every element. A throwing handler aborts that render
  1069. * cycle through renderAll's try/catch, exactly as the previous hardcoded
  1070. * call chain did, so handlers get no per-handler try/catch here.
  1071. * @type {Array<{name: string, fn: Function, prefix: boolean}>}
  1072. */
  1073. var attributeHandlers = [];
  1074. /**
  1075. * Register a handler for an `stm-*` attribute.
  1076. *
  1077. * `name` is either an exact attribute name (`'stm-disabled'`) or, when it
  1078. * ends with a dot, a prefix matcher (`'stm-class.'` matches any
  1079. * `stm-class.{name}`). The handler is called once per element per render
  1080. * cycle when the element carries at least one matching attribute; it then
  1081. * iterates the element's attributes itself (several may match a prefix).
  1082. *
  1083. * `opts.after` / `opts.before` name another registered attribute and the
  1084. * handler is inserted directly after / before it. A constraint naming an
  1085. * unregistered attribute warns and keeps plain registration order, so
  1086. * loading a module early cannot break the page. Registering the same name
  1087. * twice warns and ignores the second handler.
  1088. *
  1089. * @param {string} name
  1090. * @param {Function} fn `fn(el, scope)`
  1091. * @param {{after?: string, before?: string}} [opts]
  1092. */
  1093. function registerAttribute(name, fn, opts) {
  1094. if (typeof name !== 'string' || !name || typeof fn !== 'function') {
  1095. console.warn('[statum] registerAttribute: expected an attribute name and a handler function');
  1096. return;
  1097. }
  1098. for (var i = 0; i < attributeHandlers.length; i++) {
  1099. if (attributeHandlers[i].name === name) {
  1100. console.warn('[statum] registerAttribute: "' + name + '" is already registered; ignoring');
  1101. return;
  1102. }
  1103. }
  1104. var entry = { name: name, fn: fn, prefix: name.charAt(name.length - 1) === '.' };
  1105. var anchor = opts && (opts.after || opts.before);
  1106. var at = anchor ? handlerIndex(anchor) : -1;
  1107. if (anchor && at === -1) {
  1108. console.warn('[statum] registerAttribute: "' + anchor +
  1109. '" is not registered; keeping registration order for "' + name + '"');
  1110. }
  1111. if (at !== -1 && opts.after) at += 1; // insert directly after the anchor
  1112. if (at === -1) attributeHandlers.push(entry);
  1113. else attributeHandlers.splice(at, 0, entry);
  1114. }
  1115. /** Position of a registered handler by name, or -1. */
  1116. function handlerIndex(name) {
  1117. for (var i = 0; i < attributeHandlers.length; i++) {
  1118. if (attributeHandlers[i].name === name) return i;
  1119. }
  1120. return -1;
  1121. }
  1122. /**
  1123. * The render driver: installed by statum-document.js at load time, called
  1124. * by renderAll to walk the document. When absent (core loaded alone)
  1125. * render cycles still run the evaluate hooks and guards but skip the DOM
  1126. * walk.
  1127. * @type {Function|null}
  1128. */
  1129. var renderDriver = null;
  1130. /** Install the render driver. @param {Function} fn `fn(scope)` */
  1131. function installRenderDriver(fn) {
  1132. if (typeof fn === 'function') renderDriver = fn;
  1133. }
  1134. /**
  1135. * The module bridge: everything the other modules need from core (and the
  1136. * one thing core needs from them, the render driver) crosses here. The
  1137. * evaluate hooks stay core-private on purpose — no other module needs
  1138. * them; modules register attribute handlers instead.
  1139. */
  1140. var bridge = {
  1141. /** Expression machinery (core-owned). */
  1142. evalExpr: evalExpr,
  1143. childScope: childScope,
  1144. stateScope: stateScope,
  1145. /** Render cycle + requests. */
  1146. renderAll: renderAll,
  1147. loadEntrypoint: loadEntrypoint,
  1148. performAction: performAction,
  1149. /** UI handler overrides (runElementAction gates on confirm). */
  1150. triggerConfirm: triggerConfirm,
  1151. triggerNotify: triggerNotify,
  1152. triggerError: triggerError,
  1153. handlers: handlers,
  1154. /** Error-state classes for action elements. */
  1155. applyErrorClasses: applyErrorClasses,
  1156. /** The seam itself. */
  1157. registerAttribute: registerAttribute,
  1158. attributeHandlers: attributeHandlers,
  1159. installRenderDriver: installRenderDriver
  1160. };
  1161. /**
  1162. * Evaluate every `<link rel="stm-guard">` in the document head. A guard whose
  1163. * `require` predicate is false redirects the page to its `href`.
  1164. *
  1165. * Guards marked `pre-entrypoint` are evaluated on every cycle (including the
  1166. * initial, pre-entrypoint render, which uses only hydrated state); guards
  1167. * without it are evaluated only once the entrypoint has loaded. On every later
  1168. * evaluate cycle (set/clear) all guards are re-checked, so logging out, for
  1169. * example, can bounce the user off a guarded page.
  1170. */
  1171. function evaluateGuards() {
  1172. if (guardRedirected) return;
  1173. var scope = stateScope();
  1174. var guards = document.querySelectorAll('link[rel~="stm-guard"]');
  1175. for (var i = 0; i < guards.length; i++) {
  1176. var g = guards[i];
  1177. var preEntrypoint = g.hasAttribute('pre-entrypoint');
  1178. if (!preEntrypoint && !entrypointLoaded) continue;
  1179. var require = g.getAttribute('require');
  1180. if (!require) continue;
  1181. if (!evalExpr(require, scope)) {
  1182. guardRedirected = true;
  1183. var href = g.getAttribute('href') || '/';
  1184. console.warn('[statum] guard failed (' + require + '); redirecting to ' + href);
  1185. window.location.href = href;
  1186. return;
  1187. }
  1188. }
  1189. }
  1190. // ---------------------------------------------------------------------------
  1191. // Evaluation hooks (no-arg callbacks before/after each render cycle)
  1192. // ---------------------------------------------------------------------------
  1193. var beforeHooks = [];
  1194. var afterHooks = [];
  1195. /** Re-render the whole document against the current state. */
  1196. function renderAll() {
  1197. if (guardRedirected) return;
  1198. beforeHooks.forEach(function (fn) { try { fn(); } catch (e) { console.error('[statum] beforeEvaluate hook error', e); } });
  1199. try {
  1200. // The DOM walk lives in statum-document.js and is installed through
  1201. // the seam; without it the cycle still runs hooks and guards.
  1202. if (renderDriver) renderDriver(stateScope());
  1203. }
  1204. catch (e) { console.error('[statum] render error', e); }
  1205. afterHooks.forEach(function (fn) { try { fn(); } catch (e) { console.error('[statum] afterEvaluate hook error', e); } });
  1206. evaluateGuards();
  1207. }
  1208. // ---------------------------------------------------------------------------
  1209. // Boot visibility (stm-preloader / stm-content)
  1210. // ---------------------------------------------------------------------------
  1211. /**
  1212. * Toggle pre/post-entrypoint visibility with the `hidden` attribute. While
  1213. * loading, `stm-preloader` elements are shown and `stm-content` elements
  1214. * hidden; once ready, the reverse.
  1215. *
  1216. * To avoid a flash of un-bound template before the script runs, authors may
  1217. * pre-set `hidden` directly on `stm-content` in the HTML (e.g.
  1218. * `<div stm-content hidden>`); the library removes it once ready. The library
  1219. * also sets `hidden` itself during loading as a fallback for authors who do
  1220. * not pre-set it.
  1221. * @param {boolean} ready
  1222. */
  1223. function setBootState(ready) {
  1224. var preloaders = document.querySelectorAll('[stm-preloader]');
  1225. var contents = document.querySelectorAll('[stm-content]');
  1226. for (var i = 0; i < preloaders.length; i++) {
  1227. ready ? preloaders[i].setAttribute('hidden', '') : preloaders[i].removeAttribute('hidden');
  1228. }
  1229. for (var j = 0; j < contents.length; j++) {
  1230. ready ? contents[j].removeAttribute('hidden') : contents[j].setAttribute('hidden', '');
  1231. }
  1232. }
  1233. // ---------------------------------------------------------------------------
  1234. // Public state accessors
  1235. // ---------------------------------------------------------------------------
  1236. /** Build the scope used for expression evaluation: `{ typeName: public }`. */
  1237. function stateScope() {
  1238. var scope = {};
  1239. store.forEach(function (entry, type) { scope[type] = entry.snapshot.public; });
  1240. return scope;
  1241. }
  1242. /** Read a type's `public` data (what the attributes bind to). */
  1243. function read(type) {
  1244. var entry = store.get(type);
  1245. return entry ? entry.snapshot.public : undefined;
  1246. }
  1247. /** Read a type's full snapshot object. */
  1248. function getSnapshot(type) {
  1249. var entry = store.get(type);
  1250. return entry ? entry.snapshot : undefined;
  1251. }
  1252. /** Read the frame wrapping a type's snapshot. */
  1253. function getFrame(type) {
  1254. var entry = store.get(type);
  1255. return entry ? entry.frame : undefined;
  1256. }
  1257. /** Build an object of `{ typeName: public }` for every held type. */
  1258. function state() {
  1259. var result = {};
  1260. store.forEach(function (entry, type) { result[type] = entry.snapshot.public; });
  1261. return result;
  1262. }
  1263. /**
  1264. * Clear state. With a type argument, clears that type only; without, clears
  1265. * all held state.
  1266. * @param {string} [type]
  1267. */
  1268. function clear(type) {
  1269. if (type === undefined) {
  1270. Array.from(store.keys()).forEach(function (t) { clearType(t, { broadcast: true }); });
  1271. } else {
  1272. clearType(type, { broadcast: true });
  1273. }
  1274. renderAll();
  1275. }
  1276. /**
  1277. * Perform an action. `action` may be an action object or a string path that
  1278. * resolves to an action object within the current state.
  1279. * @param {object|string} action
  1280. * @param {object} [data]
  1281. * @returns {Promise<void>}
  1282. */
  1283. function act(action, data) {
  1284. var resolved = action;
  1285. if (typeof action === 'string') resolved = evalExpr(action, stateScope());
  1286. if (!resolved || typeof resolved.uri !== 'string') {
  1287. return Promise.reject(new StatumError('Invalid action'));
  1288. }
  1289. return performAction(resolved, data, null);
  1290. }
  1291. /** Attach a state listener for a type. */
  1292. function addStateListener(type, callback) {
  1293. if (typeof callback !== 'function') return;
  1294. if (!listeners.has(type)) listeners.set(type, new Set());
  1295. listeners.get(type).add(callback);
  1296. }
  1297. /** Remove a previously-attached state listener. */
  1298. function removeStateListener(type, callback) {
  1299. var set = listeners.get(type);
  1300. if (!set) return;
  1301. set.delete(callback);
  1302. if (set.size === 0) listeners.delete(type);
  1303. }
  1304. // ---------------------------------------------------------------------------
  1305. // Initialization
  1306. // ---------------------------------------------------------------------------
  1307. /**
  1308. * Inject the stylesheet that makes the `hidden` attribute authoritative.
  1309. * Statum toggles `stm-if`/`stm-else` branches and loop holders via
  1310. * `hidden`, whose user-agent rule loses specificity battles to ordinary
  1311. * author CSS (a rule like `li { display: flex }` let hidden loop holders
  1312. * leak as phantom rows). Idempotent: skipped when the stylesheet is
  1313. * already present.
  1314. */
  1315. function injectHiddenStyle() {
  1316. var id = 'statum-hidden-style';
  1317. if (document.getElementById(id)) return;
  1318. var head = document.head;
  1319. if (!head) return;
  1320. var style = document.createElement('style');
  1321. style.id = id;
  1322. style.textContent = '[hidden]{display:none !important}';
  1323. head.appendChild(style);
  1324. }
  1325. /**
  1326. * Scan the document for `pstm-*` attributes and `<pstm-*>` elements, which
  1327. * are intended for server-side pre-rendering and should never reach the
  1328. * browser. Emits a single `console.warn` summarizing them.
  1329. */
  1330. function warnServerSideMarkup() {
  1331. var found = [];
  1332. var els = document.querySelectorAll('*');
  1333. for (var i = 0; i < els.length; i++) {
  1334. var el = els[i];
  1335. var tag = el.tagName.toLowerCase();
  1336. if (tag.indexOf('pstm-') === 0) found.push('<' + tag + '>');
  1337. var attrs = el.attributes;
  1338. for (var j = 0; j < attrs.length; j++) {
  1339. var name = attrs[j].name;
  1340. if (name.indexOf('pstm-') === 0) found.push('<' + tag + '> ' + name);
  1341. }
  1342. }
  1343. if (found.length) {
  1344. console.warn('[statum] ' + found.length + ' server-side pstm-* attribute/element(s) ' +
  1345. 'found in the DOM; they should have been resolved during pre-rendering: ' +
  1346. found.slice(0, 10).join(', ') + (found.length > 10 ? ' …' : ''));
  1347. }
  1348. }
  1349. /**
  1350. * Initialize Statum: read URL overrides, run the session-cookie check,
  1351. * hydrate persisted state, open the cross-tab channel, fetch the entrypoint,
  1352. * and render. Safe to call multiple times.
  1353. * @returns {Promise<void>}
  1354. */
  1355. async function init() {
  1356. if (initialized) return;
  1357. initialized = true;
  1358. // Before the first render and the boot visibility toggling, so `hidden`
  1359. // wins over author CSS from the very first paint.
  1360. injectHiddenStyle();
  1361. var body = document.body;
  1362. if (body) {
  1363. if (body.hasAttribute('stm-entrypoint')) config.entrypointUrl = body.getAttribute('stm-entrypoint');
  1364. if (body.hasAttribute('stm-slots')) config.slotsUrl = body.getAttribute('stm-slots');
  1365. if (body.hasAttribute('stm-channel')) config.channelUrl = body.getAttribute('stm-channel');
  1366. if (body.hasAttribute('stm-worker')) config.workerUrl = body.getAttribute('stm-worker');
  1367. }
  1368. try { warnServerSideMarkup(); } catch (e) {}
  1369. try { initSession(); } catch (e) {}
  1370. try { hydrate(); } catch (e) {}
  1371. setupChannel();
  1372. setBootState(false);
  1373. renderAll(); // bind against any persisted/hydrated state immediately
  1374. try {
  1375. await loadEntrypoint();
  1376. } catch (err) {
  1377. console.error('[statum] entrypoint load failed', err);
  1378. } finally {
  1379. setBootState(true);
  1380. }
  1381. }
  1382. function autoInit() {
  1383. if (document.readyState === 'loading') {
  1384. document.addEventListener('DOMContentLoaded', init);
  1385. } else {
  1386. init();
  1387. }
  1388. }
  1389. // ---------------------------------------------------------------------------
  1390. // Public API
  1391. // ---------------------------------------------------------------------------
  1392. /** @namespace statum */
  1393. window.statum = {
  1394. /** Library version. */
  1395. version: '0.1.0',
  1396. /** Mutable endpoint configuration. */
  1397. config: config,
  1398. /** (Re)initialize the library. Usually runs automatically on load. */
  1399. init: init,
  1400. /** Read a type's `public` data. */
  1401. read: read,
  1402. /** Read a type's full snapshot object. */
  1403. getSnapshot: getSnapshot,
  1404. /** Read the frame wrapping a type's snapshot. */
  1405. getFrame: getFrame,
  1406. /** Build `{ typeName: public }` for every held type. */
  1407. state: state,
  1408. /** Clear one type (`clear("x")`) or all state (`clear()`). */
  1409. clear: clear,
  1410. /** Perform an action object or named action. */
  1411. act: act,
  1412. /** Attach a state-changed listener for a type. */
  1413. addStateListener: addStateListener,
  1414. /** Remove a previously-attached listener. */
  1415. removeStateListener: removeStateListener,
  1416. /**
  1417. * Register a handler for an `stm-*` attribute (module seam — see the
  1418. * registry in statum-core.js). `name` is an exact attribute name, or a
  1419. * prefix matcher when it ends with `.`; `opts.after` / `opts.before`
  1420. * order the handler against another registered attribute.
  1421. */
  1422. registerAttribute: registerAttribute,
  1423. /** Register a callback that runs before each render cycle (no arguments). */
  1424. beforeEvaluate: function (fn) { if (typeof fn === 'function') beforeHooks.push(fn); },
  1425. /** Register a callback that runs after each render cycle (no arguments). */
  1426. afterEvaluate: function (fn) { if (typeof fn === 'function') afterHooks.push(fn); },
  1427. /** The Statum error type (thrown by `act` and surfaced to handlers). */
  1428. Error: StatumError,
  1429. get onConfirmHandler() { return handlers.onConfirm; },
  1430. set onConfirmHandler(v) { handlers.onConfirm = typeof v === 'function' ? v : null; },
  1431. get onNotifyHandler() { return handlers.onNotify; },
  1432. set onNotifyHandler(v) { handlers.onNotify = typeof v === 'function' ? v : null; },
  1433. get onErrorHandler() { return handlers.onError; },
  1434. set onErrorHandler(v) { handlers.onError = typeof v === 'function' ? v : null; }
  1435. };
  1436. // The seam must be exposed before any other module loads. autoInit only
  1437. // ever runs on DOMContentLoaded (or immediately at load); both happen
  1438. // outside this script tag, so the later module tags always see the bridge.
  1439. window.statum._bridge = bridge;
  1440. autoInit();
  1441. })();