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.
- package/LICENSE +661 -0
- package/README.md +234 -2
- package/SECURITY.md +37 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +124 -0
- package/dist/cloudflare.d.ts +9 -0
- package/dist/cloudflare.js +53 -0
- package/dist/hit.d.ts +83 -0
- package/dist/hit.js +301 -0
- package/dist/http.d.ts +36 -0
- package/dist/http.js +393 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +4 -0
- package/dist/node.d.ts +40 -0
- package/dist/node.js +66 -0
- package/dist/query.d.ts +31 -0
- package/dist/query.js +699 -0
- package/dist/react.d.ts +27 -0
- package/dist/react.js +34 -0
- package/dist/script.d.ts +17 -0
- package/dist/script.js +147 -0
- package/dist/stores.d.ts +129 -0
- package/dist/stores.js +393 -0
- package/dist/tallymark.d.ts +49 -0
- package/dist/tallymark.js +265 -0
- package/dist/types.d.ts +306 -0
- package/dist/types.js +1 -0
- package/dist/vercel.d.ts +33 -0
- package/dist/vercel.js +36 -0
- package/dist/webhook.d.ts +27 -0
- package/dist/webhook.js +61 -0
- package/docs/DEPLOYMENT.md +155 -0
- package/docs/HOW_IT_WORKS.md +106 -0
- package/docs/USAGE.md +237 -0
- package/examples/README.md +39 -0
- package/examples/browser/index.html +32 -0
- package/examples/browser/server.ts +34 -0
- package/examples/events/index.html +89 -0
- package/examples/events/server.ts +101 -0
- package/examples/frameworks/astro/[...path].ts +21 -0
- package/examples/frameworks/bun.ts +23 -0
- package/examples/frameworks/cloudflare.ts +37 -0
- package/examples/frameworks/deno.ts +26 -0
- package/examples/frameworks/express.ts +57 -0
- package/examples/frameworks/hono.ts +38 -0
- package/examples/frameworks/nextjs/app/api/analytics/[...route]/route.ts +7 -0
- package/examples/frameworks/nextjs/app/api/analytics-cron/route.ts +6 -0
- package/examples/frameworks/nextjs/app/layout.tsx +15 -0
- package/examples/frameworks/nextjs/app/page.tsx +21 -0
- package/examples/frameworks/nextjs/lib/analytics.ts +14 -0
- package/examples/frameworks/nextjs/vercel.json +3 -0
- package/examples/frameworks/react/main.tsx +32 -0
- package/examples/frameworks/sveltekit/+server.ts +26 -0
- package/examples/frameworks/vercel/api/analytics-cron.ts +9 -0
- package/examples/frameworks/vercel/api/analytics.ts +22 -0
- package/examples/frameworks/vercel/vercel.json +4 -0
- package/examples/http/Java.java +74 -0
- package/examples/http/curl.sh +46 -0
- package/examples/http/go.go +93 -0
- package/examples/http/php.php +74 -0
- package/examples/http/python.py +62 -0
- package/examples/http/ruby.rb +60 -0
- package/examples/library/basic.ts +95 -0
- package/examples/library/reports.ts +136 -0
- package/examples/library/stores.ts +57 -0
- package/examples/library/webhook-receiver.ts +30 -0
- package/llms.txt +235 -0
- package/package.json +116 -4
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// Tallymark from Java 11+, standard library only.
|
|
2
|
+
//
|
|
3
|
+
// TALLYMARK_API_KEY=... java examples/http/Java.java
|
|
4
|
+
//
|
|
5
|
+
// How this works
|
|
6
|
+
// 1. POST /collect records a hit. The body is JSON: { url, name?, props?, value?, referrer? }.
|
|
7
|
+
// Leave out `name` for a pageview; give a `name` for a custom event ("Signup", "Purchase").
|
|
8
|
+
// 2. GET /api/... reads numbers back. It needs the API key as "Authorization: Bearer <key>".
|
|
9
|
+
// Ranges: ?range=1h|24h|7d|30d|90d|365d. Break down with /api/top?by=country|channel|device|path|prop:plan ...
|
|
10
|
+
//
|
|
11
|
+
// Why forward the visitor's User-Agent and X-Forwarded-For?
|
|
12
|
+
// Tallymark works out browser, OS, device and country from the request it receives. If your backend sends
|
|
13
|
+
// the hit, that request is YOURS, so without these two headers every visitor would look like your server.
|
|
14
|
+
// Forward the real values from the request you are handling. (The server must run with
|
|
15
|
+
// TALLYMARK_TRUST_PROXY=true, or trustProxy: true, to read X-Forwarded-For.) If you cannot, the hit is
|
|
16
|
+
// still recorded, as an anonymous visitor with no device or location.
|
|
17
|
+
//
|
|
18
|
+
// Responses
|
|
19
|
+
// 202 accepted, OR deliberately ignored (bot, Do-Not-Track, your own IP). Ignored hits are not errors.
|
|
20
|
+
// 422 the url was not a valid http(s) URL 429 too many hits from one IP 403 origin not allowed
|
|
21
|
+
// 401 (read API) missing or wrong API key 503 the database is unavailable: retry later
|
|
22
|
+
import java.net.URI;
|
|
23
|
+
import java.net.http.HttpClient;
|
|
24
|
+
import java.net.http.HttpRequest;
|
|
25
|
+
import java.net.http.HttpResponse;
|
|
26
|
+
|
|
27
|
+
public class Java {
|
|
28
|
+
static final String BASE = System.getenv().getOrDefault("TALLYMARK_URL", "http://localhost:3000");
|
|
29
|
+
static final String KEY = System.getenv("TALLYMARK_API_KEY");
|
|
30
|
+
static final HttpClient HTTP = HttpClient.newHttpClient();
|
|
31
|
+
|
|
32
|
+
// Forward the *visitor's* User-Agent and IP from the request you are handling.
|
|
33
|
+
// (Run the server with TALLYMARK_TRUST_PROXY=true so it reads X-Forwarded-For.)
|
|
34
|
+
static final String VISITOR_UA =
|
|
35
|
+
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/130.0.0.0 Safari/537.36";
|
|
36
|
+
static final String VISITOR_IP = "203.0.113.9";
|
|
37
|
+
|
|
38
|
+
static String send(HttpRequest request) throws Exception {
|
|
39
|
+
HttpResponse<String> res = HTTP.send(request, HttpResponse.BodyHandlers.ofString());
|
|
40
|
+
if (res.statusCode() >= 300) {
|
|
41
|
+
throw new RuntimeException(request.method() + " " + request.uri().getPath() + " -> " + res.statusCode() + " " + res.body());
|
|
42
|
+
}
|
|
43
|
+
return res.body();
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
static void track(String json) throws Exception {
|
|
47
|
+
send(HttpRequest.newBuilder(URI.create(BASE + "/collect"))
|
|
48
|
+
.header("User-Agent", VISITOR_UA)
|
|
49
|
+
.header("X-Forwarded-For", VISITOR_IP)
|
|
50
|
+
.POST(HttpRequest.BodyPublishers.ofString(json))
|
|
51
|
+
.build());
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
static String read(String path) throws Exception {
|
|
55
|
+
return send(HttpRequest.newBuilder(URI.create(BASE + path))
|
|
56
|
+
.header("Authorization", "Bearer " + KEY)
|
|
57
|
+
.GET()
|
|
58
|
+
.build());
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
public static void main(String[] args) throws Exception {
|
|
62
|
+
if (KEY == null) throw new IllegalStateException("set TALLYMARK_API_KEY");
|
|
63
|
+
|
|
64
|
+
// 1. A pageview.
|
|
65
|
+
track("{\"url\":\"https://shop.example/pricing?utm_source=example-java\",\"referrer\":\"https://news.ycombinator.com/\"}");
|
|
66
|
+
|
|
67
|
+
// 2. A custom event with props and a numeric value (revenue).
|
|
68
|
+
track("{\"name\":\"Signup\",\"url\":\"https://shop.example/signup\",\"props\":{\"plan\":\"pro\"},\"value\":49}");
|
|
69
|
+
|
|
70
|
+
// 3. Read it back.
|
|
71
|
+
System.out.println(read("/api/summary?range=1h"));
|
|
72
|
+
System.out.println(read("/api/top?by=event&range=1h"));
|
|
73
|
+
}
|
|
74
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
#!/bin/sh
|
|
2
|
+
# Tallymark from the shell: the HTTP API is all you need, in any language.
|
|
3
|
+
# TALLYMARK_API_KEY=... sh examples/http/curl.sh
|
|
4
|
+
#
|
|
5
|
+
# How this works
|
|
6
|
+
# 1. POST /collect records a hit. The body is JSON: { url, name?, props?, value?, referrer? }.
|
|
7
|
+
# Leave out `name` for a pageview; give a `name` for a custom event ("Signup", "Purchase").
|
|
8
|
+
# 2. GET /api/... reads numbers back. It needs the API key as "Authorization: Bearer <key>".
|
|
9
|
+
# Ranges: ?range=1h|24h|7d|30d|90d|365d. Break down with /api/top?by=country|channel|device|path|prop:plan ...
|
|
10
|
+
#
|
|
11
|
+
# Why forward the visitor's User-Agent and X-Forwarded-For?
|
|
12
|
+
# Tallymark works out browser, OS, device and country from the request it receives. If your backend sends
|
|
13
|
+
# the hit, that request is YOURS, so without these two headers every visitor would look like your server.
|
|
14
|
+
# Forward the real values from the request you are handling. (The server must run with
|
|
15
|
+
# TALLYMARK_TRUST_PROXY=true, or trustProxy: true, to read X-Forwarded-For.) If you cannot, the hit is
|
|
16
|
+
# still recorded, as an anonymous visitor with no device or location.
|
|
17
|
+
#
|
|
18
|
+
# Responses
|
|
19
|
+
# 202 accepted, OR deliberately ignored (bot, Do-Not-Track, your own IP). Ignored hits are not errors.
|
|
20
|
+
# 422 the url was not a valid http(s) URL 429 too many hits from one IP 403 origin not allowed
|
|
21
|
+
# 401 (read API) missing or wrong API key 503 the database is unavailable: retry later
|
|
22
|
+
set -eu
|
|
23
|
+
|
|
24
|
+
URL="${TALLYMARK_URL:-http://localhost:3000}"
|
|
25
|
+
KEY="${TALLYMARK_API_KEY:?set TALLYMARK_API_KEY}"
|
|
26
|
+
|
|
27
|
+
# When you send hits from your own backend, forward the *visitor's* User-Agent and IP.
|
|
28
|
+
# (Run the server with TALLYMARK_TRUST_PROXY=true so it reads X-Forwarded-For.)
|
|
29
|
+
UA='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/130.0.0.0 Safari/537.36'
|
|
30
|
+
IP='203.0.113.9'
|
|
31
|
+
|
|
32
|
+
# 1. A pageview.
|
|
33
|
+
curl -fsS -X POST "$URL/collect" -H "user-agent: $UA" -H "x-forwarded-for: $IP" \
|
|
34
|
+
-d '{"url":"https://shop.example/pricing?utm_source=example-curl","referrer":"https://news.ycombinator.com/"}'
|
|
35
|
+
echo
|
|
36
|
+
|
|
37
|
+
# 2. A custom event with props and a numeric value (revenue).
|
|
38
|
+
curl -fsS -X POST "$URL/collect" -H "user-agent: $UA" -H "x-forwarded-for: $IP" \
|
|
39
|
+
-d '{"name":"Signup","url":"https://shop.example/signup","props":{"plan":"pro"},"value":49}'
|
|
40
|
+
echo
|
|
41
|
+
|
|
42
|
+
# 3. Read it back. Every /api/* route needs the API key.
|
|
43
|
+
curl -fsS "$URL/api/summary?range=1h" -H "authorization: Bearer $KEY"
|
|
44
|
+
echo
|
|
45
|
+
curl -fsS "$URL/api/top?by=event&range=1h" -H "authorization: Bearer $KEY"
|
|
46
|
+
echo
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// Tallymark from Go, standard library only.
|
|
2
|
+
//
|
|
3
|
+
// TALLYMARK_API_KEY=... go run examples/http/go.go
|
|
4
|
+
//
|
|
5
|
+
// How this works
|
|
6
|
+
// 1. POST /collect records a hit. The body is JSON: { url, name?, props?, value?, referrer? }.
|
|
7
|
+
// Leave out `name` for a pageview; give a `name` for a custom event ("Signup", "Purchase").
|
|
8
|
+
// 2. GET /api/... reads numbers back. It needs the API key as "Authorization: Bearer <key>".
|
|
9
|
+
// Ranges: ?range=1h|24h|7d|30d|90d|365d. Break down with /api/top?by=country|channel|device|path|prop:plan ...
|
|
10
|
+
//
|
|
11
|
+
// Why forward the visitor's User-Agent and X-Forwarded-For?
|
|
12
|
+
// Tallymark works out browser, OS, device and country from the request it receives. If your backend sends
|
|
13
|
+
// the hit, that request is YOURS, so without these two headers every visitor would look like your server.
|
|
14
|
+
// Forward the real values from the request you are handling. (The server must run with
|
|
15
|
+
// TALLYMARK_TRUST_PROXY=true, or trustProxy: true, to read X-Forwarded-For.) If you cannot, the hit is
|
|
16
|
+
// still recorded, as an anonymous visitor with no device or location.
|
|
17
|
+
//
|
|
18
|
+
// Responses
|
|
19
|
+
// 202 accepted, OR deliberately ignored (bot, Do-Not-Track, your own IP). Ignored hits are not errors.
|
|
20
|
+
// 422 the url was not a valid http(s) URL 429 too many hits from one IP 403 origin not allowed
|
|
21
|
+
// 401 (read API) missing or wrong API key 503 the database is unavailable: retry later
|
|
22
|
+
package main
|
|
23
|
+
|
|
24
|
+
import (
|
|
25
|
+
"bytes"
|
|
26
|
+
"encoding/json"
|
|
27
|
+
"fmt"
|
|
28
|
+
"io"
|
|
29
|
+
"net/http"
|
|
30
|
+
"os"
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
var (
|
|
34
|
+
baseURL = env("TALLYMARK_URL", "http://localhost:3000")
|
|
35
|
+
apiKey = os.Getenv("TALLYMARK_API_KEY")
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
// Forward the *visitor's* User-Agent and IP from the request you are handling.
|
|
39
|
+
// (Run the server with TALLYMARK_TRUST_PROXY=true so it reads X-Forwarded-For.)
|
|
40
|
+
const (
|
|
41
|
+
visitorUA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/130.0.0.0 Safari/537.36"
|
|
42
|
+
visitorIP = "203.0.113.9"
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
func env(key, fallback string) string {
|
|
46
|
+
if v := os.Getenv(key); v != "" {
|
|
47
|
+
return v
|
|
48
|
+
}
|
|
49
|
+
return fallback
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
func do(req *http.Request) string {
|
|
53
|
+
res, err := http.DefaultClient.Do(req)
|
|
54
|
+
if err != nil {
|
|
55
|
+
panic(err)
|
|
56
|
+
}
|
|
57
|
+
defer res.Body.Close()
|
|
58
|
+
out, _ := io.ReadAll(res.Body)
|
|
59
|
+
if res.StatusCode >= 300 {
|
|
60
|
+
panic(fmt.Sprintf("%s %s -> %d %s", req.Method, req.URL.Path, res.StatusCode, out))
|
|
61
|
+
}
|
|
62
|
+
return string(out)
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
func track(body map[string]any) {
|
|
66
|
+
payload, _ := json.Marshal(body)
|
|
67
|
+
req, _ := http.NewRequest("POST", baseURL+"/collect", bytes.NewReader(payload))
|
|
68
|
+
req.Header.Set("User-Agent", visitorUA)
|
|
69
|
+
req.Header.Set("X-Forwarded-For", visitorIP)
|
|
70
|
+
do(req)
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
func read(path string) string {
|
|
74
|
+
req, _ := http.NewRequest("GET", baseURL+path, nil)
|
|
75
|
+
req.Header.Set("Authorization", "Bearer "+apiKey)
|
|
76
|
+
return do(req)
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
func main() {
|
|
80
|
+
if apiKey == "" {
|
|
81
|
+
panic("set TALLYMARK_API_KEY")
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// 1. A pageview.
|
|
85
|
+
track(map[string]any{"url": "https://shop.example/pricing?utm_source=example-go", "referrer": "https://news.ycombinator.com/"})
|
|
86
|
+
|
|
87
|
+
// 2. A custom event with props and a numeric value (revenue).
|
|
88
|
+
track(map[string]any{"name": "Signup", "url": "https://shop.example/signup", "props": map[string]any{"plan": "pro"}, "value": 49})
|
|
89
|
+
|
|
90
|
+
// 3. Read it back.
|
|
91
|
+
fmt.Println(read("/api/summary?range=1h"))
|
|
92
|
+
fmt.Println(read("/api/top?by=event&range=1h"))
|
|
93
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
<?php
|
|
2
|
+
// Tallymark from PHP, no extensions or packages needed.
|
|
3
|
+
//
|
|
4
|
+
// TALLYMARK_API_KEY=... php examples/http/php.php
|
|
5
|
+
//
|
|
6
|
+
// How this works
|
|
7
|
+
// 1. POST /collect records a hit. The body is JSON: { url, name?, props?, value?, referrer? }.
|
|
8
|
+
// Leave out `name` for a pageview; give a `name` for a custom event ("Signup", "Purchase").
|
|
9
|
+
// 2. GET /api/... reads numbers back. It needs the API key as "Authorization: Bearer <key>".
|
|
10
|
+
// Ranges: ?range=1h|24h|7d|30d|90d|365d. Break down with /api/top?by=country|channel|device|path|prop:plan ...
|
|
11
|
+
//
|
|
12
|
+
// Why forward the visitor's User-Agent and X-Forwarded-For?
|
|
13
|
+
// Tallymark works out browser, OS, device and country from the request it receives. If your backend sends
|
|
14
|
+
// the hit, that request is YOURS, so without these two headers every visitor would look like your server.
|
|
15
|
+
// Forward the real values from the request you are handling. (The server must run with
|
|
16
|
+
// TALLYMARK_TRUST_PROXY=true, or trustProxy: true, to read X-Forwarded-For.) If you cannot, the hit is
|
|
17
|
+
// still recorded, as an anonymous visitor with no device or location.
|
|
18
|
+
//
|
|
19
|
+
// Responses
|
|
20
|
+
// 202 accepted, OR deliberately ignored (bot, Do-Not-Track, your own IP). Ignored hits are not errors.
|
|
21
|
+
// 422 the url was not a valid http(s) URL 429 too many hits from one IP 403 origin not allowed
|
|
22
|
+
// 401 (read API) missing or wrong API key 503 the database is unavailable: retry later
|
|
23
|
+
|
|
24
|
+
$url = getenv('TALLYMARK_URL') ?: 'http://localhost:3000';
|
|
25
|
+
$key = getenv('TALLYMARK_API_KEY') ?: die("set TALLYMARK_API_KEY\n");
|
|
26
|
+
|
|
27
|
+
// Forward the *visitor's* User-Agent and IP from the request you are handling.
|
|
28
|
+
// (Run the server with TALLYMARK_TRUST_PROXY=true so it reads X-Forwarded-For.)
|
|
29
|
+
$visitor = [
|
|
30
|
+
'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/130.0.0.0 Safari/537.36',
|
|
31
|
+
'X-Forwarded-For: 203.0.113.9',
|
|
32
|
+
];
|
|
33
|
+
|
|
34
|
+
function call(string $method, string $path, array $headers = [], ?array $body = null): string {
|
|
35
|
+
global $url;
|
|
36
|
+
if ($body !== null) {
|
|
37
|
+
$headers[] = 'Content-Type: application/json';
|
|
38
|
+
}
|
|
39
|
+
$ctx = stream_context_create(['http' => [
|
|
40
|
+
'method' => $method,
|
|
41
|
+
'header' => implode("\r\n", $headers),
|
|
42
|
+
'content' => $body === null ? '' : json_encode($body),
|
|
43
|
+
'ignore_errors' => true,
|
|
44
|
+
]]);
|
|
45
|
+
// A stream (not file_get_contents) so the status line is available on every PHP version.
|
|
46
|
+
$stream = fopen($url . $path, 'r', false, $ctx);
|
|
47
|
+
$out = stream_get_contents($stream);
|
|
48
|
+
$status = (int) explode(' ', stream_get_meta_data($stream)['wrapper_data'][0])[1];
|
|
49
|
+
fclose($stream);
|
|
50
|
+
if ($status >= 300) {
|
|
51
|
+
throw new RuntimeException("$method $path -> $status $out");
|
|
52
|
+
}
|
|
53
|
+
return $out;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function track(array $body): void {
|
|
57
|
+
global $visitor;
|
|
58
|
+
call('POST', '/collect', $visitor, $body);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function read(string $path): string {
|
|
62
|
+
global $key;
|
|
63
|
+
return call('GET', $path, ["Authorization: Bearer $key"]);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// 1. A pageview.
|
|
67
|
+
track(['url' => 'https://shop.example/pricing?utm_source=example-php', 'referrer' => 'https://news.ycombinator.com/']);
|
|
68
|
+
|
|
69
|
+
// 2. A custom event with props and a numeric value (revenue).
|
|
70
|
+
track(['name' => 'Signup', 'url' => 'https://shop.example/signup', 'props' => ['plan' => 'pro'], 'value' => 49]);
|
|
71
|
+
|
|
72
|
+
// 3. Read it back.
|
|
73
|
+
echo read('/api/summary?range=1h'), "\n";
|
|
74
|
+
echo read('/api/top?by=event&range=1h'), "\n";
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Tallymark from Python, standard library only.
|
|
3
|
+
|
|
4
|
+
TALLYMARK_API_KEY=... python3 examples/http/python.py
|
|
5
|
+
|
|
6
|
+
How this works
|
|
7
|
+
1. POST /collect records a hit. The body is JSON: { url, name?, props?, value?, referrer? }.
|
|
8
|
+
Leave out `name` for a pageview; give a `name` for a custom event ("Signup", "Purchase").
|
|
9
|
+
2. GET /api/... reads numbers back. It needs the API key as "Authorization: Bearer <key>".
|
|
10
|
+
Ranges: ?range=1h|24h|7d|30d|90d|365d. Break down with /api/top?by=country|channel|device|path|prop:plan ...
|
|
11
|
+
|
|
12
|
+
Why forward the visitor's User-Agent and X-Forwarded-For?
|
|
13
|
+
Tallymark works out browser, OS, device and country from the request it receives. If your backend sends
|
|
14
|
+
the hit, that request is YOURS, so without these two headers every visitor would look like your server.
|
|
15
|
+
Forward the real values from the request you are handling. (The server must run with
|
|
16
|
+
TALLYMARK_TRUST_PROXY=true, or trustProxy: true, to read X-Forwarded-For.) If you cannot, the hit is
|
|
17
|
+
still recorded, as an anonymous visitor with no device or location.
|
|
18
|
+
|
|
19
|
+
Responses
|
|
20
|
+
202 accepted, OR deliberately ignored (bot, Do-Not-Track, your own IP). Ignored hits are not errors.
|
|
21
|
+
422 the url was not a valid http(s) URL 429 too many hits from one IP 403 origin not allowed
|
|
22
|
+
401 (read API) missing or wrong API key 503 the database is unavailable: retry later
|
|
23
|
+
"""
|
|
24
|
+
import json
|
|
25
|
+
import os
|
|
26
|
+
import urllib.request
|
|
27
|
+
|
|
28
|
+
URL = os.environ.get("TALLYMARK_URL", "http://localhost:3000")
|
|
29
|
+
KEY = os.environ["TALLYMARK_API_KEY"]
|
|
30
|
+
|
|
31
|
+
# Forward the *visitor's* User-Agent and IP from the request you are handling.
|
|
32
|
+
# (Run the server with TALLYMARK_TRUST_PROXY=true so it reads X-Forwarded-For.)
|
|
33
|
+
VISITOR = {
|
|
34
|
+
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/130.0.0.0 Safari/537.36",
|
|
35
|
+
"X-Forwarded-For": "203.0.113.9",
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def call(method, path, body=None, headers=None):
|
|
40
|
+
data = json.dumps(body).encode() if body is not None else None
|
|
41
|
+
req = urllib.request.Request(URL + path, data=data, method=method, headers=headers or {})
|
|
42
|
+
with urllib.request.urlopen(req) as res:
|
|
43
|
+
return json.load(res)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def track(body):
|
|
47
|
+
return call("POST", "/collect", body, VISITOR)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def read(path):
|
|
51
|
+
return call("GET", path, headers={"Authorization": f"Bearer {KEY}"})
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
# 1. A pageview.
|
|
55
|
+
track({"url": "https://shop.example/pricing?utm_source=example-python", "referrer": "https://news.ycombinator.com/"})
|
|
56
|
+
|
|
57
|
+
# 2. A custom event with props and a numeric value (revenue).
|
|
58
|
+
track({"name": "Signup", "url": "https://shop.example/signup", "props": {"plan": "pro"}, "value": 49})
|
|
59
|
+
|
|
60
|
+
# 3. Read it back.
|
|
61
|
+
print(read("/api/summary?range=1h")["data"])
|
|
62
|
+
print(read("/api/top?by=event&range=1h")["data"])
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
# Tallymark from Ruby, standard library only.
|
|
2
|
+
#
|
|
3
|
+
# TALLYMARK_API_KEY=... ruby examples/http/ruby.rb
|
|
4
|
+
#
|
|
5
|
+
# How this works
|
|
6
|
+
# 1. POST /collect records a hit. The body is JSON: { url, name?, props?, value?, referrer? }.
|
|
7
|
+
# Leave out `name` for a pageview; give a `name` for a custom event ("Signup", "Purchase").
|
|
8
|
+
# 2. GET /api/... reads numbers back. It needs the API key as "Authorization: Bearer <key>".
|
|
9
|
+
# Ranges: ?range=1h|24h|7d|30d|90d|365d. Break down with /api/top?by=country|channel|device|path|prop:plan ...
|
|
10
|
+
#
|
|
11
|
+
# Why forward the visitor's User-Agent and X-Forwarded-For?
|
|
12
|
+
# Tallymark works out browser, OS, device and country from the request it receives. If your backend sends
|
|
13
|
+
# the hit, that request is YOURS, so without these two headers every visitor would look like your server.
|
|
14
|
+
# Forward the real values from the request you are handling. (The server must run with
|
|
15
|
+
# TALLYMARK_TRUST_PROXY=true, or trustProxy: true, to read X-Forwarded-For.) If you cannot, the hit is
|
|
16
|
+
# still recorded, as an anonymous visitor with no device or location.
|
|
17
|
+
#
|
|
18
|
+
# Responses
|
|
19
|
+
# 202 accepted, OR deliberately ignored (bot, Do-Not-Track, your own IP). Ignored hits are not errors.
|
|
20
|
+
# 422 the url was not a valid http(s) URL 429 too many hits from one IP 403 origin not allowed
|
|
21
|
+
# 401 (read API) missing or wrong API key 503 the database is unavailable: retry later
|
|
22
|
+
require 'json'
|
|
23
|
+
require 'net/http'
|
|
24
|
+
|
|
25
|
+
BASE = URI(ENV.fetch('TALLYMARK_URL', 'http://localhost:3000'))
|
|
26
|
+
KEY = ENV.fetch('TALLYMARK_API_KEY')
|
|
27
|
+
|
|
28
|
+
# Forward the *visitor's* User-Agent and IP from the request you are handling.
|
|
29
|
+
# (Run the server with TALLYMARK_TRUST_PROXY=true so it reads X-Forwarded-For.)
|
|
30
|
+
VISITOR = {
|
|
31
|
+
'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/130.0.0.0 Safari/537.36',
|
|
32
|
+
'X-Forwarded-For' => '203.0.113.9'
|
|
33
|
+
}.freeze
|
|
34
|
+
|
|
35
|
+
def call(request)
|
|
36
|
+
res = Net::HTTP.start(BASE.host, BASE.port) { |http| http.request(request) }
|
|
37
|
+
raise "#{request.method} #{request.path} -> #{res.code} #{res.body}" unless res.code.to_i < 300
|
|
38
|
+
|
|
39
|
+
res.body
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
def track(body)
|
|
43
|
+
request = Net::HTTP::Post.new('/collect', VISITOR)
|
|
44
|
+
request.body = body.to_json
|
|
45
|
+
call(request)
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
def read(path)
|
|
49
|
+
call(Net::HTTP::Get.new(path, 'Authorization' => "Bearer #{KEY}"))
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
# 1. A pageview.
|
|
53
|
+
track(url: 'https://shop.example/pricing?utm_source=example-ruby', referrer: 'https://news.ycombinator.com/')
|
|
54
|
+
|
|
55
|
+
# 2. A custom event with props and a numeric value (revenue).
|
|
56
|
+
track(name: 'Signup', url: 'https://shop.example/signup', props: { plan: 'pro' }, value: 49)
|
|
57
|
+
|
|
58
|
+
# 3. Read it back.
|
|
59
|
+
puts read('/api/summary?range=1h')
|
|
60
|
+
puts read('/api/top?by=event&range=1h')
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
// bun examples/library/basic.ts
|
|
2
|
+
//
|
|
3
|
+
// Tallymark as a plain library: no server, no database, no browser.
|
|
4
|
+
// This is the smallest way to see what it does: record hits from your own code, then ask questions.
|
|
5
|
+
//
|
|
6
|
+
// In a real app you rarely call track() for pageviews yourself. The browser script (or the
|
|
7
|
+
// <Analytics /> component) sends those automatically. track() / trackRequest() are for events
|
|
8
|
+
// that happen on your server, and for apps that have no browser at all (a CLI, a game server).
|
|
9
|
+
import { createTallymark, memoryStore, mirrorStore, webhookSink } from 'tallymark'
|
|
10
|
+
|
|
11
|
+
const tm = createTallymark({
|
|
12
|
+
// Salts the anonymous visitor hash. Use a long random value and keep it private.
|
|
13
|
+
// Changing it makes every existing visitor look new, which is a quick way to "forget" everyone.
|
|
14
|
+
secret: 'change-me-to-a-long-random-string',
|
|
15
|
+
|
|
16
|
+
// Where events are kept. The default is in-memory (gone on restart): perfect for a demo.
|
|
17
|
+
// Swap in pgStore(...), d1Store(...), bunSqliteStore(...), upstashRestStore(...) for real use.
|
|
18
|
+
store: memoryStore(),
|
|
19
|
+
|
|
20
|
+
// Ignore hits from these IP addresses: your own office, uptime checks.
|
|
21
|
+
excludeIps: ['203.0.113.7'],
|
|
22
|
+
|
|
23
|
+
// Failures never crash a request, so they are reported here instead. Send them to your logger.
|
|
24
|
+
onError: (error, { where }) => console.error(where, error),
|
|
25
|
+
})
|
|
26
|
+
|
|
27
|
+
const chrome =
|
|
28
|
+
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/130.0.0.0 Safari/537.36'
|
|
29
|
+
|
|
30
|
+
// ── 1. Record hits ──────────────────────────────────────────────────────────────────────────
|
|
31
|
+
// Each hit needs a url. ip and userAgent identify the visitor (they are hashed with a daily salt
|
|
32
|
+
// and never stored). Everything else is optional context you happen to know.
|
|
33
|
+
const alice = { ip: '198.51.100.1', userAgent: chrome, country: 'DE', language: 'de-DE' }
|
|
34
|
+
const bob = { ip: '198.51.100.2', userAgent: chrome, country: 'US', language: 'en-US' }
|
|
35
|
+
|
|
36
|
+
// A pageview. The referrer says where the visitor came from; ?utm_* in the url is the campaign.
|
|
37
|
+
await tm.track({
|
|
38
|
+
url: 'https://shop.example/',
|
|
39
|
+
referrer: 'https://news.ycombinator.com/',
|
|
40
|
+
...alice,
|
|
41
|
+
})
|
|
42
|
+
await tm.track({ url: 'https://shop.example/pricing?utm_source=newsletter', ...alice })
|
|
43
|
+
|
|
44
|
+
// A custom event: a `name`, optional `props` to break it down by later, optional `value` to sum.
|
|
45
|
+
await tm.track({
|
|
46
|
+
name: 'Signup',
|
|
47
|
+
url: 'https://shop.example/signup',
|
|
48
|
+
props: { plan: 'pro' },
|
|
49
|
+
value: 49,
|
|
50
|
+
...alice,
|
|
51
|
+
})
|
|
52
|
+
|
|
53
|
+
await tm.track({ url: 'https://shop.example/', ...bob })
|
|
54
|
+
|
|
55
|
+
// ── 2. Hits can be skipped, and you are told why ───────────────────────────────────────────
|
|
56
|
+
// track() never throws. It returns { ok: true, event } or { ok: false, reason }.
|
|
57
|
+
// Reasons: 'bot' 'dnt' 'excluded' 'spam' 'host' 'invalid' 'storage' ...
|
|
58
|
+
const bot = await tm.track({
|
|
59
|
+
url: 'https://shop.example/',
|
|
60
|
+
userAgent: 'Googlebot/2.1',
|
|
61
|
+
ip: '66.249.66.1',
|
|
62
|
+
})
|
|
63
|
+
console.log('bot ->', bot) // { ok: false, reason: 'bot' }
|
|
64
|
+
|
|
65
|
+
// ── 3. Ask questions ───────────────────────────────────────────────────────────────────────
|
|
66
|
+
// The first argument is a time range: '1h' '24h' '7d' '30d' '90d' '365d', or { from, to } in ms.
|
|
67
|
+
console.log('summary', await tm.summary('24h')) // visitors, pageviews, bounce rate, revenue ...
|
|
68
|
+
console.log('top pages', await tm.top('path', '24h')) // any dimension: path, country, channel, device ...
|
|
69
|
+
console.log('top countries', await tm.top('country', '24h'))
|
|
70
|
+
console.log('revenue by event', await tm.top('event', '24h')) // counts events and adds up their `value`
|
|
71
|
+
console.log('only Germany', await tm.summary('24h', { country: 'DE' })) // the third argument filters
|
|
72
|
+
console.log('vs. previous period', (await tm.compare('24h')).delta.pageviews)
|
|
73
|
+
|
|
74
|
+
// ── 4. A funnel ────────────────────────────────────────────────────────────────────────────
|
|
75
|
+
// Of the visitors who saw the home page, how many reached pricing, then signed up?
|
|
76
|
+
// A step is a page { path } (a trailing * matches a prefix) or an event { event }.
|
|
77
|
+
console.log(
|
|
78
|
+
'funnel',
|
|
79
|
+
await tm.funnel([{ path: '/' }, { path: '/pricing' }, { event: 'Signup' }], '24h'),
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
// ── 5. Backup and restore ──────────────────────────────────────────────────────────────────
|
|
83
|
+
// One JSON event per line. Works between any two stores, so it doubles as a migration tool.
|
|
84
|
+
const backup = await tm.export('24h')
|
|
85
|
+
const restored = createTallymark({ secret: 'x' })
|
|
86
|
+
console.log('restored', await restored.import(backup)) // { imported: 4, skipped: 0 }
|
|
87
|
+
|
|
88
|
+
// ── 6. Optional: backups and third parties ─────────────────────────────────────────────────
|
|
89
|
+
// mirrorStore: every event is written to the primary and copied to the backups.
|
|
90
|
+
// forward: every event is also POSTed (signed) to a URL you control: Zapier, n8n, your own service.
|
|
91
|
+
const withBackups = createTallymark({
|
|
92
|
+
store: mirrorStore(memoryStore(), memoryStore()),
|
|
93
|
+
forward: webhookSink({ url: 'https://hooks.example.com/tallymark', secret: 'whsec_123' }),
|
|
94
|
+
})
|
|
95
|
+
void withBackups
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
// bun examples/library/reports.ts
|
|
2
|
+
//
|
|
3
|
+
// Every kind of question Tallymark answers, on a small made-up day of traffic.
|
|
4
|
+
//
|
|
5
|
+
// IMPORTANT: the traffic below is typed in by hand ONLY so this file can run on its own.
|
|
6
|
+
// In a real app you write none of it. The browser script (<script src=".../script.js">) or the
|
|
7
|
+
// <Analytics /> component records, automatically and with no code:
|
|
8
|
+
// pageviews, referrer, ?utm_* campaign, browser, OS, device, language, screen size,
|
|
9
|
+
// country/region/city/timezone (from your host's headers), time on page, and scroll depth.
|
|
10
|
+
// The only thing you add yourself is a custom event, e.g. data-tally="Signup" on a button.
|
|
11
|
+
// Everything after the "Ask" comments is what you would run to read the numbers back.
|
|
12
|
+
import { createTallymark } from 'tallymark'
|
|
13
|
+
|
|
14
|
+
const now = Date.now()
|
|
15
|
+
const tm = createTallymark({ secret: 'demo', now: () => now })
|
|
16
|
+
|
|
17
|
+
const WIN =
|
|
18
|
+
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/130.0.0.0 Safari/537.36'
|
|
19
|
+
const IPHONE =
|
|
20
|
+
'Mozilla/5.0 (iPhone; CPU iPhone OS 17_2 like Mac OS X) AppleWebKit/605.1.15 Version/17.2 Mobile/15E148 Safari/604.1'
|
|
21
|
+
|
|
22
|
+
/** One visitor's hits. Geo and device are the same for every hit, as in real traffic.
|
|
23
|
+
* secondsAgo: when it happened. extra: the page's referrer, or an engagement beacon (time on page). */
|
|
24
|
+
async function visit(
|
|
25
|
+
who: Record<string, unknown>,
|
|
26
|
+
hits: Array<[secondsAgo: number, path: string, extra?: Record<string, unknown>]>,
|
|
27
|
+
) {
|
|
28
|
+
for (const [secondsAgo, path, extra] of hits) {
|
|
29
|
+
await tm.track({
|
|
30
|
+
url: `https://shop.example${path}`,
|
|
31
|
+
ts: now - secondsAgo * 1000,
|
|
32
|
+
...who,
|
|
33
|
+
...extra,
|
|
34
|
+
})
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// Alice: found us on Google, read the home page 40 s, then pricing, then signed up and paid.
|
|
39
|
+
// (The `engagement` rows are what the browser script reports on its own when a visitor leaves a page.)
|
|
40
|
+
await visit(
|
|
41
|
+
{
|
|
42
|
+
ip: '10.0.0.1',
|
|
43
|
+
userAgent: WIN,
|
|
44
|
+
country: 'DE',
|
|
45
|
+
city: 'Berlin',
|
|
46
|
+
timezone: 'Europe/Berlin',
|
|
47
|
+
language: 'de-DE',
|
|
48
|
+
screenWidth: 1920,
|
|
49
|
+
},
|
|
50
|
+
[
|
|
51
|
+
[300, '/', { referrer: 'https://www.google.com/' }],
|
|
52
|
+
[260, '/', { name: 'engagement', duration: 40_000, scroll: 70 }], // time on page, reported by the browser script
|
|
53
|
+
[259, '/pricing'],
|
|
54
|
+
[230, '/pricing', { name: 'engagement', duration: 25_000, scroll: 100 }],
|
|
55
|
+
[229, '/signup'],
|
|
56
|
+
[200, '/signup', { name: 'Signup', props: { plan: 'pro' }, value: 49 }],
|
|
57
|
+
],
|
|
58
|
+
)
|
|
59
|
+
// Bob: came from a newsletter on his phone, looked at pricing, left.
|
|
60
|
+
await visit(
|
|
61
|
+
{
|
|
62
|
+
ip: '10.0.0.2',
|
|
63
|
+
userAgent: IPHONE,
|
|
64
|
+
country: 'US',
|
|
65
|
+
city: 'Austin',
|
|
66
|
+
language: 'en-US',
|
|
67
|
+
screenWidth: 390,
|
|
68
|
+
},
|
|
69
|
+
[
|
|
70
|
+
[200, '/pricing?utm_source=newsletter&utm_medium=email&utm_campaign=spring'],
|
|
71
|
+
[170, '/pricing', { name: 'engagement', duration: 12_000, scroll: 35 }],
|
|
72
|
+
],
|
|
73
|
+
)
|
|
74
|
+
// Carol: arrived directly, bounced.
|
|
75
|
+
await visit(
|
|
76
|
+
{
|
|
77
|
+
ip: '10.0.0.3',
|
|
78
|
+
userAgent: WIN,
|
|
79
|
+
country: 'DE',
|
|
80
|
+
city: 'Munich',
|
|
81
|
+
language: 'de-DE',
|
|
82
|
+
screenWidth: 1366,
|
|
83
|
+
},
|
|
84
|
+
[[100, '/']],
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
const show = (title: string, value: unknown) =>
|
|
88
|
+
console.log(`\n── ${title}\n`, JSON.stringify(value, null, 1).replace(/\n\s*/g, ' '))
|
|
89
|
+
|
|
90
|
+
// Ask ───────────────────────────────────────────────────────────────────────
|
|
91
|
+
// Totals ---------------------------------------------------------------------
|
|
92
|
+
show('summary', await tm.summary('24h')) // pageviews, visitors, sessions, bounce rate, time on site, revenue
|
|
93
|
+
show('vs. the previous period', (await tm.compare('24h')).delta.pageviews)
|
|
94
|
+
|
|
95
|
+
// Over time: hour, day, week or month ------------------------------------------
|
|
96
|
+
show(
|
|
97
|
+
'timeseries (hourly)',
|
|
98
|
+
(await tm.timeseries('24h')).filter((p) => p.pageviews),
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
// Breakdowns: any dimension, optionally filtered -------------------------------
|
|
102
|
+
show('top pages, with time on page and scroll depth', await tm.top('path', '24h'))
|
|
103
|
+
show('where visitors come from', await tm.top('channel', '24h'))
|
|
104
|
+
show('sources', await tm.top('source', '24h'))
|
|
105
|
+
show('countries', await tm.top('country', '24h'))
|
|
106
|
+
show('continents', await tm.top('continent', '24h'))
|
|
107
|
+
show('devices', await tm.top('device', '24h'))
|
|
108
|
+
show('screen sizes', await tm.top('screen', '24h'))
|
|
109
|
+
show('browsers and versions', await tm.top('browser_version', '24h'))
|
|
110
|
+
show('operating systems', await tm.top('os', '24h'))
|
|
111
|
+
show('languages', await tm.top('language', '24h'))
|
|
112
|
+
show('entry pages', await tm.top('entry_page', '24h'))
|
|
113
|
+
show('exit pages', await tm.top('exit_page', '24h'))
|
|
114
|
+
show('only mobile visitors', await tm.top('path', '24h', { device: 'mobile' }))
|
|
115
|
+
|
|
116
|
+
// Events: counts, revenue, and any custom property ------------------------------
|
|
117
|
+
show('events, with revenue', await tm.top('event', '24h'))
|
|
118
|
+
show(
|
|
119
|
+
"revenue by source (events inherit the visitor's first source)",
|
|
120
|
+
await tm.top('event', '24h', { channel: 'Organic Search' }),
|
|
121
|
+
)
|
|
122
|
+
show('events broken down by a property', await tm.top('event', '24h', { 'prop:plan': 'pro' }))
|
|
123
|
+
|
|
124
|
+
// Paths travelled ----------------------------------------------------------------
|
|
125
|
+
show('funnel', await tm.funnel([{ path: '/' }, { path: '/pricing' }, { event: 'Signup' }], '24h'))
|
|
126
|
+
show('common journeys', await tm.journeys('24h', {}, { depth: 3 }))
|
|
127
|
+
const [alice] = await tm.sessions('24h', { screen: 'desktop' }) // Alice's 1920px-wide window
|
|
128
|
+
show('one session, step by step', {
|
|
129
|
+
source: alice?.source,
|
|
130
|
+
seconds: alice?.seconds,
|
|
131
|
+
revenue: alice?.revenue,
|
|
132
|
+
steps: alice?.steps,
|
|
133
|
+
})
|
|
134
|
+
|
|
135
|
+
// Live ------------------------------------------------------------------------
|
|
136
|
+
show('realtime', await tm.realtime())
|