Phase 3 part 3: the audit, ranked by traffic, with AI visibility
A polite crawl of each website (Search Console's busiest pages, the sitemap, then links; up to 300 pages; robots.txt honoured) checks titles and descriptions (characters and pixels), headings, canonical, noindex, status and redirects, broken links (outside ones twice), alt text, Open Graph, JSON-LD, text without JavaScript, and whether the title says what the page's main search asks. Issues are ranked by severity, then the page's clicks and impressions. AI visibility: AI crawlers in robots.txt, llms.txt, structured data, Organization data. Optional PageSpeed checks. Weekly in the background, or Audit now. Schema 14. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,774 @@
|
||||
package seo
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"golang.org/x/net/html"
|
||||
|
||||
"supermarket/internal/api/sitemap"
|
||||
"supermarket/internal/db"
|
||||
)
|
||||
|
||||
// MaxAuditPages is how many pages one audit reads.
|
||||
const MaxAuditPages = 300
|
||||
|
||||
// maxExternalLinks is how many outside links an audit checks.
|
||||
const maxExternalLinks = 150
|
||||
|
||||
// Severity of an issue.
|
||||
const (
|
||||
SevError = "error" // the page can't rank, or visitors hit a wall
|
||||
SevWarning = "warning" // it ranks or gets clicked less than it could
|
||||
SevNotice = "notice" // worth fixing when you're there
|
||||
)
|
||||
|
||||
// Issue is one problem on one page.
|
||||
type Issue struct {
|
||||
Page string `json:"page"`
|
||||
Code string `json:"code"`
|
||||
Severity string `json:"severity"`
|
||||
Title string `json:"title"` // what's wrong, short
|
||||
Detail string `json:"detail"` // the specifics: the text, the length, the link
|
||||
Traffic Numbers `json:"traffic"`
|
||||
}
|
||||
|
||||
// PageReport is what the audit read on one page.
|
||||
type PageReport struct {
|
||||
URL string `json:"url"`
|
||||
Status int `json:"status"`
|
||||
FinalURL string `json:"final_url,omitempty"` // after redirects
|
||||
Redirects int `json:"redirects,omitempty"`
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
H1 []string `json:"h1"`
|
||||
Canonical string `json:"canonical"`
|
||||
Noindex bool `json:"noindex"`
|
||||
Lang string `json:"lang"`
|
||||
OG bool `json:"og"`
|
||||
JSONLD []string `json:"jsonld"` // @types
|
||||
TextChars int `json:"text_chars"`
|
||||
ImagesNoAlt int `json:"images_no_alt"`
|
||||
HeadingSkips []string `json:"heading_skips"`
|
||||
InSitemap bool `json:"in_sitemap"`
|
||||
FromGSC bool `json:"from_gsc"`
|
||||
Error string `json:"error,omitempty"`
|
||||
internalLinks []string
|
||||
externalLinks []string
|
||||
}
|
||||
|
||||
// Check is a site-wide pass or fail, for AI visibility and the basics.
|
||||
type SiteCheck struct {
|
||||
Group string `json:"group"` // ai, basics
|
||||
OK bool `json:"ok"`
|
||||
Title string `json:"title"`
|
||||
Detail string `json:"detail"`
|
||||
}
|
||||
|
||||
// Audit is one run over a site.
|
||||
type Audit struct {
|
||||
ID int64 `json:"-"`
|
||||
Site string `json:"site"` // the website's address
|
||||
Property string `json:"property"` // its Search Console property, for traffic
|
||||
Status string `json:"-"` // running, done, failed
|
||||
StartedAt time.Time `json:"-"`
|
||||
FinishedAt time.Time `json:"-"`
|
||||
Error string `json:"-"`
|
||||
Pages []PageReport `json:"pages"`
|
||||
Issues []Issue `json:"issues"`
|
||||
Checks []SiteCheck `json:"checks"`
|
||||
Speed []Speed `json:"speed,omitempty"`
|
||||
}
|
||||
|
||||
// Counts is how many issues of each severity.
|
||||
func (a *Audit) Counts() map[string]int {
|
||||
out := map[string]int{}
|
||||
for _, i := range a.Issues {
|
||||
out[i.Severity]++
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Fetcher reads web pages; the audit's own HTTP client in the app, a fake
|
||||
// server's in tests.
|
||||
type Fetcher struct {
|
||||
Client *http.Client
|
||||
UserAgent string
|
||||
Delay time.Duration // between requests, to be polite
|
||||
}
|
||||
|
||||
// NewFetcher returns a fetcher that doesn't follow redirects itself, so
|
||||
// they can be counted.
|
||||
func NewFetcher(userAgent string) *Fetcher {
|
||||
return &Fetcher{
|
||||
Client: &http.Client{Timeout: 30 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error {
|
||||
return http.ErrUseLastResponse
|
||||
}},
|
||||
UserAgent: userAgent,
|
||||
Delay: 150 * time.Millisecond,
|
||||
}
|
||||
}
|
||||
|
||||
type fetched struct {
|
||||
status int
|
||||
final string
|
||||
redirects int
|
||||
ctype string
|
||||
body []byte
|
||||
}
|
||||
|
||||
// get fetches a URL, following up to 5 redirects and counting them.
|
||||
func (f *Fetcher) get(ctx context.Context, u string, method string, limit int64) (*fetched, error) {
|
||||
out := &fetched{final: u}
|
||||
for i := 0; i < 6; i++ {
|
||||
req, err := http.NewRequestWithContext(ctx, method, out.final, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("User-Agent", f.UserAgent)
|
||||
res, err := f.Client.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if res.StatusCode >= 300 && res.StatusCode < 400 {
|
||||
res.Body.Close()
|
||||
loc, err := res.Request.URL.Parse(res.Header.Get("Location"))
|
||||
if err != nil || res.Header.Get("Location") == "" {
|
||||
out.status = res.StatusCode
|
||||
return out, nil
|
||||
}
|
||||
out.final = loc.String()
|
||||
out.redirects++
|
||||
continue
|
||||
}
|
||||
out.status = res.StatusCode
|
||||
out.ctype = res.Header.Get("Content-Type")
|
||||
if method == http.MethodGet && limit > 0 {
|
||||
out.body, _ = io.ReadAll(io.LimitReader(res.Body, limit))
|
||||
}
|
||||
res.Body.Close()
|
||||
return out, nil
|
||||
}
|
||||
return nil, errors.New("too many redirects")
|
||||
}
|
||||
|
||||
// RunAudit reads a site and checks every page it can find: the sitemap's,
|
||||
// Search Console's, and those linked from them. Issues are ranked by the
|
||||
// page's clicks and impressions over the last 90 days.
|
||||
func RunAudit(ctx context.Context, d *db.DB, f *Fetcher, siteURL, property string) (*Audit, error) {
|
||||
base, err := url.Parse(strings.TrimRight(strings.TrimSpace(siteURL), "/") + "/")
|
||||
if err != nil || base.Host == "" {
|
||||
return nil, fmt.Errorf("%q isn't a website address", siteURL)
|
||||
}
|
||||
a := &Audit{Site: base.String(), Property: property}
|
||||
host := strings.TrimPrefix(base.Hostname(), "www.")
|
||||
|
||||
// robots.txt, llms.txt and the sitemap.
|
||||
var rob *robots
|
||||
if r, err := f.get(ctx, base.Scheme+"://"+base.Host+"/robots.txt", http.MethodGet, 512<<10); err == nil && r.status == 200 {
|
||||
rob = parseRobots(string(r.body))
|
||||
}
|
||||
llms, _ := f.get(ctx, base.Scheme+"://"+base.Host+"/llms.txt", http.MethodGet, 64<<10)
|
||||
smc := sitemap.New(f.UserAgent)
|
||||
inSitemap := map[string]bool{}
|
||||
var mapErr error
|
||||
maps := []string{""}
|
||||
if rob != nil && len(rob.sitemaps) > 0 {
|
||||
maps = rob.sitemaps
|
||||
}
|
||||
for _, m := range maps {
|
||||
pages, err := smc.AllPages(ctx, base.String(), m)
|
||||
if err != nil {
|
||||
mapErr = err
|
||||
continue
|
||||
}
|
||||
mapErr = nil
|
||||
for _, p := range pages {
|
||||
inSitemap[normalize(p.URL)] = true
|
||||
}
|
||||
}
|
||||
|
||||
// Pages: the home page, the sitemap's, Search Console's, then links.
|
||||
traffic := map[string]Numbers{}
|
||||
if property != "" {
|
||||
if from, to, ok := period(d, property, RanksDays); ok {
|
||||
if rows, err := pageNumbers(d, property, from, to); err == nil {
|
||||
for _, p := range rows {
|
||||
traffic[normalize(p.Page)] = p.Numbers
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
queue := []string{normalize(base.String())}
|
||||
seen := map[string]bool{queue[0]: true}
|
||||
add := func(u string) {
|
||||
n := normalize(u)
|
||||
if n == "" || seen[n] || len(seen) >= MaxAuditPages {
|
||||
return
|
||||
}
|
||||
if p, err := url.Parse(n); err != nil || strings.TrimPrefix(p.Hostname(), "www.") != host {
|
||||
return
|
||||
}
|
||||
seen[n] = true
|
||||
queue = append(queue, n)
|
||||
}
|
||||
// Busiest pages first, so a big site's cut-off drops the quiet ones.
|
||||
byTraffic := make([]string, 0, len(traffic))
|
||||
for u := range traffic {
|
||||
byTraffic = append(byTraffic, u)
|
||||
}
|
||||
slices.SortFunc(byTraffic, func(x, y string) int { return traffic[y].Impressions - traffic[x].Impressions })
|
||||
for _, u := range byTraffic {
|
||||
add(u)
|
||||
}
|
||||
mapped := make([]string, 0, len(inSitemap))
|
||||
for u := range inSitemap {
|
||||
mapped = append(mapped, u)
|
||||
}
|
||||
slices.Sort(mapped)
|
||||
for _, u := range mapped {
|
||||
add(u)
|
||||
}
|
||||
|
||||
external := map[string][]string{} // link → pages linking to it
|
||||
internalFrom := map[string][]string{}
|
||||
for i := 0; i < len(queue); i++ {
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
u := queue[i]
|
||||
p := PageReport{URL: u, InSitemap: inSitemap[u], FromGSC: traffic[u].Impressions > 0}
|
||||
pu, _ := url.Parse(u)
|
||||
if rob != nil && !rob.allowed(f.UserAgent, pu.EscapedPath()) && !rob.allowed("Googlebot", pu.EscapedPath()) {
|
||||
p.Error = "robots.txt blocks it"
|
||||
a.Pages = append(a.Pages, p)
|
||||
continue
|
||||
}
|
||||
r, err := f.get(ctx, u, http.MethodGet, 4<<20)
|
||||
time.Sleep(f.Delay)
|
||||
if err != nil {
|
||||
p.Error = err.Error()
|
||||
a.Pages = append(a.Pages, p)
|
||||
continue
|
||||
}
|
||||
p.Status, p.Redirects = r.status, r.redirects
|
||||
if r.redirects > 0 {
|
||||
p.FinalURL = r.final
|
||||
}
|
||||
if r.status == 200 && strings.Contains(r.ctype, "html") {
|
||||
readPage(&p, r.final, r.body)
|
||||
for _, l := range p.internalLinks {
|
||||
internalFrom[l] = append(internalFrom[l], u)
|
||||
add(l)
|
||||
}
|
||||
for _, l := range p.externalLinks {
|
||||
external[l] = append(external[l], u)
|
||||
}
|
||||
}
|
||||
a.Pages = append(a.Pages, p)
|
||||
}
|
||||
|
||||
// Broken links: internal ones from the pages read, external ones checked.
|
||||
status := map[string]int{}
|
||||
for _, p := range a.Pages {
|
||||
status[p.URL] = p.Status
|
||||
}
|
||||
brokenOn := map[string][]string{} // page → its broken links
|
||||
for link, from := range internalFrom {
|
||||
if st, ok := status[link]; ok && st >= 400 {
|
||||
for _, pg := range from {
|
||||
brokenOn[pg] = append(brokenOn[pg], fmt.Sprintf("%s (%d)", link, st))
|
||||
}
|
||||
}
|
||||
}
|
||||
links := make([]string, 0, len(external))
|
||||
for l := range external {
|
||||
links = append(links, l)
|
||||
}
|
||||
slices.Sort(links)
|
||||
if len(links) > maxExternalLinks {
|
||||
links = links[:maxExternalLinks]
|
||||
}
|
||||
var mu sync.Mutex
|
||||
sem := make(chan struct{}, 4)
|
||||
var wg sync.WaitGroup
|
||||
for _, l := range links {
|
||||
wg.Add(1)
|
||||
sem <- struct{}{}
|
||||
go func(l string) {
|
||||
defer wg.Done()
|
||||
defer func() { <-sem }()
|
||||
check := func() (*fetched, error) {
|
||||
r, err := f.get(ctx, l, http.MethodHead, 0)
|
||||
if err == nil && (r.status == 405 || r.status == 403 || r.status == 501) {
|
||||
r, err = f.get(ctx, l, http.MethodGet, 1)
|
||||
}
|
||||
return r, err
|
||||
}
|
||||
r, err := check()
|
||||
if err != nil || r.status >= 500 {
|
||||
// One failure can be a blip: ask again before calling it broken.
|
||||
time.Sleep(f.Delay * 10)
|
||||
r, err = check()
|
||||
}
|
||||
if err != nil || r.status == 404 || r.status == 410 || r.status >= 500 {
|
||||
why := "unreachable"
|
||||
if err == nil {
|
||||
why = fmt.Sprint(r.status)
|
||||
}
|
||||
mu.Lock()
|
||||
for _, pg := range external[l] {
|
||||
brokenOn[pg] = append(brokenOn[pg], fmt.Sprintf("%s (%s)", l, why))
|
||||
}
|
||||
mu.Unlock()
|
||||
}
|
||||
}(l)
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
for i := range a.Pages {
|
||||
p := &a.Pages[i]
|
||||
t := traffic[p.URL]
|
||||
for _, is := range pageIssues(d, property, p, t, brokenOn[p.URL]) {
|
||||
is.Page, is.Traffic = p.URL, t
|
||||
a.Issues = append(a.Issues, is)
|
||||
}
|
||||
}
|
||||
rank := map[string]int{SevError: 0, SevWarning: 1, SevNotice: 2}
|
||||
slices.SortStableFunc(a.Issues, func(x, y Issue) int {
|
||||
if rank[x.Severity] != rank[y.Severity] {
|
||||
return rank[x.Severity] - rank[y.Severity]
|
||||
}
|
||||
if x.Traffic.Clicks != y.Traffic.Clicks {
|
||||
return y.Traffic.Clicks - x.Traffic.Clicks
|
||||
}
|
||||
if x.Traffic.Impressions != y.Traffic.Impressions {
|
||||
return y.Traffic.Impressions - x.Traffic.Impressions
|
||||
}
|
||||
return strings.Compare(x.Page+x.Code, y.Page+y.Code)
|
||||
})
|
||||
a.Checks = siteChecks(a, rob, llms, mapErr, len(inSitemap))
|
||||
return a, nil
|
||||
}
|
||||
|
||||
// normalize makes page addresses comparable: no fragment, no default
|
||||
// "index.html", the same trailing slash as written.
|
||||
func normalize(u string) string {
|
||||
p, err := url.Parse(strings.TrimSpace(u))
|
||||
if err != nil || (p.Scheme != "http" && p.Scheme != "https") || p.Host == "" {
|
||||
return ""
|
||||
}
|
||||
p.Fragment = ""
|
||||
p.Host = strings.ToLower(p.Host)
|
||||
if p.Path == "" {
|
||||
p.Path = "/"
|
||||
}
|
||||
p.Path = strings.TrimSuffix(p.Path, "index.html")
|
||||
return p.String()
|
||||
}
|
||||
|
||||
// readPage parses a page's HTML.
|
||||
func readPage(p *PageReport, pageURL string, body []byte) {
|
||||
base, _ := url.Parse(pageURL)
|
||||
doc, err := html.Parse(strings.NewReader(string(body)))
|
||||
if err != nil {
|
||||
p.Error = "unreadable HTML: " + err.Error()
|
||||
return
|
||||
}
|
||||
var text strings.Builder
|
||||
lastLevel := 0
|
||||
seenLinks := map[string]bool{}
|
||||
var walk func(n *html.Node, inBody, skip bool)
|
||||
walk = func(n *html.Node, inBody, skip bool) {
|
||||
if n.Type == html.ElementNode {
|
||||
switch n.Data {
|
||||
case "script", "style", "noscript", "template", "svg":
|
||||
if n.Data == "script" && attr(n, "type") == "application/ld+json" && n.FirstChild != nil {
|
||||
p.JSONLD = append(p.JSONLD, ldTypes(n.FirstChild.Data)...)
|
||||
}
|
||||
return
|
||||
case "html":
|
||||
p.Lang = attr(n, "lang")
|
||||
case "body":
|
||||
inBody = true
|
||||
case "title":
|
||||
if p.Title == "" && n.FirstChild != nil {
|
||||
p.Title = strings.Join(strings.Fields(n.FirstChild.Data), " ")
|
||||
}
|
||||
case "meta":
|
||||
name := strings.ToLower(attr(n, "name"))
|
||||
prop := strings.ToLower(attr(n, "property"))
|
||||
switch {
|
||||
case name == "description":
|
||||
p.Description = strings.Join(strings.Fields(attr(n, "content")), " ")
|
||||
case name == "robots" || name == "googlebot":
|
||||
if strings.Contains(strings.ToLower(attr(n, "content")), "noindex") {
|
||||
p.Noindex = true
|
||||
}
|
||||
case strings.HasPrefix(prop, "og:"):
|
||||
p.OG = true
|
||||
}
|
||||
case "link":
|
||||
if strings.EqualFold(attr(n, "rel"), "canonical") {
|
||||
if c, err := base.Parse(attr(n, "href")); err == nil {
|
||||
p.Canonical = normalize(c.String())
|
||||
}
|
||||
}
|
||||
case "h1", "h2", "h3", "h4", "h5", "h6":
|
||||
level := int(n.Data[1] - '0')
|
||||
if n.Data == "h1" {
|
||||
p.H1 = append(p.H1, strings.Join(strings.Fields(nodeText(n)), " "))
|
||||
}
|
||||
if lastLevel > 0 && level > lastLevel+1 {
|
||||
p.HeadingSkips = append(p.HeadingSkips, fmt.Sprintf("h%d → h%d", lastLevel, level))
|
||||
}
|
||||
lastLevel = level
|
||||
case "img":
|
||||
if _, has := attrOK(n, "alt"); !has {
|
||||
p.ImagesNoAlt++
|
||||
}
|
||||
case "a":
|
||||
href := attr(n, "href")
|
||||
if href == "" || strings.HasPrefix(href, "#") || strings.HasPrefix(href, "mailto:") || strings.HasPrefix(href, "tel:") || strings.HasPrefix(href, "javascript:") {
|
||||
break
|
||||
}
|
||||
l, err := base.Parse(href)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
nl := normalize(l.String())
|
||||
if nl == "" || seenLinks[nl] {
|
||||
break
|
||||
}
|
||||
seenLinks[nl] = true
|
||||
if strings.TrimPrefix(l.Hostname(), "www.") == strings.TrimPrefix(base.Hostname(), "www.") {
|
||||
if !strings.HasSuffix(strings.ToLower(l.Path), ".pdf") {
|
||||
p.internalLinks = append(p.internalLinks, nl)
|
||||
}
|
||||
} else {
|
||||
p.externalLinks = append(p.externalLinks, nl)
|
||||
}
|
||||
}
|
||||
}
|
||||
if n.Type == html.TextNode && inBody && !skip {
|
||||
text.WriteString(n.Data)
|
||||
text.WriteByte(' ')
|
||||
}
|
||||
for c := n.FirstChild; c != nil; c = c.NextSibling {
|
||||
walk(c, inBody, skip)
|
||||
}
|
||||
}
|
||||
walk(doc, false, false)
|
||||
p.TextChars = len([]rune(strings.Join(strings.Fields(text.String()), " ")))
|
||||
}
|
||||
|
||||
func attr(n *html.Node, key string) string {
|
||||
v, _ := attrOK(n, key)
|
||||
return v
|
||||
}
|
||||
|
||||
func attrOK(n *html.Node, key string) (string, bool) {
|
||||
for _, a := range n.Attr {
|
||||
if strings.EqualFold(a.Key, key) {
|
||||
return a.Val, true
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
func nodeText(n *html.Node) string {
|
||||
var b strings.Builder
|
||||
var walk func(*html.Node)
|
||||
walk = func(n *html.Node) {
|
||||
if n.Type == html.TextNode {
|
||||
b.WriteString(n.Data)
|
||||
}
|
||||
for c := n.FirstChild; c != nil; c = c.NextSibling {
|
||||
walk(c)
|
||||
}
|
||||
}
|
||||
walk(n)
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// ldTypes are the @type values in a JSON-LD block.
|
||||
func ldTypes(raw string) []string {
|
||||
var v any
|
||||
if err := json.Unmarshal([]byte(raw), &v); err != nil {
|
||||
return []string{"(invalid JSON-LD)"}
|
||||
}
|
||||
var out []string
|
||||
var walk func(any)
|
||||
walk = func(v any) {
|
||||
switch x := v.(type) {
|
||||
case map[string]any:
|
||||
switch t := x["@type"].(type) {
|
||||
case string:
|
||||
out = append(out, t)
|
||||
case []any:
|
||||
for _, s := range t {
|
||||
if s, ok := s.(string); ok {
|
||||
out = append(out, s)
|
||||
}
|
||||
}
|
||||
}
|
||||
if g, ok := x["@graph"]; ok {
|
||||
walk(g)
|
||||
}
|
||||
case []any:
|
||||
for _, e := range x {
|
||||
walk(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
walk(v)
|
||||
return out
|
||||
}
|
||||
|
||||
// pageIssues finds one page's problems.
|
||||
func pageIssues(d *db.DB, property string, p *PageReport, t Numbers, broken []string) []Issue {
|
||||
var out []Issue
|
||||
add := func(code, sev, title, detail string) {
|
||||
out = append(out, Issue{Code: code, Severity: sev, Title: title, Detail: detail})
|
||||
}
|
||||
switch {
|
||||
case p.Error != "":
|
||||
sev := SevWarning
|
||||
if t.Impressions > 0 {
|
||||
sev = SevError
|
||||
}
|
||||
add("unreachable", sev, "Couldn't be read", p.Error)
|
||||
return out
|
||||
case p.Status >= 400:
|
||||
add("status", SevError, fmt.Sprintf("Answers %d", p.Status), "Visitors and Google get an error page.")
|
||||
return out
|
||||
case p.Status != 200:
|
||||
return out
|
||||
}
|
||||
if p.Redirects > 0 {
|
||||
sev := SevNotice
|
||||
if p.InSitemap || p.Redirects > 1 {
|
||||
sev = SevWarning
|
||||
}
|
||||
detail := "Redirects to " + p.FinalURL
|
||||
if p.InSitemap {
|
||||
detail += "; the sitemap should list the final address."
|
||||
}
|
||||
add("redirect", sev, fmt.Sprintf("%d %s", p.Redirects, map[bool]string{true: "redirect", false: "redirects"}[p.Redirects == 1]), detail)
|
||||
}
|
||||
if p.Title == "" && p.Error == "" && p.TextChars == 0 && len(p.H1) == 0 {
|
||||
return out // not an HTML page we could read
|
||||
}
|
||||
if p.Noindex {
|
||||
sev := SevNotice
|
||||
if t.Impressions > 0 || p.InSitemap {
|
||||
sev = SevError
|
||||
}
|
||||
add("noindex", sev, "Tells search engines not to index it", "A robots meta tag says noindex.")
|
||||
}
|
||||
switch tp := TitlePixels(p.Title); {
|
||||
case p.Title == "":
|
||||
add("title-missing", SevError, "No title", "")
|
||||
case tp > TitleMaxPixels:
|
||||
add("title-long", SevWarning, "Title too long", fmt.Sprintf("“%s”: %d characters, about %d px; Google cuts it off around %d px.", p.Title, len([]rune(p.Title)), tp, TitleMaxPixels))
|
||||
case len([]rune(p.Title)) < 20:
|
||||
add("title-short", SevNotice, "Title very short", fmt.Sprintf("“%s”: %d characters. A specific title gets clicked more.", p.Title, len([]rune(p.Title))))
|
||||
}
|
||||
switch dp := DescriptionPixels(p.Description); {
|
||||
case p.Description == "":
|
||||
add("description-missing", SevWarning, "No meta description", "Google writes its own snippet from the page.")
|
||||
case dp > DescriptionMaxPixels:
|
||||
add("description-long", SevNotice, "Meta description too long", fmt.Sprintf("%d characters, about %d px; Google cuts it off around %d px.", len([]rune(p.Description)), dp, DescriptionMaxPixels))
|
||||
case len([]rune(p.Description)) < 50:
|
||||
add("description-short", SevNotice, "Meta description very short", fmt.Sprintf("“%s”", p.Description))
|
||||
}
|
||||
switch len(p.H1) {
|
||||
case 0:
|
||||
add("h1-missing", SevWarning, "No H1 heading", "")
|
||||
case 1:
|
||||
default:
|
||||
add("h1-many", SevNotice, fmt.Sprintf("%d H1 headings", len(p.H1)), strings.Join(p.H1, " · "))
|
||||
}
|
||||
if len(p.HeadingSkips) > 0 {
|
||||
add("heading-order", SevNotice, "Headings skip a level", strings.Join(p.HeadingSkips, ", "))
|
||||
}
|
||||
if p.Canonical == "" {
|
||||
add("canonical-missing", SevNotice, "No canonical address", "")
|
||||
} else if p.Canonical != p.URL && p.Canonical != normalize(p.FinalURL) {
|
||||
add("canonical-other", SevWarning, "Canonical points elsewhere", "Google is told the real page is "+p.Canonical+".")
|
||||
}
|
||||
if p.ImagesNoAlt > 0 {
|
||||
add("alt-missing", SevNotice, fmt.Sprintf("%d %s without alt text", p.ImagesNoAlt, map[bool]string{true: "image", false: "images"}[p.ImagesNoAlt == 1]), "")
|
||||
}
|
||||
if !p.OG {
|
||||
add("og-missing", SevNotice, "No Open Graph tags", "Shared on social networks, it shows without a proper title and picture.")
|
||||
}
|
||||
if len(p.JSONLD) == 0 {
|
||||
add("jsonld-missing", SevNotice, "No structured data (JSON-LD)", "Search engines and AI assistants understand pages with it better.")
|
||||
} else if slices.Contains(p.JSONLD, "(invalid JSON-LD)") {
|
||||
add("jsonld-invalid", SevWarning, "Structured data that isn't valid JSON", "")
|
||||
}
|
||||
if p.TextChars < 200 {
|
||||
add("thin", SevNotice, "Little text without JavaScript", fmt.Sprintf("%d characters of text in the HTML; crawlers that don't run JavaScript, like most AI ones, see almost nothing.", p.TextChars))
|
||||
}
|
||||
if !p.InSitemap && (p.FromGSC || t.Impressions > 0) {
|
||||
add("not-in-sitemap", SevNotice, "Not in the sitemap", "Google shows it, but the sitemap doesn't list it.")
|
||||
}
|
||||
if len(broken) > 0 {
|
||||
slices.Sort(broken)
|
||||
add("broken-links", SevWarning, fmt.Sprintf("%d broken %s", len(broken), map[bool]string{true: "link", false: "links"}[len(broken) == 1]), strings.Join(broken, ", "))
|
||||
}
|
||||
// The cheapest fix there is: the title doesn't say what people search.
|
||||
if property != "" && p.Title != "" && t.Impressions >= 50 {
|
||||
if from, to, ok := period(d, property, RanksDays); ok {
|
||||
pick := Pick{Page: p.URL, Numbers: t}
|
||||
if mainQuery(d, property, from, to, &pick) == nil && pick.MainQuery != "" && pick.MainShare >= 30 && covers(p.Title, pick.MainQuery) < 0.75 {
|
||||
add("title-query", SevWarning, "Its title doesn't say what people search",
|
||||
fmt.Sprintf("%.0f%% of its impressions come from “%s” (position %.1f), but the title is “%s”.", pick.MainShare, pick.MainQuery, pick.MainPos, p.Title))
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// siteChecks are the site-wide checks, AI visibility first.
|
||||
func siteChecks(a *Audit, rob *robots, llms *fetched, mapErr error, mapped int) []SiteCheck {
|
||||
var out []SiteCheck
|
||||
var blocked, allowed []string
|
||||
for _, c := range AICrawlers {
|
||||
if rob != nil && !rob.allowed(c.Agent, "/") {
|
||||
blocked = append(blocked, c.Agent+" ("+c.For+")")
|
||||
} else {
|
||||
allowed = append(allowed, c.Agent)
|
||||
}
|
||||
}
|
||||
if len(blocked) == 0 {
|
||||
out = append(out, SiteCheck{"ai", true, "AI crawlers may read the site", "robots.txt blocks none of: " + strings.Join(allowed, ", ") + "."})
|
||||
} else {
|
||||
out = append(out, SiteCheck{"ai", false, "robots.txt blocks some AI crawlers", "Blocked: " + strings.Join(blocked, "; ") + ". If you want to be cited by these assistants, allow them."})
|
||||
}
|
||||
if llms != nil && llms.status == 200 && len(strings.TrimSpace(string(llms.body))) > 0 {
|
||||
out = append(out, SiteCheck{"ai", true, "llms.txt is there", "A short guide to the site for AI assistants."})
|
||||
} else {
|
||||
out = append(out, SiteCheck{"ai", false, "No llms.txt", "A /llms.txt file (a Markdown summary with links to the key pages) helps AI assistants describe and cite you. It's a proposal, not a standard: cheap to add."})
|
||||
}
|
||||
var html, ld, thin int
|
||||
var org bool
|
||||
for _, p := range a.Pages {
|
||||
if p.Status != 200 || (p.Title == "" && p.TextChars == 0) {
|
||||
continue
|
||||
}
|
||||
html++
|
||||
if len(p.JSONLD) > 0 {
|
||||
ld++
|
||||
}
|
||||
if p.TextChars < 200 {
|
||||
thin++
|
||||
}
|
||||
for _, t := range p.JSONLD {
|
||||
if t == "Organization" || t == "Corporation" || t == "LocalBusiness" || t == "WebSite" {
|
||||
org = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if html > 0 {
|
||||
out = append(out, SiteCheck{"ai", ld*2 >= html, fmt.Sprintf("Structured data on %d of %d pages", ld, html),
|
||||
"JSON-LD (Article, Product, FAQ, Organization…) tells search engines and AI assistants what a page is about."})
|
||||
out = append(out, SiteCheck{"ai", org, map[bool]string{true: "The site says who you are", false: "No Organization or WebSite data"}[org],
|
||||
"Organization or WebSite structured data names the company, its logo and its profiles, so assistants get it right."})
|
||||
out = append(out, SiteCheck{"ai", thin == 0, fmt.Sprintf("%d of %d pages readable without JavaScript", html-thin, html),
|
||||
"Most AI crawlers don't run JavaScript: the text must be in the HTML."})
|
||||
}
|
||||
switch {
|
||||
case mapErr != nil:
|
||||
out = append(out, SiteCheck{"basics", false, "No readable sitemap", mapErr.Error()})
|
||||
default:
|
||||
out = append(out, SiteCheck{"basics", true, fmt.Sprintf("Sitemap lists %d pages", mapped), ""})
|
||||
}
|
||||
if rob == nil {
|
||||
out = append(out, SiteCheck{"basics", false, "No robots.txt", "Not required, but it's where crawlers look for the sitemap."})
|
||||
} else if len(rob.sitemaps) == 0 {
|
||||
out = append(out, SiteCheck{"basics", false, "robots.txt doesn't name the sitemap", "Add a line: Sitemap: https://…/sitemap.xml"})
|
||||
} else {
|
||||
out = append(out, SiteCheck{"basics", true, "robots.txt names the sitemap", strings.Join(rob.sitemaps, ", ")})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// --- Storing audits ---
|
||||
|
||||
// StartAudit records that an audit began.
|
||||
func StartAudit(d *db.DB, site string, now time.Time) (int64, error) {
|
||||
res, err := d.Exec(`INSERT INTO seo_audits (site, status, started_at) VALUES (?, 'running', ?)`, site, now.UTC().Format(time.RFC3339))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return res.LastInsertId()
|
||||
}
|
||||
|
||||
// FinishAudit stores an audit's result, or its error.
|
||||
func FinishAudit(d *db.DB, id int64, a *Audit, runErr error, now time.Time) error {
|
||||
status, data, msg := "done", "{}", ""
|
||||
if runErr != nil {
|
||||
status, msg = "failed", runErr.Error()
|
||||
} else {
|
||||
raw, err := json.Marshal(a)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
data = string(raw)
|
||||
}
|
||||
_, err := d.Exec(`UPDATE seo_audits SET status = ?, finished_at = ?, error = ?, data = ? WHERE id = ?`,
|
||||
status, now.UTC().Format(time.RFC3339), msg, data, id)
|
||||
return err
|
||||
}
|
||||
|
||||
// RecoverAudits marks audits a stopped app left running as failed.
|
||||
func RecoverAudits(d *db.DB) error {
|
||||
_, err := d.Exec(`UPDATE seo_audits SET status = 'failed', error = 'Supermarket stopped during the audit' WHERE status = 'running'`)
|
||||
return err
|
||||
}
|
||||
|
||||
// LatestAudit is a site's newest audit (running, done or failed), or nil.
|
||||
func LatestAudit(d *db.DB, site string) (*Audit, error) {
|
||||
var a Audit
|
||||
var started string
|
||||
var finished sql.NullString
|
||||
var data string
|
||||
err := d.QueryRow(`SELECT id, status, started_at, finished_at, error, data FROM seo_audits WHERE site = ? ORDER BY id DESC LIMIT 1`, site).
|
||||
Scan(&a.ID, &a.Status, &started, &finished, &a.Error, &data)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if a.Status == "done" {
|
||||
if err := json.Unmarshal([]byte(data), &a); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
a.StartedAt, _ = time.Parse(time.RFC3339, started)
|
||||
if finished.Valid {
|
||||
a.FinishedAt, _ = time.Parse(time.RFC3339, finished.String)
|
||||
}
|
||||
return &a, nil
|
||||
}
|
||||
|
||||
// LastDoneAudit is when a site was last audited successfully.
|
||||
func LastDoneAudit(d *db.DB, site string) time.Time {
|
||||
var s sql.NullString
|
||||
_ = d.QueryRow(`SELECT max(finished_at) FROM seo_audits WHERE site = ? AND status = 'done'`, site).Scan(&s)
|
||||
t, _ := time.Parse(time.RFC3339, s.String)
|
||||
return t
|
||||
}
|
||||
Reference in New Issue
Block a user