@10x-media/analytics 1.0.0-beta.12 → 1.0.0-beta.14

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 (194) hide show
  1. package/CHANGELOG.md +75 -0
  2. package/dist/adapters/ga4/ga4.d.ts +6 -0
  3. package/dist/adapters/ga4/ga4.js +3 -2
  4. package/dist/adapters/ga4/ga4.js.map +1 -1
  5. package/dist/adapters/plausible/plausible.d.ts +6 -0
  6. package/dist/adapters/plausible/plausible.js +2 -1
  7. package/dist/adapters/plausible/plausible.js.map +1 -1
  8. package/dist/adapters/posthog/posthog.d.ts +6 -0
  9. package/dist/adapters/posthog/posthog.js +21 -8
  10. package/dist/adapters/posthog/posthog.js.map +1 -1
  11. package/dist/adapters/umami/umami.d.ts +6 -0
  12. package/dist/adapters/umami/umami.js +2 -1
  13. package/dist/adapters/umami/umami.js.map +1 -1
  14. package/dist/capture/exclusionEndpoint.js +1 -1
  15. package/dist/capture/exclusionEndpoint.js.map +1 -1
  16. package/dist/capture/slots.js +3 -3
  17. package/dist/capture/slots.js.map +1 -1
  18. package/dist/capture/trackerConfig.js +11 -3
  19. package/dist/capture/trackerConfig.js.map +1 -1
  20. package/dist/charts/series.js +1 -1
  21. package/dist/core/adminOptions.js +6 -1
  22. package/dist/core/adminOptions.js.map +1 -1
  23. package/dist/core/capture.d.ts +3 -1
  24. package/dist/core/contract.d.ts +13 -1
  25. package/dist/core/contract.js.map +1 -1
  26. package/dist/core/options.d.ts +37 -5
  27. package/dist/core/options.js +6 -2
  28. package/dist/core/options.js.map +1 -1
  29. package/dist/core/registry.js.map +1 -1
  30. package/dist/core/scopeOptions.js +2 -0
  31. package/dist/core/scopeOptions.js.map +1 -1
  32. package/dist/core/scopedRead.js +170 -21
  33. package/dist/core/scopedRead.js.map +1 -1
  34. package/dist/core/sourceLabel.d.ts +10 -0
  35. package/dist/core/sourceLabel.js +63 -0
  36. package/dist/core/sourceLabel.js.map +1 -0
  37. package/dist/core/sourceOptions.js +18 -6
  38. package/dist/core/sourceOptions.js.map +1 -1
  39. package/dist/core/sourcePolicy.d.ts +55 -0
  40. package/dist/core/sourcePolicy.js +51 -0
  41. package/dist/core/sourcePolicy.js.map +1 -0
  42. package/dist/exports/adapters/contract.d.ts +2 -1
  43. package/dist/exports/adapters/ga4.d.ts +3 -2
  44. package/dist/exports/adapters/native.d.ts +3 -2
  45. package/dist/exports/adapters/plausible.d.ts +3 -2
  46. package/dist/exports/adapters/posthog.d.ts +3 -2
  47. package/dist/exports/adapters/umami.d.ts +3 -2
  48. package/dist/exports/client.d.ts +7 -5
  49. package/dist/exports/client.js +2 -1
  50. package/dist/exports/next.d.ts +3 -2
  51. package/dist/exports/rsc.d.ts +7 -6
  52. package/dist/exports/testing.d.ts +3 -2
  53. package/dist/exports/types.d.ts +12 -8
  54. package/dist/fields/AnalyticsPanelClient.js.map +1 -1
  55. package/dist/fields/AnalyticsPanelField.d.ts +1 -1
  56. package/dist/fields/AnalyticsPanelField.js +3 -1
  57. package/dist/fields/AnalyticsPanelField.js.map +1 -1
  58. package/dist/fields/AnalyticsStatField.d.ts +1 -1
  59. package/dist/fields/AnalyticsStatField.js +1 -1
  60. package/dist/fields/PanelContent.js +6 -1
  61. package/dist/fields/PanelContent.js.map +1 -1
  62. package/dist/fields/config/fetchSources.d.ts +3 -0
  63. package/dist/fields/config/fetchSources.js +5 -3
  64. package/dist/fields/config/fetchSources.js.map +1 -1
  65. package/dist/fields/readForDocument.d.ts +5 -4
  66. package/dist/fields/readForDocument.js +6 -2
  67. package/dist/fields/readForDocument.js.map +1 -1
  68. package/dist/goals/collection.js +4 -31
  69. package/dist/goals/collection.js.map +1 -1
  70. package/dist/goals/resolver.js +2 -2
  71. package/dist/goals/trackGoalAction.js +1 -1
  72. package/dist/index.d.ts +14 -11
  73. package/dist/index.js +6 -5
  74. package/dist/index.js.map +1 -1
  75. package/dist/native/geo/maxmindResolver.js +1 -1
  76. package/dist/native/ingest/normalizeEvent.js +1 -1
  77. package/dist/native/nativeAdapter.d.ts +6 -0
  78. package/dist/native/nativeAdapter.js +3 -2
  79. package/dist/native/nativeAdapter.js.map +1 -1
  80. package/dist/plugin/createRuntime.js +6 -3
  81. package/dist/plugin/createRuntime.js.map +1 -1
  82. package/dist/plugin/documentEndpoint.js +1 -0
  83. package/dist/plugin/documentEndpoint.js.map +1 -1
  84. package/dist/plugin/pluginCollections.js +11 -5
  85. package/dist/plugin/pluginCollections.js.map +1 -1
  86. package/dist/plugin/queryEndpoint.js +1 -1
  87. package/dist/plugin/queryEndpoint.js.map +1 -1
  88. package/dist/plugin/readContextForRequest.d.ts +11 -0
  89. package/dist/plugin/readContextForRequest.js +25 -15
  90. package/dist/plugin/readContextForRequest.js.map +1 -1
  91. package/dist/plugin/runtime.js +13 -5
  92. package/dist/plugin/runtime.js.map +1 -1
  93. package/dist/plugin/sourcesEndpoint.js +8 -9
  94. package/dist/plugin/sourcesEndpoint.js.map +1 -1
  95. package/dist/providers/ProvidersListNotice.d.ts +11 -0
  96. package/dist/providers/ProvidersListNotice.js +36 -0
  97. package/dist/providers/ProvidersListNotice.js.map +1 -0
  98. package/dist/providers/collection.d.ts +9 -1
  99. package/dist/providers/collection.js +111 -42
  100. package/dist/providers/collection.js.map +1 -1
  101. package/dist/providers/factory.d.ts +1 -1
  102. package/dist/providers/factory.js +8 -11
  103. package/dist/providers/factory.js.map +1 -1
  104. package/dist/providers/probe.js +5 -1
  105. package/dist/providers/probe.js.map +1 -1
  106. package/dist/providers/registry.js +49 -39
  107. package/dist/providers/registry.js.map +1 -1
  108. package/dist/providers/resolver.js +6 -3
  109. package/dist/providers/resolver.js.map +1 -1
  110. package/dist/providers/scopeUnique.js +41 -0
  111. package/dist/providers/scopeUnique.js.map +1 -0
  112. package/dist/query/fetchQuery.d.ts +1 -1
  113. package/dist/surfacing/rebucket.js +1 -1
  114. package/dist/tracker/config.d.ts +5 -0
  115. package/dist/tracker/config.js.map +1 -1
  116. package/dist/tracker/sinks/createSink.js +4 -1
  117. package/dist/tracker/sinks/createSink.js.map +1 -1
  118. package/dist/tracker/sinks/ga4.js +2 -2
  119. package/dist/tracker/sinks/posthog.js +30 -2
  120. package/dist/tracker/sinks/posthog.js.map +1 -1
  121. package/dist/tracker/sinks/vendor.js +2 -2
  122. package/dist/tracker/sinks/vendor.js.map +1 -1
  123. package/dist/translations/ar.js +6 -0
  124. package/dist/translations/ar.js.map +1 -1
  125. package/dist/translations/de.js +6 -0
  126. package/dist/translations/de.js.map +1 -1
  127. package/dist/translations/en.js +6 -0
  128. package/dist/translations/en.js.map +1 -1
  129. package/dist/translations/es.js +6 -0
  130. package/dist/translations/es.js.map +1 -1
  131. package/dist/translations/fr.js +6 -0
  132. package/dist/translations/fr.js.map +1 -1
  133. package/dist/translations/id.js +6 -0
  134. package/dist/translations/id.js.map +1 -1
  135. package/dist/translations/keys.d.ts +6 -0
  136. package/dist/translations/keys.js +7 -1
  137. package/dist/translations/keys.js.map +1 -1
  138. package/dist/translations/ko.js +6 -0
  139. package/dist/translations/ko.js.map +1 -1
  140. package/dist/translations/pt.js +6 -0
  141. package/dist/translations/pt.js.map +1 -1
  142. package/dist/translations/ru.js +6 -0
  143. package/dist/translations/ru.js.map +1 -1
  144. package/dist/translations/uk.js +6 -0
  145. package/dist/translations/uk.js.map +1 -1
  146. package/dist/translations/zh.js +6 -0
  147. package/dist/translations/zh.js.map +1 -1
  148. package/dist/ui/analytics.css +5 -0
  149. package/dist/ui/components/SourcesNoticeBanner.js +20 -0
  150. package/dist/ui/components/SourcesNoticeBanner.js.map +1 -0
  151. package/dist/view/ViewRoot.js +2 -0
  152. package/dist/view/ViewRoot.js.map +1 -1
  153. package/dist/view/registerView.js +5 -4
  154. package/dist/view/registerView.js.map +1 -1
  155. package/dist/view/viewContext.d.ts +1 -1
  156. package/dist/view/viewProps.d.ts +1 -1
  157. package/dist/view/viewProps.js +3 -2
  158. package/dist/view/viewProps.js.map +1 -1
  159. package/dist/widgets/AnalyticsBreakdownWidget.js +1 -0
  160. package/dist/widgets/AnalyticsBreakdownWidget.js.map +1 -1
  161. package/dist/widgets/AnalyticsGoalsWidget.js +1 -0
  162. package/dist/widgets/AnalyticsGoalsWidget.js.map +1 -1
  163. package/dist/widgets/AnalyticsMetricWidget.js +1 -0
  164. package/dist/widgets/AnalyticsMetricWidget.js.map +1 -1
  165. package/dist/widgets/AnalyticsRealtimeWidget.js +15 -7
  166. package/dist/widgets/AnalyticsRealtimeWidget.js.map +1 -1
  167. package/dist/widgets/AnalyticsTrendWidget.js +1 -0
  168. package/dist/widgets/AnalyticsTrendWidget.js.map +1 -1
  169. package/dist/widgets/defaultLayout.d.ts +26 -0
  170. package/dist/widgets/defaultLayout.js +51 -0
  171. package/dist/widgets/defaultLayout.js.map +1 -0
  172. package/dist/widgets/notices.js +1 -0
  173. package/dist/widgets/notices.js.map +1 -1
  174. package/dist/widgets/prepareWidgetRead.d.ts +14 -1
  175. package/dist/widgets/prepareWidgetRead.js +6 -2
  176. package/dist/widgets/prepareWidgetRead.js.map +1 -1
  177. package/dist/widgets/readForWidget.d.ts +4 -4
  178. package/dist/widgets/readForWidget.js +3 -1
  179. package/dist/widgets/readForWidget.js.map +1 -1
  180. package/dist/widgets/readForWidgetBreakdown.d.ts +4 -4
  181. package/dist/widgets/readForWidgetBreakdown.js +3 -1
  182. package/dist/widgets/readForWidgetBreakdown.js.map +1 -1
  183. package/dist/widgets/readForWidgetGoals.d.ts +4 -4
  184. package/dist/widgets/readForWidgetGoals.js +3 -1
  185. package/dist/widgets/readForWidgetGoals.js.map +1 -1
  186. package/dist/widgets/readForWidgetRealtime.d.ts +4 -3
  187. package/dist/widgets/readForWidgetRealtime.js +3 -1
  188. package/dist/widgets/readForWidgetRealtime.js.map +1 -1
  189. package/dist/widgets/readForWidgetSeries.d.ts +4 -4
  190. package/dist/widgets/readForWidgetSeries.js +3 -1
  191. package/dist/widgets/readForWidgetSeries.js.map +1 -1
  192. package/dist/widgets/registerWidgets.js +3 -1
  193. package/dist/widgets/registerWidgets.js.map +1 -1
  194. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"posthog.js","names":[],"sources":["../../../src/adapters/posthog/posthog.ts"],"sourcesContent":["import { jsLiteral } from '../../capture/jsLiteral'\nimport type { CaptureSupport, ProxyRoute } from '../../core/capture'\nimport {\n\ttype AdapterContext,\n\ttype AnalyticsAdapter,\n\ttype AnalyticsCapabilities,\n\ttype AnalyticsQuery,\n\ttype AnalyticsResult,\n\ttype AnalyticsRow,\n\tDIMENSION_KEYS,\n\ttype DimensionKey,\n\ttype FilterOperator,\n\ttype MetricKey,\n\ttype MetricValues,\n} from '../../core/contract'\nimport type { FetchLike } from '../../core/fetch'\nimport { vendorReading } from '../../core/metricValues'\nimport { DEFAULT_TIMEZONE } from '../../timeframe/tz'\nimport { emptyGoalBreakdown, goalHint, hintFailed, hintSlugs } from '../goalRead'\nimport { hostnameOf, withoutTrailingSlash } from '../http/baseUrl'\nimport {\n\tdeclaredFilters,\n\teveryOperatorOn,\n\tfirstMapped,\n\tmappedKeys,\n\tproviderMetricKeys,\n} from '../mapping'\nimport { readTime } from '../readTime'\nimport { dayIso, hourIso } from '../series'\nimport { upstreamJson } from '../upstream'\n\nexport interface PosthogConfig {\n\t/** PostHog project id (numeric). */\n\tprojectId: string\n\t/** Personal API key with the \"Query Read\" scope (phx_...). Never exposed to the browser. */\n\tapiKey: string\n\t/**\n\t * API address. Defaults to US Cloud; EU is https://eu.posthog.com, self-host is your instance's\n\t * address, with the base path when a reverse proxy serves it under one.\n\t */\n\thost?: string\n\t/** Maximum days of historical data. Defaults to 730. Pass null to disable clamping. */\n\tmaxLookbackDays?: number | null\n\t/**\n\t * Event property holding a read's scope (e.g. 'tenant'): one project captures every scope with it\n\t * set, and a scoped read filters on it as an escaped literal.\n\t */\n\tscopeProperty?: string\n\t/**\n\t * PostHog Cloud region for the proxied capture routes. Derived from `host` when omitted. A\n\t * self-hosted `host` takes capture itself and ignores this.\n\t */\n\tregion?: 'us' | 'eu'\n\t/**\n\t * The PostHog app's address, passed as `ui_host` so toolbar links open the app, not the proxy. A\n\t * self-hosted instance gets none unless this names it, so no page publishes its address on its own.\n\t */\n\tuiHost?: string\n\t/**\n\t * The public browser key (phc_...) for `posthog.init`, never the private `apiKey`. Capture is\n\t * declared only when this is set: without it the install reads dashboards and captures nothing.\n\t */\n\tprojectToken?: string\n\t/** The fetch reads and the capture proxy reach PostHog with. Unset, the global fetch. */\n\tfetch?: FetchLike\n}\n\nconst US_CLOUD = 'https://us.posthog.com'\n\nconst resolveRegion = (config: PosthogConfig): 'us' | 'eu' => {\n\tif (config.region) {\n\t\treturn config.region\n\t}\n\treturn config.host?.includes('eu.posthog.com') ? 'eu' : 'us'\n}\n\n/**\n * PostHog's official stub, trimmed: one self-sequencing script whose `init` injects `array.js` from\n * the proxy. Added: the injected tag inherits the inline's nonce, or a nonce CSP blocks the bundle.\n */\nconst POSTHOG_STUB =\n\t'!function(t,e){var o,n,p,r,c;e.__SV||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(\".\");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement(\"script\")).type=\"text/javascript\",p.crossOrigin=\"anonymous\",p.async=!0,p.src=s.api_host.replace(\".i.posthog.com\",\"-assets.i.posthog.com\")+\"/static/array.js\",(c=t.currentScript&&(t.currentScript.nonce||t.currentScript.getAttribute(\"nonce\")))&&(p.nonce=c,p.setAttribute(\"nonce\",c)),(r=t.getElementsByTagName(\"script\")[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a=\"posthog\",u.people=u.people||[],o=\"init capture register register_once identify group alias reset setPersonProperties captureException opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing getFeatureFlag isFeatureEnabled reloadFeatureFlags onFeatureFlags on debug\".split(\" \"),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);'\n\n/** Whether an address is PostHog Cloud's, which serves capture from per-region hosts of its own. */\nconst isCloudHost = (address: string): boolean => {\n\tconst hostname = hostnameOf(address)\n\treturn hostname === 'posthog.com' || hostname.endsWith('.posthog.com')\n}\n\ninterface CaptureHosts {\n\tassets: string\n\tingest: string\n\tcloud: boolean\n\tui?: string\n}\n\n/**\n * Where capture goes and app links point. PostHog Cloud splits assets and ingest hosts; a self-hosted\n * instance serves both at the read address, as posthog-js assumes for any non-Cloud `api_host`.\n */\nconst captureHosts = (config: PosthogConfig): CaptureHosts => {\n\tconst host = config.host === undefined ? undefined : withoutTrailingSlash(config.host)\n\tconst ui = config.uiHost === undefined ? undefined : withoutTrailingSlash(config.uiHost)\n\tif (host !== undefined && !isCloudHost(host)) {\n\t\treturn { assets: host, ingest: host, cloud: false, ...(ui === undefined ? {} : { ui }) }\n\t}\n\tconst region = resolveRegion(config)\n\treturn {\n\t\tassets: `https://${region}-assets.i.posthog.com`,\n\t\tingest: `https://${region}.i.posthog.com`,\n\t\tcloud: true,\n\t\tui: ui ?? `https://${region}.posthog.com`,\n\t}\n}\n\n/**\n * The paths posthog-js sends to on a self-hosted instance, which is also the whole app with its\n * login and admin: its proxy declares these alone, and Cloud's capture-only hosts keep the catch-all.\n */\nexport const POSTHOG_SELF_HOSTED_CAPTURE_PATHS: readonly string[] = [\n\t'/e',\n\t'/i/v0/e',\n\t'/batch',\n\t'/capture',\n\t'/track',\n\t'/engage',\n\t'/decide',\n\t'/flags',\n\t'/s',\n]\n\nconst dataRoutes = (hosts: CaptureHosts): ProxyRoute[] =>\n\thosts.cloud\n\t\t? [{ source: '/:p*', upstream: `${hosts.ingest}/:p*`, kind: 'data' }]\n\t\t: POSTHOG_SELF_HOSTED_CAPTURE_PATHS.map((path) => ({\n\t\t\t\tsource: path,\n\t\t\t\tupstream: `${hosts.ingest}${path}`,\n\t\t\t\tkind: 'data',\n\t\t\t}))\n\n/**\n * posthog-js's single-page-app mode: without it every navigation after the first page is lost, since\n * the vendor sink forwards no pageview.\n */\nconst CAPTURE_PAGEVIEW = 'history_change'\n\n/**\n * `opt_out_persistence_by_default` makes an opt-out (closed gate, excluded browser) delete PostHog's\n * `ph_<token>_posthog` storage, distinct id included, and keep none while it holds.\n */\nconst initOptions = (path: string, ui: string | undefined): string =>\n\t[\n\t\t`api_host:${jsLiteral(path)}`,\n\t\t...(ui === undefined ? [] : [`ui_host:${jsLiteral(ui)}`]),\n\t\t`capture_pageview:${jsLiteral(CAPTURE_PAGEVIEW)}`,\n\t\t'opt_out_persistence_by_default:true',\n\t].join(',')\n\nfunction buildCapture(config: PosthogConfig, token: string): CaptureSupport {\n\tconst hosts = captureHosts(config)\n\treturn {\n\t\tproxy: {\n\t\t\ttrailingSlashes: true,\n\t\t\troutes: [\n\t\t\t\t{ source: '/static/:p*', upstream: `${hosts.assets}/static/:p*`, kind: 'script' },\n\t\t\t\t{ source: '/array/:p*', upstream: `${hosts.assets}/array/:p*`, kind: 'script' },\n\t\t\t\t...dataRoutes(hosts),\n\t\t\t],\n\t\t\t...(config.fetch ? { fetch: config.fetch } : {}),\n\t\t},\n\t\tsnippet: ({ path, scope }) => {\n\t\t\t// A super-property rather than a per-call one, so it rides the events a host\n\t\t\t// captures itself, which is what `scopeProperty` reads back on.\n\t\t\tconst stamp =\n\t\t\t\tconfig.scopeProperty && scope\n\t\t\t\t\t? `;posthog.register({[${jsLiteral(config.scopeProperty)}]:${jsLiteral(scope)}})`\n\t\t\t\t\t: ''\n\t\t\treturn {\n\t\t\t\tscripts: [\n\t\t\t\t\t{\n\t\t\t\t\t\tinline: `${POSTHOG_STUB}posthog.init(${jsLiteral(token)},{${initOptions(path, hosts.ui)}})${stamp}`,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t}\n\t\t},\n\t\tclient: { kind: 'posthog', token },\n\t}\n}\n\n// Pageview-scoped expressions, for a WHERE filtered to `$pageview`. visits and sessions\n// share one expression, deduped before the SELECT and read back by position.\nconst METRIC_SQL_PAGEVIEW: Partial<Record<MetricKey, string>> = {\n\tpageviews: 'count()',\n\tvisitors: 'count(DISTINCT person_id)',\n\tvisits: 'count(DISTINCT properties.$session_id)',\n\tsessions: 'count(DISTINCT properties.$session_id)',\n}\n\n// All-event expressions, for `events`, `conversions` or an `event`/`goal` breakdown: the\n// WHERE keeps every event, so pageview metrics scope themselves with conditional aggregates.\nconst METRIC_SQL_ALL: Partial<Record<MetricKey, string>> = {\n\tpageviews: \"countIf(event = '$pageview')\",\n\tvisitors: \"count(DISTINCT if(event = '$pageview', person_id, NULL))\",\n\tvisits: \"count(DISTINCT if(event = '$pageview', properties.$session_id, NULL))\",\n\tsessions: \"count(DISTINCT if(event = '$pageview', properties.$session_id, NULL))\",\n\tevents: 'count()',\n}\n\n// A goal breakdown scans only the goal events, so every metric counts the rows it has: the\n// conditional aggregates above would zero visitors, and every goal's conversion rate with it.\nconst METRIC_SQL_GOAL: Partial<Record<MetricKey, string>> = {\n\tpageviews: 'count()',\n\tvisitors: 'count(DISTINCT person_id)',\n\tvisits: 'count(DISTINCT properties.$session_id)',\n\tsessions: 'count(DISTINCT properties.$session_id)',\n\tevents: 'count()',\n}\n\n/**\n * A goal is an event name, so its slug must equal the captured event's. `channel` is PostHog's own\n * `$channel_type`, computed per session and honouring a project's custom channel rules.\n */\nconst DIMENSION_SQL: Partial<Record<DimensionKey, string>> = {\n\tpage: 'properties.$pathname',\n\tchannel: 'session.$channel_type',\n\tevent: 'event',\n\tgoal: 'event',\n}\n\nconst posthogMetrics: ReadonlySet<MetricKey> = new Set<MetricKey>([\n\t'pageviews',\n\t'visitors',\n\t'visits',\n\t'sessions',\n\t'events',\n\t// No fixed expression: it counts the read's own goal slugs, so each query builds its own.\n\t'conversions',\n])\nconst posthogDimensions = mappedKeys(DIMENSION_KEYS, DIMENSION_SQL)\nconst posthogFilters = everyOperatorOn(posthogDimensions)\n\n// The Query API has no parameter binding, so values are inlined as quoted literals.\n// Escape backslashes first, then single quotes, so a crafted path cannot break out.\nconst sqlString = (value: string): string =>\n\t`'${value.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")}'`\n\n// ILIKE reads % and _ as wildcards and \\ as its escape, so \\ is escaped first (a raw one\n// would escape the next character), then % and _, before the value is wrapped in % ... %.\nconst escapeLikeValue = (value: string): string => value.replace(/[\\\\%_]/g, (c) => `\\\\${c}`)\n\n/** Each filter operator as HogQL on a dimension's expression. */\nconst FILTER_SQL: Record<FilterOperator, (expr: string, value: string) => string> = {\n\teq: (expr, value) => `${expr} = ${sqlString(value)}`,\n\tcontains: (expr, value) => `${expr} ILIKE ${sqlString(`%${escapeLikeValue(value)}%`)}`,\n\tmatches: (expr, value) => `match(${expr}, ${sqlString(value)})`,\n}\n\ninterface SeriesBucket {\n\t/** The HogQL function that buckets a timestamp. */\n\tfn: string\n\t/** A bucket label read back as an ISO instant. */\n\tisoOf: (label: string) => string | null\n}\n\nconst SERIES_BUCKETS: Record<'day' | 'hour', SeriesBucket> = {\n\tday: { fn: 'toStartOfDay', isoOf: dayIso },\n\thour: { fn: 'toStartOfHour', isoOf: hourIso },\n}\n\n/**\n * A bare HogQL date literal parses in the project's timezone, so the zone is passed explicitly to\n * keep the bound an absolute instant.\n */\nconst utcDateTime = (d: Date): string =>\n\t`toDateTime(${sqlString(d.toISOString().slice(0, 19).replace('T', ' '))}, 'UTC')`\n\ninterface PosthogQueryResponse {\n\tcolumns: string[]\n\ttypes: string[]\n\tresults: unknown[][]\n}\n\nexport function posthog(config: PosthogConfig): AnalyticsAdapter {\n\tconst host = withoutTrailingSlash(config.host ?? US_CLOUD)\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 730\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\trealtime: false,\n\t\tminGranularity: 'hour',\n\t\tmaxLookbackDays,\n\t\tmetrics: posthogMetrics,\n\t\tdimensions: posthogDimensions,\n\t\tfilters: posthogFilters,\n\t\tsemantics: { visitors: 'distinct', sessions: 'provider' },\n\t\trateLimit: { requestsPerMinute: 240, requestsPerHour: 2400 },\n\t\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n\t\tupstreamAware: true,\n\t\t...(config.scopeProperty ? { scopedQueries: true } : {}),\n\t}\n\n\treturn {\n\t\tid: 'posthog',\n\t\tlabel: 'PostHog',\n\t\tcapabilities,\n\t\t...(config.projectToken ? { capture: buildCapture(config, config.projectToken) } : {}),\n\t\tisConfigured: () => Boolean(config.projectId && config.apiKey),\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = readTime(ctx)\n\t\t\tconst breakdown = firstMapped(q.dimensions, DIMENSION_SQL)\n\t\t\tconst goalBreakdown = breakdown?.dimension === 'goal'\n\t\t\tconst hint = goalHint(q)\n\t\t\tconst empty = goalBreakdown\n\t\t\t\t? emptyGoalBreakdown({ provider: 'posthog', fetchedAt, hint })\n\t\t\t\t: null\n\t\t\tif (empty) {\n\t\t\t\treturn empty\n\t\t\t}\n\t\t\t// These reads scan every event: a `$pageview` WHERE beside an `event = 'x'` filter would\n\t\t\t// contradict itself and zero every metric, so they switch to conditional aggregation.\n\t\t\tconst scanAllEvents =\n\t\t\t\tq.metrics.includes('events') ||\n\t\t\t\tq.metrics.includes('conversions') ||\n\t\t\t\tbreakdown?.dimension === 'event' ||\n\t\t\t\tgoalBreakdown ||\n\t\t\t\t(q.filters ?? []).some((f) => f.dimension === 'event')\n\t\t\tconst slugs = hintSlugs(hint)\n\t\t\tconst eventInHint = slugs ? `event IN (${slugs.map(sqlString).join(', ')})` : undefined\n\t\t\t// Counting the goals conditionally, rather than restricting the WHERE, keeps the\n\t\t\t// site metrics of a read that asks for both site-wide.\n\t\t\tconst metricSql: Partial<Record<MetricKey, string>> = {\n\t\t\t\t...(goalBreakdown ? METRIC_SQL_GOAL : scanAllEvents ? METRIC_SQL_ALL : METRIC_SQL_PAGEVIEW),\n\t\t\t\t...(eventInHint ? { conversions: `countIf(${eventInHint})` } : {}),\n\t\t\t}\n\t\t\tconst exprs = providerMetricKeys(q.metrics, metricSql)\n\t\t\tconst unresolved = q.metrics.includes('conversions') && hintFailed(hint)\n\t\t\tconst meta: AnalyticsResult['meta'] = {\n\t\t\t\tprovider: 'posthog',\n\t\t\t\tfetchedAt,\n\t\t\t\t...(unresolved ? { goalsUnresolved: true as const } : {}),\n\t\t\t}\n\n\t\t\tconst where = [\n\t\t\t\t...(scanAllEvents ? [] : [\"event = '$pageview'\"]),\n\t\t\t\t`timestamp >= ${utcDateTime(q.dateRange.start)}`,\n\t\t\t\t`timestamp <= ${utcDateTime(q.dateRange.end)}`,\n\t\t\t]\n\t\t\t// Only the goal breakdown narrows the scan itself: its rows are the goals and\n\t\t\t// nothing else.\n\t\t\tif (goalBreakdown && eventInHint) {\n\t\t\t\twhere.push(eventInHint)\n\t\t\t}\n\t\t\tif (q.path) {\n\t\t\t\twhere.push(`properties.$pathname = ${sqlString(q.path)}`)\n\t\t\t}\n\t\t\tif (q.hostname) {\n\t\t\t\twhere.push(`properties.$host = ${sqlString(q.hostname)}`)\n\t\t\t}\n\t\t\tif (config.scopeProperty && q.scope !== undefined) {\n\t\t\t\t// Bracket property access with escaped literals: neither the configured\n\t\t\t\t// property name nor the scope value can break out of the HogQL string.\n\t\t\t\twhere.push(`properties[${sqlString(config.scopeProperty)}] = ${sqlString(q.scope)}`)\n\t\t\t}\n\t\t\tfor (const { filter, field } of declaredFilters(capabilities, q.filters, DIMENSION_SQL)) {\n\t\t\t\twhere.push(FILTER_SQL[filter.operator](field, filter.value))\n\t\t\t}\n\t\t\tconst columns = exprs.map((expr, i) => `${expr} AS m${i}`).join(', ')\n\t\t\tconst from = `FROM events WHERE ${where.join(' AND ')}`\n\n\t\t\tconst runSql = (sql: string): Promise<PosthogQueryResponse> =>\n\t\t\t\tupstreamJson<PosthogQueryResponse>(ctx, `${host}/api/projects/${config.projectId}/query/`, {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders: { authorization: `Bearer ${config.apiKey}` },\n\t\t\t\t\tbody: { query: { kind: 'HogQLQuery', query: sql } },\n\t\t\t\t\tprovider: 'posthog',\n\t\t\t\t\tfetch: config.fetch,\n\t\t\t\t})\n\n\t\t\t/** A result row's metrics, its metric columns starting at `offset`. */\n\t\t\tconst readRow = (row: unknown[], offset: number): MetricValues => {\n\t\t\t\tconst out: MetricValues = {}\n\t\t\t\tfor (const metric of q.metrics) {\n\t\t\t\t\tconst expr = metricSql[metric]\n\t\t\t\t\tif (expr !== undefined) {\n\t\t\t\t\t\tout[metric] = vendorReading(metric, row[offset + exprs.indexOf(expr)])\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn out\n\t\t\t}\n\n\t\t\tconst fetchTotals = async (): Promise<MetricValues> => {\n\t\t\t\tconst data = await runSql(`SELECT ${columns} ${from}`)\n\t\t\t\tconst row = data.results[0]\n\t\t\t\treturn row ? readRow(row, 0) : {}\n\t\t\t}\n\n\t\t\tconst unit =\n\t\t\t\t!breakdown && (q.granularity === 'day' || q.granularity === 'hour')\n\t\t\t\t\t? q.granularity\n\t\t\t\t\t: undefined\n\t\t\tif (unit) {\n\t\t\t\tconst { fn, isoOf } = SERIES_BUCKETS[unit]\n\t\t\t\t// Without a timezone argument HogQL buckets in the project's zone, so the reporting zone\n\t\t\t\t// (UTC included) is always passed; the window literals stay UTC instants, already aligned.\n\t\t\t\tconst bucket = `${fn}(timestamp, ${sqlString(q.timezone ?? DEFAULT_TIMEZONE)})`\n\t\t\t\tconst [series, totals] = await Promise.all([\n\t\t\t\t\trunSql(\n\t\t\t\t\t\t`SELECT ${bucket} AS ${unit}, ${columns} ${from} GROUP BY ${unit} ORDER BY ${unit}`\n\t\t\t\t\t),\n\t\t\t\t\tfetchTotals(),\n\t\t\t\t])\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const row of series.results) {\n\t\t\t\t\tconst timestamp = isoOf(String(row[0] ?? ''))\n\t\t\t\t\tif (timestamp) {\n\t\t\t\t\t\trows.push({ timestamp, metrics: readRow(row, 1) })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { rows, totals, meta }\n\t\t\t}\n\n\t\t\tif (breakdown) {\n\t\t\t\tconst data = await runSql(\n\t\t\t\t\t`SELECT ${breakdown.field} AS dim, ${columns} ${from} GROUP BY dim ORDER BY m0 DESC LIMIT ${q.limit ?? 100}`\n\t\t\t\t)\n\t\t\t\tconst rows: AnalyticsRow[] = data.results.map((row) => ({\n\t\t\t\t\tdimensions: { [breakdown.dimension]: String(row[0] ?? '') },\n\t\t\t\t\tmetrics: readRow(row, 1),\n\t\t\t\t}))\n\t\t\t\treturn { rows, totals: undefined, meta }\n\t\t\t}\n\n\t\t\tconst totals = await fetchTotals()\n\t\t\treturn { rows: [{ metrics: totals }], totals, meta }\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;AAmEA,MAAM,WAAW;AAEjB,MAAM,iBAAiB,WAAuC;CAC7D,IAAI,OAAO,QACV,OAAO,OAAO;CAEf,OAAO,OAAO,MAAM,SAAS,gBAAgB,IAAI,OAAO;AACzD;;;;;AAMA,MAAM,eACL;;AAGD,MAAM,eAAe,YAA6B;CACjD,MAAM,WAAW,WAAW,OAAO;CACnC,OAAO,aAAa,iBAAiB,SAAS,SAAS,cAAc;AACtE;;;;;AAaA,MAAM,gBAAgB,WAAwC;CAC7D,MAAM,OAAO,OAAO,SAAS,KAAA,IAAY,KAAA,IAAY,qBAAqB,OAAO,IAAI;CACrF,MAAM,KAAK,OAAO,WAAW,KAAA,IAAY,KAAA,IAAY,qBAAqB,OAAO,MAAM;CACvF,IAAI,SAAS,KAAA,KAAa,CAAC,YAAY,IAAI,GAC1C,OAAO;EAAE,QAAQ;EAAM,QAAQ;EAAM,OAAO;EAAO,GAAI,OAAO,KAAA,IAAY,CAAC,IAAI,EAAE,GAAG;CAAG;CAExF,MAAM,SAAS,cAAc,MAAM;CACnC,OAAO;EACN,QAAQ,WAAW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/adapters/posthog/posthog.ts"],"sourcesContent":["import { jsLiteral } from '../../capture/jsLiteral'\nimport type { CaptureSupport, ProxyRoute } from '../../core/capture'\nimport {\n\ttype AdapterContext,\n\ttype AnalyticsAdapter,\n\ttype AnalyticsCapabilities,\n\ttype AnalyticsQuery,\n\ttype AnalyticsResult,\n\ttype AnalyticsRow,\n\tDIMENSION_KEYS,\n\ttype DimensionKey,\n\ttype FilterOperator,\n\ttype MetricKey,\n\ttype MetricValues,\n} from '../../core/contract'\nimport type { FetchLike } from '../../core/fetch'\nimport { vendorReading } from '../../core/metricValues'\nimport { type AdapterLabelOption, adapterLabel } from '../../core/sourceLabel'\nimport { DEFAULT_TIMEZONE } from '../../timeframe/tz'\nimport { emptyGoalBreakdown, goalHint, hintFailed, hintSlugs } from '../goalRead'\nimport { hostnameOf, withoutTrailingSlash } from '../http/baseUrl'\nimport {\n\tdeclaredFilters,\n\teveryOperatorOn,\n\tfirstMapped,\n\tmappedKeys,\n\tproviderMetricKeys,\n} from '../mapping'\nimport { readTime } from '../readTime'\nimport { dayIso, hourIso } from '../series'\nimport { upstreamJson } from '../upstream'\n\nexport interface PosthogConfig {\n\t/**\n\t * The source's name in pickers and listings: a string, a map by admin language (read like\n\t * `view.navLabel`), or a function naming it per reader and scope. Default `'PostHog'`.\n\t */\n\tlabel?: AdapterLabelOption\n\t/** PostHog project id (numeric). */\n\tprojectId: string\n\t/** Personal API key with the \"Query Read\" scope (phx_...). Never exposed to the browser. */\n\tapiKey: string\n\t/**\n\t * API address. Defaults to US Cloud; EU is https://eu.posthog.com, self-host is your instance's\n\t * address, with the base path when a reverse proxy serves it under one.\n\t */\n\thost?: string\n\t/** Maximum days of historical data. Defaults to 730. Pass null to disable clamping. */\n\tmaxLookbackDays?: number | null\n\t/**\n\t * Event property holding a read's scope (e.g. 'tenant'): one project captures every scope with it\n\t * set, and a scoped read filters on it as an escaped literal.\n\t */\n\tscopeProperty?: string\n\t/**\n\t * PostHog Cloud region for the proxied capture routes. Derived from `host` when omitted. A\n\t * self-hosted `host` takes capture itself and ignores this.\n\t */\n\tregion?: 'us' | 'eu'\n\t/**\n\t * The PostHog app's address, passed as `ui_host` so toolbar links open the app, not the proxy. A\n\t * self-hosted instance gets none unless this names it, so no page publishes its address on its own.\n\t */\n\tuiHost?: string\n\t/**\n\t * The public browser key (phc_...) for `posthog.init`, never the private `apiKey`. Capture is\n\t * declared only when this is set: without it the install reads dashboards and captures nothing.\n\t */\n\tprojectToken?: string\n\t/** The fetch reads and the capture proxy reach PostHog with. Unset, the global fetch. */\n\tfetch?: FetchLike\n}\n\nconst US_CLOUD = 'https://us.posthog.com'\n\nconst resolveRegion = (config: PosthogConfig): 'us' | 'eu' => {\n\tif (config.region) {\n\t\treturn config.region\n\t}\n\treturn config.host?.includes('eu.posthog.com') ? 'eu' : 'us'\n}\n\n/**\n * PostHog's official stub, trimmed: one self-sequencing script whose `init` injects `array.js` from\n * the proxy. Added: the injected tag inherits the inline's nonce, or a nonce CSP blocks the bundle.\n * Changed for a second slot's named client: `init` stays the stub's own rather than a queued call, so\n * that client gets its own queue at once; only the first `init` injects `array.js`; and a loaded\n * posthog-js (no longer an array) is never replaced, so the client is initialised on it.\n */\nconst POSTHOG_STUB =\n\t'!function(t,e){var o,n,p,r,c;e.__SV||!Array.isArray(e)||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(\".\");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}e.__L||(e.__L=1,(p=t.createElement(\"script\")).type=\"text/javascript\",p.crossOrigin=\"anonymous\",p.async=!0,p.src=s.api_host.replace(\".i.posthog.com\",\"-assets.i.posthog.com\")+\"/static/array.js\",(c=t.currentScript&&(t.currentScript.nonce||t.currentScript.getAttribute(\"nonce\")))&&(p.nonce=c,p.setAttribute(\"nonce\",c)),(r=t.getElementsByTagName(\"script\")[0]).parentNode.insertBefore(p,r));var u=e;for(void 0!==a?u=e[a]=[]:a=\"posthog\",u.people=u.people||[],o=\"capture register register_once identify group alias reset setPersonProperties captureException opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing getFeatureFlag isFeatureEnabled reloadFeatureFlags onFeatureFlags on debug\".split(\" \"),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);'\n\n/** Whether an address is PostHog Cloud's, which serves capture from per-region hosts of its own. */\nconst isCloudHost = (address: string): boolean => {\n\tconst hostname = hostnameOf(address)\n\treturn hostname === 'posthog.com' || hostname.endsWith('.posthog.com')\n}\n\ninterface CaptureHosts {\n\tassets: string\n\tingest: string\n\tcloud: boolean\n\tui?: string\n}\n\n/**\n * Where capture goes and app links point. PostHog Cloud splits assets and ingest hosts; a self-hosted\n * instance serves both at the read address, as posthog-js assumes for any non-Cloud `api_host`.\n */\nconst captureHosts = (config: PosthogConfig): CaptureHosts => {\n\tconst host = config.host === undefined ? undefined : withoutTrailingSlash(config.host)\n\tconst ui = config.uiHost === undefined ? undefined : withoutTrailingSlash(config.uiHost)\n\tif (host !== undefined && !isCloudHost(host)) {\n\t\treturn { assets: host, ingest: host, cloud: false, ...(ui === undefined ? {} : { ui }) }\n\t}\n\tconst region = resolveRegion(config)\n\treturn {\n\t\tassets: `https://${region}-assets.i.posthog.com`,\n\t\tingest: `https://${region}.i.posthog.com`,\n\t\tcloud: true,\n\t\tui: ui ?? `https://${region}.posthog.com`,\n\t}\n}\n\n/**\n * The paths posthog-js sends to on a self-hosted instance, which is also the whole app with its\n * login and admin: its proxy declares these alone, and Cloud's capture-only hosts keep the catch-all.\n */\nexport const POSTHOG_SELF_HOSTED_CAPTURE_PATHS: readonly string[] = [\n\t'/e',\n\t'/i/v0/e',\n\t'/batch',\n\t'/capture',\n\t'/track',\n\t'/engage',\n\t'/decide',\n\t'/flags',\n\t'/s',\n]\n\nconst dataRoutes = (hosts: CaptureHosts): ProxyRoute[] =>\n\thosts.cloud\n\t\t? [{ source: '/:p*', upstream: `${hosts.ingest}/:p*`, kind: 'data' }]\n\t\t: POSTHOG_SELF_HOSTED_CAPTURE_PATHS.map((path) => ({\n\t\t\t\tsource: path,\n\t\t\t\tupstream: `${hosts.ingest}${path}`,\n\t\t\t\tkind: 'data',\n\t\t\t}))\n\n/**\n * posthog-js's single-page-app mode: without it every navigation after the first page is lost, since\n * the vendor sink forwards no pageview to the primary client.\n */\nconst CAPTURE_PAGEVIEW = 'history_change'\n\n/**\n * A named client counts no pageview itself: posthog-js wraps `history.pushState` for the first\n * client alone, so the sink hands it the tracker's pageviews. Its pageleave, which PostHog ties to\n * its own pageviews, is asked for outright.\n */\nconst NAMED_CLIENT_PAGEVIEWS = ['capture_pageview:false', 'capture_pageleave:true']\n\n/**\n * `opt_out_persistence_by_default` makes an opt-out (closed gate, excluded browser) delete PostHog's\n * `ph_<token>_posthog` storage, distinct id included, and keep none while it holds.\n */\nconst initOptions = (path: string, ui: string | undefined, named: boolean): string =>\n\t[\n\t\t`api_host:${jsLiteral(path)}`,\n\t\t...(ui === undefined ? [] : [`ui_host:${jsLiteral(ui)}`]),\n\t\t...(named ? NAMED_CLIENT_PAGEVIEWS : [`capture_pageview:${jsLiteral(CAPTURE_PAGEVIEW)}`]),\n\t\t'opt_out_persistence_by_default:true',\n\t].join(',')\n\nfunction buildCapture(config: PosthogConfig, token: string): CaptureSupport {\n\tconst hosts = captureHosts(config)\n\treturn {\n\t\tproxy: {\n\t\t\ttrailingSlashes: true,\n\t\t\troutes: [\n\t\t\t\t{ source: '/static/:p*', upstream: `${hosts.assets}/static/:p*`, kind: 'script' },\n\t\t\t\t{ source: '/array/:p*', upstream: `${hosts.assets}/array/:p*`, kind: 'script' },\n\t\t\t\t...dataRoutes(hosts),\n\t\t\t],\n\t\t\t...(config.fetch ? { fetch: config.fetch } : {}),\n\t\t},\n\t\tsnippet: ({ path, scope, instance }) => {\n\t\t\tconst named = instance !== undefined\n\t\t\tconst client = named ? `posthog[${jsLiteral(instance)}]` : 'posthog'\n\t\t\t// A super-property rather than a per-call one, so it rides the events a host\n\t\t\t// captures itself, which is what `scopeProperty` reads back on.\n\t\t\tconst stamp =\n\t\t\t\tconfig.scopeProperty && scope\n\t\t\t\t\t? `;${client}.register({[${jsLiteral(config.scopeProperty)}]:${jsLiteral(scope)}})`\n\t\t\t\t\t: ''\n\t\t\tconst name = named ? `,${jsLiteral(instance)}` : ''\n\t\t\treturn {\n\t\t\t\tscripts: [\n\t\t\t\t\t{\n\t\t\t\t\t\tinline: `${POSTHOG_STUB}posthog.init(${jsLiteral(token)},{${initOptions(path, hosts.ui, named)}}${name})${stamp}`,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t}\n\t\t},\n\t\tclient: { kind: 'posthog', token },\n\t}\n}\n\n// Pageview-scoped expressions, for a WHERE filtered to `$pageview`. visits and sessions\n// share one expression, deduped before the SELECT and read back by position.\nconst METRIC_SQL_PAGEVIEW: Partial<Record<MetricKey, string>> = {\n\tpageviews: 'count()',\n\tvisitors: 'count(DISTINCT person_id)',\n\tvisits: 'count(DISTINCT properties.$session_id)',\n\tsessions: 'count(DISTINCT properties.$session_id)',\n}\n\n// All-event expressions, for `events`, `conversions` or an `event`/`goal` breakdown: the\n// WHERE keeps every event, so pageview metrics scope themselves with conditional aggregates.\nconst METRIC_SQL_ALL: Partial<Record<MetricKey, string>> = {\n\tpageviews: \"countIf(event = '$pageview')\",\n\tvisitors: \"count(DISTINCT if(event = '$pageview', person_id, NULL))\",\n\tvisits: \"count(DISTINCT if(event = '$pageview', properties.$session_id, NULL))\",\n\tsessions: \"count(DISTINCT if(event = '$pageview', properties.$session_id, NULL))\",\n\tevents: 'count()',\n}\n\n// A goal breakdown scans only the goal events, so every metric counts the rows it has: the\n// conditional aggregates above would zero visitors, and every goal's conversion rate with it.\nconst METRIC_SQL_GOAL: Partial<Record<MetricKey, string>> = {\n\tpageviews: 'count()',\n\tvisitors: 'count(DISTINCT person_id)',\n\tvisits: 'count(DISTINCT properties.$session_id)',\n\tsessions: 'count(DISTINCT properties.$session_id)',\n\tevents: 'count()',\n}\n\n/**\n * A goal is an event name, so its slug must equal the captured event's. `channel` is PostHog's own\n * `$channel_type`, computed per session and honouring a project's custom channel rules.\n */\nconst DIMENSION_SQL: Partial<Record<DimensionKey, string>> = {\n\tpage: 'properties.$pathname',\n\tchannel: 'session.$channel_type',\n\tevent: 'event',\n\tgoal: 'event',\n}\n\nconst posthogMetrics: ReadonlySet<MetricKey> = new Set<MetricKey>([\n\t'pageviews',\n\t'visitors',\n\t'visits',\n\t'sessions',\n\t'events',\n\t// No fixed expression: it counts the read's own goal slugs, so each query builds its own.\n\t'conversions',\n])\nconst posthogDimensions = mappedKeys(DIMENSION_KEYS, DIMENSION_SQL)\nconst posthogFilters = everyOperatorOn(posthogDimensions)\n\n// The Query API has no parameter binding, so values are inlined as quoted literals.\n// Escape backslashes first, then single quotes, so a crafted path cannot break out.\nconst sqlString = (value: string): string =>\n\t`'${value.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")}'`\n\n// ILIKE reads % and _ as wildcards and \\ as its escape, so \\ is escaped first (a raw one\n// would escape the next character), then % and _, before the value is wrapped in % ... %.\nconst escapeLikeValue = (value: string): string => value.replace(/[\\\\%_]/g, (c) => `\\\\${c}`)\n\n/** Each filter operator as HogQL on a dimension's expression. */\nconst FILTER_SQL: Record<FilterOperator, (expr: string, value: string) => string> = {\n\teq: (expr, value) => `${expr} = ${sqlString(value)}`,\n\tcontains: (expr, value) => `${expr} ILIKE ${sqlString(`%${escapeLikeValue(value)}%`)}`,\n\tmatches: (expr, value) => `match(${expr}, ${sqlString(value)})`,\n}\n\ninterface SeriesBucket {\n\t/** The HogQL function that buckets a timestamp. */\n\tfn: string\n\t/** A bucket label read back as an ISO instant. */\n\tisoOf: (label: string) => string | null\n}\n\nconst SERIES_BUCKETS: Record<'day' | 'hour', SeriesBucket> = {\n\tday: { fn: 'toStartOfDay', isoOf: dayIso },\n\thour: { fn: 'toStartOfHour', isoOf: hourIso },\n}\n\n/**\n * A bare HogQL date literal parses in the project's timezone, so the zone is passed explicitly to\n * keep the bound an absolute instant.\n */\nconst utcDateTime = (d: Date): string =>\n\t`toDateTime(${sqlString(d.toISOString().slice(0, 19).replace('T', ' '))}, 'UTC')`\n\ninterface PosthogQueryResponse {\n\tcolumns: string[]\n\ttypes: string[]\n\tresults: unknown[][]\n}\n\nexport function posthog(config: PosthogConfig): AnalyticsAdapter {\n\tconst host = withoutTrailingSlash(config.host ?? US_CLOUD)\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 730\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\trealtime: false,\n\t\tminGranularity: 'hour',\n\t\tmaxLookbackDays,\n\t\tmetrics: posthogMetrics,\n\t\tdimensions: posthogDimensions,\n\t\tfilters: posthogFilters,\n\t\tsemantics: { visitors: 'distinct', sessions: 'provider' },\n\t\trateLimit: { requestsPerMinute: 240, requestsPerHour: 2400 },\n\t\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n\t\tupstreamAware: true,\n\t\t...(config.scopeProperty ? { scopedQueries: true } : {}),\n\t}\n\n\treturn {\n\t\tid: 'posthog',\n\t\t...adapterLabel(config.label, 'PostHog', 'posthog({ label })'),\n\t\tcapabilities,\n\t\t...(config.projectToken ? { capture: buildCapture(config, config.projectToken) } : {}),\n\t\tisConfigured: () => Boolean(config.projectId && config.apiKey),\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = readTime(ctx)\n\t\t\tconst breakdown = firstMapped(q.dimensions, DIMENSION_SQL)\n\t\t\tconst goalBreakdown = breakdown?.dimension === 'goal'\n\t\t\tconst hint = goalHint(q)\n\t\t\tconst empty = goalBreakdown\n\t\t\t\t? emptyGoalBreakdown({ provider: 'posthog', fetchedAt, hint })\n\t\t\t\t: null\n\t\t\tif (empty) {\n\t\t\t\treturn empty\n\t\t\t}\n\t\t\t// These reads scan every event: a `$pageview` WHERE beside an `event = 'x'` filter would\n\t\t\t// contradict itself and zero every metric, so they switch to conditional aggregation.\n\t\t\tconst scanAllEvents =\n\t\t\t\tq.metrics.includes('events') ||\n\t\t\t\tq.metrics.includes('conversions') ||\n\t\t\t\tbreakdown?.dimension === 'event' ||\n\t\t\t\tgoalBreakdown ||\n\t\t\t\t(q.filters ?? []).some((f) => f.dimension === 'event')\n\t\t\tconst slugs = hintSlugs(hint)\n\t\t\tconst eventInHint = slugs ? `event IN (${slugs.map(sqlString).join(', ')})` : undefined\n\t\t\t// Counting the goals conditionally, rather than restricting the WHERE, keeps the\n\t\t\t// site metrics of a read that asks for both site-wide.\n\t\t\tconst metricSql: Partial<Record<MetricKey, string>> = {\n\t\t\t\t...(goalBreakdown ? METRIC_SQL_GOAL : scanAllEvents ? METRIC_SQL_ALL : METRIC_SQL_PAGEVIEW),\n\t\t\t\t...(eventInHint ? { conversions: `countIf(${eventInHint})` } : {}),\n\t\t\t}\n\t\t\tconst exprs = providerMetricKeys(q.metrics, metricSql)\n\t\t\tconst unresolved = q.metrics.includes('conversions') && hintFailed(hint)\n\t\t\tconst meta: AnalyticsResult['meta'] = {\n\t\t\t\tprovider: 'posthog',\n\t\t\t\tfetchedAt,\n\t\t\t\t...(unresolved ? { goalsUnresolved: true as const } : {}),\n\t\t\t}\n\n\t\t\tconst where = [\n\t\t\t\t...(scanAllEvents ? [] : [\"event = '$pageview'\"]),\n\t\t\t\t`timestamp >= ${utcDateTime(q.dateRange.start)}`,\n\t\t\t\t`timestamp <= ${utcDateTime(q.dateRange.end)}`,\n\t\t\t]\n\t\t\t// Only the goal breakdown narrows the scan itself: its rows are the goals and\n\t\t\t// nothing else.\n\t\t\tif (goalBreakdown && eventInHint) {\n\t\t\t\twhere.push(eventInHint)\n\t\t\t}\n\t\t\tif (q.path) {\n\t\t\t\twhere.push(`properties.$pathname = ${sqlString(q.path)}`)\n\t\t\t}\n\t\t\tif (q.hostname) {\n\t\t\t\twhere.push(`properties.$host = ${sqlString(q.hostname)}`)\n\t\t\t}\n\t\t\tif (config.scopeProperty && q.scope !== undefined) {\n\t\t\t\t// Bracket property access with escaped literals: neither the configured\n\t\t\t\t// property name nor the scope value can break out of the HogQL string.\n\t\t\t\twhere.push(`properties[${sqlString(config.scopeProperty)}] = ${sqlString(q.scope)}`)\n\t\t\t}\n\t\t\tfor (const { filter, field } of declaredFilters(capabilities, q.filters, DIMENSION_SQL)) {\n\t\t\t\twhere.push(FILTER_SQL[filter.operator](field, filter.value))\n\t\t\t}\n\t\t\tconst columns = exprs.map((expr, i) => `${expr} AS m${i}`).join(', ')\n\t\t\tconst from = `FROM events WHERE ${where.join(' AND ')}`\n\n\t\t\tconst runSql = (sql: string): Promise<PosthogQueryResponse> =>\n\t\t\t\tupstreamJson<PosthogQueryResponse>(ctx, `${host}/api/projects/${config.projectId}/query/`, {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders: { authorization: `Bearer ${config.apiKey}` },\n\t\t\t\t\tbody: { query: { kind: 'HogQLQuery', query: sql } },\n\t\t\t\t\tprovider: 'posthog',\n\t\t\t\t\tfetch: config.fetch,\n\t\t\t\t})\n\n\t\t\t/** A result row's metrics, its metric columns starting at `offset`. */\n\t\t\tconst readRow = (row: unknown[], offset: number): MetricValues => {\n\t\t\t\tconst out: MetricValues = {}\n\t\t\t\tfor (const metric of q.metrics) {\n\t\t\t\t\tconst expr = metricSql[metric]\n\t\t\t\t\tif (expr !== undefined) {\n\t\t\t\t\t\tout[metric] = vendorReading(metric, row[offset + exprs.indexOf(expr)])\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn out\n\t\t\t}\n\n\t\t\tconst fetchTotals = async (): Promise<MetricValues> => {\n\t\t\t\tconst data = await runSql(`SELECT ${columns} ${from}`)\n\t\t\t\tconst row = data.results[0]\n\t\t\t\treturn row ? readRow(row, 0) : {}\n\t\t\t}\n\n\t\t\tconst unit =\n\t\t\t\t!breakdown && (q.granularity === 'day' || q.granularity === 'hour')\n\t\t\t\t\t? q.granularity\n\t\t\t\t\t: undefined\n\t\t\tif (unit) {\n\t\t\t\tconst { fn, isoOf } = SERIES_BUCKETS[unit]\n\t\t\t\t// Without a timezone argument HogQL buckets in the project's zone, so the reporting zone\n\t\t\t\t// (UTC included) is always passed; the window literals stay UTC instants, already aligned.\n\t\t\t\tconst bucket = `${fn}(timestamp, ${sqlString(q.timezone ?? DEFAULT_TIMEZONE)})`\n\t\t\t\tconst [series, totals] = await Promise.all([\n\t\t\t\t\trunSql(\n\t\t\t\t\t\t`SELECT ${bucket} AS ${unit}, ${columns} ${from} GROUP BY ${unit} ORDER BY ${unit}`\n\t\t\t\t\t),\n\t\t\t\t\tfetchTotals(),\n\t\t\t\t])\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const row of series.results) {\n\t\t\t\t\tconst timestamp = isoOf(String(row[0] ?? ''))\n\t\t\t\t\tif (timestamp) {\n\t\t\t\t\t\trows.push({ timestamp, metrics: readRow(row, 1) })\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { rows, totals, meta }\n\t\t\t}\n\n\t\t\tif (breakdown) {\n\t\t\t\tconst data = await runSql(\n\t\t\t\t\t`SELECT ${breakdown.field} AS dim, ${columns} ${from} GROUP BY dim ORDER BY m0 DESC LIMIT ${q.limit ?? 100}`\n\t\t\t\t)\n\t\t\t\tconst rows: AnalyticsRow[] = data.results.map((row) => ({\n\t\t\t\t\tdimensions: { [breakdown.dimension]: String(row[0] ?? '') },\n\t\t\t\t\tmetrics: readRow(row, 1),\n\t\t\t\t}))\n\t\t\t\treturn { rows, totals: undefined, meta }\n\t\t\t}\n\n\t\t\tconst totals = await fetchTotals()\n\t\t\treturn { rows: [{ metrics: totals }], totals, meta }\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;;AAyEA,MAAM,WAAW;AAEjB,MAAM,iBAAiB,WAAuC;CAC7D,IAAI,OAAO,QACV,OAAO,OAAO;CAEf,OAAO,OAAO,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AAE,YAAA,KAA4B,EAAE;IAC7E,MAAM,CAAC,QAAQ,UAAU,MAAM,QAAQ,IAAI,CAC1C,OACC,UAAU,OAAO,MAAM,KAAK,IAAI,QAAQ,GAAG,KAAK,YAAY,KAAK,YAAY,MAC9E,GACA,YAAY,CACb,CAAC;IACD,MAAM,OAAuB,CAAC;IAC9B,KAAK,MAAM,OAAO,OAAO,SAAS;KACjC,MAAM,YAAY,MAAM,OAAO,IAAI,MAAM,EAAE,CAAC;KAC5C,IAAI,WACH,KAAK,KAAK;MAAE;MAAW,SAAS,QAAQ,KAAK,CAAC;KAAE,CAAC;IAEnD;IACA,OAAO;KAAE;KAAM;KAAQ;IAAK;GAC7B;GAEA,IAAI,WAQH,OAAO;IAAE,OAJoB,MAHV,OAClB,UAAU,UAAU,MAAM,WAAW,QAAQ,GAAG,KAAK,uCAAuC,EAAE,SAAS,KACxG,GACkC,QAAQ,KAAK,SAAS;KACvD,YAAY,GAAG,UAAU,YAAY,OAAO,IAAI,MAAM,EAAE,EAAE;KAC1D,SAAS,QAAQ,KAAK,CAAC;IACxB,EACY;IAAG,QAAQ,KAAA;IAAW;GAAK;GAGxC,MAAM,SAAS,MAAM,YAAY;GACjC,OAAO;IAAE,MAAM,CAAC,EAAE,SAAS,OAAO,CAAC;IAAG;IAAQ;GAAK;EACpD;CACD;AACD"}
@@ -1,8 +1,14 @@
1
1
  import { FetchLike } from "../../core/fetch.js";
2
2
  import { AnalyticsAdapter } from "../../core/contract.js";
3
+ import { AdapterLabelOption } from "../../core/sourceLabel.js";
3
4
 
4
5
  //#region src/adapters/umami/umami.d.ts
5
6
  interface UmamiConfig {
7
+ /**
8
+ * The source's name in pickers and listings: a string, a map by admin language (read like
9
+ * `view.navLabel`), or a function naming it per reader and scope. Default `'Umami'`.
10
+ */
11
+ label?: AdapterLabelOption;
6
12
  websiteId: string;
7
13
  /** Umami Cloud API key (sent as x-umami-api-key). */
8
14
  apiKey?: string;
@@ -1,4 +1,5 @@
1
1
  import { DIMENSION_KEYS } from "../../core/contract.js";
2
+ import { adapterLabel } from "../../core/sourceLabel.js";
2
3
  import { filterableDimensions } from "../../core/capabilities.js";
3
4
  import { emptyGoalBreakdown, goalHint, hintFailed, hintSlugs } from "../goalRead.js";
4
5
  import { declaredFilters, everyOperatorOn, firstMapped, mappedKeys } from "../mapping.js";
@@ -261,7 +262,7 @@ function umami(config) {
261
262
  const authHeaders = () => config.apiKey ? { "x-umami-api-key": config.apiKey } : config.token ? { authorization: `Bearer ${config.token}` } : {};
262
263
  return {
263
264
  id: "umami",
264
- label: "Umami",
265
+ ...adapterLabel(config.label, "Umami", "umami({ label })"),
265
266
  capabilities,
266
267
  capture: buildCapture(config, endpoints),
267
268
  isConfigured: () => Boolean(config.websiteId && (config.apiKey || config.token)),
@@ -1 +1 @@
1
- {"version":3,"file":"umami.js","names":[],"sources":["../../../src/adapters/umami/umami.ts"],"sourcesContent":["import { filterableDimensions } from '../../core/capabilities'\nimport type { CaptureSupport } from '../../core/capture'\nimport {\n\ttype AdapterContext,\n\ttype AnalyticsAdapter,\n\ttype AnalyticsCapabilities,\n\ttype AnalyticsFilter,\n\ttype AnalyticsQuery,\n\ttype AnalyticsResult,\n\ttype AnalyticsRow,\n\tDIMENSION_KEYS,\n\ttype DimensionKey,\n\ttype FilterOperator,\n\ttype MetricKey,\n\ttype MetricReach,\n\ttype MetricValues,\n} from '../../core/contract'\nimport type { FetchLike } from '../../core/fetch'\nimport { DEFAULT_TIMEZONE } from '../../timeframe/tz'\nimport { emptyGoalBreakdown, goalHint, hintFailed, hintSlugs } from '../goalRead'\nimport { hostnameOf, withoutTrailingSlash } from '../http/baseUrl'\nimport { declaredFilters, everyOperatorOn, firstMapped, mappedKeys } from '../mapping'\nimport { readTime } from '../readTime'\nimport { dayIso } from '../series'\nimport { upstreamJson } from '../upstream'\n\nexport interface UmamiConfig {\n\twebsiteId: string\n\t/** Umami Cloud API key (sent as x-umami-api-key). */\n\tapiKey?: string\n\t/** Self-hosted bearer token (from POST /api/auth/login). */\n\ttoken?: string\n\t/**\n\t * The self-hosted Umami app's address, base path included (`https://example.com/umami`), whose\n\t * API is read under `/api`; a trailing `/api` is dropped. Unset, or Umami Cloud's, reads the cloud.\n\t */\n\thost?: string\n\t/** Maximum days of historical data. Defaults to 730. Pass null to disable clamping. */\n\tmaxLookbackDays?: number | null\n\t/** The fetch reads and the capture proxy reach Umami with. Unset, the global fetch. */\n\tfetch?: FetchLike\n}\n\n/** Where one Umami install answers: its Stats API, its tracker script, and its event sink. */\nexport interface UmamiEndpoints {\n\tapi: string\n\tscript: string\n\tsend: string\n}\n\nconst CLOUD: UmamiEndpoints = {\n\tapi: 'https://api.umami.is/v1',\n\tscript: 'https://cloud.umami.is/script.js',\n\tsend: 'https://gateway.umami.is/api/send',\n}\n\n/** Umami Cloud's own hosts, which mean the cloud rather than an app address under them. */\nconst CLOUD_HOSTNAMES: ReadonlySet<string> = new Set(['api.umami.is', 'cloud.umami.is'])\n\n/**\n * The endpoints `host` names: the cloud for nothing or for Umami Cloud's own address, otherwise\n * the app address (trailing slashes and a trailing `/api` dropped) with the API under `/api`.\n */\nexport const umamiEndpoints = (host: string | undefined): UmamiEndpoints => {\n\tconst trimmed = withoutTrailingSlash(host?.trim() ?? '')\n\tconst address = withoutTrailingSlash(trimmed.replace(/\\/api$/, ''))\n\tif (address === '' || CLOUD_HOSTNAMES.has(hostnameOf(address))) {\n\t\treturn CLOUD\n\t}\n\treturn { api: `${address}/api`, script: `${address}/script.js`, send: `${address}/api/send` }\n}\n\nfunction buildCapture(config: UmamiConfig, endpoints: UmamiEndpoints): CaptureSupport {\n\treturn {\n\t\tproxy: {\n\t\t\troutes: [\n\t\t\t\t{ source: '/script.js', upstream: endpoints.script, kind: 'script' },\n\t\t\t\t{ source: '/api/send', upstream: endpoints.send, kind: 'data' },\n\t\t\t],\n\t\t\t...(config.fetch ? { fetch: config.fetch } : {}),\n\t\t},\n\t\tsnippet: ({ path }) => ({\n\t\t\tscripts: [\n\t\t\t\t{\n\t\t\t\t\tsrc: `${path}/script.js`,\n\t\t\t\t\tdefer: true,\n\t\t\t\t\tattrs: { 'data-website-id': config.websiteId, 'data-host-url': path },\n\t\t\t\t},\n\t\t\t],\n\t\t}),\n\t\tclient: { kind: 'umami' },\n\t}\n}\n\nconst umamiMetrics: ReadonlySet<MetricKey> = new Set<MetricKey>([\n\t'pageviews',\n\t'visitors',\n\t'visits',\n\t'sessions',\n\t'bounceRate',\n\t'visitDuration',\n\t'conversions',\n])\n\ninterface UmamiDimension {\n\t/** Umami filter param, which doubles as the /metrics `type` value. */\n\tparam: string\n\t/** The one metric /metrics reports for this type: y is nothing else. */\n\tmetric: MetricKey\n}\n\n// y is count(distinct session_id) on every pageview and session type, and event\n// occurrences on `type=event`.\nconst DIMENSION_MAP: Partial<Record<DimensionKey, UmamiDimension>> = {\n\tpage: { param: 'path', metric: 'visitors' },\n\treferrer: { param: 'referrer', metric: 'visitors' },\n\tbrowser: { param: 'browser', metric: 'visitors' },\n\tos: { param: 'os', metric: 'visitors' },\n\tdevice: { param: 'device', metric: 'visitors' },\n\tcountry: { param: 'country', metric: 'visitors' },\n\tregion: { param: 'region', metric: 'visitors' },\n\tcity: { param: 'city', metric: 'visitors' },\n\tlanguage: { param: 'language', metric: 'visitors' },\n\tevent: { param: 'event', metric: 'events' },\n\tutmSource: { param: 'utmSource', metric: 'visitors' },\n\tutmMedium: { param: 'utmMedium', metric: 'visitors' },\n\tutmCampaign: { param: 'utmCampaign', metric: 'visitors' },\n\tutmContent: { param: 'utmContent', metric: 'visitors' },\n\tutmTerm: { param: 'utmTerm', metric: 'visitors' },\n}\n\n/**\n * Goals are custom events, so a goal's slug must equal the captured event's name. Only this shape\n * answers `conversions`: other breakdowns and the daily series report none.\n */\nconst GOAL_DIMENSION: UmamiDimension = { param: 'event', metric: 'conversions' }\n\n/**\n * The /metrics types a read groups by. `channel` is Umami's acquisition classification, a type\n * with no filter param, which is why it sits outside {@link DIMENSION_MAP}.\n */\nconst BREAKDOWNS: Partial<Record<DimensionKey, UmamiDimension>> = {\n\t...DIMENSION_MAP,\n\tchannel: { param: 'channel', metric: 'visitors' },\n}\n\n/**\n * Umami's `re.` is `~*`: a case-insensitive partial match, so an unanchored pattern hits\n * anywhere in the value. `c.` is `ilike`, also case-insensitive.\n */\nconst OPERATOR_PREFIX: Record<FilterOperator, string> = {\n\teq: 'eq.',\n\tcontains: 'c.',\n\tmatches: 're.',\n}\n\n/** A filter as its param value, always prefixed so a value starting like an operator stays literal. */\nconst paramValue = (filter: AnalyticsFilter): string =>\n\t`${OPERATOR_PREFIX[filter.operator]}${filter.value}`\n\n/**\n * Every filter param takes equals, contains and a regular expression\n * (https://docs.umami.is/docs/filters), written as the `eq.`, `c.` and `re.` prefixes.\n */\nconst umamiFilters = everyOperatorOn(mappedKeys(DIMENSION_KEYS, DIMENSION_MAP))\n\n// `event` filters but does not group, since /stats reports no `events` number to declare;\n// `goal` and `channel` are the reverse, /metrics types with no matching filter param.\nconst umamiDimensions: ReadonlySet<DimensionKey> = new Set<DimensionKey>([\n\t...filterableDimensions({ filters: umamiFilters }).filter((dimension) => dimension !== 'event'),\n\t'goal',\n\t'channel',\n])\n\n/**\n * /stats answers site totals and /metrics one count per row, so other metrics are site-wide only.\n * Nothing reports time per pageview, so no time on page is offered.\n */\nconst siteOnly: MetricReach = { dimensions: [] }\nconst umamiReach: Partial<Record<MetricKey, MetricReach>> = {\n\tpageviews: siteOnly,\n\tvisits: siteOnly,\n\tsessions: siteOnly,\n\tbounceRate: siteOnly,\n\tvisitDuration: siteOnly,\n\tvisitors: { dimensions: [...umamiDimensions].filter((dimension) => dimension !== 'goal') },\n\tconversions: { dimensions: ['goal'] },\n}\n\ninterface UmamiParams {\n\tsearch: URLSearchParams\n\t/** Filters a one-value-per-param request could not carry. */\n\tunapplied: AnalyticsFilter[]\n\t/** Two `eq` values on one param: the AND matches nothing, so the read serves no rows. */\n\tempty: boolean\n}\n\n/**\n * The read's range and filters as query params, one value per param: clashing `eq` values match\n * nothing (an empty read), and other clashes keep the first, the page path always winning.\n */\nconst paramsFor = (q: AnalyticsQuery): UmamiParams => {\n\tconst search = new URLSearchParams({\n\t\tstartAt: String(q.dateRange.start.getTime()),\n\t\tendAt: String(q.dateRange.end.getTime()),\n\t})\n\tconst filters = declaredFilters({ filters: umamiFilters }, q.filters, DIMENSION_MAP)\n\tconst eqValues = new Map<string, string>()\n\tfor (const { filter, field } of filters) {\n\t\tif (filter.operator !== 'eq') {\n\t\t\tcontinue\n\t\t}\n\t\tconst held = eqValues.get(field.param)\n\t\tif (held !== undefined && held !== filter.value) {\n\t\t\treturn { search, unapplied: [], empty: true }\n\t\t}\n\t\teqValues.set(field.param, filter.value)\n\t}\n\tconst unapplied: AnalyticsFilter[] = []\n\tconst held = new Map<string, { value: string; filter: AnalyticsFilter }>()\n\tfor (const { filter, field } of filters) {\n\t\t// Umami splits an `eq.` value on commas with no escape, which would widen the question.\n\t\tif (filter.operator === 'eq' && filter.value.includes(',')) {\n\t\t\tunapplied.push(filter)\n\t\t\tcontinue\n\t\t}\n\t\tconst value = paramValue(filter)\n\t\tconst first = held.get(field.param)\n\t\tif (first === undefined) {\n\t\t\theld.set(field.param, { value, filter })\n\t\t\tsearch.set(field.param, value)\n\t\t} else if (first.value !== value) {\n\t\t\tunapplied.push(filter)\n\t\t}\n\t}\n\tif (q.path) {\n\t\tconst value = `eq.${q.path}`\n\t\tconst first = held.get('path')\n\t\tif (first !== undefined && first.value !== value) {\n\t\t\tunapplied.push(first.filter)\n\t\t}\n\t\tsearch.set('path', value)\n\t}\n\treturn { search, unapplied, empty: false }\n}\n\n/** `values` narrowed to the metrics a read asked for. */\nconst requested = (metrics: readonly MetricKey[], values: MetricValues): MetricValues => {\n\tconst out: MetricValues = {}\n\tfor (const metric of metrics) {\n\t\tif (values[metric] !== undefined) {\n\t\t\tout[metric] = values[metric]\n\t\t}\n\t}\n\treturn out\n}\n\ninterface UmamiPoint {\n\tx: string\n\ty: number\n}\n\ninterface UmamiSeries {\n\tpageviews: UmamiPoint[]\n\tsessions: UmamiPoint[]\n}\n\ninterface UmamiStats {\n\tpageviews: number\n\tvisitors: number\n\tvisits: number\n\tbounces: number\n\ttotaltime: number\n}\n\n/**\n * The Umami 3.x adapter, cloud and self-hosted. Filter values always carry an explicit `eq.` prefix,\n * so a value starting like an operator is never read as one.\n */\nexport function umami(config: UmamiConfig): AnalyticsAdapter {\n\tconst endpoints = umamiEndpoints(config.host)\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 730\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\trealtime: false,\n\t\tminGranularity: 'day',\n\t\tmaxLookbackDays,\n\t\tmetrics: umamiMetrics,\n\t\tdimensions: umamiDimensions,\n\t\tmetricReach: umamiReach,\n\t\tfilters: umamiFilters,\n\t\tsemantics: { visitors: 'distinct', sessions: 'provider' },\n\t\trateLimit: null,\n\t\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n\t\tupstreamAware: true,\n\t}\n\t// Cloud authenticates with x-umami-api-key; self-hosted with a bearer token.\n\tconst authHeaders = (): Record<string, string> =>\n\t\tconfig.apiKey\n\t\t\t? { 'x-umami-api-key': config.apiKey }\n\t\t\t: config.token\n\t\t\t\t? { authorization: `Bearer ${config.token}` }\n\t\t\t\t: {}\n\n\treturn {\n\t\tid: 'umami',\n\t\tlabel: 'Umami',\n\t\tcapabilities,\n\t\tcapture: buildCapture(config, endpoints),\n\t\tisConfigured: () => Boolean(config.websiteId && (config.apiKey || config.token)),\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = readTime(ctx)\n\t\t\tconst headers = authHeaders()\n\t\t\tconst goalBreakdown = (q.dimensions ?? []).includes('goal')\n\t\t\tconst hint = goalHint(q)\n\t\t\tconst slugs = hintSlugs(hint)\n\t\t\tconst plan = paramsFor(q)\n\t\t\tconst breakdown = firstMapped(q.dimensions, BREAKDOWNS)\n\t\t\t// Umami splits an `eq.` list on commas with no escape, so a slug carrying one is left out\n\t\t\t// and reported rather than widening the read to every event.\n\t\t\tconst askable = (slugs ?? []).filter((slug) => !slug.includes(','))\n\t\t\tconst unaskable = (slugs ?? []).filter((slug) => slug.includes(','))\n\t\t\tconst eventValue = `eq.${askable.join(',')}`\n\t\t\t// Goal rows come from the `event` param, so on a read that fetches them the hint wins and a\n\t\t\t// caller's own event filter is reported unapplied; any other breakdown sends it as written.\n\t\t\tconst eventFilter = (q.filters ?? []).find((f) => f.dimension === 'event')\n\t\t\tconst readsGoals =\n\t\t\t\tgoalBreakdown || (!breakdown && q.metrics.includes('conversions') && slugs !== null)\n\t\t\tconst unapplied: AnalyticsFilter[] = [\n\t\t\t\t...plan.unapplied,\n\t\t\t\t...unaskable.map(\n\t\t\t\t\t(slug): AnalyticsFilter => ({ dimension: 'goal', operator: 'eq', value: slug })\n\t\t\t\t),\n\t\t\t\t...(readsGoals && eventFilter && paramValue(eventFilter) !== eventValue\n\t\t\t\t\t? [eventFilter]\n\t\t\t\t\t: []),\n\t\t\t]\n\t\t\tconst unresolved = q.metrics.includes('conversions') && hintFailed(hint)\n\t\t\tconst unappliedMeta = unapplied.length > 0 ? { unappliedFilters: unapplied } : {}\n\t\t\tconst empty = goalBreakdown\n\t\t\t\t? emptyGoalBreakdown({ provider: 'umami', fetchedAt, hint, meta: unappliedMeta })\n\t\t\t\t: null\n\t\t\tif (empty) {\n\t\t\t\treturn empty\n\t\t\t}\n\t\t\tconst meta: AnalyticsResult['meta'] = {\n\t\t\t\tprovider: 'umami',\n\t\t\t\tfetchedAt,\n\t\t\t\t...unappliedMeta,\n\t\t\t\t...(unresolved ? { goalsUnresolved: true as const } : {}),\n\t\t\t}\n\t\t\t// Totals are left undefined rather than zeroed, the same as every other number this\n\t\t\t// adapter cannot report, so the display layer shows \"no data\" instead of a real 0.\n\t\t\tif (plan.empty) {\n\t\t\t\treturn { rows: [], totals: undefined, meta }\n\t\t\t}\n\n\t\t\t/** The read's params plus `extra`, on a fresh copy so no request sees another's. */\n\t\t\tconst search = (extra: Record<string, string> = {}): URLSearchParams => {\n\t\t\t\tconst params = new URLSearchParams(plan.search)\n\t\t\t\tfor (const [name, value] of Object.entries(extra)) {\n\t\t\t\t\tparams.set(name, value)\n\t\t\t\t}\n\t\t\t\treturn params\n\t\t\t}\n\t\t\tconst getJson = <T>(endpoint: string, params: URLSearchParams): Promise<T> =>\n\t\t\t\tupstreamJson<T>(\n\t\t\t\t\tctx,\n\t\t\t\t\t`${endpoints.api}/websites/${config.websiteId}/${endpoint}?${params.toString()}`,\n\t\t\t\t\t{ headers, provider: 'umami', fetch: config.fetch }\n\t\t\t\t)\n\n\t\t\t/**\n\t\t\t * The goal rows for the hint, narrowed to it again on the way back so nothing the API\n\t\t\t * did not restrict can arrive as a goal.\n\t\t\t */\n\t\t\tconst fetchGoalRows = async (): Promise<UmamiPoint[]> => {\n\t\t\t\tif (askable.length === 0) {\n\t\t\t\t\treturn []\n\t\t\t\t}\n\t\t\t\tconst data = await getJson<UmamiPoint[]>(\n\t\t\t\t\t'metrics',\n\t\t\t\t\tsearch({ type: GOAL_DIMENSION.param, [GOAL_DIMENSION.param]: eventValue })\n\t\t\t\t)\n\t\t\t\tconst wanted = new Set(askable)\n\t\t\t\treturn data.filter((row) => wanted.has(row.x))\n\t\t\t}\n\n\t\t\tif (goalBreakdown) {\n\t\t\t\tconst rows: AnalyticsRow[] = (await fetchGoalRows()).map((row) => ({\n\t\t\t\t\tdimensions: { goal: row.x },\n\t\t\t\t\tmetrics: { [GOAL_DIMENSION.metric]: row.y },\n\t\t\t\t}))\n\t\t\t\treturn { rows, totals: undefined, meta }\n\t\t\t}\n\n\t\t\tif (breakdown) {\n\t\t\t\tconst { dimension, field } = breakdown\n\t\t\t\tconst data = await getJson<UmamiPoint[]>('metrics', search({ type: field.param }))\n\t\t\t\t// /metrics reports one number per row, under the name it holds: a requested metric with no\n\t\t\t\t// per-row source is absent rather than labelled with a number it is not.\n\t\t\t\tconst rows: AnalyticsRow[] = data.map((row) => ({\n\t\t\t\t\tdimensions: { [dimension]: row.x },\n\t\t\t\t\tmetrics: { [field.metric]: row.y },\n\t\t\t\t}))\n\t\t\t\treturn { rows, totals: undefined, meta }\n\t\t\t}\n\n\t\t\tconst fetchTotals = async (): Promise<MetricValues> => {\n\t\t\t\t// Conversions have no place in /stats: their total is the goal rows summed.\n\t\t\t\tconst [stats, goalRows] = await Promise.all([\n\t\t\t\t\tgetJson<UmamiStats>('stats', search()),\n\t\t\t\t\tq.metrics.includes('conversions') && slugs ? fetchGoalRows() : undefined,\n\t\t\t\t])\n\t\t\t\treturn requested(q.metrics, {\n\t\t\t\t\t...(goalRows ? { conversions: goalRows.reduce((sum, row) => sum + row.y, 0) } : {}),\n\t\t\t\t\tpageviews: stats.pageviews,\n\t\t\t\t\tvisitors: stats.visitors,\n\t\t\t\t\tvisits: stats.visits,\n\t\t\t\t\tsessions: stats.visits,\n\t\t\t\t\t// Derived ratios read null (not zero) when there are no visits: a bounce rate of\n\t\t\t\t\t// nobody is no data, and a 0 would read as every visitor staying.\n\t\t\t\t\tbounceRate: stats.visits > 0 ? Math.round((stats.bounces / stats.visits) * 100) : null,\n\t\t\t\t\tvisitDuration:\n\t\t\t\t\t\tstats.visits > 0 ? Math.round((stats.totaltime / stats.visits) * 1000) : null,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\t// Umami's only series endpoint reports pageviews and sessions, so a trend on any other\n\t\t\t// metric keeps its /stats headline but an empty series.\n\t\t\tif (q.granularity === 'day') {\n\t\t\t\tconst [series, totals] = await Promise.all([\n\t\t\t\t\tgetJson<UmamiSeries>(\n\t\t\t\t\t\t'pageviews',\n\t\t\t\t\t\tsearch({ unit: 'day', timezone: q.timezone ?? DEFAULT_TIMEZONE })\n\t\t\t\t\t),\n\t\t\t\t\tfetchTotals(),\n\t\t\t\t])\n\t\t\t\tconst sessionsByDay = new Map(series.sessions.map((point) => [point.x, point.y]))\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const point of series.pageviews) {\n\t\t\t\t\tconst timestamp = dayIso(point.x)\n\t\t\t\t\tif (!timestamp) {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tconst sessions = sessionsByDay.get(point.x) ?? 0\n\t\t\t\t\trows.push({\n\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t\tmetrics: requested(q.metrics, { pageviews: point.y, visits: sessions, sessions }),\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\treturn { rows, totals, meta }\n\t\t\t}\n\n\t\t\tconst totals = await fetchTotals()\n\t\t\treturn { rows: [{ metrics: totals }], totals, meta }\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;AAkDA,MAAM,QAAwB;CAC7B,KAAK;CACL,QAAQ;CACR,MAAM;AACP;;AAGA,MAAM,kBAAuC,IAAI,IAAI,CAAC,gBAAgB,gBAAgB,CAAC;;;;;AAMvF,MAAa,kBAAkB,SAA6C;CAE3E,MAAM,UAAU,qBADA,qBAAqB,MAAM,KAAK,KAAK,EACV,EAAE,QAAQ,UAAU,EAAE,CAAC;CAClE,IAAI,YAAY,MAAM,gBAAgB,IAAI,WAAW,OAAO,CAAC,GAC5D,OAAO;CAER,OAAO;EAAE,KAAK,GAAG,QAAQ;EAAO,QAAQ,GAAG,QAAQ;EAAa,MAAM,GAAG,QAAQ;CAAW;AAC7F;AAEA,SAAS,aAAa,QAAqB,WAA2C;CACrF,OAAO;EACN,OAAO;GACN,QAAQ,CACP;IAAE,QAAQ;IAAc,UAAU,UAAU;IAAQ,MAAM;GAAS,GACnE;IAAE,QAAQ;IAAa,UAAU,UAAU;IAAM,MAAM;GAAO,CAC/D;GACA,GAAI,OAAO,QAAQ,EAAE,OAAO,OAAO,MAAM,IAAI,CAAC;EAC/C;EACA,UAAU,EAAE,YAAY,EACvB,SAAS,CACR;GACC,KAAK,GAAG,KAAK;GACb,OAAO;GACP,OAAO;IAAE,mBAAmB,OAAO;IA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,GAAG,CAAC,EAAE,IAAI,CAAC;KACjF,WAAW,MAAM;KACjB,UAAU,MAAM;KAChB,QAAQ,MAAM;KACd,UAAU,MAAM;KAGhB,YAAY,MAAM,SAAS,IAAI,KAAK,MAAO,MAAM,UAAU,MAAM,SAAU,GAAG,IAAI;KAClF,eACC,MAAM,SAAS,IAAI,KAAK,MAAO,MAAM,YAAY,MAAM,SAAU,GAAI,IAAI;IAC3E,CAAC;GACF;GAIA,IAAI,EAAE,gBAAgB,OAAO;IAC5B,MAAM,CAAC,QAAQ,UAAU,MAAM,QAAQ,IAAI,CAC1C,QACC,aACA,OAAO;KAAE,MAAM;KAAO,UAAU,EAAE,YAAA;IAA6B,CAAC,CACjE,GACA,YAAY,CACb,CAAC;IACD,MAAM,gBAAgB,IAAI,IAAI,OAAO,SAAS,KAAK,UAAU,CAAC,MAAM,GAAG,MAAM,CAAC,CAAC,CAAC;IAChF,MAAM,OAAuB,CAAC;IAC9B,KAAK,MAAM,SAAS,OAAO,WAAW;KACrC,MAAM,YAAY,OAAO,MAAM,CAAC;KAChC,IAAI,CAAC,WACJ;KAED,MAAM,WAAW,cAAc,IAAI,MAAM,CAAC,KAAK;KAC/C,KAAK,KAAK;MACT;MACA,SAAS,UAAU,EAAE,SAAS;OAAE,WAAW,MAAM;OAAG,QAAQ;OAAU;MAAS,CAAC;KACjF,CAAC;IACF;IACA,OAAO;KAAE;KAAM;KAAQ;IAAK;GAC7B;GAEA,MAAM,SAAS,MAAM,YAAY;GACjC,OAAO;IAAE,MAAM,CAAC,EAAE,SAAS,OAAO,CAAC;IAAG;IAAQ;GAAK;EACpD;CACD;AACD"}
1
+ {"version":3,"file":"umami.js","names":[],"sources":["../../../src/adapters/umami/umami.ts"],"sourcesContent":["import { filterableDimensions } from '../../core/capabilities'\nimport type { CaptureSupport } from '../../core/capture'\nimport {\n\ttype AdapterContext,\n\ttype AnalyticsAdapter,\n\ttype AnalyticsCapabilities,\n\ttype AnalyticsFilter,\n\ttype AnalyticsQuery,\n\ttype AnalyticsResult,\n\ttype AnalyticsRow,\n\tDIMENSION_KEYS,\n\ttype DimensionKey,\n\ttype FilterOperator,\n\ttype MetricKey,\n\ttype MetricReach,\n\ttype MetricValues,\n} from '../../core/contract'\nimport type { FetchLike } from '../../core/fetch'\nimport { type AdapterLabelOption, adapterLabel } from '../../core/sourceLabel'\nimport { DEFAULT_TIMEZONE } from '../../timeframe/tz'\nimport { emptyGoalBreakdown, goalHint, hintFailed, hintSlugs } from '../goalRead'\nimport { hostnameOf, withoutTrailingSlash } from '../http/baseUrl'\nimport { declaredFilters, everyOperatorOn, firstMapped, mappedKeys } from '../mapping'\nimport { readTime } from '../readTime'\nimport { dayIso } from '../series'\nimport { upstreamJson } from '../upstream'\n\nexport interface UmamiConfig {\n\t/**\n\t * The source's name in pickers and listings: a string, a map by admin language (read like\n\t * `view.navLabel`), or a function naming it per reader and scope. Default `'Umami'`.\n\t */\n\tlabel?: AdapterLabelOption\n\twebsiteId: string\n\t/** Umami Cloud API key (sent as x-umami-api-key). */\n\tapiKey?: string\n\t/** Self-hosted bearer token (from POST /api/auth/login). */\n\ttoken?: string\n\t/**\n\t * The self-hosted Umami app's address, base path included (`https://example.com/umami`), whose\n\t * API is read under `/api`; a trailing `/api` is dropped. Unset, or Umami Cloud's, reads the cloud.\n\t */\n\thost?: string\n\t/** Maximum days of historical data. Defaults to 730. Pass null to disable clamping. */\n\tmaxLookbackDays?: number | null\n\t/** The fetch reads and the capture proxy reach Umami with. Unset, the global fetch. */\n\tfetch?: FetchLike\n}\n\n/** Where one Umami install answers: its Stats API, its tracker script, and its event sink. */\nexport interface UmamiEndpoints {\n\tapi: string\n\tscript: string\n\tsend: string\n}\n\nconst CLOUD: UmamiEndpoints = {\n\tapi: 'https://api.umami.is/v1',\n\tscript: 'https://cloud.umami.is/script.js',\n\tsend: 'https://gateway.umami.is/api/send',\n}\n\n/** Umami Cloud's own hosts, which mean the cloud rather than an app address under them. */\nconst CLOUD_HOSTNAMES: ReadonlySet<string> = new Set(['api.umami.is', 'cloud.umami.is'])\n\n/**\n * The endpoints `host` names: the cloud for nothing or for Umami Cloud's own address, otherwise\n * the app address (trailing slashes and a trailing `/api` dropped) with the API under `/api`.\n */\nexport const umamiEndpoints = (host: string | undefined): UmamiEndpoints => {\n\tconst trimmed = withoutTrailingSlash(host?.trim() ?? '')\n\tconst address = withoutTrailingSlash(trimmed.replace(/\\/api$/, ''))\n\tif (address === '' || CLOUD_HOSTNAMES.has(hostnameOf(address))) {\n\t\treturn CLOUD\n\t}\n\treturn { api: `${address}/api`, script: `${address}/script.js`, send: `${address}/api/send` }\n}\n\nfunction buildCapture(config: UmamiConfig, endpoints: UmamiEndpoints): CaptureSupport {\n\treturn {\n\t\tproxy: {\n\t\t\troutes: [\n\t\t\t\t{ source: '/script.js', upstream: endpoints.script, kind: 'script' },\n\t\t\t\t{ source: '/api/send', upstream: endpoints.send, kind: 'data' },\n\t\t\t],\n\t\t\t...(config.fetch ? { fetch: config.fetch } : {}),\n\t\t},\n\t\tsnippet: ({ path }) => ({\n\t\t\tscripts: [\n\t\t\t\t{\n\t\t\t\t\tsrc: `${path}/script.js`,\n\t\t\t\t\tdefer: true,\n\t\t\t\t\tattrs: { 'data-website-id': config.websiteId, 'data-host-url': path },\n\t\t\t\t},\n\t\t\t],\n\t\t}),\n\t\tclient: { kind: 'umami' },\n\t}\n}\n\nconst umamiMetrics: ReadonlySet<MetricKey> = new Set<MetricKey>([\n\t'pageviews',\n\t'visitors',\n\t'visits',\n\t'sessions',\n\t'bounceRate',\n\t'visitDuration',\n\t'conversions',\n])\n\ninterface UmamiDimension {\n\t/** Umami filter param, which doubles as the /metrics `type` value. */\n\tparam: string\n\t/** The one metric /metrics reports for this type: y is nothing else. */\n\tmetric: MetricKey\n}\n\n// y is count(distinct session_id) on every pageview and session type, and event\n// occurrences on `type=event`.\nconst DIMENSION_MAP: Partial<Record<DimensionKey, UmamiDimension>> = {\n\tpage: { param: 'path', metric: 'visitors' },\n\treferrer: { param: 'referrer', metric: 'visitors' },\n\tbrowser: { param: 'browser', metric: 'visitors' },\n\tos: { param: 'os', metric: 'visitors' },\n\tdevice: { param: 'device', metric: 'visitors' },\n\tcountry: { param: 'country', metric: 'visitors' },\n\tregion: { param: 'region', metric: 'visitors' },\n\tcity: { param: 'city', metric: 'visitors' },\n\tlanguage: { param: 'language', metric: 'visitors' },\n\tevent: { param: 'event', metric: 'events' },\n\tutmSource: { param: 'utmSource', metric: 'visitors' },\n\tutmMedium: { param: 'utmMedium', metric: 'visitors' },\n\tutmCampaign: { param: 'utmCampaign', metric: 'visitors' },\n\tutmContent: { param: 'utmContent', metric: 'visitors' },\n\tutmTerm: { param: 'utmTerm', metric: 'visitors' },\n}\n\n/**\n * Goals are custom events, so a goal's slug must equal the captured event's name. Only this shape\n * answers `conversions`: other breakdowns and the daily series report none.\n */\nconst GOAL_DIMENSION: UmamiDimension = { param: 'event', metric: 'conversions' }\n\n/**\n * The /metrics types a read groups by. `channel` is Umami's acquisition classification, a type\n * with no filter param, which is why it sits outside {@link DIMENSION_MAP}.\n */\nconst BREAKDOWNS: Partial<Record<DimensionKey, UmamiDimension>> = {\n\t...DIMENSION_MAP,\n\tchannel: { param: 'channel', metric: 'visitors' },\n}\n\n/**\n * Umami's `re.` is `~*`: a case-insensitive partial match, so an unanchored pattern hits\n * anywhere in the value. `c.` is `ilike`, also case-insensitive.\n */\nconst OPERATOR_PREFIX: Record<FilterOperator, string> = {\n\teq: 'eq.',\n\tcontains: 'c.',\n\tmatches: 're.',\n}\n\n/** A filter as its param value, always prefixed so a value starting like an operator stays literal. */\nconst paramValue = (filter: AnalyticsFilter): string =>\n\t`${OPERATOR_PREFIX[filter.operator]}${filter.value}`\n\n/**\n * Every filter param takes equals, contains and a regular expression\n * (https://docs.umami.is/docs/filters), written as the `eq.`, `c.` and `re.` prefixes.\n */\nconst umamiFilters = everyOperatorOn(mappedKeys(DIMENSION_KEYS, DIMENSION_MAP))\n\n// `event` filters but does not group, since /stats reports no `events` number to declare;\n// `goal` and `channel` are the reverse, /metrics types with no matching filter param.\nconst umamiDimensions: ReadonlySet<DimensionKey> = new Set<DimensionKey>([\n\t...filterableDimensions({ filters: umamiFilters }).filter((dimension) => dimension !== 'event'),\n\t'goal',\n\t'channel',\n])\n\n/**\n * /stats answers site totals and /metrics one count per row, so other metrics are site-wide only.\n * Nothing reports time per pageview, so no time on page is offered.\n */\nconst siteOnly: MetricReach = { dimensions: [] }\nconst umamiReach: Partial<Record<MetricKey, MetricReach>> = {\n\tpageviews: siteOnly,\n\tvisits: siteOnly,\n\tsessions: siteOnly,\n\tbounceRate: siteOnly,\n\tvisitDuration: siteOnly,\n\tvisitors: { dimensions: [...umamiDimensions].filter((dimension) => dimension !== 'goal') },\n\tconversions: { dimensions: ['goal'] },\n}\n\ninterface UmamiParams {\n\tsearch: URLSearchParams\n\t/** Filters a one-value-per-param request could not carry. */\n\tunapplied: AnalyticsFilter[]\n\t/** Two `eq` values on one param: the AND matches nothing, so the read serves no rows. */\n\tempty: boolean\n}\n\n/**\n * The read's range and filters as query params, one value per param: clashing `eq` values match\n * nothing (an empty read), and other clashes keep the first, the page path always winning.\n */\nconst paramsFor = (q: AnalyticsQuery): UmamiParams => {\n\tconst search = new URLSearchParams({\n\t\tstartAt: String(q.dateRange.start.getTime()),\n\t\tendAt: String(q.dateRange.end.getTime()),\n\t})\n\tconst filters = declaredFilters({ filters: umamiFilters }, q.filters, DIMENSION_MAP)\n\tconst eqValues = new Map<string, string>()\n\tfor (const { filter, field } of filters) {\n\t\tif (filter.operator !== 'eq') {\n\t\t\tcontinue\n\t\t}\n\t\tconst held = eqValues.get(field.param)\n\t\tif (held !== undefined && held !== filter.value) {\n\t\t\treturn { search, unapplied: [], empty: true }\n\t\t}\n\t\teqValues.set(field.param, filter.value)\n\t}\n\tconst unapplied: AnalyticsFilter[] = []\n\tconst held = new Map<string, { value: string; filter: AnalyticsFilter }>()\n\tfor (const { filter, field } of filters) {\n\t\t// Umami splits an `eq.` value on commas with no escape, which would widen the question.\n\t\tif (filter.operator === 'eq' && filter.value.includes(',')) {\n\t\t\tunapplied.push(filter)\n\t\t\tcontinue\n\t\t}\n\t\tconst value = paramValue(filter)\n\t\tconst first = held.get(field.param)\n\t\tif (first === undefined) {\n\t\t\theld.set(field.param, { value, filter })\n\t\t\tsearch.set(field.param, value)\n\t\t} else if (first.value !== value) {\n\t\t\tunapplied.push(filter)\n\t\t}\n\t}\n\tif (q.path) {\n\t\tconst value = `eq.${q.path}`\n\t\tconst first = held.get('path')\n\t\tif (first !== undefined && first.value !== value) {\n\t\t\tunapplied.push(first.filter)\n\t\t}\n\t\tsearch.set('path', value)\n\t}\n\treturn { search, unapplied, empty: false }\n}\n\n/** `values` narrowed to the metrics a read asked for. */\nconst requested = (metrics: readonly MetricKey[], values: MetricValues): MetricValues => {\n\tconst out: MetricValues = {}\n\tfor (const metric of metrics) {\n\t\tif (values[metric] !== undefined) {\n\t\t\tout[metric] = values[metric]\n\t\t}\n\t}\n\treturn out\n}\n\ninterface UmamiPoint {\n\tx: string\n\ty: number\n}\n\ninterface UmamiSeries {\n\tpageviews: UmamiPoint[]\n\tsessions: UmamiPoint[]\n}\n\ninterface UmamiStats {\n\tpageviews: number\n\tvisitors: number\n\tvisits: number\n\tbounces: number\n\ttotaltime: number\n}\n\n/**\n * The Umami 3.x adapter, cloud and self-hosted. Filter values always carry an explicit `eq.` prefix,\n * so a value starting like an operator is never read as one.\n */\nexport function umami(config: UmamiConfig): AnalyticsAdapter {\n\tconst endpoints = umamiEndpoints(config.host)\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 730\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\trealtime: false,\n\t\tminGranularity: 'day',\n\t\tmaxLookbackDays,\n\t\tmetrics: umamiMetrics,\n\t\tdimensions: umamiDimensions,\n\t\tmetricReach: umamiReach,\n\t\tfilters: umamiFilters,\n\t\tsemantics: { visitors: 'distinct', sessions: 'provider' },\n\t\trateLimit: null,\n\t\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n\t\tupstreamAware: true,\n\t}\n\t// Cloud authenticates with x-umami-api-key; self-hosted with a bearer token.\n\tconst authHeaders = (): Record<string, string> =>\n\t\tconfig.apiKey\n\t\t\t? { 'x-umami-api-key': config.apiKey }\n\t\t\t: config.token\n\t\t\t\t? { authorization: `Bearer ${config.token}` }\n\t\t\t\t: {}\n\n\treturn {\n\t\tid: 'umami',\n\t\t...adapterLabel(config.label, 'Umami', 'umami({ label })'),\n\t\tcapabilities,\n\t\tcapture: buildCapture(config, endpoints),\n\t\tisConfigured: () => Boolean(config.websiteId && (config.apiKey || config.token)),\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = readTime(ctx)\n\t\t\tconst headers = authHeaders()\n\t\t\tconst goalBreakdown = (q.dimensions ?? []).includes('goal')\n\t\t\tconst hint = goalHint(q)\n\t\t\tconst slugs = hintSlugs(hint)\n\t\t\tconst plan = paramsFor(q)\n\t\t\tconst breakdown = firstMapped(q.dimensions, BREAKDOWNS)\n\t\t\t// Umami splits an `eq.` list on commas with no escape, so a slug carrying one is left out\n\t\t\t// and reported rather than widening the read to every event.\n\t\t\tconst askable = (slugs ?? []).filter((slug) => !slug.includes(','))\n\t\t\tconst unaskable = (slugs ?? []).filter((slug) => slug.includes(','))\n\t\t\tconst eventValue = `eq.${askable.join(',')}`\n\t\t\t// Goal rows come from the `event` param, so on a read that fetches them the hint wins and a\n\t\t\t// caller's own event filter is reported unapplied; any other breakdown sends it as written.\n\t\t\tconst eventFilter = (q.filters ?? []).find((f) => f.dimension === 'event')\n\t\t\tconst readsGoals =\n\t\t\t\tgoalBreakdown || (!breakdown && q.metrics.includes('conversions') && slugs !== null)\n\t\t\tconst unapplied: AnalyticsFilter[] = [\n\t\t\t\t...plan.unapplied,\n\t\t\t\t...unaskable.map(\n\t\t\t\t\t(slug): AnalyticsFilter => ({ dimension: 'goal', operator: 'eq', value: slug })\n\t\t\t\t),\n\t\t\t\t...(readsGoals && eventFilter && paramValue(eventFilter) !== eventValue\n\t\t\t\t\t? [eventFilter]\n\t\t\t\t\t: []),\n\t\t\t]\n\t\t\tconst unresolved = q.metrics.includes('conversions') && hintFailed(hint)\n\t\t\tconst unappliedMeta = unapplied.length > 0 ? { unappliedFilters: unapplied } : {}\n\t\t\tconst empty = goalBreakdown\n\t\t\t\t? emptyGoalBreakdown({ provider: 'umami', fetchedAt, hint, meta: unappliedMeta })\n\t\t\t\t: null\n\t\t\tif (empty) {\n\t\t\t\treturn empty\n\t\t\t}\n\t\t\tconst meta: AnalyticsResult['meta'] = {\n\t\t\t\tprovider: 'umami',\n\t\t\t\tfetchedAt,\n\t\t\t\t...unappliedMeta,\n\t\t\t\t...(unresolved ? { goalsUnresolved: true as const } : {}),\n\t\t\t}\n\t\t\t// Totals are left undefined rather than zeroed, the same as every other number this\n\t\t\t// adapter cannot report, so the display layer shows \"no data\" instead of a real 0.\n\t\t\tif (plan.empty) {\n\t\t\t\treturn { rows: [], totals: undefined, meta }\n\t\t\t}\n\n\t\t\t/** The read's params plus `extra`, on a fresh copy so no request sees another's. */\n\t\t\tconst search = (extra: Record<string, string> = {}): URLSearchParams => {\n\t\t\t\tconst params = new URLSearchParams(plan.search)\n\t\t\t\tfor (const [name, value] of Object.entries(extra)) {\n\t\t\t\t\tparams.set(name, value)\n\t\t\t\t}\n\t\t\t\treturn params\n\t\t\t}\n\t\t\tconst getJson = <T>(endpoint: string, params: URLSearchParams): Promise<T> =>\n\t\t\t\tupstreamJson<T>(\n\t\t\t\t\tctx,\n\t\t\t\t\t`${endpoints.api}/websites/${config.websiteId}/${endpoint}?${params.toString()}`,\n\t\t\t\t\t{ headers, provider: 'umami', fetch: config.fetch }\n\t\t\t\t)\n\n\t\t\t/**\n\t\t\t * The goal rows for the hint, narrowed to it again on the way back so nothing the API\n\t\t\t * did not restrict can arrive as a goal.\n\t\t\t */\n\t\t\tconst fetchGoalRows = async (): Promise<UmamiPoint[]> => {\n\t\t\t\tif (askable.length === 0) {\n\t\t\t\t\treturn []\n\t\t\t\t}\n\t\t\t\tconst data = await getJson<UmamiPoint[]>(\n\t\t\t\t\t'metrics',\n\t\t\t\t\tsearch({ type: GOAL_DIMENSION.param, [GOAL_DIMENSION.param]: eventValue })\n\t\t\t\t)\n\t\t\t\tconst wanted = new Set(askable)\n\t\t\t\treturn data.filter((row) => wanted.has(row.x))\n\t\t\t}\n\n\t\t\tif (goalBreakdown) {\n\t\t\t\tconst rows: AnalyticsRow[] = (await fetchGoalRows()).map((row) => ({\n\t\t\t\t\tdimensions: { goal: row.x },\n\t\t\t\t\tmetrics: { [GOAL_DIMENSION.metric]: row.y },\n\t\t\t\t}))\n\t\t\t\treturn { rows, totals: undefined, meta }\n\t\t\t}\n\n\t\t\tif (breakdown) {\n\t\t\t\tconst { dimension, field } = breakdown\n\t\t\t\tconst data = await getJson<UmamiPoint[]>('metrics', search({ type: field.param }))\n\t\t\t\t// /metrics reports one number per row, under the name it holds: a requested metric with no\n\t\t\t\t// per-row source is absent rather than labelled with a number it is not.\n\t\t\t\tconst rows: AnalyticsRow[] = data.map((row) => ({\n\t\t\t\t\tdimensions: { [dimension]: row.x },\n\t\t\t\t\tmetrics: { [field.metric]: row.y },\n\t\t\t\t}))\n\t\t\t\treturn { rows, totals: undefined, meta }\n\t\t\t}\n\n\t\t\tconst fetchTotals = async (): Promise<MetricValues> => {\n\t\t\t\t// Conversions have no place in /stats: their total is the goal rows summed.\n\t\t\t\tconst [stats, goalRows] = await Promise.all([\n\t\t\t\t\tgetJson<UmamiStats>('stats', search()),\n\t\t\t\t\tq.metrics.includes('conversions') && slugs ? fetchGoalRows() : undefined,\n\t\t\t\t])\n\t\t\t\treturn requested(q.metrics, {\n\t\t\t\t\t...(goalRows ? { conversions: goalRows.reduce((sum, row) => sum + row.y, 0) } : {}),\n\t\t\t\t\tpageviews: stats.pageviews,\n\t\t\t\t\tvisitors: stats.visitors,\n\t\t\t\t\tvisits: stats.visits,\n\t\t\t\t\tsessions: stats.visits,\n\t\t\t\t\t// Derived ratios read null (not zero) when there are no visits: a bounce rate of\n\t\t\t\t\t// nobody is no data, and a 0 would read as every visitor staying.\n\t\t\t\t\tbounceRate: stats.visits > 0 ? Math.round((stats.bounces / stats.visits) * 100) : null,\n\t\t\t\t\tvisitDuration:\n\t\t\t\t\t\tstats.visits > 0 ? Math.round((stats.totaltime / stats.visits) * 1000) : null,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\t// Umami's only series endpoint reports pageviews and sessions, so a trend on any other\n\t\t\t// metric keeps its /stats headline but an empty series.\n\t\t\tif (q.granularity === 'day') {\n\t\t\t\tconst [series, totals] = await Promise.all([\n\t\t\t\t\tgetJson<UmamiSeries>(\n\t\t\t\t\t\t'pageviews',\n\t\t\t\t\t\tsearch({ unit: 'day', timezone: q.timezone ?? DEFAULT_TIMEZONE })\n\t\t\t\t\t),\n\t\t\t\t\tfetchTotals(),\n\t\t\t\t])\n\t\t\t\tconst sessionsByDay = new Map(series.sessions.map((point) => [point.x, point.y]))\n\t\t\t\tconst rows: AnalyticsRow[] = []\n\t\t\t\tfor (const point of series.pageviews) {\n\t\t\t\t\tconst timestamp = dayIso(point.x)\n\t\t\t\t\tif (!timestamp) {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tconst sessions = sessionsByDay.get(point.x) ?? 0\n\t\t\t\t\trows.push({\n\t\t\t\t\t\ttimestamp,\n\t\t\t\t\t\tmetrics: requested(q.metrics, { pageviews: point.y, visits: sessions, sessions }),\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\treturn { rows, totals, meta }\n\t\t\t}\n\n\t\t\tconst totals = await fetchTotals()\n\t\t\treturn { rows: [{ metrics: totals }], totals, meta }\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;AAwDA,MAAM,QAAwB;CAC7B,KAAK;CACL,QAAQ;CACR,MAAM;AACP;;AAGA,MAAM,kBA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AAS,KAAK,UAAU,CAAC,MAAM,GAAG,MAAM,CAAC,CAAC,CAAC;IAChF,MAAM,OAAuB,CAAC;IAC9B,KAAK,MAAM,SAAS,OAAO,WAAW;KACrC,MAAM,YAAY,OAAO,MAAM,CAAC;KAChC,IAAI,CAAC,WACJ;KAED,MAAM,WAAW,cAAc,IAAI,MAAM,CAAC,KAAK;KAC/C,KAAK,KAAK;MACT;MACA,SAAS,UAAU,EAAE,SAAS;OAAE,WAAW,MAAM;OAAG,QAAQ;OAAU;MAAS,CAAC;KACjF,CAAC;IACF;IACA,OAAO;KAAE;KAAM;KAAQ;IAAK;GAC7B;GAEA,MAAM,SAAS,MAAM,YAAY;GACjC,OAAO;IAAE,MAAM,CAAC,EAAE,SAAS,OAAO,CAAC;IAAG;IAAQ;GAAK;EACpD;CACD;AACD"}
@@ -79,7 +79,7 @@ const makeExclusionHandler = () => async (req) => {
79
79
  });
80
80
  if (!requested.ok) return errorResponse(400, analyticsError("untrusted_scope", "analytics: scope is not permitted for this request", "scope"));
81
81
  if (requested.scope === "*") return errorResponse(400, analyticsError("invalid_param", "analytics: an exclusion link belongs to one site, so name one scope or none", "scope"));
82
- const everyScope = runtime.scoped === true && requested.scope === null && await gates.named();
82
+ const everyScope = runtime.scoped === true && requested.scope === null && await gates.named({ scope: null });
83
83
  const answer = {
84
84
  param: runtime.exclusion.param,
85
85
  token: exclusionToken(req.payload.secret, requested.scope),
@@ -1 +1 @@
1
- {"version":3,"file":"exclusionEndpoint.js","names":[],"sources":["../../src/capture/exclusionEndpoint.ts"],"sourcesContent":["import type { PayloadHandler, PayloadRequest } from 'payload'\nimport { readGate } from '../access/readGate'\nimport { PLATFORM_SCOPE } from '../core/contract'\nimport { resolveRequestedScope } from '../core/scopedRead'\nimport { resolveScopeList } from '../core/scopeList'\nimport { siteAddress } from '../core/siteAddress'\nimport { analyticsError, errorResponse, NO_STORE } from '../plugin/errors'\nimport {\n\ttype AnalyticsRuntime,\n\tgetRuntime,\n\tresolveCaptureScopeFor,\n\tscopeGates,\n} from '../plugin/runtime'\nimport type { ExclusionResponse, ExclusionSite } from '../view/exclusionLink'\nimport { exclusionToken } from './exclusionToken'\n\nconst viewAllowed = async (runtime: AnalyticsRuntime, req: PayloadRequest): Promise<boolean> =>\n\truntime.viewAccess ? runtime.viewAccess({ req }) : true\n\n/**\n * Whether the admin's own address resolves to `scope` as a visit would. Null on an unscoped\n * install, whose site may run at this address or on a separate frontend.\n */\nconst servesScope = async (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tscope: string | null\n): Promise<boolean | null> => {\n\tif (runtime.scoped !== true) {\n\t\treturn null\n\t}\n\tif (scope === null) {\n\t\treturn false\n\t}\n\ttry {\n\t\treturn (await resolveCaptureScopeFor(runtime, req)) === scope\n\t} catch {\n\t\treturn false\n\t}\n}\n\n/**\n * The scope's site addresses from `capture.exclusion.sites`, trimmed to origin and path. A throwing\n * resolver costs the whole links, never the token: the view hands out the part to add instead.\n */\nconst sitesOf = async (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tscope: string | null\n): Promise<string[]> => {\n\tconst resolve = runtime.exclusion?.sites\n\tif (!resolve) {\n\t\treturn []\n\t}\n\tlet answered: unknown\n\ttry {\n\t\tanswered = await resolve({ req, scope })\n\t} catch (err) {\n\t\treq.payload.logger?.warn(`analytics: capture.exclusion.sites failed: ${String(err)}`)\n\t\treturn []\n\t}\n\tconst sites = (Array.isArray(answered) ? answered : []).flatMap((site: unknown) => {\n\t\tconst address = siteAddress(site)\n\t\treturn address === null ? [] : [address]\n\t})\n\treturn [...new Set(sites)]\n}\n\nconst siteEntries = async (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tscope: string | null\n): Promise<ExclusionSite[]> => {\n\tconst token = exclusionToken(req.payload.secret, scope)\n\treturn (await sitesOf(runtime, req, scope)).map((address) => ({ address, token }))\n}\n\n/** The install-wide sites, then each listed scope's, each with its own token; an address once. */\nconst everyScopeSites = async (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest\n): Promise<ExclusionSite[]> => {\n\tconst scopes = await resolveScopeList(runtime.scopeList, req.payload)\n\tconst lists = await Promise.all(scopes.map((scope) => siteEntries(runtime, req, scope)))\n\tconst byAddress = new Map<string, ExclusionSite>()\n\tfor (const site of lists.flat()) {\n\t\tif (!byAddress.has(site.address)) {\n\t\t\tbyAddress.set(site.address, site)\n\t\t}\n\t}\n\treturn [...byAddress.values()]\n}\n\n/**\n * A scope's exclusion token and sites, gated like a read plus `access.view` (all sites: every\n * scope's, for a reader who may name each). Never cached: a token drops a browser from numbers.\n */\nexport const makeExclusionHandler = (): PayloadHandler => async (req) => {\n\tif (!req.user) {\n\t\treturn errorResponse(401, analyticsError('unauthorized', 'analytics: authentication required'))\n\t}\n\tconst runtime = getRuntime(req.payload)\n\tif (!runtime?.exclusion) {\n\t\treturn errorResponse(404, analyticsError('not_found', 'analytics: the exclusion link is off'))\n\t}\n\ttry {\n\t\tif (!(await readGate(runtime, req)) || !(await viewAllowed(runtime, req))) {\n\t\t\treturn errorResponse(403, analyticsError('forbidden', 'analytics: read access denied'))\n\t\t}\n\t\tconst raw = new URL(req.url ?? '', 'http://localhost').searchParams.get('scope')\n\t\tconst gates = scopeGates(runtime, req)\n\t\tconst requested = await resolveRequestedScope({ runtime, req, raw, gates })\n\t\tif (!requested.ok) {\n\t\t\treturn errorResponse(\n\t\t\t\t400,\n\t\t\t\tanalyticsError(\n\t\t\t\t\t'untrusted_scope',\n\t\t\t\t\t'analytics: scope is not permitted for this request',\n\t\t\t\t\t'scope'\n\t\t\t\t)\n\t\t\t)\n\t\t}\n\t\tif (requested.scope === PLATFORM_SCOPE) {\n\t\t\treturn errorResponse(\n\t\t\t\t400,\n\t\t\t\tanalyticsError(\n\t\t\t\t\t'invalid_param',\n\t\t\t\t\t'analytics: an exclusion link belongs to one site, so name one scope or none',\n\t\t\t\t\t'scope'\n\t\t\t\t)\n\t\t\t)\n\t\t}\n\t\t// A scoped install's null passed the aggregate gate; another scope's token also takes `named`.\n\t\tconst everyScope = runtime.scoped === true && requested.scope === null && (await gates.named())\n\t\tconst answer: ExclusionResponse = {\n\t\t\tparam: runtime.exclusion.param,\n\t\t\ttoken: exclusionToken(req.payload.secret, requested.scope),\n\t\t\tsameOrigin: await servesScope(runtime, req, requested.scope),\n\t\t\tsites: everyScope\n\t\t\t\t? await everyScopeSites(runtime, req)\n\t\t\t\t: await siteEntries(runtime, req, requested.scope),\n\t\t}\n\t\treturn Response.json(answer, { headers: NO_STORE })\n\t} catch (err) {\n\t\treq.payload.logger?.warn(`analytics: exclusion link failed: ${String(err)}`)\n\t\treturn errorResponse(\n\t\t\t500,\n\t\t\tanalyticsError('internal', 'analytics: the exclusion link could not be made')\n\t\t)\n\t}\n}\n"],"mappings":";;;;;;;;;AAgBA,MAAM,cAAc,OAAO,SAA2B,QACrD,QAAQ,aAAa,QAAQ,WAAW,EAAE,IAAI,CAAC,IAAI;;;;;AAMpD,MAAM,cAAc,OACnB,SACA,KACA,UAC6B;CAC7B,IAAI,QAAQ,WAAW,MACtB,OAAO;CAER,IAAI,UAAU,MACb,OAAO;CAER,IAAI;EACH,OAAQ,MAAM,uBAAuB,SAAS,GAAG,MAAO;CACzD,QAAQ;EACP,OAAO;CACR;AACD;;;;;AAMA,MAAM,UAAU,OACf,SACA,KACA,UACuB;CACvB,MAAM,UAAU,QAAQ,WAAW;CACnC,IAAI,CAAC,SACJ,OAAO,CAAC;CAET,IAAI;CACJ,IAAI;EACH,WAAW,MAAM,QAAQ;GAAE;GAAK;EAAM,CAAC;CACxC,SAAS,KAAK;EACb,IAAI,QAAQ,QAAQ,KAAK,8CAA8C,OAAO,GAAG,GAAG;EACpF,OAAO,CAAC;CACT;CACA,MAAM,SAAS,MAAM,QAAQ,QAAQ,IAAI,WAAW,CAAC,GAAG,SAAS,SAAkB;EAClF,MAAM,UAAU,YAAY,IAAI;EAChC,OAAO,YAAY,OAAO,CAAC,IAAI,CAAC,OAAO;CACxC,CAAC;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,eACC,mBACA,sDACA,OACD,CACD;EAED,IAAI,UAAU,UAAA,KACb,OAAO,cACN,KACA,eACC,iBACA,+EACA,OACD,CACD;EAGD,MAAM,aAAa,QAAQ,WAAW,QAAQ,UAAU,UAAU,QAAS,MAAM,MAAM,MAAM;EAC7F,MAAM,SAA4B;GACjC,OAAO,QAAQ,UAAU;GACzB,OAAO,eAAe,IAAI,QAAQ,QAAQ,UAAU,KAAK;GACzD,YAAY,MAAM,YAAY,SAAS,KAAK,UAAU,KAAK;GAC3D,OAAO,aACJ,MAAM,gBAAgB,SAAS,GAAG,IAClC,MAAM,YAAY,SAAS,KAAK,UAAU,KAAK;EACnD;EACA,OAAO,SAAS,KAAK,QAAQ,EAAE,SAAS,SAAS,CAAC;CACnD,SAAS,KAAK;EACb,IAAI,QAAQ,QAAQ,KAAK,qCAAqC,OAAO,GAAG,GAAG;EAC3E,OAAO,cACN,KACA,eAAe,YAAY,iDAAiD,CAC7E;CACD;AACD"}
1
+ {"version":3,"file":"exclusionEndpoint.js","names":[],"sources":["../../src/capture/exclusionEndpoint.ts"],"sourcesContent":["import type { PayloadHandler, PayloadRequest } from 'payload'\nimport { readGate } from '../access/readGate'\nimport { PLATFORM_SCOPE } from '../core/contract'\nimport { resolveRequestedScope } from '../core/scopedRead'\nimport { resolveScopeList } from '../core/scopeList'\nimport { siteAddress } from '../core/siteAddress'\nimport { analyticsError, errorResponse, NO_STORE } from '../plugin/errors'\nimport {\n\ttype AnalyticsRuntime,\n\tgetRuntime,\n\tresolveCaptureScopeFor,\n\tscopeGates,\n} from '../plugin/runtime'\nimport type { ExclusionResponse, ExclusionSite } from '../view/exclusionLink'\nimport { exclusionToken } from './exclusionToken'\n\nconst viewAllowed = async (runtime: AnalyticsRuntime, req: PayloadRequest): Promise<boolean> =>\n\truntime.viewAccess ? runtime.viewAccess({ req }) : true\n\n/**\n * Whether the admin's own address resolves to `scope` as a visit would. Null on an unscoped\n * install, whose site may run at this address or on a separate frontend.\n */\nconst servesScope = async (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tscope: string | null\n): Promise<boolean | null> => {\n\tif (runtime.scoped !== true) {\n\t\treturn null\n\t}\n\tif (scope === null) {\n\t\treturn false\n\t}\n\ttry {\n\t\treturn (await resolveCaptureScopeFor(runtime, req)) === scope\n\t} catch {\n\t\treturn false\n\t}\n}\n\n/**\n * The scope's site addresses from `capture.exclusion.sites`, trimmed to origin and path. A throwing\n * resolver costs the whole links, never the token: the view hands out the part to add instead.\n */\nconst sitesOf = async (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tscope: string | null\n): Promise<string[]> => {\n\tconst resolve = runtime.exclusion?.sites\n\tif (!resolve) {\n\t\treturn []\n\t}\n\tlet answered: unknown\n\ttry {\n\t\tanswered = await resolve({ req, scope })\n\t} catch (err) {\n\t\treq.payload.logger?.warn(`analytics: capture.exclusion.sites failed: ${String(err)}`)\n\t\treturn []\n\t}\n\tconst sites = (Array.isArray(answered) ? answered : []).flatMap((site: unknown) => {\n\t\tconst address = siteAddress(site)\n\t\treturn address === null ? [] : [address]\n\t})\n\treturn [...new Set(sites)]\n}\n\nconst siteEntries = async (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tscope: string | null\n): Promise<ExclusionSite[]> => {\n\tconst token = exclusionToken(req.payload.secret, scope)\n\treturn (await sitesOf(runtime, req, scope)).map((address) => ({ address, token }))\n}\n\n/** The install-wide sites, then each listed scope's, each with its own token; an address once. */\nconst everyScopeSites = async (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest\n): Promise<ExclusionSite[]> => {\n\tconst scopes = await resolveScopeList(runtime.scopeList, req.payload)\n\tconst lists = await Promise.all(scopes.map((scope) => siteEntries(runtime, req, scope)))\n\tconst byAddress = new Map<string, ExclusionSite>()\n\tfor (const site of lists.flat()) {\n\t\tif (!byAddress.has(site.address)) {\n\t\t\tbyAddress.set(site.address, site)\n\t\t}\n\t}\n\treturn [...byAddress.values()]\n}\n\n/**\n * A scope's exclusion token and sites, gated like a read plus `access.view` (all sites: every\n * scope's, for a reader who may name each). Never cached: a token drops a browser from numbers.\n */\nexport const makeExclusionHandler = (): PayloadHandler => async (req) => {\n\tif (!req.user) {\n\t\treturn errorResponse(401, analyticsError('unauthorized', 'analytics: authentication required'))\n\t}\n\tconst runtime = getRuntime(req.payload)\n\tif (!runtime?.exclusion) {\n\t\treturn errorResponse(404, analyticsError('not_found', 'analytics: the exclusion link is off'))\n\t}\n\ttry {\n\t\tif (!(await readGate(runtime, req)) || !(await viewAllowed(runtime, req))) {\n\t\t\treturn errorResponse(403, analyticsError('forbidden', 'analytics: read access denied'))\n\t\t}\n\t\tconst raw = new URL(req.url ?? '', 'http://localhost').searchParams.get('scope')\n\t\tconst gates = scopeGates(runtime, req)\n\t\tconst requested = await resolveRequestedScope({ runtime, req, raw, gates })\n\t\tif (!requested.ok) {\n\t\t\treturn errorResponse(\n\t\t\t\t400,\n\t\t\t\tanalyticsError(\n\t\t\t\t\t'untrusted_scope',\n\t\t\t\t\t'analytics: scope is not permitted for this request',\n\t\t\t\t\t'scope'\n\t\t\t\t)\n\t\t\t)\n\t\t}\n\t\tif (requested.scope === PLATFORM_SCOPE) {\n\t\t\treturn errorResponse(\n\t\t\t\t400,\n\t\t\t\tanalyticsError(\n\t\t\t\t\t'invalid_param',\n\t\t\t\t\t'analytics: an exclusion link belongs to one site, so name one scope or none',\n\t\t\t\t\t'scope'\n\t\t\t\t)\n\t\t\t)\n\t\t}\n\t\t// A scoped install's null passed the aggregate gate; another scope's token also takes `named`.\n\t\tconst everyScope =\n\t\t\truntime.scoped === true && requested.scope === null && (await gates.named({ scope: null }))\n\t\tconst answer: ExclusionResponse = {\n\t\t\tparam: runtime.exclusion.param,\n\t\t\ttoken: exclusionToken(req.payload.secret, requested.scope),\n\t\t\tsameOrigin: await servesScope(runtime, req, requested.scope),\n\t\t\tsites: everyScope\n\t\t\t\t? await everyScopeSites(runtime, req)\n\t\t\t\t: await siteEntries(runtime, req, requested.scope),\n\t\t}\n\t\treturn Response.json(answer, { headers: NO_STORE })\n\t} catch (err) {\n\t\treq.payload.logger?.warn(`analytics: exclusion link failed: ${String(err)}`)\n\t\treturn errorResponse(\n\t\t\t500,\n\t\t\tanalyticsError('internal', 'analytics: the exclusion link could not be made')\n\t\t)\n\t}\n}\n"],"mappings":";;;;;;;;;AAgBA,MAAM,cAAc,OAAO,SAA2B,QACrD,QAAQ,aAAa,QAAQ,WAAW,EAAE,IAAI,CAAC,IAAI;;;;;AAMpD,MAAM,cAAc,OACnB,SACA,KACA,UAC6B;CAC7B,IAAI,QAAQ,WAAW,MACtB,OAAO;CAER,IAAI,UAAU,MACb,OAAO;CAER,IAAI;EACH,OAAQ,MAAM,uBAAuB,SAAS,GAAG,MAAO;CACzD,QAAQ;EACP,OAAO;CACR;AACD;;;;;AAMA,MAAM,UAAU,OACf,SACA,KACA,UACuB;CACvB,MAAM,UAAU,QAAQ,WAAW;CACnC,IAAI,CAAC,SACJ,OAAO,CAAC;CAET,IAAI;CACJ,IAAI;EACH,WAAW,MAAM,QAAQ;GAAE;GAAK;EAAM,CAAC;CACxC,SAAS,KAAK;EACb,IAAI,QAAQ,QAAQ,KAAK,8CAA8C,OAAO,GAAG,GAAG;EACpF,OAAO,CAAC;CACT;CACA,MAAM,SAAS,MAAM,QAAQ,QAAQ,IAAI,WAAW,CAAC,GAAG,SAAS,SAAkB;EAClF,MAAM,UAAU,YAAY,IAAI;EAChC,OAAO,YAAY,OAAO,CAAC,IAAI,CAAC,OAAO;CACxC,CAAC;CACD,OAAO,CAAC,GAAG,IAAI,IAAI,KAAK,CAAC;AAC1B;AAEA,MAAM,cAAc,OACnB,SACA,KACA,UAC8B;CAC9B,MAAM,QAAQ,eAAe,IAAI,QAAQ,QAAQ,KAAK;CACtD,QAAQ,MAAM,QAAQ,SAAS,KAAK,KAAK,GAAG,KAAK,aAAa;EAAE;EAAS;CAAM,EAAE;AAClF;;AAGA,MAAM,kBAAkB,OACvB,SACA,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AAQ,UAAU,KAAK;GACzD,YAAY,MAAM,YAAY,SAAS,KAAK,UAAU,KAAK;GAC3D,OAAO,aACJ,MAAM,gBAAgB,SAAS,GAAG,IAClC,MAAM,YAAY,SAAS,KAAK,UAAU,KAAK;EACnD;EACA,OAAO,SAAS,KAAK,QAAQ,EAAE,SAAS,SAAS,CAAC;CACnD,SAAS,KAAK;EACb,IAAI,QAAQ,QAAQ,KAAK,qCAAqC,OAAO,GAAG,GAAG;EAC3E,OAAO,cACN,KACA,eAAe,YAAY,iDAAiD,CAC7E;CACD;AACD"}
@@ -26,15 +26,15 @@ const resolveSlotAdapterFor = async (args) => {
26
26
  const visitor = captureRequest(req);
27
27
  const resolved = scope === void 0 ? await resolveCaptureScopeFor(runtime, visitor) : scope;
28
28
  if (resolved === null) return null;
29
- const { registry, grants } = await resolveRegistryFor(runtime, {
29
+ const { registry, grants, defaultGrant } = await resolveRegistryFor(runtime, {
30
30
  payload: req.payload,
31
31
  req: visitor,
32
32
  scope: resolved
33
33
  });
34
34
  const candidates = runtime.providersCollection ? registry.all().filter((adapter) => grants.has(adapter.id)) : registry.all();
35
35
  if (configured) return candidates.find((adapter) => adapter.id === configured) ?? null;
36
- const preferred = registry.default();
37
- return candidates.find((adapter) => adapter.id === preferred.id && adapter.capture) ?? candidates.find((adapter) => adapter.capture) ?? null;
36
+ const preferred = defaultGrant ?? registry.default().id;
37
+ return candidates.find((adapter) => adapter.id === preferred && adapter.capture) ?? candidates.find((adapter) => adapter.capture) ?? null;
38
38
  } catch (err) {
39
39
  req.payload?.logger?.warn(`analytics: capture slot "${slot}" resolution failed: ${String(err)}`);
40
40
  return null;
@@ -1 +1 @@
1
- {"version":3,"file":"slots.js","names":[],"sources":["../../src/capture/slots.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport type { AnalyticsAdapter } from '../core/contract'\nimport type { CaptureGateArgs } from '../core/options'\nimport { isOneOf } from '../core/values'\nimport {\n\ttype AnalyticsRuntime,\n\tresolveCaptureScopeFor,\n\tresolveRegistryFor,\n} from '../plugin/runtime'\nimport type { CaptureClientKind, CaptureSlot } from '../tracker/config'\nimport { captureRequest } from './captureRequest'\n\nexport const CAPTURE_SLOTS: readonly CaptureSlot[] = ['global', 'tenant']\n\nexport const isCaptureSlot = (value: string): value is CaptureSlot => isOneOf(CAPTURE_SLOTS, value)\n\n/** The adapter the global slot falls to when none is configured: the platform's, else the only one. */\nconst defaultGlobalId = (runtime: AnalyticsRuntime): string | undefined => {\n\tif (runtime.platformAdapterId) {\n\t\treturn runtime.platformAdapterId\n\t}\n\tconst all = runtime.registry.all()\n\treturn all.length === 1 ? all[0]?.id : undefined\n}\n\n/**\n * The adapter filling one capture slot for this request, or null; any failure degrades to null so\n * the proxy 404s. Pass `scope` to reuse a resolved one; a slot configured `false` resolves nothing.\n */\nexport const resolveSlotAdapterFor = async (args: {\n\truntime: AnalyticsRuntime\n\treq: PayloadRequest\n\tslot: CaptureSlot\n\tscope?: string | null\n}): Promise<AnalyticsAdapter | null> => {\n\tconst { runtime, req, slot, scope } = args\n\tconst configured = runtime.captureSlots?.[slot]\n\tif (configured === false) {\n\t\treturn null\n\t}\n\ttry {\n\t\tif (slot === 'global') {\n\t\t\tconst id = configured || defaultGlobalId(runtime)\n\t\t\treturn id === undefined ? null : runtime.registry.get(id)\n\t\t}\n\t\t// The visitor's request: the slot follows the site an editor is on, not their admin tenant.\n\t\tconst visitor = captureRequest(req)\n\t\tconst resolved = scope === undefined ? await resolveCaptureScopeFor(runtime, visitor) : scope\n\t\tif (resolved === null) {\n\t\t\treturn null\n\t\t}\n\t\tconst { registry, grants } = await resolveRegistryFor(runtime, {\n\t\t\tpayload: req.payload,\n\t\t\treq: visitor,\n\t\t\tscope: resolved,\n\t\t})\n\t\t// Only a granted source may fill it, so a tenant without a native document gets no beacon.\n\t\tconst candidates = runtime.providersCollection\n\t\t\t? registry.all().filter((adapter) => grants.has(adapter.id))\n\t\t\t: registry.all()\n\t\tif (configured) {\n\t\t\treturn candidates.find((adapter) => adapter.id === configured) ?? null\n\t\t}\n\t\t// The default source only when it can capture: one that cannot would leave the slot empty.\n\t\tconst preferred = registry.default()\n\t\treturn (\n\t\t\tcandidates.find((adapter) => adapter.id === preferred.id && adapter.capture) ??\n\t\t\tcandidates.find((adapter) => adapter.capture) ??\n\t\t\tnull\n\t\t)\n\t} catch (err) {\n\t\treq.payload?.logger?.warn(`analytics: capture slot \"${slot}\" resolution failed: ${String(err)}`)\n\t\treturn null\n\t}\n}\n\n/** {@link resolveSlotAdapterFor} for a caller holding one slot and no scope of its own. */\nexport const resolveSlotAdapter = (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tslot: CaptureSlot\n): Promise<AnalyticsAdapter | null> => resolveSlotAdapterFor({ runtime, req, slot })\n\n/** Whether the slot may hold `adapterId`, judged with no request: the tenant slot on any scoped install. */\nconst mayFill = (runtime: AnalyticsRuntime, slot: CaptureSlot, adapterId: string): boolean => {\n\tconst configured = runtime.captureSlots?.[slot]\n\tif (configured === false) {\n\t\treturn false\n\t}\n\tif (typeof configured === 'string') {\n\t\treturn configured === adapterId\n\t}\n\tif (slot === 'tenant') {\n\t\treturn runtime.scoped === true || runtime.resolveScope !== undefined\n\t}\n\treturn defaultGlobalId(runtime) === adapterId\n}\n\n/**\n * Whether `capture.gate` holds one slot. No gate, and a gate that throws (reported to `onError`),\n * hold it: capturing without the host's say-so is the one answer this must never give by accident.\n */\nexport const gateHolds = (\n\truntime: AnalyticsRuntime,\n\targs: CaptureGateArgs,\n\tonError?: (err: unknown) => void\n): boolean => {\n\tif (!runtime.captureGate) {\n\t\treturn true\n\t}\n\ttry {\n\t\treturn runtime.captureGate(args)\n\t} catch (err) {\n\t\tonError?.(err)\n\t\treturn true\n\t}\n}\n\n/** Whether `capture.gate` holds any slot the adapter may fill, for a caller with no request. */\nexport const gateHoldsAdapter = (\n\truntime: AnalyticsRuntime,\n\tadapterId: string,\n\tkind: CaptureClientKind\n): boolean =>\n\tCAPTURE_SLO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A4B,KAAK,uBAAuB,OAAO,GAAG,GAAG;EAC/F,OAAO;CACR;AACD;;AAGA,MAAa,sBACZ,SACA,KACA,SACsC,sBAAsB;CAAE;CAAS;CAAK;AAAK,CAAC;;AAGnF,MAAM,WAAW,SAA2B,MAAmB,cAA+B;CAC7F,MAAM,aAAa,QAAQ,eAAe;CAC1C,IAAI,eAAe,OAClB,OAAO;CAER,IAAI,OAAO,eAAe,UACzB,OAAO,eAAe;CAEvB,IAAI,SAAS,UACZ,OAAO,QAAQ,WAAW,QAAQ,QAAQ,iBAAiB,KAAA;CAE5D,OAAO,gBAAgB,OAAO,MAAM;AACrC;;;;;AAMA,MAAa,aACZ,SACA,MACA,YACa;CACb,IAAI,CAAC,QAAQ,aACZ,OAAO;CAER,IAAI;EACH,OAAO,QAAQ,YAAY,IAAI;CAChC,SAAS,KAAK;EACb,UAAU,GAAG;EACb,OAAO;CACR;AACD;;AAGA,MAAa,oBACZ,SACA,WACA,SAEA,cAAc,MACZ,SAAS,QAAQ,SAAS,MAAM,SAAS,KAAK,UAAU,SAAS;CAAE;CAAM;CAAW;AAAK,CAAC,CAC5F"}
1
+ {"version":3,"file":"slots.js","names":[],"sources":["../../src/capture/slots.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport type { AnalyticsAdapter } from '../core/contract'\nimport type { CaptureGateArgs } from '../core/options'\nimport { isOneOf } from '../core/values'\nimport {\n\ttype AnalyticsRuntime,\n\tresolveCaptureScopeFor,\n\tresolveRegistryFor,\n} from '../plugin/runtime'\nimport type { CaptureClientKind, CaptureSlot } from '../tracker/config'\nimport { captureRequest } from './captureRequest'\n\nexport const CAPTURE_SLOTS: readonly CaptureSlot[] = ['global', 'tenant']\n\nexport const isCaptureSlot = (value: string): value is CaptureSlot => isOneOf(CAPTURE_SLOTS, value)\n\n/** The adapter the global slot falls to when none is configured: the platform's, else the only one. */\nconst defaultGlobalId = (runtime: AnalyticsRuntime): string | undefined => {\n\tif (runtime.platformAdapterId) {\n\t\treturn runtime.platformAdapterId\n\t}\n\tconst all = runtime.registry.all()\n\treturn all.length === 1 ? all[0]?.id : undefined\n}\n\n/**\n * The adapter filling one capture slot for this request, or null; any failure degrades to null so\n * the proxy 404s. Pass `scope` to reuse a resolved one; a slot configured `false` resolves nothing.\n */\nexport const resolveSlotAdapterFor = async (args: {\n\truntime: AnalyticsRuntime\n\treq: PayloadRequest\n\tslot: CaptureSlot\n\tscope?: string | null\n}): Promise<AnalyticsAdapter | null> => {\n\tconst { runtime, req, slot, scope } = args\n\tconst configured = runtime.captureSlots?.[slot]\n\tif (configured === false) {\n\t\treturn null\n\t}\n\ttry {\n\t\tif (slot === 'global') {\n\t\t\tconst id = configured || defaultGlobalId(runtime)\n\t\t\treturn id === undefined ? null : runtime.registry.get(id)\n\t\t}\n\t\t// The visitor's request: the slot follows the site an editor is on, not their admin tenant.\n\t\tconst visitor = captureRequest(req)\n\t\tconst resolved = scope === undefined ? await resolveCaptureScopeFor(runtime, visitor) : scope\n\t\tif (resolved === null) {\n\t\t\treturn null\n\t\t}\n\t\tconst { registry, grants, defaultGrant } = await resolveRegistryFor(runtime, {\n\t\t\tpayload: req.payload,\n\t\t\treq: visitor,\n\t\t\tscope: resolved,\n\t\t})\n\t\t// Only a granted source may fill it, so a tenant without a native document gets no beacon.\n\t\tconst candidates = runtime.providersCollection\n\t\t\t? registry.all().filter((adapter) => grants.has(adapter.id))\n\t\t\t: registry.all()\n\t\tif (configured) {\n\t\t\treturn candidates.find((adapter) => adapter.id === configured) ?? null\n\t\t}\n\t\t// The scope's flagged default, else the registry's, only when it can capture: one that\n\t\t// cannot would leave the slot empty.\n\t\tconst preferred = defaultGrant ?? registry.default().id\n\t\treturn (\n\t\t\tcandidates.find((adapter) => adapter.id === preferred && adapter.capture) ??\n\t\t\tcandidates.find((adapter) => adapter.capture) ??\n\t\t\tnull\n\t\t)\n\t} catch (err) {\n\t\treq.payload?.logger?.warn(`analytics: capture slot \"${slot}\" resolution failed: ${String(err)}`)\n\t\treturn null\n\t}\n}\n\n/** {@link resolveSlotAdapterFor} for a caller holding one slot and no scope of its own. */\nexport const resolveSlotAdapter = (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tslot: CaptureSlot\n): Promise<AnalyticsAdapter | null> => resolveSlotAdapterFor({ runtime, req, slot })\n\n/** Whether the slot may hold `adapterId`, judged with no request: the tenant slot on any scoped install. */\nconst mayFill = (runtime: AnalyticsRuntime, slot: CaptureSlot, adapterId: string): boolean => {\n\tconst configured = runtime.captureSlots?.[slot]\n\tif (configured === false) {\n\t\treturn false\n\t}\n\tif (typeof configured === 'string') {\n\t\treturn configured === adapterId\n\t}\n\tif (slot === 'tenant') {\n\t\treturn runtime.scoped === true || runtime.resolveScope !== undefined\n\t}\n\treturn defaultGlobalId(runtime) === adapterId\n}\n\n/**\n * Whether `capture.gate` holds one slot. No gate, and a gate that throws (reported to `onError`),\n * hold it: capturing without the host's say-so is the one answer this must never give by accident.\n */\nexport const gateHolds = (\n\truntime: AnalyticsRuntime,\n\targs: CaptureGateArgs,\n\tonError?: (err: unknown) => void\n): boolean => {\n\tif (!runtime.captureGate) {\n\t\treturn true\n\t}\n\ttry {\n\t\treturn runtime.captureGate(args)\n\t} catch (err) {\n\t\tonError?.(err)\n\t\treturn true\n\t}\n}\n\n/** Whether `capture.gate` holds any slot the adapter may fill, for a caller with no request. */\nexport const gateHoldsAdapter = (\n\truntime: AnalyticsRuntime,\n\tadapterId: string,\n\tkind: CaptureClientKind\n): boolean =>\n\tCAPTURE_SLOTS.some(\n\t\t(slot) => mayFill(runtime, slot, adapterId) && gateHolds(runtime, { slot, adapterId, kind })\n\t)\n"],"mappings":";;;;AAYA,MAAa,gBAAwC,CAAC,UAAU,QAAQ;AAExE,MAAa,iBAAiB,UAAwC,QAAQ,eAAe,KAAK;;AAGlG,MAAM,mBAAmB,YAAkD;CAC1E,IAAI,QAAQ,mBACX,OAAO,QAAQ;CAEhB,MAAM,MAAM,QAAQ,SAAS,IAAI;CACj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AO,eAAe;CAEvB,IAAI,SAAS,UACZ,OAAO,QAAQ,WAAW,QAAQ,QAAQ,iBAAiB,KAAA;CAE5D,OAAO,gBAAgB,OAAO,MAAM;AACrC;;;;;AAMA,MAAa,aACZ,SACA,MACA,YACa;CACb,IAAI,CAAC,QAAQ,aACZ,OAAO;CAER,IAAI;EACH,OAAO,QAAQ,YAAY,IAAI;CAChC,SAAS,KAAK;EACb,UAAU,GAAG;EACb,OAAO;CACR;AACD;;AAGA,MAAa,oBACZ,SACA,WACA,SAEA,cAAc,MACZ,SAAS,QAAQ,SAAS,MAAM,SAAS,KAAK,UAAU,SAAS;CAAE;CAAM;CAAW;AAAK,CAAC,CAC5F"}
@@ -80,11 +80,16 @@ const exclusionFor = (runtime, req, scope) => {
80
80
  };
81
81
  /** The Payload instances that already logged a vendor filling both slots, so a busy site hears it once. */
82
82
  const warnedSharedVendor = /* @__PURE__ */ new WeakSet();
83
+ /**
84
+ * The vendors whose browser SDK runs a second client beside the first, each with its own project,
85
+ * gate and storage: a second slot of one of these kinds captures through a client named after it.
86
+ */
87
+ const NAMED_CLIENT_KINDS = new Set(["posthog"]);
83
88
  /** Why the second slot of one vendor kind is left out, logged once per instance. */
84
89
  const warnSharedVendor = (payload, args) => {
85
90
  if (!payload || warnedSharedVendor.has(payload)) return;
86
91
  warnedSharedVendor.add(payload);
87
- payload.logger?.warn(`analytics: the ${args.slot} slot resolved to "${args.adapterId}", a second ${args.kind} slot beside "${args.first.adapterId}" on the ${args.first.slot} slot. Two slots of one vendor share its one client in the browser, so neither slot's gate could be answered alone and the ${args.slot} slot's events could land in the other slot's project: the ${args.slot} slot is left out of the tracker config. Logged once.`);
92
+ payload.logger?.warn(`analytics: the ${args.slot} slot resolved to "${args.adapterId}", a second ${args.kind} slot beside "${args.first.adapterId}" on the ${args.first.slot} slot. ${args.kind} runs one client per page, so two slots of it would share that client: neither slot's gate could be answered alone and the ${args.slot} slot's events could land in the other slot's project. The ${args.slot} slot is left out of the tracker config; only PostHog runs a second client beside the first. Logged once.`);
88
93
  };
89
94
  /**
90
95
  * The per-request tracker config, one entry per capturing slot in slot order. Public and anonymous
@@ -110,7 +115,7 @@ const resolveTrackerConfig = async (args) => {
110
115
  if (!adapter || !capture || filled.has(adapter.id)) continue;
111
116
  const kind = capture.client.kind;
112
117
  const first = slots.find((entry) => entry.kind === kind);
113
- if (first) {
118
+ if (first && !NAMED_CLIENT_KINDS.has(kind)) {
114
119
  warnSharedVendor(req.payload, {
115
120
  slot,
116
121
  adapterId: adapter.id,
@@ -119,6 +124,7 @@ const resolveTrackerConfig = async (args) => {
119
124
  });
120
125
  continue;
121
126
  }
127
+ const instance = first ? slot : void 0;
122
128
  const override = runtime.capturePaths?.[slot];
123
129
  const path = override ? appPath(normalizeMountPath(override)) : apiPath(config, `${routes.proxy}/${slot}`);
124
130
  const gated = gateHolds(runtime, {
@@ -134,9 +140,11 @@ const resolveTrackerConfig = async (args) => {
134
140
  path,
135
141
  snippet: withExclusionPrelude(capture.snippet({
136
142
  path,
137
- scope
143
+ scope,
144
+ ...instance ? { instance } : {}
138
145
  }), exclusion?.param),
139
146
  client: capture.client,
147
+ ...instance ? { instance } : {},
140
148
  gated
141
149
  });
142
150
  filled.add(adapter.id);
@@ -1 +1 @@
1
- {"version":3,"file":"trackerConfig.js","names":[],"sources":["../../src/capture/trackerConfig.ts"],"sourcesContent":["import type { Payload, PayloadRequest, SanitizedConfig } from 'payload'\nimport { formatAdminURL } from 'payload/shared'\nimport type { ResolvedGoal } from '../goals/resolver'\nimport { apiPath, appPath } from '../plugin/apiPath'\nimport { analyticsRoutes } from '../plugin/routes'\nimport {\n\ttype AnalyticsRuntime,\n\tresolveCaptureScopeFor,\n\tresolveGoalsDetailedFor,\n} from '../plugin/runtime'\nimport {\n\ttype AdminDigest,\n\ttype CaptureClientKind,\n\ttype CaptureSlot,\n\tDEFAULT_AUTO_CAPTURE,\n\ttype TrackerConfig,\n\ttype TrackerExclusion,\n\ttype TrackerGoal,\n\ttype TrackerSlotConfig,\n} from '../tracker/config'\nimport { DEFAULT_TRACKER_SKIP } from '../tracker/skip'\nimport { captureRequest } from './captureRequest'\nimport { withExclusionPrelude } from './exclusionPrelude'\nimport { exclusionToken, exclusionTokenHash, publicDigest } from './exclusionToken'\nimport { normalizeMountPath } from './mountPath'\nimport { CAPTURE_SLOTS, gateHolds, resolveSlotAdapterFor } from './slots'\n\n/**\n * The admin's address as a page reaches it, behind the Next basePath, as digests: its origin only\n * when `serverURL` puts it on one, its path without a trailing slash.\n */\nconst adminDigest = (config: Partial<SanitizedConfig>): AdminDigest => {\n\tconst address = formatAdminURL({\n\t\tadminRoute: config.routes?.admin ?? '/admin',\n\t\tpath: '',\n\t\tserverURL: config.serverURL,\n\t\tincludeBasePath: true,\n\t})\n\tlet origin: string | undefined\n\tlet path = address\n\tif (/^https?:\\/\\//i.test(address)) {\n\t\ttry {\n\t\t\tconst url = new URL(address)\n\t\t\torigin = url.origin\n\t\t\tpath = url.pathname\n\t\t} catch {\n\t\t\t// A serverURL that does not parse: its digest matches no window, so no page reads as a preview.\n\t\t}\n\t}\n\treturn {\n\t\t...(origin === undefined ? {} : { origin: publicDigest(origin) }),\n\t\tpath: publicDigest(path.replace(/\\/+$/, '') || '/'),\n\t}\n}\n\n/** What the config says about skipping: the install's choice when not the default, and the admin. */\nconst skipFields = (\n\truntime: AnalyticsRuntime,\n\tconfig: Partial<SanitizedConfig>,\n\tdraft: boolean\n): Pick<TrackerConfig, 'skip' | 'draft' | 'admin'> => {\n\tconst skip = runtime.captureSkip ?? DEFAULT_TRACKER_SKIP\n\tconst changed =\n\t\tskip.automation !== DEFAULT_TRACKER_SKIP.automation ||\n\t\tskip.previews !== DEFAULT_TRACKER_SKIP.previews\n\treturn {\n\t\t...(changed ? { skip: { ...skip } } : {}),\n\t\t...(draft ? { draft: true } : {}),\n\t\t...(skip.previews ? { admin: adminDigest(config) } : {}),\n\t}\n}\n\nconst trackerGoals = (goals: ResolvedGoal[]): TrackerGoal[] =>\n\tgoals\n\t\t.filter((entry) => entry.source !== 'builtin')\n\t\t.map(({ goal: { slug, match, value, currency } }) => ({\n\t\t\tslug,\n\t\t\tmatch,\n\t\t\t...(value ? { value } : {}),\n\t\t\t...(currency ? { currency } : {}),\n\t\t}))\n\n/** The visit's scope, or null when the host's resolver has none or throws. */\nconst scopeFor = async (runtime: AnalyticsRuntime, req: PayloadRequest): Promise<string | null> => {\n\ttry {\n\t\treturn await resolveCaptureScopeFor(runtime, req)\n\t} catch (err) {\n\t\treq.payload?.logger?.warn(`analytics: tracker config scope resolution failed: ${String(err)}`)\n\t\treturn null\n\t}\n}\n\n/** The scope's merged goals, falling back to the config goals when the merge fails. */\nconst goalsFor = async (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tscope: string | null\n): Promise<ResolvedGoal[]> => {\n\ttry {\n\t\treturn await resolveGoalsDetailedFor(runtime, req, scope)\n\t} catch (err) {\n\t\treq.payload?.logger?.warn(\n\t\t\t`analytics: tracker config goals resolution failed, falling back to config goals: ${String(err)}`\n\t\t)\n\t\treturn (runtime.goals ?? []).map((goal) => ({ goal, source: 'config' as const }))\n\t}\n}\n\n/** The scope's exclusion link as the tracker sees it: the token's hash, never the token. */\nconst exclusionFor = (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tscope: string | null\n): TrackerExclusion | undefined => {\n\tconst secret = req.payload?.secret\n\tif (!runtime.exclusion || typeof secret !== 'string' || secret === '') {\n\t\treturn undefined\n\t}\n\treturn {\n\t\tparam: runtime.exclusion.param,\n\t\ttokenHash: exclusionTokenHash(exclusionToken(secret, scope)),\n\t}\n}\n\n/** The Payload instances that already logged a vendor filling both slots, so a busy site hears it once. */\nconst warnedSharedVendor = new WeakSet<Payload>()\n\n/** Why the second slot of one vendor kind is left out, logged once per instance. */\nconst warnSharedVendor = (\n\tpayload: Payload | undefined,\n\targs: { slot: CaptureSlot; adapterId: string; kind: CaptureClientKind; first: TrackerSlotConfig }\n): void => {\n\tif (!payload || warnedSharedVendor.has(payload)) {\n\t\treturn\n\t}\n\twarnedSharedVendor.add(payload)\n\tpayload.logger?.warn(\n\t\t`analytics: the ${args.slot} slot resolved to \"${args.adapterId}\", a second ${args.kind} slot beside \"${args.first.adapterId}\" on the ${args.first.slot} slot. Two slots of one vendor share its one client in the browser, so neither slot's gate could be answered alone and the ${args.slot} slot's events could land in the other slot's project: the ${args.slot} slot is left out of the tracker config. Logged once.`\n\t)\n}\n\n/**\n * The per-request tracker config, one entry per capturing slot in slot order. Public and anonymous\n * (the visitor's request, no user or cookies), so any failure drops a slot instead of erroring.\n */\nexport const resolveTrackerConfig = async (args: {\n\truntime: AnalyticsRuntime\n\treq: PayloadRequest\n\t/** The page is rendered in draft mode, which `capture.skip.previews` leaves uncounted. */\n\tdraft?: boolean\n}): Promise<TrackerConfig> => {\n\tconst { runtime } = args\n\tconst req = captureRequest(args.req)\n\tconst config = req.payload?.config ?? {}\n\tconst routes = analyticsRoutes(req.payload?.config)\n\t// One scope resolution for the whole config: the slots and the goals must agree on it,\n\t// and the host's resolver can be as expensive as a database read.\n\tconst scope = await scopeFor(runtime, req)\n\tconst exclusion = exclusionFor(runtime, req, scope)\n\tconst slots: TrackerSlotConfig[] = []\n\tconst filled = new Set<string>()\n\tfor (const slot of CAPTURE_SLOTS) {\n\t\tconst adapter = await resolveSlotAdapterFor({ runtime, req, slot, scope })\n\t\tconst capture = adapter?.capture\n\t\t// One adapter fills one slot: two sinks for it would send every event twice.\n\t\tif (!adapter || !capture || filled.has(adapter.id)) {\n\t\t\tcontinue\n\t\t}\n\t\tconst kind = capture.client.kind\n\t\t// Two slots of one vendor share its one browser global, so neither gate could be answered alone.\n\t\tconst first = slots.find((entry) => entry.kind === kind)\n\t\tif (first) {\n\t\t\twarnSharedVendor(req.payload, { slot, adapterId: adapter.id, kind, first })\n\t\t\tcontinue\n\t\t}\n\t\tconst override = runtime.capturePaths?.[slot]\n\t\tconst path = override\n\t\t\t? appPath(normalizeMountPath(override))\n\t\t\t: apiPath(config, `${routes.proxy}/${slot}`)\n\t\tconst gated = gateHolds(runtime, { slot, adapterId: adapter.id, kind }, (err) =>\n\t\t\treq.payload?.logger?.warn(\n\t\t\t\t`analytics: capture.gate threw for the ${slot} slot, which waits: ${String(err)}`\n\t\t\t)\n\t\t)\n\t\ttry {\n\t\t\tslots.push({\n\t\t\t\tslot,\n\t\t\t\tkind,\n\t\t\t\tadapterId: adapter.id,\n\t\t\t\tpath,\n\t\t\t\tsnippet: withExclusionPrelude(capture.snippet({ path, scope }), exclusion?.param),\n\t\t\t\tclient: capture.client,\n\t\t\t\tgated,\n\t\t\t})\n\t\t\tfilled.add(adapter.id)\n\t\t} catch (err) {\n\t\t\treq.payload?.logger?.warn(\n\t\t\t\t`analytics: capture snippet for \"${adapter.id}\" failed, dropping the ${slot} slot: ${String(err)}`\n\t\t\t)\n\t\t}\n\t}\n\treturn {\n\t\tslots,\n\t\tautoCapture: runtime.autoCapture ?? DEFAULT_AUTO_CAPTURE,\n\t\tgoals: trackerGoals(await goalsFor(runtime, req, scope)),\n\t\tingestPath: apiPath(config, runtime.ingestPath ?? routes.ingest),\n\t\t...(exclusion ? { exclusion } : {}),\n\t\t...skipFields(runtime, config, args.draft === true),\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA+BA,MAAM,eAAe,WAAkD;CACtE,MAAM,UAAU,eAAe;EAC9B,YAAY,OAAO,QAAQ,SAAS;EACpC,MAAM;EACN,WAAW,OAAO;EAClB,iBAAiB;CAClB,CAAC;CACD,IAAI;CACJ,IAAI,OAAO;CACX,IAAI,gBAAgB,KAAK,OAAO,GAC/B,IAAI;EACH,MAAM,MAAM,IAAI,IAAI,OAAO;EAC3B,SAAS,IAAI;EACb,OAAO,IAAI;CACZ,QAAQ,CAER;CAED,OAAO;EACN,GAAI,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ,aAAa,MAAM,EAAE;EAC/D,MAAM,aAAa,KAAK,QAAQ,QAAQ,EAAE,KA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AW,QAAQ;GAAI;EAAK,IAAI,QACxE,IAAI,SAAS,QAAQ,KACpB,yCAAyC,KAAK,sBAAsB,OAAO,GAAG,GAC/E,CACD;EACA,IAAI;GACH,MAAM,KAAK;IACV;IACA;IACA,WAAW,QAAQ;IACnB;IACA,SAAS,qBAAqB,QAAQ,QAAQ;KAAE;KAAM;IAAM,CAAC,GAAG,WAAW,KAAK;IAChF,QAAQ,QAAQ;IAChB;GACD,CAAC;GACD,OAAO,IAAI,QAAQ,EAAE;EACtB,SAAS,KAAK;GACb,IAAI,SAAS,QAAQ,KACpB,mCAAmC,QAAQ,GAAG,yBAAyB,KAAK,SAAS,OAAO,GAAG,GAChG;EACD;CACD;CACA,OAAO;EACN;EACA,aAAa,QAAQ,eAAe;EACpC,OAAO,aAAa,MAAM,SAAS,SAAS,KAAK,KAAK,CAAC;EACvD,YAAY,QAAQ,QAAQ,QAAQ,cAAc,OAAO,MAAM;EAC/D,GAAI,YAAY,EAAE,UAAU,IAAI,CAAC;EACjC,GAAG,WAAW,SAAS,QAAQ,KAAK,UAAU,IAAI;CACnD;AACD"}
1
+ {"version":3,"file":"trackerConfig.js","names":[],"sources":["../../src/capture/trackerConfig.ts"],"sourcesContent":["import type { Payload, PayloadRequest, SanitizedConfig } from 'payload'\nimport { formatAdminURL } from 'payload/shared'\nimport type { ResolvedGoal } from '../goals/resolver'\nimport { apiPath, appPath } from '../plugin/apiPath'\nimport { analyticsRoutes } from '../plugin/routes'\nimport {\n\ttype AnalyticsRuntime,\n\tresolveCaptureScopeFor,\n\tresolveGoalsDetailedFor,\n} from '../plugin/runtime'\nimport {\n\ttype AdminDigest,\n\ttype CaptureClientKind,\n\ttype CaptureSlot,\n\tDEFAULT_AUTO_CAPTURE,\n\ttype TrackerConfig,\n\ttype TrackerExclusion,\n\ttype TrackerGoal,\n\ttype TrackerSlotConfig,\n} from '../tracker/config'\nimport { DEFAULT_TRACKER_SKIP } from '../tracker/skip'\nimport { captureRequest } from './captureRequest'\nimport { withExclusionPrelude } from './exclusionPrelude'\nimport { exclusionToken, exclusionTokenHash, publicDigest } from './exclusionToken'\nimport { normalizeMountPath } from './mountPath'\nimport { CAPTURE_SLOTS, gateHolds, resolveSlotAdapterFor } from './slots'\n\n/**\n * The admin's address as a page reaches it, behind the Next basePath, as digests: its origin only\n * when `serverURL` puts it on one, its path without a trailing slash.\n */\nconst adminDigest = (config: Partial<SanitizedConfig>): AdminDigest => {\n\tconst address = formatAdminURL({\n\t\tadminRoute: config.routes?.admin ?? '/admin',\n\t\tpath: '',\n\t\tserverURL: config.serverURL,\n\t\tincludeBasePath: true,\n\t})\n\tlet origin: string | undefined\n\tlet path = address\n\tif (/^https?:\\/\\//i.test(address)) {\n\t\ttry {\n\t\t\tconst url = new URL(address)\n\t\t\torigin = url.origin\n\t\t\tpath = url.pathname\n\t\t} catch {\n\t\t\t// A serverURL that does not parse: its digest matches no window, so no page reads as a preview.\n\t\t}\n\t}\n\treturn {\n\t\t...(origin === undefined ? {} : { origin: publicDigest(origin) }),\n\t\tpath: publicDigest(path.replace(/\\/+$/, '') || '/'),\n\t}\n}\n\n/** What the config says about skipping: the install's choice when not the default, and the admin. */\nconst skipFields = (\n\truntime: AnalyticsRuntime,\n\tconfig: Partial<SanitizedConfig>,\n\tdraft: boolean\n): Pick<TrackerConfig, 'skip' | 'draft' | 'admin'> => {\n\tconst skip = runtime.captureSkip ?? DEFAULT_TRACKER_SKIP\n\tconst changed =\n\t\tskip.automation !== DEFAULT_TRACKER_SKIP.automation ||\n\t\tskip.previews !== DEFAULT_TRACKER_SKIP.previews\n\treturn {\n\t\t...(changed ? { skip: { ...skip } } : {}),\n\t\t...(draft ? { draft: true } : {}),\n\t\t...(skip.previews ? { admin: adminDigest(config) } : {}),\n\t}\n}\n\nconst trackerGoals = (goals: ResolvedGoal[]): TrackerGoal[] =>\n\tgoals\n\t\t.filter((entry) => entry.source !== 'builtin')\n\t\t.map(({ goal: { slug, match, value, currency } }) => ({\n\t\t\tslug,\n\t\t\tmatch,\n\t\t\t...(value ? { value } : {}),\n\t\t\t...(currency ? { currency } : {}),\n\t\t}))\n\n/** The visit's scope, or null when the host's resolver has none or throws. */\nconst scopeFor = async (runtime: AnalyticsRuntime, req: PayloadRequest): Promise<string | null> => {\n\ttry {\n\t\treturn await resolveCaptureScopeFor(runtime, req)\n\t} catch (err) {\n\t\treq.payload?.logger?.warn(`analytics: tracker config scope resolution failed: ${String(err)}`)\n\t\treturn null\n\t}\n}\n\n/** The scope's merged goals, falling back to the config goals when the merge fails. */\nconst goalsFor = async (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tscope: string | null\n): Promise<ResolvedGoal[]> => {\n\ttry {\n\t\treturn await resolveGoalsDetailedFor(runtime, req, scope)\n\t} catch (err) {\n\t\treq.payload?.logger?.warn(\n\t\t\t`analytics: tracker config goals resolution failed, falling back to config goals: ${String(err)}`\n\t\t)\n\t\treturn (runtime.goals ?? []).map((goal) => ({ goal, source: 'config' as const }))\n\t}\n}\n\n/** The scope's exclusion link as the tracker sees it: the token's hash, never the token. */\nconst exclusionFor = (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tscope: string | null\n): TrackerExclusion | undefined => {\n\tconst secret = req.payload?.secret\n\tif (!runtime.exclusion || typeof secret !== 'string' || secret === '') {\n\t\treturn undefined\n\t}\n\treturn {\n\t\tparam: runtime.exclusion.param,\n\t\ttokenHash: exclusionTokenHash(exclusionToken(secret, scope)),\n\t}\n}\n\n/** The Payload instances that already logged a vendor filling both slots, so a busy site hears it once. */\nconst warnedSharedVendor = new WeakSet<Payload>()\n\n/**\n * The vendors whose browser SDK runs a second client beside the first, each with its own project,\n * gate and storage: a second slot of one of these kinds captures through a client named after it.\n */\nconst NAMED_CLIENT_KINDS: ReadonlySet<CaptureClientKind> = new Set<CaptureClientKind>(['posthog'])\n\n/** Why the second slot of one vendor kind is left out, logged once per instance. */\nconst warnSharedVendor = (\n\tpayload: Payload | undefined,\n\targs: { slot: CaptureSlot; adapterId: string; kind: CaptureClientKind; first: TrackerSlotConfig }\n): void => {\n\tif (!payload || warnedSharedVendor.has(payload)) {\n\t\treturn\n\t}\n\twarnedSharedVendor.add(payload)\n\tpayload.logger?.warn(\n\t\t`analytics: the ${args.slot} slot resolved to \"${args.adapterId}\", a second ${args.kind} slot beside \"${args.first.adapterId}\" on the ${args.first.slot} slot. ${args.kind} runs one client per page, so two slots of it would share that client: neither slot's gate could be answered alone and the ${args.slot} slot's events could land in the other slot's project. The ${args.slot} slot is left out of the tracker config; only PostHog runs a second client beside the first. Logged once.`\n\t)\n}\n\n/**\n * The per-request tracker config, one entry per capturing slot in slot order. Public and anonymous\n * (the visitor's request, no user or cookies), so any failure drops a slot instead of erroring.\n */\nexport const resolveTrackerConfig = async (args: {\n\truntime: AnalyticsRuntime\n\treq: PayloadRequest\n\t/** The page is rendered in draft mode, which `capture.skip.previews` leaves uncounted. */\n\tdraft?: boolean\n}): Promise<TrackerConfig> => {\n\tconst { runtime } = args\n\tconst req = captureRequest(args.req)\n\tconst config = req.payload?.config ?? {}\n\tconst routes = analyticsRoutes(req.payload?.config)\n\t// One scope resolution for the whole config: the slots and the goals must agree on it,\n\t// and the host's resolver can be as expensive as a database read.\n\tconst scope = await scopeFor(runtime, req)\n\tconst exclusion = exclusionFor(runtime, req, scope)\n\tconst slots: TrackerSlotConfig[] = []\n\tconst filled = new Set<string>()\n\tfor (const slot of CAPTURE_SLOTS) {\n\t\tconst adapter = await resolveSlotAdapterFor({ runtime, req, slot, scope })\n\t\tconst capture = adapter?.capture\n\t\t// One adapter fills one slot: two sinks for it would send every event twice.\n\t\tif (!adapter || !capture || filled.has(adapter.id)) {\n\t\t\tcontinue\n\t\t}\n\t\tconst kind = capture.client.kind\n\t\tconst first = slots.find((entry) => entry.kind === kind)\n\t\tif (first && !NAMED_CLIENT_KINDS.has(kind)) {\n\t\t\twarnSharedVendor(req.payload, { slot, adapterId: adapter.id, kind, first })\n\t\t\tcontinue\n\t\t}\n\t\tconst instance = first ? slot : undefined\n\t\tconst override = runtime.capturePaths?.[slot]\n\t\tconst path = override\n\t\t\t? appPath(normalizeMountPath(override))\n\t\t\t: apiPath(config, `${routes.proxy}/${slot}`)\n\t\tconst gated = gateHolds(runtime, { slot, adapterId: adapter.id, kind }, (err) =>\n\t\t\treq.payload?.logger?.warn(\n\t\t\t\t`analytics: capture.gate threw for the ${slot} slot, which waits: ${String(err)}`\n\t\t\t)\n\t\t)\n\t\ttry {\n\t\t\tslots.push({\n\t\t\t\tslot,\n\t\t\t\tkind,\n\t\t\t\tadapterId: adapter.id,\n\t\t\t\tpath,\n\t\t\t\tsnippet: withExclusionPrelude(\n\t\t\t\t\tcapture.snippet({ path, scope, ...(instance ? { instance } : {}) }),\n\t\t\t\t\texclusion?.param\n\t\t\t\t),\n\t\t\t\tclient: capture.client,\n\t\t\t\t...(instance ? { instance } : {}),\n\t\t\t\tgated,\n\t\t\t})\n\t\t\tfilled.add(adapter.id)\n\t\t} catch (err) {\n\t\t\treq.payload?.logger?.warn(\n\t\t\t\t`analytics: capture snippet for \"${adapter.id}\" failed, dropping the ${slot} slot: ${String(err)}`\n\t\t\t)\n\t\t}\n\t}\n\treturn {\n\t\tslots,\n\t\tautoCapture: runtime.autoCapture ?? DEFAULT_AUTO_CAPTURE,\n\t\tgoals: trackerGoals(await goalsFor(runtime, req, scope)),\n\t\tingestPath: apiPath(config, runtime.ingestPath ?? routes.ingest),\n\t\t...(exclusion ? { exclusion } : {}),\n\t\t...skipFields(runtime, config, args.draft === true),\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA+BA,MAAM,eAAe,WAAkD;CACtE,MAAM,UAAU,eAAe;EAC9B,YAAY,OAAO,QAAQ,SAAS;EACpC,MAAM;EACN,WAAW,OAAO;EAClB,iBAAiB;CAClB,CAAC;CACD,IAAI;CACJ,IAAI,OAAO;CACX,IAAI,gBAAgB,KAAK,OAAO,GAC/B,IAAI;EACH,MAAM,MAAM,IAAI,IAAI,OAAO;EAC3B,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mB,IAAI,IAAI,GAAG;GAC3C,iBAAiB,IAAI,SAAS;IAAE;IAAM,WAAW,QAAQ;IAAI;IAAM;GAAM,CAAC;GAC1E;EACD;EACA,MAAM,WAAW,QAAQ,OAAO,KAAA;EAChC,MAAM,WAAW,QAAQ,eAAe;EACxC,MAAM,OAAO,WACV,QAAQ,mBAAmB,QAAQ,CAAC,IACpC,QAAQ,QAAQ,GAAG,OAAO,MAAM,GAAG,MAAM;EAC5C,MAAM,QAAQ,UAAU,SAAS;GAAE;GAAM,WAAW,QAAQ;GAAI;EAAK,IAAI,QACxE,IAAI,SAAS,QAAQ,KACpB,yCAAyC,KAAK,sBAAsB,OAAO,GAAG,GAC/E,CACD;EACA,IAAI;GACH,MAAM,KAAK;IACV;IACA;IACA,WAAW,QAAQ;IACnB;IACA,SAAS,qBACR,QAAQ,QAAQ;KAAE;KAAM;KAAO,GAAI,WAAW,EAAE,SAAS,IAAI,CAAC;IAAG,CAAC,GAClE,WAAW,KACZ;IACA,QAAQ,QAAQ;IAChB,GAAI,WAAW,EAAE,SAAS,IAAI,CAAC;IAC/B;GACD,CAAC;GACD,OAAO,IAAI,QAAQ,EAAE;EACtB,SAAS,KAAK;GACb,IAAI,SAAS,QAAQ,KACpB,mCAAmC,QAAQ,GAAG,yBAAyB,KAAK,SAAS,OAAO,GAAG,GAChG;EACD;CACD;CACA,OAAO;EACN;EACA,aAAa,QAAQ,eAAe;EACpC,OAAO,aAAa,MAAM,SAAS,SAAS,KAAK,KAAK,CAAC;EACvD,YAAY,QAAQ,QAAQ,QAAQ,cAAc,OAAO,MAAM;EAC/D,GAAI,YAAY,EAAE,UAAU,IAAI,CAAC;EACjC,GAAG,WAAW,SAAS,QAAQ,KAAK,UAAU,IAAI;CACnD;AACD"}
@@ -1,8 +1,8 @@
1
1
  import { supportsGranularity } from "../core/granularity.js";
2
2
  import { HOUR_MS, addDaysInTz, startOfDayInTz, startOfHourInTz } from "../timeframe/tz.js";
3
+ import { combineMetricValues, emptyReading } from "../core/metricValues.js";
3
4
  import { addCalendarDays, calendarDayOf, calendarDayStart } from "../timeframe/calendar.js";
4
5
  import { bucketStartOf, bucketStarts } from "../native/engine/buckets.js";
5
- import { combineMetricValues, emptyReading } from "../core/metricValues.js";
6
6
  import { dayOfTimestamp } from "../surfacing/rebucket.js";
7
7
  import { unitForRange } from "./bucket.js";
8
8
  //#region src/charts/series.ts
@@ -10,6 +10,7 @@ const VIEW_KEYS = keysOf({
10
10
  defaultRange: true,
11
11
  defaultMetric: true,
12
12
  navLabel: true,
13
+ navLink: true,
13
14
  Component: true
14
15
  });
15
16
  const WIDGETS_KEYS = keysOf({
@@ -39,7 +40,8 @@ const WIDGET_WIDTHS = keysOf({
39
40
  const DEFAULT_VIEW = {
40
41
  path: "/analytics",
41
42
  defaultRange: "last30days",
42
- defaultMetric: "pageviews"
43
+ defaultMetric: "pageviews",
44
+ navLink: true
43
45
  };
44
46
  /** A label as Payload takes one without a function: a string, or a map of strings by language. */
45
47
  const isStaticLabel = (value) => typeof value === "string" || isRecord(value) && Object.values(value).every((text) => typeof text === "string");
@@ -84,10 +86,13 @@ const resolveView = (option) => {
84
86
  if (!TIMEFRAME_PRESETS.includes(defaultRange)) throw new Error(`analytics: unknown view.defaultRange "${String(defaultRange)}"`);
85
87
  const defaultMetric = option?.defaultMetric ?? DEFAULT_VIEW.defaultMetric;
86
88
  if (!(defaultMetric in METRIC_KEYS)) throw new Error(`analytics: unknown view.defaultMetric "${String(defaultMetric)}"`);
89
+ const navLink = option?.navLink ?? DEFAULT_VIEW.navLink;
90
+ if (typeof navLink !== "boolean") throw new Error(`analytics: view.navLink must be a boolean, got ${kindOf(navLink)}`);
87
91
  return {
88
92
  path,
89
93
  defaultRange,
90
94
  defaultMetric,
95
+ navLink,
91
96
  ...option?.navLabel !== void 0 ? { navLabel: option.navLabel } : {},
92
97
  ...option?.Component !== void 0 ? { Component: resolveComponent(option.Component, "view.Component") } : {}
93
98
  };