@10x-media/analytics 1.0.0-beta.6 → 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.
Files changed (391) hide show
  1. package/CHANGELOG.md +73 -0
  2. package/README.md +13 -3
  3. package/dist/adapters/ga4/ga4.js +3 -2
  4. package/dist/adapters/ga4/ga4.js.map +1 -1
  5. package/dist/adapters/http/fetchJson.js +1 -1
  6. package/dist/adapters/plausible/plausible.d.ts +10 -0
  7. package/dist/adapters/plausible/plausible.js +42 -1
  8. package/dist/adapters/plausible/plausible.js.map +1 -1
  9. package/dist/adapters/posthog/posthog.d.ts +10 -1
  10. package/dist/adapters/posthog/posthog.js +47 -0
  11. package/dist/adapters/posthog/posthog.js.map +1 -1
  12. package/dist/adapters/umami/umami.d.ts +5 -1
  13. package/dist/adapters/umami/umami.js +26 -0
  14. package/dist/adapters/umami/umami.js.map +1 -1
  15. package/dist/capture/getTrackerConfig.d.ts +20 -0
  16. package/dist/capture/getTrackerConfig.js +31 -0
  17. package/dist/capture/getTrackerConfig.js.map +1 -0
  18. package/dist/capture/mountPath.js +14 -0
  19. package/dist/capture/mountPath.js.map +1 -0
  20. package/dist/capture/proxyEndpoint.js +123 -0
  21. package/dist/capture/proxyEndpoint.js.map +1 -0
  22. package/dist/capture/proxyRoutes.js +108 -0
  23. package/dist/capture/proxyRoutes.js.map +1 -0
  24. package/dist/capture/requestBody.js +68 -0
  25. package/dist/capture/requestBody.js.map +1 -0
  26. package/dist/capture/slots.d.ts +8 -0
  27. package/dist/capture/slots.js +54 -0
  28. package/dist/capture/slots.js.map +1 -0
  29. package/dist/capture/trackerConfig.d.ts +33 -0
  30. package/dist/capture/trackerConfig.js +95 -0
  31. package/dist/capture/trackerConfig.js.map +1 -0
  32. package/dist/capture/trackerEndpoint.js +35 -0
  33. package/dist/capture/trackerEndpoint.js.map +1 -0
  34. package/dist/charts/BarList.d.ts +15 -1
  35. package/dist/charts/BarList.js +34 -18
  36. package/dist/charts/BarList.js.map +1 -1
  37. package/dist/charts/TrendChart.d.ts +16 -3
  38. package/dist/charts/TrendChart.js +172 -106
  39. package/dist/charts/TrendChart.js.map +1 -1
  40. package/dist/charts/bars.d.ts +2 -0
  41. package/dist/charts/bars.js +2 -1
  42. package/dist/charts/bars.js.map +1 -1
  43. package/dist/charts/bucket.js +10 -1
  44. package/dist/charts/bucket.js.map +1 -1
  45. package/dist/charts/spline.js +2 -2
  46. package/dist/charts/spline.js.map +1 -1
  47. package/dist/charts/styles.js +18 -1
  48. package/dist/charts/styles.js.map +1 -1
  49. package/dist/core/cacheKey.js +13 -1
  50. package/dist/core/cacheKey.js.map +1 -1
  51. package/dist/core/capture.d.ts +49 -0
  52. package/dist/core/contract.d.ts +35 -4
  53. package/dist/core/contract.js +29 -1
  54. package/dist/core/contract.js.map +1 -1
  55. package/dist/core/granularity.js +1 -1
  56. package/dist/core/options.d.ts +148 -4
  57. package/dist/core/options.js +121 -3
  58. package/dist/core/options.js.map +1 -1
  59. package/dist/core/registry.d.ts +1 -0
  60. package/dist/core/scopeList.js +32 -0
  61. package/dist/core/scopeList.js.map +1 -0
  62. package/dist/core/scopedRead.js +45 -28
  63. package/dist/core/scopedRead.js.map +1 -1
  64. package/dist/core/serverEvent.d.ts +42 -0
  65. package/dist/core/serverEvent.js +12 -0
  66. package/dist/core/serverEvent.js.map +1 -0
  67. package/dist/exports/client.d.ts +8 -2
  68. package/dist/exports/client.js +6 -1
  69. package/dist/exports/next.d.ts +2 -1
  70. package/dist/exports/next.js +2 -1
  71. package/dist/exports/react.d.ts +4 -0
  72. package/dist/exports/react.js +5 -0
  73. package/dist/exports/rsc.d.ts +8 -1
  74. package/dist/exports/rsc.js +7 -2
  75. package/dist/exports/tracker.d.ts +18 -0
  76. package/dist/exports/tracker.js +12 -0
  77. package/dist/exports/types.d.ts +14 -3
  78. package/dist/exports/types.js +2 -2
  79. package/dist/fields/AnalyticsPanelClient.js +2 -2
  80. package/dist/fields/AnalyticsPanelField.js +1 -1
  81. package/dist/fields/AnalyticsStatField.js +2 -2
  82. package/dist/fields/config/MetricSelectField.js +2 -2
  83. package/dist/fields/config/MetricSelectField.js.map +1 -1
  84. package/dist/fields/config/SourceSelectField.js +2 -2
  85. package/dist/fields/config/SourceSelectField.js.map +1 -1
  86. package/dist/fields/config/fetchSources.d.ts +5 -1
  87. package/dist/fields/config/narrow.js +2 -0
  88. package/dist/fields/config/narrow.js.map +1 -1
  89. package/dist/fields/readForDocument.d.ts +5 -0
  90. package/dist/fields/readForDocument.js +6 -6
  91. package/dist/fields/readForDocument.js.map +1 -1
  92. package/dist/goals/GoalSelectField.d.ts +7 -0
  93. package/dist/goals/GoalSelectField.js +77 -0
  94. package/dist/goals/GoalSelectField.js.map +1 -0
  95. package/dist/goals/collection.js +250 -0
  96. package/dist/goals/collection.js.map +1 -0
  97. package/dist/goals/currency.js +14 -0
  98. package/dist/goals/currency.js.map +1 -0
  99. package/dist/goals/fetchGoals.d.ts +18 -0
  100. package/dist/goals/fetchGoals.js +29 -0
  101. package/dist/goals/fetchGoals.js.map +1 -0
  102. package/dist/goals/goalField.d.ts +31 -0
  103. package/dist/goals/goalField.js +56 -0
  104. package/dist/goals/goalField.js.map +1 -0
  105. package/dist/goals/goalsEndpoint.d.ts +1 -0
  106. package/dist/goals/goalsEndpoint.js +55 -0
  107. package/dist/goals/goalsEndpoint.js.map +1 -0
  108. package/dist/goals/match.js +64 -0
  109. package/dist/goals/match.js.map +1 -0
  110. package/dist/goals/resolver.d.ts +8 -0
  111. package/dist/goals/resolver.js +147 -0
  112. package/dist/goals/resolver.js.map +1 -0
  113. package/dist/goals/trackGoalAction.d.ts +74 -0
  114. package/dist/goals/trackGoalAction.js +139 -0
  115. package/dist/goals/trackGoalAction.js.map +1 -0
  116. package/dist/goals/types.d.ts +33 -0
  117. package/dist/goals/types.js +7 -0
  118. package/dist/goals/types.js.map +1 -0
  119. package/dist/goals/useAnalyticsGoals.d.ts +20 -0
  120. package/dist/goals/useAnalyticsGoals.js +67 -0
  121. package/dist/goals/useAnalyticsGoals.js.map +1 -0
  122. package/dist/index.d.ts +11 -3
  123. package/dist/index.js +104 -17
  124. package/dist/index.js.map +1 -1
  125. package/dist/native/collections/events.js +21 -1
  126. package/dist/native/collections/events.js.map +1 -1
  127. package/dist/native/collections/rollups.js +24 -0
  128. package/dist/native/collections/rollups.js.map +1 -1
  129. package/dist/native/geo/maxmindResolver.js +2 -4
  130. package/dist/native/geo/maxmindResolver.js.map +1 -1
  131. package/dist/native/ingest/clientIp.js +15 -0
  132. package/dist/native/ingest/clientIp.js.map +1 -0
  133. package/dist/native/ingest/device.js +11 -3
  134. package/dist/native/ingest/device.js.map +1 -1
  135. package/dist/native/ingest/endpoint.d.ts +1 -0
  136. package/dist/native/ingest/endpoint.js +25 -4
  137. package/dist/native/ingest/endpoint.js.map +1 -1
  138. package/dist/native/ingest/flushBatch.js +4 -13
  139. package/dist/native/ingest/flushBatch.js.map +1 -1
  140. package/dist/native/ingest/normalizeEvent.d.ts +20 -0
  141. package/dist/native/ingest/normalizeEvent.js +78 -10
  142. package/dist/native/ingest/normalizeEvent.js.map +1 -1
  143. package/dist/native/ingest/serverTrack.d.ts +20 -0
  144. package/dist/native/ingest/serverTrack.js +99 -0
  145. package/dist/native/ingest/serverTrack.js.map +1 -0
  146. package/dist/native/ingest/validate.js +27 -0
  147. package/dist/native/ingest/validate.js.map +1 -0
  148. package/dist/native/nativeAdapter.d.ts +1 -1
  149. package/dist/native/nativeAdapter.js +38 -11
  150. package/dist/native/nativeAdapter.js.map +1 -1
  151. package/dist/native/query/eventAgg.js +39 -13
  152. package/dist/native/query/eventAgg.js.map +1 -1
  153. package/dist/native/retention/pruneTask.js +1 -1
  154. package/dist/native/rollupAcc.js +12 -1
  155. package/dist/native/rollupAcc.js.map +1 -1
  156. package/dist/native/rollups/bumpRollup.js +5 -1
  157. package/dist/native/rollups/bumpRollup.js.map +1 -1
  158. package/dist/native/rollups/deltas.js +28 -6
  159. package/dist/native/rollups/deltas.js.map +1 -1
  160. package/dist/native/rollups/insertIfNew.js +36 -2
  161. package/dist/native/rollups/insertIfNew.js.map +1 -1
  162. package/dist/next/captureRewrites.d.ts +41 -0
  163. package/dist/next/captureRewrites.js +56 -0
  164. package/dist/next/captureRewrites.js.map +1 -0
  165. package/dist/next/posthogProxyRewrites.d.ts +5 -0
  166. package/dist/next/posthogProxyRewrites.js +16 -21
  167. package/dist/next/posthogProxyRewrites.js.map +1 -1
  168. package/dist/plugin/documentEndpoint.js +28 -10
  169. package/dist/plugin/documentEndpoint.js.map +1 -1
  170. package/dist/plugin/paths.js +15 -1
  171. package/dist/plugin/paths.js.map +1 -1
  172. package/dist/plugin/queryEndpoint.js +113 -0
  173. package/dist/plugin/queryEndpoint.js.map +1 -0
  174. package/dist/plugin/readContextForRequest.js +71 -0
  175. package/dist/plugin/readContextForRequest.js.map +1 -0
  176. package/dist/plugin/realtimeEndpoint.js +6 -3
  177. package/dist/plugin/realtimeEndpoint.js.map +1 -1
  178. package/dist/plugin/runtime.d.ts +1 -0
  179. package/dist/plugin/runtime.js +31 -1
  180. package/dist/plugin/runtime.js.map +1 -1
  181. package/dist/plugin/scopeFieldBoot.js +22 -0
  182. package/dist/plugin/scopeFieldBoot.js.map +1 -0
  183. package/dist/plugin/sourcesEndpoint.js +13 -39
  184. package/dist/plugin/sourcesEndpoint.js.map +1 -1
  185. package/dist/plugin/warmTask.js +0 -0
  186. package/dist/plugin/warmTask.js.map +1 -1
  187. package/dist/providers/collection.js +71 -25
  188. package/dist/providers/collection.js.map +1 -1
  189. package/dist/providers/factory.js +8 -2
  190. package/dist/providers/factory.js.map +1 -1
  191. package/dist/providers/resolver.js.map +1 -1
  192. package/dist/query/dates.js +64 -0
  193. package/dist/query/dates.js.map +1 -0
  194. package/dist/query/errors.d.ts +17 -0
  195. package/dist/query/errors.js +10 -0
  196. package/dist/query/errors.js.map +1 -0
  197. package/dist/query/fetchQuery.d.ts +59 -0
  198. package/dist/query/fetchQuery.js +110 -0
  199. package/dist/query/fetchQuery.js.map +1 -0
  200. package/dist/query/parse.d.ts +22 -0
  201. package/dist/query/parse.js +168 -0
  202. package/dist/query/parse.js.map +1 -0
  203. package/dist/query/response.d.ts +36 -0
  204. package/dist/react/AnalyticsProvider.d.ts +43 -0
  205. package/dist/react/AnalyticsProvider.js +66 -0
  206. package/dist/react/AnalyticsProvider.js.map +1 -0
  207. package/dist/react/TrackerBoot.d.ts +22 -0
  208. package/dist/react/TrackerBoot.js +30 -0
  209. package/dist/react/TrackerBoot.js.map +1 -0
  210. package/dist/react/useAnalytics.d.ts +17 -0
  211. package/dist/react/useAnalytics.js +36 -0
  212. package/dist/react/useAnalytics.js.map +1 -0
  213. package/dist/rsc/AnalyticsScripts.d.ts +30 -0
  214. package/dist/rsc/AnalyticsScripts.js +41 -0
  215. package/dist/rsc/AnalyticsScripts.js.map +1 -0
  216. package/dist/surfacing/cacheStore.d.ts +1 -0
  217. package/dist/surfacing/cacheStore.js +18 -2
  218. package/dist/surfacing/cacheStore.js.map +1 -1
  219. package/dist/surfacing/engine.d.ts +1 -0
  220. package/dist/surfacing/engine.js +44 -4
  221. package/dist/surfacing/engine.js.map +1 -1
  222. package/dist/surfacing/queue.js +22 -6
  223. package/dist/surfacing/queue.js.map +1 -1
  224. package/dist/surfacing/rateLimiter.js +130 -0
  225. package/dist/surfacing/rateLimiter.js.map +1 -0
  226. package/dist/surfacing/retryPolicy.js +15 -0
  227. package/dist/surfacing/retryPolicy.js.map +1 -0
  228. package/dist/sync/syncTask.js +60 -33
  229. package/dist/sync/syncTask.js.map +1 -1
  230. package/dist/testing/memoryAdapter.d.ts +2 -0
  231. package/dist/testing/memoryAdapter.js +10 -0
  232. package/dist/testing/memoryAdapter.js.map +1 -1
  233. package/dist/timeframe/tz.js +17 -6
  234. package/dist/timeframe/tz.js.map +1 -1
  235. package/dist/tracker/autoCapture.d.ts +48 -0
  236. package/dist/tracker/autoCapture.js +129 -0
  237. package/dist/tracker/autoCapture.js.map +1 -0
  238. package/dist/tracker/consent.d.ts +24 -0
  239. package/dist/tracker/consent.js +48 -0
  240. package/dist/tracker/consent.js.map +1 -0
  241. package/dist/tracker/createTracker.d.ts +18 -0
  242. package/dist/tracker/createTracker.js +163 -0
  243. package/dist/tracker/createTracker.js.map +1 -0
  244. package/dist/tracker/initTracker.d.ts +22 -0
  245. package/dist/tracker/initTracker.js +33 -0
  246. package/dist/tracker/initTracker.js.map +1 -0
  247. package/dist/tracker/loadScript.d.ts +14 -0
  248. package/dist/tracker/loadScript.js +41 -0
  249. package/dist/tracker/loadScript.js.map +1 -0
  250. package/dist/tracker/pageTracking.d.ts +17 -0
  251. package/dist/tracker/pageTracking.js +38 -0
  252. package/dist/tracker/pageTracking.js.map +1 -0
  253. package/dist/tracker/registry.d.ts +27 -0
  254. package/dist/tracker/registry.js +73 -0
  255. package/dist/tracker/registry.js.map +1 -0
  256. package/dist/tracker/sinks/native.d.ts +22 -0
  257. package/dist/tracker/sinks/native.js +56 -0
  258. package/dist/tracker/sinks/native.js.map +1 -0
  259. package/dist/tracker/sinks/plausible.d.ts +14 -0
  260. package/dist/tracker/sinks/plausible.js +25 -0
  261. package/dist/tracker/sinks/plausible.js.map +1 -0
  262. package/dist/tracker/sinks/posthog.d.ts +14 -0
  263. package/dist/tracker/sinks/posthog.js +18 -0
  264. package/dist/tracker/sinks/posthog.js.map +1 -0
  265. package/dist/tracker/sinks/umami.d.ts +13 -0
  266. package/dist/tracker/sinks/umami.js +17 -0
  267. package/dist/tracker/sinks/umami.js.map +1 -0
  268. package/dist/tracker/sinks/vendor.d.ts +14 -0
  269. package/dist/tracker/sinks/vendor.js +66 -0
  270. package/dist/tracker/sinks/vendor.js.map +1 -0
  271. package/dist/tracker/transport.js +28 -0
  272. package/dist/tracker/transport.js.map +1 -0
  273. package/dist/tracker/types.d.ts +66 -0
  274. package/dist/translations/ar.js +104 -1
  275. package/dist/translations/ar.js.map +1 -1
  276. package/dist/translations/de.js +104 -1
  277. package/dist/translations/de.js.map +1 -1
  278. package/dist/translations/en.js +104 -1
  279. package/dist/translations/en.js.map +1 -1
  280. package/dist/translations/es.js +104 -1
  281. package/dist/translations/es.js.map +1 -1
  282. package/dist/translations/fr.js +104 -1
  283. package/dist/translations/fr.js.map +1 -1
  284. package/dist/translations/id.js +104 -1
  285. package/dist/translations/id.js.map +1 -1
  286. package/dist/translations/keys.d.ts +103 -0
  287. package/dist/translations/keys.js +104 -1
  288. package/dist/translations/keys.js.map +1 -1
  289. package/dist/translations/ko.js +104 -1
  290. package/dist/translations/ko.js.map +1 -1
  291. package/dist/translations/metricKeys.js +1 -1
  292. package/dist/translations/metricKeys.js.map +1 -1
  293. package/dist/translations/pt.js +104 -1
  294. package/dist/translations/pt.js.map +1 -1
  295. package/dist/translations/ru.js +104 -1
  296. package/dist/translations/ru.js.map +1 -1
  297. package/dist/translations/uk.js +104 -1
  298. package/dist/translations/uk.js.map +1 -1
  299. package/dist/translations/zh.js +104 -1
  300. package/dist/translations/zh.js.map +1 -1
  301. package/dist/view/AnalyticsNavLink.d.ts +19 -0
  302. package/dist/view/AnalyticsNavLink.js +40 -0
  303. package/dist/view/AnalyticsNavLink.js.map +1 -0
  304. package/dist/view/AnalyticsView.d.ts +23 -0
  305. package/dist/view/AnalyticsView.js +45 -0
  306. package/dist/view/AnalyticsView.js.map +1 -0
  307. package/dist/view/AnalyticsViewClient.d.ts +15 -0
  308. package/dist/view/AnalyticsViewClient.js +189 -0
  309. package/dist/view/AnalyticsViewClient.js.map +1 -0
  310. package/dist/view/authRedirect.js +32 -0
  311. package/dist/view/authRedirect.js.map +1 -0
  312. package/dist/view/conversionRate.js +18 -0
  313. package/dist/view/conversionRate.js.map +1 -0
  314. package/dist/view/dayRange.js +68 -0
  315. package/dist/view/dayRange.js.map +1 -0
  316. package/dist/view/gating.d.ts +1 -0
  317. package/dist/view/gating.js +105 -0
  318. package/dist/view/gating.js.map +1 -0
  319. package/dist/view/labels.js +44 -0
  320. package/dist/view/labels.js.map +1 -0
  321. package/dist/view/registerView.js +48 -0
  322. package/dist/view/registerView.js.map +1 -0
  323. package/dist/view/sections/Breakdowns.js +157 -0
  324. package/dist/view/sections/Breakdowns.js.map +1 -0
  325. package/dist/view/sections/EmptyStates.js +92 -0
  326. package/dist/view/sections/EmptyStates.js.map +1 -0
  327. package/dist/view/sections/FilterChips.js +41 -0
  328. package/dist/view/sections/FilterChips.js.map +1 -0
  329. package/dist/view/sections/GoalsPanel.js +81 -0
  330. package/dist/view/sections/GoalsPanel.js.map +1 -0
  331. package/dist/view/sections/OverviewCards.js +65 -0
  332. package/dist/view/sections/OverviewCards.js.map +1 -0
  333. package/dist/view/sections/RealtimeStrip.js +77 -0
  334. package/dist/view/sections/RealtimeStrip.js.map +1 -0
  335. package/dist/view/sections/Toolbar.js +179 -0
  336. package/dist/view/sections/Toolbar.js.map +1 -0
  337. package/dist/view/sections/Trend.js +119 -0
  338. package/dist/view/sections/Trend.js.map +1 -0
  339. package/dist/view/sections/styles.js +74 -0
  340. package/dist/view/sections/styles.js.map +1 -0
  341. package/dist/view/state.js +206 -0
  342. package/dist/view/state.js.map +1 -0
  343. package/dist/view/useViewQueries.js +150 -0
  344. package/dist/view/useViewQueries.js.map +1 -0
  345. package/dist/view/viewProps.d.ts +40 -0
  346. package/dist/view/viewProps.js +90 -0
  347. package/dist/view/viewProps.js.map +1 -0
  348. package/dist/widgets/AnalyticsBreakdownWidget.d.ts +2 -1
  349. package/dist/widgets/AnalyticsBreakdownWidget.js +22 -4
  350. package/dist/widgets/AnalyticsBreakdownWidget.js.map +1 -1
  351. package/dist/widgets/AnalyticsGoalsWidget.d.ts +14 -0
  352. package/dist/widgets/AnalyticsGoalsWidget.js +188 -0
  353. package/dist/widgets/AnalyticsGoalsWidget.js.map +1 -0
  354. package/dist/widgets/AnalyticsMetricWidget.d.ts +2 -1
  355. package/dist/widgets/AnalyticsMetricWidget.js +35 -12
  356. package/dist/widgets/AnalyticsMetricWidget.js.map +1 -1
  357. package/dist/widgets/AnalyticsRealtimeWidget.d.ts +2 -1
  358. package/dist/widgets/AnalyticsRealtimeWidget.js +42 -22
  359. package/dist/widgets/AnalyticsRealtimeWidget.js.map +1 -1
  360. package/dist/widgets/AnalyticsTrendWidget.d.ts +2 -1
  361. package/dist/widgets/AnalyticsTrendWidget.js +51 -15
  362. package/dist/widgets/AnalyticsTrendWidget.js.map +1 -1
  363. package/dist/widgets/WidgetViewLink.js +17 -0
  364. package/dist/widgets/WidgetViewLink.js.map +1 -0
  365. package/dist/widgets/breakdownTypes.js +32 -0
  366. package/dist/widgets/breakdownTypes.js.map +1 -1
  367. package/dist/widgets/cardChrome.js +31 -7
  368. package/dist/widgets/cardChrome.js.map +1 -1
  369. package/dist/widgets/range.js +43 -12
  370. package/dist/widgets/range.js.map +1 -1
  371. package/dist/widgets/readForWidget.d.ts +12 -0
  372. package/dist/widgets/readForWidget.js +30 -19
  373. package/dist/widgets/readForWidget.js.map +1 -1
  374. package/dist/widgets/readForWidgetBreakdown.d.ts +15 -0
  375. package/dist/widgets/readForWidgetBreakdown.js +32 -20
  376. package/dist/widgets/readForWidgetBreakdown.js.map +1 -1
  377. package/dist/widgets/readForWidgetGoals.d.ts +57 -0
  378. package/dist/widgets/readForWidgetGoals.js +126 -0
  379. package/dist/widgets/readForWidgetGoals.js.map +1 -0
  380. package/dist/widgets/readForWidgetRealtime.js +1 -1
  381. package/dist/widgets/readForWidgetSeries.d.ts +13 -0
  382. package/dist/widgets/readForWidgetSeries.js +56 -28
  383. package/dist/widgets/readForWidgetSeries.js.map +1 -1
  384. package/dist/widgets/registerWidgets.js +58 -9
  385. package/dist/widgets/registerWidgets.js.map +1 -1
  386. package/dist/widgets/types.js +16 -2
  387. package/dist/widgets/types.js.map +1 -1
  388. package/dist/widgets/viewLink.d.ts +22 -0
  389. package/dist/widgets/viewLink.js +83 -0
  390. package/dist/widgets/viewLink.js.map +1 -0
  391. package/package.json +25 -5
@@ -13,14 +13,10 @@ async function flushBatch(payload, events) {
13
13
  for (const event of events) for (const delta of computeRollupDeltas(event)) {
14
14
  const bk = bucketKey(delta.key);
15
15
  const agg = base.get(bk);
16
- if (agg) {
17
- agg.pageviews += delta.inc.pageviews;
18
- agg.events += delta.inc.events;
19
- agg.durationMs += delta.inc.durationMs;
20
- agg.samples += delta.inc.samples;
21
- } else base.set(bk, {
16
+ if (agg) for (const metric of Object.keys(agg.inc)) agg.inc[metric] += delta.inc[metric];
17
+ else base.set(bk, {
22
18
  key: delta.key,
23
- ...delta.inc
19
+ inc: { ...delta.inc }
24
20
  });
25
21
  candidates.set(`${bk}|visitor|${event.visitorHash}`, {
26
22
  key: delta.key,
@@ -33,12 +29,7 @@ async function flushBatch(payload, events) {
33
29
  value: event.sessionId
34
30
  });
35
31
  }
36
- for (const agg of base.values()) await bumpRollup(payload, agg.key, {
37
- pageviews: agg.pageviews,
38
- events: agg.events,
39
- durationMs: agg.durationMs,
40
- samples: agg.samples
41
- });
32
+ for (const agg of base.values()) await bumpRollup(payload, agg.key, agg.inc);
42
33
  const distinct = /* @__PURE__ */ new Map();
43
34
  for (const candidate of candidates.values()) {
44
35
  if (!await insertIfNew(payload, "analytics-seen", {
@@ -1 +1 @@
1
- {"version":3,"file":"flushBatch.js","names":[],"sources":["../../../src/native/ingest/flushBatch.ts"],"sourcesContent":["import type { Payload } from 'payload'\nimport { SEEN_SLUG } from '../collections/seen'\nimport { bucketKey } from '../rollups/applyDistinctDeltas'\nimport { bumpRollup } from '../rollups/bumpRollup'\nimport { computeRollupDeltas, type RollupKey, type RollupMetric } from '../rollups/deltas'\nimport { insertIfNew } from '../rollups/insertIfNew'\nimport type { StoredEvent } from './normalizeEvent'\nimport { writeEvent } from './writeEvent'\n\ninterface BaseAgg {\n\tkey: RollupKey\n\tpageviews: number\n\tevents: number\n\tdurationMs: number\n\tsamples: number\n}\n\ninterface DistinctCandidate {\n\tkey: RollupKey\n\tkind: 'visitor' | 'session'\n\tvalue: string\n}\n\n// Coalesces a batch of events into the fewest writes: events insert concurrently, base\n// rollup increments are summed per bucket into one upsert each, and distinct visitor /\n// session candidates are de-duplicated within the batch before insert-if-new. Correctness\n// matches the per-event path because the seen ledger still de-dupes across batches.\nexport async function flushBatch(payload: Payload, events: StoredEvent[]): Promise<void> {\n\tif (events.length === 0) {\n\t\treturn\n\t}\n\tawait Promise.all(events.map((event) => writeEvent(payload, event)))\n\n\tconst base = new Map<string, BaseAgg>()\n\tconst candidates = new Map<string, DistinctCandidate>()\n\tfor (const event of events) {\n\t\tfor (const delta of computeRollupDeltas(event)) {\n\t\t\tconst bk = bucketKey(delta.key)\n\t\t\tconst agg = base.get(bk)\n\t\t\tif (agg) {\n\t\t\t\tagg.pageviews += delta.inc.pageviews\n\t\t\t\tagg.events += delta.inc.events\n\t\t\t\tagg.durationMs += delta.inc.durationMs\n\t\t\t\tagg.samples += delta.inc.samples\n\t\t\t} else {\n\t\t\t\tbase.set(bk, { key: delta.key, ...delta.inc })\n\t\t\t}\n\t\t\tcandidates.set(`${bk}|visitor|${event.visitorHash}`, {\n\t\t\t\tkey: delta.key,\n\t\t\t\tkind: 'visitor',\n\t\t\t\tvalue: event.visitorHash,\n\t\t\t})\n\t\t\tcandidates.set(`${bk}|session|${event.sessionId}`, {\n\t\t\t\tkey: delta.key,\n\t\t\t\tkind: 'session',\n\t\t\t\tvalue: event.sessionId,\n\t\t\t})\n\t\t}\n\t}\n\n\tfor (const agg of base.values()) {\n\t\tawait bumpRollup(payload, agg.key, {\n\t\t\tpageviews: agg.pageviews,\n\t\t\tevents: agg.events,\n\t\t\tdurationMs: agg.durationMs,\n\t\t\tsamples: agg.samples,\n\t\t})\n\t}\n\n\tconst distinct = new Map<string, { key: RollupKey; metric: RollupMetric; count: number }>()\n\tfor (const candidate of candidates.values()) {\n\t\tconst isNew = await insertIfNew(payload, SEEN_SLUG, {\n\t\t\tbucket: bucketKey(candidate.key),\n\t\t\tkind: candidate.kind,\n\t\t\tvalue: candidate.value,\n\t\t\tperiod: candidate.key.period,\n\t\t})\n\t\tif (!isNew) {\n\t\t\tcontinue\n\t\t}\n\t\tconst metric: RollupMetric = candidate.kind === 'visitor' ? 'visitors' : 'sessions'\n\t\tconst dk = `${bucketKey(candidate.key)}|${metric}`\n\t\tconst entry = distinct.get(dk)\n\t\tif (entry) {\n\t\t\tentry.count += 1\n\t\t} else {\n\t\t\tdistinct.set(dk, { key: candidate.key, metric, count: 1 })\n\t\t}\n\t}\n\n\tfor (const entry of distinct.values()) {\n\t\tconst inc: Partial<Record<RollupMetric, number>> = {}\n\t\tinc[entry.metric] = entry.count\n\t\tawait bumpRollup(payload, entry.key, inc)\n\t}\n}\n"],"mappings":";;;;;;;AA2BA,eAAsB,WAAW,SAAkB,QAAsC;CACxF,IAAI,OAAO,WAAW,GACrB;CAED,MAAM,QAAQ,IAAI,OAAO,KAAK,UAAU,WAAW,SAAS,KAAK,CAAC,CAAC;CAEnE,MAAM,uBAAO,IAAI,IAAqB;CACtC,MAAM,6BAAa,IAAI,IAA+B;CACtD,KAAK,MAAM,SAAS,QACnB,KAAK,MAAM,SAAS,oBAAoB,KAAK,GAAG;EAC/C,MAAM,KAAK,UAAU,MAAM,GAAG;EAC9B,MAAM,MAAM,KAAK,IAAI,EAAE;EACvB,IAAI,KAAK;GACR,IAAI,aAAa,MAAM,IAAI;GAC3B,IAAI,UAAU,MAAM,IAAI;GACxB,IAAI,cAAc,MAAM,IAAI;GAC5B,IAAI,WAAW,MAAM,IAAI;EAC1B,OACC,KAAK,IAAI,IAAI;GAAE,KAAK,MAAM;GAAK,GAAG,MAAM;EAAI,CAAC;EAE9C,WAAW,IAAI,GAAG,GAAG,WAAW,MAAM,eAAe;GACpD,KAAK,MAAM;GACX,MAAM;GACN,OAAO,MAAM;EACd,CAAC;EACD,WAAW,IAAI,GAAG,GAAG,WAAW,MAAM,aAAa;GAClD,KAAK,MAAM;GACX,MAAM;GACN,OAAO,MAAM;EACd,CAAC;CACF;CAGD,KAAK,MAAM,OAAO,KAAK,OAAO,GAC7B,MAAM,WAAW,SAAS,IAAI,KAAK;EAClC,WAAW,IAAI;EACf,QAAQ,IAAI;EACZ,YAAY,IAAI;EAChB,SAAS,IAAI;CACd,CAAC;CAGF,MAAM,2BAAW,IAAI,IAAqE;CAC1F,KAAK,MAAM,aAAa,WAAW,OAAO,GAAG;EAO5C,IAAI,CAAC,MANe,YAAY,SAAA,kBAAoB;GACnD,QAAQ,UAAU,UAAU,GAAG;GAC/B,MAAM,UAAU;GAChB,OAAO,UAAU;GACjB,QAAQ,UAAU,IAAI;EACvB,CAAC,GAEA;EAED,MAAM,SAAuB,UAAU,SAAS,YAAY,aAAa;EACzE,MAAM,KAAK,GAAG,UAAU,UAAU,GAAG,EAAE,GAAG;EAC1C,MAAM,QAAQ,SAAS,IAAI,EAAE;EAC7B,IAAI,OACH,MAAM,SAAS;OAEf,SAAS,IAAI,IAAI;GAAE,KAAK,UAAU;GAAK;GAAQ,OAAO;EAAE,CAAC;CAE3D;CAEA,KAAK,MAAM,SAAS,SAAS,OAAO,GAAG;EACtC,MAAM,MAA6C,CAAC;EACpD,IAAI,MAAM,UAAU,MAAM;EAC1B,MAAM,WAAW,SAAS,MAAM,KAAK,GAAG;CACzC;AACD"}
1
+ {"version":3,"file":"flushBatch.js","names":[],"sources":["../../../src/native/ingest/flushBatch.ts"],"sourcesContent":["import type { Payload } from 'payload'\nimport { SEEN_SLUG } from '../collections/seen'\nimport { bucketKey } from '../rollups/applyDistinctDeltas'\nimport { bumpRollup } from '../rollups/bumpRollup'\nimport {\n\tcomputeRollupDeltas,\n\ttype RollupInc,\n\ttype RollupKey,\n\ttype RollupMetric,\n} from '../rollups/deltas'\nimport { insertIfNew } from '../rollups/insertIfNew'\nimport type { StoredEvent } from './normalizeEvent'\nimport { writeEvent } from './writeEvent'\n\ninterface BaseAgg {\n\tkey: RollupKey\n\tinc: RollupInc\n}\n\ninterface DistinctCandidate {\n\tkey: RollupKey\n\tkind: 'visitor' | 'session'\n\tvalue: string\n}\n\n// Coalesces a batch of events into the fewest writes: events insert concurrently, base\n// rollup increments are summed per bucket into one upsert each, and distinct visitor /\n// session candidates are de-duplicated within the batch before insert-if-new. Correctness\n// matches the per-event path because the seen ledger still de-dupes across batches.\nexport async function flushBatch(payload: Payload, events: StoredEvent[]): Promise<void> {\n\tif (events.length === 0) {\n\t\treturn\n\t}\n\tawait Promise.all(events.map((event) => writeEvent(payload, event)))\n\n\tconst base = new Map<string, BaseAgg>()\n\tconst candidates = new Map<string, DistinctCandidate>()\n\tfor (const event of events) {\n\t\tfor (const delta of computeRollupDeltas(event)) {\n\t\t\tconst bk = bucketKey(delta.key)\n\t\t\tconst agg = base.get(bk)\n\t\t\tif (agg) {\n\t\t\t\tfor (const metric of Object.keys(agg.inc) as Array<keyof RollupInc>) {\n\t\t\t\t\tagg.inc[metric] += delta.inc[metric]\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tbase.set(bk, { key: delta.key, inc: { ...delta.inc } })\n\t\t\t}\n\t\t\tcandidates.set(`${bk}|visitor|${event.visitorHash}`, {\n\t\t\t\tkey: delta.key,\n\t\t\t\tkind: 'visitor',\n\t\t\t\tvalue: event.visitorHash,\n\t\t\t})\n\t\t\tcandidates.set(`${bk}|session|${event.sessionId}`, {\n\t\t\t\tkey: delta.key,\n\t\t\t\tkind: 'session',\n\t\t\t\tvalue: event.sessionId,\n\t\t\t})\n\t\t}\n\t}\n\n\tfor (const agg of base.values()) {\n\t\tawait bumpRollup(payload, agg.key, agg.inc)\n\t}\n\n\tconst distinct = new Map<string, { key: RollupKey; metric: RollupMetric; count: number }>()\n\tfor (const candidate of candidates.values()) {\n\t\tconst isNew = await insertIfNew(payload, SEEN_SLUG, {\n\t\t\tbucket: bucketKey(candidate.key),\n\t\t\tkind: candidate.kind,\n\t\t\tvalue: candidate.value,\n\t\t\tperiod: candidate.key.period,\n\t\t})\n\t\tif (!isNew) {\n\t\t\tcontinue\n\t\t}\n\t\tconst metric: RollupMetric = candidate.kind === 'visitor' ? 'visitors' : 'sessions'\n\t\tconst dk = `${bucketKey(candidate.key)}|${metric}`\n\t\tconst entry = distinct.get(dk)\n\t\tif (entry) {\n\t\t\tentry.count += 1\n\t\t} else {\n\t\t\tdistinct.set(dk, { key: candidate.key, metric, count: 1 })\n\t\t}\n\t}\n\n\tfor (const entry of distinct.values()) {\n\t\tconst inc: Partial<Record<RollupMetric, number>> = {}\n\t\tinc[entry.metric] = entry.count\n\t\tawait bumpRollup(payload, entry.key, inc)\n\t}\n}\n"],"mappings":";;;;;;;AA6BA,eAAsB,WAAW,SAAkB,QAAsC;CACxF,IAAI,OAAO,WAAW,GACrB;CAED,MAAM,QAAQ,IAAI,OAAO,KAAK,UAAU,WAAW,SAAS,KAAK,CAAC,CAAC;CAEnE,MAAM,uBAAO,IAAI,IAAqB;CACtC,MAAM,6BAAa,IAAI,IAA+B;CACtD,KAAK,MAAM,SAAS,QACnB,KAAK,MAAM,SAAS,oBAAoB,KAAK,GAAG;EAC/C,MAAM,KAAK,UAAU,MAAM,GAAG;EAC9B,MAAM,MAAM,KAAK,IAAI,EAAE;EACvB,IAAI,KACH,KAAK,MAAM,UAAU,OAAO,KAAK,IAAI,GAAG,GACvC,IAAI,IAAI,WAAW,MAAM,IAAI;OAG9B,KAAK,IAAI,IAAI;GAAE,KAAK,MAAM;GAAK,KAAK,EAAE,GAAG,MAAM,IAAI;EAAE,CAAC;EAEvD,WAAW,IAAI,GAAG,GAAG,WAAW,MAAM,eAAe;GACpD,KAAK,MAAM;GACX,MAAM;GACN,OAAO,MAAM;EACd,CAAC;EACD,WAAW,IAAI,GAAG,GAAG,WAAW,MAAM,aAAa;GAClD,KAAK,MAAM;GACX,MAAM;GACN,OAAO,MAAM;EACd,CAAC;CACF;CAGD,KAAK,MAAM,OAAO,KAAK,OAAO,GAC7B,MAAM,WAAW,SAAS,IAAI,KAAK,IAAI,GAAG;CAG3C,MAAM,2BAAW,IAAI,IAAqE;CAC1F,KAAK,MAAM,aAAa,WAAW,OAAO,GAAG;EAO5C,IAAI,CAAC,MANe,YAAY,SAAA,kBAAoB;GACnD,QAAQ,UAAU,UAAU,GAAG;GAC/B,MAAM,UAAU;GAChB,OAAO,UAAU;GACjB,QAAQ,UAAU,IAAI;EACvB,CAAC,GAEA;EAED,MAAM,SAAuB,UAAU,SAAS,YAAY,aAAa;EACzE,MAAM,KAAK,GAAG,UAAU,UAAU,GAAG,EAAE,GAAG;EAC1C,MAAM,QAAQ,SAAS,IAAI,EAAE;EAC7B,IAAI,OACH,MAAM,SAAS;OAEf,SAAS,IAAI,IAAI;GAAE,KAAK,UAAU;GAAK;GAAQ,OAAO;EAAE,CAAC;CAE3D;CAEA,KAAK,MAAM,SAAS,SAAS,OAAO,GAAG;EACtC,MAAM,MAA6C,CAAC;EACpD,IAAI,MAAM,UAAU,MAAM;EAC1B,MAAM,WAAW,SAAS,MAAM,KAAK,GAAG;CACzC;AACD"}
@@ -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,34 +1,102 @@
1
+ import { clientIpFromHeaders } from "./clientIp.js";
1
2
  import { classifyDevice } from "./device.js";
3
+ import { matchGoals } from "../../goals/match.js";
2
4
  import { deriveSource } from "./source.js";
3
5
  import { dailyVisitorHash, deriveSessionId } from "./visitorHash.js";
4
6
  //#region src/native/ingest/normalizeEvent.ts
5
- async function normalizeEvent({ raw, headers, geoResolver, salt, now, scope, timezone }) {
7
+ const MAX_PROPS = 20;
8
+ const MAX_KEY_LENGTH = 64;
9
+ const MAX_VALUE_LENGTH = 256;
10
+ const MAX_NAME_LENGTH = 128;
11
+ const MAX_PATH_LENGTH = 512;
12
+ /** Longest legal DNS name. */
13
+ const MAX_HOSTNAME_LENGTH = 253;
14
+ /** 24 hours. A longer duration is a broken clock, not a session. */
15
+ const MAX_DURATION_MS = 864e5;
16
+ const CURRENCY = /^[A-Z]{3}$/;
17
+ /**
18
+ * Optional wire fields are sanitized rather than rejected: a bad `value`, `currency`,
19
+ * `scrollDepth`, `durationMs`, or prop is dropped and the event is still ingested, so one malformed
20
+ * attribute never costs a pageview. Only the required fields (checked in the endpoint)
21
+ * can fail an event.
22
+ */
23
+ const nonNegative = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
24
+ const currencyCode = (value) => typeof value === "string" && CURRENCY.test(value) ? value : void 0;
25
+ /**
26
+ * Infinity would poison a rollup bucket's average for good, and a string would throw out of
27
+ * the write and take the whole buffered batch with it, so a duration outside the ceiling is
28
+ * dropped like any other malformed attribute.
29
+ */
30
+ const duration = (value) => {
31
+ const n = nonNegative(value);
32
+ return n === void 0 || n > MAX_DURATION_MS ? void 0 : n;
33
+ };
34
+ /** The event name is a rollup bucket key (the `event` dimension), so it is length-capped. */
35
+ const eventName = (value) => typeof value === "string" ? value.slice(0, MAX_NAME_LENGTH) : void 0;
36
+ const depth = (value) => {
37
+ const n = nonNegative(value);
38
+ return n === void 0 ? void 0 : Math.round(Math.min(n, 100));
39
+ };
40
+ /** Flat JSON scalars only: the first 20 short-keyed string/number/boolean entries. */
41
+ const sanitizeProps = (raw) => {
42
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return;
43
+ const out = {};
44
+ let kept = 0;
45
+ for (const [key, value] of Object.entries(raw)) {
46
+ if (kept >= MAX_PROPS || key.length > MAX_KEY_LENGTH) continue;
47
+ if (typeof value === "string") out[key] = value.slice(0, MAX_VALUE_LENGTH);
48
+ else if (typeof value === "boolean" || typeof value === "number" && Number.isFinite(value)) out[key] = value;
49
+ else continue;
50
+ kept++;
51
+ }
52
+ return kept > 0 ? out : void 0;
53
+ };
54
+ async function normalizeEvent({ raw, headers, geoResolver, salt, now, scope, timezone, goals }) {
6
55
  const geo = await geoResolver(headers);
7
- const ip = (headers.get("x-forwarded-for")?.split(",")[0] ?? headers.get("x-real-ip") ?? "").trim();
56
+ const ip = clientIpFromHeaders(headers) ?? "";
8
57
  const ua = headers.get("user-agent") ?? "";
58
+ const path = raw.path.slice(0, MAX_PATH_LENGTH);
59
+ const hostname = raw.hostname.slice(0, MAX_HOSTNAME_LENGTH);
9
60
  const visitorHash = dailyVisitorHash({
10
61
  ip,
11
62
  ua,
12
- site: raw.hostname,
63
+ site: hostname,
13
64
  salt
14
65
  });
15
66
  const hourBucket = now.toISOString().slice(0, 13);
67
+ const props = sanitizeProps(raw.props);
68
+ const value = nonNegative(raw.value);
69
+ const scrollDepth = depth(raw.scrollDepth);
70
+ const durationMs = duration(raw.durationMs);
71
+ const name = eventName(raw.name);
72
+ const device = classifyDevice(ua);
73
+ const completions = goals?.length ? matchGoals({
74
+ type: raw.type,
75
+ name,
76
+ path,
77
+ props,
78
+ value
79
+ }, goals) : [];
16
80
  return {
17
81
  timestamp: now,
18
82
  type: raw.type,
19
- name: raw.name,
20
- path: raw.path,
21
- hostname: raw.hostname,
83
+ name,
84
+ path,
85
+ hostname,
22
86
  referrer: raw.referrer,
23
- device: classifyDevice(ua),
24
- source: deriveSource(raw.referrer, raw.hostname),
87
+ ...device ? { device } : {},
88
+ source: deriveSource(raw.referrer, hostname),
25
89
  country: geo.country,
26
90
  region: geo.region,
27
91
  city: geo.city,
28
92
  visitorHash,
29
93
  sessionId: deriveSessionId(visitorHash, hourBucket),
30
- durationMs: raw.durationMs,
31
- props: raw.props,
94
+ props,
95
+ ...durationMs !== void 0 ? { durationMs } : {},
96
+ ...value !== void 0 ? { value } : {},
97
+ ...currencyCode(raw.currency) !== void 0 ? { currency: raw.currency } : {},
98
+ ...scrollDepth !== void 0 ? { scrollDepth } : {},
99
+ ...completions.length > 0 ? { goals: completions } : {},
32
100
  ...scope !== void 0 ? { scope } : {},
33
101
  ...timezone !== void 0 ? { timezone } : {}
34
102
  };
@@ -1 +1 @@
1
- {"version":3,"file":"normalizeEvent.js","names":[],"sources":["../../../src/native/ingest/normalizeEvent.ts"],"sourcesContent":["import type { GeoResolver } from '../geo/geoResolver'\nimport { classifyDevice, type DeviceType } from './device'\nimport { deriveSource } from './source'\nimport { dailyVisitorHash, deriveSessionId } from './visitorHash'\n\nexport interface RawEventInput {\n\ttype: 'pageview' | 'event'\n\tname?: string\n\tpath: string\n\thostname: string\n\treferrer?: string\n\tdurationMs?: number\n\tprops?: Record<string, unknown>\n}\n\nexport interface StoredEvent {\n\ttimestamp: Date\n\ttype: 'pageview' | 'event'\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\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}\n\nexport async function normalizeEvent({\n\traw,\n\theaders,\n\tgeoResolver,\n\tsalt,\n\tnow,\n\tscope,\n\ttimezone,\n}: NormalizeArgs): Promise<StoredEvent> {\n\tconst geo = await geoResolver(headers)\n\tconst ip = (\n\t\theaders.get('x-forwarded-for')?.split(',')[0] ??\n\t\theaders.get('x-real-ip') ??\n\t\t''\n\t).trim()\n\tconst ua = headers.get('user-agent') ?? ''\n\tconst visitorHash = dailyVisitorHash({ ip, ua, site: raw.hostname, salt })\n\tconst hourBucket = now.toISOString().slice(0, 13)\n\treturn {\n\t\ttimestamp: now,\n\t\ttype: raw.type,\n\t\tname: raw.name,\n\t\tpath: raw.path,\n\t\thostname: raw.hostname,\n\t\treferrer: raw.referrer,\n\t\tdevice: classifyDevice(ua),\n\t\tsource: deriveSource(raw.referrer, raw.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\tdurationMs: raw.durationMs,\n\t\tprops: raw.props,\n\t\t...(scope !== undefined ? { scope } : {}),\n\t\t...(timezone !== undefined ? { timezone } : {}),\n\t}\n}\n"],"mappings":";;;;AAmDA,eAAsB,eAAe,EACpC,KACA,SACA,aACA,MACA,KACA,OACA,YACuC;CACvC,MAAM,MAAM,MAAM,YAAY,OAAO;CACrC,MAAM,MACL,QAAQ,IAAI,iBAAiB,GAAG,MAAM,GAAG,EAAE,MAC3C,QAAQ,IAAI,WAAW,KACvB,IACC,KAAK;CACP,MAAM,KAAK,QAAQ,IAAI,YAAY,KAAK;CACxC,MAAM,cAAc,iBAAiB;EAAE;EAAI;EAAI,MAAM,IAAI;EAAU;CAAK,CAAC;CACzE,MAAM,aAAa,IAAI,YAAY,EAAE,MAAM,GAAG,EAAE;CAChD,OAAO;EACN,WAAW;EACX,MAAM,IAAI;EACV,MAAM,IAAI;EACV,MAAM,IAAI;EACV,UAAU,IAAI;EACd,UAAU,IAAI;EACd,QAAQ,eAAe,EAAE;EACzB,QAAQ,aAAa,IAAI,UAAU,IAAI,QAAQ;EAC/C,SAAS,IAAI;EACb,QAAQ,IAAI;EACZ,MAAM,IAAI;EACV;EACA,WAAW,gBAAgB,aAAa,UAAU;EAClD,YAAY,IAAI;EAChB,OAAO,IAAI;EACX,GAAI,UAAU,KAAA,IAAY,EAAE,MAAM,IAAI,CAAC;EACvC,GAAI,aAAa,KAAA,IAAY,EAAE,SAAS,IAAI,CAAC;CAC9C;AACD"}
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,YAAY,OAAO,SAAS,KAAK,KAAK,SAAS,IAAI,QAAQ,KAAA;AAE7E,MAAM,gBAAgB,UACrB,OAAO,UAAU,YAAY,SAAS,KAAK,KAAK,IAAI,QAAQ,KAAA;;;;;;AAO7D,MAAM,YAAY,UAAuC;CACxD,MAAM,IAAI,YAAY,KAAK;CAC3B,OAAO,MAAM,KAAA,KAAa,IAAI,kBAAkB,KAAA,IAAY;AAC7D;;AAGA,MAAM,aAAa,UAClB,OAAO,UAAU,WAAW,MAAM,MAAM,GAAG,eAAe,IAAI,KAAA;AAE/D,MAAM,SAAS,UAAuC;CACrD,MAAM,IAAI,YAAY,KAAK;CAC3B,OAAO,MAAM,KAAA,IAAY,KAAA,IAAY,KAAK,MAAM,KAAK,IAAI,GAAG,GAAG,CAAC;AACjE;;AAGA,MAAM,iBAAiB,QAAsD;CAC5E,IAAI,OAAO,QAAQ,YAAY,QAAQ,QAAQ,MAAM,QAAQ,GAAG,GAC/D;CAED,MAAM,MAA+B,CAAC;CACtC,IAAI,OAAO;CACX,K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EACZ,MAAM,IAAI;EACV;EACA,WAAW,gBAAgB,aAAa,UAAU;EAClD;EACA,GAAI,eAAe,KAAA,IAAY,EAAE,WAAW,IAAI,CAAC;EACjD,GAAI,UAAU,KAAA,IAAY,EAAE,MAAM,IAAI,CAAC;EACvC,GAAI,aAAa,IAAI,QAAQ,MAAM,KAAA,IAAY,EAAE,UAAU,IAAI,SAAS,IAAI,CAAC;EAC7E,GAAI,gBAAgB,KAAA,IAAY,EAAE,YAAY,IAAI,CAAC;EACnD,GAAI,YAAY,SAAS,IAAI,EAAE,OAAO,YAAY,IAAI,CAAC;EACvD,GAAI,UAAU,KAAA,IAAY,EAAE,MAAM,IAAI,CAAC;EACvC,GAAI,aAAa,KAAA,IAAY,EAAE,SAAS,IAAI,CAAC;CAC9C;AACD"}
@@ -0,0 +1,20 @@
1
+ import { ServerEventInput, ServerTrackOptions } from "../../core/serverEvent.js";
2
+ import { 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,QAAQ,KAAK,OAAO;CACxC,IAAI,MAAM,IACT,QAAQ,IAAI,mBAAmB,MAAM,EAAE;CAExC,IAAI,MAAM,WACT,QAAQ,IAAI,cAAc,MAAM,SAAS;CAE1C,IAAI,CAAC,QAAQ,IAAI,YAAY,GAC5B,QAAQ,IAAI,cAAc,iBAAiB;CAE5C,OAAO;AACR;AAEA,MAAM,eAAe,OACpB,OACA,MACA,cACiC;CAGjC,IAAI,CAAC,UAAU,OACd;CAED,IAAI,MAAM,U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,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
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validate.js","names":[],"sources":["../../../src/native/ingest/validate.ts"],"sourcesContent":["import type { EventType, RawEventInput } from './normalizeEvent'\n\nconst TYPES: ReadonlySet<string> = new Set<EventType>(['pageview', 'event', 'goal'])\n\nconst nonEmptyString = (value: unknown): boolean => typeof value === 'string' && value.length > 0\n\nexport type RawEventField = 'type' | 'path' | 'hostname' | 'name'\n\n/**\n * The first required field an event fails on, or undefined when it is valid: a known `type`,\n * a `path`, a `hostname`, and a `name` (the event name, or the goal slug on a `goal`) for\n * everything but a pageview. Optional fields are sanitized in `normalizeEvent` and dropped\n * when malformed, so one bad attribute costs an attribute rather than the whole event.\n *\n * Types are checked rather than truthiness: a non-string path would otherwise reach goal\n * matching and throw there rather than being refused here.\n */\nexport const rawEventError = (raw: RawEventInput | undefined): RawEventField | undefined => {\n\tif (!raw || !TYPES.has(raw.type)) {\n\t\treturn 'type'\n\t}\n\tif (!nonEmptyString(raw.path)) {\n\t\treturn 'path'\n\t}\n\tif (!nonEmptyString(raw.hostname)) {\n\t\treturn 'hostname'\n\t}\n\tif (raw.type !== 'pageview' && !nonEmptyString(raw.name)) {\n\t\treturn 'name'\n\t}\n\treturn undefined\n}\n\nexport const validateRawEvent = (raw: RawEventInput | undefined): raw is RawEventInput =>\n\trawEventError(raw) === undefined\n"],"mappings":";AAEA,MAAM,QAA6B,IAAI,IAAe;CAAC;CAAY;CAAS;AAAM,CAAC;AAEnF,MAAM,kBAAkB,UAA4B,OAAO,UAAU,YAAY,MAAM,SAAS;;;;;;;;;;AAahG,MAAa,iBAAiB,QAA8D;CAC3F,IAAI,CAAC,OAAO,CAAC,MAAM,IAAI,IAAI,IAAI,GAC9B,OAAO;CAER,IAAI,CAAC,eAAe,IAAI,IAAI,GAC3B,OAAO;CAER,IAAI,CAAC,eAAe,IAAI,QAAQ,GAC/B,OAAO;CAER,IAAI,IAAI,SAAS,cAAc,CAAC,eAAe,IAAI,IAAI,GACtD,OAAO;AAGT;AAEA,MAAa,oBAAoB,QAChC,cAAc,GAAG,MAAM,KAAA"}
@@ -1,5 +1,5 @@
1
- import { AnalyticsAdapter } from "../core/contract.js";
2
1
  import { GeoResolver } from "./geo/geoResolver.js";
2
+ import { AnalyticsAdapter } from "../core/contract.js";
3
3
 
4
4
  //#region src/native/nativeAdapter.d.ts
5
5
  interface NativeOptions {
@@ -1,10 +1,12 @@
1
+ import "../plugin/paths.js";
2
+ import { seenCollection } from "./collections/seen.js";
3
+ import { ROLLUPS_SLUG, rollupsCollection } from "./collections/rollups.js";
4
+ import { EVENTS_SLUG, eventsCollection } from "./collections/events.js";
5
+ import { flushBatch } from "./ingest/flushBatch.js";
6
+ import { makeServerTrack } from "./ingest/serverTrack.js";
1
7
  import { composeGeoResolvers } from "./geo/composeGeoResolvers.js";
2
8
  import { platformHeaderResolver } from "./geo/geoResolver.js";
3
9
  import { maxmindResolver } from "./geo/maxmindResolver.js";
4
- import { EVENTS_SLUG, eventsCollection } from "./collections/events.js";
5
- import { ROLLUPS_SLUG, rollupsCollection } from "./collections/rollups.js";
6
- import { seenCollection } from "./collections/seen.js";
7
- import { flushBatch } from "./ingest/flushBatch.js";
8
10
  import { makeIngestHandler } from "./ingest/endpoint.js";
9
11
  import { createWriteBuffer } from "./ingest/writeBuffer.js";
10
12
  import { aggregateEvents, filtersToWhere } from "./query/eventAgg.js";
@@ -17,14 +19,18 @@ const metrics = new Set([
17
19
  "visitors",
18
20
  "sessions",
19
21
  "events",
20
- "avgDuration"
22
+ "avgDuration",
23
+ "conversions",
24
+ "revenue",
25
+ "scrollDepth"
21
26
  ]);
22
27
  const dimensions = new Set([
23
28
  "page",
24
29
  "country",
25
30
  "source",
26
31
  "device",
27
- "event"
32
+ "event",
33
+ "goal"
28
34
  ]);
29
35
  const REALTIME_EVENT_LIMIT = 5e4;
30
36
  const baseCapabilities = {
@@ -54,6 +60,11 @@ const baseCapabilities = {
54
60
  }
55
61
  };
56
62
  const DAY_MS = 864e5;
63
+ const nativeCapture = {
64
+ proxy: { routes: [] },
65
+ snippet: () => ({ scripts: [] }),
66
+ client: { kind: "native" }
67
+ };
57
68
  /**
58
69
  * Filtered/hour-granularity reads bypass the day-bucketed rollups and aggregate raw
59
70
  * events directly, under the same hard cap as `realtime()`. `retentionDays` clamps how
@@ -129,10 +140,22 @@ function native(options = {}) {
129
140
  });
130
141
  return docs;
131
142
  };
143
+ let resolvers = {};
144
+ const ingest = {
145
+ path: options.ingestPath ?? "/analytics/ingest",
146
+ track: makeServerTrack({
147
+ getPayload: () => payloadRef,
148
+ geoResolver,
149
+ getBuffer: () => buffer,
150
+ getResolvers: () => resolvers
151
+ })
152
+ };
132
153
  return {
133
154
  id: "native",
134
155
  label: "Native (Payload)",
135
156
  capabilities,
157
+ capture: nativeCapture,
158
+ ingest,
136
159
  isConfigured: () => true,
137
160
  flush: () => buffer?.flush() ?? Promise.resolve(),
138
161
  register(config, context) {
@@ -144,13 +167,15 @@ function native(options = {}) {
144
167
  rollupsCollection(scoped),
145
168
  seenCollection()
146
169
  ];
170
+ resolvers = {
171
+ scope: scoped ? context?.resolveScope : void 0,
172
+ timezone: context?.resolveTimezone,
173
+ goals: context?.resolveGoals
174
+ };
147
175
  config.endpoints = [...config.endpoints ?? [], {
148
176
  method: "post",
149
- path: options.ingestPath ?? "/analytics/ingest",
150
- handler: makeIngestHandler(geoResolver, () => buffer, {
151
- scope: scoped ? context?.resolveScope : void 0,
152
- timezone: context?.resolveTimezone
153
- })
177
+ path: ingest.path,
178
+ handler: makeIngestHandler(geoResolver, () => buffer, resolvers)
154
179
  }];
155
180
  if (options.retentionDays && options.retentionDays > 0) config.jobs = {
156
181
  ...config.jobs,
@@ -270,6 +295,8 @@ function native(options = {}) {
270
295
  greater_than_equal: q.dateRange.start.toISOString(),
271
296
  less_than_equal: q.dateRange.end.toISOString()
272
297
  },
298
+ ...q.hostname ? { hostname: { equals: q.hostname } } : {},
299
+ ...q.path ? { path: { equals: q.path } } : {},
273
300
  ...scopeWhere(q)
274
301
  },
275
302
  limit: REALTIME_EVENT_LIMIT,
@@ -1 +1 @@
1
- {"version":3,"file":"nativeAdapter.js","names":["events"],"sources":["../../src/native/nativeAdapter.ts"],"sourcesContent":["import type { Config, Payload } from 'payload'\nimport type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tDimensionKey,\n\tMetricKey,\n} from '../core/contract'\nimport { EVENTS_SLUG, eventsCollection } from './collections/events'\nimport { ROLLUPS_SLUG, rollupsCollection } from './collections/rollups'\nimport { seenCollection } from './collections/seen'\nimport { composeGeoResolvers } from './geo/composeGeoResolvers'\nimport { type GeoResolver, platformHeaderResolver } from './geo/geoResolver'\nimport { maxmindResolver } from './geo/maxmindResolver'\nimport { makeIngestHandler } from './ingest/endpoint'\nimport { flushBatch } from './ingest/flushBatch'\nimport type { StoredEvent } from './ingest/normalizeEvent'\nimport { createWriteBuffer, type WriteBuffer } from './ingest/writeBuffer'\nimport { aggregateEvents, type EventLike, filtersToWhere } from './query/eventAgg'\nimport { buildRealtime, type RealtimeEvent } from './realtime/buildRealtime'\nimport { pruneEventsTask } from './retention/pruneTask'\nimport {\n\ttype Acc,\n\tadd,\n\temptyAcc,\n\ttype RollupDoc,\n\tselectMetrics,\n\tseriesFromRollups,\n} from './rollupAcc'\n\nexport interface NativeOptions {\n\tgeoResolver?: GeoResolver\n\tgeoDbPath?: string\n\tingestPath?: string\n\tretentionDays?: number\n\t/** Opt-in in-process write batching. `true` uses defaults (maxSize 50, maxAgeMs 2000). */\n\tbuffer?: boolean | { maxSize?: number; maxAgeMs?: number }\n}\n\nexport type NativeAdapter = AnalyticsAdapter & { flush: () => Promise<void> }\n\nconst metrics: ReadonlySet<MetricKey> = new Set([\n\t'pageviews',\n\t'visitors',\n\t'sessions',\n\t'events',\n\t'avgDuration',\n])\nconst dimensions: ReadonlySet<DimensionKey> = new Set([\n\t'page',\n\t'country',\n\t'source',\n\t'device',\n\t'event',\n])\n\nconst REALTIME_EVENT_LIMIT = 50_000\n\nconst baseCapabilities: AnalyticsCapabilities = {\n\tperPageQuery: true,\n\trealtime: true,\n\trealtimeWindowMinutes: 60,\n\tcomparison: true,\n\tminGranularity: 'hour',\n\tmaxLookbackDays: null,\n\tmetrics,\n\tdimensions,\n\tfilters: new Set(['page', 'country', 'region', 'city', 'device', 'source', 'event']),\n\tfilterOperators: new Set(['eq', 'contains']),\n\tbatchPageReport: true,\n\trateLimit: null,\n\trecommendedTtl: { realtime: 10, aggregate: 300 },\n}\n\nconst DAY_MS = 86_400_000\n\ninterface QueryEventsContext {\n\tretentionDays?: number\n\tscopeWhere: (q: AnalyticsQuery) => Record<string, unknown>\n}\n\n/**\n * Filtered/hour-granularity reads bypass the day-bucketed rollups and aggregate raw\n * events directly, under the same hard cap as `realtime()`. `retentionDays` clamps how\n * far back the read can reach when it would otherwise ask for events the prune task has\n * already deleted (or will delete before they're queryable).\n */\nasync function queryEvents(\n\tpayload: Payload,\n\tq: AnalyticsQuery,\n\tctx: QueryEventsContext\n): Promise<AnalyticsResult> {\n\tconst fetchedAt = q.dateRange.end.toISOString()\n\tlet start = q.dateRange.start\n\tlet clamped = false\n\tif (ctx.retentionDays && ctx.retentionDays > 0) {\n\t\tconst floor = new Date(Date.now() - ctx.retentionDays * DAY_MS)\n\t\tif (start < floor) {\n\t\t\tstart = floor\n\t\t\tclamped = true\n\t\t}\n\t}\n\tconst baseWhere: Record<string, unknown> = {\n\t\ttimestamp: {\n\t\t\tgreater_than_equal: start.toISOString(),\n\t\t\tless_than_equal: q.dateRange.end.toISOString(),\n\t\t},\n\t\t...(q.hostname ? { hostname: { equals: q.hostname } } : {}),\n\t\t...(q.path ? { path: { equals: q.path } } : {}),\n\t\t...ctx.scopeWhere(q),\n\t}\n\t// filtersToWhere can also key off 'path' (a page filter); AND rather than spread so\n\t// q.path and a page filter both constrain the query instead of one overwriting the other.\n\tconst filterWhere = filtersToWhere(q.filters ?? [])\n\tconst where: Record<string, unknown> =\n\t\tObject.keys(filterWhere).length > 0 ? { and: [baseWhere, filterWhere] } : baseWhere\n\tconst { docs } = await payload.find({\n\t\tcollection: EVENTS_SLUG as never,\n\t\twhere: where as never,\n\t\t// Newest-first under a hard cap, same tradeoff as realtime(): a very busy site\n\t\t// with more events than the cap in range keeps its most recent activity.\n\t\tlimit: REALTIME_EVENT_LIMIT,\n\t\tpagination: false,\n\t\tdepth: 0,\n\t\tsort: '-timestamp',\n\t})\n\tconst events = docs as unknown as EventLike[]\n\tconst dim = q.dimensions?.find((d) => dimensions.has(d))\n\tconst granularity =\n\t\tq.granularity === 'hour' || q.granularity === 'day' ? q.granularity : undefined\n\tconst { rows, totals } = aggregateEvents(events, {\n\t\tmetrics: q.metrics,\n\t\tdimension: dim,\n\t\tgranularity,\n\t\ttimezone: q.timezone,\n\t\torder: q.order,\n\t\tlimit: q.limit,\n\t})\n\tconst meta: AnalyticsResult['meta'] = { provider: 'native', fetchedAt }\n\tif (clamped) meta.clamped = true\n\tif (events.length >= REALTIME_EVENT_LIMIT) meta.sampled = true\n\treturn { rows, totals, meta }\n}\n\nexport function native(options: NativeOptions = {}): NativeAdapter {\n\tconst geoResolver =\n\t\toptions.geoResolver ??\n\t\t(options.geoDbPath\n\t\t\t? composeGeoResolvers(platformHeaderResolver, maxmindResolver({ dbPath: options.geoDbPath }))\n\t\t\t: platformHeaderResolver)\n\t// Per-instance copy: register() flips scopedQueries when the install is scoped.\n\tconst capabilities: AnalyticsCapabilities = { ...baseCapabilities }\n\tlet payloadRef: Payload | null = null\n\tlet buffer: WriteBuffer<StoredEvent> | null = null\n\tlet scoped = false\n\n\tconst scopeWhere = (q: AnalyticsQuery): Record<string, unknown> =>\n\t\tscoped && q.scope !== undefined ? { scope: { equals: q.scope } } : {}\n\n\tconst readRollups = async (\n\t\tpayload: Payload,\n\t\twhere: Record<string, unknown>\n\t): Promise<RollupDoc[]> => {\n\t\tconst { docs } = await payload.find({\n\t\t\tcollection: ROLLUPS_SLUG as never,\n\t\t\twhere: where as never,\n\t\t\tlimit: 100_000,\n\t\t\tpagination: false,\n\t\t})\n\t\treturn docs as unknown as RollupDoc[]\n\t}\n\n\treturn {\n\t\tid: 'native',\n\t\tlabel: 'Native (Payload)',\n\t\tcapabilities,\n\t\tisConfigured: () => true,\n\t\tflush: () => buffer?.flush() ?? Promise.resolve(),\n\t\tregister(config: Config, context) {\n\t\t\tscoped = context?.scoped ?? false\n\t\t\tif (scoped) {\n\t\t\t\tcapabilities.scopedQueries = true\n\t\t\t}\n\t\t\tconfig.collections = [\n\t\t\t\t...(config.collections ?? []),\n\t\t\t\teventsCollection(scoped),\n\t\t\t\trollupsCollection(scoped),\n\t\t\t\tseenCollection(),\n\t\t\t]\n\t\t\tconfig.endpoints = [\n\t\t\t\t...(config.endpoints ?? []),\n\t\t\t\t{\n\t\t\t\t\tmethod: 'post',\n\t\t\t\t\tpath: options.ingestPath ?? '/analytics/ingest',\n\t\t\t\t\thandler: makeIngestHandler(geoResolver, () => buffer, {\n\t\t\t\t\t\tscope: scoped ? context?.resolveScope : undefined,\n\t\t\t\t\t\ttimezone: context?.resolveTimezone,\n\t\t\t\t\t}),\n\t\t\t\t},\n\t\t\t]\n\t\t\tif (options.retentionDays && options.retentionDays > 0) {\n\t\t\t\tconfig.jobs = {\n\t\t\t\t\t...config.jobs,\n\t\t\t\t\ttasks: [...(config.jobs?.tasks ?? []), pruneEventsTask(options.retentionDays)],\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst prevOnInit = config.onInit\n\t\t\t// payloadRef is set before the app's own onInit so consumer init code can\n\t\t\t// already query the native adapter.\n\t\t\tconfig.onInit = async (p) => {\n\t\t\t\tpayloadRef = p\n\t\t\t\tif (options.buffer) {\n\t\t\t\t\tconst cfg = options.buffer === true ? {} : options.buffer\n\t\t\t\t\tbuffer = createWriteBuffer<StoredEvent>({\n\t\t\t\t\t\tmaxSize: cfg.maxSize ?? 50,\n\t\t\t\t\t\tmaxAgeMs: cfg.maxAgeMs ?? 2000,\n\t\t\t\t\t\tonFlush: (batch) => flushBatch(p, batch),\n\t\t\t\t\t\tonError: (error) => {\n\t\t\t\t\t\t\tp.logger.error({ err: error, msg: 'analytics: write buffer flush failed' })\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tawait prevOnInit?.(p)\n\t\t\t}\n\t\t},\n\t\tasync query(q: AnalyticsQuery): Promise<AnalyticsResult> {\n\t\t\tif (!payloadRef) {\n\t\t\t\tthrow new Error('analytics: native adapter queried before init')\n\t\t\t}\n\t\t\tif ((q.filters && q.filters.length > 0) || q.granularity === 'hour') {\n\t\t\t\treturn queryEvents(payloadRef, q, { retentionDays: options.retentionDays, scopeWhere })\n\t\t\t}\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst periodWhere = {\n\t\t\t\tgreater_than_equal: q.dateRange.start.toISOString(),\n\t\t\t\tless_than_equal: q.dateRange.end.toISOString(),\n\t\t\t}\n\t\t\tconst dim = q.dimensions?.find((d) => dimensions.has(d))\n\n\t\t\t// Distinct metrics (visitors/sessions) must not be summed across breakdown rows.\n\t\t\t// Totals always come from the non-dimensioned aggregate row. A dimensioned query\n\t\t\t// reports site-wide totals (path=''), a plain query uses the path-scoped row.\n\t\t\tconst totalsPath = dim ? '' : (q.path ?? '')\n\t\t\tconst totalsDocs = await readRollups(payloadRef, {\n\t\t\t\tgranularity: { equals: 'day' },\n\t\t\t\tdimension: { equals: '' },\n\t\t\t\tpath: { equals: totalsPath },\n\t\t\t\thostname: { equals: q.hostname ?? '' },\n\t\t\t\tperiod: periodWhere,\n\t\t\t\t...scopeWhere(q),\n\t\t\t})\n\t\t\tconst totalsAcc = emptyAcc()\n\t\t\tfor (const d of totalsDocs) {\n\t\t\t\tadd(totalsAcc, d)\n\t\t\t}\n\t\t\tconst totals = selectMetrics(totalsAcc, q.metrics)\n\n\t\t\tif (!dim) {\n\t\t\t\tif (q.granularity === 'day') {\n\t\t\t\t\treturn {\n\t\t\t\t\t\trows: seriesFromRollups(totalsDocs, q.metrics, q.timezone),\n\t\t\t\t\t\ttotals,\n\t\t\t\t\t\tmeta: { provider: 'native', fetchedAt },\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { rows: [{ metrics: totals }], totals, meta: { provider: 'native', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst breakdownWhere =\n\t\t\t\tdim === 'page'\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tgranularity: { equals: 'day' },\n\t\t\t\t\t\t\tdimension: { equals: '' },\n\t\t\t\t\t\t\tpath: { not_equals: '' },\n\t\t\t\t\t\t\thostname: { equals: q.hostname ?? '' },\n\t\t\t\t\t\t\tperiod: periodWhere,\n\t\t\t\t\t\t\t...scopeWhere(q),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {\n\t\t\t\t\t\t\tgranularity: { equals: 'day' },\n\t\t\t\t\t\t\tdimension: { equals: dim },\n\t\t\t\t\t\t\tpath: { equals: '' },\n\t\t\t\t\t\t\thostname: { equals: q.hostname ?? '' },\n\t\t\t\t\t\t\tperiod: periodWhere,\n\t\t\t\t\t\t\t...scopeWhere(q),\n\t\t\t\t\t\t}\n\t\t\tconst groups = new Map<string, Acc>()\n\t\t\tfor (const d of await readRollups(payloadRef, breakdownWhere)) {\n\t\t\t\tconst value = dim === 'page' ? d.path : d.dimvalue\n\t\t\t\tlet acc = groups.get(value)\n\t\t\t\tif (!acc) {\n\t\t\t\t\tacc = emptyAcc()\n\t\t\t\t\tgroups.set(value, acc)\n\t\t\t\t}\n\t\t\t\tadd(acc, d)\n\t\t\t}\n\t\t\tlet rows: AnalyticsRow[] = [...groups].map(([value, acc]) => ({\n\t\t\t\tdimensions: { [dim]: value } as Partial<Record<DimensionKey, string>>,\n\t\t\t\tmetrics: selectMetrics(acc, q.metrics),\n\t\t\t}))\n\t\t\tconst sortMetric = q.order?.metric ?? 'pageviews'\n\t\t\tconst direction = (q.order?.direction ?? 'desc') === 'asc' ? 1 : -1\n\t\t\trows.sort((a, b) => ((a.metrics[sortMetric] ?? 0) - (b.metrics[sortMetric] ?? 0)) * direction)\n\t\t\tif (q.limit) {\n\t\t\t\trows = rows.slice(0, q.limit)\n\t\t\t}\n\t\t\treturn { rows, totals, meta: { provider: 'native', fetchedAt } }\n\t\t},\n\t\tasync realtime(q: AnalyticsQuery, _ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tif (!payloadRef) {\n\t\t\t\tthrow new Error('analytics: native adapter queried before init')\n\t\t\t}\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst { docs } = await payloadRef.find({\n\t\t\t\tcollection: EVENTS_SLUG as never,\n\t\t\t\twhere: {\n\t\t\t\t\ttimestamp: {\n\t\t\t\t\t\tgreater_than_equal: q.dateRange.start.toISOString(),\n\t\t\t\t\t\tless_than_equal: q.dateRange.end.toISOString(),\n\t\t\t\t\t},\n\t\t\t\t\t...scopeWhere(q),\n\t\t\t\t} as never,\n\t\t\t\t// Newest-first under a hard cap: if a very busy site has more events than the\n\t\t\t\t// cap in the window, keep the most recent activity rather than the oldest.\n\t\t\t\t// Unbounded accuracy via DB-side aggregation is deferred to the hardening spec.\n\t\t\t\tlimit: REALTIME_EVENT_LIMIT,\n\t\t\t\tpagination: false,\n\t\t\t\tdepth: 0,\n\t\t\t\tsort: '-timestamp',\n\t\t\t})\n\t\t\tconst events = docs as unknown as RealtimeEvent[]\n\t\t\tconst { rows, totals } = buildRealtime(events, q.dateRange, q.metrics)\n\t\t\treturn { rows, totals, meta: { provider: 'native', fetchedAt } }\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;AA4CA,MAAM,UAAkC,IAAI,IAAI;CAC/C;CACA;CACA;CACA;CACA;AACD,CAAC;AACD,MAAM,aAAwC,IAAI,IAAI;CACrD;CACA;CACA;CACA;CACA;AACD,CAAC;AAED,MAAM,uBAAuB;AAE7B,MAAM,mBAA0C;CAC/C,cAAc;CACd,UAAU;CACV,uBAAuB;CACvB,YAAY;CACZ,gBAAgB;CAChB,iBAAiB;CACjB;CACA;CACA,SAAS,IAAI,IAAI;EAAC;EAAQ;EAAW;EAAU;EAAQ;EAAU;EAAU;CAAO,CAAC;CACnF,iBAAiB,IAAI,IAAI,CAAC,MAAM,UAAU,CAAC;CAC3C,iBAAiB;CACjB,WAAW;CACX,gBAAg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jE,KAAK,MAAM,GAAG,QAAQ,EAAE,QAAQ,eAAe,MAAM,EAAE,QAAQ,eAAe,MAAM,SAAS;GAC7F,IAAI,EAAE,OACL,OAAO,KAAK,MAAM,GAAG,EAAE,KAAK;GAE7B,OAAO;IAAE;IAAM;IAAQ,MAAM;KAAE,UAAU;KAAU;IAAU;GAAE;EAChE;EACA,MAAM,SAAS,GAAmB,MAAgD;GACjF,IAAI,CAAC,YACJ,MAAM,IAAI,MAAM,+CAA+C;GAEhE,MAAM,YAAY,EAAE,UAAU,IAAI,YAAY;GAC9C,MAAM,EAAE,SAAS,MAAM,WAAW,KAAK;IACtC,YAAY;IACZ,OAAO;KACN,WAAW;MACV,oBAAoB,EAAE,UAAU,MAAM,YAAY;MAClD,iBAAiB,EAAE,UAAU,IAAI,YAAY;KAC9C;KACA,GAAG,WAAW,CAAC;IAChB;IAIA,OAAO;IACP,YAAY;IACZ,OAAO;IACP,MAAM;GACP,CAAC;GAED,MAAM,EAAE,MAAM,WAAW,cAAcA,MAAQ,EAAE,WAAW,EAAE,OAAO;GACrE,OAAO;IAAE;IAAM;IAAQ,MAAM;KAAE,UAAU;KAAU;IAAU;GAAE;EAChE;CACD;AACD"}
1
+ {"version":3,"file":"nativeAdapter.js","names":["events"],"sources":["../../src/native/nativeAdapter.ts"],"sourcesContent":["import type { Config, Payload } from 'payload'\nimport type { CaptureSupport } from '../core/capture'\nimport type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tDimensionKey,\n\tMetricKey,\n} from '../core/contract'\nimport { INGEST_PATH } from '../plugin/paths'\nimport { EVENTS_SLUG, eventsCollection } from './collections/events'\nimport { ROLLUPS_SLUG, rollupsCollection } from './collections/rollups'\nimport { seenCollection } from './collections/seen'\nimport { composeGeoResolvers } from './geo/composeGeoResolvers'\nimport { type GeoResolver, platformHeaderResolver } from './geo/geoResolver'\nimport { maxmindResolver } from './geo/maxmindResolver'\nimport { type IngestResolvers, makeIngestHandler } from './ingest/endpoint'\nimport { flushBatch } from './ingest/flushBatch'\nimport type { StoredEvent } from './ingest/normalizeEvent'\nimport { makeServerTrack } from './ingest/serverTrack'\nimport { createWriteBuffer, type WriteBuffer } from './ingest/writeBuffer'\nimport { aggregateEvents, type EventLike, filtersToWhere } from './query/eventAgg'\nimport { buildRealtime, type RealtimeEvent } from './realtime/buildRealtime'\nimport { pruneEventsTask } from './retention/pruneTask'\nimport {\n\ttype Acc,\n\tadd,\n\temptyAcc,\n\ttype RollupDoc,\n\tselectMetrics,\n\tseriesFromRollups,\n} from './rollupAcc'\n\nexport interface NativeOptions {\n\tgeoResolver?: GeoResolver\n\tgeoDbPath?: string\n\tingestPath?: string\n\tretentionDays?: number\n\t/** Opt-in in-process write batching. `true` uses defaults (maxSize 50, maxAgeMs 2000). */\n\tbuffer?: boolean | { maxSize?: number; maxAgeMs?: number }\n}\n\nexport type NativeAdapter = AnalyticsAdapter & { flush: () => Promise<void> }\n\nconst metrics: ReadonlySet<MetricKey> = new Set([\n\t'pageviews',\n\t'visitors',\n\t'sessions',\n\t'events',\n\t'avgDuration',\n\t'conversions',\n\t'revenue',\n\t'scrollDepth',\n])\nconst dimensions: ReadonlySet<DimensionKey> = new Set([\n\t'page',\n\t'country',\n\t'source',\n\t'device',\n\t'event',\n\t'goal',\n])\n\nconst REALTIME_EVENT_LIMIT = 50_000\n\nconst baseCapabilities: AnalyticsCapabilities = {\n\tperPageQuery: true,\n\trealtime: true,\n\trealtimeWindowMinutes: 60,\n\tcomparison: true,\n\tminGranularity: 'hour',\n\tmaxLookbackDays: null,\n\tmetrics,\n\tdimensions,\n\tfilters: new Set(['page', 'country', 'region', 'city', 'device', 'source', 'event']),\n\tfilterOperators: new Set(['eq', 'contains']),\n\tbatchPageReport: true,\n\trateLimit: null,\n\trecommendedTtl: { realtime: 10, aggregate: 300 },\n}\n\nconst DAY_MS = 86_400_000\n\n// The tracker itself is the client (an RSC renders TrackerBoot), so there is nothing to\n// proxy or inject; the ingest path is carried by the tracker config resolver instead.\nconst nativeCapture: CaptureSupport = {\n\tproxy: { routes: [] },\n\tsnippet: () => ({ scripts: [] }),\n\tclient: { kind: 'native' },\n}\n\ninterface QueryEventsContext {\n\tretentionDays?: number\n\tscopeWhere: (q: AnalyticsQuery) => Record<string, unknown>\n}\n\n/**\n * Filtered/hour-granularity reads bypass the day-bucketed rollups and aggregate raw\n * events directly, under the same hard cap as `realtime()`. `retentionDays` clamps how\n * far back the read can reach when it would otherwise ask for events the prune task has\n * already deleted (or will delete before they're queryable).\n */\nasync function queryEvents(\n\tpayload: Payload,\n\tq: AnalyticsQuery,\n\tctx: QueryEventsContext\n): Promise<AnalyticsResult> {\n\tconst fetchedAt = q.dateRange.end.toISOString()\n\tlet start = q.dateRange.start\n\tlet clamped = false\n\tif (ctx.retentionDays && ctx.retentionDays > 0) {\n\t\tconst floor = new Date(Date.now() - ctx.retentionDays * DAY_MS)\n\t\tif (start < floor) {\n\t\t\tstart = floor\n\t\t\tclamped = true\n\t\t}\n\t}\n\tconst baseWhere: Record<string, unknown> = {\n\t\ttimestamp: {\n\t\t\tgreater_than_equal: start.toISOString(),\n\t\t\tless_than_equal: q.dateRange.end.toISOString(),\n\t\t},\n\t\t...(q.hostname ? { hostname: { equals: q.hostname } } : {}),\n\t\t...(q.path ? { path: { equals: q.path } } : {}),\n\t\t...ctx.scopeWhere(q),\n\t}\n\t// filtersToWhere can also key off 'path' (a page filter); AND rather than spread so\n\t// q.path and a page filter both constrain the query instead of one overwriting the other.\n\tconst filterWhere = filtersToWhere(q.filters ?? [])\n\tconst where: Record<string, unknown> =\n\t\tObject.keys(filterWhere).length > 0 ? { and: [baseWhere, filterWhere] } : baseWhere\n\tconst { docs } = await payload.find({\n\t\tcollection: EVENTS_SLUG as never,\n\t\twhere: where as never,\n\t\t// Newest-first under a hard cap, same tradeoff as realtime(): a very busy site\n\t\t// with more events than the cap in range keeps its most recent activity.\n\t\tlimit: REALTIME_EVENT_LIMIT,\n\t\tpagination: false,\n\t\tdepth: 0,\n\t\tsort: '-timestamp',\n\t})\n\tconst events = docs as unknown as EventLike[]\n\tconst dim = q.dimensions?.find((d) => dimensions.has(d))\n\tconst granularity =\n\t\tq.granularity === 'hour' || q.granularity === 'day' ? q.granularity : undefined\n\tconst { rows, totals } = aggregateEvents(events, {\n\t\tmetrics: q.metrics,\n\t\tdimension: dim,\n\t\tgranularity,\n\t\ttimezone: q.timezone,\n\t\torder: q.order,\n\t\tlimit: q.limit,\n\t})\n\tconst meta: AnalyticsResult['meta'] = { provider: 'native', fetchedAt }\n\tif (clamped) meta.clamped = true\n\tif (events.length >= REALTIME_EVENT_LIMIT) meta.sampled = true\n\treturn { rows, totals, meta }\n}\n\nexport function native(options: NativeOptions = {}): NativeAdapter {\n\tconst geoResolver =\n\t\toptions.geoResolver ??\n\t\t(options.geoDbPath\n\t\t\t? composeGeoResolvers(platformHeaderResolver, maxmindResolver({ dbPath: options.geoDbPath }))\n\t\t\t: platformHeaderResolver)\n\t// Per-instance copy: register() flips scopedQueries when the install is scoped.\n\tconst capabilities: AnalyticsCapabilities = { ...baseCapabilities }\n\tlet payloadRef: Payload | null = null\n\tlet buffer: WriteBuffer<StoredEvent> | null = null\n\tlet scoped = false\n\n\tconst scopeWhere = (q: AnalyticsQuery): Record<string, unknown> =>\n\t\tscoped && q.scope !== undefined ? { scope: { equals: q.scope } } : {}\n\n\tconst readRollups = async (\n\t\tpayload: Payload,\n\t\twhere: Record<string, unknown>\n\t): Promise<RollupDoc[]> => {\n\t\tconst { docs } = await payload.find({\n\t\t\tcollection: ROLLUPS_SLUG as never,\n\t\t\twhere: where as never,\n\t\t\tlimit: 100_000,\n\t\t\tpagination: false,\n\t\t})\n\t\treturn docs as unknown as RollupDoc[]\n\t}\n\n\t// The plugin's resolvers arrive in register(); server tracking reads them late so it\n\t// resolves the same scope, timezone and goals the endpoint does.\n\tlet resolvers: IngestResolvers = {}\n\n\tconst ingest = {\n\t\tpath: options.ingestPath ?? INGEST_PATH,\n\t\ttrack: makeServerTrack({\n\t\t\tgetPayload: () => payloadRef,\n\t\t\tgeoResolver,\n\t\t\tgetBuffer: () => buffer,\n\t\t\tgetResolvers: () => resolvers,\n\t\t}),\n\t}\n\n\treturn {\n\t\tid: 'native',\n\t\tlabel: 'Native (Payload)',\n\t\tcapabilities,\n\t\tcapture: nativeCapture,\n\t\tingest,\n\t\tisConfigured: () => true,\n\t\tflush: () => buffer?.flush() ?? Promise.resolve(),\n\t\tregister(config: Config, context) {\n\t\t\tscoped = context?.scoped ?? false\n\t\t\tif (scoped) {\n\t\t\t\tcapabilities.scopedQueries = true\n\t\t\t}\n\t\t\tconfig.collections = [\n\t\t\t\t...(config.collections ?? []),\n\t\t\t\teventsCollection(scoped),\n\t\t\t\trollupsCollection(scoped),\n\t\t\t\tseenCollection(),\n\t\t\t]\n\t\t\tresolvers = {\n\t\t\t\tscope: scoped ? context?.resolveScope : undefined,\n\t\t\t\ttimezone: context?.resolveTimezone,\n\t\t\t\tgoals: context?.resolveGoals,\n\t\t\t}\n\t\t\tconfig.endpoints = [\n\t\t\t\t...(config.endpoints ?? []),\n\t\t\t\t{\n\t\t\t\t\tmethod: 'post',\n\t\t\t\t\tpath: ingest.path,\n\t\t\t\t\thandler: makeIngestHandler(geoResolver, () => buffer, resolvers),\n\t\t\t\t},\n\t\t\t]\n\t\t\tif (options.retentionDays && options.retentionDays > 0) {\n\t\t\t\tconfig.jobs = {\n\t\t\t\t\t...config.jobs,\n\t\t\t\t\ttasks: [...(config.jobs?.tasks ?? []), pruneEventsTask(options.retentionDays)],\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst prevOnInit = config.onInit\n\t\t\t// payloadRef is set before the app's own onInit so consumer init code can\n\t\t\t// already query the native adapter.\n\t\t\tconfig.onInit = async (p) => {\n\t\t\t\tpayloadRef = p\n\t\t\t\tif (options.buffer) {\n\t\t\t\t\tconst cfg = options.buffer === true ? {} : options.buffer\n\t\t\t\t\tbuffer = createWriteBuffer<StoredEvent>({\n\t\t\t\t\t\tmaxSize: cfg.maxSize ?? 50,\n\t\t\t\t\t\tmaxAgeMs: cfg.maxAgeMs ?? 2000,\n\t\t\t\t\t\tonFlush: (batch) => flushBatch(p, batch),\n\t\t\t\t\t\tonError: (error) => {\n\t\t\t\t\t\t\tp.logger.error({ err: error, msg: 'analytics: write buffer flush failed' })\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tawait prevOnInit?.(p)\n\t\t\t}\n\t\t},\n\t\tasync query(q: AnalyticsQuery): Promise<AnalyticsResult> {\n\t\t\tif (!payloadRef) {\n\t\t\t\tthrow new Error('analytics: native adapter queried before init')\n\t\t\t}\n\t\t\tif ((q.filters && q.filters.length > 0) || q.granularity === 'hour') {\n\t\t\t\treturn queryEvents(payloadRef, q, { retentionDays: options.retentionDays, scopeWhere })\n\t\t\t}\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst periodWhere = {\n\t\t\t\tgreater_than_equal: q.dateRange.start.toISOString(),\n\t\t\t\tless_than_equal: q.dateRange.end.toISOString(),\n\t\t\t}\n\t\t\tconst dim = q.dimensions?.find((d) => dimensions.has(d))\n\n\t\t\t// Distinct metrics (visitors/sessions) must not be summed across breakdown rows.\n\t\t\t// Totals always come from the non-dimensioned aggregate row. A dimensioned query\n\t\t\t// reports site-wide totals (path=''), a plain query uses the path-scoped row.\n\t\t\tconst totalsPath = dim ? '' : (q.path ?? '')\n\t\t\tconst totalsDocs = await readRollups(payloadRef, {\n\t\t\t\tgranularity: { equals: 'day' },\n\t\t\t\tdimension: { equals: '' },\n\t\t\t\tpath: { equals: totalsPath },\n\t\t\t\thostname: { equals: q.hostname ?? '' },\n\t\t\t\tperiod: periodWhere,\n\t\t\t\t...scopeWhere(q),\n\t\t\t})\n\t\t\tconst totalsAcc = emptyAcc()\n\t\t\tfor (const d of totalsDocs) {\n\t\t\t\tadd(totalsAcc, d)\n\t\t\t}\n\t\t\tconst totals = selectMetrics(totalsAcc, q.metrics)\n\n\t\t\tif (!dim) {\n\t\t\t\tif (q.granularity === 'day') {\n\t\t\t\t\treturn {\n\t\t\t\t\t\trows: seriesFromRollups(totalsDocs, q.metrics, q.timezone),\n\t\t\t\t\t\ttotals,\n\t\t\t\t\t\tmeta: { provider: 'native', fetchedAt },\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { rows: [{ metrics: totals }], totals, meta: { provider: 'native', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst breakdownWhere =\n\t\t\t\tdim === 'page'\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tgranularity: { equals: 'day' },\n\t\t\t\t\t\t\tdimension: { equals: '' },\n\t\t\t\t\t\t\tpath: { not_equals: '' },\n\t\t\t\t\t\t\thostname: { equals: q.hostname ?? '' },\n\t\t\t\t\t\t\tperiod: periodWhere,\n\t\t\t\t\t\t\t...scopeWhere(q),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {\n\t\t\t\t\t\t\tgranularity: { equals: 'day' },\n\t\t\t\t\t\t\tdimension: { equals: dim },\n\t\t\t\t\t\t\tpath: { equals: '' },\n\t\t\t\t\t\t\thostname: { equals: q.hostname ?? '' },\n\t\t\t\t\t\t\tperiod: periodWhere,\n\t\t\t\t\t\t\t...scopeWhere(q),\n\t\t\t\t\t\t}\n\t\t\tconst groups = new Map<string, Acc>()\n\t\t\tfor (const d of await readRollups(payloadRef, breakdownWhere)) {\n\t\t\t\tconst value = dim === 'page' ? d.path : d.dimvalue\n\t\t\t\tlet acc = groups.get(value)\n\t\t\t\tif (!acc) {\n\t\t\t\t\tacc = emptyAcc()\n\t\t\t\t\tgroups.set(value, acc)\n\t\t\t\t}\n\t\t\t\tadd(acc, d)\n\t\t\t}\n\t\t\tlet rows: AnalyticsRow[] = [...groups].map(([value, acc]) => ({\n\t\t\t\tdimensions: { [dim]: value } as Partial<Record<DimensionKey, string>>,\n\t\t\t\tmetrics: selectMetrics(acc, q.metrics),\n\t\t\t}))\n\t\t\tconst sortMetric = q.order?.metric ?? 'pageviews'\n\t\t\tconst direction = (q.order?.direction ?? 'desc') === 'asc' ? 1 : -1\n\t\t\trows.sort((a, b) => ((a.metrics[sortMetric] ?? 0) - (b.metrics[sortMetric] ?? 0)) * direction)\n\t\t\tif (q.limit) {\n\t\t\t\trows = rows.slice(0, q.limit)\n\t\t\t}\n\t\t\treturn { rows, totals, meta: { provider: 'native', fetchedAt } }\n\t\t},\n\t\tasync realtime(q: AnalyticsQuery, _ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tif (!payloadRef) {\n\t\t\t\tthrow new Error('analytics: native adapter queried before init')\n\t\t\t}\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst { docs } = await payloadRef.find({\n\t\t\t\tcollection: EVENTS_SLUG as never,\n\t\t\t\twhere: {\n\t\t\t\t\ttimestamp: {\n\t\t\t\t\t\tgreater_than_equal: q.dateRange.start.toISOString(),\n\t\t\t\t\t\tless_than_equal: q.dateRange.end.toISOString(),\n\t\t\t\t\t},\n\t\t\t\t\t...(q.hostname ? { hostname: { equals: q.hostname } } : {}),\n\t\t\t\t\t...(q.path ? { path: { equals: q.path } } : {}),\n\t\t\t\t\t...scopeWhere(q),\n\t\t\t\t} as never,\n\t\t\t\t// Newest-first under a hard cap: if a very busy site has more events than the\n\t\t\t\t// cap in the window, keep the most recent activity rather than the oldest.\n\t\t\t\t// Unbounded accuracy via DB-side aggregation is deferred to the hardening spec.\n\t\t\t\tlimit: REALTIME_EVENT_LIMIT,\n\t\t\t\tpagination: false,\n\t\t\t\tdepth: 0,\n\t\t\t\tsort: '-timestamp',\n\t\t\t})\n\t\t\tconst events = docs as unknown as RealtimeEvent[]\n\t\t\tconst { rows, totals } = buildRealtime(events, q.dateRange, q.metrics)\n\t\t\treturn { rows, totals, meta: { provider: 'native', fetchedAt } }\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;A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