@10x-media/analytics 0.1.0-beta.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/CHANGELOG.md +41 -0
- package/LICENSE +21 -0
- package/README.md +387 -0
- package/dist/RealtimeCounter-BJrjMPSa.js +473 -0
- package/dist/RealtimeCounter-BJrjMPSa.js.map +1 -0
- package/dist/contract-CWZPKWuR.d.ts +83 -0
- package/dist/dist-B6HruP5v.js +4731 -0
- package/dist/dist-B6HruP5v.js.map +1 -0
- package/dist/exports/adapters/ga4.d.ts +20 -0
- package/dist/exports/adapters/ga4.js +177 -0
- package/dist/exports/adapters/ga4.js.map +1 -0
- package/dist/exports/adapters/native.d.ts +22 -0
- package/dist/exports/adapters/native.js +849 -0
- package/dist/exports/adapters/native.js.map +1 -0
- package/dist/exports/adapters/plausible.d.ts +15 -0
- package/dist/exports/adapters/plausible.js +143 -0
- package/dist/exports/adapters/plausible.js.map +1 -0
- package/dist/exports/adapters/posthog.d.ts +17 -0
- package/dist/exports/adapters/posthog.js +119 -0
- package/dist/exports/adapters/posthog.js.map +1 -0
- package/dist/exports/adapters/umami.d.ts +18 -0
- package/dist/exports/adapters/umami.js +139 -0
- package/dist/exports/adapters/umami.js.map +1 -0
- package/dist/exports/client.d.ts +77 -0
- package/dist/exports/client.js +388 -0
- package/dist/exports/client.js.map +1 -0
- package/dist/exports/geo.d.ts +19 -0
- package/dist/exports/geo.js +2 -0
- package/dist/exports/i18n.d.ts +63 -0
- package/dist/exports/i18n.js +3 -0
- package/dist/exports/rsc.d.ts +120 -0
- package/dist/exports/rsc.js +598 -0
- package/dist/exports/rsc.js.map +1 -0
- package/dist/exports/types.d.ts +4 -0
- package/dist/exports/types.js +1 -0
- package/dist/fetchJson-DZb2_Puj.js +36 -0
- package/dist/fetchJson-DZb2_Puj.js.map +1 -0
- package/dist/geoResolver-CasIa4T9.d.ts +12 -0
- package/dist/index-CZdCT0WJ.d.ts +98 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +1081 -0
- package/dist/index.js.map +1 -0
- package/dist/keys-DEqL4LOT.js +57 -0
- package/dist/keys-DEqL4LOT.js.map +1 -0
- package/dist/lib-CE5x1zLQ.js +1058 -0
- package/dist/lib-CE5x1zLQ.js.map +1 -0
- package/dist/maxmindResolver-CXYXXdul.js +99 -0
- package/dist/maxmindResolver-CXYXXdul.js.map +1 -0
- package/dist/presets-CBfq_uJX.d.ts +38 -0
- package/dist/readForWidgetRealtime-D1BD37ST.d.ts +32 -0
- package/dist/series-zytbzPoc.js +17 -0
- package/dist/series-zytbzPoc.js.map +1 -0
- package/dist/server-Cuvhgz-S.js +492 -0
- package/dist/server-Cuvhgz-S.js.map +1 -0
- package/dist/testing/memoryAdapter.d.ts +16 -0
- package/dist/testing/memoryAdapter.js +98 -0
- package/dist/testing/memoryAdapter.js.map +1 -0
- package/dist/translations-keiKtSjF.js +77 -0
- package/dist/translations-keiKtSjF.js.map +1 -0
- package/package.json +156 -0
|
@@ -0,0 +1,492 @@
|
|
|
1
|
+
import { t as keys } from "./keys-DEqL4LOT.js";
|
|
2
|
+
//#region src/core/capabilities.ts
|
|
3
|
+
function satisfiesCapabilities(caps, req) {
|
|
4
|
+
if (req.realtime && !caps.realtime) return false;
|
|
5
|
+
if (req.perPageQuery && !caps.perPageQuery) return false;
|
|
6
|
+
if (req.metrics?.some((m) => !caps.metrics.has(m))) return false;
|
|
7
|
+
if (req.dimensions?.some((d) => !caps.dimensions.has(d))) return false;
|
|
8
|
+
return true;
|
|
9
|
+
}
|
|
10
|
+
//#endregion
|
|
11
|
+
//#region src/plugin/runtime.ts
|
|
12
|
+
/**
|
|
13
|
+
* Stored on the Payload instance (not a module global) so the runtime survives the
|
|
14
|
+
* separate `.` and `/rsc` bundles a consumer loads: a server-component bundle that
|
|
15
|
+
* imported its own copy of a module-level map would never see what the plugin wrote.
|
|
16
|
+
* `Symbol.for` keys into the cross-realm global symbol registry, so both bundles
|
|
17
|
+
* resolve the same key on the same `payload` object.
|
|
18
|
+
*/
|
|
19
|
+
const RUNTIME_KEY = Symbol.for("@10x-media/analytics/runtime");
|
|
20
|
+
const setRuntime = (payload, runtime) => {
|
|
21
|
+
payload[RUNTIME_KEY] = runtime;
|
|
22
|
+
};
|
|
23
|
+
const getRuntime = (payload) => payload[RUNTIME_KEY];
|
|
24
|
+
//#endregion
|
|
25
|
+
//#region src/surfacing/cacheStore.ts
|
|
26
|
+
function kvCacheStore(kv) {
|
|
27
|
+
const store = {
|
|
28
|
+
now: () => Date.now(),
|
|
29
|
+
async get(key) {
|
|
30
|
+
const hit = await kv.get(key);
|
|
31
|
+
if (!hit) return null;
|
|
32
|
+
if (hit.expiresAt <= store.now()) {
|
|
33
|
+
await kv.delete(key);
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
return hit.value;
|
|
37
|
+
},
|
|
38
|
+
async set(key, value, ttlSeconds) {
|
|
39
|
+
await kv.set(key, {
|
|
40
|
+
value,
|
|
41
|
+
expiresAt: store.now() + ttlSeconds * 1e3
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
return store;
|
|
46
|
+
}
|
|
47
|
+
//#endregion
|
|
48
|
+
//#region src/widgets/readForWidgetRealtime.ts
|
|
49
|
+
const empty = (status, adapterId) => ({
|
|
50
|
+
status,
|
|
51
|
+
adapterId,
|
|
52
|
+
activeNow: 0,
|
|
53
|
+
series: []
|
|
54
|
+
});
|
|
55
|
+
/**
|
|
56
|
+
* Site-wide realtime read for the "active now" widget. The window arrives as a
|
|
57
|
+
* dateRange (now - windowMinutes -> now). Cached under a realtime-specific key bucketed
|
|
58
|
+
* to the realtime TTL: it is deliberately NOT routed through the engine, whose key
|
|
59
|
+
* day-snaps the range (so a "last 30 min" read would collide with a "today" aggregate).
|
|
60
|
+
*/
|
|
61
|
+
const readForWidgetRealtime = async (args) => {
|
|
62
|
+
const { req, metric, windowMinutes, adapterId, now } = args;
|
|
63
|
+
const runtime = getRuntime(req.payload);
|
|
64
|
+
if (!runtime) return empty("unavailable", adapterId ?? "");
|
|
65
|
+
let adapter;
|
|
66
|
+
try {
|
|
67
|
+
adapter = adapterId ? runtime.registry.get(adapterId) : runtime.registry.default();
|
|
68
|
+
} catch {
|
|
69
|
+
return empty("unavailable", adapterId ?? "");
|
|
70
|
+
}
|
|
71
|
+
if (!adapter.isConfigured()) return empty("not-configured", adapter.id);
|
|
72
|
+
if (!adapter.realtime || !satisfiesCapabilities(adapter.capabilities, { realtime: true })) return empty("unavailable", adapter.id);
|
|
73
|
+
const ttlSeconds = adapter.capabilities.recommendedTtl.realtime || runtime.ttl.realtime;
|
|
74
|
+
const bucket = Math.floor(now.getTime() / 1e3 / Math.max(1, ttlSeconds));
|
|
75
|
+
const key = `rt:${adapter.id}:${metric}:${windowMinutes}:${bucket}`;
|
|
76
|
+
const store = kvCacheStore(req.payload.kv);
|
|
77
|
+
const cached = await store.get(key);
|
|
78
|
+
if (cached) return cached;
|
|
79
|
+
const dateRange = {
|
|
80
|
+
start: /* @__PURE__ */ new Date(now.getTime() - windowMinutes * 6e4),
|
|
81
|
+
end: now
|
|
82
|
+
};
|
|
83
|
+
const result = await adapter.realtime({
|
|
84
|
+
metrics: [metric],
|
|
85
|
+
dateRange
|
|
86
|
+
}, {});
|
|
87
|
+
const out = {
|
|
88
|
+
status: "ok",
|
|
89
|
+
adapterId: adapter.id,
|
|
90
|
+
activeNow: result.totals?.[metric] ?? 0,
|
|
91
|
+
series: result.rows.map((r) => ({
|
|
92
|
+
date: r.timestamp ?? "",
|
|
93
|
+
value: r.metrics[metric] ?? 0
|
|
94
|
+
}))
|
|
95
|
+
};
|
|
96
|
+
await store.set(key, out, ttlSeconds);
|
|
97
|
+
return out;
|
|
98
|
+
};
|
|
99
|
+
//#endregion
|
|
100
|
+
//#region src/plugin/realtimeEndpoint.ts
|
|
101
|
+
const ALLOWED_METRICS = ["visitors", "pageviews"];
|
|
102
|
+
const ALLOWED_WINDOWS = [
|
|
103
|
+
5,
|
|
104
|
+
15,
|
|
105
|
+
30,
|
|
106
|
+
60
|
|
107
|
+
];
|
|
108
|
+
const DEFAULT_WINDOW = 30;
|
|
109
|
+
const REALTIME_PATH = "/analytics/realtime";
|
|
110
|
+
/**
|
|
111
|
+
* Authenticated GET handler for the realtime widget poller. Reads + clamps the query
|
|
112
|
+
* params, then delegates to readForWidgetRealtime. Returns 401 for an anonymous request.
|
|
113
|
+
* The gate is any authenticated user (not admin-panel access specifically); the response
|
|
114
|
+
* is integer counts only. Tightening to admin-only is a post-v1 option.
|
|
115
|
+
*/
|
|
116
|
+
const makeRealtimeHandler = () => async (req) => {
|
|
117
|
+
if (!req.user) return Response.json({ error: "unauthorized" }, { status: 401 });
|
|
118
|
+
const params = new URL(req.url ?? "", "http://localhost").searchParams;
|
|
119
|
+
const rawMetric = params.get("metric");
|
|
120
|
+
const metric = ALLOWED_METRICS.includes(rawMetric) ? rawMetric : "visitors";
|
|
121
|
+
const rawWindow = Number(params.get("windowMinutes"));
|
|
122
|
+
const result = await readForWidgetRealtime({
|
|
123
|
+
req,
|
|
124
|
+
metric,
|
|
125
|
+
windowMinutes: ALLOWED_WINDOWS.includes(rawWindow) ? rawWindow : DEFAULT_WINDOW,
|
|
126
|
+
adapterId: params.get("dataSource") ?? void 0,
|
|
127
|
+
now: /* @__PURE__ */ new Date()
|
|
128
|
+
});
|
|
129
|
+
return Response.json(result);
|
|
130
|
+
};
|
|
131
|
+
//#endregion
|
|
132
|
+
//#region src/timeframe/presets.ts
|
|
133
|
+
const TIMEFRAME_PRESETS = [
|
|
134
|
+
"today",
|
|
135
|
+
"last7days",
|
|
136
|
+
"last30days",
|
|
137
|
+
"last90days",
|
|
138
|
+
"thisMonth",
|
|
139
|
+
"thisYear",
|
|
140
|
+
"lastYear",
|
|
141
|
+
"allTime"
|
|
142
|
+
];
|
|
143
|
+
const startOfUtcDay$1 = (d) => new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()));
|
|
144
|
+
const daysBack = (d, days) => {
|
|
145
|
+
const start = startOfUtcDay$1(d);
|
|
146
|
+
start.setUTCDate(start.getUTCDate() - days);
|
|
147
|
+
return start;
|
|
148
|
+
};
|
|
149
|
+
/**
|
|
150
|
+
* Resolve a relative timeframe preset to an absolute `DateRange`. `now` is injected
|
|
151
|
+
* so callers stay deterministic. `end` is `now`; `start` is the UTC-day floor of the
|
|
152
|
+
* window. Inclusive day windows count the current day (`last7days` = today plus 6).
|
|
153
|
+
*/
|
|
154
|
+
const resolveTimeframe = (preset, now) => {
|
|
155
|
+
const end = new Date(now);
|
|
156
|
+
switch (preset) {
|
|
157
|
+
case "today": return {
|
|
158
|
+
start: startOfUtcDay$1(now),
|
|
159
|
+
end
|
|
160
|
+
};
|
|
161
|
+
case "last7days": return {
|
|
162
|
+
start: daysBack(now, 6),
|
|
163
|
+
end
|
|
164
|
+
};
|
|
165
|
+
case "last30days": return {
|
|
166
|
+
start: daysBack(now, 29),
|
|
167
|
+
end
|
|
168
|
+
};
|
|
169
|
+
case "last90days": return {
|
|
170
|
+
start: daysBack(now, 89),
|
|
171
|
+
end
|
|
172
|
+
};
|
|
173
|
+
case "thisMonth": return {
|
|
174
|
+
start: new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)),
|
|
175
|
+
end
|
|
176
|
+
};
|
|
177
|
+
case "thisYear": return {
|
|
178
|
+
start: new Date(Date.UTC(now.getUTCFullYear(), 0, 1)),
|
|
179
|
+
end
|
|
180
|
+
};
|
|
181
|
+
case "lastYear": return {
|
|
182
|
+
start: daysBack(now, 364),
|
|
183
|
+
end
|
|
184
|
+
};
|
|
185
|
+
case "allTime": return {
|
|
186
|
+
start: /* @__PURE__ */ new Date(0),
|
|
187
|
+
end
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
};
|
|
191
|
+
//#endregion
|
|
192
|
+
//#region src/widgets/breakdownTypes.ts
|
|
193
|
+
const BREAKDOWN_SPECS = [
|
|
194
|
+
{
|
|
195
|
+
slug: "analytics-breakdown-pages",
|
|
196
|
+
dimension: "page",
|
|
197
|
+
label: keys.widgetBreakdownPages
|
|
198
|
+
},
|
|
199
|
+
{
|
|
200
|
+
slug: "analytics-breakdown-sources",
|
|
201
|
+
dimension: "source",
|
|
202
|
+
label: keys.widgetBreakdownSources
|
|
203
|
+
},
|
|
204
|
+
{
|
|
205
|
+
slug: "analytics-breakdown-devices",
|
|
206
|
+
dimension: "device",
|
|
207
|
+
label: keys.widgetBreakdownDevices
|
|
208
|
+
},
|
|
209
|
+
{
|
|
210
|
+
slug: "analytics-breakdown-countries",
|
|
211
|
+
dimension: "country",
|
|
212
|
+
label: keys.widgetBreakdownCountries
|
|
213
|
+
}
|
|
214
|
+
];
|
|
215
|
+
const breakdownSpecBySlug = (slug) => BREAKDOWN_SPECS.find((s) => s.slug === slug);
|
|
216
|
+
//#endregion
|
|
217
|
+
//#region src/widgets/range.ts
|
|
218
|
+
/**
|
|
219
|
+
* Resolve a widget's explicit custom range to a concrete DateRange, or undefined when
|
|
220
|
+
* the widget is on a relative preset, the custom range is incomplete, or either bound
|
|
221
|
+
* is an unparseable date (a corrupt or hand-set widgetData would otherwise reach the
|
|
222
|
+
* cache key and throw on `toISOString`).
|
|
223
|
+
*/
|
|
224
|
+
const resolveCustomRange = (timeframe, range) => {
|
|
225
|
+
if (timeframe !== "custom" || !range?.from || !range?.to) return;
|
|
226
|
+
const start = new Date(range.from);
|
|
227
|
+
const end = new Date(range.to);
|
|
228
|
+
if (Number.isNaN(start.getTime()) || Number.isNaN(end.getTime())) return;
|
|
229
|
+
return {
|
|
230
|
+
start,
|
|
231
|
+
end
|
|
232
|
+
};
|
|
233
|
+
};
|
|
234
|
+
const formatDay = (d, locale) => d.toLocaleDateString(locale, {
|
|
235
|
+
month: "short",
|
|
236
|
+
day: "numeric",
|
|
237
|
+
year: "numeric"
|
|
238
|
+
});
|
|
239
|
+
/** Server-side caption for a custom range, e.g. "Jun 1, 2026 - Jun 23, 2026". */
|
|
240
|
+
const formatRangeCaption = (range, locale) => `${formatDay(range.start, locale)} - ${formatDay(range.end, locale)}`;
|
|
241
|
+
//#endregion
|
|
242
|
+
//#region src/widgets/readForWidget.ts
|
|
243
|
+
const readForWidget = async (args) => {
|
|
244
|
+
const { req, metrics, timeframe, adapterId, now, range } = args;
|
|
245
|
+
const dateRange = range ?? resolveTimeframe(timeframe, now);
|
|
246
|
+
const base = {
|
|
247
|
+
dateRange,
|
|
248
|
+
metrics: {}
|
|
249
|
+
};
|
|
250
|
+
const runtime = getRuntime(req.payload);
|
|
251
|
+
if (!runtime) return {
|
|
252
|
+
status: "unavailable",
|
|
253
|
+
adapterId: adapterId ?? "",
|
|
254
|
+
...base
|
|
255
|
+
};
|
|
256
|
+
let adapter;
|
|
257
|
+
try {
|
|
258
|
+
adapter = adapterId ? runtime.registry.get(adapterId) : runtime.registry.default();
|
|
259
|
+
} catch {
|
|
260
|
+
return {
|
|
261
|
+
status: "unavailable",
|
|
262
|
+
adapterId: adapterId ?? "",
|
|
263
|
+
...base
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
if (!adapter.isConfigured()) return {
|
|
267
|
+
status: "not-configured",
|
|
268
|
+
adapterId: adapter.id,
|
|
269
|
+
...base
|
|
270
|
+
};
|
|
271
|
+
if (!satisfiesCapabilities(adapter.capabilities, { metrics })) return {
|
|
272
|
+
status: "unavailable",
|
|
273
|
+
adapterId: adapter.id,
|
|
274
|
+
...base
|
|
275
|
+
};
|
|
276
|
+
const result = await runtime.engine.read(adapter, {
|
|
277
|
+
metrics,
|
|
278
|
+
dateRange
|
|
279
|
+
});
|
|
280
|
+
return {
|
|
281
|
+
status: "ok",
|
|
282
|
+
adapterId: adapter.id,
|
|
283
|
+
dateRange,
|
|
284
|
+
metrics: result.totals ?? {},
|
|
285
|
+
clamped: result.meta.clamped ?? false
|
|
286
|
+
};
|
|
287
|
+
};
|
|
288
|
+
//#endregion
|
|
289
|
+
//#region src/widgets/readForWidgetBreakdown.ts
|
|
290
|
+
/**
|
|
291
|
+
* Site-wide ranked breakdown of one metric by one dimension, read through the engine.
|
|
292
|
+
* Mirrors `readForWidget` but gates on the dimension too and maps each result row to a
|
|
293
|
+
* `{ label, value }` pair the bar list renders. The adapter owns sorting and limiting.
|
|
294
|
+
*/
|
|
295
|
+
const readForWidgetBreakdown = async (args) => {
|
|
296
|
+
const { req, metric, dimension, timeframe, limit, adapterId, now, range } = args;
|
|
297
|
+
const dateRange = range ?? resolveTimeframe(timeframe, now);
|
|
298
|
+
const base = {
|
|
299
|
+
dateRange,
|
|
300
|
+
rows: []
|
|
301
|
+
};
|
|
302
|
+
const runtime = getRuntime(req.payload);
|
|
303
|
+
if (!runtime) return {
|
|
304
|
+
status: "unavailable",
|
|
305
|
+
adapterId: adapterId ?? "",
|
|
306
|
+
...base
|
|
307
|
+
};
|
|
308
|
+
let adapter;
|
|
309
|
+
try {
|
|
310
|
+
adapter = adapterId ? runtime.registry.get(adapterId) : runtime.registry.default();
|
|
311
|
+
} catch {
|
|
312
|
+
return {
|
|
313
|
+
status: "unavailable",
|
|
314
|
+
adapterId: adapterId ?? "",
|
|
315
|
+
...base
|
|
316
|
+
};
|
|
317
|
+
}
|
|
318
|
+
if (!adapter.isConfigured()) return {
|
|
319
|
+
status: "not-configured",
|
|
320
|
+
adapterId: adapter.id,
|
|
321
|
+
...base
|
|
322
|
+
};
|
|
323
|
+
if (!satisfiesCapabilities(adapter.capabilities, {
|
|
324
|
+
metrics: [metric],
|
|
325
|
+
dimensions: [dimension]
|
|
326
|
+
})) return {
|
|
327
|
+
status: "unavailable",
|
|
328
|
+
adapterId: adapter.id,
|
|
329
|
+
...base
|
|
330
|
+
};
|
|
331
|
+
const result = await runtime.engine.read(adapter, {
|
|
332
|
+
metrics: [metric],
|
|
333
|
+
dimensions: [dimension],
|
|
334
|
+
dateRange,
|
|
335
|
+
limit,
|
|
336
|
+
order: {
|
|
337
|
+
metric,
|
|
338
|
+
direction: "desc"
|
|
339
|
+
}
|
|
340
|
+
});
|
|
341
|
+
const rows = result.rows.map((row) => ({
|
|
342
|
+
label: row.dimensions?.[dimension] ?? "(none)",
|
|
343
|
+
value: row.metrics[metric] ?? 0
|
|
344
|
+
}));
|
|
345
|
+
return {
|
|
346
|
+
status: "ok",
|
|
347
|
+
adapterId: adapter.id,
|
|
348
|
+
dateRange,
|
|
349
|
+
rows,
|
|
350
|
+
clamped: result.meta.clamped ?? false
|
|
351
|
+
};
|
|
352
|
+
};
|
|
353
|
+
//#endregion
|
|
354
|
+
//#region src/core/granularity.ts
|
|
355
|
+
const GRANULARITY_ORDER = [
|
|
356
|
+
"minute",
|
|
357
|
+
"hour",
|
|
358
|
+
"day",
|
|
359
|
+
"week",
|
|
360
|
+
"month"
|
|
361
|
+
];
|
|
362
|
+
/**
|
|
363
|
+
* Whether an adapter can bucket at granularity `g`. `minGranularity` is the finest
|
|
364
|
+
* bucket a provider supports, so it also supports every coarser one.
|
|
365
|
+
*/
|
|
366
|
+
const supportsGranularity = (caps, g) => GRANULARITY_ORDER.indexOf(g) >= GRANULARITY_ORDER.indexOf(caps.minGranularity);
|
|
367
|
+
//#endregion
|
|
368
|
+
//#region src/widgets/readForWidgetSeries.ts
|
|
369
|
+
const DAY_MS = 864e5;
|
|
370
|
+
const MAX_SERIES_DAYS = 366;
|
|
371
|
+
const startOfUtcDay = (d) => new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()));
|
|
372
|
+
/**
|
|
373
|
+
* Project time-series rows onto a contiguous daily axis, zero-filling gaps. The axis
|
|
374
|
+
* is capped at the most recent `MAX_SERIES_DAYS` so an unbounded range (all time)
|
|
375
|
+
* stays a bounded, drawable sparkline; the headline total still reflects the full
|
|
376
|
+
* range.
|
|
377
|
+
*/
|
|
378
|
+
const fillDailySeries = (rows, dateRange, metric) => {
|
|
379
|
+
const lastDay = startOfUtcDay(dateRange.end);
|
|
380
|
+
const requestedStart = startOfUtcDay(dateRange.start);
|
|
381
|
+
const floor = /* @__PURE__ */ new Date(lastDay.getTime() - (MAX_SERIES_DAYS - 1) * DAY_MS);
|
|
382
|
+
const firstDay = requestedStart.getTime() > floor.getTime() ? requestedStart : floor;
|
|
383
|
+
const byDay = /* @__PURE__ */ new Map();
|
|
384
|
+
for (const row of rows) {
|
|
385
|
+
if (!row.timestamp) continue;
|
|
386
|
+
const day = startOfUtcDay(new Date(row.timestamp)).toISOString();
|
|
387
|
+
byDay.set(day, (byDay.get(day) ?? 0) + (row.metrics[metric] ?? 0));
|
|
388
|
+
}
|
|
389
|
+
const points = [];
|
|
390
|
+
for (let t = firstDay.getTime(); t <= lastDay.getTime(); t += DAY_MS) {
|
|
391
|
+
const date = new Date(t).toISOString();
|
|
392
|
+
points.push({
|
|
393
|
+
date,
|
|
394
|
+
value: byDay.get(date) ?? 0
|
|
395
|
+
});
|
|
396
|
+
}
|
|
397
|
+
return points;
|
|
398
|
+
};
|
|
399
|
+
/**
|
|
400
|
+
* Site-wide time-series read for a trend widget: resolve the timeframe, pick the
|
|
401
|
+
* adapter, gate on the metric and day-granularity support, read through the engine,
|
|
402
|
+
* then return a zero-filled daily series plus the headline total. Mirrors
|
|
403
|
+
* `readForWidget` but yields points instead of a single value.
|
|
404
|
+
*/
|
|
405
|
+
const readForWidgetSeries = async (args) => {
|
|
406
|
+
const { req, metric, timeframe, adapterId, now, range } = args;
|
|
407
|
+
const dateRange = range ?? resolveTimeframe(timeframe, now);
|
|
408
|
+
const base = {
|
|
409
|
+
dateRange,
|
|
410
|
+
points: [],
|
|
411
|
+
total: 0
|
|
412
|
+
};
|
|
413
|
+
const runtime = getRuntime(req.payload);
|
|
414
|
+
if (!runtime) return {
|
|
415
|
+
status: "unavailable",
|
|
416
|
+
adapterId: adapterId ?? "",
|
|
417
|
+
...base
|
|
418
|
+
};
|
|
419
|
+
let adapter;
|
|
420
|
+
try {
|
|
421
|
+
adapter = adapterId ? runtime.registry.get(adapterId) : runtime.registry.default();
|
|
422
|
+
} catch {
|
|
423
|
+
return {
|
|
424
|
+
status: "unavailable",
|
|
425
|
+
adapterId: adapterId ?? "",
|
|
426
|
+
...base
|
|
427
|
+
};
|
|
428
|
+
}
|
|
429
|
+
if (!adapter.isConfigured()) return {
|
|
430
|
+
status: "not-configured",
|
|
431
|
+
adapterId: adapter.id,
|
|
432
|
+
...base
|
|
433
|
+
};
|
|
434
|
+
if (!satisfiesCapabilities(adapter.capabilities, { metrics: [metric] }) || !supportsGranularity(adapter.capabilities, "day")) return {
|
|
435
|
+
status: "unavailable",
|
|
436
|
+
adapterId: adapter.id,
|
|
437
|
+
...base
|
|
438
|
+
};
|
|
439
|
+
const result = await runtime.engine.read(adapter, {
|
|
440
|
+
metrics: [metric],
|
|
441
|
+
dateRange,
|
|
442
|
+
granularity: "day"
|
|
443
|
+
});
|
|
444
|
+
return {
|
|
445
|
+
status: "ok",
|
|
446
|
+
adapterId: adapter.id,
|
|
447
|
+
dateRange,
|
|
448
|
+
points: fillDailySeries(result.rows, dateRange, metric),
|
|
449
|
+
total: result.totals?.[metric] ?? 0,
|
|
450
|
+
clamped: result.meta.clamped ?? false
|
|
451
|
+
};
|
|
452
|
+
};
|
|
453
|
+
//#endregion
|
|
454
|
+
//#region src/translations/metricKeys.ts
|
|
455
|
+
const METRIC_KEYS = {
|
|
456
|
+
pageviews: keys.metricPageviews,
|
|
457
|
+
visitors: keys.metricVisitors,
|
|
458
|
+
visits: keys.metricVisitors,
|
|
459
|
+
sessions: keys.metricSessions,
|
|
460
|
+
events: keys.metricEvents,
|
|
461
|
+
avgDuration: keys.metricAvgDuration,
|
|
462
|
+
bounceRate: keys.metricBounceRate,
|
|
463
|
+
entries: keys.metricEntries,
|
|
464
|
+
exits: keys.metricExits,
|
|
465
|
+
scrollDepth: keys.metricScrollDepth,
|
|
466
|
+
conversions: keys.metricConversions,
|
|
467
|
+
revenue: keys.metricRevenue
|
|
468
|
+
};
|
|
469
|
+
const TIMEFRAME_KEYS = {
|
|
470
|
+
today: keys.timeframeToday,
|
|
471
|
+
last7days: keys.timeframeLast7Days,
|
|
472
|
+
last30days: keys.timeframeLast30Days,
|
|
473
|
+
last90days: keys.timeframeLast90Days,
|
|
474
|
+
thisMonth: keys.timeframeThisMonth,
|
|
475
|
+
thisYear: keys.timeframeThisYear,
|
|
476
|
+
lastYear: keys.timeframeLastYear,
|
|
477
|
+
allTime: keys.timeframeAllTime
|
|
478
|
+
};
|
|
479
|
+
//#endregion
|
|
480
|
+
//#region src/translations/server.ts
|
|
481
|
+
/**
|
|
482
|
+
* Adapt a Payload request `t` (typed to core keys only) so it also accepts this
|
|
483
|
+
* plugin's keys. They are registered at config time and resolve at runtime; the
|
|
484
|
+
* cast only widens the compile-time key domain.
|
|
485
|
+
*/
|
|
486
|
+
const asTranslate = (t) => t;
|
|
487
|
+
/** A field `label`/`description` backed by a typed key, resolved per request. */
|
|
488
|
+
const labelForKey = (key) => ({ t }) => asTranslate(t)(key);
|
|
489
|
+
//#endregion
|
|
490
|
+
export { readForWidgetRealtime as _, readForWidgetSeries as a, setRuntime as b, readForWidget as c, BREAKDOWN_SPECS as d, breakdownSpecBySlug as f, makeRealtimeHandler as g, REALTIME_PATH as h, TIMEFRAME_KEYS as i, formatRangeCaption as l, resolveTimeframe as m, labelForKey as n, supportsGranularity as o, TIMEFRAME_PRESETS as p, METRIC_KEYS as r, readForWidgetBreakdown as s, asTranslate as t, resolveCustomRange as u, kvCacheStore as v, satisfiesCapabilities as x, getRuntime as y };
|
|
491
|
+
|
|
492
|
+
//# sourceMappingURL=server-Cuvhgz-S.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"server-Cuvhgz-S.js","names":["startOfUtcDay"],"sources":["../src/core/capabilities.ts","../src/plugin/runtime.ts","../src/surfacing/cacheStore.ts","../src/widgets/readForWidgetRealtime.ts","../src/plugin/realtimeEndpoint.ts","../src/timeframe/presets.ts","../src/widgets/breakdownTypes.ts","../src/widgets/range.ts","../src/widgets/readForWidget.ts","../src/widgets/readForWidgetBreakdown.ts","../src/core/granularity.ts","../src/widgets/readForWidgetSeries.ts","../src/translations/metricKeys.ts","../src/translations/server.ts"],"sourcesContent":["import type { AnalyticsCapabilities, DimensionKey, MetricKey } from './contract'\n\nexport interface CapabilityRequirement {\n\tmetrics?: MetricKey[]\n\tdimensions?: DimensionKey[]\n\trealtime?: boolean\n\tperPageQuery?: boolean\n}\n\nexport function satisfiesCapabilities(\n\tcaps: AnalyticsCapabilities,\n\treq: CapabilityRequirement\n): boolean {\n\tif (req.realtime && !caps.realtime) return false\n\tif (req.perPageQuery && !caps.perPageQuery) return false\n\tif (req.metrics?.some((m) => !caps.metrics.has(m))) return false\n\tif (req.dimensions?.some((d) => !caps.dimensions.has(d))) return false\n\treturn true\n}\n","import type { Payload } from 'payload'\nimport type { ResolvedBinding } from '../binding/types'\nimport type { AdapterRegistry } from '../core/registry'\nimport type { Engine } from '../surfacing/engine'\n\nexport interface AnalyticsRuntime {\n\tregistry: AdapterRegistry\n\tbindings: Record<string, ResolvedBinding>\n\tengine: Engine\n\tttl: { aggregate: number; realtime: number }\n}\n\n/**\n * Stored on the Payload instance (not a module global) so the runtime survives the\n * separate `.` and `/rsc` bundles a consumer loads: a server-component bundle that\n * imported its own copy of a module-level map would never see what the plugin wrote.\n * `Symbol.for` keys into the cross-realm global symbol registry, so both bundles\n * resolve the same key on the same `payload` object.\n */\nconst RUNTIME_KEY = Symbol.for('@10x-media/analytics/runtime')\n\ntype RuntimeHost = { [RUNTIME_KEY]?: AnalyticsRuntime }\n\nexport const setRuntime = (payload: Payload, runtime: AnalyticsRuntime): void => {\n\t;(payload as unknown as RuntimeHost)[RUNTIME_KEY] = runtime\n}\n\nexport const getRuntime = (payload: Payload): AnalyticsRuntime | undefined =>\n\t(payload as unknown as RuntimeHost)[RUNTIME_KEY]\n","import type { KVAdapter } from 'payload'\n\nexport interface CacheStore {\n\tget<T>(key: string): Promise<T | null>\n\tset<T>(key: string, value: T, ttlSeconds: number): Promise<void>\n\t// Injected for testing; defaults to Date.now\n\tnow: () => number\n}\n\ninterface Wrapped<T> {\n\tvalue: T\n\texpiresAt: number\n}\n\nexport function kvCacheStore(kv: KVAdapter): CacheStore {\n\tconst store: CacheStore = {\n\t\tnow: () => Date.now(),\n\t\tasync get<T>(key: string): Promise<T | null> {\n\t\t\tconst hit = await kv.get<Wrapped<T>>(key)\n\t\t\tif (!hit) return null\n\t\t\tif (hit.expiresAt <= store.now()) {\n\t\t\t\tawait kv.delete(key)\n\t\t\t\treturn null\n\t\t\t}\n\t\t\treturn hit.value\n\t\t},\n\t\tasync set<T>(key: string, value: T, ttlSeconds: number): Promise<void> {\n\t\t\tawait kv.set(key, { value, expiresAt: store.now() + ttlSeconds * 1000 } satisfies Wrapped<T>)\n\t\t},\n\t}\n\treturn store\n}\n","import type { PayloadRequest } from 'payload'\nimport { satisfiesCapabilities } from '../core/capabilities'\nimport type { AnalyticsAdapter, MetricKey } from '../core/contract'\nimport { getRuntime } from '../plugin/runtime'\nimport { kvCacheStore } from '../surfacing/cacheStore'\n\nexport type WidgetRealtimeStatus = 'ok' | 'not-configured' | 'unavailable'\n\nexport interface RealtimePoint {\n\tdate: string\n\tvalue: number\n}\n\nexport interface WidgetRealtimeResult {\n\tstatus: WidgetRealtimeStatus\n\tadapterId: string\n\tactiveNow: number\n\tseries: RealtimePoint[]\n}\n\nexport interface ReadForWidgetRealtimeArgs {\n\treq: PayloadRequest\n\tmetric: MetricKey\n\twindowMinutes: number\n\tadapterId?: string\n\tnow: Date\n}\n\nconst empty = (status: WidgetRealtimeStatus, adapterId: string): WidgetRealtimeResult => ({\n\tstatus,\n\tadapterId,\n\tactiveNow: 0,\n\tseries: [],\n})\n\n/**\n * Site-wide realtime read for the \"active now\" widget. The window arrives as a\n * dateRange (now - windowMinutes -> now). Cached under a realtime-specific key bucketed\n * to the realtime TTL: it is deliberately NOT routed through the engine, whose key\n * day-snaps the range (so a \"last 30 min\" read would collide with a \"today\" aggregate).\n */\nexport const readForWidgetRealtime = async (\n\targs: ReadForWidgetRealtimeArgs\n): Promise<WidgetRealtimeResult> => {\n\tconst { req, metric, windowMinutes, adapterId, now } = args\n\tconst runtime = getRuntime(req.payload)\n\tif (!runtime) {\n\t\treturn empty('unavailable', adapterId ?? '')\n\t}\n\tlet adapter: AnalyticsAdapter\n\ttry {\n\t\tadapter = adapterId ? runtime.registry.get(adapterId) : runtime.registry.default()\n\t} catch {\n\t\treturn empty('unavailable', adapterId ?? '')\n\t}\n\tif (!adapter.isConfigured()) {\n\t\treturn empty('not-configured', adapter.id)\n\t}\n\tif (!adapter.realtime || !satisfiesCapabilities(adapter.capabilities, { realtime: true })) {\n\t\treturn empty('unavailable', adapter.id)\n\t}\n\n\tconst ttlSeconds = adapter.capabilities.recommendedTtl.realtime || runtime.ttl.realtime\n\tconst bucket = Math.floor(now.getTime() / 1000 / Math.max(1, ttlSeconds))\n\tconst key = `rt:${adapter.id}:${metric}:${windowMinutes}:${bucket}`\n\tconst store = kvCacheStore(req.payload.kv)\n\tconst cached = await store.get<WidgetRealtimeResult>(key)\n\tif (cached) {\n\t\treturn cached\n\t}\n\n\tconst dateRange = { start: new Date(now.getTime() - windowMinutes * 60_000), end: now }\n\tconst result = await adapter.realtime({ metrics: [metric], dateRange }, {})\n\tconst out: WidgetRealtimeResult = {\n\t\tstatus: 'ok',\n\t\tadapterId: adapter.id,\n\t\tactiveNow: result.totals?.[metric] ?? 0,\n\t\tseries: result.rows.map((r) => ({ date: r.timestamp ?? '', value: r.metrics[metric] ?? 0 })),\n\t}\n\tawait store.set(key, out, ttlSeconds)\n\treturn out\n}\n","import type { PayloadHandler } from 'payload'\nimport type { MetricKey } from '../core/contract'\nimport { readForWidgetRealtime } from '../widgets/readForWidgetRealtime'\n\nconst ALLOWED_METRICS: MetricKey[] = ['visitors', 'pageviews']\nconst ALLOWED_WINDOWS = [5, 15, 30, 60]\nconst DEFAULT_WINDOW = 30\n\nexport const REALTIME_PATH = '/analytics/realtime'\n\n/**\n * Authenticated GET handler for the realtime widget poller. Reads + clamps the query\n * params, then delegates to readForWidgetRealtime. Returns 401 for an anonymous request.\n * The gate is any authenticated user (not admin-panel access specifically); the response\n * is integer counts only. Tightening to admin-only is a post-v1 option.\n */\nexport const makeRealtimeHandler = (): PayloadHandler => async (req) => {\n\tif (!req.user) {\n\t\treturn Response.json({ error: 'unauthorized' }, { status: 401 })\n\t}\n\tconst params = new URL(req.url ?? '', 'http://localhost').searchParams\n\tconst rawMetric = params.get('metric')\n\tconst metric: MetricKey = ALLOWED_METRICS.includes(rawMetric as MetricKey)\n\t\t? (rawMetric as MetricKey)\n\t\t: 'visitors'\n\tconst rawWindow = Number(params.get('windowMinutes'))\n\tconst windowMinutes = ALLOWED_WINDOWS.includes(rawWindow) ? rawWindow : DEFAULT_WINDOW\n\tconst dataSource = params.get('dataSource') ?? undefined\n\tconst result = await readForWidgetRealtime({\n\t\treq,\n\t\tmetric,\n\t\twindowMinutes,\n\t\tadapterId: dataSource,\n\t\tnow: new Date(),\n\t})\n\treturn Response.json(result)\n}\n","import type { DateRange } from '../core/contract'\n\nexport const TIMEFRAME_PRESETS = [\n\t'today',\n\t'last7days',\n\t'last30days',\n\t'last90days',\n\t'thisMonth',\n\t'thisYear',\n\t'lastYear',\n\t'allTime',\n] as const\n\nexport type TimeframePreset = (typeof TIMEFRAME_PRESETS)[number]\n\nconst startOfUtcDay = (d: Date): Date =>\n\tnew Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()))\n\nconst daysBack = (d: Date, days: number): Date => {\n\tconst start = startOfUtcDay(d)\n\tstart.setUTCDate(start.getUTCDate() - days)\n\treturn start\n}\n\n/**\n * Resolve a relative timeframe preset to an absolute `DateRange`. `now` is injected\n * so callers stay deterministic. `end` is `now`; `start` is the UTC-day floor of the\n * window. Inclusive day windows count the current day (`last7days` = today plus 6).\n */\nexport const resolveTimeframe = (preset: TimeframePreset, now: Date): DateRange => {\n\tconst end = new Date(now)\n\tswitch (preset) {\n\t\tcase 'today':\n\t\t\treturn { start: startOfUtcDay(now), end }\n\t\tcase 'last7days':\n\t\t\treturn { start: daysBack(now, 6), end }\n\t\tcase 'last30days':\n\t\t\treturn { start: daysBack(now, 29), end }\n\t\tcase 'last90days':\n\t\t\treturn { start: daysBack(now, 89), end }\n\t\tcase 'thisMonth':\n\t\t\treturn { start: new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)), end }\n\t\tcase 'thisYear':\n\t\t\treturn { start: new Date(Date.UTC(now.getUTCFullYear(), 0, 1)), end }\n\t\tcase 'lastYear':\n\t\t\treturn { start: daysBack(now, 364), end }\n\t\tcase 'allTime':\n\t\t\treturn { start: new Date(0), end }\n\t}\n}\n","import type { DimensionKey, MetricKey } from '../core/contract'\nimport type { TimeframePreset } from '../timeframe/presets'\nimport { keys, type TranslationKey } from '../translations/keys'\nimport type { WidgetRange } from './types'\n\nexport interface BreakdownWidgetData {\n\ttitle?: string\n\tmetric?: MetricKey\n\ttimeframe?: TimeframePreset | 'custom'\n\trange?: WidgetRange\n\tlimit?: number\n\tdataSource?: string\n}\n\nexport interface BreakdownSpec {\n\tslug: string\n\tdimension: DimensionKey\n\tlabel: TranslationKey\n}\n\nexport const BREAKDOWN_SPECS: BreakdownSpec[] = [\n\t{ slug: 'analytics-breakdown-pages', dimension: 'page', label: keys.widgetBreakdownPages },\n\t{ slug: 'analytics-breakdown-sources', dimension: 'source', label: keys.widgetBreakdownSources },\n\t{ slug: 'analytics-breakdown-devices', dimension: 'device', label: keys.widgetBreakdownDevices },\n\t{\n\t\tslug: 'analytics-breakdown-countries',\n\t\tdimension: 'country',\n\t\tlabel: keys.widgetBreakdownCountries,\n\t},\n]\n\nexport const breakdownSpecBySlug = (slug: string): BreakdownSpec | undefined =>\n\tBREAKDOWN_SPECS.find((s) => s.slug === slug)\n","import type { DateRange } from '../core/contract'\nimport type { WidgetRange } from './types'\n\n/**\n * Resolve a widget's explicit custom range to a concrete DateRange, or undefined when\n * the widget is on a relative preset, the custom range is incomplete, or either bound\n * is an unparseable date (a corrupt or hand-set widgetData would otherwise reach the\n * cache key and throw on `toISOString`).\n */\nexport const resolveCustomRange = (\n\ttimeframe: string | undefined,\n\trange: WidgetRange | undefined\n): DateRange | undefined => {\n\tif (timeframe !== 'custom' || !range?.from || !range?.to) {\n\t\treturn undefined\n\t}\n\tconst start = new Date(range.from)\n\tconst end = new Date(range.to)\n\tif (Number.isNaN(start.getTime()) || Number.isNaN(end.getTime())) {\n\t\treturn undefined\n\t}\n\treturn { start, end }\n}\n\nconst formatDay = (d: Date, locale: string): string =>\n\td.toLocaleDateString(locale, { month: 'short', day: 'numeric', year: 'numeric' })\n\n/** Server-side caption for a custom range, e.g. \"Jun 1, 2026 - Jun 23, 2026\". */\nexport const formatRangeCaption = (range: DateRange, locale: string): string =>\n\t`${formatDay(range.start, locale)} - ${formatDay(range.end, locale)}`\n","import type { PayloadRequest } from 'payload'\nimport { satisfiesCapabilities } from '../core/capabilities'\nimport type { AnalyticsAdapter, DateRange, MetricKey } from '../core/contract'\nimport { getRuntime } from '../plugin/runtime'\nimport { resolveTimeframe, type TimeframePreset } from '../timeframe/presets'\n\nexport type WidgetReadStatus = 'ok' | 'not-configured' | 'unavailable'\n\nexport interface WidgetReadResult {\n\tstatus: WidgetReadStatus\n\tadapterId: string\n\tdateRange: DateRange\n\tmetrics: Partial<Record<MetricKey, number>>\n\tclamped?: boolean\n}\n\nexport interface ReadForWidgetArgs {\n\treq: PayloadRequest\n\tmetrics: MetricKey[]\n\ttimeframe: TimeframePreset\n\tadapterId?: string\n\tnow: Date\n\trange?: DateRange\n}\n\nexport const readForWidget = async (args: ReadForWidgetArgs): Promise<WidgetReadResult> => {\n\tconst { req, metrics, timeframe, adapterId, now, range } = args\n\tconst dateRange = range ?? resolveTimeframe(timeframe, now)\n\tconst base = { dateRange, metrics: {} as Partial<Record<MetricKey, number>> }\n\n\tconst runtime = getRuntime(req.payload)\n\tif (!runtime) {\n\t\treturn { status: 'unavailable', adapterId: adapterId ?? '', ...base }\n\t}\n\tlet adapter: AnalyticsAdapter\n\ttry {\n\t\tadapter = adapterId ? runtime.registry.get(adapterId) : runtime.registry.default()\n\t} catch {\n\t\treturn { status: 'unavailable', adapterId: adapterId ?? '', ...base }\n\t}\n\tif (!adapter.isConfigured()) {\n\t\treturn { status: 'not-configured', adapterId: adapter.id, ...base }\n\t}\n\tif (!satisfiesCapabilities(adapter.capabilities, { metrics })) {\n\t\treturn { status: 'unavailable', adapterId: adapter.id, ...base }\n\t}\n\tconst result = await runtime.engine.read(adapter, { metrics, dateRange })\n\treturn {\n\t\tstatus: 'ok',\n\t\tadapterId: adapter.id,\n\t\tdateRange,\n\t\tmetrics: result.totals ?? {},\n\t\tclamped: result.meta.clamped ?? false,\n\t}\n}\n","import type { PayloadRequest } from 'payload'\nimport { satisfiesCapabilities } from '../core/capabilities'\nimport type { AnalyticsAdapter, DateRange, DimensionKey, MetricKey } from '../core/contract'\nimport { getRuntime } from '../plugin/runtime'\nimport { resolveTimeframe, type TimeframePreset } from '../timeframe/presets'\nimport type { WidgetReadStatus } from './readForWidget'\n\nexport interface BreakdownRow {\n\tlabel: string\n\tvalue: number\n}\n\nexport interface WidgetBreakdownResult {\n\tstatus: WidgetReadStatus\n\tadapterId: string\n\tdateRange: DateRange\n\trows: BreakdownRow[]\n\tclamped?: boolean\n}\n\nexport interface ReadForWidgetBreakdownArgs {\n\treq: PayloadRequest\n\tmetric: MetricKey\n\tdimension: DimensionKey\n\ttimeframe: TimeframePreset\n\tlimit: number\n\tadapterId?: string\n\tnow: Date\n\trange?: DateRange\n}\n\n/**\n * Site-wide ranked breakdown of one metric by one dimension, read through the engine.\n * Mirrors `readForWidget` but gates on the dimension too and maps each result row to a\n * `{ label, value }` pair the bar list renders. The adapter owns sorting and limiting.\n */\nexport const readForWidgetBreakdown = async (\n\targs: ReadForWidgetBreakdownArgs\n): Promise<WidgetBreakdownResult> => {\n\tconst { req, metric, dimension, timeframe, limit, adapterId, now, range } = args\n\tconst dateRange = range ?? resolveTimeframe(timeframe, now)\n\tconst base = { dateRange, rows: [] as BreakdownRow[] }\n\n\tconst runtime = getRuntime(req.payload)\n\tif (!runtime) {\n\t\treturn { status: 'unavailable', adapterId: adapterId ?? '', ...base }\n\t}\n\tlet adapter: AnalyticsAdapter\n\ttry {\n\t\tadapter = adapterId ? runtime.registry.get(adapterId) : runtime.registry.default()\n\t} catch {\n\t\treturn { status: 'unavailable', adapterId: adapterId ?? '', ...base }\n\t}\n\tif (!adapter.isConfigured()) {\n\t\treturn { status: 'not-configured', adapterId: adapter.id, ...base }\n\t}\n\tif (\n\t\t!satisfiesCapabilities(adapter.capabilities, { metrics: [metric], dimensions: [dimension] })\n\t) {\n\t\treturn { status: 'unavailable', adapterId: adapter.id, ...base }\n\t}\n\tconst result = await runtime.engine.read(adapter, {\n\t\tmetrics: [metric],\n\t\tdimensions: [dimension],\n\t\tdateRange,\n\t\tlimit,\n\t\torder: { metric, direction: 'desc' },\n\t})\n\tconst rows = result.rows.map((row) => ({\n\t\tlabel: row.dimensions?.[dimension] ?? '(none)',\n\t\tvalue: row.metrics[metric] ?? 0,\n\t}))\n\treturn {\n\t\tstatus: 'ok',\n\t\tadapterId: adapter.id,\n\t\tdateRange,\n\t\trows,\n\t\tclamped: result.meta.clamped ?? false,\n\t}\n}\n","import type { AnalyticsCapabilities, Granularity } from './contract'\n\nexport const GRANULARITY_ORDER: Granularity[] = ['minute', 'hour', 'day', 'week', 'month']\n\n/**\n * Whether an adapter can bucket at granularity `g`. `minGranularity` is the finest\n * bucket a provider supports, so it also supports every coarser one.\n */\nexport const supportsGranularity = (caps: AnalyticsCapabilities, g: Granularity): boolean =>\n\tGRANULARITY_ORDER.indexOf(g) >= GRANULARITY_ORDER.indexOf(caps.minGranularity)\n","import type { PayloadRequest } from 'payload'\nimport { satisfiesCapabilities } from '../core/capabilities'\nimport type { AnalyticsAdapter, AnalyticsRow, DateRange, MetricKey } from '../core/contract'\nimport { supportsGranularity } from '../core/granularity'\nimport { getRuntime } from '../plugin/runtime'\nimport { resolveTimeframe, type TimeframePreset } from '../timeframe/presets'\nimport type { WidgetReadStatus } from './readForWidget'\n\nexport interface SeriesPoint {\n\tdate: string\n\tvalue: number\n}\n\nexport interface WidgetSeriesResult {\n\tstatus: WidgetReadStatus\n\tadapterId: string\n\tdateRange: DateRange\n\tpoints: SeriesPoint[]\n\ttotal: number\n\tclamped?: boolean\n}\n\nexport interface ReadForWidgetSeriesArgs {\n\treq: PayloadRequest\n\tmetric: MetricKey\n\ttimeframe: TimeframePreset\n\tadapterId?: string\n\tnow: Date\n\trange?: DateRange\n}\n\nconst DAY_MS = 86_400_000\nconst MAX_SERIES_DAYS = 366\n\nconst startOfUtcDay = (d: Date): Date =>\n\tnew Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()))\n\n/**\n * Project time-series rows onto a contiguous daily axis, zero-filling gaps. The axis\n * is capped at the most recent `MAX_SERIES_DAYS` so an unbounded range (all time)\n * stays a bounded, drawable sparkline; the headline total still reflects the full\n * range.\n */\nexport const fillDailySeries = (\n\trows: AnalyticsRow[],\n\tdateRange: DateRange,\n\tmetric: MetricKey\n): SeriesPoint[] => {\n\tconst lastDay = startOfUtcDay(dateRange.end)\n\tconst requestedStart = startOfUtcDay(dateRange.start)\n\tconst floor = new Date(lastDay.getTime() - (MAX_SERIES_DAYS - 1) * DAY_MS)\n\tconst firstDay = requestedStart.getTime() > floor.getTime() ? requestedStart : floor\n\tconst byDay = new Map<string, number>()\n\tfor (const row of rows) {\n\t\tif (!row.timestamp) {\n\t\t\tcontinue\n\t\t}\n\t\tconst day = startOfUtcDay(new Date(row.timestamp)).toISOString()\n\t\tbyDay.set(day, (byDay.get(day) ?? 0) + (row.metrics[metric] ?? 0))\n\t}\n\tconst points: SeriesPoint[] = []\n\tfor (let t = firstDay.getTime(); t <= lastDay.getTime(); t += DAY_MS) {\n\t\tconst date = new Date(t).toISOString()\n\t\tpoints.push({ date, value: byDay.get(date) ?? 0 })\n\t}\n\treturn points\n}\n\n/**\n * Site-wide time-series read for a trend widget: resolve the timeframe, pick the\n * adapter, gate on the metric and day-granularity support, read through the engine,\n * then return a zero-filled daily series plus the headline total. Mirrors\n * `readForWidget` but yields points instead of a single value.\n */\nexport const readForWidgetSeries = async (\n\targs: ReadForWidgetSeriesArgs\n): Promise<WidgetSeriesResult> => {\n\tconst { req, metric, timeframe, adapterId, now, range } = args\n\tconst dateRange = range ?? resolveTimeframe(timeframe, now)\n\tconst base = { dateRange, points: [] as SeriesPoint[], total: 0 }\n\n\tconst runtime = getRuntime(req.payload)\n\tif (!runtime) {\n\t\treturn { status: 'unavailable', adapterId: adapterId ?? '', ...base }\n\t}\n\tlet adapter: AnalyticsAdapter\n\ttry {\n\t\tadapter = adapterId ? runtime.registry.get(adapterId) : runtime.registry.default()\n\t} catch {\n\t\treturn { status: 'unavailable', adapterId: adapterId ?? '', ...base }\n\t}\n\tif (!adapter.isConfigured()) {\n\t\treturn { status: 'not-configured', adapterId: adapter.id, ...base }\n\t}\n\tif (\n\t\t!satisfiesCapabilities(adapter.capabilities, { metrics: [metric] }) ||\n\t\t!supportsGranularity(adapter.capabilities, 'day')\n\t) {\n\t\treturn { status: 'unavailable', adapterId: adapter.id, ...base }\n\t}\n\tconst result = await runtime.engine.read(adapter, {\n\t\tmetrics: [metric],\n\t\tdateRange,\n\t\tgranularity: 'day',\n\t})\n\treturn {\n\t\tstatus: 'ok',\n\t\tadapterId: adapter.id,\n\t\tdateRange,\n\t\tpoints: fillDailySeries(result.rows, dateRange, metric),\n\t\ttotal: result.totals?.[metric] ?? 0,\n\t\tclamped: result.meta.clamped ?? false,\n\t}\n}\n","import type { MetricKey } from '../core/contract'\nimport type { TimeframePreset } from '../timeframe/presets'\nimport type { TranslationKey } from './keys'\nimport { keys } from './keys'\n\nexport const METRIC_KEYS: Record<MetricKey, TranslationKey> = {\n\tpageviews: keys.metricPageviews,\n\tvisitors: keys.metricVisitors,\n\tvisits: keys.metricVisitors,\n\tsessions: keys.metricSessions,\n\tevents: keys.metricEvents,\n\tavgDuration: keys.metricAvgDuration,\n\tbounceRate: keys.metricBounceRate,\n\tentries: keys.metricEntries,\n\texits: keys.metricExits,\n\tscrollDepth: keys.metricScrollDepth,\n\tconversions: keys.metricConversions,\n\trevenue: keys.metricRevenue,\n}\n\nexport const TIMEFRAME_KEYS: Record<TimeframePreset, TranslationKey> = {\n\ttoday: keys.timeframeToday,\n\tlast7days: keys.timeframeLast7Days,\n\tlast30days: keys.timeframeLast30Days,\n\tlast90days: keys.timeframeLast90Days,\n\tthisMonth: keys.timeframeThisMonth,\n\tthisYear: keys.timeframeThisYear,\n\tlastYear: keys.timeframeLastYear,\n\tallTime: keys.timeframeAllTime,\n}\n","import type { LabelFunction } from 'payload'\n\nimport type { TranslationKey } from './keys'\n\n/** A `t`-like function narrowed to this plugin's typed keys. */\ntype Translate = (key: TranslationKey) => string\n\n/**\n * Adapt a Payload request `t` (typed to core keys only) so it also accepts this\n * plugin's keys. They are registered at config time and resolve at runtime; the\n * cast only widens the compile-time key domain.\n */\nexport const asTranslate = (t: unknown): Translate => t as Translate\n\n/** A field `label`/`description` backed by a typed key, resolved per request. */\nexport const labelForKey =\n\t(key: TranslationKey): LabelFunction =>\n\t({ t }) =>\n\t\tasTranslate(t)(key)\n"],"mappings":";;AASA,SAAgB,sBACf,MACA,KACU;CACV,IAAI,IAAI,YAAY,CAAC,KAAK,UAAU,OAAO;CAC3C,IAAI,IAAI,gBAAgB,CAAC,KAAK,cAAc,OAAO;CACnD,IAAI,IAAI,SAAS,MAAM,MAAM,CAAC,KAAK,QAAQ,IAAI,CAAC,CAAC,GAAG,OAAO;CAC3D,IAAI,IAAI,YAAY,MAAM,MAAM,CAAC,KAAK,WAAW,IAAI,CAAC,CAAC,GAAG,OAAO;CACjE,OAAO;AACR;;;;;;;;;;ACCA,MAAM,cAAc,OAAO,IAAI,8BAA8B;AAI7D,MAAa,cAAc,SAAkB,YAAoC;CAC/E,QAAoC,eAAe;AACrD;A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CACjB,SAAS,KAAK;CACd,OAAO,KAAK;CACZ,aAAa,KAAK;CAClB,aAAa,KAAK;CAClB,SAAS,KAAK;AACf;AAEA,MAAa,iBAA0D;CACtE,OAAO,KAAK;CACZ,WAAW,KAAK;CAChB,YAAY,KAAK;CACjB,YAAY,KAAK;CACjB,WAAW,KAAK;CAChB,UAAU,KAAK;CACf,UAAU,KAAK;CACf,SAAS,KAAK;AACf;;;;;;;;ACjBA,MAAa,eAAe,MAA0B;;AAGtD,MAAa,eACX,SACA,EAAE,QACF,YAAY,CAAC,EAAE,GAAG"}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { n as AnalyticsAdapter } from "../contract-CWZPKWuR.js";
|
|
2
|
+
|
|
3
|
+
//#region src/testing/memoryAdapter.d.ts
|
|
4
|
+
interface MemoryEvent {
|
|
5
|
+
path: string;
|
|
6
|
+
timestamp: Date;
|
|
7
|
+
visitor?: string;
|
|
8
|
+
}
|
|
9
|
+
interface MemoryAnalyticsAdapter extends AnalyticsAdapter {
|
|
10
|
+
record(event: MemoryEvent): void;
|
|
11
|
+
reset(): void;
|
|
12
|
+
}
|
|
13
|
+
declare function memoryAdapter(): MemoryAnalyticsAdapter;
|
|
14
|
+
//#endregion
|
|
15
|
+
export { MemoryAnalyticsAdapter, memoryAdapter };
|
|
16
|
+
//# sourceMappingURL=memoryAdapter.d.ts.map
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
//#region src/testing/memoryAdapter.ts
|
|
2
|
+
const capabilities = {
|
|
3
|
+
perPageQuery: true,
|
|
4
|
+
realtime: true,
|
|
5
|
+
realtimeWindowMinutes: 5,
|
|
6
|
+
comparison: true,
|
|
7
|
+
minGranularity: "minute",
|
|
8
|
+
maxLookbackDays: null,
|
|
9
|
+
metrics: new Set([
|
|
10
|
+
"pageviews",
|
|
11
|
+
"visitors",
|
|
12
|
+
"visits",
|
|
13
|
+
"sessions",
|
|
14
|
+
"bounceRate",
|
|
15
|
+
"avgDuration"
|
|
16
|
+
]),
|
|
17
|
+
dimensions: new Set([
|
|
18
|
+
"page",
|
|
19
|
+
"referrer",
|
|
20
|
+
"country",
|
|
21
|
+
"device"
|
|
22
|
+
]),
|
|
23
|
+
batchPageReport: true,
|
|
24
|
+
rateLimit: null,
|
|
25
|
+
recommendedTtl: {
|
|
26
|
+
realtime: 300,
|
|
27
|
+
aggregate: 3600
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
function memoryAdapter() {
|
|
31
|
+
const events = [];
|
|
32
|
+
const inRange = (e, q) => {
|
|
33
|
+
if (q.path && e.path !== q.path) return false;
|
|
34
|
+
return e.timestamp >= q.dateRange.start && e.timestamp <= q.dateRange.end;
|
|
35
|
+
};
|
|
36
|
+
return {
|
|
37
|
+
id: "memory",
|
|
38
|
+
label: "In-memory (testing)",
|
|
39
|
+
capabilities,
|
|
40
|
+
isConfigured: () => true,
|
|
41
|
+
record: (event) => {
|
|
42
|
+
events.push(event);
|
|
43
|
+
},
|
|
44
|
+
reset: () => {
|
|
45
|
+
events.length = 0;
|
|
46
|
+
},
|
|
47
|
+
async query(q, _ctx) {
|
|
48
|
+
const matched = events.filter((e) => inRange(e, q));
|
|
49
|
+
const countVisitors = (list) => new Set(list.map((e) => e.visitor ?? e.path + e.timestamp.toDateString())).size;
|
|
50
|
+
if (q.granularity === "day") {
|
|
51
|
+
const byDay = /* @__PURE__ */ new Map();
|
|
52
|
+
for (const e of matched) {
|
|
53
|
+
const day = new Date(Date.UTC(e.timestamp.getUTCFullYear(), e.timestamp.getUTCMonth(), e.timestamp.getUTCDate())).toISOString();
|
|
54
|
+
const list = byDay.get(day) ?? [];
|
|
55
|
+
list.push(e);
|
|
56
|
+
byDay.set(day, list);
|
|
57
|
+
}
|
|
58
|
+
return {
|
|
59
|
+
rows: [...byDay.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([day, list]) => ({
|
|
60
|
+
timestamp: day,
|
|
61
|
+
metrics: {
|
|
62
|
+
pageviews: list.length,
|
|
63
|
+
visitors: countVisitors(list)
|
|
64
|
+
}
|
|
65
|
+
})),
|
|
66
|
+
totals: {
|
|
67
|
+
pageviews: matched.length,
|
|
68
|
+
visitors: countVisitors(matched)
|
|
69
|
+
},
|
|
70
|
+
meta: {
|
|
71
|
+
provider: "memory",
|
|
72
|
+
fetchedAt: q.dateRange.end.toISOString()
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
const pageviews = matched.length;
|
|
77
|
+
const visitors = countVisitors(matched);
|
|
78
|
+
return {
|
|
79
|
+
rows: [{ metrics: {
|
|
80
|
+
pageviews,
|
|
81
|
+
visitors
|
|
82
|
+
} }],
|
|
83
|
+
totals: {
|
|
84
|
+
pageviews,
|
|
85
|
+
visitors
|
|
86
|
+
},
|
|
87
|
+
meta: {
|
|
88
|
+
provider: "memory",
|
|
89
|
+
fetchedAt: q.dateRange.end.toISOString()
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
//#endregion
|
|
96
|
+
export { memoryAdapter };
|
|
97
|
+
|
|
98
|
+
//# sourceMappingURL=memoryAdapter.js.map
|