statum.js 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865
  1. /*!
  2. * Statum - client-side state library.
  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. * Distribution: a single IIFE that attaches `window.statum` (no dependencies,
  10. * no build step). Targets modern evergreen browsers (uses fetch,
  11. * BroadcastChannel, queueMicrotask, URLSearchParams, FormData).
  12. */
  13. (function () {
  14. 'use strict';
  15. /** Content-Type used by every Statum directive response. */
  16. var STATUM_CONTENT_TYPE = 'application/vnd.statum+json';
  17. /** Request/response header carrying one slot's reference (or base64 frame). */
  18. var SLOT_HEADER = 'X-Statum-Slot';
  19. /** Request header carrying an action's opaque `private` blob. */
  20. var PRIVATE_HEADER = 'X-Statum-Private';
  21. /** Session-cookie marker used to detect a fresh browser session. */
  22. var SESSION_COOKIE = '_statum_sdc';
  23. /** BroadcastChannel name used to sync session/device state across tabs. */
  24. var CHANNEL_NAME = 'statum';
  25. /** localStorage / sessionStorage key prefix for persisted frames. */
  26. var STORAGE_PREFIX = 'statum:';
  27. // ---------------------------------------------------------------------------
  28. // Configuration
  29. // ---------------------------------------------------------------------------
  30. /**
  31. * Endpoint URLs. These defaults may be overridden per-page with the
  32. * `stm-entrypoint` and `stm-slots` attributes on the `<body>` element.
  33. *
  34. * @type {{entrypointUrl: string, slotsUrl: string}}
  35. */
  36. var config = {
  37. entrypointUrl: '/_statum/entrypoint',
  38. slotsUrl: '/_statum/slots',
  39. channelUrl: '/_statum/channel',
  40. // The realtime worker is embedded in the library as a default resource
  41. // (served at /_statum/resource/statum-worker.js); override with stm-worker.
  42. workerUrl: '/_statum/resource/statum-worker.js'
  43. };
  44. // ---------------------------------------------------------------------------
  45. // State store
  46. // ---------------------------------------------------------------------------
  47. /**
  48. * In-memory store, keyed by slot type. Each value is `{frame, snapshot}`
  49. * where `snapshot` is the parsed `frame.content`. This map is the single
  50. * source of truth for rendering; persistent backends merely hydrate it.
  51. *
  52. * @type {Map<string, {frame: object, snapshot: object}>}
  53. */
  54. var store = new Map();
  55. /** Listeners, keyed by type name. @type {Map<string, Set<Function>>} */
  56. var listeners = new Map();
  57. /**
  58. * Idempotency tracking: slot key -> last-applied frame `signature`. Held in
  59. * memory only (per tab), so a frame already persisted by another tab still
  60. * re-draws a tab whose tracking lags. Entries are dropped on clear so a
  61. * replayed frame re-applies.
  62. * @type {Map<string, string>}
  63. */
  64. var signatures = new Map();
  65. /** Optional UI handlers (set via `statum.on*Handler`). */
  66. var handlers = { onConfirm: null, onNotify: null, onError: null };
  67. /** @type {BroadcastChannel|null} */
  68. var channel = null;
  69. /** Whether {@link init} has already run. */
  70. var initialized = false;
  71. /** Whether the entrypoint has been fetched (guards without pre-entrypoint
  72. * only evaluate after this). */
  73. var entrypointLoaded = false;
  74. /** Set when a guard has triggered a redirect, so further work is skipped. */
  75. var guardRedirected = false;
  76. // ---------------------------------------------------------------------------
  77. // Small utilities
  78. // ---------------------------------------------------------------------------
  79. /**
  80. * Parse an ISO 8601 timestamp to epoch millis, or `undefined`.
  81. * @param {string|undefined} s
  82. * @returns {number|undefined}
  83. */
  84. function parseTime(s) {
  85. if (!s) return undefined;
  86. var t = new Date(s).getTime();
  87. return isNaN(t) ? undefined : t;
  88. }
  89. /**
  90. * Base64-encode a UTF-8 string (safe for frames containing non-Latin1 data).
  91. * @param {string} str
  92. * @returns {string}
  93. */
  94. function b64encode(str) {
  95. var bytes = new TextEncoder().encode(str);
  96. var bin = '';
  97. var chunk = 0x8000;
  98. for (var i = 0; i < bytes.length; i += chunk) {
  99. bin += String.fromCharCode.apply(null, bytes.subarray(i, i + chunk));
  100. }
  101. return btoa(bin);
  102. }
  103. /** Read a cookie value, or `null` if absent. @param {string} name */
  104. function getCookie(name) {
  105. var escaped = name.replace(/([.$?*|{}()[\]\\/+^])/g, '\\$1');
  106. var match = document.cookie.match(new RegExp('(?:^|; )' + escaped + '=([^;]*)'));
  107. return match ? decodeURIComponent(match[1]) : null;
  108. }
  109. /** Set a session cookie (no expiry => cleared when the browser closes). */
  110. function setCookie(name, value) {
  111. document.cookie = name + '=' + encodeURIComponent(value) + '; path=/; SameSite=Lax';
  112. }
  113. // ---------------------------------------------------------------------------
  114. // Expression evaluation
  115. // ---------------------------------------------------------------------------
  116. /**
  117. * Compiled-expression cache. Expressions are evaluated as JavaScript against
  118. * a scope object (the page's HTML is trusted, per the model).
  119. * @type {Map<string, Function>}
  120. */
  121. var exprCache = new Map();
  122. /**
  123. * Compile (and cache) an expression string into a function of `scope`.
  124. * Uses `with` so that arbitrary type names and loop variables are resolved
  125. * as bare identifiers. Returns a function that yields `undefined` on any
  126. * runtime or compile error.
  127. * @param {string} expr
  128. * @returns {Function}
  129. */
  130. function compileExpr(expr) {
  131. var cached = exprCache.get(expr);
  132. if (cached !== undefined) return cached;
  133. var fn;
  134. try {
  135. // Function-constructor bodies are non-strict by default, so `with` is
  136. // permitted. The inner try/catch turns reference errors into `undefined`
  137. // so a missing path simply yields no value.
  138. fn = new Function('scope', 'with(scope){try{return (' + expr + ');}catch(e){return undefined;}}');
  139. } catch (e) {
  140. fn = function () { return undefined; };
  141. }
  142. exprCache.set(expr, fn);
  143. return fn;
  144. }
  145. /**
  146. * Evaluate an expression against a scope.
  147. * @param {string} expr
  148. * @param {object} [scope]
  149. * @returns {*} `undefined` if the expression is empty or fails.
  150. */
  151. function evalExpr(expr, scope) {
  152. if (expr == null || expr === '') return undefined;
  153. try {
  154. return compileExpr(expr)(scope || {});
  155. } catch (e) {
  156. return undefined;
  157. }
  158. }
  159. /**
  160. * Build a child scope that inherits the parent (so type bindings remain
  161. * visible) and adds one own loop variable.
  162. * @param {object} parent
  163. * @param {string} name
  164. * @param {*} value
  165. * @returns {object}
  166. */
  167. function childScope(parent, name, value) {
  168. var scope = Object.create(parent || null);
  169. scope[name] = value;
  170. return scope;
  171. }
  172. // ---------------------------------------------------------------------------
  173. // StatumError
  174. // ---------------------------------------------------------------------------
  175. /**
  176. * Error type thrown for HTTP failures and `error` directives.
  177. * @param {string} [message]
  178. * @param {string} [code]
  179. * @param {object} [data]
  180. */
  181. function StatumError(message, code, data) {
  182. this.name = 'StatumError';
  183. this.message = message || '';
  184. this.code = code || undefined;
  185. this.data = data || undefined;
  186. }
  187. StatumError.prototype = Object.create(Error.prototype);
  188. // ---------------------------------------------------------------------------
  189. // UI handlers (confirm / notify / error)
  190. // ---------------------------------------------------------------------------
  191. /**
  192. * Run the `notify` directive's default behaviour or the custom
  193. * `statum.onNotifyHandler`. The default surfaces the message via `alert()`.
  194. * @param {string} [kind] Application-defined category (freeform).
  195. * @param {string} [message]
  196. */
  197. function triggerNotify(kind, message) {
  198. var fn = handlers.onNotify;
  199. try {
  200. if (fn) fn(kind, message);
  201. else if (message != null) window.alert(message);
  202. } catch (e) { console.error('[statum] notify handler error', e); }
  203. }
  204. /**
  205. * Run the `stm-confirm` gate: the custom `statum.onConfirmHandler` if set,
  206. * otherwise `window.confirm`. Supports async handlers (custom modals).
  207. * @param {string} message
  208. * @param {HTMLElement} element
  209. * @returns {Promise<boolean>} truthy if the action should proceed.
  210. */
  211. async function triggerConfirm(message, element) {
  212. var fn = handlers.onConfirm;
  213. try {
  214. if (fn) return !!(await fn(message, element));
  215. return !!window.confirm(message);
  216. } catch (e) {
  217. console.error('[statum] confirm handler error', e);
  218. return false;
  219. }
  220. }
  221. /**
  222. * Run the custom `statum.onErrorHandler`, if set. Returns whether the default
  223. * behaviour (promise rejection + `stm-on-error` classes) should proceed: the
  224. * handler suppresses the default by returning (or resolving) `false`.
  225. * @param {StatumError} error
  226. * @param {HTMLElement|null} element
  227. * @returns {Promise<boolean>}
  228. */
  229. async function triggerError(error, element) {
  230. var fn = handlers.onError;
  231. if (!fn) return true;
  232. try {
  233. var suppress = await fn(error, element);
  234. return suppress !== false;
  235. } catch (e) {
  236. console.error('[statum] error handler error', e);
  237. return true;
  238. }
  239. }
  240. /**
  241. * Surface a failure: run `triggerError`, and if the default is not
  242. * suppressed, apply `stm-on-error` classes (when an origin element exists)
  243. * and re-throw so the originating promise rejects.
  244. * @param {StatumError} error
  245. * @param {HTMLElement|null} element
  246. */
  247. async function reportFailure(error, element) {
  248. if (await triggerError(error, element)) {
  249. if (element) applyErrorClasses(element, true);
  250. throw error;
  251. }
  252. }
  253. // ---------------------------------------------------------------------------
  254. // Persistence
  255. // ---------------------------------------------------------------------------
  256. /**
  257. * Pick the storage backend for a scope.
  258. * @param {string} scope
  259. * @returns {Storage|null} `null` for in-memory scopes.
  260. */
  261. function storageFor(scope) {
  262. if (scope === 'device' || scope === 'session') return localStorage;
  263. if (scope === 'flow') return sessionStorage;
  264. return null; // page / transient
  265. }
  266. /**
  267. * Persist a slot's frame to the backend matching its scope, removing any
  268. * stale copy from the other backend first (in case the scope changed).
  269. * @param {string} type
  270. * @param {{frame: object, snapshot: object}} entry
  271. */
  272. function persistEntry(type, entry) {
  273. var scope = entry.snapshot.slot && entry.snapshot.slot.scope;
  274. removePersisted(type);
  275. var storage = storageFor(scope);
  276. if (!storage) return;
  277. try {
  278. storage.setItem(STORAGE_PREFIX + type, JSON.stringify(entry.frame));
  279. } catch (e) {
  280. /* storage full or unavailable; remain in-memory only */
  281. }
  282. }
  283. /** Remove a persisted frame from both backends. @param {string} type */
  284. function removePersisted(type) {
  285. try { localStorage.removeItem(STORAGE_PREFIX + type); } catch (e) {}
  286. try { sessionStorage.removeItem(STORAGE_PREFIX + type); } catch (e) {}
  287. }
  288. /** Load every persisted frame from a backend into the in-memory store. */
  289. function loadFrom(storage) {
  290. for (var i = 0; i < storage.length; i++) {
  291. var key = storage.key(i);
  292. if (!key || key.indexOf(STORAGE_PREFIX) !== 0) continue;
  293. try {
  294. var frame = JSON.parse(storage.getItem(key));
  295. var snapshot = JSON.parse(frame.content);
  296. var type = snapshot.slot && snapshot.slot.type;
  297. if (type && !store.has(type)) store.set(type, { frame: frame, snapshot: snapshot });
  298. } catch (e) {
  299. /* corrupt entry: ignore */
  300. }
  301. }
  302. }
  303. /** Hydrate the store from localStorage and sessionStorage. */
  304. function hydrate() {
  305. try { loadFrom(localStorage); } catch (e) {}
  306. try { loadFrom(sessionStorage); } catch (e) {}
  307. }
  308. // ---------------------------------------------------------------------------
  309. // Session-cookie initialization
  310. // ---------------------------------------------------------------------------
  311. /**
  312. * Detect a fresh browser session using the `_statum_sdc` session cookie.
  313. * On a fresh session, clear all `session`-scoped persisted frames, then set
  314. * the marker. Session cookies are shared across tabs, so a tab opened
  315. * mid-session sees the marker and leaves session data intact.
  316. */
  317. function initSession() {
  318. if (getCookie(SESSION_COOKIE) !== null) return;
  319. clearSessionSlotsFromStorage();
  320. setCookie(SESSION_COOKIE, '1');
  321. }
  322. /** Remove all `session`-scoped frames from localStorage. */
  323. function clearSessionSlotsFromStorage() {
  324. var toRemove = [];
  325. for (var i = 0; i < localStorage.length; i++) {
  326. var key = localStorage.key(i);
  327. if (!key || key.indexOf(STORAGE_PREFIX) !== 0) continue;
  328. try {
  329. var frame = JSON.parse(localStorage.getItem(key));
  330. var snapshot = JSON.parse(frame.content);
  331. if (snapshot.slot && snapshot.slot.scope === 'session') toRemove.push(key);
  332. } catch (e) {}
  333. }
  334. for (var j = 0; j < toRemove.length; j++) localStorage.removeItem(toRemove[j]);
  335. }
  336. // ---------------------------------------------------------------------------
  337. // Listeners & cross-tab broadcast
  338. // ---------------------------------------------------------------------------
  339. /**
  340. * Fire all listeners for a type. (Renamed from `notify` to avoid confusion
  341. * with the `notify` directive.)
  342. * @param {string} type
  343. * @param {object|null} frame
  344. * @param {object|null} snapshot
  345. */
  346. function fireListeners(type, frame, snapshot) {
  347. var set = listeners.get(type);
  348. if (!set) return;
  349. var event = { type: type, frame: frame, snapshot: snapshot };
  350. set.forEach(function (cb) {
  351. try { cb(event); } catch (e) { console.error('[statum] listener error', e); }
  352. });
  353. }
  354. /**
  355. * Broadcast a state change to other tabs. Only `session`/`device` scopes are
  356. * shared (flow/page/transient are per-tab).
  357. * @param {object} message
  358. * @param {string} [scope]
  359. */
  360. function broadcast(message, scope) {
  361. if (!channel) return;
  362. if (scope !== 'session' && scope !== 'device') return;
  363. try { channel.postMessage(message); } catch (e) {}
  364. }
  365. /**
  366. * Broadcast a message to other tabs regardless of slot scope. Used to relay
  367. * realtime (live) events so they reach every tab, not just session/device
  368. * ones.
  369. */
  370. function broadcastAlways(message) {
  371. if (!channel) return;
  372. try { channel.postMessage(message); } catch (e) {}
  373. }
  374. /** Open the BroadcastChannel and wire inbound messages. */
  375. function setupChannel() {
  376. if (typeof BroadcastChannel === 'undefined') return;
  377. try {
  378. channel = new BroadcastChannel(CHANNEL_NAME);
  379. } catch (e) {
  380. channel = null;
  381. return;
  382. }
  383. channel.onmessage = function (ev) {
  384. var msg = ev.data;
  385. if (!msg) return;
  386. if (msg.kind === 'set' && msg.frame) {
  387. try {
  388. var snapshot = JSON.parse(msg.frame.content);
  389. var type = snapshot.slot && snapshot.slot.type;
  390. if (type && commitSet(msg.frame, snapshot, type, false)) renderAll();
  391. } catch (e) { /* ignore malformed */ }
  392. } else if (msg.kind === 'clear') {
  393. var t = msg.type;
  394. if (!t && msg.key != null) {
  395. store.forEach(function (entry, type) {
  396. if (entry.snapshot.slot && entry.snapshot.slot.key === msg.key) t = type;
  397. });
  398. }
  399. if (t) clearType(t, { broadcast: false });
  400. else if (msg.key != null) signatures.delete(msg.key);
  401. renderAll();
  402. }
  403. };
  404. }
  405. // ---------------------------------------------------------------------------
  406. // State mutation
  407. // ---------------------------------------------------------------------------
  408. /**
  409. * Remove a type from the store, un-persist it, drop its idempotency entry,
  410. * fire listeners, and (optionally) broadcast the clear to other tabs.
  411. * @param {string} type
  412. * @param {{broadcast?: boolean}} [opts]
  413. */
  414. function clearType(type, opts) {
  415. var entry = store.get(type);
  416. if (!entry) return;
  417. var scope = entry.snapshot.slot && entry.snapshot.slot.scope;
  418. var key = entry.snapshot.slot && entry.snapshot.slot.key;
  419. store.delete(type);
  420. removePersisted(type);
  421. if (key) signatures.delete(key);
  422. fireListeners(type, null, null);
  423. if (opts && opts.broadcast) broadcast({ kind: 'clear', key: key, type: type }, scope);
  424. }
  425. /**
  426. * Resolve a slot key to its type and clear it. Used by the `clear` directive
  427. * (keyed) and by live `clear` events.
  428. * @param {string} key
  429. * @param {boolean} [broadcast]
  430. */
  431. function clearByKey(key, broadcast) {
  432. var typeToRemove = null;
  433. store.forEach(function (entry, type) {
  434. if (entry.snapshot.slot && entry.snapshot.slot.key === key) typeToRemove = type;
  435. });
  436. if (typeToRemove) clearType(typeToRemove, { broadcast: !!broadcast });
  437. else if (key) signatures.delete(key);
  438. }
  439. /**
  440. * Resolve a frame signature to its slot type and clear it. Used by the
  441. * `invalidate` directive, which references a signature (not a key) because the
  442. * server reports a bad signature without trusting the frame's content.
  443. * @param {string} signature
  444. * @param {boolean} [broadcast]
  445. */
  446. function clearBySignature(signature, broadcast) {
  447. var typeToRemove = null;
  448. store.forEach(function (entry, type) {
  449. if (entry.frame && entry.frame.signature === signature) typeToRemove = type;
  450. });
  451. if (typeToRemove) clearType(typeToRemove, { broadcast: !!broadcast });
  452. else if (signature) signatures.delete(signature);
  453. }
  454. /**
  455. * Commit a `set` to the in-memory store, persist it, and fire listeners.
  456. * Idempotent: if the frame's `signature` matches the last-applied signature
  457. * for this slot (tracked in {@link signatures}), nothing happens and `false`
  458. * is returned. When `doBroadcast` is true the set is forwarded to other tabs
  459. * via the scope-gated broadcast (session/device only).
  460. * @param {object} frame
  461. * @param {object} snapshot
  462. * @param {string} type
  463. * @param {boolean} doBroadcast
  464. * @returns {boolean} `true` if state changed.
  465. */
  466. function commitSet(frame, snapshot, type, doBroadcast) {
  467. var key = snapshot.slot && snapshot.slot.key;
  468. var sig = frame.signature;
  469. if (key && sig !== undefined && signatures.get(key) === sig) return false;
  470. var entry = { frame: frame, snapshot: snapshot };
  471. store.set(type, entry);
  472. persistEntry(type, entry);
  473. fireListeners(type, frame, snapshot);
  474. if (key && sig !== undefined) signatures.set(key, sig);
  475. if (doBroadcast) {
  476. var scope = snapshot.slot && snapshot.slot.scope;
  477. broadcast({ kind: 'set', frame: frame }, scope);
  478. }
  479. return true;
  480. }
  481. /**
  482. * Apply a `set` directive: store/refresh a slot's snapshot (idempotently),
  483. * broadcasting to other tabs.
  484. * @param {object} directive `{ snapshot_frame }`
  485. */
  486. function applySet(directive) {
  487. var frame = directive.snapshot_frame;
  488. if (!frame || !frame.content) return;
  489. var snapshot;
  490. try { snapshot = JSON.parse(frame.content); } catch (e) { return; }
  491. var type = snapshot.slot && snapshot.slot.type;
  492. if (!type) return;
  493. commitSet(frame, snapshot, type, true);
  494. }
  495. /**
  496. * Apply a `clear` directive. The directive carries a slot key, so the type
  497. * holding that key is resolved and removed.
  498. * @param {object} directive `{ key }`
  499. */
  500. function applyClear(directive) {
  501. if (directive.key == null) return;
  502. clearByKey(directive.key, true);
  503. }
  504. /**
  505. * Apply a live `set` event received over the realtime channel. The frame is
  506. * committed (idempotently) and, when new, broadcast to sibling tabs via the
  507. * scope-agnostic {@link broadcastAlways} so every tab sees it regardless of
  508. * which (or how many) tabs hold a subscription.
  509. * @param {object} frame
  510. */
  511. function applyRemoteSet(frame) {
  512. try {
  513. var snapshot = JSON.parse(frame.content);
  514. var type = snapshot.slot && snapshot.slot.type;
  515. if (!type) return;
  516. if (commitSet(frame, snapshot, type, false)) {
  517. broadcastAlways({ kind: 'set', frame: frame });
  518. renderAll();
  519. }
  520. } catch (e) { /* malformed frame */ }
  521. }
  522. /** Apply a live `clear` event received over the realtime channel. */
  523. function applyRemoteClear(key) {
  524. if (key == null) return;
  525. signatures.delete(key);
  526. clearByKey(key, false);
  527. broadcastAlways({ kind: 'clear', key: key });
  528. renderAll();
  529. }
  530. // ---------------------------------------------------------------------------
  531. // Snapshot freshness & request headers
  532. // ---------------------------------------------------------------------------
  533. /**
  534. * Categorize a held snapshot relative to the current time.
  535. * @returns {'silent'|'always'|'invalid'|'stale'|'fresh'}
  536. * - `silent`: unidirectional (`transmit_after` undefined) - never sent.
  537. * - `always`: `transmit_after === as_at` - send the base64 frame each time.
  538. * - `invalid`: past `invalid_after` - drop and refetch.
  539. * - `stale`: past `transmit_after` but not yet invalid - pre-flight first.
  540. * - `fresh`: still cached server-side - send the `as_at` reference.
  541. */
  542. function entryCategory(entry) {
  543. var snap = entry.snapshot;
  544. var transmit = snap.transmit_after;
  545. if (transmit === undefined || transmit === null) return 'silent';
  546. if (transmit === snap.as_at) return 'always';
  547. var now = Date.now();
  548. var invalidAt = parseTime(snap.invalid_after);
  549. var transmitAt = parseTime(transmit);
  550. if (invalidAt !== undefined && now >= invalidAt) return 'invalid';
  551. if (transmitAt !== undefined && now >= transmitAt) return 'stale';
  552. return 'fresh';
  553. }
  554. /**
  555. * Drop locally-invalid snapshots and pre-flight any stale ones. Pre-flighting
  556. * posts the stale frames to the slot endpoint and applies the returned `set`
  557. * directives, refreshing their `as_at` values before the real request runs.
  558. *
  559. * Single-flight: concurrent callers share one in-flight preparation.
  560. * @returns {Promise<void>}
  561. */
  562. var preparePromise = null;
  563. function prepareSlots() {
  564. if (preparePromise) return preparePromise;
  565. preparePromise = doPrepareSlots().then(function () {
  566. preparePromise = null;
  567. }, function () {
  568. preparePromise = null;
  569. });
  570. return preparePromise;
  571. }
  572. async function doPrepareSlots() {
  573. var stale = [];
  574. store.forEach(function (entry, type) {
  575. var cat = entryCategory(entry);
  576. if (cat === 'invalid') {
  577. clearType(type, { broadcast: false });
  578. } else if (cat === 'stale') {
  579. stale.push(entry.frame);
  580. }
  581. });
  582. if (stale.length) {
  583. var directives = await postSlots(stale);
  584. var pfResult = applyDirectives(directives, { originElement: null });
  585. executeTerminal(pfResult);
  586. }
  587. }
  588. /**
  589. * Build the `X-Statum-Slot` header values for every held slot, using the
  590. * freshness rules. Assumes {@link prepareSlots} has just run.
  591. * @returns {string[]}
  592. */
  593. function buildSlotHeaders() {
  594. var headers = [];
  595. store.forEach(function (entry) {
  596. var snap = entry.snapshot;
  597. var cat = entryCategory(entry);
  598. if (cat === 'silent' || cat === 'invalid') return;
  599. if (cat === 'always') {
  600. headers.push(b64encode(JSON.stringify(entry.frame)));
  601. } else {
  602. headers.push('key=' + snap.slot.key + '; as_at=' + snap.as_at);
  603. }
  604. });
  605. return headers;
  606. }
  607. /**
  608. * Collect the current frames held for the given slot keys, in the order the
  609. * keys are first supplied. Used by the `transmit` directive (which forces a
  610. * slot's frame to be posted as if its `transmit_after` had elapsed). Keys the
  611. * client does not currently hold are skipped.
  612. * @param {string[]} keys
  613. * @returns {object[]}
  614. */
  615. function collectFramesForKeys(keys) {
  616. var keySet = Object.create(null);
  617. for (var i = 0; i < keys.length; i++) keySet[keys[i]] = true;
  618. var frames = [];
  619. store.forEach(function (entry) {
  620. var key = entry.snapshot.slot && entry.snapshot.slot.key;
  621. if (key && keySet[key]) {
  622. frames.push(entry.frame);
  623. delete keySet[key];
  624. }
  625. });
  626. return frames;
  627. }
  628. // ---------------------------------------------------------------------------
  629. // HTTP helpers
  630. // ---------------------------------------------------------------------------
  631. /** True if a response is a Statum directive response. */
  632. function isStatum(res) {
  633. return (res.headers.get('Content-Type') || '').indexOf(STATUM_CONTENT_TYPE) !== -1;
  634. }
  635. /**
  636. * POST an array of frames to the slot endpoint (the pre-flight target) and
  637. * return its directive array. This request intentionally carries no slot
  638. * headers (it is itself the refresh).
  639. * @param {object[]} frames
  640. * @returns {Promise<object[]>}
  641. */
  642. async function postSlots(frames) {
  643. var headers = new Headers();
  644. headers.set('Accept', STATUM_CONTENT_TYPE);
  645. headers.set('Content-Type', 'application/json');
  646. var res = await fetch(config.slotsUrl, {
  647. method: 'POST',
  648. headers: headers,
  649. body: JSON.stringify(frames),
  650. credentials: 'same-origin'
  651. });
  652. if (!isStatum(res)) return [];
  653. try { return await res.json(); } catch (e) { return []; }
  654. }
  655. /**
  656. * Apply the non-terminal directives from a response (set/clear/subscribe/
  657. * unsubscribe/notify/transmit-collection), then `render`.
  658. *
  659. * Terminal directives (`navigate`, `post`), error directives, and any
  660. * transmit/retry intent are collected on the returned result rather than
  661. * executed here: {@link handleResponse} performs the asynchronous
  662. * transmission (and optional retry) and then runs terminal navigation, so
  663. * that a `transmit` with `retry` can re-issue the request before the page is
  664. * navigated away.
  665. * @param {object[]} directives
  666. * @param {{originElement?: HTMLElement}} [ctx]
  667. * @returns {{errors: StatumError[], transmitKeys: string[], retry: boolean, navigate: object|null, post: object|null}}
  668. */
  669. function applyDirectives(directives, ctx) {
  670. var result = { errors: [], transmitKeys: [], retry: false, navigate: null, post: null, formSubmits: [], formResets: [] };
  671. var list = Array.isArray(directives) ? directives : [];
  672. for (var i = 0; i < list.length; i++) {
  673. var d = list[i];
  674. if (!d || typeof d !== 'object') continue;
  675. switch (d.type) {
  676. case 'set': applySet(d); break;
  677. case 'clear': applyClear(d); break;
  678. case 'invalidate':
  679. if (d.signature != null) {
  680. console.warn('[statum] server could not verify slot frame ' + d.signature + '; clearing it');
  681. clearBySignature(d.signature, true);
  682. }
  683. break;
  684. case 'subscribe': channelSubscribe(d.key); break;
  685. case 'unsubscribe': channelUnsubscribe(d.key); break;
  686. case 'notify': triggerNotify(d.kind, d.message); break;
  687. case 'transmit':
  688. if (d.key != null) {
  689. if (result.transmitKeys.indexOf(d.key) === -1) result.transmitKeys.push(d.key);
  690. if (d.retry) result.retry = true;
  691. }
  692. break;
  693. case 'error':
  694. {
  695. var err = new StatumError(d.message, d.code, d.data);
  696. var detail = d.code ? (d.message + ' [' + d.code + ']') : d.message;
  697. console.error('[statum] error directive: ' + (detail || '(no message)'));
  698. result.errors.push(err);
  699. }
  700. break;
  701. case 'navigate': result.navigate = d; break;
  702. case 'post': result.post = d; break;
  703. case 'form-submit': result.formSubmits.push(d); break;
  704. case 'form-reset': result.formResets.push(d); break;
  705. }
  706. }
  707. renderAll();
  708. return result;
  709. }
  710. /** Execute the terminal directives collected by {@link applyDirectives}. */
  711. function executeTerminal(result) {
  712. result.formResets.forEach(doFormReset);
  713. result.formSubmits.forEach(doFormSubmit);
  714. if (result.navigate) doNavigate(result.navigate);
  715. if (result.post) doPost(result.post);
  716. }
  717. /** Execute a `form-submit` directive: optionally override action/method, then submit. */
  718. function doFormSubmit(d) {
  719. var form = document.getElementById(d.form);
  720. if (form) {
  721. if (d.action) form.setAttribute('action', d.action);
  722. if (d.method) form.setAttribute('method', d.method);
  723. form.submit();
  724. }
  725. }
  726. /** Execute a `form-reset` directive. */
  727. function doFormReset(d) {
  728. var form = document.getElementById(d.form);
  729. if (form) form.reset();
  730. }
  731. /** Execute a `navigate` directive as a full page load. */
  732. function doNavigate(d) {
  733. if (d.uri) window.location.href = d.uri;
  734. }
  735. /** Execute a `post` directive as a real (navigating) form POST. */
  736. function doPost(d) {
  737. if (!d.uri) return;
  738. var form = document.createElement('form');
  739. form.method = 'POST';
  740. form.action = d.uri;
  741. form.style.display = 'none';
  742. var data = d.data || {};
  743. Object.keys(data).forEach(function (name) {
  744. var input = document.createElement('input');
  745. input.type = 'hidden';
  746. input.name = name;
  747. input.value = data[name] == null ? '' : String(data[name]);
  748. form.appendChild(input);
  749. });
  750. document.body.appendChild(form);
  751. form.submit();
  752. }
  753. /**
  754. * Handle a fetch response: if it is a Statum response, apply its directives;
  755. * otherwise throw on HTTP errors and no-op on other successful responses.
  756. *
  757. * Directive ordering: non-terminal directives are applied and the page
  758. * rendered; then any `transmit` directives force their slot frames to be
  759. * posted (applying the directives the slot endpoint returns); then, if a
  760. * transmit requested a retry, the originating request (`ctx.retry`) is
  761. * re-issued and this response's terminal directives and errors are skipped.
  762. * Otherwise terminal navigation runs, then error directives are surfaced.
  763. * @param {Response} res
  764. * @param {{originElement?: HTMLElement, retry?: Function}} [ctx]
  765. */
  766. async function handleResponse(res, ctx) {
  767. var el = ctx && ctx.originElement;
  768. if (!isStatum(res)) {
  769. if (!res.ok) await reportFailure(new StatumError('HTTP ' + res.status), el);
  770. return;
  771. }
  772. var directives;
  773. try { directives = await res.json(); } catch (e) { directives = []; }
  774. var result = applyDirectives(directives, ctx);
  775. if (result.transmitKeys && result.transmitKeys.length) {
  776. var frames = collectFramesForKeys(result.transmitKeys);
  777. if (frames.length) {
  778. var txDirectives = await postSlots(frames);
  779. applyDirectives(txDirectives, { originElement: el });
  780. }
  781. }
  782. if (result.retry && ctx && typeof ctx.retry === 'function') {
  783. await ctx.retry();
  784. return;
  785. }
  786. executeTerminal(result);
  787. var errors = result.errors || [];
  788. for (var i = 0; i < errors.length; i++) {
  789. await reportFailure(errors[i], el);
  790. }
  791. }
  792. // ---------------------------------------------------------------------------
  793. // Entrypoint & action requests
  794. // ---------------------------------------------------------------------------
  795. /**
  796. * Fetch the entrypoint for the current URL, applying its directives. Carries
  797. * slot headers (and pre-flights) like any other request. The request is
  798. * wrapped in an `attempt` closure passed as the response `retry` callback, so
  799. * a `transmit` directive with `retry` can re-issue it after transmission.
  800. * @returns {Promise<void>}
  801. */
  802. function loadEntrypoint() {
  803. if (guardRedirected) return Promise.resolve();
  804. // From this point on guards are "post-entrypoint" (all of them evaluate).
  805. entrypointLoaded = true;
  806. var attempt = async function () {
  807. await prepareSlots();
  808. var headers = new Headers();
  809. headers.set('Accept', STATUM_CONTENT_TYPE);
  810. buildSlotHeaders().forEach(function (v) { headers.append(SLOT_HEADER, v); });
  811. var url = config.entrypointUrl + '?uri=' + encodeURIComponent(window.location.href);
  812. var res = await fetch(url, { headers: headers, credentials: 'same-origin' });
  813. await handleResponse(res, { originElement: null, retry: attempt });
  814. };
  815. return attempt();
  816. }
  817. /**
  818. * Perform an action request.
  819. *
  820. * The request is wrapped in an `attempt` closure passed as the response
  821. * `retry` callback, so a `transmit` directive with `retry` can re-issue the
  822. * same action after the transmission (rebuilding headers from current state).
  823. *
  824. * @param {object} action `{ uri, method, private }`
  825. * @param {object} [data] Key/value parameters. Encoded as query string for
  826. * GET/HEAD, otherwise as `application/x-www-form-urlencoded`.
  827. * @param {HTMLElement} [originElement] Element that triggered the action, so
  828. * that `stm-on-error` classes can be applied on an `error` directive.
  829. * @returns {Promise<void>} Resolves once the request completes and its
  830. * directives have run; rejects on HTTP failure or an `error` directive.
  831. */
  832. function performAction(action, data, originElement) {
  833. var attempt = async function () {
  834. await prepareSlots();
  835. var headers = new Headers();
  836. headers.set('Accept', STATUM_CONTENT_TYPE);
  837. buildSlotHeaders().forEach(function (v) { headers.append(SLOT_HEADER, v); });
  838. if (action.private) headers.set(PRIVATE_HEADER, action.private);
  839. var method = (action.method || 'GET').toUpperCase();
  840. var params = data || {};
  841. var init = { method: method, headers: headers, credentials: 'same-origin' };
  842. var url = action.uri;
  843. if (method === 'GET' || method === 'HEAD') {
  844. var qs = new URLSearchParams(params).toString();
  845. if (qs) url += (url.indexOf('?') !== -1 ? '&' : '?') + qs;
  846. } else {
  847. init.body = new URLSearchParams(params).toString();
  848. headers.set('Content-Type', 'application/x-www-form-urlencoded');
  849. }
  850. var res;
  851. try {
  852. res = await fetch(url, init);
  853. } catch (networkErr) {
  854. await reportFailure(new StatumError('Network error'), originElement);
  855. return;
  856. }
  857. await handleResponse(res, { originElement: originElement, retry: attempt });
  858. };
  859. return attempt();
  860. }
  861. // ---------------------------------------------------------------------------
  862. // Realtime channel (subscribe/unsubscribe directives)
  863. // ---------------------------------------------------------------------------
  864. /**
  865. * Per-tab fallback engine, used when `SharedWorker` is unavailable. Owns an
  866. * `EventSource`, reads the channel id from the first `event: channel`,
  867. * reference-counts slot keys within this tab, PATCHes subscription changes,
  868. * applies incoming set/clear events (broadcasting them to siblings), and
  869. * closes the stream once it has no subscriptions.
  870. */
  871. function createFallbackEngine() {
  872. var es = null;
  873. var channelId = null;
  874. var refs = new Map(); // slotKey -> count
  875. var pending = { subscribe: [], unsubscribe: [] };
  876. var patchScheduled = false;
  877. function openStream() {
  878. if (es) return;
  879. try { es = new EventSource(config.channelUrl); }
  880. catch (e) { es = null; return; }
  881. es.addEventListener('channel', function (ev) { channelId = ev.data; flushPatch(); });
  882. es.addEventListener('set', function (ev) {
  883. try { applyRemoteSet(JSON.parse(ev.data)); } catch (e) {}
  884. });
  885. es.addEventListener('clear', function (ev) { applyRemoteClear(ev.data); });
  886. es.onerror = function () { /* EventSource auto-reconnects */ };
  887. }
  888. function closeStream() {
  889. if (es) { try { es.close(); } catch (e) {} es = null; }
  890. channelId = null;
  891. }
  892. function schedulePatch() {
  893. if (patchScheduled) return;
  894. patchScheduled = true;
  895. Promise.resolve().then(function () { patchScheduled = false; flushPatch(); });
  896. }
  897. function flushPatch() {
  898. if (!channelId) return;
  899. var sub = pending.subscribe, uns = pending.unsubscribe;
  900. if (!sub.length && !uns.length) return;
  901. pending = { subscribe: [], unsubscribe: [] };
  902. var body = {};
  903. if (sub.length) body.subscribe = sub;
  904. if (uns.length) body.unsubscribe = uns;
  905. try {
  906. fetch(config.channelUrl + '/' + encodeURIComponent(channelId), {
  907. method: 'PATCH',
  908. headers: { 'Content-Type': 'application/json' },
  909. credentials: 'same-origin',
  910. body: JSON.stringify(body)
  911. }).catch(function () {});
  912. } catch (e) {}
  913. }
  914. return {
  915. subscribe: function (key) {
  916. var c = refs.get(key) || 0;
  917. refs.set(key, c + 1);
  918. if (c === 0) { openStream(); pending.subscribe.push(key); schedulePatch(); }
  919. },
  920. unsubscribe: function (key) {
  921. var c = refs.get(key) || 0;
  922. if (c <= 0) return;
  923. if (c - 1 <= 0) {
  924. refs.delete(key);
  925. pending.unsubscribe.push(key);
  926. schedulePatch();
  927. if (refs.size === 0) setTimeout(function () { if (refs.size === 0) closeStream(); }, 0);
  928. } else {
  929. refs.set(key, c - 1);
  930. }
  931. }
  932. };
  933. }
  934. /**
  935. * Channel manager. Prefers a `SharedWorker` (which owns the single SSE
  936. * connection, reference-counts subscriptions across tabs, and relays events
  937. * through the cross-tab `BroadcastChannel`); falls back to a per-tab
  938. * `EventSource` engine when `SharedWorker` is unavailable or the worker
  939. * script fails to load. Tracks the true per-slot subscription count so it can
  940. * replay active subscriptions into the fallback on a mid-session switch.
  941. */
  942. function createChannelManager() {
  943. var port = null;
  944. var workerObj = null;
  945. var fallback = null;
  946. var mode = null; // 'worker' | 'fallback' | null
  947. var counts = new Map(); // slotKey -> count (true subscription state)
  948. function switchToFallback() {
  949. if (mode === 'fallback') return;
  950. mode = 'fallback';
  951. port = null;
  952. workerObj = null;
  953. fallback = createFallbackEngine();
  954. counts.forEach(function (c, key) {
  955. for (var i = 0; i < c; i++) fallback.subscribe(key);
  956. });
  957. }
  958. function ensure() {
  959. if (mode !== null) return;
  960. if (typeof SharedWorker !== 'undefined') {
  961. try {
  962. workerObj = new SharedWorker(config.workerUrl);
  963. port = workerObj.port;
  964. port.start();
  965. port.postMessage({ op: 'init', url: config.channelUrl });
  966. // The worker delivers events via the BroadcastChannel, so nothing is
  967. // required on this port beyond command messages.
  968. port.onmessage = function () {};
  969. workerObj.onerror = function () {
  970. console.warn('[statum] realtime worker failed; falling back to per-tab channel');
  971. switchToFallback();
  972. };
  973. window.addEventListener('pagehide', function () {
  974. if (mode === 'worker' && port) {
  975. try { port.postMessage({ op: 'disconnect' }); } catch (e) {}
  976. }
  977. });
  978. mode = 'worker';
  979. return;
  980. } catch (e) { workerObj = null; port = null; }
  981. }
  982. switchToFallback();
  983. }
  984. return {
  985. subscribe: function (key) {
  986. if (key == null) return;
  987. ensure();
  988. counts.set(key, (counts.get(key) || 0) + 1);
  989. if (mode === 'worker') { try { port.postMessage({ op: 'subscribe', key: key }); } catch (e) {} }
  990. else fallback.subscribe(key);
  991. },
  992. unsubscribe: function (key) {
  993. if (key == null) return;
  994. var c = (counts.get(key) || 0) - 1;
  995. if (c <= 0) counts.delete(key); else counts.set(key, c);
  996. ensure();
  997. if (mode === 'worker') { try { port.postMessage({ op: 'unsubscribe', key: key }); } catch (e) {} }
  998. else fallback.unsubscribe(key);
  999. }
  1000. };
  1001. }
  1002. var channelManager = createChannelManager();
  1003. function channelSubscribe(key) { channelManager.subscribe(key); }
  1004. function channelUnsubscribe(key) { channelManager.unsubscribe(key); }
  1005. // ---------------------------------------------------------------------------
  1006. // Rendering: loops, conditionals, bindings
  1007. // ---------------------------------------------------------------------------
  1008. /** Templates captured from loop holders. @type {WeakMap<Element, Element>} */
  1009. var templates = new WeakMap();
  1010. /** Instance nodes managed by a loop holder. @type {WeakMap<Element, Element[]>} */
  1011. var instancesByHolder = new WeakMap();
  1012. /** Loop instance nodes; skipped by the render walk (owned by their holder). */
  1013. var instanceNodes = new WeakSet();
  1014. /** Elements whose `stm-action` has been wired, to avoid double-binding. */
  1015. var wired = new WeakSet();
  1016. /**
  1017. * Find a `stm-for-{name}-in` attribute on an element.
  1018. * @returns {{varName: string, expr: string}|null}
  1019. */
  1020. function getStmFor(el) {
  1021. var attrs = el.attributes;
  1022. for (var i = 0; i < attrs.length; i++) {
  1023. var match = attrs[i].name.match(/^stm-for-(.+)-in$/);
  1024. if (match) return { varName: match[1], expr: attrs[i].value };
  1025. }
  1026. return null;
  1027. }
  1028. /** Remove any `stm-for-*` and `stm-key` attributes from an element. */
  1029. function stripLoopAttrs(el) {
  1030. var toRemove = [];
  1031. for (var i = 0; i < el.attributes.length; i++) {
  1032. var name = el.attributes[i].name;
  1033. if (/^stm-for-(.+)-in$/.test(name) || name === 'stm-key') toRemove.push(name);
  1034. }
  1035. toRemove.forEach(function (n) { el.removeAttribute(n); });
  1036. }
  1037. /**
  1038. * Evaluate an `stm-if` / `stm-else-if` / `stm-else` chain beginning at `el`,
  1039. * showing the matching branch and hiding the rest.
  1040. *
  1041. * Branches are toggled with the `hidden` attribute rather than detached, so
  1042. * every branch stays in the DOM and is re-evaluated on each render. (Detaching
  1043. * the `stm-if` element would remove it from the render walk, leaving an
  1044. * already-attached `stm-else` branch skipped and never refreshed.)
  1045. * @returns {Element|null} The active branch element (or `null`).
  1046. */
  1047. function handleIfChain(el, scope) {
  1048. var branches = [{ el: el, expr: el.getAttribute('stm-if') }];
  1049. var cur = el.nextElementSibling;
  1050. while (cur) {
  1051. if (cur.hasAttribute('stm-else-if')) {
  1052. branches.push({ el: cur, expr: cur.getAttribute('stm-else-if') });
  1053. cur = cur.nextElementSibling;
  1054. } else if (cur.hasAttribute('stm-else')) {
  1055. branches.push({ el: cur, expr: null });
  1056. break;
  1057. } else {
  1058. break;
  1059. }
  1060. }
  1061. var activeEl = null;
  1062. for (var i = 0; i < branches.length; i++) {
  1063. var b = branches[i];
  1064. if (b.expr === null || !!evalExpr(b.expr, scope)) { activeEl = b.el; break; }
  1065. }
  1066. branches.forEach(function (b) {
  1067. if (b.el === activeEl) b.el.removeAttribute('hidden');
  1068. else b.el.setAttribute('hidden', '');
  1069. });
  1070. return activeEl;
  1071. }
  1072. /** Toggle `stm-class.{name}` classes from their predicate expressions. */
  1073. function handleClass(el, scope) {
  1074. var attrs = el.attributes;
  1075. for (var i = 0; i < attrs.length; i++) {
  1076. var attr = attrs[i];
  1077. if (attr.name.indexOf('stm-class.') === 0) {
  1078. var cls = attr.name.slice('stm-class.'.length);
  1079. if (cls && !!evalExpr(attr.value, scope)) el.classList.add(cls);
  1080. else el.classList.remove(cls);
  1081. }
  1082. }
  1083. }
  1084. /**
  1085. * Bind `stm-attribute.{name}`: a boolean result toggles the attribute, any
  1086. * other defined value sets it, and `undefined` removes it.
  1087. *
  1088. * For booleans, prefer the element's IDL property when one exists (e.g.
  1089. * `checked`, `disabled`, `hidden`) — setting the content attribute is
  1090. * unreliable for these once the control is "dirty".
  1091. */
  1092. function handleAttribute(el, scope) {
  1093. var attrs = el.attributes;
  1094. for (var i = 0; i < attrs.length; i++) {
  1095. var attr = attrs[i];
  1096. if (attr.name.indexOf('stm-attribute.') === 0) {
  1097. var name = attr.name.slice('stm-attribute.'.length);
  1098. if (!name) continue;
  1099. var value = evalExpr(attr.value, scope);
  1100. if (value === undefined) {
  1101. el.removeAttribute(name);
  1102. } else if (typeof value === 'boolean') {
  1103. if (name in el && typeof el[name] === 'boolean') el[name] = value;
  1104. else if (value) el.setAttribute(name, '');
  1105. else el.removeAttribute(name);
  1106. } else {
  1107. el.setAttribute(name, value === null ? '' : String(value));
  1108. }
  1109. }
  1110. }
  1111. }
  1112. /**
  1113. * Apply `stm-disabled`: when the predicate is truthy, disable the element and
  1114. * its descendant form controls; otherwise enable them.
  1115. */
  1116. function handleDisabled(el, scope) {
  1117. if (!el.hasAttribute('stm-disabled')) return;
  1118. setDisabledCascade(el, !!evalExpr(el.getAttribute('stm-disabled'), scope));
  1119. }
  1120. /** Set the `disabled` attribute on an element and its descendant controls. */
  1121. function setDisabledCascade(el, on) {
  1122. var nodes = [el].concat(Array.prototype.slice.call(
  1123. el.querySelectorAll('button,input,select,textarea,fieldset')));
  1124. nodes.forEach(function (n) {
  1125. if (on) n.setAttribute('disabled', ''); else n.removeAttribute('disabled');
  1126. });
  1127. }
  1128. /**
  1129. * Escape-first minimal markdown renderer. All HTML in the source is escaped
  1130. * before formatting is applied, so untrusted input cannot inject markup.
  1131. * Supports headings, bold, italic, inline code, fenced code blocks, links,
  1132. * lists, blockquotes, horizontal rules and paragraphs.
  1133. */
  1134. function renderMarkdown(raw) {
  1135. var escaped = raw
  1136. .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
  1137. .replace(/"/g, '&quot;').replace(/'/g, '&#39;');
  1138. var lines = escaped.split('\n');
  1139. var out = [];
  1140. var inList = false, inCode = false;
  1141. function closeList() { if (inList) { out.push(inList === 'ul' ? '</ul>' : '</ol>'); inList = false; } }
  1142. for (var i = 0; i < lines.length; i++) {
  1143. var line = lines[i];
  1144. if (/^```/.test(line)) {
  1145. if (inCode) { out.push('</code></pre>'); inCode = false; }
  1146. else { closeList(); out.push('<pre><code>'); inCode = true; }
  1147. continue;
  1148. }
  1149. if (inCode) { out.push(line); continue; }
  1150. var h = line.match(/^(#{1,6})\s+(.*)$/);
  1151. if (h) { closeList(); out.push('<h' + h[1].length + '>' + mdInline(h[2]) + '</h' + h[1].length + '>'); continue; }
  1152. if (/^---+\s*$/.test(line)) { closeList(); out.push('<hr>'); continue; }
  1153. var bq = line.match(/^&gt;\s*(.*)$/);
  1154. if (bq) { closeList(); out.push('<blockquote>' + mdInline(bq[1]) + '</blockquote>'); continue; }
  1155. var ul = line.match(/^[-*]\s+(.*)$/);
  1156. if (ul) { if (inList !== 'ul') { closeList(); out.push('<ul>'); inList = 'ul'; } out.push('<li>' + mdInline(ul[1]) + '</li>'); continue; }
  1157. var ol = line.match(/^\d+\.\s+(.*)$/);
  1158. if (ol) { if (inList !== 'ol') { closeList(); out.push('<ol>'); inList = 'ol'; } out.push('<li>' + mdInline(ol[1]) + '</li>'); continue; }
  1159. closeList();
  1160. if (line.trim() === '') continue;
  1161. out.push('<p>' + mdInline(line) + '</p>');
  1162. }
  1163. closeList();
  1164. if (inCode) out.push('</code></pre>');
  1165. return out.join('\n');
  1166. }
  1167. function mdInline(text) {
  1168. return text
  1169. .replace(/`([^`]+)`/g, '<code>$1</code>')
  1170. .replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
  1171. .replace(/\*([^*]+)\*/g, '<em>$1</em>')
  1172. .replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2">$1</a>');
  1173. }
  1174. /**
  1175. * Demote child header tags by N levels (h1 → h2, etc.), capping at h6.
  1176. */
  1177. function handleHDemotion(el) {
  1178. var attr = el.getAttribute('stm-h-demotion');
  1179. if (!attr) return;
  1180. var n = parseInt(attr, 10);
  1181. if (isNaN(n) || n <= 0) return;
  1182. el.querySelectorAll('h1,h2,h3,h4,h5,h6').forEach(function (h) {
  1183. var level = parseInt(h.tagName.charAt(1), 10);
  1184. var newLevel = Math.min(level + n, 6);
  1185. if (newLevel === level) return;
  1186. var replacement = document.createElement('h' + newLevel);
  1187. for (var i = 0; i < h.attributes.length; i++)
  1188. replacement.setAttribute(h.attributes[i].name, h.attributes[i].value);
  1189. while (h.firstChild) replacement.appendChild(h.firstChild);
  1190. h.replaceWith(replacement);
  1191. });
  1192. }
  1193. /**
  1194. * Bind `stm-text` / `stm-html` / `stm-markdown`. Per the "leave original DOM
  1195. * content" policy, an unresolved value (`undefined`) leaves the element
  1196. * untouched; otherwise the value is stringified (`null` becomes empty).
  1197. */
  1198. function handleTextHtml(el, scope) {
  1199. if (el.hasAttribute('stm-text')) {
  1200. var text = evalExpr(el.getAttribute('stm-text'), scope);
  1201. if (text !== undefined) el.textContent = text === null ? '' : String(text);
  1202. }
  1203. if (el.hasAttribute('stm-html')) {
  1204. var html = evalExpr(el.getAttribute('stm-html'), scope);
  1205. if (html !== undefined) el.innerHTML = html === null ? '' : String(html);
  1206. }
  1207. if (el.hasAttribute('stm-markdown')) {
  1208. var md = evalExpr(el.getAttribute('stm-markdown'), scope);
  1209. if (md !== undefined) el.innerHTML = renderMarkdown(md === null ? '' : String(md));
  1210. }
  1211. // stm-h-demotion runs after stm-html / stm-markdown so the rendered
  1212. // headers are present in the DOM.
  1213. if (el.hasAttribute('stm-h-demotion')) handleHDemotion(el);
  1214. }
  1215. /**
  1216. * Expand a loop holder: reconcile its instances against the current array.
  1217. * Keyed loops (`stm-key`) reuse DOM nodes for unchanged keys to preserve
  1218. * focus/selection/input state; unkeyed loops rebuild wholesale.
  1219. */
  1220. function handleLoop(el, scope) {
  1221. var info = getStmFor(el);
  1222. if (!info) return;
  1223. var template = templates.get(el);
  1224. if (!template) {
  1225. template = el.cloneNode(true);
  1226. stripLoopAttrs(template);
  1227. templates.set(el, template);
  1228. }
  1229. var raw = evalExpr(info.expr, scope);
  1230. if (raw === undefined) {
  1231. // No value for the source path yet: clear instances and restore the
  1232. // server-rendered holder content (progressive enhancement).
  1233. var prev = instancesByHolder.get(el) || [];
  1234. prev.forEach(function (n) { n.remove(); });
  1235. instancesByHolder.set(el, []);
  1236. if (el.getAttribute('data-stm-active') === '1') {
  1237. el.removeAttribute('data-stm-active');
  1238. el.removeAttribute('hidden');
  1239. }
  1240. return;
  1241. }
  1242. var arr = Array.isArray(raw) ? raw : [];
  1243. // Activate: hide the holder so only rendered instances are visible.
  1244. if (el.getAttribute('data-stm-active') !== '1') {
  1245. el.setAttribute('data-stm-active', '1');
  1246. el.setAttribute('hidden', '');
  1247. }
  1248. var keyExpr = el.getAttribute('stm-key');
  1249. var next = [];
  1250. if (keyExpr) {
  1251. var oldByKey = new Map();
  1252. (instancesByHolder.get(el) || []).forEach(function (n) {
  1253. if (n.__stmKey !== undefined) oldByKey.set(n.__stmKey, n);
  1254. });
  1255. var used = new Set();
  1256. arr.forEach(function (item) {
  1257. var child = childScope(scope, info.varName, item);
  1258. var key = evalExpr(keyExpr, child);
  1259. var node = (key !== undefined && !used.has(key)) ? oldByKey.get(key) : undefined;
  1260. if (node) {
  1261. used.add(key);
  1262. processElement(node, child);
  1263. } else {
  1264. node = template.cloneNode(true);
  1265. node.__stmKey = key;
  1266. instanceNodes.add(node);
  1267. processElement(node, child);
  1268. }
  1269. next.push(node);
  1270. });
  1271. oldByKey.forEach(function (n, key) { if (!used.has(key)) n.remove(); });
  1272. } else {
  1273. (instancesByHolder.get(el) || []).forEach(function (n) { n.remove(); });
  1274. arr.forEach(function (item) {
  1275. var child = childScope(scope, info.varName, item);
  1276. var node = template.cloneNode(true);
  1277. instanceNodes.add(node);
  1278. processElement(node, child);
  1279. next.push(node);
  1280. });
  1281. }
  1282. // Place instances in order, immediately after the holder.
  1283. var ref = el;
  1284. next.forEach(function (node) {
  1285. if (node !== ref.nextSibling) ref.parentNode.insertBefore(node, ref.nextSibling);
  1286. ref = node;
  1287. });
  1288. instancesByHolder.set(el, next);
  1289. }
  1290. /**
  1291. * Process one element's bindings (and recurse). Loop holders are handled by
  1292. * {@link handleLoop}; `stm-else-if` / `stm-else` are owned by their `stm-if`.
  1293. */
  1294. function processElement(el, scope) {
  1295. if (getStmFor(el)) { handleLoop(el, scope); return; }
  1296. if (el.hasAttribute('stm-else-if') || el.hasAttribute('stm-else')) return;
  1297. if (el.hasAttribute('stm-if')) {
  1298. var active = handleIfChain(el, scope);
  1299. if (active) processInner(active, scope);
  1300. return;
  1301. }
  1302. processInner(el, scope);
  1303. }
  1304. /**
  1305. * Collect `stm-def-{name}-as` attributes on an element into a child scope.
  1306. * Each expression is evaluated against the incoming scope (so the new
  1307. * variables cannot reference each other within the same element), and the
  1308. * results are added to a child scope visible to the element and its
  1309. * descendants. Multiple defs on one element are supported. If there are no
  1310. * defs, the original scope is returned unchanged.
  1311. * @param {Element} el
  1312. * @param {object} scope
  1313. * @returns {object}
  1314. */
  1315. function applyDefs(el, scope) {
  1316. var attrs = el.attributes;
  1317. var child = null;
  1318. for (var i = 0; i < attrs.length; i++) {
  1319. var name = attrs[i].name;
  1320. if (name.indexOf('stm-def-') === 0 && name.slice(-3) === '-as') {
  1321. var varName = name.slice(8, -3);
  1322. if (!varName) continue;
  1323. if (!child) child = Object.create(scope || null);
  1324. child[varName] = evalExpr(attrs[i].value, scope);
  1325. }
  1326. }
  1327. return child || scope;
  1328. }
  1329. /** Bind the non-control-flow attributes and recurse into children. */
  1330. function processInner(el, scope) {
  1331. var s = applyDefs(el, scope); // local definitions: element + descendants
  1332. el.__stmScope = s; // latest scope, used when an action fires
  1333. handleClass(el, s);
  1334. handleAttribute(el, s);
  1335. handleDisabled(el, s);
  1336. handleTextHtml(el, s);
  1337. wireAction(el);
  1338. render(el, s);
  1339. }
  1340. /**
  1341. * Walk an element's children, processing each. Loop instance nodes are
  1342. * skipped here (they are owned and processed by their holder).
  1343. */
  1344. function render(root, scope) {
  1345. if (!root || !root.children) return;
  1346. // Snapshot the children: processing mutates the DOM (detaching branches,
  1347. // inserting loop instances) and a live HTMLCollection would shift indices.
  1348. var children = Array.prototype.slice.call(root.children);
  1349. for (var i = 0; i < children.length; i++) {
  1350. var el = children[i];
  1351. if (instanceNodes.has(el)) continue;
  1352. processElement(el, scope);
  1353. }
  1354. }
  1355. /** Re-render the whole document against the current state. */
  1356. /**
  1357. * Evaluate every `<link rel="stm-guard">` in the document head. A guard whose
  1358. * `require` predicate is false redirects the page to its `href`.
  1359. *
  1360. * Guards marked `pre-entrypoint` are evaluated on every cycle (including the
  1361. * initial, pre-entrypoint render, which uses only hydrated state); guards
  1362. * without it are evaluated only once the entrypoint has loaded. On every later
  1363. * evaluate cycle (set/clear) all guards are re-checked, so logging out, for
  1364. * example, can bounce the user off a guarded page.
  1365. */
  1366. function evaluateGuards() {
  1367. if (guardRedirected) return;
  1368. var scope = stateScope();
  1369. var guards = document.querySelectorAll('link[rel~="stm-guard"]');
  1370. for (var i = 0; i < guards.length; i++) {
  1371. var g = guards[i];
  1372. var preEntrypoint = g.hasAttribute('pre-entrypoint');
  1373. if (!preEntrypoint && !entrypointLoaded) continue;
  1374. var require = g.getAttribute('require');
  1375. if (!require) continue;
  1376. if (!evalExpr(require, scope)) {
  1377. guardRedirected = true;
  1378. var href = g.getAttribute('href') || '/';
  1379. console.warn('[statum] guard failed (' + require + '); redirecting to ' + href);
  1380. window.location.href = href;
  1381. return;
  1382. }
  1383. }
  1384. }
  1385. // ---------------------------------------------------------------------------
  1386. // Evaluation hooks (no-arg callbacks before/after each render cycle)
  1387. // ---------------------------------------------------------------------------
  1388. var beforeHooks = [];
  1389. var afterHooks = [];
  1390. function renderAll() {
  1391. if (guardRedirected) return;
  1392. beforeHooks.forEach(function (fn) { try { fn(); } catch (e) { console.error('[statum] beforeEvaluate hook error', e); } });
  1393. try { render(document.body, stateScope()); }
  1394. catch (e) { console.error('[statum] render error', e); }
  1395. afterHooks.forEach(function (fn) { try { fn(); } catch (e) { console.error('[statum] afterEvaluate hook error', e); } });
  1396. evaluateGuards();
  1397. }
  1398. // ---------------------------------------------------------------------------
  1399. // HTML API: actions
  1400. // ---------------------------------------------------------------------------
  1401. /**
  1402. * Collect data for an action trigger: `stm-data-{key}` attributes plus, for a
  1403. * form, its named inputs.
  1404. * @param {HTMLElement} el
  1405. * @returns {object}
  1406. */
  1407. function collectData(el) {
  1408. var data = {};
  1409. var attrs = el.attributes;
  1410. for (var i = 0; i < attrs.length; i++) {
  1411. var name = attrs[i].name;
  1412. if (name.indexOf('stm-data-') === 0) data[name.slice('stm-data-'.length)] = attrs[i].value;
  1413. }
  1414. if (el.tagName === 'FORM') {
  1415. var fd = new FormData(el);
  1416. fd.forEach(function (value, key) {
  1417. data[key] = value instanceof File ? value.name : String(value);
  1418. });
  1419. }
  1420. return data;
  1421. }
  1422. /**
  1423. * Toggle the busy state of an action element: disables the element and its
  1424. * descendant form controls and applies `stm-busy-class` classes while busy.
  1425. *
  1426. * On un-busy the disabled state is not "restored" to a captured snapshot
  1427. * (that would clobber a `stm-disabled` value that `renderAll` applied during
  1428. * the response); instead the nodes are re-enabled and `stm-disabled` is
  1429. * re-evaluated, which re-disables any that should remain disabled.
  1430. */
  1431. function setBusyState(el, busy) {
  1432. var nodes = [el].concat(Array.prototype.slice.call(
  1433. el.querySelectorAll('button,input,select,textarea,fieldset')));
  1434. var busyClasses = (el.getAttribute('stm-busy-class') || '').split(/\s+/).filter(Boolean);
  1435. if (busy) {
  1436. nodes.forEach(function (n) { n.setAttribute('disabled', ''); });
  1437. busyClasses.forEach(function (c) { el.classList.add(c); });
  1438. } else {
  1439. nodes.forEach(function (n) { n.removeAttribute('disabled'); });
  1440. busyClasses.forEach(function (c) { el.classList.remove(c); });
  1441. reapplyDisabled(el);
  1442. }
  1443. }
  1444. /** Re-apply `stm-disabled` to an element and any descendants that carry it. */
  1445. function reapplyDisabled(el) {
  1446. var scope = el.__stmScope || stateScope();
  1447. if (el.hasAttribute('stm-disabled')) handleDisabled(el, scope);
  1448. var scoped = el.querySelectorAll('[stm-disabled]');
  1449. Array.prototype.forEach.call(scoped, function (n) {
  1450. handleDisabled(n, n.__stmScope || scope);
  1451. });
  1452. }
  1453. /** Apply or remove `stm-on-error` classes on an action element. */
  1454. function applyErrorClasses(el, on) {
  1455. if (!el || !el.hasAttribute || !el.hasAttribute('stm-on-error')) return;
  1456. var classes = (el.getAttribute('stm-on-error') || '').split(/\s+/).filter(Boolean);
  1457. classes.forEach(function (c) { on ? el.classList.add(c) : el.classList.remove(c); });
  1458. }
  1459. /**
  1460. * Wire an element's primary action once. The listener resolves the action
  1461. * object against the element's latest render scope, so loop instances bind to
  1462. * their own item.
  1463. */
  1464. function wireAction(el) {
  1465. if (!el.hasAttribute('stm-action') || wired.has(el)) return;
  1466. wired.add(el);
  1467. var eventName = el.tagName === 'FORM' ? 'submit' : 'click';
  1468. el.addEventListener(eventName, function (event) {
  1469. event.preventDefault();
  1470. runElementAction(el);
  1471. });
  1472. }
  1473. /**
  1474. * Resolve and perform the action attached to an element, managing busy and
  1475. * error-state classes around the request.
  1476. * @param {HTMLElement} el
  1477. */
  1478. async function runElementAction(el) {
  1479. var scope = el.__stmScope || stateScope();
  1480. var action = evalExpr(el.getAttribute('stm-action'), scope);
  1481. if (!action || typeof action.uri !== 'string') return;
  1482. // stm-confirm: gate the action behind the confirm handler (async-capable,
  1483. // so custom modals are supported).
  1484. if (el.hasAttribute('stm-confirm')) {
  1485. var confirmed = await triggerConfirm(el.getAttribute('stm-confirm'), el);
  1486. if (!confirmed) return;
  1487. }
  1488. applyErrorClasses(el, false); // clear error state on a new attempt
  1489. var data = collectData(el);
  1490. setBusyState(el, true);
  1491. try {
  1492. await performAction(action, data, el);
  1493. } catch (err) {
  1494. // Already handled: stm-on-error classes and the onErrorHandler run inside
  1495. // performAction/reportFailure. Swallow so an HTML-triggered action does
  1496. // not surface as an unhandled rejection.
  1497. } finally {
  1498. setBusyState(el, false);
  1499. }
  1500. }
  1501. // ---------------------------------------------------------------------------
  1502. // Boot visibility (stm-preloader / stm-content)
  1503. // ---------------------------------------------------------------------------
  1504. /**
  1505. * Toggle pre/post-entrypoint visibility with the `hidden` attribute. While
  1506. * loading, `stm-preloader` elements are shown and `stm-content` elements
  1507. * hidden; once ready, the reverse.
  1508. *
  1509. * To avoid a flash of un-bound template before the script runs, authors may
  1510. * pre-set `hidden` directly on `stm-content` in the HTML (e.g.
  1511. * `<div stm-content hidden>`); the library removes it once ready. The library
  1512. * also sets `hidden` itself during loading as a fallback for authors who do
  1513. * not pre-set it.
  1514. * @param {boolean} ready
  1515. */
  1516. function setBootState(ready) {
  1517. var preloaders = document.querySelectorAll('[stm-preloader]');
  1518. var contents = document.querySelectorAll('[stm-content]');
  1519. for (var i = 0; i < preloaders.length; i++) {
  1520. ready ? preloaders[i].setAttribute('hidden', '') : preloaders[i].removeAttribute('hidden');
  1521. }
  1522. for (var j = 0; j < contents.length; j++) {
  1523. ready ? contents[j].removeAttribute('hidden') : contents[j].setAttribute('hidden', '');
  1524. }
  1525. }
  1526. // ---------------------------------------------------------------------------
  1527. // Public state accessors
  1528. // ---------------------------------------------------------------------------
  1529. /** Build the scope used for expression evaluation: `{ typeName: public }`. */
  1530. function stateScope() {
  1531. var scope = {};
  1532. store.forEach(function (entry, type) { scope[type] = entry.snapshot.public; });
  1533. return scope;
  1534. }
  1535. /** Read a type's `public` data (what the attributes bind to). */
  1536. function read(type) {
  1537. var entry = store.get(type);
  1538. return entry ? entry.snapshot.public : undefined;
  1539. }
  1540. /** Read a type's full snapshot object. */
  1541. function getSnapshot(type) {
  1542. var entry = store.get(type);
  1543. return entry ? entry.snapshot : undefined;
  1544. }
  1545. /** Read the frame wrapping a type's snapshot. */
  1546. function getFrame(type) {
  1547. var entry = store.get(type);
  1548. return entry ? entry.frame : undefined;
  1549. }
  1550. /** Build an object of `{ typeName: public }` for every held type. */
  1551. function state() {
  1552. var result = {};
  1553. store.forEach(function (entry, type) { result[type] = entry.snapshot.public; });
  1554. return result;
  1555. }
  1556. /**
  1557. * Clear state. With a type argument, clears that type only; without, clears
  1558. * all held state.
  1559. * @param {string} [type]
  1560. */
  1561. function clear(type) {
  1562. if (type === undefined) {
  1563. Array.from(store.keys()).forEach(function (t) { clearType(t, { broadcast: true }); });
  1564. } else {
  1565. clearType(type, { broadcast: true });
  1566. }
  1567. renderAll();
  1568. }
  1569. /**
  1570. * Perform an action. `action` may be an action object or a string path that
  1571. * resolves to an action object within the current state.
  1572. * @param {object|string} action
  1573. * @param {object} [data]
  1574. * @returns {Promise<void>}
  1575. */
  1576. function act(action, data) {
  1577. var resolved = action;
  1578. if (typeof action === 'string') resolved = evalExpr(action, stateScope());
  1579. if (!resolved || typeof resolved.uri !== 'string') {
  1580. return Promise.reject(new StatumError('Invalid action'));
  1581. }
  1582. return performAction(resolved, data, null);
  1583. }
  1584. /** Attach a state listener for a type. */
  1585. function addStateListener(type, callback) {
  1586. if (typeof callback !== 'function') return;
  1587. if (!listeners.has(type)) listeners.set(type, new Set());
  1588. listeners.get(type).add(callback);
  1589. }
  1590. /** Remove a previously-attached state listener. */
  1591. function removeStateListener(type, callback) {
  1592. var set = listeners.get(type);
  1593. if (!set) return;
  1594. set.delete(callback);
  1595. if (set.size === 0) listeners.delete(type);
  1596. }
  1597. // ---------------------------------------------------------------------------
  1598. // Initialization
  1599. // ---------------------------------------------------------------------------
  1600. /**
  1601. * Scan the document for `pstm-*` attributes and `<pstm-*>` elements, which
  1602. * are intended for server-side pre-rendering and should never reach the
  1603. * browser. Emits a single `console.warn` summarizing them.
  1604. */
  1605. function warnServerSideMarkup() {
  1606. var found = [];
  1607. var els = document.querySelectorAll('*');
  1608. for (var i = 0; i < els.length; i++) {
  1609. var el = els[i];
  1610. var tag = el.tagName.toLowerCase();
  1611. if (tag.indexOf('pstm-') === 0) found.push('<' + tag + '>');
  1612. var attrs = el.attributes;
  1613. for (var j = 0; j < attrs.length; j++) {
  1614. var name = attrs[j].name;
  1615. if (name.indexOf('pstm-') === 0) found.push('<' + tag + '> ' + name);
  1616. }
  1617. }
  1618. if (found.length) {
  1619. console.warn('[statum] ' + found.length + ' server-side pstm-* attribute/element(s) ' +
  1620. 'found in the DOM; they should have been resolved during pre-rendering: ' +
  1621. found.slice(0, 10).join(', ') + (found.length > 10 ? ' …' : ''));
  1622. }
  1623. }
  1624. /**
  1625. * Initialize Statum: read URL overrides, run the session-cookie check,
  1626. * hydrate persisted state, open the cross-tab channel, fetch the entrypoint,
  1627. * and render. Safe to call multiple times.
  1628. * @returns {Promise<void>}
  1629. */
  1630. async function init() {
  1631. if (initialized) return;
  1632. initialized = true;
  1633. var body = document.body;
  1634. if (body) {
  1635. if (body.hasAttribute('stm-entrypoint')) config.entrypointUrl = body.getAttribute('stm-entrypoint');
  1636. if (body.hasAttribute('stm-slots')) config.slotsUrl = body.getAttribute('stm-slots');
  1637. if (body.hasAttribute('stm-channel')) config.channelUrl = body.getAttribute('stm-channel');
  1638. if (body.hasAttribute('stm-worker')) config.workerUrl = body.getAttribute('stm-worker');
  1639. }
  1640. try { warnServerSideMarkup(); } catch (e) {}
  1641. try { initSession(); } catch (e) {}
  1642. try { hydrate(); } catch (e) {}
  1643. setupChannel();
  1644. setBootState(false);
  1645. renderAll(); // bind against any persisted/hydrated state immediately
  1646. try {
  1647. await loadEntrypoint();
  1648. } catch (err) {
  1649. console.error('[statum] entrypoint load failed', err);
  1650. } finally {
  1651. setBootState(true);
  1652. }
  1653. }
  1654. function autoInit() {
  1655. if (document.readyState === 'loading') {
  1656. document.addEventListener('DOMContentLoaded', init);
  1657. } else {
  1658. init();
  1659. }
  1660. }
  1661. // ---------------------------------------------------------------------------
  1662. // Public API
  1663. // ---------------------------------------------------------------------------
  1664. /** @namespace statum */
  1665. window.statum = {
  1666. /** Library version. */
  1667. version: '0.1.0',
  1668. /** Mutable endpoint configuration. */
  1669. config: config,
  1670. /** (Re)initialize the library. Usually runs automatically on load. */
  1671. init: init,
  1672. /** Read a type's `public` data. */
  1673. read: read,
  1674. /** Read a type's full snapshot object. */
  1675. getSnapshot: getSnapshot,
  1676. /** Read the frame wrapping a type's snapshot. */
  1677. getFrame: getFrame,
  1678. /** Build `{ typeName: public }` for every held type. */
  1679. state: state,
  1680. /** Clear one type (`clear("x")`) or all state (`clear()`). */
  1681. clear: clear,
  1682. /** Perform an action object or named action. */
  1683. act: act,
  1684. /** Attach a state-changed listener for a type. */
  1685. addStateListener: addStateListener,
  1686. /** Remove a previously-attached listener. */
  1687. removeStateListener: removeStateListener,
  1688. /** Register a callback that runs before each render cycle (no arguments). */
  1689. beforeEvaluate: function (fn) { if (typeof fn === 'function') beforeHooks.push(fn); },
  1690. /** Register a callback that runs after each render cycle (no arguments). */
  1691. afterEvaluate: function (fn) { if (typeof fn === 'function') afterHooks.push(fn); },
  1692. /** The Statum error type (thrown by `act` and surfaced to handlers). */
  1693. Error: StatumError,
  1694. get onConfirmHandler() { return handlers.onConfirm; },
  1695. set onConfirmHandler(v) { handlers.onConfirm = typeof v === 'function' ? v : null; },
  1696. get onNotifyHandler() { return handlers.onNotify; },
  1697. set onNotifyHandler(v) { handlers.onNotify = typeof v === 'function' ? v : null; },
  1698. get onErrorHandler() { return handlers.onError; },
  1699. set onErrorHandler(v) { handlers.onError = typeof v === 'function' ? v : null; }
  1700. };
  1701. autoInit();
  1702. })();