๐ท Photo Mode
diff --git a/privacy.html b/privacy.html
index a81a628..190e0f0 100644
--- a/privacy.html
+++ b/privacy.html
@@ -20,6 +20,7 @@
๐ง The short version (for kids)
We don't know who you are. We never ask for your real name, email, address, phone number, school or photos.
Your worlds stay on your device unless you choose to play online.
If you make an account, we keep only a made-up username and your password (scrambled so nobody can read it). Never use your real name as your username!
+
In the online edition we count things, not people. Like "12 visits from tablets today". If the game breaks, it tells us what went wrong so we can fix it, but never who you are.
No ads, no tracking, nothing to buy. We never sell anything about you.
In Play Together other players only see a colour-and-animal name like "Blue Fox". There's no chat, just emoji.
You can delete your account any time, and it's gone straight away.
@@ -33,8 +34,9 @@
1. Who we are
2. Two ways to play
- Free edition and playing without an account: everything happens in your browser. We receive nothing about you or your game.
- Online edition with an account: adds features that need our server, such as Play Together. Only then do we keep the small amount of information below.
+ Free edition: everything happens in your browser. We receive nothing about you or your game.
+ Online edition: sends anonymous usage counts and problem reports (section 6), which say nothing about who you are.
+ Online edition with an account: adds features that need our server, such as Play Together. Only then do we keep the small amount of account information below.
3. What is stored on your device
@@ -43,6 +45,7 @@
3. What is stored on your device
Your worlds, quest stars, settings and hotbar.
Your Play Together colour-and-animal name.
For Adventure mode, a note that the grown-up check was passed, which is cleared when the browser is closed.
+
In the online edition, a list of which usage counts this visit already sent (so each is counted once), cleared when the browser is closed.
A copy of the game's files, so it works without internet.
You can remove all of this by clearing the site's data in your browser settings.
@@ -67,14 +70,23 @@
5. Play Together
The host lets each player in and can remove players.
-
6. Keeping things safe
+
6. Anonymous usage counts and problem reports (online edition)
+
To see which features are used and to fix bugs, the online edition sends us a little information. It is built so that it can't identify anyone:
+
+ No cookies, no player IDs, no fingerprinting, and no internet addresses stored. The free edition sends none of this.
+ Daily counts only. We add 1 to a counter for the day, for example "a visit from a phone using Safari", "Play Together was used" or "Bit ran a program", at most once per visit. We never keep a list of visits or a history for any person.
+ Problem reports. When the game crashes or freezes, or a player presses "๐ Report a problem" and picks what went wrong from a list (there's no typing), we keep: the error message, where in the game it happened, the game version, the browser and device family (such as "iPhone, Safari"), the screen size, and the last few steps in the game (such as "opened Bit's panel โ pressed Run"). Identical reports are grouped and counted.
+ How long: problem reports are deleted after 90 days. Daily counts contain nothing about any person, so we keep them to see how the game is used over time.
+
+
+
7. Keeping things safe
To stop people guessing passwords or flooding the service, our server briefly remembers internet addresses in memory only, for up to one hour . They are never written to disk.
We switch off request logs for the game. Technical error logs may briefly contain an internet address while we fix a problem.
Our account database is backed up every night in encrypted cloud storage. Backups are kept for up to 30 days, so a deleted account fully disappears from backups within 30 days.
-
7. Services that help us run MiniCrafter
+
8. Services that help us run MiniCrafter
We don't sell or share your information for advertising, ever. These providers process data only to run the service for us:
Cloudflare delivers the website and protects it from attacks. It handles internet addresses and may set a short-lived security cookie.
@@ -84,21 +96,21 @@ 7. Services that help us run MiniCrafter
These providers may be located outside your country. We use them with protections required by law.
-
8. Children
+
9. Children
MiniCrafter is made for children, so we collect as little as possible and never use anything for advertising or profiling.
Players under 13 can make an account only with a parent or guardian, who confirms when the account is made.
Grown-ups can ask us to see or delete a child's account at info@dynamicweblab.com . Please include the username.
-
9. Your rights
+
10. Your rights
Delete: open the ๐ค account screen in the game, choose "Delete my account" and enter your password. Your account, sessions and agreement record are deleted straight away.
See, correct or ask questions: email info@dynamicweblab.com . Depending on where you live (for example the UAE, the EU, the UK or the US), you may have more rights. We'll help with all of them.
You can also complain to your local data protection authority.
-
10. Changes
+
11. Changes
If we change this policy, we'll update the date at the top. If a change is important, we'll show a notice in the game before it applies.
diff --git a/server/Dockerfile b/server/Dockerfile
index cbc9c41..528321a 100644
--- a/server/Dockerfile
+++ b/server/Dockerfile
@@ -3,6 +3,6 @@ FROM node:22-alpine
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev --ignore-scripts && npm cache clean --force
-COPY rooms.mjs accounts.mjs ./
+COPY rooms.mjs accounts.mjs stats.mjs ./
USER node
CMD ["node", "rooms.mjs"]
diff --git a/server/README.md b/server/README.md
index c8c075a..fdf8f9a 100644
--- a/server/README.md
+++ b/server/README.md
@@ -6,6 +6,7 @@ Two small services for the hosted online edition, plus a database. Single-player
|---|---|---|
| Relay | `rooms.mjs` | Play Together rooms for up to 4 logged-in players (zero dependencies, nothing stored) |
| Accounts | `accounts.mjs` | Register, log in, log out and delete an account (Postgres; only dependency: `pg`) |
+| Insights | `stats.mjs` | Anonymous daily usage counts and problem reports, mounted in the accounts service |
| Database | Postgres 16 | Usernames, password hashes and sessions. **Back it up.** |
| Dev server | `dev.mjs` | All of the above on one local address, with accounts in memory |
@@ -17,6 +18,13 @@ Two small services for the hosted online edition, plus a database. Single-player
- Rate limits: new accounts per address per hour, and wrong passwords per address and per username.
- Deleting an account deletes its sessions too, straight away.
+## Insights: anonymous counts and problem reports
+- `POST /api/events` adds 1 to daily counters ("a visit from a phone using Safari", "Bit ran"). No cookies, no IDs, nothing per person.
+- `POST /api/errors` keeps crashes, freezes (the game stopped for over 5 s) and "Report a problem" picks (a fixed list, no typing), with the message, place, game version, browser/device family, screen size and the last 12 game steps. Grouped per day and deleted after 90 days.
+- Both are same-origin only and rate-limited; internet addresses are held in memory for one minute and never stored.
+- `GET /api/stats` needs `Authorization: Bearer $STATS_TOKEN`. Open `stats.html` on the site and enter the key. Without `STATS_TOKEN` in `.env` it is closed.
+- Only the hosted site sends any of this (`"insights": true` in its `site-config.json`). The free edition sends nothing.
+
# The Play Together relay
## Why a relay (and not direct peer-to-peer)
@@ -36,7 +44,7 @@ For the whole online edition locally, run `node server/dev.mjs` and open http://
## Deploy (Docker, behind a reverse proxy)
```bash
cd server
-printf "ALLOWED_ORIGINS=https://your-site.example\nPOSTGRES_PASSWORD=%s\n" "$(openssl rand -hex 24)" > .env
+printf "ALLOWED_ORIGINS=https://your-site.example\nPOSTGRES_PASSWORD=%s\nSTATS_TOKEN=%s\n" "$(openssl rand -hex 24)" "$(openssl rand -hex 24)" > .env
chmod 600 .env
docker compose up -d --build
```
diff --git a/server/accounts.mjs b/server/accounts.mjs
index 5313d0e..a8c0cfc 100644
--- a/server/accounts.mjs
+++ b/server/accounts.mjs
@@ -234,10 +234,17 @@ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href)
for (let i = 1; ; i++) { // the database may still be starting up
try { await store.init(); break; } catch (e) { if (i >= 30) throw e; await new Promise((r) => setTimeout(r, 2000)); }
}
- const acc = createAccounts({ store, origins: (process.env.ALLOWED_ORIGINS || '').split(',').map((s) => s.trim()).filter(Boolean), secureCookie: process.env.SECURE_COOKIE !== '0' });
+ const origins = (process.env.ALLOWED_ORIGINS || '').split(',').map((s) => s.trim()).filter(Boolean);
+ const acc = createAccounts({ store, origins, secureCookie: process.env.SECURE_COOKIE !== '0' });
+ // Anonymous usage counts and error reports share the database (see stats.mjs).
+ const { createStats, PgStats, MemoryStats } = await import('./stats.mjs');
+ const statsStore = store.pool ? new PgStats(store.pool) : new MemoryStats();
+ await statsStore.init();
+ const stats = createStats({ store: statsStore, origins, token: process.env.STATS_TOKEN || '' });
const server = http.createServer(async (req, res) => {
if (req.url === '/health') { res.writeHead(200); return res.end('ok'); }
if (await acc.handleInternal(req, res)) return;
+ if (await stats.handle(req, res)) return;
if (await acc.handle(req, res)) return;
res.writeHead(404); res.end();
});
diff --git a/server/dev.mjs b/server/dev.mjs
index 7656353..ad62ec2 100644
--- a/server/dev.mjs
+++ b/server/dev.mjs
@@ -7,22 +7,26 @@ import { extname, join, normalize, sep } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { createAccounts, MemoryStore } from './accounts.mjs';
import { attachRelay } from './rooms.mjs';
+import { createStats, MemoryStats } from './stats.mjs';
const ROOT = fileURLToPath(new URL('..', import.meta.url));
const TYPES = { '.html': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript', '.css': 'text/css', '.json': 'application/json', '.webmanifest': 'application/manifest+json', '.png': 'image/png', '.jpg': 'image/jpeg', '.svg': 'image/svg+xml' };
-const SERVE = ['index.html', 'style.css', 'privacy.html', 'terms.html', 'legal.css', 'features.html', 'features.css', 'llms.txt', 'docs', 'sw.js', 'manifest.webmanifest', 'icons', 'src', 'vendor'];
+const SERVE = ['index.html', 'stats.html', 'style.css', 'privacy.html', 'terms.html', 'legal.css', 'features.html', 'features.css', 'llms.txt', 'docs', 'sw.js', 'manifest.webmanifest', 'icons', 'src', 'vendor'];
/** Starts the dev server. Returns { server, port, url }. */
export async function startDevServer(port = 8770) {
const cfg = { origins: [] };
const accounts = createAccounts({ store: new MemoryStore(), get origins() { return cfg.origins; }, secureCookie: false });
+ const statsStore = new MemoryStats();
+ const stats = createStats({ store: statsStore, get origins() { return cfg.origins; }, token: 'dev' });
const server = http.createServer(async (req, res) => {
+ if (await stats.handle(req, res)) return;
if (await accounts.handle(req, res)) return;
try {
let p = decodeURIComponent(new URL(req.url, 'http://x').pathname);
if (p === '/site-config.json') {
res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
- return res.end('{ "online": true, "rooms": "/rooms", "accounts": true }\n');
+ return res.end('{ "online": true, "rooms": "/rooms", "accounts": true, "insights": true }\n');
}
if (p.endsWith('/')) p += 'index.html';
const file = normalize(join(ROOT, p));
@@ -37,7 +41,7 @@ export async function startDevServer(port = 8770) {
await new Promise((r) => server.listen(port, '127.0.0.1', r));
const p = server.address().port;
cfg.origins = [`http://127.0.0.1:${p}`, `http://localhost:${p}`];
- return { server, port: p, url: `http://127.0.0.1:${p}/` };
+ return { server, port: p, url: `http://127.0.0.1:${p}/`, stats: statsStore };
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
diff --git a/server/docker-compose.yml b/server/docker-compose.yml
index 3e875d0..b00e040 100644
--- a/server/docker-compose.yml
+++ b/server/docker-compose.yml
@@ -3,6 +3,7 @@
# Settings come from a .env file next to this one (never commit it):
# ALLOWED_ORIGINS=https://your-site.example
# POSTGRES_PASSWORD=
+# STATS_TOKEN=
services:
minicrafter-rooms:
build: .
@@ -25,6 +26,7 @@ services:
environment:
ALLOWED_ORIGINS: ${ALLOWED_ORIGINS:?set ALLOWED_ORIGINS in .env}
DATABASE_URL: postgres://minicrafter:${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env}@minicrafter-db:5432/minicrafter
+ STATS_TOKEN: ${STATS_TOKEN:-} # empty = /api/stats is closed
networks: [minicrafter_net]
read_only: true
mem_limit: 256m
diff --git a/server/stats.mjs b/server/stats.mjs
new file mode 100644
index 0000000..5eb1658
--- /dev/null
+++ b/server/stats.mjs
@@ -0,0 +1,143 @@
+// Anonymous usage counts and error reports for the online edition.
+//
+// Privacy by design (players are often children):
+// - No cookies, no player IDs, no fingerprinting, no IP addresses stored (they are only held in
+// memory for a minute for rate limiting).
+// - Usage is stored as daily counters only ("12 visits from phones today"), never per person.
+// - Error reports keep the message, where in the game it happened, the game version and the
+// browser family, grouped and counted. Kept for 90 days.
+// - Problem reports have three kinds: "error" (a crash), "freeze" (the game stopped responding for a
+// while) and "report" (a player pressed "Report a problem" and picked a category: no free text).
+// Each keeps the last few game steps ("opened Bit's panel", "pressed Run") to help reproduce it.
+// Routes: POST /api/events, POST /api/errors (same-site only), GET /api/stats (needs STATS_TOKEN).
+const MAX_BODY = 8192;
+const COUNTER = /^[a-z0-9_:.-]{1,60}$/;
+const CTX = {
+ device: ['phone', 'tablet', 'desktop'],
+ os: ['ios', 'android', 'windows', 'mac', 'chromeos', 'linux', 'other'],
+ browser: ['safari', 'chrome', 'firefox', 'edge', 'samsung', 'other'],
+ edition: ['online', 'free', 'dev'],
+ mode: ['creative', 'survival', 'adventure'],
+};
+export const REPORTS = ['The game got stuck', "Bit isn't working", "Play Together isn't working", 'Something looks wrong', "A button doesn't work", 'Something else'];
+const EVENTS = new Set(['visit', 'play', 'installed', 'together_host', 'together_join', 'course_finish', 'photo_saved', 'bit_run',
+ 'account_register', 'account_login', 'adventure', 'circuit', 'quest_done', 'world_new', 'touch']);
+
+export class MemoryStats {
+ constructor() { this.counts = new Map(); this.errors = new Map(); }
+ async init() {}
+ async add(day, keys) { for (const k of keys) { const id = `${day}|${k}`; this.counts.set(id, (this.counts.get(id) || 0) + 1); } }
+ async addError(day, e) {
+ const id = `${day}|${e.sig}`;
+ const old = this.errors.get(id);
+ this.errors.set(id, old ? { ...old, count: old.count + 1, last_seen: new Date() } : { day, ...e, count: 1, last_seen: new Date() });
+ }
+ async summary(days) {
+ const since = dayStr(Date.now() - days * 86400_000);
+ const counts = [...this.counts].map(([id, n]) => { const [day, key] = id.split('|'); return { day, key, n }; }).filter((r) => r.day >= since);
+ const errors = [...this.errors.values()].filter((r) => r.day >= since).sort((a, b) => b.last_seen - a.last_seen);
+ return { counts, errors };
+ }
+}
+
+export class PgStats {
+ constructor(pool) { this.pool = pool; }
+ async init() {
+ await this.pool.query(`
+ CREATE TABLE IF NOT EXISTS daily_counts (day DATE NOT NULL, key TEXT NOT NULL, n BIGINT NOT NULL DEFAULT 0, PRIMARY KEY (day, key));
+ CREATE TABLE IF NOT EXISTS error_reports (
+ day DATE NOT NULL, sig TEXT NOT NULL, message TEXT NOT NULL, place TEXT, version TEXT,
+ browser TEXT, os TEXT, device TEXT, count INT NOT NULL DEFAULT 1, last_seen TIMESTAMPTZ NOT NULL DEFAULT now(),
+ PRIMARY KEY (day, sig));
+ ALTER TABLE error_reports ADD COLUMN IF NOT EXISTS kind TEXT NOT NULL DEFAULT 'error';
+ ALTER TABLE error_reports ADD COLUMN IF NOT EXISTS steps TEXT;
+ ALTER TABLE error_reports ADD COLUMN IF NOT EXISTS screen TEXT;`);
+ setInterval(() => this.pool.query("DELETE FROM error_reports WHERE day < now() - interval '90 days'").catch(() => {}), 6 * 3600_000).unref();
+ }
+ async add(day, keys) {
+ for (const k of keys) await this.pool.query('INSERT INTO daily_counts (day, key, n) VALUES ($1, $2, 1) ON CONFLICT (day, key) DO UPDATE SET n = daily_counts.n + 1', [day, k]);
+ }
+ async addError(day, e) {
+ await this.pool.query(`INSERT INTO error_reports (day, sig, kind, message, place, version, browser, os, device, steps, screen) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)
+ ON CONFLICT (day, sig) DO UPDATE SET count = error_reports.count + 1, last_seen = now(), steps = EXCLUDED.steps, screen = EXCLUDED.screen`,
+ [day, e.sig, e.kind, e.message, e.place, e.version, e.browser, e.os, e.device, e.steps, e.screen]);
+ }
+ async summary(days) {
+ const counts = (await this.pool.query("SELECT to_char(day, 'YYYY-MM-DD') AS day, key, n::int AS n FROM daily_counts WHERE day >= current_date - $1::int ORDER BY day", [days])).rows;
+ const errors = (await this.pool.query("SELECT to_char(day, 'YYYY-MM-DD') AS day, kind, message, place, version, browser, os, device, steps, screen, count, last_seen FROM error_reports WHERE day >= current_date - $1::int ORDER BY last_seen DESC LIMIT 300", [days])).rows;
+ return { counts, errors };
+ }
+}
+
+const dayStr = (t = Date.now()) => new Date(t).toISOString().slice(0, 10);
+const pick = (v, list) => (list.includes(v) ? v : 'other');
+const clean = (s, max) => String(s ?? '').replace(/https?:\/\/[^\s)]+?\/([^/\s)]+)(?=[\s):]|$)/g, '$1').replace(/[\u0000-\u001f]/g, ' ').slice(0, max);
+
+/**
+ * @param {object} o { store, origins (getter ok), token }
+ * @returns {{ handle(req, res) -> Promise }}
+ */
+export function createStats(o) {
+ const hits = new Map(); // address -> { n, reset }, for one minute, in memory only
+ setInterval(() => { const n = Date.now(); for (const [k, v] of hits) if (n > v.reset) hits.delete(k); }, 60_000).unref();
+ const limited = (req, max) => {
+ const ip = String(req.headers['x-real-ip'] || req.socket.remoteAddress || '');
+ const n = Date.now(); const v = hits.get(ip) || { n: 0, reset: n + 60_000 };
+ if (n > v.reset) { v.n = 0; v.reset = n + 60_000; }
+ v.n++; hits.set(ip, v);
+ return v.n > max;
+ };
+ const send = (res, code, body) => { res.writeHead(code, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }); res.end(JSON.stringify(body)); };
+ const read = (req) => new Promise((resolve, reject) => {
+ let n = 0; const parts = [];
+ req.on('data', (c) => { n += c.length; if (n > MAX_BODY) { reject(new Error('big')); req.destroy(); } else parts.push(c); });
+ req.on('end', () => { try { resolve(JSON.parse(Buffer.concat(parts).toString('utf8') || '{}')); } catch { reject(new Error('json')); } });
+ req.on('error', reject);
+ });
+ const ctxOf = (c = {}) => ({ device: pick(c.device, CTX.device), os: pick(c.os, CTX.os), browser: pick(c.browser, CTX.browser), edition: pick(c.edition, CTX.edition), mode: CTX.mode.includes(c.mode) ? c.mode : null, version: /^v\d{1,4}$/.test(c.version) ? c.version : 'v?' });
+
+ async function handle(req, res) {
+ const path = new URL(req.url, 'http://x').pathname;
+ if (path === '/api/stats' && req.method === 'GET') {
+ const auth = String(req.headers.authorization || '');
+ if (!o.token || auth !== `Bearer ${o.token}`) return send(res, 401, { error: 'no' }), true;
+ const days = Math.min(365, Math.max(1, Number(new URL(req.url, 'http://x').searchParams.get('days')) || 30));
+ return send(res, 200, await o.store.summary(days)), true;
+ }
+ if (path !== '/api/events' && path !== '/api/errors') return false;
+ if (req.method !== 'POST') return send(res, 405, {}), true;
+ // Same-site only (sendBeacon can't add custom headers, so the Origin check is the gate).
+ if (!(o.origins || []).includes(req.headers.origin || '')) return send(res, 403, {}), true;
+ if (limited(req, 120)) return send(res, 429, {}), true;
+ let body;
+ try { body = await read(req); } catch { return send(res, 400, {}), true; }
+ const ctx = ctxOf(body.ctx);
+ const day = dayStr();
+ try {
+ if (path === '/api/events') {
+ const names = (Array.isArray(body.events) ? body.events : []).slice(0, 20).filter((e) => EVENTS.has(e));
+ const keys = [];
+ for (const e of names) {
+ keys.push(e);
+ if (e === 'visit') keys.push(`device:${ctx.device}`, `os:${ctx.os}`, `browser:${ctx.browser}`, `edition:${ctx.edition}`, `version:${ctx.version}`);
+ if (e === 'play' && ctx.mode) keys.push(`mode:${ctx.mode}`);
+ }
+ await o.store.add(day, keys.filter((k) => COUNTER.test(k)));
+ } else {
+ const kind = ['error', 'freeze', 'report'].includes(body.kind) ? body.kind : 'error';
+ // Player reports are a picked category only (no typing), so nothing personal can slip in.
+ const message = kind === 'report' ? (REPORTS.includes(body.message) ? body.message : '') : clean(body.message, 300);
+ if (!message) return send(res, 400, {}), true;
+ const place = clean(body.place, 120);
+ const steps = (Array.isArray(body.steps) ? body.steps : []).slice(-12).map((t) => clean(t, 60).replace(/[^\w .,:+\-#()/'โ]/g, '')).join(' โ ').slice(0, 900);
+ const screen = /^\d{2,5}x\d{2,5}( [a-z, ]{0,40})?$/.test(String(body.screen || '')) ? String(body.screen) : '';
+ const sig = `${kind}|${message}|${place}|${ctx.version}|${ctx.browser}|${ctx.device}`.slice(0, 500);
+ await o.store.addError(day, { sig, kind, message, place, version: ctx.version, browser: ctx.browser, os: ctx.os, device: ctx.device, steps, screen });
+ await o.store.add(day, [kind]);
+ }
+ } catch { return send(res, 500, {}), true; }
+ res.writeHead(204, { 'Cache-Control': 'no-store' }); res.end();
+ return true;
+ }
+ return { handle };
+}
diff --git a/src/insights.js b/src/insights.js
new file mode 100644
index 0000000..233e175
--- /dev/null
+++ b/src/insights.js
@@ -0,0 +1,114 @@
+// Anonymous usage counts and error reports (online edition only; see server/stats.mjs).
+// No cookies and no IDs: the game only says things like "a visit from a phone using Safari"
+// or "Play Together was used", at most once per browser session each, plus error messages
+// so we can fix problems players hit. The free edition never sends anything.
+const ONCE = 'minicrafter:insights'; // sessionStorage: which counts this session already sent
+const MAX_ERRORS = 8; // per session
+const FREEZE_MS = 5000; // the game stopped responding this long (while on screen) = a freeze
+export const REPORTS = ['The game got stuck', "Bit isn't working", "Play Together isn't working", 'Something looks wrong', "A button doesn't work", 'Something else'];
+
+function detect() {
+ const ua = navigator.userAgent;
+ const iPad = /iPad/.test(ua) || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);
+ const os = /iPhone|iPod/.test(ua) || iPad ? 'ios' : /Android/.test(ua) ? 'android' : /CrOS/.test(ua) ? 'chromeos'
+ : /Windows/.test(ua) ? 'windows' : /Mac OS X/.test(ua) ? 'mac' : /Linux/.test(ua) ? 'linux' : 'other';
+ const device = iPad || (/Android/.test(ua) && !/Mobile/.test(ua)) || /Tablet/.test(ua) ? 'tablet' : /Mobi|iPhone|iPod|Android/.test(ua) ? 'phone' : 'desktop';
+ const browser = /SamsungBrowser/.test(ua) ? 'samsung' : /Edg\//.test(ua) ? 'edge' : /Firefox|FxiOS/.test(ua) ? 'firefox'
+ : /Chrome|CriOS|Chromium/.test(ua) ? 'chrome' : /Safari/.test(ua) ? 'safari' : 'other';
+ return { device, os, browser };
+}
+
+export class Insights {
+ constructor() {
+ this.enabled = false;
+ this.queue = [];
+ this.errors = 0;
+ this.steps = []; // the last few things the player did, to help reproduce a problem
+ this.t0 = performance.now();
+ this.lastBeat = 0;
+ this.ctx = { ...detect(), edition: 'online', version: 'v?' };
+ try { this.sent = new Set(JSON.parse(sessionStorage.getItem(ONCE) || '[]')); } catch { this.sent = new Set(); }
+ }
+
+ /** Switch on (only where the site config says so) and count the visit. */
+ start(edition = 'online') {
+ if (this.enabled) return;
+ this.enabled = true;
+ this.ctx.edition = edition;
+ window.caches?.keys().then((keys) => {
+ const v = Math.max(0, ...keys.map((k) => Number((/^minicrafter-v(\d+)$/.exec(k) || [])[1] || 0)));
+ if (v) this.ctx.version = `v${v}`;
+ }).catch(() => {}).finally(() => this.event('visit'));
+ window.addEventListener('error', (e) => this.error(e.message || 'error', `${(e.filename || '').split('/').pop()}:${e.lineno || 0}:${e.colno || 0}`));
+ window.addEventListener('unhandledrejection', (e) => {
+ const r = e.reason;
+ const frame = (r && r.stack ? String(r.stack).split('\n').find((l) => /\.js/.test(l)) : '') || '';
+ this.error(r && r.message ? r.message : String(r).slice(0, 200), (frame.match(/([\w-]+\.js:\d+:\d+)/) || [])[1] || 'promise');
+ });
+ setInterval(() => this.flush(), 15000);
+ addEventListener('pagehide', () => this.flush(true));
+ document.addEventListener('visibilitychange', () => {
+ this.lastBeat = 0; // frames pause while hidden: that gap is not a freeze
+ if (document.visibilityState === 'hidden') this.flush(true);
+ });
+ addEventListener('pageshow', () => { this.lastBeat = 0; });
+ }
+
+ /** Counts a thing that happened, at most once per browser session. */
+ event(name, extra = {}) {
+ if (!this.enabled || this.sent.has(name)) return;
+ this.sent.add(name);
+ try { sessionStorage.setItem(ONCE, JSON.stringify([...this.sent])); } catch { /* ignore */ }
+ if (extra.mode) this.ctx.mode = extra.mode;
+ this.queue.push(name);
+ if (name === 'visit') this.flush();
+ }
+
+ /** Remembers a game step, like "opened Bit's panel" (kept in memory, sent only with a problem report). */
+ step(text) {
+ const t = Math.round((performance.now() - this.t0) / 1000);
+ this.steps.push(`${t}s ${text}`);
+ if (this.steps.length > 12) this.steps.shift();
+ }
+
+ /** Called every frame: notices when the game froze for a while and then recovered. */
+ beat(now = performance.now()) {
+ if (this.lastBeat && document.visibilityState === 'visible' && now - this.lastBeat > FREEZE_MS) {
+ this.problem('freeze', `The game froze for ${Math.round((now - this.lastBeat) / 1000)} s`, 'frame loop');
+ }
+ this.lastBeat = now;
+ }
+
+ screen() {
+ const standalone = navigator.standalone || matchMedia('(display-mode: standalone), (display-mode: fullscreen)').matches;
+ const touch = navigator.maxTouchPoints > 0;
+ return `${innerWidth}x${innerHeight} ${[innerWidth > innerHeight ? 'landscape' : 'portrait', touch ? 'touch' : '', standalone ? 'installed' : ''].filter(Boolean).join(', ')}`;
+ }
+
+ error(message, place = '') { this.problem('error', message, place); }
+
+ /** A player pressed "Report a problem" and picked a category. */
+ report(category) { return this.problem('report', REPORTS.includes(category) ? category : 'Something else', this.where || 'menu', true); }
+
+ problem(kind, message, place, always = false) {
+ if (!this.enabled || (!always && this.errors >= MAX_ERRORS)) return false;
+ this.errors++;
+ this.step(`problem: ${kind}`);
+ this.post('./api/errors', { kind, message: String(message).slice(0, 300), place: String(place).slice(0, 120), steps: this.steps, screen: this.screen(), ctx: this.ctx }, false);
+ return true;
+ }
+
+ flush(closing = false) {
+ if (!this.queue.length) return;
+ const events = this.queue.splice(0, 20);
+ this.post('./api/events', { events, ctx: this.ctx }, closing);
+ }
+
+ post(url, body, closing) {
+ const data = JSON.stringify(body);
+ try {
+ if (closing && navigator.sendBeacon) { navigator.sendBeacon(url, new Blob([data], { type: 'application/json' })); return; }
+ fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: data, keepalive: true, credentials: 'omit' }).catch(() => {});
+ } catch { /* never let reporting break the game */ }
+ }
+}
diff --git a/src/main.js b/src/main.js
index b865288..d872fc0 100644
--- a/src/main.js
+++ b/src/main.js
@@ -27,6 +27,9 @@ import { Together, COLORS, ANIMALS, EMOJI, profileName, saveProfile, loadSiteCon
import { Account, accountMessage } from './account.js';
import { Course, fmtTime } from './course.js';
import { PhotoMode, FRAMES, FILTERS, STICKERS } from './photo.js';
+import { Insights, REPORTS } from './insights.js';
+
+const insights = new Insights(); // anonymous counts + error reports, online edition only
const account = new Account();
import { IDEAS, ideaOfTheDay } from './ideas.js';
@@ -51,6 +54,8 @@ renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
$('game').appendChild(renderer.domElement);
const canvas = renderer.domElement;
+/** Leaves pointer lock. iPhones and iPads have no Pointer Lock API, so calling it bare there throws. */
+function exitLock() { if (document.pointerLockElement) document.exitPointerLock?.(); }
const scene = new THREE.Scene();
scene.fog = new THREE.Fog(0x87ceeb, 50, 100);
@@ -109,6 +114,7 @@ const course = new Course({
hint(`๐ Finished in ${fmtTime(r.time)}${coins}${r.newBest ? (r.beatOld ? ' ยท ๐ New best time!' : '') : ` ยท Best ${fmtTime(r.best)}`}`, 4500);
renderCourseHud();
quests.emit('course', { kind: 'finish', time: r.time, coins: r.coins, total: r.total, beatOld: r.beatOld });
+ insights.event('course_finish');
dirtySave = true;
},
onCancel(reason) {
@@ -126,13 +132,14 @@ function renderCourseHud() {
// ---------- Photo Mode ----------
const photo = new PhotoMode();
async function openPhoto() {
+ insights.step('opened Photo Mode');
if (state !== 'playing') return;
renderer.render(scene, camera); // capture a clean frame (the HUD is not part of the 3D view)
await photo.capture(canvas);
state = 'photo';
clearInput();
touch?.setEnabled(false);
- if (document.pointerLockElement) document.exitPointerLock();
+ exitLock();
sfx.tone(1400, 0.05, 'square', 0.12); setTimeout(() => sfx.tone(900, 0.08, 'square', 0.1), 60); // click!
$('photo').classList.remove('hidden');
renderPhoto();
@@ -179,6 +186,7 @@ $('ph-save').addEventListener('click', async () => {
document.body.appendChild(a); a.click(); a.remove();
setTimeout(() => URL.revokeObjectURL(a.href), 4000);
toast('๐ท Photo saved!');
+ insights.event('photo_saved');
quests.emit('photo', {});
});
$('ph-share').addEventListener('click', async () => {
@@ -214,6 +222,7 @@ const together = new Together({
closeTogether();
sfx.fanfare?.();
toast('๐ซ You joined the game! Press T (or ๐) to wave.');
+ insights.event('together_join');
if (state !== 'playing') enterPlay();
},
endGuest(reason) {
@@ -604,6 +613,7 @@ function renderQuestBook() {
let celebrateTimer;
quests.onComplete = (q) => {
+ insights.event('quest_done');
gainXp(q.stars * 5);
const c = $('celebrate');
c.querySelector('.c-name').textContent = `${q.icon} ${q.title}`;
@@ -710,6 +720,7 @@ function refreshMode() {
}
function setMode(m) {
+ insights.step(`mode ${m}`);
if (m === mode) return;
if (adv.hardcore) { toast('Hardcore worlds stay in Adventure mode'); return; }
if (together.isGuest) { toast("The host picks the game mode"); return; }
@@ -787,6 +798,7 @@ function clearInput() {
}
function showMenu() {
+ insights.step('menu');
state = 'menu';
touch?.setEnabled(false);
$('menu').classList.remove('hidden');
@@ -797,6 +809,7 @@ function showMenu() {
}
function openOverlay() {
+ insights.step('opened inventory');
clearInput();
touch?.setEnabled(false);
if (isSurvival()) {
@@ -807,18 +820,19 @@ function openOverlay() {
$('inv-slot').textContent = selected + 1;
$('inventory').classList.remove('hidden');
}
- document.exitPointerLock();
+ exitLock();
}
let bookFromMenu = false;
function openQuestBook(fromMenu) {
+ insights.step('opened quest book');
bookFromMenu = fromMenu;
clearInput();
touch?.setEnabled(false);
state = 'questbook';
renderQuestBook();
$('questbook').classList.remove('hidden');
- if (!fromMenu) document.exitPointerLock();
+ if (!fromMenu) exitLock();
}
/** What Bit is currently running (for the coding quests). */
@@ -830,6 +844,8 @@ const robotUI = new RobotUI({
getRobot: () => robot,
onRun: (name, program) => {
robotRun.program = program;
+ insights.event('bit_run');
+ insights.step('Bit run');
robotRun.custom = !EXAMPLE_KEYS.has(stripIds(program));
robotRun.startY = robot.y;
dirtySave = true;
@@ -848,6 +864,7 @@ const robotUI = new RobotUI({
// ---------- villager trading ----------
let tradeWith = null;
function openTrade(mob) {
+ insights.step('opened trading');
clearInput();
touch?.setEnabled(false);
state = 'trade';
@@ -856,7 +873,7 @@ function openTrade(mob) {
quests.emit('meetVillager', { job: mob.job });
renderTrade();
$('trade').classList.remove('hidden');
- document.exitPointerLock();
+ exitLock();
}
function renderTrade() {
@@ -895,11 +912,12 @@ function renderTrade() {
$('tr-done').addEventListener('click', () => closeOverlay(true));
function openRobotPanel() {
+ insights.step("opened Bit's panel");
clearInput();
touch?.setEnabled(false);
state = 'robot';
robotUI.open();
- document.exitPointerLock();
+ exitLock();
tip('robot', 'Pick a starter program and watch Bit work. Hold a block so Bit can build with it!');
}
@@ -930,6 +948,11 @@ document.addEventListener('pointerlockerror', () => {
/** Switch to the in-game view (after pointer lock on desktop, immediately on touch). */
function startPlaying() {
+ insights.step(`playing ${mode}${touchMode ? ' (touch)' : ''}`);
+ insights.event('play', { mode });
+ if (touchMode) insights.event('touch');
+ if (isAdventure()) insights.event('adventure');
+ if (navigator.standalone || matchMedia('(display-mode: standalone), (display-mode: fullscreen)').matches) insights.event('installed');
state = 'playing';
hasPlayed = true;
$('menu').classList.add('hidden');
@@ -946,6 +969,7 @@ function startPlaying() {
}
function enterPlay() {
+ insights.step('pressed Play');
// Adventure worlds sit behind the grown-up gate (once per browser session).
if (isAdventure() && !gateUnlocked()) { showGate(() => enterPlay(), () => showMenu()); return; }
if (touchMode && upright.matches) { askSideways(); return; }
@@ -1015,6 +1039,7 @@ function renderTogether() {
: r === 'guest' ? `๐ซ You're in game ${together.code}.` : (together.error || '');
$('tg-close').textContent = r === 'waiting' ? 'Cancel' : r === 'guest' ? 'Leave the game' : 'Back';
if (hosting) {
+ insights.event('together_host');
$('tg-code-big').textContent = together.code;
$('tg-lock').textContent = together.locked ? '๐ Room locked' : '๐ Room open';
const ul = $('tg-players');
@@ -1080,6 +1105,7 @@ loadSiteConfig().then(() => {
// The free edition links to the online edition for Play Together and accounts.
if (!SITE.online && SITE.onlineUrl) { $('btn-online').href = SITE.onlineUrl; $('btn-online').classList.remove('hidden'); }
account.enabled = SITE.accounts;
+ if (SITE.online && SITE.insights) { insights.start('online'); $('btn-report').classList.remove('hidden'); }
$('btn-account').classList.toggle('hidden', !SITE.accounts);
if (SITE.accounts) account.refresh();
});
@@ -1094,8 +1120,8 @@ async function withLogin(fn) {
if (SITE.accounts && !(await account.refresh())) { renderTogether(); openAccount('login'); return; }
fn();
}
-$('tg-host').addEventListener('click', () => withLogin(() => { together.error = ''; together.host(); }));
-$('tg-join').addEventListener('click', () => withLogin(() => { together.error = ''; together.join($('tg-code').value); }));
+$('tg-host').addEventListener('click', () => (insights.step('Play Together: host'), withLogin(() => { together.error = ''; together.host(); })));
+$('tg-join').addEventListener('click', () => (insights.step('Play Together: join'), withLogin(() => { together.error = ''; together.join($('tg-code').value); })));
$('tg-login-btn').addEventListener('click', () => openAccount('login'));
$('tg-code').addEventListener('input', (e) => { e.target.value = e.target.value.toUpperCase().replace(/[^A-Z0-9]/g, ''); });
$('tg-code').addEventListener('keydown', (e) => { e.stopPropagation(); if (e.key === 'Enter') $('tg-join').click(); });
@@ -1179,6 +1205,7 @@ $('acc-form').addEventListener('submit', async (e) => {
$('acc-pass').value = ''; $('acc-pass2').value = '';
if (!r.ok) { $('acc-msg').textContent = accountMessage(r.error); return; }
$('acc-msg').textContent = '';
+ insights.event(accMode === 'new' ? 'account_register' : 'account_login');
toast(accMode === 'new' ? `๐ Welcome, ${r.username}! Your account is ready.` : `๐ Welcome back, ${r.username}!`);
closeAccount();
if (!$('together').classList.contains('hidden')) renderTogether();
@@ -1201,7 +1228,7 @@ $('acc-delete').addEventListener('click', async () => {
// Every pop-up panel gets a โ that is always on screen, and tapping the dimmed area
// outside a panel closes it too. (Phones have no Escape key, and on a small screen the
// Done button can be scrolled out of sight under a long list.)
-for (const [overlay, done] of [['inventory', 'inv-done'], ['craft', 'craft-done'], ['worlds', 'w-done'], ['trade', 'tr-done'], ['questbook', 'qb-done'], ['together', 'tg-close'], ['account', 'acc-done'], ['gate', 'gate-cancel'], ['photo', 'ph-close']]) {
+for (const [overlay, done] of [['inventory', 'inv-done'], ['craft', 'craft-done'], ['worlds', 'w-done'], ['trade', 'tr-done'], ['questbook', 'qb-done'], ['together', 'tg-close'], ['account', 'acc-done'], ['gate', 'gate-cancel'], ['photo', 'ph-close'], ['report', 'report-done']]) {
const ov = $(overlay);
const x = document.createElement('button');
x.type = 'button'; x.className = 'x-close'; x.textContent = 'โ'; x.setAttribute('aria-label', 'Close');
@@ -1224,6 +1251,23 @@ window.caches?.keys().then((keys) => {
if (v) $('game-version').textContent = `Version ${v}`;
}).catch(() => {});
+// ---------- Report a problem (online edition) ----------
+{
+ const box = $('report-choices');
+ for (const label of REPORTS) {
+ const b = document.createElement('button');
+ b.type = 'button'; b.className = 'wide-btn'; b.textContent = label;
+ b.addEventListener('click', () => {
+ insights.report(label);
+ $('report').classList.add('hidden');
+ toast('๐ Thanks! We got your report and will look into it.');
+ });
+ box.appendChild(b);
+ }
+}
+$('btn-report').addEventListener('click', () => { insights.where = state; $('report').classList.remove('hidden'); });
+$('report-done').addEventListener('click', () => $('report').classList.add('hidden'));
+
// ---------- today's building idea ----------
$('idea-text').textContent = ideaOfTheDay();
$('btn-idea').addEventListener('click', () => { $('idea-text').textContent = IDEAS[Math.floor(Math.random() * IDEAS.length)]; });
@@ -1231,6 +1275,7 @@ $('btn-idea').addEventListener('click', () => { $('idea-text').textContent = IDE
// ---------- worlds screen ----------
/** Switches to a saved world (saving the current one first). */
function openWorld(id) {
+ insights.step('opened a world');
const meta = worlds.get(id);
if (!meta) return;
if (together.isHost) { together.leave(); toast('Play Together ended (you switched worlds)'); }
@@ -1245,6 +1290,7 @@ function openWorld(id) {
}
function createWorld(name, seed, newMode, hardcore = false) {
+ insights.event('world_new');
const w = worlds.add({ name, seed: seed || String(Math.floor(Math.random() * 1e9)), mode: newMode, hardcore });
openWorld(w.id);
return w;
@@ -1368,7 +1414,7 @@ survival.onDeath = (reason) => {
$('death').classList.remove('hidden');
$('hud').classList.add('hidden');
touch?.setEnabled(false);
- document.exitPointerLock();
+ exitLock();
};
$('btn-respawn').addEventListener('click', () => {
survival.reset();
@@ -1769,6 +1815,7 @@ function placeBlock(item) {
world.flushDirty();
sfx.place(id);
quests.emit('place', { id: item, x: px, y: py, z: pz });
+ if (BLOCKS[id].spark) insights.event('circuit');
if (BLOCKS[id].spark) tip('spark', 'Spark circuits! Wire a Lever, Button, Plate or Battery to a Lamp, Door or Piston. Right-click a lever to flip it.');
return true;
}
@@ -1923,6 +1970,7 @@ function actRobot(now) {
/** Places Bit on the targeted face, facing the same way as the player. */
function placeRobot() {
+ insights.step('placed Bit');
const x = target.x + target.normal[0], y = target.y + target.normal[1], z = target.z + target.normal[2];
if (SOLID[world.getBlock(x, y, z)]) return false;
const fwd = [-Math.sin(player.yaw), -Math.cos(player.yaw)];
@@ -2218,6 +2266,8 @@ function trackMovement(dt, input, wasOnGround, dist) {
}
function frame(now, manual = false) {
+ // Ask for the next frame first, so one error can never stop the whole game.
+ if (!manual) requestAnimationFrame(frame);
const dt = Math.min(0.05, (now - last) / 1000);
last = now;
simTime += dt;
@@ -2318,9 +2368,9 @@ function frame(now, manual = false) {
particles.update(dt, light);
renderer.render(scene, camera);
+ insights.beat(now);
frames++;
if (now - fpsTime > 500) { fps = Math.round(frames * 1000 / (now - fpsTime)); frames = 0; fpsTime = now; updateDebug(pending); }
- if (!manual) requestAnimationFrame(frame);
}
window.addEventListener('resize', () => {
@@ -2418,7 +2468,7 @@ $('btn-install').addEventListener('click', () => {
// Expose for debugging in the console.
window.minicrafter = {
get world() { return world; }, get player() { return player; }, get target() { return target; },
- get inv() { return inv; }, adv, projectiles, spark, together, account, course, photo, openPhoto, closePhoto, get state() { return state; }, placeFacing, lightLevel, hurtPlayer, bow, gainXp, isAdventure, createWorld, history, tool, undoRedo, crops, waterAt, critters, findPortals, get fireflyTarget() { return fireflyTarget; }, worlds, get currentWorldId() { return currentWorldId; }, openWorld, get mobTarget() { return mobTarget; }, get robotTarget() { return robotTarget; }, survival, mobs, quests, robot, robotUI, keys, mouse, save, setMode,
+ get inv() { return inv; }, adv, projectiles, spark, together, account, course, photo, insights, openPhoto, closePhoto, get state() { return state; }, placeFacing, lightLevel, hurtPlayer, bow, gainXp, isAdventure, createWorld, history, tool, undoRedo, crops, waterAt, critters, findPortals, get fireflyTarget() { return fireflyTarget; }, worlds, get currentWorldId() { return currentWorldId; }, openWorld, get mobTarget() { return mobTarget; }, get robotTarget() { return robotTarget; }, survival, mobs, quests, robot, robotUI, keys, mouse, save, setMode,
select: (i) => select(i),
openOverlay: () => openOverlay(),
/** Dev/test helper: enter play mode without pointer lock (for automated testing). */
diff --git a/src/together.js b/src/together.js
index 0d8dc24..5be5ae1 100644
--- a/src/together.js
+++ b/src/together.js
@@ -35,7 +35,7 @@ export function saveProfile(p) { try { localStorage.setItem(PROFILE_KEY, JSON.st
// Online features (Play Together, and accounts later) only run on our own hosted site.
// ./site-config.json says whether they're on: the copy in Git (and so on GitHub Pages) says
// off, and tools/deploy-site.sh uploads an "on" version to our own site.
-export const SITE = { online: false, rooms: '', accounts: false, onlineUrl: '' };
+export const SITE = { online: false, rooms: '', accounts: false, insights: false, onlineUrl: '' };
const isDev = () => ['localhost', '127.0.0.1'].includes(location.hostname);
export async function loadSiteConfig() {
@@ -44,7 +44,7 @@ export async function loadSiteConfig() {
if (r.ok) {
const c = await r.json();
if (c && typeof c.onlineUrl === 'string' && /^https:\/\/[\w.-]+\/$/.test(c.onlineUrl)) SITE.onlineUrl = c.onlineUrl; // free edition: where the online one is
- if (c && c.online === true && typeof c.rooms === 'string' && /^\/[\w/-]*$/.test(c.rooms)) { SITE.online = true; SITE.rooms = c.rooms; SITE.accounts = c.accounts === true; }
+ if (c && c.online === true && typeof c.rooms === 'string' && /^\/[\w/-]*$/.test(c.rooms)) { SITE.online = true; SITE.rooms = c.rooms; SITE.accounts = c.accounts === true; SITE.insights = c.insights === true; }
}
} catch { /* offline or no config: free edition */ }
if (isDev() || new URLSearchParams(location.search).has('rooms')) SITE.online = true; // development and tests
diff --git a/stats.html b/stats.html
new file mode 100644
index 0000000..ce6f463
--- /dev/null
+++ b/stats.html
@@ -0,0 +1,85 @@
+
+
+
+
+
+
+ MiniCrafter insights
+
+
+
+
+
+
+ โ Back to the game
+ ๐ Insights
+ Anonymous daily counts and error reports from the online edition. No cookies, no player IDs, no IP addresses.
+
+
+
+
Period: Today Last 7 days Last 30 days Last 90 days
+
+
+
+
+
+
+
โจ Features used (sessions)
+
+
+
+
๐ Problems Crashes, freezes and "Report a problem" picks, grouped per day. Steps are the last things the player did before it happened.
+
+
+
+
+
diff --git a/style.css b/style.css
index 16ea852..96f5050 100644
--- a/style.css
+++ b/style.css
@@ -481,3 +481,9 @@ body.touch #quest-tracker { right: calc(max(10px, env(safe-area-inset-right)) +
.ph-stickers .chip { font-size: 1.2rem; padding: 2px 8px; }
#ph-caption-row { display: grid; gap: 4px; }
#ph-caption { font: inherit; padding: 8px 10px; border-radius: 6px; border: 2px solid #4b556b; background: #121622; color: #fff; user-select: text; -webkit-user-select: text; }
+
+/* Report a problem */
+.report-btn { background: #3a2b2b; border-color: #9a5a5a; }
+.report-panel { width: min(420px, 100%); }
+.report-choices { display: grid; gap: 6px; margin: 10px 0; }
+.report-choices .wide-btn { margin-top: 0; text-align: left; }
diff --git a/sw.js b/sw.js
index 963892a..fd980a0 100644
--- a/sw.js
+++ b/sw.js
@@ -1,6 +1,6 @@
// Service worker: caches the whole game so it works offline once loaded.
// Bump VERSION whenever files change so players get the update.
-const VERSION = 'minicrafter-v27';
+const VERSION = 'minicrafter-v29';
const CORE = [
'./', './index.html', './style.css', './privacy.html', './terms.html', './legal.css', './features.html', './features.css', './manifest.webmanifest', './site-config.json',
'./icons/icon-192.png', './icons/icon-512.png', './icons/icon-maskable-512.png', './icons/apple-touch-icon.png', './icons/favicon-32.png',
@@ -14,6 +14,7 @@ const CORE = [
'./src/account.js',
'./src/course.js',
'./src/photo.js',
+ './src/insights.js',
'./src/craftui.js',
'./src/critters.js',
'./src/ideas.js',
diff --git a/tests/smoke.mjs b/tests/smoke.mjs
index 29bafbf..e5602a8 100644
--- a/tests/smoke.mjs
+++ b/tests/smoke.mjs
@@ -23,6 +23,10 @@ const srcFiles = (await readdir(join(ROOT, 'src'))).filter((f) => f.endsWith('.j
const sw = await readFile(join(ROOT, 'sw.js'), 'utf8');
const missing = srcFiles.filter((f) => !sw.includes(`'./src/${f}'`));
ok(missing.length === 0, 'sw.js precaches every src/*.js file', missing.length ? `missing: ${missing.join(', ')}` : `${srcFiles.length} files`);
+// iPhones have no Pointer Lock API: a bare document.exitPointerLock() throws there (it froze Bit's panel).
+const bareLock = [];
+for (const f of srcFiles) for (const [i, line] of (await readFile(join(ROOT, 'src', f), 'utf8')).split('\n').entries()) if (/exitPointerLock\(\)/.test(line)) bareLock.push(`${f}:${i + 1}`);
+ok(bareLock.length === 0, 'no bare exitPointerLock() calls (iOS has no Pointer Lock)', bareLock.join(', ') || 'use exitLock()');
// ---------- tiny static server ----------
const server = http.createServer(async (req, res) => {
@@ -340,6 +344,19 @@ try {
});
ok(legal, 'privacy policy and terms pages are served (company, contact, version)');
ok(synced && back && noSave, 'play together: host lets a friend in, blocks sync both ways, guest never saves', code);
+ // Insights: the visit was counted on load, and a problem report arrives with its steps.
+ await host.page.evaluate(() => { const i = window.minicrafter.insights; i.step('smoke step'); i.error('smoke test error', 'smoke.mjs:1:1'); });
+ const insight = await (async () => {
+ for (let k = 0; k < 50; k++) {
+ const { counts, errors } = await dev.stats.summary(1);
+ const e = errors.find((x) => x.message === 'smoke test error');
+ if (e && counts.some((c) => c.key === 'visit')) return { e, visits: counts.find((c) => c.key === 'visit').n };
+ await new Promise((r) => setTimeout(r, 200));
+ }
+ return null;
+ })();
+ const statsLocked = (await fetch(`${dev.url}api/stats`)).status === 401;
+ ok(insight && insight.e.kind === 'error' && insight.e.steps.includes('smoke step') && statsLocked, 'insights: visits and problem reports (with steps) reach the server; stats need the key', insight ? `${insight.visits} visits` : 'nothing arrived');
ok(host.errors.length + guest.errors.length === 0, 'no console errors (online edition)', [...host.errors, ...guest.errors].slice(0, 3).join(' | '));
await host.page.close(); await guest.page.close();
} finally { dev.server.close(); }
@@ -370,6 +387,7 @@ try {
const m = window.minicrafter;
return m && m.world && [...m.world.chunks.values()].some((c) => c.meshed) ? m.world.chunks.size : 0;
}, null, { timeout: 30000 }).then((h) => h.jsonValue()).catch(() => 0);
+ ok(!(await s.page.evaluate(() => window.minicrafter.insights.enabled)), 'insights: off in the free edition (site-config.json in Git)');
ok(offline > 0 && offlineErrors.length === 0, 'game starts with no network (offline reload)', offlineErrors.slice(0, 3).join(' | ') || `${offline} chunks`);
await s.page.context().setOffline(false);
await s.page.close();
diff --git a/tools/deploy-site.sh b/tools/deploy-site.sh
index d3c8c12..61e9f41 100755
--- a/tools/deploy-site.sh
+++ b/tools/deploy-site.sh
@@ -6,6 +6,7 @@
# SITE_URL=https://example.com/ (the site's public address, with a trailing slash)
# It builds the site in a temporary folder (your checkout is never changed), then:
# - uploads an "on" site-config.json (the copy in Git keeps the online features off),
+# - includes stats.html, the insights page (it asks for STATS_TOKEN from the server's .env),
# - adds the site's address to features.html (canonical and social-sharing tags),
# - writes sitemap.xml and robots.txt for search engines.
set -euo pipefail
@@ -21,12 +22,12 @@ trap 'rm -rf "$BUILD"' EXIT
rsync -a \
--include='index.html' --include='style.css' --include='sw.js' --include='manifest.webmanifest' \
--include='privacy.html' --include='terms.html' --include='legal.css' \
- --include='features.html' --include='features.css' --include='llms.txt' \
+ --include='features.html' --include='features.css' --include='llms.txt' --include='stats.html' \
--include='icons/***' --include='src/***' --include='vendor/***' \
--include='docs/' --include='docs/screenshots/***' --exclude='*' \
./ "$BUILD/"
-printf '{ "online": true, "rooms": "/rooms", "accounts": true }\n' > "$BUILD/site-config.json"
+printf '{ "online": true, "rooms": "/rooms", "accounts": true, "insights": true }\n' > "$BUILD/site-config.json"
# Site-specific tags on the features page (absolute addresses for search engines and link previews).
META=" \n \n \n "
@@ -48,7 +49,7 @@ cat > "$BUILD/sitemap.xml" <${SITE_URL}terms.html ${TODAY} 0.3
EOF
-printf 'User-agent: *\nAllow: /\nDisallow: /api/\nDisallow: /rooms\nSitemap: %ssitemap.xml\n' "$SITE_URL" > "$BUILD/robots.txt"
+printf 'User-agent: *\nAllow: /\nDisallow: /api/\nDisallow: /rooms\nDisallow: /stats.html\nSitemap: %ssitemap.xml\n' "$SITE_URL" > "$BUILD/robots.txt"
rsync -az --delete "$BUILD/" "$DEPLOY_SSH:$DEPLOY_DIR/"
ssh "$DEPLOY_SSH" "chmod -R a+rX $DEPLOY_DIR"