@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":"readForWidgetGoals.js","names":[],"sources":["../../src/widgets/readForWidgetGoals.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport type { DateRange } from '../core/contract'\nimport { resolveReadContext } from '../core/scopedRead'\nimport {\n\ttype AnalyticsRuntime,\n\tgetRuntime,\n\tresolveGoalsDetailedFor,\n\tresolveTimezoneFor,\n} from '../plugin/runtime'\nimport { MAX_QUERY_LIMIT } from '../query/limits'\nimport { resolveTimeframe, type TimeframePreset } from '../timeframe/presets'\nimport { DEFAULT_TIMEZONE } from '../timeframe/tz'\nimport { conversionRate } from '../view/conversionRate'\nimport { previousWindow } from './comparison'\nimport { readForWidget, type WidgetReadStatus } from './readForWidget'\nimport { readForWidgetBreakdown } from './readForWidgetBreakdown'\n\nexport interface GoalRow {\n\tslug: string\n\t/** The goal's admin-facing name, or its slug when no configured goal claims it. */\n\tname: string\n\tconversions: number\n\trevenue?: number\n\t/** 0..1 share of the site's visitors, absent when either side of the ratio is missing. */\n\trate?: number\n\tpreviousConversions?: number\n}\n\nexport interface WidgetGoalsResult {\n\tstatus: WidgetReadStatus\n\tadapterId: string\n\tdateRange: DateRange\n\ttimezone: string\n\trows: GoalRow[]\n\t/** Range total the rate divides by; absent when the source does not serve visitors. */\n\tsiteVisitors?: number\n\tclamped?: boolean\n\tstale?: boolean\n}\n\nexport interface ReadForWidgetGoalsArgs {\n\treq: PayloadRequest\n\ttimeframe: TimeframePreset\n\tlimit: number\n\t/** Read the previous window too, when the source can compare. */\n\tcompare: boolean\n\tadapterId?: string\n\tnow: Date\n\trange?: DateRange\n\t/** Explicit scope override; omitted resolves via the plugin's scopeResolver. */\n\tscope?: string | null\n\t/**\n\t * Reporting timezone the caller already resolved, reused rather than resolved again so\n\t * a caller-supplied `range` is read in the very timezone it was interpreted in.\n\t */\n\ttimezone?: string\n}\n\n/**\n * How much wider than the table the previous window is read. Both windows rank by their own\n * conversions, so a goal in today's top rows may sit well below them in the previous window;\n * reading only as many rows as the table shows would drop exactly those deltas. Capped at\n * the bound every analytics query is held to.\n */\nconst PREVIOUS_LIMIT_FACTOR = 4\n\nconst previousLimit = (limit: number): number =>\n\tMath.min(limit * PREVIOUS_LIMIT_FACTOR, MAX_QUERY_LIMIT)\n\n/**\n * Goal names for the read's own scope. A resolver that throws must not cost the widget its\n * table, so the rows fall back to their slugs.\n */\nconst goalNames = async (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tscope: string | null\n): Promise<Map<string, string>> => {\n\ttry {\n\t\tconst resolved = await resolveGoalsDetailedFor(runtime, req, scope)\n\t\treturn new Map(resolved.map(({ goal }) => [goal.slug, goal.name]))\n\t} catch (err) {\n\t\treq.payload.logger?.warn(`analytics: widget goal names failed to resolve: ${String(err)}`)\n\t\treturn new Map()\n\t}\n}\n\n/**\n * The goals table behind the goals widget: conversions per goal over the window, each with\n * its revenue, its share of the site's visitors, and (when comparing) the same goal's\n * conversions in the previous window. Rows come from one `goal` breakdown read and the site\n * total from one totals read, both through the existing widget helpers so capability\n * gating, scoping and caching stay in one place. Revenue and visitors ride along only where\n * the source serves them; the status is the breakdown's, since a table without its rows has\n * nothing to show.\n */\nexport const readForWidgetGoals = async (\n\targs: ReadForWidgetGoalsArgs\n): Promise<WidgetGoalsResult> => {\n\tconst { req, timeframe, limit, compare, adapterId, now } = args\n\tconst fallback = (status: WidgetReadStatus, id: string): WidgetGoalsResult => ({\n\t\tstatus,\n\t\tadapterId: id,\n\t\tdateRange: args.range ?? resolveTimeframe(timeframe, now, args.timezone),\n\t\ttimezone: args.timezone ?? DEFAULT_TIMEZONE,\n\t\trows: [],\n\t})\n\n\tconst runtime = getRuntime(req.payload)\n\tif (!runtime) {\n\t\treturn fallback('unavailable', adapterId ?? '')\n\t}\n\tconst ctx = await resolveReadContext({ runtime, req, adapterId, scope: args.scope })\n\tif (!ctx.ok) {\n\t\treturn fallback('unavailable', adapterId ?? '')\n\t}\n\tconst adapter = ctx.adapter\n\tconst tz = args.timezone ?? (await resolveTimezoneFor(runtime, req, ctx.scope))\n\tconst dateRange = args.range ?? resolveTimeframe(timeframe, now, tz)\n\t// The sub-reads resolve their own context; pinning the adapter, scope, timezone and\n\t// window keeps all three answering about exactly the same read.\n\tconst shared = { req, timeframe, adapterId: adapter.id, scope: ctx.scope, timezone: tz, now }\n\tconst comparisonRange =\n\t\tcompare && runtime.comparison && adapter.capabilities.comparison\n\t\t\t? (previousWindow(dateRange, tz) ?? undefined)\n\t\t\t: undefined\n\n\tconst [breakdown, totals, previous, names] = await Promise.all([\n\t\treadForWidgetBreakdown({\n\t\t\t...shared,\n\t\t\trange: dateRange,\n\t\t\tmetric: 'conversions',\n\t\t\tdimension: 'goal',\n\t\t\tlimit,\n\t\t\textraMetrics: ['revenue', 'visitors'],\n\t\t}),\n\t\tadapter.capabilities.metrics.has('visitors')\n\t\t\t? // The site total is a denominator, never a delta: its own previous window would\n\t\t\t\t// be a second read nothing renders.\n\t\t\t\treadForWidget({ ...shared, range: dateRange, metrics: ['visitors'], comparison: false })\n\t\t\t: undefined,\n\t\tcomparisonRange\n\t\t\t? readForWidgetBreakdown({\n\t\t\t\t\t...shared,\n\t\t\t\t\trange: comparisonRange,\n\t\t\t\t\tmetric: 'conversions',\n\t\t\t\t\tdimension: 'goal',\n\t\t\t\t\tlimit: previousLimit(limit),\n\t\t\t\t})\n\t\t\t: undefined,\n\t\tgoalNames(runtime, req, ctx.scope),\n\t])\n\tif (breakdown.status !== 'ok') {\n\t\treturn { ...fallback(breakdown.status, breakdown.adapterId), dateRange, timezone: tz }\n\t}\n\n\tconst previousBySlug = new Map(\n\t\t(previous?.status === 'ok' ? previous.rows : []).map((row) => [row.label, row.value])\n\t)\n\tconst siteVisitors = totals?.status === 'ok' ? totals.metrics.visitors : undefined\n\tconst rows: GoalRow[] = breakdown.rows\n\t\t.map((row) => {\n\t\t\tconst rate = conversionRate(row.metrics?.visitors, siteVisitors)\n\t\t\tconst previousConversions = previousBySlug.get(row.label)\n\t\t\treturn {\n\t\t\t\tslug: row.label,\n\t\t\t\tname: names.get(row.label) ?? row.label,\n\t\t\t\tconversions: row.value,\n\t\t\t\t...(row.metrics?.revenue !== undefined ? { revenue: row.metrics.revenue } : {}),\n\t\t\t\t...(rate !== null ? { rate } : {}),\n\t\t\t\t...(previousConversions !== undefined ? { previousConversions } : {}),\n\t\t\t}\n\t\t})\n\t\t// The adapter ranks and caps already; re-applying both keeps one that does not from\n\t\t// spilling a long, unranked table into a dashboard card.\n\t\t.sort((a, b) => b.conversions - a.conversions)\n\t\t.slice(0, limit)\n\n\treturn {\n\t\tstatus: 'ok',\n\t\tadapterId: adapter.id,\n\t\tdateRange,\n\t\ttimezone: tz,\n\t\trows,\n\t\t...(siteVisitors !== undefined ? { siteVisitors } : {}),\n\t\tclamped: Boolean(breakdown.clamped || totals?.clamped || previous?.clamped),\n\t\tstale: Boolean(breakdown.stale || totals?.stale || previous?.stale),\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;AAgEA,MAAM,wBAAwB;AAE9B,MAAM,iBAAiB,UACtB,KAAK,IAAI,QAAQ,uBAAA,GAAsC;;;;;AAMxD,MAAM,YAAY,OACjB,SACA,KACA,UACkC;CAClC,IAAI;EACH,MAAM,WAAW,MAAM,wBAAwB,SAAS,KAAK,KAAK;EAClE,OAAO,IAAI,IAAI,SAAS,KAAK,EAAE,WAAW,CAAC,KAAK,MAAM,KAAK,IAAI,CAAC,CAAC;CAClE,SAAS,KAAK;EACb,IAAI,QAAQ,QAAQ,KAAK,m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/readForWidgetGoals.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport { comparisonOf } from '../core/capabilities'\nimport type { DateRange } from '../core/contract'\nimport { type AnalyticsRuntime, resolveGoalsDetailedFor } from '../plugin/runtime'\nimport { MAX_QUERY_LIMIT } from '../query/limits'\nimport type { TimeframePreset } from '../timeframe/presets'\nimport { conversionRate } from '../view/conversionRate'\nimport { previousWindow, withinLookback } from './comparison'\nimport { prepareWidgetRead, type WidgetReadStatus } from './prepareWidgetRead'\nimport { readForWidget } from './readForWidget'\nimport { readForWidgetBreakdown } from './readForWidgetBreakdown'\n\nexport interface GoalRow {\n\tslug: string\n\t/** The goal's admin-facing name, or its slug when no configured goal claims it. */\n\tname: string\n\tconversions: number\n\trevenue?: number\n\t/** 0..1 share of the site's visitors, absent when either side of the ratio is missing. */\n\trate?: number\n\tpreviousConversions?: number\n}\n\nexport interface WidgetGoalsResult {\n\tstatus: WidgetReadStatus\n\tadapterId: string\n\tdateRange: DateRange\n\ttimezone: string\n\trows: GoalRow[]\n\t/** Range total the rate divides by; absent when the source does not serve visitors. */\n\tsiteVisitors?: number\n\t/** The source that answered, absent on a read that never reached one. */\n\tprovider?: string\n\tclamped?: boolean\n\tstale?: boolean\n\t/** True when the source answered without one of the filters a read carried. */\n\tfiltersUnapplied?: boolean\n\t/** True when a read hit the source's event scan cap, so the numbers are a floor. */\n\tsampled?: boolean\n\t/** True when the source could not read the scope's goals, so the empty table means nothing. */\n\tgoalsUnresolved?: boolean\n\t/** True when the scope configures no goals at all, which is an empty table, not a failure. */\n\tnoGoals?: boolean\n}\n\nexport interface ReadForWidgetGoalsArgs {\n\treq: PayloadRequest\n\ttimeframe: TimeframePreset\n\tlimit: number\n\t/** Read the previous window too, when the source can compare. */\n\tcompare: boolean\n\tadapterId?: string\n\tnow: Date\n\trange?: DateRange\n\t/** Explicit scope override; omitted resolves via the plugin's scopeResolver. */\n\tscope?: string | null\n\t/**\n\t * Reporting timezone the caller already resolved, reused rather than resolved again so\n\t * a caller-supplied `range` is read in the very timezone it was interpreted in.\n\t */\n\ttimezone?: string\n}\n\n/**\n * How much wider than the table the previous window is read. Both windows rank by their own\n * conversions, so a goal in today's top rows may sit well below them in the previous window;\n * reading only as many rows as the table shows would drop exactly those deltas. Capped at\n * the bound every analytics query is held to.\n */\nconst PREVIOUS_LIMIT_FACTOR = 4\n\nconst previousLimit = (limit: number): number =>\n\tMath.min(limit * PREVIOUS_LIMIT_FACTOR, MAX_QUERY_LIMIT)\n\n/**\n * Goal names for the read's own scope. A resolver that throws must not cost the widget its\n * table, so the rows fall back to their slugs; the failure travels on as the hint, which is\n * what tells the read apart from a scope that configured no goals at all.\n */\nconst goalNames = async (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tscope: string | null\n): Promise<Map<string, string> | 'unresolved'> => {\n\ttry {\n\t\tconst resolved = await resolveGoalsDetailedFor(runtime, req, scope)\n\t\treturn new Map(resolved.map(({ goal }) => [goal.slug, goal.name]))\n\t} catch (err) {\n\t\treq.payload.logger?.warn(`analytics: widget goal names failed to resolve: ${String(err)}`)\n\t\treturn 'unresolved'\n\t}\n}\n\n/**\n * The goals table behind the goals widget: conversions per goal over the window, each with\n * its revenue, its share of the site's visitors, and (when comparing) the same goal's\n * conversions in the previous window. Rows come from one `goal` breakdown read and the site\n * total from one totals read, both through the existing widget helpers so capability\n * gating, scoping and caching stay in one place. Revenue and visitors ride along only where\n * the source serves them; the status is the breakdown's, since a table without its rows has\n * nothing to show.\n */\nexport const readForWidgetGoals = async (\n\targs: ReadForWidgetGoalsArgs\n): Promise<WidgetGoalsResult> => {\n\tconst { req, timeframe, limit, compare, adapterId, now } = args\n\tconst fallback = (\n\t\tstatus: WidgetReadStatus,\n\t\tid: string,\n\t\twindow: { dateRange: DateRange; timezone: string }\n\t): WidgetGoalsResult => ({ status, adapterId: id, rows: [], ...window })\n\n\tconst prepared = await prepareWidgetRead({\n\t\treq,\n\t\tnow,\n\t\ttimeframe,\n\t\tadapterId,\n\t\tscope: args.scope,\n\t\ttimezone: args.timezone,\n\t\trange: args.range,\n\t})\n\tif (!prepared.ok) {\n\t\treturn fallback(prepared.status, prepared.adapterId, {\n\t\t\tdateRange: prepared.dateRange,\n\t\t\ttimezone: prepared.tz,\n\t\t})\n\t}\n\tconst { runtime, adapter, tz, dateRange } = prepared\n\t// The sub-reads resolve their own context; pinning the adapter, scope, timezone and\n\t// window keeps all three answering about exactly the same read.\n\tconst shared = { req, timeframe, adapterId: adapter.id, scope: prepared.scope, timezone: tz, now }\n\tconst previousRange =\n\t\tcompare && runtime.comparison && comparisonOf(adapter.capabilities)\n\t\t\t? previousWindow(dateRange, tz)\n\t\t\t: null\n\tconst comparisonRange =\n\t\tpreviousRange &&\n\t\twithinLookback(previousRange, adapter.capabilities.maxLookbackDays, { tz, now })\n\t\t\t? previousRange\n\t\t\t: undefined\n\n\t// The names are resolved first: their slugs are the hint a provider source restricts its\n\t// goal rows to, so both reads below need them before they run.\n\tconst resolved = await goalNames(runtime, req, prepared.scope)\n\tconst names = resolved === 'unresolved' ? new Map<string, string>() : resolved\n\tconst goalSlugs = resolved === 'unresolved' ? 'unresolved' : [...names.keys()]\n\tconst [breakdown, totals, previous] = await Promise.all([\n\t\treadForWidgetBreakdown({\n\t\t\t...shared,\n\t\t\trange: dateRange,\n\t\t\tmetric: 'conversions',\n\t\t\tdimension: 'goal',\n\t\t\tlimit,\n\t\t\textraMetrics: ['revenue', 'visitors'],\n\t\t\tgoalSlugs,\n\t\t}),\n\t\tadapter.capabilities.metrics.has('visitors')\n\t\t\t? // The site total is a denominator, never a delta: its own previous window would\n\t\t\t\t// be a second read nothing renders.\n\t\t\t\treadForWidget({ ...shared, range: dateRange, metrics: ['visitors'], comparison: false })\n\t\t\t: undefined,\n\t\tcomparisonRange\n\t\t\t? readForWidgetBreakdown({\n\t\t\t\t\t...shared,\n\t\t\t\t\trange: comparisonRange,\n\t\t\t\t\tmetric: 'conversions',\n\t\t\t\t\tdimension: 'goal',\n\t\t\t\t\tlimit: previousLimit(limit),\n\t\t\t\t\tgoalSlugs,\n\t\t\t\t})\n\t\t\t: undefined,\n\t])\n\tif (breakdown.status !== 'ok') {\n\t\treturn fallback(breakdown.status, breakdown.adapterId, { dateRange, timezone: tz })\n\t}\n\n\tconst previousBySlug = new Map(\n\t\t(previous?.status === 'ok' ? previous.rows : []).map((row) => [row.label, row.value])\n\t)\n\tconst siteVisitors = totals?.status === 'ok' ? totals.metrics.visitors : undefined\n\tconst rows: GoalRow[] = breakdown.rows\n\t\t.map((row) => {\n\t\t\tconst rate = conversionRate(row.metrics?.visitors, siteVisitors)\n\t\t\tconst previousConversions = previousBySlug.get(row.label)\n\t\t\treturn {\n\t\t\t\tslug: row.label,\n\t\t\t\tname: names.get(row.label) ?? row.label,\n\t\t\t\tconversions: row.value,\n\t\t\t\t...(row.metrics?.revenue !== undefined ? { revenue: row.metrics.revenue } : {}),\n\t\t\t\t...(rate !== null ? { rate } : {}),\n\t\t\t\t...(previousConversions !== undefined ? { previousConversions } : {}),\n\t\t\t}\n\t\t})\n\t\t// The adapter ranks and caps already; re-applying both keeps one that does not from\n\t\t// spilling a long, unranked table into a dashboard card.\n\t\t.sort((a, b) => b.conversions - a.conversions)\n\t\t.slice(0, limit)\n\n\treturn {\n\t\tstatus: 'ok',\n\t\tadapterId: adapter.id,\n\t\tdateRange,\n\t\ttimezone: tz,\n\t\trows,\n\t\t...(siteVisitors !== undefined ? { siteVisitors } : {}),\n\t\t...(breakdown.provider === undefined ? {} : { provider: breakdown.provider }),\n\t\tclamped: Boolean(breakdown.clamped || totals?.clamped || previous?.clamped),\n\t\tstale: Boolean(breakdown.stale || totals?.stale || previous?.stale),\n\t\tfiltersUnapplied: Boolean(\n\t\t\tbreakdown.filtersUnapplied || totals?.filtersUnapplied || previous?.filtersUnapplied\n\t\t),\n\t\tsampled: Boolean(breakdown.sampled || totals?.sampled || previous?.sampled),\n\t\tgoalsUnresolved: breakdown.goalsUnresolved === true,\n\t\tnoGoals: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AAY,EAAE,oBAAoB,IAAI,CAAC;EACpE;CACD,CAAC,EAGA,MAAM,GAAG,MAAM,EAAE,cAAc,EAAE,WAAW,EAC5C,MAAM,GAAG,KAAK;CAEhB,OAAO;EACN,QAAQ;EACR,WAAW,QAAQ;EACnB;EACA,UAAU;EACV;EACA,GAAI,iBAAiB,KAAA,IAAY,EAAE,aAAa,IAAI,CAAC;EACrD,GAAI,UAAU,aAAa,KAAA,IAAY,CAAC,IAAI,EAAE,UAAU,UAAU,SAAS;EAC3E,SAAS,QAAQ,UAAU,WAAW,QAAQ,WAAW,UAAU,OAAO;EAC1E,OAAO,QAAQ,UAAU,SAAS,QAAQ,SAAS,UAAU,KAAK;EAClE,kBAAkB,QACjB,UAAU,oBAAoB,QAAQ,oBAAoB,UAAU,gBACrE;EACA,SAAS,QAAQ,UAAU,WAAW,QAAQ,WAAW,UAAU,OAAO;EAC1E,iBAAiB,UAAU,oBAAoB;EAC/C,SAAS,UAAU,YAAY;CAChC;AACD"}
@@ -12,6 +12,14 @@ interface WidgetRealtimeResult {
12
12
  adapterId: string;
13
13
  activeNow: number;
14
14
  series: RealtimePoint[];
15
+ /** The source that answered, absent on a read that never reached one. */
16
+ provider?: string;
17
+ clamped?: boolean;
18
+ stale?: boolean;
19
+ filtersUnapplied?: boolean;
20
+ goalsUnresolved?: boolean;
21
+ /** True when the read hit the source's event scan cap, so the counts are a floor. */
22
+ sampled?: boolean;
15
23
  }
16
24
  interface ReadForWidgetRealtimeArgs {
17
25
  req: PayloadRequest;
@@ -1,6 +1,5 @@
1
- import { getRuntime } from "../plugin/runtime.js";
2
- import { satisfiesCapabilities } from "../core/capabilities.js";
3
- import { resolveReadContext } from "../core/scopedRead.js";
1
+ import { prepareWidgetRead } from "./prepareWidgetRead.js";
2
+ import { readMeta } from "./readMeta.js";
4
3
  import { kvCacheStore } from "../surfacing/cacheStore.js";
5
4
  //#region src/widgets/readForWidgetRealtime.ts
6
5
  const empty = (status, adapterId) => ({
@@ -17,33 +16,34 @@ const empty = (status, adapterId) => ({
17
16
  */
18
17
  const readForWidgetRealtime = async (args) => {
19
18
  const { req, metric, windowMinutes, adapterId, now } = args;
20
- const runtime = getRuntime(req.payload);
21
- if (!runtime) return empty("unavailable", adapterId ?? "");
22
- const ctx = await resolveReadContext({
23
- runtime,
19
+ const dateRange = {
20
+ start: /* @__PURE__ */ new Date(now.getTime() - windowMinutes * 6e4),
21
+ end: now
22
+ };
23
+ const prepared = await prepareWidgetRead({
24
24
  req,
25
+ now,
26
+ range: dateRange,
27
+ timezone: "UTC",
25
28
  adapterId,
26
- scope: args.scope
29
+ scope: args.scope,
30
+ requires: { realtime: true }
27
31
  });
28
- if (!ctx.ok) return empty("unavailable", adapterId ?? "");
29
- const adapter = ctx.adapter;
30
- if (!adapter.isConfigured()) return empty("not-configured", adapter.id);
31
- if (!adapter.realtime || !satisfiesCapabilities(adapter.capabilities, { realtime: true })) return empty("unavailable", adapter.id);
32
+ if (!prepared.ok) return empty(prepared.status === "not-configured" ? "not-configured" : "unavailable", prepared.adapterId);
33
+ const { runtime, adapter, queryScope } = prepared;
34
+ const realtime = adapter.realtime;
35
+ if (!realtime) return empty("unavailable", adapter.id);
32
36
  const ttlSeconds = runtime.ttl.realtime ?? adapter.capabilities.recommendedTtl.realtime;
33
37
  const bucket = Math.floor(now.getTime() / 1e3 / Math.max(1, ttlSeconds));
34
- const scopeKey = ctx.queryScope === void 0 ? "" : `:${encodeURIComponent(ctx.queryScope)}`;
38
+ const scopeKey = queryScope === void 0 ? "" : `:${encodeURIComponent(queryScope)}`;
35
39
  const key = `rt:${adapter.id}:${metric}:${windowMinutes}:${bucket}${scopeKey}`;
36
40
  const store = kvCacheStore(req.payload.kv);
37
41
  const cached = await store.get(key);
38
42
  if (cached) return cached;
39
- const dateRange = {
40
- start: /* @__PURE__ */ new Date(now.getTime() - windowMinutes * 6e4),
41
- end: now
42
- };
43
- const result = await adapter.realtime({
43
+ const result = await realtime({
44
44
  metrics: [metric],
45
45
  dateRange,
46
- scope: ctx.queryScope
46
+ scope: queryScope
47
47
  }, {});
48
48
  const out = {
49
49
  status: "ok",
@@ -52,7 +52,8 @@ const readForWidgetRealtime = async (args) => {
52
52
  series: result.rows.map((r) => ({
53
53
  date: r.timestamp ?? "",
54
54
  value: r.metrics[metric] ?? 0
55
- }))
55
+ })),
56
+ ...readMeta(result)
56
57
  };
57
58
  await store.set(key, out, ttlSeconds);
58
59
  return out;
@@ -1 +1 @@
1
- {"version":3,"file":"readForWidgetRealtime.js","names":[],"sources":["../../src/widgets/readForWidgetRealtime.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport { satisfiesCapabilities } from '../core/capabilities'\nimport type { AnalyticsAdapter, MetricKey } from '../core/contract'\nimport { resolveReadContext } from '../core/scopedRead'\nimport { getRuntime } from '../plugin/runtime'\nimport { kvCacheStore } from '../surfacing/cacheStore'\n\nexport type WidgetRealtimeStatus = 'ok' | 'not-configured' | 'unavailable'\n\nexport interface RealtimePoint {\n\tdate: string\n\tvalue: number\n}\n\nexport interface WidgetRealtimeResult {\n\tstatus: WidgetRealtimeStatus\n\tadapterId: string\n\tactiveNow: number\n\tseries: RealtimePoint[]\n}\n\nexport interface ReadForWidgetRealtimeArgs {\n\treq: PayloadRequest\n\tmetric: MetricKey\n\twindowMinutes: number\n\tadapterId?: string\n\tnow: Date\n\t/** Explicit scope override; omitted resolves via the plugin's scopeResolver. */\n\tscope?: string | null\n}\n\nconst empty = (status: WidgetRealtimeStatus, adapterId: string): WidgetRealtimeResult => ({\n\tstatus,\n\tadapterId,\n\tactiveNow: 0,\n\tseries: [],\n})\n\n/**\n * Site-wide realtime read for the \"active now\" widget. The window arrives as a\n * dateRange (now - windowMinutes -> now). Cached under a realtime-specific key bucketed\n * to the realtime TTL: it is deliberately NOT routed through the engine, whose key\n * day-snaps the range (so a \"last 30 min\" read would collide with a \"today\" aggregate).\n */\nexport const readForWidgetRealtime = async (\n\targs: ReadForWidgetRealtimeArgs\n): Promise<WidgetRealtimeResult> => {\n\tconst { req, metric, windowMinutes, adapterId, now } = args\n\tconst runtime = getRuntime(req.payload)\n\tif (!runtime) {\n\t\treturn empty('unavailable', adapterId ?? '')\n\t}\n\tconst ctx = await resolveReadContext({ runtime, req, adapterId, scope: args.scope })\n\tif (!ctx.ok) {\n\t\treturn empty('unavailable', adapterId ?? '')\n\t}\n\tconst adapter: AnalyticsAdapter = ctx.adapter\n\tif (!adapter.isConfigured()) {\n\t\treturn empty('not-configured', adapter.id)\n\t}\n\tif (!adapter.realtime || !satisfiesCapabilities(adapter.capabilities, { realtime: true })) {\n\t\treturn empty('unavailable', adapter.id)\n\t}\n\n\tconst ttlSeconds = runtime.ttl.realtime ?? adapter.capabilities.recommendedTtl.realtime\n\tconst bucket = Math.floor(now.getTime() / 1000 / Math.max(1, ttlSeconds))\n\tconst scopeKey = ctx.queryScope === undefined ? '' : `:${encodeURIComponent(ctx.queryScope)}`\n\tconst key = `rt:${adapter.id}:${metric}:${windowMinutes}:${bucket}${scopeKey}`\n\tconst store = kvCacheStore(req.payload.kv)\n\tconst cached = await store.get<WidgetRealtimeResult>(key)\n\tif (cached) {\n\t\treturn cached\n\t}\n\n\tconst dateRange = { start: new Date(now.getTime() - windowMinutes * 60_000), end: now }\n\tconst result = await adapter.realtime({ metrics: [metric], dateRange, scope: ctx.queryScope }, {})\n\tconst out: WidgetRealtimeResult = {\n\t\tstatus: 'ok',\n\t\tadapterId: adapter.id,\n\t\tactiveNow: result.totals?.[metric] ?? 0,\n\t\tseries: result.rows.map((r) => ({ date: r.timestamp ?? '', value: r.metrics[metric] ?? 0 })),\n\t}\n\tawait store.set(key, out, ttlSeconds)\n\treturn out\n}\n"],"mappings":";;;;;AA+BA,MAAM,SAAS,QAA8B,eAA6C;CACzF;CACA;CACA,WAAW;CACX,QAAQ,CAAC;AACV;;;;;;;AAQA,MAAa,wBAAwB,OACpC,SACmC;CACnC,MAAM,EAAE,KAAK,QAAQ,eAAe,WAAW,QAAQ;CACvD,MAAM,U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AC5F;CACA,MAAM,MAAM,IAAI,KAAK,KAAK,UAAU;CACpC,OAAO;AACR"}
1
+ {"version":3,"file":"readForWidgetRealtime.js","names":[],"sources":["../../src/widgets/readForWidgetRealtime.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport type { MetricKey } from '../core/contract'\nimport { kvCacheStore } from '../surfacing/cacheStore'\nimport { DEFAULT_TIMEZONE } from '../timeframe/tz'\nimport { prepareWidgetRead } from './prepareWidgetRead'\nimport { readMeta } from './readMeta'\n\nexport type WidgetRealtimeStatus = 'ok' | 'not-configured' | 'unavailable'\n\nexport interface RealtimePoint {\n\tdate: string\n\tvalue: number\n}\n\nexport interface WidgetRealtimeResult {\n\tstatus: WidgetRealtimeStatus\n\tadapterId: string\n\tactiveNow: number\n\tseries: RealtimePoint[]\n\t/** The source that answered, absent on a read that never reached one. */\n\tprovider?: string\n\tclamped?: boolean\n\tstale?: boolean\n\tfiltersUnapplied?: boolean\n\tgoalsUnresolved?: boolean\n\t/** True when the read hit the source's event scan cap, so the counts are a floor. */\n\tsampled?: boolean\n}\n\nexport interface ReadForWidgetRealtimeArgs {\n\treq: PayloadRequest\n\tmetric: MetricKey\n\twindowMinutes: number\n\tadapterId?: string\n\tnow: Date\n\t/** Explicit scope override; omitted resolves via the plugin's scopeResolver. */\n\tscope?: string | null\n}\n\nconst empty = (status: WidgetRealtimeStatus, adapterId: string): WidgetRealtimeResult => ({\n\tstatus,\n\tadapterId,\n\tactiveNow: 0,\n\tseries: [],\n})\n\n/**\n * Site-wide realtime read for the \"active now\" widget. The window arrives as a\n * dateRange (now - windowMinutes -> now). Cached under a realtime-specific key bucketed\n * to the realtime TTL: it is deliberately NOT routed through the engine, whose key\n * day-snaps the range (so a \"last 30 min\" read would collide with a \"today\" aggregate).\n */\nexport const readForWidgetRealtime = async (\n\targs: ReadForWidgetRealtimeArgs\n): Promise<WidgetRealtimeResult> => {\n\tconst { req, metric, windowMinutes, adapterId, now } = args\n\tconst dateRange = { start: new Date(now.getTime() - windowMinutes * 60_000), end: now }\n\t// The window is anchored on `now` and never rendered in a zone, so the poll skips the\n\t// install's timezone resolver rather than paying for it ahead of the cache check.\n\tconst prepared = await prepareWidgetRead({\n\t\treq,\n\t\tnow,\n\t\trange: dateRange,\n\t\ttimezone: DEFAULT_TIMEZONE,\n\t\tadapterId,\n\t\tscope: args.scope,\n\t\trequires: { realtime: true },\n\t})\n\tif (!prepared.ok) {\n\t\t// The window carries no filters, so `filter-unsupported` cannot arise here.\n\t\tconst status = prepared.status === 'not-configured' ? 'not-configured' : 'unavailable'\n\t\treturn empty(status, prepared.adapterId)\n\t}\n\tconst { runtime, adapter, queryScope } = prepared\n\t// The capability says the source counts live visitors; the hook is what reads them.\n\tconst realtime = adapter.realtime\n\tif (!realtime) {\n\t\treturn empty('unavailable', adapter.id)\n\t}\n\n\tconst ttlSeconds = runtime.ttl.realtime ?? adapter.capabilities.recommendedTtl.realtime\n\tconst bucket = Math.floor(now.getTime() / 1000 / Math.max(1, ttlSeconds))\n\tconst scopeKey = queryScope === undefined ? '' : `:${encodeURIComponent(queryScope)}`\n\tconst key = `rt:${adapter.id}:${metric}:${windowMinutes}:${bucket}${scopeKey}`\n\tconst store = kvCacheStore(req.payload.kv)\n\tconst cached = await store.get<WidgetRealtimeResult>(key)\n\tif (cached) {\n\t\treturn cached\n\t}\n\n\tconst result = await realtime({ metrics: [metric], dateRange, scope: queryScope }, {})\n\tconst out: WidgetRealtimeResult = {\n\t\tstatus: 'ok',\n\t\tadapterId: adapter.id,\n\t\tactiveNow: result.totals?.[metric] ?? 0,\n\t\tseries: result.rows.map((r) => ({ date: r.timestamp ?? '', value: r.metrics[metric] ?? 0 })),\n\t\t...readMeta(result),\n\t}\n\tawait store.set(key, out, ttlSeconds)\n\treturn out\n}\n"],"mappings":";;;;AAuCA,MAAM,SAAS,QAA8B,eAA6C;CACzF;CACA;CACA,WAAW;CACX,QAAQ,CAAC;AACV;;;;;;;AAQA,MAAa,wBAAwB,OACpC,S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CACpC,OAAO;AACR"}
@@ -1,6 +1,6 @@
1
1
  import { AnalyticsFilter, DateRange, MetricKey } from "../core/contract.js";
2
2
  import { TimeframePreset } from "../timeframe/presets.js";
3
- import { WidgetReadStatus } from "./readForWidget.js";
3
+ import { WidgetReadStatus } from "./prepareWidgetRead.js";
4
4
  import { PayloadRequest } from "payload";
5
5
 
6
6
  //#region src/widgets/readForWidgetSeries.d.ts
@@ -16,7 +16,17 @@ interface WidgetSeriesResult {
16
16
  timezone: string;
17
17
  points: SeriesPoint[];
18
18
  total: number;
19
+ /** The source that answered, absent on a read that never reached one. */
20
+ provider?: string;
19
21
  clamped?: boolean;
22
+ /** True when the engine served a stale cache entry after a failed provider read. */
23
+ stale?: boolean;
24
+ /** True when the source answered without one of the filters the read carried. */
25
+ filtersUnapplied?: boolean;
26
+ /** True when the read hit the source's event scan cap, so the numbers are a floor. */
27
+ sampled?: boolean;
28
+ /** True when the source could not read the scope's goals, so a conversions series means nothing. */
29
+ goalsUnresolved?: boolean;
20
30
  /** Previous-window headline total, present only when the adapter supports comparison. */
21
31
  previousTotal?: number;
22
32
  /** The previous comparable window, present only when comparison ran. */
@@ -1,10 +1,8 @@
1
1
  import { addDaysInTz, startOfDayInTz, zonedDayIso } from "../timeframe/tz.js";
2
- import { getRuntime, resolveTimezoneFor } from "../plugin/runtime.js";
3
- import { resolveTimeframe } from "../timeframe/presets.js";
4
- import { satisfiesCapabilities } from "../core/capabilities.js";
5
- import { supportsGranularity } from "../core/granularity.js";
6
- import { resolveReadContext } from "../core/scopedRead.js";
7
- import { previousWindow } from "./comparison.js";
2
+ import { comparisonOf } from "../core/capabilities.js";
3
+ import { previousWindow, withinLookback } from "./comparison.js";
4
+ import { prepareWidgetRead } from "./prepareWidgetRead.js";
5
+ import { readMeta } from "./readMeta.js";
8
6
  //#region src/widgets/readForWidgetSeries.ts
9
7
  const MAX_SERIES_DAYS = 366;
10
8
  /**
@@ -54,66 +52,57 @@ const alignSeries = (points, axis) => points.length === axis.length ? points : a
54
52
  */
55
53
  const readForWidgetSeries = async (args) => {
56
54
  const { req, metric, timeframe, adapterId, now, range, filters, compare } = args;
57
- const fallback = (status, id) => ({
58
- status,
59
- adapterId: id,
60
- dateRange: range ?? resolveTimeframe(timeframe, now, args.timezone),
61
- timezone: args.timezone ?? "UTC",
62
- points: [],
63
- total: 0
64
- });
65
- const runtime = getRuntime(req.payload);
66
- if (!runtime) return fallback("unavailable", adapterId ?? "");
67
- const ctx = await resolveReadContext({
68
- runtime,
55
+ const prepared = await prepareWidgetRead({
69
56
  req,
57
+ now,
58
+ timeframe,
70
59
  adapterId,
71
- scope: args.scope
60
+ scope: args.scope,
61
+ timezone: args.timezone,
62
+ range,
63
+ filters,
64
+ requires: { metrics: [metric] },
65
+ granularity: "day",
66
+ goalRead: () => ({ metrics: [metric] })
72
67
  });
73
- if (!ctx.ok) return fallback("unavailable", adapterId ?? "");
74
- const tz = args.timezone ?? await resolveTimezoneFor(runtime, req, ctx.scope);
75
- const dateRange = range ?? resolveTimeframe(timeframe, now, tz);
68
+ if (!prepared.ok) return {
69
+ status: prepared.status,
70
+ adapterId: prepared.adapterId,
71
+ dateRange: prepared.dateRange,
72
+ timezone: prepared.tz,
73
+ points: [],
74
+ total: 0
75
+ };
76
+ const { runtime, adapter, tz, dateRange, goalSlugs } = prepared;
76
77
  const base = {
77
78
  dateRange,
78
79
  timezone: tz,
79
80
  points: [],
80
81
  total: 0
81
82
  };
82
- const adapter = ctx.adapter;
83
- if (!adapter.isConfigured()) return {
84
- status: "not-configured",
85
- adapterId: adapter.id,
86
- ...base
87
- };
88
- if (!satisfiesCapabilities(adapter.capabilities, {
83
+ const previousRange = runtime.comparison && comparisonOf(adapter.capabilities) ? previousWindow(dateRange, tz) : null;
84
+ const comparisonRange = previousRange && withinLookback(previousRange, adapter.capabilities.maxLookbackDays, {
85
+ tz,
86
+ now
87
+ }) ? previousRange : void 0;
88
+ const readBase = {
89
89
  metrics: [metric],
90
- ...filters && filters.length > 0 ? {
91
- filters: filters.map((f) => f.dimension),
92
- filterOperators: filters.map((f) => f.operator)
93
- } : {}
94
- }) || !supportsGranularity(adapter.capabilities, "day")) return {
95
- status: "unavailable",
96
- adapterId: adapter.id,
97
- ...base
90
+ filters,
91
+ timezone: tz,
92
+ scope: prepared.queryScope,
93
+ ...goalSlugs === void 0 ? {} : { goalSlugs }
98
94
  };
99
- const comparisonRange = runtime.comparison && adapter.capabilities.comparison ? previousWindow(dateRange, tz) ?? void 0 : void 0;
100
95
  let result;
101
96
  let previous;
102
97
  try {
103
98
  [result, previous] = await Promise.all([runtime.engine.read(adapter, {
104
- metrics: [metric],
99
+ ...readBase,
105
100
  dateRange,
106
- granularity: "day",
107
- filters,
108
- timezone: tz,
109
- scope: ctx.queryScope
101
+ granularity: "day"
110
102
  }), comparisonRange ? runtime.engine.read(adapter, {
111
- metrics: [metric],
103
+ ...readBase,
112
104
  dateRange: comparisonRange,
113
- ...compare ? { granularity: "day" } : {},
114
- filters,
115
- timezone: tz,
116
- scope: ctx.queryScope
105
+ ...compare ? { granularity: "day" } : {}
117
106
  }) : void 0]);
118
107
  } catch {
119
108
  return {
@@ -136,7 +125,7 @@ const readForWidgetSeries = async (args) => {
136
125
  timezone: tz,
137
126
  points,
138
127
  total: result.totals?.[metric] ?? 0,
139
- clamped: result.meta.clamped ?? false,
128
+ ...readMeta(result),
140
129
  previousTotal,
141
130
  comparisonRange,
142
131
  ...compare && previous && comparisonRange ? { comparisonPoints: alignSeries(fillDailySeries({
@@ -1 +1 @@
1
- {"version":3,"file":"readForWidgetSeries.js","names":[],"sources":["../../src/widgets/readForWidgetSeries.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport { satisfiesCapabilities } from '../core/capabilities'\nimport type {\n\tAnalyticsAdapter,\n\tAnalyticsFilter,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tDateRange,\n\tMetricKey,\n} from '../core/contract'\nimport { supportsGranularity } from '../core/granularity'\nimport { resolveReadContext } from '../core/scopedRead'\nimport { getRuntime, resolveTimezoneFor } from '../plugin/runtime'\nimport { resolveTimeframe, type TimeframePreset } from '../timeframe/presets'\nimport { addDaysInTz, DEFAULT_TIMEZONE, startOfDayInTz, zonedDayIso } from '../timeframe/tz'\nimport { previousWindow } from './comparison'\nimport type { WidgetReadStatus } from './readForWidget'\n\nexport interface SeriesPoint {\n\tdate: string\n\tvalue: number\n}\n\nexport interface WidgetSeriesResult {\n\tstatus: WidgetReadStatus\n\tadapterId: string\n\tdateRange: DateRange\n\t/** Reporting timezone the read resolved in; the trend axis buckets in it. */\n\ttimezone: string\n\tpoints: SeriesPoint[]\n\ttotal: number\n\tclamped?: boolean\n\t/** Previous-window headline total, present only when the adapter supports comparison. */\n\tpreviousTotal?: number\n\t/** The previous comparable window, present only when comparison ran. */\n\tcomparisonRange?: DateRange\n\t/**\n\t * The previous window's daily series, present only when `compare` was asked for and the\n\t * adapter supports comparison. Zero-filled to the same length as `points`, so the\n\t * previous window's day i overlays `points[i]`.\n\t */\n\tcomparisonPoints?: SeriesPoint[]\n}\n\nexport interface ReadForWidgetSeriesArgs {\n\treq: PayloadRequest\n\tmetric: MetricKey\n\ttimeframe: TimeframePreset\n\tadapterId?: string\n\tnow: Date\n\trange?: DateRange\n\t/** Explicit scope override; omitted resolves via the plugin's scopeResolver. */\n\tscope?: string | null\n\t/**\n\t * Reporting timezone the caller already resolved, reused rather than resolved again so\n\t * a caller-supplied `range` is read in the very timezone it was interpreted in.\n\t */\n\ttimezone?: string\n\tfilters?: AnalyticsFilter[]\n\t/** Also return the previous window's series, for the chart's comparison overlay. */\n\tcompare?: boolean\n}\n\nconst MAX_SERIES_DAYS = 366\n\n/**\n * Project time-series rows onto a contiguous daily axis, zero-filling gaps. Days are\n * counted in `tz` (defaulting to UTC), so a reporting-timezone read aligns each bucket\n * to that zone's midnight. The axis is capped at the most recent `MAX_SERIES_DAYS` so\n * an unbounded range (all time) stays a bounded, drawable sparkline; the headline total\n * still reflects the full range.\n */\nexport const fillDailySeries = (args: {\n\trows: AnalyticsRow[]\n\tdateRange: DateRange\n\tmetric: MetricKey\n\ttz?: string\n}): SeriesPoint[] => {\n\tconst { rows, dateRange, metric } = args\n\tconst tz = args.tz ?? DEFAULT_TIMEZONE\n\tconst lastDay = startOfDayInTz(dateRange.end, tz)\n\tconst requestedStart = startOfDayInTz(dateRange.start, tz)\n\tconst byDay = new Map<string, number>()\n\tfor (const row of rows) {\n\t\tif (!row.timestamp) {\n\t\t\tcontinue\n\t\t}\n\t\tconst day = zonedDayIso(new Date(row.timestamp), tz)\n\t\tbyDay.set(day, (byDay.get(day) ?? 0) + (row.metrics[metric] ?? 0))\n\t}\n\t// Walk calendar days back from the last day so DST-length days never mis-step, capping\n\t// the axis at MAX_SERIES_DAYS or the requested start, whichever is more recent.\n\tconst isoDays: string[] = []\n\tlet cursor = lastDay\n\tfor (let i = 0; i < MAX_SERIES_DAYS && cursor.getTime() >= requestedStart.getTime(); i += 1) {\n\t\tisoDays.push(cursor.toISOString())\n\t\tcursor = addDaysInTz(cursor, -1, tz)\n\t}\n\treturn isoDays.reverse().map((date) => ({ date, value: byDay.get(date) ?? 0 }))\n}\n\n/**\n * Project a comparison series onto the primary axis: day i of the previous window overlays\n * day i of the current one. Both windows span the same day count by construction, so this\n * only guards a DST-shifted or clamped edge, silently truncating or zero-filling; a filled\n * bucket borrows the axis day so every point still carries a real date.\n */\nconst alignSeries = (points: SeriesPoint[], axis: SeriesPoint[]): SeriesPoint[] =>\n\tpoints.length === axis.length\n\t\t? points\n\t\t: axis.map((day, i) => points[i] ?? { date: day.date, value: 0 })\n\n/**\n * Site-wide time-series read for a trend widget: resolve the timeframe, pick the\n * adapter, gate on the metric and day-granularity support, read through the engine,\n * then return a zero-filled daily series plus the headline total. Mirrors\n * `readForWidget` but yields points instead of a single value.\n */\nexport const readForWidgetSeries = async (\n\targs: ReadForWidgetSeriesArgs\n): Promise<WidgetSeriesResult> => {\n\tconst { req, metric, timeframe, adapterId, now, range, filters, compare } = args\n\tconst fallback = (status: WidgetReadStatus, id: string): WidgetSeriesResult => ({\n\t\tstatus,\n\t\tadapterId: id,\n\t\tdateRange: range ?? resolveTimeframe(timeframe, now, args.timezone),\n\t\ttimezone: args.timezone ?? DEFAULT_TIMEZONE,\n\t\tpoints: [],\n\t\ttotal: 0,\n\t})\n\n\tconst runtime = getRuntime(req.payload)\n\tif (!runtime) {\n\t\treturn fallback('unavailable', adapterId ?? '')\n\t}\n\tconst ctx = await resolveReadContext({ runtime, req, adapterId, scope: args.scope })\n\tif (!ctx.ok) {\n\t\treturn fallback('unavailable', adapterId ?? '')\n\t}\n\tconst tz = args.timezone ?? (await resolveTimezoneFor(runtime, req, ctx.scope))\n\tconst dateRange = range ?? resolveTimeframe(timeframe, now, tz)\n\tconst base = { dateRange, timezone: tz, points: [] as SeriesPoint[], total: 0 }\n\tconst adapter: AnalyticsAdapter = ctx.adapter\n\tif (!adapter.isConfigured()) {\n\t\treturn { status: 'not-configured', adapterId: adapter.id, ...base }\n\t}\n\tif (\n\t\t!satisfiesCapabilities(adapter.capabilities, {\n\t\t\tmetrics: [metric],\n\t\t\t...(filters && filters.length > 0\n\t\t\t\t? {\n\t\t\t\t\t\tfilters: filters.map((f) => f.dimension),\n\t\t\t\t\t\tfilterOperators: filters.map((f) => f.operator),\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t}) ||\n\t\t!supportsGranularity(adapter.capabilities, 'day')\n\t) {\n\t\treturn { status: 'unavailable', adapterId: adapter.id, ...base }\n\t}\n\tconst comparisonRange =\n\t\truntime.comparison && adapter.capabilities.comparison\n\t\t\t? (previousWindow(dateRange, tz) ?? undefined)\n\t\t\t: undefined\n\tlet result: AnalyticsResult\n\tlet previous: AnalyticsResult | undefined\n\ttry {\n\t\t;[result, previous] = await Promise.all([\n\t\t\truntime.engine.read(adapter, {\n\t\t\t\tmetrics: [metric],\n\t\t\t\tdateRange,\n\t\t\t\tgranularity: 'day',\n\t\t\t\tfilters,\n\t\t\t\ttimezone: tz,\n\t\t\t\tscope: ctx.queryScope,\n\t\t\t}),\n\t\t\tcomparisonRange\n\t\t\t\t? runtime.engine.read(adapter, {\n\t\t\t\t\t\tmetrics: [metric],\n\t\t\t\t\t\tdateRange: comparisonRange,\n\t\t\t\t\t\t// The overlay needs the previous window bucketed like the primary; the delta\n\t\t\t\t\t\t// alone only needs its total, so the read stays as it was without `compare`.\n\t\t\t\t\t\t...(compare ? { granularity: 'day' as const } : {}),\n\t\t\t\t\t\tfilters,\n\t\t\t\t\t\ttimezone: tz,\n\t\t\t\t\t\tscope: ctx.queryScope,\n\t\t\t\t\t})\n\t\t\t\t: undefined,\n\t\t])\n\t} catch {\n\t\t// No cache entry (fresh or stale) survived the failed read; degrade like an\n\t\t// unsupported capability instead of throwing through the widget render tree.\n\t\treturn { status: 'unavailable', adapterId: adapter.id, ...base }\n\t}\n\tconst previousTotal = previous ? previous.totals?.[metric] : undefined\n\tconst points = fillDailySeries({ rows: result.rows, dateRange, metric, tz })\n\treturn {\n\t\tstatus: 'ok',\n\t\tadapterId: adapter.id,\n\t\tdateRange,\n\t\ttimezone: tz,\n\t\tpoints,\n\t\ttotal: result.totals?.[metric] ?? 0,\n\t\tclamped: result.meta.clamped ?? false,\n\t\tpreviousTotal,\n\t\tcomparisonRange,\n\t\t...(compare && previous && comparisonRange\n\t\t\t? {\n\t\t\t\t\tcomparisonPoints: alignSeries(\n\t\t\t\t\t\tfillDailySeries({ rows: previous.rows, dateRange: comparisonRange, metric, tz }),\n\t\t\t\t\t\tpoints\n\t\t\t\t\t),\n\t\t\t\t}\n\t\t\t: {}),\n\t}\n}\n"],"mappings":";;;;;;;;AA+DA,MAAM,kBAAkB;;;;;;;;AASxB,MAAa,mBAAmB,SAKX;CACpB,MAAM,EAAE,MAAM,WAAW,WAAW;CACpC,MAAM,KAAK,KAAK,MAAA;CAChB,MAAM,UAAU,eAAe,UAAU,KAAK,EAAE;CAChD,MAAM,iBAAiB,eAAe,UAAU,OAAO,EAAE;CACzD,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AAM,SAAS,gBAAgB;EAAE,MAAM,OAAO;EAAM;EAAW;EAAQ;CAAG,CAAC;CAC3E,OAAO;EACN,QAAQ;EACR,WAAW,QAAQ;EACnB;EACA,UAAU;EACV;EACA,OAAO,OAAO,SAAS,WAAW;EAClC,SAAS,OAAO,KAAK,WAAW;EAChC;EACA;EACA,GAAI,WAAW,YAAY,kBACxB,EACA,kBAAkB,YACjB,gBAAgB;GAAE,MAAM,SAAS;GAAM,WAAW;GAAiB;GAAQ;EAAG,CAAC,GAC/E,MACD,EACD,IACC,CAAC;CACL;AACD"}
1
+ {"version":3,"file":"readForWidgetSeries.js","names":[],"sources":["../../src/widgets/readForWidgetSeries.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport { comparisonOf } from '../core/capabilities'\nimport type {\n\tAnalyticsFilter,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tDateRange,\n\tMetricKey,\n} from '../core/contract'\nimport type { TimeframePreset } from '../timeframe/presets'\nimport { addDaysInTz, DEFAULT_TIMEZONE, startOfDayInTz, zonedDayIso } from '../timeframe/tz'\nimport { previousWindow, withinLookback } from './comparison'\nimport { prepareWidgetRead, type WidgetReadStatus } from './prepareWidgetRead'\nimport { readMeta } from './readMeta'\n\nexport interface SeriesPoint {\n\tdate: string\n\tvalue: number\n}\n\nexport interface WidgetSeriesResult {\n\tstatus: WidgetReadStatus\n\tadapterId: string\n\tdateRange: DateRange\n\t/** Reporting timezone the read resolved in; the trend axis buckets in it. */\n\ttimezone: string\n\tpoints: SeriesPoint[]\n\ttotal: number\n\t/** The source that answered, absent on a read that never reached one. */\n\tprovider?: string\n\tclamped?: boolean\n\t/** True when the engine served a stale cache entry after a failed provider read. */\n\tstale?: boolean\n\t/** True when the source answered without one of the filters the read carried. */\n\tfiltersUnapplied?: boolean\n\t/** True when the read hit the source's event scan cap, so the numbers are a floor. */\n\tsampled?: boolean\n\t/** True when the source could not read the scope's goals, so a conversions series means nothing. */\n\tgoalsUnresolved?: boolean\n\t/** Previous-window headline total, present only when the adapter supports comparison. */\n\tpreviousTotal?: number\n\t/** The previous comparable window, present only when comparison ran. */\n\tcomparisonRange?: DateRange\n\t/**\n\t * The previous window's daily series, present only when `compare` was asked for and the\n\t * adapter supports comparison. Zero-filled to the same length as `points`, so the\n\t * previous window's day i overlays `points[i]`.\n\t */\n\tcomparisonPoints?: SeriesPoint[]\n}\n\nexport interface ReadForWidgetSeriesArgs {\n\treq: PayloadRequest\n\tmetric: MetricKey\n\ttimeframe: TimeframePreset\n\tadapterId?: string\n\tnow: Date\n\trange?: DateRange\n\t/** Explicit scope override; omitted resolves via the plugin's scopeResolver. */\n\tscope?: string | null\n\t/**\n\t * Reporting timezone the caller already resolved, reused rather than resolved again so\n\t * a caller-supplied `range` is read in the very timezone it was interpreted in.\n\t */\n\ttimezone?: string\n\tfilters?: AnalyticsFilter[]\n\t/** Also return the previous window's series, for the chart's comparison overlay. */\n\tcompare?: boolean\n}\n\nconst MAX_SERIES_DAYS = 366\n\n/**\n * Project time-series rows onto a contiguous daily axis, zero-filling gaps. Days are\n * counted in `tz` (defaulting to UTC), so a reporting-timezone read aligns each bucket\n * to that zone's midnight. The axis is capped at the most recent `MAX_SERIES_DAYS` so\n * an unbounded range (all time) stays a bounded, drawable sparkline; the headline total\n * still reflects the full range.\n */\nexport const fillDailySeries = (args: {\n\trows: AnalyticsRow[]\n\tdateRange: DateRange\n\tmetric: MetricKey\n\ttz?: string\n}): SeriesPoint[] => {\n\tconst { rows, dateRange, metric } = args\n\tconst tz = args.tz ?? DEFAULT_TIMEZONE\n\tconst lastDay = startOfDayInTz(dateRange.end, tz)\n\tconst requestedStart = startOfDayInTz(dateRange.start, tz)\n\tconst byDay = new Map<string, number>()\n\tfor (const row of rows) {\n\t\tif (!row.timestamp) {\n\t\t\tcontinue\n\t\t}\n\t\tconst day = zonedDayIso(new Date(row.timestamp), tz)\n\t\tbyDay.set(day, (byDay.get(day) ?? 0) + (row.metrics[metric] ?? 0))\n\t}\n\t// Walk calendar days back from the last day so DST-length days never mis-step, capping\n\t// the axis at MAX_SERIES_DAYS or the requested start, whichever is more recent.\n\tconst isoDays: string[] = []\n\tlet cursor = lastDay\n\tfor (let i = 0; i < MAX_SERIES_DAYS && cursor.getTime() >= requestedStart.getTime(); i += 1) {\n\t\tisoDays.push(cursor.toISOString())\n\t\tcursor = addDaysInTz(cursor, -1, tz)\n\t}\n\treturn isoDays.reverse().map((date) => ({ date, value: byDay.get(date) ?? 0 }))\n}\n\n/**\n * Project a comparison series onto the primary axis: day i of the previous window overlays\n * day i of the current one. Both windows span the same day count by construction, so this\n * only guards a DST-shifted or clamped edge, silently truncating or zero-filling; a filled\n * bucket borrows the axis day so every point still carries a real date.\n */\nconst alignSeries = (points: SeriesPoint[], axis: SeriesPoint[]): SeriesPoint[] =>\n\tpoints.length === axis.length\n\t\t? points\n\t\t: axis.map((day, i) => points[i] ?? { date: day.date, value: 0 })\n\n/**\n * Site-wide time-series read for a trend widget: resolve the timeframe, pick the\n * adapter, gate on the metric and day-granularity support, read through the engine,\n * then return a zero-filled daily series plus the headline total. Mirrors\n * `readForWidget` but yields points instead of a single value.\n */\nexport const readForWidgetSeries = async (\n\targs: ReadForWidgetSeriesArgs\n): Promise<WidgetSeriesResult> => {\n\tconst { req, metric, timeframe, adapterId, now, range, filters, compare } = args\n\n\tconst prepared = await prepareWidgetRead({\n\t\treq,\n\t\tnow,\n\t\ttimeframe,\n\t\tadapterId,\n\t\tscope: args.scope,\n\t\ttimezone: args.timezone,\n\t\trange,\n\t\tfilters,\n\t\trequires: { metrics: [metric] },\n\t\tgranularity: 'day',\n\t\tgoalRead: () => ({ metrics: [metric] }),\n\t})\n\tif (!prepared.ok) {\n\t\treturn {\n\t\t\tstatus: prepared.status,\n\t\t\tadapterId: prepared.adapterId,\n\t\t\tdateRange: prepared.dateRange,\n\t\t\ttimezone: prepared.tz,\n\t\t\tpoints: [],\n\t\t\ttotal: 0,\n\t\t}\n\t}\n\tconst { runtime, adapter, tz, dateRange, goalSlugs } = prepared\n\tconst base = { dateRange, timezone: tz, points: [] as SeriesPoint[], total: 0 }\n\tconst previousRange =\n\t\truntime.comparison && comparisonOf(adapter.capabilities) ? previousWindow(dateRange, tz) : null\n\tconst comparisonRange =\n\t\tpreviousRange &&\n\t\twithinLookback(previousRange, adapter.capabilities.maxLookbackDays, { tz, now })\n\t\t\t? previousRange\n\t\t\t: undefined\n\tconst readBase = {\n\t\tmetrics: [metric],\n\t\tfilters,\n\t\ttimezone: tz,\n\t\tscope: prepared.queryScope,\n\t\t...(goalSlugs === undefined ? {} : { goalSlugs }),\n\t}\n\tlet result: AnalyticsResult\n\tlet previous: AnalyticsResult | undefined\n\ttry {\n\t\t;[result, previous] = await Promise.all([\n\t\t\truntime.engine.read(adapter, { ...readBase, dateRange, granularity: 'day' }),\n\t\t\tcomparisonRange\n\t\t\t\t? runtime.engine.read(adapter, {\n\t\t\t\t\t\t...readBase,\n\t\t\t\t\t\tdateRange: comparisonRange,\n\t\t\t\t\t\t// The overlay needs the previous window bucketed like the primary; the delta\n\t\t\t\t\t\t// alone only needs its total, so the read stays as it was without `compare`.\n\t\t\t\t\t\t...(compare ? { granularity: 'day' as const } : {}),\n\t\t\t\t\t})\n\t\t\t\t: undefined,\n\t\t])\n\t} catch {\n\t\t// No cache entry (fresh or stale) survived the failed read; degrade like an\n\t\t// unsupported capability instead of throwing through the widget render tree.\n\t\treturn { status: 'unavailable', adapterId: adapter.id, ...base }\n\t}\n\tconst previousTotal = previous ? previous.totals?.[metric] : undefined\n\tconst points = fillDailySeries({ rows: result.rows, dateRange, metric, tz })\n\treturn {\n\t\tstatus: 'ok',\n\t\tadapterId: adapter.id,\n\t\tdateRange,\n\t\ttimezone: tz,\n\t\tpoints,\n\t\ttotal: result.totals?.[metric] ?? 0,\n\t\t...readMeta(result),\n\t\tpreviousTotal,\n\t\tcomparisonRange,\n\t\t...(compare && previous && comparisonRange\n\t\t\t? {\n\t\t\t\t\tcomparisonPoints: alignSeries(\n\t\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AC;CAC3E,OAAO;EACN,QAAQ;EACR,WAAW,QAAQ;EACnB;EACA,UAAU;EACV;EACA,OAAO,OAAO,SAAS,WAAW;EAClC,GAAG,SAAS,MAAM;EAClB;EACA;EACA,GAAI,WAAW,YAAY,kBACxB,EACA,kBAAkB,YACjB,gBAAgB;GAAE,MAAM,SAAS;GAAM,WAAW;GAAiB;GAAQ;EAAG,CAAC,GAC/E,MACD,EACD,IACC,CAAC;CACL;AACD"}
@@ -0,0 +1,18 @@
1
+ //#region src/widgets/readMeta.ts
2
+ /**
3
+ * One mapping from an adapter result's meta to the flags a widget renders. Every helper
4
+ * maps all of them, so a widget that starts rendering a notice needs nothing from the read
5
+ * path, and a flag cannot go missing on one widget while its neighbour shows it.
6
+ */
7
+ const readMeta = (result) => ({
8
+ clamped: result.meta.clamped ?? false,
9
+ stale: result.meta.stale ?? false,
10
+ filtersUnapplied: (result.meta.unappliedFilters?.length ?? 0) > 0,
11
+ goalsUnresolved: result.meta.goalsUnresolved === true,
12
+ sampled: result.meta.sampled ?? false,
13
+ provider: result.meta.provider
14
+ });
15
+ //#endregion
16
+ export { readMeta };
17
+
18
+ //# sourceMappingURL=readMeta.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"readMeta.js","names":[],"sources":["../../src/widgets/readMeta.ts"],"sourcesContent":["import type { AnalyticsResult } from '../core/contract'\n\n/** The state flags every widget result carries, whatever shape its numbers take. */\nexport interface WidgetReadMeta {\n\t/** The source read a shorter window than the one that was asked for. */\n\tclamped: boolean\n\t/** The engine served an expired cache entry after a failed provider read. */\n\tstale: boolean\n\t/** The source answered without one of the filters the read carried. */\n\tfiltersUnapplied: boolean\n\t/** The source could not read the scope's goals, so the goal numbers mean nothing. */\n\tgoalsUnresolved: boolean\n\t/** The read hit the source's event scan cap, so the numbers are a floor. */\n\tsampled: boolean\n\t/** The source that answered. */\n\tprovider: string\n}\n\n/**\n * One mapping from an adapter result's meta to the flags a widget renders. Every helper\n * maps all of them, so a widget that starts rendering a notice needs nothing from the read\n * path, and a flag cannot go missing on one widget while its neighbour shows it.\n */\nexport const readMeta = (result: AnalyticsResult): WidgetReadMeta => ({\n\tclamped: result.meta.clamped ?? false,\n\tstale: result.meta.stale ?? false,\n\tfiltersUnapplied: (result.meta.unappliedFilters?.length ?? 0) > 0,\n\tgoalsUnresolved: result.meta.goalsUnresolved === true,\n\tsampled: result.meta.sampled ?? false,\n\tprovider: result.meta.provider,\n})\n"],"mappings":";;;;;;AAuBA,MAAa,YAAY,YAA6C;CACrE,SAAS,OAAO,KAAK,WAAW;CAChC,OAAO,OAAO,KAAK,SAAS;CAC5B,mBAAmB,OAAO,KAAK,kBAAkB,UAAU,KAAK;CAChE,iBAAiB,OAAO,KAAK,oBAAoB;CACjD,SAAS,OAAO,KAAK,WAAW;CAChC,UAAU,OAAO,KAAK;AACvB"}
@@ -9,6 +9,7 @@ import { BREAKDOWN_SPECS } from "./breakdownTypes.js";
9
9
  import { GOAL_ROW_LIMITS, WIDGET_METRICS } from "./types.js";
10
10
  import { dateRangeField } from "../fields/dateRange/field.js";
11
11
  import { buildCustomWidgets } from "./customWidget.js";
12
+ import { filterField } from "./filterField.js";
12
13
  //#region src/widgets/registerWidgets.ts
13
14
  /**
14
15
  * Select options must carry static labels: `filterOptions` results are serialized
@@ -132,7 +133,8 @@ const metricWidgetFields = (args, extra = []) => [
132
133
  timeframeSelectField(),
133
134
  customRangeField(),
134
135
  ...extra,
135
- ...args.multiProvider ? [dataSourceField(args)] : []
136
+ ...args.multiProvider ? [dataSourceField(args)] : [],
137
+ filterField()
136
138
  ];
137
139
  const breakdownWidgetFields = (args, spec) => [
138
140
  titleField(args, en[spec.label]),
@@ -150,7 +152,8 @@ const breakdownWidgetFields = (args, spec) => [
150
152
  max: 20,
151
153
  label: labelForKey(keys.widgetFieldLimit)
152
154
  },
153
- ...args.multiProvider ? [dataSourceField(args)] : []
155
+ ...args.multiProvider ? [dataSourceField(args)] : [],
156
+ filterField()
154
157
  ];
155
158
  /** A select, not the breakdown's free number: the goals table is a summary, not a report. */
156
159
  const goalLimitField = () => ({
@@ -1 +1 @@
1
- {"version":3,"file":"registerWidgets.js","names":[],"sources":["../../src/widgets/registerWidgets.ts"],"sourcesContent":["import type {\n\tConfig,\n\tField,\n\tSelectField,\n\tSelectFieldSingleValidation,\n\tWidget,\n\tWidgetWidth,\n} from 'payload'\nimport { type CapabilityRequirement, satisfiesCapabilities } from '../core/capabilities'\nimport type { AnalyticsAdapter, MetricKey } from '../core/contract'\nimport { dateRangeField } from '../fields/dateRange/field'\nimport { TIMEFRAME_PRESETS } from '../timeframe/presets'\nimport { de } from '../translations/de'\nimport { en } from '../translations/en'\nimport type { TranslationKey } from '../translations/keys'\nimport { keys } from '../translations/keys'\nimport { METRIC_KEYS, TIMEFRAME_KEYS } from '../translations/metricKeys'\nimport { labelForKey } from '../translations/server'\nimport { BREAKDOWN_SPECS, type BreakdownSpec } from './breakdownTypes'\nimport { buildCustomWidgets, type CustomWidgetDef } from './customWidget'\nimport { GOAL_ROW_LIMITS, WIDGET_METRICS } from './types'\nimport type { WidgetView } from './viewLink'\n\n/**\n * Select options must carry static labels: `filterOptions` results are serialized\n * into client form state at request time, where a label function cannot cross the\n * server/client boundary.\n */\nconst staticLabel = (key: TranslationKey): Record<string, string> => ({\n\tde: de[key],\n\ten: en[key],\n})\n\nexport interface RegisterWidgetsArgs {\n\tadapters: AnalyticsAdapter[]\n\tmultiProvider: boolean\n\t/**\n\t * True when a tenant's own runtime adapter can exist (`providers.collection` or\n\t * `providers.resolve`). Such an adapter's capabilities are unknown at config time, so\n\t * gating on the config-adapter union would impose a false ceiling: widgets and metric\n\t * options open up, and the per-request sources endpoint plus client pickers narrow per\n\t * request instead.\n\t */\n\tprovidersEnabled: boolean\n\tdisabled: string[]\n\tregister: CustomWidgetDef[]\n\tlocalizeText?: boolean\n\t/** The plugin's configured defaultAdapter, when set; falls back to the first adapter. */\n\tdefaultId?: string\n\t/** `widgets.comparison`; false hides every compare checkbox. Defaults to on. */\n\tcomparison?: boolean\n\t/**\n\t * Where the analytics view mounts, so every built-in widget can link into it. False or\n\t * absent means no view to link to, and the widgets render without the footer link.\n\t */\n\tview?: WidgetView\n}\n\ninterface WidgetDef {\n\tslug: string\n\tcomponent: string\n\tlabel: TranslationKey\n\trequires?: CapabilityRequirement\n\tminWidth?: WidgetWidth\n\tmaxWidth?: WidgetWidth\n\tfields: (args: RegisterWidgetsArgs) => Field[]\n}\n\nexport const widgetIsSupported = (\n\trequires: CapabilityRequirement | undefined,\n\tadapters: AnalyticsAdapter[]\n): boolean => !requires || adapters.some((a) => satisfiesCapabilities(a.capabilities, requires))\n\n/**\n * The widget metric select. Options are limited to metrics at least one configured\n * adapter can serve, mirroring the OR-across-adapters gating used to hide whole widgets;\n * `extra` layers on further requirements (a breakdown widget's dimension, realtime) so\n * the picker never offers a metric the read path would report as unavailable. In\n * multi-provider installs `filterOptions` additionally narrows the picker to the selected\n * `dataSource`'s capabilities; an id not known at config time (a runtime/DB provider)\n * keeps the union. The default clamps to the first option when the preferred metric is\n * not servable, and options can come out empty for exotic adapter sets, which\n * {@link registerWidgets} treats as \"skip this widget\". When `providersEnabled`, the\n * config-adapter filter is skipped entirely: a tenant's own runtime adapter may serve\n * metrics no config adapter does, so every candidate is offered and `filterOptions` alone\n * narrows once a `dataSource` is picked.\n */\nconst metricSelectField = (\n\tcandidates: MetricKey[],\n\targs: RegisterWidgetsArgs,\n\topts: {\n\t\textra?: Omit<CapabilityRequirement, 'metrics'>\n\t\tpreferredDefault?: MetricKey\n\t} = {}\n): Field => {\n\tconst { extra, preferredDefault = 'pageviews' } = opts\n\tconst supports = (adapter: AnalyticsAdapter, metric: MetricKey): boolean =>\n\t\tsatisfiesCapabilities(adapter.capabilities, { ...extra, metrics: [metric] })\n\tconst options = (\n\t\targs.providersEnabled\n\t\t\t? candidates\n\t\t\t: candidates.filter((m) => args.adapters.some((a) => supports(a, m)))\n\t).map((m) => ({ value: m, label: staticLabel(METRIC_KEYS[m]) }))\n\tconst defaultValue = options.some((o) => o.value === preferredDefault)\n\t\t? preferredDefault\n\t\t: options[0]?.value\n\tconst filterOptions: SelectField['filterOptions'] = ({ options: opts, siblingData }) => {\n\t\tconst sourceId = (siblingData as { dataSource?: unknown } | undefined)?.dataSource\n\t\tconst adapter =\n\t\t\ttypeof sourceId === 'string' ? args.adapters.find((a) => a.id === sourceId) : undefined\n\t\tif (!adapter) {\n\t\t\treturn opts\n\t\t}\n\t\treturn opts.filter((o) => typeof o === 'object' && supports(adapter, o.value as MetricKey))\n\t}\n\treturn {\n\t\tname: 'metric',\n\t\ttype: 'select',\n\t\trequired: true,\n\t\t...(defaultValue !== undefined ? { defaultValue } : {}),\n\t\tlabel: labelForKey(keys.widgetFieldMetric),\n\t\toptions,\n\t\tadmin: {\n\t\t\t// A required metric has no meaningful cleared state.\n\t\t\tisClearable: false,\n\t\t\tcomponents: {\n\t\t\t\tField: {\n\t\t\t\t\tpath: '@10x-media/analytics/client#MetricSelectField',\n\t\t\t\t\t...(extra ? { clientProps: { requires: extra } } : {}),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t...(args.multiProvider ? { filterOptions } : {}),\n\t}\n}\n\nconst titleField = (args: RegisterWidgetsArgs, placeholder: string): Field => ({\n\tname: 'title',\n\ttype: 'text',\n\tlabel: labelForKey(keys.widgetFieldTitle),\n\t...(args.localizeText ? { localized: true } : {}),\n\tadmin: { placeholder },\n})\n\nconst timeframeSelectField = (): Field => ({\n\tname: 'timeframe',\n\ttype: 'select',\n\trequired: true,\n\tdefaultValue: 'last30days',\n\tlabel: labelForKey(keys.widgetFieldTimeframe),\n\tadmin: { isClearable: false },\n\toptions: [\n\t\t...TIMEFRAME_PRESETS.map((p) => ({ value: p, label: labelForKey(TIMEFRAME_KEYS[p]) })),\n\t\t{ value: 'custom', label: labelForKey(keys.widgetTimeframeCustom) },\n\t],\n})\n\n/** Reads the previous period too: the trend overlays it, the goals table deltas against it. */\nconst compareField = (): Field => ({\n\tname: 'compare',\n\ttype: 'checkbox',\n\tdefaultValue: false,\n\tlabel: labelForKey(keys.widgetFieldCompare),\n})\n\nconst dataSourceField = (args: RegisterWidgetsArgs): Field => ({\n\tname: 'dataSource',\n\ttype: 'select',\n\tlabel: labelForKey(keys.widgetFieldDataSource),\n\tdefaultValue: args.defaultId ?? args.adapters[0]?.id,\n\tadmin: {\n\t\t// Clearing would leave no source; the widget always reads through one.\n\t\tisClearable: false,\n\t\tcomponents: { Field: { path: '@10x-media/analytics/client#SourceSelectField' } },\n\t},\n\toptions: args.adapters.map((a) => ({ value: a.id, label: a.label })),\n\t// Payload's select validator rejects any value absent from `options`, but runtime\n\t// (DB-registered) provider ids are only known per request, not at config time.\n\tvalidate: ((value) =>\n\t\tvalue === undefined || value === null || (typeof value === 'string' && value.length > 0)\n\t\t\t? true\n\t\t\t: 'invalid data source') as SelectFieldSingleValidation,\n})\n\nconst customRangeField = (): Field =>\n\tdateRangeField({\n\t\tname: 'range',\n\t\tlabel: labelForKey(keys.widgetFieldRange),\n\t\tpickerAppearance: 'dayOnly',\n\t\toverrides: (f) => ({\n\t\t\t...f,\n\t\t\tadmin: {\n\t\t\t\t...f.admin,\n\t\t\t\tcondition: (_data, siblingData) => siblingData?.timeframe === 'custom',\n\t\t\t},\n\t\t}),\n\t})\n\n/** The metric select in a widget's field list. */\nexport const findMetricField = (fields: Field[]): Field | undefined =>\n\tfields.find((field) => 'name' in field && field.name === 'metric')\n\nconst metricWidgetFields = (args: RegisterWidgetsArgs, extra: Field[] = []): Field[] => [\n\ttitleField(args, en[keys.widgetFieldTitlePlaceholder]),\n\tmetricSelectField(WIDGET_METRICS, args),\n\ttimeframeSelectField(),\n\tcustomRangeField(),\n\t...extra,\n\t...(args.multiProvider ? [dataSourceField(args)] : []),\n]\n\nconst breakdownWidgetFields = (args: RegisterWidgetsArgs, spec: BreakdownSpec): Field[] => [\n\ttitleField(args, en[spec.label]),\n\tmetricSelectField(WIDGET_METRICS, args, {\n\t\textra: { dimensions: [spec.dimension] },\n\t\t...(spec.preferredDefault ? { preferredDefault: spec.preferredDefault } : {}),\n\t}),\n\ttimeframeSelectField(),\n\tcustomRangeField(),\n\t{\n\t\tname: 'limit',\n\t\ttype: 'number',\n\t\tdefaultValue: 5,\n\t\tmin: 1,\n\t\tmax: 20,\n\t\tlabel: labelForKey(keys.widgetFieldLimit),\n\t},\n\t...(args.multiProvider ? [dataSourceField(args)] : []),\n]\n\n/** A select, not the breakdown's free number: the goals table is a summary, not a report. */\nconst goalLimitField = (): Field => ({\n\tname: 'limit',\n\ttype: 'select',\n\tdefaultValue: String(GOAL_ROW_LIMITS[0]),\n\tlabel: labelForKey(keys.widgetFieldLimit),\n\tadmin: { isClearable: false },\n\toptions: GOAL_ROW_LIMITS.map((limit) => ({ value: String(limit), label: String(limit) })),\n})\n\nconst goalsWidgetFields = (args: RegisterWidgetsArgs): Field[] => [\n\ttitleField(args, en[keys.widgetGoals]),\n\ttimeframeSelectField(),\n\tcustomRangeField(),\n\tgoalLimitField(),\n\t...(args.comparison === false ? [] : [compareField()]),\n\t...(args.multiProvider ? [dataSourceField(args)] : []),\n]\n\nconst realtimeWidgetFields = (args: RegisterWidgetsArgs): Field[] => [\n\ttitleField(args, en[keys.widgetFieldTitlePlaceholder]),\n\tmetricSelectField(['visitors', 'pageviews'], args, {\n\t\textra: { realtime: true },\n\t\tpreferredDefault: 'visitors',\n\t}),\n\t{\n\t\tname: 'windowMinutes',\n\t\ttype: 'select',\n\t\tdefaultValue: '30',\n\t\tlabel: labelForKey(keys.widgetFieldWindow),\n\t\tadmin: { isClearable: false },\n\t\toptions: [\n\t\t\t{ value: '5', label: '5 min' },\n\t\t\t{ value: '15', label: '15 min' },\n\t\t\t{ value: '30', label: '30 min' },\n\t\t\t{ value: '60', label: '60 min' },\n\t\t],\n\t},\n\t...(args.multiProvider ? [dataSourceField(args)] : []),\n]\n\nconst WIDGET_DEFS: WidgetDef[] = [\n\t{\n\t\tslug: 'analytics-metric',\n\t\tcomponent: '@10x-media/analytics/rsc#AnalyticsMetricWidget',\n\t\tlabel: keys.widgetMetricLabel,\n\t\tminWidth: 'x-small',\n\t\tmaxWidth: 'medium',\n\t\tfields: metricWidgetFields,\n\t},\n\t{\n\t\tslug: 'analytics-trend',\n\t\tcomponent: '@10x-media/analytics/rsc#AnalyticsTrendWidget',\n\t\tlabel: keys.widgetTrendLabel,\n\t\trequires: { metrics: ['pageviews'] },\n\t\tminWidth: 'small',\n\t\tmaxWidth: 'full',\n\t\tfields: (args) => metricWidgetFields(args, args.comparison === false ? [] : [compareField()]),\n\t},\n\t{\n\t\tslug: 'analytics-realtime',\n\t\tcomponent: '@10x-media/analytics/rsc#AnalyticsRealtimeWidget',\n\t\tlabel: keys.widgetRealtimeLabel,\n\t\trequires: { realtime: true },\n\t\tminWidth: 'small' as WidgetWidth,\n\t\tmaxWidth: 'medium' as WidgetWidth,\n\t\tfields: realtimeWidgetFields,\n\t},\n\t{\n\t\tslug: 'analytics-goals',\n\t\tcomponent: '@10x-media/analytics/rsc#AnalyticsGoalsWidget',\n\t\tlabel: keys.widgetGoals,\n\t\trequires: { metrics: ['conversions'], dimensions: ['goal'] },\n\t\tminWidth: 'small' as WidgetWidth,\n\t\tmaxWidth: 'large' as WidgetWidth,\n\t\tfields: goalsWidgetFields,\n\t},\n\t...BREAKDOWN_SPECS.map(\n\t\t(spec): WidgetDef => ({\n\t\t\tslug: spec.slug,\n\t\t\tcomponent: '@10x-media/analytics/rsc#AnalyticsBreakdownWidget',\n\t\t\tlabel: spec.label,\n\t\t\trequires: { dimensions: [spec.dimension] },\n\t\t\tminWidth: 'small' as WidgetWidth,\n\t\t\tmaxWidth: 'large' as WidgetWidth,\n\t\t\tfields: (args) => breakdownWidgetFields(args, spec),\n\t\t})\n\t),\n]\n\nexport const registerWidgets = (config: Config, args: RegisterWidgetsArgs): void => {\n\tconst built: Widget[] = []\n\tfor (const def of WIDGET_DEFS) {\n\t\tif (args.disabled.includes(def.slug)) {\n\t\t\tcontinue\n\t\t}\n\t\tif (!args.providersEnabled && !widgetIsSupported(def.requires, args.adapters)) {\n\t\t\tcontinue\n\t\t}\n\t\tconst fields = def.fields(args)\n\t\t// A required metric select with no servable option would make the widget\n\t\t// impossible to configure; skip it like an unsupported widget.\n\t\tconst metricField = findMetricField(fields)\n\t\tif (metricField && 'options' in metricField && metricField.options.length === 0) {\n\t\t\tcontinue\n\t\t}\n\t\tbuilt.push({\n\t\t\tslug: def.slug,\n\t\t\tComponent: { path: def.component, serverProps: { view: args.view ?? false } },\n\t\t\tlabel: labelForKey(def.label),\n\t\t\tfields,\n\t\t\tminWidth: def.minWidth,\n\t\t\tmaxWidth: def.maxWidth,\n\t\t})\n\t}\n\tbuilt.push(...buildCustomWidgets(args.register, args.adapters, args.disabled))\n\tif (!built.length) {\n\t\treturn\n\t}\n\tconfig.admin ??= {}\n\tconfig.admin.dashboard ??= { widgets: [] }\n\tconfig.admin.dashboard.widgets ??= []\n\tconfig.admin.dashboard.widgets.push(...built)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA4BA,MAAM,eAAe,SAAiD;CACrE,IAAI,GAAG;CACP,IAAI,GAAG;AACR;AAqCA,MAAa,qBACZ,UACA,aACa,CAAC,YAAY,SAAS,MAAM,MAAM,sBAAsB,EAAE,cAAc,QAAQ,CAAC;;;;;;;;;;;;;;;AAgB/F,MAAM,qBACL,YACA,MACA,OAGI,CAAC,MACM;CACX,MAAM,EAAE,OAAO,mBAAmB,gBAAgB;CAClD,MAAM,YAAY,SAA2B,WAC5C,sBAAsB,QAAQ,cAAc;EAAE,GAAG;EAAO,SAAS,CAAC,MAAM;CAAE,CAAC;CAC5E,MAAM,WACL,KAAK,mBACF,aACA,WAAW,QAAQ,MAAM,KAAK,SAAS,MAAM,MAAM,SAAS,GAAG,CAAC,CAAC,CAAC,GACpE,KAAK,OAAO;EAAE,OAAO;EAAG,OAAO,YAAY,YAAY,EAAE;CAAE,EAAE;CAC/D,MAAM,eAAe,QAAQ,MAAM,MAAM,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AM,QACV;CAED,OAAO,UAAU,CAAC;CAClB,OAAO,MAAM,cAAc,EAAE,SAAS,CAAC,EAAE;CACzC,OAAO,MAAM,UAAU,YAAY,CAAC;CACpC,OAAO,MAAM,UAAU,QAAQ,KAAK,GAAG,KAAK;AAC7C"}
1
+ {"version":3,"file":"registerWidgets.js","names":[],"sources":["../../src/widgets/registerWidgets.ts"],"sourcesContent":["import type {\n\tConfig,\n\tField,\n\tSelectField,\n\tSelectFieldSingleValidation,\n\tWidget,\n\tWidgetWidth,\n} from 'payload'\nimport { type CapabilityRequirement, satisfiesCapabilities } from '../core/capabilities'\nimport type { AnalyticsAdapter, MetricKey } from '../core/contract'\nimport { dateRangeField } from '../fields/dateRange/field'\nimport { TIMEFRAME_PRESETS } from '../timeframe/presets'\nimport { de } from '../translations/de'\nimport { en } from '../translations/en'\nimport type { TranslationKey } from '../translations/keys'\nimport { keys } from '../translations/keys'\nimport { METRIC_KEYS, TIMEFRAME_KEYS } from '../translations/metricKeys'\nimport { labelForKey } from '../translations/server'\nimport { BREAKDOWN_SPECS, type BreakdownSpec } from './breakdownTypes'\nimport { buildCustomWidgets, type CustomWidgetDef } from './customWidget'\nimport { filterField } from './filterField'\nimport { GOAL_ROW_LIMITS, WIDGET_METRICS } from './types'\nimport type { WidgetView } from './viewLink'\n\n/**\n * Select options must carry static labels: `filterOptions` results are serialized\n * into client form state at request time, where a label function cannot cross the\n * server/client boundary.\n */\nconst staticLabel = (key: TranslationKey): Record<string, string> => ({\n\tde: de[key],\n\ten: en[key],\n})\n\nexport interface RegisterWidgetsArgs {\n\tadapters: AnalyticsAdapter[]\n\tmultiProvider: boolean\n\t/**\n\t * True when a tenant's own runtime adapter can exist (`providers.collection` or\n\t * `providers.resolve`). Such an adapter's capabilities are unknown at config time, so\n\t * gating on the config-adapter union would impose a false ceiling: widgets and metric\n\t * options open up, and the per-request sources endpoint plus client pickers narrow per\n\t * request instead.\n\t */\n\tprovidersEnabled: boolean\n\tdisabled: string[]\n\tregister: CustomWidgetDef[]\n\tlocalizeText?: boolean\n\t/** The plugin's configured defaultAdapter, when set; falls back to the first adapter. */\n\tdefaultId?: string\n\t/** `widgets.comparison`; false hides every compare checkbox. Defaults to on. */\n\tcomparison?: boolean\n\t/**\n\t * Where the analytics view mounts, so every built-in widget can link into it. False or\n\t * absent means no view to link to, and the widgets render without the footer link.\n\t */\n\tview?: WidgetView\n}\n\ninterface WidgetDef {\n\tslug: string\n\tcomponent: string\n\tlabel: TranslationKey\n\trequires?: CapabilityRequirement\n\tminWidth?: WidgetWidth\n\tmaxWidth?: WidgetWidth\n\tfields: (args: RegisterWidgetsArgs) => Field[]\n}\n\nexport const widgetIsSupported = (\n\trequires: CapabilityRequirement | undefined,\n\tadapters: AnalyticsAdapter[]\n): boolean => !requires || adapters.some((a) => satisfiesCapabilities(a.capabilities, requires))\n\n/**\n * The widget metric select. Options are limited to metrics at least one configured\n * adapter can serve, mirroring the OR-across-adapters gating used to hide whole widgets;\n * `extra` layers on further requirements (a breakdown widget's dimension, realtime) so\n * the picker never offers a metric the read path would report as unavailable. In\n * multi-provider installs `filterOptions` additionally narrows the picker to the selected\n * `dataSource`'s capabilities; an id not known at config time (a runtime/DB provider)\n * keeps the union. The default clamps to the first option when the preferred metric is\n * not servable, and options can come out empty for exotic adapter sets, which\n * {@link registerWidgets} treats as \"skip this widget\". When `providersEnabled`, the\n * config-adapter filter is skipped entirely: a tenant's own runtime adapter may serve\n * metrics no config adapter does, so every candidate is offered and `filterOptions` alone\n * narrows once a `dataSource` is picked.\n */\nconst metricSelectField = (\n\tcandidates: MetricKey[],\n\targs: RegisterWidgetsArgs,\n\topts: {\n\t\textra?: Omit<CapabilityRequirement, 'metrics'>\n\t\tpreferredDefault?: MetricKey\n\t} = {}\n): Field => {\n\tconst { extra, preferredDefault = 'pageviews' } = opts\n\tconst supports = (adapter: AnalyticsAdapter, metric: MetricKey): boolean =>\n\t\tsatisfiesCapabilities(adapter.capabilities, { ...extra, metrics: [metric] })\n\tconst options = (\n\t\targs.providersEnabled\n\t\t\t? candidates\n\t\t\t: candidates.filter((m) => args.adapters.some((a) => supports(a, m)))\n\t).map((m) => ({ value: m, label: staticLabel(METRIC_KEYS[m]) }))\n\tconst defaultValue = options.some((o) => o.value === preferredDefault)\n\t\t? preferredDefault\n\t\t: options[0]?.value\n\tconst filterOptions: SelectField['filterOptions'] = ({ options: opts, siblingData }) => {\n\t\tconst sourceId = (siblingData as { dataSource?: unknown } | undefined)?.dataSource\n\t\tconst adapter =\n\t\t\ttypeof sourceId === 'string' ? args.adapters.find((a) => a.id === sourceId) : undefined\n\t\tif (!adapter) {\n\t\t\treturn opts\n\t\t}\n\t\treturn opts.filter((o) => typeof o === 'object' && supports(adapter, o.value as MetricKey))\n\t}\n\treturn {\n\t\tname: 'metric',\n\t\ttype: 'select',\n\t\trequired: true,\n\t\t...(defaultValue !== undefined ? { defaultValue } : {}),\n\t\tlabel: labelForKey(keys.widgetFieldMetric),\n\t\toptions,\n\t\tadmin: {\n\t\t\t// A required metric has no meaningful cleared state.\n\t\t\tisClearable: false,\n\t\t\tcomponents: {\n\t\t\t\tField: {\n\t\t\t\t\tpath: '@10x-media/analytics/client#MetricSelectField',\n\t\t\t\t\t...(extra ? { clientProps: { requires: extra } } : {}),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t...(args.multiProvider ? { filterOptions } : {}),\n\t}\n}\n\nconst titleField = (args: RegisterWidgetsArgs, placeholder: string): Field => ({\n\tname: 'title',\n\ttype: 'text',\n\tlabel: labelForKey(keys.widgetFieldTitle),\n\t...(args.localizeText ? { localized: true } : {}),\n\tadmin: { placeholder },\n})\n\nconst timeframeSelectField = (): Field => ({\n\tname: 'timeframe',\n\ttype: 'select',\n\trequired: true,\n\tdefaultValue: 'last30days',\n\tlabel: labelForKey(keys.widgetFieldTimeframe),\n\tadmin: { isClearable: false },\n\toptions: [\n\t\t...TIMEFRAME_PRESETS.map((p) => ({ value: p, label: labelForKey(TIMEFRAME_KEYS[p]) })),\n\t\t{ value: 'custom', label: labelForKey(keys.widgetTimeframeCustom) },\n\t],\n})\n\n/** Reads the previous period too: the trend overlays it, the goals table deltas against it. */\nconst compareField = (): Field => ({\n\tname: 'compare',\n\ttype: 'checkbox',\n\tdefaultValue: false,\n\tlabel: labelForKey(keys.widgetFieldCompare),\n})\n\nconst dataSourceField = (args: RegisterWidgetsArgs): Field => ({\n\tname: 'dataSource',\n\ttype: 'select',\n\tlabel: labelForKey(keys.widgetFieldDataSource),\n\tdefaultValue: args.defaultId ?? args.adapters[0]?.id,\n\tadmin: {\n\t\t// Clearing would leave no source; the widget always reads through one.\n\t\tisClearable: false,\n\t\tcomponents: { Field: { path: '@10x-media/analytics/client#SourceSelectField' } },\n\t},\n\toptions: args.adapters.map((a) => ({ value: a.id, label: a.label })),\n\t// Payload's select validator rejects any value absent from `options`, but runtime\n\t// (DB-registered) provider ids are only known per request, not at config time.\n\tvalidate: ((value) =>\n\t\tvalue === undefined || value === null || (typeof value === 'string' && value.length > 0)\n\t\t\t? true\n\t\t\t: 'invalid data source') as SelectFieldSingleValidation,\n})\n\nconst customRangeField = (): Field =>\n\tdateRangeField({\n\t\tname: 'range',\n\t\tlabel: labelForKey(keys.widgetFieldRange),\n\t\tpickerAppearance: 'dayOnly',\n\t\toverrides: (f) => ({\n\t\t\t...f,\n\t\t\tadmin: {\n\t\t\t\t...f.admin,\n\t\t\t\tcondition: (_data, siblingData) => siblingData?.timeframe === 'custom',\n\t\t\t},\n\t\t}),\n\t})\n\n/** The metric select in a widget's field list. */\nexport const findMetricField = (fields: Field[]): Field | undefined =>\n\tfields.find((field) => 'name' in field && field.name === 'metric')\n\nconst metricWidgetFields = (args: RegisterWidgetsArgs, extra: Field[] = []): Field[] => [\n\ttitleField(args, en[keys.widgetFieldTitlePlaceholder]),\n\tmetricSelectField(WIDGET_METRICS, args),\n\ttimeframeSelectField(),\n\tcustomRangeField(),\n\t...extra,\n\t...(args.multiProvider ? [dataSourceField(args)] : []),\n\tfilterField(),\n]\n\nconst breakdownWidgetFields = (args: RegisterWidgetsArgs, spec: BreakdownSpec): Field[] => [\n\ttitleField(args, en[spec.label]),\n\tmetricSelectField(WIDGET_METRICS, args, {\n\t\textra: { dimensions: [spec.dimension] },\n\t\t...(spec.preferredDefault ? { preferredDefault: spec.preferredDefault } : {}),\n\t}),\n\ttimeframeSelectField(),\n\tcustomRangeField(),\n\t{\n\t\tname: 'limit',\n\t\ttype: 'number',\n\t\tdefaultValue: 5,\n\t\tmin: 1,\n\t\tmax: 20,\n\t\tlabel: labelForKey(keys.widgetFieldLimit),\n\t},\n\t...(args.multiProvider ? [dataSourceField(args)] : []),\n\tfilterField(),\n]\n\n/** A select, not the breakdown's free number: the goals table is a summary, not a report. */\nconst goalLimitField = (): Field => ({\n\tname: 'limit',\n\ttype: 'select',\n\tdefaultValue: String(GOAL_ROW_LIMITS[0]),\n\tlabel: labelForKey(keys.widgetFieldLimit),\n\tadmin: { isClearable: false },\n\toptions: GOAL_ROW_LIMITS.map((limit) => ({ value: String(limit), label: String(limit) })),\n})\n\nconst goalsWidgetFields = (args: RegisterWidgetsArgs): Field[] => [\n\ttitleField(args, en[keys.widgetGoals]),\n\ttimeframeSelectField(),\n\tcustomRangeField(),\n\tgoalLimitField(),\n\t...(args.comparison === false ? [] : [compareField()]),\n\t...(args.multiProvider ? [dataSourceField(args)] : []),\n]\n\nconst realtimeWidgetFields = (args: RegisterWidgetsArgs): Field[] => [\n\ttitleField(args, en[keys.widgetFieldTitlePlaceholder]),\n\tmetricSelectField(['visitors', 'pageviews'], args, {\n\t\textra: { realtime: true },\n\t\tpreferredDefault: 'visitors',\n\t}),\n\t{\n\t\tname: 'windowMinutes',\n\t\ttype: 'select',\n\t\tdefaultValue: '30',\n\t\tlabel: labelForKey(keys.widgetFieldWindow),\n\t\tadmin: { isClearable: false },\n\t\toptions: [\n\t\t\t{ value: '5', label: '5 min' },\n\t\t\t{ value: '15', label: '15 min' },\n\t\t\t{ value: '30', label: '30 min' },\n\t\t\t{ value: '60', label: '60 min' },\n\t\t],\n\t},\n\t...(args.multiProvider ? [dataSourceField(args)] : []),\n]\n\nconst WIDGET_DEFS: WidgetDef[] = [\n\t{\n\t\tslug: 'analytics-metric',\n\t\tcomponent: '@10x-media/analytics/rsc#AnalyticsMetricWidget',\n\t\tlabel: keys.widgetMetricLabel,\n\t\tminWidth: 'x-small',\n\t\tmaxWidth: 'medium',\n\t\tfields: metricWidgetFields,\n\t},\n\t{\n\t\tslug: 'analytics-trend',\n\t\tcomponent: '@10x-media/analytics/rsc#AnalyticsTrendWidget',\n\t\tlabel: keys.widgetTrendLabel,\n\t\trequires: { metrics: ['pageviews'] },\n\t\tminWidth: 'small',\n\t\tmaxWidth: 'full',\n\t\tfields: (args) => metricWidgetFields(args, args.comparison === false ? [] : [compareField()]),\n\t},\n\t{\n\t\tslug: 'analytics-realtime',\n\t\tcomponent: '@10x-media/analytics/rsc#AnalyticsRealtimeWidget',\n\t\tlabel: keys.widgetRealtimeLabel,\n\t\trequires: { realtime: true },\n\t\tminWidth: 'small' as WidgetWidth,\n\t\tmaxWidth: 'medium' as WidgetWidth,\n\t\tfields: realtimeWidgetFields,\n\t},\n\t{\n\t\tslug: 'analytics-goals',\n\t\tcomponent: '@10x-media/analytics/rsc#AnalyticsGoalsWidget',\n\t\tlabel: keys.widgetGoals,\n\t\trequires: { metrics: ['conversions'], dimensions: ['goal'] },\n\t\tminWidth: 'small' as WidgetWidth,\n\t\tmaxWidth: 'large' as WidgetWidth,\n\t\tfields: goalsWidgetFields,\n\t},\n\t...BREAKDOWN_SPECS.map(\n\t\t(spec): WidgetDef => ({\n\t\t\tslug: spec.slug,\n\t\t\tcomponent: '@10x-media/analytics/rsc#AnalyticsBreakdownWidget',\n\t\t\tlabel: spec.label,\n\t\t\trequires: { dimensions: [spec.dimension] },\n\t\t\tminWidth: 'small' as WidgetWidth,\n\t\t\tmaxWidth: 'large' as WidgetWidth,\n\t\t\tfields: (args) => breakdownWidgetFields(args, spec),\n\t\t})\n\t),\n]\n\nexport const registerWidgets = (config: Config, args: RegisterWidgetsArgs): void => {\n\tconst built: Widget[] = []\n\tfor (const def of WIDGET_DEFS) {\n\t\tif (args.disabled.includes(def.slug)) {\n\t\t\tcontinue\n\t\t}\n\t\tif (!args.providersEnabled && !widgetIsSupported(def.requires, args.adapters)) {\n\t\t\tcontinue\n\t\t}\n\t\tconst fields = def.fields(args)\n\t\t// A required metric select with no servable option would make the widget\n\t\t// impossible to configure; skip it like an unsupported widget.\n\t\tconst metricField = findMetricField(fields)\n\t\tif (metricField && 'options' in metricField && metricField.options.length === 0) {\n\t\t\tcontinue\n\t\t}\n\t\tbuilt.push({\n\t\t\tslug: def.slug,\n\t\t\tComponent: { path: def.component, serverProps: { view: args.view ?? false } },\n\t\t\tlabel: labelForKey(def.label),\n\t\t\tfields,\n\t\t\tminWidth: def.minWidth,\n\t\t\tmaxWidth: def.maxWidth,\n\t\t})\n\t}\n\tbuilt.push(...buildCustomWidgets(args.register, args.adapters, args.disabled))\n\tif (!built.length) {\n\t\treturn\n\t}\n\tconfig.admin ??= {}\n\tconfig.admin.dashboard ??= { widgets: [] }\n\tconfig.admin.dashboard.widgets ??= []\n\tconfig.admin.dashboard.widgets.push(...built)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA6BA,MAAM,eAAe,SAAiD;CACrE,IAAI,GAAG;CACP,IAAI,GAAG;AACR;AAqCA,MAAa,qBACZ,UACA,aACa,CAAC,YAAY,SAAS,MAAM,MAAM,sBAAsB,EAAE,cAAc,QAAQ,CAAC;;;;;;;;;;;;;;;AAgB/F,MAAM,qBACL,YACA,MACA,OAGI,CAAC,MACM;CACX,MAAM,EAAE,OAAO,mBAAmB,gBAAgB;CAClD,MAAM,YAAY,SAA2B,WAC5C,sBAAsB,QAAQ,cAAc;EAAE,GAAG;EAAO,SAAS,CAAC,MAAM;CAAE,CAAC;CAC5E,MAAM,WACL,KAAK,mBACF,aACA,WAAW,QAAQ,MAAM,KAAK,SAAS,M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O,YAAY,IAAI,KAAK;GAC5B;GACA,UAAU,IAAI;GACd,UAAU,IAAI;EACf,CAAC;CACF;CACA,MAAM,KAAK,GAAG,mBAAmB,KAAK,UAAU,KAAK,UAAU,KAAK,QAAQ,CAAC;CAC7E,IAAI,CAAC,MAAM,QACV;CAED,OAAO,UAAU,CAAC;CAClB,OAAO,MAAM,cAAc,EAAE,SAAS,CAAC,EAAE;CACzC,OAAO,MAAM,UAAU,YAAY,CAAC;CACpC,OAAO,MAAM,UAAU,QAAQ,KAAK,GAAG,KAAK;AAC7C"}
@@ -0,0 +1,15 @@
1
+ import { DimensionKey, FilterOperator } from "../core/contract.js";
2
+ //#region src/widgets/types.d.ts
3
+ /**
4
+ * The optional one-filter group a widget stores. Every part is optional because the group
5
+ * is only ever partly filled while it is being configured; a filter counts as set once it
6
+ * has a dimension and a value.
7
+ */
8
+ interface WidgetFilter {
9
+ dimension?: DimensionKey;
10
+ operator?: FilterOperator;
11
+ value?: string;
12
+ }
13
+ //#endregion
14
+ export { WidgetFilter };
15
+ //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","names":[],"sources":["../../src/widgets/types.ts"],"sourcesContent":["import type { MetricKey } from '../core/contract'\nimport type { TimeframePreset } from '../timeframe/presets'\n\nexport interface WidgetRange {\n\tfrom?: string\n\tto?: string\n}\n\nexport interface MetricWidgetData {\n\ttitle?: string\n\tmetric?: MetricKey\n\ttimeframe?: TimeframePreset | 'custom'\n\trange?: WidgetRange\n\tdataSource?: string\n\t/** Trend widget only: overlay the previous period on the chart. */\n\tcompare?: boolean\n}\n\nexport interface GoalsWidgetData {\n\ttitle?: string\n\ttimeframe?: TimeframePreset | 'custom'\n\trange?: WidgetRange\n\t/** One of {@link GOAL_ROW_LIMITS}, stored as the select's string value. */\n\tlimit?: string | number\n\tcompare?: boolean\n\tdataSource?: string\n}\n\n/** Row counts the goals widget offers; the first is its default. */\nexport const GOAL_ROW_LIMITS = [10, 25, 50] as const\n\nexport type GoalRowLimit = (typeof GOAL_ROW_LIMITS)[number]\n\n/** The stored select value as a row count, falling back to the default for anything else. */\nexport const resolveGoalRowLimit = (value: unknown): GoalRowLimit => {\n\tconst parsed = typeof value === 'string' || typeof value === 'number' ? Number(value) : Number.NaN\n\tconst match = GOAL_ROW_LIMITS.find((limit) => limit === parsed)\n\treturn match ?? GOAL_ROW_LIMITS[0]\n}\n\nexport const WIDGET_METRICS: MetricKey[] = [\n\t'pageviews',\n\t'visitors',\n\t'sessions',\n\t'avgDuration',\n\t'bounceRate',\n\t'events',\n\t'conversions',\n\t'revenue',\n\t'scrollDepth',\n]\n"],"mappings":";;AA6BA,MAAa,kBAAkB;CAAC;CAAI;CAAI;AAAE;;AAK1C,MAAa,uBAAuB,UAAiC;CACpE,MAAM,SAAS,OAAO,UAAU,YAAY,OAAO,UAAU,WAAW,OAAO,KAAK,IAAI;CAExF,OADc,gBAAgB,MAAM,UAAU,UAAU,MAC7C,KAAK,gBAAgB;AACjC;AAEA,MAAa,iBAA8B;CAC1C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD"}
1
+ {"version":3,"file":"types.js","names":[],"sources":["../../src/widgets/types.ts"],"sourcesContent":["import type { DimensionKey, FilterOperator, MetricKey } from '../core/contract'\nimport type { TimeframePreset } from '../timeframe/presets'\n\nexport interface WidgetRange {\n\tfrom?: string\n\tto?: string\n}\n\n/**\n * The optional one-filter group a widget stores. Every part is optional because the group\n * is only ever partly filled while it is being configured; a filter counts as set once it\n * has a dimension and a value.\n */\nexport interface WidgetFilter {\n\tdimension?: DimensionKey\n\toperator?: FilterOperator\n\tvalue?: string\n}\n\nexport interface MetricWidgetData {\n\ttitle?: string\n\tmetric?: MetricKey\n\ttimeframe?: TimeframePreset | 'custom'\n\trange?: WidgetRange\n\tdataSource?: string\n\t/** Trend widget only: overlay the previous period on the chart. */\n\tcompare?: boolean\n\tfilter?: WidgetFilter\n}\n\nexport interface GoalsWidgetData {\n\ttitle?: string\n\ttimeframe?: TimeframePreset | 'custom'\n\trange?: WidgetRange\n\t/** One of {@link GOAL_ROW_LIMITS}, stored as the select's string value. */\n\tlimit?: string | number\n\tcompare?: boolean\n\tdataSource?: string\n}\n\n/** Row counts the goals widget offers; the first is its default. */\nexport const GOAL_ROW_LIMITS = [10, 25, 50] as const\n\nexport type GoalRowLimit = (typeof GOAL_ROW_LIMITS)[number]\n\n/** The stored select value as a row count, falling back to the default for anything else. */\nexport const resolveGoalRowLimit = (value: unknown): GoalRowLimit => {\n\tconst parsed = typeof value === 'string' || typeof value === 'number' ? Number(value) : Number.NaN\n\tconst match = GOAL_ROW_LIMITS.find((limit) => limit === parsed)\n\treturn match ?? GOAL_ROW_LIMITS[0]\n}\n\nexport const WIDGET_METRICS: MetricKey[] = [\n\t'pageviews',\n\t'visitors',\n\t'sessions',\n\t'avgDuration',\n\t'bounceRate',\n\t'events',\n\t'conversions',\n\t'revenue',\n\t'scrollDepth',\n]\n"],"mappings":";;AAyCA,MAAa,kBAAkB;CAAC;CAAI;CAAI;AAAE;;AAK1C,MAAa,uBAAuB,UAAiC;CACpE,MAAM,SAAS,OAAO,UAAU,YAAY,OAAO,UAAU,WAAW,OAAO,KAAK,IAAI;CAExF,OADc,gBAAgB,MAAM,UAAU,UAAU,MAC7C,KAAK,gBAAgB;AACjC;AAEA,MAAa,iBAA8B;CAC1C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD"}
@@ -46,13 +46,16 @@ const viewHref = (args) => {
46
46
  range: args.defaultRange,
47
47
  metric: args.defaultMetric
48
48
  };
49
+ const tab = args.tab ?? "pages";
50
+ const dim = args.dim === TAB_DIMENSIONS[tab][0] ? void 0 : args.dim;
49
51
  const state = {
50
52
  ...rangeOf(args, defaults),
51
53
  compare: args.compare === true,
52
54
  ...args.source === void 0 ? {} : { source: args.source },
53
55
  metric: args.metric ?? defaults.metric,
54
- tab: args.tab ?? "pages",
55
- filters: [],
56
+ tab,
57
+ ...dim === void 0 ? {} : { dim },
58
+ filters: args.filters ?? [],
56
59
  limit: 10
57
60
  };
58
61
  const path = formatAdminURL({
@@ -1 +1 @@
1
- {"version":3,"file":"viewLink.js","names":[],"sources":["../../src/widgets/viewLink.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport { formatAdminURL } from 'payload/shared'\nimport type { DateRange, DimensionKey, MetricKey } from '../core/contract'\nimport { MAX_QUERY_RANGE_DAYS } from '../query/limits'\nimport type { TimeframePreset } from '../timeframe/presets'\nimport { zonedCalendarDay } from '../timeframe/tz'\nimport { BREAKDOWN_TABS, type BreakdownTab, TAB_DIMENSIONS } from '../view/gating'\nimport {\n\tDEFAULT_VIEW_LIMIT,\n\tDEFAULT_VIEW_RANGE,\n\tDEFAULT_VIEW_TAB,\n\tserializeViewState,\n\tVIEW_RANGE_PRESETS,\n\ttype ViewDefaults,\n\ttype ViewState,\n} from '../view/state'\n\n/**\n * The view as a widget sees it: where it mounts and what it opens on, or false when the\n * app turned it off. The defaults travel with the path because a link must leave out\n * exactly what the view would have defaulted to anyway.\n */\nexport type WidgetView =\n\t| { path: string; defaultRange: TimeframePreset; defaultMetric: MetricKey }\n\t| false\n\n/** What `registerWidgets` adds to every built-in widget's server props. */\nexport interface WidgetViewProps {\n\tview?: WidgetView\n}\n\nexport interface ViewHrefArgs {\n\tadminRoute: string\n\tviewPath: string\n\t/** The install's own starting point, so the link omits what the view defaults to. */\n\tdefaultRange: TimeframePreset\n\tdefaultMetric: MetricKey\n\tsource?: string\n\ttimeframe: TimeframePreset | 'custom'\n\t/** The widget's own window, needed only for a custom timeframe. */\n\trange?: DateRange\n\ttimezone: string\n\tcompare?: boolean\n\tmetric?: MetricKey\n\ttab?: BreakdownTab\n}\n\n/** `allTime` is no range the view can hold, so an install defaulting to it opens here. */\nconst fallbackRange = (defaults: ViewDefaults): TimeframePreset =>\n\tdefaults.range === 'allTime' ? DEFAULT_VIEW_RANGE : defaults.range\n\nconst DAY_MS = 86_400_000\n\n/**\n * The widest custom window the view will accept, as a start day. `parseViewState` drops a\n * wider one and opens on the default range instead, silently, so a widget on a longer\n * window links to the last `MAX_QUERY_RANGE_DAYS` days of it: the most of what the widget\n * shows that the view can show back.\n */\nconst clampStartDay = (from: string, to: string): string => {\n\tconst start = Date.parse(`${from}T00:00:00.000Z`)\n\tconst end = Date.parse(`${to}T00:00:00.000Z`)\n\tif (Number.isNaN(start) || Number.isNaN(end)) {\n\t\treturn from\n\t}\n\t// Both days are read whole, so the cap counts them inclusively.\n\tconst earliest = end - (MAX_QUERY_RANGE_DAYS - 1) * DAY_MS\n\treturn start < earliest ? new Date(earliest).toISOString().slice(0, 10) : from\n}\n\n/**\n * The widget's window as the view's toolbar can hold it. A preset the toolbar does not\n * offer (`allTime`, `thisMonth`, `thisYear`) would select nothing there, so the link drops\n * the range instead and the view opens on its own default.\n */\nconst rangeOf = (\n\targs: ViewHrefArgs,\n\tdefaults: ViewDefaults\n): Pick<ViewState, 'range' | 'from' | 'to'> => {\n\tif (args.timeframe === 'custom') {\n\t\tif (!args.range) {\n\t\t\treturn { range: fallbackRange(defaults) }\n\t\t}\n\t\tconst to = zonedCalendarDay(args.range.end, args.timezone)\n\t\treturn {\n\t\t\trange: 'custom',\n\t\t\tfrom: clampStartDay(zonedCalendarDay(args.range.start, args.timezone), to),\n\t\t\tto,\n\t\t}\n\t}\n\treturn VIEW_RANGE_PRESETS.includes(args.timeframe)\n\t\t? { range: args.timeframe }\n\t\t: { range: fallbackRange(defaults) }\n}\n\n/**\n * A relative admin link opening the analytics view on what the widget shows. Nothing is\n * coerced against the source's capabilities here: the view does that on open, so a link\n * naming something the selected source cannot serve still lands on a working view.\n */\nexport const viewHref = (args: ViewHrefArgs): string => {\n\tconst defaults: ViewDefaults = { range: args.defaultRange, metric: args.defaultMetric }\n\tconst state: ViewState = {\n\t\t...rangeOf(args, defaults),\n\t\tcompare: args.compare === true,\n\t\t...(args.source === undefined ? {} : { source: args.source }),\n\t\tmetric: args.metric ?? defaults.metric,\n\t\ttab: args.tab ?? DEFAULT_VIEW_TAB,\n\t\tfilters: [],\n\t\tlimit: DEFAULT_VIEW_LIMIT,\n\t}\n\t// `resolveView` refuses a path without a leading slash, so the option cannot be wider.\n\tconst path = formatAdminURL({\n\t\tadminRoute: args.adminRoute,\n\t\tpath: args.viewPath as `/${string}`,\n\t})\n\tconst query = serializeViewState(state, defaults).toString()\n\treturn query ? `${path}?${query}` : path\n}\n\n/**\n * The same link for a built-in widget, or nothing at all when the view is off. Omitting\n * `timeframe` opens the view on its configured range, for a widget (realtime) whose own\n * rolling window is no range the view can hold.\n */\nexport const widgetViewHref = (\n\tview: WidgetView | undefined,\n\treq: PayloadRequest,\n\targs: Omit<\n\t\tViewHrefArgs,\n\t\t'adminRoute' | 'viewPath' | 'defaultRange' | 'defaultMetric' | 'timeframe'\n\t> & { timeframe?: TimeframePreset | 'custom' }\n): string | undefined =>\n\tview\n\t\t? viewHref({\n\t\t\t\t...args,\n\t\t\t\ttimeframe: args.timeframe ?? view.defaultRange,\n\t\t\t\tadminRoute: req.payload.config.routes.admin,\n\t\t\t\tviewPath: view.path,\n\t\t\t\tdefaultRange: view.defaultRange,\n\t\t\t\tdefaultMetric: view.defaultMetric,\n\t\t\t})\n\t\t: undefined\n\n/** The breakdown tab that offers a dimension; every contract dimension belongs to one. */\nexport const viewTabForDimension = (dimension: DimensionKey): BreakdownTab | undefined =>\n\tBREAKDOWN_TABS.find((tab) => TAB_DIMENSIONS[tab].includes(dimension))\n"],"mappings":";;;;;;AAgDA,MAAM,iBAAiB,aACtB,SAAS,UAAU,YAAY,qBAAqB,SAAS;AAE9D,MAAM,SAAS;;;;;;;AAQf,MAAM,iBAAiB,MAAc,OAAuB;CAC3D,MAAM,QAAQ,KAAK,MAAM,GAAG,KAAK,eAAe;CAChD,MAAM,MAAM,KAAK,MAAM,GAAG,GAAG,eAAe;CAC5C,IAAI,OAAO,MAAM,KAAK,KAAK,OAAO,MAAM,GAAG,GAC1C,OAAO;CAGR,MAAM,WAAW,MAAA,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,MAAa,uBAAuB,cACnC,eAAe,MAAM,QAAQ,eAAe,KAAK,SAAS,SAAS,CAAC"}
1
+ {"version":3,"file":"viewLink.js","names":[],"sources":["../../src/widgets/viewLink.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport { formatAdminURL } from 'payload/shared'\nimport type { AnalyticsFilter, DateRange, DimensionKey, MetricKey } from '../core/contract'\nimport { MAX_QUERY_RANGE_DAYS } from '../query/limits'\nimport type { TimeframePreset } from '../timeframe/presets'\nimport { zonedCalendarDay } from '../timeframe/tz'\nimport { BREAKDOWN_TABS, type BreakdownTab, TAB_DIMENSIONS } from '../view/gating'\nimport {\n\tDEFAULT_VIEW_LIMIT,\n\tDEFAULT_VIEW_RANGE,\n\tDEFAULT_VIEW_TAB,\n\tserializeViewState,\n\tVIEW_RANGE_PRESETS,\n\ttype ViewDefaults,\n\ttype ViewState,\n} from '../view/state'\n\n/**\n * The view as a widget sees it: where it mounts and what it opens on, or false when the\n * app turned it off. The defaults travel with the path because a link must leave out\n * exactly what the view would have defaulted to anyway.\n */\nexport type WidgetView =\n\t| { path: string; defaultRange: TimeframePreset; defaultMetric: MetricKey }\n\t| false\n\n/** What `registerWidgets` adds to every built-in widget's server props. */\nexport interface WidgetViewProps {\n\tview?: WidgetView\n}\n\nexport interface ViewHrefArgs {\n\tadminRoute: string\n\tviewPath: string\n\t/** The install's own starting point, so the link omits what the view defaults to. */\n\tdefaultRange: TimeframePreset\n\tdefaultMetric: MetricKey\n\tsource?: string\n\ttimeframe: TimeframePreset | 'custom'\n\t/** The widget's own window, needed only for a custom timeframe. */\n\trange?: DateRange\n\ttimezone: string\n\tcompare?: boolean\n\tmetric?: MetricKey\n\ttab?: BreakdownTab\n\t/**\n\t * The dimension the widget ranks, so the view opens on the same grouping rather than on\n\t * whatever its tab defaults to. Dropped when it is that default, which keeps the link short\n\t * and unchanged for every widget whose dimension already leads its tab.\n\t */\n\tdim?: DimensionKey\n\t/** The widget's own filter, carried as the view's filter state. */\n\tfilters?: AnalyticsFilter[]\n}\n\n/** `allTime` is no range the view can hold, so an install defaulting to it opens here. */\nconst fallbackRange = (defaults: ViewDefaults): TimeframePreset =>\n\tdefaults.range === 'allTime' ? DEFAULT_VIEW_RANGE : defaults.range\n\nconst DAY_MS = 86_400_000\n\n/**\n * The widest custom window the view will accept, as a start day. `parseViewState` drops a\n * wider one and opens on the default range instead, silently, so a widget on a longer\n * window links to the last `MAX_QUERY_RANGE_DAYS` days of it: the most of what the widget\n * shows that the view can show back.\n */\nconst clampStartDay = (from: string, to: string): string => {\n\tconst start = Date.parse(`${from}T00:00:00.000Z`)\n\tconst end = Date.parse(`${to}T00:00:00.000Z`)\n\tif (Number.isNaN(start) || Number.isNaN(end)) {\n\t\treturn from\n\t}\n\t// Both days are read whole, so the cap counts them inclusively.\n\tconst earliest = end - (MAX_QUERY_RANGE_DAYS - 1) * DAY_MS\n\treturn start < earliest ? new Date(earliest).toISOString().slice(0, 10) : from\n}\n\n/**\n * The widget's window as the view's toolbar can hold it. A preset the toolbar does not\n * offer (`allTime`, `thisMonth`, `thisYear`) would select nothing there, so the link drops\n * the range instead and the view opens on its own default.\n */\nconst rangeOf = (\n\targs: ViewHrefArgs,\n\tdefaults: ViewDefaults\n): Pick<ViewState, 'range' | 'from' | 'to'> => {\n\tif (args.timeframe === 'custom') {\n\t\tif (!args.range) {\n\t\t\treturn { range: fallbackRange(defaults) }\n\t\t}\n\t\tconst to = zonedCalendarDay(args.range.end, args.timezone)\n\t\treturn {\n\t\t\trange: 'custom',\n\t\t\tfrom: clampStartDay(zonedCalendarDay(args.range.start, args.timezone), to),\n\t\t\tto,\n\t\t}\n\t}\n\treturn VIEW_RANGE_PRESETS.includes(args.timeframe)\n\t\t? { range: args.timeframe }\n\t\t: { range: fallbackRange(defaults) }\n}\n\n/**\n * A relative admin link opening the analytics view on what the widget shows. Nothing is\n * coerced against the source's capabilities here: the view does that on open, so a link\n * naming something the selected source cannot serve still lands on a working view.\n */\nexport const viewHref = (args: ViewHrefArgs): string => {\n\tconst defaults: ViewDefaults = { range: args.defaultRange, metric: args.defaultMetric }\n\tconst tab = args.tab ?? DEFAULT_VIEW_TAB\n\t// Against the declared order, not the source's: a link is built without capabilities, and a\n\t// `dim` naming what the selected source leads its tab with is dropped by the view anyway.\n\tconst dim = args.dim === TAB_DIMENSIONS[tab][0] ? undefined : args.dim\n\tconst state: ViewState = {\n\t\t...rangeOf(args, defaults),\n\t\tcompare: args.compare === true,\n\t\t...(args.source === undefined ? {} : { source: args.source }),\n\t\tmetric: args.metric ?? defaults.metric,\n\t\ttab,\n\t\t...(dim === undefined ? {} : { dim }),\n\t\tfilters: args.filters ?? [],\n\t\tlimit: DEFAULT_VIEW_LIMIT,\n\t}\n\t// `resolveView` refuses a path without a leading slash, so the option cannot be wider.\n\tconst path = formatAdminURL({\n\t\tadminRoute: args.adminRoute,\n\t\tpath: args.viewPath as `/${string}`,\n\t})\n\tconst query = serializeViewState(state, defaults).toString()\n\treturn query ? `${path}?${query}` : path\n}\n\n/**\n * The same link for a built-in widget, or nothing at all when the view is off. Omitting\n * `timeframe` opens the view on its configured range, for a widget (realtime) whose own\n * rolling window is no range the view can hold.\n */\nexport const widgetViewHref = (\n\tview: WidgetView | undefined,\n\treq: PayloadRequest,\n\targs: Omit<\n\t\tViewHrefArgs,\n\t\t'adminRoute' | 'viewPath' | 'defaultRange' | 'defaultMetric' | 'timeframe'\n\t> & { timeframe?: TimeframePreset | 'custom' }\n): string | undefined =>\n\tview\n\t\t? viewHref({\n\t\t\t\t...args,\n\t\t\t\ttimeframe: args.timeframe ?? view.defaultRange,\n\t\t\t\tadminRoute: req.payload.config.routes.admin,\n\t\t\t\tviewPath: view.path,\n\t\t\t\tdefaultRange: view.defaultRange,\n\t\t\t\tdefaultMetric: view.defaultMetric,\n\t\t\t})\n\t\t: undefined\n\n/** The breakdown tab that offers a dimension; every contract dimension belongs to one. */\nexport const viewTabForDimension = (dimension: DimensionKey): BreakdownTab | undefined =>\n\tBREAKD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