simple-module-analytics 0.0.15__py3-none-any.whl
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.
- simple_module_analytics-0.0.15.dist-info/METADATA +57 -0
- simple_module_analytics-0.0.15.dist-info/RECORD +50 -0
- simple_module_analytics-0.0.15.dist-info/WHEEL +4 -0
- simple_module_analytics-0.0.15.dist-info/entry_points.txt +2 -0
- sm_analytics/__init__.py +1 -0
- sm_analytics/collection/__init__.py +1 -0
- sm_analytics/collection/privacy.py +85 -0
- sm_analytics/collection/retention.py +33 -0
- sm_analytics/collection/service.py +105 -0
- sm_analytics/core/__init__.py +1 -0
- sm_analytics/core/constants.py +15 -0
- sm_analytics/core/geo.py +133 -0
- sm_analytics/core/runtime.py +58 -0
- sm_analytics/core/settings.py +22 -0
- sm_analytics/core/tenancy.py +26 -0
- sm_analytics/index.ts +3 -0
- sm_analytics/locales/de.json +118 -0
- sm_analytics/locales/en.json +118 -0
- sm_analytics/models/__init__.py +87 -0
- sm_analytics/module.py +103 -0
- sm_analytics/package.json +21 -0
- sm_analytics/pages/Dashboard.tsx +164 -0
- sm_analytics/reporting/__init__.py +1 -0
- sm_analytics/reporting/reports.py +145 -0
- sm_analytics/ui/components/DateRangeControl.tsx +126 -0
- sm_analytics/ui/components/DeleteProperty.tsx +68 -0
- sm_analytics/ui/components/FilterChips.tsx +74 -0
- sm_analytics/ui/components/PropertyEditor.tsx +189 -0
- sm_analytics/ui/components/PropertySettings.tsx +120 -0
- sm_analytics/ui/components/RankingPanel.tsx +119 -0
- sm_analytics/ui/components/RecentActivity.tsx +63 -0
- sm_analytics/ui/components/ReportExport.tsx +63 -0
- sm_analytics/ui/components/ReportFilters.tsx +119 -0
- sm_analytics/ui/components/ReportView.tsx +86 -0
- sm_analytics/ui/components/TrafficChart.tsx +123 -0
- sm_analytics/ui/utils/api.ts +52 -0
- sm_analytics/ui/utils/csrf.ts +46 -0
- sm_analytics/ui/utils/hostTracker.ts +52 -0
- sm_analytics/ui/utils/i18n.ts +89 -0
- sm_analytics/ui/utils/reportExport.ts +48 -0
- sm_analytics/ui/utils/tracker.ts +102 -0
- sm_analytics/ui/utils/trackingPaths.ts +36 -0
- sm_analytics/ui/utils/types.ts +55 -0
- sm_analytics/ui/utils/useAnalytics.ts +111 -0
- sm_analytics/web/__init__.py +1 -0
- sm_analytics/web/deps.py +30 -0
- sm_analytics/web/endpoints/__init__.py +1 -0
- sm_analytics/web/endpoints/admin.py +115 -0
- sm_analytics/web/endpoints/public.py +76 -0
- sm_analytics/web/schemas.py +132 -0
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { Button } from '@simple-module-py/ui/components/ui/button';
|
|
2
|
+
import {
|
|
3
|
+
ChartContainer,
|
|
4
|
+
ChartTooltip,
|
|
5
|
+
ChartTooltipContent,
|
|
6
|
+
} from '@simple-module-py/ui/components/ui/chart';
|
|
7
|
+
import { useId, useState } from 'react';
|
|
8
|
+
import { Area, AreaChart, CartesianGrid, XAxis, YAxis } from 'recharts';
|
|
9
|
+
import { keys, useT } from '../utils/i18n';
|
|
10
|
+
import type { Report } from '../utils/types';
|
|
11
|
+
|
|
12
|
+
export function TrafficChart({ series }: { series: Report['series'] }) {
|
|
13
|
+
const { t, locale } = useT();
|
|
14
|
+
const heading = useId();
|
|
15
|
+
const [metric, setMetric] = useState<'pageviews' | 'events'>('pageviews');
|
|
16
|
+
const label = t(keys.analytics[metric]);
|
|
17
|
+
return (
|
|
18
|
+
<section aria-labelledby={heading} className="min-w-0 border-b pb-6">
|
|
19
|
+
<div className="mb-5 flex flex-wrap items-center justify-between gap-3">
|
|
20
|
+
<h2 id={heading} className="text-lg font-semibold">
|
|
21
|
+
{t(keys.analytics.period)}
|
|
22
|
+
</h2>
|
|
23
|
+
<fieldset aria-label={t(keys.analytics.ui.chart_metric)} className="flex gap-1">
|
|
24
|
+
{(['pageviews', 'events'] as const).map((value) => (
|
|
25
|
+
<Button
|
|
26
|
+
key={value}
|
|
27
|
+
variant="ghost"
|
|
28
|
+
size="sm"
|
|
29
|
+
aria-pressed={metric === value}
|
|
30
|
+
className={
|
|
31
|
+
metric === value
|
|
32
|
+
? 'text-blue-600 dark:text-blue-400 bg-blue-500/10'
|
|
33
|
+
: 'text-muted-foreground'
|
|
34
|
+
}
|
|
35
|
+
onClick={() => setMetric(value)}
|
|
36
|
+
>
|
|
37
|
+
{t(keys.analytics[value])}
|
|
38
|
+
</Button>
|
|
39
|
+
))}
|
|
40
|
+
</fieldset>
|
|
41
|
+
</div>
|
|
42
|
+
{series.length === 0 ? (
|
|
43
|
+
<p className="flex h-64 items-center justify-center text-sm text-muted-foreground">
|
|
44
|
+
{t(keys.analytics.no_data)}
|
|
45
|
+
</p>
|
|
46
|
+
) : (
|
|
47
|
+
<ChartContainer
|
|
48
|
+
aria-label={label}
|
|
49
|
+
className="h-72 w-full aspect-auto md:h-80"
|
|
50
|
+
config={{ [metric]: { label, theme: { light: '#2563eb', dark: '#60a5fa' } } }}
|
|
51
|
+
>
|
|
52
|
+
<AreaChart
|
|
53
|
+
data={series}
|
|
54
|
+
accessibilityLayer
|
|
55
|
+
margin={{ top: 12, right: 8, left: 0, bottom: 0 }}
|
|
56
|
+
>
|
|
57
|
+
<CartesianGrid vertical={false} stroke="var(--border)" strokeDasharray="3 3" />
|
|
58
|
+
<XAxis
|
|
59
|
+
dataKey="date"
|
|
60
|
+
tickLine={false}
|
|
61
|
+
axisLine={false}
|
|
62
|
+
minTickGap={40}
|
|
63
|
+
tickMargin={12}
|
|
64
|
+
tickFormatter={(date: string) =>
|
|
65
|
+
new Date(`${date}T00:00:00Z`).toLocaleDateString(locale, {
|
|
66
|
+
month: 'short',
|
|
67
|
+
day: 'numeric',
|
|
68
|
+
timeZone: 'UTC',
|
|
69
|
+
})
|
|
70
|
+
}
|
|
71
|
+
/>
|
|
72
|
+
<YAxis
|
|
73
|
+
tickLine={false}
|
|
74
|
+
axisLine={false}
|
|
75
|
+
allowDecimals={false}
|
|
76
|
+
width={48}
|
|
77
|
+
tickFormatter={(count: number) =>
|
|
78
|
+
count.toLocaleString(locale, { notation: 'compact' })
|
|
79
|
+
}
|
|
80
|
+
/>
|
|
81
|
+
<ChartTooltip content={<ChartTooltipContent />} />
|
|
82
|
+
<Area
|
|
83
|
+
type="linear"
|
|
84
|
+
dataKey={metric}
|
|
85
|
+
name={label}
|
|
86
|
+
stroke={`var(--color-${metric})`}
|
|
87
|
+
fill={`var(--color-${metric})`}
|
|
88
|
+
fillOpacity={0.08}
|
|
89
|
+
strokeWidth={2}
|
|
90
|
+
isAnimationActive={false}
|
|
91
|
+
dot={series.length === 1}
|
|
92
|
+
activeDot={{ r: 4 }}
|
|
93
|
+
/>
|
|
94
|
+
</AreaChart>
|
|
95
|
+
</ChartContainer>
|
|
96
|
+
)}
|
|
97
|
+
<details className="mt-4 text-sm">
|
|
98
|
+
<summary className="w-fit cursor-pointer text-muted-foreground focus-visible:outline-ring">
|
|
99
|
+
{t(keys.analytics.ui.chart_data)}
|
|
100
|
+
</summary>
|
|
101
|
+
<div className="max-h-64 overflow-auto">
|
|
102
|
+
<table className="mt-3 w-full text-left text-sm">
|
|
103
|
+
<caption className="sr-only">{label}</caption>
|
|
104
|
+
<thead>
|
|
105
|
+
<tr className="border-b">
|
|
106
|
+
<th className="py-2">{t(keys.analytics.date)}</th>
|
|
107
|
+
<th className="text-right">{label}</th>
|
|
108
|
+
</tr>
|
|
109
|
+
</thead>
|
|
110
|
+
<tbody>
|
|
111
|
+
{series.map((row) => (
|
|
112
|
+
<tr key={row.date} className="border-b last:border-0">
|
|
113
|
+
<td className="py-2">{row.date}</td>
|
|
114
|
+
<td className="text-right tabular-nums">{row[metric].toLocaleString(locale)}</td>
|
|
115
|
+
</tr>
|
|
116
|
+
))}
|
|
117
|
+
</tbody>
|
|
118
|
+
</table>
|
|
119
|
+
</div>
|
|
120
|
+
</details>
|
|
121
|
+
</section>
|
|
122
|
+
);
|
|
123
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { csrfHeaders } from './csrf';
|
|
2
|
+
import { keys, translate } from './i18n';
|
|
3
|
+
import type { Filters, GeoStatus, Property, PropertyInput, Report } from './types';
|
|
4
|
+
|
|
5
|
+
const BASE = '/api/analytics';
|
|
6
|
+
|
|
7
|
+
async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
|
|
8
|
+
const response = await fetch(`${BASE}${path}`, {
|
|
9
|
+
...options,
|
|
10
|
+
credentials: 'same-origin',
|
|
11
|
+
headers: {
|
|
12
|
+
'Content-Type': 'application/json',
|
|
13
|
+
...csrfHeaders(options.method),
|
|
14
|
+
...options.headers,
|
|
15
|
+
},
|
|
16
|
+
});
|
|
17
|
+
if (!response.ok) {
|
|
18
|
+
let detail = '';
|
|
19
|
+
try {
|
|
20
|
+
const data = await response.json();
|
|
21
|
+
detail =
|
|
22
|
+
typeof data.detail === 'string'
|
|
23
|
+
? data.detail
|
|
24
|
+
: Array.isArray(data.detail)
|
|
25
|
+
? data.detail.map((v: { msg: string }) => v.msg).join('; ')
|
|
26
|
+
: '';
|
|
27
|
+
} catch {
|
|
28
|
+
/* Never display HTML from an upstream error. */
|
|
29
|
+
}
|
|
30
|
+
throw new Error(detail || translate(keys.analytics.error));
|
|
31
|
+
}
|
|
32
|
+
return response.status === 204 ? (undefined as T) : response.json();
|
|
33
|
+
}
|
|
34
|
+
export const listProperties = (signal?: AbortSignal) =>
|
|
35
|
+
request<Property[]>('/properties', { signal });
|
|
36
|
+
export const geoStatus = (signal?: AbortSignal) =>
|
|
37
|
+
request<{ geo: GeoStatus }>('/status', { signal });
|
|
38
|
+
export const saveProperty = (data: PropertyInput, id?: string) =>
|
|
39
|
+
request<Property>(id ? `/properties/${encodeURIComponent(id)}` : '/properties', {
|
|
40
|
+
method: id ? 'PUT' : 'POST',
|
|
41
|
+
body: JSON.stringify(data),
|
|
42
|
+
});
|
|
43
|
+
export const deleteProperty = (id: string) =>
|
|
44
|
+
request<void>(`/properties/${encodeURIComponent(id)}`, { method: 'DELETE' });
|
|
45
|
+
export const loadReport = (id: string, filters: Filters, signal?: AbortSignal) => {
|
|
46
|
+
const query = new URLSearchParams(
|
|
47
|
+
Object.entries(filters)
|
|
48
|
+
.filter(([, value]) => value !== '')
|
|
49
|
+
.map(([key, value]) => [key, value === '__unknown__' ? '' : value]),
|
|
50
|
+
);
|
|
51
|
+
return request<Report>(`/properties/${encodeURIComponent(id)}/report?${query}`, { signal });
|
|
52
|
+
};
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/** API helpers receive no page props, so remember the initial and later Inertia tokens.
|
|
2
|
+
* Each distributable module owns its copy to avoid depending on an optional sibling.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { router } from '@inertiajs/react';
|
|
6
|
+
|
|
7
|
+
export const CSRF_HEADER = 'X-CSRF-Token';
|
|
8
|
+
export const CSRF_PROP = 'csrf_token';
|
|
9
|
+
|
|
10
|
+
const UNSAFE = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
|
|
11
|
+
|
|
12
|
+
let current = '';
|
|
13
|
+
|
|
14
|
+
function remember(props: unknown): void {
|
|
15
|
+
const token = (props as Record<string, unknown> | null | undefined)?.[CSRF_PROP];
|
|
16
|
+
if (typeof token === 'string' && token) current = token;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** The first page, from the JSON Inertia 3 renders it into. Read because this
|
|
20
|
+
* module can load after the first `navigate` event has already fired. */
|
|
21
|
+
function initialProps(): unknown {
|
|
22
|
+
const script = document.querySelector('script[data-page="app"][type="application/json"]');
|
|
23
|
+
try {
|
|
24
|
+
return script?.textContent
|
|
25
|
+
? (JSON.parse(script.textContent) as { props?: unknown }).props
|
|
26
|
+
: null;
|
|
27
|
+
} catch {
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
if (typeof document !== 'undefined') {
|
|
33
|
+
remember(initialProps());
|
|
34
|
+
try {
|
|
35
|
+
router.on('navigate', (event) => remember(event.detail?.page?.props));
|
|
36
|
+
} catch {
|
|
37
|
+
// A component test's partial mock of `@inertiajs/react` has no `router`.
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The header a request of `method` needs: nothing for a read, and nothing on
|
|
42
|
+
* a page that was never handed a token (the server then refuses the write). */
|
|
43
|
+
export function csrfHeaders(method: string | undefined): Record<string, string> {
|
|
44
|
+
if (!UNSAFE.has((method ?? 'GET').toUpperCase()) || !current) return {};
|
|
45
|
+
return { [CSRF_HEADER]: current };
|
|
46
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { type AnalyticsConfig, initAnalytics, privacyRequested } from './tracker';
|
|
2
|
+
|
|
3
|
+
type Subscribe = (listener: (url: string) => void) => () => void;
|
|
4
|
+
/** Host adapter: configuration is always re-resolved under the current tenant. */
|
|
5
|
+
export function startHostAnalytics(
|
|
6
|
+
subscribe: Subscribe,
|
|
7
|
+
initialUrl = window.location.href,
|
|
8
|
+
): () => void {
|
|
9
|
+
let generation = 0;
|
|
10
|
+
let previous = '';
|
|
11
|
+
let previousHash = '';
|
|
12
|
+
let pending: AbortController | undefined;
|
|
13
|
+
const navigate = (url: string) => {
|
|
14
|
+
const absolute = new URL(url, window.location.origin);
|
|
15
|
+
const hash = absolute.hash;
|
|
16
|
+
absolute.hash = '';
|
|
17
|
+
const hashOnly = absolute.href === previous && hash !== previousHash;
|
|
18
|
+
previousHash = hash;
|
|
19
|
+
if (hashOnly) return;
|
|
20
|
+
previous = absolute.href;
|
|
21
|
+
const revision = ++generation;
|
|
22
|
+
pending?.abort();
|
|
23
|
+
initAnalytics({ properties: [] });
|
|
24
|
+
if (privacyRequested()) return;
|
|
25
|
+
const controller = new AbortController();
|
|
26
|
+
pending = controller;
|
|
27
|
+
const timer = setTimeout(() => controller.abort(), 3000);
|
|
28
|
+
void fetch('/api/analytics/config', {
|
|
29
|
+
credentials: 'same-origin',
|
|
30
|
+
cache: 'no-store',
|
|
31
|
+
signal: controller.signal,
|
|
32
|
+
})
|
|
33
|
+
.then(async (response) => {
|
|
34
|
+
if (!response.ok) return;
|
|
35
|
+
const config = (await response.json()) as AnalyticsConfig;
|
|
36
|
+
if (revision === generation && Array.isArray(config.properties))
|
|
37
|
+
initAnalytics(config, absolute.href);
|
|
38
|
+
})
|
|
39
|
+
.catch(() => {
|
|
40
|
+
/* Configuration failures leave tracking disabled. */
|
|
41
|
+
})
|
|
42
|
+
.finally(() => clearTimeout(timer));
|
|
43
|
+
};
|
|
44
|
+
const unsubscribe = subscribe(navigate);
|
|
45
|
+
navigate(initialUrl);
|
|
46
|
+
return () => {
|
|
47
|
+
++generation;
|
|
48
|
+
pending?.abort();
|
|
49
|
+
unsubscribe();
|
|
50
|
+
initAnalytics({ properties: [] });
|
|
51
|
+
};
|
|
52
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { t as frameworkT, useT as useFrameworkT } from '@simple-module-py/i18n';
|
|
2
|
+
import { useMemo } from 'react';
|
|
3
|
+
|
|
4
|
+
import en from '../../locales/en.json';
|
|
5
|
+
|
|
6
|
+
const NAMESPACE = 'analytics';
|
|
7
|
+
|
|
8
|
+
const PLURAL_SUFFIXES = ['_zero', '_one', '_two', '_few', '_many', '_other'] as const;
|
|
9
|
+
|
|
10
|
+
type PluralCategory = 'zero' | 'one' | 'two' | 'few' | 'many' | 'other';
|
|
11
|
+
|
|
12
|
+
type StemOf<K extends string> = K extends `${infer S}_${PluralCategory}` ? S : never;
|
|
13
|
+
|
|
14
|
+
type KeyTree<T> = {
|
|
15
|
+
[K in keyof T]: T[K] extends string ? string : KeyTree<T[K]>;
|
|
16
|
+
} & { [K in StemOf<Extract<keyof T, string>>]: string };
|
|
17
|
+
|
|
18
|
+
function build(node: Record<string, unknown>, prefix: string): Record<string, unknown> {
|
|
19
|
+
const out: Record<string, unknown> = {};
|
|
20
|
+
for (const [name, value] of Object.entries(node)) {
|
|
21
|
+
const path = `${prefix}.${name}`;
|
|
22
|
+
if (typeof value !== 'string') {
|
|
23
|
+
out[name] = build(value as Record<string, unknown>, path);
|
|
24
|
+
continue;
|
|
25
|
+
}
|
|
26
|
+
out[name] = path;
|
|
27
|
+
const suffix = PLURAL_SUFFIXES.find((s) => name.endsWith(s));
|
|
28
|
+
if (suffix) {
|
|
29
|
+
const stem = name.slice(0, -suffix.length);
|
|
30
|
+
if (!(stem in out)) out[stem] = `${prefix}.${stem}`;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return out;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export const keys: Record<typeof NAMESPACE, KeyTree<typeof en>> = {
|
|
37
|
+
[NAMESPACE]: build(en, NAMESPACE) as KeyTree<typeof en>,
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
function flatten(node: Record<string, unknown>, prefix: string, out: Record<string, string>) {
|
|
41
|
+
for (const [name, value] of Object.entries(node)) {
|
|
42
|
+
const path = `${prefix}.${name}`;
|
|
43
|
+
if (typeof value !== 'string') {
|
|
44
|
+
flatten(value as Record<string, unknown>, path, out);
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
out[path] = value;
|
|
48
|
+
const suffix = PLURAL_SUFFIXES.find((s) => name.endsWith(s));
|
|
49
|
+
if (suffix) {
|
|
50
|
+
const bareStem = name.slice(0, -suffix.length);
|
|
51
|
+
const stem = `${prefix}.${bareStem}`;
|
|
52
|
+
if (stem in out) continue;
|
|
53
|
+
const other = node[`${bareStem}_other`];
|
|
54
|
+
if (typeof other === 'string') {
|
|
55
|
+
out[stem] = other;
|
|
56
|
+
} else {
|
|
57
|
+
out[stem] = PLURAL_SUFFIXES.map((s) => node[`${bareStem}${s}`]).find(
|
|
58
|
+
(v): v is string => typeof v === 'string',
|
|
59
|
+
) as string;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return out;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const english: Record<string, string> = flatten(en, NAMESPACE, {});
|
|
67
|
+
|
|
68
|
+
export type TranslateParams = Record<string, unknown>;
|
|
69
|
+
|
|
70
|
+
export type Translate = (key: string, params?: TranslateParams) => string;
|
|
71
|
+
|
|
72
|
+
export function translate(key: string, params?: TranslateParams): string {
|
|
73
|
+
return frameworkT(key, { defaultValue: english[key] ?? key, ...params });
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function useT(): { t: Translate; locale: string | undefined } {
|
|
77
|
+
const { t, i18n } = useFrameworkT();
|
|
78
|
+
// The console's language, for `Intl` date and number formatting: the
|
|
79
|
+
// browser's own locale is not the one the console speaks (#189).
|
|
80
|
+
const locale = i18n?.language || undefined;
|
|
81
|
+
return useMemo(
|
|
82
|
+
() => ({
|
|
83
|
+
t: (key: string, params?: TranslateParams) =>
|
|
84
|
+
t(key, { defaultValue: english[key] ?? key, ...params }),
|
|
85
|
+
locale,
|
|
86
|
+
}),
|
|
87
|
+
[t, locale],
|
|
88
|
+
);
|
|
89
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { Filters, Property, Report } from './types';
|
|
2
|
+
|
|
3
|
+
function cell(value: string | number): string {
|
|
4
|
+
if (typeof value === 'number') return String(value);
|
|
5
|
+
// Spreadsheet apps may ignore leading whitespace/control characters before formulas.
|
|
6
|
+
const safe = /^[\s\p{Cc}\p{Cf}]*[=+\-@]|^[\p{Cc}]/u.test(value) ? `'${value}` : value;
|
|
7
|
+
return `"${safe.replaceAll('"', '""')}"`;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export function reportCsv(property: Property, filters: Filters, report: Report): string {
|
|
11
|
+
const rows: (string | number)[][] = [
|
|
12
|
+
['section', 'dimension', 'date', 'value', 'label', 'metric', 'count'],
|
|
13
|
+
];
|
|
14
|
+
const metadata = {
|
|
15
|
+
property_id: property.id,
|
|
16
|
+
property_name: property.name,
|
|
17
|
+
property_kind: property.kind,
|
|
18
|
+
start_utc: filters.start,
|
|
19
|
+
end_utc: filters.end,
|
|
20
|
+
date_bounds: 'inclusive_utc',
|
|
21
|
+
scope: 'current_report',
|
|
22
|
+
breakdown_limit: 'top_50_per_dimension',
|
|
23
|
+
};
|
|
24
|
+
for (const [key, value] of Object.entries(metadata))
|
|
25
|
+
rows.push(['metadata', key, '', value, '', '', '']);
|
|
26
|
+
for (const dimension of ['path', 'event', 'country', 'region', 'city'] as const) {
|
|
27
|
+
const value = filters[dimension];
|
|
28
|
+
const unknown = dimension !== 'path' && dimension !== 'event' && value === '__unknown__';
|
|
29
|
+
rows.push([
|
|
30
|
+
'filter',
|
|
31
|
+
dimension,
|
|
32
|
+
'',
|
|
33
|
+
unknown ? '' : value,
|
|
34
|
+
unknown ? 'Unknown' : value || 'All',
|
|
35
|
+
'',
|
|
36
|
+
'',
|
|
37
|
+
]);
|
|
38
|
+
}
|
|
39
|
+
for (const [metric, count] of Object.entries(report.totals))
|
|
40
|
+
rows.push(['total', '', '', '', '', metric, count]);
|
|
41
|
+
for (const day of report.series)
|
|
42
|
+
for (const metric of ['pageviews', 'events'] as const)
|
|
43
|
+
rows.push(['series', '', day.date, '', '', metric, day[metric]]);
|
|
44
|
+
for (const [dimension, breakdown] of Object.entries(report.breakdowns))
|
|
45
|
+
for (const row of breakdown)
|
|
46
|
+
rows.push(['breakdown', dimension, '', row.value, row.label, '', row.count]);
|
|
47
|
+
return `\uFEFF${rows.map((row) => row.map(cell).join(',')).join('\r\n')}\r\n`;
|
|
48
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { matchPath } from './trackingPaths';
|
|
2
|
+
|
|
3
|
+
export type Scalar = string | number | boolean;
|
|
4
|
+
export type TrackingProperty = {
|
|
5
|
+
id: string;
|
|
6
|
+
kind: 'public' | 'application';
|
|
7
|
+
route_patterns: string[];
|
|
8
|
+
utm_parameters: string[];
|
|
9
|
+
event_allowlist: Record<string, string[]>;
|
|
10
|
+
};
|
|
11
|
+
export type AnalyticsConfig = { properties: TrackingProperty[] };
|
|
12
|
+
let active: AnalyticsConfig = { properties: [] };
|
|
13
|
+
let currentUrl = '';
|
|
14
|
+
|
|
15
|
+
export function privacyRequested(): boolean {
|
|
16
|
+
return (
|
|
17
|
+
typeof navigator === 'undefined' ||
|
|
18
|
+
navigator.doNotTrack === '1' ||
|
|
19
|
+
(navigator as Navigator & { globalPrivacyControl?: boolean }).globalPrivacyControl === true
|
|
20
|
+
);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function eventId(): string {
|
|
24
|
+
if (typeof crypto.randomUUID === 'function') return crypto.randomUUID();
|
|
25
|
+
const bytes = crypto.getRandomValues(new Uint8Array(16));
|
|
26
|
+
bytes[6] = (bytes[6] & 0x0f) | 0x40;
|
|
27
|
+
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
|
28
|
+
const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
|
|
29
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async function send(
|
|
33
|
+
property: TrackingProperty,
|
|
34
|
+
kind: 'pageview' | 'event',
|
|
35
|
+
name?: string,
|
|
36
|
+
values: Record<string, Scalar> = {},
|
|
37
|
+
): Promise<void> {
|
|
38
|
+
if (privacyRequested() || !currentUrl) return;
|
|
39
|
+
const url = new URL(currentUrl, window.location.origin);
|
|
40
|
+
const path = matchPath(url.pathname, property.route_patterns, property.kind);
|
|
41
|
+
if (path === null) return;
|
|
42
|
+
if (kind === 'event' && (!name || !Object.hasOwn(property.event_allowlist, name))) return;
|
|
43
|
+
const allowed = name ? property.event_allowlist[name] : [];
|
|
44
|
+
const properties = Object.fromEntries(
|
|
45
|
+
Object.entries(values).filter(
|
|
46
|
+
([key, value]) =>
|
|
47
|
+
allowed.includes(key) && ['string', 'number', 'boolean'].includes(typeof value),
|
|
48
|
+
),
|
|
49
|
+
);
|
|
50
|
+
const utm = Object.fromEntries(
|
|
51
|
+
property.utm_parameters.flatMap((key) => {
|
|
52
|
+
const value = url.searchParams.get(key);
|
|
53
|
+
return value === null ? [] : [[key, value.slice(0, 200)]];
|
|
54
|
+
}),
|
|
55
|
+
);
|
|
56
|
+
let referrer = '';
|
|
57
|
+
try {
|
|
58
|
+
referrer = document.referrer ? new URL(document.referrer).hostname : '';
|
|
59
|
+
} catch {
|
|
60
|
+
/* An invalid referrer is omitted. */
|
|
61
|
+
}
|
|
62
|
+
const controller = new AbortController();
|
|
63
|
+
const timer = setTimeout(() => controller.abort(), 3000);
|
|
64
|
+
try {
|
|
65
|
+
await fetch('/api/analytics/collect', {
|
|
66
|
+
method: 'POST',
|
|
67
|
+
credentials: 'same-origin',
|
|
68
|
+
signal: controller.signal,
|
|
69
|
+
keepalive: true,
|
|
70
|
+
headers: { 'Content-Type': 'application/json' },
|
|
71
|
+
body: JSON.stringify({
|
|
72
|
+
property_id: property.id,
|
|
73
|
+
event_id: eventId(),
|
|
74
|
+
kind,
|
|
75
|
+
path,
|
|
76
|
+
referrer,
|
|
77
|
+
name,
|
|
78
|
+
properties,
|
|
79
|
+
utm,
|
|
80
|
+
}),
|
|
81
|
+
});
|
|
82
|
+
} catch {
|
|
83
|
+
/* Analytics must never interrupt navigation or retry personal data. */
|
|
84
|
+
} finally {
|
|
85
|
+
clearTimeout(timer);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Replace configuration on every navigation, including tenant switches. */
|
|
90
|
+
export function initAnalytics(
|
|
91
|
+
config: AnalyticsConfig,
|
|
92
|
+
url = typeof window === 'undefined' ? '' : window.location.href,
|
|
93
|
+
): void {
|
|
94
|
+
active = config;
|
|
95
|
+
currentUrl = url;
|
|
96
|
+
if (privacyRequested()) return;
|
|
97
|
+
for (const property of active.properties) void send(property, 'pageview');
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export async function track(name: string, properties: Record<string, Scalar> = {}): Promise<void> {
|
|
101
|
+
await Promise.all(active.properties.map((property) => send(property, 'event', name, properties)));
|
|
102
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/** Match explicit routes before collecting any pathname. */
|
|
2
|
+
const EXCLUDED = new Set(['auth', 'login', 'logout', 'register', 'settings', 'analytics']);
|
|
3
|
+
|
|
4
|
+
export function matchPath(
|
|
5
|
+
path: string,
|
|
6
|
+
patterns: string[],
|
|
7
|
+
kind: 'public' | 'application',
|
|
8
|
+
): string | null {
|
|
9
|
+
const clean = path.split(/[?#]/, 1)[0];
|
|
10
|
+
if (!clean.startsWith('/') || clean.startsWith('//')) return null;
|
|
11
|
+
let decoded: string;
|
|
12
|
+
try {
|
|
13
|
+
decoded = decodeURIComponent(clean);
|
|
14
|
+
} catch {
|
|
15
|
+
return null;
|
|
16
|
+
}
|
|
17
|
+
if (
|
|
18
|
+
decoded
|
|
19
|
+
.split('/')
|
|
20
|
+
.some((part) => EXCLUDED.has(part.toLowerCase()) || part === '.' || part === '..')
|
|
21
|
+
)
|
|
22
|
+
return null;
|
|
23
|
+
const segments = clean.split('/');
|
|
24
|
+
for (const pattern of patterns) {
|
|
25
|
+
const expected = pattern.split('/');
|
|
26
|
+
if (expected.length !== segments.length) continue;
|
|
27
|
+
if (
|
|
28
|
+
expected.every((part, i) =>
|
|
29
|
+
part.startsWith(':') ? Boolean(segments[i]) : part === segments[i],
|
|
30
|
+
)
|
|
31
|
+
) {
|
|
32
|
+
return kind === 'application' ? pattern : clean;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { TrackingProperty } from './tracker';
|
|
2
|
+
export type Property = TrackingProperty & { name: string; origins: string[]; enabled: boolean };
|
|
3
|
+
export type PropertyInput = Omit<Property, 'id'>;
|
|
4
|
+
export type Breakdown = { value: string; label: string; count: number };
|
|
5
|
+
export const DIMENSIONS = [
|
|
6
|
+
'path',
|
|
7
|
+
'referrer',
|
|
8
|
+
'utm_source',
|
|
9
|
+
'utm_medium',
|
|
10
|
+
'utm_campaign',
|
|
11
|
+
'browser',
|
|
12
|
+
'os',
|
|
13
|
+
'device',
|
|
14
|
+
'country',
|
|
15
|
+
'region',
|
|
16
|
+
'city',
|
|
17
|
+
'event',
|
|
18
|
+
] as const;
|
|
19
|
+
export type Dimension = (typeof DIMENSIONS)[number];
|
|
20
|
+
export type Filters = {
|
|
21
|
+
start: string;
|
|
22
|
+
end: string;
|
|
23
|
+
path: string;
|
|
24
|
+
event: string;
|
|
25
|
+
country: string;
|
|
26
|
+
region: string;
|
|
27
|
+
city: string;
|
|
28
|
+
};
|
|
29
|
+
export type Report = {
|
|
30
|
+
totals: { pageviews: number; visitors: number; sessions: number; events: number };
|
|
31
|
+
series: { date: string; pageviews: number; events: number }[];
|
|
32
|
+
breakdowns: Record<Dimension, Breakdown[]> & Record<string, Breakdown[]>;
|
|
33
|
+
recent: {
|
|
34
|
+
visitors: number;
|
|
35
|
+
events: {
|
|
36
|
+
event_id: string;
|
|
37
|
+
kind: string;
|
|
38
|
+
path: string;
|
|
39
|
+
name: string | null;
|
|
40
|
+
created_at: string;
|
|
41
|
+
country: string;
|
|
42
|
+
region: string;
|
|
43
|
+
city: string;
|
|
44
|
+
country_name?: string;
|
|
45
|
+
region_name?: string;
|
|
46
|
+
city_name?: string;
|
|
47
|
+
}[];
|
|
48
|
+
};
|
|
49
|
+
};
|
|
50
|
+
export type GeoStatus = {
|
|
51
|
+
enabled: boolean;
|
|
52
|
+
available: boolean;
|
|
53
|
+
status: string;
|
|
54
|
+
age_days: number | null;
|
|
55
|
+
};
|