@goosetools/goose-tools 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +98 -2
  2. package/bin/goose-tools.js +61 -0
  3. package/lib/check/src/agent.js +90 -0
  4. package/lib/check/src/analyze.js +311 -0
  5. package/lib/check/src/client.js +136 -0
  6. package/lib/check/src/copy.js +355 -0
  7. package/lib/check/src/fixes.js +153 -0
  8. package/lib/check/src/frame.js +92 -0
  9. package/lib/check/src/guard.js +441 -0
  10. package/lib/check/src/index.js +18 -0
  11. package/lib/check/src/mcp-http.js +169 -0
  12. package/lib/check/src/mcp.js +153 -0
  13. package/lib/check/src/scan.js +55 -0
  14. package/lib/check/src/stack.js +61 -0
  15. package/lib/check/src/tlds.js +3 -0
  16. package/lib/check/src/view.js +130 -0
  17. package/lib/check/src/worker.js +257 -0
  18. package/lib/engine/src/bots.js +146 -0
  19. package/lib/engine/src/directives.js +131 -0
  20. package/lib/engine/src/exposure.js +70 -0
  21. package/lib/engine/src/frontend.js +157 -0
  22. package/lib/engine/src/headers.js +76 -0
  23. package/lib/engine/src/hidden-text.js +425 -0
  24. package/lib/engine/src/html.js +794 -0
  25. package/lib/engine/src/index.js +20 -0
  26. package/lib/engine/src/php.js +316 -0
  27. package/lib/engine/src/policies.js +234 -0
  28. package/lib/engine/src/reach.js +199 -0
  29. package/lib/engine/src/robots.js +275 -0
  30. package/lib/engine/src/secrets.js +142 -0
  31. package/lib/engine/src/signals.js +144 -0
  32. package/lib/rules/data/bots.json.js +1 -0
  33. package/lib/rules/data/exposure.json.js +1 -0
  34. package/lib/rules/data/frontend.json.js +1 -0
  35. package/lib/rules/data/headers.json.js +1 -0
  36. package/lib/rules/data/secrets.json.js +1 -0
  37. package/lib/ui/LICENSE-Inter.txt +93 -0
  38. package/lib/ui/assets.js +5 -0
  39. package/package.json +37 -4
  40. package/src/local.js +61 -0
  41. package/src/mcp.js +61 -0
  42. package/src/setup.js +395 -0
  43. package/src/site/auth.js +287 -0
  44. package/src/site/beacon.js +462 -0
  45. package/src/site/collect.js +484 -0
  46. package/src/site/handler.js +405 -0
  47. package/src/site/index.js +88 -0
  48. package/src/site/limits.js +48 -0
  49. package/src/site/pages.js +75 -0
  50. package/src/site/qr.js +318 -0
  51. package/src/site/reports.js +1117 -0
  52. package/src/site/source.js +68 -0
  53. package/src/site/store-pg.js +225 -0
  54. package/src/site/store.js +249 -0
@@ -0,0 +1,484 @@
1
+ // The beacon route (POST /_gt/e): one page view becomes one upsert of its day's totals. A port of the WordPress
2
+ // plugin's request checks and field rules (goose-tools/includes/src/Insights/Collector.php, Payload.php, Bots.php,
3
+ // Country.php, and Speed/Collector.php, Payload.php, Kinds.php, Metrics.php), without its buffer: the plugin appends
4
+ // lines to a file and merges them each minute (Insights\Buffer, Aggregate); here the counts are added on arrival.
5
+ //
6
+ // Never read here: the IP address, cookie values, and any field the script does not send. The user agent is read for
7
+ // the bot check only and never stored. Cookie names are read only to leave out the owner's own views.
8
+ //
9
+ // Rows added for one view (store.add(day, rows), day in UTC):
10
+ // page <path> views of the page
11
+ // continued <path> views the page sent on to another page of the site (the view's r)
12
+ // source <kind>|<name> where the view came from (source.js; internal and direct have no name)
13
+ // country <code> '' when unknown
14
+ // device mobile|tablet|desktop
15
+ // hour <0-23> the hour (UTC) the view arrived
16
+ // and, when the view carries speed measures:
17
+ // speed <page kind>|<path> measured views of the page
18
+ // speed.<measure>.<rating> <path> good, ni or poor views per measure (lcp, inp, cls, ttfb)
19
+ // speed.hist <page kind>|<measure>|<bucket> histogram of each measure per page kind (Metrics.EDGES)
20
+ // speed.element <page kind>|<type> LCP element types (img, text, video)
21
+ // ttfb.ms <path>, ttfb.n <path> time to first byte, summed, and the views that measured it
22
+ // and, when it also carries the attribution fields (spec/standalone-deep-dives.md; Chrome and Edge name scripts):
23
+ // speed.named 1|0 views whose browser could name scripts, and views whose browser could not
24
+ // script.ms <address>, script.views <address> script time in long frames, and the views it ran in
25
+ // script.inp <address> views where it ran in the tap or click that set INP
26
+ // load.lcp <page kind>, load.n <page kind> LCP time, summed, and the views that measured it
27
+ // load.ms <page kind>|<address> time before LCP taken by each file, host, 'inline' script or 'html'
28
+ // call.ms <address>, call.n <address> data call time, summed, and the number of calls
29
+ import { classify } from './source.js';
30
+ import { today, COUNTED, CAP } from './limits.js';
31
+ import { cookieName } from './auth.js';
32
+
33
+ /* ------------------------------------------------------------------ Field rules (Insights/Payload.php) */
34
+
35
+ /**
36
+ * Largest request body accepted, in bytes. Insights\Payload::MAX_BYTES is 1024 for the insights fields; one beacon
37
+ * here also carries the speed fields and up to 21 attribution entries of at most 120 characters each
38
+ * (spec/standalone-deep-dives.md section 3).
39
+ */
40
+ export const MAX_BYTES = 4096;
41
+ /** Longest page path kept. */
42
+ export const MAX_PATH = 191;
43
+ /** Longest referrer host kept. */
44
+ export const MAX_HOST = 191;
45
+ /** Longest campaign source kept. */
46
+ export const MAX_SOURCE = 64;
47
+ /** Screen classes the script sends, and their stored names. */
48
+ export const DEVICES = { m: 'mobile', t: 'tablet', d: 'desktop' };
49
+
50
+ /**
51
+ * A URL path as the browser reports it (percent-encoded ASCII), or '' when malformed or too long.
52
+ * @param {unknown} v
53
+ */
54
+ export function path(v) {
55
+ if (typeof v !== 'string' || v.length > MAX_PATH) return '';
56
+ return /^\/[A-Za-z0-9\-._~!$&'()*+,;=:@%/[\]|^]*$/.test(v) ? v : '';
57
+ }
58
+
59
+ /**
60
+ * A host name in lower case, or '' when malformed or too long. No ports, no user info.
61
+ * @param {unknown} v
62
+ */
63
+ export function host(v) {
64
+ if (typeof v !== 'string' || v.length > MAX_HOST) return '';
65
+ v = v.toLowerCase();
66
+ return /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*$/.test(v) ? v : '';
67
+ }
68
+
69
+ /**
70
+ * A campaign source (utm_source) in lower case with spaces as dashes, or '' when missing or not a plain tag. Values
71
+ * with other characters (an email address, for example) are dropped.
72
+ * @param {unknown} v
73
+ */
74
+ export function source(v) {
75
+ if (typeof v !== 'string' || v.length > 4 * MAX_SOURCE) return '';
76
+ v = v.trim().toLowerCase().replace(/\s+/g, '-');
77
+ if (v.length > MAX_SOURCE) return '';
78
+ return /^[a-z0-9][a-z0-9._~+-]*$/.test(v) ? v : '';
79
+ }
80
+
81
+ /**
82
+ * A two-character country code, or '' (unknown). "XX" means the host did not know the country; "T1" is Tor and is
83
+ * kept as Cloudflare reports it.
84
+ * @param {unknown} v
85
+ */
86
+ export function country(v) {
87
+ if (typeof v !== 'string') return '';
88
+ v = v.trim().toUpperCase();
89
+ return v !== 'XX' && /^[A-Z][A-Z0-9]$/.test(v) ? v : '';
90
+ }
91
+
92
+ /**
93
+ * A page view from the script's fields, or null when any field is malformed (Insights\Payload::hit()). A malformed
94
+ * utm_source is dropped rather than rejecting the view, since campaign tags are free text.
95
+ * @param {Record<string, string>} f
96
+ * @returns {{p: string, r: string, h: string, s: string, d: string} | null}
97
+ */
98
+ export function hit(f) {
99
+ const p = path(f.p);
100
+ const d = typeof f.d === 'string' && Object.hasOwn(DEVICES, f.d) ? f.d : '';
101
+ if (p === '' || d === '') return null;
102
+ let r = '';
103
+ if (f.r !== undefined && f.r !== '') {
104
+ r = path(f.r);
105
+ if (r === '') return null;
106
+ }
107
+ let h = '';
108
+ if (f.h !== undefined && f.h !== '') {
109
+ h = host(f.h);
110
+ if (h === '') return null;
111
+ }
112
+ if (r !== '' && h !== '') return null; // A view has one referrer: this site or another one.
113
+ return { p, r, h, s: source(f.s ?? ''), d };
114
+ }
115
+
116
+ /* ------------------------------------------------------------------ Measures (Speed/Metrics.php, Kinds.php) */
117
+
118
+ /** Page kinds, in report order (Speed\Kinds::ALL). */
119
+ export const PAGE_KINDS = ['home', 'product', 'category', 'post', 'page', 'cart', 'other'];
120
+ /** Every measure, in report order. TTFB is measured too, but is not a Core Web Vital. */
121
+ export const METRICS = ['lcp', 'inp', 'cls', 'ttfb'];
122
+ export const CORE = ['lcp', 'inp', 'cls'];
123
+ export const RATINGS = ['good', 'ni', 'poor'];
124
+ /** Good up to the first value, needs improvement up to the second, poor above it (web.dev). */
125
+ export const THRESHOLDS = { lcp: [2500, 4000], inp: [200, 500], cls: [100, 250], ttfb: [800, 1800] };
126
+ /** Histogram bucket upper edges (inclusive); one more bucket holds values above the last edge. */
127
+ export const EDGES = {
128
+ lcp: [250, 500, 750, 1000, 1250, 1500, 1750, 2000, 2250, 2500, 2750, 3000, 3500, 4000, 5000, 6000, 8000, 10000, 15000, 20000, 30000],
129
+ inp: [25, 50, 75, 100, 125, 150, 175, 200, 250, 300, 350, 400, 450, 500, 600, 800, 1000, 1500, 2000, 3000, 5000],
130
+ cls: [10, 25, 50, 75, 100, 125, 150, 200, 250, 300, 400, 500, 750, 1000, 1500, 2000, 3000],
131
+ ttfb: [100, 200, 300, 400, 500, 600, 700, 800, 1000, 1200, 1400, 1600, 1800, 2200, 2600, 3000, 4000, 6000, 10000],
132
+ };
133
+ /** Largest value accepted per measure. Larger values come from a broken clock or a page left open for hours. */
134
+ export const MAX = { lcp: 120000, inp: 60000, cls: 100000, ttfb: 120000 };
135
+ /** Fields the script sends for each measure (Speed\Payload::FIELDS). */
136
+ export const FIELDS = { l: 'lcp', i: 'inp', c: 'cls', t: 'ttfb' };
137
+ /** Types of LCP element the script sends. */
138
+ export const ELEMENTS = ['img', 'text', 'video'];
139
+
140
+ /**
141
+ * Rating of one value: good, ni or poor. A value exactly on a threshold counts on the better side.
142
+ * @param {string} metric
143
+ * @param {number} value
144
+ */
145
+ export function rate(metric, value) {
146
+ const [good, poor] = THRESHOLDS[metric];
147
+ if (value <= good) return 'good';
148
+ return value <= poor ? 'ni' : 'poor';
149
+ }
150
+
151
+ /**
152
+ * Histogram bucket of a value: 0 to EDGES[metric].length.
153
+ * @param {string} metric
154
+ * @param {number} value
155
+ */
156
+ export function bucket(metric, value) {
157
+ const edges = EDGES[metric];
158
+ for (let i = 0; i < edges.length; i++) if (value <= edges[i]) return i;
159
+ return edges.length;
160
+ }
161
+
162
+ /**
163
+ * A whole number from 0 to max, sent as decimal digits, or null (Speed\Payload::number()).
164
+ * @param {unknown} v
165
+ * @param {number} max
166
+ */
167
+ export function number(v, max) {
168
+ if (typeof v !== 'string' || !/^(?:0|[1-9][0-9]{0,8})$/.test(v)) return null;
169
+ const n = Number(v);
170
+ return n <= max ? n : null;
171
+ }
172
+
173
+ /**
174
+ * The page kind when the script tag names none. The plugin decides it from WordPress's conditional tags
175
+ * (Speed\Kinds::of()); a site without them has only its path: the front page is home, anything else a page.
176
+ * @param {string} p
177
+ */
178
+ export function defaultKind(p) {
179
+ return p === '/' ? 'home' : 'page';
180
+ }
181
+
182
+ /**
183
+ * A view's measures from the script's fields, or null when there are none or any is malformed (Speed\Payload::view()).
184
+ * k (page kind) is optional here and defaults to defaultKind(); a k that is sent must be a kind.
185
+ * @param {Record<string, string>} f
186
+ * @param {string} p The view's valid path.
187
+ * @returns {{k: string, m: Record<string, number>, e: string} | null}
188
+ */
189
+ export function measures(f, p) {
190
+ let k = defaultKind(p);
191
+ if (f.k !== undefined && f.k !== '') {
192
+ if (!PAGE_KINDS.includes(f.k)) return null;
193
+ k = f.k;
194
+ }
195
+ /** @type {Record<string, number>} */
196
+ const m = {};
197
+ for (const [field, metric] of Object.entries(FIELDS)) {
198
+ if (f[field] === undefined || f[field] === '') continue;
199
+ const v = number(f[field], MAX[metric]);
200
+ if (v === null) return null;
201
+ m[metric] = v;
202
+ }
203
+ if (!Object.keys(m).length) return null;
204
+ let e = '';
205
+ if (f.e !== undefined && f.e !== '') {
206
+ if (!ELEMENTS.includes(f.e) || m.lcp === undefined) return null;
207
+ e = f.e;
208
+ }
209
+ return { k, m, e };
210
+ }
211
+
212
+ /* ------------------------------------------------------------------ Attribution (spec/standalone-deep-dives.md) */
213
+
214
+ /** Most entries of each attribution field: slow scripts, scripts in the slowest tap, files before LCP, data calls. */
215
+ export const MOST = { 's[]': 6, 'x[]': 3, 'f[]': 6, 'q[]': 6 };
216
+ /** Longest address. */
217
+ export const MAX_ADDRESS = 120;
218
+ /** Largest time in one entry, ms. */
219
+ export const MAX_MS = 60000;
220
+ /** Most calls to one address in one entry. */
221
+ export const MAX_CALLS = 10000;
222
+
223
+ /**
224
+ * An address as the script sends it: a path on this site, //host or //host/path elsewhere, 'inline' (code in the page
225
+ * itself) or, for load time only, 'html' (waiting for the page's HTML). No query string, no hash, no spaces.
226
+ * @param {string} v
227
+ * @param {boolean} [html]
228
+ */
229
+ export function address(v, html = false) {
230
+ if (v.length > MAX_ADDRESS) return false;
231
+ if (v === 'inline' || (html && v === 'html')) return true;
232
+ if (v.startsWith('//')) {
233
+ const i = v.indexOf('/', 2);
234
+ if (!host(i < 0 ? v.slice(2) : v.slice(2, i))) return false;
235
+ return i < 0 || path(v.slice(i)) !== '';
236
+ }
237
+ return path(v) !== '';
238
+ }
239
+
240
+ /**
241
+ * Entries "<ms> <address>", or "<ms> <calls> <address>" for data calls, as [ms, calls, address]; null when any is
242
+ * malformed, out of range, repeated or past the most allowed.
243
+ * @param {string[]} list
244
+ * @param {string} field
245
+ */
246
+ function entries(list, field) {
247
+ if (list.length > MOST[field]) return null;
248
+ const calls = field === 'q[]';
249
+ const seen = new Set();
250
+ const out = [];
251
+ for (const e of list) {
252
+ const parts = e.split(' ');
253
+ if (parts.length !== (calls ? 3 : 2)) return null;
254
+ const ms = number(parts[0], MAX_MS);
255
+ const n = calls ? number(parts[1], MAX_CALLS) : 1;
256
+ const a = parts[parts.length - 1];
257
+ if (ms === null || n === null || n < 1 || seen.has(a) || !address(a, field === 'f[]')) return null;
258
+ seen.add(a);
259
+ out.push(/** @type {[number, number, string]} */ ([ms, n, a]));
260
+ }
261
+ return out;
262
+ }
263
+
264
+ /**
265
+ * The attribution rows of a view with speed measures, or [] when it sends none or any field fails its rules: then
266
+ * every attribution field is dropped, and the view and its speed still count.
267
+ * @param {URLSearchParams} q
268
+ * @param {{k: string, m: Record<string, number>}} v
269
+ * @returns {[string, string, number][]}
270
+ */
271
+ export function attribution(q, v) {
272
+ const named = q.get('a');
273
+ if (named === null) return [];
274
+ if (named !== '1' && named !== '0') return [];
275
+ /** @type {Record<string, [number, number, string][]>} */
276
+ const got = {};
277
+ for (const field of Object.keys(MOST)) {
278
+ const list = entries(q.getAll(field), field);
279
+ if (!list) return [];
280
+ got[field] = list;
281
+ }
282
+ // Scripts are named only by a browser that can (a=1); files and calls are timed in every browser.
283
+ if (named === '0' && (got['s[]'].length || got['x[]'].length)) return [];
284
+ if (got['f[]'].length && v.m.lcp === undefined) return [];
285
+ // The parts add up to the LCP time at most; each was rounded on its own.
286
+ if (got['f[]'].reduce((t, [ms]) => t + ms, 0) > (v.m.lcp ?? 0) + MOST['f[]']) return [];
287
+ /** @type {[string, string, number][]} */
288
+ const rows = [['speed.named', named, 1]];
289
+ for (const [ms, , a] of got['s[]']) rows.push(['script.ms', a, ms], ['script.views', a, 1]);
290
+ for (const [, , a] of got['x[]']) rows.push(['script.inp', a, 1]);
291
+ if (v.m.lcp !== undefined) rows.push(['load.lcp', v.k, v.m.lcp], ['load.n', v.k, 1]);
292
+ for (const [ms, , a] of got['f[]']) rows.push(['load.ms', `${v.k}|${a}`, ms]);
293
+ for (const [ms, n, a] of got['q[]']) rows.push(['call.ms', a, ms], ['call.n', a, n]);
294
+ return rows;
295
+ }
296
+
297
+ /* ------------------------------------------------------------------ Bots (Insights/Bots.php) */
298
+
299
+ /**
300
+ * User agent words that mark crawlers, monitors, previews, test browsers and HTTP libraries. "bot" is not matched
301
+ * inside "cubot", a phone brand.
302
+ */
303
+ export const BOT_UA = /(?<!cu)bot|crawl|spider|slurp|scrap|seo|lighthouse|pagespeed|gtmetrix|headless|phantom|puppeteer|playwright|selenium|webdriver|prerender|preview|facebookexternalhit|embedly|chatgpt-user|perplexity-user|claude-user|google-|googleother|mediapartners|feedfetcher|ia_archiver|python|curl|wget|httpie|go-http|okhttp|node-fetch|undici|axios|java\/|libwww|http[-_]?client|guzzle|monitor|uptime|pingdom|statuscake|validator|scanner|archiver/i;
304
+
305
+ /**
306
+ * Whether a user agent belongs to a bot. An empty user agent counts as a bot.
307
+ * @param {unknown} ua
308
+ */
309
+ export function isBot(ua) {
310
+ if (typeof ua !== 'string' || ua.trim() === '') return true;
311
+ return BOT_UA.test(ua);
312
+ }
313
+
314
+ /**
315
+ * Why the request headers show this is not a page view from the script: 'prefetch', 'navigate' (someone opened the
316
+ * endpoint URL), 'cross_site' (sent from another site), or '' when nothing is wrong. Sites are compared with the
317
+ * browser's Sec-Fetch-Site header, not Origin against Host, because a proxy in front of the site can change Host.
318
+ * @param {Headers} headers
319
+ */
320
+ export function requestProblem(headers) {
321
+ for (const name of ['sec-purpose', 'purpose', 'x-purpose', 'x-moz']) {
322
+ const v = headers.get(name);
323
+ if (v !== null && v.toLowerCase().includes('prefetch')) return 'prefetch';
324
+ }
325
+ if (headers.get('sec-fetch-mode') === 'navigate') return 'navigate';
326
+ if (headers.get('sec-fetch-site') === 'cross-site') return 'cross_site';
327
+ return '';
328
+ }
329
+
330
+ /* ------------------------------------------------------------------ Country (Insights/Country.php) */
331
+
332
+ /**
333
+ * The visitor's country from the host's header, or '' (unknown): Cloudflare's CF-IPCountry, then Vercel's
334
+ * X-Vercel-IP-Country. The plugin believes CF-IPCountry only when the connection comes from Cloudflare's address
335
+ * ranges; a web Request carries no connecting address, so here the header is taken as the host sent it. A forged
336
+ * header can only move a count between countries, and the value must still be a two-character code.
337
+ * @param {Headers} headers
338
+ */
339
+ export function countryFrom(headers) {
340
+ for (const name of ['cf-ipcountry', 'x-vercel-ip-country']) {
341
+ const c = country(headers.get(name));
342
+ if (c) return c;
343
+ }
344
+ return '';
345
+ }
346
+
347
+ /* ------------------------------------------------------------------ Requests (Insights/Collector.php) */
348
+
349
+ /**
350
+ * Names of the cookies sent with a request. Values are never read.
351
+ * @param {Headers} headers
352
+ */
353
+ function cookieNames(headers) {
354
+ const raw = headers.get('cookie');
355
+ if (!raw) return [];
356
+ return raw.split(';').map((c) => c.split('=')[0].trim()).filter(Boolean);
357
+ }
358
+
359
+ /**
360
+ * What to do with one beacon (the plugin's Collector::handle(), for the insights and speed fields at once).
361
+ * @param {string} body Raw request body, at most MAX_BYTES.
362
+ * @param {Headers} headers
363
+ * @param {number} now Milliseconds.
364
+ * @param {string} [signedIn] Name of the dashboard's session cookie.
365
+ * @returns {{action: 'count', day: string, rows: ([string, string] | [string, string, number])[]} | {action: 'drop', reason: string}}
366
+ */
367
+ export function handle(body, headers, now, signedIn = '') {
368
+ const problem = requestProblem(headers);
369
+ if (problem) return drop(problem);
370
+ if (isBot(headers.get('user-agent'))) return drop('bot');
371
+ if (signedIn && cookieNames(headers).includes(signedIn)) return drop('signed_in');
372
+ /** @type {Record<string, string>} */
373
+ const f = {};
374
+ const q = new URLSearchParams(body);
375
+ for (const [k, v] of q) f[k] = v; // The last value of a field wins, as in PHP.
376
+ const h = hit(f);
377
+ if (!h) return drop('invalid');
378
+ const [kind, name] = classify({ internal: h.r !== '', host: h.h, utm: h.s });
379
+ /** @type {([string, string] | [string, string, number])[]} */
380
+ const rows = [['page', h.p]];
381
+ if (h.r) rows.push(['continued', h.r]);
382
+ rows.push(['source', `${kind}|${name}`], ['country', countryFrom(headers)], ['device', DEVICES[h.d]], ['hour', String(new Date(now).getUTCHours())]);
383
+ // Speed: measures that fail their rules leave the page view counted, as the plugin's two beacons were apart.
384
+ const v = measures(f, h.p);
385
+ if (v) {
386
+ rows.push(['speed', `${v.k}|${h.p}`]);
387
+ for (const [metric, value] of Object.entries(v.m)) {
388
+ rows.push([`speed.${metric}.${rate(metric, value)}`, h.p], ['speed.hist', `${v.k}|${metric}|${bucket(metric, value)}`]);
389
+ }
390
+ if (v.e) rows.push(['speed.element', `${v.k}|${v.e}`]);
391
+ if (v.m.ttfb !== undefined) rows.push(['ttfb.ms', h.p, v.m.ttfb], ['ttfb.n', h.p, 1]);
392
+ rows.push(...attribution(q, v));
393
+ }
394
+ return { action: 'count', day: today(now), rows };
395
+ }
396
+
397
+ /** @param {string} reason */
398
+ function drop(reason) {
399
+ return /** @type {const} */ ({ action: 'drop', reason });
400
+ }
401
+
402
+ /**
403
+ * The request body as text, or null when it is longer than max bytes. Reads at most max + 1 bytes.
404
+ * @param {Request} request
405
+ * @param {number} max
406
+ */
407
+ export async function readBody(request, max) {
408
+ if (!request.body) return '';
409
+ const reader = request.body.getReader();
410
+ const chunks = [];
411
+ let size = 0;
412
+ for (;;) {
413
+ const { done, value } = await reader.read();
414
+ if (done) break;
415
+ size += value.byteLength;
416
+ if (size > max) {
417
+ reader.cancel().catch(() => {});
418
+ return null;
419
+ }
420
+ chunks.push(value);
421
+ }
422
+ const all = new Uint8Array(size);
423
+ let at = 0;
424
+ for (const c of chunks) {
425
+ all.set(c, at);
426
+ at += c.byteLength;
427
+ }
428
+ return new TextDecoder().decode(all);
429
+ }
430
+
431
+ /** @param {number} status @param {Record<string, string>} [more] */
432
+ const reply = (status, more = {}) => new Response(null, { status, headers: { 'cache-control': 'no-store', ...more } });
433
+
434
+ /** How long a page view's write may take before it is dropped (spec/standalone-database.md section 7). */
435
+ export const WRITE_MS = 2000;
436
+
437
+ /**
438
+ * The promise's value, or null after WRITE_MS. Its error is never thrown, so a late failure is not unhandled.
439
+ * @template T @param {Promise<T>} p @returns {Promise<T | null>}
440
+ */
441
+ export async function within(p) {
442
+ p.catch(() => {});
443
+ /** @type {any} */
444
+ let timer;
445
+ try {
446
+ return await Promise.race([p, new Promise((resolve) => (timer = setTimeout(() => resolve(null), WRITE_MS)).unref?.())]);
447
+ } catch {
448
+ return null;
449
+ } finally {
450
+ clearTimeout(timer);
451
+ }
452
+ }
453
+
454
+ /**
455
+ * The /_gt/e route: 204 when the view is counted or silently dropped, 413 over MAX_BYTES, 405 for anything but POST.
456
+ * Fails open: an error while reading or counting still answers 204, so the page never sees it.
457
+ * @param {Request} request
458
+ * @param {{add: (day: string, rows: any[]) => number | Promise<number>}} store From openStore() or openPgStore().
459
+ * @param {{now?: number, cap?: number, counted?: (n: number, day: string) => boolean}} [options] With `cap`, the view
460
+ * also counts toward the day's cap. Once the count reaches it, `counted` hears it and returns true the first time
461
+ * this process sees it, and the cap is written for the day (spec/standalone-database.md section 5).
462
+ */
463
+ export async function collect(request, store, { now = Date.now(), cap = 0, counted } = {}) {
464
+ if (request.method !== 'POST') return reply(405, { allow: 'POST' });
465
+ if ((parseInt(request.headers.get('content-length') ?? '', 10) || 0) > MAX_BYTES) return reply(413);
466
+ try {
467
+ const body = await readBody(request, MAX_BYTES);
468
+ if (body === null) return reply(413);
469
+ let signedIn = '';
470
+ try {
471
+ signedIn = cookieName(new URL(request.url));
472
+ } catch {}
473
+ const r = handle(body, request.headers, now, signedIn);
474
+ if (r.action === 'count') {
475
+ if (cap) r.rows.push([COUNTED, 'all', 1]);
476
+ // A database that is down or slow cannot keep the function running: 2 seconds at most, then the view is dropped.
477
+ const n = await within(Promise.resolve(store.add(r.day, r.rows)));
478
+ if (cap && typeof n === 'number' && n >= cap && counted?.(n, r.day)) await within(Promise.resolve(store.add(r.day, [[CAP, String(cap), 1]])));
479
+ }
480
+ } catch {
481
+ // Counting is never worth an error on the site.
482
+ }
483
+ return reply(204);
484
+ }