@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
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetchQuery.js","names":[],"sources":["../../src/query/fetchQuery.ts"],"sourcesContent":["import type { AnalyticsFilter, DimensionKey, Granularity, MetricKey } from '../core/contract'\nimport { QUERY_PATH } from '../plugin/paths'\nimport type { QueryError } from './errors'\nimport type { QueryErrorResponse, QueryResponse } from './response'\n\n/** A client-side mirror of the parameters `parseQueryParams` reads off the request. */\nexport interface QueryRequest {\n\tmetrics: MetricKey[]\n\tdimensions?: DimensionKey[]\n\tfrom: string\n\tto: string\n\tgranularity?: Granularity\n\tfilters?: AnalyticsFilter[]\n\tlimit?: number\n\torder?: { metric: MetricKey; direction: 'asc' | 'desc' }\n\tcompare?: 'previous'\n\tsource?: string\n\t/**\n\t * Read another scope's data. Platform readers only: the endpoint answers\n\t * `400 untrusted_scope` for any caller that may not read across scopes.\n\t */\n\tscope?: string\n\tpath?: string\n\thostname?: string\n\ttimezone?: string\n}\n\n/**\n * Builds the query endpoint URL from a fixed field order (not object insertion order),\n * so two `QueryRequest`s with the same values always produce the same URL string. That\n * determinism is what `fetchQuery`'s in-flight dedupe keys on.\n */\nexport const buildQueryUrl = (apiRoute: string, request: QueryRequest): string => {\n\tconst params = new URLSearchParams()\n\tparams.set('metrics', request.metrics.join(','))\n\tif (request.dimensions && request.dimensions.length > 0) {\n\t\tparams.set('dimensions', request.dimensions.join(','))\n\t}\n\tparams.set('from', request.from)\n\tparams.set('to', request.to)\n\tif (request.granularity !== undefined) {\n\t\tparams.set('granularity', request.granularity)\n\t}\n\tif (request.filters && request.filters.length > 0) {\n\t\tparams.set('filters', JSON.stringify(request.filters))\n\t}\n\tif (request.limit !== undefined) {\n\t\tparams.set('limit', String(request.limit))\n\t}\n\tif (request.order !== undefined) {\n\t\tparams.set('order', `${request.order.metric}:${request.order.direction}`)\n\t}\n\tif (request.compare !== undefined) {\n\t\tparams.set('compare', request.compare)\n\t}\n\tif (request.source !== undefined) {\n\t\tparams.set('source', request.source)\n\t}\n\tif (request.scope !== undefined) {\n\t\tparams.set('scope', request.scope)\n\t}\n\tif (request.path !== undefined) {\n\t\tparams.set('path', request.path)\n\t}\n\tif (request.hostname !== undefined) {\n\t\tparams.set('hostname', request.hostname)\n\t}\n\tif (request.timezone !== undefined) {\n\t\tparams.set('timezone', request.timezone)\n\t}\n\tconst base = apiRoute.endsWith('/') ? apiRoute.slice(0, -1) : apiRoute\n\treturn `${base}${QUERY_PATH}?${params.toString()}`\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n\ttypeof value === 'object' && value !== null\n\n/**\n * Only the query endpoint's structured body counts. The plugin's other read endpoints\n * answer a flat `{ \"error\": \"forbidden\" }`, which must not land in `QueryFetchError.error`\n * as a string where a `QueryError` is declared.\n */\nconst isQueryErrorResponse = (value: unknown): value is QueryErrorResponse => {\n\tif (!isRecord(value)) return false\n\tconst error = value.error\n\treturn isRecord(error) && typeof error.code === 'string' && typeof error.message === 'string'\n}\n\n/** Thrown by `fetchQuery` for any non-2xx response; `error` is set only when the body parsed as the endpoint's error shape. */\nexport class QueryFetchError extends Error {\n\treadonly status: number\n\treadonly error?: QueryError\n\treadonly retryAfter?: number\n\n\tconstructor(status: number, error?: QueryError, retryAfter?: number) {\n\t\tsuper(error?.message ?? `analytics query request failed with status ${status}`)\n\t\tthis.name = 'QueryFetchError'\n\t\tthis.status = status\n\t\tif (error !== undefined) this.error = error\n\t\tif (retryAfter !== undefined) this.retryAfter = retryAfter\n\t}\n}\n\nconst readRetryAfter = (res: Response): number | undefined => {\n\tconst header = res.headers.get('Retry-After')\n\tif (header === null) return undefined\n\t// The HTTP-date form is not a number, so it yields no delay rather than a bogus one;\n\t// a fractional delay floors, since callers schedule in whole seconds.\n\tconst seconds = Number(header)\n\treturn Number.isFinite(seconds) ? Math.floor(seconds) : undefined\n}\n\nconst runFetch = async (url: string): Promise<QueryResponse> => {\n\tconst res = await fetch(url, {\n\t\tcredentials: 'include',\n\t\theaders: { Accept: 'application/json' },\n\t})\n\tif (!res.ok) {\n\t\tlet error: QueryError | undefined\n\t\ttry {\n\t\t\tconst body: unknown = await res.json()\n\t\t\tif (isQueryErrorResponse(body)) error = body.error\n\t\t} catch {\n\t\t\t// Body wasn't JSON; error stays undefined and the status still carries the failure.\n\t\t}\n\t\tthrow new QueryFetchError(res.status, error, readRetryAfter(res))\n\t}\n\treturn (await res.json()) as QueryResponse\n}\n\nconst inFlight = new Map<string, Promise<QueryResponse>>()\n\n/**\n * Fetches `GET /analytics/query`, deduping concurrent identical requests (same URL) into\n * one underlying fetch; the entry clears on settle (success or failure), so a later call\n * always sees fresh data and a failed one retries instead of pinning the error.\n *\n * Dedupe means the shared fetch itself never carries a caller's `AbortSignal`, since\n * aborting it would also cancel every other caller sharing that in-flight request.\n * `init.signal` instead races the caller's own promise against the abort: aborting\n * rejects that caller without touching the shared fetch. Use distinct requests (varying\n * a param) when one caller's cancellation must actually stop the network call.\n */\nexport const fetchQuery = (\n\tapiRoute: string,\n\trequest: QueryRequest,\n\tinit?: { signal?: AbortSignal }\n): Promise<QueryResponse> => {\n\tconst url = buildQueryUrl(apiRoute, request)\n\tlet pending = inFlight.get(url)\n\tif (!pending) {\n\t\tpending = runFetch(url).finally(() => {\n\t\t\tinFlight.delete(url)\n\t\t})\n\t\tinFlight.set(url, pending)\n\t}\n\n\tconst signal = init?.signal\n\tif (!signal) return pending\n\tif (signal.aborted) return Promise.reject(signal.reason)\n\n\treturn new Promise<QueryResponse>((resolve, reject) => {\n\t\tconst onAbort = () => reject(signal.reason)\n\t\tsignal.addEventListener('abort', onAbort, { once: true })\n\t\tpending.then(\n\t\t\t(value) => {\n\t\t\t\tsignal.removeEventListener('abort', onAbort)\n\t\t\t\tresolve(value)\n\t\t\t},\n\t\t\t(err: unknown) => {\n\t\t\t\tsignal.removeEventListener('abort', onAbort)\n\t\t\t\treject(err)\n\t\t\t}\n\t\t)\n\t})\n}\n"],"mappings":";;;;;;;AAgCA,MAAa,iBAAiB,UAAkB,YAAkC;CACjF,MAAM,SAAS,IAAI,gBAAgB;CACnC,OAAO,IAAI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AAI,KAAK,OAAO;CAC1B;CAEA,MAAM,SAAS,MAAM;CACrB,IAAI,CAAC,QAAQ,OAAO;CACpB,IAAI,OAAO,SAAS,OAAO,QAAQ,OAAO,OAAO,MAAM;CAEvD,OAAO,IAAI,SAAwB,SAAS,WAAW;EACtD,MAAM,gBAAgB,OAAO,OAAO,MAAM;EAC1C,OAAO,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;EACxD,QAAQ,MACN,UAAU;GACV,OAAO,oBAAoB,SAAS,OAAO;GAC3C,QAAQ,KAAK;EACd,IACC,QAAiB;GACjB,OAAO,oBAAoB,SAAS,OAAO;GAC3C,OAAO,GAAG;EACX,CACD;CACD,CAAC;AACF"}
@@ -0,0 +1,22 @@
1
+ import { AnalyticsQuery } from "../core/contract.js";
2
+ import { QueryError } from "./errors.js";
3
+
4
+ //#region src/query/parse.d.ts
5
+ /**
6
+ * A validated read request. `source` and `scope` are absent by design: the handler must
7
+ * resolve both before the parser can run, and reads them itself through {@link readParam}.
8
+ */
9
+ interface ParsedQuery {
10
+ query: AnalyticsQuery;
11
+ compare: 'previous' | null;
12
+ }
13
+ type ParseResult = {
14
+ ok: true;
15
+ value: ParsedQuery;
16
+ } | {
17
+ ok: false;
18
+ error: QueryError;
19
+ };
20
+ //#endregion
21
+ export { ParseResult, ParsedQuery };
22
+ //# sourceMappingURL=parse.d.ts.map
@@ -0,0 +1,168 @@
1
+ import { DIMENSION_KEYS, FILTER_OPERATORS } from "../core/contract.js";
2
+ import { isValidTimeZone } from "../timeframe/tz.js";
3
+ import { METRIC_KEYS } from "../translations/metricKeys.js";
4
+ import { GRANULARITY_ORDER } from "../core/granularity.js";
5
+ import { parseDayOrInstant } from "./dates.js";
6
+ import { queryError } from "./errors.js";
7
+ //#region src/query/parse.ts
8
+ const KNOWN_METRICS = new Set(Object.keys(METRIC_KEYS));
9
+ const KNOWN_DIMENSIONS = new Set(DIMENSION_KEYS);
10
+ const KNOWN_OPERATORS = new Set(FILTER_OPERATORS);
11
+ const KNOWN_GRANULARITIES = new Set(GRANULARITY_ORDER);
12
+ const DAY_MS = 864e5;
13
+ const fail = (code, message, param) => ({
14
+ ok: false,
15
+ error: queryError(code, message, param)
16
+ });
17
+ /** Echo a rejected value back in a message without letting a caller inflate the response. */
18
+ const echo = (value) => value.length > 40 ? `${value.slice(0, 40)}...` : value;
19
+ /**
20
+ * A trimmed non-empty parameter, or null when absent or blank. Exported so the handler
21
+ * reads `source` and `scope` (which it must resolve before the parser can run) exactly
22
+ * the way the parser reads everything else.
23
+ */
24
+ const readParam = (params, name) => {
25
+ const raw = params.get(name)?.trim();
26
+ return raw ? raw : null;
27
+ };
28
+ const commaList = (raw) => raw.split(",").map((part) => part.trim()).filter((part) => part.length > 0);
29
+ const dedupe = (values) => [...new Set(values)];
30
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
31
+ const parseFilters = (raw, capabilities) => {
32
+ let decoded;
33
+ try {
34
+ decoded = JSON.parse(raw);
35
+ } catch {
36
+ return fail("invalid_param", "filters must be a JSON array", "filters");
37
+ }
38
+ if (!Array.isArray(decoded)) return fail("invalid_param", "filters must be a JSON array", "filters");
39
+ if (decoded.length > 10) return fail("invalid_param", `at most 10 filters are allowed`, "filters");
40
+ const filterable = new Set(capabilities.filters);
41
+ const operators = new Set(capabilities.filterOperators);
42
+ const parsed = [];
43
+ for (const item of decoded) {
44
+ if (!isRecord(item)) return fail("invalid_param", "each filter must be an object", "filters");
45
+ const { dimension, operator, value } = item;
46
+ if (typeof dimension !== "string" || !KNOWN_DIMENSIONS.has(dimension)) return fail("invalid_param", `unknown filter dimension: ${echo(String(dimension))}`, "filters");
47
+ if (typeof operator !== "string" || !KNOWN_OPERATORS.has(operator)) return fail("invalid_param", `unknown filter operator: ${echo(String(operator))}`, "filters");
48
+ if (typeof value !== "string") return fail("invalid_param", "each filter value must be a string", "filters");
49
+ const trimmed = value.trim();
50
+ if (trimmed.length < 1 || trimmed.length > 256) return fail("invalid_param", `each filter value must be 1 to 256 characters`, "filters");
51
+ if (!filterable.has(dimension)) return fail("unsupported_filter", `source cannot filter on ${dimension}`, "filters");
52
+ if (!operators.has(operator)) return fail("unsupported_operator", `source does not support ${operator}`, "filters");
53
+ parsed.push({
54
+ dimension,
55
+ operator,
56
+ value: trimmed
57
+ });
58
+ }
59
+ return parsed;
60
+ };
61
+ /**
62
+ * Validate a query string against a source's serialized capabilities. Rules are evaluated
63
+ * in a fixed order and the first failure wins: timezone, metrics, dimensions, from/to,
64
+ * granularity, filters, limit, order, compare, path, hostname. Within each, a value
65
+ * outside the contract's own union is `invalid_param` and a contract value the source
66
+ * lacks is its `unsupported_*` code. Unknown parameters are ignored; `source` and `scope`
67
+ * pass through unvalidated, since only the handler knows whether they are trusted.
68
+ */
69
+ const parseQueryParams = (params, args) => {
70
+ const rawTimezone = readParam(params, "timezone");
71
+ if (rawTimezone !== null && !isValidTimeZone(rawTimezone)) return fail("invalid_param", `unknown timezone: ${echo(rawTimezone)}`, "timezone");
72
+ const timezone = rawTimezone ?? args.timezone;
73
+ const rawMetrics = readParam(params, "metrics");
74
+ const metricList = rawMetrics ? commaList(rawMetrics) : [];
75
+ if (metricList.length === 0) return fail("invalid_param", "metrics is required", "metrics");
76
+ const unknownMetric = metricList.find((m) => !KNOWN_METRICS.has(m));
77
+ if (unknownMetric !== void 0) return fail("invalid_param", `unknown metric: ${echo(unknownMetric)}`, "metrics");
78
+ const metrics = dedupe(metricList);
79
+ if (metrics.length > 10) return fail("invalid_param", `at most 10 metrics are allowed`, "metrics");
80
+ const servedMetrics = new Set(args.capabilities.metrics);
81
+ const unsupportedMetric = metrics.find((m) => !servedMetrics.has(m));
82
+ if (unsupportedMetric !== void 0) return fail("unsupported_metric", `source does not serve ${unsupportedMetric}`, "metrics");
83
+ const rawDimensions = readParam(params, "dimensions");
84
+ const dimensionList = rawDimensions ? commaList(rawDimensions) : [];
85
+ const unknownDimension = dimensionList.find((d) => !KNOWN_DIMENSIONS.has(d));
86
+ if (unknownDimension !== void 0) return fail("invalid_param", `unknown dimension: ${echo(unknownDimension)}`, "dimensions");
87
+ const dimensions = dedupe(dimensionList);
88
+ if (dimensions.length > 2) return fail("invalid_param", `at most 2 dimensions are allowed`, "dimensions");
89
+ const servedDimensions = new Set(args.capabilities.dimensions);
90
+ const unsupportedDimension = dimensions.find((d) => !servedDimensions.has(d));
91
+ if (unsupportedDimension !== void 0) return fail("unsupported_dimension", `source does not break down by ${unsupportedDimension}`, "dimensions");
92
+ const rawFrom = readParam(params, "from");
93
+ const rawTo = readParam(params, "to");
94
+ if (!rawFrom) return fail("invalid_param", "from is required", "from");
95
+ const start = parseDayOrInstant(rawFrom, {
96
+ timezone,
97
+ edge: "start"
98
+ });
99
+ if (!start) return fail("invalid_param", `from is not a date: ${echo(rawFrom)}`, "from");
100
+ if (!rawTo) return fail("invalid_param", "to is required", "to");
101
+ const end = parseDayOrInstant(rawTo, {
102
+ timezone,
103
+ edge: "end"
104
+ });
105
+ if (!end) return fail("invalid_param", `to is not a date: ${echo(rawTo)}`, "to");
106
+ if (end.getTime() < start.getTime()) return fail("invalid_param", "to must not be before from", "to");
107
+ if (end.getTime() - start.getTime() > 366 * DAY_MS) return fail("range_too_long", `the range must not exceed 366 days`, "to");
108
+ const rawGranularity = readParam(params, "granularity");
109
+ if (rawGranularity !== null && !KNOWN_GRANULARITIES.has(rawGranularity)) return fail("invalid_param", `unknown granularity: ${echo(rawGranularity)}`, "granularity");
110
+ const granularity = rawGranularity;
111
+ if (granularity !== null && GRANULARITY_ORDER.indexOf(granularity) < GRANULARITY_ORDER.indexOf(args.capabilities.minGranularity)) return fail("unsupported_granularity", `source buckets no finer than ${args.capabilities.minGranularity}`, "granularity");
112
+ const rawFilters = readParam(params, "filters");
113
+ const filters = rawFilters === null ? [] : parseFilters(rawFilters, args.capabilities);
114
+ if (!Array.isArray(filters)) return filters;
115
+ const rawLimit = readParam(params, "limit");
116
+ let limit = 50;
117
+ if (rawLimit !== null) {
118
+ if (!/^\d+$/.test(rawLimit)) return fail("invalid_param", `limit must be an integer: ${echo(rawLimit)}`, "limit");
119
+ limit = Number(rawLimit);
120
+ if (limit < 1 || limit > 500) return fail("invalid_param", `limit must be between 1 and 500`, "limit");
121
+ }
122
+ const rawOrder = readParam(params, "order");
123
+ let order;
124
+ if (rawOrder !== null) {
125
+ const parts = rawOrder.split(":");
126
+ const metric = parts[0] ?? "";
127
+ const direction = parts[1] ?? "";
128
+ if (parts.length !== 2 || direction !== "asc" && direction !== "desc") return fail("invalid_param", "order must be <metric>:<asc|desc>", "order");
129
+ const ordered = metrics.find((m) => m === metric);
130
+ if (ordered === void 0) return fail("invalid_param", `order metric is not in metrics: ${echo(metric)}`, "order");
131
+ order = {
132
+ metric: ordered,
133
+ direction
134
+ };
135
+ }
136
+ const rawCompare = readParam(params, "compare");
137
+ if (rawCompare !== null && rawCompare !== "previous") return fail("invalid_param", `compare must be "previous": ${echo(rawCompare)}`, "compare");
138
+ if (rawCompare === "previous" && !args.capabilities.comparison) return fail("invalid_param", "source does not support comparison", "compare");
139
+ const path = readParam(params, "path");
140
+ if (path !== null && path.length > 512) return fail("invalid_param", `path must be at most 512 characters`, "path");
141
+ const hostname = readParam(params, "hostname");
142
+ if (hostname !== null && hostname.length > 253) return fail("invalid_param", `hostname must be at most 253 characters`, "hostname");
143
+ return {
144
+ ok: true,
145
+ value: {
146
+ query: {
147
+ metrics,
148
+ dateRange: {
149
+ start,
150
+ end
151
+ },
152
+ limit,
153
+ timezone,
154
+ ...dimensions.length > 0 ? { dimensions } : {},
155
+ ...granularity !== null ? { granularity } : {},
156
+ ...filters.length > 0 ? { filters } : {},
157
+ ...order ? { order } : {},
158
+ ...path !== null ? { path } : {},
159
+ ...hostname !== null ? { hostname } : {}
160
+ },
161
+ compare: rawCompare === "previous" ? "previous" : null
162
+ }
163
+ };
164
+ };
165
+ //#endregion
166
+ export { parseQueryParams, readParam };
167
+
168
+ //# sourceMappingURL=parse.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"parse.js","names":[],"sources":["../../src/query/parse.ts"],"sourcesContent":["import type { SerializedCapabilities } from '../core/capabilities'\nimport {\n\ttype AnalyticsFilter,\n\ttype AnalyticsQuery,\n\tDIMENSION_KEYS,\n\ttype DimensionKey,\n\tFILTER_OPERATORS,\n\ttype FilterOperator,\n\ttype Granularity,\n\ttype MetricKey,\n} from '../core/contract'\nimport { GRANULARITY_ORDER } from '../core/granularity'\nimport { isValidTimeZone } from '../timeframe/tz'\nimport { METRIC_KEYS } from '../translations/metricKeys'\nimport { parseDayOrInstant } from './dates'\nimport { type QueryError, queryError } from './errors'\nimport {\n\tDEFAULT_QUERY_LIMIT,\n\tMAX_QUERY_DIMENSIONS,\n\tMAX_QUERY_FILTER_VALUE_LENGTH,\n\tMAX_QUERY_FILTERS,\n\tMAX_QUERY_HOSTNAME_LENGTH,\n\tMAX_QUERY_LIMIT,\n\tMAX_QUERY_METRICS,\n\tMAX_QUERY_PATH_LENGTH,\n\tMAX_QUERY_RANGE_DAYS,\n\tMIN_QUERY_LIMIT,\n} from './limits'\n\n/**\n * A validated read request. `source` and `scope` are absent by design: the handler must\n * resolve both before the parser can run, and reads them itself through {@link readParam}.\n */\nexport interface ParsedQuery {\n\tquery: AnalyticsQuery\n\tcompare: 'previous' | null\n}\n\nexport type ParseResult = { ok: true; value: ParsedQuery } | { ok: false; error: QueryError }\n\nexport interface ParseQueryArgs {\n\tcapabilities: SerializedCapabilities\n\t/** Reporting timezone the plugin resolved for this request; the `timezone` param overrides it. */\n\ttimezone: string\n}\n\nconst KNOWN_METRICS = new Set<string>(Object.keys(METRIC_KEYS))\nconst KNOWN_DIMENSIONS = new Set<string>(DIMENSION_KEYS)\nconst KNOWN_OPERATORS = new Set<string>(FILTER_OPERATORS)\nconst KNOWN_GRANULARITIES = new Set<string>(GRANULARITY_ORDER)\nconst DAY_MS = 86_400_000\n\nconst fail = (code: QueryError['code'], message: string, param: string): ParseResult => ({\n\tok: false,\n\terror: queryError(code, message, param),\n})\n\n/** Echo a rejected value back in a message without letting a caller inflate the response. */\nconst echo = (value: string): string => (value.length > 40 ? `${value.slice(0, 40)}...` : value)\n\n/**\n * A trimmed non-empty parameter, or null when absent or blank. Exported so the handler\n * reads `source` and `scope` (which it must resolve before the parser can run) exactly\n * the way the parser reads everything else.\n */\nexport const readParam = (params: URLSearchParams, name: string): string | null => {\n\tconst raw = params.get(name)?.trim()\n\treturn raw ? raw : null\n}\n\nconst commaList = (raw: string): string[] =>\n\traw\n\t\t.split(',')\n\t\t.map((part) => part.trim())\n\t\t.filter((part) => part.length > 0)\n\nconst dedupe = <T extends string>(values: T[]): T[] => [...new Set(values)]\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n\ttypeof value === 'object' && value !== null && !Array.isArray(value)\n\nconst parseFilters = (\n\traw: string,\n\tcapabilities: SerializedCapabilities\n): AnalyticsFilter[] | ParseResult => {\n\tlet decoded: unknown\n\ttry {\n\t\tdecoded = JSON.parse(raw)\n\t} catch {\n\t\treturn fail('invalid_param', 'filters must be a JSON array', 'filters')\n\t}\n\tif (!Array.isArray(decoded)) {\n\t\treturn fail('invalid_param', 'filters must be a JSON array', 'filters')\n\t}\n\tif (decoded.length > MAX_QUERY_FILTERS) {\n\t\treturn fail('invalid_param', `at most ${MAX_QUERY_FILTERS} filters are allowed`, 'filters')\n\t}\n\tconst filterable = new Set<string>(capabilities.filters)\n\tconst operators = new Set<string>(capabilities.filterOperators)\n\tconst parsed: AnalyticsFilter[] = []\n\tfor (const item of decoded) {\n\t\tif (!isRecord(item)) {\n\t\t\treturn fail('invalid_param', 'each filter must be an object', 'filters')\n\t\t}\n\t\tconst { dimension, operator, value } = item\n\t\tif (typeof dimension !== 'string' || !KNOWN_DIMENSIONS.has(dimension)) {\n\t\t\treturn fail(\n\t\t\t\t'invalid_param',\n\t\t\t\t`unknown filter dimension: ${echo(String(dimension))}`,\n\t\t\t\t'filters'\n\t\t\t)\n\t\t}\n\t\tif (typeof operator !== 'string' || !KNOWN_OPERATORS.has(operator)) {\n\t\t\treturn fail('invalid_param', `unknown filter operator: ${echo(String(operator))}`, 'filters')\n\t\t}\n\t\tif (typeof value !== 'string') {\n\t\t\treturn fail('invalid_param', 'each filter value must be a string', 'filters')\n\t\t}\n\t\tconst trimmed = value.trim()\n\t\tif (trimmed.length < 1 || trimmed.length > MAX_QUERY_FILTER_VALUE_LENGTH) {\n\t\t\treturn fail(\n\t\t\t\t'invalid_param',\n\t\t\t\t`each filter value must be 1 to ${MAX_QUERY_FILTER_VALUE_LENGTH} characters`,\n\t\t\t\t'filters'\n\t\t\t)\n\t\t}\n\t\tif (!filterable.has(dimension)) {\n\t\t\treturn fail('unsupported_filter', `source cannot filter on ${dimension}`, 'filters')\n\t\t}\n\t\tif (!operators.has(operator)) {\n\t\t\treturn fail('unsupported_operator', `source does not support ${operator}`, 'filters')\n\t\t}\n\t\tparsed.push({\n\t\t\tdimension: dimension as DimensionKey,\n\t\t\toperator: operator as FilterOperator,\n\t\t\tvalue: trimmed,\n\t\t})\n\t}\n\treturn parsed\n}\n\n/**\n * Validate a query string against a source's serialized capabilities. Rules are evaluated\n * in a fixed order and the first failure wins: timezone, metrics, dimensions, from/to,\n * granularity, filters, limit, order, compare, path, hostname. Within each, a value\n * outside the contract's own union is `invalid_param` and a contract value the source\n * lacks is its `unsupported_*` code. Unknown parameters are ignored; `source` and `scope`\n * pass through unvalidated, since only the handler knows whether they are trusted.\n */\nexport const parseQueryParams = (params: URLSearchParams, args: ParseQueryArgs): ParseResult => {\n\tconst rawTimezone = readParam(params, 'timezone')\n\tif (rawTimezone !== null && !isValidTimeZone(rawTimezone)) {\n\t\treturn fail('invalid_param', `unknown timezone: ${echo(rawTimezone)}`, 'timezone')\n\t}\n\tconst timezone = rawTimezone ?? args.timezone\n\n\tconst rawMetrics = readParam(params, 'metrics')\n\tconst metricList = rawMetrics ? commaList(rawMetrics) : []\n\tif (metricList.length === 0) {\n\t\treturn fail('invalid_param', 'metrics is required', 'metrics')\n\t}\n\tconst unknownMetric = metricList.find((m) => !KNOWN_METRICS.has(m))\n\tif (unknownMetric !== undefined) {\n\t\treturn fail('invalid_param', `unknown metric: ${echo(unknownMetric)}`, 'metrics')\n\t}\n\tconst metrics = dedupe(metricList) as MetricKey[]\n\tif (metrics.length > MAX_QUERY_METRICS) {\n\t\treturn fail('invalid_param', `at most ${MAX_QUERY_METRICS} metrics are allowed`, 'metrics')\n\t}\n\tconst servedMetrics = new Set<string>(args.capabilities.metrics)\n\tconst unsupportedMetric = metrics.find((m) => !servedMetrics.has(m))\n\tif (unsupportedMetric !== undefined) {\n\t\treturn fail('unsupported_metric', `source does not serve ${unsupportedMetric}`, 'metrics')\n\t}\n\n\tconst rawDimensions = readParam(params, 'dimensions')\n\tconst dimensionList = rawDimensions ? commaList(rawDimensions) : []\n\tconst unknownDimension = dimensionList.find((d) => !KNOWN_DIMENSIONS.has(d))\n\tif (unknownDimension !== undefined) {\n\t\treturn fail('invalid_param', `unknown dimension: ${echo(unknownDimension)}`, 'dimensions')\n\t}\n\tconst dimensions = dedupe(dimensionList) as DimensionKey[]\n\tif (dimensions.length > MAX_QUERY_DIMENSIONS) {\n\t\treturn fail(\n\t\t\t'invalid_param',\n\t\t\t`at most ${MAX_QUERY_DIMENSIONS} dimensions are allowed`,\n\t\t\t'dimensions'\n\t\t)\n\t}\n\tconst servedDimensions = new Set<string>(args.capabilities.dimensions)\n\tconst unsupportedDimension = dimensions.find((d) => !servedDimensions.has(d))\n\tif (unsupportedDimension !== undefined) {\n\t\treturn fail(\n\t\t\t'unsupported_dimension',\n\t\t\t`source does not break down by ${unsupportedDimension}`,\n\t\t\t'dimensions'\n\t\t)\n\t}\n\n\tconst rawFrom = readParam(params, 'from')\n\tconst rawTo = readParam(params, 'to')\n\tif (!rawFrom) {\n\t\treturn fail('invalid_param', 'from is required', 'from')\n\t}\n\tconst start = parseDayOrInstant(rawFrom, { timezone, edge: 'start' })\n\tif (!start) {\n\t\treturn fail('invalid_param', `from is not a date: ${echo(rawFrom)}`, 'from')\n\t}\n\tif (!rawTo) {\n\t\treturn fail('invalid_param', 'to is required', 'to')\n\t}\n\tconst end = parseDayOrInstant(rawTo, { timezone, edge: 'end' })\n\tif (!end) {\n\t\treturn fail('invalid_param', `to is not a date: ${echo(rawTo)}`, 'to')\n\t}\n\tif (end.getTime() < start.getTime()) {\n\t\treturn fail('invalid_param', 'to must not be before from', 'to')\n\t}\n\tif (end.getTime() - start.getTime() > MAX_QUERY_RANGE_DAYS * DAY_MS) {\n\t\treturn fail('range_too_long', `the range must not exceed ${MAX_QUERY_RANGE_DAYS} days`, 'to')\n\t}\n\n\tconst rawGranularity = readParam(params, 'granularity')\n\tif (rawGranularity !== null && !KNOWN_GRANULARITIES.has(rawGranularity)) {\n\t\treturn fail('invalid_param', `unknown granularity: ${echo(rawGranularity)}`, 'granularity')\n\t}\n\tconst granularity = rawGranularity as Granularity | null\n\tif (\n\t\tgranularity !== null &&\n\t\tGRANULARITY_ORDER.indexOf(granularity) <\n\t\t\tGRANULARITY_ORDER.indexOf(args.capabilities.minGranularity)\n\t) {\n\t\treturn fail(\n\t\t\t'unsupported_granularity',\n\t\t\t`source buckets no finer than ${args.capabilities.minGranularity}`,\n\t\t\t'granularity'\n\t\t)\n\t}\n\n\tconst rawFilters = readParam(params, 'filters')\n\tconst filters = rawFilters === null ? [] : parseFilters(rawFilters, args.capabilities)\n\tif (!Array.isArray(filters)) {\n\t\treturn filters\n\t}\n\n\tconst rawLimit = readParam(params, 'limit')\n\tlet limit = DEFAULT_QUERY_LIMIT\n\tif (rawLimit !== null) {\n\t\tif (!/^\\d+$/.test(rawLimit)) {\n\t\t\treturn fail('invalid_param', `limit must be an integer: ${echo(rawLimit)}`, 'limit')\n\t\t}\n\t\tlimit = Number(rawLimit)\n\t\tif (limit < MIN_QUERY_LIMIT || limit > MAX_QUERY_LIMIT) {\n\t\t\treturn fail(\n\t\t\t\t'invalid_param',\n\t\t\t\t`limit must be between ${MIN_QUERY_LIMIT} and ${MAX_QUERY_LIMIT}`,\n\t\t\t\t'limit'\n\t\t\t)\n\t\t}\n\t}\n\n\tconst rawOrder = readParam(params, 'order')\n\tlet order: AnalyticsQuery['order']\n\tif (rawOrder !== null) {\n\t\tconst parts = rawOrder.split(':')\n\t\tconst metric = parts[0] ?? ''\n\t\tconst direction = parts[1] ?? ''\n\t\tif (parts.length !== 2 || (direction !== 'asc' && direction !== 'desc')) {\n\t\t\treturn fail('invalid_param', 'order must be <metric>:<asc|desc>', 'order')\n\t\t}\n\t\tconst ordered = metrics.find((m) => m === metric)\n\t\tif (ordered === undefined) {\n\t\t\treturn fail('invalid_param', `order metric is not in metrics: ${echo(metric)}`, 'order')\n\t\t}\n\t\torder = { metric: ordered, direction }\n\t}\n\n\tconst rawCompare = readParam(params, 'compare')\n\tif (rawCompare !== null && rawCompare !== 'previous') {\n\t\treturn fail('invalid_param', `compare must be \"previous\": ${echo(rawCompare)}`, 'compare')\n\t}\n\tif (rawCompare === 'previous' && !args.capabilities.comparison) {\n\t\treturn fail('invalid_param', 'source does not support comparison', 'compare')\n\t}\n\n\tconst path = readParam(params, 'path')\n\tif (path !== null && path.length > MAX_QUERY_PATH_LENGTH) {\n\t\treturn fail('invalid_param', `path must be at most ${MAX_QUERY_PATH_LENGTH} characters`, 'path')\n\t}\n\tconst hostname = readParam(params, 'hostname')\n\tif (hostname !== null && hostname.length > MAX_QUERY_HOSTNAME_LENGTH) {\n\t\treturn fail(\n\t\t\t'invalid_param',\n\t\t\t`hostname must be at most ${MAX_QUERY_HOSTNAME_LENGTH} characters`,\n\t\t\t'hostname'\n\t\t)\n\t}\n\n\tconst query: AnalyticsQuery = {\n\t\tmetrics,\n\t\tdateRange: { start, end },\n\t\tlimit,\n\t\ttimezone,\n\t\t...(dimensions.length > 0 ? { dimensions } : {}),\n\t\t...(granularity !== null ? { granularity } : {}),\n\t\t...(filters.length > 0 ? { filters } : {}),\n\t\t...(order ? { order } : {}),\n\t\t...(path !== null ? { path } : {}),\n\t\t...(h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a,aAAa;EAAK;CACxE;AACD"}
@@ -0,0 +1,36 @@
1
+ import { AnalyticsQuery, AnalyticsResult } from "../core/contract.js";
2
+ import { SerializedCapabilities } from "../core/capabilities.js";
3
+ import { QueryError } from "./errors.js";
4
+
5
+ //#region src/query/response.d.ts
6
+ /** Identity of the source a read was served by; its capabilities travel beside it. */
7
+ interface QuerySourceRef {
8
+ id: string;
9
+ label: string;
10
+ /** `config` for an adapter every scope shares, `runtime` for one resolved per scope. */
11
+ kind: 'config' | 'runtime';
12
+ }
13
+ /** An `AnalyticsQuery` as it survives JSON: the date range's instants are ISO strings. */
14
+ type SerializedAnalyticsQuery = Omit<AnalyticsQuery, 'dateRange'> & {
15
+ dateRange: {
16
+ start: string;
17
+ end: string;
18
+ };
19
+ };
20
+ /** Successful answer of `GET /analytics/query`. */
21
+ interface QueryResponse {
22
+ result: AnalyticsResult;
23
+ /** The equal-length window before `query.dateRange`, present only for `compare=previous`. */
24
+ comparison?: AnalyticsResult;
25
+ source: QuerySourceRef;
26
+ capabilities: SerializedCapabilities;
27
+ /** The query after validation and defaulting, so a client renders what it actually got. */
28
+ query: SerializedAnalyticsQuery;
29
+ }
30
+ /** Every non-2xx answer of `GET /analytics/query`. */
31
+ interface QueryErrorResponse {
32
+ error: QueryError;
33
+ }
34
+ //#endregion
35
+ export { QueryErrorResponse, QueryResponse, QuerySourceRef, SerializedAnalyticsQuery };
36
+ //# sourceMappingURL=response.d.ts.map
@@ -0,0 +1,43 @@
1
+ import { TrackerConfig } from "../capture/trackerConfig.js";
2
+ import { LoadScript, Tracker } from "../tracker/types.js";
3
+ import { ReactElement, ReactNode } from "react";
4
+
5
+ //#region src/react/AnalyticsProvider.d.ts
6
+ /** The tracker surface a component gets from `useAnalytics`. */
7
+ interface AnalyticsApi {
8
+ track: Tracker['track'];
9
+ trackGoal: Tracker['trackGoal'];
10
+ consent: Tracker['consent'];
11
+ }
12
+ interface AnalyticsProviderProps {
13
+ /** Resolved server-side by `getTrackerConfig`, or fetched from the tracker endpoint. */
14
+ config: TrackerConfig;
15
+ children?: ReactNode;
16
+ /** CSP nonce applied to the vendor scripts the tracker injects. */
17
+ nonce?: string;
18
+ /** Replaces script injection, for a consent manager or a framework script loader. */
19
+ loadScript?: LoadScript;
20
+ }
21
+ /**
22
+ * Shares the window's tracker with the tree through `useAnalytics`. Use it when components
23
+ * need to call `track`, `trackGoal`, or `consent` themselves; a page that only needs
24
+ * pageviews and auto-capture can render `<AnalyticsScripts />` (which boots
25
+ * `<TrackerBoot />`) and skip the provider. Rendering both is fine: the tracker is leased
26
+ * from a per-window registry, so there is still only one.
27
+ *
28
+ * The lease is taken lazily in the browser rather than during render, so server rendering
29
+ * stays inert and React's double-invoked render cannot leak a second tracker.
30
+ *
31
+ * Whichever component boots the tracker first owns its options, so a `nonce` or
32
+ * `loadScript` passed to a provider that mounts after `<TrackerBoot />` is ignored: give
33
+ * them to whatever boots first, or render only one of the two.
34
+ */
35
+ declare const AnalyticsProvider: ({
36
+ config,
37
+ children,
38
+ nonce,
39
+ loadScript
40
+ }: AnalyticsProviderProps) => ReactElement;
41
+ //#endregion
42
+ export { AnalyticsApi, AnalyticsProvider, AnalyticsProviderProps };
43
+ //# sourceMappingURL=AnalyticsProvider.d.ts.map
@@ -0,0 +1,66 @@
1
+ "use client";
2
+ import { acquireTracker } from "../tracker/registry.js";
3
+ import { createContext, useCallback, useEffect, useMemo, useRef } from "react";
4
+ import { jsx } from "react/jsx-runtime";
5
+ //#region src/react/AnalyticsProvider.tsx
6
+ const AnalyticsContext = createContext(null);
7
+ /**
8
+ * Shares the window's tracker with the tree through `useAnalytics`. Use it when components
9
+ * need to call `track`, `trackGoal`, or `consent` themselves; a page that only needs
10
+ * pageviews and auto-capture can render `<AnalyticsScripts />` (which boots
11
+ * `<TrackerBoot />`) and skip the provider. Rendering both is fine: the tracker is leased
12
+ * from a per-window registry, so there is still only one.
13
+ *
14
+ * The lease is taken lazily in the browser rather than during render, so server rendering
15
+ * stays inert and React's double-invoked render cannot leak a second tracker.
16
+ *
17
+ * Whichever component boots the tracker first owns its options, so a `nonce` or
18
+ * `loadScript` passed to a provider that mounts after `<TrackerBoot />` is ignored: give
19
+ * them to whatever boots first, or render only one of the two.
20
+ */
21
+ const AnalyticsProvider = ({ config, children, nonce, loadScript }) => {
22
+ const boot = useRef({
23
+ config,
24
+ nonce,
25
+ loadScript
26
+ });
27
+ boot.current = {
28
+ config,
29
+ nonce,
30
+ loadScript
31
+ };
32
+ const lease = useRef(null);
33
+ const unmounted = useRef(false);
34
+ const ensure = useCallback(() => {
35
+ if (!lease.current && !unmounted.current && typeof window !== "undefined") {
36
+ const { config: current, nonce: currentNonce, loadScript: currentLoad } = boot.current;
37
+ lease.current = acquireTracker(current, {
38
+ nonce: currentNonce,
39
+ loadScript: currentLoad
40
+ });
41
+ }
42
+ return lease.current?.tracker ?? null;
43
+ }, []);
44
+ useEffect(() => {
45
+ unmounted.current = false;
46
+ ensure();
47
+ return () => {
48
+ unmounted.current = true;
49
+ lease.current?.release();
50
+ lease.current = null;
51
+ };
52
+ }, [ensure]);
53
+ const api = useMemo(() => ({
54
+ track: (name, props) => ensure()?.track(name, props),
55
+ trackGoal: (slug, opts) => ensure()?.trackGoal(slug, opts),
56
+ consent: (state) => ensure()?.consent(state)
57
+ }), [ensure]);
58
+ return /* @__PURE__ */ jsx(AnalyticsContext.Provider, {
59
+ value: api,
60
+ children
61
+ });
62
+ };
63
+ //#endregion
64
+ export { AnalyticsContext, AnalyticsProvider };
65
+
66
+ //# sourceMappingURL=AnalyticsProvider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AnalyticsProvider.js","names":[],"sources":["../../src/react/AnalyticsProvider.tsx"],"sourcesContent":["'use client'\n\nimport {\n\tcreateContext,\n\ttype ReactElement,\n\ttype ReactNode,\n\tuseCallback,\n\tuseEffect,\n\tuseMemo,\n\tuseRef,\n} from 'react'\nimport type { TrackerConfig } from '../capture/trackerConfig'\nimport { acquireTracker, type TrackerLease } from '../tracker/registry'\nimport type { LoadScript, Tracker } from '../tracker/types'\n\n/** The tracker surface a component gets from `useAnalytics`. */\nexport interface AnalyticsApi {\n\ttrack: Tracker['track']\n\ttrackGoal: Tracker['trackGoal']\n\tconsent: Tracker['consent']\n}\n\nexport const AnalyticsContext = createContext<AnalyticsApi | null>(null)\n\nexport interface AnalyticsProviderProps {\n\t/** Resolved server-side by `getTrackerConfig`, or fetched from the tracker endpoint. */\n\tconfig: TrackerConfig\n\tchildren?: ReactNode\n\t/** CSP nonce applied to the vendor scripts the tracker injects. */\n\tnonce?: string\n\t/** Replaces script injection, for a consent manager or a framework script loader. */\n\tloadScript?: LoadScript\n}\n\n/**\n * Shares the window's tracker with the tree through `useAnalytics`. Use it when components\n * need to call `track`, `trackGoal`, or `consent` themselves; a page that only needs\n * pageviews and auto-capture can render `<AnalyticsScripts />` (which boots\n * `<TrackerBoot />`) and skip the provider. Rendering both is fine: the tracker is leased\n * from a per-window registry, so there is still only one.\n *\n * The lease is taken lazily in the browser rather than during render, so server rendering\n * stays inert and React's double-invoked render cannot leak a second tracker.\n *\n * Whichever component boots the tracker first owns its options, so a `nonce` or\n * `loadScript` passed to a provider that mounts after `<TrackerBoot />` is ignored: give\n * them to whatever boots first, or render only one of the two.\n */\nexport const AnalyticsProvider = ({\n\tconfig,\n\tchildren,\n\tnonce,\n\tloadScript,\n}: AnalyticsProviderProps): ReactElement => {\n\tconst boot = useRef({ config, nonce, loadScript })\n\tboot.current = { config, nonce, loadScript }\n\tconst lease = useRef<TrackerLease | null>(null)\n\tconst unmounted = useRef(false)\n\n\tconst ensure = useCallback((): Tracker | null => {\n\t\tif (!lease.current && !unmounted.current && typeof window !== 'undefined') {\n\t\t\tconst { config: current, nonce: currentNonce, loadScript: currentLoad } = boot.current\n\t\t\tlease.current = acquireTracker(current, { nonce: currentNonce, loadScript: currentLoad })\n\t\t}\n\t\treturn lease.current?.tracker ?? null\n\t}, [])\n\n\tuseEffect(() => {\n\t\tunmounted.current = false\n\t\tensure()\n\t\treturn () => {\n\t\t\t// A stale `track` call held past unmount must not resurrect the tracker.\n\t\t\tunmounted.current = true\n\t\t\tlease.current?.release()\n\t\t\tlease.current = null\n\t\t}\n\t}, [ensure])\n\n\tconst api = useMemo<AnalyticsApi>(\n\t\t() => ({\n\t\t\ttrack: (name, props) => ensure()?.track(name, props),\n\t\t\ttrackGoal: (slug, opts) => ensure()?.trackGoal(slug, opts),\n\t\t\tconsent: (state) => ensure()?.consent(state),\n\t\t}),\n\t\t[ensure]\n\t)\n\n\treturn <AnalyticsContext.Provider value={api}>{children}</AnalyticsContext.Provider>\n}\n"],"mappings":";;;;;AAsBA,MAAa,mBAAmB,cAAmC,IAAI;;;;;;;;;;;;;;;AA0BvE,MAAa,qBAAqB,EACjC,QACA,UACA,OACA,iBAC2C;CAC3C,MAAM,OAAO,OAAO;EAAE;EAAQ;EAAO;CAAW,CAAC;CACjD,KAAK,UAAU;EAAE;EAAQ;EAAO;CAAW;CAC3C,MAAM,QAAQ,OAA4B,IAAI;CAC9C,MAAM,YAAY,OAAO,KAAK;CAE9B,MAAM,SAAS,kBAAkC;EAChD,IAAI,CAAC,MAAM,WAAW,CAAC,UAAU,WAAW,OAAO,WAAW,aAAa;GAC1E,MAAM,EAAE,QAAQ,SAAS,OAAO,cAAc,YAAY,gBAAgB,KAAK;GAC/E,MAAM,UAAU,eAAe,SAAS;IAAE,OAAO;IAAc,YAAY;GAAY,CAAC;EACzF;EACA,OAAO,MAAM,SAAS,WAAW;CAClC,GAAG,CAAC,CAAC;CAEL,gBAAgB;EACf,UAAU,UAAU;EACpB,OAAO;EACP,aAAa;GAEZ,UAAU,UAAU;GACpB,MAAM,SAAS,QAAQ;GACvB,MAAM,UAAU;EACjB;CACD,GAAG,CAAC,MAAM,CAAC;CAEX,MAAM,MAAM,eACJ;EACN,QAAQ,MAAM,UAAU,OAAO,GAAG,MAAM,MAAM,KAAK;EACnD,YAAY,MAAM,SAAS,OAAO,GAAG,UAAU,MAAM,IAAI;EACzD,UAAU,UAAU,OAAO,GAAG,QAAQ,KAAK;CAC5C,IACA,CAAC,MAAM,CACR;CAEA,OAAO,oBAAC,iBAAiB,UAAlB;EAA2B,OAAO;EAAM;CAAoC,CAAA;AACpF"}
@@ -0,0 +1,22 @@
1
+ import { TrackerConfig } from "../capture/trackerConfig.js";
2
+
3
+ //#region src/react/TrackerBoot.d.ts
4
+ interface TrackerBootProps {
5
+ config: TrackerConfig;
6
+ /** CSP nonce for any script this component injects. */
7
+ nonce?: string;
8
+ }
9
+ /**
10
+ * Boots the browser tracker from a server-resolved config and renders nothing. This is the
11
+ * RSC path: `<AnalyticsScripts />` renders it after the slot snippets, so a page gets
12
+ * pageviews and auto-capture with no provider and no client state. Wrap the tree in
13
+ * `<AnalyticsProvider>` as well when components need to call `track` themselves: both take
14
+ * a lease on the window's one tracker, so neither double-counts.
15
+ */
16
+ declare const TrackerBoot: ({
17
+ config,
18
+ nonce
19
+ }: TrackerBootProps) => null;
20
+ //#endregion
21
+ export { TrackerBoot, TrackerBootProps };
22
+ //# sourceMappingURL=TrackerBoot.d.ts.map
@@ -0,0 +1,30 @@
1
+ "use client";
2
+ import { acquireTracker } from "../tracker/registry.js";
3
+ import { useEffect, useRef } from "react";
4
+ //#region src/react/TrackerBoot.tsx
5
+ /**
6
+ * Boots the browser tracker from a server-resolved config and renders nothing. This is the
7
+ * RSC path: `<AnalyticsScripts />` renders it after the slot snippets, so a page gets
8
+ * pageviews and auto-capture with no provider and no client state. Wrap the tree in
9
+ * `<AnalyticsProvider>` as well when components need to call `track` themselves: both take
10
+ * a lease on the window's one tracker, so neither double-counts.
11
+ */
12
+ const TrackerBoot = ({ config, nonce }) => {
13
+ const boot = useRef({
14
+ config,
15
+ nonce
16
+ });
17
+ boot.current = {
18
+ config,
19
+ nonce
20
+ };
21
+ useEffect(() => {
22
+ const lease = acquireTracker(boot.current.config, { nonce: boot.current.nonce });
23
+ return () => lease.release();
24
+ }, []);
25
+ return null;
26
+ };
27
+ //#endregion
28
+ export { TrackerBoot };
29
+
30
+ //# sourceMappingURL=TrackerBoot.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"TrackerBoot.js","names":[],"sources":["../../src/react/TrackerBoot.tsx"],"sourcesContent":["'use client'\n\nimport { useEffect, useRef } from 'react'\nimport type { TrackerConfig } from '../capture/trackerConfig'\nimport { acquireTracker } from '../tracker/registry'\n\nexport interface TrackerBootProps {\n\tconfig: TrackerConfig\n\t/** CSP nonce for any script this component injects. */\n\tnonce?: string\n}\n\n/**\n * Boots the browser tracker from a server-resolved config and renders nothing. This is the\n * RSC path: `<AnalyticsScripts />` renders it after the slot snippets, so a page gets\n * pageviews and auto-capture with no provider and no client state. Wrap the tree in\n * `<AnalyticsProvider>` as well when components need to call `track` themselves: both take\n * a lease on the window's one tracker, so neither double-counts.\n */\nexport const TrackerBoot = ({ config, nonce }: TrackerBootProps): null => {\n\tconst boot = useRef({ config, nonce })\n\tboot.current = { config, nonce }\n\n\tuseEffect(() => {\n\t\tconst lease = acquireTracker(boot.current.config, { nonce: boot.current.nonce })\n\t\treturn () => lease.release()\n\t}, [])\n\n\treturn null\n}\n"],"mappings":";;;;;;;;;;;AAmBA,MAAa,eAAe,EAAE,QAAQ,YAAoC;CACzE,MAAM,OAAO,OAAO;EAAE;EAAQ;CAAM,CAAC;CACrC,KAAK,UAAU;EAAE;EAAQ;CAAM;CAE/B,gBAAgB;EACf,MAAM,QAAQ,eAAe,KAAK,QAAQ,QAAQ,EAAE,OAAO,KAAK,QAAQ,MAAM,CAAC;EAC/E,aAAa,MAAM,QAAQ;CAC5B,GAAG,CAAC,CAAC;CAEL,OAAO;AACR"}
@@ -0,0 +1,17 @@
1
+ import { AnalyticsApi } from "./AnalyticsProvider.js";
2
+
3
+ //#region src/react/useAnalytics.d.ts
4
+ /**
5
+ * The window's tracker: the surrounding `<AnalyticsProvider>`'s when there is one, else
6
+ * whichever instance `<AnalyticsScripts />` booted, so the RSC path alone is enough for a
7
+ * client component to send its own events.
8
+ *
9
+ * The tracker is resolved per call, not per render: `<TrackerBoot />`'s effect may not have
10
+ * run when a sibling renders, and an eagerly resolved null would never recover. A call that
11
+ * finds neither a provider nor a booted tracker throws, because a silently dead `track` is
12
+ * worse than a build-time mistake.
13
+ */
14
+ declare const useAnalytics: () => AnalyticsApi;
15
+ //#endregion
16
+ export { useAnalytics };
17
+ //# sourceMappingURL=useAnalytics.d.ts.map
@@ -0,0 +1,36 @@
1
+ "use client";
2
+ import { liveTracker } from "../tracker/registry.js";
3
+ import { AnalyticsContext } from "./AnalyticsProvider.js";
4
+ import { useContext, useMemo } from "react";
5
+ //#region src/react/useAnalytics.tsx
6
+ const NO_TRACKER = "analytics: useAnalytics found no tracker. Render <AnalyticsScripts /> (or <AnalyticsProvider>) above this component.";
7
+ /**
8
+ * The window's tracker: the surrounding `<AnalyticsProvider>`'s when there is one, else
9
+ * whichever instance `<AnalyticsScripts />` booted, so the RSC path alone is enough for a
10
+ * client component to send its own events.
11
+ *
12
+ * The tracker is resolved per call, not per render: `<TrackerBoot />`'s effect may not have
13
+ * run when a sibling renders, and an eagerly resolved null would never recover. A call that
14
+ * finds neither a provider nor a booted tracker throws, because a silently dead `track` is
15
+ * worse than a build-time mistake.
16
+ */
17
+ const useAnalytics = () => {
18
+ const provided = useContext(AnalyticsContext);
19
+ return useMemo(() => {
20
+ if (provided) return provided;
21
+ const tracker = () => {
22
+ const live = liveTracker();
23
+ if (!live) throw new Error(NO_TRACKER);
24
+ return live;
25
+ };
26
+ return {
27
+ track: (name, props) => tracker().track(name, props),
28
+ trackGoal: (slug, opts) => tracker().trackGoal(slug, opts),
29
+ consent: (state) => tracker().consent(state)
30
+ };
31
+ }, [provided]);
32
+ };
33
+ //#endregion
34
+ export { useAnalytics };
35
+
36
+ //# sourceMappingURL=useAnalytics.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useAnalytics.js","names":[],"sources":["../../src/react/useAnalytics.tsx"],"sourcesContent":["'use client'\n\nimport { useContext, useMemo } from 'react'\nimport { liveTracker } from '../tracker/registry'\nimport type { Tracker } from '../tracker/types'\nimport { type AnalyticsApi, AnalyticsContext } from './AnalyticsProvider'\n\nconst NO_TRACKER =\n\t'analytics: useAnalytics found no tracker. Render <AnalyticsScripts /> (or <AnalyticsProvider>) above this component.'\n\n/**\n * The window's tracker: the surrounding `<AnalyticsProvider>`'s when there is one, else\n * whichever instance `<AnalyticsScripts />` booted, so the RSC path alone is enough for a\n * client component to send its own events.\n *\n * The tracker is resolved per call, not per render: `<TrackerBoot />`'s effect may not have\n * run when a sibling renders, and an eagerly resolved null would never recover. A call that\n * finds neither a provider nor a booted tracker throws, because a silently dead `track` is\n * worse than a build-time mistake.\n */\nexport const useAnalytics = (): AnalyticsApi => {\n\tconst provided = useContext(AnalyticsContext)\n\treturn useMemo<AnalyticsApi>(() => {\n\t\tif (provided) {\n\t\t\treturn provided\n\t\t}\n\t\tconst tracker = (): Tracker => {\n\t\t\tconst live = liveTracker()\n\t\t\tif (!live) {\n\t\t\t\tthrow new Error(NO_TRACKER)\n\t\t\t}\n\t\t\treturn live\n\t\t}\n\t\treturn {\n\t\t\ttrack: (name, props) => tracker().track(name, props),\n\t\t\ttrackGoal: (slug, opts) => tracker().trackGoal(slug, opts),\n\t\t\tconsent: (state) => tracker().consent(state),\n\t\t}\n\t}, [provided])\n}\n"],"mappings":";;;;;AAOA,MAAM,aACL;;;;;;;;;;;AAYD,MAAa,qBAAmC;CAC/C,MAAM,WAAW,WAAW,gBAAgB;CAC5C,OAAO,cAA4B;EAClC,IAAI,UACH,OAAO;EAER,MAAM,gBAAyB;GAC9B,MAAM,OAAO,YAAY;GACzB,IAAI,CAAC,MACJ,MAAM,IAAI,MAAM,UAAU;GAE3B,OAAO;EACR;EACA,OAAO;GACN,QAAQ,MAAM,UAAU,QAAQ,EAAE,MAAM,MAAM,KAAK;GACnD,YAAY,MAAM,SAAS,QAAQ,EAAE,UAAU,MAAM,IAAI;GACzD,UAAU,UAAU,QAAQ,EAAE,QAAQ,KAAK;EAC5C;CACD,GAAG,CAAC,QAAQ,CAAC;AACd"}
@@ -0,0 +1,30 @@
1
+ import { TrackerConfig } from "../capture/trackerConfig.js";
2
+ import { ReactElement } from "react";
3
+
4
+ //#region src/rsc/AnalyticsScripts.d.ts
5
+ interface AnalyticsScriptsProps {
6
+ /** Resolved server-side, by `getTrackerConfig` or the tracker endpoint. */
7
+ config: TrackerConfig;
8
+ /** CSP nonce, applied to every script this renders. */
9
+ nonce?: string;
10
+ }
11
+ /**
12
+ * Renders each capture slot's vendor snippet, then boots the tracker over them. Snippet
13
+ * scripts come from the slot adapter's own `capture.snippet`, so they are plugin-authored
14
+ * strings rather than anything a request supplied; the inline ones are injected verbatim
15
+ * because a vendor init call has to parse as script, not as text.
16
+ *
17
+ * A slot that waits for consent renders nothing: shipping its script in the HTML would run
18
+ * the vendor's tracker before the visitor answered, which is the whole point of the gate.
19
+ * Its sink injects the same snippet once consent is granted (or immediately, when a granted
20
+ * decision was already persisted), and the loader skips scripts the page already carries.
21
+ *
22
+ * A native-only install renders no snippet at all: the tracker is the client.
23
+ */
24
+ declare const AnalyticsScripts: ({
25
+ config,
26
+ nonce
27
+ }: AnalyticsScriptsProps) => ReactElement;
28
+ //#endregion
29
+ export { AnalyticsScripts, AnalyticsScriptsProps };
30
+ //# sourceMappingURL=AnalyticsScripts.d.ts.map
@@ -0,0 +1,41 @@
1
+ import { TrackerBoot } from "../react/TrackerBoot.js";
2
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
3
+ //#region src/rsc/AnalyticsScripts.tsx
4
+ /**
5
+ * Renders each capture slot's vendor snippet, then boots the tracker over them. Snippet
6
+ * scripts come from the slot adapter's own `capture.snippet`, so they are plugin-authored
7
+ * strings rather than anything a request supplied; the inline ones are injected verbatim
8
+ * because a vendor init call has to parse as script, not as text.
9
+ *
10
+ * A slot that waits for consent renders nothing: shipping its script in the HTML would run
11
+ * the vendor's tracker before the visitor answered, which is the whole point of the gate.
12
+ * Its sink injects the same snippet once consent is granted (or immediately, when a granted
13
+ * decision was already persisted), and the loader skips scripts the page already carries.
14
+ *
15
+ * A native-only install renders no snippet at all: the tracker is the client.
16
+ */
17
+ const AnalyticsScripts = ({ config, nonce }) => /* @__PURE__ */ jsxs(Fragment, { children: [config.slots.flatMap((slot) => slot.requiresConsent ? [] : slot.snippet.scripts.map((script, index) => {
18
+ const key = `${slot.slot}-${index}`;
19
+ return script.inline ? /* @__PURE__ */ jsx("script", {
20
+ ...script.attrs,
21
+ async: script.async,
22
+ defer: script.defer,
23
+ dangerouslySetInnerHTML: { __html: script.inline },
24
+ nonce,
25
+ type: script.type
26
+ }, key) : /* @__PURE__ */ jsx("script", {
27
+ ...script.attrs,
28
+ async: script.async,
29
+ defer: script.defer,
30
+ nonce,
31
+ src: script.src,
32
+ type: script.type
33
+ }, key);
34
+ })), /* @__PURE__ */ jsx(TrackerBoot, {
35
+ config,
36
+ nonce
37
+ })] });
38
+ //#endregion
39
+ export { AnalyticsScripts };
40
+
41
+ //# sourceMappingURL=AnalyticsScripts.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AnalyticsScripts.js","names":[],"sources":["../../src/rsc/AnalyticsScripts.tsx"],"sourcesContent":["import type { ReactElement } from 'react'\nimport type { TrackerConfig } from '../capture/trackerConfig'\nimport { TrackerBoot } from '../react/TrackerBoot'\n\nexport interface AnalyticsScriptsProps {\n\t/** Resolved server-side, by `getTrackerConfig` or the tracker endpoint. */\n\tconfig: TrackerConfig\n\t/** CSP nonce, applied to every script this renders. */\n\tnonce?: string\n}\n\n/**\n * Renders each capture slot's vendor snippet, then boots the tracker over them. Snippet\n * scripts come from the slot adapter's own `capture.snippet`, so they are plugin-authored\n * strings rather than anything a request supplied; the inline ones are injected verbatim\n * because a vendor init call has to parse as script, not as text.\n *\n * A slot that waits for consent renders nothing: shipping its script in the HTML would run\n * the vendor's tracker before the visitor answered, which is the whole point of the gate.\n * Its sink injects the same snippet once consent is granted (or immediately, when a granted\n * decision was already persisted), and the loader skips scripts the page already carries.\n *\n * A native-only install renders no snippet at all: the tracker is the client.\n */\nexport const AnalyticsScripts = ({ config, nonce }: AnalyticsScriptsProps): ReactElement => (\n\t<>\n\t\t{config.slots.flatMap((slot) =>\n\t\t\tslot.requiresConsent\n\t\t\t\t? []\n\t\t\t\t: slot.snippet.scripts.map((script, index) => {\n\t\t\t\t\t\tconst key = `${slot.slot}-${index}`\n\t\t\t\t\t\treturn script.inline ? (\n\t\t\t\t\t\t\t<script\n\t\t\t\t\t\t\t\tkey={key}\n\t\t\t\t\t\t\t\t{...script.attrs}\n\t\t\t\t\t\t\t\tasync={script.async}\n\t\t\t\t\t\t\t\tdefer={script.defer}\n\t\t\t\t\t\t\t\t// biome-ignore lint/security/noDangerouslySetInnerHtml: adapter-authored vendor init\n\t\t\t\t\t\t\t\tdangerouslySetInnerHTML={{ __html: script.inline }}\n\t\t\t\t\t\t\t\tnonce={nonce}\n\t\t\t\t\t\t\t\ttype={script.type}\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t) : (\n\t\t\t\t\t\t\t<script\n\t\t\t\t\t\t\t\tkey={key}\n\t\t\t\t\t\t\t\t{...script.attrs}\n\t\t\t\t\t\t\t\tasync={script.async}\n\t\t\t\t\t\t\t\tdefer={script.defer}\n\t\t\t\t\t\t\t\tnonce={nonce}\n\t\t\t\t\t\t\t\tsrc={script.src}\n\t\t\t\t\t\t\t\ttype={script.type}\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t)\n\t\t\t\t\t})\n\t\t)}\n\t\t<TrackerBoot config={config} nonce={nonce} />\n\t</>\n)\n"],"mappings":";;;;;;;;;;;;;;;;AAwBA,MAAa,oBAAoB,EAAE,QAAQ,YAC1C,qBAAA,UAAA,EAAA,UAAA,CACE,OAAO,MAAM,SAAS,SACtB,KAAK,kBACF,CAAC,IACD,KAAK,QAAQ,QAAQ,KAAK,QAAQ,UAAU;CAC5C,MAAM,MAAM,GAAG,KAAK,KAAK,GAAG;CAC5B,OAAO,OAAO,SACb,oBAAC,UAAD;EAEC,GAAI,OAAO;EACX,OAAO,OAAO;EACd,OAAO,OAAO;EAEd,yBAAyB,EAAE,QAAQ,OAAO,OAAO;EAC1C;EACP,MAAM,OAAO;CACb,GARK,GAQL,IAED,oBAAC,UAAD;EAEC,GAAI,OAAO;EACX,OAAO,OAAO;EACd,OAAO,OAAO;EACP;EACP,KAAK,OAAO;EACZ,MAAM,OAAO;CACb,GAPK,GAOL;AAEH,CAAC,CACJ,GACA,oBAAC,aAAD;CAAqB;CAAe;AAAQ,CAAA,CAC3C,EAAA,CAAA"}
@@ -0,0 +1 @@
1
+ export { };