| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916 |
- /*!
- * Statum - client-side state library.
- *
- * An HTMX-inspired state layer. The library manages signed "snapshots" of
- * application state (one per slot type), keeps them fresh via the server's
- * `transmit_after` / `invalid_after` timestamps, and binds them to the DOM
- * through `stm-*` attributes. See model.md for the full specification.
- *
- * Distribution: a single IIFE that attaches `window.statum` (no dependencies,
- * no build step). Targets modern evergreen browsers (uses fetch,
- * BroadcastChannel, queueMicrotask, URLSearchParams, FormData).
- */
- (function () {
- 'use strict';
- /** Content-Type used by every Statum directive response. */
- var STATUM_CONTENT_TYPE = 'application/vnd.statum+json';
- /** Request/response header carrying one slot's reference (or base64 frame). */
- var SLOT_HEADER = 'X-Statum-Slot';
- /** Request header carrying an action's opaque `private` blob. */
- var PRIVATE_HEADER = 'X-Statum-Private';
- /** Session-cookie marker used to detect a fresh browser session. */
- var SESSION_COOKIE = '_statum_sdc';
- /** BroadcastChannel name used to sync session/device state across tabs. */
- var CHANNEL_NAME = 'statum';
- /** localStorage / sessionStorage key prefix for persisted frames. */
- var STORAGE_PREFIX = 'statum:';
- // ---------------------------------------------------------------------------
- // Configuration
- // ---------------------------------------------------------------------------
- /**
- * Endpoint URLs. These defaults may be overridden per-page with the
- * `stm-entrypoint` and `stm-slots` attributes on the `<body>` element.
- *
- * @type {{entrypointUrl: string, slotsUrl: string}}
- */
- var config = {
- entrypointUrl: '/_statum/entrypoint',
- slotsUrl: '/_statum/slots',
- channelUrl: '/_statum/channel',
- // The realtime worker is embedded in the library as a default resource
- // (served at /_statum/resource/statum-worker.js); override with stm-worker.
- workerUrl: '/_statum/resource/statum-worker.js'
- };
- // ---------------------------------------------------------------------------
- // State store
- // ---------------------------------------------------------------------------
- /**
- * In-memory store, keyed by slot type. Each value is `{frame, snapshot}`
- * where `snapshot` is the parsed `frame.content`. This map is the single
- * source of truth for rendering; persistent backends merely hydrate it.
- *
- * @type {Map<string, {frame: object, snapshot: object}>}
- */
- var store = new Map();
- /** Listeners, keyed by type name. @type {Map<string, Set<Function>>} */
- var listeners = new Map();
- /**
- * Idempotency tracking: slot key -> last-applied frame `signature`. Held in
- * memory only (per tab), so a frame already persisted by another tab still
- * re-draws a tab whose tracking lags. Entries are dropped on clear so a
- * replayed frame re-applies.
- * @type {Map<string, string>}
- */
- var signatures = new Map();
- /** Optional UI handlers (set via `statum.on*Handler`). */
- var handlers = { onConfirm: null, onNotify: null, onError: null };
- /** @type {BroadcastChannel|null} */
- var channel = null;
- /** Whether {@link init} has already run. */
- var initialized = false;
- /** Whether the entrypoint has been fetched (guards without pre-entrypoint
- * only evaluate after this). */
- var entrypointLoaded = false;
- /** Set when a guard has triggered a redirect, so further work is skipped. */
- var guardRedirected = false;
- // ---------------------------------------------------------------------------
- // Small utilities
- // ---------------------------------------------------------------------------
- /**
- * Parse an ISO 8601 timestamp to epoch millis, or `undefined`.
- * @param {string|undefined} s
- * @returns {number|undefined}
- */
- function parseTime(s) {
- if (!s) return undefined;
- var t = new Date(s).getTime();
- return isNaN(t) ? undefined : t;
- }
- /**
- * Base64-encode a UTF-8 string (safe for frames containing non-Latin1 data).
- * @param {string} str
- * @returns {string}
- */
- function b64encode(str) {
- var bytes = new TextEncoder().encode(str);
- var bin = '';
- var chunk = 0x8000;
- for (var i = 0; i < bytes.length; i += chunk) {
- bin += String.fromCharCode.apply(null, bytes.subarray(i, i + chunk));
- }
- return btoa(bin);
- }
- /** Read a cookie value, or `null` if absent. @param {string} name */
- function getCookie(name) {
- var escaped = name.replace(/([.$?*|{}()[\]\\/+^])/g, '\\$1');
- var match = document.cookie.match(new RegExp('(?:^|; )' + escaped + '=([^;]*)'));
- return match ? decodeURIComponent(match[1]) : null;
- }
- /** Set a session cookie (no expiry => cleared when the browser closes). */
- function setCookie(name, value) {
- document.cookie = name + '=' + encodeURIComponent(value) + '; path=/; SameSite=Lax';
- }
- // ---------------------------------------------------------------------------
- // Expression evaluation
- // ---------------------------------------------------------------------------
- /**
- * Compiled-expression cache. Expressions are evaluated as JavaScript against
- * a scope object (the page's HTML is trusted, per the model).
- * @type {Map<string, Function>}
- */
- var exprCache = new Map();
- /**
- * Wrap a scope for expression evaluation so bare identifiers resolve in a
- * controlled order: names on the scope (slot types, loop variables,
- * `stm-def-*` locals) win; names missing from the scope but present on
- * `globalThis` (`Math`, `parseInt`, `String`, …) forward to that global;
- * anything else resolves to `undefined` instead of throwing a
- * `ReferenceError` or leaking an unintended global. The `has` trap claims
- * every name so `with` never falls through around the proxy, and the inner
- * try/catch of the compiled expression still turns property access on a
- * resolved `undefined`/`null` into `undefined` for that expression alone.
- * @param {object} scope
- * @returns {Proxy<object>}
- */
- function evalScope(scope) {
- return new Proxy(scope, {
- has: function () { return true; },
- get: function (target, name) {
- if (name in target) return target[name];
- if (typeof name === 'string' && name in globalThis) return globalThis[name];
- return undefined;
- }
- });
- }
- /**
- * Compile (and cache) an expression string into a function of `scope`.
- * Uses `with` so that arbitrary type names and loop variables are resolved
- * as bare identifiers. Returns a function that yields `undefined` on any
- * runtime or compile error.
- * @param {string} expr
- * @returns {Function}
- */
- function compileExpr(expr) {
- var cached = exprCache.get(expr);
- if (cached !== undefined) return cached;
- var fn;
- try {
- // Function-constructor bodies are non-strict by default, so `with` is
- // permitted. The inner try/catch turns runtime errors (property access
- // on an unset slot's `undefined`) into `undefined` so a missing path
- // simply yields no value; missing identifiers already resolve to
- // `undefined` via the evalScope proxy.
- fn = new Function('scope', 'with(scope){try{return (' + expr + ');}catch(e){return undefined;}}');
- } catch (e) {
- fn = function () { return undefined; };
- }
- exprCache.set(expr, fn);
- return fn;
- }
- /**
- * Evaluate an expression against a scope.
- * @param {string} expr
- * @param {object} [scope]
- * @returns {*} `undefined` if the expression is empty or fails.
- */
- function evalExpr(expr, scope) {
- if (expr == null || expr === '') return undefined;
- try {
- return compileExpr(expr)(evalScope(scope || {}));
- } catch (e) {
- return undefined;
- }
- }
- /**
- * Build a child scope that inherits the parent (so type bindings remain
- * visible) and adds one own loop variable.
- * @param {object} parent
- * @param {string} name
- * @param {*} value
- * @returns {object}
- */
- function childScope(parent, name, value) {
- var scope = Object.create(parent || null);
- scope[name] = value;
- return scope;
- }
- // ---------------------------------------------------------------------------
- // StatumError
- // ---------------------------------------------------------------------------
- /**
- * Error type thrown for HTTP failures and `error` directives.
- * @param {string} [message]
- * @param {string} [code]
- * @param {object} [data]
- */
- function StatumError(message, code, data) {
- this.name = 'StatumError';
- this.message = message || '';
- this.code = code || undefined;
- this.data = data || undefined;
- }
- StatumError.prototype = Object.create(Error.prototype);
- // ---------------------------------------------------------------------------
- // UI handlers (confirm / notify / error)
- // ---------------------------------------------------------------------------
- /**
- * Run the `notify` directive's default behaviour or the custom
- * `statum.onNotifyHandler`. The default surfaces the message via `alert()`.
- * @param {string} [kind] Application-defined category (freeform).
- * @param {string} [message]
- */
- function triggerNotify(kind, message) {
- var fn = handlers.onNotify;
- try {
- if (fn) fn(kind, message);
- else if (message != null) window.alert(message);
- } catch (e) { console.error('[statum] notify handler error', e); }
- }
- /**
- * Run the `stm-confirm` gate: the custom `statum.onConfirmHandler` if set,
- * otherwise `window.confirm`. Supports async handlers (custom modals).
- * @param {string} message
- * @param {HTMLElement} element
- * @returns {Promise<boolean>} truthy if the action should proceed.
- */
- async function triggerConfirm(message, element) {
- var fn = handlers.onConfirm;
- try {
- if (fn) return !!(await fn(message, element));
- return !!window.confirm(message);
- } catch (e) {
- console.error('[statum] confirm handler error', e);
- return false;
- }
- }
- /**
- * Run the custom `statum.onErrorHandler`, if set. Returns whether the default
- * behaviour (promise rejection + `stm-on-error` classes) should proceed: the
- * handler suppresses the default by returning (or resolving) `false`.
- * @param {StatumError} error
- * @param {HTMLElement|null} element
- * @returns {Promise<boolean>}
- */
- async function triggerError(error, element) {
- var fn = handlers.onError;
- if (!fn) return true;
- try {
- var suppress = await fn(error, element);
- return suppress !== false;
- } catch (e) {
- console.error('[statum] error handler error', e);
- return true;
- }
- }
- /**
- * Surface a failure: run `triggerError`, and if the default is not
- * suppressed, apply `stm-on-error` classes (when an origin element exists)
- * and re-throw so the originating promise rejects.
- * @param {StatumError} error
- * @param {HTMLElement|null} element
- */
- async function reportFailure(error, element) {
- if (await triggerError(error, element)) {
- if (element) applyErrorClasses(element, true);
- throw error;
- }
- }
- // ---------------------------------------------------------------------------
- // Persistence
- // ---------------------------------------------------------------------------
- /**
- * Pick the storage backend for a scope.
- * @param {string} scope
- * @returns {Storage|null} `null` for in-memory scopes.
- */
- function storageFor(scope) {
- if (scope === 'device' || scope === 'session') return localStorage;
- if (scope === 'flow') return sessionStorage;
- return null; // page / transient
- }
- /**
- * Persist a slot's frame to the backend matching its scope, removing any
- * stale copy from the other backend first (in case the scope changed).
- * @param {string} type
- * @param {{frame: object, snapshot: object}} entry
- */
- function persistEntry(type, entry) {
- var scope = entry.snapshot.slot && entry.snapshot.slot.scope;
- removePersisted(type);
- var storage = storageFor(scope);
- if (!storage) return;
- try {
- storage.setItem(STORAGE_PREFIX + type, JSON.stringify(entry.frame));
- } catch (e) {
- /* storage full or unavailable; remain in-memory only */
- }
- }
- /** Remove a persisted frame from both backends. @param {string} type */
- function removePersisted(type) {
- try { localStorage.removeItem(STORAGE_PREFIX + type); } catch (e) {}
- try { sessionStorage.removeItem(STORAGE_PREFIX + type); } catch (e) {}
- }
- /** Load every persisted frame from a backend into the in-memory store. */
- function loadFrom(storage) {
- for (var i = 0; i < storage.length; i++) {
- var key = storage.key(i);
- if (!key || key.indexOf(STORAGE_PREFIX) !== 0) continue;
- try {
- var frame = JSON.parse(storage.getItem(key));
- var snapshot = JSON.parse(frame.content);
- var type = snapshot.slot && snapshot.slot.type;
- if (type && !store.has(type)) store.set(type, { frame: frame, snapshot: snapshot });
- } catch (e) {
- /* corrupt entry: ignore */
- }
- }
- }
- /** Hydrate the store from localStorage and sessionStorage. */
- function hydrate() {
- try { loadFrom(localStorage); } catch (e) {}
- try { loadFrom(sessionStorage); } catch (e) {}
- }
- // ---------------------------------------------------------------------------
- // Session-cookie initialization
- // ---------------------------------------------------------------------------
- /**
- * Detect a fresh browser session using the `_statum_sdc` session cookie.
- * On a fresh session, clear all `session`-scoped persisted frames, then set
- * the marker. Session cookies are shared across tabs, so a tab opened
- * mid-session sees the marker and leaves session data intact.
- */
- function initSession() {
- if (getCookie(SESSION_COOKIE) !== null) return;
- clearSessionSlotsFromStorage();
- setCookie(SESSION_COOKIE, '1');
- }
- /** Remove all `session`-scoped frames from localStorage. */
- function clearSessionSlotsFromStorage() {
- var toRemove = [];
- for (var i = 0; i < localStorage.length; i++) {
- var key = localStorage.key(i);
- if (!key || key.indexOf(STORAGE_PREFIX) !== 0) continue;
- try {
- var frame = JSON.parse(localStorage.getItem(key));
- var snapshot = JSON.parse(frame.content);
- if (snapshot.slot && snapshot.slot.scope === 'session') toRemove.push(key);
- } catch (e) {}
- }
- for (var j = 0; j < toRemove.length; j++) localStorage.removeItem(toRemove[j]);
- }
- // ---------------------------------------------------------------------------
- // Listeners & cross-tab broadcast
- // ---------------------------------------------------------------------------
- /**
- * Fire all listeners for a type. (Renamed from `notify` to avoid confusion
- * with the `notify` directive.)
- * @param {string} type
- * @param {object|null} frame
- * @param {object|null} snapshot
- */
- function fireListeners(type, frame, snapshot) {
- var set = listeners.get(type);
- if (!set) return;
- var event = { type: type, frame: frame, snapshot: snapshot };
- set.forEach(function (cb) {
- try { cb(event); } catch (e) { console.error('[statum] listener error', e); }
- });
- }
- /**
- * Broadcast a state change to other tabs. Only `session`/`device` scopes are
- * shared (flow/page/transient are per-tab).
- * @param {object} message
- * @param {string} [scope]
- */
- function broadcast(message, scope) {
- if (!channel) return;
- if (scope !== 'session' && scope !== 'device') return;
- try { channel.postMessage(message); } catch (e) {}
- }
- /**
- * Broadcast a message to other tabs regardless of slot scope. Used to relay
- * realtime (live) events so they reach every tab, not just session/device
- * ones.
- */
- function broadcastAlways(message) {
- if (!channel) return;
- try { channel.postMessage(message); } catch (e) {}
- }
- /** Open the BroadcastChannel and wire inbound messages. */
- function setupChannel() {
- if (typeof BroadcastChannel === 'undefined') return;
- try {
- channel = new BroadcastChannel(CHANNEL_NAME);
- } catch (e) {
- channel = null;
- return;
- }
- channel.onmessage = function (ev) {
- var msg = ev.data;
- if (!msg) return;
- if (msg.kind === 'set' && msg.frame) {
- try {
- var snapshot = JSON.parse(msg.frame.content);
- var type = snapshot.slot && snapshot.slot.type;
- if (type && commitSet(msg.frame, snapshot, type, false)) renderAll();
- } catch (e) { /* ignore malformed */ }
- } else if (msg.kind === 'clear') {
- var t = msg.type;
- if (!t && msg.key != null) {
- store.forEach(function (entry, type) {
- if (entry.snapshot.slot && entry.snapshot.slot.key === msg.key) t = type;
- });
- }
- if (t) clearType(t, { broadcast: false });
- else if (msg.key != null) signatures.delete(msg.key);
- renderAll();
- }
- };
- }
- // ---------------------------------------------------------------------------
- // State mutation
- // ---------------------------------------------------------------------------
- /**
- * Remove a type from the store, un-persist it, drop its idempotency entry,
- * fire listeners, and (optionally) broadcast the clear to other tabs.
- * @param {string} type
- * @param {{broadcast?: boolean}} [opts]
- */
- function clearType(type, opts) {
- var entry = store.get(type);
- if (!entry) return;
- var scope = entry.snapshot.slot && entry.snapshot.slot.scope;
- var key = entry.snapshot.slot && entry.snapshot.slot.key;
- store.delete(type);
- removePersisted(type);
- if (key) signatures.delete(key);
- fireListeners(type, null, null);
- if (opts && opts.broadcast) broadcast({ kind: 'clear', key: key, type: type }, scope);
- }
- /**
- * Resolve a slot key to its type and clear it. Used by the `clear` directive
- * (keyed) and by live `clear` events.
- * @param {string} key
- * @param {boolean} [broadcast]
- */
- function clearByKey(key, broadcast) {
- var typeToRemove = null;
- store.forEach(function (entry, type) {
- if (entry.snapshot.slot && entry.snapshot.slot.key === key) typeToRemove = type;
- });
- if (typeToRemove) clearType(typeToRemove, { broadcast: !!broadcast });
- else if (key) signatures.delete(key);
- }
- /**
- * Resolve a frame signature to its slot type and clear it. Used by the
- * `invalidate` directive, which references a signature (not a key) because the
- * server reports a bad signature without trusting the frame's content.
- * @param {string} signature
- * @param {boolean} [broadcast]
- */
- function clearBySignature(signature, broadcast) {
- var typeToRemove = null;
- store.forEach(function (entry, type) {
- if (entry.frame && entry.frame.signature === signature) typeToRemove = type;
- });
- if (typeToRemove) clearType(typeToRemove, { broadcast: !!broadcast });
- else if (signature) signatures.delete(signature);
- }
- /**
- * Commit a `set` to the in-memory store, persist it, and fire listeners.
- * Idempotent: if the frame's `signature` matches the last-applied signature
- * for this slot (tracked in {@link signatures}), nothing happens and `false`
- * is returned. When `doBroadcast` is true the set is forwarded to other tabs
- * via the scope-gated broadcast (session/device only).
- * @param {object} frame
- * @param {object} snapshot
- * @param {string} type
- * @param {boolean} doBroadcast
- * @returns {boolean} `true` if state changed.
- */
- function commitSet(frame, snapshot, type, doBroadcast) {
- var key = snapshot.slot && snapshot.slot.key;
- var sig = frame.signature;
- if (key && sig !== undefined && signatures.get(key) === sig) return false;
- var entry = { frame: frame, snapshot: snapshot };
- store.set(type, entry);
- persistEntry(type, entry);
- fireListeners(type, frame, snapshot);
- if (key && sig !== undefined) signatures.set(key, sig);
- if (doBroadcast) {
- var scope = snapshot.slot && snapshot.slot.scope;
- broadcast({ kind: 'set', frame: frame }, scope);
- }
- return true;
- }
- /**
- * Apply a `set` directive: store/refresh a slot's snapshot (idempotently),
- * broadcasting to other tabs.
- * @param {object} directive `{ snapshot_frame }`
- */
- function applySet(directive) {
- var frame = directive.snapshot_frame;
- if (!frame || !frame.content) return;
- var snapshot;
- try { snapshot = JSON.parse(frame.content); } catch (e) { return; }
- var type = snapshot.slot && snapshot.slot.type;
- if (!type) return;
- commitSet(frame, snapshot, type, true);
- }
- /**
- * Apply a `clear` directive. The directive carries a slot key, so the type
- * holding that key is resolved and removed.
- * @param {object} directive `{ key }`
- */
- function applyClear(directive) {
- if (directive.key == null) return;
- clearByKey(directive.key, true);
- }
- /**
- * Apply a live `set` event received over the realtime channel. The frame is
- * committed (idempotently) and, when new, broadcast to sibling tabs via the
- * scope-agnostic {@link broadcastAlways} so every tab sees it regardless of
- * which (or how many) tabs hold a subscription.
- * @param {object} frame
- */
- function applyRemoteSet(frame) {
- try {
- var snapshot = JSON.parse(frame.content);
- var type = snapshot.slot && snapshot.slot.type;
- if (!type) return;
- if (commitSet(frame, snapshot, type, false)) {
- broadcastAlways({ kind: 'set', frame: frame });
- renderAll();
- }
- } catch (e) { /* malformed frame */ }
- }
- /** Apply a live `clear` event received over the realtime channel. */
- function applyRemoteClear(key) {
- if (key == null) return;
- signatures.delete(key);
- clearByKey(key, false);
- broadcastAlways({ kind: 'clear', key: key });
- renderAll();
- }
- // ---------------------------------------------------------------------------
- // Snapshot freshness & request headers
- // ---------------------------------------------------------------------------
- /**
- * Categorize a held snapshot relative to the current time.
- * @returns {'silent'|'always'|'invalid'|'stale'|'fresh'}
- * - `silent`: unidirectional (`transmit_after` undefined) - never sent.
- * - `always`: `transmit_after === as_at` - send the base64 frame each time.
- * - `invalid`: past `invalid_after` - drop and refetch.
- * - `stale`: past `transmit_after` but not yet invalid - pre-flight first.
- * - `fresh`: still cached server-side - send the `as_at` reference.
- */
- function entryCategory(entry) {
- var snap = entry.snapshot;
- var transmit = snap.transmit_after;
- if (transmit === undefined || transmit === null) return 'silent';
- if (transmit === snap.as_at) return 'always';
- var now = Date.now();
- var invalidAt = parseTime(snap.invalid_after);
- var transmitAt = parseTime(transmit);
- if (invalidAt !== undefined && now >= invalidAt) return 'invalid';
- if (transmitAt !== undefined && now >= transmitAt) return 'stale';
- return 'fresh';
- }
- /**
- * Drop locally-invalid snapshots and pre-flight any stale ones. Pre-flighting
- * posts the stale frames to the slot endpoint and applies the returned `set`
- * directives, refreshing their `as_at` values before the real request runs.
- *
- * Single-flight: concurrent callers share one in-flight preparation.
- * @returns {Promise<void>}
- */
- var preparePromise = null;
- function prepareSlots() {
- if (preparePromise) return preparePromise;
- preparePromise = doPrepareSlots().then(function () {
- preparePromise = null;
- }, function () {
- preparePromise = null;
- });
- return preparePromise;
- }
- async function doPrepareSlots() {
- var stale = [];
- store.forEach(function (entry, type) {
- var cat = entryCategory(entry);
- if (cat === 'invalid') {
- clearType(type, { broadcast: false });
- } else if (cat === 'stale') {
- stale.push(entry.frame);
- }
- });
- if (stale.length) {
- var directives = await postSlots(stale);
- var pfResult = applyDirectives(directives, { originElement: null });
- executeTerminal(pfResult);
- }
- }
- /**
- * Build the `X-Statum-Slot` header values for every held slot, using the
- * freshness rules. Assumes {@link prepareSlots} has just run.
- * @returns {string[]}
- */
- function buildSlotHeaders() {
- var headers = [];
- store.forEach(function (entry) {
- var snap = entry.snapshot;
- var cat = entryCategory(entry);
- if (cat === 'silent' || cat === 'invalid') return;
- if (cat === 'always') {
- headers.push(b64encode(JSON.stringify(entry.frame)));
- } else {
- headers.push('key=' + snap.slot.key + '; as_at=' + snap.as_at);
- }
- });
- return headers;
- }
- /**
- * Collect the current frames held for the given slot keys, in the order the
- * keys are first supplied. Used by the `transmit` directive (which forces a
- * slot's frame to be posted as if its `transmit_after` had elapsed). Keys the
- * client does not currently hold are skipped.
- * @param {string[]} keys
- * @returns {object[]}
- */
- function collectFramesForKeys(keys) {
- var keySet = Object.create(null);
- for (var i = 0; i < keys.length; i++) keySet[keys[i]] = true;
- var frames = [];
- store.forEach(function (entry) {
- var key = entry.snapshot.slot && entry.snapshot.slot.key;
- if (key && keySet[key]) {
- frames.push(entry.frame);
- delete keySet[key];
- }
- });
- return frames;
- }
- // ---------------------------------------------------------------------------
- // HTTP helpers
- // ---------------------------------------------------------------------------
- /** True if a response is a Statum directive response. */
- function isStatum(res) {
- return (res.headers.get('Content-Type') || '').indexOf(STATUM_CONTENT_TYPE) !== -1;
- }
- /**
- * POST an array of frames to the slot endpoint (the pre-flight target) and
- * return its directive array. This request intentionally carries no slot
- * headers (it is itself the refresh).
- * @param {object[]} frames
- * @returns {Promise<object[]>}
- */
- async function postSlots(frames) {
- var headers = new Headers();
- headers.set('Accept', STATUM_CONTENT_TYPE);
- headers.set('Content-Type', 'application/json');
- var res = await fetch(config.slotsUrl, {
- method: 'POST',
- headers: headers,
- body: JSON.stringify(frames),
- credentials: 'same-origin'
- });
- if (!isStatum(res)) return [];
- try { return await res.json(); } catch (e) { return []; }
- }
- /**
- * Apply the non-terminal directives from a response (set/clear/subscribe/
- * unsubscribe/notify/transmit-collection), then `render`.
- *
- * Terminal directives (`navigate`, `post`), error directives, and any
- * transmit/retry intent are collected on the returned result rather than
- * executed here: {@link handleResponse} performs the asynchronous
- * transmission (and optional retry) and then runs terminal navigation, so
- * that a `transmit` with `retry` can re-issue the request before the page is
- * navigated away.
- * @param {object[]} directives
- * @param {{originElement?: HTMLElement}} [ctx]
- * @returns {{errors: StatumError[], transmitKeys: string[], retry: boolean, navigate: object|null, post: object|null}}
- */
- function applyDirectives(directives, ctx) {
- var result = { errors: [], transmitKeys: [], retry: false, navigate: null, post: null, formSubmits: [], formResets: [] };
- var list = Array.isArray(directives) ? directives : [];
- for (var i = 0; i < list.length; i++) {
- var d = list[i];
- if (!d || typeof d !== 'object') continue;
- switch (d.type) {
- case 'set': applySet(d); break;
- case 'clear': applyClear(d); break;
- case 'invalidate':
- if (d.signature != null) {
- console.warn('[statum] server could not verify slot frame ' + d.signature + '; clearing it');
- clearBySignature(d.signature, true);
- }
- break;
- case 'subscribe': channelSubscribe(d.key); break;
- case 'unsubscribe': channelUnsubscribe(d.key); break;
- case 'notify': triggerNotify(d.kind, d.message); break;
- case 'transmit':
- if (d.key != null) {
- if (result.transmitKeys.indexOf(d.key) === -1) result.transmitKeys.push(d.key);
- if (d.retry) result.retry = true;
- }
- break;
- case 'error':
- {
- var err = new StatumError(d.message, d.code, d.data);
- var detail = d.code ? (d.message + ' [' + d.code + ']') : d.message;
- console.error('[statum] error directive: ' + (detail || '(no message)'));
- result.errors.push(err);
- }
- break;
- case 'navigate': result.navigate = d; break;
- case 'post': result.post = d; break;
- case 'form-submit': result.formSubmits.push(d); break;
- case 'form-reset': result.formResets.push(d); break;
- }
- }
- renderAll();
- return result;
- }
- /** Execute the terminal directives collected by {@link applyDirectives}. */
- function executeTerminal(result) {
- result.formResets.forEach(doFormReset);
- result.formSubmits.forEach(doFormSubmit);
- if (result.navigate) doNavigate(result.navigate);
- if (result.post) doPost(result.post);
- }
- /** Execute a `form-submit` directive: optionally override action/method, then submit. */
- function doFormSubmit(d) {
- var form = document.getElementById(d.form);
- if (form) {
- if (d.action) form.setAttribute('action', d.action);
- if (d.method) form.setAttribute('method', d.method);
- form.submit();
- }
- }
- /** Execute a `form-reset` directive. */
- function doFormReset(d) {
- var form = document.getElementById(d.form);
- if (form) form.reset();
- }
- /** Execute a `navigate` directive as a full page load. */
- function doNavigate(d) {
- if (d.uri) window.location.href = d.uri;
- }
- /** Execute a `post` directive as a real (navigating) form POST. */
- function doPost(d) {
- if (!d.uri) return;
- var form = document.createElement('form');
- form.method = 'POST';
- form.action = d.uri;
- form.style.display = 'none';
- var data = d.data || {};
- Object.keys(data).forEach(function (name) {
- var input = document.createElement('input');
- input.type = 'hidden';
- input.name = name;
- input.value = data[name] == null ? '' : String(data[name]);
- form.appendChild(input);
- });
- document.body.appendChild(form);
- form.submit();
- }
- /**
- * Handle a fetch response: if it is a Statum response, apply its directives;
- * otherwise throw on HTTP errors and no-op on other successful responses.
- *
- * Directive ordering: non-terminal directives are applied and the page
- * rendered; then any `transmit` directives force their slot frames to be
- * posted (applying the directives the slot endpoint returns); then, if a
- * transmit requested a retry, the originating request (`ctx.retry`) is
- * re-issued and this response's terminal directives and errors are skipped.
- * Otherwise terminal navigation runs, then error directives are surfaced.
- * @param {Response} res
- * @param {{originElement?: HTMLElement, retry?: Function}} [ctx]
- */
- async function handleResponse(res, ctx) {
- var el = ctx && ctx.originElement;
- if (!isStatum(res)) {
- if (!res.ok) await reportFailure(new StatumError('HTTP ' + res.status), el);
- return;
- }
- var directives;
- try { directives = await res.json(); } catch (e) { directives = []; }
- var result = applyDirectives(directives, ctx);
- if (result.transmitKeys && result.transmitKeys.length) {
- var frames = collectFramesForKeys(result.transmitKeys);
- if (frames.length) {
- var txDirectives = await postSlots(frames);
- applyDirectives(txDirectives, { originElement: el });
- }
- }
- if (result.retry && ctx && typeof ctx.retry === 'function') {
- await ctx.retry();
- return;
- }
- executeTerminal(result);
- var errors = result.errors || [];
- for (var i = 0; i < errors.length; i++) {
- await reportFailure(errors[i], el);
- }
- }
- // ---------------------------------------------------------------------------
- // Entrypoint & action requests
- // ---------------------------------------------------------------------------
- /**
- * Fetch the entrypoint for the current URL, applying its directives. Carries
- * slot headers (and pre-flights) like any other request. The request is
- * wrapped in an `attempt` closure passed as the response `retry` callback, so
- * a `transmit` directive with `retry` can re-issue it after transmission.
- * @returns {Promise<void>}
- */
- function loadEntrypoint() {
- if (guardRedirected) return Promise.resolve();
- // From this point on guards are "post-entrypoint" (all of them evaluate).
- entrypointLoaded = true;
- var attempt = async function () {
- await prepareSlots();
- var headers = new Headers();
- headers.set('Accept', STATUM_CONTENT_TYPE);
- buildSlotHeaders().forEach(function (v) { headers.append(SLOT_HEADER, v); });
- var url = config.entrypointUrl + '?uri=' + encodeURIComponent(window.location.href);
- var res = await fetch(url, { headers: headers, credentials: 'same-origin' });
- await handleResponse(res, { originElement: null, retry: attempt });
- };
- return attempt();
- }
- /**
- * Perform an action request.
- *
- * The request is wrapped in an `attempt` closure passed as the response
- * `retry` callback, so a `transmit` directive with `retry` can re-issue the
- * same action after the transmission (rebuilding headers from current state).
- *
- * @param {object} action `{ uri, method, private }`
- * @param {object} [data] Key/value parameters. Encoded as query string for
- * GET/HEAD, otherwise as `application/x-www-form-urlencoded`.
- * @param {HTMLElement} [originElement] Element that triggered the action, so
- * that `stm-on-error` classes can be applied on an `error` directive.
- * @returns {Promise<void>} Resolves once the request completes and its
- * directives have run; rejects on HTTP failure or an `error` directive.
- */
- function performAction(action, data, originElement) {
- var attempt = async function () {
- await prepareSlots();
- var headers = new Headers();
- headers.set('Accept', STATUM_CONTENT_TYPE);
- buildSlotHeaders().forEach(function (v) { headers.append(SLOT_HEADER, v); });
- if (action.private) headers.set(PRIVATE_HEADER, action.private);
- var method = (action.method || 'GET').toUpperCase();
- var params = data || {};
- var init = { method: method, headers: headers, credentials: 'same-origin' };
- var url = action.uri;
- if (method === 'GET' || method === 'HEAD') {
- var qs = new URLSearchParams(params).toString();
- if (qs) url += (url.indexOf('?') !== -1 ? '&' : '?') + qs;
- } else {
- init.body = new URLSearchParams(params).toString();
- headers.set('Content-Type', 'application/x-www-form-urlencoded');
- }
- var res;
- try {
- res = await fetch(url, init);
- } catch (networkErr) {
- await reportFailure(new StatumError('Network error'), originElement);
- return;
- }
- await handleResponse(res, { originElement: originElement, retry: attempt });
- };
- return attempt();
- }
- // ---------------------------------------------------------------------------
- // Realtime channel (subscribe/unsubscribe directives)
- // ---------------------------------------------------------------------------
- /**
- * Per-tab fallback engine, used when `SharedWorker` is unavailable. Owns an
- * `EventSource`, reads the channel id from the first `event: channel`,
- * reference-counts slot keys within this tab, PATCHes subscription changes,
- * applies incoming set/clear events (broadcasting them to siblings), and
- * closes the stream once it has no subscriptions.
- */
- function createFallbackEngine() {
- var es = null;
- var channelId = null;
- var refs = new Map(); // slotKey -> count
- var pending = { subscribe: [], unsubscribe: [] };
- var patchScheduled = false;
- function openStream() {
- if (es) return;
- try { es = new EventSource(config.channelUrl); }
- catch (e) { es = null; return; }
- es.addEventListener('channel', function (ev) { channelId = ev.data; flushPatch(); });
- es.addEventListener('set', function (ev) {
- try { applyRemoteSet(JSON.parse(ev.data)); } catch (e) {}
- });
- es.addEventListener('clear', function (ev) { applyRemoteClear(ev.data); });
- es.onerror = function () { /* EventSource auto-reconnects */ };
- }
- function closeStream() {
- if (es) { try { es.close(); } catch (e) {} es = null; }
- channelId = null;
- }
- function schedulePatch() {
- if (patchScheduled) return;
- patchScheduled = true;
- Promise.resolve().then(function () { patchScheduled = false; flushPatch(); });
- }
- function flushPatch() {
- if (!channelId) return;
- var sub = pending.subscribe, uns = pending.unsubscribe;
- if (!sub.length && !uns.length) return;
- pending = { subscribe: [], unsubscribe: [] };
- var body = {};
- if (sub.length) body.subscribe = sub;
- if (uns.length) body.unsubscribe = uns;
- try {
- fetch(config.channelUrl + '/' + encodeURIComponent(channelId), {
- method: 'PATCH',
- headers: { 'Content-Type': 'application/json' },
- credentials: 'same-origin',
- body: JSON.stringify(body)
- }).catch(function () {});
- } catch (e) {}
- }
- return {
- subscribe: function (key) {
- var c = refs.get(key) || 0;
- refs.set(key, c + 1);
- if (c === 0) { openStream(); pending.subscribe.push(key); schedulePatch(); }
- },
- unsubscribe: function (key) {
- var c = refs.get(key) || 0;
- if (c <= 0) return;
- if (c - 1 <= 0) {
- refs.delete(key);
- pending.unsubscribe.push(key);
- schedulePatch();
- if (refs.size === 0) setTimeout(function () { if (refs.size === 0) closeStream(); }, 0);
- } else {
- refs.set(key, c - 1);
- }
- }
- };
- }
- /**
- * Channel manager. Prefers a `SharedWorker` (which owns the single SSE
- * connection, reference-counts subscriptions across tabs, and relays events
- * through the cross-tab `BroadcastChannel`); falls back to a per-tab
- * `EventSource` engine when `SharedWorker` is unavailable or the worker
- * script fails to load. Tracks the true per-slot subscription count so it can
- * replay active subscriptions into the fallback on a mid-session switch.
- */
- function createChannelManager() {
- var port = null;
- var workerObj = null;
- var fallback = null;
- var mode = null; // 'worker' | 'fallback' | null
- var counts = new Map(); // slotKey -> count (true subscription state)
- function switchToFallback() {
- if (mode === 'fallback') return;
- mode = 'fallback';
- port = null;
- workerObj = null;
- fallback = createFallbackEngine();
- counts.forEach(function (c, key) {
- for (var i = 0; i < c; i++) fallback.subscribe(key);
- });
- }
- function ensure() {
- if (mode !== null) return;
- if (typeof SharedWorker !== 'undefined') {
- try {
- workerObj = new SharedWorker(config.workerUrl);
- port = workerObj.port;
- port.start();
- port.postMessage({ op: 'init', url: config.channelUrl });
- // The worker delivers events via the BroadcastChannel, so nothing is
- // required on this port beyond command messages.
- port.onmessage = function () {};
- workerObj.onerror = function () {
- console.warn('[statum] realtime worker failed; falling back to per-tab channel');
- switchToFallback();
- };
- window.addEventListener('pagehide', function () {
- if (mode === 'worker' && port) {
- try { port.postMessage({ op: 'disconnect' }); } catch (e) {}
- }
- });
- mode = 'worker';
- return;
- } catch (e) { workerObj = null; port = null; }
- }
- switchToFallback();
- }
- return {
- subscribe: function (key) {
- if (key == null) return;
- ensure();
- counts.set(key, (counts.get(key) || 0) + 1);
- if (mode === 'worker') { try { port.postMessage({ op: 'subscribe', key: key }); } catch (e) {} }
- else fallback.subscribe(key);
- },
- unsubscribe: function (key) {
- if (key == null) return;
- var c = (counts.get(key) || 0) - 1;
- if (c <= 0) counts.delete(key); else counts.set(key, c);
- ensure();
- if (mode === 'worker') { try { port.postMessage({ op: 'unsubscribe', key: key }); } catch (e) {} }
- else fallback.unsubscribe(key);
- }
- };
- }
- var channelManager = createChannelManager();
- function channelSubscribe(key) { channelManager.subscribe(key); }
- function channelUnsubscribe(key) { channelManager.unsubscribe(key); }
- // ---------------------------------------------------------------------------
- // Rendering: loops, conditionals, bindings
- // ---------------------------------------------------------------------------
- /** Templates captured from loop holders. @type {WeakMap<Element, Element>} */
- var templates = new WeakMap();
- /** Instance nodes managed by a loop holder. @type {WeakMap<Element, Element[]>} */
- var instancesByHolder = new WeakMap();
- /** Loop instance nodes; skipped by the render walk (owned by their holder). */
- var instanceNodes = new WeakSet();
- /** Elements whose `stm-action` has been wired, to avoid double-binding. */
- var wired = new WeakSet();
- /**
- * Find a `stm-for-{name}-in` attribute on an element.
- * @returns {{varName: string, expr: string}|null}
- */
- function getStmFor(el) {
- var attrs = el.attributes;
- for (var i = 0; i < attrs.length; i++) {
- var match = attrs[i].name.match(/^stm-for-(.+)-in$/);
- if (match) return { varName: match[1], expr: attrs[i].value };
- }
- return null;
- }
- /** Remove any `stm-for-*` and `stm-key` attributes from an element. */
- function stripLoopAttrs(el) {
- var toRemove = [];
- for (var i = 0; i < el.attributes.length; i++) {
- var name = el.attributes[i].name;
- if (/^stm-for-(.+)-in$/.test(name) || name === 'stm-key') toRemove.push(name);
- }
- toRemove.forEach(function (n) { el.removeAttribute(n); });
- }
- /**
- * Evaluate an `stm-if` / `stm-else-if` / `stm-else` chain beginning at `el`,
- * showing the matching branch and hiding the rest.
- *
- * Branches are toggled with the `hidden` attribute rather than detached, so
- * every branch stays in the DOM and is re-evaluated on each render. (Detaching
- * the `stm-if` element would remove it from the render walk, leaving an
- * already-attached `stm-else` branch skipped and never refreshed.)
- * @returns {Element|null} The active branch element (or `null`).
- */
- function handleIfChain(el, scope) {
- var branches = [{ el: el, expr: el.getAttribute('stm-if') }];
- var cur = el.nextElementSibling;
- while (cur) {
- if (cur.hasAttribute('stm-else-if')) {
- branches.push({ el: cur, expr: cur.getAttribute('stm-else-if') });
- cur = cur.nextElementSibling;
- } else if (cur.hasAttribute('stm-else')) {
- branches.push({ el: cur, expr: null });
- break;
- } else {
- break;
- }
- }
- var activeEl = null;
- for (var i = 0; i < branches.length; i++) {
- var b = branches[i];
- if (b.expr === null || !!evalExpr(b.expr, scope)) { activeEl = b.el; break; }
- }
- branches.forEach(function (b) {
- if (b.el === activeEl) b.el.removeAttribute('hidden');
- else b.el.setAttribute('hidden', '');
- });
- return activeEl;
- }
- /** Toggle `stm-class.{name}` classes from their predicate expressions. */
- function handleClass(el, scope) {
- var attrs = el.attributes;
- for (var i = 0; i < attrs.length; i++) {
- var attr = attrs[i];
- if (attr.name.indexOf('stm-class.') === 0) {
- var cls = attr.name.slice('stm-class.'.length);
- if (cls && !!evalExpr(attr.value, scope)) el.classList.add(cls);
- else el.classList.remove(cls);
- }
- }
- }
- /**
- * Bind `stm-attribute.{name}`: a boolean result toggles the attribute, any
- * other defined value sets it, and `undefined` removes it.
- *
- * For booleans, prefer the element's IDL property when one exists (e.g.
- * `checked`, `disabled`, `hidden`) — setting the content attribute is
- * unreliable for these once the control is "dirty".
- */
- function handleAttribute(el, scope) {
- var attrs = el.attributes;
- for (var i = 0; i < attrs.length; i++) {
- var attr = attrs[i];
- if (attr.name.indexOf('stm-attribute.') === 0) {
- var name = attr.name.slice('stm-attribute.'.length);
- if (!name) continue;
- var value = evalExpr(attr.value, scope);
- if (value === undefined) {
- el.removeAttribute(name);
- } else if (typeof value === 'boolean') {
- if (name in el && typeof el[name] === 'boolean') el[name] = value;
- else if (value) el.setAttribute(name, '');
- else el.removeAttribute(name);
- } else {
- el.setAttribute(name, value === null ? '' : String(value));
- }
- }
- }
- }
- /**
- * Apply `stm-disabled`: when the predicate is truthy, disable the element and
- * its descendant form controls; otherwise enable them.
- */
- function handleDisabled(el, scope) {
- if (!el.hasAttribute('stm-disabled')) return;
- setDisabledCascade(el, !!evalExpr(el.getAttribute('stm-disabled'), scope));
- }
- /** Set the `disabled` attribute on an element and its descendant controls. */
- function setDisabledCascade(el, on) {
- var nodes = [el].concat(Array.prototype.slice.call(
- el.querySelectorAll('button,input,select,textarea,fieldset')));
- nodes.forEach(function (n) {
- if (on) n.setAttribute('disabled', ''); else n.removeAttribute('disabled');
- });
- }
- // ---------------------------------------------------------------------------
- // Markdown rendering (CommonMark 0.31.2)
- // ---------------------------------------------------------------------------
- //
- // A two-pass CommonMark engine: block structure first (paragraphs, ATX and
- // setext headings, thematic breaks, indented and fenced code blocks, block
- // quotes with lazy continuation, lists with tight/loose rendering and link
- // reference definitions), then inline parsing inside the leaf blocks
- // (delimiter-run emphasis, links and images, code spans, autolinks,
- // backslash escapes, entity references, hard/soft line breaks).
- //
- // SECURITY: the markdown source is untrusted text. Raw HTML is never passed
- // through — inline HTML and HTML-block-looking constructs render as escaped
- // text, which intentionally diverges from the CommonMark HTML output for
- // those examples. Link and image destinations are scheme-filtered by
- // safeMarkdownUrl() and everything is escaped before it reaches the output.
- function safeMarkdownUrl(url) {
- var u = url.trim();
- var m = u.match(/^([a-zA-Z][a-zA-Z0-9+.-]*):/);
- if (!m) return u;
- var scheme = m[1].toLowerCase();
- if (scheme === 'http' || scheme === 'https' || scheme === 'mailto' || scheme === 'ftp') return u;
- return '#';
- }
- /**
- * Packed HTML5 named-entity table (WHATWG `entities.json`, 2125 entries).
- * Each record is "name cp[,cp...]" on one line; multi-codepoint entities
- * carry comma-separated codepoints. Line breaks are escaped so the whole
- * table stays one string literal. Parsed lazily into a name -> text map the
- * first time an entity reference is looked up.
- */
- var MD_ENTITIES_PACKED = ''
- + "AElig 198\nAMP 38\nAacute 193\nAbreve 258\nAcirc 194\nAcy 1040\nAfr 120068\nAgrave 192\n"
- + "Alpha 913\nAmacr 256\nAnd 10835\nAogon 260\nAopf 120120\nApplyFunction 8289\nAring 197\n"
- + "Ascr 119964\nAssign 8788\nAtilde 195\nAuml 196\nBackslash 8726\nBarv 10983\nBarwed 8966\n"
- + "Bcy 1041\nBecause 8757\nBernoullis 8492\nBeta 914\nBfr 120069\nBopf 120121\nBreve 728\n"
- + "Bscr 8492\nBumpeq 8782\nCHcy 1063\nCOPY 169\nCacute 262\nCap 8914\n"
- + "CapitalDifferentialD 8517\nCayleys 8493\nCcaron 268\nCcedil 199\nCcirc 264\nCconint 8752\n"
- + "Cdot 266\nCedilla 184\nCenterDot 183\nCfr 8493\nChi 935\nCircleDot 8857\n"
- + "CircleMinus 8854\nCirclePlus 8853\nCircleTimes 8855\nClockwiseContourIntegral 8754\n"
- + "CloseCurlyDoubleQuote 8221\nCloseCurlyQuote 8217\nColon 8759\nColone 10868\n"
- + "Congruent 8801\nConint 8751\nContourIntegral 8750\nCopf 8450\nCoproduct 8720\n"
- + "CounterClockwiseContourIntegral 8755\nCross 10799\nCscr 119966\nCup 8915\nCupCap 8781\n"
- + "DD 8517\nDDotrahd 10513\nDJcy 1026\nDScy 1029\nDZcy 1039\nDagger 8225\nDarr 8609\n"
- + "Dashv 10980\nDcaron 270\nDcy 1044\nDel 8711\nDelta 916\nDfr 120071\nDiacriticalAcute 180\n"
- + "DiacriticalDot 729\nDiacriticalDoubleAcute 733\nDiacriticalGrave 96\n"
- + "DiacriticalTilde 732\nDiamond 8900\nDifferentialD 8518\nDopf 120123\nDot 168\n"
- + "DotDot 8412\nDotEqual 8784\nDoubleContourIntegral 8751\nDoubleDot 168\n"
- + "DoubleDownArrow 8659\nDoubleLeftArrow 8656\nDoubleLeftRightArrow 8660\n"
- + "DoubleLeftTee 10980\nDoubleLongLeftArrow 10232\nDoubleLongLeftRightArrow 10234\n"
- + "DoubleLongRightArrow 10233\nDoubleRightArrow 8658\nDoubleRightTee 8872\n"
- + "DoubleUpArrow 8657\nDoubleUpDownArrow 8661\nDoubleVerticalBar 8741\nDownArrow 8595\n"
- + "DownArrowBar 10515\nDownArrowUpArrow 8693\nDownBreve 785\nDownLeftRightVector 10576\n"
- + "DownLeftTeeVector 10590\nDownLeftVector 8637\nDownLeftVectorBar 10582\n"
- + "DownRightTeeVector 10591\nDownRightVector 8641\nDownRightVectorBar 10583\nDownTee 8868\n"
- + "DownTeeArrow 8615\nDownarrow 8659\nDscr 119967\nDstrok 272\nENG 330\nETH 208\nEacute 201\n"
- + "Ecaron 282\nEcirc 202\nEcy 1069\nEdot 278\nEfr 120072\nEgrave 200\nElement 8712\n"
- + "Emacr 274\nEmptySmallSquare 9723\nEmptyVerySmallSquare 9643\nEogon 280\nEopf 120124\n"
- + "Epsilon 917\nEqual 10869\nEqualTilde 8770\nEquilibrium 8652\nEscr 8496\nEsim 10867\n"
- + "Eta 919\nEuml 203\nExists 8707\nExponentialE 8519\nFcy 1060\nFfr 120073\n"
- + "FilledSmallSquare 9724\nFilledVerySmallSquare 9642\nFopf 120125\nForAll 8704\n"
- + "Fouriertrf 8497\nFscr 8497\nGJcy 1027\nGT 62\nGamma 915\nGammad 988\nGbreve 286\n"
- + "Gcedil 290\nGcirc 284\nGcy 1043\nGdot 288\nGfr 120074\nGg 8921\nGopf 120126\n"
- + "GreaterEqual 8805\nGreaterEqualLess 8923\nGreaterFullEqual 8807\nGreaterGreater 10914\n"
- + "GreaterLess 8823\nGreaterSlantEqual 10878\nGreaterTilde 8819\nGscr 119970\nGt 8811\n"
- + "HARDcy 1066\nHacek 711\nHat 94\nHcirc 292\nHfr 8460\nHilbertSpace 8459\nHopf 8461\n"
- + "HorizontalLine 9472\nHscr 8459\nHstrok 294\nHumpDownHump 8782\nHumpEqual 8783\nIEcy 1045\n"
- + "IJlig 306\nIOcy 1025\nIacute 205\nIcirc 206\nIcy 1048\nIdot 304\nIfr 8465\nIgrave 204\n"
- + "Im 8465\nImacr 298\nImaginaryI 8520\nImplies 8658\nInt 8748\nIntegral 8747\n"
- + "Intersection 8898\nInvisibleComma 8291\nInvisibleTimes 8290\nIogon 302\nIopf 120128\n"
- + "Iota 921\nIscr 8464\nItilde 296\nIukcy 1030\nIuml 207\nJcirc 308\nJcy 1049\nJfr 120077\n"
- + "Jopf 120129\nJscr 119973\nJsercy 1032\nJukcy 1028\nKHcy 1061\nKJcy 1036\nKappa 922\n"
- + "Kcedil 310\nKcy 1050\nKfr 120078\nKopf 120130\nKscr 119974\nLJcy 1033\nLT 60\nLacute 313\n"
- + "Lambda 923\nLang 10218\nLaplacetrf 8466\nLarr 8606\nLcaron 317\nLcedil 315\nLcy 1051\n"
- + "LeftAngleBracket 10216\nLeftArrow 8592\nLeftArrowBar 8676\nLeftArrowRightArrow 8646\n"
- + "LeftCeiling 8968\nLeftDoubleBracket 10214\nLeftDownTeeVector 10593\nLeftDownVector 8643\n"
- + "LeftDownVectorBar 10585\nLeftFloor 8970\nLeftRightArrow 8596\nLeftRightVector 10574\n"
- + "LeftTee 8867\nLeftTeeArrow 8612\nLeftTeeVector 10586\nLeftTriangle 8882\n"
- + "LeftTriangleBar 10703\nLeftTriangleEqual 8884\nLeftUpDownVector 10577\n"
- + "LeftUpTeeVector 10592\nLeftUpVector 8639\nLeftUpVectorBar 10584\nLeftVector 8636\n"
- + "LeftVectorBar 10578\nLeftarrow 8656\nLeftrightarrow 8660\nLessEqualGreater 8922\n"
- + "LessFullEqual 8806\nLessGreater 8822\nLessLess 10913\nLessSlantEqual 10877\n"
- + "LessTilde 8818\nLfr 120079\nLl 8920\nLleftarrow 8666\nLmidot 319\nLongLeftArrow 10229\n"
- + "LongLeftRightArrow 10231\nLongRightArrow 10230\nLongleftarrow 10232\n"
- + "Longleftrightarrow 10234\nLongrightarrow 10233\nLopf 120131\nLowerLeftArrow 8601\n"
- + "LowerRightArrow 8600\nLscr 8466\nLsh 8624\nLstrok 321\nLt 8810\nMap 10501\nMcy 1052\n"
- + "MediumSpace 8287\nMellintrf 8499\nMfr 120080\nMinusPlus 8723\nMopf 120132\nMscr 8499\n"
- + "Mu 924\nNJcy 1034\nNacute 323\nNcaron 327\nNcedil 325\nNcy 1053\n"
- + "NegativeMediumSpace 8203\nNegativeThickSpace 8203\nNegativeThinSpace 8203\n"
- + "NegativeVeryThinSpace 8203\nNestedGreaterGreater 8811\nNestedLessLess 8810\nNewLine 10\n"
- + "Nfr 120081\nNoBreak 8288\nNonBreakingSpace 160\nNopf 8469\nNot 10988\nNotCongruent 8802\n"
- + "NotCupCap 8813\nNotDoubleVerticalBar 8742\nNotElement 8713\nNotEqual 8800\n"
- + "NotEqualTilde 8770,824\nNotExists 8708\nNotGreater 8815\nNotGreaterEqual 8817\n"
- + "NotGreaterFullEqual 8807,824\nNotGreaterGreater 8811,824\nNotGreaterLess 8825\n"
- + "NotGreaterSlantEqual 10878,824\nNotGreaterTilde 8821\nNotHumpDownHump 8782,824\n"
- + "NotHumpEqual 8783,824\nNotLeftTriangle 8938\nNotLeftTriangleBar 10703,824\n"
- + "NotLeftTriangleEqual 8940\nNotLess 8814\nNotLessEqual 8816\nNotLessGreater 8824\n"
- + "NotLessLess 8810,824\nNotLessSlantEqual 10877,824\nNotLessTilde 8820\n"
- + "NotNestedGreaterGreater 10914,824\nNotNestedLessLess 10913,824\nNotPrecedes 8832\n"
- + "NotPrecedesEqual 10927,824\nNotPrecedesSlantEqual 8928\nNotReverseElement 8716\n"
- + "NotRightTriangle 8939\nNotRightTriangleBar 10704,824\nNotRightTriangleEqual 8941\n"
- + "NotSquareSubset 8847,824\nNotSquareSubsetEqual 8930\nNotSquareSuperset 8848,824\n"
- + "NotSquareSupersetEqual 8931\nNotSubset 8834,8402\nNotSubsetEqual 8840\nNotSucceeds 8833\n"
- + "NotSucceedsEqual 10928,824\nNotSucceedsSlantEqual 8929\nNotSucceedsTilde 8831,824\n"
- + "NotSuperset 8835,8402\nNotSupersetEqual 8841\nNotTilde 8769\nNotTildeEqual 8772\n"
- + "NotTildeFullEqual 8775\nNotTildeTilde 8777\nNotVerticalBar 8740\nNscr 119977\nNtilde 209\n"
- + "Nu 925\nOElig 338\nOacute 211\nOcirc 212\nOcy 1054\nOdblac 336\nOfr 120082\nOgrave 210\n"
- + "Omacr 332\nOmega 937\nOmicron 927\nOopf 120134\nOpenCurlyDoubleQuote 8220\n"
- + "OpenCurlyQuote 8216\nOr 10836\nOscr 119978\nOslash 216\nOtilde 213\nOtimes 10807\n"
- + "Ouml 214\nOverBar 8254\nOverBrace 9182\nOverBracket 9140\nOverParenthesis 9180\n"
- + "PartialD 8706\nPcy 1055\nPfr 120083\nPhi 934\nPi 928\nPlusMinus 177\nPoincareplane 8460\n"
- + "Popf 8473\nPr 10939\nPrecedes 8826\nPrecedesEqual 10927\nPrecedesSlantEqual 8828\n"
- + "PrecedesTilde 8830\nPrime 8243\nProduct 8719\nProportion 8759\nProportional 8733\n"
- + "Pscr 119979\nPsi 936\nQUOT 34\nQfr 120084\nQopf 8474\nQscr 119980\nRBarr 10512\nREG 174\n"
- + "Racute 340\nRang 10219\nRarr 8608\nRarrtl 10518\nRcaron 344\nRcedil 342\nRcy 1056\n"
- + "Re 8476\nReverseElement 8715\nReverseEquilibrium 8651\nReverseUpEquilibrium 10607\n"
- + "Rfr 8476\nRho 929\nRightAngleBracket 10217\nRightArrow 8594\nRightArrowBar 8677\n"
- + "RightArrowLeftArrow 8644\nRightCeiling 8969\nRightDoubleBracket 10215\n"
- + "RightDownTeeVector 10589\nRightDownVector 8642\nRightDownVectorBar 10581\n"
- + "RightFloor 8971\nRightTee 8866\nRightTeeArrow 8614\nRightTeeVector 10587\n"
- + "RightTriangle 8883\nRightTriangleBar 10704\nRightTriangleEqual 8885\n"
- + "RightUpDownVector 10575\nRightUpTeeVector 10588\nRightUpVector 8638\n"
- + "RightUpVectorBar 10580\nRightVector 8640\nRightVectorBar 10579\nRightarrow 8658\n"
- + "Ropf 8477\nRoundImplies 10608\nRrightarrow 8667\nRscr 8475\nRsh 8625\nRuleDelayed 10740\n"
- + "SHCHcy 1065\nSHcy 1064\nSOFTcy 1068\nSacute 346\nSc 10940\nScaron 352\nScedil 350\n"
- + "Scirc 348\nScy 1057\nSfr 120086\nShortDownArrow 8595\nShortLeftArrow 8592\n"
- + "ShortRightArrow 8594\nShortUpArrow 8593\nSigma 931\nSmallCircle 8728\nSopf 120138\n"
- + "Sqrt 8730\nSquare 9633\nSquareIntersection 8851\nSquareSubset 8847\n"
- + "SquareSubsetEqual 8849\nSquareSuperset 8848\nSquareSupersetEqual 8850\nSquareUnion 8852\n"
- + "Sscr 119982\nStar 8902\nSub 8912\nSubset 8912\nSubsetEqual 8838\nSucceeds 8827\n"
- + "SucceedsEqual 10928\nSucceedsSlantEqual 8829\nSucceedsTilde 8831\nSuchThat 8715\n"
- + "Sum 8721\nSup 8913\nSuperset 8835\nSupersetEqual 8839\nSupset 8913\nTHORN 222\n"
- + "TRADE 8482\nTSHcy 1035\nTScy 1062\nTab 9\nTau 932\nTcaron 356\nTcedil 354\nTcy 1058\n"
- + "Tfr 120087\nTherefore 8756\nTheta 920\nThickSpace 8287,8202\nThinSpace 8201\nTilde 8764\n"
- + "TildeEqual 8771\nTildeFullEqual 8773\nTildeTilde 8776\nTopf 120139\nTripleDot 8411\n"
- + "Tscr 119983\nTstrok 358\nUacute 218\nUarr 8607\nUarrocir 10569\nUbrcy 1038\nUbreve 364\n"
- + "Ucirc 219\nUcy 1059\nUdblac 368\nUfr 120088\nUgrave 217\nUmacr 362\nUnderBar 95\n"
- + "UnderBrace 9183\nUnderBracket 9141\nUnderParenthesis 9181\nUnion 8899\nUnionPlus 8846\n"
- + "Uogon 370\nUopf 120140\nUpArrow 8593\nUpArrowBar 10514\nUpArrowDownArrow 8645\n"
- + "UpDownArrow 8597\nUpEquilibrium 10606\nUpTee 8869\nUpTeeArrow 8613\nUparrow 8657\n"
- + "Updownarrow 8661\nUpperLeftArrow 8598\nUpperRightArrow 8599\nUpsi 978\nUpsilon 933\n"
- + "Uring 366\nUscr 119984\nUtilde 360\nUuml 220\nVDash 8875\nVbar 10987\nVcy 1042\n"
- + "Vdash 8873\nVdashl 10982\nVee 8897\nVerbar 8214\nVert 8214\nVerticalBar 8739\n"
- + "VerticalLine 124\nVerticalSeparator 10072\nVerticalTilde 8768\nVeryThinSpace 8202\n"
- + "Vfr 120089\nVopf 120141\nVscr 119985\nVvdash 8874\nWcirc 372\nWedge 8896\nWfr 120090\n"
- + "Wopf 120142\nWscr 119986\nXfr 120091\nXi 926\nXopf 120143\nXscr 119987\nYAcy 1071\n"
- + "YIcy 1031\nYUcy 1070\nYacute 221\nYcirc 374\nYcy 1067\nYfr 120092\nYopf 120144\n"
- + "Yscr 119988\nYuml 376\nZHcy 1046\nZacute 377\nZcaron 381\nZcy 1047\nZdot 379\n"
- + "ZeroWidthSpace 8203\nZeta 918\nZfr 8488\nZopf 8484\nZscr 119989\naacute 225\nabreve 259\n"
- + "ac 8766\nacE 8766,819\nacd 8767\nacirc 226\nacute 180\nacy 1072\naelig 230\naf 8289\n"
- + "afr 120094\nagrave 224\nalefsym 8501\naleph 8501\nalpha 945\namacr 257\namalg 10815\n"
- + "amp 38\nand 8743\nandand 10837\nandd 10844\nandslope 10840\nandv 10842\nang 8736\n"
- + "ange 10660\nangle 8736\nangmsd 8737\nangmsdaa 10664\nangmsdab 10665\nangmsdac 10666\n"
- + "angmsdad 10667\nangmsdae 10668\nangmsdaf 10669\nangmsdag 10670\nangmsdah 10671\n"
- + "angrt 8735\nangrtvb 8894\nangrtvbd 10653\nangsph 8738\nangst 197\nangzarr 9084\n"
- + "aogon 261\naopf 120146\nap 8776\napE 10864\napacir 10863\nape 8778\napid 8779\napos 39\n"
- + "approx 8776\napproxeq 8778\naring 229\nascr 119990\nast 42\nasymp 8776\nasympeq 8781\n"
- + "atilde 227\nauml 228\nawconint 8755\nawint 10769\nbNot 10989\nbackcong 8780\n"
- + "backepsilon 1014\nbackprime 8245\nbacksim 8765\nbacksimeq 8909\nbarvee 8893\nbarwed 8965\n"
- + "barwedge 8965\nbbrk 9141\nbbrktbrk 9142\nbcong 8780\nbcy 1073\nbdquo 8222\nbecaus 8757\n"
- + "because 8757\nbemptyv 10672\nbepsi 1014\nbernou 8492\nbeta 946\nbeth 8502\nbetween 8812\n"
- + "bfr 120095\nbigcap 8898\nbigcirc 9711\nbigcup 8899\nbigodot 10752\nbigoplus 10753\n"
- + "bigotimes 10754\nbigsqcup 10758\nbigstar 9733\nbigtriangledown 9661\nbigtriangleup 9651\n"
- + "biguplus 10756\nbigvee 8897\nbigwedge 8896\nbkarow 10509\nblacklozenge 10731\n"
- + "blacksquare 9642\nblacktriangle 9652\nblacktriangledown 9662\nblacktriangleleft 9666\n"
- + "blacktriangleright 9656\nblank 9251\nblk12 9618\nblk14 9617\nblk34 9619\nblock 9608\n"
- + "bne 61,8421\nbnequiv 8801,8421\nbnot 8976\nbopf 120147\nbot 8869\nbottom 8869\n"
- + "bowtie 8904\nboxDL 9559\nboxDR 9556\nboxDl 9558\nboxDr 9555\nboxH 9552\nboxHD 9574\n"
- + "boxHU 9577\nboxHd 9572\nboxHu 9575\nboxUL 9565\nboxUR 9562\nboxUl 9564\nboxUr 9561\n"
- + "boxV 9553\nboxVH 9580\nboxVL 9571\nboxVR 9568\nboxVh 9579\nboxVl 9570\nboxVr 9567\n"
- + "boxbox 10697\nboxdL 9557\nboxdR 9554\nboxdl 9488\nboxdr 9484\nboxh 9472\nboxhD 9573\n"
- + "boxhU 9576\nboxhd 9516\nboxhu 9524\nboxminus 8863\nboxplus 8862\nboxtimes 8864\n"
- + "boxuL 9563\nboxuR 9560\nboxul 9496\nboxur 9492\nboxv 9474\nboxvH 9578\nboxvL 9569\n"
- + "boxvR 9566\nboxvh 9532\nboxvl 9508\nboxvr 9500\nbprime 8245\nbreve 728\nbrvbar 166\n"
- + "bscr 119991\nbsemi 8271\nbsim 8765\nbsime 8909\nbsol 92\nbsolb 10693\nbsolhsub 10184\n"
- + "bull 8226\nbullet 8226\nbump 8782\nbumpE 10926\nbumpe 8783\nbumpeq 8783\ncacute 263\n"
- + "cap 8745\ncapand 10820\ncapbrcup 10825\ncapcap 10827\ncapcup 10823\ncapdot 10816\n"
- + "caps 8745,65024\ncaret 8257\ncaron 711\nccaps 10829\nccaron 269\nccedil 231\nccirc 265\n"
- + "ccups 10828\nccupssm 10832\ncdot 267\ncedil 184\ncemptyv 10674\ncent 162\ncenterdot 183\n"
- + "cfr 120096\nchcy 1095\ncheck 10003\ncheckmark 10003\nchi 967\ncir 9675\ncirE 10691\n"
- + "circ 710\ncirceq 8791\ncirclearrowleft 8634\ncirclearrowright 8635\ncircledR 174\n"
- + "circledS 9416\ncircledast 8859\ncircledcirc 8858\ncircleddash 8861\ncire 8791\n"
- + "cirfnint 10768\ncirmid 10991\ncirscir 10690\nclubs 9827\nclubsuit 9827\ncolon 58\n"
- + "colone 8788\ncoloneq 8788\ncomma 44\ncommat 64\ncomp 8705\ncompfn 8728\ncomplement 8705\n"
- + "complexes 8450\ncong 8773\ncongdot 10861\nconint 8750\ncopf 120148\ncoprod 8720\n"
- + "copy 169\ncopysr 8471\ncrarr 8629\ncross 10007\ncscr 119992\ncsub 10959\ncsube 10961\n"
- + "csup 10960\ncsupe 10962\nctdot 8943\ncudarrl 10552\ncudarrr 10549\ncuepr 8926\n"
- + "cuesc 8927\ncularr 8630\ncularrp 10557\ncup 8746\ncupbrcap 10824\ncupcap 10822\n"
- + "cupcup 10826\ncupdot 8845\ncupor 10821\ncups 8746,65024\ncurarr 8631\ncurarrm 10556\n"
- + "curlyeqprec 8926\ncurlyeqsucc 8927\ncurlyvee 8910\ncurlywedge 8911\ncurren 164\n"
- + "curvearrowleft 8630\ncurvearrowright 8631\ncuvee 8910\ncuwed 8911\ncwconint 8754\n"
- + "cwint 8753\ncylcty 9005\ndArr 8659\ndHar 10597\ndagger 8224\ndaleth 8504\ndarr 8595\n"
- + "dash 8208\ndashv 8867\ndbkarow 10511\ndblac 733\ndcaron 271\ndcy 1076\ndd 8518\n"
- + "ddagger 8225\nddarr 8650\nddotseq 10871\ndeg 176\ndelta 948\ndemptyv 10673\ndfisht 10623\n"
- + "dfr 120097\ndharl 8643\ndharr 8642\ndiam 8900\ndiamond 8900\ndiamondsuit 9830\n"
- + "diams 9830\ndie 168\ndigamma 989\ndisin 8946\ndiv 247\ndivide 247\ndivideontimes 8903\n"
- + "divonx 8903\ndjcy 1106\ndlcorn 8990\ndlcrop 8973\ndollar 36\ndopf 120149\ndot 729\n"
- + "doteq 8784\ndoteqdot 8785\ndotminus 8760\ndotplus 8724\ndotsquare 8865\n"
- + "doublebarwedge 8966\ndownarrow 8595\ndowndownarrows 8650\ndownharpoonleft 8643\n"
- + "downharpoonright 8642\ndrbkarow 10512\ndrcorn 8991\ndrcrop 8972\ndscr 119993\ndscy 1109\n"
- + "dsol 10742\ndstrok 273\ndtdot 8945\ndtri 9663\ndtrif 9662\nduarr 8693\nduhar 10607\n"
- + "dwangle 10662\ndzcy 1119\ndzigrarr 10239\neDDot 10871\neDot 8785\neacute 233\n"
- + "easter 10862\necaron 283\necir 8790\necirc 234\necolon 8789\necy 1101\nedot 279\nee 8519\n"
- + "efDot 8786\nefr 120098\neg 10906\negrave 232\negs 10902\negsdot 10904\nel 10905\n"
- + "elinters 9191\nell 8467\nels 10901\nelsdot 10903\nemacr 275\nempty 8709\nemptyset 8709\n"
- + "emptyv 8709\nemsp 8195\nemsp13 8196\nemsp14 8197\neng 331\nensp 8194\neogon 281\n"
- + "eopf 120150\nepar 8917\neparsl 10723\neplus 10865\nepsi 949\nepsilon 949\nepsiv 1013\n"
- + "eqcirc 8790\neqcolon 8789\neqsim 8770\neqslantgtr 10902\neqslantless 10901\nequals 61\n"
- + "equest 8799\nequiv 8801\nequivDD 10872\neqvparsl 10725\nerDot 8787\nerarr 10609\n"
- + "escr 8495\nesdot 8784\nesim 8770\neta 951\neth 240\neuml 235\neuro 8364\nexcl 33\n"
- + "exist 8707\nexpectation 8496\nexponentiale 8519\nfallingdotseq 8786\nfcy 1092\n"
- + "female 9792\nffilig 64259\nfflig 64256\nffllig 64260\nffr 120099\nfilig 64257\n"
- + "fjlig 102,106\nflat 9837\nfllig 64258\nfltns 9649\nfnof 402\nfopf 120151\nforall 8704\n"
- + "fork 8916\nforkv 10969\nfpartint 10765\nfrac12 189\nfrac13 8531\nfrac14 188\nfrac15 8533\n"
- + "frac16 8537\nfrac18 8539\nfrac23 8532\nfrac25 8534\nfrac34 190\nfrac35 8535\nfrac38 8540\n"
- + "frac45 8536\nfrac56 8538\nfrac58 8541\nfrac78 8542\nfrasl 8260\nfrown 8994\nfscr 119995\n"
- + "gE 8807\ngEl 10892\ngacute 501\ngamma 947\ngammad 989\ngap 10886\ngbreve 287\ngcirc 285\n"
- + "gcy 1075\ngdot 289\nge 8805\ngel 8923\ngeq 8805\ngeqq 8807\ngeqslant 10878\nges 10878\n"
- + "gescc 10921\ngesdot 10880\ngesdoto 10882\ngesdotol 10884\ngesl 8923,65024\ngesles 10900\n"
- + "gfr 120100\ngg 8811\nggg 8921\ngimel 8503\ngjcy 1107\ngl 8823\nglE 10898\ngla 10917\n"
- + "glj 10916\ngnE 8809\ngnap 10890\ngnapprox 10890\ngne 10888\ngneq 10888\ngneqq 8809\n"
- + "gnsim 8935\ngopf 120152\ngrave 96\ngscr 8458\ngsim 8819\ngsime 10894\ngsiml 10896\ngt 62\n"
- + "gtcc 10919\ngtcir 10874\ngtdot 8919\ngtlPar 10645\ngtquest 10876\ngtrapprox 10886\n"
- + "gtrarr 10616\ngtrdot 8919\ngtreqless 8923\ngtreqqless 10892\ngtrless 8823\ngtrsim 8819\n"
- + "gvertneqq 8809,65024\ngvnE 8809,65024\nhArr 8660\nhairsp 8202\nhalf 189\nhamilt 8459\n"
- + "hardcy 1098\nharr 8596\nharrcir 10568\nharrw 8621\nhbar 8463\nhcirc 293\nhearts 9829\n"
- + "heartsuit 9829\nhellip 8230\nhercon 8889\nhfr 120101\nhksearow 10533\nhkswarow 10534\n"
- + "hoarr 8703\nhomtht 8763\nhookleftarrow 8617\nhookrightarrow 8618\nhopf 120153\n"
- + "horbar 8213\nhscr 119997\nhslash 8463\nhstrok 295\nhybull 8259\nhyphen 8208\niacute 237\n"
- + "ic 8291\nicirc 238\nicy 1080\niecy 1077\niexcl 161\niff 8660\nifr 120102\nigrave 236\n"
- + "ii 8520\niiiint 10764\niiint 8749\niinfin 10716\niiota 8489\nijlig 307\nimacr 299\n"
- + "image 8465\nimagline 8464\nimagpart 8465\nimath 305\nimof 8887\nimped 437\nin 8712\n"
- + "incare 8453\ninfin 8734\ninfintie 10717\ninodot 305\nint 8747\nintcal 8890\n"
- + "integers 8484\nintercal 8890\nintlarhk 10775\nintprod 10812\niocy 1105\niogon 303\n"
- + "iopf 120154\niota 953\niprod 10812\niquest 191\niscr 119998\nisin 8712\nisinE 8953\n"
- + "isindot 8949\nisins 8948\nisinsv 8947\nisinv 8712\nit 8290\nitilde 297\niukcy 1110\n"
- + "iuml 239\njcirc 309\njcy 1081\njfr 120103\njmath 567\njopf 120155\njscr 119999\n"
- + "jsercy 1112\njukcy 1108\nkappa 954\nkappav 1008\nkcedil 311\nkcy 1082\nkfr 120104\n"
- + "kgreen 312\nkhcy 1093\nkjcy 1116\nkopf 120156\nkscr 120000\nlAarr 8666\nlArr 8656\n"
- + "lAtail 10523\nlBarr 10510\nlE 8806\nlEg 10891\nlHar 10594\nlacute 314\nlaemptyv 10676\n"
- + "lagran 8466\nlambda 955\nlang 10216\nlangd 10641\nlangle 10216\nlap 10885\nlaquo 171\n"
- + "larr 8592\nlarrb 8676\nlarrbfs 10527\nlarrfs 10525\nlarrhk 8617\nlarrlp 8619\n"
- + "larrpl 10553\nlarrsim 10611\nlarrtl 8610\nlat 10923\nlatail 10521\nlate 10925\n"
- + "lates 10925,65024\nlbarr 10508\nlbbrk 10098\nlbrace 123\nlbrack 91\nlbrke 10635\n"
- + "lbrksld 10639\nlbrkslu 10637\nlcaron 318\nlcedil 316\nlceil 8968\nlcub 123\nlcy 1083\n"
- + "ldca 10550\nldquo 8220\nldquor 8222\nldrdhar 10599\nldrushar 10571\nldsh 8626\nle 8804\n"
- + "leftarrow 8592\nleftarrowtail 8610\nleftharpoondown 8637\nleftharpoonup 8636\n"
- + "leftleftarrows 8647\nleftrightarrow 8596\nleftrightarrows 8646\nleftrightharpoons 8651\n"
- + "leftrightsquigarrow 8621\nleftthreetimes 8907\nleg 8922\nleq 8804\nleqq 8806\n"
- + "leqslant 10877\nles 10877\nlescc 10920\nlesdot 10879\nlesdoto 10881\nlesdotor 10883\n"
- + "lesg 8922,65024\nlesges 10899\nlessapprox 10885\nlessdot 8918\nlesseqgtr 8922\n"
- + "lesseqqgtr 10891\nlessgtr 8822\nlesssim 8818\nlfisht 10620\nlfloor 8970\nlfr 120105\n"
- + "lg 8822\nlgE 10897\nlhard 8637\nlharu 8636\nlharul 10602\nlhblk 9604\nljcy 1113\nll 8810\n"
- + "llarr 8647\nllcorner 8990\nllhard 10603\nlltri 9722\nlmidot 320\nlmoust 9136\n"
- + "lmoustache 9136\nlnE 8808\nlnap 10889\nlnapprox 10889\nlne 10887\nlneq 10887\nlneqq 8808\n"
- + "lnsim 8934\nloang 10220\nloarr 8701\nlobrk 10214\nlongleftarrow 10229\n"
- + "longleftrightarrow 10231\nlongmapsto 10236\nlongrightarrow 10230\nlooparrowleft 8619\n"
- + "looparrowright 8620\nlopar 10629\nlopf 120157\nloplus 10797\nlotimes 10804\nlowast 8727\n"
- + "lowbar 95\nloz 9674\nlozenge 9674\nlozf 10731\nlpar 40\nlparlt 10643\nlrarr 8646\n"
- + "lrcorner 8991\nlrhar 8651\nlrhard 10605\nlrm 8206\nlrtri 8895\nlsaquo 8249\nlscr 120001\n"
- + "lsh 8624\nlsim 8818\nlsime 10893\nlsimg 10895\nlsqb 91\nlsquo 8216\nlsquor 8218\n"
- + "lstrok 322\nlt 60\nltcc 10918\nltcir 10873\nltdot 8918\nlthree 8907\nltimes 8905\n"
- + "ltlarr 10614\nltquest 10875\nltrPar 10646\nltri 9667\nltrie 8884\nltrif 9666\n"
- + "lurdshar 10570\nluruhar 10598\nlvertneqq 8808,65024\nlvnE 8808,65024\nmDDot 8762\n"
- + "macr 175\nmale 9794\nmalt 10016\nmaltese 10016\nmap 8614\nmapsto 8614\nmapstodown 8615\n"
- + "mapstoleft 8612\nmapstoup 8613\nmarker 9646\nmcomma 10793\nmcy 1084\nmdash 8212\n"
- + "measuredangle 8737\nmfr 120106\nmho 8487\nmicro 181\nmid 8739\nmidast 42\nmidcir 10992\n"
- + "middot 183\nminus 8722\nminusb 8863\nminusd 8760\nminusdu 10794\nmlcp 10971\nmldr 8230\n"
- + "mnplus 8723\nmodels 8871\nmopf 120158\nmp 8723\nmscr 120002\nmstpos 8766\nmu 956\n"
- + "multimap 8888\nmumap 8888\nnGg 8921,824\nnGt 8811,8402\nnGtv 8811,824\nnLeftarrow 8653\n"
- + "nLeftrightarrow 8654\nnLl 8920,824\nnLt 8810,8402\nnLtv 8810,824\nnRightarrow 8655\n"
- + "nVDash 8879\nnVdash 8878\nnabla 8711\nnacute 324\nnang 8736,8402\nnap 8777\n"
- + "napE 10864,824\nnapid 8779,824\nnapos 329\nnapprox 8777\nnatur 9838\nnatural 9838\n"
- + "naturals 8469\nnbsp 160\nnbump 8782,824\nnbumpe 8783,824\nncap 10819\nncaron 328\n"
- + "ncedil 326\nncong 8775\nncongdot 10861,824\nncup 10818\nncy 1085\nndash 8211\nne 8800\n"
- + "neArr 8663\nnearhk 10532\nnearr 8599\nnearrow 8599\nnedot 8784,824\nnequiv 8802\n"
- + "nesear 10536\nnesim 8770,824\nnexist 8708\nnexists 8708\nnfr 120107\nngE 8807,824\n"
- + "nge 8817\nngeq 8817\nngeqq 8807,824\nngeqslant 10878,824\nnges 10878,824\nngsim 8821\n"
- + "ngt 8815\nngtr 8815\nnhArr 8654\nnharr 8622\nnhpar 10994\nni 8715\nnis 8956\nnisd 8954\n"
- + "niv 8715\nnjcy 1114\nnlArr 8653\nnlE 8806,824\nnlarr 8602\nnldr 8229\nnle 8816\n"
- + "nleftarrow 8602\nnleftrightarrow 8622\nnleq 8816\nnleqq 8806,824\nnleqslant 10877,824\n"
- + "nles 10877,824\nnless 8814\nnlsim 8820\nnlt 8814\nnltri 8938\nnltrie 8940\nnmid 8740\n"
- + "nopf 120159\nnot 172\nnotin 8713\nnotinE 8953,824\nnotindot 8949,824\nnotinva 8713\n"
- + "notinvb 8951\nnotinvc 8950\nnotni 8716\nnotniva 8716\nnotnivb 8958\nnotnivc 8957\n"
- + "npar 8742\nnparallel 8742\nnparsl 11005,8421\nnpart 8706,824\nnpolint 10772\nnpr 8832\n"
- + "nprcue 8928\nnpre 10927,824\nnprec 8832\nnpreceq 10927,824\nnrArr 8655\nnrarr 8603\n"
- + "nrarrc 10547,824\nnrarrw 8605,824\nnrightarrow 8603\nnrtri 8939\nnrtrie 8941\nnsc 8833\n"
- + "nsccue 8929\nnsce 10928,824\nnscr 120003\nnshortmid 8740\nnshortparallel 8742\nnsim 8769\n"
- + "nsime 8772\nnsimeq 8772\nnsmid 8740\nnspar 8742\nnsqsube 8930\nnsqsupe 8931\nnsub 8836\n"
- + "nsubE 10949,824\nnsube 8840\nnsubset 8834,8402\nnsubseteq 8840\nnsubseteqq 10949,824\n"
- + "nsucc 8833\nnsucceq 10928,824\nnsup 8837\nnsupE 10950,824\nnsupe 8841\nnsupset 8835,8402\n"
- + "nsupseteq 8841\nnsupseteqq 10950,824\nntgl 8825\nntilde 241\nntlg 8824\n"
- + "ntriangleleft 8938\nntrianglelefteq 8940\nntriangleright 8939\nntrianglerighteq 8941\n"
- + "nu 957\nnum 35\nnumero 8470\nnumsp 8199\nnvDash 8877\nnvHarr 10500\nnvap 8781,8402\n"
- + "nvdash 8876\nnvge 8805,8402\nnvgt 62,8402\nnvinfin 10718\nnvlArr 10498\nnvle 8804,8402\n"
- + "nvlt 60,8402\nnvltrie 8884,8402\nnvrArr 10499\nnvrtrie 8885,8402\nnvsim 8764,8402\n"
- + "nwArr 8662\nnwarhk 10531\nnwarr 8598\nnwarrow 8598\nnwnear 10535\noS 9416\noacute 243\n"
- + "oast 8859\nocir 8858\nocirc 244\nocy 1086\nodash 8861\nodblac 337\nodiv 10808\nodot 8857\n"
- + "odsold 10684\noelig 339\nofcir 10687\nofr 120108\nogon 731\nograve 242\nogt 10689\n"
- + "ohbar 10677\nohm 937\noint 8750\nolarr 8634\nolcir 10686\nolcross 10683\noline 8254\n"
- + "olt 10688\nomacr 333\nomega 969\nomicron 959\nomid 10678\nominus 8854\noopf 120160\n"
- + "opar 10679\noperp 10681\noplus 8853\nor 8744\norarr 8635\nord 10845\norder 8500\n"
- + "orderof 8500\nordf 170\nordm 186\norigof 8886\noror 10838\norslope 10839\norv 10843\n"
- + "oscr 8500\noslash 248\nosol 8856\notilde 245\notimes 8855\notimesas 10806\nouml 246\n"
- + "ovbar 9021\npar 8741\npara 182\nparallel 8741\nparsim 10995\nparsl 11005\npart 8706\n"
- + "pcy 1087\npercnt 37\nperiod 46\npermil 8240\nperp 8869\npertenk 8241\npfr 120109\n"
- + "phi 966\nphiv 981\nphmmat 8499\nphone 9742\npi 960\npitchfork 8916\npiv 982\nplanck 8463\n"
- + "planckh 8462\nplankv 8463\nplus 43\nplusacir 10787\nplusb 8862\npluscir 10786\n"
- + "plusdo 8724\nplusdu 10789\npluse 10866\nplusmn 177\nplussim 10790\nplustwo 10791\npm 177\n"
- + "pointint 10773\npopf 120161\npound 163\npr 8826\nprE 10931\nprap 10935\nprcue 8828\n"
- + "pre 10927\nprec 8826\nprecapprox 10935\npreccurlyeq 8828\npreceq 10927\n"
- + "precnapprox 10937\nprecneqq 10933\nprecnsim 8936\nprecsim 8830\nprime 8242\nprimes 8473\n"
- + "prnE 10933\nprnap 10937\nprnsim 8936\nprod 8719\nprofalar 9006\nprofline 8978\n"
- + "profsurf 8979\nprop 8733\npropto 8733\nprsim 8830\nprurel 8880\npscr 120005\npsi 968\n"
- + "puncsp 8200\nqfr 120110\nqint 10764\nqopf 120162\nqprime 8279\nqscr 120006\n"
- + "quaternions 8461\nquatint 10774\nquest 63\nquesteq 8799\nquot 34\nrAarr 8667\nrArr 8658\n"
- + "rAtail 10524\nrBarr 10511\nrHar 10596\nrace 8765,817\nracute 341\nradic 8730\n"
- + "raemptyv 10675\nrang 10217\nrangd 10642\nrange 10661\nrangle 10217\nraquo 187\nrarr 8594\n"
- + "rarrap 10613\nrarrb 8677\nrarrbfs 10528\nrarrc 10547\nrarrfs 10526\nrarrhk 8618\n"
- + "rarrlp 8620\nrarrpl 10565\nrarrsim 10612\nrarrtl 8611\nrarrw 8605\nratail 10522\n"
- + "ratio 8758\nrationals 8474\nrbarr 10509\nrbbrk 10099\nrbrace 125\nrbrack 93\nrbrke 10636\n"
- + "rbrksld 10638\nrbrkslu 10640\nrcaron 345\nrcedil 343\nrceil 8969\nrcub 125\nrcy 1088\n"
- + "rdca 10551\nrdldhar 10601\nrdquo 8221\nrdquor 8221\nrdsh 8627\nreal 8476\nrealine 8475\n"
- + "realpart 8476\nreals 8477\nrect 9645\nreg 174\nrfisht 10621\nrfloor 8971\nrfr 120111\n"
- + "rhard 8641\nrharu 8640\nrharul 10604\nrho 961\nrhov 1009\nrightarrow 8594\n"
- + "rightarrowtail 8611\nrightharpoondown 8641\nrightharpoonup 8640\nrightleftarrows 8644\n"
- + "rightleftharpoons 8652\nrightrightarrows 8649\nrightsquigarrow 8605\n"
- + "rightthreetimes 8908\nring 730\nrisingdotseq 8787\nrlarr 8644\nrlhar 8652\nrlm 8207\n"
- + "rmoust 9137\nrmoustache 9137\nrnmid 10990\nroang 10221\nroarr 8702\nrobrk 10215\n"
- + "ropar 10630\nropf 120163\nroplus 10798\nrotimes 10805\nrpar 41\nrpargt 10644\n"
- + "rppolint 10770\nrrarr 8649\nrsaquo 8250\nrscr 120007\nrsh 8625\nrsqb 93\nrsquo 8217\n"
- + "rsquor 8217\nrthree 8908\nrtimes 8906\nrtri 9657\nrtrie 8885\nrtrif 9656\nrtriltri 10702\n"
- + "ruluhar 10600\nrx 8478\nsacute 347\nsbquo 8218\nsc 8827\nscE 10932\nscap 10936\n"
- + "scaron 353\nsccue 8829\nsce 10928\nscedil 351\nscirc 349\nscnE 10934\nscnap 10938\n"
- + "scnsim 8937\nscpolint 10771\nscsim 8831\nscy 1089\nsdot 8901\nsdotb 8865\nsdote 10854\n"
- + "seArr 8664\nsearhk 10533\nsearr 8600\nsearrow 8600\nsect 167\nsemi 59\nseswar 10537\n"
- + "setminus 8726\nsetmn 8726\nsext 10038\nsfr 120112\nsfrown 8994\nsharp 9839\nshchcy 1097\n"
- + "shcy 1096\nshortmid 8739\nshortparallel 8741\nshy 173\nsigma 963\nsigmaf 962\nsigmav 962\n"
- + "sim 8764\nsimdot 10858\nsime 8771\nsimeq 8771\nsimg 10910\nsimgE 10912\nsiml 10909\n"
- + "simlE 10911\nsimne 8774\nsimplus 10788\nsimrarr 10610\nslarr 8592\nsmallsetminus 8726\n"
- + "smashp 10803\nsmeparsl 10724\nsmid 8739\nsmile 8995\nsmt 10922\nsmte 10924\n"
- + "smtes 10924,65024\nsoftcy 1100\nsol 47\nsolb 10692\nsolbar 9023\nsopf 120164\n"
- + "spades 9824\nspadesuit 9824\nspar 8741\nsqcap 8851\nsqcaps 8851,65024\nsqcup 8852\n"
- + "sqcups 8852,65024\nsqsub 8847\nsqsube 8849\nsqsubset 8847\nsqsubseteq 8849\nsqsup 8848\n"
- + "sqsupe 8850\nsqsupset 8848\nsqsupseteq 8850\nsqu 9633\nsquare 9633\nsquarf 9642\n"
- + "squf 9642\nsrarr 8594\nsscr 120008\nssetmn 8726\nssmile 8995\nsstarf 8902\nstar 9734\n"
- + "starf 9733\nstraightepsilon 1013\nstraightphi 981\nstrns 175\nsub 8834\nsubE 10949\n"
- + "subdot 10941\nsube 8838\nsubedot 10947\nsubmult 10945\nsubnE 10955\nsubne 8842\n"
- + "subplus 10943\nsubrarr 10617\nsubset 8834\nsubseteq 8838\nsubseteqq 10949\n"
- + "subsetneq 8842\nsubsetneqq 10955\nsubsim 10951\nsubsub 10965\nsubsup 10963\nsucc 8827\n"
- + "succapprox 10936\nsucccurlyeq 8829\nsucceq 10928\nsuccnapprox 10938\nsuccneqq 10934\n"
- + "succnsim 8937\nsuccsim 8831\nsum 8721\nsung 9834\nsup 8835\nsup1 185\nsup2 178\nsup3 179\n"
- + "supE 10950\nsupdot 10942\nsupdsub 10968\nsupe 8839\nsupedot 10948\nsuphsol 10185\n"
- + "suphsub 10967\nsuplarr 10619\nsupmult 10946\nsupnE 10956\nsupne 8843\nsupplus 10944\n"
- + "supset 8835\nsupseteq 8839\nsupseteqq 10950\nsupsetneq 8843\nsupsetneqq 10956\n"
- + "supsim 10952\nsupsub 10964\nsupsup 10966\nswArr 8665\nswarhk 10534\nswarr 8601\n"
- + "swarrow 8601\nswnwar 10538\nszlig 223\ntarget 8982\ntau 964\ntbrk 9140\ntcaron 357\n"
- + "tcedil 355\ntcy 1090\ntdot 8411\ntelrec 8981\ntfr 120113\nthere4 8756\ntherefore 8756\n"
- + "theta 952\nthetasym 977\nthetav 977\nthickapprox 8776\nthicksim 8764\nthinsp 8201\n"
- + "thkap 8776\nthksim 8764\nthorn 254\ntilde 732\ntimes 215\ntimesb 8864\ntimesbar 10801\n"
- + "timesd 10800\ntint 8749\ntoea 10536\ntop 8868\ntopbot 9014\ntopcir 10993\ntopf 120165\n"
- + "topfork 10970\ntosa 10537\ntprime 8244\ntrade 8482\ntriangle 9653\ntriangledown 9663\n"
- + "triangleleft 9667\ntrianglelefteq 8884\ntriangleq 8796\ntriangleright 9657\n"
- + "trianglerighteq 8885\ntridot 9708\ntrie 8796\ntriminus 10810\ntriplus 10809\ntrisb 10701\n"
- + "tritime 10811\ntrpezium 9186\ntscr 120009\ntscy 1094\ntshcy 1115\ntstrok 359\ntwixt 8812\n"
- + "twoheadleftarrow 8606\ntwoheadrightarrow 8608\nuArr 8657\nuHar 10595\nuacute 250\n"
- + "uarr 8593\nubrcy 1118\nubreve 365\nucirc 251\nucy 1091\nudarr 8645\nudblac 369\n"
- + "udhar 10606\nufisht 10622\nufr 120114\nugrave 249\nuharl 8639\nuharr 8638\nuhblk 9600\n"
- + "ulcorn 8988\nulcorner 8988\nulcrop 8975\nultri 9720\numacr 363\numl 168\nuogon 371\n"
- + "uopf 120166\nuparrow 8593\nupdownarrow 8597\nupharpoonleft 8639\nupharpoonright 8638\n"
- + "uplus 8846\nupsi 965\nupsih 978\nupsilon 965\nupuparrows 8648\nurcorn 8989\n"
- + "urcorner 8989\nurcrop 8974\nuring 367\nurtri 9721\nuscr 120010\nutdot 8944\nutilde 361\n"
- + "utri 9653\nutrif 9652\nuuarr 8648\nuuml 252\nuwangle 10663\nvArr 8661\nvBar 10984\n"
- + "vBarv 10985\nvDash 8872\nvangrt 10652\nvarepsilon 1013\nvarkappa 1008\nvarnothing 8709\n"
- + "varphi 981\nvarpi 982\nvarpropto 8733\nvarr 8597\nvarrho 1009\nvarsigma 962\n"
- + "varsubsetneq 8842,65024\nvarsubsetneqq 10955,65024\nvarsupsetneq 8843,65024\n"
- + "varsupsetneqq 10956,65024\nvartheta 977\nvartriangleleft 8882\nvartriangleright 8883\n"
- + "vcy 1074\nvdash 8866\nvee 8744\nveebar 8891\nveeeq 8794\nvellip 8942\nverbar 124\n"
- + "vert 124\nvfr 120115\nvltri 8882\nvnsub 8834,8402\nvnsup 8835,8402\nvopf 120167\n"
- + "vprop 8733\nvrtri 8883\nvscr 120011\nvsubnE 10955,65024\nvsubne 8842,65024\n"
- + "vsupnE 10956,65024\nvsupne 8843,65024\nvzigzag 10650\nwcirc 373\nwedbar 10847\n"
- + "wedge 8743\nwedgeq 8793\nweierp 8472\nwfr 120116\nwopf 120168\nwp 8472\nwr 8768\n"
- + "wreath 8768\nwscr 120012\nxcap 8898\nxcirc 9711\nxcup 8899\nxdtri 9661\nxfr 120117\n"
- + "xhArr 10234\nxharr 10231\nxi 958\nxlArr 10232\nxlarr 10229\nxmap 10236\nxnis 8955\n"
- + "xodot 10752\nxopf 120169\nxoplus 10753\nxotime 10754\nxrArr 10233\nxrarr 10230\n"
- + "xscr 120013\nxsqcup 10758\nxuplus 10756\nxutri 9651\nxvee 8897\nxwedge 8896\nyacute 253\n"
- + "yacy 1103\nycirc 375\nycy 1099\nyen 165\nyfr 120118\nyicy 1111\nyopf 120170\nyscr 120014\n"
- + "yucy 1102\nyuml 255\nzacute 378\nzcaron 382\nzcy 1079\nzdot 380\nzeetrf 8488\nzeta 950\n"
- + "zfr 120119\nzhcy 1078\nzigrarr 8669\nzopf 120171\nzscr 120015\nzwj 8205\nzwnj 8204\n"
- ;
- // ---------------------------------------------------------------------------
- // Markdown block structure (CommonMark 0.31.2, section 3)
- // ---------------------------------------------------------------------------
- //
- // A cmark-style line scanner: each line is matched against the stack of
- // open "container" blocks (document > blockquote > list > item > ...),
- // consuming their prefixes, then new blocks are attempted in order
- // (blockquote, ATX heading, fenced code, setext underline, thematic break,
- // list item, indented code). Whatever remains is appended to the deepest
- // open leaf, or becomes a lazy paragraph continuation.
- //
- // We do not implement HTML blocks as containers: raw HTML is a security
- // hazard for `innerHTML`, so HTML-block-looking paragraphs stay paragraphs
- // and get escaped by the inline pass like any other text. That also means
- // `<script>` cannot interrupt a paragraph the way the spec allows.
- /** Number of columns that count as an indented code block. */
- var MD_CODE_INDENT = 4;
- /** Characters that can begin a non-paragraph block (fast bail-out). */
- var MD_MAYBE_SPECIAL_RE = /^[#`~*+_=<>0-9\-]/;
- var MD_THEMATIC_RE = /^(?:\*[ \t]*){3,}$|^(?:_[ \t]*){3,}$|^(?:-[ \t]*){3,}$/;
- var MD_BULLET_RE = /^[*+\-]/;
- var MD_ORDERED_RE = /^(\d{1,9})([.)])/;
- var MD_ATX_RE = /^#{1,6}(?:[ \t]+|$)/;
- var MD_FENCE_RE = /^`{3,}(?!.*`)|^~{3,}/;
- var MD_CLOSE_FENCE_RE = /^(?:`{3,}|~{3,})(?=[ \t]*$)/;
- var MD_SETEXT_RE = /^(?:=+|-+)[ \t]*$/;
- var MD_NON_SPACE_RE = /[^ \t\f\v\r\n]/;
- /**
- * Create a block node of the given type.
- * @param {string} type document|blockquote|list|item|paragraph|heading|code|thematic
- */
- function mdNode(type) {
- return {
- type: type, parent: null, children: [], strings: [],
- open: true, info: '', literal: '',
- fenced: false, fenceChar: '', fenceLength: 0, fenceOffset: 0,
- level: 1, listData: null, tight: true, headingSetext: false,
- sourceLine: 0
- };
- }
- function mdParser() {
- var doc = mdNode('document');
- return {
- doc: doc, tip: doc, oldtip: doc,
- offset: 0, column: 0, nextNonspace: 0, nextNonspaceColumn: 0,
- indent: 0, indented: false, blank: false, partiallyConsumedTab: false,
- allClosed: true, lastMatchedContainer: doc,
- currentLine: '', lineNumber: 0, lastLineLength: 0,
- refmap: {}, lineOffsets: []
- };
- }
- /** Normalise endings and split into lines (trailing blank from final \n dropped). */
- function mdSplitInput(raw) {
- var text = String(raw).replace(/\r\n|\r(?!\n)/g, '\n').replace(/\r/g, '\n');
- var out = text.split('\n');
- if (out.length && out[out.length - 1] === '') out.pop();
- return out;
- }
- // --- parser cursor helpers ------------------------------------------------
- /** Find the next non-space/tab char; sets blank/indent/indented on p. */
- function mdFindNextNonspace(p) {
- var ln = p.currentLine, i = p.offset, cols = p.column, c;
- while ((c = ln.charAt(i)) !== '') {
- if (c === ' ') { i++; cols++; }
- else if (c === '\t') { i++; cols += 4 - (cols % 4); }
- else break;
- }
- p.blank = c === '' ;
- p.nextNonspace = i;
- p.nextNonspaceColumn = cols;
- p.indent = p.nextNonspaceColumn - p.column;
- p.indented = p.indent >= MD_CODE_INDENT;
- }
- /**
- * Advance the cursor by `count` columns (or characters when `columns` is
- * false). Handles partially consumed tabs, which stay in the line as the
- * equivalent spaces.
- */
- function mdAdvanceOffset(p, count, columns) {
- var ln = p.currentLine, charsToTab, advance, c;
- while (count > 0 && (c = ln.charAt(p.offset)) !== '') {
- if (c === '\t') {
- charsToTab = 4 - (p.column % 4);
- if (columns) {
- p.partiallyConsumedTab = charsToTab > count;
- advance = charsToTab > count ? count : charsToTab;
- p.column += advance;
- if (!p.partiallyConsumedTab) p.offset += 1;
- count -= advance;
- } else {
- p.partiallyConsumedTab = false;
- p.column += charsToTab;
- p.offset += 1;
- count -= 1;
- }
- } else {
- p.partiallyConsumedTab = false;
- p.offset += 1;
- p.column += 1;
- count -= 1;
- }
- }
- }
- function mdAdvanceNextNonspace(p) {
- p.offset = p.nextNonspace;
- p.column = p.nextNonspaceColumn;
- p.partiallyConsumedTab = false;
- }
- /**
- * Append the rest of the current line (from p.offset) to the tip. When a
- * tab was only partially consumed, the surviving columns are re-emitted as
- * spaces, exactly like cmark.
- */
- function mdAddLine(p) {
- var s = '';
- if (p.partiallyConsumedTab) {
- p.offset += 1; // skip the tab character itself
- var charsToTab = 4 - (p.column % 4);
- while (s.length < charsToTab) s += ' ';
- }
- p.tip.strings.push(s + p.currentLine.slice(p.offset));
- }
- function mdCanContain(type, child) {
- if (type === 'item' || type === 'blockquote' ||
- type === 'document' || type === 'list') {
- if (type === 'list') return child === 'item';
- return child !== 'item';
- }
- return false;
- }
- function mdAcceptsLines(type) {
- return type === 'paragraph' || type === 'code';
- }
- /** Close every block from tip down to (excluding) `lastMatched`. */
- function mdCloseUnmatched(p) {
- if (p.allClosed) return;
- while (p.oldtip !== p.lastMatchedContainer) {
- mdFinalize(p, p.oldtip, p.lineNumber - 1);
- p.oldtip = p.oldtip.parent;
- }
- p.allClosed = true;
- }
- /**
- * Add a child block of `tag` under the tip, finalising any tip that cannot
- * contain it first.
- */
- function mdAddChild(p, tag) {
- while (!mdCanContain(p.tip.type, tag)) mdFinalize(p, p.tip, p.lineNumber - 1);
- var node = mdNode(tag);
- node.parent = p.tip;
- node.sourceLine = p.lineNumber;
- p.tip.children.push(node);
- p.tip = node;
- return node;
- }
- // --- container continue checks -------------------------------------------
- // 0 = matched, 1 = not matched, 2 = line fully handled (fence close)
- function mdContinueBlock(p, container) {
- var ln = p.currentLine, t = container.type;
- if (t === 'document' || t === 'list') return 0;
- if (t === 'blockquote') {
- if (!p.indented && ln.charAt(p.nextNonspace) === '>') {
- mdAdvanceNextNonspace(p);
- mdAdvanceOffset(p, 1, false);
- if (ln.charAt(p.offset) === ' ' || ln.charAt(p.offset) === '\t') {
- mdAdvanceOffset(p, 1, true);
- }
- return 0;
- }
- return 1;
- }
- if (t === 'item') {
- if (p.blank) {
- if (!container.children.length) return 1; // blank after empty item
- mdAdvanceNextNonspace(p);
- return 0;
- }
- var need = container.listData.markerOffset + container.listData.padding;
- if (p.indent >= need) {
- mdAdvanceOffset(p, need, true);
- return 0;
- }
- return 1;
- }
- if (t === 'code') {
- if (container.fenced) {
- var rest = ln.slice(p.nextNonspace);
- if (p.indent <= 3 && ln.charAt(p.nextNonspace) === container.fenceChar &&
- MD_CLOSE_FENCE_RE.test(rest) && rest.match(MD_CLOSE_FENCE_RE)[0].length >= container.fenceLength) {
- mdFinalize(p, container, p.lineNumber);
- return 2;
- }
- // skip up to fenceOffset leading spaces
- var i = container.fenceOffset;
- while (i > 0 && (ln.charAt(p.offset) === ' ' || ln.charAt(p.offset) === '\t')) {
- mdAdvanceOffset(p, 1, true);
- i--;
- }
- return 0;
- }
- if (p.indent >= MD_CODE_INDENT) { mdAdvanceOffset(p, MD_CODE_INDENT, true); return 0; }
- if (p.blank) { mdAdvanceNextNonspace(p); return 0; }
- return 1;
- }
- if (t === 'heading' || t === 'thematic') return 1;
- if (t === 'paragraph') return p.blank ? 1 : 0;
- return 1;
- }
- /**
- * True when a blank line separates `node` from its following sibling (used
- * for the tight/loose list decision).
- */
- function mdEndsWithBlank(node) {
- if (!node.parent) return false;
- var idx = node.parent.children.indexOf(node);
- var next = node.parent.children[idx + 1];
- if (!next) return false;
- return mdNodeEndLine(node) !== next.sourceLine - 1;
- }
- /** Last source line number consumed by a node (tracked during the scan). */
- function mdNodeEndLine(node) {
- return node.endLine == null ? node.sourceLine : node.endLine;
- }
- // --- block starts ----------------------------------------------------------
- /**
- * Parse a list marker at the cursor. Returns the marker data or null.
- * Mirrors cmark: the marker itself, then 1-4 spaces (5+ or a blank rest
- * means "content starts one space after the marker").
- */
- function mdParseListMarker(p, container) {
- var rest = p.currentLine.slice(p.nextNonspace);
- var data = { type: null, tight: true, bulletChar: null, start: null,
- delimiter: null, padding: null, markerOffset: p.indent };
- var m, nextc;
- if (p.indent >= 4) return null;
- if ((m = rest.match(MD_BULLET_RE))) {
- data.type = 'bullet';
- data.bulletChar = m[0].charAt(0);
- } else if ((m = rest.match(MD_ORDERED_RE)) &&
- (container.type !== 'paragraph' || Number(m[1]) === 1)) {
- data.type = 'ordered';
- data.start = parseInt(m[1], 10);
- data.delimiter = m[2];
- } else {
- return null;
- }
- nextc = p.currentLine.charAt(p.nextNonspace + m[0].length);
- if (!(nextc === '' || nextc === ' ' || nextc === '\t')) return null;
- if (container.type === 'paragraph' &&
- !MD_NON_SPACE_RE.test(p.currentLine.slice(p.nextNonspace + m[0].length))) {
- return null;
- }
- mdAdvanceNextNonspace(p);
- mdAdvanceOffset(p, m[0].length, true);
- var spacesStartCol = p.column, spacesStartOffset = p.offset;
- do {
- mdAdvanceOffset(p, 1, true);
- nextc = p.currentLine.charAt(p.offset);
- } while (p.column - spacesStartCol < 5 && (nextc === ' ' || nextc === '\t'));
- var blankItem = p.currentLine.charAt(p.offset) === '' && p.offset >= p.currentLine.length;
- var spacesAfterMarker = p.column - spacesStartCol;
- if (spacesAfterMarker >= 5 || spacesAfterMarker < 1 || blankItem) {
- data.padding = m[0].length + 1;
- p.column = spacesStartCol;
- p.offset = spacesStartOffset;
- var c2 = p.currentLine.charAt(p.offset);
- if (c2 === ' ' || c2 === '\t') mdAdvanceOffset(p, 1, true);
- } else {
- data.padding = m[0].length + spacesAfterMarker;
- }
- return data;
- }
- function mdListsMatch(a, b) {
- return a.type === b.type && a.delimiter === b.delimiter &&
- a.bulletChar === b.bulletChar;
- }
- /**
- * Try to start a new block at the cursor. Returns 0 (no match), 1 (opened a
- * container, keep trying), or 2 (opened a leaf; the line is spent).
- */
- function mdTryBlockStart(p, container) {
- var ln = p.currentLine, m, node;
- // block quote
- if (!p.indented && ln.charAt(p.nextNonspace) === '>') {
- mdAdvanceNextNonspace(p);
- mdAdvanceOffset(p, 1, false);
- if (ln.charAt(p.offset) === ' ' || ln.charAt(p.offset) === '\t') {
- mdAdvanceOffset(p, 1, true);
- }
- mdCloseUnmatched(p);
- mdAddChild(p, 'blockquote');
- return 1;
- }
- // ATX heading
- if (!p.indented && (m = ln.slice(p.nextNonspace).match(MD_ATX_RE))) {
- mdAdvanceNextNonspace(p);
- mdAdvanceOffset(p, m[0].length, false);
- mdCloseUnmatched(p);
- node = mdAddChild(p, 'heading');
- node.level = m[0].replace(/[ \t]/g, '').length;
- node.strings.push(
- ln.slice(p.offset)
- .replace(/^[ \t]*#+[ \t]*$/, '')
- .replace(/[ \t]+#+[ \t]*$/, ''));
- mdAdvanceOffset(p, ln.length - p.offset, false);
- return 2;
- }
- // fenced code block
- if (!p.indented && (m = ln.slice(p.nextNonspace).match(MD_FENCE_RE))) {
- mdCloseUnmatched(p);
- node = mdAddChild(p, 'code');
- node.fenced = true;
- node.fenceLength = m[0].length;
- node.fenceChar = m[0].charAt(0);
- node.fenceOffset = p.indent;
- mdAdvanceNextNonspace(p);
- mdAdvanceOffset(p, m[0].length, false);
- return 2;
- }
- // setext heading underline
- if (!p.indented && container.type === 'paragraph' &&
- (m = ln.slice(p.nextNonspace).match(MD_SETEXT_RE))) {
- mdCloseUnmatched(p);
- var pos;
- var joined = container.strings.join('\n');
- while (joined.charAt(0) === '[' && (pos = mdParseReference(joined, p.refmap)) > 0) {
- joined = joined.slice(pos);
- }
- container.strings = joined.length ? [joined] : [];
- var content = container.strings.join('\n');
- if (content.length > 0) {
- node = mdNode('heading');
- node.level = m[0].charAt(0) === '=' ? 1 : 2;
- node.headingSetext = true;
- node.strings = container.strings.slice();
- node.sourceLine = container.sourceLine;
- node.endLine = p.lineNumber;
- node.parent = container.parent;
- var ci = container.parent.children.indexOf(container);
- container.parent.children[ci] = node;
- p.tip = node;
- mdAdvanceOffset(p, ln.length - p.offset, false);
- return 2;
- }
- return 0;
- }
- // thematic break
- if (!p.indented && MD_THEMATIC_RE.test(ln.slice(p.nextNonspace))) {
- mdCloseUnmatched(p);
- mdAddChild(p, 'thematic');
- mdAdvanceOffset(p, ln.length - p.offset, false);
- return 2;
- }
- // list item
- var data;
- if ((!p.indented || container.type === 'list') && (data = mdParseListMarker(p, container))) {
- mdCloseUnmatched(p);
- if (p.tip.type !== 'list' || !mdListsMatch(container.listData, data)) {
- var list = mdAddChild(p, 'list');
- list.listData = data;
- container = list;
- }
- var item = mdAddChild(p, 'item');
- item.listData = data;
- return 1;
- }
- // indented code block
- if (p.indented && p.tip.type !== 'paragraph' && !p.blank) {
- mdAdvanceOffset(p, MD_CODE_INDENT, true);
- mdCloseUnmatched(p);
- mdAddChild(p, 'code');
- return 2;
- }
- return 0;
- }
- // --- line incorporation and finalisation -----------------------------------
- /**
- * Process one source line into the open block tree: match container
- * prefixes, try to open new blocks, then hand the remainder to a leaf.
- */
- function mdIncorporateLine(p, ln) {
- var container = p.doc, lastChild, allMatched = true, res;
- p.oldtip = p.tip;
- p.offset = 0;
- p.column = 0;
- p.blank = false;
- p.partiallyConsumedTab = false;
- p.lineNumber += 1;
- p.currentLine = ln.indexOf('\u0000') >= 0 ? ln.replace(/\u0000/g, '\uFFFD') : ln;
- // 1. Match the open containers' prefixes, deepest first.
- while (container.children.length) {
- lastChild = container.children[container.children.length - 1];
- if (!lastChild.open) break;
- container = lastChild;
- mdFindNextNonspace(p);
- res = mdContinueBlock(p, container);
- if (res === 2) { p.lastLineLength = ln.length; return; }
- if (res === 1) { allMatched = false; container = container.parent; break; }
- }
- p.allClosed = container === p.oldtip;
- p.lastMatchedContainer = container;
- // 2. Unless we already sit in a leaf that accepts lines, try block starts.
- var matchedLeaf = container.type !== 'paragraph' && mdAcceptsLines(container.type);
- while (!matchedLeaf) {
- mdFindNextNonspace(p);
- if (!p.indented && !MD_MAYBE_SPECIAL_RE.test(p.currentLine.slice(p.nextNonspace))) {
- mdAdvanceNextNonspace(p);
- break;
- }
- res = mdTryBlockStart(p, container);
- if (res === 1) { container = p.tip; continue; }
- if (res === 2) { container = p.tip; matchedLeaf = true; break; }
- mdAdvanceNextNonspace(p);
- break;
- }
- // 3. The remainder is line content for the tip.
- if (!p.allClosed && !p.blank && p.tip.type === 'paragraph') {
- mdAddLine(p); // lazy paragraph continuation
- } else {
- mdCloseUnmatched(p);
- if (mdAcceptsLines(container.type)) {
- mdAddLine(p);
- } else if (p.offset < p.currentLine.length && !p.blank) {
- mdAddChild(p, 'paragraph');
- mdAdvanceNextNonspace(p);
- mdAddLine(p);
- }
- }
- p.lastLineLength = ln.length;
- }
- /**
- * Close a block: extract fenced info strings / indented-code literals, work
- * out list tightness, peel link reference definitions off paragraphs and
- * record which source line the block ended on.
- */
- function mdFinalize(p, block, endLine) {
- var above = block.parent;
- block.open = false;
- block.endLine = endLine == null ? p.lineNumber : endLine;
- if (block.type === 'code') {
- if (block.fenced) {
- var content = block.strings.join('\n');
- var nl = content.indexOf('\n');
- var firstLine = nl >= 0 ? content.slice(0, nl) : content;
- var rest = nl >= 0 ? content.slice(nl + 1) : '';
- block.info = mdUnescapeString(firstLine.replace(/^[ \t]+/, '').replace(/[ \t]+$/, ''));
- // cmark keeps the final newline of the block's content
- block.literal = rest.length ? rest + '\n' : (block.strings.length > 1 ? '\n' : '');
- } else {
- var lines = block.strings.slice();
- while (lines.length && !MD_NON_SPACE_RE.test(lines[lines.length - 1])) lines.pop();
- block.literal = lines.join('\n') + '\n';
- }
- block.strings = [];
- }
- if (block.type === 'paragraph') {
- // Reference definitions live at the start of paragraphs only; each
- // consumed definition must advance or we stop.
- var txt = block.strings.join('\n');
- var pos;
- while (txt.charAt(0) === '[' && (pos = mdParseReference(txt, p.refmap)) > 0) {
- txt = txt.slice(pos);
- }
- block.strings = txt.length ? [txt] : [];
- if (!txt.length) mdRemoveFromParent(block);
- }
- if ((block.type === 'item' || block.type === 'list') && block.children.length) {
- // items and lists end where their last child ends (a trailing blank
- // line is not part of them) — this drives the tight/loose rule.
- // Blockquotes deliberately keep the line their `>` marker last
- // appeared on: ` >` is not a blank line for these purposes.
- block.endLine = block.children[block.children.length - 1].endLine;
- }
- if (block.type === 'list') {
- block.tight = true;
- for (var i = 0; i < block.children.length; i++) {
- var item = block.children[i];
- if (i < block.children.length - 1 && mdEndsWithBlank(item)) { block.tight = false; break; }
- for (var j = 0; j < item.children.length; j++) {
- if (j < item.children.length - 1 && mdEndsWithBlank(item.children[j])) { block.tight = false; break; }
- }
- if (!block.tight) break;
- }
- }
- p.tip = above;
- }
- /** Detach a node (used when a paragraph turns out to be all references). */
- function mdRemoveFromParent(node) {
- if (!node.parent) return;
- var i = node.parent.children.indexOf(node);
- if (i >= 0) node.parent.children.splice(i, 1);
- }
- /** Parse the whole input into a block tree. */
- function mdParseDocument(raw) {
- var p = mdParser();
- var lines = mdSplitInput(raw);
- for (var i = 0; i < lines.length; i++) mdIncorporateLine(p, lines[i]);
- while (p.tip && p.tip.type !== 'document') mdFinalize(p, p.tip, lines.length);
- return p;
- }
- // --- shared inline regexes / URI handling -----------------------------------
- var MD_LINK_TITLE_RE = /(?:")([^"]*)(?:")|(?:')([^']*)(?:')/;
- /**
- * Scan a link title at `subject[pos]` without regex backtracking: a quoted
- * run (with `\"`-style escapes) or a parenthesised run. Returns
- * `{ text, len }` or null.
- * @param {string} subject
- * @param {number} pos
- * @returns {?{text: string, len: number}}
- */
- function mdScanLinkTitle(subject, pos) {
- var start = pos, q = subject.charAt(pos);
- if (q !== '"' && q !== "'" && q !== '(') return null;
- var close = q === '(' ? ')' : q;
- var i = pos + 1;
- while (i < subject.length) {
- var ch = subject.charAt(i);
- if (ch === '\\' && subject.charAt(i + 1) !== '' &&
- MD_ESCAPABLE.indexOf(subject.charAt(i + 1)) >= 0) { i += 2; continue; }
- if (ch === close) {
- return { text: subject.slice(start + 1, i), len: i + 1 - start };
- }
- if (ch === '\n' && subject.charAt(i + 1) === '\n') return null; // blank line ends it
- i++;
- }
- return null;
- }
- var MD_LINK_DEST_BRACES_RE = /^<(?:[^<>\n\\\x00]|\\.)*>/;
- /**
- * Match a raw HTML open/close tag at subject[pos] using a linear scan
- * (the equivalent regex backtracks catastrophically on malformed input).
- * Returns the matched text or null. SECURITY: callers render this escaped.
- * @param {string} subject
- * @param {number} pos
- * @returns {?string}
- */
- function mdScanHtmlTag(subject, pos) {
- var i = pos;
- if (subject.charAt(i) !== '<') return null;
- i++;
- var closing = subject.charAt(i) === '/';
- if (closing) i++;
- if (!/[A-Za-z]/.test(subject.charAt(i))) return null;
- var start = i;
- while (i < subject.length && /[A-Za-z0-9-]/.test(subject.charAt(i))) i++;
- if (i === start) return null;
- if (closing) {
- while (i < subject.length && /[ \t\n]/.test(subject.charAt(i))) i++;
- if (subject.charAt(i) === '>') return subject.slice(pos, i + 1);
- return null;
- }
- // attributes
- while (i < subject.length) {
- var wsStart = i;
- while (i < subject.length && /[ \t\n]/.test(subject.charAt(i))) i++;
- if (subject.charAt(i) === '>') return subject.slice(pos, i + 1);
- if (subject.charAt(i) === '/' && subject.charAt(i + 1) === '>') return subject.slice(pos, i + 2);
- if (i === wsStart) return null; // attribute must be preceded by space
- var an = i;
- while (i < subject.length && !/[\s/=><]/.test(subject.charAt(i))) i++;
- if (i === an) return null;
- var eq = i;
- while (i < subject.length && /[ \t\n]/.test(subject.charAt(i))) i++;
- if (subject.charAt(i) !== '=') { i = eq; continue; }
- i++;
- while (i < subject.length && /[ \t\n]/.test(subject.charAt(i))) i++;
- var q = subject.charAt(i);
- if (q === '"' || q === "'") {
- i++;
- var endq = subject.indexOf(q, i);
- if (endq < 0) return null;
- i = endq + 1;
- } else {
- var v = i;
- while (i < subject.length && !/[\s>]/.test(subject.charAt(i))) i++;
- if (i === v) return null;
- }
- }
- return null;
- }
- /**
- * CommonMark's URL normalisation: percent-encode every character that is
- * not in the RFC 3986 "unreserved + reserved + '#' escape" set. Non-ASCII
- * characters become UTF-8 percent-escapes (like encodeURIComponent).
- * @param {string} uri
- * @returns {string}
- */
- function mdNormalizeUri(uri) {
- if (!uri) return '';
- var out = '', ch, i;
- for (i = 0; i < uri.length; i++) {
- ch = uri.charAt(i);
- if (MD_URI_SAFE_RE.test(ch)) { out += ch; continue; }
- // encode one code point (surrogate pairs together)
- var cp = uri.charCodeAt(i);
- var str = ch;
- if (cp >= 0xD800 && cp <= 0xDBFF && i + 1 < uri.length) {
- str += uri.charAt(i + 1);
- i++;
- }
- out += encodeURIComponent(str);
- }
- return out;
- }
- /** URI characters kept literally (unreserved, reserved and '%'). */
- var MD_URI_SAFE_RE = /^[A-Za-z0-9;,\/?:@&=+\$\-_\.!~\*'\(\)%#]$/;
- /**
- * Normalise a link label for reference lookup: strip brackets, trim,
- * collapse internal whitespace, case-fold.
- * @param {string} label raw `[...]` including brackets
- * @returns {string}
- */
- function mdNormalizeReference(label) {
- return label.slice(1, label.length - 1).trim()
- .replace(/[ \t\r\n]+/g, ' ')
- .toLowerCase().toUpperCase();
- }
- /**
- * Parse one link reference definition from the start of `s`. Returns the
- * number of characters consumed, or 0.
- * @param {string} s
- * @param {Object} refmap
- * @returns {number}
- */
- function mdParseReference(s, refmap) {
- var subject = s, pos = 0, rawlabel, dest, title = null, startpos = 0;
- function peek2() { return pos < subject.length ? subject.charAt(pos) : ''; }
- function match2(re) {
- var m = re.exec(subject.slice(pos));
- if (m) pos += m[0].length;
- return m;
- }
- function spnl2() { match2(/^ *(?:\n *)?/); }
- // label: one bracketed run, no nested brackets, no blank line
- var depth = 0, i = 0, ch;
- while (i < subject.length) {
- ch = subject.charAt(i);
- if (ch === '\\') { i += 2; continue; }
- if (ch === '[') { depth++; if (depth > 1) return 0; }
- else if (ch === ']') break;
- i++;
- }
- if (depth !== 1 || subject.charAt(i) !== ']') return 0;
- rawlabel = subject.slice(0, i + 1);
- if (rawlabel.length > 1001) return 0;
- pos = i + 1;
- if (peek2() !== ':') return 0;
- pos++;
- spnl2();
- // destination
- var m2 = match2(MD_LINK_DEST_BRACES_RE);
- if (m2) {
- dest = mdNormalizeUri(mdUnescapeString(m2[0].slice(1, -1)));
- } else {
- var save = pos, openparens = 0, c;
- while ((c = peek2()) !== '') {
- if (c === '\\' && subject.charAt(pos + 1) !== '' &&
- MD_ESCAPABLE.indexOf(subject.charAt(pos + 1)) >= 0) {
- pos += 1;
- if (peek2() !== '') pos += 1;
- } else if (c === '(') { pos++; openparens++; }
- else if (c === ')') { if (openparens < 1) break; pos++; openparens--; }
- else if (MD_WS_CHAR_RE.test(c)) break;
- else pos++;
- }
- if (pos === save && c !== ')') return 0;
- if (openparens !== 0) return 0;
- dest = mdNormalizeUri(mdUnescapeString(subject.slice(save, pos)));
- }
- var beforetitle = pos;
- spnl2();
- if (pos !== beforetitle) {
- var t = mdScanLinkTitle(subject, pos);
- if (t) { title = mdUnescapeString(t.text); pos += t.len; }
- }
- if (title === null) pos = beforetitle;
- // must be at end of line
- var atLineEnd = match2(/^ *(?:\n|$)/) !== null;
- if (!atLineEnd) {
- if (title !== null) {
- title = null;
- pos = beforetitle;
- atLineEnd = match2(/^ *(?:\n|$)/) !== null;
- }
- if (!atLineEnd) return 0;
- }
- var normlabel = mdNormalizeReference(rawlabel);
- if (normlabel === '') return 0;
- if (!refmap[normlabel]) {
- refmap[normlabel] = { destination: dest, title: title == null ? '' : title };
- }
- return pos;
- }
- // ---------------------------------------------------------------------------
- // Markdown inline parsing (CommonMark 0.31.2, section 6)
- // ---------------------------------------------------------------------------
- //
- // A hand-rolled scanner over paragraph/heading content: plain text runs are
- // copied until a special character (\n ` [ ] \ ! < & * _), then that
- // character's handler runs. Emphasis is resolved afterwards with the
- // delimiter-run algorithm from the spec: openers are searched bottom-up
- // with the "rule of 3" and openers_bottom optimisation; leftover delimiter
- // text stays literal. Links and images share a bracket stack; links may
- // not contain links.
- //
- // Inline nodes form a doubly-linked list (firstChild/lastChild/next/prev on
- // the parent) exactly like the block tree: process_emphasis has to splice
- // nodes out of the middle, which is painful with arrays.
- var MD_ESCAPABLE = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~';
- var MD_ASCII_PUNCT_TEST_RE = /^[!-/:-@[-`{-~]$/;
- var MD_ENTITY_HERE_RE = /^&(?:#x[a-f0-9]{1,6}|#[0-9]{1,7}|[a-z][a-z0-9]{1,31});/i;
- var MD_TICKS_HERE_RE = /^`+/;
- var MD_WS_CHAR_RE = /[ \t\n\x0b\x0c\x0d]/;
- var MD_FINAL_SPACE_RE = / *$/;
- /**
- * Unicode punctuation/symbol code points (categories P* and S*) above the
- * ASCII range, as "lo-hi" hex ranges (binary-searched). Needed for the
- * left/right-flanking rules on non-ASCII text; ES5 has no \p{P}.
- */
- var MD_UNICODE_PUNCT_RANGES = [
- 'A1-A9','AB-AC','AE-B1','B4','B6-B8','BB','BF','D7','F7','2C2-2C5','2D2-2DF','2E5-2EB',
- '2ED','2EF-2FF','375','37E','384-385','387','3F6','482','55A-55F','589-58A','58D-58F','5BE',
- '5C0','5C3','5C6','5F3-5F4','606-60F','61B','61D-61F','66A-66D','6D4','6DE','6E9','6FD-6FE',
- '700-70D','7F6-7F9','7FE-7FF','830-83E','85E','888','964-965','970','9F2-9F3','9FA-9FB',
- '9FD','A76','AF0-AF1','B70','BF3-BFA','C77','C7F','C84','D4F','D79','DF4','E3F','E4F',
- 'E5A-E5B','F01-F17','F1A-F1F','F34','F36','F38','F3A-F3D','F85','FBE-FC5','FC7-FCC',
- 'FCE-FDA','104A-104F','109E-109F','10FB','1360-1368','1390-1399','1400','166D-166E',
- '169B-169C','16EB-16ED','1735-1736','17D4-17D6','17D8-17DB','1800-180A','1940','1944-1945',
- '19DE-19FF','1A1E-1A1F','1AA0-1AA6','1AA8-1AAD','1B4E-1B4F','1B5A-1B6A','1B74-1B7F',
- '1BFC-1BFF','1C3B-1C3F','1C7E-1C7F','1CC0-1CC7','1CD3','1FBD','1FBF-1FC1','1FCD-1FCF',
- '1FDD-1FDF','1FED-1FEF','1FFD-1FFE','2010-2027','2030-205E','207A-207E','208A-208E',
- '20A0-20C0','2100-2101','2103-2106','2108-2109','2114','2116-2118','211E-2123','2125',
- '2127','2129','212E','213A-213B','2140-2144','214A-214D','214F','218A-218B','2190-2429',
- '2440-244A','249C-24E9','2500-2775','2794-2B73','2B76-2B95','2B97-2BFF','2CE5-2CEA',
- '2CF9-2CFC','2CFE-2CFF','2D70','2E00-2E2E','2E30-2E5D','2E80-2E99','2E9B-2EF3','2F00-2FD5',
- '2FF0-2FFF','3001-3004','3008-3020','3030','3036-3037','303D-303F','309B-309C','30A0',
- '30FB','3190-3191','3196-319F','31C0-31E5','31EF','3200-321E','322A-3247','3250',
- '3260-327F','328A-32B0','32C0-33FF','4DC0-4DFF','A490-A4C6','A4FE-A4FF','A60D-A60F','A673',
- 'A67E','A6F2-A6F7','A700-A716','A720-A721','A789-A78A','A828-A82B','A836-A839','A874-A877',
- 'A8CE-A8CF','A8F8-A8FA','A8FC','A92E-A92F','A95F','A9C1-A9CD','A9DE-A9DF','AA5C-AA5F',
- 'AA77-AA79','AADE-AADF','AAF0-AAF1','AB5B','AB6A-AB6B','ABEB','FB29','FBB2-FBC2',
- 'FD3E-FD4F','FDCF','FDFC-FDFF','FE10-FE19','FE30-FE52','FE54-FE66','FE68-FE6B','FF01-FF0F',
- 'FF1A-FF20','FF3B-FF40','FF5B-FF65','FFE0-FFE6','FFE8-FFEE','FFFC-FFFD','10100-10102',
- '10137-1013F','10179-10189','1018C-1018E','10190-1019C','101A0','101D0-101FC','1039F',
- '103D0','1056F','10857','10877-10878','1091F','1093F','10A50-10A58','10A7F','10AC8',
- '10AF0-10AF6','10B39-10B3F','10B99-10B9C','10D6E','10D8E-10D8F','10EAD','10F55-10F59',
- '10F86-10F89','11047-1104D','110BB-110BC','110BE-110C1','11140-11143','11174-11175',
- '111C5-111C8','111CD','111DB','111DD-111DF','11238-1123D','112A9','113D4-113D5',
- '113D7-113D8','1144B-1144F','1145A-1145B','1145D','114C6','115C1-115D7','11641-11643',
- '11660-1166C','116B9','1173C-1173F','1183B','11944-11946','119E2','11A3F-11A46',
- '11A9A-11A9C','11A9E-11AA2','11B00-11B09','11BE1','11C41-11C45','11C70-11C71','11EF7-11EF8',
- '11F43-11F4F','11FD5-11FF1','11FFF','12470-12474','12FF1-12FF2','16A6E-16A6F','16AF5',
- '16B37-16B3F','16B44-16B45','16D6D-16D6F','16E97-16E9A','16FE2','1BC9C','1BC9F',
- '1CC00-1CCEF','1CD00-1CEB3','1CF50-1CFC3','1D000-1D0F5','1D100-1D126','1D129-1D164',
- '1D16A-1D16C','1D183-1D184','1D18C-1D1A9','1D1AE-1D1EA','1D200-1D241','1D245','1D300-1D356',
- '1D6C1','1D6DB','1D6FB','1D715','1D735','1D74F','1D76F','1D789','1D7A9','1D7C3',
- '1D800-1D9FF','1DA37-1DA3A','1DA6D-1DA74','1DA76-1DA83','1DA85-1DA8B','1E14F','1E2FF',
- '1E5FF','1E95E-1E95F','1ECAC','1ECB0','1ED2E','1EEF0-1EEF1','1F000-1F02B','1F030-1F093',
- '1F0A0-1F0AE','1F0B1-1F0BF','1F0C1-1F0CF','1F0D1-1F0F5','1F10D-1F1AD','1F1E6-1F202',
- '1F210-1F23B','1F240-1F248','1F250-1F251','1F260-1F265','1F300-1F6D7','1F6DC-1F6EC',
- '1F6F0-1F6FC','1F700-1F776','1F77B-1F7D9','1F7E0-1F7EB','1F7F0','1F800-1F80B','1F810-1F847',
- '1F850-1F859','1F860-1F887','1F890-1F8AD','1F8B0-1F8BB','1F8C0-1F8C1','1F900-1FA53',
- '1FA60-1FA6D','1FA70-1FA7C','1FA80-1FA89','1FA8F-1FAC6','1FACE-1FADC','1FADF-1FAE9',
- '1FAF0-1FAF8','1FB00-1FB92','1FB94-1FBEF',
- ];
- function mdIsUnicodePunct(cp) {
- var lo = 0, hi = MD_UNICODE_PUNCT_RANGES.length - 1;
- while (lo <= hi) {
- var mid = (lo + hi) >> 1;
- var dash = MD_UNICODE_PUNCT_RANGES[mid].indexOf('-');
- var a, b;
- if (dash < 0) { a = b = parseInt(MD_UNICODE_PUNCT_RANGES[mid], 16); }
- else {
- a = parseInt(MD_UNICODE_PUNCT_RANGES[mid].slice(0, dash), 16);
- b = parseInt(MD_UNICODE_PUNCT_RANGES[mid].slice(dash + 1), 16);
- }
- if (cp < a) hi = mid - 1;
- else if (cp > b) lo = mid + 1;
- else return true;
- }
- return false;
- }
- function mdIsPunct(ch) {
- if (ch === '' || ch == null) return false;
- if (MD_ASCII_PUNCT_TEST_RE.test(ch)) return true;
- var cp = ch.charCodeAt(0);
- if (cp < 0xA1) return false;
- // combine a surrogate pair into one code point
- if (cp >= 0xD800 && cp <= 0xDBFF && ch.length > 1) {
- var lo = ch.charCodeAt(1);
- if (lo >= 0xDC00 && lo <= 0xDFFF) cp = 0x10000 + ((cp - 0xD800) << 10) + (lo - 0xDC00);
- }
- return mdIsUnicodePunct(cp);
- }
- /**
- * String.fromCharCode with surrogate-pair support.
- * @param {number} cp
- * @returns {string}
- */
- function mdFromCodePoint(cp) {
- if (cp == null || cp < 0 || cp > 0x10FFFF || (cp >= 0xD800 && cp <= 0xDFFF)) return '\uFFFD';
- if (cp <= 0xFFFF) return String.fromCharCode(cp);
- var c = cp - 0x10000;
- return String.fromCharCode(0xD800 + (c >> 10), 0xDC00 + (c & 0x3FF));
- }
- var mdEntityMap = null;
- /** Parse MD_ENTITIES_PACKED into a name -> string map (once). */
- function mdGetEntityMap() {
- if (mdEntityMap) return mdEntityMap;
- var map = {}, recs = MD_ENTITIES_PACKED.split('\n');
- for (var i = 0; i < recs.length; i++) {
- var sp = recs[i].indexOf(' ');
- if (sp < 0) continue;
- var cps = recs[i].slice(sp + 1).split(',');
- var s = '';
- for (var j = 0; j < cps.length; j++) s += mdFromCodePoint(parseInt(cps[j], 10));
- map[recs[i].slice(0, sp)] = s;
- }
- mdEntityMap = map;
- return map;
- }
- /**
- * Resolve an entity reference at the start of `s`; null when invalid.
- * @param {string} s
- * @returns {?string}
- */
- function mdReplaceEntity(s) {
- var m = s.match(MD_ENTITY_HERE_RE);
- if (!m) return null;
- var body = m[0].slice(1, -1);
- if (body.charAt(0) === '#') {
- var num = body.charAt(1) === 'x' || body.charAt(1) === 'X'
- ? parseInt(body.slice(2), 16)
- : parseInt(body.slice(1), 10);
- if (isNaN(num) || num === 0 || num > 0x10FFFF) return '\uFFFD';
- return mdFromCodePoint(num);
- }
- var map = mdGetEntityMap();
- return Object.prototype.hasOwnProperty.call(map, body) ? map[body] : null;
- }
- /**
- * Replace backslash escapes and entity references (spec 2.2/2.3). Used on
- * link destinations, titles, labels and code info strings.
- * @param {string} s
- * @returns {string}
- */
- function mdUnescapeString(s) {
- if (s.indexOf('\\') < 0 && s.indexOf('&') < 0) return s;
- var out = '', i = 0, ch, rep, m;
- while (i < s.length) {
- ch = s.charAt(i);
- if (ch === '\\' && MD_ESCAPABLE.indexOf(s.charAt(i + 1)) >= 0) {
- out += s.charAt(i + 1);
- i += 2;
- continue;
- }
- if (ch === '&') {
- rep = mdReplaceEntity(s.slice(i));
- if (rep !== null) {
- m = s.slice(i).match(MD_ENTITY_HERE_RE);
- out += rep;
- i += m[0].length;
- continue;
- }
- }
- out += ch;
- i++;
- }
- return out;
- }
- // --- inline nodes -----------------------------------------------------------
- /**
- * Create an inline node. Types: text, softbreak, code, emph, strong,
- * link, image, html (escaped text).
- */
- function mdInlineNode(type, literal) {
- return { type: type, literal: literal == null ? '' : literal,
- parent: null, next: null, prev: null,
- firstChild: null, lastChild: null,
- destination: null, title: null, hardBreak: false };
- }
- function mdAppendChild(parent, node) {
- node.parent = parent;
- node.prev = parent.lastChild;
- if (parent.lastChild) parent.lastChild.next = node;
- else parent.firstChild = node;
- parent.lastChild = node;
- return node;
- }
- function mdUnlink(node) {
- if (node.prev) node.prev.next = node.next;
- else if (node.parent) node.parent.firstChild = node.next;
- if (node.next) node.next.prev = node.prev;
- else if (node.parent) node.parent.lastChild = node.prev;
- node.parent = null;
- node.next = null;
- node.prev = null;
- }
- function mdInsertAfter(node, sibling) {
- sibling.parent = node.parent;
- sibling.next = node.next;
- sibling.prev = node;
- if (node.next) node.next.prev = sibling;
- else if (node.parent) node.parent.lastChild = sibling;
- node.next = sibling;
- }
- /** Collect a node's children into an array (for rendering). */
- function mdChildren(node) {
- var out = [], c = node.firstChild;
- while (c) { out.push(c); c = c.next; }
- return out;
- }
- // --- the subject scanner ----------------------------------------------------
- /**
- * Parse the inline content of one leaf block.
- * @param {string} subject already-trimmed paragraph/heading text
- * @param {Object} refmap normalised-label -> { destination, title }
- * @returns {Object} a synthetic parent whose children are the inlines
- */
- function mdParseInlines(subject, refmap) {
- var block = { parent: null, next: null, prev: null,
- firstChild: null, lastChild: null, type: 'root' };
- var pos = 0;
- var delimiters = null; // linked list, newest first
- var brackets = null; // linked list, newest first
- function text(s) { return mdAppendChild(block, mdInlineNode('text', s)); }
- function peek() { return pos < subject.length ? subject.charAt(pos) : ''; }
- function match(re) {
- var m = re.exec(subject.slice(pos));
- if (m) pos += m[0].length;
- return m;
- }
- function spnl() {
- match(/^ *(?:\n *)?/);
- return true;
- }
- // -- emphasis delimiter bookkeeping --
- function scanDelims(cc) {
- var numdelims = 0, startpos = pos;
- while (peek() === cc) { numdelims++; pos++; }
- // adjacent characters, taking surrogate pairs as one character
- var charBefore = startpos === 0 ? '\n'
- : (mdIsHighSurrogate(subject.charAt(startpos - 1))
- ? subject.slice(startpos - 2, startpos)
- : subject.charAt(startpos - 1));
- var nextCh = peek();
- var charAfter = nextCh === '' ? '\n'
- : (mdIsHighSurrogate(nextCh) ? subject.substr(pos, 2) : nextCh);
- var afterWs = /^\s/.test(charAfter);
- var beforeWs = /^\s/.test(charBefore);
- var afterPunct = mdIsPunct(charAfter);
- var beforePunct = mdIsPunct(charBefore);
- var leftFlanking = !afterWs && (!afterPunct || beforeWs || beforePunct);
- var rightFlanking = !beforeWs && (!beforePunct || afterWs || afterPunct);
- var canOpen, canClose;
- if (cc === '_') {
- canOpen = leftFlanking && (!rightFlanking || beforePunct);
- canClose = rightFlanking && (!leftFlanking || afterPunct);
- } else {
- canOpen = leftFlanking;
- canClose = rightFlanking;
- }
- pos = startpos;
- return { numdelims: numdelims, canOpen: canOpen, canClose: canClose };
- }
- function handleDelim(cc) {
- var res = scanDelims(cc);
- if (!res || res.numdelims === 0) return false;
- var node = text(subject.slice(pos, pos + res.numdelims));
- pos += res.numdelims;
- if (res.canOpen || res.canClose) {
- var d = { cc: cc, numdelims: res.numdelims, origdelims: res.numdelims,
- node: node, previous: delimiters, next: null,
- canOpen: res.canOpen, canClose: res.canClose };
- if (delimiters) delimiters.next = d;
- delimiters = d;
- }
- return true;
- }
- function removeDelimiter(d) {
- if (d.previous) d.previous.next = d.next;
- if (d.next === null) delimiters = d.previous;
- else d.next.previous = d.previous;
- }
- function removeDelimitersBetween(bottom, top) {
- if (bottom.next !== top) { bottom.next = top; top.previous = bottom; }
- }
- /** True for the high half of a UTF-16 surrogate pair. */
- function mdIsHighSurrogate(ch) {
- var c = ch.charCodeAt(0);
- return c >= 0xD800 && c <= 0xDBFF;
- }
- /** Emphasis resolution over the delimiter stack (spec 6.2). */
- function processEmphasis(stackBottom) {
- var openersBottom = new Array(8);
- for (var i = 0; i < 8; i++) openersBottom[i] = stackBottom;
- var closer = delimiters;
- while (closer !== null && closer.previous !== stackBottom) closer = closer.previous;
- var opener, openerInl, closerInl, useDelims, tmp, next, openerFound, oddMatch;
- while (closer !== null) {
- if (!closer.canClose) { closer = closer.next; continue; }
- opener = closer.previous;
- openerFound = false;
- // openers_bottom index: 0..3 for '_', 4..7 for '*' — see rule of 3
- var idx = (closer.cc === '_' ? 0 : 4) + (closer.canOpen ? 2 : 0) + (closer.origdelims % 3 === 0 ? 0 : 1);
- while (opener !== null && opener !== stackBottom && opener !== openersBottom[idx]) {
- oddMatch = (closer.canOpen || opener.canClose) &&
- closer.origdelims % 3 !== 0 &&
- (opener.origdelims + closer.origdelims) % 3 === 0;
- if (opener.cc === closer.cc && opener.canOpen && !oddMatch) { openerFound = true; break; }
- opener = opener.previous;
- }
- var oldCloser = closer;
- if (!openerFound) {
- openersBottom[idx] = oldCloser.previous;
- if (!oldCloser.canOpen) removeDelimiter(oldCloser);
- closer = closer.next;
- continue;
- }
- useDelims = closer.numdelims >= 2 && opener.numdelims >= 2 ? 2 : 1;
- openerInl = opener.node;
- closerInl = closer.node;
- opener.numdelims -= useDelims;
- closer.numdelims -= useDelims;
- openerInl.literal = openerInl.literal.slice(0, openerInl.literal.length - useDelims);
- closerInl.literal = closerInl.literal.slice(0, closerInl.literal.length - useDelims);
- var emph = mdInlineNode(useDelims === 1 ? 'emph' : 'strong');
- tmp = openerInl.next;
- while (tmp && tmp !== closerInl) {
- next = tmp.next;
- mdUnlink(tmp);
- mdAppendChild(emph, tmp);
- tmp = next;
- }
- mdInsertAfter(openerInl, emph);
- removeDelimitersBetween(opener, closer);
- if (opener.numdelims === 0) { mdUnlink(openerInl); removeDelimiter(opener); }
- if (closer.numdelims === 0) {
- mdUnlink(closerInl);
- var after = closer.next;
- removeDelimiter(closer);
- closer = after;
- }
- // when the closer still has delimiters left, stay on it: the next
- // iteration searches for another opener further left
- }
- while (delimiters !== null && delimiters !== stackBottom) removeDelimiter(delimiters);
- }
- // -- link / image machinery --
- /**
- * Parse a link title at pos; returns the unescaped title or null.
- * Uses the linear scanner (no regex backtracking).
- */
- function parseLinkTitle() {
- var res = mdScanLinkTitle(subject, pos);
- if (!res) return null;
- pos += res.len;
- return mdUnescapeString(res.text);
- }
- /** Parse `<dest>` or a bare destination; returns normalised URI or null. */
- function parseLinkDestination() {
- var m = match(MD_LINK_DEST_BRACES_RE);
- if (m) return mdNormalizeUri(mdUnescapeString(m[0].slice(1, -1)));
- if (peek() === '<') return null;
- var savepos = pos, openparens = 0, c;
- while ((c = peek()) !== '') {
- if (c === '\\' && subject.charAt(pos + 1) !== '' &&
- MD_ESCAPABLE.indexOf(subject.charAt(pos + 1)) >= 0) {
- pos += 1;
- if (peek() !== '') pos += 1;
- } else if (c === '(') { pos++; openparens++; }
- else if (c === ')') { if (openparens < 1) break; pos++; openparens--; }
- else if (MD_WS_CHAR_RE.test(c)) break;
- else pos++;
- }
- if (pos === savepos && c !== ')') return null;
- if (openparens !== 0) { pos = savepos; return null; }
- return mdNormalizeUri(mdUnescapeString(subject.slice(savepos, pos)));
- }
- /**
- * Parse `[...]` at pos; returns the consumed length (including both
- * brackets), or 0 when there is no well-formed label. A label may not
- * contain a blank line and is capped at 1000 characters.
- */
- function parseLinkLabel() {
- if (subject.charAt(pos) !== '[') return 0;
- var i = pos + 1, ch;
- while (i < subject.length) {
- ch = subject.charAt(i);
- if (ch === '\\') { i += 2; continue; }
- if (ch === '[') return 0; // nested brackets are not labels
- if (ch === ']') break;
- i++;
- }
- if (subject.charAt(i) !== ']') return 0;
- var len = i + 1 - pos;
- var label = subject.slice(pos, i + 1);
- if (len > 1001) return 0;
- if (/\n[ \t]*\n/.test(label)) return 0; // no blank lines inside
- return len;
- }
- function addBracket(node, index, image) {
- if (brackets) brackets.bracketAfter = true;
- brackets = { node: node, previous: brackets, previousDelimiter: delimiters,
- index: index, image: image, active: true, bracketAfter: false };
- }
- function removeBracket() { brackets = brackets.previous; }
- function parseCloseBracket() {
- var startpos = pos, isImage, dest, title, matched = false, reflabel;
- pos += 1;
- var opener = brackets;
- if (opener === null) { text(']'); return true; }
- if (!opener.active) { text(']'); removeBracket(); return true; }
- isImage = opener.image;
- var savepos = pos;
- if (peek() === '(') {
- pos++;
- if (spnl() && (dest = parseLinkDestination()) !== null) {
- var beforeTitle = pos;
- spnl();
- // A title is only allowed when whitespace separated it from the
- // destination (spec: "optional... preceded by a space").
- if (pos !== beforeTitle) {
- var tryTitle = parseLinkTitle();
- if (tryTitle !== null) {
- title = tryTitle;
- spnl();
- } else {
- pos = beforeTitle;
- }
- }
- if (peek() === ')') {
- pos += 1;
- matched = true;
- } else {
- pos = savepos;
- }
- } else {
- pos = savepos;
- }
- }
- if (!matched) {
- var beforelabel = pos;
- var n = parseLinkLabel();
- if (n > 2) {
- // full reference: [text][label]
- reflabel = subject.slice(beforelabel, beforelabel + n);
- pos = beforelabel + n;
- } else if (n === 2 && !opener.bracketAfter) {
- // collapsed reference: [text][] — consume the empty label
- reflabel = '[' + subject.slice(opener.index, startpos) + ']';
- pos = beforelabel + n;
- } else if (!opener.bracketAfter) {
- // shortcut reference: [text]
- reflabel = '[' + subject.slice(opener.index, startpos) + ']';
- }
- if (n === 0) pos = savepos;
- if (reflabel) {
- var link = refmap[mdNormalizeReference(reflabel)];
- if (link) { dest = link.destination; title = link.title; matched = true; }
- }
- }
- if (matched) {
- var node = mdInlineNode(isImage ? 'image' : 'link');
- node.destination = dest == null ? '' : dest;
- node.title = title == null ? '' : title;
- var tmp = opener.node.next, next;
- while (tmp) {
- next = tmp.next;
- mdUnlink(tmp);
- mdAppendChild(node, tmp);
- tmp = next;
- }
- // the link takes the opener's position in the parent's child list
- mdInsertAfter(opener.node, node);
- processEmphasis(opener.previousDelimiter);
- removeBracket();
- mdUnlink(opener.node);
- if (!isImage) {
- var b = brackets;
- while (b !== null) { if (!b.image) b.active = false; b = b.previous; }
- }
- return true;
- }
- removeBracket();
- // NB: `startpos` was captured before consuming ']', so pos now sits
- // just after it — do not rewind onto the bracket again.
- pos = startpos + 1;
- text(']');
- return true;
- }
- // -- autolinks and raw HTML (neutralised) --
- var MD_EMAIL_AUTOLINK_RE = /^<([a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)>/;
- var MD_AUTOLINK_RE = /^<[A-Za-z][A-Za-z0-9.+-]{1,31}:[^<>\x00-\x20]*>/i;
- /**
- * Try an autolink at pos. Returns the node or null.
- */
- function parseAutolink() {
- var rest = subject.slice(pos);
- var m = rest.match(MD_AUTOLINK_RE);
- var node;
- if (m) {
- node = mdInlineNode('link');
- node.destination = mdNormalizeUri(m[0].slice(1, -1));
- node.autolinkText = m[0].slice(1, -1);
- mdAppendChild(block, node);
- mdAppendChild(node, mdInlineNode('text', m[0].slice(1, -1)));
- pos += m[0].length;
- return node;
- }
- m = rest.match(MD_EMAIL_AUTOLINK_RE);
- if (m) {
- node = mdInlineNode('link');
- node.destination = 'mailto:' + m[1];
- node.autolinkText = m[1];
- mdAppendChild(block, node);
- mdAppendChild(node, mdInlineNode('text', m[1]));
- pos += m[0].length;
- return node;
- }
- return null;
- }
- /**
- * Match a raw HTML tag at pos. SECURITY: the matched text is returned so
- * the caller can render it escaped — it is never emitted as markup.
- */
- function parseHtmlTag() {
- var raw = mdScanHtmlTag(subject, pos);
- if (!raw) return null;
- var node = mdAppendChild(block, mdInlineNode('html'));
- node.literal = raw;
- pos += raw.length;
- return node;
- }
- // -- the main dispatch loop --
- while (pos < subject.length) {
- var c = peek();
- var res = false;
- switch (c) {
- case '\n':
- pos++;
- {
- var lastc = block.lastChild;
- if (lastc && lastc.type === 'text' && / $/.test(lastc.literal)) {
- var hard = / {2}$/.test(lastc.literal);
- lastc.literal = lastc.literal.replace(MD_FINAL_SPACE_RE, '');
- var sb = mdAppendChild(block, mdInlineNode('softbreak'));
- sb.hardBreak = hard;
- } else {
- mdAppendChild(block, mdInlineNode('softbreak'));
- }
- match(/^ */);
- }
- break;
- case '\\':
- if (subject.charAt(pos + 1) === '\n') {
- pos += 2;
- var hb = mdAppendChild(block, mdInlineNode('softbreak'));
- hb.hardBreak = true;
- match(/^ */);
- } else if (subject.charAt(pos + 1) !== '' &&
- MD_ESCAPABLE.indexOf(subject.charAt(pos + 1)) >= 0) {
- text(subject.charAt(pos + 1));
- pos += 2;
- } else {
- text('\\');
- pos++;
- }
- break;
- case '`':
- {
- // opening run, then the next run of backticks of the SAME length
- var ticks = subject.slice(pos).match(MD_TICKS_HERE_RE)[0];
- var afterOpen = pos + ticks.length;
- var searchPos = afterOpen, run;
- var codeNode = null;
- while ((run = subject.slice(searchPos).match(/^[\s\S]*?(`+)/)) && run[1]) {
- var runStart = searchPos + run[0].length - run[1].length;
- if (run[1].length === ticks.length) {
- // newline -> space; spaces *before* a newline are dropped
- // (spec: "line endings are replaced by spaces... preceded
- // by a space are removed")
- var content = subject.slice(afterOpen, runStart)
- .replace(/ *\n/g, '\n').replace(/\n/g, ' ');
- if (/^ /.test(content) && / $/.test(content) && content.replace(/ /g, '') !== '') {
- content = content.slice(1, content.length - 1);
- }
- codeNode = mdAppendChild(block, mdInlineNode('code', content));
- pos = runStart + run[1].length;
- break;
- }
- searchPos = runStart + run[1].length;
- }
- if (!codeNode) {
- text(ticks);
- pos = afterOpen;
- }
- }
- break;
- case '*':
- case '_':
- handleDelim(c);
- break;
- case '[':
- {
- var node = text('[');
- addBracket(node, pos + 1, false);
- pos++;
- }
- break;
- case '!':
- if (subject.charAt(pos + 1) === '[') {
- var n2 = text('![');
- addBracket(n2, pos + 2, true);
- pos += 2;
- } else {
- text('!');
- pos++;
- }
- break;
- case ']':
- parseCloseBracket();
- break;
- case '<':
- if (parseAutolink()) break;
- if (parseHtmlTag()) break;
- text('<');
- pos++;
- break;
- case '&':
- {
- var rep = mdReplaceEntity(subject.slice(pos));
- if (rep !== null) {
- text(rep);
- pos += subject.slice(pos).match(MD_ENTITY_HERE_RE)[0].length;
- } else {
- text('&');
- pos++;
- }
- }
- break;
- default:
- {
- var m = subject.slice(pos).match(/^[^\n`\\[\]!<&*_]+/);
- if (!m) { text(c); pos++; }
- else { text(m[0]); pos += m[0].length; }
- }
- }
- }
- processEmphasis(null);
- return block;
- }
- // ---------------------------------------------------------------------------
- // Markdown HTML rendering
- // ---------------------------------------------------------------------------
- /**
- * Escape the five HTML-significant characters. `"` becomes `"` (also
- * safe inside double-quoted attributes), matching cmark.
- * @param {string} s
- * @returns {string}
- */
- function mdEscape(s) {
- return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
- .replace(/"/g, '"');
- }
- /**
- * Parse (once) and render a leaf block's inline content. The parsed inline
- * tree is cached on the block so image alt text can reuse it.
- */
- function mdLeafInlines(node, refmap) {
- if (!node._inlines) {
- node._inlines = mdParseInlines(node.strings.join('\n').trim(), refmap);
- }
- return node._inlines;
- }
- /** Render inline nodes to HTML (children of a paragraph/heading). */
- function mdRenderInlines(node) {
- var out = '', c = node.firstChild;
- while (c) {
- switch (c.type) {
- case 'text':
- out += mdEscape(c.literal);
- break;
- case 'softbreak':
- out += c.hardBreak ? '<br />\n' : '\n';
- break;
- case 'code':
- out += '<code>' + mdEscape(c.literal) + '</code>';
- break;
- case 'emph':
- out += '<em>' + mdRenderInlines(c) + '</em>';
- break;
- case 'strong':
- out += '<strong>' + mdRenderInlines(c) + '</strong>';
- break;
- case 'link':
- out += '<a href="' + safeMarkdownUrl(mdEscapeAttr(c.destination)) + '"' +
- (c.title ? ' title="' + mdEscapeAttr(c.title) + '"' : '') + '>' +
- mdRenderInlines(c) + '</a>';
- break;
- case 'image':
- out += '<img src="' + safeMarkdownUrl(mdEscapeAttr(c.destination)) + '"' +
- ' alt="' + mdImageAlt(c) + '"' +
- (c.title ? ' title="' + mdEscapeAttr(c.title) + '"' : '') + ' />';
- break;
- case 'html':
- out += mdEscape(c.literal);
- break;
- default:
- out += mdEscape(c.literal || '');
- }
- c = c.next;
- }
- return out;
- }
- /** Plain-text rendering of image alt text (markdown stripped). */
- function mdImageAlt(node) {
- var out = '', c = node.firstChild;
- while (c) {
- if (c.type === 'text' || c.type === 'code' || c.type === 'html') out += c.literal;
- else if (c.type === 'softbreak') out += c.hardBreak ? '\n' : '\n';
- else if (c.firstChild) out += mdImageAlt(c);
- c = c.next;
- }
- return mdEscapeAttr(out);
- }
- /** Escape for a double-quoted attribute value. */
- function mdEscapeAttr(s) {
- return String(s).replace(/&/g, '&').replace(/"/g, '"')
- .replace(/</g, '<').replace(/>/g, '>');
- }
- /**
- * Output buffer that suppresses repeated newlines (cmark's `cr`).
- */
- function mdOut() {
- // `last` starts as a newline so the very first cr() is a no-op
- return { s: '', last: '\n' };
- }
- /** Append a literal string. */
- function mdLit(out, s) {
- if (!s) return;
- out.s += s;
- out.last = s.charAt(s.length - 1);
- }
- /** Append a newline unless the output already ends with one. */
- function mdCr(out) {
- if (out.last !== '\n') mdLit(out, '\n');
- }
- /**
- * Render one block node (and its children) to HTML. `tight` is the
- * enclosing list's tightness: tight lists suppress `<p>` wrappers.
- */
- function mdRenderBlocks(node, tight, out, refmap) {
- var i, child;
- switch (node.type) {
- case 'document':
- for (i = 0; i < node.children.length; i++) mdRenderBlocks(node.children[i], tight, out, refmap);
- break;
- case 'paragraph':
- // in a tight list the paragraph renders bare
- if (tight) { mdLit(out, mdRenderInlines(mdLeafInlines(node, refmap))); }
- else {
- mdCr(out);
- mdLit(out, '<p>');
- mdLit(out, mdRenderInlines(mdLeafInlines(node, refmap)));
- mdLit(out, '</p>');
- mdCr(out);
- }
- break;
- case 'heading':
- mdCr(out);
- mdLit(out, '<h' + node.level + '>');
- mdLit(out, mdRenderInlines(mdLeafInlines(node, refmap)));
- mdLit(out, '</h' + node.level + '>');
- mdCr(out);
- break;
- case 'thematic':
- mdCr(out);
- mdLit(out, '<hr />');
- mdCr(out);
- break;
- case 'code':
- mdCr(out);
- var info = node.info ? node.info.split(/\s+/)[0] : '';
- var attrs = '';
- if (info) attrs = ' class="language-' + mdEscapeAttr(info) + '"';
- mdLit(out, '<pre><code' + attrs + '>' + mdEscape(node.literal) + '</code></pre>');
- mdCr(out);
- break;
- case 'blockquote':
- mdCr(out);
- mdLit(out, '<blockquote>');
- mdCr(out);
- // cmark unwraps paragraphs only when their grandparent is a tight
- // list; inside a blockquote they always keep their <p>.
- for (i = 0; i < node.children.length; i++) mdRenderBlocks(node.children[i], false, out, refmap);
- mdCr(out);
- mdLit(out, '</blockquote>');
- mdCr(out);
- break;
- case 'list':
- mdCr(out);
- var tag = node.listData.type === 'ordered' ? 'ol' : 'ul';
- var start = '';
- if (tag === 'ol' && node.listData.start != null && node.listData.start !== 1) {
- start = ' start="' + node.listData.start + '"';
- }
- mdLit(out, '<' + tag + start + '>');
- mdCr(out);
- for (i = 0; i < node.children.length; i++) mdRenderBlocks(node.children[i], node.tight, out, refmap);
- mdCr(out);
- mdLit(out, '</' + tag + '>');
- mdCr(out);
- break;
- case 'item':
- mdLit(out, '<li>');
- for (i = 0; i < node.children.length; i++) {
- // tightness applies to the item's own paragraphs and lists;
- // blockquote contents are always loose.
- mdRenderBlocks(node.children[i], node.children[i].type === 'blockquote' ? false : tight, out, refmap);
- }
- mdLit(out, '</li>');
- mdCr(out);
- break;
- default:
- break;
- }
- }
- /**
- * Render markdown to safe HTML.
- *
- * CommonMark 0.31.2 minus raw HTML (escaped instead, see the note at the
- * top of the markdown section) and minus HTML-block constructs that only
- * exist to feed raw HTML through.
- * @param {string} raw markdown source
- * @returns {string} HTML safe for `innerHTML`
- */
- function renderMarkdown(raw) {
- var parser = mdParseDocument(raw);
- var out = mdOut();
- mdRenderBlocks(parser.doc, false, out, parser.refmap);
- return out.s;
- }
- /**
- * Demote child header tags by N levels (h1 → h2, etc.), capping at h6.
- */
- function handleHDemotion(el) {
- var attr = el.getAttribute('stm-h-demotion');
- if (!attr) return;
- var n = parseInt(attr, 10);
- if (isNaN(n) || n <= 0) return;
- el.querySelectorAll('h1,h2,h3,h4,h5,h6').forEach(function (h) {
- var level = parseInt(h.tagName.charAt(1), 10);
- var newLevel = Math.min(level + n, 6);
- if (newLevel === level) return;
- var replacement = document.createElement('h' + newLevel);
- for (var i = 0; i < h.attributes.length; i++)
- replacement.setAttribute(h.attributes[i].name, h.attributes[i].value);
- while (h.firstChild) replacement.appendChild(h.firstChild);
- h.replaceWith(replacement);
- });
- }
- /**
- * Bind `stm-text` / `stm-html` / `stm-markdown`. Per the "leave original DOM
- * content" policy, an unresolved value (`undefined`) leaves the element
- * untouched; otherwise the value is stringified (`null` becomes empty).
- */
- function handleTextHtml(el, scope) {
- if (el.hasAttribute('stm-text')) {
- var text = evalExpr(el.getAttribute('stm-text'), scope);
- if (text !== undefined) el.textContent = text === null ? '' : String(text);
- }
- if (el.hasAttribute('stm-html')) {
- var html = evalExpr(el.getAttribute('stm-html'), scope);
- if (html !== undefined) el.innerHTML = html === null ? '' : String(html);
- }
- if (el.hasAttribute('stm-markdown')) {
- var md = evalExpr(el.getAttribute('stm-markdown'), scope);
- if (md !== undefined) el.innerHTML = renderMarkdown(md === null ? '' : String(md));
- }
- // stm-h-demotion runs after stm-html / stm-markdown so the rendered
- // headers are present in the DOM.
- if (el.hasAttribute('stm-h-demotion')) handleHDemotion(el);
- }
- /**
- * Expand a loop holder: reconcile its instances against the current array.
- * Keyed loops (`stm-key`) reuse DOM nodes for unchanged keys to preserve
- * focus/selection/input state; unkeyed loops rebuild wholesale.
- */
- function handleLoop(el, scope) {
- var info = getStmFor(el);
- if (!info) return;
- var template = templates.get(el);
- if (!template) {
- template = el.cloneNode(true);
- stripLoopAttrs(template);
- templates.set(el, template);
- }
- var raw = evalExpr(info.expr, scope);
- if (raw === undefined) {
- // No value for the source path yet: clear instances and restore the
- // server-rendered holder content (progressive enhancement).
- var prev = instancesByHolder.get(el) || [];
- prev.forEach(function (n) { n.remove(); });
- instancesByHolder.set(el, []);
- if (el.getAttribute('data-stm-active') === '1') {
- el.removeAttribute('data-stm-active');
- el.removeAttribute('hidden');
- }
- return;
- }
- var arr = Array.isArray(raw) ? raw : [];
- // Activate: hide the holder so only rendered instances are visible.
- if (el.getAttribute('data-stm-active') !== '1') {
- el.setAttribute('data-stm-active', '1');
- el.setAttribute('hidden', '');
- }
- var keyExpr = el.getAttribute('stm-key');
- var next = [];
- if (keyExpr) {
- var oldByKey = new Map();
- (instancesByHolder.get(el) || []).forEach(function (n) {
- if (n.__stmKey !== undefined) oldByKey.set(n.__stmKey, n);
- });
- var used = new Set();
- arr.forEach(function (item) {
- var child = childScope(scope, info.varName, item);
- var key = evalExpr(keyExpr, child);
- var node = (key !== undefined && !used.has(key)) ? oldByKey.get(key) : undefined;
- if (node) {
- used.add(key);
- processElement(node, child);
- } else {
- node = template.cloneNode(true);
- node.__stmKey = key;
- instanceNodes.add(node);
- processElement(node, child);
- }
- next.push(node);
- });
- oldByKey.forEach(function (n, key) { if (!used.has(key)) n.remove(); });
- } else {
- (instancesByHolder.get(el) || []).forEach(function (n) { n.remove(); });
- arr.forEach(function (item) {
- var child = childScope(scope, info.varName, item);
- var node = template.cloneNode(true);
- instanceNodes.add(node);
- processElement(node, child);
- next.push(node);
- });
- }
- // Place instances in order, immediately after the holder.
- var ref = el;
- next.forEach(function (node) {
- if (node !== ref.nextSibling) ref.parentNode.insertBefore(node, ref.nextSibling);
- ref = node;
- });
- instancesByHolder.set(el, next);
- }
- /**
- * Process one element's bindings (and recurse). Loop holders are handled by
- * {@link handleLoop}; `stm-else-if` / `stm-else` are owned by their `stm-if`.
- */
- function processElement(el, scope) {
- if (getStmFor(el)) { handleLoop(el, scope); return; }
- if (el.hasAttribute('stm-else-if') || el.hasAttribute('stm-else')) return;
- if (el.hasAttribute('stm-if')) {
- var active = handleIfChain(el, scope);
- if (active) processInner(active, scope);
- return;
- }
- processInner(el, scope);
- }
- /**
- * Collect `stm-def-{name}-as` attributes on an element into a child scope.
- * Each expression is evaluated against the incoming scope (so the new
- * variables cannot reference each other within the same element), and the
- * results are added to a child scope visible to the element and its
- * descendants. Multiple defs on one element are supported. If there are no
- * defs, the original scope is returned unchanged.
- * @param {Element} el
- * @param {object} scope
- * @returns {object}
- */
- function applyDefs(el, scope) {
- var attrs = el.attributes;
- var child = null;
- for (var i = 0; i < attrs.length; i++) {
- var name = attrs[i].name;
- if (name.indexOf('stm-def-') === 0 && name.slice(-3) === '-as') {
- var varName = name.slice(8, -3);
- if (!varName) continue;
- if (!child) child = Object.create(scope || null);
- child[varName] = evalExpr(attrs[i].value, scope);
- }
- }
- return child || scope;
- }
- /** Bind the non-control-flow attributes and recurse into children. */
- function processInner(el, scope) {
- var s = applyDefs(el, scope); // local definitions: element + descendants
- el.__stmScope = s; // latest scope, used when an action fires
- handleClass(el, s);
- handleAttribute(el, s);
- handleDisabled(el, s);
- handleTextHtml(el, s);
- wireAction(el);
- render(el, s);
- }
- /**
- * Walk an element's children, processing each. Loop instance nodes are
- * skipped here (they are owned and processed by their holder).
- */
- function render(root, scope) {
- if (!root || !root.children) return;
- // Snapshot the children: processing mutates the DOM (detaching branches,
- // inserting loop instances) and a live HTMLCollection would shift indices.
- var children = Array.prototype.slice.call(root.children);
- for (var i = 0; i < children.length; i++) {
- var el = children[i];
- if (instanceNodes.has(el)) continue;
- processElement(el, scope);
- }
- }
- /** Re-render the whole document against the current state. */
- /**
- * Evaluate every `<link rel="stm-guard">` in the document head. A guard whose
- * `require` predicate is false redirects the page to its `href`.
- *
- * Guards marked `pre-entrypoint` are evaluated on every cycle (including the
- * initial, pre-entrypoint render, which uses only hydrated state); guards
- * without it are evaluated only once the entrypoint has loaded. On every later
- * evaluate cycle (set/clear) all guards are re-checked, so logging out, for
- * example, can bounce the user off a guarded page.
- */
- function evaluateGuards() {
- if (guardRedirected) return;
- var scope = stateScope();
- var guards = document.querySelectorAll('link[rel~="stm-guard"]');
- for (var i = 0; i < guards.length; i++) {
- var g = guards[i];
- var preEntrypoint = g.hasAttribute('pre-entrypoint');
- if (!preEntrypoint && !entrypointLoaded) continue;
- var require = g.getAttribute('require');
- if (!require) continue;
- if (!evalExpr(require, scope)) {
- guardRedirected = true;
- var href = g.getAttribute('href') || '/';
- console.warn('[statum] guard failed (' + require + '); redirecting to ' + href);
- window.location.href = href;
- return;
- }
- }
- }
- // ---------------------------------------------------------------------------
- // Evaluation hooks (no-arg callbacks before/after each render cycle)
- // ---------------------------------------------------------------------------
- var beforeHooks = [];
- var afterHooks = [];
- function renderAll() {
- if (guardRedirected) return;
- beforeHooks.forEach(function (fn) { try { fn(); } catch (e) { console.error('[statum] beforeEvaluate hook error', e); } });
- try { render(document.body, stateScope()); }
- catch (e) { console.error('[statum] render error', e); }
- afterHooks.forEach(function (fn) { try { fn(); } catch (e) { console.error('[statum] afterEvaluate hook error', e); } });
- evaluateGuards();
- }
- // ---------------------------------------------------------------------------
- // HTML API: actions
- // ---------------------------------------------------------------------------
- /**
- * Collect data for an action trigger: `stm-data-{key}` attributes plus, for a
- * form, its named inputs.
- * @param {HTMLElement} el
- * @returns {object}
- */
- function collectData(el) {
- var data = {};
- var attrs = el.attributes;
- for (var i = 0; i < attrs.length; i++) {
- var name = attrs[i].name;
- if (name.indexOf('stm-data-') === 0) data[name.slice('stm-data-'.length)] = attrs[i].value;
- }
- if (el.tagName === 'FORM') {
- var fd = new FormData(el);
- fd.forEach(function (value, key) {
- data[key] = value instanceof File ? value.name : String(value);
- });
- }
- return data;
- }
- /**
- * Toggle the busy state of an action element: disables the element and its
- * descendant form controls and applies `stm-busy-class` classes while busy.
- *
- * On un-busy the disabled state is not "restored" to a captured snapshot
- * (that would clobber a `stm-disabled` value that `renderAll` applied during
- * the response); instead the nodes are re-enabled and `stm-disabled` is
- * re-evaluated, which re-disables any that should remain disabled.
- */
- function setBusyState(el, busy) {
- var nodes = [el].concat(Array.prototype.slice.call(
- el.querySelectorAll('button,input,select,textarea,fieldset')));
- var busyClasses = (el.getAttribute('stm-busy-class') || '').split(/\s+/).filter(Boolean);
- if (busy) {
- nodes.forEach(function (n) { n.setAttribute('disabled', ''); });
- busyClasses.forEach(function (c) { el.classList.add(c); });
- } else {
- nodes.forEach(function (n) { n.removeAttribute('disabled'); });
- busyClasses.forEach(function (c) { el.classList.remove(c); });
- reapplyDisabled(el);
- }
- }
- /** Re-apply `stm-disabled` to an element and any descendants that carry it. */
- function reapplyDisabled(el) {
- var scope = el.__stmScope || stateScope();
- if (el.hasAttribute('stm-disabled')) handleDisabled(el, scope);
- var scoped = el.querySelectorAll('[stm-disabled]');
- Array.prototype.forEach.call(scoped, function (n) {
- handleDisabled(n, n.__stmScope || scope);
- });
- }
- /** Apply or remove `stm-on-error` classes on an action element. */
- function applyErrorClasses(el, on) {
- if (!el || !el.hasAttribute || !el.hasAttribute('stm-on-error')) return;
- var classes = (el.getAttribute('stm-on-error') || '').split(/\s+/).filter(Boolean);
- classes.forEach(function (c) { on ? el.classList.add(c) : el.classList.remove(c); });
- }
- /**
- * Wire an element's primary action once. The listener resolves the action
- * object against the element's latest render scope, so loop instances bind to
- * their own item.
- */
- function wireAction(el) {
- if (!el.hasAttribute('stm-action') || wired.has(el)) return;
- wired.add(el);
- var eventName = el.tagName === 'FORM' ? 'submit' : 'click';
- el.addEventListener(eventName, function (event) {
- event.preventDefault();
- runElementAction(el);
- });
- }
- /**
- * Resolve and perform the action attached to an element, managing busy and
- * error-state classes around the request.
- * @param {HTMLElement} el
- */
- async function runElementAction(el) {
- var scope = el.__stmScope || stateScope();
- var action = evalExpr(el.getAttribute('stm-action'), scope);
- if (!action || typeof action.uri !== 'string') return;
- // stm-confirm: gate the action behind the confirm handler (async-capable,
- // so custom modals are supported).
- if (el.hasAttribute('stm-confirm')) {
- var confirmed = await triggerConfirm(el.getAttribute('stm-confirm'), el);
- if (!confirmed) return;
- }
- applyErrorClasses(el, false); // clear error state on a new attempt
- var data = collectData(el);
- setBusyState(el, true);
- try {
- await performAction(action, data, el);
- } catch (err) {
- // Already handled: stm-on-error classes and the onErrorHandler run inside
- // performAction/reportFailure. Swallow so an HTML-triggered action does
- // not surface as an unhandled rejection.
- } finally {
- setBusyState(el, false);
- }
- }
- // ---------------------------------------------------------------------------
- // Boot visibility (stm-preloader / stm-content)
- // ---------------------------------------------------------------------------
- /**
- * Toggle pre/post-entrypoint visibility with the `hidden` attribute. While
- * loading, `stm-preloader` elements are shown and `stm-content` elements
- * hidden; once ready, the reverse.
- *
- * To avoid a flash of un-bound template before the script runs, authors may
- * pre-set `hidden` directly on `stm-content` in the HTML (e.g.
- * `<div stm-content hidden>`); the library removes it once ready. The library
- * also sets `hidden` itself during loading as a fallback for authors who do
- * not pre-set it.
- * @param {boolean} ready
- */
- function setBootState(ready) {
- var preloaders = document.querySelectorAll('[stm-preloader]');
- var contents = document.querySelectorAll('[stm-content]');
- for (var i = 0; i < preloaders.length; i++) {
- ready ? preloaders[i].setAttribute('hidden', '') : preloaders[i].removeAttribute('hidden');
- }
- for (var j = 0; j < contents.length; j++) {
- ready ? contents[j].removeAttribute('hidden') : contents[j].setAttribute('hidden', '');
- }
- }
- // ---------------------------------------------------------------------------
- // Public state accessors
- // ---------------------------------------------------------------------------
- /** Build the scope used for expression evaluation: `{ typeName: public }`. */
- function stateScope() {
- var scope = {};
- store.forEach(function (entry, type) { scope[type] = entry.snapshot.public; });
- return scope;
- }
- /** Read a type's `public` data (what the attributes bind to). */
- function read(type) {
- var entry = store.get(type);
- return entry ? entry.snapshot.public : undefined;
- }
- /** Read a type's full snapshot object. */
- function getSnapshot(type) {
- var entry = store.get(type);
- return entry ? entry.snapshot : undefined;
- }
- /** Read the frame wrapping a type's snapshot. */
- function getFrame(type) {
- var entry = store.get(type);
- return entry ? entry.frame : undefined;
- }
- /** Build an object of `{ typeName: public }` for every held type. */
- function state() {
- var result = {};
- store.forEach(function (entry, type) { result[type] = entry.snapshot.public; });
- return result;
- }
- /**
- * Clear state. With a type argument, clears that type only; without, clears
- * all held state.
- * @param {string} [type]
- */
- function clear(type) {
- if (type === undefined) {
- Array.from(store.keys()).forEach(function (t) { clearType(t, { broadcast: true }); });
- } else {
- clearType(type, { broadcast: true });
- }
- renderAll();
- }
- /**
- * Perform an action. `action` may be an action object or a string path that
- * resolves to an action object within the current state.
- * @param {object|string} action
- * @param {object} [data]
- * @returns {Promise<void>}
- */
- function act(action, data) {
- var resolved = action;
- if (typeof action === 'string') resolved = evalExpr(action, stateScope());
- if (!resolved || typeof resolved.uri !== 'string') {
- return Promise.reject(new StatumError('Invalid action'));
- }
- return performAction(resolved, data, null);
- }
- /** Attach a state listener for a type. */
- function addStateListener(type, callback) {
- if (typeof callback !== 'function') return;
- if (!listeners.has(type)) listeners.set(type, new Set());
- listeners.get(type).add(callback);
- }
- /** Remove a previously-attached state listener. */
- function removeStateListener(type, callback) {
- var set = listeners.get(type);
- if (!set) return;
- set.delete(callback);
- if (set.size === 0) listeners.delete(type);
- }
- // ---------------------------------------------------------------------------
- // Initialization
- // ---------------------------------------------------------------------------
- /**
- * Inject the stylesheet that makes the `hidden` attribute authoritative.
- * Statum toggles `stm-if`/`stm-else` branches and loop holders via
- * `hidden`, whose user-agent rule loses specificity battles to ordinary
- * author CSS (a rule like `li { display: flex }` let hidden loop holders
- * leak as phantom rows). Idempotent: skipped when the stylesheet is
- * already present.
- */
- function injectHiddenStyle() {
- var id = 'statum-hidden-style';
- if (document.getElementById(id)) return;
- var head = document.head;
- if (!head) return;
- var style = document.createElement('style');
- style.id = id;
- style.textContent = '[hidden]{display:none !important}';
- head.appendChild(style);
- }
- /**
- * Scan the document for `pstm-*` attributes and `<pstm-*>` elements, which
- * are intended for server-side pre-rendering and should never reach the
- * browser. Emits a single `console.warn` summarizing them.
- */
- function warnServerSideMarkup() {
- var found = [];
- var els = document.querySelectorAll('*');
- for (var i = 0; i < els.length; i++) {
- var el = els[i];
- var tag = el.tagName.toLowerCase();
- if (tag.indexOf('pstm-') === 0) found.push('<' + tag + '>');
- var attrs = el.attributes;
- for (var j = 0; j < attrs.length; j++) {
- var name = attrs[j].name;
- if (name.indexOf('pstm-') === 0) found.push('<' + tag + '> ' + name);
- }
- }
- if (found.length) {
- console.warn('[statum] ' + found.length + ' server-side pstm-* attribute/element(s) ' +
- 'found in the DOM; they should have been resolved during pre-rendering: ' +
- found.slice(0, 10).join(', ') + (found.length > 10 ? ' …' : ''));
- }
- }
- /**
- * Initialize Statum: read URL overrides, run the session-cookie check,
- * hydrate persisted state, open the cross-tab channel, fetch the entrypoint,
- * and render. Safe to call multiple times.
- * @returns {Promise<void>}
- */
- async function init() {
- if (initialized) return;
- initialized = true;
- // Before the first render and the boot visibility toggling, so `hidden`
- // wins over author CSS from the very first paint.
- injectHiddenStyle();
- var body = document.body;
- if (body) {
- if (body.hasAttribute('stm-entrypoint')) config.entrypointUrl = body.getAttribute('stm-entrypoint');
- if (body.hasAttribute('stm-slots')) config.slotsUrl = body.getAttribute('stm-slots');
- if (body.hasAttribute('stm-channel')) config.channelUrl = body.getAttribute('stm-channel');
- if (body.hasAttribute('stm-worker')) config.workerUrl = body.getAttribute('stm-worker');
- }
- try { warnServerSideMarkup(); } catch (e) {}
- try { initSession(); } catch (e) {}
- try { hydrate(); } catch (e) {}
- setupChannel();
- setBootState(false);
- renderAll(); // bind against any persisted/hydrated state immediately
- try {
- await loadEntrypoint();
- } catch (err) {
- console.error('[statum] entrypoint load failed', err);
- } finally {
- setBootState(true);
- }
- }
- function autoInit() {
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', init);
- } else {
- init();
- }
- }
- // ---------------------------------------------------------------------------
- // Public API
- // ---------------------------------------------------------------------------
- /** @namespace statum */
- window.statum = {
- /** Library version. */
- version: '0.1.0',
- /** Mutable endpoint configuration. */
- config: config,
- /** (Re)initialize the library. Usually runs automatically on load. */
- init: init,
- /** Read a type's `public` data. */
- read: read,
- /** Read a type's full snapshot object. */
- getSnapshot: getSnapshot,
- /** Read the frame wrapping a type's snapshot. */
- getFrame: getFrame,
- /** Build `{ typeName: public }` for every held type. */
- state: state,
- /** Clear one type (`clear("x")`) or all state (`clear()`). */
- clear: clear,
- /** Perform an action object or named action. */
- act: act,
- /** Attach a state-changed listener for a type. */
- addStateListener: addStateListener,
- /** Remove a previously-attached listener. */
- removeStateListener: removeStateListener,
- /** Register a callback that runs before each render cycle (no arguments). */
- beforeEvaluate: function (fn) { if (typeof fn === 'function') beforeHooks.push(fn); },
- /** Register a callback that runs after each render cycle (no arguments). */
- afterEvaluate: function (fn) { if (typeof fn === 'function') afterHooks.push(fn); },
- /** The Statum error type (thrown by `act` and surfaced to handlers). */
- Error: StatumError,
- get onConfirmHandler() { return handlers.onConfirm; },
- set onConfirmHandler(v) { handlers.onConfirm = typeof v === 'function' ? v : null; },
- get onNotifyHandler() { return handlers.onNotify; },
- set onNotifyHandler(v) { handlers.onNotify = typeof v === 'function' ? v : null; },
- get onErrorHandler() { return handlers.onError; },
- set onErrorHandler(v) { handlers.onError = typeof v === 'function' ? v : null; }
- };
- autoInit();
- // Test-only escape hatch: tests/markdown loads this file under QuickJS with
- // `window.__STATUM_TEST__` set beforehand and reaches the markdown engine
- // through statum._testMarkdown. Shipped pages never set the flag, so this
- // adds no surface to the public API.
- if (window.__STATUM_TEST__) window.statum._testMarkdown = renderMarkdown;
- })();
|