All files / src strict-html.ts

95.73% Statements 292/305
93.04% Branches 254/273
96.87% Functions 31/32
97.86% Lines 229/234

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468                                                          9x       9x 28218x 2715x 9x     9x     9x 9x   9x             9x           9x           9x     9x       9x                       9x         9x     9x                 9x             333x 9x                   522x     9x 260x         9x 4745x 4744x           9x 32x                   9x 3822x 163x 265x 32x 32x 32x 233x 48x   210x                                     9x 1080x 1080x           1247x                   9x 1731x 1731x 7377x 1731x 1730x 1730x 1730x 2772x 2772x 2772x 2772x 1093x 17x           1076x 5765x 1076x 1076x 1076x 1076x 1076x 889x 889x 889x 889x 866x 866x 865x 865x 23x 23x 29x 23x   888x   1042x           9x 316x 316x 316x 316x 309x   309x 307x 307x 307x 307x           9x 572x 572x   260x           9x 99x 99x     9x     572x 572x   571x 571x 8244x     571x 571x   571x 3184x 1279x 1279x 4x   1275x 1275x 1275x 1247x     571x   571x 600x 398x 398x       398x 393x   541x         571x 138x 131x 131x 131x 125x   16x     1565x   571x 109x 109x 109x 108x 2x   106x 105x 105x 105x 105x     571x 1587x 1587x 1587x 1541x 1541x 1483x 5x 5x   1478x 1473x 1471x 1468x 1465x 1461x   1460x 1460x 1460x 1368x     571x 969x 969x 960x 960x 936x     571x 571x 2884x 2884x 106x 106x   2778x 2757x   2757x 37x 37x 36x   35x 35x 35x 34x 33x   35x   2720x 2720x   2715x 970x 970x 970x 3880x 970x 970x 969x 969x 969x 969x 936x 936x     1745x 14x 14x 14x     1731x 1696x 1696x 1696x 109x 105x   1587x 1460x 1460x 1460x     69x 3x   65x   1456x 316x 307x 303x 303x       326x         969x 312x 312x 312x 607x 44x 23x             23x   312x    
// ---------------------------------------------------------------------------
// a component file, read exactly as the HTML parser reads it - or not at all
//
// The runtime reads a component with DOMParser (parseFile, in jq79.ts). A build
// can do that reading once, in node, and ship the result: Component79.parsed()
// then skips the parse on the page (RECORD/2026-12-02.parsed-components-in-builds.md).
// That is only sound if node builds *the tree the browser builds*, and a
// conforming HTML parser is most of a browser. So this one is strict: it builds
// the tree only where the HTML parser does nothing but the obvious - every
// element closed by its own end tag, in order, in a place the content model
// allows - and gives up on anything the parser would fix up: an implied end
// tag, a <tbody> it would insert, text it would move out of a table, a
// reference it can't decode. Giving up costs that file its head start (it ships
// as source, as before); building a different tree would cost a wrong render.
//
// It follows the parser in what it does accept: the input stream's newlines,
// character references (with html.ts's tables, and only the references they
// hold), raw text and escapable raw text, the newline dropped after <pre>,
// <listing> and <textarea>, comments splitting text, ASCII-only lowercasing,
// and SVG - its namespace, the tag and attribute case tables, `/>` closing an
// element, <desc>/<title> holding text.
//
// tests/strictHtml.test.ts holds it against the runtime's own parse, file by
// file: each result is null or the same tree.
// ---------------------------------------------------------------------------
 
import { CHARACTER_REFERENCE_RE, decodeReference, isKnownReference } from "./html"
import { COMPONENT_TAG_ATTR, prepareSource, scopeHash, type ParsedComponent, type ParsedFile, type TemplateNode } from "./source"
 
const SVG_NS = "http://www.w3.org/2000/svg"
 
// the five characters HTML calls whitespace - not JavaScript's \s, which also
// takes \v and every Unicode space, none of which end a tag name
const WHITESPACE = new Set(["\t", "\n", "\f", "\r", " "])
const isWhitespace = (char: string | undefined) => char !== undefined && WHITESPACE.has(char)
const isAsciiLetter = (char: string | undefined) => char !== undefined && /^[A-Za-z]$/.test(char)
const ONLY_WHITESPACE_RE = /^[\t\n\f\r ]*$/
 
// what the parser inserts and pops at once, whatever follows
const VOID_TAGS = new Set([
  "area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr",
])
const RAW_TEXT_TAGS = new Set(["script", "style", "xmp", "iframe", "noembed", "noframes"])
const ESCAPABLE_RAW_TEXT_TAGS = new Set(["textarea", "title"])
// the parser drops a newline right after these start tags
const LEADING_NEWLINE_TAGS = new Set(["pre", "listing", "textarea"])
 
// start tags whose handling isn't "insert it here", or that no component needs
// badly enough to follow the parser into: the document's own structure, the
// legacy and the obsolete, <noscript> (DOMParser parses it with scripting off),
// <select> (its parsing is changing in browsers, for customizable select),
// MathML, and ruby's implied end tags
const GIVE_UP_TAGS = new Set([
  "html", "head", "body", "frameset", "frame", "image", "isindex", "keygen", "basefont", "bgsound",
  "noscript", "plaintext", "select", "math", "rb", "rp", "rt", "rtc",
])
 
// the start tags that close an open <p> (in button scope) before they insert
const CLOSES_P = new Set([
  "address", "article", "aside", "blockquote", "center", "details", "dialog", "dir", "div", "dl", "fieldset",
  "figcaption", "figure", "footer", "header", "hgroup", "main", "menu", "nav", "ol", "p", "search", "section",
  "summary", "ul", "h1", "h2", "h3", "h4", "h5", "h6", "pre", "listing", "form", "li", "dd", "dt", "plaintext",
  "table", "hr", "xmp",
])
const HEADINGS = new Set(["h1", "h2", "h3", "h4", "h5", "h6"])
 
// where a <p> stops being "in button scope"
const BUTTON_SCOPE = new Set(["applet", "caption", "html", "table", "td", "th", "marquee", "object", "template", "button"])
 
// the parser's "special" elements: where the search for an <li> (or <dd>/<dt>)
// to close stops
const SPECIAL = new Set([
  "address", "applet", "area", "article", "aside", "base", "basefont", "bgsound", "blockquote", "body", "br",
  "button", "caption", "center", "col", "colgroup", "dd", "details", "dir", "div", "dl", "dt", "embed",
  "fieldset", "figcaption", "figure", "footer", "form", "frame", "frameset", "h1", "h2", "h3", "h4", "h5", "h6",
  "head", "header", "hgroup", "hr", "html", "iframe", "img", "input", "keygen", "li", "link", "listing", "main",
  "marquee", "menu", "meta", "nav", "noembed", "noframes", "noscript", "object", "ol", "p", "param",
  "plaintext", "pre", "script", "search", "section", "select", "source", "style", "summary", "table", "tbody",
  "td", "template", "textarea", "tfoot", "th", "thead", "title", "tr", "track", "ul", "wbr", "xmp",
])
 
// a table's parts, and the one parent each may have here. Anywhere else the
// parser inserts what's missing (<tbody>, <colgroup>) or ignores the tag
const TABLE_PARENTS: Record<string, string[]> = {
  caption: ["table"], colgroup: ["table"], thead: ["table"], tbody: ["table"], tfoot: ["table"],
  tr: ["thead", "tbody", "tfoot"], td: ["tr"], th: ["tr"], col: ["colgroup"],
}
// inside these, the parser moves what doesn't belong (foster parenting)
const TABLE_CONTEXT = new Set(["table", "thead", "tbody", "tfoot", "tr", "colgroup"])
 
// inside <svg>, these start tags end the SVG (the parser pops out of it)
const SVG_BREAKOUT = new Set([
  "b", "big", "blockquote", "body", "br", "center", "code", "dd", "div", "dl", "dt", "em", "embed",
  "h1", "h2", "h3", "h4", "h5", "h6", "head", "hr", "i", "img", "li", "listing", "menu", "meta", "nobr",
  "ol", "p", "pre", "ruby", "s", "small", "span", "strong", "strike", "sub", "sup", "table", "tt", "u",
  "ul", "var",
])
 
// the HTML standard's case tables for SVG: a tag or attribute name, lowercased
// by the tokenizer, gets its SVG spelling back
const SVG_TAG_CASE = Object.fromEntries([
  "altGlyph", "altGlyphDef", "altGlyphItem", "animateColor", "animateMotion", "animateTransform", "clipPath",
  "feBlend", "feColorMatrix", "feComponentTransfer", "feComposite", "feConvolveMatrix", "feDiffuseLighting",
  "feDisplacementMap", "feDistantLight", "feDropShadow", "feFlood", "feFuncA", "feFuncB", "feFuncG", "feFuncR",
  "feGaussianBlur", "feImage", "feMerge", "feMergeNode", "feMorphology", "feOffset", "fePointLight",
  "feSpecularLighting", "feSpotLight", "feTile", "feTurbulence", "foreignObject", "glyphRef", "linearGradient",
  "radialGradient", "textPath",
].map(name => [name.toLowerCase(), name]))
const SVG_ATTRIBUTE_CASE = Object.fromEntries([
  "attributeName", "attributeType", "baseFrequency", "baseProfile", "calcMode", "clipPathUnits", "diffuseConstant",
  "edgeMode", "filterUnits", "glyphRef", "gradientTransform", "gradientUnits", "kernelMatrix", "kernelUnitLength",
  "keyPoints", "keySplines", "keyTimes", "lengthAdjust", "limitingConeAngle", "markerHeight", "markerUnits",
  "markerWidth", "maskContentUnits", "maskUnits", "numOctaves", "pathLength", "patternContentUnits",
  "patternTransform", "patternUnits", "pointsAtX", "pointsAtY", "pointsAtZ", "preserveAlpha",
  "preserveAspectRatio", "primitiveUnits", "refX", "refY", "repeatCount", "repeatDur", "requiredExtensions",
  "requiredFeatures", "specularConstant", "specularExponent", "spreadMethod", "startOffset", "stdDeviation",
  "stitchTiles", "surfaceScale", "systemLanguage", "tableValues", "targetX", "targetY", "textLength", "viewBox",
  "viewTarget", "xChannelSelector", "yChannelSelector", "zoomAndPan",
].map(name => [name.toLowerCase(), name]))
 
class GiveUp extends Error {}
const giveUp = (reason: string): never => {
  throw new GiveUp(reason)
}
 
// ASCII only: the tokenizer lowercases A-Z and nothing else, and a name with
// anything beyond ASCII in it is not one a component needs
const lowerName = (name: string): string => {
  if (/[^\x21-\x7e]/.test(name)) giveUp(`a name with a character the tokenizer treats specially: ${JSON.stringify(name)}`)
  return name.replace(/[A-Z]/g, char => char.toLowerCase())
}
 
// a code point a numeric reference may name with no fixing up: not NUL, not a
// surrogate or out of range, not one the parser remaps (C1) or reports as a
// control or a noncharacter
const plainCodePoint = (code: number): boolean =>
  code > 0 && code <= 0x10ffff &&
  !(code >= 0xd800 && code <= 0xdfff) &&
  !(code >= 0x80 && code <= 0x9f) &&
  !(code < 0x20 && code !== 0x09 && code !== 0x0a && code !== 0x0c) &&
  code !== 0x0d && code !== 0x7f &&
  !(code >= 0xfdd0 && code <= 0xfdef) && (code & 0xfffe) !== 0xfffe
 
// references decoded as the parser decodes them - or a give-up, for one these
// tables don't hold (the parser's has two thousand; `&notin;` must not come out
// as `¬in;`) or a numeric one the parser would fix up
const decode = (text: string, inAttribute: boolean): string => {
  if (!text.includes("&")) return text
  return text.replace(CHARACTER_REFERENCE_RE, (whole: string, ref: string, offset: number) => {
    if (ref[0] === "#") {
      const hex = ref[1] === "x" || ref[1] === "X"
      const code = parseInt(ref.slice(hex ? 2 : 1).replace(/;$/, ""), hex ? 16 : 10)
      if (!plainCodePoint(code)) giveUp(`a numeric reference the parser fixes up: ${whole}`)
    } else if (ref.endsWith(";") && !isKnownReference(ref.slice(0, -1))) {
      giveUp(`a named reference outside the known tables: ${whole}`)
    }
    return decodeReference(text, whole, ref, offset, inAttribute)
  })
}
 
type BuildNode = {
  tag: string
  attrs: Record<string, string>
  ns?: string
  // a comment is a node in the DOM: the texts on either side of it stay two
  children: (BuildNode | string | null)[]
}
 
type Frame = {
  // the name as the tokenizer gave it (lowercase), which is what end tags match
  name: string
  svg: boolean
  node: BuildNode
}
 
const finish = (node: BuildNode): TemplateNode => {
  const { [COMPONENT_TAG_ATTR]: component, ...attrs } = node.attrs
  return {
    tag: node.tag,
    attrs,
    ...(component === undefined ? {} : { component }),
    ...(node.ns ? { ns: node.ns } : {}),
    children: node.children.flatMap((child): (TemplateNode | string)[] =>
      child === null ? [] : typeof child === "string" ? (child ? [child] : []) : [finish(child)]
    ),
  }
}
 
type StartTag = { name: string; attrs: Record<string, string>; selfClosing: boolean; end: number }
 
// a start tag from `<` at `at`: its name, its attributes (first of two
// duplicates kept, values decoded) and where it ends - by the tokenizer's
// states, so a `>` inside a quoted value doesn't end it
const readStartTag = (src: string, at: number): StartTag => {
  let i = at + 1
  let rawName = ""
  while (i < src.length && !isWhitespace(src[i]) && src[i] !== "/" && src[i] !== ">") rawName += src[i++]
  const name = lowerName(rawName)
  const attrs: Record<string, string> = {}
  let selfClosing = false
  for (;;) {
    while (isWhitespace(src[i])) i++
    const char = src[i]
    Iif (char === undefined) return giveUp("a start tag cut off by the end of the file")
    if (char === ">") return { name, attrs, selfClosing, end: i + 1 }
    if (char === "/") {
      Eif (src[i + 1] === ">") return { name, attrs, selfClosing: true, end: i + 2 }
      i++
      continue
    }
    // an attribute name may start with `=`; after that it runs to whitespace,
    // `/`, `>` or `=`
    let rawAttr = src[i++]
    while (i < src.length && !isWhitespace(src[i]) && src[i] !== "/" && src[i] !== ">" && src[i] !== "=") rawAttr += src[i++]
    const attrName = lowerName(rawAttr)
    let value = ""
    let j = i
    while (isWhitespace(src[j])) j++
    if (src[j] === "=") {
      i = j + 1
      while (isWhitespace(src[i])) i++
      const quote = src[i]
      if (quote === "\"" || quote === "'") {
        const close = src.indexOf(quote, i + 1)
        if (close === -1) return giveUp("an attribute value cut off by the end of the file")
        value = src.slice(i + 1, close)
        i = close + 1
      } else Eif (quote !== ">") {
        const start = i
        while (i < src.length && !isWhitespace(src[i]) && src[i] !== ">") i++
        value = src.slice(start, i)
      }
      value = decode(value, true)
    }
    if (!(attrName in attrs)) attrs[attrName] = value
  }
}
 
// the text of a raw text element, up to its own end tag - which must be just
// that, `</name>` with nothing but whitespace before its `>`
const readRawText = (src: string, at: number, name: string): { text: string; end: number } => {
  const re = new RegExp(`</${name}(?=[\\t\\n\\f\\r />])`, "gi")
  re.lastIndex = at
  const match = re.exec(src)
  if (!match) return giveUp(`<${name}> not closed`)
  const text = src.slice(at, match.index)
  // a <script>'s text has escape states of its own (`<!--` in a script)
  if (name === "script" && text.includes("<!--")) giveUp("`<!--` inside a <script>")
  let end = match.index + match[0].length
  while (isWhitespace(src[end])) end++
  Iif (src[end] !== ">") giveUp(`an end tag with something in it: </${name}…>`)
  return { text, end: end + 1 }
}
 
type Read = { file: ParsedFile } | { reason: string }
 
// the file, as the runtime's parseFile would read it - or why not
export const readComponent = (source: string): Read => {
  try {
    return { file: build(source) }
  } catch (error) {
    Eif (error instanceof GiveUp) return { reason: error.message }
    throw error
  }
}
 
// the file as ParsedFile, or null where only the browser's parser can say
export const parseComponent = (source: string): ParsedFile | null => {
  const read = readComponent(source)
  return "file" in read ? read.file : null
}
 
const build = (source: string): ParsedFile => {
  // the input stream: newlines normalized. A NUL is a parse error with
  // per-state handling, and nothing a component writes
  const src = prepareSource(source).replace(/\r\n?/g, "\n")
  if (src.includes("\0")) giveUp("a NUL character")
 
  const root: BuildNode = { tag: "#root", attrs: {}, children: [] }
  const stack: Frame[] = [{ name: "#root", svg: false, node: root }]
  const current = () => stack[stack.length - 1]
 
  // a top-level <template>'s content, by its node: hashed for its scope
  const templateStart = new Map<BuildNode, number>()
  const templateSource = new Map<BuildNode, string>()
 
  const appendText = (text: string) => {
    if (!text) return
    const frame = current()
    if (!frame.svg && TABLE_CONTEXT.has(frame.name) && !ONLY_WHITESPACE_RE.test(text)) {
      giveUp(`text inside a <${frame.name}> (the parser moves it out of the table)`)
    }
    const children = frame.node.children
    const last = children[children.length - 1]
    if (typeof last === "string") children[children.length - 1] = last + text
    else children.push(text)
  }
 
  const onStack = (name: string) => stack.some(frame => !frame.svg && frame.name === name)
 
  const pInButtonScope = (): boolean => {
    for (let depth = stack.length - 1; depth > 0; depth--) {
      const frame = stack[depth]
      Iif (frame.svg) {
        if (["foreignobject", "desc", "title"].includes(frame.name)) return false
        continue
      }
      if (frame.name === "p") return true
      if (BUTTON_SCOPE.has(frame.name)) return false
    }
    return false
  }
 
  // what an <li> (or <dd>/<dt>) start tag would close: walking up, one of
  // `closes` before any special element other than address, div and p
  const closesListItem = (closes: string[]): boolean => {
    for (let depth = stack.length - 1; depth > 0; depth--) {
      const frame = stack[depth]
      Iif (frame.svg) return false
      if (closes.includes(frame.name)) return true
      if (SPECIAL.has(frame.name) && !["address", "div", "p"].includes(frame.name)) return false
    }
    return false
  }
 
  const insert = (node: BuildNode) => current().node.children.push(node)
 
  const startSvg = (tag: StartTag) => {
    const frame = current()
    Iif (!frame.svg && TABLE_CONTEXT.has(frame.name)) giveUp(`<${tag.name}> inside <${frame.name}> (the parser moves it out of the table)`)
    if (frame.svg && (frame.name === "desc" || frame.name === "title")) giveUp(`<${tag.name}> inside an SVG <${frame.name}>`)
    if (frame.svg && (SVG_BREAKOUT.has(tag.name) || (tag.name === "font" && ["color", "face", "size"].some(a => a in tag.attrs)))) {
      giveUp(`<${tag.name}> inside <svg> (the parser ends the SVG there)`)
    }
    if (tag.name === "foreignobject" || tag.name === "math") giveUp(`<${tag.name}> inside <svg>`)
    const attrs = Object.fromEntries(Object.entries(tag.attrs).map(([name, value]) => [SVG_ATTRIBUTE_CASE[name] ?? name, value]))
    const node: BuildNode = { tag: SVG_TAG_CASE[tag.name] ?? tag.name, attrs, ns: SVG_NS, children: [] }
    insert(node)
    Eif (!tag.selfClosing) stack.push({ name: tag.name, svg: true, node })
  }
 
  const startHtml = (tag: StartTag) => {
    const { name } = tag
    const frame = current()
    if (GIVE_UP_TAGS.has(name)) giveUp(`<${name}>`)
    const parents = TABLE_PARENTS[name]
    if (parents && (frame.svg || !parents.includes(frame.name))) giveUp(`<${name}> inside <${frame.name}>`)
    if (!frame.svg && TABLE_CONTEXT.has(frame.name) && !parents?.includes(frame.name)) {
      const inHead = frame.name !== "colgroup" && (name === "script" || name === "style")
      Eif (!inHead) giveUp(`<${name}> inside <${frame.name}> (the parser moves it out of the table)`)
    }
    if (CLOSES_P.has(name) && pInButtonScope()) giveUp(`<${name}> inside an open <p> (the parser closes the <p>)`)
    if (HEADINGS.has(name) && HEADINGS.has(frame.name)) giveUp(`<${name}> inside <${frame.name}>`)
    if (name === "li" && closesListItem(["li"])) giveUp("<li> inside an open <li>")
    if ((name === "dd" || name === "dt") && closesListItem(["dd", "dt"])) giveUp(`<${name}> inside an open <dd>/<dt>`)
    if (["a", "button", "nobr", "form"].includes(name) && onStack(name)) giveUp(`<${name}> inside <${name}>`)
    if ((name === "option" || name === "optgroup") && frame.name === "option") giveUp(`<${name}> inside <option>`)
 
    const node: BuildNode = { tag: name, attrs: tag.attrs, children: [] }
    insert(node)
    if (VOID_TAGS.has(name)) return
    stack.push({ name, svg: false, node })
  }
 
  const end = (rawName: string) => {
    const name = lowerName(rawName)
    if (VOID_TAGS.has(name)) giveUp(`an end tag for a void element: </${name}>`)
    const frame = current()
    if (stack.length === 1 || frame.name !== name) giveUp(`</${name}> where <${frame.name}> is open`)
    stack.pop()
  }
 
  let at = 0
  while (at < src.length) {
    const lt = src.indexOf("<", at)
    if (lt === -1) {
      appendText(decode(src.slice(at), false))
      break
    }
    appendText(decode(src.slice(at, lt), false))
    at = lt
 
    if (src.startsWith("<!--", at)) {
      current().node.children.push(null)
      if (src.startsWith(">", at + 4)) at += 5
      else if (src.startsWith("->", at + 4)) at += 6
      else {
        const close = src.indexOf("-->", at + 4)
        const bang = src.indexOf("--!>", at + 4)
        if (close === -1) giveUp("a comment not closed")
        if (bang !== -1 && bang < close) giveUp("a comment closed by `--!>`")
        at = close + 3
      }
      continue
    }
    const next = src[at + 1]
    if (next === "!" || next === "?") giveUp(`markup the parser reads as a bogus comment, a doctype or CDATA: ${src.slice(at, at + 9)}`)
 
    if (next === "/") {
      Iif (!isAsciiLetter(src[at + 2])) giveUp("`</` not followed by a tag name")
      let i = at + 2
      let rawName = ""
      while (i < src.length && !isWhitespace(src[i]) && src[i] !== "/" && src[i] !== ">") rawName += src[i++]
      while (isWhitespace(src[i])) i++
      if (src[i] !== ">") giveUp(`an end tag with something in it: </${rawName}…>`)
      const frame = current()
      const name = lowerName(rawName)
      if (frame.name === "template" && name === "template" && stack.length === 2) templateSource.set(frame.node, src.slice(templateStart.get(frame.node), at))
      end(rawName)
      at = i + 1
      continue
    }
 
    if (!isAsciiLetter(next)) {
      appendText("<")
      at++
      continue
    }
 
    const tag = readStartTag(src, at)
    at = tag.end
    const frame = current()
    if (frame.svg || tag.name === "svg") {
      startSvg(tag)
      continue
    }
    startHtml(tag)
    const { name } = tag
    if (name === "template" && stack.length === 2) templateStart.set(current().node, at)
    if (LEADING_NEWLINE_TAGS.has(name)) {
      // the parser drops a newline *token*: a reference that decodes to one
      // would be dropped too, and that is not worth following
      if (src[at] === "&" && decode(src.slice(at, at + 32).split("<")[0], false).startsWith("\n")) {
        giveUp(`a reference to a newline right after <${name}>`)
      }
      if (src[at] === "\n") at++
    }
    if (RAW_TEXT_TAGS.has(name) || ESCAPABLE_RAW_TEXT_TAGS.has(name)) {
      const raw = readRawText(src, at, name)
      appendText(ESCAPABLE_RAW_TEXT_TAGS.has(name) ? decode(raw.text, false) : raw.text)
      stack.pop()
      at = raw.end
    }
  }
 
  if (stack.length > 1) giveUp(`<${current().name}> not closed at the end of the file`)
 
  // the file's own component: every top-level element but a <template>; each
  // <template> declares another, by its name. Text at the top level is not
  // read by the runtime either
  const elements = root.children.filter((child): child is BuildNode => child !== null && typeof child !== "string")
  const nodes: TemplateNode[] = []
  const templates: NonNullable<ParsedFile["templates"]> = []
  elements.forEach(node => {
    if (node.ns || node.tag !== "template") return void nodes.push(finish(node))
    const children = node.children.filter((child): child is BuildNode => child !== null && typeof child !== "string")
    const declared: ParsedComponent & { name: string | null } = {
      name: node.attrs.name ?? null,
      nodes: children.map(finish),
      // the runtime hashes the template's innerHTML, which node can't
      // reproduce; its source is as stable, and as distinct
      scope: scopeHash(templateSource.get(node) ?? ""),
    }
    templates.push(declared)
  })
  return { nodes, scope: scopeHash(source), ...(templates.length ? { templates } : {}) }
}