@10x-media/analytics 1.0.0-beta.8 → 1.0.0-beta.9

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 (239) hide show
  1. package/CHANGELOG.md +70 -0
  2. package/LICENSE +21 -21
  3. package/README.md +3 -3
  4. package/dist/adapters/ga4/eventName.d.ts +15 -0
  5. package/dist/adapters/ga4/eventName.js +19 -0
  6. package/dist/adapters/ga4/eventName.js.map +1 -0
  7. package/dist/adapters/ga4/ga4.d.ts +5 -0
  8. package/dist/adapters/ga4/ga4.js +178 -70
  9. package/dist/adapters/ga4/ga4.js.map +1 -1
  10. package/dist/adapters/ga4/measurementId.js +15 -0
  11. package/dist/adapters/ga4/measurementId.js.map +1 -0
  12. package/dist/adapters/goalRead.js +126 -0
  13. package/dist/adapters/goalRead.js.map +1 -0
  14. package/dist/adapters/plausible/plausible.d.ts +15 -0
  15. package/dist/adapters/plausible/plausible.js +110 -42
  16. package/dist/adapters/plausible/plausible.js.map +1 -1
  17. package/dist/adapters/posthog/posthog.js +47 -25
  18. package/dist/adapters/posthog/posthog.js.map +1 -1
  19. package/dist/adapters/umami/umami.d.ts +8 -0
  20. package/dist/adapters/umami/umami.js +237 -28
  21. package/dist/adapters/umami/umami.js.map +1 -1
  22. package/dist/charts/BarList.js +8 -2
  23. package/dist/charts/BarList.js.map +1 -1
  24. package/dist/core/cacheKey.js +11 -1
  25. package/dist/core/cacheKey.js.map +1 -1
  26. package/dist/core/capabilities.js +7 -2
  27. package/dist/core/capabilities.js.map +1 -1
  28. package/dist/core/capture.d.ts +1 -1
  29. package/dist/core/contract.d.ts +32 -2
  30. package/dist/core/contract.js.map +1 -1
  31. package/dist/core/options.d.ts +8 -2
  32. package/dist/core/options.js +4 -2
  33. package/dist/core/options.js.map +1 -1
  34. package/dist/core/serverEvent.d.ts +4 -2
  35. package/dist/core/serverEvent.js.map +1 -1
  36. package/dist/exports/adapters/ga4.d.ts +2 -1
  37. package/dist/exports/adapters/ga4.js +2 -1
  38. package/dist/exports/client.d.ts +5 -2
  39. package/dist/exports/client.js +4 -1
  40. package/dist/exports/rsc.d.ts +2 -1
  41. package/dist/exports/tracker.d.ts +3 -2
  42. package/dist/exports/tracker.js +2 -1
  43. package/dist/exports/types.d.ts +2 -1
  44. package/dist/exports/types.js +2 -1
  45. package/dist/fields/config/FilterDimensionSelectField.d.ts +14 -0
  46. package/dist/fields/config/FilterDimensionSelectField.js +77 -0
  47. package/dist/fields/config/FilterDimensionSelectField.js.map +1 -0
  48. package/dist/fields/config/FilterOperatorSelectField.d.ts +14 -0
  49. package/dist/fields/config/FilterOperatorSelectField.js +75 -0
  50. package/dist/fields/config/FilterOperatorSelectField.js.map +1 -0
  51. package/dist/fields/config/MetricSelectField.js +1 -1
  52. package/dist/fields/config/SourceSelectField.js +1 -1
  53. package/dist/fields/config/sourcesState.js +19 -3
  54. package/dist/fields/config/sourcesState.js.map +1 -1
  55. package/dist/fields/config/useAnalyticsSources.d.ts +8 -3
  56. package/dist/fields/config/useAnalyticsSources.js +9 -6
  57. package/dist/fields/config/useAnalyticsSources.js.map +1 -1
  58. package/dist/fields/config/useFilterCapabilities.d.ts +28 -0
  59. package/dist/fields/config/useFilterCapabilities.js +52 -0
  60. package/dist/fields/config/useFilterCapabilities.js.map +1 -0
  61. package/dist/fields/readForDocument.js +16 -4
  62. package/dist/fields/readForDocument.js.map +1 -1
  63. package/dist/index.d.ts +3 -1
  64. package/dist/index.js +2 -1
  65. package/dist/index.js.map +1 -1
  66. package/dist/native/collections/events.js +36 -0
  67. package/dist/native/collections/events.js.map +1 -1
  68. package/dist/native/eventScan.js +25 -0
  69. package/dist/native/eventScan.js.map +1 -0
  70. package/dist/native/ingest/browser.js +47 -0
  71. package/dist/native/ingest/browser.js.map +1 -0
  72. package/dist/native/ingest/flushBatch.js +26 -26
  73. package/dist/native/ingest/flushBatch.js.map +1 -1
  74. package/dist/native/ingest/language.js +14 -0
  75. package/dist/native/ingest/language.js.map +1 -0
  76. package/dist/native/ingest/normalizeEvent.d.ts +6 -0
  77. package/dist/native/ingest/normalizeEvent.js +32 -5
  78. package/dist/native/ingest/normalizeEvent.js.map +1 -1
  79. package/dist/native/ingest/referrer.js +48 -0
  80. package/dist/native/ingest/referrer.js.map +1 -0
  81. package/dist/native/ingest/serverTrack.js +1 -0
  82. package/dist/native/ingest/serverTrack.js.map +1 -1
  83. package/dist/native/ingest/source.d.ts +7 -0
  84. package/dist/native/ingest/source.js +139 -14
  85. package/dist/native/ingest/source.js.map +1 -1
  86. package/dist/native/ingest/utm.js +33 -0
  87. package/dist/native/ingest/utm.js.map +1 -0
  88. package/dist/native/nativeAdapter.js +32 -26
  89. package/dist/native/nativeAdapter.js.map +1 -1
  90. package/dist/native/query/eventAgg.js +14 -1
  91. package/dist/native/query/eventAgg.js.map +1 -1
  92. package/dist/native/rollups/bucketKey.js +15 -0
  93. package/dist/native/rollups/bucketKey.js.map +1 -0
  94. package/dist/native/rollups/bumpRollups.js +116 -0
  95. package/dist/native/rollups/bumpRollups.js.map +1 -0
  96. package/dist/native/rollups/deltas.js +30 -15
  97. package/dist/native/rollups/deltas.js.map +1 -1
  98. package/dist/native/rollups/insertManyIfNew.js +93 -0
  99. package/dist/native/rollups/insertManyIfNew.js.map +1 -0
  100. package/dist/next/captureRewrites.d.ts +3 -2
  101. package/dist/next/captureRewrites.js +3 -2
  102. package/dist/next/captureRewrites.js.map +1 -1
  103. package/dist/plugin/documentEndpoint.js +26 -7
  104. package/dist/plugin/documentEndpoint.js.map +1 -1
  105. package/dist/plugin/goalHint.d.ts +1 -0
  106. package/dist/plugin/goalHint.js +24 -0
  107. package/dist/plugin/goalHint.js.map +1 -0
  108. package/dist/plugin/queryEndpoint.js +19 -12
  109. package/dist/plugin/queryEndpoint.js.map +1 -1
  110. package/dist/plugin/realtimeEndpoint.js +40 -15
  111. package/dist/plugin/realtimeEndpoint.js.map +1 -1
  112. package/dist/plugin/responses.js +17 -0
  113. package/dist/plugin/responses.js.map +1 -0
  114. package/dist/plugin/sourcesEndpoint.js +10 -3
  115. package/dist/plugin/sourcesEndpoint.js.map +1 -1
  116. package/dist/providers/collection.js +14 -4
  117. package/dist/providers/collection.js.map +1 -1
  118. package/dist/providers/factory.js +4 -2
  119. package/dist/providers/factory.js.map +1 -1
  120. package/dist/query/response.d.ts +4 -1
  121. package/dist/query/response.js +11 -0
  122. package/dist/query/response.js.map +1 -0
  123. package/dist/surfacing/engine.js +1 -1
  124. package/dist/surfacing/engine.js.map +1 -1
  125. package/dist/testing/memoryAdapter.js +0 -1
  126. package/dist/testing/memoryAdapter.js.map +1 -1
  127. package/dist/tracker/createTracker.js +13 -1
  128. package/dist/tracker/createTracker.js.map +1 -1
  129. package/dist/tracker/sinks/ga4.d.ts +21 -0
  130. package/dist/tracker/sinks/ga4.js +26 -0
  131. package/dist/tracker/sinks/ga4.js.map +1 -0
  132. package/dist/tracker/types.d.ts +5 -0
  133. package/dist/translations/ar.js +30 -1
  134. package/dist/translations/ar.js.map +1 -1
  135. package/dist/translations/de.js +30 -1
  136. package/dist/translations/de.js.map +1 -1
  137. package/dist/translations/en.js +30 -1
  138. package/dist/translations/en.js.map +1 -1
  139. package/dist/translations/es.js +30 -1
  140. package/dist/translations/es.js.map +1 -1
  141. package/dist/translations/fr.js +30 -1
  142. package/dist/translations/fr.js.map +1 -1
  143. package/dist/translations/id.js +30 -1
  144. package/dist/translations/id.js.map +1 -1
  145. package/dist/translations/keys.d.ts +29 -0
  146. package/dist/translations/keys.js +30 -1
  147. package/dist/translations/keys.js.map +1 -1
  148. package/dist/translations/ko.js +30 -1
  149. package/dist/translations/ko.js.map +1 -1
  150. package/dist/translations/metricKeys.js +7 -1
  151. package/dist/translations/metricKeys.js.map +1 -1
  152. package/dist/translations/pt.js +30 -1
  153. package/dist/translations/pt.js.map +1 -1
  154. package/dist/translations/ru.js +30 -1
  155. package/dist/translations/ru.js.map +1 -1
  156. package/dist/translations/server.js.map +1 -1
  157. package/dist/translations/uk.js +30 -1
  158. package/dist/translations/uk.js.map +1 -1
  159. package/dist/translations/zh.js +30 -1
  160. package/dist/translations/zh.js.map +1 -1
  161. package/dist/view/AnalyticsViewClient.js +13 -2
  162. package/dist/view/AnalyticsViewClient.js.map +1 -1
  163. package/dist/view/gating.js +40 -3
  164. package/dist/view/gating.js.map +1 -1
  165. package/dist/view/labels.js +21 -1
  166. package/dist/view/labels.js.map +1 -1
  167. package/dist/view/sections/Breakdowns.js +78 -38
  168. package/dist/view/sections/Breakdowns.js.map +1 -1
  169. package/dist/view/sections/FilterChips.js +8 -3
  170. package/dist/view/sections/FilterChips.js.map +1 -1
  171. package/dist/view/sections/GoalsPanel.js +2 -1
  172. package/dist/view/sections/GoalsPanel.js.map +1 -1
  173. package/dist/view/sections/RealtimeStrip.js +4 -1
  174. package/dist/view/sections/RealtimeStrip.js.map +1 -1
  175. package/dist/view/sections/Toolbar.js +10 -3
  176. package/dist/view/sections/Toolbar.js.map +1 -1
  177. package/dist/view/sections/Trend.js +8 -2
  178. package/dist/view/sections/Trend.js.map +1 -1
  179. package/dist/view/state.js +7 -2
  180. package/dist/view/state.js.map +1 -1
  181. package/dist/view/useViewQueries.js +6 -3
  182. package/dist/view/useViewQueries.js.map +1 -1
  183. package/dist/widgets/AnalyticsBreakdownWidget.js +59 -10
  184. package/dist/widgets/AnalyticsBreakdownWidget.js.map +1 -1
  185. package/dist/widgets/AnalyticsGoalsWidget.js +10 -2
  186. package/dist/widgets/AnalyticsGoalsWidget.js.map +1 -1
  187. package/dist/widgets/AnalyticsMetricWidget.js +30 -3
  188. package/dist/widgets/AnalyticsMetricWidget.js.map +1 -1
  189. package/dist/widgets/AnalyticsRealtimeWidget.js +3 -1
  190. package/dist/widgets/AnalyticsRealtimeWidget.js.map +1 -1
  191. package/dist/widgets/AnalyticsTrendWidget.js +30 -3
  192. package/dist/widgets/AnalyticsTrendWidget.js.map +1 -1
  193. package/dist/widgets/RealtimeCounter.d.ts +4 -0
  194. package/dist/widgets/RealtimeCounter.js +10 -1
  195. package/dist/widgets/RealtimeCounter.js.map +1 -1
  196. package/dist/widgets/breakdownTypes.js.map +1 -1
  197. package/dist/widgets/comparison.js +15 -1
  198. package/dist/widgets/comparison.js.map +1 -1
  199. package/dist/widgets/defaults.d.ts +6 -2
  200. package/dist/widgets/defaults.js +72 -25
  201. package/dist/widgets/defaults.js.map +1 -1
  202. package/dist/widgets/filterCaption.js +27 -0
  203. package/dist/widgets/filterCaption.js.map +1 -0
  204. package/dist/widgets/filterField.d.ts +19 -0
  205. package/dist/widgets/filterField.js +75 -0
  206. package/dist/widgets/filterField.js.map +1 -0
  207. package/dist/widgets/prepareWidgetRead.d.ts +7 -0
  208. package/dist/widgets/prepareWidgetRead.js +74 -0
  209. package/dist/widgets/prepareWidgetRead.js.map +1 -0
  210. package/dist/widgets/readForWidget.d.ts +12 -2
  211. package/dist/widgets/readForWidget.js +34 -49
  212. package/dist/widgets/readForWidget.js.map +1 -1
  213. package/dist/widgets/readForWidgetBreakdown.d.ts +17 -1
  214. package/dist/widgets/readForWidgetBreakdown.js +29 -42
  215. package/dist/widgets/readForWidgetBreakdown.js.map +1 -1
  216. package/dist/widgets/readForWidgetGoals.d.ts +11 -1
  217. package/dist/widgets/readForWidgetGoals.js +44 -30
  218. package/dist/widgets/readForWidgetGoals.js.map +1 -1
  219. package/dist/widgets/readForWidgetRealtime.d.ts +8 -0
  220. package/dist/widgets/readForWidgetRealtime.js +21 -20
  221. package/dist/widgets/readForWidgetRealtime.js.map +1 -1
  222. package/dist/widgets/readForWidgetSeries.d.ts +11 -1
  223. package/dist/widgets/readForWidgetSeries.js +38 -49
  224. package/dist/widgets/readForWidgetSeries.js.map +1 -1
  225. package/dist/widgets/readMeta.js +18 -0
  226. package/dist/widgets/readMeta.js.map +1 -0
  227. package/dist/widgets/registerWidgets.js +5 -2
  228. package/dist/widgets/registerWidgets.js.map +1 -1
  229. package/dist/widgets/types.d.ts +15 -0
  230. package/dist/widgets/types.js.map +1 -1
  231. package/dist/widgets/viewLink.js +5 -2
  232. package/dist/widgets/viewLink.js.map +1 -1
  233. package/package.json +5 -5
  234. package/dist/native/rollups/applyDistinctDeltas.js +0 -9
  235. package/dist/native/rollups/applyDistinctDeltas.js.map +0 -1
  236. package/dist/native/rollups/bumpRollup.js +0 -73
  237. package/dist/native/rollups/bumpRollup.js.map +0 -1
  238. package/dist/native/rollups/insertIfNew.js +0 -53
  239. package/dist/native/rollups/insertIfNew.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"umami.js","names":[],"sources":["../../../src/adapters/umami/umami.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 } from '../series'\n\nexport interface UmamiConfig {\n\twebsiteId: string\n\t/** Umami Cloud API key (sent as x-umami-api-key). */\n\tapiKey?: string\n\t/** Self-hosted bearer token (from POST /api/auth/login). */\n\ttoken?: string\n\t/**\n\t * API base URL. Defaults to Umami Cloud (https://api.umami.is/v1). Self-hosted is\n\t * e.g. https://site/api. Capture derives the app origin from this (a trailing `/api`\n\t * is stripped), so one `host` value serves both the Stats API and the tracker.\n\t */\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 CLOUD_BASE = 'https://api.umami.is/v1'\nconst CLOUD_SCRIPT = 'https://cloud.umami.is/script.js'\nconst CLOUD_SEND = 'https://gateway.umami.is/api/send'\n\nfunction buildCapture(config: UmamiConfig): CaptureSupport {\n\tconst origin = config.host ? config.host.replace(/\\/api\\/?$/, '').replace(/\\/+$/, '') : null\n\tconst scriptUpstream = origin ? `${origin}/script.js` : CLOUD_SCRIPT\n\tconst sendUpstream = origin ? `${origin}/api/send` : CLOUD_SEND\n\treturn {\n\t\tproxy: {\n\t\t\troutes: [\n\t\t\t\t{ source: '/script.js', upstream: scriptUpstream },\n\t\t\t\t{ source: '/api/send', upstream: sendUpstream },\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\tsrc: `${path}/script.js`,\n\t\t\t\t\tdefer: true,\n\t\t\t\t\tattrs: { 'data-website-id': config.websiteId, 'data-host-url': path },\n\t\t\t\t},\n\t\t\t],\n\t\t}),\n\t\tclient: { kind: 'umami' },\n\t}\n}\n\nconst umamiMetrics: ReadonlySet<MetricKey> = new Set<MetricKey>([\n\t'pageviews',\n\t'visitors',\n\t'visits',\n\t'sessions',\n\t'bounceRate',\n\t'avgDuration',\n])\nconst umamiDimensions: ReadonlySet<DimensionKey> = new Set<DimensionKey>(['page'])\n\ninterface UmamiStats {\n\tpageviews: number\n\tvisitors: number\n\tvisits: number\n\tbounces: number\n\ttotaltime: number\n}\n\nexport function umami(config: UmamiConfig): AnalyticsAdapter {\n\tconst base = config.host ?? CLOUD_BASE\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: umamiMetrics,\n\t\tdimensions: umamiDimensions,\n\t\tfilters: new Set(),\n\t\tfilterOperators: new Set(['eq']),\n\t\tbatchPageReport: true,\n\t\trateLimit: null,\n\t\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n\t}\n\t// Cloud authenticates with x-umami-api-key; self-hosted with a bearer token.\n\t// NOTE: the cloud header name and the per-URL `path` filter (set in params(), also\n\t// sent to /metrics) match the documented v2 shape but are unvalidated against a live\n\t// instance; confirm both before relying on per-URL provider data in production.\n\tconst authHeaders = (): Record<string, string> =>\n\t\tconfig.apiKey\n\t\t\t? { 'x-umami-api-key': config.apiKey }\n\t\t\t: config.token\n\t\t\t\t? { authorization: `Bearer ${config.token}` }\n\t\t\t\t: {}\n\n\tconst params = (q: AnalyticsQuery): URLSearchParams => {\n\t\tconst p = new URLSearchParams({\n\t\t\tstartAt: String(q.dateRange.start.getTime()),\n\t\t\tendAt: String(q.dateRange.end.getTime()),\n\t\t})\n\t\tif (q.path) {\n\t\t\tp.set('path', q.path)\n\t\t}\n\t\treturn p\n\t}\n\n\treturn {\n\t\tid: 'umami',\n\t\tlabel: 'Umami',\n\t\tcapabilities,\n\t\tcapture: buildCapture(config),\n\t\tisConfigured: () => Boolean(config.websiteId && (config.apiKey || config.token)),\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst headers = authHeaders()\n\t\t\tconst wantsPageBreakdown = (q.dimensions ?? []).includes('page')\n\n\t\t\tif (wantsPageBreakdown) {\n\t\t\t\tconst p = params(q)\n\t\t\t\tp.set('type', 'url')\n\t\t\t\tconst data = await fetchJson<Array<{ x: string; y: number }>>(\n\t\t\t\t\t`${base}/websites/${config.websiteId}/metrics?${p.toString()}`,\n\t\t\t\t\t{ headers, signal: ctx.signal, provider: 'umami' }\n\t\t\t\t)\n\t\t\t\tconst metric: MetricKey = q.metrics.includes('pageviews') ? 'pageviews' : 'visitors'\n\t\t\t\tconst rows: AnalyticsRow[] = data.map((row) => ({\n\t\t\t\t\tdimensions: { page: row.x },\n\t\t\t\t\tmetrics: { [metric]: row.y } as Partial<Record<MetricKey, number>>,\n\t\t\t\t}))\n\t\t\t\treturn { rows, totals: undefined, meta: { provider: 'umami', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst fetchTotals = async (): Promise<Partial<Record<MetricKey, number>>> => {\n\t\t\t\tconst stats = await fetchJson<UmamiStats>(\n\t\t\t\t\t`${base}/websites/${config.websiteId}/stats?${params(q).toString()}`,\n\t\t\t\t\t{ headers, signal: ctx.signal, provider: 'umami' }\n\t\t\t\t)\n\t\t\t\tconst all: Partial<Record<MetricKey, number>> = {\n\t\t\t\t\tpageviews: stats.pageviews,\n\t\t\t\t\tvisitors: stats.visitors,\n\t\t\t\t\tvisits: stats.visits,\n\t\t\t\t\tsessions: stats.visits,\n\t\t\t\t\t// Derived ratios are omitted (not zeroed) when there are no visits, so the\n\t\t\t\t\t// display layer shows a \"no data\" state instead of a misleading 0.\n\t\t\t\t\tbounceRate:\n\t\t\t\t\t\tstats.visits > 0 ? Math.round((stats.bounces / stats.visits) * 100) : undefined,\n\t\t\t\t\tavgDuration:\n\t\t\t\t\t\tstats.visits > 0 ? Math.round((stats.totaltime / stats.visits) * 1000) : undefined,\n\t\t\t\t}\n\t\t\t\tconst totals: Partial<Record<MetricKey, number>> = {}\n\t\t\t\tfor (const m of q.metrics) {\n\t\t\t\t\tif (all[m] !== undefined) {\n\t\t\t\t\t\ttotals[m] = all[m]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn totals\n\t\t\t}\n\n\t\t\t// Umami's only time-series endpoint reports pageviews and sessions per interval;\n\t\t\t// visitors/bounceRate/avgDuration have no per-day source, so a trend on those\n\t\t\t// metrics keeps a correct headline (from /stats) but an empty series.\n\t\t\tif (q.granularity === 'day') {\n\t\t\t\tconst p = params(q)\n\t\t\t\tp.set('unit', 'day')\n\t\t\t\tp.set('timezone', q.timezone ?? 'UTC')\n\t\t\t\tconst fetchSeries = () =>\n\t\t\t\t\tfetchJson<{\n\t\t\t\t\t\tpageviews: Array<{ x: string; y: number }>\n\t\t\t\t\t\tsessions: Array<{ x: string; y: number }>\n\t\t\t\t\t}>(`${base}/websites/${config.websiteId}/pageviews?${p.toString()}`, {\n\t\t\t\t\t\theaders,\n\t\t\t\t\t\tsignal: ctx.signal,\n\t\t\t\t\t\tprovider: 'umami',\n\t\t\t\t\t})\n\t\t\t\tconst [series, totals] = await Promise.all([fetchSeries(), fetchTotals()])\n\t\t\t\tconst sessionsByX = new Map(series.sessions.map((s) => [s.x, s.y]))\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const pv of series.pageviews) {\n\t\t\t\t\tconst ts = dayIso(pv.x)\n\t\t\t\t\tif (!ts) {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tconst dayMetrics = sessionsByX.get(pv.x) ?? 0\n\t\t\t\t\tconst all: Partial<Record<MetricKey, number>> = {\n\t\t\t\t\t\tpageviews: pv.y,\n\t\t\t\t\t\tvisits: dayMetrics,\n\t\t\t\t\t\tsessions: dayMetrics,\n\t\t\t\t\t}\n\t\t\t\t\tconst metrics: Partial<Record<MetricKey, number>> = {}\n\t\t\t\t\tfor (const m of q.metrics) {\n\t\t\t\t\t\tif (all[m] !== undefined) {\n\t\t\t\t\t\t\tmetrics[m] = all[m]\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\trows.push({ timestamp: ts, metrics })\n\t\t\t\t}\n\t\t\t\treturn { rows, totals, meta: { provider: 'umami', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst totals = await fetchTotals()\n\t\t\treturn { rows: [{ metrics: totals }], totals, meta: { provider: 'umami', fetchedAt } }\n\t\t},\n\t}\n}\n"],"mappings":";;;AA8BA,MAAM,aAAa;AACnB,MAAM,eAAe;AACrB,MAAM,aAAa;AAEnB,SAAS,aAAa,QAAqC;CAC1D,MAAM,SAAS,OAAO,OAAO,OAAO,KAAK,QAAQ,aAAa,EAAE,EAAE,QAAQ,QAAQ,EAAE,IAAI;CACxF,MAAM,iBAAiB,SAAS,GAAG,OAAO,cAAc;CACxD,MAAM,eAAe,SAAS,GAAG,OAAO,aAAa;CACrD,OAAO;EACN,OAAO,EACN,QAAQ,CACP;GAAE,QAAQ;GAAc,UAAU;EAAe,GACjD;GAAE,QAAQ;GAAa,UAAU;EAAa,CAC/C,EACD;EACA,UAAU,EAAE,YAAY,EACvB,SAAS,CACR;GACC,KAAK,GAAG,KAAK;GACb,OA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AAK;KACpE;KACA,QAAQ,IAAI;KACZ,UAAU;IACX,CAAC;IACF,MAAM,CAAC,QAAQ,UAAU,MAAM,QAAQ,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC,CAAC;IACzE,MAAM,cAAc,IAAI,IAAI,OAAO,SAAS,KAAK,MAAM,CAAC,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC;IAClE,MAAM,OAAuB,CAAC;IAC9B,KAAK,MAAM,MAAM,OAAO,WAAW;KAClC,MAAM,KAAK,OAAO,GAAG,CAAC;KACtB,IAAI,CAAC,IACJ;KAED,MAAM,aAAa,YAAY,IAAI,GAAG,CAAC,KAAK;KAC5C,MAAM,MAA0C;MAC/C,WAAW,GAAG;MACd,QAAQ;MACR,UAAU;KACX;KACA,MAAM,UAA8C,CAAC;KACrD,KAAK,MAAM,KAAK,EAAE,SACjB,IAAI,IAAI,OAAO,KAAA,GACd,QAAQ,KAAK,IAAI;KAGnB,KAAK,KAAK;MAAE,WAAW;MAAI;KAAQ,CAAC;IACrC;IACA,OAAO;KAAE;KAAM;KAAQ,MAAM;MAAE,UAAU;MAAS;KAAU;IAAE;GAC/D;GAEA,MAAM,SAAS,MAAM,YAAY;GACjC,OAAO;IAAE,MAAM,CAAC,EAAE,SAAS,OAAO,CAAC;IAAG;IAAQ,MAAM;KAAE,UAAU;KAAS;IAAU;GAAE;EACtF;CACD;AACD"}
1
+ {"version":3,"file":"umami.js","names":[],"sources":["../../../src/adapters/umami/umami.ts"],"sourcesContent":["import type { CaptureSupport } from '../../core/capture'\nimport type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsFilter,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tDimensionKey,\n\tFilterOperator,\n\tMetricKey,\n} from '../../core/contract'\nimport { emptyGoalBreakdown, goalHint, hintFailed, hintSlugs } from '../goalRead'\nimport { fetchJson } from '../http/fetchJson'\nimport { dayIso } from '../series'\n\nexport interface UmamiConfig {\n\twebsiteId: string\n\t/** Umami Cloud API key (sent as x-umami-api-key). */\n\tapiKey?: string\n\t/** Self-hosted bearer token (from POST /api/auth/login). */\n\ttoken?: string\n\t/**\n\t * API base URL. Defaults to Umami Cloud (https://api.umami.is/v1). Self-hosted is\n\t * e.g. https://site/api. Capture derives the app origin from this (a trailing `/api`\n\t * is stripped), so one `host` value serves both the Stats API and the tracker.\n\t */\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 CLOUD_BASE = 'https://api.umami.is/v1'\nconst CLOUD_SCRIPT = 'https://cloud.umami.is/script.js'\nconst CLOUD_SEND = 'https://gateway.umami.is/api/send'\n\nfunction buildCapture(config: UmamiConfig): CaptureSupport {\n\tconst origin = config.host ? config.host.replace(/\\/api\\/?$/, '').replace(/\\/+$/, '') : null\n\tconst scriptUpstream = origin ? `${origin}/script.js` : CLOUD_SCRIPT\n\tconst sendUpstream = origin ? `${origin}/api/send` : CLOUD_SEND\n\treturn {\n\t\tproxy: {\n\t\t\troutes: [\n\t\t\t\t{ source: '/script.js', upstream: scriptUpstream },\n\t\t\t\t{ source: '/api/send', upstream: sendUpstream },\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\tsrc: `${path}/script.js`,\n\t\t\t\t\tdefer: true,\n\t\t\t\t\tattrs: { 'data-website-id': config.websiteId, 'data-host-url': path },\n\t\t\t\t},\n\t\t\t],\n\t\t}),\n\t\tclient: { kind: 'umami' },\n\t}\n}\n\nconst umamiMetrics: ReadonlySet<MetricKey> = new Set<MetricKey>([\n\t'pageviews',\n\t'visitors',\n\t'visits',\n\t'sessions',\n\t'bounceRate',\n\t'avgDuration',\n\t'conversions',\n])\n\ninterface UmamiDimension {\n\t/** Umami filter param, which doubles as the /metrics `type` value. */\n\tparam: string\n\t/** The one metric /metrics reports for this type: y is nothing else. */\n\tmetric: MetricKey\n}\n\n// y is count(distinct session_id) on every pageview and session type, and event\n// occurrences on `type=event`.\nconst DIMENSION_MAP: Partial<Record<DimensionKey, UmamiDimension>> = {\n\tpage: { param: 'path', metric: 'visitors' },\n\treferrer: { param: 'referrer', metric: 'visitors' },\n\tbrowser: { param: 'browser', metric: 'visitors' },\n\tos: { param: 'os', metric: 'visitors' },\n\tdevice: { param: 'device', metric: 'visitors' },\n\tcountry: { param: 'country', metric: 'visitors' },\n\tregion: { param: 'region', metric: 'visitors' },\n\tcity: { param: 'city', metric: 'visitors' },\n\tlanguage: { param: 'language', metric: 'visitors' },\n\tevent: { param: 'event', metric: 'events' },\n\tutmSource: { param: 'utmSource', metric: 'visitors' },\n\tutmMedium: { param: 'utmMedium', metric: 'visitors' },\n\tutmCampaign: { param: 'utmCampaign', metric: 'visitors' },\n\tutmContent: { param: 'utmContent', metric: 'visitors' },\n\tutmTerm: { param: 'utmTerm', metric: 'visitors' },\n}\n\n/**\n * Goals are custom events here, counted by `/metrics?type=event`, whose y is the number of\n * occurrences: a plugin goal's slug must equal the captured event's name. It is the one\n * shape that answers `conversions`, so a breakdown by any other dimension and the daily\n * series report none.\n */\nconst GOAL_DIMENSION: UmamiDimension = { param: 'event', metric: 'conversions' }\n\n/**\n * Umami's `re.` is `~*`: a case-insensitive partial match, so an unanchored pattern hits\n * anywhere in the value. `c.` is `ilike`, also case-insensitive.\n */\nconst OPERATOR_PREFIX: Record<FilterOperator, string> = {\n\teq: 'eq.',\n\tcontains: 'c.',\n\tmatches: 're.',\n}\n\nconst umamiFilters: ReadonlySet<DimensionKey> = new Set(\n\tObject.keys(DIMENSION_MAP) as DimensionKey[]\n)\n\n// `event` is filterable but not a group: /metrics counts event occurrences for it, and the\n// adapter cannot declare `events` as a metric because /stats reports no such number. `goal`\n// is the reverse, a group the read's own slugs narrow rather than a filter a caller writes.\nconst umamiDimensions: ReadonlySet<DimensionKey> = new Set([\n\t...[...umamiFilters].filter((dimension) => dimension !== 'event'),\n\t'goal' as DimensionKey,\n])\n\ninterface UmamiParams {\n\tsearch: URLSearchParams\n\t/** Filters a one-value-per-param request could not carry. */\n\tunapplied: AnalyticsFilter[]\n\t/** Two `eq` values on one param: the AND matches nothing, so the read serves no rows. */\n\tempty: boolean\n}\n\ninterface UmamiStats {\n\tpageviews: number\n\tvisitors: number\n\tvisits: number\n\tbounces: number\n\ttotaltime: number\n}\n\n/**\n * Targets Umami 3.x (cloud and self-hosted): filter values carry an operator prefix, and\n * `eq.` is always written explicitly. Umami parses any of `eq`, `neq`, `c`, `dnc`, `re`,\n * `nre`, `s`, `ns`, `t`, `f`, `gt`, `lt`, `gte`, `lte`, `bf` and `af` followed by a dot as\n * the operator, so a bare value beginning with one (`s.example.com`) would change meaning;\n * written as `eq.s.example.com` it stays a literal. Umami splits an `eq.` value on commas\n * into a value list, with no escape.\n */\nexport function umami(config: UmamiConfig): AnalyticsAdapter {\n\tconst base = config.host ?? CLOUD_BASE\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 730\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\tperPageQuery: true,\n\t\trealtime: false,\n\t\tminGranularity: 'day',\n\t\tmaxLookbackDays,\n\t\tmetrics: umamiMetrics,\n\t\tdimensions: umamiDimensions,\n\t\tfilters: umamiFilters,\n\t\tfilterOperators: new Set(['eq', 'contains', 'matches']),\n\t\tbatchPageReport: true,\n\t\trateLimit: null,\n\t\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n\t}\n\t// Cloud authenticates with x-umami-api-key; self-hosted with a bearer token.\n\tconst authHeaders = (): Record<string, string> =>\n\t\tconfig.apiKey\n\t\t\t? { 'x-umami-api-key': config.apiKey }\n\t\t\t: config.token\n\t\t\t\t? { authorization: `Bearer ${config.token}` }\n\t\t\t\t: {}\n\n\t/**\n\t * Umami takes one value per query param, so filters that land on the same param cannot\n\t * all be sent. Two `eq` values on one param are an AND that matches nothing, which the\n\t * read answers as empty without calling the API; anything else keeps the first filter,\n\t * except that `q.path` always wins the `path` param so a per-page read stays scoped to\n\t * its page. An `eq` value carrying a comma is dropped too: Umami reads such a value as a\n\t * list and offers no escape, so sending it would answer a wider question than the one\n\t * asked. Whatever was dropped travels back in `meta.unappliedFilters`.\n\t */\n\tconst params = (q: AnalyticsQuery): UmamiParams => {\n\t\tconst p = new URLSearchParams({\n\t\t\tstartAt: String(q.dateRange.start.getTime()),\n\t\t\tendAt: String(q.dateRange.end.getTime()),\n\t\t})\n\t\tconst unapplied: AnalyticsFilter[] = []\n\t\tconst eqValues = new Map<string, string>()\n\t\tfor (const filter of q.filters ?? []) {\n\t\t\tconst mapped = DIMENSION_MAP[filter.dimension]\n\t\t\tif (!mapped || filter.operator !== 'eq') {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst held = eqValues.get(mapped.param)\n\t\t\tif (held !== undefined && held !== filter.value) {\n\t\t\t\treturn { search: p, unapplied, empty: true }\n\t\t\t}\n\t\t\teqValues.set(mapped.param, filter.value)\n\t\t}\n\t\tconst held = new Map<string, { value: string; filter: AnalyticsFilter }>()\n\t\tfor (const filter of q.filters ?? []) {\n\t\t\tconst mapped = DIMENSION_MAP[filter.dimension]\n\t\t\tif (!mapped) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (filter.operator === 'eq' && filter.value.includes(',')) {\n\t\t\t\tunapplied.push(filter)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst value = `${OPERATOR_PREFIX[filter.operator]}${filter.value}`\n\t\t\tconst first = held.get(mapped.param)\n\t\t\tif (first === undefined) {\n\t\t\t\theld.set(mapped.param, { value, filter })\n\t\t\t\tp.set(mapped.param, value)\n\t\t\t} else if (first.value !== value) {\n\t\t\t\tunapplied.push(filter)\n\t\t\t}\n\t\t}\n\t\tif (q.path) {\n\t\t\tconst value = `eq.${q.path}`\n\t\t\tconst first = held.get('path')\n\t\t\tif (first !== undefined && first.value !== value) {\n\t\t\t\tunapplied.push(first.filter)\n\t\t\t}\n\t\t\tp.set('path', value)\n\t\t}\n\t\treturn { search: p, unapplied, empty: false }\n\t}\n\n\treturn {\n\t\tid: 'umami',\n\t\tlabel: 'Umami',\n\t\tcapabilities,\n\t\tcapture: buildCapture(config),\n\t\tisConfigured: () => Boolean(config.websiteId && (config.apiKey || config.token)),\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst headers = authHeaders()\n\t\t\tconst goalBreakdown = (q.dimensions ?? []).includes('goal')\n\t\t\tconst hint = goalHint(q)\n\t\t\tconst slugs = hintSlugs(hint)\n\t\t\tconst plan = params(q)\n\t\t\tlet breakdown: ({ dimension: DimensionKey } & UmamiDimension) | undefined\n\t\t\tfor (const dimension of q.dimensions ?? []) {\n\t\t\t\tconst mapped = DIMENSION_MAP[dimension]\n\t\t\t\tif (mapped) {\n\t\t\t\t\tbreakdown = { dimension, ...mapped }\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Umami splits an `eq.` value list on commas and offers no escape, so a slug carrying\n\t\t\t// one cannot be asked for: it is left out of the request and reported, rather than\n\t\t\t// widening the read to every event.\n\t\t\tconst askable = (slugs ?? []).filter((slug) => !slug.includes(','))\n\t\t\tconst eventValue = `eq.${askable.join(',')}`\n\t\t\t// The goal rows come from the `event` param, so a caller's own filter on it would\n\t\t\t// contradict the hint. The hint wins and that filter is reported unapplied, but only\n\t\t\t// on a read that fetches goal rows at all: a breakdown by another dimension never\n\t\t\t// does, so its event filter travels with the request as written.\n\t\t\tconst eventFilter = (q.filters ?? []).find((f) => f.dimension === 'event')\n\t\t\tconst readsGoals =\n\t\t\t\tgoalBreakdown || (!breakdown && q.metrics.includes('conversions') && slugs !== null)\n\t\t\tconst unapplied: AnalyticsFilter[] = [\n\t\t\t\t...plan.unapplied,\n\t\t\t\t...(slugs ?? [])\n\t\t\t\t\t.filter((slug) => slug.includes(','))\n\t\t\t\t\t.map((slug) => ({\n\t\t\t\t\t\tdimension: 'goal' as const,\n\t\t\t\t\t\toperator: 'eq' as const,\n\t\t\t\t\t\tvalue: slug,\n\t\t\t\t\t})),\n\t\t\t\t...(readsGoals &&\n\t\t\t\teventFilter &&\n\t\t\t\t`${OPERATOR_PREFIX[eventFilter.operator]}${eventFilter.value}` !== eventValue\n\t\t\t\t\t? [eventFilter]\n\t\t\t\t\t: []),\n\t\t\t]\n\t\t\tconst unresolved = q.metrics.includes('conversions') && hintFailed(hint)\n\t\t\tconst unappliedMeta = unapplied.length > 0 ? { unappliedFilters: unapplied } : {}\n\t\t\tconst empty = goalBreakdown\n\t\t\t\t? emptyGoalBreakdown({ provider: 'umami', q, hint, meta: unappliedMeta })\n\t\t\t\t: null\n\t\t\tif (empty) {\n\t\t\t\treturn empty\n\t\t\t}\n\t\t\tconst meta: AnalyticsResult['meta'] = {\n\t\t\t\tprovider: 'umami',\n\t\t\t\tfetchedAt,\n\t\t\t\t...unappliedMeta,\n\t\t\t\t...(unresolved ? { goalsUnresolved: true as const } : {}),\n\t\t\t}\n\t\t\t// Totals are left undefined rather than zeroed, the same as every other number this\n\t\t\t// adapter cannot report, so the display layer shows \"no data\" instead of a real 0.\n\t\t\tif (plan.empty) {\n\t\t\t\treturn { rows: [], totals: undefined, meta }\n\t\t\t}\n\t\t\tconst search = (): URLSearchParams => new URLSearchParams(plan.search)\n\n\t\t\t/**\n\t\t\t * The goal rows for the hint, narrowed to it again on the way back so nothing the API\n\t\t\t * did not restrict can arrive as a goal.\n\t\t\t */\n\t\t\tconst fetchGoalRows = async (): Promise<Array<{ x: string; y: number }>> => {\n\t\t\t\tif (askable.length === 0) {\n\t\t\t\t\treturn []\n\t\t\t\t}\n\t\t\t\tconst p = search()\n\t\t\t\tp.set('type', GOAL_DIMENSION.param)\n\t\t\t\tp.set(GOAL_DIMENSION.param, eventValue)\n\t\t\t\tconst data = await fetchJson<Array<{ x: string; y: number }>>(\n\t\t\t\t\t`${base}/websites/${config.websiteId}/metrics?${p.toString()}`,\n\t\t\t\t\t{ headers, signal: ctx.signal, provider: 'umami' }\n\t\t\t\t)\n\t\t\t\tconst wanted = new Set(askable)\n\t\t\t\treturn data.filter((row) => wanted.has(row.x))\n\t\t\t}\n\n\t\t\tif (goalBreakdown) {\n\t\t\t\tconst data = await fetchGoalRows()\n\t\t\t\tconst rows: AnalyticsRow[] = data.map((row) => ({\n\t\t\t\t\tdimensions: { goal: row.x },\n\t\t\t\t\tmetrics: { [GOAL_DIMENSION.metric]: row.y },\n\t\t\t\t}))\n\t\t\t\treturn { rows, totals: undefined, meta }\n\t\t\t}\n\n\t\t\tif (breakdown) {\n\t\t\t\tconst { dimension, param, metric } = breakdown\n\t\t\t\tconst p = search()\n\t\t\t\tp.set('type', param)\n\t\t\t\tconst data = await fetchJson<Array<{ x: string; y: number }>>(\n\t\t\t\t\t`${base}/websites/${config.websiteId}/metrics?${p.toString()}`,\n\t\t\t\t\t{ headers, signal: ctx.signal, provider: 'umami' }\n\t\t\t\t)\n\t\t\t\t// /metrics reports exactly one number per row, and rows always carry it under the\n\t\t\t\t// name it actually holds. A requested metric Umami has no per-row source for is\n\t\t\t\t// absent rather than labelled with a number it is not.\n\t\t\t\tconst rows: AnalyticsRow[] = data.map((row) => ({\n\t\t\t\t\tdimensions: { [dimension]: row.x },\n\t\t\t\t\tmetrics: { [metric]: row.y },\n\t\t\t\t}))\n\t\t\t\treturn { rows, totals: undefined, meta }\n\t\t\t}\n\n\t\t\tconst fetchTotals = async (): Promise<Partial<Record<MetricKey, number>>> => {\n\t\t\t\t// Conversions have no place in /stats: their total is the goal rows summed.\n\t\t\t\tconst [stats, goalRows] = await Promise.all([\n\t\t\t\t\tfetchJson<UmamiStats>(\n\t\t\t\t\t\t`${base}/websites/${config.websiteId}/stats?${search().toString()}`,\n\t\t\t\t\t\t{ headers, signal: ctx.signal, provider: 'umami' }\n\t\t\t\t\t),\n\t\t\t\t\tq.metrics.includes('conversions') && slugs ? fetchGoalRows() : undefined,\n\t\t\t\t])\n\t\t\t\tconst all: Partial<Record<MetricKey, number>> = {\n\t\t\t\t\t...(goalRows ? { conversions: goalRows.reduce((sum, row) => sum + row.y, 0) } : {}),\n\t\t\t\t\tpageviews: stats.pageviews,\n\t\t\t\t\tvisitors: stats.visitors,\n\t\t\t\t\tvisits: stats.visits,\n\t\t\t\t\tsessions: stats.visits,\n\t\t\t\t\t// Derived ratios are omitted (not zeroed) when there are no visits, so the\n\t\t\t\t\t// display layer shows a \"no data\" state instead of a misleading 0.\n\t\t\t\t\tbounceRate:\n\t\t\t\t\t\tstats.visits > 0 ? Math.round((stats.bounces / stats.visits) * 100) : undefined,\n\t\t\t\t\tavgDuration:\n\t\t\t\t\t\tstats.visits > 0 ? Math.round((stats.totaltime / stats.visits) * 1000) : undefined,\n\t\t\t\t}\n\t\t\t\tconst totals: Partial<Record<MetricKey, number>> = {}\n\t\t\t\tfor (const m of q.metrics) {\n\t\t\t\t\tif (all[m] !== undefined) {\n\t\t\t\t\t\ttotals[m] = all[m]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn totals\n\t\t\t}\n\n\t\t\t// Umami's only time-series endpoint reports pageviews and sessions per interval;\n\t\t\t// visitors/bounceRate/avgDuration have no per-day source, so a trend on those\n\t\t\t// metrics keeps a correct headline (from /stats) but an empty series.\n\t\t\tif (q.granularity === 'day') {\n\t\t\t\tconst p = search()\n\t\t\t\tp.set('unit', 'day')\n\t\t\t\tp.set('timezone', q.timezone ?? 'UTC')\n\t\t\t\tconst fetchSeries = () =>\n\t\t\t\t\tfetchJson<{\n\t\t\t\t\t\tpageviews: Array<{ x: string; y: number }>\n\t\t\t\t\t\tsessions: Array<{ x: string; y: number }>\n\t\t\t\t\t}>(`${base}/websites/${config.websiteId}/pageviews?${p.toString()}`, {\n\t\t\t\t\t\theaders,\n\t\t\t\t\t\tsignal: ctx.signal,\n\t\t\t\t\t\tprovider: 'umami',\n\t\t\t\t\t})\n\t\t\t\tconst [series, totals] = await Promise.all([fetchSeries(), fetchTotals()])\n\t\t\t\tconst sessionsByX = new Map(series.sessions.map((s) => [s.x, s.y]))\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const pv of series.pageviews) {\n\t\t\t\t\tconst ts = dayIso(pv.x)\n\t\t\t\t\tif (!ts) {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tconst dayMetrics = sessionsByX.get(pv.x) ?? 0\n\t\t\t\t\tconst all: Partial<Record<MetricKey, number>> = {\n\t\t\t\t\t\tpageviews: pv.y,\n\t\t\t\t\t\tvisits: dayMetrics,\n\t\t\t\t\t\tsessions: dayMetrics,\n\t\t\t\t\t}\n\t\t\t\t\tconst metrics: Partial<Record<MetricKey, number>> = {}\n\t\t\t\t\tfor (const m of q.metrics) {\n\t\t\t\t\t\tif (all[m] !== undefined) {\n\t\t\t\t\t\t\tmetrics[m] = all[m]\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\trows.push({ timestamp: ts, metrics })\n\t\t\t\t}\n\t\t\t\treturn { rows, totals, meta }\n\t\t\t}\n\n\t\t\tconst totals = await fetchTotals()\n\t\t\treturn { rows: [{ metrics: totals }], totals, meta }\n\t\t},\n\t}\n}\n"],"mappings":";;;;AAiCA,MAAM,aAAa;AACnB,MAAM,eAAe;AACrB,MAAM,aAAa;AAEnB,SAAS,aAAa,QAAqC;CAC1D,MAAM,SAAS,OAAO,OAAO,OAAO,KAAK,QAAQ,aAAa,EAAE,EAAE,QAAQ,QAAQ,EAAE,IAAI;CACxF,MAAM,iBAAiB,SAAS,GAAG,OAAO,cAAc;CACxD,MAAM,eAAe,SAAS,GAAG,OAAO,aAAa;CACrD,OAAO;EACN,OAAO,EACN,QAAQ,CACP;GAAE,QAAQ;GAAc,UAAU;EAAe,GACjD;GAAE,QAAQ;GAAa,UAAU;EAAa,CAC/C,EACD;EACA,UAAU,EAAE,YAAY,EACvB,SAAS,CACR;GACC,KAAK,GAAG,KAAK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,MAAM,KAAK,EAAE,SACjB,IAAI,IAAI,OAAO,KAAA,GACd,OAAO,KAAK,IAAI;IAGlB,OAAO;GACR;GAKA,IAAI,EAAE,gBAAgB,OAAO;IAC5B,MAAM,IAAI,OAAO;IACjB,EAAE,IAAI,QAAQ,KAAK;IACnB,EAAE,IAAI,YAAY,EAAE,YAAY,KAAK;IACrC,MAAM,oBACL,UAGG,GAAG,KAAK,YAAY,OAAO,UAAU,aAAa,EAAE,SAAS,KAAK;KACpE;KACA,QAAQ,IAAI;KACZ,UAAU;IACX,CAAC;IACF,MAAM,CAAC,QAAQ,UAAU,MAAM,QAAQ,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC,CAAC;IACzE,MAAM,cAAc,IAAI,IAAI,OAAO,SAAS,KAAK,MAAM,CAAC,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC;IAClE,MAAM,OAAuB,CAAC;IAC9B,KAAK,MAAM,MAAM,OAAO,WAAW;KAClC,MAAM,KAAK,OAAO,GAAG,CAAC;KACtB,IAAI,CAAC,IACJ;KAED,MAAM,aAAa,YAAY,IAAI,GAAG,CAAC,KAAK;KAC5C,MAAM,MAA0C;MAC/C,WAAW,GAAG;MACd,QAAQ;MACR,UAAU;KACX;KACA,MAAM,UAA8C,CAAC;KACrD,KAAK,MAAM,KAAK,EAAE,SACjB,IAAI,IAAI,OAAO,KAAA,GACd,QAAQ,KAAK,IAAI;KAGnB,KAAK,KAAK;MAAE,WAAW;MAAI;KAAQ,CAAC;IACrC;IACA,OAAO;KAAE;KAAM;KAAQ;IAAK;GAC7B;GAEA,MAAM,SAAS,MAAM,YAAY;GACjC,OAAO;IAAE,MAAM,CAAC,EAAE,SAAS,OAAO,CAAC;IAAG;IAAQ;GAAK;EACpD;CACD;AACD"}
@@ -4,6 +4,12 @@ import { ChartStyles } from "./styles.js";
4
4
  import { useState } from "react";
5
5
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
6
6
  //#region src/charts/BarList.tsx
7
+ /**
8
+ * Ranked rows are identified by rank, since two can share a label: a provider that answers an
9
+ * unattributed bucket as an empty string, or one that repeats a value. Keying on the label
10
+ * alone made those collide, and React strands the duplicates in the DOM across a rerender.
11
+ */
12
+ const rowKey = (row, i) => `${i}:${row.label}`;
7
13
  const RowContent = ({ row }) => /* @__PURE__ */ jsxs(Fragment, { children: [
8
14
  /* @__PURE__ */ jsxs("span", {
9
15
  className: "analytics-bars__track",
@@ -57,13 +63,13 @@ function BarList({ data, emptyLabel, onSelect, fill = "solid" }) {
57
63
  onPointerMove: track(i),
58
64
  type: "button",
59
65
  children: /* @__PURE__ */ jsx(RowContent, { row })
60
- }, row.label) : /* @__PURE__ */ jsx("div", {
66
+ }, rowKey(row, i)) : /* @__PURE__ */ jsx("div", {
61
67
  className: "analytics-bars__row",
62
68
  onPointerEnter: track(i),
63
69
  onPointerLeave: () => setHover(null),
64
70
  onPointerMove: track(i),
65
71
  children: /* @__PURE__ */ jsx(RowContent, { row })
66
- }, row.label))
72
+ }, rowKey(row, i)))
67
73
  }),
68
74
  hover && hovered ? /* @__PURE__ */ jsxs("div", {
69
75
  className: "analytics-chart__tooltip",
@@ -1 +1 @@
1
- {"version":3,"file":"BarList.js","names":[],"sources":["../../src/charts/BarList.tsx"],"sourcesContent":["'use client'\n\nimport { type PointerEvent, type ReactNode, useState } from 'react'\nimport { type BarDatum, type BarRow, toBarRows } from './bars'\nimport { ChartStyles } from './styles'\n\nexport interface BarListProps {\n\tdata: BarDatum[]\n\temptyLabel: string\n\t/**\n\t * Makes every row a button reporting its index. Left out, rows are inert: a source that\n\t * cannot filter by the dimension must not offer a click that would do nothing.\n\t */\n\tonSelect?: (index: number) => void\n\t/**\n\t * `solid` (the default) fills the bar with the chart color and puts a white label inside\n\t * it, which reads as long as every row has a bar to sit on. `soft` pales the fill and\n\t * moves the label onto the elevation ramp, for a list whose rows can be zero-valued (a\n\t * goal with no pageviews), where a zero-width bar leaves a white label on bare track.\n\t */\n\tfill?: 'solid' | 'soft'\n}\n\ninterface Hover {\n\ti: number\n\tx: number\n\ty: number\n}\n\nconst RowContent = ({ row }: { row: BarRow }): ReactNode => (\n\t<>\n\t\t<span className=\"analytics-bars__track\">\n\t\t\t<span className=\"analytics-bars__fill\" style={{ width: `${row.fraction * 100}%` }} />\n\t\t\t<span className=\"analytics-bars__label\">{row.label}</span>\n\t\t</span>\n\t\t<span className=\"analytics-bars__value\">{row.display ?? row.value}</span>\n\t\t{row.secondary === undefined ? null : (\n\t\t\t<span className=\"analytics-bars__secondary\">{row.secondary}</span>\n\t\t)}\n\t</>\n)\n\n/**\n * Ranked horizontal bar list (shadcn \"custom label\" style): each row is a filled,\n * proportional bar with the label inside and the value outside; hovering a row lifts\n * it and shows a tooltip with the full label and value (useful when the label is\n * truncated). Dependency-free; styling comes from the shared chart stylesheet.\n */\nexport function BarList({ data, emptyLabel, onSelect, fill = 'solid' }: BarListProps) {\n\tconst rows = toBarRows(data)\n\tconst [hover, setHover] = useState<Hover | null>(null)\n\tif (rows.length === 0) {\n\t\treturn <span className=\"analytics-bars__empty\">{emptyLabel}</span>\n\t}\n\tconst track = (i: number) => (e: PointerEvent<HTMLElement>) =>\n\t\tsetHover({ i, x: e.clientX, y: e.clientY })\n\tconst hovered = hover ? rows[hover.i] : undefined\n\treturn (\n\t\t<div className=\"analytics-chart\">\n\t\t\t<ChartStyles />\n\t\t\t<div className={`analytics-bars${fill === 'soft' ? ' analytics-bars--soft' : ''}`}>\n\t\t\t\t{rows.map((row, i) =>\n\t\t\t\t\tonSelect ? (\n\t\t\t\t\t\t<button\n\t\t\t\t\t\t\tclassName=\"analytics-bars__row analytics-bars__row--action\"\n\t\t\t\t\t\t\tkey={row.label}\n\t\t\t\t\t\t\tonClick={() => onSelect(i)}\n\t\t\t\t\t\t\tonPointerEnter={track(i)}\n\t\t\t\t\t\t\tonPointerLeave={() => setHover(null)}\n\t\t\t\t\t\t\tonPointerMove={track(i)}\n\t\t\t\t\t\t\ttype=\"button\"\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t<RowContent row={row} />\n\t\t\t\t\t\t</button>\n\t\t\t\t\t) : (\n\t\t\t\t\t\t<div\n\t\t\t\t\t\t\tclassName=\"analytics-bars__row\"\n\t\t\t\t\t\t\tkey={row.label}\n\t\t\t\t\t\t\tonPointerEnter={track(i)}\n\t\t\t\t\t\t\tonPointerLeave={() => setHover(null)}\n\t\t\t\t\t\t\tonPointerMove={track(i)}\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t<RowContent row={row} />\n\t\t\t\t\t\t</div>\n\t\t\t\t\t)\n\t\t\t\t)}\n\t\t\t</div>\n\t\t\t{hover && hovered ? (\n\t\t\t\t<div\n\t\t\t\t\tclassName=\"analytics-chart__tooltip\"\n\t\t\t\t\tstyle={{ position: 'fixed', left: hover.x, top: hover.y }}\n\t\t\t\t>\n\t\t\t\t\t<div className=\"analytics-chart__tooltip-label\">{hovered.label}</div>\n\t\t\t\t\t<div className=\"analytics-chart__tooltip-value\">{hovered.display ?? hovered.value}</div>\n\t\t\t\t</div>\n\t\t\t) : null}\n\t\t</div>\n\t)\n}\n"],"mappings":";;;;;;AA6BA,MAAM,cAAc,EAAE,UACrB,qBAAA,UAAA,EAAA,UAAA;CACC,qBAAC,QAAD;EAAM,WAAU;YAAhB,CACC,oBAAC,QAAD;GAAM,WAAU;GAAuB,OAAO,EAAE,OAAO,GAAG,IAAI,WAAW,IAAI,GAAG;EAAI,CAAA,GACpF,oBAAC,QAAD;GAAM,WAAU;aAAyB,IAAI;EAAY,CAAA,CACpD;;CACN,oBAAC,QAAD;EAAM,WAAU;YAAyB,IAAI,WAAW,IAAI;CAAY,CAAA;CACvE,IAAI,cAAc,KAAA,IAAY,OAC9B,oBAAC,QAAD;EAAM,WAAU;YAA6B,IAAI;CAAgB,CAAA;AAEjE,EAAA,CAAA;;;;;;;AASH,SAAgB,QAAQ,EAAE,MAAM,YAAY,UAAU,OAAO,WAAyB;CACrF,MAAM,OAAO,UAAU,IAAI;CAC3B,MAAM,CAAC,OAAO,YAAY,SAAuB,IAAI;CACrD,IAAI,KAAK,WAAW,GACnB,OAAO,oBAAC,QAAD;EAAM,WAAU;YAAyB;CAAiB,CAAA;CAElE,MAAM,SAAS,OAAe,MAC7B,SAAS;EAAE;EAAG,GAAG,EAAE;EAAS,GAAG,EAAE;CAAQ,CAAC;CAC3C,MAAM,UAAU,QAAQ,KAAK,MAAM,KAAK,KAAA;CACxC,OACC,qBAAC,OAAD;EAAK,WAAU;YAAf;GACC,oBAAC,aAAD,CAAc,CAAA;GACd,oBAAC,OAAD;IAAK,WAAW,iBAAiB,SAAS,SAAS,0BAA0B;cAC3E,KAAK,KAAK,KAAK,MACf,WACC,oBAAC,UAAD;KACC,WAAU;KAEV,eAAe,SAAS,CAAC;KACzB,gBAAgB,MAAM,CAAC;KACvB,sBAAsB,SAAS,IAAI;KACnC,eAAe,MAAM,CAAC;KACtB,MAAK;eAEL,oBAAC,YAAD,EAAiB,IAAM,CAAA;IAChB,GARF,IAAI,KAQF,IAER,oBAAC,OAAD;KACC,WAAU;KAEV,gBAAgB,MAAM,CAAC;KACvB,sBAAsB,SAAS,IAAI;KACnC,eAAe,MAAM,CAAC;eAEtB,oBAAC,YAAD,EAAiB,IAAM,CAAA;IACnB,GANC,IAAI,KAML,CAEP;GACI,CAAA;GACJ,SAAS,UACT,qBAAC,OAAD;IACC,WAAU;IACV,OAAO;KAAE,UAAU;KAAS,MAAM,MAAM;KAAG,KAAK,MAAM;IAAE;cAFzD,CAIC,oBAAC,OAAD;KAAK,WAAU;eAAkC,QAAQ;IAAW,CAAA,GACpE,oBAAC,OAAD;KAAK,WAAU;eAAkC,QAAQ,WAAW,QAAQ;IAAW,CAAA,CACnF;QACF;EACA;;AAEP"}
1
+ {"version":3,"file":"BarList.js","names":[],"sources":["../../src/charts/BarList.tsx"],"sourcesContent":["'use client'\n\nimport { type PointerEvent, type ReactNode, useState } from 'react'\nimport { type BarDatum, type BarRow, toBarRows } from './bars'\nimport { ChartStyles } from './styles'\n\nexport interface BarListProps {\n\tdata: BarDatum[]\n\temptyLabel: string\n\t/**\n\t * Makes every row a button reporting its index. Left out, rows are inert: a source that\n\t * cannot filter by the dimension must not offer a click that would do nothing.\n\t */\n\tonSelect?: (index: number) => void\n\t/**\n\t * `solid` (the default) fills the bar with the chart color and puts a white label inside\n\t * it, which reads as long as every row has a bar to sit on. `soft` pales the fill and\n\t * moves the label onto the elevation ramp, for a list whose rows can be zero-valued (a\n\t * goal with no pageviews), where a zero-width bar leaves a white label on bare track.\n\t */\n\tfill?: 'solid' | 'soft'\n}\n\ninterface Hover {\n\ti: number\n\tx: number\n\ty: number\n}\n\n/**\n * Ranked rows are identified by rank, since two can share a label: a provider that answers an\n * unattributed bucket as an empty string, or one that repeats a value. Keying on the label\n * alone made those collide, and React strands the duplicates in the DOM across a rerender.\n */\nconst rowKey = (row: BarRow, i: number): string => `${i}:${row.label}`\n\nconst RowContent = ({ row }: { row: BarRow }): ReactNode => (\n\t<>\n\t\t<span className=\"analytics-bars__track\">\n\t\t\t<span className=\"analytics-bars__fill\" style={{ width: `${row.fraction * 100}%` }} />\n\t\t\t<span className=\"analytics-bars__label\">{row.label}</span>\n\t\t</span>\n\t\t<span className=\"analytics-bars__value\">{row.display ?? row.value}</span>\n\t\t{row.secondary === undefined ? null : (\n\t\t\t<span className=\"analytics-bars__secondary\">{row.secondary}</span>\n\t\t)}\n\t</>\n)\n\n/**\n * Ranked horizontal bar list (shadcn \"custom label\" style): each row is a filled,\n * proportional bar with the label inside and the value outside; hovering a row lifts\n * it and shows a tooltip with the full label and value (useful when the label is\n * truncated). Dependency-free; styling comes from the shared chart stylesheet.\n */\nexport function BarList({ data, emptyLabel, onSelect, fill = 'solid' }: BarListProps) {\n\tconst rows = toBarRows(data)\n\tconst [hover, setHover] = useState<Hover | null>(null)\n\tif (rows.length === 0) {\n\t\treturn <span className=\"analytics-bars__empty\">{emptyLabel}</span>\n\t}\n\tconst track = (i: number) => (e: PointerEvent<HTMLElement>) =>\n\t\tsetHover({ i, x: e.clientX, y: e.clientY })\n\tconst hovered = hover ? rows[hover.i] : undefined\n\treturn (\n\t\t<div className=\"analytics-chart\">\n\t\t\t<ChartStyles />\n\t\t\t<div className={`analytics-bars${fill === 'soft' ? ' analytics-bars--soft' : ''}`}>\n\t\t\t\t{rows.map((row, i) =>\n\t\t\t\t\tonSelect ? (\n\t\t\t\t\t\t<button\n\t\t\t\t\t\t\tclassName=\"analytics-bars__row analytics-bars__row--action\"\n\t\t\t\t\t\t\tkey={rowKey(row, i)}\n\t\t\t\t\t\t\tonClick={() => onSelect(i)}\n\t\t\t\t\t\t\tonPointerEnter={track(i)}\n\t\t\t\t\t\t\tonPointerLeave={() => setHover(null)}\n\t\t\t\t\t\t\tonPointerMove={track(i)}\n\t\t\t\t\t\t\ttype=\"button\"\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t<RowContent row={row} />\n\t\t\t\t\t\t</button>\n\t\t\t\t\t) : (\n\t\t\t\t\t\t<div\n\t\t\t\t\t\t\tclassName=\"analytics-bars__row\"\n\t\t\t\t\t\t\tkey={rowKey(row, i)}\n\t\t\t\t\t\t\tonPointerEnter={track(i)}\n\t\t\t\t\t\t\tonPointerLeave={() => setHover(null)}\n\t\t\t\t\t\t\tonPointerMove={track(i)}\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t<RowContent row={row} />\n\t\t\t\t\t\t</div>\n\t\t\t\t\t)\n\t\t\t\t)}\n\t\t\t</div>\n\t\t\t{hover && hovered ? (\n\t\t\t\t<div\n\t\t\t\t\tclassName=\"analytics-chart__tooltip\"\n\t\t\t\t\tstyle={{ position: 'fixed', left: hover.x, top: hover.y }}\n\t\t\t\t>\n\t\t\t\t\t<div className=\"analytics-chart__tooltip-label\">{hovered.label}</div>\n\t\t\t\t\t<div className=\"analytics-chart__tooltip-value\">{hovered.display ?? hovered.value}</div>\n\t\t\t\t</div>\n\t\t\t) : null}\n\t\t</div>\n\t)\n}\n"],"mappings":";;;;;;;;;;;AAkCA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,OAAD;KACC,WAAU;KAEV,gBAAgB,MAAM,CAAC;KACvB,sBAAsB,SAAS,IAAI;KACnC,eAAe,MAAM,CAAC;eAEtB,oBAAC,YAAD,EAAiB,IAAM,CAAA;IACnB,GANC,OAAO,KAAK,CAAC,CAMd,CAEP;GACI,CAAA;GACJ,SAAS,UACT,qBAAC,OAAD;IACC,WAAU;IACV,OAAO;KAAE,UAAU;KAAS,MAAM,MAAM;KAAG,KAAK,MAAM;IAAE;cAFzD,CAIC,oBAAC,OAAD;KAAK,WAAU;eAAkC,QAAQ;IAAW,CAAA,GACpE,oBAAC,OAAD;KAAK,WAAU;eAAkC,QAAQ,WAAW,QAAQ;IAAW,CAAA,CACnF;QACF;EACA;;AAEP"}
@@ -13,6 +13,15 @@ const rangeKey = (range, tz) => {
13
13
  if (nextDay.getTime() - 1 === range.end.getTime()) return `${range.start.toISOString()}_${range.end.toISOString()}`;
14
14
  return `${startOfDayInTz(range.start, tz).toISOString()}_${nextDay.toISOString()}`;
15
15
  };
16
+ /**
17
+ * The goal segment, absent for a read with no hint and for an install with no goals, which
18
+ * both ask the provider for the same rows. The failed-resolver segment carries a `!`, which
19
+ * `GOAL_SLUG_PATTERN` forbids, so no list of slugs can be written to look like it.
20
+ */
21
+ const goalKey = (goalSlugs) => {
22
+ if (goalSlugs === "unresolved") return ["goals:!unresolved"];
23
+ return goalSlugs?.length ? [`goals:${stable(goalSlugs)}`] : [];
24
+ };
16
25
  function buildCacheKey(provider, q) {
17
26
  const pathKey = q.path ?? "site";
18
27
  const tz = q.timezone ?? "UTC";
@@ -31,7 +40,8 @@ function buildCacheKey(provider, q) {
31
40
  String(q.limit ?? "_"),
32
41
  q.order ? `${q.order.metric}:${q.order.direction}` : "_",
33
42
  ...q.timezone !== void 0 && q.timezone !== "UTC" ? [q.timezone] : [],
34
- ...q.scope !== void 0 ? [encodeURIComponent(q.scope)] : []
43
+ ...q.scope !== void 0 ? [encodeURIComponent(q.scope)] : [],
44
+ ...goalKey(q.goalSlugs)
35
45
  ].join("|");
36
46
  }
37
47
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"cacheKey.js","names":[],"sources":["../../src/core/cacheKey.ts"],"sourcesContent":["import { addDaysInTz, DEFAULT_TIMEZONE, startOfDayInTz } from '../timeframe/tz'\nimport type { AnalyticsQuery } from './contract'\n\nconst stable = (xs?: string[]): string => (xs ? [...xs].sort().join(',') : '')\n\n/**\n * The window segment. A live window (a preset ends at `now`) snaps to whole days, so every\n * render within one day shares one entry. A closed window, whose end is the final instant\n * of its day in `tz`, keys on its exact bounds instead: snapping those too would let two\n * windows that differ only inside their last day share an entry, and an instant-comparing\n * adapter read the narrower one's answer.\n */\nconst rangeKey = (range: AnalyticsQuery['dateRange'], tz: string): string => {\n\tconst nextDay = addDaysInTz(range.end, 1, tz)\n\tif (nextDay.getTime() - 1 === range.end.getTime()) {\n\t\treturn `${range.start.toISOString()}_${range.end.toISOString()}`\n\t}\n\treturn `${startOfDayInTz(range.start, tz).toISOString()}_${nextDay.toISOString()}`\n}\n\nexport function buildCacheKey(provider: string, q: AnalyticsQuery): string {\n\tconst pathKey = q.path ?? 'site'\n\tconst tz = q.timezone ?? DEFAULT_TIMEZONE\n\tconst range = rangeKey(q.dateRange, tz)\n\tconst filters = (q.filters ?? [])\n\t\t.map((f) => `${f.dimension}${f.operator}${f.value}`)\n\t\t.sort()\n\t\t.join(';')\n\treturn [\n\t\t'analytics',\n\t\tprovider,\n\t\tq.hostname ?? '_',\n\t\tpathKey,\n\t\tstable(q.metrics),\n\t\tstable(q.dimensions),\n\t\trange,\n\t\tq.granularity ?? '_',\n\t\tfilters,\n\t\tString(q.limit ?? '_'),\n\t\tq.order ? `${q.order.metric}:${q.order.direction}` : '_',\n\t\t// Appended only for a non-UTC timezone so default (UTC) keys keep their format.\n\t\t...(q.timezone !== undefined && q.timezone !== DEFAULT_TIMEZONE ? [q.timezone] : []),\n\t\t...(q.scope !== undefined ? [encodeURIComponent(q.scope)] : []),\n\t].join('|')\n}\n"],"mappings":";;AAGA,MAAM,UAAU,OAA2B,KAAK,CAAC,GAAG,EAAE,EAAE,KAAK,EAAE,KAAK,GAAG,IAAI;;;;;;;;AAS3E,MAAM,YAAY,OAAoC,OAAuB;CAC5E,MAAM,UAAU,YAAY,MAAM,KAAK,GAAG,EAAE;CAC5C,IAAI,QAAQ,QAAQ,IAAI,MAAM,MAAM,IAAI,QAAQ,GAC/C,OAAO,GAAG,MAAM,MAAM,YAAY,EAAE,GAAG,MAAM,IAAI,YAAY;CAE9D,OAAO,GAAG,eAAe,MAAM,OAAO,EAAE,EAAE,YAAY,EAAE,GAAG,QAAQ,YAAY;AAChF;AAEA,SAAgB,cAAc,UAAkB,GAA2B;CAC1E,MAAM,UAAU,EAAE,QAAQ;CAC1B,MAAM,KAAK,EAAE,YAAA;CACb,MAAM,QAAQ,SAAS,EAAE,WAAW,EAAE;CACtC,MAAM,WAAW,EAAE,WAAW,CAAC,GAC7B,KAAK,MAAM,GAAG,EAAE,YAAY,EAAE,WAAW,EAAE,OAAO,EAClD,KAAK,EACL,KAAK,GAAG;CACV,OAAO;EACN;EACA;EACA,EAAE,YAAY;EACd;EACA,OAAO,EAAE,OAAO;EAChB,OAAO,EAAE,UAAU;EACnB;EACA,EAAE,eAAe;EACjB;EACA,OAAO,EAAE,SAAS,GAAG;EACrB,EAAE,QAAQ,GAAG,EAAE,MAAM,OAAO,GAAG,EAAE,MAAM,cAAc;EAErD,GAAI,EAAE,aAAa,KAAA,KAAa,EAAE,aAAA,QAAgC,CAAC,EAAE,QAAQ,IAAI,CAAC;EAClF,GAAI,EAAE,UAAU,KAAA,IAAY,CAAC,mBAAmB,EAAE,KAAK,CAAC,IAAI,CAAC;CAC9D,EAAE,KAAK,GAAG;AACX"}
1
+ {"version":3,"file":"cacheKey.js","names":[],"sources":["../../src/core/cacheKey.ts"],"sourcesContent":["import { addDaysInTz, DEFAULT_TIMEZONE, startOfDayInTz } from '../timeframe/tz'\nimport type { AnalyticsQuery } from './contract'\n\nconst stable = (xs?: string[]): string => (xs ? [...xs].sort().join(',') : '')\n\n/**\n * The window segment. A live window (a preset ends at `now`) snaps to whole days, so every\n * render within one day shares one entry. A closed window, whose end is the final instant\n * of its day in `tz`, keys on its exact bounds instead: snapping those too would let two\n * windows that differ only inside their last day share an entry, and an instant-comparing\n * adapter read the narrower one's answer.\n */\nconst rangeKey = (range: AnalyticsQuery['dateRange'], tz: string): string => {\n\tconst nextDay = addDaysInTz(range.end, 1, tz)\n\tif (nextDay.getTime() - 1 === range.end.getTime()) {\n\t\treturn `${range.start.toISOString()}_${range.end.toISOString()}`\n\t}\n\treturn `${startOfDayInTz(range.start, tz).toISOString()}_${nextDay.toISOString()}`\n}\n\n/**\n * The goal segment, absent for a read with no hint and for an install with no goals, which\n * both ask the provider for the same rows. The failed-resolver segment carries a `!`, which\n * `GOAL_SLUG_PATTERN` forbids, so no list of slugs can be written to look like it.\n */\nconst goalKey = (goalSlugs: AnalyticsQuery['goalSlugs']): string[] => {\n\tif (goalSlugs === 'unresolved') {\n\t\treturn ['goals:!unresolved']\n\t}\n\treturn goalSlugs?.length ? [`goals:${stable(goalSlugs)}`] : []\n}\n\nexport function buildCacheKey(provider: string, q: AnalyticsQuery): string {\n\tconst pathKey = q.path ?? 'site'\n\tconst tz = q.timezone ?? DEFAULT_TIMEZONE\n\tconst range = rangeKey(q.dateRange, tz)\n\tconst filters = (q.filters ?? [])\n\t\t.map((f) => `${f.dimension}${f.operator}${f.value}`)\n\t\t.sort()\n\t\t.join(';')\n\treturn [\n\t\t'analytics',\n\t\tprovider,\n\t\tq.hostname ?? '_',\n\t\tpathKey,\n\t\tstable(q.metrics),\n\t\tstable(q.dimensions),\n\t\trange,\n\t\tq.granularity ?? '_',\n\t\tfilters,\n\t\tString(q.limit ?? '_'),\n\t\tq.order ? `${q.order.metric}:${q.order.direction}` : '_',\n\t\t// Appended only for a non-UTC timezone so default (UTC) keys keep their format.\n\t\t...(q.timezone !== undefined && q.timezone !== DEFAULT_TIMEZONE ? [q.timezone] : []),\n\t\t...(q.scope !== undefined ? [encodeURIComponent(q.scope)] : []),\n\t\t// A provider read restricts its goal rows to the hint, so two hints answer differently\n\t\t// and must never share an entry. A failed resolver keys on its own segment rather than\n\t\t// on the healthy no-hint key. Prefixed, so the segment cannot read as a scope.\n\t\t...goalKey(q.goalSlugs),\n\t].join('|')\n}\n"],"mappings":";;AAGA,MAAM,UAAU,OAA2B,KAAK,CAAC,GAAG,EAAE,EAAE,KAAK,EAAE,KAAK,GAAG,IAAI;;;;;;;;AAS3E,MAAM,YAAY,OAAoC,OAAuB;CAC5E,MAAM,UAAU,YAAY,MAAM,KAAK,GAAG,EAAE;CAC5C,IAAI,QAAQ,QAAQ,IAAI,MAAM,MAAM,IAAI,QAAQ,GAC/C,OAAO,GAAG,MAAM,MAAM,YAAY,EAAE,GAAG,MAAM,IAAI,YAAY;CAE9D,OAAO,GAAG,eAAe,MAAM,OAAO,EAAE,EAAE,YAAY,EAAE,GAAG,QAAQ,YAAY;AAChF;;;;;;AAOA,MAAM,WAAW,cAAqD;CACrE,IAAI,cAAc,cACjB,OAAO,CAAC,mBAAmB;CAE5B,OAAO,WAAW,SAAS,CAAC,SAAS,OAAO,SAAS,GAAG,IAAI,CAAC;AAC9D;AAEA,SAAgB,cAAc,UAAkB,GAA2B;CAC1E,MAAM,UAAU,EAAE,QAAQ;CAC1B,MAAM,KAAK,EAAE,YAAA;CACb,MAAM,QAAQ,SAAS,EAAE,WAAW,EAAE;CACtC,MAAM,WAAW,EAAE,WAAW,CAAC,GAC7B,KAAK,MAAM,GAAG,EAAE,YAAY,EAAE,WAAW,EAAE,OAAO,EAClD,KAAK,EACL,KAAK,GAAG;CACV,OAAO;EACN;EACA;EACA,EAAE,YAAY;EACd;EACA,OAAO,EAAE,OAAO;EAChB,OAAO,EAAE,UAAU;EACnB;EACA,EAAE,eAAe;EACjB;EACA,OAAO,EAAE,SAAS,GAAG;EACrB,EAAE,QAAQ,GAAG,EAAE,MAAM,OAAO,GAAG,EAAE,MAAM,cAAc;EAErD,GAAI,EAAE,aAAa,KAAA,KAAa,EAAE,aAAA,QAAgC,CAAC,EAAE,QAAQ,IAAI,CAAC;EAClF,GAAI,EAAE,UAAU,KAAA,IAAY,CAAC,mBAAmB,EAAE,KAAK,CAAC,IAAI,CAAC;EAI7D,GAAG,QAAQ,EAAE,SAAS;CACvB,EAAE,KAAK,GAAG;AACX"}
@@ -8,6 +8,11 @@ function satisfiesCapabilities(caps, req) {
8
8
  if (req.filterOperators?.some((op) => !caps.filterOperators.has(op))) return false;
9
9
  return true;
10
10
  }
11
+ /**
12
+ * Whether a source compares against its previous period. The engine does that read
13
+ * generically, so it is on unless an adapter opted out.
14
+ */
15
+ const comparisonOf = (caps) => caps.comparison ?? true;
11
16
  const serializeCapabilities = (caps) => ({
12
17
  metrics: [...caps.metrics],
13
18
  dimensions: [...caps.dimensions],
@@ -16,11 +21,11 @@ const serializeCapabilities = (caps) => ({
16
21
  realtime: caps.realtime,
17
22
  ...caps.realtimeWindowMinutes !== void 0 ? { realtimeWindowMinutes: caps.realtimeWindowMinutes } : {},
18
23
  perPageQuery: caps.perPageQuery,
19
- comparison: caps.comparison,
24
+ comparison: comparisonOf(caps),
20
25
  minGranularity: caps.minGranularity,
21
26
  maxLookbackDays: caps.maxLookbackDays
22
27
  });
23
28
  //#endregion
24
- export { satisfiesCapabilities, serializeCapabilities };
29
+ export { comparisonOf, satisfiesCapabilities, serializeCapabilities };
25
30
 
26
31
  //# sourceMappingURL=capabilities.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"capabilities.js","names":[],"sources":["../../src/core/capabilities.ts"],"sourcesContent":["import type {\n\tAnalyticsCapabilities,\n\tDimensionKey,\n\tFilterOperator,\n\tGranularity,\n\tMetricKey,\n} from './contract'\n\nexport interface CapabilityRequirement {\n\tmetrics?: MetricKey[]\n\tdimensions?: DimensionKey[]\n\tfilters?: DimensionKey[]\n\tfilterOperators?: FilterOperator[]\n\trealtime?: boolean\n\tperPageQuery?: boolean\n}\n\nexport function satisfiesCapabilities(\n\tcaps: AnalyticsCapabilities,\n\treq: CapabilityRequirement\n): boolean {\n\tif (req.realtime && !caps.realtime) return false\n\tif (req.perPageQuery && !caps.perPageQuery) return false\n\tif (req.metrics?.some((m) => !caps.metrics.has(m))) return false\n\tif (req.dimensions?.some((d) => !caps.dimensions.has(d))) return false\n\tif (req.filters?.some((d) => !caps.filters.has(d))) return false\n\tif (req.filterOperators?.some((op) => !caps.filterOperators.has(op))) return false\n\treturn true\n}\n\n/** Wire form of AnalyticsCapabilities for client pickers: a deliberate allowlist, so adapter internals (rate limits, TTLs) never become client contract by accident. */\nexport type SerializedCapabilities = {\n\tmetrics: MetricKey[]\n\tdimensions: DimensionKey[]\n\tfilters: DimensionKey[]\n\tfilterOperators: FilterOperator[]\n\trealtime: boolean\n\trealtimeWindowMinutes?: number\n\tperPageQuery: boolean\n\tcomparison: boolean\n\tminGranularity: Granularity\n\tmaxLookbackDays: number | null\n}\n\nexport const serializeCapabilities = (caps: AnalyticsCapabilities): SerializedCapabilities => ({\n\tmetrics: [...caps.metrics],\n\tdimensions: [...caps.dimensions],\n\tfilters: [...caps.filters],\n\tfilterOperators: [...caps.filterOperators],\n\trealtime: caps.realtime,\n\t...(caps.realtimeWindowMinutes !== undefined\n\t\t? { realtimeWindowMinutes: caps.realtimeWindowMinutes }\n\t\t: {}),\n\tperPageQuery: caps.perPageQuery,\n\tcomparison: caps.comparison,\n\tminGranularity: caps.minGranularity,\n\tmaxLookbackDays: caps.maxLookbackDays,\n})\n"],"mappings":";AAiBA,SAAgB,sBACf,MACA,KACU;CACV,IAAI,IAAI,YAAY,CAAC,KAAK,UAAU,OAAO;CAC3C,IAAI,IAAI,gBAAgB,CAAC,KAAK,cAAc,OAAO;CACnD,IAAI,IAAI,SAAS,MAAM,MAAM,CAAC,KAAK,QAAQ,IAAI,CAAC,CAAC,GAAG,OAAO;CAC3D,IAAI,IAAI,YAAY,MAAM,MAAM,CAAC,KAAK,WAAW,IAAI,CAAC,CAAC,GAAG,OAAO;CACjE,IAAI,IAAI,SAAS,MAAM,MAAM,CAAC,KAAK,QAAQ,IAAI,CAAC,CAAC,GAAG,OAAO;CAC3D,IAAI,IAAI,iBAAiB,MAAM,OAAO,CAAC,KAAK,gBAAgB,IAAI,EAAE,CAAC,GAAG,OAAO;CAC7E,OAAO;AACR;AAgBA,MAAa,yBAAyB,UAAyD;CAC9F,SAAS,CAAC,GAAG,KAAK,OAAO;CACzB,YAAY,CAAC,GAAG,KAAK,UAAU;CAC/B,SAAS,CAAC,GAAG,KAAK,OAAO;CACzB,iBAAiB,CAAC,GAAG,KAAK,eAAe;CACzC,UAAU,KAAK;CACf,GAAI,KAAK,0BAA0B,KAAA,IAChC,EAAE,uBAAuB,KAAK,sBAAsB,IACpD,CAAC;CACJ,cAAc,KAAK;CACnB,YAAY,KAAK;CACjB,gBAAgB,KAAK;CACrB,iBAAiB,KAAK;AACvB"}
1
+ {"version":3,"file":"capabilities.js","names":[],"sources":["../../src/core/capabilities.ts"],"sourcesContent":["import type {\n\tAnalyticsCapabilities,\n\tDimensionKey,\n\tFilterOperator,\n\tGranularity,\n\tMetricKey,\n} from './contract'\n\nexport interface CapabilityRequirement {\n\tmetrics?: MetricKey[]\n\tdimensions?: DimensionKey[]\n\tfilters?: DimensionKey[]\n\tfilterOperators?: FilterOperator[]\n\trealtime?: boolean\n\tperPageQuery?: boolean\n}\n\nexport function satisfiesCapabilities(\n\tcaps: AnalyticsCapabilities,\n\treq: CapabilityRequirement\n): boolean {\n\tif (req.realtime && !caps.realtime) return false\n\tif (req.perPageQuery && !caps.perPageQuery) return false\n\tif (req.metrics?.some((m) => !caps.metrics.has(m))) return false\n\tif (req.dimensions?.some((d) => !caps.dimensions.has(d))) return false\n\tif (req.filters?.some((d) => !caps.filters.has(d))) return false\n\tif (req.filterOperators?.some((op) => !caps.filterOperators.has(op))) return false\n\treturn true\n}\n\n/**\n * Whether a source compares against its previous period. The engine does that read\n * generically, so it is on unless an adapter opted out.\n */\nexport const comparisonOf = (caps: AnalyticsCapabilities): boolean => caps.comparison ?? true\n\n/** Wire form of AnalyticsCapabilities for client pickers: a deliberate allowlist, so adapter internals (rate limits, TTLs) never become client contract by accident. */\nexport type SerializedCapabilities = {\n\tmetrics: MetricKey[]\n\tdimensions: DimensionKey[]\n\tfilters: DimensionKey[]\n\tfilterOperators: FilterOperator[]\n\trealtime: boolean\n\trealtimeWindowMinutes?: number\n\tperPageQuery: boolean\n\tcomparison: boolean\n\tminGranularity: Granularity\n\tmaxLookbackDays: number | null\n}\n\nexport const serializeCapabilities = (caps: AnalyticsCapabilities): SerializedCapabilities => ({\n\tmetrics: [...caps.metrics],\n\tdimensions: [...caps.dimensions],\n\tfilters: [...caps.filters],\n\tfilterOperators: [...caps.filterOperators],\n\trealtime: caps.realtime,\n\t...(caps.realtimeWindowMinutes !== undefined\n\t\t? { realtimeWindowMinutes: caps.realtimeWindowMinutes }\n\t\t: {}),\n\tperPageQuery: caps.perPageQuery,\n\tcomparison: comparisonOf(caps),\n\tminGranularity: caps.minGranularity,\n\tmaxLookbackDays: caps.maxLookbackDays,\n})\n"],"mappings":";AAiBA,SAAgB,sBACf,MACA,KACU;CACV,IAAI,IAAI,YAAY,CAAC,KAAK,UAAU,OAAO;CAC3C,IAAI,IAAI,gBAAgB,CAAC,KAAK,cAAc,OAAO;CACnD,IAAI,IAAI,SAAS,MAAM,MAAM,CAAC,KAAK,QAAQ,IAAI,CAAC,CAAC,GAAG,OAAO;CAC3D,IAAI,IAAI,YAAY,MAAM,MAAM,CAAC,KAAK,WAAW,IAAI,CAAC,CAAC,GAAG,OAAO;CACjE,IAAI,IAAI,SAAS,MAAM,MAAM,CAAC,KAAK,QAAQ,IAAI,CAAC,CAAC,GAAG,OAAO;CAC3D,IAAI,IAAI,iBAAiB,MAAM,OAAO,CAAC,KAAK,gBAAgB,IAAI,EAAE,CAAC,GAAG,OAAO;CAC7E,OAAO;AACR;;;;;AAMA,MAAa,gBAAgB,SAAyC,KAAK,cAAc;AAgBzF,MAAa,yBAAyB,UAAyD;CAC9F,SAAS,CAAC,GAAG,KAAK,OAAO;CACzB,YAAY,CAAC,GAAG,KAAK,UAAU;CAC/B,SAAS,CAAC,GAAG,KAAK,OAAO;CACzB,iBAAiB,CAAC,GAAG,KAAK,eAAe;CACzC,UAAU,KAAK;CACf,GAAI,KAAK,0BAA0B,KAAA,IAChC,EAAE,uBAAuB,KAAK,sBAAsB,IACpD,CAAC;CACJ,cAAc,KAAK;CACnB,YAAY,aAAa,IAAI;CAC7B,gBAAgB,KAAK;CACrB,iBAAiB,KAAK;AACvB"}
@@ -28,7 +28,7 @@ interface SnippetScript {
28
28
  interface CaptureSnippet {
29
29
  scripts: SnippetScript[];
30
30
  }
31
- type CaptureClientKind = 'native' | 'posthog' | 'plausible' | 'umami';
31
+ type CaptureClientKind = 'native' | 'posthog' | 'plausible' | 'umami' | 'ga4';
32
32
  /**
33
33
  * Pure descriptor of how a vendor's browser tracker is proxied and booted, consumed by
34
34
  * a later runtime proxy endpoint, a Next rewrites helper, and a snippet renderer. Never
@@ -52,6 +52,16 @@ interface AnalyticsQuery {
52
52
  * others report in their own account timezone. Part of the cache key when set.
53
53
  */
54
54
  timezone?: string;
55
+ /**
56
+ * The scope's goal slugs, set by callers that ask for the `goal` dimension or the
57
+ * `conversions` metric, and possibly empty when the scope configures no goals. Provider
58
+ * adapters restrict goal rows to it, since nothing in a provider marks which of its
59
+ * events are this install's goals; the native engine ignores it and matches completions
60
+ * itself. `'unresolved'` is the sentinel for a goal resolver that failed: the read keeps
61
+ * its site numbers, reports `goalsUnresolved`, and never shares a healthy cache key.
62
+ * Part of the surfacing cache key when set.
63
+ */
64
+ goalSlugs?: string[] | 'unresolved';
55
65
  }
56
66
  interface AnalyticsRow {
57
67
  dimensions?: Partial<Record<DimensionKey, string>>;
@@ -67,8 +77,24 @@ interface AnalyticsResult {
67
77
  clamped?: boolean;
68
78
  fetchedAt: string; /** Served from an expired cache entry because the live refresh failed. */
69
79
  stale?: boolean;
80
+ /**
81
+ * Filters the source could not carry, so the rows are wider than the query asked for.
82
+ * A provider whose API takes one value per dimension reports the ones it dropped here.
83
+ */
84
+ unappliedFilters?: AnalyticsFilter[];
85
+ /**
86
+ * The read's goal numbers are absent because resolving them failed: it ran without
87
+ * `AnalyticsQuery.goalSlugs`, or with `'unresolved'`, or the provider rejected the goal
88
+ * request and the rest of the read was served without it. A scope that configured no
89
+ * goals is an empty result instead, not this flag.
90
+ */
91
+ goalsUnresolved?: true;
70
92
  };
71
93
  }
94
+ /**
95
+ * A read carrying conversions costs a provider up to twice the requests: the goal numbers
96
+ * come from a second, goal-filtered request the adapter issues after the plain one.
97
+ */
72
98
  interface RateLimitDescriptor {
73
99
  requestsPerMinute?: number;
74
100
  requestsPerHour?: number;
@@ -85,7 +111,11 @@ interface AnalyticsCapabilities {
85
111
  perPageQuery: boolean;
86
112
  realtime: boolean;
87
113
  realtimeWindowMinutes?: number;
88
- comparison: boolean;
114
+ /**
115
+ * Period-over-period comparison, which the engine serves for every source by reading the
116
+ * previous window itself. Adapters omit this; set it false only to opt a source out.
117
+ */
118
+ comparison?: boolean;
89
119
  minGranularity: Granularity;
90
120
  maxLookbackDays: number | null;
91
121
  metrics: ReadonlySet<MetricKey>;
@@ -133,7 +163,7 @@ interface AnalyticsAdapter {
133
163
  readonly id: string;
134
164
  readonly label: string;
135
165
  readonly capabilities: AnalyticsCapabilities;
136
- /** Browser-tracker proxying/boot descriptor. Absent when the adapter has no client-side script (GA4). */
166
+ /** Browser-tracker proxying/boot descriptor. Absent when no public capture field is set. */
137
167
  readonly capture?: CaptureSupport;
138
168
  /**
139
169
  * Where this adapter's own ingest endpoint listens, relative to `routes.api`, for the
@@ -1 +1 @@
1
- {"version":3,"file":"contract.js","names":[],"sources":["../../src/core/contract.ts"],"sourcesContent":["import type { Config, PayloadRequest } from 'payload'\nimport type { Goal } from '../goals/types'\nimport type { CaptureSupport } from './capture'\nimport type { ServerTrack } from './serverEvent'\n\n/**\n * Explicit cross-scope read marker: pass as a read's `scope` to aggregate over every\n * scope. Gated by `access.platformRead`; the query reaches the adapter unscoped.\n */\nexport const PLATFORM_SCOPE = '*'\n\nexport type MetricKey =\n\t| 'pageviews'\n\t| 'visitors'\n\t| 'visits'\n\t| 'sessions'\n\t| 'bounceRate'\n\t| 'avgDuration'\n\t| 'scrollDepth'\n\t| 'events'\n\t| 'conversions'\n\t| 'revenue'\n\n/** Every breakdown key the contract defines; the registry request parsers validate against. */\nexport const DIMENSION_KEYS = [\n\t'page',\n\t'referrer',\n\t'source',\n\t'medium',\n\t'campaign',\n\t'utmSource',\n\t'utmMedium',\n\t'utmCampaign',\n\t'utmContent',\n\t'utmTerm',\n\t'device',\n\t'browser',\n\t'os',\n\t'country',\n\t'region',\n\t'city',\n\t'language',\n\t'event',\n\t'goal',\n] as const\n\nexport type DimensionKey = (typeof DIMENSION_KEYS)[number]\n\nexport type Granularity = 'minute' | 'hour' | 'day' | 'week' | 'month'\n\nexport interface DateRange {\n\tstart: Date\n\tend: Date\n}\n\n/** Every filter operator the contract defines; the registry request parsers validate against. */\nexport const FILTER_OPERATORS = ['eq', 'contains', 'matches'] as const\n\nexport type FilterOperator = (typeof FILTER_OPERATORS)[number]\n\nexport interface AnalyticsFilter {\n\tdimension: DimensionKey\n\toperator: FilterOperator\n\tvalue: string\n}\n\nexport interface AnalyticsQuery {\n\tpath?: string\n\thostname?: string\n\tmetrics: MetricKey[]\n\tdimensions?: DimensionKey[]\n\tdateRange: DateRange\n\tgranularity?: Granularity\n\tfilters?: AnalyticsFilter[]\n\tlimit?: number\n\torder?: { metric: MetricKey; direction: 'asc' | 'desc' }\n\t/**\n\t * Analytics boundary this read belongs to (tenant id, site key). Undefined means\n\t * install-wide (the default). Adapters that can filter by scope apply it; others\n\t * ignore it. Always part of the surfacing cache key, so per-scope adapter\n\t * instances sharing an id never share cached results.\n\t */\n\tscope?: string\n\t/**\n\t * IANA reporting timezone the read's day boundaries are aligned to. Undefined\n\t * means UTC. Adapters that can bucket in a timezone apply it (PostHog, Umami);\n\t * others report in their own account timezone. Part of the cache key when set.\n\t */\n\ttimezone?: string\n}\n\nexport interface AnalyticsRow {\n\tdimensions?: Partial<Record<DimensionKey, string>>\n\tmetrics: Partial<Record<MetricKey, number>>\n\ttimestamp?: string\n}\n\nexport interface AnalyticsResult {\n\trows: AnalyticsRow[]\n\ttotals?: Partial<Record<MetricKey, number>>\n\tmeta: {\n\t\tprovider: string\n\t\tsampled?: boolean\n\t\tclamped?: boolean\n\t\tfetchedAt: string\n\t\t/** Served from an expired cache entry because the live refresh failed. */\n\t\tstale?: boolean\n\t}\n}\n\nexport interface RateLimitDescriptor {\n\trequestsPerMinute?: number\n\trequestsPerHour?: number\n\tmaxConcurrent?: number\n\t/**\n\t * Describes the provider's quota model for documentation; the limiter always\n\t * throttles by request count regardless of this value.\n\t */\n\tquotaModel?: 'requests' | 'tokens'\n\t/** Documents whether reads consume the provider's write/ingest quota too. */\n\treadsCountAsUsage?: boolean\n}\n\nexport interface AnalyticsCapabilities {\n\tperPageQuery: boolean\n\trealtime: boolean\n\trealtimeWindowMinutes?: number\n\tcomparison: boolean\n\tminGranularity: Granularity\n\tmaxLookbackDays: number | null\n\tmetrics: ReadonlySet<MetricKey>\n\tdimensions: ReadonlySet<DimensionKey>\n\t/** Dimensions the adapter can apply AnalyticsQuery.filters on; empty = filters unsupported. */\n\tfilters: ReadonlySet<DimensionKey>\n\t/** Operators the adapter honors in filters; adapters ignore filters whose operator they lack. */\n\tfilterOperators: ReadonlySet<FilterOperator>\n\tbatchPageReport: boolean\n\trateLimit: RateLimitDescriptor | null\n\trecommendedTtl: { realtime: number; aggregate: number }\n\t/**\n\t * The adapter applies `AnalyticsQuery.scope` as a provider-native filter (native\n\t * scope column, PostHog `scopeProperty`, ...). Without it, a scoped read through\n\t * a shared platform adapter would expose cross-scope data, so such reads are\n\t * gated by `access.platformRead`.\n\t */\n\tscopedQueries?: boolean\n}\n\nexport interface AdapterContext {\n\tsignal?: AbortSignal\n}\n\n/** Extra context the plugin hands adapters when they register config surface. */\nexport interface AdapterRegisterContext {\n\t/** True when the plugin has a scopeResolver configured. */\n\tscoped: boolean\n\t/** The plugin's scopeResolver bound for adapter use (e.g. ingest stamping). */\n\tresolveScope: (req: PayloadRequest) => Promise<string | null>\n\t/**\n\t * The plugin's reportingTimezone bound for adapter use (e.g. bucketing native\n\t * rollups at ingest). Resolves to `'UTC'` when no reportingTimezone is set.\n\t */\n\tresolveTimezone: (req: PayloadRequest, scope?: string | null) => Promise<string>\n\t/**\n\t * The install's goals for a request's scope, for adapters that match completions\n\t * themselves (the native engine, at ingest). Config goals, with the goals collection\n\t * merged over them per scope once the install enables it.\n\t */\n\tresolveGoals: (req: PayloadRequest, scope?: string | null) => Promise<Goal[]>\n}\n\nexport interface AnalyticsAdapter {\n\treadonly id: string\n\treadonly label: string\n\treadonly capabilities: AnalyticsCapabilities\n\t/** Browser-tracker proxying/boot descriptor. Absent when the adapter has no client-side script (GA4). */\n\treadonly capture?: CaptureSupport\n\t/**\n\t * Where this adapter's own ingest endpoint listens, relative to `routes.api`, for the\n\t * adapters that register one (the native engine), and how server code reaches the same\n\t * pipeline without an HTTP round trip. Server-side only: the tracker learns the path\n\t * from `TrackerConfig.ingestPath`, and this object is never serialized.\n\t */\n\treadonly ingest?: { path: string; track?: ServerTrack }\n\tisConfigured(): boolean\n\tquery(query: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult>\n\trealtime?(query: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult>\n\tregister?(config: Config, context?: AdapterRegisterContext): void\n}\n\nexport type AnalyticsAdapterFactory<Config> = (config: Config) => AnalyticsAdapter\n"],"mappings":";;;;;AASA,MAAa,iBAAiB;;AAe9B,MAAa,iBAAiB;CAC7B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD;;AAYA,MAAa,mBAAmB;CAAC;CAAM;CAAY;AAAS"}
1
+ {"version":3,"file":"contract.js","names":[],"sources":["../../src/core/contract.ts"],"sourcesContent":["import type { Config, PayloadRequest } from 'payload'\nimport type { Goal } from '../goals/types'\nimport type { CaptureSupport } from './capture'\nimport type { ServerTrack } from './serverEvent'\n\n/**\n * Explicit cross-scope read marker: pass as a read's `scope` to aggregate over every\n * scope. Gated by `access.platformRead`; the query reaches the adapter unscoped.\n */\nexport const PLATFORM_SCOPE = '*'\n\nexport type MetricKey =\n\t| 'pageviews'\n\t| 'visitors'\n\t| 'visits'\n\t| 'sessions'\n\t| 'bounceRate'\n\t| 'avgDuration'\n\t| 'scrollDepth'\n\t| 'events'\n\t| 'conversions'\n\t| 'revenue'\n\n/** Every breakdown key the contract defines; the registry request parsers validate against. */\nexport const DIMENSION_KEYS = [\n\t'page',\n\t'referrer',\n\t'source',\n\t'medium',\n\t'campaign',\n\t'utmSource',\n\t'utmMedium',\n\t'utmCampaign',\n\t'utmContent',\n\t'utmTerm',\n\t'device',\n\t'browser',\n\t'os',\n\t'country',\n\t'region',\n\t'city',\n\t'language',\n\t'event',\n\t'goal',\n] as const\n\nexport type DimensionKey = (typeof DIMENSION_KEYS)[number]\n\nexport type Granularity = 'minute' | 'hour' | 'day' | 'week' | 'month'\n\nexport interface DateRange {\n\tstart: Date\n\tend: Date\n}\n\n/** Every filter operator the contract defines; the registry request parsers validate against. */\nexport const FILTER_OPERATORS = ['eq', 'contains', 'matches'] as const\n\nexport type FilterOperator = (typeof FILTER_OPERATORS)[number]\n\nexport interface AnalyticsFilter {\n\tdimension: DimensionKey\n\toperator: FilterOperator\n\tvalue: string\n}\n\nexport interface AnalyticsQuery {\n\tpath?: string\n\thostname?: string\n\tmetrics: MetricKey[]\n\tdimensions?: DimensionKey[]\n\tdateRange: DateRange\n\tgranularity?: Granularity\n\tfilters?: AnalyticsFilter[]\n\tlimit?: number\n\torder?: { metric: MetricKey; direction: 'asc' | 'desc' }\n\t/**\n\t * Analytics boundary this read belongs to (tenant id, site key). Undefined means\n\t * install-wide (the default). Adapters that can filter by scope apply it; others\n\t * ignore it. Always part of the surfacing cache key, so per-scope adapter\n\t * instances sharing an id never share cached results.\n\t */\n\tscope?: string\n\t/**\n\t * IANA reporting timezone the read's day boundaries are aligned to. Undefined\n\t * means UTC. Adapters that can bucket in a timezone apply it (PostHog, Umami);\n\t * others report in their own account timezone. Part of the cache key when set.\n\t */\n\ttimezone?: string\n\t/**\n\t * The scope's goal slugs, set by callers that ask for the `goal` dimension or the\n\t * `conversions` metric, and possibly empty when the scope configures no goals. Provider\n\t * adapters restrict goal rows to it, since nothing in a provider marks which of its\n\t * events are this install's goals; the native engine ignores it and matches completions\n\t * itself. `'unresolved'` is the sentinel for a goal resolver that failed: the read keeps\n\t * its site numbers, reports `goalsUnresolved`, and never shares a healthy cache key.\n\t * Part of the surfacing cache key when set.\n\t */\n\tgoalSlugs?: string[] | 'unresolved'\n}\n\nexport interface AnalyticsRow {\n\tdimensions?: Partial<Record<DimensionKey, string>>\n\tmetrics: Partial<Record<MetricKey, number>>\n\ttimestamp?: string\n}\n\nexport interface AnalyticsResult {\n\trows: AnalyticsRow[]\n\ttotals?: Partial<Record<MetricKey, number>>\n\tmeta: {\n\t\tprovider: string\n\t\tsampled?: boolean\n\t\tclamped?: boolean\n\t\tfetchedAt: string\n\t\t/** Served from an expired cache entry because the live refresh failed. */\n\t\tstale?: boolean\n\t\t/**\n\t\t * Filters the source could not carry, so the rows are wider than the query asked for.\n\t\t * A provider whose API takes one value per dimension reports the ones it dropped here.\n\t\t */\n\t\tunappliedFilters?: AnalyticsFilter[]\n\t\t/**\n\t\t * The read's goal numbers are absent because resolving them failed: it ran without\n\t\t * `AnalyticsQuery.goalSlugs`, or with `'unresolved'`, or the provider rejected the goal\n\t\t * request and the rest of the read was served without it. A scope that configured no\n\t\t * goals is an empty result instead, not this flag.\n\t\t */\n\t\tgoalsUnresolved?: true\n\t}\n}\n\n/**\n * A read carrying conversions costs a provider up to twice the requests: the goal numbers\n * come from a second, goal-filtered request the adapter issues after the plain one.\n */\nexport interface RateLimitDescriptor {\n\trequestsPerMinute?: number\n\trequestsPerHour?: number\n\tmaxConcurrent?: number\n\t/**\n\t * Describes the provider's quota model for documentation; the limiter always\n\t * throttles by request count regardless of this value.\n\t */\n\tquotaModel?: 'requests' | 'tokens'\n\t/** Documents whether reads consume the provider's write/ingest quota too. */\n\treadsCountAsUsage?: boolean\n}\n\nexport interface AnalyticsCapabilities {\n\tperPageQuery: boolean\n\trealtime: boolean\n\trealtimeWindowMinutes?: number\n\t/**\n\t * Period-over-period comparison, which the engine serves for every source by reading the\n\t * previous window itself. Adapters omit this; set it false only to opt a source out.\n\t */\n\tcomparison?: boolean\n\tminGranularity: Granularity\n\tmaxLookbackDays: number | null\n\tmetrics: ReadonlySet<MetricKey>\n\tdimensions: ReadonlySet<DimensionKey>\n\t/** Dimensions the adapter can apply AnalyticsQuery.filters on; empty = filters unsupported. */\n\tfilters: ReadonlySet<DimensionKey>\n\t/** Operators the adapter honors in filters; adapters ignore filters whose operator they lack. */\n\tfilterOperators: ReadonlySet<FilterOperator>\n\tbatchPageReport: boolean\n\trateLimit: RateLimitDescriptor | null\n\trecommendedTtl: { realtime: number; aggregate: number }\n\t/**\n\t * The adapter applies `AnalyticsQuery.scope` as a provider-native filter (native\n\t * scope column, PostHog `scopeProperty`, ...). Without it, a scoped read through\n\t * a shared platform adapter would expose cross-scope data, so such reads are\n\t * gated by `access.platformRead`.\n\t */\n\tscopedQueries?: boolean\n}\n\nexport interface AdapterContext {\n\tsignal?: AbortSignal\n}\n\n/** Extra context the plugin hands adapters when they register config surface. */\nexport interface AdapterRegisterContext {\n\t/** True when the plugin has a scopeResolver configured. */\n\tscoped: boolean\n\t/** The plugin's scopeResolver bound for adapter use (e.g. ingest stamping). */\n\tresolveScope: (req: PayloadRequest) => Promise<string | null>\n\t/**\n\t * The plugin's reportingTimezone bound for adapter use (e.g. bucketing native\n\t * rollups at ingest). Resolves to `'UTC'` when no reportingTimezone is set.\n\t */\n\tresolveTimezone: (req: PayloadRequest, scope?: string | null) => Promise<string>\n\t/**\n\t * The install's goals for a request's scope, for adapters that match completions\n\t * themselves (the native engine, at ingest). Config goals, with the goals collection\n\t * merged over them per scope once the install enables it.\n\t */\n\tresolveGoals: (req: PayloadRequest, scope?: string | null) => Promise<Goal[]>\n}\n\nexport interface AnalyticsAdapter {\n\treadonly id: string\n\treadonly label: string\n\treadonly capabilities: AnalyticsCapabilities\n\t/** Browser-tracker proxying/boot descriptor. Absent when no public capture field is set. */\n\treadonly capture?: CaptureSupport\n\t/**\n\t * Where this adapter's own ingest endpoint listens, relative to `routes.api`, for the\n\t * adapters that register one (the native engine), and how server code reaches the same\n\t * pipeline without an HTTP round trip. Server-side only: the tracker learns the path\n\t * from `TrackerConfig.ingestPath`, and this object is never serialized.\n\t */\n\treadonly ingest?: { path: string; track?: ServerTrack }\n\tisConfigured(): boolean\n\tquery(query: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult>\n\trealtime?(query: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult>\n\tregister?(config: Config, context?: AdapterRegisterContext): void\n}\n\nexport type AnalyticsAdapterFactory<Config> = (config: Config) => AnalyticsAdapter\n"],"mappings":";;;;;AASA,MAAa,iBAAiB;;AAe9B,MAAa,iBAAiB;CAC7B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD;;AAYA,MAAa,mBAAmB;CAAC;CAAM;CAAY;AAAS"}
@@ -132,6 +132,11 @@ type AutoCaptureOptions = {
132
132
  outboundLinks?: boolean;
133
133
  fileDownloads?: boolean;
134
134
  goalAttribute?: boolean;
135
+ /**
136
+ * Send each pageview's query string so ingest can extract its utm keys. The raw query is
137
+ * never stored, only the five campaign values; set false to stop sending it at all.
138
+ */
139
+ query?: boolean;
135
140
  };
136
141
  type ResolvedAutoCapture = Required<AutoCaptureOptions>;
137
142
  type AnalyticsGoalsCollectionOptions = {
@@ -272,8 +277,9 @@ type AnalyticsPluginOptions = {
272
277
  localizeText?: boolean;
273
278
  /**
274
279
  * Period-over-period comparison on the metric and trend widgets. On by
275
- * default for adapters that declare `capabilities.comparison`; set false
276
- * to skip the second (previous-window) read entirely.
280
+ * default for every source except one whose adapter sets
281
+ * `capabilities.comparison` false; set false to skip the second
282
+ * (previous-window) read entirely.
277
283
  */
278
284
  comparison?: boolean;
279
285
  };
@@ -16,13 +16,15 @@ const DEFAULT_AUTO_CAPTURE = {
16
16
  scrollDepth: false,
17
17
  outboundLinks: true,
18
18
  fileDownloads: true,
19
- goalAttribute: true
19
+ goalAttribute: true,
20
+ query: true
20
21
  };
21
22
  const resolveAutoCapture = (option) => ({
22
23
  scrollDepth: option?.scrollDepth ?? DEFAULT_AUTO_CAPTURE.scrollDepth,
23
24
  outboundLinks: option?.outboundLinks ?? DEFAULT_AUTO_CAPTURE.outboundLinks,
24
25
  fileDownloads: option?.fileDownloads ?? DEFAULT_AUTO_CAPTURE.fileDownloads,
25
- goalAttribute: option?.goalAttribute ?? DEFAULT_AUTO_CAPTURE.goalAttribute
26
+ goalAttribute: option?.goalAttribute ?? DEFAULT_AUTO_CAPTURE.goalAttribute,
27
+ query: option?.query ?? DEFAULT_AUTO_CAPTURE.query
26
28
  });
27
29
  /** Cookieless native capture needs no consent gate; a vendor's tracker does. */
28
30
  const defaultConsentFor = (kind) => kind === "native" ? "none" : "required";
@@ -1 +1 @@
1
- {"version":3,"file":"options.js","names":[],"sources":["../../src/core/options.ts"],"sourcesContent":["import type { KeysConfig } from '@10x-media/fields/encrypted'\nimport type { CollectionConfig, CollectionSlug, Payload, PayloadRequest } from 'payload'\nimport type { AnalyticsBinding, ResolvedBinding } from '../binding/types'\nimport { DEFAULT_PROXY_MAX_BODY_BYTES, DEFAULT_PROXY_TIMEOUT_MS } from '../capture/proxyEndpoint'\nimport type { CaptureSlot } from '../capture/slots'\nimport { GOALS_SLUG } from '../goals/collection'\nimport { GOAL_SLUG_PATTERN, type Goal } from '../goals/types'\nimport { PROVIDERS_SLUG } from '../providers/collection'\nimport { TIMEFRAME_PRESETS, type TimeframePreset } from '../timeframe/presets'\nimport type { TranslationsOption } from '../translations'\nimport { METRIC_KEYS } from '../translations/metricKeys'\nimport type { CustomWidgetDef } from '../widgets/customWidget'\nimport type { CaptureClientKind } from './capture'\nimport type { AnalyticsAdapter, MetricKey } from './contract'\n\nconst DEFAULT_WARM_CRON = '*/30 * * * *'\nconst DEFAULT_SYNC_CRON = '0 */6 * * *'\nconst DEFAULT_SYNC_COLLECTION = 'analytics-daily'\nconst DEFAULT_SYNC_LOOKBACK = 3\nconst DEFAULT_SCOPE_FIELD = 'scope'\nconst DEFAULT_TIMEOUT_MS = 15_000\n\n/**\n * Maps a request to its analytics boundary (tenant id, site key). Null means the\n * whole install, which is the default single-site behavior. With a multi-tenant\n * plugin, return the request's tenant id here.\n */\nexport type ScopeResolver = (args: {\n\treq: PayloadRequest\n}) => string | null | Promise<string | null>\n\n/**\n * Resolves the IANA reporting timezone a read's (or ingest's) day boundaries align\n * to. Receives the request and its already-resolved scope, so per-tenant, per-user\n * (`req.user`), and selector (cookie/preference) strategies are all expressible.\n * Return `null` to fall back to UTC.\n */\nexport type TimezoneResolver = (args: {\n\treq: PayloadRequest\n\tscope: string | null\n}) => string | null | Promise<string | null>\n\n/**\n * Enumerates the tenant scopes the cron tiers (cache warming, sync) fan out over.\n * Absent, each tier runs once for the install-wide scope.\n */\nexport type ScopesResolver = (args: { payload: Payload }) => string[] | Promise<string[]>\n\n/**\n * Escape hatch replacing the provider-collection lookup: return the runtime\n * adapters for a scope yourself (any store, any shape). Results are layered onto\n * the static config adapters exactly like collection-resolved ones, but are not\n * cached; memoize inside the function if lookups are expensive.\n */\nexport type ProvidersResolve = (args: {\n\tpayload: Payload\n\treq?: PayloadRequest\n\tscope: string | null\n}) => AnalyticsAdapter[] | Promise<AnalyticsAdapter[]>\n\nexport type ProvidersCollectionOptions = {\n\tslug?: string\n\t/**\n\t * Field matched against the resolved scope when looking up a scope's providers.\n\t * Point it at a tenant plugin's field (e.g. 'tenant') when that plugin manages\n\t * scoping for the collection.\n\t */\n\tscopeField?: string\n\toverrides?: (collection: CollectionConfig) => CollectionConfig\n\taccess?: Partial<CollectionConfig['access']>\n\t/**\n\t * Dedicated key ring for the stored provider credentials. Unset, the\n\t * fields plugin's global `encrypted.keys` applies, and with neither the\n\t * ring derives from the Payload secret. Configure a dedicated key for\n\t * anything beyond a dev install.\n\t */\n\tencryption?: { keys?: KeysConfig }\n}\n\nexport type ProvidersOptions = {\n\t/** Opt-in admin collection storing runtime provider configurations. */\n\tcollection?: boolean | ProvidersCollectionOptions\n\tresolve?: ProvidersResolve\n}\n\n/** Access checker for cross-scope (platform) analytics reads. */\nexport type PlatformReadAccess = (args: { req: PayloadRequest }) => boolean | Promise<boolean>\n\n/** Access checker for authenticated analytics reads. */\nexport type AnalyticsReadAccess = (args: { req: PayloadRequest }) => boolean | Promise<boolean>\n\n/** Access checker for the analytics admin view. */\nexport type AnalyticsViewAccess = (args: { req: PayloadRequest }) => boolean | Promise<boolean>\n\nexport type AnalyticsAccessOptions = {\n\t/**\n\t * Gates every authenticated read endpoint: query, document panel, realtime, sources\n\t * and goals. Defaults to any authenticated user; narrow it to a role check to keep\n\t * analytics away from admins who should not see them. Scope gating is separate and\n\t * always applies: granting `read` never widens which scope a user reads.\n\t */\n\tread?: AnalyticsReadAccess\n\t/**\n\t * Gates cross-scope reads: explicit `scope: '*'` reads, and scoped reads through\n\t * a shared config adapter that cannot filter by scope. Scoped installs\n\t * (`scopeResolver` configured) default to deny; configure it, for example a role\n\t * check, so platform admins can read cross-scope and manage every tenant's\n\t * providers. Unscoped installs default to any authenticated admin-panel user.\n\t */\n\tplatformRead?: PlatformReadAccess\n\t/**\n\t * Gates the analytics admin view. Defaults to `read`, so one gate covers the view and\n\t * the endpoints behind it. A reader this denies still sees the nav link (it is a client\n\t * component with no access context) and lands on the view's no-access message.\n\t */\n\tview?: AnalyticsViewAccess\n}\n\nexport type ConsentMode = 'none' | 'required'\n\n/** Per-slot consent decision, evaluated against the slot's resolved adapter. */\nexport type ConsentResolver = (args: { slot: CaptureSlot; adapterId: string }) => ConsentMode\n\n/** An adapter id to fill a capture slot with, or `false` to leave it deliberately empty. */\nexport type CaptureSlotOption = string | false\n\n/**\n * A bare mode applies to every slot; a resolver decides per request-resolved adapter; the\n * object form maps ids and slots, with an adapter entry winning over a slot entry. Every\n * form overrides the default, which is `none` for the cookieless native tracker and\n * `required` for a vendor's.\n */\nexport type CaptureConsentOption =\n\t| ConsentMode\n\t| ConsentResolver\n\t| {\n\t\t\tslots?: Partial<Record<CaptureSlot, ConsentMode>>\n\t\t\t/**\n\t\t\t * Keyed by adapter id. A bare id must name a config adapter; a runtime provider\n\t\t\t * instance id (`<provider>:<instance>`) is taken on trust, since the providers it\n\t\t\t * comes from are only resolved per request.\n\t\t\t */\n\t\t\tadapters?: Record<string, ConsentMode>\n\t }\n\n/** The normalized policy the runtime evaluates; `kind` carries the adapter's tracker family. */\nexport type ConsentPolicy = (\n\tslot: CaptureSlot,\n\tadapterId: string,\n\tkind: CaptureClientKind\n) => ConsentMode\n\nexport type AutoCaptureOptions = {\n\tscrollDepth?: boolean\n\toutboundLinks?: boolean\n\tfileDownloads?: boolean\n\tgoalAttribute?: boolean\n}\n\nexport type ResolvedAutoCapture = Required<AutoCaptureOptions>\n\nexport type AnalyticsGoalsCollectionOptions = {\n\t/** Set false to keep the object form's other settings while leaving the collection off. */\n\tenabled?: boolean\n\tslug?: string\n\t/**\n\t * Field matched against the resolved scope when looking up a scope's goals. Point it at\n\t * a tenant plugin's field (e.g. 'tenant') when that plugin manages scoping.\n\t */\n\tscopeField?: string\n\toverrides?: (collection: CollectionConfig) => CollectionConfig\n\taccess?: Partial<CollectionConfig['access']>\n}\n\n/** Goals as config, plus the opt-in collection editors manage their own goals through. */\nexport type AnalyticsGoalsOptions = {\n\tdefaults?: Goal[]\n\t/** Opt-in admin collection whose goals merge over `defaults`, by slug, per scope. */\n\tcollection?: boolean | AnalyticsGoalsCollectionOptions\n}\n\nexport type AnalyticsCaptureOptions = {\n\t/**\n\t * Which adapter fills each capture slot, overriding the defaults: `global` is the\n\t * designated `platformAdapter`, or the single config adapter when only one is\n\t * configured; `tenant` is the resolved scope's default adapter. A `global` id must\n\t * name a config adapter; a `tenant` id may also name a runtime provider instance,\n\t * so it is resolved per request rather than validated at config time.\n\t *\n\t * `false` disables a slot outright: it fills with nothing, its proxy mount 404s, and\n\t * the tracker config omits it. Use it to keep a default from filling a slot at all.\n\t */\n\tslots?: { global?: CaptureSlotOption; tenant?: CaptureSlotOption }\n\t/**\n\t * Mount each slot's snippet points at. Defaults to the runtime proxy endpoint\n\t * (`<routes.api>/analytics/p/<slot>`); set it when the slot is served through Next\n\t * rewrites instead, passing the same path `captureRewrites` was mounted at.\n\t */\n\tpaths?: { global?: string; tenant?: string }\n\t/** Whether a slot's tracker waits for consent. Native defaults to no gate, vendors to one. */\n\tconsent?: CaptureConsentOption\n\t/** Browser auto-capture listeners, all on by default except `scrollDepth`. */\n\tautoCapture?: AutoCaptureOptions\n\t/** Limits for the public runtime capture proxy, separate from the read-path `cache`. */\n\tproxy?: {\n\t\t/**\n\t\t * Deadline for the upstream response headers, in ms. Default 10000. The body\n\t\t * download is not on the clock, so a large tracker bundle streams to completion.\n\t\t */\n\t\ttimeoutMs?: number\n\t\t/**\n\t\t * Largest proxied request body, in bytes. Default 1 MiB, which clears a PostHog\n\t\t * batch carrying session-replay data. Anything larger is refused with 413.\n\t\t */\n\t\tmaxBodyBytes?: number\n\t}\n}\n\nexport type AnalyticsViewOptions = {\n\t/** Admin path the view mounts at, under `routes.admin`. Default `/analytics`. */\n\tpath?: `/${string}`\n\t/** Timeframe the view opens on before the URL says otherwise. Default `last30days`. */\n\tdefaultRange?: TimeframePreset\n\t/** Metric the cards and the trend open on. Default `pageviews`. */\n\tdefaultMetric?: MetricKey\n\t/**\n\t * Nav link label. A string is used as-is; a map is keyed by admin language code and\n\t * falls back to `en`. Unset, the plugin's own translated label applies.\n\t */\n\tnavLabel?: string | Record<string, string>\n}\n\nexport interface ResolvedView {\n\tpath: `/${string}`\n\tdefaultRange: TimeframePreset\n\tdefaultMetric: MetricKey\n\tnavLabel?: string | Record<string, string>\n}\n\nexport type AnalyticsPluginOptions = {\n\tdisabled?: boolean\n\t/**\n\t * Per-locale overrides for this plugin's UI strings, keyed by the typed\n\t * translation keys exported from `@10x-media/analytics/i18n`. Values win over\n\t * the built-in locales key-by-key; locales the plugin does not ship are added\n\t * whole. App-level `i18n.translations` still wins over both.\n\t */\n\ttranslations?: TranslationsOption\n\tadapters?: AnalyticsAdapter[]\n\tdefaultAdapter?: string\n\tscopeResolver?: ScopeResolver\n\t/**\n\t * Enumerates the tenant scopes the cache-warming and sync cron tiers fan out\n\t * over, in addition to the install-wide (null) scope every tier already runs.\n\t * Unset, those tiers run once for the whole install, same as before.\n\t */\n\tscopes?: ScopesResolver\n\t/**\n\t * IANA reporting timezone that day boundaries (timeframe windows, series axes,\n\t * native rollup buckets) align to. Defaults to UTC. A string forces one timezone\n\t * (the single-tenant / no-multi-tenancy case); a resolver derives it per request\n\t * from the scope, user, or a selector. Native rollups bucket at ingest in the\n\t * resolved timezone, so changing it does not re-bucket existing history.\n\t */\n\treportingTimezone?: string | TimezoneResolver\n\tproviders?: ProvidersOptions\n\t/**\n\t * Id of one config adapter shared by every scope (the platform's own analytics,\n\t * e.g. a PostHog project capturing all tenants). Included in each scope's\n\t * registry like any config adapter; reads through it are scope-filtered only\n\t * when the adapter supports scoped queries, otherwise they are cross-scope and\n\t * require `access.platformRead`.\n\t */\n\tplatformAdapter?: string\n\taccess?: AnalyticsAccessOptions\n\t/**\n\t * The analytics admin view and its nav link, on by default. `false` registers neither;\n\t * the read endpoints stay mounted either way, so a custom surface keeps working.\n\t */\n\tview?: false | AnalyticsViewOptions\n\tcapture?: AnalyticsCaptureOptions\n\t/**\n\t * Conversion goals the tracker and the native ingest match events against. Slugs must\n\t * be unique and kebab-case; only the slug and its match reach the browser.\n\t */\n\tgoals?: Goal[] | AnalyticsGoalsOptions\n\t/**\n\t * Per-collection bindings, keyed by collection slug. With generated types\n\t * augmented, each slug's resolvers receive that collection's typed document.\n\t */\n\tcollections?: { [TSlug in CollectionSlug]?: AnalyticsBinding<TSlug> }\n\tcache?: {\n\t\tttl?: { aggregate?: number; realtime?: number }\n\t\twarm?: boolean | { cron?: string }\n\t\t/** Per-read provider timeout in ms, spanning retries and limiter waits. Default 15000. */\n\t\ttimeoutMs?: number\n\t}\n\twidgets?:\n\t\t| boolean\n\t\t| {\n\t\t\t\tdisabled?: string[]\n\t\t\t\tregister?: CustomWidgetDef[]\n\t\t\t\t/**\n\t\t\t\t * Marks the free-text widget config fields (each widget's Title) as\n\t\t\t\t * `localized`. Off by default; takes effect only when the Payload config\n\t\t\t\t * enables localization (Payload strips the flag otherwise).\n\t\t\t\t */\n\t\t\t\tlocalizeText?: boolean\n\t\t\t\t/**\n\t\t\t\t * Period-over-period comparison on the metric and trend widgets. On by\n\t\t\t\t * default for adapters that declare `capabilities.comparison`; set false\n\t\t\t\t * to skip the second (previous-window) read entirely.\n\t\t\t\t */\n\t\t\t\tcomparison?: boolean\n\t\t }\n\t/**\n\t * Opt-in sync tier: a cron job that persists each provider's daily metrics into a\n\t * queryable collection. Reads go through the surfacing cache, so persisted rows reflect\n\t * cached values up to `cache.ttl.aggregate` old; keep that TTL below the sync interval\n\t * for the freshest data.\n\t */\n\tsync?:\n\t\t| boolean\n\t\t| {\n\t\t\t\tcollectionSlug?: CollectionSlug\n\t\t\t\tcron?: string\n\t\t\t\tlookbackDays?: number\n\t\t\t\tadapters?: string[]\n\t\t\t\t/** Surface the analytics-daily collection in the admin nav. Default false (hidden). */\n\t\t\t\thidden?: boolean\n\t\t }\n}\n\nexport interface ResolvedCapture {\n\tslots: { global?: CaptureSlotOption; tenant?: CaptureSlotOption }\n\tpaths: { global?: string; tenant?: string }\n\tconsent: ConsentPolicy\n\tautoCapture: ResolvedAutoCapture\n\tproxy: { timeoutMs: number; maxBodyBytes: number }\n}\n\nexport interface ResolvedOptions {\n\tadapters: AnalyticsAdapter[]\n\tdefaultAdapter?: string\n\tscopeResolver: ScopeResolver\n\t/** True when the app configured a scopeResolver (scoped install). */\n\tscoped: boolean\n\t/** Raw scopes option; undefined runs the cron tiers install-wide only. */\n\tscopes?: ScopesResolver\n\t/** Raw reportingTimezone option; normalized into a resolver at init. */\n\treportingTimezone?: string | TimezoneResolver\n\tplatformAdapter?: string\n\taccess: {\n\t\tplatformRead: PlatformReadAccess\n\t\tread: AnalyticsReadAccess\n\t\tview: AnalyticsViewAccess\n\t}\n\t/** The admin view, filled with its defaults, or false when the app turned it off. */\n\tview: false | ResolvedView\n\tcapture: ResolvedCapture\n\t/** Config goals, validated; the goals collection layers its own on top of these. */\n\tgoals: Goal[]\n\tgoalsCollection: {\n\t\tenabled: boolean\n\t\tslug: string\n\t\tscopeField: string\n\t\toverrides?: (collection: CollectionConfig) => CollectionConfig\n\t\taccess?: Partial<CollectionConfig['access']>\n\t}\n\tproviders: {\n\t\tcollection: {\n\t\t\tenabled: boolean\n\t\t\tslug: string\n\t\t\tscopeField: string\n\t\t\toverrides?: (collection: CollectionConfig) => CollectionConfig\n\t\t\taccess?: Partial<CollectionConfig['access']>\n\t\t\tencryption?: { keys?: KeysConfig }\n\t\t}\n\t\tresolve?: ProvidersResolve\n\t}\n\tbindings: Record<string, ResolvedBinding>\n\tcache: {\n\t\t/** Undefined when unset: adapter recommendedTtl is the fallback, an explicit value wins. */\n\t\tttl: { aggregate?: number; realtime?: number }\n\t\twarm: { enabled: boolean; cron: string }\n\t\ttimeoutMs: number\n\t}\n\twidgets: {\n\t\tenabled: boolean\n\t\tdisabled: string[]\n\t\tregister: CustomWidgetDef[]\n\t\tlocalizeText: boolean\n\t\tcomparison: boolean\n\t}\n\tsync: {\n\t\tenabled: boolean\n\t\tcollectionSlug: string\n\t\tcron: string\n\t\tlookbackDays: number\n\t\tadapters?: string[]\n\t\t/** True hides the analytics-daily collection from the admin nav (default). */\n\t\thidden: boolean\n\t}\n}\n\n/** Scroll depth is the one listener off by default: it fires on every page, for every visitor. */\nexport const DEFAULT_AUTO_CAPTURE: ResolvedAutoCapture = {\n\tscrollDepth: false,\n\toutboundLinks: true,\n\tfileDownloads: true,\n\tgoalAttribute: true,\n}\n\nconst resolveAutoCapture = (option: AutoCaptureOptions | undefined): ResolvedAutoCapture => ({\n\tscrollDepth: option?.scrollDepth ?? DEFAULT_AUTO_CAPTURE.scrollDepth,\n\toutboundLinks: option?.outboundLinks ?? DEFAULT_AUTO_CAPTURE.outboundLinks,\n\tfileDownloads: option?.fileDownloads ?? DEFAULT_AUTO_CAPTURE.fileDownloads,\n\tgoalAttribute: option?.goalAttribute ?? DEFAULT_AUTO_CAPTURE.goalAttribute,\n})\n\n/** Cookieless native capture needs no consent gate; a vendor's tracker does. */\nexport const defaultConsentFor = (kind: CaptureClientKind): ConsentMode =>\n\tkind === 'native' ? 'none' : 'required'\n\nconst resolveConsent = (\n\toption: CaptureConsentOption | undefined,\n\tadapters: AnalyticsAdapter[]\n): ConsentPolicy => {\n\tif (option === 'none' || option === 'required') {\n\t\treturn () => option\n\t}\n\tif (typeof option === 'function') {\n\t\treturn (slot, adapterId) => option({ slot, adapterId })\n\t}\n\tfor (const id of Object.keys(option?.adapters ?? {})) {\n\t\t// A runtime provider instance id is `<provider>:<instance>` and only exists once a\n\t\t// scope resolves, so it cannot be checked here; a bare id must name a config adapter.\n\t\tif (!id.includes(':') && !adapters.some((a) => a.id === id)) {\n\t\t\tthrow new Error(`analytics: unknown consent adapter \"${id}\"`)\n\t\t}\n\t}\n\treturn (slot, adapterId, kind) =>\n\t\toption?.adapters?.[adapterId] ?? option?.slots?.[slot] ?? defaultConsentFor(kind)\n}\n\nconst resolveGoals = (option: AnalyticsPluginOptions['goals']): Goal[] => {\n\tconst goals = Array.isArray(option) ? option : (option?.defaults ?? [])\n\tconst seen = new Set<string>()\n\tfor (const goal of goals) {\n\t\tif (!GOAL_SLUG_PATTERN.test(goal.slug)) {\n\t\t\tthrow new Error(`analytics: goal slug \"${goal.slug}\" must be kebab-case`)\n\t\t}\n\t\tif (seen.has(goal.slug)) {\n\t\t\tthrow new Error(`analytics: duplicate goal slug \"${goal.slug}\"`)\n\t\t}\n\t\tconst fixed = goal.value?.fixed\n\t\t// Revenue is money: a negative or non-finite fixed value would be silently ignored at\n\t\t// ingest, so it fails the boot instead.\n\t\tif (fixed !== undefined && (!Number.isFinite(fixed) || fixed < 0)) {\n\t\t\tthrow new Error(\n\t\t\t\t`analytics: goal \"${goal.slug}\" value.fixed must be a finite number >= 0, got ${String(fixed)}`\n\t\t\t)\n\t\t}\n\t\tseen.add(goal.slug)\n\t}\n\treturn goals\n}\n\nconst resolveGoalsCollection = (\n\toption: AnalyticsPluginOptions['goals']\n): ResolvedOptions['goalsCollection'] => {\n\tconst off = { enabled: false, slug: GOALS_SLUG, scopeField: DEFAULT_SCOPE_FIELD }\n\tconst collection = Array.isArray(option) ? undefined : option?.collection\n\tif (!collection) {\n\t\treturn off\n\t}\n\tconst resolved =\n\t\tcollection === true\n\t\t\t? { ...off, enabled: true }\n\t\t\t: {\n\t\t\t\t\tenabled: collection.enabled ?? true,\n\t\t\t\t\tslug: collection.slug ?? GOALS_SLUG,\n\t\t\t\t\tscopeField: collection.scopeField ?? DEFAULT_SCOPE_FIELD,\n\t\t\t\t\toverrides: collection.overrides,\n\t\t\t\t\taccess: collection.access,\n\t\t\t\t}\n\tif (!resolved.enabled) {\n\t\treturn off\n\t}\n\tif (typeof resolved.slug !== 'string' || resolved.slug.trim() === '') {\n\t\tthrow new Error('analytics: goals.collection.slug must be a non-empty collection slug')\n\t}\n\tif (resolved.scopeField.trim() === '') {\n\t\tthrow new Error('analytics: goals.collection.scopeField must be a non-empty field name')\n\t}\n\tif (resolved.scopeField.includes('.')) {\n\t\tthrow new Error(\n\t\t\t'analytics: goals.collection.scopeField must be a top-level field name (no dots); the scope stamp writes it as a flat key'\n\t\t)\n\t}\n\treturn { ...resolved, slug: resolved.slug.trim() }\n}\n\nexport const DEFAULT_VIEW: ResolvedView = {\n\tpath: '/analytics',\n\tdefaultRange: 'last30days',\n\tdefaultMetric: 'pageviews',\n}\n\nconst resolveView = (option: AnalyticsPluginOptions['view']): false | ResolvedView => {\n\tif (option === false) {\n\t\treturn false\n\t}\n\tconst path = option?.path ?? DEFAULT_VIEW.path\n\tif (typeof path !== 'string' || !path.startsWith('/')) {\n\t\tthrow new Error(`analytics: view.path must start with \"/\", got \"${String(path)}\"`)\n\t}\n\tconst defaultRange = option?.defaultRange ?? DEFAULT_VIEW.defaultRange\n\tif (!TIMEFRAME_PRESETS.includes(defaultRange)) {\n\t\tthrow new Error(`analytics: unknown view.defaultRange \"${String(defaultRange)}\"`)\n\t}\n\tconst defaultMetric = option?.defaultMetric ?? DEFAULT_VIEW.defaultMetric\n\tif (!(defaultMetric in METRIC_KEYS)) {\n\t\tthrow new Error(`analytics: unknown view.defaultMetric \"${String(defaultMetric)}\"`)\n\t}\n\treturn {\n\t\tpath,\n\t\tdefaultRange,\n\t\tdefaultMetric,\n\t\t...(option?.navLabel !== undefined ? { navLabel: option.navLabel } : {}),\n\t}\n}\n\nconst resolveBindings = (\n\tcollections: AnalyticsPluginOptions['collections']\n): Record<string, ResolvedBinding> => {\n\tconst out: Record<string, ResolvedBinding> = {}\n\tfor (const [slug, binding] of Object.entries(collections ?? {})) {\n\t\tif (!binding) continue\n\t\tif (!binding.path && !binding.pathField) {\n\t\t\tthrow new Error(`analytics: binding for \"${slug}\" needs a path resolver or a pathField`)\n\t\t}\n\t\t// Erases the per-slug doc generic; safe because the runtime only ever hands\n\t\t// a binding documents from its own collection.\n\t\tout[slug] = binding as ResolvedBinding\n\t}\n\treturn out\n}\n\nexport function resolveOptions(options: AnalyticsPluginOptions): ResolvedOptions {\n\tif (!options.adapters || options.adapters.length === 0) {\n\t\tthrow new Error('analytics: at least one adapter is required')\n\t}\n\tif (\n\t\toptions.platformAdapter !== undefined &&\n\t\t!options.adapters.some((a) => a.id === options.platformAdapter)\n\t) {\n\t\tthrow new Error(`analytics: unknown platform adapter \"${options.platformAdapter}\"`)\n\t}\n\tfor (const [slot, value] of Object.entries(options.capture?.slots ?? {})) {\n\t\tif (value !== false && typeof value !== 'string' && value !== undefined) {\n\t\t\tthrow new Error(\n\t\t\t\t`analytics: capture slot \"${slot}\" must be an adapter id or false, got ${typeof value}`\n\t\t\t)\n\t\t}\n\t}\n\tconst globalSlot = options.capture?.slots?.global\n\t// A tenant id may name a runtime provider instance, which only exists once a scope\n\t// resolves; a global one can only come from the config registry, so it is checked here.\n\tif (typeof globalSlot === 'string' && !options.adapters.some((a) => a.id === globalSlot)) {\n\t\tthrow new Error(`analytics: unknown global capture slot adapter \"${globalSlot}\"`)\n\t}\n\tconst widgets =\n\t\toptions.widgets === false\n\t\t\t? {\n\t\t\t\t\tenabled: false,\n\t\t\t\t\tdisabled: [] as string[],\n\t\t\t\t\tregister: [] as CustomWidgetDef[],\n\t\t\t\t\tlocalizeText: false,\n\t\t\t\t\tcomparison: true,\n\t\t\t\t}\n\t\t\t: options.widgets === undefined || options.widgets === true\n\t\t\t\t? {\n\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\tdisabled: [] as string[],\n\t\t\t\t\t\tregister: [] as CustomWidgetDef[],\n\t\t\t\t\t\tlocalizeText: false,\n\t\t\t\t\t\tcomparison: true,\n\t\t\t\t\t}\n\t\t\t\t: {\n\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\tdisabled: options.widgets.disabled ?? [],\n\t\t\t\t\t\tregister: options.widgets.register ?? [],\n\t\t\t\t\t\tlocalizeText: options.widgets.localizeText ?? false,\n\t\t\t\t\t\tcomparison: options.widgets.comparison ?? true,\n\t\t\t\t\t}\n\tconst warmOpt = options.cache?.warm\n\tconst warm =\n\t\twarmOpt === true\n\t\t\t? { enabled: true, cron: DEFAULT_WARM_CRON }\n\t\t\t: warmOpt && typeof warmOpt === 'object'\n\t\t\t\t? { enabled: true, cron: warmOpt.cron ?? DEFAULT_WARM_CRON }\n\t\t\t\t: { enabled: false, cron: DEFAULT_WARM_CRON }\n\tconst collectionOpt = options.providers?.collection\n\tconst providers = {\n\t\tcollection:\n\t\t\tcollectionOpt === true\n\t\t\t\t? { enabled: true, slug: PROVIDERS_SLUG, scopeField: DEFAULT_SCOPE_FIELD }\n\t\t\t\t: collectionOpt && typeof collectionOpt === 'object'\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\t\tslug: collectionOpt.slug ?? PROVIDERS_SLUG,\n\t\t\t\t\t\t\tscopeField: collectionOpt.scopeField ?? DEFAULT_SCOPE_FIELD,\n\t\t\t\t\t\t\toverrides: collectionOpt.overrides,\n\t\t\t\t\t\t\taccess: collectionOpt.access,\n\t\t\t\t\t\t\tencryption: collectionOpt.encryption,\n\t\t\t\t\t\t}\n\t\t\t\t\t: { enabled: false, slug: PROVIDERS_SLUG, scopeField: DEFAULT_SCOPE_FIELD },\n\t\tresolve: options.providers?.resolve,\n\t}\n\tif (providers.collection.enabled) {\n\t\tif (providers.collection.scopeField.trim() === '') {\n\t\t\tthrow new Error('analytics: providers.collection.scopeField must be a non-empty field name')\n\t\t}\n\t\tif (providers.collection.scopeField.includes('.')) {\n\t\t\tthrow new Error(\n\t\t\t\t'analytics: providers.collection.scopeField must be a top-level field name (no dots); the scope stamp writes it as a flat key'\n\t\t\t)\n\t\t}\n\t}\n\tconst syncOpt = options.sync\n\tconst sync =\n\t\tsyncOpt === true\n\t\t\t? {\n\t\t\t\t\tenabled: true,\n\t\t\t\t\tcollectionSlug: DEFAULT_SYNC_COLLECTION,\n\t\t\t\t\tcron: DEFAULT_SYNC_CRON,\n\t\t\t\t\tlookbackDays: DEFAULT_SYNC_LOOKBACK,\n\t\t\t\t\thidden: true,\n\t\t\t\t}\n\t\t\t: syncOpt && typeof syncOpt === 'object'\n\t\t\t\t? {\n\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\tcollectionSlug: syncOpt.collectionSlug ?? DEFAULT_SYNC_COLLECTION,\n\t\t\t\t\t\tcron: syncOpt.cron ?? DEFAULT_SYNC_CRON,\n\t\t\t\t\t\tlookbackDays: syncOpt.lookbackDays ?? DEFAULT_SYNC_LOOKBACK,\n\t\t\t\t\t\tadapters: syncOpt.adapters,\n\t\t\t\t\t\thidden: syncOpt.hidden ?? true,\n\t\t\t\t\t}\n\t\t\t\t: {\n\t\t\t\t\t\tenabled: false,\n\t\t\t\t\t\tcollectionSlug: DEFAULT_SYNC_COLLECTION,\n\t\t\t\t\t\tcron: DEFAULT_SYNC_CRON,\n\t\t\t\t\t\tlookbackDays: DEFAULT_SYNC_LOOKBACK,\n\t\t\t\t\t\thidden: true,\n\t\t\t\t\t}\n\tconst scoped = options.scopeResolver !== undefined\n\t// The view gate defaults to this exact function, so one `access.read` covers both.\n\tconst read: AnalyticsReadAccess = options.access?.read ?? (({ req }) => Boolean(req.user))\n\treturn {\n\t\tadapters: options.adapters,\n\t\tdefaultAdapter: options.defaultAdapter,\n\t\tscopeResolver: options.scopeResolver ?? (() => null),\n\t\tscoped,\n\t\tscopes: options.scopes,\n\t\treportingTimezone: options.reportingTimezone,\n\t\tplatformAdapter: options.platformAdapter,\n\t\taccess: {\n\t\t\tplatformRead:\n\t\t\t\toptions.access?.platformRead ?? (scoped ? () => false : ({ req }) => Boolean(req.user)),\n\t\t\tread,\n\t\t\tview: options.access?.view ?? read,\n\t\t},\n\t\tview: resolveView(options.view),\n\t\tcapture: {\n\t\t\tslots: {\n\t\t\t\tglobal: options.capture?.slots?.global,\n\t\t\t\ttenant: options.capture?.slots?.tenant,\n\t\t\t},\n\t\t\tpaths: {\n\t\t\t\tglobal: options.capture?.paths?.global,\n\t\t\t\ttenant: options.capture?.paths?.tenant,\n\t\t\t},\n\t\t\tconsent: resolveConsent(options.capture?.consent, options.adapters),\n\t\t\tautoCapture: resolveAutoCapture(options.capture?.autoCapture),\n\t\t\tproxy: {\n\t\t\t\ttimeoutMs: options.capture?.proxy?.timeoutMs ?? DEFAULT_PROXY_TIMEOUT_MS,\n\t\t\t\tmaxBodyBytes: options.capture?.proxy?.maxBodyBytes ?? DEFAULT_PROXY_MAX_BODY_BYTES,\n\t\t\t},\n\t\t},\n\t\tgoals: resolveGoals(options.goals),\n\t\tgoalsCollection: resolveGoalsCollection(options.goals),\n\t\tproviders,\n\t\tbindings: resolveBindings(options.collections),\n\t\tcache: {\n\t\t\t// Left undefined when the app did not set them so the adapter's recommendedTtl\n\t\t\t// applies as the default; an explicit value overrides the adapter recommendation.\n\t\t\tttl: {\n\t\t\t\taggregate: options.cache?.ttl?.aggregate,\n\t\t\t\trealtime: options.cache?.ttl?.realtime,\n\t\t\t},\n\t\t\twarm,\n\t\t\ttimeoutMs: options.cache?.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n\t\t},\n\t\twidgets,\n\t\tsync,\n\t}\n}\n"],"mappings":";;;;;;;AAeA,MAAM,oBAAoB;AAC1B,MAAM,oBAAoB;AAC1B,MAAM,0BAA0B;AAChC,MAAM,wBAAwB;AAC9B,MAAM,sBAAsB;AAC5B,MAAM,qBAAqB;;AAkY3B,MAAa,uBAA4C;CACxD,aAAa;CACb,eAAe;CACf,eAAe;CACf,eAAe;AAChB;AAEA,MAAM,sBAAsB,YAAiE;CAC5F,aAAa,QAAQ,eAAe,qBAAqB;CACzD,eAAe,QAAQ,iBAAiB,qBAAqB;CAC7D,eAAe,QAAQ,iBAAiB,qBAAqB;CAC7D,eAAe,QAAQ,iBAAiB,qBAAqB;AAC9D;;AAGA,MAAa,qBAAqB,SACjC,SAAS,WAAW,SAAS;AAE9B,MAAM,kBACL,QACA,aACmB;CACnB,IAAI,WAAW,UAAU,WAAW,YACnC,aAAa;CAEd,IAAI,OAAO,WAAW,YACrB,QAAQ,MAAM,cAAc,OAAO;EAAE;EAAM;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U,QAAQ,IAAI,IAAI;GACtF;GACA,MAAM,QAAQ,QAAQ,QAAQ;EAC/B;EACA,MAAM,YAAY,QAAQ,IAAI;EAC9B,SAAS;GACR,OAAO;IACN,QAAQ,QAAQ,SAAS,OAAO;IAChC,QAAQ,QAAQ,SAAS,OAAO;GACjC;GACA,OAAO;IACN,QAAQ,QAAQ,SAAS,OAAO;IAChC,QAAQ,QAAQ,SAAS,OAAO;GACjC;GACA,SAAS,eAAe,QAAQ,SAAS,SAAS,QAAQ,QAAQ;GAClE,aAAa,mBAAmB,QAAQ,SAAS,WAAW;GAC5D,OAAO;IACN,WAAW,QAAQ,SAAS,OAAO,aAAA;IACnC,cAAc,QAAQ,SAAS,OAAO,gBAAA;GACvC;EACD;EACA,OAAO,aAAa,QAAQ,KAAK;EACjC,iBAAiB,uBAAuB,QAAQ,KAAK;EACrD;EACA,UAAU,gBAAgB,QAAQ,WAAW;EAC7C,OAAO;GAGN,KAAK;IACJ,WAAW,QAAQ,OAAO,KAAK;IAC/B,UAAU,QAAQ,OAAO,KAAK;GAC/B;GACA;GACA,WAAW,QAAQ,OAAO,aAAa;EACxC;EACA;EACA;CACD;AACD"}
1
+ {"version":3,"file":"options.js","names":[],"sources":["../../src/core/options.ts"],"sourcesContent":["import type { KeysConfig } from '@10x-media/fields/encrypted'\nimport type { CollectionConfig, CollectionSlug, Payload, PayloadRequest } from 'payload'\nimport type { AnalyticsBinding, ResolvedBinding } from '../binding/types'\nimport { DEFAULT_PROXY_MAX_BODY_BYTES, DEFAULT_PROXY_TIMEOUT_MS } from '../capture/proxyEndpoint'\nimport type { CaptureSlot } from '../capture/slots'\nimport { GOALS_SLUG } from '../goals/collection'\nimport { GOAL_SLUG_PATTERN, type Goal } from '../goals/types'\nimport { PROVIDERS_SLUG } from '../providers/collection'\nimport { TIMEFRAME_PRESETS, type TimeframePreset } from '../timeframe/presets'\nimport type { TranslationsOption } from '../translations'\nimport { METRIC_KEYS } from '../translations/metricKeys'\nimport type { CustomWidgetDef } from '../widgets/customWidget'\nimport type { CaptureClientKind } from './capture'\nimport type { AnalyticsAdapter, MetricKey } from './contract'\n\nconst DEFAULT_WARM_CRON = '*/30 * * * *'\nconst DEFAULT_SYNC_CRON = '0 */6 * * *'\nconst DEFAULT_SYNC_COLLECTION = 'analytics-daily'\nconst DEFAULT_SYNC_LOOKBACK = 3\nconst DEFAULT_SCOPE_FIELD = 'scope'\nconst DEFAULT_TIMEOUT_MS = 15_000\n\n/**\n * Maps a request to its analytics boundary (tenant id, site key). Null means the\n * whole install, which is the default single-site behavior. With a multi-tenant\n * plugin, return the request's tenant id here.\n */\nexport type ScopeResolver = (args: {\n\treq: PayloadRequest\n}) => string | null | Promise<string | null>\n\n/**\n * Resolves the IANA reporting timezone a read's (or ingest's) day boundaries align\n * to. Receives the request and its already-resolved scope, so per-tenant, per-user\n * (`req.user`), and selector (cookie/preference) strategies are all expressible.\n * Return `null` to fall back to UTC.\n */\nexport type TimezoneResolver = (args: {\n\treq: PayloadRequest\n\tscope: string | null\n}) => string | null | Promise<string | null>\n\n/**\n * Enumerates the tenant scopes the cron tiers (cache warming, sync) fan out over.\n * Absent, each tier runs once for the install-wide scope.\n */\nexport type ScopesResolver = (args: { payload: Payload }) => string[] | Promise<string[]>\n\n/**\n * Escape hatch replacing the provider-collection lookup: return the runtime\n * adapters for a scope yourself (any store, any shape). Results are layered onto\n * the static config adapters exactly like collection-resolved ones, but are not\n * cached; memoize inside the function if lookups are expensive.\n */\nexport type ProvidersResolve = (args: {\n\tpayload: Payload\n\treq?: PayloadRequest\n\tscope: string | null\n}) => AnalyticsAdapter[] | Promise<AnalyticsAdapter[]>\n\nexport type ProvidersCollectionOptions = {\n\tslug?: string\n\t/**\n\t * Field matched against the resolved scope when looking up a scope's providers.\n\t * Point it at a tenant plugin's field (e.g. 'tenant') when that plugin manages\n\t * scoping for the collection.\n\t */\n\tscopeField?: string\n\toverrides?: (collection: CollectionConfig) => CollectionConfig\n\taccess?: Partial<CollectionConfig['access']>\n\t/**\n\t * Dedicated key ring for the stored provider credentials. Unset, the\n\t * fields plugin's global `encrypted.keys` applies, and with neither the\n\t * ring derives from the Payload secret. Configure a dedicated key for\n\t * anything beyond a dev install.\n\t */\n\tencryption?: { keys?: KeysConfig }\n}\n\nexport type ProvidersOptions = {\n\t/** Opt-in admin collection storing runtime provider configurations. */\n\tcollection?: boolean | ProvidersCollectionOptions\n\tresolve?: ProvidersResolve\n}\n\n/** Access checker for cross-scope (platform) analytics reads. */\nexport type PlatformReadAccess = (args: { req: PayloadRequest }) => boolean | Promise<boolean>\n\n/** Access checker for authenticated analytics reads. */\nexport type AnalyticsReadAccess = (args: { req: PayloadRequest }) => boolean | Promise<boolean>\n\n/** Access checker for the analytics admin view. */\nexport type AnalyticsViewAccess = (args: { req: PayloadRequest }) => boolean | Promise<boolean>\n\nexport type AnalyticsAccessOptions = {\n\t/**\n\t * Gates every authenticated read endpoint: query, document panel, realtime, sources\n\t * and goals. Defaults to any authenticated user; narrow it to a role check to keep\n\t * analytics away from admins who should not see them. Scope gating is separate and\n\t * always applies: granting `read` never widens which scope a user reads.\n\t */\n\tread?: AnalyticsReadAccess\n\t/**\n\t * Gates cross-scope reads: explicit `scope: '*'` reads, and scoped reads through\n\t * a shared config adapter that cannot filter by scope. Scoped installs\n\t * (`scopeResolver` configured) default to deny; configure it, for example a role\n\t * check, so platform admins can read cross-scope and manage every tenant's\n\t * providers. Unscoped installs default to any authenticated admin-panel user.\n\t */\n\tplatformRead?: PlatformReadAccess\n\t/**\n\t * Gates the analytics admin view. Defaults to `read`, so one gate covers the view and\n\t * the endpoints behind it. A reader this denies still sees the nav link (it is a client\n\t * component with no access context) and lands on the view's no-access message.\n\t */\n\tview?: AnalyticsViewAccess\n}\n\nexport type ConsentMode = 'none' | 'required'\n\n/** Per-slot consent decision, evaluated against the slot's resolved adapter. */\nexport type ConsentResolver = (args: { slot: CaptureSlot; adapterId: string }) => ConsentMode\n\n/** An adapter id to fill a capture slot with, or `false` to leave it deliberately empty. */\nexport type CaptureSlotOption = string | false\n\n/**\n * A bare mode applies to every slot; a resolver decides per request-resolved adapter; the\n * object form maps ids and slots, with an adapter entry winning over a slot entry. Every\n * form overrides the default, which is `none` for the cookieless native tracker and\n * `required` for a vendor's.\n */\nexport type CaptureConsentOption =\n\t| ConsentMode\n\t| ConsentResolver\n\t| {\n\t\t\tslots?: Partial<Record<CaptureSlot, ConsentMode>>\n\t\t\t/**\n\t\t\t * Keyed by adapter id. A bare id must name a config adapter; a runtime provider\n\t\t\t * instance id (`<provider>:<instance>`) is taken on trust, since the providers it\n\t\t\t * comes from are only resolved per request.\n\t\t\t */\n\t\t\tadapters?: Record<string, ConsentMode>\n\t }\n\n/** The normalized policy the runtime evaluates; `kind` carries the adapter's tracker family. */\nexport type ConsentPolicy = (\n\tslot: CaptureSlot,\n\tadapterId: string,\n\tkind: CaptureClientKind\n) => ConsentMode\n\nexport type AutoCaptureOptions = {\n\tscrollDepth?: boolean\n\toutboundLinks?: boolean\n\tfileDownloads?: boolean\n\tgoalAttribute?: boolean\n\t/**\n\t * Send each pageview's query string so ingest can extract its utm keys. The raw query is\n\t * never stored, only the five campaign values; set false to stop sending it at all.\n\t */\n\tquery?: boolean\n}\n\nexport type ResolvedAutoCapture = Required<AutoCaptureOptions>\n\nexport type AnalyticsGoalsCollectionOptions = {\n\t/** Set false to keep the object form's other settings while leaving the collection off. */\n\tenabled?: boolean\n\tslug?: string\n\t/**\n\t * Field matched against the resolved scope when looking up a scope's goals. Point it at\n\t * a tenant plugin's field (e.g. 'tenant') when that plugin manages scoping.\n\t */\n\tscopeField?: string\n\toverrides?: (collection: CollectionConfig) => CollectionConfig\n\taccess?: Partial<CollectionConfig['access']>\n}\n\n/** Goals as config, plus the opt-in collection editors manage their own goals through. */\nexport type AnalyticsGoalsOptions = {\n\tdefaults?: Goal[]\n\t/** Opt-in admin collection whose goals merge over `defaults`, by slug, per scope. */\n\tcollection?: boolean | AnalyticsGoalsCollectionOptions\n}\n\nexport type AnalyticsCaptureOptions = {\n\t/**\n\t * Which adapter fills each capture slot, overriding the defaults: `global` is the\n\t * designated `platformAdapter`, or the single config adapter when only one is\n\t * configured; `tenant` is the resolved scope's default adapter. A `global` id must\n\t * name a config adapter; a `tenant` id may also name a runtime provider instance,\n\t * so it is resolved per request rather than validated at config time.\n\t *\n\t * `false` disables a slot outright: it fills with nothing, its proxy mount 404s, and\n\t * the tracker config omits it. Use it to keep a default from filling a slot at all.\n\t */\n\tslots?: { global?: CaptureSlotOption; tenant?: CaptureSlotOption }\n\t/**\n\t * Mount each slot's snippet points at. Defaults to the runtime proxy endpoint\n\t * (`<routes.api>/analytics/p/<slot>`); set it when the slot is served through Next\n\t * rewrites instead, passing the same path `captureRewrites` was mounted at.\n\t */\n\tpaths?: { global?: string; tenant?: string }\n\t/** Whether a slot's tracker waits for consent. Native defaults to no gate, vendors to one. */\n\tconsent?: CaptureConsentOption\n\t/** Browser auto-capture listeners, all on by default except `scrollDepth`. */\n\tautoCapture?: AutoCaptureOptions\n\t/** Limits for the public runtime capture proxy, separate from the read-path `cache`. */\n\tproxy?: {\n\t\t/**\n\t\t * Deadline for the upstream response headers, in ms. Default 10000. The body\n\t\t * download is not on the clock, so a large tracker bundle streams to completion.\n\t\t */\n\t\ttimeoutMs?: number\n\t\t/**\n\t\t * Largest proxied request body, in bytes. Default 1 MiB, which clears a PostHog\n\t\t * batch carrying session-replay data. Anything larger is refused with 413.\n\t\t */\n\t\tmaxBodyBytes?: number\n\t}\n}\n\nexport type AnalyticsViewOptions = {\n\t/** Admin path the view mounts at, under `routes.admin`. Default `/analytics`. */\n\tpath?: `/${string}`\n\t/** Timeframe the view opens on before the URL says otherwise. Default `last30days`. */\n\tdefaultRange?: TimeframePreset\n\t/** Metric the cards and the trend open on. Default `pageviews`. */\n\tdefaultMetric?: MetricKey\n\t/**\n\t * Nav link label. A string is used as-is; a map is keyed by admin language code and\n\t * falls back to `en`. Unset, the plugin's own translated label applies.\n\t */\n\tnavLabel?: string | Record<string, string>\n}\n\nexport interface ResolvedView {\n\tpath: `/${string}`\n\tdefaultRange: TimeframePreset\n\tdefaultMetric: MetricKey\n\tnavLabel?: string | Record<string, string>\n}\n\nexport type AnalyticsPluginOptions = {\n\tdisabled?: boolean\n\t/**\n\t * Per-locale overrides for this plugin's UI strings, keyed by the typed\n\t * translation keys exported from `@10x-media/analytics/i18n`. Values win over\n\t * the built-in locales key-by-key; locales the plugin does not ship are added\n\t * whole. App-level `i18n.translations` still wins over both.\n\t */\n\ttranslations?: TranslationsOption\n\tadapters?: AnalyticsAdapter[]\n\tdefaultAdapter?: string\n\tscopeResolver?: ScopeResolver\n\t/**\n\t * Enumerates the tenant scopes the cache-warming and sync cron tiers fan out\n\t * over, in addition to the install-wide (null) scope every tier already runs.\n\t * Unset, those tiers run once for the whole install, same as before.\n\t */\n\tscopes?: ScopesResolver\n\t/**\n\t * IANA reporting timezone that day boundaries (timeframe windows, series axes,\n\t * native rollup buckets) align to. Defaults to UTC. A string forces one timezone\n\t * (the single-tenant / no-multi-tenancy case); a resolver derives it per request\n\t * from the scope, user, or a selector. Native rollups bucket at ingest in the\n\t * resolved timezone, so changing it does not re-bucket existing history.\n\t */\n\treportingTimezone?: string | TimezoneResolver\n\tproviders?: ProvidersOptions\n\t/**\n\t * Id of one config adapter shared by every scope (the platform's own analytics,\n\t * e.g. a PostHog project capturing all tenants). Included in each scope's\n\t * registry like any config adapter; reads through it are scope-filtered only\n\t * when the adapter supports scoped queries, otherwise they are cross-scope and\n\t * require `access.platformRead`.\n\t */\n\tplatformAdapter?: string\n\taccess?: AnalyticsAccessOptions\n\t/**\n\t * The analytics admin view and its nav link, on by default. `false` registers neither;\n\t * the read endpoints stay mounted either way, so a custom surface keeps working.\n\t */\n\tview?: false | AnalyticsViewOptions\n\tcapture?: AnalyticsCaptureOptions\n\t/**\n\t * Conversion goals the tracker and the native ingest match events against. Slugs must\n\t * be unique and kebab-case; only the slug and its match reach the browser.\n\t */\n\tgoals?: Goal[] | AnalyticsGoalsOptions\n\t/**\n\t * Per-collection bindings, keyed by collection slug. With generated types\n\t * augmented, each slug's resolvers receive that collection's typed document.\n\t */\n\tcollections?: { [TSlug in CollectionSlug]?: AnalyticsBinding<TSlug> }\n\tcache?: {\n\t\tttl?: { aggregate?: number; realtime?: number }\n\t\twarm?: boolean | { cron?: string }\n\t\t/** Per-read provider timeout in ms, spanning retries and limiter waits. Default 15000. */\n\t\ttimeoutMs?: number\n\t}\n\twidgets?:\n\t\t| boolean\n\t\t| {\n\t\t\t\tdisabled?: string[]\n\t\t\t\tregister?: CustomWidgetDef[]\n\t\t\t\t/**\n\t\t\t\t * Marks the free-text widget config fields (each widget's Title) as\n\t\t\t\t * `localized`. Off by default; takes effect only when the Payload config\n\t\t\t\t * enables localization (Payload strips the flag otherwise).\n\t\t\t\t */\n\t\t\t\tlocalizeText?: boolean\n\t\t\t\t/**\n\t\t\t\t * Period-over-period comparison on the metric and trend widgets. On by\n\t\t\t\t * default for every source except one whose adapter sets\n\t\t\t\t * `capabilities.comparison` false; set false to skip the second\n\t\t\t\t * (previous-window) read entirely.\n\t\t\t\t */\n\t\t\t\tcomparison?: boolean\n\t\t }\n\t/**\n\t * Opt-in sync tier: a cron job that persists each provider's daily metrics into a\n\t * queryable collection. Reads go through the surfacing cache, so persisted rows reflect\n\t * cached values up to `cache.ttl.aggregate` old; keep that TTL below the sync interval\n\t * for the freshest data.\n\t */\n\tsync?:\n\t\t| boolean\n\t\t| {\n\t\t\t\tcollectionSlug?: CollectionSlug\n\t\t\t\tcron?: string\n\t\t\t\tlookbackDays?: number\n\t\t\t\tadapters?: string[]\n\t\t\t\t/** Surface the analytics-daily collection in the admin nav. Default false (hidden). */\n\t\t\t\thidden?: boolean\n\t\t }\n}\n\nexport interface ResolvedCapture {\n\tslots: { global?: CaptureSlotOption; tenant?: CaptureSlotOption }\n\tpaths: { global?: string; tenant?: string }\n\tconsent: ConsentPolicy\n\tautoCapture: ResolvedAutoCapture\n\tproxy: { timeoutMs: number; maxBodyBytes: number }\n}\n\nexport interface ResolvedOptions {\n\tadapters: AnalyticsAdapter[]\n\tdefaultAdapter?: string\n\tscopeResolver: ScopeResolver\n\t/** True when the app configured a scopeResolver (scoped install). */\n\tscoped: boolean\n\t/** Raw scopes option; undefined runs the cron tiers install-wide only. */\n\tscopes?: ScopesResolver\n\t/** Raw reportingTimezone option; normalized into a resolver at init. */\n\treportingTimezone?: string | TimezoneResolver\n\tplatformAdapter?: string\n\taccess: {\n\t\tplatformRead: PlatformReadAccess\n\t\tread: AnalyticsReadAccess\n\t\tview: AnalyticsViewAccess\n\t}\n\t/** The admin view, filled with its defaults, or false when the app turned it off. */\n\tview: false | ResolvedView\n\tcapture: ResolvedCapture\n\t/** Config goals, validated; the goals collection layers its own on top of these. */\n\tgoals: Goal[]\n\tgoalsCollection: {\n\t\tenabled: boolean\n\t\tslug: string\n\t\tscopeField: string\n\t\toverrides?: (collection: CollectionConfig) => CollectionConfig\n\t\taccess?: Partial<CollectionConfig['access']>\n\t}\n\tproviders: {\n\t\tcollection: {\n\t\t\tenabled: boolean\n\t\t\tslug: string\n\t\t\tscopeField: string\n\t\t\toverrides?: (collection: CollectionConfig) => CollectionConfig\n\t\t\taccess?: Partial<CollectionConfig['access']>\n\t\t\tencryption?: { keys?: KeysConfig }\n\t\t}\n\t\tresolve?: ProvidersResolve\n\t}\n\tbindings: Record<string, ResolvedBinding>\n\tcache: {\n\t\t/** Undefined when unset: adapter recommendedTtl is the fallback, an explicit value wins. */\n\t\tttl: { aggregate?: number; realtime?: number }\n\t\twarm: { enabled: boolean; cron: string }\n\t\ttimeoutMs: number\n\t}\n\twidgets: {\n\t\tenabled: boolean\n\t\tdisabled: string[]\n\t\tregister: CustomWidgetDef[]\n\t\tlocalizeText: boolean\n\t\tcomparison: boolean\n\t}\n\tsync: {\n\t\tenabled: boolean\n\t\tcollectionSlug: string\n\t\tcron: string\n\t\tlookbackDays: number\n\t\tadapters?: string[]\n\t\t/** True hides the analytics-daily collection from the admin nav (default). */\n\t\thidden: boolean\n\t}\n}\n\n/** Scroll depth is the one listener off by default: it fires on every page, for every visitor. */\nexport const DEFAULT_AUTO_CAPTURE: ResolvedAutoCapture = {\n\tscrollDepth: false,\n\toutboundLinks: true,\n\tfileDownloads: true,\n\tgoalAttribute: true,\n\tquery: true,\n}\n\nconst resolveAutoCapture = (option: AutoCaptureOptions | undefined): ResolvedAutoCapture => ({\n\tscrollDepth: option?.scrollDepth ?? DEFAULT_AUTO_CAPTURE.scrollDepth,\n\toutboundLinks: option?.outboundLinks ?? DEFAULT_AUTO_CAPTURE.outboundLinks,\n\tfileDownloads: option?.fileDownloads ?? DEFAULT_AUTO_CAPTURE.fileDownloads,\n\tgoalAttribute: option?.goalAttribute ?? DEFAULT_AUTO_CAPTURE.goalAttribute,\n\tquery: option?.query ?? DEFAULT_AUTO_CAPTURE.query,\n})\n\n/** Cookieless native capture needs no consent gate; a vendor's tracker does. */\nexport const defaultConsentFor = (kind: CaptureClientKind): ConsentMode =>\n\tkind === 'native' ? 'none' : 'required'\n\nconst resolveConsent = (\n\toption: CaptureConsentOption | undefined,\n\tadapters: AnalyticsAdapter[]\n): ConsentPolicy => {\n\tif (option === 'none' || option === 'required') {\n\t\treturn () => option\n\t}\n\tif (typeof option === 'function') {\n\t\treturn (slot, adapterId) => option({ slot, adapterId })\n\t}\n\tfor (const id of Object.keys(option?.adapters ?? {})) {\n\t\t// A runtime provider instance id is `<provider>:<instance>` and only exists once a\n\t\t// scope resolves, so it cannot be checked here; a bare id must name a config adapter.\n\t\tif (!id.includes(':') && !adapters.some((a) => a.id === id)) {\n\t\t\tthrow new Error(`analytics: unknown consent adapter \"${id}\"`)\n\t\t}\n\t}\n\treturn (slot, adapterId, kind) =>\n\t\toption?.adapters?.[adapterId] ?? option?.slots?.[slot] ?? defaultConsentFor(kind)\n}\n\nconst resolveGoals = (option: AnalyticsPluginOptions['goals']): Goal[] => {\n\tconst goals = Array.isArray(option) ? option : (option?.defaults ?? [])\n\tconst seen = new Set<string>()\n\tfor (const goal of goals) {\n\t\tif (!GOAL_SLUG_PATTERN.test(goal.slug)) {\n\t\t\tthrow new Error(`analytics: goal slug \"${goal.slug}\" must be kebab-case`)\n\t\t}\n\t\tif (seen.has(goal.slug)) {\n\t\t\tthrow new Error(`analytics: duplicate goal slug \"${goal.slug}\"`)\n\t\t}\n\t\tconst fixed = goal.value?.fixed\n\t\t// Revenue is money: a negative or non-finite fixed value would be silently ignored at\n\t\t// ingest, so it fails the boot instead.\n\t\tif (fixed !== undefined && (!Number.isFinite(fixed) || fixed < 0)) {\n\t\t\tthrow new Error(\n\t\t\t\t`analytics: goal \"${goal.slug}\" value.fixed must be a finite number >= 0, got ${String(fixed)}`\n\t\t\t)\n\t\t}\n\t\tseen.add(goal.slug)\n\t}\n\treturn goals\n}\n\nconst resolveGoalsCollection = (\n\toption: AnalyticsPluginOptions['goals']\n): ResolvedOptions['goalsCollection'] => {\n\tconst off = { enabled: false, slug: GOALS_SLUG, scopeField: DEFAULT_SCOPE_FIELD }\n\tconst collection = Array.isArray(option) ? undefined : option?.collection\n\tif (!collection) {\n\t\treturn off\n\t}\n\tconst resolved =\n\t\tcollection === true\n\t\t\t? { ...off, enabled: true }\n\t\t\t: {\n\t\t\t\t\tenabled: collection.enabled ?? true,\n\t\t\t\t\tslug: collection.slug ?? GOALS_SLUG,\n\t\t\t\t\tscopeField: collection.scopeField ?? DEFAULT_SCOPE_FIELD,\n\t\t\t\t\toverrides: collection.overrides,\n\t\t\t\t\taccess: collection.access,\n\t\t\t\t}\n\tif (!resolved.enabled) {\n\t\treturn off\n\t}\n\tif (typeof resolved.slug !== 'string' || resolved.slug.trim() === '') {\n\t\tthrow new Error('analytics: goals.collection.slug must be a non-empty collection slug')\n\t}\n\tif (resolved.scopeField.trim() === '') {\n\t\tthrow new Error('analytics: goals.collection.scopeField must be a non-empty field name')\n\t}\n\tif (resolved.scopeField.includes('.')) {\n\t\tthrow new Error(\n\t\t\t'analytics: goals.collection.scopeField must be a top-level field name (no dots); the scope stamp writes it as a flat key'\n\t\t)\n\t}\n\treturn { ...resolved, slug: resolved.slug.trim() }\n}\n\nexport const DEFAULT_VIEW: ResolvedView = {\n\tpath: '/analytics',\n\tdefaultRange: 'last30days',\n\tdefaultMetric: 'pageviews',\n}\n\nconst resolveView = (option: AnalyticsPluginOptions['view']): false | ResolvedView => {\n\tif (option === false) {\n\t\treturn false\n\t}\n\tconst path = option?.path ?? DEFAULT_VIEW.path\n\tif (typeof path !== 'string' || !path.startsWith('/')) {\n\t\tthrow new Error(`analytics: view.path must start with \"/\", got \"${String(path)}\"`)\n\t}\n\tconst defaultRange = option?.defaultRange ?? DEFAULT_VIEW.defaultRange\n\tif (!TIMEFRAME_PRESETS.includes(defaultRange)) {\n\t\tthrow new Error(`analytics: unknown view.defaultRange \"${String(defaultRange)}\"`)\n\t}\n\tconst defaultMetric = option?.defaultMetric ?? DEFAULT_VIEW.defaultMetric\n\tif (!(defaultMetric in METRIC_KEYS)) {\n\t\tthrow new Error(`analytics: unknown view.defaultMetric \"${String(defaultMetric)}\"`)\n\t}\n\treturn {\n\t\tpath,\n\t\tdefaultRange,\n\t\tdefaultMetric,\n\t\t...(option?.navLabel !== undefined ? { navLabel: option.navLabel } : {}),\n\t}\n}\n\nconst resolveBindings = (\n\tcollections: AnalyticsPluginOptions['collections']\n): Record<string, ResolvedBinding> => {\n\tconst out: Record<string, ResolvedBinding> = {}\n\tfor (const [slug, binding] of Object.entries(collections ?? {})) {\n\t\tif (!binding) continue\n\t\tif (!binding.path && !binding.pathField) {\n\t\t\tthrow new Error(`analytics: binding for \"${slug}\" needs a path resolver or a pathField`)\n\t\t}\n\t\t// Erases the per-slug doc generic; safe because the runtime only ever hands\n\t\t// a binding documents from its own collection.\n\t\tout[slug] = binding as ResolvedBinding\n\t}\n\treturn out\n}\n\nexport function resolveOptions(options: AnalyticsPluginOptions): ResolvedOptions {\n\tif (!options.adapters || options.adapters.length === 0) {\n\t\tthrow new Error('analytics: at least one adapter is required')\n\t}\n\tif (\n\t\toptions.platformAdapter !== undefined &&\n\t\t!options.adapters.some((a) => a.id === options.platformAdapter)\n\t) {\n\t\tthrow new Error(`analytics: unknown platform adapter \"${options.platformAdapter}\"`)\n\t}\n\tfor (const [slot, value] of Object.entries(options.capture?.slots ?? {})) {\n\t\tif (value !== false && typeof value !== 'string' && value !== undefined) {\n\t\t\tthrow new Error(\n\t\t\t\t`analytics: capture slot \"${slot}\" must be an adapter id or false, got ${typeof value}`\n\t\t\t)\n\t\t}\n\t}\n\tconst globalSlot = options.capture?.slots?.global\n\t// A tenant id may name a runtime provider instance, which only exists once a scope\n\t// resolves; a global one can only come from the config registry, so it is checked here.\n\tif (typeof globalSlot === 'string' && !options.adapters.some((a) => a.id === globalSlot)) {\n\t\tthrow new Error(`analytics: unknown global capture slot adapter \"${globalSlot}\"`)\n\t}\n\tconst widgets =\n\t\toptions.widgets === false\n\t\t\t? {\n\t\t\t\t\tenabled: false,\n\t\t\t\t\tdisabled: [] as string[],\n\t\t\t\t\tregister: [] as CustomWidgetDef[],\n\t\t\t\t\tlocalizeText: false,\n\t\t\t\t\tcomparison: true,\n\t\t\t\t}\n\t\t\t: options.widgets === undefined || options.widgets === true\n\t\t\t\t? {\n\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\tdisabled: [] as string[],\n\t\t\t\t\t\tregister: [] as CustomWidgetDef[],\n\t\t\t\t\t\tlocalizeText: false,\n\t\t\t\t\t\tcomparison: true,\n\t\t\t\t\t}\n\t\t\t\t: {\n\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\tdisabled: options.widgets.disabled ?? [],\n\t\t\t\t\t\tregister: options.widgets.register ?? [],\n\t\t\t\t\t\tlocalizeText: options.widgets.localizeText ?? false,\n\t\t\t\t\t\tcomparison: options.widgets.comparison ?? true,\n\t\t\t\t\t}\n\tconst warmOpt = options.cache?.warm\n\tconst warm =\n\t\twarmOpt === true\n\t\t\t? { enabled: true, cron: DEFAULT_WARM_CRON }\n\t\t\t: warmOpt && typeof warmOpt === 'object'\n\t\t\t\t? { enabled: true, cron: warmOpt.cron ?? DEFAULT_WARM_CRON }\n\t\t\t\t: { enabled: false, cron: DEFAULT_WARM_CRON }\n\tconst collectionOpt = options.providers?.collection\n\tconst providers = {\n\t\tcollection:\n\t\t\tcollectionOpt === true\n\t\t\t\t? { enabled: true, slug: PROVIDERS_SLUG, scopeField: DEFAULT_SCOPE_FIELD }\n\t\t\t\t: collectionOpt && typeof collectionOpt === 'object'\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\t\tslug: collectionOpt.slug ?? PROVIDERS_SLUG,\n\t\t\t\t\t\t\tscopeField: collectionOpt.scopeField ?? DEFAULT_SCOPE_FIELD,\n\t\t\t\t\t\t\toverrides: collectionOpt.overrides,\n\t\t\t\t\t\t\taccess: collectionOpt.access,\n\t\t\t\t\t\t\tencryption: collectionOpt.encryption,\n\t\t\t\t\t\t}\n\t\t\t\t\t: { enabled: false, slug: PROVIDERS_SLUG, scopeField: DEFAULT_SCOPE_FIELD },\n\t\tresolve: options.providers?.resolve,\n\t}\n\tif (providers.collection.enabled) {\n\t\tif (providers.collection.scopeField.trim() === '') {\n\t\t\tthrow new Error('analytics: providers.collection.scopeField must be a non-empty field name')\n\t\t}\n\t\tif (providers.collection.scopeField.includes('.')) {\n\t\t\tthrow new Error(\n\t\t\t\t'analytics: providers.collection.scopeField must be a top-level field name (no dots); the scope stamp writes it as a flat key'\n\t\t\t)\n\t\t}\n\t}\n\tconst syncOpt = options.sync\n\tconst sync =\n\t\tsyncOpt === true\n\t\t\t? {\n\t\t\t\t\tenabled: true,\n\t\t\t\t\tcollectionSlug: DEFAULT_SYNC_COLLECTION,\n\t\t\t\t\tcron: DEFAULT_SYNC_CRON,\n\t\t\t\t\tlookbackDays: DEFAULT_SYNC_LOOKBACK,\n\t\t\t\t\thidden: true,\n\t\t\t\t}\n\t\t\t: syncOpt && typeof syncOpt === 'object'\n\t\t\t\t? {\n\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\tcollectionSlug: syncOpt.collectionSlug ?? DEFAULT_SYNC_COLLECTION,\n\t\t\t\t\t\tcron: syncOpt.cron ?? DEFAULT_SYNC_CRON,\n\t\t\t\t\t\tlookbackDays: syncOpt.lookbackDays ?? DEFAULT_SYNC_LOOKBACK,\n\t\t\t\t\t\tadapters: syncOpt.adapters,\n\t\t\t\t\t\thidden: syncOpt.hidden ?? true,\n\t\t\t\t\t}\n\t\t\t\t: {\n\t\t\t\t\t\tenabled: false,\n\t\t\t\t\t\tcollectionSlug: DEFAULT_SYNC_COLLECTION,\n\t\t\t\t\t\tcron: DEFAULT_SYNC_CRON,\n\t\t\t\t\t\tlookbackDays: DEFAULT_SYNC_LOOKBACK,\n\t\t\t\t\t\thidden: true,\n\t\t\t\t\t}\n\tconst scoped = options.scopeResolver !== undefined\n\t// The view gate defaults to this exact function, so one `access.read` covers both.\n\tconst read: AnalyticsReadAccess = options.access?.read ?? (({ req }) => Boolean(req.user))\n\treturn {\n\t\tadapters: options.adapters,\n\t\tdefaultAdapter: options.defaultAdapter,\n\t\tscopeResolver: options.scopeResolver ?? (() => null),\n\t\tscoped,\n\t\tscopes: options.scopes,\n\t\treportingTimezone: options.reportingTimezone,\n\t\tplatformAdapter: options.platformAdapter,\n\t\taccess: {\n\t\t\tplatformRead:\n\t\t\t\toptions.access?.platformRead ?? (scoped ? () => false : ({ req }) => Boolean(req.user)),\n\t\t\tread,\n\t\t\tview: options.access?.view ?? read,\n\t\t},\n\t\tview: resolveView(options.view),\n\t\tcapture: {\n\t\t\tslots: {\n\t\t\t\tglobal: options.capture?.slots?.global,\n\t\t\t\ttenant: options.capture?.slots?.tenant,\n\t\t\t},\n\t\t\tpaths: {\n\t\t\t\tglobal: options.capture?.paths?.global,\n\t\t\t\ttenant: options.capture?.paths?.tenant,\n\t\t\t},\n\t\t\tconsent: resolveConsent(options.capture?.consent, options.adapters),\n\t\t\tautoCapture: resolveAutoCapture(options.capture?.autoCapture),\n\t\t\tproxy: {\n\t\t\t\ttimeoutMs: options.capture?.proxy?.timeoutMs ?? DEFAULT_PROXY_TIMEOUT_MS,\n\t\t\t\tmaxBodyBytes: options.capture?.proxy?.maxBodyBytes ?? DEFAULT_PROXY_MAX_BODY_BYTES,\n\t\t\t},\n\t\t},\n\t\tgoals: resolveGoals(options.goals),\n\t\tgoalsCollection: resolveGoalsCollection(options.goals),\n\t\tproviders,\n\t\tbindings: resolveBindings(options.collections),\n\t\tcache: {\n\t\t\t// Left undefined when the app did not set them so the adapter's recommendedTtl\n\t\t\t// applies as the default; an explicit value overrides the adapter recommendation.\n\t\t\tttl: {\n\t\t\t\taggregate: options.cache?.ttl?.aggregate,\n\t\t\t\trealtime: options.cache?.ttl?.realtime,\n\t\t\t},\n\t\t\twarm,\n\t\t\ttimeoutMs: options.cache?.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n\t\t},\n\t\twidgets,\n\t\tsync,\n\t}\n}\n"],"mappings":";;;;;;;AAeA,MAAM,oBAAoB;AAC1B,MAAM,oBAAoB;AAC1B,MAAM,0BAA0B;AAChC,MAAM,wBAAwB;AAC9B,MAAM,sBAAsB;AAC5B,MAAM,qBAAqB;;AAwY3B,MAAa,uBAA4C;CACxD,aAAa;CACb,eAAe;CACf,eAAe;CACf,eAAe;CACf,OAAO;AACR;AAEA,MAAM,sBAAsB,YAAiE;CAC5F,aAAa,QAAQ,eAAe,qBAAqB;CACzD,eAAe,QAAQ,iBAAiB,qBAAqB;CAC7D,eAAe,QAAQ,iBAAiB,qBAAqB;CAC7D,eAAe,QAAQ,iBAAiB,qBAAqB;CAC7D,OAAO,QAAQ,SAAS,qBAAqB;AAC9C;;AAGA,MAAa,qBAAqB,SACjC,SAAS,WAAW,SAAS;AAE9B,MAAM,kBACL,QACA,aACmB;CACnB,IAAI,WAAW,UAAU,WAAW,YACnC,aAAa;CAEd,IAAI,OAAO,WAAW,YACrB,QAAQ,MAAM,cAAc,OAAO;EAAE;EAA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AAU,QAAQ,IAAI,IAAI;GACtF;GACA,MAAM,QAAQ,QAAQ,QAAQ;EAC/B;EACA,MAAM,YAAY,QAAQ,IAAI;EAC9B,SAAS;GACR,OAAO;IACN,QAAQ,QAAQ,SAAS,OAAO;IAChC,QAAQ,QAAQ,SAAS,OAAO;GACjC;GACA,OAAO;IACN,QAAQ,QAAQ,SAAS,OAAO;IAChC,QAAQ,QAAQ,SAAS,OAAO;GACjC;GACA,SAAS,eAAe,QAAQ,SAAS,SAAS,QAAQ,QAAQ;GAClE,aAAa,mBAAmB,QAAQ,SAAS,WAAW;GAC5D,OAAO;IACN,WAAW,QAAQ,SAAS,OAAO,aAAA;IACnC,cAAc,QAAQ,SAAS,OAAO,gBAAA;GACvC;EACD;EACA,OAAO,aAAa,QAAQ,KAAK;EACjC,iBAAiB,uBAAuB,QAAQ,KAAK;EACrD;EACA,UAAU,gBAAgB,QAAQ,WAAW;EAC7C,OAAO;GAGN,KAAK;IACJ,WAAW,QAAQ,OAAO,KAAK;IAC/B,UAAU,QAAQ,OAAO,KAAK;GAC/B;GACA;GACA,WAAW,QAAQ,OAAO,aAAa;EACxC;EACA;EACA;CACD;AACD"}
@@ -7,11 +7,13 @@ import { PayloadRequest } from "payload";
7
7
  * they mean on the wire (and go through the same sanitizers); the rest say what the server
8
8
  * knows that a browser request would otherwise have said for itself.
9
9
  */
10
- type ServerEventInput = Pick<RawEventInput, 'type' | 'name' | 'path' | 'hostname' | 'referrer' | 'props' | 'value' | 'currency'> & {
10
+ type ServerEventInput = Pick<RawEventInput, 'type' | 'name' | 'path' | 'hostname' | 'referrer' | 'query' | 'props' | 'value' | 'currency'> & {
11
11
  /**
12
12
  * Attribution inputs, overlaid on `opts.req`'s own headers when there is a request.
13
13
  * With neither, the event is attributed to the day's synthetic server visitor and
14
- * reports no device. No IP is ever fabricated.
14
+ * reports no device, browser, OS or language: those are read off the request's headers,
15
+ * and inventing them would put a fabricated visitor in every breakdown. No IP is ever
16
+ * fabricated either.
15
17
  */
16
18
  ip?: string;
17
19
  userAgent?: string;
@@ -1 +1 @@
1
- {"version":3,"file":"serverEvent.js","names":[],"sources":["../../src/core/serverEvent.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport type { RawEventInput } from '../native/ingest/normalizeEvent'\n\n/**\n * One event recorded from server code. The fields a browser event carries mean exactly what\n * they mean on the wire (and go through the same sanitizers); the rest say what the server\n * knows that a browser request would otherwise have said for itself.\n */\nexport type ServerEventInput = Pick<\n\tRawEventInput,\n\t'type' | 'name' | 'path' | 'hostname' | 'referrer' | 'props' | 'value' | 'currency'\n> & {\n\t/**\n\t * Attribution inputs, overlaid on `opts.req`'s own headers when there is a request.\n\t * With neither, the event is attributed to the day's synthetic server visitor and\n\t * reports no device. No IP is ever fabricated.\n\t */\n\tip?: string\n\tuserAgent?: string\n\t/**\n\t * Analytics boundary to stamp; null is install-wide. Unset resolves from `opts.req`.\n\t * Ignored on an unscoped install, and never validated against the scopes that exist.\n\t */\n\tscope?: string | null\n\t/** IANA reporting timezone the rollup day bucket is computed in. */\n\ttimezone?: string\n\t/** Event time; defaults to now. */\n\tnow?: Date\n}\n\nexport interface ServerTrackOptions {\n\t/** The request the event belongs to: attribution, scope and timezone all come from it. */\n\treq?: PayloadRequest\n\t/**\n\t * Wait for the write to land. On an install with a write buffer the call otherwise\n\t * resolves as soon as the event is queued, and a failed flush only reaches the logger.\n\t */\n\tflush?: boolean\n}\n\nexport type ServerTrack = (event: ServerEventInput, opts?: ServerTrackOptions) => Promise<void>\n\n/** Thrown instead of dropping the event: a server caller can handle a rejected promise. */\nexport class AnalyticsTrackError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message)\n\t\tthis.name = 'AnalyticsTrackError'\n\t}\n}\n"],"mappings":";;AA2CA,IAAa,sBAAb,cAAyC,MAAM;CAC9C,YAAY,SAAiB;EAC5B,MAAM,OAAO;EACb,KAAK,OAAO;CACb;AACD"}
1
+ {"version":3,"file":"serverEvent.js","names":[],"sources":["../../src/core/serverEvent.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport type { RawEventInput } from '../native/ingest/normalizeEvent'\n\n/**\n * One event recorded from server code. The fields a browser event carries mean exactly what\n * they mean on the wire (and go through the same sanitizers); the rest say what the server\n * knows that a browser request would otherwise have said for itself.\n */\nexport type ServerEventInput = Pick<\n\tRawEventInput,\n\t'type' | 'name' | 'path' | 'hostname' | 'referrer' | 'query' | 'props' | 'value' | 'currency'\n> & {\n\t/**\n\t * Attribution inputs, overlaid on `opts.req`'s own headers when there is a request.\n\t * With neither, the event is attributed to the day's synthetic server visitor and\n\t * reports no device, browser, OS or language: those are read off the request's headers,\n\t * and inventing them would put a fabricated visitor in every breakdown. No IP is ever\n\t * fabricated either.\n\t */\n\tip?: string\n\tuserAgent?: string\n\t/**\n\t * Analytics boundary to stamp; null is install-wide. Unset resolves from `opts.req`.\n\t * Ignored on an unscoped install, and never validated against the scopes that exist.\n\t */\n\tscope?: string | null\n\t/** IANA reporting timezone the rollup day bucket is computed in. */\n\ttimezone?: string\n\t/** Event time; defaults to now. */\n\tnow?: Date\n}\n\nexport interface ServerTrackOptions {\n\t/** The request the event belongs to: attribution, scope and timezone all come from it. */\n\treq?: PayloadRequest\n\t/**\n\t * Wait for the write to land. On an install with a write buffer the call otherwise\n\t * resolves as soon as the event is queued, and a failed flush only reaches the logger.\n\t */\n\tflush?: boolean\n}\n\nexport type ServerTrack = (event: ServerEventInput, opts?: ServerTrackOptions) => Promise<void>\n\n/** Thrown instead of dropping the event: a server caller can handle a rejected promise. */\nexport class AnalyticsTrackError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message)\n\t\tthis.name = 'AnalyticsTrackError'\n\t}\n}\n"],"mappings":";;AA6CA,IAAa,sBAAb,cAAyC,MAAM;CAC9C,YAAY,SAAiB;EAC5B,MAAM,OAAO;EACb,KAAK,OAAO;CACb;AACD"}