tallymark 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 (68) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +234 -2
  3. package/SECURITY.md +37 -0
  4. package/dist/cli.d.ts +2 -0
  5. package/dist/cli.js +124 -0
  6. package/dist/cloudflare.d.ts +9 -0
  7. package/dist/cloudflare.js +53 -0
  8. package/dist/hit.d.ts +83 -0
  9. package/dist/hit.js +301 -0
  10. package/dist/http.d.ts +36 -0
  11. package/dist/http.js +393 -0
  12. package/dist/index.d.ts +7 -0
  13. package/dist/index.js +4 -0
  14. package/dist/node.d.ts +40 -0
  15. package/dist/node.js +66 -0
  16. package/dist/query.d.ts +31 -0
  17. package/dist/query.js +699 -0
  18. package/dist/react.d.ts +27 -0
  19. package/dist/react.js +34 -0
  20. package/dist/script.d.ts +17 -0
  21. package/dist/script.js +147 -0
  22. package/dist/stores.d.ts +129 -0
  23. package/dist/stores.js +393 -0
  24. package/dist/tallymark.d.ts +49 -0
  25. package/dist/tallymark.js +265 -0
  26. package/dist/types.d.ts +306 -0
  27. package/dist/types.js +1 -0
  28. package/dist/vercel.d.ts +33 -0
  29. package/dist/vercel.js +36 -0
  30. package/dist/webhook.d.ts +27 -0
  31. package/dist/webhook.js +61 -0
  32. package/docs/DEPLOYMENT.md +155 -0
  33. package/docs/HOW_IT_WORKS.md +106 -0
  34. package/docs/USAGE.md +237 -0
  35. package/examples/README.md +39 -0
  36. package/examples/browser/index.html +32 -0
  37. package/examples/browser/server.ts +34 -0
  38. package/examples/events/index.html +89 -0
  39. package/examples/events/server.ts +101 -0
  40. package/examples/frameworks/astro/[...path].ts +21 -0
  41. package/examples/frameworks/bun.ts +23 -0
  42. package/examples/frameworks/cloudflare.ts +37 -0
  43. package/examples/frameworks/deno.ts +26 -0
  44. package/examples/frameworks/express.ts +57 -0
  45. package/examples/frameworks/hono.ts +38 -0
  46. package/examples/frameworks/nextjs/app/api/analytics/[...route]/route.ts +7 -0
  47. package/examples/frameworks/nextjs/app/api/analytics-cron/route.ts +6 -0
  48. package/examples/frameworks/nextjs/app/layout.tsx +15 -0
  49. package/examples/frameworks/nextjs/app/page.tsx +21 -0
  50. package/examples/frameworks/nextjs/lib/analytics.ts +14 -0
  51. package/examples/frameworks/nextjs/vercel.json +3 -0
  52. package/examples/frameworks/react/main.tsx +32 -0
  53. package/examples/frameworks/sveltekit/+server.ts +26 -0
  54. package/examples/frameworks/vercel/api/analytics-cron.ts +9 -0
  55. package/examples/frameworks/vercel/api/analytics.ts +22 -0
  56. package/examples/frameworks/vercel/vercel.json +4 -0
  57. package/examples/http/Java.java +74 -0
  58. package/examples/http/curl.sh +46 -0
  59. package/examples/http/go.go +93 -0
  60. package/examples/http/php.php +74 -0
  61. package/examples/http/python.py +62 -0
  62. package/examples/http/ruby.rb +60 -0
  63. package/examples/library/basic.ts +95 -0
  64. package/examples/library/reports.ts +136 -0
  65. package/examples/library/stores.ts +57 -0
  66. package/examples/library/webhook-receiver.ts +30 -0
  67. package/llms.txt +235 -0
  68. package/package.json +116 -4
package/README.md CHANGED
@@ -1,3 +1,235 @@
1
- # Temporary Holding Version
1
+ <div align="center">
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ <picture>
4
+ <source media="(prefers-color-scheme: dark)" srcset="./assets/logo-dark.svg">
5
+ <img alt="tallymark" src="./assets/logo-light.svg" width="420">
6
+ </picture>
7
+
8
+ **Count your visitors, not your visitors' data.**
9
+ <!--
10
+ A cookie banner means the analytics follows people.<br>
11
+ Tallymark is a library that counts the visit and forgets the person.<br>
12
+ At midnight UTC the same person becomes a different hash, so nobody can follow them into tomorrow.
13
+
14
+ It is not a dashboard, not a hosted service, and not a record of who someone is. -->
15
+
16
+ <br>
17
+
18
+ [![CI](https://github.com/whoisjayd/tallymark/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/whoisjayd/tallymark/actions/workflows/ci.yml)
19
+ [![License](https://img.shields.io/badge/license-AGPL--3.0-blue?style=flat-square)](./LICENSE)
20
+ [![TypeScript](https://img.shields.io/badge/TypeScript-strict-3178C6?style=flat-square&logo=typescript&logoColor=white)](https://www.typescriptlang.org/)
21
+ [![Dependencies](https://img.shields.io/badge/dependencies-zero-f97316?style=flat-square)](./package.json)
22
+
23
+ <br>
24
+
25
+ [Quick start](#quick-start) · [Why a library](#why-a-library) · [How it works](#how-it-works) · [Reports](#what-you-can-ask) · [Storage](#storage) · [Docs](#documentation)
26
+
27
+ <br>
28
+
29
+ <img alt="Launch film. The tally closes, then the script tag, the daily hash, the runtimes, and the stores." src="./assets/launch.gif" width="880">
30
+
31
+ </div>
32
+
33
+ <br>
34
+
35
+ ## Quick start
36
+
37
+ ```bash
38
+ bun add tallymark # or: npm i tallymark · pnpm add tallymark
39
+ ```
40
+
41
+ The same engine runs three ways.
42
+
43
+ ### A script tag
44
+
45
+ ```bash
46
+ TALLYMARK_SECRET=$(openssl rand -hex 32) TALLYMARK_API_KEY=$(openssl rand -hex 24) bunx tallymark
47
+ ```
48
+
49
+ ```html
50
+ <script defer src="http://localhost:3000/script.js" data-localhost="true"></script>
51
+ ```
52
+
53
+ ```bash
54
+ curl -H "Authorization: Bearer $TALLYMARK_API_KEY" "http://localhost:3000/api/summary?range=24h"
55
+ ```
56
+
57
+ The same server is a Cloudflare Worker or a Vercel function. See [Deploy](./docs/DEPLOYMENT.md).
58
+
59
+ ### Your own code
60
+
61
+ No server and no database. `trackRequest()` reads the IP, browser, language and location from the request.
62
+
63
+ ```ts
64
+ import { createTallymark } from 'tallymark'
65
+
66
+ const tm = createTallymark({ secret: process.env.SECRET })
67
+
68
+ await tm.trackRequest(request, { name: 'Signup', props: { plan: 'pro' }, value: 49 })
69
+
70
+ await tm.summary('7d')
71
+ await tm.top('country', '7d')
72
+ await tm.top('channel', '7d')
73
+ await tm.sessions('24h')
74
+ ```
75
+
76
+ ### Any language
77
+
78
+ `POST /collect` and `GET /api/summary` are plain HTTP. Python, Go, PHP, Ruby, Java and curl are in [examples/http](./examples/http). Next.js, Vercel, Express, Hono, SvelteKit, Astro, Cloudflare Workers, Bun, Deno and React are in [examples/frameworks](./examples/frameworks).
79
+
80
+ ## Why a library
81
+
82
+ Plausible and Fathom you rent. Umami and Plausible CE you deploy. This one is a dependency of the app you already have, it uses the database you already run, and the answers are typed values. See [limits](./docs/HOW_IT_WORKS.md#limits).
83
+
84
+ ## How it works
85
+
86
+ ```mermaid
87
+ flowchart LR
88
+ subgraph IN["Where hits come from"]
89
+ B["Browser script<br/>pageviews, events,<br/>time on page, scroll"]
90
+ S["Your server code<br/>trackRequest()"]
91
+ H["Any language<br/>POST /collect"]
92
+ end
93
+
94
+ subgraph TM["Tallymark"]
95
+ R["1. Read the request<br/>browser, device, location"] --> V["2. Hash the visitor"] --> E["3. Store the event"]
96
+ end
97
+
98
+ ST[("Store<br/>memory, SQLite, Postgres<br/>D1, Redis")]
99
+
100
+ subgraph OUT["Where answers go"]
101
+ L["Library calls<br/>summary(), top(), sessions()"]
102
+ A["HTTP API<br/>/api/summary, /api/top"]
103
+ end
104
+
105
+ B --> R
106
+ S --> R
107
+ H --> R
108
+ E --> ST
109
+ ST --> L
110
+ ST --> A
111
+ ```
112
+
113
+ One visit, step by step:
114
+
115
+ ```mermaid
116
+ sequenceDiagram
117
+ participant V as Visitor's browser
118
+ participant T as Tallymark
119
+ participant D as Store
120
+ participant Y as You
121
+
122
+ V->>T: GET /script.js (once)
123
+ V->>T: POST /collect (pageview)
124
+ T->>T: read browser, device, location, hash the visitor, drop bots
125
+ T->>D: store the event
126
+ V->>T: POST /collect (left after 40 s, scrolled 70%)
127
+ T->>D: store the engagement
128
+ Y->>T: GET /api/summary
129
+ T->>D: events for the range
130
+ D-->>T: events
131
+ T-->>Y: visitors, pageviews, bounce rate, time on site
132
+ ```
133
+
134
+ Three ideas are enough to use it:
135
+
136
+ - **An event** is one thing that happened: a pageview, or a name you choose (`Signup`, `Purchase`). It records the page, where the visitor came from, their browser and device, a coarse location, and any properties or value you attach.
137
+ - **A visitor** is `hash(secret + today's date + site + IP + User-Agent)`. The raw IP and User-Agent are not stored.
138
+ - **A session** is one visit: a visitor's events, split when they go quiet for 30 minutes. A long read stays in that visit, because the engagement beacon counts as activity on the page it belongs to. Sessions are rebuilt when you ask a question, which is how bounce rate, time on site, entry and exit pages, and the path each visitor took are computed with no extra storage.
139
+
140
+ ### What is automatic, and what you write
141
+
142
+ | What gets recorded | What you write |
143
+ |---|---|
144
+ | Pageviews, including single-page-app navigation | Nothing. One `<script>` tag (or `<Analytics />`) does it. |
145
+ | Referrer, UTM campaign, and channel (Direct, Search, Social, Email, Paid) | Nothing |
146
+ | Browser and version, OS, device, language, screen size | Nothing |
147
+ | Country, region, city and timezone | Nothing, on Cloudflare or Vercel (read from their headers) |
148
+ | Time on page and scroll depth | Nothing |
149
+ | Clicks on outbound links and file downloads | `data-outbound` or `data-downloads` on the script tag. Stored as `outbound` and `download`. |
150
+ | Bots, Do-Not-Track, prefetches and your own IPs are skipped | Nothing |
151
+
152
+ ## Custom events
153
+
154
+ Four ways to name one. A [runnable example of each](./examples/events) is in the repo.
155
+
156
+ ```html
157
+ <!-- 1. An attribute, no JavaScript. Properties are data-tally-<name>. -->
158
+ <button data-tally="Signup" data-tally-plan="pro">Start free trial</button>
159
+
160
+ <!-- 2. From JavaScript: name, properties, and a value to add up (revenue). -->
161
+ <button onclick="tallymark.track('Purchase', { sku: 'A1' }, 49)">Buy</button>
162
+ ```
163
+
164
+ ```ts
165
+ // 3. From your server, for things the browser cannot see (a payment webhook, an API call).
166
+ await tm.trackRequest(request, { name: 'Subscribe', props: { plan: 'free' }, value: 5 })
167
+
168
+ // 4. In React, anywhere: import { track } from 'tallymark/react'
169
+ track('Purchase', { sku: 'A1' }, 49)
170
+ ```
171
+
172
+ ## What you can ask
173
+
174
+ Every question takes a time range (`'24h'`, `'7d'`, `'30d'`, … or `{ from, to }`) and optional filters on any dimension.
175
+
176
+ | Question | Call |
177
+ |---|---|
178
+ | Totals: visitors, pageviews, sessions, bounce rate, time on site and page, revenue | `summary()` |
179
+ | Is it up or down compared to the last period? | `compare()` |
180
+ | Traffic over time, by hour, day, week or month | `timeseries()` |
181
+ | The top values of anything, with time on page and scroll depth for pages | `top(dimension)` |
182
+ | Where visitors drop off | `funnel([...steps])` |
183
+ | The path each visitor took, step by step | `sessions()` |
184
+ | The most common routes through the site | `journeys()` |
185
+ | Who is on the site right now | `realtime()` |
186
+ | Every event, for export | `events()`, `export()` |
187
+
188
+ **Dimensions** for `top()` and for filters: `path` `entry_page` `exit_page` `referrer` `source` `channel` `country` `continent` `region` `city` `timezone` `language` `browser` `browser_version` `os` `os_version` `device` `screen` `utm_source` `utm_medium` `utm_campaign` `utm_term` `utm_content` `event` `hostname` `weekday` `hour`, and `prop:<name>` for any custom property, such as `prop:plan`.
189
+
190
+ The HTTP paths are in the [reference](./docs/USAGE.md).
191
+
192
+ ## Storage
193
+
194
+ Events go to a *store*. Memory is the default. Every store passes the same test suite, and the PostgreSQL and Redis ones are tested against real servers.
195
+
196
+ | Store | Use it for |
197
+ |---|---|
198
+ | `memoryStore()` | Trying it out, tests. Lost on restart. |
199
+ | `bunSqliteStore(db)` | One server, a file on disk |
200
+ | `pgStore(client)` | PostgreSQL: `pg`, Neon, Supabase, Vercel Postgres, RDS |
201
+ | `d1Store(env.DB)` | Cloudflare Workers |
202
+ | `libsqlStore(client)` | Turso |
203
+ | `upstashRestStore({ url, token })` | Upstash Redis over `fetch`, for any edge runtime |
204
+ | `mirrorStore(primary, [backups])` | A live backup, or moving between stores |
205
+ | your own | Three methods: `insert`, `list`, `prune` |
206
+
207
+ Back up and restore with `export()` / `import()` (or `/api/export.ndjson`), between any two stores. Send every event to a third party with `forward: webhookSink({ url, secret })`.
208
+
209
+ ## Documentation
210
+
211
+ > **Using an AI coding agent?** Point it at [llms.txt](./llms.txt). It has copy-exact integration steps for every supported platform, the rules to follow, a verification checklist and a troubleshooting table. After `npm i tallymark` it is also at `node_modules/tallymark/llms.txt`.
212
+
213
+ - **[How it works](./docs/HOW_IT_WORKS.md)**: the event model, the visitor hash, sessions, attribution, time on page, privacy, and honest limits.
214
+ - **[Reference](./docs/USAGE.md)**: every option, method, dimension, endpoint and tracker setting.
215
+ - **[Deployment](./docs/DEPLOYMENT.md)**: Cloudflare, Vercel, Docker, reverse proxies, retention and backups.
216
+ - **[Examples](./examples/README.md)**: runnable, commented, and checked.
217
+
218
+ ## The name
219
+
220
+ A tally mark is the oldest way of counting: four upright strokes, and a fifth across them. That is the logo.
221
+
222
+ ## Develop
223
+
224
+ ```bash
225
+ bun install # dependencies and git hooks
226
+ bun run check # format, lint, typecheck, tests
227
+ bun run services # real Postgres and Redis in Docker, for the store tests
228
+ bun run build && bun run smoke && bun run validate
229
+ ```
230
+
231
+ ESM only. [AGENTS.md](./AGENTS.md) describes the code and its rules; [CONTRIBUTING.md](./CONTRIBUTING.md) says how to send a patch; the [Code of Conduct](./CODE_OF_CONDUCT.md) covers how people are treated here; report vulnerabilities as described in [SECURITY.md](./SECURITY.md).
232
+
233
+ ## License
234
+
235
+ [AGPL-3.0-only](./LICENSE). You may use, modify and self-host it freely. If you offer a modified version to others over a network, you must share your changes under the same license.
package/SECURITY.md ADDED
@@ -0,0 +1,37 @@
1
+ # SECURITY
2
+
3
+ ## Reporting a vulnerability
4
+
5
+ Report vulnerabilities privately at <https://github.com/whoisjayd/tallymark/security/advisories/new>. Please do not open a public issue.
6
+
7
+ Expect an acknowledgement within a few days. Reports about privacy regressions (anything that stores or leaks an IP address, a raw User-Agent, or an identifier that survives the UTC day) are treated as security issues.
8
+
9
+ Only the latest released version is supported.
10
+
11
+ ## Threat model
12
+
13
+ **What Tallymark does protect**
14
+
15
+ - The read API is off without `apiKey`, and keys are compared in constant time.
16
+ - `/collect` enforces a streamed 8 KB body limit, JSON validation, rate limiting, bot filtering, referrer-spam filtering, origin allow-lists, strict origin mode, and IP exclusion.
17
+ - All SQL is parameterised. CSV export neutralises spreadsheet formula injection. Imported backups are validated line by line. Webhooks are signed with HMAC-SHA256.
18
+ - Errors never leak internals to callers.
19
+ - No IP address, raw User-Agent, cookie or full query string is stored.
20
+
21
+ **What it does not protect**
22
+
23
+ - **Fake events.** The ingest endpoint is public, as in every analytics tool. A non-browser client can send any headers. The mitigations raise the cost of forging data; they cannot remove it.
24
+ - **Shared rate limits.** The built-in limiter is per process. Use your platform's rate limiting for hard limits.
25
+ - **Data at rest.** Encrypting the database is the database's job.
26
+ - **A leaked `secret`.** Anyone with it who can guess an IP and a User-Agent could recompute a visitor's hash for that day. Keep it private; changing it invalidates every visitor id.
27
+
28
+ ## Deployment checklist
29
+
30
+ - [ ] `secret` and `apiKey` are long random values (`openssl rand -hex 32`) kept in a secret store, not in git, and never in client-side code.
31
+ - [ ] `trustProxy` is on only behind Cloudflare, Vercel, or a proxy you control that overwrites client-supplied IP headers. Otherwise it is off.
32
+ - [ ] TLS is terminated in front (Caddy, nginx, your platform).
33
+ - [ ] `allowedHosts` and `strictOrigin` are set to your own sites.
34
+ - [ ] `onError` is wired to your logger or alerting.
35
+ - [ ] `retentionDays` is set and `prune()` runs on a schedule.
36
+ - [ ] Backups exist (`mirrorStore`, or a scheduled `/api/export.ndjson`).
37
+ - [ ] No personal data goes into event names or properties.
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env bun
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,124 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * Self-host in one command:
4
+ *
5
+ * TALLYMARK_SECRET=... TALLYMARK_API_KEY=... bunx tallymark
6
+ *
7
+ * Storage (first match wins):
8
+ * UPSTASH_REDIS_REST_URL + UPSTASH_REDIS_REST_TOKEN Upstash Redis
9
+ * TALLYMARK_DB=postgres://user:pass@host/db PostgreSQL (Bun's built-in client)
10
+ * TALLYMARK_DB=./tallymark.db SQLite file (default)
11
+ * TALLYMARK_DB=:memory: in-memory, lost on restart
12
+ *
13
+ * Other env:
14
+ * PORT (3000) · TALLYMARK_SECRET · TALLYMARK_API_KEY
15
+ * TALLYMARK_ORIGINS, TALLYMARK_HOSTS, TALLYMARK_EXCLUDE_IPS, TALLYMARK_BLOCKED_REFERRERS (comma lists)
16
+ * TALLYMARK_STRICT_ORIGIN=true · TALLYMARK_RETENTION_DAYS · TALLYMARK_TRUST_PROXY=true
17
+ * TALLYMARK_WEBHOOK_URL + TALLYMARK_WEBHOOK_SECRET forward every event to a third party
18
+ */
19
+ import { Database } from 'bun:sqlite';
20
+ import { SQL } from 'bun';
21
+ import { bunSqliteStore, memoryStore, postgresJsStore, upstashRestStore } from './stores.js';
22
+ import { createTallymark } from './tallymark.js';
23
+ import { webhookSink } from './webhook.js';
24
+ const env = process.env;
25
+ const fail = (msg) => {
26
+ console.error(`tallymark: ${msg}`);
27
+ process.exit(1);
28
+ };
29
+ const list = (v) => v
30
+ ? v
31
+ .split(',')
32
+ .map((s) => s.trim())
33
+ .filter(Boolean)
34
+ : undefined;
35
+ const int = (name, fallback) => {
36
+ const raw = env[name];
37
+ if (raw === undefined || raw === '')
38
+ return fallback;
39
+ const n = Number(raw);
40
+ return Number.isInteger(n) && n >= 0
41
+ ? n
42
+ : fail(`${name} must be a non-negative integer, got "${raw}"`);
43
+ };
44
+ if (!env.TALLYMARK_SECRET) {
45
+ console.warn('! TALLYMARK_SECRET is not set: visitor ids will reset on every restart. Try: openssl rand -hex 32');
46
+ }
47
+ if (!env.TALLYMARK_API_KEY) {
48
+ console.warn('! TALLYMARK_API_KEY is not set: the read API is disabled.');
49
+ }
50
+ // ── storage ──────────────────────────────────────────────────────────────
51
+ let store;
52
+ let closeStore = () => { };
53
+ let where;
54
+ const db = env.TALLYMARK_DB ?? './tallymark.db';
55
+ if (env.UPSTASH_REDIS_REST_URL && env.UPSTASH_REDIS_REST_TOKEN) {
56
+ store = upstashRestStore({ url: env.UPSTASH_REDIS_REST_URL, token: env.UPSTASH_REDIS_REST_TOKEN });
57
+ where = 'upstash';
58
+ }
59
+ else if (/^postgres(ql)?:\/\//i.test(db)) {
60
+ const pg = new SQL(db);
61
+ store = postgresJsStore(pg);
62
+ closeStore = () => void pg.close();
63
+ where = 'postgres';
64
+ }
65
+ else if (db === ':memory:') {
66
+ store = memoryStore();
67
+ where = 'memory (data is lost on restart)';
68
+ }
69
+ else {
70
+ const sqlite = new Database(db, { create: true });
71
+ // WAL: readers don't block the writer. busy_timeout: wait instead of erroring under contention.
72
+ sqlite.run('PRAGMA journal_mode = WAL');
73
+ sqlite.run('PRAGMA busy_timeout = 5000');
74
+ store = bunSqliteStore(sqlite);
75
+ closeStore = () => sqlite.close();
76
+ where = `sqlite ${db}`;
77
+ }
78
+ // ── engine ───────────────────────────────────────────────────────────────
79
+ const trustProxy = env.TALLYMARK_TRUST_PROXY === 'true';
80
+ const analytics = createTallymark({
81
+ store,
82
+ secret: env.TALLYMARK_SECRET,
83
+ apiKey: env.TALLYMARK_API_KEY,
84
+ allowedOrigins: list(env.TALLYMARK_ORIGINS) ?? '*',
85
+ allowedHosts: list(env.TALLYMARK_HOSTS),
86
+ excludeIps: list(env.TALLYMARK_EXCLUDE_IPS),
87
+ blockedReferrers: list(env.TALLYMARK_BLOCKED_REFERRERS),
88
+ strictOrigin: env.TALLYMARK_STRICT_ORIGIN === 'true',
89
+ retentionDays: int('TALLYMARK_RETENTION_DAYS', 0),
90
+ // Behind nginx / Caddy / Cloudflare? Set TALLYMARK_TRUST_PROXY=true.
91
+ trustProxy,
92
+ forward: env.TALLYMARK_WEBHOOK_URL
93
+ ? webhookSink({ url: env.TALLYMARK_WEBHOOK_URL, secret: env.TALLYMARK_WEBHOOK_SECRET })
94
+ : undefined,
95
+ onError: (error, { where }) => console.error(`tallymark: ${where} failed:`, error?.message ?? error),
96
+ });
97
+ if (env.TALLYMARK_STRICT_ORIGIN === 'true' && !env.TALLYMARK_HOSTS) {
98
+ fail('TALLYMARK_STRICT_ORIGIN=true requires TALLYMARK_HOSTS');
99
+ }
100
+ // Direct exposure: the socket address is the truth. Behind a proxy it is the proxy's
101
+ // address, so defer to the forwarded headers instead.
102
+ const server = Bun.serve({
103
+ port: int('PORT', 3000),
104
+ fetch: (req, srv) => analytics.handle(req, { ip: trustProxy ? undefined : srv.requestIP(req)?.address }),
105
+ });
106
+ console.log(`tallymark listening on ${server.url} · storage: ${where}`);
107
+ // Retention: once at boot, then daily.
108
+ if (analytics.options.retentionDays) {
109
+ const sweep = () => analytics.prune().catch(() => undefined);
110
+ void sweep();
111
+ setInterval(sweep, 86_400_000).unref();
112
+ }
113
+ // Graceful shutdown: finish in-flight requests, then release the database.
114
+ let stopping = false;
115
+ const shutdown = async () => {
116
+ if (stopping)
117
+ return;
118
+ stopping = true;
119
+ await server.stop();
120
+ closeStore();
121
+ process.exit(0);
122
+ };
123
+ process.on('SIGTERM', shutdown);
124
+ process.on('SIGINT', shutdown);
@@ -0,0 +1,9 @@
1
+ import type { TallymarkOptions } from './types.js';
2
+ export declare function cloudflare<Env>(config: (env: Env) => TallymarkOptions): {
3
+ fetch: (request: Request, env: Env, ctx?: {
4
+ waitUntil(p: Promise<unknown>): void;
5
+ }) => Promise<Response>;
6
+ scheduled: (_event: unknown, env: Env, ctx?: {
7
+ waitUntil(p: Promise<unknown>): void;
8
+ }) => Promise<void>;
9
+ };
@@ -0,0 +1,53 @@
1
+ import { timezone } from './hit.js';
2
+ import { createTallymark } from './tallymark.js';
3
+ /**
4
+ * Cloudflare Workers. Bindings only exist per request, so the engine is built
5
+ * lazily from `env` and reused for the life of the isolate.
6
+ *
7
+ * export default cloudflare<Env>((env) => ({
8
+ * store: d1Store(env.DB),
9
+ * secret: env.SECRET,
10
+ * apiKey: env.API_KEY,
11
+ * }))
12
+ *
13
+ * Add `[triggers] crons = ["0 3 * * *"]` to wrangler.toml and `retentionDays`
14
+ * to enforce data retention.
15
+ */
16
+ /**
17
+ * Cloudflare exposes precise location on `request.cf`, not in headers. Only the
18
+ * country header is sent by default, so read the object for region and city.
19
+ * `XX` (unknown) and `T1` (Tor) are not countries.
20
+ */
21
+ function cfGeo(request) {
22
+ const cf = request.cf;
23
+ if (!cf)
24
+ return undefined;
25
+ const country = cf.country &&
26
+ /^[A-Za-z]{2}$/.test(cf.country) &&
27
+ !['XX', 'T1'].includes(cf.country.toUpperCase())
28
+ ? cf.country.toUpperCase()
29
+ : null;
30
+ return {
31
+ country,
32
+ region: cf.region ?? null,
33
+ city: cf.city ?? null,
34
+ timezone: timezone(cf.timezone),
35
+ };
36
+ }
37
+ export function cloudflare(config) {
38
+ let engine;
39
+ const get = (env) => (engine ??= createTallymark(config(env)));
40
+ return {
41
+ fetch: (request, env, ctx) => get(env).handle(request, {
42
+ waitUntil: ctx ? (p) => ctx.waitUntil(p) : undefined,
43
+ geo: cfGeo(request),
44
+ }),
45
+ scheduled: async (_event, env, ctx) => {
46
+ const job = get(env).prune();
47
+ if (ctx)
48
+ ctx.waitUntil(job);
49
+ else
50
+ await job;
51
+ },
52
+ };
53
+ }
package/dist/hit.d.ts ADDED
@@ -0,0 +1,83 @@
1
+ import type { ConnInfo, Device, Props, ScreenClass, Utm } from './types.js';
2
+ /**
3
+ * Turning a raw request into clean event fields: User-Agent, URL, referrer,
4
+ * language, location, spam, and the anonymous daily visitor id.
5
+ */
6
+ export interface UaInfo {
7
+ browser: string | null;
8
+ browserVersion: string | null;
9
+ os: string | null;
10
+ osVersion: string | null;
11
+ device: Device;
12
+ bot: boolean;
13
+ }
14
+ /** Tiny, dependency-free UA parser. Browser family + major version, OS, and device class. */
15
+ export declare function parseUserAgent(ua: string | null | undefined): UaInfo;
16
+ export interface ParsedUrl {
17
+ hostname: string;
18
+ path: string;
19
+ utm: Utm;
20
+ }
21
+ /**
22
+ * Accepts an absolute URL or a bare path. Keeps only hostname, path and campaign
23
+ * parameters. Every other query parameter is dropped: they often carry tokens or
24
+ * personal data.
25
+ */
26
+ export declare function parseUrl(input: string): ParsedUrl | null;
27
+ /** Returns `{ url, host }` for an external referrer, or nulls for internal/invalid. */
28
+ export declare function parseReferrer(referrer: string | null | undefined, hostname: string): {
29
+ referrer: string | null;
30
+ host: string | null;
31
+ };
32
+ export interface Geo {
33
+ country: string | null;
34
+ region: string | null;
35
+ city: string | null;
36
+ timezone: string | null;
37
+ }
38
+ /**
39
+ * Location and client IP from headers the hosting platform already sets. Free,
40
+ * instant, and no third-party lookup: Cloudflare, Vercel, and generic proxies.
41
+ *
42
+ * Only trust these when the request really passed through that platform.
43
+ */
44
+ /** An IANA timezone such as `Europe/Berlin`, or null. Anything else is dropped. */
45
+ export declare function timezone(v: string | null | undefined): string | null;
46
+ export declare function geoFromHeaders(h: Headers): Geo;
47
+ export declare function clientIp(h: Headers): string | null;
48
+ export declare function isSpamReferrer(host: string | null, extra?: string[]): boolean;
49
+ /**
50
+ * Anonymous, cookieless visitor id:
51
+ *
52
+ * sha256(secret : utcDay : hostname : ip : userAgent)
53
+ *
54
+ * The raw IP and User-Agent only exist inside this call. Because the day is part
55
+ * of the input, the same person gets a different id tomorrow and cannot be
56
+ * followed across days. Different sites get different ids for the same person.
57
+ */
58
+ export declare function visitorId(secret: string, ts: number, hostname: string, ip: string | null, userAgent: string | null): Promise<string>;
59
+ export declare function randomId(): string;
60
+ export declare function randomSecret(): string;
61
+ /** Keep props flat, small, and primitive. Anything else is dropped, not thrown. */
62
+ export declare function sanitizeProps(input: unknown): Props;
63
+ /** `en-US,en;q=0.9` -> `en-US`. Only the primary tag; never the whole header. */
64
+ export declare function primaryLanguage(header: string | null | undefined): string | null;
65
+ /** Plausible-style viewport classes. Bucketed server-side so raw widths are never stored. */
66
+ export declare function screenClass(width: unknown): ScreenClass | null;
67
+ /** Continent name for an ISO 3166-1 alpha-2 country code, or null. */
68
+ export declare function continentOf(country: string | null): string | null;
69
+ export interface RequestFacts {
70
+ ip: string | null;
71
+ userAgent: string | null;
72
+ language: string | null;
73
+ country: string | null;
74
+ region: string | null;
75
+ city: string | null;
76
+ timezone: string | null;
77
+ }
78
+ /**
79
+ * Read the visitor's IP, User-Agent, language and location from a request. The one
80
+ * place this happens, so the browser endpoint and server-side tracking agree.
81
+ * `info` (the socket address, Cloudflare's `request.cf`) wins over headers.
82
+ */
83
+ export declare function describeRequest(req: Request, info: ConnInfo, trustProxy: boolean): RequestFacts;