@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
@@ -0,0 +1,24 @@
1
+ import { resolveGoalsFor } from "./runtime.js";
2
+ //#region src/plugin/goalHint.ts
3
+ /** A read whose numbers are goal completions: the `goal` breakdown, or the `conversions` metric. */
4
+ const needsGoalHint = (read) => read.metrics.includes("conversions") || (read.dimensions ?? []).includes("goal");
5
+ /**
6
+ * The scope's goal slugs for a read that asks about goals, and undefined for every other
7
+ * read, which no adapter restricts. An empty list is an install with no goals, which reads
8
+ * as an empty result; a resolver that throws hints `'unresolved'` instead, so the read
9
+ * costs only its goal rows (the provider answers `goalsUnresolved`) and is neither cached
10
+ * as a healthy answer nor mistaken for an install that configured nothing.
11
+ */
12
+ const goalSlugsFor = async (args) => {
13
+ if (!needsGoalHint(args)) return;
14
+ try {
15
+ return (await resolveGoalsFor(args.runtime, args.req, args.scope)).map((goal) => goal.slug);
16
+ } catch (err) {
17
+ args.req.payload.logger?.warn(`analytics: goal slugs failed to resolve: ${String(err)}`);
18
+ return "unresolved";
19
+ }
20
+ };
21
+ //#endregion
22
+ export { goalSlugsFor };
23
+
24
+ //# sourceMappingURL=goalHint.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"goalHint.js","names":[],"sources":["../../src/plugin/goalHint.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport type { DimensionKey, MetricKey } from '../core/contract'\nimport { type AnalyticsRuntime, resolveGoalsFor } from './runtime'\n\n/** What a read asks for, which is all the hint needs to know whether goals are involved. */\nexport interface GoalRead {\n\tmetrics: MetricKey[]\n\tdimensions?: DimensionKey[]\n}\n\nexport interface GoalSlugsArgs extends GoalRead {\n\truntime: AnalyticsRuntime\n\treq: PayloadRequest\n\t/** The read's own scope; goals are resolved per scope. */\n\tscope: string | null | undefined\n}\n\n/** A read whose numbers are goal completions: the `goal` breakdown, or the `conversions` metric. */\nexport const needsGoalHint = (read: GoalRead): boolean =>\n\tread.metrics.includes('conversions') || (read.dimensions ?? []).includes('goal')\n\n/**\n * The scope's goal slugs for a read that asks about goals, and undefined for every other\n * read, which no adapter restricts. An empty list is an install with no goals, which reads\n * as an empty result; a resolver that throws hints `'unresolved'` instead, so the read\n * costs only its goal rows (the provider answers `goalsUnresolved`) and is neither cached\n * as a healthy answer nor mistaken for an install that configured nothing.\n */\nexport const goalSlugsFor = async (\n\targs: GoalSlugsArgs\n): Promise<string[] | 'unresolved' | undefined> => {\n\tif (!needsGoalHint(args)) {\n\t\treturn undefined\n\t}\n\ttry {\n\t\tconst goals = await resolveGoalsFor(args.runtime, args.req, args.scope)\n\t\treturn goals.map((goal) => goal.slug)\n\t} catch (err) {\n\t\targs.req.payload.logger?.warn(`analytics: goal slugs failed to resolve: ${String(err)}`)\n\t\treturn 'unresolved'\n\t}\n}\n"],"mappings":";;;AAkBA,MAAa,iBAAiB,SAC7B,KAAK,QAAQ,SAAS,aAAa,MAAM,KAAK,cAAc,CAAC,GAAG,SAAS,MAAM;;;;;;;;AAShF,MAAa,eAAe,OAC3B,SACkD;CAClD,IAAI,CAAC,cAAc,IAAI,GACtB;CAED,IAAI;EAEH,QAAO,MADa,gBAAgB,KAAK,SAAS,KAAK,KAAK,KAAK,KAAK,GACzD,KAAK,SAAS,KAAK,IAAI;CACrC,SAAS,KAAK;EACb,KAAK,IAAI,QAAQ,QAAQ,KAAK,4CAA4C,OAAO,GAAG,GAAG;EACvF,OAAO;CACR;AACD"}
@@ -3,21 +3,19 @@ import "../core/contract.js";
3
3
  import { getRuntime, platformReadGate, readAccessFor, resolveTimezoneFor } from "./runtime.js";
4
4
  import { serializeCapabilities } from "../core/capabilities.js";
5
5
  import { resolveQueryScope } from "../core/scopedRead.js";
6
- import { previousWindow } from "../widgets/comparison.js";
6
+ import { goalSlugsFor } from "./goalHint.js";
7
+ import { previousWindow, withinLookback } from "../widgets/comparison.js";
8
+ import { NO_STORE, RETRY_AFTER, errorResponse } from "./responses.js";
7
9
  import { queryError } from "../query/errors.js";
8
10
  import { parseQueryParams, readParam } from "../query/parse.js";
9
11
  import { resolveSourcesForRequest } from "./readContextForRequest.js";
10
12
  //#region src/plugin/queryEndpoint.ts
11
- /** Scope depends on the caller's cookies, so no shared cache may ever hold an answer. */
12
- const NO_STORE = { "Cache-Control": "private, no-store" };
13
- const errorResponse = (status, error, headers = {}) => Response.json({ error }, {
14
- status,
15
- headers: {
16
- ...NO_STORE,
17
- ...headers
18
- }
19
- });
20
- const RETRY_AFTER = { "Retry-After": "30" };
13
+ /**
14
+ * The query as the response echoes it: the date range's instants as ISO strings, every
15
+ * other field as the read carried it. `goalSlugs` rides along unchanged, so a client sees
16
+ * the scope's slugs, an empty list for a scope with no goals, or the string `'unresolved'`
17
+ * when the resolver failed.
18
+ */
21
19
  const serializeQuery = (query) => ({
22
20
  ...query,
23
21
  dateRange: {
@@ -70,14 +68,23 @@ const makeQueryHandler = () => async (req) => {
70
68
  timezone: await resolveTimezoneFor(runtime, req, context.scope === "*" ? null : context.scope)
71
69
  });
72
70
  if (!parsed.ok) return errorResponse(400, parsed.error);
71
+ const goalSlugs = await goalSlugsFor({
72
+ runtime,
73
+ req,
74
+ scope: context.scope === "*" ? null : context.scope,
75
+ metrics: parsed.value.query.metrics,
76
+ dimensions: parsed.value.query.dimensions
77
+ });
73
78
  const query = {
74
79
  ...parsed.value.query,
75
- ...queryScope.queryScope === void 0 ? {} : { scope: queryScope.queryScope }
80
+ ...queryScope.queryScope === void 0 ? {} : { scope: queryScope.queryScope },
81
+ ...goalSlugs === void 0 ? {} : { goalSlugs }
76
82
  };
77
83
  let comparisonRange = null;
78
84
  if (parsed.value.compare === "previous") {
79
85
  comparisonRange = previousWindow(query.dateRange, query.timezone);
80
86
  if (!comparisonRange) return errorResponse(400, queryError("invalid_param", "analytics: the range is too long to compare against a previous period", "compare"));
87
+ if (!withinLookback(comparisonRange, adapter.capabilities.maxLookbackDays, { tz: query.timezone })) comparisonRange = null;
81
88
  }
82
89
  let result;
83
90
  let comparison;
@@ -1 +1 @@
1
- {"version":3,"file":"queryEndpoint.js","names":[],"sources":["../../src/plugin/queryEndpoint.ts"],"sourcesContent":["import type { PayloadHandler } from 'payload'\nimport { serializeCapabilities } from '../core/capabilities'\nimport {\n\ttype AnalyticsQuery,\n\ttype AnalyticsResult,\n\ttype DateRange,\n\tPLATFORM_SCOPE,\n} from '../core/contract'\nimport { resolveQueryScope } from '../core/scopedRead'\nimport { type QueryError, queryError } from '../query/errors'\nimport { parseQueryParams, readParam } from '../query/parse'\nimport type { QueryResponse, SerializedAnalyticsQuery } from '../query/response'\nimport { previousWindow } from '../widgets/comparison'\nimport { QUERY_PATH } from './paths'\nimport { resolveSourcesForRequest } from './readContextForRequest'\nimport { getRuntime, platformReadGate, readAccessFor, resolveTimezoneFor } from './runtime'\n\nexport { QUERY_PATH }\n\n/** Scope depends on the caller's cookies, so no shared cache may ever hold an answer. */\nconst NO_STORE = { 'Cache-Control': 'private, no-store' }\n\nconst errorResponse = (\n\tstatus: number,\n\terror: QueryError,\n\theaders: Record<string, string> = {}\n): Response => Response.json({ error }, { status, headers: { ...NO_STORE, ...headers } })\n\n/** How long a client should wait out a provider outage before retrying the same read. */\nconst RETRY_AFTER_SECONDS = '30'\nconst RETRY_AFTER = { 'Retry-After': RETRY_AFTER_SECONDS }\n\nconst serializeQuery = (query: AnalyticsQuery): SerializedAnalyticsQuery => ({\n\t...query,\n\tdateRange: {\n\t\tstart: query.dateRange.start.toISOString(),\n\t\tend: query.dateRange.end.toISOString(),\n\t},\n})\n\n/**\n * Authenticated GET over the surfacing engine: the public read primitive the admin view\n * and consumers' own dashboards are built on. Gating runs in a fixed order so a caller\n * learns nothing from the answer it is not already entitled to: authentication, then\n * `access.read`, then scope and source resolution (shared with the sources endpoint, so a\n * tenant can select no source that endpoint does not list), then capability validation of\n * every parameter against the selected source. Being listed is not sufficient: a shared\n * source that cannot narrow to the caller's scope answers 403 with `param: 'source'`.\n * Errors carry a code and the parameter at fault; adapter configuration and upstream error\n * text never reach the response.\n */\nexport const makeQueryHandler = (): PayloadHandler => async (req) => {\n\tif (!req.user) {\n\t\treturn errorResponse(401, queryError('unauthorized', 'analytics: authentication required'))\n\t}\n\tconst runtime = getRuntime(req.payload)\n\tif (!runtime) {\n\t\t// Both `unavailable` answers are retryable, so both carry the same delay: a client\n\t\t// backs off identically whether the plugin is still booting or a provider is down.\n\t\treturn errorResponse(503, queryError('unavailable', 'analytics: not available'), RETRY_AFTER)\n\t}\n\tlet adapterId = 'unresolved'\n\ttry {\n\t\tif (!(await readAccessFor(runtime, req))) {\n\t\t\treturn errorResponse(403, queryError('forbidden', 'analytics: read access denied'))\n\t\t}\n\t\tconst params = new URL(req.url ?? '', 'http://localhost').searchParams\n\t\tconst platformRead = platformReadGate(runtime, req)\n\t\tconst requestedScope = readParam(params, 'scope')\n\t\tif (requestedScope !== null && !(await platformRead())) {\n\t\t\treturn errorResponse(\n\t\t\t\t400,\n\t\t\t\tqueryError('untrusted_scope', 'analytics: scope is not permitted for this request', 'scope')\n\t\t\t)\n\t\t}\n\t\tconst context = await resolveSourcesForRequest(req, {\n\t\t\tplatformRead,\n\t\t\t...(requestedScope === null ? {} : { scope: requestedScope }),\n\t\t})\n\t\tif (context.adapters.size === 0) {\n\t\t\treturn errorResponse(\n\t\t\t\t404,\n\t\t\t\tqueryError('unknown_source', 'analytics: no source is available for this request')\n\t\t\t)\n\t\t}\n\t\tconst requestedSource = readParam(params, 'source')\n\t\tconst adapter = context.adapters.get(requestedSource ?? context.defaultId ?? '')\n\t\tif (!adapter) {\n\t\t\treturn errorResponse(404, queryError('unknown_source', 'analytics: unknown source', 'source'))\n\t\t}\n\t\tadapterId = adapter.id\n\t\tconst queryScope = await resolveQueryScope({\n\t\t\truntime,\n\t\t\treq,\n\t\t\tscope: context.scope,\n\t\t\tadapter,\n\t\t\tplatformRead,\n\t\t})\n\t\tif (!queryScope.ok) {\n\t\t\treturn errorResponse(\n\t\t\t\t403,\n\t\t\t\tqueryError('forbidden', 'analytics: this source cannot be read for your scope', 'source')\n\t\t\t)\n\t\t}\n\t\tconst capabilities = serializeCapabilities(adapter.capabilities)\n\t\tconst timezone = await resolveTimezoneFor(\n\t\t\truntime,\n\t\t\treq,\n\t\t\tcontext.scope === PLATFORM_SCOPE ? null : context.scope\n\t\t)\n\t\tconst parsed = parseQueryParams(params, { capabilities, timezone })\n\t\tif (!parsed.ok) {\n\t\t\treturn errorResponse(400, parsed.error)\n\t\t}\n\t\tconst query: AnalyticsQuery = {\n\t\t\t...parsed.value.query,\n\t\t\t...(queryScope.queryScope === undefined ? {} : { scope: queryScope.queryScope }),\n\t\t}\n\t\tlet comparisonRange: DateRange | null = null\n\t\tif (parsed.value.compare === 'previous') {\n\t\t\tcomparisonRange = previousWindow(query.dateRange, query.timezone)\n\t\t\tif (!comparisonRange) {\n\t\t\t\treturn errorResponse(\n\t\t\t\t\t400,\n\t\t\t\t\tqueryError(\n\t\t\t\t\t\t'invalid_param',\n\t\t\t\t\t\t'analytics: the range is too long to compare against a previous period',\n\t\t\t\t\t\t'compare'\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t\tlet result: AnalyticsResult\n\t\tlet comparison: AnalyticsResult | undefined\n\t\ttry {\n\t\t\t;[result, comparison] = await Promise.all([\n\t\t\t\truntime.engine.read(adapter, query),\n\t\t\t\tcomparisonRange\n\t\t\t\t\t? runtime.engine.read(adapter, { ...query, dateRange: comparisonRange })\n\t\t\t\t\t: undefined,\n\t\t\t])\n\t\t} catch (err) {\n\t\t\t// Neither a fresh nor a stale entry survived the read: the source is down, not the\n\t\t\t// request wrong, so the client is told to retry rather than to change anything.\n\t\t\treq.payload.logger?.warn(\n\t\t\t\t`analytics: query read failed for adapter \"${adapter.id}\": ${String(err)}`\n\t\t\t)\n\t\t\treturn errorResponse(\n\t\t\t\t503,\n\t\t\t\tqueryError('unavailable', 'analytics: source is temporarily unavailable'),\n\t\t\t\tRETRY_AFTER\n\t\t\t)\n\t\t}\n\t\tconst body: QueryResponse = {\n\t\t\tresult,\n\t\t\t...(comparison ? { comparison } : {}),\n\t\t\tsource: {\n\t\t\t\tid: adapter.id,\n\t\t\t\tlabel: adapter.label,\n\t\t\t\tkind: runtime.configAdapterIds.has(adapter.id) ? 'config' : 'runtime',\n\t\t\t},\n\t\t\tcapabilities,\n\t\t\tquery: serializeQuery(query),\n\t\t}\n\t\treturn Response.json(body, { headers: NO_STORE })\n\t} catch (err) {\n\t\treq.payload.logger?.warn(`analytics: query failed for adapter \"${adapterId}\": ${String(err)}`)\n\t\treturn errorResponse(500, queryError('internal', 'analytics: query failed'))\n\t}\n}\n"],"mappings":";;;;;;;;;;;AAoBA,MAAM,WAAW,EAAE,iBAAiB,oBAAoB;AAExD,MAAM,iBACL,QACA,OACA,UAAkC,CAAC,MACrB,SAAS,KAAK,EAAE,MAAM,GAAG;CAAE;CAAQ,SAAS;EAAE,GAAG;EAAU,GAAG;CAAQ;AAAE,CAAC;AAIxF,MAAM,cAAc,EAAE,eAAe,KAAoB;AAEzD,MAAM,kBAAkB,WAAqD;CAC5E,GAAG;CACH,WAAW;EACV,OAAO,MAAM,UAAU,MAAM,YAAY;EACzC,KAAK,MAAM,UAAU,IAAI,YAAY;CACtC;AACD;;;;;;;;;;;;AAaA,MAAa,yBAAyC,OAAO,QAAQ;CACpE,IAAI,CAAC,IAAI,MACR,OAAO,cAAc,KAAK,WAAW,gBAAgB,oCAAoC,CAAC;CAE3F,MAAM,UAAU,WAAW,IAAI,OAAO;CACtC,IAAI,CAAC,SAGJ,OAAO,cAAc,KAAK,WAAW,eAAe,0BAA0B,GAAG,WAAW;CAE7F,IAAI,YA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AAE,OAAO,WAAW,WAAW;EAC/E;EACA,IAAI,kBAAoC;EACxC,IAAI,OAAO,MAAM,YAAY,YAAY;GACxC,kBAAkB,eAAe,MAAM,WAAW,MAAM,QAAQ;GAChE,IAAI,CAAC,iBACJ,OAAO,cACN,KACA,WACC,iBACA,yEACA,SACD,CACD;EAEF;EACA,IAAI;EACJ,IAAI;EACJ,IAAI;GACF,CAAC,QAAQ,cAAc,MAAM,QAAQ,IAAI,CACzC,QAAQ,OAAO,KAAK,SAAS,KAAK,GAClC,kBACG,QAAQ,OAAO,KAAK,SAAS;IAAE,GAAG;IAAO,WAAW;GAAgB,CAAC,IACrE,KAAA,CACJ,CAAC;EACF,SAAS,KAAK;GAGb,IAAI,QAAQ,QAAQ,KACnB,6CAA6C,QAAQ,GAAG,KAAK,OAAO,GAAG,GACxE;GACA,OAAO,cACN,KACA,WAAW,eAAe,8CAA8C,GACxE,WACD;EACD;EACA,MAAM,OAAsB;GAC3B;GACA,GAAI,aAAa,EAAE,WAAW,IAAI,CAAC;GACnC,QAAQ;IACP,IAAI,QAAQ;IACZ,OAAO,QAAQ;IACf,MAAM,QAAQ,iBAAiB,IAAI,QAAQ,EAAE,IAAI,WAAW;GAC7D;GACA;GACA,OAAO,eAAe,KAAK;EAC5B;EACA,OAAO,SAAS,KAAK,MAAM,EAAE,SAAS,SAAS,CAAC;CACjD,SAAS,KAAK;EACb,IAAI,QAAQ,QAAQ,KAAK,wCAAwC,UAAU,KAAK,OAAO,GAAG,GAAG;EAC7F,OAAO,cAAc,KAAK,WAAW,YAAY,yBAAyB,CAAC;CAC5E;AACD"}
1
+ {"version":3,"file":"queryEndpoint.js","names":[],"sources":["../../src/plugin/queryEndpoint.ts"],"sourcesContent":["import type { PayloadHandler } from 'payload'\nimport { serializeCapabilities } from '../core/capabilities'\nimport {\n\ttype AnalyticsQuery,\n\ttype AnalyticsResult,\n\ttype DateRange,\n\tPLATFORM_SCOPE,\n} from '../core/contract'\nimport { resolveQueryScope } from '../core/scopedRead'\nimport { queryError } from '../query/errors'\nimport { parseQueryParams, readParam } from '../query/parse'\nimport type { QueryResponse, SerializedAnalyticsQuery } from '../query/response'\nimport { previousWindow, withinLookback } from '../widgets/comparison'\nimport { goalSlugsFor } from './goalHint'\nimport { QUERY_PATH } from './paths'\nimport { resolveSourcesForRequest } from './readContextForRequest'\nimport { errorResponse, NO_STORE, RETRY_AFTER } from './responses'\nimport { getRuntime, platformReadGate, readAccessFor, resolveTimezoneFor } from './runtime'\n\nexport { QUERY_PATH }\n\n/**\n * The query as the response echoes it: the date range's instants as ISO strings, every\n * other field as the read carried it. `goalSlugs` rides along unchanged, so a client sees\n * the scope's slugs, an empty list for a scope with no goals, or the string `'unresolved'`\n * when the resolver failed.\n */\nexport const serializeQuery = (query: AnalyticsQuery): SerializedAnalyticsQuery => ({\n\t...query,\n\tdateRange: {\n\t\tstart: query.dateRange.start.toISOString(),\n\t\tend: query.dateRange.end.toISOString(),\n\t},\n})\n\n/**\n * Authenticated GET over the surfacing engine: the public read primitive the admin view\n * and consumers' own dashboards are built on. Gating runs in a fixed order so a caller\n * learns nothing from the answer it is not already entitled to: authentication, then\n * `access.read`, then scope and source resolution (shared with the sources endpoint, so a\n * tenant can select no source that endpoint does not list), then capability validation of\n * every parameter against the selected source. Being listed is not sufficient: a shared\n * source that cannot narrow to the caller's scope answers 403 with `param: 'source'`.\n * Errors carry a code and the parameter at fault; adapter configuration and upstream error\n * text never reach the response.\n */\nexport const makeQueryHandler = (): PayloadHandler => async (req) => {\n\tif (!req.user) {\n\t\treturn errorResponse(401, queryError('unauthorized', 'analytics: authentication required'))\n\t}\n\tconst runtime = getRuntime(req.payload)\n\tif (!runtime) {\n\t\t// Both `unavailable` answers are retryable, so both carry the same delay: a client\n\t\t// backs off identically whether the plugin is still booting or a provider is down.\n\t\treturn errorResponse(503, queryError('unavailable', 'analytics: not available'), RETRY_AFTER)\n\t}\n\tlet adapterId = 'unresolved'\n\ttry {\n\t\tif (!(await readAccessFor(runtime, req))) {\n\t\t\treturn errorResponse(403, queryError('forbidden', 'analytics: read access denied'))\n\t\t}\n\t\tconst params = new URL(req.url ?? '', 'http://localhost').searchParams\n\t\tconst platformRead = platformReadGate(runtime, req)\n\t\tconst requestedScope = readParam(params, 'scope')\n\t\tif (requestedScope !== null && !(await platformRead())) {\n\t\t\treturn errorResponse(\n\t\t\t\t400,\n\t\t\t\tqueryError('untrusted_scope', 'analytics: scope is not permitted for this request', 'scope')\n\t\t\t)\n\t\t}\n\t\tconst context = await resolveSourcesForRequest(req, {\n\t\t\tplatformRead,\n\t\t\t...(requestedScope === null ? {} : { scope: requestedScope }),\n\t\t})\n\t\tif (context.adapters.size === 0) {\n\t\t\treturn errorResponse(\n\t\t\t\t404,\n\t\t\t\tqueryError('unknown_source', 'analytics: no source is available for this request')\n\t\t\t)\n\t\t}\n\t\tconst requestedSource = readParam(params, 'source')\n\t\tconst adapter = context.adapters.get(requestedSource ?? context.defaultId ?? '')\n\t\tif (!adapter) {\n\t\t\treturn errorResponse(404, queryError('unknown_source', 'analytics: unknown source', 'source'))\n\t\t}\n\t\tadapterId = adapter.id\n\t\tconst queryScope = await resolveQueryScope({\n\t\t\truntime,\n\t\t\treq,\n\t\t\tscope: context.scope,\n\t\t\tadapter,\n\t\t\tplatformRead,\n\t\t})\n\t\tif (!queryScope.ok) {\n\t\t\treturn errorResponse(\n\t\t\t\t403,\n\t\t\t\tqueryError('forbidden', 'analytics: this source cannot be read for your scope', 'source')\n\t\t\t)\n\t\t}\n\t\tconst capabilities = serializeCapabilities(adapter.capabilities)\n\t\tconst timezone = await resolveTimezoneFor(\n\t\t\truntime,\n\t\t\treq,\n\t\t\tcontext.scope === PLATFORM_SCOPE ? null : context.scope\n\t\t)\n\t\tconst parsed = parseQueryParams(params, { capabilities, timezone })\n\t\tif (!parsed.ok) {\n\t\t\treturn errorResponse(400, parsed.error)\n\t\t}\n\t\tconst goalSlugs = await goalSlugsFor({\n\t\t\truntime,\n\t\t\treq,\n\t\t\tscope: context.scope === PLATFORM_SCOPE ? null : context.scope,\n\t\t\tmetrics: parsed.value.query.metrics,\n\t\t\tdimensions: parsed.value.query.dimensions,\n\t\t})\n\t\tconst query: AnalyticsQuery = {\n\t\t\t...parsed.value.query,\n\t\t\t...(queryScope.queryScope === undefined ? {} : { scope: queryScope.queryScope }),\n\t\t\t...(goalSlugs === undefined ? {} : { goalSlugs }),\n\t\t}\n\t\tlet comparisonRange: DateRange | null = null\n\t\tif (parsed.value.compare === 'previous') {\n\t\t\tcomparisonRange = previousWindow(query.dateRange, query.timezone)\n\t\t\tif (!comparisonRange) {\n\t\t\t\treturn errorResponse(\n\t\t\t\t\t400,\n\t\t\t\t\tqueryError(\n\t\t\t\t\t\t'invalid_param',\n\t\t\t\t\t\t'analytics: the range is too long to compare against a previous period',\n\t\t\t\t\t\t'compare'\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t}\n\t\t\t// The view decides this same predicate on the browser clock, so a client near the\n\t\t\t// floor or with a skewed clock must lose only its delta, never the whole read.\n\t\t\tif (\n\t\t\t\t!withinLookback(comparisonRange, adapter.capabilities.maxLookbackDays, {\n\t\t\t\t\ttz: query.timezone,\n\t\t\t\t})\n\t\t\t) {\n\t\t\t\tcomparisonRange = null\n\t\t\t}\n\t\t}\n\t\tlet result: AnalyticsResult\n\t\tlet comparison: AnalyticsResult | undefined\n\t\ttry {\n\t\t\t;[result, comparison] = await Promise.all([\n\t\t\t\truntime.engine.read(adapter, query),\n\t\t\t\tcomparisonRange\n\t\t\t\t\t? runtime.engine.read(adapter, { ...query, dateRange: comparisonRange })\n\t\t\t\t\t: undefined,\n\t\t\t])\n\t\t} catch (err) {\n\t\t\t// Neither a fresh nor a stale entry survived the read: the source is down, not the\n\t\t\t// request wrong, so the client is told to retry rather than to change anything.\n\t\t\treq.payload.logger?.warn(\n\t\t\t\t`analytics: query read failed for adapter \"${adapter.id}\": ${String(err)}`\n\t\t\t)\n\t\t\treturn errorResponse(\n\t\t\t\t503,\n\t\t\t\tqueryError('unavailable', 'analytics: source is temporarily unavailable'),\n\t\t\t\tRETRY_AFTER\n\t\t\t)\n\t\t}\n\t\tconst body: QueryResponse = {\n\t\t\tresult,\n\t\t\t...(comparison ? { comparison } : {}),\n\t\t\tsource: {\n\t\t\t\tid: adapter.id,\n\t\t\t\tlabel: adapter.label,\n\t\t\t\tkind: runtime.configAdapterIds.has(adapter.id) ? 'config' : 'runtime',\n\t\t\t},\n\t\t\tcapabilities,\n\t\t\tquery: serializeQuery(query),\n\t\t}\n\t\treturn Response.json(body, { headers: NO_STORE })\n\t} catch (err) {\n\t\treq.payload.logger?.warn(`analytics: query failed for adapter \"${adapterId}\": ${String(err)}`)\n\t\treturn errorResponse(500, queryError('internal', 'analytics: query failed'))\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA2BA,MAAa,kBAAkB,WAAqD;CACnF,GAAG;CACH,WAAW;EACV,OAAO,MAAM,UAAU,MAAM,YAAY;EACzC,KAAK,MAAM,UAAU,IAAI,YAAY;CACtC;AACD;;;;;;;;;;;;AAaA,MAAa,yBAAyC,OAAO,QAAQ;CACpE,IAAI,CAAC,IAAI,MACR,OAAO,cAAc,KAAK,WAAW,gBAAgB,oCAAoC,CAAC;CAE3F,MAAM,UAAU,WAAW,IAAI,OAAO;CACtC,IAAI,CAAC,SAGJ,OAAO,cAAc,KAAK,WAAW,eAAe,0BAA0B,GAAG,WAAW;CAE7F,IAAI,YAAY;CAChB,IAAI;EACH,IAAI,CAAE,MAAM,cAAc,SAAS,GAAG,GACrC,OAAO,cAAc,KAAK,WAAW,aAAa,+BAA+B,CAAC;EAEnF,MAAM,SAAS,IAAI,IAAI,IAAI,OAAO,IAAI,kBAAkB,EAAE;EAC1D,MAAM,eAAe,iBAAiB,SAAS,GAAG;EAClD,MAAM,iBAAiB,UAAU,QAAQ,OAAO;EAChD,IAAI,mBAAmB,QAAQ,CAAE,MAAM,aAAa,GACnD,OAAO,cACN,KACA,WAAW,mBAAmB,sDAAsD,O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;GAChE,IAAI,CAAC,iBACJ,OAAO,cACN,KACA,WACC,iBACA,yEACA,SACD,CACD;GAID,IACC,CAAC,eAAe,iBAAiB,QAAQ,aAAa,iBAAiB,EACtE,IAAI,MAAM,SACX,CAAC,GAED,kBAAkB;EAEpB;EACA,IAAI;EACJ,IAAI;EACJ,IAAI;GACF,CAAC,QAAQ,cAAc,MAAM,QAAQ,IAAI,CACzC,QAAQ,OAAO,KAAK,SAAS,KAAK,GAClC,kBACG,QAAQ,OAAO,KAAK,SAAS;IAAE,GAAG;IAAO,WAAW;GAAgB,CAAC,IACrE,KAAA,CACJ,CAAC;EACF,SAAS,KAAK;GAGb,IAAI,QAAQ,QAAQ,KACnB,6CAA6C,QAAQ,GAAG,KAAK,OAAO,GAAG,GACxE;GACA,OAAO,cACN,KACA,WAAW,eAAe,8CAA8C,GACxE,WACD;EACD;EACA,MAAM,OAAsB;GAC3B;GACA,GAAI,aAAa,EAAE,WAAW,IAAI,CAAC;GACnC,QAAQ;IACP,IAAI,QAAQ;IACZ,OAAO,QAAQ;IACf,MAAM,QAAQ,iBAAiB,IAAI,QAAQ,EAAE,IAAI,WAAW;GAC7D;GACA;GACA,OAAO,eAAe,KAAK;EAC5B;EACA,OAAO,SAAS,KAAK,MAAM,EAAE,SAAS,SAAS,CAAC;CACjD,SAAS,KAAK;EACb,IAAI,QAAQ,QAAQ,KAAK,wCAAwC,UAAU,KAAK,OAAO,GAAG,GAAG;EAC7F,OAAO,cAAc,KAAK,WAAW,YAAY,yBAAyB,CAAC;CAC5E;AACD"}
@@ -1,5 +1,7 @@
1
1
  import "./paths.js";
2
2
  import { getRuntime, readAccessFor } from "./runtime.js";
3
+ import { NO_STORE, RETRY_AFTER, errorResponse } from "./responses.js";
4
+ import { queryError } from "../query/errors.js";
3
5
  import { readForWidgetRealtime } from "../widgets/readForWidgetRealtime.js";
4
6
  //#region src/plugin/realtimeEndpoint.ts
5
7
  const ALLOWED_METRICS = ["visitors", "pageviews"];
@@ -14,24 +16,47 @@ const DEFAULT_WINDOW = 30;
14
16
  * Authenticated GET handler for the realtime widget poller. Reads + clamps the query
15
17
  * params, then delegates to readForWidgetRealtime. Returns 401 for an anonymous request
16
18
  * and 403 when `access.read` denies, which defaults to any authenticated user (not
17
- * admin-panel access specifically); the response is integer counts only.
19
+ * admin-panel access specifically); the response is integer counts only. A source that
20
+ * throws answers a retryable 503 rather than an unhandled 500: the widget polls this every
21
+ * few seconds, and a provider outage is not a reason to burn a stack trace per poll. Only
22
+ * the read is retryable, though, so an `access.read` resolver that throws answers 500: that
23
+ * is a configuration bug, and telling the poller to come back would only repeat it. Every
24
+ * answer is `no-store`, since what it counts depends on the caller's own scope.
18
25
  */
19
26
  const makeRealtimeHandler = () => async (req) => {
20
- if (!req.user) return Response.json({ error: "unauthorized" }, { status: 401 });
21
- const runtime = getRuntime(req.payload);
22
- if (runtime && !await readAccessFor(runtime, req)) return Response.json({ error: "forbidden" }, { status: 403 });
23
- const params = new URL(req.url ?? "", "http://localhost").searchParams;
24
- const rawMetric = params.get("metric");
25
- const metric = ALLOWED_METRICS.includes(rawMetric) ? rawMetric : "visitors";
26
- const rawWindow = Number(params.get("windowMinutes"));
27
- const result = await readForWidgetRealtime({
28
- req,
29
- metric,
30
- windowMinutes: ALLOWED_WINDOWS.includes(rawWindow) ? rawWindow : DEFAULT_WINDOW,
31
- adapterId: params.get("dataSource") ?? void 0,
32
- now: /* @__PURE__ */ new Date()
27
+ if (!req.user) return Response.json({ error: "unauthorized" }, {
28
+ status: 401,
29
+ headers: NO_STORE
33
30
  });
34
- return Response.json(result);
31
+ try {
32
+ const runtime = getRuntime(req.payload);
33
+ if (runtime && !await readAccessFor(runtime, req)) return Response.json({ error: "forbidden" }, {
34
+ status: 403,
35
+ headers: NO_STORE
36
+ });
37
+ const params = new URL(req.url ?? "", "http://localhost").searchParams;
38
+ const rawMetric = params.get("metric");
39
+ const metric = ALLOWED_METRICS.includes(rawMetric) ? rawMetric : "visitors";
40
+ const rawWindow = Number(params.get("windowMinutes"));
41
+ const windowMinutes = ALLOWED_WINDOWS.includes(rawWindow) ? rawWindow : DEFAULT_WINDOW;
42
+ const dataSource = params.get("dataSource") ?? void 0;
43
+ try {
44
+ const result = await readForWidgetRealtime({
45
+ req,
46
+ metric,
47
+ windowMinutes,
48
+ adapterId: dataSource,
49
+ now: /* @__PURE__ */ new Date()
50
+ });
51
+ return Response.json(result, { headers: NO_STORE });
52
+ } catch (err) {
53
+ req.payload.logger?.warn(`analytics: realtime read failed: ${String(err)}`);
54
+ return errorResponse(503, queryError("unavailable", "analytics: source is temporarily unavailable"), RETRY_AFTER);
55
+ }
56
+ } catch (err) {
57
+ req.payload.logger?.warn(`analytics: realtime request failed: ${String(err)}`);
58
+ return errorResponse(500, queryError("internal", "analytics: realtime read failed"));
59
+ }
35
60
  };
36
61
  //#endregion
37
62
  export { makeRealtimeHandler };
@@ -1 +1 @@
1
- {"version":3,"file":"realtimeEndpoint.js","names":[],"sources":["../../src/plugin/realtimeEndpoint.ts"],"sourcesContent":["import type { PayloadHandler } from 'payload'\nimport type { MetricKey } from '../core/contract'\nimport { readForWidgetRealtime } from '../widgets/readForWidgetRealtime'\nimport { REALTIME_PATH } from './paths'\nimport { getRuntime, readAccessFor } from './runtime'\n\nexport { REALTIME_PATH }\n\nconst ALLOWED_METRICS: MetricKey[] = ['visitors', 'pageviews']\nconst ALLOWED_WINDOWS = [5, 15, 30, 60]\nconst DEFAULT_WINDOW = 30\n\n/**\n * Authenticated GET handler for the realtime widget poller. Reads + clamps the query\n * params, then delegates to readForWidgetRealtime. Returns 401 for an anonymous request\n * and 403 when `access.read` denies, which defaults to any authenticated user (not\n * admin-panel access specifically); the response is integer counts only.\n */\nexport const makeRealtimeHandler = (): PayloadHandler => async (req) => {\n\tif (!req.user) {\n\t\treturn Response.json({ error: 'unauthorized' }, { status: 401 })\n\t}\n\tconst runtime = getRuntime(req.payload)\n\t// No runtime means no adapter to read, so the skipped gate protects no data.\n\tif (runtime && !(await readAccessFor(runtime, req))) {\n\t\treturn Response.json({ error: 'forbidden' }, { status: 403 })\n\t}\n\tconst params = new URL(req.url ?? '', 'http://localhost').searchParams\n\tconst rawMetric = params.get('metric')\n\tconst metric: MetricKey = ALLOWED_METRICS.includes(rawMetric as MetricKey)\n\t\t? (rawMetric as MetricKey)\n\t\t: 'visitors'\n\tconst rawWindow = Number(params.get('windowMinutes'))\n\tconst windowMinutes = ALLOWED_WINDOWS.includes(rawWindow) ? rawWindow : DEFAULT_WINDOW\n\tconst dataSource = params.get('dataSource') ?? undefined\n\tconst result = await readForWidgetRealtime({\n\t\treq,\n\t\tmetric,\n\t\twindowMinutes,\n\t\tadapterId: dataSource,\n\t\tnow: new Date(),\n\t})\n\treturn Response.json(result)\n}\n"],"mappings":";;;;AAQA,MAAM,kBAA+B,CAAC,YAAY,WAAW;AAC7D,MAAM,kBAAkB;CAAC;CAAG;CAAI;CAAI;AAAE;AACtC,MAAM,iBAAiB;;;;;;;AAQvB,MAAa,4BAA4C,OAAO,QAAQ;CACvE,IAAI,CAAC,IAAI,MACR,OAAO,SAAS,KAAK,EAAE,OAAO,eAAe,GAAG,EAAE,QAAQ,IAAI,CAAC;CAEhE,MAAM,UAAU,WAAW,IAAI,OAAO;CAEtC,IAAI,WAAW,CAAE,MAAM,cAAc,SAAS,GAAG,GAChD,OAAO,SAAS,KAAK,EAAE,OAAO,YAAY,GAAG,EAAE,QAAQ,IAAI,CAAC;CAE7D,MAAM,SAAS,IAAI,IAAI,IAAI,OAAO,IAAI,kBAAkB,EAAE;CAC1D,MAAM,YAAY,OAAO,IAAI,QAAQ;CACrC,MAAM,SAAoB,gBAAgB,SAAS,SAAsB,IACrE,YACD;CACH,MAAM,YAAY,OAAO,OAAO,IAAI,eAAe,CAAC;CAGpD,MAAM,SAAS,MAAM,sBAAsB;EAC1C;EACA;EACA,eALqB,gBAAgB,SAAS,SAAS,IAAI,YAAY;EAMvE,WALkB,OAAO,IAAI,YAAY,KAAK,KAAA;EAM9C,qBAAK,IAAI,KAAK;CACf,CAAC;CACD,OAAO,SAAS,KAAK,MAAM;AAC5B"}
1
+ {"version":3,"file":"realtimeEndpoint.js","names":[],"sources":["../../src/plugin/realtimeEndpoint.ts"],"sourcesContent":["import type { PayloadHandler } from 'payload'\nimport type { MetricKey } from '../core/contract'\nimport { queryError } from '../query/errors'\nimport { readForWidgetRealtime } from '../widgets/readForWidgetRealtime'\nimport { REALTIME_PATH } from './paths'\nimport { errorResponse, NO_STORE, RETRY_AFTER } from './responses'\nimport { getRuntime, readAccessFor } from './runtime'\n\nexport { REALTIME_PATH }\n\nconst ALLOWED_METRICS: MetricKey[] = ['visitors', 'pageviews']\nconst ALLOWED_WINDOWS = [5, 15, 30, 60]\nconst DEFAULT_WINDOW = 30\n\n/**\n * Authenticated GET handler for the realtime widget poller. Reads + clamps the query\n * params, then delegates to readForWidgetRealtime. Returns 401 for an anonymous request\n * and 403 when `access.read` denies, which defaults to any authenticated user (not\n * admin-panel access specifically); the response is integer counts only. A source that\n * throws answers a retryable 503 rather than an unhandled 500: the widget polls this every\n * few seconds, and a provider outage is not a reason to burn a stack trace per poll. Only\n * the read is retryable, though, so an `access.read` resolver that throws answers 500: that\n * is a configuration bug, and telling the poller to come back would only repeat it. Every\n * answer is `no-store`, since what it counts depends on the caller's own scope.\n */\nexport const makeRealtimeHandler = (): PayloadHandler => async (req) => {\n\tif (!req.user) {\n\t\treturn Response.json({ error: 'unauthorized' }, { status: 401, headers: NO_STORE })\n\t}\n\ttry {\n\t\tconst runtime = getRuntime(req.payload)\n\t\t// No runtime means no adapter to read, so the skipped gate protects no data.\n\t\tif (runtime && !(await readAccessFor(runtime, req))) {\n\t\t\treturn Response.json({ error: 'forbidden' }, { status: 403, headers: NO_STORE })\n\t\t}\n\t\tconst params = new URL(req.url ?? '', 'http://localhost').searchParams\n\t\tconst rawMetric = params.get('metric')\n\t\tconst metric: MetricKey = ALLOWED_METRICS.includes(rawMetric as MetricKey)\n\t\t\t? (rawMetric as MetricKey)\n\t\t\t: 'visitors'\n\t\tconst rawWindow = Number(params.get('windowMinutes'))\n\t\tconst windowMinutes = ALLOWED_WINDOWS.includes(rawWindow) ? rawWindow : DEFAULT_WINDOW\n\t\tconst dataSource = params.get('dataSource') ?? undefined\n\t\ttry {\n\t\t\tconst result = await readForWidgetRealtime({\n\t\t\t\treq,\n\t\t\t\tmetric,\n\t\t\t\twindowMinutes,\n\t\t\t\tadapterId: dataSource,\n\t\t\t\tnow: new Date(),\n\t\t\t})\n\t\t\treturn Response.json(result, { headers: NO_STORE })\n\t\t} catch (err) {\n\t\t\treq.payload.logger?.warn(`analytics: realtime read failed: ${String(err)}`)\n\t\t\treturn errorResponse(\n\t\t\t\t503,\n\t\t\t\tqueryError('unavailable', 'analytics: source is temporarily unavailable'),\n\t\t\t\tRETRY_AFTER\n\t\t\t)\n\t\t}\n\t} catch (err) {\n\t\treq.payload.logger?.warn(`analytics: realtime request failed: ${String(err)}`)\n\t\treturn errorResponse(500, queryError('internal', 'analytics: realtime read failed'))\n\t}\n}\n"],"mappings":";;;;;;AAUA,MAAM,kBAA+B,CAAC,YAAY,WAAW;AAC7D,MAAM,kBAAkB;CAAC;CAAG;CAAI;CAAI;AAAE;AACtC,MAAM,iBAAiB;;;;;;;;;;;;AAavB,MAAa,4BAA4C,OAAO,QAAQ;CACvE,IAAI,CAAC,IAAI,MACR,OAAO,SAAS,KAAK,EAAE,OAAO,eAAe,GAAG;EAAE,QAAQ;EAAK,SAAS;CAAS,CAAC;CAEnF,IAAI;EACH,MAAM,UAAU,WAAW,IAAI,OAAO;EAEtC,IAAI,WAAW,CAAE,MAAM,cAAc,SAAS,GAAG,GAChD,OAAO,SAAS,KAAK,EAAE,OAAO,YAAY,GAAG;GAAE,QAAQ;GAAK,SAAS;EAAS,CAAC;EAEhF,MAAM,SAAS,IAAI,IAAI,IAAI,OAAO,IAAI,kBAAkB,EAAE;EAC1D,MAAM,YAAY,OAAO,IAAI,QAAQ;EACrC,MAAM,SAAoB,gBAAgB,SAAS,SAAsB,IACrE,YACD;EACH,MAAM,YAAY,OAAO,OAAO,IAAI,eAAe,CAAC;EACpD,MAAM,gBAAgB,gBAAgB,SAAS,SAAS,IAAI,YAAY;EACxE,MAAM,aAAa,OAAO,IAAI,YAAY,KAAK,KAAA;EAC/C,IAAI;GACH,MAAM,SAAS,MAAM,sBAAsB;IAC1C;IACA;IACA;IACA,WAAW;IACX,qBAAK,IAAI,KAAK;GACf,CAAC;GACD,OAAO,SAAS,KAAK,QAAQ,EAAE,SAAS,SAAS,CAAC;EACnD,SAAS,KAAK;GACb,IAAI,QAAQ,QAAQ,KAAK,oCAAoC,OAAO,GAAG,GAAG;GAC1E,OAAO,cACN,KACA,WAAW,eAAe,8CAA8C,GACxE,WACD;EACD;CACD,SAAS,KAAK;EACb,IAAI,QAAQ,QAAQ,KAAK,uCAAuC,OAAO,GAAG,GAAG;EAC7E,OAAO,cAAc,KAAK,WAAW,YAAY,iCAAiC,CAAC;CACpF;AACD"}
@@ -0,0 +1,17 @@
1
+ //#region src/plugin/responses.ts
2
+ /** Scope depends on the caller's cookies, so no shared cache may ever hold an answer. */
3
+ const NO_STORE = { "Cache-Control": "private, no-store" };
4
+ /** How long a client should wait out a provider outage before retrying the same read. */
5
+ const RETRY_AFTER = { "Retry-After": "30" };
6
+ /** A read endpoint's error answer: coded body, never cached, headers merged over `NO_STORE`. */
7
+ const errorResponse = (status, error, headers = {}) => Response.json({ error }, {
8
+ status,
9
+ headers: {
10
+ ...NO_STORE,
11
+ ...headers
12
+ }
13
+ });
14
+ //#endregion
15
+ export { NO_STORE, RETRY_AFTER, errorResponse };
16
+
17
+ //# sourceMappingURL=responses.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"responses.js","names":[],"sources":["../../src/plugin/responses.ts"],"sourcesContent":["import type { QueryError } from '../query/errors'\n\n/** Scope depends on the caller's cookies, so no shared cache may ever hold an answer. */\nexport const NO_STORE = { 'Cache-Control': 'private, no-store' }\n\n/** How long a client should wait out a provider outage before retrying the same read. */\nexport const RETRY_AFTER = { 'Retry-After': '30' }\n\n/** A read endpoint's error answer: coded body, never cached, headers merged over `NO_STORE`. */\nexport const errorResponse = (\n\tstatus: number,\n\terror: QueryError,\n\theaders: Record<string, string> = {}\n): Response => Response.json({ error }, { status, headers: { ...NO_STORE, ...headers } })\n"],"mappings":";;AAGA,MAAa,WAAW,EAAE,iBAAiB,oBAAoB;;AAG/D,MAAa,cAAc,EAAE,eAAe,KAAK;;AAGjD,MAAa,iBACZ,QACA,OACA,UAAkC,CAAC,MACrB,SAAS,KAAK,EAAE,MAAM,GAAG;CAAE;CAAQ,SAAS;EAAE,GAAG;EAAU,GAAG;CAAQ;AAAE,CAAC"}
@@ -1,5 +1,6 @@
1
1
  import "./paths.js";
2
2
  import { getRuntime, readAccessFor } from "./runtime.js";
3
+ import { NO_STORE } from "./responses.js";
3
4
  import { resolveSourcesForRequest } from "./readContextForRequest.js";
4
5
  //#region src/plugin/sourcesEndpoint.ts
5
6
  /**
@@ -12,14 +13,20 @@ import { resolveSourcesForRequest } from "./readContextForRequest.js";
12
13
  * {@link resolveSourcesForRequest}, which the query endpoint shares.
13
14
  */
14
15
  const makeSourcesHandler = () => async (req) => {
15
- if (!req.user) return Response.json({ error: "unauthorized" }, { status: 401 });
16
+ if (!req.user) return Response.json({ error: "unauthorized" }, {
17
+ status: 401,
18
+ headers: NO_STORE
19
+ });
16
20
  const runtime = getRuntime(req.payload);
17
- if (runtime && !await readAccessFor(runtime, req)) return Response.json({ error: "forbidden" }, { status: 403 });
21
+ if (runtime && !await readAccessFor(runtime, req)) return Response.json({ error: "forbidden" }, {
22
+ status: 403,
23
+ headers: NO_STORE
24
+ });
18
25
  const { sources, defaultId } = await resolveSourcesForRequest(req);
19
26
  return Response.json({
20
27
  defaultId,
21
28
  sources
22
- });
29
+ }, { headers: NO_STORE });
23
30
  };
24
31
  //#endregion
25
32
  export { makeSourcesHandler };
@@ -1 +1 @@
1
- {"version":3,"file":"sourcesEndpoint.js","names":[],"sources":["../../src/plugin/sourcesEndpoint.ts"],"sourcesContent":["import type { PayloadHandler } from 'payload'\nimport { SOURCES_PATH } from './paths'\nimport { resolveSourcesForRequest } from './readContextForRequest'\nimport { getRuntime, readAccessFor } from './runtime'\n\nexport { SOURCES_PATH }\n\n/**\n * Authenticated GET listing the adapters visible to the requesting scope, with\n * serialized capabilities for client-side pickers. Gated by `access.read` like\n * every other read endpoint. Always answers for the caller's own resolved scope;\n * there is deliberately no scope parameter, so a tenant can never enumerate\n * another tenant's sources. Everything else about the resolution, including how a\n * null scope and a failed resolution fail closed, lives in\n * {@link resolveSourcesForRequest}, which the query endpoint shares.\n */\nexport const makeSourcesHandler = (): PayloadHandler => async (req) => {\n\tif (!req.user) {\n\t\treturn Response.json({ error: 'unauthorized' }, { status: 401 })\n\t}\n\tconst runtime = getRuntime(req.payload)\n\t// No runtime means the plugin served nothing to gate: the listing below is empty anyway.\n\tif (runtime && !(await readAccessFor(runtime, req))) {\n\t\treturn Response.json({ error: 'forbidden' }, { status: 403 })\n\t}\n\tconst { sources, defaultId } = await resolveSourcesForRequest(req)\n\treturn Response.json({ defaultId, sources })\n}\n"],"mappings":";;;;;;;;;;;;;AAgBA,MAAa,2BAA2C,OAAO,QAAQ;CACtE,IAAI,CAAC,IAAI,MACR,OAAO,SAAS,KAAK,EAAE,OAAO,eAAe,GAAG,EAAE,QAAQ,IAAI,CAAC;CAEhE,MAAM,UAAU,WAAW,IAAI,OAAO;CAEtC,IAAI,WAAW,CAAE,MAAM,cAAc,SAAS,GAAG,GAChD,OAAO,SAAS,KAAK,EAAE,OAAO,YAAY,GAAG,EAAE,QAAQ,IAAI,CAAC;CAE7D,MAAM,EAAE,SAAS,cAAc,MAAM,yBAAyB,GAAG;CACjE,OAAO,SAAS,KAAK;EAAE;EAAW;CAAQ,CAAC;AAC5C"}
1
+ {"version":3,"file":"sourcesEndpoint.js","names":[],"sources":["../../src/plugin/sourcesEndpoint.ts"],"sourcesContent":["import type { PayloadHandler } from 'payload'\nimport { SOURCES_PATH } from './paths'\nimport { resolveSourcesForRequest } from './readContextForRequest'\nimport { NO_STORE } from './responses'\nimport { getRuntime, readAccessFor } from './runtime'\n\nexport { SOURCES_PATH }\n\n/**\n * Authenticated GET listing the adapters visible to the requesting scope, with\n * serialized capabilities for client-side pickers. Gated by `access.read` like\n * every other read endpoint. Always answers for the caller's own resolved scope;\n * there is deliberately no scope parameter, so a tenant can never enumerate\n * another tenant's sources. Everything else about the resolution, including how a\n * null scope and a failed resolution fail closed, lives in\n * {@link resolveSourcesForRequest}, which the query endpoint shares.\n */\nexport const makeSourcesHandler = (): PayloadHandler => async (req) => {\n\tif (!req.user) {\n\t\treturn Response.json({ error: 'unauthorized' }, { status: 401, headers: NO_STORE })\n\t}\n\tconst runtime = getRuntime(req.payload)\n\t// No runtime means the plugin served nothing to gate: the listing below is empty anyway.\n\tif (runtime && !(await readAccessFor(runtime, req))) {\n\t\treturn Response.json({ error: 'forbidden' }, { status: 403, headers: NO_STORE })\n\t}\n\tconst { sources, defaultId } = await resolveSourcesForRequest(req)\n\treturn Response.json({ defaultId, sources }, { headers: NO_STORE })\n}\n"],"mappings":";;;;;;;;;;;;;;AAiBA,MAAa,2BAA2C,OAAO,QAAQ;CACtE,IAAI,CAAC,IAAI,MACR,OAAO,SAAS,KAAK,EAAE,OAAO,eAAe,GAAG;EAAE,QAAQ;EAAK,SAAS;CAAS,CAAC;CAEnF,MAAM,UAAU,WAAW,IAAI,OAAO;CAEtC,IAAI,WAAW,CAAE,MAAM,cAAc,SAAS,GAAG,GAChD,OAAO,SAAS,KAAK,EAAE,OAAO,YAAY,GAAG;EAAE,QAAQ;EAAK,SAAS;CAAS,CAAC;CAEhF,MAAM,EAAE,SAAS,cAAc,MAAM,yBAAyB,GAAG;CACjE,OAAO,SAAS,KAAK;EAAE;EAAW;CAAQ,GAAG,EAAE,SAAS,SAAS,CAAC;AACnE"}
@@ -2,6 +2,8 @@ import { providerCreateAccess, providerRowAccess } from "./access.js";
2
2
  import { stampScope } from "./stampScope.js";
3
3
  import { keys } from "../translations/keys.js";
4
4
  import { labelForKey } from "../translations/server.js";
5
+ import { validateCurrency } from "../goals/currency.js";
6
+ import { validateMeasurementId } from "../adapters/ga4/measurementId.js";
5
7
  //#region src/providers/collection.ts
6
8
  const PROVIDERS_SLUG = "analytics-providers";
7
9
  const textField = (name, label, width) => ({
@@ -21,13 +23,14 @@ const secretField = (args, opts) => args.buildSecret({
21
23
  * serves it to the browser. An adapter declares `capture` only when its public field is
22
24
  * filled, so these are what let a provider document fill a capture slot.
23
25
  */
24
- const captureField = (name, label, width) => ({
26
+ const captureField = (name, label, opts = {}) => ({
25
27
  name,
26
28
  type: "text",
27
29
  label: labelForKey(label),
30
+ ...opts.validate ? { validate: opts.validate } : {},
28
31
  admin: {
29
32
  description: labelForKey(keys.providerFieldCaptureHelp),
30
- ...width ? { width } : {}
33
+ ...opts.width ? { width: opts.width } : {}
31
34
  }
32
35
  });
33
36
  /**
@@ -152,7 +155,13 @@ const buildProvidersCollection = (args) => {
152
155
  },
153
156
  {
154
157
  type: "row",
155
- fields: [captureField("domain", keys.providerFieldDomain, "50%"), captureField("scriptId", keys.providerFieldScriptId, "50%")]
158
+ fields: [captureField("domain", keys.providerFieldDomain, { width: "50%" }), captureField("scriptId", keys.providerFieldScriptId, { width: "50%" })]
159
+ },
160
+ {
161
+ name: "revenueCurrency",
162
+ type: "text",
163
+ label: labelForKey(keys.providerFieldRevenueCurrency),
164
+ validate: validateCurrency
156
165
  },
157
166
  hostField()
158
167
  ]),
@@ -177,6 +186,7 @@ const buildProvidersCollection = (args) => {
177
186
  fields: [textField("propertyId", keys.providerFieldPropertyId, "50%"), textField("projectId", keys.providerFieldProjectId, "50%")]
178
187
  },
179
188
  textField("clientEmail", keys.providerFieldClientEmail),
189
+ captureField("measurementId", keys.providerFieldMeasurementId, { validate: validateMeasurementId }),
180
190
  ...args.buildSecret({
181
191
  name: "privateKey",
182
192
  type: "textarea",
@@ -194,7 +204,7 @@ const buildProvidersCollection = (args) => {
194
204
  },
195
205
  {
196
206
  type: "row",
197
- fields: [captureField("projectToken", keys.providerFieldProjectToken, "50%"), {
207
+ fields: [captureField("projectToken", keys.providerFieldProjectToken, { width: "50%" }), {
198
208
  name: "region",
199
209
  type: "select",
200
210
  label: labelForKey(keys.providerFieldRegion),
@@ -1 +1 @@
1
- {"version":3,"file":"collection.js","names":[],"sources":["../../src/providers/collection.ts"],"sourcesContent":["import type { CollectionConfig, Field, TextareaField, TextField } from 'payload'\nimport { keys, type TranslationKey } from '../translations/keys'\nimport { labelForKey } from '../translations/server'\nimport type { ProviderAccessArgs } from './access'\nimport { providerCreateAccess, providerRowAccess } from './access'\nimport type { ProviderId } from './factory'\nimport { stampScope } from './stampScope'\n\nexport const PROVIDERS_SLUG = 'analytics-providers'\n\n/** Builds the sealed variant of a secret source field; injected so the fields peer stays lazy. */\nexport type BuildSecretField = (source: TextField | TextareaField) => Field[]\n\nexport interface BuildProvidersCollectionArgs extends ProviderAccessArgs {\n\tslug: string\n\taccess?: Partial<CollectionConfig['access']>\n\toverrides?: (collection: CollectionConfig) => CollectionConfig\n\t/** Called after any change or delete so the per-scope registry cache drops stale adapters. */\n\tonChange: () => void\n\tbuildSecret: BuildSecretField\n}\n\nconst textField = (name: string, label: TranslationKey, width?: string): Field => ({\n\tname,\n\ttype: 'text',\n\tlabel: labelForKey(label),\n\t...(width ? { admin: { width } } : {}),\n})\n\nconst secretField = (\n\targs: BuildProvidersCollectionArgs,\n\topts: { name: string; label: TranslationKey; width?: string }\n): Field[] =>\n\targs.buildSecret({\n\t\tname: opts.name,\n\t\ttype: 'text',\n\t\tlabel: labelForKey(opts.label),\n\t\t...(opts.width ? { admin: { width: opts.width } } : {}),\n\t})\n\n/**\n * Public capture config: plain text, never a sealed secret, because the tracker config\n * serves it to the browser. An adapter declares `capture` only when its public field is\n * filled, so these are what let a provider document fill a capture slot.\n */\nconst captureField = (name: string, label: TranslationKey, width?: string): Field => ({\n\tname,\n\ttype: 'text',\n\tlabel: labelForKey(label),\n\tadmin: {\n\t\tdescription: labelForKey(keys.providerFieldCaptureHelp),\n\t\t...(width ? { width } : {}),\n\t},\n})\n\n/**\n * The plugin's own scope field, and only when `scopeField` still names it: a host-owned\n * field (a tenant plugin's relationship) is the host's to register, and shadowing it with a\n * hidden text field of another name would store the scope twice.\n */\nconst scopeField = (args: BuildProvidersCollectionArgs): Field[] =>\n\targs.scopeField === 'scope'\n\t\t? [\n\t\t\t\t{\n\t\t\t\t\t// Written by scoped setups; hidden because single-site installs never touch it.\n\t\t\t\t\tname: 'scope',\n\t\t\t\t\ttype: 'text',\n\t\t\t\t\tindex: true,\n\t\t\t\t\tlabel: labelForKey(keys.providerFieldScope),\n\t\t\t\t\tadmin: { hidden: true },\n\t\t\t\t},\n\t\t\t]\n\t\t: []\n\nconst hostField = (): Field => ({\n\tname: 'host',\n\ttype: 'text',\n\tlabel: labelForKey(keys.providerFieldHost),\n\tadmin: { description: labelForKey(keys.providerFieldHostHelp) },\n})\n\nconst providerGroup = (provider: ProviderId, label: TranslationKey, fields: Field[]): Field => ({\n\tname: provider,\n\ttype: 'group',\n\tlabel: labelForKey(label),\n\tadmin: { condition: (data) => data?.provider === provider },\n\tfields,\n})\n\n/**\n * The runtime provider-settings collection: one document per provider (and per scope\n * in scoped installs). Admin-only by default; `access` entries override individual\n * operations and `overrides` reshapes the whole config last, so slugs, labels,\n * fields, and access all stay overridable.\n */\nexport const buildProvidersCollection = (args: BuildProvidersCollectionArgs): CollectionConfig => {\n\tconst collection: CollectionConfig = {\n\t\tslug: args.slug,\n\t\tlabels: {\n\t\t\tsingular: labelForKey(keys.providersCollectionSingular),\n\t\t\tplural: labelForKey(keys.providersCollectionPlural),\n\t\t},\n\t\tdisableDuplicate: true,\n\t\tadmin: {\n\t\t\tuseAsTitle: 'name',\n\t\t\tdefaultColumns: ['name', 'provider', 'enabled'],\n\t\t\tgroup: 'Analytics',\n\t\t},\n\t\taccess: {\n\t\t\tread: providerRowAccess(args),\n\t\t\tcreate: providerCreateAccess(args),\n\t\t\tupdate: providerRowAccess(args),\n\t\t\tdelete: providerRowAccess(args),\n\t\t\t...args.access,\n\t\t},\n\t\thooks: {\n\t\t\tbeforeChange: [stampScope(args)],\n\t\t\tafterChange: [\n\t\t\t\t({ doc }) => {\n\t\t\t\t\targs.onChange()\n\t\t\t\t\treturn doc\n\t\t\t\t},\n\t\t\t],\n\t\t\tafterDelete: [\n\t\t\t\t({ doc }) => {\n\t\t\t\t\targs.onChange()\n\t\t\t\t\treturn doc\n\t\t\t\t},\n\t\t\t],\n\t\t},\n\t\tfields: [\n\t\t\t{\n\t\t\t\tname: 'name',\n\t\t\t\ttype: 'text',\n\t\t\t\trequired: true,\n\t\t\t\tlabel: labelForKey(keys.providerFieldName),\n\t\t\t},\n\t\t\t{\n\t\t\t\ttype: 'row',\n\t\t\t\tfields: [\n\t\t\t\t\t{\n\t\t\t\t\t\tname: 'provider',\n\t\t\t\t\t\ttype: 'select',\n\t\t\t\t\t\trequired: true,\n\t\t\t\t\t\tlabel: labelForKey(keys.providerFieldProvider),\n\t\t\t\t\t\toptions: [\n\t\t\t\t\t\t\t{ label: labelForKey(keys.providerNamePlausible), value: 'plausible' },\n\t\t\t\t\t\t\t{ label: labelForKey(keys.providerNameUmami), value: 'umami' },\n\t\t\t\t\t\t\t{ label: labelForKey(keys.providerNameGa4), value: 'ga4' },\n\t\t\t\t\t\t\t{ label: labelForKey(keys.providerNamePosthog), value: 'posthog' },\n\t\t\t\t\t\t],\n\t\t\t\t\t\tadmin: { width: '50%' },\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tname: 'enabled',\n\t\t\t\t\t\ttype: 'checkbox',\n\t\t\t\t\t\tdefaultValue: true,\n\t\t\t\t\t\tlabel: labelForKey(keys.providerFieldEnabled),\n\t\t\t\t\t\tadmin: { width: '50%', style: { alignSelf: 'flex-end' } },\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t\t...scopeField(args),\n\t\t\tproviderGroup('plausible', keys.providerNamePlausible, [\n\t\t\t\t{\n\t\t\t\t\ttype: 'row',\n\t\t\t\t\tfields: [\n\t\t\t\t\t\ttextField('siteId', keys.providerFieldSiteId, '50%'),\n\t\t\t\t\t\t...secretField(args, { name: 'apiKey', label: keys.providerFieldApiKey, width: '50%' }),\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\ttype: 'row',\n\t\t\t\t\tfields: [\n\t\t\t\t\t\tcaptureField('domain', keys.providerFieldDomain, '50%'),\n\t\t\t\t\t\tcaptureField('scriptId', keys.providerFieldScriptId, '50%'),\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t\thostField(),\n\t\t\t]),\n\t\t\tproviderGroup('umami', keys.providerNameUmami, [\n\t\t\t\t{\n\t\t\t\t\ttype: 'row',\n\t\t\t\t\tfields: [\n\t\t\t\t\t\ttextField('websiteId', keys.providerFieldWebsiteId, '50%'),\n\t\t\t\t\t\t...secretField(args, { name: 'apiKey', label: keys.providerFieldApiKey, width: '50%' }),\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t\t...secretField(args, { name: 'token', label: keys.providerFieldToken }),\n\t\t\t\thostField(),\n\t\t\t]),\n\t\t\tproviderGroup('ga4', keys.providerNameGa4, [\n\t\t\t\t{\n\t\t\t\t\ttype: 'row',\n\t\t\t\t\tfields: [\n\t\t\t\t\t\ttextField('propertyId', keys.providerFieldPropertyId, '50%'),\n\t\t\t\t\t\ttextField('projectId', keys.providerFieldProjectId, '50%'),\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t\ttextField('clientEmail', keys.providerFieldClientEmail),\n\t\t\t\t...args.buildSecret({\n\t\t\t\t\tname: 'privateKey',\n\t\t\t\t\ttype: 'textarea',\n\t\t\t\t\tlabel: labelForKey(keys.providerFieldPrivateKey),\n\t\t\t\t}),\n\t\t\t]),\n\t\t\tproviderGroup('posthog', keys.providerNamePosthog, [\n\t\t\t\t{\n\t\t\t\t\ttype: 'row',\n\t\t\t\t\tfields: [\n\t\t\t\t\t\ttextField('projectId', keys.providerFieldProjectId, '50%'),\n\t\t\t\t\t\t...secretField(args, { name: 'apiKey', label: keys.providerFieldApiKey, width: '50%' }),\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\ttype: 'row',\n\t\t\t\t\tfields: [\n\t\t\t\t\t\tcaptureField('projectToken', keys.providerFieldProjectToken, '50%'),\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tname: 'region',\n\t\t\t\t\t\t\ttype: 'select',\n\t\t\t\t\t\t\tlabel: labelForKey(keys.providerFieldRegion),\n\t\t\t\t\t\t\toptions: [\n\t\t\t\t\t\t\t\t{ label: 'US', value: 'us' },\n\t\t\t\t\t\t\t\t{ label: 'EU', value: 'eu' },\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\tadmin: { width: '50%' },\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t\thostField(),\n\t\t\t]),\n\t\t],\n\t}\n\treturn args.overrides ? args.overrides(collection) : collection\n}\n"],"mappings":";;;;;AAQA,MAAa,iBAAiB;AAc9B,MAAM,aAAa,MAAc,OAAuB,WAA2B;CAClF;CACA,MAAM;CACN,OAAO,YAAY,KAAK;CACxB,GAAI,QAAQ,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC;AACrC;AAEA,MAAM,eACL,MACA,SAEA,KAAK,YAAY;CAChB,MAAM,KAAK;CACX,MAAM;CACN,OAAO,YAAY,KAAK,KAAK;CAC7B,GAAI,KAAK,QAAQ,EAAE,OAAO,EAAE,OAAO,KAAK,MAAM,EAAE,IAAI,CAAC;AACtD,CAAC;;;;;;AAOF,MAAM,gBAAgB,MAAc,OAAuB,WAA2B;CACrF;CACA,MAAM;CACN,OAAO,YAAY,KAAK;CACxB,OAAO;EACN,aAAa,YAAY,KAAK,wBAAwB;EACtD,GAAI,QAAQ,EAAE,MAAM,I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AK,wBAAwB;IACtD,GAAG,KAAK,YAAY;KACnB,MAAM;KACN,MAAM;KACN,OAAO,YAAY,KAAK,uBAAuB;IAChD,CAAC;GACF,CAAC;GACD,cAAc,WAAW,KAAK,qBAAqB;IAClD;KACC,MAAM;KACN,QAAQ,CACP,UAAU,aAAa,KAAK,wBAAwB,KAAK,GACzD,GAAG,YAAY,MAAM;MAAE,MAAM;MAAU,OAAO,KAAK;MAAqB,OAAO;KAAM,CAAC,CACvF;IACD;IACA;KACC,MAAM;KACN,QAAQ,CACP,aAAa,gBAAgB,KAAK,2BAA2B,KAAK,GAClE;MACC,MAAM;MACN,MAAM;MACN,OAAO,YAAY,KAAK,mBAAmB;MAC3C,SAAS,CACR;OAAE,OAAO;OAAM,OAAO;MAAK,GAC3B;OAAE,OAAO;OAAM,OAAO;MAAK,CAC5B;MACA,OAAO,EAAE,OAAO,MAAM;KACvB,CACD;IACD;IACA,UAAU;GACX,CAAC;EACF;CACD;CACA,OAAO,KAAK,YAAY,KAAK,UAAU,UAAU,IAAI;AACtD"}
1
+ {"version":3,"file":"collection.js","names":[],"sources":["../../src/providers/collection.ts"],"sourcesContent":["import type {\n\tCollectionConfig,\n\tField,\n\tTextareaField,\n\tTextField,\n\tTextFieldSingleValidation,\n} from 'payload'\nimport { validateMeasurementId } from '../adapters/ga4/measurementId'\nimport { validateCurrency } from '../goals/currency'\nimport { keys, type TranslationKey } from '../translations/keys'\nimport { labelForKey } from '../translations/server'\nimport type { ProviderAccessArgs } from './access'\nimport { providerCreateAccess, providerRowAccess } from './access'\nimport type { ProviderId } from './factory'\nimport { stampScope } from './stampScope'\n\nexport const PROVIDERS_SLUG = 'analytics-providers'\n\n/** Builds the sealed variant of a secret source field; injected so the fields peer stays lazy. */\nexport type BuildSecretField = (source: TextField | TextareaField) => Field[]\n\nexport interface BuildProvidersCollectionArgs extends ProviderAccessArgs {\n\tslug: string\n\taccess?: Partial<CollectionConfig['access']>\n\toverrides?: (collection: CollectionConfig) => CollectionConfig\n\t/** Called after any change or delete so the per-scope registry cache drops stale adapters. */\n\tonChange: () => void\n\tbuildSecret: BuildSecretField\n}\n\nconst textField = (name: string, label: TranslationKey, width?: string): Field => ({\n\tname,\n\ttype: 'text',\n\tlabel: labelForKey(label),\n\t...(width ? { admin: { width } } : {}),\n})\n\nconst secretField = (\n\targs: BuildProvidersCollectionArgs,\n\topts: { name: string; label: TranslationKey; width?: string }\n): Field[] =>\n\targs.buildSecret({\n\t\tname: opts.name,\n\t\ttype: 'text',\n\t\tlabel: labelForKey(opts.label),\n\t\t...(opts.width ? { admin: { width: opts.width } } : {}),\n\t})\n\n/**\n * Public capture config: plain text, never a sealed secret, because the tracker config\n * serves it to the browser. An adapter declares `capture` only when its public field is\n * filled, so these are what let a provider document fill a capture slot.\n */\nconst captureField = (\n\tname: string,\n\tlabel: TranslationKey,\n\topts: { width?: string; validate?: TextFieldSingleValidation } = {}\n): Field => ({\n\tname,\n\ttype: 'text',\n\tlabel: labelForKey(label),\n\t...(opts.validate ? { validate: opts.validate } : {}),\n\tadmin: {\n\t\tdescription: labelForKey(keys.providerFieldCaptureHelp),\n\t\t...(opts.width ? { width: opts.width } : {}),\n\t},\n})\n\n/**\n * The plugin's own scope field, and only when `scopeField` still names it: a host-owned\n * field (a tenant plugin's relationship) is the host's to register, and shadowing it with a\n * hidden text field of another name would store the scope twice.\n */\nconst scopeField = (args: BuildProvidersCollectionArgs): Field[] =>\n\targs.scopeField === 'scope'\n\t\t? [\n\t\t\t\t{\n\t\t\t\t\t// Written by scoped setups; hidden because single-site installs never touch it.\n\t\t\t\t\tname: 'scope',\n\t\t\t\t\ttype: 'text',\n\t\t\t\t\tindex: true,\n\t\t\t\t\tlabel: labelForKey(keys.providerFieldScope),\n\t\t\t\t\tadmin: { hidden: true },\n\t\t\t\t},\n\t\t\t]\n\t\t: []\n\nconst hostField = (): Field => ({\n\tname: 'host',\n\ttype: 'text',\n\tlabel: labelForKey(keys.providerFieldHost),\n\tadmin: { description: labelForKey(keys.providerFieldHostHelp) },\n})\n\nconst providerGroup = (provider: ProviderId, label: TranslationKey, fields: Field[]): Field => ({\n\tname: provider,\n\ttype: 'group',\n\tlabel: labelForKey(label),\n\tadmin: { condition: (data) => data?.provider === provider },\n\tfields,\n})\n\n/**\n * The runtime provider-settings collection: one document per provider (and per scope\n * in scoped installs). Admin-only by default; `access` entries override individual\n * operations and `overrides` reshapes the whole config last, so slugs, labels,\n * fields, and access all stay overridable.\n */\nexport const buildProvidersCollection = (args: BuildProvidersCollectionArgs): CollectionConfig => {\n\tconst collection: CollectionConfig = {\n\t\tslug: args.slug,\n\t\tlabels: {\n\t\t\tsingular: labelForKey(keys.providersCollectionSingular),\n\t\t\tplural: labelForKey(keys.providersCollectionPlural),\n\t\t},\n\t\tdisableDuplicate: true,\n\t\tadmin: {\n\t\t\tuseAsTitle: 'name',\n\t\t\tdefaultColumns: ['name', 'provider', 'enabled'],\n\t\t\tgroup: 'Analytics',\n\t\t},\n\t\taccess: {\n\t\t\tread: providerRowAccess(args),\n\t\t\tcreate: providerCreateAccess(args),\n\t\t\tupdate: providerRowAccess(args),\n\t\t\tdelete: providerRowAccess(args),\n\t\t\t...args.access,\n\t\t},\n\t\thooks: {\n\t\t\tbeforeChange: [stampScope(args)],\n\t\t\tafterChange: [\n\t\t\t\t({ doc }) => {\n\t\t\t\t\targs.onChange()\n\t\t\t\t\treturn doc\n\t\t\t\t},\n\t\t\t],\n\t\t\tafterDelete: [\n\t\t\t\t({ doc }) => {\n\t\t\t\t\targs.onChange()\n\t\t\t\t\treturn doc\n\t\t\t\t},\n\t\t\t],\n\t\t},\n\t\tfields: [\n\t\t\t{\n\t\t\t\tname: 'name',\n\t\t\t\ttype: 'text',\n\t\t\t\trequired: true,\n\t\t\t\tlabel: labelForKey(keys.providerFieldName),\n\t\t\t},\n\t\t\t{\n\t\t\t\ttype: 'row',\n\t\t\t\tfields: [\n\t\t\t\t\t{\n\t\t\t\t\t\tname: 'provider',\n\t\t\t\t\t\ttype: 'select',\n\t\t\t\t\t\trequired: true,\n\t\t\t\t\t\tlabel: labelForKey(keys.providerFieldProvider),\n\t\t\t\t\t\toptions: [\n\t\t\t\t\t\t\t{ label: labelForKey(keys.providerNamePlausible), value: 'plausible' },\n\t\t\t\t\t\t\t{ label: labelForKey(keys.providerNameUmami), value: 'umami' },\n\t\t\t\t\t\t\t{ label: labelForKey(keys.providerNameGa4), value: 'ga4' },\n\t\t\t\t\t\t\t{ label: labelForKey(keys.providerNamePosthog), value: 'posthog' },\n\t\t\t\t\t\t],\n\t\t\t\t\t\tadmin: { width: '50%' },\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tname: 'enabled',\n\t\t\t\t\t\ttype: 'checkbox',\n\t\t\t\t\t\tdefaultValue: true,\n\t\t\t\t\t\tlabel: labelForKey(keys.providerFieldEnabled),\n\t\t\t\t\t\tadmin: { width: '50%', style: { alignSelf: 'flex-end' } },\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t\t...scopeField(args),\n\t\t\tproviderGroup('plausible', keys.providerNamePlausible, [\n\t\t\t\t{\n\t\t\t\t\ttype: 'row',\n\t\t\t\t\tfields: [\n\t\t\t\t\t\ttextField('siteId', keys.providerFieldSiteId, '50%'),\n\t\t\t\t\t\t...secretField(args, { name: 'apiKey', label: keys.providerFieldApiKey, width: '50%' }),\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\ttype: 'row',\n\t\t\t\t\tfields: [\n\t\t\t\t\t\tcaptureField('domain', keys.providerFieldDomain, { width: '50%' }),\n\t\t\t\t\t\tcaptureField('scriptId', keys.providerFieldScriptId, { width: '50%' }),\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: 'revenueCurrency',\n\t\t\t\t\ttype: 'text',\n\t\t\t\t\tlabel: labelForKey(keys.providerFieldRevenueCurrency),\n\t\t\t\t\tvalidate: validateCurrency,\n\t\t\t\t},\n\t\t\t\thostField(),\n\t\t\t]),\n\t\t\tproviderGroup('umami', keys.providerNameUmami, [\n\t\t\t\t{\n\t\t\t\t\ttype: 'row',\n\t\t\t\t\tfields: [\n\t\t\t\t\t\ttextField('websiteId', keys.providerFieldWebsiteId, '50%'),\n\t\t\t\t\t\t...secretField(args, { name: 'apiKey', label: keys.providerFieldApiKey, width: '50%' }),\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t\t...secretField(args, { name: 'token', label: keys.providerFieldToken }),\n\t\t\t\thostField(),\n\t\t\t]),\n\t\t\tproviderGroup('ga4', keys.providerNameGa4, [\n\t\t\t\t{\n\t\t\t\t\ttype: 'row',\n\t\t\t\t\tfields: [\n\t\t\t\t\t\ttextField('propertyId', keys.providerFieldPropertyId, '50%'),\n\t\t\t\t\t\ttextField('projectId', keys.providerFieldProjectId, '50%'),\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t\ttextField('clientEmail', keys.providerFieldClientEmail),\n\t\t\t\tcaptureField('measurementId', keys.providerFieldMeasurementId, {\n\t\t\t\t\tvalidate: validateMeasurementId,\n\t\t\t\t}),\n\t\t\t\t...args.buildSecret({\n\t\t\t\t\tname: 'privateKey',\n\t\t\t\t\ttype: 'textarea',\n\t\t\t\t\tlabel: labelForKey(keys.providerFieldPrivateKey),\n\t\t\t\t}),\n\t\t\t]),\n\t\t\tproviderGroup('posthog', keys.providerNamePosthog, [\n\t\t\t\t{\n\t\t\t\t\ttype: 'row',\n\t\t\t\t\tfields: [\n\t\t\t\t\t\ttextField('projectId', keys.providerFieldProjectId, '50%'),\n\t\t\t\t\t\t...secretField(args, { name: 'apiKey', label: keys.providerFieldApiKey, width: '50%' }),\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\ttype: 'row',\n\t\t\t\t\tfields: [\n\t\t\t\t\t\tcaptureField('projectToken', keys.providerFieldProjectToken, { width: '50%' }),\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tname: 'region',\n\t\t\t\t\t\t\ttype: 'select',\n\t\t\t\t\t\t\tlabel: labelForKey(keys.providerFieldRegion),\n\t\t\t\t\t\t\toptions: [\n\t\t\t\t\t\t\t\t{ label: 'US', value: 'us' },\n\t\t\t\t\t\t\t\t{ label: 'EU', value: 'eu' },\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\tadmin: { width: '50%' },\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t\thostField(),\n\t\t\t]),\n\t\t],\n\t}\n\treturn args.overrides ? args.overrides(collection) : collection\n}\n"],"mappings":";;;;;;;AAgBA,MAAa,iBAAiB;AAc9B,MAAM,aAAa,MAAc,OAAuB,WAA2B;CAClF;CACA,MAAM;CACN,OAAO,YAAY,KAAK;CACxB,GAAI,QAAQ,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC;AACrC;AAEA,MAAM,eACL,MACA,SAEA,KAAK,YAAY;CAChB,MAAM,KAAK;CACX,MAAM;CACN,OAAO,YAAY,KAAK,KAAK;CAC7B,GAAI,KAAK,QAAQ,EAAE,OAAO,EAAE,OAAO,KAAK,MAAM,EAAE,IAAI,CAAC;AACtD,CAAC;;;;;;AAOF,MAAM,gBACL,MACA,OACA,OAAiE,CAAC,OACtD;CACZ;CACA,MAAM;CACN,OAAO,YAAY,KAAK;CACxB,GAAI,KAAK,WAAW,EAAE,UAAU,KAAK,SAAS,IAAI,CAAC;CACnD,OAAO;EACN,aAAa,YAAY,KAAK,wBAAwB;EACtD,GAAI,KAAK,QAAQ,EAAE,OAAO,KAAK,MAAM,IAAI,CAAC;CAC3C;AACD;;;;;;AAOA,MAAM,cAAc,SACnB,KAAK,eAAe,UACjB,CACA;CAEC,MAAM;CACN,MAAM;CACN,OAAO;CACP,OAAO,YAAY,KAAK,kBAAkB;CAC1C,OAAO,EAAE,QAAQ,KAAK;AACvB,CACD,IACC,CAAC;AAEL,MAAM,mBAA0B;CAC/B,MAAM;CACN,MAAM;CACN,OAAO,YAAY,KAAK,iBAAiB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;GACF,CAAC;GACD,cAAc,WAAW,KAAK,qBAAqB;IAClD;KACC,MAAM;KACN,QAAQ,CACP,UAAU,aAAa,KAAK,wBAAwB,KAAK,GACzD,GAAG,YAAY,MAAM;MAAE,MAAM;MAAU,OAAO,KAAK;MAAqB,OAAO;KAAM,CAAC,CACvF;IACD;IACA;KACC,MAAM;KACN,QAAQ,CACP,aAAa,gBAAgB,KAAK,2BAA2B,EAAE,OAAO,MAAM,CAAC,GAC7E;MACC,MAAM;MACN,MAAM;MACN,OAAO,YAAY,KAAK,mBAAmB;MAC3C,SAAS,CACR;OAAE,OAAO;OAAM,OAAO;MAAK,GAC3B;OAAE,OAAO;OAAM,OAAO;MAAK,CAC5B;MACA,OAAO,EAAE,OAAO,MAAM;KACvB,CACD;IACD;IACA,UAAU;GACX,CAAC;EACF;CACD;CACA,OAAO,KAAK,YAAY,KAAK,UAAU,UAAU,IAAI;AACtD"}
@@ -30,7 +30,8 @@ const buildBaseAdapter = (doc) => {
30
30
  apiKey: cfg.apiKey ?? "",
31
31
  host: orUndefined(cfg.host),
32
32
  domain: orUndefined(cfg.domain),
33
- scriptId: orUndefined(cfg.scriptId)
33
+ scriptId: orUndefined(cfg.scriptId),
34
+ revenueCurrency: orUndefined(cfg.revenueCurrency)
34
35
  });
35
36
  }
36
37
  case "umami": {
@@ -50,7 +51,8 @@ const buildBaseAdapter = (doc) => {
50
51
  client_email: cfg.clientEmail ?? "",
51
52
  private_key: normalizePrivateKey(cfg.privateKey ?? "")
52
53
  },
53
- projectId: orUndefined(cfg.projectId)
54
+ projectId: orUndefined(cfg.projectId),
55
+ measurementId: orUndefined(cfg.measurementId)
54
56
  });
55
57
  }
56
58
  case "posthog": {
@@ -1 +1 @@
1
- {"version":3,"file":"factory.js","names":[],"sources":["../../src/providers/factory.ts"],"sourcesContent":["import { ga4 } from '../adapters/ga4/ga4'\nimport { plausible } from '../adapters/plausible/plausible'\nimport { posthog } from '../adapters/posthog/posthog'\nimport { umami } from '../adapters/umami/umami'\nimport type { AnalyticsAdapter } from '../core/contract'\n\nexport const PROVIDER_IDS = ['plausible', 'umami', 'ga4', 'posthog'] as const\nexport type ProviderId = (typeof PROVIDER_IDS)[number]\n\n/** The provider-settings document shape the adapter factory reads (depth 0, secrets revealed). */\nexport type ProviderDoc = {\n\tid?: number | string\n\tname?: string | null\n\tprovider?: string | null\n\tenabled?: boolean | null\n\tscope?: string | null\n\tplausible?: {\n\t\tsiteId?: string | null\n\t\tapiKey?: string | null\n\t\thost?: string | null\n\t\tdomain?: string | null\n\t\tscriptId?: string | null\n\t} | null\n\tumami?: {\n\t\twebsiteId?: string | null\n\t\tapiKey?: string | null\n\t\ttoken?: string | null\n\t\thost?: string | null\n\t} | null\n\tga4?: {\n\t\tpropertyId?: string | null\n\t\tclientEmail?: string | null\n\t\tprivateKey?: string | null\n\t\tprojectId?: string | null\n\t} | null\n\tposthog?: {\n\t\tprojectId?: string | null\n\t\tapiKey?: string | null\n\t\thost?: string | null\n\t\tprojectToken?: string | null\n\t\tregion?: string | null\n\t} | null\n}\n\nconst orUndefined = (value: string | null | undefined): string | undefined => value || undefined\n\n/** An unset or unrecognized stored region falls back to host-derived detection. */\nconst posthogRegion = (value: string | null | undefined): 'us' | 'eu' | undefined =>\n\tvalue === 'us' || value === 'eu' ? value : undefined\n\n/**\n * Keys pasted from a service-account JSON often carry escaped newlines; the gRPC\n * client needs real ones.\n */\nexport const normalizePrivateKey = (key: string): string => key.replace(/\\\\n/g, '\\n')\n\nconst shortId = (id: number | string): string => String(id).slice(-6)\n\n/** Runtime adapters carry a per-document instance id so two projects of one provider type never collide in a registry; config adapters keep their plain ids. */\nconst withInstanceIdentity = (adapter: AnalyticsAdapter, doc: ProviderDoc): AnalyticsAdapter => {\n\tif (doc.id === undefined || doc.id === null || doc.id === '') {\n\t\treturn adapter\n\t}\n\treturn {\n\t\t...adapter,\n\t\tid: `${doc.provider}:${doc.id}`,\n\t\tlabel: doc.name || `${adapter.label} ${shortId(doc.id)}`,\n\t}\n}\n\nconst buildBaseAdapter = (doc: ProviderDoc): AnalyticsAdapter | null => {\n\tswitch (doc.provider) {\n\t\tcase 'plausible': {\n\t\t\tconst cfg = doc.plausible ?? {}\n\t\t\treturn plausible({\n\t\t\t\tsiteId: cfg.siteId ?? '',\n\t\t\t\tapiKey: cfg.apiKey ?? '',\n\t\t\t\thost: orUndefined(cfg.host),\n\t\t\t\tdomain: orUndefined(cfg.domain),\n\t\t\t\tscriptId: orUndefined(cfg.scriptId),\n\t\t\t})\n\t\t}\n\t\tcase 'umami': {\n\t\t\tconst cfg = doc.umami ?? {}\n\t\t\treturn umami({\n\t\t\t\twebsiteId: cfg.websiteId ?? '',\n\t\t\t\tapiKey: orUndefined(cfg.apiKey),\n\t\t\t\ttoken: orUndefined(cfg.token),\n\t\t\t\thost: orUndefined(cfg.host),\n\t\t\t})\n\t\t}\n\t\tcase 'ga4': {\n\t\t\tconst cfg = doc.ga4 ?? {}\n\t\t\treturn ga4({\n\t\t\t\tpropertyId: cfg.propertyId ?? '',\n\t\t\t\tcredentials: {\n\t\t\t\t\tclient_email: cfg.clientEmail ?? '',\n\t\t\t\t\tprivate_key: normalizePrivateKey(cfg.privateKey ?? ''),\n\t\t\t\t},\n\t\t\t\tprojectId: orUndefined(cfg.projectId),\n\t\t\t})\n\t\t}\n\t\tcase 'posthog': {\n\t\t\tconst cfg = doc.posthog ?? {}\n\t\t\treturn posthog({\n\t\t\t\tprojectId: cfg.projectId ?? '',\n\t\t\t\tapiKey: cfg.apiKey ?? '',\n\t\t\t\thost: orUndefined(cfg.host),\n\t\t\t\tprojectToken: orUndefined(cfg.projectToken),\n\t\t\t\tregion: posthogRegion(cfg.region),\n\t\t\t})\n\t\t}\n\t\tdefault:\n\t\t\treturn null\n\t}\n}\n\n/**\n * Build an adapter instance from a provider-settings document using the same\n * constructors as config-time adapters. Missing credentials are passed through as\n * empty strings so the adapter reports `isConfigured() === false` instead of the\n * factory throwing; an unknown provider value returns null and is skipped.\n */\nexport const adap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KACjC,aAAa,oBAAoB,IAAI,cAAc,EAAE;IACtD;IACA,WAAW,YAAY,IAAI,SAAS;GACrC,CAAC;EACF;EACA,KAAK,WAAW;GACf,MAAM,MAAM,IAAI,WAAW,CAAC;GAC5B,OAAO,QAAQ;IACd,WAAW,IAAI,aAAa;IAC5B,QAAQ,IAAI,UAAU;IACtB,MAAM,YAAY,IAAI,IAAI;IAC1B,cAAc,YAAY,IAAI,YAAY;IAC1C,QAAQ,cAAc,IAAI,MAAM;GACjC,CAAC;EACF;EACA,SACC,OAAO;CACT;AACD;;;;;;;AAQA,MAAa,0BAA0B,QAA8C;CACpF,MAAM,OAAO,iBAAiB,GAAG;CACjC,OAAO,OAAO,qBAAqB,MAAM,GAAG,IAAI;AACjD"}
1
+ {"version":3,"file":"factory.js","names":[],"sources":["../../src/providers/factory.ts"],"sourcesContent":["import { ga4 } from '../adapters/ga4/ga4'\nimport { plausible } from '../adapters/plausible/plausible'\nimport { posthog } from '../adapters/posthog/posthog'\nimport { umami } from '../adapters/umami/umami'\nimport type { AnalyticsAdapter } from '../core/contract'\n\nexport const PROVIDER_IDS = ['plausible', 'umami', 'ga4', 'posthog'] as const\nexport type ProviderId = (typeof PROVIDER_IDS)[number]\n\n/** The provider-settings document shape the adapter factory reads (depth 0, secrets revealed). */\nexport type ProviderDoc = {\n\tid?: number | string\n\tname?: string | null\n\tprovider?: string | null\n\tenabled?: boolean | null\n\tscope?: string | null\n\tplausible?: {\n\t\tsiteId?: string | null\n\t\tapiKey?: string | null\n\t\thost?: string | null\n\t\tdomain?: string | null\n\t\tscriptId?: string | null\n\t\trevenueCurrency?: string | null\n\t} | null\n\tumami?: {\n\t\twebsiteId?: string | null\n\t\tapiKey?: string | null\n\t\ttoken?: string | null\n\t\thost?: string | null\n\t} | null\n\tga4?: {\n\t\tpropertyId?: string | null\n\t\tclientEmail?: string | null\n\t\tprivateKey?: string | null\n\t\tprojectId?: string | null\n\t\tmeasurementId?: string | null\n\t} | null\n\tposthog?: {\n\t\tprojectId?: string | null\n\t\tapiKey?: string | null\n\t\thost?: string | null\n\t\tprojectToken?: string | null\n\t\tregion?: string | null\n\t} | null\n}\n\nconst orUndefined = (value: string | null | undefined): string | undefined => value || undefined\n\n/** An unset or unrecognized stored region falls back to host-derived detection. */\nconst posthogRegion = (value: string | null | undefined): 'us' | 'eu' | undefined =>\n\tvalue === 'us' || value === 'eu' ? value : undefined\n\n/**\n * Keys pasted from a service-account JSON often carry escaped newlines; the gRPC\n * client needs real ones.\n */\nexport const normalizePrivateKey = (key: string): string => key.replace(/\\\\n/g, '\\n')\n\nconst shortId = (id: number | string): string => String(id).slice(-6)\n\n/** Runtime adapters carry a per-document instance id so two projects of one provider type never collide in a registry; config adapters keep their plain ids. */\nconst withInstanceIdentity = (adapter: AnalyticsAdapter, doc: ProviderDoc): AnalyticsAdapter => {\n\tif (doc.id === undefined || doc.id === null || doc.id === '') {\n\t\treturn adapter\n\t}\n\treturn {\n\t\t...adapter,\n\t\tid: `${doc.provider}:${doc.id}`,\n\t\tlabel: doc.name || `${adapter.label} ${shortId(doc.id)}`,\n\t}\n}\n\nconst buildBaseAdapter = (doc: ProviderDoc): AnalyticsAdapter | null => {\n\tswitch (doc.provider) {\n\t\tcase 'plausible': {\n\t\t\tconst cfg = doc.plausible ?? {}\n\t\t\treturn plausible({\n\t\t\t\tsiteId: cfg.siteId ?? '',\n\t\t\t\tapiKey: cfg.apiKey ?? '',\n\t\t\t\thost: orUndefined(cfg.host),\n\t\t\t\tdomain: orUndefined(cfg.domain),\n\t\t\t\tscriptId: orUndefined(cfg.scriptId),\n\t\t\t\trevenueCurrency: orUndefined(cfg.revenueCurrency),\n\t\t\t})\n\t\t}\n\t\tcase 'umami': {\n\t\t\tconst cfg = doc.umami ?? {}\n\t\t\treturn umami({\n\t\t\t\twebsiteId: cfg.websiteId ?? '',\n\t\t\t\tapiKey: orUndefined(cfg.apiKey),\n\t\t\t\ttoken: orUndefined(cfg.token),\n\t\t\t\thost: orUndefined(cfg.host),\n\t\t\t})\n\t\t}\n\t\tcase 'ga4': {\n\t\t\tconst cfg = doc.ga4 ?? {}\n\t\t\treturn ga4({\n\t\t\t\tpropertyId: cfg.propertyId ?? '',\n\t\t\t\tcredentials: {\n\t\t\t\t\tclient_email: cfg.clientEmail ?? '',\n\t\t\t\t\tprivate_key: normalizePrivateKey(cfg.privateKey ?? ''),\n\t\t\t\t},\n\t\t\t\tprojectId: orUndefined(cfg.projectId),\n\t\t\t\tmeasurementId: orUndefined(cfg.measurementId),\n\t\t\t})\n\t\t}\n\t\tcase 'posthog': {\n\t\t\tconst cfg = doc.posthog ?? {}\n\t\t\treturn posthog({\n\t\t\t\tprojectId: cfg.projectId ?? '',\n\t\t\t\tapiKey: cfg.apiKey ?? '',\n\t\t\t\thost: orUndefined(cfg.host),\n\t\t\t\tprojectToken: orUndefined(cfg.projectToken),\n\t\t\t\tregion: posthogRegion(cfg.region),\n\t\t\t})\n\t\t}\n\t\tdefault:\n\t\t\treturn null\n\t}\n}\n\n/**\n * Build an adapter instance from a provider-settings document using the same\n * constructors as config-time adapters. Missing credentials are passed through as\n * empty strings so the adapter reports `isConfigured() === false` instead of the\n * factory throwing; an unknown provider value returns null and is skipped.\n */\nexport const adapterFromProviderDoc = (doc: ProviderDoc): AnalyticsAdapter | null => {\n\tconst base = buildBaseAdapter(doc)\n\treturn base ? withInstanceIdentity(base, doc) : null\n}\n"],"mappings":";;;;;AA8CA,MAAM,eAAe,UAAyD,SAAS,KAAA;;AAGvF,MAAM,iBAAiB,UACtB,UAAU,QAAQ,UAAU,OAAO,QAAQ,KAAA;;;;;AAM5C,MAAa,uBAAuB,QAAwB,IAAI,QAAQ,QAAQ,IAAI;AAEpF,MAAM,WAAW,OAAgC,OAAO,EAAE,EAAE,MAAM,EAAE;;AAGpE,MAAM,wBAAwB,SAA2B,QAAuC;CAC/F,IAAI,IAAI,OAAO,KAAA,KAAa,IAAI,OAAO,QAAQ,IAAI,OAAO,IACzD,OAAO;CAER,OAAO;E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GAAG;CACjC,OAAO,OAAO,qBAAqB,MAAM,GAAG,IAAI;AACjD"}
@@ -20,7 +20,10 @@ type SerializedAnalyticsQuery = Omit<AnalyticsQuery, 'dateRange'> & {
20
20
  /** Successful answer of `GET /analytics/query`. */
21
21
  interface QueryResponse {
22
22
  result: AnalyticsResult;
23
- /** The equal-length window before `query.dateRange`, present only for `compare=previous`. */
23
+ /**
24
+ * The equal-length window before `query.dateRange`, asked for with `compare=previous`.
25
+ * Omitted when the source does not compare or that window is beyond its lookback.
26
+ */
24
27
  comparison?: AnalyticsResult;
25
28
  source: QuerySourceRef;
26
29
  capabilities: SerializedCapabilities;
@@ -0,0 +1,11 @@
1
+ //#region src/query/response.ts
2
+ /**
3
+ * Whether the echoed query asked about goals and the scope configured none. The hint is
4
+ * set only for a goal read, so an empty list is a scope with nothing to convert on: an
5
+ * empty table rather than a source that could not answer, which is `meta.goalsUnresolved`.
6
+ */
7
+ const askedAboutNoGoals = (query) => Array.isArray(query?.goalSlugs) && query.goalSlugs.length === 0;
8
+ //#endregion
9
+ export { askedAboutNoGoals };
10
+
11
+ //# sourceMappingURL=response.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"response.js","names":[],"sources":["../../src/query/response.ts"],"sourcesContent":["import type { SerializedCapabilities } from '../core/capabilities'\nimport type { AnalyticsQuery, AnalyticsResult } from '../core/contract'\nimport type { QueryError } from './errors'\n\n/** Identity of the source a read was served by; its capabilities travel beside it. */\nexport interface QuerySourceRef {\n\tid: string\n\tlabel: string\n\t/** `config` for an adapter every scope shares, `runtime` for one resolved per scope. */\n\tkind: 'config' | 'runtime'\n}\n\n/** An `AnalyticsQuery` as it survives JSON: the date range's instants are ISO strings. */\nexport type SerializedAnalyticsQuery = Omit<AnalyticsQuery, 'dateRange'> & {\n\tdateRange: { start: string; end: string }\n}\n\n/** Successful answer of `GET /analytics/query`. */\nexport interface QueryResponse {\n\tresult: AnalyticsResult\n\t/**\n\t * The equal-length window before `query.dateRange`, asked for with `compare=previous`.\n\t * Omitted when the source does not compare or that window is beyond its lookback.\n\t */\n\tcomparison?: AnalyticsResult\n\tsource: QuerySourceRef\n\tcapabilities: SerializedCapabilities\n\t/** The query after validation and defaulting, so a client renders what it actually got. */\n\tquery: SerializedAnalyticsQuery\n}\n\n/**\n * Whether the echoed query asked about goals and the scope configured none. The hint is\n * set only for a goal read, so an empty list is a scope with nothing to convert on: an\n * empty table rather than a source that could not answer, which is `meta.goalsUnresolved`.\n */\nexport const askedAboutNoGoals = (query?: SerializedAnalyticsQuery): boolean =>\n\tArray.isArray(query?.goalSlugs) && query.goalSlugs.length === 0\n\n/** Every non-2xx answer of `GET /analytics/query`. */\nexport interface QueryErrorResponse {\n\terror: QueryError\n}\n"],"mappings":";;;;;;AAoCA,MAAa,qBAAqB,UACjC,MAAM,QAAQ,OAAO,SAAS,KAAK,MAAM,UAAU,WAAW"}
@@ -91,7 +91,7 @@ function createEngine(opts) {
91
91
  clamped: true
92
92
  }
93
93
  } : fresh;
94
- const ttl = opts.ttl.aggregate ?? adapter.capabilities.recommendedTtl.aggregate;
94
+ const ttl = result.meta.goalsUnresolved === true ? opts.ttl.realtime ?? adapter.capabilities.recommendedTtl.realtime : opts.ttl.aggregate ?? adapter.capabilities.recommendedTtl.aggregate;
95
95
  await opts.store.set(key, result, ttl);
96
96
  return result;
97
97
  });
@@ -1 +1 @@
1
- {"version":3,"file":"engine.js","names":[],"sources":["../../src/surfacing/engine.ts"],"sourcesContent":["import { buildCacheKey } from '../core/cacheKey'\nimport type { AnalyticsAdapter, AnalyticsQuery, AnalyticsResult } from '../core/contract'\nimport { DEFAULT_TIMEZONE, startOfDayInTz } from '../timeframe/tz'\nimport type { CacheStore } from './cacheStore'\nimport { createCoalescer } from './coalesce'\nimport { createQueue, type QueueOptions } from './queue'\nimport { limiterFor, type RateLimiter } from './rateLimiter'\nimport { PROVIDER_READ_TIMEOUT_MESSAGE, shouldRetryProviderError } from './retryPolicy'\n\nconst DAY_MS = 86_400_000\n\nconst clampRange = (\n\trange: AnalyticsQuery['dateRange'],\n\tmaxLookbackDays: number | null,\n\ttz: string = DEFAULT_TIMEZONE\n): { range: AnalyticsQuery['dateRange']; clamped: boolean } => {\n\tif (maxLookbackDays == null) {\n\t\treturn { range, clamped: false }\n\t}\n\tconst floor = new Date(startOfDayInTz(range.end, tz).getTime() - maxLookbackDays * DAY_MS)\n\tif (range.start.getTime() >= floor.getTime()) {\n\t\treturn { range, clamped: false }\n\t}\n\treturn { range: { start: floor, end: range.end }, clamped: true }\n}\n\nexport interface EngineOptions {\n\tstore: CacheStore\n\tqueue: QueueOptions\n\t/** Explicit TTL overrides; when a value is unset the adapter's recommendedTtl applies. */\n\tttl: { aggregate?: number; realtime?: number }\n\t/** Budget for a single adapter read; the in-flight request is aborted past this. */\n\ttimeoutMs: number\n\t/** Called once per failed adapter fetch, before falling back to a stale cache entry. */\n\tonError?: (err: unknown, adapterId: string) => void\n}\n\nexport interface Engine {\n\tread(adapter: AnalyticsAdapter, query: AnalyticsQuery): Promise<AnalyticsResult>\n}\n\nconst emptyResult = (provider: string, q: AnalyticsQuery): AnalyticsResult => ({\n\trows: [],\n\tmeta: { provider, fetchedAt: q.dateRange.end.toISOString() },\n})\n\nexport function createEngine(opts: EngineOptions): Engine {\n\tconst coalesce = createCoalescer<AnalyticsResult>()\n\tconst limiters = new Map<string, RateLimiter>()\n\tconst queue = createQueue({\n\t\t...opts.queue,\n\t\tshouldRetry: shouldRetryProviderError,\n\t\tbaseDelayMs: 500,\n\t})\n\n\treturn {\n\t\tasync read(adapter, query) {\n\t\t\tif (!adapter.isConfigured()) return emptyResult(adapter.id, query)\n\n\t\t\tconst { range, clamped } = clampRange(\n\t\t\t\tquery.dateRange,\n\t\t\t\tadapter.capabilities.maxLookbackDays,\n\t\t\t\tquery.timezone\n\t\t\t)\n\t\t\tconst q = clamped ? { ...query, dateRange: range } : query\n\t\t\tconst key = buildCacheKey(adapter.id, q)\n\t\t\treturn coalesce(key, async () => {\n\t\t\t\tlet fresh: AnalyticsResult\n\t\t\t\tconst controller = new AbortController()\n\t\t\t\tconst timer = setTimeout(\n\t\t\t\t\t() => controller.abort(new Error(PROVIDER_READ_TIMEOUT_MESSAGE)),\n\t\t\t\t\topts.timeoutMs\n\t\t\t\t)\n\t\t\t\ttimer.unref?.()\n\t\t\t\ttry {\n\t\t\t\t\tconst cached = await opts.store.get<AnalyticsResult>(key)\n\t\t\t\t\tif (cached) return cached\n\n\t\t\t\t\t// Races the queued attempt itself, not just its backoff waits, so a signal-blind\n\t\t\t\t\t// adapter (one that never checks ctx.signal) still bounds the read at timeoutMs.\n\t\t\t\t\t// The orphaned attempt keeps its queue slot until the underlying client gives up;\n\t\t\t\t\t// this only bounds how long read() waits for it.\n\t\t\t\t\tconst aborted = new Promise<never>((_resolve, reject) => {\n\t\t\t\t\t\tcontroller.signal.addEventListener('abort', () => reject(controller.signal.reason), {\n\t\t\t\t\t\t\tonce: true,\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\t\t\t\t\tconst attempt = queue.run(async () => {\n\t\t\t\t\t\tconst release = await limiterFor(limiters, adapter).take(controller.signal)\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\treturn await adapter.query(q, { signal: controller.signal })\n\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\trelease()\n\t\t\t\t\t\t}\n\t\t\t\t\t}, controller.signal)\n\t\t\t\t\tattempt.catch(() => {})\n\t\t\t\t\tfresh = await Promise.race([attempt, aborted])\n\t\t\t\t} catch (err) {\n\t\t\t\t\topts.onError?.(err, adapter.id)\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst stale = await opts.store.getStale<AnalyticsResult>(key)\n\t\t\t\t\t\tif (stale) return { ...stale, meta: { ...stale.meta, stale: true } }\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// A broken store fails getStale too; surface the original read error, not this one.\n\t\t\t\t\t}\n\t\t\t\t\tthrow err\n\t\t\t\t} finally {\n\t\t\t\t\tclearTimeout(timer)\n\t\t\t\t}\n\t\t\t\tconst result: AnalyticsResult = clamped\n\t\t\t\t\t? { ...fresh, meta: { ...fresh.meta, clamped: true } }\n\t\t\t\t\t: fresh\n\t\t\t\tconst ttl = opts.ttl.aggregate ?? adapter.capabilities.recommendedTtl.aggregate\n\t\t\t\tawait opts.store.set(key, result, ttl)\n\t\t\t\treturn result\n\t\t\t})\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;AASA,MAAM,SAAS;AAEf,MAAM,cACL,OACA,iBACA,KAAA,UAC8D;CAC9D,IAAI,mBAAmB,MACtB,OAAO;EAAE;EAAO,SAAS;CAAM;CAEhC,MAAM,wBAAQ,IAAI,KAAK,eAAe,MAAM,KAAK,EAAE,EAAE,QAAQ,IAAI,kBAAkB,MAAM;CACzF,IAAI,MAAM,MAAM,QAAQ,KAAK,MAAM,QAAQ,GAC1C,OAAO;EAAE;EAAO,SAAS;CAAM;CAEhC,OAAO;EAAE,OAAO;GAAE,OAAO;GAAO,KAAK,MAAM;EAAI;EAAG,SAAS;CAAK;AACjE;AAiBA,MAAM,eAAe,UAAkB,OAAwC;CAC9E,MAAM,CAAC;CACP,MAAM;EAAE;EAAU,WAAW,EAAE,UAAU,IAAI,YAAY;CAAE;AAC5D;AAEA,SAAgB,aAAa,MAA6B;CACzD,MAAM,WAAW,gBAAiC;CAClD,MAAM,2BAAW,IAAI,IAAyB;CAC9C,MAAM,QAAQ,YAAY;EACzB,GAAG,KAAK;EACR,aAAa;EACb,aAAa;CACd,CAAC;CAED,OAAO,EACN,MAAM,KAAK,SAAS,OAAO;EAC1B,IAAI,CAAC,QAAQ,aAAa,GAAG,OAAO,YAAY,QAAQ,IAAI,KAAK;EAEjE,MAAM,EAAE,OAAO,YAAY,WAC1B,MAAM,WACN,QAAQ,aAAa,iBACrB,MAAM,QACP;EACA,MAAM,IAAI,UAAU;GAAE,GAAG;GAAO,WAAW;EAAM,IAAI;EACrD,MAAM,MAAM,cAAc,QAAQ,IAAI,CAAC;EACvC,OAAO,SAA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file":"engine.js","names":[],"sources":["../../src/surfacing/engine.ts"],"sourcesContent":["import { buildCacheKey } from '../core/cacheKey'\nimport type { AnalyticsAdapter, AnalyticsQuery, AnalyticsResult } from '../core/contract'\nimport { DEFAULT_TIMEZONE, startOfDayInTz } from '../timeframe/tz'\nimport type { CacheStore } from './cacheStore'\nimport { createCoalescer } from './coalesce'\nimport { createQueue, type QueueOptions } from './queue'\nimport { limiterFor, type RateLimiter } from './rateLimiter'\nimport { PROVIDER_READ_TIMEOUT_MESSAGE, shouldRetryProviderError } from './retryPolicy'\n\nconst DAY_MS = 86_400_000\n\nconst clampRange = (\n\trange: AnalyticsQuery['dateRange'],\n\tmaxLookbackDays: number | null,\n\ttz: string = DEFAULT_TIMEZONE\n): { range: AnalyticsQuery['dateRange']; clamped: boolean } => {\n\tif (maxLookbackDays == null) {\n\t\treturn { range, clamped: false }\n\t}\n\tconst floor = new Date(startOfDayInTz(range.end, tz).getTime() - maxLookbackDays * DAY_MS)\n\tif (range.start.getTime() >= floor.getTime()) {\n\t\treturn { range, clamped: false }\n\t}\n\treturn { range: { start: floor, end: range.end }, clamped: true }\n}\n\nexport interface EngineOptions {\n\tstore: CacheStore\n\tqueue: QueueOptions\n\t/** Explicit TTL overrides; when a value is unset the adapter's recommendedTtl applies. */\n\tttl: { aggregate?: number; realtime?: number }\n\t/** Budget for a single adapter read; the in-flight request is aborted past this. */\n\ttimeoutMs: number\n\t/** Called once per failed adapter fetch, before falling back to a stale cache entry. */\n\tonError?: (err: unknown, adapterId: string) => void\n}\n\nexport interface Engine {\n\tread(adapter: AnalyticsAdapter, query: AnalyticsQuery): Promise<AnalyticsResult>\n}\n\nconst emptyResult = (provider: string, q: AnalyticsQuery): AnalyticsResult => ({\n\trows: [],\n\tmeta: { provider, fetchedAt: q.dateRange.end.toISOString() },\n})\n\nexport function createEngine(opts: EngineOptions): Engine {\n\tconst coalesce = createCoalescer<AnalyticsResult>()\n\tconst limiters = new Map<string, RateLimiter>()\n\tconst queue = createQueue({\n\t\t...opts.queue,\n\t\tshouldRetry: shouldRetryProviderError,\n\t\tbaseDelayMs: 500,\n\t})\n\n\treturn {\n\t\tasync read(adapter, query) {\n\t\t\tif (!adapter.isConfigured()) return emptyResult(adapter.id, query)\n\n\t\t\tconst { range, clamped } = clampRange(\n\t\t\t\tquery.dateRange,\n\t\t\t\tadapter.capabilities.maxLookbackDays,\n\t\t\t\tquery.timezone\n\t\t\t)\n\t\t\tconst q = clamped ? { ...query, dateRange: range } : query\n\t\t\tconst key = buildCacheKey(adapter.id, q)\n\t\t\treturn coalesce(key, async () => {\n\t\t\t\tlet fresh: AnalyticsResult\n\t\t\t\tconst controller = new AbortController()\n\t\t\t\tconst timer = setTimeout(\n\t\t\t\t\t() => controller.abort(new Error(PROVIDER_READ_TIMEOUT_MESSAGE)),\n\t\t\t\t\topts.timeoutMs\n\t\t\t\t)\n\t\t\t\ttimer.unref?.()\n\t\t\t\ttry {\n\t\t\t\t\tconst cached = await opts.store.get<AnalyticsResult>(key)\n\t\t\t\t\tif (cached) return cached\n\n\t\t\t\t\t// Races the queued attempt itself, not just its backoff waits, so a signal-blind\n\t\t\t\t\t// adapter (one that never checks ctx.signal) still bounds the read at timeoutMs.\n\t\t\t\t\t// The orphaned attempt keeps its queue slot until the underlying client gives up;\n\t\t\t\t\t// this only bounds how long read() waits for it.\n\t\t\t\t\tconst aborted = new Promise<never>((_resolve, reject) => {\n\t\t\t\t\t\tcontroller.signal.addEventListener('abort', () => reject(controller.signal.reason), {\n\t\t\t\t\t\t\tonce: true,\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\t\t\t\t\tconst attempt = queue.run(async () => {\n\t\t\t\t\t\tconst release = await limiterFor(limiters, adapter).take(controller.signal)\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\treturn await adapter.query(q, { signal: controller.signal })\n\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\trelease()\n\t\t\t\t\t\t}\n\t\t\t\t\t}, controller.signal)\n\t\t\t\t\tattempt.catch(() => {})\n\t\t\t\t\tfresh = await Promise.race([attempt, aborted])\n\t\t\t\t} catch (err) {\n\t\t\t\t\topts.onError?.(err, adapter.id)\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst stale = await opts.store.getStale<AnalyticsResult>(key)\n\t\t\t\t\t\tif (stale) return { ...stale, meta: { ...stale.meta, stale: true } }\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// A broken store fails getStale too; surface the original read error, not this one.\n\t\t\t\t\t}\n\t\t\t\t\tthrow err\n\t\t\t\t} finally {\n\t\t\t\t\tclearTimeout(timer)\n\t\t\t\t}\n\t\t\t\tconst result: AnalyticsResult = clamped\n\t\t\t\t\t? { ...fresh, meta: { ...fresh.meta, clamped: true } }\n\t\t\t\t\t: fresh\n\t\t\t\t// `goalsUnresolved` is always a failure to resolve, whatever hint the read carried:\n\t\t\t\t// a scope with no goals answers empty rows unflagged. At the aggregate TTL one\n\t\t\t\t// transient error would pin \"no conversions\" for an hour. A direct engine caller\n\t\t\t\t// that never hints is flagged on every read and so stays at the short TTL.\n\t\t\t\tconst degraded = result.meta.goalsUnresolved === true\n\t\t\t\tconst ttl = degraded\n\t\t\t\t\t? (opts.ttl.realtime ?? adapter.capabilities.recommendedTtl.realtime)\n\t\t\t\t\t: (opts.ttl.aggregate ?? adapter.capabilities.recommendedTtl.aggregate)\n\t\t\t\tawait opts.store.set(key, result, ttl)\n\t\t\t\treturn result\n\t\t\t})\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;AASA,MAAM,SAAS;AAEf,MAAM,cACL,OACA,iBACA,KAAA,UAC8D;CAC9D,IAAI,mBAAmB,MACtB,OAAO;EAAE;EAAO,SAAS;CAAM;CAEhC,MAAM,wBAAQ,IAAI,KAAK,eAAe,MAAM,KAAK,EAAE,EAAE,QAAQ,IAAI,kBAAkB,MAAM;CACzF,IAAI,MAAM,MAAM,QAAQ,KAAK,MAAM,QAAQ,GAC1C,OAAO;EAAE;EAAO,SAAS;CAAM;CA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CAAC;KAC5D,UAAU;MACT,QAAQ;KACT;IACD,GAAG,WAAW,MAAM;IACpB,QAAQ,YAAY,CAAC,CAAC;IACtB,QAAQ,MAAM,QAAQ,KAAK,CAAC,SAAS,OAAO,CAAC;GAC9C,SAAS,KAAK;IACb,KAAK,UAAU,KAAK,QAAQ,EAAE;IAC9B,IAAI;KACH,MAAM,QAAQ,MAAM,KAAK,MAAM,SAA0B,GAAG;KAC5D,IAAI,OAAO,OAAO;MAAE,GAAG;MAAO,MAAM;OAAE,GAAG,MAAM;OAAM,OAAO;MAAK;KAAE;IACpE,QAAQ,CAER;IACA,MAAM;GACP,UAAU;IACT,aAAa,KAAK;GACnB;GACA,MAAM,SAA0B,UAC7B;IAAE,GAAG;IAAO,MAAM;KAAE,GAAG,MAAM;KAAM,SAAS;IAAK;GAAE,IACnD;GAMH,MAAM,MADW,OAAO,KAAK,oBAAoB,OAE7C,KAAK,IAAI,YAAY,QAAQ,aAAa,eAAe,WACzD,KAAK,IAAI,aAAa,QAAQ,aAAa,eAAe;GAC9D,MAAM,KAAK,MAAM,IAAI,KAAK,QAAQ,GAAG;GACrC,OAAO;EACR,CAAC;CACF,EACD;AACD"}
@@ -4,7 +4,6 @@ const capabilities = {
4
4
  perPageQuery: true,
5
5
  realtime: true,
6
6
  realtimeWindowMinutes: 5,
7
- comparison: true,
8
7
  minGranularity: "minute",
9
8
  maxLookbackDays: null,
10
9
  metrics: new Set([
@@ -1 +1 @@
1
- {"version":3,"file":"memoryAdapter.js","names":[],"sources":["../../src/testing/memoryAdapter.ts"],"sourcesContent":["import { ProviderHttpError } from '../adapters/http/fetchJson'\nimport type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tDimensionKey,\n\tMetricKey,\n} from '../core/contract'\n\ninterface MemoryEvent {\n\tpath: string\n\ttimestamp: Date\n\tvisitor?: string\n}\n\nconst metrics: ReadonlySet<MetricKey> = new Set([\n\t'pageviews',\n\t'visitors',\n\t'visits',\n\t'sessions',\n\t'bounceRate',\n\t'avgDuration',\n])\nconst dimensions: ReadonlySet<DimensionKey> = new Set(['page', 'referrer', 'country', 'device'])\n\nconst capabilities: AnalyticsCapabilities = {\n\tperPageQuery: true,\n\trealtime: true,\n\trealtimeWindowMinutes: 5,\n\tcomparison: true,\n\tminGranularity: 'minute',\n\tmaxLookbackDays: null,\n\tmetrics,\n\tdimensions,\n\tfilters: new Set(['page']),\n\tfilterOperators: new Set(['eq']),\n\tbatchPageReport: true,\n\trateLimit: null,\n\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n}\n\nexport interface MemoryAnalyticsAdapter extends AnalyticsAdapter {\n\trecord(event: MemoryEvent): void\n\treset(): void\n\t/** Test seam for engine resilience: the next query() call rejects with err, then resets. */\n\tfailNext(err?: Error): void\n}\n\nexport function memoryAdapter(): MemoryAnalyticsAdapter {\n\tconst events: MemoryEvent[] = []\n\tlet pendingFailure: Error | undefined\n\n\t// Only page has a backing MemoryEvent field; other declared dimensions drop as unsupported.\n\tconst matchesFilters = (e: MemoryEvent, q: AnalyticsQuery): boolean =>\n\t\t(q.filters ?? []).every((filter) => {\n\t\t\tif (filter.dimension !== 'page' || filter.operator !== 'eq') {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\treturn e.path === filter.value\n\t\t})\n\n\tconst inRange = (e: MemoryEvent, q: AnalyticsQuery): boolean => {\n\t\tif (q.path && e.path !== q.path) return false\n\t\tif (!matchesFilters(e, q)) return false\n\t\treturn e.timestamp >= q.dateRange.start && e.timestamp <= q.dateRange.end\n\t}\n\n\treturn {\n\t\tid: 'memory',\n\t\tlabel: 'In-memory (testing)',\n\t\tcapabilities,\n\t\tisConfigured: () => true,\n\t\trecord: (event) => {\n\t\t\tevents.push(event)\n\t\t},\n\t\treset: () => {\n\t\t\tevents.length = 0\n\t\t},\n\t\tfailNext: (err) => {\n\t\t\tpendingFailure = err ?? new ProviderHttpError(500, 'memory', 'memory: injected failure')\n\t\t},\n\t\tasync query(q: AnalyticsQuery, _ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tif (pendingFailure) {\n\t\t\t\tconst err = pendingFailure\n\t\t\t\tpendingFailure = undefined\n\t\t\t\tthrow err\n\t\t\t}\n\t\t\tconst matched = events.filter((e) => inRange(e, q))\n\t\t\tconst countVisitors = (list: MemoryEvent[]): number =>\n\t\t\t\tnew Set(list.map((e) => e.visitor ?? e.path + e.timestamp.toDateString())).size\n\t\t\tif (q.granularity === 'day') {\n\t\t\t\tconst byDay = new Map<string, MemoryEvent[]>()\n\t\t\t\tfor (const e of matched) {\n\t\t\t\t\tconst day = new Date(\n\t\t\t\t\t\tDate.UTC(\n\t\t\t\t\t\t\te.timestamp.getUTCFullYear(),\n\t\t\t\t\t\t\te.timestamp.getUTCMonth(),\n\t\t\t\t\t\t\te.timestamp.getUTCDate()\n\t\t\t\t\t\t)\n\t\t\t\t\t).toISOString()\n\t\t\t\t\tconst list = byDay.get(day) ?? []\n\t\t\t\t\tlist.push(e)\n\t\t\t\t\tbyDay.set(day, list)\n\t\t\t\t}\n\t\t\t\tconst rows = [...byDay.entries()]\n\t\t\t\t\t.sort(([a], [b]) => a.localeCompare(b))\n\t\t\t\t\t.map(([day, list]) => ({\n\t\t\t\t\t\ttimestamp: day,\n\t\t\t\t\t\tmetrics: { pageviews: list.length, visitors: countVisitors(list) },\n\t\t\t\t\t}))\n\t\t\t\treturn {\n\t\t\t\t\trows,\n\t\t\t\t\ttotals: { pageviews: matched.length, visitors: countVisitors(matched) },\n\t\t\t\t\tmeta: { provider: 'memory', fetchedAt: q.dateRange.end.toISOString() },\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst pageviews = matched.length\n\t\t\tconst visitors = countVisitors(matched)\n\t\t\treturn {\n\t\t\t\trows: [{ metrics: { pageviews, visitors } }],\n\t\t\t\ttotals: { pageviews, visitors },\n\t\t\t\tmeta: { provider: 'memory', fetchedAt: q.dateRange.end.toISOString() },\n\t\t\t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,CAAC,CAAC;GAClD,MAAM,iBAAiB,SACtB,IAAI,IAAI,KAAK,KAAK,MAAM,EAAE,WAAW,EAAE,OAAO,EAAE,UAAU,aAAa,CAAC,CAAC,EAAE;GAC5E,IAAI,EAAE,gBAAgB,OAAO;IAC5B,MAAM,wBAAQ,IAAI,IAA2B;IAC7C,KAAK,MAAM,KAAK,SAAS;KACxB,MAAM,MAAM,IAAI,KACf,KAAK,IACJ,EAAE,UAAU,eAAe,GAC3B,EAAE,UAAU,YAAY,GACxB,EAAE,UAAU,WAAW,CACxB,CACD,EAAE,YAAY;KACd,MAAM,OAAO,MAAM,IAAI,GAAG,KAAK,CAAC;KAChC,KAAK,KAAK,CAAC;KACX,MAAM,IAAI,KAAK,IAAI;IACpB;IAOA,OAAO;KACN,MAPY,CAAC,GAAG,MAAM,QAAQ,CAAC,EAC9B,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,cAAc,CAAC,CAAC,EACrC,KAAK,CAAC,KAAK,WAAW;MACtB,WAAW;MACX,SAAS;OAAE,WAAW,KAAK;OAAQ,UAAU,cAAc,IAAI;MAAE;KAClE,EAEG;KACH,QAAQ;MAAE,WAAW,QAAQ;MAAQ,UAAU,cAAc,OAAO;KAAE;KACtE,MAAM;MAAE,UAAU;MAAU,WAAW,EAAE,UAAU,IAAI,YAAY;KAAE;IACtE;GACD;GACA,MAAM,YAAY,QAAQ;GAC1B,MAAM,WAAW,cAAc,OAAO;GACtC,OAAO;IACN,MAAM,CAAC,EAAE,SAAS;KAAE;KAAW;IAAS,EAAE,CAAC;IAC3C,QAAQ;KAAE;KAAW;IAAS;IAC9B,MAAM;KAAE,UAAU;KAAU,WAAW,EAAE,UAAU,IAAI,YAAY;IAAE;GACtE;EACD;CACD;AACD"}
1
+ {"version":3,"file":"memoryAdapter.js","names":[],"sources":["../../src/testing/memoryAdapter.ts"],"sourcesContent":["import { ProviderHttpError } from '../adapters/http/fetchJson'\nimport type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tDimensionKey,\n\tMetricKey,\n} from '../core/contract'\n\ninterface MemoryEvent {\n\tpath: string\n\ttimestamp: Date\n\tvisitor?: string\n}\n\nconst metrics: ReadonlySet<MetricKey> = new Set([\n\t'pageviews',\n\t'visitors',\n\t'visits',\n\t'sessions',\n\t'bounceRate',\n\t'avgDuration',\n])\nconst dimensions: ReadonlySet<DimensionKey> = new Set(['page', 'referrer', 'country', 'device'])\n\nconst capabilities: AnalyticsCapabilities = {\n\tperPageQuery: true,\n\trealtime: true,\n\trealtimeWindowMinutes: 5,\n\tminGranularity: 'minute',\n\tmaxLookbackDays: null,\n\tmetrics,\n\tdimensions,\n\tfilters: new Set(['page']),\n\tfilterOperators: new Set(['eq']),\n\tbatchPageReport: true,\n\trateLimit: null,\n\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n}\n\nexport interface MemoryAnalyticsAdapter extends AnalyticsAdapter {\n\trecord(event: MemoryEvent): void\n\treset(): void\n\t/** Test seam for engine resilience: the next query() call rejects with err, then resets. */\n\tfailNext(err?: Error): void\n}\n\nexport function memoryAdapter(): MemoryAnalyticsAdapter {\n\tconst events: MemoryEvent[] = []\n\tlet pendingFailure: Error | undefined\n\n\t// Only page has a backing MemoryEvent field; other declared dimensions drop as unsupported.\n\tconst matchesFilters = (e: MemoryEvent, q: AnalyticsQuery): boolean =>\n\t\t(q.filters ?? []).every((filter) => {\n\t\t\tif (filter.dimension !== 'page' || filter.operator !== 'eq') {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\treturn e.path === filter.value\n\t\t})\n\n\tconst inRange = (e: MemoryEvent, q: AnalyticsQuery): boolean => {\n\t\tif (q.path && e.path !== q.path) return false\n\t\tif (!matchesFilters(e, q)) return false\n\t\treturn e.timestamp >= q.dateRange.start && e.timestamp <= q.dateRange.end\n\t}\n\n\treturn {\n\t\tid: 'memory',\n\t\tlabel: 'In-memory (testing)',\n\t\tcapabilities,\n\t\tisConfigured: () => true,\n\t\trecord: (event) => {\n\t\t\tevents.push(event)\n\t\t},\n\t\treset: () => {\n\t\t\tevents.length = 0\n\t\t},\n\t\tfailNext: (err) => {\n\t\t\tpendingFailure = err ?? new ProviderHttpError(500, 'memory', 'memory: injected failure')\n\t\t},\n\t\tasync query(q: AnalyticsQuery, _ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tif (pendingFailure) {\n\t\t\t\tconst err = pendingFailure\n\t\t\t\tpendingFailure = undefined\n\t\t\t\tthrow err\n\t\t\t}\n\t\t\tconst matched = events.filter((e) => inRange(e, q))\n\t\t\tconst countVisitors = (list: MemoryEvent[]): number =>\n\t\t\t\tnew Set(list.map((e) => e.visitor ?? e.path + e.timestamp.toDateString())).size\n\t\t\tif (q.granularity === 'day') {\n\t\t\t\tconst byDay = new Map<string, MemoryEvent[]>()\n\t\t\t\tfor (const e of matched) {\n\t\t\t\t\tconst day = new Date(\n\t\t\t\t\t\tDate.UTC(\n\t\t\t\t\t\t\te.timestamp.getUTCFullYear(),\n\t\t\t\t\t\t\te.timestamp.getUTCMonth(),\n\t\t\t\t\t\t\te.timestamp.getUTCDate()\n\t\t\t\t\t\t)\n\t\t\t\t\t).toISOString()\n\t\t\t\t\tconst list = byDay.get(day) ?? []\n\t\t\t\t\tlist.push(e)\n\t\t\t\t\tbyDay.set(day, list)\n\t\t\t\t}\n\t\t\t\tconst rows = [...byDay.entries()]\n\t\t\t\t\t.sort(([a], [b]) => a.localeCompare(b))\n\t\t\t\t\t.map(([day, list]) => ({\n\t\t\t\t\t\ttimestamp: day,\n\t\t\t\t\t\tmetrics: { pageviews: list.length, visitors: countVisitors(list) },\n\t\t\t\t\t}))\n\t\t\t\treturn {\n\t\t\t\t\trows,\n\t\t\t\t\ttotals: { pageviews: matched.length, visitors: countVisitors(matched) },\n\t\t\t\t\tmeta: { provider: 'memory', fetchedAt: q.dateRange.end.toISOString() },\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst pageviews = matched.length\n\t\t\tconst visitors = countVisitors(matched)\n\t\t\treturn {\n\t\t\t\trows: [{ metrics: { pageviews, visitors } }],\n\t\t\t\ttotals: { pageviews, visitors },\n\t\t\t\tmeta: { provider: 'memory', fetchedAt: q.dateRange.end.toISOString() },\n\t\t\t}\n\t\t},\n\t}\n}\n"],"mappings":";;AA2BA,MAAM,eAAsC;CAC3C,cAAc;CACd,UAAU;CACV,uBAAuB;CACvB,gBAAgB;CAChB,iBAAiB;CACjB,SAAA,IAhB2C,IAAI;EAC/C;EACA;EACA;EACA;EACA;EACA;CACD,CASO;CACN,YAAA,IATiD,IAAI;EAAC;EAAQ;EAAY;EAAW;CAAQ,CASpF;CACT,SAAS,IAAI,IAAI,CAAC,MAAM,CAAC;CACzB,iBAAiB,IAAI,IAAI,CAAC,IAAI,CAAC;CAC/B,iBAAiB;CACjB,WAAW;CACX,gBAAgB;EAAE,UAAU;EAAK,WAAW;CAAK;AAClD;AASA,SAAgB,gBAAwC;CACvD,MAAM,SAAwB,CAAC;CAC/B,IAAI;CAGJ,MAAM,kBAAkB,GAAgB,OACtC,EAAE,WAAW,CAAC,GAAG,OAAO,WAAW;EACnC,IAAI,OAAO,cAAc,UAAU,OAAO,aAAa,MACtD,OAAO;EAER,OAAO,EAAE,SAAS,OAAO;CAC1B,CAAC;CAEF,MAAM,WAAW,GAAgB,MAA+B;EAC/D,IAAI,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,OAAO;EACxC,IAAI,CAAC,eAAe,GAAG,CAAC,GAAG,OAAO;EAClC,OAAO,EAAE,aAAa,EAAE,UAAU,SAAS,EAAE,aAAa,EAAE,UAAU;CACvE;CAEA,OAAO;EACN,IAAI;EACJ,OAAO;EACP;EACA,oBAAoB;EACpB,SAAS,UAAU;GAClB,OAAO,KAAK,KAAK;EAClB;EACA,aAAa;GACZ,OAAO,SAAS;EACjB;EACA,WAAW,QAAQ;GAClB,iBAAiB,OAAO,IAAI,kBAAkB,KAAK,UAAU,0BAA0B;EACxF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