statum.js 70 KB

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