@10x-media/analytics 1.0.0-beta.7 → 1.0.0-beta.8
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 +48 -0
- package/README.md +8 -2
- package/dist/adapters/ga4/ga4.js +3 -2
- package/dist/adapters/ga4/ga4.js.map +1 -1
- package/dist/adapters/plausible/plausible.js +2 -1
- package/dist/adapters/plausible/plausible.js.map +1 -1
- package/dist/capture/slots.js +16 -5
- package/dist/capture/slots.js.map +1 -1
- package/dist/capture/trackerConfig.d.ts +1 -0
- package/dist/capture/trackerConfig.js +28 -3
- package/dist/capture/trackerConfig.js.map +1 -1
- package/dist/charts/BarList.d.ts +15 -1
- package/dist/charts/BarList.js +34 -18
- package/dist/charts/BarList.js.map +1 -1
- package/dist/charts/TrendChart.d.ts +16 -3
- package/dist/charts/TrendChart.js +172 -106
- package/dist/charts/TrendChart.js.map +1 -1
- package/dist/charts/bars.d.ts +2 -0
- package/dist/charts/bars.js +2 -1
- package/dist/charts/bars.js.map +1 -1
- package/dist/charts/bucket.js +10 -1
- package/dist/charts/bucket.js.map +1 -1
- package/dist/charts/spline.js +2 -2
- package/dist/charts/spline.js.map +1 -1
- package/dist/charts/styles.js +18 -1
- package/dist/charts/styles.js.map +1 -1
- package/dist/core/cacheKey.js +13 -1
- package/dist/core/cacheKey.js.map +1 -1
- package/dist/core/contract.d.ts +14 -7
- package/dist/core/contract.js +29 -1
- package/dist/core/contract.js.map +1 -1
- package/dist/core/granularity.js +1 -1
- package/dist/core/options.d.ts +54 -5
- package/dist/core/options.js +59 -2
- package/dist/core/options.js.map +1 -1
- package/dist/core/scopedRead.js +33 -23
- package/dist/core/scopedRead.js.map +1 -1
- package/dist/core/serverEvent.d.ts +42 -0
- package/dist/core/serverEvent.js +12 -0
- package/dist/core/serverEvent.js.map +1 -0
- package/dist/exports/client.d.ts +8 -2
- package/dist/exports/client.js +6 -1
- package/dist/exports/rsc.d.ts +5 -1
- package/dist/exports/rsc.js +6 -3
- package/dist/exports/types.d.ts +12 -4
- package/dist/exports/types.js +2 -2
- package/dist/fields/AnalyticsPanelClient.js +1 -1
- package/dist/fields/AnalyticsPanelField.js +1 -1
- package/dist/fields/AnalyticsStatField.js +2 -2
- package/dist/fields/config/MetricSelectField.js +2 -2
- package/dist/fields/config/MetricSelectField.js.map +1 -1
- package/dist/fields/config/SourceSelectField.js +2 -2
- package/dist/fields/config/SourceSelectField.js.map +1 -1
- package/dist/fields/config/fetchSources.d.ts +5 -1
- package/dist/fields/readForDocument.d.ts +5 -0
- package/dist/fields/readForDocument.js +5 -5
- package/dist/fields/readForDocument.js.map +1 -1
- package/dist/goals/GoalSelectField.d.ts +7 -0
- package/dist/goals/GoalSelectField.js +77 -0
- package/dist/goals/GoalSelectField.js.map +1 -0
- package/dist/goals/collection.js +250 -0
- package/dist/goals/collection.js.map +1 -0
- package/dist/goals/currency.js +14 -0
- package/dist/goals/currency.js.map +1 -0
- package/dist/goals/fetchGoals.d.ts +18 -0
- package/dist/goals/fetchGoals.js +29 -0
- package/dist/goals/fetchGoals.js.map +1 -0
- package/dist/goals/goalField.d.ts +31 -0
- package/dist/goals/goalField.js +56 -0
- package/dist/goals/goalField.js.map +1 -0
- package/dist/goals/goalsEndpoint.d.ts +1 -0
- package/dist/goals/goalsEndpoint.js +55 -0
- package/dist/goals/goalsEndpoint.js.map +1 -0
- package/dist/goals/resolver.d.ts +8 -0
- package/dist/goals/resolver.js +147 -0
- package/dist/goals/resolver.js.map +1 -0
- package/dist/goals/trackGoalAction.d.ts +74 -0
- package/dist/goals/trackGoalAction.js +139 -0
- package/dist/goals/trackGoalAction.js.map +1 -0
- package/dist/goals/useAnalyticsGoals.d.ts +20 -0
- package/dist/goals/useAnalyticsGoals.js +67 -0
- package/dist/goals/useAnalyticsGoals.js.map +1 -0
- package/dist/index.d.ts +10 -3
- package/dist/index.js +74 -11
- package/dist/index.js.map +1 -1
- package/dist/native/ingest/device.js +11 -3
- package/dist/native/ingest/device.js.map +1 -1
- package/dist/native/ingest/endpoint.d.ts +1 -0
- package/dist/native/ingest/endpoint.js +2 -17
- package/dist/native/ingest/endpoint.js.map +1 -1
- package/dist/native/ingest/normalizeEvent.d.ts +20 -0
- package/dist/native/ingest/normalizeEvent.js +3 -2
- package/dist/native/ingest/normalizeEvent.js.map +1 -1
- package/dist/native/ingest/serverTrack.d.ts +20 -0
- package/dist/native/ingest/serverTrack.js +99 -0
- package/dist/native/ingest/serverTrack.js.map +1 -0
- package/dist/native/ingest/validate.js +27 -0
- package/dist/native/ingest/validate.js.map +1 -0
- package/dist/native/nativeAdapter.d.ts +1 -1
- package/dist/native/nativeAdapter.js +21 -10
- package/dist/native/nativeAdapter.js.map +1 -1
- package/dist/native/retention/pruneTask.js +1 -1
- package/dist/native/rollups/insertIfNew.js +36 -2
- package/dist/native/rollups/insertIfNew.js.map +1 -1
- package/dist/plugin/documentEndpoint.js +27 -9
- package/dist/plugin/documentEndpoint.js.map +1 -1
- package/dist/plugin/paths.js +5 -1
- package/dist/plugin/paths.js.map +1 -1
- package/dist/plugin/queryEndpoint.js +113 -0
- package/dist/plugin/queryEndpoint.js.map +1 -0
- package/dist/plugin/readContextForRequest.js +71 -0
- package/dist/plugin/readContextForRequest.js.map +1 -0
- package/dist/plugin/realtimeEndpoint.js +6 -3
- package/dist/plugin/realtimeEndpoint.js.map +1 -1
- package/dist/plugin/runtime.js +31 -1
- package/dist/plugin/runtime.js.map +1 -1
- package/dist/plugin/scopeFieldBoot.js +22 -0
- package/dist/plugin/scopeFieldBoot.js.map +1 -0
- package/dist/plugin/sourcesEndpoint.js +13 -51
- 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 +15 -9
- package/dist/providers/collection.js.map +1 -1
- package/dist/providers/resolver.js.map +1 -1
- package/dist/query/dates.js +64 -0
- package/dist/query/dates.js.map +1 -0
- package/dist/query/errors.d.ts +17 -0
- package/dist/query/errors.js +10 -0
- package/dist/query/errors.js.map +1 -0
- package/dist/query/fetchQuery.d.ts +59 -0
- package/dist/query/fetchQuery.js +110 -0
- package/dist/query/fetchQuery.js.map +1 -0
- package/dist/query/parse.d.ts +22 -0
- package/dist/query/parse.js +168 -0
- package/dist/query/parse.js.map +1 -0
- package/dist/query/response.d.ts +36 -0
- package/dist/timeframe/tz.js +17 -6
- package/dist/timeframe/tz.js.map +1 -1
- package/dist/translations/ar.js +98 -1
- package/dist/translations/ar.js.map +1 -1
- package/dist/translations/de.js +98 -1
- package/dist/translations/de.js.map +1 -1
- package/dist/translations/en.js +98 -1
- package/dist/translations/en.js.map +1 -1
- package/dist/translations/es.js +98 -1
- package/dist/translations/es.js.map +1 -1
- package/dist/translations/fr.js +98 -1
- package/dist/translations/fr.js.map +1 -1
- package/dist/translations/id.js +98 -1
- package/dist/translations/id.js.map +1 -1
- package/dist/translations/keys.d.ts +97 -0
- package/dist/translations/keys.js +98 -1
- package/dist/translations/keys.js.map +1 -1
- package/dist/translations/ko.js +98 -1
- package/dist/translations/ko.js.map +1 -1
- package/dist/translations/metricKeys.js +1 -1
- package/dist/translations/metricKeys.js.map +1 -1
- package/dist/translations/pt.js +98 -1
- package/dist/translations/pt.js.map +1 -1
- package/dist/translations/ru.js +98 -1
- package/dist/translations/ru.js.map +1 -1
- package/dist/translations/uk.js +98 -1
- package/dist/translations/uk.js.map +1 -1
- package/dist/translations/zh.js +98 -1
- package/dist/translations/zh.js.map +1 -1
- package/dist/view/AnalyticsNavLink.d.ts +19 -0
- package/dist/view/AnalyticsNavLink.js +40 -0
- package/dist/view/AnalyticsNavLink.js.map +1 -0
- package/dist/view/AnalyticsView.d.ts +23 -0
- package/dist/view/AnalyticsView.js +45 -0
- package/dist/view/AnalyticsView.js.map +1 -0
- package/dist/view/AnalyticsViewClient.d.ts +15 -0
- package/dist/view/AnalyticsViewClient.js +189 -0
- package/dist/view/AnalyticsViewClient.js.map +1 -0
- package/dist/view/authRedirect.js +32 -0
- package/dist/view/authRedirect.js.map +1 -0
- package/dist/view/conversionRate.js +18 -0
- package/dist/view/conversionRate.js.map +1 -0
- package/dist/view/dayRange.js +68 -0
- package/dist/view/dayRange.js.map +1 -0
- package/dist/view/gating.d.ts +1 -0
- package/dist/view/gating.js +105 -0
- package/dist/view/gating.js.map +1 -0
- package/dist/view/labels.js +44 -0
- package/dist/view/labels.js.map +1 -0
- package/dist/view/registerView.js +48 -0
- package/dist/view/registerView.js.map +1 -0
- package/dist/view/sections/Breakdowns.js +157 -0
- package/dist/view/sections/Breakdowns.js.map +1 -0
- package/dist/view/sections/EmptyStates.js +92 -0
- package/dist/view/sections/EmptyStates.js.map +1 -0
- package/dist/view/sections/FilterChips.js +41 -0
- package/dist/view/sections/FilterChips.js.map +1 -0
- package/dist/view/sections/GoalsPanel.js +81 -0
- package/dist/view/sections/GoalsPanel.js.map +1 -0
- package/dist/view/sections/OverviewCards.js +65 -0
- package/dist/view/sections/OverviewCards.js.map +1 -0
- package/dist/view/sections/RealtimeStrip.js +77 -0
- package/dist/view/sections/RealtimeStrip.js.map +1 -0
- package/dist/view/sections/Toolbar.js +179 -0
- package/dist/view/sections/Toolbar.js.map +1 -0
- package/dist/view/sections/Trend.js +119 -0
- package/dist/view/sections/Trend.js.map +1 -0
- package/dist/view/sections/styles.js +74 -0
- package/dist/view/sections/styles.js.map +1 -0
- package/dist/view/state.js +206 -0
- package/dist/view/state.js.map +1 -0
- package/dist/view/useViewQueries.js +150 -0
- package/dist/view/useViewQueries.js.map +1 -0
- package/dist/view/viewProps.d.ts +40 -0
- package/dist/view/viewProps.js +90 -0
- package/dist/view/viewProps.js.map +1 -0
- package/dist/widgets/AnalyticsBreakdownWidget.d.ts +2 -1
- package/dist/widgets/AnalyticsBreakdownWidget.js +22 -4
- package/dist/widgets/AnalyticsBreakdownWidget.js.map +1 -1
- package/dist/widgets/AnalyticsGoalsWidget.d.ts +14 -0
- package/dist/widgets/AnalyticsGoalsWidget.js +188 -0
- package/dist/widgets/AnalyticsGoalsWidget.js.map +1 -0
- package/dist/widgets/AnalyticsMetricWidget.d.ts +2 -1
- package/dist/widgets/AnalyticsMetricWidget.js +35 -12
- package/dist/widgets/AnalyticsMetricWidget.js.map +1 -1
- package/dist/widgets/AnalyticsRealtimeWidget.d.ts +2 -1
- package/dist/widgets/AnalyticsRealtimeWidget.js +42 -22
- package/dist/widgets/AnalyticsRealtimeWidget.js.map +1 -1
- package/dist/widgets/AnalyticsTrendWidget.d.ts +2 -1
- package/dist/widgets/AnalyticsTrendWidget.js +51 -15
- package/dist/widgets/AnalyticsTrendWidget.js.map +1 -1
- package/dist/widgets/WidgetViewLink.js +17 -0
- package/dist/widgets/WidgetViewLink.js.map +1 -0
- package/dist/widgets/breakdownTypes.js +28 -1
- package/dist/widgets/breakdownTypes.js.map +1 -1
- package/dist/widgets/cardChrome.js +31 -7
- package/dist/widgets/cardChrome.js.map +1 -1
- package/dist/widgets/range.js +43 -12
- package/dist/widgets/range.js.map +1 -1
- package/dist/widgets/readForWidget.d.ts +12 -0
- package/dist/widgets/readForWidget.js +6 -5
- package/dist/widgets/readForWidget.js.map +1 -1
- package/dist/widgets/readForWidgetBreakdown.d.ts +15 -0
- package/dist/widgets/readForWidgetBreakdown.js +10 -7
- package/dist/widgets/readForWidgetBreakdown.js.map +1 -1
- package/dist/widgets/readForWidgetGoals.d.ts +57 -0
- package/dist/widgets/readForWidgetGoals.js +126 -0
- package/dist/widgets/readForWidgetGoals.js.map +1 -0
- package/dist/widgets/readForWidgetSeries.d.ts +13 -0
- package/dist/widgets/readForWidgetSeries.js +30 -12
- package/dist/widgets/readForWidgetSeries.js.map +1 -1
- package/dist/widgets/registerWidgets.js +49 -6
- package/dist/widgets/registerWidgets.js.map +1 -1
- package/dist/widgets/types.js +12 -1
- package/dist/widgets/types.js.map +1 -1
- package/dist/widgets/viewLink.d.ts +22 -0
- package/dist/widgets/viewLink.js +83 -0
- package/dist/widgets/viewLink.js.map +1 -0
- package/package.json +9 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"validate.js","names":[],"sources":["../../../src/native/ingest/validate.ts"],"sourcesContent":["import type { EventType, RawEventInput } from './normalizeEvent'\n\nconst TYPES: ReadonlySet<string> = new Set<EventType>(['pageview', 'event', 'goal'])\n\nconst nonEmptyString = (value: unknown): boolean => typeof value === 'string' && value.length > 0\n\nexport type RawEventField = 'type' | 'path' | 'hostname' | 'name'\n\n/**\n * The first required field an event fails on, or undefined when it is valid: a known `type`,\n * a `path`, a `hostname`, and a `name` (the event name, or the goal slug on a `goal`) for\n * everything but a pageview. Optional fields are sanitized in `normalizeEvent` and dropped\n * when malformed, so one bad attribute costs an attribute rather than the whole event.\n *\n * Types are checked rather than truthiness: a non-string path would otherwise reach goal\n * matching and throw there rather than being refused here.\n */\nexport const rawEventError = (raw: RawEventInput | undefined): RawEventField | undefined => {\n\tif (!raw || !TYPES.has(raw.type)) {\n\t\treturn 'type'\n\t}\n\tif (!nonEmptyString(raw.path)) {\n\t\treturn 'path'\n\t}\n\tif (!nonEmptyString(raw.hostname)) {\n\t\treturn 'hostname'\n\t}\n\tif (raw.type !== 'pageview' && !nonEmptyString(raw.name)) {\n\t\treturn 'name'\n\t}\n\treturn undefined\n}\n\nexport const validateRawEvent = (raw: RawEventInput | undefined): raw is RawEventInput =>\n\trawEventError(raw) === undefined\n"],"mappings":";AAEA,MAAM,QAA6B,IAAI,IAAe;CAAC;CAAY;CAAS;AAAM,CAAC;AAEnF,MAAM,kBAAkB,UAA4B,OAAO,UAAU,YAAY,MAAM,SAAS;;;;;;;;;;AAahG,MAAa,iBAAiB,QAA8D;CAC3F,IAAI,CAAC,OAAO,CAAC,MAAM,IAAI,IAAI,IAAI,GAC9B,OAAO;CAER,IAAI,CAAC,eAAe,IAAI,IAAI,GAC3B,OAAO;CAER,IAAI,CAAC,eAAe,IAAI,QAAQ,GAC/B,OAAO;CAER,IAAI,IAAI,SAAS,cAAc,CAAC,eAAe,IAAI,IAAI,GACtD,OAAO;AAGT;AAEA,MAAa,oBAAoB,QAChC,cAAc,GAAG,MAAM,KAAA"}
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import "../plugin/paths.js";
|
|
2
|
+
import { seenCollection } from "./collections/seen.js";
|
|
3
|
+
import { ROLLUPS_SLUG, rollupsCollection } from "./collections/rollups.js";
|
|
4
|
+
import { EVENTS_SLUG, eventsCollection } from "./collections/events.js";
|
|
5
|
+
import { flushBatch } from "./ingest/flushBatch.js";
|
|
6
|
+
import { makeServerTrack } from "./ingest/serverTrack.js";
|
|
2
7
|
import { composeGeoResolvers } from "./geo/composeGeoResolvers.js";
|
|
3
8
|
import { platformHeaderResolver } from "./geo/geoResolver.js";
|
|
4
9
|
import { maxmindResolver } from "./geo/maxmindResolver.js";
|
|
5
|
-
import { EVENTS_SLUG, eventsCollection } from "./collections/events.js";
|
|
6
|
-
import { ROLLUPS_SLUG, rollupsCollection } from "./collections/rollups.js";
|
|
7
|
-
import { seenCollection } from "./collections/seen.js";
|
|
8
|
-
import { flushBatch } from "./ingest/flushBatch.js";
|
|
9
10
|
import { makeIngestHandler } from "./ingest/endpoint.js";
|
|
10
11
|
import { createWriteBuffer } from "./ingest/writeBuffer.js";
|
|
11
12
|
import { aggregateEvents, filtersToWhere } from "./query/eventAgg.js";
|
|
@@ -139,7 +140,16 @@ function native(options = {}) {
|
|
|
139
140
|
});
|
|
140
141
|
return docs;
|
|
141
142
|
};
|
|
142
|
-
|
|
143
|
+
let resolvers = {};
|
|
144
|
+
const ingest = {
|
|
145
|
+
path: options.ingestPath ?? "/analytics/ingest",
|
|
146
|
+
track: makeServerTrack({
|
|
147
|
+
getPayload: () => payloadRef,
|
|
148
|
+
geoResolver,
|
|
149
|
+
getBuffer: () => buffer,
|
|
150
|
+
getResolvers: () => resolvers
|
|
151
|
+
})
|
|
152
|
+
};
|
|
143
153
|
return {
|
|
144
154
|
id: "native",
|
|
145
155
|
label: "Native (Payload)",
|
|
@@ -157,14 +167,15 @@ function native(options = {}) {
|
|
|
157
167
|
rollupsCollection(scoped),
|
|
158
168
|
seenCollection()
|
|
159
169
|
];
|
|
170
|
+
resolvers = {
|
|
171
|
+
scope: scoped ? context?.resolveScope : void 0,
|
|
172
|
+
timezone: context?.resolveTimezone,
|
|
173
|
+
goals: context?.resolveGoals
|
|
174
|
+
};
|
|
160
175
|
config.endpoints = [...config.endpoints ?? [], {
|
|
161
176
|
method: "post",
|
|
162
177
|
path: ingest.path,
|
|
163
|
-
handler: makeIngestHandler(geoResolver, () => buffer,
|
|
164
|
-
scope: scoped ? context?.resolveScope : void 0,
|
|
165
|
-
timezone: context?.resolveTimezone,
|
|
166
|
-
goals: context?.resolveGoals
|
|
167
|
-
})
|
|
178
|
+
handler: makeIngestHandler(geoResolver, () => buffer, resolvers)
|
|
168
179
|
}];
|
|
169
180
|
if (options.retentionDays && options.retentionDays > 0) config.jobs = {
|
|
170
181
|
...config.jobs,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nativeAdapter.js","names":["events"],"sources":["../../src/native/nativeAdapter.ts"],"sourcesContent":["import type { Config, Payload } from 'payload'\nimport type { CaptureSupport } from '../core/capture'\nimport type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tDimensionKey,\n\tMetricKey,\n} from '../core/contract'\nimport { INGEST_PATH } from '../plugin/paths'\nimport { EVENTS_SLUG, eventsCollection } from './collections/events'\nimport { ROLLUPS_SLUG, rollupsCollection } from './collections/rollups'\nimport { seenCollection } from './collections/seen'\nimport { composeGeoResolvers } from './geo/composeGeoResolvers'\nimport { type GeoResolver, platformHeaderResolver } from './geo/geoResolver'\nimport { maxmindResolver } from './geo/maxmindResolver'\nimport { makeIngestHandler } from './ingest/endpoint'\nimport { flushBatch } from './ingest/flushBatch'\nimport type { StoredEvent } from './ingest/normalizeEvent'\nimport { createWriteBuffer, type WriteBuffer } from './ingest/writeBuffer'\nimport { aggregateEvents, type EventLike, filtersToWhere } from './query/eventAgg'\nimport { buildRealtime, type RealtimeEvent } from './realtime/buildRealtime'\nimport { pruneEventsTask } from './retention/pruneTask'\nimport {\n\ttype Acc,\n\tadd,\n\temptyAcc,\n\ttype RollupDoc,\n\tselectMetrics,\n\tseriesFromRollups,\n} from './rollupAcc'\n\nexport interface NativeOptions {\n\tgeoResolver?: GeoResolver\n\tgeoDbPath?: string\n\tingestPath?: string\n\tretentionDays?: number\n\t/** Opt-in in-process write batching. `true` uses defaults (maxSize 50, maxAgeMs 2000). */\n\tbuffer?: boolean | { maxSize?: number; maxAgeMs?: number }\n}\n\nexport type NativeAdapter = AnalyticsAdapter & { flush: () => Promise<void> }\n\nconst metrics: ReadonlySet<MetricKey> = new Set([\n\t'pageviews',\n\t'visitors',\n\t'sessions',\n\t'events',\n\t'avgDuration',\n\t'conversions',\n\t'revenue',\n\t'scrollDepth',\n])\nconst dimensions: ReadonlySet<DimensionKey> = new Set([\n\t'page',\n\t'country',\n\t'source',\n\t'device',\n\t'event',\n\t'goal',\n])\n\nconst REALTIME_EVENT_LIMIT = 50_000\n\nconst baseCapabilities: AnalyticsCapabilities = {\n\tperPageQuery: true,\n\trealtime: true,\n\trealtimeWindowMinutes: 60,\n\tcomparison: true,\n\tminGranularity: 'hour',\n\tmaxLookbackDays: null,\n\tmetrics,\n\tdimensions,\n\tfilters: new Set(['page', 'country', 'region', 'city', 'device', 'source', 'event']),\n\tfilterOperators: new Set(['eq', 'contains']),\n\tbatchPageReport: true,\n\trateLimit: null,\n\trecommendedTtl: { realtime: 10, aggregate: 300 },\n}\n\nconst DAY_MS = 86_400_000\n\n// The tracker itself is the client (an RSC renders TrackerBoot), so there is nothing to\n// proxy or inject; the ingest path is carried by the tracker config resolver instead.\nconst nativeCapture: CaptureSupport = {\n\tproxy: { routes: [] },\n\tsnippet: () => ({ scripts: [] }),\n\tclient: { kind: 'native' },\n}\n\ninterface QueryEventsContext {\n\tretentionDays?: number\n\tscopeWhere: (q: AnalyticsQuery) => Record<string, unknown>\n}\n\n/**\n * Filtered/hour-granularity reads bypass the day-bucketed rollups and aggregate raw\n * events directly, under the same hard cap as `realtime()`. `retentionDays` clamps how\n * far back the read can reach when it would otherwise ask for events the prune task has\n * already deleted (or will delete before they're queryable).\n */\nasync function queryEvents(\n\tpayload: Payload,\n\tq: AnalyticsQuery,\n\tctx: QueryEventsContext\n): Promise<AnalyticsResult> {\n\tconst fetchedAt = q.dateRange.end.toISOString()\n\tlet start = q.dateRange.start\n\tlet clamped = false\n\tif (ctx.retentionDays && ctx.retentionDays > 0) {\n\t\tconst floor = new Date(Date.now() - ctx.retentionDays * DAY_MS)\n\t\tif (start < floor) {\n\t\t\tstart = floor\n\t\t\tclamped = true\n\t\t}\n\t}\n\tconst baseWhere: Record<string, unknown> = {\n\t\ttimestamp: {\n\t\t\tgreater_than_equal: start.toISOString(),\n\t\t\tless_than_equal: q.dateRange.end.toISOString(),\n\t\t},\n\t\t...(q.hostname ? { hostname: { equals: q.hostname } } : {}),\n\t\t...(q.path ? { path: { equals: q.path } } : {}),\n\t\t...ctx.scopeWhere(q),\n\t}\n\t// filtersToWhere can also key off 'path' (a page filter); AND rather than spread so\n\t// q.path and a page filter both constrain the query instead of one overwriting the other.\n\tconst filterWhere = filtersToWhere(q.filters ?? [])\n\tconst where: Record<string, unknown> =\n\t\tObject.keys(filterWhere).length > 0 ? { and: [baseWhere, filterWhere] } : baseWhere\n\tconst { docs } = await payload.find({\n\t\tcollection: EVENTS_SLUG as never,\n\t\twhere: where as never,\n\t\t// Newest-first under a hard cap, same tradeoff as realtime(): a very busy site\n\t\t// with more events than the cap in range keeps its most recent activity.\n\t\tlimit: REALTIME_EVENT_LIMIT,\n\t\tpagination: false,\n\t\tdepth: 0,\n\t\tsort: '-timestamp',\n\t})\n\tconst events = docs as unknown as EventLike[]\n\tconst dim = q.dimensions?.find((d) => dimensions.has(d))\n\tconst granularity =\n\t\tq.granularity === 'hour' || q.granularity === 'day' ? q.granularity : undefined\n\tconst { rows, totals } = aggregateEvents(events, {\n\t\tmetrics: q.metrics,\n\t\tdimension: dim,\n\t\tgranularity,\n\t\ttimezone: q.timezone,\n\t\torder: q.order,\n\t\tlimit: q.limit,\n\t})\n\tconst meta: AnalyticsResult['meta'] = { provider: 'native', fetchedAt }\n\tif (clamped) meta.clamped = true\n\tif (events.length >= REALTIME_EVENT_LIMIT) meta.sampled = true\n\treturn { rows, totals, meta }\n}\n\nexport function native(options: NativeOptions = {}): NativeAdapter {\n\tconst geoResolver =\n\t\toptions.geoResolver ??\n\t\t(options.geoDbPath\n\t\t\t? composeGeoResolvers(platformHeaderResolver, maxmindResolver({ dbPath: options.geoDbPath }))\n\t\t\t: platformHeaderResolver)\n\t// Per-instance copy: register() flips scopedQueries when the install is scoped.\n\tconst capabilities: AnalyticsCapabilities = { ...baseCapabilities }\n\tlet payloadRef: Payload | null = null\n\tlet buffer: WriteBuffer<StoredEvent> | null = null\n\tlet scoped = false\n\n\tconst scopeWhere = (q: AnalyticsQuery): Record<string, unknown> =>\n\t\tscoped && q.scope !== undefined ? { scope: { equals: q.scope } } : {}\n\n\tconst readRollups = async (\n\t\tpayload: Payload,\n\t\twhere: Record<string, unknown>\n\t): Promise<RollupDoc[]> => {\n\t\tconst { docs } = await payload.find({\n\t\t\tcollection: ROLLUPS_SLUG as never,\n\t\t\twhere: where as never,\n\t\t\tlimit: 100_000,\n\t\t\tpagination: false,\n\t\t})\n\t\treturn docs as unknown as RollupDoc[]\n\t}\n\n\tconst ingest = { path: options.ingestPath ?? INGEST_PATH }\n\n\treturn {\n\t\tid: 'native',\n\t\tlabel: 'Native (Payload)',\n\t\tcapabilities,\n\t\tcapture: nativeCapture,\n\t\tingest,\n\t\tisConfigured: () => true,\n\t\tflush: () => buffer?.flush() ?? Promise.resolve(),\n\t\tregister(config: Config, context) {\n\t\t\tscoped = context?.scoped ?? false\n\t\t\tif (scoped) {\n\t\t\t\tcapabilities.scopedQueries = true\n\t\t\t}\n\t\t\tconfig.collections = [\n\t\t\t\t...(config.collections ?? []),\n\t\t\t\teventsCollection(scoped),\n\t\t\t\trollupsCollection(scoped),\n\t\t\t\tseenCollection(),\n\t\t\t]\n\t\t\tconfig.endpoints = [\n\t\t\t\t...(config.endpoints ?? []),\n\t\t\t\t{\n\t\t\t\t\tmethod: 'post',\n\t\t\t\t\tpath: ingest.path,\n\t\t\t\t\thandler: makeIngestHandler(geoResolver, () => buffer, {\n\t\t\t\t\t\tscope: scoped ? context?.resolveScope : undefined,\n\t\t\t\t\t\ttimezone: context?.resolveTimezone,\n\t\t\t\t\t\tgoals: context?.resolveGoals,\n\t\t\t\t\t}),\n\t\t\t\t},\n\t\t\t]\n\t\t\tif (options.retentionDays && options.retentionDays > 0) {\n\t\t\t\tconfig.jobs = {\n\t\t\t\t\t...config.jobs,\n\t\t\t\t\ttasks: [...(config.jobs?.tasks ?? []), pruneEventsTask(options.retentionDays)],\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst prevOnInit = config.onInit\n\t\t\t// payloadRef is set before the app's own onInit so consumer init code can\n\t\t\t// already query the native adapter.\n\t\t\tconfig.onInit = async (p) => {\n\t\t\t\tpayloadRef = p\n\t\t\t\tif (options.buffer) {\n\t\t\t\t\tconst cfg = options.buffer === true ? {} : options.buffer\n\t\t\t\t\tbuffer = createWriteBuffer<StoredEvent>({\n\t\t\t\t\t\tmaxSize: cfg.maxSize ?? 50,\n\t\t\t\t\t\tmaxAgeMs: cfg.maxAgeMs ?? 2000,\n\t\t\t\t\t\tonFlush: (batch) => flushBatch(p, batch),\n\t\t\t\t\t\tonError: (error) => {\n\t\t\t\t\t\t\tp.logger.error({ err: error, msg: 'analytics: write buffer flush failed' })\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tawait prevOnInit?.(p)\n\t\t\t}\n\t\t},\n\t\tasync query(q: AnalyticsQuery): Promise<AnalyticsResult> {\n\t\t\tif (!payloadRef) {\n\t\t\t\tthrow new Error('analytics: native adapter queried before init')\n\t\t\t}\n\t\t\tif ((q.filters && q.filters.length > 0) || q.granularity === 'hour') {\n\t\t\t\treturn queryEvents(payloadRef, q, { retentionDays: options.retentionDays, scopeWhere })\n\t\t\t}\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst periodWhere = {\n\t\t\t\tgreater_than_equal: q.dateRange.start.toISOString(),\n\t\t\t\tless_than_equal: q.dateRange.end.toISOString(),\n\t\t\t}\n\t\t\tconst dim = q.dimensions?.find((d) => dimensions.has(d))\n\n\t\t\t// Distinct metrics (visitors/sessions) must not be summed across breakdown rows.\n\t\t\t// Totals always come from the non-dimensioned aggregate row. A dimensioned query\n\t\t\t// reports site-wide totals (path=''), a plain query uses the path-scoped row.\n\t\t\tconst totalsPath = dim ? '' : (q.path ?? '')\n\t\t\tconst totalsDocs = await readRollups(payloadRef, {\n\t\t\t\tgranularity: { equals: 'day' },\n\t\t\t\tdimension: { equals: '' },\n\t\t\t\tpath: { equals: totalsPath },\n\t\t\t\thostname: { equals: q.hostname ?? '' },\n\t\t\t\tperiod: periodWhere,\n\t\t\t\t...scopeWhere(q),\n\t\t\t})\n\t\t\tconst totalsAcc = emptyAcc()\n\t\t\tfor (const d of totalsDocs) {\n\t\t\t\tadd(totalsAcc, d)\n\t\t\t}\n\t\t\tconst totals = selectMetrics(totalsAcc, q.metrics)\n\n\t\t\tif (!dim) {\n\t\t\t\tif (q.granularity === 'day') {\n\t\t\t\t\treturn {\n\t\t\t\t\t\trows: seriesFromRollups(totalsDocs, q.metrics, q.timezone),\n\t\t\t\t\t\ttotals,\n\t\t\t\t\t\tmeta: { provider: 'native', fetchedAt },\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { rows: [{ metrics: totals }], totals, meta: { provider: 'native', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst breakdownWhere =\n\t\t\t\tdim === 'page'\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tgranularity: { equals: 'day' },\n\t\t\t\t\t\t\tdimension: { equals: '' },\n\t\t\t\t\t\t\tpath: { not_equals: '' },\n\t\t\t\t\t\t\thostname: { equals: q.hostname ?? '' },\n\t\t\t\t\t\t\tperiod: periodWhere,\n\t\t\t\t\t\t\t...scopeWhere(q),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {\n\t\t\t\t\t\t\tgranularity: { equals: 'day' },\n\t\t\t\t\t\t\tdimension: { equals: dim },\n\t\t\t\t\t\t\tpath: { equals: '' },\n\t\t\t\t\t\t\thostname: { equals: q.hostname ?? '' },\n\t\t\t\t\t\t\tperiod: periodWhere,\n\t\t\t\t\t\t\t...scopeWhere(q),\n\t\t\t\t\t\t}\n\t\t\tconst groups = new Map<string, Acc>()\n\t\t\tfor (const d of await readRollups(payloadRef, breakdownWhere)) {\n\t\t\t\tconst value = dim === 'page' ? d.path : d.dimvalue\n\t\t\t\tlet acc = groups.get(value)\n\t\t\t\tif (!acc) {\n\t\t\t\t\tacc = emptyAcc()\n\t\t\t\t\tgroups.set(value, acc)\n\t\t\t\t}\n\t\t\t\tadd(acc, d)\n\t\t\t}\n\t\t\tlet rows: AnalyticsRow[] = [...groups].map(([value, acc]) => ({\n\t\t\t\tdimensions: { [dim]: value } as Partial<Record<DimensionKey, string>>,\n\t\t\t\tmetrics: selectMetrics(acc, q.metrics),\n\t\t\t}))\n\t\t\tconst sortMetric = q.order?.metric ?? 'pageviews'\n\t\t\tconst direction = (q.order?.direction ?? 'desc') === 'asc' ? 1 : -1\n\t\t\trows.sort((a, b) => ((a.metrics[sortMetric] ?? 0) - (b.metrics[sortMetric] ?? 0)) * direction)\n\t\t\tif (q.limit) {\n\t\t\t\trows = rows.slice(0, q.limit)\n\t\t\t}\n\t\t\treturn { rows, totals, meta: { provider: 'native', fetchedAt } }\n\t\t},\n\t\tasync realtime(q: AnalyticsQuery, _ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tif (!payloadRef) {\n\t\t\t\tthrow new Error('analytics: native adapter queried before init')\n\t\t\t}\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst { docs } = await payloadRef.find({\n\t\t\t\tcollection: EVENTS_SLUG as never,\n\t\t\t\twhere: {\n\t\t\t\t\ttimestamp: {\n\t\t\t\t\t\tgreater_than_equal: q.dateRange.start.toISOString(),\n\t\t\t\t\t\tless_than_equal: q.dateRange.end.toISOString(),\n\t\t\t\t\t},\n\t\t\t\t\t...(q.hostname ? { hostname: { equals: q.hostname } } : {}),\n\t\t\t\t\t...(q.path ? { path: { equals: q.path } } : {}),\n\t\t\t\t\t...scopeWhere(q),\n\t\t\t\t} as never,\n\t\t\t\t// Newest-first under a hard cap: if a very busy site has more events than the\n\t\t\t\t// cap in the window, keep the most recent activity rather than the oldest.\n\t\t\t\t// Unbounded accuracy via DB-side aggregation is deferred to the hardening spec.\n\t\t\t\tlimit: REALTIME_EVENT_LIMIT,\n\t\t\t\tpagination: false,\n\t\t\t\tdepth: 0,\n\t\t\t\tsort: '-timestamp',\n\t\t\t})\n\t\t\tconst events = docs as unknown as RealtimeEvent[]\n\t\t\tconst { rows, totals } = buildRealtime(events, q.dateRange, q.metrics)\n\t\t\treturn { rows, totals, meta: { provider: 'native', fetchedAt } }\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;AA8CA,MAAM,UAAkC,IAAI,IAAI;CAC/C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAAC;AACD,MAAM,aAAwC,IAAI,IAAI;CACrD;CACA;CACA;CACA;CACA;CACA;AACD,CAAC;AAED,MAAM,uBAAuB;AAE7B,MAAM,mBAA0C;CAC/C,cAAc;CACd,UAAU;CACV,uBAAuB;CACvB,YAAY;CACZ,gBAAgB;CAChB,iBAAiB;CACjB;CACA;CACA,SAAS,IAAI,IAAI;EAAC;EAAQ;EAAW;EAAU;EAAQ;EAAU;EAAU;CAAO,CAAC;CACnF,iBAAiB,IAAI,IAAI,CAAC,MAAM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apter.ts"],"sourcesContent":["import type { Config, Payload } from 'payload'\nimport type { CaptureSupport } from '../core/capture'\nimport type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tDimensionKey,\n\tMetricKey,\n} from '../core/contract'\nimport { INGEST_PATH } from '../plugin/paths'\nimport { EVENTS_SLUG, eventsCollection } from './collections/events'\nimport { ROLLUPS_SLUG, rollupsCollection } from './collections/rollups'\nimport { seenCollection } from './collections/seen'\nimport { composeGeoResolvers } from './geo/composeGeoResolvers'\nimport { type GeoResolver, platformHeaderResolver } from './geo/geoResolver'\nimport { maxmindResolver } from './geo/maxmindResolver'\nimport { type IngestResolvers, makeIngestHandler } from './ingest/endpoint'\nimport { flushBatch } from './ingest/flushBatch'\nimport type { StoredEvent } from './ingest/normalizeEvent'\nimport { makeServerTrack } from './ingest/serverTrack'\nimport { createWriteBuffer, type WriteBuffer } from './ingest/writeBuffer'\nimport { aggregateEvents, type EventLike, filtersToWhere } from './query/eventAgg'\nimport { buildRealtime, type RealtimeEvent } from './realtime/buildRealtime'\nimport { pruneEventsTask } from './retention/pruneTask'\nimport {\n\ttype Acc,\n\tadd,\n\temptyAcc,\n\ttype RollupDoc,\n\tselectMetrics,\n\tseriesFromRollups,\n} from './rollupAcc'\n\nexport interface NativeOptions {\n\tgeoResolver?: GeoResolver\n\tgeoDbPath?: string\n\tingestPath?: string\n\tretentionDays?: number\n\t/** Opt-in in-process write batching. `true` uses defaults (maxSize 50, maxAgeMs 2000). */\n\tbuffer?: boolean | { maxSize?: number; maxAgeMs?: number }\n}\n\nexport type NativeAdapter = AnalyticsAdapter & { flush: () => Promise<void> }\n\nconst metrics: ReadonlySet<MetricKey> = new Set([\n\t'pageviews',\n\t'visitors',\n\t'sessions',\n\t'events',\n\t'avgDuration',\n\t'conversions',\n\t'revenue',\n\t'scrollDepth',\n])\nconst dimensions: ReadonlySet<DimensionKey> = new Set([\n\t'page',\n\t'country',\n\t'source',\n\t'device',\n\t'event',\n\t'goal',\n])\n\nconst REALTIME_EVENT_LIMIT = 50_000\n\nconst baseCapabilities: AnalyticsCapabilities = {\n\tperPageQuery: true,\n\trealtime: true,\n\trealtimeWindowMinutes: 60,\n\tcomparison: true,\n\tminGranularity: 'hour',\n\tmaxLookbackDays: null,\n\tmetrics,\n\tdimensions,\n\tfilters: new Set(['page', 'country', 'region', 'city', 'device', 'source', 'event']),\n\tfilterOperators: new Set(['eq', 'contains']),\n\tbatchPageReport: true,\n\trateLimit: null,\n\trecommendedTtl: { realtime: 10, aggregate: 300 },\n}\n\nconst DAY_MS = 86_400_000\n\n// The tracker itself is the client (an RSC renders TrackerBoot), so there is nothing to\n// proxy or inject; the ingest path is carried by the tracker config resolver instead.\nconst nativeCapture: CaptureSupport = {\n\tproxy: { routes: [] },\n\tsnippet: () => ({ scripts: [] }),\n\tclient: { kind: 'native' },\n}\n\ninterface QueryEventsContext {\n\tretentionDays?: number\n\tscopeWhere: (q: AnalyticsQuery) => Record<string, unknown>\n}\n\n/**\n * Filtered/hour-granularity reads bypass the day-bucketed rollups and aggregate raw\n * events directly, under the same hard cap as `realtime()`. `retentionDays` clamps how\n * far back the read can reach when it would otherwise ask for events the prune task has\n * already deleted (or will delete before they're queryable).\n */\nasync function queryEvents(\n\tpayload: Payload,\n\tq: AnalyticsQuery,\n\tctx: QueryEventsContext\n): Promise<AnalyticsResult> {\n\tconst fetchedAt = q.dateRange.end.toISOString()\n\tlet start = q.dateRange.start\n\tlet clamped = false\n\tif (ctx.retentionDays && ctx.retentionDays > 0) {\n\t\tconst floor = new Date(Date.now() - ctx.retentionDays * DAY_MS)\n\t\tif (start < floor) {\n\t\t\tstart = floor\n\t\t\tclamped = true\n\t\t}\n\t}\n\tconst baseWhere: Record<string, unknown> = {\n\t\ttimestamp: {\n\t\t\tgreater_than_equal: start.toISOString(),\n\t\t\tless_than_equal: q.dateRange.end.toISOString(),\n\t\t},\n\t\t...(q.hostname ? { hostname: { equals: q.hostname } } : {}),\n\t\t...(q.path ? { path: { equals: q.path } } : {}),\n\t\t...ctx.scopeWhere(q),\n\t}\n\t// filtersToWhere can also key off 'path' (a page filter); AND rather than spread so\n\t// q.path and a page filter both constrain the query instead of one overwriting the other.\n\tconst filterWhere = filtersToWhere(q.filters ?? [])\n\tconst where: Record<string, unknown> =\n\t\tObject.keys(filterWhere).length > 0 ? { and: [baseWhere, filterWhere] } : baseWhere\n\tconst { docs } = await payload.find({\n\t\tcollection: EVENTS_SLUG as never,\n\t\twhere: where as never,\n\t\t// Newest-first under a hard cap, same tradeoff as realtime(): a very busy site\n\t\t// with more events than the cap in range keeps its most recent activity.\n\t\tlimit: REALTIME_EVENT_LIMIT,\n\t\tpagination: false,\n\t\tdepth: 0,\n\t\tsort: '-timestamp',\n\t})\n\tconst events = docs as unknown as EventLike[]\n\tconst dim = q.dimensions?.find((d) => dimensions.has(d))\n\tconst granularity =\n\t\tq.granularity === 'hour' || q.granularity === 'day' ? q.granularity : undefined\n\tconst { rows, totals } = aggregateEvents(events, {\n\t\tmetrics: q.metrics,\n\t\tdimension: dim,\n\t\tgranularity,\n\t\ttimezone: q.timezone,\n\t\torder: q.order,\n\t\tlimit: q.limit,\n\t})\n\tconst meta: AnalyticsResult['meta'] = { provider: 'native', fetchedAt }\n\tif (clamped) meta.clamped = true\n\tif (events.length >= REALTIME_EVENT_LIMIT) meta.sampled = true\n\treturn { rows, totals, meta }\n}\n\nexport function native(options: NativeOptions = {}): NativeAdapter {\n\tconst geoResolver =\n\t\toptions.geoResolver ??\n\t\t(options.geoDbPath\n\t\t\t? composeGeoResolvers(platformHeaderResolver, maxmindResolver({ dbPath: options.geoDbPath }))\n\t\t\t: platformHeaderResolver)\n\t// Per-instance copy: register() flips scopedQueries when the install is scoped.\n\tconst capabilities: AnalyticsCapabilities = { ...baseCapabilities }\n\tlet payloadRef: Payload | null = null\n\tlet buffer: WriteBuffer<StoredEvent> | null = null\n\tlet scoped = false\n\n\tconst scopeWhere = (q: AnalyticsQuery): Record<string, unknown> =>\n\t\tscoped && q.scope !== undefined ? { scope: { equals: q.scope } } : {}\n\n\tconst readRollups = async (\n\t\tpayload: Payload,\n\t\twhere: Record<string, unknown>\n\t): Promise<RollupDoc[]> => {\n\t\tconst { docs } = await payload.find({\n\t\t\tcollection: ROLLUPS_SLUG as never,\n\t\t\twhere: where as never,\n\t\t\tlimit: 100_000,\n\t\t\tpagination: false,\n\t\t})\n\t\treturn docs as unknown as RollupDoc[]\n\t}\n\n\t// The plugin's resolvers arrive in register(); server tracking reads them late so it\n\t// resolves the same scope, timezone and goals the endpoint does.\n\tlet resolvers: IngestResolvers = {}\n\n\tconst ingest = {\n\t\tpath: options.ingestPath ?? INGEST_PATH,\n\t\ttrack: makeServerTrack({\n\t\t\tgetPayload: () => payloadRef,\n\t\t\tgeoResolver,\n\t\t\tgetBuffer: () => buffer,\n\t\t\tgetResolvers: () => resolvers,\n\t\t}),\n\t}\n\n\treturn {\n\t\tid: 'native',\n\t\tlabel: 'Native (Payload)',\n\t\tcapabilities,\n\t\tcapture: nativeCapture,\n\t\tingest,\n\t\tisConfigured: () => true,\n\t\tflush: () => buffer?.flush() ?? Promise.resolve(),\n\t\tregister(config: Config, context) {\n\t\t\tscoped = context?.scoped ?? false\n\t\t\tif (scoped) {\n\t\t\t\tcapabilities.scopedQueries = true\n\t\t\t}\n\t\t\tconfig.collections = [\n\t\t\t\t...(config.collections ?? []),\n\t\t\t\teventsCollection(scoped),\n\t\t\t\trollupsCollection(scoped),\n\t\t\t\tseenCollection(),\n\t\t\t]\n\t\t\tresolvers = {\n\t\t\t\tscope: scoped ? context?.resolveScope : undefined,\n\t\t\t\ttimezone: context?.resolveTimezone,\n\t\t\t\tgoals: context?.resolveGoals,\n\t\t\t}\n\t\t\tconfig.endpoints = [\n\t\t\t\t...(config.endpoints ?? []),\n\t\t\t\t{\n\t\t\t\t\tmethod: 'post',\n\t\t\t\t\tpath: ingest.path,\n\t\t\t\t\thandler: makeIngestHandler(geoResolver, () => buffer, resolvers),\n\t\t\t\t},\n\t\t\t]\n\t\t\tif (options.retentionDays && options.retentionDays > 0) {\n\t\t\t\tconfig.jobs = {\n\t\t\t\t\t...config.jobs,\n\t\t\t\t\ttasks: [...(config.jobs?.tasks ?? []), pruneEventsTask(options.retentionDays)],\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst prevOnInit = config.onInit\n\t\t\t// payloadRef is set before the app's own onInit so consumer init code can\n\t\t\t// already query the native adapter.\n\t\t\tconfig.onInit = async (p) => {\n\t\t\t\tpayloadRef = p\n\t\t\t\tif (options.buffer) {\n\t\t\t\t\tconst cfg = options.buffer === true ? {} : options.buffer\n\t\t\t\t\tbuffer = createWriteBuffer<StoredEvent>({\n\t\t\t\t\t\tmaxSize: cfg.maxSize ?? 50,\n\t\t\t\t\t\tmaxAgeMs: cfg.maxAgeMs ?? 2000,\n\t\t\t\t\t\tonFlush: (batch) => flushBatch(p, batch),\n\t\t\t\t\t\tonError: (error) => {\n\t\t\t\t\t\t\tp.logger.error({ err: error, msg: 'analytics: write buffer flush failed' })\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tawait prevOnInit?.(p)\n\t\t\t}\n\t\t},\n\t\tasync query(q: AnalyticsQuery): Promise<AnalyticsResult> {\n\t\t\tif (!payloadRef) {\n\t\t\t\tthrow new Error('analytics: native adapter queried before init')\n\t\t\t}\n\t\t\tif ((q.filters && q.filters.length > 0) || q.granularity === 'hour') {\n\t\t\t\treturn queryEvents(payloadRef, q, { retentionDays: options.retentionDays, scopeWhere })\n\t\t\t}\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst periodWhere = {\n\t\t\t\tgreater_than_equal: q.dateRange.start.toISOString(),\n\t\t\t\tless_than_equal: q.dateRange.end.toISOString(),\n\t\t\t}\n\t\t\tconst dim = q.dimensions?.find((d) => dimensions.has(d))\n\n\t\t\t// Distinct metrics (visitors/sessions) must not be summed across breakdown rows.\n\t\t\t// Totals always come from the non-dimensioned aggregate row. A dimensioned query\n\t\t\t// reports site-wide totals (path=''), a plain query uses the path-scoped row.\n\t\t\tconst totalsPath = dim ? '' : (q.path ?? '')\n\t\t\tconst totalsDocs = await readRollups(payloadRef, {\n\t\t\t\tgranularity: { equals: 'day' },\n\t\t\t\tdimension: { equals: '' },\n\t\t\t\tpath: { equals: totalsPath },\n\t\t\t\thostname: { equals: q.hostname ?? '' },\n\t\t\t\tperiod: periodWhere,\n\t\t\t\t...scopeWhere(q),\n\t\t\t})\n\t\t\tconst totalsAcc = emptyAcc()\n\t\t\tfor (const d of totalsDocs) {\n\t\t\t\tadd(totalsAcc, d)\n\t\t\t}\n\t\t\tconst totals = selectMetrics(totalsAcc, q.metrics)\n\n\t\t\tif (!dim) {\n\t\t\t\tif (q.granularity === 'day') {\n\t\t\t\t\treturn {\n\t\t\t\t\t\trows: seriesFromRollups(totalsDocs, q.metrics, q.timezone),\n\t\t\t\t\t\ttotals,\n\t\t\t\t\t\tmeta: { provider: 'native', fetchedAt },\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { rows: [{ metrics: totals }], totals, meta: { provider: 'native', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst breakdownWhere =\n\t\t\t\tdim === 'page'\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tgranularity: { equals: 'day' },\n\t\t\t\t\t\t\tdimension: { equals: '' },\n\t\t\t\t\t\t\tpath: { not_equals: '' },\n\t\t\t\t\t\t\thostname: { equals: q.hostname ?? '' },\n\t\t\t\t\t\t\tperiod: periodWhere,\n\t\t\t\t\t\t\t...scopeWhere(q),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {\n\t\t\t\t\t\t\tgranularity: { equals: 'day' },\n\t\t\t\t\t\t\tdimension: { equals: dim },\n\t\t\t\t\t\t\tpath: { equals: '' },\n\t\t\t\t\t\t\thostname: { equals: q.hostname ?? '' },\n\t\t\t\t\t\t\tperiod: periodWhere,\n\t\t\t\t\t\t\t...scopeWhere(q),\n\t\t\t\t\t\t}\n\t\t\tconst groups = new Map<string, Acc>()\n\t\t\tfor (const d of await readRollups(payloadRef, breakdownWhere)) {\n\t\t\t\tconst value = dim === 'page' ? d.path : d.dimvalue\n\t\t\t\tlet acc = groups.get(value)\n\t\t\t\tif (!acc) {\n\t\t\t\t\tacc = emptyAcc()\n\t\t\t\t\tgroups.set(value, acc)\n\t\t\t\t}\n\t\t\t\tadd(acc, d)\n\t\t\t}\n\t\t\tlet rows: AnalyticsRow[] = [...groups].map(([value, acc]) => ({\n\t\t\t\tdimensions: { [dim]: value } as Partial<Record<DimensionKey, string>>,\n\t\t\t\tmetrics: selectMetrics(acc, q.metrics),\n\t\t\t}))\n\t\t\tconst sortMetric = q.order?.metric ?? 'pageviews'\n\t\t\tconst direction = (q.order?.direction ?? 'desc') === 'asc' ? 1 : -1\n\t\t\trows.sort((a, b) => ((a.metrics[sortMetric] ?? 0) - (b.metrics[sortMetric] ?? 0)) * direction)\n\t\t\tif (q.limit) {\n\t\t\t\trows = rows.slice(0, q.limit)\n\t\t\t}\n\t\t\treturn { rows, totals, meta: { provider: 'native', fetchedAt } }\n\t\t},\n\t\tasync realtime(q: AnalyticsQuery, _ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tif (!payloadRef) {\n\t\t\t\tthrow new Error('analytics: native adapter queried before init')\n\t\t\t}\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst { docs } = await payloadRef.find({\n\t\t\t\tcollection: EVENTS_SLUG as never,\n\t\t\t\twhere: {\n\t\t\t\t\ttimestamp: {\n\t\t\t\t\t\tgreater_than_equal: q.dateRange.start.toISOString(),\n\t\t\t\t\t\tless_than_equal: q.dateRange.end.toISOString(),\n\t\t\t\t\t},\n\t\t\t\t\t...(q.hostname ? { hostname: { equals: q.hostname } } : {}),\n\t\t\t\t\t...(q.path ? { path: { equals: q.path } } : {}),\n\t\t\t\t\t...scopeWhere(q),\n\t\t\t\t} as never,\n\t\t\t\t// Newest-first under a hard cap: if a very busy site has more events than the\n\t\t\t\t// cap in the window, keep the most recent activity rather than the oldest.\n\t\t\t\t// Unbounded accuracy via DB-side aggregation is deferred to the hardening spec.\n\t\t\t\tlimit: REALTIME_EVENT_LIMIT,\n\t\t\t\tpagination: false,\n\t\t\t\tdepth: 0,\n\t\t\t\tsort: '-timestamp',\n\t\t\t})\n\t\t\tconst events = docs as unknown as RealtimeEvent[]\n\t\t\tconst { rows, totals } = buildRealtime(events, q.dateRange, q.metrics)\n\t\t\treturn { rows, totals, meta: { provider: 'native', fetchedAt } }\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA+CA,MAAM,UAAkC,IAAI,IAAI;CAC/C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAAC;AACD,MAAM,aAAwC,IAAI,IAAI;CACrD;CACA;CACA;CACA;CACA;CACA;AACD,CAAC;AAED,MAAM,uBAAuB;AAE7B,MAAM,mBAA0C;CAC/C,cAAc;CACd,UAAU;CACV,uBAAuB;CACvB,YAAY;CACZ,gBAAgB;CAChB,iBAAiB;CACjB;CACA;CACA,SAAS,IAAI,IAAI;EAAC;EAAQ;EAAW;EAAU;EAAQ;EAAU;EAAU;CAAO,CAAC;CACnF,iBAAiB,IAAI,IAAI,CAAC,MAAM,UAAU,CAAC;CAC3C,iBAAiB;CACjB,WAAW;CACX,gBAAgB;EAAE,UAAU;EAAI,WAAW;CAAI;AAChD;AAEA,MAAM,SAAS;AAIf,MAAM,gBAAgC;CACrC,OAAO,EAAE,QAAQ,CAAC,EAAE;CACpB,gBAAgB,EAAE,SAAS,CAAC,EAAE;CAC9B,QAAQ,EAAE,MAAM,SAAS;AAC1B;;;;;;;AAaA,eAAe,YACd,SACA,GACA,KAC2B;CAC3B,MAAM,YAAY,EAAE,UAAU,IAAI,YAAY;CAC9C,IAAI,QAAQ,EAAE,UAAU;CACxB,IAAI,UAAU;CACd,IAAI,IAAI,iBA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Q,EAAE,QAAQ,eAAe,MAAM,EAAE,QAAQ,eAAe,MAAM,SAAS;GAC7F,IAAI,EAAE,OACL,OAAO,KAAK,MAAM,GAAG,EAAE,KAAK;GAE7B,OAAO;IAAE;IAAM;IAAQ,MAAM;KAAE,UAAU;KAAU;IAAU;GAAE;EAChE;EACA,MAAM,SAAS,GAAmB,MAAgD;GACjF,IAAI,CAAC,YACJ,MAAM,IAAI,MAAM,+CAA+C;GAEhE,MAAM,YAAY,EAAE,UAAU,IAAI,YAAY;GAC9C,MAAM,EAAE,SAAS,MAAM,WAAW,KAAK;IACtC,YAAY;IACZ,OAAO;KACN,WAAW;MACV,oBAAoB,EAAE,UAAU,MAAM,YAAY;MAClD,iBAAiB,EAAE,UAAU,IAAI,YAAY;KAC9C;KACA,GAAI,EAAE,WAAW,EAAE,UAAU,EAAE,QAAQ,EAAE,SAAS,EAAE,IAAI,CAAC;KACzD,GAAI,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,KAAK,EAAE,IAAI,CAAC;KAC7C,GAAG,WAAW,CAAC;IAChB;IAIA,OAAO;IACP,YAAY;IACZ,OAAO;IACP,MAAM;GACP,CAAC;GAED,MAAM,EAAE,MAAM,WAAW,cAAcA,MAAQ,EAAE,WAAW,EAAE,OAAO;GACrE,OAAO;IAAE;IAAM;IAAQ,MAAM;KAAE,UAAU;KAAU;IAAU;GAAE;EAChE;CACD;AACD"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { EVENTS_SLUG } from "../collections/events.js";
|
|
2
1
|
import { SEEN_SLUG } from "../collections/seen.js";
|
|
2
|
+
import { EVENTS_SLUG } from "../collections/events.js";
|
|
3
3
|
//#region src/native/retention/pruneTask.ts
|
|
4
4
|
const PRUNE_TASK_SLUG = "analytics-prune-events";
|
|
5
5
|
const pruneEventsTask = (retentionDays) => ({
|
|
@@ -1,9 +1,38 @@
|
|
|
1
1
|
//#region src/native/rollups/insertIfNew.ts
|
|
2
|
+
/** Mongo duplicate key. */
|
|
3
|
+
const MONGO_DUPLICATE = 11e3;
|
|
4
|
+
/** Postgres unique_violation. */
|
|
5
|
+
const PG_UNIQUE_VIOLATION = "23505";
|
|
6
|
+
/**
|
|
7
|
+
* Drizzle wraps driver errors in a `DrizzleQueryError` and Mongoose can wrap a write error in
|
|
8
|
+
* turn, so the cause chain is walked rather than only the error handed to the catch.
|
|
9
|
+
*/
|
|
10
|
+
const isDuplicateKeyError = (err, code) => {
|
|
11
|
+
let current = err;
|
|
12
|
+
for (let depth = 0; depth < 4; depth++) {
|
|
13
|
+
if (typeof current !== "object" || current === null) return false;
|
|
14
|
+
if (current.code === code) return true;
|
|
15
|
+
current = current.cause;
|
|
16
|
+
}
|
|
17
|
+
return false;
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* Returns true iff the row was newly inserted (the key had not been seen). Single statement on
|
|
21
|
+
* both adapters, and the unique index on the key is what makes it concurrency-safe: two writers
|
|
22
|
+
* racing the same key means one of them loses, either quietly (no upsert, no insert) or with a
|
|
23
|
+
* duplicate-key error the driver raises after the index rejects its write. Both outcomes mean
|
|
24
|
+
* "already seen", so the error is caught here rather than escaping into the ingest response.
|
|
25
|
+
*/
|
|
2
26
|
async function insertIfNew(payload, slug, key) {
|
|
3
27
|
if (payload.db.name === "mongoose") {
|
|
4
28
|
const model = payload.db.collections[slug];
|
|
5
29
|
if (!model) throw new Error(`analytics: mongoose collection "${slug}" not found`);
|
|
6
|
-
|
|
30
|
+
try {
|
|
31
|
+
return (await model.collection.updateOne(key, { $setOnInsert: key }, { upsert: true })).upsertedCount === 1;
|
|
32
|
+
} catch (err) {
|
|
33
|
+
if (isDuplicateKeyError(err, MONGO_DUPLICATE)) return false;
|
|
34
|
+
throw err;
|
|
35
|
+
}
|
|
7
36
|
}
|
|
8
37
|
const db = payload.db;
|
|
9
38
|
const tableKey = slug.replace(/-/g, "_");
|
|
@@ -11,7 +40,12 @@ async function insertIfNew(payload, slug, key) {
|
|
|
11
40
|
if (!tableName) throw new Error(`analytics: drizzle table "${tableKey}" not found`);
|
|
12
41
|
const table = db.tables[tableName];
|
|
13
42
|
if (!table) throw new Error(`analytics: drizzle table object for "${tableName}" not found`);
|
|
14
|
-
|
|
43
|
+
try {
|
|
44
|
+
return (await db.drizzle.insert(table).values(key).onConflictDoNothing().returning()).length === 1;
|
|
45
|
+
} catch (err) {
|
|
46
|
+
if (isDuplicateKeyError(err, PG_UNIQUE_VIOLATION)) return false;
|
|
47
|
+
throw err;
|
|
48
|
+
}
|
|
15
49
|
}
|
|
16
50
|
//#endregion
|
|
17
51
|
export { insertIfNew };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"insertIfNew.js","names":[],"sources":["../../../src/native/rollups/insertIfNew.ts"],"sourcesContent":["import type { Payload } from 'payload'\n\n// payload.db raw-access shapes are intentionally loose; these narrow casts reach the\n// Mongoose driver collection / Drizzle instance directly (no public typed API).\ntype MongoDb = {\n\tname: 'mongoose'\n\tcollections: Record<\n\t\tstring,\n\t\t{\n\t\t\tcollection: {\n\t\t\t\tupdateOne: (f: object, u: object, o: object) => Promise<{ upsertedCount: number }>\n\t\t\t}\n\t\t}\n\t>\n}\ntype PgDb = {\n\tname: 'postgres'\n\tdrizzle: {\n\t\tinsert: (t: unknown) => {\n\t\t\tvalues: (v: unknown) => { onConflictDoNothing: () => { returning: () => Promise<unknown[]> } }\n\t\t}\n\t}\n\ttables: Record<string, Record<string, unknown>>\n\ttableNameMap: Map<string, string>\n}\n\n
|
|
1
|
+
{"version":3,"file":"insertIfNew.js","names":[],"sources":["../../../src/native/rollups/insertIfNew.ts"],"sourcesContent":["import type { Payload } from 'payload'\n\n// payload.db raw-access shapes are intentionally loose; these narrow casts reach the\n// Mongoose driver collection / Drizzle instance directly (no public typed API).\ntype MongoDb = {\n\tname: 'mongoose'\n\tcollections: Record<\n\t\tstring,\n\t\t{\n\t\t\tcollection: {\n\t\t\t\tupdateOne: (f: object, u: object, o: object) => Promise<{ upsertedCount: number }>\n\t\t\t}\n\t\t}\n\t>\n}\ntype PgDb = {\n\tname: 'postgres'\n\tdrizzle: {\n\t\tinsert: (t: unknown) => {\n\t\t\tvalues: (v: unknown) => { onConflictDoNothing: () => { returning: () => Promise<unknown[]> } }\n\t\t}\n\t}\n\ttables: Record<string, Record<string, unknown>>\n\ttableNameMap: Map<string, string>\n}\n\n/** Mongo duplicate key. */\nconst MONGO_DUPLICATE = 11000\n/** Postgres unique_violation. */\nconst PG_UNIQUE_VIOLATION = '23505'\n\n/**\n * Drizzle wraps driver errors in a `DrizzleQueryError` and Mongoose can wrap a write error in\n * turn, so the cause chain is walked rather than only the error handed to the catch.\n */\nconst isDuplicateKeyError = (err: unknown, code: number | string): boolean => {\n\tlet current: unknown = err\n\tfor (let depth = 0; depth < 4; depth++) {\n\t\tif (typeof current !== 'object' || current === null) {\n\t\t\treturn false\n\t\t}\n\t\tif ((current as { code?: unknown }).code === code) {\n\t\t\treturn true\n\t\t}\n\t\tcurrent = (current as { cause?: unknown }).cause\n\t}\n\treturn false\n}\n\n/**\n * Returns true iff the row was newly inserted (the key had not been seen). Single statement on\n * both adapters, and the unique index on the key is what makes it concurrency-safe: two writers\n * racing the same key means one of them loses, either quietly (no upsert, no insert) or with a\n * duplicate-key error the driver raises after the index rejects its write. Both outcomes mean\n * \"already seen\", so the error is caught here rather than escaping into the ingest response.\n */\nexport async function insertIfNew(\n\tpayload: Payload,\n\tslug: string,\n\tkey: Record<string, unknown>\n): Promise<boolean> {\n\tif (payload.db.name === 'mongoose') {\n\t\tconst db = payload.db as unknown as MongoDb\n\t\tconst model = db.collections[slug]\n\t\tif (!model) throw new Error(`analytics: mongoose collection \"${slug}\" not found`)\n\t\ttry {\n\t\t\tconst res = await model.collection.updateOne(key, { $setOnInsert: key }, { upsert: true })\n\t\t\treturn res.upsertedCount === 1\n\t\t} catch (err) {\n\t\t\tif (isDuplicateKeyError(err, MONGO_DUPLICATE)) return false\n\t\t\tthrow err\n\t\t}\n\t}\n\tconst db = payload.db as unknown as PgDb\n\tconst tableKey = slug.replace(/-/g, '_')\n\tconst tableName = db.tableNameMap.get(tableKey)\n\tif (!tableName) throw new Error(`analytics: drizzle table \"${tableKey}\" not found`)\n\tconst table = db.tables[tableName]\n\tif (!table) throw new Error(`analytics: drizzle table object for \"${tableName}\" not found`)\n\ttry {\n\t\tconst inserted = await db.drizzle.insert(table).values(key).onConflictDoNothing().returning()\n\t\treturn inserted.length === 1\n\t} catch (err) {\n\t\tif (isDuplicateKeyError(err, PG_UNIQUE_VIOLATION)) return false\n\t\tthrow err\n\t}\n}\n"],"mappings":";;AA2BA,MAAM,kBAAkB;;AAExB,MAAM,sBAAsB;;;;;AAM5B,MAAM,uBAAuB,KAAc,SAAmC;CAC7E,IAAI,UAAmB;CACvB,KAAK,IAAI,QAAQ,GAAG,QAAQ,GAAG,SAAS;EACvC,IAAI,OAAO,YAAY,YAAY,YAAY,MAC9C,OAAO;EAER,IAAK,QAA+B,SAAS,MAC5C,OAAO;EAER,UAAW,QAAgC;CAC5C;CACA,OAAO;AACR;;;;;;;;AASA,eAAsB,YACrB,SACA,MACA,KACmB;CACnB,IAAI,QAAQ,GAAG,SAAS,YAAY;EAEnC,MAAM,QADK,QAAQ,GACF,YAAY;EAC7B,IAAI,CAAC,OAAO,MAAM,IAAI,MAAM,mCAAmC,KAAK,YAAY;EAChF,IAAI;GAEH,QAAO,MADW,MAAM,WAAW,UAAU,KAAK,EAAE,cAAc,IAAI,GAAG,EAAE,QAAQ,KAAK,CAAC,GAC9E,kBAAkB;EAC9B,SAAS,KAAK;GACb,IAAI,oBAAoB,KAAK,eAAe,GAAG,OAAO;GACtD,MAAM;EACP;CACD;CACA,MAAM,KAAK,QAAQ;CACnB,MAAM,WAAW,KAAK,QAAQ,MAAM,GAAG;CACvC,MAAM,YAAY,GAAG,aAAa,IAAI,QAAQ;CAC9C,IAAI,CAAC,WAAW,MAAM,IAAI,MAAM,6BAA6B,SAAS,YAAY;CAClF,MAAM,QAAQ,GAAG,OAAO;CACxB,IAAI,CAAC,OAAO,MAAM,IAAI,MAAM,wCAAwC,UAAU,YAAY;CAC1F,IAAI;EAEH,QAAO,MADgB,GAAG,QAAQ,OAAO,KAAK,EAAE,OAAO,GAAG,EAAE,oBAAoB,EAAE,UAAU,GAC5E,WAAW;CAC5B,SAAS,KAAK;EACb,IAAI,oBAAoB,KAAK,mBAAmB,GAAG,OAAO;EAC1D,MAAM;CACP;AACD"}
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import "./paths.js";
|
|
2
|
-
import { getRuntime } from "./runtime.js";
|
|
2
|
+
import { getRuntime, readAccessFor, requestTimezone } from "./runtime.js";
|
|
3
3
|
import { TIMEFRAME_PRESETS } from "../timeframe/presets.js";
|
|
4
|
-
import { readForField } from "../fields/readForDocument.js";
|
|
5
4
|
import { METRIC_KEYS } from "../translations/metricKeys.js";
|
|
5
|
+
import { readForField } from "../fields/readForDocument.js";
|
|
6
|
+
import { parseDayOrInstant } from "../query/dates.js";
|
|
6
7
|
//#region src/plugin/documentEndpoint.ts
|
|
7
8
|
const KNOWN_METRICS = new Set(Object.keys(METRIC_KEYS));
|
|
8
9
|
const MAX_METRICS = 8;
|
|
@@ -11,19 +12,33 @@ const parseMetrics = (raw) => {
|
|
|
11
12
|
const metrics = raw.split(",").map((m) => m.trim()).filter((m) => KNOWN_METRICS.has(m));
|
|
12
13
|
return metrics.length > 0 ? metrics.slice(0, MAX_METRICS) : null;
|
|
13
14
|
};
|
|
14
|
-
|
|
15
|
+
/**
|
|
16
|
+
* A custom window from the query string, read exactly like the query endpoint's: a
|
|
17
|
+
* `YYYY-MM-DD` day is the whole calendar day in the reporting timezone (`to` inclusive of
|
|
18
|
+
* its final instant), a datetime must carry `Z` or a `±HH:MM` offset, and anything else,
|
|
19
|
+
* including an offset-less datetime, is rejected. `from` equal to `to` is one whole day for
|
|
20
|
+
* day strings and a zero-width window for two instants, so only the latter is rejected.
|
|
21
|
+
*/
|
|
22
|
+
const parseRange = (from, to, timezone) => {
|
|
15
23
|
if (!from || !to) return null;
|
|
16
|
-
const start =
|
|
17
|
-
|
|
18
|
-
|
|
24
|
+
const start = parseDayOrInstant(from, {
|
|
25
|
+
timezone,
|
|
26
|
+
edge: "start"
|
|
27
|
+
});
|
|
28
|
+
const end = parseDayOrInstant(to, {
|
|
29
|
+
timezone,
|
|
30
|
+
edge: "end"
|
|
31
|
+
});
|
|
32
|
+
if (!start || !end || end.getTime() <= start.getTime()) return null;
|
|
19
33
|
return {
|
|
20
34
|
start,
|
|
21
35
|
end
|
|
22
36
|
};
|
|
23
37
|
};
|
|
24
38
|
/**
|
|
25
|
-
* Authenticated GET handler behind the interactive document analytics panel
|
|
26
|
-
*
|
|
39
|
+
* Authenticated GET handler behind the interactive document analytics panel, gated
|
|
40
|
+
* by `access.read` like every other read endpoint. The caller must also be able to
|
|
41
|
+
* read the target document (enforced through `findByID`
|
|
27
42
|
* without `overrideAccess`), so analytics never leak for content the user cannot
|
|
28
43
|
* see; an unreadable or missing document is a uniform 404. Timeframe, metrics, and
|
|
29
44
|
* data source are whitelist-validated; `timeframe=custom` requires a parseable
|
|
@@ -33,12 +48,14 @@ const makeDocumentHandler = () => async (req) => {
|
|
|
33
48
|
if (!req.user) return Response.json({ error: "unauthorized" }, { status: 401 });
|
|
34
49
|
const runtime = getRuntime(req.payload);
|
|
35
50
|
if (!runtime) return Response.json({ error: "unavailable" }, { status: 503 });
|
|
51
|
+
if (!await readAccessFor(runtime, req)) return Response.json({ error: "forbidden" }, { status: 403 });
|
|
36
52
|
const params = new URL(req.url ?? "", "http://localhost").searchParams;
|
|
37
53
|
const collection = params.get("collection") ?? "";
|
|
38
54
|
const id = params.get("id") ?? "";
|
|
39
55
|
if (!runtime.bindings[collection] || !id) return Response.json({ error: "not found" }, { status: 404 });
|
|
40
56
|
const rawTimeframe = params.get("timeframe") ?? "last30days";
|
|
41
|
-
const
|
|
57
|
+
const timezone = rawTimeframe === "custom" ? await requestTimezone(req) : void 0;
|
|
58
|
+
const range = timezone !== void 0 ? parseRange(params.get("from"), params.get("to"), timezone) : void 0;
|
|
42
59
|
const timeframe = TIMEFRAME_PRESETS.includes(rawTimeframe) ? rawTimeframe : "last30days";
|
|
43
60
|
if (rawTimeframe === "custom" && !range) return Response.json({ error: "invalid range" }, { status: 400 });
|
|
44
61
|
const metrics = parseMetrics(params.get("metrics")) ?? [
|
|
@@ -67,6 +84,7 @@ const makeDocumentHandler = () => async (req) => {
|
|
|
67
84
|
metrics,
|
|
68
85
|
timeframe,
|
|
69
86
|
range: range ?? void 0,
|
|
87
|
+
...timezone !== void 0 ? { timezone } : {},
|
|
70
88
|
adapterId: params.get("dataSource") ?? void 0,
|
|
71
89
|
now: /* @__PURE__ */ new Date(),
|
|
72
90
|
compare: params.get("compare") === "1",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"documentEndpoint.js","names":[],"sources":["../../src/plugin/documentEndpoint.ts"],"sourcesContent":["import type { CollectionSlug, PayloadHandler } from 'payload'\nimport type { BindingDoc } from '../binding/types'\nimport type { DateRange, MetricKey } from '../core/contract'\nimport { readForField } from '../fields/readForDocument'\nimport { TIMEFRAME_PRESETS, type TimeframePreset } from '../timeframe/presets'\nimport { METRIC_KEYS } from '../translations/metricKeys'\nimport { DOCUMENT_PATH } from './paths'\nimport { getRuntime } from './runtime'\n\nexport { DOCUMENT_PATH }\n\nconst KNOWN_METRICS = new Set(Object.keys(METRIC_KEYS) as MetricKey[])\nconst MAX_METRICS = 8\n\nconst parseMetrics = (raw: string | null): MetricKey[] | null => {\n\tif (!raw) {\n\t\treturn null\n\t}\n\tconst metrics = raw\n\t\t.split(',')\n\t\t.map((m) => m.trim())\n\t\t.filter((m): m is MetricKey => KNOWN_METRICS.has(m as MetricKey))\n\treturn metrics.length > 0 ? metrics.slice(0, MAX_METRICS) : null\n}\n\nconst parseRange = (from: string | null, to: string | null): DateRange | null => {\n\tif (!from || !to) {\n\t\treturn null\n\t}\n\tconst start =
|
|
1
|
+
{"version":3,"file":"documentEndpoint.js","names":[],"sources":["../../src/plugin/documentEndpoint.ts"],"sourcesContent":["import type { CollectionSlug, PayloadHandler } from 'payload'\nimport type { BindingDoc } from '../binding/types'\nimport type { DateRange, MetricKey } from '../core/contract'\nimport { readForField } from '../fields/readForDocument'\nimport { parseDayOrInstant } from '../query/dates'\nimport { TIMEFRAME_PRESETS, type TimeframePreset } from '../timeframe/presets'\nimport { METRIC_KEYS } from '../translations/metricKeys'\nimport { DOCUMENT_PATH } from './paths'\nimport { getRuntime, readAccessFor, requestTimezone } from './runtime'\n\nexport { DOCUMENT_PATH }\n\nconst KNOWN_METRICS = new Set(Object.keys(METRIC_KEYS) as MetricKey[])\nconst MAX_METRICS = 8\n\nconst parseMetrics = (raw: string | null): MetricKey[] | null => {\n\tif (!raw) {\n\t\treturn null\n\t}\n\tconst metrics = raw\n\t\t.split(',')\n\t\t.map((m) => m.trim())\n\t\t.filter((m): m is MetricKey => KNOWN_METRICS.has(m as MetricKey))\n\treturn metrics.length > 0 ? metrics.slice(0, MAX_METRICS) : null\n}\n\n/**\n * A custom window from the query string, read exactly like the query endpoint's: a\n * `YYYY-MM-DD` day is the whole calendar day in the reporting timezone (`to` inclusive of\n * its final instant), a datetime must carry `Z` or a `±HH:MM` offset, and anything else,\n * including an offset-less datetime, is rejected. `from` equal to `to` is one whole day for\n * day strings and a zero-width window for two instants, so only the latter is rejected.\n */\nconst parseRange = (from: string | null, to: string | null, timezone: string): DateRange | null => {\n\tif (!from || !to) {\n\t\treturn null\n\t}\n\tconst start = parseDayOrInstant(from, { timezone, edge: 'start' })\n\tconst end = parseDayOrInstant(to, { timezone, edge: 'end' })\n\tif (!start || !end || end.getTime() <= start.getTime()) {\n\t\treturn null\n\t}\n\treturn { start, end }\n}\n\n/**\n * Authenticated GET handler behind the interactive document analytics panel, gated\n * by `access.read` like every other read endpoint. The caller must also be able to\n * read the target document (enforced through `findByID`\n * without `overrideAccess`), so analytics never leak for content the user cannot\n * see; an unreadable or missing document is a uniform 404. Timeframe, metrics, and\n * data source are whitelist-validated; `timeframe=custom` requires a parseable\n * `from`/`to` pair.\n */\nexport const makeDocumentHandler = (): 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({ error: 'unavailable' }, { status: 503 })\n\t}\n\tif (!(await readAccessFor(runtime, req))) {\n\t\treturn Response.json({ error: 'forbidden' }, { status: 403 })\n\t}\n\tconst params = new URL(req.url ?? '', 'http://localhost').searchParams\n\tconst collection = params.get('collection') ?? ''\n\tconst id = params.get('id') ?? ''\n\tif (!runtime.bindings[collection] || !id) {\n\t\treturn Response.json({ error: 'not found' }, { status: 404 })\n\t}\n\tconst rawTimeframe = params.get('timeframe') ?? 'last30days'\n\t// Custom bounds name calendar days, so the reporting timezone has to be resolved before\n\t// they can be read; a preset resolves its window inside `readForField` as before.\n\tconst timezone = rawTimeframe === 'custom' ? await requestTimezone(req) : undefined\n\tconst range =\n\t\ttimezone !== undefined ? parseRange(params.get('from'), params.get('to'), timezone) : undefined\n\tconst timeframe: TimeframePreset = TIMEFRAME_PRESETS.includes(rawTimeframe as TimeframePreset)\n\t\t? (rawTimeframe as TimeframePreset)\n\t\t: 'last30days'\n\tif (rawTimeframe === 'custom' && !range) {\n\t\treturn Response.json({ error: 'invalid range' }, { status: 400 })\n\t}\n\tconst metrics = parseMetrics(params.get('metrics')) ?? [\n\t\t'pageviews',\n\t\t'visitors',\n\t\t'sessions',\n\t\t'avgDuration',\n\t]\n\tlet data: BindingDoc\n\ttry {\n\t\tdata = (await req.payload.findByID({\n\t\t\tcollection: collection as CollectionSlug,\n\t\t\tid,\n\t\t\tdepth: 0,\n\t\t\toverrideAccess: false,\n\t\t\tuser: req.user,\n\t\t\treq,\n\t\t})) as BindingDoc\n\t} catch {\n\t\treturn Response.json({ error: 'not found' }, { status: 404 })\n\t}\n\tconst result = await readForField({\n\t\treq,\n\t\tcollectionSlug: collection,\n\t\tdata,\n\t\tmetrics,\n\t\ttimeframe,\n\t\trange: range ?? undefined,\n\t\t...(timezone !== undefined ? { timezone } : {}),\n\t\tadapterId: params.get('dataSource') ?? undefined,\n\t\tnow: new Date(),\n\t\tcompare: params.get('compare') === '1',\n\t\tseries: params.get('series') === '1',\n\t})\n\treturn Response.json(result)\n}\n"],"mappings":";;;;;;;AAYA,MAAM,gBAAgB,IAAI,IAAI,OAAO,KAAK,WAAW,CAAgB;AACrE,MAAM,cAAc;AAEpB,MAAM,gBAAgB,QAA2C;CAChE,IAAI,CAAC,KACJ,OAAO;CAER,MAAM,UAAU,IACd,MAAM,GAAG,EACT,KAAK,MAAM,EAAE,KAAK,CAAC,EACnB,QAAQ,MAAsB,cAAc,IAAI,CAAc,CAAC;CACjE,OAAO,QAAQ,SAAS,IAAI,QAAQ,MAAM,GAAG,WAAW,IAAI;AAC7D;;;;;;;;AASA,MAAM,cAAc,MAAqB,IAAmB,aAAuC;CAClG,IAAI,CAAC,QAAQ,CAAC,IACb,OAAO;CAER,MAAM,QAAQ,kBAAkB,MAAM;EAAE;EAAU,MAAM;CAAQ,CAAC;CACjE,MAAM,MAAM,kBAAkB,IAAI;EAAE;EAAU,MAAM;CAAM,CAAC;CAC3D,IAAI,CAAC,SAAS,CAAC,OAAO,IAAI,QAAQ,KAAK,MAAM,QAAQ,GACpD,OAAO;CAER,OAAO;EAAE;EAAO;CAAI;AACrB;;;;;;;;;;AAWA,MAAa,4BAA4C,OAAO,QAAQ;CACvE,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,OAAO,cAAc,GAAG,EAAE,QAAQ,IAAI,CAAC;CAE/D,IAAI,CAAE,MAAM,cAAc,SAAS,GAAG,GACr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SAAS,OAAO,IAAI,SAAS,MAAM;EACnC,QAAQ,OAAO,IAAI,QAAQ,MAAM;CAClC,CAAC;CACD,OAAO,SAAS,KAAK,MAAM;AAC5B"}
|
package/dist/plugin/paths.js
CHANGED
|
@@ -6,6 +6,10 @@
|
|
|
6
6
|
*/
|
|
7
7
|
const DOCUMENT_PATH = "/analytics/document";
|
|
8
8
|
const SOURCES_PATH = "/analytics/sources";
|
|
9
|
+
/** Authenticated goal list for the admin goal picker, per-request scope. */
|
|
10
|
+
const GOALS_PATH = "/analytics/goals";
|
|
11
|
+
/** Authenticated read endpoint over the surfacing engine, per-request scope. */
|
|
12
|
+
const QUERY_PATH = "/analytics/query";
|
|
9
13
|
const REALTIME_PATH = "/analytics/realtime";
|
|
10
14
|
/** Mount of the public capture proxy; each slot is served under `${PROXY_PATH}/<slot>`. */
|
|
11
15
|
const PROXY_PATH = "/analytics/p";
|
|
@@ -18,6 +22,6 @@ const TRACKER_PATH = "/analytics/tracker";
|
|
|
18
22
|
*/
|
|
19
23
|
const INGEST_PATH = "/analytics/ingest";
|
|
20
24
|
//#endregion
|
|
21
|
-
export { DOCUMENT_PATH, INGEST_PATH, PROXY_PATH, REALTIME_PATH, SOURCES_PATH, TRACKER_PATH };
|
|
25
|
+
export { DOCUMENT_PATH, GOALS_PATH, INGEST_PATH, PROXY_PATH, QUERY_PATH, REALTIME_PATH, SOURCES_PATH, TRACKER_PATH };
|
|
22
26
|
|
|
23
27
|
//# 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/** 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;
|
|
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'\n/** Authenticated goal list for the admin goal picker, per-request scope. */\nexport const GOALS_PATH = '/analytics/goals'\n/** Authenticated read endpoint over the surfacing engine, per-request scope. */\nexport const QUERY_PATH = '/analytics/query'\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;;AAE5B,MAAa,aAAa;;AAE1B,MAAa,aAAa;AAC1B,MAAa,gBAAgB;;AAE7B,MAAa,aAAa;;AAE1B,MAAa,eAAe;;;;;;AAM5B,MAAa,cAAc"}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import "./paths.js";
|
|
2
|
+
import "../core/contract.js";
|
|
3
|
+
import { getRuntime, platformReadGate, readAccessFor, resolveTimezoneFor } from "./runtime.js";
|
|
4
|
+
import { serializeCapabilities } from "../core/capabilities.js";
|
|
5
|
+
import { resolveQueryScope } from "../core/scopedRead.js";
|
|
6
|
+
import { previousWindow } from "../widgets/comparison.js";
|
|
7
|
+
import { queryError } from "../query/errors.js";
|
|
8
|
+
import { parseQueryParams, readParam } from "../query/parse.js";
|
|
9
|
+
import { resolveSourcesForRequest } from "./readContextForRequest.js";
|
|
10
|
+
//#region src/plugin/queryEndpoint.ts
|
|
11
|
+
/** Scope depends on the caller's cookies, so no shared cache may ever hold an answer. */
|
|
12
|
+
const NO_STORE = { "Cache-Control": "private, no-store" };
|
|
13
|
+
const errorResponse = (status, error, headers = {}) => Response.json({ error }, {
|
|
14
|
+
status,
|
|
15
|
+
headers: {
|
|
16
|
+
...NO_STORE,
|
|
17
|
+
...headers
|
|
18
|
+
}
|
|
19
|
+
});
|
|
20
|
+
const RETRY_AFTER = { "Retry-After": "30" };
|
|
21
|
+
const serializeQuery = (query) => ({
|
|
22
|
+
...query,
|
|
23
|
+
dateRange: {
|
|
24
|
+
start: query.dateRange.start.toISOString(),
|
|
25
|
+
end: query.dateRange.end.toISOString()
|
|
26
|
+
}
|
|
27
|
+
});
|
|
28
|
+
/**
|
|
29
|
+
* Authenticated GET over the surfacing engine: the public read primitive the admin view
|
|
30
|
+
* and consumers' own dashboards are built on. Gating runs in a fixed order so a caller
|
|
31
|
+
* learns nothing from the answer it is not already entitled to: authentication, then
|
|
32
|
+
* `access.read`, then scope and source resolution (shared with the sources endpoint, so a
|
|
33
|
+
* tenant can select no source that endpoint does not list), then capability validation of
|
|
34
|
+
* every parameter against the selected source. Being listed is not sufficient: a shared
|
|
35
|
+
* source that cannot narrow to the caller's scope answers 403 with `param: 'source'`.
|
|
36
|
+
* Errors carry a code and the parameter at fault; adapter configuration and upstream error
|
|
37
|
+
* text never reach the response.
|
|
38
|
+
*/
|
|
39
|
+
const makeQueryHandler = () => async (req) => {
|
|
40
|
+
if (!req.user) return errorResponse(401, queryError("unauthorized", "analytics: authentication required"));
|
|
41
|
+
const runtime = getRuntime(req.payload);
|
|
42
|
+
if (!runtime) return errorResponse(503, queryError("unavailable", "analytics: not available"), RETRY_AFTER);
|
|
43
|
+
let adapterId = "unresolved";
|
|
44
|
+
try {
|
|
45
|
+
if (!await readAccessFor(runtime, req)) return errorResponse(403, queryError("forbidden", "analytics: read access denied"));
|
|
46
|
+
const params = new URL(req.url ?? "", "http://localhost").searchParams;
|
|
47
|
+
const platformRead = platformReadGate(runtime, req);
|
|
48
|
+
const requestedScope = readParam(params, "scope");
|
|
49
|
+
if (requestedScope !== null && !await platformRead()) return errorResponse(400, queryError("untrusted_scope", "analytics: scope is not permitted for this request", "scope"));
|
|
50
|
+
const context = await resolveSourcesForRequest(req, {
|
|
51
|
+
platformRead,
|
|
52
|
+
...requestedScope === null ? {} : { scope: requestedScope }
|
|
53
|
+
});
|
|
54
|
+
if (context.adapters.size === 0) return errorResponse(404, queryError("unknown_source", "analytics: no source is available for this request"));
|
|
55
|
+
const requestedSource = readParam(params, "source");
|
|
56
|
+
const adapter = context.adapters.get(requestedSource ?? context.defaultId ?? "");
|
|
57
|
+
if (!adapter) return errorResponse(404, queryError("unknown_source", "analytics: unknown source", "source"));
|
|
58
|
+
adapterId = adapter.id;
|
|
59
|
+
const queryScope = await resolveQueryScope({
|
|
60
|
+
runtime,
|
|
61
|
+
req,
|
|
62
|
+
scope: context.scope,
|
|
63
|
+
adapter,
|
|
64
|
+
platformRead
|
|
65
|
+
});
|
|
66
|
+
if (!queryScope.ok) return errorResponse(403, queryError("forbidden", "analytics: this source cannot be read for your scope", "source"));
|
|
67
|
+
const capabilities = serializeCapabilities(adapter.capabilities);
|
|
68
|
+
const parsed = parseQueryParams(params, {
|
|
69
|
+
capabilities,
|
|
70
|
+
timezone: await resolveTimezoneFor(runtime, req, context.scope === "*" ? null : context.scope)
|
|
71
|
+
});
|
|
72
|
+
if (!parsed.ok) return errorResponse(400, parsed.error);
|
|
73
|
+
const query = {
|
|
74
|
+
...parsed.value.query,
|
|
75
|
+
...queryScope.queryScope === void 0 ? {} : { scope: queryScope.queryScope }
|
|
76
|
+
};
|
|
77
|
+
let comparisonRange = null;
|
|
78
|
+
if (parsed.value.compare === "previous") {
|
|
79
|
+
comparisonRange = previousWindow(query.dateRange, query.timezone);
|
|
80
|
+
if (!comparisonRange) return errorResponse(400, queryError("invalid_param", "analytics: the range is too long to compare against a previous period", "compare"));
|
|
81
|
+
}
|
|
82
|
+
let result;
|
|
83
|
+
let comparison;
|
|
84
|
+
try {
|
|
85
|
+
[result, comparison] = await Promise.all([runtime.engine.read(adapter, query), comparisonRange ? runtime.engine.read(adapter, {
|
|
86
|
+
...query,
|
|
87
|
+
dateRange: comparisonRange
|
|
88
|
+
}) : void 0]);
|
|
89
|
+
} catch (err) {
|
|
90
|
+
req.payload.logger?.warn(`analytics: query read failed for adapter "${adapter.id}": ${String(err)}`);
|
|
91
|
+
return errorResponse(503, queryError("unavailable", "analytics: source is temporarily unavailable"), RETRY_AFTER);
|
|
92
|
+
}
|
|
93
|
+
const body = {
|
|
94
|
+
result,
|
|
95
|
+
...comparison ? { comparison } : {},
|
|
96
|
+
source: {
|
|
97
|
+
id: adapter.id,
|
|
98
|
+
label: adapter.label,
|
|
99
|
+
kind: runtime.configAdapterIds.has(adapter.id) ? "config" : "runtime"
|
|
100
|
+
},
|
|
101
|
+
capabilities,
|
|
102
|
+
query: serializeQuery(query)
|
|
103
|
+
};
|
|
104
|
+
return Response.json(body, { headers: NO_STORE });
|
|
105
|
+
} catch (err) {
|
|
106
|
+
req.payload.logger?.warn(`analytics: query failed for adapter "${adapterId}": ${String(err)}`);
|
|
107
|
+
return errorResponse(500, queryError("internal", "analytics: query failed"));
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
//#endregion
|
|
111
|
+
export { makeQueryHandler };
|
|
112
|
+
|
|
113
|
+
//# sourceMappingURL=queryEndpoint.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"queryEndpoint.js","names":[],"sources":["../../src/plugin/queryEndpoint.ts"],"sourcesContent":["import type { PayloadHandler } from 'payload'\nimport { serializeCapabilities } from '../core/capabilities'\nimport {\n\ttype AnalyticsQuery,\n\ttype AnalyticsResult,\n\ttype DateRange,\n\tPLATFORM_SCOPE,\n} from '../core/contract'\nimport { resolveQueryScope } from '../core/scopedRead'\nimport { type QueryError, queryError } from '../query/errors'\nimport { parseQueryParams, readParam } from '../query/parse'\nimport type { QueryResponse, SerializedAnalyticsQuery } from '../query/response'\nimport { previousWindow } from '../widgets/comparison'\nimport { QUERY_PATH } from './paths'\nimport { resolveSourcesForRequest } from './readContextForRequest'\nimport { getRuntime, platformReadGate, readAccessFor, resolveTimezoneFor } from './runtime'\n\nexport { QUERY_PATH }\n\n/** Scope depends on the caller's cookies, so no shared cache may ever hold an answer. */\nconst NO_STORE = { 'Cache-Control': 'private, no-store' }\n\nconst errorResponse = (\n\tstatus: number,\n\terror: QueryError,\n\theaders: Record<string, string> = {}\n): Response => Response.json({ error }, { status, headers: { ...NO_STORE, ...headers } })\n\n/** How long a client should wait out a provider outage before retrying the same read. */\nconst RETRY_AFTER_SECONDS = '30'\nconst RETRY_AFTER = { 'Retry-After': RETRY_AFTER_SECONDS }\n\nconst serializeQuery = (query: AnalyticsQuery): SerializedAnalyticsQuery => ({\n\t...query,\n\tdateRange: {\n\t\tstart: query.dateRange.start.toISOString(),\n\t\tend: query.dateRange.end.toISOString(),\n\t},\n})\n\n/**\n * Authenticated GET over the surfacing engine: the public read primitive the admin view\n * and consumers' own dashboards are built on. Gating runs in a fixed order so a caller\n * learns nothing from the answer it is not already entitled to: authentication, then\n * `access.read`, then scope and source resolution (shared with the sources endpoint, so a\n * tenant can select no source that endpoint does not list), then capability validation of\n * every parameter against the selected source. Being listed is not sufficient: a shared\n * source that cannot narrow to the caller's scope answers 403 with `param: 'source'`.\n * Errors carry a code and the parameter at fault; adapter configuration and upstream error\n * text never reach the response.\n */\nexport const makeQueryHandler = (): PayloadHandler => async (req) => {\n\tif (!req.user) {\n\t\treturn errorResponse(401, queryError('unauthorized', 'analytics: authentication required'))\n\t}\n\tconst runtime = getRuntime(req.payload)\n\tif (!runtime) {\n\t\t// Both `unavailable` answers are retryable, so both carry the same delay: a client\n\t\t// backs off identically whether the plugin is still booting or a provider is down.\n\t\treturn errorResponse(503, queryError('unavailable', 'analytics: not available'), RETRY_AFTER)\n\t}\n\tlet adapterId = 'unresolved'\n\ttry {\n\t\tif (!(await readAccessFor(runtime, req))) {\n\t\t\treturn errorResponse(403, queryError('forbidden', 'analytics: read access denied'))\n\t\t}\n\t\tconst params = new URL(req.url ?? '', 'http://localhost').searchParams\n\t\tconst platformRead = platformReadGate(runtime, req)\n\t\tconst requestedScope = readParam(params, 'scope')\n\t\tif (requestedScope !== null && !(await platformRead())) {\n\t\t\treturn errorResponse(\n\t\t\t\t400,\n\t\t\t\tqueryError('untrusted_scope', 'analytics: scope is not permitted for this request', 'scope')\n\t\t\t)\n\t\t}\n\t\tconst context = await resolveSourcesForRequest(req, {\n\t\t\tplatformRead,\n\t\t\t...(requestedScope === null ? {} : { scope: requestedScope }),\n\t\t})\n\t\tif (context.adapters.size === 0) {\n\t\t\treturn errorResponse(\n\t\t\t\t404,\n\t\t\t\tqueryError('unknown_source', 'analytics: no source is available for this request')\n\t\t\t)\n\t\t}\n\t\tconst requestedSource = readParam(params, 'source')\n\t\tconst adapter = context.adapters.get(requestedSource ?? context.defaultId ?? '')\n\t\tif (!adapter) {\n\t\t\treturn errorResponse(404, queryError('unknown_source', 'analytics: unknown source', 'source'))\n\t\t}\n\t\tadapterId = adapter.id\n\t\tconst queryScope = await resolveQueryScope({\n\t\t\truntime,\n\t\t\treq,\n\t\t\tscope: context.scope,\n\t\t\tadapter,\n\t\t\tplatformRead,\n\t\t})\n\t\tif (!queryScope.ok) {\n\t\t\treturn errorResponse(\n\t\t\t\t403,\n\t\t\t\tqueryError('forbidden', 'analytics: this source cannot be read for your scope', 'source')\n\t\t\t)\n\t\t}\n\t\tconst capabilities = serializeCapabilities(adapter.capabilities)\n\t\tconst timezone = await resolveTimezoneFor(\n\t\t\truntime,\n\t\t\treq,\n\t\t\tcontext.scope === PLATFORM_SCOPE ? null : context.scope\n\t\t)\n\t\tconst parsed = parseQueryParams(params, { capabilities, timezone })\n\t\tif (!parsed.ok) {\n\t\t\treturn errorResponse(400, parsed.error)\n\t\t}\n\t\tconst query: AnalyticsQuery = {\n\t\t\t...parsed.value.query,\n\t\t\t...(queryScope.queryScope === undefined ? {} : { scope: queryScope.queryScope }),\n\t\t}\n\t\tlet comparisonRange: DateRange | null = null\n\t\tif (parsed.value.compare === 'previous') {\n\t\t\tcomparisonRange = previousWindow(query.dateRange, query.timezone)\n\t\t\tif (!comparisonRange) {\n\t\t\t\treturn errorResponse(\n\t\t\t\t\t400,\n\t\t\t\t\tqueryError(\n\t\t\t\t\t\t'invalid_param',\n\t\t\t\t\t\t'analytics: the range is too long to compare against a previous period',\n\t\t\t\t\t\t'compare'\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t\tlet result: AnalyticsResult\n\t\tlet comparison: AnalyticsResult | undefined\n\t\ttry {\n\t\t\t;[result, comparison] = await Promise.all([\n\t\t\t\truntime.engine.read(adapter, query),\n\t\t\t\tcomparisonRange\n\t\t\t\t\t? runtime.engine.read(adapter, { ...query, dateRange: comparisonRange })\n\t\t\t\t\t: undefined,\n\t\t\t])\n\t\t} catch (err) {\n\t\t\t// Neither a fresh nor a stale entry survived the read: the source is down, not the\n\t\t\t// request wrong, so the client is told to retry rather than to change anything.\n\t\t\treq.payload.logger?.warn(\n\t\t\t\t`analytics: query read failed for adapter \"${adapter.id}\": ${String(err)}`\n\t\t\t)\n\t\t\treturn errorResponse(\n\t\t\t\t503,\n\t\t\t\tqueryError('unavailable', 'analytics: source is temporarily unavailable'),\n\t\t\t\tRETRY_AFTER\n\t\t\t)\n\t\t}\n\t\tconst body: QueryResponse = {\n\t\t\tresult,\n\t\t\t...(comparison ? { comparison } : {}),\n\t\t\tsource: {\n\t\t\t\tid: adapter.id,\n\t\t\t\tlabel: adapter.label,\n\t\t\t\tkind: runtime.configAdapterIds.has(adapter.id) ? 'config' : 'runtime',\n\t\t\t},\n\t\t\tcapabilities,\n\t\t\tquery: serializeQuery(query),\n\t\t}\n\t\treturn Response.json(body, { headers: NO_STORE })\n\t} catch (err) {\n\t\treq.payload.logger?.warn(`analytics: query failed for adapter \"${adapterId}\": ${String(err)}`)\n\t\treturn errorResponse(500, queryError('internal', 'analytics: query failed'))\n\t}\n}\n"],"mappings":";;;;;;;;;;;AAoBA,MAAM,WAAW,EAAE,iBAAiB,oBAAoB;AAExD,MAAM,iBACL,QACA,OACA,UAAkC,CAAC,MACrB,SAAS,KAAK,EAAE,MAAM,GAAG;CAAE;CAAQ,SAAS;EAAE,GAAG;EAAU,GAAG;CAAQ;AAAE,CAAC;AAIxF,MAAM,cAAc,EAAE,eAAe,KAAoB;AAEzD,MAAM,kBAAkB,WAAqD;CAC5E,GAAG;CACH,WAAW;EACV,OAAO,MAAM,UAAU,MAAM,YAAY;EACzC,KAAK,MAAM,UAAU,IAAI,YAAY;CACtC;AACD;;;;;;;;;;;;AAaA,MAAa,yBAAyC,OAAO,QAAQ;CACpE,IAAI,CAAC,IAAI,MACR,OAAO,cAAc,KAAK,WAAW,gBAAgB,oCAAoC,CAAC;CAE3F,MAAM,UAAU,WAAW,IAAI,OAAO;CACtC,IAAI,CAAC,SAGJ,OAAO,cAAc,KAAK,WAAW,eAAe,0BAA0B,GAAG,WAAW;CAE7F,IAAI,YAAY;CAChB,IAAI;EACH,IAAI,CAAE,MAAM,cAAc,SAAS,GAAG,GACrC,OAAO,cAAc,KAAK,WAAW,aAAa,+BAA+B,CAAC;EAEnF,MAAM,SAAS,IAAI,IAAI,IAAI,OAAO,IAAI,kBAAkB,EAAE;EAC1D,MAAM,eAAe,iBAAiB,SA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EF;EACA,IAAI;EACJ,IAAI;EACJ,IAAI;GACF,CAAC,QAAQ,cAAc,MAAM,QAAQ,IAAI,CACzC,QAAQ,OAAO,KAAK,SAAS,KAAK,GAClC,kBACG,QAAQ,OAAO,KAAK,SAAS;IAAE,GAAG;IAAO,WAAW;GAAgB,CAAC,IACrE,KAAA,CACJ,CAAC;EACF,SAAS,KAAK;GAGb,IAAI,QAAQ,QAAQ,KACnB,6CAA6C,QAAQ,GAAG,KAAK,OAAO,GAAG,GACxE;GACA,OAAO,cACN,KACA,WAAW,eAAe,8CAA8C,GACxE,WACD;EACD;EACA,MAAM,OAAsB;GAC3B;GACA,GAAI,aAAa,EAAE,WAAW,IAAI,CAAC;GACnC,QAAQ;IACP,IAAI,QAAQ;IACZ,OAAO,QAAQ;IACf,MAAM,QAAQ,iBAAiB,IAAI,QAAQ,EAAE,IAAI,WAAW;GAC7D;GACA;GACA,OAAO,eAAe,KAAK;EAC5B;EACA,OAAO,SAAS,KAAK,MAAM,EAAE,SAAS,SAAS,CAAC;CACjD,SAAS,KAAK;EACb,IAAI,QAAQ,QAAQ,KAAK,wCAAwC,UAAU,KAAK,OAAO,GAAG,GAAG;EAC7F,OAAO,cAAc,KAAK,WAAW,YAAY,yBAAyB,CAAC;CAC5E;AACD"}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import "../core/contract.js";
|
|
2
|
+
import { getRuntime, platformReadGate, resolveRegistryFor, resolveScopeFor } from "./runtime.js";
|
|
3
|
+
import { serializeCapabilities } from "../core/capabilities.js";
|
|
4
|
+
//#region src/plugin/readContextForRequest.ts
|
|
5
|
+
const empty = () => ({
|
|
6
|
+
sources: [],
|
|
7
|
+
defaultId: null,
|
|
8
|
+
adapters: /* @__PURE__ */ new Map(),
|
|
9
|
+
scope: null
|
|
10
|
+
});
|
|
11
|
+
const fromRegistry = (args) => {
|
|
12
|
+
const { runtime, registry, scope } = args;
|
|
13
|
+
const adapters = registry.all();
|
|
14
|
+
return {
|
|
15
|
+
sources: adapters.map((adapter) => ({
|
|
16
|
+
id: adapter.id,
|
|
17
|
+
label: adapter.label,
|
|
18
|
+
kind: runtime.configAdapterIds.has(adapter.id) ? "config" : "runtime",
|
|
19
|
+
capabilities: serializeCapabilities(adapter.capabilities)
|
|
20
|
+
})),
|
|
21
|
+
defaultId: registry.default().id,
|
|
22
|
+
adapters: new Map(adapters.map((adapter) => [adapter.id, adapter])),
|
|
23
|
+
scope
|
|
24
|
+
};
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* The sources a request may read, resolved once for both read endpoints: the request's
|
|
28
|
+
* own scope (or a trusted explicit one), the per-scope registry, and each adapter's
|
|
29
|
+
* serialized capabilities. Two resolutions are cross-scope and fail closed behind
|
|
30
|
+
* `platformRead`: a scopeResolver answering the `'*'` marker, and, on a scoped install, one
|
|
31
|
+
* answering no scope at all, which is ambiguous rather than install-wide (returning null
|
|
32
|
+
* usually means "no tenant selected"). A failed resolution resolves nothing too, since it is
|
|
33
|
+
* indistinguishable from a forged one. An unscoped install falls back to the static config
|
|
34
|
+
* registry on failure.
|
|
35
|
+
*/
|
|
36
|
+
const resolveSourcesForRequest = async (req, args = {}) => {
|
|
37
|
+
const runtime = getRuntime(req.payload);
|
|
38
|
+
if (!runtime) return empty();
|
|
39
|
+
const allowed = args.platformRead ?? platformReadGate(runtime, req);
|
|
40
|
+
try {
|
|
41
|
+
let scope;
|
|
42
|
+
if (args.scope !== void 0) {
|
|
43
|
+
if (!await allowed()) return empty();
|
|
44
|
+
scope = args.scope;
|
|
45
|
+
} else {
|
|
46
|
+
scope = await resolveScopeFor(runtime, req);
|
|
47
|
+
if ((scope === "*" || runtime.scoped && scope === null) && !await allowed()) return empty();
|
|
48
|
+
}
|
|
49
|
+
return fromRegistry({
|
|
50
|
+
runtime,
|
|
51
|
+
registry: await resolveRegistryFor(runtime, {
|
|
52
|
+
payload: req.payload,
|
|
53
|
+
req,
|
|
54
|
+
scope: scope === "*" ? null : scope
|
|
55
|
+
}),
|
|
56
|
+
scope
|
|
57
|
+
});
|
|
58
|
+
} catch (err) {
|
|
59
|
+
req.payload.logger?.warn(`analytics: source resolution failed: ${String(err)}`);
|
|
60
|
+
if (runtime.scoped) return empty();
|
|
61
|
+
return fromRegistry({
|
|
62
|
+
runtime,
|
|
63
|
+
registry: runtime.registry,
|
|
64
|
+
scope: null
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
//#endregion
|
|
69
|
+
export { resolveSourcesForRequest };
|
|
70
|
+
|
|
71
|
+
//# sourceMappingURL=readContextForRequest.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"readContextForRequest.js","names":[],"sources":["../../src/plugin/readContextForRequest.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport { type SerializedCapabilities, serializeCapabilities } from '../core/capabilities'\nimport { type AnalyticsAdapter, PLATFORM_SCOPE } from '../core/contract'\nimport type { AdapterRegistry } from '../core/registry'\nimport type { QuerySourceRef } from '../query/response'\nimport {\n\ttype AnalyticsRuntime,\n\tgetRuntime,\n\ttype PlatformReadGate,\n\tplatformReadGate,\n\tresolveRegistryFor,\n\tresolveScopeFor,\n} from './runtime'\n\n/** One readable source on the wire: its identity plus the capabilities a client gates on. */\nexport interface RequestSource extends QuerySourceRef {\n\tcapabilities: SerializedCapabilities\n}\n\nexport interface RequestSources {\n\t/** Wire rows for the resolved scope, in registry order; empty when none resolve. */\n\tsources: RequestSource[]\n\tdefaultId: string | null\n\t/** The adapters behind `sources`, for callers that read through them. */\n\tadapters: ReadonlyMap<string, AnalyticsAdapter>\n\t/** Scope the sources were resolved for; null is install-wide, `*` is cross-scope. */\n\tscope: string | null\n}\n\nexport interface ResolveSourcesArgs {\n\t/**\n\t * Read another scope's sources instead of the request's own. Evaluated behind\n\t * `access.platformRead`; a denied override resolves nothing at all.\n\t */\n\tscope?: string | null\n\t/** Shared `platformRead` decision; one is created per call when omitted. */\n\tplatformRead?: PlatformReadGate\n}\n\nconst empty = (): RequestSources => ({\n\tsources: [],\n\tdefaultId: null,\n\tadapters: new Map(),\n\tscope: null,\n})\n\nconst fromRegistry = (args: {\n\truntime: AnalyticsRuntime\n\tregistry: AdapterRegistry\n\tscope: string | null\n}): RequestSources => {\n\tconst { runtime, registry, scope } = args\n\tconst adapters = registry.all()\n\treturn {\n\t\tsources: adapters.map((adapter) => ({\n\t\t\tid: adapter.id,\n\t\t\tlabel: adapter.label,\n\t\t\tkind: runtime.configAdapterIds.has(adapter.id) ? ('config' as const) : ('runtime' as const),\n\t\t\tcapabilities: serializeCapabilities(adapter.capabilities),\n\t\t})),\n\t\tdefaultId: registry.default().id,\n\t\tadapters: new Map(adapters.map((adapter) => [adapter.id, adapter])),\n\t\tscope,\n\t}\n}\n\n/**\n * The sources a request may read, resolved once for both read endpoints: the request's\n * own scope (or a trusted explicit one), the per-scope registry, and each adapter's\n * serialized capabilities. Two resolutions are cross-scope and fail closed behind\n * `platformRead`: a scopeResolver answering the `'*'` marker, and, on a scoped install, one\n * answering no scope at all, which is ambiguous rather than install-wide (returning null\n * usually means \"no tenant selected\"). A failed resolution resolves nothing too, since it is\n * indistinguishable from a forged one. An unscoped install falls back to the static config\n * registry on failure.\n */\nexport const resolveSourcesForRequest = async (\n\treq: PayloadRequest,\n\targs: ResolveSourcesArgs = {}\n): Promise<RequestSources> => {\n\tconst runtime = getRuntime(req.payload)\n\tif (!runtime) {\n\t\treturn empty()\n\t}\n\tconst allowed = args.platformRead ?? platformReadGate(runtime, req)\n\ttry {\n\t\tlet scope: string | null\n\t\tif (args.scope !== undefined) {\n\t\t\tif (!(await allowed())) {\n\t\t\t\treturn empty()\n\t\t\t}\n\t\t\tscope = args.scope\n\t\t} else {\n\t\t\tscope = await resolveScopeFor(runtime, req)\n\t\t\tconst crossScope = scope === PLATFORM_SCOPE || (runtime.scoped && scope === null)\n\t\t\tif (crossScope && !(await allowed())) {\n\t\t\t\treturn empty()\n\t\t\t}\n\t\t}\n\t\tconst registry = await resolveRegistryFor(runtime, {\n\t\t\tpayload: req.payload,\n\t\t\treq,\n\t\t\tscope: scope === PLATFORM_SCOPE ? null : scope,\n\t\t})\n\t\treturn fromRegistry({ runtime, registry, scope })\n\t} catch (err) {\n\t\treq.payload.logger?.warn(`analytics: source resolution failed: ${String(err)}`)\n\t\tif (runtime.scoped) {\n\t\t\treturn empty()\n\t\t}\n\t\treturn fromRegistry({ runtime, registry: runtime.registry, scope: null })\n\t}\n}\n"],"mappings":";;;;AAuCA,MAAM,eAA+B;CACpC,SAAS,CAAC;CACV,WAAW;CACX,0BAAU,IAAI,IAAI;CAClB,OAAO;AACR;AAEA,MAAM,gBAAgB,SAIA;CACrB,MAAM,EAAE,SAAS,UAAU,UAAU;CACrC,MAAM,WAAW,SAAS,IAAI;CAC9B,OAAO;EACN,SAAS,SAAS,KAAK,aAAa;GACnC,IAAI,QAAQ;GACZ,OAAO,QAAQ;GACf,MAAM,QAAQ,iBAAiB,IAAI,QAAQ,EAAE,IAAK,WAAsB;GACxE,cAAc,sBAAsB,QAAQ,YAAY;EACzD,EAAE;EACF,WAAW,SAAS,QAAQ,EAAE;EAC9B,UAAU,IAAI,IAAI,SAAS,KAAK,YAAY,CAAC,QAAQ,IAAI,OAAO,CAAC,CAAC;EAClE;CACD;AACD;;;;;;;;;;;AAYA,MAAa,2BAA2B,OACvC,KACA,OAA2B,CAAC,MACC;CAC7B,MAAM,UAAU,WAAW,IAAI,OAAO;CACtC,IAAI,CAAC,SACJ,OAAO,MAAM;CAEd,MAAM,UAAU,KAAK,gBAAgB,iBAAiB,SAAS,GAAG;CAClE,IAAI;EACH,IAAI;EACJ,IAAI,KAAK,UAAU,KAAA,GAAW;GAC7B,IAAI,CAAE,MAAM,QAAQ,GACnB,OAAO,MAAM;GAEd,QAAQ,KAAK;EACd,OAAO;GACN,QAAQ,MAAM,gBAAgB,SAAS,GAAG;GAE1C,KADmB,UAAA,OAA6B,QAAQ,UAAU,UAAU,SAC1D,CAAE,MAAM,QA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