From 2302fb0436111a9e1ee29be3887b410ae767965a Mon Sep 17 00:00:00 2001 From: David Young Date: Sun, 22 Nov 2026 08:45:13 -0700 Subject: [PATCH] Phase 3 part 7: Bing, IndexNow and search engine setup MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SEO → Search engines: a pull request that adds the IndexNow key file, a robots.txt naming the sitemap, and turns the sitemap on when the Hugo config disables it (checked with a build); IndexNow submissions of pages that go live through Changes or Briefs once the key file is served; the sitemaps Search Console has; and, with an API key, Bing's traffic, searches and crawl issues. NewlyLive no longer queries while a result set holds the database's only connection. Co-Authored-By: Claude Opus 5.5 --- PLAN.md | 24 ++ README.md | 6 + TEST.md | 15 ++ internal/api/bing/client.go | 137 +++++++++++ internal/api/bing/client_test.go | 46 ++++ internal/api/gsc/client.go | 25 ++ internal/hugorepo/repo.go | 96 +++++++- internal/secrets/secrets.go | 1 + internal/seo/engines.go | 267 +++++++++++++++++++++ internal/seo/engines_test.go | 113 +++++++++ internal/web/engines.go | 196 +++++++++++++++ internal/web/engines_test.go | 60 +++++ internal/web/seo.go | 5 +- internal/web/server.go | 5 + internal/web/server_test.go | 2 +- internal/web/templates/layout.html | 1 + internal/web/templates/search-engines.html | 6 + internal/web/templates/seo-engines.html | 60 +++++ 18 files changed, 1061 insertions(+), 4 deletions(-) create mode 100644 internal/api/bing/client.go create mode 100644 internal/api/bing/client_test.go create mode 100644 internal/seo/engines.go create mode 100644 internal/seo/engines_test.go create mode 100644 internal/web/engines.go create mode 100644 internal/web/engines_test.go create mode 100644 internal/web/templates/seo-engines.html diff --git a/PLAN.md b/PLAN.md index 4f77211..3623e89 100644 --- a/PLAN.md +++ b/PLAN.md @@ -936,6 +936,30 @@ into `main`. - Bing Webmaster's API, for Bing's queries and crawl problems. - IndexNow on every merge. - The Search Console sitemap status. + - **Built 2026-11-22** (no schema change): + - `internal/api/bing` reads traffic, query stats and crawl issues, + with an API key and the profile's Bing site (or the website's + address). + - `gsc.Sitemaps` lists the sitemaps Search Console has. + - **IndexNow.** A 32-hex key is kept in settings. `KeyLive` checks the + site serves `.txt`. Once it does, `NewlyLive` submits the + pages that went live through Changes or Briefs in the last 14 days + and haven't been submitted, every 30 minutes, to + api.indexnow.org. The last 30 submissions are kept. + - **Site setup.** `Applier.SetupSite` opens one pull request, + `supermarket/search-engines`, that adds `static/.txt`, a + `static/robots.txt` naming the sitemap (unless the site has one), + and takes `sitemap` out of a one-line `disableKinds`. A build + checks that sitemap.xml, robots.txt and the key file come out. + - `hugorepo` gained `WriteFile`, `Exists`, `ConfigFile` and + `EnableSitemap`. Files written are tracked, so commits never pick + up Hugo's generated files. + - The page is SEO → Search engines; the Bing key is under Settings → + Search engines. Submitting a sitemap to Google needs a write + scope, so the page says to do it in Search Console. + - Fixed along the way: `NewlyLive` looked things up while a query + still held the database's only connection, and would hang. It now + reads all rows first. Before the first part: a Google Cloud project with the Search Console API turned on and an OAuth client (redirect diff --git a/README.md b/README.md index 0f95ca4..9d3055f 100644 --- a/README.md +++ b/README.md @@ -137,6 +137,12 @@ Each candidate is checked against your own pages, and buyer searches (price, bes Edit the brief and answer those questions ("not tested" is a fine answer), then *Write the page*: the AI drafts it around your answers and invents no test, price or customer. Every sentence that claims an experience is listed for you to confirm or remove. *Open a pull request* adds the page (or rewrites the existing one) in the site's repository, checks it with a Hugo build, and opens a pull request for you to read and merge. +**SEO: search engines (SEO → Search engines).** +- **Set the site up:** *Open the pull request* adds what search engines need and the site lacks: an IndexNow key file, a `robots.txt` that names the sitemap, and the sitemap itself if the Hugo config turns it off. A Hugo build checks all three. +- **IndexNow:** once the key file is live, every page that goes live through Changes or Briefs is submitted to IndexNow, so Bing and the other engines that use it hear about it at once. Google doesn't use IndexNow. +- **Google:** the sitemaps Search Console has, with their errors. +- **Bing:** with a Bing Webmaster API key (Settings → Search engines), Bing's weekly clicks and impressions, its top searches, and its crawl issues. + **The end of the funnel (Settings → Website & sales).** When writing posts on Content, choose *For a buying signal*: the posts speak to that situation, and their links carry the signal's campaign tag. Each signal's page lists its posts and gives your websites' addresses tagged with it, for landing pages, the shopping cart or links you share. With a Plausible Stats API key (Plausible on your Core by default), Supermarket reads yesterday's visitors on tagged links once a day and counts them as Visited for the signal, by channel; visits are counted per signal, never per person. With a restricted, read-only Stripe key, it reads new checkouts and paid invoices every hour: a checkout with nothing to pay (a trial or a free plan) counts as Signed up, and money paid as Paid, with the amount. A customer is tied to a signal by the `utm_campaign` your shopping cart saves in the Checkout Session's metadata, or else by their email (a prospect's, or one at a prospect company's domain). Your Core's Cal.com has no API, so bookings are read from Cal.com's booking emails in the outreach mailbox: give Cal.com's sending address under Settings → Email, and each new booking counts as Booked for the person who booked. **Prospects (Prospects → Review).** Companies and people who may fit your targets wait here for review; for now you add them by hand, and finding them for you comes next. Each keeps where and when it was found. Accepting a company queues an EspoCRM Account, accepting a person queues a Lead at their company, with the source, date and why they fit in the record's description. Before you decide, the page warns about records already in your CRM (as of the last sync). *Set aside* keeps a prospect out of the way; the **suppression list** (Prospects → Suppression list) holds emails and domains that must never be added, and is checked when a prospect is added and again before anything is queued. diff --git a/TEST.md b/TEST.md index 09464c2..1c531f6 100644 --- a/TEST.md +++ b/TEST.md @@ -384,6 +384,21 @@ Throughout, also notice: - [ ] **(real)** After you merge it and the site deploys, the brief shows as live. +### Search engines + +- [ ] SEO → Search engines shows the sitemaps Search Console has (compare + with Search Console → Indexing → Sitemaps). +- [ ] **(real)** *Open the pull request* (under "Set the site up") opens a + pull request adding the IndexNow key file and a robots.txt naming the + sitemap, and turning the sitemap on if the config turned it off; its + note says the build produced all three. +- [ ] After it's merged and deployed, the IndexNow key shows as served, + and *Submit the home page now* is accepted. +- [ ] A change or page that goes live afterwards appears in the IndexNow + list on its own (within half an hour). +- [ ] With a Bing Webmaster API key saved, Bing's weekly numbers, searches + and crawl issues appear. + ## 8. Search - [ ] Searching for an inventory entry, a fetched item, a post, a prospect diff --git a/internal/api/bing/client.go b/internal/api/bing/client.go new file mode 100644 index 0000000..ccd6cfc --- /dev/null +++ b/internal/api/bing/client.go @@ -0,0 +1,137 @@ +// Package bing reads Bing Webmaster Tools through its API +// (https://learn.microsoft.com/en-us/bingwebmaster/getting-access): +// a site's traffic, its searches and its crawl issues. It only reads. +package bing + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "regexp" + "strconv" + "strings" + "time" +) + +const apiBase = "https://ssl.bing.com/webmaster/api.svc/json" + +// ErrUnauthorized means the key was refused. +var ErrUnauthorized = errors.New("Bing refused the API key") + +// Client calls the API with one key. +type Client struct { + key, base string + http *http.Client +} + +func New(key string) *Client { + return &Client{key: key, base: apiBase, http: &http.Client{Timeout: time.Minute}} +} + +// WithBase points the client at another server (for tests). +func (c *Client) WithBase(u string) *Client { + c.base = strings.TrimRight(u, "/") + return c +} + +func (c *Client) get(ctx context.Context, method, site string, out any) error { + q := url.Values{"apikey": {c.key}, "siteUrl": {site}} + req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.base+"/"+method+"?"+q.Encode(), nil) + if err != nil { + return err + } + res, err := c.http.Do(req) + if err != nil { + return err + } + defer res.Body.Close() + raw, err := io.ReadAll(io.LimitReader(res.Body, 16<<20)) + if err != nil { + return err + } + if res.StatusCode == http.StatusUnauthorized || res.StatusCode == http.StatusForbidden { + return ErrUnauthorized + } + if res.StatusCode != http.StatusOK { + var e struct { + Message string `json:"Message"` + } + if json.Unmarshal(raw, &e) == nil && e.Message != "" { + return fmt.Errorf("Bing %s: %s", method, e.Message) + } + return fmt.Errorf("Bing %s: HTTP %d", method, res.StatusCode) + } + var env struct { + D json.RawMessage `json:"d"` + } + if err := json.Unmarshal(raw, &env); err != nil { + return fmt.Errorf("Bing %s: %w", method, err) + } + return json.Unmarshal(env.D, out) +} + +// Date is Bing's "/Date(1700000000000-0700)/". +type Date struct{ time.Time } + +var msDate = regexp.MustCompile(`/Date\((-?\d+)`) + +func (d *Date) UnmarshalJSON(b []byte) error { + var s string + if err := json.Unmarshal(b, &s); err != nil { + return nil + } + if m := msDate.FindStringSubmatch(s); m != nil { + ms, _ := strconv.ParseInt(m[1], 10, 64) + d.Time = time.UnixMilli(ms).UTC() + } + return nil +} + +// Day is one day's (or week's) traffic. +type Day struct { + Date Date `json:"Date"` + Clicks int `json:"Clicks"` + Impressions int `json:"Impressions"` +} + +// Traffic is the site's clicks and impressions over time. +func (c *Client) Traffic(ctx context.Context, site string) ([]Day, error) { + var out []Day + err := c.get(ctx, "GetRankAndTrafficStats", site, &out) + return out, err +} + +// Query is a search's numbers. +type Query struct { + Query string `json:"Query"` + Date Date `json:"Date"` + Clicks int `json:"Clicks"` + Impressions int `json:"Impressions"` + Position float64 `json:"AvgImpressionPosition"` +} + +// Queries are the site's searches, by week. +func (c *Client) Queries(ctx context.Context, site string) ([]Query, error) { + var out []Query + err := c.get(ctx, "GetQueryStats", site, &out) + return out, err +} + +// CrawlIssue is a page Bing had trouble with. +type CrawlIssue struct { + URL string `json:"Url"` + HTTPCode int `json:"HttpCode"` + Issues int `json:"Issues"` // flags + InLinks int `json:"InLinks"` +} + +// CrawlIssues lists the pages Bing had trouble crawling. +func (c *Client) CrawlIssues(ctx context.Context, site string) ([]CrawlIssue, error) { + var out []CrawlIssue + err := c.get(ctx, "GetCrawlIssues", site, &out) + return out, err +} diff --git a/internal/api/bing/client_test.go b/internal/api/bing/client_test.go new file mode 100644 index 0000000..3d64d0a --- /dev/null +++ b/internal/api/bing/client_test.go @@ -0,0 +1,46 @@ +package bing + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" +) + +func TestClient(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Query().Get("apikey") != "k" { + w.WriteHeader(http.StatusUnauthorized) + return + } + if r.URL.Query().Get("siteUrl") != "https://us.example/" { + t.Errorf("site: %s", r.URL) + } + switch r.URL.Path { + case "/GetRankAndTrafficStats": + w.Write([]byte(`{"d":[{"__type":"x","Clicks":12,"Date":"/Date(1763337600000-0800)/","Impressions":340}]}`)) + case "/GetQueryStats": + w.Write([]byte(`{"d":[{"Query":"nextcloud hosting","Clicks":2,"Impressions":90,"AvgImpressionPosition":8.5,"Date":"/Date(1763337600000)/"}]}`)) + case "/GetCrawlIssues": + w.Write([]byte(`{"d":[{"Url":"https://us.example/old","HttpCode":404,"Issues":1}]}`)) + } + })) + defer srv.Close() + ctx := context.Background() + c := New("k").WithBase(srv.URL) + days, err := c.Traffic(ctx, "https://us.example/") + if err != nil || len(days) != 1 || days[0].Clicks != 12 || days[0].Date.Year() != 2025 { + t.Errorf("traffic: %+v %v", days, err) + } + qs, err := c.Queries(ctx, "https://us.example/") + if err != nil || qs[0].Position != 8.5 { + t.Errorf("queries: %+v %v", qs, err) + } + is, err := c.CrawlIssues(ctx, "https://us.example/") + if err != nil || is[0].HTTPCode != 404 { + t.Errorf("issues: %+v %v", is, err) + } + if _, err := New("bad").WithBase(srv.URL).Traffic(ctx, "https://us.example/"); err != ErrUnauthorized { + t.Errorf("bad key: %v", err) + } +} diff --git a/internal/api/gsc/client.go b/internal/api/gsc/client.go index dc88d9c..7d7cd28 100644 --- a/internal/api/gsc/client.go +++ b/internal/api/gsc/client.go @@ -154,3 +154,28 @@ func (c *Client) Analytics(ctx context.Context, site string, q Query) ([]Row, er q.StartRow += maxRows } } + +// Sitemap is a sitemap Search Console knows about. +type Sitemap struct { + Path string `json:"path"` + LastSubmitted *time.Time `json:"lastSubmitted"` + LastDownloaded *time.Time `json:"lastDownloaded"` + IsPending bool `json:"isPending"` + Warnings string `json:"warnings"` + Errors string `json:"errors"` + Contents []struct { + Type string `json:"type"` + Submitted string `json:"submitted"` + } `json:"contents"` +} + +// Sitemaps lists the sitemaps submitted for a property. +func (c *Client) Sitemaps(ctx context.Context, site string) ([]Sitemap, error) { + var out struct { + Sitemap []Sitemap `json:"sitemap"` + } + if err := c.do(ctx, http.MethodGet, "/sites/"+url.PathEscape(site)+"/sitemaps", nil, &out); err != nil { + return nil, err + } + return out.Sitemap, nil +} diff --git a/internal/hugorepo/repo.go b/internal/hugorepo/repo.go index e283080..60534bc 100644 --- a/internal/hugorepo/repo.go +++ b/internal/hugorepo/repo.go @@ -29,6 +29,8 @@ type Repo struct { Token string // sent as a header, never stored in the copy Branch string // the branch that gets published Author string // "Name " for commits + + touched []string // files written outside content/, to commit } // git runs a git command in the working copy, with the token as an HTTP @@ -103,7 +105,7 @@ func (r *Repo) NewBranch(ctx context.Context, name string) error { // Diff is the working copy's uncommitted change, new files included. func (r *Repo) Diff(ctx context.Context) (string, error) { - if _, err := r.git(ctx, "add", "-A", "--intent-to-add", "content"); err != nil { + if _, err := r.git(ctx, append([]string{"add", "-A", "--intent-to-add", "content"}, r.touched...)...); err != nil { return "", err } return r.git(ctx, "diff") @@ -111,7 +113,7 @@ func (r *Repo) Diff(ctx context.Context) (string, error) { // CommitAndPush commits everything changed and pushes the current branch. func (r *Repo) CommitAndPush(ctx context.Context, branch, message string) error { - if _, err := r.git(ctx, "add", "-A", "content"); err != nil { + if _, err := r.git(ctx, append([]string{"add", "-A", "content"}, r.touched...)...); err != nil { return err } if _, err := r.git(ctx, "commit", "--quiet", "-am", message); err != nil { @@ -442,3 +444,93 @@ func (r *Repo) ReplaceBody(rel, body string) error { out := strings.Join(lines[:end+1], "\n") + "\n\n" + strings.TrimSpace(body) + "\n" return os.WriteFile(path, []byte(out), 0o644) } + +// --- Files outside content --- + +// inside resolves a path in the repository, refusing ones that leave it. +func (r *Repo) inside(rel string) (string, error) { + p := filepath.Clean(filepath.Join(r.Dir, rel)) + if !strings.HasPrefix(p, filepath.Clean(r.Dir)+string(filepath.Separator)) { + return "", fmt.Errorf("%s is outside the repository", rel) + } + return p, nil +} + +// Exists reports whether a file is in the working copy. +func (r *Repo) Exists(rel string) bool { + p, err := r.inside(rel) + if err != nil { + return false + } + _, err = os.Stat(p) + return err == nil +} + +// WriteFile writes a file anywhere in the repository and marks it to be +// committed. +func (r *Repo) WriteFile(rel, content string) error { + p, err := r.inside(rel) + if err != nil { + return err + } + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + return err + } + if err := os.WriteFile(p, []byte(content), 0o644); err != nil { + return err + } + r.touched = append(r.touched, filepath.ToSlash(rel)) + return nil +} + +// ConfigFile is the site's main Hugo configuration file, or "". +func (r *Repo) ConfigFile() string { + for _, name := range []string{"hugo.toml", "hugo.yaml", "hugo.yml", "config.toml", "config.yaml", "config.yml", + "config/_default/hugo.toml", "config/_default/hugo.yaml", "config/_default/config.toml", "config/_default/config.yaml"} { + if r.Exists(name) { + return name + } + } + return "" +} + +var disableKinds = regexp.MustCompile(`(?m)^(\s*disableKinds\s*[:=]\s*\[)([^\]]*)(\])`) + +// EnableSitemap takes "sitemap" out of the config's disableKinds, when it's +// written on one line. It reports whether it changed anything. +func (r *Repo) EnableSitemap() (bool, error) { + cfg := r.ConfigFile() + if cfg == "" { + return false, nil + } + p, _ := r.inside(cfg) + raw, err := os.ReadFile(p) + if err != nil { + return false, err + } + changed := false + out := disableKinds.ReplaceAllStringFunc(string(raw), func(m string) string { + parts := disableKinds.FindStringSubmatch(m) + var keep []string + for _, k := range strings.Split(parts[2], ",") { + if t := strings.Trim(strings.TrimSpace(k), `"'`); strings.EqualFold(t, "sitemap") { + changed = true + continue + } + if strings.TrimSpace(k) != "" { + keep = append(keep, strings.TrimSpace(k)) + } + } + return parts[1] + strings.Join(keep, ", ") + parts[3] + }) + if !changed { + return false, nil + } + return true, r.WriteFile(cfg, out) +} + +// BuiltFile reads a file from a build. +func BuiltFile(outDir, rel string) (string, error) { + raw, err := os.ReadFile(filepath.Join(outDir, rel)) + return string(raw), err +} diff --git a/internal/secrets/secrets.go b/internal/secrets/secrets.go index 6963404..b124745 100644 --- a/internal/secrets/secrets.go +++ b/internal/secrets/secrets.go @@ -44,6 +44,7 @@ const ( GoogleRefreshToken = "google.refresh_token" // Search Console, read-only PageSpeedAPIKey = "pagespeed.api_key" GiteaToken = "gitea.token" // opens pull requests on the sites' repositories + BingAPIKey = "bing.api_key" PlausibleAPIKey = "plausible.api_key" StripeAPIKey = "stripe.api_key" // restricted, read-only diff --git a/internal/seo/engines.go b/internal/seo/engines.go new file mode 100644 index 0000000..dd48ce4 --- /dev/null +++ b/internal/seo/engines.go @@ -0,0 +1,267 @@ +package seo + +import ( + "bytes" + "context" + "crypto/rand" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "os" + "strings" + "time" + + "supermarket/internal/db" + "supermarket/internal/hugorepo" +) + +// --- IndexNow --- + +// IndexNowURL is where pings go; it shares them with Bing, Yandex, Seznam, +// Naver and the other engines that take part (Google doesn't). Tests +// replace it. +var IndexNowURL = "https://api.indexnow.org/indexnow" + +const indexNowKeyKey = "seo:indexnow-key" + +// IndexNowKey is the site's IndexNow key, made the first time. It isn't a +// secret: it's published in a file on the site. +func IndexNowKey(d *db.DB) (string, error) { + var k string + if _, err := d.GetJSON(indexNowKeyKey, &k); err != nil { + return "", err + } + if k != "" { + return k, nil + } + b := make([]byte, 16) + if _, err := rand.Read(b); err != nil { + return "", err + } + k = hex.EncodeToString(b) + return k, d.PutJSON(indexNowKeyKey, k) +} + +// KeyFileURL is where the key file must be on a site. +func KeyFileURL(site, key string) string { + return strings.TrimRight(site, "/") + "/" + key + ".txt" +} + +// KeyLive reports whether the site serves its IndexNow key file. +func KeyLive(ctx context.Context, f *Fetcher, site, key string) bool { + r, err := f.get(ctx, KeyFileURL(site, key), http.MethodGet, 4096) + return err == nil && r.status == 200 && strings.TrimSpace(string(r.body)) == key +} + +// Ping is one IndexNow submission. +type Ping struct { + At time.Time `json:"at"` + URLs []string `json:"urls"` + Status int `json:"status"` + Error string `json:"error,omitempty"` +} + +func pingsKey(site string) string { return "seo:indexnow-pings:" + site } + +// Pings are a site's recent submissions, newest first. +func Pings(d *db.DB, site string) []Ping { + var out []Ping + _, _ = d.GetJSON(pingsKey(site), &out) + return out +} + +// pinged reports whether a page was submitted already. +func pinged(d *db.DB, site, page string) bool { + for _, p := range Pings(d, site) { + for _, u := range p.URLs { + if u == page && p.Error == "" { + return true + } + } + } + return false +} + +// SubmitIndexNow tells the IndexNow engines that pages changed, and keeps +// the submission. +func SubmitIndexNow(ctx context.Context, d *db.DB, site, key string, pages []string, now time.Time) (*Ping, error) { + u, err := url.Parse(site) + if err != nil || u.Host == "" { + return nil, fmt.Errorf("%q isn't a website address", site) + } + body, _ := json.Marshal(map[string]any{"host": u.Host, "key": key, "keyLocation": KeyFileURL(site, key), "urlList": pages}) + p := &Ping{At: now, URLs: pages} + req, err := http.NewRequestWithContext(ctx, http.MethodPost, IndexNowURL, bytes.NewReader(body)) + if err != nil { + return nil, err + } + req.Header.Set("Content-Type", "application/json; charset=utf-8") + res, err := http.DefaultClient.Do(req) + if err != nil { + p.Error = err.Error() + } else { + p.Status = res.StatusCode + msg, _ := io.ReadAll(io.LimitReader(res.Body, 2048)) + res.Body.Close() + // 200: accepted; 202: accepted, the key is being checked. + if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusAccepted { + p.Error = fmt.Sprintf("IndexNow said HTTP %d %s", res.StatusCode, strings.TrimSpace(string(msg))) + } + } + list := append([]Ping{*p}, Pings(d, site)...) + if len(list) > 30 { + list = list[:30] + } + if perr := d.PutJSON(pingsKey(site), list); perr != nil { + return p, perr + } + if p.Error != "" { + return p, errors.New(p.Error) + } + return p, nil +} + +// NewlyLive are the site's pages that went live in the last 14 days (from +// changes and briefs) and haven't been submitted to IndexNow yet. +func NewlyLive(d *db.DB, site string, now time.Time) ([]string, error) { + since := now.AddDate(0, 0, -14).UTC().Format(time.RFC3339) + rows, err := d.Query(`SELECT page FROM seo_changes WHERE site = ? AND status = 'live' AND live_at >= ? + UNION SELECT page FROM seo_briefs WHERE site = ? AND status = 'live' AND live_at >= ? AND page != ''`, site, since, site, since) + if err != nil { + return nil, err + } + // Read every row before looking anything else up: the database has one + // connection, which the open query holds. + var live []string + for rows.Next() { + var p string + if err := rows.Scan(&p); err != nil { + rows.Close() + return nil, err + } + live = append(live, p) + } + rows.Close() + if err := rows.Err(); err != nil { + return nil, err + } + var out []string + for _, p := range live { + if !pinged(d, site, p) { + out = append(out, p) + } + } + return out, nil +} + +// --- Setting the site up for search engines --- + +// Setup is the "set the site up" pull request's state. +type Setup struct { + At time.Time `json:"at"` + PRNumber int64 `json:"pr_number"` + PRURL string `json:"pr_url"` + Done []string `json:"done"` + Note string `json:"note"` + Error string `json:"error,omitempty"` +} + +func setupKey(site string) string { return "seo:setup:" + site } + +// LastSetup is a site's last setup pull request, or nil. +func LastSetup(d *db.DB, site string) *Setup { + var s Setup + if ok, _ := d.GetJSON(setupKey(site), &s); !ok { + return nil + } + return &s +} + +// SetupSite opens one pull request that gets the site ready for search +// engines: the IndexNow key file, a robots.txt naming the sitemap (unless +// the site has its own), and the sitemap turned back on if the Hugo config +// turns it off. A build checks the sitemap, robots.txt and key file come +// out. +func (ap *Applier) SetupSite(ctx context.Context, d *db.DB, site, key string, now time.Time) (*Setup, error) { + st := &Setup{At: now} + err := ap.setupSite(ctx, site, key, st) + if err != nil { + st.Error = err.Error() + } + if perr := d.PutJSON(setupKey(site), st); perr != nil && err == nil { + err = perr + } + return st, err +} + +func (ap *Applier) setupSite(ctx context.Context, site, key string, st *Setup) error { + wc, full, branch, err := ap.workingCopy(ctx) + if err != nil { + return err + } + canBuild, note := buildCheck(ctx, wc) + work := "supermarket/search-engines" + if err := wc.NewBranch(ctx, work); err != nil { + return err + } + keyFile := "static/" + key + ".txt" + if !wc.Exists(keyFile) { + if err := wc.WriteFile(keyFile, key+"\n"); err != nil { + return err + } + st.Done = append(st.Done, "Adds the IndexNow key file ("+key+".txt), so Supermarket can tell Bing and other engines when a page changes.") + } + if !wc.Exists("static/robots.txt") && !wc.Exists("layouts/robots.txt") { + robots := "User-agent: *\nAllow: /\n\nSitemap: " + strings.TrimRight(site, "/") + "/sitemap.xml\n" + if err := wc.WriteFile("static/robots.txt", robots); err != nil { + return err + } + st.Done = append(st.Done, "Adds a robots.txt that lets every crawler in and names the sitemap.") + } + if changed, err := wc.EnableSitemap(); err != nil { + return err + } else if changed { + st.Done = append(st.Done, "Turns the sitemap back on: the Hugo config listed it under disableKinds.") + } + if len(st.Done) == 0 { + return errors.New("the site already has the key file and its own robots.txt, and its config doesn't turn the sitemap off") + } + if canBuild { + out, err := wc.Build(ctx) + if err != nil { + return fmt.Errorf("after the change, %w", err) + } + var missing []string + for _, f := range []string{"sitemap.xml", "robots.txt", key + ".txt"} { + if _, err := hugorepo.BuiltFile(out, f); err != nil { + missing = append(missing, f) + } + } + os.RemoveAll(out) + if len(missing) > 0 { + note = "The build doesn't produce " + strings.Join(missing, ", ") + ": the theme or config may turn it off in a way Supermarket can't change; check before merging." + } else { + note = "Checked with a build: the site now produces sitemap.xml, robots.txt and the key file." + } + } + subject := "SEO: set the site up for search engines" + if err := wc.CommitAndPush(ctx, work, subject); err != nil { + return err + } + var body strings.Builder + body.WriteString("Proposed by Supermarket, from the audit.\n\n") + for _, d := range st.Done { + body.WriteString("- " + d + "\n") + } + body.WriteString("\n" + note + "\n\nAfter merging, submit " + strings.TrimRight(site, "/") + "/sitemap.xml in Google Search Console and Bing Webmaster Tools.") + pr, err := ap.Gitea.OpenPull(ctx, full, work, branch, subject, body.String()) + if err != nil { + return err + } + st.PRNumber, st.PRURL, st.Note = pr.Number, pr.HTMLURL, note + return nil +} diff --git a/internal/seo/engines_test.go b/internal/seo/engines_test.go new file mode 100644 index 0000000..66a1531 --- /dev/null +++ b/internal/seo/engines_test.go @@ -0,0 +1,113 @@ +package seo + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" + + "supermarket/internal/api/gitea" + "supermarket/internal/hugorepo" + "supermarket/internal/hugorepo/hugotest" +) + +func TestIndexNow(t *testing.T) { + d := openDB(t) + key, err := IndexNowKey(d) + if err != nil || len(key) != 32 { + t.Fatalf("key: %q %v", key, err) + } + if again, _ := IndexNowKey(d); again != key { + t.Error("the key changed") + } + var got map[string]any + in := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + json.NewDecoder(r.Body).Decode(&got) + w.WriteHeader(http.StatusAccepted) + })) + defer in.Close() + IndexNowURL = in.URL + defer func() { IndexNowURL = "https://api.indexnow.org/indexnow" }() + site := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/"+key+".txt" { + fmt.Fprintln(w, key) + return + } + http.NotFound(w, r) + })) + defer site.Close() + f := NewFetcher("test") + if !KeyLive(context.Background(), f, site.URL, key) || KeyLive(context.Background(), f, site.URL, "other") { + t.Error("key check") + } + // A change went live: it's waiting to be submitted, then it isn't. + now := time.Now() + c := &Change{Site: site.URL + "/", Page: site.URL + "/pricing/", NewTitle: "x", CreatedAt: now} + insertChange(d, c) + d.Exec(`UPDATE seo_changes SET status = 'live', live_at = ? WHERE id = ?`, now.UTC().Format(time.RFC3339), c.ID) + pages, _ := NewlyLive(d, site.URL+"/", now) + if len(pages) != 1 { + t.Fatalf("newly live: %v", pages) + } + p, err := SubmitIndexNow(context.Background(), d, site.URL+"/", key, pages, now) + if err != nil || p.Status != 202 { + t.Fatalf("submit: %+v %v", p, err) + } + if got["key"] != key || got["keyLocation"] != site.URL+"/"+key+".txt" || !strings.HasPrefix(site.URL, "http://"+got["host"].(string)) { + t.Errorf("request: %+v", got) + } + if pages, _ := NewlyLive(d, site.URL+"/", now); len(pages) != 0 { + t.Errorf("submitted twice: %v", pages) + } + if len(Pings(d, site.URL+"/")) != 1 { + t.Error("the ping isn't kept") + } +} + +func TestSetupSite(t *testing.T) { + if hugorepo.HugoVersion(context.Background()) == "" { + t.Skip("no hugo") + } + d := openDB(t) + clone := hugotest.Site(t) + var body map[string]string + g := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.URL.Path == "/api/v1/repos/o/site": + json.NewEncoder(w).Encode(map[string]any{"full_name": "o/site", "default_branch": "main", "clone_url": clone, "permissions": map[string]any{"push": true}}) + case r.URL.Path == "/api/v1/repos/o/site/pulls": + json.NewDecoder(r.Body).Decode(&body) + json.NewEncoder(w).Encode(map[string]any{"number": 3, "html_url": "https://gitea.example/pr/3"}) + } + })) + defer g.Close() + ap := &Applier{Gitea: gitea.New(g.URL, "tok"), Repo: "o/site", ReposDir: filepath.Join(t.TempDir(), "sites"), Author: "P "} + st, err := ap.SetupSite(context.Background(), d, "https://site.example", "abc123", time.Now()) + if err != nil { + t.Fatal(err) + } + if st.PRNumber != 3 || len(st.Done) != 3 || !strings.HasPrefix(st.Note, "Checked with a build") { + t.Fatalf("setup: %+v", st) + } + if !strings.Contains(body["body"], "Turns the sitemap back on") || !strings.Contains(body["body"], "https://site.example/sitemap.xml") { + t.Errorf("pull request: %s", body["body"]) + } + repo := strings.TrimPrefix(clone, "file://") + for file, want := range map[string]string{ + "static/abc123.txt": "abc123", "static/robots.txt": "Sitemap: https://site.example/sitemap.xml", "hugo.toml": "disableKinds = ['taxonomy', 'term', 'RSS']", + } { + out, err := exec.Command("git", "-C", repo, "show", "supermarket/search-engines:"+file).CombinedOutput() + if err != nil || !strings.Contains(string(out), want) { + t.Errorf("%s: %s %v", file, out, err) + } + } + if LastSetup(d, "https://site.example") == nil { + t.Error("the setup isn't kept") + } +} diff --git a/internal/web/engines.go b/internal/web/engines.go new file mode 100644 index 0000000..5e948ec --- /dev/null +++ b/internal/web/engines.go @@ -0,0 +1,196 @@ +package web + +import ( + "context" + "net/http" + "slices" + "strconv" + "strings" + "time" + + "supermarket/internal/api/bing" + "supermarket/internal/profile" + "supermarket/internal/secrets" + "supermarket/internal/seo" +) + +var bingKey = secretField{"bing", secrets.BingAPIKey, "Bing Webmaster API key (optional)", + "In Bing Webmaster Tools: Settings (the gear) → API access → API key. Your site must be verified there.", "https://www.bing.com/webmasters"} + +// bingBase is the Bing API's address; tests point it elsewhere. +var bingBase = "" + +func (s *Server) bing() *bing.Client { + key := s.Secrets.Get(secrets.BingAPIKey) + if key == "" { + return nil + } + c := bing.New(key) + if bingBase != "" { + c.WithBase(bingBase) + } + return c +} + +// bingSite is how Bing names a website: the profile's Bing site, or its +// address with a trailing slash. +func (s *Server) bingSite(site seoSite) string { + if p, _ := profile.Load(s.DB); p != nil && site.Index < len(p.Websites) && p.Websites[site.Index].BingSite != "" { + return p.Websites[site.Index].BingSite + } + return strings.TrimRight(site.URL, "/") + "/" +} + +type bingQuery struct { + Query string + Clicks, Impressions int + Position float64 +} + +func (s *Server) seoEnginesPage(w http.ResponseWriter, r *http.Request) { + s.renderEngines(w, r, "") +} + +func (s *Server) renderEngines(w http.ResponseWriter, r *http.Request, errMsg string) { + sites, cur := s.auditSites(r) + data := map[string]any{"Sites": sites, "Current": cur} + if cur != nil { + ctx, cancel := context.WithTimeout(r.Context(), 40*time.Second) + defer cancel() + if c := s.gsc(); c != nil && cur.Property != "" { + maps, err := c.Sitemaps(ctx, cur.Property) + data["Sitemaps"], data["SitemapsErr"] = maps, errText(err) + } + data["GoogleConnected"] = s.gsc() != nil && cur.Property != "" + if b := s.bing(); b != nil { + site := s.bingSite(*cur) + data["BingSite"] = site + if days, err := b.Traffic(ctx, site); err != nil { + data["BingErr"] = err.Error() + } else { + slices.SortFunc(days, func(a, b bing.Day) int { return b.Date.Compare(a.Date.Time) }) + if len(days) > 8 { + days = days[:8] + } + data["BingDays"] = days + if qs, err := b.Queries(ctx, site); err == nil { + data["BingQueries"] = topBingQueries(qs, 28) + } + if issues, err := b.CrawlIssues(ctx, site); err == nil { + data["BingIssues"] = issues + } + } + } + key, err := seo.IndexNowKey(s.DB) + if err != nil { + s.serverError(w, err) + return + } + f := seo.NewFetcher("Supermarket/" + s.Version + " (SEO)") + data["Key"], data["KeyURL"], data["KeyLive"] = key, seo.KeyFileURL(cur.URL, key), seo.KeyLive(ctx, f, cur.URL, key) + data["Pings"] = seo.Pings(s.DB, cur.URL) + data["Setup"] = seo.LastSetup(s.DB, cur.URL) + data["Gitea"] = s.gitea() != nil + } + s.render(w, r, "seo-engines", page{Title: "Search engines", Nav: "seo/engines", Error: errMsg, Data: data}) +} + +func errText(err error) string { + if err == nil { + return "" + } + return err.Error() +} + +// topBingQueries sums the last weeks' rows per search, most impressions +// first. +func topBingQueries(qs []bing.Query, days int) []bingQuery { + since := time.Now().AddDate(0, 0, -days) + sum := map[string]*bingQuery{} + var pos = map[string]float64{} + for _, q := range qs { + if q.Date.Before(since) { + continue + } + b := sum[q.Query] + if b == nil { + b = &bingQuery{Query: q.Query} + sum[q.Query] = b + } + b.Clicks += q.Clicks + b.Impressions += q.Impressions + pos[q.Query] += q.Position * float64(q.Impressions) + } + var out []bingQuery + for k, b := range sum { + if b.Impressions > 0 { + b.Position = pos[k] / float64(b.Impressions) + } + out = append(out, *b) + } + slices.SortFunc(out, func(a, b bingQuery) int { return b.Impressions - a.Impressions }) + if len(out) > 15 { + out = out[:15] + } + return out +} + +// seoEnginesSetup opens the "set the site up for search engines" pull +// request. +func (s *Server) seoEnginesSetup(w http.ResponseWriter, r *http.Request) { + _, cur := s.auditSites(r) + if cur == nil { + http.NotFound(w, r) + return + } + key, err := seo.IndexNowKey(s.DB) + if err == nil { + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Minute) + defer cancel() + _, err = s.applier(*cur).SetupSite(ctx, s.DB, cur.URL, key, time.Now()) + } + if err != nil { + s.renderEngines(w, r, "Couldn't open the pull request: "+err.Error()) + return + } + redirect(w, r, "/seo/engines?site="+strconv.Itoa(cur.Index), "setup-opened") +} + +// seoEnginesPing submits the home page to IndexNow, to check it works. +func (s *Server) seoEnginesPing(w http.ResponseWriter, r *http.Request) { + _, cur := s.auditSites(r) + if cur == nil { + http.NotFound(w, r) + return + } + key, err := seo.IndexNowKey(s.DB) + if err == nil { + ctx, cancel := context.WithTimeout(r.Context(), time.Minute) + defer cancel() + _, err = seo.SubmitIndexNow(ctx, s.DB, cur.URL, key, []string{strings.TrimRight(cur.URL, "/") + "/"}, time.Now()) + } + if err != nil { + s.renderEngines(w, r, "IndexNow: "+err.Error()) + return + } + redirect(w, r, "/seo/engines?site="+strconv.Itoa(cur.Index), "pinged") +} + +// pingNewlyLive submits pages that went live to IndexNow, once the site +// serves its key file. +func (s *Server) pingNewlyLive(ctx context.Context) { + key, err := seo.IndexNowKey(s.DB) + if err != nil { + return + } + f := seo.NewFetcher("Supermarket/" + s.Version + " (SEO)") + for _, site := range s.seoSites() { + pages, err := seo.NewlyLive(s.DB, site.URL, time.Now()) + if err != nil || len(pages) == 0 || !seo.KeyLive(ctx, f, site.URL, key) { + continue + } + if _, err := seo.SubmitIndexNow(ctx, s.DB, site.URL, key, pages, time.Now()); err != nil { + s.Log.Warn("seo: IndexNow", "site", site.URL, "err", err) + } + } +} diff --git a/internal/web/engines_test.go b/internal/web/engines_test.go new file mode 100644 index 0000000..31f5595 --- /dev/null +++ b/internal/web/engines_test.go @@ -0,0 +1,60 @@ +package web + +import ( + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" + + "supermarket/internal/profile" + "supermarket/internal/secrets" + "supermarket/internal/seo" +) + +func TestEnginesPage(t *testing.T) { + s, h := newTestServer(t, nil) + key, _ := seo.IndexNowKey(s.DB) + site := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/"+key+".txt" { + fmt.Fprint(w, key) + return + } + http.NotFound(w, r) + })) + defer site.Close() + b := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/GetRankAndTrafficStats": + w.Write([]byte(`{"d":[{"Clicks":12,"Impressions":340,"Date":"/Date(1763337600000)/"}]}`)) + case "/GetQueryStats": + w.Write([]byte(`{"d":[]}`)) + case "/GetCrawlIssues": + w.Write([]byte(`{"d":[{"Url":"https://us.example/old","HttpCode":404}]}`)) + } + })) + defer b.Close() + bingBase = b.URL + defer func() { bingBase = "" }() + var pinged string + in := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { pinged = r.URL.Path; w.WriteHeader(200) })) + defer in.Close() + seo.IndexNowURL = in.URL + defer func() { seo.IndexNowURL = "https://api.indexnow.org/indexnow" }() + + profile.Save(s.DB, &profile.Profile{Name: "Us", Websites: []profile.Website{{URL: site.URL}}}) + postForm(h, "/settings/search", url.Values{secrets.BingAPIKey: {"k"}}) + body := do(h, http.MethodGet, "/seo/engines", nil, nil).Body.String() + for _, want := range []string{key, "the site serves it", "340", "https://us.example/old (404)", "Connect Search Console", "Open the pull request"} { + if !strings.Contains(body, want) { + t.Errorf("page lacks %q", want) + } + } + if rec := postForm(h, "/seo/engines/ping?site=0", nil); rec.Code != http.StatusSeeOther || pinged == "" { + t.Errorf("ping: %d %q", rec.Code, pinged) + } + if body := do(h, http.MethodGet, "/seo/engines", nil, nil).Body.String(); !strings.Contains(body, "accepted (200)") { + t.Error("the ping isn't listed") + } +} diff --git a/internal/web/seo.go b/internal/web/seo.go index f93eeb1..cf258cb 100644 --- a/internal/web/seo.go +++ b/internal/web/seo.go @@ -115,6 +115,8 @@ func (s *Server) renderSearchSettings(w http.ResponseWriter, r *http.Request, er "Fields": googleFields, "Speed": pageSpeedKey, "GiteaKey": giteaToken, + "BingKey": bingKey, + "BingSet": s.Secrets.Has(secrets.BingAPIKey), "GiteaSet": s.Secrets.Has(secrets.GiteaToken), "GiteaURL": s.giteaURL(), "SpeedSet": s.Secrets.Has(secrets.PageSpeedAPIKey), @@ -142,7 +144,7 @@ func (s *Server) searchSettingsSave(w http.ResponseWriter, r *http.Request) { http.Error(w, err.Error(), http.StatusBadRequest) return } - if err := s.saveSecrets(r, append(googleFields, pageSpeedKey, giteaToken)); err != nil { + if err := s.saveSecrets(r, append(googleFields, pageSpeedKey, giteaToken, bingKey)); err != nil { s.serverError(w, err) return } @@ -268,6 +270,7 @@ func (s *Server) RunSEO(ctx context.Context) { } s.refreshChanges(ctx) s.refreshBriefs(ctx) + s.pingNewlyLive(ctx) select { case <-ctx.Done(): return diff --git a/internal/web/server.go b/internal/web/server.go index c18881e..06cb771 100644 --- a/internal/web/server.go +++ b/internal/web/server.go @@ -161,6 +161,9 @@ func (s *Server) Handler() (http.Handler, error) { mux.HandleFunc("POST /settings/email/send-test", s.emailSendTest) mux.HandleFunc("GET /seo", s.seoPage) mux.HandleFunc("GET /seo/check", s.seoCheckPage) + mux.HandleFunc("GET /seo/engines", s.seoEnginesPage) + mux.HandleFunc("POST /seo/engines/setup", s.seoEnginesSetup) + mux.HandleFunc("POST /seo/engines/ping", s.seoEnginesPing) mux.HandleFunc("GET /seo/briefs", s.seoBriefsPage) mux.HandleFunc("POST /seo/briefs", s.seoBriefNew) mux.HandleFunc("GET /seo/briefs/{id}", s.seoBriefPage) @@ -425,6 +428,8 @@ var flashes = map[string]string{ "google-connected": "Search Console is connected. Choose each website's property below, then sync.", "synced": "Synced from Search Console.", "report-written": "This week's report is written.", + "setup-opened": "Pull request opened: read it on Gitea, then merge it.", + "pinged": "Sent to IndexNow.", "brief-written": "Brief written. Read it, answer its questions, then write the page.", "page-written": "Page drafted. Read it, and confirm or remove every sentence that claims an experience.", "keywords-found": "Looked for keywords: the candidates are below.", diff --git a/internal/web/server_test.go b/internal/web/server_test.go index 71d84fc..5a0babc 100644 --- a/internal/web/server_test.go +++ b/internal/web/server_test.go @@ -100,7 +100,7 @@ func TestEveryPageRenders(t *testing.T) { "/settings/ai", "/settings/accounts", "/settings/core", "/static/app.css", "/favicon.ico", "/static/favicon.png", "/static/logo.png", "/static/apple-touch-icon.png", "/search", "/crm", "/search?q=rival", "/search?q=nothing+here", "/static/htmx.min.js", "/healthz", "/content", "/content/1", "/content/1?dismissed=1", "/posts", "/posts?msg=drafted", "/content/scheduled", "/content/published", - "/prospects", "/prospects?status=accepted", "/prospects?status=rejected", "/prospects/new", "/prospects/suppressed", "/outreach", "/outreach?tab=queued", "/outreach?tab=sent", "/outreach?tab=replied", "/outreach?tab=failed", "/settings/email", "/settings/tracking", "/settings/search", "/seo", "/seo/check", "/seo/report", "/seo/audit", "/seo/changes", "/seo/keywords", "/seo/briefs", + "/prospects", "/prospects?status=accepted", "/prospects?status=rejected", "/prospects/new", "/prospects/suppressed", "/outreach", "/outreach?tab=queued", "/outreach?tab=sent", "/outreach?tab=replied", "/outreach?tab=failed", "/settings/email", "/settings/tracking", "/settings/search", "/seo", "/seo/check", "/seo/report", "/seo/audit", "/seo/changes", "/seo/keywords", "/seo/briefs", "/seo/engines", "/signals", "/signals?period=30d&channel=email", "/signals/new", "/settings/sources"} { rec := do(h, http.MethodGet, path, nil, nil) if rec.Code != http.StatusOK { diff --git a/internal/web/templates/layout.html b/internal/web/templates/layout.html index cd2ad8a..80f641c 100644 --- a/internal/web/templates/layout.html +++ b/internal/web/templates/layout.html @@ -47,6 +47,7 @@ Next keywords Briefs and pages Audit + Search engines {{end}} {{if eq .ID "prospects"}} diff --git a/internal/web/templates/search-engines.html b/internal/web/templates/search-engines.html index 9583e72..80da90b 100644 --- a/internal/web/templates/search-engines.html +++ b/internal/web/templates/search-engines.html @@ -34,6 +34,12 @@ {{end}} +
+

Bing Webmaster Tools

+

Bing's clicks, impressions, searches and crawl issues, on SEO → Search engines. DuckDuckGo and many AI assistants draw on Bing's index.

+ {{template "key-field" (dict "F" .BingKey "Set" .BingSet)}} +
+

Gitea: your sites' repositories

For changes you approve: Supermarket pushes a branch to the website's Hugo repository (set in the profile) and opens a pull request. It never merges.

diff --git a/internal/web/templates/seo-engines.html b/internal/web/templates/seo-engines.html new file mode 100644 index 0000000..ad80d48 --- /dev/null +++ b/internal/web/templates/seo-engines.html @@ -0,0 +1,60 @@ +{{define "content"}}{{with .Data}}{{$d := .}} +

Search engines

+

What Google and Bing know about the site, and IndexNow, which tells Bing and other engines the moment a page changes, so they don't wait for their next crawl. Google doesn't use IndexNow; it reads the sitemap.

+ +{{if not .Sites}} +

Add your websites to the profile first.

+{{else}} +{{if gt (len .Sites) 1}}{{end}} + +
+

Set the site up for search engines

+

One pull request that adds what's missing: the IndexNow key file, a robots.txt that names the sitemap (unless the site has its own), and the sitemap itself if the Hugo config turns it off. A Hugo build checks all three come out.

+ {{with .Setup}} + {{if .Error}}

Last try, {{ago .At}}: {{.Error}}

+ {{else}}

Opened {{ago .At}}: pull request #{{.PRNumber}} ↗. {{range .Done}}{{.}} {{end}}
{{.Note}}

{{end}} + {{end}} +
+
+ +
+

IndexNow

+

Key {{.Key}}, published at {{.KeyURL}}: + {{if .KeyLive}}the site serves it. Pages that go live through Changes or Briefs are submitted on their own. + {{else}}not on the site yet. Merge the setup pull request above; until then nothing is submitted.{{end}}

+ {{if .KeyLive}}
{{end}} + {{if .Pings}} + + {{range .Pings}} + {{end}}
WhenPagesResult
{{ago .At}}{{range .URLs}}{{pagePath .}} {{end}}{{if .Error}}{{.Error}}{{else}}accepted ({{.Status}}){{end}}
+ {{end}} +
+ +
+

Google: sitemaps

+ {{if not .GoogleConnected}}

Connect Search Console and choose this website's property under Settings → Search engines.

+ {{else if .SitemapsErr}}

{{.SitemapsErr}}

+ {{else if .Sitemaps}} + + {{range .Sitemaps}} + {{end}}
SitemapSubmittedLast readPagesProblems
{{.Path}}{{with .LastSubmitted}}{{ago .}}{{end}}{{with .LastDownloaded}}{{ago .}}{{else}}{{if .IsPending}}pending{{end}}{{end}}{{range .Contents}}{{if eq .Type "web"}}{{.Submitted}}{{end}}{{end}}{{if or (ne .Errors "0") (ne .Warnings "0")}}errors: {{.Errors}}, warnings: {{.Warnings}}{{else}}none{{end}}
+ {{else}}

Google has no sitemap for this site. Once the site has one, submit it in Search Console (Indexing → Sitemaps): Supermarket's access is read-only.

{{end}} +
+ +
+

Bing

+ {{if not .BingSite}}

Save a Bing Webmaster API key under Settings → Search engines to see Bing's numbers.

+ {{else if .BingErr}}

{{.BingErr}} (site: {{.BingSite}})

+ {{else}} + {{if .BingDays}} + {{range .BingDays}}{{end}}
Week ofClicksImpressions
{{.Date.Format "2 Jan 2006"}}{{num .Clicks}}{{num .Impressions}}
+ {{else}}

No traffic data from Bing yet.

{{end}} + {{if .BingQueries}}

Searches, last 4 weeks

+ + {{range .BingQueries}}{{end}}
SearchImpressionsClicksPosition
{{.Query}}{{num .Impressions}}{{num .Clicks}}{{dec1 .Position}}
{{end}} +

Crawl issues

+ {{if .BingIssues}}
    {{range .BingIssues}}
  • {{.URL}}{{if .HTTPCode}} ({{.HTTPCode}}){{end}}
  • {{end}}
{{else}}

None.

{{end}} + {{end}} +
+{{end}} +{{end}}{{end}}