Skip to content

Commit dc6fd34

Browse files
TMHSDigitalclaude
andcommitted
Count page views and empty searches with GoatCounter (#120)
The maintainer chose GoatCounter to learn which searches find nothing. - site/public/count.js is a small self-hosted counter that sends GoatCounter's documented /count hits with sendBeacon: page path (no query string), title and referrer, plus named events. No cookies, storage or identifiers; nothing is sent under Do Not Track, Global Privacy Control, automation, localhost or file://. - Every page loads it deferred. script-src stays 'self'; the CSP opens connect-src to the counter's origin only (shared.mjs ANALYTICS_ENDPOINT). The service worker precaches it. - The catalog reports a view once it has settled for two seconds, and each event once per page load (search.mjs viewEvents): the filter combination, and a search with no results (query lowercased and cut to 40 characters, with its filters). - The footer and a new README Privacy section say what is collected. Tests cover the event names, the CSP and the script tag. Checked in a browser on a local build: an empty search is reported once, a search with results is not, nothing is sent from localhost, and the console shows no CSP errors. Fixes #120 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 84aa264 commit dc6fd34

7 files changed

Lines changed: 122 additions & 4 deletions

File tree

‎README.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ re-check forty tabs before a release. (Thanks to magictools: many tool entries s
5656
5757
## Contents
5858

59-
[Start here](#start-here) · [Starter stacks](#starter-stacks) · [Browse the catalog](#browse-the-catalog) · [Reading an entry](#reading-an-entry) · [Safe starting points](#safe-starting-points) · [Licences](#licences) · [Godot](#godot) · [Unreal Engine](#unreal-engine) · [How the catalog stays honest](#how-the-catalog-stays-honest) · [Use the data](#use-the-data) · [Scope](#scope) · [Contributing](#contributing) · [Support](#support)
59+
[Start here](#start-here) · [Starter stacks](#starter-stacks) · [Browse the catalog](#browse-the-catalog) · [Reading an entry](#reading-an-entry) · [Safe starting points](#safe-starting-points) · [Licences](#licences) · [Godot](#godot) · [Unreal Engine](#unreal-engine) · [How the catalog stays honest](#how-the-catalog-stays-honest) · [Use the data](#use-the-data) · [Scope](#scope) · [Contributing](#contributing) · [Privacy](#privacy) · [Support](#support)
6060

6161
## A few of the sources
6262

@@ -262,6 +262,10 @@ recorded about it and how to correct it or remove its preview.
262262
Please follow the [Code of Conduct](CODE_OF_CONDUCT.md). Local commands and the repository
263263
layout are in [CONTRIBUTING.md](CONTRIBUTING.md#repository-layout).
264264

265+
## Privacy
266+
267+
The website counts usage with [GoatCounter](https://www.goatcounter.com/), so the catalog can see which searches find nothing and add what is missing. It sends the page path, title and referrer on each page view, plus two kinds of named event from the catalog: a search that found no results (the query, lowercased and cut to 40 characters) and the set of filters used. There are no cookies, no local storage and no identifiers, and the counter script is served from this site. Nothing is sent when the browser has Do Not Track or Global Privacy Control turned on, or when the site runs locally. The code is [`site/public/count.js`](site/public/count.js).
268+
265269
## Support
266270

267271
If the catalog saves you time, you can [sponsor TMHSDigital on GitHub](https://github.com/sponsors/TMHSDigital). Entirely optional.

‎site/build.mjs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -608,7 +608,7 @@ function main() {
608608
writeOut("manifest.webmanifest", `${JSON.stringify(webManifest(config.site), null, 2)}\n`);
609609
writeOut("sw.js", serviceWorkerJs({
610610
version: payload.generatedAt,
611-
precache: [...new Set(["./", "data.js", "styles.css", "theme.js", "favicon.svg", ...PAGE_MODULES.home, ...FONT_FILES])],
611+
precache: [...new Set(["./", "data.js", "styles.css", "theme.js", "count.js", "favicon.svg", ...PAGE_MODULES.home, ...FONT_FILES])],
612612
}));
613613
writeOut("opensearch.xml", opensearchXml(config.site));
614614
writeOut("404.html", notFoundHtml(config.site));

‎site/lib/lib.test.mjs‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1071,6 +1071,22 @@ eq("url: round trip", readState(`?${stateQuery(urlSt, URL_DEF)}`, URL_DEF, URL_A
10711071
eq("url: defaults write nothing", stateQuery(URL_DEF, URL_DEF), "");
10721072
eq("url: switch off written as 0", stateQuery({ ...URL_DEF, active: false }, URL_DEF), "active=0");
10731073
eq("url: blank q not written", stateQuery({ ...URL_DEF, q: " " }, URL_DEF), "");
1074+
1075+
/* usage events (#120) ----------------------------------------------------- */
1076+
await section("usage events from a catalog view (#120)", async () => {
1077+
const { viewEvents } = await import("./search.mjs");
1078+
const { CSP, ANALYTICS_ENDPOINT, headAssetsHtml, siteFooterHtml } = await import("./shared.mjs");
1079+
eq("default view sends nothing", JSON.stringify(viewEvents(URL_DEF, URL_DEF, 400)), JSON.stringify([]));
1080+
eq("a query with results sends nothing", JSON.stringify(viewEvents({ ...URL_DEF, q: "pixel" }, URL_DEF, 12)), JSON.stringify([]));
1081+
eq("a query with no results is sent normalised", JSON.stringify(viewEvents({ ...URL_DEF, q: " Voxel TREES " }, URL_DEF, 0)), JSON.stringify(["no-results/voxel trees"]));
1082+
eq("the query is cut to 40 characters", viewEvents({ ...URL_DEF, q: "x".repeat(90) }, URL_DEF, 0)[0].length, "no-results/".length + 40);
1083+
eq("filters are sent without the query", JSON.stringify(viewEvents({ ...URL_DEF, q: "tree", category: "2d" }, URL_DEF, 3)), JSON.stringify(["filters/cat=2d"]));
1084+
eq("no results with filters names both", JSON.stringify(viewEvents({ ...URL_DEF, q: "tree", category: "2d" }, URL_DEF, 0)), JSON.stringify(["filters/cat=2d", "no-results/tree [cat=2d]"]));
1085+
eq("CSP connects only to the counter's origin", CSP.includes(`connect-src 'self' ${new URL(ANALYTICS_ENDPOINT).origin};`), true);
1086+
eq("CSP keeps scripts same-origin", CSP.includes("script-src 'self';"), true);
1087+
eq("every page loads count.js deferred", headAssetsHtml("../").includes('<script src="../count.js" defer></script>'), true);
1088+
eq("the footer states what is counted", siteFooterHtml({ root: "./", stamp: "x", total: 1 }).includes("GoatCounter"), true);
1089+
});
10741090
await section("block at line 960", async () => {
10751091
// #223: every choice and switch survives a round trip through the URL.
10761092
const other = { category: "3d", sort: "verified", perspective: "top_down", license: "cc0", format: "image", engine: "godot", fresh: "6m" };

‎site/lib/search.mjs‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -383,6 +383,22 @@ export function stateQuery(state, defaults) {
383383
return p.toString();
384384
}
385385

386+
/**
387+
* The usage events one settled catalog view sends (#120): what was searched
388+
* and found nothing, and which filter combination was used. The query is
389+
* lowercased, whitespace-collapsed and cut to 40 characters; nothing else
390+
* about the reader goes in. Returns a list of event names, empty when the
391+
* view is the default one.
392+
*/
393+
export function viewEvents(state, defaults, resultCount) {
394+
const events = [];
395+
const q = String(state.q || "").trim().toLowerCase().replace(/\s+/g, " ").slice(0, 40);
396+
const filters = stateQuery({ ...state, q: "" }, defaults);
397+
if (filters) events.push(`filters/${filters}`);
398+
if (resultCount === 0 && (q || filters)) events.push(`no-results/${q || "(filters only)"}${filters ? ` [${filters}]` : ""}`);
399+
return events;
400+
}
401+
386402
/* ---------------------------------------------------------------- 404 page */
387403

388404
/** Site sections whose pages live at <section>/<id>/. */

‎site/lib/shared.mjs‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -283,6 +283,7 @@ export function siteFooterHtml({ root, stamp, total, credit = true, current = nu
283283
return `<footer class="footer">
284284
<p>Catalog metadata is CC0. Linked assets keep their own licences. This is the catalog's reading of each licence, not legal advice: re-check the live source before shipping.</p>
285285
${credit ? ` <p class="footer-credit">${PREVIEW_CREDIT_LINE}</p>\n` : ""} <p>${links.join(" · ")}</p>
286+
<p class="footer-privacy">Page views and searches that find nothing are counted with GoatCounter: no cookies, nothing that identifies you, and nothing is sent when your browser asks not to be tracked.</p>
286287
<p class="footer-sponsor">${sponsorButtonHtml()}</p>
287288
<p class="footer-stamp">Built ${esc(stamp)} from ${total} listed sources.</p>
288289
</footer>`;
@@ -362,9 +363,12 @@ export function opensearchLinkHtml(site) {
362363
* requests are same-origin only; inline styles stay allowed for the few
363364
* style="--var: ..." attributes; JSON-LD blocks are data, not script, so the
364365
* policy does not touch them. frame-ancestors cannot be set from a <meta>.
366+
* The one cross-origin request is the cookie-less usage count (#120): the
367+
* self-hosted count.js may connect to ANALYTICS_ENDPOINT's origin, nothing else.
365368
*/
369+
export const ANALYTICS_ENDPOINT = "https://tmhs.goatcounter.com/count";
366370
export const CSP =
367-
"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'";
371+
`default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' ${new URL(ANALYTICS_ENDPOINT).origin}; object-src 'none'; base-uri 'self'; form-action 'self'`;
368372
export const CSP_META = `<meta http-equiv="Content-Security-Policy" content="${CSP}" />`;
369373

370374
/** The CSP, icon, font preloads and stylesheet, resolved against `root`. Every page type shares them. */
@@ -377,6 +381,8 @@ export function headAssetsHtml(root = "./") {
377381
`<link rel="manifest" href="${esc(root)}manifest.webmanifest" />`,
378382
// Blocking on purpose: it sets the chosen theme before the first paint (#111).
379383
`<script src="${esc(root)}theme.js"></script>`,
384+
// Usage counts (#120): deferred, so it never delays the page.
385+
`<script src="${esc(root)}count.js" defer></script>`,
380386
];
381387
}
382388

‎site/public/app.js‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { activeFilterChips, FILTER_DEFAULTS, FILTERS, gapIssueUrl, closestEntries, computeResults as computeResultsFor, passesFilters as passes, placementKey, queryTests as compileQuery, readState, scoreFields, searchFields, shouldGroup as shouldGroupFor, slugOf, sorterFor, SORTS, stateQuery, ENGINES } from "./search.js";
1+
import { activeFilterChips, FILTER_DEFAULTS, FILTERS, gapIssueUrl, closestEntries, computeResults as computeResultsFor, passesFilters as passes, placementKey, queryTests as compileQuery, readState, scoreFields, searchFields, shouldGroup as shouldGroupFor, slugOf, sorterFor, SORTS, stateQuery, ENGINES, viewEvents } from "./search.js";
22
import { CARD_LIMIT, LIST_LIMIT, entryCardHtml, escapeHtml, groupHeadingHtml, groupMoreHtml, PERSPECTIVE_LABELS } from "./cards.mjs";
33
import { installViewToggles } from "./views.js";
44
import { catalogCsv } from "./exports.js";
@@ -548,6 +548,22 @@ import { isListed, PERSPECTIVES } from "./shared.mjs";
548548
// The entries the current view shows, for "Download these" (#110).
549549
let lastList = [];
550550

551+
// Usage counts (#120, count.js): a view is reported once it has stayed the
552+
// same for two seconds, so typing does not send every keystroke, and each
553+
// event name at most once per page load.
554+
let countTimer;
555+
const counted = new Set();
556+
function countView(resultCount) {
557+
clearTimeout(countTimer);
558+
countTimer = setTimeout(() => {
559+
for (const name of viewEvents(state, DEFAULTS, resultCount)) {
560+
if (counted.has(name)) continue;
561+
counted.add(name);
562+
window.fgdaCount?.event(name);
563+
}
564+
}, 2000);
565+
}
566+
551567
function apply({ push = false } = {}) {
552568
clearTimeout(searchTimer);
553569
const results = computeResults();
@@ -556,6 +572,7 @@ import { isListed, PERSPECTIVES } from "./shared.mjs";
556572
renderActiveFilters();
557573
renderGrid(results);
558574
writeUrl({ push });
575+
countView(results.list.length);
559576
}
560577

561578
// The starter table and the guide list are prerendered by the build and

‎site/public/count.js‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/*
2+
* Cookie-less usage counts (#120), sent to GoatCounter's /count endpoint
3+
* (https://www.goatcounter.com/help/countjs-host). Self-hosted instead of
4+
* GoatCounter's count.js so script-src stays 'self'; the CSP allows
5+
* connect-src to the endpoint only (shared.mjs ANALYTICS_ENDPOINT).
6+
*
7+
* What is sent: the page path (no query string), its title and the referrer
8+
* on each page view, plus named events from the catalog (app.js countView:
9+
* a search that found nothing, and which filters were set). No cookies, no
10+
* storage, no identifiers. Nothing is sent when the browser asks not to be
11+
* tracked (Do Not Track or Global Privacy Control), on localhost or a file,
12+
* or under automation.
13+
*/
14+
(function () {
15+
"use strict";
16+
var ENDPOINT = "https://tmhs.goatcounter.com/count";
17+
18+
function off() {
19+
try {
20+
if (navigator.doNotTrack === "1" || window.doNotTrack === "1" || navigator.globalPrivacyControl === true) return true;
21+
if (navigator.webdriver) return true;
22+
var host = location.hostname;
23+
if (location.protocol === "file:" || host === "" || host === "localhost" || host === "127.0.0.1" || host === "[::1]") return true;
24+
return false;
25+
} catch (e) {
26+
return true;
27+
}
28+
}
29+
30+
function send(params) {
31+
if (off()) return;
32+
var parts = [];
33+
for (var k in params) {
34+
if (Object.prototype.hasOwnProperty.call(params, k) && params[k] !== "") {
35+
parts.push(encodeURIComponent(k) + "=" + encodeURIComponent(params[k]));
36+
}
37+
}
38+
parts.push("rnd=" + Math.random().toString(36).slice(2));
39+
var url = ENDPOINT + "?" + parts.join("&");
40+
try {
41+
if (navigator.sendBeacon && navigator.sendBeacon(url)) return;
42+
} catch (e) {
43+
// Fall through to fetch.
44+
}
45+
try {
46+
fetch(url, { method: "POST", keepalive: true, mode: "no-cors", credentials: "omit" }).catch(function () {});
47+
} catch (e) {
48+
// Counting is best effort; it never breaks the page.
49+
}
50+
}
51+
52+
window.fgdaCount = {
53+
event: function (name) {
54+
send({ p: String(name).slice(0, 200), t: String(name).slice(0, 200), e: "true" });
55+
},
56+
};
57+
58+
send({ p: location.pathname, t: document.title, r: document.referrer });
59+
})();

0 commit comments

Comments
 (0)