@tansy/analytics 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/logic.js ADDED
@@ -0,0 +1,163 @@
1
+ import { breakdown, daysIn } from "./provider";
2
+ export const TABLES = ["pages", "referrers", "countries", "devices", "browsers"];
3
+ /** Enough for the pages anyone looks at, small enough to keep a day under the store's limit. */
4
+ export const TABLE_LIMITS = { pages: 500, referrers: 200, countries: 250, devices: 10, browsers: 20 };
5
+ export const OTHER = "(other)";
6
+ export const emptyDay = () => ({ views: 0, visitors: 0, pages: {}, referrers: {}, countries: {}, devices: {}, browsers: {} });
7
+ const bump = (table, key, by = 1) => {
8
+ table[key] = (Object.hasOwn(table, key) ? table[key] : 0) + by;
9
+ };
10
+ export function addHit(day, hit) {
11
+ day.views += 1;
12
+ if (hit.newVisitor)
13
+ day.visitors += 1;
14
+ bump(day.pages, hit.path);
15
+ if (hit.referrer)
16
+ bump(day.referrers, hit.referrer);
17
+ if (hit.country)
18
+ bump(day.countries, hit.country);
19
+ bump(day.devices, hit.device);
20
+ bump(day.browsers, hit.browser);
21
+ }
22
+ /** Keeps the biggest `limit` entries, and adds the rest to "(other)". */
23
+ export function capTable(table, limit) {
24
+ const entries = Object.entries(table);
25
+ if (entries.length <= limit)
26
+ return table;
27
+ entries.sort((a, b) => (a[0] === OTHER ? 1 : b[0] === OTHER ? -1 : b[1] - a[1]));
28
+ const kept = Object.fromEntries(entries.slice(0, limit - 1).filter(([name]) => name !== OTHER));
29
+ const rest = entries.filter(([name]) => !Object.hasOwn(kept, name)).reduce((sum, [, count]) => sum + count, 0);
30
+ if (rest)
31
+ kept[OTHER] = rest;
32
+ return kept;
33
+ }
34
+ /** A stored day, read defensively: anything that isn't a count is left out. */
35
+ export function readDay(value) {
36
+ const day = emptyDay();
37
+ if (!value || typeof value !== "object")
38
+ return day;
39
+ const source = value;
40
+ const count = (raw) => (typeof raw === "number" && Number.isFinite(raw) && raw > 0 ? Math.floor(raw) : 0);
41
+ day.views = count(source.views);
42
+ day.visitors = count(source.visitors);
43
+ for (const table of TABLES) {
44
+ const raw = source[table];
45
+ if (!raw || typeof raw !== "object")
46
+ continue;
47
+ for (const [name, value] of Object.entries(raw))
48
+ if (count(value))
49
+ day[table][name] = count(value);
50
+ }
51
+ return day;
52
+ }
53
+ /** Adds `delta` to `day`, capping each table. */
54
+ export function mergeDay(day, delta) {
55
+ const merged = emptyDay();
56
+ merged.views = day.views + delta.views;
57
+ merged.visitors = day.visitors + delta.visitors;
58
+ for (const table of TABLES) {
59
+ const sum = { ...day[table] };
60
+ for (const [name, count] of Object.entries(delta[table]))
61
+ bump(sum, name, count);
62
+ merged[table] = capTable(sum, TABLE_LIMITS[table]);
63
+ }
64
+ return merged;
65
+ }
66
+ /** Days' counts as a report. Visitors add up per day, so one person on two days counts twice. */
67
+ export function reportFrom(range, days) {
68
+ const series = daysIn(range).map((date) => ({ date, views: days.get(date)?.views ?? 0, visitors: days.get(date)?.visitors ?? 0 }));
69
+ const sum = (table) => {
70
+ const total = {};
71
+ for (const day of days.values())
72
+ for (const [name, count] of Object.entries(day[table]))
73
+ bump(total, name, count);
74
+ return breakdown(Object.entries(total).map(([name, count]) => ({ name, count })));
75
+ };
76
+ return {
77
+ totals: { views: series.reduce((n, day) => n + day.views, 0), visitors: series.reduce((n, day) => n + day.visitors, 0) },
78
+ days: series,
79
+ pages: sum("pages"),
80
+ referrers: sum("referrers"),
81
+ countries: sum("countries"),
82
+ devices: sum("devices"),
83
+ browsers: sum("browsers"),
84
+ };
85
+ }
86
+ const BOT = /bot|crawl|spider|slurp|scrape|fetch|curl|wget|python|java\/|go-http|axios|node|headless|phantom|puppeteer|playwright|selenium|lighthouse|pagespeed|gtmetrix|pingdom|uptime|monitor|preview|facebookexternalhit|embedly|whatsapp|telegram|discord|slack|vercel|semrush|ahrefs|bingpreview/i;
87
+ /** Whether a page view comes from a program rather than a person. A missing browser name counts as a program. */
88
+ export const isBot = (userAgent) => !userAgent || userAgent.length < 10 || BOT.test(userAgent);
89
+ /** The browser's family, never its version. */
90
+ export function browserOf(userAgent) {
91
+ if (/Edg(e|A|iOS)?\//.test(userAgent))
92
+ return "Edge";
93
+ if (/OPR\/|Opera/.test(userAgent))
94
+ return "Opera";
95
+ if (/SamsungBrowser\//.test(userAgent))
96
+ return "Samsung Internet";
97
+ if (/Firefox\/|FxiOS\//.test(userAgent))
98
+ return "Firefox";
99
+ if (/Chrome\/|CriOS\//.test(userAgent))
100
+ return "Chrome";
101
+ if (/Safari\//.test(userAgent))
102
+ return "Safari";
103
+ return "Other";
104
+ }
105
+ /** From the screen's width, as Plausible does: it says nothing about the person. */
106
+ export function deviceOf(width) {
107
+ if (typeof width !== "number" || !Number.isFinite(width) || width <= 0)
108
+ return "Unknown";
109
+ if (width < 576)
110
+ return "Mobile";
111
+ if (width < 992)
112
+ return "Tablet";
113
+ return "Desktop";
114
+ }
115
+ const COUNTRY_HEADERS = ["cf-ipcountry", "x-vercel-ip-country", "cloudfront-viewer-country", "x-country-code", "fly-client-country"];
116
+ /** The country a CDN in front of the site says the visitor is in, when one does. The address itself is never looked at. */
117
+ export function countryOf(headers) {
118
+ for (const name of COUNTRY_HEADERS) {
119
+ const value = headers.get(name)?.trim().toUpperCase();
120
+ if (value && /^[A-Z]{2}$/.test(value) && value !== "XX" && value !== "T1")
121
+ return value;
122
+ }
123
+ return null;
124
+ }
125
+ /** Where the visitor came from: a campaign's `utm_source` or `ref`, or the other site's host. Links within the site count as none. */
126
+ export function referrerOf(referrer, source, ownHost) {
127
+ const named = source?.trim().toLowerCase().replace(/[^\w .-]/g, "").slice(0, 60);
128
+ if (named)
129
+ return named;
130
+ if (!referrer)
131
+ return null;
132
+ let url;
133
+ try {
134
+ url = new URL(referrer);
135
+ }
136
+ catch {
137
+ return null;
138
+ }
139
+ if (url.protocol !== "http:" && url.protocol !== "https:")
140
+ return null;
141
+ const host = url.hostname.toLowerCase().replace(/^www\./, "");
142
+ const own = ownHost?.toLowerCase().replace(/:\d+$/, "").replace(/^www\./, "");
143
+ return host && host !== own ? host.slice(0, 100) : null;
144
+ }
145
+ const MAX_PATH = 200;
146
+ /** The address without its query or fragment, or null for anything that isn't a site address. */
147
+ export function cleanPath(path) {
148
+ if (typeof path !== "string" || !path.startsWith("/") || path.startsWith("//"))
149
+ return null;
150
+ const bare = path.split(/[?#]/)[0];
151
+ if (/[\u0000-\u001f\s]/.test(bare))
152
+ return null;
153
+ const trimmed = bare.length > 1 ? bare.replace(/\/+$/, "") || "/" : bare;
154
+ return trimmed.slice(0, MAX_PATH);
155
+ }
156
+ /** Today in UTC, as YYYY-MM-DD. */
157
+ export const today = (now = new Date()) => now.toISOString().slice(0, 10);
158
+ /** The last `days` days up to today, inclusive. */
159
+ export function lastDays(days, now = new Date()) {
160
+ const from = new Date(now);
161
+ from.setUTCDate(from.getUTCDate() - (days - 1));
162
+ return { from: today(from), to: today(now) };
163
+ }
package/messages.d.ts ADDED
@@ -0,0 +1,143 @@
1
+ /** The analytics plugin's dashboard words, read as `t("ext.analytics.<key>")`. Each provider package adds its own settings' words. */
2
+ export declare const messages: {
3
+ en: {
4
+ section: string;
5
+ pages: {
6
+ analytics: string;
7
+ };
8
+ widgets: {
9
+ "analytics-overview": string;
10
+ };
11
+ description: string;
12
+ settings: {
13
+ collect: {
14
+ label: string;
15
+ description: string;
16
+ };
17
+ provider: {
18
+ label: string;
19
+ description: string;
20
+ options: {
21
+ none: string;
22
+ };
23
+ };
24
+ exclude: {
25
+ label: string;
26
+ description: string;
27
+ };
28
+ respectOptOut: {
29
+ label: string;
30
+ description: string;
31
+ };
32
+ retentionDays: {
33
+ label: string;
34
+ description: string;
35
+ };
36
+ };
37
+ tabs: {
38
+ settings: string;
39
+ };
40
+ range: string;
41
+ ranges: {
42
+ "7": string;
43
+ "30": string;
44
+ "90": string;
45
+ };
46
+ own: string;
47
+ totals: {
48
+ views: string;
49
+ visitors: string;
50
+ };
51
+ tables: {
52
+ pages: string;
53
+ referrers: string;
54
+ countries: string;
55
+ devices: string;
56
+ browsers: string;
57
+ };
58
+ direct: string;
59
+ none: string;
60
+ chart: string;
61
+ day: string;
62
+ openProvider: string;
63
+ failed: string;
64
+ off: string;
65
+ sentTo: string;
66
+ noKey: string;
67
+ visitorsNote: string;
68
+ widget: {
69
+ summary: string;
70
+ more: string;
71
+ };
72
+ };
73
+ ar: {
74
+ section: string;
75
+ pages: {
76
+ analytics: string;
77
+ };
78
+ widgets: {
79
+ "analytics-overview": string;
80
+ };
81
+ description: string;
82
+ settings: {
83
+ collect: {
84
+ label: string;
85
+ description: string;
86
+ };
87
+ provider: {
88
+ label: string;
89
+ description: string;
90
+ options: {
91
+ none: string;
92
+ };
93
+ };
94
+ exclude: {
95
+ label: string;
96
+ description: string;
97
+ };
98
+ respectOptOut: {
99
+ label: string;
100
+ description: string;
101
+ };
102
+ retentionDays: {
103
+ label: string;
104
+ description: string;
105
+ };
106
+ };
107
+ tabs: {
108
+ settings: string;
109
+ };
110
+ range: string;
111
+ ranges: {
112
+ "7": string;
113
+ "30": string;
114
+ "90": string;
115
+ };
116
+ own: string;
117
+ totals: {
118
+ views: string;
119
+ visitors: string;
120
+ };
121
+ tables: {
122
+ pages: string;
123
+ referrers: string;
124
+ countries: string;
125
+ devices: string;
126
+ browsers: string;
127
+ };
128
+ direct: string;
129
+ none: string;
130
+ chart: string;
131
+ day: string;
132
+ openProvider: string;
133
+ failed: string;
134
+ off: string;
135
+ sentTo: string;
136
+ noKey: string;
137
+ visitorsNote: string;
138
+ widget: {
139
+ summary: string;
140
+ more: string;
141
+ };
142
+ };
143
+ };
package/messages.js ADDED
@@ -0,0 +1,63 @@
1
+ /** The analytics plugin's dashboard words, read as `t("ext.analytics.<key>")`. Each provider package adds its own settings' words. */
2
+ export const messages = {
3
+ en: {
4
+ section: "Analytics",
5
+ pages: { analytics: "Analytics" },
6
+ widgets: { "analytics-overview": "Visitors" },
7
+ description: "Who visits the site, which pages they read and where they came from.",
8
+ settings: {
9
+ collect: { label: "Count page views here", description: "Counts views, visitors, pages and where visitors came from, with no cookies and nothing that could identify anyone. Shown on the dashboard." },
10
+ provider: { label: "Also send page views to", description: "An analytics service of your own. Fill in its settings below. Until they're set, nothing is sent to it.", options: { none: "None" } },
11
+ exclude: { label: "Addresses not to count", description: "One per line, such as /members. Each counts with everything under it." },
12
+ respectOptOut: { label: "Respect visitors who opt out", description: "Visitors whose browser sends Global Privacy Control or Do Not Track aren't sent to the outside service. The count here identifies no one, so it still counts them." },
13
+ retentionDays: { label: "Keep counts for (days)", description: "Older days are deleted each night." },
14
+ },
15
+ tabs: { settings: "Settings" },
16
+ range: "Date range",
17
+ ranges: { "7": "7 days", "30": "30 days", "90": "90 days" },
18
+ own: "This site",
19
+ totals: { views: "Page views", visitors: "Visitors" },
20
+ tables: { pages: "Top pages", referrers: "Where visitors came from", countries: "Countries", devices: "Devices", browsers: "Browsers" },
21
+ direct: "Direct or unknown",
22
+ none: "Nothing yet.",
23
+ chart: "Page views and visitors a day",
24
+ day: "{date}: {views} views, {visitors} visitors",
25
+ openProvider: "Open {provider}",
26
+ failed: "{provider} couldn't be read. Check its API key under Settings.",
27
+ off: "Nothing is counted yet. Turn on counting here, or choose a service, under Settings.",
28
+ sentTo: "Page views also go to {provider}.",
29
+ noKey: "Page views go to {provider}. Add its API key under Settings to see its numbers here.",
30
+ visitorsNote: "Visitors are counted once a day, so someone who comes back on another day counts again.",
31
+ widget: { summary: "{views} views from {visitors} visitors in the last 7 days.", more: "See more" },
32
+ },
33
+ ar: {
34
+ section: "التحليلات",
35
+ pages: { analytics: "التحليلات" },
36
+ widgets: { "analytics-overview": "الزوار" },
37
+ description: "من يزور الموقع، وأي الصفحات يقرأ، ومن أين جاء.",
38
+ settings: {
39
+ collect: { label: "عُدّ مشاهدات الصفحات هنا", description: "يعدّ المشاهدات والزوار والصفحات ومصادر الزيارات، دون ملفات تعريف ارتباط ودون أي شيء يمكن أن يدل على أحد. يظهر في لوحة التحكم." },
40
+ provider: { label: "أرسل المشاهدات أيضًا إلى", description: "خدمة تحليلات خاصة بك. املأ إعداداتها أدناه. حتى تُضبط، لا يُرسل إليها شيء.", options: { none: "لا شيء" } },
41
+ exclude: { label: "عناوين لا تُعدّ", description: "عنوان في كل سطر، مثل /members. يشمل كل عنوان ما تحته." },
42
+ respectOptOut: { label: "احترم الزوار الذين يرفضون التتبع", description: "الزوار الذين يرسل متصفحهم Global Privacy Control أو Do Not Track لا يُرسلون إلى الخدمة الخارجية. العدّ هنا لا يدل على أحد، فيبقى يعدّهم." },
43
+ retentionDays: { label: "احتفظ بالأعداد لمدة (أيام)", description: "تُحذف الأيام الأقدم كل ليلة." },
44
+ },
45
+ tabs: { settings: "الإعدادات" },
46
+ range: "الفترة الزمنية",
47
+ ranges: { "7": "7 أيام", "30": "30 يومًا", "90": "90 يومًا" },
48
+ own: "هذا الموقع",
49
+ totals: { views: "مشاهدات الصفحات", visitors: "الزوار" },
50
+ tables: { pages: "أكثر الصفحات زيارة", referrers: "من أين جاء الزوار", countries: "الدول", devices: "الأجهزة", browsers: "المتصفحات" },
51
+ direct: "مباشر أو غير معروف",
52
+ none: "لا شيء بعد.",
53
+ chart: "مشاهدات الصفحات والزوار في اليوم",
54
+ day: "{date}: {views} مشاهدة، {visitors} زائر",
55
+ openProvider: "افتح {provider}",
56
+ failed: "تعذرت قراءة {provider}. تحقق من مفتاح API في الإعدادات.",
57
+ off: "لا يُعدّ شيء بعد. فعّل العدّ هنا، أو اختر خدمة، من الإعدادات.",
58
+ sentTo: "تُرسل المشاهدات أيضًا إلى {provider}.",
59
+ noKey: "تُرسل المشاهدات إلى {provider}. أضف مفتاح API الخاص به في الإعدادات لترى أرقامه هنا.",
60
+ visitorsNote: "يُعدّ الزائر مرة في اليوم، فمن يعود في يوم آخر يُعدّ من جديد.",
61
+ widget: { summary: "{views} مشاهدة من {visitors} زائر في آخر 7 أيام.", more: "المزيد" },
62
+ },
63
+ };
package/package.json CHANGED
@@ -1,6 +1,46 @@
1
1
  {
2
2
  "name": "@tansy/analytics",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Page views for tansy: counted by the CMS with no cookies and nothing personal kept, or sent to Plausible, Umami, Google Analytics, Fathom or Matomo through a provider package, with the numbers on the dashboard.",
5
+ "keywords": [
6
+ "tansy",
7
+ "tansy-plugin",
8
+ "cms",
9
+ "nextjs"
10
+ ],
11
+ "license": "MIT",
12
+ "author": "Mohamed Salah <mohamedsalahsebai@gmail.com>",
13
+ "homepage": "https://github.com/mhmdsalahsebai/tansy",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/mhmdsalahsebai/tansy.git",
17
+ "directory": "plugins/analytics"
18
+ },
19
+ "bugs": "https://github.com/mhmdsalahsebai/tansy/issues",
20
+ "exports": {
21
+ ".": {
22
+ "types": "./index.d.ts",
23
+ "default": "./index.js"
24
+ },
25
+ "./provider": {
26
+ "types": "./provider.d.ts",
27
+ "default": "./provider.js"
28
+ },
29
+ "./admin": {
30
+ "types": "./admin.d.ts",
31
+ "default": "./admin.js"
32
+ },
33
+ "./render": {
34
+ "types": "./render.d.ts",
35
+ "default": "./render.js"
36
+ }
37
+ },
38
+ "peerDependencies": {
39
+ "next": "^16.4.6",
40
+ "react": "^19.3.0",
41
+ "tansy": "^0.1.0"
42
+ },
43
+ "dependencies": {
44
+ "zod": "^4.6.7"
45
+ }
46
+ }
package/provider.d.ts ADDED
@@ -0,0 +1,80 @@
1
+ import type { CspAdditions, Messages, PluginSettingField } from "tansy/plugin";
2
+ import type { AnalyticsReport, ProviderTracker } from "./tracker";
3
+ export type { AnalyticsReport, Breakdown, ProviderTracker, TrackerCall, TrackerStub } from "./tracker";
4
+ /**
5
+ * What an analytics provider adapter implements, such as @tansy/analytics-plausible.
6
+ * The analytics plugin keeps what providers share: choosing one, putting its tracker on
7
+ * every page, and showing its numbers on the dashboard. An adapter describes its script
8
+ * and, optionally, how to read its numbers back. See docs/plugins/analytics.md.
9
+ */
10
+ /** The analytics plugin's own settings, and each installed provider's, by name. */
11
+ export interface AnalyticsSettings {
12
+ /** The id of the outside provider in use, or "none". */
13
+ provider: string;
14
+ [name: string]: unknown;
15
+ }
16
+ /** An inclusive range of whole days, as YYYY-MM-DD in UTC. */
17
+ export interface ReportRange {
18
+ from: string;
19
+ to: string;
20
+ }
21
+ export interface AnalyticsProvider {
22
+ /** Lowercase letters and digits, such as "plausible". Every setting's name starts with it. */
23
+ id: string;
24
+ label: string;
25
+ /** Its keys on the analytics plugin's settings. */
26
+ settings(): PluginSettingField[];
27
+ /**
28
+ * Its settings' words in other interface languages, by language code, as
29
+ * `{ ar: { settings: { <name>: { label, description } } } }`.
30
+ */
31
+ messages?: Record<string, Messages>;
32
+ /** Whether what the tracker needs is set, such as a site id. */
33
+ ready(settings: AnalyticsSettings): boolean;
34
+ /**
35
+ * What the browser loads and calls on each page view. Public: never a secret. Checked
36
+ * before it reaches a page: an https script on one of the origins in `csp.connect`.
37
+ */
38
+ tracker(settings: AnalyticsSettings): ProviderTracker;
39
+ /** Whether `report` can run, such as when an API key is set. */
40
+ reportReady?(settings: AnalyticsSettings): boolean;
41
+ /** The provider's own numbers for the range, for the dashboard. Leave it out when the provider has no API. */
42
+ report?(range: ReportRange, settings: AnalyticsSettings): Promise<AnalyticsReport>;
43
+ /** The origins its script loads from and sends to, added to the Content Security Policy. */
44
+ csp: CspAdditions;
45
+ /** Where its own dashboard is, for a link next to the numbers. */
46
+ dashboardUrl?(settings: AnalyticsSettings): string | null;
47
+ }
48
+ /** Types an adapter. */
49
+ export declare const defineAnalyticsProvider: (provider: AnalyticsProvider) => AnalyticsProvider;
50
+ export declare const str: (value: unknown) => string;
51
+ /** A number from an API that may send numbers as strings. */
52
+ export declare const num: (value: unknown) => number;
53
+ /** An origin with no trailing slash, from an option such as a self-hosted instance's address. */
54
+ export declare function originOf(url: string, what: string): string;
55
+ /** An address and the path under it, such as a Matomo installed in a folder. No trailing slash. */
56
+ export declare function baseOf(url: string, what: string): string;
57
+ /**
58
+ * A JSON request to a provider's API. Redirects, timeouts and error statuses throw with
59
+ * the host and status only: what the provider says may echo a key, so it's never logged.
60
+ */
61
+ export declare function requestJson<T = unknown>(url: string, init?: RequestInit, fetcher?: typeof fetch): Promise<T>;
62
+ /** Every day in the range, oldest first. */
63
+ export declare function daysIn({ from, to }: ReportRange): string[];
64
+ /** Days the provider left out count zero, so every report has one entry a day. */
65
+ export declare function fillDays(range: ReportRange, known: Map<string, {
66
+ views: number;
67
+ visitors: number;
68
+ }>): {
69
+ date: string;
70
+ views: number;
71
+ visitors: number;
72
+ }[];
73
+ /** The first `limit` rows, named and counted, most first, without empty names. */
74
+ export declare function breakdown(rows: Array<{
75
+ name: unknown;
76
+ count: unknown;
77
+ }>, limit?: number): {
78
+ name: string;
79
+ count: number;
80
+ }[];
package/provider.js ADDED
@@ -0,0 +1,70 @@
1
+ /** Types an adapter. */
2
+ export const defineAnalyticsProvider = (provider) => provider;
3
+ export const str = (value) => (typeof value === "string" ? value.trim() : "");
4
+ /** A number from an API that may send numbers as strings. */
5
+ export const num = (value) => {
6
+ const parsed = typeof value === "number" ? value : typeof value === "string" ? Number(value) : NaN;
7
+ return Number.isFinite(parsed) ? parsed : 0;
8
+ };
9
+ /** An origin with no trailing slash, from an option such as a self-hosted instance's address. */
10
+ export function originOf(url, what) {
11
+ let parsed;
12
+ try {
13
+ parsed = new URL(url);
14
+ }
15
+ catch {
16
+ throw new Error(`${what} must be an address such as https://example.com. Got "${url}".`);
17
+ }
18
+ if (parsed.protocol !== "https:" && !(parsed.protocol === "http:" && ["localhost", "127.0.0.1"].includes(parsed.hostname)))
19
+ throw new Error(`${what} must use https. Got "${url}".`);
20
+ return parsed.origin;
21
+ }
22
+ /** An address and the path under it, such as a Matomo installed in a folder. No trailing slash. */
23
+ export function baseOf(url, what) {
24
+ const origin = originOf(url, what);
25
+ return `${origin}${new URL(url).pathname.replace(/\/+$/, "")}`;
26
+ }
27
+ const TIMEOUT_MS = 15_000;
28
+ /**
29
+ * A JSON request to a provider's API. Redirects, timeouts and error statuses throw with
30
+ * the host and status only: what the provider says may echo a key, so it's never logged.
31
+ */
32
+ export async function requestJson(url, init = {}, fetcher = fetch) {
33
+ const host = new URL(url).host;
34
+ let response;
35
+ try {
36
+ response = await fetcher(url, { ...init, redirect: "error", signal: AbortSignal.timeout(TIMEOUT_MS) });
37
+ }
38
+ catch {
39
+ throw new Error(`${host} couldn't be reached.`);
40
+ }
41
+ if (!response.ok) {
42
+ await response.body?.cancel().catch(() => { });
43
+ throw new Error(`${host} answered ${response.status}.`);
44
+ }
45
+ try {
46
+ return (await response.json());
47
+ }
48
+ catch {
49
+ throw new Error(`${host} didn't answer with JSON.`);
50
+ }
51
+ }
52
+ /** Every day in the range, oldest first. */
53
+ export function daysIn({ from, to }) {
54
+ const days = [];
55
+ for (let day = new Date(`${from}T00:00:00Z`); day <= new Date(`${to}T00:00:00Z`) && days.length < 400; day.setUTCDate(day.getUTCDate() + 1))
56
+ days.push(day.toISOString().slice(0, 10));
57
+ return days;
58
+ }
59
+ /** Days the provider left out count zero, so every report has one entry a day. */
60
+ export function fillDays(range, known) {
61
+ return daysIn(range).map((date) => ({ date, views: known.get(date)?.views ?? 0, visitors: known.get(date)?.visitors ?? 0 }));
62
+ }
63
+ /** The first `limit` rows, named and counted, most first, without empty names. */
64
+ export function breakdown(rows, limit = 10) {
65
+ return rows
66
+ .map((row) => ({ name: String(row.name ?? "").trim(), count: num(row.count) }))
67
+ .filter((row) => row.name && row.count > 0)
68
+ .sort((a, b) => b.count - a.count)
69
+ .slice(0, limit);
70
+ }
package/render.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ export { AnalyticsTracker, type AnalyticsTrackerProps } from "./tracker-view";
2
+ export type { TrackerConfig } from "./tracker";
3
+ declare const _default: import("tansy/react").Renderers;
4
+ export default _default;
package/render.js ADDED
@@ -0,0 +1,11 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { defineRenderers } from "tansy/react";
3
+ import { AnalyticsTracker } from "./tracker-view";
4
+ export { AnalyticsTracker } from "./tracker-view";
5
+ /** On every page, with what the plugin's settings say to load. A new address is a new page view. */
6
+ function Tracker({ page, props }) {
7
+ return _jsx(AnalyticsTracker, { config: props, path: `${page.locale ?? ""}:${page.path}` });
8
+ }
9
+ export default defineRenderers({
10
+ everyPage: { "analytics-tracker": Tracker },
11
+ });
@@ -0,0 +1,15 @@
1
+ import { type TrackerConfig } from "./tracker";
2
+ export interface AnalyticsTrackerProps {
3
+ /** What the plugin's `everyPage` gave this page. Without it, fetched from `api`. */
4
+ config?: TrackerConfig | null;
5
+ /** The CMS's API, such as https://cms.example.com/api, on a headless site. This app's own when left out. */
6
+ api?: string;
7
+ /** Raise a page view whenever it changes, such as your router's current path. */
8
+ path?: string;
9
+ }
10
+ /**
11
+ * Reports each page view to the CMS's own count and to the outside service chosen under
12
+ * Analytics → Settings. Every page of a themed site has it already. A headless site puts
13
+ * it in its root layout with `api` and the current `path`.
14
+ */
15
+ export declare function AnalyticsTracker({ config: given, api, path }: AnalyticsTrackerProps): null;