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
@@ -0,0 +1,34 @@
1
+ // bun examples/website/server.ts → open http://localhost:3000
2
+ //
3
+ // The complete loop in one file: a web page loads the tracker, the tracker sends
4
+ // hits to Tallymark, and you read the numbers back from the API.
5
+ //
6
+ // What happens when you open the page:
7
+ // 1. index.html loads /analytics/script.js (the browser tracker, served by Tallymark itself)
8
+ // 2. the script sends a pageview to /analytics/collect, then time on page and scroll when you leave
9
+ // 3. Tallymark works out browser, OS, device, language and (behind a CDN) location from that request
10
+ // 4. you read it back: curl -H 'Authorization: Bearer dev-key' .../analytics/api/summary?range=1h
11
+ import { createTallymark } from 'tallymark'
12
+
13
+ const tm = createTallymark({
14
+ secret: 'dev-secret',
15
+ apiKey: 'dev-key',
16
+ basePath: '/analytics', // Tallymark lives under /analytics on this server
17
+ })
18
+
19
+ const server = Bun.serve({
20
+ port: Number(process.env.PORT ?? 3000),
21
+ async fetch(req, srv) {
22
+ const { pathname } = new URL(req.url)
23
+ if (pathname.startsWith('/analytics')) {
24
+ return tm.handle(req, { ip: srv.requestIP(req)?.address })
25
+ }
26
+ if (pathname === '/') return new Response(Bun.file(`${import.meta.dir}/index.html`))
27
+ return new Response('not found', { status: 404 })
28
+ },
29
+ })
30
+
31
+ console.log(`site: ${server.url}`)
32
+ console.log(
33
+ `stats: curl -H 'Authorization: Bearer dev-key' '${server.url}analytics/api/summary?range=1h'`,
34
+ )
@@ -0,0 +1,89 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <title>Custom events: every way to add one</title>
7
+
8
+ <!--
9
+ THE ONLY SETUP. This one tag gives you, with no further code:
10
+ • a pageview on load, and on every client-side navigation
11
+ • the referrer and ?utm_* campaign, browser, OS, device, language, screen size
12
+ • country / region / city (from your host's headers, nothing extra to configure)
13
+ • time on page and scroll depth, reported when the visitor leaves
14
+
15
+ Optional switches (all off by default except pageviews and time on page):
16
+ data-outbound="true" record clicks on links to other sites -> event "outbound"
17
+ data-downloads="true" record clicks on .pdf/.zip/... links -> event "download"
18
+ data-engagement="false" turn off time on page / scroll depth
19
+ data-localhost="true" also record from localhost (skipped by default)
20
+ -->
21
+ <script defer src="/analytics/script.js" data-localhost="true" data-outbound="true" data-downloads="true"></script>
22
+ </head>
23
+
24
+ <body>
25
+ <h1>Custom events</h1>
26
+ <p>
27
+ Pageviews, sources, devices, locations and time on page are automatic. Everything below is for
28
+ the things only <em>you</em> know matter: a signup, a purchase, a feature being used.
29
+ </p>
30
+
31
+ <!--
32
+ WAY 1: HTML attributes. No JavaScript.
33
+ data-tally="<event name>" sends that event when the element is clicked.
34
+ data-tally-<name>="<value>" adds a property called <name>.
35
+ Here: event "Signup" with the property plan = "pro".
36
+ -->
37
+ <h2>1. Attributes</h2>
38
+ <button type="button" id="signup" data-tally="Signup" data-tally-plan="pro" data-tally-source="pricing-page">Start free trial</button>
39
+
40
+ <!--
41
+ WAY 2: JavaScript. tallymark.track(name, properties?, value?)
42
+ name what happened, as a short stable label: "Purchase", "VideoPlayed", "SearchUsed"
43
+ properties extra facts you can break the event down by later (flat: strings, numbers, booleans)
44
+ value a number to add up, usually revenue. The API sums it for you.
45
+ window.tallymark exists as soon as the script has loaded; the ?. keeps this safe
46
+ if it was blocked or has not loaded yet.
47
+ -->
48
+ <h2>2. JavaScript</h2>
49
+ <button type="button" id="buy" onclick="window.tallymark?.track('Purchase', { sku: 'A1', currency: 'EUR' }, 49)">Buy for 49 EUR</button>
50
+
51
+ <!-- Same idea after something happens in your own code: a form, a search, a toggle. -->
52
+ <form id="search" onsubmit="event.preventDefault(); window.tallymark?.track('Search', { results: 12, query_length: this.q.value.length })">
53
+ <input name="q" placeholder="Search…" />
54
+ <button type="submit">Search</button>
55
+ </form>
56
+
57
+ <!-- A/B tests and feature flags: record which variant the visitor saw, then compare conversions. -->
58
+ <button type="button" id="variant" onclick="window.tallymark?.track('PricingToggle', { variant: 'annual' })">Show annual pricing</button>
59
+
60
+ <!--
61
+ WAY 3: automatic. No code at all, once enabled on the script tag above.
62
+ <a href="https://other-site.example/docs"> -> event "outbound" { url: "https://other-site.example/docs" }
63
+ <a href="/files/report.pdf"> -> event "download" { file: "/files/report.pdf" }
64
+ The query string of an outbound link is dropped on purpose: it often contains tokens.
65
+ -->
66
+ <h2>3. Automatic</h2>
67
+ <p>
68
+ <a id="out" href="https://example.org/docs?token=secret" target="_blank">Outbound link</a> ·
69
+ <a id="dl" href="/files/report.pdf" onclick="return false">Download report.pdf</a>
70
+ </p>
71
+
72
+ <!--
73
+ WAY 4: single-page apps. Changing the URL with the History API is a pageview.
74
+ Nothing to call: the script listens for it.
75
+ -->
76
+ <h2>4. Navigation without a page load</h2>
77
+ <button type="button" id="spa" onclick="history.pushState({}, '', '/pricing')">Go to /pricing (no reload)</button>
78
+
79
+ <!--
80
+ WAY 5: from your server. Events the browser cannot see (a payment webhook, a cron job,
81
+ an API call) are recorded in server.ts with tm.trackRequest(...) or tm.track(...).
82
+ This button calls a route that does exactly that.
83
+ -->
84
+ <h2>5. From the server</h2>
85
+ <button type="button" id="subscribe" onclick="fetch('/api/subscribe', { method: 'POST', body: JSON.stringify({ plan: 'newsletter' }) })">Subscribe (server records it)</button>
86
+
87
+ <p><a href="/stats">See what was recorded →</a></p>
88
+ </body>
89
+ </html>
@@ -0,0 +1,101 @@
1
+ // bun examples/events/server.ts → open http://localhost:3000, click around, then open /stats
2
+ //
3
+ // Custom events, end to end: how they are sent (index.html and this file) and how to read them back.
4
+ import { createTallymark } from 'tallymark'
5
+
6
+ const tm = createTallymark({
7
+ secret: 'dev-secret',
8
+ apiKey: 'dev-key',
9
+ basePath: '/analytics', // the browser script and the API live under /analytics
10
+ })
11
+
12
+ // ── Sending events from the server ───────────────────────────────────────────
13
+ //
14
+ // Use these for things that never happen in a browser: a payment provider's webhook, a cron job,
15
+ // a mobile app calling your API. There are two functions, and you almost always want the first.
16
+
17
+ /**
18
+ * trackRequest: you already have the visitor's request in hand (a route handler, a server action).
19
+ * It reads their IP, browser, language, location and referrer from it, so you only say what happened.
20
+ */
21
+ async function subscribe(request: Request, conn: { ip?: string }) {
22
+ const { plan } = (await request.json().catch(() => ({}))) as { plan?: string }
23
+
24
+ const result = await tm.trackRequest(
25
+ request,
26
+ {
27
+ name: 'Subscribe', // what happened
28
+ props: { plan: plan ?? 'free' }, // facts to break it down by (flat; strings, numbers, booleans)
29
+ value: 5, // a number to sum, e.g. what this is worth
30
+ },
31
+ conn,
32
+ ) // conn = the socket address; behind Vercel/Cloudflare you can omit it
33
+
34
+ // trackRequest never throws. It returns what happened, so you can tell why a hit was skipped:
35
+ // { ok: true, event } recorded
36
+ // { ok: false, reason } 'bot' | 'dnt' | 'excluded' | 'spam' | 'host' | 'invalid' | 'storage' ...
37
+ return Response.json({ ok: result.ok })
38
+ }
39
+
40
+ /**
41
+ * track: there is no visitor request, only facts you already know (a webhook from a payment
42
+ * provider). You supply what is available; everything is optional except the url.
43
+ */
44
+ async function paymentWebhook() {
45
+ await tm.track({
46
+ name: 'Purchase',
47
+ url: 'https://shop.example/checkout/success', // the page this belongs to
48
+ props: { sku: 'A1', method: 'card' },
49
+ value: 49,
50
+ country: 'DE', // you may know the country from the billing address
51
+ // ip / userAgent are optional: without them the hit counts as its own anonymous visitor.
52
+ })
53
+ }
54
+ void paymentWebhook // shown for illustration; call it from your webhook route
55
+
56
+ // ── Reading events back ──────────────────────────────────────────────────────
57
+
58
+ async function stats() {
59
+ return {
60
+ // Every event name, how many times, how many people, and the summed value (revenue).
61
+ events: await tm.top('event', '24h'),
62
+
63
+ // Break one event down by a property you attached: prop:<name>.
64
+ // → [{ key: 'pro', count: 2, value: 98 }, { key: 'free', count: 1, value: 0 }]
65
+ signupsByPlan: await tm.top('prop:plan', '24h', { event: 'Signup' }),
66
+
67
+ // The other direction: filter to one property value, then ask about the events.
68
+ proSignups: await tm.top('event', '24h', { 'prop:plan': 'pro' }),
69
+
70
+ // Who converts? Ordered steps of pages and events. Here: saw pricing, then signed up.
71
+ funnel: await tm.funnel([{ path: '/' }, { event: 'Signup' }], '24h'),
72
+
73
+ // Which source earns money? Events inherit the visitor's source (Google, a newsletter, ...).
74
+ purchasesByChannel: await Promise.all(
75
+ ['Organic Search', 'Social', 'Email', 'Direct'].map(async (channel) => ({
76
+ channel,
77
+ purchases: await tm.top('event', '24h', { channel, event: 'Purchase' }),
78
+ })),
79
+ ),
80
+
81
+ // The path one visitor took, step by step, with the events they fired along the way.
82
+ latestSession: (await tm.sessions('24h', {}, 1))[0],
83
+ }
84
+ }
85
+
86
+ // ── Wiring ────────────────────────────────────────────────────────────────────
87
+
88
+ Bun.serve({
89
+ port: Number(process.env.PORT ?? 3000),
90
+ async fetch(request, server) {
91
+ const { pathname } = new URL(request.url)
92
+ const conn = { ip: server.requestIP(request)?.address }
93
+
94
+ if (pathname.startsWith('/analytics')) return tm.handle(request, conn)
95
+ if (pathname === '/api/subscribe' && request.method === 'POST') return subscribe(request, conn)
96
+ if (pathname === '/stats') return Response.json(await stats())
97
+ return new Response(Bun.file(`${import.meta.dir}/index.html`))
98
+ },
99
+ })
100
+
101
+ console.log('open http://localhost:3000')
@@ -0,0 +1,21 @@
1
+ // Astro: src/pages/analytics/[...path].ts
2
+ //
3
+ // Needs server rendering (an SSR adapter, output "server" or "hybrid"). The endpoint serves the browser
4
+ // script, receives its hits and answers the reports, all through one Fetch handler.
5
+ import { createTallymark } from 'tallymark'
6
+
7
+ const analytics = createTallymark({
8
+ secret: process.env.ANALYTICS_SECRET,
9
+ apiKey: process.env.ANALYTICS_API_KEY,
10
+ basePath: '/analytics',
11
+ })
12
+
13
+ export const prerender = false
14
+
15
+ export const ALL = ({ request }: { request: Request }) => analytics.handle(request)
16
+
17
+ // Load the tracker once, in your layout. One tag records pageviews, sources, devices, time on page and
18
+ // scroll depth. `is:inline` stops Astro from bundling it, so it keeps reading its own data-* settings:
19
+ // <script is:inline defer src="/analytics/script.js"></script>
20
+ //
21
+ // A custom event needs no code: <button data-tally="Signup" data-tally-plan="pro">
@@ -0,0 +1,23 @@
1
+ // bun examples/frameworks/bun.ts
2
+ //
3
+ // The smallest complete server: Tallymark with data that survives restarts (a SQLite file).
4
+ // Point any site's <script src="http://localhost:3000/script.js"> at it and it starts counting.
5
+ // (The packaged CLI does the same with zero code: `bunx tallymark`.)
6
+ import { Database } from 'bun:sqlite'
7
+ import { createTallymark } from 'tallymark'
8
+ import { bunSqliteStore } from 'tallymark/stores'
9
+
10
+ const analytics = createTallymark({
11
+ // A file on disk. The table is created on first use; reads and writes need no setup.
12
+ store: bunSqliteStore(new Database('stats.db', { create: true })),
13
+
14
+ secret: process.env.TALLYMARK_SECRET ?? 'change-me', // set a real one in production
15
+ apiKey: process.env.TALLYMARK_API_KEY ?? 'dev-key', // protects /api/*
16
+ })
17
+
18
+ Bun.serve({
19
+ port: 3000,
20
+ // Tell Tallymark the real socket address. Nothing sits in front of this server, so it is
21
+ // the only trustworthy source for the visitor's IP (headers could be forged by anyone).
22
+ fetch: (req, server) => analytics.handle(req, { ip: server.requestIP(req)?.address }),
23
+ })
@@ -0,0 +1,37 @@
1
+ // A complete Cloudflare Worker. Deploy with `wrangler deploy`.
2
+ //
3
+ // What you get with no extra configuration:
4
+ // • the visitor's country, region, city and timezone (read from Cloudflare's own request data)
5
+ // • their real IP (hashed, never stored)
6
+ // • work that runs after the response (forwarding to webhooks) without slowing the visitor down
7
+ //
8
+ // wrangler.toml
9
+ // name = "stats"
10
+ // main = "examples/frameworks/cloudflare.ts"
11
+ // compatibility_date = "2026-01-01"
12
+ // [[d1_databases]] # a serverless SQLite database
13
+ // binding = "DB" # becomes env.DB below
14
+ // database_name = "stats"
15
+ // database_id = "<from `wrangler d1 create stats`>"
16
+ // [triggers]
17
+ // crons = ["0 3 * * *"] # runs `scheduled` below every day at 03:00: the retention sweep
18
+ //
19
+ // Secrets (never commit these): wrangler secret put SECRET && wrangler secret put API_KEY
20
+ import { cloudflare } from 'tallymark/cloudflare'
21
+ import { d1Store } from 'tallymark/stores'
22
+
23
+ interface Env {
24
+ DB: Parameters<typeof d1Store>[0]
25
+ SECRET: string
26
+ API_KEY: string
27
+ }
28
+
29
+ // Bindings only exist per request on Workers, so the config is a function of `env`.
30
+ // It runs once per isolate and the result is reused.
31
+ export default cloudflare<Env>((env) => ({
32
+ store: d1Store(env.DB),
33
+ secret: env.SECRET,
34
+ apiKey: env.API_KEY,
35
+ retentionDays: 395, // events older than this are deleted by the daily cron
36
+ onError: (error, { where }) => console.error(where, error), // shows up in `wrangler tail`
37
+ }))
@@ -0,0 +1,26 @@
1
+ // deno run --allow-net --allow-env examples/frameworks/deno.ts
2
+ //
3
+ // Deno and Deno Deploy: the handler is a plain Fetch function, so it needs no adapter.
4
+ import { createTallymark } from 'npm:tallymark'
5
+
6
+ // Deno's global, declared so this file also reads cleanly outside Deno.
7
+ declare const Deno: {
8
+ env: { get(key: string): string | undefined }
9
+ serve(
10
+ options: { port: number },
11
+ handler: (
12
+ request: Request,
13
+ info: { remoteAddr: { hostname: string } },
14
+ ) => Response | Promise<Response>,
15
+ ): unknown
16
+ }
17
+
18
+ const analytics = createTallymark({
19
+ secret: Deno.env.get('TALLYMARK_SECRET'), // salts the anonymous visitor hash
20
+ apiKey: Deno.env.get('TALLYMARK_API_KEY'), // protects /api/*; without it the read API is off
21
+ })
22
+
23
+ Deno.serve({ port: 3000 }, (request, info) =>
24
+ // info.remoteAddr is the real socket address: the trustworthy source for the visitor's IP.
25
+ analytics.handle(request, { ip: info.remoteAddr.hostname }),
26
+ )
@@ -0,0 +1,57 @@
1
+ // bun examples/frameworks/express.ts (or run with node + tsx)
2
+ //
3
+ // Tallymark inside an existing Express app. It does three jobs here:
4
+ // 1. serves the browser script and receives its hits (app.use('/analytics', ...))
5
+ // 2. lets your own routes record events the browser can't see (analytics.trackRequest)
6
+ // 3. lets you read the numbers in-process (analytics.summary)
7
+ import express from 'express'
8
+ import { createTallymark } from 'tallymark'
9
+ import { nodeConn, nodeHandler, nodeRequest } from 'tallymark/node'
10
+
11
+ const analytics = createTallymark({
12
+ secret: 'change-me', // salts the anonymous visitor hash: use a long random value
13
+ apiKey: 'dev-key', // protects the read API (/analytics/api/*). Without it the read API is off.
14
+ basePath: '/analytics', // must match where it is mounted below
15
+
16
+ // Whether to believe X-Forwarded-For / CF-Connecting-IP for the visitor's IP.
17
+ // true → you are behind nginx, Caddy, a load balancer or Cloudflare that sets them.
18
+ // false → Express is exposed directly; the socket address is used instead (safer, the default for the CLI).
19
+ trustProxy: true,
20
+ })
21
+
22
+ const app = express()
23
+
24
+ // 1. The whole Tallymark API under /analytics:
25
+ // POST /analytics/collect hits from the browser script
26
+ // GET /analytics/script.js the browser script itself
27
+ // GET /analytics/api/* reports (needs the API key)
28
+ app.use('/analytics', nodeHandler(analytics, { trustProxy: true }))
29
+
30
+ // 2. A custom event from your own route, for something the browser can't see (here: a signup API call).
31
+ // trackRequest reads the visitor's IP, browser, language, location and referrer FROM THE REQUEST,
32
+ // so you only say what happened:
33
+ // name what happened props facts to break it down by later
34
+ // value a number to add up (revenue)
35
+ // nodeRequest(req) turns Express's request into a standard Request without touching the body
36
+ // stream, so it is safe after express.json().
37
+ app.post('/api/subscribe', express.json(), async (req, res) => {
38
+ await analytics.trackRequest(
39
+ nodeRequest(req),
40
+ { name: 'Subscribe', props: { plan: String(req.body?.plan ?? 'free') }, value: 5 },
41
+ nodeConn(req, { trustProxy: true }),
42
+ )
43
+ res.json({ ok: true })
44
+ })
45
+
46
+ // 3. Read numbers directly, with no HTTP round trip. Protect this route yourself: it is YOUR route.
47
+ app.get('/admin/summary', async (_req, res) => res.json(await analytics.summary('7d')))
48
+
49
+ // The only line a page needs. Pageviews, sources, devices, time on page and scroll depth follow.
50
+ app.get('/', (_req, res) =>
51
+ res.send(
52
+ '<script defer src="/analytics/script.js" data-localhost="true"></script><h1>Hello</h1>',
53
+ ),
54
+ )
55
+
56
+ const port = Number(process.env.PORT ?? 3000)
57
+ app.listen(port, () => console.log(`http://localhost:${port}`))
@@ -0,0 +1,38 @@
1
+ // bun examples/frameworks/hono.ts
2
+ //
3
+ // Hono runs on Bun, Deno, Cloudflare Workers and Node. Tallymark is a plain Fetch handler
4
+ // (Request in, Response out), so it mounts without an adapter.
5
+ import { Hono } from 'hono'
6
+ import { createTallymark } from 'tallymark'
7
+
8
+ const analytics = createTallymark({
9
+ secret: 'change-me', // salts the anonymous visitor hash
10
+ apiKey: 'dev-key', // protects the read API; without it the read API is off
11
+ basePath: '/analytics', // must match the mount path below
12
+ })
13
+
14
+ const app = new Hono()
15
+
16
+ // The whole Tallymark API: the browser script, the hit endpoint and the reports.
17
+ app.all('/analytics/*', (c) => analytics.handle(c.req.raw))
18
+
19
+ // A route of your own that records an event the browser can't see.
20
+ // trackRequest reads the visitor's IP, browser, language, location and referrer from the request,
21
+ // so you only say what happened. Omit `name` and it records a pageview instead.
22
+ app.post('/checkout', async (c) => {
23
+ const result = await analytics.trackRequest(c.req.raw, {
24
+ name: 'Purchase', // what happened
25
+ value: 49, // added up in the reports as revenue
26
+ // props: { sku: 'A1' }, // optional facts to break the event down by
27
+ })
28
+ // result is { ok: true, event } or { ok: false, reason } ('bot', 'dnt', ...). It never throws.
29
+ return c.json({ ok: true, tracked: result.ok })
30
+ })
31
+
32
+ // The one line a page needs for pageviews, sources, devices, time on page and scroll depth.
33
+ app.get('/', (c) =>
34
+ c.html('<script defer src="/analytics/script.js" data-localhost="true"></script><h1>Hello</h1>'),
35
+ )
36
+
37
+ // Bun reads `port` and `fetch` from the default export.
38
+ export default { port: Number(process.env.PORT ?? 3000), fetch: app.fetch }
@@ -0,0 +1,7 @@
1
+ // Mounts the whole Tallymark API (collect, script.js, stats) at /api/analytics/*.
2
+ // In a real project, import waitUntil from '@vercel/functions' so forwarding and
3
+ // mirroring run after the response is sent: vercel(analytics, { waitUntil }).
4
+ import { vercel } from 'tallymark/vercel'
5
+ import { analytics } from '../../../../lib/analytics'
6
+
7
+ export const { GET, POST, OPTIONS } = vercel(analytics)
@@ -0,0 +1,6 @@
1
+ // Daily retention sweep. Vercel Cron calls this with `Authorization: Bearer $CRON_SECRET`
2
+ // (set CRON_SECRET in the project settings). See ../../../vercel.json for the schedule.
3
+ import { vercelCron } from 'tallymark/vercel'
4
+ import { analytics } from '../../../lib/analytics'
5
+
6
+ export const GET = vercelCron(analytics, { secret: process.env.CRON_SECRET })
@@ -0,0 +1,15 @@
1
+ // The root layout: one component loads the tracker on every page, including client-side
2
+ // navigations in the App Router. Nothing else is needed for pageviews and time on page.
3
+ import type { ReactNode } from 'react'
4
+ import { Analytics } from 'tallymark/react'
5
+
6
+ export default function RootLayout({ children }: { children: ReactNode }) {
7
+ return (
8
+ <html lang="en">
9
+ <body>
10
+ {children}
11
+ <Analytics api="/api/analytics" outbound downloads />
12
+ </body>
13
+ </html>
14
+ )
15
+ }
@@ -0,0 +1,21 @@
1
+ 'use client'
2
+ // Custom events from a client component, and a server-side event from a server action.
3
+ import { track } from 'tallymark/react'
4
+
5
+ export default function Home() {
6
+ return (
7
+ <main>
8
+ <h1>Pricing</h1>
9
+
10
+ {/* No JavaScript needed: attributes become the event name and its properties. */}
11
+ <button type="button" data-tally="Signup" data-tally-plan="pro">
12
+ Start free trial
13
+ </button>
14
+
15
+ {/* Or call track() with a numeric value (revenue). */}
16
+ <button type="button" onClick={() => track('Purchase', { sku: 'A1' }, 49)}>
17
+ Buy now
18
+ </button>
19
+ </main>
20
+ )
21
+ }
@@ -0,0 +1,14 @@
1
+ // One Tallymark instance for the whole Next.js app. Import it wherever you need it.
2
+
3
+ import { Pool } from 'pg' // Neon, Supabase, Vercel Postgres and RDS all work. Or use neon(url) for HTTP.
4
+ import { createTallymark } from 'tallymark'
5
+ import { pgStore } from 'tallymark/stores'
6
+
7
+ export const analytics = createTallymark({
8
+ store: pgStore(new Pool({ connectionString: process.env.DATABASE_URL })),
9
+ secret: process.env.ANALYTICS_SECRET, // salts the daily visitor hash
10
+ apiKey: process.env.ANALYTICS_API_KEY, // read API is off without it
11
+ basePath: '/api/analytics', // where the route handler below is mounted
12
+ retentionDays: 395,
13
+ onError: (error, { where }) => console.error('[tallymark]', where, error),
14
+ })
@@ -0,0 +1,3 @@
1
+ {
2
+ "crons": [{ "path": "/api/analytics-cron", "schedule": "0 3 * * *" }]
3
+ }
@@ -0,0 +1,32 @@
1
+ // A Vite / Create React App / React Router app.
2
+ //
3
+ // <Analytics /> loads the tracker script once and renders nothing. From then on, with no further code:
4
+ // pageviews (including React Router navigation), sources and campaigns, device, language, screen size,
5
+ // location, time on page and scroll depth are all recorded. You add only the events that matter to you.
6
+ import { createRoot } from 'react-dom/client'
7
+ import { Analytics, track } from 'tallymark/react'
8
+
9
+ function App() {
10
+ return (
11
+ <>
12
+ <h1>Hello</h1>
13
+
14
+ {/* Way 1: attributes, no JavaScript. The element's click sends event "Signup" with plan = "pro". */}
15
+ <button type="button" data-tally="Signup" data-tally-plan="pro">
16
+ Sign up
17
+ </button>
18
+
19
+ {/* Way 2: from code. track(name, properties?, value?). The value is added up as revenue. */}
20
+ <button type="button" onClick={() => track('Purchase', { sku: 'A1' }, 49)}>
21
+ Buy
22
+ </button>
23
+
24
+ {/* Mount once, anywhere. api = where Tallymark runs.
25
+ outbound also record clicks on links to other sites
26
+ downloads also record clicks on files (.pdf .zip ...) */}
27
+ <Analytics api="https://stats.example.com" outbound downloads />
28
+ </>
29
+ )
30
+ }
31
+
32
+ createRoot(document.getElementById('root')!).render(<App />)
@@ -0,0 +1,26 @@
1
+ // SvelteKit: src/routes/analytics/[...path]/+server.ts
2
+ //
3
+ // SvelteKit endpoints are Fetch handlers, so Tallymark plugs straight in. The one file below serves
4
+ // /analytics/script.js the browser script
5
+ // /analytics/collect the hits it sends
6
+ // /analytics/api/* reports (needs the API key)
7
+ // Every verb goes to the same handler. No framework types are needed.
8
+ import { createTallymark } from 'tallymark'
9
+
10
+ const analytics = createTallymark({
11
+ secret: process.env.ANALYTICS_SECRET,
12
+ apiKey: process.env.ANALYTICS_API_KEY,
13
+ basePath: '/analytics',
14
+ })
15
+
16
+ const handler = ({ request }: { request: Request }) => analytics.handle(request)
17
+
18
+ export { handler as GET, handler as POST, handler as OPTIONS }
19
+
20
+ // Load the tracker once, in src/app.html or +layout.svelte. That single tag records pageviews
21
+ // (including SvelteKit's client-side navigation), sources, devices, time on page and scroll depth:
22
+ // <script defer src="/analytics/script.js"></script>
23
+ //
24
+ // A custom event needs no code either: <button data-tally="Signup" data-tally-plan="pro">
25
+ // Or from a +page.server.ts action, record one on the server:
26
+ // await analytics.trackRequest(request, { name: 'Signup', props: { plan: 'pro' } })
@@ -0,0 +1,9 @@
1
+ // Retention sweep for the function in ./analytics.ts. Vercel Cron sends
2
+ // `Authorization: Bearer $CRON_SECRET`; set CRON_SECRET in the project settings.
3
+ import { createTallymark } from 'tallymark'
4
+ import { vercelCron } from 'tallymark/vercel'
5
+
6
+ // In a real project, import the same instance from a shared module instead.
7
+ const analytics = createTallymark({ retentionDays: 395 })
8
+
9
+ export const GET = vercelCron(analytics, { secret: process.env.CRON_SECRET })
@@ -0,0 +1,22 @@
1
+ // Vercel Functions without a framework (static site, Vite, Astro, plain HTML...).
2
+ // Place in /api/analytics.ts and Vercel serves /api/analytics. The rewrite in
3
+ // ../vercel.json routes the sub-paths (/collect, /script.js, /api/...) to it too.
4
+ import { createTallymark } from 'tallymark'
5
+ import { upstashRestStore } from 'tallymark/stores'
6
+ import { vercel } from 'tallymark/vercel'
7
+
8
+ // Upstash Redis over plain fetch: no SDK, no connection pool, built for serverless.
9
+ // Add the Upstash integration in the Vercel dashboard and these variables appear.
10
+ const analytics = createTallymark({
11
+ store: upstashRestStore({
12
+ url: process.env.UPSTASH_REDIS_REST_URL!,
13
+ token: process.env.UPSTASH_REDIS_REST_TOKEN!,
14
+ }),
15
+ secret: process.env.ANALYTICS_SECRET,
16
+ apiKey: process.env.ANALYTICS_API_KEY,
17
+ basePath: '/api/analytics',
18
+ allowedHosts: ['example.com'], // only record your own sites
19
+ strictOrigin: true, // and only when the browser says the hit came from them
20
+ })
21
+
22
+ export const { GET, POST, OPTIONS } = vercel(analytics)
@@ -0,0 +1,4 @@
1
+ {
2
+ "rewrites": [{ "source": "/api/analytics/:path*", "destination": "/api/analytics" }],
3
+ "crons": [{ "path": "/api/analytics-cron", "schedule": "0 3 * * *" }]
4
+ }