@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
package/CHANGELOG.md CHANGED
@@ -1,5 +1,78 @@
1
1
  # @10x-media/analytics
2
2
 
3
+ ## 1.0.0-beta.8
4
+
5
+ ### Minor Changes
6
+
7
+ - **Additive: goal surfaces.** `goals.collection` (`true`, or `{ enabled, slug, scopeField, access, overrides }`) enables an `analytics-goals` collection scoped exactly like providers: rows filter by the request's resolved scope, `scope` is stamped on write and a forged one is refused, platform admins read every scope, and slugs are unique per scope, checked on every write and backed by a unique index on `slug` for an unscoped install or on `(slug, scope)` once a `scopeResolver` is configured and the plugin owns the scope field. Two cases stay hook-guarded only: install-wide rows on a scoped Postgres install (Postgres treats a NULL scope as distinct), and a host-owned `scopeField`, which the plugin does not index. Enabled collection goals merge over config goals by slug, cached for 30 seconds per scope and invalidated on change (one read serves at most 500 enabled goals per scope), and reach the native ingest, the browser tracker config and the new `GET /api/analytics/goals` endpoint (authenticated, per scope, `{ goals: [{ slug, name, source }], collection }`).
8
+
9
+ `goalField()` is a field factory that stores a goal slug behind a picker of the request's goals, with `goalSlug()` for renderers; the picker follows native field rules (`admin.condition`, `admin.width`, `admin.description`, `admin.placeholder`), and it, `SourceSelectField` and `MetricSelectField` now resolve their path through Payload's field context, so all three behave inside blocks and array rows. `@10x-media/analytics/client` gains `GoalSelectField` and `useAnalyticsGoals` plus the `GoalsResponse` and `WireGoal` wire types, and `GoalFieldOptions` is exported from both the root and `/types`.
10
+
11
+ `trackServerEvent(payload, event, { req, flush })` records a pageview, event or goal from server code through the native ingest (no HTTP round trip, same sanitizers and goal matching). With `req` the event inherits that request's headers, so geo, device and the visitor hash follow the real request; with neither a `req` nor an explicit `userAgent` it is attributed to a stable synthetic server visitor per day per hostname and reports no device at all rather than counting as desktop. `flush: true` awaits a buffered write. An explicit `scope` is ignored on an unscoped install and is never validated against the scopes that exist. A missing required field rejects with `AnalyticsTrackError` naming the field, and nothing is written. Needs the native adapter.
12
+
13
+ `trackGoalAction({ hostname, path, scope })` returns a form-builder action definition (type `analyticsGoal`, exported as `GOAL_ACTION_TYPE`) with no form-builder dependency; register it as `actions: { [GOAL_ACTION_TYPE]: trackGoalAction({ hostname: 'example.com' }) }`. Treat `hostname` as required wherever a jobs runner queues actions, and `scope` as required there on a scoped install: a queued run carries the runner's request rather than the submitter's, so the fallback chain (option, request host, `serverURL` host, then throw) has nothing useful to fall back to. The action is not `essential`, so a failed write never fails the submission.
14
+
15
+ **Breaking (scoped installs on a custom scope field):** where `providers.collection.scopeField` or `goals.collection.scopeField` names a field the plugin does not own, the plugin no longer adds its own hidden `scope` text field to that collection, since shadowing the host's field stored the scope twice. Generated types change accordingly, and a scoped Postgres install on a custom `scopeField` wants a migration dropping the now-unused `scope` column. Boot also fails with a named error when the collection carries no field of that name (`analytics: goals.collection.scopeField "tenant" does not exist on analytics-goals; register the collection with your tenant plugin or use the default scope field`), where the same misconfiguration previously booted and misbehaved silently.
16
+
17
+ **Behavioral:** `resolveGoals` on the adapter register context and on the runtime resolves per scope once the collection is enabled, and a collection goal replaces the config goal of the same slug. The public tracker config, which was a snapshot of the config goals, now carries the request scope's merged goals, still trimmed to `slug`, `match`, `value` and `currency`, so an editor's fixed value and currency reach `trackGoal()` defaults and vendor sinks; a change reaches browsers within the 30 second resolver cache plus that endpoint's own `Cache-Control: private, max-age=60`. `AnalyticsAdapter.ingest` gains an optional `track`.
18
+
19
+ **Consumer steps:** regenerate the admin import map (`payload generate:importmap`) once a `goalField()` is in the config, so `GoalSelectField` resolves. On Postgres, enabling `goals.collection` adds a table: run `payload migrate:create` in the app afterwards, which generates the DDL from the collection config the way every other schema change in this plugin does.
20
+
21
+ Multi-tenant note: the goals collection uses the plugin's own `scope` field and the plugin's scope resolver. Registering it with `@payloadcms/plugin-multi-tenant` (a `tenant` relationship through `scopeField` plus an entry in that plugin's `collections`) is not supported yet: it hangs a tenant user's admin panel in the dev app and the cause is not diagnosed. Providers still support that wiring (`isGlobal: true`). Goals scope correctly either way (access, stamping, per-scope uniqueness, the picker, the tracker config and the endpoint all follow the resolved scope); what a multi-tenant install gives up today is the tenant selector filtering the goals list view. A fix is planned.
22
+
23
+ - **Additive: query endpoint.** `GET /api/analytics/query` reads any configured source through the surfacing engine for signed-in users allowed by `access.read`: metrics, up to two dimensions, a date range, granularity, filters, ordering, a row limit and an optional previous-period comparison, validated against the selected source's capabilities with coded `400` errors (`invalid_param`, `unsupported_metric`, `unsupported_dimension`, `unsupported_filter`, `unsupported_operator`, `unsupported_granularity`, `range_too_long`). Scope follows the same rules as the sources endpoint: it comes from the request, an explicit `scope` is honored only for platform readers (`400 untrusted_scope` otherwise), and a scoped install with no resolvable scope answers `404 unknown_source`. A listed shared source that cannot filter by scope still answers `403` for a tenant reader. Responses carry the normalized query (ISO date range), the source and its capabilities, and `meta.stale` when the engine served an expired cache entry; a provider outage with no cached answer is `503 unavailable` with `Retry-After`, and every answer is `Cache-Control: private, no-store`. Date-only bounds are interpreted in the reporting timezone (the whole `to` day included); datetime bounds must carry an offset. `fetchQuery`, `buildQueryUrl` and `QueryFetchError` from `/client` wrap the endpoint for admin code, and `QueryRequest` carries every parameter including the optional `scope` a platform reader needs; `QueryRequest`, `QueryResponse`, `QueryError` and the parser's own result types are exported from `/types`, where the contract's own key registries are now runtime values too: `DIMENSION_KEYS` and `FILTER_OPERATORS`, named here because picker and validator authors want the list rather than only the union type.
24
+
25
+ **Additive: `access.read`.** A new access option gating every authenticated read endpoint (document, realtime, sources, goals, query); it defaults to allowing any signed-in user, so existing installs see no change until they set it. It is independent of scope gating: granting `read` never widens which scope a user reads.
26
+
27
+ **Behavioral:** a `scopeResolver` that answers the platform wildcard (`'*'`) now requires `access.platformRead` on the sources endpoint too, so a non-platform user gets an empty source list instead of the config adapters.
28
+
29
+ **Behavioral:** GA4 and Plausible reads now format both range bounds as calendar days in the reporting timezone, and every widget and field on those two providers with a non-UTC `reportingTimezone` changes its numbers as a result. East of UTC the start date was one calendar day early, so a 30-day widget was querying 31 days and totals drop after the upgrade; west of UTC the end date named the following UTC day whenever local time was past the UTC rollover, so a trailing partial day is no longer included. Native, PostHog and Umami installs are unaffected.
30
+
31
+ - **Additive: analytics view.** A dedicated admin view at `/admin/analytics` (option `view: { path, defaultRange, defaultMetric, navLabel }`, `view: false` to disable, `access.view` to gate it, defaulting to `access.read`) built on the query endpoint. It shows overview cards with a previous-period comparison, a trend, capability-gated breakdown tabs (pages, sources, technology, geography, events, goals) with click-to-filter chips, a goals panel with conversion rate, and a realtime strip, for any configured source. Range, comparison, source, metric, granularity, tab, filters, row limit and sort live in the URL, so a view is a shareable link and Back undoes a change. Every control appears only when the selected source's capabilities allow it. Scope follows the request (the tenant selector on multi-tenant installs). `AnalyticsView` is exported from `/rsc`, `AnalyticsViewClient` and `AnalyticsNavLink` from `/client`, the option types from `/types`; `AnalyticsViewClientProps` gains `scopeKey`, the resolved scope the server rendered for, which keys the client so a tenant switch refetches. `@payloadcms/next` and `next` are now peer dependencies.
32
+
33
+ **Additive:** `BarList` gains two optional props. `onSelect` makes every row a button reporting its index (rows stay inert `div`s without it), and `fill="soft"` pales the bar and moves its label onto the elevation ramp, for a list whose rows can be zero-valued; the default `fill="solid"` is exactly the current widget look.
34
+
35
+ **Behavioral:** the admin gains an "Analytics" nav link and the `/analytics` route by default; set `view: false` to opt out. The `visits` metric is now labelled "Visits" wherever a metric label is rendered (display fields, the document panel and the view's cards); it carried the "Visitors" label before. No widget metric picker offers `visits`, so widget configuration is unaffected.
36
+
37
+ **Breaking: custom ranges follow the reporting timezone.** A custom widget range and a document read with a custom `from`/`to` now interpret the picked days in the reporting timezone and include the whole final day; captions show the picked days. Previously the picker's stored instant (the admin browser's local midnight) was used as-is, so the final day was mostly dropped and providers could disagree by hemisphere. Numbers move on installs whose admin browsers sit in a different zone from the reporting timezone, and on instant-comparing reads (filtered or hour-granular native reads, and the vendor adapters' calendar-day formatting), which used to drop the final day; day-rollup reads where the two zones coincide were already right. The picked day is recovered from a stored instant exactly for every browser offset in `(-12, +12]`; a browser at +12:45 or beyond recovers the previous day. Day strings (`YYYY-MM-DD`) are accepted on the document endpoint; offset-less datetimes and zero-width instant windows are rejected.
38
+
39
+ **Behavioral: cache keys for a closed window carry its exact bounds.** A window ending on the final instant of its day is no longer day-snapped in the cache key, so an entry cached under the old, narrower window is never served after this upgrade. That covers every custom range and every comparison window, presets included (a previous period ends 1ms before the current window's first day), so each of those re-keys once and reads cold the first time after upgrading. Live preset windows, which end at `now`, keep their day-snapped key and their hit rate. The warm task re-keys its custom-range targets on the stored days and resolves them per scope, so it warms the keys a non-UTC install's widgets actually request.
40
+
41
+ - **Additive: more widgets.** Five new breakdown widgets (referrers, browsers, operating systems, campaigns, events) register from the same table as the existing ones, each gated on its own dimension. A goals widget (`analytics-goals`) lists conversions, revenue and conversion rate per goal for the widget's timeframe, under each goal's own name, with a previous-period delta on conversions when comparison is on; it needs a source that serves both `conversions` and the `goal` dimension, and costs one engine read, plus one for the rate's denominator where the source serves `visitors`, plus one for the deltas with comparison on. Every built-in widget gains an "Open in Analytics" link that opens the analytics view on the widget's source, range, metric or tab; the source is the adapter that actually served the widget, not the id it asked for, and the link serializes against the install's own `view.defaultRange` / `view.defaultMetric`, so anything already on a default is left out. A custom range becomes two day strings in the reporting timezone, clamped to the last 366 days of the window where it is wider than the view can hold; `allTime`, `thisMonth` and `thisYear` are windows the view's range picker does not offer, so those links carry no range and open the view on its default. The link disappears with `view: false`.
42
+
43
+ `TrendChart` accepts `comparison`, `comparisonLabel`, `comparisonRange` and `label` (and `TrendPoint` is exported from `/client`), drawing the previous period as a muted line on a y-scale covering both series, with a legend that carries the previous window's range and a tooltip row per series. The trend widget gains a "Compare to previous period" checkbox (off by default, absent when `widgets.comparison` is false) that reads the previous window's series through `readForWidgetSeries({ compare: true })`, which now returns `comparisonPoints` aligned to `points` by index. `readForWidget` accepts `comparison: false` for callers that only want totals; `readForWidgetBreakdown` accepts `extraMetrics` and returns per-row `metrics` for them; both surface `stale`.
44
+
45
+ **Fix:** the view's trend re-dates the comparison series onto the primary axis by index before labelling it. The query endpoint buckets each window on its own week and month boundaries, so at those granularities the comparison could come back a bucket longer or shorter and the chart padded or truncated it silently.
46
+
47
+ **Behavioral:** the analytics view's trend section draws one chart with the overlay instead of stacking a second chart for the previous period. With the trend widget's comparison ticked, the previous-window read it already made is asked for by day rather than as a total, so an adapter that answers series and totals in separate calls makes one more call for it.
48
+
49
+ **Fix:** a duplicate row on the native engine's seen ledger is treated as "already seen" rather than thrown. A pageview and a goal event arriving together for the same visitor race on the same ledger key, and the loser's duplicate-key error (Mongo 11000, Postgres 23505) used to escape the ingest handler as a 500.
50
+
51
+ ## 1.0.0-beta.7
52
+
53
+ ### Minor Changes
54
+
55
+ - **Breaking: first-class event capture.** Capture-capable adapters (native, PostHog, Plausible, Umami) now declare a `capture` descriptor: proxy routes, a snippet, and a public client config. An adapter declares one only when the public config capture needs is present, so a read-only PostHog (no `projectToken`) or a Plausible with neither `domain` nor `scriptId` gets no proxy route, no snippet, and fills no slot; reads are unaffected. The descriptor drives three new surfaces:
56
+
57
+ - A first-party runtime proxy at `/api/analytics/p/<slot>/*` (public; declared routes only; GET, POST and OPTIONS served, and PUT, PATCH and DELETE answered 405; cookies and authorization never forwarded and `set-cookie` never returned; body cap and timeout via `capture.proxy.{maxBodyBytes,timeoutMs}`; 404 for unknown slots or paths, 413 over the cap, 400 on a body that dies in transit, 502 on upstream failure). No rate limiting yet.
58
+ - `captureRewrites([{ path, adapter }])` from `@10x-media/analytics/next` for installs that prefer Next rewrites. `posthogProxyRewrites` now wraps it and is deprecated; its emitted param name changed from `:path*` to `:p*` (equivalent for Next). Root mounts and nested or duplicate mount paths throw.
59
+ - A public `GET /api/analytics/tracker` endpoint plus `getTrackerConfig(payload, { headers })` and the `AnalyticsScripts` server component (`@10x-media/analytics/rsc`) that resolve per-request capture config for up to two slots, `global` and `tenant`, one adapter each, deduped when both resolve to the same adapter. Vendor snippets are rendered only for slots that do not require consent; consent-gated vendors load after `consent('granted')`.
60
+
61
+ **Breaking: native engine.** Ingest accepts `type: 'goal'`, plus `value`, `currency` and `scrollDepth` on any event; a missing or non-string `name` on events and goals answers 400 (a nameless `type: 'event'` previously ingested); `name` is capped at 128 characters and `props`, previously stored verbatim, is sanitized to at most 20 flat scalar keys. Config `goals` (`{ slug, name, match: { kind: 'goal' | 'event' | 'path' }, value?, currency? }`) are matched at ingest into `goal` rollup buckets and stamped onto the stored event. `DimensionKey` gains `goal`, `RollupDelta.inc` widens to the full counter set, and `AdapterRegisterContext` gains a required `resolveGoals(req, scope)` that any code building that context by hand must supply. Existing native installs need a migration adding four numeric rollup counters, the `value`, `currency`, `scrollDepth` and `goals` event fields, and the `goal` event type (snippet in the native docs; on Postgres the enum change is irreversible).
62
+
63
+ **Behavioral:** native serves `conversions`, `revenue` (summed in the event's currency, no conversion) and `scrollDepth` (average over the pageviews that reported one), and a `goal` dimension that is groupable but not filterable. A `goal` event counts under `events` and never appears in the `event` dimension breakdown. Goal buckets also accrue visitor and session rows. The native ingest endpoint now caps the request body at 64 KiB (`413` above it), answers `400` on unparseable or non-object JSON (previously a logged `500`), drops a non-finite, negative or over-a-day `durationMs`, and truncates `path` to 512 and `hostname` to 253 characters. `autoCapture` is on by default except `scrollDepth`. Consent defaults per tracker family: vendors require it, native does not.
64
+
65
+ **Additive:** new subpaths `@10x-media/analytics/tracker` (dependency-free browser tracker: `page`, `track`, `trackGoal`, a consent gate whose decision persists under the `analytics:consent` storage key and whose pending events wait in a bounded in-memory queue, SPA route tracking, scroll depth, outbound links, file downloads, `data-analytics-goal` on click and submit) and `@10x-media/analytics/react` (`AnalyticsProvider`, `useAnalytics`, `TrackerBoot`). `useAnalytics()` also works without a provider once `TrackerBoot` has booted. Vendor snippets are self-sequencing (PostHog's official queued stub, Plausible's per-site stub) and carry the CSP nonce, which the PostHog stub propagates onto the bundle it injects. New options: `capture.{slots, paths, consent, autoCapture, proxy}` and `goals` (array, or `{ defaults }`); `capture.slots.<slot>: false` disables a slot; `capture.consent` overrides per slot, per adapter id, or through a resolver. `AnalyticsAdapter` gains optional `capture` and `ingest` members; PostHog gains `region` and `projectToken`; Plausible gains `domain` and `scriptId`; Umami's `host` also serves as the app origin for capture. The widget pickers offer `conversions`, `revenue` and `scrollDepth`, and a new `analytics-breakdown-goals` block lists goal completions.
66
+
67
+ - Engine hardening. Provider reads now run under a real timeout (`cache.timeoutMs`, default 15s) delivered to adapters as `AdapterContext.signal`, retry with backoff only on 429/5xx (one retry for network failures, none for other 4xx or aborts), and respect each adapter's declared rate limits through per-adapter token buckets (`requestsPerMinute`/`requestsPerHour`/`maxConcurrent`). When a refresh fails and an expired cache entry is still within a 24 hour stale window, the read serves it flagged `meta.stale: true` instead of degrading, and failures are logged with the adapter id. Also: native `realtime()` now honors `hostname` and `path` the way aggregate reads do, multiple filters on one dimension compose as AND instead of last-wins, and the client-side capability check mirrors the server's filter requirements.
68
+
69
+ - Multi-tenancy completes. A new `scopes` option enumerates tenant scopes so the cache-warm and sync cron tiers fan out per tenant (each scope resolves its own runtime providers and sync rows carry that scope); without it both tiers keep running install-wide only. Installs with runtime providers (`providers.collection` or `providers.resolve`) no longer treat the config-adapter capability union as a ceiling: every built-in widget registers, the metric pickers offer every metric, and the realtime endpoint is always available, with the per-request sources endpoint and pickers narrowing to what each tenant's sources actually serve. The dev app gains a `TENANCY=on` mode wired through `@payloadcms/plugin-multi-tenant` with two seeded tenants, and the e2e suite runs in both tenancy shapes. The sync task no longer derives a scope from the job request (it fans out over `scopes` and otherwise runs install-wide), and reads on a scoped install that resolve no scope now fail closed unless `access.platformRead` grants.
70
+
71
+ ### Patch Changes
72
+
73
+ - Updated dependencies:
74
+ - @10x-media/fields@0.1.0-beta.7
75
+
3
76
  ## 1.0.0-beta.6
4
77
 
5
78
  ### Minor Changes
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  # @10x-media/analytics
4
4
 
5
- Adapter-based analytics for Payload v3. One adapter contract covers a self-hosted native engine and the major providers (GA4, Plausible, Umami, PostHog), surfaced through dashboard widgets and per-document stat fields, with cached reads, an opt-in sync tier, and capability gating so unsupported surfaces never appear.
5
+ Adapter-based analytics for Payload v3. One adapter contract covers a self-hosted native engine and the major providers (GA4, Plausible, Umami, PostHog), surfaced through an admin analytics view, dashboard widgets and per-document stat fields, with cached reads, an opt-in sync tier, and capability gating so unsupported surfaces never appear.
6
6
 
7
7
  [![npm](https://img.shields.io/npm/v/@10x-media/analytics?style=flat-square)](https://www.npmjs.com/package/@10x-media/analytics)
8
8
 
@@ -12,8 +12,12 @@ Part of the [@10x-media Payload plugins](https://github.com/10x-media/payload-pl
12
12
 
13
13
  - **One adapter contract** with a capabilities model; adapters ship as code-split subpaths (`@10x-media/analytics/adapters/*`) plus a `memoryAdapter` for tests.
14
14
  - **Native engine**: self-hosted, cookieless analytics in your own database, with atomic rollups, exact daily uniques, geo resolution (platform headers or MaxMind), retention pruning, and opt-in write batching.
15
- - **Dashboard widgets** for Payload's Modular Dashboard: metric, trend, four breakdowns, and realtime, all capability-gated, plus a public API for custom widgets.
15
+ - **Capture**: a dependency-free browser tracker (`@10x-media/analytics/tracker`) with SPA pageviews, consent gating, auto-capture, and goals, booted from React (`@10x-media/analytics/react`) or a server component; capture-capable adapters are served through a first-party proxy so a vendor's SDK loads from your own origin.
16
+ - **Goals**: conversions and revenue, completed from a `data-analytics-goal` attribute, a `goalField()` picker in your own blocks, a `@10x-media/form-builder` action, or `trackServerEvent` from server code (webhooks, jobs), and declared in config or in an opt-in collection editors manage per scope.
17
+ - **Analytics view** at `/admin/analytics`: overview cards, a trend, capability-gated breakdown tabs with click-to-filter, goals and realtime, with range, source, metric, tab and filters in the URL so a report is a shareable link.
18
+ - **Dashboard widgets** for Payload's Modular Dashboard: metric, trend (with an optional previous-period overlay), goals, ten breakdowns, and realtime, each capability-gated, each linking into the analytics view, plus a public API for custom widgets.
16
19
  - **Display fields**: `analyticsStat`, `analyticsStatRow`, `analyticsFields`, `analyticsTab`, `analyticsTabsField` place per-document stats on your collections; typed per-collection bindings resolve each document's URL path.
20
+ - **Query endpoint**: an authenticated `GET /api/analytics/query` over any configured source, capability-validated and scope-gated, with coded errors and a `fetchQuery` helper for admin code.
17
21
  - **Caching** through `payload.kv` with request coalescing, plus an opt-in scheduled warm job.
18
22
  - **Sync tier**: persist provider daily metrics into a queryable Payload collection.
19
23
  - **Typed translations** with per-key overrides via `@10x-media/analytics/i18n`.
@@ -47,7 +51,7 @@ export default buildConfig({
47
51
  })
48
52
  ```
49
53
 
50
- Run `payload generate:importmap`, send pageviews to `POST /api/analytics/ingest`, and the dashboard fills in.
54
+ Run `payload generate:importmap`, render `<AnalyticsScripts config={await getTrackerConfig(payload, { headers: await headers() })} />` from `@10x-media/analytics/rsc` in your root layout, and the dashboard fills in.
51
55
 
52
56
  ## Documentation
53
57
 
@@ -56,13 +60,19 @@ Full documentation at [docs.10xmedia.de](https://docs.10xmedia.de/analytics):
56
60
  - [Overview](https://docs.10xmedia.de/analytics)
57
61
  - [Quick start](https://docs.10xmedia.de/analytics/quick-start)
58
62
  - [Adapters](https://docs.10xmedia.de/analytics/adapters)
63
+ - [Data sources and the query endpoint](https://docs.10xmedia.de/analytics/data-sources)
64
+ - [Analytics view](https://docs.10xmedia.de/analytics/analytics-view)
59
65
  - [Native engine](https://docs.10xmedia.de/analytics/native)
66
+ - [Capture](https://docs.10xmedia.de/analytics/capture)
67
+ - [Goals](https://docs.10xmedia.de/analytics/goals)
68
+ - [First-party proxy](https://docs.10xmedia.de/analytics/proxy)
60
69
  - [Geo resolution](https://docs.10xmedia.de/analytics/geo)
61
70
  - [Display fields](https://docs.10xmedia.de/analytics/display-fields)
62
71
  - [Dashboard widgets](https://docs.10xmedia.de/analytics/widgets)
63
72
  - [Caching and warming](https://docs.10xmedia.de/analytics/cache)
64
73
  - [Reporting timezone](https://docs.10xmedia.de/analytics/timezone)
65
74
  - [Sync tier](https://docs.10xmedia.de/analytics/sync)
75
+ - [Multi-tenancy](https://docs.10xmedia.de/analytics/multi-tenancy)
66
76
  - [i18n](https://docs.10xmedia.de/analytics/i18n)
67
77
 
68
78
  ## License
@@ -1,3 +1,4 @@
1
+ import { zonedCalendarDay } from "../../timeframe/tz.js";
1
2
  import { dayIso } from "../series.js";
2
3
  //#region src/adapters/ga4/ga4.ts
3
4
  const METRIC_MAP = {
@@ -123,8 +124,8 @@ function ga4(config) {
123
124
  const baseRequest = {
124
125
  property: `properties/${config.propertyId}`,
125
126
  dateRanges: [{
126
- startDate: q.dateRange.start.toISOString().slice(0, 10),
127
- endDate: q.dateRange.end.toISOString().slice(0, 10)
127
+ startDate: zonedCalendarDay(q.dateRange.start, q.timezone ?? "UTC"),
128
+ endDate: zonedCalendarDay(q.dateRange.end, q.timezone ?? "UTC")
128
129
  }],
129
130
  metrics: providerMetrics.map((name) => ({ name })),
130
131
  ...dimensionFilter ? { dimensionFilter } : {}
@@ -1 +1 @@
1
- {"version":3,"file":"ga4.js","names":[],"sources":["../../../src/adapters/ga4/ga4.ts"],"sourcesContent":["import type { BetaAnalyticsDataClient, protos } from '@google-analytics/data'\nimport type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tDimensionKey,\n\tMetricKey,\n} from '../../core/contract'\nimport { dayIso } from '../series'\n\nexport interface Ga4Config {\n\t/** GA4 property id (numeric), e.g. '123456789'. */\n\tpropertyId: string\n\t/** Service-account credentials. */\n\tcredentials: { client_email: string; private_key: string }\n\t/** GCP project id; inferred from the credentials when omitted. */\n\tprojectId?: string\n\t/** Maximum days of historical data. Defaults to 425 (GA4's rolling-window limit). Pass null to disable clamping. */\n\tmaxLookbackDays?: number | null\n}\n\nconst METRIC_MAP: Partial<Record<MetricKey, string>> = {\n\tpageviews: 'screenPageViews',\n\tvisitors: 'totalUsers',\n\tvisits: 'sessions',\n\tsessions: 'sessions',\n\tbounceRate: 'bounceRate',\n\tavgDuration: 'averageSessionDuration',\n\tevents: 'eventCount',\n\tconversions: 'keyEvents',\n\trevenue: 'totalRevenue',\n}\n\nconst DIMENSION_MAP: Partial<Record<DimensionKey, string>> = {\n\tpage: 'pagePath',\n\treferrer: 'pageReferrer',\n\tsource: 'sessionSource',\n\tmedium: 'sessionMedium',\n\tcampaign: 'sessionCampaignName',\n\tutmSource: 'sessionSource',\n\tutmMedium: 'sessionMedium',\n\tutmCampaign: 'sessionCampaignName',\n\tdevice: 'deviceCategory',\n\tbrowser: 'browser',\n\tos: 'operatingSystem',\n\tcountry: 'countryId',\n\tregion: 'region',\n\tcity: 'city',\n\tlanguage: 'language',\n\tevent: 'eventName',\n}\n\nconst ga4Metrics: ReadonlySet<MetricKey> = new Set(Object.keys(METRIC_MAP) as MetricKey[])\nconst ga4Dimensions: ReadonlySet<DimensionKey> = new Set(\n\tObject.keys(DIMENSION_MAP) as DimensionKey[]\n)\n\n// GA4 returns bounceRate as a 0..1 ratio and averageSessionDuration in seconds; the\n// contract uses a 0..100 percentage and milliseconds.\nconst toContractValue = (metric: MetricKey, raw: number): number => {\n\tif (metric === 'avgDuration') {\n\t\treturn Math.round(raw * 1000)\n\t}\n\tif (metric === 'bounceRate') {\n\t\treturn Math.round(raw * 100)\n\t}\n\treturn raw\n}\n\nexport function ga4(config: Ga4Config): AnalyticsAdapter {\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 425\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\tperPageQuery: true,\n\t\trealtime: false,\n\t\tcomparison: false,\n\t\tminGranularity: 'day',\n\t\tmaxLookbackDays,\n\t\tmetrics: ga4Metrics,\n\t\tdimensions: ga4Dimensions,\n\t\tfilters: ga4Dimensions,\n\t\tfilterOperators: new Set(['eq']),\n\t\tbatchPageReport: true,\n\t\trateLimit: { maxConcurrent: 10, quotaModel: 'tokens', readsCountAsUsage: true },\n\t\trecommendedTtl: { realtime: 300, aggregate: 21600 },\n\t}\n\n\tlet clientPromise: Promise<BetaAnalyticsDataClient> | undefined\n\n\tconst getClient = (): Promise<BetaAnalyticsDataClient> => {\n\t\tif (!clientPromise) {\n\t\t\tclientPromise = (async () => {\n\t\t\t\tlet mod: typeof import('@google-analytics/data')\n\t\t\t\ttry {\n\t\t\t\t\tmod = await import('@google-analytics/data')\n\t\t\t\t} catch {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t'@10x-media/analytics: the GA4 adapter requires the optional peer dependency \"@google-analytics/data\". Install it with: pnpm add @google-analytics/data'\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\treturn new mod.BetaAnalyticsDataClient({\n\t\t\t\t\tcredentials: config.credentials,\n\t\t\t\t\tprojectId: config.projectId,\n\t\t\t\t})\n\t\t\t})()\n\t\t}\n\t\treturn clientPromise\n\t}\n\n\treturn {\n\t\tid: 'ga4',\n\t\tlabel: 'Google Analytics 4',\n\t\tcapabilities,\n\t\tisConfigured: () =>\n\t\t\tBoolean(\n\t\t\t\tconfig.propertyId && config.credentials?.client_email && config.credentials?.private_key\n\t\t\t),\n\t\t// The gRPC SDK's gax CallOptions has no AbortSignal field, so ctx.signal cannot be\n\t\t// forwarded; gax cancellation uses the call's own handle, not our signal.\n\t\tasync query(q: AnalyticsQuery, _ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst wanted = q.metrics.filter((m) => METRIC_MAP[m])\n\t\t\tconst providerMetrics = [...new Set(wanted.map((m) => METRIC_MAP[m] as string))]\n\t\t\tconst dims = (q.dimensions ?? []).filter((d) => DIMENSION_MAP[d])\n\t\t\tconst providerDims = [...new Set(dims.map((d) => DIMENSION_MAP[d] as string))]\n\n\t\t\tconst readRow = (\n\t\t\t\trow: protos.google.analytics.data.v1beta.IRow\n\t\t\t): Partial<Record<MetricKey, number>> => {\n\t\t\t\tconst out: Partial<Record<MetricKey, number>> = {}\n\t\t\t\tfor (const m of wanted) {\n\t\t\t\t\tconst idx = providerMetrics.indexOf(METRIC_MAP[m] as string)\n\t\t\t\t\tout[m] = toContractValue(m, Number(row.metricValues?.[idx]?.value ?? 0))\n\t\t\t\t}\n\t\t\t\treturn out\n\t\t\t}\n\n\t\t\tconst filterExprs: protos.google.analytics.data.v1beta.IFilterExpression[] = []\n\t\t\tif (q.path) {\n\t\t\t\tfilterExprs.push({\n\t\t\t\t\tfilter: { fieldName: 'pagePath', stringFilter: { matchType: 'EXACT', value: q.path } },\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (q.hostname) {\n\t\t\t\tfilterExprs.push({\n\t\t\t\t\tfilter: {\n\t\t\t\t\t\tfieldName: 'hostName',\n\t\t\t\t\t\tstringFilter: { matchType: 'EXACT', value: q.hostname },\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t}\n\t\t\t// Capability gating (filters/filterOperators) is the real contract upstream; an\n\t\t\t// unsupported dimension or operator is dropped here as the safety net.\n\t\t\tfor (const filter of q.filters ?? []) {\n\t\t\t\tconst fieldName = DIMENSION_MAP[filter.dimension]\n\t\t\t\tif (!fieldName || filter.operator !== 'eq') {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tfilterExprs.push({\n\t\t\t\t\tfilter: { fieldName, stringFilter: { matchType: 'EXACT', value: filter.value } },\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst dimensionFilter =\n\t\t\t\tfilterExprs.length === 0\n\t\t\t\t\t? undefined\n\t\t\t\t\t: filterExprs.length === 1\n\t\t\t\t\t\t? filterExprs[0]\n\t\t\t\t\t\t: { andGroup: { expressions: filterExprs } }\n\n\t\t\tconst baseRequest: protos.google.analytics.data.v1beta.IRunReportRequest = {\n\t\t\t\tproperty: `properties/${config.propertyId}`,\n\t\t\t\tdateRanges: [\n\t\t\t\t\t{\n\t\t\t\t\t\tstartDate: q.dateRange.start.toISOString().slice(0, 10),\n\t\t\t\t\t\tendDate: q.dateRange.end.toISOString().slice(0, 10),\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tmetrics: providerMetrics.map((name) => ({ name })),\n\t\t\t\t...(dimensionFilter ? { dimensionFilter } : {}),\n\t\t\t}\n\n\t\t\tconst client = await getClient()\n\n\t\t\tif (q.granularity === 'day' && !dims.length) {\n\t\t\t\tconst [response] = await client.runReport({\n\t\t\t\t\t...baseRequest,\n\t\t\t\t\tdimensions: [{ name: 'date' }],\n\t\t\t\t\tmetricAggregations: [\n\t\t\t\t\t\t'TOTAL',\n\t\t\t\t\t] as unknown as protos.google.analytics.data.v1beta.MetricAggregation[],\n\t\t\t\t\torderBys: [{ dimension: { dimensionName: 'date' } }],\n\t\t\t\t})\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const row of response.rows ?? []) {\n\t\t\t\t\tconst ymd = row.dimensionValues?.[0]?.value ?? ''\n\t\t\t\t\tconst ts = dayIso(`${ymd.slice(0, 4)}-${ymd.slice(4, 6)}-${ymd.slice(6, 8)}`)\n\t\t\t\t\tif (ts) {\n\t\t\t\t\t\trows.push({ timestamp: ts, metrics: readRow(row) })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst totalsRow = response.totals?.[0]\n\t\t\t\tconst totals = totalsRow ? readRow(totalsRow) : {}\n\t\t\t\treturn { rows, totals, meta: { provider: 'ga4', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst [response] = await client.runReport({\n\t\t\t\t...baseRequest,\n\t\t\t\t...(providerDims.length ? { dimensions: providerDims.map((name) => ({ name })) } : {}),\n\t\t\t\t...(q.limit ? { limit: q.limit } : {}),\n\t\t\t})\n\n\t\t\tif (!dims.length) {\n\t\t\t\tconst row = response.rows?.[0]\n\t\t\t\tconst totals = row ? readRow(row) : {}\n\t\t\t\treturn { rows: [{ metrics: totals }], totals, meta: { provider: 'ga4', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst rows: AnalyticsRow[] = (response.rows ?? []).map((row) => {\n\t\t\t\tconst dimValues: Partial<Record<DimensionKey, string>> = {}\n\t\t\t\tfor (const d of dims) {\n\t\t\t\t\tconst idx = providerDims.indexOf(DIMENSION_MAP[d] as string)\n\t\t\t\t\tdimValues[d] = row.dimensionValues?.[idx]?.value ?? ''\n\t\t\t\t}\n\t\t\t\treturn { dimensions: dimValues, metrics: readRow(row) }\n\t\t\t})\n\t\t\treturn { rows, totals: undefined, meta: { provider: 'ga4', fetchedAt } }\n\t\t},\n\t}\n}\n"],"mappings":";;AAwBA,MAAM,aAAiD;CACtD,WAAW;CACX,UAAU;CACV,QAAQ;CACR,UAAU;CACV,YAAY;CACZ,aAAa;CACb,QAAQ;CACR,aAAa;CACb,SAAS;AACV;AAEA,MAAM,gBAAuD;CAC5D,MAAM;CACN,UAAU;CACV,QAAQ;CACR,QAAQ;CACR,UAAU;CACV,WAAW;CACX,WAAW;CACX,aAAa;CACb,QAAQ;CACR,SAAS;CACT,IAAI;CACJ,SAAS;CACT,QAAQ;CACR,MAAM;CACN,UAAU;CACV,OAAO;AACR;AAEA,MAAM,aAAqC,IAAI,IAAI,OAAO,KAAK,UAAU,CAAgB;AACzF,MAAM,gBAA2C,IAAI,IACpD,OAAO,KAAK,aAAa,CAC1B;AAIA,MAAM,mBAAmB,QAAmB,QAAwB;CACnE,IAAI,WAAW,eACd,OAAO,KAAK,MAAM,MAAM,GAAI;CAE7B,IAAI,WAAW,cACd,OAAO,KAAK,MAAM,MAAM,GAAG;CAE5B,OAAO;AACR;AAEA,SAAgB,IAAI,QAAqC;CAGxD,MAAM,eAAsC;EAC3C,cAAc;EACd,UAAU;EACV,YAAY;EACZ,gBAAgB;EAChB,iBAPuB,OAAO,oBAAoB,KAAA,IAAY,OAAO,kBAAkB;EAQvF,SAAS;EACT,YAAY;EACZ,SAAS;EACT,iBAAiB,IAAI,IAAI,CAAC,IAAI,CAAC;EAC/B,iBAAiB;EACjB,WAAW;GAAE,eAAe;GAAI,YAAY;GAAU,mBAAmB;EAAK;EAC9E,gBAAgB;GAAE,UAAU;GAAK,WAAW;EAAM;CACnD;CAEA,IAAI;CAEJ,MAAM,kBAAoD;EACzD,IAAI,CAAC,eACJ,iBAAiB,YAAY;GAC5B,IAAI;GACJ,IAAI;IACH,MAAM,MAAM,OAAO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S,IAAI,CAAC;KAC1B,MAAM;MAAE,UAAU;MAAO;KAAU;IAAE;GAC7D;GAEA,MAAM,CAAC,YAAY,MAAM,OAAO,UAAU;IACzC,GAAG;IACH,GAAI,aAAa,SAAS,EAAE,YAAY,aAAa,KAAK,UAAU,EAAE,KAAK,EAAE,EAAE,IAAI,CAAC;IACpF,GAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,IAAI,CAAC;GACrC,CAAC;GAED,IAAI,CAAC,KAAK,QAAQ;IACjB,MAAM,MAAM,SAAS,OAAO;IAC5B,MAAM,SAAS,MAAM,QAAQ,GAAG,IAAI,CAAC;IACrC,OAAO;KAAE,MAAM,CAAC,EAAE,SAAS,OAAO,CAAC;KAAG;KAAQ,MAAM;MAAE,UAAU;MAAO;KAAU;IAAE;GACpF;GAUA,OAAO;IAAE,OARqB,SAAS,QAAQ,CAAC,GAAG,KAAK,QAAQ;KAC/D,MAAM,YAAmD,CAAC;KAC1D,KAAK,MAAM,KAAK,MAAM;MACrB,MAAM,MAAM,aAAa,QAAQ,cAAc,EAAY;MAC3D,UAAU,KAAK,IAAI,kBAAkB,MAAM,SAAS;KACrD;KACA,OAAO;MAAE,YAAY;MAAW,SAAS,QAAQ,GAAG;KAAE;IACvD,CACY;IAAG,QAAQ,KAAA;IAAW,MAAM;KAAE,UAAU;KAAO;IAAU;GAAE;EACxE;CACD;AACD"}
1
+ {"version":3,"file":"ga4.js","names":[],"sources":["../../../src/adapters/ga4/ga4.ts"],"sourcesContent":["import type { BetaAnalyticsDataClient, protos } from '@google-analytics/data'\nimport type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tDimensionKey,\n\tMetricKey,\n} from '../../core/contract'\nimport { DEFAULT_TIMEZONE, zonedCalendarDay } from '../../timeframe/tz'\nimport { dayIso } from '../series'\n\nexport interface Ga4Config {\n\t/** GA4 property id (numeric), e.g. '123456789'. */\n\tpropertyId: string\n\t/** Service-account credentials. */\n\tcredentials: { client_email: string; private_key: string }\n\t/** GCP project id; inferred from the credentials when omitted. */\n\tprojectId?: string\n\t/** Maximum days of historical data. Defaults to 425 (GA4's rolling-window limit). Pass null to disable clamping. */\n\tmaxLookbackDays?: number | null\n}\n\nconst METRIC_MAP: Partial<Record<MetricKey, string>> = {\n\tpageviews: 'screenPageViews',\n\tvisitors: 'totalUsers',\n\tvisits: 'sessions',\n\tsessions: 'sessions',\n\tbounceRate: 'bounceRate',\n\tavgDuration: 'averageSessionDuration',\n\tevents: 'eventCount',\n\tconversions: 'keyEvents',\n\trevenue: 'totalRevenue',\n}\n\nconst DIMENSION_MAP: Partial<Record<DimensionKey, string>> = {\n\tpage: 'pagePath',\n\treferrer: 'pageReferrer',\n\tsource: 'sessionSource',\n\tmedium: 'sessionMedium',\n\tcampaign: 'sessionCampaignName',\n\tutmSource: 'sessionSource',\n\tutmMedium: 'sessionMedium',\n\tutmCampaign: 'sessionCampaignName',\n\tdevice: 'deviceCategory',\n\tbrowser: 'browser',\n\tos: 'operatingSystem',\n\tcountry: 'countryId',\n\tregion: 'region',\n\tcity: 'city',\n\tlanguage: 'language',\n\tevent: 'eventName',\n}\n\nconst ga4Metrics: ReadonlySet<MetricKey> = new Set(Object.keys(METRIC_MAP) as MetricKey[])\nconst ga4Dimensions: ReadonlySet<DimensionKey> = new Set(\n\tObject.keys(DIMENSION_MAP) as DimensionKey[]\n)\n\n// GA4 returns bounceRate as a 0..1 ratio and averageSessionDuration in seconds; the\n// contract uses a 0..100 percentage and milliseconds.\nconst toContractValue = (metric: MetricKey, raw: number): number => {\n\tif (metric === 'avgDuration') {\n\t\treturn Math.round(raw * 1000)\n\t}\n\tif (metric === 'bounceRate') {\n\t\treturn Math.round(raw * 100)\n\t}\n\treturn raw\n}\n\nexport function ga4(config: Ga4Config): AnalyticsAdapter {\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 425\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\tperPageQuery: true,\n\t\trealtime: false,\n\t\tcomparison: false,\n\t\tminGranularity: 'day',\n\t\tmaxLookbackDays,\n\t\tmetrics: ga4Metrics,\n\t\tdimensions: ga4Dimensions,\n\t\tfilters: ga4Dimensions,\n\t\tfilterOperators: new Set(['eq']),\n\t\tbatchPageReport: true,\n\t\trateLimit: { maxConcurrent: 10, quotaModel: 'tokens', readsCountAsUsage: true },\n\t\trecommendedTtl: { realtime: 300, aggregate: 21600 },\n\t}\n\n\tlet clientPromise: Promise<BetaAnalyticsDataClient> | undefined\n\n\tconst getClient = (): Promise<BetaAnalyticsDataClient> => {\n\t\tif (!clientPromise) {\n\t\t\tclientPromise = (async () => {\n\t\t\t\tlet mod: typeof import('@google-analytics/data')\n\t\t\t\ttry {\n\t\t\t\t\tmod = await import('@google-analytics/data')\n\t\t\t\t} catch {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t'@10x-media/analytics: the GA4 adapter requires the optional peer dependency \"@google-analytics/data\". Install it with: pnpm add @google-analytics/data'\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\treturn new mod.BetaAnalyticsDataClient({\n\t\t\t\t\tcredentials: config.credentials,\n\t\t\t\t\tprojectId: config.projectId,\n\t\t\t\t})\n\t\t\t})()\n\t\t}\n\t\treturn clientPromise\n\t}\n\n\treturn {\n\t\tid: 'ga4',\n\t\tlabel: 'Google Analytics 4',\n\t\tcapabilities,\n\t\tisConfigured: () =>\n\t\t\tBoolean(\n\t\t\t\tconfig.propertyId && config.credentials?.client_email && config.credentials?.private_key\n\t\t\t),\n\t\t// The gRPC SDK's gax CallOptions has no AbortSignal field, so ctx.signal cannot be\n\t\t// forwarded; gax cancellation uses the call's own handle, not our signal.\n\t\tasync query(q: AnalyticsQuery, _ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst wanted = q.metrics.filter((m) => METRIC_MAP[m])\n\t\t\tconst providerMetrics = [...new Set(wanted.map((m) => METRIC_MAP[m] as string))]\n\t\t\tconst dims = (q.dimensions ?? []).filter((d) => DIMENSION_MAP[d])\n\t\t\tconst providerDims = [...new Set(dims.map((d) => DIMENSION_MAP[d] as string))]\n\n\t\t\tconst readRow = (\n\t\t\t\trow: protos.google.analytics.data.v1beta.IRow\n\t\t\t): Partial<Record<MetricKey, number>> => {\n\t\t\t\tconst out: Partial<Record<MetricKey, number>> = {}\n\t\t\t\tfor (const m of wanted) {\n\t\t\t\t\tconst idx = providerMetrics.indexOf(METRIC_MAP[m] as string)\n\t\t\t\t\tout[m] = toContractValue(m, Number(row.metricValues?.[idx]?.value ?? 0))\n\t\t\t\t}\n\t\t\t\treturn out\n\t\t\t}\n\n\t\t\tconst filterExprs: protos.google.analytics.data.v1beta.IFilterExpression[] = []\n\t\t\tif (q.path) {\n\t\t\t\tfilterExprs.push({\n\t\t\t\t\tfilter: { fieldName: 'pagePath', stringFilter: { matchType: 'EXACT', value: q.path } },\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (q.hostname) {\n\t\t\t\tfilterExprs.push({\n\t\t\t\t\tfilter: {\n\t\t\t\t\t\tfieldName: 'hostName',\n\t\t\t\t\t\tstringFilter: { matchType: 'EXACT', value: q.hostname },\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t}\n\t\t\t// Capability gating (filters/filterOperators) is the real contract upstream; an\n\t\t\t// unsupported dimension or operator is dropped here as the safety net.\n\t\t\tfor (const filter of q.filters ?? []) {\n\t\t\t\tconst fieldName = DIMENSION_MAP[filter.dimension]\n\t\t\t\tif (!fieldName || filter.operator !== 'eq') {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tfilterExprs.push({\n\t\t\t\t\tfilter: { fieldName, stringFilter: { matchType: 'EXACT', value: filter.value } },\n\t\t\t\t})\n\t\t\t}\n\t\t\tconst dimensionFilter =\n\t\t\t\tfilterExprs.length === 0\n\t\t\t\t\t? undefined\n\t\t\t\t\t: filterExprs.length === 1\n\t\t\t\t\t\t? filterExprs[0]\n\t\t\t\t\t\t: { andGroup: { expressions: filterExprs } }\n\n\t\t\tconst baseRequest: protos.google.analytics.data.v1beta.IRunReportRequest = {\n\t\t\t\tproperty: `properties/${config.propertyId}`,\n\t\t\t\tdateRanges: [\n\t\t\t\t\t{\n\t\t\t\t\t\tstartDate: zonedCalendarDay(q.dateRange.start, q.timezone ?? DEFAULT_TIMEZONE),\n\t\t\t\t\t\tendDate: zonedCalendarDay(q.dateRange.end, q.timezone ?? DEFAULT_TIMEZONE),\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tmetrics: providerMetrics.map((name) => ({ name })),\n\t\t\t\t...(dimensionFilter ? { dimensionFilter } : {}),\n\t\t\t}\n\n\t\t\tconst client = await getClient()\n\n\t\t\tif (q.granularity === 'day' && !dims.length) {\n\t\t\t\tconst [response] = await client.runReport({\n\t\t\t\t\t...baseRequest,\n\t\t\t\t\tdimensions: [{ name: 'date' }],\n\t\t\t\t\tmetricAggregations: [\n\t\t\t\t\t\t'TOTAL',\n\t\t\t\t\t] as unknown as protos.google.analytics.data.v1beta.MetricAggregation[],\n\t\t\t\t\torderBys: [{ dimension: { dimensionName: 'date' } }],\n\t\t\t\t})\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const row of response.rows ?? []) {\n\t\t\t\t\tconst ymd = row.dimensionValues?.[0]?.value ?? ''\n\t\t\t\t\tconst ts = dayIso(`${ymd.slice(0, 4)}-${ymd.slice(4, 6)}-${ymd.slice(6, 8)}`)\n\t\t\t\t\tif (ts) {\n\t\t\t\t\t\trows.push({ timestamp: ts, metrics: readRow(row) })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst totalsRow = response.totals?.[0]\n\t\t\t\tconst totals = totalsRow ? readRow(totalsRow) : {}\n\t\t\t\treturn { rows, totals, meta: { provider: 'ga4', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst [response] = await client.runReport({\n\t\t\t\t...baseRequest,\n\t\t\t\t...(providerDims.length ? { dimensions: providerDims.map((name) => ({ name })) } : {}),\n\t\t\t\t...(q.limit ? { limit: q.limit } : {}),\n\t\t\t})\n\n\t\t\tif (!dims.length) {\n\t\t\t\tconst row = response.rows?.[0]\n\t\t\t\tconst totals = row ? readRow(row) : {}\n\t\t\t\treturn { rows: [{ metrics: totals }], totals, meta: { provider: 'ga4', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst rows: AnalyticsRow[] = (response.rows ?? []).map((row) => {\n\t\t\t\tconst dimValues: Partial<Record<DimensionKey, string>> = {}\n\t\t\t\tfor (const d of dims) {\n\t\t\t\t\tconst idx = providerDims.indexOf(DIMENSION_MAP[d] as string)\n\t\t\t\t\tdimValues[d] = row.dimensionValues?.[idx]?.value ?? ''\n\t\t\t\t}\n\t\t\t\treturn { dimensions: dimValues, metrics: readRow(row) }\n\t\t\t})\n\t\t\treturn { rows, totals: undefined, meta: { provider: 'ga4', fetchedAt } }\n\t\t},\n\t}\n}\n"],"mappings":";;;AAyBA,MAAM,aAAiD;CACtD,WAAW;CACX,UAAU;CACV,QAAQ;CACR,UAAU;CACV,YAAY;CACZ,aAAa;CACb,QAAQ;CACR,aAAa;CACb,SAAS;AACV;AAEA,MAAM,gBAAuD;CAC5D,MAAM;CACN,UAAU;CACV,QAAQ;CACR,QAAQ;CACR,UAAU;CACV,WAAW;CACX,WAAW;CACX,aAAa;CACb,QAAQ;CACR,SAAS;CACT,IAAI;CACJ,SAAS;CACT,QAAQ;CACR,MAAM;CACN,UAAU;CACV,OAAO;AACR;AAEA,MAAM,aAAqC,IAAI,IAAI,OAAO,KAAK,UAAU,CAAgB;AACzF,MAAM,gBAA2C,IAAI,IACpD,OAAO,KAAK,aAAa,CAC1B;AAIA,MAAM,mBAAmB,QAAmB,QAAwB;CACnE,IAAI,WAAW,eACd,OAAO,KAAK,MAAM,MAAM,GAAI;CAE7B,IAAI,WAAW,cACd,OAAO,KAAK,MAAM,MAAM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AAY;MAAW,SAAS,QAAQ,GAAG;KAAE;IACvD,CACY;IAAG,QAAQ,KAAA;IAAW,MAAM;KAAE,UAAU;KAAO;IAAU;GAAE;EACxE;CACD;AACD"}
@@ -31,6 +31,6 @@ const fetchJson = async (url, opts) => {
31
31
  return await res.json();
32
32
  };
33
33
  //#endregion
34
- export { fetchJson };
34
+ export { ProviderHttpError, fetchJson };
35
35
 
36
36
  //# sourceMappingURL=fetchJson.js.map
@@ -8,6 +8,16 @@ interface PlausibleConfig {
8
8
  host?: string;
9
9
  /** Maximum days of historical data. Defaults to 730. Pass null to disable clamping. */
10
10
  maxLookbackDays?: number | null;
11
+ /**
12
+ * Site domain for the legacy script tag (`data-domain`). Takes priority over `scriptId`.
13
+ * The adapter declares `capture` only when one of the two is set.
14
+ */
15
+ domain?: string;
16
+ /**
17
+ * Per-site tracker id (`pa-<id>.js`) for the newer per-site script model. The adapter
18
+ * declares `capture` only when one of it and `domain` is set.
19
+ */
20
+ scriptId?: string;
11
21
  }
12
22
  declare function plausible(config: PlausibleConfig): AnalyticsAdapter;
13
23
  //#endregion
@@ -1,6 +1,46 @@
1
+ import { zonedCalendarDay } from "../../timeframe/tz.js";
1
2
  import { dayIso } from "../series.js";
2
3
  import { fetchJson } from "../http/fetchJson.js";
3
4
  //#region src/adapters/plausible/plausible.ts
5
+ /**
6
+ * Plausible's official per-site stub, as served on plausible.io's own pages: `plausible.q`
7
+ * queues calls the tracker replays on load, and `plausible.init` parks the options on
8
+ * `plausible.o` for it to read. It makes the inline safe next to the async loader in either
9
+ * order, which the bare `plausible.init(...)` call was not. `init` is guarded with `||`
10
+ * (the official one assigns unconditionally) because here the tracker is a separate async
11
+ * tag and may win the race, and overwriting the real `init` with the stub would lose the
12
+ * endpoint.
13
+ */
14
+ const PLAUSIBLE_STUB = "window.plausible=window.plausible||function(){(window.plausible.q=window.plausible.q||[]).push(arguments)},window.plausible.init=window.plausible.init||function(e){window.plausible.o=e||{}};";
15
+ function buildCapture(config) {
16
+ const base = config.host ?? "https://plausible.io";
17
+ const scripts = (path) => {
18
+ if (config.domain) return [{
19
+ src: `${path}/js/script.js`,
20
+ defer: true,
21
+ attrs: {
22
+ "data-domain": config.domain,
23
+ "data-api": `${path}/api/event`
24
+ }
25
+ }];
26
+ if (config.scriptId) return [{
27
+ src: `${path}/js/pa-${config.scriptId}.js`,
28
+ async: true
29
+ }, { inline: `${PLAUSIBLE_STUB}plausible.init({endpoint:${JSON.stringify(`${path}/api/event`)}})` }];
30
+ return [];
31
+ };
32
+ return {
33
+ proxy: { routes: [{
34
+ source: "/js/:script*",
35
+ upstream: `${base}/js/:script*`
36
+ }, {
37
+ source: "/api/event",
38
+ upstream: `${base}/api/event`
39
+ }] },
40
+ snippet: ({ path }) => ({ scripts: scripts(path) }),
41
+ client: { kind: "plausible" }
42
+ };
43
+ }
4
44
  const METRIC_MAP = {
5
45
  pageviews: "pageviews",
6
46
  visitors: "visitors",
@@ -51,6 +91,7 @@ function plausible(config) {
51
91
  aggregate: 3600
52
92
  }
53
93
  },
94
+ ...config.domain || config.scriptId ? { capture: buildCapture(config) } : {},
54
95
  isConfigured: () => Boolean(config.siteId && config.apiKey),
55
96
  async query(q, ctx) {
56
97
  const fetchedAt = q.dateRange.end.toISOString();
@@ -91,7 +132,7 @@ function plausible(config) {
91
132
  body: {
92
133
  site_id: config.siteId,
93
134
  metrics: providerMetrics,
94
- date_range: [q.dateRange.start.toISOString().slice(0, 10), q.dateRange.end.toISOString().slice(0, 10)],
135
+ date_range: [zonedCalendarDay(q.dateRange.start, q.timezone ?? "UTC"), zonedCalendarDay(q.dateRange.end, q.timezone ?? "UTC")],
95
136
  ...filters.length ? { filters } : {},
96
137
  ...extra
97
138
  },
@@ -1 +1 @@
1
- {"version":3,"file":"plausible.js","names":[],"sources":["../../../src/adapters/plausible/plausible.ts"],"sourcesContent":["import type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tDimensionKey,\n\tMetricKey,\n} from '../../core/contract'\nimport { fetchJson } from '../http/fetchJson'\nimport { dayIso } from '../series'\n\nexport interface PlausibleConfig {\n\tsiteId: string\n\tapiKey: string\n\t/** Base URL for self-hosted CE. Defaults to Plausible Cloud. */\n\thost?: string\n\t/** Maximum days of historical data. Defaults to 730. Pass null to disable clamping. */\n\tmaxLookbackDays?: number | null\n}\n\nconst METRIC_MAP: Partial<Record<MetricKey, string>> = {\n\tpageviews: 'pageviews',\n\tvisitors: 'visitors',\n\tvisits: 'visits',\n\tsessions: 'visits',\n\tbounceRate: 'bounce_rate',\n\tavgDuration: 'visit_duration',\n\tevents: 'events',\n\tscrollDepth: 'scroll_depth',\n\trevenue: 'total_revenue',\n}\n\nconst DIMENSION_MAP: Partial<Record<DimensionKey, string>> = {\n\tpage: 'event:page',\n\tsource: 'visit:source',\n\treferrer: 'visit:referrer',\n\tdevice: 'visit:device',\n\tbrowser: 'visit:browser',\n\tos: 'visit:os',\n\tcountry: 'visit:country',\n\tregion: 'visit:region',\n\tcity: 'visit:city',\n\tutmSource: 'visit:utm_source',\n\tutmMedium: 'visit:utm_medium',\n\tutmCampaign: 'visit:utm_campaign',\n}\n\nconst plausibleMetrics: ReadonlySet<MetricKey> = new Set(Object.keys(METRIC_MAP) as MetricKey[])\nconst plausibleDimensions: ReadonlySet<DimensionKey> = new Set(\n\tObject.keys(DIMENSION_MAP) as DimensionKey[]\n)\n\ninterface PlausibleResponse {\n\tresults: Array<{ metrics: number[]; dimensions: string[] }>\n}\n\n// visit_duration is reported in seconds; the contract avgDuration is milliseconds.\nconst toContractValue = (metric: MetricKey, raw: number): number =>\n\tmetric === 'avgDuration' ? Math.round(raw * 1000) : raw\n\nexport function plausible(config: PlausibleConfig): AnalyticsAdapter {\n\tconst host = config.host ?? 'https://plausible.io'\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 730\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\tperPageQuery: true,\n\t\trealtime: false,\n\t\tcomparison: false,\n\t\tminGranularity: 'day',\n\t\tmaxLookbackDays,\n\t\tmetrics: plausibleMetrics,\n\t\tdimensions: plausibleDimensions,\n\t\tfilters: plausibleDimensions,\n\t\tfilterOperators: new Set(['eq']),\n\t\tbatchPageReport: true,\n\t\trateLimit: { requestsPerHour: 600 },\n\t\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n\t}\n\n\treturn {\n\t\tid: 'plausible',\n\t\tlabel: 'Plausible',\n\t\tcapabilities,\n\t\tisConfigured: () => Boolean(config.siteId && config.apiKey),\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst wanted = q.metrics.filter((m) => METRIC_MAP[m])\n\t\t\t// Several contract metrics alias one Plausible metric (sessions and visits both\n\t\t\t// map to \"visits\"), so dedupe before sending and read each contract metric back\n\t\t\t// from its provider key's position rather than the request index.\n\t\t\tconst providerMetrics = [...new Set(wanted.map((m) => METRIC_MAP[m] as string))]\n\t\t\tconst dims = (q.dimensions ?? []).filter((d) => DIMENSION_MAP[d])\n\t\t\tconst filters: Array<[string, string, string[]]> = []\n\t\t\tif (q.path) {\n\t\t\t\tfilters.push(['is', 'event:page', [q.path]])\n\t\t\t}\n\t\t\tif (q.hostname) {\n\t\t\t\tfilters.push(['is', 'event:hostname', [q.hostname]])\n\t\t\t}\n\t\t\t// Capability gating (filters/filterOperators) is the real contract upstream; an\n\t\t\t// unsupported dimension or operator is dropped here as the safety net.\n\t\t\tfor (const filter of q.filters ?? []) {\n\t\t\t\tconst mapped = DIMENSION_MAP[filter.dimension]\n\t\t\t\tif (!mapped || filter.operator !== 'eq') {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tfilters.push(['is', mapped, [filter.value]])\n\t\t\t}\n\n\t\t\tconst readRow = (row: { metrics: number[] }): Partial<Record<MetricKey, number>> => {\n\t\t\t\tconst out: Partial<Record<MetricKey, number>> = {}\n\t\t\t\tfor (const m of wanted) {\n\t\t\t\t\tconst idx = providerMetrics.indexOf(METRIC_MAP[m] as string)\n\t\t\t\t\tout[m] = toContractValue(m, row.metrics[idx] ?? 0)\n\t\t\t\t}\n\t\t\t\treturn out\n\t\t\t}\n\n\t\t\tconst postQuery = (extra: Record<string, unknown>): Promise<PlausibleResponse> =>\n\t\t\t\tfetchJson<PlausibleResponse>(`${host}/api/v2/query`, {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders: { authorization: `Bearer ${config.apiKey}` },\n\t\t\t\t\tbody: {\n\t\t\t\t\t\tsite_id: config.siteId,\n\t\t\t\t\t\tmetrics: providerMetrics,\n\t\t\t\t\t\tdate_range: [\n\t\t\t\t\t\t\tq.dateRange.start.toISOString().slice(0, 10),\n\t\t\t\t\t\t\tq.dateRange.end.toISOString().slice(0, 10),\n\t\t\t\t\t\t],\n\t\t\t\t\t\t...(filters.length ? { filters } : {}),\n\t\t\t\t\t\t...extra,\n\t\t\t\t\t},\n\t\t\t\t\tsignal: ctx.signal,\n\t\t\t\t\tprovider: 'plausible',\n\t\t\t\t})\n\n\t\t\tconst fetchTotals = async (): Promise<Partial<Record<MetricKey, number>>> => {\n\t\t\t\tconst data = await postQuery({})\n\t\t\t\treturn data.results[0] ? readRow(data.results[0]) : {}\n\t\t\t}\n\n\t\t\tif (q.granularity === 'day' && !dims.length) {\n\t\t\t\tconst [seriesData, totals] = await Promise.all([\n\t\t\t\t\tpostQuery({ dimensions: ['time:day'] }),\n\t\t\t\t\tfetchTotals(),\n\t\t\t\t])\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const row of seriesData.results) {\n\t\t\t\t\tconst ts = dayIso(row.dimensions[0] ?? '')\n\t\t\t\t\tif (ts) {\n\t\t\t\t\t\trows.push({ timestamp: ts, metrics: readRow(row) })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { rows, totals, meta: { provider: 'plausible', fetchedAt } }\n\t\t\t}\n\n\t\t\tif (!dims.length) {\n\t\t\t\tconst totals = await fetchTotals()\n\t\t\t\treturn { rows: [{ metrics: totals }], totals, meta: { provider: 'plausible', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst data = await postQuery({ dimensions: dims.map((d) => DIMENSION_MAP[d] as string) })\n\t\t\tconst rows: AnalyticsRow[] = data.results.map((row) => {\n\t\t\t\tconst dimValues: Partial<Record<DimensionKey, string>> = {}\n\t\t\t\tfor (let i = 0; i < dims.length; i++) {\n\t\t\t\t\tconst d = dims[i]\n\t\t\t\t\tif (d !== undefined) {\n\t\t\t\t\t\tdimValues[d] = row.dimensions[i] ?? ''\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { dimensions: dimValues, metrics: readRow(row) }\n\t\t\t})\n\t\t\treturn { rows, totals: undefined, meta: { provider: 'plausible', fetchedAt } }\n\t\t},\n\t}\n}\n"],"mappings":";;;AAsBA,MAAM,aAAiD;CACtD,WAAW;CACX,UAAU;CACV,QAAQ;CACR,UAAU;CACV,YAAY;CACZ,aAAa;CACb,QAAQ;CACR,aAAa;CACb,SAAS;AACV;AAEA,MAAM,gBAAuD;CAC5D,MAAM;CACN,QAAQ;CACR,UAAU;CACV,QAAQ;CACR,SAAS;CACT,IAAI;CACJ,SAAS;CACT,QAAQ;CACR,MAAM;CACN,WAAW;CACX,WAAW;CACX,aAAa;AACd;AAEA,MAAM,mBAA2C,IAAI,IAAI,OAAO,KAAK,UAAU,CAAgB;AAC/F,MAAM,sBAAiD,IAAI,IAC1D,OAAO,KAAK,aAAa,CAC1B;AAOA,MAAM,mBAAmB,QAAmB,QAC3C,WAAW,gBAAgB,KAAK,MAAM,MAAM,GAAI,IAAI;AAErD,SAAgB,UAAU,QAA2C;CACpE,MAAM,OAAO,OAAO,QAAQ;CAkB5B,OAAO;EACN,IAAI;EACJ,OAAO;EACP,cAAA;GAjBA,cAAc;GACd,UAAU;GACV,YAAY;GACZ,gB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AC1D,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;MACrC,MAAM,IAAI,KAAK;MACf,IAAI,MAAM,KAAA,GACT,UAAU,KAAK,IAAI,WAAW,MAAM;KAEtC;KACA,OAAO;MAAE,YAAY;MAAW,SAAS,QAAQ,GAAG;KAAE;IACvD,CACY;IAAG,QAAQ,KAAA;IAAW,MAAM;KAAE,UAAU;KAAa;IAAU;GAAE;EAC9E;CACD;AACD"}
1
+ {"version":3,"file":"plausible.js","names":[],"sources":["../../../src/adapters/plausible/plausible.ts"],"sourcesContent":["import 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 { DEFAULT_TIMEZONE, zonedCalendarDay } from '../../timeframe/tz'\nimport { fetchJson } from '../http/fetchJson'\nimport { dayIso } from '../series'\n\nexport interface PlausibleConfig {\n\tsiteId: string\n\tapiKey: string\n\t/** Base URL for self-hosted CE. Defaults to Plausible Cloud. */\n\thost?: string\n\t/** Maximum days of historical data. Defaults to 730. Pass null to disable clamping. */\n\tmaxLookbackDays?: number | null\n\t/**\n\t * Site domain for the legacy script tag (`data-domain`). Takes priority over `scriptId`.\n\t * The adapter declares `capture` only when one of the two is set.\n\t */\n\tdomain?: string\n\t/**\n\t * Per-site tracker id (`pa-<id>.js`) for the newer per-site script model. The adapter\n\t * declares `capture` only when one of it and `domain` is set.\n\t */\n\tscriptId?: string\n}\n\n/**\n * Plausible's official per-site stub, as served on plausible.io's own pages: `plausible.q`\n * queues calls the tracker replays on load, and `plausible.init` parks the options on\n * `plausible.o` for it to read. It makes the inline safe next to the async loader in either\n * order, which the bare `plausible.init(...)` call was not. `init` is guarded with `||`\n * (the official one assigns unconditionally) because here the tracker is a separate async\n * tag and may win the race, and overwriting the real `init` with the stub would lose the\n * endpoint.\n */\nconst PLAUSIBLE_STUB =\n\t'window.plausible=window.plausible||function(){(window.plausible.q=window.plausible.q||[]).push(arguments)},window.plausible.init=window.plausible.init||function(e){window.plausible.o=e||{}};'\n\nfunction buildCapture(config: PlausibleConfig): CaptureSupport {\n\tconst base = config.host ?? 'https://plausible.io'\n\tconst scripts = (path: string) => {\n\t\tif (config.domain) {\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\tsrc: `${path}/js/script.js`,\n\t\t\t\t\tdefer: true,\n\t\t\t\t\tattrs: { 'data-domain': config.domain, 'data-api': `${path}/api/event` },\n\t\t\t\t},\n\t\t\t]\n\t\t}\n\t\tif (config.scriptId) {\n\t\t\treturn [\n\t\t\t\t{ src: `${path}/js/pa-${config.scriptId}.js`, async: true },\n\t\t\t\t{\n\t\t\t\t\tinline: `${PLAUSIBLE_STUB}plausible.init({endpoint:${JSON.stringify(`${path}/api/event`)}})`,\n\t\t\t\t},\n\t\t\t]\n\t\t}\n\t\treturn []\n\t}\n\treturn {\n\t\tproxy: {\n\t\t\troutes: [\n\t\t\t\t{ source: '/js/:script*', upstream: `${base}/js/:script*` },\n\t\t\t\t{ source: '/api/event', upstream: `${base}/api/event` },\n\t\t\t],\n\t\t},\n\t\tsnippet: ({ path }) => ({ scripts: scripts(path) }),\n\t\tclient: { kind: 'plausible' },\n\t}\n}\n\nconst METRIC_MAP: Partial<Record<MetricKey, string>> = {\n\tpageviews: 'pageviews',\n\tvisitors: 'visitors',\n\tvisits: 'visits',\n\tsessions: 'visits',\n\tbounceRate: 'bounce_rate',\n\tavgDuration: 'visit_duration',\n\tevents: 'events',\n\tscrollDepth: 'scroll_depth',\n\trevenue: 'total_revenue',\n}\n\nconst DIMENSION_MAP: Partial<Record<DimensionKey, string>> = {\n\tpage: 'event:page',\n\tsource: 'visit:source',\n\treferrer: 'visit:referrer',\n\tdevice: 'visit:device',\n\tbrowser: 'visit:browser',\n\tos: 'visit:os',\n\tcountry: 'visit:country',\n\tregion: 'visit:region',\n\tcity: 'visit:city',\n\tutmSource: 'visit:utm_source',\n\tutmMedium: 'visit:utm_medium',\n\tutmCampaign: 'visit:utm_campaign',\n}\n\nconst plausibleMetrics: ReadonlySet<MetricKey> = new Set(Object.keys(METRIC_MAP) as MetricKey[])\nconst plausibleDimensions: ReadonlySet<DimensionKey> = new Set(\n\tObject.keys(DIMENSION_MAP) as DimensionKey[]\n)\n\ninterface PlausibleResponse {\n\tresults: Array<{ metrics: number[]; dimensions: string[] }>\n}\n\n// visit_duration is reported in seconds; the contract avgDuration is milliseconds.\nconst toContractValue = (metric: MetricKey, raw: number): number =>\n\tmetric === 'avgDuration' ? Math.round(raw * 1000) : raw\n\nexport function plausible(config: PlausibleConfig): AnalyticsAdapter {\n\tconst host = config.host ?? 'https://plausible.io'\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 730\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\tperPageQuery: true,\n\t\trealtime: false,\n\t\tcomparison: false,\n\t\tminGranularity: 'day',\n\t\tmaxLookbackDays,\n\t\tmetrics: plausibleMetrics,\n\t\tdimensions: plausibleDimensions,\n\t\tfilters: plausibleDimensions,\n\t\tfilterOperators: new Set(['eq']),\n\t\tbatchPageReport: true,\n\t\trateLimit: { requestsPerHour: 600 },\n\t\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n\t}\n\n\treturn {\n\t\tid: 'plausible',\n\t\tlabel: 'Plausible',\n\t\tcapabilities,\n\t\t...(config.domain || config.scriptId ? { capture: buildCapture(config) } : {}),\n\t\tisConfigured: () => Boolean(config.siteId && config.apiKey),\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst wanted = q.metrics.filter((m) => METRIC_MAP[m])\n\t\t\t// Several contract metrics alias one Plausible metric (sessions and visits both\n\t\t\t// map to \"visits\"), so dedupe before sending and read each contract metric back\n\t\t\t// from its provider key's position rather than the request index.\n\t\t\tconst providerMetrics = [...new Set(wanted.map((m) => METRIC_MAP[m] as string))]\n\t\t\tconst dims = (q.dimensions ?? []).filter((d) => DIMENSION_MAP[d])\n\t\t\tconst filters: Array<[string, string, string[]]> = []\n\t\t\tif (q.path) {\n\t\t\t\tfilters.push(['is', 'event:page', [q.path]])\n\t\t\t}\n\t\t\tif (q.hostname) {\n\t\t\t\tfilters.push(['is', 'event:hostname', [q.hostname]])\n\t\t\t}\n\t\t\t// Capability gating (filters/filterOperators) is the real contract upstream; an\n\t\t\t// unsupported dimension or operator is dropped here as the safety net.\n\t\t\tfor (const filter of q.filters ?? []) {\n\t\t\t\tconst mapped = DIMENSION_MAP[filter.dimension]\n\t\t\t\tif (!mapped || filter.operator !== 'eq') {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tfilters.push(['is', mapped, [filter.value]])\n\t\t\t}\n\n\t\t\tconst readRow = (row: { metrics: number[] }): Partial<Record<MetricKey, number>> => {\n\t\t\t\tconst out: Partial<Record<MetricKey, number>> = {}\n\t\t\t\tfor (const m of wanted) {\n\t\t\t\t\tconst idx = providerMetrics.indexOf(METRIC_MAP[m] as string)\n\t\t\t\t\tout[m] = toContractValue(m, row.metrics[idx] ?? 0)\n\t\t\t\t}\n\t\t\t\treturn out\n\t\t\t}\n\n\t\t\tconst postQuery = (extra: Record<string, unknown>): Promise<PlausibleResponse> =>\n\t\t\t\tfetchJson<PlausibleResponse>(`${host}/api/v2/query`, {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders: { authorization: `Bearer ${config.apiKey}` },\n\t\t\t\t\tbody: {\n\t\t\t\t\t\tsite_id: config.siteId,\n\t\t\t\t\t\tmetrics: providerMetrics,\n\t\t\t\t\t\tdate_range: [\n\t\t\t\t\t\t\tzonedCalendarDay(q.dateRange.start, q.timezone ?? DEFAULT_TIMEZONE),\n\t\t\t\t\t\t\tzonedCalendarDay(q.dateRange.end, q.timezone ?? DEFAULT_TIMEZONE),\n\t\t\t\t\t\t],\n\t\t\t\t\t\t...(filters.length ? { filters } : {}),\n\t\t\t\t\t\t...extra,\n\t\t\t\t\t},\n\t\t\t\t\tsignal: ctx.signal,\n\t\t\t\t\tprovider: 'plausible',\n\t\t\t\t})\n\n\t\t\tconst fetchTotals = async (): Promise<Partial<Record<MetricKey, number>>> => {\n\t\t\t\tconst data = await postQuery({})\n\t\t\t\treturn data.results[0] ? readRow(data.results[0]) : {}\n\t\t\t}\n\n\t\t\tif (q.granularity === 'day' && !dims.length) {\n\t\t\t\tconst [seriesData, totals] = await Promise.all([\n\t\t\t\t\tpostQuery({ dimensions: ['time:day'] }),\n\t\t\t\t\tfetchTotals(),\n\t\t\t\t])\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const row of seriesData.results) {\n\t\t\t\t\tconst ts = dayIso(row.dimensions[0] ?? '')\n\t\t\t\t\tif (ts) {\n\t\t\t\t\t\trows.push({ timestamp: ts, metrics: readRow(row) })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { rows, totals, meta: { provider: 'plausible', fetchedAt } }\n\t\t\t}\n\n\t\t\tif (!dims.length) {\n\t\t\t\tconst totals = await fetchTotals()\n\t\t\t\treturn { rows: [{ metrics: totals }], totals, meta: { provider: 'plausible', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst data = await postQuery({ dimensions: dims.map((d) => DIMENSION_MAP[d] as string) })\n\t\t\tconst rows: AnalyticsRow[] = data.results.map((row) => {\n\t\t\t\tconst dimValues: Partial<Record<DimensionKey, string>> = {}\n\t\t\t\tfor (let i = 0; i < dims.length; i++) {\n\t\t\t\t\tconst d = dims[i]\n\t\t\t\t\tif (d !== undefined) {\n\t\t\t\t\t\tdimValues[d] = row.dimensions[i] ?? ''\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { dimensions: dimValues, metrics: readRow(row) }\n\t\t\t})\n\t\t\treturn { rows, totals: undefined, meta: { provider: 'plausible', fetchedAt } }\n\t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KAAG;KAAQ,MAAM;MAAE,UAAU;MAAa;KAAU;IAAE;GAC1F;GAaA,OAAO;IAAE,OAVoB,MADV,UAAU,EAAE,YAAY,KAAK,KAAK,MAAM,cAAc,EAAY,EAAE,CAAC,GACtD,QAAQ,KAAK,QAAQ;KACtD,MAAM,YAAmD,CAAC;KAC1D,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;MACrC,MAAM,IAAI,KAAK;MACf,IAAI,MAAM,KAAA,GACT,UAAU,KAAK,IAAI,WAAW,MAAM;KAEtC;KACA,OAAO;MAAE,YAAY;MAAW,SAAS,QAAQ,GAAG;KAAE;IACvD,CACY;IAAG,QAAQ,KAAA;IAAW,MAAM;KAAE,UAAU;KAAa;IAAU;GAAE;EAC9E;CACD;AACD"}
@@ -4,7 +4,7 @@ import { AnalyticsAdapter } from "../../core/contract.js";
4
4
  interface PosthogConfig {
5
5
  /** PostHog project id (numeric). */
6
6
  projectId: string;
7
- /** Personal API key with the "Query Read" scope (phx_...). */
7
+ /** Personal API key with the "Query Read" scope (phx_...). Never exposed to the browser. */
8
8
  apiKey: string;
9
9
  /** API host. Defaults to US Cloud; EU is https://eu.posthog.com, self-host is your instance URL. */
10
10
  host?: string;
@@ -16,6 +16,15 @@ interface PosthogConfig {
16
16
  * read filters on it. Both the property name and value are escaped literals.
17
17
  */
18
18
  scopeProperty?: string;
19
+ /** Cloud region for the proxied capture routes. Derived from `host` when omitted. */
20
+ region?: 'us' | 'eu';
21
+ /**
22
+ * The public browser key (phc_...) sent to `posthog.init`. Distinct from `apiKey`, the
23
+ * private Query API key, which must never reach the client. The adapter declares
24
+ * `capture` only when this is set: without it the install reads dashboards and captures
25
+ * nothing, so it gets no public proxy and no snippet.
26
+ */
27
+ projectToken?: string;
19
28
  }
20
29
  declare function posthog(config: PosthogConfig): AnalyticsAdapter;
21
30
  //#endregion
@@ -2,6 +2,52 @@ import { dayIso, hourIso } from "../series.js";
2
2
  import { fetchJson } from "../http/fetchJson.js";
3
3
  //#region src/adapters/posthog/posthog.ts
4
4
  const US_CLOUD = "https://us.posthog.com";
5
+ const resolveRegion = (config) => {
6
+ if (config.region) return config.region;
7
+ return config.host?.includes("eu.posthog.com") ? "eu" : "us";
8
+ };
9
+ /**
10
+ * PostHog's official install stub (https://posthog.com/docs/libraries/js), trimmed to the
11
+ * methods this plugin and a host are likely to call before the SDK lands. It has to be one
12
+ * self-sequencing script: `init` is what injects `array.js`, deriving the URL from
13
+ * `api_host` (the `.i.posthog.com` rewrite is a no-op on a first-party proxy path, so it
14
+ * resolves to `<path>/static/array.js`, exactly the route the proxy declares). Every call
15
+ * made before the SDK arrives is queued on the stub and replayed by it.
16
+ *
17
+ * One addition to the official code: the injected tag inherits the nonce of the inline that
18
+ * injected it, or a nonce CSP without `strict-dynamic` would pass the inline and block the
19
+ * bundle. `document.currentScript` is the inline itself during its own synchronous run, on
20
+ * the server-rendered path and the loader's path alike. The IDL property is read first
21
+ * because browsers blank the content attribute once the document is parsed.
22
+ */
23
+ const POSTHOG_STUB = "!function(t,e){var o,n,p,r,c;e.__SV||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(\".\");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement(\"script\")).type=\"text/javascript\",p.crossOrigin=\"anonymous\",p.async=!0,p.src=s.api_host.replace(\".i.posthog.com\",\"-assets.i.posthog.com\")+\"/static/array.js\",(c=t.currentScript&&(t.currentScript.nonce||t.currentScript.getAttribute(\"nonce\")))&&(p.nonce=c,p.setAttribute(\"nonce\",c)),(r=t.getElementsByTagName(\"script\")[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a=\"posthog\",u.people=u.people||[],o=\"init capture register register_once identify group alias reset setPersonProperties captureException opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing getFeatureFlag isFeatureEnabled reloadFeatureFlags onFeatureFlags on debug\".split(\" \"),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);";
24
+ function buildCapture(config, token) {
25
+ const region = resolveRegion(config);
26
+ return {
27
+ proxy: {
28
+ trailingSlashes: true,
29
+ routes: [
30
+ {
31
+ source: "/static/:p*",
32
+ upstream: `https://${region}-assets.i.posthog.com/static/:p*`
33
+ },
34
+ {
35
+ source: "/array/:p*",
36
+ upstream: `https://${region}-assets.i.posthog.com/array/:p*`
37
+ },
38
+ {
39
+ source: "/:p*",
40
+ upstream: `https://${region}.i.posthog.com/:p*`
41
+ }
42
+ ]
43
+ },
44
+ snippet: ({ path }) => ({ scripts: [{ inline: `${POSTHOG_STUB}posthog.init(${JSON.stringify(token)},{api_host:${JSON.stringify(path)},ui_host:${JSON.stringify(`https://${region}.posthog.com`)}})` }] }),
45
+ client: {
46
+ kind: "posthog",
47
+ token
48
+ }
49
+ };
50
+ }
5
51
  const METRIC_SQL_PAGEVIEW = {
6
52
  pageviews: "count()",
7
53
  visitors: "count(DISTINCT person_id)",
@@ -54,6 +100,7 @@ function posthog(config) {
54
100
  },
55
101
  ...config.scopeProperty ? { scopedQueries: true } : {}
56
102
  },
103
+ ...config.projectToken ? { capture: buildCapture(config, config.projectToken) } : {},
57
104
  isConfigured: () => Boolean(config.projectId && config.apiKey),
58
105
  async query(q, ctx) {
59
106
  const fetchedAt = q.dateRange.end.toISOString();
@@ -1 +1 @@
1
- {"version":3,"file":"posthog.js","names":[],"sources":["../../../src/adapters/posthog/posthog.ts"],"sourcesContent":["import type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tDimensionKey,\n\tMetricKey,\n} from '../../core/contract'\nimport { fetchJson } from '../http/fetchJson'\nimport { dayIso, hourIso } from '../series'\n\nexport interface PosthogConfig {\n\t/** PostHog project id (numeric). */\n\tprojectId: string\n\t/** Personal API key with the \"Query Read\" scope (phx_...). */\n\tapiKey: string\n\t/** API host. Defaults to US Cloud; EU is https://eu.posthog.com, self-host is your instance URL. */\n\thost?: string\n\t/** Maximum days of historical data. Defaults to 730. Pass null to disable clamping. */\n\tmaxLookbackDays?: number | null\n\t/**\n\t * Event property holding a query's scope (e.g. 'tenant'). Enables scoped queries:\n\t * one platform project captures every scope with this property set, and a scoped\n\t * read filters on it. Both the property name and value are escaped literals.\n\t */\n\tscopeProperty?: string\n}\n\nconst US_CLOUD = 'https://us.posthog.com'\n\n// Pageview-scoped expressions, used when the read filters the WHERE to `$pageview`.\n// visits and sessions share the distinct-session expression and are deduped before the\n// SELECT, then read back by the expression's position.\nconst METRIC_SQL_PAGEVIEW: Partial<Record<MetricKey, string>> = {\n\tpageviews: 'count()',\n\tvisitors: 'count(DISTINCT person_id)',\n\tvisits: 'count(DISTINCT properties.$session_id)',\n\tsessions: 'count(DISTINCT properties.$session_id)',\n}\n\n// All-event expressions, used when `events` (total captured events, matching PostHog's own\n// Events definition) or an `event`-name breakdown is requested. The WHERE is not filtered to\n// `$pageview`, so the pageview-family metrics scope themselves with conditional aggregates.\nconst METRIC_SQL_ALL: Partial<Record<MetricKey, string>> = {\n\tpageviews: \"countIf(event = '$pageview')\",\n\tvisitors: \"count(DISTINCT if(event = '$pageview', person_id, NULL))\",\n\tvisits: \"count(DISTINCT if(event = '$pageview', properties.$session_id, NULL))\",\n\tsessions: \"count(DISTINCT if(event = '$pageview', properties.$session_id, NULL))\",\n\tevents: 'count()',\n}\n\nconst DIMENSION_SQL: Partial<Record<DimensionKey, string>> = {\n\tpage: 'properties.$pathname',\n\tevent: 'event',\n}\n\nconst posthogMetrics: ReadonlySet<MetricKey> = new Set(Object.keys(METRIC_SQL_ALL) as MetricKey[])\nconst posthogDimensions: ReadonlySet<DimensionKey> = new Set(\n\tObject.keys(DIMENSION_SQL) as DimensionKey[]\n)\n\n// The Query API has no parameter binding, so values are inlined as quoted literals.\n// Escape backslashes first, then single quotes, so a crafted path cannot break out.\nconst sqlString = (value: string): string =>\n\t`'${value.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")}'`\n\n// ILIKE treats % and _ as wildcards and backslash as its own escape char; backslash-escape\n// backslash first (so a raw \\ in the value doesn't get read as escaping the next char),\n// then % and _, before the whole thing is wrapped in % ... % and quoted.\nconst escapeLikeValue = (value: string): string => value.replace(/[\\\\%_]/g, (c) => `\\\\${c}`)\n\nconst sqlDateTimeLiteral = (d: Date): string =>\n\tsqlString(d.toISOString().slice(0, 19).replace('T', ' '))\n\ninterface PosthogQueryResponse {\n\tcolumns: string[]\n\ttypes: string[]\n\tresults: unknown[][]\n}\n\nexport function posthog(config: PosthogConfig): AnalyticsAdapter {\n\tconst host = config.host ?? US_CLOUD\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 730\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\tperPageQuery: true,\n\t\trealtime: false,\n\t\tcomparison: false,\n\t\tminGranularity: 'hour',\n\t\tmaxLookbackDays,\n\t\tmetrics: posthogMetrics,\n\t\tdimensions: posthogDimensions,\n\t\tfilters: posthogDimensions,\n\t\tfilterOperators: new Set(['eq', 'contains', 'matches']),\n\t\tbatchPageReport: true,\n\t\trateLimit: { requestsPerMinute: 240, requestsPerHour: 2400 },\n\t\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n\t\t...(config.scopeProperty ? { scopedQueries: true } : {}),\n\t}\n\n\treturn {\n\t\tid: 'posthog',\n\t\tlabel: 'PostHog',\n\t\tcapabilities,\n\t\tisConfigured: () => Boolean(config.projectId && config.apiKey),\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst breakdownDim = (q.dimensions ?? []).find((d) => DIMENSION_SQL[d])\n\t\t\t// A total-events metric, an event-name breakdown, or a filter on the event\n\t\t\t// dimension must scan every event, not just pageviews (a `$pageview` WHERE\n\t\t\t// clause combined with an `event = 'x'` filter would be self-contradictory and\n\t\t\t// zero every metric); those reads switch to conditional aggregation.\n\t\t\tconst scanAllEvents =\n\t\t\t\tq.metrics.includes('events') ||\n\t\t\t\tbreakdownDim === 'event' ||\n\t\t\t\t(q.filters ?? []).some((f) => f.dimension === 'event' && DIMENSION_SQL[f.dimension])\n\t\t\tconst metricSql = scanAllEvents ? METRIC_SQL_ALL : METRIC_SQL_PAGEVIEW\n\t\t\tconst wanted = q.metrics.filter((m) => metricSql[m])\n\t\t\tconst exprs = [...new Set(wanted.map((m) => metricSql[m] as string))]\n\n\t\t\tconst where = [\n\t\t\t\t`timestamp >= toDateTime(${sqlDateTimeLiteral(q.dateRange.start)})`,\n\t\t\t\t`timestamp <= toDateTime(${sqlDateTimeLiteral(q.dateRange.end)})`,\n\t\t\t]\n\t\t\tif (!scanAllEvents) {\n\t\t\t\twhere.unshift(\"event = '$pageview'\")\n\t\t\t}\n\t\t\tif (q.path) {\n\t\t\t\twhere.push(`properties.$pathname = ${sqlString(q.path)}`)\n\t\t\t}\n\t\t\tif (q.hostname) {\n\t\t\t\twhere.push(`properties.$host = ${sqlString(q.hostname)}`)\n\t\t\t}\n\t\t\tif (config.scopeProperty && q.scope !== undefined) {\n\t\t\t\t// Bracket property access with escaped literals: neither the configured\n\t\t\t\t// property name nor the scope value can break out of the HogQL string.\n\t\t\t\twhere.push(`properties[${sqlString(config.scopeProperty)}] = ${sqlString(q.scope)}`)\n\t\t\t}\n\t\t\t// Capability gating (filters/filterOperators) is the real contract upstream; an\n\t\t\t// unsupported dimension is dropped here as the safety net so it never throws.\n\t\t\tfor (const filter of q.filters ?? []) {\n\t\t\t\tconst expr = DIMENSION_SQL[filter.dimension]\n\t\t\t\tif (!expr) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif (filter.operator === 'eq') {\n\t\t\t\t\twhere.push(`${expr} = ${sqlString(filter.value)}`)\n\t\t\t\t} else if (filter.operator === 'contains') {\n\t\t\t\t\twhere.push(`${expr} ILIKE ${sqlString(`%${escapeLikeValue(filter.value)}%`)}`)\n\t\t\t\t} else if (filter.operator === 'matches') {\n\t\t\t\t\twhere.push(`match(${expr}, ${sqlString(filter.value)})`)\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst selectMetrics = exprs.map((expr, i) => `${expr} AS m${i}`)\n\n\t\t\tconst runSql = (sql: string): Promise<PosthogQueryResponse> =>\n\t\t\t\tfetchJson<PosthogQueryResponse>(`${host}/api/projects/${config.projectId}/query/`, {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders: { authorization: `Bearer ${config.apiKey}` },\n\t\t\t\t\tbody: { query: { kind: 'HogQLQuery', query: sql } },\n\t\t\t\t\tsignal: ctx.signal,\n\t\t\t\t\tprovider: 'posthog',\n\t\t\t\t})\n\n\t\t\tconst readRow = (row: unknown[], offset: number): Partial<Record<MetricKey, number>> => {\n\t\t\t\tconst out: Partial<Record<MetricKey, number>> = {}\n\t\t\t\tfor (const m of wanted) {\n\t\t\t\t\tconst idx = exprs.indexOf(metricSql[m] as string)\n\t\t\t\t\tout[m] = Number(row[offset + idx] ?? 0)\n\t\t\t\t}\n\t\t\t\treturn out\n\t\t\t}\n\n\t\t\tconst fetchTotals = async (): Promise<Partial<Record<MetricKey, number>>> => {\n\t\t\t\tconst data = await runSql(\n\t\t\t\t\t`SELECT ${selectMetrics.join(', ')} FROM events WHERE ${where.join(' AND ')}`\n\t\t\t\t)\n\t\t\t\tconst row = data.results[0]\n\t\t\t\treturn row ? readRow(row, 0) : {}\n\t\t\t}\n\n\t\t\tif (q.granularity === 'day' && !breakdownDim) {\n\t\t\t\t// HogQL buckets in the timezone argument when given; without it PostHog falls back\n\t\t\t\t// to the project's own timezone, so the resolved reporting timezone (UTC included)\n\t\t\t\t// is always passed to keep day buckets deterministic across projects. The window\n\t\t\t\t// literals stay UTC instants (already aligned to the reporting-timezone day\n\t\t\t\t// boundary by the caller).\n\t\t\t\tconst dayExpr = `toStartOfDay(timestamp, ${sqlString(q.timezone ?? 'UTC')})`\n\t\t\t\tconst seriesSql = `SELECT ${dayExpr} AS day, ${selectMetrics.join(', ')} FROM events WHERE ${where.join(' AND ')} GROUP BY day ORDER BY day`\n\t\t\t\tconst [seriesData, totals] = await Promise.all([runSql(seriesSql), fetchTotals()])\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const row of seriesData.results) {\n\t\t\t\t\tconst ts = dayIso(String(row[0] ?? ''))\n\t\t\t\t\tif (ts) {\n\t\t\t\t\t\trows.push({ timestamp: ts, metrics: readRow(row, 1) })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { rows, totals, meta: { provider: 'posthog', fetchedAt } }\n\t\t\t}\n\n\t\t\tif (q.granularity === 'hour' && !breakdownDim) {\n\t\t\t\t// Same timezone-bucketing rationale as the day branch above, at hour resolution.\n\t\t\t\tconst hourExpr = `toStartOfHour(timestamp, ${sqlString(q.timezone ?? 'UTC')})`\n\t\t\t\tconst seriesSql = `SELECT ${hourExpr} AS hour, ${selectMetrics.join(', ')} FROM events WHERE ${where.join(' AND ')} GROUP BY hour ORDER BY hour`\n\t\t\t\tconst [seriesData, totals] = await Promise.all([runSql(seriesSql), fetchTotals()])\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const row of seriesData.results) {\n\t\t\t\t\tconst ts = hourIso(String(row[0] ?? ''))\n\t\t\t\t\tif (ts) {\n\t\t\t\t\t\trows.push({ timestamp: ts, metrics: readRow(row, 1) })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { rows, totals, meta: { provider: 'posthog', fetchedAt } }\n\t\t\t}\n\n\t\t\tif (breakdownDim) {\n\t\t\t\tconst dimSql = DIMENSION_SQL[breakdownDim] as string\n\t\t\t\tconst sql = `SELECT ${dimSql} AS dim, ${selectMetrics.join(', ')} FROM events WHERE ${where.join(' AND ')} GROUP BY dim ORDER BY m0 DESC LIMIT ${q.limit ?? 100}`\n\t\t\t\tconst data = await runSql(sql)\n\t\t\t\tconst rows: AnalyticsRow[] = data.results.map((row) => ({\n\t\t\t\t\tdimensions: { [breakdownDim]: String(row[0] ?? '') },\n\t\t\t\t\tmetrics: readRow(row, 1),\n\t\t\t\t}))\n\t\t\t\treturn { rows, totals: undefined, meta: { provider: 'posthog', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst totals = await fetchTotals()\n\t\t\treturn { rows: [{ metrics: totals }], totals, meta: { provider: 'posthog', fetchedAt } }\n\t\t},\n\t}\n}\n"],"mappings":";;;AA8BA,MAAM,WAAW;AAKjB,MAAM,sBAA0D;CAC/D,WAAW;CACX,UAAU;CACV,QAAQ;CACR,UAAU;AACX;AAKA,MAAM,iBAAqD;CAC1D,WAAW;CACX,UAAU;CACV,QAAQ;CACR,UAAU;CACV,QAAQ;AACT;AAEA,MAAM,gBAAuD;CAC5D,MAAM;CACN,OAAO;AACR;AAEA,MAAM,iBAAyC,IAAI,IAAI,OAAO,KAAK,cAAc,CAAgB;AACjG,MAAM,oBAA+C,IAAI,IACxD,OAAO,KAAK,aAAa,CAC1B;AAIA,MAAM,aAAa,UAClB,IAAI,MAAM,QAAQ,OAAO,MAAM,EAAE,QAAQ,MAAM,KAAK,EAAE;AAKvD,MAAM,mBAAmB,UAA0B,MAAM,QAAQ,YAAY,MAAM,KAAK,GAAG;AAE3F,MAAM,sBAAsB,MAC3B,UAAU,EAAE,YAAY,EAAE,MAAM,GAAG,EAAE,EAAE,QAAQ,KAAK,GAAG,CAAC;AAQzD,SAAgB,QAAQ,QAAyC;CAChE,MAAM,OAAO,OAAO,QAAQ;CAmB5B,OAAO;EACN,IAAI;EACJ,OAAO;EACP,cAAA;GAlBA,cAAc;GACd,UAAU;GACV,YAAY;GACZ,gBAAgB;GAChB,iBAPuB,OAAO,oBAAoB,KAAA,IAAY,OAAO,kBAAkB;GAQvF,SAAS;GACT,YAAY;GACZ,SAAS;GACT,iBAAiB,IAAI,IAAI;IAAC;IAAM;IA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C,EAAE,SAAS,OAAO,CAAC;IAAG;IAAQ,MAAM;KAAE,UAAU;KAAW;IAAU;GAAE;EACxF;CACD;AACD"}
1
+ {"version":3,"file":"posthog.js","names":[],"sources":["../../../src/adapters/posthog/posthog.ts"],"sourcesContent":["import 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 { fetchJson } from '../http/fetchJson'\nimport { dayIso, hourIso } from '../series'\n\nexport interface PosthogConfig {\n\t/** PostHog project id (numeric). */\n\tprojectId: string\n\t/** Personal API key with the \"Query Read\" scope (phx_...). Never exposed to the browser. */\n\tapiKey: string\n\t/** API host. Defaults to US Cloud; EU is https://eu.posthog.com, self-host is your instance URL. */\n\thost?: string\n\t/** Maximum days of historical data. Defaults to 730. Pass null to disable clamping. */\n\tmaxLookbackDays?: number | null\n\t/**\n\t * Event property holding a query's scope (e.g. 'tenant'). Enables scoped queries:\n\t * one platform project captures every scope with this property set, and a scoped\n\t * read filters on it. Both the property name and value are escaped literals.\n\t */\n\tscopeProperty?: string\n\t/** Cloud region for the proxied capture routes. Derived from `host` when omitted. */\n\tregion?: 'us' | 'eu'\n\t/**\n\t * The public browser key (phc_...) sent to `posthog.init`. Distinct from `apiKey`, the\n\t * private Query API key, which must never reach the client. The adapter declares\n\t * `capture` only when this is set: without it the install reads dashboards and captures\n\t * nothing, so it gets no public proxy and no snippet.\n\t */\n\tprojectToken?: string\n}\n\nconst US_CLOUD = 'https://us.posthog.com'\n\nconst resolveRegion = (config: PosthogConfig): 'us' | 'eu' => {\n\tif (config.region) {\n\t\treturn config.region\n\t}\n\treturn config.host?.includes('eu.posthog.com') ? 'eu' : 'us'\n}\n\n/**\n * PostHog's official install stub (https://posthog.com/docs/libraries/js), trimmed to the\n * methods this plugin and a host are likely to call before the SDK lands. It has to be one\n * self-sequencing script: `init` is what injects `array.js`, deriving the URL from\n * `api_host` (the `.i.posthog.com` rewrite is a no-op on a first-party proxy path, so it\n * resolves to `<path>/static/array.js`, exactly the route the proxy declares). Every call\n * made before the SDK arrives is queued on the stub and replayed by it.\n *\n * One addition to the official code: the injected tag inherits the nonce of the inline that\n * injected it, or a nonce CSP without `strict-dynamic` would pass the inline and block the\n * bundle. `document.currentScript` is the inline itself during its own synchronous run, on\n * the server-rendered path and the loader's path alike. The IDL property is read first\n * because browsers blank the content attribute once the document is parsed.\n */\nconst POSTHOG_STUB =\n\t'!function(t,e){var o,n,p,r,c;e.__SV||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(\".\");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement(\"script\")).type=\"text/javascript\",p.crossOrigin=\"anonymous\",p.async=!0,p.src=s.api_host.replace(\".i.posthog.com\",\"-assets.i.posthog.com\")+\"/static/array.js\",(c=t.currentScript&&(t.currentScript.nonce||t.currentScript.getAttribute(\"nonce\")))&&(p.nonce=c,p.setAttribute(\"nonce\",c)),(r=t.getElementsByTagName(\"script\")[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a=\"posthog\",u.people=u.people||[],o=\"init capture register register_once identify group alias reset setPersonProperties captureException opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing getFeatureFlag isFeatureEnabled reloadFeatureFlags onFeatureFlags on debug\".split(\" \"),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);'\n\nfunction buildCapture(config: PosthogConfig, token: string): CaptureSupport {\n\tconst region = resolveRegion(config)\n\treturn {\n\t\tproxy: {\n\t\t\ttrailingSlashes: true,\n\t\t\troutes: [\n\t\t\t\t{\n\t\t\t\t\tsource: '/static/:p*',\n\t\t\t\t\tupstream: `https://${region}-assets.i.posthog.com/static/:p*`,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tsource: '/array/:p*',\n\t\t\t\t\tupstream: `https://${region}-assets.i.posthog.com/array/:p*`,\n\t\t\t\t},\n\t\t\t\t{ source: '/:p*', upstream: `https://${region}.i.posthog.com/:p*` },\n\t\t\t],\n\t\t},\n\t\tsnippet: ({ path }) => ({\n\t\t\tscripts: [\n\t\t\t\t{\n\t\t\t\t\tinline: `${POSTHOG_STUB}posthog.init(${JSON.stringify(token)},{api_host:${JSON.stringify(path)},ui_host:${JSON.stringify(`https://${region}.posthog.com`)}})`,\n\t\t\t\t},\n\t\t\t],\n\t\t}),\n\t\tclient: { kind: 'posthog', token },\n\t}\n}\n\n// Pageview-scoped expressions, used when the read filters the WHERE to `$pageview`.\n// visits and sessions share the distinct-session expression and are deduped before the\n// SELECT, then read back by the expression's position.\nconst METRIC_SQL_PAGEVIEW: Partial<Record<MetricKey, string>> = {\n\tpageviews: 'count()',\n\tvisitors: 'count(DISTINCT person_id)',\n\tvisits: 'count(DISTINCT properties.$session_id)',\n\tsessions: 'count(DISTINCT properties.$session_id)',\n}\n\n// All-event expressions, used when `events` (total captured events, matching PostHog's own\n// Events definition) or an `event`-name breakdown is requested. The WHERE is not filtered to\n// `$pageview`, so the pageview-family metrics scope themselves with conditional aggregates.\nconst METRIC_SQL_ALL: Partial<Record<MetricKey, string>> = {\n\tpageviews: \"countIf(event = '$pageview')\",\n\tvisitors: \"count(DISTINCT if(event = '$pageview', person_id, NULL))\",\n\tvisits: \"count(DISTINCT if(event = '$pageview', properties.$session_id, NULL))\",\n\tsessions: \"count(DISTINCT if(event = '$pageview', properties.$session_id, NULL))\",\n\tevents: 'count()',\n}\n\nconst DIMENSION_SQL: Partial<Record<DimensionKey, string>> = {\n\tpage: 'properties.$pathname',\n\tevent: 'event',\n}\n\nconst posthogMetrics: ReadonlySet<MetricKey> = new Set(Object.keys(METRIC_SQL_ALL) as MetricKey[])\nconst posthogDimensions: ReadonlySet<DimensionKey> = new Set(\n\tObject.keys(DIMENSION_SQL) as DimensionKey[]\n)\n\n// The Query API has no parameter binding, so values are inlined as quoted literals.\n// Escape backslashes first, then single quotes, so a crafted path cannot break out.\nconst sqlString = (value: string): string =>\n\t`'${value.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")}'`\n\n// ILIKE treats % and _ as wildcards and backslash as its own escape char; backslash-escape\n// backslash first (so a raw \\ in the value doesn't get read as escaping the next char),\n// then % and _, before the whole thing is wrapped in % ... % and quoted.\nconst escapeLikeValue = (value: string): string => value.replace(/[\\\\%_]/g, (c) => `\\\\${c}`)\n\nconst sqlDateTimeLiteral = (d: Date): string =>\n\tsqlString(d.toISOString().slice(0, 19).replace('T', ' '))\n\ninterface PosthogQueryResponse {\n\tcolumns: string[]\n\ttypes: string[]\n\tresults: unknown[][]\n}\n\nexport function posthog(config: PosthogConfig): AnalyticsAdapter {\n\tconst host = config.host ?? US_CLOUD\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 730\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\tperPageQuery: true,\n\t\trealtime: false,\n\t\tcomparison: false,\n\t\tminGranularity: 'hour',\n\t\tmaxLookbackDays,\n\t\tmetrics: posthogMetrics,\n\t\tdimensions: posthogDimensions,\n\t\tfilters: posthogDimensions,\n\t\tfilterOperators: new Set(['eq', 'contains', 'matches']),\n\t\tbatchPageReport: true,\n\t\trateLimit: { requestsPerMinute: 240, requestsPerHour: 2400 },\n\t\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n\t\t...(config.scopeProperty ? { scopedQueries: true } : {}),\n\t}\n\n\treturn {\n\t\tid: 'posthog',\n\t\tlabel: 'PostHog',\n\t\tcapabilities,\n\t\t...(config.projectToken ? { capture: buildCapture(config, config.projectToken) } : {}),\n\t\tisConfigured: () => Boolean(config.projectId && config.apiKey),\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst breakdownDim = (q.dimensions ?? []).find((d) => DIMENSION_SQL[d])\n\t\t\t// A total-events metric, an event-name breakdown, or a filter on the event\n\t\t\t// dimension must scan every event, not just pageviews (a `$pageview` WHERE\n\t\t\t// clause combined with an `event = 'x'` filter would be self-contradictory and\n\t\t\t// zero every metric); those reads switch to conditional aggregation.\n\t\t\tconst scanAllEvents =\n\t\t\t\tq.metrics.includes('events') ||\n\t\t\t\tbreakdownDim === 'event' ||\n\t\t\t\t(q.filters ?? []).some((f) => f.dimension === 'event' && DIMENSION_SQL[f.dimension])\n\t\t\tconst metricSql = scanAllEvents ? METRIC_SQL_ALL : METRIC_SQL_PAGEVIEW\n\t\t\tconst wanted = q.metrics.filter((m) => metricSql[m])\n\t\t\tconst exprs = [...new Set(wanted.map((m) => metricSql[m] as string))]\n\n\t\t\tconst where = [\n\t\t\t\t`timestamp >= toDateTime(${sqlDateTimeLiteral(q.dateRange.start)})`,\n\t\t\t\t`timestamp <= toDateTime(${sqlDateTimeLiteral(q.dateRange.end)})`,\n\t\t\t]\n\t\t\tif (!scanAllEvents) {\n\t\t\t\twhere.unshift(\"event = '$pageview'\")\n\t\t\t}\n\t\t\tif (q.path) {\n\t\t\t\twhere.push(`properties.$pathname = ${sqlString(q.path)}`)\n\t\t\t}\n\t\t\tif (q.hostname) {\n\t\t\t\twhere.push(`properties.$host = ${sqlString(q.hostname)}`)\n\t\t\t}\n\t\t\tif (config.scopeProperty && q.scope !== undefined) {\n\t\t\t\t// Bracket property access with escaped literals: neither the configured\n\t\t\t\t// property name nor the scope value can break out of the HogQL string.\n\t\t\t\twhere.push(`properties[${sqlString(config.scopeProperty)}] = ${sqlString(q.scope)}`)\n\t\t\t}\n\t\t\t// Capability gating (filters/filterOperators) is the real contract upstream; an\n\t\t\t// unsupported dimension is dropped here as the safety net so it never throws.\n\t\t\tfor (const filter of q.filters ?? []) {\n\t\t\t\tconst expr = DIMENSION_SQL[filter.dimension]\n\t\t\t\tif (!expr) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif (filter.operator === 'eq') {\n\t\t\t\t\twhere.push(`${expr} = ${sqlString(filter.value)}`)\n\t\t\t\t} else if (filter.operator === 'contains') {\n\t\t\t\t\twhere.push(`${expr} ILIKE ${sqlString(`%${escapeLikeValue(filter.value)}%`)}`)\n\t\t\t\t} else if (filter.operator === 'matches') {\n\t\t\t\t\twhere.push(`match(${expr}, ${sqlString(filter.value)})`)\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst selectMetrics = exprs.map((expr, i) => `${expr} AS m${i}`)\n\n\t\t\tconst runSql = (sql: string): Promise<PosthogQueryResponse> =>\n\t\t\t\tfetchJson<PosthogQueryResponse>(`${host}/api/projects/${config.projectId}/query/`, {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders: { authorization: `Bearer ${config.apiKey}` },\n\t\t\t\t\tbody: { query: { kind: 'HogQLQuery', query: sql } },\n\t\t\t\t\tsignal: ctx.signal,\n\t\t\t\t\tprovider: 'posthog',\n\t\t\t\t})\n\n\t\t\tconst readRow = (row: unknown[], offset: number): Partial<Record<MetricKey, number>> => {\n\t\t\t\tconst out: Partial<Record<MetricKey, number>> = {}\n\t\t\t\tfor (const m of wanted) {\n\t\t\t\t\tconst idx = exprs.indexOf(metricSql[m] as string)\n\t\t\t\t\tout[m] = Number(row[offset + idx] ?? 0)\n\t\t\t\t}\n\t\t\t\treturn out\n\t\t\t}\n\n\t\t\tconst fetchTotals = async (): Promise<Partial<Record<MetricKey, number>>> => {\n\t\t\t\tconst data = await runSql(\n\t\t\t\t\t`SELECT ${selectMetrics.join(', ')} FROM events WHERE ${where.join(' AND ')}`\n\t\t\t\t)\n\t\t\t\tconst row = data.results[0]\n\t\t\t\treturn row ? readRow(row, 0) : {}\n\t\t\t}\n\n\t\t\tif (q.granularity === 'day' && !breakdownDim) {\n\t\t\t\t// HogQL buckets in the timezone argument when given; without it PostHog falls back\n\t\t\t\t// to the project's own timezone, so the resolved reporting timezone (UTC included)\n\t\t\t\t// is always passed to keep day buckets deterministic across projects. The window\n\t\t\t\t// literals stay UTC instants (already aligned to the reporting-timezone day\n\t\t\t\t// boundary by the caller).\n\t\t\t\tconst dayExpr = `toStartOfDay(timestamp, ${sqlString(q.timezone ?? 'UTC')})`\n\t\t\t\tconst seriesSql = `SELECT ${dayExpr} AS day, ${selectMetrics.join(', ')} FROM events WHERE ${where.join(' AND ')} GROUP BY day ORDER BY day`\n\t\t\t\tconst [seriesData, totals] = await Promise.all([runSql(seriesSql), fetchTotals()])\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const row of seriesData.results) {\n\t\t\t\t\tconst ts = dayIso(String(row[0] ?? ''))\n\t\t\t\t\tif (ts) {\n\t\t\t\t\t\trows.push({ timestamp: ts, metrics: readRow(row, 1) })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { rows, totals, meta: { provider: 'posthog', fetchedAt } }\n\t\t\t}\n\n\t\t\tif (q.granularity === 'hour' && !breakdownDim) {\n\t\t\t\t// Same timezone-bucketing rationale as the day branch above, at hour resolution.\n\t\t\t\tconst hourExpr = `toStartOfHour(timestamp, ${sqlString(q.timezone ?? 'UTC')})`\n\t\t\t\tconst seriesSql = `SELECT ${hourExpr} AS hour, ${selectMetrics.join(', ')} FROM events WHERE ${where.join(' AND ')} GROUP BY hour ORDER BY hour`\n\t\t\t\tconst [seriesData, totals] = await Promise.all([runSql(seriesSql), fetchTotals()])\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const row of seriesData.results) {\n\t\t\t\t\tconst ts = hourIso(String(row[0] ?? ''))\n\t\t\t\t\tif (ts) {\n\t\t\t\t\t\trows.push({ timestamp: ts, metrics: readRow(row, 1) })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { rows, totals, meta: { provider: 'posthog', fetchedAt } }\n\t\t\t}\n\n\t\t\tif (breakdownDim) {\n\t\t\t\tconst dimSql = DIMENSION_SQL[breakdownDim] as string\n\t\t\t\tconst sql = `SELECT ${dimSql} AS dim, ${selectMetrics.join(', ')} FROM events WHERE ${where.join(' AND ')} GROUP BY dim ORDER BY m0 DESC LIMIT ${q.limit ?? 100}`\n\t\t\t\tconst data = await runSql(sql)\n\t\t\t\tconst rows: AnalyticsRow[] = data.results.map((row) => ({\n\t\t\t\t\tdimensions: { [breakdownDim]: String(row[0] ?? '') },\n\t\t\t\t\tmetrics: readRow(row, 1),\n\t\t\t\t}))\n\t\t\t\treturn { rows, totals: undefined, meta: { provider: 'posthog', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst totals = await fetchTotals()\n\t\t\treturn { rows: [{ metrics: totals }], totals, meta: { provider: 'posthog', fetchedAt } }\n\t\t},\n\t}\n}\n"],"mappings":";;;AAwCA,MAAM,WAAW;AAEjB,MAAM,iBAAiB,WAAuC;CAC7D,IAAI,OAAO,QACV,OAAO,OAAO;CAEf,OAAO,OAAO,MAAM,SAAS,gBAAgB,IAAI,OAAO;AACzD;;;;;;;;;;;;;;;AAgBA,MAAM,eACL;AAED,SAAS,aAAa,QAAuB,OAA+B;CAC3E,MAAM,SAAS,cAAc,MAAM;CACnC,OAAO;EACN,OAAO;GACN,iBAAiB;GACjB,QAAQ;IACP;KACC,QAAQ;KACR,UAAU,WAAW,OAAO;IAC7B;IACA;KACC,QAAQ;KACR,UAAU,WAAW,OAAO;IAC7B;IACA;KAAE,QAAQ;KAAQ,UAAU,WAAW,OAAO;IAAoB;GACnE;EACD;EACA,UAAU,EAAE,YAAY,EACvB,SAAS,CACR,EACC,QAAQ,GAAG,aAAa,eAAe,KAAK,UAAU,KAAK,EAAE,aAAa,KAAK,UAAU,IAAI,EAAE,WAAW,KAAK,UAAU,WAAW,OAAO,aAAa,EAAE,IAC3J,CACD,EACD;EACA,QAAQ;GAAE,MAAM;GAAW;EAAM;CAClC;AACD;AAKA,MAAM,sBAA0D;CAC/D,WAAW;CACX,UAAU;CACV,QAAQ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M,YAAY,UAAU,4BADiB,UAAU,EAAE,YAAY,KAAK,EAAE,GACvC,YAAY,cAAc,KAAK,IAAI,EAAE,qBAAqB,MAAM,KAAK,OAAO,EAAE;IACnH,MAAM,CAAC,YAAY,UAAU,MAAM,QAAQ,IAAI,CAAC,OAAO,SAAS,GAAG,YAAY,CAAC,CAAC;IACjF,MAAM,OAAuB,CAAC;IAC9B,KAAK,MAAM,OAAO,WAAW,SAAS;KACrC,MAAM,KAAK,QAAQ,OAAO,IAAI,MAAM,EAAE,CAAC;KACvC,IAAI,IACH,KAAK,KAAK;MAAE,WAAW;MAAI,SAAS,QAAQ,KAAK,CAAC;KAAE,CAAC;IAEvD;IACA,OAAO;KAAE;KAAM;KAAQ,MAAM;MAAE,UAAU;MAAW;KAAU;IAAE;GACjE;GAEA,IAAI,cAQH,OAAO;IAAE,OAJoB,MADV,OAAO,UAFX,cAAc,cACA,WAAW,cAAc,KAAK,IAAI,EAAE,qBAAqB,MAAM,KAAK,OAAO,EAAE,uCAAuC,EAAE,SAAS,KAC/H,GACK,QAAQ,KAAK,SAAS;KACvD,YAAY,GAAG,eAAe,OAAO,IAAI,MAAM,EAAE,EAAE;KACnD,SAAS,QAAQ,KAAK,CAAC;IACxB,EACY;IAAG,QAAQ,KAAA;IAAW,MAAM;KAAE,UAAU;KAAW;IAAU;GAAE;GAG5E,MAAM,SAAS,MAAM,YAAY;GACjC,OAAO;IAAE,MAAM,CAAC,EAAE,SAAS,OAAO,CAAC;IAAG;IAAQ,MAAM;KAAE,UAAU;KAAW;IAAU;GAAE;EACxF;CACD;AACD"}
@@ -7,7 +7,11 @@ interface UmamiConfig {
7
7
  apiKey?: string;
8
8
  /** Self-hosted bearer token (from POST /api/auth/login). */
9
9
  token?: string;
10
- /** API base URL. Defaults to Umami Cloud (https://api.umami.is/v1). Self-hosted is e.g. https://site/api. */
10
+ /**
11
+ * API base URL. Defaults to Umami Cloud (https://api.umami.is/v1). Self-hosted is
12
+ * e.g. https://site/api. Capture derives the app origin from this (a trailing `/api`
13
+ * is stripped), so one `host` value serves both the Stats API and the tracker.
14
+ */
11
15
  host?: string;
12
16
  /** Maximum days of historical data. Defaults to 730. Pass null to disable clamping. */
13
17
  maxLookbackDays?: number | null;