gitoria
All repositories: gitoria
20.4 KB
// lib/markdown.hl — copied from tickets.worldapi.org (markdown.hl, ticket tickets#6) for the repo homepage (gitoria#8), with tables, quotes and rules added. Originally: MARKDOWN IN TEXT FIELDS (mission 014; CONCEPT.md// "Data formats": Markdown inside text fields). The summary, comment texts and state notes are// Markdown; the ticket page renders them. Statics only, server realm.//// SAFE BY CONSTRUCTION: the text is parsed HERE into plain data — blocks of spans — and the// View (components/markdown.hl) builds elements from it. Every character of the source ends// up in a TEXT node (hl:web escapes it); there is no HTML string anywhere, so raw HTML in the// source (`<script>`, `<img onerror>`) is shown as the text it is. A link's href is taken only// if `safeHref` accepts it: http(s):, mailto:, a same-site path (`/…`, not `//…`) or `#…`;// anything else (`javascript:`, `data:`, `vbscript:`, relative `foo`, quotes, spaces, control// characters) stays plain text.//// WHAT IS UNDERSTOOD (the subset ticket #6 names — headings, lists, code, links, emphasis):// blocks: `#`…`######` headings, `-`/`*`/`+` and `1.`/`1)` list items (one level; deeper// indentation is flattened; a list may interrupt a paragraph — the import writes// them that way), ``` / ~~~ fenced code, paragraphs (blank-line separated; their// single line breaks are KEPT — the page showed them before, `white-space: pre-wrap`)// inline: `code` (any backtick run), [text](url), <https://…>, bare http(s):// URLs,// *em* _em_ **strong** __strong__ ***both***, backslash escapes of punctuation// Also understood here (gitoria#8): `> block quotes` (inline text only), | tables |, horizontal rules.// Not understood (shown as typed): images, nested lists, HTML.//// A block is COMPACT (it travels in the page values): ONE flag that names its kind (omitted = false) and only the fields that// kind has. The View's `if` takes a field, not a comparison (a `kind == 'p'` string cannot be tested there), so the kind IS the field.// { isP | isQuote | isH1 | isH2 | isH3 (3 = level 3+) = true, spans } { isUl = true, items: [{ spans }] } { isOl = true, items, start }// { isCode = true, code (the text) } { isTable = true, head: [{ spans }], rows: [[{ spans }]] } { isHr = true }// A span: { text, isText | isStrong | isEm | isStrongEm | isCode | isLink = true, href (link only) }static NL = ""import { sha256 } from 'hl:crypto'// ---- the parsed-blocks cache (G3) ----------------------------------------------------------// The homepage reads README.md from git on EVERY request and the scanner below costs ~100 ms on a big README (~26 % of the// page's server time, W113). The blocks are a pure function of the text, so they are kept under the text's sha256: a push// changes the text, hence the key — nothing to invalidate, a stale entry can only be unused. BOUNDED: at most mdMaxEntries// texts and mdMaxChars characters of source in total (the cost of an entry is its text length); the least recently used goes// first. A text over mdMaxOne characters is parsed but not kept. Flat statics written key by key (like tracker's maps).static mdMaxEntries = 32static mdMaxChars = 4000000static mdMaxOne = 1000000static mdCache = {} // sha256 hex → blocksstatic mdSize = {} // sha256 hex → characters of its textstatic mdOrder = [] // keys, least recently used firststatic mdChars = [0] // the sum of mdSize (one slot: a static number cannot be written from a lambda)static isSpaceC = (c) => { return c == 32 || c == 9 || c == 10 || c == 13 }static isAlnumC = (c) => { return (c >= 48 && c <= 57) || (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || c > 127 }static isPunctC = (c) => { return (c >= 33 && c <= 47) || (c >= 58 && c <= 64) || (c >= 91 && c <= 96) || (c >= 123 && c <= 126) }// ---- links ------------------------------------------------------------------------------// the href of a link, or null when it is not one we let throughstatic safeHref = (u) => {if (u == null) { return null }t = ('' + u).trim()if (t == '' || t.length > 2000) { return null }let i = 0while (i < t.length) {let c = t.charCodeAt(i)// no spaces / control characters, no quotes, no < > ` and no backslashif (c <= 32 || c == 127 || c == 34 || c == 39 || c == 60 || c == 62 || c == 96 || c == 92) { return null }i = i + 1}low = t.toLowerCase()if (low.startsWith('https://') && t.length > 8) { return t }if (low.startsWith('http://') && t.length > 7) { return t }if (low.startsWith('mailto:') && t.length > 7) { return t }if (t.startsWith('/') && !t.startsWith('//')) { return t }if (t.startsWith('#')) { return t }return null}static isUrlStart = (s, i) => {low = s.slice(i, i + 8).toLowerCase()return low.startsWith('https://') || low.startsWith('http://')}// where a bare URL starting at i ends: up to whitespace or < > " `, minus trailing punctuation// (and a closing parenthesis that has no opening one inside the URL)static isUrlStop = (c) => { return isSpaceC(c) || c == 60 || c == 62 || c == 34 || c == 96 }static urlEnd = (s, i) => {let end = iwhile (end < s.length && !isUrlStop(s.charCodeAt(end))) { end = end + 1 }let trimming = truewhile (trimming && end > i) {let c = s.charCodeAt(end - 1)if (c == 46 || c == 44 || c == 59 || c == 58 || c == 33 || c == 63 || c == 39 || c == 42 || c == 95) {end = end - 1} else if (c == 41) {let opens = 0let closes = 0let k = iwhile (k < end) {if (s.charCodeAt(k) == 40) { opens = opens + 1 }if (s.charCodeAt(k) == 41) { closes = closes + 1 }k = k + 1}if (closes > opens) { end = end - 1 } else { trimming = false }} else {trimming = false}}return end}// `[label](url)` at i → { label, href (null = not allowed), end } or null (not a link)static linkAt = (s, i) => {let j = i + 1let found = -1while (j < s.length && found < 0) {let c = s.charCodeAt(j)if (c == 91) { return null }if (c == 93) { found = j }j = j + 1}if (found < 0 || found == i + 1) { return null }if (found + 1 >= s.length || s.charCodeAt(found + 1) != 40) { return null }k = s.indexOf(')', found + 2)if (k < 0) { return null }let target = s.slice(found + 2, k).trim()// an optional title after a space is dropped: [x](url "title")sp = target.indexOf(' ')if (sp > 0) { target = target.slice(0, sp) }return { label = s.slice(i + 1, found) href = safeHref(target) end = k + 1 }}// ---- spans --------------------------------------------------------------------------------static textSpan = (t, strong, em) => {if (strong && em) { return { text = t isStrongEm = true } }if (strong) { return { text = t isStrong = true } }if (em) { return { text = t isEm = true } }return { text = t isText = true }}static codeSpan = (t) => {return { text = t isCode = true }}static linkSpan = (t, h) => {return { text = t isLink = true href = h }}// the index of a run of EXACTLY n characters c at or after `at`, or -1. `esc`: a character// after a backslash does not count (emphasis; inside `code` a backslash is just a backslash)static runAt = (s, at, c, n, esc) => {let i = atwhile (i < s.length) {if (esc && s.charCodeAt(i) == 92) {i = i + 2} else if (s.charCodeAt(i) == c) {let k = iwhile (k < s.length && s.charCodeAt(k) == c) { k = k + 1 }if (k - i == n) { return i }i = k} else {i = i + 1}}return -1}// is there a CLOSING delimiter run (exactly n of c, not after a space; `_` not before a// letter/digit) after `at`?static hasCloser = (s, at, c, n) => {let i = atwhile (i < s.length) {let r = runAt(s, i, c, n, true)if (r < 0) { return false }let prev = r > 0 ? s.charCodeAt(r - 1) : 32let next = r + n < s.length ? s.charCodeAt(r + n) : 32if (r > at && !isSpaceC(prev) && (c != 95 || !isAlnumC(next))) { return true }i = r + n}return false}static inlineSpans = (src) => {out = []if (src == null || src == '') { return out }s = '' + srcn = s.lengthlet buf = ''let strong = falselet em = falselet strongC = 0let emC = 0let i = 0while (i < n) {let c = s.charCodeAt(i)if (c == 92 && i + 1 < n && isPunctC(s.charCodeAt(i + 1))) {// a backslash escape: the next punctuation character as itselfbuf = buf + s[i + 1]i = i + 2} else if (c == 96) {// `code`: a run of backticks up to the same runlet k = iwhile (k < n && s.charCodeAt(k) == 96) { k = k + 1 }let close = runAt(s, k, 96, k - i, false)if (close < 0) {buf = buf + s.slice(i, k)i = k} else {if (buf != '') { out.push(textSpan(buf, strong, em)) }buf = ''let code = s.slice(k, close).replaceAll(NL, ' ')if (code.length > 2 && code.startsWith(' ') && code.endsWith(' ') && code.trim() != '') { code = code.slice(1, code.length - 1) }out.push(codeSpan(code))i = close + (k - i)}} else if (c == 91) {// [label](url)let l = linkAt(s, i)if (l == null) {buf = buf + '['i = i + 1} else if (l.href == null) {buf = buf + s.slice(i, l.end)i = l.end} else {if (buf != '') { out.push(textSpan(buf, strong, em)) }buf = ''out.push(linkSpan(l.label, l.href))i = l.end}} else if (c == 60 && i + 1 < n && isUrlStart(s, i + 1)) {// <https://…>let e = s.indexOf('>', i + 1)let url = e > 0 ? s.slice(i + 1, e) : ''let h = safeHref(url)if (e < 0 || h == null) {buf = buf + '<'i = i + 1} else {if (buf != '') { out.push(textSpan(buf, strong, em)) }buf = ''out.push(linkSpan(url, h))i = e + 1}} else if ((c == 104 || c == 72) && (i == 0 || !isAlnumC(s.charCodeAt(i - 1))) && isUrlStart(s, i)) {// a bare http(s):// URLlet e = urlEnd(s, i)let url = s.slice(i, e)let h = safeHref(url)if (h == null) {buf = buf + s[i]i = i + 1} else {if (buf != '') { out.push(textSpan(buf, strong, em)) }buf = ''out.push(linkSpan(url, h))i = e}} else if (c == 42 || c == 95) {// * and _: emphasis (1), strong (2), both (3)let k = iwhile (k < n && s.charCodeAt(k) == c) { k = k + 1 }let run = k - ilet prev = i > 0 ? s.charCodeAt(i - 1) : 32let next = k < n ? s.charCodeAt(k) : 32let wantStrong = run == 2 || run == 3let wantEm = run == 1 || run == 3let canOpen = !isSpaceC(next) && (c == 42 || !isAlnumC(prev))let canClose = !isSpaceC(prev) && (c == 42 || !isAlnumC(next))let closes = canClose && run <= 3 && (!wantStrong || (strong && strongC == c)) && (!wantEm || (em && emC == c))let opens = !closes && canOpen && run <= 3 && (!wantStrong || !strong) && (!wantEm || !em) && hasCloser(s, k, c, run)if (closes || opens) {if (buf != '') { out.push(textSpan(buf, strong, em)) }buf = ''if (wantStrong) {strong = opensstrongC = c}if (wantEm) {em = opensemC = c}} else {buf = buf + s.slice(i, k)}i = k} else {buf = buf + s[i]i = i + 1}}if (buf != '') { out.push(textSpan(buf, strong, em)) }return out}// ---- blocks -------------------------------------------------------------------------------static noCr = (line) => { return line.length > 0 && line.charCodeAt(line.length - 1) == 13 ? line.slice(0, line.length - 1) : line }static indentOf = (line) => {let i = 0while (i < line.length && (line.charCodeAt(i) == 32 || line.charCodeAt(i) == 9)) { i = i + 1 }return i}// a heading line (≤ 3 spaces in, 1–6 '#', a space or the end) → { level, text } or nullstatic headingOf = (line) => {if (indentOf(line) > 3) { return null }t = line.trim()let k = 0while (k < t.length && t.charCodeAt(k) == 35) { k = k + 1 }if (k == 0 || k > 6) { return null }if (k < t.length && t.charCodeAt(k) != 32 && t.charCodeAt(k) != 9) { return null }let body = t.slice(k).trim()// a closing run of '#' after a space goeslet e = body.lengthwhile (e > 0 && body.charCodeAt(e - 1) == 35) { e = e - 1 }if (e == 0) { body = '' } else if (e < body.length && (body.charCodeAt(e - 1) == 32 || body.charCodeAt(e - 1) == 9)) { body = body.slice(0, e).trim() }return { level = k text = body }}// a list item line → { ordered, start, text } or nullstatic itemOf = (line) => {t = line.trim()if (t.length >= 2 && (t.charCodeAt(0) == 45 || t.charCodeAt(0) == 42 || t.charCodeAt(0) == 43) && (t.charCodeAt(1) == 32 || t.charCodeAt(1) == 9)) {return { ordered = false start = 1 text = t.slice(2).trim() }}if (t.length == 1 && (t == '-' || t == '*' || t == '+')) { return { ordered = false start = 1 text = '' } }let k = 0while (k < t.length && k < 9 && t.charCodeAt(k) >= 48 && t.charCodeAt(k) <= 57) { k = k + 1 }if (k == 0 || k >= t.length) { return null }d = t.charCodeAt(k)if (d != 46 && d != 41) { return null }if (k + 1 < t.length && t.charCodeAt(k + 1) != 32 && t.charCodeAt(k + 1) != 9) { return null }return { ordered = true start = toNumber(t.slice(0, k)) text = t.slice(k + 1).trim() }}// a code fence line (``` or ~~~, ≥ 3) → its run (e.g. '````') or nullstatic fenceOf = (line) => {if (indentOf(line) > 3) { return null }t = line.trim()if (t.length < 3) { return null }c = t.charCodeAt(0)if (c != 96 && c != 126) { return null }let k = 0while (k < t.length && t.charCodeAt(k) == c) { k = k + 1 }if (k < 3) { return null }// an info string after ``` must not contain a backtickif (c == 96 && t.slice(k).includes('`')) { return null }return t.slice(0, k)}static paraBlock = (lines) => {let spans = inlineSpans(lines.join(NL))return { isP = true spans = spans }}static headingBlock = (level, text) => {let spans = inlineSpans(text)if (level == 1) { return { isH1 = true spans = spans } }if (level == 2) { return { isH2 = true spans = spans } }return { isH3 = true spans = spans }}static codeBlock = (lines) => {text = lines.join(NL)return { isCode = true code = text }}static listBlock = (ordered, first, itemLines) => {let items = []for (lines of itemLines) {let spans = inlineSpans(lines.join(NL))items.push({ spans = spans })}if (ordered) { return { isOl = true items = items start = first } }return { isUl = true items = items }}static quoteBlock = (lines) => {let spans = inlineSpans(lines.join(NL))return { isQuote = true spans = spans }}static hrBlock = () => {return { isHr = true }}static tableBlock = (head, rows) => {return { isTable = true head = head rows = rows }}// a line of 3+ of one of - * _ (spaces between allowed) and nothing elsestatic isHrLine = (line) => {if (indentOf(line) > 3) { return false }t = line.trim()if (t.length < 3) { return false }c = t.charCodeAt(0)if (c != 45 && c != 42 && c != 95) { return false }let n = 0let i = 0while (i < t.length) {let d = t.charCodeAt(i)if (d == c) { n = n + 1 } else if (d != 32 && d != 9) { return false }i = i + 1}return n >= 3}// `> text` → the text after the marker, or nullstatic quoteOf = (line) => {if (indentOf(line) > 3) { return null }t = line.trim()if (!t.startsWith('>')) { return null }return t.slice(1).trim()}// the cells of a table row line: `| a | b |` → [a, b] as spans listsstatic cellsOf = (line) => {let t = line.trim()if (t.startsWith('|')) { t = t.slice(1) }if (t.endsWith('|')) { t = t.slice(0, t.length - 1) }out = []for (c of t.split('|')) { out.push({ spans = inlineSpans(c.trim()) }) }return out}// is this the `|---|:--:|` line under a table head?static isSepLine = (line) => {t = line.trim()if (!t.includes('-') || !t.includes('|') && !t.includes(':')) { return false }let i = 0while (i < t.length) {let d = t.charCodeAt(i)if (d != 124 && d != 45 && d != 58 && d != 32 && d != 9) { return false }i = i + 1}return true}// the Markdown text → blocks (see the header): the scanner itself, no cachestatic parseBlocks = (text) => {out = []if (text == null || text == '') { return out }lines = ('' + text).split(NL)let para = []let inList = falselet listOrdered = falselet listStart = 1let items = []let blankBefore = falselet i = 0while (i < lines.length) {let line = noCr(lines[i])let fence = fenceOf(line)let hr = fence == null && isHrLine(line)let q = fence == null && !hr ? quoteOf(line) : nulllet isTab = fence == null && !hr && q == null && line.includes('|') && i + 1 < lines.length && isSepLine(noCr(lines[i + 1])) && noCr(lines[i + 1]).includes('|')let h = fence == null && !hr && q == null && !isTab ? headingOf(line) : nulllet it = fence == null && !hr && q == null && !isTab && h == null ? itemOf(line) : nullif (hr) {if (para.length > 0) { out.push(paraBlock(para)) }para = []if (inList) { out.push(listBlock(listOrdered, listStart, items)) }inList = falseitems = []out.push(hrBlock())blankBefore = falsei = i + 1} else if (q != null) {if (para.length > 0) { out.push(paraBlock(para)) }para = []if (inList) { out.push(listBlock(listOrdered, listStart, items)) }inList = falseitems = []let ql = []let j = ilet more = truewhile (j < lines.length && more) {let x = quoteOf(noCr(lines[j]))if (x == null) { more = false } else {ql.push(x)j = j + 1}}out.push(quoteBlock(ql))i = jblankBefore = false} else if (isTab) {if (para.length > 0) { out.push(paraBlock(para)) }para = []if (inList) { out.push(listBlock(listOrdered, listStart, items)) }inList = falseitems = []let head = cellsOf(line)let rows = []let j = i + 2while (j < lines.length && noCr(lines[j]).trim() != '' && noCr(lines[j]).includes('|')) {rows.push(cellsOf(noCr(lines[j])))j = j + 1}out.push(tableBlock(head, rows))i = jblankBefore = false} else if (fence != null) {if (para.length > 0) { out.push(paraBlock(para)) }para = []if (inList) { out.push(listBlock(listOrdered, listStart, items)) }inList = falseitems = []let code = []let j = i + 1let closed = falselet fc = fence.charCodeAt(0)while (j < lines.length && !closed) {let l = noCr(lines[j])let f = fenceOf(l)if (f != null && f.charCodeAt(0) == fc && f.length >= fence.length && l.trim() == f) {closed = true} else {code.push(l)}j = j + 1}out.push(codeBlock(code))i = jblankBefore = false} else if (line.trim() == '') {if (para.length > 0) { out.push(paraBlock(para)) }para = []blankBefore = truei = i + 1} else if (h != null) {if (para.length > 0) { out.push(paraBlock(para)) }para = []if (inList) { out.push(listBlock(listOrdered, listStart, items)) }inList = falseitems = []out.push(headingBlock(h.level, h.text))blankBefore = falsei = i + 1} else if (it != null) {if (para.length > 0) { out.push(paraBlock(para)) }para = []if (inList && listOrdered != it.ordered) {out.push(listBlock(listOrdered, listStart, items))inList = falseitems = []}if (!inList) {inList = truelistOrdered = it.orderedlistStart = it.startitems = []}items.push([it.text])blankBefore = falsei = i + 1} else if (inList && (!blankBefore || indentOf(line) >= 2)) {// a wrapped item line (or an indented paragraph of the item): onto the last itemlet last = items[items.length - 1]last.push(line.trim())items[items.length - 1] = lastblankBefore = falsei = i + 1} else {if (inList) { out.push(listBlock(listOrdered, listStart, items)) }inList = falseitems = []para.push(line.trim())blankBefore = falsei = i + 1}}if (para.length > 0) { out.push(paraBlock(para)) }if (inList) { out.push(listBlock(listOrdered, listStart, items)) }return out}// the Markdown text → blocks, from the cache when this exact text was parsed beforestatic markdownBlocks = (text) => {if (text == null || text == '') { return [] }let t = '' + textif (t.length > mdMaxOne) { return parseBlocks(t) }let key = sha256(t)let hit = mdCache[key]if (hit != null) {// most recently used: to the end of the orderlet rest = []for (k of mdOrder) { if (k != key) { rest.push(k) } }rest.push(key)mdOrder = restreturn hit}let blocks = parseBlocks(t)while (mdOrder.length > 0 && (mdOrder.length >= mdMaxEntries || mdChars[0] + t.length > mdMaxChars)) {let old = mdOrder[0]mdChars[0] = mdChars[0] - mdSize[old]delete mdCache[old]delete mdSize[old]mdOrder = mdOrder.slice(1)}mdCache[key] = blocksmdSize[key] = t.lengthmdChars[0] = mdChars[0] + t.lengthmdOrder.push(key)return blocks}
Branches
- f1-broken-json
- f2-api-bugs
- gp-gate-ports
- heap-revert
- hl25-records
- ident-chooser-selector
- mainmain branch
- p51-public-pr-reads
- records-1112
- s25-no-session-on-login-error
- v59
- w52-person-approval
- w52b-approval-followup
- w52c-header-phone
- w53-pulls-speed-pr
- w54-repo-rename-pr
- w55-rename-org
- w56-owner-members
- w62-pr-close
- w63-force-push
- w64-org-slash
Latest commits
- c52424e9gitoria mobile: repo list before the forms, 3x2 tab grid, no duplicate branch heading, ordered commit rows, aligned ticket rows, pull title on its own row, wrapping clone commands, no dead strip under formsMG
- 3a95252dG3: cache parsed README blocks by sha256 of the text (bounded LRU), reportmre
- 570138cddeploy: security gate (tests/security.mjs)mre
- da6b20fcgitoria SG: security audit fixes (uploadMax 0, Secure cookie on https, session rotation at login, nosniff on function routes, no identity in page data) + tests/security.mjs gate + reportmre
- f98c981fgitoria B1: report wordingmre
- c6364cedgitoria B1: compact Markdown blocks (one kind flag per block/span, empty and false fields omitted); same rendered HTML, page values -67%mre
- cd99d2feWIP gitoria#22: always render the repo level's slot (missing-repo boot hang), pages render nothing without a repo; hydration diagnosis in reports/G2-hydrate.mdmre
- e5404b9breport: commit idsmre
- 63cfa21ereports/G2-repotabs.mdmre
- 9b0516fdgitoria#22: mark the tab underline functional (check-theme), chain E2E: serve/measure split, bring the lisbeth tab to frontmre
- 19bc1df8gitoria#22: all repo pages under ONE layout level (components/repo.hl, hl:web D-CHAIN): a tab click replaces only the page in the slot; head and tab nav stay the same DOM nodesmre
- 40658417tests/browser.mjs: wait for the page to be live (hydrated) before clicking Merge — a click on the server-rendered button before the client mounted was lost (flaky 'Clashing change' under load)mre
- 48a6154bre-vendor Hybriel 5406d146 (hl:web batches 9+10: #72 emits while the socket is closed delivered after reconnect, browser boot linear, faster list appends; contains int 6–14 + m406)mre
- e972e8d7tests: short-id-switch (GITORIA_SWITCH_IDENT_PORT/_PORT) and ssh tunnel (GITORIA_GATE_TUNNEL_PORT) ports from env, defaults unchangedmre
- f06f5349re-vendor Hybriel 6f8a0689 (int 6–11: streaming cursors, #203 index heal + close() fix, fd403 listDir/cursor fds, hl:time browser side, hl:web batches 5+6)mre
- c7d3cc87docker-compose: nofile 65536 (Hybriel int 6+ boot opened >1024 files in the tracker)mre
- f0e7ff8cdeploy: backup copies index files first and *.mpack data last (hot-copy skew, hybriel #203)mre
- fe5f707cgitoria 010: report, mission, comment on why current = true staysmre
- 9705ca86gitoria 010: gate: menu marker in the server HTMLmre
- 8cff663agitoria 010: main-menu.hl from layouts 0bcc629 (route marker)mre