@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/LICENSE +21 -0
- package/README.md +12 -2
- package/admin.d.ts +2 -0
- package/admin.js +22 -0
- package/counter.d.ts +13 -0
- package/counter.js +109 -0
- package/dashboard.d.ts +4 -0
- package/dashboard.js +83 -0
- package/index.d.ts +23 -0
- package/index.js +243 -0
- package/logic.d.ts +57 -0
- package/logic.js +163 -0
- package/messages.d.ts +143 -0
- package/messages.js +63 -0
- package/package.json +44 -4
- package/provider.d.ts +80 -0
- package/provider.js +70 -0
- package/render.d.ts +4 -0
- package/render.js +11 -0
- package/tracker-view.d.ts +15 -0
- package/tracker-view.js +153 -0
- package/tracker.d.ts +85 -0
- package/tracker.js +69 -0
package/tracker-view.js
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { useEffect, useRef, useState } from "react";
|
|
3
|
+
import { apiPath } from "tansy/react";
|
|
4
|
+
import { excluded } from "./tracker";
|
|
5
|
+
const win = () => window;
|
|
6
|
+
const scripts = new Map();
|
|
7
|
+
const setUp = new Set();
|
|
8
|
+
/** The address of the last page view, the referrer of the next one within the site. */
|
|
9
|
+
let previous = null;
|
|
10
|
+
let lastSent = { href: "", at: 0 };
|
|
11
|
+
/**
|
|
12
|
+
* Loads the provider's script once per page. Trusted through the page's nonce, under
|
|
13
|
+
* 'strict-dynamic', as the CAPTCHA's is.
|
|
14
|
+
*/
|
|
15
|
+
function load(tracker) {
|
|
16
|
+
let loading = scripts.get(tracker.script);
|
|
17
|
+
if (!loading) {
|
|
18
|
+
loading = new Promise((resolve) => {
|
|
19
|
+
const element = document.createElement("script");
|
|
20
|
+
element.src = tracker.script;
|
|
21
|
+
element.async = true;
|
|
22
|
+
for (const [name, value] of Object.entries(tracker.attributes ?? {}))
|
|
23
|
+
element.setAttribute(name, value);
|
|
24
|
+
element.onload = () => resolve();
|
|
25
|
+
// A blocker stopping the script is the visitor's choice: calls to it are dropped.
|
|
26
|
+
element.onerror = () => resolve();
|
|
27
|
+
document.head.appendChild(element);
|
|
28
|
+
});
|
|
29
|
+
scripts.set(tracker.script, loading);
|
|
30
|
+
}
|
|
31
|
+
return loading;
|
|
32
|
+
}
|
|
33
|
+
/** Creates the queues the script reads once it loads. */
|
|
34
|
+
function stub(tracker) {
|
|
35
|
+
const globals = win();
|
|
36
|
+
for (const item of tracker.stubs ?? []) {
|
|
37
|
+
if (item.type === "array") {
|
|
38
|
+
globals[item.name] ??= [];
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
const [owner, property] = item.into.split(".");
|
|
42
|
+
if (typeof globals[item.name] === "function")
|
|
43
|
+
continue;
|
|
44
|
+
globals[item.name] = function queue() {
|
|
45
|
+
// eslint-disable-next-line prefer-rest-params -- gtag.js reads the arguments object itself.
|
|
46
|
+
const args = arguments;
|
|
47
|
+
const target = property ? (globals[owner][property] ??= []) : (globals[owner] ??= []);
|
|
48
|
+
target.push(args);
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/** The page's own values for the placeholders. */
|
|
53
|
+
function fill(arg, page) {
|
|
54
|
+
if (typeof arg === "string")
|
|
55
|
+
return arg === "$now" ? new Date() : Object.hasOwn(page, arg) ? page[arg] : arg;
|
|
56
|
+
if (Array.isArray(arg))
|
|
57
|
+
return arg.map((item) => fill(item, page));
|
|
58
|
+
if (arg && typeof arg === "object")
|
|
59
|
+
return Object.fromEntries(Object.entries(arg).map(([name, value]) => [name, fill(value, page)]));
|
|
60
|
+
return arg;
|
|
61
|
+
}
|
|
62
|
+
function resolve(fn) {
|
|
63
|
+
const [name, property] = fn.split(".");
|
|
64
|
+
const owner = win()[name];
|
|
65
|
+
const target = property ? owner?.[property] : owner;
|
|
66
|
+
return typeof target === "function" ? { call: target, self: property ? owner : window } : null;
|
|
67
|
+
}
|
|
68
|
+
/** Calls now when the function is there, such as a stub, or once the script has loaded. */
|
|
69
|
+
async function run(tracker, calls, page) {
|
|
70
|
+
for (const call of calls) {
|
|
71
|
+
let target = resolve(call.fn);
|
|
72
|
+
if (!target) {
|
|
73
|
+
await load(tracker);
|
|
74
|
+
target = resolve(call.fn);
|
|
75
|
+
}
|
|
76
|
+
try {
|
|
77
|
+
target?.call.apply(target.self, (call.args ?? []).map((arg) => fill(arg, page)));
|
|
78
|
+
}
|
|
79
|
+
catch (error) {
|
|
80
|
+
console.error("[analytics]", error);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
const optedOut = () => {
|
|
85
|
+
const nav = navigator;
|
|
86
|
+
return nav.globalPrivacyControl === true || nav.doNotTrack === "1" || window.doNotTrack === "1";
|
|
87
|
+
};
|
|
88
|
+
function track(config, base) {
|
|
89
|
+
const { href, pathname, search } = window.location;
|
|
90
|
+
if (excluded(pathname, config.exclude))
|
|
91
|
+
return;
|
|
92
|
+
// React runs effects twice while developing, and a page view is one visit.
|
|
93
|
+
if (lastSent.href === href && Date.now() - lastSent.at < 1000)
|
|
94
|
+
return;
|
|
95
|
+
lastSent = { href, at: Date.now() };
|
|
96
|
+
const referrer = previous ?? document.referrer;
|
|
97
|
+
previous = href;
|
|
98
|
+
if (config.collect) {
|
|
99
|
+
const params = new URLSearchParams(search);
|
|
100
|
+
void fetch(`${base}/ext/analytics/hit`, {
|
|
101
|
+
method: "POST",
|
|
102
|
+
headers: { "content-type": "application/json" },
|
|
103
|
+
body: JSON.stringify({ path: pathname, referrer: referrer || null, source: params.get("utm_source") ?? params.get("ref"), width: window.screen?.width ?? null }),
|
|
104
|
+
keepalive: true,
|
|
105
|
+
credentials: "omit",
|
|
106
|
+
}).catch(() => { });
|
|
107
|
+
}
|
|
108
|
+
const tracker = config.provider;
|
|
109
|
+
if (!tracker || (config.respectOptOut && optedOut()))
|
|
110
|
+
return;
|
|
111
|
+
const page = { $url: href, $path: pathname, $title: document.title, $referrer: referrer };
|
|
112
|
+
const first = !setUp.has(tracker.id);
|
|
113
|
+
setUp.add(tracker.id);
|
|
114
|
+
if (first)
|
|
115
|
+
stub(tracker);
|
|
116
|
+
void (async () => {
|
|
117
|
+
if (first) {
|
|
118
|
+
await run(tracker, tracker.setup ?? [], page);
|
|
119
|
+
void load(tracker);
|
|
120
|
+
}
|
|
121
|
+
await run(tracker, tracker.pageview, page);
|
|
122
|
+
})();
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Reports each page view to the CMS's own count and to the outside service chosen under
|
|
126
|
+
* Analytics → Settings. Every page of a themed site has it already. A headless site puts
|
|
127
|
+
* it in its root layout with `api` and the current `path`.
|
|
128
|
+
*/
|
|
129
|
+
export function AnalyticsTracker({ config: given, api, path }) {
|
|
130
|
+
const base = (api ?? apiPath("")).replace(/\/+$/, "");
|
|
131
|
+
const [fetched, setFetched] = useState(null);
|
|
132
|
+
const config = given ?? fetched;
|
|
133
|
+
useEffect(() => {
|
|
134
|
+
if (given !== undefined)
|
|
135
|
+
return;
|
|
136
|
+
let live = true;
|
|
137
|
+
fetch(`${base}/ext/analytics/tracker`, { credentials: "omit" })
|
|
138
|
+
.then((response) => (response.ok ? response.json() : null))
|
|
139
|
+
.then((value) => { if (live && value)
|
|
140
|
+
setFetched(value); })
|
|
141
|
+
.catch(() => { });
|
|
142
|
+
return () => { live = false; };
|
|
143
|
+
}, [base, given]);
|
|
144
|
+
// The page's props are a new object on every render. Only a new address is a new page view.
|
|
145
|
+
const latest = useRef(config);
|
|
146
|
+
useEffect(() => { latest.current = config; });
|
|
147
|
+
const ready = config !== null;
|
|
148
|
+
useEffect(() => {
|
|
149
|
+
if (ready && latest.current)
|
|
150
|
+
track(latest.current, base);
|
|
151
|
+
}, [ready, base, path]);
|
|
152
|
+
return null;
|
|
153
|
+
}
|
package/tracker.d.ts
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What reaches the browser, and the checks it passes first. No server imports: the
|
|
3
|
+
* tracker component and headless sites use these types too.
|
|
4
|
+
*/
|
|
5
|
+
/** JSON. Strings "$url", "$path", "$title" and "$referrer" become the page's, and "$now" a Date. */
|
|
6
|
+
export type TrackerArg = string | number | boolean | null | TrackerArg[] | {
|
|
7
|
+
[key: string]: TrackerArg;
|
|
8
|
+
};
|
|
9
|
+
/** A call to a function the provider's script or a stub defines, such as `{ fn: "plausible", args: ["pageview"] }` or `{ fn: "_paq.push", args: [["trackPageView"]] }`. */
|
|
10
|
+
export interface TrackerCall {
|
|
11
|
+
fn: string;
|
|
12
|
+
args?: TrackerArg[];
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Set up before the script loads, so calls made meanwhile wait in a queue the script reads:
|
|
16
|
+
* an array (`window._paq = []`), or a function pushing its arguments to one
|
|
17
|
+
* (`window.gtag = function () { dataLayer.push(arguments) }`).
|
|
18
|
+
*/
|
|
19
|
+
export type TrackerStub = {
|
|
20
|
+
type: "array";
|
|
21
|
+
name: string;
|
|
22
|
+
} | {
|
|
23
|
+
type: "queue";
|
|
24
|
+
name: string;
|
|
25
|
+
into: string;
|
|
26
|
+
};
|
|
27
|
+
export interface ProviderTracker {
|
|
28
|
+
/** An https script on one of the provider's own origins. */
|
|
29
|
+
script: string;
|
|
30
|
+
/** `data-` attributes on the script tag, such as data-domain. */
|
|
31
|
+
attributes?: Record<string, string>;
|
|
32
|
+
/** The global the script defines. Calls to it wait until it's there. */
|
|
33
|
+
global?: string;
|
|
34
|
+
stubs?: TrackerStub[];
|
|
35
|
+
/** Calls made once, before the first page view. */
|
|
36
|
+
setup?: TrackerCall[];
|
|
37
|
+
/** Calls made on each page view, including moves between pages without a reload. */
|
|
38
|
+
pageview: TrackerCall[];
|
|
39
|
+
}
|
|
40
|
+
/** What every page's tracker gets. */
|
|
41
|
+
export interface TrackerConfig {
|
|
42
|
+
/** Whether page views go to the CMS's own count. */
|
|
43
|
+
collect: boolean;
|
|
44
|
+
/** The outside provider in use and ready, if any. */
|
|
45
|
+
provider: (ProviderTracker & {
|
|
46
|
+
id: string;
|
|
47
|
+
}) | null;
|
|
48
|
+
/** Addresses starting with any of these aren't counted. */
|
|
49
|
+
exclude: string[];
|
|
50
|
+
/** Whether visitors whose browser sends Global Privacy Control or Do Not Track are kept from the outside provider. */
|
|
51
|
+
respectOptOut: boolean;
|
|
52
|
+
}
|
|
53
|
+
export type Breakdown = Array<{
|
|
54
|
+
name: string;
|
|
55
|
+
count: number;
|
|
56
|
+
}>;
|
|
57
|
+
/** One provider's numbers, or the CMS's own, in the same shape. */
|
|
58
|
+
export interface AnalyticsReport {
|
|
59
|
+
totals: {
|
|
60
|
+
views: number;
|
|
61
|
+
visitors: number;
|
|
62
|
+
};
|
|
63
|
+
/** One entry a day, oldest first. */
|
|
64
|
+
days: Array<{
|
|
65
|
+
date: string;
|
|
66
|
+
views: number;
|
|
67
|
+
visitors: number;
|
|
68
|
+
}>;
|
|
69
|
+
pages: Breakdown;
|
|
70
|
+
referrers: Breakdown;
|
|
71
|
+
countries?: Breakdown;
|
|
72
|
+
devices?: Breakdown;
|
|
73
|
+
browsers?: Breakdown;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* The provider's tracker as the browser may get it, or null with the reason logged. The
|
|
77
|
+
* script must be https on one of `origins`, attributes plain `data-` text, and calls
|
|
78
|
+
* only to the provider's own global or its stubs, with JSON arguments. So a setting gone
|
|
79
|
+
* wrong can't load another script or call anything else on every page.
|
|
80
|
+
*/
|
|
81
|
+
export declare function checkedTracker(id: string, tracker: ProviderTracker, origins: string[]): (ProviderTracker & {
|
|
82
|
+
id: string;
|
|
83
|
+
}) | null;
|
|
84
|
+
/** Whether an address is one the owner chose not to count. */
|
|
85
|
+
export declare const excluded: (path: string, exclude: string[]) => boolean;
|
package/tracker.js
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What reaches the browser, and the checks it passes first. No server imports: the
|
|
3
|
+
* tracker component and headless sites use these types too.
|
|
4
|
+
*/
|
|
5
|
+
const NAME = /^[A-Za-z_$][\w$]{0,39}$/;
|
|
6
|
+
const FORBIDDEN = new Set(["__proto__", "prototype", "constructor"]);
|
|
7
|
+
const ATTRIBUTE = /^data-[a-z][a-z0-9-]{0,40}$/;
|
|
8
|
+
const MAX_ARGS_BYTES = 4096;
|
|
9
|
+
const globalName = (value) => typeof value === "string" && NAME.test(value) && !FORBIDDEN.has(value);
|
|
10
|
+
/** A global or one property of it, such as "umami.track". */
|
|
11
|
+
const path = (value) => typeof value === "string" && value.split(".").length <= 2 && value.split(".").every(globalName);
|
|
12
|
+
/**
|
|
13
|
+
* The provider's tracker as the browser may get it, or null with the reason logged. The
|
|
14
|
+
* script must be https on one of `origins`, attributes plain `data-` text, and calls
|
|
15
|
+
* only to the provider's own global or its stubs, with JSON arguments. So a setting gone
|
|
16
|
+
* wrong can't load another script or call anything else on every page.
|
|
17
|
+
*/
|
|
18
|
+
export function checkedTracker(id, tracker, origins) {
|
|
19
|
+
const fail = (problem) => {
|
|
20
|
+
console.error(`[analytics] ${id}: ${problem}, so the tracker is left off.`);
|
|
21
|
+
return null;
|
|
22
|
+
};
|
|
23
|
+
let script;
|
|
24
|
+
try {
|
|
25
|
+
script = new URL(tracker.script);
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return fail("the script isn't an address");
|
|
29
|
+
}
|
|
30
|
+
const local = script.protocol === "http:" && ["localhost", "127.0.0.1"].includes(script.hostname);
|
|
31
|
+
if ((script.protocol !== "https:" && !local) || !origins.includes(script.origin))
|
|
32
|
+
return fail(`the script isn't on one of its origins (${origins.join(", ")})`);
|
|
33
|
+
const attributes = {};
|
|
34
|
+
for (const [name, value] of Object.entries(tracker.attributes ?? {})) {
|
|
35
|
+
if (!ATTRIBUTE.test(name) || typeof value !== "string" || value.length > 500 || /[\u0000-\u001f]/.test(value))
|
|
36
|
+
return fail(`the attribute "${name}" isn't plain data`);
|
|
37
|
+
attributes[name] = value;
|
|
38
|
+
}
|
|
39
|
+
const stubs = tracker.stubs ?? [];
|
|
40
|
+
for (const stub of stubs) {
|
|
41
|
+
if (!globalName(stub.name) || (stub.type === "queue" ? !path(stub.into) : stub.type !== "array"))
|
|
42
|
+
return fail("a stub isn't a plain global");
|
|
43
|
+
}
|
|
44
|
+
if (tracker.global !== undefined && !globalName(tracker.global))
|
|
45
|
+
return fail("its global isn't a plain name");
|
|
46
|
+
const callable = new Set([...stubs.map((stub) => stub.name), ...(tracker.global ? [tracker.global] : [])]);
|
|
47
|
+
const calls = [...(tracker.setup ?? []), ...tracker.pageview];
|
|
48
|
+
for (const call of calls) {
|
|
49
|
+
if (!path(call.fn) || !callable.has(call.fn.split(".")[0]))
|
|
50
|
+
return fail(`"${String(call.fn)}" isn't its global or one of its stubs`);
|
|
51
|
+
if (call.args !== undefined && !Array.isArray(call.args))
|
|
52
|
+
return fail("arguments must be a list");
|
|
53
|
+
}
|
|
54
|
+
const text = JSON.stringify(calls.map((call) => call.args ?? []));
|
|
55
|
+
if (text === undefined || text.length > MAX_ARGS_BYTES)
|
|
56
|
+
return fail("its arguments aren't small JSON");
|
|
57
|
+
const copy = (list) => (list ?? []).map((call) => ({ fn: call.fn, args: JSON.parse(JSON.stringify(call.args ?? [])) }));
|
|
58
|
+
return {
|
|
59
|
+
id,
|
|
60
|
+
script: script.toString(),
|
|
61
|
+
attributes,
|
|
62
|
+
...(tracker.global ? { global: tracker.global } : {}),
|
|
63
|
+
stubs: stubs.map((stub) => (stub.type === "queue" ? { type: "queue", name: stub.name, into: stub.into } : { type: "array", name: stub.name })),
|
|
64
|
+
setup: copy(tracker.setup),
|
|
65
|
+
pageview: copy(tracker.pageview),
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
/** Whether an address is one the owner chose not to count. */
|
|
69
|
+
export const excluded = (path, exclude) => exclude.some((prefix) => prefix && (path === prefix || path.startsWith(prefix.endsWith("/") ? prefix : `${prefix}/`)));
|