package markup
import (
"io/fs"
"os"
"path/filepath"
"regexp"
"strings"
"testing"
)
func TestReservedHeadingIDsAreSuffixed(t *testing.T) {
md := "## Find\n\n## Chatlog\n\n## Toasts\n\n## Refpop\n\n## Composer\n\n" +
"## Constructor\n\n## Prototype\n\n## Document\n\n## Window\n\n" +
"## Location\n\n## History\n\n## Top\n\n## Parent\n\n## Self\n\n" +
"## Frames\n\n## Length\n\n## Name\n\n## Cookie\n"
out, err := Render([]byte(md), nil)
if err != nil {
t.Fatal(err)
}
s := string(out)
for _, id := range []string{
"find", "chatlog", "toasts", "refpop", "composer",
"constructor", "prototype", "document", "window",
"location", "history", "top", "parent", "self",
"frames", "length", "name", "cookie",
} {
if strings.Contains(s, `id="`+id+`"`) {
t.Errorf("FAIL: reserved id=%q emitted:\n%s", id, s)
}
if !strings.Contains(s, `id="`+id+`-1"`) {
t.Errorf("FAIL: expected suffixed id=%q:\n%s", id+"-1", s)
}
}
// Repeats and explicit -1 headings increment without colliding.
rep, err := Render([]byte("## Find\n\n## Find\n\n## Find-1\n"), nil)
if err != nil {
t.Fatal(err)
}
rs := string(rep)
for _, want := range []string{`id="find-1"`, `id="find-2"`, `id="find-1-1"`} {
if !strings.Contains(rs, want) {
t.Errorf("FAIL: repeated reserved headings missing %s:\n%s", want, rs)
}
}
// Outline (used by Fossil wiki and HTML docs) also suffixes reserved headings.
anchored, heads := Outline([]byte("<h2>Find</h2><h2>Chatlog</h2>"))
if strings.Contains(string(anchored), `id="find"`) || strings.Contains(string(anchored), `id="chatlog"`) {
t.Errorf("FAIL: Outline emitted reserved id:\n%s", anchored)
}
if len(heads) != 2 || heads[0].ID != "find-1" || heads[1].ID != "chatlog-1" {
t.Errorf("FAIL: Outline headings = %+v, want find-1 and chatlog-1", heads)
}
}
func TestReservedPatternTermination(t *testing.T) {
inputs := []string{
"l1", "l01234567-n1", "chatmsg-1", "chatbody-1",
"p-0123456789ab", "vote-0123456789ab", "km0", "pa0", "pm0", "ps0",
"m0-c0", "mtf-0123456789ab", "mtz-0123456789ab", "mv-0123456789ab",
"exc-0123456789ab", "a-0-b-1", "s-0-1", "s-0-1-2",
"approve-01jabcdef1234567890abcd", "attn-all", "attn-msg-7",
"release-v1", "f-readme", "mf-readme",
}
for _, in := range inputs {
out, err := Render([]byte("## "+in+"\n\n## "+in+"\n\n## "+in+"\n"), nil)
if err != nil {
t.Fatalf("Render(%q): %v", in, err)
}
s := string(out)
if strings.Contains(s, `id="`+in+`"`) {
t.Errorf("FAIL: reserved pattern %q leaked in Render:\n%s", in, s)
}
anch, heads := Outline([]byte("<h2>" + in + "</h2>"))
if len(heads) != 1 || isReservedID(heads[0].ID) || strings.Contains(string(anch), `id="`+in+`"`) {
t.Errorf("FAIL: Outline(%q) emitted reserved id %+v:\n%s", in, heads, anch)
}
san := Sanitize(`<h2 id="` + in + `">X</h2>`)
if strings.Contains(san, `id="`+in+`"`) {
t.Errorf("FAIL: Sanitize(%q) leaked reserved id:\n%s", in, san)
}
}
}
func TestReservedInDocMarkdownLinksAreRewritten(t *testing.T) {
out, err := Render([]byte("## Find\n\n[Jump](#find)\n\n## Chatlog\n\n[Chat](#chatlog)\n\n## \\_\\_proto\\_\\_\n\n[Proto](#__proto__)\n"), nil)
if err != nil {
t.Fatal(err)
}
s := string(out)
for _, want := range []string{`id="find-1"`, `href="#find-1"`, `id="chatlog-1"`, `href="#chatlog-1"`, `id="__proto__-1"`, `href="#__proto__-1"`} {
if !strings.Contains(s, want) {
t.Errorf("FAIL: missing %s:\n%s", want, s)
}
}
// Unrelated fragment with no matching heading stays untouched.
noHeading, err := Render([]byte("[Top](#top)\n"), nil)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(noHeading), `href="#top"`) {
t.Errorf("FAIL: unrelated fragment rewritten:\n%s", noHeading)
}
}
func TestOutlineReservedIDDeduplicationAndSpacing(t *testing.T) {
anchored, heads := Outline([]byte(`<h2 id="find">A</h2><h2 id="find-1">B</h2>`))
s := string(anchored)
if strings.Contains(s, "<h2 ") {
t.Errorf("FAIL: Outline doubled space after tag:\n%s", s)
}
if len(heads) != 2 || heads[0].ID == heads[1].ID {
t.Fatalf("FAIL: Outline produced duplicate IDs: %+v\n%s", heads, s)
}
if heads[0].ID != "find-2" || heads[1].ID != "find-1" {
t.Errorf("FAIL: Outline headings = %+v, want find-2 and find-1", heads)
}
}
func TestReservedGitHubAnchorsAreSuffixed(t *testing.T) {
// NBSP makes Quarry's slug "nbspfind" while GitHub's slug is "find",
// and "\_\_proto\_\_" makes Quarry's slug "--proto--" while GitHub's
// slug is "__proto__". Both extra anchors must be suffixed rather than
// colliding or being dropped.
src := "## Find\n\n## Find\n\n## Document\n\n## \\_\\_proto\\_\\_\n"
out, err := Render([]byte(src), nil)
if err != nil {
t.Fatal(err)
}
s := string(out)
for _, banned := range []string{`id="find"`, `id="document"`, `id="__proto__"`} {
if strings.Contains(s, banned) {
t.Errorf("FAIL: reserved GitHub anchor %s emitted:\n%s", banned, s)
}
}
for _, want := range []string{`id="find-1"`, `id="find-2"`, `id="document-1"`, `id="__proto__-1"`} {
if !strings.Contains(s, want) {
t.Errorf("FAIL: missing suffixed GitHub anchor %s:\n%s", want, s)
}
}
}
func TestReservedFootnoteIDsAreSuffixed(t *testing.T) {
origFn, hadFn := reservedIDs["fn:1"]
origRef, hadRef := reservedIDs["fnref:1"]
reservedIDs["fn:1"] = true
reservedIDs["fnref:1"] = true
t.Cleanup(func() {
if hadFn {
reservedIDs["fn:1"] = origFn
} else {
delete(reservedIDs, "fn:1")
}
if hadRef {
reservedIDs["fnref:1"] = origRef
} else {
delete(reservedIDs, "fnref:1")
}
})
out, err := Render([]byte("Sentence with a note.[^1]\n\n[^1]: Note body.\n"), nil)
if err != nil {
t.Fatal(err)
}
s := string(out)
for _, banned := range []string{`id="fn:1"`, `id="fnref:1"`} {
if strings.Contains(s, banned) {
t.Errorf("FAIL: reserved footnote %s emitted:\n%s", banned, s)
}
}
for _, want := range []string{`id="fnref:1-1"`, `href="#fn:1-1"`, `id="fn:1-1"`, `href="#fnref:1-1"`} {
if !strings.Contains(s, want) {
t.Errorf("FAIL: footnote missing rewritten %s:\n%s", want, s)
}
}
}
func TestReservedRawHTMLIDsAreSuffixed(t *testing.T) {
in := `<h2 id="find">Find</h2><a id="chatlog"></a><a href="#find">jump</a>`
for name, fn := range map[string]func(string) string{
"Sanitize": Sanitize,
"SanitizeDoc": SanitizeDoc,
"FossilWiki": func(s string) string {
b, err := RenderFossilWiki([]byte(s), nil)
if err != nil {
t.Fatal(err)
}
return string(b)
},
} {
got := fn(in)
if strings.Contains(got, `id="find"`) || strings.Contains(got, `id="chatlog"`) {
t.Errorf("FAIL: %s leaked reserved id:\n%s", name, got)
}
for _, want := range []string{`id="find-1"`, `id="chatlog-1"`, `href="#find-1"`} {
if !strings.Contains(got, want) {
t.Errorf("FAIL: %s missing %s:\n%s", name, want, got)
}
}
}
}
// TestAllTemplateAndScriptIDsAreReserved walks the repository's templates
// and scripts and fails if any id="..." attribute (or hardcoded script id
// lookup) is missing from the reserved-name list.
func TestAllTemplateAndScriptIDsAreReserved(t *testing.T) {
skipFiles := map[string]bool{
filepath.FromSlash("../../internal/web/assets/datastar.js"): true,
filepath.FromSlash("../../internal/web/assets/geo.js"): true,
}
// Dynamic id="..." templates paired with concrete representative samples
// that the reserved-name matcher must reject.
dynamicSamples := map[string][]string{
"{{.ID}}": {"find-suggest", "tl-suggest", "people-suggest", "m0-c0"},
"{{.ID}}-n": {"find-suggest-n", "tl-suggest-n", "people-suggest-n"},
"{{$id}}": {"git-mirror", "fossil-mirror"},
"{{$p.ID}}-{{.Field}}": {"git-mirror-remote", "git-mirror-branch", "fossil-mirror-user", "fossil-mirror-password"},
"{{$p.ID}}-{{.Field}}-err": {"git-mirror-remote-err", "fossil-mirror-password-err"},
"L{{.N}}": {"L1", "L42"},
"chatmsg-%d": {"chatmsg-1", "chatmsg-99"},
"chatbody-%d": {"chatbody-1", "chatbody-99"},
`p-{{printf "%.12s" .Hash}}`: {"p-0123456789ab"},
`vote-{{printf "%.12s" .Hash}}`: {"vote-0123456789ab"},
"{{rowid $path .}}": {"L01234567-o1", "L01234567-n12"},
"{{splitid $path .}}": {"L01234567-n1", "L01234567-o5"},
"km{{.Idx}}": {"km0", "km12"},
"pa{{$i}}": {"pa0", "pa3"},
"pm{{$i}}": {"pm0", "pm3"},
"ps{{$i}}": {"ps0", "ps3"},
"mtf-{{.ID}}": {"mtf-0123456789ab"},
"mtz-{{.ID}}": {"mtz-0123456789ab"},
"mv-{{$id}}": {"mv-0123456789ab"},
"exc-{{.Sig}}": {"exc-0123456789ab"},
"a-{{$.CIRunView.Anchor}}-{{$step}}-{{.N}}": {"a-0123456789ab-build-1"},
"s-{{$.CIRunView.Anchor}}-{{.Attempt}}-{{.Seq}}": {"s-0123456789ab-1-2"},
"s-{{$.CIRunView.Anchor}}-{{.Seq}}": {"s-0123456789ab-2"},
"v-{{$field}}": {"v-status", "v-resolution", "v-type", "v-severity", "v-priority", "v-subsystem"},
"t-opts-{{$c.Key}}": {"t-opts-status", "t-opts-resolution", "t-opts-type", "t-opts-severity", "t-opts-priority", "t-opts-subsystem", "t-opts-assigned_to", "t-opts-author", "t-opts-repo"},
"approve-{{$.SignOff.ID}}": {"approve-01jabcdef1234567890abcd"},
// Page-specific / non-user-content templates with dynamic suffixes:
"{{.ElemID}}": {"attn-01jabcdef1234567890abcd", "attn-msg-7", "attn-all"},
"f-{{pathesc .Path}}": {"f-readme.md", "f-a-b"},
"mf-{{.Path}}": {"mf-readme.md", "mf-cmd-main.go"},
"release-{{.Name}}": {"release-v1.0.0", "release-2026-11-30"},
"{{.Module}}": nil,
}
idAttrRe := regexp.MustCompile(`(?:^|[^a-zA-Z0-9_-])id\s*=\s*(?:\\"((?:[^"<\n{}]|{{[^}\n]*}})+)\\"|"((?:[^"<\n{}]|{{[^}\n]*}})+)"|'((?:[^'<\n{}]|{{[^}\n]*}})+)')`)
gebiRe := regexp.MustCompile(`getElementById\(\s*(?:"([^"]+)"|'([^']+)')\s*\)`)
qselRe := regexp.MustCompile(`(?:querySelector(?:All)?|closest|matches)\(\s*(?:"([^"]*#[^"]*)"|'([^']*#[^']*)')\s*\)`)
hashIDRe := regexp.MustCompile(`#([a-zA-Z0-9_-]+)`)
var scanned int
for _, root := range []string{"../../internal/web", "../../internal/notify", "../../cmd"} {
err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
return nil
}
if skipFiles[p] || strings.HasSuffix(p, "_test.go") {
return nil
}
ext := filepath.Ext(p)
if ext != ".go" && ext != ".html" && ext != ".tmpl" && ext != ".js" {
return nil
}
raw, err := os.ReadFile(p)
if err != nil {
return err
}
scanned++
src := string(raw)
// 1. Check id="..." attributes in templates, Go HTML strings, and JS.
for _, m := range idAttrRe.FindAllStringSubmatch(src, -1) {
val := m[1]
if val == "" {
val = m[2]
}
if val == "" {
val = m[3]
}
// Ignore JS string concatenation fragments like `' + id + '` and CSS/JS vars.
if strings.Contains(val, "' +") || strings.Contains(val, `" +`) || strings.HasPrefix(val, "$") {
continue
}
if strings.Contains(val, "{{") || strings.Contains(val, "%") {
samples, ok := dynamicSamples[val]
if !ok {
t.Errorf("FAIL: %s has unrecognized dynamic id=%q; add it to reserved list and dynamicSamples", p, val)
continue
}
for _, s := range samples {
if !isReservedID(s) {
t.Errorf("FAIL: %s dynamic id=%q sample %q is missing from reserved list", p, val, s)
}
}
continue
}
if !isReservedID(val) {
t.Errorf("FAIL: %s id=%q is missing from reserved list", p, val)
}
}
// 2. Check hardcoded script lookups: getElementById("...") and querySelector("#...").
for _, m := range gebiRe.FindAllStringSubmatch(src, -1) {
val := m[1]
if val == "" {
val = m[2]
}
if !isReservedID(val) {
t.Errorf("FAIL: %s getElementById(%q) is missing from reserved list", p, val)
}
}
for _, m := range qselRe.FindAllStringSubmatch(src, -1) {
sel := m[1]
if sel == "" {
sel = m[2]
}
for _, hm := range hashIDRe.FindAllStringSubmatch(sel, -1) {
id := hm[1]
if strings.Contains(id, "{{") {
continue
}
if !isReservedID(id) {
t.Errorf("FAIL: %s selector %q references #%s which is missing from reserved list", p, sel, id)
}
}
}
return nil
})
if err != nil {
t.Fatal(err)
}
}
if scanned == 0 {
t.Fatal("FAIL: scanned 0 files")
}
}