@10x-media/analytics 1.0.0-beta.6 → 1.0.0-beta.7
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 +25 -0
- package/README.md +5 -1
- package/dist/adapters/http/fetchJson.js +1 -1
- package/dist/adapters/plausible/plausible.d.ts +10 -0
- package/dist/adapters/plausible/plausible.js +40 -0
- package/dist/adapters/plausible/plausible.js.map +1 -1
- package/dist/adapters/posthog/posthog.d.ts +10 -1
- package/dist/adapters/posthog/posthog.js +47 -0
- package/dist/adapters/posthog/posthog.js.map +1 -1
- package/dist/adapters/umami/umami.d.ts +5 -1
- package/dist/adapters/umami/umami.js +26 -0
- package/dist/adapters/umami/umami.js.map +1 -1
- package/dist/capture/getTrackerConfig.d.ts +20 -0
- package/dist/capture/getTrackerConfig.js +31 -0
- package/dist/capture/getTrackerConfig.js.map +1 -0
- package/dist/capture/mountPath.js +14 -0
- package/dist/capture/mountPath.js.map +1 -0
- package/dist/capture/proxyEndpoint.js +123 -0
- package/dist/capture/proxyEndpoint.js.map +1 -0
- package/dist/capture/proxyRoutes.js +108 -0
- package/dist/capture/proxyRoutes.js.map +1 -0
- package/dist/capture/requestBody.js +68 -0
- package/dist/capture/requestBody.js.map +1 -0
- package/dist/capture/slots.d.ts +8 -0
- package/dist/capture/slots.js +43 -0
- package/dist/capture/slots.js.map +1 -0
- package/dist/capture/trackerConfig.d.ts +32 -0
- package/dist/capture/trackerConfig.js +70 -0
- package/dist/capture/trackerConfig.js.map +1 -0
- package/dist/capture/trackerEndpoint.js +35 -0
- package/dist/capture/trackerEndpoint.js.map +1 -0
- package/dist/core/capture.d.ts +49 -0
- package/dist/core/contract.d.ts +26 -2
- package/dist/core/contract.js.map +1 -1
- package/dist/core/options.d.ts +97 -2
- package/dist/core/options.js +63 -2
- package/dist/core/options.js.map +1 -1
- package/dist/core/registry.d.ts +1 -0
- package/dist/core/scopeList.js +32 -0
- package/dist/core/scopeList.js.map +1 -0
- package/dist/core/scopedRead.js +13 -6
- package/dist/core/scopedRead.js.map +1 -1
- package/dist/exports/next.d.ts +2 -1
- package/dist/exports/next.js +2 -1
- package/dist/exports/react.d.ts +4 -0
- package/dist/exports/react.js +5 -0
- package/dist/exports/rsc.d.ts +4 -1
- package/dist/exports/rsc.js +3 -1
- package/dist/exports/tracker.d.ts +18 -0
- package/dist/exports/tracker.js +12 -0
- package/dist/exports/types.d.ts +5 -2
- package/dist/fields/AnalyticsPanelClient.js +1 -1
- package/dist/fields/config/narrow.js +2 -0
- package/dist/fields/config/narrow.js.map +1 -1
- package/dist/fields/readForDocument.js +1 -1
- package/dist/goals/match.js +64 -0
- package/dist/goals/match.js.map +1 -0
- package/dist/goals/types.d.ts +33 -0
- package/dist/goals/types.js +7 -0
- package/dist/goals/types.js.map +1 -0
- package/dist/index.d.ts +4 -3
- package/dist/index.js +33 -9
- package/dist/index.js.map +1 -1
- package/dist/native/collections/events.js +21 -1
- package/dist/native/collections/events.js.map +1 -1
- package/dist/native/collections/rollups.js +24 -0
- package/dist/native/collections/rollups.js.map +1 -1
- package/dist/native/geo/maxmindResolver.js +2 -4
- package/dist/native/geo/maxmindResolver.js.map +1 -1
- package/dist/native/ingest/clientIp.js +15 -0
- package/dist/native/ingest/clientIp.js.map +1 -0
- package/dist/native/ingest/endpoint.js +40 -4
- package/dist/native/ingest/endpoint.js.map +1 -1
- package/dist/native/ingest/flushBatch.js +4 -13
- package/dist/native/ingest/flushBatch.js.map +1 -1
- package/dist/native/ingest/normalizeEvent.js +76 -9
- package/dist/native/ingest/normalizeEvent.js.map +1 -1
- package/dist/native/nativeAdapter.js +20 -4
- package/dist/native/nativeAdapter.js.map +1 -1
- package/dist/native/query/eventAgg.js +39 -13
- package/dist/native/query/eventAgg.js.map +1 -1
- package/dist/native/rollupAcc.js +12 -1
- package/dist/native/rollupAcc.js.map +1 -1
- package/dist/native/rollups/bumpRollup.js +5 -1
- package/dist/native/rollups/bumpRollup.js.map +1 -1
- package/dist/native/rollups/deltas.js +28 -6
- package/dist/native/rollups/deltas.js.map +1 -1
- package/dist/next/captureRewrites.d.ts +41 -0
- package/dist/next/captureRewrites.js +56 -0
- package/dist/next/captureRewrites.js.map +1 -0
- package/dist/next/posthogProxyRewrites.d.ts +5 -0
- package/dist/next/posthogProxyRewrites.js +16 -21
- package/dist/next/posthogProxyRewrites.js.map +1 -1
- package/dist/plugin/documentEndpoint.js +1 -1
- package/dist/plugin/paths.js +11 -1
- package/dist/plugin/paths.js.map +1 -1
- package/dist/plugin/runtime.d.ts +1 -0
- package/dist/plugin/runtime.js.map +1 -1
- package/dist/plugin/sourcesEndpoint.js +16 -4
- package/dist/plugin/sourcesEndpoint.js.map +1 -1
- package/dist/plugin/warmTask.js +0 -0
- package/dist/plugin/warmTask.js.map +1 -1
- package/dist/providers/collection.js +56 -16
- package/dist/providers/collection.js.map +1 -1
- package/dist/providers/factory.js +8 -2
- package/dist/providers/factory.js.map +1 -1
- package/dist/react/AnalyticsProvider.d.ts +43 -0
- package/dist/react/AnalyticsProvider.js +66 -0
- package/dist/react/AnalyticsProvider.js.map +1 -0
- package/dist/react/TrackerBoot.d.ts +22 -0
- package/dist/react/TrackerBoot.js +30 -0
- package/dist/react/TrackerBoot.js.map +1 -0
- package/dist/react/useAnalytics.d.ts +17 -0
- package/dist/react/useAnalytics.js +36 -0
- package/dist/react/useAnalytics.js.map +1 -0
- package/dist/rsc/AnalyticsScripts.d.ts +30 -0
- package/dist/rsc/AnalyticsScripts.js +41 -0
- package/dist/rsc/AnalyticsScripts.js.map +1 -0
- package/dist/surfacing/cacheStore.d.ts +1 -0
- package/dist/surfacing/cacheStore.js +18 -2
- package/dist/surfacing/cacheStore.js.map +1 -1
- package/dist/surfacing/engine.d.ts +1 -0
- package/dist/surfacing/engine.js +44 -4
- package/dist/surfacing/engine.js.map +1 -1
- package/dist/surfacing/queue.js +22 -6
- package/dist/surfacing/queue.js.map +1 -1
- package/dist/surfacing/rateLimiter.js +130 -0
- package/dist/surfacing/rateLimiter.js.map +1 -0
- package/dist/surfacing/retryPolicy.js +15 -0
- package/dist/surfacing/retryPolicy.js.map +1 -0
- package/dist/sync/syncTask.js +60 -33
- package/dist/sync/syncTask.js.map +1 -1
- package/dist/testing/memoryAdapter.d.ts +2 -0
- package/dist/testing/memoryAdapter.js +10 -0
- package/dist/testing/memoryAdapter.js.map +1 -1
- package/dist/tracker/autoCapture.d.ts +48 -0
- package/dist/tracker/autoCapture.js +129 -0
- package/dist/tracker/autoCapture.js.map +1 -0
- package/dist/tracker/consent.d.ts +24 -0
- package/dist/tracker/consent.js +48 -0
- package/dist/tracker/consent.js.map +1 -0
- package/dist/tracker/createTracker.d.ts +18 -0
- package/dist/tracker/createTracker.js +163 -0
- package/dist/tracker/createTracker.js.map +1 -0
- package/dist/tracker/initTracker.d.ts +22 -0
- package/dist/tracker/initTracker.js +33 -0
- package/dist/tracker/initTracker.js.map +1 -0
- package/dist/tracker/loadScript.d.ts +14 -0
- package/dist/tracker/loadScript.js +41 -0
- package/dist/tracker/loadScript.js.map +1 -0
- package/dist/tracker/pageTracking.d.ts +17 -0
- package/dist/tracker/pageTracking.js +38 -0
- package/dist/tracker/pageTracking.js.map +1 -0
- package/dist/tracker/registry.d.ts +27 -0
- package/dist/tracker/registry.js +73 -0
- package/dist/tracker/registry.js.map +1 -0
- package/dist/tracker/sinks/native.d.ts +22 -0
- package/dist/tracker/sinks/native.js +56 -0
- package/dist/tracker/sinks/native.js.map +1 -0
- package/dist/tracker/sinks/plausible.d.ts +14 -0
- package/dist/tracker/sinks/plausible.js +25 -0
- package/dist/tracker/sinks/plausible.js.map +1 -0
- package/dist/tracker/sinks/posthog.d.ts +14 -0
- package/dist/tracker/sinks/posthog.js +18 -0
- package/dist/tracker/sinks/posthog.js.map +1 -0
- package/dist/tracker/sinks/umami.d.ts +13 -0
- package/dist/tracker/sinks/umami.js +17 -0
- package/dist/tracker/sinks/umami.js.map +1 -0
- package/dist/tracker/sinks/vendor.d.ts +14 -0
- package/dist/tracker/sinks/vendor.js +66 -0
- package/dist/tracker/sinks/vendor.js.map +1 -0
- package/dist/tracker/transport.js +28 -0
- package/dist/tracker/transport.js.map +1 -0
- package/dist/tracker/types.d.ts +66 -0
- package/dist/translations/ar.js +6 -0
- package/dist/translations/ar.js.map +1 -1
- package/dist/translations/de.js +6 -0
- package/dist/translations/de.js.map +1 -1
- package/dist/translations/en.js +6 -0
- package/dist/translations/en.js.map +1 -1
- package/dist/translations/es.js +6 -0
- package/dist/translations/es.js.map +1 -1
- package/dist/translations/fr.js +6 -0
- package/dist/translations/fr.js.map +1 -1
- package/dist/translations/id.js +6 -0
- package/dist/translations/id.js.map +1 -1
- package/dist/translations/keys.d.ts +6 -0
- package/dist/translations/keys.js +6 -0
- package/dist/translations/keys.js.map +1 -1
- package/dist/translations/ko.js +6 -0
- package/dist/translations/ko.js.map +1 -1
- package/dist/translations/pt.js +6 -0
- package/dist/translations/pt.js.map +1 -1
- package/dist/translations/ru.js +6 -0
- package/dist/translations/ru.js.map +1 -1
- package/dist/translations/uk.js +6 -0
- package/dist/translations/uk.js.map +1 -1
- package/dist/translations/zh.js +6 -0
- package/dist/translations/zh.js.map +1 -1
- package/dist/widgets/breakdownTypes.js +5 -0
- package/dist/widgets/breakdownTypes.js.map +1 -1
- package/dist/widgets/readForWidget.js +24 -14
- package/dist/widgets/readForWidget.js.map +1 -1
- package/dist/widgets/readForWidgetBreakdown.js +23 -14
- package/dist/widgets/readForWidgetBreakdown.js.map +1 -1
- package/dist/widgets/readForWidgetRealtime.js +1 -1
- package/dist/widgets/readForWidgetSeries.js +26 -16
- package/dist/widgets/readForWidgetSeries.js.map +1 -1
- package/dist/widgets/registerWidgets.js +10 -4
- package/dist/widgets/registerWidgets.js.map +1 -1
- package/dist/widgets/types.js +4 -1
- package/dist/widgets/types.js.map +1 -1
- package/package.json +21 -6
package/dist/native/rollupAcc.js
CHANGED
|
@@ -5,7 +5,11 @@ const emptyAcc = () => ({
|
|
|
5
5
|
events: 0,
|
|
6
6
|
durationMs: 0,
|
|
7
7
|
visitors: 0,
|
|
8
|
-
sessions: 0
|
|
8
|
+
sessions: 0,
|
|
9
|
+
conversions: 0,
|
|
10
|
+
revenue: 0,
|
|
11
|
+
scrollDepthSum: 0,
|
|
12
|
+
scrollSamples: 0
|
|
9
13
|
});
|
|
10
14
|
const add = (acc, d) => {
|
|
11
15
|
acc.pageviews += d.pageviews;
|
|
@@ -13,6 +17,10 @@ const add = (acc, d) => {
|
|
|
13
17
|
acc.durationMs += d.durationMs;
|
|
14
18
|
acc.visitors += d.visitors;
|
|
15
19
|
acc.sessions += d.sessions;
|
|
20
|
+
acc.conversions += d.conversions ?? 0;
|
|
21
|
+
acc.revenue += d.revenue ?? 0;
|
|
22
|
+
acc.scrollDepthSum += d.scrollDepthSum ?? 0;
|
|
23
|
+
acc.scrollSamples += d.scrollSamples ?? 0;
|
|
16
24
|
};
|
|
17
25
|
const selectMetrics = (acc, wanted) => {
|
|
18
26
|
const out = {};
|
|
@@ -20,7 +28,10 @@ const selectMetrics = (acc, wanted) => {
|
|
|
20
28
|
if (wanted.includes("events")) out.events = acc.events;
|
|
21
29
|
if (wanted.includes("visitors")) out.visitors = acc.visitors;
|
|
22
30
|
if (wanted.includes("sessions")) out.sessions = acc.sessions;
|
|
31
|
+
if (wanted.includes("conversions")) out.conversions = acc.conversions;
|
|
32
|
+
if (wanted.includes("revenue")) out.revenue = acc.revenue;
|
|
23
33
|
if (wanted.includes("avgDuration")) out.avgDuration = acc.pageviews > 0 ? Math.round(acc.durationMs / acc.pageviews) : 0;
|
|
34
|
+
if (wanted.includes("scrollDepth")) out.scrollDepth = acc.scrollSamples > 0 ? Math.round(acc.scrollDepthSum / acc.scrollSamples) : 0;
|
|
24
35
|
return out;
|
|
25
36
|
};
|
|
26
37
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rollupAcc.js","names":[],"sources":["../../src/native/rollupAcc.ts"],"sourcesContent":["import type { AnalyticsRow, MetricKey } from '../core/contract'\nimport { DEFAULT_TIMEZONE, startOfDayInTz } from '../timeframe/tz'\n\nexport interface RollupDoc {\n\tpath: string\n\tdimvalue: string\n\tperiod: string | Date\n\tpageviews: number\n\tevents: number\n\tdurationMs: number\n\tvisitors: number\n\tsessions: number\n}\n\nexport interface Acc {\n\tpageviews: number\n\tevents: number\n\tdurationMs: number\n\tvisitors: number\n\tsessions: number\n}\n\nexport const emptyAcc = (): Acc => ({\n\tpageviews: 0,\n\tevents: 0,\n\tdurationMs: 0,\n\tvisitors: 0,\n\tsessions: 0,\n})\n\nexport const add = (acc: Acc, d: Acc): void => {\n\tacc.pageviews += d.pageviews\n\tacc.events += d.events\n\tacc.durationMs += d.durationMs\n\tacc.visitors += d.visitors\n\tacc.sessions += d.sessions\n}\n\nexport const selectMetrics = (\n\tacc: Acc,\n\twanted: MetricKey[]\n): Partial<Record<MetricKey, number>> => {\n\tconst out: Partial<Record<MetricKey, number>> = {}\n\tif (wanted.includes('pageviews')) out.pageviews = acc.pageviews\n\tif (wanted.includes('events')) out.events = acc.events\n\tif (wanted.includes('visitors')) out.visitors = acc.visitors\n\tif (wanted.includes('sessions')) out.sessions = acc.sessions\n\tif (wanted.includes('avgDuration')) {\n\t\tout.avgDuration = acc.pageviews > 0 ? Math.round(acc.durationMs / acc.pageviews) : 0\n\t}\n\treturn out\n}\n\n/**\n * Collapse per-day rollup docs into one time-series row per day in `tz` (UTC by\n * default), ascending by day. Rollups are already bucketed to their reporting-timezone\n * day at ingest, so flooring in the same `tz` is idempotent; passing the read's timezone\n * keeps a trend aligned to that zone. Distinct metrics (visitors/sessions) come from each\n * day's own rollup and are never summed across days, so a daily trend shows that day's\n * uniques.\n */\nexport const seriesFromRollups = (\n\tdocs: RollupDoc[],\n\tmetrics: MetricKey[],\n\ttz: string = DEFAULT_TIMEZONE\n): AnalyticsRow[] => {\n\tconst byDay = new Map<string, Acc>()\n\tfor (const d of docs) {\n\t\tconst day = startOfDayInTz(new Date(d.period), tz).toISOString()\n\t\tlet acc = byDay.get(day)\n\t\tif (!acc) {\n\t\t\tacc = emptyAcc()\n\t\t\tbyDay.set(day, acc)\n\t\t}\n\t\tadd(acc, d)\n\t}\n\treturn [...byDay.entries()]\n\t\t.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n\t\t.map(([day, acc]) => ({ timestamp: day, metrics: selectMetrics(acc, metrics) }))\n}\n"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"rollupAcc.js","names":[],"sources":["../../src/native/rollupAcc.ts"],"sourcesContent":["import type { AnalyticsRow, MetricKey } from '../core/contract'\nimport { DEFAULT_TIMEZONE, startOfDayInTz } from '../timeframe/tz'\n\nexport interface RollupDoc {\n\tpath: string\n\tdimvalue: string\n\tperiod: string | Date\n\tpageviews: number\n\tevents: number\n\tdurationMs: number\n\tvisitors: number\n\tsessions: number\n\t/** Optional: rows written before the goal-counter migration carry none of these. */\n\tconversions?: number\n\trevenue?: number\n\tscrollDepthSum?: number\n\tscrollSamples?: number\n}\n\nexport interface Acc {\n\tpageviews: number\n\tevents: number\n\tdurationMs: number\n\tvisitors: number\n\tsessions: number\n\tconversions: number\n\trevenue: number\n\tscrollDepthSum: number\n\t/** Pageviews that reported a scroll depth; the `scrollDepth` average's denominator. */\n\tscrollSamples: number\n}\n\nexport const emptyAcc = (): Acc => ({\n\tpageviews: 0,\n\tevents: 0,\n\tdurationMs: 0,\n\tvisitors: 0,\n\tsessions: 0,\n\tconversions: 0,\n\trevenue: 0,\n\tscrollDepthSum: 0,\n\tscrollSamples: 0,\n})\n\nexport const add = (acc: Acc, d: RollupDoc | Acc): void => {\n\tacc.pageviews += d.pageviews\n\tacc.events += d.events\n\tacc.durationMs += d.durationMs\n\tacc.visitors += d.visitors\n\tacc.sessions += d.sessions\n\tacc.conversions += d.conversions ?? 0\n\tacc.revenue += d.revenue ?? 0\n\tacc.scrollDepthSum += d.scrollDepthSum ?? 0\n\tacc.scrollSamples += d.scrollSamples ?? 0\n}\n\nexport const selectMetrics = (\n\tacc: Acc,\n\twanted: MetricKey[]\n): Partial<Record<MetricKey, number>> => {\n\tconst out: Partial<Record<MetricKey, number>> = {}\n\tif (wanted.includes('pageviews')) out.pageviews = acc.pageviews\n\tif (wanted.includes('events')) out.events = acc.events\n\tif (wanted.includes('visitors')) out.visitors = acc.visitors\n\tif (wanted.includes('sessions')) out.sessions = acc.sessions\n\tif (wanted.includes('conversions')) out.conversions = acc.conversions\n\tif (wanted.includes('revenue')) out.revenue = acc.revenue\n\tif (wanted.includes('avgDuration')) {\n\t\tout.avgDuration = acc.pageviews > 0 ? Math.round(acc.durationMs / acc.pageviews) : 0\n\t}\n\tif (wanted.includes('scrollDepth')) {\n\t\t// Averaged over the pageviews that reported a depth, never over every pageview: a\n\t\t// tracker that never got to send one must not drag the average down.\n\t\tout.scrollDepth = acc.scrollSamples > 0 ? Math.round(acc.scrollDepthSum / acc.scrollSamples) : 0\n\t}\n\treturn out\n}\n\n/**\n * Collapse per-day rollup docs into one time-series row per day in `tz` (UTC by\n * default), ascending by day. Rollups are already bucketed to their reporting-timezone\n * day at ingest, so flooring in the same `tz` is idempotent; passing the read's timezone\n * keeps a trend aligned to that zone. Distinct metrics (visitors/sessions) come from each\n * day's own rollup and are never summed across days, so a daily trend shows that day's\n * uniques.\n */\nexport const seriesFromRollups = (\n\tdocs: RollupDoc[],\n\tmetrics: MetricKey[],\n\ttz: string = DEFAULT_TIMEZONE\n): AnalyticsRow[] => {\n\tconst byDay = new Map<string, Acc>()\n\tfor (const d of docs) {\n\t\tconst day = startOfDayInTz(new Date(d.period), tz).toISOString()\n\t\tlet acc = byDay.get(day)\n\t\tif (!acc) {\n\t\t\tacc = emptyAcc()\n\t\t\tbyDay.set(day, acc)\n\t\t}\n\t\tadd(acc, d)\n\t}\n\treturn [...byDay.entries()]\n\t\t.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n\t\t.map(([day, acc]) => ({ timestamp: day, metrics: selectMetrics(acc, metr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GAAG,EAAE,EAAE,YAAY;EAC/D,IAAI,MAAM,MAAM,IAAI,GAAG;EACvB,IAAI,CAAC,KAAK;GACT,MAAM,SAAS;GACf,MAAM,IAAI,KAAK,GAAG;EACnB;EACA,IAAI,KAAK,CAAC;CACX;CACA,OAAO,CAAC,GAAG,MAAM,QAAQ,CAAC,EACxB,MAAM,CAAC,IAAI,CAAC,OAAQ,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,CAAE,EAC/C,KAAK,CAAC,KAAK,UAAU;EAAE,WAAW;EAAK,SAAS,cAAc,KAAK,OAAO;CAAE,EAAE;AACjF"}
|
|
@@ -23,7 +23,11 @@ const ZERO = {
|
|
|
23
23
|
durationMs: 0,
|
|
24
24
|
samples: 0,
|
|
25
25
|
visitors: 0,
|
|
26
|
-
sessions: 0
|
|
26
|
+
sessions: 0,
|
|
27
|
+
conversions: 0,
|
|
28
|
+
revenue: 0,
|
|
29
|
+
scrollDepthSum: 0,
|
|
30
|
+
scrollSamples: 0
|
|
27
31
|
};
|
|
28
32
|
async function bumpRollup(payload, key, inc) {
|
|
29
33
|
if (payload.db.name === "mongoose") {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bumpRollup.js","names":[],"sources":["../../../src/native/rollups/bumpRollup.ts"],"sourcesContent":["import type { Payload } from 'payload'\nimport { ROLLUPS_SLUG } from '../collections/rollups'\nimport type { RollupKey, RollupMetric } from './deltas'\n\nconst PG_TABLE_KEY = 'analytics_rollups'\n\ntype PostgresSqlModule = { sql: typeof import('@payloadcms/db-postgres')['sql'] }\n\n/**\n * Loads the optional Postgres peer without a literal specifier: bundlers (Turbopack, webpack,\n * Vite) resolve literal dynamic imports at build time, which fails a Mongo host's build even\n * though this branch is unreachable there. The function-built specifier is opaque to their\n * analyzers, the ignore comments cover bundlers that would still warn, and the type-only\n * reference above erases at compile time, so the package is touched only when the Postgres\n * branch actually runs.\n */\nconst importPostgresSql = (): Promise<PostgresSqlModule> => {\n\tconst specifier = ['@payloadcms', 'db-postgres'].join('/')\n\treturn import(\n\t\t/* webpackIgnore: true */ /* turbopackIgnore: true */ /* @vite-ignore */ specifier\n\t) as Promise<PostgresSqlModule>\n}\n\n// payload.db raw-access shapes are intentionally loose; these narrow casts reach the\n// Mongoose driver collection / Drizzle instance for atomic upserts (no public typed API).\ntype MongoDb = {\n\tname: 'mongoose'\n\tcollections: Record<\n\t\tstring,\n\t\t{ collection: { updateOne: (f: object, u: object, o: object) => Promise<unknown> } }\n\t>\n}\ntype PgDb = {\n\tname: 'postgres'\n\tdrizzle: {\n\t\tinsert: (t: unknown) => {\n\t\t\tvalues: (v: unknown) => { onConflictDoUpdate: (c: unknown) => Promise<unknown> }\n\t\t}\n\t}\n\ttables: Record<string, Record<string, unknown>>\n\ttableNameMap: Map<string, string>\n}\n\nconst ZERO: Record<RollupMetric, number> = {\n\tpageviews: 0,\n\tevents: 0,\n\tdurationMs: 0,\n\tsamples: 0,\n\tvisitors: 0,\n\tsessions: 0,\n}\n\n// Always seed every metric on insert: Payload's defaultValue is applied app-side, not as\n// a SQL default, so a raw insert that omits a NOT NULL metric column would fail on Postgres.\nexport async function bumpRollup(\n\tpayload: Payload,\n\tkey: RollupKey,\n\tinc: Partial<Record<RollupMetric, number>>\n): Promise<void> {\n\tif (payload.db.name === 'mongoose') {\n\t\tconst db = payload.db as unknown as MongoDb\n\t\tconst model = db.collections[ROLLUPS_SLUG]\n\t\tif (!model) throw new Error(`analytics: mongoose collection \"${ROLLUPS_SLUG}\" not found`)\n\t\tconst setOnInsert: Record<string, unknown> = { ...key }\n\t\tfor (const [metric, zero] of Object.entries(ZERO)) {\n\t\t\tif (!(metric in inc)) setOnInsert[metric] = zero\n\t\t}\n\t\tawait model.collection.updateOne(\n\t\t\tkey,\n\t\t\t{ $inc: inc, $setOnInsert: setOnInsert },\n\t\t\t{ upsert: true }\n\t\t)\n\t\treturn\n\t}\n\tconst { sql } = await importPostgresSql()\n\tconst db = payload.db as unknown as PgDb\n\tconst tableName = db.tableNameMap.get(PG_TABLE_KEY)\n\tif (!tableName) throw new Error(`analytics: drizzle table \"${PG_TABLE_KEY}\" not found`)\n\tconst table = db.tables[tableName]\n\tif (!table) throw new Error(`analytics: drizzle table object for \"${tableName}\" not found`)\n\tconst set: Record<string, unknown> = {}\n\tfor (const [metric, amount] of Object.entries(inc)) {\n\t\tset[metric] = sql`${table[metric]} + ${amount}`\n\t}\n\t// The conflict target must match the unique index exactly, which includes the\n\t// scope column only in scoped installs (mirrored by a scope key on RollupKey).\n\tconst target = [\n\t\ttable.granularity,\n\t\ttable.period,\n\t\ttable.path,\n\t\ttable.dimension,\n\t\ttable.dimvalue,\n\t\ttable.hostname,\n\t]\n\tif (key.scope !== undefined) {\n\t\ttarget.push(table.scope)\n\t}\n\tawait db.drizzle\n\t\t.insert(table)\n\t\t.values({ ...key, ...ZERO, ...inc })\n\t\t.onConflictDoUpdate({ target, set })\n}\n"],"mappings":";;AAIA,MAAM,eAAe;;;;;;;;;AAYrB,MAAM,0BAAsD;CAE3D,OAAO;;;;EADW,CAAC,eAAe,aAAa,EAAE,KAAK,GAE4B;;AAEnF;AAsBA,MAAM,OAAqC;CAC1C,WAAW;CACX,QAAQ;CACR,YAAY;CACZ,SAAS;CACT,UAAU;CACV,UAAU;
|
|
1
|
+
{"version":3,"file":"bumpRollup.js","names":[],"sources":["../../../src/native/rollups/bumpRollup.ts"],"sourcesContent":["import type { Payload } from 'payload'\nimport { ROLLUPS_SLUG } from '../collections/rollups'\nimport type { RollupKey, RollupMetric } from './deltas'\n\nconst PG_TABLE_KEY = 'analytics_rollups'\n\ntype PostgresSqlModule = { sql: typeof import('@payloadcms/db-postgres')['sql'] }\n\n/**\n * Loads the optional Postgres peer without a literal specifier: bundlers (Turbopack, webpack,\n * Vite) resolve literal dynamic imports at build time, which fails a Mongo host's build even\n * though this branch is unreachable there. The function-built specifier is opaque to their\n * analyzers, the ignore comments cover bundlers that would still warn, and the type-only\n * reference above erases at compile time, so the package is touched only when the Postgres\n * branch actually runs.\n */\nconst importPostgresSql = (): Promise<PostgresSqlModule> => {\n\tconst specifier = ['@payloadcms', 'db-postgres'].join('/')\n\treturn import(\n\t\t/* webpackIgnore: true */ /* turbopackIgnore: true */ /* @vite-ignore */ specifier\n\t) as Promise<PostgresSqlModule>\n}\n\n// payload.db raw-access shapes are intentionally loose; these narrow casts reach the\n// Mongoose driver collection / Drizzle instance for atomic upserts (no public typed API).\ntype MongoDb = {\n\tname: 'mongoose'\n\tcollections: Record<\n\t\tstring,\n\t\t{ collection: { updateOne: (f: object, u: object, o: object) => Promise<unknown> } }\n\t>\n}\ntype PgDb = {\n\tname: 'postgres'\n\tdrizzle: {\n\t\tinsert: (t: unknown) => {\n\t\t\tvalues: (v: unknown) => { onConflictDoUpdate: (c: unknown) => Promise<unknown> }\n\t\t}\n\t}\n\ttables: Record<string, Record<string, unknown>>\n\ttableNameMap: Map<string, string>\n}\n\nconst ZERO: Record<RollupMetric, number> = {\n\tpageviews: 0,\n\tevents: 0,\n\tdurationMs: 0,\n\tsamples: 0,\n\tvisitors: 0,\n\tsessions: 0,\n\tconversions: 0,\n\trevenue: 0,\n\tscrollDepthSum: 0,\n\tscrollSamples: 0,\n}\n\n// Always seed every metric on insert: Payload's defaultValue is applied app-side, not as\n// a SQL default, so a raw insert that omits a NOT NULL metric column would fail on Postgres.\nexport async function bumpRollup(\n\tpayload: Payload,\n\tkey: RollupKey,\n\tinc: Partial<Record<RollupMetric, number>>\n): Promise<void> {\n\tif (payload.db.name === 'mongoose') {\n\t\tconst db = payload.db as unknown as MongoDb\n\t\tconst model = db.collections[ROLLUPS_SLUG]\n\t\tif (!model) throw new Error(`analytics: mongoose collection \"${ROLLUPS_SLUG}\" not found`)\n\t\tconst setOnInsert: Record<string, unknown> = { ...key }\n\t\tfor (const [metric, zero] of Object.entries(ZERO)) {\n\t\t\tif (!(metric in inc)) setOnInsert[metric] = zero\n\t\t}\n\t\tawait model.collection.updateOne(\n\t\t\tkey,\n\t\t\t{ $inc: inc, $setOnInsert: setOnInsert },\n\t\t\t{ upsert: true }\n\t\t)\n\t\treturn\n\t}\n\tconst { sql } = await importPostgresSql()\n\tconst db = payload.db as unknown as PgDb\n\tconst tableName = db.tableNameMap.get(PG_TABLE_KEY)\n\tif (!tableName) throw new Error(`analytics: drizzle table \"${PG_TABLE_KEY}\" not found`)\n\tconst table = db.tables[tableName]\n\tif (!table) throw new Error(`analytics: drizzle table object for \"${tableName}\" not found`)\n\tconst set: Record<string, unknown> = {}\n\tfor (const [metric, amount] of Object.entries(inc)) {\n\t\tset[metric] = sql`${table[metric]} + ${amount}`\n\t}\n\t// The conflict target must match the unique index exactly, which includes the\n\t// scope column only in scoped installs (mirrored by a scope key on RollupKey).\n\tconst target = [\n\t\ttable.granularity,\n\t\ttable.period,\n\t\ttable.path,\n\t\ttable.dimension,\n\t\ttable.dimvalue,\n\t\ttable.hostname,\n\t]\n\tif (key.scope !== undefined) {\n\t\ttarget.push(table.scope)\n\t}\n\tawait db.drizzle\n\t\t.insert(table)\n\t\t.values({ ...key, ...ZERO, ...inc })\n\t\t.onConflictDoUpdate({ target, set })\n}\n"],"mappings":";;AAIA,MAAM,eAAe;;;;;;;;;AAYrB,MAAM,0BAAsD;CAE3D,OAAO;;;;EADW,CAAC,eAAe,aAAa,EAAE,KAAK,GAE4B;;AAEnF;AAsBA,MAAM,OAAqC;CAC1C,WAAW;CACX,QAAQ;CACR,YAAY;CACZ,SAAS;CACT,UAAU;CACV,UAAU;CACV,aAAa;CACb,SAAS;CACT,gBAAgB;CAChB,eAAe;AAChB;AAIA,eAAsB,WACrB,SACA,KACA,KACgB;CAChB,IAAI,QAAQ,GAAG,SAAS,YAAY;EAEnC,MAAM,QADK,QAAQ,GACF,YAAY;EAC7B,IAAI,CAAC,OAAO,MAAM,IAAI,MAAM,mCAAmC,aAAa,YAAY;EACxF,MAAM,cAAuC,EAAE,GAAG,IAAI;EACtD,KAAK,MAAM,CAAC,QAAQ,SAAS,OAAO,QAAQ,IAAI,GAC/C,IAAI,EAAE,UAAU,MAAM,YAAY,UAAU;EAE7C,MAAM,MAAM,WAAW,UACtB,KACA;GAAE,MAAM;GAAK,cAAc;EAAY,GACvC,EAAE,QAAQ,KAAK,CAChB;EACA;CACD;CACA,MAAM,EAAE,QAAQ,MAAM,kBAAkB;CACxC,MAAM,KAAK,QAAQ;CACnB,MAAM,YAAY,GAAG,aAAa,IAAI,YAAY;CAClD,IAAI,CAAC,WAAW,MAAM,IAAI,MAAM,6BAA6B,aAAa,YAAY;CACtF,MAAM,QAAQ,GAAG,OAAO;CACxB,IAAI,CAAC,OAAO,MAAM,IAAI,MAAM,wCAAwC,UAAU,YAAY;CAC1F,MAAM,MAA+B,CAAC;CACtC,KAAK,MAAM,CAAC,QAAQ,WAAW,OAAO,QAAQ,GAAG,GAChD,IAAI,UAAU,GAAG,GAAG,MAAM,QAAQ,KAAK;CAIxC,MAAM,SAAS;EACd,MAAM;EACN,MAAM;EACN,MAAM;EACN,MAAM;EACN,MAAM;EACN,MAAM;CACP;CACA,IAAI,IAAI,UAAU,KAAA,GACjB,OAAO,KAAK,MAAM,KAAK;CAExB,MAAM,GAAG,QACP,OAAO,KAAK,EACZ,OAAO;EAAE,GAAG;EAAK,GAAG;EAAM,GAAG;CAAI,CAAC,EAClC,mBAAmB;EAAE;EAAQ;CAAI,CAAC;AACrC"}
|
|
@@ -8,16 +8,26 @@ import { startOfDayInTz } from "../../timeframe/tz.js";
|
|
|
8
8
|
* reads use, and once more in the exact-hostname family that a hostname-scoped read uses.
|
|
9
9
|
* Both families stay per-bucket exact at the cost of one extra bucket set per distinct
|
|
10
10
|
* hostname a site sees.
|
|
11
|
+
*
|
|
12
|
+
* Goal completions add one `('', 'goal', slug)` bucket each, carrying that goal's own single
|
|
13
|
+
* conversion, while every other bucket carries the event's whole conversion count, so a
|
|
14
|
+
* site-wide or per-page total never has to scan the goal buckets.
|
|
11
15
|
*/
|
|
12
16
|
function computeRollupDeltas(event) {
|
|
13
17
|
const period = startOfDayInTz(event.timestamp, event.timezone);
|
|
18
|
+
const completions = event.goals ?? [];
|
|
19
|
+
const reportedDepth = event.scrollDepth !== void 0;
|
|
14
20
|
const inc = {
|
|
15
21
|
pageviews: event.type === "pageview" ? 1 : 0,
|
|
16
|
-
events: event.type === "
|
|
22
|
+
events: event.type === "pageview" ? 0 : 1,
|
|
17
23
|
durationMs: event.durationMs ?? 0,
|
|
18
|
-
samples: 1
|
|
24
|
+
samples: 1,
|
|
25
|
+
conversions: completions.length,
|
|
26
|
+
revenue: completions.reduce((sum, goal) => sum + goal.value, 0),
|
|
27
|
+
scrollDepthSum: reportedDepth ? event.scrollDepth ?? 0 : 0,
|
|
28
|
+
scrollSamples: reportedDepth ? 1 : 0
|
|
19
29
|
};
|
|
20
|
-
const make = (bucket, hostname) => ({
|
|
30
|
+
const make = (bucket, hostname, over) => ({
|
|
21
31
|
key: {
|
|
22
32
|
granularity: "day",
|
|
23
33
|
period,
|
|
@@ -27,7 +37,10 @@ function computeRollupDeltas(event) {
|
|
|
27
37
|
hostname,
|
|
28
38
|
...event.scope !== void 0 ? { scope: event.scope } : {}
|
|
29
39
|
},
|
|
30
|
-
inc: {
|
|
40
|
+
inc: {
|
|
41
|
+
...inc,
|
|
42
|
+
...over
|
|
43
|
+
}
|
|
31
44
|
});
|
|
32
45
|
const buckets = [[
|
|
33
46
|
event.path,
|
|
@@ -58,8 +71,17 @@ function computeRollupDeltas(event) {
|
|
|
58
71
|
"source",
|
|
59
72
|
event.source
|
|
60
73
|
]);
|
|
61
|
-
const
|
|
62
|
-
|
|
74
|
+
const families = event.hostname ? ["", event.hostname] : [""];
|
|
75
|
+
const deltas = [];
|
|
76
|
+
for (const hostname of families) deltas.push(...buckets.map((bucket) => make(bucket, hostname)));
|
|
77
|
+
for (const hostname of families) for (const completion of completions) deltas.push(make([
|
|
78
|
+
"",
|
|
79
|
+
"goal",
|
|
80
|
+
completion.slug
|
|
81
|
+
], hostname, {
|
|
82
|
+
conversions: 1,
|
|
83
|
+
revenue: completion.value
|
|
84
|
+
}));
|
|
63
85
|
return deltas;
|
|
64
86
|
}
|
|
65
87
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"deltas.js","names":[],"sources":["../../../src/native/rollups/deltas.ts"],"sourcesContent":["import { startOfDayInTz } from '../../timeframe/tz'\nimport type { StoredEvent } from '../ingest/normalizeEvent'\n\nexport interface RollupKey {\n\tgranularity: 'day'\n\tperiod: Date\n\tpath: string\n\tdimension: string\n\tdimvalue: string\n\t/** '' is the hostname-less bucket family; a real hostname is its own family. */\n\thostname: string\n\t/** Present only in scoped installs, where it is part of the unique bucket. */\n\tscope?: string\n}\n\nexport type RollupMetric =\n\t| 'pageviews'\n\t| 'events'\n\t| 'durationMs'\n\t| 'samples'\n\t| 'visitors'\n\t| 'sessions'\n\nexport
|
|
1
|
+
{"version":3,"file":"deltas.js","names":[],"sources":["../../../src/native/rollups/deltas.ts"],"sourcesContent":["import { startOfDayInTz } from '../../timeframe/tz'\nimport type { StoredEvent } from '../ingest/normalizeEvent'\n\nexport interface RollupKey {\n\tgranularity: 'day'\n\tperiod: Date\n\tpath: string\n\tdimension: string\n\tdimvalue: string\n\t/** '' is the hostname-less bucket family; a real hostname is its own family. */\n\thostname: string\n\t/** Present only in scoped installs, where it is part of the unique bucket. */\n\tscope?: string\n}\n\nexport type RollupMetric =\n\t| 'pageviews'\n\t| 'events'\n\t| 'durationMs'\n\t| 'samples'\n\t| 'visitors'\n\t| 'sessions'\n\t| 'conversions'\n\t| 'revenue'\n\t| 'scrollDepthSum'\n\t| 'scrollSamples'\n\n/**\n * `samples` counts every event in the bucket, so it cannot be the scroll-depth denominator:\n * `scrollSamples` counts only the pageviews that actually reported a depth, which is what\n * keeps the `scrollDepth` average honest when the tracker never got to send one.\n */\nexport type RollupInc = {\n\tpageviews: number\n\tevents: number\n\tdurationMs: number\n\tsamples: number\n\tconversions: number\n\trevenue: number\n\tscrollDepthSum: number\n\tscrollSamples: number\n}\n\nexport interface RollupDelta {\n\tkey: RollupKey\n\tinc: RollupInc\n}\n\n/**\n * Distinct metrics (visitors, sessions) are exact per bucket and must never be summed\n * across buckets, so an unfiltered read has to hit its own exact family rather than\n * derive from a hostname-scoped one (or vice versa). Every bucket is therefore emitted\n * twice when a hostname is present: once in the hostname-less ('') family that unfiltered\n * reads use, and once more in the exact-hostname family that a hostname-scoped read uses.\n * Both families stay per-bucket exact at the cost of one extra bucket set per distinct\n * hostname a site sees.\n *\n * Goal completions add one `('', 'goal', slug)` bucket each, carrying that goal's own single\n * conversion, while every other bucket carries the event's whole conversion count, so a\n * site-wide or per-page total never has to scan the goal buckets.\n */\nexport function computeRollupDeltas(event: StoredEvent): RollupDelta[] {\n\t// Bucket into the event's reporting-timezone day (UTC when unset), fixing the day\n\t// boundary at ingest. Existing rollups are not re-bucketed if the timezone changes.\n\tconst period = startOfDayInTz(event.timestamp, event.timezone)\n\tconst completions = event.goals ?? []\n\tconst reportedDepth = event.scrollDepth !== undefined\n\tconst inc: RollupInc = {\n\t\tpageviews: event.type === 'pageview' ? 1 : 0,\n\t\t// A `goal` event is a non-pageview hit like a custom event; it stays out of the\n\t\t// `event` dimension breakdown, which reports named custom events only.\n\t\tevents: event.type === 'pageview' ? 0 : 1,\n\t\tdurationMs: event.durationMs ?? 0,\n\t\tsamples: 1,\n\t\tconversions: completions.length,\n\t\trevenue: completions.reduce((sum, goal) => sum + goal.value, 0),\n\t\tscrollDepthSum: reportedDepth ? (event.scrollDepth ?? 0) : 0,\n\t\tscrollSamples: reportedDepth ? 1 : 0,\n\t}\n\tconst make = (\n\t\tbucket: [path: string, dimension: string, dimvalue: string],\n\t\thostname: string,\n\t\tover?: Partial<RollupInc>\n\t): RollupDelta => ({\n\t\tkey: {\n\t\t\tgranularity: 'day',\n\t\t\tperiod,\n\t\t\tpath: bucket[0],\n\t\t\tdimension: bucket[1],\n\t\t\tdimvalue: bucket[2],\n\t\t\thostname,\n\t\t\t...(event.scope !== undefined ? { scope: event.scope } : {}),\n\t\t},\n\t\tinc: { ...inc, ...over },\n\t})\n\tconst buckets: Array<[path: string, dimension: string, dimvalue: string]> = [\n\t\t[event.path, '', ''],\n\t\t['', '', ''],\n\t]\n\tif (event.type === 'event' && event.name) {\n\t\tbuckets.push(['', 'event', event.name])\n\t}\n\tif (event.country) {\n\t\tbuckets.push(['', 'country', event.country])\n\t}\n\tif (event.device) {\n\t\tbuckets.push(['', 'device', event.device])\n\t}\n\tif (event.source) {\n\t\tbuckets.push(['', 'source', event.source])\n\t}\n\tconst families = event.hostname ? ['', event.hostname] : ['']\n\tconst deltas: RollupDelta[] = []\n\tfor (const hostname of families) {\n\t\tdeltas.push(...buckets.map((bucket) => make(bucket, hostname)))\n\t}\n\tfor (const hostname of families) {\n\t\tfor (const completion of completions) {\n\t\t\tdeltas.push(\n\t\t\t\tmake(['', 'goal', completion.slug], hostname, {\n\t\t\t\t\tconversions: 1,\n\t\t\t\t\trevenue: completion.value,\n\t\t\t\t})\n\t\t\t)\n\t\t}\n\t}\n\treturn deltas\n}\n"],"mappings":";;;;;;;;;;;;;;;AA6DA,SAAgB,oBAAoB,OAAmC;CAGtE,MAAM,SAAS,eAAe,MAAM,WAAW,MAAM,QAAQ;CAC7D,MAAM,cAAc,MAAM,SAAS,CAAC;CACpC,MAAM,gBAAgB,MAAM,gBAAgB,KAAA;CAC5C,MAAM,MAAiB;EACtB,WAAW,MAAM,SAAS,aAAa,IAAI;EAG3C,QAAQ,MAAM,SAAS,aAAa,IAAI;EACxC,YAAY,MAAM,cAAc;EAChC,SAAS;EACT,aAAa,YAAY;EACzB,SAAS,YAAY,QAAQ,KAAK,SAAS,MAAM,KAAK,OAAO,CAAC;EAC9D,gBAAgB,gBAAiB,MAAM,eAAe,IAAK;EAC3D,eAAe,gBAAgB,IAAI;CACpC;CACA,MAAM,QACL,QACA,UACA,UACkB;EAClB,KAAK;GACJ,aAAa;GACb;GACA,MAAM,OAAO;GACb,WAAW,OAAO;GAClB,UAAU,OAAO;GACjB;GACA,GAAI,MAAM,UAAU,KAAA,IAAY,EAAE,OAAO,MAAM,MAAM,IAAI,CAAC;EAC3D;EACA,KAAK;GAAE,GAAG;GAAK,GAAG;EAAK;CACxB;CACA,MAAM,UAAsE,CAC3E;EAAC,MAAM;EAAM;EAAI;CAAE,GACnB;EAAC;EAAI;EAAI;CAAE,CACZ;CACA,IAAI,MAAM,SAAS,WAAW,MAAM,MACnC,QAAQ,KAAK;EAAC;EAAI;EAAS,MAAM;CAAI,CAAC;CAEvC,IAAI,MAAM,SACT,QAAQ,KAAK;EAAC;EAAI;EAAW,MAAM;CAAO,CAAC;CAE5C,IAAI,MAAM,QACT,QAAQ,KAAK;EAAC;EAAI;EAAU,MAAM;CAAM,CAAC;CAE1C,IAAI,MAAM,QACT,QAAQ,KAAK;EAAC;EAAI;EAAU,MAAM;CAAM,CAAC;CAE1C,MAAM,WAAW,MAAM,WAAW,CAAC,IAAI,MAAM,QAAQ,IAAI,CAAC,EAAE;CAC5D,MAAM,SAAwB,CAAC;CAC/B,KAAK,MAAM,YAAY,UACtB,OAAO,KAAK,GAAG,QAAQ,KAAK,WAAW,KAAK,QAAQ,QAAQ,CAAC,CAAC;CAE/D,KAAK,MAAM,YAAY,UACtB,KAAK,MAAM,cAAc,aACxB,OAAO,KACN,KAAK;EAAC;EAAI;EAAQ,WAAW;CAAI,GAAG,UAAU;EAC7C,aAAa;EACb,SAAS,WAAW;CACrB,CAAC,CACF;CAGF,OAAO;AACR"}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { AnalyticsAdapter } from "../core/contract.js";
|
|
2
|
+
|
|
3
|
+
//#region src/next/captureRewrites.d.ts
|
|
4
|
+
/** One Next.js rewrite entry (the shape `next.config` `rewrites()` returns). */
|
|
5
|
+
interface CaptureRewrite {
|
|
6
|
+
source: string;
|
|
7
|
+
destination: string;
|
|
8
|
+
}
|
|
9
|
+
/** An adapter's capture proxy mounted at a base path in the consumer's Next app. */
|
|
10
|
+
interface CaptureRewriteMount {
|
|
11
|
+
/** Base path this adapter's proxy is mounted at, e.g. '/ph' or '/api/analytics/p/global'. */
|
|
12
|
+
path: string;
|
|
13
|
+
adapter: AnalyticsAdapter;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Next.js `rewrites()` entries for every adapter's capture proxy, one mount at a time.
|
|
17
|
+
* Each route's `source`/`upstream` already share `path-to-regexp` param names (e.g.
|
|
18
|
+
* `:p*`), so no translation happens beyond prefixing `source` with the mount's
|
|
19
|
+
* (normalized) path; `upstream` is used verbatim as `destination`. Next always strips a
|
|
20
|
+
* trailing slash from the matched path before substituting it into `destination` (unlike
|
|
21
|
+
* the runtime proxy, which can be told to keep one via `trailingSlashes`); harmless for
|
|
22
|
+
* every vendor this helper supports today.
|
|
23
|
+
*
|
|
24
|
+
* An adapter without `capture` (GA4) or with no proxy routes (the native adapter)
|
|
25
|
+
* contributes nothing rather than throwing, so one broken slot never blanks the rest.
|
|
26
|
+
* Output preserves mount order, then each mount's declared route order.
|
|
27
|
+
*
|
|
28
|
+
* Throws for a mount path that normalizes to the site root (an unprefixed catch-all
|
|
29
|
+
* route would swallow the whole app) or for two mounts whose normalized paths are equal
|
|
30
|
+
* or nested (Next matches rewrites first-match-wins, so an earlier catch-all would
|
|
31
|
+
* silently shadow a later mount's routes). Distinct sibling paths that merely share a
|
|
32
|
+
* string prefix, e.g. `/ph` and `/phx`, are unaffected.
|
|
33
|
+
*
|
|
34
|
+
* When any mounted adapter's descriptor sets `capture.proxy.trailingSlashes`, add
|
|
35
|
+
* `skipTrailingSlashRedirect: true` to `next.config` (see `posthogProxyRewrites`'s
|
|
36
|
+
* JSDoc for why PostHog needs it).
|
|
37
|
+
*/
|
|
38
|
+
declare const captureRewrites: (mounts: CaptureRewriteMount[]) => CaptureRewrite[];
|
|
39
|
+
//#endregion
|
|
40
|
+
export { CaptureRewrite, CaptureRewriteMount, captureRewrites };
|
|
41
|
+
//# sourceMappingURL=captureRewrites.d.ts.map
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { normalizeMountPath } from "../capture/mountPath.js";
|
|
2
|
+
//#region src/next/captureRewrites.ts
|
|
3
|
+
const assertNotRoot = (path) => {
|
|
4
|
+
if (path === "/") throw new Error("captureRewrites: mount path must not be the site root");
|
|
5
|
+
};
|
|
6
|
+
const isPrefixOrEqual = (a, b) => a === b || b.startsWith(`${a}/`);
|
|
7
|
+
const assertNoCollisions = (paths) => {
|
|
8
|
+
for (let i = 0; i < paths.length; i++) for (let j = i + 1; j < paths.length; j++) {
|
|
9
|
+
const a = paths[i];
|
|
10
|
+
const b = paths[j];
|
|
11
|
+
if (isPrefixOrEqual(a, b) || isPrefixOrEqual(b, a)) throw new Error(`captureRewrites: mount paths collide: '${a}' and '${b}'`);
|
|
12
|
+
}
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Next.js `rewrites()` entries for every adapter's capture proxy, one mount at a time.
|
|
16
|
+
* Each route's `source`/`upstream` already share `path-to-regexp` param names (e.g.
|
|
17
|
+
* `:p*`), so no translation happens beyond prefixing `source` with the mount's
|
|
18
|
+
* (normalized) path; `upstream` is used verbatim as `destination`. Next always strips a
|
|
19
|
+
* trailing slash from the matched path before substituting it into `destination` (unlike
|
|
20
|
+
* the runtime proxy, which can be told to keep one via `trailingSlashes`); harmless for
|
|
21
|
+
* every vendor this helper supports today.
|
|
22
|
+
*
|
|
23
|
+
* An adapter without `capture` (GA4) or with no proxy routes (the native adapter)
|
|
24
|
+
* contributes nothing rather than throwing, so one broken slot never blanks the rest.
|
|
25
|
+
* Output preserves mount order, then each mount's declared route order.
|
|
26
|
+
*
|
|
27
|
+
* Throws for a mount path that normalizes to the site root (an unprefixed catch-all
|
|
28
|
+
* route would swallow the whole app) or for two mounts whose normalized paths are equal
|
|
29
|
+
* or nested (Next matches rewrites first-match-wins, so an earlier catch-all would
|
|
30
|
+
* silently shadow a later mount's routes). Distinct sibling paths that merely share a
|
|
31
|
+
* string prefix, e.g. `/ph` and `/phx`, are unaffected.
|
|
32
|
+
*
|
|
33
|
+
* When any mounted adapter's descriptor sets `capture.proxy.trailingSlashes`, add
|
|
34
|
+
* `skipTrailingSlashRedirect: true` to `next.config` (see `posthogProxyRewrites`'s
|
|
35
|
+
* JSDoc for why PostHog needs it).
|
|
36
|
+
*/
|
|
37
|
+
const captureRewrites = (mounts) => {
|
|
38
|
+
const normalized = mounts.map((mount) => normalizeMountPath(mount.path));
|
|
39
|
+
for (const path of normalized) assertNotRoot(path);
|
|
40
|
+
assertNoCollisions(normalized);
|
|
41
|
+
const rewrites = [];
|
|
42
|
+
for (let i = 0; i < mounts.length; i++) {
|
|
43
|
+
const routes = mounts[i].adapter.capture?.proxy.routes;
|
|
44
|
+
if (!routes?.length) continue;
|
|
45
|
+
const base = normalized[i];
|
|
46
|
+
for (const route of routes) rewrites.push({
|
|
47
|
+
source: `${base}${route.source}`,
|
|
48
|
+
destination: route.upstream
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
return rewrites;
|
|
52
|
+
};
|
|
53
|
+
//#endregion
|
|
54
|
+
export { captureRewrites };
|
|
55
|
+
|
|
56
|
+
//# sourceMappingURL=captureRewrites.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"captureRewrites.js","names":[],"sources":["../../src/next/captureRewrites.ts"],"sourcesContent":["import { normalizeMountPath } from '../capture/mountPath'\nimport type { AnalyticsAdapter } from '../core/contract'\n\n/** One Next.js rewrite entry (the shape `next.config` `rewrites()` returns). */\nexport interface CaptureRewrite {\n\tsource: string\n\tdestination: string\n}\n\n/** An adapter's capture proxy mounted at a base path in the consumer's Next app. */\nexport interface CaptureRewriteMount {\n\t/** Base path this adapter's proxy is mounted at, e.g. '/ph' or '/api/analytics/p/global'. */\n\tpath: string\n\tadapter: AnalyticsAdapter\n}\n\nconst assertNotRoot = (path: string): void => {\n\tif (path === '/') {\n\t\tthrow new Error('captureRewrites: mount path must not be the site root')\n\t}\n}\n\n// One base is a prefix of another when they're equal or the longer one continues past a\n// '/' boundary, so '/ph' collides with '/ph' and '/ph/x' but not the mere string-prefix\n// sibling '/phx'.\nconst isPrefixOrEqual = (a: string, b: string): boolean => a === b || b.startsWith(`${a}/`)\n\nconst assertNoCollisions = (paths: string[]): void => {\n\tfor (let i = 0; i < paths.length; i++) {\n\t\tfor (let j = i + 1; j < paths.length; j++) {\n\t\t\tconst a = paths[i] as string\n\t\t\tconst b = paths[j] as string\n\t\t\tif (isPrefixOrEqual(a, b) || isPrefixOrEqual(b, a)) {\n\t\t\t\tthrow new Error(`captureRewrites: mount paths collide: '${a}' and '${b}'`)\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Next.js `rewrites()` entries for every adapter's capture proxy, one mount at a time.\n * Each route's `source`/`upstream` already share `path-to-regexp` param names (e.g.\n * `:p*`), so no translation happens beyond prefixing `source` with the mount's\n * (normalized) path; `upstream` is used verbatim as `destination`. Next always strips a\n * trailing slash from the matched path before substituting it into `destination` (unlike\n * the runtime proxy, which can be told to keep one via `trailingSlashes`); harmless for\n * every vendor this helper supports today.\n *\n * An adapter without `capture` (GA4) or with no proxy routes (the native adapter)\n * contributes nothing rather than throwing, so one broken slot never blanks the rest.\n * Output preserves mount order, then each mount's declared route order.\n *\n * Throws for a mount path that normalizes to the site root (an unprefixed catch-all\n * route would swallow the whole app) or for two mounts whose normalized paths are equal\n * or nested (Next matches rewrites first-match-wins, so an earlier catch-all would\n * silently shadow a later mount's routes). Distinct sibling paths that merely share a\n * string prefix, e.g. `/ph` and `/phx`, are unaffected.\n *\n * When any mounted adapter's descriptor sets `capture.proxy.trailingSlashes`, add\n * `skipTrailingSlashRedirect: true` to `next.config` (see `posthogProxyRewrites`'s\n * JSDoc for why PostHog needs it).\n */\nexport const captureRewrites = (mounts: CaptureRewriteMount[]): CaptureRewrite[] => {\n\tconst normalized = mounts.map((mount) => normalizeMountPath(mount.path))\n\tfor (const path of normalized) {\n\t\tassertNotRoot(path)\n\t}\n\tassertNoCollisions(normalized)\n\n\tconst rewrites: CaptureRewrite[] = []\n\tfor (let i = 0; i < mounts.length; i++) {\n\t\tconst mount = mounts[i] as CaptureRewriteMount\n\t\tconst routes = mount.adapter.capture?.proxy.routes\n\t\tif (!routes?.length) {\n\t\t\tcontinue\n\t\t}\n\t\tconst base = normalized[i] as string\n\t\tfor (const route of routes) {\n\t\t\trewrites.push({ source: `${base}${route.source}`, destination: route.upstream })\n\t\t}\n\t}\n\treturn rewrites\n}\n"],"mappings":";;AAgBA,MAAM,iBAAiB,SAAuB;CAC7C,IAAI,SAAS,KACZ,MAAM,IAAI,MAAM,uDAAuD;AAEzE;AAKA,MAAM,mBAAmB,GAAW,MAAuB,MAAM,KAAK,EAAE,WAAW,GAAG,EAAE,EAAE;AAE1F,MAAM,sBAAsB,UAA0B;CACrD,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KACjC,KAAK,IAAI,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;EAC1C,MAAM,IAAI,MAAM;EAChB,MAAM,IAAI,MAAM;EAChB,IAAI,gBAAgB,GAAG,CAAC,KAAK,gBAAgB,GAAG,CAAC,GAChD,MAAM,IAAI,MAAM,0CAA0C,EAAE,SAAS,EAAE,EAAE;CAE3E;AAEF;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,MAAa,mBAAmB,WAAoD;CACnF,MAAM,aAAa,OAAO,KAAK,UAAU,mBAAmB,MAAM,IAAI,CAAC;CACvE,KAAK,MAAM,QAAQ,YAClB,cAAc,IAAI;CAEnB,mBAAmB,UAAU;CAE7B,MAAM,WAA6B,CAAC;CACpC,KAAK,IAAI,IAAI,GAAG,IAAI,OAAO,QAAQ,KAAK;EAEvC,MAAM,SADQ,OAAO,GACA,QAAQ,SAAS,MAAM;EAC5C,IAAI,CAAC,QAAQ,QACZ;EAED,MAAM,OAAO,WAAW;EACxB,KAAK,MAAM,SAAS,QACnB,SAAS,KAAK;GAAE,QAAQ,GAAG,OAAO,MAAM;GAAU,aAAa,MAAM;EAAS,CAAC;CAEjF;CACA,OAAO;AACR"}
|
|
@@ -29,6 +29,11 @@ type PosthogProxyRewritesOptions = {
|
|
|
29
29
|
* ```
|
|
30
30
|
*
|
|
31
31
|
* Point the snippet at it with `api_host: '/ph'` (plus `ui_host` for the region).
|
|
32
|
+
*
|
|
33
|
+
* @deprecated Use `captureRewrites` with a `posthog()` adapter instance instead: this
|
|
34
|
+
* helper is now a thin wrapper over it, kept only so existing `next.config` files don't
|
|
35
|
+
* break. `captureRewrites` also covers Plausible, Umami, and any adapter that mixes
|
|
36
|
+
* PostHog with another vendor across multiple mount paths.
|
|
32
37
|
*/
|
|
33
38
|
declare const posthogProxyRewrites: (options?: PosthogProxyRewritesOptions) => PosthogProxyRewrite[];
|
|
34
39
|
//#endregion
|
|
@@ -1,8 +1,6 @@
|
|
|
1
|
+
import { posthog } from "../adapters/posthog/posthog.js";
|
|
2
|
+
import { captureRewrites } from "./captureRewrites.js";
|
|
1
3
|
//#region src/next/posthogProxyRewrites.ts
|
|
2
|
-
const normalizePath = (path) => {
|
|
3
|
-
const trimmed = (path.startsWith("/") ? path : `/${path}`).replace(/\/+$/, "");
|
|
4
|
-
return trimmed === "" ? "/" : trimmed;
|
|
5
|
-
};
|
|
6
4
|
/**
|
|
7
5
|
* Next.js rewrites for a first-party PostHog reverse proxy, per PostHog's own
|
|
8
6
|
* guidance: static assets and the array loader route to the region's assets host,
|
|
@@ -23,26 +21,23 @@ const normalizePath = (path) => {
|
|
|
23
21
|
* ```
|
|
24
22
|
*
|
|
25
23
|
* Point the snippet at it with `api_host: '/ph'` (plus `ui_host` for the region).
|
|
24
|
+
*
|
|
25
|
+
* @deprecated Use `captureRewrites` with a `posthog()` adapter instance instead: this
|
|
26
|
+
* helper is now a thin wrapper over it, kept only so existing `next.config` files don't
|
|
27
|
+
* break. `captureRewrites` also covers Plausible, Umami, and any adapter that mixes
|
|
28
|
+
* PostHog with another vendor across multiple mount paths.
|
|
26
29
|
*/
|
|
27
30
|
const posthogProxyRewrites = (options = {}) => {
|
|
28
31
|
const region = options.region ?? "eu";
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
source: `${path}/array/:path*`,
|
|
39
|
-
destination: `${assets}/array/:path*`
|
|
40
|
-
},
|
|
41
|
-
{
|
|
42
|
-
source: `${path}/:path*`,
|
|
43
|
-
destination: `${ingest}/:path*`
|
|
44
|
-
}
|
|
45
|
-
];
|
|
32
|
+
return captureRewrites([{
|
|
33
|
+
path: options.path ?? "/ph",
|
|
34
|
+
adapter: posthog({
|
|
35
|
+
projectId: "",
|
|
36
|
+
apiKey: "",
|
|
37
|
+
region,
|
|
38
|
+
projectToken: "rewrites-only"
|
|
39
|
+
})
|
|
40
|
+
}]);
|
|
46
41
|
};
|
|
47
42
|
//#endregion
|
|
48
43
|
export { posthogProxyRewrites };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"posthogProxyRewrites.js","names":[],"sources":["../../src/next/posthogProxyRewrites.ts"],"sourcesContent":["
|
|
1
|
+
{"version":3,"file":"posthogProxyRewrites.js","names":[],"sources":["../../src/next/posthogProxyRewrites.ts"],"sourcesContent":["import { posthog } from '../adapters/posthog/posthog'\nimport { captureRewrites } from './captureRewrites'\n\nexport type PosthogProxyRegion = 'eu' | 'us'\n\n/** One Next.js rewrite entry (the shape `next.config` `rewrites()` returns). */\nexport type PosthogProxyRewrite = { source: string; destination: string }\n\nexport type PosthogProxyRewritesOptions = {\n\t/** First-party base path the snippet's `api_host` points at. Default '/ph'. */\n\tpath?: string\n\t/** PostHog Cloud region. Default 'eu'. */\n\tregion?: PosthogProxyRegion\n}\n\n/**\n * Next.js rewrites for a first-party PostHog reverse proxy, per PostHog's own\n * guidance: static assets and the array loader route to the region's assets host,\n * everything else to the ingest host. Order matters (Next evaluates rewrites in\n * order), and the app should also set `skipTrailingSlashRedirect: true` because\n * PostHog's capture endpoints use trailing slashes.\n *\n * ```ts\n * // next.config.ts\n * import { posthogProxyRewrites } from '@10x-media/analytics/next'\n *\n * const nextConfig = {\n * skipTrailingSlashRedirect: true,\n * async rewrites() {\n * return posthogProxyRewrites({ path: '/ph', region: 'eu' })\n * },\n * }\n * ```\n *\n * Point the snippet at it with `api_host: '/ph'` (plus `ui_host` for the region).\n *\n * @deprecated Use `captureRewrites` with a `posthog()` adapter instance instead: this\n * helper is now a thin wrapper over it, kept only so existing `next.config` files don't\n * break. `captureRewrites` also covers Plausible, Umami, and any adapter that mixes\n * PostHog with another vendor across multiple mount paths.\n */\nexport const posthogProxyRewrites = (\n\toptions: PosthogProxyRewritesOptions = {}\n): PosthogProxyRewrite[] => {\n\tconst region = options.region ?? 'eu'\n\tconst path = options.path ?? '/ph'\n\t// A token is what makes an adapter declare capture, and only the capture descriptor's\n\t// routes are read here; the placeholder never reaches a snippet or a browser.\n\tconst adapter = posthog({ projectId: '', apiKey: '', region, projectToken: 'rewrites-only' })\n\treturn captureRewrites([{ path, adapter }])\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,MAAa,wBACZ,UAAuC,CAAC,MACb;CAC3B,MAAM,SAAS,QAAQ,UAAU;CAKjC,OAAO,gBAAgB,CAAC;EAAE,MAJb,QAAQ,QAAQ;EAIG,SADhB,QAAQ;GAAE,WAAW;GAAI,QAAQ;GAAI;GAAQ,cAAc;EAAgB,CACrD;CAAE,CAAC,CAAC;AAC3C"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
+
import "./paths.js";
|
|
1
2
|
import { getRuntime } from "./runtime.js";
|
|
2
3
|
import { TIMEFRAME_PRESETS } from "../timeframe/presets.js";
|
|
3
4
|
import { readForField } from "../fields/readForDocument.js";
|
|
4
5
|
import { METRIC_KEYS } from "../translations/metricKeys.js";
|
|
5
|
-
import "./paths.js";
|
|
6
6
|
//#region src/plugin/documentEndpoint.ts
|
|
7
7
|
const KNOWN_METRICS = new Set(Object.keys(METRIC_KEYS));
|
|
8
8
|
const MAX_METRICS = 8;
|
package/dist/plugin/paths.js
CHANGED
|
@@ -7,7 +7,17 @@
|
|
|
7
7
|
const DOCUMENT_PATH = "/analytics/document";
|
|
8
8
|
const SOURCES_PATH = "/analytics/sources";
|
|
9
9
|
const REALTIME_PATH = "/analytics/realtime";
|
|
10
|
+
/** Mount of the public capture proxy; each slot is served under `${PROXY_PATH}/<slot>`. */
|
|
11
|
+
const PROXY_PATH = "/analytics/p";
|
|
12
|
+
/** Public tracker config, per-request scope. */
|
|
13
|
+
const TRACKER_PATH = "/analytics/tracker";
|
|
14
|
+
/**
|
|
15
|
+
* Default mount of the native ingest endpoint, and the fallback for the `ingestPath` the
|
|
16
|
+
* tracker config hands the browser. `native({ ingestPath })` moves both: the adapter
|
|
17
|
+
* declares the override through `ingest.path`, which the runtime lifts onto the config.
|
|
18
|
+
*/
|
|
19
|
+
const INGEST_PATH = "/analytics/ingest";
|
|
10
20
|
//#endregion
|
|
11
|
-
export { DOCUMENT_PATH, REALTIME_PATH, SOURCES_PATH };
|
|
21
|
+
export { DOCUMENT_PATH, INGEST_PATH, PROXY_PATH, REALTIME_PATH, SOURCES_PATH, TRACKER_PATH };
|
|
12
22
|
|
|
13
23
|
//# sourceMappingURL=paths.js.map
|
package/dist/plugin/paths.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"paths.js","names":[],"sources":["../../src/plugin/paths.ts"],"sourcesContent":["/**\n * Endpoint paths shared between server registration and client fetchers. Kept in a\n * dependency-free leaf module so client components can import the path without\n * pulling server code into the bundle.\n */\nexport const DOCUMENT_PATH = '/analytics/document'\nexport const SOURCES_PATH = '/analytics/sources'\nexport const REALTIME_PATH = '/analytics/realtime'\n"],"mappings":";;;;;;AAKA,MAAa,gBAAgB;AAC7B,MAAa,eAAe;AAC5B,MAAa,gBAAgB"}
|
|
1
|
+
{"version":3,"file":"paths.js","names":[],"sources":["../../src/plugin/paths.ts"],"sourcesContent":["/**\n * Endpoint paths shared between server registration and client fetchers. Kept in a\n * dependency-free leaf module so client components can import the path without\n * pulling server code into the bundle.\n */\nexport const DOCUMENT_PATH = '/analytics/document'\nexport const SOURCES_PATH = '/analytics/sources'\nexport const REALTIME_PATH = '/analytics/realtime'\n/** Mount of the public capture proxy; each slot is served under `${PROXY_PATH}/<slot>`. */\nexport const PROXY_PATH = '/analytics/p'\n/** Public tracker config, per-request scope. */\nexport const TRACKER_PATH = '/analytics/tracker'\n/**\n * Default mount of the native ingest endpoint, and the fallback for the `ingestPath` the\n * tracker config hands the browser. `native({ ingestPath })` moves both: the adapter\n * declares the override through `ingest.path`, which the runtime lifts onto the config.\n */\nexport const INGEST_PATH = '/analytics/ingest'\n"],"mappings":";;;;;;AAKA,MAAa,gBAAgB;AAC7B,MAAa,eAAe;AAC5B,MAAa,gBAAgB;;AAE7B,MAAa,aAAa;;AAE1B,MAAa,eAAe;;;;;;AAM5B,MAAa,cAAc"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import { Payload, PayloadRequest } from "payload";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.js","names":[],"sources":["../../src/plugin/runtime.ts"],"sourcesContent":["import type { Payload, PayloadRequest } from 'payload'\nimport type { ResolvedBinding } from '../binding/types'\nimport type { AdapterRegistry, RegistryResolver, ResolveRegistryArgs } from '../core/registry'\nimport type { Engine } from '../surfacing/engine'\nimport { DEFAULT_TIMEZONE } from '../timeframe/tz'\n\nexport interface AnalyticsRuntime {\n\tregistry: AdapterRegistry\n\t/** Per-scope adapter resolution; absent runtimes fall back to the static registry. */\n\tresolveRegistry?: RegistryResolver\n\t/** The plugin's scopeResolver bound at init; absent runtimes resolve null. */\n\tresolveScope?: (req: PayloadRequest) => Promise<string | null>\n\t/** The plugin's reportingTimezone bound at init; absent runtimes resolve 'UTC'. */\n\tresolveTimezone?: (req: PayloadRequest, scope?: string | null) => Promise<string>\n\t/** Id of the config adapter shared by every scope, when one is designated. */\n\tplatformAdapterId?: string\n\t/**\n\t * Ids of the config-time adapters shared by every scope (the ones passed to\n\t * `adapters` in plugin options). Runtime provider adapters (resolved per scope\n\t * from the providers collection or `providers.resolve`) are never in it.\n\t */\n\tconfigAdapterIds: ReadonlySet<string>\n\t/** Gate for cross-scope reads; absent runtimes require an authenticated user. */\n\tplatformRead?: (args: { req: PayloadRequest }) => boolean | Promise<boolean>\n\tbindings: Record<string, ResolvedBinding>\n\tengine: Engine\n\t/** Explicit TTL overrides; when a value is unset the adapter's recommendedTtl applies. */\n\tttl: { aggregate?: number; realtime?: number }\n\t/** Widget period-over-period comparison; false skips the previous-window read. */\n\tcomparison: boolean\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\nexport const resolveScopeFor = (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest\n): Promise<string | null> => runtime.resolveScope?.(req) ?? Promise.resolve(null)\n\nexport const resolveTimezoneFor = (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tscope?: string | null\n): Promise<string> => runtime.resolveTimezone?.(req, scope) ?? Promise.resolve(DEFAULT_TIMEZONE)\n\nexport const resolveRegistryFor = (\n\truntime: AnalyticsRuntime,\n\targs: ResolveRegistryArgs\n): Promise<AdapterRegistry> => runtime.resolveRegistry?.(args) ?? Promise.resolve(runtime.registry)\n\nexport const platformReadFor = async (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest\n): Promise<boolean> =>\n\truntime.platformRead ? await runtime.platformRead({ req }) : Boolean(req.user)\n"],"mappings":";;;;;;;;
|
|
1
|
+
{"version":3,"file":"runtime.js","names":[],"sources":["../../src/plugin/runtime.ts"],"sourcesContent":["import type { Payload, PayloadRequest } from 'payload'\nimport type { ResolvedBinding } from '../binding/types'\nimport type { CaptureSlotOption, ConsentPolicy, ResolvedAutoCapture } from '../core/options'\nimport type { AdapterRegistry, RegistryResolver, ResolveRegistryArgs } from '../core/registry'\nimport type { Goal } from '../goals/types'\nimport type { Engine } from '../surfacing/engine'\nimport { DEFAULT_TIMEZONE } from '../timeframe/tz'\n\nexport interface AnalyticsRuntime {\n\tregistry: AdapterRegistry\n\t/** Per-scope adapter resolution; absent runtimes fall back to the static registry. */\n\tresolveRegistry?: RegistryResolver\n\t/** The plugin's scopeResolver bound at init; absent runtimes resolve null. */\n\tresolveScope?: (req: PayloadRequest) => Promise<string | null>\n\t/** The plugin's reportingTimezone bound at init; absent runtimes resolve 'UTC'. */\n\tresolveTimezone?: (req: PayloadRequest, scope?: string | null) => Promise<string>\n\t/** Id of the config adapter shared by every scope, when one is designated. */\n\tplatformAdapterId?: string\n\t/** `capture.slots` overrides naming the adapter that fills each capture slot. */\n\tcaptureSlots?: { global?: CaptureSlotOption; tenant?: CaptureSlotOption }\n\t/**\n\t * `capture.paths` overrides for a slot's mount. Unset, the tracker config derives the\n\t * runtime proxy mount; set when the slot is served through Next rewrites instead.\n\t */\n\tcapturePaths?: { global?: string; tenant?: string }\n\t/**\n\t * Whether a slot's tracker waits for consent, evaluated per request-resolved adapter.\n\t * Absent runtimes fall back to the default: no gate for native, one for a vendor.\n\t */\n\tconsentFor?: ConsentPolicy\n\t/** Browser auto-capture toggles handed to the tracker; absent runtimes default all on. */\n\tautoCapture?: ResolvedAutoCapture\n\t/** Config goals; the tracker receives their slug and match only. */\n\tgoals?: Goal[]\n\t/**\n\t * Where the ingest endpoint listens, relative to `routes.api`, lifted at init from the\n\t * adapter that registered one. Absent runtimes fall back to the default mount.\n\t */\n\tingestPath?: string\n\t/**\n\t * `capture.proxy` limits for the runtime capture proxy. Deliberately separate from\n\t * `cache.timeoutMs`: that is a per-read provider deadline for authenticated dashboard\n\t * queries, this is a public request path with entirely different traffic.\n\t */\n\tcaptureProxy?: { timeoutMs: number; maxBodyBytes: number }\n\t/** True when the app configured a scopeResolver (scoped install); mirrors `resolved.scoped`. */\n\tscoped?: boolean\n\t/**\n\t * Ids of the config-time adapters shared by every scope (the ones passed to\n\t * `adapters` in plugin options). Runtime provider adapters (resolved per scope\n\t * from the providers collection or `providers.resolve`) are never in it.\n\t */\n\tconfigAdapterIds: ReadonlySet<string>\n\t/** Gate for cross-scope reads; absent runtimes require an authenticated user. */\n\tplatformRead?: (args: { req: PayloadRequest }) => boolean | Promise<boolean>\n\tbindings: Record<string, ResolvedBinding>\n\tengine: Engine\n\t/** Explicit TTL overrides; when a value is unset the adapter's recommendedTtl applies. */\n\tttl: { aggregate?: number; realtime?: number }\n\t/** Widget period-over-period comparison; false skips the previous-window read. */\n\tcomparison: boolean\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\nexport const resolveScopeFor = (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest\n): Promise<string | null> => runtime.resolveScope?.(req) ?? Promise.resolve(null)\n\nexport const resolveTimezoneFor = (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tscope?: string | null\n): Promise<string> => runtime.resolveTimezone?.(req, scope) ?? Promise.resolve(DEFAULT_TIMEZONE)\n\nexport const resolveRegistryFor = (\n\truntime: AnalyticsRuntime,\n\targs: ResolveRegistryArgs\n): Promise<AdapterRegistry> => runtime.resolveRegistry?.(args) ?? Promise.resolve(runtime.registry)\n\nexport const platformReadFor = async (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest\n): Promise<boolean> =>\n\truntime.platformRead ? await runtime.platformRead({ req }) : Boolean(req.user)\n"],"mappings":";;;;;;;;AAsEA,MAAM,cAAc,OAAO,IAAI,8BAA8B;AAI7D,MAAa,cAAc,SAAkB,YAAoC;CAC/E,QAAoC,eAAe;AACrD;AAEA,MAAa,cAAc,YACzB,QAAmC;AAErC,MAAa,mBACZ,SACA,QAC4B,QAAQ,eAAe,GAAG,KAAK,QAAQ,QAAQ,IAAI;AAEhF,MAAa,sBACZ,SACA,KACA,UACqB,QAAQ,kBAAkB,KAAK,KAAK,KAAK,QAAQ,QAAA,KAAwB;AAE/F,MAAa,sBACZ,SACA,SAC8B,QAAQ,kBAAkB,IAAI,KAAK,QAAQ,QAAQ,QAAQ,QAAQ;AAElG,MAAa,kBAAkB,OAC9B,SACA,QAEA,QAAQ,eAAe,MAAM,QAAQ,aAAa,EAAE,IAAI,CAAC,IAAI,QAAQ,IAAI,IAAI"}
|
|
@@ -1,13 +1,17 @@
|
|
|
1
|
-
import { serializeCapabilities } from "../core/capabilities.js";
|
|
2
|
-
import { getRuntime, resolveRegistryFor, resolveScopeFor } from "./runtime.js";
|
|
3
1
|
import "./paths.js";
|
|
2
|
+
import { getRuntime, platformReadFor, resolveRegistryFor, resolveScopeFor } from "./runtime.js";
|
|
3
|
+
import { serializeCapabilities } from "../core/capabilities.js";
|
|
4
4
|
//#region src/plugin/sourcesEndpoint.ts
|
|
5
5
|
/**
|
|
6
6
|
* Authenticated GET listing the adapters visible to the requesting scope, with
|
|
7
7
|
* serialized capabilities for client-side pickers. Always answers for the
|
|
8
8
|
* caller's own resolved scope; there is deliberately no scope parameter, so a
|
|
9
|
-
* tenant can never enumerate another tenant's sources.
|
|
10
|
-
*
|
|
9
|
+
* tenant can never enumerate another tenant's sources. On a scoped install, a
|
|
10
|
+
* request that resolves no scope at all is ambiguous, not install-wide, so it
|
|
11
|
+
* answers empty rather than leaking the static config registry, unless
|
|
12
|
+
* `platformRead` grants it. On resolution failure, an unscoped install falls
|
|
13
|
+
* back to the static config registry; a scoped install answers empty, since a
|
|
14
|
+
* failed resolution is indistinguishable from a forged one.
|
|
11
15
|
*/
|
|
12
16
|
const makeSourcesHandler = () => async (req) => {
|
|
13
17
|
if (!req.user) return Response.json({ error: "unauthorized" }, { status: 401 });
|
|
@@ -18,6 +22,10 @@ const makeSourcesHandler = () => async (req) => {
|
|
|
18
22
|
});
|
|
19
23
|
try {
|
|
20
24
|
const scope = await resolveScopeFor(runtime, req);
|
|
25
|
+
if (runtime.scoped && scope === null && !await platformReadFor(runtime, req)) return Response.json({
|
|
26
|
+
defaultId: null,
|
|
27
|
+
sources: []
|
|
28
|
+
});
|
|
21
29
|
const registry = await resolveRegistryFor(runtime, {
|
|
22
30
|
payload: req.payload,
|
|
23
31
|
req,
|
|
@@ -35,6 +43,10 @@ const makeSourcesHandler = () => async (req) => {
|
|
|
35
43
|
});
|
|
36
44
|
} catch (err) {
|
|
37
45
|
req.payload.logger?.warn(`analytics: sources listing failed: ${String(err)}`);
|
|
46
|
+
if (runtime.scoped) return Response.json({
|
|
47
|
+
defaultId: null,
|
|
48
|
+
sources: []
|
|
49
|
+
});
|
|
38
50
|
const sources = runtime.registry.all().map((a) => ({
|
|
39
51
|
id: a.id,
|
|
40
52
|
label: a.label,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sourcesEndpoint.js","names":[],"sources":["../../src/plugin/sourcesEndpoint.ts"],"sourcesContent":["import type { PayloadHandler } from 'payload'\nimport { serializeCapabilities } from '../core/capabilities'\nimport { SOURCES_PATH } from './paths'\nimport { getRuntime, resolveRegistryFor, resolveScopeFor } from './runtime'\n\nexport { SOURCES_PATH }\n\n/**\n * Authenticated GET listing the adapters visible to the requesting scope, with\n * serialized capabilities for client-side pickers. Always answers for the\n * caller's own resolved scope; there is deliberately no scope parameter, so a\n * tenant can never enumerate another tenant's sources.
|
|
1
|
+
{"version":3,"file":"sourcesEndpoint.js","names":[],"sources":["../../src/plugin/sourcesEndpoint.ts"],"sourcesContent":["import type { PayloadHandler } from 'payload'\nimport { serializeCapabilities } from '../core/capabilities'\nimport { SOURCES_PATH } from './paths'\nimport { getRuntime, platformReadFor, resolveRegistryFor, resolveScopeFor } from './runtime'\n\nexport { SOURCES_PATH }\n\n/**\n * Authenticated GET listing the adapters visible to the requesting scope, with\n * serialized capabilities for client-side pickers. Always answers for the\n * caller's own resolved scope; there is deliberately no scope parameter, so a\n * tenant can never enumerate another tenant's sources. On a scoped install, a\n * request that resolves no scope at all is ambiguous, not install-wide, so it\n * answers empty rather than leaking the static config registry, unless\n * `platformRead` grants it. On resolution failure, an unscoped install falls\n * back to the static config registry; a scoped install answers empty, since a\n * failed resolution is indistinguishable from a forged one.\n */\nexport const makeSourcesHandler = (): PayloadHandler => async (req) => {\n\tif (!req.user) {\n\t\treturn Response.json({ error: 'unauthorized' }, { status: 401 })\n\t}\n\tconst runtime = getRuntime(req.payload)\n\tif (!runtime) {\n\t\treturn Response.json({ defaultId: null, sources: [] })\n\t}\n\ttry {\n\t\tconst scope = await resolveScopeFor(runtime, req)\n\t\tif (runtime.scoped && scope === null && !(await platformReadFor(runtime, req))) {\n\t\t\treturn Response.json({ defaultId: null, sources: [] })\n\t\t}\n\t\tconst registry = await resolveRegistryFor(runtime, { payload: req.payload, req, scope })\n\t\tconst sources = registry.all().map((a) => ({\n\t\t\tid: a.id,\n\t\t\tlabel: a.label,\n\t\t\tkind: runtime.configAdapterIds.has(a.id) ? ('config' as const) : ('runtime' as const),\n\t\t\tcapabilities: serializeCapabilities(a.capabilities),\n\t\t}))\n\t\treturn Response.json({ defaultId: registry.default().id, sources })\n\t} catch (err) {\n\t\treq.payload.logger?.warn(`analytics: sources listing failed: ${String(err)}`)\n\t\tif (runtime.scoped) {\n\t\t\treturn Response.json({ defaultId: null, sources: [] })\n\t\t}\n\t\tconst sources = runtime.registry.all().map((a) => ({\n\t\t\tid: a.id,\n\t\t\tlabel: a.label,\n\t\t\tkind: 'config' as const,\n\t\t\tcapabilities: serializeCapabilities(a.capabilities),\n\t\t}))\n\t\treturn Response.json({ defaultId: runtime.registry.default().id, sources })\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;AAkBA,MAAa,2BAA2C,OAAO,QAAQ;CACtE,IAAI,CAAC,IAAI,MACR,OAAO,SAAS,KAAK,EAAE,OAAO,eAAe,GAAG,EAAE,QAAQ,IAAI,CAAC;CAEhE,MAAM,UAAU,WAAW,IAAI,OAAO;CACtC,IAAI,CAAC,SACJ,OAAO,SAAS,KAAK;EAAE,WAAW;EAAM,SAAS,CAAC;CAAE,CAAC;CAEtD,IAAI;EACH,MAAM,QAAQ,MAAM,gBAAgB,SAAS,GAAG;EAChD,IAAI,QAAQ,UAAU,UAAU,QAAQ,CAAE,MAAM,gBAAgB,SAAS,GAAG,GAC3E,OAAO,SAAS,KAAK;GAAE,WAAW;GAAM,SAAS,CAAC;EAAE,CAAC;EAEtD,MAAM,WAAW,MAAM,mBAAmB,SAAS;GAAE,SAAS,IAAI;GAAS;GAAK;EAAM,CAAC;EACvF,MAAM,UAAU,SAAS,IAAI,EAAE,KAAK,OAAO;GAC1C,IAAI,EAAE;GACN,OAAO,EAAE;GACT,MAAM,QAAQ,iBAAiB,IAAI,EAAE,EAAE,IAAK,WAAsB;GAClE,cAAc,sBAAsB,EAAE,YAAY;EACnD,EAAE;EACF,OAAO,SAAS,KAAK;GAAE,WAAW,SAAS,QAAQ,EAAE;GAAI;EAAQ,CAAC;CACnE,SAAS,KAAK;EACb,IAAI,QAAQ,QAAQ,KAAK,sCAAsC,OAAO,GAAG,GAAG;EAC5E,IAAI,QAAQ,QACX,OAAO,SAAS,KAAK;GAAE,WAAW;GAAM,SAAS,CAAC;EAAE,CAAC;EAEtD,MAAM,UAAU,QAAQ,SAAS,IAAI,EAAE,KAAK,OAAO;GAClD,IAAI,EAAE;GACN,OAAO,EAAE;GACT,MAAM;GACN,cAAc,sBAAsB,EAAE,YAAY;EACnD,EAAE;EACF,OAAO,SAAS,KAAK;GAAE,WAAW,QAAQ,SAAS,QAAQ,EAAE;GAAI;EAAQ,CAAC;CAC3E;AACD"}
|
package/dist/plugin/warmTask.js
CHANGED
|
Binary file
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"warmTask.js","names":[],"sources":["../../src/plugin/warmTask.ts"],"sourcesContent":["import type { PayloadRequest, TaskConfig, WidgetInstance } from 'payload'\nimport type { DateRange, DimensionKey, MetricKey } from '../core/contract'\nimport { TIMEFRAME_PRESETS, type TimeframePreset } from '../timeframe/presets'\nimport { breakdownSpecBySlug } from '../widgets/breakdownTypes'\nimport { resolveCustomRange } from '../widgets/range'\nimport { readForWidget } from '../widgets/readForWidget'\nimport { readForWidgetBreakdown } from '../widgets/readForWidgetBreakdown'\nimport { readForWidgetSeries } from '../widgets/readForWidgetSeries'\nimport { WIDGET_METRICS, type WidgetRange } from '../widgets/types'\n\n/** Minimal shape of a dashboard widget instance the warm job reads. */\nexport interface WarmWidgetInstance {\n\twidgetSlug?: string\n\tdata?: Record<string, unknown>\n}\n\nexport type WarmTarget =\n\t| {\n\t\t\tkind: 'metric'\n\t\t\tmetric: MetricKey\n\t\t\ttimeframe: TimeframePreset\n\t\t\trange?: DateRange\n\t\t\tadapterId?: string\n\t }\n\t| {\n\t\t\tkind: 'series'\n\t\t\tmetric: MetricKey\n\t\t\ttimeframe: TimeframePreset\n\t\t\trange?: DateRange\n\t\t\tadapterId?: string\n\t }\n\t| {\n\t\t\tkind: 'breakdown'\n\t\t\tmetric: MetricKey\n\t\t\tdimension: DimensionKey\n\t\t\ttimeframe: TimeframePreset\n\t\t\tlimit: number\n\t\t\trange?: DateRange\n\t\t\tadapterId?: string\n\t }\n\nconst asString = (v: unknown): string | undefined => (typeof v === 'string' ? v : undefined)\n\nconst asMetric = (v: unknown): MetricKey =>\n\ttypeof v === 'string' && (WIDGET_METRICS as readonly string[]).includes(v)\n\t\t? (v as MetricKey)\n\t\t: 'pageviews'\n\nconst asTimeframe = (v: unknown): TimeframePreset | 'custom' => {\n\tif (v === 'custom') {\n\t\treturn 'custom'\n\t}\n\tif (typeof v === 'string' && (TIMEFRAME_PRESETS as readonly string[]).includes(v)) {\n\t\treturn v as TimeframePreset\n\t}\n\treturn 'last30days'\n}\n\nconst asLimit = (v: unknown): number => (typeof v === 'number' && v > 0 ? v : 5)\n\nconst asRange = (v: unknown): WidgetRange | undefined => {\n\tif (!v || typeof v !== 'object') {\n\t\treturn undefined\n\t}\n\tconst r = v as { from?: unknown; to?: unknown }\n\treturn { from: asString(r.from), to: asString(r.to) }\n}\n\nconst targetKey = (t: WarmTarget): string => {\n\tconst range = t.range ? `${t.range.start.toISOString()}:${t.range.end.toISOString()}` : ''\n\tconst dimension = t.kind === 'breakdown' ? t.dimension : ''\n\tconst limit = t.kind === 'breakdown' ? String(t.limit) : ''\n\treturn `${t.kind}:${t.metric}:${dimension}:${t.timeframe}:${limit}:${t.adapterId ?? ''}:${range}`\n}\n\n/**\n * Map a dashboard's widget layout to the set of reads that warm its cache. Built-in\n * metric, trend, and breakdown widgets become targets; the realtime widget is skipped\n * (its short-TTL key is kept warm by the live poller) and any other slug is a custom app\n * widget whose read shape the plugin does not know. A `custom` timeframe is kept only when\n * its range resolves (the read takes an explicit range; `timeframe` is then unused).\n * Identical targets are de-duplicated so a repeated widget warms its tuple once.\n */\nexport const deriveWarmTargets = (widgets: readonly WarmWidgetInstance[]): WarmTarget[] => {\n\tconst out: WarmTarget[] = []\n\tconst seen = new Set<string>()\n\tfor (const widget of widgets) {\n\t\tconst slug = widget.widgetSlug\n\t\tif (!slug || slug === 'analytics-realtime') {\n\t\t\tcontinue\n\t\t}\n\t\tconst data = widget.data ?? {}\n\t\tconst metric = asMetric(data.metric)\n\t\tconst adapterId = asString(data.dataSource)\n\t\tconst timeframeRaw = asTimeframe(data.timeframe)\n\t\tlet timeframe: TimeframePreset = 'last30days'\n\t\tlet range: DateRange | undefined\n\t\tif (timeframeRaw === 'custom') {\n\t\t\tconst resolved = resolveCustomRange('custom', asRange(data.range))\n\t\t\tif (!resolved) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\trange = resolved\n\t\t} else {\n\t\t\ttimeframe = timeframeRaw\n\t\t}\n\n\t\tlet target: WarmTarget | undefined\n\t\tif (slug === 'analytics-metric') {\n\t\t\ttarget = { kind: 'metric', metric, timeframe, range, adapterId }\n\t\t} else if (slug === 'analytics-trend') {\n\t\t\ttarget = { kind: 'series', metric, timeframe, range, adapterId }\n\t\t} else {\n\t\t\tconst spec = breakdownSpecBySlug(slug)\n\t\t\tif (spec) {\n\t\t\t\ttarget = {\n\t\t\t\t\tkind: 'breakdown',\n\t\t\t\t\tmetric,\n\t\t\t\t\tdimension: spec.dimension,\n\t\t\t\t\ttimeframe,\n\t\t\t\t\tlimit: asLimit(data.limit),\n\t\t\t\t\trange,\n\t\t\t\t\tadapterId,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (!target) {\n\t\t\tcontinue\n\t\t}\n\t\tconst key = targetKey(target)\n\t\tif (seen.has(key)) {\n\t\t\tcontinue\n\t\t}\n\t\tseen.add(key)\n\t\tout.push(target)\n\t}\n\treturn out\n}\n\nexport const WARM_TASK_SLUG = 'analytics-warm-cache'\n\n/** A dashboard `defaultLayout`: an array, or a function resolving one per request. */\nexport type WarmLayout =\n\t| ((args: { req: PayloadRequest }) => WidgetInstance[] | Promise<WidgetInstance[]>)\n\t| WidgetInstance[]\n\t| undefined\n\nconst resolveLayout = async (\n\tlayout: WarmLayout,\n\treq: PayloadRequest\n): Promise<WarmWidgetInstance[]> => {\n\ttry {\n\t\tconst list = typeof layout === 'function' ? await layout({ req }) : (layout ?? [])\n\t\treturn list.map((w) => ({ widgetSlug: w.widgetSlug, data: w.data }))\n\t} catch (err) {\n\t\treq.payload.logger.warn(\n\t\t\t`analytics warm-cache: could not resolve the dashboard layout: ${String(err)}`\n\t\t)\n\t\treturn []\n\t}\n}\n\n/** Run one target's read; returns true when the read served data (status `ok`). */\nconst runTarget = async (target: WarmTarget, req: PayloadRequest, now: Date): Promise<boolean> => {\n\tif (target.kind === 'metric') {\n\t\tconst result = await readForWidget({\n\t\t\treq,\n\t\t\tmetrics: [target.metric],\n\t\t\ttimeframe: target.timeframe,\n\t\t\tadapterId: target.adapterId,\n\t\t\tnow,\n\t\t\trange: target.range,\n\t\t})\n\t\treturn result.status === 'ok'\n\t}\n\tif (target.kind === 'series') {\n\t\tconst result = await readForWidgetSeries({\n\t\t\treq,\n\t\t\tmetric: target.metric,\n\t\t\ttimeframe: target.timeframe,\n\t\t\tadapterId: target.adapterId,\n\t\t\tnow,\n\t\t\trange: target.range,\n\t\t})\n\t\treturn result.status === 'ok'\n\t}\n\tconst result = await readForWidgetBreakdown({\n\t\treq,\n\t\tmetric: target.metric,\n\t\tdimension: target.dimension,\n\t\ttimeframe: target.timeframe,\n\t\tlimit: target.limit,\n\t\tadapterId: target.adapterId,\n\t\tnow,\n\t\trange: target.range,\n\t})\n\treturn result.status === 'ok'\n}\n\n/**\n * Opt-in Payload task that pre-runs the dashboard's widget reads through the surfacing\n * engine so `payload.kv` is warm before a user opens the dashboard. Targets are derived\n * from `layout` (the app's `defaultLayout`, captured at registration and resolved here);\n * each read is isolated so one failing provider does not abort the rest. Most valuable\n * for slow or rate-limited provider adapters; native reads are cheap and harmless to warm.\n */\nexport const warmTask = (\n\tcron: string,\n\tlayout: WarmLayout\n): TaskConfig<{ input: Record<string, never>; output: { warmed: number; failed: number } }> => ({\n\tslug: WARM_TASK_SLUG,\n\thandler: async ({ req }) => {\n\t\tconst targets = deriveWarmTargets(await resolveLayout(layout, req))\n\t\tconst now = new Date()\n\t\tlet warmed = 0\n\t\tlet failed = 0\n\t\tfor (const target of targets) {\n\t\t\ttry {\n\t\t\t\tif (await runTarget(target, req, now)) {\n\t\t\t\t\twarmed++\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tfailed++\n\t\t\t\treq.payload.logger.warn(\n\t\t\t\t\t`analytics warm-cache: ${target.kind} read for \"${target.metric}\" failed: ${String(err)}`\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t\treturn { output: { warmed, failed } }\n\t},\n\tschedule: [{ cron, queue: 'default' }],\n})\n"],"mappings":";;;;;;;;AAyCA,MAAM,YAAY,MAAoC,OAAO,MAAM,WAAW,IAAI,KAAA;AAElF,MAAM,YAAY,MACjB,OAAO,MAAM,YAAa,eAAqC,SAAS,CAAC,IACrE,IACD;AAEJ,MAAM,eAAe,MAA2C;CAC/D,IAAI,MAAM,UACT,OAAO;CAER,IAAI,OAAO,MAAM,YAAa,kBAAwC,SAAS,CAAC,GAC/E,OAAO;CAER,OAAO;AACR;AAEA,MAAM,WAAW,MAAwB,OAAO,MAAM,YAAY,IAAI,IAAI,IAAI;AAE9E,MAAM,WAAW,MAAwC;CACxD,IAAI,CAAC,KAAK,OAAO,MAAM,UACtB;CAED,MAAM,IAAI;CACV,OAAO;EAAE,MAAM,SAAS,EAAE,IAAI;EAAG,IAAI,SAAS,EAAE,EAAE;CAAE;AACrD;AAEA,MAAM,aAAa,MAA0B;CAC5C,MAAM,QAAQ,EAAE,QAAQ,GAAG,EAAE,MAAM,MAAM,YAAY,EAAE,GAAG,EAAE,MAAM,IAAI,YAAY,MAAM;CACxF,MAAM,YAAY,EAAE,SAAS,cAAc,EAAE,YAAY;CACzD,MAAM,QAA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rC;CACA,UAAU,CAAC;EAAE;EAAM,OAAO;CAAU,CAAC;AACtC"}
|
|
1
|
+
{"version":3,"file":"warmTask.js","names":[],"sources":["../../src/plugin/warmTask.ts"],"sourcesContent":["import type { PayloadRequest, TaskConfig, WidgetInstance } from 'payload'\nimport type { DateRange, DimensionKey, MetricKey } from '../core/contract'\nimport type { ScopesResolver } from '../core/options'\nimport { resolveScopeList } from '../core/scopeList'\nimport { TIMEFRAME_PRESETS, type TimeframePreset } from '../timeframe/presets'\nimport { breakdownSpecBySlug } from '../widgets/breakdownTypes'\nimport { resolveCustomRange } from '../widgets/range'\nimport { readForWidget, type WidgetReadStatus } from '../widgets/readForWidget'\nimport { readForWidgetBreakdown } from '../widgets/readForWidgetBreakdown'\nimport { readForWidgetSeries } from '../widgets/readForWidgetSeries'\nimport { WIDGET_METRICS, type WidgetRange } from '../widgets/types'\n\n/** Minimal shape of a dashboard widget instance the warm job reads. */\nexport interface WarmWidgetInstance {\n\twidgetSlug?: string\n\tdata?: Record<string, unknown>\n}\n\nexport type WarmTarget =\n\t| {\n\t\t\tkind: 'metric'\n\t\t\tmetric: MetricKey\n\t\t\ttimeframe: TimeframePreset\n\t\t\trange?: DateRange\n\t\t\tadapterId?: string\n\t }\n\t| {\n\t\t\tkind: 'series'\n\t\t\tmetric: MetricKey\n\t\t\ttimeframe: TimeframePreset\n\t\t\trange?: DateRange\n\t\t\tadapterId?: string\n\t }\n\t| {\n\t\t\tkind: 'breakdown'\n\t\t\tmetric: MetricKey\n\t\t\tdimension: DimensionKey\n\t\t\ttimeframe: TimeframePreset\n\t\t\tlimit: number\n\t\t\trange?: DateRange\n\t\t\tadapterId?: string\n\t }\n\nconst asString = (v: unknown): string | undefined => (typeof v === 'string' ? v : undefined)\n\nconst asMetric = (v: unknown): MetricKey =>\n\ttypeof v === 'string' && (WIDGET_METRICS as readonly string[]).includes(v)\n\t\t? (v as MetricKey)\n\t\t: 'pageviews'\n\nconst asTimeframe = (v: unknown): TimeframePreset | 'custom' => {\n\tif (v === 'custom') {\n\t\treturn 'custom'\n\t}\n\tif (typeof v === 'string' && (TIMEFRAME_PRESETS as readonly string[]).includes(v)) {\n\t\treturn v as TimeframePreset\n\t}\n\treturn 'last30days'\n}\n\nconst asLimit = (v: unknown): number => (typeof v === 'number' && v > 0 ? v : 5)\n\nconst asRange = (v: unknown): WidgetRange | undefined => {\n\tif (!v || typeof v !== 'object') {\n\t\treturn undefined\n\t}\n\tconst r = v as { from?: unknown; to?: unknown }\n\treturn { from: asString(r.from), to: asString(r.to) }\n}\n\nconst targetKey = (t: WarmTarget): string => {\n\tconst range = t.range ? `${t.range.start.toISOString()}:${t.range.end.toISOString()}` : ''\n\tconst dimension = t.kind === 'breakdown' ? t.dimension : ''\n\tconst limit = t.kind === 'breakdown' ? String(t.limit) : ''\n\treturn `${t.kind}:${t.metric}:${dimension}:${t.timeframe}:${limit}:${t.adapterId ?? ''}:${range}`\n}\n\n/**\n * Map a dashboard's widget layout to the set of reads that warm its cache. Built-in\n * metric, trend, and breakdown widgets become targets; the realtime widget is skipped\n * (its short-TTL key is kept warm by the live poller) and any other slug is a custom app\n * widget whose read shape the plugin does not know. A `custom` timeframe is kept only when\n * its range resolves (the read takes an explicit range; `timeframe` is then unused).\n * Identical targets are de-duplicated so a repeated widget warms its tuple once.\n */\nexport const deriveWarmTargets = (widgets: readonly WarmWidgetInstance[]): WarmTarget[] => {\n\tconst out: WarmTarget[] = []\n\tconst seen = new Set<string>()\n\tfor (const widget of widgets) {\n\t\tconst slug = widget.widgetSlug\n\t\tif (!slug || slug === 'analytics-realtime') {\n\t\t\tcontinue\n\t\t}\n\t\tconst data = widget.data ?? {}\n\t\tconst metric = asMetric(data.metric)\n\t\tconst adapterId = asString(data.dataSource)\n\t\tconst timeframeRaw = asTimeframe(data.timeframe)\n\t\tlet timeframe: TimeframePreset = 'last30days'\n\t\tlet range: DateRange | undefined\n\t\tif (timeframeRaw === 'custom') {\n\t\t\tconst resolved = resolveCustomRange('custom', asRange(data.range))\n\t\t\tif (!resolved) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\trange = resolved\n\t\t} else {\n\t\t\ttimeframe = timeframeRaw\n\t\t}\n\n\t\tlet target: WarmTarget | undefined\n\t\tif (slug === 'analytics-metric') {\n\t\t\ttarget = { kind: 'metric', metric, timeframe, range, adapterId }\n\t\t} else if (slug === 'analytics-trend') {\n\t\t\ttarget = { kind: 'series', metric, timeframe, range, adapterId }\n\t\t} else {\n\t\t\tconst spec = breakdownSpecBySlug(slug)\n\t\t\tif (spec) {\n\t\t\t\ttarget = {\n\t\t\t\t\tkind: 'breakdown',\n\t\t\t\t\tmetric,\n\t\t\t\t\tdimension: spec.dimension,\n\t\t\t\t\ttimeframe,\n\t\t\t\t\tlimit: asLimit(data.limit),\n\t\t\t\t\trange,\n\t\t\t\t\tadapterId,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (!target) {\n\t\t\tcontinue\n\t\t}\n\t\tconst key = targetKey(target)\n\t\tif (seen.has(key)) {\n\t\t\tcontinue\n\t\t}\n\t\tseen.add(key)\n\t\tout.push(target)\n\t}\n\treturn out\n}\n\nexport const WARM_TASK_SLUG = 'analytics-warm-cache'\n\n/** A dashboard `defaultLayout`: an array, or a function resolving one per request. */\nexport type WarmLayout =\n\t| ((args: { req: PayloadRequest }) => WidgetInstance[] | Promise<WidgetInstance[]>)\n\t| WidgetInstance[]\n\t| undefined\n\nconst resolveLayout = async (\n\tlayout: WarmLayout,\n\treq: PayloadRequest\n): Promise<WarmWidgetInstance[]> => {\n\ttry {\n\t\tconst list = typeof layout === 'function' ? await layout({ req }) : (layout ?? [])\n\t\treturn list.map((w) => ({ widgetSlug: w.widgetSlug, data: w.data }))\n\t} catch (err) {\n\t\treq.payload.logger.warn(\n\t\t\t`analytics warm-cache: could not resolve the dashboard layout: ${String(err)}`\n\t\t)\n\t\treturn []\n\t}\n}\n\ninterface TargetRunResult {\n\tstatus: WidgetReadStatus\n\tadapterId: string\n}\n\n/** Run one target's read for one scope; the caller decides how to count/log the status. */\nconst runTarget = async (args: {\n\ttarget: WarmTarget\n\treq: PayloadRequest\n\tnow: Date\n\tscope: string | null\n}): Promise<TargetRunResult> => {\n\tconst { target, req, now, scope } = args\n\tif (target.kind === 'metric') {\n\t\tconst result = await readForWidget({\n\t\t\treq,\n\t\t\tmetrics: [target.metric],\n\t\t\ttimeframe: target.timeframe,\n\t\t\tadapterId: target.adapterId,\n\t\t\tnow,\n\t\t\trange: target.range,\n\t\t\tscope,\n\t\t})\n\t\treturn { status: result.status, adapterId: result.adapterId }\n\t}\n\tif (target.kind === 'series') {\n\t\tconst result = await readForWidgetSeries({\n\t\t\treq,\n\t\t\tmetric: target.metric,\n\t\t\ttimeframe: target.timeframe,\n\t\t\tadapterId: target.adapterId,\n\t\t\tnow,\n\t\t\trange: target.range,\n\t\t\tscope,\n\t\t})\n\t\treturn { status: result.status, adapterId: result.adapterId }\n\t}\n\tconst result = await readForWidgetBreakdown({\n\t\treq,\n\t\tmetric: target.metric,\n\t\tdimension: target.dimension,\n\t\ttimeframe: target.timeframe,\n\t\tlimit: target.limit,\n\t\tadapterId: target.adapterId,\n\t\tnow,\n\t\trange: target.range,\n\t\tscope,\n\t})\n\treturn { status: result.status, adapterId: result.adapterId }\n}\n\n/**\n * Opt-in Payload task that pre-runs the dashboard's widget reads through the surfacing\n * engine so `payload.kv` is warm before a user opens the dashboard. Targets are derived\n * from `layout` (the app's `defaultLayout`, captured at registration and resolved here);\n * each read is isolated so one failing provider does not abort the rest. Most valuable\n * for slow or rate-limited provider adapters; native reads are cheap and harmless to warm.\n * With `scopes` configured, every target runs once per tenant scope (plus the install-wide\n * scope) so a multi-tenant install warms every tenant's dashboard, not just the null one.\n */\nexport const warmTask = (\n\tcron: string,\n\tlayout: WarmLayout,\n\tscopes?: ScopesResolver\n): TaskConfig<{ input: Record<string, never>; output: { warmed: number; failed: number } }> => ({\n\tslug: WARM_TASK_SLUG,\n\thandler: async ({ req }) => {\n\t\tconst targets = deriveWarmTargets(await resolveLayout(layout, req))\n\t\tif (targets.length === 0) {\n\t\t\treturn { output: { warmed: 0, failed: 0 } }\n\t\t}\n\t\tconst scopeList = await resolveScopeList(scopes, req.payload)\n\t\tconst now = new Date()\n\t\tlet warmed = 0\n\t\tlet failed = 0\n\t\t// A tenant-pass target that degrades (e.g. a shared config adapter gated for\n\t\t// that scope) is not a failure, but a silent one leaves `warmed` unexplainably\n\t\t// short of `scopes x targets`; warn once per (scope, adapter) so it is visible.\n\t\tconst warnedGated = new Set<string>()\n\t\tfor (const scope of scopeList) {\n\t\t\tfor (const target of targets) {\n\t\t\t\ttry {\n\t\t\t\t\tconst result = await runTarget({ target, req, now, scope })\n\t\t\t\t\tif (result.status === 'ok') {\n\t\t\t\t\t\twarmed++\n\t\t\t\t\t} else if (scope !== null) {\n\t\t\t\t\t\tconst key = `${scope}\u0000${result.adapterId}`\n\t\t\t\t\t\tif (!warnedGated.has(key)) {\n\t\t\t\t\t\t\twarnedGated.add(key)\n\t\t\t\t\t\t\treq.payload.logger.warn(\n\t\t\t\t\t\t\t\t`analytics warm-cache: scope \"${scope}\" adapter \"${result.adapterId}\" returned \"${result.status}\", skipping`\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tfailed++\n\t\t\t\t\treq.payload.logger.warn(\n\t\t\t\t\t\t`analytics warm-cache: ${target.kind} read for \"${target.metric}\" (scope \"${scope ?? ''}\") failed: ${String(err)}`\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn { output: { warmed, failed } }\n\t},\n\tschedule: [{ cron, queue: 'default' }],\n})\n"],"mappings":";;;;;;;;;AA2CA,MAAM,YAAY,MAAoC,OAAO,MAAM,WAAW,IAAI,KAAA;AAElF,MAAM,YAAY,MACjB,OAAO,MAAM,YAAa,eAAqC,SAAS,CAAC,IACrE,IACD;AAEJ,MAAM,eAAe,MAA2C;CAC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