@10x-media/analytics 1.0.0-beta.13 → 1.0.0-beta.15
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 +53 -0
- package/dist/adapters/ga4/ga4.d.ts +7 -0
- package/dist/adapters/ga4/ga4.js +17 -3
- package/dist/adapters/ga4/ga4.js.map +1 -1
- package/dist/adapters/plausible/plausible.d.ts +6 -0
- package/dist/adapters/plausible/plausible.js +6 -3
- package/dist/adapters/plausible/plausible.js.map +1 -1
- package/dist/adapters/posthog/posthog.d.ts +7 -0
- package/dist/adapters/posthog/posthog.js +92 -19
- package/dist/adapters/posthog/posthog.js.map +1 -1
- package/dist/adapters/posthog/projectCheck.js +56 -0
- package/dist/adapters/posthog/projectCheck.js.map +1 -0
- package/dist/adapters/umami/umami.d.ts +6 -0
- package/dist/adapters/umami/umami.js +3 -1
- package/dist/adapters/umami/umami.js.map +1 -1
- package/dist/capture/trackerConfig.js +29 -6
- package/dist/capture/trackerConfig.js.map +1 -1
- package/dist/capture/withoutConsent.js +91 -0
- package/dist/capture/withoutConsent.js.map +1 -0
- package/dist/core/capture.d.ts +41 -11
- package/dist/core/captureOptions.js +97 -8
- package/dist/core/captureOptions.js.map +1 -1
- package/dist/core/contract.d.ts +25 -0
- package/dist/core/contract.js.map +1 -1
- package/dist/core/options.d.ts +26 -4
- package/dist/core/options.js.map +1 -1
- package/dist/core/sourceOptions.js +2 -1
- package/dist/core/sourceOptions.js.map +1 -1
- package/dist/exports/adapters/contract.d.ts +3 -3
- package/dist/exports/adapters/ga4.d.ts +4 -4
- package/dist/exports/adapters/native.d.ts +5 -5
- package/dist/exports/adapters/plausible.d.ts +4 -4
- package/dist/exports/adapters/posthog.d.ts +4 -4
- package/dist/exports/adapters/umami.d.ts +4 -4
- package/dist/exports/next.d.ts +4 -4
- package/dist/exports/react.d.ts +3 -2
- package/dist/exports/site.d.ts +2 -2
- package/dist/exports/testing.d.ts +4 -4
- package/dist/exports/tracker.d.ts +3 -2
- package/dist/exports/types.d.ts +5 -5
- package/dist/index.d.ts +5 -5
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/native/collections/hits.js +1 -0
- package/dist/native/collections/hits.js.map +1 -1
- package/dist/native/engine/engine.js +5 -1
- package/dist/native/engine/engine.js.map +1 -1
- package/dist/native/engine/planner.js +2 -1
- package/dist/native/engine/planner.js.map +1 -1
- package/dist/native/engine/toHit.js +4 -2
- package/dist/native/engine/toHit.js.map +1 -1
- package/dist/native/ingest/endpoint.js +5 -2
- package/dist/native/ingest/endpoint.js.map +1 -1
- package/dist/native/ingest/normalizeEvent.d.ts +6 -1
- package/dist/native/ingest/normalizeEvent.js +17 -7
- package/dist/native/ingest/normalizeEvent.js.map +1 -1
- package/dist/native/ingest/serverTrack.js +2 -1
- package/dist/native/ingest/serverTrack.js.map +1 -1
- package/dist/native/ingest/validate.js +3 -0
- package/dist/native/ingest/validate.js.map +1 -1
- package/dist/native/nativeAdapter.d.ts +10 -1
- package/dist/native/nativeAdapter.js +11 -1
- package/dist/native/nativeAdapter.js.map +1 -1
- package/dist/native/store/aggregate.js +1 -1
- package/dist/native/store/aggregate.js.map +1 -1
- package/dist/native/store/hitRow.js +3 -0
- package/dist/native/store/hitRow.js.map +1 -1
- package/dist/native/store/hits.js +3 -1
- package/dist/native/store/hits.js.map +1 -1
- package/dist/native/store/mongo/aggregatePipelines.js +10 -2
- package/dist/native/store/mongo/aggregatePipelines.js.map +1 -1
- package/dist/native/store/mongo/pipelines.js +15 -5
- package/dist/native/store/mongo/pipelines.js.map +1 -1
- package/dist/native/store/parts.js +9 -3
- package/dist/native/store/parts.js.map +1 -1
- package/dist/native/store/rawRead.js +6 -3
- package/dist/native/store/rawRead.js.map +1 -1
- package/dist/native/store/sql/aggregateSql.js +6 -2
- package/dist/native/store/sql/aggregateSql.js.map +1 -1
- package/dist/native/store/sql/columns.js +1 -0
- package/dist/native/store/sql/columns.js.map +1 -1
- package/dist/native/store/sql/compile.js +19 -7
- package/dist/native/store/sql/compile.js.map +1 -1
- package/dist/native/store/types.d.ts +7 -1
- package/dist/native/store/types.js +10 -0
- package/dist/native/store/types.js.map +1 -0
- package/dist/plugin/createRuntime.js +10 -1
- package/dist/plugin/createRuntime.js.map +1 -1
- package/dist/plugin/runtime.js.map +1 -1
- package/dist/providers/collection.d.ts +4 -2
- package/dist/providers/collection.js +29 -4
- package/dist/providers/collection.js.map +1 -1
- package/dist/providers/factory.d.ts +9 -1
- package/dist/providers/factory.js +14 -5
- package/dist/providers/factory.js.map +1 -1
- package/dist/providers/registry.js +2 -1
- package/dist/providers/registry.js.map +1 -1
- package/dist/react/AnalyticsProvider.d.ts +6 -0
- package/dist/react/AnalyticsProvider.js.map +1 -1
- package/dist/react/useAnalytics.js +9 -5
- package/dist/react/useAnalytics.js.map +1 -1
- package/dist/site/AnalyticsScripts.d.ts +4 -3
- package/dist/site/AnalyticsScripts.js +18 -4
- package/dist/site/AnalyticsScripts.js.map +1 -1
- package/dist/surfacing/todaySplit.js +7 -1
- package/dist/surfacing/todaySplit.js.map +1 -1
- package/dist/tracker/config.d.ts +26 -1
- package/dist/tracker/config.js.map +1 -1
- package/dist/tracker/createTracker.d.ts +2 -1
- package/dist/tracker/createTracker.js +91 -59
- package/dist/tracker/createTracker.js.map +1 -1
- package/dist/tracker/gate.d.ts +8 -0
- package/dist/tracker/gate.js +61 -11
- package/dist/tracker/gate.js.map +1 -1
- package/dist/tracker/loadScript.js +2 -1
- package/dist/tracker/loadScript.js.map +1 -1
- package/dist/tracker/registry.js +14 -3
- package/dist/tracker/registry.js.map +1 -1
- package/dist/tracker/sinks/createSink.js +27 -8
- package/dist/tracker/sinks/createSink.js.map +1 -1
- package/dist/tracker/sinks/ga4.js +38 -6
- package/dist/tracker/sinks/ga4.js.map +1 -1
- package/dist/tracker/sinks/native.js +17 -3
- package/dist/tracker/sinks/native.js.map +1 -1
- package/dist/tracker/sinks/plausible.js +8 -2
- package/dist/tracker/sinks/plausible.js.map +1 -1
- package/dist/tracker/sinks/posthog.js +108 -16
- package/dist/tracker/sinks/posthog.js.map +1 -1
- package/dist/tracker/sinks/umami.js +2 -2
- package/dist/tracker/sinks/umami.js.map +1 -1
- package/dist/tracker/sinks/vendor.js +25 -11
- package/dist/tracker/sinks/vendor.js.map +1 -1
- package/dist/tracker/types.d.ts +10 -3
- package/dist/translations/ar.js +7 -0
- package/dist/translations/ar.js.map +1 -1
- package/dist/translations/de.js +7 -0
- package/dist/translations/de.js.map +1 -1
- package/dist/translations/en.js +7 -0
- package/dist/translations/en.js.map +1 -1
- package/dist/translations/es.js +7 -0
- package/dist/translations/es.js.map +1 -1
- package/dist/translations/fr.js +7 -0
- package/dist/translations/fr.js.map +1 -1
- package/dist/translations/id.js +7 -0
- package/dist/translations/id.js.map +1 -1
- package/dist/translations/keys.d.ts +7 -0
- package/dist/translations/keys.js +8 -1
- package/dist/translations/keys.js.map +1 -1
- package/dist/translations/ko.js +7 -0
- package/dist/translations/ko.js.map +1 -1
- package/dist/translations/pt.js +7 -0
- package/dist/translations/pt.js.map +1 -1
- package/dist/translations/ru.js +7 -0
- package/dist/translations/ru.js.map +1 -1
- package/dist/translations/uk.js +7 -0
- package/dist/translations/uk.js.map +1 -1
- package/dist/translations/zh.js +7 -0
- package/dist/translations/zh.js.map +1 -1
- package/dist/view/consentShare.js +15 -0
- package/dist/view/consentShare.js.map +1 -0
- package/dist/view/sections/OverviewCards.js +38 -28
- package/dist/view/sections/OverviewCards.js.map +1 -1
- package/dist/widgets/notices.js +6 -1
- package/dist/widgets/notices.js.map +1 -1
- package/dist/widgets/readMeta.d.ts +4 -0
- package/dist/widgets/readMeta.js +5 -0
- package/dist/widgets/readMeta.js.map +1 -1
- package/package.json +4 -4
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,58 @@
|
|
|
1
1
|
# @10x-media/analytics
|
|
2
2
|
|
|
3
|
+
## 1.0.0-beta.15
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- **Consent modes: a slot that waits for the consent manager can count without storing anything on the device, before an answer and after a refusal.** `capture.withoutConsent` decides what a held slot does in each phase without consent, and the plugin still stores no consent state and makes no legal decision ([Consent](https://docs.10xmedia.de/analytics/consent)).
|
|
8
|
+
|
|
9
|
+
**Behavioral:** the default is `'cookieless'`. A slot `capture.gate` holds now counts before the visitor answers and after a refusal, where 1.0.0-beta.14 sent nothing until `setGate(true)`: native as it always did, Plausible and Umami with their usual script, PostHog in posthog-js's cookieless mode. Each request still carries the visitor's IP address and user agent to the vendor or to native ingest. To keep 1.0.0-beta.14 exactly, set one option: `analytics({ capture: { withoutConsent: 'off' } })`, which renders the same tracker config and snippets and sends nothing without consent. An install that leaves the option unset while a held slot can count logs one line per boot naming the default. Whether a site may count without consent is the operator's decision: update the privacy policy and confirm with the data protection officer before shipping the default ([From 1.0.0-beta.14](https://docs.10xmedia.de/analytics/upgrading/beta-15)).
|
|
10
|
+
|
|
11
|
+
**Upgrade actions**
|
|
12
|
+
|
|
13
|
+
1. Set `capture.withoutConsent`: `'off'` for 1.0.0-beta.14's behaviour, `'cookieless'` to keep the default, `{ pending, refused }` per phase, or a function `({ slot, adapterId, kind, phase }) => 'cookieless' | 'off'`.
|
|
14
|
+
2. With a PostHog slot that counts without consent, turn on the project's **Cookieless tracking** (Settings, Web analytics), or PostHog drops those events, and give the read `apiKey` the `project:read` scope so the adapter can check it.
|
|
15
|
+
3. Behind a proxy, set `trustedProxyHops` or `trustedPlatform`: cookieless counting tells visitors apart by a hash of the client address.
|
|
16
|
+
4. On Postgres or SQLite in migrate mode, generate and run a migration (four nullable columns). Coming straight from 1.0.0-beta.11 on SQLite, apply the beta.12 page's providers-rebuild edit, which also removes `"without_consent"`.
|
|
17
|
+
5. Update a Content Security Policy that allows the PostHog or GA4 snippet by hash.
|
|
18
|
+
6. Code implementing `Tracker` or `AnalyticsApi` itself adds `mode`.
|
|
19
|
+
|
|
20
|
+
**Behavioral:** GA4 stays strict by default: its adapter declares `off` without consent, since its cookieless pings still reach Google. `ga4({ withoutConsent: 'cookieless' })` or a document's field opts it in: the snippet sets consent mode defaults, all four signals denied, before `gtag('config')`, and a grant updates `analytics_storage` alone.
|
|
21
|
+
|
|
22
|
+
**Behavioral:** a held slot that counts before an answer renders its snippet with the page, in a cookieless variant, so its first pageview counts. A grant runs it in full on the same page; a refusal or a revoke moves it to its refused level. After a revoke the only storage left is PostHog's `__ph_opt_in_out_<token>`: the PostHog sink also removes `ph_<token>_window_id`, and the GA4 sink expires `_ga` and `_ga_<id>` when the page had granted them, strict GA4 slots included.
|
|
23
|
+
|
|
24
|
+
**Behavioral:** the tracker reads no storage until some slot runs in full: the exclusion flag is read, and the old consent key deleted, only then, so a staff browser is counted by cookieless slots until that point. Plausible and Umami opt-out keys set by an exclusion or a strict refusal are cleared only once the slot runs in full.
|
|
25
|
+
|
|
26
|
+
**Behavioral:** a page restored from the back/forward cache returns held slots to their pending level, and a vendor already running in full keeps running until the manager answers again.
|
|
27
|
+
|
|
28
|
+
**Behavioral:** a PostHog read that finds cookieless pageviews reports visitors as a sum of days (`meta.visitorsAre: 'sumOfDaily'`).
|
|
29
|
+
|
|
30
|
+
**Behavioral:** the native ingest endpoint refuses an `m` other than `'f'`, `'c'` or `'a'` with `400 invalid_param` naming `m`. A beacon without `m` is stored as full.
|
|
31
|
+
|
|
32
|
+
**Breaking:** `Tracker.mode` and `AnalyticsApi.mode` are required members: each slot's `SlotMode` (`'off'`, `'cookieless'`, `'anonymous'`, `'full'`), `off` everywhere before a tracker boots.
|
|
33
|
+
|
|
34
|
+
**Additive:** `withoutConsent` on `native()`, `plausible()`, `umami()`, `posthog()` and `ga4()`, which beats the install's option for its slot; a **Without consent** field on PostHog, Plausible, Umami and GA4 provider documents (empty follows the install), with the override key `providers.collection.fields.withoutConsent`.
|
|
35
|
+
|
|
36
|
+
**Additive:** `native({ withoutConsent: 'anonymous' })` stores what native counts without consent with no visitor id, country only, and no time on page, scroll or items seen. Those hits count toward pageviews, events, goals and most breakdowns, and toward no visitor, visit or bounce rate; an erasure request naming a visitor cannot find them. Each hit stores its mode (`mode`: `f`, `c`, `a`), and server events map `identity: 'request'` to `f` and `'none'` to `a`. ([Anonymous hits](https://docs.10xmedia.de/analytics/native#anonymous-hits)).
|
|
37
|
+
|
|
38
|
+
**Behavioral:** native's time on page averages over pageviews that have a visitor, so server pageviews recorded with `identity: 'none'` no longer lower it.
|
|
39
|
+
|
|
40
|
+
**Additive:** reads gain `meta.withoutConsent` and `meta.withoutVisitor` (`{ pageviews }`) and `meta.withoutConsentDropped`. The analytics view shows the share of pageviews counted without consent; a read holding pageviews without a visitor says how many; a PostHog source whose project drops cookieless events says so in the admin. Every new note and field is translated in all built-in languages.
|
|
41
|
+
|
|
42
|
+
**Additive:** a production boot warning when a held slot can count cookielessly while neither `trustedProxyHops` nor `trustedPlatform` is set.
|
|
43
|
+
|
|
44
|
+
**Additive:** for adapter authors, `CaptureSupport.cookieless` (`{ kind: 'inherent' | 'switched', default? }`) and `withoutConsent`, `SnippetArgs` with `mode` and `withoutConsent`, `TrackerSlotConfig.withoutConsent`, `AdapterRegisterContext.countsWithoutConsent`, and the types `ConsentPhase`, `CookielessSupport`, `HeldSlotMode`, `HitMode`, `NativeWithoutConsent`, `SlotMode`, `SlotWithoutConsent`, `SnippetMode`, `WithoutConsentArgs`, `WithoutConsentFunction`, `WithoutConsentLevel` and `WithoutConsentOption`. An adapter that declares no `cookieless` sends nothing without consent, as before.
|
|
45
|
+
|
|
46
|
+
**Schema:** on SQL databases, `analytics_hits.mode`, `analytics_aggregates.pageviews_without_visitor` and `pageviews_without_consent`, and `analytics_providers.without_consent`, all nullable. Days counted before read the new counts as 0, with no recount. On a rolling deploy, a node on the old code that counts a day holding anonymous hits leaves the new counts empty until the day is counted again.
|
|
47
|
+
|
|
48
|
+
## 1.0.0-beta.14
|
|
49
|
+
|
|
50
|
+
### Patch Changes
|
|
51
|
+
|
|
52
|
+
- **Fix: the providers' create and edit views open again when the Provider select is narrowed.** In 1.0.0-beta.13 they answered 500 ("Functions cannot be passed directly to Client Components") on every install running the providers collection without `native()` in `adapters`, or with `providers.collection.types` naming fewer than every type: the select's `filterOptions` handed Payload's client form state option labels that were functions. It now hands over the types' values alone, which is all the client select reads. A document stored with a type the install no longer serves still opens showing its type, and its save is still refused on the **Provider** field ([Which provider types a document may have](https://docs.10xmedia.de/analytics/providers#which-provider-types-a-document-may-have)).
|
|
53
|
+
|
|
54
|
+
**Behavioral:** the docs no longer promise that `providers.collection.types` orders the select. Its first type is the default, and the select lists the types it offers in one fixed order, the order of the **Provider** column's values, so no install's column changes with the list. A host that wrapped `providers.collection.fields.provider` to map the result to values keeps working, and can drop the wrapper.
|
|
55
|
+
|
|
3
56
|
## 1.0.0-beta.13
|
|
4
57
|
|
|
5
58
|
### Minor Changes
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { WithoutConsentLevel } from "../../tracker/config.js";
|
|
1
2
|
import { Ga4Sdk } from "../../core/sdks.js";
|
|
2
3
|
import { AnalyticsAdapter } from "../../core/contract.js";
|
|
3
4
|
import { AdapterLabelOption } from "../../core/sourceLabel.js";
|
|
@@ -35,6 +36,12 @@ interface Ga4Config {
|
|
|
35
36
|
* but such a code throws when the adapter is built.
|
|
36
37
|
*/
|
|
37
38
|
currency?: string;
|
|
39
|
+
/**
|
|
40
|
+
* What this source's held slot does without consent, over `capture.withoutConsent`. Unset, GA4
|
|
41
|
+
* sends nothing until consent, since its cookieless pings still reach Google. `'cookieless'` loads
|
|
42
|
+
* the tag with every consent signal denied (Consent Mode "advanced") and grants on consent.
|
|
43
|
+
*/
|
|
44
|
+
withoutConsent?: WithoutConsentLevel;
|
|
38
45
|
}
|
|
39
46
|
declare function ga4(config: Ga4Config): AnalyticsAdapter;
|
|
40
47
|
//#endregion
|
package/dist/adapters/ga4/ga4.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { DIMENSION_KEYS } from "../../core/contract.js";
|
|
2
2
|
import { adapterLabel } from "../../core/sourceLabel.js";
|
|
3
3
|
import { jsLiteral } from "../../capture/jsLiteral.js";
|
|
4
|
+
import { WITHOUT_CONSENT_LEVELS, adapterWithoutConsent, cookielessCapture } from "../../capture/withoutConsent.js";
|
|
4
5
|
import { MEASUREMENT_ID_PATTERN } from "./measurementId.js";
|
|
5
6
|
import { CURRENCY_PATTERN, currencyOption } from "../../goals/currency.js";
|
|
6
7
|
import { vendorReading } from "../../core/metricValues.js";
|
|
@@ -33,14 +34,20 @@ const cancelWhenAborted = (call, signal) => {
|
|
|
33
34
|
call.then(() => signal.removeEventListener("abort", onAbort), () => signal.removeEventListener("abort", onAbort));
|
|
34
35
|
};
|
|
35
36
|
/**
|
|
37
|
+
* Consent mode's defaults for a slot counting without consent ("advanced" mode), set before the tag
|
|
38
|
+
* loads: analytics storage only once in full, and advertising signals never, unless the host grants them.
|
|
39
|
+
*/
|
|
40
|
+
const consentDefault = (mode) => `gtag("consent","default",{analytics_storage:${jsLiteral(mode === "full" ? "granted" : "denied")},ad_storage:"denied",ad_user_data:"denied",ad_personalization:"denied"});`;
|
|
41
|
+
/**
|
|
36
42
|
* Google's install snippet, inline first as consent mode expects, led by the exclusion guard. The
|
|
37
|
-
* tag loads from Google's CDN, so `routes` stays empty and the slot's proxy mount answers 404.
|
|
43
|
+
* tag loads from Google's CDN, so `routes` stays empty and the slot's proxy mount answers 404. A
|
|
44
|
+
* snippet started cookieless reads no storage, so no guard: the tracker reads the flag once in full.
|
|
38
45
|
*/
|
|
39
46
|
function buildCapture(measurementId) {
|
|
40
47
|
const id = jsLiteral(measurementId);
|
|
41
48
|
return {
|
|
42
49
|
proxy: { routes: [] },
|
|
43
|
-
snippet: () => ({ scripts: [{ inline: `${ga4ExcludeGuard(measurementId)}window.dataLayer=window.dataLayer||[];function gtag(){dataLayer.push(arguments)}gtag("js",new Date());gtag("config",${id})` }, {
|
|
50
|
+
snippet: ({ mode = "full", withoutConsent = false }) => ({ scripts: [{ inline: `${mode === "cookieless" ? "" : ga4ExcludeGuard(measurementId)}window.dataLayer=window.dataLayer||[];function gtag(){dataLayer.push(arguments)}${withoutConsent ? consentDefault(mode) : ""}gtag("js",new Date());gtag("config",${id})` }, {
|
|
44
51
|
src: `https://www.googletagmanager.com/gtag/js?id=${encodeURIComponent(measurementId)}`,
|
|
45
52
|
async: true
|
|
46
53
|
}] }),
|
|
@@ -213,6 +220,7 @@ function ga4(config) {
|
|
|
213
220
|
upstreamAware: true
|
|
214
221
|
};
|
|
215
222
|
const configCurrency = currencyOption("ga4({ currency })", config.currency);
|
|
223
|
+
const withoutConsent = adapterWithoutConsent(config.withoutConsent, "ga4({ withoutConsent })", WITHOUT_CONSENT_LEVELS);
|
|
216
224
|
/** One client per Payload instance, so closing one instance's leaves the others' open. */
|
|
217
225
|
const clients = /* @__PURE__ */ new WeakMap();
|
|
218
226
|
/** The instances this adapter was closed for, which get no client again until attached anew. */
|
|
@@ -242,7 +250,13 @@ function ga4(config) {
|
|
|
242
250
|
id: "ga4",
|
|
243
251
|
...adapterLabel(config.label, "Google Analytics 4", "ga4({ label })"),
|
|
244
252
|
capabilities,
|
|
245
|
-
...measurementId && MEASUREMENT_ID_PATTERN.test(measurementId) ? { capture:
|
|
253
|
+
...measurementId && MEASUREMENT_ID_PATTERN.test(measurementId) ? { capture: {
|
|
254
|
+
...buildCapture(measurementId),
|
|
255
|
+
...cookielessCapture({
|
|
256
|
+
kind: "switched",
|
|
257
|
+
default: "off"
|
|
258
|
+
}, withoutConsent)
|
|
259
|
+
} } : {},
|
|
246
260
|
isConfigured: () => Boolean(config.propertyId && config.credentials?.client_email && config.credentials?.private_key),
|
|
247
261
|
register(_config, context) {
|
|
248
262
|
pluginSdk = context?.sdks?.ga4;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ga4.js","names":[],"sources":["../../../src/adapters/ga4/ga4.ts"],"sourcesContent":["import type { Payload } from 'payload'\nimport { jsLiteral } from '../../capture/jsLiteral'\nimport type { CaptureSupport } from '../../core/capture'\nimport {\n\ttype AdapterContext,\n\ttype AnalyticsAdapter,\n\ttype AnalyticsCapabilities,\n\ttype AnalyticsQuery,\n\ttype AnalyticsResult,\n\ttype AnalyticsRow,\n\tDIMENSION_KEYS,\n\ttype DimensionKey,\n\ttype FilterOperator,\n\ttype MetricKey,\n\ttype MetricReach,\n\ttype MetricValues,\n} from '../../core/contract'\nimport { vendorReading } from '../../core/metricValues'\nimport type { Ga4Client, Ga4ReportResponse, Ga4ReportRow, Ga4Sdk } from '../../core/sdks'\nimport { type AdapterLabelOption, adapterLabel } from '../../core/sourceLabel'\nimport { CURRENCY_PATTERN, currencyOption } from '../../goals/currency'\nimport { GA4_SDK_WARNING, isProductionBuild, loadGa4 } from '../../plugin/peers'\nimport {\n\temptyGoalBreakdown,\n\ttype GoalKeyedRow,\n\tgoalHint,\n\thintSlugs,\n\tmergeGoalRows,\n\tmergeGoalTotals,\n\treadGoalPair,\n\tsplitGoalMetrics,\n} from '../goalRead'\nimport {\n\tcalendarDays,\n\tdeclaredFilters,\n\teveryOperatorOn,\n\tmappedKeys,\n\tproviderMetricKeys,\n\treadableMetrics,\n} from '../mapping'\nimport { readTime } from '../readTime'\nimport { datedRows, dayIso } from '../series'\nimport { upstream } from '../upstream'\nimport { ga4ExcludeGuard } from './disableKey'\nimport { ga4EventName } from './eventName'\nimport { MEASUREMENT_ID_PATTERN } from './measurementId'\n\nexport interface Ga4Config {\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 `'Google Analytics 4'`.\n\t */\n\tlabel?: AdapterLabelOption\n\t/** GA4 property id (numeric), e.g. '123456789'. */\n\tpropertyId: string\n\t/** Service-account credentials. */\n\tcredentials: { client_email: string; private_key: string }\n\t/** GCP project id; inferred from the credentials when omitted. */\n\tprojectId?: string\n\t/** Maximum days of historical data. Defaults to 425 (GA4's rolling-window limit). Pass null to disable clamping. */\n\tmaxLookbackDays?: number | null\n\t/**\n\t * Public measurement id (`G-XXXXXXX`). Setting it turns on capture: the tag is loaded\n\t * from googletagmanager.com and booted with gtag.\n\t */\n\tmeasurementId?: string\n\t/**\n\t * `{ BetaAnalyticsDataClient }` from `@google-analytics/data`. Unset, the plugin's `sdks.ga4`\n\t * serves, and without either it is loaded at runtime, which a standalone build does not ship.\n\t */\n\tsdk?: Ga4Sdk\n\t/**\n\t * The property's ISO 4217 currency, used only when an answer names none; GA4's own wins. Anything\n\t * but such a code throws when the adapter is built.\n\t */\n\tcurrency?: string\n}\n\n/** How long one report may take when the adapter is called outside the engine, which sets its own. */\nconst DEFAULT_REPORT_TIMEOUT_MS = 60_000\n\n/**\n * Cancels a Data API call when its read gives up, where `cancel` survives: `@google-analytics/data`\n * 6.1 drops it, leaving the call's own gRPC `timeout` to bound it.\n */\nconst cancelWhenAborted = (call: Promise<unknown>, signal: AbortSignal | undefined): void => {\n\tconst cancel: unknown = Reflect.get(call, 'cancel')\n\tif (!signal || typeof cancel !== 'function') {\n\t\treturn\n\t}\n\tconst onAbort = (): void => {\n\t\tReflect.apply(cancel, call, [])\n\t}\n\tif (signal.aborted) {\n\t\tonAbort()\n\t\treturn\n\t}\n\tsignal.addEventListener('abort', onAbort, { once: true })\n\tvoid call.then(\n\t\t() => signal.removeEventListener('abort', onAbort),\n\t\t() => signal.removeEventListener('abort', onAbort)\n\t)\n}\n\n/**\n * Google's install snippet, inline first as consent mode expects, led by the exclusion guard. The\n * tag loads from Google's CDN, so `routes` stays empty and the slot's proxy mount answers 404.\n */\nfunction buildCapture(measurementId: string): CaptureSupport {\n\tconst id = jsLiteral(measurementId)\n\treturn {\n\t\tproxy: { routes: [] },\n\t\tsnippet: () => ({\n\t\t\tscripts: [\n\t\t\t\t{\n\t\t\t\t\tinline: `${ga4ExcludeGuard(measurementId)}window.dataLayer=window.dataLayer||[];function gtag(){dataLayer.push(arguments)}gtag(\"js\",new Date());gtag(\"config\",${id})`,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tsrc: `https://www.googletagmanager.com/gtag/js?id=${encodeURIComponent(measurementId)}`,\n\t\t\t\t\tasync: true,\n\t\t\t\t},\n\t\t\t],\n\t\t}),\n\t\tclient: { kind: 'ga4', measurementId },\n\t}\n}\n\nconst METRIC_MAP: Partial<Record<MetricKey, string>> = {\n\tpageviews: 'screenPageViews',\n\tvisitors: 'totalUsers',\n\tvisits: 'sessions',\n\tsessions: 'sessions',\n\tbounceRate: 'bounceRate',\n\tvisitDuration: 'averageSessionDuration',\n\tevents: 'eventCount',\n\tconversions: 'keyEvents',\n\trevenue: 'totalRevenue',\n}\n\nconst ENGAGED_SECONDS = 'userEngagementDuration'\nconst VIEWS = 'screenPageViews'\n\n/**\n * The GA4 metrics each contract metric is read from. Time on page is engaged seconds over views;\n * both are sums, so the ratio holds per row and for the totals alike.\n */\nconst METRIC_SOURCES: Partial<Record<MetricKey, string | readonly string[]>> = {\n\t...METRIC_MAP,\n\tavgDuration: [ENGAGED_SECONDS, VIEWS],\n}\n\nconst DIMENSION_MAP: Partial<Record<DimensionKey, string>> = {\n\tpage: 'pagePath',\n\treferrer: 'pageReferrer',\n\tsource: 'sessionSource',\n\tchannel: 'sessionDefaultChannelGroup',\n\tmedium: 'sessionMedium',\n\tcampaign: 'sessionCampaignName',\n\tutmSource: 'sessionSource',\n\tutmMedium: 'sessionMedium',\n\tutmCampaign: 'sessionCampaignName',\n\tdevice: 'deviceCategory',\n\tbrowser: 'browser',\n\tos: 'operatingSystem',\n\tcountry: 'countryId',\n\tregion: 'region',\n\tcity: 'city',\n\tlanguage: 'language',\n\tevent: 'eventName',\n\tgoal: 'eventName',\n}\n\n/**\n * Metrics GA4 answers only for a goal-restricted read. `keyEvents` counts only events the property\n * marks as key events, so a goal here that GA4 does not mark reports 0.\n */\nconst GOAL_METRICS: ReadonlySet<MetricKey> = new Set(['conversions'])\n\n/**\n * The hint's slugs by the GA4 event name each normalizes to, for the request and mapping rows back.\n * Two slugs normalizing alike are one GA4 event: the first slug owns its rows.\n */\nconst goalSlugsByEventName = (slugs: string[]): Map<string, string> => {\n\tconst byName = new Map<string, string>()\n\tfor (const slug of slugs) {\n\t\tconst name = ga4EventName(slug)\n\t\tif (!byName.has(name)) {\n\t\t\tbyName.set(name, slug)\n\t\t}\n\t}\n\treturn byName\n}\n\ntype StringMatchType = 'EXACT' | 'CONTAINS' | 'FULL_REGEXP'\n\n/**\n * FULL_REGEXP is a full match, so a pattern has to cover the whole value (`/docs/.*`, not\n * `^/docs`). PARTIAL_REGEXP exists but is not the contract's `matches`.\n */\nconst MATCH_TYPE_MAP: Record<FilterOperator, StringMatchType> = {\n\teq: 'EXACT',\n\tcontains: 'CONTAINS',\n\tmatches: 'FULL_REGEXP',\n}\n\n// The Data API defaults caseSensitive to false, so it is explicit: `contains` stays\n// insensitive like native and Umami's ilike, while `eq` and `matches` compare literally.\nconst CASE_SENSITIVE: Record<StringMatchType, boolean> = {\n\tEXACT: true,\n\tCONTAINS: false,\n\tFULL_REGEXP: true,\n}\n\n/**\n * A filter expression as the Data API reads one (`FilterExpression` in its REST reference), written\n * here so the adapter needs no type of the SDK.\n */\ninterface FilterExpression {\n\tfilter?: {\n\t\tfieldName: string\n\t\tstringFilter?: { matchType: StringMatchType; value: string; caseSensitive: boolean }\n\t\tinListFilter?: { values: string[]; caseSensitive: boolean }\n\t}\n\tandGroup?: { expressions: FilterExpression[] }\n}\n\n/** The parts of a `RunReportRequest` a read adds to the property, the window and the metrics. */\ninterface ReportShape {\n\tdimensions?: Array<{ name: string }>\n\tmetricAggregations?: Array<'TOTAL'>\n\torderBys?: Array<{ dimension: { dimensionName: string } }>\n\tlimit?: number\n}\n\nconst stringFilter = (\n\tfieldName: string,\n\tmatchType: StringMatchType,\n\tvalue: string\n): FilterExpression => ({\n\tfilter: {\n\t\tfieldName,\n\t\tstringFilter: { matchType, value, caseSensitive: CASE_SENSITIVE[matchType] },\n\t},\n})\n\n/** `exprs` as one dimension filter: none, the only one, or all of them and-ed. */\nconst allOf = (exprs: FilterExpression[]): FilterExpression | undefined =>\n\texprs.length > 1 ? { andGroup: { expressions: exprs } } : exprs[0]\n\nconst ga4Metrics: ReadonlySet<MetricKey> = new Set<MetricKey>([\n\t'pageviews',\n\t'visitors',\n\t'visits',\n\t'sessions',\n\t'bounceRate',\n\t'avgDuration',\n\t'visitDuration',\n\t'events',\n\t'conversions',\n\t'revenue',\n])\nconst ga4Dimensions = mappedKeys(DIMENSION_KEYS, DIMENSION_MAP)\n/**\n * Views are page_view and screen_view events only, so a time on page per event name divides the\n * engagement of one event by the views of another: it is read under every other breakdown.\n */\nconst ga4Reach: Partial<Record<MetricKey, MetricReach>> = {\n\tavgDuration: {\n\t\tdimensions: [...ga4Dimensions].filter(\n\t\t\t(dimension) => dimension !== 'event' && dimension !== 'goal'\n\t\t),\n\t},\n}\nconst ga4Filters = everyOperatorOn(ga4Dimensions)\n\n// GA4 returns bounceRate as a 0..1 ratio and averageSessionDuration in seconds; the\n// contract uses a 0..100 percentage and milliseconds.\nconst toContractValue = (metric: MetricKey, raw: number): number => {\n\tif (metric === 'visitDuration') {\n\t\treturn Math.round(raw * 1000)\n\t}\n\tif (metric === 'bounceRate') {\n\t\treturn Math.round(raw * 100)\n\t}\n\treturn raw\n}\n\ninterface Ga4Reading {\n\tmetrics: MetricValues\n\t/** The views each time on page was taken over, which folds days into weeks exactly. */\n\tsamples?: Partial<Record<MetricKey, number>>\n}\n\n/** One report row's contract metrics, each read back by GA4 name from the report's `names`. */\nconst readRow = (metrics: MetricKey[], names: string[], row: Ga4ReportRow): Ga4Reading => {\n\tconst raw = (name: string): unknown => row.metricValues?.[names.indexOf(name)]?.value\n\tconst out: MetricValues = {}\n\tlet samples: Ga4Reading['samples']\n\tfor (const metric of metrics) {\n\t\tif (metric === 'avgDuration') {\n\t\t\tconst views = vendorReading('pageviews', raw(VIEWS)) ?? 0\n\t\t\tconst engaged = vendorReading('avgDuration', raw(ENGAGED_SECONDS))\n\t\t\tout.avgDuration = views > 0 && engaged !== null ? Math.round((engaged / views) * 1000) : null\n\t\t\tsamples = { avgDuration: views }\n\t\t\tcontinue\n\t\t}\n\t\tconst name = METRIC_MAP[metric]\n\t\tconst value = name === undefined ? null : vendorReading(metric, raw(name))\n\t\tout[metric] = value === null ? null : toContractValue(metric, value)\n\t}\n\treturn samples ? { metrics: out, samples } : { metrics: out }\n}\n\n/** A report's rows keyed by their dimension values; undefined when the report was never run. */\nconst keyedRows = (\n\tresponse: Ga4ReportResponse | undefined,\n\tmetrics: MetricKey[],\n\tnames: string[]\n): GoalKeyedRow[] | undefined =>\n\tresponse?.rows?.map((row) => ({\n\t\tkeys: (row.dimensionValues ?? []).map((value) => value.value ?? ''),\n\t\t...readRow(metrics, names, row),\n\t})) ?? (response ? [] : undefined)\n\nconst totalsOf = (\n\tresponse: Ga4ReportResponse | undefined,\n\tmetrics: MetricKey[],\n\tnames: string[]\n): MetricValues | undefined => {\n\tconst row = response?.totals?.[0]\n\treturn row ? readRow(metrics, names, row).metrics : undefined\n}\n\n/** GA4's `date` dimension value (`YYYYMMDD`) as a UTC-day ISO string. */\nconst ga4DayIso = (ymd: string): string | null =>\n\tdayIso(`${ymd.slice(0, 4)}-${ymd.slice(4, 6)}-${ymd.slice(6, 8)}`)\n\nexport function ga4(config: Ga4Config): AnalyticsAdapter {\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 425\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\trealtime: false,\n\t\tminGranularity: 'day',\n\t\tmaxLookbackDays,\n\t\tmetrics: ga4Metrics,\n\t\tdimensions: ga4Dimensions,\n\t\tmetricReach: ga4Reach,\n\t\tfilters: ga4Filters,\n\t\tsemantics: { visitors: 'distinct', sessions: 'provider' },\n\t\trateLimit: { maxConcurrent: 10, readsCountAsUsage: true },\n\t\trecommendedTtl: { realtime: 300, aggregate: 21600 },\n\t\tupstreamAware: true,\n\t}\n\tconst configCurrency = currencyOption('ga4({ currency })', config.currency)\n\n\t/** One client per Payload instance, so closing one instance's leaves the others' open. */\n\tconst clients = new WeakMap<object, Promise<Ga4Client>>()\n\t/** The instances this adapter was closed for, which get no client again until attached anew. */\n\tconst closed = new WeakSet<object>()\n\t/** Whom a read with no instance in its context shares a client with. */\n\tconst unattached = {}\n\t/** The plugin's `sdks.ga4`, handed over when the plugin registers this adapter. */\n\tlet pluginSdk: Ga4Sdk | undefined\n\tlet warned = false\n\tconst sdk = (): Ga4Sdk | undefined => config.sdk ?? pluginSdk\n\n\tconst getClient = (payload: Payload | undefined): Promise<Ga4Client> => {\n\t\tconst owner = payload ?? unattached\n\t\tconst held = clients.get(owner)\n\t\tif (held) {\n\t\t\treturn held\n\t\t}\n\t\t// A read that reaches a closed adapter late (a retired runtime's refresh) would otherwise\n\t\t// open a client nothing ever closes.\n\t\tif (closed.has(owner)) {\n\t\t\treturn Promise.reject(new Error('analytics: this GA4 source was closed'))\n\t\t}\n\t\tconst created = (async () => {\n\t\t\tconst mod = sdk() ?? (await loadGa4())\n\t\t\treturn new mod.BetaAnalyticsDataClient({\n\t\t\t\tcredentials: config.credentials,\n\t\t\t\t...(config.projectId ? { projectId: config.projectId } : {}),\n\t\t\t})\n\t\t})()\n\t\tclients.set(owner, created)\n\t\treturn created\n\t}\n\n\tconst measurementId = config.measurementId\n\treturn {\n\t\tid: 'ga4',\n\t\t...adapterLabel(config.label, 'Google Analytics 4', 'ga4({ label })'),\n\t\tcapabilities,\n\t\t// An id that is not a bare token is dropped rather than escaped: it lands in an inline\n\t\t// script and in the tag URL, and no legitimate measurement id needs anything else.\n\t\t...(measurementId && MEASUREMENT_ID_PATTERN.test(measurementId)\n\t\t\t? { capture: buildCapture(measurementId) }\n\t\t\t: {}),\n\t\tisConfigured: () =>\n\t\t\tBoolean(\n\t\t\t\tconfig.propertyId && config.credentials?.client_email && config.credentials?.private_key\n\t\t\t),\n\t\tregister(_config, context) {\n\t\t\tpluginSdk = context?.sdks?.ga4\n\t\t},\n\t\t// At boot, before the first read fails in front of an editor.\n\t\tattach(payload: Payload) {\n\t\t\tclosed.delete(payload)\n\t\t\tif (!warned && sdk() === undefined && isProductionBuild()) {\n\t\t\t\twarned = true\n\t\t\t\tpayload.logger?.warn(GA4_SDK_WARNING)\n\t\t\t}\n\t\t},\n\t\tasync close(payload: Payload) {\n\t\t\tclosed.add(payload)\n\t\t\tconst held = clients.get(payload)\n\t\t\tclients.delete(payload)\n\t\t\tconst client = await held?.catch(() => undefined)\n\t\t\tawait client?.close?.()\n\t\t},\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = readTime(ctx)\n\t\t\tconst dims = (q.dimensions ?? []).filter((d) => DIMENSION_MAP[d])\n\t\t\tconst goalBreakdown = dims.includes('goal')\n\t\t\tconst hint = goalHint(q)\n\t\t\tconst empty = goalBreakdown ? emptyGoalBreakdown({ provider: 'ga4', fetchedAt, hint }) : null\n\t\t\tif (empty) {\n\t\t\t\treturn empty\n\t\t\t}\n\t\t\tconst { siteMetrics, goalMetrics, unresolved } = splitGoalMetrics({\n\t\t\t\twanted: readableMetrics(capabilities, q, dims),\n\t\t\t\tgoalOnly: GOAL_METRICS,\n\t\t\t\tgoalBreakdown,\n\t\t\t\thint,\n\t\t\t})\n\t\t\tconst siteNames = providerMetricKeys(siteMetrics, METRIC_SOURCES)\n\t\t\tconst goalNames = providerMetricKeys(goalMetrics, METRIC_SOURCES)\n\t\t\tconst providerDims = [...new Set(dims.flatMap((d) => DIMENSION_MAP[d] ?? []))]\n\t\t\t// Set when GA4 rejects a goal report the site report survived, so the rows keep their\n\t\t\t// site metrics and lose only their conversions.\n\t\t\tlet goalsFailed = false\n\t\t\t// What the answers said about themselves: a sampled report anywhere makes the read an estimate.\n\t\t\tlet sampled = false\n\t\t\tlet reportedCurrency: string | undefined\n\t\t\tconst meta = (): AnalyticsResult['meta'] => {\n\t\t\t\tconst currency = reportedCurrency ?? configCurrency\n\t\t\t\treturn {\n\t\t\t\t\tprovider: 'ga4',\n\t\t\t\t\tfetchedAt,\n\t\t\t\t\t...(currency ? { currency } : {}),\n\t\t\t\t\t...(sampled ? { sampled: true } : {}),\n\t\t\t\t\t...(unresolved || goalsFailed ? { goalsUnresolved: true as const } : {}),\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst filterExprs: FilterExpression[] = []\n\t\t\tif (q.path) {\n\t\t\t\tfilterExprs.push(stringFilter('pagePath', 'EXACT', q.path))\n\t\t\t}\n\t\t\tif (q.hostname) {\n\t\t\t\tfilterExprs.push(stringFilter('hostName', 'EXACT', q.hostname))\n\t\t\t}\n\t\t\tfor (const { filter, field } of declaredFilters(capabilities, q.filters, DIMENSION_MAP)) {\n\t\t\t\tfilterExprs.push(stringFilter(field, MATCH_TYPE_MAP[filter.operator], filter.value))\n\t\t\t}\n\t\t\tconst slugs = hintSlugs(hint)\n\t\t\tconst goalSlugs = slugs ? goalSlugsByEventName(slugs) : null\n\t\t\tconst goalExprs: FilterExpression[] = goalSlugs\n\t\t\t\t? [\n\t\t\t\t\t\t...filterExprs,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfilter: {\n\t\t\t\t\t\t\t\tfieldName: 'eventName',\n\t\t\t\t\t\t\t\tinListFilter: { values: [...goalSlugs.keys()], caseSensitive: true },\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t]\n\t\t\t\t: filterExprs\n\t\t\t// A goal breakdown restricts its own rows, so its one report carries the hint too.\n\t\t\tconst siteExprs = goalBreakdown ? goalExprs : filterExprs\n\n\t\t\tconst [startDate, endDate] = calendarDays(q)\n\t\t\tconst client = await getClient(ctx.payload)\n\n\t\t\t// Each report is one upstream request with its own token, so a paired read spends two. It\n\t\t\t// runs with no retry of the SDK's own (the lane retries) and a deadline of what the read has left.\n\t\t\tconst runReport = (\n\t\t\t\tnames: string[],\n\t\t\t\texprs: FilterExpression[],\n\t\t\t\tshape: ReportShape\n\t\t\t): Promise<Ga4ReportResponse> =>\n\t\t\t\tupstream(ctx, async (signal) => {\n\t\t\t\t\tconst dimensionFilter = allOf(exprs)\n\t\t\t\t\tconst request = {\n\t\t\t\t\t\tproperty: `properties/${config.propertyId}`,\n\t\t\t\t\t\tdateRanges: [{ startDate, endDate }],\n\t\t\t\t\t\tmetrics: names.map((name) => ({ name })),\n\t\t\t\t\t\t...(dimensionFilter ? { dimensionFilter } : {}),\n\t\t\t\t\t\t...shape,\n\t\t\t\t\t}\n\t\t\t\t\tconst timeout = Math.max(1, Math.floor(ctx.remainingMs?.() ?? DEFAULT_REPORT_TIMEOUT_MS))\n\t\t\t\t\tconst call = client.runReport(request, { timeout, retry: null })\n\t\t\t\t\tcancelWhenAborted(call, signal)\n\t\t\t\t\tconst [response] = await call\n\t\t\t\t\tif ((response.metadata?.samplingMetadatas?.length ?? 0) > 0) {\n\t\t\t\t\t\tsampled = true\n\t\t\t\t\t}\n\t\t\t\t\tconst code = response.metadata?.currencyCode?.toUpperCase()\n\t\t\t\t\tif (code && CURRENCY_PATTERN.test(code)) {\n\t\t\t\t\t\treportedCurrency = code\n\t\t\t\t\t}\n\t\t\t\t\treturn response\n\t\t\t\t})\n\n\t\t\t/**\n\t\t\t * One report shape run plainly and goal-filtered, unioned per row. `limit` is the site report's\n\t\t\t * alone, since a goal ranked outside its top N would otherwise drop out of the union.\n\t\t\t */\n\t\t\tconst runPair = async (\n\t\t\t\tshape: ReportShape,\n\t\t\t\tlimit?: number\n\t\t\t): Promise<{ rows: GoalKeyedRow[]; totals: MetricValues | undefined }> => {\n\t\t\t\tconst siteShape = limit ? { ...shape, limit } : shape\n\t\t\t\tconst pair = await readGoalPair({\n\t\t\t\t\tsite: siteNames.length ? () => runReport(siteNames, siteExprs, siteShape) : undefined,\n\t\t\t\t\tgoals: goalNames.length ? () => runReport(goalNames, goalExprs, shape) : undefined,\n\t\t\t\t})\n\t\t\t\tif (pair.failed) {\n\t\t\t\t\tgoalsFailed = true\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\trows: mergeGoalRows(\n\t\t\t\t\t\tkeyedRows(pair.site, siteMetrics, siteNames),\n\t\t\t\t\t\tkeyedRows(pair.goals, goalMetrics, goalNames)\n\t\t\t\t\t),\n\t\t\t\t\ttotals: mergeGoalTotals(\n\t\t\t\t\t\ttotalsOf(pair.site, siteMetrics, siteNames),\n\t\t\t\t\t\ttotalsOf(pair.goals, goalMetrics, goalNames)\n\t\t\t\t\t),\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (q.granularity === 'day' && !dims.length) {\n\t\t\t\tconst report = await runPair({\n\t\t\t\t\tdimensions: [{ name: 'date' }],\n\t\t\t\t\tmetricAggregations: ['TOTAL'],\n\t\t\t\t\torderBys: [{ dimension: { dimensionName: 'date' } }],\n\t\t\t\t})\n\t\t\t\treturn {\n\t\t\t\t\trows: datedRows(report.rows, ga4DayIso),\n\t\t\t\t\ttotals: report.totals ?? {},\n\t\t\t\t\tmeta: meta(),\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst report = await runPair(\n\t\t\t\tproviderDims.length ? { dimensions: providerDims.map((name) => ({ name })) } : {},\n\t\t\t\tq.limit\n\t\t\t)\n\n\t\t\tif (!dims.length) {\n\t\t\t\tconst totals = report.rows[0]?.metrics ?? {}\n\t\t\t\treturn { rows: [{ metrics: totals }], totals, meta: meta() }\n\t\t\t}\n\n\t\t\tconst rows: AnalyticsRow[] = report.rows.map((row) => {\n\t\t\t\tconst dimensions: Partial<Record<DimensionKey, string>> = {}\n\t\t\t\tfor (const d of dims) {\n\t\t\t\t\tconst name = DIMENSION_MAP[d]\n\t\t\t\t\tconst value =\n\t\t\t\t\t\t(name === undefined ? undefined : row.keys[providerDims.indexOf(name)]) ?? ''\n\t\t\t\t\t// A `goal` row reports the slug it was asked for; an `event` row reports GA4's own\n\t\t\t\t\t// event name, even though both read the same dimension.\n\t\t\t\t\tdimensions[d] = d === 'goal' ? (goalSlugs?.get(value) ?? value) : value\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tdimensions,\n\t\t\t\t\tmetrics: row.metrics,\n\t\t\t\t\t...(row.samples ? { samples: row.samples } : {}),\n\t\t\t\t}\n\t\t\t})\n\t\t\treturn { rows, totals: undefined, meta: meta() }\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA+EA,MAAM,4BAA4B;;;;;AAMlC,MAAM,qBAAqB,MAAwB,WAA0C;CAC5F,MAAM,SAAkB,QAAQ,IAAI,MAAM,QAAQ;CAClD,IAAI,CAAC,UAAU,OAAO,WAAW,YAChC;CAED,MAAM,gBAAsB;EAC3B,QAAQ,MAAM,QAAQ,MAAM,CAAC,CAAC;CAC/B;CACA,IAAI,OAAO,SAAS;EACnB,QAAQ;EACR;CACD;CACA,OAAO,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;CACxD,KAAU,WACH,OAAO,oBAAoB,SAAS,OAAO,SAC3C,OAAO,oBAAoB,SAAS,OAAO,CAClD;AACD;;;;;AAMA,SAAS,aAAa,eAAuC;CAC5D,MAAM,KAAK,UAAU,aAAa;CAClC,OAAO;EACN,OAAO,EAAE,QAAQ,CAAC,EAAE;EACpB,gBAAgB,EACf,SAAS,CACR,EACC,QAAQ,GAAG,gBAAgB,aAAa,EAAE,sHAAsH,GAAG,GACpK,GACA;GACC,KAAK,+CAA+C,mBAAmB,aAAa;GACpF,OAAO;EACR,CACD,EACD;EACA,QAAQ;GAAE,MAAM;GAAO;EAAc;CACtC;AACD;AAEA,MAAM,aAAiD;CACtD,WAAW;CACX,UAAU;CACV,QAAQ;CACR,UAAU;CACV,YAAY;CACZ,eAAe;CACf,QAAQ;CACR,aAAa;CACb,SAAS;AACV;AAEA,MAAM,kBAAkB;AACxB,MAAM,QAAQ;;;;;AAMd,MAAM,iBAAyE;CAC9E,GAAG;CACH,aAAa,CAAC,iBAAiB,KAAK;AACrC;AAEA,MAAM,gBAAuD;CAC5D,MAAM;CACN,UAAU;CACV,QAAQ;CACR,SAAS;CACT,QAAQ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rB,MAAM,OAAO,cAAc;MAC3B,MAAM,SACJ,SAAS,KAAA,IAAY,KAAA,IAAY,IAAI,KAAK,aAAa,QAAQ,IAAI,OAAO;MAG5E,WAAW,KAAK,MAAM,SAAU,WAAW,IAAI,KAAK,KAAK,QAAS;KACnE;KACA,OAAO;MACN;MACA,SAAS,IAAI;MACb,GAAI,IAAI,UAAU,EAAE,SAAS,IAAI,QAAQ,IAAI,CAAC;KAC/C;IACD,CACY;IAAG,QAAQ,KAAA;IAAW,MAAM,KAAK;GAAE;EAChD;CACD;AACD"}
|
|
1
|
+
{"version":3,"file":"ga4.js","names":[],"sources":["../../../src/adapters/ga4/ga4.ts"],"sourcesContent":["import type { Payload } from 'payload'\nimport { jsLiteral } from '../../capture/jsLiteral'\nimport {\n\tadapterWithoutConsent,\n\tcookielessCapture,\n\tWITHOUT_CONSENT_LEVELS,\n} from '../../capture/withoutConsent'\nimport type { CaptureSupport, SnippetMode } from '../../core/capture'\nimport {\n\ttype AdapterContext,\n\ttype AnalyticsAdapter,\n\ttype AnalyticsCapabilities,\n\ttype AnalyticsQuery,\n\ttype AnalyticsResult,\n\ttype AnalyticsRow,\n\tDIMENSION_KEYS,\n\ttype DimensionKey,\n\ttype FilterOperator,\n\ttype MetricKey,\n\ttype MetricReach,\n\ttype MetricValues,\n} from '../../core/contract'\nimport { vendorReading } from '../../core/metricValues'\nimport type { Ga4Client, Ga4ReportResponse, Ga4ReportRow, Ga4Sdk } from '../../core/sdks'\nimport { type AdapterLabelOption, adapterLabel } from '../../core/sourceLabel'\nimport { CURRENCY_PATTERN, currencyOption } from '../../goals/currency'\nimport { GA4_SDK_WARNING, isProductionBuild, loadGa4 } from '../../plugin/peers'\nimport type { WithoutConsentLevel } from '../../tracker/config'\nimport {\n\temptyGoalBreakdown,\n\ttype GoalKeyedRow,\n\tgoalHint,\n\thintSlugs,\n\tmergeGoalRows,\n\tmergeGoalTotals,\n\treadGoalPair,\n\tsplitGoalMetrics,\n} from '../goalRead'\nimport {\n\tcalendarDays,\n\tdeclaredFilters,\n\teveryOperatorOn,\n\tmappedKeys,\n\tproviderMetricKeys,\n\treadableMetrics,\n} from '../mapping'\nimport { readTime } from '../readTime'\nimport { datedRows, dayIso } from '../series'\nimport { upstream } from '../upstream'\nimport { ga4ExcludeGuard } from './disableKey'\nimport { ga4EventName } from './eventName'\nimport { MEASUREMENT_ID_PATTERN } from './measurementId'\n\nexport interface Ga4Config {\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 `'Google Analytics 4'`.\n\t */\n\tlabel?: AdapterLabelOption\n\t/** GA4 property id (numeric), e.g. '123456789'. */\n\tpropertyId: string\n\t/** Service-account credentials. */\n\tcredentials: { client_email: string; private_key: string }\n\t/** GCP project id; inferred from the credentials when omitted. */\n\tprojectId?: string\n\t/** Maximum days of historical data. Defaults to 425 (GA4's rolling-window limit). Pass null to disable clamping. */\n\tmaxLookbackDays?: number | null\n\t/**\n\t * Public measurement id (`G-XXXXXXX`). Setting it turns on capture: the tag is loaded\n\t * from googletagmanager.com and booted with gtag.\n\t */\n\tmeasurementId?: string\n\t/**\n\t * `{ BetaAnalyticsDataClient }` from `@google-analytics/data`. Unset, the plugin's `sdks.ga4`\n\t * serves, and without either it is loaded at runtime, which a standalone build does not ship.\n\t */\n\tsdk?: Ga4Sdk\n\t/**\n\t * The property's ISO 4217 currency, used only when an answer names none; GA4's own wins. Anything\n\t * but such a code throws when the adapter is built.\n\t */\n\tcurrency?: string\n\t/**\n\t * What this source's held slot does without consent, over `capture.withoutConsent`. Unset, GA4\n\t * sends nothing until consent, since its cookieless pings still reach Google. `'cookieless'` loads\n\t * the tag with every consent signal denied (Consent Mode \"advanced\") and grants on consent.\n\t */\n\twithoutConsent?: WithoutConsentLevel\n}\n\n/** How long one report may take when the adapter is called outside the engine, which sets its own. */\nconst DEFAULT_REPORT_TIMEOUT_MS = 60_000\n\n/**\n * Cancels a Data API call when its read gives up, where `cancel` survives: `@google-analytics/data`\n * 6.1 drops it, leaving the call's own gRPC `timeout` to bound it.\n */\nconst cancelWhenAborted = (call: Promise<unknown>, signal: AbortSignal | undefined): void => {\n\tconst cancel: unknown = Reflect.get(call, 'cancel')\n\tif (!signal || typeof cancel !== 'function') {\n\t\treturn\n\t}\n\tconst onAbort = (): void => {\n\t\tReflect.apply(cancel, call, [])\n\t}\n\tif (signal.aborted) {\n\t\tonAbort()\n\t\treturn\n\t}\n\tsignal.addEventListener('abort', onAbort, { once: true })\n\tvoid call.then(\n\t\t() => signal.removeEventListener('abort', onAbort),\n\t\t() => signal.removeEventListener('abort', onAbort)\n\t)\n}\n\n/**\n * Consent mode's defaults for a slot counting without consent (\"advanced\" mode), set before the tag\n * loads: analytics storage only once in full, and advertising signals never, unless the host grants them.\n */\nconst consentDefault = (mode: SnippetMode): string =>\n\t`gtag(\"consent\",\"default\",{analytics_storage:${jsLiteral(mode === 'full' ? 'granted' : 'denied')},ad_storage:\"denied\",ad_user_data:\"denied\",ad_personalization:\"denied\"});`\n\n/**\n * Google's install snippet, inline first as consent mode expects, led by the exclusion guard. The\n * tag loads from Google's CDN, so `routes` stays empty and the slot's proxy mount answers 404. A\n * snippet started cookieless reads no storage, so no guard: the tracker reads the flag once in full.\n */\nfunction buildCapture(measurementId: string): CaptureSupport {\n\tconst id = jsLiteral(measurementId)\n\treturn {\n\t\tproxy: { routes: [] },\n\t\tsnippet: ({ mode = 'full', withoutConsent = false }) => ({\n\t\t\tscripts: [\n\t\t\t\t{\n\t\t\t\t\tinline: `${mode === 'cookieless' ? '' : ga4ExcludeGuard(measurementId)}window.dataLayer=window.dataLayer||[];function gtag(){dataLayer.push(arguments)}${withoutConsent ? consentDefault(mode) : ''}gtag(\"js\",new Date());gtag(\"config\",${id})`,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tsrc: `https://www.googletagmanager.com/gtag/js?id=${encodeURIComponent(measurementId)}`,\n\t\t\t\t\tasync: true,\n\t\t\t\t},\n\t\t\t],\n\t\t}),\n\t\tclient: { kind: 'ga4', measurementId },\n\t}\n}\n\nconst METRIC_MAP: Partial<Record<MetricKey, string>> = {\n\tpageviews: 'screenPageViews',\n\tvisitors: 'totalUsers',\n\tvisits: 'sessions',\n\tsessions: 'sessions',\n\tbounceRate: 'bounceRate',\n\tvisitDuration: 'averageSessionDuration',\n\tevents: 'eventCount',\n\tconversions: 'keyEvents',\n\trevenue: 'totalRevenue',\n}\n\nconst ENGAGED_SECONDS = 'userEngagementDuration'\nconst VIEWS = 'screenPageViews'\n\n/**\n * The GA4 metrics each contract metric is read from. Time on page is engaged seconds over views;\n * both are sums, so the ratio holds per row and for the totals alike.\n */\nconst METRIC_SOURCES: Partial<Record<MetricKey, string | readonly string[]>> = {\n\t...METRIC_MAP,\n\tavgDuration: [ENGAGED_SECONDS, VIEWS],\n}\n\nconst DIMENSION_MAP: Partial<Record<DimensionKey, string>> = {\n\tpage: 'pagePath',\n\treferrer: 'pageReferrer',\n\tsource: 'sessionSource',\n\tchannel: 'sessionDefaultChannelGroup',\n\tmedium: 'sessionMedium',\n\tcampaign: 'sessionCampaignName',\n\tutmSource: 'sessionSource',\n\tutmMedium: 'sessionMedium',\n\tutmCampaign: 'sessionCampaignName',\n\tdevice: 'deviceCategory',\n\tbrowser: 'browser',\n\tos: 'operatingSystem',\n\tcountry: 'countryId',\n\tregion: 'region',\n\tcity: 'city',\n\tlanguage: 'language',\n\tevent: 'eventName',\n\tgoal: 'eventName',\n}\n\n/**\n * Metrics GA4 answers only for a goal-restricted read. `keyEvents` counts only events the property\n * marks as key events, so a goal here that GA4 does not mark reports 0.\n */\nconst GOAL_METRICS: ReadonlySet<MetricKey> = new Set(['conversions'])\n\n/**\n * The hint's slugs by the GA4 event name each normalizes to, for the request and mapping rows back.\n * Two slugs normalizing alike are one GA4 event: the first slug owns its rows.\n */\nconst goalSlugsByEventName = (slugs: string[]): Map<string, string> => {\n\tconst byName = new Map<string, string>()\n\tfor (const slug of slugs) {\n\t\tconst name = ga4EventName(slug)\n\t\tif (!byName.has(name)) {\n\t\t\tbyName.set(name, slug)\n\t\t}\n\t}\n\treturn byName\n}\n\ntype StringMatchType = 'EXACT' | 'CONTAINS' | 'FULL_REGEXP'\n\n/**\n * FULL_REGEXP is a full match, so a pattern has to cover the whole value (`/docs/.*`, not\n * `^/docs`). PARTIAL_REGEXP exists but is not the contract's `matches`.\n */\nconst MATCH_TYPE_MAP: Record<FilterOperator, StringMatchType> = {\n\teq: 'EXACT',\n\tcontains: 'CONTAINS',\n\tmatches: 'FULL_REGEXP',\n}\n\n// The Data API defaults caseSensitive to false, so it is explicit: `contains` stays\n// insensitive like native and Umami's ilike, while `eq` and `matches` compare literally.\nconst CASE_SENSITIVE: Record<StringMatchType, boolean> = {\n\tEXACT: true,\n\tCONTAINS: false,\n\tFULL_REGEXP: true,\n}\n\n/**\n * A filter expression as the Data API reads one (`FilterExpression` in its REST reference), written\n * here so the adapter needs no type of the SDK.\n */\ninterface FilterExpression {\n\tfilter?: {\n\t\tfieldName: string\n\t\tstringFilter?: { matchType: StringMatchType; value: string; caseSensitive: boolean }\n\t\tinListFilter?: { values: string[]; caseSensitive: boolean }\n\t}\n\tandGroup?: { expressions: FilterExpression[] }\n}\n\n/** The parts of a `RunReportRequest` a read adds to the property, the window and the metrics. */\ninterface ReportShape {\n\tdimensions?: Array<{ name: string }>\n\tmetricAggregations?: Array<'TOTAL'>\n\torderBys?: Array<{ dimension: { dimensionName: string } }>\n\tlimit?: number\n}\n\nconst stringFilter = (\n\tfieldName: string,\n\tmatchType: StringMatchType,\n\tvalue: string\n): FilterExpression => ({\n\tfilter: {\n\t\tfieldName,\n\t\tstringFilter: { matchType, value, caseSensitive: CASE_SENSITIVE[matchType] },\n\t},\n})\n\n/** `exprs` as one dimension filter: none, the only one, or all of them and-ed. */\nconst allOf = (exprs: FilterExpression[]): FilterExpression | undefined =>\n\texprs.length > 1 ? { andGroup: { expressions: exprs } } : exprs[0]\n\nconst ga4Metrics: ReadonlySet<MetricKey> = new Set<MetricKey>([\n\t'pageviews',\n\t'visitors',\n\t'visits',\n\t'sessions',\n\t'bounceRate',\n\t'avgDuration',\n\t'visitDuration',\n\t'events',\n\t'conversions',\n\t'revenue',\n])\nconst ga4Dimensions = mappedKeys(DIMENSION_KEYS, DIMENSION_MAP)\n/**\n * Views are page_view and screen_view events only, so a time on page per event name divides the\n * engagement of one event by the views of another: it is read under every other breakdown.\n */\nconst ga4Reach: Partial<Record<MetricKey, MetricReach>> = {\n\tavgDuration: {\n\t\tdimensions: [...ga4Dimensions].filter(\n\t\t\t(dimension) => dimension !== 'event' && dimension !== 'goal'\n\t\t),\n\t},\n}\nconst ga4Filters = everyOperatorOn(ga4Dimensions)\n\n// GA4 returns bounceRate as a 0..1 ratio and averageSessionDuration in seconds; the\n// contract uses a 0..100 percentage and milliseconds.\nconst toContractValue = (metric: MetricKey, raw: number): number => {\n\tif (metric === 'visitDuration') {\n\t\treturn Math.round(raw * 1000)\n\t}\n\tif (metric === 'bounceRate') {\n\t\treturn Math.round(raw * 100)\n\t}\n\treturn raw\n}\n\ninterface Ga4Reading {\n\tmetrics: MetricValues\n\t/** The views each time on page was taken over, which folds days into weeks exactly. */\n\tsamples?: Partial<Record<MetricKey, number>>\n}\n\n/** One report row's contract metrics, each read back by GA4 name from the report's `names`. */\nconst readRow = (metrics: MetricKey[], names: string[], row: Ga4ReportRow): Ga4Reading => {\n\tconst raw = (name: string): unknown => row.metricValues?.[names.indexOf(name)]?.value\n\tconst out: MetricValues = {}\n\tlet samples: Ga4Reading['samples']\n\tfor (const metric of metrics) {\n\t\tif (metric === 'avgDuration') {\n\t\t\tconst views = vendorReading('pageviews', raw(VIEWS)) ?? 0\n\t\t\tconst engaged = vendorReading('avgDuration', raw(ENGAGED_SECONDS))\n\t\t\tout.avgDuration = views > 0 && engaged !== null ? Math.round((engaged / views) * 1000) : null\n\t\t\tsamples = { avgDuration: views }\n\t\t\tcontinue\n\t\t}\n\t\tconst name = METRIC_MAP[metric]\n\t\tconst value = name === undefined ? null : vendorReading(metric, raw(name))\n\t\tout[metric] = value === null ? null : toContractValue(metric, value)\n\t}\n\treturn samples ? { metrics: out, samples } : { metrics: out }\n}\n\n/** A report's rows keyed by their dimension values; undefined when the report was never run. */\nconst keyedRows = (\n\tresponse: Ga4ReportResponse | undefined,\n\tmetrics: MetricKey[],\n\tnames: string[]\n): GoalKeyedRow[] | undefined =>\n\tresponse?.rows?.map((row) => ({\n\t\tkeys: (row.dimensionValues ?? []).map((value) => value.value ?? ''),\n\t\t...readRow(metrics, names, row),\n\t})) ?? (response ? [] : undefined)\n\nconst totalsOf = (\n\tresponse: Ga4ReportResponse | undefined,\n\tmetrics: MetricKey[],\n\tnames: string[]\n): MetricValues | undefined => {\n\tconst row = response?.totals?.[0]\n\treturn row ? readRow(metrics, names, row).metrics : undefined\n}\n\n/** GA4's `date` dimension value (`YYYYMMDD`) as a UTC-day ISO string. */\nconst ga4DayIso = (ymd: string): string | null =>\n\tdayIso(`${ymd.slice(0, 4)}-${ymd.slice(4, 6)}-${ymd.slice(6, 8)}`)\n\nexport function ga4(config: Ga4Config): AnalyticsAdapter {\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 425\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\trealtime: false,\n\t\tminGranularity: 'day',\n\t\tmaxLookbackDays,\n\t\tmetrics: ga4Metrics,\n\t\tdimensions: ga4Dimensions,\n\t\tmetricReach: ga4Reach,\n\t\tfilters: ga4Filters,\n\t\tsemantics: { visitors: 'distinct', sessions: 'provider' },\n\t\trateLimit: { maxConcurrent: 10, readsCountAsUsage: true },\n\t\trecommendedTtl: { realtime: 300, aggregate: 21600 },\n\t\tupstreamAware: true,\n\t}\n\tconst configCurrency = currencyOption('ga4({ currency })', config.currency)\n\tconst withoutConsent = adapterWithoutConsent(\n\t\tconfig.withoutConsent,\n\t\t'ga4({ withoutConsent })',\n\t\tWITHOUT_CONSENT_LEVELS\n\t)\n\n\t/** One client per Payload instance, so closing one instance's leaves the others' open. */\n\tconst clients = new WeakMap<object, Promise<Ga4Client>>()\n\t/** The instances this adapter was closed for, which get no client again until attached anew. */\n\tconst closed = new WeakSet<object>()\n\t/** Whom a read with no instance in its context shares a client with. */\n\tconst unattached = {}\n\t/** The plugin's `sdks.ga4`, handed over when the plugin registers this adapter. */\n\tlet pluginSdk: Ga4Sdk | undefined\n\tlet warned = false\n\tconst sdk = (): Ga4Sdk | undefined => config.sdk ?? pluginSdk\n\n\tconst getClient = (payload: Payload | undefined): Promise<Ga4Client> => {\n\t\tconst owner = payload ?? unattached\n\t\tconst held = clients.get(owner)\n\t\tif (held) {\n\t\t\treturn held\n\t\t}\n\t\t// A read that reaches a closed adapter late (a retired runtime's refresh) would otherwise\n\t\t// open a client nothing ever closes.\n\t\tif (closed.has(owner)) {\n\t\t\treturn Promise.reject(new Error('analytics: this GA4 source was closed'))\n\t\t}\n\t\tconst created = (async () => {\n\t\t\tconst mod = sdk() ?? (await loadGa4())\n\t\t\treturn new mod.BetaAnalyticsDataClient({\n\t\t\t\tcredentials: config.credentials,\n\t\t\t\t...(config.projectId ? { projectId: config.projectId } : {}),\n\t\t\t})\n\t\t})()\n\t\tclients.set(owner, created)\n\t\treturn created\n\t}\n\n\tconst measurementId = config.measurementId\n\treturn {\n\t\tid: 'ga4',\n\t\t...adapterLabel(config.label, 'Google Analytics 4', 'ga4({ label })'),\n\t\tcapabilities,\n\t\t// An id that is not a bare token is dropped rather than escaped: it lands in an inline\n\t\t// script and in the tag URL, and no legitimate measurement id needs anything else.\n\t\t...(measurementId && MEASUREMENT_ID_PATTERN.test(measurementId)\n\t\t\t? {\n\t\t\t\t\tcapture: {\n\t\t\t\t\t\t...buildCapture(measurementId),\n\t\t\t\t\t\t...cookielessCapture({ kind: 'switched', default: 'off' }, withoutConsent),\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\n\t\tisConfigured: () =>\n\t\t\tBoolean(\n\t\t\t\tconfig.propertyId && config.credentials?.client_email && config.credentials?.private_key\n\t\t\t),\n\t\tregister(_config, context) {\n\t\t\tpluginSdk = context?.sdks?.ga4\n\t\t},\n\t\t// At boot, before the first read fails in front of an editor.\n\t\tattach(payload: Payload) {\n\t\t\tclosed.delete(payload)\n\t\t\tif (!warned && sdk() === undefined && isProductionBuild()) {\n\t\t\t\twarned = true\n\t\t\t\tpayload.logger?.warn(GA4_SDK_WARNING)\n\t\t\t}\n\t\t},\n\t\tasync close(payload: Payload) {\n\t\t\tclosed.add(payload)\n\t\t\tconst held = clients.get(payload)\n\t\t\tclients.delete(payload)\n\t\t\tconst client = await held?.catch(() => undefined)\n\t\t\tawait client?.close?.()\n\t\t},\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = readTime(ctx)\n\t\t\tconst dims = (q.dimensions ?? []).filter((d) => DIMENSION_MAP[d])\n\t\t\tconst goalBreakdown = dims.includes('goal')\n\t\t\tconst hint = goalHint(q)\n\t\t\tconst empty = goalBreakdown ? emptyGoalBreakdown({ provider: 'ga4', fetchedAt, hint }) : null\n\t\t\tif (empty) {\n\t\t\t\treturn empty\n\t\t\t}\n\t\t\tconst { siteMetrics, goalMetrics, unresolved } = splitGoalMetrics({\n\t\t\t\twanted: readableMetrics(capabilities, q, dims),\n\t\t\t\tgoalOnly: GOAL_METRICS,\n\t\t\t\tgoalBreakdown,\n\t\t\t\thint,\n\t\t\t})\n\t\t\tconst siteNames = providerMetricKeys(siteMetrics, METRIC_SOURCES)\n\t\t\tconst goalNames = providerMetricKeys(goalMetrics, METRIC_SOURCES)\n\t\t\tconst providerDims = [...new Set(dims.flatMap((d) => DIMENSION_MAP[d] ?? []))]\n\t\t\t// Set when GA4 rejects a goal report the site report survived, so the rows keep their\n\t\t\t// site metrics and lose only their conversions.\n\t\t\tlet goalsFailed = false\n\t\t\t// What the answers said about themselves: a sampled report anywhere makes the read an estimate.\n\t\t\tlet sampled = false\n\t\t\tlet reportedCurrency: string | undefined\n\t\t\tconst meta = (): AnalyticsResult['meta'] => {\n\t\t\t\tconst currency = reportedCurrency ?? configCurrency\n\t\t\t\treturn {\n\t\t\t\t\tprovider: 'ga4',\n\t\t\t\t\tfetchedAt,\n\t\t\t\t\t...(currency ? { currency } : {}),\n\t\t\t\t\t...(sampled ? { sampled: true } : {}),\n\t\t\t\t\t...(unresolved || goalsFailed ? { goalsUnresolved: true as const } : {}),\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst filterExprs: FilterExpression[] = []\n\t\t\tif (q.path) {\n\t\t\t\tfilterExprs.push(stringFilter('pagePath', 'EXACT', q.path))\n\t\t\t}\n\t\t\tif (q.hostname) {\n\t\t\t\tfilterExprs.push(stringFilter('hostName', 'EXACT', q.hostname))\n\t\t\t}\n\t\t\tfor (const { filter, field } of declaredFilters(capabilities, q.filters, DIMENSION_MAP)) {\n\t\t\t\tfilterExprs.push(stringFilter(field, MATCH_TYPE_MAP[filter.operator], filter.value))\n\t\t\t}\n\t\t\tconst slugs = hintSlugs(hint)\n\t\t\tconst goalSlugs = slugs ? goalSlugsByEventName(slugs) : null\n\t\t\tconst goalExprs: FilterExpression[] = goalSlugs\n\t\t\t\t? [\n\t\t\t\t\t\t...filterExprs,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfilter: {\n\t\t\t\t\t\t\t\tfieldName: 'eventName',\n\t\t\t\t\t\t\t\tinListFilter: { values: [...goalSlugs.keys()], caseSensitive: true },\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t]\n\t\t\t\t: filterExprs\n\t\t\t// A goal breakdown restricts its own rows, so its one report carries the hint too.\n\t\t\tconst siteExprs = goalBreakdown ? goalExprs : filterExprs\n\n\t\t\tconst [startDate, endDate] = calendarDays(q)\n\t\t\tconst client = await getClient(ctx.payload)\n\n\t\t\t// Each report is one upstream request with its own token, so a paired read spends two. It\n\t\t\t// runs with no retry of the SDK's own (the lane retries) and a deadline of what the read has left.\n\t\t\tconst runReport = (\n\t\t\t\tnames: string[],\n\t\t\t\texprs: FilterExpression[],\n\t\t\t\tshape: ReportShape\n\t\t\t): Promise<Ga4ReportResponse> =>\n\t\t\t\tupstream(ctx, async (signal) => {\n\t\t\t\t\tconst dimensionFilter = allOf(exprs)\n\t\t\t\t\tconst request = {\n\t\t\t\t\t\tproperty: `properties/${config.propertyId}`,\n\t\t\t\t\t\tdateRanges: [{ startDate, endDate }],\n\t\t\t\t\t\tmetrics: names.map((name) => ({ name })),\n\t\t\t\t\t\t...(dimensionFilter ? { dimensionFilter } : {}),\n\t\t\t\t\t\t...shape,\n\t\t\t\t\t}\n\t\t\t\t\tconst timeout = Math.max(1, Math.floor(ctx.remainingMs?.() ?? DEFAULT_REPORT_TIMEOUT_MS))\n\t\t\t\t\tconst call = client.runReport(request, { timeout, retry: null })\n\t\t\t\t\tcancelWhenAborted(call, signal)\n\t\t\t\t\tconst [response] = await call\n\t\t\t\t\tif ((response.metadata?.samplingMetadatas?.length ?? 0) > 0) {\n\t\t\t\t\t\tsampled = true\n\t\t\t\t\t}\n\t\t\t\t\tconst code = response.metadata?.currencyCode?.toUpperCase()\n\t\t\t\t\tif (code && CURRENCY_PATTERN.test(code)) {\n\t\t\t\t\t\treportedCurrency = code\n\t\t\t\t\t}\n\t\t\t\t\treturn response\n\t\t\t\t})\n\n\t\t\t/**\n\t\t\t * One report shape run plainly and goal-filtered, unioned per row. `limit` is the site report's\n\t\t\t * alone, since a goal ranked outside its top N would otherwise drop out of the union.\n\t\t\t */\n\t\t\tconst runPair = async (\n\t\t\t\tshape: ReportShape,\n\t\t\t\tlimit?: number\n\t\t\t): Promise<{ rows: GoalKeyedRow[]; totals: MetricValues | undefined }> => {\n\t\t\t\tconst siteShape = limit ? { ...shape, limit } : shape\n\t\t\t\tconst pair = await readGoalPair({\n\t\t\t\t\tsite: siteNames.length ? () => runReport(siteNames, siteExprs, siteShape) : undefined,\n\t\t\t\t\tgoals: goalNames.length ? () => runReport(goalNames, goalExprs, shape) : undefined,\n\t\t\t\t})\n\t\t\t\tif (pair.failed) {\n\t\t\t\t\tgoalsFailed = true\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\trows: mergeGoalRows(\n\t\t\t\t\t\tkeyedRows(pair.site, siteMetrics, siteNames),\n\t\t\t\t\t\tkeyedRows(pair.goals, goalMetrics, goalNames)\n\t\t\t\t\t),\n\t\t\t\t\ttotals: mergeGoalTotals(\n\t\t\t\t\t\ttotalsOf(pair.site, siteMetrics, siteNames),\n\t\t\t\t\t\ttotalsOf(pair.goals, goalMetrics, goalNames)\n\t\t\t\t\t),\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (q.granularity === 'day' && !dims.length) {\n\t\t\t\tconst report = await runPair({\n\t\t\t\t\tdimensions: [{ name: 'date' }],\n\t\t\t\t\tmetricAggregations: ['TOTAL'],\n\t\t\t\t\torderBys: [{ dimension: { dimensionName: 'date' } }],\n\t\t\t\t})\n\t\t\t\treturn {\n\t\t\t\t\trows: datedRows(report.rows, ga4DayIso),\n\t\t\t\t\ttotals: report.totals ?? {},\n\t\t\t\t\tmeta: meta(),\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst report = await runPair(\n\t\t\t\tproviderDims.length ? { dimensions: providerDims.map((name) => ({ name })) } : {},\n\t\t\t\tq.limit\n\t\t\t)\n\n\t\t\tif (!dims.length) {\n\t\t\t\tconst totals = report.rows[0]?.metrics ?? {}\n\t\t\t\treturn { rows: [{ metrics: totals }], totals, meta: meta() }\n\t\t\t}\n\n\t\t\tconst rows: AnalyticsRow[] = report.rows.map((row) => {\n\t\t\t\tconst dimensions: Partial<Record<DimensionKey, string>> = {}\n\t\t\t\tfor (const d of dims) {\n\t\t\t\t\tconst name = DIMENSION_MAP[d]\n\t\t\t\t\tconst value =\n\t\t\t\t\t\t(name === undefined ? undefined : row.keys[providerDims.indexOf(name)]) ?? ''\n\t\t\t\t\t// A `goal` row reports the slug it was asked for; an `event` row reports GA4's own\n\t\t\t\t\t// event name, even though both read the same dimension.\n\t\t\t\t\tdimensions[d] = d === 'goal' ? (goalSlugs?.get(value) ?? value) : value\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tdimensions,\n\t\t\t\t\tmetrics: row.metrics,\n\t\t\t\t\t...(row.samples ? { samples: row.samples } : {}),\n\t\t\t\t}\n\t\t\t})\n\t\t\treturn { rows, totals: undefined, meta: meta() }\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA2FA,MAAM,4BAA4B;;;;;AAMlC,MAAM,qBAAqB,MAAwB,WAA0C;CAC5F,MAAM,SAAkB,QAAQ,IAAI,MAAM,QAAQ;CAClD,IAAI,CAAC,UAAU,OAAO,WAAW,YAChC;CAED,MAAM,gBAAsB;EAC3B,QAAQ,MAAM,QAAQ,MAAM,CAAC,CAAC;CAC/B;CACA,IAAI,OAAO,SAAS;EACnB,QAAQ;EACR;CACD;CACA,OAAO,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;CACxD,KAAU,WACH,OAAO,oBAAoB,SAAS,OAAO,SAC3C,OAAO,oBAAoB,SAAS,OAAO,CAClD;AACD;;;;;AAMA,MAAM,kBAAkB,SACvB,+CAA+C,UAAU,SAAS,SAAS,YAAY,QAAQ,EAAE;;;;;;AAOlG,SAAS,aAAa,eAAuC;CAC5D,MAAM,KAAK,UAAU,aAAa;CAClC,OAAO;EACN,OAAO,EAAE,QAAQ,CAAC,EAAE;EACpB,UAAU,EAAE,OAAO,QAAQ,iBAAiB,aAAa,EACxD,SAAS,CACR,EACC,QAAQ,GAAG,SAAS,eAAe,KAAK,gBAAgB,aAAa,EAAE,kFAAkF,iBAAiB,eAAe,IAAI,IAAI,GAAG,sCAAsC,GAAG,GAC9O,GACA;GACC,KAAK,+CAA+C,mBAAmB,aAAa;GACpF,OAAO;EACR,CACD,EACD;EACA,QAAQ;GAAE,MAAM;GAAO;EAAc;CACtC;AACD;AAEA,MAAM,aAAiD;CACtD,WA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IACZ;GACD;GAEA,MAAM,SAAS,MAAM,QACpB,aAAa,SAAS,EAAE,YAAY,aAAa,KAAK,UAAU,EAAE,KAAK,EAAE,EAAE,IAAI,CAAC,GAChF,EAAE,KACH;GAEA,IAAI,CAAC,KAAK,QAAQ;IACjB,MAAM,SAAS,OAAO,KAAK,IAAI,WAAW,CAAC;IAC3C,OAAO;KAAE,MAAM,CAAC,EAAE,SAAS,OAAO,CAAC;KAAG;KAAQ,MAAM,KAAK;IAAE;GAC5D;GAkBA,OAAO;IAAE,MAhBoB,OAAO,KAAK,KAAK,QAAQ;KACrD,MAAM,aAAoD,CAAC;KAC3D,KAAK,MAAM,KAAK,MAAM;MACrB,MAAM,OAAO,cAAc;MAC3B,MAAM,SACJ,SAAS,KAAA,IAAY,KAAA,IAAY,IAAI,KAAK,aAAa,QAAQ,IAAI,OAAO;MAG5E,WAAW,KAAK,MAAM,SAAU,WAAW,IAAI,KAAK,KAAK,QAAS;KACnE;KACA,OAAO;MACN;MACA,SAAS,IAAI;MACb,GAAI,IAAI,UAAU,EAAE,SAAS,IAAI,QAAQ,IAAI,CAAC;KAC/C;IACD,CACY;IAAG,QAAQ,KAAA;IAAW,MAAM,KAAK;GAAE;EAChD;CACD;AACD"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { WithoutConsentLevel } from "../../tracker/config.js";
|
|
1
2
|
import { FetchLike } from "../../core/fetch.js";
|
|
2
3
|
import { AnalyticsAdapter } from "../../core/contract.js";
|
|
3
4
|
import { AdapterLabelOption } from "../../core/sourceLabel.js";
|
|
@@ -35,6 +36,11 @@ interface PlausibleConfig {
|
|
|
35
36
|
revenueCurrency?: string;
|
|
36
37
|
/** The fetch reads and the capture proxy reach Plausible with. Unset, the global fetch. */
|
|
37
38
|
fetch?: FetchLike;
|
|
39
|
+
/**
|
|
40
|
+
* What this source's held slot does without consent, over `capture.withoutConsent`. Plausible
|
|
41
|
+
* stores nothing on the device, so `'cookieless'` loads the script as it is; `'off'` holds it.
|
|
42
|
+
*/
|
|
43
|
+
withoutConsent?: WithoutConsentLevel;
|
|
38
44
|
}
|
|
39
45
|
/**
|
|
40
46
|
* The Plausible adapter. A goal's slug must equal its display name in the site's goal list for its
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { DIMENSION_KEYS } from "../../core/contract.js";
|
|
2
2
|
import { adapterLabel } from "../../core/sourceLabel.js";
|
|
3
3
|
import { jsLiteral } from "../../capture/jsLiteral.js";
|
|
4
|
+
import { WITHOUT_CONSENT_LEVELS, adapterWithoutConsent, cookielessCapture } from "../../capture/withoutConsent.js";
|
|
4
5
|
import { isScriptId } from "./scriptId.js";
|
|
5
6
|
import { currencyOption } from "../../goals/currency.js";
|
|
6
7
|
import { vendorReading } from "../../core/metricValues.js";
|
|
@@ -17,7 +18,7 @@ const PLAUSIBLE_CLOUD = "https://plausible.io";
|
|
|
17
18
|
* guarded with `||` because the loader may win the race, and overwriting it would lose the endpoint.
|
|
18
19
|
*/
|
|
19
20
|
const PLAUSIBLE_STUB = "window.plausible=window.plausible||function(){(window.plausible.q=window.plausible.q||[]).push(arguments)},window.plausible.init=window.plausible.init||function(e){window.plausible.o=e||{}};";
|
|
20
|
-
function buildCapture(config, scriptId) {
|
|
21
|
+
function buildCapture(config, scriptId, withoutConsent) {
|
|
21
22
|
const base = withoutTrailingSlash(config.host ?? PLAUSIBLE_CLOUD);
|
|
22
23
|
const scripts = (path) => {
|
|
23
24
|
if (config.domain) return [{
|
|
@@ -48,7 +49,8 @@ function buildCapture(config, scriptId) {
|
|
|
48
49
|
...config.fetch ? { fetch: config.fetch } : {}
|
|
49
50
|
},
|
|
50
51
|
snippet: ({ path }) => ({ scripts: scripts(path) }),
|
|
51
|
-
client: { kind: "plausible" }
|
|
52
|
+
client: { kind: "plausible" },
|
|
53
|
+
...cookielessCapture({ kind: "inherent" }, withoutConsent)
|
|
52
54
|
};
|
|
53
55
|
}
|
|
54
56
|
const METRIC_MAP = {
|
|
@@ -148,6 +150,7 @@ function plausible(config) {
|
|
|
148
150
|
const revenueCurrency = currencyOption("plausible({ revenueCurrency })", config.revenueCurrency);
|
|
149
151
|
const revenueGoals = revenueCurrency !== void 0;
|
|
150
152
|
const scriptId = isScriptId(config.scriptId) ? config.scriptId : void 0;
|
|
153
|
+
const withoutConsent = adapterWithoutConsent(config.withoutConsent, "plausible({ withoutConsent })", WITHOUT_CONSENT_LEVELS);
|
|
151
154
|
const capabilities = {
|
|
152
155
|
realtime: false,
|
|
153
156
|
minGranularity: "day",
|
|
@@ -171,7 +174,7 @@ function plausible(config) {
|
|
|
171
174
|
id: "plausible",
|
|
172
175
|
...adapterLabel(config.label, "Plausible", "plausible({ label })"),
|
|
173
176
|
capabilities,
|
|
174
|
-
...config.domain || scriptId ? { capture: buildCapture(config, scriptId) } : {},
|
|
177
|
+
...config.domain || scriptId ? { capture: buildCapture(config, scriptId, withoutConsent) } : {},
|
|
175
178
|
isConfigured: () => Boolean(config.siteId && config.apiKey),
|
|
176
179
|
async query(q, ctx) {
|
|
177
180
|
const fetchedAt = readTime(ctx);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plausible.js","names":[],"sources":["../../../src/adapters/plausible/plausible.ts"],"sourcesContent":["import { jsLiteral } from '../../capture/jsLiteral'\nimport type { CaptureSupport } from '../../core/capture'\nimport {\n\ttype AdapterContext,\n\ttype AnalyticsAdapter,\n\ttype AnalyticsCapabilities,\n\ttype AnalyticsQuery,\n\ttype AnalyticsResult,\n\ttype AnalyticsRow,\n\tDIMENSION_KEYS,\n\ttype DimensionKey,\n\ttype FilterOperator,\n\ttype MetricKey,\n\ttype MetricReach,\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 { currencyOption } from '../../goals/currency'\nimport {\n\temptyGoalBreakdown,\n\ttype GoalKeyedRow,\n\tgoalHint,\n\thintSlugs,\n\tmergeGoalRows,\n\treadGoalPair,\n\tsplitGoalMetrics,\n} from '../goalRead'\nimport { withoutTrailingSlash } from '../http/baseUrl'\nimport {\n\tcalendarDays,\n\tdeclaredFilters,\n\teveryOperatorOn,\n\tmappedKeys,\n\tproviderMetricKeys,\n\treadableMetrics,\n} from '../mapping'\nimport { readTime } from '../readTime'\nimport { datedRows, dayIso } from '../series'\nimport { upstreamJson } from '../upstream'\nimport { isScriptId } from './scriptId'\n\nexport interface PlausibleConfig {\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 `'Plausible'`.\n\t */\n\tlabel?: AdapterLabelOption\n\tsiteId: string\n\tapiKey: string\n\t/**\n\t * Address of a self-hosted Community Edition, with the base path when it runs under one.\n\t * Defaults to Plausible 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/**\n\t * Site domain for the legacy script tag (`data-domain`). Takes priority over `scriptId`.\n\t * The adapter declares `capture` only when one of the two is set.\n\t */\n\tdomain?: string\n\t/**\n\t * Per-site tracker id (`pa-<id>.js`) for the newer per-site script model: letters, digits, `_`\n\t * and `-`. Any other value is dropped, and capture then needs `domain`.\n\t */\n\tscriptId?: string\n\t/**\n\t * The ISO 4217 currency of the site's revenue goals. Declaring it turns on `revenue`: Plausible\n\t * errors the whole request for `total_revenue` on a site without a revenue goal.\n\t */\n\trevenueCurrency?: string\n\t/** The fetch reads and the capture proxy reach Plausible with. Unset, the global fetch. */\n\tfetch?: FetchLike\n}\n\nconst PLAUSIBLE_CLOUD = 'https://plausible.io'\n\n/**\n * Plausible's official per-site stub, safe beside the async loader in either order. `init` is\n * guarded with `||` because the loader may win the race, and overwriting it would lose the endpoint.\n */\nconst PLAUSIBLE_STUB =\n\t'window.plausible=window.plausible||function(){(window.plausible.q=window.plausible.q||[]).push(arguments)},window.plausible.init=window.plausible.init||function(e){window.plausible.o=e||{}};'\n\nfunction buildCapture(config: PlausibleConfig, scriptId: string | undefined): CaptureSupport {\n\tconst base = withoutTrailingSlash(config.host ?? PLAUSIBLE_CLOUD)\n\tconst scripts = (path: string) => {\n\t\tif (config.domain) {\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\tsrc: `${path}/js/script.js`,\n\t\t\t\t\tdefer: true,\n\t\t\t\t\tattrs: { 'data-domain': config.domain, 'data-api': `${path}/api/event` },\n\t\t\t\t},\n\t\t\t]\n\t\t}\n\t\tif (scriptId) {\n\t\t\treturn [\n\t\t\t\t{ src: `${path}/js/pa-${encodeURIComponent(scriptId)}.js`, async: true },\n\t\t\t\t{\n\t\t\t\t\tinline: `${PLAUSIBLE_STUB}plausible.init({endpoint:${jsLiteral(`${path}/api/event`)}})`,\n\t\t\t\t},\n\t\t\t]\n\t\t}\n\t\treturn []\n\t}\n\treturn {\n\t\tproxy: {\n\t\t\troutes: [\n\t\t\t\t{ source: '/js/:script*', upstream: `${base}/js/:script*`, kind: 'script' },\n\t\t\t\t{ source: '/api/event', upstream: `${base}/api/event`, kind: 'data' },\n\t\t\t],\n\t\t\t...(config.fetch ? { fetch: config.fetch } : {}),\n\t\t},\n\t\tsnippet: ({ path }) => ({ scripts: scripts(path) }),\n\t\tclient: { kind: 'plausible' },\n\t}\n}\n\nconst METRIC_MAP: Partial<Record<MetricKey, string>> = {\n\tpageviews: 'pageviews',\n\tvisitors: 'visitors',\n\tvisits: 'visits',\n\tsessions: 'visits',\n\tbounceRate: 'bounce_rate',\n\tvisitDuration: 'visit_duration',\n\tevents: 'events',\n\tscrollDepth: 'scroll_depth',\n\t// Both only mean anything under an event:goal filter or dimension, which is the one\n\t// shape they are requested in: \"events\" on goal rows is Plausible's Total Conversions.\n\tconversions: 'events',\n\trevenue: 'total_revenue',\n}\n\n/** Metrics Plausible answers only for a goal-restricted read. */\nconst GOAL_METRICS: ReadonlySet<MetricKey> = new Set(['conversions', 'revenue'])\n\nconst DIMENSION_MAP: Partial<Record<DimensionKey, string>> = {\n\tpage: 'event:page',\n\tsource: 'visit:source',\n\tchannel: 'visit:channel',\n\treferrer: 'visit:referrer',\n\tdevice: 'visit:device',\n\tbrowser: 'visit:browser',\n\tos: 'visit:os',\n\tcountry: 'visit:country',\n\tregion: 'visit:region',\n\tcity: 'visit:city',\n\tutmSource: 'visit:utm_source',\n\tutmMedium: 'visit:utm_medium',\n\tutmCampaign: 'visit:utm_campaign',\n\tgoal: 'event:goal',\n}\n\n/** `matches` is an re2 full match, so a pattern must cover the whole value (`/docs/.*`, not `^/docs`). */\nconst OPERATOR_MAP: Record<FilterOperator, string> = {\n\teq: 'is',\n\tcontains: 'contains',\n\tmatches: 'matches',\n}\n\nconst plausibleMetrics: 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'events',\n\t'scrollDepth',\n\t'conversions',\n\t'revenue',\n])\n// A site without revenue goals has no total_revenue at all, so the metric is opt-in.\nconst plausibleMetricsNoRevenue: ReadonlySet<MetricKey> = new Set(\n\t[...plausibleMetrics].filter((m) => m !== 'revenue')\n)\nconst plausibleDimensions = mappedKeys(DIMENSION_KEYS, DIMENSION_MAP)\nconst withoutGoal: readonly DimensionKey[] = [...plausibleDimensions].filter(\n\t(dimension) => dimension !== 'goal'\n)\n/**\n * The Stats API refuses bounce rate and duration under event dimensions but event:page, and scroll\n * depth without event:page. Its `time_on_page` is per visit, not per pageview, so none is offered.\n */\nconst plausibleReach: Partial<Record<MetricKey, MetricReach>> = {\n\tbounceRate: { dimensions: withoutGoal },\n\tvisitDuration: { dimensions: withoutGoal },\n\tscrollDepth: { dimensions: withoutGoal, requires: 'page' },\n}\nconst plausibleFilters = everyOperatorOn(plausibleDimensions)\n\n/** One Stats API v2 filter: `[operator, dimension, values]`. */\ntype PlausibleClause = [operator: string, dimension: string, values: string[]]\n\n/** The parts of a v2 query a read adds to the site, the window, the metrics and the filters. */\ninterface QueryShape {\n\tdimensions?: string[]\n}\n\n/** `total_revenue` is an object, and null when the rows mix currencies. Every other metric is a number. */\ntype PlausibleMetricValue = number | { value: number | null } | null\n\ninterface PlausibleResult {\n\tmetrics: PlausibleMetricValue[]\n\tdimensions: string[]\n}\n\ninterface PlausibleResponse {\n\tresults: PlausibleResult[]\n}\n\nconst revenueAmount = (raw: PlausibleMetricValue | undefined): number | undefined =>\n\ttypeof raw === 'object' && raw !== null && typeof raw.value === 'number' ? raw.value : undefined\n\n// visit_duration is reported in seconds; the contract's visitDuration is milliseconds.\nconst toContractValue = (metric: MetricKey, raw: number): number =>\n\tmetric === 'visitDuration' ? Math.round(raw * 1000) : raw\n\n/** One result row's contract metrics, each read back by Plausible name from the request's `names`. */\nconst readRow = (metrics: MetricKey[], names: string[], row: PlausibleResult): MetricValues => {\n\tconst out: MetricValues = {}\n\tfor (const metric of metrics) {\n\t\tconst name = METRIC_MAP[metric]\n\t\tconst raw = name === undefined ? undefined : row.metrics[names.indexOf(name)]\n\t\tif (metric === 'revenue') {\n\t\t\tconst amount = revenueAmount(raw)\n\t\t\tif (amount !== undefined) {\n\t\t\t\tout.revenue = amount\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\t// Plausible answers an average it has no samples for with null, which stays no\n\t\t// data here rather than becoming a 0 the reports would read as a real value.\n\t\tconst value = vendorReading(metric, raw)\n\t\tout[metric] = value === null ? null : toContractValue(metric, value)\n\t}\n\treturn out\n}\n\n/** A response's rows keyed by their dimension values; undefined when the request was never sent. */\nconst keyedRows = (\n\tresponse: PlausibleResponse | undefined,\n\tmetrics: MetricKey[],\n\tnames: string[]\n): GoalKeyedRow[] | undefined =>\n\tresponse?.results.map((row) => ({ keys: row.dimensions, metrics: readRow(metrics, names, row) }))\n\n/**\n * The Plausible adapter. A goal's slug must equal its display name in the site's goal list for its\n * conversions to read; `revenue` needs `revenueCurrency`.\n */\nexport function plausible(config: PlausibleConfig): AnalyticsAdapter {\n\tconst host = withoutTrailingSlash(config.host ?? PLAUSIBLE_CLOUD)\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 730\n\tconst revenueCurrency = currencyOption('plausible({ revenueCurrency })', config.revenueCurrency)\n\tconst revenueGoals = revenueCurrency !== undefined\n\t// Dropped rather than escaped, like GA4's measurement id: it lands in the page's script address.\n\tconst scriptId = isScriptId(config.scriptId) ? config.scriptId : undefined\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\trealtime: false,\n\t\tminGranularity: 'day',\n\t\tmaxLookbackDays,\n\t\tmetrics: revenueGoals ? plausibleMetrics : plausibleMetricsNoRevenue,\n\t\tdimensions: plausibleDimensions,\n\t\tmetricReach: plausibleReach,\n\t\tfilters: plausibleFilters,\n\t\tsemantics: { visitors: 'distinct', sessions: 'provider' },\n\t\trateLimit: { requestsPerHour: 600 },\n\t\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n\t\tupstreamAware: true,\n\t}\n\treturn {\n\t\tid: 'plausible',\n\t\t...adapterLabel(config.label, 'Plausible', 'plausible({ label })'),\n\t\tcapabilities,\n\t\t...(config.domain || scriptId ? { capture: buildCapture(config, scriptId) } : {}),\n\t\tisConfigured: () => Boolean(config.siteId && config.apiKey),\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = readTime(ctx)\n\t\t\tconst dims = (q.dimensions ?? []).filter((d) => DIMENSION_MAP[d])\n\t\t\tconst goalBreakdown = dims.includes('goal')\n\t\t\tconst hint = goalHint(q)\n\t\t\tconst empty = goalBreakdown\n\t\t\t\t? emptyGoalBreakdown({ provider: 'plausible', fetchedAt, hint })\n\t\t\t\t: null\n\t\t\tif (empty) {\n\t\t\t\treturn empty\n\t\t\t}\n\t\t\tconst { siteMetrics, goalMetrics, unresolved } = splitGoalMetrics({\n\t\t\t\twanted: readableMetrics(capabilities, q, dims),\n\t\t\t\tgoalOnly: GOAL_METRICS,\n\t\t\t\tgoalBreakdown,\n\t\t\t\thint,\n\t\t\t})\n\t\t\tconst siteNames = providerMetricKeys(siteMetrics, METRIC_MAP)\n\t\t\tconst goalNames = providerMetricKeys(goalMetrics, METRIC_MAP)\n\n\t\t\tconst filters: PlausibleClause[] = []\n\t\t\tif (q.path) {\n\t\t\t\tfilters.push(['is', 'event:page', [q.path]])\n\t\t\t}\n\t\t\tif (q.hostname) {\n\t\t\t\tfilters.push(['is', 'event:hostname', [q.hostname]])\n\t\t\t}\n\t\t\tfor (const { filter, field } of declaredFilters(capabilities, q.filters, DIMENSION_MAP)) {\n\t\t\t\tfilters.push([OPERATOR_MAP[filter.operator], field, [filter.value]])\n\t\t\t}\n\t\t\tconst slugs = hintSlugs(hint)\n\t\t\tconst goalFilters: PlausibleClause[] = slugs\n\t\t\t\t? [...filters, ['is', 'event:goal', slugs]]\n\t\t\t\t: filters\n\t\t\tconst siteFilters = goalBreakdown ? goalFilters : filters\n\t\t\t// Set when the provider rejects a goal request the site request survived, so the\n\t\t\t// rows keep their site metrics and lose only their goal numbers.\n\t\t\tlet goalsFailed = false\n\t\t\tconst meta = (): AnalyticsResult['meta'] => ({\n\t\t\t\tprovider: 'plausible',\n\t\t\t\tfetchedAt,\n\t\t\t\t...(revenueCurrency ? { currency: revenueCurrency } : {}),\n\t\t\t\t...(unresolved || goalsFailed ? { goalsUnresolved: true as const } : {}),\n\t\t\t})\n\n\t\t\tconst dateRange = calendarDays(q)\n\t\t\tconst postQuery = (\n\t\t\t\tnames: string[],\n\t\t\t\tclauses: PlausibleClause[],\n\t\t\t\tshape: QueryShape\n\t\t\t): Promise<PlausibleResponse> =>\n\t\t\t\tupstreamJson<PlausibleResponse>(ctx, `${host}/api/v2/query`, {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders: { authorization: `Bearer ${config.apiKey}` },\n\t\t\t\t\tbody: {\n\t\t\t\t\t\tsite_id: config.siteId,\n\t\t\t\t\t\tmetrics: names,\n\t\t\t\t\t\tdate_range: dateRange,\n\t\t\t\t\t\t...(clauses.length ? { filters: clauses } : {}),\n\t\t\t\t\t\t...shape,\n\t\t\t\t\t},\n\t\t\t\t\tprovider: 'plausible',\n\t\t\t\t\tfetch: config.fetch,\n\t\t\t\t})\n\n\t\t\t/**\n\t\t\t * One request shape read twice, plainly and goal-filtered, unioned per row. A row the\n\t\t\t * goal read has no counterpart for carries no conversions: no goal was completed there.\n\t\t\t */\n\t\t\tconst readPair = async (shape: QueryShape): Promise<GoalKeyedRow[]> => {\n\t\t\t\tconst pair = await readGoalPair({\n\t\t\t\t\tsite: siteNames.length ? () => postQuery(siteNames, siteFilters, shape) : undefined,\n\t\t\t\t\tgoals: goalNames.length ? () => postQuery(goalNames, goalFilters, shape) : undefined,\n\t\t\t\t})\n\t\t\t\tif (pair.failed) {\n\t\t\t\t\tgoalsFailed = true\n\t\t\t\t}\n\t\t\t\treturn mergeGoalRows(\n\t\t\t\t\tkeyedRows(pair.site, siteMetrics, siteNames),\n\t\t\t\t\tkeyedRows(pair.goals, goalMetrics, goalNames)\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tif (q.granularity === 'day' && !dims.length) {\n\t\t\t\tconst [series, totalRows] = await Promise.all([\n\t\t\t\t\treadPair({ dimensions: ['time:day'] }),\n\t\t\t\t\treadPair({}),\n\t\t\t\t])\n\t\t\t\treturn {\n\t\t\t\t\trows: datedRows(series, dayIso),\n\t\t\t\t\ttotals: totalRows[0]?.metrics ?? {},\n\t\t\t\t\tmeta: meta(),\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!dims.length) {\n\t\t\t\tconst totals = (await readPair({}))[0]?.metrics ?? {}\n\t\t\t\treturn { rows: [{ metrics: totals }], totals, meta: meta() }\n\t\t\t}\n\n\t\t\tconst merged = await readPair({ dimensions: dims.flatMap((d) => DIMENSION_MAP[d] ?? []) })\n\t\t\tconst rows: AnalyticsRow[] = merged.map((row) => {\n\t\t\t\tconst dimensions: Partial<Record<DimensionKey, string>> = {}\n\t\t\t\tfor (const [i, d] of dims.entries()) {\n\t\t\t\t\tdimensions[d] = row.keys[i] ?? ''\n\t\t\t\t}\n\t\t\t\treturn { dimensions, metrics: row.metrics }\n\t\t\t})\n\t\t\treturn { rows, totals: undefined, meta: meta() }\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;AA6EA,MAAM,kBAAkB;;;;;AAMxB,MAAM,iBACL;AAED,SAAS,aAAa,QAAyB,UAA8C;CAC5F,MAAM,OAAO,qBAAqB,OAAO,QAAQ,eAAe;CAChE,MAAM,WAAW,SAAiB;EACjC,IAAI,OAAO,QACV,OAAO,CACN;GACC,KAAK,GAAG,KAAK;GACb,OAAO;GACP,OAAO;IAAE,eAAe,OAAO;IAAQ,YAAY,GAAG,KAAK;GAAY;EACxE,CACD;EAED,IAAI,UACH,OAAO,CACN;GAAE,KAAK,GAAG,KAAK,SAAS,mBAAmB,QAAQ,EAAE;GAAM,OAAO;EAAK,GACvE,EACC,QAAQ,GAAG,eAAe,2BAA2B,UAAU,GAAG,KAAK,WAAW,EAAE,IACrF,CACD;EAED,OAAO,CAAC;CACT;CACA,OAAO;EACN,OAAO;GACN,QAAQ,CACP;IAAE,QAAQ;IAAgB,UAAU,GAAG,KAAK;IAAe,MAAM;GAAS,GAC1E;IAAE,QAAQ;IAAc,UAAU,GAAG,KAAK;IAAa,MAAM;GAAO,CACrE;GACA,GAAI,OAAO,QAAQ,EAAE,OAAO,OAAO,MAAM,IAAI,CAAC;EAC/C;EACA,UAAU,EAAE,YAAY,EAAE,SAAS,QAAQ,IAAI,EAAE;EACjD,QAAQ,EAAE,MAAM,YAAY;CAC7B;AACD;AAEA,MAAM,aAAiD;CACtD,WAAW;CACX,UAAU;CACV,QAAQ;CACR,UAAU;CACV,YAAY;CACZ,eAAe;CACf,QAAQ;CACR,aAAa;CAGb,aAAa;CACb,SAAS;AACV;;AAGA,MAAM,eAAuC,IAAI,IAAI,CAAC,eAAe,SAAS,CAAC;AAE/E,MAAM,gBAAuD;CAC5D,MAAM;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KAC/B,MAAM,UAAU,eAAe,UAAU,WAAW,aAAa,KAAK,IAAI,KAAA;KAC1E,OAAO,UAAU,eAAe,UAAU,WAAW,aAAa,KAAK,IAAI,KAAA;IAC5E,CAAC;IACD,IAAI,KAAK,QACR,cAAc;IAEf,OAAO,cACN,UAAU,KAAK,MAAM,aAAa,SAAS,GAC3C,UAAU,KAAK,OAAO,aAAa,SAAS,CAC7C;GACD;GAEA,IAAI,EAAE,gBAAgB,SAAS,CAAC,KAAK,QAAQ;IAC5C,MAAM,CAAC,QAAQ,aAAa,MAAM,QAAQ,IAAI,CAC7C,SAAS,EAAE,YAAY,CAAC,UAAU,EAAE,CAAC,GACrC,SAAS,CAAC,CAAC,CACZ,CAAC;IACD,OAAO;KACN,MAAM,UAAU,QAAQ,MAAM;KAC9B,QAAQ,UAAU,IAAI,WAAW,CAAC;KAClC,MAAM,KAAK;IACZ;GACD;GAEA,IAAI,CAAC,KAAK,QAAQ;IACjB,MAAM,UAAU,MAAM,SAAS,CAAC,CAAC,GAAG,IAAI,WAAW,CAAC;IACpD,OAAO;KAAE,MAAM,CAAC,EAAE,SAAS,OAAO,CAAC;KAAG;KAAQ,MAAM,KAAK;IAAE;GAC5D;GAUA,OAAO;IAAE,OAPoB,MADR,SAAS,EAAE,YAAY,KAAK,SAAS,MAAM,cAAc,MAAM,CAAC,CAAC,EAAE,CAAC,GACrD,KAAK,QAAQ;KAChD,MAAM,aAAoD,CAAC;KAC3D,KAAK,MAAM,CAAC,GAAG,MAAM,KAAK,QAAQ,GACjC,WAAW,KAAK,IAAI,KAAK,MAAM;KAEhC,OAAO;MAAE;MAAY,SAAS,IAAI;KAAQ;IAC3C,CACY;IAAG,QAAQ,KAAA;IAAW,MAAM,KAAK;GAAE;EAChD;CACD;AACD"}
|
|
1
|
+
{"version":3,"file":"plausible.js","names":[],"sources":["../../../src/adapters/plausible/plausible.ts"],"sourcesContent":["import { jsLiteral } from '../../capture/jsLiteral'\nimport {\n\tadapterWithoutConsent,\n\tcookielessCapture,\n\tWITHOUT_CONSENT_LEVELS,\n} from '../../capture/withoutConsent'\nimport type { CaptureSupport } from '../../core/capture'\nimport {\n\ttype AdapterContext,\n\ttype AnalyticsAdapter,\n\ttype AnalyticsCapabilities,\n\ttype AnalyticsQuery,\n\ttype AnalyticsResult,\n\ttype AnalyticsRow,\n\tDIMENSION_KEYS,\n\ttype DimensionKey,\n\ttype FilterOperator,\n\ttype MetricKey,\n\ttype MetricReach,\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 { currencyOption } from '../../goals/currency'\nimport type { WithoutConsentLevel } from '../../tracker/config'\nimport {\n\temptyGoalBreakdown,\n\ttype GoalKeyedRow,\n\tgoalHint,\n\thintSlugs,\n\tmergeGoalRows,\n\treadGoalPair,\n\tsplitGoalMetrics,\n} from '../goalRead'\nimport { withoutTrailingSlash } from '../http/baseUrl'\nimport {\n\tcalendarDays,\n\tdeclaredFilters,\n\teveryOperatorOn,\n\tmappedKeys,\n\tproviderMetricKeys,\n\treadableMetrics,\n} from '../mapping'\nimport { readTime } from '../readTime'\nimport { datedRows, dayIso } from '../series'\nimport { upstreamJson } from '../upstream'\nimport { isScriptId } from './scriptId'\n\nexport interface PlausibleConfig {\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 `'Plausible'`.\n\t */\n\tlabel?: AdapterLabelOption\n\tsiteId: string\n\tapiKey: string\n\t/**\n\t * Address of a self-hosted Community Edition, with the base path when it runs under one.\n\t * Defaults to Plausible 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/**\n\t * Site domain for the legacy script tag (`data-domain`). Takes priority over `scriptId`.\n\t * The adapter declares `capture` only when one of the two is set.\n\t */\n\tdomain?: string\n\t/**\n\t * Per-site tracker id (`pa-<id>.js`) for the newer per-site script model: letters, digits, `_`\n\t * and `-`. Any other value is dropped, and capture then needs `domain`.\n\t */\n\tscriptId?: string\n\t/**\n\t * The ISO 4217 currency of the site's revenue goals. Declaring it turns on `revenue`: Plausible\n\t * errors the whole request for `total_revenue` on a site without a revenue goal.\n\t */\n\trevenueCurrency?: string\n\t/** The fetch reads and the capture proxy reach Plausible with. Unset, the global fetch. */\n\tfetch?: FetchLike\n\t/**\n\t * What this source's held slot does without consent, over `capture.withoutConsent`. Plausible\n\t * stores nothing on the device, so `'cookieless'` loads the script as it is; `'off'` holds it.\n\t */\n\twithoutConsent?: WithoutConsentLevel\n}\n\nconst PLAUSIBLE_CLOUD = 'https://plausible.io'\n\n/**\n * Plausible's official per-site stub, safe beside the async loader in either order. `init` is\n * guarded with `||` because the loader may win the race, and overwriting it would lose the endpoint.\n */\nconst PLAUSIBLE_STUB =\n\t'window.plausible=window.plausible||function(){(window.plausible.q=window.plausible.q||[]).push(arguments)},window.plausible.init=window.plausible.init||function(e){window.plausible.o=e||{}};'\n\nfunction buildCapture(\n\tconfig: PlausibleConfig,\n\tscriptId: string | undefined,\n\twithoutConsent: WithoutConsentLevel | undefined\n): CaptureSupport {\n\tconst base = withoutTrailingSlash(config.host ?? PLAUSIBLE_CLOUD)\n\tconst scripts = (path: string) => {\n\t\tif (config.domain) {\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\tsrc: `${path}/js/script.js`,\n\t\t\t\t\tdefer: true,\n\t\t\t\t\tattrs: { 'data-domain': config.domain, 'data-api': `${path}/api/event` },\n\t\t\t\t},\n\t\t\t]\n\t\t}\n\t\tif (scriptId) {\n\t\t\treturn [\n\t\t\t\t{ src: `${path}/js/pa-${encodeURIComponent(scriptId)}.js`, async: true },\n\t\t\t\t{\n\t\t\t\t\tinline: `${PLAUSIBLE_STUB}plausible.init({endpoint:${jsLiteral(`${path}/api/event`)}})`,\n\t\t\t\t},\n\t\t\t]\n\t\t}\n\t\treturn []\n\t}\n\treturn {\n\t\tproxy: {\n\t\t\troutes: [\n\t\t\t\t{ source: '/js/:script*', upstream: `${base}/js/:script*`, kind: 'script' },\n\t\t\t\t{ source: '/api/event', upstream: `${base}/api/event`, kind: 'data' },\n\t\t\t],\n\t\t\t...(config.fetch ? { fetch: config.fetch } : {}),\n\t\t},\n\t\tsnippet: ({ path }) => ({ scripts: scripts(path) }),\n\t\tclient: { kind: 'plausible' },\n\t\t...cookielessCapture({ kind: 'inherent' }, withoutConsent),\n\t}\n}\n\nconst METRIC_MAP: Partial<Record<MetricKey, string>> = {\n\tpageviews: 'pageviews',\n\tvisitors: 'visitors',\n\tvisits: 'visits',\n\tsessions: 'visits',\n\tbounceRate: 'bounce_rate',\n\tvisitDuration: 'visit_duration',\n\tevents: 'events',\n\tscrollDepth: 'scroll_depth',\n\t// Both only mean anything under an event:goal filter or dimension, which is the one\n\t// shape they are requested in: \"events\" on goal rows is Plausible's Total Conversions.\n\tconversions: 'events',\n\trevenue: 'total_revenue',\n}\n\n/** Metrics Plausible answers only for a goal-restricted read. */\nconst GOAL_METRICS: ReadonlySet<MetricKey> = new Set(['conversions', 'revenue'])\n\nconst DIMENSION_MAP: Partial<Record<DimensionKey, string>> = {\n\tpage: 'event:page',\n\tsource: 'visit:source',\n\tchannel: 'visit:channel',\n\treferrer: 'visit:referrer',\n\tdevice: 'visit:device',\n\tbrowser: 'visit:browser',\n\tos: 'visit:os',\n\tcountry: 'visit:country',\n\tregion: 'visit:region',\n\tcity: 'visit:city',\n\tutmSource: 'visit:utm_source',\n\tutmMedium: 'visit:utm_medium',\n\tutmCampaign: 'visit:utm_campaign',\n\tgoal: 'event:goal',\n}\n\n/** `matches` is an re2 full match, so a pattern must cover the whole value (`/docs/.*`, not `^/docs`). */\nconst OPERATOR_MAP: Record<FilterOperator, string> = {\n\teq: 'is',\n\tcontains: 'contains',\n\tmatches: 'matches',\n}\n\nconst plausibleMetrics: 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'events',\n\t'scrollDepth',\n\t'conversions',\n\t'revenue',\n])\n// A site without revenue goals has no total_revenue at all, so the metric is opt-in.\nconst plausibleMetricsNoRevenue: ReadonlySet<MetricKey> = new Set(\n\t[...plausibleMetrics].filter((m) => m !== 'revenue')\n)\nconst plausibleDimensions = mappedKeys(DIMENSION_KEYS, DIMENSION_MAP)\nconst withoutGoal: readonly DimensionKey[] = [...plausibleDimensions].filter(\n\t(dimension) => dimension !== 'goal'\n)\n/**\n * The Stats API refuses bounce rate and duration under event dimensions but event:page, and scroll\n * depth without event:page. Its `time_on_page` is per visit, not per pageview, so none is offered.\n */\nconst plausibleReach: Partial<Record<MetricKey, MetricReach>> = {\n\tbounceRate: { dimensions: withoutGoal },\n\tvisitDuration: { dimensions: withoutGoal },\n\tscrollDepth: { dimensions: withoutGoal, requires: 'page' },\n}\nconst plausibleFilters = everyOperatorOn(plausibleDimensions)\n\n/** One Stats API v2 filter: `[operator, dimension, values]`. */\ntype PlausibleClause = [operator: string, dimension: string, values: string[]]\n\n/** The parts of a v2 query a read adds to the site, the window, the metrics and the filters. */\ninterface QueryShape {\n\tdimensions?: string[]\n}\n\n/** `total_revenue` is an object, and null when the rows mix currencies. Every other metric is a number. */\ntype PlausibleMetricValue = number | { value: number | null } | null\n\ninterface PlausibleResult {\n\tmetrics: PlausibleMetricValue[]\n\tdimensions: string[]\n}\n\ninterface PlausibleResponse {\n\tresults: PlausibleResult[]\n}\n\nconst revenueAmount = (raw: PlausibleMetricValue | undefined): number | undefined =>\n\ttypeof raw === 'object' && raw !== null && typeof raw.value === 'number' ? raw.value : undefined\n\n// visit_duration is reported in seconds; the contract's visitDuration is milliseconds.\nconst toContractValue = (metric: MetricKey, raw: number): number =>\n\tmetric === 'visitDuration' ? Math.round(raw * 1000) : raw\n\n/** One result row's contract metrics, each read back by Plausible name from the request's `names`. */\nconst readRow = (metrics: MetricKey[], names: string[], row: PlausibleResult): MetricValues => {\n\tconst out: MetricValues = {}\n\tfor (const metric of metrics) {\n\t\tconst name = METRIC_MAP[metric]\n\t\tconst raw = name === undefined ? undefined : row.metrics[names.indexOf(name)]\n\t\tif (metric === 'revenue') {\n\t\t\tconst amount = revenueAmount(raw)\n\t\t\tif (amount !== undefined) {\n\t\t\t\tout.revenue = amount\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\t// Plausible answers an average it has no samples for with null, which stays no\n\t\t// data here rather than becoming a 0 the reports would read as a real value.\n\t\tconst value = vendorReading(metric, raw)\n\t\tout[metric] = value === null ? null : toContractValue(metric, value)\n\t}\n\treturn out\n}\n\n/** A response's rows keyed by their dimension values; undefined when the request was never sent. */\nconst keyedRows = (\n\tresponse: PlausibleResponse | undefined,\n\tmetrics: MetricKey[],\n\tnames: string[]\n): GoalKeyedRow[] | undefined =>\n\tresponse?.results.map((row) => ({ keys: row.dimensions, metrics: readRow(metrics, names, row) }))\n\n/**\n * The Plausible adapter. A goal's slug must equal its display name in the site's goal list for its\n * conversions to read; `revenue` needs `revenueCurrency`.\n */\nexport function plausible(config: PlausibleConfig): AnalyticsAdapter {\n\tconst host = withoutTrailingSlash(config.host ?? PLAUSIBLE_CLOUD)\n\tconst maxLookbackDays = config.maxLookbackDays !== undefined ? config.maxLookbackDays : 730\n\tconst revenueCurrency = currencyOption('plausible({ revenueCurrency })', config.revenueCurrency)\n\tconst revenueGoals = revenueCurrency !== undefined\n\t// Dropped rather than escaped, like GA4's measurement id: it lands in the page's script address.\n\tconst scriptId = isScriptId(config.scriptId) ? config.scriptId : undefined\n\tconst withoutConsent = adapterWithoutConsent(\n\t\tconfig.withoutConsent,\n\t\t'plausible({ withoutConsent })',\n\t\tWITHOUT_CONSENT_LEVELS\n\t)\n\n\tconst capabilities: AnalyticsCapabilities = {\n\t\trealtime: false,\n\t\tminGranularity: 'day',\n\t\tmaxLookbackDays,\n\t\tmetrics: revenueGoals ? plausibleMetrics : plausibleMetricsNoRevenue,\n\t\tdimensions: plausibleDimensions,\n\t\tmetricReach: plausibleReach,\n\t\tfilters: plausibleFilters,\n\t\tsemantics: { visitors: 'distinct', sessions: 'provider' },\n\t\trateLimit: { requestsPerHour: 600 },\n\t\trecommendedTtl: { realtime: 300, aggregate: 3600 },\n\t\tupstreamAware: true,\n\t}\n\treturn {\n\t\tid: 'plausible',\n\t\t...adapterLabel(config.label, 'Plausible', 'plausible({ label })'),\n\t\tcapabilities,\n\t\t...(config.domain || scriptId\n\t\t\t? { capture: buildCapture(config, scriptId, withoutConsent) }\n\t\t\t: {}),\n\t\tisConfigured: () => Boolean(config.siteId && config.apiKey),\n\t\tasync query(q: AnalyticsQuery, ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tconst fetchedAt = readTime(ctx)\n\t\t\tconst dims = (q.dimensions ?? []).filter((d) => DIMENSION_MAP[d])\n\t\t\tconst goalBreakdown = dims.includes('goal')\n\t\t\tconst hint = goalHint(q)\n\t\t\tconst empty = goalBreakdown\n\t\t\t\t? emptyGoalBreakdown({ provider: 'plausible', fetchedAt, hint })\n\t\t\t\t: null\n\t\t\tif (empty) {\n\t\t\t\treturn empty\n\t\t\t}\n\t\t\tconst { siteMetrics, goalMetrics, unresolved } = splitGoalMetrics({\n\t\t\t\twanted: readableMetrics(capabilities, q, dims),\n\t\t\t\tgoalOnly: GOAL_METRICS,\n\t\t\t\tgoalBreakdown,\n\t\t\t\thint,\n\t\t\t})\n\t\t\tconst siteNames = providerMetricKeys(siteMetrics, METRIC_MAP)\n\t\t\tconst goalNames = providerMetricKeys(goalMetrics, METRIC_MAP)\n\n\t\t\tconst filters: PlausibleClause[] = []\n\t\t\tif (q.path) {\n\t\t\t\tfilters.push(['is', 'event:page', [q.path]])\n\t\t\t}\n\t\t\tif (q.hostname) {\n\t\t\t\tfilters.push(['is', 'event:hostname', [q.hostname]])\n\t\t\t}\n\t\t\tfor (const { filter, field } of declaredFilters(capabilities, q.filters, DIMENSION_MAP)) {\n\t\t\t\tfilters.push([OPERATOR_MAP[filter.operator], field, [filter.value]])\n\t\t\t}\n\t\t\tconst slugs = hintSlugs(hint)\n\t\t\tconst goalFilters: PlausibleClause[] = slugs\n\t\t\t\t? [...filters, ['is', 'event:goal', slugs]]\n\t\t\t\t: filters\n\t\t\tconst siteFilters = goalBreakdown ? goalFilters : filters\n\t\t\t// Set when the provider rejects a goal request the site request survived, so the\n\t\t\t// rows keep their site metrics and lose only their goal numbers.\n\t\t\tlet goalsFailed = false\n\t\t\tconst meta = (): AnalyticsResult['meta'] => ({\n\t\t\t\tprovider: 'plausible',\n\t\t\t\tfetchedAt,\n\t\t\t\t...(revenueCurrency ? { currency: revenueCurrency } : {}),\n\t\t\t\t...(unresolved || goalsFailed ? { goalsUnresolved: true as const } : {}),\n\t\t\t})\n\n\t\t\tconst dateRange = calendarDays(q)\n\t\t\tconst postQuery = (\n\t\t\t\tnames: string[],\n\t\t\t\tclauses: PlausibleClause[],\n\t\t\t\tshape: QueryShape\n\t\t\t): Promise<PlausibleResponse> =>\n\t\t\t\tupstreamJson<PlausibleResponse>(ctx, `${host}/api/v2/query`, {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders: { authorization: `Bearer ${config.apiKey}` },\n\t\t\t\t\tbody: {\n\t\t\t\t\t\tsite_id: config.siteId,\n\t\t\t\t\t\tmetrics: names,\n\t\t\t\t\t\tdate_range: dateRange,\n\t\t\t\t\t\t...(clauses.length ? { filters: clauses } : {}),\n\t\t\t\t\t\t...shape,\n\t\t\t\t\t},\n\t\t\t\t\tprovider: 'plausible',\n\t\t\t\t\tfetch: config.fetch,\n\t\t\t\t})\n\n\t\t\t/**\n\t\t\t * One request shape read twice, plainly and goal-filtered, unioned per row. A row the\n\t\t\t * goal read has no counterpart for carries no conversions: no goal was completed there.\n\t\t\t */\n\t\t\tconst readPair = async (shape: QueryShape): Promise<GoalKeyedRow[]> => {\n\t\t\t\tconst pair = await readGoalPair({\n\t\t\t\t\tsite: siteNames.length ? () => postQuery(siteNames, siteFilters, shape) : undefined,\n\t\t\t\t\tgoals: goalNames.length ? () => postQuery(goalNames, goalFilters, shape) : undefined,\n\t\t\t\t})\n\t\t\t\tif (pair.failed) {\n\t\t\t\t\tgoalsFailed = true\n\t\t\t\t}\n\t\t\t\treturn mergeGoalRows(\n\t\t\t\t\tkeyedRows(pair.site, siteMetrics, siteNames),\n\t\t\t\t\tkeyedRows(pair.goals, goalMetrics, goalNames)\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tif (q.granularity === 'day' && !dims.length) {\n\t\t\t\tconst [series, totalRows] = await Promise.all([\n\t\t\t\t\treadPair({ dimensions: ['time:day'] }),\n\t\t\t\t\treadPair({}),\n\t\t\t\t])\n\t\t\t\treturn {\n\t\t\t\t\trows: datedRows(series, dayIso),\n\t\t\t\t\ttotals: totalRows[0]?.metrics ?? {},\n\t\t\t\t\tmeta: meta(),\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!dims.length) {\n\t\t\t\tconst totals = (await readPair({}))[0]?.metrics ?? {}\n\t\t\t\treturn { rows: [{ metrics: totals }], totals, meta: meta() }\n\t\t\t}\n\n\t\t\tconst merged = await readPair({ dimensions: dims.flatMap((d) => DIMENSION_MAP[d] ?? []) })\n\t\t\tconst rows: AnalyticsRow[] = merged.map((row) => {\n\t\t\t\tconst dimensions: Partial<Record<DimensionKey, string>> = {}\n\t\t\t\tfor (const [i, d] of dims.entries()) {\n\t\t\t\t\tdimensions[d] = row.keys[i] ?? ''\n\t\t\t\t}\n\t\t\t\treturn { dimensions, metrics: row.metrics }\n\t\t\t})\n\t\t\treturn { rows, totals: undefined, meta: meta() }\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;AAwFA,MAAM,kBAAkB;;;;;AAMxB,MAAM,iBACL;AAED,SAAS,aACR,QACA,UACA,gBACiB;CACjB,MAAM,OAAO,qBAAqB,OAAO,QAAQ,eAAe;CAChE,MAAM,WAAW,SAAiB;EACjC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aAAa,SAAS,CAC7C;GACD;GAEA,IAAI,EAAE,gBAAgB,SAAS,CAAC,KAAK,QAAQ;IAC5C,MAAM,CAAC,QAAQ,aAAa,MAAM,QAAQ,IAAI,CAC7C,SAAS,EAAE,YAAY,CAAC,UAAU,EAAE,CAAC,GACrC,SAAS,CAAC,CAAC,CACZ,CAAC;IACD,OAAO;KACN,MAAM,UAAU,QAAQ,MAAM;KAC9B,QAAQ,UAAU,IAAI,WAAW,CAAC;KAClC,MAAM,KAAK;IACZ;GACD;GAEA,IAAI,CAAC,KAAK,QAAQ;IACjB,MAAM,UAAU,MAAM,SAAS,CAAC,CAAC,GAAG,IAAI,WAAW,CAAC;IACpD,OAAO;KAAE,MAAM,CAAC,EAAE,SAAS,OAAO,CAAC;KAAG;KAAQ,MAAM,KAAK;IAAE;GAC5D;GAUA,OAAO;IAAE,OAPoB,MADR,SAAS,EAAE,YAAY,KAAK,SAAS,MAAM,cAAc,MAAM,CAAC,CAAC,EAAE,CAAC,GACrD,KAAK,QAAQ;KAChD,MAAM,aAAoD,CAAC;KAC3D,KAAK,MAAM,CAAC,GAAG,MAAM,KAAK,QAAQ,GACjC,WAAW,KAAK,IAAI,KAAK,MAAM;KAEhC,OAAO;MAAE;MAAY,SAAS,IAAI;KAAQ;IAC3C,CACY;IAAG,QAAQ,KAAA;IAAW,MAAM,KAAK;GAAE;EAChD;CACD;AACD"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { WithoutConsentLevel } from "../../tracker/config.js";
|
|
1
2
|
import { FetchLike } from "../../core/fetch.js";
|
|
2
3
|
import { AnalyticsAdapter } from "../../core/contract.js";
|
|
3
4
|
import { AdapterLabelOption } from "../../core/sourceLabel.js";
|
|
@@ -42,6 +43,12 @@ interface PosthogConfig {
|
|
|
42
43
|
projectToken?: string;
|
|
43
44
|
/** The fetch reads and the capture proxy reach PostHog with. Unset, the global fetch. */
|
|
44
45
|
fetch?: FetchLike;
|
|
46
|
+
/**
|
|
47
|
+
* What this source's held slot does without consent, over `capture.withoutConsent`.
|
|
48
|
+
* `'cookieless'` counts with PostHog's cookieless mode until consent, which needs the project's
|
|
49
|
+
* "Cookieless tracking" (Web analytics settings); `'off'` keeps PostHog opted out until then.
|
|
50
|
+
*/
|
|
51
|
+
withoutConsent?: WithoutConsentLevel;
|
|
45
52
|
}
|
|
46
53
|
declare function posthog(config: PosthogConfig): AnalyticsAdapter;
|
|
47
54
|
//#endregion
|