@10x-media/analytics 1.0.0-beta.15 → 1.0.0-beta.17

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 (163) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/README.md +1 -1
  3. package/dist/adapters/ga4/ga4.js +33 -2
  4. package/dist/adapters/ga4/ga4.js.map +1 -1
  5. package/dist/adapters/ga4/measurementId.js +4 -1
  6. package/dist/adapters/ga4/measurementId.js.map +1 -1
  7. package/dist/adapters/ga4/propertyId.js +17 -0
  8. package/dist/adapters/ga4/propertyId.js.map +1 -0
  9. package/dist/adapters/http/fetchJson.js +24 -1
  10. package/dist/adapters/http/fetchJson.js.map +1 -1
  11. package/dist/adapters/plausible/plausible.js +16 -1
  12. package/dist/adapters/plausible/plausible.js.map +1 -1
  13. package/dist/adapters/plausible/siteId.js +31 -0
  14. package/dist/adapters/plausible/siteId.js.map +1 -0
  15. package/dist/adapters/posthog/cloud.js +20 -0
  16. package/dist/adapters/posthog/cloud.js.map +1 -0
  17. package/dist/adapters/posthog/credentials.js +20 -0
  18. package/dist/adapters/posthog/credentials.js.map +1 -0
  19. package/dist/adapters/posthog/posthog.d.ts +3 -3
  20. package/dist/adapters/posthog/posthog.js +24 -10
  21. package/dist/adapters/posthog/posthog.js.map +1 -1
  22. package/dist/adapters/umami/umami.js +34 -7
  23. package/dist/adapters/umami/umami.js.map +1 -1
  24. package/dist/charts/series.js +1 -1
  25. package/dist/core/contract.d.ts +16 -1
  26. package/dist/core/contract.js.map +1 -1
  27. package/dist/core/options.d.ts +1 -1
  28. package/dist/core/options.js +1 -1
  29. package/dist/core/options.js.map +1 -1
  30. package/dist/core/scopedRead.js +62 -14
  31. package/dist/core/scopedRead.js.map +1 -1
  32. package/dist/core/sourceErrors.js +12 -1
  33. package/dist/core/sourceErrors.js.map +1 -1
  34. package/dist/core/sourceOptions.js +1 -1
  35. package/dist/core/sourceOptions.js.map +1 -1
  36. package/dist/core/sourcePolicy.d.ts +8 -1
  37. package/dist/core/sourcePolicy.js.map +1 -1
  38. package/dist/core/throttle.js +3 -1
  39. package/dist/core/throttle.js.map +1 -1
  40. package/dist/exports/adapters/contract.d.ts +1 -1
  41. package/dist/exports/adapters/ga4.d.ts +2 -2
  42. package/dist/exports/adapters/native.d.ts +2 -2
  43. package/dist/exports/adapters/plausible.d.ts +2 -2
  44. package/dist/exports/adapters/posthog.d.ts +2 -2
  45. package/dist/exports/adapters/umami.d.ts +2 -2
  46. package/dist/exports/client.d.ts +3 -1
  47. package/dist/exports/client.js +3 -1
  48. package/dist/exports/next.d.ts +2 -2
  49. package/dist/exports/testing.d.ts +2 -2
  50. package/dist/exports/types.d.ts +3 -3
  51. package/dist/fields/config/fetchSources.js +1 -1
  52. package/dist/fields/config/fetchSources.js.map +1 -1
  53. package/dist/goals/collection.js +3 -2
  54. package/dist/goals/collection.js.map +1 -1
  55. package/dist/goals/resolver.js +1 -1
  56. package/dist/index.d.ts +4 -3
  57. package/dist/index.js +50 -4
  58. package/dist/index.js.map +1 -1
  59. package/dist/native/geo/maxmindResolver.js +1 -1
  60. package/dist/native/nativeAdapter.js +1 -1
  61. package/dist/plugin/createRuntime.js +57 -13
  62. package/dist/plugin/createRuntime.js.map +1 -1
  63. package/dist/plugin/pluginCollections.js +4 -1
  64. package/dist/plugin/pluginCollections.js.map +1 -1
  65. package/dist/plugin/providerStatusEndpoint.js +80 -0
  66. package/dist/plugin/providerStatusEndpoint.js.map +1 -0
  67. package/dist/plugin/queryEndpoint.js +1 -1
  68. package/dist/plugin/queryEndpoint.js.map +1 -1
  69. package/dist/plugin/readContextForRequest.d.ts +4 -3
  70. package/dist/plugin/readContextForRequest.js +2 -2
  71. package/dist/plugin/readContextForRequest.js.map +1 -1
  72. package/dist/plugin/refreshEndpoint.js +1 -1
  73. package/dist/plugin/routes.d.ts +5 -0
  74. package/dist/plugin/routes.js +1 -0
  75. package/dist/plugin/routes.js.map +1 -1
  76. package/dist/plugin/runtime.js.map +1 -1
  77. package/dist/providers/ProviderConnection.d.ts +12 -0
  78. package/dist/providers/ProviderConnection.js +105 -0
  79. package/dist/providers/ProviderConnection.js.map +1 -0
  80. package/dist/providers/ProviderConnectionTest.d.ts +12 -0
  81. package/dist/providers/ProviderConnectionTest.js +55 -0
  82. package/dist/providers/ProviderConnectionTest.js.map +1 -0
  83. package/dist/providers/ProvidersListNotice.d.ts +1 -1
  84. package/dist/providers/ProvidersListNotice.js +3 -2
  85. package/dist/providers/ProvidersListNotice.js.map +1 -1
  86. package/dist/providers/collection.d.ts +1 -1
  87. package/dist/providers/collection.js +106 -41
  88. package/dist/providers/collection.js.map +1 -1
  89. package/dist/providers/connectionCheck.d.ts +1 -0
  90. package/dist/providers/connectionCheck.js +80 -0
  91. package/dist/providers/connectionCheck.js.map +1 -0
  92. package/dist/providers/connectionState.js +53 -0
  93. package/dist/providers/connectionState.js.map +1 -0
  94. package/dist/providers/factory.d.ts +1 -3
  95. package/dist/providers/factory.js +18 -21
  96. package/dist/providers/factory.js.map +1 -1
  97. package/dist/providers/hosts.js +31 -9
  98. package/dist/providers/hosts.js.map +1 -1
  99. package/dist/providers/ids.d.ts +6 -0
  100. package/dist/providers/ids.js +32 -0
  101. package/dist/providers/ids.js.map +1 -0
  102. package/dist/providers/providerStatusClient.js +60 -0
  103. package/dist/providers/providerStatusClient.js.map +1 -0
  104. package/dist/providers/registry.js +56 -20
  105. package/dist/providers/registry.js.map +1 -1
  106. package/dist/providers/retarget.js +39 -8
  107. package/dist/providers/retarget.js.map +1 -1
  108. package/dist/providers/secrets.d.ts +1 -1
  109. package/dist/providers/secrets.js.map +1 -1
  110. package/dist/providers/status.d.ts +1 -0
  111. package/dist/providers/status.js +181 -0
  112. package/dist/providers/status.js.map +1 -0
  113. package/dist/surfacing/classifyError.js +37 -5
  114. package/dist/surfacing/classifyError.js.map +1 -1
  115. package/dist/surfacing/engine.js +2 -2
  116. package/dist/surfacing/engine.js.map +1 -1
  117. package/dist/surfacing/lanes.js +29 -22
  118. package/dist/surfacing/lanes.js.map +1 -1
  119. package/dist/surfacing/rebucket.js +1 -1
  120. package/dist/testing/settle.d.ts +2 -1
  121. package/dist/testing/settle.js +6 -2
  122. package/dist/testing/settle.js.map +1 -1
  123. package/dist/tracker/sinks/ga4.js +2 -2
  124. package/dist/translations/ar.js +43 -8
  125. package/dist/translations/ar.js.map +1 -1
  126. package/dist/translations/de.js +43 -8
  127. package/dist/translations/de.js.map +1 -1
  128. package/dist/translations/en.js +43 -8
  129. package/dist/translations/en.js.map +1 -1
  130. package/dist/translations/es.js +43 -8
  131. package/dist/translations/es.js.map +1 -1
  132. package/dist/translations/fr.js +43 -8
  133. package/dist/translations/fr.js.map +1 -1
  134. package/dist/translations/id.js +43 -8
  135. package/dist/translations/id.js.map +1 -1
  136. package/dist/translations/keys.d.ts +35 -0
  137. package/dist/translations/keys.js +35 -0
  138. package/dist/translations/keys.js.map +1 -1
  139. package/dist/translations/ko.js +43 -8
  140. package/dist/translations/ko.js.map +1 -1
  141. package/dist/translations/pt.js +43 -8
  142. package/dist/translations/pt.js.map +1 -1
  143. package/dist/translations/ru.js +43 -8
  144. package/dist/translations/ru.js.map +1 -1
  145. package/dist/translations/uk.js +43 -8
  146. package/dist/translations/uk.js.map +1 -1
  147. package/dist/translations/zh.js +43 -8
  148. package/dist/translations/zh.js.map +1 -1
  149. package/dist/ui/analytics.css +63 -0
  150. package/dist/ui/components/SourcesNoticeBanner.js +4 -3
  151. package/dist/ui/components/SourcesNoticeBanner.js.map +1 -1
  152. package/dist/view/ViewSections.js +9 -2
  153. package/dist/view/ViewSections.js.map +1 -1
  154. package/dist/view/sections/EmptyStates.js +5 -4
  155. package/dist/view/sections/EmptyStates.js.map +1 -1
  156. package/dist/view/sections/OverviewCards.js +6 -2
  157. package/dist/view/sections/OverviewCards.js.map +1 -1
  158. package/dist/view/sections/SourceConnectionNote.js +56 -0
  159. package/dist/view/sections/SourceConnectionNote.js.map +1 -0
  160. package/dist/view/viewProps.d.ts +2 -0
  161. package/dist/view/viewProps.js +2 -1
  162. package/dist/view/viewProps.js.map +1 -1
  163. package/package.json +5 -5
@@ -0,0 +1 @@
1
+ {"version":3,"file":"siteId.js","names":[],"sources":["../../../src/adapters/plausible/siteId.ts"],"sourcesContent":["import type { TextFieldSingleValidation } from 'payload'\nimport { keys } from '../../translations/keys'\nimport { asTranslate } from '../../translations/server'\n\n/** Segments of letters, digits, dots and hyphens in any script, slash-separated for a subfolder site. */\nconst SITE_DOMAIN_PATTERN = /^[\\p{L}\\p{N}.-]+(?:\\/[\\p{L}\\p{N}.-]+)*$/u\n\n/**\n * A Plausible site as Plausible stores it: lowercase, without a scheme, `www.` or a trailing slash,\n * a subfolder site with its path (`example.com/blog`). Plausible's own form strips the rest, so a\n * pasted address saves here but every read answers \"Invalid API key or site ID\". Empty is allowed:\n * the field is optional.\n */\nexport const validateSiteDomain: TextFieldSingleValidation = (value, { req }) => {\n\tconst site = value?.trim()\n\treturn !site ||\n\t\t(SITE_DOMAIN_PATTERN.test(site) && site === site.toLowerCase() && !site.startsWith('www.'))\n\t\t? true\n\t\t: asTranslate(req.t)(keys.providerErrorSiteDomain)\n}\n\n/**\n * The Website address the tracker sends to: one site, or several separated by commas, each counting\n * the pageview on its own dashboard. Each one follows {@link validateSiteDomain}.\n */\nexport const validateSiteDomains: TextFieldSingleValidation = (value, args) => {\n\tif (!value?.trim()) {\n\t\treturn true\n\t}\n\tfor (const site of value.split(',')) {\n\t\tconst valid = site.trim() !== '' && validateSiteDomain(site, args)\n\t\tif (valid !== true) {\n\t\t\treturn valid || asTranslate(args.req.t)(keys.providerErrorSiteDomain)\n\t\t}\n\t}\n\treturn true\n}\n"],"mappings":";;;;AAKA,MAAM,sBAAsB;;;;;;;AAQ5B,MAAa,sBAAiD,OAAO,EAAE,UAAU;CAChF,MAAM,OAAO,OAAO,KAAK;CACzB,OAAO,CAAC,QACN,oBAAoB,KAAK,IAAI,KAAK,SAAS,KAAK,YAAY,KAAK,CAAC,KAAK,WAAW,MAAM,IACvF,OACA,YAAY,IAAI,CAAC,EAAE,KAAK,uBAAuB;AACnD;;;;;AAMA,MAAa,uBAAkD,OAAO,SAAS;CAC9E,IAAI,CAAC,OAAO,KAAK,GAChB,OAAO;CAER,KAAK,MAAM,QAAQ,MAAM,MAAM,GAAG,GAAG;EACpC,MAAM,QAAQ,KAAK,KAAK,MAAM,MAAM,mBAAmB,MAAM,IAAI;EACjE,IAAI,UAAU,MACb,OAAO,SAAS,YAAY,KAAK,IAAI,CAAC,EAAE,KAAK,uBAAuB;CAEtE;CACA,OAAO;AACR"}
@@ -0,0 +1,20 @@
1
+ import { hostnameOf } from "../http/baseUrl.js";
2
+ //#region src/adapters/posthog/cloud.ts
3
+ /**
4
+ * PostHog Cloud's app hosts and the region each serves: the region's own address, and the older US
5
+ * address `app.posthog.com`. Its own module so the providers collection checks a Host against its
6
+ * Region on the adapter's terms without loading the adapter.
7
+ */
8
+ const POSTHOG_CLOUD_HOSTS = {
9
+ "us.posthog.com": "us",
10
+ "eu.posthog.com": "eu",
11
+ "app.posthog.com": "us"
12
+ };
13
+ /** The cloud region an address belongs to, or null for a self-hosted instance or no address. */
14
+ const cloudRegionOf = (address) => POSTHOG_CLOUD_HOSTS[hostnameOf(address)] ?? null;
15
+ /** Where a region's app and Query API answer. */
16
+ const cloudAppHost = (region) => `https://${region}.posthog.com`;
17
+ //#endregion
18
+ export { POSTHOG_CLOUD_HOSTS, cloudAppHost, cloudRegionOf };
19
+
20
+ //# sourceMappingURL=cloud.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cloud.js","names":[],"sources":["../../../src/adapters/posthog/cloud.ts"],"sourcesContent":["import { hostnameOf } from '../http/baseUrl'\n\n/** A PostHog Cloud region. */\nexport type PosthogRegion = 'us' | 'eu'\n\n/**\n * PostHog Cloud's app hosts and the region each serves: the region's own address, and the older US\n * address `app.posthog.com`. Its own module so the providers collection checks a Host against its\n * Region on the adapter's terms without loading the adapter.\n */\nexport const POSTHOG_CLOUD_HOSTS: Readonly<Record<string, PosthogRegion>> = {\n\t'us.posthog.com': 'us',\n\t'eu.posthog.com': 'eu',\n\t'app.posthog.com': 'us',\n}\n\n/** The cloud region an address belongs to, or null for a self-hosted instance or no address. */\nexport const cloudRegionOf = (address: string): PosthogRegion | null =>\n\tPOSTHOG_CLOUD_HOSTS[hostnameOf(address)] ?? null\n\n/** Where a region's app and Query API answer. */\nexport const cloudAppHost = (region: PosthogRegion): string => `https://${region}.posthog.com`\n"],"mappings":";;;;;;;AAUA,MAAa,sBAA+D;CAC3E,kBAAkB;CAClB,kBAAkB;CAClB,mBAAmB;AACpB;;AAGA,MAAa,iBAAiB,YAC7B,oBAAoB,WAAW,OAAO,MAAM;;AAG7C,MAAa,gBAAgB,WAAkC,WAAW,OAAO"}
@@ -0,0 +1,20 @@
1
+ import { keys } from "../../translations/keys.js";
2
+ import { asTranslate } from "../../translations/server.js";
3
+ //#region src/adapters/posthog/credentials.ts
4
+ /** PostHog's key prefixes (posthog/models/utils.py): a project token is public, phx_ and phs_ keys are private. */
5
+ const PROJECT_TOKEN_PREFIX = "phc_";
6
+ const PRIVATE_KEY_PREFIXES = ["phx_", "phs_"];
7
+ /**
8
+ * Catches a project token pasted into the personal API key field. Empty passes: on a stored document
9
+ * it keeps the saved key.
10
+ */
11
+ const validatePersonalApiKey = (value, { req }) => value?.trim().startsWith(PROJECT_TOKEN_PREFIX) ? asTranslate(req.t)(keys.providerErrorPosthogTokenAsApiKey) : true;
12
+ /**
13
+ * Catches a private key pasted into the project token field, which the tracker config serves to
14
+ * every visitor's browser.
15
+ */
16
+ const validateProjectToken = (value, { req }) => PRIVATE_KEY_PREFIXES.some((prefix) => value?.trim().startsWith(prefix)) ? asTranslate(req.t)(keys.providerErrorPosthogKeyAsToken) : true;
17
+ //#endregion
18
+ export { validatePersonalApiKey, validateProjectToken };
19
+
20
+ //# sourceMappingURL=credentials.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"credentials.js","names":[],"sources":["../../../src/adapters/posthog/credentials.ts"],"sourcesContent":["import type { TextFieldSingleValidation } from 'payload'\nimport { keys } from '../../translations/keys'\nimport { asTranslate } from '../../translations/server'\n\n/** PostHog's key prefixes (posthog/models/utils.py): a project token is public, phx_ and phs_ keys are private. */\nconst PROJECT_TOKEN_PREFIX = 'phc_'\nconst PRIVATE_KEY_PREFIXES = ['phx_', 'phs_']\n\n/**\n * Catches a project token pasted into the personal API key field. Empty passes: on a stored document\n * it keeps the saved key.\n */\nexport const validatePersonalApiKey: TextFieldSingleValidation = (value, { req }) =>\n\tvalue?.trim().startsWith(PROJECT_TOKEN_PREFIX)\n\t\t? asTranslate(req.t)(keys.providerErrorPosthogTokenAsApiKey)\n\t\t: true\n\n/**\n * Catches a private key pasted into the project token field, which the tracker config serves to\n * every visitor's browser.\n */\nexport const validateProjectToken: TextFieldSingleValidation = (value, { req }) =>\n\tPRIVATE_KEY_PREFIXES.some((prefix) => value?.trim().startsWith(prefix))\n\t\t? asTranslate(req.t)(keys.providerErrorPosthogKeyAsToken)\n\t\t: true\n"],"mappings":";;;;AAKA,MAAM,uBAAuB;AAC7B,MAAM,uBAAuB,CAAC,QAAQ,MAAM;;;;;AAM5C,MAAa,0BAAqD,OAAO,EAAE,UAC1E,OAAO,KAAK,EAAE,WAAW,oBAAoB,IAC1C,YAAY,IAAI,CAAC,EAAE,KAAK,iCAAiC,IACzD;;;;;AAMJ,MAAa,wBAAmD,OAAO,EAAE,UACxE,qBAAqB,MAAM,WAAW,OAAO,KAAK,EAAE,WAAW,MAAM,CAAC,IACnE,YAAY,IAAI,CAAC,EAAE,KAAK,8BAA8B,IACtD"}
@@ -15,7 +15,7 @@ interface PosthogConfig {
15
15
  /** Personal API key with the "Query Read" scope (phx_...). Never exposed to the browser. */
16
16
  apiKey: string;
17
17
  /**
18
- * API address. Defaults to US Cloud; EU is https://eu.posthog.com, self-host is your instance's
18
+ * API address. Unset, the `region`'s cloud, US Cloud without one; self-host is your instance's
19
19
  * address, with the base path when a reverse proxy serves it under one.
20
20
  */
21
21
  host?: string;
@@ -27,8 +27,8 @@ interface PosthogConfig {
27
27
  */
28
28
  scopeProperty?: string;
29
29
  /**
30
- * PostHog Cloud region for the proxied capture routes. Derived from `host` when omitted. A
31
- * self-hosted `host` takes capture itself and ignores this.
30
+ * PostHog Cloud region: where capture goes and, with no `host`, where reads go. Derived from `host`
31
+ * when omitted. A self-hosted `host` takes both and ignores this.
32
32
  */
33
33
  region?: 'us' | 'eu';
34
34
  /**
@@ -3,19 +3,20 @@ import { currentTime } from "../../core/clock.js";
3
3
  import { adapterLabel } from "../../core/sourceLabel.js";
4
4
  import { jsLiteral } from "../../capture/jsLiteral.js";
5
5
  import { WITHOUT_CONSENT_LEVELS, adapterWithoutConsent, cookielessCapture } from "../../capture/withoutConsent.js";
6
+ import { hostnameOf, withoutTrailingSlash } from "../http/baseUrl.js";
7
+ import { cloudAppHost, cloudRegionOf } from "./cloud.js";
6
8
  import { vendorReading } from "../../core/metricValues.js";
7
9
  import { emptyGoalBreakdown, goalHint, hintFailed, hintSlugs } from "../goalRead.js";
8
10
  import { declaredFilters, everyOperatorOn, firstMapped, mappedKeys, providerMetricKeys } from "../mapping.js";
9
11
  import { readTime } from "../readTime.js";
10
12
  import { dayIso, hourIso } from "../series.js";
13
+ import { fetchJson } from "../http/fetchJson.js";
11
14
  import { upstreamJson } from "../upstream.js";
12
- import { hostnameOf, withoutTrailingSlash } from "../http/baseUrl.js";
13
15
  import { createProjectCheck } from "./projectCheck.js";
14
16
  //#region src/adapters/posthog/posthog.ts
15
- const US_CLOUD = "https://us.posthog.com";
16
17
  const resolveRegion = (config) => {
17
18
  if (config.region) return config.region;
18
- return config.host?.includes("eu.posthog.com") ? "eu" : "us";
19
+ return config.host && cloudRegionOf(config.host) || "us";
19
20
  };
20
21
  /**
21
22
  * PostHog's official stub, trimmed: one self-sequencing script whose `init` injects `array.js` from
@@ -48,7 +49,7 @@ const captureHosts = (config) => {
48
49
  assets: `https://${region}-assets.i.posthog.com`,
49
50
  ingest: `https://${region}.i.posthog.com`,
50
51
  cloud: true,
51
- ui: ui ?? `https://${region}.posthog.com`
52
+ ui: ui ?? cloudAppHost(region)
52
53
  };
53
54
  };
54
55
  /**
@@ -201,11 +202,11 @@ const FILTER_SQL = {
201
202
  };
202
203
  const SERIES_BUCKETS = {
203
204
  day: {
204
- fn: "toStartOfDay",
205
+ expr: (zone) => `toStartOfDay(timestamp, ${zone})`,
205
206
  isoOf: dayIso
206
207
  },
207
208
  hour: {
208
- fn: "toStartOfHour",
209
+ expr: (zone) => `toStartOfHour(toTimeZone(timestamp, ${zone}))`,
209
210
  isoOf: hourIso
210
211
  }
211
212
  };
@@ -215,7 +216,7 @@ const SERIES_BUCKETS = {
215
216
  */
216
217
  const utcDateTime = (d) => `toDateTime(${sqlString(d.toISOString().slice(0, 19).replace("T", " "))}, 'UTC')`;
217
218
  function posthog(config) {
218
- const host = withoutTrailingSlash(config.host ?? US_CLOUD);
219
+ const host = withoutTrailingSlash(config.host ?? cloudAppHost(resolveRegion(config)));
219
220
  const maxLookbackDays = config.maxLookbackDays !== void 0 ? config.maxLookbackDays : 730;
220
221
  const withoutConsent = adapterWithoutConsent(config.withoutConsent, "posthog({ withoutConsent })", WITHOUT_CONSENT_LEVELS);
221
222
  const capabilities = {
@@ -261,6 +262,19 @@ function posthog(config) {
261
262
  ...cookielessCapture({ kind: "switched" }, withoutConsent)
262
263
  } } : {},
263
264
  isConfigured: () => Boolean(config.projectId && config.apiKey),
265
+ async checkConnection(ctx) {
266
+ await fetchJson(`${host}/api/projects/${encodeURIComponent(config.projectId)}/query/`, {
267
+ method: "POST",
268
+ headers: { authorization: `Bearer ${config.apiKey}` },
269
+ body: { query: {
270
+ kind: "HogQLQuery",
271
+ query: "SELECT 1"
272
+ } },
273
+ provider: "posthog",
274
+ signal: ctx.signal,
275
+ ...config.fetch ? { fetch: config.fetch } : {}
276
+ });
277
+ },
264
278
  register(_config, context) {
265
279
  fillsCountingSlot = context?.adapterCountsWithoutConsent !== false;
266
280
  },
@@ -323,7 +337,7 @@ function posthog(config) {
323
337
  const tallyCookieless = (row, offset) => {
324
338
  if (countsCookielessColumn) cookieless += vendorReading("pageviews", row[offset + exprs.length]) ?? 0;
325
339
  };
326
- const runSql = (sql) => upstreamJson(ctx, `${host}/api/projects/${config.projectId}/query/`, {
340
+ const runSql = (sql) => upstreamJson(ctx, `${host}/api/projects/${encodeURIComponent(config.projectId)}/query/`, {
327
341
  method: "POST",
328
342
  headers: { authorization: `Bearer ${config.apiKey}` },
329
343
  body: { query: {
@@ -350,8 +364,8 @@ function posthog(config) {
350
364
  };
351
365
  const unit = !breakdown && (q.granularity === "day" || q.granularity === "hour") ? q.granularity : void 0;
352
366
  if (unit) {
353
- const { fn, isoOf } = SERIES_BUCKETS[unit];
354
- const bucket = `${fn}(timestamp, ${sqlString(q.timezone ?? "UTC")})`;
367
+ const { expr, isoOf } = SERIES_BUCKETS[unit];
368
+ const bucket = expr(sqlString(q.timezone ?? "UTC"));
355
369
  const [series, totals] = await Promise.all([runSql(`SELECT ${bucket} AS ${unit}, ${columns} ${from} GROUP BY ${unit} ORDER BY ${unit}`), fetchTotals()]);
356
370
  const rows = [];
357
371
  for (const row of series.results) {
@@ -1 +1 @@
1
- {"version":3,"file":"posthog.js","names":[],"sources":["../../../src/adapters/posthog/posthog.ts"],"sourcesContent":["import { jsLiteral } from '../../capture/jsLiteral'\nimport {\n\tadapterWithoutConsent,\n\tcookielessCapture,\n\tWITHOUT_CONSENT_LEVELS,\n} from '../../capture/withoutConsent'\nimport type { CaptureSupport, ProxyRoute, SnippetMode } from '../../core/capture'\nimport { currentTime } from '../../core/clock'\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 type { WithoutConsentLevel } from '../../tracker/config'\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'\nimport { createProjectCheck } from './projectCheck'\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\t/**\n\t * What this source's held slot does without consent, over `capture.withoutConsent`.\n\t * `'cookieless'` counts with PostHog's cookieless mode until consent, which needs the project's\n\t * \"Cookieless tracking\" (Web analytics settings); `'off'` keeps PostHog opted out until then.\n\t */\n\twithoutConsent?: WithoutConsentLevel\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 * A slot counting without consent boots in PostHog's cookieless mode, which an opt-out returns to\n * rather than stopping. Started cookieless, it counts from the first pageview while opted out by\n * default, storing nothing, until the sink opts it in.\n */\nconst cookielessOptions = (mode: SnippetMode): string[] => [\n\t`cookieless_mode:${jsLiteral('on_reject')}`,\n\t...(mode === 'cookieless' ? ['opt_out_capturing_by_default:true'] : []),\n]\n\n/**\n * The scope stamped on each event as it is sent: switching between cookieless and full resets\n * PostHog's identity and every super-property `register` set with it.\n */\nconst scopeHook = (property: string, scope: string): string =>\n\t`before_send:function(e){e&&e.properties&&(e.properties[${jsLiteral(property)}]=${jsLiteral(scope)});return e}`\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`api_host:${jsLiteral(path)}`,\n\t...(ui === undefined ? [] : [`ui_host:${jsLiteral(ui)}`]),\n\t...(named ? NAMED_CLIENT_PAGEVIEWS : [`capture_pageview:${jsLiteral(CAPTURE_PAGEVIEW)}`]),\n\t'opt_out_persistence_by_default:true',\n]\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, mode = 'full', withoutConsent = false }) => {\n\t\t\tconst named = instance !== undefined\n\t\t\tconst client = named ? `posthog[${jsLiteral(instance)}]` : 'posthog'\n\t\t\tconst property = config.scopeProperty && scope ? config.scopeProperty : undefined\n\t\t\t// Stamped on every event rather than per call, so it rides the events a host captures itself,\n\t\t\t// which is what `scopeProperty` reads back on.\n\t\t\tconst stamp =\n\t\t\t\tproperty && scope && !withoutConsent\n\t\t\t\t\t? `;${client}.register({[${jsLiteral(property)}]:${jsLiteral(scope)}})`\n\t\t\t\t\t: ''\n\t\t\tconst options = [\n\t\t\t\t...initOptions(path, hosts.ui, named),\n\t\t\t\t...(withoutConsent ? cookielessOptions(mode) : []),\n\t\t\t\t...(withoutConsent && property && scope ? [scopeHook(property, scope)] : []),\n\t\t\t].join(',')\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)},{${options}}${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 * An event counted without consent. Ingestion keeps `$cookieless_mode` while it strips the address;\n * compared as text, it matches whether the project types the property as a boolean or not.\n */\nconst COOKIELESS_EVENT = \"toString(properties.$cookieless_mode) = 'true'\"\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\tconst withoutConsent = adapterWithoutConsent(\n\t\tconfig.withoutConsent,\n\t\t'posthog({ withoutConsent })',\n\t\tWITHOUT_CONSENT_LEVELS\n\t)\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\tlet fillsCountingSlot = true\n\tconst projectDropsCookieless = createProjectCheck({\n\t\thost,\n\t\tprojectId: config.projectId,\n\t\tapiKey: config.apiKey,\n\t\t...(config.fetch ? { fetch: config.fetch } : {}),\n\t})\n\t/**\n\t * Whether a held slot this source fills may count cookielessly, which the project must accept:\n\t * the boot's answer for a config source, the factory's `withoutConsent` for a document's.\n\t */\n\tconst countsCookieless = (): boolean =>\n\t\tBoolean(config.projectToken) && withoutConsent !== 'off' && fillsCountingSlot\n\n\treturn {\n\t\tid: 'posthog',\n\t\t...adapterLabel(config.label, 'PostHog', 'posthog({ label })'),\n\t\tcapabilities,\n\t\t...(config.projectToken\n\t\t\t? {\n\t\t\t\t\tcapture: {\n\t\t\t\t\t\t...buildCapture(config, config.projectToken),\n\t\t\t\t\t\t...cookielessCapture({ kind: 'switched' }, withoutConsent),\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\n\t\tisConfigured: () => Boolean(config.projectId && config.apiKey),\n\t\tregister(_config, context) {\n\t\t\tfillsCountingSlot = context?.adapterCountsWithoutConsent !== false\n\t\t},\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = readTime(ctx)\n\t\t\tconst dropped = countsCookieless()\n\t\t\t\t? projectDropsCookieless(ctx.now?.().getTime() ?? currentTime())\n\t\t\t\t: Promise.resolve(undefined)\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\tlet cookieless = 0\n\t\t\t/** The result with what the read learnt about events counted without consent. */\n\t\t\tconst withConsentMeta = async (result: AnalyticsResult): Promise<AnalyticsResult> => {\n\t\t\t\tconst drops = await dropped\n\t\t\t\tconst counted = cookieless > 0\n\t\t\t\treturn {\n\t\t\t\t\t...result,\n\t\t\t\t\tmeta: {\n\t\t\t\t\t\t...result.meta,\n\t\t\t\t\t\t...(counted && q.metrics.includes('visitors') ? { visitorsAre: 'sumOfDaily' } : {}),\n\t\t\t\t\t\t...(counted && !breakdown && q.metrics.includes('pageviews')\n\t\t\t\t\t\t\t? { withoutConsent: { pageviews: cookieless } }\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t...(drops ? { withoutConsentDropped: true } : {}),\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t}\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 withConsentMeta(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\t\t\t// A column on the totals or breakdown query the read runs anyway, never a request of its\n\t\t\t// own. Visitors are counted on pageviews, except in a goal breakdown, which counts its rows.\n\t\t\tconst cookielessRows =\n\t\t\t\tscanAllEvents && !goalBreakdown\n\t\t\t\t\t? `event = '$pageview' AND ${COOKIELESS_EVENT}`\n\t\t\t\t\t: COOKIELESS_EVENT\n\t\t\tconst countsCookielessColumn =\n\t\t\t\tq.metrics.includes('visitors') || (!breakdown && q.metrics.includes('pageviews'))\n\t\t\tconst cookielessColumn = countsCookielessColumn ? `, countIf(${cookielessRows}) AS c` : ''\n\t\t\t/** Adds a result row's count of events counted without consent, after its metric columns. */\n\t\t\tconst tallyCookieless = (row: unknown[], offset: number): void => {\n\t\t\t\tif (countsCookielessColumn) {\n\t\t\t\t\tcookieless += vendorReading('pageviews', row[offset + exprs.length]) ?? 0\n\t\t\t\t}\n\t\t\t}\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}${cookielessColumn} ${from}`)\n\t\t\t\tconst row = data.results[0]\n\t\t\t\tif (!row) {\n\t\t\t\t\treturn {}\n\t\t\t\t}\n\t\t\t\ttallyCookieless(row, 0)\n\t\t\t\treturn 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 withConsentMeta({ 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}${cookielessColumn} ${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\ttallyCookieless(row, 1)\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdimensions: { [breakdown.dimension]: String(row[0] ?? '') },\n\t\t\t\t\t\tmetrics: readRow(row, 1),\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\treturn withConsentMeta({ rows, totals: undefined, meta })\n\t\t\t}\n\n\t\t\tconst totals = await fetchTotals()\n\t\t\treturn withConsentMeta({ rows: [{ metr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AAU,MAAM,WAAW,UAAU,iBAAiB,GAAG,KAAK,uCAAuC,EAAE,SAAS,KAC3H,GACkC,QAAQ,KAAK,QAAQ;KACtD,gBAAgB,KAAK,CAAC;KACtB,OAAO;MACN,YAAY,GAAG,UAAU,YAAY,OAAO,IAAI,MAAM,EAAE,EAAE;MAC1D,SAAS,QAAQ,KAAK,CAAC;KACxB;IACD,CAC4B;IAAG,QAAQ,KAAA;IAAW;GAAK,CAAC;GAGzD,MAAM,SAAS,MAAM,YAAY;GACjC,OAAO,gBAAgB;IAAE,MAAM,CAAC,EAAE,SAAS,OAAO,CAAC;IAAG;IAAQ;GAAK,CAAC;EACrE;CACD;AACD"}
1
+ {"version":3,"file":"posthog.js","names":[],"sources":["../../../src/adapters/posthog/posthog.ts"],"sourcesContent":["import { jsLiteral } from '../../capture/jsLiteral'\nimport {\n\tadapterWithoutConsent,\n\tcookielessCapture,\n\tWITHOUT_CONSENT_LEVELS,\n} from '../../capture/withoutConsent'\nimport type { CaptureSupport, ProxyRoute, SnippetMode } from '../../core/capture'\nimport { currentTime } from '../../core/clock'\nimport {\n\ttype AdapterContext,\n\ttype AnalyticsAdapter,\n\ttype AnalyticsCapabilities,\n\ttype AnalyticsQuery,\n\ttype AnalyticsResult,\n\ttype AnalyticsRow,\n\ttype ConnectionCheckContext,\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 type { WithoutConsentLevel } from '../../tracker/config'\nimport { emptyGoalBreakdown, goalHint, hintFailed, hintSlugs } from '../goalRead'\nimport { hostnameOf, withoutTrailingSlash } from '../http/baseUrl'\nimport { fetchJson } from '../http/fetchJson'\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'\nimport { cloudAppHost, cloudRegionOf, type PosthogRegion } from './cloud'\nimport { createProjectCheck } from './projectCheck'\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. Unset, the `region`'s cloud, US Cloud without one; 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: where capture goes and, with no `host`, where reads go. Derived from `host`\n\t * when omitted. A self-hosted `host` takes both 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\t/**\n\t * What this source's held slot does without consent, over `capture.withoutConsent`.\n\t * `'cookieless'` counts with PostHog's cookieless mode until consent, which needs the project's\n\t * \"Cookieless tracking\" (Web analytics settings); `'off'` keeps PostHog opted out until then.\n\t */\n\twithoutConsent?: WithoutConsentLevel\n}\n\nconst resolveRegion = (config: PosthogConfig): PosthogRegion => {\n\tif (config.region) {\n\t\treturn config.region\n\t}\n\treturn (config.host && cloudRegionOf(config.host)) || '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 ?? cloudAppHost(region),\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 * A slot counting without consent boots in PostHog's cookieless mode, which an opt-out returns to\n * rather than stopping. Started cookieless, it counts from the first pageview while opted out by\n * default, storing nothing, until the sink opts it in.\n */\nconst cookielessOptions = (mode: SnippetMode): string[] => [\n\t`cookieless_mode:${jsLiteral('on_reject')}`,\n\t...(mode === 'cookieless' ? ['opt_out_capturing_by_default:true'] : []),\n]\n\n/**\n * The scope stamped on each event as it is sent: switching between cookieless and full resets\n * PostHog's identity and every super-property `register` set with it.\n */\nconst scopeHook = (property: string, scope: string): string =>\n\t`before_send:function(e){e&&e.properties&&(e.properties[${jsLiteral(property)}]=${jsLiteral(scope)});return e}`\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`api_host:${jsLiteral(path)}`,\n\t...(ui === undefined ? [] : [`ui_host:${jsLiteral(ui)}`]),\n\t...(named ? NAMED_CLIENT_PAGEVIEWS : [`capture_pageview:${jsLiteral(CAPTURE_PAGEVIEW)}`]),\n\t'opt_out_persistence_by_default:true',\n]\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, mode = 'full', withoutConsent = false }) => {\n\t\t\tconst named = instance !== undefined\n\t\t\tconst client = named ? `posthog[${jsLiteral(instance)}]` : 'posthog'\n\t\t\tconst property = config.scopeProperty && scope ? config.scopeProperty : undefined\n\t\t\t// Stamped on every event rather than per call, so it rides the events a host captures itself,\n\t\t\t// which is what `scopeProperty` reads back on.\n\t\t\tconst stamp =\n\t\t\t\tproperty && scope && !withoutConsent\n\t\t\t\t\t? `;${client}.register({[${jsLiteral(property)}]:${jsLiteral(scope)}})`\n\t\t\t\t\t: ''\n\t\t\tconst options = [\n\t\t\t\t...initOptions(path, hosts.ui, named),\n\t\t\t\t...(withoutConsent ? cookielessOptions(mode) : []),\n\t\t\t\t...(withoutConsent && property && scope ? [scopeHook(property, scope)] : []),\n\t\t\t].join(',')\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)},{${options}}${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 * An event counted without consent. Ingestion keeps `$cookieless_mode` while it strips the address;\n * compared as text, it matches whether the project types the property as a boolean or not.\n */\nconst COOKIELESS_EVENT = \"toString(properties.$cookieless_mode) = 'true'\"\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/** HogQL that buckets `timestamp` in the reporting zone, given as a quoted literal. */\n\texpr: (zone: string) => 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: { expr: (zone) => `toStartOfDay(timestamp, ${zone})`, isoOf: dayIso },\n\t// HogQL's toStartOfHour takes one argument, unlike toStartOfDay, so the zone goes through toTimeZone.\n\thour: { expr: (zone) => `toStartOfHour(toTimeZone(timestamp, ${zone}))`, 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 ?? cloudAppHost(resolveRegion(config)))\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 730\n\tconst withoutConsent = adapterWithoutConsent(\n\t\tconfig.withoutConsent,\n\t\t'posthog({ withoutConsent })',\n\t\tWITHOUT_CONSENT_LEVELS\n\t)\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\tlet fillsCountingSlot = true\n\tconst projectDropsCookieless = createProjectCheck({\n\t\thost,\n\t\tprojectId: config.projectId,\n\t\tapiKey: config.apiKey,\n\t\t...(config.fetch ? { fetch: config.fetch } : {}),\n\t})\n\t/**\n\t * Whether a held slot this source fills may count cookielessly, which the project must accept:\n\t * the boot's answer for a config source, the factory's `withoutConsent` for a document's.\n\t */\n\tconst countsCookieless = (): boolean =>\n\t\tBoolean(config.projectToken) && withoutConsent !== 'off' && fillsCountingSlot\n\n\treturn {\n\t\tid: 'posthog',\n\t\t...adapterLabel(config.label, 'PostHog', 'posthog({ label })'),\n\t\tcapabilities,\n\t\t...(config.projectToken\n\t\t\t? {\n\t\t\t\t\tcapture: {\n\t\t\t\t\t\t...buildCapture(config, config.projectToken),\n\t\t\t\t\t\t...cookielessCapture({ kind: 'switched' }, withoutConsent),\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\n\t\tisConfigured: () => Boolean(config.projectId && config.apiKey),\n\t\t// The Query API reads go through, rather than the project settings, which need project:read.\n\t\tasync checkConnection(ctx: ConnectionCheckContext): Promise<void> {\n\t\t\tawait fetchJson<unknown>(\n\t\t\t\t`${host}/api/projects/${encodeURIComponent(config.projectId)}/query/`,\n\t\t\t\t{\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: 'SELECT 1' } },\n\t\t\t\t\tprovider: 'posthog',\n\t\t\t\t\tsignal: ctx.signal,\n\t\t\t\t\t...(config.fetch ? { fetch: config.fetch } : {}),\n\t\t\t\t}\n\t\t\t)\n\t\t},\n\t\tregister(_config, context) {\n\t\t\tfillsCountingSlot = context?.adapterCountsWithoutConsent !== false\n\t\t},\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = readTime(ctx)\n\t\t\tconst dropped = countsCookieless()\n\t\t\t\t? projectDropsCookieless(ctx.now?.().getTime() ?? currentTime())\n\t\t\t\t: Promise.resolve(undefined)\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\tlet cookieless = 0\n\t\t\t/** The result with what the read learnt about events counted without consent. */\n\t\t\tconst withConsentMeta = async (result: AnalyticsResult): Promise<AnalyticsResult> => {\n\t\t\t\tconst drops = await dropped\n\t\t\t\tconst counted = cookieless > 0\n\t\t\t\treturn {\n\t\t\t\t\t...result,\n\t\t\t\t\tmeta: {\n\t\t\t\t\t\t...result.meta,\n\t\t\t\t\t\t...(counted && q.metrics.includes('visitors') ? { visitorsAre: 'sumOfDaily' } : {}),\n\t\t\t\t\t\t...(counted && !breakdown && q.metrics.includes('pageviews')\n\t\t\t\t\t\t\t? { withoutConsent: { pageviews: cookieless } }\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t...(drops ? { withoutConsentDropped: true } : {}),\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t}\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 withConsentMeta(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\t\t\t// A column on the totals or breakdown query the read runs anyway, never a request of its\n\t\t\t// own. Visitors are counted on pageviews, except in a goal breakdown, which counts its rows.\n\t\t\tconst cookielessRows =\n\t\t\t\tscanAllEvents && !goalBreakdown\n\t\t\t\t\t? `event = '$pageview' AND ${COOKIELESS_EVENT}`\n\t\t\t\t\t: COOKIELESS_EVENT\n\t\t\tconst countsCookielessColumn =\n\t\t\t\tq.metrics.includes('visitors') || (!breakdown && q.metrics.includes('pageviews'))\n\t\t\tconst cookielessColumn = countsCookielessColumn ? `, countIf(${cookielessRows}) AS c` : ''\n\t\t\t/** Adds a result row's count of events counted without consent, after its metric columns. */\n\t\t\tconst tallyCookieless = (row: unknown[], offset: number): void => {\n\t\t\t\tif (countsCookielessColumn) {\n\t\t\t\t\tcookieless += vendorReading('pageviews', row[offset + exprs.length]) ?? 0\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst runSql = (sql: string): Promise<PosthogQueryResponse> =>\n\t\t\t\tupstreamJson<PosthogQueryResponse>(\n\t\t\t\t\tctx,\n\t\t\t\t\t`${host}/api/projects/${encodeURIComponent(config.projectId)}/query/`,\n\t\t\t\t\t{\n\t\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\t\theaders: { authorization: `Bearer ${config.apiKey}` },\n\t\t\t\t\t\tbody: { query: { kind: 'HogQLQuery', query: sql } },\n\t\t\t\t\t\tprovider: 'posthog',\n\t\t\t\t\t\tfetch: config.fetch,\n\t\t\t\t\t}\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}${cookielessColumn} ${from}`)\n\t\t\t\tconst row = data.results[0]\n\t\t\t\tif (!row) {\n\t\t\t\t\treturn {}\n\t\t\t\t}\n\t\t\t\ttallyCookieless(row, 0)\n\t\t\t\treturn 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 { expr, 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 = expr(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 withConsentMeta({ 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}${cookielessColumn} ${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\ttallyCookieless(row, 1)\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdimensions: { [breakdown.dimension]: String(row[0] ?? '') },\n\t\t\t\t\t\tmetrics: readRow(row, 1),\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\treturn withConsentMeta({ rows, totals: undefined, meta })\n\t\t\t}\n\n\t\t\tconst totals = await fetchTotals()\n\t\t\treturn withConsentMeta({ rows: [{ metrics: totals }], totals, meta })\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA0FA,MAAM,iBAAiB,WAAyC;CAC/D,IAAI,OAAO,QACV,OAAO,OAAO;CAEf,OAAQ,OAAO,QAAQ,cAAc,OAAO,IAAI,KAAM;AACvD;;;;;;;;AASA,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,OAAO;EAC1B,QAAQ,WAAW,OAAO;EAC1B,OAAO;EACP,IAAI,MAAM,aAAa,MAAM;CAC9B;AACD;;;;;AAMA,MAAa,oCAAuD;CACnE;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD;AAEA,MAAM,cAAc,UACnB,MAAM,QACH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AEA,MAAM,OACL,CAAC,cAAc,EAAE,gBAAgB,SAAS,EAAE,gBAAgB,UACzD,EAAE,cACF,KAAA;GACJ,IAAI,MAAM;IACT,MAAM,EAAE,MAAM,UAAU,eAAe;IAGvC,MAAM,SAAS,KAAK,UAAU,EAAE,YAAA,KAA4B,CAAC;IAC7D,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,gBAAgB;KAAE;KAAM;KAAQ;IAAK,CAAC;GAC9C;GAEA,IAAI,WAWH,OAAO,gBAAgB;IAAE,OAPI,MAHV,OAClB,UAAU,UAAU,MAAM,WAAW,UAAU,iBAAiB,GAAG,KAAK,uCAAuC,EAAE,SAAS,KAC3H,GACkC,QAAQ,KAAK,QAAQ;KACtD,gBAAgB,KAAK,CAAC;KACtB,OAAO;MACN,YAAY,GAAG,UAAU,YAAY,OAAO,IAAI,MAAM,EAAE,EAAE;MAC1D,SAAS,QAAQ,KAAK,CAAC;KACxB;IACD,CAC4B;IAAG,QAAQ,KAAA;IAAW;GAAK,CAAC;GAGzD,MAAM,SAAS,MAAM,YAAY;GACjC,OAAO,gBAAgB;IAAE,MAAM,CAAC,EAAE,SAAS,OAAO,CAAC;IAAG;IAAQ;GAAK,CAAC;EACrE;CACD;AACD"}
@@ -1,13 +1,16 @@
1
1
  import { DIMENSION_KEYS } from "../../core/contract.js";
2
+ import { isRecord } from "../../core/values.js";
3
+ import { UnknownSiteError } from "../../core/sourceErrors.js";
2
4
  import { adapterLabel } from "../../core/sourceLabel.js";
3
5
  import { WITHOUT_CONSENT_LEVELS, adapterWithoutConsent, cookielessCapture } from "../../capture/withoutConsent.js";
4
6
  import { filterableDimensions } from "../../core/capabilities.js";
7
+ import { hostnameOf, withoutTrailingSlash } from "../http/baseUrl.js";
5
8
  import { emptyGoalBreakdown, goalHint, hintFailed, hintSlugs } from "../goalRead.js";
6
9
  import { declaredFilters, everyOperatorOn, firstMapped, mappedKeys } from "../mapping.js";
7
10
  import { readTime } from "../readTime.js";
8
11
  import { dayIso } from "../series.js";
9
- import { upstreamJson } from "../upstream.js";
10
- import { hostnameOf, withoutTrailingSlash } from "../http/baseUrl.js";
12
+ import { fetchJson } from "../http/fetchJson.js";
13
+ import { upstream, upstreamJson } from "../upstream.js";
11
14
  //#region src/adapters/umami/umami.ts
12
15
  const CLOUD = {
13
16
  api: "https://api.umami.is/v1",
@@ -262,12 +265,25 @@ function umami(config) {
262
265
  upstreamAware: true
263
266
  };
264
267
  const authHeaders = () => config.apiKey ? { "x-umami-api-key": config.apiKey } : config.token ? { authorization: `Bearer ${config.token}` } : {};
268
+ const websiteUrl = `${endpoints.api}/websites/${encodeURIComponent(config.websiteId)}`;
269
+ const requireWebsite = (website) => {
270
+ if (!isRecord(website)) throw new UnknownSiteError(`umami: no website ${config.websiteId}; check the Website ID`);
271
+ };
272
+ let websiteKnown = false;
265
273
  return {
266
274
  id: "umami",
267
275
  ...adapterLabel(config.label, "Umami", "umami({ label })"),
268
276
  capabilities,
269
277
  capture: buildCapture(config, endpoints),
270
278
  isConfigured: () => Boolean(config.websiteId && (config.apiKey || config.token)),
279
+ async checkConnection(ctx) {
280
+ requireWebsite(await fetchJson(websiteUrl, {
281
+ headers: authHeaders(),
282
+ provider: "umami",
283
+ signal: ctx.signal,
284
+ ...config.fetch ? { fetch: config.fetch } : {}
285
+ }));
286
+ },
271
287
  async query(q, ctx) {
272
288
  const fetchedAt = readTime(ctx);
273
289
  const headers = authHeaders();
@@ -316,11 +332,22 @@ function umami(config) {
316
332
  for (const [name, value] of Object.entries(extra)) params.set(name, value);
317
333
  return params;
318
334
  };
319
- const getJson = (endpoint, params) => upstreamJson(ctx, `${endpoints.api}/websites/${config.websiteId}/${endpoint}?${params.toString()}`, {
320
- headers,
321
- provider: "umami",
322
- fetch: config.fetch
323
- });
335
+ const getJson = async (endpoint, params) => {
336
+ if (!websiteKnown) {
337
+ await upstream(ctx, (signal) => fetchJson(websiteUrl, {
338
+ headers,
339
+ provider: "umami",
340
+ signal,
341
+ ...config.fetch ? { fetch: config.fetch } : {}
342
+ }).then(requireWebsite));
343
+ websiteKnown = true;
344
+ }
345
+ return upstreamJson(ctx, `${websiteUrl}/${endpoint}?${params.toString()}`, {
346
+ headers,
347
+ provider: "umami",
348
+ fetch: config.fetch
349
+ });
350
+ };
324
351
  /**
325
352
  * The goal rows for the hint, narrowed to it again on the way back so nothing the API
326
353
  * did not restrict can arrive as a goal.
@@ -1 +1 @@
1
- {"version":3,"file":"umami.js","names":[],"sources":["../../../src/adapters/umami/umami.ts"],"sourcesContent":["import {\n\tadapterWithoutConsent,\n\tcookielessCapture,\n\tWITHOUT_CONSENT_LEVELS,\n} from '../../capture/withoutConsent'\nimport { 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 type { WithoutConsentLevel } from '../../tracker/config'\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\t/**\n\t * What this source's held slot does without consent, over `capture.withoutConsent`. Umami stores\n\t * nothing on the device, so `'cookieless'` loads the script as it is; `'off'` holds it.\n\t */\n\twithoutConsent?: WithoutConsentLevel\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\t...cookielessCapture(\n\t\t\t{ kind: 'inherent' },\n\t\t\tadapterWithoutConsent(\n\t\t\t\tconfig.withoutConsent,\n\t\t\t\t'umami({ withoutConsent })',\n\t\t\t\tWITHOUT_CONSENT_LEVELS\n\t\t\t)\n\t\t),\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":";;;;;;;;;;;AAmEA,MAAM,QAAwB;CAC7B,KAAK;CACL,QAAQ;CACR,MAAM;AACP;;AAGA,MAAM,kBAAuC,IA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C,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 {\n\tadapterWithoutConsent,\n\tcookielessCapture,\n\tWITHOUT_CONSENT_LEVELS,\n} from '../../capture/withoutConsent'\nimport { 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\ttype ConnectionCheckContext,\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 { UnknownSiteError } from '../../core/sourceErrors'\nimport { type AdapterLabelOption, adapterLabel } from '../../core/sourceLabel'\nimport { isRecord } from '../../core/values'\nimport { DEFAULT_TIMEZONE } from '../../timeframe/tz'\nimport type { WithoutConsentLevel } from '../../tracker/config'\nimport { emptyGoalBreakdown, goalHint, hintFailed, hintSlugs } from '../goalRead'\nimport { hostnameOf, withoutTrailingSlash } from '../http/baseUrl'\nimport { fetchJson } from '../http/fetchJson'\nimport { declaredFilters, everyOperatorOn, firstMapped, mappedKeys } from '../mapping'\nimport { readTime } from '../readTime'\nimport { dayIso } from '../series'\nimport { upstream, 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\t/**\n\t * What this source's held slot does without consent, over `capture.withoutConsent`. Umami stores\n\t * nothing on the device, so `'cookieless'` loads the script as it is; `'off'` holds it.\n\t */\n\twithoutConsent?: WithoutConsentLevel\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\t...cookielessCapture(\n\t\t\t{ kind: 'inherent' },\n\t\t\tadapterWithoutConsent(\n\t\t\t\tconfig.withoutConsent,\n\t\t\t\t'umami({ withoutConsent })',\n\t\t\t\tWITHOUT_CONSENT_LEVELS\n\t\t\t)\n\t\t),\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\tconst websiteUrl = `${endpoints.api}/websites/${encodeURIComponent(config.websiteId)}`\n\t// Self-hosted Umami answers a website id it does not know with 200 and a `null` body, and that\n\t// id's stats with zeros, so a read would pass for a working source.\n\tconst requireWebsite = (website: unknown): void => {\n\t\tif (!isRecord(website)) {\n\t\t\tthrow new UnknownSiteError(`umami: no website ${config.websiteId}; check the Website ID`)\n\t\t}\n\t}\n\t// Remembered once Umami answers: a failed lookup is the asking read's alone. A new adapter (a save\n\t// of its document, or a `providers.resolve` that builds one per read) asks again.\n\tlet websiteKnown = false\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 checkConnection(ctx: ConnectionCheckContext): Promise<void> {\n\t\t\trequireWebsite(\n\t\t\t\tawait fetchJson<unknown>(websiteUrl, {\n\t\t\t\t\theaders: authHeaders(),\n\t\t\t\t\tprovider: 'umami',\n\t\t\t\t\tsignal: ctx.signal,\n\t\t\t\t\t...(config.fetch ? { fetch: config.fetch } : {}),\n\t\t\t\t})\n\t\t\t)\n\t\t},\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 = async <T>(endpoint: string, params: URLSearchParams): Promise<T> => {\n\t\t\t\t// Inside the lane, so the lane records an unknown website as a refusal, not a success.\n\t\t\t\tif (!websiteKnown) {\n\t\t\t\t\tawait upstream(ctx, (signal) =>\n\t\t\t\t\t\tfetchJson<unknown>(websiteUrl, {\n\t\t\t\t\t\t\theaders,\n\t\t\t\t\t\t\tprovider: 'umami',\n\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t\t...(config.fetch ? { fetch: config.fetch } : {}),\n\t\t\t\t\t\t}).then(requireWebsite)\n\t\t\t\t\t)\n\t\t\t\t\twebsiteKnown = true\n\t\t\t\t}\n\t\t\t\treturn upstreamJson<T>(ctx, `${websiteUrl}/${endpoint}?${params.toString()}`, {\n\t\t\t\t\theaders,\n\t\t\t\t\tprovider: 'umami',\n\t\t\t\t\tfetch: config.fetch,\n\t\t\t\t})\n\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":";;;;;;;;;;;;;;AAuEA,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,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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,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";
4
3
  import { addCalendarDays, calendarDayOf, calendarDayStart } from "../timeframe/calendar.js";
5
4
  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
@@ -405,6 +405,15 @@ interface AdapterLabelArgs {
405
405
  /** Null is install-wide, `*` is cross-scope. */
406
406
  scope: string | null;
407
407
  }
408
+ /** What a connection check runs with. */
409
+ interface ConnectionCheckContext {
410
+ /** Ends the check: aborted once {@link ConnectionCheckContext.timeoutMs} has passed. */
411
+ signal: AbortSignal;
412
+ /** The time the check may take, for an SDK that wants a deadline rather than a signal. */
413
+ timeoutMs: number;
414
+ /** The instance the check runs on, for an adapter that keeps a client per instance. */
415
+ payload?: Payload;
416
+ }
408
417
  interface AnalyticsAdapter {
409
418
  readonly id: string;
410
419
  /** The source's name wherever no reader is known (boot-time pickers, logs). */
@@ -429,6 +438,12 @@ interface AnalyticsAdapter {
429
438
  isConfigured(): boolean;
430
439
  query(query: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult>;
431
440
  realtime?(query: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult>;
441
+ /**
442
+ * One cheap read that proves the source's settings work, behind a provider document's Test
443
+ * connection: it resolves when the vendor accepts them and throws what a read would when it does
444
+ * not. It does not go through the source's lane, so a rested source is tried anyway.
445
+ */
446
+ checkConnection?(ctx: ConnectionCheckContext): Promise<void>;
432
447
  register?(config: Config, context?: AdapterRegisterContext): void;
433
448
  /**
434
449
  * For `disabled: true`: adds exactly the schema `register` would (collections, fields, indexes,
@@ -448,5 +463,5 @@ interface AnalyticsAdapter {
448
463
  }
449
464
  type AnalyticsAdapterFactory<Config> = (config: Config) => AnalyticsAdapter;
450
465
  //#endregion
451
- export { AdapterContext, AdapterLabelArgs, AdapterRegisterContext, AdapterSchemaContext, AnalyticsAdapter, AnalyticsAdapterFactory, AnalyticsCapabilities, AnalyticsFilter, AnalyticsQuery, AnalyticsResult, AnalyticsRow, DIMENSION_KEYS, DateRange, DimensionKey, FILTER_OPERATORS, FilterOperator, FilterOperatorMap, Granularity, MetricKey, MetricReach, MetricSemantics, MetricValue, MetricValues, PLATFORM_SCOPE, RateLimitDescriptor, SourceErrorKind, VisitorCounting };
466
+ export { AdapterContext, AdapterLabelArgs, AdapterRegisterContext, AdapterSchemaContext, AnalyticsAdapter, AnalyticsAdapterFactory, AnalyticsCapabilities, AnalyticsFilter, AnalyticsQuery, AnalyticsResult, AnalyticsRow, ConnectionCheckContext, DIMENSION_KEYS, DateRange, DimensionKey, FILTER_OPERATORS, FilterOperator, FilterOperatorMap, Granularity, MetricKey, MetricReach, MetricSemantics, MetricValue, MetricValues, PLATFORM_SCOPE, RateLimitDescriptor, SourceErrorKind, VisitorCounting };
452
467
  //# sourceMappingURL=contract.d.ts.map