@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
package/dist/index.js
CHANGED
|
@@ -1,25 +1,35 @@
|
|
|
1
|
-
import { DOCUMENT_PATH, REALTIME_PATH, SOURCES_PATH } from "./plugin/paths.js";
|
|
1
|
+
import { DOCUMENT_PATH, GOALS_PATH, QUERY_PATH, REALTIME_PATH, SOURCES_PATH } from "./plugin/paths.js";
|
|
2
|
+
import { PLATFORM_SCOPE } from "./core/contract.js";
|
|
2
3
|
import { isValidTimeZone } from "./timeframe/tz.js";
|
|
3
4
|
import { setRuntime } from "./plugin/runtime.js";
|
|
4
5
|
import { proxyEndpoints } from "./capture/proxyEndpoint.js";
|
|
6
|
+
import { configGoalsResolver, createGoalsResolver } from "./goals/resolver.js";
|
|
7
|
+
import { buildGoalsCollection } from "./goals/collection.js";
|
|
5
8
|
import { buildProvidersCollection } from "./providers/collection.js";
|
|
6
9
|
import { resolveOptions } from "./core/options.js";
|
|
7
10
|
import { trackerEndpoint } from "./capture/trackerEndpoint.js";
|
|
8
11
|
import { createRegistry, staticRegistryResolver } from "./core/registry.js";
|
|
9
|
-
import {
|
|
12
|
+
import { makeGoalsHandler } from "./goals/goalsEndpoint.js";
|
|
13
|
+
import { AnalyticsTrackError } from "./core/serverEvent.js";
|
|
14
|
+
import { trackServerEvent } from "./native/ingest/serverTrack.js";
|
|
10
15
|
import { makeDocumentHandler } from "./plugin/documentEndpoint.js";
|
|
11
16
|
import { isModuleNotFoundError } from "./plugin/peerImportError.js";
|
|
17
|
+
import { makeQueryHandler } from "./plugin/queryEndpoint.js";
|
|
12
18
|
import { kvCacheStore } from "./surfacing/cacheStore.js";
|
|
13
19
|
import { makeRealtimeHandler } from "./plugin/realtimeEndpoint.js";
|
|
14
20
|
import { registerTranslations } from "./plugin/registerTranslations.js";
|
|
21
|
+
import { validateScopeField } from "./plugin/scopeFieldBoot.js";
|
|
15
22
|
import { makeSourcesHandler } from "./plugin/sourcesEndpoint.js";
|
|
16
23
|
import { warmTask } from "./plugin/warmTask.js";
|
|
17
24
|
import { collectionProvidersSource, combineRegistries, createScopedRegistryResolver } from "./providers/resolver.js";
|
|
18
25
|
import { createEngine } from "./surfacing/engine.js";
|
|
19
26
|
import { syncCollection } from "./sync/collection.js";
|
|
20
27
|
import { syncTask } from "./sync/syncTask.js";
|
|
28
|
+
import { registerView } from "./view/registerView.js";
|
|
21
29
|
import { registerWidgets } from "./widgets/registerWidgets.js";
|
|
22
30
|
import { analyticsFields, analyticsStat, analyticsStatRow, analyticsTab, analyticsTabsField } from "./fields/factories.js";
|
|
31
|
+
import { goalField, goalSlug } from "./goals/goalField.js";
|
|
32
|
+
import { GOAL_ACTION_TYPE, trackGoalAction } from "./goals/trackGoalAction.js";
|
|
23
33
|
import { analyticsDefaultWidgets } from "./widgets/defaults.js";
|
|
24
34
|
import { definePlugin } from "payload";
|
|
25
35
|
//#region src/index.ts
|
|
@@ -78,6 +88,22 @@ const analytics = definePlugin({
|
|
|
78
88
|
});
|
|
79
89
|
config.collections = [...config.collections ?? [], withEncryptedQueryRewrite(providersCollection)];
|
|
80
90
|
}
|
|
91
|
+
const goalsResolver = resolved.goalsCollection.enabled ? createGoalsResolver({
|
|
92
|
+
slug: resolved.goalsCollection.slug,
|
|
93
|
+
scopeField: resolved.goalsCollection.scopeField,
|
|
94
|
+
scoped: resolved.scoped,
|
|
95
|
+
config: resolved.goals
|
|
96
|
+
}) : configGoalsResolver(resolved.goals);
|
|
97
|
+
if (resolved.goalsCollection.enabled) config.collections = [...config.collections ?? [], buildGoalsCollection({
|
|
98
|
+
slug: resolved.goalsCollection.slug,
|
|
99
|
+
access: resolved.goalsCollection.access,
|
|
100
|
+
overrides: resolved.goalsCollection.overrides,
|
|
101
|
+
onChange: () => goalsResolver.invalidate(),
|
|
102
|
+
scoped: resolved.scoped,
|
|
103
|
+
scopeField: resolved.goalsCollection.scopeField,
|
|
104
|
+
resolveScope,
|
|
105
|
+
platformRead: resolved.access.platformRead
|
|
106
|
+
})];
|
|
81
107
|
const resolveTimezone = async (req, scope) => {
|
|
82
108
|
const opt = resolved.reportingTimezone;
|
|
83
109
|
if (opt === void 0) return "UTC";
|
|
@@ -92,12 +118,11 @@ const analytics = definePlugin({
|
|
|
92
118
|
return "UTC";
|
|
93
119
|
}
|
|
94
120
|
};
|
|
95
|
-
const resolveGoals = async (_req, _scope) => resolved.goals;
|
|
96
121
|
for (const adapter of resolved.adapters) adapter.register?.(config, {
|
|
97
122
|
scoped: resolved.scoped,
|
|
98
123
|
resolveScope,
|
|
99
124
|
resolveTimezone,
|
|
100
|
-
resolveGoals
|
|
125
|
+
resolveGoals: goalsResolver.resolve
|
|
101
126
|
});
|
|
102
127
|
if (resolved.adapters.some((a) => a.capabilities.realtime && typeof a.realtime === "function") || providersEnabled) config.endpoints = [...config.endpoints ?? [], {
|
|
103
128
|
method: "get",
|
|
@@ -109,11 +134,24 @@ const analytics = definePlugin({
|
|
|
109
134
|
path: DOCUMENT_PATH,
|
|
110
135
|
handler: makeDocumentHandler()
|
|
111
136
|
}];
|
|
112
|
-
config.endpoints = [
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
137
|
+
config.endpoints = [
|
|
138
|
+
...config.endpoints ?? [],
|
|
139
|
+
{
|
|
140
|
+
method: "get",
|
|
141
|
+
path: SOURCES_PATH,
|
|
142
|
+
handler: makeSourcesHandler()
|
|
143
|
+
},
|
|
144
|
+
{
|
|
145
|
+
method: "get",
|
|
146
|
+
path: GOALS_PATH,
|
|
147
|
+
handler: makeGoalsHandler()
|
|
148
|
+
},
|
|
149
|
+
{
|
|
150
|
+
method: "get",
|
|
151
|
+
path: QUERY_PATH,
|
|
152
|
+
handler: makeQueryHandler()
|
|
153
|
+
}
|
|
154
|
+
];
|
|
117
155
|
if (resolved.adapters.some((a) => a.capture) || providersEnabled) config.endpoints = [
|
|
118
156
|
...config.endpoints,
|
|
119
157
|
...proxyEndpoints(),
|
|
@@ -128,9 +166,19 @@ const analytics = definePlugin({
|
|
|
128
166
|
disabled: resolved.widgets.disabled,
|
|
129
167
|
register: resolved.widgets.register,
|
|
130
168
|
localizeText: resolved.widgets.localizeText,
|
|
131
|
-
defaultId: resolved.defaultAdapter
|
|
169
|
+
defaultId: resolved.defaultAdapter,
|
|
170
|
+
comparison: resolved.widgets.comparison,
|
|
171
|
+
view: resolved.view === false ? false : {
|
|
172
|
+
path: resolved.view.path,
|
|
173
|
+
defaultRange: resolved.view.defaultRange,
|
|
174
|
+
defaultMetric: resolved.view.defaultMetric
|
|
175
|
+
}
|
|
132
176
|
});
|
|
133
177
|
}
|
|
178
|
+
registerView(config, {
|
|
179
|
+
view: resolved.view,
|
|
180
|
+
pluginOptions: options
|
|
181
|
+
});
|
|
134
182
|
if (resolved.cache.warm.enabled) config.jobs = {
|
|
135
183
|
...config.jobs,
|
|
136
184
|
tasks: [...config.jobs?.tasks ?? [], warmTask(resolved.cache.warm.cron, defaultLayout, resolved.scopes)]
|
|
@@ -155,6 +203,16 @@ const analytics = definePlugin({
|
|
|
155
203
|
}
|
|
156
204
|
const prevOnInit = config.onInit;
|
|
157
205
|
config.onInit = async (payload) => {
|
|
206
|
+
if (resolved.scoped && resolved.goalsCollection.enabled) validateScopeField(payload, {
|
|
207
|
+
option: "goals.collection.scopeField",
|
|
208
|
+
slug: resolved.goalsCollection.slug,
|
|
209
|
+
scopeField: resolved.goalsCollection.scopeField
|
|
210
|
+
});
|
|
211
|
+
if (resolved.scoped && resolved.providers.collection.enabled) validateScopeField(payload, {
|
|
212
|
+
option: "providers.collection.scopeField",
|
|
213
|
+
slug: resolved.providers.collection.slug,
|
|
214
|
+
scopeField: resolved.providers.collection.scopeField
|
|
215
|
+
});
|
|
158
216
|
if (resolved.providers.collection.enabled) {
|
|
159
217
|
const { validateEncryptedBoot } = await import("@10x-media/fields/encrypted");
|
|
160
218
|
await validateEncryptedBoot(payload, resolved.providers.collection.encryption?.keys);
|
|
@@ -180,10 +238,15 @@ const analytics = definePlugin({
|
|
|
180
238
|
consentFor: resolved.capture.consent,
|
|
181
239
|
autoCapture: resolved.capture.autoCapture,
|
|
182
240
|
goals: resolved.goals,
|
|
241
|
+
resolveGoals: goalsResolver.resolve,
|
|
242
|
+
resolveGoalsDetailed: goalsResolver.resolveDetailed,
|
|
243
|
+
...resolved.goalsCollection.enabled ? { goalsCollectionSlug: resolved.goalsCollection.slug } : {},
|
|
183
244
|
ingestPath: resolved.adapters.find((a) => a.ingest)?.ingest?.path,
|
|
245
|
+
track: (event, opts) => trackServerEvent(payload, event, opts),
|
|
184
246
|
scoped: resolved.scoped,
|
|
185
247
|
configAdapterIds: new Set(resolved.adapters.map((a) => a.id)),
|
|
186
248
|
platformRead: resolved.access.platformRead,
|
|
249
|
+
readAccess: resolved.access.read,
|
|
187
250
|
bindings: resolved.bindings,
|
|
188
251
|
engine,
|
|
189
252
|
ttl: resolved.cache.ttl,
|
|
@@ -195,6 +258,6 @@ const analytics = definePlugin({
|
|
|
195
258
|
}
|
|
196
259
|
});
|
|
197
260
|
//#endregion
|
|
198
|
-
export { PLATFORM_SCOPE, analytics, analyticsDefaultWidgets, analyticsFields, analyticsStat, analyticsStatRow, analyticsTab, analyticsTabsField };
|
|
261
|
+
export { AnalyticsTrackError, GOAL_ACTION_TYPE, PLATFORM_SCOPE, analytics, analyticsDefaultWidgets, analyticsFields, analyticsStat, analyticsStatRow, analyticsTab, analyticsTabsField, goalField, goalSlug, trackGoalAction, trackServerEvent };
|
|
199
262
|
|
|
200
263
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["import { type Config, definePlugin, type PayloadRequest } from 'payload'\n\nimport { proxyEndpoints } from './capture/proxyEndpoint'\nimport { trackerEndpoint } from './capture/trackerEndpoint'\nimport { type AnalyticsPluginOptions, resolveOptions } from './core/options'\nimport { createRegistry, staticRegistryResolver } from './core/registry'\nimport type { Goal } from './goals/types'\nimport { DOCUMENT_PATH, makeDocumentHandler } from './plugin/documentEndpoint'\nimport { isModuleNotFoundError } from './plugin/peerImportError'\nimport { makeRealtimeHandler, REALTIME_PATH } from './plugin/realtimeEndpoint'\nimport { registerTranslations } from './plugin/registerTranslations'\nimport { setRuntime } from './plugin/runtime'\nimport { makeSourcesHandler, SOURCES_PATH } from './plugin/sourcesEndpoint'\nimport { warmTask } from './plugin/warmTask'\nimport type { BuildSecretField } from './providers/collection'\nimport { buildProvidersCollection } from './providers/collection'\nimport {\n\tcollectionProvidersSource,\n\tcombineRegistries,\n\tcreateScopedRegistryResolver,\n} from './providers/resolver'\nimport { kvCacheStore } from './surfacing/cacheStore'\nimport { createEngine } from './surfacing/engine'\nimport { syncCollection } from './sync/collection'\nimport { syncTask } from './sync/syncTask'\nimport { DEFAULT_TIMEZONE, isValidTimeZone } from './timeframe/tz'\nimport { registerWidgets } from './widgets/registerWidgets'\n\ndeclare module 'payload' {\n\tinterface RegisteredPlugins {\n\t\t'@10x-media/analytics': AnalyticsPluginOptions\n\t}\n}\n\nexport const analytics = definePlugin<AnalyticsPluginOptions>({\n\tslug: '@10x-media/analytics',\n\tplugin: async ({ config, plugins: _plugins, ...options }): Promise<Config> => {\n\t\tif (options.disabled === true) {\n\t\t\treturn config\n\t\t}\n\t\tconst resolved = resolveOptions(options)\n\t\t// A tenant's own runtime adapter (providers.collection or providers.resolve) has\n\t\t// capabilities unknown at config time, so it opens the widget/endpoint gates that\n\t\t// otherwise key off the config-adapter capability union.\n\t\tconst providersEnabled =\n\t\t\tresolved.providers.collection.enabled || Boolean(resolved.providers.resolve)\n\t\tconst defaultLayout = config.admin?.dashboard?.defaultLayout\n\t\tregisterTranslations(config, options.translations)\n\t\tconst registry = createRegistry(resolved.adapters, resolved.defaultAdapter)\n\t\tconst registryBase = { adapters: resolved.adapters, defaultId: resolved.defaultAdapter }\n\t\tlet resolveRegistry = staticRegistryResolver(registry)\n\t\tlet invalidateProviders = () => {}\n\t\tconst providersResolve = resolved.providers.resolve\n\t\tif (providersResolve) {\n\t\t\tresolveRegistry = async (args) =>\n\t\t\t\tcombineRegistries(\n\t\t\t\t\tregistryBase,\n\t\t\t\t\tawait providersResolve({ payload: args.payload, req: args.req, scope: args.scope })\n\t\t\t\t)\n\t\t} else if (resolved.providers.collection.enabled) {\n\t\t\tconst scoped = createScopedRegistryResolver({\n\t\t\t\tbase: registryBase,\n\t\t\t\tsource: collectionProvidersSource(\n\t\t\t\t\tresolved.providers.collection.slug,\n\t\t\t\t\tresolved.providers.collection.scopeField\n\t\t\t\t),\n\t\t\t})\n\t\t\tresolveRegistry = scoped.resolver\n\t\t\tinvalidateProviders = scoped.invalidate\n\t\t}\n\t\tconst resolveScope = async (req: PayloadRequest) => resolved.scopeResolver({ req })\n\t\tif (resolved.providers.collection.enabled) {\n\t\t\tconst { encryptedField, withEncryptedQueryRewrite } = await import(\n\t\t\t\t'@10x-media/fields/encrypted'\n\t\t\t).catch((err: unknown) => {\n\t\t\t\tif (isModuleNotFoundError(err)) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t'analytics: providers.collection requires @10x-media/fields (peer). Install it: pnpm add @10x-media/fields'\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tthrow err\n\t\t\t})\n\t\t\tconst encryption = resolved.providers.collection.encryption\n\t\t\tconst buildSecret: BuildSecretField = (source) =>\n\t\t\t\tencryptedField(source, {\n\t\t\t\t\tprotection: 'writeOnly',\n\t\t\t\t\taadScope: '10x-analytics:providers',\n\t\t\t\t\t...(source.type === 'text' ? { hint: { suffix: 4 } } : {}),\n\t\t\t\t\t...(encryption?.keys ? { keys: encryption.keys } : {}),\n\t\t\t\t})\n\t\t\tconst providersCollection = buildProvidersCollection({\n\t\t\t\tslug: resolved.providers.collection.slug,\n\t\t\t\taccess: resolved.providers.collection.access,\n\t\t\t\toverrides: resolved.providers.collection.overrides,\n\t\t\t\tonChange: () => invalidateProviders(),\n\t\t\t\tscoped: resolved.scoped,\n\t\t\t\tscopeField: resolved.providers.collection.scopeField,\n\t\t\t\tresolveScope,\n\t\t\t\tplatformRead: resolved.access.platformRead,\n\t\t\t\tbuildSecret,\n\t\t\t})\n\t\t\t// Always wrap, even though a consumer's own @10x-media/fields plugin (if\n\t\t\t// registered) may wrap this collection again later: double application is\n\t\t\t// inert here (writeOnly forbids queryable, so there are no blind-index\n\t\t\t// markers to rewrite and the response strip is an idempotent delete),\n\t\t\t// while skipping would leak ciphertext whenever fields() runs before this\n\t\t\t// collection exists (e.g. an earlier plugin `order`).\n\t\t\tconfig.collections = [\n\t\t\t\t...(config.collections ?? []),\n\t\t\t\twithEncryptedQueryRewrite(providersCollection),\n\t\t\t]\n\t\t}\n\t\tconst resolveTimezone = async (req: PayloadRequest, scope?: string | null): Promise<string> => {\n\t\t\tconst opt = resolved.reportingTimezone\n\t\t\tif (opt === undefined) {\n\t\t\t\treturn DEFAULT_TIMEZONE\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst tz =\n\t\t\t\t\ttypeof opt === 'string'\n\t\t\t\t\t\t? opt\n\t\t\t\t\t\t: await opt({ req, scope: scope !== undefined ? scope : await resolveScope(req) })\n\t\t\t\treturn tz && isValidTimeZone(tz) ? tz : DEFAULT_TIMEZONE\n\t\t\t} catch (err) {\n\t\t\t\treq.payload?.logger?.warn?.(\n\t\t\t\t\t`analytics: reportingTimezone resolution failed, falling back to UTC: ${String(err)}`\n\t\t\t\t)\n\t\t\t\treturn DEFAULT_TIMEZONE\n\t\t\t}\n\t\t}\n\t\t// Config goals are install-wide, so scope is accepted and ignored here; a collection\n\t\t// source resolves per scope behind the same signature.\n\t\tconst resolveGoals = async (_req: PayloadRequest, _scope?: string | null): Promise<Goal[]> =>\n\t\t\tresolved.goals\n\t\tfor (const adapter of resolved.adapters) {\n\t\t\tadapter.register?.(config, {\n\t\t\t\tscoped: resolved.scoped,\n\t\t\t\tresolveScope,\n\t\t\t\tresolveTimezone,\n\t\t\t\tresolveGoals,\n\t\t\t})\n\t\t}\n\t\tif (\n\t\t\tresolved.adapters.some((a) => a.capabilities.realtime && typeof a.realtime === 'function') ||\n\t\t\tprovidersEnabled\n\t\t) {\n\t\t\tconfig.endpoints = [\n\t\t\t\t...(config.endpoints ?? []),\n\t\t\t\t{ method: 'get', path: REALTIME_PATH, handler: makeRealtimeHandler() },\n\t\t\t]\n\t\t}\n\t\tif (Object.keys(resolved.bindings).length > 0) {\n\t\t\tconfig.endpoints = [\n\t\t\t\t...(config.endpoints ?? []),\n\t\t\t\t{ method: 'get', path: DOCUMENT_PATH, handler: makeDocumentHandler() },\n\t\t\t]\n\t\t}\n\t\tconfig.endpoints = [\n\t\t\t...(config.endpoints ?? []),\n\t\t\t{ method: 'get', path: SOURCES_PATH, handler: makeSourcesHandler() },\n\t\t]\n\t\t// A runtime provider's capture support is unknown at config time, so providers\n\t\t// alone are enough to mount the proxy; every slot is still resolved per request.\n\t\tif (resolved.adapters.some((a) => a.capture) || providersEnabled) {\n\t\t\tconfig.endpoints = [...config.endpoints, ...proxyEndpoints(), trackerEndpoint()]\n\t\t}\n\t\tif (resolved.widgets.enabled) {\n\t\t\tconst multiProvider = registry.isMultiProvider() || providersEnabled\n\t\t\tregisterWidgets(config, {\n\t\t\t\tadapters: resolved.adapters,\n\t\t\t\tmultiProvider,\n\t\t\t\tprovidersEnabled,\n\t\t\t\tdisabled: resolved.widgets.disabled,\n\t\t\t\tregister: resolved.widgets.register,\n\t\t\t\tlocalizeText: resolved.widgets.localizeText,\n\t\t\t\tdefaultId: resolved.defaultAdapter,\n\t\t\t})\n\t\t}\n\t\tif (resolved.cache.warm.enabled) {\n\t\t\tconfig.jobs = {\n\t\t\t\t...config.jobs,\n\t\t\t\ttasks: [\n\t\t\t\t\t...(config.jobs?.tasks ?? []),\n\t\t\t\t\twarmTask(resolved.cache.warm.cron, defaultLayout, resolved.scopes),\n\t\t\t\t],\n\t\t\t}\n\t\t}\n\t\tif (resolved.sync.enabled) {\n\t\t\tconfig.collections = [\n\t\t\t\t...(config.collections ?? []),\n\t\t\t\tsyncCollection(resolved.sync.collectionSlug, resolved.sync.hidden, {\n\t\t\t\t\tscoped: resolved.scoped,\n\t\t\t\t\tscopeField: 'scope',\n\t\t\t\t\tresolveScope,\n\t\t\t\t\tplatformRead: resolved.access.platformRead,\n\t\t\t\t}),\n\t\t\t]\n\t\t\tconfig.jobs = {\n\t\t\t\t...config.jobs,\n\t\t\t\ttasks: [\n\t\t\t\t\t...(config.jobs?.tasks ?? []),\n\t\t\t\t\tsyncTask({\n\t\t\t\t\t\tcron: resolved.sync.cron,\n\t\t\t\t\t\tlookbackDays: resolved.sync.lookbackDays,\n\t\t\t\t\t\tcollectionSlug: resolved.sync.collectionSlug,\n\t\t\t\t\t\tadapterIds: resolved.sync.adapters,\n\t\t\t\t\t\tscopes: resolved.scopes,\n\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t}\n\t\t}\n\t\tconst prevOnInit = config.onInit\n\t\t// The runtime is installed before the app's own onInit runs so consumer init code\n\t\t// (seeding, cache warming, sync passes) can already read through the plugin.\n\t\tconfig.onInit = async (payload) => {\n\t\t\tif (resolved.providers.collection.enabled) {\n\t\t\t\tconst { validateEncryptedBoot } = await import('@10x-media/fields/encrypted')\n\t\t\t\tawait validateEncryptedBoot(payload, resolved.providers.collection.encryption?.keys)\n\t\t\t}\n\t\t\tconst engine = createEngine({\n\t\t\t\tstore: kvCacheStore(payload.kv),\n\t\t\t\tqueue: { concurrency: 4 },\n\t\t\t\tttl: resolved.cache.ttl,\n\t\t\t\ttimeoutMs: resolved.cache.timeoutMs,\n\t\t\t\tonError: (err, adapterId) => {\n\t\t\t\t\tpayload.logger?.warn(`analytics: read failed for adapter \"${adapterId}\": ${String(err)}`)\n\t\t\t\t},\n\t\t\t})\n\t\t\tsetRuntime(payload, {\n\t\t\t\tregistry,\n\t\t\t\tresolveRegistry,\n\t\t\t\tresolveScope,\n\t\t\t\tresolveTimezone,\n\t\t\t\tplatformAdapterId: resolved.platformAdapter,\n\t\t\t\tcaptureSlots: resolved.capture.slots,\n\t\t\t\tcapturePaths: resolved.capture.paths,\n\t\t\t\tcaptureProxy: resolved.capture.proxy,\n\t\t\t\tconsentFor: resolved.capture.consent,\n\t\t\t\tautoCapture: resolved.capture.autoCapture,\n\t\t\t\tgoals: resolved.goals,\n\t\t\t\tingestPath: resolved.adapters.find((a) => a.ingest)?.ingest?.path,\n\t\t\t\tscoped: resolved.scoped,\n\t\t\t\tconfigAdapterIds: new Set(resolved.adapters.map((a) => a.id)),\n\t\t\t\tplatformRead: resolved.access.platformRead,\n\t\t\t\tbindings: resolved.bindings,\n\t\t\t\tengine,\n\t\t\t\tttl: resolved.cache.ttl,\n\t\t\t\tcomparison: resolved.widgets.comparison,\n\t\t\t})\n\t\t\tawait prevOnInit?.(payload)\n\t\t}\n\t\treturn config\n\t},\n})\n\nexport type {\n\tAnalyticsBinding,\n\tBindingContext,\n\tHostnameResolver,\n\tPathResolver,\n} from './binding/types'\nexport { PLATFORM_SCOPE } from './core/contract'\nexport type {\n\tAnalyticsAccessOptions,\n\tAnalyticsCaptureOptions,\n\tAnalyticsGoalsOptions,\n\tAnalyticsPluginOptions,\n\tAnalyticsPluginOptions as PluginOptions,\n\tAutoCaptureOptions,\n\tCaptureConsentOption,\n\tConsentMode,\n\tConsentResolver,\n\tPlatformReadAccess,\n\tProvidersCollectionOptions,\n\tProvidersOptions,\n\tProvidersResolve,\n\tScopeResolver,\n\tScopesResolver,\n\tTimezoneResolver,\n} from './core/options'\nexport type {\n\tAnalyticsFieldsOptions,\n\tAnalyticsMetricLabel,\n\tAnalyticsMetricLabels,\n\tAnalyticsStatOptions,\n\tAnalyticsStatRowOptions,\n\tAnalyticsTabOptions,\n} from './fields/factories'\nexport {\n\tanalyticsFields,\n\tanalyticsStat,\n\tanalyticsStatRow,\n\tanalyticsTab,\n\tanalyticsTabsField,\n} from './fields/factories'\nexport type { Goal, GoalMatch, TrackerGoal } from './goals/types'\nexport type { TimeframePreset } from './timeframe/presets'\nexport type { CustomWidgetDef } from './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QAAQ,SAAS;IAClB,CAAC,CACF;GACD;EACD;EACA,MAAM,aAAa,OAAO;EAG1B,OAAO,SAAS,OAAO,YAAY;GAClC,IAAI,SAAS,UAAU,WAAW,SAAS;IAC1C,MAAM,EAAE,0BAA0B,MAAM,OAAO;IAC/C,MAAM,sBAAsB,SAAS,SAAS,UAAU,WAAW,YAAY,IAAI;GACpF;GACA,MAAM,SAAS,aAAa;IAC3B,OAAO,aAAa,QAAQ,EAAE;IAC9B,OAAO,EAAE,aAAa,EAAE;IACxB,KAAK,SAAS,MAAM;IACpB,WAAW,SAAS,MAAM;IAC1B,UAAU,KAAK,cAAc;KAC5B,QAAQ,QAAQ,KAAK,uCAAuC,UAAU,KAAK,OAAO,GAAG,GAAG;IACzF;GACD,CAAC;GACD,WAAW,SAAS;IACnB;IACA;IACA;IACA;IACA,mBAAmB,SAAS;IAC5B,cAAc,SAAS,QAAQ;IAC/B,cAAc,SAAS,QAAQ;IAC/B,cAAc,SAAS,QAAQ;IAC/B,YAAY,SAAS,QAAQ;IAC7B,aAAa,SAAS,QAAQ;IAC9B,OAAO,SAAS;IAChB,YAAY,SAAS,SAAS,MAAM,MAAM,EAAE,MAAM,GAAG,QAAQ;IAC7D,QAAQ,SAAS;IACjB,kBAAkB,IAAI,IAAI,SAAS,SAAS,KAAK,MAAM,EAAE,EAAE,CAAC;IAC5D,cAAc,SAAS,OAAO;IAC9B,UAAU,SAAS;IACnB;IACA,KAAK,SAAS,MAAM;IACpB,YAAY,SAAS,QAAQ;GAC9B,CAAC;GACD,MAAM,aAAa,OAAO;EAC3B;EACA,OAAO;CACR;AACD,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["import { type Config, definePlugin, type PayloadRequest } from 'payload'\n\nimport { proxyEndpoints } from './capture/proxyEndpoint'\nimport { trackerEndpoint } from './capture/trackerEndpoint'\nimport { type AnalyticsPluginOptions, resolveOptions } from './core/options'\nimport { createRegistry, staticRegistryResolver } from './core/registry'\nimport { buildGoalsCollection } from './goals/collection'\nimport { GOALS_PATH, makeGoalsHandler } from './goals/goalsEndpoint'\nimport { configGoalsResolver, createGoalsResolver } from './goals/resolver'\nimport { trackServerEvent } from './native/ingest/serverTrack'\nimport { DOCUMENT_PATH, makeDocumentHandler } from './plugin/documentEndpoint'\nimport { isModuleNotFoundError } from './plugin/peerImportError'\nimport { makeQueryHandler, QUERY_PATH } from './plugin/queryEndpoint'\nimport { makeRealtimeHandler, REALTIME_PATH } from './plugin/realtimeEndpoint'\nimport { registerTranslations } from './plugin/registerTranslations'\nimport { setRuntime } from './plugin/runtime'\nimport { validateScopeField } from './plugin/scopeFieldBoot'\nimport { makeSourcesHandler, SOURCES_PATH } from './plugin/sourcesEndpoint'\nimport { warmTask } from './plugin/warmTask'\nimport type { BuildSecretField } from './providers/collection'\nimport { buildProvidersCollection } from './providers/collection'\nimport {\n\tcollectionProvidersSource,\n\tcombineRegistries,\n\tcreateScopedRegistryResolver,\n} from './providers/resolver'\nimport { kvCacheStore } from './surfacing/cacheStore'\nimport { createEngine } from './surfacing/engine'\nimport { syncCollection } from './sync/collection'\nimport { syncTask } from './sync/syncTask'\nimport { DEFAULT_TIMEZONE, isValidTimeZone } from './timeframe/tz'\nimport { registerView } from './view/registerView'\nimport { registerWidgets } from './widgets/registerWidgets'\n\ndeclare module 'payload' {\n\tinterface RegisteredPlugins {\n\t\t'@10x-media/analytics': AnalyticsPluginOptions\n\t}\n}\n\nexport const analytics = definePlugin<AnalyticsPluginOptions>({\n\tslug: '@10x-media/analytics',\n\tplugin: async ({ config, plugins: _plugins, ...options }): Promise<Config> => {\n\t\tif (options.disabled === true) {\n\t\t\treturn config\n\t\t}\n\t\tconst resolved = resolveOptions(options)\n\t\t// A tenant's own runtime adapter (providers.collection or providers.resolve) has\n\t\t// capabilities unknown at config time, so it opens the widget/endpoint gates that\n\t\t// otherwise key off the config-adapter capability union.\n\t\tconst providersEnabled =\n\t\t\tresolved.providers.collection.enabled || Boolean(resolved.providers.resolve)\n\t\tconst defaultLayout = config.admin?.dashboard?.defaultLayout\n\t\tregisterTranslations(config, options.translations)\n\t\tconst registry = createRegistry(resolved.adapters, resolved.defaultAdapter)\n\t\tconst registryBase = { adapters: resolved.adapters, defaultId: resolved.defaultAdapter }\n\t\tlet resolveRegistry = staticRegistryResolver(registry)\n\t\tlet invalidateProviders = () => {}\n\t\tconst providersResolve = resolved.providers.resolve\n\t\tif (providersResolve) {\n\t\t\tresolveRegistry = async (args) =>\n\t\t\t\tcombineRegistries(\n\t\t\t\t\tregistryBase,\n\t\t\t\t\tawait providersResolve({ payload: args.payload, req: args.req, scope: args.scope })\n\t\t\t\t)\n\t\t} else if (resolved.providers.collection.enabled) {\n\t\t\tconst scoped = createScopedRegistryResolver({\n\t\t\t\tbase: registryBase,\n\t\t\t\tsource: collectionProvidersSource(\n\t\t\t\t\tresolved.providers.collection.slug,\n\t\t\t\t\tresolved.providers.collection.scopeField\n\t\t\t\t),\n\t\t\t})\n\t\t\tresolveRegistry = scoped.resolver\n\t\t\tinvalidateProviders = scoped.invalidate\n\t\t}\n\t\tconst resolveScope = async (req: PayloadRequest) => resolved.scopeResolver({ req })\n\t\tif (resolved.providers.collection.enabled) {\n\t\t\tconst { encryptedField, withEncryptedQueryRewrite } = await import(\n\t\t\t\t'@10x-media/fields/encrypted'\n\t\t\t).catch((err: unknown) => {\n\t\t\t\tif (isModuleNotFoundError(err)) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t'analytics: providers.collection requires @10x-media/fields (peer). Install it: pnpm add @10x-media/fields'\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tthrow err\n\t\t\t})\n\t\t\tconst encryption = resolved.providers.collection.encryption\n\t\t\tconst buildSecret: BuildSecretField = (source) =>\n\t\t\t\tencryptedField(source, {\n\t\t\t\t\tprotection: 'writeOnly',\n\t\t\t\t\taadScope: '10x-analytics:providers',\n\t\t\t\t\t...(source.type === 'text' ? { hint: { suffix: 4 } } : {}),\n\t\t\t\t\t...(encryption?.keys ? { keys: encryption.keys } : {}),\n\t\t\t\t})\n\t\t\tconst providersCollection = buildProvidersCollection({\n\t\t\t\tslug: resolved.providers.collection.slug,\n\t\t\t\taccess: resolved.providers.collection.access,\n\t\t\t\toverrides: resolved.providers.collection.overrides,\n\t\t\t\tonChange: () => invalidateProviders(),\n\t\t\t\tscoped: resolved.scoped,\n\t\t\t\tscopeField: resolved.providers.collection.scopeField,\n\t\t\t\tresolveScope,\n\t\t\t\tplatformRead: resolved.access.platformRead,\n\t\t\t\tbuildSecret,\n\t\t\t})\n\t\t\t// Always wrap, even though a consumer's own @10x-media/fields plugin (if\n\t\t\t// registered) may wrap this collection again later: double application is\n\t\t\t// inert here (writeOnly forbids queryable, so there are no blind-index\n\t\t\t// markers to rewrite and the response strip is an idempotent delete),\n\t\t\t// while skipping would leak ciphertext whenever fields() runs before this\n\t\t\t// collection exists (e.g. an earlier plugin `order`).\n\t\t\tconfig.collections = [\n\t\t\t\t...(config.collections ?? []),\n\t\t\t\twithEncryptedQueryRewrite(providersCollection),\n\t\t\t]\n\t\t}\n\t\t// Config goals are install-wide; the collection resolves per scope and merges over\n\t\t// them behind the same signature, so ingest and the tracker config read one source.\n\t\tconst goalsResolver = resolved.goalsCollection.enabled\n\t\t\t? createGoalsResolver({\n\t\t\t\t\tslug: resolved.goalsCollection.slug,\n\t\t\t\t\tscopeField: resolved.goalsCollection.scopeField,\n\t\t\t\t\tscoped: resolved.scoped,\n\t\t\t\t\tconfig: resolved.goals,\n\t\t\t\t})\n\t\t\t: configGoalsResolver(resolved.goals)\n\t\tif (resolved.goalsCollection.enabled) {\n\t\t\tconfig.collections = [\n\t\t\t\t...(config.collections ?? []),\n\t\t\t\tbuildGoalsCollection({\n\t\t\t\t\tslug: resolved.goalsCollection.slug,\n\t\t\t\t\taccess: resolved.goalsCollection.access,\n\t\t\t\t\toverrides: resolved.goalsCollection.overrides,\n\t\t\t\t\tonChange: () => goalsResolver.invalidate(),\n\t\t\t\t\tscoped: resolved.scoped,\n\t\t\t\t\tscopeField: resolved.goalsCollection.scopeField,\n\t\t\t\t\tresolveScope,\n\t\t\t\t\tplatformRead: resolved.access.platformRead,\n\t\t\t\t}),\n\t\t\t]\n\t\t}\n\t\tconst resolveTimezone = async (req: PayloadRequest, scope?: string | null): Promise<string> => {\n\t\t\tconst opt = resolved.reportingTimezone\n\t\t\tif (opt === undefined) {\n\t\t\t\treturn DEFAULT_TIMEZONE\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst tz =\n\t\t\t\t\ttypeof opt === 'string'\n\t\t\t\t\t\t? opt\n\t\t\t\t\t\t: await opt({ req, scope: scope !== undefined ? scope : await resolveScope(req) })\n\t\t\t\treturn tz && isValidTimeZone(tz) ? tz : DEFAULT_TIMEZONE\n\t\t\t} catch (err) {\n\t\t\t\treq.payload?.logger?.warn?.(\n\t\t\t\t\t`analytics: reportingTimezone resolution failed, falling back to UTC: ${String(err)}`\n\t\t\t\t)\n\t\t\t\treturn DEFAULT_TIMEZONE\n\t\t\t}\n\t\t}\n\t\tfor (const adapter of resolved.adapters) {\n\t\t\tadapter.register?.(config, {\n\t\t\t\tscoped: resolved.scoped,\n\t\t\t\tresolveScope,\n\t\t\t\tresolveTimezone,\n\t\t\t\tresolveGoals: goalsResolver.resolve,\n\t\t\t})\n\t\t}\n\t\tif (\n\t\t\tresolved.adapters.some((a) => a.capabilities.realtime && typeof a.realtime === 'function') ||\n\t\t\tprovidersEnabled\n\t\t) {\n\t\t\tconfig.endpoints = [\n\t\t\t\t...(config.endpoints ?? []),\n\t\t\t\t{ method: 'get', path: REALTIME_PATH, handler: makeRealtimeHandler() },\n\t\t\t]\n\t\t}\n\t\tif (Object.keys(resolved.bindings).length > 0) {\n\t\t\tconfig.endpoints = [\n\t\t\t\t...(config.endpoints ?? []),\n\t\t\t\t{ method: 'get', path: DOCUMENT_PATH, handler: makeDocumentHandler() },\n\t\t\t]\n\t\t}\n\t\tconfig.endpoints = [\n\t\t\t...(config.endpoints ?? []),\n\t\t\t{ method: 'get', path: SOURCES_PATH, handler: makeSourcesHandler() },\n\t\t\t{ method: 'get', path: GOALS_PATH, handler: makeGoalsHandler() },\n\t\t\t{ method: 'get', path: QUERY_PATH, handler: makeQueryHandler() },\n\t\t]\n\t\t// A runtime provider's capture support is unknown at config time, so providers\n\t\t// alone are enough to mount the proxy; every slot is still resolved per request.\n\t\tif (resolved.adapters.some((a) => a.capture) || providersEnabled) {\n\t\t\tconfig.endpoints = [...config.endpoints, ...proxyEndpoints(), trackerEndpoint()]\n\t\t}\n\t\tif (resolved.widgets.enabled) {\n\t\t\tconst multiProvider = registry.isMultiProvider() || providersEnabled\n\t\t\tregisterWidgets(config, {\n\t\t\t\tadapters: resolved.adapters,\n\t\t\t\tmultiProvider,\n\t\t\t\tprovidersEnabled,\n\t\t\t\tdisabled: resolved.widgets.disabled,\n\t\t\t\tregister: resolved.widgets.register,\n\t\t\t\tlocalizeText: resolved.widgets.localizeText,\n\t\t\t\tdefaultId: resolved.defaultAdapter,\n\t\t\t\tcomparison: resolved.widgets.comparison,\n\t\t\t\tview:\n\t\t\t\t\tresolved.view === false\n\t\t\t\t\t\t? false\n\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\tpath: resolved.view.path,\n\t\t\t\t\t\t\t\tdefaultRange: resolved.view.defaultRange,\n\t\t\t\t\t\t\t\tdefaultMetric: resolved.view.defaultMetric,\n\t\t\t\t\t\t\t},\n\t\t\t})\n\t\t}\n\t\tregisterView(config, { view: resolved.view, pluginOptions: options })\n\t\tif (resolved.cache.warm.enabled) {\n\t\t\tconfig.jobs = {\n\t\t\t\t...config.jobs,\n\t\t\t\ttasks: [\n\t\t\t\t\t...(config.jobs?.tasks ?? []),\n\t\t\t\t\twarmTask(resolved.cache.warm.cron, defaultLayout, resolved.scopes),\n\t\t\t\t],\n\t\t\t}\n\t\t}\n\t\tif (resolved.sync.enabled) {\n\t\t\tconfig.collections = [\n\t\t\t\t...(config.collections ?? []),\n\t\t\t\tsyncCollection(resolved.sync.collectionSlug, resolved.sync.hidden, {\n\t\t\t\t\tscoped: resolved.scoped,\n\t\t\t\t\tscopeField: 'scope',\n\t\t\t\t\tresolveScope,\n\t\t\t\t\tplatformRead: resolved.access.platformRead,\n\t\t\t\t}),\n\t\t\t]\n\t\t\tconfig.jobs = {\n\t\t\t\t...config.jobs,\n\t\t\t\ttasks: [\n\t\t\t\t\t...(config.jobs?.tasks ?? []),\n\t\t\t\t\tsyncTask({\n\t\t\t\t\t\tcron: resolved.sync.cron,\n\t\t\t\t\t\tlookbackDays: resolved.sync.lookbackDays,\n\t\t\t\t\t\tcollectionSlug: resolved.sync.collectionSlug,\n\t\t\t\t\t\tadapterIds: resolved.sync.adapters,\n\t\t\t\t\t\tscopes: resolved.scopes,\n\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t}\n\t\t}\n\t\tconst prevOnInit = config.onInit\n\t\t// The runtime is installed before the app's own onInit runs so consumer init code\n\t\t// (seeding, cache warming, sync passes) can already read through the plugin.\n\t\tconfig.onInit = async (payload) => {\n\t\t\t// Host-owned scope fields only exist once every plugin has run, so the collections\n\t\t\t// are checked against the assembled config rather than at config time.\n\t\t\tif (resolved.scoped && resolved.goalsCollection.enabled) {\n\t\t\t\tvalidateScopeField(payload, {\n\t\t\t\t\toption: 'goals.collection.scopeField',\n\t\t\t\t\tslug: resolved.goalsCollection.slug,\n\t\t\t\t\tscopeField: resolved.goalsCollection.scopeField,\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (resolved.scoped && resolved.providers.collection.enabled) {\n\t\t\t\tvalidateScopeField(payload, {\n\t\t\t\t\toption: 'providers.collection.scopeField',\n\t\t\t\t\tslug: resolved.providers.collection.slug,\n\t\t\t\t\tscopeField: resolved.providers.collection.scopeField,\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (resolved.providers.collection.enabled) {\n\t\t\t\tconst { validateEncryptedBoot } = await import('@10x-media/fields/encrypted')\n\t\t\t\tawait validateEncryptedBoot(payload, resolved.providers.collection.encryption?.keys)\n\t\t\t}\n\t\t\tconst engine = createEngine({\n\t\t\t\tstore: kvCacheStore(payload.kv),\n\t\t\t\tqueue: { concurrency: 4 },\n\t\t\t\tttl: resolved.cache.ttl,\n\t\t\t\ttimeoutMs: resolved.cache.timeoutMs,\n\t\t\t\tonError: (err, adapterId) => {\n\t\t\t\t\tpayload.logger?.warn(`analytics: read failed for adapter \"${adapterId}\": ${String(err)}`)\n\t\t\t\t},\n\t\t\t})\n\t\t\tsetRuntime(payload, {\n\t\t\t\tregistry,\n\t\t\t\tresolveRegistry,\n\t\t\t\tresolveScope,\n\t\t\t\tresolveTimezone,\n\t\t\t\tplatformAdapterId: resolved.platformAdapter,\n\t\t\t\tcaptureSlots: resolved.capture.slots,\n\t\t\t\tcapturePaths: resolved.capture.paths,\n\t\t\t\tcaptureProxy: resolved.capture.proxy,\n\t\t\t\tconsentFor: resolved.capture.consent,\n\t\t\t\tautoCapture: resolved.capture.autoCapture,\n\t\t\t\tgoals: resolved.goals,\n\t\t\t\tresolveGoals: goalsResolver.resolve,\n\t\t\t\tresolveGoalsDetailed: goalsResolver.resolveDetailed,\n\t\t\t\t...(resolved.goalsCollection.enabled\n\t\t\t\t\t? { goalsCollectionSlug: resolved.goalsCollection.slug }\n\t\t\t\t\t: {}),\n\t\t\t\tingestPath: resolved.adapters.find((a) => a.ingest)?.ingest?.path,\n\t\t\t\ttrack: (event, opts) => trackServerEvent(payload, event, opts),\n\t\t\t\tscoped: resolved.scoped,\n\t\t\t\tconfigAdapterIds: new Set(resolved.adapters.map((a) => a.id)),\n\t\t\t\tplatformRead: resolved.access.platformRead,\n\t\t\t\treadAccess: resolved.access.read,\n\t\t\t\tbindings: resolved.bindings,\n\t\t\t\tengine,\n\t\t\t\tttl: resolved.cache.ttl,\n\t\t\t\tcomparison: resolved.widgets.comparison,\n\t\t\t})\n\t\t\tawait prevOnInit?.(payload)\n\t\t}\n\t\treturn config\n\t},\n})\n\nexport type {\n\tAnalyticsBinding,\n\tBindingContext,\n\tHostnameResolver,\n\tPathResolver,\n} from './binding/types'\nexport { PLATFORM_SCOPE } from './core/contract'\nexport type {\n\tAnalyticsAccessOptions,\n\tAnalyticsCaptureOptions,\n\tAnalyticsGoalsCollectionOptions,\n\tAnalyticsGoalsOptions,\n\tAnalyticsPluginOptions,\n\tAnalyticsPluginOptions as PluginOptions,\n\tAnalyticsReadAccess,\n\tAnalyticsViewAccess,\n\tAnalyticsViewOptions,\n\tAutoCaptureOptions,\n\tCaptureConsentOption,\n\tConsentMode,\n\tConsentResolver,\n\tPlatformReadAccess,\n\tProvidersCollectionOptions,\n\tProvidersOptions,\n\tProvidersResolve,\n\tScopeResolver,\n\tScopesResolver,\n\tTimezoneResolver,\n} from './core/options'\nexport type { ServerEventInput, ServerTrack, ServerTrackOptions } from './core/serverEvent'\nexport { AnalyticsTrackError } from './core/serverEvent'\nexport type {\n\tAnalyticsFieldsOptions,\n\tAnalyticsMetricLabel,\n\tAnalyticsMetricLabels,\n\tAnalyticsStatOptions,\n\tAnalyticsStatRowOptions,\n\tAnalyticsTabOptions,\n} from './fields/factories'\nexport {\n\tanalyticsFields,\n\tanalyticsStat,\n\tanalyticsStatRow,\n\tanalyticsTab,\n\tanalyticsTabsField,\n} from './fields/factories'\nexport type { GoalFieldOptions } from './goals/goalField'\nexport { goalField, goalSlug } from './goals/goalField'\nexport type { GoalsResponse, WireGoal } from './goals/goalsEndpoint'\nexport type {\n\tGoalActionDefinition,\n\tGoalActionRunArgs,\n\tTrackGoalActionOptions,\n} from './goals/trackGoalAction'\nexport { GOAL_ACTION_TYPE, trackGoalAction } from './goals/trackGoalAction'\nexport type { Goal, GoalMatch, TrackerGoal } from './goals/types'\nexport { trackServerEvent } from './native/ingest/serverTrack'\nexport type { QueryError, QueryErrorCode } from './query/errors'\nexport type {\n\tQueryErrorResponse,\n\tQueryResponse,\n\tQuerySourceRef,\n\tSerializedAnalyticsQuery,\n} from './query/response'\nexport type { TimeframePreset } from './timeframe/presets'\nexport type { CustomWidgetDef } from './widgets/customWidget'\nexport { analyticsDefaultWidgets } from './widgets/defaults'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,MAAa,YAAY,aAAqC;CAC7D,MAAM;CACN,QAAQ,OAAO,EAAE,QAAQ,SAAS,UAAU,GAAG,cAA+B;EAC7E,IAAI,QAAQ,aAAa,MACxB,OAAO;EAER,MAAM,WAAW,eAAe,OAAO;EAIvC,MAAM,mBACL,SAAS,UAAU,WAAW,WAAW,QAAQ,SAAS,UAAU,OAAO;EAC5E,MAAM,gBAAgB,OAAO,OAAO,WAAW;EAC/C,qBAAqB,QAAQ,QAAQ,YAAY;EACjD,MAAM,WAAW,eAAe,SAAS,UAAU,SAAS,cAAc;EAC1E,MAAM,eAAe;GAAE,UAAU,SAAS;GAAU,WAAW,SAAS;EAAe;EACvF,IAAI,kBAAkB,uBAAuB,QAAQ;EACrD,IAAI,4BAA4B,CAAC;EACjC,MAAM,mBAAmB,SAAS,UAAU;EAC5C,IAAI,kBACH,kBAAkB,OAAO,SACxB,kBACC,cACA,MAAM,iBAAiB;GAAE,SAAS,KAAK;GAAS,KAAK,KAAK;GAAK,OAAO,KAAK;EAAM,CAAC,CACnF;OACK,IAAI,SAAS,UAAU,WAAW,SAAS;GACjD,MAAM,SAAS,6BAA6B;IAC3C,MAAM;IACN,QAAQ,0BACP,SAAS,UAAU,WAAW,MAC9B,SAAS,UAAU,WAAW,UAC/B;GACD,CAAC;GACD,kBAAkB,OAAO;GACzB,sBAAsB,OAAO;EAC9B;EACA,MAAM,eAAe,OAAO,QAAwB,SAAS,cAAc,EAAE,IAAI,CAAC;EAClF,IAAI,SAAS,UAAU,WAAW,SAAS;GAC1C,MAAM,EAAE,gBAAgB,8BAA8B,MAAM,OAC3D,+BACC,OAAO,QAAiB;IACzB,IAAI,sBAAsB,GAAG,GAC5B,MAAM,IAAI,MACT,2GACD;IAED,MAAM;GACP,CAAC;GACD,MA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C,MAAM,EAAE,0BAA0B,MAAM,OAAO;IAC/C,MAAM,sBAAsB,SAAS,SAAS,UAAU,WAAW,YAAY,IAAI;GACpF;GACA,MAAM,SAAS,aAAa;IAC3B,OAAO,aAAa,QAAQ,EAAE;IAC9B,OAAO,EAAE,aAAa,EAAE;IACxB,KAAK,SAAS,MAAM;IACpB,WAAW,SAAS,MAAM;IAC1B,UAAU,KAAK,cAAc;KAC5B,QAAQ,QAAQ,KAAK,uCAAuC,UAAU,KAAK,OAAO,GAAG,GAAG;IACzF;GACD,CAAC;GACD,WAAW,SAAS;IACnB;IACA;IACA;IACA;IACA,mBAAmB,SAAS;IAC5B,cAAc,SAAS,QAAQ;IAC/B,cAAc,SAAS,QAAQ;IAC/B,cAAc,SAAS,QAAQ;IAC/B,YAAY,SAAS,QAAQ;IAC7B,aAAa,SAAS,QAAQ;IAC9B,OAAO,SAAS;IAChB,cAAc,cAAc;IAC5B,sBAAsB,cAAc;IACpC,GAAI,SAAS,gBAAgB,UAC1B,EAAE,qBAAqB,SAAS,gBAAgB,KAAK,IACrD,CAAC;IACJ,YAAY,SAAS,SAAS,MAAM,MAAM,EAAE,MAAM,GAAG,QAAQ;IAC7D,QAAQ,OAAO,SAAS,iBAAiB,SAAS,OAAO,IAAI;IAC7D,QAAQ,SAAS;IACjB,kBAAkB,IAAI,IAAI,SAAS,SAAS,KAAK,MAAM,EAAE,EAAE,CAAC;IAC5D,cAAc,SAAS,OAAO;IAC9B,YAAY,SAAS,OAAO;IAC5B,UAAU,SAAS;IACnB;IACA,KAAK,SAAS,MAAM;IACpB,YAAY,SAAS,QAAQ;GAC9B,CAAC;GACD,MAAM,aAAa,OAAO;EAC3B;EACA,OAAO;CACR;AACD,CAAC"}
|
|
@@ -1,15 +1,23 @@
|
|
|
1
1
|
//#region src/native/ingest/device.ts
|
|
2
2
|
/**
|
|
3
|
-
*
|
|
4
|
-
*
|
|
3
|
+
* The user agent server-side tracking stamps when the event has no browser request behind
|
|
4
|
+
* it. There is no device to report, so events carrying it abstain from the device breakdown
|
|
5
|
+
* rather than piling into `desktop` and skewing it.
|
|
6
|
+
*/
|
|
7
|
+
const SERVER_USER_AGENT = "analytics-server";
|
|
8
|
+
/**
|
|
9
|
+
* Coarse device class from a user-agent string, or undefined when the agent is not a device
|
|
10
|
+
* at all. Tablets are checked before phones because an Android tablet UA lacks the `Mobile`
|
|
11
|
+
* token an Android phone carries.
|
|
5
12
|
*/
|
|
6
13
|
const classifyDevice = (ua) => {
|
|
14
|
+
if (ua === "analytics-server") return;
|
|
7
15
|
const s = ua.toLowerCase();
|
|
8
16
|
if (/ipad|tablet|playbook|silk|kindle/.test(s) || /android/.test(s) && !/mobi/.test(s)) return "tablet";
|
|
9
17
|
if (/mobi|iphone|ipod|android|blackberry|iemobile|opera mini|windows phone/.test(s)) return "mobile";
|
|
10
18
|
return "desktop";
|
|
11
19
|
};
|
|
12
20
|
//#endregion
|
|
13
|
-
export { classifyDevice };
|
|
21
|
+
export { SERVER_USER_AGENT, classifyDevice };
|
|
14
22
|
|
|
15
23
|
//# sourceMappingURL=device.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"device.js","names":[],"sources":["../../../src/native/ingest/device.ts"],"sourcesContent":["export type DeviceType = 'desktop' | 'mobile' | 'tablet'\n\n/**\n * Coarse device class from a user-agent string. Tablets are checked before phones
|
|
1
|
+
{"version":3,"file":"device.js","names":[],"sources":["../../../src/native/ingest/device.ts"],"sourcesContent":["export type DeviceType = 'desktop' | 'mobile' | 'tablet'\n\n/**\n * The user agent server-side tracking stamps when the event has no browser request behind\n * it. There is no device to report, so events carrying it abstain from the device breakdown\n * rather than piling into `desktop` and skewing it.\n */\nexport const SERVER_USER_AGENT = 'analytics-server'\n\n/**\n * Coarse device class from a user-agent string, or undefined when the agent is not a device\n * at all. Tablets are checked before phones because an Android tablet UA lacks the `Mobile`\n * token an Android phone carries.\n */\nexport const classifyDevice = (ua: string): DeviceType | undefined => {\n\tif (ua === SERVER_USER_AGENT) {\n\t\treturn undefined\n\t}\n\tconst s = ua.toLowerCase()\n\tif (/ipad|tablet|playbook|silk|kindle/.test(s) || (/android/.test(s) && !/mobi/.test(s))) {\n\t\treturn 'tablet'\n\t}\n\tif (/mobi|iphone|ipod|android|blackberry|iemobile|opera mini|windows phone/.test(s)) {\n\t\treturn 'mobile'\n\t}\n\treturn 'desktop'\n}\n"],"mappings":";;;;;;AAOA,MAAa,oBAAoB;;;;;;AAOjC,MAAa,kBAAkB,OAAuC;CACrE,IAAI,OAAA,oBACH;CAED,MAAM,IAAI,GAAG,YAAY;CACzB,IAAI,mCAAmC,KAAK,CAAC,KAAM,UAAU,KAAK,CAAC,KAAK,CAAC,OAAO,KAAK,CAAC,GACrF,OAAO;CAER,IAAI,wEAAwE,KAAK,CAAC,GACjF,OAAO;CAER,OAAO;AACR"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import { PayloadRequest } from "payload";
|
|
@@ -2,12 +2,8 @@ import { readCappedBody } from "../../capture/requestBody.js";
|
|
|
2
2
|
import { flushBatch } from "./flushBatch.js";
|
|
3
3
|
import { normalizeEvent } from "./normalizeEvent.js";
|
|
4
4
|
import { dailySalt } from "./salt.js";
|
|
5
|
+
import { validateRawEvent } from "./validate.js";
|
|
5
6
|
//#region src/native/ingest/endpoint.ts
|
|
6
|
-
const TYPES = new Set([
|
|
7
|
-
"pageview",
|
|
8
|
-
"event",
|
|
9
|
-
"goal"
|
|
10
|
-
]);
|
|
11
7
|
/** One event, not a session replay: far above any legitimate payload, far below a DoS. */
|
|
12
8
|
const MAX_INGEST_BODY_BYTES = 64 * 1024;
|
|
13
9
|
/**
|
|
@@ -23,23 +19,12 @@ const parseBody = (bytes) => {
|
|
|
23
19
|
return;
|
|
24
20
|
}
|
|
25
21
|
};
|
|
26
|
-
/**
|
|
27
|
-
* An event is rejected only on its required fields: a known `type`, a `path`, a `hostname`,
|
|
28
|
-
* and a `name` (the event name, or the goal slug on a `goal`) for everything but a pageview.
|
|
29
|
-
* Optional fields are sanitized in `normalizeEvent` and dropped when malformed, so one bad
|
|
30
|
-
* attribute costs an attribute rather than the whole event.
|
|
31
|
-
*/
|
|
32
|
-
const nonEmptyString = (value) => typeof value === "string" && value.length > 0;
|
|
33
|
-
const isValid = (raw) => {
|
|
34
|
-
if (!raw || !TYPES.has(raw.type) || !nonEmptyString(raw.path) || !nonEmptyString(raw.hostname)) return false;
|
|
35
|
-
return raw.type === "pageview" || nonEmptyString(raw.name);
|
|
36
|
-
};
|
|
37
22
|
const makeIngestHandler = (geoResolver, getBuffer = () => null, resolvers = {}) => async (req) => {
|
|
38
23
|
const { scope: resolveScope, timezone: resolveTimezone, goals: resolveGoals } = resolvers;
|
|
39
24
|
const read = await readCappedBody(req, MAX_INGEST_BODY_BYTES);
|
|
40
25
|
if (!read.ok) return Response.json({ error: read.reason === "too-large" ? "payload too large" : "invalid payload" }, { status: read.reason === "too-large" ? 413 : 400 });
|
|
41
26
|
const raw = parseBody(read.body);
|
|
42
|
-
if (!
|
|
27
|
+
if (!validateRawEvent(raw)) return Response.json({ error: "invalid payload" }, { status: 400 });
|
|
43
28
|
const now = /* @__PURE__ */ new Date();
|
|
44
29
|
const salt = await dailySalt(req.payload, now);
|
|
45
30
|
const scope = resolveScope ? await resolveScope(req) ?? "" : void 0;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"endpoint.js","names":[],"sources":["../../../src/native/ingest/endpoint.ts"],"sourcesContent":["import type { PayloadHandler, PayloadRequest } from 'payload'\nimport { readCappedBody } from '../../capture/requestBody'\nimport type { Goal } from '../../goals/types'\nimport type { GeoResolver } from '../geo/geoResolver'\nimport { flushBatch } from './flushBatch'\nimport {
|
|
1
|
+
{"version":3,"file":"endpoint.js","names":[],"sources":["../../../src/native/ingest/endpoint.ts"],"sourcesContent":["import type { PayloadHandler, PayloadRequest } from 'payload'\nimport { readCappedBody } from '../../capture/requestBody'\nimport type { Goal } from '../../goals/types'\nimport type { GeoResolver } from '../geo/geoResolver'\nimport { flushBatch } from './flushBatch'\nimport { normalizeEvent, type RawEventInput, type StoredEvent } from './normalizeEvent'\nimport { dailySalt } from './salt'\nimport { validateRawEvent } from './validate'\nimport type { WriteBuffer } from './writeBuffer'\n\nexport interface IngestResolvers {\n\tscope?: (req: PayloadRequest) => Promise<string | null>\n\ttimezone?: (req: PayloadRequest, scope?: string | null) => Promise<string>\n\tgoals?: (req: PayloadRequest, scope?: string | null) => Promise<Goal[]>\n}\n\n/** One event, not a session replay: far above any legitimate payload, far below a DoS. */\nexport const MAX_INGEST_BODY_BYTES = 64 * 1024\n\n/**\n * Parses the buffered body, answering undefined for anything the validator could not judge:\n * a garbage POST is a 400 like any other bad payload rather than a thrown parse error that\n * escapes into Payload's routeError as a logged 500.\n */\nconst parseBody = (bytes: ArrayBuffer): RawEventInput | undefined => {\n\ttry {\n\t\tconst parsed: unknown = JSON.parse(new TextDecoder().decode(bytes))\n\t\treturn typeof parsed === 'object' && parsed !== null ? (parsed as RawEventInput) : undefined\n\t} catch {\n\t\treturn undefined\n\t}\n}\n\nexport const makeIngestHandler =\n\t(\n\t\tgeoResolver: GeoResolver,\n\t\tgetBuffer: () => WriteBuffer<StoredEvent> | null = () => null,\n\t\tresolvers: IngestResolvers = {}\n\t): PayloadHandler =>\n\tasync (req) => {\n\t\tconst { scope: resolveScope, timezone: resolveTimezone, goals: resolveGoals } = resolvers\n\t\t// Read like the capture proxy does, and for the same reasons: this is a public,\n\t\t// unauthenticated path, so the body is capped before it is buffered and a body that\n\t\t// dies in transit (a beacon from an unloading tab) answers 400 rather than throwing.\n\t\tconst read = await readCappedBody(req, MAX_INGEST_BODY_BYTES)\n\t\tif (!read.ok) {\n\t\t\treturn Response.json(\n\t\t\t\t{ error: read.reason === 'too-large' ? 'payload too large' : 'invalid payload' },\n\t\t\t\t{ status: read.reason === 'too-large' ? 413 : 400 }\n\t\t\t)\n\t\t}\n\t\tconst raw = parseBody(read.body)\n\t\tif (!validateRawEvent(raw)) {\n\t\t\treturn Response.json({ error: 'invalid payload' }, { status: 400 })\n\t\t}\n\t\tconst now = new Date()\n\t\tconst salt = await dailySalt(req.payload, now)\n\t\tconst scope = resolveScope ? ((await resolveScope(req)) ?? '') : undefined\n\t\tconst timezone = resolveTimezone ? await resolveTimezone(req, scope ?? null) : undefined\n\t\t// Goals resolve under the same scope the event is stamped with, so a tenant's event\n\t\t// can only ever complete that tenant's goals.\n\t\tconst goals = resolveGoals ? await resolveGoals(req, scope ?? null) : undefined\n\t\tconst event = await normalizeEvent({\n\t\t\traw,\n\t\t\theaders: req.headers,\n\t\t\tgeoResolver,\n\t\t\tsalt,\n\t\t\tnow,\n\t\t\tscope,\n\t\t\ttimezone,\n\t\t\tgoals,\n\t\t})\n\t\tconst buffer = getBuffer()\n\t\tif (buffer) {\n\t\t\tbuffer.add(event)\n\t\t} else {\n\t\t\tawait flushBatch(req.payload, [event])\n\t\t}\n\t\treturn Response.json({ ok: true }, { status: 202 })\n\t}\n"],"mappings":";;;;;;;AAiBA,MAAa,wBAAwB,KAAK;;;;;;AAO1C,MAAM,aAAa,UAAkD;CACpE,IAAI;EACH,MAAM,SAAkB,KAAK,MAAM,IAAI,YAAY,EAAE,OAAO,KAAK,CAAC;EAClE,OAAO,OAAO,WAAW,YAAY,WAAW,OAAQ,SAA2B,KAAA;CACpF,QAAQ;EACP;CACD;AACD;AAEA,MAAa,qBAEX,aACA,kBAAyD,MACzD,YAA6B,CAAC,MAE/B,OAAO,QAAQ;CACd,MAAM,EAAE,OAAO,cAAc,UAAU,iBAAiB,OAAO,iBAAiB;CAIhF,MAAM,OAAO,MAAM,eAAe,KAAK,qBAAqB;CAC5D,IAAI,CAAC,KAAK,IACT,OAAO,SAAS,KACf,EAAE,OAAO,KAAK,WAAW,cAAc,sBAAsB,kBAAkB,GAC/E,EAAE,QAAQ,KAAK,WAAW,cAAc,MAAM,IAAI,CACnD;CAED,MAAM,MAAM,UAAU,KAAK,IAAI;CAC/B,IAAI,CAAC,iBAAiB,GAAG,GACxB,OAAO,SAAS,KAAK,EAAE,OAAO,kBAAkB,GAAG,EAAE,QAAQ,IAAI,CAAC;CAEnE,MAAM,sBAAM,IAAI,KAAK;CACrB,MAAM,OAAO,MAAM,UAAU,IAAI,SAAS,GAAG;CAC7C,MAAM,QAAQ,eAAiB,MAAM,aAAa,GAAG,KAAM,KAAM,KAAA;CACjE,MAAM,WAAW,kBAAkB,MAAM,gBAAgB,KAAK,SAAS,IAAI,IAAI,KAAA;CAG/E,MAAM,QAAQ,eAAe,MAAM,aAAa,KAAK,SAAS,IAAI,IAAI,KAAA;CACtE,MAAM,QAAQ,MAAM,eAAe;EAClC;EACA,SAAS,IAAI;EACb;EACA;EACA;EACA;EACA;EACA;CACD,CAAC;CACD,MAAM,SAAS,UAAU;CACzB,IAAI,QACH,OAAO,IAAI,KAAK;MAEhB,MAAM,WAAW,IAAI,SAAS,CAAC,KAAK,CAAC;CAEtC,OAAO,SAAS,KAAK,EAAE,IAAI,KAAK,GAAG,EAAE,QAAQ,IAAI,CAAC;AACnD"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
//#region src/native/ingest/normalizeEvent.d.ts
|
|
2
|
+
type EventType = 'pageview' | 'event' | 'goal';
|
|
3
|
+
interface RawEventInput {
|
|
4
|
+
type: EventType;
|
|
5
|
+
/** Event name, or the goal slug on a `goal`. Absent on pageviews. */
|
|
6
|
+
name?: string;
|
|
7
|
+
path: string;
|
|
8
|
+
hostname: string;
|
|
9
|
+
referrer?: string;
|
|
10
|
+
durationMs?: number;
|
|
11
|
+
props?: Record<string, unknown>;
|
|
12
|
+
/** Revenue for a goal completion, in `currency`. */
|
|
13
|
+
value?: number;
|
|
14
|
+
currency?: string;
|
|
15
|
+
/** Max scroll depth reached on a pageview, 0-100. */
|
|
16
|
+
scrollDepth?: number;
|
|
17
|
+
}
|
|
18
|
+
//#endregion
|
|
19
|
+
export { RawEventInput };
|
|
20
|
+
//# sourceMappingURL=normalizeEvent.d.ts.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { clientIpFromHeaders } from "./clientIp.js";
|
|
2
|
-
import { matchGoals } from "../../goals/match.js";
|
|
3
2
|
import { classifyDevice } from "./device.js";
|
|
3
|
+
import { matchGoals } from "../../goals/match.js";
|
|
4
4
|
import { deriveSource } from "./source.js";
|
|
5
5
|
import { dailyVisitorHash, deriveSessionId } from "./visitorHash.js";
|
|
6
6
|
//#region src/native/ingest/normalizeEvent.ts
|
|
@@ -69,6 +69,7 @@ async function normalizeEvent({ raw, headers, geoResolver, salt, now, scope, tim
|
|
|
69
69
|
const scrollDepth = depth(raw.scrollDepth);
|
|
70
70
|
const durationMs = duration(raw.durationMs);
|
|
71
71
|
const name = eventName(raw.name);
|
|
72
|
+
const device = classifyDevice(ua);
|
|
72
73
|
const completions = goals?.length ? matchGoals({
|
|
73
74
|
type: raw.type,
|
|
74
75
|
name,
|
|
@@ -83,7 +84,7 @@ async function normalizeEvent({ raw, headers, geoResolver, salt, now, scope, tim
|
|
|
83
84
|
path,
|
|
84
85
|
hostname,
|
|
85
86
|
referrer: raw.referrer,
|
|
86
|
-
device:
|
|
87
|
+
...device ? { device } : {},
|
|
87
88
|
source: deriveSource(raw.referrer, hostname),
|
|
88
89
|
country: geo.country,
|
|
89
90
|
region: geo.region,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"normalizeEvent.js","names":[],"sources":["../../../src/native/ingest/normalizeEvent.ts"],"sourcesContent":["import { type GoalCompletion, matchGoals } from '../../goals/match'\nimport type { Goal } from '../../goals/types'\nimport type { GeoResolver } from '../geo/geoResolver'\nimport { clientIpFromHeaders } from './clientIp'\nimport { classifyDevice, type DeviceType } from './device'\nimport { deriveSource } from './source'\nimport { dailyVisitorHash, deriveSessionId } from './visitorHash'\n\nexport type EventType = 'pageview' | 'event' | 'goal'\n\nexport interface RawEventInput {\n\ttype: EventType\n\t/** Event name, or the goal slug on a `goal`. Absent on pageviews. */\n\tname?: string\n\tpath: string\n\thostname: string\n\treferrer?: string\n\tdurationMs?: number\n\tprops?: Record<string, unknown>\n\t/** Revenue for a goal completion, in `currency`. */\n\tvalue?: number\n\tcurrency?: string\n\t/** Max scroll depth reached on a pageview, 0-100. */\n\tscrollDepth?: number\n}\n\nexport interface StoredEvent {\n\ttimestamp: Date\n\ttype: EventType\n\tname?: string\n\tpath: string\n\thostname: string\n\treferrer?: string\n\tdevice?: DeviceType\n\tsource?: string\n\tcountry?: string\n\tregion?: string\n\tcity?: string\n\tvisitorHash: string\n\tsessionId: string\n\tdurationMs?: number\n\tprops?: Record<string, unknown>\n\tvalue?: number\n\t/** ISO 4217 code `value` is denominated in. Stored as sent; revenue is never converted. */\n\tcurrency?: string\n\tscrollDepth?: number\n\t/**\n\t * Goals this event completed, resolved against the install's goals at ingest so a later\n\t * goal edit never rewrites history and a raw-event read can re-derive the same numbers\n\t * the rollups hold.\n\t */\n\tgoals?: GoalCompletion[]\n\t/** Set only in scoped installs; '' is the null scope. */\n\tscope?: string\n\t/**\n\t * Reporting timezone the rollup day bucket is computed in. In-memory only: stripped\n\t * before the event row is persisted (day bucketing happens at rollup time). Absent\n\t * means UTC.\n\t */\n\ttimezone?: string\n}\n\nexport interface NormalizeArgs {\n\traw: RawEventInput\n\theaders: Headers\n\tgeoResolver: GeoResolver\n\tsalt: string\n\tnow: Date\n\tscope?: string\n\ttimezone?: string\n\t/** Goals to match this event against; omitted means no goal matching. */\n\tgoals?: Goal[]\n}\n\nconst MAX_PROPS = 20\nconst MAX_KEY_LENGTH = 64\nconst MAX_VALUE_LENGTH = 256\nconst MAX_NAME_LENGTH = 128\nconst MAX_PATH_LENGTH = 512\n/** Longest legal DNS name. */\nconst MAX_HOSTNAME_LENGTH = 253\n/** 24 hours. A longer duration is a broken clock, not a session. */\nconst MAX_DURATION_MS = 86_400_000\nconst CURRENCY = /^[A-Z]{3}$/\n\n/**\n * Optional wire fields are sanitized rather than rejected: a bad `value`, `currency`,\n * `scrollDepth`, `durationMs`, or prop is dropped and the event is still ingested, so one malformed\n * attribute never costs a pageview. Only the required fields (checked in the endpoint)\n * can fail an event.\n */\nconst nonNegative = (value: unknown): number | undefined =>\n\ttypeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined\n\nconst currencyCode = (value: unknown): string | undefined =>\n\ttypeof value === 'string' && CURRENCY.test(value) ? value : undefined\n\n/**\n * Infinity would poison a rollup bucket's average for good, and a string would throw out of\n * the write and take the whole buffered batch with it, so a duration outside the ceiling is\n * dropped like any other malformed attribute.\n */\nconst duration = (value: unknown): number | undefined => {\n\tconst n = nonNegative(value)\n\treturn n === undefined || n > MAX_DURATION_MS ? undefined : n\n}\n\n/** The event name is a rollup bucket key (the `event` dimension), so it is length-capped. */\nconst eventName = (value: unknown): string | undefined =>\n\ttypeof value === 'string' ? value.slice(0, MAX_NAME_LENGTH) : undefined\n\nconst depth = (value: unknown): number | undefined => {\n\tconst n = nonNegative(value)\n\treturn n === undefined ? undefined : Math.round(Math.min(n, 100))\n}\n\n/** Flat JSON scalars only: the first 20 short-keyed string/number/boolean entries. */\nconst sanitizeProps = (raw: unknown): Record<string, unknown> | undefined => {\n\tif (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {\n\t\treturn undefined\n\t}\n\tconst out: Record<string, unknown> = {}\n\tlet kept = 0\n\tfor (const [key, value] of Object.entries(raw)) {\n\t\tif (kept >= MAX_PROPS || key.length > MAX_KEY_LENGTH) {\n\t\t\tcontinue\n\t\t}\n\t\tif (typeof value === 'string') {\n\t\t\tout[key] = value.slice(0, MAX_VALUE_LENGTH)\n\t\t} else if (\n\t\t\ttypeof value === 'boolean' ||\n\t\t\t(typeof value === 'number' && Number.isFinite(value))\n\t\t) {\n\t\t\tout[key] = value\n\t\t} else {\n\t\t\tcontinue\n\t\t}\n\t\tkept++\n\t}\n\treturn kept > 0 ? out : undefined\n}\n\nexport async function normalizeEvent({\n\traw,\n\theaders,\n\tgeoResolver,\n\tsalt,\n\tnow,\n\tscope,\n\ttimezone,\n\tgoals,\n}: NormalizeArgs): Promise<StoredEvent> {\n\tconst geo = await geoResolver(headers)\n\tconst ip = clientIpFromHeaders(headers) ?? ''\n\tconst ua = headers.get('user-agent') ?? ''\n\t// Both are unique-index bucket keys on the rollup and seen rows, so they are capped\n\t// before anything derives from them: an uncapped path exceeds Mongo's index key limit.\n\tconst path = raw.path.slice(0, MAX_PATH_LENGTH)\n\tconst hostname = raw.hostname.slice(0, MAX_HOSTNAME_LENGTH)\n\tconst visitorHash = dailyVisitorHash({ ip, ua, site: hostname, salt })\n\tconst hourBucket = now.toISOString().slice(0, 13)\n\tconst props = sanitizeProps(raw.props)\n\tconst value = nonNegative(raw.value)\n\tconst scrollDepth = depth(raw.scrollDepth)\n\tconst durationMs = duration(raw.durationMs)\n\tconst name = eventName(raw.name)\n\t// Match on the sanitized fields so a rejected value never reaches a goal's revenue.\n\tconst completions = goals?.length\n\t\t? matchGoals({ type: raw.type, name, path, props, value }, goals)\n\t\t: []\n\treturn {\n\t\ttimestamp: now,\n\t\ttype: raw.type,\n\t\tname,\n\t\tpath,\n\t\thostname,\n\t\treferrer: raw.referrer,\n\t\
|
|
1
|
+
{"version":3,"file":"normalizeEvent.js","names":[],"sources":["../../../src/native/ingest/normalizeEvent.ts"],"sourcesContent":["import { type GoalCompletion, matchGoals } from '../../goals/match'\nimport type { Goal } from '../../goals/types'\nimport type { GeoResolver } from '../geo/geoResolver'\nimport { clientIpFromHeaders } from './clientIp'\nimport { classifyDevice, type DeviceType } from './device'\nimport { deriveSource } from './source'\nimport { dailyVisitorHash, deriveSessionId } from './visitorHash'\n\nexport type EventType = 'pageview' | 'event' | 'goal'\n\nexport interface RawEventInput {\n\ttype: EventType\n\t/** Event name, or the goal slug on a `goal`. Absent on pageviews. */\n\tname?: string\n\tpath: string\n\thostname: string\n\treferrer?: string\n\tdurationMs?: number\n\tprops?: Record<string, unknown>\n\t/** Revenue for a goal completion, in `currency`. */\n\tvalue?: number\n\tcurrency?: string\n\t/** Max scroll depth reached on a pageview, 0-100. */\n\tscrollDepth?: number\n}\n\nexport interface StoredEvent {\n\ttimestamp: Date\n\ttype: EventType\n\tname?: string\n\tpath: string\n\thostname: string\n\treferrer?: string\n\tdevice?: DeviceType\n\tsource?: string\n\tcountry?: string\n\tregion?: string\n\tcity?: string\n\tvisitorHash: string\n\tsessionId: string\n\tdurationMs?: number\n\tprops?: Record<string, unknown>\n\tvalue?: number\n\t/** ISO 4217 code `value` is denominated in. Stored as sent; revenue is never converted. */\n\tcurrency?: string\n\tscrollDepth?: number\n\t/**\n\t * Goals this event completed, resolved against the install's goals at ingest so a later\n\t * goal edit never rewrites history and a raw-event read can re-derive the same numbers\n\t * the rollups hold.\n\t */\n\tgoals?: GoalCompletion[]\n\t/** Set only in scoped installs; '' is the null scope. */\n\tscope?: string\n\t/**\n\t * Reporting timezone the rollup day bucket is computed in. In-memory only: stripped\n\t * before the event row is persisted (day bucketing happens at rollup time). Absent\n\t * means UTC.\n\t */\n\ttimezone?: string\n}\n\nexport interface NormalizeArgs {\n\traw: RawEventInput\n\theaders: Headers\n\tgeoResolver: GeoResolver\n\tsalt: string\n\tnow: Date\n\tscope?: string\n\ttimezone?: string\n\t/** Goals to match this event against; omitted means no goal matching. */\n\tgoals?: Goal[]\n}\n\nconst MAX_PROPS = 20\nconst MAX_KEY_LENGTH = 64\nconst MAX_VALUE_LENGTH = 256\nconst MAX_NAME_LENGTH = 128\nconst MAX_PATH_LENGTH = 512\n/** Longest legal DNS name. */\nconst MAX_HOSTNAME_LENGTH = 253\n/** 24 hours. A longer duration is a broken clock, not a session. */\nconst MAX_DURATION_MS = 86_400_000\nconst CURRENCY = /^[A-Z]{3}$/\n\n/**\n * Optional wire fields are sanitized rather than rejected: a bad `value`, `currency`,\n * `scrollDepth`, `durationMs`, or prop is dropped and the event is still ingested, so one malformed\n * attribute never costs a pageview. Only the required fields (checked in the endpoint)\n * can fail an event.\n */\nconst nonNegative = (value: unknown): number | undefined =>\n\ttypeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined\n\nconst currencyCode = (value: unknown): string | undefined =>\n\ttypeof value === 'string' && CURRENCY.test(value) ? value : undefined\n\n/**\n * Infinity would poison a rollup bucket's average for good, and a string would throw out of\n * the write and take the whole buffered batch with it, so a duration outside the ceiling is\n * dropped like any other malformed attribute.\n */\nconst duration = (value: unknown): number | undefined => {\n\tconst n = nonNegative(value)\n\treturn n === undefined || n > MAX_DURATION_MS ? undefined : n\n}\n\n/** The event name is a rollup bucket key (the `event` dimension), so it is length-capped. */\nconst eventName = (value: unknown): string | undefined =>\n\ttypeof value === 'string' ? value.slice(0, MAX_NAME_LENGTH) : undefined\n\nconst depth = (value: unknown): number | undefined => {\n\tconst n = nonNegative(value)\n\treturn n === undefined ? undefined : Math.round(Math.min(n, 100))\n}\n\n/** Flat JSON scalars only: the first 20 short-keyed string/number/boolean entries. */\nconst sanitizeProps = (raw: unknown): Record<string, unknown> | undefined => {\n\tif (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {\n\t\treturn undefined\n\t}\n\tconst out: Record<string, unknown> = {}\n\tlet kept = 0\n\tfor (const [key, value] of Object.entries(raw)) {\n\t\tif (kept >= MAX_PROPS || key.length > MAX_KEY_LENGTH) {\n\t\t\tcontinue\n\t\t}\n\t\tif (typeof value === 'string') {\n\t\t\tout[key] = value.slice(0, MAX_VALUE_LENGTH)\n\t\t} else if (\n\t\t\ttypeof value === 'boolean' ||\n\t\t\t(typeof value === 'number' && Number.isFinite(value))\n\t\t) {\n\t\t\tout[key] = value\n\t\t} else {\n\t\t\tcontinue\n\t\t}\n\t\tkept++\n\t}\n\treturn kept > 0 ? out : undefined\n}\n\nexport async function normalizeEvent({\n\traw,\n\theaders,\n\tgeoResolver,\n\tsalt,\n\tnow,\n\tscope,\n\ttimezone,\n\tgoals,\n}: NormalizeArgs): Promise<StoredEvent> {\n\tconst geo = await geoResolver(headers)\n\tconst ip = clientIpFromHeaders(headers) ?? ''\n\tconst ua = headers.get('user-agent') ?? ''\n\t// Both are unique-index bucket keys on the rollup and seen rows, so they are capped\n\t// before anything derives from them: an uncapped path exceeds Mongo's index key limit.\n\tconst path = raw.path.slice(0, MAX_PATH_LENGTH)\n\tconst hostname = raw.hostname.slice(0, MAX_HOSTNAME_LENGTH)\n\tconst visitorHash = dailyVisitorHash({ ip, ua, site: hostname, salt })\n\tconst hourBucket = now.toISOString().slice(0, 13)\n\tconst props = sanitizeProps(raw.props)\n\tconst value = nonNegative(raw.value)\n\tconst scrollDepth = depth(raw.scrollDepth)\n\tconst durationMs = duration(raw.durationMs)\n\tconst name = eventName(raw.name)\n\tconst device = classifyDevice(ua)\n\t// Match on the sanitized fields so a rejected value never reaches a goal's revenue.\n\tconst completions = goals?.length\n\t\t? matchGoals({ type: raw.type, name, path, props, value }, goals)\n\t\t: []\n\treturn {\n\t\ttimestamp: now,\n\t\ttype: raw.type,\n\t\tname,\n\t\tpath,\n\t\thostname,\n\t\treferrer: raw.referrer,\n\t\t...(device ? { device } : {}),\n\t\tsource: deriveSource(raw.referrer, hostname),\n\t\tcountry: geo.country,\n\t\tregion: geo.region,\n\t\tcity: geo.city,\n\t\tvisitorHash,\n\t\tsessionId: deriveSessionId(visitorHash, hourBucket),\n\t\tprops,\n\t\t...(durationMs !== undefined ? { durationMs } : {}),\n\t\t...(value !== undefined ? { value } : {}),\n\t\t...(currencyCode(raw.currency) !== undefined ? { currency: raw.currency } : {}),\n\t\t...(scrollDepth !== undefined ? { scrollDepth } : {}),\n\t\t...(completions.length > 0 ? { goals: completions } : {}),\n\t\t...(scope !== undefined ? { scope } : {}),\n\t\t...(timezone !== undefined ? { timezone } : {}),\n\t}\n}\n"],"mappings":";;;;;;AA0EA,MAAM,YAAY;AAClB,MAAM,iBAAiB;AACvB,MAAM,mBAAmB;AACzB,MAAM,kBAAkB;AACxB,MAAM,kBAAkB;;AAExB,MAAM,sBAAsB;;AAE5B,MAAM,kBAAkB;AACxB,MAAM,WAAW;;;;;;;AAQjB,MAAM,eAAe,UACpB,OAAO,UAAU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{ Payload } from "payload";
|
|
3
|
+
|
|
4
|
+
//#region src/native/ingest/serverTrack.d.ts
|
|
5
|
+
/**
|
|
6
|
+
* Records an analytics event from server code: a webhook, a job, a server action. The event
|
|
7
|
+
* goes through the same normalization, sanitization and goal matching a browser event does.
|
|
8
|
+
* Pass `opts.req` whenever there is a request behind the event, so it inherits that request's
|
|
9
|
+
* attribution, scope and reporting timezone.
|
|
10
|
+
*
|
|
11
|
+
* `event.scope` overrides the request's scope; it is ignored on an unscoped install and is
|
|
12
|
+
* never checked against the scopes that exist, so the caller owns what it stamps.
|
|
13
|
+
*
|
|
14
|
+
* Needs the native adapter: a provider slot (Plausible, GA4) has no server ingestion seam
|
|
15
|
+
* here yet, so an install without the native adapter throws rather than dropping the event.
|
|
16
|
+
*/
|
|
17
|
+
declare const trackServerEvent: (payload: Payload, event: ServerEventInput, opts?: ServerTrackOptions) => Promise<void>;
|
|
18
|
+
//#endregion
|
|
19
|
+
export { trackServerEvent };
|
|
20
|
+
//# sourceMappingURL=serverTrack.d.ts.map
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { getRuntime } from "../../plugin/runtime.js";
|
|
2
|
+
import { AnalyticsTrackError } from "../../core/serverEvent.js";
|
|
3
|
+
import { SERVER_USER_AGENT } from "./device.js";
|
|
4
|
+
import { flushBatch } from "./flushBatch.js";
|
|
5
|
+
import { normalizeEvent } from "./normalizeEvent.js";
|
|
6
|
+
import { dailySalt } from "./salt.js";
|
|
7
|
+
import { rawEventError } from "./validate.js";
|
|
8
|
+
import { createLocalReq } from "payload";
|
|
9
|
+
//#region src/native/ingest/serverTrack.ts
|
|
10
|
+
/**
|
|
11
|
+
* The originating request's own headers, so a server event attributes exactly like the
|
|
12
|
+
* browser event it stands in for: the platform's geo headers reach the geo resolver and the
|
|
13
|
+
* visitor hashes to the same person. Explicit `ip` / `userAgent` overlay them.
|
|
14
|
+
*
|
|
15
|
+
* With no request and no user agent the synthetic server agent stands in, which hashes every
|
|
16
|
+
* such event in a day to one visitor per site and reports no device at all.
|
|
17
|
+
*/
|
|
18
|
+
const attributionHeaders = (event, req) => {
|
|
19
|
+
const headers = new Headers(req?.headers);
|
|
20
|
+
if (event.ip) headers.set("x-forwarded-for", event.ip);
|
|
21
|
+
if (event.userAgent) headers.set("user-agent", event.userAgent);
|
|
22
|
+
if (!headers.get("user-agent")) headers.set("user-agent", SERVER_USER_AGENT);
|
|
23
|
+
return headers;
|
|
24
|
+
};
|
|
25
|
+
const resolveScope = async (event, opts, resolvers) => {
|
|
26
|
+
if (!resolvers.scope) return;
|
|
27
|
+
if (event.scope !== void 0) return event.scope ?? "";
|
|
28
|
+
if (!opts?.req) return "";
|
|
29
|
+
return await resolvers.scope(opts.req) ?? "";
|
|
30
|
+
};
|
|
31
|
+
/**
|
|
32
|
+
* The native adapter's server-side ingestion, exposed as `adapter.ingest.track`. Same
|
|
33
|
+
* normalization, goal matching and write path the HTTP endpoint uses; only attribution and
|
|
34
|
+
* scope resolution differ, since there may be no request behind the event at all.
|
|
35
|
+
*/
|
|
36
|
+
const makeServerTrack = (deps) => async (event, opts) => {
|
|
37
|
+
const payload = deps.getPayload();
|
|
38
|
+
if (!payload) throw new AnalyticsTrackError("analytics: trackServerEvent called before init");
|
|
39
|
+
const invalid = rawEventError(event);
|
|
40
|
+
if (invalid) throw new AnalyticsTrackError(`analytics: trackServerEvent needs a valid "${invalid}"`);
|
|
41
|
+
const resolvers = deps.getResolvers();
|
|
42
|
+
const scope = await resolveScope(event, opts, resolvers);
|
|
43
|
+
let local;
|
|
44
|
+
const requestFor = async () => {
|
|
45
|
+
if (opts?.req) return opts.req;
|
|
46
|
+
local ??= await createLocalReq({}, payload);
|
|
47
|
+
return local;
|
|
48
|
+
};
|
|
49
|
+
const timezone = event.timezone ?? (resolvers.timezone ? await resolvers.timezone(await requestFor(), scope ?? null) : void 0);
|
|
50
|
+
const goals = resolvers.goals ? await resolvers.goals(await requestFor(), scope ?? null) : void 0;
|
|
51
|
+
const now = event.now ?? /* @__PURE__ */ new Date();
|
|
52
|
+
const stored = await normalizeEvent({
|
|
53
|
+
raw: {
|
|
54
|
+
type: event.type,
|
|
55
|
+
name: event.name,
|
|
56
|
+
path: event.path,
|
|
57
|
+
hostname: event.hostname,
|
|
58
|
+
referrer: event.referrer,
|
|
59
|
+
props: event.props,
|
|
60
|
+
value: event.value,
|
|
61
|
+
currency: event.currency
|
|
62
|
+
},
|
|
63
|
+
headers: attributionHeaders(event, opts?.req),
|
|
64
|
+
geoResolver: deps.geoResolver,
|
|
65
|
+
salt: await dailySalt(payload, now),
|
|
66
|
+
now,
|
|
67
|
+
scope,
|
|
68
|
+
timezone,
|
|
69
|
+
goals
|
|
70
|
+
});
|
|
71
|
+
const buffer = deps.getBuffer();
|
|
72
|
+
if (!buffer) {
|
|
73
|
+
await flushBatch(payload, [stored]);
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
buffer.add(stored);
|
|
77
|
+
if (opts?.flush) await buffer.flush();
|
|
78
|
+
};
|
|
79
|
+
/**
|
|
80
|
+
* Records an analytics event from server code: a webhook, a job, a server action. The event
|
|
81
|
+
* goes through the same normalization, sanitization and goal matching a browser event does.
|
|
82
|
+
* Pass `opts.req` whenever there is a request behind the event, so it inherits that request's
|
|
83
|
+
* attribution, scope and reporting timezone.
|
|
84
|
+
*
|
|
85
|
+
* `event.scope` overrides the request's scope; it is ignored on an unscoped install and is
|
|
86
|
+
* never checked against the scopes that exist, so the caller owns what it stamps.
|
|
87
|
+
*
|
|
88
|
+
* Needs the native adapter: a provider slot (Plausible, GA4) has no server ingestion seam
|
|
89
|
+
* here yet, so an install without the native adapter throws rather than dropping the event.
|
|
90
|
+
*/
|
|
91
|
+
const trackServerEvent = async (payload, event, opts) => {
|
|
92
|
+
const track = getRuntime(payload)?.registry.all().find((adapter) => adapter.ingest?.track)?.ingest?.track;
|
|
93
|
+
if (!track) throw new AnalyticsTrackError("analytics: trackServerEvent needs the native adapter; provider-slot server tracking is not supported yet");
|
|
94
|
+
await track(event, opts);
|
|
95
|
+
};
|
|
96
|
+
//#endregion
|
|
97
|
+
export { makeServerTrack, trackServerEvent };
|
|
98
|
+
|
|
99
|
+
//# sourceMappingURL=serverTrack.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"serverTrack.js","names":[],"sources":["../../../src/native/ingest/serverTrack.ts"],"sourcesContent":["import { createLocalReq, type Payload, type PayloadRequest } from 'payload'\nimport {\n\tAnalyticsTrackError,\n\ttype ServerEventInput,\n\ttype ServerTrack,\n\ttype ServerTrackOptions,\n} from '../../core/serverEvent'\nimport { getRuntime } from '../../plugin/runtime'\nimport type { GeoResolver } from '../geo/geoResolver'\nimport { SERVER_USER_AGENT } from './device'\nimport type { IngestResolvers } from './endpoint'\nimport { flushBatch } from './flushBatch'\nimport { normalizeEvent, type StoredEvent } from './normalizeEvent'\nimport { dailySalt } from './salt'\nimport { rawEventError } from './validate'\nimport type { WriteBuffer } from './writeBuffer'\n\nexport interface ServerTrackDeps {\n\t/** Null until the adapter's onInit has run. */\n\tgetPayload: () => Payload | null\n\tgeoResolver: GeoResolver\n\tgetBuffer: () => WriteBuffer<StoredEvent> | null\n\t/** Read late: the register context that carries them arrives after the adapter is built. */\n\tgetResolvers: () => IngestResolvers\n}\n\n/**\n * The originating request's own headers, so a server event attributes exactly like the\n * browser event it stands in for: the platform's geo headers reach the geo resolver and the\n * visitor hashes to the same person. Explicit `ip` / `userAgent` overlay them.\n *\n * With no request and no user agent the synthetic server agent stands in, which hashes every\n * such event in a day to one visitor per site and reports no device at all.\n */\nconst attributionHeaders = (event: ServerEventInput, req?: PayloadRequest): Headers => {\n\tconst headers = new Headers(req?.headers)\n\tif (event.ip) {\n\t\theaders.set('x-forwarded-for', event.ip)\n\t}\n\tif (event.userAgent) {\n\t\theaders.set('user-agent', event.userAgent)\n\t}\n\tif (!headers.get('user-agent')) {\n\t\theaders.set('user-agent', SERVER_USER_AGENT)\n\t}\n\treturn headers\n}\n\nconst resolveScope = async (\n\tevent: ServerEventInput,\n\topts: ServerTrackOptions | undefined,\n\tresolvers: IngestResolvers\n): Promise<string | undefined> => {\n\t// An unscoped install has no scope resolver and no scope field on its rows, so a scope\n\t// declared by the caller is ignored exactly as the endpoint ignores one on the wire.\n\tif (!resolvers.scope) {\n\t\treturn undefined\n\t}\n\tif (event.scope !== undefined) {\n\t\treturn event.scope ?? ''\n\t}\n\tif (!opts?.req) {\n\t\treturn ''\n\t}\n\treturn (await resolvers.scope(opts.req)) ?? ''\n}\n\n/**\n * The native adapter's server-side ingestion, exposed as `adapter.ingest.track`. Same\n * normalization, goal matching and write path the HTTP endpoint uses; only attribution and\n * scope resolution differ, since there may be no request behind the event at all.\n */\nexport const makeServerTrack =\n\t(deps: ServerTrackDeps): ServerTrack =>\n\tasync (event, opts) => {\n\t\tconst payload = deps.getPayload()\n\t\tif (!payload) {\n\t\t\tthrow new AnalyticsTrackError('analytics: trackServerEvent called before init')\n\t\t}\n\t\tconst invalid = rawEventError(event)\n\t\tif (invalid) {\n\t\t\tthrow new AnalyticsTrackError(`analytics: trackServerEvent needs a valid \"${invalid}\"`)\n\t\t}\n\t\tconst resolvers = deps.getResolvers()\n\t\tconst scope = await resolveScope(event, opts, resolvers)\n\t\t// createLocalReq mutates the request it is given, so a caller's own req is passed\n\t\t// through untouched and a fresh one is built only when a resolver needs it.\n\t\tlet local: PayloadRequest | undefined\n\t\tconst requestFor = async (): Promise<PayloadRequest> => {\n\t\t\tif (opts?.req) {\n\t\t\t\treturn opts.req\n\t\t\t}\n\t\t\tlocal ??= await createLocalReq({}, payload)\n\t\t\treturn local\n\t\t}\n\t\tconst timezone =\n\t\t\tevent.timezone ??\n\t\t\t(resolvers.timezone ? await resolvers.timezone(await requestFor(), scope ?? null) : undefined)\n\t\t// Goals resolve under the scope the event is stamped with, so a tenant's server event\n\t\t// can only ever complete that tenant's goals.\n\t\tconst goals = resolvers.goals\n\t\t\t? await resolvers.goals(await requestFor(), scope ?? null)\n\t\t\t: undefined\n\t\tconst now = event.now ?? new Date()\n\t\tconst stored = await normalizeEvent({\n\t\t\traw: {\n\t\t\t\ttype: event.type,\n\t\t\t\tname: event.name,\n\t\t\t\tpath: event.path,\n\t\t\t\thostname: event.hostname,\n\t\t\t\treferrer: event.referrer,\n\t\t\t\tprops: event.props,\n\t\t\t\tvalue: event.value,\n\t\t\t\tcurrency: event.currency,\n\t\t\t},\n\t\t\theaders: attributionHeaders(event, opts?.req),\n\t\t\tgeoResolver: deps.geoResolver,\n\t\t\tsalt: await dailySalt(payload, now),\n\t\t\tnow,\n\t\t\tscope,\n\t\t\ttimezone,\n\t\t\tgoals,\n\t\t})\n\t\tconst buffer = deps.getBuffer()\n\t\tif (!buffer) {\n\t\t\tawait flushBatch(payload, [stored])\n\t\t\treturn\n\t\t}\n\t\tbuffer.add(stored)\n\t\tif (opts?.flush) {\n\t\t\tawait buffer.flush()\n\t\t}\n\t}\n\n/**\n * Records an analytics event from server code: a webhook, a job, a server action. The event\n * goes through the same normalization, sanitization and goal matching a browser event does.\n * Pass `opts.req` whenever there is a request behind the event, so it inherits that request's\n * attribution, scope and reporting timezone.\n *\n * `event.scope` overrides the request's scope; it is ignored on an unscoped install and is\n * never checked against the scopes that exist, so the caller owns what it stamps.\n *\n * Needs the native adapter: a provider slot (Plausible, GA4) has no server ingestion seam\n * here yet, so an install without the native adapter throws rather than dropping the event.\n */\nexport const trackServerEvent = async (\n\tpayload: Payload,\n\tevent: ServerEventInput,\n\topts?: ServerTrackOptions\n): Promise<void> => {\n\tconst track = getRuntime(payload)\n\t\t?.registry.all()\n\t\t.find((adapter) => adapter.ingest?.track)?.ingest?.track\n\tif (!track) {\n\t\tthrow new AnalyticsTrackError(\n\t\t\t'analytics: trackServerEvent needs the native adapter; provider-slot server tracking is not supported yet'\n\t\t)\n\t}\n\tawait track(event, opts)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAkCA,MAAM,sBAAsB,OAAyB,QAAkC;CACtF,MAAM,UAAU,IAAI,QAA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GAChB,OAAO,MAAM;GACb,OAAO,MAAM;GACb,UAAU,MAAM;EACjB;EACA,SAAS,mBAAmB,OAAO,MAAM,GAAG;EAC5C,aAAa,KAAK;EAClB,MAAM,MAAM,UAAU,SAAS,GAAG;EAClC;EACA;EACA;EACA;CACD,CAAC;CACD,MAAM,SAAS,KAAK,UAAU;CAC9B,IAAI,CAAC,QAAQ;EACZ,MAAM,WAAW,SAAS,CAAC,MAAM,CAAC;EAClC;CACD;CACA,OAAO,IAAI,MAAM;CACjB,IAAI,MAAM,OACT,MAAM,OAAO,MAAM;AAErB;;;;;;;;;;;;;AAcD,MAAa,mBAAmB,OAC/B,SACA,OACA,SACmB;CACnB,MAAM,QAAQ,WAAW,OAAO,GAC7B,SAAS,IAAI,EACd,MAAM,YAAY,QAAQ,QAAQ,KAAK,GAAG,QAAQ;CACpD,IAAI,CAAC,OACJ,MAAM,IAAI,oBACT,0GACD;CAED,MAAM,MAAM,OAAO,IAAI;AACxB"}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
//#region src/native/ingest/validate.ts
|
|
2
|
+
const TYPES = new Set([
|
|
3
|
+
"pageview",
|
|
4
|
+
"event",
|
|
5
|
+
"goal"
|
|
6
|
+
]);
|
|
7
|
+
const nonEmptyString = (value) => typeof value === "string" && value.length > 0;
|
|
8
|
+
/**
|
|
9
|
+
* The first required field an event fails on, or undefined when it is valid: a known `type`,
|
|
10
|
+
* a `path`, a `hostname`, and a `name` (the event name, or the goal slug on a `goal`) for
|
|
11
|
+
* everything but a pageview. Optional fields are sanitized in `normalizeEvent` and dropped
|
|
12
|
+
* when malformed, so one bad attribute costs an attribute rather than the whole event.
|
|
13
|
+
*
|
|
14
|
+
* Types are checked rather than truthiness: a non-string path would otherwise reach goal
|
|
15
|
+
* matching and throw there rather than being refused here.
|
|
16
|
+
*/
|
|
17
|
+
const rawEventError = (raw) => {
|
|
18
|
+
if (!raw || !TYPES.has(raw.type)) return "type";
|
|
19
|
+
if (!nonEmptyString(raw.path)) return "path";
|
|
20
|
+
if (!nonEmptyString(raw.hostname)) return "hostname";
|
|
21
|
+
if (raw.type !== "pageview" && !nonEmptyString(raw.name)) return "name";
|
|
22
|
+
};
|
|
23
|
+
const validateRawEvent = (raw) => rawEventError(raw) === void 0;
|
|
24
|
+
//#endregion
|
|
25
|
+
export { rawEventError, validateRawEvent };
|
|
26
|
+
|
|
27
|
+
//# sourceMappingURL=validate.js.map
|