okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
5d9f47922
main
1// serve/web/math.js - chat math that never changes the source. Engine-independent: a renderer (math-adapter.js) is plugged in. 2// Ported from PR #2972 by CC-David-CC. The text of a message stays as the model wrote it (history, copying, the Markdown 3// export and the requests all use it); math is only drawn over a placeholder in the page, and a formula that cannot be drawn 4// stays as its source text. 5"use strict" ; 6( function ( root ) { 7const escape = ( s ) => String ( s ). replace ( / [ &<>"' ] / g , ( c ) => ({ "&" :"&" , "<" :"<" , ">" :">" , '"' :""" , "'" :"'" }[ c ])); 8const escaped = ( s , i ) => { let n = 0 ; while ( i > 0 && s [ -- i ] === "\\" ) n ++ ; return n % 2 === 1 ; }; 9 10// split(text) -> [{raw}, {source, display, raw}, {raw, incomplete: true}, ...] 11// \( \) and $x$ are inline, \[ \] and $$ $$ are display. Code (fences, `spans`), Markdown link targets and prices ($5 and 12// $10) are not math. A formula that is still being written (no closing delimiter yet) stays plain text. 13function split ( text ) { 14const parts = []; let start = 0 , i = 0 ; 15const push = ( end , math ) => { if ( start < i ) parts . push ({ raw :text . slice ( start , i )}); parts . push ( math ); start = i = end ; }; 16while ( i < text . length ) { 17// Code takes precedence, including incomplete fences while streaming. 18const fence = ( i === 0 || text [ i - 1 ] === "\n" ) && text . slice ( i ). match ( / ^ { 0 , 3 }( ` { 3 ,} | ~ { 3 ,})[ ^ \n ] * \n / ); 19if ( fence ) { 20const marker = fence [ 1 ][ 0 ], count = fence [ 1 ]. length ; 21const end = new RegExp ( "^ {0,3}" + marker + "{" + count + ",}[ \\t]*(?:\\n|$)" , "m" ). exec ( text . slice ( i + fence [ 0 ]. length )); 22i = end ?i + fence [ 0 ]. length + end . index + end [ 0 ]. length :text . length ; continue ; 23} 24if ( text [ i ] === "`" && ! escaped ( text , i )) { 25const ticks = text . slice ( i ). match ( / ^` +/ )[ 0 ]; let end = text . indexOf ( ticks , i + ticks . length ); 26while ( end >= 0 && ( text [ end - 1 ] === "`" || text [ end + ticks . length ] === "`" )) end = text . indexOf ( ticks , end + ticks . length ); 27i = end < 0 ?text . length :end + ticks . length ; continue ; 28} 29if ( escaped ( text , i )) { i ++ ; continue ; } 30// Never inject a math element into a Markdown link's href attribute. 31if ( text . startsWith ( "](http" , i )) { 32const end = text . indexOf ( ")" , i + 2 ); 33i = end < 0 ?text . length :end + 1 ; continue ; 34} 35let open , close , display ; 36if ( text . startsWith ( "\\(" , i )) { open = "\\(" ; close = "\\)" ; display = false ; } 37else if ( text . startsWith ( "\\[" , i )) { open = "\\[" ; close = "\\]" ; display = true ; } 38else if ( text . startsWith ( "$$" , i )) { open = close = "$$" ; display = true ; } 39else if ( text [ i ] === "$" && ! /\s / . test ( text [ i + 1 ] || " " ) && text [ i - 1 ] !== "$" ) { open = close = "$" ; display = false ; } 40if ( ! open ) { i ++ ; continue ; } 41let end = text . indexOf ( close , i + open . length ); 42while ( end >= 0 && ( escaped ( text , end ) || ( close === "$" && ( / \s / . test ( text [ end - 1 ]) || / [ \d $ ] / . test ( text [ end + 1 ] || "" ))))) end = text . indexOf ( close , end + close . length ); 43const source = end >= 0 ?text . slice ( i + open . length , end ) :text . slice ( i + open . length ); 44// Numeric prices are text, even when separated by a second dollar amount. 45if ( open === "$" && ( / \n / . test ( source ) || / \$ / . test ( source ) || 46/ ^\d [ \d ,. ] * (?: \s * [ A - Za - z ] | \s * $ ) / . test ( source ))) { i ++ ; continue ; } 47if ( end < 0 ) { push ( text . length , { raw :text . slice ( i ), incomplete :true }); break ; } 48push ( end + close . length , { source, display, raw :text . slice ( i , end + close . length )}); 49} 50if ( start < text . length ) parts . push ({ raw :text . slice ( start )}); 51return parts ; 52} 53 54// markdown(text, format): format() is the page's Markdown, run on the text with every formula swapped for a placeholder 55// word, then each word becomes <span class="chat-math" data-math="..."> holding the escaped source until it is drawn. 56function markdown ( text , format ) { 57let prefix = "STRATAMATHPLACEHOLDER" ; while ( text . includes ( prefix )) prefix += "X" ; 58const slots = []; 59const protectedText = split ( text ). map (( p ) => { 60if ( p . source === undefined && ! p . incomplete ) return p . raw ; 61const key = prefix + slots . length + "END" ; 62slots . push ( p ); return key ; 63}). join ( "" ); 64let html = format ( protectedText ); 65slots . forEach (( p , i ) => { 66const body = p . incomplete ?escape ( p . raw ) :`<span class="chat-math ${ p . display ? " chat-math--display" : "" } " data-math=" ${ escape ( encodeURIComponent ( p . source ))} " data-display=" ${ p . display ? "1" : "0" } "> ${ escape ( p . raw )} </span>` ; 67html = html . replaceAll ( prefix + i + "END" , () => body ); 68}); 69return html ; 70} 71 72// drawing: one formula at a time (an engine may keep state between formulas), 256 results cached, a 10 s deadline for the 73// engine to start and 15 s for one formula. A formula over 16 KiB is not drawn. The adapter returns an element that is not 74// in the page; the core clones it into the placeholder if that is still on the screen. 75const cache = new Map (), done = new Map (); 76let initialization = null , queue = Promise . resolve (), epoch = 0 ; 77function reset () { cache . clear (); done . clear (); initialization = null ; epoch ++ ; } 78const keyOf = ( source , display ) => JSON . stringify ([ source , display ]); 79async function result ( source , display ) { 80if ( new TextEncoder (). encode ( source ). length > 16384 ) return { ok :false , reason :"limit" }; 81const key = keyOf ( source , display ); 82if ( cache . has ( key )) { const hit = cache . get ( key ); cache . delete ( key ); cache . set ( key , hit ); return hit ; } 83if ( cache . size >= 256 ) { const old = cache . keys (). next (). value ; cache . delete ( old ); done . delete ( old ); } 84const current = epoch ; let work ; 85const task = queue . then ( async () => { 86if ( epoch !== current || cache . get ( key ) !== task ) return { ok :false , reason :"unavailable" }; 87try { 88const adapter = root . StrataMathAdapter ; 89if ( ! adapter ) return { ok :false , reason :"unavailable" }; 90initialization ||= Promise . race ([ adapter . initialize (), new Promise (( _ , reject ) => 91setTimeout (() => reject ( new Error ( "Math initialization timed out" )), 10000 ))]); 92await initialization ; 93const signal = AbortSignal . timeout ( 15000 ); 94let onAbort ; 95const deadline = new Promise (( resolve ) => { 96onAbort = () => resolve ({ ok :false , reason :"limit" }); 97signal . addEventListener ( "abort" , onAbort , { once :true }); 98}); 99work = Promise . resolve ( adapter . render ( source , { display, signal})); 100try { return await Promise . race ([ work , deadline ]); } 101finally { signal . removeEventListener ( "abort" , onAbort ); } 102} catch ( _ ) { return { ok :false , reason :"unavailable" }; } 103}); 104// A browser engine may ignore cancellation. Return source at the deadline, 105// but do not overlap conversions that mutate the engine's macro state. 106queue = task . then (() => work , () => work ). then (() => undefined , () => undefined ); 107cache . set ( key , task ); 108task . then (( r ) => { if ( cache . get ( key ) === task ) done . set ( key , r ); }); 109return task ; 110} 111 112function place ( slot , r , tr ) { 113if ( r . ok ) slot . replaceChildren ( r . element . cloneNode ( true )); 114else { slot . dataset . mathError = r . reason ; slot . title = tr ?tr ( "math.source" , "Math source ({reason})" , { reason :r . reason }) :"Math source (" + r . reason + ")" ; } 115} 116// hydrate(container): draw the placeholders in a container. A formula drawn before is placed at once, so a streaming 117// answer that is rebuilt on every frame does not flicker back to source text. 118function hydrate ( container ) { 119const generation = container . _mathGeneration = ( container . _mathGeneration || 0 ) + 1 ; 120for ( const slot of container . querySelectorAll ( "[data-math]" )) { 121const source = decodeURIComponent ( slot . dataset . math ), display = slot . dataset . display === "1" ; 122const known = done . get ( keyOf ( source , display )); 123if ( known && known . ok ) { place ( slot , known , root . tr ); continue ; } 124result ( source , display ). then (( r ) => { 125if ( generation !== container . _mathGeneration || ! container . contains ( slot )) return ; 126place ( slot , r , root . tr ); 127}); 128} 129} 130function script ( url ) { 131return new Promise (( resolve , reject ) => { 132const s = document . createElement ( "script" ); s . src = url ; 133const timer = setTimeout (() => { s . remove (); reject ( new Error ( "Math script timed out" )); }, 10000 ); 134s . onload = () => { clearTimeout ( timer ); resolve (); }; 135s . onerror = () => { clearTimeout ( timer ); s . remove (); reject ( new Error ( "Math script unavailable" )); }; 136document . head . append ( s ); 137}); 138} 139const api = { split, markdown, hydrate, reset, script, result}; 140root . StrataMath = api ; 141if ( typeof module !== "undefined" && module . exports ) module . exports = api ; 142})( typeof globalThis !== "undefined" ?globalThis :this );