@10x-media/analytics 1.0.0-beta.16 → 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.
- package/CHANGELOG.md +46 -0
- package/dist/adapters/ga4/ga4.js +33 -2
- package/dist/adapters/ga4/ga4.js.map +1 -1
- package/dist/adapters/ga4/measurementId.js +4 -1
- package/dist/adapters/ga4/measurementId.js.map +1 -1
- package/dist/adapters/ga4/propertyId.js +17 -0
- package/dist/adapters/ga4/propertyId.js.map +1 -0
- package/dist/adapters/http/fetchJson.js +24 -1
- package/dist/adapters/http/fetchJson.js.map +1 -1
- package/dist/adapters/plausible/plausible.js +16 -1
- package/dist/adapters/plausible/plausible.js.map +1 -1
- package/dist/adapters/plausible/siteId.js +31 -0
- package/dist/adapters/plausible/siteId.js.map +1 -0
- package/dist/adapters/posthog/posthog.js +17 -3
- package/dist/adapters/posthog/posthog.js.map +1 -1
- package/dist/adapters/umami/umami.js +34 -7
- package/dist/adapters/umami/umami.js.map +1 -1
- package/dist/charts/series.js +1 -1
- package/dist/core/contract.d.ts +16 -1
- package/dist/core/contract.js.map +1 -1
- package/dist/core/options.d.ts +1 -1
- package/dist/core/options.js +1 -1
- package/dist/core/options.js.map +1 -1
- package/dist/core/scopedRead.js +62 -14
- package/dist/core/scopedRead.js.map +1 -1
- package/dist/core/sourceErrors.js +12 -1
- package/dist/core/sourceErrors.js.map +1 -1
- package/dist/core/sourceOptions.js +1 -1
- package/dist/core/sourceOptions.js.map +1 -1
- package/dist/core/sourcePolicy.d.ts +8 -1
- package/dist/core/sourcePolicy.js.map +1 -1
- package/dist/core/throttle.js +3 -1
- package/dist/core/throttle.js.map +1 -1
- package/dist/exports/adapters/contract.d.ts +1 -1
- package/dist/exports/adapters/ga4.d.ts +2 -2
- package/dist/exports/adapters/native.d.ts +2 -2
- package/dist/exports/adapters/plausible.d.ts +2 -2
- package/dist/exports/adapters/posthog.d.ts +2 -2
- package/dist/exports/adapters/umami.d.ts +2 -2
- package/dist/exports/client.d.ts +3 -1
- package/dist/exports/client.js +3 -1
- package/dist/exports/next.d.ts +2 -2
- package/dist/exports/testing.d.ts +2 -2
- package/dist/exports/types.d.ts +3 -3
- package/dist/fields/config/fetchSources.js +1 -1
- package/dist/fields/config/fetchSources.js.map +1 -1
- package/dist/goals/collection.js +3 -2
- package/dist/goals/collection.js.map +1 -1
- package/dist/goals/resolver.js +1 -1
- package/dist/index.d.ts +4 -3
- package/dist/index.js +50 -4
- package/dist/index.js.map +1 -1
- package/dist/native/geo/maxmindResolver.js +1 -1
- package/dist/native/nativeAdapter.js +1 -1
- package/dist/plugin/createRuntime.js +57 -13
- package/dist/plugin/createRuntime.js.map +1 -1
- package/dist/plugin/pluginCollections.js +4 -1
- package/dist/plugin/pluginCollections.js.map +1 -1
- package/dist/plugin/providerStatusEndpoint.js +80 -0
- package/dist/plugin/providerStatusEndpoint.js.map +1 -0
- package/dist/plugin/queryEndpoint.js +1 -1
- package/dist/plugin/queryEndpoint.js.map +1 -1
- package/dist/plugin/readContextForRequest.d.ts +4 -3
- package/dist/plugin/readContextForRequest.js +2 -2
- package/dist/plugin/readContextForRequest.js.map +1 -1
- package/dist/plugin/refreshEndpoint.js +1 -1
- package/dist/plugin/routes.d.ts +5 -0
- package/dist/plugin/routes.js +1 -0
- package/dist/plugin/routes.js.map +1 -1
- package/dist/plugin/runtime.js.map +1 -1
- package/dist/providers/ProviderConnection.d.ts +12 -0
- package/dist/providers/ProviderConnection.js +105 -0
- package/dist/providers/ProviderConnection.js.map +1 -0
- package/dist/providers/ProviderConnectionTest.d.ts +12 -0
- package/dist/providers/ProviderConnectionTest.js +55 -0
- package/dist/providers/ProviderConnectionTest.js.map +1 -0
- package/dist/providers/ProvidersListNotice.d.ts +1 -1
- package/dist/providers/ProvidersListNotice.js +3 -2
- package/dist/providers/ProvidersListNotice.js.map +1 -1
- package/dist/providers/collection.d.ts +1 -1
- package/dist/providers/collection.js +97 -38
- package/dist/providers/collection.js.map +1 -1
- package/dist/providers/connectionCheck.d.ts +1 -0
- package/dist/providers/connectionCheck.js +80 -0
- package/dist/providers/connectionCheck.js.map +1 -0
- package/dist/providers/connectionState.js +53 -0
- package/dist/providers/connectionState.js.map +1 -0
- package/dist/providers/factory.d.ts +1 -3
- package/dist/providers/factory.js +18 -21
- package/dist/providers/factory.js.map +1 -1
- package/dist/providers/hosts.js +20 -6
- package/dist/providers/hosts.js.map +1 -1
- package/dist/providers/ids.d.ts +6 -0
- package/dist/providers/ids.js +32 -0
- package/dist/providers/ids.js.map +1 -0
- package/dist/providers/providerStatusClient.js +60 -0
- package/dist/providers/providerStatusClient.js.map +1 -0
- package/dist/providers/registry.js +56 -20
- package/dist/providers/registry.js.map +1 -1
- package/dist/providers/retarget.js +39 -8
- package/dist/providers/retarget.js.map +1 -1
- package/dist/providers/secrets.d.ts +1 -1
- package/dist/providers/secrets.js.map +1 -1
- package/dist/providers/status.d.ts +1 -0
- package/dist/providers/status.js +181 -0
- package/dist/providers/status.js.map +1 -0
- package/dist/surfacing/classifyError.js +37 -5
- package/dist/surfacing/classifyError.js.map +1 -1
- package/dist/surfacing/engine.js +2 -2
- package/dist/surfacing/engine.js.map +1 -1
- package/dist/surfacing/lanes.js +29 -22
- package/dist/surfacing/lanes.js.map +1 -1
- package/dist/surfacing/rebucket.js +1 -1
- package/dist/testing/settle.d.ts +2 -1
- package/dist/testing/settle.js +6 -2
- package/dist/testing/settle.js.map +1 -1
- package/dist/tracker/sinks/ga4.js +2 -2
- package/dist/translations/ar.js +40 -8
- package/dist/translations/ar.js.map +1 -1
- package/dist/translations/de.js +40 -8
- package/dist/translations/de.js.map +1 -1
- package/dist/translations/en.js +40 -8
- package/dist/translations/en.js.map +1 -1
- package/dist/translations/es.js +40 -8
- package/dist/translations/es.js.map +1 -1
- package/dist/translations/fr.js +40 -8
- package/dist/translations/fr.js.map +1 -1
- package/dist/translations/id.js +40 -8
- package/dist/translations/id.js.map +1 -1
- package/dist/translations/keys.d.ts +32 -0
- package/dist/translations/keys.js +32 -0
- package/dist/translations/keys.js.map +1 -1
- package/dist/translations/ko.js +40 -8
- package/dist/translations/ko.js.map +1 -1
- package/dist/translations/pt.js +40 -8
- package/dist/translations/pt.js.map +1 -1
- package/dist/translations/ru.js +40 -8
- package/dist/translations/ru.js.map +1 -1
- package/dist/translations/uk.js +40 -8
- package/dist/translations/uk.js.map +1 -1
- package/dist/translations/zh.js +40 -8
- package/dist/translations/zh.js.map +1 -1
- package/dist/ui/analytics.css +63 -0
- package/dist/ui/components/SourcesNoticeBanner.js +4 -3
- package/dist/ui/components/SourcesNoticeBanner.js.map +1 -1
- package/dist/view/ViewSections.js +9 -2
- package/dist/view/ViewSections.js.map +1 -1
- package/dist/view/sections/EmptyStates.js +5 -4
- package/dist/view/sections/EmptyStates.js.map +1 -1
- package/dist/view/sections/OverviewCards.js +6 -2
- package/dist/view/sections/OverviewCards.js.map +1 -1
- package/dist/view/sections/SourceConnectionNote.js +56 -0
- package/dist/view/sections/SourceConnectionNote.js.map +1 -0
- package/dist/view/viewProps.d.ts +2 -0
- package/dist/view/viewProps.js +2 -1
- package/dist/view/viewProps.js.map +1 -1
- package/package.json +1 -1
|
@@ -3,14 +3,15 @@ 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
|
-
import { cloudAppHost, cloudRegionOf } from "./cloud.js";
|
|
14
15
|
import { createProjectCheck } from "./projectCheck.js";
|
|
15
16
|
//#region src/adapters/posthog/posthog.ts
|
|
16
17
|
const resolveRegion = (config) => {
|
|
@@ -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: {
|
|
@@ -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 { 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\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 { 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":";;;;;;;;;;;;;;;AAwFA,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,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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;;;;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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 {
|
|
10
|
-
import {
|
|
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) =>
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
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,IAAI,IAAI,CAAC,gBAAgB,gBAAgB,CAAC;;;;;AAMvF,MAAa,kBAAkB,SAA6C;CAE3E,MAAM,UAAU,qBADA,qBAAqB,MAAM,KAAK,KAAK,EACV,EAAE,QAA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,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,YAAY,MAAM,gBAAgB,IAAI,WAAW,OAAO,CAAC,GAC5D,OAAO;CAER,OAAO;EAAE,KAAK,GAAG,QAAQ;EAAO,QAAQ,GAAG,QAAQ;EAAa,MAAM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K,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"}
|
package/dist/charts/series.js
CHANGED
|
@@ -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
|
package/dist/core/contract.d.ts
CHANGED
|
@@ -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
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"contract.js","names":[],"sources":["../../src/core/contract.ts"],"sourcesContent":["import type { Config, Payload, PayloadRequest } from 'payload'\nimport type { CurrencyConverter } from '../goals/currency'\nimport type { BrowserAmounts, OrderSignatureMode } from '../goals/match'\nimport type { Goal } from '../goals/types'\nimport type { TrustedPlatform } from '../net/platform'\nimport type { RoutePaths } from '../plugin/routes'\nimport type { CaptureSupport } from './capture'\nimport type { AdapterJobs } from './jobs'\nimport type { AnalyticsSdks } from './sdks'\nimport type { IngestHostnameResolver, ServerTrack } from './serverEvent'\n\n/**\n * Explicit cross-scope read marker: pass as a read's `scope` to aggregate over every\n * scope. Gated by `access.crossScope.aggregate`; the query reaches the adapter unscoped.\n */\nexport const PLATFORM_SCOPE = '*'\n\nexport type { AdapterJobs, AnalyticsTaskName, ScheduledTask } from './jobs'\n\nexport type MetricKey =\n\t| 'pageviews'\n\t| 'visitors'\n\t| 'visits'\n\t| 'sessions'\n\t| 'bounceRate'\n\t/** Time on page: engaged time per pageview, an average in milliseconds over the pageviews it is read for. */\n\t| 'avgDuration'\n\t/** Time per visit: engaged time per visit, an average in milliseconds over the visits it is read for. */\n\t| 'visitDuration'\n\t| 'scrollDepth'\n\t| 'events'\n\t| 'conversions'\n\t| 'revenue'\n\t/** Times a content item was seen on screen. Counted per item only, never per page or site. */\n\t| 'impressions'\n\t/** Clicks on a content item, the first per item and pageview. */\n\t| 'interactions'\n\n/**\n * One metric's reading. `null` is an average or a share with nothing to average over (no\n * pageviews to time, no scroll reported, no sessions to bounce): no data, not zero.\n */\nexport type MetricValue = number | null\n\n/** A row's or a read's metrics. A metric the source did not report is absent. */\nexport type MetricValues = Partial<Record<MetricKey, MetricValue>>\n\n/** Every breakdown key the contract defines, the list request parsers validate against. */\nexport const DIMENSION_KEYS = [\n\t'page',\n\t'referrer',\n\t'source',\n\t'channel',\n\t'medium',\n\t'campaign',\n\t'utmSource',\n\t'utmMedium',\n\t'utmCampaign',\n\t'utmContent',\n\t'utmTerm',\n\t'device',\n\t'browser',\n\t'os',\n\t'country',\n\t'region',\n\t'city',\n\t'language',\n\t'event',\n\t'goal',\n\t'currency',\n\t'item',\n] as const\n\nexport type DimensionKey = (typeof DIMENSION_KEYS)[number]\n\nexport type Granularity = 'minute' | 'hour' | 'day' | 'week' | 'month'\n\nexport interface DateRange {\n\tstart: Date\n\tend: Date\n}\n\n/** Every filter operator the contract defines, the list request parsers validate against. */\nexport const FILTER_OPERATORS = ['eq', 'contains', 'matches'] as const\n\nexport type FilterOperator = (typeof FILTER_OPERATORS)[number]\n\nexport interface AnalyticsFilter {\n\tdimension: DimensionKey\n\toperator: FilterOperator\n\tvalue: string\n}\n\nexport interface AnalyticsQuery {\n\tpath?: string\n\thostname?: string\n\t/**\n\t * One content item's ref (`<collection>:<id>`): the read answers about that item, wherever\n\t * it was shown. Only a source declaring `capabilities.perItemQuery` can serve it.\n\t */\n\titem?: string\n\tmetrics: MetricKey[]\n\tdimensions?: DimensionKey[]\n\tdateRange: DateRange\n\tgranularity?: Granularity\n\tfilters?: AnalyticsFilter[]\n\tlimit?: number\n\t/**\n\t * How a breakdown is ranked before `limit` cuts it. The metric belongs in `metrics`: ranked by\n\t * one the read did not ask for, rows keep the source's order.\n\t */\n\torder?: { metric: MetricKey; direction: 'asc' | 'desc' }\n\t/**\n\t * Analytics boundary of the read (tenant id, site key); undefined means install-wide. Adapters\n\t * that can filter by scope apply it, and it is always part of the cache key.\n\t */\n\tscope?: string\n\t/**\n\t * IANA timezone the read's day boundaries align to; undefined means UTC. Adapters that can bucket\n\t * in a zone apply it, others report in their account's own.\n\t */\n\ttimezone?: string\n\t/**\n\t * The scope's goal slugs, which provider adapters restrict goal rows to (native matches goals\n\t * itself). `'unresolved'` marks a failed goal resolver and never shares a healthy cache key.\n\t */\n\tgoalSlugs?: string[] | 'unresolved'\n}\n\nexport interface AnalyticsRow {\n\tdimensions?: Partial<Record<DimensionKey, string>>\n\tmetrics: MetricValues\n\ttimestamp?: string\n\t/**\n\t * How many observations each average in `metrics` was taken over, which folds days into weeks\n\t * exactly. An average without one is weighted by its row's matching count.\n\t */\n\tsamples?: Partial<Record<MetricKey, number>>\n}\n\n/** How a read's `visitors` were counted. */\nexport type VisitorCounting = 'distinct' | 'sumOfDaily'\n\n/** Why a stale answer's source needs a look: its settings were refused, or its host is not allowed. */\nexport type SourceErrorKind = 'misconfigured' | 'host-refused'\n\nexport interface AnalyticsResult {\n\trows: AnalyticsRow[]\n\ttotals?: MetricValues\n\tmeta: {\n\t\tprovider: string\n\t\t/** The source counted from a sample of its data (GA4 on a large property), so the numbers are estimates. */\n\t\tsampled?: boolean\n\t\t/** The read covers less than it asked for: from `dataFrom` and up to `dataTo`, where set. */\n\t\tclamped?: boolean\n\t\t/** ISO instant the data starts at, set with `clamped` when later than the range's start. */\n\t\tdataFrom?: string\n\t\t/**\n\t\t * ISO instant the data ends at, set with `clamped` when earlier than the range's end: a day\n\t\t * the range cuts lies past raw retention in a scope's own zone.\n\t\t */\n\t\tdataTo?: string\n\t\t/**\n\t\t * `distinct` counts each person once per number; `sumOfDaily` means some number adds up daily\n\t\t * visitors, so a person who came on two days counts twice.\n\t\t */\n\t\tvisitorsAre?: VisitorCounting\n\t\t/** Some days of the range could not be read yet, so the numbers are a floor. */\n\t\tpartial?: { missingDays: number }\n\t\t/**\n\t\t * On this many days of the range a value the read asks about was folded into the `(other)`\n\t\t * row of its daily totals, and its raw hits are no longer kept: the numbers are a floor.\n\t\t */\n\t\tcapped?: { days: number }\n\t\t/**\n\t\t * On this many days of the range counting failed again and again and was given up: each is\n\t\t * read from an earlier count when it had one, and left out otherwise.\n\t\t */\n\t\tfailed?: { days: number }\n\t\t/**\n\t\t * The scope's reporting timezone could not be resolved and none was ever recorded, so this\n\t\t * read cut its days in UTC and counted nothing for later reads.\n\t\t */\n\t\ttimezoneUnresolved?: true\n\t\t/** ISO instant the numbers were last brought up to date, when older than `fetchedAt`. */\n\t\tasOf?: string\n\t\t/**\n\t\t * ISO instant the source was read (`ctx.now`), never later than the engine got the answer; a\n\t\t * cached answer keeps it.\n\t\t */\n\t\tfetchedAt: string\n\t\t/**\n\t\t * ISO 4217 code `revenue` is reported in: the vendor's own, else the install's\n\t\t * `revenue.currency` or the read's `currency` filter. Absent, revenue is a plain sum as sent.\n\t\t */\n\t\tcurrency?: string\n\t\t/**\n\t\t * The currencies the read's revenue adds unconverted amounts of, when more than one. Native\n\t\t * sets it.\n\t\t */\n\t\tmixedCurrencies?: string[]\n\t\t/**\n\t\t * Served from a cache entry past its TTL: at once while a refresh runs, or because the refresh\n\t\t * failed. `asOf` then says when the entry was fetched.\n\t\t */\n\t\tstale?: boolean\n\t\t/**\n\t\t * Set on a stale answer whose source last failed as set up rather than as an outage:\n\t\t * credentials refused (`misconfigured`) or host not allowed (`host-refused`).\n\t\t */\n\t\tsourceError?: SourceErrorKind\n\t\t/**\n\t\t * Filters the source could not carry, so the rows are wider than the query asked for.\n\t\t * A provider whose API takes one value per dimension reports the ones it dropped here.\n\t\t */\n\t\tunappliedFilters?: AnalyticsFilter[]\n\t\t/**\n\t\t * The read's goal numbers are absent because resolving them failed. A scope with no goals gets\n\t\t * an empty result instead, not this flag.\n\t\t */\n\t\tgoalsUnresolved?: true\n\t\t/**\n\t\t * Pageviews of the read counted without consent, at a cookieless or anonymous level, which\n\t\t * the view shows as a share of all pageviews. Absent when the source cannot tell or found none.\n\t\t */\n\t\twithoutConsent?: { pageviews: number }\n\t\t/**\n\t\t * Pageviews of the read recorded without a visitor (native's anonymous level): they count as\n\t\t * pageviews, and toward no visitor, visit, bounce rate or time.\n\t\t */\n\t\twithoutVisitor?: { pageviews: number }\n\t\t/**\n\t\t * The vendor drops what a slot counts without consent, so those visits are missing from every\n\t\t * number: PostHog with its project's cookieless tracking setting off.\n\t\t */\n\t\twithoutConsentDropped?: true\n\t}\n}\n\n/**\n * The vendor's limits the source's lane keeps to, one token per upstream request per window. A read\n * with conversions may cost a second, goal-filtered request.\n */\nexport interface RateLimitDescriptor {\n\trequestsPerMinute?: number\n\trequestsPerHour?: number\n\t/** Upstream requests the source may have in flight; `cache.concurrency.perSource` when unset. */\n\tmaxConcurrent?: number\n\t/** Whether reads also spend the provider's write or ingest quota. */\n\treadsCountAsUsage?: boolean\n}\n\n/**\n * Which operators each dimension can be filtered with. A dimension absent here, or listed with\n * no operator, cannot be filtered at all.\n */\nexport type FilterOperatorMap = Partial<Record<DimensionKey, readonly FilterOperator[]>>\n\n/** Where a source reads one metric, when it cannot read it under every breakdown it offers. */\nexport interface MetricReach {\n\t/**\n\t * The breakdowns the metric is read under; empty when only whole-site numbers carry it.\n\t * Absent: every dimension the source declares.\n\t */\n\tdimensions?: readonly DimensionKey[]\n\t/**\n\t * A dimension the read must break down or filter by for the metric to have a value at all.\n\t * A read of one page (`AnalyticsQuery.path`) counts as filtering by `page`.\n\t */\n\trequires?: DimensionKey\n}\n\n/** What the numbers of a source mean where sources differ. */\nexport interface MetricSemantics {\n\t/**\n\t * `distinct` counts each person once over a range; `sumOfDaily` adds up each day's visitors.\n\t * Either may be per hostname: native's visitor id is, so two hostnames add up.\n\t */\n\tvisitors: VisitorCounting\n\t/** `inactivity30m` ends a visit after 30 minutes without activity; `provider` is the vendor's own rule. */\n\tsessions: 'inactivity30m' | 'provider'\n}\n\nexport interface AnalyticsCapabilities {\n\t/** The source answers `AnalyticsQuery.item`: one content item's views, clicks and outcomes. */\n\tperItemQuery?: boolean\n\trealtime: boolean\n\trealtimeWindowMinutes?: number\n\t/**\n\t * Period-over-period comparison, which the engine serves for every source by reading the\n\t * previous window itself. Adapters omit this; set it false only to opt a source out.\n\t */\n\tcomparison?: boolean\n\tminGranularity: Granularity\n\t/**\n\t * The source answers `week` and `month` series itself, exactly. Without it the engine reads\n\t * days and folds them into weeks and months in the read's reporting timezone.\n\t */\n\tcalendarBuckets?: boolean\n\tmaxLookbackDays: number | null\n\t/**\n\t * How far back a filtered read reaches, when that is shorter than `maxLookbackDays`: the\n\t * source narrows a longer one itself and marks it `clamped`. Absent or null: as far as any read.\n\t */\n\tfilterLookbackDays?: number | null\n\tmetrics: ReadonlySet<MetricKey>\n\tdimensions: ReadonlySet<DimensionKey>\n\t/**\n\t * Metrics the source reads only under some breakdowns or only for a page; any other is read under\n\t * every dimension. Reads outside a metric's reach are refused and hidden by pickers.\n\t */\n\tmetricReach?: Partial<Record<MetricKey, MetricReach>>\n\t/**\n\t * The `AnalyticsQuery.filters` the source applies, per dimension. A read carrying any other\n\t * pair is refused before it reaches the adapter. Absent: no filter at all.\n\t */\n\tfilters?: FilterOperatorMap\n\t/** What `visitors` and `sessions` mean here. Absent: not declared. */\n\tsemantics?: MetricSemantics\n\trateLimit: RateLimitDescriptor | null\n\t/**\n\t * Seconds an answer stays fresh. `today`, for a source cheap to read again, caps a window that\n\t * reaches into the current day whatever `cache.ttl` says; such an answer is never served stale.\n\t */\n\trecommendedTtl: { realtime: number; aggregate: number; today?: number }\n\t/**\n\t * The adapter applies `AnalyticsQuery.scope` as a native filter. Without it a scoped read through\n\t * a shared adapter would see other scopes, so it is gated by `access.crossScope.unscopedSource`.\n\t */\n\tscopedQueries?: boolean\n\t/**\n\t * The adapter sends every vendor request through `AdapterContext.upstream`, so each one spends\n\t * its own rate token and slot. Without it the engine counts a whole read as one request.\n\t */\n\tupstreamAware?: boolean\n}\n\nexport interface AdapterContext {\n\tsignal?: AbortSignal\n\t/**\n\t * The Payload instance the read is for, which the surfacing engine always passes. An adapter\n\t * that stores its data in Payload's database reads through it.\n\t */\n\tpayload?: Payload\n\t/**\n\t * Sends one vendor request through the source's lane: rate token, slot, retries on outage,\n\t * circuit breaker. Absent outside the engine, where `fn(ctx.signal)` is called directly.\n\t */\n\tupstream?: <T>(fn: (signal?: AbortSignal) => Promise<T>) => Promise<T>\n\t/**\n\t * Milliseconds the read has left before it gives up, for a vendor SDK that takes a deadline of\n\t * its own rather than a signal. Absent outside the engine.\n\t */\n\tremainingMs?: () => number\n\t/**\n\t * What time it is by the plugin's clock (Payload's), which an adapter stamps `meta.fetchedAt`\n\t * with. The engine always passes it; absent outside the engine.\n\t */\n\tnow?: () => Date\n}\n\n/** Extra context the plugin hands adapters when they register config surface. */\nexport interface AdapterRegisterContext {\n\t/** True when the plugin has `scope.resolve` configured. */\n\tscoped: boolean\n\t/**\n\t * `scope.resolve` at the `capture` call site, for ingest stamping: the host's resolver sees no\n\t * user, cookies or authorization header, so a hit files under the site it landed on.\n\t */\n\tresolveScope: (req: PayloadRequest) => Promise<string | null>\n\t/**\n\t * The plugin's reportingTimezone bound for adapter use, for what is shown in it. Resolves to\n\t * `'UTC'` when no reportingTimezone is set, and when the host's resolver fails.\n\t */\n\tresolveTimezone: (req: PayloadRequest, scope?: string | null) => Promise<string>\n\t/**\n\t * The same timezone, thrown rather than falling back to UTC: for an adapter storing days counted\n\t * in it, where recounting a day in UTC would move its numbers.\n\t */\n\tresolveTimezoneStrict: (req: PayloadRequest, scope?: string | null) => Promise<string>\n\t/** The install's `revenue` settings, for adapters that declare or reconcile revenue. */\n\trevenue: {\n\t\tenabled: boolean\n\t\tdimension: boolean\n\t\t/** `revenue.currency` bound for adapter use: `undefined` when none is set, revenue a plain number. */\n\t\tcurrency: (req: PayloadRequest, scope?: string | null) => Promise<string | undefined>\n\t\t/** `revenue.convert`, for adapters that reconcile revenue at ingest. */\n\t\tconvert?: CurrencyConverter\n\t\t/** `revenue.browserAmounts`, for an adapter that takes amounts from the browser itself. */\n\t\tbrowserAmounts?: BrowserAmounts\n\t\t/** `revenue.orderSignature`, for an adapter that takes the browser's order ids. */\n\t\torderSignature?: OrderSignatureMode\n\t}\n\t/**\n\t * The install's goals for a request's scope (config goals, the collection's merged over them),\n\t * for adapters that match completions themselves.\n\t */\n\tresolveGoals: (req: PayloadRequest, scope?: string | null) => Promise<Goal[]>\n\t/**\n\t * Whether a scope's own provider documents grant it this adapter; present only when the providers\n\t * collection runs under `scope.resolve`. Native ingest stores nothing for a scope it denies.\n\t */\n\tadapterGrantedForScope?: (\n\t\treq: PayloadRequest,\n\t\tscope: string | null,\n\t\tadapterId: string\n\t) => Promise<boolean>\n\t/** The plugin's `trustedProxyHops`, for adapters that read a request's client address. */\n\ttrustedProxyHops?: number\n\t/**\n\t * The plugin's `trustedPlatform`, for adapters that read a request's client address or\n\t * location: the only platform whose edge headers may be believed.\n\t */\n\ttrustedPlatform?: TrustedPlatform\n\t/**\n\t * `capture.allowedOrigins`, normalized, for adapters that register a public POST endpoint: the\n\t * only other sites whose pages may send to it from a visitor's browser.\n\t */\n\tallowedOrigins?: ReadonlySet<string>\n\t/**\n\t * False when this adapter fills no slot `capture.gate` holds that can count without consent, as\n\t * far as the boot can tell, so it need not check its vendor accepts such events. Absent reads as\n\t * true.\n\t */\n\tadapterCountsWithoutConsent?: boolean\n\t/**\n\t * The collections bound as content items, the only ones whose refs ingest keeps, and whether\n\t * an item is also counted per page it appeared on. Absent means no item is bound.\n\t */\n\titems?: { collections: ReadonlySet<string>; pages: boolean }\n\t/** The plugin's mounts under `routes.api`, for adapters that register an endpoint of their own. */\n\troutes?: RoutePaths\n\t/**\n\t * The packages the host handed the plugin as `sdks`, for adapters that would otherwise load\n\t * them at runtime: GA4's Data API client, the native engine's MaxMind reader.\n\t */\n\tsdks?: AnalyticsSdks\n\t/**\n\t * The plugin's `jobs`: the queue and schedule of the maintenance task an adapter registers, or\n\t * false when the install registers no task and the adapter's own requests do that work instead.\n\t */\n\tjobs?: AdapterJobs\n\t/**\n\t * The host's `jobs.enableConcurrencyControl`: only then may a task an adapter registers carry a\n\t * concurrency key, which Payload refuses otherwise.\n\t */\n\tjobsConcurrency?: boolean\n\t/** Says something at init, once the instance can log: what the boot warns about rather than refuses. */\n\tnotice?: (message: string) => void\n}\n\n/** What a switched-off install hands an adapter that keeps its schema (`disabled: true`). */\nexport interface AdapterSchemaContext {\n\t/** The plugin's `jobs`, which decides whether the adapter's task slug is in the jobs enum. */\n\tjobs: AdapterJobs\n\t/** What the boot would warn about, which a switched-off install never says. */\n\tnotice?: (message: string) => void\n}\n\n/** Whom a source's label is read for: the request, and the scope its sources were listed for. */\nexport interface AdapterLabelArgs {\n\treq: PayloadRequest\n\t/** Null is install-wide, `*` is cross-scope. */\n\tscope: string | null\n}\n\nexport interface AnalyticsAdapter {\n\treadonly id: string\n\t/** The source's name wherever no reader is known (boot-time pickers, logs). */\n\treadonly label: string\n\t/**\n\t * The source's name for one reader, where it differs by language or by who reads. Read through\n\t * `sourceLabelFor`, which falls back to `label` when this fails.\n\t */\n\treadonly labelFor?: (args: AdapterLabelArgs) => string | Promise<string>\n\treadonly capabilities: AnalyticsCapabilities\n\t/** Browser-tracker proxying/boot descriptor. Absent when no public capture field is set. */\n\treadonly capture?: CaptureSupport\n\t/**\n\t * Where the adapter's own ingest endpoint listens, relative to `routes.api`, and how server code\n\t * reaches that pipeline directly. Server-side only, never serialized.\n\t */\n\treadonly ingest?: { path: string; track?: ServerTrack; hostname?: IngestHostnameResolver }\n\tisConfigured(): boolean\n\tquery(query: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult>\n\trealtime?(query: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult>\n\tregister?(config: Config, context?: AdapterRegisterContext): void\n\t/**\n\t * For `disabled: true`: adds exactly the schema `register` would (collections, fields, indexes,\n\t * task slugs) and nothing that runs, so a switched-off install keeps its tables.\n\t */\n\tregisterSchema?(config: Config, context: AdapterSchemaContext): void\n\t/**\n\t * Binds the adapter to the Payload instance a runtime is built for, whenever one is, with or\n\t * without `onInit`. Called again for every rebuild, so it must be idempotent per instance.\n\t */\n\tattach?(payload: Payload): void\n\t/**\n\t * Releases what the adapter holds for one instance (buffers, clients, timers) once that\n\t * instance's runtime is retired; another instance the adapter serves keeps what it holds.\n\t */\n\tclose?(payload: Payload): void | Promise<void>\n}\n\nexport type AnalyticsAdapterFactory<Config> = (config: Config) => AnalyticsAdapter\n"],"mappings":";;;;;AAeA,MAAa,iBAAiB;;AAiC9B,MAAa,iBAAiB;CAC7B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD;;AAYA,MAAa,mBAAmB;CAAC;CAAM;CAAY;AAAS"}
|
|
1
|
+
{"version":3,"file":"contract.js","names":[],"sources":["../../src/core/contract.ts"],"sourcesContent":["import type { Config, Payload, PayloadRequest } from 'payload'\nimport type { CurrencyConverter } from '../goals/currency'\nimport type { BrowserAmounts, OrderSignatureMode } from '../goals/match'\nimport type { Goal } from '../goals/types'\nimport type { TrustedPlatform } from '../net/platform'\nimport type { RoutePaths } from '../plugin/routes'\nimport type { CaptureSupport } from './capture'\nimport type { AdapterJobs } from './jobs'\nimport type { AnalyticsSdks } from './sdks'\nimport type { IngestHostnameResolver, ServerTrack } from './serverEvent'\n\n/**\n * Explicit cross-scope read marker: pass as a read's `scope` to aggregate over every\n * scope. Gated by `access.crossScope.aggregate`; the query reaches the adapter unscoped.\n */\nexport const PLATFORM_SCOPE = '*'\n\nexport type { AdapterJobs, AnalyticsTaskName, ScheduledTask } from './jobs'\n\nexport type MetricKey =\n\t| 'pageviews'\n\t| 'visitors'\n\t| 'visits'\n\t| 'sessions'\n\t| 'bounceRate'\n\t/** Time on page: engaged time per pageview, an average in milliseconds over the pageviews it is read for. */\n\t| 'avgDuration'\n\t/** Time per visit: engaged time per visit, an average in milliseconds over the visits it is read for. */\n\t| 'visitDuration'\n\t| 'scrollDepth'\n\t| 'events'\n\t| 'conversions'\n\t| 'revenue'\n\t/** Times a content item was seen on screen. Counted per item only, never per page or site. */\n\t| 'impressions'\n\t/** Clicks on a content item, the first per item and pageview. */\n\t| 'interactions'\n\n/**\n * One metric's reading. `null` is an average or a share with nothing to average over (no\n * pageviews to time, no scroll reported, no sessions to bounce): no data, not zero.\n */\nexport type MetricValue = number | null\n\n/** A row's or a read's metrics. A metric the source did not report is absent. */\nexport type MetricValues = Partial<Record<MetricKey, MetricValue>>\n\n/** Every breakdown key the contract defines, the list request parsers validate against. */\nexport const DIMENSION_KEYS = [\n\t'page',\n\t'referrer',\n\t'source',\n\t'channel',\n\t'medium',\n\t'campaign',\n\t'utmSource',\n\t'utmMedium',\n\t'utmCampaign',\n\t'utmContent',\n\t'utmTerm',\n\t'device',\n\t'browser',\n\t'os',\n\t'country',\n\t'region',\n\t'city',\n\t'language',\n\t'event',\n\t'goal',\n\t'currency',\n\t'item',\n] as const\n\nexport type DimensionKey = (typeof DIMENSION_KEYS)[number]\n\nexport type Granularity = 'minute' | 'hour' | 'day' | 'week' | 'month'\n\nexport interface DateRange {\n\tstart: Date\n\tend: Date\n}\n\n/** Every filter operator the contract defines, the list request parsers validate against. */\nexport const FILTER_OPERATORS = ['eq', 'contains', 'matches'] as const\n\nexport type FilterOperator = (typeof FILTER_OPERATORS)[number]\n\nexport interface AnalyticsFilter {\n\tdimension: DimensionKey\n\toperator: FilterOperator\n\tvalue: string\n}\n\nexport interface AnalyticsQuery {\n\tpath?: string\n\thostname?: string\n\t/**\n\t * One content item's ref (`<collection>:<id>`): the read answers about that item, wherever\n\t * it was shown. Only a source declaring `capabilities.perItemQuery` can serve it.\n\t */\n\titem?: string\n\tmetrics: MetricKey[]\n\tdimensions?: DimensionKey[]\n\tdateRange: DateRange\n\tgranularity?: Granularity\n\tfilters?: AnalyticsFilter[]\n\tlimit?: number\n\t/**\n\t * How a breakdown is ranked before `limit` cuts it. The metric belongs in `metrics`: ranked by\n\t * one the read did not ask for, rows keep the source's order.\n\t */\n\torder?: { metric: MetricKey; direction: 'asc' | 'desc' }\n\t/**\n\t * Analytics boundary of the read (tenant id, site key); undefined means install-wide. Adapters\n\t * that can filter by scope apply it, and it is always part of the cache key.\n\t */\n\tscope?: string\n\t/**\n\t * IANA timezone the read's day boundaries align to; undefined means UTC. Adapters that can bucket\n\t * in a zone apply it, others report in their account's own.\n\t */\n\ttimezone?: string\n\t/**\n\t * The scope's goal slugs, which provider adapters restrict goal rows to (native matches goals\n\t * itself). `'unresolved'` marks a failed goal resolver and never shares a healthy cache key.\n\t */\n\tgoalSlugs?: string[] | 'unresolved'\n}\n\nexport interface AnalyticsRow {\n\tdimensions?: Partial<Record<DimensionKey, string>>\n\tmetrics: MetricValues\n\ttimestamp?: string\n\t/**\n\t * How many observations each average in `metrics` was taken over, which folds days into weeks\n\t * exactly. An average without one is weighted by its row's matching count.\n\t */\n\tsamples?: Partial<Record<MetricKey, number>>\n}\n\n/** How a read's `visitors` were counted. */\nexport type VisitorCounting = 'distinct' | 'sumOfDaily'\n\n/** Why a stale answer's source needs a look: its settings were refused, or its host is not allowed. */\nexport type SourceErrorKind = 'misconfigured' | 'host-refused'\n\nexport interface AnalyticsResult {\n\trows: AnalyticsRow[]\n\ttotals?: MetricValues\n\tmeta: {\n\t\tprovider: string\n\t\t/** The source counted from a sample of its data (GA4 on a large property), so the numbers are estimates. */\n\t\tsampled?: boolean\n\t\t/** The read covers less than it asked for: from `dataFrom` and up to `dataTo`, where set. */\n\t\tclamped?: boolean\n\t\t/** ISO instant the data starts at, set with `clamped` when later than the range's start. */\n\t\tdataFrom?: string\n\t\t/**\n\t\t * ISO instant the data ends at, set with `clamped` when earlier than the range's end: a day\n\t\t * the range cuts lies past raw retention in a scope's own zone.\n\t\t */\n\t\tdataTo?: string\n\t\t/**\n\t\t * `distinct` counts each person once per number; `sumOfDaily` means some number adds up daily\n\t\t * visitors, so a person who came on two days counts twice.\n\t\t */\n\t\tvisitorsAre?: VisitorCounting\n\t\t/** Some days of the range could not be read yet, so the numbers are a floor. */\n\t\tpartial?: { missingDays: number }\n\t\t/**\n\t\t * On this many days of the range a value the read asks about was folded into the `(other)`\n\t\t * row of its daily totals, and its raw hits are no longer kept: the numbers are a floor.\n\t\t */\n\t\tcapped?: { days: number }\n\t\t/**\n\t\t * On this many days of the range counting failed again and again and was given up: each is\n\t\t * read from an earlier count when it had one, and left out otherwise.\n\t\t */\n\t\tfailed?: { days: number }\n\t\t/**\n\t\t * The scope's reporting timezone could not be resolved and none was ever recorded, so this\n\t\t * read cut its days in UTC and counted nothing for later reads.\n\t\t */\n\t\ttimezoneUnresolved?: true\n\t\t/** ISO instant the numbers were last brought up to date, when older than `fetchedAt`. */\n\t\tasOf?: string\n\t\t/**\n\t\t * ISO instant the source was read (`ctx.now`), never later than the engine got the answer; a\n\t\t * cached answer keeps it.\n\t\t */\n\t\tfetchedAt: string\n\t\t/**\n\t\t * ISO 4217 code `revenue` is reported in: the vendor's own, else the install's\n\t\t * `revenue.currency` or the read's `currency` filter. Absent, revenue is a plain sum as sent.\n\t\t */\n\t\tcurrency?: string\n\t\t/**\n\t\t * The currencies the read's revenue adds unconverted amounts of, when more than one. Native\n\t\t * sets it.\n\t\t */\n\t\tmixedCurrencies?: string[]\n\t\t/**\n\t\t * Served from a cache entry past its TTL: at once while a refresh runs, or because the refresh\n\t\t * failed. `asOf` then says when the entry was fetched.\n\t\t */\n\t\tstale?: boolean\n\t\t/**\n\t\t * Set on a stale answer whose source last failed as set up rather than as an outage:\n\t\t * credentials refused (`misconfigured`) or host not allowed (`host-refused`).\n\t\t */\n\t\tsourceError?: SourceErrorKind\n\t\t/**\n\t\t * Filters the source could not carry, so the rows are wider than the query asked for.\n\t\t * A provider whose API takes one value per dimension reports the ones it dropped here.\n\t\t */\n\t\tunappliedFilters?: AnalyticsFilter[]\n\t\t/**\n\t\t * The read's goal numbers are absent because resolving them failed. A scope with no goals gets\n\t\t * an empty result instead, not this flag.\n\t\t */\n\t\tgoalsUnresolved?: true\n\t\t/**\n\t\t * Pageviews of the read counted without consent, at a cookieless or anonymous level, which\n\t\t * the view shows as a share of all pageviews. Absent when the source cannot tell or found none.\n\t\t */\n\t\twithoutConsent?: { pageviews: number }\n\t\t/**\n\t\t * Pageviews of the read recorded without a visitor (native's anonymous level): they count as\n\t\t * pageviews, and toward no visitor, visit, bounce rate or time.\n\t\t */\n\t\twithoutVisitor?: { pageviews: number }\n\t\t/**\n\t\t * The vendor drops what a slot counts without consent, so those visits are missing from every\n\t\t * number: PostHog with its project's cookieless tracking setting off.\n\t\t */\n\t\twithoutConsentDropped?: true\n\t}\n}\n\n/**\n * The vendor's limits the source's lane keeps to, one token per upstream request per window. A read\n * with conversions may cost a second, goal-filtered request.\n */\nexport interface RateLimitDescriptor {\n\trequestsPerMinute?: number\n\trequestsPerHour?: number\n\t/** Upstream requests the source may have in flight; `cache.concurrency.perSource` when unset. */\n\tmaxConcurrent?: number\n\t/** Whether reads also spend the provider's write or ingest quota. */\n\treadsCountAsUsage?: boolean\n}\n\n/**\n * Which operators each dimension can be filtered with. A dimension absent here, or listed with\n * no operator, cannot be filtered at all.\n */\nexport type FilterOperatorMap = Partial<Record<DimensionKey, readonly FilterOperator[]>>\n\n/** Where a source reads one metric, when it cannot read it under every breakdown it offers. */\nexport interface MetricReach {\n\t/**\n\t * The breakdowns the metric is read under; empty when only whole-site numbers carry it.\n\t * Absent: every dimension the source declares.\n\t */\n\tdimensions?: readonly DimensionKey[]\n\t/**\n\t * A dimension the read must break down or filter by for the metric to have a value at all.\n\t * A read of one page (`AnalyticsQuery.path`) counts as filtering by `page`.\n\t */\n\trequires?: DimensionKey\n}\n\n/** What the numbers of a source mean where sources differ. */\nexport interface MetricSemantics {\n\t/**\n\t * `distinct` counts each person once over a range; `sumOfDaily` adds up each day's visitors.\n\t * Either may be per hostname: native's visitor id is, so two hostnames add up.\n\t */\n\tvisitors: VisitorCounting\n\t/** `inactivity30m` ends a visit after 30 minutes without activity; `provider` is the vendor's own rule. */\n\tsessions: 'inactivity30m' | 'provider'\n}\n\nexport interface AnalyticsCapabilities {\n\t/** The source answers `AnalyticsQuery.item`: one content item's views, clicks and outcomes. */\n\tperItemQuery?: boolean\n\trealtime: boolean\n\trealtimeWindowMinutes?: number\n\t/**\n\t * Period-over-period comparison, which the engine serves for every source by reading the\n\t * previous window itself. Adapters omit this; set it false only to opt a source out.\n\t */\n\tcomparison?: boolean\n\tminGranularity: Granularity\n\t/**\n\t * The source answers `week` and `month` series itself, exactly. Without it the engine reads\n\t * days and folds them into weeks and months in the read's reporting timezone.\n\t */\n\tcalendarBuckets?: boolean\n\tmaxLookbackDays: number | null\n\t/**\n\t * How far back a filtered read reaches, when that is shorter than `maxLookbackDays`: the\n\t * source narrows a longer one itself and marks it `clamped`. Absent or null: as far as any read.\n\t */\n\tfilterLookbackDays?: number | null\n\tmetrics: ReadonlySet<MetricKey>\n\tdimensions: ReadonlySet<DimensionKey>\n\t/**\n\t * Metrics the source reads only under some breakdowns or only for a page; any other is read under\n\t * every dimension. Reads outside a metric's reach are refused and hidden by pickers.\n\t */\n\tmetricReach?: Partial<Record<MetricKey, MetricReach>>\n\t/**\n\t * The `AnalyticsQuery.filters` the source applies, per dimension. A read carrying any other\n\t * pair is refused before it reaches the adapter. Absent: no filter at all.\n\t */\n\tfilters?: FilterOperatorMap\n\t/** What `visitors` and `sessions` mean here. Absent: not declared. */\n\tsemantics?: MetricSemantics\n\trateLimit: RateLimitDescriptor | null\n\t/**\n\t * Seconds an answer stays fresh. `today`, for a source cheap to read again, caps a window that\n\t * reaches into the current day whatever `cache.ttl` says; such an answer is never served stale.\n\t */\n\trecommendedTtl: { realtime: number; aggregate: number; today?: number }\n\t/**\n\t * The adapter applies `AnalyticsQuery.scope` as a native filter. Without it a scoped read through\n\t * a shared adapter would see other scopes, so it is gated by `access.crossScope.unscopedSource`.\n\t */\n\tscopedQueries?: boolean\n\t/**\n\t * The adapter sends every vendor request through `AdapterContext.upstream`, so each one spends\n\t * its own rate token and slot. Without it the engine counts a whole read as one request.\n\t */\n\tupstreamAware?: boolean\n}\n\nexport interface AdapterContext {\n\tsignal?: AbortSignal\n\t/**\n\t * The Payload instance the read is for, which the surfacing engine always passes. An adapter\n\t * that stores its data in Payload's database reads through it.\n\t */\n\tpayload?: Payload\n\t/**\n\t * Sends one vendor request through the source's lane: rate token, slot, retries on outage,\n\t * circuit breaker. Absent outside the engine, where `fn(ctx.signal)` is called directly.\n\t */\n\tupstream?: <T>(fn: (signal?: AbortSignal) => Promise<T>) => Promise<T>\n\t/**\n\t * Milliseconds the read has left before it gives up, for a vendor SDK that takes a deadline of\n\t * its own rather than a signal. Absent outside the engine.\n\t */\n\tremainingMs?: () => number\n\t/**\n\t * What time it is by the plugin's clock (Payload's), which an adapter stamps `meta.fetchedAt`\n\t * with. The engine always passes it; absent outside the engine.\n\t */\n\tnow?: () => Date\n}\n\n/** Extra context the plugin hands adapters when they register config surface. */\nexport interface AdapterRegisterContext {\n\t/** True when the plugin has `scope.resolve` configured. */\n\tscoped: boolean\n\t/**\n\t * `scope.resolve` at the `capture` call site, for ingest stamping: the host's resolver sees no\n\t * user, cookies or authorization header, so a hit files under the site it landed on.\n\t */\n\tresolveScope: (req: PayloadRequest) => Promise<string | null>\n\t/**\n\t * The plugin's reportingTimezone bound for adapter use, for what is shown in it. Resolves to\n\t * `'UTC'` when no reportingTimezone is set, and when the host's resolver fails.\n\t */\n\tresolveTimezone: (req: PayloadRequest, scope?: string | null) => Promise<string>\n\t/**\n\t * The same timezone, thrown rather than falling back to UTC: for an adapter storing days counted\n\t * in it, where recounting a day in UTC would move its numbers.\n\t */\n\tresolveTimezoneStrict: (req: PayloadRequest, scope?: string | null) => Promise<string>\n\t/** The install's `revenue` settings, for adapters that declare or reconcile revenue. */\n\trevenue: {\n\t\tenabled: boolean\n\t\tdimension: boolean\n\t\t/** `revenue.currency` bound for adapter use: `undefined` when none is set, revenue a plain number. */\n\t\tcurrency: (req: PayloadRequest, scope?: string | null) => Promise<string | undefined>\n\t\t/** `revenue.convert`, for adapters that reconcile revenue at ingest. */\n\t\tconvert?: CurrencyConverter\n\t\t/** `revenue.browserAmounts`, for an adapter that takes amounts from the browser itself. */\n\t\tbrowserAmounts?: BrowserAmounts\n\t\t/** `revenue.orderSignature`, for an adapter that takes the browser's order ids. */\n\t\torderSignature?: OrderSignatureMode\n\t}\n\t/**\n\t * The install's goals for a request's scope (config goals, the collection's merged over them),\n\t * for adapters that match completions themselves.\n\t */\n\tresolveGoals: (req: PayloadRequest, scope?: string | null) => Promise<Goal[]>\n\t/**\n\t * Whether a scope's own provider documents grant it this adapter; present only when the providers\n\t * collection runs under `scope.resolve`. Native ingest stores nothing for a scope it denies.\n\t */\n\tadapterGrantedForScope?: (\n\t\treq: PayloadRequest,\n\t\tscope: string | null,\n\t\tadapterId: string\n\t) => Promise<boolean>\n\t/** The plugin's `trustedProxyHops`, for adapters that read a request's client address. */\n\ttrustedProxyHops?: number\n\t/**\n\t * The plugin's `trustedPlatform`, for adapters that read a request's client address or\n\t * location: the only platform whose edge headers may be believed.\n\t */\n\ttrustedPlatform?: TrustedPlatform\n\t/**\n\t * `capture.allowedOrigins`, normalized, for adapters that register a public POST endpoint: the\n\t * only other sites whose pages may send to it from a visitor's browser.\n\t */\n\tallowedOrigins?: ReadonlySet<string>\n\t/**\n\t * False when this adapter fills no slot `capture.gate` holds that can count without consent, as\n\t * far as the boot can tell, so it need not check its vendor accepts such events. Absent reads as\n\t * true.\n\t */\n\tadapterCountsWithoutConsent?: boolean\n\t/**\n\t * The collections bound as content items, the only ones whose refs ingest keeps, and whether\n\t * an item is also counted per page it appeared on. Absent means no item is bound.\n\t */\n\titems?: { collections: ReadonlySet<string>; pages: boolean }\n\t/** The plugin's mounts under `routes.api`, for adapters that register an endpoint of their own. */\n\troutes?: RoutePaths\n\t/**\n\t * The packages the host handed the plugin as `sdks`, for adapters that would otherwise load\n\t * them at runtime: GA4's Data API client, the native engine's MaxMind reader.\n\t */\n\tsdks?: AnalyticsSdks\n\t/**\n\t * The plugin's `jobs`: the queue and schedule of the maintenance task an adapter registers, or\n\t * false when the install registers no task and the adapter's own requests do that work instead.\n\t */\n\tjobs?: AdapterJobs\n\t/**\n\t * The host's `jobs.enableConcurrencyControl`: only then may a task an adapter registers carry a\n\t * concurrency key, which Payload refuses otherwise.\n\t */\n\tjobsConcurrency?: boolean\n\t/** Says something at init, once the instance can log: what the boot warns about rather than refuses. */\n\tnotice?: (message: string) => void\n}\n\n/** What a switched-off install hands an adapter that keeps its schema (`disabled: true`). */\nexport interface AdapterSchemaContext {\n\t/** The plugin's `jobs`, which decides whether the adapter's task slug is in the jobs enum. */\n\tjobs: AdapterJobs\n\t/** What the boot would warn about, which a switched-off install never says. */\n\tnotice?: (message: string) => void\n}\n\n/** Whom a source's label is read for: the request, and the scope its sources were listed for. */\nexport interface AdapterLabelArgs {\n\treq: PayloadRequest\n\t/** Null is install-wide, `*` is cross-scope. */\n\tscope: string | null\n}\n\n/** What a connection check runs with. */\nexport interface ConnectionCheckContext {\n\t/** Ends the check: aborted once {@link ConnectionCheckContext.timeoutMs} has passed. */\n\tsignal: AbortSignal\n\t/** The time the check may take, for an SDK that wants a deadline rather than a signal. */\n\ttimeoutMs: number\n\t/** The instance the check runs on, for an adapter that keeps a client per instance. */\n\tpayload?: Payload\n}\n\nexport interface AnalyticsAdapter {\n\treadonly id: string\n\t/** The source's name wherever no reader is known (boot-time pickers, logs). */\n\treadonly label: string\n\t/**\n\t * The source's name for one reader, where it differs by language or by who reads. Read through\n\t * `sourceLabelFor`, which falls back to `label` when this fails.\n\t */\n\treadonly labelFor?: (args: AdapterLabelArgs) => string | Promise<string>\n\treadonly capabilities: AnalyticsCapabilities\n\t/** Browser-tracker proxying/boot descriptor. Absent when no public capture field is set. */\n\treadonly capture?: CaptureSupport\n\t/**\n\t * Where the adapter's own ingest endpoint listens, relative to `routes.api`, and how server code\n\t * reaches that pipeline directly. Server-side only, never serialized.\n\t */\n\treadonly ingest?: { path: string; track?: ServerTrack; hostname?: IngestHostnameResolver }\n\tisConfigured(): boolean\n\tquery(query: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult>\n\trealtime?(query: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult>\n\t/**\n\t * One cheap read that proves the source's settings work, behind a provider document's Test\n\t * connection: it resolves when the vendor accepts them and throws what a read would when it does\n\t * not. It does not go through the source's lane, so a rested source is tried anyway.\n\t */\n\tcheckConnection?(ctx: ConnectionCheckContext): Promise<void>\n\tregister?(config: Config, context?: AdapterRegisterContext): void\n\t/**\n\t * For `disabled: true`: adds exactly the schema `register` would (collections, fields, indexes,\n\t * task slugs) and nothing that runs, so a switched-off install keeps its tables.\n\t */\n\tregisterSchema?(config: Config, context: AdapterSchemaContext): void\n\t/**\n\t * Binds the adapter to the Payload instance a runtime is built for, whenever one is, with or\n\t * without `onInit`. Called again for every rebuild, so it must be idempotent per instance.\n\t */\n\tattach?(payload: Payload): void\n\t/**\n\t * Releases what the adapter holds for one instance (buffers, clients, timers) once that\n\t * instance's runtime is retired; another instance the adapter serves keeps what it holds.\n\t */\n\tclose?(payload: Payload): void | Promise<void>\n}\n\nexport type AnalyticsAdapterFactory<Config> = (config: Config) => AnalyticsAdapter\n"],"mappings":";;;;;AAeA,MAAa,iBAAiB;;AAiC9B,MAAa,iBAAiB;CAC7B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD;;AAYA,MAAa,mBAAmB;CAAC;CAAM;CAAY;AAAS"}
|
package/dist/core/options.d.ts
CHANGED
|
@@ -14,7 +14,7 @@ import { AnalyticsBinding } from "../binding/types.js";
|
|
|
14
14
|
import { TranslationsOption } from "../translations/index.js";
|
|
15
15
|
import { GoalCollectionFieldOverrides } from "../goals/collection.js";
|
|
16
16
|
import { ProviderHostPolicy } from "../providers/hosts.js";
|
|
17
|
-
import { ProviderId } from "../providers/
|
|
17
|
+
import { ProviderId } from "../providers/ids.js";
|
|
18
18
|
import { ConnectionAccess, ProviderCollectionFieldOverrides } from "../providers/collection.js";
|
|
19
19
|
import { AfterReadHook } from "../surfacing/afterRead.js";
|
|
20
20
|
import { TimeframePreset } from "../timeframe/presets.js";
|